A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Move the group's own Session to a part in the group folder
Fei2411c840fd01f1e3
diff --git a/ds-bot/client.js b/ds-bot/client.jsindex 1213657e..46ad9e2d 100644--- a/ds-bot/client.js+++ b/ds-bot/client.js@@ -1541,7 +1541,9 @@ function indexRoster(value) {for (const id of [...bot.parts ?? [], bot.sessionId ?? bot.id, bot.id]) byId[id] = bot;}const roomsById = {};- for (const room2 of value.rooms) roomsById[room2.id] = room2;+ for (const room2 of value.rooms) {+ for (const id of [room2.id, room2.sessionId, ...room2.ownParts ?? []]) roomsById[id] = room2;+ }const agentsById = {};const agentOf = {};for (const agent of value.agents ?? []) {@@ -8893,7 +8895,7 @@ function ActivityIndicator({ sessionId, useRoster, useSessionStatus, useLive, usconst bot = roster.byId[sessionId];const room2 = roster.roomsById[sessionId];const moveAt = useWork?.((work) => {- const entry = bot === void 0 ? void 0 : work.bots?.[bot.id];+ const entry = bot !== void 0 ? work.bots?.[bot.id] : room2 !== void 0 ? work.rooms?.[room2.id]?.find((item) => item.self === true) : void 0;return entry?.switching === true && entry.folder === true && entry.roomId === void 0 ? entry.since : 0;}) ?? 0;const entries2 = (0, import_react17.useMemo)(() => Object.values(JSON.parse(liveKey)), [liveKey]);@@ -9293,13 +9295,14 @@ function BotRow({ bot, roster, actions, useSessions, useSessionStatus, useSessio}function RoomRow({ room: room2, roster, actions, useSessions, useSessionStatus, useSessionRetainInfo, useWork, wide, marked }) {const id = room2.id;- const fallback = useSessions((list) => previewOf(list, id));+ const sessionId = room2.sessionId ?? id;+ const fallback = useSessions((list) => previewOf(list, sessionId));const preview = room2.preview?.replace(/\s+/g, " ").trim() || fallback;- const active = useSessionRetainInfo(id, (info) => (info?.retainedBy?.mainView ?? 0) > 0);- const unread = useSessionStatus((map) => map.get(id)?.completionUnread === true) || marked && !active;+ const active = useSessionRetainInfo(sessionId, (info) => (info?.retainedBy?.mainView ?? 0) > 0);+ const unread = useSessionStatus((map) => map.get(sessionId)?.completionUnread === true) || marked && !active;useMarkedUnread(id, active, marked, actions);const approval = useApproval(useWork, (entry) => entry.roomId === id);- const members = workKeys(useGroupWork(useWork, (rooms) => (rooms[id] ?? []).map((entry) => ({ id: entry.botId, ...doingOf(entry) }))));+ const members = workKeys(useGroupWork(useWork, (rooms) => (rooms[id] ?? []).filter((entry) => entry.botId !== void 0).map((entry) => ({ id: entry.botId, ...doingOf(entry) }))));const first = roster.byId[members[0]?.id];const workingLine = first ? workLine(first.name, members[0], members.length - 1) : null;if (room2.hidden && !active) return null;@@ -10089,7 +10092,13 @@ function useLandOnMainBot(roster, useSessions, actions) {if (currentPart(bot) !== id) actions.landOn(bot.id);return void 0;}- if (id !== "" && (roster.roomsById[id] || (actions.isAgentSession?.(id) ?? roster.agentOf[id] !== void 0) || blank3 !== "1")) {+ const room2 = id === "" ? void 0 : roster.roomsById[id];+ if (room2 !== void 0) {+ lastBot.current = null;+ if ((room2.sessionId ?? room2.id) !== id) actions.openSession(room2.id);+ return void 0;+ }+ if (id !== "" && ((actions.isAgentSession?.(id) ?? roster.agentOf[id] !== void 0) || blank3 !== "1")) {lastBot.current = null;return void 0;}@@ -10660,7 +10669,7 @@ function chatRows(roster, list, sessionId) {});const team = /* @__PURE__ */ new Set([...roster.bots.flatMap((bot) => [bot.id, currentPart(bot), ...bot.parts ?? []]),- ...roster.rooms.flatMap((room2) => [room2.id, ...room2.parts ?? []])+ ...roster.rooms.flatMap((room2) => [room2.id, room2.sessionId, ...room2.ownParts ?? [], ...room2.parts ?? []].filter((id) => id !== void 0))]);const others = (list?.ids ?? []).map((id) => byId[id]).filter((row) => row !== void 0 && row.id !== sessionId && !team.has(row.id) && row.origin !== "subagent" && row.blank !== true).sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)).slice(0, OTHER_CHATS_MAX).map((row) => ({ sessionId: row.id, label: row.displayTitle || row.title || row.id, updatedAt: row.updatedAt }));return [...bots, ...others];@@ -20383,7 +20392,7 @@ function apply(ctx) {let expected2 = null;const setPlain = (plain) => surface.set((state) => state.plain === plain ? state : { ...state, plain });const dropPanels = () => ui2.set((state) => state.details || state.renaming ? { ...state, details: null, view: "details", renaming: false, tab: null } : state);- const seenKey = (id) => roster.getSnapshot().byId?.[id]?.id ?? id;+ const seenKey = (id) => roster.getSnapshot().byId?.[id]?.id ?? roster.getSnapshot().roomsById?.[id]?.id ?? id;const leaveVisits = (ids) => {seenAt = seenStore.update((seen) => noteLeft(seen, ids.map(seenKey), Date.now()), seenAt);};@@ -20474,7 +20483,7 @@ function apply(ctx) {for (const id of pendingAdopt.keys()) {if (roster.getSnapshot().agentOf[id] !== void 0 || listed[id] === void 0) pendingAdopt.delete(id);}- for (const id of [...value.bots.map(currentPart), ...value.rooms.map((room2) => room2.id)]) {+ for (const id of [...value.bots.map(currentPart), ...value.rooms.map((room2) => room2.sessionId ?? room2.id)]) {if (refreshed.has(id)) continue;refreshed.add(id);void Promise.resolve(ctx.sessions.refreshProjections?.(id)).catch(quietly("refresh projections"));@@ -20701,8 +20710,11 @@ function apply(ctx) {return value;});const partFor = (id) => {- const bot = roster.getSnapshot().byId[id];- return bot ? currentPart(bot) : id;+ const snapshot = roster.getSnapshot();+ const bot = snapshot.byId[id];+ if (bot !== void 0) return currentPart(bot);+ const room2 = snapshot.roomsById[id];+ return room2 === void 0 ? id : room2.sessionId ?? room2.id;};const agentSessions = (agentId) => {const ids = [...roster.getSnapshot().agentsById[agentId]?.sessions ?? []];diff --git a/ds-bot/src/client/activity-row.js b/ds-bot/src/client/activity-row.jsindex dcc75ce6..1cb6caf4 100644--- a/ds-bot/src/client/activity-row.js+++ b/ds-bot/src/client/activity-row.js@@ -120,7 +120,8 @@ export function ActivityIndicator({ sessionId, useRoster, useSessionStatus, useL// The one switch the row names: a working-folder move jumps the chat to a fresh// part while a turn is not running, so without it the conversation just empties.const moveAt = useWork?.((work) => {- const entry = bot === undefined ? undefined : work.bots?.[bot.id]+ const entry = bot !== undefined ? work.bots?.[bot.id]+ : room !== undefined ? work.rooms?.[room.id]?.find(item => item.self === true) : undefinedreturn entry?.switching === true && entry.folder === true && entry.roomId === undefined ? entry.since : 0}) ?? 0const entries = useMemo(() => Object.values(JSON.parse(liveKey)), [liveKey])diff --git a/ds-bot/src/client/at-menu.js b/ds-bot/src/client/at-menu.jsindex 64d6cf05..ca6c5b7d 100644--- a/ds-bot/src/client/at-menu.js+++ b/ds-bot/src/client/at-menu.js@@ -50,7 +50,7 @@ export function chatRows(roster, list, sessionId) {})const team = new Set([...roster.bots.flatMap(bot => [bot.id, currentPart(bot), ...(bot.parts ?? [])]),- ...roster.rooms.flatMap(room => [room.id, ...(room.parts ?? [])]),+ ...roster.rooms.flatMap(room => [room.id, room.sessionId, ...(room.ownParts ?? []), ...(room.parts ?? [])].filter(id => id !== undefined)),])const others = (list?.ids ?? []).map(id => byId[id]).filter(row => row !== undefined && row.id !== sessionId && !team.has(row.id) && row.origin !== 'subagent' && row.blank !== true)diff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.jsindex 15ba3b56..875d983c 100644--- a/ds-bot/src/client/index.js+++ b/ds-bot/src/client/index.js@@ -92,7 +92,7 @@ export function apply(ctx) {// panels would follow it and report it is not on the team, so they close.const dropPanels = () => ui.set(state => (state.details || state.renaming ? { ...state, details: null, view: 'details', renaming: false, tab: null } : state))// A Bot's chat spans several parts, so when it was last left is kept per Bot.- const seenKey = id => roster.getSnapshot().byId?.[id]?.id ?? id+ const seenKey = id => roster.getSnapshot().byId?.[id]?.id ?? roster.getSnapshot().roomsById?.[id]?.id ?? idconst leaveVisits = (ids) => {seenAt = seenStore.update(seen => noteLeft(seen, ids.map(seenKey), Date.now()), seenAt)}@@ -186,7 +186,7 @@ export function apply(ctx) {for (const id of pendingAdopt.keys()) {if (roster.getSnapshot().agentOf[id] !== undefined || listed[id] === undefined) pendingAdopt.delete(id)}- for (const id of [...value.bots.map(currentPart), ...value.rooms.map(room => room.id)]) {+ for (const id of [...value.bots.map(currentPart), ...value.rooms.map(room => room.sessionId ?? room.id)]) {if (refreshed.has(id)) continuerefreshed.add(id)void Promise.resolve(ctx.sessions.refreshProjections?.(id)).catch(quietly('refresh projections'))@@ -391,10 +391,13 @@ export function apply(ctx) {ctx.inject(['shortcuts'], scope => { scope.effect(() => holdShellShortcuts(scope.shortcuts), 'ds-bot: settings shortcut') })const after = promise => promise.then(async (value) => { await pull().catch(() => {}); return value })- // A Bot id, or any part of its chat, opens the Bot's current part.+ // A Bot id or a group chat id, or any part of either's chat, opens the current part.const partFor = (id) => {- const bot = roster.getSnapshot().byId[id]- return bot ? currentPart(bot) : id+ const snapshot = roster.getSnapshot()+ const bot = snapshot.byId[id]+ if (bot !== undefined) return currentPart(bot)+ const room = snapshot.roomsById[id]+ return room === undefined ? id : (room.sessionId ?? room.id)}// Sessions owned by an Agent, including ones adopted before the roster caught up.const agentSessions = (agentId) => {diff --git a/ds-bot/src/client/sidebar.js b/ds-bot/src/client/sidebar.jsindex e372e16c..fcd15be5 100644--- a/ds-bot/src/client/sidebar.js+++ b/ds-bot/src/client/sidebar.js@@ -111,13 +111,15 @@ function BotRow({ bot, roster, actions, useSessions, useSessionStatus, useSessiofunction RoomRow({ room, roster, actions, useSessions, useSessionStatus, useSessionRetainInfo, useWork, wide, marked }) {const id = room.id- const fallback = useSessions(list => previewOf(list, id))+ // The group's own Session is a chain of parts; the row shows the current one.+ const sessionId = room.sessionId ?? id+ const fallback = useSessions(list => previewOf(list, sessionId))const preview = room.preview?.replace(/\s+/g, ' ').trim() || fallback- const active = useSessionRetainInfo(id, info => (info?.retainedBy?.mainView ?? 0) > 0)- const unread = useSessionStatus(map => map.get(id)?.completionUnread === true) || (marked && !active)+ const active = useSessionRetainInfo(sessionId, info => (info?.retainedBy?.mainView ?? 0) > 0)+ const unread = useSessionStatus(map => map.get(sessionId)?.completionUnread === true) || (marked && !active)useMarkedUnread(id, active, marked, actions)const approval = useApproval(useWork, entry => entry.roomId === id)- const members = workKeys(useGroupWork(useWork, rooms => (rooms[id] ?? []).map(entry => ({ id: entry.botId, ...doingOf(entry) }))))+ const members = workKeys(useGroupWork(useWork, rooms => (rooms[id] ?? []).filter(entry => entry.botId !== undefined).map(entry => ({ id: entry.botId, ...doingOf(entry) }))))const first = roster.byId[members[0]?.id]const workingLine = first ? workLine(first.name, members[0], members.length - 1) : nullif (room.hidden && !active) return null@@ -820,8 +822,16 @@ function useLandOnMainBot(roster, useSessions, actions) {if (currentPart(bot) !== id) actions.landOn(bot.id)return undefined}+ // The group's own Session moves on like a Bot's chat does: the part it archived+ // is cleared, and the view goes on in the fresh one.+ const room = id === '' ? undefined : roster.roomsById[id]+ if (room !== undefined) {+ lastBot.current = null+ if ((room.sessionId ?? room.id) !== id) actions.openSession(room.id)+ return undefined+ }// A DSH Agent Session, blank or not, is a real destination: it stays.- if (id !== '' && (roster.roomsById[id] || (actions.isAgentSession?.(id) ?? roster.agentOf[id] !== undefined) || blank !== '1')) {+ if (id !== '' && ((actions.isAgentSession?.(id) ?? roster.agentOf[id] !== undefined) || blank !== '1')) {lastBot.current = nullreturn undefined}diff --git a/ds-bot/src/client/sources.js b/ds-bot/src/client/sources.jsindex 36e9b579..84125722 100644--- a/ds-bot/src/client/sources.js+++ b/ds-bot/src/client/sources.js@@ -29,7 +29,11 @@ export function indexRoster(value) {for (const id of [...(bot.parts ?? []), bot.sessionId ?? bot.id, bot.id]) byId[id] = bot}const roomsById = {}- for (const room of value.rooms) roomsById[room.id] = room+ // A group's own Session is a chain of parts like a Bot's chat: `room.id` is its+ // first part's id and `sessionId` its current one; every part id finds the room.+ for (const room of value.rooms) {+ for (const id of [room.id, room.sessionId, ...(room.ownParts ?? [])]) roomsById[id] = room+ }// The DSH Agent is not a Bot: it indexes by its own id and by each Session it owns.const agentsById = {}const agentOf = {}diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex 48e69671..584be6bc 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -45,11 +45,13 @@ export function install(rt) {bots: Object.values(state.bots).map(({ segments, kickoff, ...bot }) => ({...bot, sessionId: rt.chatOf(bot.id), parts: (segments ?? []).map(segment => segment.sessionId), ...(kickoff ? { waiting: true } : {}),})),- // `parts`: the members' hidden group Sessions and their earlier segments, for usage.- rooms: Object.values(state.rooms).map(({ log, seen, paused, sessions, segments, ...room }) => {- const parts = [...Object.values(sessions ?? {}), ...Object.values(segments ?? {}).flat().map(segment => segment.sessionId)]+ // `sessionId` is the group's own Session's current part, `ownParts` its earlier+ // ones; `parts` the members' hidden group Sessions and their earlier segments,+ // for usage.+ rooms: Object.values(state.rooms).map(({ log, seen, paused, sessions, segments, parts: ownParts, ...room }) => {+ const parts = [...Object.values(sessions ?? {}), ...Object.values(segments ?? {}).flat().map(segment => segment.sessionId), ...(ownParts ?? []).map(segment => segment.sessionId)]const last = (log ?? []).filter(line => line.kind === undefined).at(-1)- return { ...room, parts, ...(last ? { preview: last.who === 'User' ? last.text : `${last.who}:${last.text}` } : {}) }+ return { ...room, sessionId: rt.sessionOfRoom(room), ownParts: (ownParts ?? []).map(segment => segment.sessionId), parts, ...(last ? { preview: last.who === 'User' ? last.text : `${last.who}:${last.text}` } : {}) }}),// Deleted private Bots whose folder, memory and chats stay closed to the others.privateArchives: rt.archivesView(),@@ -421,9 +423,14 @@ export function install(rt) {const text = String(body.text ?? '').trim()if (text === '' || typeof body.sessionId !== 'string') return fail('Nothing to send', 'bot/invalid')await rt.load()- // A Bot id or an earlier part of its own chat means the current part.+ // A Bot id, a group chat's id, or an earlier part of either means the+ // current part.const past = rt.pastOwners.get(body.sessionId)- const sessionId = rt.botOf(body.sessionId) ? rt.chatOf(body.sessionId) : past && past.roomId === undefined ? rt.chatOf(past.botId) : body.sessionId+ const room = rt.roomOf(body.sessionId)+ const sessionId = rt.botOf(body.sessionId) ? rt.chatOf(body.sessionId)+ : room !== undefined ? rt.sessionOfRoom(room)+ : past?.roomId === undefined && past !== undefined ? rt.chatOf(past.botId)+ : past !== undefined ? rt.sessionOfRoom(rt.roomOf(past.roomId)) : body.sessionIdawait rt.ensureCapabilities(sessionId)await ctx.sessionController.prompt({requestId: randomUUID(),diff --git a/ds-bot/src/host/folders.js b/ds-bot/src/host/folders.jsindex 7c334edc..af5e5094 100644--- a/ds-bot/src/host/folders.js+++ b/ds-bot/src/host/folders.js@@ -57,29 +57,10 @@ export function install(rt) {const reported = session?.header === undefined ? undefined : ctx.get?.('workingDirectory')?.get?.(session) ?? session.header.cwdif (reported !== undefined) return reportedconst id = session?.id+ const room = rt.roomOf(id)+ if (room !== undefined) return workDirOf({ roomId: room.id }) ?? teamFolder()return workDirOf({ botId: rt.selfOf?.(id), roomId: rt.groupOwners?.get(id)?.roomId }) ?? teamFolder()}-- // The file panel lists a Session at its workspace root, which the workspaceFileScope- // lookup resolves from the header the Session was made with; a group's relay Session- // keeps that header after the group gets a folder. The declared resolver answers the- // group's folder for the group's own Session, and every other Session goes back to the- // provider's own resolution.- const lookups = ctx.get?.('typert')?.lookups- const files = lookups?.get?.('workspaceFileScope')- if (files !== undefined) {- try {- lookups.configure('workspaceFileScope', async (id) => {- await rt.load()- const dir = rt.roomOf(id)?.workDir- if (dir !== undefined && await isFolder(dir)) return { sessionId: id, workspaceRoot: dir }- return files.resolve(id)- })- } catch (error) {- rt.warn('ds-bot: group folders cannot be given to the file panel: %s', error)- }- }-// The desktop app runs its own DSH and names the user's, which Bots must not write either.const dataRoots = () => [rt.dshHome, rt.home, process.env.DS_BOT_USER_DSH_HOME?.trim()].filter(Boolean)diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex ab8364d8..187bbfa9 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -1080,7 +1080,7 @@ export function install(rt) {await rt.save()return}- const agent = await rt.resolveAgent(room.id)+ const agent = await rt.resolveAgent(rt.sessionOfRoom(room))agent.followup(createUserMessage({content: [{ type: 'text', text: `[Group post from ${sender.name}]\n${text}` }, ...files.map(attachment => ({ type: 'file', attachment }))],source: { kind: SOURCE_KIND, form: 'relay', role: 'post', exchangeId: randomUUID(), senderName: sender.name, senderSessionId: sender.id, roomId: room.id, ...extra },@@ -1237,7 +1237,7 @@ export function install(rt) {const room = rt.roomOf(roomId)if (room === undefined) return falseconst round = rt.roomBusy(room.id)- if (round) (await rt.resolveAgent(room.id)).cancel({ kind: 'user' })+ if (round) (await rt.resolveAgent(rt.sessionOfRoom(room))).cancel({ kind: 'user' })let stopped = falsefor (const botId of room.members) stopped = (await stopMemberWork(room.id, botId)) || stoppedreturn round || stopped@@ -1267,7 +1267,7 @@ export function install(rt) {async function greetRoom(roomId) {const room = rt.roomOf(roomId)if (!room?.admin) return- const agent = await rt.resolveAgent(room.id)+ const agent = await rt.resolveAgent(rt.sessionOfRoom(room))agent.followup(createUserMessage({content: [{ type: 'text', text: '[Group chat created]' }],source: { kind: SOURCE_KIND, form: 'relay', role: 'kickoff', exchangeId: randomUUID(), senderName: 'You', roomId: room.id },diff --git a/ds-bot/src/host/memory.js b/ds-bot/src/host/memory.jsindex 8a4f4666..06ab9fe2 100644--- a/ds-bot/src/host/memory.js+++ b/ds-bot/src/host/memory.js@@ -881,7 +881,7 @@ export function install(rt) {// A deleted group chat's memory moves to the archive, whole. Called before the// group's Sessions leave the state, whose snapshots go with them.function archiveGroupMemory(room) {- for (const sessionId of [...Object.values(room.sessions ?? {}), ...Object.values(room.segments ?? {}).flat().map(segment => segment.sessionId)]) renewMemory(sessionId)+ for (const sessionId of [rt.sessionOfRoom(room), ...(room.parts ?? []).map(segment => segment.sessionId), ...Object.values(room.sessions ?? {}), ...Object.values(room.segments ?? {}).flat().map(segment => segment.sessionId)].filter(Boolean)) renewMemory(sessionId)summaries.delete(room.id)summaryFailures.delete(room.id)news.delete(room.id)@@ -1347,7 +1347,7 @@ export function install(rt) {if (body.roomId !== undefined && body.roomId !== null) {const room = rt.roomOf(String(body.roomId))if (room === undefined) throw new Error('Unknown group chat')- return { id: room.id, name: room.name, group: true, keeper: keeperOf(room), tag: { sessionId: room.id, kind: 'memory' }, scopes: { group: groupScope(room.id) } }+ return { id: room.id, name: room.name, group: true, keeper: keeperOf(room), tag: { sessionId: rt.sessionOfRoom(room), kind: 'memory' }, scopes: { group: groupScope(room.id) } }}const bot = rt.botOf(String(body.botId ?? ''))if (bot === undefined) throw new Error('Unknown Bot')diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex fa6d15f3..273f9118 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -318,12 +318,21 @@ export function install(rt) {}, 'ds-bot: Bot compaction')ctx.on('agent/created', ({ agent }) => { adoptCompaction(agent) })- // A Bot's own chat, or its Session in one group, as numbered parts, oldest first;- // the last one is current.+ // A Bot's own chat, or its Session in one group, or the group's own Session+ // (`botId === undefined`), as numbered parts, oldest first; the last one is+ // current.function partsOf(botId, roomId) {+ const room = rt.roomOf(roomId)+ if (botId === undefined) {+ if (room === undefined) return []+ const earlier = room.parts ?? []+ const parts = earlier.map((segment, index) => ({ ...segment, number: index + 1, startedAt: earlier[index - 1]?.endedAt ?? room.createdAt }))+ const current = rt.sessionOfRoom(room)+ if (current !== undefined) parts.push({ sessionId: current, number: parts.length + 1, startedAt: earlier.at(-1)?.endedAt ?? room.createdAt })+ return parts+ }const bot = rt.botOf(botId)if (bot === undefined) return []- const room = rt.roomOf(roomId)const earlier = (room ? room.segments?.[botId] : bot.segments) ?? []const current = room ? room.sessions?.[botId] : rt.chatOf(botId)const parts = earlier.map((segment, index) => ({ ...segment, number: index + 1, startedAt: earlier[index - 1]?.endedAt ?? bot.createdAt }))@@ -644,14 +653,16 @@ 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, segment, lines, number, resume, overflow, failed, bare, folder }) {- const where = room ? `your conversation in the group chat "${room.name}"` : 'your own chat with the user'- const lookup = room- ? 'read_group_chat shows the group\'s latest messages, and read_own_chat your own chat.'- : 'read_own_chat searches every part, reads around an anchor such as [part 2 #1234 · …], and shows the note that closed any earlier part.'+ function handoffPackage({ room, self = false, segment, lines, number, resume, overflow, failed, bare, folder }) {+ 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+ ? 'read_own_chat searches every part, reads around an anchor such as [part 2 #1234 · …], and shows the note that closed any earlier part.'+ : self ? 'the earlier part stays in the group\'s saved record.'+ : '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 ? `your working folder changed to ${folder}` : 'the previous part grew long'+ : folder !== undefined ? `${self ? 'the group\'s' : 'your'} working folder changed to ${folder}` : 'the previous part grew long'const { recent, earlier, unlisted, complete } = linesconst omitted = [...(unlisted > 0 ? [`(${unlisted} older messages are not listed.)`] : []),@@ -722,9 +733,13 @@ export function install(rt) {const botId = rt.chatOwners.get(sessionId)if (botId !== undefined) return { botId }const owner = rt.groupOwners.get(sessionId)- return owner && { botId: owner.botId, roomId: owner.roomId }+ if (owner !== undefined) return { botId: owner.botId, roomId: owner.roomId }+ const roomId = rt.roomOwners.get(sessionId)+ return roomId === undefined ? undefined : { roomId }}- const currentOf = owner => (owner.roomId === undefined ? rt.chatOf(owner.botId) : rt.roomOf(owner.roomId)?.sessions?.[owner.botId])+ const currentOf = owner => (owner.roomId === undefined ? rt.chatOf(owner.botId)+ : owner.botId === undefined ? rt.sessionOfRoom(rt.roomOf(owner.roomId))+ : rt.roomOf(owner.roomId)?.sessions?.[owner.botId])const grown = (sessionId, tokens, lines) => tokens >= (partBase.get(sessionId) ?? 0) + lines.check / 4// A read-only process (another dsh holds the team) neither condenses nor switches.const readOnly = () => rt.readOnly() !== undefined@@ -824,8 +839,9 @@ export function install(rt) {switches.set(agent.id, job)void runSwitch(agent, job).catch(error => {- if (unloaded(error)) return noteInfo('ds-bot: plugin unloaded while %s switched parts; input kept in part %s', rt.botOf(job.botId)?.name ?? agent.id, agent.id)- rt.warn('ds-bot: %s did not move on to a fresh part: %s', rt.botOf(job.botId)?.name ?? agent.id, error)+ const name = rt.botOf(job.botId)?.name ?? rt.roomOf(job.roomId)?.name ?? agent.id+ if (unloaded(error)) return noteInfo('ds-bot: plugin unloaded while %s switched parts; input kept in part %s', name, agent.id)+ rt.warn('ds-bot: %s did not move on to a fresh part: %s', name, error)}).finally(async () => {switches.delete(agent.id)@@ -838,7 +854,7 @@ export function install(rt) {noteFailures.delete(agent.id)folderRetry.delete(agent.id)// The folder may have changed again while the switch ran.- if (job.roomId === undefined) void followFolder(job.botId)+ void followFolder(job)return}if (folder) folderRetry.set(agent.id, Date.now() + FOLDER_RETRY_MS)@@ -902,27 +918,30 @@ export function install(rt) {}}- // A fresh part runs on the Bot's model. The earlier part's route is what its last- // request used, which misses a model the user picked since, so it counts only for a- // Bot without a model of its own.+ // A fresh part runs on the Bot's model; the group's own Session, which has no Bot,+ // keeps the earlier part's route. That route is what its last request used, which+ // misses a model the user picked since, so it counts only for a conversation+ // without a model of its own.async function freshRoute(bot, session) {- const ref = await rt.desiredModel(bot)+ const ref = bot === undefined ? undefined : await rt.desiredModel(bot)if (ref !== undefined) return { ref, effort: await rt.desiredEffort(bot, ref) }const route = session.requestHeader()?.configreturn route?.provider && route?.model ? { ref: `${route.provider}/${route.model}`, effort: route.reasoningEffort } : undefined}- const selectRoute = (bot, sessionId, { ref, effort }) => rt.selectSessionModel(sessionId, { ...splitRef(ref), ...(effort === undefined ? {} : { reasoningEffort: effort }) })- .catch(error => rt.warn('ds-bot: model for the fresh part of %s not applied: %s', bot.name, error))+ const selectRoute = (named, sessionId, { ref, effort }) => rt.selectSessionModel(sessionId, { ...splitRef(ref), ...(effort === undefined ? {} : { reasoningEffort: effort }) })+ .catch(error => rt.warn('ds-bot: model for the fresh part of %s not applied: %s', named.name, error))async function moveOn(agent, job, signal) {job.started = true- const bot = rt.botOf(job.botId)+ const bot = job.botId === undefined ? undefined : rt.botOf(job.botId)const room = rt.roomOf(job.roomId)- if (bot === undefined || (job.roomId !== undefined && room === undefined)) return+ if (bot === undefined ? room === undefined+ : job.roomId !== undefined && (room === undefined || !room.members.includes(bot.id))) return+ const name = bot?.name ?? room?.name ?? agent.idconst session = agent.sessionconst tokens = tokensOf(session)const lines = await contextLines(session).catch(() => undefined)- const parts = partsOf(bot.id, room?.id)+ const parts = bot === undefined ? partsOf(undefined, room.id) : partsOf(bot.id, room?.id)const number = parts.lengthconst budget = Math.min(RECENT_TOKENS, Math.floor((lines?.check ?? 4 * RECENT_TOKENS) / 4))const readLines = () => (job.bare ? { recent: [], earlier: [], unlisted: 0, complete: true } : handoffLines(agent.id, { budget, group: room !== undefined, number }))@@ -931,7 +950,8 @@ export function install(rt) {const whole = carried?.whole === true && !session.deriveMessages().some(message => message.role === 'tool')let writtenlet failure- if (!job.overflow && job.failed === undefined && !whole) {+ // 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) {try {written = await writeNote(agent, AbortSignal.any([signal, AbortSignal.timeout(NOTE_TIMEOUT_MS)]), { folder: job.folder })} catch (error) {@@ -946,10 +966,10 @@ export function install(rt) {const wait = NOTE_COOLDOWN_MS[Math.min(count, NOTE_COOLDOWN_MS.length) - 1]noteFailures.set(agent.id, { count, until: Date.now() + wait })job.noteFailed = true- rt.warn('ds-bot: handoff note for %s failed (%d in a row); part %d goes on, next try in %ds: %s', bot.name, count, number, wait / 1000, failure)+ rt.warn('ds-bot: handoff note for %s failed (%d in a row); part %d goes on, next try in %ds: %s', name, count, number, wait / 1000, failure)return}- if (failure !== undefined) rt.warn('ds-bot: handoff note for %s failed past the hard line; moving on with the earlier note: %s', bot.name, failure)+ 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 }: { fallback: whole ? 'whole' : job.failed !== undefined ? 'failure' : job.overflow ? 'overflow' : 'failed', ...(previous?.note ? { note: previous.note, noteFrom: previous.noteFrom ?? previous.number } : {}) }@@ -957,22 +977,26 @@ export function install(rt) {if (signal.aborted) throw signal.reasonconst dir = rt.workDirOf(job)const intended = dir !== undefined && await rt.isFolder(dir) ? dir : rt.teamFolder()- const freshId = await rt.createSession(room ? `${bot.name} · ${room.name}` : bot.name, { dir })+ const freshId = await rt.createSession(room === undefined ? name : bot === undefined ? room.name : `${name} · ${room.name}`, { dir })const picked = await freshRoute(bot, session)- if (picked !== undefined) await selectRoute(bot, freshId, picked)- await rt.applyPermission(bot, freshId, room)- .catch(error => rt.warn('ds-bot: permission for the fresh part of %s not applied: %s', bot.name, error))+ if (picked !== undefined) await selectRoute({ name }, freshId, picked)+ if (bot !== undefined) await rt.applyPermission(bot, freshId, room)+ .catch(error => rt.warn('ds-bot: permission for the fresh part of %s not applied: %s', name, error))// The fresh part took several awaits: a Bot or group deleted meanwhile, a member that// left, or a part that is no longer the current one gets no fresh part.- const current = room !== undefined ? room.sessions?.[bot.id] : rt.chatOf(bot.id)- const gone = rt.botOf(bot.id) === undefined || (room !== undefined && (rt.roomOf(room.id) !== room || !room.members.includes(bot.id)))+ const current = bot === undefined ? rt.sessionOfRoom(room) : room === undefined ? rt.chatOf(bot.id) : room.sessions?.[bot.id]+ const gone = bot === undefined ? rt.roomOf(room.id) !== room+ : rt.botOf(bot.id) === undefined || (room !== undefined && (rt.roomOf(room.id) !== room || !room.members.includes(bot.id)))if (gone || current !== agent.id) {await ctx.workspaceRegistry.archiveSession(freshId, { stopActivity: true })- .catch(error => rt.warn('ds-bot: unused fresh part of %s not archived: %s', bot.name, error))+ .catch(error => rt.warn('ds-bot: unused fresh part of %s not archived: %s', name, error))return}const segment = { sessionId: agent.id, endedAt: Date.now(), ...(tokens !== undefined ? { tokens } : {}), ...noted }- if (room !== undefined) {+ if (bot === undefined) {+ ;(room.parts ??= []).push(segment)+ room.sessionId = freshId+ } else if (room !== undefined) {room.segments ??= {};(room.segments[bot.id] ??= []).push(segment)room.sessions[bot.id] = freshId@@ -996,7 +1020,7 @@ export function install(rt) {// A model the user picked until now went to the earlier part, which was still the// Bot's; from here on a change goes to the fresh one.const now = await freshRoute(bot, session)- if (now !== undefined && (now.ref !== picked?.ref || now.effort !== picked?.effort)) await selectRoute(bot, freshId, now)+ if (now !== undefined && (now.ref !== picked?.ref || now.effort !== picked?.effort)) await selectRoute({ name }, freshId, now)if (job.failed !== undefined) rescued.set(freshId, job.bare ? 'bare' : 'carried')job.moved = trueconst resume = job.resume || job.overflow@@ -1013,9 +1037,9 @@ export function install(rt) {// A fresh part that is not where it was made for would move on at every step.if (intended !== undefined && cwd !== undefined && cwd !== intended) {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', bot.name, intended, cwd)+ 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, 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 })freshParts.set(freshId, estimateTokens(text))fresh.followup(createUserMessage({ content: [{ type: 'text', text }], source: handoffSource(job, resume) }))await ctx.sessions.flush(fresh.session)@@ -1035,7 +1059,7 @@ export function install(rt) {throw error})}- ctx.logger.info('ds-bot: %s%s moved on to part %d at %d tokens (check line %d, hard line %d); %s; %d latest and %d earlier messages carried%s', bot.name, room ? ` in ${room.name}` : '', number + 1, tokens ?? -1, lines?.check ?? -1, lines?.hard ?? -1,+ ctx.logger.info('ds-bot: %s%s moved on to part %d at %d tokens (check line %d, hard line %d); %s; %d latest and %d earlier messages carried%s', name, bot !== undefined && room !== undefined ? ` in ${room.name}` : '', number + 1, tokens ?? -1, lines?.check ?? -1, lines?.hard ?? -1,written !== undefined ? `note written in ${written.attempts} attempt(s)` : `note put together by DS Bot (${noted.fallback}${noted.note ? `, carries part ${noted.noteFrom}'s` : ', nothing to carry'})`,carried.recent.length, carried.earlier.length, folder === undefined ? '' : `; now works in ${folder}`)}@@ -1051,7 +1075,8 @@ export function install(rt) {await forward(past, payload.messages).catch(error => rt.warn('ds-bot: input for %s was not handed on: %s', agent.id, error))return { kind: 'reject' }}- if (!rt.isBotSession(agent.id)) return next()+ const place = placeOf(agent.id)+ if (place === undefined) return next()adoptCompaction(agent)const job = switches.get(agent.id)if (job !== undefined) {@@ -1064,6 +1089,9 @@ export function install(rt) {partBase.set(agent.id, (tokensOf(agent.session) ?? 0) + fresh)}if (!readOnly() && await folderMove(agent, { midTurn: payload.step > 1 }) !== undefined) return switchBeforeStep(agent, payload, { folder: true })+ // 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()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()@@ -1132,15 +1160,16 @@ export function install(rt) {}, { prepend: true })// A Bot's own chat moves to its new folder now when it is idle; a running turn- // moves at its next step, and each group conversation at its next turn there.- async function followFolder(botId) {- const sessionId = rt.chatOf(botId)+ // moves at its next step, and each group conversation at its next turn there. The+ // group's own Session follows the same way when the group's folder changes.+ async function followFolder(owner) {+ const sessionId = currentOf(owner)if (sessionId === undefined || switches.has(sessionId) || readOnly()) returntry {const agent = await rt.resolveAgent(sessionId)if (agent.status === 'idle' && await folderMove(agent) !== undefined) startSwitch(agent, { folder: true })} catch (error) {- rt.warn('ds-bot: %s did not move to its working folder: %s', rt.botOf(botId)?.name ?? botId, error)+ rt.warn('ds-bot: %s did not move to its working folder: %s', owner.botId === undefined ? rt.roomOf(owner.roomId)?.name ?? owner.roomId : rt.botOf(owner.botId)?.name ?? owner.botId, error)}}diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.jsindex e08a2a00..04391b55 100644--- a/ds-bot/src/host/roster.js+++ b/ds-bot/src/host/roster.js@@ -352,7 +352,7 @@ 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 })- if (moved) void rt.followFolder(bot.id)+ if (moved) void rt.followFolder({ botId: bot.id })if (bot.model && bot.kickoff !== undefined) {const held = bot.kickoffdelete bot.kickoff@@ -387,7 +387,7 @@ export function install(rt) {async function retitleRoom(room) {try {- const agent = await rt.resolveAgent(room.id)+ const agent = await rt.resolveAgent(rt.sessionOfRoom(room))await ctx.sessionTitle.rename(agent.session, room.name)} catch (error) {rt.warn('ds-bot: group title for %s not updated: %s', room.name, error)@@ -427,8 +427,8 @@ export function install(rt) {async function buildRoom({ members, custom, notice, mode, adminId, createdBy }) {const title = custom || autoRoomName(members)- // The group's own Session only relays, so it stays in the team workspace; the- // group's folder is for its members' Sessions.+ // The group's own Session only relays; like a member's it moves to a fresh part+ // in the group's folder once the group has one (parts.js).const id = await createSession(title)try {// A member deleted while the Session was made stays out, and the group is checked@@ -535,7 +535,8 @@ export function install(rt) {room.notice = noticechanges.push(notice ? 'updated the notice' : 'cleared the notice')}- // Members' group conversations move on to the folder at their next turn there.+ // Members' group conversations move on to the folder at their next turn there;+ // the group's own Session moves the same way, now when it is idle.if (moving && workDir !== room.workDir) {if (workDir === undefined) delete room.workDirelse room.workDir = workDir@@ -543,6 +544,7 @@ export function install(rt) {// cleared one does not bring it back.delete room.memberDirschanges.push(workDir ? `every member now works in ${workDir} here` : 'every member works in its own folder again')+ void rt.followFolder({ roomId: room.id })}const before = room.nameif (name !== undefined) {@@ -572,6 +574,8 @@ export function install(rt) {// Before the group's Sessions leave the state, which the archive reads.const archived = rt.archiveGroupMemory(room)for (const botId of Object.keys(room.sessions ?? {})) rt.dropGroupSession(room, botId)+ for (const segment of room.parts ?? []) delete state.switching[segment.sessionId]+ delete state.switching[rt.sessionOfRoom(room)]delete state.rooms[id]rt.roomInbox.delete(id)rt.dropGroupLines(id)@@ -579,7 +583,7 @@ export function install(rt) {const failed = await saveForDelete()// Armed scheduled tasks refuse a plain archive and would keep delivering into// the deleted group; the session-stop that stopActivity runs removes them.- await ctx.workspaceRegistry.archiveSession(id, { stopActivity: true })+ await ctx.workspaceRegistry.archiveSession(rt.sessionOfRoom(room), { stopActivity: true }).catch(error => rt.warn('ds-bot: group chat %s not archived: %s', room.name, error))if (failed !== undefined) throw failed}diff --git a/ds-bot/src/host/schedules.js b/ds-bot/src/host/schedules.jsindex 1d14a37f..02b5f3c5 100644--- a/ds-bot/src/host/schedules.js+++ b/ds-bot/src/host/schedules.js@@ -85,7 +85,8 @@ export function install(rt) {const ownerOf = (sessionId) => {const chat = rt.chatOwners.get(sessionId)if (chat !== undefined) return { botId: chat }- if (rt.roomOf(sessionId) !== undefined) return { roomId: sessionId }+ const room = rt.roomOf(sessionId)+ if (room !== undefined) return { roomId: room.id }return rt.groupOwners.get(sessionId) ?? rt.pastOwners.get(sessionId)}const known = owner => owner !== undefined && (owner.botId === undefined ? rt.roomOf(owner.roomId) !== undefined : rt.botOf(owner.botId) !== undefined)@@ -113,7 +114,7 @@ export function install(rt) {if (title === '') throw invalid('Give the task a name')if (title.length > MAX_TITLE) throw invalid(`Keep the name under ${MAX_TITLE} characters`)if (prompt === '') throw invalid('Say what the Bot should do')- await service.create(bot ? rt.chatOf(bot.id) : room.id, { title, prompt, ...selectorOf(body.when) })+ await service.create(bot ? rt.chatOf(bot.id) : rt.sessionOfRoom(room), { title, prompt, ...selectorOf(body.when) })return schedulesView()},async 'schedule-delete'(body) {diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.jsindex a7c57295..5a3642e8 100644--- a/ds-bot/src/host/store.js+++ b/ds-bot/src/host/store.js@@ -344,7 +344,11 @@ export function install(rt) {}, 'ds-bot: state lock')const botOf = id => (id === undefined ? undefined : own(state.bots, id))- const roomOf = id => (id === undefined ? undefined : own(state.rooms, id))+ // A group's own Session moves on to a fresh part when the group's folder no longer+ // matches the one it was made in (parts.js), like a Bot's own chat: `room.id` stays+ // the first Session's id and `room.sessionId` the current one, so the group keeps+ // one identity while its Session moves. `roomOwners` maps the current Session.+ const roomOf = id => (id === undefined ? undefined : own(state.rooms, id) ?? own(state.rooms, roomOwners.get(id)))const isMain = id => id !== undefined && state.mainBotIds.includes(id)// Group Sessions. A member speaks in each group from a hidden Session of its own,@@ -353,26 +357,35 @@ export function install(rt) {// member's private context. Created on the member's first turn in the group.//// Segments. A long conversation moves to a fresh Session at a context line (see- // parts.js). A Bot's id is the Session id of its first own-chat segment and- // never changes; `bot.sessionId` is the current one. Earlier segments, of the own- // chat (`bot.segments`) and of each group Session (`room.segments[botId]`), are+ // parts.js), and a group's own Session to a fresh part when the group's folder+ // changes. A Bot's id is the Session id of its first own-chat segment and never+ // changes; `bot.sessionId` is the current one, and `room.sessionId` the group's.+ // Earlier segments, of the own chat (`bot.segments`), of each group Session+ // (`room.segments[botId]`) and of the group's own Session (`room.parts`), are// archived and stay readable./** @type {Map<string, string>} */const chatOwners = new Map()/** @type {Map<string, {botId:string, roomId:string}>} */const groupOwners = new Map()- /** @type {Map<string, {botId:string, roomId?:string}>} */+ /** @type {Map<string, string>} */+ const roomOwners = new Map()+ /** @type {Map<string, {botId?:string, roomId?:string}>} */const pastOwners = new Map()const chatOf = botId => botOf(botId)?.sessionId ?? botId+ const sessionOfRoom = room => (room === undefined ? undefined : room.sessionId ?? room.id)const indexSessions = () => {chatOwners.clear()groupOwners.clear()+ roomOwners.clear()pastOwners.clear()for (const bot of Object.values(state.bots)) {for (const segment of bot.segments ?? []) pastOwners.set(segment.sessionId, { botId: bot.id })chatOwners.set(chatOf(bot.id), bot.id)}for (const room of Object.values(state.rooms)) {+ const sessionId = sessionOfRoom(room)+ if (sessionId !== undefined) roomOwners.set(sessionId, room.id)+ for (const segment of room.parts ?? []) pastOwners.set(segment.sessionId, { roomId: room.id })for (const [botId, segments] of Object.entries(room.segments ?? {})) {for (const segment of segments) pastOwners.set(segment.sessionId, { botId, roomId: room.id })}@@ -430,8 +443,8 @@ export function install(rt) {Object.assign(rt, {state, load, save, refresh, readOnly, own,- botOf, roomOf, isMain, chatOf, selfOf, isBotSession,- chatOwners, groupOwners, pastOwners,+ botOf, roomOf, isMain, chatOf, sessionOfRoom, selfOf, isBotSession,+ chatOwners, groupOwners, roomOwners, pastOwners,groupSessionsOf, dropGroupSession, retireGroupSession, findBot, findRooms, isAdminOf,})}diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex 3a6cc69d..2ef99290 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -379,10 +379,11 @@ export function install(rt) {const botId = owner?.botId ?? rt.chatOwners.get(id)if (botId !== undefined) merged[botId] ??= 'working'}- // A Bot writing its handoff note is thinking.+ // A Bot writing its handoff note is thinking; a group's own Session that moves+ // shows on the group's key.for (const job of rt.switchJobs()) {if (job.roomId === undefined) merged[job.botId] = 'thinking'- else merged[job.botId] ??= 'thinking'+ else merged[job.botId ?? job.roomId] ??= 'thinking'}for (const approval of rt.approvalsView?.() ?? []) merged[approval.botId] = 'alert'// Waiting for work it handed on shows only while no turn of the Bot runs.@@ -428,7 +429,9 @@ export function install(rt) {bots[botId] = { ...sub, ...(owner ? { roomId: owner.roomId } : {}) }}for (const job of rt.switchJobs()) {- // `folder` marks the switch the chat must name: the working folder changed.+ // `folder` marks the switch the chat must name: the working folder changed. A+ // group's own Session belongs to no Bot; the group's row shows it instead.+ if (job.botId === undefined) continueconst work = { since: job.since, switching: true, ...(job.folder === true ? { folder: true } : {}), ...(job.roomId ? { roomId: job.roomId } : {}) }if (job.roomId === undefined) bots[job.botId] = workelse bots[job.botId] ??= work@@ -467,7 +470,8 @@ export function install(rt) {if (sub !== undefined) add(owner.roomId, owner.botId, sub)}for (const job of rt.switchJobs()) {- if (job.roomId !== undefined) add(job.roomId, job.botId, { since: job.since, switching: true, ...(job.folder === true ? { folder: true } : {}) })+ // `self`: the group's own Session moves; the group's activity row names it.+ if (job.roomId !== undefined) add(job.roomId, job.botId, { since: job.since, switching: true, ...(job.folder === true ? { folder: true } : {}), ...(job.botId === undefined ? { self: true } : {}) })}return rooms}@@ -641,7 +645,7 @@ export function install(rt) {if (source?.kind === SOURCE_KIND && source.role === 'post' && rt.roomOf(id)) {// A long post comes as a file (attachLong), which stays with its line.const files = (Array.isArray(event.data.content) ? event.data.content : []).filter(block => block?.type === 'file' && block.attachment !== undefined).map(block => block.attachment)- queueRoomMessage(id, {+ queueRoomMessage(rt.roomOf(id).id, {text: textOf(event.data.content).replace(/^\[Group post from (?:[^\r\n]*\]\r?\n|[^\]\r\n]*\])/, ''),...(files.length > 0 ? { files } : {}),botId: source.senderSessionId,@@ -664,7 +668,7 @@ export function install(rt) {...(source.called ? { called: true } : {}),})} else if (source?.kind === SOURCE_KIND && source.role === 'kickoff' && rt.roomOf(id)) {- queueRoomMessage(id, { text: '', kickoff: true })+ queueRoomMessage(rt.roomOf(id).id, { text: '', kickoff: true })} else if (source?.kind === SOURCE_KIND) {if (entry.turn === undefined) {entry.pending = source@@ -689,15 +693,15 @@ export function install(rt) {// claims the running turn nor queues as the next one's trigger.} else if (source?.kind === 'schedule' && rt.roomOf(id)) {// A group's scheduled task reaches the group as the user's message.- queueRoomMessage(id, { text: reminderText(textOf(event.data.content)) })+ queueRoomMessage(rt.roomOf(id).id, { text: reminderText(textOf(event.data.content)) })} else if (source?.kind === REFERENCE_KIND && rt.roomOf(id)) {- attachReference(roomInbox.get(id), source, textOf(event.data.content))+ attachReference(roomInbox.get(rt.roomOf(id).id), source, textOf(event.data.content))} else if (source?.kind === 'user' || source?.kind === REPLY_KIND) {if (rt.roomOf(id) && source.kind === 'user') {const content = Array.isArray(event.data.content) ? event.data.content : []const images = content.filter(block => block?.type === 'image' && !block.offloaded).map(block => block.attachment)const files = content.filter(block => block?.type === 'file' && block.attachment !== undefined).map(block => block.attachment)- queueRoomMessage(id, { text: textOf(event.data.content), ...(images.length > 0 ? { images } : {}), ...(files.length > 0 ? { files } : {}) })+ queueRoomMessage(rt.roomOf(id).id, { text: textOf(event.data.content), ...(images.length > 0 ? { images } : {}), ...(files.length > 0 ? { files } : {}) })}const own = rt.chatOwners.get(id)if (own !== undefined) rt.dropKickoff(own)@@ -717,7 +721,7 @@ export function install(rt) {}case 'agent/inbox/spliced':// A message the user sends to a group while its round runs joins that round.- if (rt.roomOf(id)) rt.nudgeRoom?.(id)+ if (rt.roomOf(id)) rt.nudgeRoom?.(rt.roomOf(id).id)if (stoppedSubagentParents.has(id)) {for (const inserted of event.data?.inserted ?? []) {if (inserted?.source?.kind === 'subagent-settled' || stoppedSubagents.has(inserted?.source?.senderSessionId)) {diff --git a/ds-bot/src/host/usage.js b/ds-bot/src/host/usage.jsindex d19c0f8c..d6b2ecbe 100644--- a/ds-bot/src/host/usage.js+++ b/ds-bot/src/host/usage.js@@ -287,7 +287,7 @@ export function install(rt) {for (const sessionId of [bot.id, rt.chatOf(bot.id), ...(bot.segments ?? []).map(segment => segment.sessionId)]) owners.set(sessionId, botOwner(bot))}for (const room of Object.values(state.rooms)) {- owners.set(room.id, { owner: `room:${room.id}`, name: room.name })+ for (const sessionId of [rt.sessionOfRoom(room), ...(room.parts ?? []).map(segment => segment.sessionId)].filter(Boolean)) owners.set(sessionId, { owner: `room:${room.id}`, name: room.name })const memberOwner = botId => ({ owner: botId, name: rt.botOf(botId)?.name ?? '' })for (const [botId, sessionId] of Object.entries(room.sessions ?? {})) owners.set(sessionId, memberOwner(botId))for (const [botId, segments] of Object.entries(room.segments ?? {})) {diff --git a/ds-bot/test/work-dir.test.js b/ds-bot/test/work-dir.test.jsindex a682b76c..e7b78dd2 100644--- a/ds-bot/test/work-dir.test.js+++ b/ds-bot/test/work-dir.test.js@@ -46,6 +46,7 @@ async function start({ services = {}, workspaces = [], llm, team: saved = TEAM,const ctx = fakeContext({ services })const created = []+ const archived = []const cwds = new Map()const agents = new Map()const agentOf = (sessionId) => {@@ -79,7 +80,7 @@ async function start({ services = {}, workspaces = [], llm, team: saved = TEAM,registry.set(workspace.id, workspace)return workspace},- archiveSession: async () => {},+ archiveSession: async (id, options) => { archived.push([id, options]) },},sessionController: {create: async (options) => {@@ -124,7 +125,7 @@ async function start({ services = {}, workspaces = [], llm, team: saved = TEAM,}// Loading once fills the Session-owner indexes.await tool('list_bots', {}, 'a')- return { ctx, root, dsh, home, team, project, created, agentOf, call, tool, preStep, state, workingIn, stop }+ return { ctx, root, dsh, home, team, project, created, archived, agentOf, call, tool, preStep, state, workingIn, stop }}const settle = () => new Promise(resolve => setTimeout(resolve, 20))@@ -288,14 +289,15 @@ test('a group\'s folder holds for every member there; only the user or a Main Boassert.equal(requests.length, 0)assert.match(await tool('list_bots', {}, 'a'), new RegExp(`"Ops" — .*; members work in ${escapeRegExp(project)} here`))- // The member's group Session moves at its next turn there, not within a reply; its- // own chat stays.+ // The group's own Session moves at once; the member's group Session moves at its+ // next turn there, not within a reply; its own chat stays.+ await until(() => state().rooms.r1.sessionId === 's1')assert.equal(await preStep('b'), 'next')assert.equal(await preStep('gb', [], 2), 'next')- assert.deepEqual(created, [])- assert.deepEqual(await preStep('gb'), { kind: 'reject' })- await until(() => state().rooms.r1.sessions.b === 's1')assert.deepEqual(created, [{ cwd: project }])+ assert.deepEqual(await preStep('gb'), { kind: 'reject' })+ await until(() => state().rooms.r1.sessions.b === 's2')+ assert.deepEqual(created, [{ cwd: project }, { cwd: project }])assert.equal(state().bots.b.sessionId, 'b')// A Main Bot clears it without asking; setting it asks the user once for every member.@@ -340,14 +342,16 @@ test('a group\'s permissions hold for every member there in place of its own, unassert.equal((await call('update-bot', { id: 'b', permission: 'danger-full-access' })).ok, true)assert.deepEqual([presetOf.get('b'), presetOf.get('gb')], ['danger-full-access', 'read-only'])- // A fresh part of the group conversation starts on the group's preset.+ // A fresh part of the group conversation starts on the group's preset; the group's+ // own Session moved for the folder first.await call('update-room', { id: 'r1', workDir: project })+ await until(() => state().rooms.r1.sessionId === 's1')assert.deepEqual(await preStep('gb'), { kind: 'reject' })- await until(() => state().rooms.r1.sessions.b === 's1')- assert.equal(presetOf.get('s1'), 'read-only')+ await until(() => state().rooms.r1.sessions.b === 's2')+ assert.equal(presetOf.get('s2'), 'read-only')await call('update-room', { id: 'r1', permission: null })- assert.equal(presetOf.get('s1'), 'danger-full-access')+ assert.equal(presetOf.get('s2'), 'danger-full-access')})test('the approval counts every Session that would work in the folder', async (t) => {@@ -1006,57 +1010,43 @@ test('a member cannot pick the folder of a private Bot inside a group', async (tassert.equal(state().rooms.r1.memberDirs, undefined)})-test('a group folder change leaves the group\'s own Session as it was made', async (t) => {- const { call, created, agentOf, preStep, project, team, state, stop } = await start()+test('a group folder change moves the group\'s own Session to a part in the folder', async (t) => {+ const { call, created, archived, agentOf, project, team, state, stop } = await start()t.after(stop)assert.equal((await call('update-room', { id: 'r1', workDir: project })).ok, true)- assert.equal(state().rooms.r1.id, 'r1')- // A Session's header is creation metadata DSH owns: the relay Session stays in the- // team workspace, and no fresh Session is made for the group.- assert.equal(agentOf('r1').session.header.cwd, team)- assert.equal(state().rooms.r1.sessions.b, 'gb')- assert.deepEqual(created, [])-- assert.deepEqual(await preStep('gb'), { kind: 'reject' })- await until(() => state().rooms.r1.sessions.b === 's1')+ // The group keeps its identity while its own Session moves to a fresh part in the+ // folder, the way a Bot's own chat does: the next turn runs in the new Session.+ await until(() => state().rooms.r1.sessionId === 's1')+ await until(() => handoffOf(agentOf('s1')) !== undefined)assert.deepEqual(created, [{ cwd: project }])assert.equal(state().rooms.r1.id, 'r1')+ assert.equal(agentOf('s1').session.header.cwd, project)+ // The earlier part stays in the record and is archived, never written again.+ assert.deepEqual(state().rooms.r1.parts.map(segment => [segment.sessionId, segment.fallback]), [['r1', 'whole']])+ assert.deepEqual(archived.filter(([id]) => id === 'r1').length, 1)assert.equal(agentOf('r1').session.header.cwd, team)+ // The member's own chat and its group Session are untouched.+ assert.equal(state().bots.b.sessionId, 'b')+ assert.equal(state().rooms.r1.sessions.b, 'gb')+ assert.equal(agentOf('b').session.header.cwd, team)+ // The group's Session goes back to the team workspace when the folder is cleared.assert.equal((await call('update-room', { id: 'r1', workDir: '' })).ok, true)assert.equal(state().rooms.r1.workDir, undefined)+ await until(() => state().rooms.r1.sessionId === 's2')+ assert.deepEqual(created.map(options => options.cwd ?? options.workspaceId), [project, 'w1'])+ assert.deepEqual(state().rooms.r1.parts.map(segment => segment.sessionId), ['r1', 's1'])assert.equal(state().rooms.r1.id, 'r1')- assert.equal(agentOf('r1').session.header.cwd, team)- assert.equal(state().rooms.r1.sessions.b, 's1')})-test('the file panel of a group with a folder lists that folder', async (t) => {- // The workspaceFileScope lookup answers what the file panel lists; until DS Bot's- // resolver answers for the group's own Session, the provider's own resolution runs.- const resolved = []- const provider = { resolve: async id => { resolved.push(id); return { sessionId: id, workspaceRoot: `/header-${id}` } } }- let resolver- const typert = { lookups: {- get: key => (key === 'workspaceFileScope' ? provider : undefined),- configure: (key, next) => { resolver = next; return () => {} },- } }- const { call, project, stop } = await start({ services: { typert } })+test('the file panel of a group with a folder lists the Session\'s own folder', async (t) => {+ // DSH's file panel lists a Session at the folder the Session was made in, so no+ // lookup override is needed once the group's own Session moved there.+ const { call, agentOf, project, state, stop } = await start()t.after(stop)- assert.deepEqual(await resolver('r1'), { sessionId: 'r1', workspaceRoot: '/header-r1' })-assert.equal((await call('update-room', { id: 'r1', workDir: project })).ok, true)- assert.deepEqual(await resolver('r1'), { sessionId: 'r1', workspaceRoot: project })- // A member's Session and every other Session still resolve as the provider would.- assert.deepEqual(await resolver('gb'), { sessionId: 'gb', workspaceRoot: '/header-gb' })- assert.deepEqual(resolved, ['r1', 'gb'])-- // A folder gone from disk resolves as the provider would have it, not as an error.- rmSync(project, { recursive: true })- assert.deepEqual(await resolver('r1'), { sessionId: 'r1', workspaceRoot: '/header-r1' })- mkdirSync(project)-- assert.equal((await call('update-room', { id: 'r1', workDir: '' })).ok, true)- assert.deepEqual(await resolver('r1'), { sessionId: 'r1', workspaceRoot: '/header-r1' })+ await until(() => state().rooms.r1.sessionId === 's1')+ assert.equal(agentOf(state().rooms.r1.sessionId).session.header.cwd, project)})test('a group Session that cannot be opened still saves the folder', async (t) => {