opencode-windows-scheduler 0.0.0-stage → 1.0.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 (172) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/CROSS_PLATFORM.md +113 -0
  3. package/LICENSE +21 -0
  4. package/README.md +173 -2
  5. package/README.ru.md +131 -0
  6. package/ROADMAP-STRATEGY.md +217 -0
  7. package/ROADMAP.md +87 -0
  8. package/dist/core/cron-to-schtasks.d.ts +20 -0
  9. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  10. package/dist/core/cron-to-schtasks.js +233 -0
  11. package/dist/core/dry-run.d.ts +44 -0
  12. package/dist/core/dry-run.d.ts.map +1 -0
  13. package/dist/core/dry-run.js +252 -0
  14. package/dist/core/file-watcher.d.ts +31 -0
  15. package/dist/core/file-watcher.d.ts.map +1 -0
  16. package/dist/core/file-watcher.js +128 -0
  17. package/dist/core/lock.d.ts +43 -0
  18. package/dist/core/lock.d.ts.map +1 -0
  19. package/dist/core/lock.js +118 -0
  20. package/dist/core/matrix.d.ts +167 -0
  21. package/dist/core/matrix.d.ts.map +1 -0
  22. package/dist/core/matrix.js +687 -0
  23. package/dist/core/ps-wrapper.d.ts +60 -0
  24. package/dist/core/ps-wrapper.d.ts.map +1 -0
  25. package/dist/core/ps-wrapper.js +538 -0
  26. package/dist/core/record-history.d.ts +14 -0
  27. package/dist/core/record-history.d.ts.map +1 -0
  28. package/dist/core/record-history.js +360 -0
  29. package/dist/core/scheduler/index.d.ts +20 -0
  30. package/dist/core/scheduler/index.d.ts.map +1 -0
  31. package/dist/core/scheduler/index.js +32 -0
  32. package/dist/core/scheduler/linux.d.ts +32 -0
  33. package/dist/core/scheduler/linux.d.ts.map +1 -0
  34. package/dist/core/scheduler/linux.js +115 -0
  35. package/dist/core/scheduler/logs.d.ts +11 -0
  36. package/dist/core/scheduler/logs.d.ts.map +1 -0
  37. package/dist/core/scheduler/logs.js +34 -0
  38. package/dist/core/scheduler/mac.d.ts +39 -0
  39. package/dist/core/scheduler/mac.d.ts.map +1 -0
  40. package/dist/core/scheduler/mac.js +175 -0
  41. package/dist/core/scheduler/posix.d.ts +40 -0
  42. package/dist/core/scheduler/posix.d.ts.map +1 -0
  43. package/dist/core/scheduler/posix.js +86 -0
  44. package/dist/core/scheduler/registry.d.ts +36 -0
  45. package/dist/core/scheduler/registry.d.ts.map +1 -0
  46. package/dist/core/scheduler/registry.js +56 -0
  47. package/dist/core/scheduler/types.d.ts +63 -0
  48. package/dist/core/scheduler/types.d.ts.map +1 -0
  49. package/dist/core/scheduler/types.js +1 -0
  50. package/dist/core/scheduler/windows.d.ts +47 -0
  51. package/dist/core/scheduler/windows.d.ts.map +1 -0
  52. package/dist/core/scheduler/windows.js +375 -0
  53. package/dist/core/wrappers/bash.d.ts +58 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -0
  55. package/dist/core/wrappers/bash.js +223 -0
  56. package/dist/db/history-repo.d.ts +69 -0
  57. package/dist/db/history-repo.d.ts.map +1 -0
  58. package/dist/db/history-repo.js +150 -0
  59. package/dist/db/index.d.ts +47 -0
  60. package/dist/db/index.d.ts.map +1 -0
  61. package/dist/db/index.js +120 -0
  62. package/dist/db/metrics-repo.d.ts +43 -0
  63. package/dist/db/metrics-repo.d.ts.map +1 -0
  64. package/dist/db/metrics-repo.js +95 -0
  65. package/dist/db/migrate.d.ts +24 -0
  66. package/dist/db/migrate.d.ts.map +1 -0
  67. package/dist/db/migrate.js +237 -0
  68. package/dist/db/recovery.d.ts +11 -0
  69. package/dist/db/recovery.d.ts.map +1 -0
  70. package/dist/db/recovery.js +38 -0
  71. package/dist/db/schema.d.ts +24 -0
  72. package/dist/db/schema.d.ts.map +1 -0
  73. package/dist/db/schema.js +97 -0
  74. package/dist/db/settings-repo.d.ts +8 -0
  75. package/dist/db/settings-repo.d.ts.map +1 -0
  76. package/dist/db/settings-repo.js +27 -0
  77. package/dist/db/tasks-repo.d.ts +26 -0
  78. package/dist/db/tasks-repo.d.ts.map +1 -0
  79. package/dist/db/tasks-repo.js +120 -0
  80. package/dist/db/templates-repo.d.ts +17 -0
  81. package/dist/db/templates-repo.d.ts.map +1 -0
  82. package/dist/db/templates-repo.js +57 -0
  83. package/dist/gui-experimental.cjs +1 -0
  84. package/dist/history.d.ts +53 -0
  85. package/dist/history.d.ts.map +1 -0
  86. package/dist/history.js +57 -0
  87. package/dist/index.d.ts +156 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +2077 -0
  90. package/dist/notifications.d.ts +45 -0
  91. package/dist/notifications.d.ts.map +1 -0
  92. package/dist/notifications.js +135 -0
  93. package/dist/rpc.d.ts +2052 -0
  94. package/dist/rpc.d.ts.map +1 -0
  95. package/dist/rpc.js +863 -0
  96. package/dist/schtasks.d.ts +32 -0
  97. package/dist/schtasks.d.ts.map +1 -0
  98. package/dist/schtasks.js +45 -0
  99. package/dist/server.d.ts +106 -0
  100. package/dist/server.d.ts.map +1 -0
  101. package/dist/server.js +1478 -0
  102. package/dist/settings.d.ts +43 -0
  103. package/dist/settings.d.ts.map +1 -0
  104. package/dist/settings.js +96 -0
  105. package/dist/shared/jobs-view.d.ts +21 -0
  106. package/dist/shared/jobs-view.d.ts.map +1 -0
  107. package/dist/shared/jobs-view.js +28 -0
  108. package/dist/skill.d.ts +15 -0
  109. package/dist/skill.d.ts.map +1 -0
  110. package/dist/skill.js +93 -0
  111. package/dist/task-transfer.d.ts +176 -0
  112. package/dist/task-transfer.d.ts.map +1 -0
  113. package/dist/task-transfer.js +442 -0
  114. package/dist/templates.d.ts +57 -0
  115. package/dist/templates.d.ts.map +1 -0
  116. package/dist/templates.js +16 -0
  117. package/dist/types.d.ts +78 -0
  118. package/dist/types.d.ts.map +1 -0
  119. package/dist/types.js +88 -0
  120. package/dist/workspaces.d.ts +55 -0
  121. package/dist/workspaces.d.ts.map +1 -0
  122. package/dist/workspaces.js +183 -0
  123. package/docs/ARCHITECTURE.md +302 -0
  124. package/docs/FEATURES.md +288 -0
  125. package/docs/MIGRATION.md +266 -0
  126. package/docs/dashboard.png +0 -0
  127. package/gui-experimental.cjs +2 -0
  128. package/index.js +1 -0
  129. package/package.json +92 -4
  130. package/scripts/demo-dashboard.mjs +199 -0
  131. package/skills/scheduled-job-best-practices/SKILL.md +155 -0
  132. package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
  133. package/src/core/cron-to-schtasks.ts +269 -0
  134. package/src/core/dry-run.ts +315 -0
  135. package/src/core/file-watcher.ts +171 -0
  136. package/src/core/lock.ts +134 -0
  137. package/src/core/matrix.ts +907 -0
  138. package/src/core/ps-wrapper.ts +572 -0
  139. package/src/core/record-history.ts +493 -0
  140. package/src/core/scheduler/index.ts +44 -0
  141. package/src/core/scheduler/linux.ts +125 -0
  142. package/src/core/scheduler/logs.ts +37 -0
  143. package/src/core/scheduler/mac.ts +222 -0
  144. package/src/core/scheduler/posix.ts +111 -0
  145. package/src/core/scheduler/registry.ts +93 -0
  146. package/src/core/scheduler/types.ts +67 -0
  147. package/src/core/scheduler/windows.ts +469 -0
  148. package/src/core/wrappers/bash.ts +282 -0
  149. package/src/db/history-repo.ts +303 -0
  150. package/src/db/index.ts +166 -0
  151. package/src/db/metrics-repo.ts +158 -0
  152. package/src/db/migrate.ts +322 -0
  153. package/src/db/recovery.ts +46 -0
  154. package/src/db/schema.ts +109 -0
  155. package/src/db/settings-repo.ts +31 -0
  156. package/src/db/tasks-repo.ts +162 -0
  157. package/src/db/templates-repo.ts +77 -0
  158. package/src/gui.tsx +2725 -0
  159. package/src/history.ts +107 -0
  160. package/src/index.ts +2672 -0
  161. package/src/notifications.ts +174 -0
  162. package/src/rpc.ts +933 -0
  163. package/src/schtasks.ts +75 -0
  164. package/src/server.ts +1663 -0
  165. package/src/settings.ts +157 -0
  166. package/src/shared/jobs-view.ts +38 -0
  167. package/src/skill.ts +113 -0
  168. package/src/task-transfer.ts +648 -0
  169. package/src/templates.ts +67 -0
  170. package/src/tui.tsx +46 -0
  171. package/src/types.ts +145 -0
  172. package/src/workspaces.ts +236 -0
