Skip to content

armgit / fx0

Public Imported from GitHub
0

A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.

TypeScript

Rebind a running turn before each model request

Pranit9c0441aae7af
diff --git a/lib/draft-context.ts b/lib/draft-context.ts
index ef45fc9..754fa6b 100644
--- a/lib/draft-context.ts
+++ b/lib/draft-context.ts
@@ -1,21 +1,32 @@
// Bind transport to the prompt libfx actually executes, including an open turn
// restored in a fresh worker. Submitted prompts may still be waiting in its queue.
+// Every execution hook names its session and turn, and one (model.start) comes
+// before each model request, so a binding the size cap evicted while its turn
+// waited, for example on a question, is back before the request that needs it.
export function createDraftContext() {
const turns = new Map<string, number>()
const setTurn = (sessionId: string, value: unknown) => {
const match = typeof value === 'string' ? /^m([1-9][0-9]*)$/.exec(value) : null
if (!match || !Number.isSafeInteger(Number(match[1]))) return false
+ // Re-inserting keeps the map in order of last activity, so the cap evicts
+ // the session that has been quiet longest.
+ turns.delete(sessionId)
turns.set(sessionId, Number(match[1]))
if (turns.size > 200) turns.delete(turns.keys().next().value!)
return true
}
return {
- observe(event: { type: string; message?: unknown; sessionId?: string; data?: unknown }) {
+ observe(event: { type: string; message?: unknown; sessionId?: string; turnId?: unknown; data?: unknown }) {
if (event.type === 'journal.restore' && event.sessionId) {
const data = event.data as { resumable?: boolean; openTurnId?: unknown } | undefined
if (!data?.resumable || !setTurn(event.sessionId, data.openTurnId)) turns.delete(event.sessionId)
return
}
+ // Hook events carry the executing turn; engine and session diagnostics don't.
+ if (event.sessionId && typeof event.turnId === 'string') {
+ setTurn(event.sessionId, event.turnId)
+ return
+ }
if (event.type !== 'acp.send') return
const message = event.message as { method?: string; params?: { sessionId?: string; _meta?: { fx?: { turnId?: string } } } } | undefined
if (message?.method !== 'session/prompt' || !message.params?.sessionId) return
diff --git a/tests/libfx-transport.test.mjs b/tests/libfx-transport.test.mjs
index 02cdb99..6b817a1 100644
--- a/tests/libfx-transport.test.mjs
+++ b/tests/libfx-transport.test.mjs
@@ -55,6 +55,43 @@ test('installed libfx dispatch uses the user-scoped transport rather than a shar
}
})
+test('installed libfx rebinds a running turn the session cap evicted before its next model request', { timeout: 10_000 }, async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'fx0-binding-'))
+ const drafts = createDraftContext()
+ const seen = []
+ const sse = (...items) => new Response([...items.map((item) => `data: ${JSON.stringify(item)}`), 'data: [DONE]', ''].join('\n\n'),
+ { headers: { 'content-type': 'text/event-stream' } })
+ const finish = (reason) => ({ type: 'finish', finishReason: { unified: reason, raw: reason }, usage: { inputTokens: { total: 1 }, outputTokens: { total: 1 } } })
+ const fetcher = async (_url, init = {}) => {
+ if ((init.method ?? 'GET') === 'GET') return Response.json({ data: [{ id: 'sdk/binding-model', type: 'language' }] })
+ seen.push(drafts.turn(new Headers(init.headers).get('x-session-id')))
+ return seen.length === 1
+ ? sse({ type: 'tool-call', toolCallId: 'wait-1', toolName: 'wait_for_answer', input: '{}' }, finish('tool-calls'))
+ : sse({ type: 'text-delta', id: 'answer', delta: 'Done.' }, finish('stop'))
+ }
+ // While the turn waits in its tool, 250 other sessions start turns in this
+ // process, past the 200-session cap.
+ const crowd = async () => {
+ for (let i = 0; i < 250; i++) {
+ drafts.observe({ type: 'acp.send', message: { method: 'session/prompt', params: { sessionId: `other-${i}`, _meta: { fx: { turnId: `m${1000 + i}` } } } } })
+ }
+ return 'Answered.'
+ }
+ let agent
+ try {
+ agent = createFxAgent({ durability: local({ dir }), apiKey: 'synthetic-binding-key', model: 'sdk/binding-model', instructions: 'Reply briefly.', fetch: fetcher,
+ tools: [{ name: 'wait_for_answer', description: 'Wait for an answer.', inputSchema: { type: 'object', properties: {} }, idempotent: true, execute: crowd }],
+ onEvent: (event) => drafts.observe(event), hooks: { onEvent: (event) => drafts.observe(event) } })
+ const turn = agent.session().prompt('Ask me', { messageId: 'm31', signal: AbortSignal.timeout(5_000) })
+ try { for await (const _event of turn) {} } catch {}
+ assert.equal((await turn.result).stopReason, 'end_turn')
+ assert.deepEqual(seen, [31, 31], 'the request after the wait still names its own turn')
+ } finally {
+ await agent?.close()
+ await rm(dir, { recursive: true, force: true })
+ }
+})
+
test('installed libfx restores the original turn before its first recovered model request', { timeout: 10_000 }, async () => {
const persistence = createMemoryPersistence()
let first