lycheedev 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/bin/lycheedev.js +21 -6
  2. package/package.json +1 -1
  3. package/vendor/addon/Core/Bootstrap.lua +131 -131
  4. package/vendor/addon/Core/Clients/Mainline.lua +9 -9
  5. package/vendor/addon/Core/Clients/Mists.lua +9 -9
  6. package/vendor/addon/Core/Clients/Titan.lua +9 -9
  7. package/vendor/addon/Core/Compatibility.lua +43 -43
  8. package/vendor/addon/Core/Database.lua +859 -859
  9. package/vendor/addon/Core/Inspector.lua +647 -647
  10. package/vendor/addon/Core/Locale.lua +307 -307
  11. package/vendor/addon/Core/Locale_enUS.lua +318 -318
  12. package/vendor/addon/Core/Safety.lua +42 -42
  13. package/vendor/addon/Core/Serializer.lua +324 -324
  14. package/vendor/addon/Libs/AutomationQR.lua +1176 -1176
  15. package/vendor/addon/Lychee Dev_Mainline.toc +43 -43
  16. package/vendor/addon/Lychee Dev_Mists.toc +43 -43
  17. package/vendor/addon/Lychee Dev_Wrath.toc +43 -43
  18. package/vendor/addon/Modules/Automation/Controller.lua +757 -757
  19. package/vendor/addon/Modules/Automation/Report.lua +409 -409
  20. package/vendor/addon/Modules/Automation/auto/auto.lua +12 -12
  21. package/vendor/addon/Modules/Diagnostics.lua +238 -238
  22. package/vendor/addon/Modules/Events/Catalog.lua +184 -184
  23. package/vendor/addon/Modules/Events/CatalogData_Mainline.lua +1788 -1788
  24. package/vendor/addon/Modules/Events/CatalogData_Mists.lua +1489 -1489
  25. package/vendor/addon/Modules/Events/CatalogData_Titan.lua +1492 -1492
  26. package/vendor/addon/Modules/Events/Monitor.lua +181 -181
  27. package/vendor/addon/Modules/FunctionTrace.lua +85 -85
  28. package/vendor/addon/Modules/ObjectInspector.lua +329 -329
  29. package/vendor/addon/UI/AutomationOverlay.lua +183 -183
  30. package/vendor/addon/UI/Export.lua +140 -140
  31. package/vendor/addon/UI/Features.lua +890 -890
  32. package/vendor/addon/UI/MainWindow.lua +1145 -1145
  33. package/vendor/addon/UI/Pages/About.lua +223 -223
  34. package/vendor/addon/UI/Pages/Automation.lua +417 -417
  35. package/vendor/addon/UI/Pages/Diagnostics.lua +289 -289
  36. package/vendor/addon/UI/Pages/ExportRecords.lua +387 -387
  37. package/vendor/addon/UI/Pages/Object.lua +573 -573
  38. package/vendor/addon/UI/Pages/Trace.lua +165 -165
  39. package/vendor/skill/SKILL.md +94 -94
  40. package/vendor/skill/agents/openai.yaml +4 -4
  41. package/vendor/skill/references/automation.md +327 -327
  42. package/vendor/skill/references/runtime-investigations.md +97 -97
  43. package/vendor/skill/scripts/automation/__init__.py +1 -1
  44. package/vendor/skill/scripts/automation/registry.py +516 -516
  45. package/vendor/skill/scripts/automation/saved_variables.py +438 -438
  46. package/vendor/skill/scripts/automation/session.py +207 -207
  47. package/vendor/skill/scripts/automation/windows.py +573 -573
  48. package/vendor/skill/scripts/automation.py +865 -865
  49. package/vendor/skill/scripts/requirements.txt +13 -13
  50. package/vendor/skill/scripts/selftest_offline.py +981 -981
