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