-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdapterSupport.cs
More file actions
519 lines (497 loc) · 26 KB
/
Copy pathAdapterSupport.cs
File metadata and controls
519 lines (497 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
using OfficeCli.Core;
using OfficeCli.Handlers;
using System.Text;
namespace AIOrchestrator.API
{
/// <summary>
/// Hand-maintained adapter support — NOT regenerated by update-vendor.ps1 (the script
/// only rewrites the @@ADAPTER_SURFACE block of OfficeTool.cs). Holds the stable,
/// engine-facing logic the generated surface delegates to, so a vendor update changes
/// the method surface (which the script adapts deterministically) but never this code.
/// </summary>
internal static class AdapterSupport
{
/// <summary>
/// Applies the vendored `set` semantics with the canonical find/replace parameters:
/// merges find/replace into the props dict (parity with the upstream CommandBuilder.Set.cs,
/// where the top-level --find/--replace and the legacy find=/replace= props entries are
/// mutually exclusive), reports skipped unsupported properties and, for find operations,
/// the engine's match count (0 matched = the text moved or the path is wrong).
/// </summary>
public static string Set(IDocumentHandler handler, string path, Dictionary<string, string> props,
string? find, string? replace)
{
if (find != null && props.ContainsKey("find"))
throw new CliException("Cannot combine the find parameter with a 'find=' entry in props. Use the find parameter only.")
{ Code = "invalid_value" };
if (replace != null && props.ContainsKey("replace"))
throw new CliException("Cannot combine the replace parameter with a 'replace=' entry in props. Use the replace parameter only.")
{ Code = "invalid_value" };
if (find != null) props["find"] = find;
if (replace != null) props["replace"] = replace;
var unsupported = handler.Set(path, props);
var result = unsupported.Count == 0
? $"Updated {path}."
: $"Updated {path}. Skipped unsupported properties: {string.Join(", ", unsupported)}. These apply to a different element — call {AIOrchestrator.Utility.ToSnakeCase(nameof(OfficeTool.Help))}(format, element) for the properties supported here.";
if (find != null)
{
var matched = handler switch
{
WordHandler w => (int?)w.LastFindMatchCount,
ExcelHandler e => (int?)e.LastFindMatchCount,
PowerPointHandler p => (int?)p.LastFindMatchCount,
_ => null,
};
result += matched == 0
? " Find matched 0 occurrences — the text may have changed or the path is wrong."
: $" ({matched} matched).";
}
return result;
}
/// <summary>
/// Runs the vendored `query` pipeline faithfully: selector evaluation via the same
/// AttributeFilter engine as upstream (boolean expressions, Excel cell-attribute
/// aliases, filter warnings), the optional --find text filter, the optional --compact
/// line format with --fields extra columns (upstream FormatNodesCompact, which rejects
/// xlsx with the upstream error), and the JSON envelope {matches, results, warnings?}
/// — the warnings key is additive so existing consumers keep working.
/// </summary>
public static string Query(IDocumentHandler handler, string selector, string? find, bool compact, string? fields)
{
Func<string, string>? keyResolver = null;
if (handler is ExcelHandler && ExcelHandler.SelectorTargetsCells(selector))
keyResolver = ExcelHandler.ResolveCellAttributeAlias;
var (results, warnings) = AttributeFilter.FilterSelector(selector, handler.Query, keyResolver);
if (!string.IsNullOrEmpty(find))
results = results.Where(n => n.Text != null && AttributeFilter.MatchesTextFilter(n.Text, find)).ToList();
if (compact)
return OfficeCli.CommandBuilder.FormatNodesCompact(handler, results, fields);
var envelope = new System.Text.Json.Nodes.JsonObject
{
["matches"] = results.Count,
["results"] = System.Text.Json.Nodes.JsonNode.Parse(System.Text.Json.JsonSerializer.Serialize(results)),
};
if (warnings.Count > 0)
{
var cliWarnings = warnings.Select(w => new CliWarning
{
Message = w.Message,
Code = w.Code,
Kind = w.Kind,
Key = w.Key,
Value = w.Value,
Available = w.Available,
Suggestion = w.Suggestion,
}).ToList();
envelope["warnings"] = System.Text.Json.JsonSerializer.SerializeToNode(cliWarnings);
}
return envelope.ToJsonString();
}
/// <summary>
/// In-memory replica of the vendor's CheckDocxProtection (CommandBuilder.cs), evaluated
/// against the OPEN handler instead of a second file open. Blocks mutations of a protected
/// .docx unless force — same message and the same formfield/sdt editable-region exemptions
/// as upstream. Mirrors GetBatchProtectionBlock's "can't read protection → allow" fallback.
/// </summary>
public static string? EnsureEditable(IDocumentHandler handler, string path, bool force)
{
if (force) return null;
OfficeCli.Core.DocumentNode root;
try { root = handler.Get("/"); }
catch { return null; }
var protection = root.Format.TryGetValue("protection", out var pVal) ? pVal?.ToString() : "none";
var enforced = root.Format.TryGetValue("protectionEnforced", out var eVal) && eVal is true;
if (!enforced || protection == "none")
return null;
if (path.StartsWith("/formfield[", StringComparison.OrdinalIgnoreCase))
return null;
if (path.Contains("/sdt[", StringComparison.OrdinalIgnoreCase))
return null;
return $"Document is protected (mode: {protection}). Use {AIOrchestrator.Utility.ToSnakeCase(nameof(OfficeTool.Query))}(\"editable\") to find editable fields, or use force to override protection.";
}
/// <summary>
/// Deserializes batch items with the engine's own source-generated context (same lenient
/// props handling the CLI batch uses) so the adapter can run the vendor's in-memory
/// batch protection gate before executing.
/// </summary>
public static List<OfficeCli.BatchItem> DeserializeBatchItems(string commandsJson) =>
System.Text.Json.JsonSerializer.Deserialize(commandsJson, OfficeCli.BatchJsonContext.Default.ListBatchItem)
?? new List<OfficeCli.BatchItem>();
/// <summary>
/// Renders the whole document as a thumbnail contact-sheet PNG (the vendor's
/// `view screenshot --grid N|auto`, pptx + docx) via the HTML preview grid
/// (layoutGrid tiles in-browser; requires a Chrome-family browser, exactly like
/// the plain screenshot path). xlsx is NOT tiled — the vendor silently ignores
/// --grid for xlsx, so the caller skips this path for ExcelHandler.
/// </summary>
public static void ViewScreenshotGrid(IDocumentHandler handler, string gridSpec, string outPng, int width, int height)
{
var spec = gridSpec.Trim();
int gridCols;
if (spec.Equals("auto", StringComparison.OrdinalIgnoreCase)) gridCols = -1;
else if (!int.TryParse(spec, out gridCols) || gridCols <= 0)
throw new CliException($"Invalid --grid value: {spec}. Use a column count (e.g. 3) or 'auto'.")
{ Code = "invalid_argument" };
const int gap = 12, pad = 12;
string? html = null;
int vpW = width, vpH = height;
switch (handler)
{
case OfficeCli.Handlers.PowerPointHandler ppt:
{
var (nativeW, nativeH) = ppt.GetSlideNativePixels();
var count = ppt.GetSlideCount();
var cols = gridCols < 0 ? OfficeCli.Core.HtmlScreenshot.AutoGridColumns(count, nativeW, nativeH) : gridCols;
html = OfficeCli.CommandBuilder.RenderViaRegistry(ppt, "pptx",
new OfficeCli.Core.Rendering.RenderOptions { GridColumns = cols, ViewportPx = width });
break;
}
case OfficeCli.Handlers.WordHandler word:
{
var (npW, npH) = word.GetPageNativePixels();
// Page count needs a real layout pass; count via the preview DOM
// (independent of the grid, which only reflows after pagination).
int pageCount = 1;
var tmpForCount = Path.Combine(Path.GetTempPath(), $"oec_gridcount_{Guid.NewGuid():N}.html");
try
{
File.WriteAllText(tmpForCount, OfficeCli.CommandBuilder.RenderViaRegistry(word, "docx",
new OfficeCli.Core.Rendering.RenderOptions())!);
pageCount = OfficeCli.Core.HtmlScreenshot.GetPageCountFromDom(tmpForCount) ?? 1;
}
catch { /* fall back to 1 row */ }
finally { try { File.Delete(tmpForCount); } catch { /* ignore */ } }
var cols = gridCols < 0 ? OfficeCli.Core.HtmlScreenshot.AutoGridColumns(pageCount, npW, npH) : gridCols;
var rows = Math.Max(1, (pageCount + cols - 1) / cols);
const int scrollbar = 17, maxDim = 1920;
double cellW = Math.Max(1.0, (width - scrollbar - 2.0 * pad - (cols - 1) * gap) / cols);
double cellH = cellW * npH / npW;
double vpHd = pad * 2 + rows * cellH + (rows - 1) * gap;
double over = Math.Max(width, vpHd) / maxDim;
if (over > 1.0) { vpW = (int)(width / over); cellW /= over; cellH /= over; vpHd /= over; }
vpH = Math.Max(1, (int)Math.Ceiling(vpHd));
html = OfficeCli.CommandBuilder.RenderViaRegistry(word, "docx",
new OfficeCli.Core.Rendering.RenderOptions { GridColumns = cols, GridCellWidthPx = (int)Math.Round(cellW) });
break;
}
default:
throw new CliException("--grid is only supported for .pptx and .docx files.")
{ Code = "unsupported_type" };
}
var tmpHtml = Path.Combine(Path.GetTempPath(), $"oec_grid_{Guid.NewGuid():N}.html");
File.WriteAllText(tmpHtml, html);
try
{
var result = OfficeCli.Core.HtmlScreenshot.Capture(tmpHtml, outPng, vpW, vpH);
if (!result.Ok)
throw new CliException(
$"Screenshot failed: {result.Error}. Requires a Chrome-family browser (Chrome/Edge/Chromium) installed on the host.")
{ Code = "screenshot_unavailable" };
}
finally { File.Delete(tmpHtml); }
}
/// <summary>
/// Translates officecli CLI invocations inside skill content into the adapter's method
/// vocabulary, so an agent following the skill does not trip on CLI syntax. Conservative
/// by design: only self-contained single-command lines — a leading `officecli` verb, the
/// optional "$FILE" placeholder, no shell pipes/variables/redirects/logical operators or
/// line continuations — are rewritten; every other line is returned byte-identical and a
/// short mapping note is prepended when at least one line was translated. The vendor skill
/// files are never modified: this is a presentation-time transform.
/// </summary>
public static string TranslateSkillSyntax(string text)
{
if (string.IsNullOrWhiteSpace(text)) return text;
var lines = text.Split('\n');
var sb = new StringBuilder();
var translated = 0;
foreach (var raw in lines)
{
var line = raw.TrimEnd('\r');
if (!line.TrimEnd().EndsWith('\\') && TryTranslateCliLine(line, out var rewritten))
{
sb.Append(rewritten);
translated++;
}
else
{
sb.Append(line);
}
sb.Append('\n');
}
if (translated == 0) return text;
var note = new StringBuilder();
note.AppendLine("Note — this skill was written for the officecli CLI; the translated lines below use this session's method vocabulary.");
note.AppendLine("Mapping: drop the file argument (one document is open), `view <mode>` → View<Mode>(), `--prop k=v` repeated → props: [\"k=v\", ...],");
note.AppendLine("`get ... selected` → GetSelected(), `help <fmt>` → Help(\"<fmt>\"), `open`/`create \"$FILE\"` → Open(\"<file>\")/Create(\"<file>\"), `save`/`validate` → Save()/Validate().");
note.AppendLine("Translated calls use the CLI-mode command names (PascalCase, e.g. ViewOutline()); in API mode the same method's tool name is snake_case (view_outline) — identical arguments.");
note.AppendLine("`officecli close` has no counterpart (the document auto-saves); shell lines left untranslated (pipelines, variables) still show CLI syntax — read them as intent.");
note.AppendLine();
return note.ToString() + sb.ToString();
}
private static bool TryTranslateCliLine(string line, out string translated)
{
translated = line;
var t = line.Trim();
if (!t.StartsWith("officecli ", StringComparison.Ordinal)) return false;
var rest = t["officecli ".Length..].Trim();
var sp = rest.IndexOf(' ');
var verb = sp < 0 ? rest : rest[..sp];
var args = sp < 0 ? "" : rest[(sp + 1)..].Trim();
// Tolerate only the "$FILE" placeholder as the leading argument.
if (args.StartsWith("\"$FILE\"", StringComparison.Ordinal)) args = args["\"$FILE\"".Length..].Trim();
else if (args.StartsWith("$FILE", StringComparison.Ordinal)) args = args["$FILE".Length..].Trim();
// Strip a trailing bash comment (unquoted '#' to end of line) so flag lists like
// `--start 1 --end 80 # content QA` stay translatable. A '#' inside a quoted value
// (e.g. color=#FF0000) is preserved.
args = StripTrailingComment(args);
// Reject only UNQUOTED shell constructs we cannot faithfully rewrite (pipes,
// variables, redirects, logical ops, escapes, placeholder tokens). Quoted content
// is safe — prop values with spaces, borders ("single;6;2E75B6") and selectors
// ("[size>=24pt]") survive intact.
if (HasUnquotedShellMeta(args)) return false;
var tokens = TokenizeCli(args);
var noArgVerbs = new[] { "open", "create", "save", "validate", "watch" };
if (tokens.Count == 0 && !noArgVerbs.Contains(verb)) return false;
switch (verb)
{
case "view":
{
var mode = tokens[0];
if (mode.Length == 0) return false;
switch (mode)
{
case "svg":
{
var page = FlagValue(tokens, "--page") ?? FlagValue(tokens, "--start");
translated = page != null ? $"ViewSvg(\"{page}\")" : "ViewSvg()";
return true;
}
case "text":
case "annotated":
{
var method = "View" + char.ToUpperInvariant(mode[0]) + mode[1..];
var parts = new List<string>();
var sl = FlagInt(tokens, "--start");
var el = FlagInt(tokens, "--end");
var ml = FlagInt(tokens, "--max-lines");
if (sl.HasValue) parts.Add($"startLine: {sl}");
if (el.HasValue) parts.Add($"endLine: {el}");
if (ml.HasValue) parts.Add($"maxLines: {ml}");
var cols = FlagValue(tokens, "--cols");
if (cols != null) parts.Add("cols: [" + string.Join(", ", cols.Split(',').Select(c => $"\"{c.Trim()}\"")) + "]");
var range = FlagValue(tokens, "--range");
if (range != null) parts.Add($"range: \"{range}\"");
translated = parts.Count > 0 ? $"{method}({string.Join(", ", parts)})" : $"{method}()";
return true;
}
case "screenshot":
{
var parts = new List<string>();
var outPath = FlagValue(tokens, "-o") ?? FlagValue(tokens, "--out");
if (outPath != null) parts.Add($"\"{outPath}\"");
var page = FlagValue(tokens, "--page");
if (page != null) parts.Add($"page: \"{page}\"");
var grid = FlagValue(tokens, "--grid");
if (grid != null) parts.Add($"grid: \"{grid}\"");
translated = parts.Count > 0 ? $"ViewScreenshot({string.Join(", ", parts)})" : "ViewScreenshot()";
return true;
}
default:
translated = "View" + char.ToUpperInvariant(mode[0]) + mode[1..] + "()";
return true;
}
}
case "get":
{
var path = tokens[0];
if (path.Length == 0) return false;
if (path == "selected") { translated = "GetSelected()"; return true; }
var depth = FlagInt(tokens, "--depth");
translated = depth is > 1 ? $"Get(\"{path}\", depth: {depth})" : $"Get(\"{path}\")";
return true;
}
case "query":
{
var sel = tokens[0];
if (sel.Length == 0) return false;
translated = $"Query(\"{sel}\")";
return true;
}
case "set":
{
var path = tokens[0];
if (path.Length == 0) return false;
var call = $"Set(\"{path}\"";
var props = FindPropList(tokens);
if (props.Count > 0) call += ", props: [" + string.Join(", ", props.Select(p => $"\"{p}\"")) + "]";
var find = FlagValue(tokens, "--find");
var replace = FlagValue(tokens, "--replace");
if (find != null) call += $", find: \"{find}\"";
if (replace != null) call += $", replace: \"{replace}\"";
translated = call + ")";
return true;
}
case "add":
{
var parent = tokens[0];
if (parent.Length == 0) return false;
var type = FlagValue(tokens, "--type");
if (type == null) return false;
var call = $"Add(\"{parent}\", \"{type}\"";
var props = FindPropList(tokens);
if (props.Count > 0) call += ", props: [" + string.Join(", ", props.Select(p => $"\"{p}\"")) + "]";
var after = FlagValue(tokens, "--after");
var before = FlagValue(tokens, "--before");
var index = FlagInt(tokens, "--index");
if (after != null) call += $", after: \"{after}\"";
if (before != null) call += $", before: \"{before}\"";
if (index.HasValue) call += $", index: {index}";
translated = call + ")";
return true;
}
case "remove":
{
var path = tokens[0];
if (path.Length == 0) return false;
var shift = FlagValue(tokens, "--shift");
translated = shift != null ? $"Remove(\"{path}\", shift: \"{shift}\")" : $"Remove(\"{path}\")";
return true;
}
case "move":
{
var path = tokens[0];
if (path.Length == 0) return false;
var call = $"Move(\"{path}\"";
var to = FlagValue(tokens, "--to");
var index = FlagInt(tokens, "--index");
if (to != null) call += $", to: \"{to}\"";
if (index.HasValue) call += $", index: {index}";
translated = call + ")";
return true;
}
case "swap":
{
if (tokens.Count < 2) return false;
translated = $"Swap(\"{tokens[0]}\", \"{tokens[1]}\")";
return true;
}
case "open":
translated = "Open(\"<file>\")";
return true;
case "create":
translated = "Create(\"<file>\")";
return true;
case "save":
translated = "Save()";
return true;
case "validate":
translated = "Validate()";
return true;
case "watch":
translated = "Watch()";
return true;
case "help":
{
var fmt = tokens.FirstOrDefault(f => !f.StartsWith("--", StringComparison.Ordinal));
translated = fmt != null ? $"Help(\"{fmt}\")" : "Help()";
return true;
}
default:
return false;
}
}
private static bool HasUnquotedShellMeta(string s)
{
char? quote = null;
for (int i = 0; i < s.Length; i++)
{
var ch = s[i];
if (quote != null)
{
if (ch == quote) { quote = null; continue; }
// Double-quoted bash variables ($name) expand at runtime — reject so loop
// recipes (tc[$col], tr[$row]) stay CLI. Single-quoted $ (e.g. text='$50M')
// is a literal value — safe.
if (quote == '"' && ch == '$' && i + 1 < s.Length && (char.IsLetter(s[i + 1]) || s[i + 1] == '_'))
return true;
continue;
}
if (ch == '"' || ch == '\'') { quote = ch; continue; }
if (ch is '$' or '|' or '>' or '`' or '&' or ';' or '\\' or '<') return true;
}
return false;
}
private static string StripTrailingComment(string s)
{
char? quote = null;
for (int i = 0; i < s.Length; i++)
{
var ch = s[i];
if (quote != null) { if (ch == quote) quote = null; continue; }
if (ch == '"' || ch == '\'') { quote = ch; continue; }
if (ch == '#') return s[..i].TrimEnd();
}
return s;
}
private static List<string> TokenizeCli(string s)
{
var tokens = new List<string>();
var cur = new StringBuilder();
char? quote = null;
var hasContent = false;
for (int i = 0; i < s.Length; i++)
{
var ch = s[i];
if (quote != null)
{
if (ch == quote) quote = null;
else cur.Append(ch);
continue;
}
if (ch == '"' || ch == '\'') { quote = ch; hasContent = true; continue; }
if (char.IsWhiteSpace(ch))
{
if (hasContent) { tokens.Add(cur.ToString()); cur.Clear(); hasContent = false; }
continue;
}
cur.Append(ch);
hasContent = true;
}
if (hasContent) tokens.Add(cur.ToString());
return tokens;
}
private static List<string> FindPropList(List<string> tokens)
{
var result = new List<string>();
for (int i = 0; i < tokens.Count; i++)
{
if (tokens[i] != "--prop") continue;
var parts = new List<string>();
var j = i + 1;
while (j < tokens.Count && !tokens[j].StartsWith("--", StringComparison.Ordinal))
{
parts.Add(tokens[j]);
j++;
}
i = j - 1;
if (parts.Count == 0) continue;
var value = string.Join(" ", parts);
if (value.Length > 0) result.Add(value);
}
return result;
}
private static string? FlagValue(List<string> tokens, string name)
{
for (int i = 0; i < tokens.Count - 1; i++)
if (tokens[i] == name)
return tokens[i + 1];
return null;
}
private static int? FlagInt(List<string> tokens, string name)
{
var v = FlagValue(tokens, name);
return int.TryParse(v, out var n) ? n : null;
}
}
}