@@ -1,757 +1,757 @@
1
- local ADDON_NAME, ns = ...
2
- local L = ns.L
3
-
4
- -- Automation controller: command dispatch, task identity, execution context,
5
- -- terminal state freezing, result commit and completion notice triggering.
6
-
7
- local Controller = {}
8
- ns.Automation = Controller
9
-
10
- local TASK_SCHEMA_VERSION = 1
11
- local NOTICE_PROTOCOL_VERSION = 1
12
- local MAX_NOTICE_BYTES = 512
13
- local MAX_TASK_ID_BYTES = 64
14
- local MAX_REQUEST_ID_BYTES = 128
15
- local DEFAULT_OUTPUT_LIMIT = 384 * 1024
16
- local MAX_OUTPUT_LIMIT = 512 * 1024
17
- local RESULT_SCHEMA = "lychee.automation.result.v1"
18
- local BUG_TASK_ID = "bug"
19
-
20
- local TASK_ID_PATTERN = "^([A-Za-z0-9_%-]+)$"
21
- local REQUEST_ID_PATTERN = "^([A-Za-z0-9%.%-]+)$"
22
- local TICKET_PATTERN = "^LYCHEE%-([A-Za-z0-9%-]+)$"
23
-
24
- -- How many finished results may sit unacknowledged before new requests are
25
- -- refused. One is enough to guarantee no result is silently overwritten; a
26
- -- small backlog keeps a missed acknowledgement from blocking the whole session.
27
- local MAX_UNACKNOWLEDGED_RESULTS = 3
28
-
29
- local activeContext
30
- local awaitingNotice
31
- local unacknowledgedResults = 0
32
- local executedRequests = {}
33
-
34
- local Finalize
35
-
36
- local function Print(message)
37
- print("|cffd83b4eLychee Dev:|r " .. tostring(message))
38
- end
39
-
40
- local function Pack(...)
41
- return { n = select("#", ...), ... }
42
- end
43
-
44
- local function IsValidTaskId(taskId)
45
- return type(taskId) == "string" and #taskId >= 1 and #taskId <= MAX_TASK_ID_BYTES
46
- and taskId:match(TASK_ID_PATTERN) == taskId
47
- end
48
-
49
- local function IsValidRequestId(requestId)
50
- return type(requestId) == "string" and #requestId >= 1 and #requestId <= MAX_REQUEST_ID_BYTES
51
- and requestId:match(REQUEST_ID_PATTERN) == requestId
52
- end
53
-
54
- local function IsValidTicket(ticket)
55
- return type(ticket) == "string" and ticket:match(TICKET_PATTERN) ~= nil
56
- end
57
-
58
- local function GenerateLocalExecutionId()
59
- local sequence = ns.NextAutomationLocalRequestId() or 0
60
- return string.format("bug-%s-%04d", date("%Y%m%d-%H%M%S"), sequence)
61
- end
62
-
63
- local function EnsureReady()
64
- if ns.IsCombatBlocked() then
65
- ns.PrintCombatBlocked()
66
- return false
67
- end
68
- ns.InitializeDatabase()
69
- return true
70
- end
71
-
72
- local function ValidateTaskDefinition(taskId, definition)
73
- if type(definition) ~= "table" then
74
- return false, "not_table"
75
- end
76
- if definition.schema ~= TASK_SCHEMA_VERSION then
77
- return false, "schema"
78
- end
79
- if definition.kind ~= "lua" then
80
- return false, "kind"
81
- end
82
- if not IsValidRequestId(definition.requestId) then
83
- return false, "request_id"
84
- end
85
- if type(definition.revision) ~= "string" or #definition.revision == 0
86
- or #definition.revision > MAX_REQUEST_ID_BYTES then
87
- return false, "revision"
88
- end
89
- if type(definition.source) ~= "string" or #definition.source == 0 then
90
- return false, "source"
91
- end
92
- if type(definition.createdAt) ~= "number" then
93
- return false, "created_at"
94
- end
95
- if definition.sourceBytes ~= #definition.source then
96
- return false, "source_bytes"
97
- end
98
- if definition.sourceChecksum ~= ns.AutomationReport.Adler32(definition.source) then
99
- return false, "source_checksum"
100
- end
101
- if definition.outputLimit ~= nil
102
- and (type(definition.outputLimit) ~= "number" or definition.outputLimit < 1
103
- or definition.outputLimit > MAX_OUTPUT_LIMIT) then
104
- return false, "output_limit"
105
- end
106
- if definition.expectedClient ~= nil then
107
- if type(definition.expectedClient) ~= "table" then
108
- return false, "expected_client"
109
- end
110
- local expectedInterface = tonumber(definition.expectedClient.interface)
111
- if expectedInterface and ns.Client and ns.Client.interface ~= expectedInterface then
112
- return false, "client_mismatch"
113
- end
114
- end
115
- return true
116
- end
117
-
118
- -- Notice payloads are validated ASCII subsets, so plain embedding is safe.
119
- local function BuildNoticeJson(notice)
120
- local json = string.format('{"v":%d,"ticket":"%s","task":"%s","run":"%s","ts":%d}',
121
- NOTICE_PROTOCOL_VERSION, notice.ticket, notice.taskId, notice.executionId,
122
- math.floor(tonumber(notice.createdAt) or 0))
123
- if #json > MAX_NOTICE_BYTES then
124
- return nil
125
- end
126
- return json
127
- end
128
-
129
- local function ShowNotice(notice)
130
- if not notice or not notice.ticket then
131
- return false
132
- end
133
- local json = BuildNoticeJson(notice)
134
- if not json then
135
- Print(L.AUTO_NOTICE_FAILED)
136
- ns.AutomationOverlay.ShowError()
137
- return false
138
- end
139
- ns.AutomationOverlay.ShowNotice(json)
140
- return true
141
- end
142
-
143
- local function BuildEnvironmentInfo()
144
- local version, build, buildDate, interfaceVersion
145
- if GetBuildInfo then
146
- version, build, buildDate, interfaceVersion = GetBuildInfo()
147
- end
148
- local character, realm
149
- local succeeded, name = pcall(UnitName, "player")
150
- if succeeded and type(name) == "string" and not (issecretvalue and issecretvalue(name)) then
151
- character = name
152
- end
153
- succeeded, name = pcall(GetRealmName)
154
- if succeeded and type(name) == "string" and not (issecretvalue and issecretvalue(name)) then
155
- realm = name
156
- end
157
- return {
158
- clientId = ns.Client and ns.Client.id or nil,
159
- version = version,
160
- build = build,
161
- buildDate = buildDate,
162
- interface = interfaceVersion,
163
- locale = GetLocale and GetLocale() or nil,
164
- character = character,
165
- realm = realm,
166
- }
167
- end
168
-
169
- local function CommitContext(context, terminal)
170
- local spec = {
171
- taskId = context.taskId,
172
- executionId = context.executionId,
173
- revision = context.revision,
174
- kind = context.kind,
175
- status = terminal.status,
176
- startedAt = context.startedAt,
177
- finishedAt = time(),
178
- requestType = context.requestType,
179
- params = context.params,
180
- source = context.source,
181
- stdout = #context.outputParts > 0 and table.concat(context.outputParts) or nil,
182
- outputTruncated = context.outputTruncated,
183
- returns = terminal.returns,
184
- error = terminal.error,
185
- lifecycleLog = context.log,
186
- bugSnapshot = context.bugSnapshot,
187
- environment = BuildEnvironmentInfo(),
188
- complete = not context.outputTruncated,
189
- incompleteReasons = context.outputTruncated and { "output_truncated" } or nil,
190
- }
191
-
192
- local content, metadata, errorCode = ns.AutomationReportBuild(spec)
193
- if not content then
194
- -- The report exceeded its budget; commit a small explicit failure report
195
- -- instead of a silently truncated success.
196
- terminal.status = "failed"
197
- if not terminal.error then
198
- terminal.error = { message = "report_build_failed: " .. tostring(errorCode), stage = "report" }
199
- end
200
- terminal.errorCode = terminal.errorCode or "report_build_failed"
201
- spec.status = "failed"
202
- spec.complete = false
203
- spec.incompleteReasons = { "output_limit" }
204
- spec.stdout = nil
205
- spec.returns = nil
206
- spec.bugSnapshot = nil
207
- spec.source = nil
208
- spec.params = nil
209
- spec.error = terminal.error
210
- content, metadata, errorCode = ns.AutomationReportBuild(spec)
211
- end
212
-
213
- if not content then
214
- ns.FailAutomationExecution(context.executionId, "failed", "report_unavailable")
215
- ns.AutomationOverlay.ShowError()
216
- Print(L.AUTO_COMMIT_FAILED:format(tostring(errorCode or "unknown")))
217
- return nil
218
- end
219
-
220
- local ticket, entryOrError = ns.CommitAutomationResult(context.executionId, content, {
221
- status = terminal.status,
222
- complete = metadata.complete,
223
- resultSchema = RESULT_SCHEMA,
224
- checksumAlgorithm = "adler32",
225
- contentChecksum = metadata.contentChecksum,
226
- title = context.title,
227
- evidenceKind = context.evidenceKind,
228
- errorCode = terminal.errorCode or errorCode,
229
- })
230
- if not ticket then
231
- -- A failed commit must still reach a terminal index state: the request
232
- -- id is already spent, so an active record would strand the index until
233
- -- the next reload (spec 5.4 step 3).
234
- ns.FailAutomationExecution(context.executionId, "failed", "commit_failed")
235
- ns.AutomationOverlay.ShowError()
236
- Print(L.AUTO_COMMIT_FAILED:format(tostring(entryOrError or errorCode or "unknown")))
237
- return nil
238
- end
239
-
240
- awaitingNotice = {
241
- ticket = ticket,
242
- taskId = context.taskId,
243
- executionId = context.executionId,
244
- createdAt = entryOrError.createdAt,
245
- }
246
- unacknowledgedResults = unacknowledgedResults + 1
247
- ns.AutomationOverlay.HideStatus()
248
- if ShowNotice(awaitingNotice) then
249
- Print(L.AUTO_RESULT_READY:format(ticket))
250
- end
251
- return ticket
252
- end
253
-
254
- Finalize = function(context, terminal)
255
- if context.terminal then
256
- return
257
- end
258
- context.terminal = terminal
259
- if activeContext == context then
260
- activeContext = nil
261
- end
262
- context.record.status = "finalizing"
263
- for index = 1, #context.cleanups do
264
- local succeeded, errorText = pcall(context.cleanups[index])
265
- if not succeeded then
266
- context.log[#context.log + 1] = { at = time(), message = "cleanup_failed: " .. tostring(errorText) }
267
- end
268
- end
269
- context.finishedAt = time()
270
- CommitContext(context, terminal)
271
- end
272
-
273
- local function AddContextOutput(context, text)
274
- if context.outputTruncated then
275
- return
276
- end
277
- text = tostring(text or "")
278
- local prefix = #context.outputParts > 0 and "\n" or ""
279
- local remaining = context.outputLimit - context.outputBytes - #prefix
280
- if #text > remaining then
281
- context.outputParts[#context.outputParts + 1] = prefix
282
- .. text:sub(1, math.max(0, remaining))
283
- .. "\n... <output truncated>"
284
- context.outputTruncated = true
285
- return
286
- end
287
- context.outputParts[#context.outputParts + 1] = prefix .. text
288
- context.outputBytes = context.outputBytes + #prefix + #text
289
- end
290
-
291
- local function AddLifecycleLog(context, message)
292
- message = tostring(message or "")
293
- if #message > 512 then
294
- message = message:sub(1, 512) .. "... <truncated>"
295
- end
296
- context.log[#context.log + 1] = { at = time(), message = message }
297
- end
298
-
299
- local function BuildContextEnvironment(context)
300
- local environment = {}
301
-
302
- environment.print = function(...)
303
- local values = Pack(...)
304
- local parts = {}
305
- for index = 1, values.n do
306
- if issecretvalue and issecretvalue(values[index]) then
307
- parts[index] = "<secret>"
308
- else
309
- parts[index] = tostring(values[index])
310
- end
311
- end
312
- AddContextOutput(context, table.concat(parts, " "))
313
- end
314
-
315
- environment.Finish = function(...)
316
- local count = select("#", ...)
317
- local returns
318
- if count > 0 then
319
- returns = {}
320
- for index = 1, count do
321
- returns[index] = select(index, ...)
322
- end
323
- end
324
- Finalize(context, { status = "succeeded", returns = returns })
325
- end
326
-
327
- environment.Fail = function(message, errorCode)
328
- Finalize(context, {
329
- status = "failed",
330
- error = { message = tostring(message or "failed"), stage = "task" },
331
- errorCode = type(errorCode) == "string" and errorCode or "task_failed",
332
- })
333
- end
334
-
335
- environment.IsCancelled = function()
336
- return context.cancelRequested
337
- end
338
-
339
- environment.OnCleanup = function(handler)
340
- if type(handler) == "function" then
341
- context.cleanups[#context.cleanups + 1] = handler
342
- end
343
- end
344
-
345
- environment.Log = function(message)
346
- AddLifecycleLog(context, message)
347
- end
348
-
349
- environment.SetAsync = function()
350
- context.asyncRequested = true
351
- end
352
-
353
- setmetatable(environment, { __index = _G, __newindex = _G })
354
- return environment
355
- end
356
-
357
- local function ExecuteTask(taskId, definition)
358
- local record, beginError = ns.BeginAutomationExecution(definition.requestId, {
359
- taskId = taskId,
360
- revision = definition.revision,
361
- kind = "lua",
362
- })
363
- if not record then
364
- Print(beginError or L.AUTO_REQUEST_REPEATED)
365
- return
366
- end
367
-
368
- local context = {
369
- taskId = taskId,
370
- title = taskId,
371
- executionId = definition.requestId,
372
- revision = definition.revision,
373
- kind = "lua",
374
- requestType = "task",
375
- evidenceKind = "automation_result",
376
- record = record,
377
- outputLimit = math.floor(math.min(tonumber(definition.outputLimit) or DEFAULT_OUTPUT_LIMIT,
378
- MAX_OUTPUT_LIMIT)),
379
- outputParts = {},
380
- outputBytes = 0,
381
- outputTruncated = false,
382
- log = {},
383
- cleanups = {},
384
- terminal = nil,
385
- asyncRequested = false,
386
- cancelRequested = false,
387
- startedAt = time(),
388
- source = {
389
- sourceBytes = definition.sourceBytes,
390
- sourceChecksum = definition.sourceChecksum,
391
- requestId = definition.requestId,
392
- },
393
- params = nil,
394
- bugSnapshot = nil,
395
- }
396
- context.environment = BuildContextEnvironment(context)
397
- activeContext = context
398
- executedRequests[definition.requestId] = true
399
- ns.AutomationOverlay.ShowRunning()
400
-
401
- local chunk, compileError = loadstring(definition.source, "LycheeDevAutomation:" .. taskId)
402
- if not chunk then
403
- Finalize(context, {
404
- status = "failed",
405
- error = { message = tostring(compileError), stage = "compile" },
406
- errorCode = "compile_error",
407
- })
408
- return
409
- end
410
- setfenv(chunk, context.environment)
411
-
412
- local packed = Pack(pcall(chunk))
413
- if not packed[1] then
414
- Finalize(context, {
415
- status = "failed",
416
- error = { message = tostring(packed[2]), stage = "runtime" },
417
- errorCode = "runtime_error",
418
- })
419
- elseif not context.terminal and not context.asyncRequested then
420
- -- Sync task: returning completes it with the returned values.
421
- local returns
422
- if packed.n > 1 then
423
- returns = {}
424
- for index = 2, packed.n do
425
- returns[index - 1] = packed[index]
426
- end
427
- end
428
- Finalize(context, { status = "succeeded", returns = returns })
429
- end
430
- -- Async tasks stay active until their callbacks finish or fail explicitly.
431
- end
432
-
433
- function Controller.Run(taskId)
434
- if not EnsureReady() then
435
- return
436
- end
437
- if not IsValidTaskId(taskId) then
438
- Print(L.AUTO_TASK_INVALID:format(tostring(taskId), "task_id"))
439
- return
440
- end
441
- local definitions = ns.AutomationTaskDefinitions
442
- local definition = type(definitions) == "table" and definitions[taskId] or nil
443
- if not definition then
444
- Print(L.AUTO_TASK_NOT_LOADED:format(taskId))
445
- return
446
- end
447
- local valid, reason = ValidateTaskDefinition(taskId, definition)
448
- if not valid then
449
- Print(L.AUTO_TASK_INVALID:format(taskId, tostring(reason)))
450
- return
451
- end
452
- local expiresAt = tonumber(definition.expiresAt) or 0
453
- if expiresAt > 0 and expiresAt <= time() then
454
- Print(L.AUTO_TASK_EXPIRED:format(taskId))
455
- return
456
- end
457
- if not ns.AutomationWritesEnabled() then
458
- Print(L.AUTO_DATABASE_UNSUPPORTED)
459
- return
460
- end
461
- if executedRequests[definition.requestId] then
462
- -- Same request may not run twice in one session; re-show its notice.
463
- local record = ns.GetAutomationRecord(definition.requestId)
464
- local entry = record and record.ticket and ns.GetExport(record.ticket) or nil
465
- if entry and not activeContext then
466
- ShowNotice({
467
- ticket = record.ticket,
468
- taskId = record.taskId,
469
- executionId = record.executionId,
470
- createdAt = entry.createdAt,
471
- })
472
- else
473
- Print(L.AUTO_REQUEST_REPEATED)
474
- end
475
- return
476
- end
477
- if activeContext or unacknowledgedResults >= MAX_UNACKNOWLEDGED_RESULTS then
478
- Print(L.AUTO_BUSY)
479
- return
480
- end
481
- ExecuteTask(taskId, definition)
482
- end
483
-
484
- function Controller.Bug(countText, requestIdText)
485
- if not EnsureReady() then
486
- return
487
- end
488
- local count = tonumber(countText)
489
- if not count or count ~= math.floor(count) or count < 1 or count > 100 then
490
- Print(L.AUTO_INVALID_COUNT)
491
- return
492
- end
493
- requestIdText = requestIdText or ""
494
- if requestIdText ~= "" and not IsValidRequestId(requestIdText) then
495
- Print(L.AUTO_TASK_INVALID:format(requestIdText, "request_id"))
496
- return
497
- end
498
- if not ns.AutomationWritesEnabled() then
499
- Print(L.AUTO_DATABASE_UNSUPPORTED)
500
- return
501
- end
502
- local executionId = requestIdText ~= "" and requestIdText or GenerateLocalExecutionId()
503
- if executedRequests[executionId] then
504
- Print(L.AUTO_REQUEST_REPEATED)
505
- return
506
- end
507
- if activeContext or unacknowledgedResults >= MAX_UNACKNOWLEDGED_RESULTS then
508
- Print(L.AUTO_BUSY)
509
- return
510
- end
511
- local snapshot, snapshotError = ns.Diagnostics.SnapshotRecentErrors(count, "all")
512
- if not snapshot then
513
- Print(L.AUTO_PROVIDER_FAILED:format(tostring(snapshotError)))
514
- return
515
- end
516
-
517
- local record, beginError = ns.BeginAutomationExecution(executionId, {
518
- taskId = BUG_TASK_ID,
519
- kind = "bug_snapshot",
520
- })
521
- if not record then
522
- Print(beginError or L.AUTO_REQUEST_REPEATED)
523
- return
524
- end
525
- executedRequests[executionId] = true
526
-
527
- local context = {
528
- taskId = BUG_TASK_ID,
529
- title = L.AUTO_BUG_TITLE:format(count),
530
- executionId = executionId,
531
- kind = "bug_snapshot",
532
- requestType = "bug",
533
- evidenceKind = "error_log",
534
- record = record,
535
- outputLimit = DEFAULT_OUTPUT_LIMIT,
536
- outputParts = {},
537
- outputBytes = 0,
538
- outputTruncated = false,
539
- log = {},
540
- cleanups = {},
541
- terminal = nil,
542
- asyncRequested = false,
543
- cancelRequested = false,
544
- startedAt = time(),
545
- source = nil,
546
- params = { count = count, scope = "provider_storage" },
547
- bugSnapshot = snapshot,
548
- }
549
- activeContext = context
550
- ns.AutomationOverlay.ShowRunning()
551
- Finalize(context, { status = "succeeded" })
552
- end
553
-
554
- function Controller.Status(taskId)
555
- if not EnsureReady() then
556
- return
557
- end
558
- if not IsValidTaskId(taskId) then
559
- Print(L.AUTO_TASK_INVALID:format(tostring(taskId), "task_id"))
560
- return
561
- end
562
- local automation = ns.GetAutomationIndex()
563
- local latest
564
- if automation then
565
- for index = 1, #automation.order do
566
- local record = automation.records[automation.order[index]]
567
- if record and record.taskId == taskId then
568
- latest = record
569
- break
570
- end
571
- end
572
- end
573
- if not latest then
574
- Print(L.AUTO_TASK_NOT_LOADED:format(taskId))
575
- return
576
- end
577
- local resultText
578
- if latest.ticket and ns.GetExport(latest.ticket) then
579
- resultText = latest.ticket
580
- elseif latest.ticket then
581
- resultText = L.AUTO_RESULT_EXPIRED
582
- else
583
- resultText = "-"
584
- end
585
- Print(L.AUTO_STATUS_LINE:format(taskId, latest.executionId, latest.status, resultText))
586
- if latest.ticket and resultText == latest.ticket and not activeContext then
587
- ShowNotice({
588
- ticket = latest.ticket,
589
- taskId = latest.taskId,
590
- executionId = latest.executionId,
591
- createdAt = ns.GetExport(latest.ticket).createdAt,
592
- })
593
- end
594
- end
595
-
596
- function Controller.Show(ticket)
597
- if not EnsureReady() then
598
- return
599
- end
600
- if not IsValidTicket(ticket) then
601
- Print(L.AUTO_INVALID_TICKET)
602
- return
603
- end
604
- local entry = ns.GetExport(ticket)
605
- local record = entry and ns.FindAutomationByTicket(ticket) or nil
606
- if not entry or not record then
607
- Print(L.AUTO_RESULT_MISSING:format(ticket))
608
- return
609
- end
610
- ShowNotice({
611
- ticket = ticket,
612
- taskId = record.taskId,
613
- executionId = record.executionId,
614
- createdAt = entry.createdAt,
615
- })
616
- end
617
-
618
- function Controller.Cancel(taskId)
619
- if not EnsureReady() then
620
- return
621
- end
622
- if not IsValidTaskId(taskId) then
623
- Print(L.AUTO_TASK_INVALID:format(tostring(taskId), "task_id"))
624
- return
625
- end
626
- if not activeContext or activeContext.taskId ~= taskId then
627
- Print(L.AUTO_NO_ACTIVE:format(taskId))
628
- return
629
- end
630
- activeContext.cancelRequested = true
631
- Finalize(activeContext, {
632
- status = "cancelled",
633
- errorCode = "cancelled_by_request",
634
- })
635
- end
636
-
637
- function Controller.Stop()
638
- ns.AutomationOverlay.HideNotice()
639
- ns.AutomationOverlay.HideStatus()
640
- Print(L.AUTO_STOPPED)
641
- end
642
-
643
- -- The plugin cannot observe whether the host read a result, so the host reports
644
- -- it back as a chat command: `/dev auto ack <ticket> <received|failed>`. That
645
- -- clears the pending-flush block immediately (no reload needed) and records the
646
- -- outcome so the page can show it and a later session keeps it.
647
- function Controller.Ack(ticket, outcome)
648
- if not EnsureReady() then
649
- return
650
- end
651
- if not IsValidTicket(ticket) then
652
- Print(L.AUTO_INVALID_TICKET)
653
- return
654
- end
655
- if outcome ~= "received" and outcome ~= "failed" then
656
- Print(L.AUTO_ACK_STATUS_INVALID)
657
- return
658
- end
659
- local record = ns.FindAutomationByTicket(ticket)
660
- if not record then
661
- Print(L.AUTO_ACK_TICKET_UNKNOWN:format(ticket))
662
- return
663
- end
664
- record.receivedAt = time()
665
- record.receivedStatus = outcome
666
- -- Only the first acknowledgement of a result frees a backlog slot; a repeat
667
- -- ack must not shrink the count twice.
668
- if not record.acknowledged then
669
- record.acknowledged = true
670
- if unacknowledgedResults > 0 then
671
- unacknowledgedResults = unacknowledgedResults - 1
672
- end
673
- end
674
- if awaitingNotice and awaitingNotice.ticket == ticket then
675
- awaitingNotice = nil
676
- ns.AutomationOverlay.HideNotice()
677
- end
678
- Print(L.AUTO_ACK_DONE:format(ticket, outcome))
679
- end
680
-
681
- function Controller.HandleCommand(text)
682
- local action, rest = tostring(text or ""):match("^(%S+)%s*(.-)%s*$")
683
- action = action and action:lower() or ""
684
- if action == "run" then
685
- local taskId = rest:match("^(%S+)$")
686
- if not taskId then
687
- Print(L.AUTO_USAGE)
688
- return
689
- end
690
- Controller.Run(taskId)
691
- elseif action == "bug" then
692
- local count, requestId = rest:match("^(%S+)%s+(%S+)$")
693
- if not count then
694
- count = rest:match("^(%S+)$")
695
- end
696
- if not count then
697
- Print(L.AUTO_USAGE)
698
- return
699
- end
700
- Controller.Bug(count, requestId)
701
- elseif action == "status" then
702
- local taskId = rest:match("^(%S+)$")
703
- if not taskId then
704
- Print(L.AUTO_USAGE)
705
- return
706
- end
707
- Controller.Status(taskId)
708
- elseif action == "show" then
709
- local ticket = rest:match("^(%S+)$")
710
- if not ticket then
711
- Print(L.AUTO_USAGE)
712
- return
713
- end
714
- Controller.Show(ticket)
715
- elseif action == "cancel" then
716
- local taskId = rest:match("^(%S+)$")
717
- if not taskId then
718
- Print(L.AUTO_USAGE)
719
- return
720
- end
721
- Controller.Cancel(taskId)
722
- elseif action == "stop" then
723
- if rest ~= "" then
724
- Print(L.AUTO_USAGE)
725
- return
726
- end
727
- Controller.Stop()
728
- elseif action == "ack" then
729
- local ticket, outcome = rest:match("^(%S+)%s+(%S+)$")
730
- if not ticket or not outcome then
731
- Print(L.AUTO_USAGE)
732
- return
733
- end
734
- Controller.Ack(ticket, outcome:lower())
735
- else
736
- Print(L.AUTO_USAGE)
737
- end
738
- end
739
-
740
- function Controller.IsBusy()
741
- -- Busy means "a new request would be refused", not "a notice is on screen":
742
- -- a few unacknowledged results may queue before the cap blocks new runs.
743
- return activeContext ~= nil
744
- or unacknowledgedResults >= MAX_UNACKNOWLEDGED_RESULTS
745
- end
746
-
747
- function Controller.GetUnacknowledgedCount()
748
- return unacknowledgedResults
749
- end
750
-
751
- function Controller.MaxUnacknowledgedResults()
752
- return MAX_UNACKNOWLEDGED_RESULTS
753
- end
754
-
755
- function Controller.GetAwaitingNotice()
756
- return awaitingNotice
757
- end
1
+ local ADDON_NAME, ns = ...
2
+ local L = ns.L
3
+
4
+ -- Automation controller: command dispatch, task identity, execution context,
5
+ -- terminal state freezing, result commit and completion notice triggering.
6
+
7
+ local Controller = {}
8
+ ns.Automation = Controller
9
+
10
+ local TASK_SCHEMA_VERSION = 1
11
+ local NOTICE_PROTOCOL_VERSION = 1
12
+ local MAX_NOTICE_BYTES = 512
13
+ local MAX_TASK_ID_BYTES = 64
14
+ local MAX_REQUEST_ID_BYTES = 128
15
+ local DEFAULT_OUTPUT_LIMIT = 384 * 1024
16
+ local MAX_OUTPUT_LIMIT = 512 * 1024
17
+ local RESULT_SCHEMA = "lychee.automation.result.v1"
18
+ local BUG_TASK_ID = "bug"
19
+
20
+ local TASK_ID_PATTERN = "^([A-Za-z0-9_%-]+)$"
21
+ local REQUEST_ID_PATTERN = "^([A-Za-z0-9%.%-]+)$"
22
+ local TICKET_PATTERN = "^LYCHEE%-([A-Za-z0-9%-]+)$"
23
+
24
+ -- How many finished results may sit unacknowledged before new requests are
25
+ -- refused. One is enough to guarantee no result is silently overwritten; a
26
+ -- small backlog keeps a missed acknowledgement from blocking the whole session.
27
+ local MAX_UNACKNOWLEDGED_RESULTS = 3
28
+
29
+ local activeContext
30
+ local awaitingNotice
31
+ local unacknowledgedResults = 0
32
+ local executedRequests = {}
33
+
34
+ local Finalize
35
+
36
+ local function Print(message)
37
+ print("|cffd83b4eLychee Dev:|r " .. tostring(message))
38
+ end
39
+
40
+ local function Pack(...)
41
+ return { n = select("#", ...), ... }
42
+ end
43
+
44
+ local function IsValidTaskId(taskId)
45
+ return type(taskId) == "string" and #taskId >= 1 and #taskId <= MAX_TASK_ID_BYTES
46
+ and taskId:match(TASK_ID_PATTERN) == taskId
47
+ end
48
+
49
+ local function IsValidRequestId(requestId)
50
+ return type(requestId) == "string" and #requestId >= 1 and #requestId <= MAX_REQUEST_ID_BYTES
51
+ and requestId:match(REQUEST_ID_PATTERN) == requestId
52
+ end
53
+
54
+ local function IsValidTicket(ticket)
55
+ return type(ticket) == "string" and ticket:match(TICKET_PATTERN) ~= nil
56
+ end
57
+
58
+ local function GenerateLocalExecutionId()
59
+ local sequence = ns.NextAutomationLocalRequestId() or 0
60
+ return string.format("bug-%s-%04d", date("%Y%m%d-%H%M%S"), sequence)
61
+ end
62
+
63
+ local function EnsureReady()
64
+ if ns.IsCombatBlocked() then
65
+ ns.PrintCombatBlocked()
66
+ return false
67
+ end
68
+ ns.InitializeDatabase()
69
+ return true
70
+ end
71
+
72
+ local function ValidateTaskDefinition(taskId, definition)
73
+ if type(definition) ~= "table" then
74
+ return false, "not_table"
75
+ end
76
+ if definition.schema ~= TASK_SCHEMA_VERSION then
77
+ return false, "schema"
78
+ end
79
+ if definition.kind ~= "lua" then
80
+ return false, "kind"
81
+ end
82
+ if not IsValidRequestId(definition.requestId) then
83
+ return false, "request_id"
84
+ end
85
+ if type(definition.revision) ~= "string" or #definition.revision == 0
86
+ or #definition.revision > MAX_REQUEST_ID_BYTES then
87
+ return false, "revision"
88
+ end
89
+ if type(definition.source) ~= "string" or #definition.source == 0 then
90
+ return false, "source"
91
+ end
92
+ if type(definition.createdAt) ~= "number" then
93
+ return false, "created_at"
94
+ end
95
+ if definition.sourceBytes ~= #definition.source then
96
+ return false, "source_bytes"
97
+ end
98
+ if definition.sourceChecksum ~= ns.AutomationReport.Adler32(definition.source) then
99
+ return false, "source_checksum"
100
+ end
101
+ if definition.outputLimit ~= nil
102
+ and (type(definition.outputLimit) ~= "number" or definition.outputLimit < 1
103
+ or definition.outputLimit > MAX_OUTPUT_LIMIT) then
104
+ return false, "output_limit"
105
+ end
106
+ if definition.expectedClient ~= nil then
107
+ if type(definition.expectedClient) ~= "table" then
108
+ return false, "expected_client"
109
+ end
110
+ local expectedInterface = tonumber(definition.expectedClient.interface)
111
+ if expectedInterface and ns.Client and ns.Client.interface ~= expectedInterface then
112
+ return false, "client_mismatch"
113
+ end
114
+ end
115
+ return true
116
+ end
117
+
118
+ -- Notice payloads are validated ASCII subsets, so plain embedding is safe.
119
+ local function BuildNoticeJson(notice)
120
+ local json = string.format('{"v":%d,"ticket":"%s","task":"%s","run":"%s","ts":%d}',
121
+ NOTICE_PROTOCOL_VERSION, notice.ticket, notice.taskId, notice.executionId,
122
+ math.floor(tonumber(notice.createdAt) or 0))
123
+ if #json > MAX_NOTICE_BYTES then
124
+ return nil
125
+ end
126
+ return json
127
+ end
128
+
129
+ local function ShowNotice(notice)
130
+ if not notice or not notice.ticket then
131
+ return false
132
+ end
133
+ local json = BuildNoticeJson(notice)
134
+ if not json then
135
+ Print(L.AUTO_NOTICE_FAILED)
136
+ ns.AutomationOverlay.ShowError()
137
+ return false
138
+ end
139
+ ns.AutomationOverlay.ShowNotice(json)
140
+ return true
141
+ end
142
+
143
+ local function BuildEnvironmentInfo()
144
+ local version, build, buildDate, interfaceVersion
145
+ if GetBuildInfo then
146
+ version, build, buildDate, interfaceVersion = GetBuildInfo()
147
+ end
148
+ local character, realm
149
+ local succeeded, name = pcall(UnitName, "player")
150
+ if succeeded and type(name) == "string" and not (issecretvalue and issecretvalue(name)) then
151
+ character = name
152
+ end
153
+ succeeded, name = pcall(GetRealmName)
154
+ if succeeded and type(name) == "string" and not (issecretvalue and issecretvalue(name)) then
155
+ realm = name
156
+ end
157
+ return {
158
+ clientId = ns.Client and ns.Client.id or nil,
159
+ version = version,
160
+ build = build,
161
+ buildDate = buildDate,
162
+ interface = interfaceVersion,
163
+ locale = GetLocale and GetLocale() or nil,
164
+ character = character,
165
+ realm = realm,
166
+ }
167
+ end
168
+
169
+ local function CommitContext(context, terminal)
170
+ local spec = {
171
+ taskId = context.taskId,
172
+ executionId = context.executionId,
173
+ revision = context.revision,
174
+ kind = context.kind,
175
+ status = terminal.status,
176
+ startedAt = context.startedAt,
177
+ finishedAt = time(),
178
+ requestType = context.requestType,
179
+ params = context.params,
180
+ source = context.source,
181
+ stdout = #context.outputParts > 0 and table.concat(context.outputParts) or nil,
182
+ outputTruncated = context.outputTruncated,
183
+ returns = terminal.returns,
184
+ error = terminal.error,
185
+ lifecycleLog = context.log,
186
+ bugSnapshot = context.bugSnapshot,
187
+ environment = BuildEnvironmentInfo(),
188
+ complete = not context.outputTruncated,
189
+ incompleteReasons = context.outputTruncated and { "output_truncated" } or nil,
190
+ }
191
+
192
+ local content, metadata, errorCode = ns.AutomationReportBuild(spec)
193
+ if not content then
194
+ -- The report exceeded its budget; commit a small explicit failure report
195
+ -- instead of a silently truncated success.
196
+ terminal.status = "failed"
197
+ if not terminal.error then
198
+ terminal.error = { message = "report_build_failed: " .. tostring(errorCode), stage = "report" }
199
+ end
200
+ terminal.errorCode = terminal.errorCode or "report_build_failed"
201
+ spec.status = "failed"
202
+ spec.complete = false
203
+ spec.incompleteReasons = { "output_limit" }
204
+ spec.stdout = nil
205
+ spec.returns = nil
206
+ spec.bugSnapshot = nil
207
+ spec.source = nil
208
+ spec.params = nil
209
+ spec.error = terminal.error
210
+ content, metadata, errorCode = ns.AutomationReportBuild(spec)
211
+ end
212
+
213
+ if not content then
214
+ ns.FailAutomationExecution(context.executionId, "failed", "report_unavailable")
215
+ ns.AutomationOverlay.ShowError()
216
+ Print(L.AUTO_COMMIT_FAILED:format(tostring(errorCode or "unknown")))
217
+ return nil
218
+ end
219
+
220
+ local ticket, entryOrError = ns.CommitAutomationResult(context.executionId, content, {
221
+ status = terminal.status,
222
+ complete = metadata.complete,
223
+ resultSchema = RESULT_SCHEMA,
224
+ checksumAlgorithm = "adler32",
225
+ contentChecksum = metadata.contentChecksum,
226
+ title = context.title,
227
+ evidenceKind = context.evidenceKind,
228
+ errorCode = terminal.errorCode or errorCode,
229
+ })
230
+ if not ticket then
231
+ -- A failed commit must still reach a terminal index state: the request
232
+ -- id is already spent, so an active record would strand the index until
233
+ -- the next reload (spec 5.4 step 3).
234
+ ns.FailAutomationExecution(context.executionId, "failed", "commit_failed")
235
+ ns.AutomationOverlay.ShowError()
236
+ Print(L.AUTO_COMMIT_FAILED:format(tostring(entryOrError or errorCode or "unknown")))
237
+ return nil
238
+ end
239
+
240
+ awaitingNotice = {
241
+ ticket = ticket,
242
+ taskId = context.taskId,
243
+ executionId = context.executionId,
244
+ createdAt = entryOrError.createdAt,
245
+ }
246
+ unacknowledgedResults = unacknowledgedResults + 1
247
+ ns.AutomationOverlay.HideStatus()
248
+ if ShowNotice(awaitingNotice) then
249
+ Print(L.AUTO_RESULT_READY:format(ticket))
250
+ end
251
+ return ticket
252
+ end
253
+
254
+ Finalize = function(context, terminal)
255
+ if context.terminal then
256
+ return
257
+ end
258
+ context.terminal = terminal
259
+ if activeContext == context then
260
+ activeContext = nil
261
+ end
262
+ context.record.status = "finalizing"
263
+ for index = 1, #context.cleanups do
264
+ local succeeded, errorText = pcall(context.cleanups[index])
265
+ if not succeeded then
266
+ context.log[#context.log + 1] = { at = time(), message = "cleanup_failed: " .. tostring(errorText) }
267
+ end
268
+ end
269
+ context.finishedAt = time()
270
+ CommitContext(context, terminal)
271
+ end
272
+
273
+ local function AddContextOutput(context, text)
274
+ if context.outputTruncated then
275
+ return
276
+ end
277
+ text = tostring(text or "")
278
+ local prefix = #context.outputParts > 0 and "\n" or ""
279
+ local remaining = context.outputLimit - context.outputBytes - #prefix
280
+ if #text > remaining then
281
+ context.outputParts[#context.outputParts + 1] = prefix
282
+ .. text:sub(1, math.max(0, remaining))
283
+ .. "\n... <output truncated>"
284
+ context.outputTruncated = true
285
+ return
286
+ end
287
+ context.outputParts[#context.outputParts + 1] = prefix .. text
288
+ context.outputBytes = context.outputBytes + #prefix + #text
289
+ end
290
+
291
+ local function AddLifecycleLog(context, message)
292
+ message = tostring(message or "")
293
+ if #message > 512 then
294
+ message = message:sub(1, 512) .. "... <truncated>"
295
+ end
296
+ context.log[#context.log + 1] = { at = time(), message = message }
297
+ end
298
+
299
+ local function BuildContextEnvironment(context)
300
+ local environment = {}
301
+
302
+ environment.print = function(...)
303
+ local values = Pack(...)
304
+ local parts = {}
305
+ for index = 1, values.n do
306
+ if issecretvalue and issecretvalue(values[index]) then
307
+ parts[index] = "<secret>"
308
+ else
309
+ parts[index] = tostring(values[index])
310
+ end
311
+ end
312
+ AddContextOutput(context, table.concat(parts, " "))
313
+ end
314
+
315
+ environment.Finish = function(...)
316
+ local count = select("#", ...)
317
+ local returns
318
+ if count > 0 then
319
+ returns = {}
320
+ for index = 1, count do
321
+ returns[index] = select(index, ...)
322
+ end
323
+ end
324
+ Finalize(context, { status = "succeeded", returns = returns })
325
+ end
326
+
327
+ environment.Fail = function(message, errorCode)
328
+ Finalize(context, {
329
+ status = "failed",
330
+ error = { message = tostring(message or "failed"), stage = "task" },
331
+ errorCode = type(errorCode) == "string" and errorCode or "task_failed",
332
+ })
333
+ end
334
+
335
+ environment.IsCancelled = function()
336
+ return context.cancelRequested
337
+ end
338
+
339
+ environment.OnCleanup = function(handler)
340
+ if type(handler) == "function" then
341
+ context.cleanups[#context.cleanups + 1] = handler
342
+ end
343
+ end
344
+
345
+ environment.Log = function(message)
346
+ AddLifecycleLog(context, message)
347
+ end
348
+
349
+ environment.SetAsync = function()
350
+ context.asyncRequested = true
351
+ end
352
+
353
+ setmetatable(environment, { __index = _G, __newindex = _G })
354
+ return environment
355
+ end
356
+
357
+ local function ExecuteTask(taskId, definition)
358
+ local record, beginError = ns.BeginAutomationExecution(definition.requestId, {
359
+ taskId = taskId,
360
+ revision = definition.revision,
361
+ kind = "lua",
362
+ })
363
+ if not record then
364
+ Print(beginError or L.AUTO_REQUEST_REPEATED)
365
+ return
366
+ end
367
+
368
+ local context = {
369
+ taskId = taskId,
370
+ title = taskId,
371
+ executionId = definition.requestId,
372
+ revision = definition.revision,
373
+ kind = "lua",
374
+ requestType = "task",
375
+ evidenceKind = "automation_result",
376
+ record = record,
377
+ outputLimit = math.floor(math.min(tonumber(definition.outputLimit) or DEFAULT_OUTPUT_LIMIT,
378
+ MAX_OUTPUT_LIMIT)),
379
+ outputParts = {},
380
+ outputBytes = 0,
381
+ outputTruncated = false,
382
+ log = {},
383
+ cleanups = {},
384
+ terminal = nil,
385
+ asyncRequested = false,
386
+ cancelRequested = false,
387
+ startedAt = time(),
388
+ source = {
389
+ sourceBytes = definition.sourceBytes,
390
+ sourceChecksum = definition.sourceChecksum,
391
+ requestId = definition.requestId,
392
+ },
393
+ params = nil,
394
+ bugSnapshot = nil,
395
+ }
396
+ context.environment = BuildContextEnvironment(context)
397
+ activeContext = context
398
+ executedRequests[definition.requestId] = true
399
+ ns.AutomationOverlay.ShowRunning()
400
+
401
+ local chunk, compileError = loadstring(definition.source, "LycheeDevAutomation:" .. taskId)
402
+ if not chunk then
403
+ Finalize(context, {
404
+ status = "failed",
405
+ error = { message = tostring(compileError), stage = "compile" },
406
+ errorCode = "compile_error",
407
+ })
408
+ return
409
+ end
410
+ setfenv(chunk, context.environment)
411
+
412
+ local packed = Pack(pcall(chunk))
413
+ if not packed[1] then
414
+ Finalize(context, {
415
+ status = "failed",
416
+ error = { message = tostring(packed[2]), stage = "runtime" },
417
+ errorCode = "runtime_error",
418
+ })
419
+ elseif not context.terminal and not context.asyncRequested then
420
+ -- Sync task: returning completes it with the returned values.
421
+ local returns
422
+ if packed.n > 1 then
423
+ returns = {}
424
+ for index = 2, packed.n do
425
+ returns[index - 1] = packed[index]
426
+ end
427
+ end
428
+ Finalize(context, { status = "succeeded", returns = returns })
429
+ end
430
+ -- Async tasks stay active until their callbacks finish or fail explicitly.
431
+ end
432
+
433
+ function Controller.Run(taskId)
434
+ if not EnsureReady() then
435
+ return
436
+ end
437
+ if not IsValidTaskId(taskId) then
438
+ Print(L.AUTO_TASK_INVALID:format(tostring(taskId), "task_id"))
439
+ return
440
+ end
441
+ local definitions = ns.AutomationTaskDefinitions
442
+ local definition = type(definitions) == "table" and definitions[taskId] or nil
443
+ if not definition then
444
+ Print(L.AUTO_TASK_NOT_LOADED:format(taskId))
445
+ return
446
+ end
447
+ local valid, reason = ValidateTaskDefinition(taskId, definition)
448
+ if not valid then
449
+ Print(L.AUTO_TASK_INVALID:format(taskId, tostring(reason)))
450
+ return
451
+ end
452
+ local expiresAt = tonumber(definition.expiresAt) or 0
453
+ if expiresAt > 0 and expiresAt <= time() then
454
+ Print(L.AUTO_TASK_EXPIRED:format(taskId))
455
+ return
456
+ end
457
+ if not ns.AutomationWritesEnabled() then
458
+ Print(L.AUTO_DATABASE_UNSUPPORTED)
459
+ return
460
+ end
461
+ if executedRequests[definition.requestId] then
462
+ -- Same request may not run twice in one session; re-show its notice.
463
+ local record = ns.GetAutomationRecord(definition.requestId)
464
+ local entry = record and record.ticket and ns.GetExport(record.ticket) or nil
465
+ if entry and not activeContext then
466
+ ShowNotice({
467
+ ticket = record.ticket,
468
+ taskId = record.taskId,
469
+ executionId = record.executionId,
470
+ createdAt = entry.createdAt,
471
+ })
472
+ else
473
+ Print(L.AUTO_REQUEST_REPEATED)
474
+ end
475
+ return
476
+ end
477
+ if activeContext or unacknowledgedResults >= MAX_UNACKNOWLEDGED_RESULTS then
478
+ Print(L.AUTO_BUSY)
479
+ return
480
+ end
481
+ ExecuteTask(taskId, definition)
482
+ end
483
+
484
+ function Controller.Bug(countText, requestIdText)
485
+ if not EnsureReady() then
486
+ return
487
+ end
488
+ local count = tonumber(countText)
489
+ if not count or count ~= math.floor(count) or count < 1 or count > 100 then
490
+ Print(L.AUTO_INVALID_COUNT)
491
+ return
492
+ end
493
+ requestIdText = requestIdText or ""
494
+ if requestIdText ~= "" and not IsValidRequestId(requestIdText) then
495
+ Print(L.AUTO_TASK_INVALID:format(requestIdText, "request_id"))
496
+ return
497
+ end
498
+ if not ns.AutomationWritesEnabled() then
499
+ Print(L.AUTO_DATABASE_UNSUPPORTED)
500
+ return
501
+ end
502
+ local executionId = requestIdText ~= "" and requestIdText or GenerateLocalExecutionId()
503
+ if executedRequests[executionId] then
504
+ Print(L.AUTO_REQUEST_REPEATED)
505
+ return
506
+ end
507
+ if activeContext or unacknowledgedResults >= MAX_UNACKNOWLEDGED_RESULTS then
508
+ Print(L.AUTO_BUSY)
509
+ return
510
+ end
511
+ local snapshot, snapshotError = ns.Diagnostics.SnapshotRecentErrors(count, "all")
512
+ if not snapshot then
513
+ Print(L.AUTO_PROVIDER_FAILED:format(tostring(snapshotError)))
514
+ return
515
+ end
516
+
517
+ local record, beginError = ns.BeginAutomationExecution(executionId, {
518
+ taskId = BUG_TASK_ID,
519
+ kind = "bug_snapshot",
520
+ })
521
+ if not record then
522
+ Print(beginError or L.AUTO_REQUEST_REPEATED)
523
+ return
524
+ end
525
+ executedRequests[executionId] = true
526
+
527
+ local context = {
528
+ taskId = BUG_TASK_ID,
529
+ title = L.AUTO_BUG_TITLE:format(count),
530
+ executionId = executionId,
531
+ kind = "bug_snapshot",
532
+ requestType = "bug",
533
+ evidenceKind = "error_log",
534
+ record = record,
535
+ outputLimit = DEFAULT_OUTPUT_LIMIT,
536
+ outputParts = {},
537
+ outputBytes = 0,
538
+ outputTruncated = false,
539
+ log = {},
540
+ cleanups = {},
541
+ terminal = nil,
542
+ asyncRequested = false,
543
+ cancelRequested = false,
544
+ startedAt = time(),
545
+ source = nil,
546
+ params = { count = count, scope = "provider_storage" },
547
+ bugSnapshot = snapshot,
548
+ }
549
+ activeContext = context
550
+ ns.AutomationOverlay.ShowRunning()
551
+ Finalize(context, { status = "succeeded" })
552
+ end
553
+
554
+ function Controller.Status(taskId)
555
+ if not EnsureReady() then
556
+ return
557
+ end
558
+ if not IsValidTaskId(taskId) then
559
+ Print(L.AUTO_TASK_INVALID:format(tostring(taskId), "task_id"))
560
+ return
561
+ end
562
+ local automation = ns.GetAutomationIndex()
563
+ local latest
564
+ if automation then
565
+ for index = 1, #automation.order do
566
+ local record = automation.records[automation.order[index]]
567
+ if record and record.taskId == taskId then
568
+ latest = record
569
+ break
570
+ end
571
+ end
572
+ end
573
+ if not latest then
574
+ Print(L.AUTO_TASK_NOT_LOADED:format(taskId))
575
+ return
576
+ end
577
+ local resultText
578
+ if latest.ticket and ns.GetExport(latest.ticket) then
579
+ resultText = latest.ticket
580
+ elseif latest.ticket then
581
+ resultText = L.AUTO_RESULT_EXPIRED
582
+ else
583
+ resultText = "-"
584
+ end
585
+ Print(L.AUTO_STATUS_LINE:format(taskId, latest.executionId, latest.status, resultText))
586
+ if latest.ticket and resultText == latest.ticket and not activeContext then
587
+ ShowNotice({
588
+ ticket = latest.ticket,
589
+ taskId = latest.taskId,
590
+ executionId = latest.executionId,
591
+ createdAt = ns.GetExport(latest.ticket).createdAt,
592
+ })
593
+ end
594
+ end
595
+
596
+ function Controller.Show(ticket)
597
+ if not EnsureReady() then
598
+ return
599
+ end
600
+ if not IsValidTicket(ticket) then
601
+ Print(L.AUTO_INVALID_TICKET)
602
+ return
603
+ end
604
+ local entry = ns.GetExport(ticket)
605
+ local record = entry and ns.FindAutomationByTicket(ticket) or nil
606
+ if not entry or not record then
607
+ Print(L.AUTO_RESULT_MISSING:format(ticket))
608
+ return
609
+ end
610
+ ShowNotice({
611
+ ticket = ticket,
612
+ taskId = record.taskId,
613
+ executionId = record.executionId,
614
+ createdAt = entry.createdAt,
615
+ })
616
+ end
617
+
618
+ function Controller.Cancel(taskId)
619
+ if not EnsureReady() then
620
+ return
621
+ end
622
+ if not IsValidTaskId(taskId) then
623
+ Print(L.AUTO_TASK_INVALID:format(tostring(taskId), "task_id"))
624
+ return
625
+ end
626
+ if not activeContext or activeContext.taskId ~= taskId then
627
+ Print(L.AUTO_NO_ACTIVE:format(taskId))
628
+ return
629
+ end
630
+ activeContext.cancelRequested = true
631
+ Finalize(activeContext, {
632
+ status = "cancelled",
633
+ errorCode = "cancelled_by_request",
634
+ })
635
+ end
636
+
637
+ function Controller.Stop()
638
+ ns.AutomationOverlay.HideNotice()
639
+ ns.AutomationOverlay.HideStatus()
640
+ Print(L.AUTO_STOPPED)
641
+ end
642
+
643
+ -- The plugin cannot observe whether the host read a result, so the host reports
644
+ -- it back as a chat command: `/dev auto ack <ticket> <received|failed>`. That
645
+ -- clears the pending-flush block immediately (no reload needed) and records the
646
+ -- outcome so the page can show it and a later session keeps it.
647
+ function Controller.Ack(ticket, outcome)
648
+ if not EnsureReady() then
649
+ return
650
+ end
651
+ if not IsValidTicket(ticket) then
652
+ Print(L.AUTO_INVALID_TICKET)
653
+ return
654
+ end
655
+ if outcome ~= "received" and outcome ~= "failed" then
656
+ Print(L.AUTO_ACK_STATUS_INVALID)
657
+ return
658
+ end
659
+ local record = ns.FindAutomationByTicket(ticket)
660
+ if not record then
661
+ Print(L.AUTO_ACK_TICKET_UNKNOWN:format(ticket))
662
+ return
663
+ end
664
+ record.receivedAt = time()
665
+ record.receivedStatus = outcome
666
+ -- Only the first acknowledgement of a result frees a backlog slot; a repeat
667
+ -- ack must not shrink the count twice.
668
+ if not record.acknowledged then
669
+ record.acknowledged = true
670
+ if unacknowledgedResults > 0 then
671
+ unacknowledgedResults = unacknowledgedResults - 1
672
+ end
673
+ end
674
+ if awaitingNotice and awaitingNotice.ticket == ticket then
675
+ awaitingNotice = nil
676
+ ns.AutomationOverlay.HideNotice()
677
+ end
678
+ Print(L.AUTO_ACK_DONE:format(ticket, outcome))
679
+ end
680
+
681
+ function Controller.HandleCommand(text)
682
+ local action, rest = tostring(text or ""):match("^(%S+)%s*(.-)%s*$")
683
+ action = action and action:lower() or ""
684
+ if action == "run" then
685
+ local taskId = rest:match("^(%S+)$")
686
+ if not taskId then
687
+ Print(L.AUTO_USAGE)
688
+ return
689
+ end
690
+ Controller.Run(taskId)
691
+ elseif action == "bug" then
692
+ local count, requestId = rest:match("^(%S+)%s+(%S+)$")
693
+ if not count then
694
+ count = rest:match("^(%S+)$")
695
+ end
696
+ if not count then
697
+ Print(L.AUTO_USAGE)
698
+ return
699
+ end
700
+ Controller.Bug(count, requestId)
701
+ elseif action == "status" then
702
+ local taskId = rest:match("^(%S+)$")
703
+ if not taskId then
704
+ Print(L.AUTO_USAGE)
705
+ return
706
+ end
707
+ Controller.Status(taskId)
708
+ elseif action == "show" then
709
+ local ticket = rest:match("^(%S+)$")
710
+ if not ticket then
711
+ Print(L.AUTO_USAGE)
712
+ return
713
+ end
714
+ Controller.Show(ticket)
715
+ elseif action == "cancel" then
716
+ local taskId = rest:match("^(%S+)$")
717
+ if not taskId then
718
+ Print(L.AUTO_USAGE)
719
+ return
720
+ end
721
+ Controller.Cancel(taskId)
722
+ elseif action == "stop" then
723
+ if rest ~= "" then
724
+ Print(L.AUTO_USAGE)
725
+ return
726
+ end
727
+ Controller.Stop()
728
+ elseif action == "ack" then
729
+ local ticket, outcome = rest:match("^(%S+)%s+(%S+)$")
730
+ if not ticket or not outcome then
731
+ Print(L.AUTO_USAGE)
732
+ return
733
+ end
734
+ Controller.Ack(ticket, outcome:lower())
735
+ else
736
+ Print(L.AUTO_USAGE)
737
+ end
738
+ end
739
+
740
+ function Controller.IsBusy()
741
+ -- Busy means "a new request would be refused", not "a notice is on screen":
742
+ -- a few unacknowledged results may queue before the cap blocks new runs.
743
+ return activeContext ~= nil
744
+ or unacknowledgedResults >= MAX_UNACKNOWLEDGED_RESULTS
745
+ end
746
+
747
+ function Controller.GetUnacknowledgedCount()
748
+ return unacknowledgedResults
749
+ end
750
+
751
+ function Controller.MaxUnacknowledgedResults()
752
+ return MAX_UNACKNOWLEDGED_RESULTS
753
+ end
754
+
755
+ function Controller.GetAwaitingNotice()
756
+ return awaitingNotice
757
+ end