@dsh-teamwork/dsh-teamwork 0.8.4 → 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/assets/readme/icon-256.png +0 -0
- package/assets/readme/review-and-publish.png +0 -0
- package/assets/readme/teamwork-panel.png +0 -0
- package/assets/readme/versions-and-backups.png +0 -0
- package/docs/development.md +88 -3
- package/docs/en/guide.md +50 -2
- package/docs/zh-CN/guide.md +20 -2
- package/icon.svg +7 -4
- 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 +58 -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 +356 -97
- 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 +55 -19
- package/lib/task-session.js.map +1 -1
- package/lib/token-file.js +34 -0
- package/lib/token-file.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 +27 -4
- package/lib/types/client.d.ts.map +1 -1
- package/lib/types/index.d.ts +3 -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/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 +63 -2
- package/lib/types/task-session.d.ts.map +1 -1
- package/lib/types/token-file.d.ts +11 -0
- package/lib/types/token-file.d.ts.map +1 -0
- package/lib/web/client.js +1138 -378
- package/package.json +8 -1
package/lib/index.js
CHANGED
|
@@ -3,8 +3,8 @@ 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';
|
|
7
|
-
import { taskProjection, TaskActions, recoveryHint, retryInstruction, outcomeText } from './task-session.js';
|
|
6
|
+
import { modelData, modelLimitProblem, unsizedModel, inheritsModel, pinnedPlugin } from './client.js';
|
|
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';
|
|
10
10
|
import { registerAssistantTools } from './assistant-tools.js';
|
|
@@ -14,20 +14,30 @@ import { PhoneSessionError, phonePresets } from './phone-session.js';
|
|
|
14
14
|
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
|
+
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';
|
|
17
24
|
export const name = 'dsh-teamwork';
|
|
18
25
|
export const inject = ['agentPresets', 'agents', 'llm', 'sessionProjections'];
|
|
19
26
|
/** The hosted service. A member can pick another server in the panel; the profile's `apiEndpoint` sets the default. */
|
|
20
27
|
export const DEFAULT_SERVER = 'https://www.dshteamwork.com';
|
|
21
|
-
export const Config = z.object({ apiEndpoint: z.string().default(DEFAULT_SERVER), cachePath: z.string().required(), autoSync: z.boolean().default(true), syncIntervalMs: z.number().default(60000) });
|
|
28
|
+
export const Config = z.object({ apiEndpoint: z.string().default(DEFAULT_SERVER), cachePath: z.string().required(), autoSync: z.boolean().default(true), syncIntervalMs: z.number().default(60000), tokenFile: z.string() });
|
|
22
29
|
export async function apply(ctx, config) {
|
|
23
30
|
const client = new TeamworkClient(config.apiEndpoint, config.cachePath);
|
|
24
31
|
const serverChoice = ServerChoice.beside(config.cachePath);
|
|
25
|
-
|
|
32
|
+
// With tokenFile the host names the server in apiEndpoint, and a member's earlier choice does not apply.
|
|
33
|
+
const chosen = config.tokenFile ? undefined : await serverChoice.read();
|
|
26
34
|
if (chosen)
|
|
27
35
|
await client.setEndpoint(chosen);
|
|
28
36
|
ctx.effect(() => ctx.llm.registerAdapter([platformProvider], platformAdapter(client)));
|
|
29
37
|
const taskState = await ctx.sessionProjections.register(taskProjection);
|
|
30
38
|
ctx.effect(() => () => taskState.dispose());
|
|
39
|
+
const stepState = await ctx.sessionProjections.register(stepProjection);
|
|
40
|
+
ctx.effect(() => () => stepState.dispose());
|
|
31
41
|
const stamps = new PresetStamps(presetStampPath(config.cachePath));
|
|
32
42
|
await stamps.load();
|
|
33
43
|
const overlay = new TeamOverlay(async (id, item, team) => ctx.agentPresets.register({
|
|
@@ -67,7 +77,7 @@ export async function apply(ctx, config) {
|
|
|
67
77
|
const state = !valid ? 'catalog-changed' : !manager ? 'unknown' : pluginState(dependency.version, bundle, entries, restartRequired.has(`${item.data.package}@${dependency.version}`));
|
|
68
78
|
return { id: dependency.pluginConfigId, name: item?.name ?? dependency.pluginConfigId, package: item?.kind === 'plugin' ? item.data.package : undefined,
|
|
69
79
|
version: dependency.version, description: item?.kind === 'plugin' ? item.data.description : '', localVersion: bundle?.version, state,
|
|
70
|
-
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}` : ''}` };
|
|
71
81
|
});
|
|
72
82
|
};
|
|
73
83
|
const checkPlugins = async (preset) => {
|
|
@@ -76,40 +86,48 @@ export async function apply(ctx, config) {
|
|
|
76
86
|
throw new PhoneSessionError('missing_plugins', missing.map(p => p.text).join('\n'));
|
|
77
87
|
};
|
|
78
88
|
// A stamp that fails to save is retaken on the session's next request; the session itself is unaffected.
|
|
79
|
-
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)); };
|
|
80
90
|
const stamp = (agent, preset) => keep(stamps.set(String(agent.id), preset));
|
|
81
91
|
const detail = (agent, preset, preview = false) => {
|
|
82
92
|
const snapshot = client.current();
|
|
83
93
|
const team = teamOf(snapshot, preset.id);
|
|
84
94
|
const latest = team?.teamId === preset.teamId ? findConfig(snapshot, preset.id) : undefined;
|
|
85
95
|
const tools = requirements(agent, preset);
|
|
86
|
-
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' };
|
|
87
97
|
const saved = preview ? null : stamps.get(String(agent.id));
|
|
88
|
-
const revision = latest ? latest.version === preset.version ? '
|
|
89
|
-
return [`${preset.name} · v${preset.version}`,
|
|
90
|
-
latest && snapshot && !inheritsModel(latest) && !modelData(snapshot, latest) ? '
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
'
|
|
96
|
-
|
|
97
|
-
'
|
|
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.',
|
|
98
109
|
].filter(Boolean).join('\n');
|
|
99
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.
|
|
100
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);
|
|
101
119
|
const preset = activePreset(agent);
|
|
102
120
|
if (preset) {
|
|
103
121
|
if (preset.inheritModel && !agent.model.current())
|
|
104
|
-
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.');
|
|
105
123
|
if (preset.pluginDependencies?.length)
|
|
106
124
|
await checkPlugins(preset);
|
|
107
125
|
const saved = stamps.get(String(agent.id));
|
|
108
126
|
if (saved && !sameRevision(saved, preset))
|
|
109
|
-
throw new Error('
|
|
127
|
+
throw new Error('The team preset changed version since this session started. Start a new session.');
|
|
110
128
|
const missing = requirements(agent, preset).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
|
|
111
129
|
if (missing.length)
|
|
112
|
-
throw new Error(
|
|
130
|
+
throw new Error(`Required tools are missing: ${missing.map(t => t.name).join(', ')}. Install or enable them, then try again.`);
|
|
113
131
|
if (!saved)
|
|
114
132
|
stamp(agent, preset);
|
|
115
133
|
}
|
|
@@ -121,32 +139,35 @@ export async function apply(ctx, config) {
|
|
|
121
139
|
const readiness = async (agent, fresh = false) => {
|
|
122
140
|
const selection = agent.model.current();
|
|
123
141
|
if (!selection)
|
|
124
|
-
throw new PhoneSessionError('model_unavailable', '
|
|
142
|
+
throw new PhoneSessionError('model_unavailable', 'No model is selected. Choose a local model, or run /teamwork use <id>.');
|
|
125
143
|
if (selection.provider === platformProvider) {
|
|
126
144
|
if (!client.authenticated())
|
|
127
|
-
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.');
|
|
128
146
|
if (fresh) {
|
|
129
147
|
try {
|
|
130
148
|
await configSync.sync();
|
|
131
149
|
}
|
|
132
150
|
catch {
|
|
133
|
-
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.');
|
|
134
152
|
}
|
|
135
153
|
}
|
|
136
154
|
const snapshot = client.current(), item = findConfig(snapshot, selection.model);
|
|
137
155
|
if (!snapshot || !item || !modelData(snapshot, item))
|
|
138
|
-
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);
|
|
139
160
|
}
|
|
140
161
|
const preset = activePreset(agent);
|
|
141
162
|
if (preset) {
|
|
142
163
|
const saved = stamps.get(String(agent.id));
|
|
143
164
|
if (saved && !sameRevision(saved, preset))
|
|
144
|
-
throw new PhoneSessionError('preset_changed', '
|
|
165
|
+
throw new PhoneSessionError('preset_changed', 'The resumed session’s preset version differs. Run /teamwork new <presetId>.');
|
|
145
166
|
if (preset.pluginDependencies?.length)
|
|
146
167
|
await checkPlugins(preset);
|
|
147
168
|
const missing = requirements(agent, preset).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
|
|
148
169
|
if (missing.length)
|
|
149
|
-
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.`);
|
|
150
171
|
}
|
|
151
172
|
};
|
|
152
173
|
const actions = new TaskActions(agent => readiness(agent, true), agent => {
|
|
@@ -160,10 +181,39 @@ export async function apply(ctx, config) {
|
|
|
160
181
|
let phones = [];
|
|
161
182
|
// A paired phone's calls, replayed against this DSH's own web server through the allow-list; set where DSH serves web.
|
|
162
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();
|
|
163
212
|
const bridge = new Bridge({
|
|
164
213
|
launchUrl: () => launchUrl?.(),
|
|
165
|
-
|
|
166
|
-
|
|
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 ?? ''),
|
|
167
217
|
session: {
|
|
168
218
|
async configuration(sessionId) {
|
|
169
219
|
const agent = sessionAgent(sessionId);
|
|
@@ -218,26 +268,63 @@ export async function apply(ctx, config) {
|
|
|
218
268
|
},
|
|
219
269
|
});
|
|
220
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());
|
|
221
288
|
const security = new PhoneSecurity({
|
|
222
|
-
keys:
|
|
289
|
+
keys: phoneKeys,
|
|
223
290
|
scope: () => {
|
|
224
291
|
const revision = client.sessionRevision();
|
|
225
292
|
if (!keyScope || keyScope.revision !== revision) {
|
|
226
|
-
|
|
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}`);
|
|
227
296
|
keyScope = { revision, value };
|
|
228
297
|
void value.catch(() => { if (keyScope?.value === value)
|
|
229
298
|
keyScope = undefined; });
|
|
230
299
|
}
|
|
231
300
|
return keyScope.value;
|
|
232
301
|
},
|
|
233
|
-
send: frame => relay.send(frame), forward: frame => bridge.handle(frame),
|
|
302
|
+
send: frame => relay.send(frame), forward: frame => { audit(frame, 'in'); bridge.handle(frame); },
|
|
234
303
|
confirm: async (id) => { await relay.request({ t: 'decide', pairingId: id, accept: true }); },
|
|
235
304
|
changed: () => { },
|
|
236
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
|
+
},
|
|
237
322
|
});
|
|
238
323
|
const relay = new RelayLink({
|
|
239
324
|
endpoint: () => client.endpoint,
|
|
240
|
-
token
|
|
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.
|
|
327
|
+
token: () => !config.tokenFile && client.authenticated() ? client.platformCredential() : undefined,
|
|
241
328
|
clientIdPath: relayClientIdPath(config.cachePath),
|
|
242
329
|
onStatus: (status) => {
|
|
243
330
|
ctx.logger.debug('relay: %s', status);
|
|
@@ -249,24 +336,46 @@ export async function apply(ctx, config) {
|
|
|
249
336
|
bridge.dropAll();
|
|
250
337
|
}
|
|
251
338
|
},
|
|
252
|
-
onEvent: () =>
|
|
339
|
+
onEvent: (event) => {
|
|
340
|
+
if (event.t === 'members')
|
|
341
|
+
void sharedList(event.members);
|
|
342
|
+
else
|
|
343
|
+
void readPhones();
|
|
344
|
+
},
|
|
253
345
|
onForward: (frame) => void security.handle(frame),
|
|
254
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
|
+
};
|
|
255
358
|
const readPhones = async () => {
|
|
256
359
|
try {
|
|
257
|
-
|
|
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));
|
|
258
367
|
}
|
|
259
368
|
catch (error) {
|
|
260
|
-
ctx.logger.warn('
|
|
369
|
+
ctx.logger.warn('Could not read the paired phones: %s', error.message);
|
|
261
370
|
}
|
|
262
371
|
};
|
|
263
372
|
const phoneError = (error) => {
|
|
264
373
|
if (error instanceof RelayError && error.code === 'not_found')
|
|
265
|
-
throw new Error('
|
|
266
|
-
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'));
|
|
267
376
|
};
|
|
268
377
|
ctx.effect(() => () => relay.stop());
|
|
269
|
-
// 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,
|
|
270
379
|
// tell the relay which session, and hand on to the answerers untouched. Prepended, so it is told even when one claims the request.
|
|
271
380
|
const reportWaiting = (kind) => function (request, next) {
|
|
272
381
|
const agent = request?.agent ?? this;
|
|
@@ -281,7 +390,80 @@ export async function apply(ctx, config) {
|
|
|
281
390
|
let callback;
|
|
282
391
|
const stopCallback = () => { callback?.close(); callback = undefined; };
|
|
283
392
|
ctx.effect(() => () => stopCallback());
|
|
284
|
-
const
|
|
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
|
+
};
|
|
466
|
+
const authorize = async (code) => { hostManaged(); pendingInstalls.clear(); try {
|
|
285
467
|
await client.completeLogin(code);
|
|
286
468
|
}
|
|
287
469
|
finally {
|
|
@@ -291,15 +473,18 @@ export async function apply(ctx, config) {
|
|
|
291
473
|
await configSync.sync(); };
|
|
292
474
|
/** The sign-in page's address, and whether the code comes back by itself; without a listener it is pasted. */
|
|
293
475
|
const beginLogin = async () => {
|
|
476
|
+
hostManaged();
|
|
294
477
|
stopCallback();
|
|
295
|
-
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; });
|
|
296
479
|
return { url: client.beginLogin(callback?.uri), automatic: callback !== undefined };
|
|
297
480
|
};
|
|
298
481
|
const restore = async () => { await client.restore(); await overlay.apply(client.current()); relay.refresh(); };
|
|
299
|
-
const logout = async () => { pendingInstalls.clear(); stopCallback(); try {
|
|
482
|
+
const logout = async () => { hostManaged(); pendingInstalls.clear(); stopCallback(); try {
|
|
300
483
|
await client.logout();
|
|
484
|
+
await pins.reset();
|
|
301
485
|
}
|
|
302
486
|
finally {
|
|
487
|
+
setLocale(null);
|
|
303
488
|
await overlay.apply();
|
|
304
489
|
relay.refresh();
|
|
305
490
|
} };
|
|
@@ -343,9 +528,12 @@ export async function apply(ctx, config) {
|
|
|
343
528
|
const snapshot = client.current();
|
|
344
529
|
const item = findConfig(snapshot, id), team = teamOf(snapshot, id);
|
|
345
530
|
if (!item || !team || item.kind === 'plugin')
|
|
346
|
-
throw new Error('
|
|
531
|
+
throw new Error(say('use.pick'));
|
|
347
532
|
if (!inheritsModel(item) && !modelData(snapshot, item))
|
|
348
|
-
throw new Error('
|
|
533
|
+
throw new Error(say('use.modelGone'));
|
|
534
|
+
const limit = modelLimitProblem(snapshot, item);
|
|
535
|
+
if (limit)
|
|
536
|
+
throw new Error(limit);
|
|
349
537
|
if (item.kind === 'preset') {
|
|
350
538
|
assertBlank(ctx.agents.turnBoundaryOf(agent.session));
|
|
351
539
|
if (item.data.pluginDependencies?.length)
|
|
@@ -353,7 +541,7 @@ export async function apply(ctx, config) {
|
|
|
353
541
|
const candidate = { requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [] };
|
|
354
542
|
const unavailable = requirements(agent, candidate).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
|
|
355
543
|
if (unavailable.length)
|
|
356
|
-
throw new Error(
|
|
544
|
+
throw new Error(say('use.missingTools', { tools: unavailable.map(t => t.name).join(', ') }));
|
|
357
545
|
await ctx.agentPresets.select(agent, `team:${team.teamId}:${item.id}`);
|
|
358
546
|
const active = activePreset(agent);
|
|
359
547
|
if (active && !sameRevision(stamps.get(String(agent.id)), active))
|
|
@@ -361,7 +549,7 @@ export async function apply(ctx, config) {
|
|
|
361
549
|
}
|
|
362
550
|
if (!inheritsModel(item))
|
|
363
551
|
agent.model.select({ provider: platformProvider, model: item.id });
|
|
364
|
-
return { preset: item.kind === 'preset', text:
|
|
552
|
+
return { preset: item.kind === 'preset', text: say('use.done', { name: item.name }) };
|
|
365
553
|
};
|
|
366
554
|
/** Installs a pinned plugin disabled, enables it only when it adds configuration and overrides nothing. Callers confirm first. */
|
|
367
555
|
const installPlugin = async (item, agent) => {
|
|
@@ -369,20 +557,20 @@ export async function apply(ctx, config) {
|
|
|
369
557
|
const epoch = client.sessionRevision(), signature = JSON.stringify(item);
|
|
370
558
|
const manager = ctx.get('pluginManager');
|
|
371
559
|
if (!manager)
|
|
372
|
-
throw new Error('
|
|
560
|
+
throw new Error(say('install.noManager'));
|
|
373
561
|
const existing = (await manager.listBundles()).find(bundle => bundle.name === item.data.package);
|
|
374
562
|
if (existing && (existing.installed || existing.enabled || existing.availability === 'installation'))
|
|
375
|
-
throw new Error('
|
|
563
|
+
throw new Error(say('install.exists'));
|
|
376
564
|
const teamId = teamOf(client.current(), item.id)?.teamId;
|
|
377
565
|
const target = item.data.artifactId ? await client.downloadArtifact(teamId, item.data.artifactId, item.data.sha256) : spec;
|
|
378
566
|
if (epoch !== client.sessionRevision() || JSON.stringify(pinnedPlugin(client.current(), item.id, item.data.version)) !== signature)
|
|
379
|
-
throw new Error('
|
|
567
|
+
throw new Error(say('install.changed'));
|
|
380
568
|
const installed = await manager.installBundle(target, { saveExact: true, enabled: false });
|
|
381
569
|
if (installed.error || ['failed', 'cancelled', 'overridden'].includes(installed.application))
|
|
382
|
-
throw new Error(
|
|
570
|
+
throw new Error(say('install.incomplete', { reason: installed.error?.code ?? installed.application }));
|
|
383
571
|
const bundle = (await manager.listBundles()).find(bundle => bundle.name === item.data.package);
|
|
384
572
|
if (!bundle || bundle.error || bundle.version !== item.data.version || bundle.overrides.length || bundle.rows.some(row => row.entryId !== undefined)) {
|
|
385
|
-
throw new Error('
|
|
573
|
+
throw new Error(say('install.notEnabled'));
|
|
386
574
|
}
|
|
387
575
|
const result = await manager.setBundleEnabled(item.data.package, true);
|
|
388
576
|
if (result.error || ['failed', 'cancelled', 'overridden'].includes(result.application))
|
|
@@ -392,14 +580,15 @@ export async function apply(ctx, config) {
|
|
|
392
580
|
const refreshed = (await plugins()).find(p => p.id === item.id);
|
|
393
581
|
const currentPreset = agent && activePreset(agent);
|
|
394
582
|
const missingTools = agent && currentPreset ? requirements(agent, currentPreset).filter(t => t.required && ['missing', 'unknown'].includes(t.state)) : [];
|
|
395
|
-
const toolSummary = currentPreset ?
|
|
396
|
-
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');
|
|
397
585
|
};
|
|
398
586
|
const sessionAgent = (sessionId) => sessionId ? ctx.agents.get(sessionId) : undefined;
|
|
399
587
|
const panel = {
|
|
400
|
-
|
|
401
|
-
profile
|
|
402
|
-
|
|
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; },
|
|
403
592
|
async state(sessionId) {
|
|
404
593
|
const status = configSync.status(), snapshot = client.current(), agent = sessionAgent(sessionId);
|
|
405
594
|
// Inventory scans read the whole host. Share one within this response, never across requests.
|
|
@@ -414,14 +603,17 @@ export async function apply(ctx, config) {
|
|
|
414
603
|
const candidate = { requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [] };
|
|
415
604
|
presets.push({
|
|
416
605
|
id: item.id, teamId: team.teamId, teamName: team.teamName, name: item.name, version: item.version, description: item.data.description ?? '',
|
|
417
|
-
model: item.data.inheritModel ?
|
|
418
|
-
|
|
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),
|
|
419
610
|
tools: agent ? requirements(agent, candidate) : toolReport(candidate, () => 'unknown'),
|
|
420
611
|
plugins: item.data.pluginDependencies?.length ? await plugins({ teamId: team.teamId, pluginDependencies: item.data.pluginDependencies }, readInventory) : [],
|
|
421
612
|
});
|
|
422
613
|
}
|
|
423
614
|
const selection = agent?.model.current(), active = agent && activePreset(agent), boundary = agent && ctx.agents.turnBoundaryOf(agent.session);
|
|
424
615
|
return {
|
|
616
|
+
locale: panelLocale(),
|
|
425
617
|
authRevision: client.sessionRevision(),
|
|
426
618
|
authenticated: status.authenticated,
|
|
427
619
|
teams: (snapshot?.teams ?? []).map(team => ({ id: team.teamId, name: team.teamName, role: team.role, consoleUrl: `${client.endpoint}/teams/${team.teamId}` })),
|
|
@@ -430,15 +622,16 @@ export async function apply(ctx, config) {
|
|
|
430
622
|
sync: { auto: status.autoSync, running: status.syncing, lastSuccess: status.lastSuccess, lastError: status.lastError },
|
|
431
623
|
relay: relay.status,
|
|
432
624
|
phones: await Promise.all(phones.map(async (phone) => ({ ...phone, ...await security.details(phone.id) }))),
|
|
625
|
+
shared: await sharedView(),
|
|
433
626
|
session: agent ? {
|
|
434
627
|
id: String(agent.id),
|
|
435
628
|
model: selection ? { provider: selection.provider, model: selection.model, team: selection.provider === platformProvider } : null,
|
|
436
629
|
preset: active ? { id: active.id, name: active.name, version: active.version } : null,
|
|
437
630
|
started: boundary.openTurnStartSeq !== null || boundary.lastTurn > 0,
|
|
438
631
|
} : null,
|
|
439
|
-
presets: presets.sort((a, b) => Number(
|
|
632
|
+
presets: presets.sort((a, b) => Number(b.assistant) - Number(a.assistant)),
|
|
440
633
|
models: (snapshot?.teams ?? []).flatMap(team => team.configs.flatMap(c => c.kind === 'model'
|
|
441
|
-
? [{ id: c.id, teamId: team.teamId, teamName: team.teamName, name: c.name, version: c.version, upstream: `${c.data.provider}/${c.data.model}
|
|
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) }] : [])),
|
|
442
635
|
plugins: (await plugins(undefined, readInventory)).map(plugin => {
|
|
443
636
|
const team = teamOf(snapshot, plugin.id);
|
|
444
637
|
return { ...plugin, teamId: team?.teamId, teamName: team?.teamName };
|
|
@@ -450,6 +643,7 @@ export async function apply(ctx, config) {
|
|
|
450
643
|
sync: () => configSync.sync(),
|
|
451
644
|
logout,
|
|
452
645
|
async setServer(server) {
|
|
646
|
+
hostManaged();
|
|
453
647
|
const next = server === null ? serverAddress(config.apiEndpoint) : serverAddress(server);
|
|
454
648
|
pendingInstalls.clear();
|
|
455
649
|
try {
|
|
@@ -457,6 +651,7 @@ export async function apply(ctx, config) {
|
|
|
457
651
|
await serverChoice.write(next === serverAddress(config.apiEndpoint) ? undefined : next);
|
|
458
652
|
}
|
|
459
653
|
finally {
|
|
654
|
+
setLocale(null);
|
|
460
655
|
await overlay.apply(client.current());
|
|
461
656
|
relay.refresh();
|
|
462
657
|
}
|
|
@@ -482,26 +677,31 @@ export async function apply(ctx, config) {
|
|
|
482
677
|
await relay.request({ t: 'revoke', pairingId: id }).catch(phoneError);
|
|
483
678
|
await readPhones();
|
|
484
679
|
},
|
|
680
|
+
shareEnable,
|
|
681
|
+
shareDisable,
|
|
682
|
+
shareAuditKey: async (key) => ({ fingerprint: await shareAuditKey(key) }),
|
|
683
|
+
shareInvite,
|
|
684
|
+
shareUnlock,
|
|
485
685
|
async use(sessionId, id) {
|
|
486
686
|
const agent = sessionAgent(sessionId);
|
|
487
687
|
if (!agent)
|
|
488
|
-
throw new Error('
|
|
688
|
+
throw new Error(say('use.notLoaded'));
|
|
489
689
|
return (await useConfig(agent, id)).text;
|
|
490
690
|
},
|
|
491
691
|
async install(id, version) {
|
|
492
692
|
const item = pinnedPlugin(client.current(), id, version);
|
|
493
693
|
if (!item || item.kind !== 'plugin')
|
|
494
|
-
throw new Error('
|
|
694
|
+
throw new Error(say('install.pick'));
|
|
495
695
|
// The member confirmed this exact version; a sync since then may have changed the pin.
|
|
496
696
|
if (item.data.version !== version)
|
|
497
|
-
throw new Error('
|
|
697
|
+
throw new Error(say('install.pinChanged'));
|
|
498
698
|
return installPlugin(item);
|
|
499
699
|
},
|
|
500
700
|
};
|
|
501
701
|
// The panel's routes exist only where a browser reaches the host (DSH web and desktop), like the panel itself.
|
|
502
702
|
ctx.inject(['connection'], (scoped) => {
|
|
503
703
|
const { connection } = scoped;
|
|
504
|
-
for (const route of panelRoutes(panel))
|
|
704
|
+
for (const route of panelRoutes(panel, { say, speak: answer => speaking(panelLocale(), answer) }))
|
|
505
705
|
scoped.effect(() => { const dispose = connection.fetch.register(route); return () => { void dispose(); }; });
|
|
506
706
|
});
|
|
507
707
|
ctx.inject(['connection', 'webServer'], (scoped) => {
|
|
@@ -513,119 +713,159 @@ export async function apply(ctx, config) {
|
|
|
513
713
|
});
|
|
514
714
|
ctx.inject(['commands'], (child) => {
|
|
515
715
|
child.effect(() => child.commands.register({
|
|
516
|
-
name: 'teamwork', description: '
|
|
517
|
-
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' },
|
|
518
718
|
handler: async ({ agent, rawInput }) => {
|
|
519
719
|
const [action, requestedId, confirmation] = rawInput.trim().split(/\s+/);
|
|
520
720
|
const [id, pinVersion] = requestedId?.split('@') ?? [];
|
|
521
721
|
try {
|
|
522
722
|
if (action === 'session') {
|
|
523
|
-
let ready = '
|
|
723
|
+
let ready = 'Local checks passed; team access is verified again before continuing.';
|
|
524
724
|
try {
|
|
525
725
|
await readiness(agent, id === 'check');
|
|
526
726
|
if (id === 'check')
|
|
527
|
-
ready = '
|
|
727
|
+
ready = 'Checks passed; the server still verifies access on the real request.';
|
|
528
728
|
}
|
|
529
729
|
catch (error) {
|
|
530
730
|
ready = error.message;
|
|
531
731
|
}
|
|
532
732
|
const task = taskState.stateOf(agent.session), preset = activePreset(agent), selection = agent.model.current();
|
|
533
|
-
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') };
|
|
534
734
|
}
|
|
535
735
|
if (action === 'cancel') {
|
|
536
736
|
actions.cancel(agent);
|
|
537
|
-
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.' };
|
|
538
738
|
}
|
|
539
739
|
if (action === 'continue') {
|
|
540
740
|
await actions.submit(agent, rawInput.trim().slice('continue'.length).trim());
|
|
541
|
-
return { kind: 'success', text: '
|
|
741
|
+
return { kind: 'success', text: 'The follow-up was handed to DSH; run /teamwork session to see its status.' };
|
|
542
742
|
}
|
|
543
743
|
if (action === 'retry') {
|
|
544
744
|
if (id !== 'confirm') {
|
|
545
745
|
actions.review(agent, taskState.stateOf(agent.session).outcome);
|
|
546
|
-
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).' };
|
|
547
747
|
}
|
|
548
748
|
await actions.submit(agent, retryInstruction, true);
|
|
549
|
-
return { kind: 'success', text: '
|
|
749
|
+
return { kind: 'success', text: 'Recovery instruction sent; no original tool call was replayed.' };
|
|
550
750
|
}
|
|
551
751
|
if (action === 'login') {
|
|
552
752
|
const { url, automatic } = await beginLogin();
|
|
553
753
|
return { kind: 'success', text: automatic
|
|
554
|
-
?
|
|
555
|
-
:
|
|
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>).` };
|
|
556
756
|
}
|
|
557
757
|
if (action === 'authorize') {
|
|
558
758
|
await authorize(id ?? '');
|
|
559
|
-
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.' };
|
|
560
790
|
}
|
|
561
791
|
if (action === 'sync') {
|
|
562
792
|
await configSync.sync();
|
|
563
|
-
|
|
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.' };
|
|
564
801
|
}
|
|
565
802
|
if (action === 'logout') {
|
|
566
803
|
await logout();
|
|
567
|
-
return { kind: 'success', text: '
|
|
804
|
+
return { kind: 'success', text: 'Signed out, and the team configuration removed.' };
|
|
568
805
|
}
|
|
569
806
|
if (action === 'status') {
|
|
570
807
|
const status = configSync.status();
|
|
571
|
-
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') };
|
|
572
809
|
}
|
|
573
810
|
const snapshot = client.current();
|
|
574
811
|
const item = id ? action === 'install' && pinVersion ? pinnedPlugin(snapshot, id, pinVersion) : findConfig(snapshot, id) : undefined, team = id ? teamOf(snapshot, id) : undefined;
|
|
575
812
|
if (action === 'tools') {
|
|
576
813
|
const tools = child.get('tools');
|
|
577
814
|
if (!tools)
|
|
578
|
-
throw new Error('
|
|
815
|
+
throw new Error('The host offers no tool check service');
|
|
579
816
|
const rows = tools.definitions(agent).map(tool => {
|
|
580
|
-
const declared = (snapshot?.teams ?? []).flatMap(t => t.configs.filter(c => c.kind === 'plugin' && c.data.providesTools?.includes(tool.name)).map(c => `${c.name}
|
|
581
|
-
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'}`;
|
|
582
819
|
});
|
|
583
|
-
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') };
|
|
584
821
|
}
|
|
585
822
|
if (action === 'plugins') {
|
|
586
823
|
if (id && item?.kind !== 'preset')
|
|
587
|
-
throw new Error('
|
|
824
|
+
throw new Error('Choose a team preset ID');
|
|
588
825
|
const preset = item?.kind === 'preset' ? { teamId: team.teamId, pluginDependencies: item.data.pluginDependencies } : undefined;
|
|
589
|
-
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.' };
|
|
590
827
|
}
|
|
591
828
|
if (action === 'info') {
|
|
592
829
|
if (!id) {
|
|
593
830
|
const active = activePreset(agent);
|
|
594
|
-
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.' };
|
|
595
832
|
}
|
|
596
833
|
if (!item || item.kind !== 'preset')
|
|
597
|
-
throw new Error('
|
|
834
|
+
throw new Error('Choose a team preset ID');
|
|
598
835
|
const info = { teamId: team.teamId, id: item.id, name: item.name, version: item.version, description: '', instructions: '', outputDescription: '', requiredTools: [], optionalTools: [], ...item.data };
|
|
599
|
-
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.' };
|
|
600
837
|
}
|
|
601
838
|
if (action === 'new') {
|
|
602
839
|
if (!item || item.kind !== 'preset')
|
|
603
|
-
throw new Error('
|
|
840
|
+
throw new Error('Choose a team preset ID');
|
|
604
841
|
if (!inheritsModel(item) && !modelData(snapshot, item))
|
|
605
|
-
throw new Error('
|
|
842
|
+
throw new Error(say('use.modelGone'));
|
|
843
|
+
const limit = modelLimitProblem(snapshot, item);
|
|
844
|
+
if (limit)
|
|
845
|
+
throw new Error(limit);
|
|
606
846
|
const sessionId = `team-${crypto.randomUUID()}`;
|
|
607
847
|
const agentPreset = `team:${team.teamId}:${item.id}`;
|
|
608
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() } : {}) });
|
|
609
|
-
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.` };
|
|
610
850
|
}
|
|
611
851
|
if (action === 'use') {
|
|
612
852
|
const chosen = await useConfig(agent, id ?? '');
|
|
613
|
-
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.' : '') };
|
|
614
854
|
}
|
|
615
855
|
if (action === 'install') {
|
|
616
856
|
if (!item || item.kind !== 'plugin')
|
|
617
|
-
throw new Error('
|
|
857
|
+
throw new Error(say('install.pick'));
|
|
618
858
|
const spec = `${item.data.package}@${item.data.version}`;
|
|
619
859
|
if (confirmation !== 'confirm') {
|
|
620
860
|
pendingInstalls.set(String(agent.id), `${client.sessionRevision()}:${JSON.stringify(item)}`);
|
|
621
|
-
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` };
|
|
622
862
|
}
|
|
623
863
|
if (pendingInstalls.get(String(agent.id)) !== `${client.sessionRevision()}:${JSON.stringify(item)}`)
|
|
624
|
-
throw new Error('
|
|
864
|
+
throw new Error('Read the install note for the current plugin version first, then confirm the install');
|
|
625
865
|
pendingInstalls.delete(String(agent.id));
|
|
626
|
-
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.' };
|
|
627
867
|
}
|
|
628
|
-
return { kind: 'success', text: snapshot ? snapshot.teams.flatMap(t => t.configs.map(c => `${c.id} · ${c.kind} · ${c.name} · v${c.version} · ${t.teamName}`)).join('\n') || '
|
|
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.' };
|
|
629
869
|
}
|
|
630
870
|
catch (error) {
|
|
631
871
|
return { kind: 'error', text: error.message };
|
|
@@ -637,7 +877,26 @@ export async function apply(ctx, config) {
|
|
|
637
877
|
await restore();
|
|
638
878
|
}
|
|
639
879
|
catch {
|
|
640
|
-
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);
|
|
889
|
+
}
|
|
890
|
+
if (config.tokenFile) {
|
|
891
|
+
const watcher = watchTokenFile(config.tokenFile, async (token) => {
|
|
892
|
+
pendingInstalls.clear();
|
|
893
|
+
await client.useToken(token);
|
|
894
|
+
await overlay.apply(client.current());
|
|
895
|
+
if (token && config.autoSync !== false)
|
|
896
|
+
await configSync.sync().catch(() => { });
|
|
897
|
+
}, error => ctx.logger.warn('Could not read the Teamwork token file: %s', error.message));
|
|
898
|
+
ctx.effect(() => () => watcher.stop());
|
|
899
|
+
await watcher.ready;
|
|
641
900
|
}
|
|
642
901
|
configSync.start();
|
|
643
902
|
}
|