ai-engineering-loop 1.6.0 → 1.8.1

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.
package/studio/app.js CHANGED
@@ -1,17 +1,118 @@
1
1
  'use strict';
2
2
 
3
+ const NODE_WIDTH = 224;
4
+ const NODE_PORT_Y = 54;
5
+ const MIN_ZOOM = 0.2;
6
+ const MAX_ZOOM = 2.5;
7
+ const byId = (id) => document.getElementById(id);
8
+ const escapeHtml = (value) => String(value ?? '').replace(
9
+ /[&<>"']/g,
10
+ (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]
11
+ );
12
+
3
13
  let catalog;
4
14
  let draft;
5
15
  let source;
16
+ let loadedRecipeId;
6
17
  let selectedId;
18
+ let selectedIds = new Set();
19
+ let selectedEdgeId;
7
20
  let liveTimer;
8
21
  let validationSequence = 0;
22
+ let positions = new Map();
23
+ let viewport = { x: 0, y: 0, scale: 1 };
24
+ let history = [];
25
+ let historyIndex = -1;
26
+ let interaction;
27
+ let connection;
28
+ let layoutTimer;
29
+ let spacePressed = false;
30
+ let pendingConnectionSource;
31
+ let runs = [];
32
+ let goal = { text: '', version: 1, frozen: false };
33
+ let activeRunId;
34
+ let pendingImport;
35
+ let hydratedGoalKey;
9
36
 
10
- const byId = (id) => document.getElementById(id);
11
- const escapeHtml = (value) => String(value ?? '').replace(
12
- /[&<>"']/g,
13
- (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]
14
- );
37
+ const DISPLAY_NAME_MAX = 80;
38
+ const ROOT_TYPES = new Set(['goal-contract', 'trigger']);
39
+
40
+ function displayName(item) {
41
+ return item?.displayName || item?.name || item?.id || 'Untitled';
42
+ }
43
+
44
+ function edgeId(from, to, index = 0) {
45
+ const suffix = index ? `-${index + 1}` : '';
46
+ const base = `edge-${from}-${to}`.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
47
+ return `${base.slice(0, 64 - suffix.length)}${suffix}`;
48
+ }
49
+
50
+ function uniqueEdgeId(from, to) {
51
+ let index = 0;
52
+ let candidate = edgeId(from, to, index);
53
+ const occupied = new Set((draft?.edges || []).map((edge) => edge.id));
54
+ while (occupied.has(candidate)) candidate = edgeId(from, to, ++index);
55
+ return candidate;
56
+ }
57
+
58
+ function normalizeDraftGraph(recipe) {
59
+ recipe.nodes = (recipe.nodes || []).map((node) => ({
60
+ ...node,
61
+ displayName: displayName(node)
62
+ }));
63
+ if (!Array.isArray(recipe.edges)) {
64
+ recipe.edges = [];
65
+ recipe.nodes.forEach((node) => {
66
+ (node.dependsOn || []).forEach((from, index) => {
67
+ recipe.edges.push({ id: edgeId(from, node.id, index), from, to: node.id });
68
+ });
69
+ });
70
+ }
71
+ const used = new Set();
72
+ recipe.edges = recipe.edges.map((edge, index) => {
73
+ let id = edge.id || edgeId(edge.from, edge.to, index);
74
+ while (used.has(id)) id = `${id}-${index + 1}`;
75
+ used.add(id);
76
+ return { ...edge, id };
77
+ });
78
+ syncDependencies(recipe);
79
+ return recipe;
80
+ }
81
+
82
+ function syncDependencies(recipe = draft) {
83
+ if (!recipe) return;
84
+ recipe.nodes.forEach((node) => {
85
+ node.dependsOn = recipe.edges
86
+ .filter((edge) => edge.to === node.id)
87
+ .map((edge) => edge.from);
88
+ });
89
+ }
90
+
91
+ function authoringRecipe(recipe = draft) {
92
+ const exported = structuredClone(recipe);
93
+ exported.nodes.forEach((node) => delete node.dependsOn);
94
+ return exported;
95
+ }
96
+
97
+ function validDisplayName(value) {
98
+ const name = String(value || '').trim();
99
+ if (!name) return 'Display Name is required.';
100
+ if (name.length > DISPLAY_NAME_MAX) return `Display Name must be ${DISPLAY_NAME_MAX} characters or fewer.`;
101
+ if (/[\u0000-\u001f\u007f]/.test(name)) return 'Display Name cannot contain control characters.';
102
+ return '';
103
+ }
104
+
105
+ function isInputTarget(target) {
106
+ return target instanceof Element && Boolean(target.closest('input,textarea,select,button,[contenteditable="true"],dialog'));
107
+ }
108
+
109
+ function csv(value) {
110
+ return String(value || '').split(',').map((item) => item.trim()).filter(Boolean);
111
+ }
112
+
113
+ function slug(value) {
114
+ return String(value || 'run').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 64) || 'run';
115
+ }
15
116
 
16
117
  async function api(url, options = {}) {
17
118
  const response = await fetch(url, {
@@ -31,40 +132,11 @@ function recipeSummary() {
31
132
  return catalog.recipes.find((recipe) => recipe.id === draft.id);
32
133
  }
33
134
 
34
- function renderRecipeDetails() {
35
- const existing = recipeSummary();
36
- byId('inspector-label').textContent = 'RECIPE INSPECTOR';
37
- byId('details').innerHTML = `
38
- <div class="source-line"><span>${source.toUpperCase()}</span><span>${draft.nodes.length} NODES</span></div>
39
- <label for="recipe-id">RECIPE ID</label>
40
- <input id="recipe-id" value="${escapeHtml(draft.id)}">
41
- <label for="recipe-version">VERSION</label>
42
- <input id="recipe-version" type="number" min="1" value="${escapeHtml(draft.version)}">
43
- <label for="recipe-description">DESCRIPTION</label>
44
- <textarea id="recipe-description">${escapeHtml(draft.description)}</textarea>
45
- <label for="recipe-modes">COMPATIBLE MODES</label>
46
- <select id="recipe-modes" multiple>
47
- ${['REPORT_ONLY', 'ASSISTED', 'UNATTENDED'].map((mode) => (
48
- `<option ${draft.compatibleModes.includes(mode) ? 'selected' : ''}>${mode}</option>`
49
- )).join('')}
50
- </select>
51
- ${existing?.source === 'builtin' ? '<p class="hint">Change the recipe ID to fork this protected preset.</p>' : ''}
52
- <button id="apply-recipe">APPLY METADATA</button>
53
- `;
54
- byId('apply-recipe').onclick = applyRecipeDetails;
135
+ function layoutPayload() {
136
+ return { viewport: { ...viewport }, positions: Object.fromEntries(positions) };
55
137
  }
56
138
 
57
- function applyRecipeDetails() {
58
- draft.id = byId('recipe-id').value.trim();
59
- draft.version = Number(byId('recipe-version').value);
60
- draft.description = byId('recipe-description').value.trim();
61
- draft.compatibleModes = [...byId('recipe-modes').selectedOptions].map((option) => option.value);
62
- renderGraph();
63
- renderRecipeDetails();
64
- validateDraft();
65
- }
66
-
67
- function graphPositions() {
139
+ function defaultGraphPositions() {
68
140
  const depths = new Map();
69
141
  const visiting = new Set();
70
142
  const depthFor = (node) => {
@@ -84,125 +156,425 @@ function graphPositions() {
84
156
  const depth = depthFor(node);
85
157
  const row = rows.get(depth) || 0;
86
158
  rows.set(depth, row + 1);
87
- return [node.id, { x: 90 + depth * 300, y: 125 + row * 150 }];
159
+ return [node.id, { x: 80 + depth * 270, y: 110 + row * 150 }];
88
160
  }));
89
161
  }
90
162
 
163
+ function ensurePositions() {
164
+ const defaults = defaultGraphPositions();
165
+ const ids = new Set(draft.nodes.map((node) => node.id));
166
+ for (const id of positions.keys()) {
167
+ if (!ids.has(id)) positions.delete(id);
168
+ }
169
+ for (const node of draft.nodes) {
170
+ if (!positions.has(node.id)) positions.set(node.id, defaults.get(node.id));
171
+ }
172
+ }
173
+
174
+ function applyViewport() {
175
+ byId('scene').style.transform = `translate(${viewport.x}px,${viewport.y}px) scale(${viewport.scale})`;
176
+ byId('canvas').style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
177
+ byId('canvas').style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
178
+ byId('zoom-level').textContent = `${Math.round(viewport.scale * 100)}%`;
179
+ }
180
+
181
+ function screenToWorld(clientX, clientY) {
182
+ const rect = byId('canvas').getBoundingClientRect();
183
+ return {
184
+ x: (clientX - rect.left - viewport.x) / viewport.scale,
185
+ y: (clientY - rect.top - viewport.y) / viewport.scale
186
+ };
187
+ }
188
+
189
+ function worldAtCanvasCenter() {
190
+ const rect = byId('canvas').getBoundingClientRect();
191
+ return screenToWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
192
+ }
193
+
194
+ function edgePath(from, to) {
195
+ const startX = from.x + NODE_WIDTH;
196
+ const startY = from.y + NODE_PORT_Y;
197
+ const endX = to.x;
198
+ const endY = to.y + NODE_PORT_Y;
199
+ const bend = Math.max(55, Math.abs(endX - startX) * 0.42);
200
+ return `M${startX} ${startY} C${startX + bend} ${startY},${endX - bend} ${endY},${endX} ${endY}`;
201
+ }
202
+
203
+ function stageLabel(node, index) {
204
+ const stages = {
205
+ 'goal-contract': 'STAGE 01',
206
+ maker: 'STAGES 02–04',
207
+ verification: 'STAGE 05',
208
+ 'devil-advocate': 'STAGE 06',
209
+ judge: 'STAGE 07',
210
+ approval: 'STAGE 08 GATE',
211
+ delivery: 'STAGE 08',
212
+ report: 'REPORT'
213
+ };
214
+ return stages[node.type] || `CUSTOM ${String(index + 1).padStart(2, '0')}`;
215
+ }
216
+
217
+ function renderEdges() {
218
+ const group = byId('edge-paths');
219
+ const controls = byId('edge-controls');
220
+ group.innerHTML = '';
221
+ controls.innerHTML = '';
222
+ if (!draft) return;
223
+ draft.edges.forEach((edge) => {
224
+ const from = positions.get(edge.from);
225
+ const to = positions.get(edge.to);
226
+ if (!from || !to) return;
227
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
228
+ path.setAttribute('d', edgePath(from, to));
229
+ path.setAttribute('class', `${catalog.live?.nodes?.[edge.from]?.status === 'RUNNING' ? 'edge active' : 'edge'}${selectedEdgeId === edge.id ? ' selected' : ''}`);
230
+ path.setAttribute('marker-end', 'url(#arrow)');
231
+ path.dataset.edgeId = edge.id;
232
+ group.append(path);
233
+
234
+ const midpoint = {
235
+ x: (from.x + NODE_WIDTH + to.x) / 2,
236
+ y: (from.y + to.y) / 2 + NODE_PORT_Y
237
+ };
238
+ const control = document.createElement('button');
239
+ control.className = `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
240
+ control.dataset.edgeId = edge.id;
241
+ control.style.left = `${midpoint.x}px`;
242
+ control.style.top = `${midpoint.y}px`;
243
+ control.title = `${displayName(draft.nodes.find((node) => node.id === edge.from))} → ${displayName(draft.nodes.find((node) => node.id === edge.to))}`;
244
+ control.setAttribute('aria-label', `Delete connection ${control.title}`);
245
+ control.textContent = '×';
246
+ control.onclick = (event) => {
247
+ event.stopPropagation();
248
+ deleteEdge(edge.id);
249
+ };
250
+ let hideTimer;
251
+ path.onpointerenter = () => {
252
+ clearTimeout(hideTimer);
253
+ control.classList.add('visible');
254
+ };
255
+ path.onpointerleave = () => {
256
+ hideTimer = setTimeout(() => control.classList.remove('visible'), 100);
257
+ };
258
+ control.onpointerenter = () => {
259
+ clearTimeout(hideTimer);
260
+ control.classList.add('visible');
261
+ };
262
+ control.onpointerleave = () => control.classList.remove('visible');
263
+ controls.append(control);
264
+ });
265
+ }
266
+
267
+ function nodeMarkup(node, index) {
268
+ const runtimeNode = catalog.live?.nodes?.[node.id];
269
+ const outgoing = draft.edges.some((edge) => edge.from === node.id);
270
+ const root = rootCandidates().length === 1 && rootCandidates()[0].id === node.id;
271
+ return `
272
+ <button class="port port-in" aria-label="Input for ${escapeHtml(node.id)}" tabindex="-1"></button>
273
+ <small>${escapeHtml(stageLabel(node, index))} / ${escapeHtml(node.type.toUpperCase())}</small>
274
+ <button class="node-title" title="Double-click to edit Display Name">${escapeHtml(displayName(node))}</button>
275
+ <span class="technical-id">${escapeHtml(node.id)}</span>
276
+ <span class="status">● ${escapeHtml(runtimeNode?.status || 'DRAFT')}</span>
277
+ ${runtimeNode?.activity ? `<p class="node-activity">${escapeHtml(runtimeNode.activity)}</p>` : ''}
278
+ <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
279
+ ${outgoing ? '' : `<button class="output-add" title="Add connected node" aria-label="Add node connected after ${escapeHtml(displayName(node))}">+</button>`}
280
+ ${root ? `<div class="execute-pod"><input class="task-input" aria-label="Task for this run" placeholder="Describe this run’s task" value="${escapeHtml(catalog.live?.run?.task || '')}"><button class="execute-trigger">${goal.frozen ? 'Execute' : 'Set Goal'}</button><span class="execute-hint">${goal.frozen ? 'Local runtime only' : 'Freeze Goal first'}</span></div>` : ''}
281
+ `;
282
+ }
283
+
91
284
  function renderGraph() {
92
- const positions = graphPositions();
285
+ ensurePositions();
93
286
  const container = byId('nodes');
94
287
  container.innerHTML = '';
95
288
  draft.nodes.forEach((node, index) => {
96
289
  const position = positions.get(node.id);
97
290
  const runtimeNode = catalog.live?.nodes?.[node.id];
98
291
  const element = document.createElement('article');
99
- element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${selectedId === node.id ? 'selected' : ''}`;
292
+ element.dataset.nodeId = node.id;
293
+ element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${selectedIds.has(node.id) ? 'selected' : ''}`;
100
294
  element.style.left = `${position.x}px`;
101
295
  element.style.top = `${position.y}px`;
102
- element.innerHTML = `
103
- <small>${String(index + 1).padStart(2, '0')} / ${escapeHtml(node.type.toUpperCase())}</small>
104
- <h3>${escapeHtml(node.id)}</h3>
105
- <span class="status">● ${runtimeNode?.status || 'DRAFT'}</span>
106
- ${runtimeNode?.activity ? `<p class="node-activity">${escapeHtml(runtimeNode.activity)}</p>` : ''}
107
- `;
108
- element.onclick = (event) => {
109
- event.stopPropagation();
110
- selectNode(node.id);
111
- };
296
+ element.innerHTML = nodeMarkup(node, index);
297
+ element.addEventListener('pointerdown', beginNodeInteraction);
298
+ element.querySelector('.port-out').addEventListener('pointerdown', beginConnection);
299
+ element.querySelector('.node-title').addEventListener('dblclick', beginInlineRename);
300
+ element.querySelector('.output-add')?.addEventListener('click', openContextualAdd);
301
+ element.querySelector('.execute-trigger')?.addEventListener('click', executeFromTrigger);
112
302
  container.append(element);
113
303
  });
114
- renderEdges(positions);
115
- byId('mode').textContent = `${draft.compatibleModes.join(' · ') || 'NO MODE'} / EDIT MODE`;
304
+ renderEdges();
305
+ applyViewport();
116
306
  }
117
307
 
118
- function renderEdges(positions) {
119
- const svg = byId('edges');
120
- const group = byId('edge-paths');
121
- const coordinates = [...positions.values()];
122
- const width = Math.max(1200, ...coordinates.map((position) => position.x + 300));
123
- const height = Math.max(900, ...coordinates.map((position) => position.y + 200));
124
- svg.style.width = `${width}px`;
125
- svg.style.height = `${height}px`;
126
- group.innerHTML = '';
127
- draft.nodes.forEach((node) => {
128
- for (const dependencyId of node.dependsOn || []) {
129
- const from = positions.get(dependencyId);
130
- const to = positions.get(node.id);
131
- if (!from || !to) continue;
132
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
133
- path.setAttribute(
134
- 'd',
135
- `M${from.x + 210} ${from.y + 52} C${from.x + 255} ${from.y + 52},${to.x - 45} ${to.y + 52},${to.x} ${to.y + 52}`
136
- );
137
- const active = catalog.live?.nodes?.[dependencyId]?.status === 'RUNNING';
138
- path.setAttribute('class', active ? 'edge active' : 'edge');
139
- path.setAttribute('marker-end', 'url(#arrow)');
140
- group.append(path);
308
+ function updateRuntimePresentation() {
309
+ if (!draft) return;
310
+ for (const element of document.querySelectorAll('.node')) {
311
+ const nodeId = element.dataset.nodeId;
312
+ const runtimeNode = catalog.live?.nodes?.[nodeId];
313
+ element.classList.remove('running', 'passed', 'failed', 'blocked', 'ready', 'pending', 'skipped');
314
+ if (runtimeNode?.status) element.classList.add(runtimeNode.status.toLowerCase());
315
+ element.querySelector('.status').textContent = `● ${runtimeNode?.status || 'DRAFT'}`;
316
+ const existingActivity = element.querySelector('.node-activity');
317
+ if (runtimeNode?.activity) {
318
+ if (existingActivity) existingActivity.textContent = runtimeNode.activity;
319
+ else element.querySelector('.status').insertAdjacentHTML('afterend', `<p class="node-activity">${escapeHtml(runtimeNode.activity)}</p>`);
320
+ } else {
321
+ existingActivity?.remove();
141
322
  }
323
+ }
324
+ renderEdges();
325
+ }
326
+
327
+ function updateSelection() {
328
+ document.querySelectorAll('.node').forEach((element) => {
329
+ element.classList.toggle('selected', selectedIds.has(element.dataset.nodeId));
142
330
  });
331
+ const actions = byId('selection-actions');
332
+ actions.hidden = selectedIds.size < 2;
333
+ byId('selection-count').textContent = `${selectedIds.size} nodes`;
143
334
  }
144
335
 
145
- function selectNode(nodeId) {
146
- selectedId = nodeId;
336
+ function renderRecipeDetails() {
337
+ const existing = recipeSummary();
338
+ byId('inspector-label').textContent = 'WORKFLOW';
339
+ byId('inspector-title').textContent = draft.id;
340
+ byId('inspector-title').contentEditable = 'false';
341
+ byId('inspector-title').onkeydown = null;
342
+ byId('inspector-title').onblur = null;
343
+ byId('details').innerHTML = `
344
+ <div class="source-line"><span>${escapeHtml(source.toUpperCase())}</span><span>${draft.nodes.length} NODES</span></div>
345
+ <label for="recipe-id">Name</label><input id="recipe-id" value="${escapeHtml(draft.id)}">
346
+ <label for="recipe-description">Description</label><textarea id="recipe-description">${escapeHtml(draft.description)}</textarea>
347
+ ${existing?.source === 'builtin' ? '<p class="hint">Saving creates a project copy. The built-in remains unchanged.</p>' : ''}
348
+ <details>
349
+ <summary>Advanced settings</summary>
350
+ <div class="settings-body">
351
+ <label for="recipe-version">Version</label><input id="recipe-version" type="number" min="1" value="${escapeHtml(draft.version)}">
352
+ <label for="recipe-modes">Run modes</label>
353
+ <select id="recipe-modes" multiple>
354
+ ${['REPORT_ONLY', 'ASSISTED', 'UNATTENDED'].map((mode) => `<option ${draft.compatibleModes.includes(mode) ? 'selected' : ''}>${mode}</option>`).join('')}
355
+ </select>
356
+ </div>
357
+ </details>
358
+ <button id="apply-recipe">Apply changes</button>
359
+ `;
360
+ byId('apply-recipe').onclick = applyRecipeDetails;
361
+ }
362
+
363
+ function selectNode(nodeId, { additive = false } = {}) {
147
364
  const node = draft.nodes.find((candidate) => candidate.id === nodeId);
365
+ if (!node) return;
366
+ if (additive) {
367
+ if (selectedIds.has(nodeId)) selectedIds.delete(nodeId);
368
+ else selectedIds.add(nodeId);
369
+ } else {
370
+ selectedIds = new Set([nodeId]);
371
+ }
372
+ selectedEdgeId = null;
373
+ selectedId = nodeId;
374
+ updateSelection();
148
375
  const runtimeNode = catalog.live?.nodes?.[nodeId];
149
- byId('inspector-label').textContent = 'NODE INSPECTOR';
376
+ byId('inspector-label').textContent = 'NODE';
377
+ byId('inspector-title').textContent = displayName(node);
378
+ byId('inspector-title').contentEditable = 'true';
379
+ byId('inspector-title').title = 'Edit Display Name';
380
+ byId('inspector-title').onkeydown = (event) => {
381
+ if (event.key === 'Enter') {
382
+ event.preventDefault();
383
+ event.currentTarget.blur();
384
+ } else if (event.key === 'Escape') {
385
+ event.currentTarget.textContent = displayName(node);
386
+ event.currentTarget.blur();
387
+ }
388
+ };
389
+ byId('inspector-title').onblur = (event) => applyDisplayName(node, event.currentTarget.textContent);
390
+ byId('inspector-panel').classList.add('open');
150
391
  byId('details').innerHTML = `
151
- <div class="source-line"><span>${escapeHtml(node.type.toUpperCase())}</span><span>${runtimeNode?.status || 'DRAFT'}</span></div>
152
- <label for="node-id">NODE ID</label>
153
- <input id="node-id" value="${escapeHtml(node.id)}">
154
- <label>TYPE</label>
155
- <input value="${escapeHtml(node.type)}" disabled>
156
- <label for="node-dependencies">DEPENDENCIES</label>
157
- <input id="node-dependencies" value="${escapeHtml((node.dependsOn || []).join(', '))}" placeholder="goal, verification">
158
- ${node.type === 'agent' ? `
159
- <label for="node-extra">ROLE</label><input id="node-extra" value="${escapeHtml(node.role || '')}">
160
- <label for="node-tokens">MAX TOKENS</label><input id="node-tokens" type="number" min="1" value="${escapeHtml(node.context?.maxTokens || '')}">
161
- ` : node.type === 'approval' ? `
162
- <label for="node-extra">APPROVAL MESSAGE</label><textarea id="node-extra">${escapeHtml(node.message || '')}</textarea>
163
- ` : node.type === 'condition' ? `
164
- <label for="condition-field">CONDITION FIELD</label>
165
- <select id="condition-field">${['run.mode', 'run.state', 'run.iteration', 'run.task'].map((field) => `<option ${node.expression?.field === field ? 'selected' : ''}>${field}</option>`).join('')}</select>
166
- <label for="condition-operator">OPERATOR</label>
167
- <select id="condition-operator">${['equals', 'notEquals', 'contains', 'exists', 'isEmpty', 'greaterThan', 'lessThan'].map((operator) => `<option ${node.expression?.operator === operator ? 'selected' : ''}>${operator}</option>`).join('')}</select>
168
- <label for="condition-value">VALUE</label><input id="condition-value" value="${escapeHtml(node.expression?.value ?? '')}">
169
- ` : ''}
170
- <div class="button-row"><button id="apply-node">APPLY NODE</button><button id="delete-node" class="danger">DELETE</button></div>
392
+ <div class="source-line"><span>${escapeHtml(node.type.toUpperCase())}</span><span>${escapeHtml(runtimeNode?.status || 'DRAFT')}</span></div>
393
+ <div id="name-validation" class="validation-message" aria-live="polite"></div>
394
+ <label for="node-id">Technical ID</label><input id="node-id" value="${escapeHtml(node.id)}" disabled>
395
+ ${node.type === 'delivery' ? deliveryAdapterControls() : ''}
396
+ <details>
397
+ <summary>Settings</summary>
398
+ <div class="settings-body">
399
+ <label>Type</label><input value="${escapeHtml(node.type)}" disabled>
400
+ <label for="node-dependencies">Inputs</label>
401
+ <input id="node-dependencies" value="${escapeHtml((node.dependsOn || []).join(', '))}" placeholder="Connect nodes on the canvas">
402
+ ${node.type === 'agent' ? `
403
+ <label for="node-extra">Role</label><input id="node-extra" value="${escapeHtml(node.role || '')}">
404
+ ${node.prompt != null ? customAgentFields(node) : ''}
405
+ <label for="node-tokens">Token limit</label><input id="node-tokens" type="number" min="1" value="${escapeHtml(node.context?.maxTokens || '')}">
406
+ ` : node.type === 'approval' ? `
407
+ <label for="node-extra">Approval message</label><textarea id="node-extra">${escapeHtml(node.message || '')}</textarea>
408
+ ` : node.type === 'condition' ? `
409
+ <label for="condition-field">Field</label>
410
+ <select id="condition-field">${['run.mode', 'run.state', 'run.iteration', 'run.task'].map((field) => `<option ${node.expression?.field === field ? 'selected' : ''}>${field}</option>`).join('')}</select>
411
+ <label for="condition-operator">Rule</label>
412
+ <select id="condition-operator">${['equals', 'notEquals', 'contains', 'exists', 'isEmpty', 'greaterThan', 'lessThan'].map((operator) => `<option ${node.expression?.operator === operator ? 'selected' : ''}>${operator}</option>`).join('')}</select>
413
+ <label for="condition-value">Value</label><input id="condition-value" value="${escapeHtml(node.expression?.value ?? '')}">
414
+ ` : ''}
415
+ </div>
416
+ </details>
417
+ <div class="button-row"><button id="apply-node">Apply</button>${catalog.nodeTypes.find((type) => type.type === node.type)?.builtIn ? '' : '<button id="duplicate-node">Duplicate</button>'}<button id="delete-node" class="danger">Delete</button></div>
171
418
  ${runtimeControls(node, runtimeNode)}
172
419
  `;
173
420
  byId('apply-node').onclick = applyNodeDetails;
421
+ if (byId('duplicate-node')) byId('duplicate-node').onclick = duplicateSelectedNode;
174
422
  byId('delete-node').onclick = deleteSelectedNode;
175
- bindRuntimeControls(node, runtimeNode);
423
+ if (byId('select-adapter')) byId('select-adapter').onclick = selectDeliveryAdapter;
424
+ if (byId('generate-adapter')) byId('generate-adapter').onclick = copyAdapterBuilderPrompt;
425
+ bindRuntimeControls(node);
426
+ }
427
+
428
+ function customAgentFields(node) {
429
+ return `
430
+ <label for="custom-node-prompt">Prompt</label><textarea id="custom-node-prompt">${escapeHtml(node.prompt || '')}</textarea>
431
+ <label for="custom-node-capabilities">Capabilities</label><input id="custom-node-capabilities" value="${escapeHtml((node.capabilityRefs || []).join(', '))}">
432
+ <label for="custom-node-mcp">MCP references</label><input id="custom-node-mcp" value="${escapeHtml((node.mcpRefs || []).join(', '))}">
433
+ <label for="custom-node-inputs">Input artifacts</label><input id="custom-node-inputs" value="${escapeHtml((node.inputArtifacts || []).join(', '))}">
434
+ <label for="custom-node-output">Output artifact</label><input id="custom-node-output" value="${escapeHtml(node.outputArtifacts?.[0]?.artifact || '')}">
435
+ <label for="custom-node-schema">Output schema</label><input id="custom-node-schema" value="${escapeHtml(node.outputArtifacts?.[0]?.schema || 'schemas/report.schema.json')}">
436
+ <label for="custom-node-timeout">Timeout (sec)</label><input id="custom-node-timeout" type="number" min="1" value="${escapeHtml(Math.round((node.timeoutMs || 900000) / 1000))}">
437
+ <label for="custom-node-retries">Maximum attempts</label><input id="custom-node-retries" type="number" min="1" value="${escapeHtml(node.retry?.maxAttempts ?? 2)}">
438
+ `;
439
+ }
440
+
441
+ function applyDisplayName(node, value) {
442
+ const error = validDisplayName(value);
443
+ const message = byId('name-validation');
444
+ if (error) {
445
+ if (message) message.textContent = error;
446
+ byId('inspector-title').textContent = displayName(node);
447
+ return false;
448
+ }
449
+ const next = value.trim();
450
+ if (next === displayName(node)) return true;
451
+ node.displayName = next;
452
+ captureHistory();
176
453
  renderGraph();
454
+ selectNode(node.id);
455
+ return true;
456
+ }
457
+
458
+ function beginInlineRename(event) {
459
+ event.preventDefault();
460
+ event.stopPropagation();
461
+ const node = draft.nodes.find((candidate) => candidate.id === event.currentTarget.closest('.node').dataset.nodeId);
462
+ const input = document.createElement('input');
463
+ input.className = 'inline-rename';
464
+ input.maxLength = DISPLAY_NAME_MAX;
465
+ input.value = displayName(node);
466
+ event.currentTarget.replaceWith(input);
467
+ input.focus();
468
+ input.select();
469
+ let saved = false;
470
+ const finish = () => {
471
+ if (saved) return;
472
+ saved = true;
473
+ const error = validDisplayName(input.value);
474
+ if (error) notify(error);
475
+ else if (input.value.trim() !== displayName(node)) {
476
+ node.displayName = input.value.trim();
477
+ captureHistory();
478
+ }
479
+ renderGraph();
480
+ selectNode(node.id);
481
+ };
482
+ input.onkeydown = (keyEvent) => {
483
+ if (keyEvent.key === 'Enter') input.blur();
484
+ if (keyEvent.key === 'Escape') {
485
+ input.value = displayName(node);
486
+ input.blur();
487
+ }
488
+ };
489
+ input.onblur = finish;
490
+ }
491
+
492
+ function deliveryAdapterControls() {
493
+ const current = catalog.adapters.current;
494
+ const options = [...catalog.adapters.types];
495
+ if (current && !options.includes(current)) options.push(current);
496
+ return `
497
+ <section class="adapter-controls">
498
+ <label for="delivery-adapter">Delivery adapter</label>
499
+ <select id="delivery-adapter">
500
+ ${options.map((type) => `<option ${type === (current || catalog.adapters.recommended) ? 'selected' : ''}>${escapeHtml(type)}</option>`).join('')}
501
+ </select>
502
+ <p class="hint">${current
503
+ ? `${escapeHtml(current)} is active for this project.`
504
+ : `Recommended: ${escapeHtml(catalog.adapters.recommended)}.`}</p>
505
+ <div class="button-row"><button id="select-adapter">Use adapter</button><button id="generate-adapter">Create custom</button></div>
506
+ </section>
507
+ `;
508
+ }
509
+
510
+ async function selectDeliveryAdapter() {
511
+ const type = byId('delivery-adapter').value;
512
+ if (!catalog.adapters.types.includes(type)) {
513
+ return notify('Custom adapters are changed through the guarded AI adapter builder.');
514
+ }
515
+ try {
516
+ await api('/api/adapter/select', { method: 'POST', body: JSON.stringify({ type }) });
517
+ catalog.adapters.current = type;
518
+ selectNode(selectedId);
519
+ notify(`${type} is now the project Stage 8 adapter.`);
520
+ } catch (error) {
521
+ notify(error.message);
522
+ }
523
+ }
524
+
525
+ async function copyAdapterBuilderPrompt() {
526
+ const prompt = [
527
+ 'Use the ai-engineering-loop generate-adapter skill for this repository.',
528
+ 'Ask Q1-Q5 before writing. Build a custom Stage 8 delivery adapter only.',
529
+ 'Preserve Stages 0-7, require Judge PASS, never store credentials, and use explicit approval for remote side effects.',
530
+ 'After validation, write .ai-engineering-loop/adapter.md so Workflow Studio discovers it.'
531
+ ].join(' ');
532
+ try {
533
+ await navigator.clipboard.writeText(prompt);
534
+ notify('Guarded custom-adapter prompt copied for your AI agent.');
535
+ } catch (error) {
536
+ notify(error.message);
537
+ }
177
538
  }
178
539
 
179
540
  function runtimeControls(node, runtimeNode) {
180
541
  if (!catalog.live || !runtimeNode) return '';
181
- const approve = node.type === 'approval' && runtimeNode.status === 'READY'
182
- ? '<button id="approve-node">APPROVE</button>'
183
- : '';
184
- const retry = ['FAILED', 'RUNNING'].includes(runtimeNode.status)
185
- ? '<button id="retry-node">RETRY</button>'
186
- : '';
542
+ const approve = node.type === 'approval' && runtimeNode.status === 'READY' ? '<button id="approve-node">APPROVE</button>' : '';
543
+ const retry = ['FAILED', 'RUNNING'].includes(runtimeNode.status) ? '<button id="retry-node">RETRY</button>' : '';
544
+ const custom = node.type === 'agent' && node.prompt && ['READY', 'RUNNING'].includes(runtimeNode.status) ? `
545
+ <p class="hint">This node is waiting for an external operator. Studio does not execute the agent independently.</p>
546
+ <button id="copy-agent-command">Copy command</button>
547
+ ${runtimeNode.status === 'READY'
548
+ ? '<button id="start-agent-node">Mark running</button>'
549
+ : '<label for="agent-evidence">Run-bound evidence JSON path</label><input id="agent-evidence" placeholder=".ai-engineering-loop/runs/…/agent-report.json"><button id="complete-agent-node">Complete with evidence</button>'}
550
+ ` : '';
187
551
  const activity = runtimeNode.status === 'RUNNING'
188
552
  ? '<label for="runtime-activity">SAFE ACTIVITY UPDATE</label><input id="runtime-activity" maxlength="240"><button id="send-activity">REPORT ACTIVITY</button>'
189
553
  : '';
190
- return approve || retry || activity
191
- ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${activity}<div class="button-row">${approve}${retry}</div></section>`
554
+ return approve || retry || activity || custom
555
+ ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${custom}${activity}<div class="button-row">${approve}${retry}</div></section>`
192
556
  : '';
193
557
  }
194
558
 
195
- function bindRuntimeControls(node, runtimeNode) {
559
+ function bindRuntimeControls(node) {
196
560
  const runId = catalog.live?.run?.runId;
197
561
  if (byId('approve-node')) byId('approve-node').onclick = () => mutateNode('/api/node/approve', { runId, nodeId: node.id });
198
562
  if (byId('retry-node')) byId('retry-node').onclick = () => mutateNode('/api/node/retry', { runId, nodeId: node.id });
199
563
  if (byId('send-activity')) {
200
564
  byId('send-activity').onclick = () => mutateNode('/api/node/activity', {
201
- runId,
202
- nodeId: node.id,
203
- message: byId('runtime-activity').value
565
+ runId, nodeId: node.id, message: byId('runtime-activity').value
204
566
  });
205
567
  }
568
+ if (byId('copy-agent-command')) byId('copy-agent-command').onclick = async () => {
569
+ await navigator.clipboard.writeText(`ai-engineering-loop node start ${node.id} --run ${runId}`);
570
+ notify('External operator command copied.');
571
+ };
572
+ if (byId('start-agent-node')) byId('start-agent-node').onclick = () => mutateNode('/api/node/start', { runId, nodeId: node.id });
573
+ if (byId('complete-agent-node')) byId('complete-agent-node').onclick = () => mutateNode('/api/node/complete', {
574
+ runId,
575
+ nodeId: node.id,
576
+ artifact: byId('agent-evidence').value.trim()
577
+ });
206
578
  }
207
579
 
208
580
  async function mutateNode(endpoint, body) {
@@ -215,17 +587,48 @@ async function mutateNode(endpoint, body) {
215
587
  }
216
588
  }
217
589
 
590
+ function applyRecipeDetails() {
591
+ draft.id = byId('recipe-id').value.trim();
592
+ draft.version = Number(byId('recipe-version').value);
593
+ draft.description = byId('recipe-description').value.trim();
594
+ draft.compatibleModes = [...byId('recipe-modes').selectedOptions].map((option) => option.value);
595
+ captureHistory();
596
+ renderGraph();
597
+ renderRecipeDetails();
598
+ validateDraft();
599
+ }
600
+
218
601
  function applyNodeDetails() {
219
602
  const node = draft.nodes.find((candidate) => candidate.id === selectedId);
220
- const previousId = node.id;
221
- node.id = byId('node-id').value.trim();
222
- node.dependsOn = byId('node-dependencies').value.split(',').map((value) => value.trim()).filter(Boolean);
223
- draft.nodes.forEach((candidate) => {
224
- candidate.dependsOn = (candidate.dependsOn || []).map((dependency) => dependency === previousId ? node.id : dependency);
603
+ if (!node) return;
604
+ if (!applyDisplayName(node, byId('inspector-title').textContent)) return;
605
+ const inputs = csv(byId('node-dependencies').value);
606
+ draft.edges = draft.edges.filter((edge) => edge.to !== node.id);
607
+ inputs.forEach((from, index) => {
608
+ if (from !== node.id && draft.nodes.some((candidate) => candidate.id === from)) {
609
+ draft.edges.push({ id: uniqueEdgeId(from, node.id), from, to: node.id });
610
+ }
225
611
  });
612
+ syncDependencies();
226
613
  if (node.type === 'agent') {
227
614
  node.role = byId('node-extra').value.trim();
228
615
  node.context = { ...(node.context || {}), maxTokens: Number(byId('node-tokens').value) };
616
+ if (node.prompt != null) {
617
+ node.prompt = byId('custom-node-prompt').value.trim();
618
+ node.capabilityRefs = csv(byId('custom-node-capabilities').value);
619
+ node.mcpRefs = csv(byId('custom-node-mcp').value);
620
+ node.inputArtifacts = csv(byId('custom-node-inputs').value);
621
+ node.outputArtifacts = [{
622
+ artifact: byId('custom-node-output').value.trim(),
623
+ schema: byId('custom-node-schema').value.trim()
624
+ }];
625
+ node.tokenLimit = Number(byId('node-tokens').value);
626
+ node.timeoutMs = Number(byId('custom-node-timeout').value) * 1000;
627
+ node.retry = {
628
+ maxAttempts: Number(byId('custom-node-retries').value),
629
+ backoffMs: node.retry?.backoffMs || 1000
630
+ };
631
+ }
229
632
  } else if (node.type === 'approval') {
230
633
  node.message = byId('node-extra').value.trim();
231
634
  } else if (node.type === 'condition') {
@@ -234,34 +637,53 @@ function applyNodeDetails() {
234
637
  const rawValue = byId('condition-value').value.trim();
235
638
  node.expression = { field, operator };
236
639
  if (!['exists', 'isEmpty'].includes(operator)) {
237
- node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator)
238
- ? Number(rawValue)
239
- : rawValue;
640
+ node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator) ? Number(rawValue) : rawValue;
240
641
  }
241
642
  }
242
- selectedId = node.id;
643
+ captureHistory();
243
644
  renderGraph();
244
645
  selectNode(node.id);
245
646
  validateDraft();
647
+ saveLayoutSoon();
246
648
  }
247
649
 
248
650
  function deleteSelectedNode() {
249
- if (!selectedId) return;
250
- draft.nodes = draft.nodes.filter((node) => node.id !== selectedId);
251
- draft.nodes.forEach((node) => {
252
- node.dependsOn = (node.dependsOn || []).filter((dependency) => dependency !== selectedId);
253
- });
651
+ if (!selectedIds.size) return;
652
+ const removed = new Set(selectedIds);
653
+ draft.nodes = draft.nodes.filter((node) => !removed.has(node.id));
654
+ draft.edges = draft.edges.filter((edge) => !removed.has(edge.from) && !removed.has(edge.to));
655
+ syncDependencies();
656
+ removed.forEach((id) => positions.delete(id));
254
657
  selectedId = null;
658
+ selectedIds.clear();
659
+ captureHistory();
255
660
  renderGraph();
256
661
  renderRecipeDetails();
662
+ byId('inspector-panel').classList.remove('open');
257
663
  validateDraft();
664
+ saveLayoutSoon();
258
665
  }
259
666
 
260
- function addNode(type) {
667
+ function deleteEdge(id) {
668
+ const before = draft.edges.length;
669
+ draft.edges = draft.edges.filter((edge) => edge.id !== id);
670
+ if (draft.edges.length === before) return;
671
+ syncDependencies();
672
+ selectedEdgeId = null;
673
+ captureHistory();
674
+ renderGraph();
675
+ validateDraft();
676
+ }
677
+
678
+ function uniqueNodeId(type) {
261
679
  let suffix = draft.nodes.length + 1;
262
680
  while (draft.nodes.some((node) => node.id === `${type}-${suffix}`)) suffix += 1;
263
- const id = `${type}-${suffix}`;
264
- const node = { id, type, dependsOn: [] };
681
+ return `${type}-${suffix}`;
682
+ }
683
+
684
+ function createNode(type, id = uniqueNodeId(type)) {
685
+ const label = catalog.nodeTypes.find((candidate) => candidate.type === type)?.label || type.replaceAll('-', ' ');
686
+ const node = { id, type, displayName: label, dependsOn: [] };
265
687
  if (type === 'agent') {
266
688
  Object.assign(node, {
267
689
  role: 'analyst',
@@ -273,23 +695,736 @@ function addNode(type) {
273
695
  } else if (type === 'condition') {
274
696
  node.expression = { field: 'run.mode', operator: 'equals', value: 'ASSISTED' };
275
697
  }
698
+ return node;
699
+ }
700
+
701
+ function addNode(type, position = worldAtCanvasCenter()) {
702
+ const node = createNode(type);
276
703
  draft.nodes.push(node);
277
- selectNode(id);
704
+ if (pendingConnectionSource) {
705
+ draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, node.id), from: pendingConnectionSource, to: node.id });
706
+ syncDependencies();
707
+ pendingConnectionSource = null;
708
+ }
709
+ positions.set(node.id, { x: position.x - NODE_WIDTH / 2, y: position.y - NODE_PORT_Y });
710
+ captureHistory();
711
+ renderGraph();
712
+ selectNode(node.id);
713
+ byId('library-panel').classList.remove('open');
714
+ validateDraft();
715
+ }
716
+
717
+ function duplicateSelectedNode() {
718
+ if (!selectedIds.size) return;
719
+ const originals = draft.nodes.filter((node) => selectedIds.has(node.id));
720
+ const mapping = new Map();
721
+ const clones = originals.map((original) => {
722
+ const clone = structuredClone(original);
723
+ clone.id = uniqueNodeId(original.type);
724
+ while (draft.nodes.some((node) => node.id === clone.id) || mapping.has(clone.id)) clone.id = `${clone.id}-copy`;
725
+ clone.displayName = `${displayName(original)} copy`;
726
+ if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
727
+ mapping.set(original.id, clone.id);
728
+ const originalPosition = positions.get(original.id);
729
+ positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
730
+ draft.nodes.push(clone);
731
+ return clone;
732
+ });
733
+ const copiedEdges = draft.edges.filter((edge) => mapping.has(edge.from) && mapping.has(edge.to)).map((edge) => ({
734
+ id: uniqueEdgeId(mapping.get(edge.from), mapping.get(edge.to)),
735
+ from: mapping.get(edge.from),
736
+ to: mapping.get(edge.to)
737
+ }));
738
+ draft.edges.push(...copiedEdges);
739
+ syncDependencies();
740
+ const cloneIds = new Set(clones.map((node) => node.id));
741
+ selectedId = clones.at(-1)?.id;
742
+ captureHistory();
743
+ renderGraph();
744
+ if (selectedId) selectNode(selectedId);
745
+ selectedIds = cloneIds;
746
+ updateSelection();
278
747
  validateDraft();
279
748
  }
280
749
 
750
+ function openContextualAdd(event) {
751
+ event.stopPropagation();
752
+ pendingConnectionSource = event.currentTarget.closest('.node').dataset.nodeId;
753
+ byId('library-panel').classList.add('open');
754
+ }
755
+
281
756
  function renderPalette() {
282
- const excluded = new Set(['goal-contract', 'maker', 'verification', 'devil-advocate', 'judge', 'delivery', 'report']);
283
- byId('palette').innerHTML = catalog.nodeTypes
284
- .filter((node) => node.executable && !excluded.has(node.type))
285
- .map((node) => `
286
- <button class="palette-item" data-node-type="${escapeHtml(node.type)}">
287
- <b>${escapeHtml(node.label)}</b><small>${escapeHtml(node.category.toUpperCase())}</small>
288
- </button>
289
- `).join('');
757
+ byId('palette').innerHTML = catalog.nodeTypes.filter((node) => node.executable).map((node) => `
758
+ <button class="palette-item" draggable="true" data-node-type="${escapeHtml(node.type)}">
759
+ <b>${escapeHtml(node.label)}</b><small>${escapeHtml(node.category.toUpperCase())}</small>
760
+ </button>
761
+ `).join('');
290
762
  document.querySelectorAll('[data-node-type]').forEach((button) => {
291
763
  button.onclick = () => addNode(button.dataset.nodeType);
764
+ button.ondragstart = (event) => {
765
+ event.dataTransfer.setData('application/x-ael-node-type', button.dataset.nodeType);
766
+ event.dataTransfer.effectAllowed = 'copy';
767
+ };
768
+ });
769
+ }
770
+
771
+ function beginNodeInteraction(event) {
772
+ if (event.button !== 0 || event.target.closest('.port,.output-add,.execute-pod,.node-title,.inline-rename')) return;
773
+ event.stopPropagation();
774
+ const element = event.currentTarget;
775
+ const nodeId = element.dataset.nodeId;
776
+ if (event.shiftKey) {
777
+ selectNode(nodeId, { additive: true });
778
+ return;
779
+ }
780
+ if (!selectedIds.has(nodeId)) selectNode(nodeId);
781
+ if (spacePressed) return beginPan(event);
782
+ const world = screenToWorld(event.clientX, event.clientY);
783
+ const position = positions.get(nodeId);
784
+ interaction = {
785
+ type: 'node',
786
+ pointerId: event.pointerId,
787
+ nodeId,
788
+ element,
789
+ offsetX: world.x - position.x,
790
+ offsetY: world.y - position.y,
791
+ origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }]))
792
+ };
793
+ element.classList.add('dragging');
794
+ element.setPointerCapture(event.pointerId);
795
+ }
796
+
797
+ function beginPan(event) {
798
+ if (event.button !== 0 && event.button !== 1) return;
799
+ event.preventDefault();
800
+ interaction = {
801
+ type: 'pan',
802
+ pointerId: event.pointerId,
803
+ startX: event.clientX,
804
+ startY: event.clientY,
805
+ viewportX: viewport.x,
806
+ viewportY: viewport.y
807
+ };
808
+ byId('canvas').setPointerCapture(event.pointerId);
809
+ }
810
+
811
+ function handlePointerMove(event) {
812
+ if (connection) {
813
+ const from = positions.get(connection.sourceId);
814
+ const target = screenToWorld(event.clientX, event.clientY);
815
+ const start = { x: from.x + NODE_WIDTH, y: from.y + NODE_PORT_Y };
816
+ const bend = Math.max(55, Math.abs(target.x - start.x) * 0.42);
817
+ byId('preview-edge').setAttribute('d', `M${start.x} ${start.y} C${start.x + bend} ${start.y},${target.x - bend} ${target.y},${target.x} ${target.y}`);
818
+ return;
819
+ }
820
+ if (!interaction || interaction.pointerId !== event.pointerId) return;
821
+ if (interaction.type === 'node') {
822
+ const world = screenToWorld(event.clientX, event.clientY);
823
+ const position = { x: world.x - interaction.offsetX, y: world.y - interaction.offsetY };
824
+ const origin = interaction.origins.get(interaction.nodeId);
825
+ const delta = { x: position.x - origin.x, y: position.y - origin.y };
826
+ interaction.origins.forEach((start, id) => {
827
+ const next = { x: start.x + delta.x, y: start.y + delta.y };
828
+ positions.set(id, next);
829
+ const nodeElement = document.querySelector(`.node[data-node-id="${CSS.escape(id)}"]`);
830
+ if (nodeElement) {
831
+ nodeElement.style.left = `${next.x}px`;
832
+ nodeElement.style.top = `${next.y}px`;
833
+ }
834
+ });
835
+ renderEdges();
836
+ } else if (interaction.type === 'lasso') {
837
+ updateLasso(event);
838
+ } else {
839
+ viewport.x = interaction.viewportX + event.clientX - interaction.startX;
840
+ viewport.y = interaction.viewportY + event.clientY - interaction.startY;
841
+ applyViewport();
842
+ }
843
+ }
844
+
845
+ function finishPointer(event) {
846
+ if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
847
+ if (!interaction || interaction.pointerId !== event.pointerId) return;
848
+ if (interaction.type === 'node') {
849
+ interaction.element.classList.remove('dragging');
850
+ captureHistory();
851
+ } else if (interaction.type === 'lasso') finishLasso();
852
+ interaction = null;
853
+ saveLayoutSoon();
854
+ }
855
+
856
+ function beginConnection(event) {
857
+ event.preventDefault();
858
+ event.stopPropagation();
859
+ const sourceId = event.currentTarget.closest('.node').dataset.nodeId;
860
+ connection = { sourceId, pointerId: event.pointerId };
861
+ byId('preview-edge').style.display = 'block';
862
+ event.currentTarget.setPointerCapture(event.pointerId);
863
+ }
864
+
865
+ function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
866
+ if (nodeId === targetId) return true;
867
+ if (seen.has(nodeId)) return false;
868
+ seen.add(nodeId);
869
+ const node = draft.nodes.find((candidate) => candidate.id === nodeId);
870
+ return (node?.dependsOn || []).some((dependencyId) => transitivelyDependsOn(dependencyId, targetId, seen));
871
+ }
872
+
873
+ function finishConnection(event) {
874
+ const sourceId = connection.sourceId;
875
+ connection = null;
876
+ byId('preview-edge').style.display = 'none';
877
+ const targetElement = document.elementFromPoint(event.clientX, event.clientY)?.closest('.node');
878
+ const targetId = targetElement?.dataset.nodeId;
879
+ if (!targetId || targetId === sourceId) return;
880
+ const target = draft.nodes.find((node) => node.id === targetId);
881
+ if (draft.edges.some((edge) => edge.from === sourceId && edge.to === targetId)) return notify('Nodes are already connected.');
882
+ if (transitivelyDependsOn(sourceId, targetId)) return notify('Connection rejected: it would create a cycle.');
883
+ draft.edges.push({ id: uniqueEdgeId(sourceId, targetId), from: sourceId, to: targetId });
884
+ syncDependencies();
885
+ captureHistory();
886
+ renderGraph();
887
+ selectNode(targetId);
888
+ validateDraft();
889
+ }
890
+
891
+ function beginLasso(event) {
892
+ const start = screenToWorld(event.clientX, event.clientY);
893
+ interaction = { type: 'lasso', pointerId: event.pointerId, start, current: start, additive: event.shiftKey };
894
+ const marquee = byId('selection-marquee');
895
+ marquee.style.display = 'block';
896
+ marquee.style.left = `${start.x}px`;
897
+ marquee.style.top = `${start.y}px`;
898
+ marquee.style.width = '0';
899
+ marquee.style.height = '0';
900
+ byId('canvas').setPointerCapture(event.pointerId);
901
+ }
902
+
903
+ function updateLasso(event) {
904
+ interaction.current = screenToWorld(event.clientX, event.clientY);
905
+ const left = Math.min(interaction.start.x, interaction.current.x);
906
+ const top = Math.min(interaction.start.y, interaction.current.y);
907
+ const right = Math.max(interaction.start.x, interaction.current.x);
908
+ const bottom = Math.max(interaction.start.y, interaction.current.y);
909
+ const marquee = byId('selection-marquee');
910
+ Object.assign(marquee.style, {
911
+ left: `${left}px`, top: `${top}px`, width: `${right - left}px`, height: `${bottom - top}px`
912
+ });
913
+ const next = interaction.additive ? new Set(selectedIds) : new Set();
914
+ positions.forEach((position, id) => {
915
+ if (position.x < right && position.x + NODE_WIDTH > left && position.y < bottom && position.y + 110 > top) next.add(id);
292
916
  });
917
+ selectedIds = next;
918
+ selectedId = [...next].at(-1) || null;
919
+ updateSelection();
920
+ }
921
+
922
+ function finishLasso() {
923
+ byId('selection-marquee').style.display = 'none';
924
+ const finalSelection = new Set(selectedIds);
925
+ if (selectedId) selectNode(selectedId);
926
+ selectedIds = finalSelection;
927
+ updateSelection();
928
+ }
929
+
930
+ function rootCandidates() {
931
+ if (!draft) return [];
932
+ const incoming = new Set(draft.edges.map((edge) => edge.to));
933
+ return draft.nodes.filter((node) => ROOT_TYPES.has(node.type) || !incoming.has(node.id));
934
+ }
935
+
936
+ async function executeFromTrigger(event) {
937
+ event.stopPropagation();
938
+ const candidates = rootCandidates();
939
+ if (candidates.length !== 1) return notify(`Execute requires exactly one trigger/root; found ${candidates.length}.`);
940
+ const task = event.currentTarget.closest('.execute-pod').querySelector('.task-input').value.trim();
941
+ if (task) byId('goal-task').value = task;
942
+ if (!goal.frozen || !activeRunId) {
943
+ byId('goal-dialog').showModal();
944
+ return notify('Save and freeze the Goal Contract before execution.');
945
+ }
946
+ try {
947
+ await api(`/api/runs/${encodeURIComponent(activeRunId)}/execute`, {
948
+ method: 'POST',
949
+ body: '{}'
950
+ });
951
+ notify('Local runtime started. External AI dispatch remains disabled.');
952
+ await refreshLive();
953
+ } catch (error) {
954
+ notify(error.message);
955
+ }
956
+ }
957
+
958
+ function parseGoalCriteria(value) {
959
+ return String(value || '').split('\n').map((line) => line.trim()).filter(Boolean).map((line, index) => {
960
+ const [statement, evidenceRequired, ...failures] = line.split('|').map((part) => part.trim());
961
+ return {
962
+ id: `AC-${index + 1}`,
963
+ statement,
964
+ evidenceRequired,
965
+ failureCases: failures.filter(Boolean)
966
+ };
967
+ });
968
+ }
969
+
970
+ function goalContractFromForm(runId) {
971
+ return {
972
+ schemaVersion: 1,
973
+ runId,
974
+ objective: byId('goal-text').value.trim(),
975
+ acceptanceCriteria: parseGoalCriteria(byId('goal-criteria').value)
976
+ };
977
+ }
978
+
979
+ function validateGoalForm(contract) {
980
+ if (!byId('goal-task').value.trim()) return 'Task is required.';
981
+ if (!contract.objective) return 'Goal objective is required.';
982
+ if (!contract.acceptanceCriteria.length) return 'Add at least one acceptance failure-table row.';
983
+ for (const criterion of contract.acceptanceCriteria) {
984
+ if (!criterion.statement || !criterion.evidenceRequired || !criterion.failureCases.length) {
985
+ return `${criterion.id} must contain statement | evidence required | failure case.`;
986
+ }
987
+ }
988
+ return '';
989
+ }
990
+
991
+ async function ensureStudioRun() {
992
+ if (activeRunId && catalog.live?.run && !['DELIVERED', 'REPORTED', 'ESCALATED'].includes(catalog.live.run.state)) {
993
+ return activeRunId;
994
+ }
995
+ const task = byId('goal-task').value.trim();
996
+ const created = await api('/api/runs', {
997
+ method: 'POST',
998
+ body: JSON.stringify({
999
+ task,
1000
+ displayName: byId('goal-run-name').value.trim(),
1001
+ recipeId: loadedRecipeId,
1002
+ mode: draft.compatibleModes.includes('ASSISTED') ? 'ASSISTED' : draft.compatibleModes[0]
1003
+ })
1004
+ });
1005
+ activeRunId = created.run.runId;
1006
+ await refreshLive();
1007
+ return activeRunId;
1008
+ }
1009
+
1010
+ async function saveGoalFromForm() {
1011
+ try {
1012
+ const provisional = goalContractFromForm(activeRunId || 'pending');
1013
+ const error = validateGoalForm(provisional);
1014
+ if (error) {
1015
+ byId('goal-validation').textContent = error;
1016
+ return null;
1017
+ }
1018
+ const runId = await ensureStudioRun();
1019
+ const contract = goalContractFromForm(runId);
1020
+ await api(`/api/runs/${encodeURIComponent(runId)}/goal`, {
1021
+ method: 'PUT',
1022
+ body: JSON.stringify({ goal: contract })
1023
+ });
1024
+ goal = { text: contract.objective, criteria: contract.acceptanceCriteria, version: goal.version, frozen: false };
1025
+ byId('goal-validation').textContent = '';
1026
+ notify('Goal draft saved. It is not frozen yet.');
1027
+ return contract;
1028
+ } catch (error) {
1029
+ byId('goal-validation').textContent = error.message;
1030
+ return null;
1031
+ }
1032
+ }
1033
+
1034
+ function renderGoalState() {
1035
+ const state = byId('goal-state');
1036
+ state.className = `goal-state ${goal.frozen ? 'frozen' : 'draft'}`;
1037
+ state.textContent = goal.frozen
1038
+ ? `Frozen · version ${goal.version} · editing locked`
1039
+ : `Draft · version ${goal.version} · editing allowed`;
1040
+ byId('goal-version').textContent = `V${goal.version}`;
1041
+ byId('goal-text').disabled = goal.frozen;
1042
+ byId('goal-criteria').disabled = goal.frozen;
1043
+ byId('goal-task').disabled = goal.frozen;
1044
+ byId('goal-run-name').disabled = goal.frozen;
1045
+ byId('save-goal').hidden = goal.frozen;
1046
+ byId('review-goal').hidden = goal.frozen;
1047
+ byId('confirm-freeze').hidden = true;
1048
+ byId('unfreeze-goal').hidden = !goal.frozen;
1049
+ }
1050
+
1051
+ async function reviewGoal() {
1052
+ const contract = await saveGoalFromForm();
1053
+ if (!contract) return;
1054
+ byId('goal-review').hidden = false;
1055
+ byId('goal-review').innerHTML = `
1056
+ <strong>${escapeHtml(contract.objective)}</strong>
1057
+ <p>${contract.acceptanceCriteria.length} numbered acceptance failure rows are ready.</p>
1058
+ `;
1059
+ byId('confirm-freeze').hidden = false;
1060
+ }
1061
+
1062
+ async function freezeGoalFromForm() {
1063
+ try {
1064
+ const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/freeze`, {
1065
+ method: 'POST',
1066
+ body: JSON.stringify({ actor: 'studio-user' })
1067
+ });
1068
+ catalog.live = catalog.live || {};
1069
+ catalog.live.run = result.run;
1070
+ goal = {
1071
+ text: byId('goal-text').value.trim(),
1072
+ criteria: parseGoalCriteria(byId('goal-criteria').value),
1073
+ version: result.run.goal.version,
1074
+ frozen: true
1075
+ };
1076
+ renderGoalState();
1077
+ renderGraph();
1078
+ notify('Goal frozen with an integrity-bound version.');
1079
+ } catch (error) {
1080
+ byId('goal-validation').textContent = error.message;
1081
+ }
1082
+ }
1083
+
1084
+ async function unfreezeGoalFromForm() {
1085
+ const fields = byId('unfreeze-fields');
1086
+ if (fields.hidden) {
1087
+ fields.hidden = false;
1088
+ byId('unfreeze-reason').focus();
1089
+ return;
1090
+ }
1091
+ try {
1092
+ const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/unfreeze`, {
1093
+ method: 'POST',
1094
+ body: JSON.stringify({ actor: 'studio-user', reason: byId('unfreeze-reason').value })
1095
+ });
1096
+ goal.frozen = false;
1097
+ goal.version = result.run.goal.version;
1098
+ fields.hidden = true;
1099
+ renderGoalState();
1100
+ renderGraph();
1101
+ notify('Goal unfrozen. Previous evidence remains bound to its prior version.');
1102
+ } catch (error) {
1103
+ byId('goal-validation').textContent = error.message;
1104
+ }
1105
+ }
1106
+
1107
+ function syncGoalFromLive() {
1108
+ const liveGoal = catalog.live?.run?.goal;
1109
+ activeRunId = catalog.live?.run?.runId || null;
1110
+ if (!liveGoal) return;
1111
+ goal.version = liveGoal.version || 1;
1112
+ goal.frozen = liveGoal.frozen === true;
1113
+ if (catalog.live.run.task) byId('goal-task').value = catalog.live.run.task;
1114
+ if (catalog.live.run.displayName) byId('goal-run-name').value = catalog.live.run.displayName;
1115
+ renderGoalState();
1116
+ }
1117
+
1118
+ async function hydrateGoalFromLive() {
1119
+ const run = catalog.live?.run;
1120
+ const artifactPath = run?.artifacts?.goalContract?.path;
1121
+ const key = `${run?.runId || ''}:${run?.goal?.version || 1}:${artifactPath || ''}`;
1122
+ if (!artifactPath || hydratedGoalKey === key) return;
1123
+ try {
1124
+ const result = await api(`/api/runs/${encodeURIComponent(run.runId)}/artifacts?path=${encodeURIComponent(artifactPath)}`);
1125
+ const contract = JSON.parse(result.artifact.content);
1126
+ byId('goal-text').value = contract.objective || '';
1127
+ byId('goal-criteria').value = (contract.acceptanceCriteria || []).map((criterion) => (
1128
+ `${criterion.statement} | ${criterion.evidenceRequired} | ${(criterion.failureCases || []).join(' | ')}`
1129
+ )).join('\n');
1130
+ goal.text = contract.objective || '';
1131
+ goal.criteria = contract.acceptanceCriteria || [];
1132
+ hydratedGoalKey = key;
1133
+ } catch {
1134
+ // The Goal remains inspectable through Run History if its bounded artifact cannot be hydrated.
1135
+ }
1136
+ }
1137
+
1138
+ async function loadRuns() {
1139
+ const query = byId('run-search').value.trim();
1140
+ try {
1141
+ const params = new URLSearchParams();
1142
+ if (query) params.set('q', query);
1143
+ if (byId('run-status').value) params.set('status', byId('run-status').value);
1144
+ if (byId('run-mode').value) params.set('mode', byId('run-mode').value);
1145
+ if (byId('run-from').value) params.set('from', `${byId('run-from').value}T00:00:00.000Z`);
1146
+ if (byId('run-to').value) params.set('to', `${byId('run-to').value}T23:59:59.999Z`);
1147
+ const result = await api(`/api/runs${params.size ? `?${params}` : ''}`);
1148
+ runs = result.runs;
1149
+ const list = byId('run-list');
1150
+ if (!runs.length) {
1151
+ list.innerHTML = '<div class="empty-state"><h2>No runs found</h2><p>Create a task from the workflow trigger.</p></div>';
1152
+ } else {
1153
+ list.innerHTML = runs.map((run) => `
1154
+ <button class="run-row" data-run-id="${escapeHtml(run.runId)}">
1155
+ <strong>${escapeHtml(run.displayName)}</strong>
1156
+ <span>${escapeHtml(run.status)} · ${escapeHtml(new Date(run.updatedAt).toLocaleString())}</span>
1157
+ <small>${escapeHtml(run.task)}</small>
1158
+ </button>
1159
+ `).join('');
1160
+ list.querySelectorAll('.run-row').forEach((button) => {
1161
+ button.onclick = () => loadRunDetail(button.dataset.runId);
1162
+ });
1163
+ }
1164
+ if (result.corrupt.length) {
1165
+ list.insertAdjacentHTML('beforeend', `<p class="validation-message">${result.corrupt.length} corrupt run record(s) were isolated.</p>`);
1166
+ }
1167
+ } catch (error) {
1168
+ byId('run-list').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1169
+ }
1170
+ }
1171
+
1172
+ async function loadRunDetail(runId) {
1173
+ try {
1174
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}`);
1175
+ const run = result.run;
1176
+ const artifacts = Object.values(run.artifacts || {});
1177
+ byId('run-detail').innerHTML = `
1178
+ <header><small>${escapeHtml(run.status)} · ${escapeHtml(run.mode)}</small><h2>${escapeHtml(run.displayName)}</h2><p>${escapeHtml(run.task)}</p></header>
1179
+ <div class="run-name-editor"><label for="run-name-edit">Display Name</label><input id="run-name-edit" maxlength="100" value="${escapeHtml(run.displayName)}"><button id="save-run-name">Rename</button></div>
1180
+ <dl><dt>Technical ID</dt><dd>${escapeHtml(run.runId)}</dd><dt>Goal</dt><dd>${run.goalFrozen ? `Frozen V${escapeHtml(run.goalVersion)}` : 'Not frozen'}</dd><dt>Evidence</dt><dd>${run.evidence.present ? 'Present' : 'Absent'}</dd></dl>
1181
+ <h3>Artifacts</h3>
1182
+ <div class="artifact-list">${artifacts.length ? artifacts.map((artifact) => (
1183
+ artifact?.path ? `<button data-artifact="${escapeHtml(artifact.path)}">${escapeHtml(artifact.path)}</button>` : ''
1184
+ )).join('') : '<p class="muted">No artifacts recorded.</p>'}</div>
1185
+ <h3>Decisions</h3>
1186
+ <div class="decision-list">${run.decisions?.length ? run.decisions.map((decision) => `<p><strong>${escapeHtml(decision.summary)}</strong><br><span class="muted">${escapeHtml(decision.rationale)}</span></p>`).join('') : '<p class="muted">No decisions recorded.</p>'}</div>
1187
+ <h3>Timeline</h3>
1188
+ <div class="timeline">${[...(run.history || []), ...(run.events || [])].sort((left, right) => String(right.at).localeCompare(String(left.at))).map((event) => `<p><time>${escapeHtml(event.at || '')}</time><strong>${escapeHtml(event.type || event.gate || event.to || 'event')}</strong>${escapeHtml(event.reason || event.changedNodes?.join(', ') || '')}</p>`).join('')}</div>
1189
+ <pre id="artifact-content" hidden></pre>
1190
+ `;
1191
+ byId('save-run-name').onclick = async () => {
1192
+ try {
1193
+ await api('/api/run/name', {
1194
+ method: 'PATCH',
1195
+ body: JSON.stringify({
1196
+ runId,
1197
+ displayName: byId('run-name-edit').value,
1198
+ actor: 'studio-user'
1199
+ })
1200
+ });
1201
+ await Promise.all([loadRuns(), loadRunDetail(runId)]);
1202
+ } catch (error) {
1203
+ notify(error.message);
1204
+ }
1205
+ };
1206
+ byId('run-detail').querySelectorAll('[data-artifact]').forEach((button) => {
1207
+ button.onclick = async () => {
1208
+ try {
1209
+ const artifactResult = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifact)}`);
1210
+ const output = byId('artifact-content');
1211
+ output.hidden = false;
1212
+ output.textContent = artifactResult.artifact.content;
1213
+ } catch (error) {
1214
+ notify(error.message);
1215
+ }
1216
+ };
1217
+ });
1218
+ } catch (error) {
1219
+ byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1220
+ }
1221
+ }
1222
+
1223
+ function showWorkspace(section) {
1224
+ const showingRuns = section === 'runs';
1225
+ byId('runs-view').hidden = !showingRuns;
1226
+ byId('canvas').hidden = showingRuns;
1227
+ byId('workflow-context').hidden = showingRuns;
1228
+ byId('review').hidden = showingRuns;
1229
+ byId('show-runs').classList.toggle('active', showingRuns);
1230
+ byId('show-runs').setAttribute('aria-current', showingRuns ? 'page' : 'false');
1231
+ byId('show-workflows').classList.toggle('active', !showingRuns);
1232
+ byId('show-workflows').setAttribute('aria-current', showingRuns ? 'false' : 'page');
1233
+ if (showingRuns) loadRuns();
1234
+ }
1235
+
1236
+ async function previewImport() {
1237
+ try {
1238
+ const importedRecipe = JSON.parse(byId('import-source').value);
1239
+ const result = await api('/api/import/preview', {
1240
+ method: 'POST',
1241
+ body: JSON.stringify({ existingRecipe: draft, importedRecipe, operation: 'merge' })
1242
+ });
1243
+ pendingImport = { importedRecipe, mergePlan: result.plan };
1244
+ byId('import-preview').innerHTML = `
1245
+ <strong>${escapeHtml(importedRecipe.id || 'Imported workflow')}</strong>
1246
+ <p>${escapeHtml(importedRecipe.nodes?.length || 0)} nodes · ${escapeHtml(importedRecipe.edges?.length || 0)} explicit Edges</p>
1247
+ <p>${Object.values(result.plan.nodeIdMap).filter((id, index) => id !== Object.keys(result.plan.nodeIdMap)[index]).length} node ID conflict(s) will be renamed.</p>
1248
+ `;
1249
+ byId('import-choices').hidden = false;
1250
+ } catch (error) {
1251
+ pendingImport = null;
1252
+ byId('import-choices').hidden = true;
1253
+ byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1254
+ }
1255
+ }
1256
+
1257
+ async function applyImport(operation) {
1258
+ if (!pendingImport) return;
1259
+ try {
1260
+ const plan = operation === 'merge'
1261
+ ? pendingImport.mergePlan
1262
+ : { operation: 'replace', nodeIdMap: {}, edgeIdMap: {} };
1263
+ const result = await api('/api/import/apply', {
1264
+ method: 'POST',
1265
+ body: JSON.stringify({
1266
+ existingRecipe: draft,
1267
+ importedRecipe: pendingImport.importedRecipe,
1268
+ plan
1269
+ })
1270
+ });
1271
+ draft = normalizeDraftGraph(structuredClone(result.recipe));
1272
+ positions = new Map();
1273
+ ensurePositions();
1274
+ selectedIds.clear();
1275
+ selectedId = null;
1276
+ captureHistory();
1277
+ renderGraph();
1278
+ renderRecipeDetails();
1279
+ validateDraft();
1280
+ byId('import-dialog').close();
1281
+ notify(`${operation === 'merge' ? 'Merged' : 'Replaced'} canvas from validated JSON.`);
1282
+ } catch (error) {
1283
+ byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1284
+ }
1285
+ }
1286
+
1287
+ function exportWorkflowJson() {
1288
+ const blob = new Blob([`${JSON.stringify(authoringRecipe(), null, 2)}\n`], { type: 'application/json' });
1289
+ const link = document.createElement('a');
1290
+ link.href = URL.createObjectURL(blob);
1291
+ link.download = `${draft.id}.workflow.json`;
1292
+ link.click();
1293
+ URL.revokeObjectURL(link.href);
1294
+ }
1295
+
1296
+ function createCustomAgentFromForm(event) {
1297
+ event.preventDefault();
1298
+ const id = uniqueNodeId('agent');
1299
+ const name = byId('custom-name').value.trim();
1300
+ const prompt = byId('custom-prompt').value.trim();
1301
+ const error = validDisplayName(name);
1302
+ if (error || !prompt) return notify(error || 'Custom Agent prompt is required.');
1303
+ const artifact = byId('custom-output').value.trim() || `${id}-report`;
1304
+ const node = {
1305
+ id,
1306
+ type: 'agent',
1307
+ displayName: name,
1308
+ prompt,
1309
+ capabilityRefs: csv(byId('custom-capabilities').value),
1310
+ mcpRefs: csv(byId('custom-mcp').value),
1311
+ inputArtifacts: csv(byId('custom-inputs').value),
1312
+ outputArtifacts: [{ artifact, schema: 'schemas/report.schema.json' }],
1313
+ tokenLimit: Number(byId('custom-tokens').value),
1314
+ timeoutMs: Number(byId('custom-timeout').value) * 1000,
1315
+ retry: { maxAttempts: Number(byId('custom-retries').value), backoffMs: 1000 }
1316
+ };
1317
+ draft.nodes.push(node);
1318
+ if (pendingConnectionSource) {
1319
+ draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, id), from: pendingConnectionSource, to: id });
1320
+ pendingConnectionSource = null;
1321
+ }
1322
+ syncDependencies();
1323
+ const center = worldAtCanvasCenter();
1324
+ positions.set(id, { x: center.x - NODE_WIDTH / 2, y: center.y - NODE_PORT_Y });
1325
+ captureHistory();
1326
+ renderGraph();
1327
+ selectNode(id);
1328
+ validateDraft();
1329
+ byId('custom-dialog').close();
1330
+ }
1331
+
1332
+ function zoomAt(nextScale, clientX, clientY) {
1333
+ const scale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));
1334
+ const rect = byId('canvas').getBoundingClientRect();
1335
+ const x = clientX ?? rect.left + rect.width / 2;
1336
+ const y = clientY ?? rect.top + rect.height / 2;
1337
+ const world = screenToWorld(x, y);
1338
+ viewport.scale = scale;
1339
+ viewport.x = x - rect.left - world.x * scale;
1340
+ viewport.y = y - rect.top - world.y * scale;
1341
+ applyViewport();
1342
+ saveLayoutSoon();
1343
+ }
1344
+
1345
+ function handleWheel(event) {
1346
+ event.preventDefault();
1347
+ if (event.ctrlKey || event.metaKey) {
1348
+ zoomAt(viewport.scale * Math.exp(-event.deltaY * 0.002), event.clientX, event.clientY);
1349
+ } else {
1350
+ viewport.x -= event.deltaX;
1351
+ viewport.y -= event.deltaY;
1352
+ applyViewport();
1353
+ saveLayoutSoon();
1354
+ }
1355
+ }
1356
+
1357
+ function autoLayout({ record = true } = {}) {
1358
+ positions = defaultGraphPositions();
1359
+ renderGraph();
1360
+ fitView();
1361
+ if (record) captureHistory();
1362
+ saveLayoutSoon();
1363
+ }
1364
+
1365
+ function fitView() {
1366
+ ensurePositions();
1367
+ if (!positions.size) return;
1368
+ const rect = byId('canvas').getBoundingClientRect();
1369
+ const values = [...positions.values()];
1370
+ const minX = Math.min(...values.map((position) => position.x));
1371
+ const minY = Math.min(...values.map((position) => position.y));
1372
+ const maxX = Math.max(...values.map((position) => position.x + NODE_WIDTH));
1373
+ const maxY = Math.max(...values.map((position) => position.y + 140));
1374
+ const padding = 100;
1375
+ viewport.scale = Math.max(MIN_ZOOM, Math.min(1.35, Math.min(
1376
+ (rect.width - padding * 2) / Math.max(1, maxX - minX),
1377
+ (rect.height - padding * 2) / Math.max(1, maxY - minY)
1378
+ )));
1379
+ viewport.x = (rect.width - (maxX - minX) * viewport.scale) / 2 - minX * viewport.scale;
1380
+ viewport.y = (rect.height - (maxY - minY) * viewport.scale) / 2 - minY * viewport.scale;
1381
+ applyViewport();
1382
+ saveLayoutSoon();
1383
+ }
1384
+
1385
+ function captureHistory({ reset = false } = {}) {
1386
+ const snapshot = JSON.stringify({ draft, positions: Object.fromEntries(positions) });
1387
+ if (reset) {
1388
+ history = [snapshot];
1389
+ historyIndex = 0;
1390
+ } else if (history[historyIndex] !== snapshot) {
1391
+ history = history.slice(0, historyIndex + 1);
1392
+ history.push(snapshot);
1393
+ historyIndex = history.length - 1;
1394
+ }
1395
+ byId('undo').disabled = historyIndex <= 0;
1396
+ byId('redo').disabled = historyIndex >= history.length - 1;
1397
+ }
1398
+
1399
+ function restoreHistory(index) {
1400
+ if (index < 0 || index >= history.length) return;
1401
+ historyIndex = index;
1402
+ const snapshot = JSON.parse(history[index]);
1403
+ draft = snapshot.draft;
1404
+ positions = new Map(Object.entries(snapshot.positions));
1405
+ if (!draft.nodes.some((node) => node.id === selectedId)) selectedId = null;
1406
+ renderGraph();
1407
+ if (selectedId) selectNode(selectedId);
1408
+ else renderRecipeDetails();
1409
+ validateDraft();
1410
+ saveLayoutSoon();
1411
+ byId('undo').disabled = historyIndex <= 0;
1412
+ byId('redo').disabled = historyIndex >= history.length - 1;
1413
+ }
1414
+
1415
+ function saveLayoutSoon() {
1416
+ clearTimeout(layoutTimer);
1417
+ if (!loadedRecipeId || draft.id !== loadedRecipeId) return;
1418
+ layoutTimer = setTimeout(async () => {
1419
+ try {
1420
+ await api('/api/layout', {
1421
+ method: 'PUT',
1422
+ body: JSON.stringify({ recipeId: loadedRecipeId, layout: layoutPayload() })
1423
+ });
1424
+ } catch {
1425
+ // Canvas work remains in memory and install still submits the layout.
1426
+ }
1427
+ }, 350);
293
1428
  }
294
1429
 
295
1430
  async function validateDraft() {
@@ -319,20 +1454,21 @@ async function validateDraft() {
319
1454
  function renderLive() {
320
1455
  const live = catalog.live;
321
1456
  if (!live) {
1457
+ byId('run-summary').textContent = 'No active run';
322
1458
  byId('active-stage').textContent = 'No active run';
323
1459
  byId('activity').textContent = 'Waiting for a recipe-bound workflow.';
324
1460
  byId('events').innerHTML = '';
325
1461
  byId('budget').textContent = '—';
326
1462
  byId('meter').style.width = '0';
1463
+ updateRuntimePresentation();
327
1464
  return;
328
1465
  }
329
1466
  const active = live.plan.nodes.find((node) => live.nodes[node.id].status === 'RUNNING')
330
1467
  || live.plan.nodes.find((node) => live.nodes[node.id].status === 'READY');
331
1468
  const runtimeNode = active ? live.nodes[active.id] : null;
1469
+ byId('run-summary').textContent = active ? `${active.id} · ${runtimeNode.status}` : `Run ${live.run.state}`;
332
1470
  byId('active-stage').textContent = active?.id || 'Run complete';
333
- byId('activity').textContent = active
334
- ? runtimeNode.activity || `${runtimeNode.status} · attempt ${runtimeNode.attempts}`
335
- : `Final state: ${live.run.state}`;
1471
+ byId('activity').textContent = active ? runtimeNode.activity || `${runtimeNode.status} · attempt ${runtimeNode.attempts}` : `Final state: ${live.run.state}`;
336
1472
  const spent = live.budget.spentThisRun;
337
1473
  const limit = live.budget.perRunTokenLimit;
338
1474
  byId('meter').style.width = `${Math.min(100, limit ? (spent / limit) * 100 : 0)}%`;
@@ -342,13 +1478,15 @@ function renderLive() {
342
1478
  ${escapeHtml(event.at.slice(11, 19))} · ${escapeHtml(event.type)} · ${escapeHtml(event.changedNodes.join(', '))}
343
1479
  </p>
344
1480
  `).join('');
345
- renderGraph();
1481
+ updateRuntimePresentation();
346
1482
  }
347
1483
 
348
1484
  async function refreshLive() {
349
1485
  try {
350
1486
  const result = await api('/api/live');
351
1487
  catalog.live = result.live;
1488
+ syncGoalFromLive();
1489
+ await hydrateGoalFromLive();
352
1490
  renderLive();
353
1491
  } catch {
354
1492
  // A transient refresh failure must not discard the draft.
@@ -356,12 +1494,25 @@ async function refreshLive() {
356
1494
  }
357
1495
 
358
1496
  async function loadRecipe() {
359
- const result = await api(`/api/recipe?id=${encodeURIComponent(byId('recipe').value)}`);
360
- draft = structuredClone(result.recipe);
1497
+ const id = byId('recipe').value;
1498
+ const [result, saved] = await Promise.all([
1499
+ api(`/api/recipe?id=${encodeURIComponent(id)}`),
1500
+ api(`/api/layout?id=${encodeURIComponent(id)}`)
1501
+ ]);
1502
+ draft = normalizeDraftGraph(structuredClone(result.recipe));
361
1503
  source = result.source;
1504
+ loadedRecipeId = draft.id;
362
1505
  selectedId = null;
1506
+ selectedIds.clear();
1507
+ selectedEdgeId = null;
1508
+ byId('inspector-panel').classList.remove('open');
1509
+ positions = new Map(Object.entries(saved.layout?.positions || {}));
1510
+ ensurePositions();
1511
+ viewport = saved.layout?.viewport || { x: 0, y: 0, scale: 1 };
363
1512
  renderGraph();
1513
+ if (!saved.layout || (draft.nodes.length <= 12 && viewport.scale < 0.45)) fitView();
364
1514
  renderRecipeDetails();
1515
+ captureHistory({ reset: true });
365
1516
  validateDraft();
366
1517
  }
367
1518
 
@@ -373,22 +1524,83 @@ async function refreshCatalog(selectedRecipe) {
373
1524
  )).join('');
374
1525
  if (selectedRecipe && catalog.recipes.some((recipe) => recipe.id === selectedRecipe)) selector.value = selectedRecipe;
375
1526
  renderPalette();
1527
+ syncGoalFromLive();
376
1528
  renderLive();
377
1529
  }
378
1530
 
379
- async function initialize() {
380
- await refreshCatalog();
381
- byId('recipe').onchange = loadRecipe;
382
- byId('canvas').onclick = () => {
383
- selectedId = null;
384
- renderGraph();
385
- renderRecipeDetails();
386
- };
387
- await loadRecipe();
388
- clearInterval(liveTimer);
389
- liveTimer = setInterval(refreshLive, 1800);
1531
+ function bindCanvas() {
1532
+ const canvas = byId('canvas');
1533
+ canvas.addEventListener('pointerdown', (event) => {
1534
+ if (event.target === canvas || event.target === byId('scene') || event.target === byId('nodes') || event.target === byId('edges')) {
1535
+ selectedId = null;
1536
+ if (!event.shiftKey) selectedIds.clear();
1537
+ updateSelection();
1538
+ renderRecipeDetails();
1539
+ byId('inspector-panel').classList.remove('open');
1540
+ if (event.button === 1 || spacePressed) beginPan(event);
1541
+ else if (event.button === 0) beginLasso(event);
1542
+ }
1543
+ });
1544
+ canvas.addEventListener('pointermove', handlePointerMove);
1545
+ canvas.addEventListener('pointerup', finishPointer);
1546
+ canvas.addEventListener('pointercancel', finishPointer);
1547
+ canvas.addEventListener('wheel', handleWheel, { passive: false });
1548
+ canvas.addEventListener('dragover', (event) => {
1549
+ if (!event.dataTransfer.types.includes('application/x-ael-node-type')) return;
1550
+ event.preventDefault();
1551
+ canvas.classList.add('drop-ready');
1552
+ });
1553
+ canvas.addEventListener('dragleave', () => canvas.classList.remove('drop-ready'));
1554
+ canvas.addEventListener('drop', (event) => {
1555
+ event.preventDefault();
1556
+ canvas.classList.remove('drop-ready');
1557
+ const type = event.dataTransfer.getData('application/x-ael-node-type');
1558
+ if (type) addNode(type, screenToWorld(event.clientX, event.clientY));
1559
+ });
1560
+ byId('auto-layout').onclick = () => autoLayout();
1561
+ byId('fit-view').onclick = fitView;
1562
+ byId('fit-view-rail').onclick = fitView;
1563
+ byId('zoom-in').onclick = () => zoomAt(viewport.scale * 1.2);
1564
+ byId('zoom-out').onclick = () => zoomAt(viewport.scale / 1.2);
1565
+ byId('undo').onclick = () => restoreHistory(historyIndex - 1);
1566
+ byId('redo').onclick = () => restoreHistory(historyIndex + 1);
390
1567
  }
391
1568
 
1569
+ function editableTarget(target) {
1570
+ return target.matches('input,textarea,select,[contenteditable="true"]');
1571
+ }
1572
+
1573
+ document.addEventListener('keydown', (event) => {
1574
+ if (event.code === 'Space' && !editableTarget(event.target)) {
1575
+ spacePressed = true;
1576
+ event.preventDefault();
1577
+ }
1578
+ if (editableTarget(event.target)) return;
1579
+ const modifier = event.ctrlKey || event.metaKey;
1580
+ if (modifier && event.key.toLowerCase() === 'z') {
1581
+ event.preventDefault();
1582
+ restoreHistory(historyIndex + (event.shiftKey ? 1 : -1));
1583
+ } else if (modifier && event.key.toLowerCase() === 'y') {
1584
+ event.preventDefault();
1585
+ restoreHistory(historyIndex + 1);
1586
+ } else if (modifier && event.key.toLowerCase() === 'a' && byId('canvas').contains(document.activeElement)) {
1587
+ event.preventDefault();
1588
+ selectedIds = new Set(draft.nodes.map((node) => node.id));
1589
+ selectedId = [...selectedIds].at(-1) || null;
1590
+ updateSelection();
1591
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId) {
1592
+ event.preventDefault();
1593
+ deleteEdge(selectedEdgeId);
1594
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedIds.size) {
1595
+ event.preventDefault();
1596
+ deleteSelectedNode();
1597
+ }
1598
+ });
1599
+ document.addEventListener('keyup', (event) => {
1600
+ if (event.code === 'Space') spacePressed = false;
1601
+ });
1602
+ window.addEventListener('blur', () => { spacePressed = false; });
1603
+
392
1604
  byId('copy').onclick = async () => {
393
1605
  try {
394
1606
  const handoff = await api('/api/handoff?audience=developer');
@@ -440,10 +1652,14 @@ byId('install').onclick = async () => {
440
1652
  try {
441
1653
  await api('/api/install', {
442
1654
  method: 'POST',
443
- body: JSON.stringify({ recipe: draft, replace: catalog.recipes.some((recipe) => recipe.id === draft.id) })
1655
+ body: JSON.stringify({
1656
+ recipe: draft,
1657
+ layout: layoutPayload(),
1658
+ replace: catalog.recipes.some((recipe) => recipe.id === draft.id)
1659
+ })
444
1660
  });
445
1661
  byId('confirm').close();
446
- notify('Recipe installed atomically.');
1662
+ notify('Recipe and private canvas layout installed atomically.');
447
1663
  await refreshCatalog(draft.id);
448
1664
  await loadRecipe();
449
1665
  } catch (error) {
@@ -458,4 +1674,52 @@ function notify(text) {
458
1674
  setTimeout(() => { message.style.display = 'none'; }, 4000);
459
1675
  }
460
1676
 
1677
+ async function initialize() {
1678
+ await refreshCatalog('default');
1679
+ byId('recipe').onchange = loadRecipe;
1680
+ bindCanvas();
1681
+ byId('toggle-library').onclick = () => byId('library-panel').classList.toggle('open');
1682
+ byId('close-library').onclick = () => byId('library-panel').classList.remove('open');
1683
+ byId('show-workflows').onclick = () => showWorkspace('workflows');
1684
+ byId('show-runs').onclick = () => showWorkspace('runs');
1685
+ byId('run-search').oninput = loadRuns;
1686
+ for (const id of ['run-status', 'run-mode', 'run-from', 'run-to']) byId(id).onchange = loadRuns;
1687
+ byId('import-json').onclick = () => byId('import-dialog').showModal();
1688
+ byId('export-json').onclick = exportWorkflowJson;
1689
+ byId('preview-import').onclick = previewImport;
1690
+ byId('import-file').onchange = async (event) => {
1691
+ const [file] = event.currentTarget.files;
1692
+ if (file) byId('import-source').value = await file.text();
1693
+ };
1694
+ byId('merge-import').onclick = () => applyImport('merge');
1695
+ byId('replace-import').onclick = () => applyImport('replace');
1696
+ byId('create-custom').onclick = () => byId('custom-dialog').showModal();
1697
+ byId('custom-form').onsubmit = createCustomAgentFromForm;
1698
+ byId('open-goal').onclick = () => {
1699
+ renderGoalState();
1700
+ byId('goal-dialog').showModal();
1701
+ };
1702
+ byId('save-goal').onclick = saveGoalFromForm;
1703
+ byId('review-goal').onclick = reviewGoal;
1704
+ byId('confirm-freeze').onclick = freezeGoalFromForm;
1705
+ byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
1706
+ byId('duplicate-selection').onclick = duplicateSelectedNode;
1707
+ byId('delete-selection').onclick = deleteSelectedNode;
1708
+ document.querySelectorAll('[data-close]').forEach((button) => {
1709
+ button.onclick = () => byId(button.dataset.close).close();
1710
+ });
1711
+ byId('workflow-settings').onclick = () => {
1712
+ selectedId = null;
1713
+ updateSelection();
1714
+ renderRecipeDetails();
1715
+ byId('inspector-panel').classList.add('open');
1716
+ };
1717
+ byId('close-inspector').onclick = () => byId('inspector-panel').classList.remove('open');
1718
+ byId('toggle-execution').onclick = () => byId('execution-panel').classList.toggle('open');
1719
+ byId('close-execution').onclick = () => byId('execution-panel').classList.remove('open');
1720
+ await loadRecipe();
1721
+ clearInterval(liveTimer);
1722
+ liveTimer = setInterval(refreshLive, 1800);
1723
+ }
1724
+
461
1725
  initialize().catch((error) => notify(error.message));