opencode-windows-scheduler 1.5.0 → 1.5.2
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 +47 -1
- package/LICENSE +21 -21
- package/README.md +24 -2
- package/ROADMAP-STRATEGY.md +16 -16
- package/ROADMAP.md +649 -160
- package/dist/core/audit.d.ts +27 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +60 -0
- package/dist/core/dry-run.d.ts +10 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +55 -34
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +15 -9
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +48 -22
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +47 -10
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +29 -17
- package/dist/core/scheduler/types.d.ts +6 -0
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +6 -2
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +25 -10
- package/dist/core/secrets.d.ts +10 -3
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +28 -4
- package/dist/core/telegram.d.ts.map +1 -1
- package/dist/core/telegram.js +13 -10
- package/dist/core/wrappers/bash.d.ts +1 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +91 -5
- package/dist/i18n.d.ts +52 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +292 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +788 -183
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +74 -40
- package/dist/rpc.d.ts +15 -2
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +6 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +89 -48
- package/dist/settings.d.ts +3 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +20 -8
- package/dist/task-transfer.d.ts +13 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +11 -0
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +32 -0
- package/dist/workspaces.d.ts +2 -2
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +6 -4
- package/docs/ARCHITECTURE.md +96 -4
- package/docs/FEATURES.md +34 -5
- package/docs/README.ru.md +17 -1
- package/gui-experimental.cjs +9 -9
- package/locales/en.json +695 -0
- package/locales/ru.json +695 -0
- package/package.json +6 -3
- package/scripts/test-locale.mjs +44 -0
- package/src/core/audit.ts +89 -0
- package/src/core/dry-run.ts +76 -38
- package/src/core/git-trigger.ts +15 -9
- package/src/core/matrix.ts +52 -26
- package/src/core/ps-wrapper.ts +47 -10
- package/src/core/schedule-v2.ts +47 -17
- package/src/core/scheduler/types.ts +6 -0
- package/src/core/scheduler/windows.ts +25 -10
- package/src/core/secrets.ts +34 -10
- package/src/core/telegram.ts +16 -10
- package/src/core/wrappers/bash.ts +112 -5
- package/src/gui.tsx +575 -480
- package/src/i18n.ts +339 -0
- package/src/index.ts +960 -193
- package/src/notifications.ts +83 -42
- package/src/rpc.ts +6 -2
- package/src/server.ts +89 -48
- package/src/settings.ts +38 -10
- package/src/task-transfer.ts +24 -0
- package/src/types.ts +37 -0
- package/src/workspaces.ts +9 -4
package/src/core/matrix.ts
CHANGED
|
@@ -21,6 +21,7 @@ import { getHistory, recordRun } from "../db/history-repo.js";
|
|
|
21
21
|
import { notifyMatrixCompletion } from "../notifications.js";
|
|
22
22
|
import { getWorkspace } from "../workspaces.js";
|
|
23
23
|
import { createSchedulerBackend } from "./scheduler/index.js";
|
|
24
|
+
import { t } from "../i18n.js";
|
|
24
25
|
|
|
25
26
|
/** Суффикс агрегирующей задачи, запускаемой после всех клонов. */
|
|
26
27
|
export const MATRIX_COMPLETE_SUFFIX = "-matrix-complete";
|
|
@@ -29,7 +30,11 @@ export const MATRIX_COMPLETE_SUFFIX = "-matrix-complete";
|
|
|
29
30
|
export function matrixCloneName(parentName: string, workspaceName: string): string {
|
|
30
31
|
const parent = parentName.trim();
|
|
31
32
|
const ws = workspaceName.trim() || "workspace";
|
|
32
|
-
const safeWs = ws
|
|
33
|
+
const safeWs = ws
|
|
34
|
+
// Спринт 27.5: метасимволы оболочки и недопустимые для имени задачи
|
|
35
|
+
// символы заменяем на дефис, чтобы имя клона проходило validateTaskName.
|
|
36
|
+
.replace(/[\\/:*?"<>|&^%'`;()]+/g, "-")
|
|
37
|
+
.replace(/\s+/g, "-");
|
|
33
38
|
return `${parent}-matrix-${safeWs}`;
|
|
34
39
|
}
|
|
35
40
|
|
|
@@ -50,7 +55,9 @@ export function isMatrixCompleteName(name: string): boolean {
|
|
|
50
55
|
export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
|
|
51
56
|
const matrix = task.matrix;
|
|
52
57
|
if (!matrix || !Array.isArray(matrix.workspaceIds) || matrix.workspaceIds.length === 0) {
|
|
53
|
-
throw new Error(
|
|
58
|
+
throw new Error(
|
|
59
|
+
t("matrix.error.workspaceIdsEmpty", { task: task.name })
|
|
60
|
+
);
|
|
54
61
|
}
|
|
55
62
|
|
|
56
63
|
const clones: TaskDefinition[] = [];
|
|
@@ -60,7 +67,10 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
|
|
|
60
67
|
const workspace = getWorkspace(workspaceId);
|
|
61
68
|
if (!workspace) {
|
|
62
69
|
throw new Error(
|
|
63
|
-
|
|
70
|
+
t("matrix.error.workspaceMissing", {
|
|
71
|
+
task: task.name,
|
|
72
|
+
workspace: workspaceId,
|
|
73
|
+
})
|
|
64
74
|
);
|
|
65
75
|
}
|
|
66
76
|
const name = matrixCloneName(task.name, workspace.name);
|
|
@@ -108,7 +118,9 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
|
|
|
108
118
|
}
|
|
109
119
|
|
|
110
120
|
if (clones.length === 0) {
|
|
111
|
-
throw new Error(
|
|
121
|
+
throw new Error(
|
|
122
|
+
t("matrix.error.cloneCreation", { task: task.name })
|
|
123
|
+
);
|
|
112
124
|
}
|
|
113
125
|
return clones;
|
|
114
126
|
}
|
|
@@ -181,22 +193,37 @@ export function aggregateMatrixResults(parentId: string): MatrixAggregate {
|
|
|
181
193
|
|
|
182
194
|
if (totalCount === 0) {
|
|
183
195
|
status = "empty";
|
|
184
|
-
message =
|
|
196
|
+
message = t("matrix.aggregate.empty", { parent: parentId });
|
|
185
197
|
} else if (pendingCount > 0) {
|
|
186
198
|
status = "running";
|
|
187
|
-
message =
|
|
199
|
+
message = t("matrix.aggregate.running", {
|
|
200
|
+
done: totalCount - pendingCount,
|
|
201
|
+
total: totalCount,
|
|
202
|
+
});
|
|
188
203
|
} else if (errorCount === 0) {
|
|
189
204
|
status = "success";
|
|
190
|
-
message =
|
|
205
|
+
message = t("matrix.aggregate.success", { total: totalCount });
|
|
191
206
|
} else if (failureMode === "stop") {
|
|
192
207
|
const firstError = results.find((r) => r.status === "error");
|
|
193
208
|
status = "error";
|
|
194
209
|
message =
|
|
195
|
-
|
|
196
|
-
|
|
210
|
+
t("matrix.aggregate.stopped", {
|
|
211
|
+
errors: errorCount,
|
|
212
|
+
total: totalCount,
|
|
213
|
+
}) +
|
|
214
|
+
(firstError?.error
|
|
215
|
+
? t("matrix.aggregate.stoppedFirst", {
|
|
216
|
+
name: firstError.name,
|
|
217
|
+
error: firstError.error,
|
|
218
|
+
})
|
|
219
|
+
: "");
|
|
197
220
|
} else {
|
|
198
221
|
status = "partial";
|
|
199
|
-
message =
|
|
222
|
+
message = t("matrix.aggregate.partial", {
|
|
223
|
+
success: successCount,
|
|
224
|
+
total: totalCount,
|
|
225
|
+
errors: errorCount,
|
|
226
|
+
});
|
|
200
227
|
}
|
|
201
228
|
|
|
202
229
|
return {
|
|
@@ -250,13 +277,11 @@ export function resolveMatrixConcurrency(
|
|
|
250
277
|
export async function runMatrix(task: TaskDefinition): Promise<MatrixRunResult> {
|
|
251
278
|
const matrix = task.matrix;
|
|
252
279
|
if (!matrix) {
|
|
253
|
-
throw new Error(
|
|
280
|
+
throw new Error(t("matrix.error.notMatrix", { task: task.name }));
|
|
254
281
|
}
|
|
255
282
|
const clones = listMatrixClones(task.name);
|
|
256
283
|
if (clones.length === 0) {
|
|
257
|
-
throw new Error(
|
|
258
|
-
`У матрицы "${task.name}" нет клонов — пересоздайте задачу, чтобы развернуть её по workspace.`
|
|
259
|
-
);
|
|
284
|
+
throw new Error(t("matrix.error.noClones", { task: task.name }));
|
|
260
285
|
}
|
|
261
286
|
|
|
262
287
|
const strategy = matrix.strategy === "sequential" ? "sequential" : "parallel";
|
|
@@ -467,8 +492,10 @@ export function ensureMatrixCompleteTask(parent: TaskDefinition): TaskDefinition
|
|
|
467
492
|
schedule: parent.schedule,
|
|
468
493
|
prompt:
|
|
469
494
|
existing?.prompt ??
|
|
470
|
-
|
|
471
|
-
|
|
495
|
+
t("matrix.aggregator.prompt", {
|
|
496
|
+
parent: parent.name,
|
|
497
|
+
clones: clones.map((c) => c.name).join(", "),
|
|
498
|
+
}),
|
|
472
499
|
triggerType: "file",
|
|
473
500
|
watchPath: undefined,
|
|
474
501
|
mcpEvent: undefined,
|
|
@@ -542,7 +569,7 @@ export interface MatrixSyncPlan {
|
|
|
542
569
|
*/
|
|
543
570
|
export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
|
|
544
571
|
if (!parent.matrix) {
|
|
545
|
-
throw new Error(
|
|
572
|
+
throw new Error(t("matrix.error.notMatrix", { task: parent.name }));
|
|
546
573
|
}
|
|
547
574
|
const desired = expandMatrixTask(parent);
|
|
548
575
|
const existing = listMatrixClones(parent.name);
|
|
@@ -570,7 +597,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
|
|
|
570
597
|
running.push(current.name);
|
|
571
598
|
if (cloneSignature(current) !== cloneSignature(wanted)) {
|
|
572
599
|
warnings.push(
|
|
573
|
-
|
|
600
|
+
t("matrix.clone.runningChanges", { name: current.name })
|
|
574
601
|
);
|
|
575
602
|
}
|
|
576
603
|
continue;
|
|
@@ -586,7 +613,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
|
|
|
586
613
|
if (latest.status === "running") {
|
|
587
614
|
running.push(current.name);
|
|
588
615
|
warnings.push(
|
|
589
|
-
|
|
616
|
+
t("matrix.clone.runningDeletion", { name: current.name })
|
|
590
617
|
);
|
|
591
618
|
continue;
|
|
592
619
|
}
|
|
@@ -689,11 +716,10 @@ export function getMatrixDeletionGuard(
|
|
|
689
716
|
const definition = getTask(taskName);
|
|
690
717
|
const parentId = definition?.matrixParentId?.trim();
|
|
691
718
|
if (!parentId) return undefined;
|
|
692
|
-
return (
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
);
|
|
719
|
+
return t("matrix.deletionGuard", {
|
|
720
|
+
name: definition?.name ?? taskName,
|
|
721
|
+
parent: parentId,
|
|
722
|
+
});
|
|
697
723
|
}
|
|
698
724
|
|
|
699
725
|
/**
|
|
@@ -743,11 +769,11 @@ export interface MatrixCancelResult {
|
|
|
743
769
|
*/
|
|
744
770
|
export async function cancelPendingMatrixClones(
|
|
745
771
|
parentName: string,
|
|
746
|
-
reason = "
|
|
772
|
+
reason = t("matrix.cancel.defaultReason")
|
|
747
773
|
): Promise<MatrixCancelResult> {
|
|
748
774
|
const parent = getTask(parentName);
|
|
749
775
|
if (!parent?.matrix) {
|
|
750
|
-
throw new Error(
|
|
776
|
+
throw new Error(t("matrix.error.notMatrix", { task: parentName }));
|
|
751
777
|
}
|
|
752
778
|
|
|
753
779
|
const clones = listMatrixClones(parent.name);
|
package/src/core/ps-wrapper.ts
CHANGED
|
@@ -261,18 +261,53 @@ try {
|
|
|
261
261
|
Write-Log "[workspace] name=$WorkspaceName, cwd=$Workdir, branch=$gitBranch, remote=$gitRemote"
|
|
262
262
|
}
|
|
263
263
|
|
|
264
|
-
#
|
|
265
|
-
#
|
|
266
|
-
#
|
|
267
|
-
|
|
268
|
-
|
|
264
|
+
# Спринт 29.2: права задачи передаются через OPENCODE_CONFIG_CONTENT.
|
|
265
|
+
# opencode run CLI (v2.2.3) не поддерживает --allow-tool/--deny-tool, а файл
|
|
266
|
+
# opencode.jsonc в Workdir мог бы перезаписать проектный конфиг.
|
|
267
|
+
$toolToAction = @{
|
|
268
|
+
"read" = "read"; "write" = "edit"; "edit" = "edit"; "apply_patch" = "edit"; "remove" = "edit"
|
|
269
|
+
"bash" = "shell"; "shell" = "shell"; "glob" = "glob"; "grep" = "grep"
|
|
270
|
+
"webfetch" = "webfetch"; "websearch" = "websearch"; "question" = "question"
|
|
271
|
+
"subagent" = "subagent"; "skill" = "skill"
|
|
272
|
+
}
|
|
273
|
+
$defaultPermissions = @(
|
|
274
|
+
@{ action = "read"; resource = "*"; effect = "allow" },
|
|
275
|
+
@{ action = "edit"; resource = "*"; effect = "allow" },
|
|
276
|
+
@{ action = "glob"; resource = "*"; effect = "allow" },
|
|
277
|
+
@{ action = "grep"; resource = "*"; effect = "allow" },
|
|
278
|
+
@{ action = "shell"; resource = "*"; effect = "allow" },
|
|
279
|
+
@{ action = "subagent"; resource = "*"; effect = "allow" },
|
|
280
|
+
@{ action = "skill"; resource = "*"; effect = "allow" },
|
|
281
|
+
@{ action = "question"; resource = "*"; effect = "allow" },
|
|
282
|
+
@{ action = "webfetch"; resource = "*"; effect = "allow" },
|
|
283
|
+
@{ action = "websearch"; resource = "*"; effect = "allow" }
|
|
284
|
+
)
|
|
285
|
+
$permissions = @()
|
|
286
|
+
foreach ($p in $defaultPermissions) { $permissions += $p }
|
|
287
|
+
if ($DeniedTools) {
|
|
269
288
|
$deniedList = @($DeniedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
289
|
+
foreach ($tool in $deniedList) {
|
|
290
|
+
$action = $toolToAction[$tool]
|
|
291
|
+
if ($action) {
|
|
292
|
+
$idx = $permissions | Where-Object { $_.action -eq $action }
|
|
293
|
+
if ($idx) { $idx.effect = "deny" }
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if ($AllowedTools) {
|
|
298
|
+
$allowedList = @($AllowedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
|
|
299
|
+
$allowedActions = @{}
|
|
300
|
+
foreach ($tool in $allowedList) {
|
|
301
|
+
$action = $toolToAction[$tool]
|
|
302
|
+
if ($action) { $allowedActions[$action] = $true }
|
|
303
|
+
}
|
|
304
|
+
foreach ($p in $permissions) {
|
|
305
|
+
if (-not $allowedActions.ContainsKey($p.action)) { $p.effect = "deny" }
|
|
274
306
|
}
|
|
275
307
|
}
|
|
308
|
+
$config = @{ "$schema" = "https://opencode.ai/config.json"; "permissions" = $permissions }
|
|
309
|
+
$env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 3 -Compress)
|
|
310
|
+
Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT"
|
|
276
311
|
|
|
277
312
|
# Pre-flight: выполняется ДО основной задачи. Ненулевой код отменяет запуск.
|
|
278
313
|
if ($BeforeScript) {
|
|
@@ -312,7 +347,9 @@ try {
|
|
|
312
347
|
$opencodeCmd = Get-Command opencode | Select-Object -ExpandProperty Source
|
|
313
348
|
|
|
314
349
|
# Формируем аргументы для opencode run (Спринт 24: сессия).
|
|
315
|
-
|
|
350
|
+
# Спринт 29.2: --auto автоодобряет не запрещённые права, а ограничения
|
|
351
|
+
# берутся из сгенерированного opencode.jsonc в Workdir.
|
|
352
|
+
$opencodeArgs = @("run", "--auto")
|
|
316
353
|
if ($Model) {
|
|
317
354
|
$opencodeArgs += @("--model", $Model)
|
|
318
355
|
}
|
package/src/core/schedule-v2.ts
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* Никакого I/O и обращения к ОС.
|
|
13
13
|
*/
|
|
14
14
|
import { convertCronToSchTasks } from "./cron-to-schtasks.js";
|
|
15
|
+
import { t } from "../i18n.js";
|
|
15
16
|
import type { CronConversion } from "../types.js";
|
|
16
17
|
|
|
17
18
|
/** Ограничение на поиск ближайшего запуска. */
|
|
@@ -139,7 +140,8 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
139
140
|
const items = token.split(",");
|
|
140
141
|
for (const raw of items) {
|
|
141
142
|
let item = raw.trim().toUpperCase();
|
|
142
|
-
if (!item)
|
|
143
|
+
if (!item)
|
|
144
|
+
throw new Error(t("schedule.error.cronEmptyItem", { token }));
|
|
143
145
|
if (names && names[item] !== undefined) item = String(names[item]);
|
|
144
146
|
// шаг: a-b/n или */n
|
|
145
147
|
const stepMatch = item.match(/^(.*)\/([0-9]+)$/);
|
|
@@ -148,9 +150,15 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
148
150
|
item = (stepMatch[1] ?? "").trim();
|
|
149
151
|
step = Number(stepMatch[2]);
|
|
150
152
|
if (!Number.isInteger(step) || step < 1) {
|
|
151
|
-
throw new Error(
|
|
153
|
+
throw new Error(
|
|
154
|
+
t("schedule.error.cronStepInvalid", {
|
|
155
|
+
step: stepMatch[2],
|
|
156
|
+
raw,
|
|
157
|
+
})
|
|
158
|
+
);
|
|
152
159
|
}
|
|
153
|
-
if (item === "")
|
|
160
|
+
if (item === "")
|
|
161
|
+
throw new Error(t("schedule.error.cronStepMissing", { raw }));
|
|
154
162
|
}
|
|
155
163
|
if (item === "*" || item === "") {
|
|
156
164
|
for (let v = min; v <= max; v += step) result.add(v);
|
|
@@ -165,17 +173,21 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
165
173
|
const a = Number(aToken);
|
|
166
174
|
const b = Number(bToken);
|
|
167
175
|
if (!Number.isFinite(a) || !Number.isFinite(b)) {
|
|
168
|
-
throw new Error(
|
|
176
|
+
throw new Error(t("schedule.error.cronRangeInvalid", { item }));
|
|
169
177
|
}
|
|
170
178
|
if (a < min || b > max || a > b) {
|
|
171
|
-
throw new Error(
|
|
179
|
+
throw new Error(
|
|
180
|
+
t("schedule.error.cronRangeBounds", { item, min, max })
|
|
181
|
+
);
|
|
172
182
|
}
|
|
173
183
|
for (let v = a; v <= b; v += step) result.add(v);
|
|
174
184
|
continue;
|
|
175
185
|
}
|
|
176
186
|
const num = Number(item);
|
|
177
187
|
if (!Number.isInteger(num) || num < min || num > max) {
|
|
178
|
-
throw new Error(
|
|
188
|
+
throw new Error(
|
|
189
|
+
t("schedule.error.cronValueBounds", { raw, min, max })
|
|
190
|
+
);
|
|
179
191
|
}
|
|
180
192
|
result.add(num);
|
|
181
193
|
}
|
|
@@ -208,7 +220,9 @@ export function normalizeCron(expr: string): string {
|
|
|
208
220
|
if (unit === "m" && n >= 1 && n < 60) return `*/${n} * * * *`;
|
|
209
221
|
if (unit === "h" && n >= 1 && n <= 23) return `0 */${n} * * *`;
|
|
210
222
|
if (unit === "d" && n >= 1 && n <= 31) return `0 0 */${n} * *`;
|
|
211
|
-
throw new Error(
|
|
223
|
+
throw new Error(
|
|
224
|
+
t("schedule.error.everyInterval", { value: `${n}${unit}` })
|
|
225
|
+
);
|
|
212
226
|
}
|
|
213
227
|
|
|
214
228
|
/** Парсит cron-выражение; бросает Error с понятным сообщением. */
|
|
@@ -216,7 +230,9 @@ export function parseCron(expr: string): ParsedCron {
|
|
|
216
230
|
const raw = normalizeCron(expr);
|
|
217
231
|
const fields = raw.split(/\s+/);
|
|
218
232
|
if (fields.length !== 5) {
|
|
219
|
-
throw new Error(
|
|
233
|
+
throw new Error(
|
|
234
|
+
t("schedule.error.cronFields", { count: fields.length, raw })
|
|
235
|
+
);
|
|
220
236
|
}
|
|
221
237
|
const [minF, hourF, domF, monthF, dowF] = fields;
|
|
222
238
|
|
|
@@ -252,13 +268,18 @@ export function parseCron(expr: string): ParsedCron {
|
|
|
252
268
|
if (DOW_NAMES[dToken] !== undefined) dToken = String(DOW_NAMES[dToken]);
|
|
253
269
|
const weekday = Number(dToken);
|
|
254
270
|
if (!Number.isInteger(weekday) || weekday < 0 || weekday > 7) {
|
|
255
|
-
throw new Error(
|
|
271
|
+
throw new Error(
|
|
272
|
+
t("schedule.error.weekdayBounds", {
|
|
273
|
+
value: hash[1],
|
|
274
|
+
field: dowF,
|
|
275
|
+
})
|
|
276
|
+
);
|
|
256
277
|
}
|
|
257
278
|
nthWeekday.push({ weekday: weekday % 7, n: Number(hash[2]) });
|
|
258
279
|
continue;
|
|
259
280
|
}
|
|
260
281
|
if (token === "L") {
|
|
261
|
-
throw new Error("
|
|
282
|
+
throw new Error(t("schedule.error.lastDomOnly"));
|
|
262
283
|
}
|
|
263
284
|
kept.push(token);
|
|
264
285
|
}
|
|
@@ -431,10 +452,12 @@ export function validateLaunchWindow(notBefore?: string | null, notAfter?: strin
|
|
|
431
452
|
const nb = notBefore?.trim() ?? "";
|
|
432
453
|
const na = notAfter?.trim() ?? "";
|
|
433
454
|
if (!nb && !na) return null;
|
|
434
|
-
if (nb && !isValidDailyTime(nb))
|
|
435
|
-
|
|
436
|
-
if (
|
|
437
|
-
|
|
455
|
+
if (nb && !isValidDailyTime(nb))
|
|
456
|
+
return t("schedule.error.notBeforeFormat", { value: nb });
|
|
457
|
+
if (na && !isValidDailyTime(na))
|
|
458
|
+
return t("schedule.error.notAfterFormat", { value: na });
|
|
459
|
+
if (!nb || !na) return t("schedule.error.windowTogether");
|
|
460
|
+
if (nb === na) return t("schedule.error.windowEmpty");
|
|
438
461
|
return null;
|
|
439
462
|
}
|
|
440
463
|
|
|
@@ -536,11 +559,18 @@ export function activeWindowState(now: Date, options: ActiveWindowOptions = {}):
|
|
|
536
559
|
|
|
537
560
|
const reasons: string[] = [];
|
|
538
561
|
if (!dayOk) {
|
|
539
|
-
const
|
|
540
|
-
|
|
562
|
+
const days = (normalizedDays ?? [])
|
|
563
|
+
.map((d) => t(`schedule.weekday.${d}`))
|
|
564
|
+
.join(", ");
|
|
565
|
+
reasons.push(t("schedule.reason.dayNotAllowed", { days }));
|
|
541
566
|
}
|
|
542
567
|
if (!windowOk) {
|
|
543
|
-
reasons.push(
|
|
568
|
+
reasons.push(
|
|
569
|
+
t("schedule.reason.outsideWindow", {
|
|
570
|
+
notBefore: options.notBefore,
|
|
571
|
+
notAfter: options.notAfter,
|
|
572
|
+
})
|
|
573
|
+
);
|
|
544
574
|
}
|
|
545
575
|
return {
|
|
546
576
|
active: false,
|
|
@@ -38,6 +38,12 @@ export interface CreateTaskOptions {
|
|
|
38
38
|
notBefore?: string;
|
|
39
39
|
/** Окно запуска «не позже» (HH:MM, 24ч). Парно с notBefore. */
|
|
40
40
|
notAfter?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Windows: запускать задачу и без входа пользователя (/ru SYSTEM).
|
|
43
|
+
* По умолчанию задача интерактивная — выполняется только при активном входе.
|
|
44
|
+
* На Linux/macOS не используется: cron и так работает без входа, launchd-агент — только при входе.
|
|
45
|
+
*/
|
|
46
|
+
runWhenLoggedOff?: boolean;
|
|
41
47
|
/** Аргументы schedule-gate для обёртки (расширенный cron / окно). */
|
|
42
48
|
scheduleGate?: {
|
|
43
49
|
cron?: string;
|
|
@@ -23,11 +23,11 @@ export const WINDOWS_TASK_PREFIX = `\\${TASK_FOLDER}\\${TASK_FOLDER_NAME}\\`;
|
|
|
23
23
|
/**
|
|
24
24
|
* Декодирует вывод консольных утилит Windows.
|
|
25
25
|
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
26
|
+
* `schtasks.exe` запускается напрямую, без `cmd.exe`, поэтому метасимволы
|
|
27
|
+
* в аргументах не исполняются. Вывод утилиты на русской Windows приходит
|
|
28
|
+
* в OEM-кодировке (CP866), из-за чего Node, читающий его как UTF-8,
|
|
29
|
+
* показывает «?????». Поэтому: если байты — валидный UTF-8, декодируем
|
|
30
|
+
* как UTF-8, иначе пробуем CP866.
|
|
31
31
|
*/
|
|
32
32
|
function decodeConsoleOutput(buf: Buffer | string | undefined | null): string {
|
|
33
33
|
if (!buf) return "";
|
|
@@ -81,13 +81,16 @@ export class SchtasksError extends Error {
|
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
/**
|
|
84
|
-
* Выполняет
|
|
85
|
-
*
|
|
84
|
+
* Выполняет `schtasks.exe` напрямую с массивом аргументов.
|
|
85
|
+
*
|
|
86
|
+
* Раньше команда собиралась в строку и запускалась через `cmd.exe /c`,
|
|
87
|
+
* из-за чего метасимволы (`&`, `|`, `"`) в имени задачи исполнялись
|
|
88
|
+
* оболочкой: можно было получить command injection и «фантомную» задачу.
|
|
89
|
+
* `execFile` передаёт каждый аргумент отдельно — оболочки в цепочке нет.
|
|
86
90
|
*/
|
|
87
91
|
export async function runSchtasks(args: string[]): Promise<SchtasksResult> {
|
|
88
92
|
try {
|
|
89
|
-
const
|
|
90
|
-
const { stdout, stderr } = (await execFileAsync("cmd.exe", ["/c", command], {
|
|
93
|
+
const { stdout, stderr } = (await execFileAsync("schtasks", args, {
|
|
91
94
|
windowsHide: true,
|
|
92
95
|
encoding: "buffer",
|
|
93
96
|
maxBuffer: MAX_OUTPUT_BUFFER,
|
|
@@ -167,6 +170,11 @@ export class WindowsScheduler implements SchedulerBackend {
|
|
|
167
170
|
}
|
|
168
171
|
|
|
169
172
|
const fullName = taskFullName(name);
|
|
173
|
+
// Спринт 27.5.4: по умолчанию задача интерактивная — schtasks запускает её
|
|
174
|
+
// только при активном входе пользователя (Interactive only). Для работы без
|
|
175
|
+
// входа нужен SYSTEM: он не требует пароля, но работает в session 0 без
|
|
176
|
+
// профиля пользователя (нет доступа к пользовательским файлам/сети/ключам).
|
|
177
|
+
const logonFlags = options.runWhenLoggedOff ? ["/ru", "SYSTEM"] : [];
|
|
170
178
|
const args: string[] = [
|
|
171
179
|
"/create",
|
|
172
180
|
"/tn",
|
|
@@ -174,6 +182,7 @@ export class WindowsScheduler implements SchedulerBackend {
|
|
|
174
182
|
"/tr",
|
|
175
183
|
`"${command}"`,
|
|
176
184
|
...scheduleFlags,
|
|
185
|
+
...logonFlags,
|
|
177
186
|
"/f",
|
|
178
187
|
];
|
|
179
188
|
|
|
@@ -225,7 +234,9 @@ export class WindowsScheduler implements SchedulerBackend {
|
|
|
225
234
|
}
|
|
226
235
|
|
|
227
236
|
async listTasks(): Promise<ScheduledTaskInfo[]> {
|
|
228
|
-
|
|
237
|
+
// /v нужен, чтобы ОС отдала «Режим входа» (Logon Mode): без него
|
|
238
|
+
// schtasks печатает только имя, время и состояние, а logonMode остаётся null.
|
|
239
|
+
const args = ["/query", "/v", "/fo", "LIST"];
|
|
229
240
|
|
|
230
241
|
let result: SchtasksResult;
|
|
231
242
|
try {
|
|
@@ -284,6 +295,8 @@ export class WindowsScheduler implements SchedulerBackend {
|
|
|
284
295
|
const alreadyGone =
|
|
285
296
|
text.includes("cannot find") ||
|
|
286
297
|
text.includes("не удалось найти") ||
|
|
298
|
+
text.includes("не удается найти") ||
|
|
299
|
+
text.includes("не может найти") ||
|
|
287
300
|
text.includes("не найдено") ||
|
|
288
301
|
text.includes("the system cannot find the file specified") ||
|
|
289
302
|
text.includes("no tasks") ||
|
|
@@ -477,6 +490,8 @@ function setTaskField(task: any, key: string, value: string): void {
|
|
|
477
490
|
"следующее время запуска": "nextRunTime",
|
|
478
491
|
состояние: "status",
|
|
479
492
|
"режим входа": "logonMode",
|
|
493
|
+
// RU Windows 10/11 в /v печатает полную формулировку.
|
|
494
|
+
"режим входа в систему": "logonMode",
|
|
480
495
|
"последнее время запуска": "lastRunTime",
|
|
481
496
|
"последний результат": "lastResult",
|
|
482
497
|
автор: "author",
|
package/src/core/secrets.ts
CHANGED
|
@@ -278,13 +278,18 @@ export function listSecrets(): SecretListItem[] {
|
|
|
278
278
|
});
|
|
279
279
|
}
|
|
280
280
|
|
|
281
|
-
/** Подставляет все ссылки `${secret:NAME}` в строку. */
|
|
282
|
-
export function expandSecretRefs(
|
|
283
|
-
value: string
|
|
284
|
-
|
|
285
|
-
} {
|
|
281
|
+
/** Подставляет все ссылки `${secret:NAME}` в строку. Если задан allowedSecretNames — заменяются только ссылки на имена из этого списка (scoped-инъекция), остальные оставляются без изменений. */
|
|
282
|
+
export function expandSecretRefs(
|
|
283
|
+
value: string,
|
|
284
|
+
allowedSecretNames?: string[]
|
|
285
|
+
): { value: string; missing: string[] } {
|
|
286
286
|
const missing = new Set<string>();
|
|
287
|
+
const allowed = allowedSecretNames ? new Set(allowedSecretNames) : null;
|
|
287
288
|
const result = String(value ?? "").replace(SECRET_REF_RE, (_match, name: string) => {
|
|
289
|
+
if (allowed && !allowed.has(name)) {
|
|
290
|
+
// Секрет не разрешён для этой задачи — оставляем ссылку как есть.
|
|
291
|
+
return _match;
|
|
292
|
+
}
|
|
288
293
|
const secret = getSecret(name);
|
|
289
294
|
if (secret === undefined) {
|
|
290
295
|
missing.add(name);
|
|
@@ -298,15 +303,16 @@ export function expandSecretRefs(value: string): {
|
|
|
298
303
|
/**
|
|
299
304
|
* Разворачивает ссылки во всех значениях env. Отсутствующие секреты дают
|
|
300
305
|
* пустую строку и попадают в `missing` (только имена — без значений).
|
|
306
|
+
* Если задан allowedSecretNames — инжектит в env только реально используемые секреты.
|
|
301
307
|
*/
|
|
302
|
-
export function resolveSecretRefs(
|
|
303
|
-
env: Record<string, string
|
|
304
|
-
|
|
305
|
-
} {
|
|
308
|
+
export function resolveSecretRefs(
|
|
309
|
+
env: Record<string, string>,
|
|
310
|
+
allowedSecretNames?: string[]
|
|
311
|
+
): { env: Record<string, string>; missing: string[] } {
|
|
306
312
|
const resolved: Record<string, string> = {};
|
|
307
313
|
const missing = new Set<string>();
|
|
308
314
|
for (const [key, value] of Object.entries(env ?? {})) {
|
|
309
|
-
const result = expandSecretRefs(String(value ?? ""));
|
|
315
|
+
const result = expandSecretRefs(String(value ?? ""), allowedSecretNames);
|
|
310
316
|
resolved[key] = result.value;
|
|
311
317
|
for (const name of result.missing) missing.add(name);
|
|
312
318
|
}
|
|
@@ -383,3 +389,21 @@ export function resetSecretsCache(): void {
|
|
|
383
389
|
keyCache = null;
|
|
384
390
|
valuesCache = null;
|
|
385
391
|
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Собирает уникальные имена секретов из всех переданных строк, содержащих
|
|
395
|
+
* ссылки вида ${secret:NAME}. Возвращает отсортированный список имён.
|
|
396
|
+
* Используется для scoped-инъекции: только упомянутые секреты попадают в env задачи.
|
|
397
|
+
*/
|
|
398
|
+
export function collectSecretNames(...values: (string | undefined)[]): string[] {
|
|
399
|
+
const names = new Set<string>();
|
|
400
|
+
for (const value of values) {
|
|
401
|
+
if (!value) continue;
|
|
402
|
+
SECRET_REF_RE.lastIndex = 0;
|
|
403
|
+
let match: RegExpExecArray | null;
|
|
404
|
+
while ((match = SECRET_REF_RE.exec(value)) !== null) {
|
|
405
|
+
names.add(match[1]);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return [...names].sort();
|
|
409
|
+
}
|
package/src/core/telegram.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { t } from "../i18n.js";
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Telegram Bot API: отправка уведомлений (Спринт 25).
|
|
3
5
|
*
|
|
@@ -74,29 +76,29 @@ export function formatTelegramText(
|
|
|
74
76
|
if (!url) return body;
|
|
75
77
|
|
|
76
78
|
if (parseMode === "HTML") {
|
|
77
|
-
return `${body}\n\n<a href="${escapeHtmlAttribute(url)}"
|
|
79
|
+
return `${body}\n\n<a href="${escapeHtmlAttribute(url)}">${t("notify.telegram.openDashboard")}</a>`;
|
|
78
80
|
}
|
|
79
81
|
if (parseMode === "MarkdownV2") {
|
|
80
82
|
const escapedUrl = url.replace(/[)\\]/g, "\\$&");
|
|
81
|
-
return `${body}\n\n[
|
|
83
|
+
return `${body}\n\n[${t("notify.telegram.openDashboard")}](${escapedUrl})`;
|
|
82
84
|
}
|
|
83
85
|
if (parseMode === "Markdown") {
|
|
84
86
|
const escapedUrl = url.replace(/[)]/g, "\\)");
|
|
85
|
-
return `${body}\n\n[
|
|
87
|
+
return `${body}\n\n[${t("notify.telegram.openDashboard")}](${escapedUrl})`;
|
|
86
88
|
}
|
|
87
|
-
return `${body}\n\n
|
|
89
|
+
return `${body}\n\n${t("notify.telegram.openDashboardUrl", { url })}`;
|
|
88
90
|
}
|
|
89
91
|
|
|
90
92
|
/** Проверяет формат токена бота; возвращает trimmed-значение. */
|
|
91
93
|
export function validateTelegramToken(token: string): string {
|
|
92
94
|
const value = (token ?? "").trim();
|
|
93
95
|
if (!value) {
|
|
94
|
-
throw new Error("
|
|
96
|
+
throw new Error(t("notify.error.telegramTokenMissing"));
|
|
95
97
|
}
|
|
96
98
|
// Формат BotFather: <digits>:<base64-ish>. Проверяем достаточно мягко,
|
|
97
99
|
// чтобы не ломать тестовые токены, но отсекать явный мусор.
|
|
98
100
|
if (!/^\d+:[A-Za-z0-9_-]{5,}$/.test(value)) {
|
|
99
|
-
throw new Error("
|
|
101
|
+
throw new Error(t("notify.error.telegramTokenInvalid"));
|
|
100
102
|
}
|
|
101
103
|
return value;
|
|
102
104
|
}
|
|
@@ -125,10 +127,10 @@ function resolveApiBase(apiBase?: string): string {
|
|
|
125
127
|
try {
|
|
126
128
|
parsed = new URL(value);
|
|
127
129
|
} catch {
|
|
128
|
-
throw new Error("
|
|
130
|
+
throw new Error(t("notify.error.telegramApiBaseInvalid"));
|
|
129
131
|
}
|
|
130
132
|
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
131
|
-
throw new Error("
|
|
133
|
+
throw new Error(t("notify.error.telegramScheme"));
|
|
132
134
|
}
|
|
133
135
|
return value;
|
|
134
136
|
}
|
|
@@ -148,7 +150,7 @@ export async function sendTelegramMessage(
|
|
|
148
150
|
const safeToken = validateTelegramToken(token);
|
|
149
151
|
const target = (chatId ?? "").trim();
|
|
150
152
|
if (!target) {
|
|
151
|
-
throw new Error("
|
|
153
|
+
throw new Error(t("notify.error.telegramChatMissing"));
|
|
152
154
|
}
|
|
153
155
|
|
|
154
156
|
const apiBase = resolveApiBase(options.apiBase);
|
|
@@ -209,7 +211,11 @@ export async function sendTelegramMessage(
|
|
|
209
211
|
}
|
|
210
212
|
} catch (err: any) {
|
|
211
213
|
if (err?.name === "AbortError") {
|
|
212
|
-
throw new Error(
|
|
214
|
+
throw new Error(
|
|
215
|
+
t("notify.error.telegramTimeout", {
|
|
216
|
+
seconds: Math.floor(timeoutMs / 1000),
|
|
217
|
+
})
|
|
218
|
+
);
|
|
213
219
|
}
|
|
214
220
|
const message = err instanceof Error ? err.message : String(err);
|
|
215
221
|
throw new Error(sanitizeErrorText(message, safeToken));
|