Skip to content

Commit dc1e7ed

Browse files
authored
Keep imported native chat turn numbers consistent (#3385)
## Changes - Use the existing native Session receipt for completed FlyBot replies, including replies composed of several assistant messages. - Import genuine legacy history under DS-Bot’s native maintenance reservation, then start the next turn from the journal’s committed boundary. - Check strict native journal restoration after two replies to a conversation with a live history import. ## Verification - 464 FlyBot runtime plugin tests passed. - Runtime image recipe tests passed. - The affected production session was repaired separately and its existing history opens through the native API.
1 parent 51554f4 commit dc1e7ed

7 files changed

Lines changed: 181 additions & 55 deletions

File tree

‎runtime/flybot-image/Dockerfile‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ COPY third_party/anthropic-sdk /opt/licenses/anthropic-sdk
6767
COPY flybot-social-host /opt/flybot-workspace/runtime/flybot-social-host
6868
COPY flybot-web-slots /opt/flybot-workspace/runtime/flybot-web-slots
6969
COPY flybot-image /opt/flybot-workspace/runtime/flybot-image
70-
RUN node /opt/flybot-workspace/runtime/flybot-image/native-ds-bot-overlay.mjs /opt/flybot-workspace/runtime/ds-bot-upstream/ds-bot
70+
RUN node /opt/flybot-workspace/runtime/flybot-image/native-ds-bot-overlay.mjs /opt/flybot-workspace/runtime/ds-bot-upstream/ds-bot \
71+
&& node /opt/flybot-workspace/runtime/flybot-image/native-dsh-turn-overlay.mjs
7172
COPY flybot-workspace-web /opt/flybot-workspace/runtime/flybot-workspace-web
7273
COPY --from=flybot-workspace-static / /opt/flybot-workspace/runtime/flybot-workspace-web/pages/
7374
RUN node --input-type=module -e 'import {writeChatAssetManifest} from "/opt/flybot-workspace/runtime/flybot-workspace-web/src/pages.js"; await writeChatAssetManifest("/opt/flybot-workspace/runtime/flybot-workspace-web/pages")'
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Keep the pinned DSH driver aligned with its journal after FlyBot imports
2+
// historical turns under the native Agent's idle maintenance reservation.
3+
import {readFileSync, writeFileSync} from 'node:fs'
4+
import {createRequire} from 'node:module'
5+
import {dirname, join} from 'node:path'
6+
7+
const harnessPackage = process.argv[2] || '/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json'
8+
const requireFromHarness = createRequire(harnessPackage)
9+
const entry = requireFromHarness.resolve('@deepseek-ai/dsh-agent-loop')
10+
const manifest = JSON.parse(readFileSync(join(dirname(entry), '../package.json'), 'utf8'))
11+
if (manifest.name !== '@deepseek-ai/dsh-agent-loop') throw new Error('Unexpected native agent driver package')
12+
13+
const source = readFileSync(entry, 'utf8')
14+
const before = '\t\t\tturn: this.phase.lastTurn,'
15+
const after = '\t\t\tturn: this.loopCtx.agents.turnBoundaryOf(this.session).lastTurn,'
16+
if (source.split(before).length !== 2 || source.includes(after)) {
17+
throw new Error('Native agent wake boundary changed. Review the FlyBot history import against this DSH version.')
18+
}
19+
writeFileSync(entry, source.replace(before, after))

‎runtime/flybot-image/plugin/index.js‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ import { boundName } from '../../flybot-workspace-web/features/skills/index.js'
1414
import { nativeSkillFilter, reconcileStartupSkills } from '../../flybot-workspace-web/features/skills/library.js'
1515
import { assertNativeConsentOverlay } from '../native-ds-bot-overlay.mjs'
1616

17-
// Same inject list as runtime/ds-bot-upstream/ds-bot/index.js — this plugin
18-
// stands in for ds-bot in the web profile so createRuntime runs once.
17+
// This wrapper stands in for DS-Bot and also reads the native turn
18+
// boundary projection when importing FlyBot's previous chat history.
1919
export const name = 'flybot-workspace-flybot'
20-
export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'sessions', 'sessionTitle', 'workspaceRegistry', 'connection']
20+
export const inject = ['agents', 'llm', 'tools', 'systemPrompt', 'sessionController', 'sessions', 'sessionTitle', 'workspaceRegistry', 'connection']
2121

