import{appendUserContent,normalizeUserContent}from"#harness/messages.js";import{isApprovalRequest}from"#harness/input-requests.js";import{extractHistoricalInputRequests}from"#harness/input-extraction.js";function convertStaleResponsesToUserMessage(e){let t=e.stepInput?.inputResponses;if(e.stepInput===void 0||t===void 0||t.length===0)return{kind:`unchanged`,stepInput:e.stepInput};let n=[],i=[];for(let r of t)e.pendingRequestIds.has(r.requestId)?n.push(r):i.push(r);if(i.length===0)return{kind:`unchanged`,stepInput:e.stepInput};let a=extractHistoricalInputRequests({history:e.history,requestIds:new Set(i.map(e=>e.requestId))}),o=appendOptionalUserContent(e.stepInput.message,formatModelMessage(i,a)),s=appendOptionalUserContent(e.stepInput.message,formatDisplayMessage(i,a)),{inputResponses:c,...l}=e.stepInput,u={...l,message:o};return n.length>0&&(u.inputResponses=n),{displayMessage:s,kind:`converted`,stepInput:u}}function formatModelMessage(e,t){let r=e.map(e=>{let r=t.get(e.requestId),i=r?.options?.find(t=>t.id===e.optionId),a={};if(e.optionId!==void 0&&(a.optionId=e.optionId),i!==void 0){let e={id:i.id,label:i.label};i.description!==void 0&&(e.description=i.description),a.selectedOption=e}e.text!==void 0&&(a.text=e.text);let o={requestId:e.requestId,response:a};return r!==void 0&&(o.prompt=r.prompt,o.requestType=isApprovalRequest(r)?`approval`:`question`),o});return[`The user submitted the following response to an earlier interactive prompt.`,`Treat it as new input at the current point in the conversation and decide whether it is still relevant.${e.some(e=>{let r=t.get(e.requestId);return r===void 0||isApprovalRequest(r)})?` This does not authorize an earlier action; request approval again if that action is still needed.`:``}`,JSON.stringify(r,null,2)].join(`
`)}function formatDisplayMessage(e,t){return e.map(e=>e.text!==void 0&&e.text.length>0?e.text:t.get(e.requestId)?.options?.find(t=>t.id===e.optionId)?.label??e.optionId??`Response to an earlier interactive prompt`).join(`
`)}function appendOptionalUserContent(n,r){let i=normalizeUserContent(n);return i===void 0?r:appendUserContent({appended:r,existing:i})}export{convertStaleResponsesToUserMessage};