@@ -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
0 commit comments