2222
export function apply(ctx, config = {}) {
2323
assertNativeConsentOverlay()

‎runtime/flybot-image/test/container-gateway-isolation.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,39 @@ def api(token, method, path, payload=None, expected=200, timeout=20):
413413
assert api(token_b, 'GET', agents)['items'] == [], "B never sees A's agents"
414414
api(token_b, 'GET', chat, expected=404)
415415

416+
# A migrated reply can be appended while the native Agent is already live.
417+
# The next two real turns must resume from the journal's native boundary.
418+
docker('exec', a['name'], 'node', '-e', """
419+
const {DatabaseSync} = require('node:sqlite')
420+
const db = new DatabaseSync('/data/flybot-workspace/features/agents/agents.sqlite3', {timeout:2000})
421+
db.prepare('INSERT INTO agent_messages VALUES(?,?,?,?,?,?,?)')
422+
.run('d'.repeat(32),process.argv[1],'assistant','Imported fixture reply','succeeded',
423+
Math.floor(Date.now()/1000),'{}')
424+
db.close()
425+
""", convo['id'])
426+
for prompt in ('first turn after history import', 'next turn in the same chat'):
427+
after_import = api(token_a, 'POST', f'{chat}/messages', {'body': prompt}, expected=201, timeout=150)
428+
assert after_import['reply']['status'] == 'succeeded', 'native reply after history import completed'
429+
docker('exec', a['name'], 'node', '--input-type=module', '-e', r"""
430+
import assert from 'node:assert/strict'
431+
import {globSync,readFileSync} from 'node:fs'
432+
import {createRequire} from 'node:module'
433+
import {pathToFileURL} from 'node:url'
434+
import {zstdDecompressSync} from 'node:zlib'
435+
const requireFromDSH = createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json')
436+
const {sessionFormatCatalog} = await import(pathToFileURL(requireFromDSH.resolve('@deepseek-ai/dsh-session-format-catalog')).href)
437+
const session = process.argv[1]
438+
const files = globSync('/data/sessions/**/' + session + '/session.v4.jsonl.zstd')
439+
assert.equal(files.length,1)
440+
const [header,...events] = zstdDecompressSync(readFileSync(files[0])).toString().trim().split('\n').map(JSON.parse)
441+
const restore = sessionFormatCatalog.createRestore(header,{recovery:'strict',validation:'current'})
442+
for (const event of events) restore.decodeRow(event)
443+
restore.finish()
444+
const turns = events.filter(event => event.type==='turn/start')
445+
assert.deepEqual(turns.map(event => event.data.turn),[1,2,3,4])
446+
assert.equal(turns.filter(event => event.data.source?.kind==='flybot-workspace-history').length,1)
447+
""", history['conversation']['native_session_id'])
448+
416449
def plugin(token, endpoint, payload=None, kind='flybot-workspace'):
417450
status, _h, response = browse(token, 'POST', f'/b/api/{kind}',
418451
json.dumps({'endpoint': endpoint, 'payload': payload}))

‎runtime/flybot-workspace-web/features/agents/history.js‎

Lines changed: 82 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,19 @@ export async function importHistory({ db, rt, ctx, bot, conversationId, sessionI
4545
if (thread) scan.add(thread.sessionId)
4646
scan.add(sid)
4747
}
48+
const put = db.prepare('INSERT OR IGNORE INTO native_agent_events VALUES(?,?,?,?)')
49+
const missing = rows.filter(row => {
50+
const meta = JSON.parse(row.meta || '{}')
51+
// A successful Web reply can combine multiple native assistant messages.
52+
// Its owned Session receipt is authoritative even without one matching event.
53+
if (row.role !== 'assistant' || row.status !== 'succeeded' ||
54+
meta.engine !== 'ds-bot' || !scan.has(meta.session_id)) return true
55+
put.run(row.id, meta.session_id, null, 'native')
56+
return false
57+
})
58+
let matched = rows.length - missing.length
59+
if (!missing.length) return { imported:0, matched }
60+
4861
const events = []
4962
for (const id of scan) {
5063
const agent = await rt.resolveAgent(id); await ctx.sessions.flush(agent.session)
@@ -59,56 +72,78 @@ export async function importHistory({ db, rt, ctx, bot, conversationId, sessionI
5972
}
6073
}
6174
events.sort((a,b)=>a.time-b.time || a.seq-b.seq)
62-
const used = new Set(events.flatMap((e,i)=>db.prepare('SELECT 1 FROM native_agent_events WHERE session_id=? AND event_seq=?').get(e.id,e.seq) ? [i] : [])), put = db.prepare('INSERT OR IGNORE INTO native_agent_events VALUES(?,?,?,?)')
75+
const recorded = db.prepare('SELECT 1 FROM native_agent_events WHERE session_id=? AND event_seq=?')
76+
const used = new Set(events.flatMap((event, index) => recorded.get(event.id, event.seq) ? [index] : []))
77+
const imports = []
78+
for (const row of missing) {
79+
const index = events.findIndex((event, i) => !used.has(i) && (event.tag === row.id ||
80+
event.rpc === 'ot-agent:' + row.id || event.rpc === 'otp:' + row.id ||
81+
(event.role === row.role && event.text === row.text && row.text)))
82+
if (index < 0) {
83+
imports.push(row)
84+
continue
85+
}
86+
const known = events[index]
87+
used.add(index)
88+
put.run(row.id, known.id, known.seq, 'adopted')
89+
matched++
90+
}
91+
if (!imports.length) return { imported:0, matched }
92+
6393
const writeSessionId = privateChatThread(bot, sessionId)?.sessionId ?? sessionId
6494
const agent = await rt.resolveAgent(writeSessionId)
65-
let imported=0,matched=0
66-
// A native system head must precede the first surface message. This is an
67-
// EMPTY current initialization, not a historical prompt or model response.
68-
// Native execution replaces it with the actual scoped prompt before inference.
69-
const initializeHead = async () => {
70-
if (agent.session.surface.nodes.length) return
71-
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-llm')).href)
72-
const source={kind:'flybot-workspace-initialization',reason:'protect-native-history-head',noModelCall:true}
73-
let turn=1
74-
for(let seq=0;seq<agent.session.seq;seq++){const e=agent.session.eventAt(seq);if(e.type==='turn/start')turn=Math.max(turn,e.data.turn+1)}
75-
agent.session.append('turn/start',{turn,source})
76-
agent.session.append('step/start',{turn,step:1,source})
77-
agent.session.append('system/message',{turn,step:1,message:native.createSystemMessage('')},{surfaceOp:'append'})
78-
agent.session.append('step/end',{turn,step:1,source})
79-
agent.session.append('turn/end',{turn,source})
80-
await ctx.sessions.flush(agent.session)
81-
}
82-
for(const row of rows){
83-
const known=events.find((e,i)=>!used.has(i) && (e.tag===row.id || e.rpc==='ot-agent:'+row.id || e.rpc==='otp:'+row.id || (e.role===row.role && e.text===row.text && row.text)))
84-
if(known){ used.add(events.indexOf(known));put.run(row.id,known.id,known.seq,'adopted');matched++;continue }
85-
await initializeHead()
86-
// Failed/empty messages remain visible diagnostic events, not fabricated replies.
87-
const source={kind:'user',flybotWorkspaceMessageId:row.id,originalTime:row.created*1000,imported:true,status:row.status}
88-
let event
89-
if(!row.text || row.status==='failed') {
90-
// Resolve the engine's public module, not a second private-class copy.
91-
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-session')).href)
92-
const seq = native.appendPluginRecord(agent.session,'plugin:flybot-workspace/message-status',{source,role:row.role,text:row.text,status:row.status})
93-
event=agent.session.eventAt(seq)
94-
} else if(row.role==='user') event=agent.session.append('user/message',{id:row.id,role:'user',source,content:[{type:'text',text:row.text}]},{surfaceOp:'append'})
95-
else {
96-
// Imported transcript boundary, NOT a new model invocation. Provider/model
97-
// were not retained by the legacy platform, so explicitly label them unknown.
98-
let turn=1
99-
for(let seq=0;seq<agent.session.seq;seq++){const e=agent.session.eventAt(seq);if(e.type==='turn/start')turn=Math.max(turn,e.data.turn+1)}
100-
const history={...source,kind:'flybot-workspace-history'}
101-
agent.session.append('turn/start',{turn,source:history,imported:true})
102-
agent.session.append('step/start',{turn,step:1,source:history,imported:true})
103-
event=agent.session.append('assistant/message',{turn,step:1,source,stream:[],message:{id:row.id,role:'assistant',source:{...history,kind:'model',provider:'flybot-workspace-history',model:'historical-unknown'},content:[{type:'text',text:row.text}]}},{surfaceOp:'append'})
104-
agent.session.append('step/end',{turn,step:1,source:history,imported:true})
105-
agent.session.append('turn/end',{turn,source:history,imported:true})
95+
// Queue native input behind the import while the transcript is being flushed.
96+
await agent.whenIdle()
97+
return agent.runMaintenance(async signal => {
98+
let imported = 0
99+
// A native system head must precede the first surface message. This is an
100+
// EMPTY current initialization, not a historical prompt or model response.
101+
// Native execution replaces it with the actual scoped prompt before inference.
102+
const nextTurn = () => ctx.agents.turnBoundaryOf(agent.session).lastTurn + 1
103+
const initializeHead = async () => {
104+
if (agent.session.surface.nodes.length) return
105+
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-llm')).href)
106+
const source={kind:'flybot-workspace-initialization',reason:'protect-native-history-head',noModelCall:true}
107+
signal.throwIfAborted()
108+
const turn = nextTurn()
109+
agent.session.append('turn/start',{turn,source})
110+
agent.session.append('step/start',{turn,step:1,source})
111+
agent.session.append('system/message',{turn,step:1,message:native.createSystemMessage('')},{surfaceOp:'append'})
112+
agent.session.append('step/end',{turn,step:1,source})
113+
agent.session.append('turn/end',{turn,source})
114+
await ctx.sessions.flush(agent.session)
106115
}
107-
// Flush BEFORE mapping: a crash between these is recovered by event source id.
108-
await ctx.sessions.flush(agent.session)
109-
put.run(row.id,writeSessionId,event.seq,'imported'); imported++
110-
}
111-
return { imported,matched }
116+
for (const row of imports) {
117+
signal.throwIfAborted()
118+
await initializeHead()
119+
signal.throwIfAborted()
120+
// Failed/empty messages remain visible diagnostic events, not fabricated replies.
121+
const source={kind:'user',flybotWorkspaceMessageId:row.id,originalTime:row.created*1000,imported:true,status:row.status}
122+
let event
123+
if(!row.text || row.status==='failed') {
124+
// Resolve the engine's public module, not a second private-class copy.
125+
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-session')).href)
126+
signal.throwIfAborted()
127+
const seq = native.appendPluginRecord(agent.session,'plugin:flybot-workspace/message-status',{source,role:row.role,text:row.text,status:row.status})
128+
event=agent.session.eventAt(seq)
129+
} else if(row.role==='user') event=agent.session.append('user/message',{id:row.id,role:'user',source,content:[{type:'text',text:row.text}]},{surfaceOp:'append'})
130+
else {
131+
// Imported transcript boundary, NOT a new model invocation. Provider/model
132+
// were not retained by the legacy platform, so explicitly label them unknown.
133+
const turn = nextTurn()
134+
const history={...source,kind:'flybot-workspace-history'}
135+
agent.session.append('turn/start',{turn,source:history,imported:true})
136+
agent.session.append('step/start',{turn,step:1,source:history,imported:true})
137+
event=agent.session.append('assistant/message',{turn,step:1,source,stream:[],message:{id:row.id,role:'assistant',source:{...history,kind:'model',provider:'flybot-workspace-history',model:'historical-unknown'},content:[{type:'text',text:row.text}]}},{surfaceOp:'append'})
138+
agent.session.append('step/end',{turn,step:1,source:history,imported:true})
139+
agent.session.append('turn/end',{turn,source:history,imported:true})
140+
}
141+
// Flush BEFORE mapping: a crash between these is recovered by event source id.
142+
await ctx.sessions.flush(agent.session)
143+
put.run(row.id,writeSessionId,event.seq,'imported'); imported++
144+
}
145+
return { imported,matched }
146+
})
112147
}
113148

114149
// Compatibility for the first history-import release: those append-only events

‎runtime/flybot-workspace-web/test/native-agent-fixture.js‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,22 @@ export function nativeAgentFixture({ reply = () => 'DS-Bot reply', available = t
3232
return event
3333
},
3434
}
35-
sessions.set(id, { session, events })
35+
sessions.set(id, { session, events, async whenIdle() {},
36+
runMaintenance: job => job(new AbortController().signal) })
3637
return id
3738
},
3839
async resolveAgent(id) { return sessions.get(id) },
3940
async* eventsBackwards(id) { yield* sessions.get(id).events.toReversed() },
4041
}
4142
const services = {
4243
rt,
43-
ctx: { sessions: { flush: async () => {} } },
44+
ctx: {
45+
sessions: { flush: async () => {} },
46+
agents: {turnBoundaryOf(session) {
47+
const event = sessions.get(session.id).events.findLast(event => event.type === 'turn/end')
48+
return {lastTurn: event?.data.turn ?? 0}
49+
}},
50+
},
4451
mainBot: async () => 'main',
4552
...(available ? {
4653
chatTurn: async () => assert.fail('Expected execution through the native Bot and Session'),

‎runtime/flybot-workspace-web/test/native-history-fast-path.test.js‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,41 @@ test('history adoption appends a same-second question before its answer', async
3737
return event
3838
},
3939
}
40-
const rt = {async *eventsBackwards() {}, resolveAgent: async () => ({session})}
41-
const ctx = {sessions: {flush: async () => {}}}
40+
let maintaining = false
41+
const agent = {
42+
session,
43+
async whenIdle() {},
44+
async runMaintenance(job) {
45+
maintaining = true
46+
try { return await job(new AbortController().signal) }
47+
finally { maintaining = false }
48+
},
49+
}
50+
const rt = {async *eventsBackwards() {}, resolveAgent: async () => agent}
51+
const ctx = {
52+
sessions: {flush: async () => {}},
53+
agents: {turnBoundaryOf() {
54+
assert.equal(maintaining, true)
55+
return {lastTurn: events.findLast(event => event.type === 'turn/end')?.data.turn ?? 0}
56+
}},
57+
}
4258
assert.deepEqual(await importHistory({db, rt, ctx, bot: {}, conversationId: 'c', sessionId: 's'}),
4359
{imported: 2, matched: 0})
4460
assert.deepEqual(events.filter(event => /^(user|assistant)\/message$/.test(event.type))
4561
.map(event => event.data.source.flybotWorkspaceMessageId), ['zzz', 'aaa'])
4662
})
63+
64+
test('a composed reply with an owned native receipt never creates a synthetic turn', async t => {
65+
const db = new DatabaseSync(':memory:')
66+
t.after(() => db.close())
67+
db.exec(`CREATE TABLE agent_messages (id TEXT PRIMARY KEY, conversation_id TEXT, created INTEGER, meta TEXT, status TEXT,
68+
role TEXT, text TEXT);
69+
INSERT INTO agent_messages VALUES
70+
('combined','c',1,'{"engine":"ds-bot","session_id":"s","turn_id":"turn-2"}','succeeded','assistant','First pass and final answer');`)
71+
const rt = {resolveAgent() { assert.fail('An owned receipt does not require replay or a native scan') }}
72+
const args = {db, rt, conversationId:'c', sessionId:'s', bot:{}}
73+
assert.deepEqual(await importHistory(args), {imported:0, matched:1})
74+
const record = db.prepare('SELECT * FROM native_agent_events').get()
75+
assert.deepEqual({...record}, {message_id:'combined', session_id:'s', event_seq:null, source:'native'})
76+
assert.deepEqual(await importHistory(args), {imported:0, matched:0})
77+
})

0 commit comments

Comments
 (0)