Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion runtime/flybot-image/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ COPY third_party/anthropic-sdk /opt/licenses/anthropic-sdk
COPY flybot-social-host /opt/flybot-workspace/runtime/flybot-social-host
COPY flybot-web-slots /opt/flybot-workspace/runtime/flybot-web-slots
COPY flybot-image /opt/flybot-workspace/runtime/flybot-image
RUN node /opt/flybot-workspace/runtime/flybot-image/native-ds-bot-overlay.mjs /opt/flybot-workspace/runtime/ds-bot-upstream/ds-bot
RUN node /opt/flybot-workspace/runtime/flybot-image/native-ds-bot-overlay.mjs /opt/flybot-workspace/runtime/ds-bot-upstream/ds-bot \
&& node /opt/flybot-workspace/runtime/flybot-image/native-dsh-turn-overlay.mjs
COPY flybot-workspace-web /opt/flybot-workspace/runtime/flybot-workspace-web
COPY --from=flybot-workspace-static / /opt/flybot-workspace/runtime/flybot-workspace-web/pages/
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")'
Expand Down
19 changes: 19 additions & 0 deletions runtime/flybot-image/native-dsh-turn-overlay.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Keep the pinned DSH driver aligned with its journal after FlyBot imports
// historical turns under the native Agent's idle maintenance reservation.
import {readFileSync, writeFileSync} from 'node:fs'
import {createRequire} from 'node:module'
import {dirname, join} from 'node:path'

const harnessPackage = process.argv[2] || '/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json'
const requireFromHarness = createRequire(harnessPackage)
const entry = requireFromHarness.resolve('@deepseek-ai/dsh-agent-loop')
const manifest = JSON.parse(readFileSync(join(dirname(entry), '../package.json'), 'utf8'))
if (manifest.name !== '@deepseek-ai/dsh-agent-loop') throw new Error('Unexpected native agent driver package')

const source = readFileSync(entry, 'utf8')
const before = '\t\t\tturn: this.phase.lastTurn,'
const after = '\t\t\tturn: this.loopCtx.agents.turnBoundaryOf(this.session).lastTurn,'
if (source.split(before).length !== 2 || source.includes(after)) {
throw new Error('Native agent wake boundary changed. Review the FlyBot history import against this DSH version.')
}
writeFileSync(entry, source.replace(before, after))
6 changes: 3 additions & 3 deletions runtime/flybot-image/plugin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ import { boundName } from '../../flybot-workspace-web/features/skills/index.js'
import { nativeSkillFilter, reconcileStartupSkills } from '../../flybot-workspace-web/features/skills/library.js'
import { assertNativeConsentOverlay } from '../native-ds-bot-overlay.mjs'

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

