A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Usage: read subagent Sessions through their parent's address (#1)
Fei2411eedfb6526a71
diff --git a/ds-bot/src/host/usage.js b/ds-bot/src/host/usage.jsindex 525e6041..3ff63955 100644--- a/ds-bot/src/host/usage.js+++ b/ds-bot/src/host/usage.js@@ -320,7 +320,18 @@ export function install(rt) {...Object.values(room.segments ?? {}).flat().map(segment => segment.sessionId),]))- async function scanSession(ledger, sessionId, asOfSeq, sealable, signal) {+ // DSH reads a subagent Session only through its parent's address; the parent+ // need not exist any more. One with no parent on record cannot be read.+ const addressOf = item => (item.origin !== 'subagent'+ ? { kind: 'session', sessionId: item.sessionId }+ : item.parentSessionId === undefined+ ? undefined+ : { kind: 'subagent', parentSessionId: item.parentSessionId, childSessionId: item.sessionId, mode: 'unknown' })+ // Sessions that already failed to read, so each one warns once, not every scan.+ const unreadable = new Set()++ async function scanSession(ledger, address, asOfSeq, sealable, signal) {+ const sessionId = address.kind === 'session' ? address.sessionId : address.childSessionIdconst mark = ledger.mark(sessionId)if (mark?.sealed) returnlet through = asOfSeq@@ -338,7 +349,7 @@ export function install(rt) {let beforeSeqfor (let reached = false; !reached;) {const page = await ctx.sessionController.page({- address: { kind: 'session', sessionId },+ address,throughSeq: through,...(beforeSeq === undefined ? {} : { beforeSeq }),maxMessages: PAGE_MESSAGES,@@ -397,8 +408,19 @@ export function install(rt) {const targets = new Map()for (const item of listed) if (item.blank !== true) targets.set(item.sessionId, item.projections?.asOfSeq)for (const sessionId of owners.keys()) if (!targets.has(sessionId)) targets.set(sessionId, undefined)- await eachLimited([...targets], SCAN_PARALLEL, ([sessionId, asOfSeq]) => scanSession(ledger, sessionId, asOfSeq, ended.has(sessionId), signal)- .catch(error => rt.warn('ds-bot: usage could not read %s: %s', sessionId, error)))+ const addresses = new Map(listed.map(item => [item.sessionId, addressOf(item)]))+ await eachLimited([...targets], SCAN_PARALLEL, async ([sessionId, asOfSeq]) => {+ const address = addresses.has(sessionId) ? addresses.get(sessionId) : { kind: 'session', sessionId }+ if (address === undefined) return+ try {+ await scanSession(ledger, address, asOfSeq, ended.has(sessionId), signal)+ unreadable.delete(sessionId)+ } catch (error) {+ if (unreadable.has(sessionId)) return+ unreadable.add(sessionId)+ rt.warn('ds-bot: usage could not read %s: %s', sessionId, error)+ }+ })})().finally(() => {scannedAt = Date.now()scanning = undefineddiff --git a/ds-bot/test/usage.test.js b/ds-bot/test/usage.test.jsindex 0dfd8750..0a31d875 100644--- a/ds-bot/test/usage.test.js+++ b/ds-bot/test/usage.test.js@@ -47,7 +47,7 @@ test('a fork does not count the calls it inherited from its parent', () => {const HOUR = 3_600_000const LONG_AGO = 1_000-function start(home, { listedExtra, logsExtra } = {}) {+function start(home, { listedExtra, logsExtra, subagentsExtra } = {}) {const fresh = home === undefinedhome ??= mkdtempSync(join(tmpdir(), 'ds-bot-usage-'))if (fresh) writeFileSync(join(home, 'state.json'), JSON.stringify({@@ -75,19 +75,27 @@ function start(home, { listedExtra, logsExtra } = {}) {...logsExtra,}for (const log of Object.values(logs)) log.forEach((event, seq) => { event.seq = seq })+ // Child Session → the parent its header names, as DSH checks a page address.+ const subagents = { 's-sub': 's-b1', ...subagentsExtra }const pages = []+ const warnings = []const ctx = fakeContext()+ ctx.logger.warn = (template, ...args) => warnings.push([template, ...args])ctx.sessionController = {list: async () => ({ items: [{ sessionId: 's-x', projections: { kind: 'cached', asOfSeq: 1, values: {} } },- { sessionId: 's-sub', parentSessionId: 's-b1', projections: { kind: 'cached', asOfSeq: 1, values: {} } },+ { sessionId: 's-sub', parentSessionId: 's-b1', origin: 'subagent', projections: { kind: 'cached', asOfSeq: 1, values: {} } },{ sessionId: 's-empty', blank: true },...(listedExtra ?? []),] }),projections: async ({ sessionId }) => (logs[sessionId] ? { asOfSeq: logs[sessionId].length - 1, values: {} } : null),page: async ({ address, throughSeq, beforeSeq }) => {- pages.push(address.sessionId)- const events = logs[address.sessionId].filter(event => event.seq <= throughSeq && (beforeSeq === undefined || event.seq < beforeSeq))+ const sessionId = address.kind === 'session' ? address.sessionId : address.childSessionId+ if (address.kind === 'session' && sessionId in subagents) throw new Error('subagent Sessions require their durable parent address')+ if (address.kind === 'subagent' && subagents[sessionId] !== address.parentSessionId) throw new Error('subagent does not belong to the supplied parent')+ if (logs[sessionId] === undefined) throw new Error(`no log for ${sessionId}`)+ pages.push(sessionId)+ const events = logs[sessionId].filter(event => event.seq <= throughSeq && (beforeSeq === undefined || event.seq < beforeSeq))return { records: events.map(event => ({ event })), hasMore: false }},}@@ -103,7 +111,7 @@ function start(home, { listedExtra, logsExtra } = {}) {ctx.dispose()rmSync(home, { recursive: true, force: true })}- return { call, ctx, home, meter, pages, stop }+ return { call, ctx, home, meter, pages, stop, warnings }}// Total tokens per owner name and use.@@ -191,3 +199,32 @@ test('a plain chat journals its owner before the first scan, so a deleted Bot keassert.equal(totals(view)['Writer/chat'], 55)second.ctx.dispose()})++test('a subagent Session is read through its parent, even a parent that is gone; one that cannot be read warns once', async (t) => {+ t.mock.timers.enable({ apis: ['Date'], now: 10 * HOUR })+ const { call, pages, stop, warnings } = start(undefined, {+ listedExtra: [+ { sessionId: 's-orphan', parentSessionId: 's-gone', origin: 'subagent', projections: { kind: 'cached', asOfSeq: 1, values: {} } },+ { sessionId: 's-lost', origin: 'subagent', projections: { kind: 'cached', asOfSeq: 1, values: {} } },+ { sessionId: 's-broken', projections: { kind: 'cached', asOfSeq: 1, values: {} } },+ ],+ logsExtra: {+ 's-orphan': [header('deepseek', 'v4-flash'), message(1, 0, usage(8, 1), HOUR)],+ 's-lost': [header('deepseek', 'v4-flash'), message(1, 0, usage(9, 9), HOUR)],+ },+ subagentsExtra: { 's-orphan': 's-gone', 's-lost': 's-gone' },+ })+ t.after(stop)+ const view = (await call('usage', { timeZone: 'Asia/Shanghai' })).value+ assert.equal(totals(view)['Chief/chat'], 160 + 220 + 10)+ assert.equal(totals(view)['other/chat'], 44 + 9)+ // No parent on record: it cannot be addressed, so it is not asked for.+ assert.ok(!pages.includes('s-lost'))+ const unread = () => warnings.filter(([template]) => template.includes('usage could not read')).map(([, sessionId]) => sessionId)+ assert.deepEqual(unread(), ['s-broken'])++ t.mock.timers.tick(60_000)+ await call('usage', { timeZone: 'Asia/Shanghai' })+ assert.equal(pages.filter(sessionId => sessionId === 's-orphan').length, 1)+ assert.deepEqual(unread(), ['s-broken'])+})