opencode-windows-scheduler 1.5.2 → 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 +107 -2
- package/CROSS_PLATFORM.md +107 -71
- package/LICENSE +21 -21
- package/README.md +74 -26
- package/ROADMAP-STRATEGY.md +11 -4
- package/ROADMAP.md +322 -112
- 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/local-ai.d.ts +52 -0
- package/dist/core/local-ai.d.ts.map +1 -0
- package/dist/core/local-ai.js +119 -0
- 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 -30
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +477 -108
- 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 +40 -0
- package/dist/core/triage-chain.d.ts.map +1 -0
- package/dist/core/triage-chain.js +80 -0
- 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 +23 -0
- package/dist/core/triage-rules.d.ts.map +1 -0
- package/dist/core/triage-rules.js +196 -0
- package/dist/core/triage-shadow.d.ts +91 -0
- package/dist/core/triage-shadow.d.ts.map +1 -0
- package/dist/core/triage-shadow.js +160 -0
- 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.d.ts +76 -0
- package/dist/core/triage.d.ts.map +1 -0
- package/dist/core/triage.js +271 -0
- 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 +75 -10
- package/dist/index.d.ts +66 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +527 -68
- 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 +289 -10
- 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 +401 -5
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +138 -5
- 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 +167 -3
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +322 -3
- 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 +48 -28
- 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 +141 -44
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +17 -0
- package/docs/README.ru.md +22 -16
- 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/docs/spikes/local-model-structured-output.md +81 -0
- package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
- package/docs/spikes/ollama-qwen3-4b.json +163 -0
- package/gui-experimental.cjs +8 -8
- package/locales/en.json +85 -0
- package/locales/ru.json +85 -0
- package/locales/zh.json +780 -0
- package/package.json +31 -7
- package/scripts/bench-local.mjs +321 -0
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/spike-local-structured.mjs +182 -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 +40 -0
- 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/local-ai.ts +173 -0
- 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 +492 -108
- 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 +125 -0
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +238 -0
- package/src/core/triage-shadow.ts +240 -0
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +366 -0
- 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 +551 -14
- package/src/history.ts +7 -3
- package/src/i18n.ts +87 -13
- package/src/index.ts +649 -71
- package/src/integrations.ts +50 -6
- package/src/notifications.ts +468 -5
- package/src/profiles.ts +21 -3
- package/src/rpc.ts +143 -5
- package/src/server.ts +135 -16
- package/src/settings.ts +582 -5
- package/src/task-transfer.ts +10 -3
- package/src/types.ts +24 -5
- package/src/workspaces.ts +22 -0
package/dist/index.js
CHANGED
|
@@ -8,7 +8,7 @@ import { LockManager } from "./core/lock.js";
|
|
|
8
8
|
import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, STALE_LOCK_MAX_AGE_MS, WRAPPER_DIR, sanitizeName, validateTaskName, } from "./types.js";
|
|
9
9
|
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
|
|
10
10
|
import { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
|
|
11
|
-
import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, } from "./core/session.js";
|
|
11
|
+
import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, sessionStatePath, writeSessionStateFile, } from "./core/session.js";
|
|
12
12
|
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
|
|
13
13
|
import { getSchedulerBackend } from "./core/scheduler/index.js";
|
|
14
14
|
import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
|
|
@@ -16,15 +16,23 @@ import { getTaskLogs } from "./core/scheduler/logs.js";
|
|
|
16
16
|
import { writeBashWrapper } from "./core/wrappers/bash.js";
|
|
17
17
|
import { simulatePipeline } from "./core/dry-run.js";
|
|
18
18
|
import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.js";
|
|
19
|
+
import { normalizeWatchPath, validateWatchGlobs } from "./core/watch-paths.js";
|
|
20
|
+
import { createShutdownGate } from "./core/shutdown.js";
|
|
19
21
|
import { SchedulerRpc } from "./rpc.js";
|
|
20
22
|
import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
|
|
21
|
-
import { loadSettings, saveSettings } from "./settings.js";
|
|
22
|
-
import { setLocale, t } from "./i18n.js";
|
|
23
|
+
import { defaultNotifications, loadSettings, saveSettings } from "./settings.js";
|
|
24
|
+
import { resolveLocale, setLocale, t } from "./i18n.js";
|
|
25
|
+
import { DEFAULT_PERMISSION_POLICY, buildOpencodeConfig, resolvePermissions, } from "./core/permissions.js";
|
|
23
26
|
import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
|
|
24
27
|
import { buildAnalytics } from "./core/analytics.js";
|
|
28
|
+
import { generateSelfAnalysisReport } from "./core/self-analysis.js";
|
|
25
29
|
import { getHistory, listRunningRecords } from "./db/history-repo.js";
|
|
26
30
|
import { getAllMetrics } from "./db/metrics-repo.js";
|
|
27
31
|
import { findStuckMatrixClones, maybeSendDigest, notifyStuckMatrix, sendDigestNow, sendTestNotification, } from "./notifications.js";
|
|
32
|
+
import { shadowReport, resetShadowDecisions, } from "./core/triage-shadow.js";
|
|
33
|
+
import { compareTriage } from "./core/triage-compare.js";
|
|
34
|
+
import { applyLocalAiPatch, summarizeLocalAi } from "./core/local-ai.js";
|
|
35
|
+
import { classifyNotification } from "./core/triage.js";
|
|
28
36
|
import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExportJson, parseImportJson, normalizePriority, } from "./task-transfer.js";
|
|
29
37
|
import { FileWatchManager } from "./core/file-watcher.js";
|
|
30
38
|
import { GitTriggerManager } from "./core/git-trigger.js";
|
|
@@ -41,6 +49,10 @@ import { readAuditLog, recordAudit, recordTaskToolBlocks, } from "./core/audit.j
|
|
|
41
49
|
// Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
|
|
42
50
|
const require = createRequire(import.meta.url);
|
|
43
51
|
const resolvedRecorder = require.resolve("./core/record-history.js");
|
|
52
|
+
// Д6: ворота выгрузки. После dispose новые in-process запуски отклоняются,
|
|
53
|
+
// а начатые — получают время завершить запись в БД.
|
|
54
|
+
const shutdownGate = createShutdownGate();
|
|
55
|
+
const SHUTDOWN_WAIT_MS = 15000;
|
|
44
56
|
/**
|
|
45
57
|
* Плагин может загружаться как из dist, так и напрямую из src (tsx/транспиляция).
|
|
46
58
|
* Node не умеет исполнять .ts, поэтому для фоновых задач всегда берём
|
|
@@ -141,7 +153,7 @@ export const scheduleTaskSchema = z.object({
|
|
|
141
153
|
sessionMaxRuns: z
|
|
142
154
|
.number()
|
|
143
155
|
.int()
|
|
144
|
-
.min(
|
|
156
|
+
.min(0)
|
|
145
157
|
.max(10000)
|
|
146
158
|
.optional()
|
|
147
159
|
.describe("Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."),
|
|
@@ -265,11 +277,15 @@ export const scheduleTaskSchema = z.object({
|
|
|
265
277
|
allowedTools: z
|
|
266
278
|
.array(z.string())
|
|
267
279
|
.optional()
|
|
268
|
-
.describe("Role-scoped tool allow-list.
|
|
280
|
+
.describe("Role-scoped tool allow-list, enforced through OPENCODE_CONFIG_CONTENT. A non-empty list also allows actions that the default policy denies (for example shell). An empty array is rejected."),
|
|
269
281
|
deniedTools: z
|
|
270
282
|
.array(z.string())
|
|
271
283
|
.optional()
|
|
272
|
-
.describe("Role-scoped tool deny-list (takes precedence over allowedTools).
|
|
284
|
+
.describe("Role-scoped tool deny-list (takes precedence over allowedTools and over the default policy). Enforced through OPENCODE_CONFIG_CONTENT."),
|
|
285
|
+
legacyShell: z
|
|
286
|
+
.boolean()
|
|
287
|
+
.optional()
|
|
288
|
+
.describe("Transitional flag (release 1.6): under the hybrid policy, re-enable shell for this task. Prefer listing shell in allowedTools. Ignored by secure/legacy policy."),
|
|
273
289
|
runWhenLoggedOff: z
|
|
274
290
|
.boolean()
|
|
275
291
|
.optional()
|
|
@@ -340,7 +356,7 @@ export const updateTaskSchema = z.object({
|
|
|
340
356
|
sessionMaxRuns: z
|
|
341
357
|
.number()
|
|
342
358
|
.int()
|
|
343
|
-
.min(
|
|
359
|
+
.min(0)
|
|
344
360
|
.max(10000)
|
|
345
361
|
.optional()
|
|
346
362
|
.describe("Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."),
|
|
@@ -462,6 +478,10 @@ export const updateTaskSchema = z.object({
|
|
|
462
478
|
.array(z.string())
|
|
463
479
|
.optional()
|
|
464
480
|
.describe("New tool deny-list. Empty array clears it."),
|
|
481
|
+
legacyShell: z
|
|
482
|
+
.boolean()
|
|
483
|
+
.optional()
|
|
484
|
+
.describe("Transitional flag (release 1.6): re-enable shell under the hybrid policy for this task."),
|
|
465
485
|
matrix: matrixSchema
|
|
466
486
|
.nullable()
|
|
467
487
|
.optional()
|
|
@@ -584,6 +604,35 @@ export const getAnalyticsSchema = z.object({
|
|
|
584
604
|
.optional()
|
|
585
605
|
.describe("How many top tasks to include (default 10)."),
|
|
586
606
|
});
|
|
607
|
+
/** self_analysis — система самоанализа: здоровье, аномалии, тренды, рекомендации. */
|
|
608
|
+
export const selfAnalysisSchema = z.object({
|
|
609
|
+
days: z
|
|
610
|
+
.number()
|
|
611
|
+
.int()
|
|
612
|
+
.min(1)
|
|
613
|
+
.max(365)
|
|
614
|
+
.optional()
|
|
615
|
+
.describe("Analysis window in days (default 14)."),
|
|
616
|
+
topLimit: z
|
|
617
|
+
.number()
|
|
618
|
+
.int()
|
|
619
|
+
.min(1)
|
|
620
|
+
.max(50)
|
|
621
|
+
.optional()
|
|
622
|
+
.describe("How many top tasks to include (default 10)."),
|
|
623
|
+
includeAnomalies: z
|
|
624
|
+
.boolean()
|
|
625
|
+
.optional()
|
|
626
|
+
.describe("Include anomaly detection (default true)."),
|
|
627
|
+
includeTrends: z
|
|
628
|
+
.boolean()
|
|
629
|
+
.optional()
|
|
630
|
+
.describe("Include trend analysis (default true)."),
|
|
631
|
+
includeRecommendations: z
|
|
632
|
+
.boolean()
|
|
633
|
+
.optional()
|
|
634
|
+
.describe("Include recommendations (default true)."),
|
|
635
|
+
});
|
|
587
636
|
/** manage_settings — глобальные настройки планировщика. */
|
|
588
637
|
export const manageSettingsSchema = z.object({
|
|
589
638
|
action: z
|
|
@@ -597,9 +646,9 @@ export const manageSettingsSchema = z.object({
|
|
|
597
646
|
.optional()
|
|
598
647
|
.describe("How many task runs may execute at the same time."),
|
|
599
648
|
locale: z
|
|
600
|
-
.enum(["ru", "en"])
|
|
649
|
+
.enum(["auto", "ru", "en", "zh"])
|
|
601
650
|
.optional()
|
|
602
|
-
.describe("Interface language: ru (default) or
|
|
651
|
+
.describe("Interface language: auto (follow OpenCode), ru (default), en or zh. Applies without restart."),
|
|
603
652
|
winterMode: z
|
|
604
653
|
.boolean()
|
|
605
654
|
.optional()
|
|
@@ -607,7 +656,7 @@ export const manageSettingsSchema = z.object({
|
|
|
607
656
|
notifications: z
|
|
608
657
|
.any()
|
|
609
658
|
.optional()
|
|
610
|
-
.describe("Notification settings patch (enabled, onlyOnError, webhook, telegram, native, quietHours, templates, filters, matrix, digest)."),
|
|
659
|
+
.describe("Notification settings patch (enabled, onlyOnError, webhook, telegram, native, quietHours, templates, filters, matrix, digest, dedup)."),
|
|
611
660
|
history: z
|
|
612
661
|
.object({
|
|
613
662
|
retentionDays: z.number().int().min(1).max(3650).optional(),
|
|
@@ -623,6 +672,61 @@ export const manageSettingsSchema = z.object({
|
|
|
623
672
|
.any()
|
|
624
673
|
.optional()
|
|
625
674
|
.describe("Audit log settings patch (enabled, retentionDays, maxRecords)."),
|
|
675
|
+
permissions: z
|
|
676
|
+
.object({
|
|
677
|
+
defaultPolicy: z.enum(["hybrid", "secure", "legacy"]).optional(),
|
|
678
|
+
})
|
|
679
|
+
.optional()
|
|
680
|
+
.describe("Tool permission policy for background tasks: hybrid (default; shell/question denied), secure (read-only), legacy (allow everything, 1.5.x behaviour)."),
|
|
681
|
+
});
|
|
682
|
+
/** manage_local_ai — настройки локального ассистента и триажа (Спринт 30.7). */
|
|
683
|
+
export const manageLocalAiSchema = z.object({
|
|
684
|
+
action: z
|
|
685
|
+
.enum(["get", "update", "test"])
|
|
686
|
+
.describe("get — current triage settings and shadow state; update — merge fields and save; test — one classification request against the configured model."),
|
|
687
|
+
mode: z
|
|
688
|
+
.enum(["off", "rules", "llm", "auto"])
|
|
689
|
+
.optional()
|
|
690
|
+
.describe("off — no triage; rules — built-in rules only; llm — model only; auto — model, then rules (default)."),
|
|
691
|
+
baseUrl: z
|
|
692
|
+
.string()
|
|
693
|
+
.max(500)
|
|
694
|
+
.optional()
|
|
695
|
+
.describe("Ollama or OpenAI-compatible base URL, for example http://127.0.0.1:11434. A URL ending with /v1 switches to the OpenAI protocol."),
|
|
696
|
+
model: z
|
|
697
|
+
.string()
|
|
698
|
+
.max(200)
|
|
699
|
+
.optional()
|
|
700
|
+
.describe("Model id, for example qwen3:4b."),
|
|
701
|
+
timeoutMs: z
|
|
702
|
+
.number()
|
|
703
|
+
.int()
|
|
704
|
+
.min(1000)
|
|
705
|
+
.max(120000)
|
|
706
|
+
.optional()
|
|
707
|
+
.describe("Request timeout in milliseconds (1000..120000)."),
|
|
708
|
+
fallback: z
|
|
709
|
+
.enum(["rules", "notify", "skip"])
|
|
710
|
+
.optional()
|
|
711
|
+
.describe("When the model fails or is unsure: rules - apply rules (fail-open, default); notify - skip the rules step and deliver the notification; skip - legacy alias for notify."),
|
|
712
|
+
confidenceThreshold: z
|
|
713
|
+
.number()
|
|
714
|
+
.min(0)
|
|
715
|
+
.max(1)
|
|
716
|
+
.optional()
|
|
717
|
+
.describe("Minimum model confidence (0..1); below it the fallback applies."),
|
|
718
|
+
shadow: z
|
|
719
|
+
.object({
|
|
720
|
+
enabled: z.boolean().optional().describe("Log decisions without suppressing notifications."),
|
|
721
|
+
days: z.number().int().min(1).max(365).optional().describe("Shadow period length in days."),
|
|
722
|
+
startedAt: z
|
|
723
|
+
.string()
|
|
724
|
+
.nullable()
|
|
725
|
+
.optional()
|
|
726
|
+
.describe("ISO start of the shadow period; null restarts it on the next save."),
|
|
727
|
+
})
|
|
728
|
+
.optional()
|
|
729
|
+
.describe("Shadow mode patch."),
|
|
626
730
|
});
|
|
627
731
|
/** manage_templates — пользовательские шаблоны задач. */
|
|
628
732
|
export const manageTemplatesSchema = z.object({
|
|
@@ -811,7 +915,7 @@ function computeTaskNextRun(def, options = {}) {
|
|
|
811
915
|
}
|
|
812
916
|
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
813
917
|
const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
814
|
-
const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, } = args;
|
|
918
|
+
const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, legacyShell, } = args;
|
|
815
919
|
let effectiveRunAt;
|
|
816
920
|
if ((triggerType ?? "cron") === "once") {
|
|
817
921
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
@@ -838,7 +942,7 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
838
942
|
gitPollSeconds,
|
|
839
943
|
},
|
|
840
944
|
// Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
|
|
841
|
-
runWhenLoggedOff === true);
|
|
945
|
+
runWhenLoggedOff === true, undefined, legacyShell === true);
|
|
842
946
|
}
|
|
843
947
|
catch (err) {
|
|
844
948
|
return {
|
|
@@ -964,7 +1068,7 @@ async function cancelMatrixRun(name) {
|
|
|
964
1068
|
}
|
|
965
1069
|
// Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
|
|
966
1070
|
try {
|
|
967
|
-
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
|
|
1071
|
+
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell);
|
|
968
1072
|
}
|
|
969
1073
|
catch (err) {
|
|
970
1074
|
warnings.push(t("tool.matrix.recreateFailed", {
|
|
@@ -1321,7 +1425,7 @@ async function updateTaskFromInput(input) {
|
|
|
1321
1425
|
}
|
|
1322
1426
|
const sessionMaxRuns = input.sessionMaxRuns !== undefined ? input.sessionMaxRuns : previous.sessionMaxRuns;
|
|
1323
1427
|
if (sessionMaxRuns !== undefined &&
|
|
1324
|
-
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns <
|
|
1428
|
+
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 0)) {
|
|
1325
1429
|
return {
|
|
1326
1430
|
success: false,
|
|
1327
1431
|
message: t("tool.error.sessionMaxRuns", { name }),
|
|
@@ -1378,7 +1482,7 @@ async function updateTaskFromInput(input) {
|
|
|
1378
1482
|
await schedulerCreateTask(name, schedule ?? "", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), clearableString(input.model, previous.model), input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
|
|
1379
1483
|
// Если задача была матрицей — синхронизируем клонов, а не
|
|
1380
1484
|
// пересоздаём их с нуля (Спринт 17).
|
|
1381
|
-
matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused);
|
|
1485
|
+
matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused, input.legacyShell ?? previous.legacyShell);
|
|
1382
1486
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
1383
1487
|
if (matrixWas && !matrixNext) {
|
|
1384
1488
|
await removeMatrixChildrenFromScheduler(name);
|
|
@@ -1386,6 +1490,39 @@ async function updateTaskFromInput(input) {
|
|
|
1386
1490
|
// Пересоздание могло изменить triggerType/watchPath — сразу
|
|
1387
1491
|
// пересобираем набор файловых watcher-ов.
|
|
1388
1492
|
await refreshTriggers();
|
|
1493
|
+
// Спринт 27.5: при смене регистра имени (MyTask -> mytask) обновляем
|
|
1494
|
+
// ссылки в других задачах, иначе DAG и цепочки продолжат указывать на
|
|
1495
|
+
// старое написание.
|
|
1496
|
+
if (previous.name !== name) {
|
|
1497
|
+
const previousLower = previous.name.toLowerCase();
|
|
1498
|
+
for (const task of listTaskDefinitions()) {
|
|
1499
|
+
if (task.name.toLowerCase() === name.toLowerCase())
|
|
1500
|
+
continue;
|
|
1501
|
+
let changed = false;
|
|
1502
|
+
const renameRef = (value) => {
|
|
1503
|
+
if (value.toLowerCase() === previousLower) {
|
|
1504
|
+
changed = true;
|
|
1505
|
+
return name;
|
|
1506
|
+
}
|
|
1507
|
+
return value;
|
|
1508
|
+
};
|
|
1509
|
+
const dependsOn = task.dependsOn?.map(renameRef);
|
|
1510
|
+
const nextTaskOnSuccess = task.nextTaskOnSuccess
|
|
1511
|
+
? renameRef(task.nextTaskOnSuccess)
|
|
1512
|
+
: task.nextTaskOnSuccess;
|
|
1513
|
+
const nextTaskOnError = task.nextTaskOnError
|
|
1514
|
+
? renameRef(task.nextTaskOnError)
|
|
1515
|
+
: task.nextTaskOnError;
|
|
1516
|
+
if (!changed)
|
|
1517
|
+
continue;
|
|
1518
|
+
await saveTask({
|
|
1519
|
+
...task,
|
|
1520
|
+
...(dependsOn ? { dependsOn } : {}),
|
|
1521
|
+
nextTaskOnSuccess,
|
|
1522
|
+
nextTaskOnError,
|
|
1523
|
+
});
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1389
1526
|
// Спринт 27.5.2: после пересоздания задачи сообщаем ближайший запуск,
|
|
1390
1527
|
// рассчитанный из нового определения, не дожидаясь ОС.
|
|
1391
1528
|
const updated = getTask(name);
|
|
@@ -1591,6 +1728,7 @@ const resumeTaskExecute = wrapExecute(async (args) => {
|
|
|
1591
1728
|
return { content: JSON.stringify(result) };
|
|
1592
1729
|
});
|
|
1593
1730
|
/** Периодичность проверки автопродолжения задач (Спринт 19). */
|
|
1731
|
+
const POSIX_MAX_PROMPT_BYTES = 131072; // 128 KiB: MAX_ARG_STRLEN на одном аргументе в Linux; запас под обёртку.
|
|
1594
1732
|
const PAUSED_UNTIL_CHECK_MS = 5 * 60 * 1000;
|
|
1595
1733
|
/** Период проверки дайджеста и зависших матриц (Спринт 20). */
|
|
1596
1734
|
const NOTIFICATION_CHECK_MS = 60 * 1000;
|
|
@@ -1674,11 +1812,7 @@ async function checkStuckMatrices() {
|
|
|
1674
1812
|
/** get_history — история запусков с фильтрами по задаче и статусу. */
|
|
1675
1813
|
const getHistoryExecute = wrapExecute(async (args) => {
|
|
1676
1814
|
const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
|
|
1677
|
-
const
|
|
1678
|
-
const records = (await loadHistory())
|
|
1679
|
-
.filter((record) => !taskFilter || record.taskName.toLowerCase() === taskFilter)
|
|
1680
|
-
.filter((record) => !args.status || record.status === args.status)
|
|
1681
|
-
.slice(0, limit);
|
|
1815
|
+
const records = await loadHistory(args.taskName, limit, args.status);
|
|
1682
1816
|
return {
|
|
1683
1817
|
content: JSON.stringify({
|
|
1684
1818
|
success: true,
|
|
@@ -1965,6 +2099,38 @@ const getAnalyticsExecute = wrapExecute(async (args) => {
|
|
|
1965
2099
|
});
|
|
1966
2100
|
return { content: JSON.stringify({ success: true, report }) };
|
|
1967
2101
|
});
|
|
2102
|
+
/** self_analysis — система самоанализа: здоровье, аномалии, тренды, рекомендации. */
|
|
2103
|
+
const selfAnalysisExecute = wrapExecute(async (args) => {
|
|
2104
|
+
const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
|
|
2105
|
+
const records = getHistory(null, 20000);
|
|
2106
|
+
const definitions = await loadTaskDefinitions();
|
|
2107
|
+
const report = generateSelfAnalysisReport(records, {
|
|
2108
|
+
days: windowDays,
|
|
2109
|
+
topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
|
|
2110
|
+
tasks: definitions.map((definition) => ({
|
|
2111
|
+
name: definition.name,
|
|
2112
|
+
matrixParentId: definition.matrixParentId,
|
|
2113
|
+
})),
|
|
2114
|
+
});
|
|
2115
|
+
// Фильтруем секции если нужно
|
|
2116
|
+
const result = {
|
|
2117
|
+
generatedAt: report.generatedAt,
|
|
2118
|
+
windowDays: report.windowDays,
|
|
2119
|
+
health: report.health,
|
|
2120
|
+
summary: report.summary,
|
|
2121
|
+
sources: report.sources,
|
|
2122
|
+
};
|
|
2123
|
+
if (args.includeAnomalies !== false) {
|
|
2124
|
+
result.anomalies = report.anomalies;
|
|
2125
|
+
}
|
|
2126
|
+
if (args.includeTrends !== false) {
|
|
2127
|
+
result.trends = report.trends;
|
|
2128
|
+
}
|
|
2129
|
+
if (args.includeRecommendations !== false) {
|
|
2130
|
+
result.recommendations = report.recommendations;
|
|
2131
|
+
}
|
|
2132
|
+
return { content: JSON.stringify({ success: true, report: result }) };
|
|
2133
|
+
});
|
|
1968
2134
|
/** manage_settings — чтение и изменение глобальных настроек. */
|
|
1969
2135
|
const manageSettingsExecute = wrapExecute(async (args) => {
|
|
1970
2136
|
const current = await loadSettings();
|
|
@@ -1977,7 +2143,8 @@ const manageSettingsExecute = wrapExecute(async (args) => {
|
|
|
1977
2143
|
args.notifications === undefined &&
|
|
1978
2144
|
args.history === undefined &&
|
|
1979
2145
|
args.integrations === undefined &&
|
|
1980
|
-
args.audit === undefined
|
|
2146
|
+
args.audit === undefined &&
|
|
2147
|
+
args.permissions === undefined) {
|
|
1981
2148
|
return {
|
|
1982
2149
|
content: JSON.stringify({
|
|
1983
2150
|
success: false,
|
|
@@ -1994,11 +2161,101 @@ const manageSettingsExecute = wrapExecute(async (args) => {
|
|
|
1994
2161
|
history: args.history,
|
|
1995
2162
|
integrations: args.integrations,
|
|
1996
2163
|
audit: args.audit,
|
|
2164
|
+
permissions: args.permissions,
|
|
1997
2165
|
});
|
|
1998
2166
|
// Локаль процесса меняется сразу — перезапуск плагина не нужен.
|
|
1999
|
-
setLocale(settings.locale);
|
|
2167
|
+
setLocale(resolveLocale(settings.locale, settings.uiLocale));
|
|
2000
2168
|
return { content: JSON.stringify({ success: true, settings }) };
|
|
2001
2169
|
});
|
|
2170
|
+
/** Настройки триажа: сохранённые или дефолт для незаполненного конфига. */
|
|
2171
|
+
function triageOrDefault(settings) {
|
|
2172
|
+
const saved = settings.notifications.triage;
|
|
2173
|
+
if (saved)
|
|
2174
|
+
return saved;
|
|
2175
|
+
const fallback = defaultNotifications().triage;
|
|
2176
|
+
return (fallback ?? {
|
|
2177
|
+
mode: "off",
|
|
2178
|
+
baseUrl: "http://127.0.0.1:11434",
|
|
2179
|
+
model: "",
|
|
2180
|
+
timeoutMs: 60000,
|
|
2181
|
+
fallback: "rules",
|
|
2182
|
+
confidenceThreshold: 0.6,
|
|
2183
|
+
});
|
|
2184
|
+
}
|
|
2185
|
+
/** Синтетическое уведомление для проверки связи с моделью. */
|
|
2186
|
+
const LOCAL_AI_SELF_TEST = {
|
|
2187
|
+
taskName: "scheduler-self-test",
|
|
2188
|
+
status: "error",
|
|
2189
|
+
error: "Quality Gate failed: 2 tests broke the build",
|
|
2190
|
+
durationMs: 12000,
|
|
2191
|
+
};
|
|
2192
|
+
/** Один классификационный запрос — общий путь для инструмента и GUI. */
|
|
2193
|
+
export async function runLocalAiTest(patch = {}) {
|
|
2194
|
+
const settings = await loadSettings();
|
|
2195
|
+
const { settings: candidate } = applyLocalAiPatch(triageOrDefault(settings), patch);
|
|
2196
|
+
const result = await classifyNotification(LOCAL_AI_SELF_TEST, candidate, { retries: 0 });
|
|
2197
|
+
return {
|
|
2198
|
+
success: result.ok,
|
|
2199
|
+
localAi: summarizeLocalAi(candidate),
|
|
2200
|
+
result: {
|
|
2201
|
+
ok: result.ok,
|
|
2202
|
+
failure: result.failure ?? null,
|
|
2203
|
+
error: result.error ?? null,
|
|
2204
|
+
latencyMs: result.latencyMs,
|
|
2205
|
+
attempts: result.attempts,
|
|
2206
|
+
model: result.model,
|
|
2207
|
+
protocol: result.protocol,
|
|
2208
|
+
verdict: result.verdict ?? null,
|
|
2209
|
+
},
|
|
2210
|
+
};
|
|
2211
|
+
}
|
|
2212
|
+
/** manage_local_ai — настройки триажа и проверка связи с моделью. */
|
|
2213
|
+
const manageLocalAiExecute = wrapExecute(async (args) => {
|
|
2214
|
+
const settings = await loadSettings();
|
|
2215
|
+
const current = triageOrDefault(settings);
|
|
2216
|
+
if (args.action === "get") {
|
|
2217
|
+
return {
|
|
2218
|
+
content: JSON.stringify({ success: true, localAi: summarizeLocalAi(current) }),
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
const patch = {
|
|
2222
|
+
mode: args.mode,
|
|
2223
|
+
baseUrl: args.baseUrl,
|
|
2224
|
+
model: args.model,
|
|
2225
|
+
timeoutMs: args.timeoutMs,
|
|
2226
|
+
fallback: args.fallback,
|
|
2227
|
+
confidenceThreshold: args.confidenceThreshold,
|
|
2228
|
+
shadow: args.shadow,
|
|
2229
|
+
};
|
|
2230
|
+
if (args.action === "test") {
|
|
2231
|
+
// Проверка не меняет конфиг: патч применяется только в памяти.
|
|
2232
|
+
return { content: JSON.stringify(await runLocalAiTest(patch)) };
|
|
2233
|
+
}
|
|
2234
|
+
if (!Object.values(patch).some((value) => value !== undefined)) {
|
|
2235
|
+
return {
|
|
2236
|
+
content: JSON.stringify({
|
|
2237
|
+
success: false,
|
|
2238
|
+
error: t("tool.localAi.updateFields"),
|
|
2239
|
+
localAi: summarizeLocalAi(current),
|
|
2240
|
+
}),
|
|
2241
|
+
};
|
|
2242
|
+
}
|
|
2243
|
+
const { settings: merged, changed } = applyLocalAiPatch(current, patch);
|
|
2244
|
+
const saved = await saveSettings({
|
|
2245
|
+
notifications: { ...settings.notifications, triage: merged },
|
|
2246
|
+
});
|
|
2247
|
+
const localAi = summarizeLocalAi(triageOrDefault(saved));
|
|
2248
|
+
return {
|
|
2249
|
+
content: JSON.stringify({
|
|
2250
|
+
success: true,
|
|
2251
|
+
changed,
|
|
2252
|
+
message: changed.length > 0
|
|
2253
|
+
? t("tool.localAi.updated", { fields: changed.join(", ") })
|
|
2254
|
+
: t("tool.localAi.unchanged"),
|
|
2255
|
+
localAi,
|
|
2256
|
+
}),
|
|
2257
|
+
};
|
|
2258
|
+
});
|
|
2002
2259
|
/** manage_templates — список, сохранение и удаление шаблонов задач. */
|
|
2003
2260
|
const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
2004
2261
|
if (args.action === "list") {
|
|
@@ -2085,7 +2342,7 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
2085
2342
|
}),
|
|
2086
2343
|
};
|
|
2087
2344
|
}
|
|
2088
|
-
const removed = deleteProfile(name);
|
|
2345
|
+
const removed = await deleteProfile(name);
|
|
2089
2346
|
return {
|
|
2090
2347
|
content: JSON.stringify({
|
|
2091
2348
|
success: removed,
|
|
@@ -2466,7 +2723,8 @@ export default Plugin.define({
|
|
|
2466
2723
|
// Спринт 28: язык интерфейса берём из настроек. Ошибка чтения не должна
|
|
2467
2724
|
// мешать старту — в этом случае остаётся локаль по умолчанию (ru).
|
|
2468
2725
|
try {
|
|
2469
|
-
|
|
2726
|
+
const initialSettings = await loadSettings();
|
|
2727
|
+
setLocale(resolveLocale(initialSettings.locale, initialSettings.uiLocale));
|
|
2470
2728
|
}
|
|
2471
2729
|
catch {
|
|
2472
2730
|
// Локаль по умолчанию уже активна.
|
|
@@ -2716,6 +2974,14 @@ export default Plugin.define({
|
|
|
2716
2974
|
options: { codemode: true },
|
|
2717
2975
|
execute: getAnalyticsExecute,
|
|
2718
2976
|
});
|
|
2977
|
+
editor.add({
|
|
2978
|
+
name: "self_analysis",
|
|
2979
|
+
input: selfAnalysisSchema,
|
|
2980
|
+
description: "Generates a self-analysis report: system health score, anomaly detection, trend analysis and optimization recommendations. " +
|
|
2981
|
+
"Helps identify performance issues, cost spikes and reliability problems.",
|
|
2982
|
+
options: { codemode: true },
|
|
2983
|
+
execute: selfAnalysisExecute,
|
|
2984
|
+
});
|
|
2719
2985
|
editor.add({
|
|
2720
2986
|
name: "manage_settings",
|
|
2721
2987
|
input: manageSettingsSchema,
|
|
@@ -2725,6 +2991,17 @@ export default Plugin.define({
|
|
|
2725
2991
|
? { action: "settings.update", targetType: "settings", target: "global" }
|
|
2726
2992
|
: null, manageSettingsExecute),
|
|
2727
2993
|
});
|
|
2994
|
+
editor.add({
|
|
2995
|
+
name: "manage_local_ai",
|
|
2996
|
+
input: manageLocalAiSchema,
|
|
2997
|
+
description: "Reads, updates or tests the local assistant for notification triage: mode (off, rules, llm, auto), Ollama/OpenAI baseUrl, model, timeout, fallback, confidence threshold and shadow mode. " +
|
|
2998
|
+
"action=test sends one synthetic notification to the model and reports latency, protocol and verdict without saving anything. " +
|
|
2999
|
+
"Without a model the scheduler keeps working through rules: notifications are never blocked by a missing model.",
|
|
3000
|
+
options: { codemode: true },
|
|
3001
|
+
execute: withAudit("manage_local_ai", (args) => args.action === "update"
|
|
3002
|
+
? { action: "localAi.update", targetType: "settings", target: "triage" }
|
|
3003
|
+
: null, manageLocalAiExecute),
|
|
3004
|
+
});
|
|
2728
3005
|
editor.add({
|
|
2729
3006
|
name: "manage_templates",
|
|
2730
3007
|
input: manageTemplatesSchema,
|
|
@@ -2848,7 +3125,7 @@ export default Plugin.define({
|
|
|
2848
3125
|
},
|
|
2849
3126
|
create_task: async (input) => {
|
|
2850
3127
|
console.log("[windows-scheduler] create_task input:", input);
|
|
2851
|
-
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, } = input;
|
|
3128
|
+
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, legacyShell, } = input;
|
|
2852
3129
|
let effectiveRunAt;
|
|
2853
3130
|
if (triggerType === "once") {
|
|
2854
3131
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
@@ -2866,12 +3143,12 @@ export default Plugin.define({
|
|
|
2866
3143
|
effectiveSession = normalizedSession;
|
|
2867
3144
|
}
|
|
2868
3145
|
if (sessionMaxRuns !== undefined &&
|
|
2869
|
-
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns <
|
|
3146
|
+
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 0)) {
|
|
2870
3147
|
return { success: false, message: t("tool.error.sessionMaxRuns", { name }) };
|
|
2871
3148
|
}
|
|
2872
3149
|
const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
|
|
2873
3150
|
try {
|
|
2874
|
-
await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true);
|
|
3151
|
+
await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true, undefined, legacyShell === true);
|
|
2875
3152
|
const nextRun = computeTaskNextRun({
|
|
2876
3153
|
schedule: schedule ?? "",
|
|
2877
3154
|
triggerType: triggerType ?? "cron",
|
|
@@ -3056,10 +3333,8 @@ export default Plugin.define({
|
|
|
3056
3333
|
const filter = taskName?.trim().toLowerCase();
|
|
3057
3334
|
const statusFilter = status?.trim().toLowerCase();
|
|
3058
3335
|
const max = Math.max(1, Math.min(Math.floor(limit ?? 20), 200));
|
|
3059
|
-
const records =
|
|
3060
|
-
|
|
3061
|
-
.filter((record) => !statusFilter || String(record.status).toLowerCase() === statusFilter);
|
|
3062
|
-
return { records: records.slice(0, max) };
|
|
3336
|
+
const records = await loadHistory(filter, max, statusFilter);
|
|
3337
|
+
return { records };
|
|
3063
3338
|
},
|
|
3064
3339
|
get_metrics: async () => {
|
|
3065
3340
|
return await loadMetrics();
|
|
@@ -3128,6 +3403,47 @@ export default Plugin.define({
|
|
|
3128
3403
|
};
|
|
3129
3404
|
}
|
|
3130
3405
|
},
|
|
3406
|
+
self_analysis: async (input) => {
|
|
3407
|
+
const { days, topLimit, includeAnomalies, includeTrends, includeRecommendations } = input;
|
|
3408
|
+
try {
|
|
3409
|
+
const windowDays = Math.min(365, Math.max(1, Math.floor(Number(days) || 14)));
|
|
3410
|
+
const records = getHistory(null, 20000);
|
|
3411
|
+
const definitions = await loadTaskDefinitions();
|
|
3412
|
+
const report = generateSelfAnalysisReport(records, {
|
|
3413
|
+
days: windowDays,
|
|
3414
|
+
topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
|
|
3415
|
+
tasks: definitions.map((definition) => ({
|
|
3416
|
+
name: definition.name,
|
|
3417
|
+
matrixParentId: definition.matrixParentId,
|
|
3418
|
+
})),
|
|
3419
|
+
});
|
|
3420
|
+
// Фильтруем секции если нужно
|
|
3421
|
+
const result = {
|
|
3422
|
+
generatedAt: report.generatedAt,
|
|
3423
|
+
windowDays: report.windowDays,
|
|
3424
|
+
health: report.health,
|
|
3425
|
+
summary: report.summary,
|
|
3426
|
+
sources: report.sources,
|
|
3427
|
+
};
|
|
3428
|
+
if (includeAnomalies !== false) {
|
|
3429
|
+
result.anomalies = report.anomalies;
|
|
3430
|
+
}
|
|
3431
|
+
if (includeTrends !== false) {
|
|
3432
|
+
result.trends = report.trends;
|
|
3433
|
+
}
|
|
3434
|
+
if (includeRecommendations !== false) {
|
|
3435
|
+
result.recommendations = report.recommendations;
|
|
3436
|
+
}
|
|
3437
|
+
return { success: true, report: result };
|
|
3438
|
+
}
|
|
3439
|
+
catch (err) {
|
|
3440
|
+
return {
|
|
3441
|
+
success: false,
|
|
3442
|
+
report: null,
|
|
3443
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3444
|
+
};
|
|
3445
|
+
}
|
|
3446
|
+
},
|
|
3131
3447
|
get_dashboard_port: async () => {
|
|
3132
3448
|
return { port: getDashboardPort() };
|
|
3133
3449
|
},
|
|
@@ -3343,7 +3659,7 @@ export default Plugin.define({
|
|
|
3343
3659
|
delete_profile: async (input) => {
|
|
3344
3660
|
const { name } = input;
|
|
3345
3661
|
try {
|
|
3346
|
-
const removed = deleteProfile(name);
|
|
3662
|
+
const removed = await deleteProfile(name);
|
|
3347
3663
|
return {
|
|
3348
3664
|
success: removed,
|
|
3349
3665
|
message: removed
|
|
@@ -3359,46 +3675,54 @@ export default Plugin.define({
|
|
|
3359
3675
|
return await loadSettings();
|
|
3360
3676
|
},
|
|
3361
3677
|
save_settings: async (input) => {
|
|
3362
|
-
const { maxConcurrent, locale, winterMode, notifications, history, integrations, audit } = input;
|
|
3678
|
+
const { maxConcurrent, locale, uiLocale, winterMode, notifications, history, integrations, audit, permissions } = input;
|
|
3363
3679
|
const current = await loadSettings();
|
|
3364
3680
|
if (maxConcurrent === undefined &&
|
|
3365
3681
|
locale === undefined &&
|
|
3682
|
+
uiLocale === undefined &&
|
|
3366
3683
|
winterMode === undefined &&
|
|
3367
3684
|
notifications === undefined &&
|
|
3368
3685
|
history === undefined &&
|
|
3369
3686
|
integrations === undefined &&
|
|
3370
|
-
audit === undefined
|
|
3687
|
+
audit === undefined &&
|
|
3688
|
+
permissions === undefined) {
|
|
3371
3689
|
return {
|
|
3372
3690
|
success: false,
|
|
3373
3691
|
maxConcurrent: current.maxConcurrent,
|
|
3374
3692
|
locale: current.locale,
|
|
3693
|
+
uiLocale: current.uiLocale,
|
|
3375
3694
|
winterMode: current.winterMode,
|
|
3376
3695
|
notifications: current.notifications,
|
|
3377
3696
|
history: current.history,
|
|
3378
3697
|
integrations: current.integrations,
|
|
3379
3698
|
audit: current.audit,
|
|
3699
|
+
permissions: current.permissions,
|
|
3380
3700
|
};
|
|
3381
3701
|
}
|
|
3382
3702
|
const settings = await saveSettings({
|
|
3383
3703
|
maxConcurrent,
|
|
3384
3704
|
locale,
|
|
3705
|
+
uiLocale,
|
|
3385
3706
|
winterMode,
|
|
3386
3707
|
notifications,
|
|
3387
3708
|
history,
|
|
3388
3709
|
integrations,
|
|
3389
3710
|
audit,
|
|
3711
|
+
permissions,
|
|
3390
3712
|
});
|
|
3391
3713
|
// Локаль процесса меняется сразу — перезапуск не нужен.
|
|
3392
|
-
setLocale(settings.locale);
|
|
3714
|
+
setLocale(resolveLocale(settings.locale, settings.uiLocale));
|
|
3393
3715
|
return {
|
|
3394
3716
|
success: true,
|
|
3395
3717
|
maxConcurrent: settings.maxConcurrent,
|
|
3396
3718
|
locale: settings.locale,
|
|
3719
|
+
uiLocale: settings.uiLocale,
|
|
3397
3720
|
winterMode: settings.winterMode,
|
|
3398
3721
|
notifications: settings.notifications,
|
|
3399
3722
|
history: settings.history,
|
|
3400
3723
|
integrations: settings.integrations,
|
|
3401
3724
|
audit: settings.audit,
|
|
3725
|
+
permissions: settings.permissions,
|
|
3402
3726
|
};
|
|
3403
3727
|
},
|
|
3404
3728
|
test_notification: async () => {
|
|
@@ -3408,6 +3732,57 @@ export default Plugin.define({
|
|
|
3408
3732
|
// Ручная отправка не сдвигает плановое расписание дайджеста.
|
|
3409
3733
|
return await sendDigestNow({ updateLastSentAt: false });
|
|
3410
3734
|
},
|
|
3735
|
+
// --- Спринт 30.6: shadow-режим триажа ---------------------------------
|
|
3736
|
+
get_shadow_report: async () => {
|
|
3737
|
+
const settings = await loadSettings();
|
|
3738
|
+
const shadow = shadowReport(settings.notifications.triage?.shadow);
|
|
3739
|
+
return {
|
|
3740
|
+
success: true,
|
|
3741
|
+
active: shadow.active,
|
|
3742
|
+
startedAt: shadow.startedAt,
|
|
3743
|
+
days: shadow.days,
|
|
3744
|
+
total: shadow.total,
|
|
3745
|
+
skips: shadow.skips,
|
|
3746
|
+
wouldSuppress: shadow.wouldSuppress,
|
|
3747
|
+
bySource: shadow.bySource,
|
|
3748
|
+
// 31.8: persistent decisions from audit_log (action = triage.decision).
|
|
3749
|
+
persisted: true,
|
|
3750
|
+
truncated: shadow.truncated,
|
|
3751
|
+
decisions: shadow.decisions.slice(0, 50),
|
|
3752
|
+
};
|
|
3753
|
+
},
|
|
3754
|
+
reset_shadow_report: async () => {
|
|
3755
|
+
resetShadowDecisions();
|
|
3756
|
+
return { success: true };
|
|
3757
|
+
},
|
|
3758
|
+
test_local_ai: async (input) => {
|
|
3759
|
+
// Проверка связи: патч применяется только в памяти, конфиг не меняется.
|
|
3760
|
+
const patch = (input ?? {});
|
|
3761
|
+
return await runLocalAiTest({
|
|
3762
|
+
mode: patch.mode,
|
|
3763
|
+
baseUrl: patch.baseUrl,
|
|
3764
|
+
model: patch.model,
|
|
3765
|
+
timeoutMs: patch.timeoutMs,
|
|
3766
|
+
fallback: patch.fallback,
|
|
3767
|
+
confidenceThreshold: patch.confidenceThreshold,
|
|
3768
|
+
});
|
|
3769
|
+
},
|
|
3770
|
+
// --- Спринт 31.5: сравнение триажа «до/после» --------------------------
|
|
3771
|
+
compare_triage: async (input) => {
|
|
3772
|
+
const args = (input ?? {});
|
|
3773
|
+
const triageInput = {
|
|
3774
|
+
taskName: String(args.taskName ?? "task"),
|
|
3775
|
+
status: String(args.status ?? "success"),
|
|
3776
|
+
...(args.error ? { error: args.error } : {}),
|
|
3777
|
+
...(typeof args.durationMs === "number" ? { durationMs: args.durationMs } : {}),
|
|
3778
|
+
...(typeof args.tokens === "number" ? { tokens: args.tokens } : {}),
|
|
3779
|
+
...(typeof args.costUsd === "number" ? { costUsd: args.costUsd } : {}),
|
|
3780
|
+
};
|
|
3781
|
+
const before = args.before ?? undefined;
|
|
3782
|
+
const after = args.after ?? undefined;
|
|
3783
|
+
const result = await compareTriage(triageInput, before, after, args.dedupCount ?? 1);
|
|
3784
|
+
return { success: true, result };
|
|
3785
|
+
},
|
|
3411
3786
|
// --- Спринт 26: секреты и аудит -------------------------------------
|
|
3412
3787
|
list_secrets: async () => {
|
|
3413
3788
|
return { success: true, secrets: listSecrets() };
|
|
@@ -3566,7 +3941,7 @@ export default Plugin.define({
|
|
|
3566
3941
|
gitPaths: def.gitPaths,
|
|
3567
3942
|
gitIgnore: def.gitIgnore,
|
|
3568
3943
|
gitPollSeconds: def.gitPollSeconds,
|
|
3569
|
-
}, def.runWhenLoggedOff === true, def.paused === true);
|
|
3944
|
+
}, def.runWhenLoggedOff === true, def.paused === true, def.legacyShell === true);
|
|
3570
3945
|
await saveTaskDefinition(def);
|
|
3571
3946
|
imported.push(def.name);
|
|
3572
3947
|
}
|
|
@@ -3606,7 +3981,8 @@ export default Plugin.define({
|
|
|
3606
3981
|
if (dashboard) {
|
|
3607
3982
|
console.log(`[windows-scheduler] Открыть дашборд в браузере: http://localhost:${dashboard.port}`);
|
|
3608
3983
|
}
|
|
3609
|
-
return () => {
|
|
3984
|
+
return async () => {
|
|
3985
|
+
shutdownGate.begin();
|
|
3610
3986
|
clearInterval(pausedUntilTimer);
|
|
3611
3987
|
clearInterval(notificationTimer);
|
|
3612
3988
|
rpcRegistration.dispose();
|
|
@@ -3614,9 +3990,15 @@ export default Plugin.define({
|
|
|
3614
3990
|
void skillRegistration?.dispose();
|
|
3615
3991
|
if (fileWatcherManager)
|
|
3616
3992
|
void fileWatcherManager.stop();
|
|
3617
|
-
//
|
|
3618
|
-
//
|
|
3619
|
-
|
|
3993
|
+
// Сначала перестаём принимать новые запросы, затем ждём уже начатые
|
|
3994
|
+
// in-process операции, чтобы не закрыть SQLite под активной записью.
|
|
3995
|
+
await closeDashboardServer();
|
|
3996
|
+
const wait = await shutdownGate.waitForIdle(SHUTDOWN_WAIT_MS);
|
|
3997
|
+
if (wait.timedOut) {
|
|
3998
|
+
console.warn(`[windows-scheduler] Выгрузка: ${wait.remaining} запуск(ов) не завершились за ${SHUTDOWN_WAIT_MS} мс — закрываем БД.`);
|
|
3999
|
+
}
|
|
4000
|
+
// Чекпойнт WAL выполняется в closeDb.
|
|
4001
|
+
closeDb();
|
|
3620
4002
|
};
|
|
3621
4003
|
},
|
|
3622
4004
|
});
|
|
@@ -3694,7 +4076,12 @@ runWhenLoggedOff,
|
|
|
3694
4076
|
* Спринт 27.5.8: пересоздать задачу сразу отключённой (пауза переживает
|
|
3695
4077
|
* update). Для матрицы пауза применяется к клонам.
|
|
3696
4078
|
*/
|
|
3697
|
-
paused
|
|
4079
|
+
paused,
|
|
4080
|
+
/**
|
|
4081
|
+
* Спринт 32 / релиз 1.6: переходный флаг для гибридной политики.
|
|
4082
|
+
* true возвращает shell задаче, созданной до обновления поведения.
|
|
4083
|
+
*/
|
|
4084
|
+
legacyShell) {
|
|
3698
4085
|
// Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
|
|
3699
4086
|
// в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
|
|
3700
4087
|
// schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
|
|
@@ -3704,6 +4091,22 @@ paused) {
|
|
|
3704
4091
|
throw new Error(nameError);
|
|
3705
4092
|
}
|
|
3706
4093
|
name = normalizedName;
|
|
4094
|
+
// Обе платформы передают промпт через argv. Windows (CreateProcess) даёт
|
|
4095
|
+
// ~32767 символов на командную строку, POSIX — MAX_ARG_STRLEN (128 КиБ на
|
|
4096
|
+
// один аргумент в Linux; macOS ограничивает суммарный ARG_MAX). Проверяем до
|
|
4097
|
+
// записи файлов, чтобы не оставить полусозданную задачу и дать понятную
|
|
4098
|
+
// ошибку вместо сбоя schtasks/cron.
|
|
4099
|
+
if (process.platform === "win32") {
|
|
4100
|
+
if (prompt.length > 30000) {
|
|
4101
|
+
throw new Error(`Промпт задачи "${normalizedName}" слишком длинный для командной строки Windows: ${prompt.length} символов (максимум 30000). Сократите промпт или вынесите инструкции в файл.`);
|
|
4102
|
+
}
|
|
4103
|
+
}
|
|
4104
|
+
else {
|
|
4105
|
+
const promptBytes = Buffer.byteLength(prompt, "utf8");
|
|
4106
|
+
if (promptBytes > POSIX_MAX_PROMPT_BYTES) {
|
|
4107
|
+
throw new Error(`Промпт задачи "${normalizedName}" слишком длинный для командной строки POSIX: ${promptBytes} байт (максимум ${POSIX_MAX_PROMPT_BYTES}). Сократите промпт или вынесите инструкции в файл.`);
|
|
4108
|
+
}
|
|
4109
|
+
}
|
|
3707
4110
|
// Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
|
|
3708
4111
|
// удалять их при сбое нельзя — в БД остаётся прежнее определение.
|
|
3709
4112
|
const definitionExisted = Boolean(getTask(normalizedName));
|
|
@@ -3796,6 +4199,26 @@ paused) {
|
|
|
3796
4199
|
}
|
|
3797
4200
|
const normalizedAllowedTools = normalizeToolList(allowedTools);
|
|
3798
4201
|
const normalizedDeniedTools = normalizeToolList(deniedTools);
|
|
4202
|
+
// Спринт 32 / релиз 1.6: единая политика прав. Вычисляем здесь, чтобы
|
|
4203
|
+
// PowerShell- и bash-обёртки получили одинаковый OPENCODE_CONFIG_CONTENT.
|
|
4204
|
+
const globalPolicy = (await loadSettings()).permissions?.defaultPolicy ?? DEFAULT_PERMISSION_POLICY;
|
|
4205
|
+
const effectivePermissions = resolvePermissions({
|
|
4206
|
+
policy: globalPolicy,
|
|
4207
|
+
legacyShell: legacyShell === true,
|
|
4208
|
+
allowedTools: normalizedAllowedTools,
|
|
4209
|
+
deniedTools: normalizedDeniedTools,
|
|
4210
|
+
});
|
|
4211
|
+
const permissionsConfig = buildOpencodeConfig({
|
|
4212
|
+
policy: globalPolicy,
|
|
4213
|
+
legacyShell: legacyShell === true,
|
|
4214
|
+
allowedTools: normalizedAllowedTools,
|
|
4215
|
+
deniedTools: normalizedDeniedTools,
|
|
4216
|
+
});
|
|
4217
|
+
const policyMeta = {
|
|
4218
|
+
policy: effectivePermissions.policy,
|
|
4219
|
+
legacyShell: effectivePermissions.legacyShell,
|
|
4220
|
+
denied: effectivePermissions.deniedByPolicy,
|
|
4221
|
+
};
|
|
3799
4222
|
// Matrix (fan-out, Спринт 15): валидируем до создания файлов, чтобы не
|
|
3800
4223
|
// оставить «полу-созданную» задачу. Родитель сам не выполняется — он шаблон.
|
|
3801
4224
|
let normalizedMatrix;
|
|
@@ -3927,6 +4350,24 @@ paused) {
|
|
|
3927
4350
|
}
|
|
3928
4351
|
}
|
|
3929
4352
|
const effectiveWorkingDirectory = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
4353
|
+
// Файловые триггеры: относительный watchPath не должен выходить за рабочую
|
|
4354
|
+
// директорию задачи, а glob-маски — за пределы watchPath (path traversal).
|
|
4355
|
+
let effectiveWatchPath = watchPath?.trim() || undefined;
|
|
4356
|
+
if (effectiveWatchPath) {
|
|
4357
|
+
try {
|
|
4358
|
+
effectiveWatchPath = normalizeWatchPath(effectiveWatchPath, effectiveWorkingDirectory);
|
|
4359
|
+
}
|
|
4360
|
+
catch (err) {
|
|
4361
|
+
throw new Error(t("tool.error.taskReason", { name, error: err.message || String(err) }));
|
|
4362
|
+
}
|
|
4363
|
+
}
|
|
4364
|
+
try {
|
|
4365
|
+
validateWatchGlobs(normalizedWatchGlobs);
|
|
4366
|
+
validateWatchGlobs(normalizedWatchIgnore);
|
|
4367
|
+
}
|
|
4368
|
+
catch (err) {
|
|
4369
|
+
throw new Error(t("tool.error.taskReason", { name, error: err.message || String(err) }));
|
|
4370
|
+
}
|
|
3930
4371
|
// Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
|
|
3931
4372
|
// Спринт 29.3: инжектит в env только реально используемые секреты (scoped-инъекция).
|
|
3932
4373
|
const usedSecretNames = collectSecretNames(prompt, beforeScript, afterScript, qualityGate);
|
|
@@ -3948,11 +4389,14 @@ paused) {
|
|
|
3948
4389
|
// Обёртка зависит от платформы:
|
|
3949
4390
|
// - Windows: .cmd → PowerShell-скрипт (lock, таймаут, метрики);
|
|
3950
4391
|
// - Linux/macOS: .sh с тем же набором гарантий.
|
|
4392
|
+
// Спринт 24: id сессии читается обёрткой из sidecar-файла в рантайме,
|
|
4393
|
+
// поэтому ротация подхватывается без пересоздания задачи.
|
|
4394
|
+
const sessionFile = effectiveSession === "reuse" ? sessionStatePath(name) : undefined;
|
|
3951
4395
|
let wrapperPath;
|
|
3952
4396
|
try {
|
|
3953
4397
|
if (scheduler.platform === "win32") {
|
|
3954
4398
|
await ensureWrapper();
|
|
3955
|
-
wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId);
|
|
4399
|
+
wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId, retryCount, retryDelay, undefined, permissionsConfig, policyMeta, sessionFile);
|
|
3956
4400
|
}
|
|
3957
4401
|
else {
|
|
3958
4402
|
wrapperPath = await writeBashWrapper({
|
|
@@ -3971,12 +4415,15 @@ paused) {
|
|
|
3971
4415
|
workspaceName: workspace?.name,
|
|
3972
4416
|
allowedTools: normalizedAllowedTools,
|
|
3973
4417
|
deniedTools: normalizedDeniedTools,
|
|
4418
|
+
policy: globalPolicy,
|
|
4419
|
+
legacyShell: legacyShell === true,
|
|
3974
4420
|
scheduleGate: wrapperGate,
|
|
3975
4421
|
envFile: taskEnvFile,
|
|
3976
4422
|
sessionMode: effectiveSession,
|
|
3977
4423
|
sessionId: effectiveSessionId,
|
|
4424
|
+
sessionFile,
|
|
3978
4425
|
...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
|
|
3979
|
-
? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized) }
|
|
4426
|
+
? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized, getProfileName()) }
|
|
3980
4427
|
: {}),
|
|
3981
4428
|
});
|
|
3982
4429
|
}
|
|
@@ -4081,7 +4528,7 @@ paused) {
|
|
|
4081
4528
|
// sessionMaxRuns обходился правкой любого поля задачи. Сохраняем счётчик,
|
|
4082
4529
|
// только если сессия и её id не изменились.
|
|
4083
4530
|
sessionRunCount: preservedSessionRunCount(previousDefinition, effectiveSession, effectiveSessionId),
|
|
4084
|
-
watchPath: normalizedMatrix ? undefined :
|
|
4531
|
+
watchPath: normalizedMatrix ? undefined : effectiveWatchPath,
|
|
4085
4532
|
timezone: normalizedTz,
|
|
4086
4533
|
notBefore: normalizedNotBefore,
|
|
4087
4534
|
notAfter: normalizedNotAfter,
|
|
@@ -4101,6 +4548,7 @@ paused) {
|
|
|
4101
4548
|
pausedUntil: normalizedPausedUntil,
|
|
4102
4549
|
allowedTools: normalizedAllowedTools,
|
|
4103
4550
|
deniedTools: normalizedDeniedTools,
|
|
4551
|
+
legacyShell: legacyShell === true ? true : undefined,
|
|
4104
4552
|
matrix: normalizedMatrix,
|
|
4105
4553
|
isMatrixParent: normalizedMatrix ? true : undefined,
|
|
4106
4554
|
matrixParentId,
|
|
@@ -4118,18 +4566,21 @@ paused) {
|
|
|
4118
4566
|
try {
|
|
4119
4567
|
await saveTaskDefinition(taskDefinition);
|
|
4120
4568
|
// Аудит политики прав: фиксируем, какие инструменты задача блокирует.
|
|
4121
|
-
recordTaskToolBlocks(name, normalizedAllowedTools, normalizedDeniedTools);
|
|
4569
|
+
recordTaskToolBlocks(name, normalizedAllowedTools, normalizedDeniedTools, "system", "policy", globalPolicy, legacyShell === true);
|
|
4122
4570
|
}
|
|
4123
4571
|
catch {
|
|
4124
4572
|
// Не критично — основная задача уже создана.
|
|
4125
4573
|
}
|
|
4574
|
+
// Спринт 24: sidecar с актуальным id сессии — обёртка читает его перед
|
|
4575
|
+
// каждым запуском, поэтому ротация не требует пересоздания задачи.
|
|
4576
|
+
await writeSessionStateFile(name, effectiveSessionId);
|
|
4126
4577
|
// Matrix (fan-out): создаём клоны по workspace и, при необходимости,
|
|
4127
4578
|
// виртуальную задачу matrix-complete, которая запускается DAG-движком.
|
|
4128
4579
|
// Спринт 17: при обновлении (matrixMode === "sync") клоны не пересоздаются
|
|
4129
4580
|
// с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
|
|
4130
4581
|
if (normalizedMatrix) {
|
|
4131
4582
|
const createClone = async (clone) => {
|
|
4132
|
-
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
|
|
4583
|
+
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell);
|
|
4133
4584
|
};
|
|
4134
4585
|
const removeChild = async (child) => {
|
|
4135
4586
|
try {
|
|
@@ -4280,34 +4731,40 @@ async function recreateTaskFromDefinition(definition) {
|
|
|
4280
4731
|
gitPaths: definition.gitPaths,
|
|
4281
4732
|
gitIgnore: definition.gitIgnore,
|
|
4282
4733
|
gitPollSeconds: definition.gitPollSeconds,
|
|
4283
|
-
}, definition.runWhenLoggedOff, paused);
|
|
4734
|
+
}, definition.runWhenLoggedOff, paused, definition.legacyShell);
|
|
4284
4735
|
}
|
|
4285
4736
|
/**
|
|
4286
4737
|
* Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
|
|
4287
4738
|
* на клоны, а не выполняет свой промпт.
|
|
4288
4739
|
*/
|
|
4289
4740
|
async function runTaskEntry(name) {
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
|
|
4741
|
+
if (shutdownGate.isShuttingDown()) {
|
|
4742
|
+
throw new Error("Плагин выгружается: новые запуски не принимаются. Повторите после перезапуска.");
|
|
4743
|
+
}
|
|
4744
|
+
const run = (async () => {
|
|
4745
|
+
const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
|
|
4746
|
+
if (definition?.matrix) {
|
|
4747
|
+
await runMatrix(definition);
|
|
4748
|
+
return { alreadyRunning: false };
|
|
4749
|
+
}
|
|
4750
|
+
// Любой запуск через этот вход — «сейчас», а не «по расписанию»:
|
|
4751
|
+
// run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
|
|
4752
|
+
// Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
|
|
4753
|
+
// запуск молча отменялся бы schedule-gate с кодом 3.
|
|
4754
|
+
const forceFile = await requestImmediateRun(name);
|
|
4755
|
+
try {
|
|
4756
|
+
return await scheduler.runTask(name);
|
|
4757
|
+
}
|
|
4758
|
+
catch (err) {
|
|
4759
|
+
// Планировщик не принял запуск — маркер не нужен, иначе он мог бы
|
|
4760
|
+
// «разрешить» следующий плановый тик в обход расписания.
|
|
4761
|
+
await fs.unlink(forceFile).catch(() => {
|
|
4762
|
+
/* не критично */
|
|
4763
|
+
});
|
|
4764
|
+
throw err;
|
|
4765
|
+
}
|
|
4766
|
+
})();
|
|
4767
|
+
return shutdownGate.track(run);
|
|
4311
4768
|
}
|
|
4312
4769
|
/**
|
|
4313
4770
|
* Спринт 27.5.3: чтение задач ОС с одним повтором.
|
|
@@ -4443,6 +4900,8 @@ async function collectTasksView() {
|
|
|
4443
4900
|
return {
|
|
4444
4901
|
name,
|
|
4445
4902
|
schedule: def?.schedule ?? "",
|
|
4903
|
+
/** Hotfix 1.5.3.1: лимит времени задачи (раньше не был виден агенту). */
|
|
4904
|
+
timeoutSeconds: def?.timeoutSeconds ?? null,
|
|
4446
4905
|
status,
|
|
4447
4906
|
orphaned,
|
|
4448
4907
|
// Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
|