@salesforce/metadata-plugins 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/index.d.ts +4 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +9 -2
  4. package/dist/plugins/agent/AgentParser.d.ts +34 -0
  5. package/dist/plugins/agent/AgentParser.d.ts.map +1 -0
  6. package/dist/plugins/agent/AgentParser.js +189 -0
  7. package/dist/plugins/agent/AgentVisualizer.d.ts +27 -0
  8. package/dist/plugins/agent/AgentVisualizer.d.ts.map +1 -0
  9. package/dist/plugins/agent/AgentVisualizer.js +36 -0
  10. package/dist/plugins/agent/extract/assertNever.d.ts +23 -0
  11. package/dist/plugins/agent/extract/assertNever.d.ts.map +1 -0
  12. package/dist/plugins/agent/extract/assertNever.js +24 -0
  13. package/dist/plugins/agent/extract/ast-to-graph.d.ts +137 -0
  14. package/dist/plugins/agent/extract/ast-to-graph.d.ts.map +1 -0
  15. package/dist/plugins/agent/extract/ast-to-graph.js +523 -0
  16. package/dist/plugins/agent/extract/ast-utils.d.ts +61 -0
  17. package/dist/plugins/agent/extract/ast-utils.d.ts.map +1 -0
  18. package/dist/plugins/agent/extract/ast-utils.js +7 -0
  19. package/dist/plugins/agent/extract/parseNamespacedRef.d.ts +31 -0
  20. package/dist/plugins/agent/extract/parseNamespacedRef.d.ts.map +1 -0
  21. package/dist/plugins/agent/extract/parseNamespacedRef.js +31 -0
  22. package/dist/plugins/agent/extract/reasoningParser.d.ts +112 -0
  23. package/dist/plugins/agent/extract/reasoningParser.d.ts.map +1 -0
  24. package/dist/plugins/agent/extract/reasoningParser.js +804 -0
  25. package/dist/plugins/agent/types/AgentScriptData.d.ts +31 -0
  26. package/dist/plugins/agent/types/AgentScriptData.d.ts.map +1 -0
  27. package/dist/plugins/agent/types/AgentScriptData.js +7 -0
  28. package/dist/plugins/agent/ui/assets/index-CTzSDPPx.css +1 -0
  29. package/dist/plugins/agent/ui/assets/index-D0wb9GBs.js +71 -0
  30. package/dist/plugins/agent/ui/index.html +14 -0
  31. package/dist/plugins/flexipage/FlexipageParser.d.ts +1 -1
  32. package/dist/plugins/flexipage/FlexipageParser.js +1 -1
  33. package/dist/plugins/flexipage/FlexipageVisualizer.d.ts +1 -1
  34. package/dist/plugins/flexipage/FlexipageVisualizer.d.ts.map +1 -1
  35. package/dist/plugins/flexipage/FlexipageVisualizer.js +3 -1
  36. package/dist/plugins/flexipage/transformer/FlexipageToUemTransformer.d.ts +1 -1
  37. package/dist/plugins/flexipage/transformer/FlexipageToUemTransformer.js +1 -1
  38. package/dist/plugins/flexipage/transformer/FlexipageTransformerUtils.d.ts +1 -1
  39. package/dist/plugins/flexipage/transformer/FlexipageTransformerUtils.js +1 -1
  40. package/dist/plugins/flexipage/types/FlexipageMetadata.d.ts +1 -1
  41. package/dist/plugins/flexipage/types/FlexipageMetadata.js +1 -1
  42. package/dist/plugins/schema/SchemaParser.d.ts +1 -1
  43. package/dist/plugins/schema/SchemaParser.js +1 -1
  44. package/dist/plugins/schema/SchemaVisualizer.d.ts +1 -1
  45. package/dist/plugins/schema/SchemaVisualizer.d.ts.map +1 -1
  46. package/dist/plugins/schema/SchemaVisualizer.js +2 -1
  47. package/dist/plugins/schema/types/SchemaERDData.d.ts +1 -1
  48. package/dist/plugins/schema/types/SchemaERDData.js +1 -1
  49. package/dist/shared/bootstrap/createPluginApp.d.ts +1 -1
  50. package/dist/shared/bootstrap/createPluginApp.js +1 -1
  51. package/dist/shared/components/ErrorBoundary.d.ts +1 -1
  52. package/dist/shared/components/ErrorBoundary.js +1 -1
  53. package/dist/shared/uem/transformer/ITransformer.d.ts +1 -1
  54. package/dist/shared/uem/transformer/ITransformer.js +1 -1
  55. package/dist/shared/uem/transformer/TransformerRegistry.d.ts +1 -1
  56. package/dist/shared/uem/transformer/TransformerRegistry.js +1 -1
  57. package/dist/shared/uem/transformer/UemBasedVisualizer.d.ts +1 -1
  58. package/dist/shared/uem/transformer/UemBasedVisualizer.js +1 -1
  59. package/dist/shared/uem/types/UemMetadata.d.ts +1 -1
  60. package/dist/shared/uem/types/UemMetadata.js +1 -1
  61. package/dist/shared/uem/ui/components/PropertyRenderer/PropertyRenderer.d.ts +1 -1
  62. package/dist/shared/uem/ui/components/PropertyRenderer/PropertyRenderer.js +1 -1
  63. package/dist/shared/uem/ui/components/UEMVisualization/UEMVisualization.d.ts +1 -1
  64. package/dist/shared/uem/ui/components/UEMVisualization/UEMVisualization.js +1 -1
  65. package/dist/shared/utils/isPluginError.d.ts +1 -1
  66. package/dist/shared/utils/isPluginError.js +1 -1
  67. package/dist/shared/utils/patternMatcher.d.ts +1 -1
  68. package/dist/shared/utils/patternMatcher.js +1 -1
  69. package/dist/shared/utils/uemTreeUtils.d.ts +1 -1
  70. package/dist/shared/utils/uemTreeUtils.js +1 -1
  71. package/dist/shared/utils/vizDependentPathsHelper.d.ts +1 -1
  72. package/dist/shared/utils/vizDependentPathsHelper.js +1 -1
  73. package/package.json +6 -3
