Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Take an opened earlier part out of DSH's archive

Fei2411daf4dc8f1a92
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.js
index ce06af21..8d4ad299 100644
--- a/ds-bot/src/host/parts.js
+++ b/ds-bot/src/host/parts.js
@@ -1584,6 +1584,9 @@ export function install(rt) {
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' })
+ // DSH turns away every step of an archived Session and every task aimed at it, so
+ // the part leaves the archive before it becomes current.
+ await ctx.workspaceRegistry.unarchiveSession(partId)
segments.splice(at, 1)
segments.splice(at, 0, { sessionId: current, endedAt: Date.now() })
bot.sessionId = partId
@@ -1591,11 +1594,18 @@ export function install(rt) {
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()
+ // The replaced part is archived like any earlier part, once its tasks sit on the
+ // opened one: the stop that archiving runs removes the tasks still on it.
+ try {
+ await rt.moveSchedules?.(current, partId)
+ await ctx.workspaceRegistry.archiveSession(current, { stopActivity: true })
+ } catch (error) {
+ rt.warn('ds-bot: earlier part %s not archived: %s', current, error)
+ }
return true
}
diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.js
index 87675211..8eaa3d8e 100644
--- a/ds-bot/src/host/store.js
+++ b/ds-bot/src/host/store.js
@@ -440,6 +440,30 @@ export function install(rt) {
const pastOwners = new Map()
const chatOf = botId => botOf(botId)?.sessionId ?? botId
const sessionOfRoom = room => (room === undefined ? undefined : room.sessionId ?? room.id)
+ // DSH turns away every step of an archived Session and every task aimed at it, so a
+ // Session the team speaks from now leaves the archive: an earlier open of an old part
+ // could leave one there, and DSH's own Session list can archive one. Earlier parts
+ // stay archived.
+ let restoring
+ const restoreCurrent = () => {
+ const registry = ctx.workspaceRegistry
+ if (restoring !== undefined || readOnly() !== undefined || typeof registry?.unarchiveSession !== 'function') return
+ let archived
+ try {
+ archived = new Set(registry.archivedSessionIds ?? [])
+ } catch {
+ return
+ }
+ const held = [...chatOwners.keys(), ...groupOwners.keys(), ...roomOwners.keys()].filter(id => archived.has(id))
+ if (held.length === 0) return
+ restoring = (async () => {
+ for (const sessionId of held) {
+ await registry.unarchiveSession(sessionId)
+ .then(() => warn('ds-bot: current Session %s was archived in DSH; taken back out', sessionId))
+ .catch(error => warn('ds-bot: current Session %s is archived in DSH and could not be taken out: %s', sessionId, error))
+ }
+ })().finally(() => { restoring = undefined })
+ }
const indexSessions = () => {
chatOwners.clear()
groupOwners.clear()
@@ -463,6 +487,7 @@ export function install(rt) {
// live Agents that joined); both install after this.
rt.indexAgents?.()
rt.syncScopedTools?.()
+ restoreCurrent()
}
// The Bot a Session speaks for: its own chat, one of its group Sessions, or an
// earlier segment of either.
diff --git a/ds-bot/test/archived-parts.test.js b/ds-bot/test/archived-parts.test.js
new file mode 100644
index 00000000..2a23d38b
--- /dev/null
+++ b/ds-bot/test/archived-parts.test.js
@@ -0,0 +1,91 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { Context } from '@deepseek-ai/cordis'
+import { SessionId } from '@deepseek-ai/dsh-session'
+import * as Jsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
+import Storage from '@deepseek-ai/dsh-storage'
+import * as StorageDomain from '@deepseek-ai/dsh-storage-domain'
+import * as StorageJson from '@deepseek-ai/dsh-storage-json'
+import WorkspaceRegistry from '@deepseek-ai/dsh-workspace'
+import { createRuntime } from '../index.js'
+import { fakeContext } from './fake-ctx.js'
+
+// DSH 0.2.2 exports the JSONL persistence as a plugin module; earlier DSH as a default class.
+const SessionPersistence = typeof Jsonl.apply === 'function' ? Jsonl : Jsonl.default
+
+// DSH's own Workspace registry, which holds the archive, on files in a temporary folder.
+// The listed Sessions count as live, so they can be archived.
+async function dshRegistry(t, root, live) {
+ const host = new Context()
+ t.after(() => host.fiber.dispose())
+ await host.plugin(Storage)
+ await host.plugin(StorageJson, { root: join(root, 'storage') })
+ await host.plugin(StorageDomain, { backend: 'json' })
+ await host.plugin(SessionPersistence, { root: join(root, 'sessions') })
+ await host.plugin({ name: 'live-sessions', apply: inner => inner.provide('sessions', { list: () => [], get: id => (live.includes(id) ? {} : undefined) }) })
+ await host.plugin(WorkspaceRegistry)
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('the Workspace registry did not start')), 5000)
+ host.inject(['workspaceRegistry'], inner => {
+ clearTimeout(timer)
+ resolve(inner.workspaceRegistry)
+ })
+ })
+}
+
+// Writer's current part is `w2`, its earlier part `w1`; the group's own Session is `g1`
+// and Writer's Session in the group `gw`.
+const TEAM = {
+ version: 1,
+ mainBotIds: ['m1'],
+ revision: 1,
+ bots: {
+ m1: { id: 'm1', sessionId: 'm1', name: 'Chief', role: 'Chief of Staff', instructions: '', createdAt: 1 },
+ w1: { id: 'w1', sessionId: 'w2', name: 'Writer', role: '', instructions: '', createdAt: 2, segments: [{ sessionId: 'w1', endedAt: 3 }] },
+ },
+ rooms: { g1: { id: 'g1', name: 'Launch', named: true, members: ['m1', 'w1'], admin: 'm1', mode: 'admin', notice: '', createdAt: 4, sessions: { w1: 'gw' } } },
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+}
+
+async function team(t, archived) {
+ const home = mkdtempSync(join(tmpdir(), 'dsb-archived-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM))
+ const registry = await dshRegistry(t, join(home, 'dsh'), ['m1', 'w1', 'w2', 'g1', 'gw', 'outside'])
+ for (const id of archived) await registry.archiveSession(SessionId(id), { stopActivity: true })
+ const ctx = fakeContext({})
+ ctx.workspaceRegistry = registry
+ const register = ctx.connection.fetch.register
+ ctx.connection.fetch.register = (route) => { ctx.route = route; return register(route) }
+ createRuntime(ctx, { home })
+ t.after(async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) })
+ const call = async (endpoint, payload = {}) => (await ctx.route.fetch(new Request('http://localhost/api/bot', { method: 'POST', body: JSON.stringify({ endpoint, payload }) }))).json()
+ return { home, registry, call }
+}
+
+const settled = async (check) => {
+ for (let i = 0; i < 50 && !check(); i += 1) await new Promise(resolve => setTimeout(resolve, 10))
+}
+
+test('opening an earlier part takes it out of the archive and archives the part it replaces', async (t) => {
+ const { home, registry, call } = await team(t, ['w1'])
+ await call('state')
+ const result = await call('bot-open-part', { botId: 'w1', sessionId: 'w1' })
+ assert.equal(result.ok, true, JSON.stringify(result))
+ await settled(() => registry.archivedSessionIds.includes('w2'))
+ assert.deepEqual([...registry.archivedSessionIds].sort(), ['w2'])
+ const saved = JSON.parse(readFileSync(join(home, 'state.json'), 'utf8')).bots.w1
+ assert.equal(saved.sessionId, 'w1')
+ assert.deepEqual(saved.segments.map(segment => segment.sessionId), ['w2'])
+})
+
+test('current team Sessions held archived in DSH are taken back out; earlier parts stay', async (t) => {
+ const { registry, call } = await team(t, ['w1', 'w2', 'g1', 'gw', 'outside'])
+ await call('state')
+ await settled(() => registry.archivedSessionIds.length === 2)
+ assert.deepEqual([...registry.archivedSessionIds].sort(), ['outside', 'w1'])
+})