import { Hono } from 'hono' import { sessionIngressAuth, acceptCliHeaders } from '../../auth/middleware' import { publishSessionEvent } from '../../services/transport' import { getEventBus } from '../../transport/event-bus' import { getSession, touchSession, updateSessionStatus, } from '../../services/session' import { handleTitleControlResponse, maybeRequestSessionTitle, } from '../../services/session-titles' import { clearPendingPermissions, registerPendingPermission, resolvePendingPermission, } from '../../services/pending-permissions' import { settlePermissionStatus } from '../../transport/ws-handler' const app = new Hono() function extractWorkerEvents(body: unknown): Array> { if (!body || typeof body !== 'object') { return [] } const payload = body as Record const rawEvents = Array.isArray(payload.events) ? payload.events : Array.isArray(body) ? body : [body] return rawEvents .filter( (evt): evt is Record => !!evt && typeof evt === 'object', ) .map(evt => { const wrappedPayload = evt.payload if ( wrappedPayload && typeof wrappedPayload === 'object' && !Array.isArray(wrappedPayload) ) { return wrappedPayload as Record } return evt }) } /** POST /v1/code/sessions/:id/worker/events — Write events */ app.post( '/:id/worker/events', acceptCliHeaders, sessionIngressAuth, async c => { const sessionId = c.req.param('id')! if (!getSession(sessionId)) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const body = await c.req.json() const events = extractWorkerEvents(body) const published = [] for (const evt of events) { const eventType = typeof evt.type === 'string' ? evt.type : 'message' // UUID dedup — mirrors the WS path (ingestBridgeMessage). HybridTransport // children can deliver the same SDK message via both POST and WS, and // replays after reconnect reuse the original UUIDs; without this check // the same assistant message gets published twice → the web UI renders // it twice. const evtUuid = typeof evt.uuid === 'string' ? evt.uuid : null if (evtUuid && getEventBus(sessionId).hasEventWithUuid(evtUuid)) { continue } const result = publishSessionEvent(sessionId, eventType, evt, 'inbound') published.push(result) // 待批权限记账 —— 只统计真正的工具审批请求;回合结束即清空。 const permissionRequest = eventType === 'control_request' ? (evt.request as Record | undefined) : undefined if (permissionRequest?.subtype === 'can_use_tool') { registerPendingPermission( sessionId, typeof evt.request_id === 'string' ? evt.request_id : '', { toolName: typeof permissionRequest.tool_name === 'string' ? permissionRequest.tool_name : undefined, toolInput: (permissionRequest.input ?? permissionRequest.tool_input) as | Record | undefined, description: typeof permissionRequest.description === 'string' ? permissionRequest.description : undefined, suggestions: Array.isArray(permissionRequest.permission_suggestions) ? permissionRequest.permission_suggestions : undefined, toolUseId: typeof permissionRequest.tool_use_id === 'string' ? permissionRequest.tool_use_id : undefined, }, ) } else if (eventType === 'control_response') { // worker 回执(本地批准/拒绝,或对 Web 决定的确认)— 按 request_id 销账。 const response = evt.response as Record | undefined if (typeof response?.request_id === 'string') { resolvePendingPermission(sessionId, response.request_id) settlePermissionStatus(sessionId) } } else if (eventType === 'control_cancel_request') { // hook/classifier 本地解决,或 V2 print worker 对 Web 决定的回执。 if (typeof evt.request_id === 'string') { resolvePendingPermission(sessionId, evt.request_id) settlePermissionStatus(sessionId) } } else if (eventType === 'result' || eventType === 'result_success') { clearPendingPermissions(sessionId) } // Derive session status from the event flow — mirrors the WS path // (ws-handler.ts ingestBridgeMessage). v2 workers push state via // PUT /worker, but the SDK result message is the authoritative // turn-end signal: without this derivation a turn that ends between // state uploads leaves the session stuck on 'running', so the web UI // input never leaves the running state and every new message lands // in the queue instead of being sent. // // Turn-signal accounting (EventBus.turnActive): the worker's write // paths are not strictly ordered — the turn-end result can reach the // server BEFORE the final assistant message. A late assistant must // not flip the session back to running after the turn ended. const bus = getEventBus(sessionId) if (eventType === 'user') { bus.turnActive = true } else if (eventType === 'result' || eventType === 'result_success') { bus.turnActive = false } const targetStatus = eventType === 'result' || eventType === 'result_success' ? 'idle' : eventType === 'control_request' ? 'requires_action' : eventType === 'assistant' && bus.turnActive ? 'running' : null if (targetStatus) { const session = getSession(sessionId) if (session && session.status !== targetStatus) { updateSessionStatus(sessionId, targetStatus) } } // Pending server-side title requests settle here (request_id match), // and a completed turn on an untitled session fires the request — // mirrors the WS path (ws-handler.ts ingestBridgeMessage). if (eventType === 'control_response') { handleTitleControlResponse(sessionId, evt.response) } else if (eventType === 'result' || eventType === 'result_success') { maybeRequestSessionTitle(sessionId) } } touchSession(sessionId) return c.json({ status: 'ok', count: published.length }, 200) }, ) /** PUT /v1/code/sessions/:id/worker/state — Report worker state */ app.put('/:id/worker/state', acceptCliHeaders, sessionIngressAuth, async c => { const sessionId = c.req.param('id')! if (!getSession(sessionId)) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } const body = await c.req.json() if (body.status) { updateSessionStatus(sessionId, body.status) } else { touchSession(sessionId) } return c.json({ status: 'ok' }, 200) }) /** PUT /v1/code/sessions/:id/worker/external_metadata — Report worker metadata (no-op) */ app.put( '/:id/worker/external_metadata', acceptCliHeaders, sessionIngressAuth, async c => { const sessionId = c.req.param('id')! if (!getSession(sessionId)) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } // TUI's CCRClient calls this for metadata reporting. Accept and discard. return c.json({ status: 'ok' }, 200) }, ) /** POST /v1/code/sessions/:id/worker/events/delivery — Batch delivery tracking (no-op) */ app.post( '/:id/worker/events/delivery', acceptCliHeaders, sessionIngressAuth, async c => { const sessionId = c.req.param('id')! if (!getSession(sessionId)) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } return c.json({ status: 'ok' }, 200) }, ) /** POST /v1/code/sessions/:id/worker/events/:eventId/delivery — Delivery tracking (no-op) */ app.post( '/:id/worker/events/:eventId/delivery', acceptCliHeaders, sessionIngressAuth, async c => { const sessionId = c.req.param('id')! if (!getSession(sessionId)) { return c.json( { error: { type: 'not_found', message: 'Session not found' } }, 404, ) } // TUI's CCRClient reports event delivery status (received/processing/processed). // Accept and discard — event bus doesn't track per-event delivery. return c.json({ status: 'ok' }, 200) }, ) export default app