@dsh-teamwork/dsh-teamwork 0.9.0 → 0.10.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.
- package/README.md +5 -2
- package/README.zh-CN.md +1 -1
- package/docs/development.md +72 -2
- package/docs/en/guide.md +43 -2
- package/docs/zh-CN/guide.md +18 -2
- package/lib/audit-archive.js +174 -0
- package/lib/audit-archive.js.map +1 -0
- package/lib/audit-cli.js +91 -0
- package/lib/audit-cli.js.map +1 -0
- package/lib/bridge.js +32 -10
- package/lib/bridge.js.map +1 -1
- package/lib/client.js +37 -15
- package/lib/client.js.map +1 -1
- package/lib/config-sync.js +1 -1
- package/lib/config-sync.js.map +1 -1
- package/lib/index.js +333 -94
- package/lib/index.js.map +1 -1
- package/lib/locale.js +18 -0
- package/lib/locale.js.map +1 -0
- package/lib/login-callback.js +1 -1
- package/lib/login-callback.js.map +1 -1
- package/lib/messages.js +119 -0
- package/lib/messages.js.map +1 -0
- package/lib/panel.js +27 -20
- package/lib/panel.js.map +1 -1
- package/lib/phone-security.js +120 -2
- package/lib/phone-security.js.map +1 -1
- package/lib/pin-lock.js +89 -0
- package/lib/pin-lock.js.map +1 -0
- package/lib/platform-models.js +10 -7
- package/lib/platform-models.js.map +1 -1
- package/lib/plugin-status.js +4 -4
- package/lib/plugin-status.js.map +1 -1
- package/lib/preset-session.js +2 -1
- package/lib/preset-session.js.map +1 -1
- package/lib/relay.js +14 -9
- package/lib/relay.js.map +1 -1
- package/lib/shared-mode.js +151 -0
- package/lib/shared-mode.js.map +1 -0
- package/lib/shared-owner.js +122 -0
- package/lib/shared-owner.js.map +1 -0
- package/lib/shared-roster.js +112 -0
- package/lib/shared-roster.js.map +1 -0
- package/lib/task-session.js +21 -19
- package/lib/task-session.js.map +1 -1
- package/lib/types/audit-archive.d.ts +78 -0
- package/lib/types/audit-archive.d.ts.map +1 -0
- package/lib/types/audit-cli.d.ts +14 -0
- package/lib/types/audit-cli.d.ts.map +1 -0
- package/lib/types/bridge.d.ts +7 -3
- package/lib/types/bridge.d.ts.map +1 -1
- package/lib/types/client.d.ts +21 -4
- package/lib/types/client.d.ts.map +1 -1
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/locale.d.ts +13 -0
- package/lib/types/locale.d.ts.map +1 -0
- package/lib/types/messages.d.ts +67 -0
- package/lib/types/messages.d.ts.map +1 -0
- package/lib/types/panel.d.ts +64 -8
- package/lib/types/panel.d.ts.map +1 -1
- package/lib/types/phone-security.d.ts +37 -0
- package/lib/types/phone-security.d.ts.map +1 -1
- package/lib/types/pin-lock.d.ts +36 -0
- package/lib/types/pin-lock.d.ts.map +1 -0
- package/lib/types/platform-models.d.ts.map +1 -1
- package/lib/types/preset-session.d.ts.map +1 -1
- package/lib/types/relay.d.ts +15 -1
- package/lib/types/relay.d.ts.map +1 -1
- package/lib/types/shared-mode.d.ts +50 -0
- package/lib/types/shared-mode.d.ts.map +1 -0
- package/lib/types/shared-owner.d.ts +42 -0
- package/lib/types/shared-owner.d.ts.map +1 -0
- package/lib/types/shared-roster.d.ts +49 -0
- package/lib/types/shared-roster.d.ts.map +1 -0
- package/lib/types/task-session.d.ts +2 -2
- package/lib/types/task-session.d.ts.map +1 -1
- package/lib/web/client.js +1086 -355
- package/package.json +8 -1
package/lib/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import z from '@deepseek-ai/schemastery';
|
|
|
3
3
|
import { allConfigs, findConfig, ServerChoice, serverAddress, teamOf, TeamOverlay, TeamworkClient } from './client.js';
|
|
4
4
|
import { ConfigSync } from './config-sync.js';
|
|
5
5
|
import { PresetStamps, presetStampPath, sameRevision, toolReport, assertBlank } from './preset-session.js';
|
|
6
|
-
import { modelData, inheritsModel, pinnedPlugin } from './client.js';
|
|
6
|
+
import { modelData, modelLimitProblem, unsizedModel, inheritsModel, pinnedPlugin } from './client.js';
|
|
7
7
|
import { taskProjection, stepProjection, TaskActions, recoveryHint, retryInstruction, outcomeText } from './task-session.js';
|
|
8
8
|
import { pluginState, stateText } from './plugin-status.js';
|
|
9
9
|
import { panelRoutes } from './panel.js';
|
|
@@ -15,6 +15,12 @@ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
|
|
|
15
15
|
import { listenForCode } from './login-callback.js';
|
|
16
16
|
import { offerSchema, pairingSchema, RelayError, RelayLink, relayClientIdPath } from './relay.js';
|
|
17
17
|
import { watchTokenFile } from './token-file.js';
|
|
18
|
+
import { SharedMode, sharedKeyPath } from './shared-mode.js';
|
|
19
|
+
import { SharedRoster, sharedRosterPath } from './shared-roster.js';
|
|
20
|
+
import { OwnerFilter } from './shared-owner.js';
|
|
21
|
+
import { PinStore, pinsPath } from './pin-lock.js';
|
|
22
|
+
import { AuditArchive, auditArchivePath } from './audit-archive.js';
|
|
23
|
+
import { panelLocale, say, setLocale, speaking } from './messages.js';
|
|
18
24
|
export const name = 'dsh-teamwork';
|
|
19
25
|
export const inject = ['agentPresets', 'agents', 'llm', 'sessionProjections'];
|
|
20
26
|
/** The hosted service. A member can pick another server in the panel; the profile's `apiEndpoint` sets the default. */
|
|
@@ -71,7 +77,7 @@ export async function apply(ctx, config) {
|
|
|
71
77
|
const state = !valid ? 'catalog-changed' : !manager ? 'unknown' : pluginState(dependency.version, bundle, entries, restartRequired.has(`${item.data.package}@${dependency.version}`));
|
|
72
78
|
return { id: dependency.pluginConfigId, name: item?.name ?? dependency.pluginConfigId, package: item?.kind === 'plugin' ? item.data.package : undefined,
|
|
73
79
|
version: dependency.version, description: item?.kind === 'plugin' ? item.data.description : '', localVersion: bundle?.version, state,
|
|
74
|
-
text: `${item?.name ?? dependency.pluginConfigId} @${dependency.version}
|
|
80
|
+
text: `${item?.name ?? dependency.pluginConfigId} @${dependency.version} (local ${bundle?.version ?? 'none'}): ${stateText[state]}${state === 'missing' ? `; /teamwork install ${dependency.pluginConfigId}@${dependency.version}` : ''}` };
|
|
75
81
|
});
|
|
76
82
|
};
|
|
77
83
|
const checkPlugins = async (preset) => {
|
|
@@ -80,40 +86,48 @@ export async function apply(ctx, config) {
|
|
|
80
86
|
throw new PhoneSessionError('missing_plugins', missing.map(p => p.text).join('\n'));
|
|
81
87
|
};
|
|
82
88
|
// A stamp that fails to save is retaken on the session's next request; the session itself is unaffected.
|
|
83
|
-
const keep = (write) => { write.catch(error => ctx.logger.warn('
|
|
89
|
+
const keep = (write) => { write.catch(error => ctx.logger.warn('Could not save the team preset version record: %s', error.message)); };
|
|
84
90
|
const stamp = (agent, preset) => keep(stamps.set(String(agent.id), preset));
|
|
85
91
|
const detail = (agent, preset, preview = false) => {
|
|
86
92
|
const snapshot = client.current();
|
|
87
93
|
const team = teamOf(snapshot, preset.id);
|
|
88
94
|
const latest = team?.teamId === preset.teamId ? findConfig(snapshot, preset.id) : undefined;
|
|
89
95
|
const tools = requirements(agent, preset);
|
|
90
|
-
const labels = { available: '
|
|
96
|
+
const labels = { available: 'registered (running it still needs the host’s permission)', conditional: 'conditional, checked when run', missing: 'missing', unknown: 'cannot be checked' };
|
|
91
97
|
const saved = preview ? null : stamps.get(String(agent.id));
|
|
92
|
-
const revision = latest ? latest.version === preset.version ? '
|
|
93
|
-
return [`${preset.name} · v${preset.version}`,
|
|
94
|
-
latest && snapshot && !inheritsModel(latest) && !modelData(snapshot, latest) ? '
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
'
|
|
100
|
-
|
|
101
|
-
'
|
|
98
|
+
const revision = latest ? latest.version === preset.version ? 'Up to date' : `Version v${latest.version} is available; a started session needs a new session to use it` : 'This preset is no longer in the team configuration';
|
|
99
|
+
return [`${preset.name} · v${preset.version}`, `Source: team ${team?.teamName ?? preset.teamId} / preset ${preset.id}`, revision,
|
|
100
|
+
latest && snapshot && !inheritsModel(latest) && !modelData(snapshot, latest) ? 'The linked model is no longer available. Ask an admin to link a team model again.' : '',
|
|
101
|
+
latest && snapshot ? modelLimitProblem(snapshot, latest) ?? '' : '',
|
|
102
|
+
saved && !sameRevision(saved, preset) ? `This session recorded v${saved.version}, which differs from the loaded version; inference is blocked. Start a new session.` : '',
|
|
103
|
+
`Session model: ${agent.model.current()?.provider ?? "none"}/${agent.model.current()?.model ?? "none"}`,
|
|
104
|
+
`Preset model: ${preset.inheritModel ? 'the session’s model' : preset.modelConfigId ?? 'legacy own model'} · through the platform; the server always applies its current model policy`,
|
|
105
|
+
`Description: ${preset.description || 'not set'}`, `Instructions: ${preset.instructions || 'not set'}`, `Deliverable: ${preset.outputDescription || 'not set'}`,
|
|
106
|
+
'Prompt: your local prompt, followed by the team text below', preset.systemPrompt || '(no team text)',
|
|
107
|
+
...tools.map(t => { const declared = (team?.configs ?? []).filter(c => c.kind === 'plugin' && c.data.providesTools?.includes(t.name)); return `${t.required ? 'Required' : 'Optional'} tool ${t.name}: ${labels[t.state]}${declared.length ? '; declared by team plugin ' + declared.map(c => `${c.name} (/teamwork install ${c.id})`).join(', ') : ''}`; }),
|
|
108
|
+
'Install or enable a missing tool in the local plugin manager; a preset never installs a plugin or grants a permission.',
|
|
102
109
|
].filter(Boolean).join('\n');
|
|
103
110
|
};
|
|
111
|
+
/** The reason a team model or preset id cannot run here (see modelLimitProblem), if any. */
|
|
112
|
+
const limitProblem = (id) => { const snapshot = client.current(), item = findConfig(snapshot, id); return snapshot && item ? modelLimitProblem(snapshot, item) : undefined; };
|
|
113
|
+
// Runs inside the host's model-switch compaction check, so a model without its window gets this reason, not that failure.
|
|
104
114
|
ctx.on('agent/request', async ({ agent }, next) => {
|
|
115
|
+
const selection = agent.model.current();
|
|
116
|
+
const limit = selection?.provider === platformProvider ? limitProblem(selection.model) : undefined;
|
|
117
|
+
if (limit)
|
|
118
|
+
throw new Error(limit);
|
|
105
119
|
const preset = activePreset(agent);
|
|
106
120
|
if (preset) {
|
|
107
121
|
if (preset.inheritModel && !agent.model.current())
|
|
108
|
-
throw new Error('
|
|
122
|
+
throw new Error('Choose a working local model first, or ask an admin to link a team model to the assistant.');
|
|
109
123
|
if (preset.pluginDependencies?.length)
|
|
110
124
|
await checkPlugins(preset);
|
|
111
125
|
const saved = stamps.get(String(agent.id));
|
|
112
126
|
if (saved && !sameRevision(saved, preset))
|
|
113
|
-
throw new Error('
|
|
127
|
+
throw new Error('The team preset changed version since this session started. Start a new session.');
|
|
114
128
|
const missing = requirements(agent, preset).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
|
|
115
129
|
if (missing.length)
|
|
116
|
-
throw new Error(
|
|
130
|
+
throw new Error(`Required tools are missing: ${missing.map(t => t.name).join(', ')}. Install or enable them, then try again.`);
|
|
117
131
|
if (!saved)
|
|
118
132
|
stamp(agent, preset);
|
|
119
133
|
}
|
|
@@ -125,32 +139,35 @@ export async function apply(ctx, config) {
|
|
|
125
139
|
const readiness = async (agent, fresh = false) => {
|
|
126
140
|
const selection = agent.model.current();
|
|
127
141
|
if (!selection)
|
|
128
|
-
throw new PhoneSessionError('model_unavailable', '
|
|
142
|
+
throw new PhoneSessionError('model_unavailable', 'No model is selected. Choose a local model, or run /teamwork use <id>.');
|
|
129
143
|
if (selection.provider === platformProvider) {
|
|
130
144
|
if (!client.authenticated())
|
|
131
|
-
throw new PhoneSessionError('not_authenticated', '
|
|
145
|
+
throw new PhoneSessionError('not_authenticated', 'Not signed in to the team model, or the sign-in expired. Run /teamwork login.');
|
|
132
146
|
if (fresh) {
|
|
133
147
|
try {
|
|
134
148
|
await configSync.sync();
|
|
135
149
|
}
|
|
136
150
|
catch {
|
|
137
|
-
throw new PhoneSessionError('unavailable', '
|
|
151
|
+
throw new PhoneSessionError('unavailable', 'Could not verify team access. Check the connection and /teamwork status, and sign in again if needed.');
|
|
138
152
|
}
|
|
139
153
|
}
|
|
140
154
|
const snapshot = client.current(), item = findConfig(snapshot, selection.model);
|
|
141
155
|
if (!snapshot || !item || !modelData(snapshot, item))
|
|
142
|
-
throw new PhoneSessionError('model_unavailable', '
|
|
156
|
+
throw new PhoneSessionError('model_unavailable', 'The team model was removed or its link is broken. Choose an available model; for a changed preset, start a new session.');
|
|
157
|
+
const limit = modelLimitProblem(snapshot, item);
|
|
158
|
+
if (limit)
|
|
159
|
+
throw new PhoneSessionError('model_unavailable', limit);
|
|
143
160
|
}
|
|
144
161
|
const preset = activePreset(agent);
|
|
145
162
|
if (preset) {
|
|
146
163
|
const saved = stamps.get(String(agent.id));
|
|
147
164
|
if (saved && !sameRevision(saved, preset))
|
|
148
|
-
throw new PhoneSessionError('preset_changed', '
|
|
165
|
+
throw new PhoneSessionError('preset_changed', 'The resumed session’s preset version differs. Run /teamwork new <presetId>.');
|
|
149
166
|
if (preset.pluginDependencies?.length)
|
|
150
167
|
await checkPlugins(preset);
|
|
151
168
|
const missing = requirements(agent, preset).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
|
|
152
169
|
if (missing.length)
|
|
153
|
-
throw new PhoneSessionError('missing_tools',
|
|
170
|
+
throw new PhoneSessionError('missing_tools', `Required tools are missing: ${missing.map(t => t.name).join(', ')}; run /teamwork info for install guidance.`);
|
|
154
171
|
}
|
|
155
172
|
};
|
|
156
173
|
const actions = new TaskActions(agent => readiness(agent, true), agent => {
|
|
@@ -164,10 +181,39 @@ export async function apply(ctx, config) {
|
|
|
164
181
|
let phones = [];
|
|
165
182
|
// A paired phone's calls, replayed against this DSH's own web server through the allow-list; set where DSH serves web.
|
|
166
183
|
let launchUrl;
|
|
184
|
+
// A shared DSH's own roster and who owns each session (src/shared-roster.ts, src/shared-owner.ts).
|
|
185
|
+
const roster = new SharedRoster(sharedRosterPath(config.cachePath));
|
|
186
|
+
// The PIN lock (src/pin-lock.ts): per member on a shared DSH, the one `owner` on a personal computer.
|
|
187
|
+
const pins = new PinStore(pinsPath(config.cachePath));
|
|
188
|
+
// The audit archive (src/audit-archive.ts): every frame of a member's, sealed to the team admin's key.
|
|
189
|
+
const archive = new AuditArchive({
|
|
190
|
+
path: auditArchivePath(config.cachePath),
|
|
191
|
+
hostId: () => shared?.status().hostId,
|
|
192
|
+
identity: () => phoneKeys.identity(),
|
|
193
|
+
upload: async (body) => {
|
|
194
|
+
const response = await fetch(`${client.endpoint}/relay/shared/archive`, { method: 'POST', headers: { Authorization: `Bearer ${client.platformCredential()}`, 'Content-Type': 'application/json' }, body, signal: AbortSignal.timeout(30000) });
|
|
195
|
+
return { status: response.status };
|
|
196
|
+
},
|
|
197
|
+
log: (message) => ctx.logger.warn('%s', message),
|
|
198
|
+
});
|
|
199
|
+
ctx.effect(() => () => archive.stop());
|
|
200
|
+
/** Records a frame between a member's device and this shared DSH, in either direction. */
|
|
201
|
+
const audit = (frame, dir) => {
|
|
202
|
+
const pairingId = frame?.pairingId;
|
|
203
|
+
if (!shared?.enabled || typeof pairingId !== 'string')
|
|
204
|
+
return;
|
|
205
|
+
void roster.memberOf(pairingId).then((member) => { if (member)
|
|
206
|
+
archive.record({ member, device: pairingId, dir, frame }); });
|
|
207
|
+
};
|
|
208
|
+
const owners = new OwnerFilter(roster, (pairingId) => roster.memberOf(pairingId));
|
|
209
|
+
/** Who the server lets reach this shared DSH, as the relay last said; and members whose handsets wait to join. */
|
|
210
|
+
let sharedMembers = [];
|
|
211
|
+
const joining = new Map();
|
|
167
212
|
const bridge = new Bridge({
|
|
168
213
|
launchUrl: () => launchUrl?.(),
|
|
169
|
-
|
|
170
|
-
|
|
214
|
+
owners: () => shared?.enabled ? owners : undefined,
|
|
215
|
+
send: (frame) => { audit(frame, 'out'); security.send(frame); },
|
|
216
|
+
log: (message, error) => ctx.logger.warn('%s: %s', message, error?.message ?? ''),
|
|
171
217
|
session: {
|
|
172
218
|
async configuration(sessionId) {
|
|
173
219
|
const agent = sessionAgent(sessionId);
|
|
@@ -222,26 +268,62 @@ export async function apply(ctx, config) {
|
|
|
222
268
|
},
|
|
223
269
|
});
|
|
224
270
|
let keyScope;
|
|
271
|
+
const phoneKeys = new PhoneKeys(config.cachePath.replace(/\.json$/, '') + '.phone-keys.json');
|
|
272
|
+
// Shared mode (src/shared-mode.ts): the team host key signs this DSH in for its team, as no person. A host-provided
|
|
273
|
+
// token (tokenFile) is a cloud computer's, which is never shared this way.
|
|
274
|
+
const shared = config.tokenFile ? undefined : new SharedMode({
|
|
275
|
+
path: sharedKeyPath(config.cachePath),
|
|
276
|
+
server: () => client.endpoint,
|
|
277
|
+
identity: () => phoneKeys.identity(),
|
|
278
|
+
onToken: async (token) => {
|
|
279
|
+
pendingInstalls.clear();
|
|
280
|
+
await client.useToken(token);
|
|
281
|
+
await overlay.apply(client.current());
|
|
282
|
+
if (token && config.autoSync !== false)
|
|
283
|
+
await configSync.sync().catch(() => { });
|
|
284
|
+
},
|
|
285
|
+
log: message => ctx.logger.warn('%s', message),
|
|
286
|
+
});
|
|
287
|
+
ctx.effect(() => () => shared?.stop());
|
|
225
288
|
const security = new PhoneSecurity({
|
|
226
|
-
keys:
|
|
289
|
+
keys: phoneKeys,
|
|
227
290
|
scope: () => {
|
|
228
291
|
const revision = client.sessionRevision();
|
|
229
292
|
if (!keyScope || keyScope.revision !== revision) {
|
|
230
|
-
|
|
293
|
+
// A shared DSH has no profile: its phones are trusted under its shared host.
|
|
294
|
+
const hostId = shared?.enabled ? shared.status().hostId : undefined;
|
|
295
|
+
const value = hostId ? Promise.resolve(`${client.endpoint}|shared:${hostId}`) : client.profile().then(profile => `${client.endpoint}|${profile.id}`);
|
|
231
296
|
keyScope = { revision, value };
|
|
232
297
|
void value.catch(() => { if (keyScope?.value === value)
|
|
233
298
|
keyScope = undefined; });
|
|
234
299
|
}
|
|
235
300
|
return keyScope.value;
|
|
236
301
|
},
|
|
237
|
-
send: frame => relay.send(frame), forward: frame => bridge.handle(frame),
|
|
302
|
+
send: frame => relay.send(frame), forward: frame => { audit(frame, 'in'); bridge.handle(frame); },
|
|
238
303
|
confirm: async (id) => { await relay.request({ t: 'decide', pairingId: id, accept: true }); },
|
|
239
304
|
changed: () => { },
|
|
240
305
|
error: error => ctx.logger.warn('phone security: %s', error.message),
|
|
306
|
+
joining: (pairingId) => shared?.enabled ? joining.get(pairingId) : undefined,
|
|
307
|
+
pins,
|
|
308
|
+
pinMember: async (pairingId) => shared?.enabled ? roster.memberOf(pairingId) : 'owner',
|
|
309
|
+
admit: async (input) => {
|
|
310
|
+
// No member joins before the admin's audit key is set: nothing they do would be archived.
|
|
311
|
+
if (!(await archive.ready())) {
|
|
312
|
+
ctx.logger.warn('A member tried to join before the audit key was set (/teamwork share audit-key).');
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
if (!sharedMembers.some((m) => m.userId === input.userId))
|
|
316
|
+
return false;
|
|
317
|
+
const admitted = await roster.accept({ inviteId: input.inviteId, secret: input.secret, userId: input.userId, pairingId: input.pairingId, deviceName: input.name });
|
|
318
|
+
if (admitted)
|
|
319
|
+
joining.delete(input.pairingId);
|
|
320
|
+
return admitted;
|
|
321
|
+
},
|
|
241
322
|
});
|
|
242
323
|
const relay = new RelayLink({
|
|
243
324
|
endpoint: () => client.endpoint,
|
|
244
325
|
// A token from tokenFile belongs to a cloud computer, which the server reaches directly; it never opens the relay.
|
|
326
|
+
// A shared DSH reaches it with its host token, as its team's host.
|
|
245
327
|
token: () => !config.tokenFile && client.authenticated() ? client.platformCredential() : undefined,
|
|
246
328
|
clientIdPath: relayClientIdPath(config.cachePath),
|
|
247
329
|
onStatus: (status) => {
|
|
@@ -254,24 +336,46 @@ export async function apply(ctx, config) {
|
|
|
254
336
|
bridge.dropAll();
|
|
255
337
|
}
|
|
256
338
|
},
|
|
257
|
-
onEvent: () =>
|
|
339
|
+
onEvent: (event) => {
|
|
340
|
+
if (event.t === 'members')
|
|
341
|
+
void sharedList(event.members);
|
|
342
|
+
else
|
|
343
|
+
void readPhones();
|
|
344
|
+
},
|
|
258
345
|
onForward: (frame) => void security.handle(frame),
|
|
259
346
|
});
|
|
347
|
+
/** The server's list changed: whoever left loses their devices here too, whatever the relay already cut. */
|
|
348
|
+
const sharedList = async (members) => {
|
|
349
|
+
sharedMembers = members;
|
|
350
|
+
try {
|
|
351
|
+
for (const pairingId of await roster.prune(new Set(members.map((m) => m.userId))))
|
|
352
|
+
await security.revoke(pairingId);
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
ctx.logger.warn('Could not update the shared roster: %s', error.message);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
260
358
|
const readPhones = async () => {
|
|
261
359
|
try {
|
|
262
|
-
|
|
360
|
+
const listed = pairingSchema.array().parse(await relay.request({ t: 'pairings' }));
|
|
361
|
+
joining.clear();
|
|
362
|
+
for (const phone of listed)
|
|
363
|
+
if (phone.status === 'pending' && phone.userId)
|
|
364
|
+
joining.set(phone.id, phone.userId);
|
|
365
|
+
phones = listed.map(({ userId: _userId, ...phone }) => phone);
|
|
366
|
+
await security.reconcile(phones.map((phone) => phone.id));
|
|
263
367
|
}
|
|
264
368
|
catch (error) {
|
|
265
|
-
ctx.logger.warn('
|
|
369
|
+
ctx.logger.warn('Could not read the paired phones: %s', error.message);
|
|
266
370
|
}
|
|
267
371
|
};
|
|
268
372
|
const phoneError = (error) => {
|
|
269
373
|
if (error instanceof RelayError && error.code === 'not_found')
|
|
270
|
-
throw new Error('
|
|
271
|
-
throw new Error(relay.status === 'connected' ? '
|
|
374
|
+
throw new Error(say('phone.notFound'));
|
|
375
|
+
throw new Error(say(relay.status === 'connected' ? 'phone.relayBusy' : 'phone.relayOff'));
|
|
272
376
|
};
|
|
273
377
|
ctx.effect(() => () => relay.stop());
|
|
274
|
-
// The phone's notifications (
|
|
378
|
+
// The phone's notifications (the server's docs/tech/relay.md, "Push notifications"): when an agent waits on its member,
|
|
275
379
|
// tell the relay which session, and hand on to the answerers untouched. Prepended, so it is told even when one claims the request.
|
|
276
380
|
const reportWaiting = (kind) => function (request, next) {
|
|
277
381
|
const agent = request?.agent ?? this;
|
|
@@ -286,8 +390,79 @@ export async function apply(ctx, config) {
|
|
|
286
390
|
let callback;
|
|
287
391
|
const stopCallback = () => { callback?.close(); callback = undefined; };
|
|
288
392
|
ctx.effect(() => () => stopCallback());
|
|
289
|
-
const hostManaged = () => {
|
|
290
|
-
|
|
393
|
+
const hostManaged = () => {
|
|
394
|
+
if (config.tokenFile)
|
|
395
|
+
throw new Error(say('auth.hostManaged'));
|
|
396
|
+
if (shared?.enabled)
|
|
397
|
+
throw new Error(say('auth.shared'));
|
|
398
|
+
};
|
|
399
|
+
/** `/teamwork share enable <key>`: personal sign-in ends first, so this DSH is never both a person's and the team's. */
|
|
400
|
+
const shareEnable = async (key) => {
|
|
401
|
+
if (!shared)
|
|
402
|
+
throw new Error(say('auth.hostManaged'));
|
|
403
|
+
pendingInstalls.clear();
|
|
404
|
+
stopCallback();
|
|
405
|
+
if (!shared.enabled && client.authenticated()) {
|
|
406
|
+
await client.logout();
|
|
407
|
+
setLocale(null);
|
|
408
|
+
await overlay.apply();
|
|
409
|
+
await pins.reset();
|
|
410
|
+
}
|
|
411
|
+
await shared.enable(key);
|
|
412
|
+
relay.refresh();
|
|
413
|
+
};
|
|
414
|
+
const shareDisable = async () => {
|
|
415
|
+
if (!shared?.enabled)
|
|
416
|
+
throw new Error(say('shared.off'));
|
|
417
|
+
await archive.clear();
|
|
418
|
+
await shared.disable();
|
|
419
|
+
await roster.clear();
|
|
420
|
+
await pins.reset();
|
|
421
|
+
sharedMembers = [];
|
|
422
|
+
joining.clear();
|
|
423
|
+
relay.refresh();
|
|
424
|
+
};
|
|
425
|
+
/** The listed member with that email, or the reason there is none, in the member's words. */
|
|
426
|
+
const listedMember = (email) => {
|
|
427
|
+
if (!shared?.enabled)
|
|
428
|
+
throw new Error(say('shared.off'));
|
|
429
|
+
const member = sharedMembers.find((m) => m.email?.toLowerCase() === email.trim().toLowerCase());
|
|
430
|
+
if (!member?.email)
|
|
431
|
+
throw new Error(say('shared.notListed', { email }));
|
|
432
|
+
return { userId: member.userId, email: member.email };
|
|
433
|
+
};
|
|
434
|
+
/** `/teamwork share unlock <email>`: clears one member's PIN and lock. */
|
|
435
|
+
const shareUnlock = async (email) => { await pins.clear(listedMember(email).userId); };
|
|
436
|
+
/** `/teamwork share audit-key <key>`: seals the archive to the admin's key; members are admitted from then on. */
|
|
437
|
+
const shareAuditKey = async (key) => {
|
|
438
|
+
if (!shared?.enabled)
|
|
439
|
+
throw new Error(say('shared.off'));
|
|
440
|
+
return archive.setKey(key);
|
|
441
|
+
};
|
|
442
|
+
/** What the panel shows of shared mode: the machine, its audit key, and its members with their devices. */
|
|
443
|
+
const sharedView = async () => {
|
|
444
|
+
const status = shared?.status();
|
|
445
|
+
if (!status?.enabled)
|
|
446
|
+
return null;
|
|
447
|
+
const devices = Object.values(await roster.devices());
|
|
448
|
+
return {
|
|
449
|
+
name: status.name ?? null, teamName: client.current()?.teams[0]?.teamName ?? null, error: status.error ?? null,
|
|
450
|
+
auditKey: (await archive.fingerprint()) ?? null,
|
|
451
|
+
members: await Promise.all(sharedMembers.map(async (m) => ({
|
|
452
|
+
userId: m.userId, email: m.email ?? null, devices: devices.filter((d) => d.userId === m.userId).map((d) => d.name), locked: await pins.locked(m.userId),
|
|
453
|
+
}))),
|
|
454
|
+
};
|
|
455
|
+
};
|
|
456
|
+
/** `/teamwork share invite <email>`: a single-use link for one member the server lists, to hand over outside it. */
|
|
457
|
+
const shareInvite = async (email) => {
|
|
458
|
+
const status = shared?.status();
|
|
459
|
+
if (!status?.enabled || !status.hostId)
|
|
460
|
+
throw new Error(say('shared.off'));
|
|
461
|
+
const member = listedMember(email);
|
|
462
|
+
const { id, secret, expiresAt } = await roster.invite({ userId: member.userId, email: member.email });
|
|
463
|
+
const query = new URLSearchParams({ server: client.endpoint, host: status.hostId, key: await security.publicKey(), invite: id, secret });
|
|
464
|
+
return { link: `dshteamwork://join?${query}`, expiresAt: new Date(expiresAt).toISOString() };
|
|
465
|
+
};
|
|
291
466
|
const authorize = async (code) => { hostManaged(); pendingInstalls.clear(); try {
|
|
292
467
|
await client.completeLogin(code);
|
|
293
468
|
}
|
|
@@ -300,14 +475,16 @@ export async function apply(ctx, config) {
|
|
|
300
475
|
const beginLogin = async () => {
|
|
301
476
|
hostManaged();
|
|
302
477
|
stopCallback();
|
|
303
|
-
callback = await listenForCode(authorize).catch((error) => { ctx.logger.warn('
|
|
478
|
+
callback = await listenForCode(authorize).catch((error) => { ctx.logger.warn('Cannot receive the authorization code on this machine; it has to be pasted: %s', error.message); return undefined; });
|
|
304
479
|
return { url: client.beginLogin(callback?.uri), automatic: callback !== undefined };
|
|
305
480
|
};
|
|
306
481
|
const restore = async () => { await client.restore(); await overlay.apply(client.current()); relay.refresh(); };
|
|
307
482
|
const logout = async () => { hostManaged(); pendingInstalls.clear(); stopCallback(); try {
|
|
308
483
|
await client.logout();
|
|
484
|
+
await pins.reset();
|
|
309
485
|
}
|
|
310
486
|
finally {
|
|
487
|
+
setLocale(null);
|
|
311
488
|
await overlay.apply();
|
|
312
489
|
relay.refresh();
|
|
313
490
|
} };
|
|
@@ -351,9 +528,12 @@ export async function apply(ctx, config) {
|
|
|
351
528
|
const snapshot = client.current();
|
|
352
529
|
const item = findConfig(snapshot, id), team = teamOf(snapshot, id);
|
|
353
530
|
if (!item || !team || item.kind === 'plugin')
|
|
354
|
-
throw new Error('
|
|
531
|
+
throw new Error(say('use.pick'));
|
|
355
532
|
if (!inheritsModel(item) && !modelData(snapshot, item))
|
|
356
|
-
throw new Error('
|
|
533
|
+
throw new Error(say('use.modelGone'));
|
|
534
|
+
const limit = modelLimitProblem(snapshot, item);
|
|
535
|
+
if (limit)
|
|
536
|
+
throw new Error(limit);
|
|
357
537
|
if (item.kind === 'preset') {
|
|
358
538
|
assertBlank(ctx.agents.turnBoundaryOf(agent.session));
|
|
359
539
|
if (item.data.pluginDependencies?.length)
|
|
@@ -361,7 +541,7 @@ export async function apply(ctx, config) {
|
|
|
361
541
|
const candidate = { requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [] };
|
|
362
542
|
const unavailable = requirements(agent, candidate).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
|
|
363
543
|
if (unavailable.length)
|
|
364
|
-
throw new Error(
|
|
544
|
+
throw new Error(say('use.missingTools', { tools: unavailable.map(t => t.name).join(', ') }));
|
|
365
545
|
await ctx.agentPresets.select(agent, `team:${team.teamId}:${item.id}`);
|
|
366
546
|
const active = activePreset(agent);
|
|
367
547
|
if (active && !sameRevision(stamps.get(String(agent.id)), active))
|
|
@@ -369,7 +549,7 @@ export async function apply(ctx, config) {
|
|
|
369
549
|
}
|
|
370
550
|
if (!inheritsModel(item))
|
|
371
551
|
agent.model.select({ provider: platformProvider, model: item.id });
|
|
372
|
-
return { preset: item.kind === 'preset', text:
|
|
552
|
+
return { preset: item.kind === 'preset', text: say('use.done', { name: item.name }) };
|
|
373
553
|
};
|
|
374
554
|
/** Installs a pinned plugin disabled, enables it only when it adds configuration and overrides nothing. Callers confirm first. */
|
|
375
555
|
const installPlugin = async (item, agent) => {
|
|
@@ -377,20 +557,20 @@ export async function apply(ctx, config) {
|
|
|
377
557
|
const epoch = client.sessionRevision(), signature = JSON.stringify(item);
|
|
378
558
|
const manager = ctx.get('pluginManager');
|
|
379
559
|
if (!manager)
|
|
380
|
-
throw new Error('
|
|
560
|
+
throw new Error(say('install.noManager'));
|
|
381
561
|
const existing = (await manager.listBundles()).find(bundle => bundle.name === item.data.package);
|
|
382
562
|
if (existing && (existing.installed || existing.enabled || existing.availability === 'installation'))
|
|
383
|
-
throw new Error('
|
|
563
|
+
throw new Error(say('install.exists'));
|
|
384
564
|
const teamId = teamOf(client.current(), item.id)?.teamId;
|
|
385
565
|
const target = item.data.artifactId ? await client.downloadArtifact(teamId, item.data.artifactId, item.data.sha256) : spec;
|
|
386
566
|
if (epoch !== client.sessionRevision() || JSON.stringify(pinnedPlugin(client.current(), item.id, item.data.version)) !== signature)
|
|
387
|
-
throw new Error('
|
|
567
|
+
throw new Error(say('install.changed'));
|
|
388
568
|
const installed = await manager.installBundle(target, { saveExact: true, enabled: false });
|
|
389
569
|
if (installed.error || ['failed', 'cancelled', 'overridden'].includes(installed.application))
|
|
390
|
-
throw new Error(
|
|
570
|
+
throw new Error(say('install.incomplete', { reason: installed.error?.code ?? installed.application }));
|
|
391
571
|
const bundle = (await manager.listBundles()).find(bundle => bundle.name === item.data.package);
|
|
392
572
|
if (!bundle || bundle.error || bundle.version !== item.data.version || bundle.overrides.length || bundle.rows.some(row => row.entryId !== undefined)) {
|
|
393
|
-
throw new Error('
|
|
573
|
+
throw new Error(say('install.notEnabled'));
|
|
394
574
|
}
|
|
395
575
|
const result = await manager.setBundleEnabled(item.data.package, true);
|
|
396
576
|
if (result.error || ['failed', 'cancelled', 'overridden'].includes(result.application))
|
|
@@ -400,14 +580,15 @@ export async function apply(ctx, config) {
|
|
|
400
580
|
const refreshed = (await plugins()).find(p => p.id === item.id);
|
|
401
581
|
const currentPreset = agent && activePreset(agent);
|
|
402
582
|
const missingTools = agent && currentPreset ? requirements(agent, currentPreset).filter(t => t.required && ['missing', 'unknown'].includes(t.state)) : [];
|
|
403
|
-
const toolSummary = currentPreset ?
|
|
404
|
-
return [(result.application === 'restart-required' ? '
|
|
583
|
+
const toolSummary = currentPreset ? `Required tools of the current preset: ${missingTools.length ? missingTools.map(t => t.name).join(', ') + ' not available yet' : 'all registered (running them still needs the host’s permission)'}` : '';
|
|
584
|
+
return [say(result.application === 'restart-required' ? 'install.restart' : 'install.done'), refreshed?.text ?? '', toolSummary].filter(Boolean).join('\n');
|
|
405
585
|
};
|
|
406
586
|
const sessionAgent = (sessionId) => sessionId ? ctx.agents.get(sessionId) : undefined;
|
|
407
587
|
const panel = {
|
|
408
|
-
|
|
409
|
-
profile
|
|
410
|
-
|
|
588
|
+
summary: teamId => client.summary(teamId),
|
|
589
|
+
// The panel reads the profile as it opens, so the host speaks the account's language from then on.
|
|
590
|
+
profile: async () => { const profile = await client.profile(); setLocale(profile.locale); return profile; },
|
|
591
|
+
updateProfile: async (input) => { const profile = await client.updateProfile(input); setLocale(profile.locale); return profile; },
|
|
411
592
|
async state(sessionId) {
|
|
412
593
|
const status = configSync.status(), snapshot = client.current(), agent = sessionAgent(sessionId);
|
|
413
594
|
// Inventory scans read the whole host. Share one within this response, never across requests.
|
|
@@ -422,14 +603,17 @@ export async function apply(ctx, config) {
|
|
|
422
603
|
const candidate = { requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [] };
|
|
423
604
|
presets.push({
|
|
424
605
|
id: item.id, teamId: team.teamId, teamName: team.teamName, name: item.name, version: item.version, description: item.data.description ?? '',
|
|
425
|
-
model: item.data.inheritModel ?
|
|
426
|
-
|
|
606
|
+
model: item.data.inheritModel ? null : item.data.modelConfigId ? linked?.name ?? item.data.modelConfigId : `${item.data.provider}/${item.data.model}`,
|
|
607
|
+
assistant: item.builtin === 'team-assistant',
|
|
608
|
+
modelAvailable: inheritsModel(item) || !!modelData(snapshot, item) && !unsizedModel(snapshot, item),
|
|
609
|
+
contextWindowMissing: !!unsizedModel(snapshot, item),
|
|
427
610
|
tools: agent ? requirements(agent, candidate) : toolReport(candidate, () => 'unknown'),
|
|
428
611
|
plugins: item.data.pluginDependencies?.length ? await plugins({ teamId: team.teamId, pluginDependencies: item.data.pluginDependencies }, readInventory) : [],
|
|
429
612
|
});
|
|
430
613
|
}
|
|
431
614
|
const selection = agent?.model.current(), active = agent && activePreset(agent), boundary = agent && ctx.agents.turnBoundaryOf(agent.session);
|
|
432
615
|
return {
|
|
616
|
+
locale: panelLocale(),
|
|
433
617
|
authRevision: client.sessionRevision(),
|
|
434
618
|
authenticated: status.authenticated,
|
|
435
619
|
teams: (snapshot?.teams ?? []).map(team => ({ id: team.teamId, name: team.teamName, role: team.role, consoleUrl: `${client.endpoint}/teams/${team.teamId}` })),
|
|
@@ -438,15 +622,16 @@ export async function apply(ctx, config) {
|
|
|
438
622
|
sync: { auto: status.autoSync, running: status.syncing, lastSuccess: status.lastSuccess, lastError: status.lastError },
|
|
439
623
|
relay: relay.status,
|
|
440
624
|
phones: await Promise.all(phones.map(async (phone) => ({ ...phone, ...await security.details(phone.id) }))),
|
|
625
|
+
shared: await sharedView(),
|
|
441
626
|
session: agent ? {
|
|
442
627
|
id: String(agent.id),
|
|
443
628
|
model: selection ? { provider: selection.provider, model: selection.model, team: selection.provider === platformProvider } : null,
|
|
444
629
|
preset: active ? { id: active.id, name: active.name, version: active.version } : null,
|
|
445
630
|
started: boundary.openTurnStartSeq !== null || boundary.lastTurn > 0,
|
|
446
631
|
} : null,
|
|
447
|
-
presets: presets.sort((a, b) => Number(
|
|
632
|
+
presets: presets.sort((a, b) => Number(b.assistant) - Number(a.assistant)),
|
|
448
633
|
models: (snapshot?.teams ?? []).flatMap(team => team.configs.flatMap(c => c.kind === 'model'
|
|
449
|
-
? [{ id: c.id, teamId: team.teamId, teamName: team.teamName, name: c.name, version: c.version, upstream: `${c.data.provider}/${c.data.model}
|
|
634
|
+
? [{ id: c.id, teamId: team.teamId, teamName: team.teamName, name: c.name, version: c.version, upstream: `${c.data.provider}/${c.data.model}`, contextWindowMissing: !!unsizedModel(snapshot, c) }] : [])),
|
|
450
635
|
plugins: (await plugins(undefined, readInventory)).map(plugin => {
|
|
451
636
|
const team = teamOf(snapshot, plugin.id);
|
|
452
637
|
return { ...plugin, teamId: team?.teamId, teamName: team?.teamName };
|
|
@@ -466,6 +651,7 @@ export async function apply(ctx, config) {
|
|
|
466
651
|
await serverChoice.write(next === serverAddress(config.apiEndpoint) ? undefined : next);
|
|
467
652
|
}
|
|
468
653
|
finally {
|
|
654
|
+
setLocale(null);
|
|
469
655
|
await overlay.apply(client.current());
|
|
470
656
|
relay.refresh();
|
|
471
657
|
}
|
|
@@ -491,26 +677,31 @@ export async function apply(ctx, config) {
|
|
|
491
677
|
await relay.request({ t: 'revoke', pairingId: id }).catch(phoneError);
|
|
492
678
|
await readPhones();
|
|
493
679
|
},
|
|
680
|
+
shareEnable,
|
|
681
|
+
shareDisable,
|
|
682
|
+
shareAuditKey: async (key) => ({ fingerprint: await shareAuditKey(key) }),
|
|
683
|
+
shareInvite,
|
|
684
|
+
shareUnlock,
|
|
494
685
|
async use(sessionId, id) {
|
|
495
686
|
const agent = sessionAgent(sessionId);
|
|
496
687
|
if (!agent)
|
|
497
|
-
throw new Error('
|
|
688
|
+
throw new Error(say('use.notLoaded'));
|
|
498
689
|
return (await useConfig(agent, id)).text;
|
|
499
690
|
},
|
|
500
691
|
async install(id, version) {
|
|
501
692
|
const item = pinnedPlugin(client.current(), id, version);
|
|
502
693
|
if (!item || item.kind !== 'plugin')
|
|
503
|
-
throw new Error('
|
|
694
|
+
throw new Error(say('install.pick'));
|
|
504
695
|
// The member confirmed this exact version; a sync since then may have changed the pin.
|
|
505
696
|
if (item.data.version !== version)
|
|
506
|
-
throw new Error('
|
|
697
|
+
throw new Error(say('install.pinChanged'));
|
|
507
698
|
return installPlugin(item);
|
|
508
699
|
},
|
|
509
700
|
};
|
|
510
701
|
// The panel's routes exist only where a browser reaches the host (DSH web and desktop), like the panel itself.
|
|
511
702
|
ctx.inject(['connection'], (scoped) => {
|
|
512
703
|
const { connection } = scoped;
|
|
513
|
-
for (const route of panelRoutes(panel))
|
|
704
|
+
for (const route of panelRoutes(panel, { say, speak: answer => speaking(panelLocale(), answer) }))
|
|
514
705
|
scoped.effect(() => { const dispose = connection.fetch.register(route); return () => { void dispose(); }; });
|
|
515
706
|
});
|
|
516
707
|
ctx.inject(['connection', 'webServer'], (scoped) => {
|
|
@@ -522,119 +713,159 @@ export async function apply(ctx, config) {
|
|
|
522
713
|
});
|
|
523
714
|
ctx.inject(['commands'], (child) => {
|
|
524
715
|
child.effect(() => child.commands.register({
|
|
525
|
-
name: 'teamwork', description: '
|
|
526
|
-
input: { hint: 'login | authorize <code> | sync | status | session [check] | continue
|
|
716
|
+
name: 'teamwork', description: 'Team sign-in, configuration sync and model selection',
|
|
717
|
+
input: { hint: 'login | authorize <code> | share enable <key> | share disable | share status | share invite <email> | share members | share unlock <email> | share audit-key <key> | pin reset | sync | status | session [check] | continue <instruction> | cancel | retry [confirm] | list | tools | plugins [presetId] | info [id] | new <id> | use <id> | install <id> confirm | logout' },
|
|
527
718
|
handler: async ({ agent, rawInput }) => {
|
|
528
719
|
const [action, requestedId, confirmation] = rawInput.trim().split(/\s+/);
|
|
529
720
|
const [id, pinVersion] = requestedId?.split('@') ?? [];
|
|
530
721
|
try {
|
|
531
722
|
if (action === 'session') {
|
|
532
|
-
let ready = '
|
|
723
|
+
let ready = 'Local checks passed; team access is verified again before continuing.';
|
|
533
724
|
try {
|
|
534
725
|
await readiness(agent, id === 'check');
|
|
535
726
|
if (id === 'check')
|
|
536
|
-
ready = '
|
|
727
|
+
ready = 'Checks passed; the server still verifies access on the real request.';
|
|
537
728
|
}
|
|
538
729
|
catch (error) {
|
|
539
730
|
ready = error.message;
|
|
540
731
|
}
|
|
541
732
|
const task = taskState.stateOf(agent.session), preset = activePreset(agent), selection = agent.model.current();
|
|
542
|
-
return { kind: 'success', text: [
|
|
733
|
+
return { kind: 'success', text: [`Session: ${agent.id}`, `Status: ${agent.status === 'running' ? 'running' : 'idle'} · last task: ${outcomeText(task.outcome)}`, `Task: ${task.task || (task.outcome === 'not-started' ? 'no task started yet' : 'non-text task (see the session history)')}`, `Pending input: ${agent.inbox.nextTurn.length} follow-up / ${agent.inbox.nextStep.length} steering`, `Model: ${selection?.provider ?? 'none'}/${selection?.model ?? 'none'}`, `Preset: ${preset ? preset.name + ' v' + preset.version : 'local or no team preset'}`, `Recovery check: ${ready}`, recoveryHint(task.failureCode, task.outcome)].join('\n') };
|
|
543
734
|
}
|
|
544
735
|
if (action === 'cancel') {
|
|
545
736
|
actions.cancel(agent);
|
|
546
|
-
return { kind: 'success', text: '
|
|
737
|
+
return { kind: 'success', text: 'Cancellation requested; run /teamwork session to see whether it stopped. History, finished changes and pending input stay; nothing is rolled back.' };
|
|
547
738
|
}
|
|
548
739
|
if (action === 'continue') {
|
|
549
740
|
await actions.submit(agent, rawInput.trim().slice('continue'.length).trim());
|
|
550
|
-
return { kind: 'success', text: '
|
|
741
|
+
return { kind: 'success', text: 'The follow-up was handed to DSH; run /teamwork session to see its status.' };
|
|
551
742
|
}
|
|
552
743
|
if (action === 'retry') {
|
|
553
744
|
if (id !== 'confirm') {
|
|
554
745
|
actions.review(agent, taskState.stateOf(agent.session).outcome);
|
|
555
|
-
return { kind: 'success', text: '
|
|
746
|
+
return { kind: 'success', text: 'Retrying sends a follow-up asking the agent to check what is done and finish the task, which may still make new changes. It never replays the original tool calls or rolls files back. To confirm, run /teamwork retry confirm (valid for two minutes; confirm again after the session or configuration changes).' };
|
|
556
747
|
}
|
|
557
748
|
await actions.submit(agent, retryInstruction, true);
|
|
558
|
-
return { kind: 'success', text: '
|
|
749
|
+
return { kind: 'success', text: 'Recovery instruction sent; no original tool call was replayed.' };
|
|
559
750
|
}
|
|
560
751
|
if (action === 'login') {
|
|
561
752
|
const { url, automatic } = await beginLogin();
|
|
562
753
|
return { kind: 'success', text: automatic
|
|
563
|
-
?
|
|
564
|
-
:
|
|
754
|
+
? `Sign in and authorize in the browser: ${url}\nThis finishes by itself once you confirm. If it does not, paste the line shown on the page here and run it.`
|
|
755
|
+
: `Sign in and authorize in the browser: ${url}\nThen paste the line shown on the page here and run it (/teamwork authorize <code>).` };
|
|
565
756
|
}
|
|
566
757
|
if (action === 'authorize') {
|
|
567
758
|
await authorize(id ?? '');
|
|
568
|
-
return { kind: 'success', text: '
|
|
759
|
+
return { kind: 'success', text: 'Authorized. Run /teamwork status to see the sync status.' };
|
|
760
|
+
}
|
|
761
|
+
if (action === 'share') {
|
|
762
|
+
if (requestedId === 'enable') {
|
|
763
|
+
await shareEnable(confirmation ?? '');
|
|
764
|
+
const st = shared.status();
|
|
765
|
+
return { kind: 'success', text: `This DSH is now the shared DSH “${st.name}” of its team. Personal sign-in is off while it is shared; /teamwork share disable ends it.` };
|
|
766
|
+
}
|
|
767
|
+
if (requestedId === 'disable') {
|
|
768
|
+
await shareDisable();
|
|
769
|
+
return { kind: 'success', text: 'Shared mode is off and its key deleted. Sign in with /teamwork login to use this DSH as yourself.' };
|
|
770
|
+
}
|
|
771
|
+
if (requestedId === 'invite') {
|
|
772
|
+
const invite = await shareInvite(confirmation ?? '');
|
|
773
|
+
return { kind: 'success', text: [`Invite for ${confirmation}, single use, valid until ${invite.expiresAt}:`, invite.link, 'Hand it over yourself, in person or through a channel your team trusts, never through the Teamwork server. Whoever opens it signed in as that member pairs a device with this DSH.'].join('\n') };
|
|
774
|
+
}
|
|
775
|
+
if (requestedId === 'audit-key') {
|
|
776
|
+
const fingerprint = await shareAuditKey(confirmation ?? '');
|
|
777
|
+
return { kind: 'success', text: `Audit key set (fingerprint ${fingerprint}). Every member's session on this DSH is now archived, sealed to it; members can join.` };
|
|
778
|
+
}
|
|
779
|
+
if (requestedId === 'unlock') {
|
|
780
|
+
await shareUnlock(confirmation ?? '');
|
|
781
|
+
return { kind: 'success', text: `${confirmation}'s PIN and lock are cleared; they set a new PIN on their next connection.` };
|
|
782
|
+
}
|
|
783
|
+
if (requestedId === 'members') {
|
|
784
|
+
const devices = await roster.devices();
|
|
785
|
+
const rows = sharedMembers.map((m) => `${m.email ?? m.userId}: ${Object.values(devices).filter((d) => d.userId === m.userId).map((d) => d.name).join(', ') || 'no device yet'}`);
|
|
786
|
+
return { kind: 'success', text: rows.length ? ['Members who may reach this shared DSH, and their devices:', ...rows].join('\n') : 'Nobody is listed yet, or the relay is not connected.' };
|
|
787
|
+
}
|
|
788
|
+
const st = shared?.status() ?? { enabled: false };
|
|
789
|
+
return { kind: 'success', text: st.enabled ? [`Shared DSH: ${st.name ?? st.hostId ?? 'not yet confirmed'}`, `Team: ${st.teamId ?? 'unknown'}`, st.expiresAt ? `Host token valid until ${st.expiresAt}` : '', st.error ?? ''].filter(Boolean).join('\n') : 'Shared mode is off. A team admin creates a team host key in the console; run /teamwork share enable <key> here.' };
|
|
569
790
|
}
|
|
570
791
|
if (action === 'sync') {
|
|
571
792
|
await configSync.sync();
|
|
572
|
-
|
|
793
|
+
const synced = client.current(), problems = [...new Set(allConfigs(synced).filter(c => c.kind === 'model').flatMap(c => modelLimitProblem(synced, c) ?? []))];
|
|
794
|
+
return { kind: 'success', text: ['Team configuration synced; your local configuration is unchanged.', ...problems].join('\n') };
|
|
795
|
+
}
|
|
796
|
+
if (action === 'pin' && requestedId === 'reset') {
|
|
797
|
+
if (shared?.enabled)
|
|
798
|
+
throw new Error('On a shared DSH, clear a member\'s PIN with /teamwork share unlock <email>.');
|
|
799
|
+
await pins.clear('owner');
|
|
800
|
+
return { kind: 'success', text: 'Your phone PIN and its lock are cleared; set a new PIN on your phone\'s next connection.' };
|
|
573
801
|
}
|
|
574
802
|
if (action === 'logout') {
|
|
575
803
|
await logout();
|
|
576
|
-
return { kind: 'success', text: '
|
|
804
|
+
return { kind: 'success', text: 'Signed out, and the team configuration removed.' };
|
|
577
805
|
}
|
|
578
806
|
if (action === 'status') {
|
|
579
807
|
const status = configSync.status();
|
|
580
|
-
return { kind: 'success', text: [
|
|
808
|
+
return { kind: 'success', text: [`Signed in: ${status.authenticated ? 'yes' : 'no (a cache is not a valid sign-in)'}`, `Auto sync: ${status.autoSync ? 'on' : 'off'}`, `Teams: ${status.teams.length ? status.teams.join(', ') : 'none'} · configurations: ${status.configCount}`, `Last successful sync: ${status.lastSuccess ?? 'not since this start'}`, status.syncing ? 'Syncing' : '', status.lastError ?? ''].filter(Boolean).join('\n') };
|
|
581
809
|
}
|
|
582
810
|
const snapshot = client.current();
|
|
583
811
|
const item = id ? action === 'install' && pinVersion ? pinnedPlugin(snapshot, id, pinVersion) : findConfig(snapshot, id) : undefined, team = id ? teamOf(snapshot, id) : undefined;
|
|
584
812
|
if (action === 'tools') {
|
|
585
813
|
const tools = child.get('tools');
|
|
586
814
|
if (!tools)
|
|
587
|
-
throw new Error('
|
|
815
|
+
throw new Error('The host offers no tool check service');
|
|
588
816
|
const rows = tools.definitions(agent).map(tool => {
|
|
589
|
-
const declared = (snapshot?.teams ?? []).flatMap(t => t.configs.filter(c => c.kind === 'plugin' && c.data.providesTools?.includes(tool.name)).map(c => `${c.name}
|
|
590
|
-
return `${tool.name} · ${tools.executable(tool.name, agent) ? '
|
|
817
|
+
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})`));
|
|
818
|
+
return `${tool.name} · ${tools.executable(tool.name, agent) ? 'registered; running it still needs a permission check' : 'conditional'} · ${declared.length ? 'declared by team plugin ' + declared.join(', ') : 'source: the host gives no owner'}`;
|
|
591
819
|
});
|
|
592
|
-
return { kind: 'success', text: ['
|
|
820
|
+
return { kind: 'success', text: ['Tools visible to this session (a declared source is not a verified runtime owner):', ...rows, rows.length ? '' : 'No tools visible'].filter(Boolean).join('\n') };
|
|
593
821
|
}
|
|
594
822
|
if (action === 'plugins') {
|
|
595
823
|
if (id && item?.kind !== 'preset')
|
|
596
|
-
throw new Error('
|
|
824
|
+
throw new Error('Choose a team preset ID');
|
|
597
825
|
const preset = item?.kind === 'preset' ? { teamId: team.teamId, pluginDependencies: item.data.pluginDependencies } : undefined;
|
|
598
|
-
return { kind: 'success', text: (await plugins(preset)).map(p => p.text).join('\n') || '
|
|
826
|
+
return { kind: 'success', text: (await plugins(preset)).map(p => p.text).join('\n') || 'No plugin dependencies.' };
|
|
599
827
|
}
|
|
600
828
|
if (action === 'info') {
|
|
601
829
|
if (!id) {
|
|
602
830
|
const active = activePreset(agent);
|
|
603
|
-
return { kind: 'success', text: active ? detail(agent, active) + '\n' + (await plugins(active)).map(p => p.text).join('\n') : '
|
|
831
|
+
return { kind: 'success', text: active ? detail(agent, active) + '\n' + (await plugins(active)).map(p => p.text).join('\n') : 'This session has no team preset. Run /teamwork info <presetId> for details.' };
|
|
604
832
|
}
|
|
605
833
|
if (!item || item.kind !== 'preset')
|
|
606
|
-
throw new Error('
|
|
834
|
+
throw new Error('Choose a team preset ID');
|
|
607
835
|
const info = { teamId: team.teamId, id: item.id, name: item.name, version: item.version, description: '', instructions: '', outputDescription: '', requiredTools: [], optionalTools: [], ...item.data };
|
|
608
|
-
return { kind: 'success', text: detail(agent, info, true) + '\n' + (await plugins(info)).map(p => p.text).join('\n') + '\
|
|
836
|
+
return { kind: 'success', text: detail(agent, info, true) + '\n' + (await plugins(info)).map(p => p.text).join('\n') + '\nTools are checked for the current session, again after switching and before every request.' };
|
|
609
837
|
}
|
|
610
838
|
if (action === 'new') {
|
|
611
839
|
if (!item || item.kind !== 'preset')
|
|
612
|
-
throw new Error('
|
|
840
|
+
throw new Error('Choose a team preset ID');
|
|
613
841
|
if (!inheritsModel(item) && !modelData(snapshot, item))
|
|
614
|
-
throw new Error('
|
|
842
|
+
throw new Error(say('use.modelGone'));
|
|
843
|
+
const limit = modelLimitProblem(snapshot, item);
|
|
844
|
+
if (limit)
|
|
845
|
+
throw new Error(limit);
|
|
615
846
|
const sessionId = `team-${crypto.randomUUID()}`;
|
|
616
847
|
const agentPreset = `team:${team.teamId}:${item.id}`;
|
|
617
848
|
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() } : {}) });
|
|
618
|
-
return { kind: 'success', text:
|
|
849
|
+
return { kind: 'success', text: `Created session ${sessionId} with ${item.name} v${item.version}. Open it from the session list; the original session and its history are unchanged.` };
|
|
619
850
|
}
|
|
620
851
|
if (action === 'use') {
|
|
621
852
|
const chosen = await useConfig(agent, id ?? '');
|
|
622
|
-
return { kind: 'success', text: chosen.text + (chosen.preset ? '
|
|
853
|
+
return { kind: 'success', text: chosen.text + (chosen.preset ? ' Run /teamwork info for its version and tool status.' : '') };
|
|
623
854
|
}
|
|
624
855
|
if (action === 'install') {
|
|
625
856
|
if (!item || item.kind !== 'plugin')
|
|
626
|
-
throw new Error('
|
|
857
|
+
throw new Error(say('install.pick'));
|
|
627
858
|
const spec = `${item.data.package}@${item.data.version}`;
|
|
628
859
|
if (confirmation !== 'confirm') {
|
|
629
860
|
pendingInstalls.set(String(agent.id), `${client.sessionRevision()}:${JSON.stringify(item)}`);
|
|
630
|
-
return { kind: 'success', text:
|
|
861
|
+
return { kind: 'success', text: `Installing and enabling ${spec} runs that plugin’s code. To confirm, run /teamwork install ${item.id} confirm` };
|
|
631
862
|
}
|
|
632
863
|
if (pendingInstalls.get(String(agent.id)) !== `${client.sessionRevision()}:${JSON.stringify(item)}`)
|
|
633
|
-
throw new Error('
|
|
864
|
+
throw new Error('Read the install note for the current plugin version first, then confirm the install');
|
|
634
865
|
pendingInstalls.delete(String(agent.id));
|
|
635
|
-
return { kind: 'success', text: await installPlugin(item, agent) + '\
|
|
866
|
+
return { kind: 'success', text: await installPlugin(item, agent) + '\nRun /teamwork plugins or /teamwork info to check dependencies and tools again.' };
|
|
636
867
|
}
|
|
637
|
-
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') || '
|
|
868
|
+
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') || 'No team configuration' : 'Not synced yet. Run /teamwork login to start.' };
|
|
638
869
|
}
|
|
639
870
|
catch (error) {
|
|
640
871
|
return { kind: 'error', text: error.message };
|
|
@@ -646,7 +877,15 @@ export async function apply(ctx, config) {
|
|
|
646
877
|
await restore();
|
|
647
878
|
}
|
|
648
879
|
catch {
|
|
649
|
-
ctx.logger.warn('
|
|
880
|
+
ctx.logger.warn('The team cache could not be restored; sign in and sync again.');
|
|
881
|
+
}
|
|
882
|
+
try {
|
|
883
|
+
await shared?.restore();
|
|
884
|
+
if (shared?.enabled)
|
|
885
|
+
void archive.drain();
|
|
886
|
+
}
|
|
887
|
+
catch (error) {
|
|
888
|
+
ctx.logger.warn('Shared mode could not resume: %s', error.message);
|
|
650
889
|
}
|
|
651
890
|
if (config.tokenFile) {
|
|
652
891
|
const watcher = watchTokenFile(config.tokenFile, async (token) => {
|
|
@@ -655,7 +894,7 @@ export async function apply(ctx, config) {
|
|
|
655
894
|
await overlay.apply(client.current());
|
|
656
895
|
if (token && config.autoSync !== false)
|
|
657
896
|
await configSync.sync().catch(() => { });
|
|
658
|
-
}, error => ctx.logger.warn('
|
|
897
|
+
}, error => ctx.logger.warn('Could not read the Teamwork token file: %s', error.message));
|
|
659
898
|
ctx.effect(() => () => watcher.stop());
|
|
660
899
|
await watcher.ready;
|
|
661
900
|
}
|