opencode-windows-scheduler 1.5.4 → 1.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -5
- package/CROSS_PLATFORM.md +107 -71
- package/README.md +72 -25
- package/ROADMAP-STRATEGY.md +6 -0
- package/ROADMAP.md +116 -85
- package/dist/core/analytics.d.ts +3 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +4 -0
- package/dist/core/audit.d.ts +2 -1
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +32 -1
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +21 -4
- package/dist/core/file-watcher.d.ts.map +1 -1
- package/dist/core/file-watcher.js +16 -1
- package/dist/core/git-trigger.d.ts +4 -2
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +34 -16
- package/dist/core/lock.d.ts +14 -0
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +81 -4
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +3 -2
- package/dist/core/native-notify.d.ts.map +1 -1
- package/dist/core/native-notify.js +3 -0
- package/dist/core/one-shot.d.ts +7 -1
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +15 -2
- package/dist/core/permissions.d.ts +69 -0
- package/dist/core/permissions.d.ts.map +1 -0
- package/dist/core/permissions.js +143 -0
- package/dist/core/ps-wrapper.d.ts +9 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +293 -96
- package/dist/core/record-history.d.ts +11 -0
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +106 -4
- package/dist/core/savings.d.ts +70 -0
- package/dist/core/savings.d.ts.map +1 -0
- package/dist/core/savings.js +87 -0
- package/dist/core/schedule-gate.js +7 -3
- package/dist/core/schedule-v2.js +1 -1
- package/dist/core/scheduler/index.d.ts +13 -1
- package/dist/core/scheduler/index.d.ts.map +1 -1
- package/dist/core/scheduler/index.js +35 -4
- package/dist/core/scheduler/linux.d.ts +4 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +53 -20
- package/dist/core/scheduler/mac.d.ts +2 -1
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +24 -6
- package/dist/core/scheduler/posix.d.ts +1 -1
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +2 -2
- package/dist/core/scheduler/registry.d.ts +3 -2
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/registry.js +6 -5
- package/dist/core/scheduler/windows.d.ts +49 -1
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +219 -34
- package/dist/core/secrets.d.ts +5 -3
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +86 -8
- package/dist/core/self-analysis.d.ts +117 -0
- package/dist/core/self-analysis.d.ts.map +1 -0
- package/dist/core/self-analysis.js +539 -0
- package/dist/core/session.d.ts +11 -3
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +34 -5
- package/dist/core/shutdown.d.ts +26 -0
- package/dist/core/shutdown.d.ts.map +1 -0
- package/dist/core/shutdown.js +49 -0
- package/dist/core/summary.d.ts +69 -0
- package/dist/core/summary.d.ts.map +1 -0
- package/dist/core/summary.js +250 -0
- package/dist/core/telegram.d.ts +10 -0
- package/dist/core/telegram.d.ts.map +1 -1
- package/dist/core/telegram.js +228 -47
- package/dist/core/triage-chain.d.ts +9 -3
- package/dist/core/triage-chain.d.ts.map +1 -1
- package/dist/core/triage-chain.js +15 -5
- package/dist/core/triage-compare.d.ts +68 -0
- package/dist/core/triage-compare.d.ts.map +1 -0
- package/dist/core/triage-compare.js +184 -0
- package/dist/core/triage-rules.d.ts.map +1 -1
- package/dist/core/triage-rules.js +22 -0
- package/dist/core/triage-shadow.d.ts +54 -10
- package/dist/core/triage-shadow.d.ts.map +1 -1
- package/dist/core/triage-shadow.js +138 -26
- package/dist/core/triage-worker.d.ts +55 -0
- package/dist/core/triage-worker.d.ts.map +1 -0
- package/dist/core/triage-worker.js +314 -0
- package/dist/core/triage.js +1 -1
- package/dist/core/watch-paths.d.ts +6 -0
- package/dist/core/watch-paths.d.ts.map +1 -0
- package/dist/core/watch-paths.js +62 -0
- package/dist/core/wrappers/bash.d.ts +15 -3
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +153 -120
- package/dist/db/history-repo.d.ts +1 -1
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +29 -14
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +31 -0
- package/dist/history.d.ts +2 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +3 -3
- package/dist/i18n.d.ts +25 -2
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +41 -3
- package/dist/index.d.ts +40 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +345 -71
- package/dist/integrations.d.ts +9 -1
- package/dist/integrations.d.ts.map +1 -1
- package/dist/integrations.js +34 -6
- package/dist/notifications.d.ts +30 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +287 -16
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +21 -3
- package/dist/rpc.d.ts +145 -8
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +81 -6
- package/dist/server.d.ts +20 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +136 -14
- package/dist/settings.d.ts +89 -5
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +143 -23
- package/dist/task-transfer.d.ts +8 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +2 -2
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +23 -5
- package/dist/workspaces.d.ts +9 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +25 -0
- package/docs/ARCHITECTURE.md +40 -22
- package/docs/CONCEPT.md +230 -0
- package/docs/CROSS_PLATFORM.ru.md +150 -0
- package/docs/CROSS_PLATFORM.zh.md +146 -0
- package/docs/FAQ.md +52 -0
- package/docs/FAQ.ru.md +53 -0
- package/docs/FAQ.zh.md +43 -0
- package/docs/FEATURES.md +125 -48
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +114 -16
- package/docs/README.ru.md +18 -13
- package/docs/README.zh.md +286 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/gui-experimental.cjs +8 -8
- package/locales/en.json +54 -1
- package/locales/ru.json +54 -1
- package/locales/zh.json +780 -0
- package/package.json +24 -7
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/test-locale.mjs +4 -3
- package/skills/scheduled-job-best-practices/SKILL.md +6 -3
- package/skills/scheduled-job-best-practices/references/recipes.md +1 -1
- package/src/core/analytics.ts +10 -0
- package/src/core/audit.ts +39 -1
- package/src/core/cron-to-schtasks.ts +23 -4
- package/src/core/file-watcher.ts +20 -1
- package/src/core/git-trigger.ts +34 -16
- package/src/core/lock.ts +88 -3
- package/src/core/matrix.ts +5 -1
- package/src/core/native-notify.ts +3 -0
- package/src/core/one-shot.ts +18 -2
- package/src/core/permissions.ts +200 -0
- package/src/core/ps-wrapper.ts +300 -96
- package/src/core/record-history.ts +111 -4
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +9 -3
- package/src/core/schedule-v2.ts +1 -1
- package/src/core/scheduler/index.ts +41 -3
- package/src/core/scheduler/linux.ts +67 -22
- package/src/core/scheduler/mac.ts +24 -7
- package/src/core/scheduler/posix.ts +2 -2
- package/src/core/scheduler/registry.ts +7 -5
- package/src/core/scheduler/windows.ts +237 -32
- package/src/core/secrets.ts +101 -7
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +40 -5
- package/src/core/shutdown.ts +69 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +266 -55
- package/src/core/triage-chain.ts +15 -6
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +23 -0
- package/src/core/triage-shadow.ts +176 -32
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +1 -1
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +181 -138
- package/src/db/history-repo.ts +31 -18
- package/src/db/schema.ts +31 -0
- package/src/gui.tsx +5070 -4761
- package/src/history.ts +7 -3
- package/src/i18n.ts +55 -4
- package/src/index.ts +432 -74
- package/src/integrations.ts +50 -6
- package/src/notifications.ts +465 -18
- package/src/profiles.ts +21 -3
- package/src/rpc.ts +86 -6
- package/src/server.ts +135 -16
- package/src/settings.ts +305 -46
- package/src/task-transfer.ts +10 -3
- package/src/types.ts +24 -5
- package/src/workspaces.ts +22 -0
- package/dist/gui-experimental.cjs +0 -1
package/src/core/ps-wrapper.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { PLUGIN_DIR, LOG_DIR, LOCK_DIR, WRAPPER_DIR, sanitizeName } from "../types.js";
|
|
3
|
+
import { PLUGIN_DIR, LOG_DIR, LOCK_DIR, WRAPPER_DIR, STALE_LOCK_MAX_AGE_MS, sanitizeName } from "../types.js";
|
|
4
4
|
import type { ScheduleGateSpec } from "./schedule-v2.js";
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -49,8 +49,13 @@ export const WRAPPER_SCRIPT = `param(
|
|
|
49
49
|
[string]$EnvFile,
|
|
50
50
|
[string]$SessionMode,
|
|
51
51
|
[string]$SessionId,
|
|
52
|
+
[string]$SessionFile,
|
|
52
53
|
[int]$RetryCount = 0,
|
|
53
|
-
[int]$RetryDelaySeconds = 0
|
|
54
|
+
[int]$RetryDelaySeconds = 0,
|
|
55
|
+
[int]$GateTimeoutSeconds = 300,
|
|
56
|
+
[int]$StaleLockMaxAgeMs = 86400000,
|
|
57
|
+
[string]$PermissionsB64 = "",
|
|
58
|
+
[string]$PolicyB64 = ""
|
|
54
59
|
)
|
|
55
60
|
|
|
56
61
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
@@ -70,6 +75,20 @@ function Write-Log {
|
|
|
70
75
|
Write-Host $line
|
|
71
76
|
}
|
|
72
77
|
|
|
78
|
+
|
|
79
|
+
# Проверяет, что процесс с указанным PID ещё существует. Нужно для stale-lock:
|
|
80
|
+
# возраст файла сам по себе не говорит, что владелец мёртв (задача может идти долго).
|
|
81
|
+
function Test-ProcessAlive {
|
|
82
|
+
param([int]$ProcessId)
|
|
83
|
+
if ($ProcessId -le 0) { return $false }
|
|
84
|
+
try {
|
|
85
|
+
$null = Get-Process -Id $ProcessId -ErrorAction Stop
|
|
86
|
+
return $true
|
|
87
|
+
} catch {
|
|
88
|
+
return $false
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
73
92
|
# Гарантируем существование папки для лога (на случай прямого вызова обёртки).
|
|
74
93
|
if ($LogFile) {
|
|
75
94
|
try {
|
|
@@ -106,27 +125,58 @@ if ($LockFile) {
|
|
|
106
125
|
}
|
|
107
126
|
$lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
|
|
108
127
|
try {
|
|
109
|
-
|
|
128
|
+
# Внутри lock храним время старта и PID владельца: по PID можно
|
|
129
|
+
# отличить живой долгий запуск от осиротевшего после kill -9.
|
|
130
|
+
$lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
|
|
110
131
|
$lockStream.Write($lockBytes, 0, $lockBytes.Length)
|
|
111
132
|
} finally {
|
|
112
133
|
$lockStream.Dispose()
|
|
113
134
|
}
|
|
114
135
|
$script:lockAcquired = $true
|
|
115
136
|
} catch [System.IO.IOException] {
|
|
116
|
-
# Зависший lock
|
|
117
|
-
#
|
|
137
|
+
# Зависший lock снимаем только если владелец мёртв (или файл старше
|
|
138
|
+
# StaleLockMaxAgeMs и PID в нём отсутствует — lock от старой версии).
|
|
118
139
|
$stale = $false
|
|
140
|
+
$holderPid = 0
|
|
119
141
|
try {
|
|
120
|
-
$
|
|
121
|
-
|
|
142
|
+
$holderRaw = "$(Get-Content -LiteralPath $LockFile -Raw -ErrorAction Stop)".Trim()
|
|
143
|
+
$holderParts = $holderRaw.Split([char]124)
|
|
144
|
+
if ($holderParts.Count -ge 2) {
|
|
145
|
+
[void][int]::TryParse($holderParts[1], [ref]$holderPid)
|
|
146
|
+
}
|
|
122
147
|
} catch {}
|
|
148
|
+
if ($holderPid -gt 0) {
|
|
149
|
+
$stale = -not (Test-ProcessAlive -ProcessId $holderPid)
|
|
150
|
+
} else {
|
|
151
|
+
try {
|
|
152
|
+
$ageMs = ((Get-Date) - (Get-Item -LiteralPath $LockFile).LastWriteTime).TotalMilliseconds
|
|
153
|
+
if ($ageMs -gt $StaleLockMaxAgeMs) { $stale = $true }
|
|
154
|
+
} catch {}
|
|
155
|
+
}
|
|
123
156
|
if ($stale) {
|
|
124
|
-
|
|
157
|
+
# T-03: не удаляем lock напрямую. Remove-Item + CreateNew давал
|
|
158
|
+
# гонку: второй воркер мог снести lock, который первый только что
|
|
159
|
+
# создал, и запустить ту же задачу повторно. Атомарно уводим старый
|
|
160
|
+
# файл в уникальное имя; если rename не удался — чужой lock не трогаем.
|
|
161
|
+
$staleLockPath = "$LockFile.stale-$PID-$([DateTime]::UtcNow.Ticks)"
|
|
162
|
+
$staleMoved = $false
|
|
125
163
|
try {
|
|
126
|
-
|
|
127
|
-
$
|
|
128
|
-
$script:lockAcquired = $true
|
|
164
|
+
Move-Item -LiteralPath $LockFile -Destination $staleLockPath -Force -ErrorAction Stop
|
|
165
|
+
$staleMoved = $true
|
|
129
166
|
} catch {}
|
|
167
|
+
if ($staleMoved) {
|
|
168
|
+
try {
|
|
169
|
+
$lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
|
|
170
|
+
try {
|
|
171
|
+
$lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
|
|
172
|
+
$lockStream.Write($lockBytes, 0, $lockBytes.Length)
|
|
173
|
+
} finally {
|
|
174
|
+
$lockStream.Dispose()
|
|
175
|
+
}
|
|
176
|
+
$script:lockAcquired = $true
|
|
177
|
+
} catch {}
|
|
178
|
+
try { Remove-Item -LiteralPath $staleLockPath -Force -ErrorAction SilentlyContinue } catch {}
|
|
179
|
+
}
|
|
130
180
|
}
|
|
131
181
|
if (-not $script:lockAcquired) {
|
|
132
182
|
Write-Log "[windows-scheduler] Запуск задачи '$TaskName' пропущен: удерживается активная блокировка."
|
|
@@ -152,14 +202,74 @@ if ($RecorderFile) {
|
|
|
152
202
|
}
|
|
153
203
|
|
|
154
204
|
# Выполняет команду оболочки и построчно пишет её вывод в лог.
|
|
205
|
+
# GateTimeoutSeconds ограничивает время хука: зависший pre-flight/Quality Gate
|
|
206
|
+
# раньше держал lock до истечения общего таймаута задачи (до 24 ч).
|
|
155
207
|
function Invoke-HookScript {
|
|
156
208
|
param([string]$Command)
|
|
157
|
-
$
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
209
|
+
$timeout = $GateTimeoutSeconds
|
|
210
|
+
|
|
211
|
+
if (-not $timeout -or $timeout -le 0) {
|
|
212
|
+
$output = & cmd.exe /c $Command 2>&1
|
|
213
|
+
$code = $LASTEXITCODE
|
|
214
|
+
foreach ($line in @($output)) {
|
|
215
|
+
Write-Log "[hook] $line"
|
|
216
|
+
}
|
|
217
|
+
return $code
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
# ВАЖНО: расширение должно быть .cmd. GetTempFileName() даёт .tmp, а
|
|
221
|
+
# запуск файла .tmp через cmd.exe /c может зависнуть вместо быстрого выполнения.
|
|
222
|
+
$hookFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-" + [guid]::NewGuid().ToString("N") + ".cmd")
|
|
223
|
+
try {
|
|
224
|
+
# Команду кладём в .cmd, чтобы кавычки/пайпы не ломали аргументы.
|
|
225
|
+
$lines = @('@echo off', 'chcp 65001 >nul', $Command)
|
|
226
|
+
Set-Content -LiteralPath $hookFile -Value $lines -Encoding Default
|
|
227
|
+
# Не используем Start-Process с -RedirectStandardOutput/-RedirectStandardError:
|
|
228
|
+
# в Windows PowerShell 5.1 такой вызов может зависнуть на закрытии потоков,
|
|
229
|
+
# даже если сам хук уже завершился. Запускаем процесс напрямую и читаем
|
|
230
|
+
# stdout/stderr асинхронно — это не блокирует WaitForExit(timeout).
|
|
231
|
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
232
|
+
$psi.FileName = "cmd.exe"
|
|
233
|
+
$psi.Arguments = '/c "' + $hookFile + '"'
|
|
234
|
+
$psi.UseShellExecute = $false
|
|
235
|
+
$psi.RedirectStandardOutput = $true
|
|
236
|
+
$psi.RedirectStandardError = $true
|
|
237
|
+
$psi.CreateNoWindow = $true
|
|
238
|
+
$psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8
|
|
239
|
+
$psi.StandardErrorEncoding = [System.Text.Encoding]::UTF8
|
|
240
|
+
$proc = New-Object System.Diagnostics.Process
|
|
241
|
+
$proc.StartInfo = $psi
|
|
242
|
+
$null = $proc.Start()
|
|
243
|
+
$outTask = $proc.StandardOutput.ReadToEndAsync()
|
|
244
|
+
$errTask = $proc.StandardError.ReadToEndAsync()
|
|
245
|
+
$finished = $proc.WaitForExit([int]($timeout * 1000))
|
|
246
|
+
if (-not $finished) {
|
|
247
|
+
try { & taskkill.exe /F /T /PID $proc.Id 2>$null | Out-Null } catch {}
|
|
248
|
+
try { $proc.WaitForExit(5000) | Out-Null } catch {}
|
|
249
|
+
$code = 124
|
|
250
|
+
Write-Log "[windows-scheduler] Таймаут хука ($timeout с): $Command"
|
|
251
|
+
} else {
|
|
252
|
+
try { $proc.WaitForExit() } catch {}
|
|
253
|
+
$code = $proc.ExitCode
|
|
254
|
+
}
|
|
255
|
+
$outText = ""
|
|
256
|
+
$errText = ""
|
|
257
|
+
if ($outTask.Wait(5000)) { try { $outText = $outTask.Result } catch {} }
|
|
258
|
+
if ($errTask.Wait(5000)) { try { $errText = $errTask.Result } catch {} }
|
|
259
|
+
foreach ($text in @($outText, $errText)) {
|
|
260
|
+
foreach ($line in @($text -split "\r?\n")) {
|
|
261
|
+
if ($line -ne "") {
|
|
262
|
+
Write-Log "[hook] $line"
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return $code
|
|
267
|
+
} catch {
|
|
268
|
+
Write-Log "[windows-scheduler] Не удалось выполнить хук: $_"
|
|
269
|
+
return 1
|
|
270
|
+
} finally {
|
|
271
|
+
Remove-Item -LiteralPath $hookFile -Force -ErrorAction SilentlyContinue
|
|
161
272
|
}
|
|
162
|
-
return $code
|
|
163
273
|
}
|
|
164
274
|
|
|
165
275
|
# Hotfix 1.5.3.1: запуск opencode с реальным таймаутом.
|
|
@@ -206,29 +316,34 @@ function Invoke-OpenCodeOnce {
|
|
|
206
316
|
|
|
207
317
|
$script:timedOut = $false
|
|
208
318
|
$script:attemptExitCode = 0
|
|
319
|
+
# Состояние фильтра лога сбрасываем на каждой попытке: иначе незакрытый
|
|
320
|
+
# служебный блок из упавшего запуска «съедал» бы весь лог следующей попытки.
|
|
321
|
+
$script:inServiceBlock = $false
|
|
322
|
+
$script:inComment = $false
|
|
209
323
|
try {
|
|
324
|
+
# Живой стриминг: вывод opencode проходит через конвейер и пишется в лог
|
|
325
|
+
# (Out-File -Append) или консоль (Out-Host) построчно, по мере поступления.
|
|
326
|
+
# Раньше вывод сначала копился в $output и сбрасывался одним куском только
|
|
327
|
+
# после завершения процесса: дашборд/get_task_logs были слепы во время
|
|
328
|
+
# долгих запусков, росла память, а при kill обёртки лог терялся целиком.
|
|
329
|
+
# $LASTEXITCODE после конвейера сохраняет код последней нативной команды.
|
|
210
330
|
if ($LogFile) {
|
|
211
331
|
if ($CommandPath -like "*.ps1") {
|
|
212
|
-
& powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 |
|
|
213
|
-
|
|
214
|
-
Out-File -FilePath $LogFile -Append -Encoding utf8
|
|
332
|
+
& powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-File -FilePath $LogFile -Append -Encoding utf8
|
|
333
|
+
$script:attemptExitCode = $LASTEXITCODE
|
|
215
334
|
} else {
|
|
216
|
-
& $CommandPath @Arguments *>&1 |
|
|
217
|
-
|
|
218
|
-
Out-File -FilePath $LogFile -Append -Encoding utf8
|
|
335
|
+
& $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-File -FilePath $LogFile -Append -Encoding utf8
|
|
336
|
+
$script:attemptExitCode = $LASTEXITCODE
|
|
219
337
|
}
|
|
220
338
|
} else {
|
|
221
339
|
if ($CommandPath -like "*.ps1") {
|
|
222
|
-
& powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 |
|
|
223
|
-
|
|
224
|
-
Out-Host
|
|
340
|
+
& powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-Host
|
|
341
|
+
$script:attemptExitCode = $LASTEXITCODE
|
|
225
342
|
} else {
|
|
226
|
-
& $CommandPath @Arguments *>&1 |
|
|
227
|
-
|
|
228
|
-
Out-Host
|
|
343
|
+
& $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-Host
|
|
344
|
+
$script:attemptExitCode = $LASTEXITCODE
|
|
229
345
|
}
|
|
230
346
|
}
|
|
231
|
-
$script:attemptExitCode = $LASTEXITCODE
|
|
232
347
|
} finally {
|
|
233
348
|
if ($timeoutMarker -and (Test-Path -LiteralPath $timeoutMarker)) {
|
|
234
349
|
$script:timedOut = $true
|
|
@@ -313,12 +428,10 @@ function Format-LogLine {
|
|
|
313
428
|
return $text
|
|
314
429
|
}
|
|
315
430
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
* чтобы recorder записал поля как отсутствующие.
|
|
321
|
-
*/
|
|
431
|
+
# Пытается вытащить из лога задачи информацию о расходе токенов и стоимости.
|
|
432
|
+
# OpenCode может печатать строки вида "Tokens: 1234", "Usage: 1234 tokens",
|
|
433
|
+
# "cost: $0.012" и т.п. Если данные не найдены — возвращает пустые строки,
|
|
434
|
+
# чтобы recorder записал поля как отсутствующие.
|
|
322
435
|
function Get-UsageFromLog {
|
|
323
436
|
param([string]$File)
|
|
324
437
|
|
|
@@ -333,18 +446,24 @@ function Get-UsageFromLog {
|
|
|
333
446
|
} catch { return $result }
|
|
334
447
|
if (-not $tail) { return $result }
|
|
335
448
|
|
|
449
|
+
# Шаблоны намеренно «якорные»: метка должна стоять в начале строки
|
|
450
|
+
# (допускается префикс времени лога). Раньше подходило любое "token=" или
|
|
451
|
+
# "cost:" внутри текста — конфиг-дампы и проза ИИ давали ложный расход.
|
|
452
|
+
$prefix = '^\\s*(?:\\[[^\\]]{4,40}\\]\\s*)?'
|
|
336
453
|
$tokenPatterns = @(
|
|
337
|
-
'(?i)tokens
|
|
338
|
-
'(?i)(?:input|output|total)\\s+tokens?\\s*[:=]?\\s*([0-9]
|
|
339
|
-
'(?i)usage[^\\r\\n]*?([0-9]+)\\s+tokens?'
|
|
454
|
+
($prefix + '(?i)(?:tokens?|token\\s+usage|usage)\\s*[:=]\\s*([0-9][0-9.,]*)\\s*([kKmM])?\\b'),
|
|
455
|
+
($prefix + '(?i)(?:input|output|total)\\s+tokens?\\s*[:=]?\\s*([0-9][0-9.,]*)\\s*([kKmM])?\\b')
|
|
340
456
|
)
|
|
341
457
|
$costPatterns = @(
|
|
342
|
-
'(?i)(?:cost|
|
|
343
|
-
'(?i)(?:cost|
|
|
458
|
+
($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)'),
|
|
459
|
+
($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
|
|
344
460
|
)
|
|
345
461
|
|
|
346
|
-
|
|
347
|
-
|
|
462
|
+
# Идём с конца: OpenCode печатает итог последним, а более ранние строки
|
|
463
|
+
# могут быть эхом промпта или промежуточной статистикой.
|
|
464
|
+
for ($i = $tail.Count - 1; $i -ge 0; $i--) {
|
|
465
|
+
$text = "$($tail[$i])"
|
|
466
|
+
if ($text -match '(?i)opencode\\.json|OPENCODE_CONFIG') { continue }
|
|
348
467
|
|
|
349
468
|
if (-not $result.Tokens) {
|
|
350
469
|
foreach ($pattern in $tokenPatterns) {
|
|
@@ -373,6 +492,8 @@ function Get-UsageFromLog {
|
|
|
373
492
|
}
|
|
374
493
|
}
|
|
375
494
|
}
|
|
495
|
+
|
|
496
|
+
if ($result.Tokens -and $result.Cost) { break }
|
|
376
497
|
}
|
|
377
498
|
|
|
378
499
|
return $result
|
|
@@ -398,53 +519,84 @@ try {
|
|
|
398
519
|
Write-Log "[workspace] name=$WorkspaceName, cwd=$Workdir, branch=$gitBranch, remote=$gitRemote"
|
|
399
520
|
}
|
|
400
521
|
|
|
401
|
-
# Спринт
|
|
402
|
-
#
|
|
403
|
-
#
|
|
522
|
+
# Спринт 32 / релиз 1.6: политика прав вычисляется в TypeScript
|
|
523
|
+
# (src/core/permissions.ts) и передаётся готовым JSON в base64.
|
|
524
|
+
# Старые .cmd, созданные до 1.6, параметр не передают — для них остаётся
|
|
525
|
+
# прежнее поведение «разрешено всё» (fallback ниже).
|
|
404
526
|
$toolToAction = @{
|
|
405
527
|
"read" = "read"; "write" = "edit"; "edit" = "edit"; "apply_patch" = "edit"; "remove" = "edit"
|
|
406
528
|
"bash" = "shell"; "shell" = "shell"; "glob" = "glob"; "grep" = "grep"
|
|
407
529
|
"webfetch" = "webfetch"; "websearch" = "websearch"; "question" = "question"
|
|
408
530
|
"subagent" = "subagent"; "skill" = "skill"
|
|
409
531
|
}
|
|
410
|
-
$
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
)
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
$
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
532
|
+
if ($PermissionsB64) {
|
|
533
|
+
try {
|
|
534
|
+
$decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($PermissionsB64))
|
|
535
|
+
$config = $decoded | ConvertFrom-Json
|
|
536
|
+
$env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 5 -Compress)
|
|
537
|
+
Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT"
|
|
538
|
+
} catch {
|
|
539
|
+
Write-Log "[policy] ERROR: cannot decode PermissionsB64 ($($_.Exception.Message)); falling back to legacy permissions"
|
|
540
|
+
$PermissionsB64 = ""
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
if ($PolicyB64) {
|
|
544
|
+
try {
|
|
545
|
+
$policyJson = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($PolicyB64)) | ConvertFrom-Json
|
|
546
|
+
$legacyFlag = ""
|
|
547
|
+
if ($policyJson.legacyShell) { $legacyFlag = ", legacyShell=true" }
|
|
548
|
+
Write-Log "[policy] policy=$($policyJson.policy)$legacyFlag"
|
|
549
|
+
foreach ($denied in @($policyJson.denied)) {
|
|
550
|
+
if ($denied.action) {
|
|
551
|
+
Write-Log "[policy] deny $($denied.action): $($denied.hint)"
|
|
552
|
+
}
|
|
431
553
|
}
|
|
554
|
+
} catch {
|
|
555
|
+
Write-Log "[policy] WARN: cannot decode PolicyB64 ($($_.Exception.Message))"
|
|
432
556
|
}
|
|
433
557
|
}
|
|
434
|
-
if ($
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
558
|
+
if (-not $PermissionsB64) {
|
|
559
|
+
# Legacy fallback для обёрток, созданных до 1.6: все action разрешены,
|
|
560
|
+
# DeniedTools/AllowedTools применяются как раньше.
|
|
561
|
+
$defaultPermissions = @(
|
|
562
|
+
@{ action = "read"; resource = "*"; effect = "allow" },
|
|
563
|
+
@{ action = "edit"; resource = "*"; effect = "allow" },
|
|
564
|
+
@{ action = "glob"; resource = "*"; effect = "allow" },
|
|
565
|
+
@{ action = "grep"; resource = "*"; effect = "allow" },
|
|
566
|
+
@{ action = "shell"; resource = "*"; effect = "allow" },
|
|
567
|
+
@{ action = "subagent"; resource = "*"; effect = "allow" },
|
|
568
|
+
@{ action = "skill"; resource = "*"; effect = "allow" },
|
|
569
|
+
@{ action = "question"; resource = "*"; effect = "allow" },
|
|
570
|
+
@{ action = "webfetch"; resource = "*"; effect = "allow" },
|
|
571
|
+
@{ action = "websearch"; resource = "*"; effect = "allow" }
|
|
572
|
+
)
|
|
573
|
+
$permissions = @()
|
|
574
|
+
foreach ($p in $defaultPermissions) { $permissions += $p }
|
|
575
|
+
if ($DeniedTools) {
|
|
576
|
+
$deniedList = @($DeniedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
|
|
577
|
+
foreach ($tool in $deniedList) {
|
|
578
|
+
$action = $toolToAction[$tool]
|
|
579
|
+
if ($action) {
|
|
580
|
+
$idx = $permissions | Where-Object { $_.action -eq $action }
|
|
581
|
+
if ($idx) { $idx.effect = "deny" }
|
|
582
|
+
}
|
|
583
|
+
}
|
|
440
584
|
}
|
|
441
|
-
|
|
442
|
-
|
|
585
|
+
if ($AllowedTools) {
|
|
586
|
+
$allowedList = @($AllowedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
|
|
587
|
+
$allowedActions = @{}
|
|
588
|
+
foreach ($tool in $allowedList) {
|
|
589
|
+
$action = $toolToAction[$tool]
|
|
590
|
+
if ($action) { $allowedActions[$action] = $true }
|
|
591
|
+
}
|
|
592
|
+
foreach ($p in $permissions) {
|
|
593
|
+
if (-not $allowedActions.ContainsKey($p.action)) { $p.effect = "deny" }
|
|
594
|
+
}
|
|
443
595
|
}
|
|
596
|
+
$config = @{ "$schema" = "https://opencode.ai/config.json"; "permissions" = $permissions }
|
|
597
|
+
$env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 3 -Compress)
|
|
598
|
+
Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT (legacy fallback)"
|
|
444
599
|
}
|
|
445
|
-
$config = @{ "$schema" = "https://opencode.ai/config.json"; "permissions" = $permissions }
|
|
446
|
-
$env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 3 -Compress)
|
|
447
|
-
Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT"
|
|
448
600
|
|
|
449
601
|
# Pre-flight: выполняется ДО основной задачи. Ненулевой код отменяет запуск.
|
|
450
602
|
if ($BeforeScript) {
|
|
@@ -465,6 +617,13 @@ try {
|
|
|
465
617
|
if (-not $script:skipMainTask) {
|
|
466
618
|
$prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
|
|
467
619
|
|
|
620
|
+
# CreateProcess ограничивает командную строку 32767 символами, а промпт
|
|
621
|
+
# передаётся opencode аргументом ($opencodeArgs += $prompt). Явная ошибка
|
|
622
|
+
# понятнее, чем обрезанный/отвергнутый запуск. Основная валидация — в schedule_task.
|
|
623
|
+
if ($prompt -and $prompt.Length -gt 30000) {
|
|
624
|
+
throw "Промпт слишком длинный для командной строки Windows: $($prompt.Length) символов (максимум 30000). Сократите промпт."
|
|
625
|
+
}
|
|
626
|
+
|
|
468
627
|
# Спринт 21: env-переменные workspace. Файл пишет плагин, значения не логируются.
|
|
469
628
|
if ($EnvFile -and (Test-Path -LiteralPath $EnvFile)) {
|
|
470
629
|
try {
|
|
@@ -490,8 +649,21 @@ try {
|
|
|
490
649
|
if ($Model) {
|
|
491
650
|
$opencodeArgs += @("--model", $Model)
|
|
492
651
|
}
|
|
493
|
-
if ($SessionMode -eq 'reuse'
|
|
494
|
-
|
|
652
|
+
if ($SessionMode -eq 'reuse') {
|
|
653
|
+
# Спринт 24: актуальный id читаем из sidecar-файла — ротация сессии
|
|
654
|
+
# обновляет файл, и обёртку не нужно пересоздавать.
|
|
655
|
+
$effectiveSessionId = $SessionId
|
|
656
|
+
if ($SessionFile -and (Test-Path -LiteralPath $SessionFile)) {
|
|
657
|
+
try {
|
|
658
|
+
$fromFile = (Get-Content -LiteralPath $SessionFile -Raw -ErrorAction Stop).Trim()
|
|
659
|
+
if ($fromFile) { $effectiveSessionId = $fromFile }
|
|
660
|
+
} catch {
|
|
661
|
+
Write-Log "[windows-scheduler] Не удалось прочитать файл сессии: $($_.Exception.Message)"
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
if ($effectiveSessionId) {
|
|
665
|
+
$opencodeArgs += @("--session", $effectiveSessionId)
|
|
666
|
+
}
|
|
495
667
|
} elseif ($SessionMode -eq 'last') {
|
|
496
668
|
$opencodeArgs += @("--continue")
|
|
497
669
|
}
|
|
@@ -527,18 +699,14 @@ try {
|
|
|
527
699
|
# завершения opencode run. Если ИИ упал — шлюз не запускаем.
|
|
528
700
|
if ($QualityGate -and $script:exitCode -eq 0) {
|
|
529
701
|
Write-Log "[windows-scheduler] Запуск Quality Gate: $QualityGate"
|
|
530
|
-
|
|
531
|
-
$gateCode = $
|
|
702
|
+
# Тот же таймаут, что у хуков: зависший gate не должен держать lock.
|
|
703
|
+
$gateCode = Invoke-HookScript -Command $QualityGate
|
|
532
704
|
|
|
533
|
-
if ($
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
}
|
|
538
|
-
$gateOutput | Out-Host
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
if ($gateCode -ne 0) {
|
|
705
|
+
if ($gateCode -eq 124) {
|
|
706
|
+
Write-Log "[windows-scheduler] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
|
|
707
|
+
$script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
|
|
708
|
+
$script:exitCode = 1
|
|
709
|
+
} elseif ($gateCode -ne 0) {
|
|
542
710
|
Write-Log "[windows-scheduler] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
|
|
543
711
|
$script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
|
|
544
712
|
$script:exitCode = 1
|
|
@@ -601,11 +769,11 @@ try {
|
|
|
601
769
|
if ($RecorderFile) {
|
|
602
770
|
try {
|
|
603
771
|
if ($script:runId) {
|
|
604
|
-
& node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
|
|
772
|
+
& node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus" "$LogFile"
|
|
605
773
|
} else {
|
|
606
774
|
# Fallback: --start не удался (например, старая установка) —
|
|
607
775
|
# пишем завершённую запись старым способом, без потери истории.
|
|
608
|
-
& node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
|
|
776
|
+
& node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus" "$LogFile"
|
|
609
777
|
}
|
|
610
778
|
} catch {}
|
|
611
779
|
}
|
|
@@ -637,11 +805,15 @@ export async function ensureWrapper(): Promise<string> {
|
|
|
637
805
|
|
|
638
806
|
/**
|
|
639
807
|
* Записывает промпт задачи во временный файл и возвращает его путь.
|
|
808
|
+
*
|
|
809
|
+
* Имя санитизируется внутри функции, а не только у вызывающей стороны:
|
|
810
|
+
* defence-in-depth против path traversal, если taskName когда-либо придёт
|
|
811
|
+
* из недоверенного источника (импорт, шаблон, RPC).
|
|
640
812
|
*/
|
|
641
813
|
export async function writePromptFile(taskName: string, prompt: string): Promise<string> {
|
|
642
814
|
const promptDir = path.join(PLUGIN_DIR, "prompts");
|
|
643
815
|
await fs.mkdir(promptDir, { recursive: true });
|
|
644
|
-
const promptPath = path.join(promptDir, `${taskName}.txt`);
|
|
816
|
+
const promptPath = path.join(promptDir, `${sanitizeName(taskName)}.txt`);
|
|
645
817
|
// BOM помогает Windows PowerShell 5.1 правильно прочитать кириллицу.
|
|
646
818
|
// На POSIX BOM попал бы в промпт как мусорный символ — не пишем его.
|
|
647
819
|
const content = process.platform === "win32" ? "\uFEFF" + prompt : prompt;
|
|
@@ -651,9 +823,12 @@ export async function writePromptFile(taskName: string, prompt: string): Promise
|
|
|
651
823
|
|
|
652
824
|
/**
|
|
653
825
|
* Возвращает путь к lock-файлу задачи.
|
|
826
|
+
*
|
|
827
|
+
* Как и writePromptFile, санитизирует имя внутри: без этого значение с `../`
|
|
828
|
+
* могло бы создать lock вне каталога locks.
|
|
654
829
|
*/
|
|
655
830
|
export function lockFilePath(taskName: string): string {
|
|
656
|
-
return path.join(PLUGIN_DIR, "locks", `${taskName}.lock`);
|
|
831
|
+
return path.join(PLUGIN_DIR, "locks", `${sanitizeName(taskName)}.lock`);
|
|
657
832
|
}
|
|
658
833
|
|
|
659
834
|
/**
|
|
@@ -730,7 +905,11 @@ export async function writeWrapperCmd(
|
|
|
730
905
|
sessionMode?: "new" | "reuse" | "last",
|
|
731
906
|
sessionId?: string,
|
|
732
907
|
retryCount?: number,
|
|
733
|
-
retryDelaySeconds?: number
|
|
908
|
+
retryDelaySeconds?: number,
|
|
909
|
+
gateTimeoutSeconds?: number,
|
|
910
|
+
permissionsConfig?: string,
|
|
911
|
+
policyMeta?: unknown,
|
|
912
|
+
sessionFile?: string
|
|
734
913
|
): Promise<string> {
|
|
735
914
|
await fs.mkdir(WRAPPER_DIR, { recursive: true });
|
|
736
915
|
const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
|
|
@@ -746,8 +925,16 @@ export async function writeWrapperCmd(
|
|
|
746
925
|
`-PromptFile "${promptFile}"`,
|
|
747
926
|
`-TimeoutSeconds ${timeoutSeconds}`,
|
|
748
927
|
`-LockFile "${lockFile}"`,
|
|
928
|
+
`-StaleLockMaxAgeMs ${STALE_LOCK_MAX_AGE_MS}`,
|
|
749
929
|
];
|
|
750
930
|
|
|
931
|
+
// Таймаут хуков/Quality Gate: 300 с по умолчанию, 0 — без ограничения.
|
|
932
|
+
const safeGateTimeout =
|
|
933
|
+
typeof gateTimeoutSeconds === "number" && Number.isFinite(gateTimeoutSeconds)
|
|
934
|
+
? Math.max(0, Math.floor(gateTimeoutSeconds))
|
|
935
|
+
: 300;
|
|
936
|
+
psArgs.push(`-GateTimeoutSeconds ${safeGateTimeout}`);
|
|
937
|
+
|
|
751
938
|
// Hotfix 1.5.3.1: ретраи. Параметр не передаём при 0 — обёртка по умолчанию
|
|
752
939
|
// делает ровно одну попытку, как раньше.
|
|
753
940
|
const safeRetryCount = Math.max(0, Math.floor(retryCount ?? 0));
|
|
@@ -800,6 +987,17 @@ export async function writeWrapperCmd(
|
|
|
800
987
|
}
|
|
801
988
|
}
|
|
802
989
|
|
|
990
|
+
// Спринт 32: готовый JSON политики и метаданные для лога — в base64.
|
|
991
|
+
// Base64 не содержит кавычек и переводов строк, поэтому безопасен для .cmd.
|
|
992
|
+
if (permissionsConfig) {
|
|
993
|
+
const b64 = Buffer.from(permissionsConfig, "utf8").toString("base64");
|
|
994
|
+
psArgs.push(`-PermissionsB64 "${b64}"`);
|
|
995
|
+
}
|
|
996
|
+
if (policyMeta) {
|
|
997
|
+
const b64 = Buffer.from(JSON.stringify(policyMeta), "utf8").toString("base64");
|
|
998
|
+
psArgs.push(`-PolicyB64 "${b64}"`);
|
|
999
|
+
}
|
|
1000
|
+
|
|
803
1001
|
// Hotfix 1.5.3.1: хуки — в отдельные .cmd-файлы (см. writeHookFile).
|
|
804
1002
|
// Раньше кавычки заменялись на апострофы, из-за чего хуки с путями в кавычках
|
|
805
1003
|
// (например, "C:\Program Files\...") падали.
|
|
@@ -831,6 +1029,12 @@ export async function writeWrapperCmd(
|
|
|
831
1029
|
if (safeSessionId) {
|
|
832
1030
|
psArgs.push(`-SessionId "${safeSessionId}"`);
|
|
833
1031
|
}
|
|
1032
|
+
if (sessionFile?.trim()) {
|
|
1033
|
+
const safeSessionFile = sessionFile.replace(/[\r\n"]+/g, "").trim();
|
|
1034
|
+
if (safeSessionFile) {
|
|
1035
|
+
psArgs.push(`-SessionFile "${safeSessionFile}"`);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
834
1038
|
}
|
|
835
1039
|
}
|
|
836
1040
|
|
|
@@ -903,7 +1107,7 @@ export const FORCE_FILE_TTL_MS = 2 * 60 * 1000;
|
|
|
903
1107
|
* поэтому обёртка (--force-file) и агент указывают на один и тот же файл.
|
|
904
1108
|
*/
|
|
905
1109
|
export function forceFilePath(taskName: string): string {
|
|
906
|
-
return `${lockFilePath(
|
|
1110
|
+
return `${lockFilePath(taskName)}.force`;
|
|
907
1111
|
}
|
|
908
1112
|
|
|
909
1113
|
/**
|