| @@ -1,4 +1,22 @@ | ||
| 1 | +import { abilityDescriptors, getAbilities } from '@agent/abilities/abilities'; | |
| 2 | +import { findBlockEl, scopeOf } from '@agent/lib/block-el'; | |
| 3 | +import { buildBlockSchema } from '@agent/lib/block-schema'; | |
| 4 | +import { | |
| 5 | + classifyBlockEdit, | |
| 6 | + IGNORED_BLOCKS, | |
| 7 | +} from '@agent/lib/classify-block-edit'; | |
| 8 | +import { getClientTools } from '@agent/lib/client-tools'; | |
| 9 | +import { isExtendableHeader } from '@agent/lib/extendable-header'; | |
| 10 | +import { INSERTABLE_BLOCK_TYPES } from '@agent/lib/insertable-blocks'; | |
| 11 | +import { fetchLinkablePages } from '@agent/lib/linkable-pages'; | |
| 12 | +import { ensureCoreBlocksRegistered } from '@agent/lib/register-blocks'; | |
| 13 | +import { | |
| 14 | + buildSubtreeManifest, | |
| 15 | + buildSubtreeTree, | |
| 16 | + ownerAncestorFor, | |
| 17 | +} from '@agent/lib/subtree-manifest'; | |
| 18 | +import { activeCanvasStep } from '@agent/state/canvas'; | |
| 1 | 19 | import { useChatStore } from '@agent/state/chat'; |
| 2 | 20 | import { useGlobalStore } from '@agent/state/global'; |
| 3 | 21 | import { tools } from '@agent/workflows/workflows'; |
| 4 | 22 | import { AI_HOST } from '@constants'; |
| @@ -4,9 +22,74 @@ | ||
| 4 | 22 | import { AI_HOST } from '@constants'; |
| 5 | 23 | import { useQuickEditStore } from '@quick-edit/state/store'; |
| 6 | 24 | import { digest } from '@shared/api/digest'; |
| 7 | 25 | import { reqDataBasics } from '@shared/lib/data'; |
| 26 | +import { getBlockType } from '@wordpress/blocks'; | |
| 8 | 27 | |
| 28 | +// page-templates:v1 declares that find-blocks and stage-block reach into parts. | |
| 29 | +// block-duplicate:v1 declares that update-blocks applies the duplicate op. | |
| 30 | +export const API_FEATURES = [ | |
| 31 | + 'qa-tool', | |
| 32 | + 'page-templates:v1', | |
| 33 | + 'block-duplicate:v1', | |
| 34 | +]; | |
| 35 | + | |
| 36 | +const rootFor = (block) => | |
| 37 | + block?.id && block?.target | |
| 38 | + ? findBlockEl(block.id, document, scopeOf(block)) | |
| 39 | + : null; | |
| 40 | + | |
| 41 | +// If greater than 5 blocks the agent will narrow the scope | |
| 42 | +const EAGER_LOAD_MAX = 5; | |
| 43 | + | |
| 44 | +// The staged selection's attribute schemas, with the install's palette baked in. | |
| 45 | +export const blockSchemasFor = async (block) => { | |
| 46 | + const root = rootFor(block); | |
| 47 | + const { bucket } = classifyBlockEdit({ block, root }); | |
| 48 | + const owner = ownerAncestorFor(root); | |
| 49 | + const types = [ | |
| 50 | + ...new Set( | |
| 51 | + [ | |
| 52 | + ...(bucket === 'single' | |
| 53 | + ? [block.blockType] | |
| 54 | + : IGNORED_BLOCKS.has(block?.blockType) | |
| 55 | + ? [] | |
| 56 | + : buildSubtreeManifest(root).map(({ type }) => type)), | |
| 57 | + owner?.type, | |
| 58 | + ].filter(Boolean), | |
| 59 | + ), | |
| 60 | + ]; | |
| 61 | + if (!types.length || types.length > EAGER_LOAD_MAX) return []; | |
| 62 | + await ensureCoreBlocksRegistered(); | |
| 63 | + return types | |
| 64 | + .map((type) => ({ type, schema: buildBlockSchema(getBlockType(type)) })) | |
| 65 | + .filter(({ schema }) => schema); | |
| 66 | +}; | |
| 67 | + | |
| 68 | +// Without the site's addresses the model links a named page to "#". | |
| 69 | +const withLinkablePages = async (data) => { | |
| 70 | + if (!data.blockSchemas?.some(({ type }) => type === 'core/navigation-link')) { | |
| 71 | + return data; | |
| 72 | + } | |
| 73 | + const pages = await fetchLinkablePages(); | |
| 74 | + return { | |
| 75 | + ...data, | |
| 76 | + linkablePages: pages.map(({ title, url }) => ({ title, url })), | |
| 77 | + }; | |
| 78 | +}; | |
| 79 | + | |
| 80 | +// Only consumed for a multi-block edit; inert for single/combo. | |
| 81 | +export const subtreeManifestFor = (block) => { | |
| 82 | + const root = rootFor(block); | |
| 83 | + const owner = ownerAncestorFor(root); | |
| 84 | + const manifest = buildSubtreeManifest(root); | |
| 85 | + // buildSubtreeManifest treats the first entry as the selection's baseline. | |
| 86 | + return owner ? [...manifest, owner] : manifest; | |
| 87 | +}; | |
| 88 | + | |
| 89 | +// Selection hierarchy for the backend's positional edits. | |
| 90 | +export const subtreeTreeFor = (block) => buildSubtreeTree(rootFor(block)); | |
| 91 | + | |
| 9 | 92 | const extra = () => { |
| 10 | 93 | const { x, y, width, height } = useGlobalStore.getState(); |
| 11 | 94 | return { |
| 12 | 95 | userAgent: window?.navigator?.userAgent, |
| @@ -55,11 +138,13 @@ | ||
| 55 | 138 | }, |
| 56 | 139 | context, |
| 57 | 140 | agentContext: window.extAgentData.agentContext, |
| 58 | 141 | wpAbilities: window.extAgentData.wpAbilities ?? [], |
| 142 | + clientTools: getClientTools(), | |
| 59 | 143 | messages: messages.slice(-5), |
| 60 | 144 | hasBlock: Boolean(block), // todo: remove this |
| 61 | 145 | blockDetails: block, |
| 146 | + features: API_FEATURES, | |
| 62 | 147 | ...options, |
| 63 | 148 | extra: extra(), |
| 64 | 149 | }), |
| 65 | 150 | }); |
| @@ -65,12 +150,9 @@ | ||
| 65 | 150 | }); |
| 66 | 151 | |
| 67 | 152 | if (!response.ok) { |
| 68 | 153 | digest({ |
| 69 | - error: { | |
| 70 | - name: response.statusText, | |
| 71 | - messages: response.statusMessage, | |
| 72 | - }, | |
| 154 | + error: response, | |
| 73 | 155 | details: { source: 'agent', caller: 'pick-workflow' }, |
| 74 | 156 | }); |
| 75 | 157 | const error = new Error('Bad response from server'); |
| 76 | 158 | error.response = response; |
| @@ -80,8 +162,24 @@ | ||
| 80 | 162 | }; |
| 81 | 163 | |
| 82 | 164 | export const handleWorkflow = async ({ workflow, workflowData, options }) => { |
| 83 | 165 | const { getCurrentMessages, getMessagesFor } = useChatStore.getState(); |
| 166 | + const block = useQuickEditStore.getState().agentBlock; | |
| 167 | + const isBlockPatching = | |
| 168 | + workflow?.id === 'block-patching' || | |
| 169 | + (workflow?.id === 'select-block' && Boolean(block)); | |
| 170 | + // Spent once the manifest flows: patching never reads this workflow's inputs. | |
| 171 | + const { blockSearch: _spent, ...carried } = workflowData ?? {}; | |
| 172 | + // Schemas: pinned up front when the selection is small enough; otherwise | |
| 173 | + // empty until get-block-schemas fetches them into the same field. | |
| 174 | + const data = isBlockPatching | |
| 175 | + ? await withLinkablePages({ | |
| 176 | + ...carried, | |
| 177 | + blockSchemas: workflowData?.blockSchemas?.length | |
| 178 | + ? workflowData.blockSchemas | |
| 179 | + : await blockSchemasFor(block), | |
| 180 | + }) | |
| 181 | + : workflowData; | |
| 84 | 182 | const response = await fetch(`${AI_HOST}/api/agent/handle-workflow`, { |
| 85 | 183 | method: 'POST', |
| 86 | 184 | headers: { 'Content-Type': 'application/json' }, |
| 87 | 185 | signal: options?.signal, |
| @@ -87,15 +185,27 @@ | ||
| 87 | 185 | signal: options?.signal, |
| 88 | 186 | body: JSON.stringify({ |
| 89 | 187 | ...reqDataBasics, |
| 90 | 188 | workflow, |
| 91 | - workflowData, | |
| 189 | + workflowData: data, | |
| 92 | 190 | messages: getCurrentMessages(), |
| 93 | 191 | previousMessages: getMessagesFor(workflow?.id), |
| 94 | 192 | context: window.extAgentData.context, |
| 95 | 193 | agentContext: window.extAgentData.agentContext, |
| 96 | 194 | wpAbilities: window.extAgentData.wpAbilities ?? [], |
| 195 | + clientTools: getClientTools(), | |
| 196 | + // The manifest is the backend's block-patching signal — never send it | |
| 197 | + // for other workflows or they'd be routed into the patching handler. | |
| 198 | + blockManifest: isBlockPatching ? subtreeManifestFor(block) : [], | |
| 199 | + blockTree: isBlockPatching ? subtreeTreeFor(block) : [], | |
| 200 | + // The plugin owns the add catalog so old fielded builds are never | |
| 201 | + // offered a type they can't build. | |
| 202 | + insertableBlockTypes: isBlockPatching ? INSERTABLE_BLOCK_TYPES : [], | |
| 203 | + // The patcher writes dead CSS for these switches and claims success. | |
| 204 | + isExtendableHeader: | |
| 205 | + isBlockPatching && block?.template === 'header' && isExtendableHeader(), | |
| 97 | 206 | retry: options?.retry || false, |
| 207 | + features: API_FEATURES, | |
| 98 | 208 | extra: extra(), |
| 99 | 209 | }), |
| 100 | 210 | }); |
| 101 | 211 | |
| @@ -102,8 +212,37 @@ | ||
| 102 | 212 | if (!response.ok) throw new Error('Bad response from server'); |
| 103 | 213 | return await response.json(); |
| 104 | 214 | }; |
| 105 | 215 | |
| 216 | +export const handleCanvas = async ({ | |
| 217 | + toolId, | |
| 218 | + sessionId, | |
| 219 | + abilities, | |
| 220 | + options, | |
| 221 | +}) => { | |
| 222 | + const { getCurrentMessages, getMessagesFor } = useChatStore.getState(); | |
| 223 | + const { values } = activeCanvasStep(); | |
| 224 | + const response = await fetch(`${AI_HOST}/api/agent/handle-canvas`, { | |
| 225 | + method: 'POST', | |
| 226 | + headers: { 'Content-Type': 'application/json' }, | |
| 227 | + signal: options?.signal, | |
| 228 | + body: JSON.stringify({ | |
| 229 | + ...reqDataBasics, | |
| 230 | + toolId, | |
| 231 | + values, | |
| 232 | + abilities: abilityDescriptors(getAbilities(abilities)), | |
| 233 | + messages: getCurrentMessages(), | |
| 234 | + previousMessages: getMessagesFor(toolId), | |
| 235 | + context: window.extAgentData.context, | |
| 236 | + sessionId, | |
| 237 | + extra: extra(), | |
| 238 | + }), | |
| 239 | + }); | |
| 240 | + | |
| 241 | + if (!response.ok) throw new Error('Bad response from server'); | |
| 242 | + return await response.json(); | |
| 243 | +}; | |
| 244 | + | |
| 106 | 245 | export const rateAnswer = ({ answerId, rating }) => |
| 107 | 246 | fetch(`${AI_HOST}/api/agent/rate-workflow`, { |
| 108 | 247 | method: 'POST', |
| 109 | 248 | headers: { 'Content-Type': 'application/json' }, |
| @@ -114,10 +253,37 @@ | ||
| 114 | 253 | details: { source: 'agent', caller: 'rateAnswer', answerId, rating }, |
| 115 | 254 | }), |
| 116 | 255 | ); |
| 117 | 256 | |
| 118 | -export const callTool = async ({ tool, inputs }) => { | |
| 257 | +// An error with no message serializes to {}, which the model reads as an empty success. | |
| 258 | +const reasonFor = async (error) => { | |
| 259 | + // An unparsed apiFetch rejects with the Response, whose body holds the reason. | |
| 260 | + if (typeof error?.json === 'function') { | |
| 261 | + const body = await error.json().catch(() => null); | |
| 262 | + return body?.message ?? `The site answered ${error.status}.`; | |
| 263 | + } | |
| 264 | + | |
| 265 | + return ( | |
| 266 | + error?.error ?? error?.message ?? 'The ability failed without saying why.' | |
| 267 | + ); | |
| 268 | +}; | |
| 269 | + | |
| 270 | +// A throw would reach the model outside the tool's slot, reading as no result. | |
| 271 | +const runAbility = async (ability, inputs) => { | |
| 272 | + try { | |
| 273 | + return await ability.execute(inputs); | |
| 274 | + } catch (error) { | |
| 275 | + return { error: await reasonFor(error) }; | |
| 276 | + } | |
| 277 | +}; | |
| 278 | + | |
| 279 | +export const callTool = async ({ tool, inputs, abilities = [] }) => { | |
| 119 | 280 | if (tools[tool]) return await tools[tool](inputs); |
| 281 | + // Ours wins a name collision, so a duplicate WP ability can't change what runs. | |
| 282 | + const ours = | |
| 283 | + getAbilities(abilities).find(({ name }) => name === tool) ?? | |
| 284 | + getAbilities([tool])[0]; | |
| 285 | + if (ours) return { [tool]: await runAbility(ours, inputs) }; | |
| 120 | 286 | // Ability tools are named after the ability and have no file; the generic |
| 121 | 287 | // runner executes them. Key the result to its slot so the loop sees it filled. |
| 122 | 288 | const isAbility = (window.extAgentData?.wpAbilities ?? []).some((category) => |
| 123 | 289 | category.abilities?.some((ability) => ability.name === tool), |