Skip to content
10 changes: 8 additions & 2 deletions ds-bot/src/host/bot-tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,8 @@ export function install(rt) {
}
}

const hasInboxInput = agent => Boolean(agent?.inbox?.nextStep?.length || agent?.inbox?.nextTurn?.length)

// Settles a task whose turn ended while the plugin was reloading (durable log).
async function reconcileEndedTask(sessionId, ended) {
if (rt.readOnly?.() !== undefined) return false
Expand All @@ -550,6 +552,11 @@ export function install(rt) {
.join('\n\n')
.trim()
const failure = reason?.kind === 'error' ? turnFailure(reason.error) : undefined
if (reason?.kind !== 'error' && reason?.kind !== 'aborted') {
const agent = await rt.resolveAgent(sessionId).catch(() => undefined)
// A child work can already be closed while its reply still waits for replay.
if (hasInboxInput(agent) || rt.unreadOf?.(sessionId)?.length > 0) return false
}
await handleTurnEnd(bot, task, reason, failure, said)
return true
}
Expand All @@ -571,8 +578,7 @@ export function install(rt) {
if ((rt.runningJobs?.(sid)?.length ?? 0) > 0) continue
if ((rt.unreadOf?.(sid)?.length ?? 0) > 0) continue
const agent = await rt.resolveAgent(sid).catch(() => undefined)
const pendingInbox = (agent?.inbox?.nextStep?.length ?? 0) + (agent?.inbox?.nextTurn?.length ?? 0)
if (agent?.status === 'running' || pendingInbox > 0) continue
if (agent?.status === 'running' || hasInboxInput(agent)) continue
if (hasOpenOutgoingWorks(bot, task)) {
if (task.status !== 'waiting_work') {
task.status = 'waiting_work'
Expand Down
68 changes: 60 additions & 8 deletions ds-bot/src/host/delivery.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { HISTORY_TIMEOUT_MS, LONG_HEAD, MESSAGE_INLINE_MAX, READ_LINE_MAX, SOURCE_KIND, TEXT_KEPT, TEXT_SHOW_MAX } from './constants.js'
import { headOf, textOf } from './text.js'
import { sameConversation } from './threads.js'

export function install(rt) {
const { ctx, state } = rt
Expand Down Expand Up @@ -57,19 +58,63 @@ export function install(rt) {
.map(entry => ({ ...entry, delivered: true })))
// A message shows the text its delivery carried: the last record of its id written before
// a delivery mark. A merged request whose replacement never went out keeps the text that did.
function pairMessages(a, b) {
function pairRecords(a, b) {
const written = new Map()
const shown = new Map()
const marks = []
for (const record of rt.ledger.records(pairBook(a, b))) {
if (record.event === 'delivered') {
if (written.has(record.id)) shown.set(record.id, written.get(record.id))
marks.push(record)
} else if (record.event === undefined) {
written.set(record.id, record)
if (record.delivered === true) shown.set(record.id, record)
}
}
return [...shown.values()]
return { written, shown, marks }
}
const pairMessages = (a, b) => [...pairRecords(a, b).shown.values()]

function deliveredReplyOf(fromId, toId, replyTo) {
if (typeof fromId !== 'string' || fromId === '' || typeof replyTo !== 'string' || replyTo === '') return undefined
if (typeof toId === 'string' && toId !== '') {
if (rt.botOf(fromId) === undefined || rt.botOf(toId) === undefined) {
return (state.exchanges ?? []).findLast(entry => entry.from === fromId && entry.to === toId && entry.role === 'reply' && entry.replyTo === replyTo)
}
return pairMessages(fromId, toId).findLast(record => record.from === fromId && record.to === toId && record.role === 'reply' && record.replyTo === replyTo)
}
if (rt.botOf(fromId) !== undefined) {
for (const otherId of Object.keys(state.bots ?? {})) {
if (otherId === fromId) continue
const found = pairMessages(fromId, otherId).findLast(record => record.from === fromId && record.to === otherId && record.role === 'reply' && record.replyTo === replyTo)
if (found !== undefined) return found
}
}
return (state.exchanges ?? []).findLast(entry => entry.from === fromId && entry.role === 'reply' && entry.replyTo === replyTo)
}

const wasReplyDelivered = (fromId, toId, replyTo) => deliveredReplyOf(fromId, toId, replyTo) !== undefined

function deliveredFailuresOf(fromId, toId, requestId, targetSessionId, parentWork) {
if (typeof fromId !== 'string' || typeof toId !== 'string' || typeof requestId !== 'string' || requestId === '') return []
if (rt.botOf(fromId) === undefined || rt.botOf(toId) === undefined) return []
const wantedWork = typeof parentWork === 'string' && parentWork !== '' ? parentWork : undefined
const { written, marks } = pairRecords(fromId, toId)
const matches = []
for (const mark of marks) {
if (mark.failureRequestId !== requestId) continue
const markWork = typeof mark.work === 'string' && mark.work !== '' ? mark.work : undefined
if (markWork !== wantedWork) continue
const message = written.get(mark.id)
if (message?.from === fromId && message?.to === toId && sameConversation(state, toId, mark.sessionId, targetSessionId)) {
matches.push({ id: mark.id, replyTo: message.replyTo, work: markWork, sessionId: mark.sessionId })
}
}
return matches
}

const wasFailureRequestDelivered = (fromId, toId, requestId, targetSessionId, parentWork) =>
deliveredFailuresOf(fromId, toId, requestId, targetSessionId, parentWork).length > 0

// `sessionId` defaults to the recipient's own chat; group turns name its group Session.
// `deferred`: a request the Bot already read mid-turn, handed back to answer in a
Expand All @@ -85,7 +130,7 @@ export function install(rt) {
// result that came back goes on with. `merged`: a request that takes in an earlier
// one its recipient had not read, under that one's exchange. `fromPart`: the Session
// of the sending Bot, which a reply comes back to when that is a background part.
async function deliver({ fromId, fromName: senderName, toId, sessionId, text, role, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, merged = false, abandoned = false, recordExchange = true, askedBy, fromRoomId, fromPart, images = [], files = [], length, work, taskId, imOrigin }) {
async function deliver({ fromId, fromName: senderName, toId, sessionId, text, role, replyTo, roomId, audience, note, exchangeId = randomUUID(), steer = false, deferred = false, resumed = false, retried = false, resent = false, merged = false, abandoned = false, recordExchange = true, askedBy, fromRoomId, fromPart, images = [], files = [], length, work, taskId, imOrigin, failureRequestId }) {
const from = rt.botOf(fromId)
const to = rt.botOf(toId)
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
Expand Down Expand Up @@ -139,7 +184,14 @@ export function install(rt) {
else agent.followup(message)
await ctx.sessions.flush(agent.session)
if (book !== undefined) {
rt.ledger.append(book, { event: 'delivered', id: exchangeId, sessionId: targetSessionId, time: Date.now() })
rt.ledger.append(book, {
event: 'delivered',
id: exchangeId,
sessionId: targetSessionId,
time: Date.now(),
...(typeof failureRequestId === 'string' && failureRequestId !== '' ? { failureRequestId } : {}),
...(typeof work === 'string' && work !== '' ? { work } : {}),
})
// The message went out either way; a mark that is lost only hides it from the dialog.
await rt.ledger.written(book).catch(() => {})
} else if (recordExchange && EXCHANGE_ROLES.has(role) && !deferred && !resumed && !retried) {
Expand Down Expand Up @@ -199,16 +251,16 @@ export function install(rt) {
}
}

// The text of a stored file, up to what the dialogs show.
async function fileText(file) {
// The text of a stored file, limited to what the dialogs show by default.
async function fileText(file, maxLength = TEXT_SHOW_MAX) {
const attachments = ctx.get?.('attachments')
if (attachments === undefined) return undefined
const decoder = new TextDecoder()
let text = ''
try {
for await (const chunk of attachments.readFileStream(file, AbortSignal.timeout(HISTORY_TIMEOUT_MS))) {
text += decoder.decode(chunk, { stream: true })
if (text.length > TEXT_SHOW_MAX) return { text: headOf(text, TEXT_SHOW_MAX), whole: false }
if (text.length > maxLength) return { text: headOf(text, maxLength), whole: false }
}
} catch (error) {
rt.warn('ds-bot: file %s not read: %s', file?.name, error)
Expand All @@ -231,5 +283,5 @@ export function install(rt) {
return { ...record, ledger: true }
}

Object.assign(rt, { resolveAgent, deliver, exchangeText, attachLong, fileText, exchangesOf, exchangeOf })
Object.assign(rt, { resolveAgent, deliver, exchangeText, attachLong, fileText, exchangesOf, exchangeOf, deliveredReplyOf, wasReplyDelivered, deliveredFailuresOf, wasFailureRequestDelivered })
}
1 change: 1 addition & 0 deletions ds-bot/src/host/handoffs.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ export function install(rt) {
if (work === undefined) return
const { parent } = work
delete works()[id]
for (const child of Object.values(works())) if (child.parent === id) delete child.parent
const above = works()[parent]
if (above !== undefined) above.open = above.open.filter(other => other !== id)
for (const result of work.results ?? []) whole.delete(result.id)
Expand Down
Loading
Loading