export function apply(ctx, config = {}) {
assertNativeConsentOverlay()
Expand Down
33 changes: 33 additions & 0 deletions runtime/flybot-image/test/container-gateway-isolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,39 @@ def api(token, method, path, payload=None, expected=200, timeout=20):
assert api(token_b, 'GET', agents)['items'] == [], "B never sees A's agents"
api(token_b, 'GET', chat, expected=404)

# A migrated reply can be appended while the native Agent is already live.
# The next two real turns must resume from the journal's native boundary.
docker('exec', a['name'], 'node', '-e', """
const {DatabaseSync} = require('node:sqlite')
const db = new DatabaseSync('/data/flybot-workspace/features/agents/agents.sqlite3', {timeout:2000})
db.prepare('INSERT INTO agent_messages VALUES(?,?,?,?,?,?,?)')
.run('d'.repeat(32),process.argv[1],'assistant','Imported fixture reply','succeeded',
Math.floor(Date.now()/1000),'{}')
db.close()
""", convo['id'])
for prompt in ('first turn after history import', 'next turn in the same chat'):
after_import = api(token_a, 'POST', f'{chat}/messages', {'body': prompt}, expected=201, timeout=150)
assert after_import['reply']['status'] == 'succeeded', 'native reply after history import completed'
docker('exec', a['name'], 'node', '--input-type=module', '-e', r"""
import assert from 'node:assert/strict'
import {globSync,readFileSync} from 'node:fs'
import {createRequire} from 'node:module'
import {pathToFileURL} from 'node:url'
import {zstdDecompressSync} from 'node:zlib'
const requireFromDSH = createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json')
const {sessionFormatCatalog} = await import(pathToFileURL(requireFromDSH.resolve('@deepseek-ai/dsh-session-format-catalog')).href)
const session = process.argv[1]
const files = globSync('/data/sessions/**/' + session + '/session.v4.jsonl.zstd')
assert.equal(files.length,1)
const [header,...events] = zstdDecompressSync(readFileSync(files[0])).toString().trim().split('\n').map(JSON.parse)
const restore = sessionFormatCatalog.createRestore(header,{recovery:'strict',validation:'current'})
for (const event of events) restore.decodeRow(event)
restore.finish()
const turns = events.filter(event => event.type==='turn/start')
assert.deepEqual(turns.map(event => event.data.turn),[1,2,3,4])
assert.equal(turns.filter(event => event.data.source?.kind==='flybot-workspace-history').length,1)
""", history['conversation']['native_session_id'])

def plugin(token, endpoint, payload=None, kind='flybot-workspace'):
status, _h, response = browse(token, 'POST', f'/b/api/{kind}',
json.dumps({'endpoint': endpoint, 'payload': payload}))
Expand Down
129 changes: 82 additions & 47 deletions runtime/flybot-workspace-web/features/agents/history.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ export async function importHistory({ db, rt, ctx, bot, conversationId, sessionI
if (thread) scan.add(thread.sessionId)
scan.add(sid)
}
const put = db.prepare('INSERT OR IGNORE INTO native_agent_events VALUES(?,?,?,?)')
const missing = rows.filter(row => {
const meta = JSON.parse(row.meta || '{}')
// A successful Web reply can combine multiple native assistant messages.
// Its owned Session receipt is authoritative even without one matching event.
if (row.role !== 'assistant' || row.status !== 'succeeded' ||
meta.engine !== 'ds-bot' || !scan.has(meta.session_id)) return true
put.run(row.id, meta.session_id, null, 'native')
return false
})
let matched = rows.length - missing.length
if (!missing.length) return { imported:0, matched }

const events = []
for (const id of scan) {
const agent = await rt.resolveAgent(id); await ctx.sessions.flush(agent.session)
Expand All @@ -59,56 +72,78 @@ export async function importHistory({ db, rt, ctx, bot, conversationId, sessionI
}
}
events.sort((a,b)=>a.time-b.time || a.seq-b.seq)
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(?,?,?,?)')
const recorded = db.prepare('SELECT 1 FROM native_agent_events WHERE session_id=? AND event_seq=?')
const used = new Set(events.flatMap((event, index) => recorded.get(event.id, event.seq) ? [index] : []))
const imports = []
for (const row of missing) {
const index = events.findIndex((event, i) => !used.has(i) && (event.tag === row.id ||
event.rpc === 'ot-agent:' + row.id || event.rpc === 'otp:' + row.id ||
(event.role === row.role && event.text === row.text && row.text)))
if (index < 0) {
imports.push(row)
continue
}
const known = events[index]
used.add(index)
put.run(row.id, known.id, known.seq, 'adopted')
matched++
}
if (!imports.length) return { imported:0, matched }

const writeSessionId = privateChatThread(bot, sessionId)?.sessionId ?? sessionId
const agent = await rt.resolveAgent(writeSessionId)
let imported=0,matched=0
// A native system head must precede the first surface message. This is an
// EMPTY current initialization, not a historical prompt or model response.
// Native execution replaces it with the actual scoped prompt before inference.
const initializeHead = async () => {
if (agent.session.surface.nodes.length) return
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-llm')).href)
const source={kind:'flybot-workspace-initialization',reason:'protect-native-history-head',noModelCall:true}
let turn=1
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)}
agent.session.append('turn/start',{turn,source})
agent.session.append('step/start',{turn,step:1,source})
agent.session.append('system/message',{turn,step:1,message:native.createSystemMessage('')},{surfaceOp:'append'})
agent.session.append('step/end',{turn,step:1,source})
agent.session.append('turn/end',{turn,source})
await ctx.sessions.flush(agent.session)
}
for(const row of rows){
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)))
if(known){ used.add(events.indexOf(known));put.run(row.id,known.id,known.seq,'adopted');matched++;continue }
await initializeHead()
// Failed/empty messages remain visible diagnostic events, not fabricated replies.
const source={kind:'user',flybotWorkspaceMessageId:row.id,originalTime:row.created*1000,imported:true,status:row.status}
let event
if(!row.text || row.status==='failed') {
// Resolve the engine's public module, not a second private-class copy.
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-session')).href)
const seq = native.appendPluginRecord(agent.session,'plugin:flybot-workspace/message-status',{source,role:row.role,text:row.text,status:row.status})
event=agent.session.eventAt(seq)
} 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'})
else {
// Imported transcript boundary, NOT a new model invocation. Provider/model
// were not retained by the legacy platform, so explicitly label them unknown.
let turn=1
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)}
const history={...source,kind:'flybot-workspace-history'}
agent.session.append('turn/start',{turn,source:history,imported:true})
agent.session.append('step/start',{turn,step:1,source:history,imported:true})
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'})
agent.session.append('step/end',{turn,step:1,source:history,imported:true})
agent.session.append('turn/end',{turn,source:history,imported:true})
// Queue native input behind the import while the transcript is being flushed.
await agent.whenIdle()
return agent.runMaintenance(async signal => {
let imported = 0
// A native system head must precede the first surface message. This is an
// EMPTY current initialization, not a historical prompt or model response.
// Native execution replaces it with the actual scoped prompt before inference.
const nextTurn = () => ctx.agents.turnBoundaryOf(agent.session).lastTurn + 1
const initializeHead = async () => {
if (agent.session.surface.nodes.length) return
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-llm')).href)
const source={kind:'flybot-workspace-initialization',reason:'protect-native-history-head',noModelCall:true}
signal.throwIfAborted()
const turn = nextTurn()
agent.session.append('turn/start',{turn,source})
agent.session.append('step/start',{turn,step:1,source})
agent.session.append('system/message',{turn,step:1,message:native.createSystemMessage('')},{surfaceOp:'append'})
agent.session.append('step/end',{turn,step:1,source})
agent.session.append('turn/end',{turn,source})
await ctx.sessions.flush(agent.session)
}
// Flush BEFORE mapping: a crash between these is recovered by event source id.
await ctx.sessions.flush(agent.session)
put.run(row.id,writeSessionId,event.seq,'imported'); imported++
}
return { imported,matched }
for (const row of imports) {
signal.throwIfAborted()
await initializeHead()
signal.throwIfAborted()
// Failed/empty messages remain visible diagnostic events, not fabricated replies.
const source={kind:'user',flybotWorkspaceMessageId:row.id,originalTime:row.created*1000,imported:true,status:row.status}
let event
if(!row.text || row.status==='failed') {
// Resolve the engine's public module, not a second private-class copy.
const native = await import(pathToFileURL(createRequire('/usr/local/lib/node_modules/@deepseek-ai/dsh/package.json').resolve('@deepseek-ai/dsh-session')).href)
signal.throwIfAborted()
const seq = native.appendPluginRecord(agent.session,'plugin:flybot-workspace/message-status',{source,role:row.role,text:row.text,status:row.status})
event=agent.session.eventAt(seq)
} 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'})
else {
// Imported transcript boundary, NOT a new model invocation. Provider/model
// were not retained by the legacy platform, so explicitly label them unknown.
const turn = nextTurn()
const history={...source,kind:'flybot-workspace-history'}
agent.session.append('turn/start',{turn,source:history,imported:true})
agent.session.append('step/start',{turn,step:1,source:history,imported:true})
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'})
agent.session.append('step/end',{turn,step:1,source:history,imported:true})
agent.session.append('turn/end',{turn,source:history,imported:true})
}
// Flush BEFORE mapping: a crash between these is recovered by event source id.
await ctx.sessions.flush(agent.session)
put.run(row.id,writeSessionId,event.seq,'imported'); imported++
}
return { imported,matched }
})
}

