agent-steward 0.0.2 → 0.0.3
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 +25 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +9 -8
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +114 -999
- package/dist/core/cron-to-schtasks.d.ts +0 -8
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +11 -86
- package/dist/core/dry-run.js +1 -1
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.js +2 -4
- package/dist/core/one-shot.d.ts +27 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +53 -10
- package/dist/core/otel.js +2 -2
- 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 +55 -35
- package/dist/core/record-history.js +22 -22
- package/dist/core/schedule-v2.d.ts +2 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +7 -7
- package/dist/core/scheduler/at-fallback.d.ts +42 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +70 -0
- package/dist/core/scheduler/linux.d.ts +3 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +43 -7
- package/dist/core/scheduler/mac.d.ts +14 -8
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +71 -22
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +12 -1
- package/dist/core/scheduler/registry.d.ts +2 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +16 -3
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +249 -96
- package/dist/core/secrets.js +2 -2
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/summary.js +1 -1
- package/dist/core/triage-chain.js +1 -1
- package/dist/core/triage-worker.js +2 -2
- package/dist/core/triage.js +1 -1
- package/dist/core/wrappers/bash.js +33 -33
- package/dist/db/index.d.ts +2 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +9 -1
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +48 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +137 -0
- package/dist/db/runs-repo.d.ts +120 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +319 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +190 -35
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +66 -36
- package/dist/notifications.js +18 -18
- package/dist/profiles.d.ts +7 -3
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +85 -7
- package/dist/rpc.d.ts +109 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +89 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +20 -19
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/skill.js +1 -1
- package/dist/task-transfer.d.ts +1 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +14 -10
- package/dist/types.d.ts +20 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +37 -9
- package/dist/workspaces.js +1 -1
- package/docs/ARCHITECTURE.md +110 -8
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +15 -3
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/FAQ.md +2 -2
- package/docs/FAQ.ru.md +2 -2
- package/docs/FAQ.zh.md +2 -2
- package/docs/FEATURES.md +5 -4
- package/docs/FEATURES.zh.md +5 -4
- package/docs/MIGRATION.md +34 -26
- package/docs/README.ru.md +26 -7
- package/docs/README.zh.md +9 -8
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +1 -0
- package/locales/ru.json +1 -0
- package/locales/zh.json +1 -0
- package/package.json +31 -10
- package/src/core/analytics.ts +2 -2
- package/src/core/audit.ts +17 -17
- package/src/core/cron-to-schtasks.ts +14 -93
- package/src/core/dry-run.ts +26 -26
- package/src/core/file-watcher.ts +17 -17
- package/src/core/git-trigger.ts +9 -9
- package/src/core/glob.ts +1 -1
- package/src/core/local-ai.ts +2 -2
- package/src/core/lock.ts +9 -9
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +63 -13
- package/src/core/otel.ts +4 -4
- package/src/core/permissions.ts +5 -5
- package/src/core/prometheus.ts +17 -17
- package/src/core/ps-wrapper.ts +57 -37
- package/src/core/record-history.ts +40 -40
- package/src/core/retention.ts +3 -3
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +12 -12
- package/src/core/schedule-v2.ts +24 -24
- package/src/core/scheduler/at-fallback.ts +113 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +64 -13
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +15 -1
- package/src/core/scheduler/registry.ts +6 -4
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +13 -13
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +3 -3
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/telegram.ts +16 -16
- package/src/core/triage-chain.ts +4 -4
- package/src/core/triage-compare.ts +8 -8
- package/src/core/triage-rules.ts +4 -4
- package/src/core/triage-shadow.ts +7 -7
- package/src/core/triage-worker.ts +6 -6
- package/src/core/triage.ts +23 -23
- package/src/core/watch-paths.ts +1 -1
- package/src/core/wrappers/bash.ts +41 -41
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +22 -22
- package/src/db/index.ts +16 -6
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +10 -10
- package/src/db/recovery.ts +3 -3
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +220 -0
- package/src/db/runs-repo.ts +481 -0
- package/src/db/schema.ts +205 -44
- package/src/db/settings-repo.ts +2 -2
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +1 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +341 -304
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +96 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +43 -42
- package/src/settings.ts +44 -44
- package/src/shared/jobs-view.ts +60 -60
- package/src/skill.ts +1 -1
- package/src/task-transfer.ts +58 -56
- package/src/templates.ts +1 -1
- package/src/types.ts +45 -10
- package/src/workspaces.ts +16 -16
- package/dist/core/self-analysis.test.d.ts +0 -2
- package/dist/core/self-analysis.test.d.ts.map +0 -1
- package/dist/core/self-analysis.test.js +0 -219
- package/dist/gui-experimental.cjs +0 -1
|
@@ -41,24 +41,24 @@ export interface UsageInfo {
|
|
|
41
41
|
costUsd?: number;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
const USAGE_PREFIX =
|
|
44
|
+
const USAGE_PREFIX = "^\\s*(?:\\[.*?\\]\\s*)?";
|
|
45
45
|
const TOKEN_PATTERNS: RegExp[] = [
|
|
46
|
-
new RegExp(USAGE_PREFIX +
|
|
47
|
-
new RegExp(USAGE_PREFIX +
|
|
46
|
+
new RegExp(USAGE_PREFIX + "(?:tokens?|token\\s+usage|usage)\\s*[:=]\\s*([0-9][0-9.,]*)\\s*([kKmM])?\\b", "i"),
|
|
47
|
+
new RegExp(USAGE_PREFIX + "(?:input|output|total)\\s+tokens?\\s*[:=]?\\s*([0-9][0-9.,]*)\\s*([kKmM])?\\b", "i"),
|
|
48
48
|
];
|
|
49
49
|
const COST_PATTERNS: RegExp[] = [
|
|
50
|
-
new RegExp(USAGE_PREFIX +
|
|
51
|
-
new RegExp(USAGE_PREFIX +
|
|
50
|
+
new RegExp(USAGE_PREFIX + "(?:cost|total\\s+cost)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)", "i"),
|
|
51
|
+
new RegExp(USAGE_PREFIX + "(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)", "i"),
|
|
52
52
|
];
|
|
53
53
|
|
|
54
54
|
function parseUsageValue(raw: string, suffix?: string): number | undefined {
|
|
55
|
-
const value = parseFloat(raw.replace(
|
|
55
|
+
const value = parseFloat(raw.replace(",", "."));
|
|
56
56
|
if (!Number.isFinite(value)) return undefined;
|
|
57
57
|
let mult = 1;
|
|
58
58
|
if (suffix) {
|
|
59
59
|
const s = suffix.toLowerCase();
|
|
60
|
-
if (s ===
|
|
61
|
-
else if (s ===
|
|
60
|
+
if (s === "k") mult = 1000;
|
|
61
|
+
else if (s === "m") mult = 1000000;
|
|
62
62
|
}
|
|
63
63
|
return Math.round(value * mult);
|
|
64
64
|
}
|
|
@@ -94,7 +94,7 @@ export function parseUsageFromLog(logFile: string): UsageInfo {
|
|
|
94
94
|
for (const pattern of COST_PATTERNS) {
|
|
95
95
|
const m = text.match(pattern);
|
|
96
96
|
if (m) {
|
|
97
|
-
result.costUsd = parseFloat(m[1].replace(
|
|
97
|
+
result.costUsd = parseFloat(m[1].replace(",", "."));
|
|
98
98
|
break;
|
|
99
99
|
}
|
|
100
100
|
}
|
|
@@ -128,9 +128,9 @@ async function triggerTask(taskName: string): Promise<boolean> {
|
|
|
128
128
|
return true;
|
|
129
129
|
} catch (err: any) {
|
|
130
130
|
console.error(
|
|
131
|
-
`[
|
|
131
|
+
`[agent-steward] Не удалось запустить задачу цепочки "${taskName}": ${
|
|
132
132
|
err instanceof Error ? err.message : String(err)
|
|
133
|
-
}
|
|
133
|
+
}`,
|
|
134
134
|
);
|
|
135
135
|
return false;
|
|
136
136
|
}
|
|
@@ -177,7 +177,7 @@ async function scheduleRetry(taskName: string): Promise<boolean> {
|
|
|
177
177
|
|
|
178
178
|
if (remaining <= 0) {
|
|
179
179
|
await clearRetryState(taskName);
|
|
180
|
-
console.log(`[
|
|
180
|
+
console.log(`[agent-steward] Повторы для "${taskName}" исчерпаны.`);
|
|
181
181
|
return false;
|
|
182
182
|
}
|
|
183
183
|
|
|
@@ -197,15 +197,15 @@ async function scheduleRetry(taskName: string): Promise<boolean> {
|
|
|
197
197
|
child.unref();
|
|
198
198
|
|
|
199
199
|
console.log(
|
|
200
|
-
`[
|
|
201
|
-
`(осталось повторов: ${remaining - 1})
|
|
200
|
+
`[agent-steward] Задача "${taskName}" будет повторена через ${delay} с ` +
|
|
201
|
+
`(осталось повторов: ${remaining - 1}).`,
|
|
202
202
|
);
|
|
203
203
|
return true;
|
|
204
204
|
} catch (err: any) {
|
|
205
205
|
console.error(
|
|
206
|
-
`[
|
|
206
|
+
`[agent-steward] Не удалось запланировать повтор "${taskName}": ${
|
|
207
207
|
err instanceof Error ? err.message : String(err)
|
|
208
|
-
}
|
|
208
|
+
}`,
|
|
209
209
|
);
|
|
210
210
|
return false;
|
|
211
211
|
}
|
|
@@ -222,12 +222,12 @@ async function runRetry(taskName: string, delaySec: number): Promise<void> {
|
|
|
222
222
|
|
|
223
223
|
try {
|
|
224
224
|
await createSchedulerBackend().runTask(taskName);
|
|
225
|
-
console.log(`[
|
|
225
|
+
console.log(`[agent-steward] Повторный запуск задачи "${taskName}".`);
|
|
226
226
|
} catch (err: any) {
|
|
227
227
|
console.error(
|
|
228
|
-
`[
|
|
228
|
+
`[agent-steward] Повторный запуск "${taskName}" не удался: ${
|
|
229
229
|
err instanceof Error ? err.message : String(err)
|
|
230
|
-
}
|
|
230
|
+
}`,
|
|
231
231
|
);
|
|
232
232
|
}
|
|
233
233
|
}
|
|
@@ -245,7 +245,7 @@ async function runRetry(taskName: string, delaySec: number): Promise<void> {
|
|
|
245
245
|
export function selectDependentsToTrigger(
|
|
246
246
|
completedTask: string,
|
|
247
247
|
definitions: TaskDefinition[],
|
|
248
|
-
history: HistoryRecord[]
|
|
248
|
+
history: HistoryRecord[],
|
|
249
249
|
): string[] {
|
|
250
250
|
const key = (value: string) => value.trim().toLowerCase();
|
|
251
251
|
|
|
@@ -278,9 +278,9 @@ export function selectDependentsToTrigger(
|
|
|
278
278
|
const depDefinition = defsByKey.get(key(dep));
|
|
279
279
|
const clones = depDefinition?.matrix
|
|
280
280
|
? definitions.filter(
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
281
|
+
(item) =>
|
|
282
|
+
item.matrixParentId && key(item.matrixParentId) === key(dep),
|
|
283
|
+
)
|
|
284
284
|
: [];
|
|
285
285
|
const requiredNames = clones.length > 0 ? clones.map((c) => c.name) : [dep];
|
|
286
286
|
|
|
@@ -318,7 +318,7 @@ export function selectDependentsToTrigger(
|
|
|
318
318
|
priorityByTask.set(key(definition.name), Number(definition.priority) || 5);
|
|
319
319
|
}
|
|
320
320
|
return toTrigger.sort(
|
|
321
|
-
(a, b) => (priorityByTask.get(key(b)) ?? 5) - (priorityByTask.get(key(a)) ?? 5)
|
|
321
|
+
(a, b) => (priorityByTask.get(key(b)) ?? 5) - (priorityByTask.get(key(a)) ?? 5),
|
|
322
322
|
);
|
|
323
323
|
}
|
|
324
324
|
|
|
@@ -352,7 +352,7 @@ async function main() {
|
|
|
352
352
|
return Number.isFinite(num) && num > 0 ? num : undefined;
|
|
353
353
|
};
|
|
354
354
|
const parseHookStatus = (
|
|
355
|
-
value?: string
|
|
355
|
+
value?: string,
|
|
356
356
|
): "success" | "error" | "skipped" | undefined => {
|
|
357
357
|
if (!value || value === "-") return undefined;
|
|
358
358
|
if (value === "success" || value === "error" || value === "skipped") return value;
|
|
@@ -375,7 +375,7 @@ async function main() {
|
|
|
375
375
|
startedAt,
|
|
376
376
|
definition?.workspaceId ?? null,
|
|
377
377
|
definition?.allowedTools ?? null,
|
|
378
|
-
definition?.deniedTools ?? null
|
|
378
|
+
definition?.deniedTools ?? null,
|
|
379
379
|
);
|
|
380
380
|
console.log(String(runId));
|
|
381
381
|
return;
|
|
@@ -433,11 +433,11 @@ async function main() {
|
|
|
433
433
|
costResolved,
|
|
434
434
|
model,
|
|
435
435
|
preFlightStatus,
|
|
436
|
-
postFlightStatus
|
|
436
|
+
postFlightStatus,
|
|
437
437
|
);
|
|
438
438
|
if (!completed) {
|
|
439
439
|
console.error(
|
|
440
|
-
`[
|
|
440
|
+
`[agent-steward] record-history: запись #${runId} уже завершена или не найдена.`,
|
|
441
441
|
);
|
|
442
442
|
return;
|
|
443
443
|
}
|
|
@@ -491,7 +491,7 @@ async function main() {
|
|
|
491
491
|
new Date().toISOString(),
|
|
492
492
|
definition?.workspaceId ?? null,
|
|
493
493
|
definition?.allowedTools ?? null,
|
|
494
|
-
definition?.deniedTools ?? null
|
|
494
|
+
definition?.deniedTools ?? null,
|
|
495
495
|
);
|
|
496
496
|
|
|
497
497
|
await handleCompletion(taskName, st, chainTarget, error, durationMs, tokens, costUsd);
|
|
@@ -508,7 +508,7 @@ async function handleCompletion(
|
|
|
508
508
|
error: string | null,
|
|
509
509
|
durationMs: number,
|
|
510
510
|
tokens?: number | null,
|
|
511
|
-
costUsd?: number | null
|
|
511
|
+
costUsd?: number | null,
|
|
512
512
|
): Promise<void> {
|
|
513
513
|
// Уведомление о завершении (webhook). Ошибки отправки логируются внутри
|
|
514
514
|
// и не влияют на историю, цепочки и повторы.
|
|
@@ -526,7 +526,7 @@ async function handleCompletion(
|
|
|
526
526
|
console.log(
|
|
527
527
|
`[matrix] ${taskName}: ошибка обработки матрицы: ${
|
|
528
528
|
err instanceof Error ? err.message : String(err)
|
|
529
|
-
}
|
|
529
|
+
}`,
|
|
530
530
|
);
|
|
531
531
|
}
|
|
532
532
|
|
|
@@ -536,7 +536,7 @@ async function handleCompletion(
|
|
|
536
536
|
if (chainTarget) {
|
|
537
537
|
const started = await triggerTask(chainTarget);
|
|
538
538
|
if (started) {
|
|
539
|
-
console.log(`[
|
|
539
|
+
console.log(`[agent-steward] Запущена следующая задача в цепочке: ${chainTarget}`);
|
|
540
540
|
}
|
|
541
541
|
}
|
|
542
542
|
|
|
@@ -551,15 +551,15 @@ async function handleCompletion(
|
|
|
551
551
|
const started = await triggerTask(dependent);
|
|
552
552
|
if (started) {
|
|
553
553
|
console.log(
|
|
554
|
-
`[
|
|
554
|
+
`[agent-steward] DAG: все зависимости выполнены, запущена задача "${dependent}".`,
|
|
555
555
|
);
|
|
556
556
|
}
|
|
557
557
|
}
|
|
558
558
|
} catch (err: any) {
|
|
559
559
|
console.error(
|
|
560
|
-
`[
|
|
560
|
+
`[agent-steward] DAG: не удалось запустить зависимые задачи: ${
|
|
561
561
|
err instanceof Error ? err.message : String(err)
|
|
562
|
-
}
|
|
562
|
+
}`,
|
|
563
563
|
);
|
|
564
564
|
}
|
|
565
565
|
} else {
|
|
@@ -569,7 +569,7 @@ async function handleCompletion(
|
|
|
569
569
|
if (!retryScheduled && chainTarget) {
|
|
570
570
|
const started = await triggerTask(chainTarget);
|
|
571
571
|
if (started) {
|
|
572
|
-
console.log(`[
|
|
572
|
+
console.log(`[agent-steward] Запущена компенсирующая задача: ${chainTarget}`);
|
|
573
573
|
}
|
|
574
574
|
}
|
|
575
575
|
}
|
|
@@ -580,9 +580,9 @@ async function handleCompletion(
|
|
|
580
580
|
await rotateSessionIfNeeded(taskName);
|
|
581
581
|
} catch (err: any) {
|
|
582
582
|
console.warn(
|
|
583
|
-
`[
|
|
583
|
+
`[agent-steward] Не удалось обновить состояние сессии "${taskName}": ${
|
|
584
584
|
err instanceof Error ? err.message : String(err)
|
|
585
|
-
}
|
|
585
|
+
}`,
|
|
586
586
|
);
|
|
587
587
|
}
|
|
588
588
|
}
|
|
@@ -606,9 +606,9 @@ function isDirectInvocation(): boolean {
|
|
|
606
606
|
if (isDirectInvocation()) {
|
|
607
607
|
main().catch((err) => {
|
|
608
608
|
console.error(
|
|
609
|
-
`[
|
|
609
|
+
`[agent-steward] record-history: не удалось записать результат запуска: ${
|
|
610
610
|
err instanceof Error ? err.message : String(err)
|
|
611
|
-
}
|
|
611
|
+
}`,
|
|
612
612
|
);
|
|
613
613
|
process.exit(1);
|
|
614
614
|
});
|
package/src/core/retention.ts
CHANGED
|
@@ -52,7 +52,7 @@ function normalizeOverride(value: unknown): number | undefined {
|
|
|
52
52
|
|
|
53
53
|
function effectiveLimits(
|
|
54
54
|
settings: HistorySettings,
|
|
55
|
-
overrides: RetentionOverrides
|
|
55
|
+
overrides: RetentionOverrides,
|
|
56
56
|
): { retentionDays: number; maxRecords: number } {
|
|
57
57
|
return {
|
|
58
58
|
retentionDays:
|
|
@@ -67,7 +67,7 @@ function effectiveLimits(
|
|
|
67
67
|
* `cleanup_history` заодно настраивает ретеншн.
|
|
68
68
|
*/
|
|
69
69
|
export async function runHistoryRetention(
|
|
70
|
-
overrides: RetentionOverrides = {}
|
|
70
|
+
overrides: RetentionOverrides = {},
|
|
71
71
|
): Promise<RetentionReport> {
|
|
72
72
|
const settings = await loadSettings();
|
|
73
73
|
const base = settings.history ?? defaultHistorySettings();
|
|
@@ -127,7 +127,7 @@ export async function runHistoryRetention(
|
|
|
127
127
|
* `force` игнорирует интервал (используется в тестах).
|
|
128
128
|
*/
|
|
129
129
|
export async function maybeRunHistoryRetention(
|
|
130
|
-
force = false
|
|
130
|
+
force = false,
|
|
131
131
|
): Promise<RetentionReport | undefined> {
|
|
132
132
|
const settings = await loadSettings();
|
|
133
133
|
const history = settings.history ?? defaultHistorySettings();
|
package/src/core/savings.ts
CHANGED
|
@@ -85,7 +85,7 @@ function roundUsd(value: number): number {
|
|
|
85
85
|
*/
|
|
86
86
|
export function computeSavings(
|
|
87
87
|
records: SavingsRecord[],
|
|
88
|
-
options: ComputeSavingsOptions = {}
|
|
88
|
+
options: ComputeSavingsOptions = {},
|
|
89
89
|
): SavingsReport {
|
|
90
90
|
const reference = positiveNumber(options.referenceCostPer1kTokensUsd)
|
|
91
91
|
|| CLOUD_REFERENCE_COST_PER_1K_TOKENS_USD;
|
|
@@ -124,11 +124,11 @@ async function main(): Promise<number> {
|
|
|
124
124
|
|
|
125
125
|
const days = daysArg
|
|
126
126
|
? normalizeActiveDays(
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
127
|
+
daysArg
|
|
128
|
+
.split(",")
|
|
129
|
+
.map((value) => Number(value.trim()))
|
|
130
|
+
.filter((value) => Number.isFinite(value)),
|
|
131
|
+
)
|
|
132
132
|
: undefined;
|
|
133
133
|
const policy: "skip" | "postpone" | "run" =
|
|
134
134
|
policyArg === "skip" || policyArg === "run" ? policyArg : "postpone";
|
|
@@ -164,7 +164,7 @@ async function main(): Promise<number> {
|
|
|
164
164
|
console.error(
|
|
165
165
|
`[schedule-gate] Невалидный cron «${cronExpr}»: ${
|
|
166
166
|
err instanceof Error ? err.message : String(err)
|
|
167
|
-
} — пропускаем проверку cron
|
|
167
|
+
} — пропускаем проверку cron.`,
|
|
168
168
|
);
|
|
169
169
|
}
|
|
170
170
|
}
|
|
@@ -191,7 +191,7 @@ async function main(): Promise<number> {
|
|
|
191
191
|
// Окно закрыто, но время его открытия неизвестно (например, окно
|
|
192
192
|
// выходит за горизонт поиска). Разрешать запуск в этом случае нельзя.
|
|
193
193
|
console.error(
|
|
194
|
-
`[schedule-gate] ${state.reason ?? "вне окна"} — время открытия окна неизвестно, запуск
|
|
194
|
+
`[schedule-gate] ${state.reason ?? "вне окна"} — время открытия окна неизвестно, запуск пропущен.`,
|
|
195
195
|
);
|
|
196
196
|
return 3;
|
|
197
197
|
}
|
|
@@ -199,7 +199,7 @@ async function main(): Promise<number> {
|
|
|
199
199
|
if (wait <= 0) return 0;
|
|
200
200
|
if (wait > MAX_POSTPONE_MS) {
|
|
201
201
|
console.error(
|
|
202
|
-
`[schedule-gate] ${state.reason ?? "вне окна"} — до открытия больше 12 часов, тик
|
|
202
|
+
`[schedule-gate] ${state.reason ?? "вне окна"} — до открытия больше 12 часов, тик пропущен.`,
|
|
203
203
|
);
|
|
204
204
|
return 3;
|
|
205
205
|
}
|
|
@@ -219,8 +219,8 @@ async function main(): Promise<number> {
|
|
|
219
219
|
|
|
220
220
|
console.error(
|
|
221
221
|
`[schedule-gate] ${state.reason ?? "Вне окна"} — запуск перенесён на ~${Math.round(
|
|
222
|
-
wait / 60000
|
|
223
|
-
)}
|
|
222
|
+
wait / 60000,
|
|
223
|
+
)} мин.`,
|
|
224
224
|
);
|
|
225
225
|
let remaining = wait;
|
|
226
226
|
while (remaining > 0) {
|
|
@@ -246,8 +246,8 @@ main().then(
|
|
|
246
246
|
(code) => process.exit(code),
|
|
247
247
|
(err) => {
|
|
248
248
|
console.error(
|
|
249
|
-
`[schedule-gate] Непредвиденная ошибка: ${err instanceof Error ? err.message : String(err)} —
|
|
249
|
+
`[schedule-gate] Непредвиденная ошибка: ${err instanceof Error ? err.message : String(err)} — запускаем.`,
|
|
250
250
|
);
|
|
251
251
|
process.exit(1);
|
|
252
|
-
}
|
|
252
|
+
},
|
|
253
253
|
);
|
package/src/core/schedule-v2.ts
CHANGED
|
@@ -114,7 +114,7 @@ export function wallToUtc(y: number, m: number, d: number, h: number, mi: number
|
|
|
114
114
|
// «следующего запуска» берём ПЕРВОЕ (более раннее) вхождение, а не то, к
|
|
115
115
|
// которому сошлась итерация. Обычно совпадение одно, тогда результат тот же.
|
|
116
116
|
const probes = [0, -30, 30, -60, 60, -90, 90, -120, 120].map(
|
|
117
|
-
(minutes) => guess + minutes * 60_000
|
|
117
|
+
(minutes) => guess + minutes * 60_000,
|
|
118
118
|
);
|
|
119
119
|
let best: number | null = null;
|
|
120
120
|
for (const ms of probes) {
|
|
@@ -142,9 +142,9 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
142
142
|
let item = raw.trim().toUpperCase();
|
|
143
143
|
if (!item)
|
|
144
144
|
throw new Error(t("schedule.error.cronEmptyItem", { token }));
|
|
145
|
-
if (names
|
|
145
|
+
if (names?.[item] !== undefined) item = String(names[item]);
|
|
146
146
|
// шаг: a-b/n или */n
|
|
147
|
-
const stepMatch =
|
|
147
|
+
const stepMatch = /^(.*)\/([0-9]+)$/.exec(item);
|
|
148
148
|
let step = 1;
|
|
149
149
|
if (stepMatch) {
|
|
150
150
|
item = (stepMatch[1] ?? "").trim();
|
|
@@ -154,7 +154,7 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
154
154
|
t("schedule.error.cronStepInvalid", {
|
|
155
155
|
step: stepMatch[2],
|
|
156
156
|
raw,
|
|
157
|
-
})
|
|
157
|
+
}),
|
|
158
158
|
);
|
|
159
159
|
}
|
|
160
160
|
if (item === "")
|
|
@@ -164,12 +164,12 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
164
164
|
for (let v = min; v <= max; v += step) result.add(v);
|
|
165
165
|
continue;
|
|
166
166
|
}
|
|
167
|
-
const rangeMatch =
|
|
167
|
+
const rangeMatch = /^([0-9A-Z]+)-([0-9A-Z]+)$/.exec(item);
|
|
168
168
|
if (rangeMatch) {
|
|
169
169
|
let aToken = rangeMatch[1];
|
|
170
170
|
let bToken = rangeMatch[2];
|
|
171
|
-
if (names
|
|
172
|
-
if (names
|
|
171
|
+
if (names?.[aToken] !== undefined) aToken = String(names[aToken]);
|
|
172
|
+
if (names?.[bToken] !== undefined) bToken = String(names[bToken]);
|
|
173
173
|
const a = Number(aToken);
|
|
174
174
|
const b = Number(bToken);
|
|
175
175
|
if (!Number.isFinite(a) || !Number.isFinite(b)) {
|
|
@@ -177,7 +177,7 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
177
177
|
}
|
|
178
178
|
if (a < min || b > max || a > b) {
|
|
179
179
|
throw new Error(
|
|
180
|
-
t("schedule.error.cronRangeBounds", { item, min, max })
|
|
180
|
+
t("schedule.error.cronRangeBounds", { item, min, max }),
|
|
181
181
|
);
|
|
182
182
|
}
|
|
183
183
|
for (let v = a; v <= b; v += step) result.add(v);
|
|
@@ -186,7 +186,7 @@ function expandField(token: string, min: number, max: number, names?: Record<str
|
|
|
186
186
|
const num = Number(item);
|
|
187
187
|
if (!Number.isInteger(num) || num < min || num > max) {
|
|
188
188
|
throw new Error(
|
|
189
|
-
t("schedule.error.cronValueBounds", { raw, min, max })
|
|
189
|
+
t("schedule.error.cronValueBounds", { raw, min, max }),
|
|
190
190
|
);
|
|
191
191
|
}
|
|
192
192
|
result.add(num);
|
|
@@ -207,13 +207,13 @@ export interface ParsedCron {
|
|
|
207
207
|
/** День недели 0(Вс)..6(Сб) или null, если поле = «*» и не содержит «#». */
|
|
208
208
|
dayOfWeek: Set<number> | null;
|
|
209
209
|
/** Пары {weekday, n} для «#». */
|
|
210
|
-
nthWeekday:
|
|
210
|
+
nthWeekday: { weekday: number; n: number }[];
|
|
211
211
|
}
|
|
212
212
|
|
|
213
213
|
/** Разворачивает «@every 15m|2h|1d» в обычный cron. */
|
|
214
214
|
export function normalizeCron(expr: string): string {
|
|
215
215
|
const trimmed = expr.trim();
|
|
216
|
-
const match =
|
|
216
|
+
const match = /^@every\s+(\d+)([mhd])$/i.exec(trimmed);
|
|
217
217
|
if (!match) return trimmed;
|
|
218
218
|
const n = Number(match[1]);
|
|
219
219
|
const unit = match[2].toLowerCase();
|
|
@@ -221,7 +221,7 @@ export function normalizeCron(expr: string): string {
|
|
|
221
221
|
if (unit === "h" && n >= 1 && n <= 23) return `0 */${n} * * *`;
|
|
222
222
|
if (unit === "d" && n >= 1 && n <= 31) return `0 0 */${n} * *`;
|
|
223
223
|
throw new Error(
|
|
224
|
-
t("schedule.error.everyInterval", { value: `${n}${unit}` })
|
|
224
|
+
t("schedule.error.everyInterval", { value: `${n}${unit}` }),
|
|
225
225
|
);
|
|
226
226
|
}
|
|
227
227
|
|
|
@@ -231,7 +231,7 @@ export function parseCron(expr: string): ParsedCron {
|
|
|
231
231
|
const fields = raw.split(/\s+/);
|
|
232
232
|
if (fields.length !== 5) {
|
|
233
233
|
throw new Error(
|
|
234
|
-
t("schedule.error.cronFields", { count: fields.length, raw })
|
|
234
|
+
t("schedule.error.cronFields", { count: fields.length, raw }),
|
|
235
235
|
);
|
|
236
236
|
}
|
|
237
237
|
const [minF, hourF, domF, monthF, dowF] = fields;
|
|
@@ -257,12 +257,12 @@ export function parseCron(expr: string): ParsedCron {
|
|
|
257
257
|
|
|
258
258
|
// dow: «*» + имена + «d#n».
|
|
259
259
|
let dayOfWeek: Set<number> | null = null;
|
|
260
|
-
const nthWeekday:
|
|
260
|
+
const nthWeekday: { weekday: number; n: number }[] = [];
|
|
261
261
|
{
|
|
262
262
|
const tokens = dowF.trim().toUpperCase().split(",").map((s) => s.trim());
|
|
263
263
|
const kept: string[] = [];
|
|
264
264
|
for (const token of tokens) {
|
|
265
|
-
const hash =
|
|
265
|
+
const hash = /^([0-9A-Z]+)#([1-5])$/.exec(token);
|
|
266
266
|
if (hash) {
|
|
267
267
|
let dToken = hash[1];
|
|
268
268
|
if (DOW_NAMES[dToken] !== undefined) dToken = String(DOW_NAMES[dToken]);
|
|
@@ -272,7 +272,7 @@ export function parseCron(expr: string): ParsedCron {
|
|
|
272
272
|
t("schedule.error.weekdayBounds", {
|
|
273
273
|
value: hash[1],
|
|
274
274
|
field: dowF,
|
|
275
|
-
})
|
|
275
|
+
}),
|
|
276
276
|
);
|
|
277
277
|
}
|
|
278
278
|
nthWeekday.push({ weekday: weekday % 7, n: Number(hash[2]) });
|
|
@@ -340,10 +340,10 @@ function candidatesOnDay(
|
|
|
340
340
|
d: number,
|
|
341
341
|
notBefore: { hour: number; minute: number } | null,
|
|
342
342
|
notAfter: { hour: number; minute: number } | null,
|
|
343
|
-
):
|
|
343
|
+
): { hour: number; minute: number }[] {
|
|
344
344
|
const hours = [...spec.hour].sort((a, b) => a - b);
|
|
345
345
|
const minutes = [...spec.minute].sort((a, b) => a - b);
|
|
346
|
-
const result:
|
|
346
|
+
const result: { hour: number; minute: number }[] = [];
|
|
347
347
|
for (const hour of hours) {
|
|
348
348
|
for (const minute of minutes) {
|
|
349
349
|
if (notBefore) {
|
|
@@ -470,8 +470,8 @@ function wallMinutes(date: Date, timeZone?: string): { minutes: number; seconds:
|
|
|
470
470
|
export function isInWindow(now: Date, notBefore?: string | null, notAfter?: string | null, timeZone?: string): boolean {
|
|
471
471
|
if (validateLaunchWindow(notBefore, notAfter) !== null) return true; // невалидное окно не должно блокировать
|
|
472
472
|
if (!notBefore?.trim() && !notAfter?.trim()) return true;
|
|
473
|
-
const start = dailyTimeToMinutes(notBefore
|
|
474
|
-
const end = dailyTimeToMinutes(notAfter
|
|
473
|
+
const start = dailyTimeToMinutes(notBefore!);
|
|
474
|
+
const end = dailyTimeToMinutes(notAfter!);
|
|
475
475
|
const { minutes } = wallMinutes(now, timeZone);
|
|
476
476
|
if (start < end) return minutes >= start && minutes < end;
|
|
477
477
|
return minutes >= start || minutes < end; // через полночь
|
|
@@ -482,7 +482,7 @@ export function windowDelayMs(now: Date, notBefore?: string | null, notAfter?: s
|
|
|
482
482
|
if (validateLaunchWindow(notBefore, notAfter) !== null) return 0;
|
|
483
483
|
if (!notBefore?.trim() && !notAfter?.trim()) return 0;
|
|
484
484
|
if (isInWindow(now, notBefore, notAfter, timeZone)) return 0;
|
|
485
|
-
const start = dailyTimeToMinutes(notBefore
|
|
485
|
+
const start = dailyTimeToMinutes(notBefore!);
|
|
486
486
|
const { minutes, seconds, ms } = wallMinutes(now, timeZone);
|
|
487
487
|
const deltaMin = (start - minutes + 1440) % 1440;
|
|
488
488
|
const deltaSec = deltaMin * 60 - seconds;
|
|
@@ -499,7 +499,7 @@ export function normalizeActiveDays(days?: number[] | null): number[] | undefine
|
|
|
499
499
|
...new Set(
|
|
500
500
|
days
|
|
501
501
|
.map((value) => Math.floor(Number(value)))
|
|
502
|
-
.filter((value) => Number.isInteger(value) && value >= 0 && value <= 6)
|
|
502
|
+
.filter((value) => Number.isInteger(value) && value >= 0 && value <= 6),
|
|
503
503
|
),
|
|
504
504
|
].sort((a, b) => a - b);
|
|
505
505
|
if (unique.length === 0 || unique.length === 7) return undefined;
|
|
@@ -569,7 +569,7 @@ export function activeWindowState(now: Date, options: ActiveWindowOptions = {}):
|
|
|
569
569
|
t("schedule.reason.outsideWindow", {
|
|
570
570
|
notBefore: options.notBefore,
|
|
571
571
|
notAfter: options.notAfter,
|
|
572
|
-
})
|
|
572
|
+
}),
|
|
573
573
|
);
|
|
574
574
|
}
|
|
575
575
|
return {
|
|
@@ -649,7 +649,7 @@ export function buildScheduleGate(
|
|
|
649
649
|
notBefore?: string,
|
|
650
650
|
notAfter?: string,
|
|
651
651
|
days?: number[] | null,
|
|
652
|
-
windowPolicy?: string | null
|
|
652
|
+
windowPolicy?: string | null,
|
|
653
653
|
): ScheduleGateSpec | undefined {
|
|
654
654
|
const tz = (timezone || "").trim() || undefined;
|
|
655
655
|
const poll = needsPollMode(expr, tz);
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import type { RegistryEntry } from "./registry.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Fallback для one-shot задач, когда утилита `at` не установлена.
|
|
6
|
+
*
|
|
7
|
+
* Запускает отвязанный (detached) `/bin/bash`, который спит до `runAt` и
|
|
8
|
+
* затем выполняет команду задачи. Это не полноценная замена `atd`:
|
|
9
|
+
* - процесс не переживает перезагрузку машины;
|
|
10
|
+
* - не переживает ручной kill;
|
|
11
|
+
* - не виден в `atq`.
|
|
12
|
+
* Поэтому fallback используется только как последнее средство и пишет
|
|
13
|
+
* предупреждение в лог. Если `at` доступен — вызывается он.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface DetachedOneShotSpawn {
|
|
17
|
+
once(event: "error", listener: (err: Error) => void): unknown;
|
|
18
|
+
once(event: "spawn", listener: () => void): unknown;
|
|
19
|
+
unref(): unknown;
|
|
20
|
+
pid?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type DetachedOneShotSpawnFn = (
|
|
24
|
+
file: string,
|
|
25
|
+
args: string[],
|
|
26
|
+
options: { detached: boolean; stdio: "ignore" },
|
|
27
|
+
) => DetachedOneShotSpawn;
|
|
28
|
+
|
|
29
|
+
export interface ScheduleAtFallbackDeps {
|
|
30
|
+
spawnFn?: DetachedOneShotSpawnFn;
|
|
31
|
+
now?: () => number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const PID_JOB_PREFIX = "pid:";
|
|
35
|
+
|
|
36
|
+
/** Ошибка `spawn("at")`, означающая, что бинарник не найден. */
|
|
37
|
+
export function isAtMissingError(err: unknown): boolean {
|
|
38
|
+
if (!err || typeof err !== "object") return false;
|
|
39
|
+
const code = (err as { code?: unknown }).code;
|
|
40
|
+
if (code === "ENOENT") return true;
|
|
41
|
+
const message = (err as { message?: unknown }).message;
|
|
42
|
+
return typeof message === "string" && /ENOENT|not found|no such file/i.test(message);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Сколько секунд осталось до `runAt` (0, если момент уже прошёл). */
|
|
46
|
+
export function computeDelaySeconds(runAt: string, nowMs: number): number {
|
|
47
|
+
const target = Date.parse(runAt);
|
|
48
|
+
if (!Number.isFinite(target)) {
|
|
49
|
+
throw new Error(`Некорректное время one-shot: «${runAt}».`);
|
|
50
|
+
}
|
|
51
|
+
return Math.max(0, Math.ceil((target - nowMs) / 1000));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Скрипт для `/bin/bash -c`: подождать и выполнить команду задачи. */
|
|
55
|
+
export function buildDetachedOneShotScript(
|
|
56
|
+
entry: RegistryEntry,
|
|
57
|
+
command: string,
|
|
58
|
+
nowMs: number,
|
|
59
|
+
): string {
|
|
60
|
+
if (!entry.runAt) {
|
|
61
|
+
throw new Error(`Задача "${entry.name}": не задано runAt для one-shot.`);
|
|
62
|
+
}
|
|
63
|
+
const delay = computeDelaySeconds(entry.runAt, nowMs);
|
|
64
|
+
return `sleep ${delay}; ${command}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Является ли сохранённый id задания pid-ом fallback-процесса. */
|
|
68
|
+
export function isPidJobId(jobId: string | undefined): boolean {
|
|
69
|
+
return typeof jobId === "string" && jobId.startsWith(PID_JOB_PREFIX);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function pidFromJobId(jobId: string): number {
|
|
73
|
+
return Number.parseInt(jobId.slice(PID_JOB_PREFIX.length), 10);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Запускает отвязанный one-shot и возвращает `pid:<pid>` для `cancelAt`.
|
|
78
|
+
* Промис резолвится сразу после успешного `spawn`, не дожидаясь выполнения.
|
|
79
|
+
*/
|
|
80
|
+
export async function scheduleAtFallback(
|
|
81
|
+
entry: RegistryEntry,
|
|
82
|
+
command: string,
|
|
83
|
+
deps: ScheduleAtFallbackDeps = {},
|
|
84
|
+
): Promise<string> {
|
|
85
|
+
const spawnFn = deps.spawnFn ?? spawn;
|
|
86
|
+
const now = deps.now ? deps.now() : Date.now();
|
|
87
|
+
const script = buildDetachedOneShotScript(entry, command, now);
|
|
88
|
+
|
|
89
|
+
return new Promise<string>((resolve, reject) => {
|
|
90
|
+
const child = spawnFn("/bin/bash", ["-c", script], {
|
|
91
|
+
detached: true,
|
|
92
|
+
stdio: "ignore",
|
|
93
|
+
});
|
|
94
|
+
child.once("error", reject);
|
|
95
|
+
child.once("spawn", () => {
|
|
96
|
+
child.unref();
|
|
97
|
+
resolve(`${PID_JOB_PREFIX}${child.pid ?? 0}`);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Снимает fallback-процесс. Ошибки (процесс уже завершился) игнорируются. */
|
|
103
|
+
export function cancelAtFallback(jobId: string): boolean {
|
|
104
|
+
if (!isPidJobId(jobId)) return false;
|
|
105
|
+
const pid = pidFromJobId(jobId);
|
|
106
|
+
if (!Number.isFinite(pid) || pid <= 0) return false;
|
|
107
|
+
try {
|
|
108
|
+
process.kill(pid, "SIGTERM");
|
|
109
|
+
return true;
|
|
110
|
+
} catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -24,7 +24,7 @@ export type { RegistryEntry } from "./registry.js";
|
|
|
24
24
|
*/
|
|
25
25
|
export function createSchedulerBackend(
|
|
26
26
|
platform: NodeJS.Platform = process.platform,
|
|
27
|
-
profile?: string
|
|
27
|
+
profile?: string,
|
|
28
28
|
): SchedulerBackend {
|
|
29
29
|
if (platform === "win32") return new WindowsScheduler(profile);
|
|
30
30
|
if (platform === "darwin") return new MacScheduler(profile);
|
|
@@ -38,7 +38,7 @@ export function createSchedulerBackend(
|
|
|
38
38
|
*/
|
|
39
39
|
export function createSchedulerBackendForProfile(
|
|
40
40
|
profile: string,
|
|
41
|
-
platform: NodeJS.Platform = process.platform
|
|
41
|
+
platform: NodeJS.Platform = process.platform,
|
|
42
42
|
): SchedulerBackend {
|
|
43
43
|
return createSchedulerBackend(platform, profile);
|
|
44
44
|
}
|
|
@@ -50,7 +50,7 @@ export function createSchedulerBackendForProfile(
|
|
|
50
50
|
*/
|
|
51
51
|
export async function removeScheduledTasksForProfile(
|
|
52
52
|
profile: string,
|
|
53
|
-
platform: NodeJS.Platform = process.platform
|
|
53
|
+
platform: NodeJS.Platform = process.platform,
|
|
54
54
|
): Promise<number> {
|
|
55
55
|
const scheduler = createSchedulerBackendForProfile(profile, platform);
|
|
56
56
|
const tasks = await scheduler.listTasks();
|