@redocly/replay 0.28.0-next.8 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/{replay-AiChatProvider--1WugvKf.js → replay-AiChatProvider-BRqjyy2W.js} +2 -2
  2. package/dist/{replay-AiChatProvider-BJdxRVOc.js → replay-AiChatProvider-DUVoLgY2.js} +128 -130
  3. package/dist/{replay-AiChatSqliteDBStorage-D9fgt_9s.js → replay-AiChatSqliteDBStorage-0evx56pl.js} +6 -6
  4. package/dist/{replay-AiChatSqliteDBStorage-DbGtw6xx.js → replay-AiChatSqliteDBStorage-C5AnRloD.js} +1 -1
  5. package/dist/{replay-AiPanel-BU8oG0pD.js → replay-AiPanel-CMjVD12K.js} +77 -77
  6. package/dist/{replay-AiPanel-BYOLZjQX.js → replay-AiPanel-PVgJioX3.js} +2 -2
  7. package/dist/replay-FileWatcher-CFYprlWN.js +364 -0
  8. package/dist/replay-FileWatcher-DGLwO5Kd.js +1 -0
  9. package/dist/{replay-HistorySqliteDBStorage-CtF6-vY8.js → replay-HistorySqliteDBStorage-Bi5vBQ2T.js} +2 -2
  10. package/dist/{replay-SemanticSearchService-DRDdGJkI.js → replay-SemanticSearchService-Bh5xYa91.js} +22 -26
  11. package/dist/replay-SemanticSearchService-CulKCCNl.js +1 -0
  12. package/dist/{replay-SqliteDBStorage-D9Oeu_XC.js → replay-SqliteDBStorage-Bz0muHEk.js} +49 -49
  13. package/dist/{replay-SqliteDBStorage-B3zO7RGD.js → replay-SqliteDBStorage-CVHRAsPD.js} +1 -1
  14. package/dist/{replay-StepContextSqliteDBStorage-BfAAKDwA.js → replay-StepContextSqliteDBStorage-BkB2NM27.js} +2 -2
  15. package/dist/replay-TauriFileSystemAdapter-B163-f2D.js +108 -0
  16. package/dist/replay-TauriFileSystemAdapter-D4bOmvzP.js +1 -0
  17. package/dist/{replay-TauriRootStorage-XIJpsp6_.js → replay-TauriRootStorage-2MPQE-3f.js} +159 -155
  18. package/dist/replay-TauriRootStorage-CjWUrnWz.js +1 -0
  19. package/dist/{replay-agent-loop-DxK1tiVw.js → replay-agent-loop-BgYyBo9e.js} +9 -9
  20. package/dist/{replay-agent-loop-IDavXm8f.js → replay-agent-loop-DYDFXAZj.js} +1 -1
  21. package/dist/{replay-ai-chat-mappers-B-_eSMi4.js → replay-ai-chat-mappers-BEwNRQPV.js} +3 -3
  22. package/dist/{replay-ai-chat-mappers-BmvAc4xt.js → replay-ai-chat-mappers-CMtNqQHX.js} +1 -1
  23. package/dist/{replay-ai-message-parts.schema-E9u9-nqr.js → replay-ai-message-parts.schema-DKLf0SiG.js} +1 -1
  24. package/dist/{replay-create-model-CscK0cT1.js → replay-create-model-B2ZsGTjs.js} +3 -3
  25. package/dist/{replay-create-model-CIY7WZ1P.js → replay-create-model-DPxfOEfv.js} +4 -4
  26. package/dist/{replay-db-e_3o5e3f.js → replay-db-C9iqyMet.js} +1 -1
  27. package/dist/{replay-db-C_cdHXEt.js → replay-db-D4-LmLRk.js} +5 -5
  28. package/dist/{replay-external-resolver-nuL3ajF5.js → replay-external-resolver-BXgVrfzk.js} +7 -7
  29. package/dist/{replay-external-resolver-BmOmF-DG.js → replay-external-resolver-CTUbNZGW.js} +1 -1
  30. package/dist/{replay-history.schema-5ce6X0R1.js → replay-history.schema-B0lLwmdG.js} +3 -3
  31. package/dist/{replay-index-DDt4LOBo.js → replay-index-4TEahAPK.js} +21968 -21367
  32. package/dist/{replay-index-DjdDUkfV.js → replay-index-B4U7iZuq.js} +46 -46
  33. package/dist/replay-index-B8O3wYqo.js +1 -0
  34. package/dist/{replay-index-etIeWhnn.js → replay-index-Bdg7noSD.js} +1 -1
  35. package/dist/replay-index-CG9VN2JQ.js +4 -0
  36. package/dist/{replay-index-E3Eu6_jY.js → replay-index-DcC173cC.js} +1 -1
  37. package/dist/{replay-index-B8Zfn7JD.js → replay-index-Nz5obVS5.js} +1139 -1141
  38. package/dist/{replay-index-DcbwI4wD.js → replay-index-q63USe25.js} +1 -1
  39. package/dist/{replay-indexes-CfsvVMi_.js → replay-indexes-B3PJtgeh.js} +43 -43
  40. package/dist/{replay-lint-DVAifLdU.js → replay-lint-4XFKTmSY.js} +97 -97
  41. package/dist/{replay-lint-graphql-U_VxwRr1.js → replay-lint-graphql-BsBWkZ6L.js} +1 -1
  42. package/dist/{replay-lint-graphql-D1qaeEmu.js → replay-lint-graphql-De2eDZnT.js} +1 -1
  43. package/dist/{replay-lint-BjrmIhuZ.js → replay-lint-s7ylMBWz.js} +6111 -6074
  44. package/dist/replay-periodic-revalidation-BMFP7f-u.js +1 -0
  45. package/dist/{replay-periodic-revalidation-BtEKdEKa.js → replay-periodic-revalidation-DJbblUef.js} +4 -5
  46. package/dist/{replay-resolve-C97SfUAB.js → replay-resolve-BtNxNrKo.js} +123 -123
  47. package/dist/{replay-resolve-BYJosLqD.js → replay-resolve-BueEsOnR.js} +1 -1
  48. package/dist/{replay-respect-run-CW5xFLKz.js → replay-respect-run-B_dJjlti.js} +1 -1
  49. package/dist/{replay-respect-run-3FHTVHvs.js → replay-respect-run-Dfpbcsns.js} +3 -3
  50. package/dist/replay-step-context.schema-BOprzd6Z.js +21 -0
  51. package/dist/{replay-tauri-path-CMpWmGvW.js → replay-tauri-path-Bht3XIt7.js} +1 -1
  52. package/dist/replay-tauri-path-CiuYXh_j.js +22 -0
  53. package/dist/replay-useAiChatQueries-02CRdEPJ.js +215 -0
  54. package/dist/{replay-useAiChatQueries-DhTcllVx.js → replay-useAiChatQueries-D2hh5omV.js} +1039 -996
  55. package/dist/{replay-validate-key-Dj_UT2WG.js → replay-validate-key-ALwOF1Ux.js} +1 -1
  56. package/dist/{replay-validate-key-DJ_1khxq.js → replay-validate-key-B7fbWbfv.js} +2 -2
  57. package/dist/replay.cjs +1 -1
  58. package/dist/replay.d.ts +5 -0
  59. package/dist/replay.js +15 -15
  60. package/package.json +6 -6
  61. package/dist/replay-FileWatcher-BrhE0AP6.js +0 -1
  62. package/dist/replay-FileWatcher-JoqPJECh.js +0 -360
  63. package/dist/replay-SemanticSearchService-BgQ1HMcT.js +0 -1
  64. package/dist/replay-TauriFileSystemAdapter-CxHFFCmk.js +0 -1
  65. package/dist/replay-TauriFileSystemAdapter-DJETGEY7.js +0 -99
  66. package/dist/replay-TauriRootStorage-BSQQcFgG.js +0 -1
  67. package/dist/replay-index-C_DfEx-H.js +0 -1
  68. package/dist/replay-index-Da2H-hpA.js +0 -25
  69. package/dist/replay-periodic-revalidation-C3eLm7Mw.js +0 -1
  70. package/dist/replay-step-context.schema-DBk4jufr.js +0 -21
  71. package/dist/replay-tauri-path-C-vLbl1V.js +0 -22
  72. package/dist/replay-useAiChatQueries-CEYDGx9f.js +0 -215