// Compatibility for the first history-import release: those append-only events
Expand Down
11 changes: 9 additions & 2 deletions runtime/flybot-workspace-web/test/native-agent-fixture.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,22 @@ export function nativeAgentFixture({ reply = () => 'DS-Bot reply', available = t
return event
},
}
sessions.set(id, { session, events })
sessions.set(id, { session, events, async whenIdle() {},
runMaintenance: job => job(new AbortController().signal) })
return id
},
async resolveAgent(id) { return sessions.get(id) },
async* eventsBackwards(id) { yield* sessions.get(id).events.toReversed() },
}
const services = {
rt,
ctx: { sessions: { flush: async () => {} } },
ctx: {
sessions: { flush: async () => {} },
agents: {turnBoundaryOf(session) {
const event = sessions.get(session.id).events.findLast(event => event.type === 'turn/end')
return {lastTurn: event?.data.turn ?? 0}
}},
},
mainBot: async () => 'main',
...(available ? {
chatTurn: async () => assert.fail('Expected execution through the native Bot and Session'),
Expand Down
35 changes: 33 additions & 2 deletions runtime/flybot-workspace-web/test/native-history-fast-path.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,41 @@ test('history adoption appends a same-second question before its answer', async
return event
},
}
const rt = {async *eventsBackwards() {}, resolveAgent: async () => ({session})}
const ctx = {sessions: {flush: async () => {}}}
let maintaining = false
const agent = {
session,
async whenIdle() {},
async runMaintenance(job) {
maintaining = true
try { return await job(new AbortController().signal) }
finally { maintaining = false }
},
}
const rt = {async *eventsBackwards() {}, resolveAgent: async () => agent}
const ctx = {
sessions: {flush: async () => {}},
agents: {turnBoundaryOf() {
assert.equal(maintaining, true)
return {lastTurn: events.findLast(event => event.type === 'turn/end')?.data.turn ?? 0}
}},
}
assert.deepEqual(await importHistory({db, rt, ctx, bot: {}, conversationId: 'c', sessionId: 's'}),
{imported: 2, matched: 0})
assert.deepEqual(events.filter(event => /^(user|assistant)\/message$/.test(event.type))
.map(event => event.data.source.flybotWorkspaceMessageId), ['zzz', 'aaa'])
})

test('a composed reply with an owned native receipt never creates a synthetic turn', async t => {
const db = new DatabaseSync(':memory:')
t.after(() => db.close())
db.exec(`CREATE TABLE agent_messages (id TEXT PRIMARY KEY, conversation_id TEXT, created INTEGER, meta TEXT, status TEXT,
role TEXT, text TEXT);
INSERT INTO agent_messages VALUES
('combined','c',1,'{"engine":"ds-bot","session_id":"s","turn_id":"turn-2"}','succeeded','assistant','First pass and final answer');`)
const rt = {resolveAgent() { assert.fail('An owned receipt does not require replay or a native scan') }}
const args = {db, rt, conversationId:'c', sessionId:'s', bot:{}}
assert.deepEqual(await importHistory(args), {imported:0, matched:1})
const record = db.prepare('SELECT * FROM native_agent_events').get()
assert.deepEqual({...record}, {message_id:'combined', session_id:'s', event_seq:null, source:'native'})
assert.deepEqual(await importHistory(args), {imported:0, matched:0})
})
Loading