ai-engineering-loop 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/studio/app.js CHANGED
@@ -1,17 +1,30 @@
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;
7
18
  let liveTimer;
8
19
  let validationSequence = 0;
9
-
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
- );
20
+ let positions = new Map();
21
+ let viewport = { x: 0, y: 0, scale: 1 };
22
+ let history = [];
23
+ let historyIndex = -1;
24
+ let interaction;
25
+ let connection;
26
+ let layoutTimer;
27
+ let spacePressed = false;
15
28
 
16
29
  async function api(url, options = {}) {
17
30
  const response = await fetch(url, {
@@ -31,40 +44,11 @@ function recipeSummary() {
31
44
  return catalog.recipes.find((recipe) => recipe.id === draft.id);
32
45
  }
33
46
 
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;
55
- }
56
-
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();
47
+ function layoutPayload() {
48
+ return { viewport: { ...viewport }, positions: Object.fromEntries(positions) };
65
49
  }
66
50
 
67
- function graphPositions() {
51
+ function defaultGraphPositions() {
68
52
  const depths = new Map();
69
53
  const visiting = new Set();
70
54
  const depthFor = (node) => {
@@ -84,106 +68,260 @@ function graphPositions() {
84
68
  const depth = depthFor(node);
85
69
  const row = rows.get(depth) || 0;
86
70
  rows.set(depth, row + 1);
87
- return [node.id, { x: 90 + depth * 300, y: 125 + row * 150 }];
71
+ return [node.id, { x: 80 + depth * 270, y: 110 + row * 150 }];
88
72
  }));
89
73
  }
90
74
 
75
+ function ensurePositions() {
76
+ const defaults = defaultGraphPositions();
77
+ const ids = new Set(draft.nodes.map((node) => node.id));
78
+ for (const id of positions.keys()) {
79
+ if (!ids.has(id)) positions.delete(id);
80
+ }
81
+ for (const node of draft.nodes) {
82
+ if (!positions.has(node.id)) positions.set(node.id, defaults.get(node.id));
83
+ }
84
+ }
85
+
86
+ function applyViewport() {
87
+ byId('scene').style.transform = `translate(${viewport.x}px,${viewport.y}px) scale(${viewport.scale})`;
88
+ byId('canvas').style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
89
+ byId('canvas').style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
90
+ byId('zoom-level').textContent = `${Math.round(viewport.scale * 100)}%`;
91
+ }
92
+
93
+ function screenToWorld(clientX, clientY) {
94
+ const rect = byId('canvas').getBoundingClientRect();
95
+ return {
96
+ x: (clientX - rect.left - viewport.x) / viewport.scale,
97
+ y: (clientY - rect.top - viewport.y) / viewport.scale
98
+ };
99
+ }
100
+
101
+ function worldAtCanvasCenter() {
102
+ const rect = byId('canvas').getBoundingClientRect();
103
+ return screenToWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
104
+ }
105
+
106
+ function edgePath(from, to) {
107
+ const startX = from.x + NODE_WIDTH;
108
+ const startY = from.y + NODE_PORT_Y;
109
+ const endX = to.x;
110
+ const endY = to.y + NODE_PORT_Y;
111
+ const bend = Math.max(55, Math.abs(endX - startX) * 0.42);
112
+ return `M${startX} ${startY} C${startX + bend} ${startY},${endX - bend} ${endY},${endX} ${endY}`;
113
+ }
114
+
115
+ function stageLabel(node, index) {
116
+ const stages = {
117
+ 'goal-contract': 'STAGE 01',
118
+ maker: 'STAGES 02–04',
119
+ verification: 'STAGE 05',
120
+ 'devil-advocate': 'STAGE 06',
121
+ judge: 'STAGE 07',
122
+ approval: 'STAGE 08 GATE',
123
+ delivery: 'STAGE 08',
124
+ report: 'REPORT'
125
+ };
126
+ return stages[node.type] || `CUSTOM ${String(index + 1).padStart(2, '0')}`;
127
+ }
128
+
129
+ function renderEdges() {
130
+ const group = byId('edge-paths');
131
+ group.innerHTML = '';
132
+ if (!draft) return;
133
+ draft.nodes.forEach((node) => {
134
+ for (const dependencyId of node.dependsOn || []) {
135
+ const from = positions.get(dependencyId);
136
+ const to = positions.get(node.id);
137
+ if (!from || !to) continue;
138
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
139
+ path.setAttribute('d', edgePath(from, to));
140
+ path.setAttribute('class', catalog.live?.nodes?.[dependencyId]?.status === 'RUNNING' ? 'edge active' : 'edge');
141
+ path.setAttribute('marker-end', 'url(#arrow)');
142
+ group.append(path);
143
+ }
144
+ });
145
+ }
146
+
147
+ function nodeMarkup(node, index) {
148
+ const runtimeNode = catalog.live?.nodes?.[node.id];
149
+ return `
150
+ <button class="port port-in" aria-label="Input for ${escapeHtml(node.id)}" tabindex="-1"></button>
151
+ <small>${escapeHtml(stageLabel(node, index))} / ${escapeHtml(node.type.toUpperCase())}</small>
152
+ <h3>${escapeHtml(node.id)}</h3>
153
+ <span class="status">● ${escapeHtml(runtimeNode?.status || 'DRAFT')}</span>
154
+ ${runtimeNode?.activity ? `<p class="node-activity">${escapeHtml(runtimeNode.activity)}</p>` : ''}
155
+ <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
156
+ `;
157
+ }
158
+
91
159
  function renderGraph() {
92
- const positions = graphPositions();
160
+ ensurePositions();
93
161
  const container = byId('nodes');
94
162
  container.innerHTML = '';
95
163
  draft.nodes.forEach((node, index) => {
96
164
  const position = positions.get(node.id);
97
165
  const runtimeNode = catalog.live?.nodes?.[node.id];
98
166
  const element = document.createElement('article');
167
+ element.dataset.nodeId = node.id;
99
168
  element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${selectedId === node.id ? 'selected' : ''}`;
100
169
  element.style.left = `${position.x}px`;
101
170
  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
- };
171
+ element.innerHTML = nodeMarkup(node, index);
172
+ element.addEventListener('pointerdown', beginNodeInteraction);
173
+ element.querySelector('.port-out').addEventListener('pointerdown', beginConnection);
112
174
  container.append(element);
113
175
  });
114
- renderEdges(positions);
115
- byId('mode').textContent = `${draft.compatibleModes.join(' · ') || 'NO MODE'} / EDIT MODE`;
176
+ renderEdges();
177
+ applyViewport();
116
178
  }
117
179
 
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);
180
+ function updateRuntimePresentation() {
181
+ if (!draft) return;
182
+ for (const element of document.querySelectorAll('.node')) {
183
+ const nodeId = element.dataset.nodeId;
184
+ const runtimeNode = catalog.live?.nodes?.[nodeId];
185
+ element.classList.remove('running', 'passed', 'failed', 'blocked', 'ready', 'pending', 'skipped');
186
+ if (runtimeNode?.status) element.classList.add(runtimeNode.status.toLowerCase());
187
+ element.querySelector('.status').textContent = `● ${runtimeNode?.status || 'DRAFT'}`;
188
+ const existingActivity = element.querySelector('.node-activity');
189
+ if (runtimeNode?.activity) {
190
+ if (existingActivity) existingActivity.textContent = runtimeNode.activity;
191
+ else element.querySelector('.status').insertAdjacentHTML('afterend', `<p class="node-activity">${escapeHtml(runtimeNode.activity)}</p>`);
192
+ } else {
193
+ existingActivity?.remove();
141
194
  }
195
+ }
196
+ renderEdges();
197
+ }
198
+
199
+ function updateSelection() {
200
+ document.querySelectorAll('.node').forEach((element) => {
201
+ element.classList.toggle('selected', element.dataset.nodeId === selectedId);
142
202
  });
143
203
  }
144
204
 
205
+ function renderRecipeDetails() {
206
+ const existing = recipeSummary();
207
+ byId('inspector-label').textContent = 'WORKFLOW';
208
+ byId('inspector-title').textContent = draft.id;
209
+ byId('details').innerHTML = `
210
+ <div class="source-line"><span>${escapeHtml(source.toUpperCase())}</span><span>${draft.nodes.length} NODES</span></div>
211
+ <label for="recipe-id">Name</label><input id="recipe-id" value="${escapeHtml(draft.id)}">
212
+ <label for="recipe-description">Description</label><textarea id="recipe-description">${escapeHtml(draft.description)}</textarea>
213
+ ${existing?.source === 'builtin' ? '<p class="hint">Saving creates a project copy. The built-in remains unchanged.</p>' : ''}
214
+ <details>
215
+ <summary>Advanced settings</summary>
216
+ <div class="settings-body">
217
+ <label for="recipe-version">Version</label><input id="recipe-version" type="number" min="1" value="${escapeHtml(draft.version)}">
218
+ <label for="recipe-modes">Run modes</label>
219
+ <select id="recipe-modes" multiple>
220
+ ${['REPORT_ONLY', 'ASSISTED', 'UNATTENDED'].map((mode) => `<option ${draft.compatibleModes.includes(mode) ? 'selected' : ''}>${mode}</option>`).join('')}
221
+ </select>
222
+ </div>
223
+ </details>
224
+ <button id="apply-recipe">Apply changes</button>
225
+ `;
226
+ byId('apply-recipe').onclick = applyRecipeDetails;
227
+ }
228
+
145
229
  function selectNode(nodeId) {
146
- selectedId = nodeId;
147
230
  const node = draft.nodes.find((candidate) => candidate.id === nodeId);
231
+ if (!node) return;
232
+ selectedId = nodeId;
233
+ updateSelection();
148
234
  const runtimeNode = catalog.live?.nodes?.[nodeId];
149
- byId('inspector-label').textContent = 'NODE INSPECTOR';
235
+ byId('inspector-label').textContent = 'NODE';
236
+ byId('inspector-title').textContent = node.id;
237
+ byId('inspector-panel').classList.add('open');
150
238
  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>
239
+ <div class="source-line"><span>${escapeHtml(node.type.toUpperCase())}</span><span>${escapeHtml(runtimeNode?.status || 'DRAFT')}</span></div>
240
+ <label for="node-id">Name</label><input id="node-id" value="${escapeHtml(node.id)}">
241
+ ${node.type === 'delivery' ? deliveryAdapterControls() : ''}
242
+ <details>
243
+ <summary>Settings</summary>
244
+ <div class="settings-body">
245
+ <label>Type</label><input value="${escapeHtml(node.type)}" disabled>
246
+ <label for="node-dependencies">Inputs</label>
247
+ <input id="node-dependencies" value="${escapeHtml((node.dependsOn || []).join(', '))}" placeholder="Connect nodes on the canvas">
248
+ ${node.type === 'agent' ? `
249
+ <label for="node-extra">Role</label><input id="node-extra" value="${escapeHtml(node.role || '')}">
250
+ <label for="node-tokens">Token limit</label><input id="node-tokens" type="number" min="1" value="${escapeHtml(node.context?.maxTokens || '')}">
251
+ ` : node.type === 'approval' ? `
252
+ <label for="node-extra">Approval message</label><textarea id="node-extra">${escapeHtml(node.message || '')}</textarea>
253
+ ` : node.type === 'condition' ? `
254
+ <label for="condition-field">Field</label>
255
+ <select id="condition-field">${['run.mode', 'run.state', 'run.iteration', 'run.task'].map((field) => `<option ${node.expression?.field === field ? 'selected' : ''}>${field}</option>`).join('')}</select>
256
+ <label for="condition-operator">Rule</label>
257
+ <select id="condition-operator">${['equals', 'notEquals', 'contains', 'exists', 'isEmpty', 'greaterThan', 'lessThan'].map((operator) => `<option ${node.expression?.operator === operator ? 'selected' : ''}>${operator}</option>`).join('')}</select>
258
+ <label for="condition-value">Value</label><input id="condition-value" value="${escapeHtml(node.expression?.value ?? '')}">
259
+ ` : ''}
260
+ </div>
261
+ </details>
262
+ <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
263
  ${runtimeControls(node, runtimeNode)}
172
264
  `;
173
265
  byId('apply-node').onclick = applyNodeDetails;
266
+ if (byId('duplicate-node')) byId('duplicate-node').onclick = duplicateSelectedNode;
174
267
  byId('delete-node').onclick = deleteSelectedNode;
175
- bindRuntimeControls(node, runtimeNode);
176
- renderGraph();
268
+ if (byId('select-adapter')) byId('select-adapter').onclick = selectDeliveryAdapter;
269
+ if (byId('generate-adapter')) byId('generate-adapter').onclick = copyAdapterBuilderPrompt;
270
+ bindRuntimeControls(node);
271
+ }
272
+
273
+ function deliveryAdapterControls() {
274
+ const current = catalog.adapters.current;
275
+ const options = [...catalog.adapters.types];
276
+ if (current && !options.includes(current)) options.push(current);
277
+ return `
278
+ <section class="adapter-controls">
279
+ <label for="delivery-adapter">Delivery adapter</label>
280
+ <select id="delivery-adapter">
281
+ ${options.map((type) => `<option ${type === (current || catalog.adapters.recommended) ? 'selected' : ''}>${escapeHtml(type)}</option>`).join('')}
282
+ </select>
283
+ <p class="hint">${current
284
+ ? `${escapeHtml(current)} is active for this project.`
285
+ : `Recommended: ${escapeHtml(catalog.adapters.recommended)}.`}</p>
286
+ <div class="button-row"><button id="select-adapter">Use adapter</button><button id="generate-adapter">Create custom</button></div>
287
+ </section>
288
+ `;
289
+ }
290
+
291
+ async function selectDeliveryAdapter() {
292
+ const type = byId('delivery-adapter').value;
293
+ if (!catalog.adapters.types.includes(type)) {
294
+ return notify('Custom adapters are changed through the guarded AI adapter builder.');
295
+ }
296
+ try {
297
+ await api('/api/adapter/select', { method: 'POST', body: JSON.stringify({ type }) });
298
+ catalog.adapters.current = type;
299
+ selectNode(selectedId);
300
+ notify(`${type} is now the project Stage 8 adapter.`);
301
+ } catch (error) {
302
+ notify(error.message);
303
+ }
304
+ }
305
+
306
+ async function copyAdapterBuilderPrompt() {
307
+ const prompt = [
308
+ 'Use the ai-engineering-loop generate-adapter skill for this repository.',
309
+ 'Ask Q1-Q5 before writing. Build a custom Stage 8 delivery adapter only.',
310
+ 'Preserve Stages 0-7, require Judge PASS, never store credentials, and use explicit approval for remote side effects.',
311
+ 'After validation, write .ai-engineering-loop/adapter.md so Workflow Studio discovers it.'
312
+ ].join(' ');
313
+ try {
314
+ await navigator.clipboard.writeText(prompt);
315
+ notify('Guarded custom-adapter prompt copied for your AI agent.');
316
+ } catch (error) {
317
+ notify(error.message);
318
+ }
177
319
  }
178
320
 
179
321
  function runtimeControls(node, runtimeNode) {
180
322
  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
- : '';
323
+ const approve = node.type === 'approval' && runtimeNode.status === 'READY' ? '<button id="approve-node">APPROVE</button>' : '';
324
+ const retry = ['FAILED', 'RUNNING'].includes(runtimeNode.status) ? '<button id="retry-node">RETRY</button>' : '';
187
325
  const activity = runtimeNode.status === 'RUNNING'
188
326
  ? '<label for="runtime-activity">SAFE ACTIVITY UPDATE</label><input id="runtime-activity" maxlength="240"><button id="send-activity">REPORT ACTIVITY</button>'
189
327
  : '';
@@ -192,15 +330,13 @@ function runtimeControls(node, runtimeNode) {
192
330
  : '';
193
331
  }
194
332
 
195
- function bindRuntimeControls(node, runtimeNode) {
333
+ function bindRuntimeControls(node) {
196
334
  const runId = catalog.live?.run?.runId;
197
335
  if (byId('approve-node')) byId('approve-node').onclick = () => mutateNode('/api/node/approve', { runId, nodeId: node.id });
198
336
  if (byId('retry-node')) byId('retry-node').onclick = () => mutateNode('/api/node/retry', { runId, nodeId: node.id });
199
337
  if (byId('send-activity')) {
200
338
  byId('send-activity').onclick = () => mutateNode('/api/node/activity', {
201
- runId,
202
- nodeId: node.id,
203
- message: byId('runtime-activity').value
339
+ runId, nodeId: node.id, message: byId('runtime-activity').value
204
340
  });
205
341
  }
206
342
  }
@@ -215,8 +351,20 @@ async function mutateNode(endpoint, body) {
215
351
  }
216
352
  }
217
353
 
354
+ function applyRecipeDetails() {
355
+ draft.id = byId('recipe-id').value.trim();
356
+ draft.version = Number(byId('recipe-version').value);
357
+ draft.description = byId('recipe-description').value.trim();
358
+ draft.compatibleModes = [...byId('recipe-modes').selectedOptions].map((option) => option.value);
359
+ captureHistory();
360
+ renderGraph();
361
+ renderRecipeDetails();
362
+ validateDraft();
363
+ }
364
+
218
365
  function applyNodeDetails() {
219
366
  const node = draft.nodes.find((candidate) => candidate.id === selectedId);
367
+ if (!node) return;
220
368
  const previousId = node.id;
221
369
  node.id = byId('node-id').value.trim();
222
370
  node.dependsOn = byId('node-dependencies').value.split(',').map((value) => value.trim()).filter(Boolean);
@@ -234,33 +382,45 @@ function applyNodeDetails() {
234
382
  const rawValue = byId('condition-value').value.trim();
235
383
  node.expression = { field, operator };
236
384
  if (!['exists', 'isEmpty'].includes(operator)) {
237
- node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator)
238
- ? Number(rawValue)
239
- : rawValue;
385
+ node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator) ? Number(rawValue) : rawValue;
240
386
  }
241
387
  }
388
+ if (previousId !== node.id && positions.has(previousId)) {
389
+ positions.set(node.id, positions.get(previousId));
390
+ positions.delete(previousId);
391
+ }
242
392
  selectedId = node.id;
393
+ captureHistory();
243
394
  renderGraph();
244
395
  selectNode(node.id);
245
396
  validateDraft();
397
+ saveLayoutSoon();
246
398
  }
247
399
 
248
400
  function deleteSelectedNode() {
249
401
  if (!selectedId) return;
250
- draft.nodes = draft.nodes.filter((node) => node.id !== selectedId);
402
+ const removedId = selectedId;
403
+ draft.nodes = draft.nodes.filter((node) => node.id !== removedId);
251
404
  draft.nodes.forEach((node) => {
252
- node.dependsOn = (node.dependsOn || []).filter((dependency) => dependency !== selectedId);
405
+ node.dependsOn = (node.dependsOn || []).filter((dependency) => dependency !== removedId);
253
406
  });
407
+ positions.delete(removedId);
254
408
  selectedId = null;
409
+ captureHistory();
255
410
  renderGraph();
256
411
  renderRecipeDetails();
412
+ byId('inspector-panel').classList.remove('open');
257
413
  validateDraft();
414
+ saveLayoutSoon();
258
415
  }
259
416
 
260
- function addNode(type) {
417
+ function uniqueNodeId(type) {
261
418
  let suffix = draft.nodes.length + 1;
262
419
  while (draft.nodes.some((node) => node.id === `${type}-${suffix}`)) suffix += 1;
263
- const id = `${type}-${suffix}`;
420
+ return `${type}-${suffix}`;
421
+ }
422
+
423
+ function createNode(type, id = uniqueNodeId(type)) {
264
424
  const node = { id, type, dependsOn: [] };
265
425
  if (type === 'agent') {
266
426
  Object.assign(node, {
@@ -273,25 +433,245 @@ function addNode(type) {
273
433
  } else if (type === 'condition') {
274
434
  node.expression = { field: 'run.mode', operator: 'equals', value: 'ASSISTED' };
275
435
  }
436
+ return node;
437
+ }
438
+
439
+ function addNode(type, position = worldAtCanvasCenter()) {
440
+ const node = createNode(type);
276
441
  draft.nodes.push(node);
277
- selectNode(id);
442
+ positions.set(node.id, { x: position.x - NODE_WIDTH / 2, y: position.y - NODE_PORT_Y });
443
+ captureHistory();
444
+ renderGraph();
445
+ selectNode(node.id);
446
+ byId('library-panel').classList.remove('open');
447
+ validateDraft();
448
+ }
449
+
450
+ function duplicateSelectedNode() {
451
+ const original = draft.nodes.find((node) => node.id === selectedId);
452
+ if (!original) return;
453
+ const clone = structuredClone(original);
454
+ clone.id = uniqueNodeId(original.type);
455
+ if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
456
+ draft.nodes.push(clone);
457
+ const originalPosition = positions.get(original.id);
458
+ positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
459
+ captureHistory();
460
+ renderGraph();
461
+ selectNode(clone.id);
278
462
  validateDraft();
279
463
  }
280
464
 
281
465
  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('');
466
+ byId('palette').innerHTML = catalog.nodeTypes.filter((node) => node.executable).map((node) => `
467
+ <button class="palette-item" draggable="true" data-node-type="${escapeHtml(node.type)}">
468
+ <b>${escapeHtml(node.label)}</b><small>${escapeHtml(node.category.toUpperCase())}</small>
469
+ </button>
470
+ `).join('');
290
471
  document.querySelectorAll('[data-node-type]').forEach((button) => {
291
472
  button.onclick = () => addNode(button.dataset.nodeType);
473
+ button.ondragstart = (event) => {
474
+ event.dataTransfer.setData('application/x-ael-node-type', button.dataset.nodeType);
475
+ event.dataTransfer.effectAllowed = 'copy';
476
+ };
292
477
  });
293
478
  }
294
479
 
480
+ function beginNodeInteraction(event) {
481
+ if (event.button !== 0 || event.target.closest('.port')) return;
482
+ event.stopPropagation();
483
+ const element = event.currentTarget;
484
+ const nodeId = element.dataset.nodeId;
485
+ selectNode(nodeId);
486
+ if (spacePressed) return beginPan(event);
487
+ const world = screenToWorld(event.clientX, event.clientY);
488
+ const position = positions.get(nodeId);
489
+ interaction = { type: 'node', pointerId: event.pointerId, nodeId, element, offsetX: world.x - position.x, offsetY: world.y - position.y };
490
+ element.classList.add('dragging');
491
+ element.setPointerCapture(event.pointerId);
492
+ }
493
+
494
+ function beginPan(event) {
495
+ if (event.button !== 0 && event.button !== 1) return;
496
+ event.preventDefault();
497
+ interaction = {
498
+ type: 'pan',
499
+ pointerId: event.pointerId,
500
+ startX: event.clientX,
501
+ startY: event.clientY,
502
+ viewportX: viewport.x,
503
+ viewportY: viewport.y
504
+ };
505
+ byId('canvas').setPointerCapture(event.pointerId);
506
+ }
507
+
508
+ function handlePointerMove(event) {
509
+ if (connection) {
510
+ const from = positions.get(connection.sourceId);
511
+ const target = screenToWorld(event.clientX, event.clientY);
512
+ const start = { x: from.x + NODE_WIDTH, y: from.y + NODE_PORT_Y };
513
+ const bend = Math.max(55, Math.abs(target.x - start.x) * 0.42);
514
+ 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}`);
515
+ return;
516
+ }
517
+ if (!interaction || interaction.pointerId !== event.pointerId) return;
518
+ if (interaction.type === 'node') {
519
+ const world = screenToWorld(event.clientX, event.clientY);
520
+ const position = { x: world.x - interaction.offsetX, y: world.y - interaction.offsetY };
521
+ positions.set(interaction.nodeId, position);
522
+ interaction.element.style.left = `${position.x}px`;
523
+ interaction.element.style.top = `${position.y}px`;
524
+ renderEdges();
525
+ } else {
526
+ viewport.x = interaction.viewportX + event.clientX - interaction.startX;
527
+ viewport.y = interaction.viewportY + event.clientY - interaction.startY;
528
+ applyViewport();
529
+ }
530
+ }
531
+
532
+ function finishPointer(event) {
533
+ if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
534
+ if (!interaction || interaction.pointerId !== event.pointerId) return;
535
+ if (interaction.type === 'node') {
536
+ interaction.element.classList.remove('dragging');
537
+ captureHistory();
538
+ }
539
+ interaction = null;
540
+ saveLayoutSoon();
541
+ }
542
+
543
+ function beginConnection(event) {
544
+ event.preventDefault();
545
+ event.stopPropagation();
546
+ const sourceId = event.currentTarget.closest('.node').dataset.nodeId;
547
+ connection = { sourceId, pointerId: event.pointerId };
548
+ byId('preview-edge').style.display = 'block';
549
+ event.currentTarget.setPointerCapture(event.pointerId);
550
+ }
551
+
552
+ function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
553
+ if (nodeId === targetId) return true;
554
+ if (seen.has(nodeId)) return false;
555
+ seen.add(nodeId);
556
+ const node = draft.nodes.find((candidate) => candidate.id === nodeId);
557
+ return (node?.dependsOn || []).some((dependencyId) => transitivelyDependsOn(dependencyId, targetId, seen));
558
+ }
559
+
560
+ function finishConnection(event) {
561
+ const sourceId = connection.sourceId;
562
+ connection = null;
563
+ byId('preview-edge').style.display = 'none';
564
+ const targetElement = document.elementFromPoint(event.clientX, event.clientY)?.closest('.node');
565
+ const targetId = targetElement?.dataset.nodeId;
566
+ if (!targetId || targetId === sourceId) return;
567
+ const target = draft.nodes.find((node) => node.id === targetId);
568
+ if ((target.dependsOn || []).includes(sourceId)) return notify('Nodes are already connected.');
569
+ if (transitivelyDependsOn(sourceId, targetId)) return notify('Connection rejected: it would create a cycle.');
570
+ target.dependsOn = [...(target.dependsOn || []), sourceId];
571
+ captureHistory();
572
+ renderGraph();
573
+ selectNode(targetId);
574
+ validateDraft();
575
+ }
576
+
577
+ function zoomAt(nextScale, clientX, clientY) {
578
+ const scale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));
579
+ const rect = byId('canvas').getBoundingClientRect();
580
+ const x = clientX ?? rect.left + rect.width / 2;
581
+ const y = clientY ?? rect.top + rect.height / 2;
582
+ const world = screenToWorld(x, y);
583
+ viewport.scale = scale;
584
+ viewport.x = x - rect.left - world.x * scale;
585
+ viewport.y = y - rect.top - world.y * scale;
586
+ applyViewport();
587
+ saveLayoutSoon();
588
+ }
589
+
590
+ function handleWheel(event) {
591
+ event.preventDefault();
592
+ if (event.ctrlKey || event.metaKey) {
593
+ zoomAt(viewport.scale * Math.exp(-event.deltaY * 0.002), event.clientX, event.clientY);
594
+ } else {
595
+ viewport.x -= event.deltaX;
596
+ viewport.y -= event.deltaY;
597
+ applyViewport();
598
+ saveLayoutSoon();
599
+ }
600
+ }
601
+
602
+ function autoLayout({ record = true } = {}) {
603
+ positions = defaultGraphPositions();
604
+ renderGraph();
605
+ fitView();
606
+ if (record) captureHistory();
607
+ saveLayoutSoon();
608
+ }
609
+
610
+ function fitView() {
611
+ ensurePositions();
612
+ if (!positions.size) return;
613
+ const rect = byId('canvas').getBoundingClientRect();
614
+ const values = [...positions.values()];
615
+ const minX = Math.min(...values.map((position) => position.x));
616
+ const minY = Math.min(...values.map((position) => position.y));
617
+ const maxX = Math.max(...values.map((position) => position.x + NODE_WIDTH));
618
+ const maxY = Math.max(...values.map((position) => position.y + 140));
619
+ const padding = 100;
620
+ viewport.scale = Math.max(MIN_ZOOM, Math.min(1.35, Math.min(
621
+ (rect.width - padding * 2) / Math.max(1, maxX - minX),
622
+ (rect.height - padding * 2) / Math.max(1, maxY - minY)
623
+ )));
624
+ viewport.x = (rect.width - (maxX - minX) * viewport.scale) / 2 - minX * viewport.scale;
625
+ viewport.y = (rect.height - (maxY - minY) * viewport.scale) / 2 - minY * viewport.scale;
626
+ applyViewport();
627
+ saveLayoutSoon();
628
+ }
629
+
630
+ function captureHistory({ reset = false } = {}) {
631
+ const snapshot = JSON.stringify({ draft, positions: Object.fromEntries(positions) });
632
+ if (reset) {
633
+ history = [snapshot];
634
+ historyIndex = 0;
635
+ } else if (history[historyIndex] !== snapshot) {
636
+ history = history.slice(0, historyIndex + 1);
637
+ history.push(snapshot);
638
+ historyIndex = history.length - 1;
639
+ }
640
+ byId('undo').disabled = historyIndex <= 0;
641
+ byId('redo').disabled = historyIndex >= history.length - 1;
642
+ }
643
+
644
+ function restoreHistory(index) {
645
+ if (index < 0 || index >= history.length) return;
646
+ historyIndex = index;
647
+ const snapshot = JSON.parse(history[index]);
648
+ draft = snapshot.draft;
649
+ positions = new Map(Object.entries(snapshot.positions));
650
+ if (!draft.nodes.some((node) => node.id === selectedId)) selectedId = null;
651
+ renderGraph();
652
+ if (selectedId) selectNode(selectedId);
653
+ else renderRecipeDetails();
654
+ validateDraft();
655
+ saveLayoutSoon();
656
+ byId('undo').disabled = historyIndex <= 0;
657
+ byId('redo').disabled = historyIndex >= history.length - 1;
658
+ }
659
+
660
+ function saveLayoutSoon() {
661
+ clearTimeout(layoutTimer);
662
+ if (!loadedRecipeId || draft.id !== loadedRecipeId) return;
663
+ layoutTimer = setTimeout(async () => {
664
+ try {
665
+ await api('/api/layout', {
666
+ method: 'PUT',
667
+ body: JSON.stringify({ recipeId: loadedRecipeId, layout: layoutPayload() })
668
+ });
669
+ } catch {
670
+ // Canvas work remains in memory and install still submits the layout.
671
+ }
672
+ }, 350);
673
+ }
674
+
295
675
  async function validateDraft() {
296
676
  const sequence = ++validationSequence;
297
677
  try {
@@ -319,20 +699,21 @@ async function validateDraft() {
319
699
  function renderLive() {
320
700
  const live = catalog.live;
321
701
  if (!live) {
702
+ byId('run-summary').textContent = 'No active run';
322
703
  byId('active-stage').textContent = 'No active run';
323
704
  byId('activity').textContent = 'Waiting for a recipe-bound workflow.';
324
705
  byId('events').innerHTML = '';
325
706
  byId('budget').textContent = '—';
326
707
  byId('meter').style.width = '0';
708
+ updateRuntimePresentation();
327
709
  return;
328
710
  }
329
711
  const active = live.plan.nodes.find((node) => live.nodes[node.id].status === 'RUNNING')
330
712
  || live.plan.nodes.find((node) => live.nodes[node.id].status === 'READY');
331
713
  const runtimeNode = active ? live.nodes[active.id] : null;
714
+ byId('run-summary').textContent = active ? `${active.id} · ${runtimeNode.status}` : `Run ${live.run.state}`;
332
715
  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}`;
716
+ byId('activity').textContent = active ? runtimeNode.activity || `${runtimeNode.status} · attempt ${runtimeNode.attempts}` : `Final state: ${live.run.state}`;
336
717
  const spent = live.budget.spentThisRun;
337
718
  const limit = live.budget.perRunTokenLimit;
338
719
  byId('meter').style.width = `${Math.min(100, limit ? (spent / limit) * 100 : 0)}%`;
@@ -342,7 +723,7 @@ function renderLive() {
342
723
  ${escapeHtml(event.at.slice(11, 19))} · ${escapeHtml(event.type)} · ${escapeHtml(event.changedNodes.join(', '))}
343
724
  </p>
344
725
  `).join('');
345
- renderGraph();
726
+ updateRuntimePresentation();
346
727
  }
347
728
 
348
729
  async function refreshLive() {
@@ -356,12 +737,23 @@ async function refreshLive() {
356
737
  }
357
738
 
358
739
  async function loadRecipe() {
359
- const result = await api(`/api/recipe?id=${encodeURIComponent(byId('recipe').value)}`);
740
+ const id = byId('recipe').value;
741
+ const [result, saved] = await Promise.all([
742
+ api(`/api/recipe?id=${encodeURIComponent(id)}`),
743
+ api(`/api/layout?id=${encodeURIComponent(id)}`)
744
+ ]);
360
745
  draft = structuredClone(result.recipe);
361
746
  source = result.source;
747
+ loadedRecipeId = draft.id;
362
748
  selectedId = null;
749
+ byId('inspector-panel').classList.remove('open');
750
+ positions = new Map(Object.entries(saved.layout?.positions || {}));
751
+ ensurePositions();
752
+ viewport = saved.layout?.viewport || { x: 0, y: 0, scale: 1 };
363
753
  renderGraph();
754
+ if (!saved.layout || (draft.nodes.length <= 12 && viewport.scale < 0.45)) fitView();
364
755
  renderRecipeDetails();
756
+ captureHistory({ reset: true });
365
757
  validateDraft();
366
758
  }
367
759
 
@@ -376,19 +768,69 @@ async function refreshCatalog(selectedRecipe) {
376
768
  renderLive();
377
769
  }
378
770
 
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);
771
+ function bindCanvas() {
772
+ const canvas = byId('canvas');
773
+ canvas.addEventListener('pointerdown', (event) => {
774
+ if (event.target === canvas || event.target === byId('scene') || event.target === byId('nodes') || event.target === byId('edges')) {
775
+ selectedId = null;
776
+ updateSelection();
777
+ renderRecipeDetails();
778
+ byId('inspector-panel').classList.remove('open');
779
+ beginPan(event);
780
+ }
781
+ });
782
+ canvas.addEventListener('pointermove', handlePointerMove);
783
+ canvas.addEventListener('pointerup', finishPointer);
784
+ canvas.addEventListener('pointercancel', finishPointer);
785
+ canvas.addEventListener('wheel', handleWheel, { passive: false });
786
+ canvas.addEventListener('dragover', (event) => {
787
+ if (!event.dataTransfer.types.includes('application/x-ael-node-type')) return;
788
+ event.preventDefault();
789
+ canvas.classList.add('drop-ready');
790
+ });
791
+ canvas.addEventListener('dragleave', () => canvas.classList.remove('drop-ready'));
792
+ canvas.addEventListener('drop', (event) => {
793
+ event.preventDefault();
794
+ canvas.classList.remove('drop-ready');
795
+ const type = event.dataTransfer.getData('application/x-ael-node-type');
796
+ if (type) addNode(type, screenToWorld(event.clientX, event.clientY));
797
+ });
798
+ byId('auto-layout').onclick = () => autoLayout();
799
+ byId('fit-view').onclick = fitView;
800
+ byId('fit-view-rail').onclick = fitView;
801
+ byId('zoom-in').onclick = () => zoomAt(viewport.scale * 1.2);
802
+ byId('zoom-out').onclick = () => zoomAt(viewport.scale / 1.2);
803
+ byId('undo').onclick = () => restoreHistory(historyIndex - 1);
804
+ byId('redo').onclick = () => restoreHistory(historyIndex + 1);
805
+ }
806
+
807
+ function editableTarget(target) {
808
+ return target.matches('input,textarea,select,[contenteditable="true"]');
390
809
  }
391
810
 
811
+ document.addEventListener('keydown', (event) => {
812
+ if (event.code === 'Space' && !editableTarget(event.target)) {
813
+ spacePressed = true;
814
+ event.preventDefault();
815
+ }
816
+ if (editableTarget(event.target)) return;
817
+ const modifier = event.ctrlKey || event.metaKey;
818
+ if (modifier && event.key.toLowerCase() === 'z') {
819
+ event.preventDefault();
820
+ restoreHistory(historyIndex + (event.shiftKey ? 1 : -1));
821
+ } else if (modifier && event.key.toLowerCase() === 'y') {
822
+ event.preventDefault();
823
+ restoreHistory(historyIndex + 1);
824
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedId) {
825
+ event.preventDefault();
826
+ deleteSelectedNode();
827
+ }
828
+ });
829
+ document.addEventListener('keyup', (event) => {
830
+ if (event.code === 'Space') spacePressed = false;
831
+ });
832
+ window.addEventListener('blur', () => { spacePressed = false; });
833
+
392
834
  byId('copy').onclick = async () => {
393
835
  try {
394
836
  const handoff = await api('/api/handoff?audience=developer');
@@ -440,10 +882,14 @@ byId('install').onclick = async () => {
440
882
  try {
441
883
  await api('/api/install', {
442
884
  method: 'POST',
443
- body: JSON.stringify({ recipe: draft, replace: catalog.recipes.some((recipe) => recipe.id === draft.id) })
885
+ body: JSON.stringify({
886
+ recipe: draft,
887
+ layout: layoutPayload(),
888
+ replace: catalog.recipes.some((recipe) => recipe.id === draft.id)
889
+ })
444
890
  });
445
891
  byId('confirm').close();
446
- notify('Recipe installed atomically.');
892
+ notify('Recipe and private canvas layout installed atomically.');
447
893
  await refreshCatalog(draft.id);
448
894
  await loadRecipe();
449
895
  } catch (error) {
@@ -458,4 +904,25 @@ function notify(text) {
458
904
  setTimeout(() => { message.style.display = 'none'; }, 4000);
459
905
  }
460
906
 
907
+ async function initialize() {
908
+ await refreshCatalog('default');
909
+ byId('recipe').onchange = loadRecipe;
910
+ bindCanvas();
911
+ byId('toggle-library').onclick = () => byId('library-panel').classList.toggle('open');
912
+ byId('quick-add').onclick = () => byId('library-panel').classList.add('open');
913
+ byId('close-library').onclick = () => byId('library-panel').classList.remove('open');
914
+ byId('workflow-settings').onclick = () => {
915
+ selectedId = null;
916
+ updateSelection();
917
+ renderRecipeDetails();
918
+ byId('inspector-panel').classList.add('open');
919
+ };
920
+ byId('close-inspector').onclick = () => byId('inspector-panel').classList.remove('open');
921
+ byId('toggle-execution').onclick = () => byId('execution-panel').classList.toggle('open');
922
+ byId('close-execution').onclick = () => byId('execution-panel').classList.remove('open');
923
+ await loadRecipe();
924
+ clearInterval(liveTimer);
925
+ liveTimer = setInterval(refreshLive, 1800);
926
+ }
927
+
461
928
  initialize().catch((error) => notify(error.message));