@@ -0,0 +1,215 @@
1
+ "use strict";const Oe=require("react"),a=require("./replay-index-Nz5obVS5.js"),m=require("./replay-db-C9iqyMet.js"),r=require("./replay-create-model-B2ZsGTjs.js"),A=require("./replay-SemanticSearchService-CulKCCNl.js"),Ee=require("@tanstack/react-query"),M={path:"pathParameters",query:"queryParameters",header:"headers",cookie:"cookies"},mt={run_request:{approveLabel:"Run",denyLabel:"Skip"},update_step:{approveLabel:"Apply",denyLabel:"Dismiss"},update_security:{approveLabel:"Apply",denyLabel:"Dismiss"}},ht={set_active_environment:{approveLabel:"Switch",denyLabel:"Cancel"},add_environment:{approveLabel:"Add",denyLabel:"Cancel"},upsert_input:{approveLabel:"Set",denyLabel:"Cancel"},upsert_server:{approveLabel:"Set",denyLabel:"Cancel"},remove_input:{approveLabel:"Remove",denyLabel:"Cancel"},remove_server:{approveLabel:"Remove",denyLabel:"Cancel"},create_collection:{approveLabel:"Create",denyLabel:"Cancel"},create_workflow:{approveLabel:"Create",denyLabel:"Cancel"},create_step:{approveLabel:"Create",denyLabel:"Cancel"},move_step:{approveLabel:"Move",denyLabel:"Cancel"},delete_collection:{approveLabel:"Delete",denyLabel:"Cancel"},delete_workflow:{approveLabel:"Delete",denyLabel:"Cancel"},delete_step:{approveLabel:"Delete",denyLabel:"Cancel"},save_tab_to_collection:{approveLabel:"Save",denyLabel:"Cancel"}},yt={CHAT:"chat",HISTORY:"history"},It="report_status",wt="run_workflow",j={WEB_SEARCH:"web_search"};function gt(e){switch(e.provider){case a.AI_PROVIDERS.GEMINI:return{[j.WEB_SEARCH]:r.google.tools.googleSearch({})};case a.AI_PROVIDERS.OPENAI:return{[j.WEB_SEARCH]:r.openai.tools.webSearch({})};case a.AI_PROVIDERS.ANTHROPIC:return{[j.WEB_SEARCH]:r.anthropic.tools.webFetch_20250910()};case a.REUNITE_AI_PROVIDER:return{[j.WEB_SEARCH]:{type:"provider",id:"reunite.web_search",name:"web_search",args:{}}};default:return{}}}const bt=["info","workflows","sourceDescriptions"];function vt(e){const t=[];return e.collectionId&&t.push(`Collection ID: ${e.collectionId}`),e.collection?.info?.title&&t.push(`Title: ${e.collection.info.title}`),e.collection?.info?.summary&&t.push(`Summary: ${e.collection.info.summary}`),e.collection?.info?.description&&t.push(`Description: ${e.collection.info.description}`),m.buildMessageFromArray(t,`
2
+ `)}function Tt(e){const t=[];if(e.collection?.workflows?.length){t.push("Workflows:");for(const o of e.collection.workflows)t.push(` workflowId=${o.workflowId} ${o.summary??""}`)}return m.buildMessageFromArray(t,`
3
+ `)}function St(e){const t=[];if(e.collection?.sourceDescriptions?.length){t.push("Source descriptions:");for(const o of e.collection.sourceDescriptions)t.push(` name=${o.name} url=${o.url}`)}return m.buildMessageFromArray(t,`
4
+ `)}function kt(e,t){const o=["Current tab (collection)"];for(const n of t)switch(n){case"info":o.push(vt(e));break;case"workflows":o.push(Tt(e));break;case"sourceDescriptions":o.push(St(e));break}return m.buildMessageFromArray(o,`
5
+
6
+ `)}function At(e,t){return m.buildMessageFromArray([e.collectionId?`Collection ID: ${e.collectionId}`:null,t.includes("title")&&e.title?`Title: ${e.title}`:null,t.includes("description")&&e.description?`Description: ${e.description}`:null],`
7
+ `)}function Ct(e,t){return m.buildMessageFromArray([t.includes("title")?e.title:null,e.apiId?`API ID: ${e.apiId}`:null,t.includes("description")&&e.description?`Description: ${e.description}`:null,t.includes("path")&&e.path?`Path: ${e.path}`:null,t.includes("method")&&e.method?`Method: ${e.method}`:null,t.includes("operationId")&&e.operationId?`Operation ID: ${e.operationId}`:null,t.includes("requestBody")&&e.requestBodySchema?`Request body schema: ${e.requestBodySchema}`:null,t.includes("parameters")&&e.parameterDetails?`Parameter details: ${m.formatSearchParameterDetails(e.parameterDetails)}`:null,t.includes("security")&&e.relatedSecuritySchemes?`Security schemes: ${m.formatSecuritySchemes(e.relatedSecuritySchemes)}`:null,t.includes("tags")&&e.tags?`Tags: ${e.tags.join("; ")}`:null,t.includes("responses")&&e.responseSchemas?`Responses: ${m.formatResponseSchema(e.responseSchemas)}`:null],`
8
+ `)}const Ot=["info","inputs","parameters","security","outputs","steps","wiring"];function Et(e){return!e.inputs||Object.keys(e.inputs).length===0?null:`Workflow inputs (JSON Schema):
9
+ ${JSON.stringify(e.inputs,null,2)}`}function _t(e){return e.outputs?.length?`Workflow outputs:
10
+ ${e.outputs.map(t=>` id=${t.id} key=${t.key} value=${t.value} active=${t.active}`).join(`
11
+ `)}`:null}function _e(e){return e.operation?` apiId=${e.operation.apiId} method=${e.operation.method} path=${e.operation.path}`:e.xOperation?` method=${e.xOperation.method} path=${e.xOperation.url}`:""}function Rt(e){return e.steps?.length?`Steps:
12
+ ${e.steps.map(t=>` stepId=${t.stepId} ${_e(t)}`).join(`
13
+ `)}`:null}function xt(e){return e.steps?.length?`Step wiring (security + outputs per step):
14
+ ${e.steps.map(o=>{const n=[` stepId=${o.stepId}${_e(o)}`],s=m.buildSecuritySection(o.security);s&&n.push(m.indentBlock(s," "));const i=m.buildStepOutputsSection(o.outputs);return i&&n.push(m.indentBlock(i," ")),n.join(`
15
+ `)}).join(`
16
+ `)}`:null}function $t(e,t){switch(t){case"inputs":return Et(e);case"parameters":return m.buildParametersSection(e.parameters);case"security":return m.buildSecuritySection(e.security);case"outputs":return _t(e);case"steps":return Rt(e);case"wiring":return xt(e);default:return null}}function Pt(e){const t=[];return e.collectionId&&t.push(`Collection ID: ${e.collectionId}`),e.workflowId&&t.push(`Workflow ID: ${e.workflowId}`),e.workflow?.summary&&t.push(`Summary: ${e.workflow.summary}`),e.workflow?.description&&t.push(`Description: ${e.workflow.description}`),m.buildMessageFromArray(t,`
17
+ `)}function qt(e,t){const o=["Current tab (workflow)"],n=e.workflow;for(const s of t){if(s==="info"){o.push(Pt(e));continue}if(!n)continue;const i=$t(n,s);i&&o.push(i)}return m.buildMessageFromArray(o,`
18
+
19
+ `)}function Nt(e,t){return m.buildMessageFromArray([e.collectionId?`Collection ID: ${e.collectionId}`:null,e.workflowId?`Workflow ID: ${e.workflowId}`:null,t.includes("title")&&e.title?`Summary: ${e.title}`:null,t.includes("description")&&e.description?`Description: ${e.description}`:null],`
20
+ `)}const Ut=["info","parameters","requestBody","security","outputs","successCriteria","response"];function Dt(e){const t=[`apiId: ${e.apiId}`,`method: ${e.method}`,`path: ${e.path}`,e.operationId?`operationId: ${e.operationId}`:null];return`Step is connected to API (${m.buildMessageFromArray(t,", ")})`}function Mt(e){const t=[`method: ${e.method}`,`url: ${e.url}`];return`Step is not connected to API (${m.buildMessageFromArray(t,", ")})`}function jt(e){return e.description?.trim()?`Description:
21
+ ${e.description}`:null}function Wt(e,t){switch(t){case"parameters":return m.buildParametersSection(e.parameters)||null;case"requestBody":return m.buildRequestBodySection(e.requestBody)||null;case"security":return m.buildSecuritySection(e.security)||null;case"outputs":return m.buildStepOutputsSection(e.outputs)||null;case"successCriteria":return m.buildSuccessCriteriaSection(e.successCriteria)||null;default:return null}}function Lt(e){const t=[];e.collectionId&&t.push(`Collection ID: ${e.collectionId}`),e.workflowId&&t.push(`Workflow ID: ${e.workflowId}`),e.stepId&&t.push(`Step ID: ${e.stepId}`),t.push(`Saved in collection: ${e.step?"yes":"no"}`);const o=e.draftStep??e.step;if(o){if(t.push(jt(o)),o.operation){const n=o.operation;t.push(Dt(n))}else if(o.xOperation){const n=o.xOperation;t.push(Mt(n))}}return e.response&&t.push(`Last response: status=${e.response.status} durationMs=${e.response.duration} size=${e.response.size}`),e.requestError&&t.push(`Request error: ${e.requestError}`),m.buildMessageFromArray(t,`
22
+ `)}function Ft(e){if(!e.response)return null;const t=e.response,o=t.headers?.length?t.headers.map(i=>` ${i[0]}: ${i[1]}`):[];let n="";t.bodyNotStored?n=" (body not stored)":t.body&&(n=`
23
+ Body:
24
+ ${t.body.length>m.RESPONSE_BODY_PREVIEW_MAX?`${t.body.slice(0,m.RESPONSE_BODY_PREVIEW_MAX)}…`:t.body}`);const s=["Last response (full)",`status: ${t.status}`,t.url?`url: ${t.url}`:null,`durationMs: ${t.duration}`,`size: ${t.size}`,o.length>0?`Headers:
25
+ ${m.buildMessageFromArray(o,`
26
+ `)}`:null,n||null];return m.buildMessageFromArray(s,`
27
+ `)}function le(e,t){const o=[];for(const n of t){const s=Wt(e,n);s&&o.push(s)}return o.length?o.filter(Boolean).join(`
28
+ `):""}function Bt(e,t){const o=["Current tab (step)"];return t.length===0?null:(t.includes("info")&&o.push(Lt(e)),e.draftStep?o.push(le(e.draftStep,t)):e.step&&o.push(le(e.step,t)),t.includes("response")&&o.push(Ft(e)),m.buildMessageFromArray(o,`
29
+
30
+ `))}function Yt(e){return e?.trim()?`Description:
31
+ ${e}`:null}function zt(e,t){if(e.apiId&&e.path&&e.method){const o=[`apiId: ${e.apiId}`,t.includes("method")?`method: ${e.method}`:null,t.includes("path")?`path: ${e.path}`:null,t.includes("operationId")&&e.operationId?`operationId: ${e.operationId}`:null];return`Step is connected to API (${m.buildMessageFromArray(o,", ")})`}if(e.path||e.method){const o=[t.includes("method")&&e.method?`method: ${e.method}`:null,t.includes("path")&&e.path?`url: ${e.path}`:null];return`Step is not connected to API (${m.buildMessageFromArray(o,", ")})`}return null}function Ht(e,t){return m.buildMessageFromArray([e.collectionId?`Collection ID: ${e.collectionId}`:null,e.workflowId?`Workflow ID: ${e.workflowId}`:null,e.stepId?`Step ID: ${e.stepId}`:null,t.includes("description")?Yt(e.description):null,zt(e,t),t.includes("requestBody")&&e.requestBodySchema?`Request body schema: ${e.requestBodySchema}`:null,t.includes("parameters")&&e.parameterDetails?`Parameter details: ${m.formatSearchParameterDetails(e.parameterDetails)}`:null,t.includes("successCriteria")&&e.successCriteria?.length?`Success criteria: ${e.successCriteria.join("; ")}`:null,t.includes("tags")&&e.tags?`Tags: ${e.tags.join("; ")}`:null,t.includes("security")&&e.relatedSecuritySchemes?`Security schemes: ${m.formatSecuritySchemes(e.relatedSecuritySchemes)}`:null,t.includes("responses")&&e.responseSchemas?`Responses: ${m.formatResponseSchema(e.responseSchemas)}`:null],`
32
+ `)}function Gt(e,t){return e.type==="collection"?At(e,t):e.type==="workflow"?Nt(e,t):e.type==="step"?Ht(e,t):Ct(e,t)}function Vt(e,t){return e.map(o=>Gt(o,t))}const Kt=["info","result","severity"],Jt=500,Xt=m.RESPONSE_BODY_PREVIEW_MAX*2;function Qt(e){const t=[];return e.collectionId&&t.push(`Collection ID: ${e.collectionId}`),e.workflowId&&t.push(`Workflow ID: ${e.workflowId}`),e.workflow?.summary&&t.push(`Summary: ${e.workflow.summary}`),e.workflow?.description&&t.push(`Description: ${e.workflow.description}`),e.runDate&&t.push(`Run date: ${new Date(e.runDate).toISOString()}`),m.buildMessageFromArray(t,`
33
+ `)}function Zt(e){return`Severity settings:
34
+ ${JSON.stringify(e.severitySettings,null,2)}`}function eo(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function de(e,t,o,n=!1){if(e==null||e==="")return"(empty)";const s=typeof e=="string"?e:n?JSON.stringify(e,null,2):JSON.stringify(e);return eo(a.maskSecretsInText(s,t),o)}function to(e,t){const o=e.request?.method||e["x-operation"]?.method,n=e.verboseLog?`${e.verboseLog.host}${e.verboseLog.path}`:e.request?.url||e["x-operation"]?.url,s=e.response?.statusCode,i=[`${e.stepId}:`];(o||n)&&i.push([o?.toUpperCase(),n?a.maskSecretsInText(n,t):null].filter(Boolean).join(" "),"->"),i.push(`status=${s??"n/a"}`,a.hasAllStepPassed(e)?"passed":"failed");const c=e.checks?a.getStepFailures(e.checks):[];if(c.length>0){const d=c.map(l=>l.message?`${l.name}: ${a.maskSecretsInText(l.message,t)}`:l.name);i.push(`(${d.join("; ")})`)}return i.join(" ")}function oo(e,t,o){const{steps:n,totalSteps:s,passedSteps:i,succeeded:c,timedOut:d}=a.getWorkflowRunVerdict(e),u=[`Run status: ${c?"SUCCEEDED":"FAILED"} (${i}/${s} steps passed, ${e.totalTimeMs}ms total${d?", global timeout reached":""})`];if(n.length>0){const p=[];let f=Xt,h=0;for(const{step:b}of n){if(p.push(` ${to(b,t)}`),f<=0){h++;continue}const g=de(b.response?.body,t,Jt);f-=g.length,p.push(` body: ${g}`)}h>0&&p.push(` (${h} step body previews omitted to save space; request them via stepIds)`),u.push(`Steps:
35
+ ${p.join(`
36
+ `)}`)}for(const p of o??[]){const f=n.find(h=>h.step.stepId===p);u.push(f?`Full response body for step ${p}:
37
+ ${de(f.step.response?.body,t,m.RESPONSE_BODY_PREVIEW_MAX,!0)}`:`Full response body for step ${p}: step not found in this run.`)}return m.buildMessageFromArray(u,`
38
+ `)}function no(e,t){const o=e.secretValues?[...e.secretValues]:void 0;if(e.runStatus==="running")return"Run status: RUNNING - the workflow is still executing; re-read this section to get the outcome, which will be reported as SUCCEEDED or FAILED once the run finishes.";if(e.runStatus==="error"){const n=`Run status: FAILED - execution error: ${a.maskSecretsInText(e.runError||"unknown error",o)}`;return e.result?`${n}
39
+ (the stored result is from an earlier run and is omitted as stale)`:n}return e.result?oo(e.result,o,t?.stepIds):"Run status: NOT STARTED - no run has executed on this tab yet."}function ro(e,t,o){const n=["Current tab (workflow run)"];for(const s of t)switch(s){case"info":n.push(Qt(e));break;case"severity":n.push(Zt(e));break;case"result":n.push(no(e,o));break}return m.buildMessageFromArray(n,`
40
+
41
+ `)}function so(e,t=["info"],o){if(!e)return null;switch(e.type){case a.TabDataType.Step:return Bt(e,t);case a.TabDataType.Workflow:return qt(e,t);case a.TabDataType.Collection:return kt(e,t);case a.TabDataType.WorkflowRun:return ro(e,t,o)}}function io(e){switch(e.type){case a.TabDataType.Collection:return bt;case a.TabDataType.Workflow:return Ot;case a.TabDataType.Step:return Ut;case a.TabDataType.WorkflowRun:return Kt}}function Re(e){return e.trim().replace(/\s+/g," ").replace(/[.!?:;,…]+$/,"").toLowerCase()}function ao(e,t){const o=[];let n=0;for(const s of e??[])if(!(s.role!=="assistant"||!Array.isArray(s.content)))for(const i of s.content)i.type==="tool-call"&&(i.toolName===t?(n+=1,o.push(i.input)):n=0);return{priorInputs:o,consecutiveCalls:n}}function co(e,t,o){const n=[];let s=!1;for(const i of e){const c=i(t,o);c&&(n.push(c.message),c.action==="block"&&(s=!0))}return{blocked:s,notes:n}}function xe(e){const t=e.warn!==void 0?"warn":"block",o=e.warn!==void 0?e.warn:e.block;return(n,s)=>{const i=ue(e.key,n);return i===null?null:s.priorInputs.some(d=>ue(e.key,d)===i)?{action:t,message:o}:null}}function ue(e,t){try{return e(t)}catch{return null}}function lo(e){const t=pe("warn",e.warnAfter,e.warnMessage),o=pe("block",e.blockAfter,e.blockMessage);if(!t&&!o)throw new Error("consecutiveCallsRule requires at least warnAfter or blockAfter");if(t&&o&&o.after<=t.after)throw new Error("consecutiveCallsRule requires blockAfter to be greater than warnAfter");return(n,s)=>{const i=s.consecutiveCalls+1;return o&&i>=o.after?{action:"block",message:o.message(i)}:t&&i>=t.after?{action:"warn",message:t.message(i)}:null}}function pe(e,t,o){if(!(t===void 0&&o===void 0)){if(t===void 0||o===void 0)throw new Error(`consecutiveCallsRule requires ${e}After and ${e}Message together`);if(!Number.isInteger(t)||t<1)throw new Error(`consecutiveCallsRule requires ${e}After to be a positive integer`);return{after:t,message:o}}}function uo(e){if(!e||typeof e.safeParse!="function")return;const t=e;return o=>{const n=t.safeParse(o);return n.success?n.data:null}}function po(e,t,o,n){return!t||t.length===0?o:async(s,i)=>{const c=ao(i?.messages,e),d={consecutiveCalls:c.consecutiveCalls,priorInputs:n?c.priorInputs.map(n).filter(p=>p!==null):c.priorInputs},l=co(t,s,d);if(l.blocked)return{isError:!1,blocked:!0,note:l.notes.join(" ")};const u=await o(s,i);return l.notes.length===0||!fo(u)?u:{...u,note:[u.note,...l.notes].filter(Boolean).join(" ")}}}function fo(e){return e!==null&&typeof e=="object"&&e.isError===!1}function mo(e,t){return{name:e.name,definition:e.definition,execute:po(e.name,e.guards,e.createExecutor(t),uo(e.definition.inputSchema))}}const ho={messages:[],isStreaming:!1,sendMessage:async()=>{},updateMessages:()=>{},stopGeneration:()=>{},addToolApprovalResponse:()=>{},chatStatus:"ready",chatError:void 0},$e=Oe.createContext(ho);function yo(){return Oe.useContext($e)}const Io=r.objectType({message:r.stringType(),details:r.unknownType().optional()}),oe=r.objectType({action:r.enumType(["add","update","remove"]).describe('Action to perform: "add", "update" or "remove".'),approved:r.booleanType().default(!0)}),$=oe.extend({id:r.stringType().optional().describe("Existing item id. Required for update/remove actions.")}),wo=oe.extend({index:r.numberType().int().min(0).optional().describe("Existing item index. Required for update/remove actions.")}),go=r.objectType({isError:r.literalType(!1),blocked:r.literalType(!0),note:r.stringType(),data:r.neverType().optional(),error:r.neverType().optional()});function C(e){return r.unionType([r.objectType({isError:r.literalType(!0),error:Io,data:r.neverType().optional(),blocked:r.neverType().optional()}),r.objectType({isError:r.literalType(!1),data:e,error:r.neverType().optional(),note:r.stringType().optional(),blocked:r.neverType().optional()}),go])}const bo=r.objectType({status:r.enumType(["applied","failed"]),summary:r.stringType().optional()}),vo=r.objectType({totalChanges:r.numberType().int().min(0),approvedChanges:r.numberType().int().min(0),applied:r.arrayType(bo),resultingState:r.stringType().optional().describe("Resulting state of the mutated fields after all changes were applied.")}),Pe=C(vo),To="Read structured state from the **active** Replay tab.\n\n**What it does**\n- Returns structured data for the active tab.\n- Read-only: does not open/switch tabs and does not mutate saved or unsaved content.\n- Returns UI-facing tab data (editable fields, configured values, responses/results), not a full OpenAPI schema dump.\n\n**Use when**\n- You need to verify UI state in the active tab after an action (edit, save, execute, rerun, tab switch).\n- You need to inspect request/response/result content as rendered in Replay UI.\n\n**Never use when**\n- You are gathering **initial schema/context** for a request from project assets (OpenAPI/Arazzo); use project-asset lookup with exact ids/coordinates.\n- You need IDs or operation/workflow coordinates from project assets; resolve them via project-asset lookup, not active-tab UI reads.\n- You need a different tab; this tool never changes focus.\n- You need to run a request or change any saved/unsaved tab content; this tool is strictly read-only.\n\n**Input guidance**\n- Treat IDs from `info` as canonical for follow-up actions.\n- Request only needed sections and combine them in one call.\n- Prefer including `info` unless you need only one slice.\n- Sections by tab type:\n - Collection tab: `info`, `workflows`, `sourceDescriptions`.\n - Workflow tab: `info`, `inputs`, `parameters`, `security`, `outputs`, `steps`, `wiring` (every step's security bindings + outputs in one call - inspect or verify multi-step wiring without opening step tabs).\n - Step tab: `info`, `parameters`, `requestBody`, `security`, `outputs`, `successCriteria`, `response`.\n - Workflow run tab: `info`, `result` (status, per-step outcomes, masked bodies; `stepIds` fetches full ones), `severity`.\n- Invalid sections are skipped; if none apply, response falls back to `info`.\n\n**Loop/budget guidance**\n- Read each needed section once per turn.\n- Re-read only after mutation/save, or when you need to inspect new output.\n- If `result` is RUNNING, re-read until the run finishes.",So=r.enumType(["info","workflows","sourceDescriptions","inputs","parameters","security","outputs","steps","wiring","requestBody","successCriteria","response","result","severity"]),ko=r.strictObjectType({sections:r.arrayType(So).min(1).describe("Content blocks to include in the response. Use tab-type-specific sections from the tool description; invalid sections for the current tab are ignored."),stepIds:r.arrayType(r.stringType()).min(1).optional().describe("Workflow run tabs only, together with the `result` section: executed step ids to return the full (secret-masked) response body for. Use after the per-step preview proves insufficient.")}),Ao=r.objectType({message:r.stringType()}),Co=C(Ao),Oo={description:To,inputSchema:ko,outputSchema:Co,needsApproval:!1};function y(e,t){return{isError:!0,error:{message:e,details:t}}}function Eo(e,t){const o=io(e),n=[],s=[];for(const i of t)o.includes(i)?n.push(i):s.push(i);return{sections:n,skipped:s}}function _o(e){return async(t,o)=>{const n=e();if(!n)return y("No active tab data available.");const{sections:s,skipped:i}=Eo(n,t.sections),c=s.length>0?s:["info"];let l=so(n,c,{stepIds:t.stepIds})??"Unable to build a summary for the active tab.";return i.length>0&&(l+=`
42
+
43
+ (Sections not applicable for this tab type were omitted: ${i.join(", ")}.)`),s.length===0&&t.sections.length>0&&(l+="\n\n(No requested sections applied to this tab type; showing `info` instead.)"),t.stepIds?.length&&(n.type!==a.TabDataType.WorkflowRun?l+=`
44
+
45
+ (stepIds applies only to workflow run tabs.)`:c.includes("result")||(l+="\n\n(stepIds requires the `result` section.)")),{isError:!1,data:{message:l}}}}const qe={name:"get_current_tab",definition:Oo,createExecutor:e=>_o(e.getActiveTabDetailedData)},Ro=`Read top-level metadata of a loaded OpenAPI document in the current Replay project.
46
+
47
+ **What it does**
48
+ - Scan: omit \`field\` to list the metadata fields present in the document, each with its shape (and item count for lists/maps).
49
+ - Read: pass one \`field\` to get that section's value. Large sections are paginated — pass the returned cursor to get the next page.
50
+
51
+ **Use when**
52
+ - You need API-level context: server/base URLs, auth model, tag grouping, titles/descriptions, external docs.
53
+ - You want to discover which metadata a document has (scan), then read a specific section.
54
+
55
+ **Never use when**
56
+ - You need operations, request/response schemas, or reusable components — use the \`search\` tool. Not available here: paths, webhooks, components, definitions, parameters, responses.
57
+
58
+ **Input guidance**
59
+ - \`apiId\` is required (the loaded API's id, the same identifier the search tool uses).
60
+ - Read one \`field\` at a time; use \`cursor\` only to continue a section you already started.`,xo=r.strictObjectType({apiId:r.stringType().describe("ID of the loaded API document to read (the API URI, the same identifier used by the search tool)."),field:r.stringType().optional().describe('Top-level metadata field to read (e.g. "info", "servers", "tags", "externalDocs", "securitySchemes"). Omit to scan: list the metadata fields present in the document. Operations and reusable components (paths, webhooks, components, definitions, parameters, responses) are not available here — use the search tool for those.'),cursor:r.stringType().optional().describe("Opaque cursor to continue a previously truncated section. Only meaningful together with `field`.")}),$o=r.objectType({name:r.stringType(),kind:r.enumType(["scalar","object","array"]),count:r.numberType().int().nonnegative().optional()}),Po=r.objectType({name:r.stringType(),hint:r.stringType()}),qo=r.objectType({available:r.arrayType($o),blocked:r.arrayType(Po)}),No=r.objectType({field:r.stringType(),value:r.unknownType(),start:r.numberType().int().nonnegative().optional(),end:r.numberType().int().nonnegative().optional(),total:r.numberType().int().nonnegative().optional(),truncated:r.booleanType(),nextCursor:r.stringType().nullable()}),Uo=r.unionType([qo,No]),Do=C(Uo),Mo={description:Ro,inputSchema:xo,outputSchema:Do,needsApproval:!1},L={paths:"Use the search tool to read endpoints and operations.",webhooks:"Use the search tool to read webhook operations.",components:"Use the search tool to read reusable components such as schemas and responses.",definitions:"Use the search tool to read reusable schemas.",parameters:"Use the search tool to read reusable parameters.",responses:"Use the search tool to read reusable responses."},Ne=["id","srcType","fileDependencies"],z=[{name:"securitySchemes",sources:["components.securitySchemes","securityDefinitions"]}],jo=10,fe=500;function Ue(e,t){for(const o of t.sources){const n=Wo(e,o);if(Lo(n))return n}return null}function Wo(e,t){return t.split(".").reduce((o,n)=>U(o)?o[n]:void 0,e)}function Lo(e){return e==null?!1:Array.isArray(e)?e.length>0:U(e)?Object.keys(e).length>0:!0}function U(e){return!(e===null||typeof e!="object"||Array.isArray(e))}const Fo=new Set(z.flatMap(e=>e.sources.map(t=>t.split(".")[0])));function me(e){const t=[],o=[];for(const[n,s]of Object.entries(e)){if(n in L){o.push({name:n,hint:L[n]});continue}Ne.includes(n)||Fo.has(n)||t.push(he(n,s))}for(const n of z){const s=Ue(e,n);s!==null&&t.push(he(n.name,s))}return{available:t,blocked:o}}function he(e,t){const o={name:e,kind:Bo(t)};return Array.isArray(t)?o.count=t.length:U(t)&&(o.count=Object.keys(t).length),o}function Bo(e){return Array.isArray(e)?"array":U(e)?"object":"scalar"}function Yo(e,t,o){if(Array.isArray(t))return ye(e,t,o,n=>n);if(U(t)){const n=Object.keys(t).sort().map(s=>[s,t[s]]);return ye(e,n,o,s=>Object.fromEntries(s))}return{field:e,value:F(t),truncated:!1,nextCursor:null}}function zo(e,t){if(!e)return 0;let o;try{o=atob(e)}catch{return null}const n=o.lastIndexOf(":");if(n===-1||o.slice(0,n)!==t)return null;const i=Number(o.slice(n+1));return!Number.isInteger(i)||i<0?null:i}function ye(e,t,o,n){const s=Math.min(Math.max(o,0),t.length),i=Math.min(s+jo,t.length),c=i<t.length;return{field:e,value:F(n(t.slice(s,i))),truncated:c,start:s,end:i,total:t.length,nextCursor:c?Ho(e,i):null}}function F(e){if(typeof e=="string")return e.length>fe?`${e.slice(0,fe)}…`:e;if(Array.isArray(e))return e.map(F);if(U(e)){const t={};for(const[o,n]of Object.entries(e))t[o]=F(n);return t}return e}function Ho(e,t){return btoa(`${e}:${t}`)}const Go=new Map(z.flatMap(e=>e.sources.map(t=>[t.split(".")[0],e.name])));function Vo(e,t,o){const n=z.find(c=>c.name===t);if(n){const c=Ue(e,n);return c===null?we(t):Ie(t,c,o)}if(t in L)return y(`"${t}" is not available from this tool. ${L[t]}`,{field:t});if(Ne.includes(t))return y(`"${t}" is not an OpenAPI metadata field.`,{field:t});const s=Go.get(t);if(s!==void 0)return y(`"${t}" is not a valid field name. Use "${s}" instead.`,{field:t});const i=e[t];return i==null?we(t):Ie(t,i,o)}function Ie(e,t,o){const n=zo(o,e);return n===null?y(`The provided cursor is not valid for field "${e}". Omit the cursor to start from the first page.`,{field:e}):{isError:!1,data:Yo(e,t,n)}}function we(e){return y(`"${e}" is not present in this API. Call this tool without a "field" to scan the available metadata fields.`,{field:e})}function Ko(e){return async t=>{const o=e.get(a.apisAtom),n=o.find(i=>i.id===t.apiId);if(!n)return y(`API "${t.apiId}" is not loaded.`,{availableApiIds:o.map(i=>i.id)});const s=n;return t.field==null&&t.cursor!==void 0?y("`cursor` requires `field` to be set — omit `cursor` and pass `field` to read a specific section, or omit both to scan. Returning scan results.",{data:me(s)}):t.field!==void 0?Vo(s,t.field,t.cursor):{isError:!1,data:me(s)}}}const De={name:"get_api_metadata",definition:Mo,createExecutor:e=>Ko(e.store)},Jo="Manage Replay collections and YAML-backed Arazzo workflows/steps.\n\n**What it does**\n- Creates or deletes collections, workflows, and steps.\n- Can copy the focused step tab into another workflow as a new step.\n- Returns a summary plus created/affected IDs when available.\n\n**Use when**\n- You need structural changes to collection/workflow/step hierarchy.\n- Create a step from an OpenAPI operation, ad-hoc request, or blank step.\n- Persist the focused step tab into a target collection/workflow.\n\n**Never use when**\n- Only editing fields on an existing step, no structural change needed.\n- Required target ids are unknown or ambiguous.\n- You are not sure destructive deletes are intended.\n\n**Input guidance**\n- Provide `payload` with one `action` from:\n - `create_collection`, `delete_collection`\n - `create_workflow`, `delete_workflow`\n - `create_step`, `delete_step`, `move_step`\n - `save_tab_to_collection`\n- Resolve missing `collectionId`, `workflowId`, and `stepId` before mutation.\n- `create_collection`: `title` is display name and derives file ID.\n- `create_step`: choose one source shape:\n - `operation` for OpenAPI link (`apiId`, `path`, `method`, optional `operationId`)\n - `xOperation` for ad-hoc HTTP (`method` + `url`)\n - omit both for a blank step\n- `create_step` optional initial fields: `description`, `parameters`, `body`, `outputs`, `successCriteria`.\n- `create_step` optional `index` inserts at that 0-based position (default: append). `move_step` moves a step to `toIndex` (0-based); indices clamp to the valid range.\n- `save_tab_to_collection`: provide `targetCollectionId`, `targetWorkflowId`, and `newStepName`.\n\n**Loop/budget guidance**\n- Prefer batching related structure setup in minimal calls per workflow.\n- Track returned `stepId` values; names may be uniquified on collisions.\n- Define outputs on producer steps; reference via `$steps.<stepId>.outputs.<name>` downstream.\n- Add `successCriteria` on created steps so workflow runs fail on unexpected responses.",Xo=r.objectType({action:r.literalType("create_collection"),title:r.stringType().min(1).describe("Collection display title (also used to derive the file id).")}).strict(),Qo=r.objectType({action:r.literalType("delete_collection"),collectionId:r.stringType().min(1).describe("Target collection id.")}).strict(),Zo=r.objectType({action:r.literalType("create_workflow"),collectionId:r.stringType().min(1).describe("Parent collection id."),name:r.stringType().min(1).describe("Workflow summary / display name.")}).strict(),en=r.objectType({action:r.literalType("delete_workflow"),collectionId:r.stringType().min(1),workflowId:r.stringType().min(1)}).strict(),tn=[a.TextContentType.Text,a.TextContentType.JSON,a.TextContentType.XML],on=r.objectType({name:r.stringType().min(1),in:r.enumType(["path","query","header","cookie"]),value:r.stringType()}).strict(),nn=r.objectType({name:r.stringType().min(1).describe("Output name."),expression:r.stringType().min(1).describe("Output expression.")}).strict(),rn=r.objectType({condition:r.stringType().min(1),context:r.stringType().optional(),type:r.enumType(["simple","regex","jsonpath","xpath"]).optional()}).strict(),sn=r.objectType({action:r.literalType("create_step"),collectionId:r.stringType().min(1),workflowId:r.stringType().min(1),stepName:r.stringType().min(1).optional().describe('Label used verbatim as the stepId, so pass a single camelCase token such as "updateUser", reusing the source operationId when there is one. Put prose in `description` instead (default: "New Step").'),description:r.stringType().min(1).optional().describe("Step description text (overrides default derived from stepName)."),parameters:r.arrayType(on).optional().describe("Initial request parameters (path, query, header, cookie)."),body:r.objectType({content:r.stringType().describe("Request body content as string."),contentType:r.enumType(tn).optional().describe("Request body content type.")}).strict().optional().describe("Initial request body."),outputs:r.arrayType(nn).optional().describe("Initial step outputs (mappings for later steps)."),successCriteria:r.arrayType(rn).optional().describe("Initial success criteria rows."),operation:r.objectType({apiId:r.stringType().min(1).describe("API id."),path:r.stringType().min(1).describe("Request path."),method:r.stringType().min(1).describe("HTTP method."),operationId:r.stringType().min(1).optional().describe("Operation id.")}).optional().describe("OpenAPI operation link (apiId, path, method). Omit if using xOperation or a blank step."),xOperation:r.objectType({method:r.stringType().min(1).describe("HTTP method."),url:r.stringType().min(1).describe("Request URL.")}).optional().describe("Ad-hoc HTTP request (method + URL). Omit if using operation or a blank step."),index:r.numberType().int().min(0).optional().describe("0-based position to insert the new step at within the workflow. Omit to append at the end. Out-of-range values clamp to the nearest valid position.")}).strict(),an=r.objectType({action:r.literalType("delete_step"),collectionId:r.stringType().min(1),workflowId:r.stringType().min(1),stepId:r.stringType().min(1)}).strict(),cn=r.objectType({action:r.literalType("move_step"),collectionId:r.stringType().min(1),workflowId:r.stringType().min(1),stepId:r.stringType().min(1).describe("Id of the existing step to move."),toIndex:r.numberType().int().min(0).describe("0-based target position for the step within the same workflow. Out-of-range values clamp to the nearest valid position.")}).strict(),ln=r.objectType({action:r.literalType("save_tab_to_collection"),targetCollectionId:r.stringType().min(1),targetWorkflowId:r.stringType().min(1),newStepName:r.stringType().min(1).describe('Step id / label for the new step, used verbatim, so pass a single camelCase token such as "updateUser".')}).strict(),dn=r.objectType({payload:r.discriminatedUnionType("action",[Xo,Qo,Zo,en,sn,an,cn,ln])}).superRefine((e,t)=>{e.payload.action==="create_step"&&e.payload.operation&&e.payload.xOperation&&t.addIssue({code:r.ZodIssueCode.custom,message:"Only one of `operation` or `xOperation` may be specified."})}),un=r.objectType({summary:r.stringType(),collectionId:r.stringType().optional(),workflowId:r.stringType().optional(),stepId:r.stringType().optional()}),pn=C(un),fn={description:Jo,inputSchema:dn,outputSchema:pn,needsApproval:e=>e.payload.action==="delete_collection"||e.payload.action==="delete_workflow"||e.payload.action==="delete_step"||e.payload.action==="save_tab_to_collection"};function ge(e,t,o){return{...a.getEmptyRequestParameter(e),key:t,value:o,active:!0}}function mn(e,t,o){const n=new Map;for(const i of o)n.set(i.name,i.value);const s=[];for(const i of e){if(a.isInlineRequestParameter(i)&&i.key&&n.has(i.key)){const c=n.get(i.key);n.delete(i.key),s.push({...ge(t,i.key,c),id:i.id,...i.allowReserved!==void 0&&{allowReserved:i.allowReserved}});continue}s.push(i)}for(const i of o)n.has(i.name)&&(s.push(ge(t,i.name,n.get(i.name))),n.delete(i.name));return s}function hn(e,t){if(t.description!==void 0&&(e.description=t.description),t.body&&(e.requestBody={...e.requestBody,content:t.body.content,...t.body.contentType!==void 0&&{type:t.body.contentType}}),t.parameters?.length){const o=new Map;for(const n of t.parameters){const s=o.get(n.in)??[];s.push(n),o.set(n.in,s)}for(const n of Object.keys(M)){const s=o.get(n);if(!s?.length)continue;const i=M[n];e.parameters[i]=mn(e.parameters[i],n,s)}}if(t.outputs?.length){const n=e.outputs.filter(s=>s.key||s.value);e.outputs=[...n,...t.outputs.map(s=>({id:crypto.randomUUID(),key:s.name,value:s.expression,active:!0}))]}if(t.successCriteria?.length)for(const o of t.successCriteria){const n=a.getEmptyCriterionObject(o.type??a.CriterionType.SIMPLE);e.successCriteria.push({...n,condition:o.condition,...o.context!==void 0&&{context:o.context}})}return e}function yn(e){return async t=>{switch(t.payload.action){case"create_collection":return In(t.payload,e);case"delete_collection":return wn(t.payload,e);case"create_workflow":return gn(t.payload,e);case"delete_workflow":return bn(t.payload,e);case"create_step":return vn(t.payload,e);case"delete_step":return Sn(t.payload,e);case"move_step":return kn(t.payload,e);case"save_tab_to_collection":return An(t.payload,e)}}}function In(e,{store:t}){const o=a.getNewCollection({name:e.title.trim(),collections:t.get(a.collectionsAtom)});return t.set(a.collectionsAtom,n=>[...n,o]),{isError:!1,data:{summary:`Created collection "${o.info.title}" (${o.id}).`,collectionId:o.id}}}function wn(e,{store:t,handleCloseByDataId:o}){const n=a.findCollection(t.get(a.collectionsAtom),e.collectionId);if(!n)return y("Collection not found.",{collectionId:e.collectionId});const s=n.info.title;return B(n,o),t.set(a.collectionsAtom,i=>a.removeCollection(i,e.collectionId)),{isError:!1,data:{summary:`Deleted collection "${s}" (${e.collectionId}).`,collectionId:e.collectionId}}}function gn(e,{store:t}){const o=a.findCollection(t.get(a.collectionsAtom),e.collectionId);if(!o)return y("Collection not found.",{collectionId:e.collectionId});const n=a.getNewWorkflow({name:e.name.trim(),collection:o});return t.set(a.collectionsAtom,s=>a.updateCollection(s,e.collectionId,i=>({...i,workflows:[...i.workflows,n]}))),{isError:!1,data:{summary:`Created workflow "${n.summary??n.workflowId}" in collection ${e.collectionId}.`,collectionId:e.collectionId,workflowId:n.workflowId}}}function bn(e,{store:t,handleCloseByDataId:o}){const n=t.get(a.collectionsAtom);if(!a.findCollection(n,e.collectionId))return y("Collection not found.",{collectionId:e.collectionId});const i=a.findWorkflow(n,{collectionId:e.collectionId,workflowId:e.workflowId});return i?(B(i,o,{collectionId:e.collectionId,workflowId:null}),t.set(a.collectionsAtom,c=>a.removeWorkflow(c,{collectionId:e.collectionId,workflowId:e.workflowId})),{isError:!1,data:{summary:`Deleted workflow ${e.workflowId} from collection ${e.collectionId}.`,collectionId:e.collectionId,workflowId:e.workflowId}}):y("Workflow not found.",{collectionId:e.collectionId,workflowId:e.workflowId})}async function vn(e,{store:t,attachApiToCollection:o,convertOperationToReplayValue:n}){const s=t.get(a.collectionsAtom);if(!a.findCollection(s,e.collectionId))return y("Collection not found.",{collectionId:e.collectionId});const c=a.findWorkflow(s,{collectionId:e.collectionId,workflowId:e.workflowId});if(!c)return y("Workflow not found.",{collectionId:e.collectionId,workflowId:e.workflowId});const d=e.operation?{apiId:e.operation.apiId,path:e.operation.path.replace(/\{\{/g,"{").replace(/\}\}/g,"}"),method:e.operation.method.toLowerCase(),operationId:e.operation.operationId,isAdditionalOperation:!1}:void 0,l=e.xOperation?{method:e.xOperation.method,url:e.xOperation.url}:void 0;let u;d&&(u=a.getApiOperationFromStore(t.get(a.apisAtom),d,n),u&&await o({collectionId:e.collectionId,apiId:d.apiId}));const p=a.getNewStep({name:e.stepName?.trim()||"New Step",workflow:c,operation:d,xOperation:l,apiOperation:u});hn(p,{description:e.description,parameters:e.parameters,body:e.body,outputs:e.outputs,successCriteria:e.successCriteria});const f=Tn(t,{collectionId:e.collectionId,workflowId:e.workflowId},p,e.index);return{isError:!1,data:{summary:`Created step ${p.stepId} at position ${f} in workflow ${e.workflowId}.`,collectionId:e.collectionId,workflowId:e.workflowId,stepId:p.stepId}}}function Me(e,t){return Math.min(Math.max(e,0),t)}function Tn(e,t,o,n){const s=a.findWorkflow(e.get(a.collectionsAtom),t)?.steps.length??0,i=n===void 0?s:Me(n,s);return e.set(a.collectionsAtom,c=>a.updateWorkflow(c,t,d=>{const l=[...d.steps];return l.splice(i,0,o),{...d,steps:l}})),i}function Sn(e,{store:t,handleCloseByDataId:o}){const n={collectionId:e.collectionId,workflowId:e.workflowId,stepId:e.stepId};return a.findStep(t.get(a.collectionsAtom),n)?(o(n),t.set(a.collectionsAtom,i=>a.removeStep(i,n)),{isError:!1,data:{summary:`Deleted step ${e.stepId} from workflow ${e.workflowId}.`,collectionId:e.collectionId,workflowId:e.workflowId,stepId:e.stepId}}):y("Step not found.",{collectionId:e.collectionId,workflowId:e.workflowId,stepId:e.stepId})}function kn(e,{store:t}){const o={collectionId:e.collectionId,workflowId:e.workflowId},n=a.findWorkflow(t.get(a.collectionsAtom),o);if(!n)return y("Workflow not found.",{collectionId:e.collectionId,workflowId:e.workflowId});const s=n.steps,i=s.findIndex(d=>d.stepId===e.stepId);if(i===-1)return y("Step not found.",{collectionId:e.collectionId,workflowId:e.workflowId,stepId:e.stepId});const c=Me(e.toIndex,s.length-1);return t.set(a.collectionsAtom,d=>a.updateWorkflow(d,o,l=>{const u=[...l.steps],[p]=u.splice(i,1);return u.splice(c,0,p),{...l,steps:u}})),{isError:!1,data:{summary:`Moved step ${e.stepId} to position ${c} in workflow ${e.workflowId}.`,collectionId:e.collectionId,workflowId:e.workflowId,stepId:e.stepId}}}async function An(e,{store:t,attachApiToCollection:o}){const n=a.getActiveTab(t);if(!n)return y("No active tab.");if(!a.isStepTab(n))return y("Active tab is not a step tab.",{tabType:n.data.type});const s=t.get(a.collectionsAtom),i=a.getStepForActiveStepTab(s,n.data);if(!i)return y("No step data available on the active tab.");if(!a.findCollection(s,e.targetCollectionId))return y("Target collection not found.",{collectionId:e.targetCollectionId});const d={collectionId:e.targetCollectionId,workflowId:e.targetWorkflowId},l=a.findWorkflow(s,d);if(!l)return y("Target workflow not found.",{collectionId:e.targetCollectionId,workflowId:e.targetWorkflowId});const u=a.getNewStep({name:e.newStepName.trim(),workflow:l,fromStep:i});return t.set(a.collectionsAtom,p=>a.updateWorkflow(p,d,f=>({...f,steps:[...f.steps,u]}))),u.operation?.apiId&&await o({collectionId:e.targetCollectionId,apiId:u.operation.apiId}),{isError:!1,data:{summary:`Added step ${u.stepId} to workflow ${e.targetWorkflowId}.`,collectionId:e.targetCollectionId,workflowId:e.targetWorkflowId,stepId:u.stepId}}}function B(e,t,o){if("workflows"in e){const n=e.id;e.workflows.forEach(s=>B(s,t,{collectionId:n,workflowId:null})),t({collectionId:n,workflowId:null,stepId:null});return}if("steps"in e){const n=e.workflowId;e.steps.forEach(s=>B(s,t,{collectionId:o?.collectionId,workflowId:n})),t({collectionId:o?.collectionId,workflowId:n,stepId:null});return}t({collectionId:o?.collectionId,workflowId:o?.workflowId,stepId:e.stepId})}const je={name:"manage_collection",definition:fn,createExecutor:e=>yn(e)},Cn=`Read, add, or change Replay environments (inputs and server mappings).
61
+
62
+ **What it does**
63
+ - Manages Replay project environments: inputs (values and secrecy) and per-\`apiId\` server URLs/variables.
64
+ - Supports reads (list/get) and mutations (add env, upsert/remove inputs and servers, set active).
65
+ - Uses Replay project state, not runtime OS/shell environment variables.
66
+
67
+ **Use when**
68
+ - You need current environment, input, or server values before configuring or running requests.
69
+ - You need reusable inputs or to point servers at different base URLs per environment.
70
+ - You need to create an environment or switch the active one for \`$inputs.*\` and server resolution.
71
+
72
+ **Never use when**
73
+ - You rely on stale chat context instead of a fresh read before accuracy-critical steps.
74
+ - You need to flip \`isSecret\` on an existing input via \`upsert_input\` (secrecy is preserved on update).
75
+
76
+ **Input guidance**
77
+ - Shape and per-action fields are defined by the tool schema: pass \`payload\` with a single \`action\`.
78
+ - Omit \`environment\` on supported actions to use the active environment (schema marks exceptions).
79
+ - Reference inputs in requests as \`$inputs.<name>\` or \`{$inputs.<name>}\`; names must exist in the target environment.
80
+
81
+ **Loop/budget guidance**
82
+ - Re-read environment/input data when decisions depend on up-to-date values.
83
+ - Batch related input/server changes for the same environment when practical.
84
+ - After changing the active environment, re-check assumptions that depended on the previous one.`,P=r.stringType().min(1).optional().describe("Environment name. Omit to use the active environment."),On=r.objectType({action:r.literalType("get_environments")}).strict(),En=r.objectType({action:r.literalType("get_active_environment")}).strict(),_n=r.objectType({action:r.literalType("get_inputs"),environment:P}).strict(),Rn=r.objectType({action:r.literalType("get_servers"),environment:P}).strict(),xn=r.objectType({action:r.literalType("get_input"),environment:P,inputName:r.stringType().min(1)}).strict(),$n=r.objectType({action:r.literalType("upsert_input"),environment:P,name:r.stringType().min(1),value:r.stringType(),isSecret:r.booleanType().optional().describe("Only when creating a new input name: whether the value is secret (default false). Ignored when the name already exists.")}).strict(),Pn=r.objectType({action:r.literalType("remove_input"),environment:P,inputName:r.stringType().min(1)}).strict(),ne=r.objectType({name:r.stringType().min(1),value:r.stringType()}).strict(),qn=r.objectType({action:r.literalType("upsert_server"),environment:P,apiId:r.stringType().min(1),value:r.stringType(),variables:r.arrayType(ne).optional()}).strict(),Nn=r.objectType({name:r.stringType().min(1),value:r.stringType(),isSecret:r.booleanType().optional().describe("Defaults to false when omitted.")}).strict(),Un=r.objectType({apiId:r.stringType().min(1),value:r.stringType(),variables:r.arrayType(ne).optional()}).strict(),Dn=r.objectType({action:r.literalType("add_environment"),environment:r.stringType().min(1).describe("Name of a new environment to create."),inputs:r.arrayType(Nn).optional().describe("Optional initial inputs for the new environment."),servers:r.arrayType(Un).optional().describe("Optional initial server mappings for the new environment."),setActive:r.booleanType().optional().describe("When true, also set the new environment as active.")}).strict(),Mn=r.objectType({action:r.literalType("remove_server"),environment:P,apiId:r.stringType().min(1)}).strict(),jn=r.objectType({action:r.literalType("set_active_environment"),environment:r.stringType().min(1).describe("Name of the environment to activate.")}).strict(),Wn=r.objectType({payload:r.discriminatedUnionType("action",[On,Dn,En,_n,Rn,xn,$n,Pn,qn,Mn,jn])}),Ln=r.objectType({summary:r.stringType(),environmentNames:r.arrayType(r.stringType()).optional(),inputs:r.arrayType(r.objectType({name:r.stringType(),isSecret:r.booleanType(),value:r.stringType()})).optional(),servers:r.arrayType(r.objectType({apiId:r.stringType(),value:r.stringType(),variables:r.arrayType(ne)})).optional(),input:r.objectType({name:r.stringType(),isSecret:r.booleanType(),value:r.stringType()}).optional(),environment:r.stringType().optional(),apiId:r.stringType().optional()}),Fn=C(Ln),Bn={description:Cn,inputSchema:Wn,outputSchema:Fn,needsApproval:e=>e.payload.action==="add_environment"||e.payload.action==="set_active_environment"||e.payload.action==="upsert_input"||e.payload.action==="remove_input"||e.payload.action==="upsert_server"||e.payload.action==="remove_server"};function Yn(e){return async(t,o)=>{switch(t.payload.action){case"get_environments":return zn(e);case"add_environment":return Hn(e,t.payload);case"get_active_environment":return Gn(e);case"set_active_environment":return tr(e,t.payload);case"get_inputs":return Vn(e,t.payload);case"get_servers":return Kn(e,t.payload);case"get_input":return Jn(e,t.payload);case"upsert_input":return Xn(e,t.payload);case"remove_input":return Qn(e,t.payload);case"upsert_server":return Zn(e,t.payload);case"remove_server":return er(e,t.payload)}}}function zn(e){const t=e.get(a.activeEnvironmentIdAtom),o=e.get(a.environmentsAtom).map(n=>n.name);return{isError:!1,data:{summary:`${o.length} environment(s). Active: "${t}".`,environmentNames:o}}}function Hn(e,t){if(H(e,t.environment))return y("Environment already exists.",{environment:t.environment});const n=a.validateEnvironmentName(t.environment,new Set);if(n)return y(n,{environment:t.environment});const s=(t.inputs??[]).map(d=>({name:d.name,value:d.value,isSecret:d.isSecret??!1})),i=(t.servers??[]).map(d=>({apiId:d.apiId,value:d.value,variables:d.variables??[]})),c=sr(s,i);return c?y(c,{environment:t.environment}):(e.set(a.environmentsAtom,d=>[...d,{name:t.environment,inputs:s,servers:i,state:a.ItemState.Normal}]),t.setActive&&e.set(a.activeEnvironmentIdAtom,t.environment),{isError:!1,data:{summary:t.setActive?`Added environment "${t.environment}" and set it active.`:`Added environment "${t.environment}".`,environment:t.environment}})}function Gn(e){const t=e.get(a.activeEnvironmentIdAtom);return H(e,t)?{isError:!1,data:{summary:`Active environment is "${t}".`,environment:t}}:y("Active environment not found.",{environment:t})}function Vn(e,t){const o=q(e,t.environment);if(!o.ok)return o.result;const{name:n,env:s}=o,i=nr(s);return{isError:!1,data:{summary:`${i.length} input(s) in "${n}".`,environment:n,inputs:i}}}function Kn(e,t){const o=q(e,t.environment);if(!o.ok)return o.result;const{name:n,env:s}=o,i=rr(s);return{isError:!1,data:{summary:`${i.length} server(s) in "${n}".`,environment:n,servers:i}}}function Jn(e,t){const o=q(e,t.environment);if(!o.ok)return o.result;const{name:n,env:s}=o,i=s.inputs.find(u=>u.name===t.inputName);if(!i)return y("Input not found.",{environment:n,inputName:t.inputName});const{name:c,isSecret:d,value:l}=i;return{isError:!1,data:{summary:`Input "${c}" (${d?"secret":"plain"}) in "${n}".`,environment:n,input:{name:c,isSecret:d,value:We(d,l)}}}}function Xn(e,t){const o=q(e,t.environment);if(!o.ok)return o.result;const{name:n,env:s}=o,i=re(t.name,"Input names");if(i)return y(i,{environment:n,inputName:t.name});const c=s.inputs.find(l=>l.name===t.name),d=c?c.isSecret:t.isSecret??!1;return G(e,n,l=>({...l,inputs:[...l.inputs.filter(u=>u.name!==t.name),{name:t.name,value:t.value,isSecret:d}]})),{isError:!1,data:{summary:`Upserted input "${t.name}" in "${n}" (${d?"secret":"plain"}).`,environment:n}}}function Qn(e,t){const o=q(e,t.environment);if(!o.ok)return o.result;const{name:n,env:s}=o;return s.inputs.some(i=>i.name===t.inputName)?(G(e,n,i=>({...i,inputs:i.inputs.filter(c=>c.name!==t.inputName)})),{isError:!1,data:{summary:`Removed input "${t.inputName}" from "${n}".`,environment:n}}):y("Input not found.",{environment:n,inputName:t.inputName})}function Zn(e,t){const o=q(e,t.environment);if(!o.ok)return o.result;const{name:n}=o,s=re(t.apiId,"Server apiIds")??W((t.variables??[]).map(i=>i.name),"Variable names");return s?y(s,{environment:n,apiId:t.apiId}):(G(e,n,i=>{const c=i.servers,d=c.findIndex(p=>p.apiId===t.apiId),l=d>=0&&t.variables===void 0?c[d].variables:t.variables??[],u={apiId:t.apiId,value:t.value,variables:l};return{...i,servers:d>=0?c.toSpliced(d,1,u):[u,...c]}}),{isError:!1,data:{summary:`Upserted server "${t.apiId}" in "${n}".`,environment:n,apiId:t.apiId}})}function er(e,t){const o=q(e,t.environment);if(!o.ok)return o.result;const{name:n,env:s}=o;return s.servers.some(i=>i.apiId===t.apiId)?(G(e,n,i=>({...i,servers:i.servers.filter(c=>c.apiId!==t.apiId)})),{isError:!1,data:{summary:`Removed server "${t.apiId}" from "${n}".`,environment:n,apiId:t.apiId}}):y("Server not found.",{environment:n,apiId:t.apiId})}function tr(e,t){return H(e,t.environment)?(e.set(a.activeEnvironmentIdAtom,t.environment),{isError:!1,data:{summary:`Active environment is now "${t.environment}".`}}):y("Environment not found.",{environment:t.environment})}function or(e,t){return t??e.get(a.activeEnvironmentIdAtom)}function q(e,t){const o=or(e,t),n=H(e,o);return n?{ok:!0,name:o,env:n}:{ok:!1,result:y(t!==void 0?"Environment not found.":"Active environment not found.",{environment:o})}}function H(e,t){return e.get(a.environmentsAtom).find(o=>o.name===t)}function G(e,t,o){e.set(a.environmentsAtom,n=>n.map(s=>s.name===t?o(s):s))}function nr(e){return e.inputs.map(t=>({name:t.name,isSecret:t.isSecret,value:We(t.isSecret,t.value)}))}function rr(e){return e.servers.map(t=>({apiId:t.apiId,value:t.value,variables:t.variables.map(o=>({name:o.name,value:o.value}))}))}function We(e,t){return e?a.SECRET_MASK:t}function sr(e,t){return W(e.map(o=>o.name),"Input names")??W(t.map(o=>o.apiId),"Server apiIds")??Le(t,o=>W(o.variables.map(n=>n.name),"Variable names",` in server "${o.apiId}"`))}function W(e,t,o=""){const n=ir(e);return n?`${t}${o} must be unique; "${n}" appears more than once.`:Le(e,s=>re(s,t))}function re(e,t){return e.trim()?a.isReservedEnvironmentFileKey(e)?`${t} cannot use the reserved key "${e}".`:null:`${t} cannot be blank.`}function Le(e,t){for(const o of e){const n=t(o);if(n)return n}return null}function ir(e){const t=new Set;for(const o of e){if(t.has(o))return o;t.add(o)}return null}const Fe={name:"manage_environment",definition:Bn,createExecutor:e=>Yn(e.store)},ar=a.REQUEST_METHODS,cr="Open or focus a tab in Replay.\n\n**What it does**\n- Opens or focuses tabs only (navigation/state change).\n- Does not execute requests and does not create/update/delete saved assets.\n\n**Use when**\n- You need to open a request, operation, collection, workflow, or step tab.\n- You need to bring an already open tab into focus.\n\n**Never use when**\n- You need to execute an HTTP request.\n- You need to run a workflow — use `run_workflow`; it runs headlessly and returns the run's `historyId`.\n- You need to create or edit saved workflow content.\n- You are re-opening the same target only to re-verify unchanged state.\n\n**Input guidance**\n- Use ids exactly as stored in Replay (same spelling and casing).\n- Choose action by intent:\n - `open_new_request`: one-off HTTP call; blank tab when `requestUrl` is omitted, prefilled ad-hoc request when provided (`requestMethod` defaults to GET).\n - `open_operation`: open a spec operation by `operationId` in an unsaved request tab.\n - `open_collection` / `open_workflow` / `open_step`: open saved entities by their required ids.\n - `focus_tab`: focus an already open tab by zero-based `tabIndex`.\n\n**Loop/budget guidance**\n- Open or focus each target once per task unless state changed.\n- Prefer `focus_tab` for already open tabs instead of repeatedly opening the same target.",lr=r.enumType(["focus_tab","open_operation","open_collection","open_workflow","open_step","open_new_request"]),dr=r.strictObjectType({action:lr.describe("Tab to open or focus; see tool description for unsaved vs collection actions."),tabIndex:r.numberType().optional().describe("focus_tab only: zero-based index of an already open tab."),collectionId:r.stringType().optional().describe("open_collection, open_workflow, or open_step."),workflowId:r.stringType().optional().describe("open_workflow or open_step."),stepId:r.stringType().optional().describe("open_step only."),operationId:r.stringType().optional().describe("open_operation only: OpenAPI operationId from the loaded spec; opens an unsaved request tab for that operation."),requestUrl:r.stringType().optional().describe("open_new_request only: absolute or host URL for an unsaved ad-hoc request (e.g. https://example.com/api). Omit for a blank tab."),requestMethod:r.enumType(ar).optional().describe("open_new_request with requestUrl: HTTP method; defaults to GET if omitted.")}).superRefine((e,t)=>{const n=(e.requestUrl?.trim()??"").length>0,s=e.requestMethod!==void 0;(n||s)&&e.action!=="open_new_request"&&t.addIssue({code:r.ZodIssueCode.custom,message:"requestUrl and requestMethod are only valid with action open_new_request.",path:["requestUrl"]}),s&&!n&&t.addIssue({code:r.ZodIssueCode.custom,message:"requestMethod requires a non-empty requestUrl.",path:["requestMethod"]})}),ur=r.objectType({outcome:r.enumType(["focused","opened"]),activeTabIndex:r.numberType().int().nonnegative(),tabId:r.stringType(),tabType:r.nativeEnumType(a.TabDataType)}),pr=C(ur),fr={description:cr,inputSchema:dr,outputSchema:pr,needsApproval:!1};function V({items:e,id:t,messages:o,getItemId:n,formatAmbiguousMatch:s,buildNotFoundDetails:i}){const c=t.trim();if(!c)return{ok:!1,message:o.empty};const d=e.filter(l=>n(l)===c);return d.length===1?{ok:!0,value:d[0]}:d.length>1?{ok:!1,message:o.ambiguous,details:{matches:d.map(s)}}:{ok:!1,message:o.notFound,details:i(c)}}function Be(e,t){const o=V({items:e,id:t,messages:{empty:"Collection id is empty.",ambiguous:"Multiple collections share that id; ids must be unique.",notFound:"No collection found with that id."},getItemId:s=>s.id,formatAmbiguousMatch:s=>({id:s.id,title:s.info.title}),buildNotFoundDetails:s=>({collectionId:s})});if(!o.ok)return o;const n=o.value;return{ok:!0,value:{collectionId:n.id,collection:n}}}function se(e,t,o){const n=Be(e,t);if(!n.ok)return n;const s=V({items:n.value.collection.workflows,id:o,messages:{empty:"Workflow id is empty.",ambiguous:"Multiple workflows share that id in this collection; ids must be unique.",notFound:"No workflow found with that id in the given collection."},getItemId:c=>c.workflowId,formatAmbiguousMatch:c=>({workflowId:c.workflowId,summary:c.summary}),buildNotFoundDetails:c=>({collectionId:n.value.collectionId,workflowId:c})});if(!s.ok)return s;const i=s.value;return{ok:!0,value:{collectionId:n.value.collectionId,workflowId:i.workflowId,workflow:i}}}function Ye(e,t,o,n){const s=se(e,t,o);if(!s.ok)return s;const i=V({items:s.value.workflow.steps,id:n,messages:{empty:"Step id is empty.",ambiguous:"Multiple steps share that id in this workflow; ids must be unique.",notFound:"No step found with that id in the given workflow."},getItemId:d=>d.stepId,formatAmbiguousMatch:d=>({stepId:d.stepId,description:d.description}),buildNotFoundDetails:d=>({collectionId:s.value.collectionId,workflowId:s.value.workflowId,stepId:d})});if(!i.ok)return i;const c=i.value;return{ok:!0,value:{collectionId:s.value.collectionId,workflowId:s.value.workflowId,stepId:c.stepId,step:c}}}function ze(e,t){const o=a.getOperationsList(e).filter(s=>s.operationId!=null&&s.operationId!=="");if(!o.length)return{ok:!1,message:"No operations with operationId in loaded APIs."};const n=V({items:o,id:t,messages:{empty:"operationId is empty.",ambiguous:"Multiple operations share that operationId; disambiguation is not supported with id-only matching.",notFound:"No operation found with that operationId in loaded APIs."},getItemId:s=>s.operationId,formatAmbiguousMatch:s=>({apiId:s.apiId,path:s.path,method:s.method}),buildNotFoundDetails:s=>({operationId:s})});return n.ok?{ok:!0,value:n.value}:n}function He(e,t,o,n,s){o=o.trim(),n=n.trim(),s=s.trim();const i=!o&&!n&&!s,c=!!(o&&n&&s);if(!i&&!c)return{ok:!1,message:"Provide all three ids for a saved step, or three empty strings for the focused unsaved request tab."};if(c){const f=Ye(e,o,n,s);return f.ok?{ok:!0,value:{step:f.value.step,source:{kind:"saved",collectionId:o,workflowId:n,stepId:s}}}:f}if(!t||!a.isStepTab(t))return{ok:!1,message:"Active tab is not a step tab.",details:{tabType:t?.data?.type}};const{collectionId:d,workflowId:l,stepId:u}=t.data;if(!a.tabStepUidsMatch(d,l,u,"","",""))return{ok:!1,message:"Active tab does not match unsaved draft target. Open the unsaved request tab first, or pass collection/workflow/step ids for a saved step.",details:{activeTab:{collectionId:d,workflowId:l,stepId:u}}};const p=t.data.draftStep;return p?{ok:!0,value:{step:p,source:{kind:"draft"}}}:{ok:!1,message:"No draft step on the active tab."}}function Ge(e,t,o,n){const s=He(e.get(a.collectionsAtom),a.getActiveTab(e)??null,t,o,n);if(!s.ok)return s;const{step:i,source:c}=s.value;if(c.kind==="saved"){const l=c;return{ok:!0,value:{step:i,readStep:()=>a.findStep(e.get(a.collectionsAtom),l)??i,updateStep:u=>e.set(a.collectionsAtom,p=>a.updateStep(p,l,u))}}}const d=a.getActiveTabIndex(e);return{ok:!0,value:{step:i,readStep:()=>mr(e,d)??i,updateStep:l=>a.updateTabDataAt(e,d,u=>({...u,draftStep:u.draftStep?l(u.draftStep):u.draftStep}))}}}function mr(e,t){const o=e.get(a.tabsAtom)[t];return o&&a.isStepTab(o)?o.data.draftStep:null}function Ve(e){return{apiId:e.apiId,path:e.path,method:e.method,operationId:e.operationId||void 0,isAdditionalOperation:e.isAdditionalOperation}}function Ke(e,t){if(t.focusOperationTab(e))return"focused";const o=t.getApiOperation(e),n=a.createTabFromOperation(e,o);return t.addNewTab({...n,state:a.TabState.Normal}),"opened"}function hr(e,t){return(o,n)=>{try{switch(o.action){case"focus_tab":return yr(e,t,o.tabIndex);case"open_operation":return Ir(e,t,o.operationId);case"open_collection":return wr(e,e.get(a.collectionsAtom),t,o.collectionId);case"open_workflow":return gr(e,e.get(a.collectionsAtom),t,o.collectionId,o.workflowId);case"open_step":return br(e,e.get(a.collectionsAtom),t,o.collectionId,o.workflowId,o.stepId);case"open_new_request":return vr(e,t,o.requestUrl,o.requestMethod);default:{const s=o.action;return S("Unsupported open_tab action.",{action:s})}}}catch(s){return S("Failed to open or focus tab.",{cause:s instanceof Error?s.message:String(s)})}}}function yr(e,t,o){if(o===void 0)return S("tabIndex is required when action is focus_tab");const n=e.get(a.tabsAtom);return o<0||o>=n.length?S("Invalid tab index.",{tabIndex:o,tabCount:n.length}):(t.handleTabChange(o),D(e,"focused"))}function Ir(e,t,o){const n=o?.trim();if(!n)return S("operationId is required when action is open_operation");const s=ze(e.get(a.apisAtom),n);if(!s.ok)return S(s.message,s.details);const i=Ke(Ve(s.value),t);return D(e,i)}function wr(e,t,o,n){const s=n?.trim();if(!s)return S("collectionId is required when action is open_collection");const i=Be(t,s);if(!i.ok)return S(i.message,i.details);const{collectionId:c}=i.value,d=e.get(a.tabsAtom).findIndex(l=>{const u=l.data;return a.isTabType(u,a.TabDataType.Collection)&&u.collectionId===c})!==-1;return o.openCollectionTab({collectionId:c,activeTabName:a.TAB_NAMES.COLLECTION_SETTINGS}),D(e,d?"focused":"opened")}function gr(e,t,o,n,s){const i=n?.trim(),c=s?.trim();if(!i)return S("collectionId is required when action is open_workflow");if(!c)return S("workflowId is required when action is open_workflow");const d=se(t,i,c);if(!d.ok)return S(d.message,d.details);const{collectionId:l,workflowId:u}=d.value,p=e.get(a.tabsAtom).findIndex(f=>{const h=f.data;return a.isTabType(h,a.TabDataType.Workflow)&&h.workflowId===u&&h.collectionId===l})!==-1;return o.openWorkflowTab({collectionId:l,workflowId:u,activeTabName:a.TAB_NAMES.WORKFLOW_SETTINGS}),D(e,p?"focused":"opened")}function br(e,t,o,n,s,i){const c=n?.trim(),d=s?.trim(),l=i?.trim();if(!c)return S("collectionId is required when action is open_step");if(!d)return S("workflowId is required when action is open_step");if(!l)return S("stepId is required when action is open_step");const u=Ye(t,c,d,l);if(!u.ok)return S(u.message,u.details);const{collectionId:p,workflowId:f,stepId:h}=u.value,b=e.get(a.tabsAtom).find(({data:g})=>a.isTabType(g,a.TabDataType.Step)&&g.collectionId===p&&g.workflowId===f&&g.stepId===h&&g.historyId===null)!==void 0;return o.openStepTabFromCollection({collectionId:p,workflowId:f,stepId:h,state:a.TabState.Normal}),D(e,b?"focused":"opened")}function vr(e,t,o,n){return o?t.openStepTabFromXOperation({method:n??"GET",url:o}):t.handleNewTabOpen(),D(e,"opened")}function D(e,t){const o=a.getActiveTabIndex(e),n=a.getActiveTab(e);return n?Tr(t,o,n.id,n.data.type):S("No active tab after navigation.",{activeTabIndex:o})}function S(e,t){return{isError:!0,error:{message:e,...t!==void 0?{details:t}:{}}}}function Tr(e,t,o,n){return{isError:!1,data:{outcome:e,activeTabIndex:t,tabId:o,tabType:n}}}const Je={name:"open_tab",definition:fr,createExecutor:e=>hr(e.store,e.context)},Sr=`Report a short milestone status for the current task. UI-only: shows a one-line status above the next action; performs no workflow action and returns only acknowledgment.
85
+
86
+ Use when: starting a multi-step task after deciding the plan; crossing a major phase boundary (planning -> creating -> wiring -> verifying); starting a new debug attempt; or pivoting to a different approach.
87
+
88
+ Report at most one status per phase and only a few per task. Do not narrate routine tool calls, repeat the previous status, or use it in place of the final assistant response. Make the message concrete and user-facing: plain text, no markdown; name the relevant Arazzo object; describe milestone intent, not internal reasoning or tool names.
89
+
90
+ Duplicates of earlier statuses and statuses reported back-to-back with no action in between add no value; when detected, the acknowledgment includes a corrective note - act on it instead of reporting another status. Too many statuses in a row are blocked instead of acknowledged.`,kr=r.strictObjectType({message:r.stringType().trim().min(1).max(220).regex(/^[^\r\n]+$/,"must be a single line").describe("Short status line for a milestone (plan start, phase boundary, new debug attempt, pivot). Plain text, no markdown. Do not narrate every tool call.")}),Ar=r.objectType({acknowledged:r.literalType(!0)}),Cr=C(Ar),Or={description:Sr,inputSchema:kr,outputSchema:Cr,needsApproval:!1};function Er(){return async()=>({isError:!1,data:{acknowledged:!0}})}const _r="Duplicate of a previous status - it adds nothing for the user. Do not repeat statuses; take a concrete action instead.";function Rr(e){return`You have reported ${e} statuses in a row with no action between them. Stop reporting status; take a concrete action (edit, run, or read) now.`}function xr(e){return`STOP: ${e} status messages in a row with no action taken. Reporting status is not progress. Do NOT call report_status again until you have made a change or run a request. Take the next concrete action now, or if you are blocked, say so in your final answer.`}const $r=[xe({key:e=>Re(e.message),warn:_r}),lo({warnAfter:2,warnMessage:Rr,blockAfter:4,blockMessage:xr})],Xe={name:"report_status",definition:Or,guards:$r,createExecutor:e=>Er()},Pr=`Send the HTTP request for the **currently focused** Replay step tab and return the live response.
91
+
92
+ **What it does**
93
+ - Executes the request from the active step context (saved step or focused draft step).
94
+ - Returns response metadata: status, headers, cookies, body (truncated if large), url, duration, and size.
95
+ - Requires user approval before execution.
96
+
97
+ **Use when**
98
+ - You need to execute a saved workflow step currently open in Replay.
99
+ - You need to execute a focused unsaved draft request tab and inspect its live response.
100
+ - You need fresh runtime output before deciding edits, retries, or follow-up actions.
101
+
102
+ **Never use when**
103
+ - The wrong tab is focused; switch focus first so active tab and ids refer to the same target.
104
+ - You are only reading existing tab state without executing anything; use a read-only tab inspection tool.
105
+ - You have only partial identifiers for a saved step; provide all required ids together.
106
+ - You need project-asset lookup (schema/context/coordinates) rather than request execution.
107
+ - The request depends on cross-step \`$steps.*\` outputs; those resolve in workflow-run context, not single-step execution.
108
+
109
+ **Input guidance**
110
+ - Saved collection step: pass non-empty \`collectionId\`, \`workflowId\`, and \`stepId\`.
111
+ - Focused unsaved draft tab: pass three empty strings for \`collectionId\`, \`workflowId\`, and \`stepId\`.
112
+ - Mixed/partial ids are invalid; ids must be either all present or all empty.
113
+ - If needed, use tab switching first so ids and focus match the intended execution target.
114
+
115
+ **Loop/budget guidance**
116
+ - Execute when you need new runtime evidence, not by default after every edit.
117
+ - Re-run after meaningful request/config changes or when validating a fix/hypothesis.
118
+ - Avoid rapid duplicate runs with unchanged inputs when prior output already answers the question.
119
+ - For endpoint exploration, treat one run per endpoint as default budget unless inputs changed or rerun is explicitly needed.`,qr=r.objectType({collectionId:r.stringType().describe("Saved step: collection id. Unsaved draft tab on focus: empty string (with empty workflowId and stepId)."),workflowId:r.stringType().describe("Saved step: workflow id. Unsaved draft tab: empty string (with empty collectionId and stepId)."),stepId:r.stringType().describe("Saved step: step id. Unsaved draft tab: empty string (with empty collectionId and workflowId).")}).strict().superRefine((e,t)=>{const o=e.collectionId.trim(),n=e.workflowId.trim(),s=e.stepId.trim();!(o&&n&&s)&&!(!o&&!n&&!s)&&t.addIssue({code:r.ZodIssueCode.custom,message:"Provide all three ids for a saved step, or three empty strings for the focused unsaved request tab.",path:["collectionId"]})}),Nr=r.objectType({status:r.numberType().optional().describe("HTTP status code."),headers:r.arrayType(r.tupleType([r.stringType(),r.stringType()])).optional().describe("Response headers as key-value pairs."),cookies:r.arrayType(r.tupleType([r.stringType(),r.stringType()])).optional().describe("Response cookies as key-value pairs."),body:r.stringType().optional().describe("Response body, truncated if too large."),url:r.stringType().optional().describe("Final response URL."),duration:r.numberType().optional().describe("Request duration in milliseconds."),size:r.numberType().optional().describe("Response size in bytes.")}),Ur=C(Nr),Dr={description:Pr,inputSchema:qr,outputSchema:Ur,needsApproval:()=>!0};function Mr(e,t){return async(n,s)=>{const i=a.getActiveTabIndex(t),c=a.getActiveTab(t);if(!c||!a.isStepTab(c))return y("Active tab is not a step tab",{tabType:c?.data?.type});const{collectionId:d,workflowId:l,stepId:u}=c.data,p=n.collectionId.trim(),f=n.workflowId.trim(),h=n.stepId.trim();if(!a.tabStepUidsMatch(d,l,u,p,f,h))return y("Active tab does not match the target step. Open the target tab first using open_tab.",{activeTab:{collectionId:d,workflowId:l,stepId:u},hint:d===null&&l===null&&u===null?"Focused tab is an unsaved request; pass empty strings for collectionId, workflowId, and stepId.":void 0});const g=t.get(a.collectionsAtom),I={collectionId:p||null,workflowId:f||null,stepId:h||null},T=a.findStep(g,I),v=c.data.draftStep;let O;if(T)O={step:T,onStepChange:(x=>t.set(a.collectionsAtom,_=>a.updateStep(_,I,x)))};else if(v)O={step:v,onStepChange:(x=>a.updateTabDataAt(t,i,_=>({..._,draftStep:_.draftStep?x(_.draftStep):_.draftStep})))};else return y("No step available for the active tab.");const X=a.findWorkflow(g,I);await a.makeRequest({tabId:c.id,updateData:x=>a.updateTabDataAt(t,i,x)},{...O,workflow:X,onWorkflowChange:x=>t.set(a.collectionsAtom,_=>a.updateWorkflow(_,I,x)),collection:a.findCollection(g,I.collectionId),collections:g},e,a.getSelectedEnvironment(t.get(a.environmentsAtom),t.get(a.activeEnvironmentIdAtom)));const E=t.get(a.tabsAtom)[i],ce=E&&a.isStepTab(E)?E.data.response:null;return ce?{isError:!1,data:jr(ce)}:y("Request did not produce a response.")}}function jr(e){return{status:e.status,headers:be(e.headers),cookies:be(e.cookies),body:Wr(e.body??""),url:e.url??"",duration:e.duration,size:e.size}}function be(e){const t=[];for(const o of e)t.push([String(o[0]),String(o[1])]);return t}function Wr(e){return e.length<=m.RESPONSE_BODY_PREVIEW_MAX?e:`${e.slice(0,m.RESPONSE_BODY_PREVIEW_MAX)}… (truncated, total ${e.length} chars)`}const Qe={name:"run_request",definition:Dr,createExecutor:e=>Mr(e.settings,e.store)},Lr=`Run an Arazzo workflow and return its result.
120
+
121
+ **What it does**
122
+ - Executes the whole workflow (all steps, with cross-step \`$steps.*\` resolution) and waits for it to finish.
123
+ - Saves the run and returns its \`historyId\` plus a per-step outcome summary.
124
+ - Does not open any tab. The user opens the finished run themselves from the link you provide.
125
+
126
+ **Use when**
127
+ - The user explicitly asks to run, re-run, test, or verify a workflow, or accepts a run you offered.
128
+ - You need the actual outcome of a workflow (status codes, which steps failed).
129
+
130
+ **Never use when**
131
+ - The user only asked to create, build, update, or fix a workflow. Creating is not running: finish at the saved workflow and offer the run instead of starting one.
132
+ - You want to confirm your own work. A build request never authorizes real traffic with the user's credentials.
133
+ - You need a single HTTP request — use \`run_request\`.
134
+ - You only need to read an already finished run that is open in a tab — use \`get_current_tab\`.
135
+
136
+ **Input guidance**
137
+ - \`collectionId\` and \`workflowId\` are required; use ids exactly as stored in Replay.
138
+
139
+ **After the run**
140
+ - Report the outcome from this tool's result; do not re-read it with other tools.
141
+ - When \`historyId\` is non-null, link to the run: \`[label](replay://workflow-run?collectionId=...&workflowId=...&historyId=...)\`. That link reopens this exact run; it never starts a new one. When it is null, say the run was not saved instead of building a link; never put the literal text null in the url.
142
+ - Each call starts a NEW run. Call it again only when the user wants another run.`,Fr=r.strictObjectType({collectionId:r.stringType().describe("Id of the collection that holds the workflow."),workflowId:r.stringType().describe("Id of the workflow to run.")}),Br=r.objectType({stepId:r.stringType(),statusCode:r.numberType().int().nullable(),passed:r.booleanType()}),Yr=r.objectType({collectionId:r.stringType().describe("Resolved id of the collection that was run."),workflowId:r.stringType().describe("Resolved id of the workflow that was run."),historyId:r.stringType().nullable().describe("Id of this saved run. Put it in the workflow-run link as &historyId=... so the user can reopen this exact run. Null when history is not persisted."),success:r.booleanType().describe("Overall verdict from the execution engine. False when a step failed a non-warn check or the run hit the global timeout. Can be false even when passedSteps equals totalSteps: a step that failed and then passed on retry is not counted as failed here."),timedOut:r.booleanType().describe("True when the run hit the global execution timeout. Then success is false even if every listed step passed; report that the run timed out rather than blaming a step."),durationMs:r.numberType().describe("Total run time in milliseconds."),totalSteps:r.numberType().int().nonnegative(),passedSteps:r.numberType().int().nonnegative(),steps:r.arrayType(Br).describe("Per-step outcome, in execution order: stepId, HTTP statusCode, and pass/fail only — no check name or failure message.")}),zr=C(Yr),Hr={description:Lr,inputSchema:Fr,outputSchema:zr,needsApproval:!1};function Gr(e,t){return async(o,n)=>{const s=o.collectionId.trim(),i=o.workflowId.trim();if(!s)return y("collectionId is required.");if(!i)return y("workflowId is required.");const c=se(e.get(a.collectionsAtom),s,i);if(!c.ok)return y(c.message,c.details);try{const{workflowResult:d,historyId:l,verdict:u}=await t({collectionId:c.value.collectionId,workflowId:c.value.workflowId});return{isError:!1,data:{collectionId:c.value.collectionId,workflowId:c.value.workflowId,historyId:l,success:u.succeeded,timedOut:u.timedOut,durationMs:d.totalTimeMs,totalSteps:u.totalSteps,passedSteps:u.passedSteps,steps:u.steps.map(({step:p,passed:f})=>({stepId:p.stepId,statusCode:p.response?.statusCode??null,passed:f}))}}}catch(d){return y(d instanceof Error?d.message:"Workflow execution failed.")}}}const Ze={name:"run_workflow",definition:Hr,createExecutor:e=>Gr(e.store,e.runWorkflow)},Vr=25,Kr='RAG semantic search over OpenAPI specs and Arazzo assets in the current Replay project.\n\n**What it does**\n- Finds OpenAPI and Arazzo entities via natural-language query (scoped by `type`), returning up to `count` matches with detail via `include`.\n\n**Use when**\n- You need **initial schema/context** or request schema details from project assets.\n- You need canonical IDs/coordinates for an API, collection, workflow, or step.\n- You need to find operations/workflows/steps by natural language when IDs are unknown.\n\n**Never use when**\n- You are only verifying post-action UI changes in the active tab.\n- You already have exact IDs and only need active-tab state.\n- You are about to repeat an identical no-result query.\n\n**Input guidance**\n- Rewording the same query rarely helps; change `type`, `query`, or intent instead.\n- "Collection" is ambiguous (Arazzo entity vs API requests by tags/path/criteria). For request lists, use `type: api_operation` with query/filters—not Arazzo `collection`.\n- Pass all known filters (`apiId`, `path`, `method`, `operationId`, `collectionId`, `workflowId`, `stepId`); `query + filters` is most precise.\n- If semantic search returns no matches, ID filters enable direct lookup (see pairing on each filter field).\n- Phrase `query` like indexed text: titles/descriptions for collections/workflows; `step: …`; `operationId: …`; path/method/tags for endpoints.\n- If results are empty and lookup needs missing IDs, the tool may ask for them.\n',Jr=r.objectType({query:r.stringType().optional().describe("Natural language search query."),count:r.numberType().positive().max(Vr).optional().default(10),type:r.enumType(["api_operation","api","collection","workflow","step"]).describe("Scope results to this item type. api = OpenAPI spec; api_operation = API endpoint; collection = Arazzo collection; workflow = Arazzo workflow; step = Arazzo workflow step."),include:r.arrayType(r.enumType(["description","path","method","operationId","requestBody","parameters","security","responses","tags","successCriteria","title"])).describe("Fields to include in the response."),apiId:r.stringType().optional().describe("OpenAPI API ID (from loaded spec). For one endpoint, pair with operationId or path+method."),path:r.stringType().optional().describe("Filter by API path (e.g. /users). Use with method for precise operation matching."),method:r.stringType().optional().describe("Filter by HTTP method (GET, POST, PUT, DELETE, etc). Use with path for precise operation matching."),operationId:r.stringType().optional().describe("OpenAPI operationId. Requires apiId."),collectionId:r.stringType().optional().describe("Arazzo collection ID."),workflowId:r.stringType().optional().describe("Workflow ID within the collection. Requires collectionId."),stepId:r.stringType().optional().describe("Step ID within a workflow. Requires collectionId and workflowId.")}).strict(),Xr=r.unknownType(),Qr={description:Kr,inputSchema:Jr,outputSchema:Xr,needsApproval:!1},Zr=["get","put","post","delete","options","head","patch","trace"],es=["query","x-query"];function ts(e){return async(t,o)=>{const n=A.getSemanticSearchService(),s={type:t.type,apiId:t.apiId,operationId:t.operationId,path:t.path,method:t.method,collectionId:t.collectionId,workflowId:t.workflowId,stepId:t.stepId},i=t.query??"";let c=await n.search(i,t.count,s);return c.length===0&&(c=is(e,s)),c.length===0?{isError:!1,data:{message:`No results found. ${os(t)}`}}:{isError:!1,data:{message:as(c,t.include)}}}}function os(e){const t=[],{type:o,apiId:n,path:s,method:i,operationId:c,collectionId:d,workflowId:l,stepId:u,query:p}=e;switch(o){case"api":n||t.push("apiId");break;case"api_operation":{if(!n){t.push("apiId");break}const g=c!=null&&c!=="",I=s!=null&&s!==""&&i!=null&&i!=="";!g&&!I&&t.push("operationId","path","method");break}case"collection":d||t.push("collectionId");break;case"workflow":d?l||t.push("workflowId"):t.push("collectionId");break;case"step":d?l?u||t.push("stepId"):t.push("workflowId"):t.push("collectionId");break;default:if(d!=null&&d!==""&&(l?u||t.push("stepId"):t.push("workflowId")),n!=null&&n!==""){const g=c!=null&&c!=="",I=s!=null&&s!==""&&i!=null&&i!=="";!g&&!I&&t.push("operationId","path","method")}}p!=null&&p.trim()!==""||t.push("query");const h=[...new Set(t)];let b;return h.length===0?b="You already pass strong filters. Try a more specific natural-language query, or confirm IDs and paths match the project.":b=`To improve results, prefer adding (in order): ${h.slice(0,5).join(", ")}. When names are known but IDs are not, phrase query like indexed text: collection/workflow titles and descriptions; step: …; operationId: …; path/method/summary/tags for endpoints.`,b}function ns(e,t){const o=e.paths??{};for(const[n,s]of Object.entries(o)){if(!s||typeof s!="object")continue;const i=s,c=[...Zr.filter(l=>l in s),...es.filter(l=>l in s)];for(const l of c){const u=s[l];if(!u||typeof u!="object")continue;const p=u;if(!(t.operationId&&(p.operationId??"")!==t.operationId)&&!(t.path&&n!==t.path)&&!(t.method&&l.toUpperCase()!==t.method.toUpperCase()))return{path:n,method:l,op:p,pathItem:i}}const d=i.additionalOperations;if(d&&typeof d=="object")for(const[l,u]of Object.entries(d)){if(!u||typeof u!="object")continue;const p=u;if(!(t.operationId&&(p.operationId??"")!==t.operationId)&&!(t.path&&n!==t.path)&&!(t.method&&l.toUpperCase()!==t.method.toUpperCase()))return{path:n,method:l,op:p,pathItem:i}}}return null}function rs(e,t){const{type:o,apiId:n,operationId:s,path:i,method:c}=t;if(!n)return[];const d=e.find(b=>b.id===n);if(!d)return[];if(o==="api")return[{...A.extractApiDocument(d).payload,score:1}];const l=s!=null&&s!=="",u=i!=null&&i!==""&&c!=null&&c!=="";if(!(o==="api_operation"||l||u||o==null&&(l||u)))return o==null?[{...A.extractApiDocument(d).payload,score:1}]:[];const f=ns(d,{operationId:s,path:i,method:c});return f?[{...A.extractOperationDocument({apiId:d.id,apiTitle:d.info?.title??"Untitled API",path:f.path,method:f.method,op:f.op,pathItem:f.pathItem,globalSchemes:A.extractGlobalSecuritySchemes(d),apiSecurity:d.security}).payload,score:1}]:[]}function ss(e,t){const{type:o,collectionId:n,workflowId:s,stepId:i}=t;if(!n)return[];const c=e.find(p=>p.id===n);if(!c)return[];const d=c.info?.title??"Untitled Collection";if(o==="collection")return[{...A.extractCollectionDocument(c).payload,score:1}];const l=()=>{if(!s||!i)return[];const p=c.workflows?.find(h=>(h.workflowId??"")===s);if(!p)return[];const f=p.steps?.find(h=>(h.stepId??"")===i);return f?[{...A.extractStepDocument({collectionId:n,collectionTitle:d,workflowId:s,workflowTitle:p.summary??s,step:f}).payload,score:1}]:[]},u=()=>{if(!s)return[];const p=c.workflows?.find(f=>(f.workflowId??"")===s);return p?[{...A.extractWorkflowDocument({collectionId:n,collectionTitle:d,workflow:p}).payload,score:1}]:[]};return o==="step"?l():o==="workflow"?u():o==null?i&&s?l():s?u():[{...A.extractCollectionDocument(c).payload,score:1}]:[]}function is(e,t){const o=e.get(a.apisAtom),n=e.get(a.collectionsAtom),{type:s}=t;return s==="api"||s==="api_operation"?rs(o,t):s==="collection"||s==="workflow"||s==="step"?ss(n,t):[]}function as(e,t){return[Vt(e,t).join(`
143
+
144
+ `)].filter(n=>n!=null&&n.length>0).join(`
145
+
146
+ `)}const cs="You already ran this exact search earlier in this conversation. If nothing has changed since then, reuse those results instead of repeating. If you expect different results (for example after an edit), do not just repeat the same search - change the query, the type, or the filters, or read the current state another way.",ls=10;function ds(e){const t=[e.type,R(e.query),R(e.apiId),R(e.operationId),R(e.path),R(e.method)?.toLowerCase(),R(e.collectionId),R(e.workflowId),R(e.stepId)];return t.every(o=>o==null)?null:JSON.stringify([...t,us(e),ps(e)])}function us(e){return typeof e?.count=="number"?e.count:ls}function ps(e){return Array.isArray(e?.include)?[...new Set(e.include)].sort():[]}function R(e){if(typeof e!="string")return null;const t=Re(e);return t===""?null:t}const fs=[xe({key:ds,warn:cs})],et={name:"search",definition:Qr,guards:fs,createExecutor:e=>ts(e.store)},ms="Update security (x-security) for one or more Replay steps.\n\n**What it does**\n- Applies atomic add/update/remove changes to step security entries.\n- `add` UPSERTS by scheme identity: an existing entry with the same `schemeId` (or same `type` when `schemeId` is omitted) - including the auto-seeded entry created when the step was linked to its operation - is updated in place, never duplicated. Repeated identical wiring converges.\n- The result echoes each affected step's resulting security in `resultingState`; confirm from it, do NOT re-read tabs after mutation.\n- Empty security list falls back to No Auth.\n\n**Targeting**\n- Saved step: `collectionId` + `workflowId` + `stepId`.\n- Multi-step batch: set `changes[].stepId` per change (top-level `stepId` is the default and may be empty); wire a whole chain in ONE call.\n- Unsaved draft tab on focus: all three ids empty strings, no per-change stepId.\n\n**Choosing the type (match the OpenAPI scheme)**\n- http bearer -> `JWT` (`data.token`). A plain bearer token is NOT OAuth 2.0.\n- http basic -> `Basic Auth`, http digest -> `Digest Auth` (`data.username`, `data.password`).\n- apiKey -> `API key` (`data.name`, `data.key`, `data.location`); keep `data.key`'s `$inputs.<name>` segment identical to `data.name`.\n- oauth2 (grant-based flows only) -> `OAuth 2.0`; `data.grantType` is REQUIRED with flow values (`accessToken`, `clientId`, ...): `clientCredentials`, `clientCredentialsWithJwtAssertion`, `authorizationCode`, `authorizationCodeWithPkce`, `implicit`, `password`.\n- openIdConnect -> `OpenID Connect` (`data.openIdConnectUrl` plus OAuth2 fields).\n- `add` with a `schemeId` existing under a different type is rejected; use `update` at that index only to intentionally change a type.\n\n**Change shapes**\n- add/update: `{ action, stepId?, index?, type, schemeId?, data? }`; pass `schemeId` whenever known (it is the upsert identity), `index` is required for update.\n- remove: `{ action: \"remove\", stepId?, index }`.",hs=["clientCredentials","clientCredentialsWithJwtAssertion","authorizationCode","authorizationCodeWithPkce","implicit","password"],ys={grantType:r.enumType(hs).optional().describe("OAuth2 grant type."),clientId:r.stringType().optional(),clientSecret:r.stringType().optional(),tokenUrl:r.stringType().optional(),authorizationUrl:r.stringType().optional(),callbackUrl:r.stringType().optional(),accessToken:r.stringType().optional(),username:r.stringType().optional().describe("For password grant type."),password:r.stringType().optional().describe("For password grant type.")},Is=r.objectType({username:r.stringType().optional(),password:r.stringType().optional()}).strict(),ws=r.objectType({username:r.stringType().optional(),password:r.stringType().optional()}).strict(),gs=r.objectType({token:r.stringType().optional()}).strict(),bs=r.objectType({location:r.enumType(["header","query","cookie"]).optional(),name:r.stringType().optional().describe("Must match the OpenAPI security scheme `name` (header/query/cookie parameter name). Not the scheme component ref id (e.g. UserCookie)."),key:r.stringType().optional().describe("Secret value or `$inputs.<name>` / `{$inputs.<name>}`. The `<name>` segment must be identical to `data.name` (OpenAPI apiKey `name`, e.g. accessToken). Wrong example: `data.name` accessToken but key `$inputs.UserCookie` (UserCookie is the securitySchemes ref, not the cookie name).")}).strict(),tt=r.objectType({...ys}).strict(),vs=tt.extend({openIdConnectUrl:r.stringType().optional(),userInfoUrl:r.stringType().optional()}).strict(),ot=r.stringType().optional().describe("Target step id for this change. Overrides the top-level stepId; use to batch changes for several steps of the same workflow in one call."),N=wo.extend({action:r.enumType(["add","update"]),schemeId:r.stringType().optional(),stepId:ot}),Ts=r.discriminatedUnionType("type",[N.extend({type:r.literalType(a.SecurityTypes.BasicAuth),data:Is.optional()}).strict(),N.extend({type:r.literalType(a.SecurityTypes.DigestAuth),data:ws.optional()}).strict(),N.extend({type:r.literalType(a.SecurityTypes.JWT),data:gs.optional()}).strict(),N.extend({type:r.literalType(a.SecurityTypes.APIKey),data:bs.optional()}).strict(),N.extend({type:r.literalType(a.SecurityTypes.OAuth2),data:tt.optional()}).strict(),N.extend({type:r.literalType(a.SecurityTypes.OpenIDConnect),data:vs.optional()}).strict()]),Ss=oe.extend({action:r.literalType("remove"),index:r.numberType().int().min(0).describe("0-based position of the entry in the step's current security list; every index in one call refers to that same list. Position, not schemeId, identifies the entry - a step can list the same scheme more than once."),stepId:ot}).strict(),ks=r.unionType([Ts,Ss]),As=r.objectType({collectionId:r.stringType().describe("Saved step: collection id. Unsaved draft tab on focus: empty string (with empty workflowId and stepId)."),workflowId:r.stringType().describe("Saved step: workflow id. Unsaved draft tab: empty string (with empty collectionId and stepId)."),stepId:r.stringType().describe("Saved step: step id (default target for changes without their own stepId; may be empty when every change sets one). Unsaved draft tab: empty string (with empty collectionId and workflowId)."),changes:r.arrayType(ks).min(1).describe("List of security changes to apply.")}).strict().superRefine((e,t)=>{const o=e.collectionId.trim(),n=e.workflowId.trim(),s=e.stepId.trim(),i=e.changes.map(p=>p.stepId?.trim()),c=i.every(Boolean),d=i.some(Boolean);!(o&&n&&(s||c))&&!(!o&&!n&&!s&&!d)&&t.addIssue({code:r.ZodIssueCode.custom,message:"Provide collectionId and workflowId plus a stepId for every change (top-level or per-change), or all empty ids for the focused unsaved request tab.",path:["collectionId"]})}),Cs=Pe,Os={description:ms,inputSchema:As,outputSchema:Cs,needsApproval:()=>!0},k={ADD:"add",UPDATE:"update",REMOVE:"remove"};function w(e,t){return{status:e,...t!==void 0&&{summary:t}}}function nt(e){if(!e||typeof e!="object"||!("meta"in e))return{};const{meta:t}=e;if(!t||typeof t!="object")return{};const o="totalChanges"in t&&typeof t.totalChanges=="number"?t.totalChanges:void 0,n="approvedChanges"in t&&typeof t.approvedChanges=="number"?t.approvedChanges:void 0;return{totalChanges:o,approvedChanges:n}}function rt(e,t){return!Number.isInteger(t.index)||t.index<0||t.index>=e.length?{ok:!1,message:`Index ${t.index} out of bounds. Step has ${e.length} security entries.`}:{ok:!0,entry:e[t.index]}}const Es=new Set(["grantType","openIdConnectUrl","userInfoUrl"]);function _s(e){return e.type===a.SecurityTypes.OAuth2||e.type===a.SecurityTypes.OpenIDConnect}function ve(e,t){const o=e;for(const[n,s]of Object.entries(t))s!==void 0&&n in o&&(o[n]=s)}function Te(e,t){const o=Object.entries(t);for(const[i,c]of o)i==="grantType"&&typeof c=="string"&&a.GRANT_TYPE_MAP[c]&&(e.grantType=a.GRANT_TYPE_MAP[c]);const n=e[e.grantType],s=new Set(Object.keys(a.OAUTH2_SECURITY[e.grantType]));for(const[i,c]of o)i!=="grantType"&&c!==void 0&&s.has(i)&&(n[i]=c)}function st(e){return e.securityType===a.SecurityTypes.NoAuth?null:e[e.securityType]?.schemeName??null}function Rs(e,t){!t||e.securityType===a.SecurityTypes.NoAuth||(e.securitySchemeId=t,e[e.securityType].schemeName=t)}function Q(e,t){if(e.securityType=t.type,Rs(e,t.schemeId),!t.data)return e;switch(t.type){case a.SecurityTypes.BasicAuth:case a.SecurityTypes.DigestAuth:case a.SecurityTypes.JWT:ve(e[t.type],t.data);break;case a.SecurityTypes.APIKey:{const{location:o,...n}=t.data;ve(e[a.SecurityTypes.APIKey],n),o&&(e[a.SecurityTypes.APIKey].location=a.getAPIKeyLocation(o));break}case a.SecurityTypes.OAuth2:Te(e[a.SecurityTypes.OAuth2],t.data);break;case a.SecurityTypes.OpenIDConnect:{const{openIdConnectUrl:o,userInfoUrl:n,...s}=t.data;Te(e[a.SecurityTypes.OpenIDConnect],s),o!==void 0&&(e[a.SecurityTypes.OpenIDConnect].openIdConnectUrl=o),n!==void 0&&(e[a.SecurityTypes.OpenIDConnect].userInfoUrl=n);break}}return e}function xs(e,t){return t.schemeId?e.findIndex(o=>o.securitySchemeId===t.schemeId||st(o)===t.schemeId):e.findIndex(o=>o.securityType===t.type)}function $s(e){return e.data?Object.entries(e.data).some(([t,o])=>o!==void 0&&!Es.has(t)):!1}function Ps(e){return e.schemeId?`${e.type} (scheme '${e.schemeId}')`:e.type}function Se(e,t,o,n){return e.has(t)?{ok:!1,message:`The security entry at index ${o} is targeted by both a mutation and a remove${n}; issue only one action for it.`}:null}function qs(e,t,o){let n=e;const s=[],i=t.filter(l=>l.action!==k.REMOVE),c=t.filter(l=>l.action===k.REMOVE),d=new Set;for(const l of c){const u=rt(e,l);if(!u.ok)return{ok:!1,message:u.message};d.add(u.entry)}for(const l of i){if(l.action===k.ADD){const f=n.length===1&&n[0].securityType===a.SecurityTypes.NoAuth,h=f?-1:xs(n,l);if(h>=0){const g=n[h],I=Se(d,g,h,o);if(I)return I;if(g.securityType!==l.type)return{ok:!1,message:`Scheme '${l.schemeId}' already exists${o} as ${g.securityType}, not ${l.type}. Match the documented scheme type (plain http/bearer -> JWT with data.token; OAuth 2.0 only for grant-based flows), or use action "update" at index ${h} to intentionally change the type.`};n=[...n],n[h]=Q(structuredClone(g),l),s.push(w("applied",`Updated existing ${Ps(l)} in place (index: ${h})${o}`));continue}if(_s(l)&&$s(l)&&!l.data?.grantType)return{ok:!1,message:`grantType is required when adding ${l.type} security with flow values${o}. For a plain http/bearer token use type "${a.SecurityTypes.JWT}" with data.token instead.`};const b=Q(a.getEmptySingleSecurity(),l);n=f?[b]:[...n,b],s.push(w("applied",`Added ${l.type} security (index: ${n.length-1})${o}`));continue}if(l.index===void 0)return{ok:!1,message:"index is required for update action."};if(l.index>=n.length)return{ok:!1,message:`Index ${l.index} out of bounds. Step has ${n.length} security entries.`};const u=n[l.index],p=Se(d,u,l.index,o);if(p)return p;if(u.securitySchemeId){const f=st(u);if(l.schemeId&&f!==l.schemeId)return{ok:!1,message:`schemeId mismatch at index ${l.index}. Expected ${f??"none"}.`}}n=[...n],n[l.index]=Q(structuredClone(u),l),s.push(w("applied",`Updated ${l.type} at index ${l.index}${o}`))}if(d.size>0){const l=n.filter(p=>!d.has(p)),u=n.length-l.length;n=l;for(let p=0;p<u;p++)s.push(w("applied"))}return n.length===0&&(n=[a.getEmptySingleSecurity()]),{ok:!0,security:n,applied:s}}function Ns(e){return async t=>{const{changes:o,collectionId:n,workflowId:s,stepId:i}=t,c=nt(t),d=i.trim(),l=new Map;for(const h of o){const b=h.stepId?.trim()||d,g=l.get(b);g?g.push(h):l.set(b,[h])}const u=[],p=[];for(const[h,b]of l){const g=Ge(e,n,s,h);if(!g.ok)return y(g.message,g.details);const{readStep:I,updateStep:T}=g.value,v=h||g.value.step.stepId,O=l.size>1?` for step '${v}'`:"",X=Array.from(I().security),E=qs(X,b,O);if(!E.ok)return y(E.message);u.push(...E.applied),p.push({updateStep:T,security:E.security,label:v})}for(const h of p)h.updateStep(b=>({...b,security:h.security}));const f=p.map(h=>`stepId=${h.label}
147
+ ${m.buildSecuritySection(h.security)}`).join(`
148
+
149
+ `);return{isError:!1,data:{totalChanges:c.totalChanges??o.length,approvedChanges:c.approvedChanges??o.length,applied:u,resultingState:f}}}}const it={name:"update_security",definition:Os,createExecutor:e=>Ns(e.store)},Us=`Update an existing Replay step with atomic changes.
150
+
151
+ **What it does**
152
+ - Mutates an existing step only (no create/delete).
153
+ - Supports updates to \`url\`, \`method\`, \`description\`, \`body\`, \`parameters\`, \`outputs\`, and \`successCriteria\`.
154
+ - \`outputs\` \`add\` upserts by name: an existing output with the same name is updated in place, never duplicated.
155
+ - After outputs changes the result echoes the resulting outputs in \`resultingState\`; no follow-up read needed.
156
+
157
+ **Use when**
158
+ - You need targeted atomic edits to a saved step (by IDs) or the focused unsaved step.
159
+
160
+ **Never use when**
161
+ - IDs and focused tab refer to different execution contexts.
162
+ - You expect parameter edits to auto-rewrite URL; URL changes must be explicit.
163
+
164
+ **Input guidance**
165
+ - Saved step: non-empty \`collectionId\`, \`workflowId\`, \`stepId\`.
166
+ - Focused unsaved request tab: all three IDs are empty strings.
167
+ - \`changes\` must be non-empty; each item mutates one field and has \`action\` = \`add\` | \`update\` | \`remove\`.
168
+ - \`changes[].id\` is required for \`update/remove\`: use row UUID for \`parameters\`/\`outputs\` (never name/key), and exact existing \`condition\` for \`successCriteria\`.
169
+ - Data shapes:
170
+ - \`url\`: string
171
+ - \`description\`: string
172
+ - \`method\`: one of ${a.REQUEST_METHODS.join(", ")}
173
+ - \`parameters\`: \`{ name, in: path|query|header|cookie, value }\`
174
+ - \`outputs\`: \`{ name, expression }\`
175
+ - \`successCriteria\`: \`{ condition, context?, type? }\`
176
+ - \`body\`: \`{ content, contentType? }\` with \`contentType\` in text/plain, application/json, application/xml
177
+ - Environment variable refs in params/body: \`{$inputs.name}\` or bare \`$inputs.name\`; the input must exist on the active environment (create it there first if missing). Prefer \`$inputs.*\` for tokens/shared config.
178
+
179
+ **Loop/budget guidance**
180
+ - Batch related edits in one call; include all known edits up front.
181
+ - For OpenAPI-linked steps, avoid method/url changes.
182
+ - After changing path/query parameters, decide whether to add a separate URL change.
183
+ `,Ds=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],Ms=[a.TextContentType.Text,a.TextContentType.JSON,a.TextContentType.XML],js=r.objectType({name:r.stringType().min(1),in:r.enumType(["path","query","header","cookie"]),value:r.stringType()}).strict(),Ws=r.objectType({condition:r.stringType().min(1),context:r.stringType().optional().describe("Context for the expression."),type:r.enumType(["simple","regex","jsonpath","xpath"]).optional()}).strict(),Ls=$.extend({field:r.literalType("url"),data:r.stringType().min(1).describe("New request URL for step.")}).strict(),Fs=$.extend({field:r.literalType("description"),data:r.stringType().describe("New step description text.")}).strict(),Bs=$.extend({field:r.literalType("method"),data:r.enumType(Ds).describe("New HTTP method for x-operation step.")}).strict(),Ys=$.extend({field:r.literalType("parameters"),data:js.optional().describe("Parameter data. Required for add/update actions.")}).strict(),zs=$.extend({field:r.literalType("outputs"),data:r.objectType({name:r.stringType().min(1).describe("Output name."),expression:r.stringType().min(1).describe("Output expression.")}).strict().optional().describe("Output mapping. Required for add/update actions.")}).strict(),Hs=$.extend({field:r.literalType("successCriteria"),data:Ws.optional().describe("Success criterion. Required for add/update actions.")}).strict(),Gs=$.extend({field:r.literalType("body"),data:r.objectType({contentType:r.enumType(Ms).optional().describe("Request body content type. Allowed: text/plain, application/json, application/xml."),content:r.stringType().describe("Request body content as string.")}).strict().describe("Request body content and optional content type.")}).strict(),Vs=r.discriminatedUnionType("field",[Ls,Fs,Bs,Ys,zs,Hs,Gs]),Ks=r.objectType({collectionId:r.stringType().describe("Saved step: collection id. Unsaved draft tab on focus: empty string (with empty workflowId and stepId)."),workflowId:r.stringType().describe("Saved step: workflow id. Unsaved draft tab: empty string (with empty collectionId and stepId)."),stepId:r.stringType().describe("Saved step: step id. Unsaved draft tab: empty string (with empty collectionId and workflowId)."),changes:r.arrayType(Vs).min(1).describe("List of individual changes to apply to the step.")}).strict().superRefine((e,t)=>{const o=e.collectionId.trim(),n=e.workflowId.trim(),s=e.stepId.trim();!(o&&n&&s)&&!(!o&&!n&&!s)&&t.addIssue({code:r.ZodIssueCode.custom,message:"Provide all three ids for a saved step, or three empty strings for the focused unsaved request tab.",path:["collectionId"]})}),Js=Pe,Xs={description:Us,inputSchema:Ks,outputSchema:Js,needsApproval:()=>!0};function Qs(e){return e.replace(/\{\{([^{}\s]+)\}\}/g,"{$1}")}function Z(e){return M[e]}function ee(e,t){return e.id===t}function ke(e,t){return e.condition===t}function te(e,t){return a.isInlineRequestParameter(e)&&e.id===t}function Ae(e,t,o){return{...a.getEmptyRequestParameter(e),key:t,value:o,active:!0}}function ie(e,t){e(o=>[...o,...t])}function Y(e,t,o){let n=!1;return e(s=>{const i=s.findIndex(d=>o.find(d,t));if(i<0)return s;const c=[...s];return c[i]=o.produce(s[i]),n=!0,c}),n}function ae(e,t,o){let n=!1;return e(s=>{const i=s.filter(c=>!o(c,t));return n=i.length<s.length,i}),n}function Zs(e,{readStep:t,updateParameters:o}){switch(e.action){case k.ADD:{if(!e.data)return w("failed","Failed parameter add because data is missing.");const{in:n,name:s,value:i}=e.data,c=Z(n),d=Ae(n,s,i);return ie(o(c),[d]),w("applied",`Added ${n} parameter '${s}' (id: ${d.id})`)}case k.UPDATE:{if(!e.id)return w("failed","Failed parameter update because id is missing.");if(!e.data)return w("failed","Failed parameter update because data is missing.");const{in:n,name:s,value:i}=e.data,c=Z(n);return Y(o(c),e.id,{find:te,produce:l=>a.isInlineRequestParameter(l)?{...Ae(n,s,i),id:l.id,...l.allowReserved!==void 0&&{allowReserved:l.allowReserved}}:l})?w("applied"):w("failed",`Parameter with id '${e.id}' not found.`)}case k.REMOVE:{if(!e.id)return w("failed","Failed parameter remove because id is missing.");const n=e.id,s=e.data?.in,i=s?[Z(s)]:Object.values(M);let c=!1;for(const d of i)if(t().parameters[d].some(u=>te(u,n))){c=ae(o(d),n,te);break}return c?w("applied"):w("failed",`Parameter with id '${n}' not found.`)}}}function ei(e,{readStep:t,updateOutputs:o}){switch(e.action){case k.ADD:{if(!e.data)return w("failed","Failed output add because data is missing.");const{name:n,expression:s}=e.data,i=t().outputs.find(d=>d.key===n);if(i)return Y(o,i.id,{find:ee,produce:d=>({...d,key:n,value:s,active:!0})}),w("applied",`Updated existing output '${n}' in place (id: ${i.id})`);const c=crypto.randomUUID();return ie(o,[{id:c,key:n,value:s,active:!0}]),w("applied",`Added output '${n}' (id: ${c})`)}case k.UPDATE:{if(!e.id)return w("failed","Failed output update because id is missing.");if(!e.data)return w("failed","Failed output update because data is missing.");const{name:n,expression:s}=e.data;return Y(o,e.id,{find:ee,produce:c=>({...c,key:n,value:s,active:!0})})?w("applied"):w("failed",`Output with id '${e.id}' not found.`)}case k.REMOVE:return e.id?ae(o,e.id,ee)?w("applied"):w("failed",`Output with id '${e.id}' not found.`):w("failed","Failed output remove because id is missing.")}}function ti(e,{updateSuccessCriteria:t}){switch(e.action){case k.ADD:{if(!e.data)return w("failed","Failed success criteria add because data is missing.");const{condition:o,context:n,type:s}=e.data,i=a.getEmptyCriterionObject(s??a.CriterionType.SIMPLE);return ie(t,[{...i,condition:o,...n!==void 0&&{context:n}}]),w("applied")}case k.UPDATE:{if(typeof e.id!="string")return w("failed","Failed success criteria update because id is missing.");if(!e.data)return w("failed","Failed success criteria update because data is missing.");const{condition:o,context:n,type:s}=e.data;return Y(t,e.id,{find:ke,produce:c=>({...c,id:c.id||crypto.randomUUID(),condition:o,context:n??c.context,type:s??c.type??a.CriterionType.SIMPLE})})?w("applied"):w("failed",`Success criterion with condition '${e.id}' not found.`)}case k.REMOVE:return typeof e.id!="string"?w("failed","Failed success criteria remove because id is missing."):ae(t,e.id,ke)?w("applied"):w("failed",`Success criterion with condition '${e.id}' not found.`)}}const Ce={method:"GET",url:""};function oi(e){return async t=>{const{changes:o,collectionId:n,workflowId:s,stepId:i}=t,c=nt(t),d=Ge(e,n,s,i);if(!d.ok)return y(d.message,d.details);const{step:l,readStep:u,updateStep:p}=d.value,f={readStep:u,updateParameters:I=>T=>p(v=>({...v,parameters:{...v.parameters,[I]:T(v.parameters[I])}})),updateOutputs:I=>p(T=>({...T,outputs:I(T.outputs)})),updateSuccessCriteria:I=>p(T=>({...T,successCriteria:I(T.successCriteria)}))};if(o.some(I=>I.field==="method"||I.field==="url")&&l.operation!==null)return y("Cannot update method or url for a step linked to an OpenAPI operation.");const b=[];for(const I of o)switch(I.field){case"method":case"url":{if(I.field==="method"){const T=I.data;p(v=>({...v,xOperation:{...v.xOperation??Ce,method:T}}))}else{const T=Qs(I.data);p(v=>({...v,xOperation:{...v.xOperation??Ce,url:T},parameters:{...v.parameters,queryParameters:a.mergeUrlParametersWithPreviousParameters(a.stringToQueryParameters(T),v.parameters.queryParameters)}}))}b.push(w("applied"));break}case"description":{const T=I.data;p(v=>({...v,description:T})),b.push(w("applied"));break}case"body":{const{content:T,contentType:v}=I.data;p(O=>({...O,requestBody:{...O.requestBody,content:T,...v!==void 0&&{type:v}}})),b.push(w("applied"));break}case"parameters":b.push(Zs(I,f));break;case"outputs":b.push(ei(I,f));break;case"successCriteria":b.push(ti(I,f));break}const g=o.some(I=>I.field==="outputs");return{isError:!1,data:{totalChanges:c.totalChanges??o.length,approvedChanges:c.approvedChanges??o.length,applied:b,...g&&{resultingState:m.buildStepOutputsSection(u().outputs)||"Outputs: (none)"}}}}}const at={name:"update_step",definition:Xs,createExecutor:e=>oi(e.store)},ni=`Search the public web via a nested agent and return a consolidated summary.
184
+
185
+ **What it does**
186
+ - Runs provider web search (results depend on the active model provider) and synthesizes findings for the parent agent.
187
+ - Does not read or mutate the Replay project, workflows, or UI.
188
+ - Requires user approval and costs multiple LLM round-trips.
189
+
190
+ **Use when**
191
+ - You need up-to-date or external information (docs, standards, release notes, vendor behavior) that is not in the project.
192
+ - The answer depends on the public internet rather than loaded specs or workflows.
193
+
194
+ **Never use when**
195
+ - You already have the URLs or facts needed to proceed.
196
+ - You need to edit workflows, run requests, or change environments.
197
+
198
+ **Input guidance**
199
+ - State a clear, self-contained query: what to look up and what to return (facts, links, version numbers, etc.).
200
+ - Prefer one web search call per distinct lookup; do not nest web search calls.`,ri=r.objectType({task:r.stringType().describe("What to search for on the web and what to return"),url:r.stringType().describe("The URL to execute search on")}),si=r.unknownType(),ii={description:ni,inputSchema:ri,outputSchema:si,needsApproval:!0},ai=`
201
+ You are a web search subagent inside Replay, invoked by the parent agent to complete a single lookup task.
202
+
203
+ Your job is to search the public web and return verified findings for the parent agent to act on. You do not communicate with the end user directly.
204
+
205
+ You must use the provider web search tool to gather information. You cannot access the Replay project, UI, workflows, internal state, or any tools other than the web search tool.
206
+ `,ci=`
207
+ - Never hallucinate or invent an answer when the information is not available from the web search.
208
+ - Do not use general knowledge, assumptions, prior training data, or speculation as evidence. Only make claims that are explicitly supported by the web search results.
209
+ - If the web search results do not contain enough information to answer the question, clearly state that the information could not be found or verified.
210
+ - Return a consolidated findings summary for the parent agent, not a user-facing completion message.
211
+ - Lead with the answer to the task, followed by supporting evidence (key facts, version numbers, dates, and relevant quotes).
212
+ - Include source URLs for all claims that are material to the parent agent's next steps.
213
+ - Clearly distinguish between verified findings, inferred conclusions, and information that could not be verified.
214
+ - When sources conflict, report the conflict and cite the competing sources rather than selecting a winner without evidence.
215
+ `,li=m.prompt(m.section("role",ai),m.section("output",ci));function di(){return[m.createSystemMessage(li)]}function ui(e){const t=gt(e),o=r.createModel(e);return async(n,s)=>{try{return{isError:!1,data:{message:await r.streamText({model:o,system:di(),prompt:pi(n),tools:t,toolChoice:"required",stopWhen:r.hasToolCall("web_search"),temperature:0,abortSignal:s.abortSignal}).text}}}catch(i){return{isError:!0,error:{message:i.message}}}}}function pi(e){return m.buildMessageFromArray(["[URL]",e.url," ","[TASK]",e.task])}const ct={name:"web_search",definition:ii,createExecutor:e=>ui(e.model)},lt=[Je,Xe,Qe,Ze,et,it,at,qe,je,Fe,ct,De];function fi(e){return lt.some(t=>t.name===e)}function mi(e,t){for(const o of lt)e.register(mo(o,t[o.name]))}function dt(e){const t=e.startsWith("tool-")?e.slice(5):e;return fi(t)?t:void 0}function ut(e,t){return`${e}::${t}`}function K(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&e.type.startsWith("tool-")&&"toolCallId"in e}function J(e){return e.state==="approval-requested"&&e.approval?.id!=null}function pt(e){return e.state==="output-denied"?!0:e.state==="output-available"&&e.approval!=null}function ft(e){return e.parts.some(t=>K(t)&&J(t))}function hi(e){return e.some(ft)}function yi(e){return e.map(t=>ft(t)?{...t,parts:t.parts.map(Ii)}:t)}function Ii(e){return!K(e)||!J(e)?e:{...e,state:"output-denied",approval:{id:e.approval.id,approved:!1}}}function wi(e){const t=[],o=[];let n=0;const s={},i=()=>{o.length!==0&&(t.push({kind:"reasoning-block",key:`reasoning-${n++}`,items:[...o]}),o.length=0)},c=d=>{const l=d.trim();if(l.length===0)return;const u=o[o.length-1];u?.kind==="action"&&u.text===l||o.push({kind:"action",text:l})};for(let d=0;d<e.length;d++){const l=e[d];if(l.type==="step-start")continue;if(l.type==="text"){i();const p=l.text??"";p.length>0&&t.push({kind:"text",text:p,key:`text-${d}`,workflowRunHistoryIds:Object.fromEntries(Object.entries(s).map(([f,h])=>[f,[...h]]))});continue}if(!K(l))continue;const u=dt(l.type);if(u===wt){const p=bi(l);if(p){const f=ut(p.collectionId,p.workflowId),h=s[f]??=[];h.includes(p.historyId)||h.push(p.historyId)}}if(u===It){const p=vi(l.input);p&&c(p);continue}if(J(l)||pt(l)){i(),t.push({kind:"tool",part:l,key:`tool-${d}`});continue}}return i(),t}const gi=r.objectType({isError:r.literalType(!1),data:r.objectType({collectionId:r.stringType().min(1),workflowId:r.stringType().min(1),historyId:r.stringType().min(1)})});function bi(e){if(e.state!=="output-available")return;const t=gi.safeParse(e.output);return t.success?t.data.data:void 0}function vi(e){if(e==null||typeof e!="object")return;const t=e.message;if(typeof t!="string")return;const o=t.trim();return o.length>0?o:void 0}function Ti(e){return e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Si(e){return Ee.useQuery({queryKey:a.aiChatKeys.detail(e??""),queryFn:async()=>e?await a.AiChatServiceFactory.getInstance().findOne(e)??null:null,enabled:!!e})}function ki(e){return Ee.useInfiniteQuery({queryKey:a.aiChatKeys.infiniteHistory(e),initialPageParam:0,queryFn:async({pageParam:t})=>a.AiChatServiceFactory.getInstance().findRecentChatsPage({offset:t,limit:e}),getNextPageParam:t=>t.hasMore?t.nextOffset:void 0})}exports.AI_TAB=yt;exports.AiConversationContext=$e;exports.CHANGE_ACTION=k;exports.LOCATION_TO_FIELD=M;exports.TOOL_APPROVAL_ACTION_BUTTON_LABELS=ht;exports.TOOL_APPROVAL_BUTTON_LABELS=mt;exports.denyPendingApprovals=yi;exports.getApiMetadataBlueprint=De;exports.getContentItems=wi;exports.getCurrentTabBlueprint=qe;exports.getMessageTextContent=Ti;exports.hasPendingApprovalMessage=hi;exports.isApprovalRequested=J;exports.isApprovalSettled=pt;exports.isToolApprovalPart=K;exports.manageCollectionBlueprint=je;exports.manageEnvironmentBlueprint=Fe;exports.openOrFocusOperationEditorTab=Ke;exports.openTabBlueprint=Je;exports.operationListItemToCollectionOperation=Ve;exports.parseToolName=dt;exports.registerBuiltInTools=mi;exports.reportStatusBlueprint=Xe;exports.resolveOperation=ze;exports.resolveRemovalTarget=rt;exports.resolveStepOrDraftData=He;exports.runRequestBlueprint=Qe;exports.runWorkflowBlueprint=Ze;exports.searchBlueprint=et;exports.updateSecurityBlueprint=it;exports.updateStepBlueprint=at;exports.useAiChat=Si;exports.useAiConversationContext=yo;exports.useInfiniteChatHistory=ki;exports.webSearchBlueprint=ct;exports.workflowRunKey=ut;