refactor(agent-loop): extract setup and publication

This commit is contained in:
imccyu
2026-08-04 23:26:37 +08:00
parent 8cbdd5b9d0
commit 69b1ea8d8c

View File

@@ -14,6 +14,7 @@ import type {
AgentFactory, AgentFactory,
AgentHandle, AgentHandle,
AgentOptions, AgentOptions,
AgentSetup,
CreateAgentOptions, CreateAgentOptions,
ResumeAgentOptions, ResumeAgentOptions,
SessionStartSource, SessionStartSource,
@@ -555,23 +556,40 @@ export class AgentLoop extends Service implements AgentFactory {
...options.seed === undefined ? {} : { seed: options.seed }, ...options.seed === undefined ? {} : { seed: options.seed },
...options.meta === undefined ? {} : { meta: options.meta }, ...options.meta === undefined ? {} : { meta: options.meta },
}) })
const prepared = this.prepare(ownerCtx, options.sessionId, options.agentOptions ?? {}, session, options.signal) const published = this.setupAndPublish(
const published = (async () => { ownerCtx,
try { options.sessionId,
const setupCommit = await raceAbort( session,
options.setup?.(prepared.agent.ctx), prepared.signal, options.sessionId, options.agentOptions ?? {},
) options.setup,
setupCommit?.commit() options.signal,
return prepared.publish('startup') 'startup',
} catch (error: unknown) { )
await prepared.dispose()
throw error
}
})()
this.ownership.trackWrapper(published) this.ownership.trackWrapper(published)
return published return published
} }
/** Prepare one Agent around an acquired Session, run setup, and publish it. */
private async setupAndPublish(
ownerCtx: Context,
id: SessionId,
session: Session,
agentOptions: AgentOptions,
setup: AgentSetup | undefined,
signal: AbortSignal | undefined,
source: SessionStartSource,
): Promise<AgentHandle> {
const prepared = this.prepare(ownerCtx, id, agentOptions, session, signal)
try {
const setupCommit = await raceAbort(setup?.(prepared.agent.ctx), prepared.signal, id)
setupCommit?.commit()
return prepared.publish(source)
} catch (error: unknown) {
await prepared.dispose()
throw error
}
}
/** /**
* Resume an owned agent from the configured persistence service. * Resume an owned agent from the configured persistence service.
* @param ownerCtx - caller context that owns load, setup, and the live lifecycle. * @param ownerCtx - caller context that owns load, setup, and the live lifecycle.