@@ -0,0 +1,572 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { PLUGIN_DIR, LOG_DIR, WRAPPER_DIR } from "../types.js";
4
+
5
+ /**
6
+ * Путь к единому generic-обёртке PowerShell, которая реализует запуск opencode run
7
+ * с таймаутом и lock-логикой.
8
+ */
9
+ const WRAPPER_FILENAME = "run-task.ps1";
10
+
11
+ /**
12
+ * Текст PowerShell-обёртки.
13
+ *
14
+ * Параметры:
15
+ * TaskName — имя задачи (для логов)
16
+ * PromptFile — путь к файлу с промптом (читается через Get-Content -Raw)
17
+ * TimeoutSeconds — таймаут в секундах
18
+ * Model — LLM-модель для `opencode run --model` (опционально)
19
+ * Workdir — рабочая директория (опционально)
20
+ * WorkspaceName — имя multi-repo workspace для git-контекста в логе
21
+ * LockFile — путь к lock-файлу (удаляется в finally)
22
+ * BeforeScript — pre-flight команда (ненулевой код отменяет задачу)
23
+ * AfterScript — post-flight команда (выполняется даже при ошибке)
24
+ *
25
+ * Логика:
26
+ * 1. Выполняет pre-flight (если задан); при ошибке задача не запускается.
27
+ * 2. Читает промпт из файла.
28
+ * 3. Запускает opencode run <промпт> через Start-Process (без окна консоли).
29
+ * 4. Ждёт завершения с таймаутом.
30
+ * 5. При таймауте — убивает процесс и дочерние процессы.
31
+ * 6. В finally выполняет post-flight и удаляет lock-файл.
32
+ */
33
+ export const WRAPPER_SCRIPT = `param(
34
+ [string]$TaskName,
35
+ [string]$PromptFile,
36
+ [int]$TimeoutSeconds,
37
+ [string]$Model,
38
+ [string]$Workdir,
39
+ [string]$WorkspaceName,
40
+ [string]$AllowedTools,
41
+ [string]$DeniedTools,
42
+ [string]$LockFile,
43
+ [string]$LogFile,
44
+ [string]$RecorderFile,
45
+ [string]$QualityGate,
46
+ [string]$BeforeScript,
47
+ [string]$AfterScript
48
+ )
49
+
50
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
51
+ $OutputEncoding = [System.Text.Encoding]::UTF8
52
+
53
+ $ErrorActionPreference = "Continue"
54
+
55
+ function Write-Log {
56
+ param([string]$Message)
57
+ $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
58
+ $line = "[$timestamp] $Message"
59
+ if ($LogFile) {
60
+ try {
61
+ Add-Content -Path $LogFile -Value $line -Encoding utf8
62
+ } catch {}
63
+ }
64
+ Write-Host $line
65
+ }
66
+
67
+ # Гарантируем существование папки для лога (на случай прямого вызова обёртки).
68
+ if ($LogFile) {
69
+ try {
70
+ $logDir = Split-Path -Parent $LogFile
71
+ if ($logDir -and -not (Test-Path $logDir)) {
72
+ New-Item -ItemType Directory -Force -Path $logDir | Out-Null
73
+ }
74
+ } catch {}
75
+ }
76
+
77
+ Write-Log "[windows-scheduler] Запуск задачи '$TaskName'..."
78
+
79
+ $startTime = Get-Date
80
+ $script:exitCode = 0
81
+ $script:errorMessage = ""
82
+ $script:preFlightStatus = "skipped"
83
+ $script:postFlightStatus = "skipped"
84
+ $script:skipMainTask = $false
85
+ $startedAtIso = $startTime.ToUniversalTime().ToString("o")
86
+ $script:runId = ""
87
+
88
+ # Crash recovery: фиксируем начало ДО pre-flight и основной задачи.
89
+ # Если процесс убьют (таймаут/KILL/перезагрузка), останется finished_at = NULL,
90
+ # и при следующем старте плагина recovery пометит запись как error.
91
+ if ($RecorderFile) {
92
+ try {
93
+ $startOutput = & node "$RecorderFile" --start "$TaskName" "$startedAtIso" 2>$null
94
+ if ($LASTEXITCODE -eq 0) {
95
+ $candidate = @($startOutput) | Select-Object -Last 1
96
+ if ($candidate) { $script:runId = "$candidate".Trim() }
97
+ }
98
+ } catch {}
99
+ }
100
+
101
+ # Выполняет команду оболочки и построчно пишет её вывод в лог.
102
+ function Invoke-HookScript {
103
+ param([string]$Command)
104
+ $output = & cmd.exe /c $Command 2>&1
105
+ $code = $LASTEXITCODE
106
+ foreach ($line in @($output)) {
107
+ Write-Log "[hook] $line"
108
+ }
109
+ return $code
110
+ }
111
+
112
+ # Фильтр технического шума и служебных блоков OpenCode.
113
+ # Строки ответа ИИ проходят без изменений.
114
+ #
115
+ # В TS-шаблоне обратные слэши удвоены, иначе JS съедает \s и regex ломается.
116
+ $esc = [char]27
117
+ $script:inServiceBlock = $false
118
+ $script:inComment = $false
119
+
120
+ $serviceOpen = '<\\s*(?:dcp-)?system[-_](?:reminder|update)\\b[^>]*>'
121
+ $serviceClose = '<\\s*/\\s*(?:dcp-)?system[-_](?:reminder|update)\\s*>'
122
+ $serviceTag = '<\\s*/?\\s*(?:dcp-)?system[-_](?:reminder|update)\\b[^>]*>'
123
+
124
+ function Format-LogLine {
125
+ param($Line)
126
+ $text = "$Line"
127
+
128
+ # ANSI-последовательности (цвета, управление курсором), например ESC[0m.
129
+ $text = $text -replace "$esc\\[[0-9;?]*[A-Za-z]", ""
130
+
131
+ # Служебные блоки, целиком уместившиеся в одной строке.
132
+ $text = [regex]::Replace($text, "$serviceOpen.*?$serviceClose", "", "IgnoreCase")
133
+ $text = [regex]::Replace($text, '<!--.*?-->', "", "IgnoreCase")
134
+
135
+ # Начало многострочного служебного блока OpenCode:
136
+ # <dcp-system-reminder> ... </dcp-system-reminder> (и <system-reminder>).
137
+ # Блоком считаем только тег в начале строки: одиночный тег внутри текста
138
+ # (например, ИИ упомянул его в объяснении) не должен съедать следующие строки.
139
+ if ($text -match "^\\s*$serviceOpen") { $script:inServiceBlock = $true }
140
+ if ($text -match '^\\s*<!--') { $script:inComment = $true }
141
+
142
+ if ($script:inServiceBlock -or $script:inComment) {
143
+ $closed = $false
144
+ if ($script:inServiceBlock -and $text -match $serviceClose) {
145
+ $script:inServiceBlock = $false
146
+ $closed = $true
147
+ }
148
+ if ($script:inComment -and $text -match '-->') {
149
+ $script:inComment = $false
150
+ $closed = $true
151
+ }
152
+
153
+ if ($closed) {
154
+ # Блок закончился в этой строке — сохраняем только хвост после тега.
155
+ $text = ($text -split '-->|<\\s*/\\s*(?:dcp-)?system[-_](?:reminder|update)\\s*>')[-1]
156
+ } else {
157
+ # Внутри служебного блока — строку не пишем.
158
+ return
159
+ }
160
+ }
161
+
162
+ # Одиночные теги, оставшиеся после вывода ИИ.
163
+ $text = [regex]::Replace($text, $serviceTag, "", "IgnoreCase")
164
+ $text = $text.TrimEnd()
165
+
166
+ # Технический шум вложенного powershell.exe.
167
+ if ($text -match "NativeCommandError|CategoryInfo|FullyQualifiedErrorId|RemoteException") { return }
168
+ if ($text -match "^At [A-Za-z]:.*:") { return }
169
+ if ($text -match "^\\s*\\+\\s*~+\\s*$") { return }
170
+ if (-not $text.Trim()) { return }
171
+
172
+ return $text
173
+ }
174
+
175
+ /**
176
+ * Пытается вытащить из лога задачи информацию о расходе токенов и стоимости.
177
+ * OpenCode может печатать строки вида "Tokens: 1234", "Usage: 1234 tokens",
178
+ * "cost: $0.012" и т.п. Если данные не найдены — возвращает пустые строки,
179
+ * чтобы recorder записал поля как отсутствующие.
180
+ */
181
+ function Get-UsageFromLog {
182
+ param([string]$File)
183
+
184
+ $result = @{ Tokens = ""; Cost = "" }
185
+ if (-not $File) { return $result }
186
+
187
+ $tail = @()
188
+ try {
189
+ if (Test-Path $File) {
190
+ $tail = Get-Content -Path $File -Tail 500 -Encoding UTF8 -ErrorAction SilentlyContinue
191
+ }
192
+ } catch { return $result }
193
+ if (-not $tail) { return $result }
194
+
195
+ $tokenPatterns = @(
196
+ '(?i)tokens?\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*([kKmM])?',
197
+ '(?i)(?:input|output|total)\\s+tokens?\\s*[:=]?\\s*([0-9]+(?:[.,][0-9]+)?)\\s*([kKmM])?',
198
+ '(?i)usage[^\\r\\n]*?([0-9]+)\\s+tokens?'
199
+ )
200
+ $costPatterns = @(
201
+ '(?i)(?:cost|price|стоимость)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)',
202
+ '(?i)(?:cost|price|стоимость)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)'
203
+ )
204
+
205
+ foreach ($line in $tail) {
206
+ $text = "$line"
207
+
208
+ if (-not $result.Tokens) {
209
+ foreach ($pattern in $tokenPatterns) {
210
+ if ($text -match $pattern) {
211
+ $raw = $matches[1] -replace ',', '.'
212
+ $value = 0.0
213
+ if ([double]::TryParse($raw, [ref]$value)) {
214
+ $suffix = ""
215
+ if ($matches.Count -gt 2 -and $matches[2]) {
216
+ $suffix = $matches[2].ToString().ToLower()
217
+ }
218
+ if ($suffix -eq 'k') { $value = $value * 1000 }
219
+ elseif ($suffix -eq 'm') { $value = $value * 1000000 }
220
+ $result.Tokens = [string]([int64][Math]::Round($value))
221
+ }
222
+ break
223
+ }
224
+ }
225
+ }
226
+
227
+ if (-not $result.Cost) {
228
+ foreach ($pattern in $costPatterns) {
229
+ if ($text -match $pattern) {
230
+ $result.Cost = $matches[1] -replace ',', '.'
231
+ break
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ return $result
238
+ }
239
+
240
+ try {
241
+ # Рабочая директория нужна и хукам, и основной задаче.
242
+ if ($Workdir) {
243
+ Set-Location $Workdir
244
+ }
245
+
246
+ if ($WorkspaceName) {
247
+ $gitBranch = "-"
248
+ $gitRemote = "-"
249
+ try {
250
+ $branchOut = & git -C "$Workdir" rev-parse --abbrev-ref HEAD 2>$null
251
+ if ($LASTEXITCODE -eq 0 -and $branchOut) { $gitBranch = "$branchOut".Trim() }
252
+ } catch {}
253
+ try {
254
+ $remoteOut = & git -C "$Workdir" remote get-url origin 2>$null
255
+ if ($LASTEXITCODE -eq 0 -and $remoteOut) { $gitRemote = "$remoteOut".Trim() }
256
+ } catch {}
257
+ Write-Log "[workspace] name=$WorkspaceName, cwd=$Workdir, branch=$gitBranch, remote=$gitRemote"
258
+ }
259
+
260
+ # Role-scoped tools: ограничения хранятся в определении задачи. Текущая
261
+ # версия opencode run не поддерживает --allow-tool/--deny-tool, поэтому
262
+ # это предупреждение + запись в историю, а не реальное блокирование.
263
+ if ($AllowedTools -or $DeniedTools) {
264
+ Write-Log "[role-scoped] allowed=[$AllowedTools], denied=[$DeniedTools]"
265
+ $deniedList = @($DeniedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
266
+ $dangerous = @('write', 'edit', 'bash', 'apply_patch', 'remove')
267
+ $hit = @($dangerous | Where-Object { $deniedList -contains $_ })
268
+ if ($hit.Count -gt 0) {
269
+ Write-Log "[role-scoped] ВНИМАНИЕ: deniedTools содержит опасные инструменты ($($hit -join ', ')), но opencode run их не ограничивает. Проверьте результаты задачи."
270
+ }
271
+ }
272
+
273
+ # Pre-flight: выполняется ДО основной задачи. Ненулевой код отменяет запуск.
274
+ if ($BeforeScript) {
275
+ Write-Log "[windows-scheduler] Pre-flight: $BeforeScript"
276
+ $preCode = Invoke-HookScript -Command $BeforeScript
277
+ if ($preCode -ne 0) {
278
+ Write-Log "[windows-scheduler] ОШИБКА: Pre-flight script failed (код $preCode)."
279
+ $script:preFlightStatus = "error"
280
+ $script:errorMessage = "Pre-flight script failed"
281
+ $script:exitCode = 1
282
+ $script:skipMainTask = $true
283
+ } else {
284
+ $script:preFlightStatus = "success"
285
+ Write-Log "[windows-scheduler] Pre-flight успешно завершён."
286
+ }
287
+ }
288
+
289
+ if (-not $script:skipMainTask) {
290
+ $prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
291
+
292
+ # Получаем путь к скрипту opencode (.ps1 или .cmd)
293
+ $opencodeCmd = Get-Command opencode | Select-Object -ExpandProperty Source
294
+
295
+ # Формируем аргументы для opencode run
296
+ $opencodeArgs = @("run")
297
+ if ($Model) {
298
+ $opencodeArgs += @("--model", $Model)
299
+ }
300
+ if ($prompt) {
301
+ $opencodeArgs += $prompt
302
+ }
303
+
304
+ # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
305
+ # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
306
+ # ответ ИИ появляется в GUI ещё до завершения задачи.
307
+ if ($LogFile) {
308
+ if ($opencodeCmd -like "*.ps1") {
309
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $opencodeCmd @opencodeArgs *>&1 |
310
+ ForEach-Object { Format-LogLine $_ } |
311
+ Out-File -FilePath $LogFile -Append -Encoding utf8
312
+ } else {
313
+ & $opencodeCmd @opencodeArgs *>&1 |
314
+ ForEach-Object { Format-LogLine $_ } |
315
+ Out-File -FilePath $LogFile -Append -Encoding utf8
316
+ }
317
+ } else {
318
+ if ($opencodeCmd -like "*.ps1") {
319
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $opencodeCmd @opencodeArgs *>&1 |
320
+ ForEach-Object { Format-LogLine $_ } |
321
+ Out-Host
322
+ } else {
323
+ & $opencodeCmd @opencodeArgs *>&1 |
324
+ ForEach-Object { Format-LogLine $_ } |
325
+ Out-Host
326
+ }
327
+ }
328
+ $script:exitCode = $LASTEXITCODE
329
+
330
+ # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
331
+ # завершения opencode run. Если ИИ упал — шлюз не запускаем.
332
+ if ($QualityGate -and $script:exitCode -eq 0) {
333
+ Write-Log "[windows-scheduler] Запуск Quality Gate: $QualityGate"
334
+ $gateOutput = & cmd.exe /c $QualityGate 2>&1
335
+ $gateCode = $LASTEXITCODE
336
+
337
+ if ($LogFile) {
338
+ try {
339
+ $gateOutput | ForEach-Object { Add-Content -Path $LogFile -Value "$_" -Encoding utf8 }
340
+ } catch {}
341
+ } else {
342
+ $gateOutput | Out-Host
343
+ }
344
+
345
+ if ($gateCode -ne 0) {
346
+ Write-Log "[windows-scheduler] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
347
+ $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
348
+ $script:exitCode = 1
349
+ } else {
350
+ Write-Log "[windows-scheduler] Quality Gate пройден."
351
+ }
352
+ }
353
+
354
+ if ($script:exitCode -ne 0) {
355
+ Write-Log "[windows-scheduler] Задача '$TaskName' завершилась с кодом $script:exitCode."
356
+ } else {
357
+ Write-Log "[windows-scheduler] Задача '$TaskName' успешно завершена."
358
+ }
359
+ } # конец блока основной задачи
360
+ } catch {
361
+ Write-Log "[windows-scheduler] Ошибка выполнения задачи '$TaskName': $_"
362
+ $script:errorMessage = "Ошибка выполнения задачи: $_"
363
+ $script:exitCode = 1
364
+ } finally {
365
+ # Post-flight: выполняется ВСЕГДА, даже если основная задача упала.
366
+ if ($AfterScript) {
367
+ Write-Log "[windows-scheduler] Post-flight: $AfterScript"
368
+ $postCode = Invoke-HookScript -Command $AfterScript
369
+ if ($postCode -ne 0) {
370
+ Write-Log "[windows-scheduler] ОШИБКА: Post-flight script failed (код $postCode)."
371
+ $script:postFlightStatus = "error"
372
+ if ($script:exitCode -eq 0) {
373
+ $script:errorMessage = "Post-flight script failed"
374
+ $script:exitCode = 1
375
+ }
376
+ } else {
377
+ $script:postFlightStatus = "success"
378
+ Write-Log "[windows-scheduler] Post-flight успешно завершён."
379
+ }
380
+ }
381
+
382
+ # Фиксируем факт выполнения в историю и метрики (независимо от того, кто запустил: GUI или Windows)
383
+ $endTime = Get-Date
384
+ $durationMs = [int](($endTime - $startTime).TotalMilliseconds)
385
+ $status = if ($script:exitCode -eq 0) { "success" } else { "error" }
386
+ $usage = Get-UsageFromLog -File $LogFile
387
+ $tokensArg = "-"
388
+ if ($usage.Tokens) { $tokensArg = $usage.Tokens }
389
+ $costArg = "-"
390
+ if ($usage.Cost) { $costArg = $usage.Cost }
391
+ $modelArg = "-"
392
+ if ($Model) { $modelArg = $Model }
393
+ if ($RecorderFile) {
394
+ try {
395
+ if ($script:runId) {
396
+ & node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
397
+ } else {
398
+ # Fallback: --start не удался (например, старая установка) —
399
+ # пишем завершённую запись старым способом, без потери истории.
400
+ & node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
401
+ }
402
+ } catch {}
403
+ }
404
+
405
+ if ($LockFile -and (Test-Path $LockFile)) {
406
+ try {
407
+ Remove-Item $LockFile -Force
408
+ } catch {}
409
+ }
410
+ }
411
+
412
+ exit $script:exitCode
413
+ `;
414
+
415
+ /**
416
+ * Гарантирует existence директорий плагина и записывает generic-обёртку.
417
+ * Возвращает путь к обёртке.
418
+ */
419
+ export async function ensureWrapper(): Promise<string> {
420
+ await fs.mkdir(WRAPPER_DIR, { recursive: true });
421
+ const wrapperPath = path.join(WRAPPER_DIR, WRAPPER_FILENAME);
422
+ // BOM обязателен: Windows PowerShell 5.1 читает .ps1 без BOM как ANSI,
423
+ // из-за чего кириллица в сообщениях Write-Log превращается в мусор.
424
+ await fs.writeFile(wrapperPath, "\uFEFF" + WRAPPER_SCRIPT, "utf8");
425
+ return wrapperPath;
426
+ }
427
+
428
+ /**
429
+ * Записывает промпт задачи во временный файл и возвращает его путь.
430
+ */
431
+ export async function writePromptFile(taskName: string, prompt: string): Promise<string> {
432
+ const promptDir = path.join(PLUGIN_DIR, "prompts");
433
+ await fs.mkdir(promptDir, { recursive: true });
434
+ const promptPath = path.join(promptDir, `${taskName}.txt`);
435
+ // BOM помогает Windows PowerShell 5.1 правильно прочитать кириллицу.
436
+ // На POSIX BOM попал бы в промпт как мусорный символ — не пишем его.
437
+ const content = process.platform === "win32" ? "\uFEFF" + prompt : prompt;
438
+ await fs.writeFile(promptPath, content, "utf8");
439
+ return promptPath;
440
+ }
441
+
442
+ /**
443
+ * Возвращает путь к lock-файлу задачи.
444
+ */
445
+ export function lockFilePath(taskName: string): string {
446
+ return path.join(PLUGIN_DIR, "locks", `${taskName}.lock`);
447
+ }
448
+
449
+ /**
450
+ * Генерирует per-task .cmd-обёртку, которую schtasks вызывает через /tr.
451
+ * Внутри .cmd — жёстко заданный вызов run-task.ps1 с задачей, промптом,
452
+ * таймаутом и lock-файлом. schtasks получает только один путь (в кавычках),
453
+ * поэтому спецсимволы и кириллица в аргументах больше не ломают парсинг.
454
+ *
455
+ * @param sanitizedName безопасное имя для файла (латиница, цифры, -, _)
456
+ * @param taskName отображаемое имя задачи в taskschd.msc (как есть, может быть кириллицей)
457
+ * @param promptFile абсолютный путь к файлу с промптом
458
+ * @param timeoutSeconds таймаут в секундах
459
+ * @param lockFile абсолютный путь к lock-файлу
460
+ * @param workdir рабочая директория (опционально; по умолчанию — process.cwd())
461
+ * @param logFile путь к файлу лога
462
+ * @param recorderFile путь к record-history.js (история/метрики)
463
+ * @param qualityGate проверочная команда Quality Gate
464
+ * @param model LLM-модель для `opencode run --model` (опционально)
465
+ * @param beforeScript pre-flight команда (опционально)
466
+ * @param afterScript post-flight команда (опционально)
467
+ * @param workspaceName имя workspace для git-контекста в логе (опционально)
468
+ * @param allowedTools список разрешённых инструментов (спринт 14, опционально)
469
+ * @param deniedTools список запрещённых инструментов (спринт 14, опционально)
470
+ */
471
+ export async function writeWrapperCmd(
472
+ sanitizedName: string,
473
+ taskName: string,
474
+ promptFile: string,
475
+ timeoutSeconds: number,
476
+ lockFile: string,
477
+ workdir?: string,
478
+ logFile?: string,
479
+ recorderFile?: string,
480
+ qualityGate?: string,
481
+ model?: string,
482
+ beforeScript?: string,
483
+ afterScript?: string,
484
+ workspaceName?: string,
485
+ allowedTools?: string[],
486
+ deniedTools?: string[]
487
+ ): Promise<string> {
488
+ await fs.mkdir(WRAPPER_DIR, { recursive: true });
489
+ const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
490
+ const ps1Path = path.join(WRAPPER_DIR, WRAPPER_FILENAME);
491
+
492
+ // ВАЖНО: команда powershell.exe должна быть ОДНОЙ строкой.
493
+ // Раньше -LogFile и -RecorderFile добавлялись отдельными строками .cmd,
494
+ // из-за чего PowerShell их не получал, а cmd пытался выполнить их как
495
+ // самостоятельные команды: логи оставались пустыми, история не писалась.
496
+ const psArgs: string[] = [
497
+ `powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -NoProfile -File "${ps1Path}"`,
498
+ `-TaskName "${taskName}"`,
499
+ `-PromptFile "${promptFile}"`,
500
+ `-TimeoutSeconds ${timeoutSeconds}`,
501
+ `-LockFile "${lockFile}"`,
502
+ ];
503
+
504
+ if (logFile) {
505
+ psArgs.push(`-LogFile "${logFile}"`);
506
+ }
507
+
508
+ if (recorderFile) {
509
+ psArgs.push(`-RecorderFile "${recorderFile}"`);
510
+ }
511
+
512
+ if (qualityGate) {
513
+ // Кавычки в .cmd-строке ломают передачу аргумента, переводы строк — тоже.
514
+ const safeGate = qualityGate.replace(/[\r\n]+/g, " ").replace(/"/g, "'").trim();
515
+ if (safeGate) {
516
+ psArgs.push(`-QualityGate "${safeGate}"`);
517
+ }
518
+ }
519
+
520
+ if (model?.trim()) {
521
+ const safeModel = model.replace(/[\r\n"]+/g, "").trim();
522
+ if (safeModel) {
523
+ psArgs.push(`-Model "${safeModel}"`);
524
+ }
525
+ }
526
+
527
+ if (workspaceName?.trim()) {
528
+ const safeWorkspace = workspaceName.replace(/[\r\n"]+/g, "'").trim();
529
+ if (safeWorkspace) {
530
+ psArgs.push(`-WorkspaceName "${safeWorkspace}"`);
531
+ }
532
+ }
533
+
534
+ // Role-scoped tools (спринт 14): передаём списки одной строкой через запятую.
535
+ for (const [flag, list] of [
536
+ ["-AllowedTools", allowedTools],
537
+ ["-DeniedTools", deniedTools],
538
+ ] as const) {
539
+ const joined = (Array.isArray(list) ? list : [])
540
+ .map((item) => String(item).trim())
541
+ .filter(Boolean)
542
+ .join(",");
543
+ if (joined) {
544
+ const safe = joined.replace(/[\r\n"]+/g, "'");
545
+ psArgs.push(`${flag} "${safe}"`);
546
+ }
547
+ }
548
+
549
+ // Хуки передаются одной строкой: кавычки заменяем на апострофы, как у Quality Gate.
550
+ for (const [flag, script] of [
551
+ ["-BeforeScript", beforeScript],
552
+ ["-AfterScript", afterScript],
553
+ ] as const) {
554
+ const safe = script?.replace(/[\r\n]+/g, " ").replace(/"/g, "'").trim();
555
+ if (safe) {
556
+ psArgs.push(`${flag} "${safe}"`);
557
+ }
558
+ }
559
+
560
+ const lines: string[] = ["@echo off", "chcp 65001 >nul"];
561
+
562
+ // Рабочая директория: всегда переходим в неё ДО запуска PowerShell.
563
+ // По умолчанию — текущая папка проекта (process.cwd()). Это критично для
564
+ // MCP: opencode run подхватывает opencode.json из рабочей директории.
565
+ const effectiveWorkdir = workdir?.trim() || process.cwd();
566
+ lines.push(`cd /d "${effectiveWorkdir}"`);
567
+
568
+ lines.push(psArgs.join(" "));
569
+
570
+ await fs.writeFile(cmdPath, lines.join("\r\n"), "utf8");
571
+ return cmdPath;
572
+ }