python-browser-use-events.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132
  1. /** Replay Stagehand's recorded auxiliary events through the packaged SDK's event projection. */
  2. import { randomUUID } from 'node:crypto'
  3. import { readFileSync } from 'node:fs'
  4. export const name = 'python-browser-use-events'
  5. export const inject = ['sessions']
  6. /**
  7. * @param {import('@deepseek-ai/cordis').Context} ctx - Snapshot runtime services.
  8. */
  9. export function apply(ctx) {
  10. const fixture = new URL('../../snapshots/session/browser-use-stagehand-native/session.v3.jsonl', import.meta.url)
  11. const events = readFileSync(fixture, 'utf8').trimEnd().split('\n').map(line => JSON.parse(line))
  12. const request = events.find(event => event.type === 'browser-use/stagehand-llm-request')
  13. const result = events.find(event => event.type === 'browser-use/stagehand-llm-result')
  14. if (request === undefined || result === undefined) throw new Error('Stagehand recording lacks auxiliary inference events')
  15. ctx.on('agent/turn-stopping', async ({ agent }) => {
  16. if (agent.session.header.parentSession !== undefined) return
  17. const before = JSON.stringify(agent.session.deriveMessages())
  18. const requestData = structuredClone(request.data)
  19. requestData.request.sessionId = agent.session.id
  20. for (const message of requestData.request.messages) message.id = randomUUID()
  21. const logged = agent.session.append(request.type, requestData)
  22. await ctx.sessions.flush(agent.session)
  23. agent.session.append(result.type, { ...structuredClone(result.data), requestSeq: logged.seq })
  24. await ctx.sessions.flush(agent.session)
  25. if (JSON.stringify(agent.session.deriveMessages()) !== before) {
  26. throw new Error('Stagehand auxiliary events changed model-visible messages')
  27. }
  28. })
  29. }