A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Wire local agent routes through the Bot runtime
Fei2411c04d6650bb91
diff --git a/ds-bot/index.js b/ds-bot/index.jsindex 895df0d6..77b67171 100644--- a/ds-bot/index.js+++ b/ds-bot/index.js@@ -44,6 +44,7 @@ import * as feed from './src/host/feed.js'import * as im from './src/host/im/index.js'import * as officeSkills from './src/host/office-skills.js'import * as goalSkills from './src/host/goal-skills.js'+import * as localAgents from './src/host/local-agents/index.js'export { COLORS } from './src/host/constants.js'@@ -55,7 +56,7 @@ export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'ses// install. Listeners run and tools are listed in registration order, so this order holds:// usage meters model requests after every listener that rewrites them. privacy checks a// call before the hooks of tools do, so a closed call never reaches a card they show.-const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, im, channel, officeSkills, goalSkills]+const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, goals, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, im, channel, officeSkills, goalSkills, localAgents]export function apply(ctx, config = {}) {createRuntime(ctx, config)diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex 720b7c38..be2ae891 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -45,6 +45,8 @@ export function install(rt) {// what failed it. `blocked`: the facts of a failure only the user can fix (turns.js).bots: Object.values(state.bots).map(({ segments, kickoff, ...bot }) => ({...bot, sessionId: rt.chatOf(bot.id), parts: (segments ?? []).map(segment => segment.sessionId), ...(kickoff ? { waiting: true } : {}),+ // `engine` is the Bot's local-agent route, present only on abots.+ ...(rt.localAgentBadge?.(bot.appliedModel ?? bot.model) !== undefined ? { engine: rt.localAgentBadge(bot.appliedModel ?? bot.model) } : {}),})),// `sessionId` is the group's own Session's current part, `ownParts` its earlier// ones; `parts` the members' hidden group Sessions and their earlier segments,@@ -119,7 +121,7 @@ export function install(rt) {}// What a host that only reads the team may still answer.// Updates change the dsh profile, not the team, so a reading host may run them too.- const READS = new Set(['state', 'models', 'efforts', 'providers', 'provider-models', 'earlier', 'chat', 'run-stats', 'room-progress', 'exchange', 'exchange-text', 'file-text', 'usage', 'schedules', 'memory-view', 'browser-wait', 'browser-result', 'diagnostics', 'diagnostics-log', 'diagnostics-clear', 'update-check', 'update-install', 'dsh-update-install', 'repo-stars', 'approval-answer', 'thinking', 'avatar-library'])+ const READS = new Set(['state', 'models', 'efforts', 'providers', 'provider-models', 'earlier', 'chat', 'run-stats', 'room-progress', 'exchange', 'exchange-text', 'file-text', 'usage', 'schedules', 'memory-view', 'browser-wait', 'browser-result', 'diagnostics', 'diagnostics-log', 'diagnostics-clear', 'update-check', 'update-install', 'dsh-update-install', 'repo-stars', 'approval-answer', 'thinking', 'avatar-library', 'local-agents'])async function setPrefs(body) {if (body.theme !== undefined) {@@ -588,6 +590,27 @@ export function install(rt) {case 'im-login-wait':await rt.load()return ok(await rt.imEndpoint(endpoint, body))+ case 'local-agents':+ case 'local-agent-refresh':+ case 'local-agent-add':+ case 'local-agent-update':+ case 'local-agent-remove':+ await rt.load()+ return ok(await rt.localAgentsEndpoint(endpoint, body))+ // "New session" and "open an earlier session" on an abot's chat: ordinary+ // parts moves (parts.js), the same mechanism every Bot's chat uses.+ case 'bot-new-part': {+ await rt.load()+ const bot = rt.botOf(String(body.botId ?? ''))+ if (bot === undefined) return fail('Unknown Bot', 'bot/not-found')+ return ok(await rt.newPart(rt.chatOf(bot.id)))+ }+ case 'bot-open-part': {+ await rt.load()+ const bot = rt.botOf(String(body.botId ?? ''))+ if (bot === undefined) return fail('Unknown Bot', 'bot/not-found')+ return ok(await rt.switchPart(bot.id, String(body.sessionId ?? '')))+ }case 'diagnostics':await rt.load()return ok(await rt.diagnostics.report(body))diff --git a/ds-bot/src/host/memory.js b/ds-bot/src/host/memory.jsindex b20eee3b..df751c3e 100644--- a/ds-bot/src/host/memory.js+++ b/ds-bot/src/host/memory.js@@ -1293,7 +1293,11 @@ export function install(rt) {}))async function modelFor(bot) {- const route = splitRef(await rt.desiredModel(bot) ?? await rt.defaultModel())+ const desired = await rt.desiredModel(bot)+ // A local agent CLI answers through its own subscription, not a model API:+ // its memory reads the team's default model when one is set.+ const ref = rt.isLocalAgentRef?.(desired) === true ? (state.prefs.defaultBotModel ?? null) : desired ?? await rt.defaultModel()+ const route = ref === null ? undefined : splitRef(ref)if (route === undefined) throw new Error('No model is available. Add one in Settings > Models.')return route}diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex 5ef8d6f4..e935881a 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -655,7 +655,7 @@ export function install(rt) {: `${head} It is the note written at the end of part ${segment.noteFrom}, carried over unchanged; anything newer is in the messages below, and read_own_chat finds the rest.)\n\n${segment.note}`}- function handoffPackage({ room, self = false, segment, lines, number, resume, overflow, failed, bare, folder }) {+ function handoffPackage({ room, self = false, segment, lines, number, resume, overflow, failed, bare, folder, manual }) {const where = room === undefined ? 'your own chat with the user': self ? `the group chat "${room.name}"` : `your conversation in the group chat "${room.name}"`const lookup = room === undefined@@ -664,7 +664,9 @@ export function install(rt) {: 'read_group_chat shows the group\'s latest messages, and read_own_chat your own chat.'const reason = failed !== undefined ? `a request in the previous part kept failing (${failed})`: overflow ? 'the previous part overflowed the model\'s window'- : folder !== undefined ? `${self ? 'the group\'s' : 'your'} working folder changed to ${folder}` : 'the previous part grew long'+ : folder !== undefined ? `${self ? 'the group\'s' : 'your'} working folder changed to ${folder}`+ : manual ? 'a fresh conversation was started'+ : 'the previous part grew long'const { recent, earlier, unlisted, complete } = linesconst omitted = [...(unlisted > 0 ? [`(${unlisted} older messages are not listed.)`] : []),@@ -834,10 +836,10 @@ export function install(rt) {// `hard`: past the hard line or the window, the part moves on even without a note// from the model. `folder`: the part moves on because its working folder changed.- function startSwitch(agent, { resume = false, carry = [], info, joined, overflow = false, failed, bare = false, folder = false, hard = overflow || folder } = {}) {+ function startSwitch(agent, { resume = false, carry = [], info, joined, overflow = false, failed, bare = false, folder = false, manual = false, hard = overflow || folder || manual } = {}) {const place = placeOf(agent.id)if (place === undefined || switches.has(agent.id) || readOnly()) return- const job = { ...place, carry: [...carry], info, joined, resume, overflow, failed, bare, folder, hard, since: Date.now() }+ const job = { ...place, carry: [...carry], info, joined, resume, overflow, failed, bare, folder, hard, manual, since: Date.now() }switches.set(agent.id, job)void runSwitch(agent, job).catch(error => {@@ -952,8 +954,11 @@ export function install(rt) {const whole = carried?.whole === true && !session.deriveMessages().some(message => message.role === 'tool')let writtenlet failure+ // A local agent CLI keeps its own compaction and notes: no model call is made+ // for its handoff; the part moves on with the deterministic package.+ const local = bot !== undefined && rt.isLocalAgentRef?.(bot.appliedModel ?? bot.model) === true// The group's own Session only relays; it has no route a note could be written with.- if (!job.overflow && job.failed === undefined && !whole && bot !== undefined) {+ if (!local && !job.overflow && job.failed === undefined && !whole && bot !== undefined) {try {written = await writeNote(agent, AbortSignal.any([signal, AbortSignal.timeout(NOTE_TIMEOUT_MS)]), { folder: job.folder })} catch (error) {@@ -974,6 +979,7 @@ export function install(rt) {if (failure !== undefined) rt.warn('ds-bot: handoff note for %s failed past the hard line; moving on with the earlier note: %s', name, failure)const previous = parts.at(-2)const noted = written !== undefined ? { note: written.note }+ : local ? {}: { fallback: whole ? 'whole' : job.failed !== undefined ? 'failure' : job.overflow ? 'overflow' : 'failed', ...(previous?.note ? { note: previous.note, noteFrom: previous.noteFrom ?? previous.number } : {}) }carried ??= await readLines()if (signal.aborted) throw signal.reason@@ -1041,7 +1047,7 @@ export function install(rt) {folderRetry.set(freshId, Date.now() + FOLDER_RETRY_MS)rt.warn('ds-bot: the fresh part of %s did not start in %s; it works in %s', name, intended, cwd)}- const text = handoffPackage({ room, self: bot === undefined, segment, lines: carried, number: number + 1, resume, overflow: job.overflow, failed: job.failed, bare: job.bare, folder })+ const text = handoffPackage({ room, self: bot === undefined, segment, lines: carried, number: number + 1, resume, overflow: job.overflow, failed: job.failed, bare: job.bare, folder, manual: job.manual })freshParts.set(freshId, estimateTokens(text))fresh.followup(createUserMessage({ content: [{ type: 'text', text }], source: handoffSource(job, resume) }))await ctx.sessions.flush(fresh.session)@@ -1102,6 +1108,9 @@ export function install(rt) {// The group's own Session moves only for its folder, never for its size: its turns// are synthesized relay calls, so the steward's lines do not apply to it.if (place.botId === undefined) return next()+ // A local agent CLI owns its in-session compaction; the DSH Session keeps the+ // full history for read_own_chat and never condenses or switches on size.+ if (rt.isLocalAgentRef?.(rt.botOf(place.botId)?.appliedModel ?? rt.botOf(place.botId)?.model) === true) return next()const lines = await contextLines(agent.session).catch(() => undefined)const tokens = tokensOf(agent.session)if (lines === undefined || tokens === undefined || tokens < lines.hard || !grown(agent.id, tokens, lines) || readOnly()) return next()@@ -1235,6 +1244,8 @@ export function install(rt) {// past it.async function checkContext(agent) {if (switches.has(agent.id) || freshParts.has(agent.id) || checking.has(agent.id) || readOnly()) return+ // A local agent CLI owns its in-session compaction.+ if (rt.isLocalAgentRef?.(rt.botOf(placeOf(agent.id)?.botId)?.appliedModel ?? rt.botOf(placeOf(agent.id)?.botId)?.model) === true) returnif (lastTurnEnd(agent)?.data?.reason?.kind === 'error') returnconst lines = await contextLines(agent.session)const tokens = tokensOf(agent.session)@@ -1471,5 +1482,45 @@ export function install(rt) {return { sessionId: parts.at(-1).sessionId, ...(await partPage(parts, index, cursor)) }}- Object.assign(rt, { clock, partsOf, historyEntry, partLines, noteText, earlierPage, chatPage, displayItems, followFolder, heldBack, switchJobs: () => switches.values() })+ // "New session" in a Bot's chat: a manual move to a fresh part with the+ // deterministic handoff package, no model call.+ async function newPart(sessionId) {+ await rt.load()+ const agent = await rt.resolveAgent(sessionId)+ const place = placeOf(sessionId)+ if (place?.botId === undefined || place.roomId !== undefined) throw Object.assign(new Error('Only a Bot\'s own chat can start a fresh part'), { code: 'bot/invalid' })+ if (agent.status !== 'idle') throw Object.assign(new Error('The Bot is working; wait for it to finish or stop it first'), { code: 'bot/busy' })+ startSwitch(agent, { manual: true })+ return true+ }++ // Opening an earlier part again: it becomes the current one and the part that+ // was current joins the earlier ones where it sat.+ async function switchPart(botId, partId) {+ await rt.load()+ const bot = rt.botOf(botId)+ if (bot === undefined) throw Object.assign(new Error('Unknown Bot'), { code: 'bot/not-found' })+ const current = rt.chatOf(botId)+ if (partId === current) return false+ const segments = bot.segments ?? []+ const at = segments.findIndex(segment => segment.sessionId === partId)+ if (at === -1) throw Object.assign(new Error('Unknown part'), { code: 'bot/not-found' })+ const live = rt.live.get(current)+ if (live?.turn !== undefined) throw Object.assign(new Error('The Bot is working; wait for it to finish or stop it first'), { code: 'bot/busy' })+ segments.splice(at, 1)+ segments.splice(at, 0, { sessionId: current, endedAt: Date.now() })+ bot.sessionId = partId+ rt.chatOwners.delete(current)+ rt.chatOwners.set(partId, botId)+ rt.pastOwners.delete(partId)+ rt.pastOwners.set(current, { botId })+ await ctx.workspaceRegistry.unarchiveSession?.({ sessionId: partId }).catch(error => rt.warn('ds-bot: part %s not unarchived: %s', partId, error))+ await rt.applyModel(bot, { force: true }).catch(error => rt.warn('ds-bot: model for %s not applied: %s', bot.name, error))+ const room = undefined+ await rt.applyPermission(bot, partId, room).catch(() => {})+ await rt.save()+ return true+ }++ Object.assign(rt, { clock, partsOf, historyEntry, partLines, noteText, earlierPage, chatPage, displayItems, followFolder, heldBack, newPart, switchPart, switchJobs: () => switches.values() })}diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.jsindex 1d8cec21..473159f9 100644--- a/ds-bot/src/host/roster.js+++ b/ds-bot/src/host/roster.js@@ -2,7 +2,7 @@// the first Main Bot of a new team.import { mkdir } from 'node:fs/promises'import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOTICE_MAX } from './constants.js'-import { currentColor, isColor, normalize, unquote } from './text.js'+import { currentColor, isColor, normalize, splitRef, unquote } from './text.js'import { nameProblem } from '../shared/mentions.js'const BROWSER_GRANT_KINDS = new Set(['post', 'upload', 'download', 'delete', '*'])@@ -102,7 +102,7 @@ export function install(rt) {const avatar = {}if (typeof input.shape === 'string' && /^[a-z][\w-]{0,31}$/.test(input.shape)) avatar.shape = input.shapeif (typeof input.image === 'string') {- if (!/^data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]+$/.test(input.image)) throw new Error('Avatar images must be PNG, JPEG, WebP, or GIF')+ if (!/^data:image\/(png|jpeg|webp|gif|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(input.image)) throw new Error('Avatar images must be PNG, JPEG, WebP, GIF, or SVG')if (input.image.length > MAX_AVATAR_IMAGE) throw new Error('Avatar image is too large')avatar.image = input.image}@@ -370,6 +370,7 @@ export function install(rt) {if (avatar) bot.avatar = avatarelse delete bot.avatar}+ const providerBefore = patch.model !== undefined ? splitRef(bot.appliedModel ?? bot.model)?.provider : undefinedif (patch.model !== undefined) {// A failure that blocked the Bot was its old model's (turns.js).if ((modelRef ?? undefined) !== bot.model) delete bot.blocked@@ -413,6 +414,17 @@ export function install(rt) {.catch(error => rt.warn('ds-bot: profile update for %s not delivered: %s', bot.name, error?.message ?? error))}if (modelChanged) await rt.applyModel(bot, { force: true })+ // A different engine cannot share the conversation's CLI session: to or+ // from a local agent route, or between two different local agents, the+ // chat opens in a fresh part.+ if (patch.model !== undefined) {+ const providerAfter = splitRef(bot.appliedModel ?? bot.model)?.provider+ const wasLocal = rt.isLocalAgentRoute?.(providerBefore) === true+ const isLocal = rt.isLocalAgentRoute?.(providerAfter) === true+ if ((wasLocal !== isLocal || (isLocal && providerBefore !== providerAfter)) && providerBefore !== providerAfter) {+ void rt.newPart?.(rt.chatOf(bot.id)).catch(error => rt.warn('ds-bot: fresh part after the engine change of %s failed: %s', bot.name, error))+ }+ }if (moved) void rt.followFolder({ botId: bot.id })// A new model lifted what blocked the Bot; a new thinking level alone fixes nothing.// releaseKickoff itself leaves when the Bot still lacks a model or holds no greeting.diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.jsindex 0ef28280..2f5b4393 100644--- a/ds-bot/src/host/tools.js+++ b/ds-bot/src/host/tools.js@@ -811,7 +811,10 @@ export function install(rt) {const disposers = []const failed = []const registered = []- for (const def of rt.teamTools) {+ // The local-agent tools (the CLI permission bridge) join the scope only of+ // a Bot whose route is a local agent; they are not in rt.teamTools.+ const localBot = rt.isLocalAgentRef?.(rt.botOf(rt.selfOf(id))?.appliedModel ?? rt.botOf(rt.selfOf(id))?.model) === true+ for (const def of [...rt.teamTools, ...(localBot ? (rt.localAgentTools ?? []) : [])]) {if (relayOnly && def.name !== 'group_relay') continuetry {const dispose = agent.ctx.tools.register(def)diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex 641d7b31..dbf84319 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -13,7 +13,7 @@ import { reminderText } from './schedules.js'// Failures only the user can fix: a key, a sign-in, a balance. They block the Bot// until it is fixed (`bot.blocked`, for the repair card).-export const BLOCKING_CODES = new Set(['MISSING_CREDENTIAL', 'INVALID_CREDENTIAL', 'AUTH', 'QUOTA', 'ACCOUNT_QUOTA', 'ACCOUNT_SIGN_IN_REQUIRED', 'ACCOUNT_SIGNED_OUT', 'ACCOUNT_TOKEN_INVALID'])+export const BLOCKING_CODES = new Set(['MISSING_CREDENTIAL', 'INVALID_CREDENTIAL', 'AUTH', 'QUOTA', 'ACCOUNT_QUOTA', 'ACCOUNT_SIGN_IN_REQUIRED', 'ACCOUNT_SIGNED_OUT', 'ACCOUNT_TOKEN_INVALID', 'LOCAL_AGENT_MISSING', 'LOCAL_AGENT_SIGNIN', 'LOCAL_AGENT_QUOTA', 'LOCAL_AGENT_EXIT'])// The ones a key set outside a turn can fix, and the ones a sign-in can (unblockBots).// A balance only a turn that completes shows fixed, as Retry runs one.const KEY_CODES = new Set(['MISSING_CREDENTIAL', 'INVALID_CREDENTIAL', 'AUTH'])