| 1 | import type { AppBindings } from "./bridge"; |
| 2 | import type { StructuredInvocationSubmit } from "./invocationDisplay"; |
| 3 | import { resolveActiveTurnId } from "./inboxSubmit"; |
| 4 | |
| 5 | type InboxEnqueueBindings = Pick<AppBindings, "EnqueueInboxFollowup" | "EnqueueInboxFollowupWithInvocations" | "EnqueueInboxSteer" | "EnqueueInboxSteerForTurn" | "EnqueueForAttachmentTarget">; |
| 6 | |
| 7 | export async function enqueueInboxGuidanceForActiveTurn( |
| 8 | binding: InboxEnqueueBindings & Pick<AppBindings, "ListTabs">, |
| 9 | tabId: string, |
| 10 | display: string, |
| 11 | submit: string, |
| 12 | structured?: StructuredInvocationSubmit, |
| 13 | knownTurnId?: string, |
| 14 | ) { |
| 15 | const turnId = !structured && typeof binding.EnqueueInboxSteerForTurn === "function" |
| 16 | ? await resolveActiveTurnId(binding, tabId, knownTurnId) |
| 17 | : knownTurnId; |
| 18 | return enqueueInboxGuidance(binding, tabId, display, submit, structured, { steer: true, turnId }); |
| 19 | } |
| 20 | |
| 21 | export function enqueueInboxGuidance( |
| 22 | binding: InboxEnqueueBindings, |
| 23 | tabId: string, |
| 24 | display: string, |
| 25 | submit: string, |
| 26 | structured?: StructuredInvocationSubmit, |
| 27 | opts?: { steer?: boolean; turnId?: string; idempotency?: string }, |
| 28 | ) { |
| 29 | if (structured) { |
| 30 | if (structured.attachments?.length) { |
| 31 | if (!structured.attachmentTarget || !binding.EnqueueForAttachmentTarget) { |
| 32 | return Promise.reject(new Error("unsupported: attachments-v2")); |
| 33 | } |
| 34 | return binding.EnqueueForAttachmentTarget( |
| 35 | structured.attachmentTarget, |
| 36 | structured.attachmentSubmissionId || opts?.idempotency || `image-${crypto.randomUUID()}`, |
| 37 | structured.input.trim(), |
| 38 | structured.display.trim() || display, |
| 39 | structured.invocations, |
| 40 | structured.attachments, |
| 41 | ); |
| 42 | } |
| 43 | return binding.EnqueueInboxFollowupWithInvocations( |
| 44 | tabId, |
| 45 | structured.display.trim() || display, |
| 46 | structured.input.trim(), |
| 47 | structured.invocations, |
| 48 | opts?.idempotency ?? "", |
| 49 | ); |
| 50 | } |
| 51 | if (opts?.steer && typeof binding.EnqueueInboxSteer === "function") { |
| 52 | if (typeof binding.EnqueueInboxSteerForTurn === "function") { |
| 53 | if (!opts.turnId) return Promise.reject(new Error("active turn id is unavailable; refresh and try again")); |
| 54 | return binding.EnqueueInboxSteerForTurn(tabId, opts.turnId, display, submit || display, ""); |
| 55 | } |
| 56 | return binding.EnqueueInboxSteer(tabId, display, submit || display, ""); |
| 57 | } |
| 58 | return binding.EnqueueInboxFollowup(tabId, display, submit || display, opts?.idempotency ?? ""); |
| 59 | } |
| 60 |