A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Deliver a private-chat steer at once instead of at the next step
Fei241143829047f217
diff --git a/ds-bot/index.js b/ds-bot/index.jsindex b1465905..a38cb365 100644--- a/ds-bot/index.js+++ b/ds-bot/index.js@@ -8,6 +8,7 @@ import * as models from './src/host/models.js'import * as providers from './src/host/providers.js'import * as permissions from './src/host/permissions.js'import * as turns from './src/host/turns.js'+import * as steer from './src/host/steer.js'import * as handoffs from './src/host/handoffs.js'import * as requests from './src/host/requests.js'import * as delivery from './src/host/delivery.js'@@ -51,7 +52,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, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, channel, officeSkills]+const MODULES = [diagnostics, store, models, providers, permissions, turns, steer, handoffs, requests, delivery, roster, folders, privacy, agents, prompt, timeContext, tools, chatIndex, groups, approvals, resume, memory, parts, images, avatarLibrary, secrets, connectors, capabilities, learning, schedules, browser, browserPlugins, usage, update, dshUpdate, thinking, feed, channel, officeSkills]export function apply(ctx, config = {}) {createRuntime(ctx, config)diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.jsindex 0df0d7d6..25d00f01 100644--- a/ds-bot/src/host/constants.js+++ b/ds-bot/src/host/constants.js@@ -85,3 +85,5 @@ export const HISTORY_PAGES_MAX = 50export const HISTORY_TIMEOUT_MS = 20_000// Shown when an aside stops at the route's own output limit. The partial answer stays.export const ASIDE_LIMIT = 'Answer cut off at the output limit.'++export const STEER_CUT = 'ds-bot/steer'diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex 48023494..ca25a9d4 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -1045,8 +1045,10 @@ export function install(rt) {running.carry.push(...payload.messages)return { kind: 'reject' }}- const midTurn = payload.step > 1const entry = rt.liveOf(agent.id)+ // A turn carried through a steer cut keeps its trigger and joined work, so+ // its first step is already the middle of a turn for the folder check.+ const midTurn = payload.step > 1 || entry.carried === trueentry.switched = truestartSwitch(agent, { resume: midTurn, carry: payload.messages, info: midTurn ? entry.info : undefined, joined: midTurn ? [...(entry.joined ?? [])] : undefined, ...options })return { kind: 'reject' }diff --git a/ds-bot/src/host/resume.js b/ds-bot/src/host/resume.jsindex e8b44c65..e507ddac 100644--- a/ds-bot/src/host/resume.js+++ b/ds-bot/src/host/resume.js@@ -191,7 +191,9 @@ export function install(rt) {case 'turn/start': {const owner = rt.groupOwners.get(id)const botId = owner?.botId ?? rt.chatOwners.get(id)- update(id, () => ({ botId, ...(owner ? { roomId: owner.roomId } : {}), since: event.time ?? Date.now() }))+ // turns.js runs first and has already claimed or restored the trigger.+ const info = rt.live.get(id)?.info+ update(id, () => ({ botId, ...(owner ? { roomId: owner.roomId } : {}), since: event.time ?? Date.now(), ...(info !== undefined ? { trigger: triggerOf(info) } : {}) }))break}case 'user/message': {diff --git a/ds-bot/src/host/steer.js b/ds-bot/src/host/steer.jsnew file mode 100644index 00000000..8ff71b8c--- /dev/null+++ b/ds-bot/src/host/steer.js@@ -0,0 +1,259 @@+// In a Bot's private chat a user steer must reach the Bot at once, not at the+// next DSH step boundary. Two mechanisms:+// - a foreground shell call detaches into the jobs registry on a steer and+// returns DSH's promoted result, so the step ends while the command runs on;+// - a running model call is cancelled (hook reason) and the steer is moved to+// the front of next-turn, so a fresh turn claims it at once.+import { isAbsolute, resolve } from 'node:path'+import { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm'+import { STEER_CUT } from './constants.js'++const SHELL_TOOLS = ['pwsh', 'bash']+const STEER_GRACE_MS = 1000++export function install(rt) {+ const ctx = rt.ctx+ let jobs+ const attachJobs = (sub) => {+ const own = sub.jobs+ jobs = own+ sub.effect(() => () => { if (jobs === own) jobs = undefined }, 'ds-bot: jobs service')+ }+ if (typeof ctx.inject === 'function') ctx.inject(['jobs'], attachJobs)+ else if (ctx.get?.('jobs') !== undefined) attachJobs({ jobs: ctx.get('jobs'), effect: (execute, label) => ctx.effect(execute, label) })++ const privateOf = (sessionId) => sessionId !== undefined && rt.chatOwners.has(sessionId) && !rt.groupOwners.has(sessionId)+ const liveAgent = (sessionId) => ctx.get('agents')?.get(sessionId)++ // Per-session state kept by the session/event listener below.+ const state = new Map()+ const stateOf = (id) => {+ let entry = state.get(id)+ if (entry === undefined) state.set(id, entry = { phase: 'boundary', jobsByCall: new Map(), jobWaiters: new Map(), steerWaiters: new Set(), killedJobs: new Set(), cutting: false })+ return entry+ }+ const isUserSteer = (event) => event?.data?.target === 'next-step'+ && (event.data.inserted ?? []).some(message => message?.source?.kind === 'user')+ const wake = (set, value) => { const waiters = [...set]; set.clear(); for (const fn of waiters) fn(value) }++ // A user steer into a private chat must cut a running model call. The check runs+ // off the event that queued it, never inside the append that emitted the event.+ const maybeCut = (id) => {+ const entry = rt.live.get(id)+ const agent = liveAgent(id)+ if (!privateOf(id) || rt.readOnly?.() !== undefined || entry === undefined || agent === undefined) return+ if ((rt.switchJobs?.() ?? []).some?.(job => job?.botId === rt.chatOwners.get(id))) return+ const track = stateOf(id)+ if (track.phase !== 'model' || track.cutting) return+ if (entry.turn === undefined || (entry.calls?.size ?? 0) > 0 || agent.status !== 'running') return+ const nextStep = agent.inbox?.nextStep ?? []+ const last = [...nextStep].reverse().find(message => message?.source?.kind === 'user')+ if (last === undefined) return+ track.cutting = true+ rt.markSteerCut(id)+ agent.inbox.remove(last.id)+ agent.cancel({ kind: 'hook', reason: STEER_CUT }, { keepInbox: true })+ agent.send(last, 'next-turn', true)+ if (agent.inbox.nextTurn[0]?.id !== last.id) {+ agent.inbox.remove(last.id)+ agent.inbox.prepend('next-turn', last)+ }+ }+ const scheduleCut = (id) => { queueMicrotask(() => maybeCut(id)) }++ // Renders one jobs.read() result the way tool-jobs' renderModelDelta does:+ // stdout and unlabeled chunks joined, then a [stderr] section, then a+ // dropped-output note when the ring lost bytes.+ const renderJobRead = (read) => {+ const visible = (read.chunks ?? []).filter(chunk => chunk?.channel !== 'log')+ const out = visible.filter(chunk => chunk.channel !== 'stderr').map(chunk => chunk.text ?? '').join('')+ const err = visible.filter(chunk => chunk.channel === 'stderr').map(chunk => chunk.text ?? '').join('')+ const separator = out.length > 0 && !out.endsWith('\n') ? '\n' : ''+ const body = out + (err.length > 0 ? `${separator}[stderr]\n${err}` : '')+ const spillPaths = read.job?.output?.spillPaths ?? []+ if (read.lossy !== true && !visible.some(chunk => chunk.gapBefore === true)) return body+ const notice = `[some output was dropped from memory; full output: ${spillPaths.length > 0 ? spillPaths.join(', ') : '(unavailable)'}]`+ return `${body}${body.length > 0 && !body.endsWith('\n') ? '\n' : ''}${notice}`+ }++ const noticeOf = (name, command, text) => createUserMessage({+ content: [{ type: 'text', text }],+ // Same source as DSH's job-completion notice so every chat renders it the+ // same way, and DS Bot's routing ignores it.+ source: { kind: 'tool-jobs', form: 'notice', summary: boundContextSummary(`${name} ${command} …`) },+ })++ const detachAfter = (jobId, args, exec, def, native, label) => {+ const id = exec.agent.id+ const command = args?.command ?? ''+ native.then(value => {+ const track = stateOf(id)+ if (track.killedJobs.delete(jobId) || liveAgent(id) !== exec.agent) return+ const deliver = (text) => {+ const message = noticeOf(label, command, text)+ if (exec.agent.status === 'idle') return exec.agent.followup(message)+ return exec.agent.inject(message)+ }+ if (value?.kind === 'promoted') {+ // The native timeout passed after the detach; the job stays registered+ // and tool-jobs will notify on settle.+ if (typeof value.output === 'string' && value.output !== '') {+ return deliver(`background job ${jobId} (${label}: ${command}) is still running. Output since your last read:\n${value.output}`)+ }+ return+ }+ const rendered = (def.output?.render?.(args, value) ?? [])+ .map(block => block?.text ?? '')+ .filter(text => text !== '')+ .join('\n')+ return deliver(`background job ${jobId} (${label}: ${command}) finished:\n${rendered}`)+ }, error => {+ const track = stateOf(id)+ if (track.killedJobs.delete(jobId) || liveAgent(id) !== exec.agent) return+ const message = noticeOf(label, command, `background job ${jobId} (${label}: ${command}) failed: ${error?.message ?? String(error)}`)+ if (exec.agent.status === 'idle') return exec.agent.followup(message)+ return exec.agent.inject(message)+ })+ }++ const shadowed = new WeakSet()+ const formatWarned = new Set()+ const shadowShell = (agent, name) => {+ if (typeof ctx.tools?.get !== 'function') return+ const def = ctx.tools.get(name, agent)+ if (def === undefined) return+ const promoted = (def.output?.schema?.oneOf ?? []).find(variant => variant?.properties?.kind?.const === 'promoted')+ if (typeof def.output?.render !== 'function'+ || promoted?.properties?.cwd === undefined || promoted?.properties?.jobId === undefined+ || promoted?.properties?.timeoutMs === undefined || promoted?.properties?.output === undefined) {+ if (!formatWarned.has(name)) {+ formatWarned.add(name)+ rt.warn('ds-bot: %s has no promoted result format; its calls keep the step boundary', name)+ }+ return+ }+ shadowed.add(agent)+ agent.ctx.tools.register({+ ...def,+ execute: async (args, exec) => {+ const native = def.execute(args, exec)+ const sessionId = exec.agent?.id+ if (args?.run_in_background === true || jobs === undefined || sessionId === undefined+ || !privateOf(sessionId)) return native+ const track = stateOf(sessionId)+ const startedAt = Date.now()+ let steerResolve+ let jobResolve+ let graceTimer+ try {+ // A user steer ends the wait: first for the steer event itself, then a+ // short grace for a fast command, then for the job id the native call+ // registers (it may not exist yet while approval is pending).+ const steerSeen = () => {+ if ((exec.agent.inbox?.nextStep ?? []).some(message => message?.source?.kind === 'user')) return Promise.resolve('steered')+ return new Promise(resolve => { steerResolve = resolve; track.steerWaiters.add(resolve) }).then(() => 'steered')+ }+ const first = await Promise.race([native, steerSeen()])+ if (first !== 'steered') return await native+ const graced = await Promise.race([native, new Promise(resolve => { graceTimer = setTimeout(() => resolve('grace'), STEER_GRACE_MS) })])+ if (graced !== 'grace') return await native+ const known = track.jobsByCall.get(exec.callId)+ const jobWait = known !== undefined ? Promise.resolve(known) : new Promise(resolve => {+ jobResolve = resolve+ const set = track.jobWaiters.get(exec.callId) ?? new Set()+ track.jobWaiters.set(exec.callId, set)+ set.add(resolve)+ })+ const settled = await Promise.race([native.then(() => 'native'), jobWait.then(() => 'job')])+ if (settled !== 'job') return await native+ } catch {+ // A native rejection before or after the steer propagates unchanged.+ return await native+ } finally {+ if (steerResolve !== undefined) track.steerWaiters.delete(steerResolve)+ if (jobResolve !== undefined) {+ const set = track.jobWaiters.get(exec.callId)+ set?.delete(jobResolve)+ if (set?.size === 0) track.jobWaiters.delete(exec.callId)+ }+ clearTimeout(graceTimer)+ }+ const jobId = track.jobsByCall.get(exec.callId)+ let read+ try {+ read = jobs.read(jobId, sessionId)+ } catch {+ return await native+ }+ const status = read?.job?.status+ if (status === 'completed' || status === 'killed' || status === 'failed') return await native+ detachAfter(jobId, args, exec, def, native, name)+ const base = rt.sessionFolder?.(exec.agent.session)+ const cwd = args?.workdir === undefined ? (base ?? '')+ : !isAbsolute(args.workdir) && base !== undefined ? resolve(base, args.workdir) : args.workdir+ return { kind: 'promoted', cwd, jobId, timeoutMs: Date.now() - startedAt, output: renderJobRead(read) }+ },+ })+ }+ rt.shadowShells = (agent) => {+ if (agent === undefined || !rt.isBotSession(agent.session?.id)) return+ if (shadowed.has(agent) || typeof agent.ctx?.tools?.register !== 'function') return+ for (const name of SHELL_TOOLS) {+ try {+ shadowShell(agent, name)+ } catch (error) {+ rt.warn('ds-bot: shadowing %s failed: %s', name, error)+ }+ }+ }++ ctx.on('session/event', (session, event) => {+ const id = session?.id+ if (id === undefined || !privateOf(id)) return+ const track = stateOf(id)+ switch (event.type) {+ case 'step/start': {+ track.phase = 'model'+ const agent = liveAgent(id)+ if ((agent?.inbox?.nextStep ?? []).some(message => message?.source?.kind === 'user')) scheduleCut(id)+ break+ }+ case 'assistant/message':+ track.phase = 'tools'+ break+ case 'step/end':+ case 'turn/start':+ case 'turn/end':+ track.phase = 'boundary'+ track.cutting = false+ break+ case 'job/registered': {+ const callId = event.data?.toolCall?.callId+ if (callId !== undefined) {+ track.jobsByCall.set(callId, event.data.jobId)+ const set = track.jobWaiters.get(callId)+ if (set !== undefined) { track.jobWaiters.delete(callId); wake(set, event.data.jobId) }+ }+ break+ }+ case 'job/settled':+ if (event.data?.toolCall?.callId !== undefined) track.jobsByCall.delete(event.data.toolCall.callId)+ break+ case 'tool/call': {+ if (event.data?.name === 'job_kill') {+ try {+ const parsed = JSON.parse(event.data.arguments ?? '{}')+ if (parsed.job_id !== undefined) track.killedJobs.add(parsed.job_id)+ } catch { /* unparseable args carry no kill target */ }+ }+ break+ }+ case 'agent/inbox/spliced':+ if (isUserSteer(event)) {+ wake(track.steerWaiters, true)+ scheduleCut(id)+ }+ break+ }+ })+}diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.jsindex da3bd825..c8a3a7e9 100644--- a/ds-bot/src/host/tools.js+++ b/ds-bot/src/host/tools.js@@ -724,6 +724,7 @@ export function install(rt) {const hiddenTools = new WeakSet()const hideBotUnusedTools = (agent) => {shareBotTools(agent)+ rt.shadowShells?.(agent)if (agent === undefined || hiddenTools.has(agent) || !rt.isBotSession(agent.session?.id)) returnif (typeof agent.ctx?.tools?.restrict !== 'function') returntry {diff --git a/ds-bot/src/host/turns.js b/ds-bot/src/host/turns.jsindex a7106b52..ecbf6fca 100644--- a/ds-bot/src/host/turns.js+++ b/ds-bot/src/host/turns.js@@ -2,7 +2,7 @@// triggered, the waiters and inboxes of group rounds, and routing a finished turn's reply.//// Turn tracking: which turns were triggered by another Bot, and what they said.-import { HANDOFF_ACK, MESSAGE_INLINE_MAX, REFERENCE_KIND, REPLY_KIND, SOURCE_KIND } from './constants.js'+import { HANDOFF_ACK, MESSAGE_INLINE_MAX, REFERENCE_KIND, REPLY_KIND, SOURCE_KIND, STEER_CUT } from './constants.js'import { absoluteLinks } from './links.js'import { textOf } from './text.js'import { reminderText } from './schedules.js'@@ -408,10 +408,24 @@ export function install(rt) {entry.joined = []entry.later = []entry.steeredAt = undefined+ entry.carried = falseif (entry.pending !== undefined) {claimTrigger(id, entry, entry.pending)entry.pending = undefined}+ if (entry.carry !== undefined) {+ const carry = entry.carry+ entry.carry = undefined+ entry.texts = carry.texts+ entry.shown = carry.shown+ entry.answers = carry.answers+ entry.joined = carry.joined+ entry.later = carry.later+ entry.opened = true+ entry.carried = true+ if (carry.info !== undefined) claimTrigger(id, entry, carry.info)+ entry.joined = carry.joined+ }breakcase 'user/message': {const source = event.data?.source@@ -538,6 +552,15 @@ export function install(rt) {}case 'turn/end': {setActivity(id, undefined)+ // A steer cut leaves the turn's routing state for the fresh turn that+ // claims the steer: nothing is answered or delivered for the cut one.+ const cut = entry.cut+ entry.cut = undefined+ const steerCut = cut !== undefined && event.data?.reason?.kind === 'aborted'+ && event.data.reason.reason?.kind === 'hook' && event.data.reason.reason.reason === STEER_CUT+ if (steerCut) {+ entry.carry = { info: entry.info, joined: entry.joined ?? [], later: entry.later ?? [], texts: entry.texts.slice(0, cut.texts), shown: entry.shown, answers: entry.answers }+ }const info = entry.infoconst joined = entry.joined ?? []// What the group already saw of the turn is not posted again.@@ -561,6 +584,7 @@ export function install(rt) {entry.lastCalled = undefinedconst later = entry.later ?? []entry.later = []+ if (steerCut) breakfor (const result of later) {void rt.deliver({fromId: result.info.senderSessionId,@@ -670,5 +694,10 @@ export function install(rt) {}})- Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, releaseBot })+ const markSteerCut = (id) => {+ const entry = live.get(id)+ if (entry?.turn !== undefined) entry.cut = { texts: entry.texts.length }+ }++ Object.assign(rt, { live, liveOf, roomWaiters, roomProgress, roomInbox, activityView, workView, roomWorkView, turnsView, steeredView, callDetail, doingOf, stopRoomTurn, releaseBot, markSteerCut })}diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.jsindex 172aa4c1..d5ec81e1 100644--- a/ds-bot/test/install.test.js+++ b/ds-bot/test/install.test.js@@ -40,6 +40,7 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {'on credentials/reference-updated','on settings/document-updated','on session/event',+ 'on session/event','on tools/execute','effect ds-bot: agent tool restrict retry','on agent/created',diff --git a/ds-bot/test/steer.test.js b/ds-bot/test/steer.test.jsnew file mode 100644index 00000000..febe3183--- /dev/null+++ b/ds-bot/test/steer.test.js@@ -0,0 +1,418 @@+import assert from 'node:assert/strict'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { test } from 'node:test'+import { createRuntime } from '../index.js'+import { fakeContext } from './fake-ctx.js'+import { SOURCE_KIND, STEER_CUT } from '../src/host/constants.js'++// A user steer in a private Bot chat detaches a running shell call into a+// promoted job and cuts a running model call, so the steer is claimed at once.+const TEAM = {+ version: 1,+ mainBotIds: ['a'],+ workspaceId: 'w1',+ bots: { a: { id: 'a', name: 'Chief', role: 'Boss', sessionId: 'dm-a', createdAt: 1 } },+ rooms: {},+ agents: {},+ exchanges: [],+ exchangeTurns: {},+ questions: {},+ prefs: {},+ revision: 0,+}++const SHELL_SCHEMA = { oneOf: [+ { properties: { kind: { const: 'foreground' }, exitCode: {} } },+ { properties: { kind: { const: 'promoted' }, cwd: {}, jobId: {}, timeoutMs: {}, output: {} } },+ { properties: { kind: { const: 'background' }, jobId: {} } },+] }++const shellDef = (name = 'pwsh') => {+ const calls = []+ return {+ calls,+ name,+ description: 'shell',+ output: {+ schema: SHELL_SCHEMA,+ render: (args, value) => [{ type: 'text', text: `exit ${value?.exitCode ?? '?'} out:${value?.stdout?.text ?? ''}` }],+ },+ execute: (args) => new Promise((res, rej) => { calls.push({ args, res, rej }) }),+ }+}++const jobsService = (read) => ({ read })++const start = async ({ services = {}, def = shellDef() } = {}) => {+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-steer-'))+ writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM))+ const ctx = fakeContext({ services })+ const agentMap = new Map()+ const deliveries = []+ const inboxOf = () => {+ const nextStep = []+ const nextTurn = []+ return { nextStep, nextTurn,+ prepend: (t, m) => (t === 'next-turn' ? nextTurn : nextStep).unshift(m),+ append: (t, m) => (t === 'next-turn' ? nextTurn : nextStep).push(m),+ remove: mid => { for (const l of [nextStep, nextTurn]) { const at = l.findIndex(m => m.id === mid); if (at !== -1) { l.splice(at, 1); return true } } return false },+ }+ }+ const calls = []+ const agentOf = (id, over = {}) => {+ const inbox = inboxOf()+ const agent = {+ id,+ session: { id, header: { cwd: '/team' } },+ ctx: { tools: { register: t => (calls.push(['register', t]), () => {}), restrict: () => () => {} }, on: () => () => {}, effect: execute => execute?.() },+ status: 'running',+ followup: msg => calls.push(['followup', msg]),+ inject: msg => calls.push(['inject', msg]),+ send: (msg, target) => inbox[target === 'next-turn' ? 'nextTurn' : 'nextStep'].push(msg),+ cancel: (cause, options) => calls.push(['cancel', cause, options]),+ inbox,+ ...over,+ }+ agentMap.set(id, agent)+ return agent+ }+ const agentById = agentOf('dm-a')+ ctx.tools.register({ ...def })+ ctx.tools.schemas = () => [{ name: 'pwsh' }, { name: 'bash' }, { name: 'ask_user_question' }]+ ctx.tools.get = (name) => (name === def.name ? def : undefined)+ Object.assign(ctx, {+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },+ workspaceRegistry: { get: () => ({ id: 'w1', path: '/team' }), list: () => [{ id: 'w1', path: '/team' }], resolveByPath: async () => undefined, create: async p => ({ id: 'w1', path: p }), archiveSession: async () => {} },+ sessionController: { create: async () => ({ sessionId: 'dm-a' }), resolveAgent: async () => ({ agent: agentById }), selectModel: async () => {}, page: async () => ({ records: [], hasMore: false }) },+ sessionTitle: { rename: async () => {} },+ sessions: { flush: async () => {} },+ })+ const origGet = ctx.get+ Object.assign(ctx, { get: name => (name === 'agents' ? agentMap : origGet(name)) })+ const rt = createRuntime(ctx, { home })+ await rt.load?.()+ const origDeliver = rt.deliver+ rt.deliver = (...args) => { deliveries.push(args); return origDeliver ? origDeliver(...args) : Promise.resolve() }+ const emit = async (id, type, data) => {+ for (const listener of ctx.listeners.get('session/event') ?? []) {+ if (listener.length >= 2) await listener({ id }, { type, data })+ }+ await new Promise(r => setTimeout(r, 0))+ }+ const stop = async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true, maxRetries: 5 }) }+ const shadowOf = () => calls.find(c => c[0] === 'register')?.[1]+ return { ctx, emit, stop, rt, agent: agentById, agentMap, calls, deliveries, shadowOf }+}++const userMessage = text => ({ id: `m-${text}`, content: [{ type: 'text', text }], source: { kind: 'user' }, role: 'user' })+const execOf = (agent, callId = 'c1') => ({ agent, callId, name: 'pwsh', signal: AbortSignal.timeout(30_000) })++test('shell shadow: no steer returns the native value as is', async () => {+ const { stop, rt, agent, shadowOf } = await start({ services: { jobs: jobsService(() => { throw new Error('no job') }) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const NATIVE = { kind: 'foreground', exitCode: 0 }+ const pending = shadow.execute({ command: 'pwd' }, execOf(agent))+ shadow.calls[0].res(NATIVE)+ assert.equal(await pending, NATIVE)+ await stop()+})++test('shell shadow: steer promotes the call and native settle notifies later', async () => {+ const { emit, stop, rt, agent, calls, shadowOf } = await start({ services: { jobs: jobsService((jobId) => ({+ job: { id: jobId, status: 'running', output: { spillPaths: ['/tmp/j1.log'] } },+ lossy: true,+ chunks: [+ { text: 'one', channel: 'stdout' },+ { text: 'oops', channel: 'stderr' },+ { text: 'two', channel: 'stdout' },+ { text: 'hidden', channel: 'log' },+ ],+ })) } })+ await emit('dm-a', 'turn/start', { turn: 1 })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const pending = shadow.execute({ command: 'sleep 5', workdir: 'sub' }, execOf(agent))+ await emit('dm-a', 'agent/inbox/spliced', { target: 'next-step', inserted: [userMessage('hurry')] })+ await emit('dm-a', 'job/registered', { jobId: 'j1', toolCall: { callId: 'c1' } })+ const value = await pending+ assert.equal(value.kind, 'promoted')+ assert.equal(value.jobId, 'j1')+ assert.equal(value.cwd, resolve('/team', 'sub'))+ assert.equal(value.output, 'onetwo\n[stderr]\noops\n[some output was dropped from memory; full output: /tmp/j1.log]')+ agent.status = 'idle'+ shadow.calls[0].res({ kind: 'foreground', exitCode: 0, stdout: { text: 'done' } })+ await new Promise(r => setTimeout(r, 0))+ const notice = calls.find(c => c[0] === 'followup')+ assert.ok(notice !== undefined)+ assert.equal(notice[1].content[0].text, 'background job j1 (pwsh: sleep 5) finished:\nexit 0 out:done')+ assert.equal(notice[1].source.kind, 'tool-jobs')+ await stop()+})++test('shell shadow: steer pending at call start keeps the native value inside the grace', async () => {+ const { stop, rt, agent, shadowOf } = await start({ services: { jobs: jobsService(() => { throw new Error('no job') }) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ agent.inbox.nextStep.push(userMessage('waiting'))+ const pending = shadow.execute({ command: 'pwd' }, execOf(agent))+ // The native settles at once, inside the grace, so its own value comes back.+ const NATIVE = { kind: 'foreground', exitCode: 9 }+ shadow.calls[0].res(NATIVE)+ assert.equal(await pending, NATIVE)+ await stop()+})++test('shell shadow: steer before job registration detaches once registered', async () => {+ const { emit, stop, rt, agent, shadowOf } = await start({ services: { jobs: jobsService(jobId => ({+ job: { id: jobId, status: 'running', output: {} }, chunks: [{ text: 'x' }],+ })) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const pending = shadow.execute({ command: 'sleep 5' }, execOf(agent))+ await emit('dm-a', 'agent/inbox/spliced', { target: 'next-step', inserted: [userMessage('go')] })+ await new Promise(r => setTimeout(r, 1100))+ await emit('dm-a', 'job/registered', { jobId: 'j2', toolCall: { callId: 'c1' } })+ const value = await pending+ assert.equal(value.kind, 'promoted')+ assert.equal(value.jobId, 'j2')+ await stop()+})++test('shell shadow: a native rejection before any steer propagates unchanged', async () => {+ const { stop, rt, agent, shadowOf } = await start({ services: { jobs: jobsService(() => ({ job: { status: 'running', output: {} }, chunks: [] })) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const err = new Error('spawn failed')+ const pending = shadow.execute({ command: 'pwd' }, execOf(agent))+ shadow.calls[0].rej(err)+ await assert.rejects(pending, e => e === err)+ await stop()+})++test('shell shadow: non-private session, run_in_background and no jobs are passthrough', async () => {+ const { rt, agent, calls } = await start({ services: { jobs: jobsService(() => { throw new Error('x') }) } })+ const { rt: rt2, stop: stop2, agent: noJobsAgent, shadowOf: noJobsShadow } = await start({ services: {} })+ rt.shadowShells(agent)+ const shadow = calls.find(c => c[0] === 'register')?.[1]+ const NATIVE = { kind: 'foreground' }+ // run_in_background on the private chat is untouched.+ const p1 = shadow.execute({ command: 'pwd', run_in_background: true }, execOf(agent))+ shadow.calls[0].res(NATIVE)+ assert.equal(await p1, NATIVE)+ // A non-Bot session is untouched.+ const other = { ...agent, id: 'plain', session: { id: 'plain' } }+ const p2 = shadow.execute({ command: 'pwd' }, execOf(other))+ shadow.calls[1].res(NATIVE)+ assert.equal(await p2, NATIVE)+ // No jobs service at all is untouched.+ rt2.shadowShells(noJobsAgent)+ const shadow2 = noJobsShadow()+ const p3 = shadow2.execute({ command: 'pwd' }, execOf(noJobsAgent))+ shadow2.calls[0].res(NATIVE)+ assert.equal(await p3, NATIVE)+ await stop2()+})++test('shell shadow: a def without a promoted variant is not shadowed', async () => {+ const def = shellDef()+ def.output.schema = { oneOf: [{ properties: { kind: { const: 'foreground' } } }] }+ const { rt, agent, calls } = await start({ services: { jobs: jobsService(() => ({})) }, def })+ rt.shadowShells(agent)+ assert.equal(calls.find(c => c[0] === 'register' && c[1].name === 'pwsh'), undefined)+})++test('shell shadow: a killed job gets no notice', async () => {+ const { emit, stop, rt, agent, calls, shadowOf } = await start({ services: { jobs: jobsService(jobId => ({+ job: { id: jobId, status: 'running', output: {} }, chunks: [],+ })) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const pending = shadow.execute({ command: 'sleep 5' }, execOf(agent))+ await emit('dm-a', 'job/registered', { jobId: 'j1', toolCall: { callId: 'c1' } })+ await emit('dm-a', 'tool/call', { name: 'job_kill', arguments: JSON.stringify({ job_id: 'j1' }) })+ await emit('dm-a', 'agent/inbox/spliced', { target: 'next-step', inserted: [userMessage('go')] })+ assert.equal((await pending).kind, 'promoted')+ shadow.calls[0].res({ kind: 'foreground', exitCode: 0, stdout: { text: 'x' } })+ await new Promise(r => setTimeout(r, 0))+ assert.equal(calls.find(c => c[0] === 'followup' || c[0] === 'inject'), undefined)+ await stop()+})++test('shell shadow: a replaced agent gets no notice', async () => {+ const { emit, stop, rt, agent, agentMap, calls, shadowOf } = await start({ services: { jobs: jobsService(jobId => ({+ job: { id: jobId, status: 'running', output: {} }, chunks: [],+ })) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const pending = shadow.execute({ command: 'sleep 5' }, execOf(agent))+ await emit('dm-a', 'job/registered', { jobId: 'j1', toolCall: { callId: 'c1' } })+ await emit('dm-a', 'agent/inbox/spliced', { target: 'next-step', inserted: [userMessage('go')] })+ assert.equal((await pending).kind, 'promoted')+ agentMap.set('dm-a', { id: 'dm-a' })+ shadow.calls[0].res({ kind: 'foreground', exitCode: 0, stdout: { text: 'x' } })+ await new Promise(r => setTimeout(r, 0))+ assert.equal(calls.find(c => c[0] === 'followup' || c[0] === 'inject'), undefined)+ await stop()+})++test('shell shadow: a terminal job read returns the native result', async () => {+ const { emit, stop, rt, agent, shadowOf } = await start({ services: { jobs: jobsService(jobId => ({+ job: { id: jobId, status: 'completed', output: {} }, chunks: [],+ })) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const pending = shadow.execute({ command: 'pwd' }, execOf(agent))+ await emit('dm-a', 'job/registered', { jobId: 'j1', toolCall: { callId: 'c1' } })+ await emit('dm-a', 'agent/inbox/spliced', { target: 'next-step', inserted: [userMessage('go')] })+ const NATIVE = { kind: 'foreground', exitCode: 3 }+ shadow.calls[0].res(NATIVE)+ assert.equal(await pending, NATIVE)+ await stop()+})++test('shell shadow: a native promoted after detach injects only with output', async () => {+ const { emit, stop, rt, agent, calls, shadowOf } = await start({ services: { jobs: jobsService(jobId => ({+ job: { id: jobId, status: 'running', output: {} }, chunks: [],+ })) } })+ rt.shadowShells(agent)+ const shadow = shadowOf()+ const pending = shadow.execute({ command: 'sleep 5' }, execOf(agent))+ await emit('dm-a', 'job/registered', { jobId: 'j1', toolCall: { callId: 'c1' } })+ await emit('dm-a', 'agent/inbox/spliced', { target: 'next-step', inserted: [userMessage('go')] })+ assert.equal((await pending).kind, 'promoted')+ shadow.calls[0].res({ kind: 'promoted', jobId: 'j1', output: 'still going' })+ await new Promise(r => setTimeout(r, 0))+ const notice = calls.find(c => c[0] === 'inject')+ assert.ok(notice !== undefined)+ assert.match(notice[1].content[0].text, /is still running\. Output since your last read:\nstill going/)+ await stop()+})++test('shell shadow: bash is shadowed the same way', async () => {+ const def = shellDef('bash')+ const { emit, stop, rt, agent, calls, } = await start({ services: { jobs: jobsService(jobId => ({+ job: { id: jobId, status: 'running', output: {} }, chunks: [],+ })) }, def })+ rt.shadowShells(agent)+ const shadow = calls.find(c => c[0] === 'register' && c[1].name === 'bash')?.[1]+ assert.ok(shadow !== undefined)+ const pending = shadow.execute({ command: 'sleep 5' }, { agent, callId: 'b1', name: 'bash' })+ await emit('dm-a', 'job/registered', { jobId: 'jb', toolCall: { callId: 'b1' } })+ await emit('dm-a', 'agent/inbox/spliced', { target: 'next-step', inserted: [userMessage('go')] })+ assert.equal((await pending).kind, 'promoted')+ await stop()+})++// Carry tests: the cut turn's routing state rides into the turn that claims the steer.+test('steer carry: a cut request turn hands its answer on the next turn', async () => {+ const { emit, stop, rt, deliveries } = await start()+ const dm = 'dm-a'+ await emit(dm, 'turn/start', { turn: 1 })+ await emit(dm, 'user/message', {+ content: [{ type: 'text', text: 'do the thing' }],+ source: { kind: SOURCE_KIND, role: 'request', senderSessionId: 'bot-b', exchangeId: 'x1', senderName: 'Writer' },+ })+ await emit(dm, 'user/message', {+ content: [{ type: 'text', text: 'me too' }],+ source: { kind: SOURCE_KIND, role: 'request', senderSessionId: 'bot-c', exchangeId: 'x2', senderName: 'Ops' },+ })+ await emit(dm, 'assistant/message', { message: { role: 'assistant', content: [{ type: 'text', text: 'half done' }] } })+ rt.markSteerCut(dm)+ await emit(dm, 'turn/end', { reason: { kind: 'aborted', reason: { kind: 'hook', reason: STEER_CUT } } })+ assert.deepEqual(deliveries, [])+ await emit(dm, 'turn/start', { turn: 2 })+ const entry = rt.live.get(dm)+ assert.equal(entry.info?.exchangeId, 'x1')+ assert.equal(entry.joined.length, 1)+ assert.equal(entry.carried, true)+ assert.deepEqual(entry.texts, ['half done'])+ await emit(dm, 'assistant/message', { message: { role: 'assistant', content: [{ type: 'text', text: 'all done' }] } })+ await emit(dm, 'turn/end', { reason: { kind: 'completed' } })+ const reply = deliveries.find(d => d[0]?.replyTo === 'x1')+ assert.ok(reply !== undefined)+ assert.match(reply[0].text, /half done/)+ assert.match(reply[0].text, /all done/)+ const handback = deliveries.find(d => d[0]?.deferred === true)+ assert.ok(handback !== undefined)+ assert.equal(handback[0].exchangeId, 'x2')+ await stop()+})++test('steer carry: a plain user turn delivers nothing for the cut turn', async () => {+ const { emit, stop, rt, deliveries } = await start()+ const dm = 'dm-a'+ await emit(dm, 'turn/start', { turn: 1 })+ await emit(dm, 'user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } })+ await emit(dm, 'assistant/message', { message: { role: 'assistant', content: [{ type: 'text', text: 'half' }] } })+ rt.markSteerCut(dm)+ await emit(dm, 'turn/end', { reason: { kind: 'aborted', reason: { kind: 'hook', reason: STEER_CUT } } })+ assert.deepEqual(deliveries, [])+ await emit(dm, 'turn/start', { turn: 2 })+ assert.deepEqual(rt.live.get(dm).texts, ['half'])+ await stop()+})++test('steer carry: a cut turn that ends on error keeps normal failure handling', async () => {+ const { emit, stop, rt, deliveries } = await start()+ const dm = 'dm-a'+ await emit(dm, 'turn/start', { turn: 1 })+ await emit(dm, 'user/message', {+ content: [{ type: 'text', text: 'do it' }],+ source: { kind: SOURCE_KIND, role: 'request', senderSessionId: 'bot-b', exchangeId: 'x1', senderName: 'Writer' },+ })+ rt.markSteerCut(dm)+ await emit(dm, 'turn/end', { reason: { kind: 'error', error: { code: 'RATE_LIMIT', message: 'over' } } })+ assert.equal(rt.live.get(dm).carry, undefined)+ const failed = deliveries.find(d => /could not answer/.test(d[0]?.text ?? ''))+ assert.ok(failed !== undefined)+ assert.equal(failed[0].replyTo, 'x1')+ await stop()+})++// Model-cut tests.+test('steer cut: user steer during model phase cancels with hook and moves steer to next-turn', async () => {+ const { emit, stop, agent, calls } = await start()+ const dm = 'dm-a'+ await emit(dm, 'turn/start', { turn: 1 })+ await emit(dm, 'step/start', { turn: 1, step: 1 })+ const steer = userMessage('还没好吗')+ agent.inbox.nextStep.push(steer)+ await emit(dm, 'agent/inbox/spliced', { target: 'next-step', inserted: [steer] })+ const cancel = calls.find(c => c[0] === 'cancel')+ assert.deepEqual(cancel?.[1], { kind: 'hook', reason: STEER_CUT })+ assert.deepEqual(cancel?.[2], { keepInbox: true })+ assert.deepEqual(agent.inbox.nextTurn.map(m => m.id), [steer.id])+ await stop()+})++test('steer cut: no cut during tools phase or for a non-Bot session', async () => {+ const { emit, stop, agent, calls } = await start()+ const dm = 'dm-a'+ await emit(dm, 'turn/start', { turn: 1 })+ await emit(dm, 'step/start', { turn: 1, step: 1 })+ await emit(dm, 'assistant/message', { turn: 1, step: 1, message: { role: 'assistant', content: [{ type: 'tool-call' }] } })+ const steer = userMessage('go')+ agent.inbox.nextStep.push(steer)+ await emit(dm, 'agent/inbox/spliced', { target: 'next-step', inserted: [steer] })+ assert.equal(calls.find(c => c[0] === 'cancel'), undefined)+ await emit('plain', 'agent/inbox/spliced', { target: 'next-step', inserted: [steer] })+ assert.equal(calls.find(c => c[0] === 'cancel'), undefined)+ await stop()+})++test('steer cut: earlier steers and queued next-turn keep order', async () => {+ const { emit, stop, agent } = await start()+ const dm = 'dm-a'+ await emit(dm, 'turn/start', { turn: 1 })+ await emit(dm, 'step/start', { turn: 1, step: 1 })+ const s1 = userMessage('one'); const s2 = userMessage('two')+ agent.inbox.nextStep.push(s1, s2)+ agent.inbox.nextTurn.push(userMessage('queued'))+ await emit(dm, 'agent/inbox/spliced', { target: 'next-step', inserted: [s2] })+ assert.deepEqual(agent.inbox.nextTurn.map(m => m.content[0].text), ['two', 'queued'])+ assert.deepEqual(agent.inbox.nextStep.map(m => m.content[0].text), ['one'])+ await stop()+})