@@ -0,0 +1,804 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.
3
+ * All rights reserved.
4
+ * Licensed under the BSD 3-Clause license.
5
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6
+ **/
7
+ /**
8
+ * Heuristic parser that lifts the prose inside `reasoning.instructions`
9
+ * into a structured tree of blocks for the detail panel to render.
10
+ *
11
+ * The agentscript parser exposes `instructions:` only as a flattened
12
+ * template string, so we re-derive the structure here. Supported shapes:
13
+ *
14
+ * **Label**: identifier → declaration block
15
+ * ## Heading → header block (1-6 levels)
16
+ * - bullet item → bullet block
17
+ * 1. numbered item → numbered block
18
+ * If <expr> → if block; following indented
19
+ * <body> lines become its body. The
20
+ * condition supports multiple
21
+ * clauses joined by `And` / `Or`.
22
+ * If <expr> → <consequent> → inline consequent (no body)
23
+ * anything else → prose block
24
+ *
25
+ * Inline content (used inside every block body / consequent) supports
26
+ * **bold**, snake_case identifiers, `@variables.X` refs, and `→` arrows.
27
+ * Quoted strings are left as plain text so any identifiers nested inside
28
+ * them (e.g. `"...vai su order_url_over5"`) still surface as chips.
29
+ *
30
+ * The parser is forgiving — anything it can't classify falls through to
31
+ * a prose block so the renderer still shows every line.
32
+ */
33
+ import { assertNever } from './assertNever.js';
34
+ /**
35
+ * Recursion cap for the block parser. Agent reasoning bodies are authored by
36
+ * hand and never reach this depth; the cap is a defence against pathological
37
+ * or adversarial input (e.g. thousands of leading-indent levels) causing a
38
+ * stack overflow inside the webview.
39
+ */
40
+ const MAX_BLOCK_DEPTH = 64;
41
+ /**
42
+ * Cap the length of a single clause text passed to the comparison regexes.
43
+ * The patterns use bounded greedy/lazy quantifiers (`.+?` / `.+`) which are
44
+ * safe but can still spike CPU on adversarial input. Anything longer than
45
+ * this is treated as a single-left-side clause with no comparison.
46
+ */
47
+ const MAX_CLAUSE_LENGTH = 4096;
48
+ /** Top-level entry point. Returns the structured tree of blocks. */
49
+ export function parseReasoning(text) {
50
+ const lines = preprocessLines(text);
51
+ const { blocks } = parseBlocks(lines, 0, -1, 0);
52
+ return blocks;
53
+ }
54
+ /** True when the parser produced at least one structural block. */
55
+ export function hasStructure(blocks) {
56
+ return blocks.some((b) => b.kind === 'if' ||
57
+ b.kind === 'run' ||
58
+ b.kind === 'set' ||
59
+ b.kind === 'transition' ||
60
+ b.kind === 'declaration' ||
61
+ b.kind === 'header' ||
62
+ b.kind === 'bullet' ||
63
+ b.kind === 'numbered');
64
+ }
65
+ /**
66
+ * Collect identifier names that match a known action set, walking the
67
+ * block tree in source order. Used by the header flow strip as a
68
+ * navigation aid.
69
+ */
70
+ export function collectActionRefs(blocks, actionNames) {
71
+ const out = [];
72
+ const seen = new Set();
73
+ const push = (name) => {
74
+ if (actionNames.has(name) && !seen.has(name)) {
75
+ seen.add(name);
76
+ out.push(name);
77
+ }
78
+ };
79
+ const walkInline = (parts) => {
80
+ for (const p of parts) {
81
+ if (p.kind === 'ident') {
82
+ push(p.name);
83
+ }
84
+ else if (p.kind === 'bold') {
85
+ walkInline(p.children);
86
+ }
87
+ }
88
+ };
89
+ const walkClauses = (cs) => {
90
+ for (const c of cs) {
91
+ if (c.group) {
92
+ walkClauses(c.group);
93
+ continue;
94
+ }
95
+ push(c.left);
96
+ if (!c.rightIsString) {
97
+ push(c.right);
98
+ }
99
+ }
100
+ };
101
+ const walk = (b) => {
102
+ switch (b.kind) {
103
+ case 'if':
104
+ walkClauses(b.clauses);
105
+ if (b.consequent) {
106
+ walkInline(b.consequent);
107
+ }
108
+ for (const child of b.body) {
109
+ walk(child);
110
+ }
111
+ if (b.elseBody) {
112
+ for (const child of b.elseBody) {
113
+ walk(child);
114
+ }
115
+ }
116
+ break;
117
+ case 'run':
118
+ push(stripAt(b.action));
119
+ break;
120
+ case 'set':
121
+ push(stripAt(b.target));
122
+ if (!b.valueIsString) {
123
+ push(stripAt(b.value));
124
+ }
125
+ break;
126
+ case 'transition':
127
+ push(stripAt(b.target));
128
+ break;
129
+ case 'declaration':
130
+ push(b.value);
131
+ walkInline(b.label);
132
+ break;
133
+ case 'header':
134
+ case 'bullet':
135
+ case 'numbered':
136
+ case 'prose':
137
+ walkInline(b.inline);
138
+ break;
139
+ default:
140
+ assertNever(b);
141
+ }
142
+ };
143
+ for (const b of blocks) {
144
+ walk(b);
145
+ }
146
+ return out;
147
+ }
148
+ function preprocessLines(text) {
149
+ return text
150
+ .split(/\r?\n/)
151
+ .map((raw) => {
152
+ const match = raw.match(/^[ \t]*/);
153
+ const lead = match ? match[0] : '';
154
+ // Treat each tab as 4 spaces so mixed indentation still compares.
155
+ const indent = lead.replace(/\t/g, ' ').length;
156
+ const trimmed = raw.replace(/^[ \t]+/, '').replace(/\s+$/, '');
157
+ return { indent, trimmed };
158
+ })
159
+ .filter((l) => l.trimmed.length > 0);
160
+ }
161
+ /**
162
+ * Recursively consume lines whose indent is strictly greater than
163
+ * `parentIndent`. Each `If` line opens a nested scope.
164
+ */
165
+ function parseBlocks(lines, startIdx, parentIndent, depth,
166
+ /**
167
+ * True when the current scope is the body of an `If` (or `else`) block.
168
+ * Nested `if` lines inside an existing If body are demoted to prose so
169
+ * the visual hierarchy stays flat — only the outermost branch becomes a
170
+ * structural If card. The inner `if` still reads as a regular sentence.
171
+ */
172
+ insideIf = false) {
173
+ const blocks = [];
174
+ let i = startIdx;
175
+ // Hit the depth cap → render the remainder of the indented region as flat
176
+ // prose lines so nothing is silently dropped, and bail out without recursing.
177
+ if (depth >= MAX_BLOCK_DEPTH) {
178
+ while (i < lines.length && lines[i].indent > parentIndent) {
179
+ blocks.push({ kind: 'prose', inline: parseInline(lines[i].trimmed) });
180
+ i++;
181
+ }
182
+ return { blocks, nextIdx: i };
183
+ }
184
+ while (i < lines.length) {
185
+ const line = lines[i];
186
+ if (line.indent <= parentIndent) {
187
+ break;
188
+ }
189
+ const ifMatch = matchIfLine(line.trimmed);
190
+ if (ifMatch) {
191
+ const clauses = parseConditionExpr(ifMatch.conditionText);
192
+ // If the condition references no variables / identifiers, treat the
193
+ // whole `If ...` line as prose — it's narrative rather than a real
194
+ // branch. Any following indented lines fall through to be parsed as
195
+ // siblings at this scope.
196
+ //
197
+ // Also demote when the condition itself contains another `if` word —
198
+ // e.g. "If we should check if the order is valid". That second `if`
199
+ // means the leading `If` is part of an English sentence, not a real
200
+ // branch keyword.
201
+ // When already inside an If body, demote any further `if` line to
202
+ // prose so we don't render nested If cards — the visual hierarchy
203
+ // stays one level deep and the nested condition reads as text.
204
+ // Indented follow-on lines belonging to that nested `if` are NOT
205
+ // re-parsed as structure either; they fall through this loop and
206
+ // get picked up by the regular block matchers at their own indent.
207
+ if (insideIf) {
208
+ blocks.push({ kind: 'prose', inline: parseInline(line.trimmed) });
209
+ i++;
210
+ continue;
211
+ }
212
+ if (!clausesHaveVariables(clauses) || containsInnerIf(ifMatch.conditionText)) {
213
+ blocks.push({ kind: 'prose', inline: parseInline(line.trimmed) });
214
+ i++;
215
+ continue;
216
+ }
217
+ const consequent = ifMatch.consequent ? parseInline(ifMatch.consequent) : undefined;
218
+ const { blocks: body, nextIdx } = parseBlocks(lines, i + 1, line.indent, depth + 1, true);
219
+ let nextI = nextIdx;
220
+ // If the very next sibling is an `else:` at the same indent, attach it.
221
+ let elseBody;
222
+ if (nextI < lines.length &&
223
+ lines[nextI].indent === line.indent &&
224
+ /^else\s*:?\s*$/i.test(lines[nextI].trimmed)) {
225
+ const { blocks: eBody, nextIdx: nextAfterElse } = parseBlocks(lines, nextI + 1, line.indent, depth + 1, true);
226
+ elseBody = eBody;
227
+ nextI = nextAfterElse;
228
+ }
229
+ blocks.push({ kind: 'if', clauses, consequent, body, elseBody });
230
+ i = nextI;
231
+ continue;
232
+ }
233
+ const runMatch = matchRunLine(line.trimmed);
234
+ if (runMatch) {
235
+ const { clauses: runClauses, nextIdx } = parseRunClauses(lines, i + 1, line.indent);
236
+ // A run with no `with` (input) and no `set` (output) clauses carries
237
+ // no I/O — render it as prose instead of a structural Run row. A
238
+ // `to`-only run still has no inputs/outputs, so it demotes too. Emit
239
+ // every consumed line (header + indented clauses) as prose so the
240
+ // indented `to @x` doesn't get re-parsed as an orphan transition.
241
+ const hasIO = runClauses.some((c) => c.kind === 'with' || c.kind === 'set');
242
+ if (!hasIO) {
243
+ for (let j = i; j < nextIdx; j++) {
244
+ blocks.push({ kind: 'prose', inline: parseInline(lines[j].trimmed) });
245
+ }
246
+ i = nextIdx;
247
+ continue;
248
+ }
249
+ blocks.push({ kind: 'run', action: runMatch.action, clauses: runClauses });
250
+ i = nextIdx;
251
+ continue;
252
+ }
253
+ const setMatch = matchSetLine(line.trimmed);
254
+ if (setMatch) {
255
+ blocks.push({
256
+ kind: 'set',
257
+ target: setMatch.target,
258
+ value: setMatch.value,
259
+ valueIsString: setMatch.valueIsString,
260
+ });
261
+ i++;
262
+ continue;
263
+ }
264
+ const toMatch = matchTransitionLine(line.trimmed);
265
+ if (toMatch) {
266
+ blocks.push({ kind: 'transition', target: toMatch.target });
267
+ i++;
268
+ continue;
269
+ }
270
+ const headerMatch = line.trimmed.match(/^(#{2,6})\s+(.+)$/);
271
+ if (headerMatch) {
272
+ blocks.push({
273
+ kind: 'header',
274
+ level: headerMatch[1].length,
275
+ inline: parseInline(headerMatch[2]),
276
+ });
277
+ i++;
278
+ continue;
279
+ }
280
+ const bulletMatch = line.trimmed.match(/^[-*+]\s+(.+)$/);
281
+ if (bulletMatch) {
282
+ blocks.push({ kind: 'bullet', inline: parseInline(bulletMatch[1]) });
283
+ i++;
284
+ continue;
285
+ }
286
+ const numberedMatch = line.trimmed.match(/^(\d+)[.)]\s+(.+)$/);
287
+ if (numberedMatch) {
288
+ blocks.push({
289
+ kind: 'numbered',
290
+ n: parseInt(numberedMatch[1], 10),
291
+ inline: parseInline(numberedMatch[2]),
292
+ });
293
+ i++;
294
+ continue;
295
+ }
296
+ const declMatch = line.trimmed.match(/^(\*\*[^*\n]+\*\*[^:\n]*)\s*:\s*([a-z][a-z0-9]*(?:_[a-z0-9]+)+)\s*$/);
297
+ if (declMatch) {
298
+ blocks.push({
299
+ kind: 'declaration',
300
+ label: parseInline(declMatch[1].trim()),
301
+ value: declMatch[2],
302
+ });
303
+ i++;
304
+ continue;
305
+ }
306
+ blocks.push({ kind: 'prose', inline: parseInline(line.trimmed) });
307
+ i++;
308
+ }
309
+ return { blocks, nextIdx: i };
310
+ }
311
+ /**
312
+ * Match a line that begins with `If` (case-insensitive). When the line
313
+ * contains `→` / `->`, the text after the arrow is captured as an inline
314
+ * consequent — these `If X → Y` forms render without an indented body.
315
+ */
316
+ /** Strip the leading `@` from a variable/action reference, if present. */
317
+ function stripAt(s) {
318
+ return s.startsWith('@') ? s.slice(1) : s;
319
+ }
320
+ /**
321
+ * True when the condition references at least one `@variables.X` (or
322
+ * `@system_variables.X`) ref. An `If` line that only references actions /
323
+ * outputs / subagents / utils — or that has no `@`-ref at all — is narrative
324
+ * prose and must not render as a structural branch. Only conditions that
325
+ * gate on a real variable earn an If card.
326
+ *
327
+ * Note: prior versions treated any snake_case identifier or comparison
328
+ * operator as "structural", which over-matched English sentences like
329
+ * `If status_code is unclear`. An intermediate version relaxed this to any
330
+ * `@`-prefixed ref, which still over-matched lines like
331
+ * `If @actions.foo returns success`. The stricter `@variables`-only rule
332
+ * eliminates both false-positive classes at the cost of demoting genuinely
333
+ * structural conditions that omit the `@variables` prefix — those should be
334
+ * flagged to the script author to add the prefix rather than be silently
335
+ * rescued here.
336
+ */
337
+ function clausesHaveVariables(clauses) {
338
+ for (const c of clauses) {
339
+ if (c.group && clausesHaveVariables(c.group)) {
340
+ return true;
341
+ }
342
+ if (looksLikeVariable(c.left)) {
343
+ return true;
344
+ }
345
+ if (!c.rightIsString && looksLikeVariable(c.right)) {
346
+ return true;
347
+ }
348
+ }
349
+ return false;
350
+ }
351
+ const VAR_REF_RE = /@(?:system_)?variables\.\w/;
352
+ function looksLikeVariable(s) {
353
+ if (!s) {
354
+ return false;
355
+ }
356
+ return VAR_REF_RE.test(s);
357
+ }
358
+ /**
359
+ * True when the condition text contains a standalone `if` word (case
360
+ * insensitive). Used to demote `If ... if ...` lines like
361
+ * "If we should check if the order is valid" to prose — the second `if`
362
+ * gives away that the leading `If` is English, not a branch keyword.
363
+ *
364
+ * Skips matches inside quoted strings so a literal like
365
+ * `If status == "completed if reviewed"` stays a real branch.
366
+ */
367
+ function containsInnerIf(s) {
368
+ if (!s) {
369
+ return false;
370
+ }
371
+ // Strip double-quoted string literals so `"... if ..."` doesn't count.
372
+ const stripped = s.replace(/"(?:[^"\\]|\\.)*"/g, '');
373
+ return /\bif\b/i.test(stripped);
374
+ }
375
+ /**
376
+ * Replace every double-quoted string in `s` with spaces of the same length,
377
+ * so callers can scan for delimiters (`→`, `->`, `and`, `or`, ...) without
378
+ * mis-firing on characters inside string literals — while keeping the
379
+ * resulting indices aligned with the original text for slicing.
380
+ */
381
+ function maskQuotedStrings(s) {
382
+ return s.replace(/"(?:[^"\\]|\\.)*"/g, (m) => ' '.repeat(m.length));
383
+ }
384
+ function matchRunLine(line) {
385
+ const m = line.match(/^run\s+(@?[\w.]+)\s*:?\s*$/i);
386
+ if (!m) {
387
+ return null;
388
+ }
389
+ return { action: m[1] };
390
+ }
391
+ function matchSetLine(line) {
392
+ const m = line.match(/^set\s+(@?[\w.]+)\s*=\s*(.+)$/i);
393
+ if (!m) {
394
+ return null;
395
+ }
396
+ const raw = m[2].trim();
397
+ const isString = /^"(?:[^"\\]|\\.)*"$/.test(raw);
398
+ return {
399
+ target: m[1],
400
+ value: isString ? raw.slice(1, -1) : raw,
401
+ valueIsString: isString,
402
+ };
403
+ }
404
+ function matchTransitionLine(line) {
405
+ // Accepts `to @x`, `transition @x`, or `transition to @x` — the agentscript
406
+ // source uses any of these forms interchangeably.
407
+ const m = line.match(/^(?:transition\s+to|transition|to)\s+(@?[\w.]+)\s*$/i);
408
+ if (!m) {
409
+ return null;
410
+ }
411
+ return { target: m[1] };
412
+ }
413
+ /**
414
+ * Consume the indented clauses that follow a `run` line. Each clause is one
415
+ * of `with X = Y`, `set @X = Y`, or `to @X`. Stops at the first line whose
416
+ * indent is `<= parentIndent` or whose content is none of the above.
417
+ */
418
+ function parseRunClauses(lines, startIdx, parentIndent) {
419
+ const clauses = [];
420
+ let i = startIdx;
421
+ while (i < lines.length) {
422
+ const line = lines[i];
423
+ if (line.indent <= parentIndent) {
424
+ break;
425
+ }
426
+ const withMatch = line.trimmed.match(/^with\s+(@?[\w.]+)\s*=\s*(.+)$/i);
427
+ if (withMatch) {
428
+ const raw = withMatch[2].trim();
429
+ const isString = /^"(?:[^"\\]|\\.)*"$/.test(raw);
430
+ clauses.push({
431
+ kind: 'with',
432
+ target: withMatch[1],
433
+ value: isString ? raw.slice(1, -1) : raw,
434
+ valueIsString: isString,
435
+ });
436
+ i++;
437
+ continue;
438
+ }
439
+ const setMatch = line.trimmed.match(/^set\s+(@?[\w.]+)\s*=\s*(.+)$/i);
440
+ if (setMatch) {
441
+ const raw = setMatch[2].trim();
442
+ const isString = /^"(?:[^"\\]|\\.)*"$/.test(raw);
443
+ clauses.push({
444
+ kind: 'set',
445
+ target: setMatch[1],
446
+ value: isString ? raw.slice(1, -1) : raw,
447
+ valueIsString: isString,
448
+ });
449
+ i++;
450
+ continue;
451
+ }
452
+ const toMatch = line.trimmed.match(/^(?:transition\s+to|transition|to)\s+(@?[\w.]+)\s*$/i);
453
+ if (toMatch) {
454
+ clauses.push({ kind: 'to', target: toMatch[1] });
455
+ i++;
456
+ continue;
457
+ }
458
+ break;
459
+ }
460
+ return { clauses, nextIdx: i };
461
+ }
462
+ function matchIfLine(line) {
463
+ const m = line.match(/^if\s+(.+)$/i);
464
+ if (!m) {
465
+ return null;
466
+ }
467
+ // Strip trailing `:` (agentscript Python-style block) before parsing.
468
+ const body = m[1].replace(/\s*:\s*$/, '');
469
+ // Arrow split for the inline-consequent form `If X → Y`. The unicode `→`
470
+ // tolerates optional whitespace on either side, but ASCII `->` MUST be
471
+ // surrounded by whitespace — otherwise code-like content such as
472
+ // `response->status` would be mis-parsed as condition=`response` /
473
+ // consequent=`status`.
474
+ //
475
+ // Mask quoted strings first (same length so offsets stay aligned) so an
476
+ // arrow inside a string literal like `"a → b"` doesn't split the line.
477
+ //
478
+ // Anchor the match on the arrow glyph itself — do NOT include leading
479
+ // whitespace. Masking blanks quoted literals to spaces, so a leading `\s*`
480
+ // would greedily swallow the run of whitespace that used to be a masked
481
+ // literal (e.g. `== "done" → x` → the `\s*` consumes `"done"`'s mask and
482
+ // the RHS gets sliced off). `.trim()` on the condition and consequent
483
+ // handles the surrounding whitespace instead.
484
+ const masked = maskQuotedStrings(body);
485
+ const arrowMatch = masked.match(/→|(?<=\s)->(?=\s)/);
486
+ if (arrowMatch && arrowMatch.index !== undefined && arrowMatch.index > 0) {
487
+ const idx = arrowMatch.index;
488
+ const conditionText = body.slice(0, idx).trim();
489
+ const consequent = body.slice(idx + arrowMatch[0].length).trim();
490
+ if (conditionText.length > 0 && consequent.length > 0) {
491
+ return { conditionText, consequent };
492
+ }
493
+ }
494
+ return { conditionText: body.trim() };
495
+ }
496
+ /**
497
+ * Split a condition expression into clauses joined by `And` / `Or`.
498
+ * Each clause supports the standard comparison operators. Predicate
499
+ * clauses without an explicit operator (e.g. `X is empty`) survive as
500
+ * a single-left-side clause with op `=` and empty right side, so the
501
+ * renderer can show them as a lone variable chip.
502
+ */
503
+ /**
504
+ * Split a condition body on top-level `and` / `or` keywords, ignoring any
505
+ * that appear inside parens or quoted strings. Returns an alternating list
506
+ * `[clause, joiner, clause, joiner, ...]` matching `String.split` shape.
507
+ */
508
+ function splitTopLevelLogical(text) {
509
+ const out = [];
510
+ let buf = '';
511
+ let depth = 0;
512
+ let inStr = false;
513
+ let i = 0;
514
+ const lower = text.toLowerCase();
515
+ while (i < text.length) {
516
+ const ch = text[i];
517
+ if (inStr) {
518
+ buf += ch;
519
+ // Preserve `\"` escapes: keep the escaped char as literal content.
520
+ if (ch === '\\' && i + 1 < text.length) {
521
+ buf += text[i + 1];
522
+ i += 2;
523
+ continue;
524
+ }
525
+ if (ch === '"') {
526
+ inStr = false;
527
+ }
528
+ i++;
529
+ continue;
530
+ }
531
+ if (ch === '"') {
532
+ inStr = true;
533
+ buf += ch;
534
+ i++;
535
+ continue;
536
+ }
537
+ if (ch === '(') {
538
+ depth++;
539
+ buf += ch;
540
+ i++;
541
+ continue;
542
+ }
543
+ if (ch === ')') {
544
+ depth = Math.max(0, depth - 1);
545
+ buf += ch;
546
+ i++;
547
+ continue;
548
+ }
549
+ if (depth === 0 && /\s/.test(ch)) {
550
+ // Look ahead for `and` / `or` surrounded by whitespace.
551
+ const rest = lower.slice(i);
552
+ const m = rest.match(/^\s+(and|or)\s+/);
553
+ if (m) {
554
+ out.push(buf.trim());
555
+ out.push(m[1]);
556
+ buf = '';
557
+ i += m[0].length;
558
+ continue;
559
+ }
560
+ }
561
+ buf += ch;
562
+ i++;
563
+ }
564
+ out.push(buf.trim());
565
+ return out;
566
+ }
567
+ /**
568
+ * True when the entire string is wrapped in a single matching pair of parens —
569
+ * i.e. the opening `(` closes only at the very last character. Distinguishes
570
+ * `(A and B)` (wrapped) from `(A) and (B)` (not wrapped).
571
+ */
572
+ function isFullyWrapped(s) {
573
+ if (!s.startsWith('(') || !s.endsWith(')')) {
574
+ return false;
575
+ }
576
+ let depth = 0;
577
+ let inStr = false;
578
+ for (let i = 0; i < s.length; i++) {
579
+ const ch = s[i];
580
+ if (inStr) {
581
+ if (ch === '\\' && i + 1 < s.length) {
582
+ i++;
583
+ continue;
584
+ }
585
+ if (ch === '"') {
586
+ inStr = false;
587
+ }
588
+ continue;
589
+ }
590
+ if (ch === '"') {
591
+ inStr = true;
592
+ continue;
593
+ }
594
+ if (ch === '(') {
595
+ depth++;
596
+ }
597
+ else if (ch === ')') {
598
+ depth--;
599
+ if (depth === 0 && i !== s.length - 1) {
600
+ return false;
601
+ }
602
+ }
603
+ }
604
+ return depth === 0;
605
+ }
606
+ function parseConditionExpr(text) {
607
+ // Strip a single set of outer parens so `(A or B) and C` still tokenizes.
608
+ // After building the flat clause list we re-group `and`-runs so the
609
+ // renderer shows standard `and`-before-`or` precedence.
610
+ let body = text.trim();
611
+ if (isFullyWrapped(body)) {
612
+ body = body.slice(1, -1).trim();
613
+ }
614
+ // Guard against pathological input — anything longer than the cap is
615
+ // treated as a single bare-left clause so the regex matchers below run on
616
+ // bounded input.
617
+ if (body.length > MAX_CLAUSE_LENGTH) {
618
+ return [{ left: body.slice(0, MAX_CLAUSE_LENGTH), op: '=', right: '', rightIsString: false }];
619
+ }
620
+ const parts = splitTopLevelLogical(body);
621
+ const clauses = [];
622
+ for (let i = 0; i < parts.length; i += 2) {
623
+ let clauseText = parts[i].trim();
624
+ const joinerRaw = i > 0 ? parts[i - 1].toLowerCase() : undefined;
625
+ const joiner = joinerRaw === 'and' || joinerRaw === 'or' ? joinerRaw : undefined;
626
+ // Unary `not <expr>` prefix on the clause.
627
+ let negate = false;
628
+ const notMatch = clauseText.match(/^not\s+(.+)$/i);
629
+ if (notMatch) {
630
+ negate = true;
631
+ clauseText = notMatch[1].trim();
632
+ }
633
+ // Parenthesized sub-expression — recurse so `(A or B) and C` keeps the
634
+ // inner OR as a nested clause list.
635
+ if (isFullyWrapped(clauseText)) {
636
+ const inner = parseConditionExpr(clauseText.slice(1, -1));
637
+ if (inner.length > 1) {
638
+ clauses.push({
639
+ joiner,
640
+ ...(negate ? { negate: true } : {}),
641
+ left: '',
642
+ op: '=',
643
+ right: '',
644
+ rightIsString: false,
645
+ group: inner,
646
+ });
647
+ continue;
648
+ }
649
+ // Single inner clause — flatten back to plain text so downstream
650
+ // matching still works.
651
+ clauseText = clauseText.slice(1, -1).trim();
652
+ }
653
+ // `is not` / `is` identity checks (Python-style). Match before `==`/`!=`
654
+ // since the keyword form is otherwise ambiguous with bare idents.
655
+ const isMatch = clauseText.match(/^(.+?)\s+(is\s+not|is)\s+(.+)$/i);
656
+ if (isMatch) {
657
+ const op = /^is\s+not$/i.test(isMatch[2]) ? 'is not' : 'is';
658
+ const right = isMatch[3].trim();
659
+ const rightIsString = /^"(?:[^"\\]|\\.)*"$/.test(right);
660
+ clauses.push({
661
+ joiner,
662
+ ...(negate ? { negate: true } : {}),
663
+ left: isMatch[1].trim(),
664
+ op,
665
+ right: rightIsString ? right.slice(1, -1) : right,
666
+ rightIsString,
667
+ });
668
+ continue;
669
+ }
670
+ const cmpMatch = clauseText.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/);
671
+ if (cmpMatch) {
672
+ const right = cmpMatch[3].trim();
673
+ const isString = /^"(?:[^"\\]|\\.)*"$/.test(right);
674
+ clauses.push({
675
+ joiner,
676
+ ...(negate ? { negate: true } : {}),
677
+ left: cmpMatch[1].trim(),
678
+ op: cmpMatch[2],
679
+ right: isString ? right.slice(1, -1) : right,
680
+ rightIsString: isString,
681
+ });
682
+ }
683
+ else {
684
+ clauses.push({
685
+ joiner,
686
+ ...(negate ? { negate: true } : {}),
687
+ left: clauseText,
688
+ op: '=',
689
+ right: '',
690
+ rightIsString: false,
691
+ });
692
+ }
693
+ }
694
+ return regroupByPrecedence(clauses);
695
+ }
696
+ /**
697
+ * Re-bind a flat clause list so `and` has higher precedence than `or`.
698
+ * `A or B and C` → `A or (B and C)` (the `and`-run becomes a `group`).
699
+ * No-op when the list mixes only one joiner kind.
700
+ */
701
+ function regroupByPrecedence(clauses) {
702
+ if (clauses.length < 2) {
703
+ return clauses;
704
+ }
705
+ const joiners = clauses.slice(1).map((c) => c.joiner);
706
+ const hasAnd = joiners.includes('and');
707
+ const hasOr = joiners.includes('or');
708
+ if (!hasAnd || !hasOr) {
709
+ return clauses;
710
+ }
711
+ const out = [];
712
+ let i = 0;
713
+ while (i < clauses.length) {
714
+ // Greedily collect an `and`-run starting at i.
715
+ let j = i + 1;
716
+ while (j < clauses.length && clauses[j].joiner === 'and') {
717
+ j++;
718
+ }
719
+ const run = clauses.slice(i, j);
720
+ if (run.length === 1) {
721
+ out.push(run[0]);
722
+ }
723
+ else {
724
+ // Re-anchor the run as a `group`; first clause's joiner inside the
725
+ // group is undefined, the group itself inherits the run-head joiner.
726
+ const inner = run.map((c, idx) => (idx === 0 ? { ...c, joiner: undefined } : c));
727
+ out.push({
728
+ joiner: run[0].joiner,
729
+ left: '',
730
+ op: '=',
731
+ right: '',
732
+ rightIsString: false,
733
+ group: inner,
734
+ });
735
+ }
736
+ i = j;
737
+ }
738
+ return out;
739
+ }
740
+ /** Single-pass inline tokenizer for the body of a block. */
741
+ export function parseInline(text) {
742
+ // Strip agentscript merge-field wrappers `{! ... }` — the surrounding
743
+ // braces add visual noise around what is otherwise a normal reference
744
+ // chip. The inner content keeps tokenizing as usual.
745
+ text = text.replace(/\{!\s*([\s\S]*?)\s*\}/g, '$1');
746
+ const out = [];
747
+ // Anchors:
748
+ // \*\*[^*\n]+\*\* bold
749
+ // @<namespace>.X namespaced reference (rendered via RefChip).
750
+ // Recognized namespaces (per the rules doc §9 / §10):
751
+ // - variables / actions / action / subagent
752
+ // - system_variables (e.g. user_input)
753
+ // - utils (escalate, setVariables, end_session, ...)
754
+ // - outputs (named output of the enclosing run)
755
+ // - MessagingSession / MessagingEndUser / VoiceCall
756
+ // (linked-variable sources)
757
+ // → or -> arrow
758
+ // snake_case ident identifier with at least one underscore
759
+ const re = /(\*\*[^*\n]+\*\*)|(@(?:system_variables|variables|actions|action|subagent|utils|outputs|MessagingSession|MessagingEndUser|VoiceCall)\.[\w.]+)|(→|->)|(\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b)/g;
760
+ let last = 0;
761
+ let m;
762
+ while ((m = re.exec(text)) !== null) {
763
+ if (m.index > last) {
764
+ out.push({ kind: 'text', text: text.slice(last, m.index) });
765
+ }
766
+ if (m[1]) {
767
+ // Recurse so refs/idents nested inside `**...**` still tokenize.
768
+ out.push({ kind: 'bold', children: parseInline(m[1].slice(2, -2)) });
769
+ }
770
+ else if (m[2]) {
771
+ out.push({ kind: 'varRef', path: m[2] });
772
+ }
773
+ else if (m[3]) {
774
+ out.push({ kind: 'arrow' });
775
+ }
776
+ else if (m[4]) {
777
+ out.push({ kind: 'ident', name: m[4] });
778
+ }
779
+ last = re.lastIndex;
780
+ }
781
+ if (last < text.length) {
782
+ out.push({ kind: 'text', text: text.slice(last) });
783
+ }
784
+ return out;
785
+ }
786
+ /** Display glyph for an operator — `<=` becomes `≤`, etc. */
787
+ export function opGlyph(op) {
788
+ switch (op) {
789
+ case '==':
790
+ return '==';
791
+ case '!=':
792
+ return '!=';
793
+ case '>=':
794
+ return '>=';
795
+ case '<=':
796
+ return '<=';
797
+ case 'is':
798
+ return 'is';
799
+ case 'is not':
800
+ return 'is not';
801
+ default:
802
+ return op;
803
+ }
804
+ }