@kadaliao/dsh-bots 0.0.0-stage → 0.3.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/index.js ADDED
@@ -0,0 +1,1286 @@
1
+ /**
2
+ * Host half of the bots bundle: Grok-style bots inside DeepSeek Harness.
3
+ *
4
+ * A bot is a named persona with its own conversation (a DSH Session), avatar,
5
+ * skills, tool access, apps (MCP servers, e.g. open-computer-use) and scheduled
6
+ * tasks. Bots message each other: `bot_send_message` drops the text into the
7
+ * other bot's inbox, which wakes it; the reply travels back the same way. One
8
+ * bot is the dispatcher that delegates work and schedules tasks.
9
+ *
10
+ * Everything a bot is made of is applied to its Agent's own scope when that
11
+ * Agent comes up (and re-applied when the bot changes): a persona prompt
12
+ * section, runtime skills, a tool restriction and agent-scoped MCP clients.
13
+ * Nothing touches other conversations, except the bot tools themselves, which
14
+ * every conversation gets so the user can manage bots from anywhere.
15
+ *
16
+ * @module @kadaliao/dsh-bots
17
+ */
18
+
19
+ import { createReadStream, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
+ import { homedir } from 'node:os';
21
+ import { join } from 'node:path';
22
+ import { randomUUID } from 'node:crypto';
23
+
24
+ import { createStore, initialsOf, slugify, SKILL_RE, PALETTE } from './lib/store.mjs';
25
+ import { catalog as appCatalog, CATEGORIES, mcpConfigFor } from './lib/apps.mjs';
26
+ import { ABILITIES } from './lib/abilities.mjs';
27
+ import { SKILL_SOURCES, importGithubSkill, importUrlSkill, listGithubSkills, parseGithub } from './lib/skills.mjs';
28
+ import { TEAMS, teamTiming, teamView } from './lib/teams.mjs';
29
+ import { maskedApp, scanExternalMcp } from './lib/mcp-import.mjs';
30
+ import { createUnfurler } from './lib/unfurl.mjs';
31
+ import { describeTiming, dmBody, dmHeader, personaText, textOf, timingFrom, timingOfEntry } from './lib/prompt.mjs';
32
+
33
+ /**
34
+ * Import one Harness package: by bare name when this directory resolves it,
35
+ * else from the running Harness's own module tree (a linked working copy sits
36
+ * outside it), else undefined.
37
+ */
38
+ async function harnessModule(name) {
39
+ try {
40
+ return await import(name);
41
+ } catch {
42
+ // Not reachable from here; ask the Harness entry below.
43
+ }
44
+ try {
45
+ const { createRequire } = await import('node:module');
46
+ const { pathToFileURL } = await import('node:url');
47
+ for (const entry of [process.argv[1], ...process.argv.slice(2).filter((a) => a.endsWith('.js'))]) {
48
+ if (!entry) continue;
49
+ try {
50
+ return await import(pathToFileURL(createRequire(entry).resolve(name)).href);
51
+ } catch {
52
+ // The next candidate.
53
+ }
54
+ }
55
+ } catch {
56
+ // No module system to ask.
57
+ }
58
+ return undefined;
59
+ }
60
+
61
+ const toolsModule = await harnessModule('@deepseek-ai/dsh-tools');
62
+ const llmModule = await harnessModule('@deepseek-ai/dsh-llm');
63
+ /** The MCP client plugin, mounted per bot for its apps; absent outside a Harness. */
64
+ const mcpClient = (await harnessModule('@deepseek-ai/dsh-mcp-client')) ?? null;
65
+ const scopeOf = (await harnessModule('@deepseek-ai/dsh-scope'))?.scopeOf ?? (() => undefined);
66
+ // The registry wants the compiled definition; outside a Harness the raw one stands in.
67
+ const defineTool = toolsModule?.defineTool ?? ((definition) => definition);
68
+ const createUserMessage = llmModule?.createUserMessage ?? ((input) => Object.freeze({ ...structuredClone(input), role: 'user', id: randomUUID() }));
69
+
70
+ export const inject = ['tools'];
71
+ export const name = 'bots';
72
+
73
+ const R = '/__dsh_bots';
74
+ const OCU_PATHS = [join(homedir(), '.local', 'share', 'ocu', 'ocu'), join(homedir(), '.local', 'bin', 'ocu')];
75
+ /** DMs one pair of bots may exchange within the window before the next is refused. */
76
+ const PAIR_LIMIT = 16;
77
+ const PAIR_WINDOW_MS = 10 * 60_000;
78
+ const PERSONA_SECTION = 'bots:persona';
79
+ const PERSONA_ORDER = 50;
80
+ const MAX_AVATAR = 2 * 1024 * 1024;
81
+ /** Tries one avatar gets when the image service fails in a way that may pass. */
82
+ const AVATAR_ATTEMPTS = 3;
83
+ /** Errors from a gateway or the network rather than from the request itself. */
84
+ export const TRANSIENT = /\b(408|409|429|500|502|503|504|520|522|524)\b|connection (lost|reset|closed)|ECONNRESET|ETIMEDOUT|EPIPE|socket hang up|fetch failed|could not reach|did not answer within|overloaded|temporarily/i;
85
+
86
+ export const TOOL_NAMES = ['bot_list', 'bot_create', 'bot_update', 'bot_delete', 'bot_send_message', 'bot_schedule'];
87
+
88
+ function homeDir() {
89
+ return process.env.DSH_HOME && process.env.DSH_HOME !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh');
90
+ }
91
+
92
+ export function ocuPath() {
93
+ return OCU_PATHS.find((p) => existsSync(p)) ?? '';
94
+ }
95
+
96
+ /** The app catalog the Apps tab offers, with the open-computer-use path in force. */
97
+ export function templates() {
98
+ return appCatalog(ocuPath());
99
+ }
100
+
101
+ /** The mcp-client row of one app of `bot`. Throws APP_INCOMPLETE when a required field is empty. */
102
+ export function mcpConfigOf(app, bot) {
103
+ return mcpConfigFor(app, templates(), { bot: bot?.handle ?? 'bot' });
104
+ }
105
+
106
+ const OCU_REPO = 'kadaliao/open-computer-use';
107
+
108
+ /**
109
+ * Install the latest open-computer-use release: download its macOS tarball,
110
+ * unpack it and run its own install.sh (→ ~/.local/share/ocu, ~/.local/bin/ocu).
111
+ * @returns {{version: string, path: string, log: string}}
112
+ */
113
+ export async function installOcu({ signal, fetchImpl = fetch } = {}) {
114
+ if (process.platform !== 'darwin') throw new Error('Open Computer Use runs on macOS only');
115
+ const { mkdtempSync } = await import('node:fs');
116
+ const { tmpdir } = await import('node:os');
117
+ const { execFile } = await import('node:child_process');
118
+ const run = (cmd, args, opts = {}) =>
119
+ new Promise((resolve, reject) =>
120
+ execFile(cmd, args, { timeout: 120_000, maxBuffer: 4 * 1024 * 1024, ...opts }, (error, stdout, stderr) =>
121
+ error ? reject(new Error(`${cmd} failed: ${String(stderr || error.message).trim().slice(0, 400)}`)) : resolve(String(stdout)),
122
+ ),
123
+ );
124
+ const res = await fetchImpl(`https://api.github.com/repos/${OCU_REPO}/releases/latest`, { headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-bots' }, signal });
125
+ if (!res.ok) throw new Error(`GitHub answered ${res.status} for the latest release`);
126
+ const release = await res.json();
127
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
128
+ const asset = (release.assets ?? []).find((a) => /macos/i.test(a.name) && a.name.includes(arch) && a.name.endsWith('.tar.gz'));
129
+ if (!asset) throw new Error(`release ${release.tag_name} has no macOS ${arch} build`);
130
+ const bin = await fetchImpl(asset.browser_download_url, { signal, redirect: 'follow' });
131
+ if (!bin.ok) throw new Error(`download failed (${bin.status})`);
132
+ const work = mkdtempSync(join(tmpdir(), 'dsh-bots-ocu-'));
133
+ try {
134
+ const tgz = join(work, asset.name);
135
+ writeFileSync(tgz, Buffer.from(await bin.arrayBuffer()));
136
+ await run('tar', ['xzf', tgz, '-C', work]);
137
+ const dirName = asset.name.replace(/\.tar\.gz$/, '');
138
+ const script = join(work, dirName, 'install.sh');
139
+ if (!existsSync(script)) throw new Error('the release has no install.sh');
140
+ const log = await run('/bin/sh', [script], { cwd: join(work, dirName) });
141
+ const path = ocuPath();
142
+ if (!path) throw new Error('install.sh finished but ~/.local/share/ocu/ocu is missing');
143
+ return { version: release.tag_name, path, log };
144
+ } finally {
145
+ rmSync(work, { recursive: true, force: true });
146
+ }
147
+ }
148
+
149
+ /** What the page and tool cards show of a bot. */
150
+ function face(bot) {
151
+ return bot ? { id: bot.id, name: bot.name, handle: bot.handle, avatar: bot.avatar, role: bot.role } : null;
152
+ }
153
+
154
+ const service = (ctx, name) => {
155
+ try {
156
+ return ctx.get(name);
157
+ } catch {
158
+ return undefined;
159
+ }
160
+ };
161
+
162
+ export function apply(ctx, config) {
163
+ const cfg = config && typeof config === 'object' ? config : {};
164
+ const dir = join(homeDir(), 'cache', 'bots');
165
+ const store = createStore(dir);
166
+ const workdir = typeof cfg.workdir === 'string' && cfg.workdir.trim() ? cfg.workdir.trim() : join(homeDir(), 'bots', 'workspace');
167
+ const zone = (() => {
168
+ try {
169
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
170
+ } catch {
171
+ return 'UTC';
172
+ }
173
+ })();
174
+
175
+ // --- seeding: a dispatcher on the very first run ---------------------------------
176
+ const seededFile = join(dir, 'seeded');
177
+ const zh = /^zh/i.test(String(cfg.language ?? '') || Intl.DateTimeFormat().resolvedOptions().locale || process.env.LANG || '');
178
+ if (store.list().length === 0 && !existsSync(seededFile)) {
179
+ try {
180
+ store.save({
181
+ name: 'Atlas',
182
+ handle: 'atlas',
183
+ role: 'primary',
184
+ avatar: { kind: 'initials', color: '#7c5cff' },
185
+ bio: zh ? '调度员:拆解需求,分派给合适的 bot,并安排定时任务。 / Dispatcher: plans, delegates, schedules.' : 'Dispatcher: plans the work, hands it to the right bot, and keeps the schedule. / 调度员:拆解、分派、排期。',
186
+ persona: zh
187
+ ? '你沉稳、有条理、说话简洁。你把模糊的需求变成清楚的计划,交给合适的专家 bot,跟进进度,最后用简短的总结向用户汇报。默认用用户使用的语言回答。'
188
+ : 'Calm, organised and brief. You turn vague requests into clear plans, delegate to specialists, follow up, and report back with a short summary. Answer in the language the user writes in.',
189
+ });
190
+ mkdirSync(dir, { recursive: true });
191
+ writeFileSync(seededFile, String(Date.now()));
192
+ } catch (error) {
193
+ ctx.logger?.warn?.(`bots: could not seed the dispatcher: ${error?.message ?? error}`);
194
+ }
195
+ }
196
+
197
+ // --- applying a bot to its Agent ----------------------------------------------------
198
+ /** sessionId → {agent, signature, disposers[]} */
199
+ const installed = new Map();
200
+
201
+ const signatureOf = (bot) => JSON.stringify({ s: bot.skills, a: bot.apps, t: bot.tools, h: bot.handle });
202
+
203
+ function uninstall(sessionId) {
204
+ const rec = installed.get(sessionId);
205
+ if (!rec) return;
206
+ installed.delete(sessionId);
207
+ for (const dispose of rec.disposers.reverse()) {
208
+ try {
209
+ const r = dispose();
210
+ if (r && typeof r.catch === 'function') r.catch(() => {});
211
+ } catch {
212
+ // Already gone with the Agent.
213
+ }
214
+ }
215
+ }
216
+
217
+ function install(agent, bot) {
218
+ const actx = agent.ctx;
219
+ const disposers = [];
220
+ const skillNames = {};
221
+ const skills = service(actx, 'skills');
222
+ let skillsInline = false;
223
+ const enabledSkills = bot.skills.filter((s) => s.enabled);
224
+ // A Harness skill is already in every conversation's catalog under its own name;
225
+ // the persona points the bot at it. Own and imported skills are registered here,
226
+ // for this conversation only, under a name prefixed with the bot's handle.
227
+ for (const s of enabledSkills) if (s.source === 'dsh') skillNames[s.id] = s.name;
228
+ const local = enabledSkills.filter((s) => s.source !== 'dsh');
229
+ if (local.length > 0) {
230
+ if (skills && typeof skills.register === 'function') {
231
+ for (const s of local) {
232
+ let n = slugify(s.name, 'skill');
233
+ if (!SKILL_RE.test(n)) n = `skill-${s.id.slice(-5)}`;
234
+ n = `${bot.handle}-${n}`.slice(0, 64).replace(/-+$/, '');
235
+ skillNames[s.id] = n;
236
+ try {
237
+ disposers.push(
238
+ skills.register({
239
+ name: n,
240
+ description: s.description || s.name,
241
+ content: s.content || s.description || s.name,
242
+ source: 'bots',
243
+ invocation: { modelInvocable: true, userInvocable: true },
244
+ ...(s.dir && existsSync(s.dir) ? { resourceBase: { kind: 'directory', path: s.dir } } : {}),
245
+ }),
246
+ );
247
+ } catch (error) {
248
+ ctx.logger?.warn?.(`bots: skill ${n} for @${bot.handle}: ${error?.message ?? error}`);
249
+ }
250
+ }
251
+ } else skillsInline = true;
252
+ }
253
+ const apps = bot.apps.filter((a) => a.enabled);
254
+ const appNames = [];
255
+ if (apps.length > 0 && mcpClient && typeof actx.plugin === 'function') {
256
+ for (const app of apps) {
257
+ try {
258
+ const fiber = actx.plugin(mcpClient, mcpConfigOf(app, bot));
259
+ appNames.push(app.serverName);
260
+ disposers.push(() => fiber?.dispose?.());
261
+ Promise.resolve(fiber).catch((error) => ctx.logger?.warn?.(`bots: app ${app.serverName} for @${bot.handle}: ${error?.message ?? error}`));
262
+ } catch (error) {
263
+ // An app missing a required key stays off for this run; the panel says what it needs.
264
+ ctx.logger?.warn?.(`bots: app ${app.serverName} for @${bot.handle}: ${error?.message ?? error}`);
265
+ }
266
+ }
267
+ }
268
+ const prompts = service(actx, 'systemPrompt');
269
+ if (prompts && typeof prompts.section === 'function') {
270
+ try {
271
+ disposers.push(
272
+ prompts.section({
273
+ name: PERSONA_SECTION,
274
+ order: PERSONA_ORDER,
275
+ interpolate: false,
276
+ // Read on every assembly: a renamed teammate or edited persona applies at once.
277
+ text: () => {
278
+ const now = store.get(bot.id);
279
+ return now ? personaText(now, store.list(), { skillsInline, skillNames, apps: appNames }) : '';
280
+ },
281
+ }),
282
+ );
283
+ } catch (error) {
284
+ ctx.logger?.warn?.(`bots: persona for @${bot.handle}: ${error?.message ?? error}`);
285
+ }
286
+ }
287
+ if (bot.tools.deny.length > 0) {
288
+ const tools = service(actx, 'tools');
289
+ try {
290
+ const view = ctx.tools?.view?.(scopeOf(actx));
291
+ const known = view?.restrictableNames instanceof Set ? view.restrictableNames : new Set((ctx.tools?.definitions?.() ?? []).map((d) => d.name));
292
+ const deny = bot.tools.deny.filter((n) => known.has(n) && n !== 'run_code');
293
+ if (deny.length > 0 && tools?.restrict) disposers.push(tools.restrict({ deny }));
294
+ } catch (error) {
295
+ ctx.logger?.warn?.(`bots: tool access for @${bot.handle}: ${error?.message ?? error}`);
296
+ }
297
+ }
298
+ installed.set(agent.session.id, { agent, signature: signatureOf(bot), disposers });
299
+ }
300
+
301
+ function reconcile(agent) {
302
+ const sessionId = agent?.session?.id;
303
+ if (!sessionId) return;
304
+ const bot = store.bySession(sessionId);
305
+ const rec = installed.get(sessionId);
306
+ if (!bot) {
307
+ if (rec) uninstall(sessionId);
308
+ return;
309
+ }
310
+ if (rec && rec.agent === agent && rec.signature === signatureOf(bot)) return;
311
+ if (rec) uninstall(sessionId);
312
+ install(agent, bot);
313
+ }
314
+
315
+ const agents = () => {
316
+ try {
317
+ return ctx.get('agents');
318
+ } catch {
319
+ return undefined;
320
+ }
321
+ };
322
+ ctx.inject?.(['agents'], (scope) => {
323
+ scope.on('agent/created', ({ agent }) => reconcile(agent));
324
+ scope.on('agent/disposed', (payload) => {
325
+ const id = payload?.agent?.session?.id ?? payload?.agent?.id;
326
+ if (id && installed.get(id)?.agent === payload?.agent) installed.delete(id);
327
+ });
328
+ for (const agent of scope.agents.list?.() ?? []) reconcile(agent);
329
+ });
330
+ ctx.effect(
331
+ () =>
332
+ store.onChange(() => {
333
+ const live = agents();
334
+ for (const bot of store.list()) {
335
+ const agent = bot.sessionId ? live?.get?.(bot.sessionId) : undefined;
336
+ if (agent) reconcile(agent);
337
+ }
338
+ for (const sessionId of [...installed.keys()]) if (!store.bySession(sessionId)) uninstall(sessionId);
339
+ }),
340
+ 'bots: re-apply changed bots',
341
+ );
342
+ ctx.effect(() => () => {
343
+ for (const id of [...installed.keys()]) uninstall(id);
344
+ }, 'bots: unwind bot scopes');
345
+
346
+ // --- sessions ---------------------------------------------------------------------
347
+ async function workspaceId() {
348
+ const reg = service(ctx, 'workspaceRegistry');
349
+ if (!reg?.create) return undefined;
350
+ mkdirSync(workdir, { recursive: true });
351
+ const ws = await reg.create(workdir, 'Bots');
352
+ return ws?.id;
353
+ }
354
+
355
+ /** The bot's home session, created on first need. Returns the session id. */
356
+ async function ensureSession(bot) {
357
+ const controller = service(ctx, 'sessionController');
358
+ if (!controller) throw new Error('bot conversations need the Web profile (no session controller here)');
359
+ const archived = service(ctx, 'workspaceRegistry')?.archivedSessionIds ?? [];
360
+ if (bot.sessionId && !archived.includes(bot.sessionId)) {
361
+ const found = await controller.resolveAgent(bot.sessionId).catch((error) => ({ error }));
362
+ if (found && !('error' in found)) return bot.sessionId;
363
+ }
364
+ const sessionId = `session-${randomUUID()}`;
365
+ // Mapped before the Agent exists, so its creation already finds the bot.
366
+ store.patch(bot.id, { sessionId });
367
+ const wsId = await workspaceId().catch(() => undefined);
368
+ try {
369
+ const created = await controller.create({ sessionId, ...(wsId ? { workspaceId: wsId } : { cwd: workdir }) });
370
+ if (created?.sessionId && created.sessionId !== sessionId) store.patch(bot.id, { sessionId: created.sessionId });
371
+ } catch (error) {
372
+ store.patch(bot.id, { sessionId: null });
373
+ throw error;
374
+ }
375
+ const id = store.get(bot.id).sessionId;
376
+ const agent = agents()?.get?.(id);
377
+ if (agent) {
378
+ reconcile(agent);
379
+ try {
380
+ service(ctx, 'sessionTitle')?.rename?.(agent.session, bot.name);
381
+ } catch {
382
+ // A title is cosmetic.
383
+ }
384
+ if (bot.model) {
385
+ try {
386
+ agent.model?.select?.({ provider: bot.model.provider, model: bot.model.model });
387
+ } catch {
388
+ // The default model stays.
389
+ }
390
+ }
391
+ }
392
+ return id;
393
+ }
394
+
395
+ async function agentOf(bot) {
396
+ const id = await ensureSession(bot);
397
+ const found = await service(ctx, 'sessionController').resolveAgent(id);
398
+ if ('error' in found) throw found.error;
399
+ return found.agent;
400
+ }
401
+
402
+ async function flush(agent) {
403
+ try {
404
+ await ctx.get('sessions')?.flush?.(agent.session);
405
+ } catch {
406
+ // Ordinary persistence follows.
407
+ }
408
+ }
409
+
410
+ // --- delivering messages ---------------------------------------------------------------
411
+ const pairs = new Map();
412
+ function admitPair(a, b) {
413
+ const key = [a, b].sort().join('|');
414
+ const now = Date.now();
415
+ const times = (pairs.get(key) ?? []).filter((t) => now - t < PAIR_WINDOW_MS);
416
+ if (times.length >= PAIR_LIMIT) return false;
417
+ times.push(now);
418
+ pairs.set(key, times);
419
+ return true;
420
+ }
421
+
422
+ /** A DM from `sender` (a bot, or null for the user) to `target`. */
423
+ async function deliver(sender, target, text, senderSessionId) {
424
+ const body = String(text ?? '').trim();
425
+ if (body === '') throw new Error('text must not be empty');
426
+ if (sender && sender.id === target.id) throw new Error('a bot cannot message itself');
427
+ if (sender && !admitPair(sender.id, target.id)) throw new Error(`@${sender.handle} and @${target.handle} exchanged ${PAIR_LIMIT} messages in the last 10 minutes; stop and report to the user instead of continuing.`);
428
+ const agent = await agentOf(target);
429
+ const message = createUserMessage({
430
+ content: [
431
+ { type: 'text', text: dmHeader(sender) },
432
+ { type: 'text', text: dmBody(body, sender) },
433
+ ],
434
+ source: senderSessionId ? { kind: 'agent-message', form: 'relay', senderSessionId } : { kind: 'user' },
435
+ });
436
+ agent.followup(message);
437
+ await flush(agent);
438
+ store.log({ from: sender ? sender.id : 'user', to: target.id, text: body, kind: 'dm' });
439
+ return agent.session.id;
440
+ }
441
+
442
+ /** The user writes to a bot from the panel: an ordinary user prompt in its conversation. */
443
+ async function userSend(target, text) {
444
+ const body = String(text ?? '').trim();
445
+ if (body === '') throw new Error('text must not be empty');
446
+ const agent = await agentOf(target);
447
+ agent.followup(createUserMessage({ content: [{ type: 'text', text: body }], source: { kind: 'user' } }));
448
+ await flush(agent);
449
+ return agent.session.id;
450
+ }
451
+
452
+ // The timeline: what the user typed to a bot, what the bot answered, scheduled runs.
453
+ const trigger = new Map();
454
+ /** Sessions whose current turn already sent a bot_send_message. */
455
+ const answered = new Set();
456
+ ctx.on('session/event', (session, event) => {
457
+ try {
458
+ const bot = store.bySession(session?.id);
459
+ if (!bot || !event) return;
460
+ if (event.type === 'user/message') {
461
+ let kind = event.data?.source?.kind;
462
+ // The Harness tells a session about task edits made elsewhere; that is not a delivery.
463
+ if (kind === 'schedule' && /^\[SCHEDULE CHANGE\]/.test(textOf(event.data.content))) kind = 'schedule-notice';
464
+ trigger.set(session.id, kind);
465
+ answered.delete(session.id);
466
+ if (kind === 'user') store.log({ from: 'user', to: bot.id, text: textOf(event.data.content), kind: 'user' });
467
+ else if (kind === 'schedule') store.log({ from: 'schedule', to: bot.id, text: textOf(event.data.content), kind: 'system' });
468
+ } else if (event.type === 'assistant/message') {
469
+ const content = event.data?.message?.content ?? [];
470
+ const calls = content.filter((b) => b?.type === 'tool-call');
471
+ if (calls.some((b) => (b.name ?? b.toolName) === 'bot_send_message')) answered.add(session.id);
472
+ if (calls.length > 0) return;
473
+ const text = textOf(content);
474
+ const why = trigger.get(session.id);
475
+ // Shown in the bot's chat: what it says to the user. Hidden: acknowledging a schedule notice,
476
+ // and the closing words of a turn that answered a bot by DM (they reach no one). The
477
+ // dispatcher reporting back after its teammates answered is a message to the user.
478
+ const hidden = why === 'schedule-notice' || (why === 'agent-message' && (bot.role !== 'primary' || answered.has(session.id)));
479
+ if (text && !hidden) store.log({ from: bot.id, to: 'user', text, kind: 'reply' });
480
+ }
481
+ } catch {
482
+ // The timeline must never disturb a conversation.
483
+ }
484
+ });
485
+
486
+ // --- schedules ------------------------------------------------------------------------
487
+ const schedule = () => {
488
+ const s = service(ctx, 'schedule');
489
+ if (!s) throw new Error('scheduled tasks are unavailable in this Harness');
490
+ return s;
491
+ };
492
+ const entryView = (e) => ({
493
+ id: e.id,
494
+ title: e.title,
495
+ prompt: e.prompt,
496
+ kind: e.kind,
497
+ scheduledAt: e.scheduledAt,
498
+ status: e.status,
499
+ timing: timingOfEntry(e),
500
+ describe: describeTiming(timingOfEntry(e)),
501
+ ...(e.executionActive ? { executionActive: true } : {}),
502
+ ...(e.lastDelivery ? { lastDelivery: e.lastDelivery } : {}),
503
+ sessionId: e.target?.kind === 'session' ? e.target.sessionId : null,
504
+ });
505
+ async function schedulesOf(bot) {
506
+ const all = await schedule().catalog();
507
+ const sessions = new Set(store.list().map((b) => b.sessionId).filter(Boolean));
508
+ return all
509
+ .filter((e) => e.target?.kind === 'session' && (bot ? e.target.sessionId === bot.sessionId : sessions.has(e.target.sessionId)))
510
+ .map((e) => ({ ...entryView(e), botId: store.bySession(e.target.sessionId)?.id ?? null }));
511
+ }
512
+ const checkEntry = (result) => {
513
+ if (result && typeof result === 'object' && 'code' in result && !('title' in result)) throw new Error(result.code === 'schedule_not_found' ? 'no such scheduled task' : String(result.code));
514
+ return result;
515
+ };
516
+ async function scheduleSave(bot, { id, title, prompt, timing }, actor) {
517
+ const t = String(title ?? '').trim().slice(0, 120);
518
+ const p = String(prompt ?? '').trim();
519
+ if (id) {
520
+ const patch = {};
521
+ if (t) patch.title = t;
522
+ if (p) patch.prompt = p;
523
+ if (timing) patch.timing = timing;
524
+ return entryView(checkEntry(await schedule().edit({ id, action: 'update', patch }, actor)));
525
+ }
526
+ if (!t || !p || !timing) throw new Error('a new task needs a title, a prompt and a timing');
527
+ const sessionId = await ensureSession(bot);
528
+ return entryView(await schedule().create({ title: t, prompt: p, timing, target: { kind: 'session', sessionId } }, actor));
529
+ }
530
+
531
+ // --- bot lifecycle helpers -----------------------------------------------------------
532
+ async function removeBot(bot) {
533
+ try {
534
+ for (const task of await schedulesOf(bot)) await schedule().edit({ id: task.id, action: 'delete' });
535
+ } catch {
536
+ // No schedule service or nothing to remove.
537
+ }
538
+ if (bot.sessionId) {
539
+ uninstall(bot.sessionId);
540
+ try {
541
+ service(ctx, 'workspaceRegistry')?.archiveSession?.(bot.sessionId);
542
+ } catch {
543
+ // The conversation stays where it is.
544
+ }
545
+ }
546
+ store.remove(bot.id);
547
+ if (bot.avatar.kind === 'image') for (const f of [bot.id, `${bot.id}.type`]) rmSync(join(dir, 'avatars', f), { force: true });
548
+ }
549
+
550
+ function botStatus(bot) {
551
+ const agent = bot.sessionId ? agents()?.get?.(bot.sessionId) : undefined;
552
+ return agent ? (agent.status === 'running' ? 'running' : 'idle') : 'offline';
553
+ }
554
+
555
+ function applyModel(bot) {
556
+ const agent = bot.sessionId ? agents()?.get?.(bot.sessionId) : undefined;
557
+ if (agent && bot.model) {
558
+ try {
559
+ agent.model?.select?.({ provider: bot.model.provider, model: bot.model.model });
560
+ } catch {
561
+ // Kept on its current model.
562
+ }
563
+ }
564
+ }
565
+
566
+ // --- AI avatars, through the images plugin's generate_image tool ---------------------
567
+ const imageTool = () => {
568
+ try {
569
+ return ctx.tools?.get?.('generate_image');
570
+ } catch {
571
+ return undefined;
572
+ }
573
+ };
574
+ function imageGenAvailable() {
575
+ return Boolean(imageTool());
576
+ }
577
+ /** The prompt an avatar is drawn from: who the bot is, as a flat, legible profile picture. */
578
+ function avatarPrompt(bot, extra) {
579
+ const who = [bot.name, bot.bio, bot.persona.split(/\n/)[0]].filter(Boolean).join(' — ').slice(0, 500);
580
+ return [
581
+ `A square profile avatar for an AI assistant character: ${who}.`,
582
+ extra ? `Style notes from the user: ${String(extra).slice(0, 400)}.` : 'Modern flat vector illustration, a friendly character or emblem centred, bold simple shapes, soft gradient background in one dominant colour, high contrast, no text, no letters, no watermark, no border.',
583
+ 'It must read clearly at 32×32 pixels.',
584
+ ].join(' ');
585
+ }
586
+ async function generateAvatar(bot, extra) {
587
+ const tool = imageTool();
588
+ if (!tool) throw new Error('the Images plugin (generate_image) is not installed or turned off');
589
+ const controller = new AbortController();
590
+ const timer = setTimeout(() => controller.abort(), 300_000);
591
+ let value;
592
+ try {
593
+ for (let attempt = 1; ; attempt += 1) {
594
+ try {
595
+ value = await tool.execute({ prompt: avatarPrompt(bot, extra), size: '1024x1024', n: 1 }, { signal: controller.signal });
596
+ break;
597
+ } catch (error) {
598
+ const message = String(error?.message ?? error);
599
+ // Gateways drop long image requests now and then; those are worth another try.
600
+ if (attempt >= AVATAR_ATTEMPTS || controller.signal.aborted || !TRANSIENT.test(message)) {
601
+ throw new Error(TRANSIENT.test(message) ? `the image service failed ${attempt} times in a row (${message}); try again in a moment` : message);
602
+ }
603
+ ctx.logger?.warn?.(`bots: avatar for @${bot.handle}, attempt ${attempt} failed: ${message}; retrying`);
604
+ await new Promise((resolve) => setTimeout(resolve, 1500 * attempt));
605
+ }
606
+ }
607
+ } finally {
608
+ clearTimeout(timer);
609
+ }
610
+ const path = value?.images?.[0]?.path;
611
+ const type = value?.images?.[0]?.mediaType;
612
+ if (!path || !/^image\/(png|jpeg|webp|gif)$/.test(String(type))) throw new Error('the image model returned no picture');
613
+ const bytes = readFileSync(path);
614
+ if (bytes.length > 8 * 1024 * 1024) throw new Error('the generated picture is too large');
615
+ mkdirSync(join(dir, 'avatars'), { recursive: true });
616
+ writeFileSync(join(dir, 'avatars', bot.id), bytes);
617
+ writeFileSync(join(dir, 'avatars', `${bot.id}.type`), type);
618
+ return store.patch(bot.id, { avatar: { kind: 'image', source: 'ai', url: `${R}/avatar/${bot.id}?v=${Date.now().toString(36)}`, color: bot.avatar.color } });
619
+ }
620
+
621
+ // --- the model's tools ------------------------------------------------------------------
622
+ const callerBot = (exec) => store.bySession(exec?.agent?.session?.id);
623
+ const resolve = (ref, what = 'bot') => {
624
+ const bot = store.find(ref);
625
+ if (!bot) throw new Error(`no ${what} "${ref}". Known bots: ${store.list().map((b) => `@${b.handle}`).join(', ') || 'none'}`);
626
+ return bot;
627
+ };
628
+ const anyValue = { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean', required: true } } };
629
+ const text = (s) => [{ type: 'text', text: s }];
630
+ const skillInput = {
631
+ type: 'array',
632
+ items: { type: 'object', additionalProperties: false, properties: { name: { type: 'string', required: true }, description: { type: 'string' }, content: { type: 'string', description: 'Markdown instructions the bot loads when the skill applies.' } } },
633
+ };
634
+ const card = (bot) => `@${bot.handle} — ${bot.name}${bot.role === 'primary' ? ' (dispatcher)' : ''}`;
635
+
636
+ const tools = [
637
+ defineTool({
638
+ name: 'bot_list',
639
+ description: "List the user's bots: handle, name, role, status, bio, skills, apps and scheduled tasks. Use it before delegating to find the right bot.",
640
+ parameters: {},
641
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bots: v.bots }) },
642
+ isConcurrencySafe: () => true,
643
+ execute: async () => {
644
+ const bots = store.list();
645
+ let tasks = [];
646
+ try {
647
+ tasks = await schedulesOf(null);
648
+ } catch {
649
+ tasks = [];
650
+ }
651
+ const lines = bots.map((b) => {
652
+ const sk = b.skills.filter((s) => s.enabled).map((s) => s.name);
653
+ const ap = b.apps.filter((a) => a.enabled).map((a) => a.name);
654
+ const ts = tasks.filter((t) => t.botId === b.id).map((t) => `${t.title} (${t.describe}${t.status !== 'active' ? `, ${t.status}` : ''})`);
655
+ return [`${card(b)} [${botStatus(b)}]${b.bio ? `: ${b.bio}` : ''}`, sk.length ? ` skills: ${sk.join(', ')}` : '', ap.length ? ` apps: ${ap.join(', ')}` : '', ts.length ? ` scheduled: ${ts.join('; ')}` : ''].filter(Boolean).join('\n');
656
+ });
657
+ return { ok: true, text: lines.length ? lines.join('\n') : 'No bots yet.', bots: bots.map(face) };
658
+ },
659
+ }),
660
+ defineTool({
661
+ name: 'bot_create',
662
+ description: 'Create a new bot with its own persona, avatar and skills, and its own conversation. Do it when the user asks, or when a recurring kind of work clearly needs a specialist; say what you created.',
663
+ parameters: {
664
+ name: { type: 'string', required: true, description: 'Display name.' },
665
+ handle: { type: 'string', description: 'Lowercase a-z, 0-9 and dashes; derived from the name when left out.' },
666
+ bio: { type: 'string', description: 'One line describing what the bot does, shown on its card and to other bots.' },
667
+ persona: { type: 'string', description: 'Who the bot is and how it works, in the second person ("You are …"). Several sentences.' },
668
+ initials: { type: 'string', description: 'Avatar letters, at most two; derived from the name (pinyin initials for a Chinese name) when left out.' },
669
+ color: { type: 'string', description: 'Avatar background colour, CSS hex.' },
670
+ skills: { ...skillInput, description: 'Skills to give it.' },
671
+ },
672
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
673
+ execute: async (args, exec) => {
674
+ const by = callerBot(exec);
675
+ const bot = store.save(
676
+ {
677
+ name: args.name,
678
+ handle: args.handle ? slugify(args.handle) : '',
679
+ bio: args.bio ?? '',
680
+ persona: args.persona ?? '',
681
+ avatar: { kind: 'initials', ...(args.initials ? { text: args.initials } : {}), ...(args.color ? { color: args.color } : {}) },
682
+ skills: (args.skills ?? []).map((s) => ({ ...s, enabled: true })),
683
+ },
684
+ { createdBy: by?.id ?? 'user' },
685
+ );
686
+ return { ok: true, text: `Created ${card(bot)}. Message it with bot_send_message to @${bot.handle}.`, bot: face(bot) };
687
+ },
688
+ }),
689
+ defineTool({
690
+ name: 'bot_update',
691
+ description: "Change a bot: name, bio, persona, avatar, skills, or make it the dispatcher. Only the fields you pass change.",
692
+ parameters: {
693
+ bot: { type: 'string', required: true, description: '@handle, id or name of the bot.' },
694
+ name: { type: 'string' },
695
+ bio: { type: 'string' },
696
+ persona: { type: 'string', description: 'Replaces the whole persona.' },
697
+ initials: { type: 'string', description: 'Avatar letters, at most two.' },
698
+ color: { type: 'string', description: 'Avatar background colour, CSS hex.' },
699
+ add_skills: { ...skillInput, description: 'Skills to add (a skill with the same name is replaced).' },
700
+ remove_skills: { type: 'array', items: { type: 'string' }, description: 'Names of skills to remove.' },
701
+ make_dispatcher: { type: 'boolean', description: 'true to make this bot the dispatcher.' },
702
+ },
703
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
704
+ execute: async (args) => {
705
+ const bot = resolve(args.bot);
706
+ const next = { id: bot.id };
707
+ for (const k of ['name', 'bio', 'persona']) if (typeof args[k] === 'string') next[k] = args[k];
708
+ if (args.initials || args.color) next.avatar = { ...(bot.avatar.kind === 'image' ? { kind: 'initials' } : bot.avatar), kind: 'initials', ...(args.initials ? { text: args.initials } : {}), color: args.color ?? bot.avatar.color };
709
+ if (args.add_skills || args.remove_skills) {
710
+ const drop = new Set([...(args.remove_skills ?? []), ...(args.add_skills ?? []).map((s) => s.name)].map((s) => String(s).toLowerCase()));
711
+ next.skills = [...bot.skills.filter((s) => !drop.has(s.name.toLowerCase())), ...(args.add_skills ?? []).map((s) => ({ ...s, enabled: true }))];
712
+ }
713
+ if (args.make_dispatcher === true) next.role = 'primary';
714
+ const saved = store.save(next);
715
+ return { ok: true, text: `Updated ${card(saved)}.`, bot: face(saved) };
716
+ },
717
+ }),
718
+ defineTool({
719
+ name: 'bot_delete',
720
+ description: 'Delete a bot, its scheduled tasks, and archive its conversation. Only when the user asked for it.',
721
+ parameters: { bot: { type: 'string', required: true, description: '@handle, id or name.' } },
722
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
723
+ execute: async (args, exec) => {
724
+ const bot = resolve(args.bot);
725
+ if (callerBot(exec)?.id === bot.id) throw new Error('a bot cannot delete itself; ask the dispatcher or the user');
726
+ if (bot.role === 'primary' && store.list().length > 1) throw new Error('make another bot the dispatcher first (bot_update make_dispatcher)');
727
+ await removeBot(bot);
728
+ return { ok: true, text: `Deleted @${bot.handle}.`, bot: face(bot) };
729
+ },
730
+ }),
731
+ defineTool({
732
+ name: 'bot_send_message',
733
+ description:
734
+ "Send a direct message to another bot. It lands in that bot's own conversation and wakes it; it works on it there and answers you with its own bot_send_message, which arrives here as a new message. Use it to delegate, ask, or report back. Make the text self-contained — the other bot cannot see this conversation. Do not reply to acknowledgements.",
735
+ parameters: {
736
+ to: { type: 'string', required: true, description: '@handle (or id / name) of the bot.' },
737
+ text: { type: 'string', required: true, description: 'The whole message.' },
738
+ },
739
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ to: v.to, from: v.from }) },
740
+ isConcurrencySafe: () => true,
741
+ execute: async (args, exec) => {
742
+ const target = resolve(args.to);
743
+ const sender = callerBot(exec);
744
+ await deliver(sender ?? null, target, args.text, exec?.agent?.session?.id);
745
+ return { ok: true, text: `Delivered to @${target.handle}. Its answer will arrive as a new message; continue with other work or end your turn.`, to: face(target), from: face(sender) };
746
+ },
747
+ }),
748
+ defineTool({
749
+ name: 'bot_schedule',
750
+ description:
751
+ "Manage a bot's scheduled tasks: at each occurrence the prompt is delivered to that bot's conversation as a scheduled instruction. Actions: create, list, update, delete, pause, resume, run (now). Timing: kind=at (at: ISO date-time with offset), every (every_minutes), daily (time HH:MM), weekly (time + weekdays 1=Mon…7=Sun), cron (five fields). Times are in time_zone, default the user's zone.",
752
+ parameters: {
753
+ action: { type: 'string', required: true, enum: ['create', 'list', 'update', 'delete', 'pause', 'resume', 'run'] },
754
+ bot: { type: 'string', description: '@handle of the bot the task belongs to (create/list); defaults to yourself.' },
755
+ id: { type: 'string', description: 'Task id for update/delete/pause/resume/run.' },
756
+ title: { type: 'string' },
757
+ prompt: { type: 'string', description: 'Instruction delivered to the bot each time, self-contained.' },
758
+ kind: { type: 'string', enum: ['at', 'every', 'daily', 'weekly', 'cron'] },
759
+ at: { type: 'string' },
760
+ every_minutes: { type: 'number' },
761
+ time: { type: 'string' },
762
+ weekdays: { type: 'array', items: { type: 'integer' } },
763
+ cron: { type: 'string' },
764
+ time_zone: { type: 'string', description: `IANA zone, default ${zone}.` },
765
+ },
766
+ output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot, task: v.task }) },
767
+ execute: async (args, exec) => {
768
+ const actor = exec?.agent?.session?.id;
769
+ const bot = args.bot ? resolve(args.bot) : callerBot(exec) ?? store.primary();
770
+ if (!bot && (args.action === 'create' || args.action === 'list')) throw new Error('say which bot with `bot`');
771
+ switch (args.action) {
772
+ case 'list': {
773
+ const items = await schedulesOf(bot);
774
+ return { ok: true, bot: face(bot), text: items.length ? items.map((t) => `${t.id}: ${t.title} — ${t.describe}, ${t.status}, next ${t.scheduledAt}`).join('\n') : `@${bot.handle} has no scheduled tasks.` };
775
+ }
776
+ case 'create':
777
+ case 'update': {
778
+ const timing = args.kind ? timingFrom(args, zone) : undefined;
779
+ const task = await scheduleSave(bot, { id: args.action === 'update' ? args.id : undefined, title: args.title, prompt: args.prompt, timing }, actor);
780
+ return { ok: true, bot: face(bot), task, text: `${args.action === 'create' ? 'Scheduled' : 'Updated'} "${task.title}" for @${bot.handle}: ${task.describe}; next at ${task.scheduledAt} (id ${task.id}).` };
781
+ }
782
+ case 'delete':
783
+ checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'delete' }, actor));
784
+ return { ok: true, text: `Deleted task ${args.id}.` };
785
+ case 'pause':
786
+ case 'resume': {
787
+ const task = entryView(checkEntry(await schedule().edit({ id: String(args.id ?? ''), action: 'update', patch: { active: args.action === 'resume' } }, actor)));
788
+ return { ok: true, task, text: `${args.action === 'pause' ? 'Paused' : 'Resumed'} "${task.title}".` };
789
+ }
790
+ case 'run':
791
+ checkEntry(await schedule().run({ id: String(args.id ?? '') }));
792
+ return { ok: true, text: `Task ${args.id} was delivered now.` };
793
+ default:
794
+ throw new Error('unknown action');
795
+ }
796
+ },
797
+ }),
798
+ ];
799
+
800
+ ctx.effect(() => {
801
+ const disposers = tools.map((t) => ctx.tools.register(t));
802
+ return () => {
803
+ for (const d of disposers) if (typeof d === 'function') d();
804
+ };
805
+ }, 'bots: tools');
806
+
807
+ const commands = service(ctx, 'commands');
808
+ if (commands?.register) {
809
+ ctx.effect(() =>
810
+ commands.register({
811
+ name: 'bots',
812
+ description: 'Open the Bots panel: your bots, their conversations, skills, apps and schedules',
813
+ handler: () => ({ kind: 'success', text: `${store.list().length} bot(s). Open the Bots panel from the sidebar.` }),
814
+ }),
815
+ );
816
+ }
817
+
818
+ // --- routes --------------------------------------------------------------------------
819
+ /** A live Agent to read scoped registries through (presets mount skill discovery per Agent). */
820
+ function sampleAgent() {
821
+ const live = agents();
822
+ return store.list().map((b) => (b.sessionId ? live?.get?.(b.sessionId) : undefined)).find(Boolean) ?? live?.list?.()?.[0];
823
+ }
824
+ /** The skills installed in this Harness, as a bot would see them (bot-registered ones left out). */
825
+ async function dshSkills() {
826
+ const registry = service(ctx, 'skills');
827
+ if (!registry?.list) return [];
828
+ const agent = sampleAgent();
829
+ let rows = [];
830
+ try {
831
+ rows = await registry.list(agent ? { scope: agent, cwd: workdir } : {});
832
+ } catch {
833
+ try {
834
+ rows = await registry.list({});
835
+ } catch {
836
+ rows = [];
837
+ }
838
+ }
839
+ return rows
840
+ .filter((r) => r.provider !== 'runtime' && r.source !== 'bots')
841
+ .map((r) => ({ name: r.name, description: String(r.description ?? '').replace(/\s+/g, ' ').slice(0, 400), source: r.source ?? '' }))
842
+ .sort((a, b) => a.name.localeCompare(b.name));
843
+ }
844
+
845
+ async function catalog() {
846
+ const toolRows = [];
847
+ try {
848
+ // Preset tools live in an Agent's scope: read them through a live bot (or any live Agent).
849
+ const live = agents();
850
+ const sample = store.list().map((b) => (b.sessionId ? live?.get?.(b.sessionId) : undefined)).find(Boolean) ?? live?.list?.()?.[0];
851
+ const scope = sample ? scopeOf(sample.ctx) : undefined;
852
+ for (const d of ctx.tools.definitions(scope)) {
853
+ if (TOOL_NAMES.includes(d.name) || d.name.startsWith('mcp__') || d.name === 'run_code') continue;
854
+ toolRows.push({ name: d.name, description: String(d.description ?? '').split(/(?<=\.)\s/)[0].slice(0, 200) });
855
+ }
856
+ } catch {
857
+ // No registry view.
858
+ }
859
+ toolRows.sort((a, b) => a.name.localeCompare(b.name));
860
+ const models = [];
861
+ try {
862
+ const llm = service(ctx, 'llm');
863
+ for (const p of llm?.listProviders?.() ?? []) {
864
+ try {
865
+ for (const m of await llm.listModels(p.id)) models.push({ provider: p.id, model: m.id, label: `${p.name ?? p.id} · ${m.name ?? m.id}` });
866
+ } catch {
867
+ // One provider down leaves the rest.
868
+ }
869
+ }
870
+ } catch {
871
+ // No model service.
872
+ }
873
+ const skills = await dshSkills();
874
+ const ocu = ocuPath();
875
+ return {
876
+ templates: templates(),
877
+ categories: CATEGORIES,
878
+ abilities: ABILITIES.map((a) => ({ ...a, available: a.tools.filter((t) => toolRows.some((r) => r.name === t)) })),
879
+ skillSources: SKILL_SOURCES,
880
+ imageGen: imageGenAvailable(),
881
+ tools: toolRows,
882
+ models,
883
+ skills: skills.map((s) => ({ name: s.name, description: String(s.description ?? '').slice(0, 300) })),
884
+ ocu: { installed: ocu !== '', path: ocu || OCU_PATHS[0] },
885
+ mcp: Boolean(mcpClient),
886
+ zone,
887
+ };
888
+ }
889
+
890
+ function state() {
891
+ const bots = store.list().map((b) => {
892
+ const appIssues = {};
893
+ for (const app of b.apps) {
894
+ try {
895
+ mcpConfigOf(app, b);
896
+ } catch (error) {
897
+ appIssues[app.id] = error?.message ?? String(error);
898
+ }
899
+ }
900
+ return { ...b, status: botStatus(b), appIssues };
901
+ });
902
+ const sessionMap = {};
903
+ for (const b of bots) if (b.sessionId) sessionMap[b.sessionId] = b.id;
904
+ return { bots, primaryId: store.primary()?.id ?? null, sessionMap, messageCount: store.messageCount(), version: store.version() };
905
+ }
906
+
907
+ let ocuInstalling = false;
908
+ // --- skills from elsewhere -------------------------------------------------------
909
+ const skillDir = join(dir, 'skills');
910
+ /** Import one skill (GitHub folder or URL) as a bot skill object, files kept under the cache. */
911
+ async function importSkill(spec) {
912
+ const signal = AbortSignal.timeout(120_000);
913
+ const id = `skill-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
914
+ const gh = spec.repo ? { ...parseGithub(spec.repo), ...(spec.path !== undefined ? { path: spec.path } : {}), ...(spec.ref ? { ref: spec.ref } : {}) } : parseGithub(spec.url ?? '');
915
+ if (gh) {
916
+ const got = await importGithubSkill(gh, skillDir, id, { signal });
917
+ return { id, source: 'import', enabled: true, ...got };
918
+ }
919
+ if (/^https?:\/\//.test(String(spec.url ?? ''))) return { id, source: 'import', enabled: true, ...(await importUrlSkill(spec.url, { signal })) };
920
+ throw new Error('give a GitHub repository or folder (owner/repo/path) or a SKILL.md URL');
921
+ }
922
+
923
+ // --- teams -------------------------------------------------------------------------
924
+ async function teamsView() {
925
+ const names = new Set((await dshSkills()).map((x) => x.name));
926
+ const appIds = new Set(templates().map((t) => t.id));
927
+ return TEAMS.map((t) => teamView(t, { dshSkillNames: names, appIds }));
928
+ }
929
+
930
+ /**
931
+ * Hire a team: create its bots (handles made unique), attach the Harness skills it has,
932
+ * import the GitHub skills it names, add its apps (left for the user to fill keys),
933
+ * schedule its tasks, and make its lead the dispatcher. Returns what was skipped.
934
+ */
935
+ async function hireTeam(teamId, lang, { primary = true } = {}) {
936
+ const team = TEAMS.find((t) => t.id === teamId);
937
+ if (!team) throw new Error(`no team "${teamId}"`);
938
+ const zh = lang === 'zh';
939
+ const pick = (v) => (zh ? v.zh : v.en);
940
+ const have = new Set((await dshSkills()).map((x) => x.name));
941
+ const tpl = templates();
942
+ const created = [];
943
+ const skipped = [];
944
+ const imports = new Map();
945
+ for (const b of team.bots) {
946
+ const skills = [];
947
+ for (const n of b.dshSkills ?? []) {
948
+ if (have.has(n)) skills.push({ name: n, source: 'dsh', description: '', enabled: true });
949
+ else skipped.push({ bot: b.handle, kind: 'skill', name: n });
950
+ }
951
+ for (const spec of b.importSkills ?? []) {
952
+ const key = `${spec.repo}/${spec.path}`;
953
+ try {
954
+ if (!imports.has(key)) imports.set(key, importSkill(spec));
955
+ const got = await imports.get(key);
956
+ skills.push({ ...got, id: undefined });
957
+ } catch (error) {
958
+ skipped.push({ bot: b.handle, kind: 'skill', name: spec.path.split('/').pop(), reason: error?.message ?? String(error) });
959
+ }
960
+ }
961
+ const apps = [];
962
+ for (const id of b.apps ?? []) {
963
+ const t = tpl.find((x) => x.id === id);
964
+ if (!t) {
965
+ skipped.push({ bot: b.handle, kind: 'app', name: id });
966
+ continue;
967
+ }
968
+ apps.push({ template: t.id, name: pick(t.name), serverName: t.serverName, enabled: true, values: {} });
969
+ }
970
+ const deny = [];
971
+ // Team bots never need to reconfigure Harness itself; plugin management starts off.
972
+ for (const off of [...new Set([...(b.off ?? []), 'plugins'])]) for (const t of ABILITIES.find((a) => a.id === off)?.tools ?? []) deny.push(t);
973
+ // The seeded dispatcher (or any bot with this handle that is not in another team) becomes this member.
974
+ const existing = store.list().find((x) => x.handle === b.handle && (!x.team || x.team === team.id));
975
+ const bot = store.save(
976
+ {
977
+ ...(existing ? { id: existing.id, skills: [...existing.skills.filter((x) => !skills.some((y) => y.name === x.name)), ...skills], apps: [...existing.apps.filter((x) => !apps.some((y) => y.serverName === x.serverName)), ...apps] } : {}),
978
+ name: pick(b.name),
979
+ handle: existing ? b.handle : store.find(b.handle) ? '' : b.handle,
980
+ bio: pick(b.bio),
981
+ persona: pick(b.persona),
982
+ // Same letters in both languages: from the English name ("Atlas" → AT), not "Atlas 幕僚长".
983
+ avatar: { kind: 'initials', text: initialsOf(b.name.en), color: b.color },
984
+ role: b.role === 'primary' && primary ? 'primary' : existing?.role === 'primary' ? 'primary' : 'bot',
985
+ ...(existing ? {} : { skills, apps }),
986
+ tools: { deny },
987
+ team: team.id,
988
+ },
989
+ { createdBy: 'user' },
990
+ );
991
+ created.push({ bot, spec: b });
992
+ }
993
+ // Scheduled tasks need each bot's conversation; create them after all bots exist.
994
+ for (const { bot, spec } of created) {
995
+ for (const task of spec.tasks ?? []) {
996
+ try {
997
+ await scheduleSave(bot, { title: pick(task.title), prompt: pick(task.prompt), timing: teamTiming(task.when, zone) });
998
+ } catch (error) {
999
+ skipped.push({ bot: bot.handle, kind: 'schedule', name: pick(task.title), reason: error?.message ?? String(error) });
1000
+ }
1001
+ }
1002
+ }
1003
+ const lead = created.find((c) => c.spec.role === 'primary')?.bot;
1004
+ return { team: team.id, bots: created.map((c) => store.get(c.bot.id)), leadId: lead?.id ?? null, kickoff: pick(team.kickoff), skipped };
1005
+ }
1006
+
1007
+ const unfurlLink = createUnfurler();
1008
+ const routes = {
1009
+ teams: { get: () => teamsView() },
1010
+ 'teams/hire': {
1011
+ post: async (body) => ({ ok: true, ...(await hireTeam(String(body.id ?? ''), body.lang === 'zh' ? 'zh' : 'en', { primary: body.primary !== false })) }),
1012
+ },
1013
+ 'skills/library': { get: async () => ({ skills: await dshSkills(), sources: SKILL_SOURCES }) },
1014
+ 'skills/github': {
1015
+ post: async (body) => {
1016
+ const loc = parseGithub(String(body.repo ?? body.url ?? ''));
1017
+ if (!loc) return { ok: false, reason: 'give owner/repo, owner/repo/path or a github.com URL' };
1018
+ return { ok: true, ...(await listGithubSkills(loc, { signal: AbortSignal.timeout(60_000) })) };
1019
+ },
1020
+ },
1021
+ 'skills/import': {
1022
+ post: async (body) => {
1023
+ const bot = store.get(String(body.botId ?? ''));
1024
+ if (!bot) return { ok: false, reason: 'no such bot' };
1025
+ const specs = Array.isArray(body.items) ? body.items : [body];
1026
+ const added = [];
1027
+ const failed = [];
1028
+ for (const spec of specs.slice(0, 30)) {
1029
+ try {
1030
+ added.push(await importSkill(spec));
1031
+ } catch (error) {
1032
+ failed.push({ spec, reason: error?.message ?? String(error) });
1033
+ }
1034
+ }
1035
+ const saved = store.save({ id: bot.id, skills: [...store.get(bot.id).skills, ...added] });
1036
+ return { ok: added.length > 0 || failed.length === 0, bot: saved, added: added.map((x) => x.name), failed, ...(failed.length && !added.length ? { reason: failed[0].reason } : {}) };
1037
+ },
1038
+ },
1039
+ 'skills/write': {
1040
+ post: async (body) => {
1041
+ // The bot writes its own skill: a DM asking it to draft one with skill-creator and save it with bot_update.
1042
+ const bot = store.get(String(body.botId ?? ''));
1043
+ if (!bot) return { ok: false, reason: 'no such bot' };
1044
+ const ask = String(body.text ?? '').trim();
1045
+ if (!ask) return { ok: false, reason: 'describe the skill' };
1046
+ const zhText = /[\u4e00-\u9fff]/.test(ask);
1047
+ const text = zhText
1048
+ ? `请为你自己写一个新技能:${ask}\n\n如果有 skill-creator 技能,先加载它并按它的方法写。写好后调用 bot_update(bot: @${bot.handle},add_skills)保存:name 用小写英文短横线,description 一句话写清楚何时使用,content 是完整的 Markdown 指南。最后用两三句话告诉我这个技能能做什么。`
1049
+ : `Write a new skill for yourself: ${ask}\n\nIf the skill-creator skill is available, load it and follow it. Save the result with bot_update (bot: @${bot.handle}, add_skills): a lowercase-dashed name, a one-sentence description of when to use it, and the full Markdown instructions as content. Then tell me in two or three sentences what the skill does.`;
1050
+ return { ok: true, sessionId: await userSend(bot, text) };
1051
+ },
1052
+ },
1053
+ 'apps/external': { get: () => ({ items: scanExternalMcp().map(maskedApp) }) },
1054
+ 'apps/import': {
1055
+ post: (body) => {
1056
+ const bot = store.get(String(body.botId ?? ''));
1057
+ if (!bot) return { ok: false, reason: 'no such bot' };
1058
+ const wanted = new Set((Array.isArray(body.names) ? body.names : []).map(String));
1059
+ const found = scanExternalMcp().filter((a) => wanted.has(`${a.from}/${a.name}`));
1060
+ const taken = new Set(bot.apps.map((a) => a.serverName));
1061
+ const apps = found.map((a) => {
1062
+ let serverName = a.serverName;
1063
+ for (let n = 2; taken.has(serverName); n += 1) serverName = `${a.serverName.slice(0, 29)}-${n}`;
1064
+ taken.add(serverName);
1065
+ return { template: a.template, name: a.name, serverName, enabled: true, config: a.config, values: {} };
1066
+ });
1067
+ const saved = store.save({ id: bot.id, apps: [...bot.apps, ...apps] });
1068
+ return { ok: true, bot: saved, added: apps.map((a) => a.name) };
1069
+ },
1070
+ },
1071
+ state: { get: () => state() },
1072
+ catalog: { get: () => catalog() },
1073
+ // A link preview card for the chat: YouTube, X posts, or any page's OpenGraph meta.
1074
+ unfurl: { get: (url) => unfurlLink(url.searchParams.get('url') ?? '') },
1075
+ messages: {
1076
+ get: (url) => ({ items: store.messages({ bot: url.searchParams.get('bot') ?? '', limit: Number(url.searchParams.get('limit')) || 200 }) }),
1077
+ },
1078
+ schedules: {
1079
+ get: async (url) => {
1080
+ const id = url.searchParams.get('bot');
1081
+ const bot = id ? store.get(id) : null;
1082
+ if (id && !bot) return { items: [] };
1083
+ if (bot && !bot.sessionId) return { items: [] };
1084
+ return { items: await schedulesOf(bot) };
1085
+ },
1086
+ },
1087
+ save: {
1088
+ post: (body) => {
1089
+ const prev = body.bot?.id ? store.get(body.bot.id) : undefined;
1090
+ const input = { ...(body.bot ?? {}) };
1091
+ delete input.sessionId;
1092
+ delete input.status;
1093
+ if (prev?.avatar?.kind === 'image' && input.avatar?.kind === 'image') input.avatar = { ...input.avatar, url: prev.avatar.url };
1094
+ const bot = store.save(input, { createdBy: 'user' });
1095
+ applyModel(bot);
1096
+ return { ok: true, bot: { ...bot, status: botStatus(bot) } };
1097
+ },
1098
+ },
1099
+ delete: {
1100
+ post: async (body) => {
1101
+ const bot = store.get(String(body.id ?? ''));
1102
+ if (!bot) return { ok: false, reason: 'no such bot' };
1103
+ if (bot.role === 'primary' && store.list().length > 1) return { ok: false, reason: 'Make another bot the dispatcher first.' };
1104
+ await removeBot(bot);
1105
+ return { ok: true };
1106
+ },
1107
+ },
1108
+ primary: { post: (body) => ({ ok: store.setPrimary(String(body.id ?? '')) }) },
1109
+ open: {
1110
+ post: async (body) => {
1111
+ const bot = store.get(String(body.id ?? ''));
1112
+ if (!bot) return { ok: false, reason: 'no such bot' };
1113
+ return { ok: true, sessionId: await ensureSession(bot) };
1114
+ },
1115
+ },
1116
+ send: {
1117
+ post: async (body) => {
1118
+ const bot = store.get(String(body.to ?? ''));
1119
+ if (!bot) return { ok: false, reason: 'no such bot' };
1120
+ return { ok: true, sessionId: await userSend(bot, body.text) };
1121
+ },
1122
+ },
1123
+ avatar: {
1124
+ post: (body) => {
1125
+ const bot = store.get(String(body.id ?? ''));
1126
+ if (!bot) return { ok: false, reason: 'no such bot' };
1127
+ const m = /^data:(image\/(?:png|jpeg|webp|gif));base64,(.+)$/s.exec(String(body.dataUrl ?? ''));
1128
+ if (!m) return { ok: false, reason: 'send a PNG, JPEG, WebP or GIF image' };
1129
+ const bytes = Buffer.from(m[2], 'base64');
1130
+ if (bytes.length > MAX_AVATAR) return { ok: false, reason: 'the image is larger than 2 MB' };
1131
+ mkdirSync(join(dir, 'avatars'), { recursive: true });
1132
+ writeFileSync(join(dir, 'avatars', bot.id), bytes);
1133
+ writeFileSync(join(dir, 'avatars', `${bot.id}.type`), m[1]);
1134
+ const saved = store.patch(bot.id, { avatar: { kind: 'image', url: `${R}/avatar/${bot.id}?v=${Date.now().toString(36)}`, color: bot.avatar.color } });
1135
+ return { ok: true, bot: saved };
1136
+ },
1137
+ },
1138
+ 'avatar/generate': {
1139
+ post: async (body) => {
1140
+ const bot = store.get(String(body.id ?? ''));
1141
+ if (!bot) return { ok: false, reason: 'no such bot' };
1142
+ return { ok: true, bot: await generateAvatar(bot, body.style) };
1143
+ },
1144
+ },
1145
+ 'avatar/clear': {
1146
+ post: (body) => {
1147
+ const bot = store.get(String(body.id ?? ''));
1148
+ if (!bot) return { ok: false, reason: 'no such bot' };
1149
+ for (const f of [bot.id, `${bot.id}.type`]) rmSync(join(dir, 'avatars', f), { force: true });
1150
+ return { ok: true, bot: store.patch(bot.id, { avatar: { kind: 'initials', color: bot.avatar.color } }) };
1151
+ },
1152
+ },
1153
+ 'ocu/install': {
1154
+ post: async () => {
1155
+ if (ocuInstalling) return { ok: false, reason: 'an install is already running' };
1156
+ ocuInstalling = true;
1157
+ try {
1158
+ const result = await installOcu({ signal: AbortSignal.timeout(300_000) });
1159
+ // Bots already running with the app retry it now instead of at their next start.
1160
+ const live = agents();
1161
+ for (const bot of store.list()) {
1162
+ if (!bot.sessionId || !bot.apps.some((a) => a.enabled && a.template === 'open-computer-use')) continue;
1163
+ const agent = live?.get?.(bot.sessionId);
1164
+ if (!agent) continue;
1165
+ uninstall(bot.sessionId);
1166
+ reconcile(agent);
1167
+ }
1168
+ return { ok: true, version: result.version, path: result.path, ocu: { installed: true, path: result.path } };
1169
+ } finally {
1170
+ ocuInstalling = false;
1171
+ }
1172
+ },
1173
+ },
1174
+ 'schedules/save': {
1175
+ post: async (body) => {
1176
+ const bot = store.get(String(body.botId ?? ''));
1177
+ if (!bot && !body.id) return { ok: false, reason: 'no such bot' };
1178
+ return { ok: true, task: await scheduleSave(bot, body) };
1179
+ },
1180
+ },
1181
+ 'schedules/delete': { post: async (body) => (checkEntry(await schedule().edit({ id: String(body.id ?? ''), action: 'delete' })), { ok: true }) },
1182
+ 'schedules/toggle': {
1183
+ post: async (body) => ({ ok: true, task: entryView(checkEntry(await schedule().edit({ id: String(body.id ?? ''), action: 'update', patch: { active: body.active === true } }))) }),
1184
+ },
1185
+ 'schedules/run': { post: async (body) => (checkEntry(await schedule().run({ id: String(body.id ?? '') })), { ok: true }) },
1186
+ };
1187
+
1188
+ const mountRoutes = (scope) => {
1189
+ const web = scope.webServer;
1190
+ if (!web?.register) return;
1191
+ for (const [path, route] of Object.entries(routes)) {
1192
+ scope.effect(() =>
1193
+ web.register({
1194
+ kind: 'exact',
1195
+ path: `${R}/${path}`,
1196
+ handler: (req, res) => {
1197
+ const url = new URL(req.url ?? '/', 'http://localhost');
1198
+ if (req.method === 'GET' && route.get) return serveJson(res, () => route.get(url));
1199
+ if (route.post) return postJson(req, res, route.post);
1200
+ res.statusCode = 405;
1201
+ res.end();
1202
+ },
1203
+ }),
1204
+ );
1205
+ }
1206
+ scope.effect(() => web.register({ kind: 'prefix', path: `${R}/avatar`, handler: (req, res) => serveAvatar(dir, req, res) }));
1207
+ };
1208
+ if (typeof ctx.inject === 'function') ctx.inject(['webServer'], mountRoutes);
1209
+ else if (ctx.webServer) mountRoutes({ webServer: ctx.webServer, effect: (fn) => ctx.effect(fn) });
1210
+
1211
+ return { store, state, deliver, install, reconcile, installed, routes };
1212
+ }
1213
+
1214
+ function serveAvatar(dir, req, res) {
1215
+ const url = new URL(req.url ?? '/', 'http://localhost');
1216
+ const id = decodeURIComponent(url.pathname.slice(`${R}/avatar/`.length));
1217
+ const file = join(dir, 'avatars', id);
1218
+ let size = 0;
1219
+ let type = 'image/png';
1220
+ try {
1221
+ if (!/^bot-[a-z0-9]+$/.test(id)) throw new Error('bad id');
1222
+ size = statSync(file).size;
1223
+ type = readSmall(`${file}.type`) || type;
1224
+ } catch {
1225
+ res.statusCode = 404;
1226
+ res.end();
1227
+ return;
1228
+ }
1229
+ res.statusCode = 200;
1230
+ res.setHeader('content-type', type);
1231
+ res.setHeader('content-length', String(size));
1232
+ res.setHeader('cache-control', 'private, max-age=31536000, immutable');
1233
+ if (req.method === 'HEAD') return void res.end();
1234
+ createReadStream(file).pipe(res);
1235
+ }
1236
+
1237
+ function readSmall(path) {
1238
+ try {
1239
+ return statSync(path).size < 100 ? readFileSync(path, 'utf8').trim() : '';
1240
+ } catch {
1241
+ return '';
1242
+ }
1243
+ }
1244
+
1245
+ function postJson(req, res, produce) {
1246
+ const type = String(req.headers?.['content-type'] ?? '');
1247
+ if (req.method !== 'POST' || !/^application\/json\b/i.test(type)) {
1248
+ res.statusCode = req.method === 'POST' ? 415 : 405;
1249
+ res.end();
1250
+ return;
1251
+ }
1252
+ const chunks = [];
1253
+ let size = 0;
1254
+ req.on('data', (chunk) => {
1255
+ size += chunk.length;
1256
+ if (size <= 4 * 1024 * 1024) chunks.push(chunk);
1257
+ });
1258
+ req.on('end', () => {
1259
+ serveJson(res, () => {
1260
+ if (size > 4 * 1024 * 1024) return { ok: false, reason: 'request too large' };
1261
+ let body;
1262
+ try {
1263
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
1264
+ } catch {
1265
+ return { ok: false, reason: 'bad-request' };
1266
+ }
1267
+ return produce(body && typeof body === 'object' ? body : {});
1268
+ });
1269
+ });
1270
+ }
1271
+
1272
+ function serveJson(res, produce) {
1273
+ Promise.resolve()
1274
+ .then(produce)
1275
+ .then((body) => {
1276
+ res.statusCode = 200;
1277
+ res.setHeader('content-type', 'application/json; charset=utf-8');
1278
+ res.setHeader('cache-control', 'no-store');
1279
+ res.end(JSON.stringify(body));
1280
+ })
1281
+ .catch((error) => {
1282
+ res.statusCode = 200;
1283
+ res.setHeader('content-type', 'application/json; charset=utf-8');
1284
+ res.end(JSON.stringify({ ok: false, reason: error?.message ?? 'error' }));
1285
+ });
1286
+ }