opencode-windows-scheduler 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/CROSS_PLATFORM.md +113 -0
- package/LICENSE +21 -0
- package/README.md +173 -2
- package/README.ru.md +131 -0
- package/ROADMAP-STRATEGY.md +217 -0
- package/ROADMAP.md +87 -0
- package/dist/core/cron-to-schtasks.d.ts +20 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +233 -0
- package/dist/core/dry-run.d.ts +44 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +252 -0
- package/dist/core/file-watcher.d.ts +31 -0
- package/dist/core/file-watcher.d.ts.map +1 -0
- package/dist/core/file-watcher.js +128 -0
- package/dist/core/lock.d.ts +43 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +118 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +687 -0
- package/dist/core/ps-wrapper.d.ts +60 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +538 -0
- package/dist/core/record-history.d.ts +14 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +360 -0
- package/dist/core/scheduler/index.d.ts +20 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +32 -0
- package/dist/core/scheduler/linux.d.ts +32 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +115 -0
- package/dist/core/scheduler/logs.d.ts +11 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -0
- package/dist/core/scheduler/logs.js +34 -0
- package/dist/core/scheduler/mac.d.ts +39 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +175 -0
- package/dist/core/scheduler/posix.d.ts +40 -0
- package/dist/core/scheduler/posix.d.ts.map +1 -0
- package/dist/core/scheduler/posix.js +86 -0
- package/dist/core/scheduler/registry.d.ts +36 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +56 -0
- package/dist/core/scheduler/types.d.ts +63 -0
- package/dist/core/scheduler/types.d.ts.map +1 -0
- package/dist/core/scheduler/types.js +1 -0
- package/dist/core/scheduler/windows.d.ts +47 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +375 -0
- package/dist/core/wrappers/bash.d.ts +58 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +223 -0
- package/dist/db/history-repo.d.ts +69 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +150 -0
- package/dist/db/index.d.ts +47 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +120 -0
- package/dist/db/metrics-repo.d.ts +43 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +95 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +237 -0
- package/dist/db/recovery.d.ts +11 -0
- package/dist/db/recovery.d.ts.map +1 -0
- package/dist/db/recovery.js +38 -0
- package/dist/db/schema.d.ts +24 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +97 -0
- package/dist/db/settings-repo.d.ts +8 -0
- package/dist/db/settings-repo.d.ts.map +1 -0
- package/dist/db/settings-repo.js +27 -0
- package/dist/db/tasks-repo.d.ts +26 -0
- package/dist/db/tasks-repo.d.ts.map +1 -0
- package/dist/db/tasks-repo.js +120 -0
- package/dist/db/templates-repo.d.ts +17 -0
- package/dist/db/templates-repo.d.ts.map +1 -0
- package/dist/db/templates-repo.js +57 -0
- package/dist/gui-experimental.cjs +1 -0
- package/dist/history.d.ts +53 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +57 -0
- package/dist/index.d.ts +156 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2077 -0
- package/dist/notifications.d.ts +45 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +135 -0
- package/dist/rpc.d.ts +2052 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +863 -0
- package/dist/schtasks.d.ts +32 -0
- package/dist/schtasks.d.ts.map +1 -0
- package/dist/schtasks.js +45 -0
- package/dist/server.d.ts +106 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1478 -0
- package/dist/settings.d.ts +43 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +96 -0
- package/dist/shared/jobs-view.d.ts +21 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +28 -0
- package/dist/skill.d.ts +15 -0
- package/dist/skill.d.ts.map +1 -0
- package/dist/skill.js +93 -0
- package/dist/task-transfer.d.ts +176 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +442 -0
- package/dist/templates.d.ts +57 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +16 -0
- package/dist/types.d.ts +78 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +88 -0
- package/dist/workspaces.d.ts +55 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +183 -0
- package/docs/ARCHITECTURE.md +302 -0
- package/docs/FEATURES.md +288 -0
- package/docs/MIGRATION.md +266 -0
- package/docs/dashboard.png +0 -0
- package/gui-experimental.cjs +2 -0
- package/index.js +1 -0
- package/package.json +92 -4
- package/scripts/demo-dashboard.mjs +199 -0
- package/skills/scheduled-job-best-practices/SKILL.md +155 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
- package/src/core/cron-to-schtasks.ts +269 -0
- package/src/core/dry-run.ts +315 -0
- package/src/core/file-watcher.ts +171 -0
- package/src/core/lock.ts +134 -0
- package/src/core/matrix.ts +907 -0
- package/src/core/ps-wrapper.ts +572 -0
- package/src/core/record-history.ts +493 -0
- package/src/core/scheduler/index.ts +44 -0
- package/src/core/scheduler/linux.ts +125 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +222 -0
- package/src/core/scheduler/posix.ts +111 -0
- package/src/core/scheduler/registry.ts +93 -0
- package/src/core/scheduler/types.ts +67 -0
- package/src/core/scheduler/windows.ts +469 -0
- package/src/core/wrappers/bash.ts +282 -0
- package/src/db/history-repo.ts +303 -0
- package/src/db/index.ts +166 -0
- package/src/db/metrics-repo.ts +158 -0
- package/src/db/migrate.ts +322 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/schema.ts +109 -0
- package/src/db/settings-repo.ts +31 -0
- package/src/db/tasks-repo.ts +162 -0
- package/src/db/templates-repo.ts +77 -0
- package/src/gui.tsx +2725 -0
- package/src/history.ts +107 -0
- package/src/index.ts +2672 -0
- package/src/notifications.ts +174 -0
- package/src/rpc.ts +933 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +1663 -0
- package/src/settings.ts +157 -0
- package/src/shared/jobs-view.ts +38 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +648 -0
- package/src/templates.ts +67 -0
- package/src/tui.tsx +46 -0
- package/src/types.ts +145 -0
- package/src/workspaces.ts +236 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2077 @@
|
|
|
1
|
+
import { Plugin } from "@opencode/plugin";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import fs from "node:fs/promises";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { LockManager } from "./core/lock.js";
|
|
8
|
+
import { LOCK_DIR, LOG_DIR, sanitizeName } from "./types.js";
|
|
9
|
+
import { convertCronToSchTasks, previousRunTime } from "./core/cron-to-schtasks.js";
|
|
10
|
+
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath } from "./core/ps-wrapper.js";
|
|
11
|
+
import { getSchedulerBackend } from "./core/scheduler/index.js";
|
|
12
|
+
import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
|
|
13
|
+
import { getTaskLogs } from "./core/scheduler/logs.js";
|
|
14
|
+
import { writeBashWrapper } from "./core/wrappers/bash.js";
|
|
15
|
+
import { simulatePipeline } from "./core/dry-run.js";
|
|
16
|
+
import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.js";
|
|
17
|
+
import { SchedulerRpc } from "./rpc.js";
|
|
18
|
+
import { loadHistory, loadMetrics } from "./history.js";
|
|
19
|
+
import { loadSettings, saveSettings } from "./settings.js";
|
|
20
|
+
import { sendTestNotification } from "./notifications.js";
|
|
21
|
+
import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExportJson, parseImportJson, normalizePriority, } from "./task-transfer.js";
|
|
22
|
+
import { FileWatchManager } from "./core/file-watcher.js";
|
|
23
|
+
import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
|
|
24
|
+
import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
|
|
25
|
+
import { closeDb, initDb } from "./db/index.js";
|
|
26
|
+
import { migrateJsonToDb } from "./db/migrate.js";
|
|
27
|
+
import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
|
|
28
|
+
import { getTask, listMatrixClones } from "./db/tasks-repo.js";
|
|
29
|
+
import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, } from "./workspaces.js";
|
|
30
|
+
// Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
|
|
31
|
+
const require = createRequire(import.meta.url);
|
|
32
|
+
const resolvedRecorder = require.resolve("./core/record-history.js");
|
|
33
|
+
/**
|
|
34
|
+
* Плагин может загружаться как из dist, так и напрямую из src (tsx/транспиляция).
|
|
35
|
+
* Node не умеет исполнять .ts, поэтому для фоновых задач всегда берём
|
|
36
|
+
* скомпилированный dist/core/record-history.js.
|
|
37
|
+
*/
|
|
38
|
+
const recorderPath = (() => {
|
|
39
|
+
if (!resolvedRecorder.endsWith(".ts"))
|
|
40
|
+
return resolvedRecorder;
|
|
41
|
+
const distPath = resolvedRecorder
|
|
42
|
+
.replace(/([\\/])src([\\/])/, "$1dist$2")
|
|
43
|
+
.replace(/\.ts$/, ".js");
|
|
44
|
+
if (existsSync(distPath))
|
|
45
|
+
return distPath;
|
|
46
|
+
console.warn("[windows-scheduler] Не найден собранный record-history.js: " +
|
|
47
|
+
`${distPath}. История/метрики не будут записываться. Выполните npm run build.`);
|
|
48
|
+
return distPath;
|
|
49
|
+
})();
|
|
50
|
+
/** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
|
|
51
|
+
const scheduler = getSchedulerBackend();
|
|
52
|
+
/** Per-workspace overrides for matrix clones (Sprint 17). */
|
|
53
|
+
export const matrixOverrideSchema = z.object({
|
|
54
|
+
prompt: z.string().optional(),
|
|
55
|
+
model: z.string().optional(),
|
|
56
|
+
qualityGate: z.string().optional(),
|
|
57
|
+
beforeScript: z.string().optional(),
|
|
58
|
+
afterScript: z.string().optional(),
|
|
59
|
+
});
|
|
60
|
+
/** Matrix (fan-out) configuration. */
|
|
61
|
+
export const matrixSchema = z.object({
|
|
62
|
+
workspaceIds: z
|
|
63
|
+
.array(z.string())
|
|
64
|
+
.describe("Workspace ids to fan out to. Cannot be combined with workspaceId."),
|
|
65
|
+
strategy: z
|
|
66
|
+
.enum(["parallel", "sequential"])
|
|
67
|
+
.optional()
|
|
68
|
+
.describe("parallel (default) starts all clones at once; sequential starts the next clone only after the previous one finishes."),
|
|
69
|
+
failureMode: z
|
|
70
|
+
.enum(["continue", "stop"])
|
|
71
|
+
.optional()
|
|
72
|
+
.describe("continue (default) keeps running the remaining clones after a failure; stop aborts the rest."),
|
|
73
|
+
aggregation: z
|
|
74
|
+
.enum(["summary", "per-task"])
|
|
75
|
+
.optional()
|
|
76
|
+
.describe("summary (default) writes one aggregate record for the parent; per-task keeps per-clone records."),
|
|
77
|
+
createAggregator: z
|
|
78
|
+
.boolean()
|
|
79
|
+
.optional()
|
|
80
|
+
.describe("Also create the <parent>-matrix-complete task depending on every clone."),
|
|
81
|
+
concurrency: z
|
|
82
|
+
.number()
|
|
83
|
+
.optional()
|
|
84
|
+
.describe("Maximum number of clones running at the same time (>= 1). Ignored for sequential (always 1) and capped by the global maxConcurrent setting."),
|
|
85
|
+
overrides: z
|
|
86
|
+
.record(z.string(), matrixOverrideSchema)
|
|
87
|
+
.optional()
|
|
88
|
+
.describe("Per-workspace overrides keyed by workspace id. Keys must be present in workspaceIds."),
|
|
89
|
+
});
|
|
90
|
+
/** Zod-схема аргументов schedule_task */
|
|
91
|
+
export const scheduleTaskSchema = z.object({
|
|
92
|
+
name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
|
|
93
|
+
schedule: z
|
|
94
|
+
.string()
|
|
95
|
+
.describe("5-field cron expression (minute hour day-of-month month day-of-week). Supported patterns: * * * * *, */N * * * *, M H * * *, M H * * D."),
|
|
96
|
+
prompt: z
|
|
97
|
+
.string()
|
|
98
|
+
.describe("Prompt passed to the agent on every run."),
|
|
99
|
+
timeoutSeconds: z
|
|
100
|
+
.number()
|
|
101
|
+
.optional()
|
|
102
|
+
.describe("Run timeout in seconds (default 3600)."),
|
|
103
|
+
model: z
|
|
104
|
+
.string()
|
|
105
|
+
.optional()
|
|
106
|
+
.describe("LLM model in OpenCode format, e.g. anthropic/claude-3-5-sonnet. Defaults to the OpenCode default model."),
|
|
107
|
+
priority: z
|
|
108
|
+
.number()
|
|
109
|
+
.optional()
|
|
110
|
+
.describe("Task priority 0..10 (10 is the highest). Default 5 (normal)."),
|
|
111
|
+
beforeScript: z
|
|
112
|
+
.string()
|
|
113
|
+
.optional()
|
|
114
|
+
.describe("Pre-flight shell command executed before the run (e.g. git pull). A non-zero exit code cancels the run."),
|
|
115
|
+
afterScript: z
|
|
116
|
+
.string()
|
|
117
|
+
.optional()
|
|
118
|
+
.describe("Post-flight shell command executed after the run (e.g. git push). Runs even when the task fails."),
|
|
119
|
+
qualityGate: z
|
|
120
|
+
.string()
|
|
121
|
+
.optional()
|
|
122
|
+
.describe("Shell command executed after a successful AI response (e.g. npm test). A non-zero exit code marks the run as a Quality Gate failure."),
|
|
123
|
+
dependsOn: z
|
|
124
|
+
.array(z.string())
|
|
125
|
+
.optional()
|
|
126
|
+
.describe("DAG dependencies: tasks that must finish successfully before this task starts."),
|
|
127
|
+
retryCount: z
|
|
128
|
+
.number()
|
|
129
|
+
.optional()
|
|
130
|
+
.describe("How many times to retry a failed run (default 0)."),
|
|
131
|
+
retryDelay: z
|
|
132
|
+
.number()
|
|
133
|
+
.optional()
|
|
134
|
+
.describe("Delay between retries in seconds (default 60)."),
|
|
135
|
+
nextTaskOnSuccess: z
|
|
136
|
+
.string()
|
|
137
|
+
.optional()
|
|
138
|
+
.describe("Task started after a successful run."),
|
|
139
|
+
nextTaskOnError: z
|
|
140
|
+
.string()
|
|
141
|
+
.optional()
|
|
142
|
+
.describe("Compensation/rollback task started after a failed run."),
|
|
143
|
+
triggerType: z
|
|
144
|
+
.enum(["cron", "file", "mcp-event"])
|
|
145
|
+
.optional()
|
|
146
|
+
.describe("Trigger type: cron (default), file or mcp-event."),
|
|
147
|
+
mcpEvent: z
|
|
148
|
+
.object({
|
|
149
|
+
server: z.string(),
|
|
150
|
+
event: z.string(),
|
|
151
|
+
filter: z.string().optional(),
|
|
152
|
+
})
|
|
153
|
+
.optional()
|
|
154
|
+
.describe("MCP event trigger: server, event name and an optional filter (key=value or regex)."),
|
|
155
|
+
workingDirectory: z
|
|
156
|
+
.string()
|
|
157
|
+
.optional()
|
|
158
|
+
.describe("Working directory of the task. Defaults to the current project folder so opencode run picks up the project's opencode.json with MCP servers."),
|
|
159
|
+
workspaceId: z
|
|
160
|
+
.string()
|
|
161
|
+
.optional()
|
|
162
|
+
.describe("Multi-repo workspace binding. When set, cwd = workspace path and workingDirectory is ignored."),
|
|
163
|
+
allowedTools: z
|
|
164
|
+
.array(z.string())
|
|
165
|
+
.optional()
|
|
166
|
+
.describe("Role-scoped tool allow-list. Metadata-only: logged and recorded in history, not enforced by opencode run yet. An empty array is rejected."),
|
|
167
|
+
deniedTools: z
|
|
168
|
+
.array(z.string())
|
|
169
|
+
.optional()
|
|
170
|
+
.describe("Role-scoped tool deny-list (takes precedence over allowedTools). Metadata-only."),
|
|
171
|
+
matrix: matrixSchema
|
|
172
|
+
.optional()
|
|
173
|
+
.describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
|
|
174
|
+
});
|
|
175
|
+
const listTasksSchema = z.object({});
|
|
176
|
+
const deleteTaskSchema = z.object({
|
|
177
|
+
name: z.string().describe("Task name to delete."),
|
|
178
|
+
});
|
|
179
|
+
const runTaskNowSchema = z.object({
|
|
180
|
+
name: z.string().describe("Task name to run immediately."),
|
|
181
|
+
});
|
|
182
|
+
export const updateTaskSchema = z.object({
|
|
183
|
+
name: z.string().describe("Name of the task to update."),
|
|
184
|
+
schedule: z
|
|
185
|
+
.string()
|
|
186
|
+
.optional()
|
|
187
|
+
.describe("New 5-field cron expression. Keeps the current value when omitted."),
|
|
188
|
+
prompt: z
|
|
189
|
+
.string()
|
|
190
|
+
.optional()
|
|
191
|
+
.describe("New prompt. Keeps the current value when omitted."),
|
|
192
|
+
timeoutSeconds: z.number().optional().describe("New run timeout in seconds."),
|
|
193
|
+
model: z
|
|
194
|
+
.string()
|
|
195
|
+
.optional()
|
|
196
|
+
.describe("New model in OpenCode format. Empty string clears it (default model)."),
|
|
197
|
+
priority: z.number().optional().describe("New priority 0..10."),
|
|
198
|
+
beforeScript: z
|
|
199
|
+
.string()
|
|
200
|
+
.optional()
|
|
201
|
+
.describe("New pre-flight command. Empty string clears it."),
|
|
202
|
+
afterScript: z
|
|
203
|
+
.string()
|
|
204
|
+
.optional()
|
|
205
|
+
.describe("New post-flight command. Empty string clears it."),
|
|
206
|
+
qualityGate: z
|
|
207
|
+
.string()
|
|
208
|
+
.optional()
|
|
209
|
+
.describe("New Quality Gate command. Empty string clears it."),
|
|
210
|
+
dependsOn: z
|
|
211
|
+
.array(z.string())
|
|
212
|
+
.optional()
|
|
213
|
+
.describe("New DAG dependencies. Empty array clears them."),
|
|
214
|
+
retryCount: z.number().optional().describe("New retry count."),
|
|
215
|
+
retryDelay: z.number().optional().describe("New retry delay in seconds."),
|
|
216
|
+
nextTaskOnSuccess: z
|
|
217
|
+
.string()
|
|
218
|
+
.optional()
|
|
219
|
+
.describe("New success-chain task. Empty string clears it."),
|
|
220
|
+
nextTaskOnError: z
|
|
221
|
+
.string()
|
|
222
|
+
.optional()
|
|
223
|
+
.describe("New error-chain task. Empty string clears it."),
|
|
224
|
+
triggerType: z
|
|
225
|
+
.enum(["cron", "file", "mcp-event"])
|
|
226
|
+
.optional()
|
|
227
|
+
.describe("New trigger type."),
|
|
228
|
+
mcpEvent: z
|
|
229
|
+
.object({
|
|
230
|
+
server: z.string(),
|
|
231
|
+
event: z.string(),
|
|
232
|
+
filter: z.string().optional(),
|
|
233
|
+
})
|
|
234
|
+
.optional()
|
|
235
|
+
.describe("New MCP event trigger."),
|
|
236
|
+
watchPath: z
|
|
237
|
+
.string()
|
|
238
|
+
.optional()
|
|
239
|
+
.describe("New file-trigger path. Empty string clears it."),
|
|
240
|
+
workingDirectory: z
|
|
241
|
+
.string()
|
|
242
|
+
.optional()
|
|
243
|
+
.describe("New working directory. Empty string clears it."),
|
|
244
|
+
workspaceId: z
|
|
245
|
+
.string()
|
|
246
|
+
.optional()
|
|
247
|
+
.describe("New workspace binding. Empty string clears it."),
|
|
248
|
+
allowedTools: z
|
|
249
|
+
.array(z.string())
|
|
250
|
+
.optional()
|
|
251
|
+
.describe("New tool allow-list. Empty array clears it."),
|
|
252
|
+
deniedTools: z
|
|
253
|
+
.array(z.string())
|
|
254
|
+
.optional()
|
|
255
|
+
.describe("New tool deny-list. Empty array clears it."),
|
|
256
|
+
matrix: matrixSchema
|
|
257
|
+
.nullable()
|
|
258
|
+
.optional()
|
|
259
|
+
.describe("New matrix configuration. Pass null to turn the matrix off (clones and aggregator are removed)."),
|
|
260
|
+
});
|
|
261
|
+
const pauseTaskSchema = z.object({
|
|
262
|
+
name: z.string().describe("Task name to pause."),
|
|
263
|
+
});
|
|
264
|
+
const resumeTaskSchema = z.object({
|
|
265
|
+
name: z.string().describe("Task name to resume."),
|
|
266
|
+
});
|
|
267
|
+
const getHistorySchema = z.object({
|
|
268
|
+
taskName: z
|
|
269
|
+
.string()
|
|
270
|
+
.optional()
|
|
271
|
+
.describe("Only return runs of this task (case-insensitive)."),
|
|
272
|
+
status: z
|
|
273
|
+
.enum(["running", "success", "error", "timeout", "partial"])
|
|
274
|
+
.optional()
|
|
275
|
+
.describe("Only return runs with this status."),
|
|
276
|
+
limit: z
|
|
277
|
+
.number()
|
|
278
|
+
.optional()
|
|
279
|
+
.describe("Maximum number of records to return (default 20, max 200)."),
|
|
280
|
+
});
|
|
281
|
+
const getTaskLogsSchema = z.object({
|
|
282
|
+
name: z.string().describe("Task name to read logs for."),
|
|
283
|
+
lines: z
|
|
284
|
+
.number()
|
|
285
|
+
.optional()
|
|
286
|
+
.describe("Return only the last N log lines (default 200)."),
|
|
287
|
+
});
|
|
288
|
+
const dryRunSchema = z.object({
|
|
289
|
+
name: z
|
|
290
|
+
.string()
|
|
291
|
+
.optional()
|
|
292
|
+
.describe("Task name to simulate. When omitted, every task is simulated (pipeline dry run, nothing is executed)."),
|
|
293
|
+
});
|
|
294
|
+
const manageWorkspacesSchema = z.object({
|
|
295
|
+
action: z
|
|
296
|
+
.enum(["list", "add", "update", "delete"])
|
|
297
|
+
.describe("Workspace operation to perform."),
|
|
298
|
+
id: z.string().optional().describe("Workspace id (update/delete)."),
|
|
299
|
+
name: z.string().optional().describe("Workspace display name (add/update)."),
|
|
300
|
+
path: z.string().optional().describe("Absolute workspace path (add/update)."),
|
|
301
|
+
color: z.string().optional().describe("Marker color, e.g. #4f8cff (add/update)."),
|
|
302
|
+
});
|
|
303
|
+
export const matrixControlSchema = z.object({
|
|
304
|
+
action: z
|
|
305
|
+
.enum(["results", "cancel", "cleanup"])
|
|
306
|
+
.describe("results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators."),
|
|
307
|
+
name: z
|
|
308
|
+
.string()
|
|
309
|
+
.optional()
|
|
310
|
+
.describe("Matrix parent name (required for results and cancel)."),
|
|
311
|
+
});
|
|
312
|
+
/**
|
|
313
|
+
* Директория проекта, в которой запущен OpenCode. Используется как рабочая
|
|
314
|
+
* директория задачи по умолчанию, чтобы `opencode run` подхватил opencode.json
|
|
315
|
+
* с MCP-серверами проекта. Заполняется в setup из ctx.location.directory.
|
|
316
|
+
*/
|
|
317
|
+
let projectDirectory;
|
|
318
|
+
/**
|
|
319
|
+
* Обёртка execute-функции: ловит ошибки и возвращает Tool.Result с content.
|
|
320
|
+
* Использует Tool.Context из @opencode/schema/tool.
|
|
321
|
+
*/
|
|
322
|
+
function wrapExecute(fn) {
|
|
323
|
+
return async (input, context) => {
|
|
324
|
+
try {
|
|
325
|
+
return await fn(input, context);
|
|
326
|
+
}
|
|
327
|
+
catch (err) {
|
|
328
|
+
return {
|
|
329
|
+
content: JSON.stringify({
|
|
330
|
+
success: false,
|
|
331
|
+
error: err instanceof Error ? err.message : String(err),
|
|
332
|
+
}),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
338
|
+
const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
339
|
+
const { name, schedule, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, } = args;
|
|
340
|
+
try {
|
|
341
|
+
await schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, undefined, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix);
|
|
342
|
+
}
|
|
343
|
+
catch (err) {
|
|
344
|
+
return {
|
|
345
|
+
content: JSON.stringify({
|
|
346
|
+
success: false,
|
|
347
|
+
error: err instanceof Error ? err.message : String(err),
|
|
348
|
+
}),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
|
|
352
|
+
const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
353
|
+
return {
|
|
354
|
+
content: JSON.stringify({
|
|
355
|
+
success: true,
|
|
356
|
+
message: `Задача "${name}" успешно создана.`,
|
|
357
|
+
task: {
|
|
358
|
+
name,
|
|
359
|
+
schedule,
|
|
360
|
+
timeoutSeconds: timeoutSeconds ?? 3600,
|
|
361
|
+
model: model?.trim() || null,
|
|
362
|
+
priority: priority ?? 5,
|
|
363
|
+
beforeScript: beforeScript?.trim() || null,
|
|
364
|
+
afterScript: afterScript?.trim() || null,
|
|
365
|
+
qualityGate: qualityGate?.trim() || null,
|
|
366
|
+
dependsOn: dependsOn ?? [],
|
|
367
|
+
retryCount: retryCount ?? 0,
|
|
368
|
+
retryDelay: retryDelay ?? null,
|
|
369
|
+
nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
|
|
370
|
+
nextTaskOnError: nextTaskOnError?.trim() || null,
|
|
371
|
+
triggerType: triggerType ?? "cron",
|
|
372
|
+
mcpEvent: mcpEvent ?? null,
|
|
373
|
+
workingDirectory: effectiveWorkdir,
|
|
374
|
+
workspaceId: workspace?.id ?? null,
|
|
375
|
+
workspaceName: workspace?.name ?? null,
|
|
376
|
+
matrix: matrix ?? null,
|
|
377
|
+
},
|
|
378
|
+
}),
|
|
379
|
+
};
|
|
380
|
+
});
|
|
381
|
+
/** list_tasks — список задач плагина (та же логика, что и у get_tasks). */
|
|
382
|
+
const listTasksExecute = wrapExecute(async () => {
|
|
383
|
+
const tasks = await collectTasksView();
|
|
384
|
+
if (tasks.length === 0) {
|
|
385
|
+
return {
|
|
386
|
+
content: JSON.stringify({
|
|
387
|
+
success: true,
|
|
388
|
+
message: "Задачи плагина не найдены.",
|
|
389
|
+
tasks: [],
|
|
390
|
+
}),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
content: JSON.stringify({
|
|
395
|
+
success: true,
|
|
396
|
+
message: `Найдено задач: ${tasks.length}.`,
|
|
397
|
+
tasks,
|
|
398
|
+
}),
|
|
399
|
+
};
|
|
400
|
+
});
|
|
401
|
+
/**
|
|
402
|
+
* Отмена выполняющейся матрицы: незавершённые клоны помечаются отменой
|
|
403
|
+
* в истории, а реально запущенные — останавливаются (удаление задачи в
|
|
404
|
+
* планировщике ОС завершает процесс) и пересоздаются как placeholder,
|
|
405
|
+
* чтобы матрицу можно было запустить повторно.
|
|
406
|
+
*/
|
|
407
|
+
async function cancelMatrixRun(name) {
|
|
408
|
+
const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
|
|
409
|
+
if (!definition?.matrix) {
|
|
410
|
+
throw new Error(`Задача "${name}" не является матрицей.`);
|
|
411
|
+
}
|
|
412
|
+
const result = await cancelPendingMatrixClones(definition.name);
|
|
413
|
+
const warnings = [];
|
|
414
|
+
for (const cloneName of result.running) {
|
|
415
|
+
const clone = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === cloneName.toLowerCase());
|
|
416
|
+
if (!clone)
|
|
417
|
+
continue;
|
|
418
|
+
// Удаление запущенной задачи планировщика останавливает её процесс.
|
|
419
|
+
try {
|
|
420
|
+
await scheduler.deleteTask(clone.name);
|
|
421
|
+
}
|
|
422
|
+
catch (err) {
|
|
423
|
+
warnings.push(`${clone.name}: не удалось остановить — ${err instanceof Error ? err.message : String(err)}`);
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
// Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
|
|
427
|
+
try {
|
|
428
|
+
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);
|
|
429
|
+
}
|
|
430
|
+
catch (err) {
|
|
431
|
+
warnings.push(`${clone.name}: не удалось пересоздать — ${err instanceof Error ? err.message : String(err)}`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const parts = [
|
|
435
|
+
`Матрица "${definition.name}": отменено ${result.cancelled.length} из ${result.aggregate.totalCount} клонов.`,
|
|
436
|
+
];
|
|
437
|
+
if (result.running.length > 0) {
|
|
438
|
+
parts.push(`Остановлено выполнявшихся: ${result.running.length}.`);
|
|
439
|
+
}
|
|
440
|
+
if (result.alreadyFinished.length > 0) {
|
|
441
|
+
parts.push(`Уже завершены и не тронуты: ${result.alreadyFinished.length}.`);
|
|
442
|
+
}
|
|
443
|
+
if (warnings.length > 0) {
|
|
444
|
+
parts.push(`Предупреждения: ${warnings.join("; ")}.`);
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
cancelled: result.cancelled,
|
|
448
|
+
running: result.running,
|
|
449
|
+
message: parts.join(" "),
|
|
450
|
+
warnings,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
/** Вычищает клоны и агрегаторы, чьи матрицы уже удалены. */
|
|
454
|
+
async function cleanupOrphanedMatrixTasks() {
|
|
455
|
+
const orphans = findOrphanedMatrixTasks();
|
|
456
|
+
const removed = [];
|
|
457
|
+
for (const orphan of orphans) {
|
|
458
|
+
try {
|
|
459
|
+
await scheduler.deleteTask(orphan);
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
// Записи могло уже не быть в планировщике.
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
await removeTaskDefinition(orphan);
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
// Не критично.
|
|
469
|
+
}
|
|
470
|
+
removed.push(orphan);
|
|
471
|
+
}
|
|
472
|
+
if (removed.length > 0) {
|
|
473
|
+
console.log(`[matrix] Очищены осиротевшие задачи матриц: ${removed.join(", ")}`);
|
|
474
|
+
}
|
|
475
|
+
return removed;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Удаляет задачу из планировщика ОС и из БД.
|
|
479
|
+
*
|
|
480
|
+
* Lifecycle матриц (Спринт 16):
|
|
481
|
+
* - удаление родителя-матрицы каскадно удаляет клоны и агрегатор;
|
|
482
|
+
* - удаление клона поодиночке запрещено (защита от «сирот» и вечного running).
|
|
483
|
+
*/
|
|
484
|
+
async function deleteTaskWithFamily(name) {
|
|
485
|
+
const trimmed = name.trim();
|
|
486
|
+
const guard = getMatrixDeletionGuard(trimmed);
|
|
487
|
+
if (guard)
|
|
488
|
+
throw new Error(guard);
|
|
489
|
+
const plan = planMatrixFamilyDelete(trimmed);
|
|
490
|
+
const removed = [];
|
|
491
|
+
if (plan) {
|
|
492
|
+
for (const child of plan.children) {
|
|
493
|
+
try {
|
|
494
|
+
await scheduler.deleteTask(child);
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
// Клона могло уже не быть в планировщике.
|
|
498
|
+
}
|
|
499
|
+
try {
|
|
500
|
+
await removeTaskDefinition(child);
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
// Не критично.
|
|
504
|
+
}
|
|
505
|
+
removed.push(child);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
await scheduler.deleteTask(trimmed);
|
|
509
|
+
try {
|
|
510
|
+
await removeTaskDefinition(trimmed);
|
|
511
|
+
}
|
|
512
|
+
catch {
|
|
513
|
+
// Определения могло уже не быть — задача всё равно удалена из ОС.
|
|
514
|
+
}
|
|
515
|
+
return { removed };
|
|
516
|
+
}
|
|
517
|
+
/** delete_task — удаление задачи по имени (/f) */
|
|
518
|
+
const deleteTaskExecute = wrapExecute(async (args) => {
|
|
519
|
+
const { name } = args;
|
|
520
|
+
try {
|
|
521
|
+
const { removed } = await deleteTaskWithFamily(name);
|
|
522
|
+
return {
|
|
523
|
+
content: JSON.stringify({
|
|
524
|
+
success: true,
|
|
525
|
+
message: removed.length > 0
|
|
526
|
+
? `Матрица "${name}" удалена вместе с клонами: ${removed.join(", ")}.`
|
|
527
|
+
: `Задача "${name}" успешно удалена.`,
|
|
528
|
+
}),
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
catch (err) {
|
|
532
|
+
return {
|
|
533
|
+
content: JSON.stringify({
|
|
534
|
+
success: false,
|
|
535
|
+
error: err.message || String(err),
|
|
536
|
+
}),
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
/** run_task_now — немедленный запуск задачи */
|
|
541
|
+
const runTaskNowExecute = wrapExecute(async (args) => {
|
|
542
|
+
const { name } = args;
|
|
543
|
+
let alreadyRunning = false;
|
|
544
|
+
try {
|
|
545
|
+
const result = await scheduler.runTask(name);
|
|
546
|
+
alreadyRunning = result.alreadyRunning;
|
|
547
|
+
}
|
|
548
|
+
catch (err) {
|
|
549
|
+
return {
|
|
550
|
+
content: JSON.stringify({
|
|
551
|
+
success: false,
|
|
552
|
+
error: err.message || String(err),
|
|
553
|
+
}),
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
return {
|
|
557
|
+
content: JSON.stringify({
|
|
558
|
+
success: true,
|
|
559
|
+
message: alreadyRunning
|
|
560
|
+
? `Задача "${name}" уже выполняется.`
|
|
561
|
+
: `Задача "${name}" запущена.`,
|
|
562
|
+
}),
|
|
563
|
+
};
|
|
564
|
+
});
|
|
565
|
+
/**
|
|
566
|
+
* Хелперы частичного обновления задачи: undefined — «не трогать»,
|
|
567
|
+
* пустая строка/массив — «очистить».
|
|
568
|
+
*/
|
|
569
|
+
function clearableString(next, current) {
|
|
570
|
+
if (next === undefined)
|
|
571
|
+
return current;
|
|
572
|
+
const trimmed = next.trim();
|
|
573
|
+
return trimmed ? trimmed : undefined;
|
|
574
|
+
}
|
|
575
|
+
function clearableList(next, current) {
|
|
576
|
+
if (next === undefined)
|
|
577
|
+
return current;
|
|
578
|
+
const cleaned = next.map((value) => value.trim()).filter(Boolean);
|
|
579
|
+
return cleaned.length > 0 ? cleaned : undefined;
|
|
580
|
+
}
|
|
581
|
+
/** Удаляет клонов и агрегатор матрицы из планировщика ОС и из БД. */
|
|
582
|
+
async function removeMatrixChildrenFromScheduler(name) {
|
|
583
|
+
const removed = [];
|
|
584
|
+
for (const child of removeMatrixChildren(name)) {
|
|
585
|
+
try {
|
|
586
|
+
await scheduler.deleteTask(child);
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
// ОС-задачи могло уже не быть.
|
|
590
|
+
}
|
|
591
|
+
try {
|
|
592
|
+
await removeTaskDefinition(child);
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
// Не критично.
|
|
596
|
+
}
|
|
597
|
+
removed.push(child);
|
|
598
|
+
}
|
|
599
|
+
return removed;
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Обновляет задачу, сохраняя все поля, которые не были переданы.
|
|
603
|
+
* Используется инструментом update_task и RPC-методом update_task.
|
|
604
|
+
*/
|
|
605
|
+
async function updateTaskFromInput(input) {
|
|
606
|
+
const name = input.name?.trim();
|
|
607
|
+
if (!name) {
|
|
608
|
+
return { success: false, message: "Не передано имя задачи." };
|
|
609
|
+
}
|
|
610
|
+
const previous = getTask(name);
|
|
611
|
+
if (!previous) {
|
|
612
|
+
return { success: false, message: `Задача "${name}" не найдена.` };
|
|
613
|
+
}
|
|
614
|
+
const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
|
|
615
|
+
const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
|
|
616
|
+
const triggerType = input.triggerType ?? previous.triggerType ?? "cron";
|
|
617
|
+
if (triggerType === "cron" && !schedule) {
|
|
618
|
+
return {
|
|
619
|
+
success: false,
|
|
620
|
+
message: `Для обновления задачи "${name}" нужен cron-график.`,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
if (!prompt) {
|
|
624
|
+
return {
|
|
625
|
+
success: false,
|
|
626
|
+
message: `Для обновления задачи "${name}" нужен промпт.`,
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
const matrixWas = previous.matrix;
|
|
630
|
+
const matrixNext = input.matrix === undefined ? matrixWas : input.matrix ?? undefined;
|
|
631
|
+
try {
|
|
632
|
+
// Обновление = пересоздание в планировщике с сохранением старых значений.
|
|
633
|
+
await scheduler.deleteTask(name);
|
|
634
|
+
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,
|
|
635
|
+
// Если задача была матрицей — синхронизируем клонов, а не
|
|
636
|
+
// пересоздаём их с нуля (Спринт 17).
|
|
637
|
+
matrixWas && matrixNext ? "sync" : "create");
|
|
638
|
+
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
639
|
+
if (matrixWas && !matrixNext) {
|
|
640
|
+
await removeMatrixChildrenFromScheduler(name);
|
|
641
|
+
}
|
|
642
|
+
return { success: true, message: `Задача "${name}" обновлена.` };
|
|
643
|
+
}
|
|
644
|
+
catch (err) {
|
|
645
|
+
return {
|
|
646
|
+
success: false,
|
|
647
|
+
message: err instanceof Error ? err.message : String(err),
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
/** update_task — частичное обновление существующей задачи. */
|
|
652
|
+
const updateTaskExecute = wrapExecute(async (args) => {
|
|
653
|
+
const result = await updateTaskFromInput(args);
|
|
654
|
+
return { content: JSON.stringify(result) };
|
|
655
|
+
});
|
|
656
|
+
/**
|
|
657
|
+
* Пауза/возобновление задачи. Для матрицы операция применяется ко всем
|
|
658
|
+
* клонам: сам родитель никогда не выполняется.
|
|
659
|
+
*/
|
|
660
|
+
async function pauseOrResumeTask(name, paused) {
|
|
661
|
+
const trimmed = name.trim();
|
|
662
|
+
const definition = getTask(trimmed);
|
|
663
|
+
if (!definition) {
|
|
664
|
+
return {
|
|
665
|
+
success: false,
|
|
666
|
+
message: `Задача "${trimmed}" не найдена.`,
|
|
667
|
+
affected: [],
|
|
668
|
+
warnings: [],
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
const targets = definition.matrix
|
|
672
|
+
? listMatrixClones(trimmed).map((clone) => clone.name)
|
|
673
|
+
: [trimmed];
|
|
674
|
+
if (targets.length === 0 && definition.matrix) {
|
|
675
|
+
return {
|
|
676
|
+
success: false,
|
|
677
|
+
message: `У матрицы "${trimmed}" нет клонов.`,
|
|
678
|
+
affected: [],
|
|
679
|
+
warnings: [],
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
const affected = [];
|
|
683
|
+
const warnings = [];
|
|
684
|
+
for (const target of targets) {
|
|
685
|
+
try {
|
|
686
|
+
if (paused) {
|
|
687
|
+
await scheduler.pauseTask(target);
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
await scheduler.resumeTask(target);
|
|
691
|
+
}
|
|
692
|
+
affected.push(target);
|
|
693
|
+
}
|
|
694
|
+
catch (err) {
|
|
695
|
+
warnings.push(`${target}: ${err instanceof Error ? err.message : String(err)}`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
const verb = paused ? "поставлена на паузу" : "возобновлена";
|
|
699
|
+
const message = definition.matrix
|
|
700
|
+
? `Матрица "${trimmed}" ${verb}: ${affected.length} из ${targets.length} клонов.` +
|
|
701
|
+
(warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
|
|
702
|
+
: `Задача "${trimmed}" ${verb}.` +
|
|
703
|
+
(warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
|
|
704
|
+
return {
|
|
705
|
+
success: warnings.length === 0,
|
|
706
|
+
message,
|
|
707
|
+
affected,
|
|
708
|
+
warnings,
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
const pauseTaskExecute = wrapExecute(async (args) => {
|
|
712
|
+
const result = await pauseOrResumeTask(args.name, true);
|
|
713
|
+
return { content: JSON.stringify(result) };
|
|
714
|
+
});
|
|
715
|
+
const resumeTaskExecute = wrapExecute(async (args) => {
|
|
716
|
+
const result = await pauseOrResumeTask(args.name, false);
|
|
717
|
+
return { content: JSON.stringify(result) };
|
|
718
|
+
});
|
|
719
|
+
/** get_history — история запусков с фильтрами по задаче и статусу. */
|
|
720
|
+
const getHistoryExecute = wrapExecute(async (args) => {
|
|
721
|
+
const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
|
|
722
|
+
const taskFilter = args.taskName?.trim().toLowerCase();
|
|
723
|
+
const records = (await loadHistory())
|
|
724
|
+
.filter((record) => !taskFilter || record.taskName.toLowerCase() === taskFilter)
|
|
725
|
+
.filter((record) => !args.status || record.status === args.status)
|
|
726
|
+
.slice(0, limit);
|
|
727
|
+
return {
|
|
728
|
+
content: JSON.stringify({
|
|
729
|
+
success: true,
|
|
730
|
+
count: records.length,
|
|
731
|
+
records,
|
|
732
|
+
}),
|
|
733
|
+
};
|
|
734
|
+
});
|
|
735
|
+
/** get_task_logs — последние строки лога задачи. */
|
|
736
|
+
const getTaskLogsExecute = wrapExecute(async (args) => {
|
|
737
|
+
const result = await getTaskLogs(args.name, args.lines ?? 200);
|
|
738
|
+
if (result.error) {
|
|
739
|
+
return {
|
|
740
|
+
content: JSON.stringify({ success: false, logs: "", error: result.error }),
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
return {
|
|
744
|
+
content: JSON.stringify({ success: true, logs: result.logs }),
|
|
745
|
+
};
|
|
746
|
+
});
|
|
747
|
+
/** dry_run — симуляция пайплайна без выполнения. */
|
|
748
|
+
const dryRunExecute = wrapExecute(async (args) => {
|
|
749
|
+
const name = args.name?.trim();
|
|
750
|
+
if (name) {
|
|
751
|
+
const report = await simulatePipeline(name);
|
|
752
|
+
return { content: JSON.stringify(report) };
|
|
753
|
+
}
|
|
754
|
+
const definitions = await loadTaskDefinitions();
|
|
755
|
+
const reports = [];
|
|
756
|
+
for (const definition of definitions) {
|
|
757
|
+
try {
|
|
758
|
+
reports.push(await simulatePipeline(definition.name));
|
|
759
|
+
}
|
|
760
|
+
catch (err) {
|
|
761
|
+
reports.push({
|
|
762
|
+
success: false,
|
|
763
|
+
taskName: definition.name,
|
|
764
|
+
tasks: [],
|
|
765
|
+
totals: {
|
|
766
|
+
estimatedDurationSec: null,
|
|
767
|
+
estimatedCostUsd: null,
|
|
768
|
+
estimatedTokens: null,
|
|
769
|
+
},
|
|
770
|
+
warnings: [],
|
|
771
|
+
error: err instanceof Error ? err.message : String(err),
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return {
|
|
776
|
+
content: JSON.stringify({
|
|
777
|
+
success: reports.every((report) => report.success !== false),
|
|
778
|
+
count: reports.length,
|
|
779
|
+
reports,
|
|
780
|
+
}),
|
|
781
|
+
};
|
|
782
|
+
});
|
|
783
|
+
/** manage_workspaces — CRUD multi-repo workspace-ов. */
|
|
784
|
+
const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
785
|
+
try {
|
|
786
|
+
switch (args.action) {
|
|
787
|
+
case "list": {
|
|
788
|
+
const workspaces = listWorkspaces().map((workspace) => ({
|
|
789
|
+
...workspace,
|
|
790
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
791
|
+
}));
|
|
792
|
+
return {
|
|
793
|
+
content: JSON.stringify({
|
|
794
|
+
success: true,
|
|
795
|
+
count: workspaces.length,
|
|
796
|
+
workspaces,
|
|
797
|
+
}),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
case "add": {
|
|
801
|
+
if (!args.path?.trim()) {
|
|
802
|
+
return {
|
|
803
|
+
content: JSON.stringify({
|
|
804
|
+
success: false,
|
|
805
|
+
error: "Для action=add нужен path.",
|
|
806
|
+
}),
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
const workspace = addWorkspace({
|
|
810
|
+
name: args.name,
|
|
811
|
+
path: args.path,
|
|
812
|
+
color: args.color,
|
|
813
|
+
});
|
|
814
|
+
return {
|
|
815
|
+
content: JSON.stringify({
|
|
816
|
+
success: true,
|
|
817
|
+
workspace: {
|
|
818
|
+
...workspace,
|
|
819
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
820
|
+
},
|
|
821
|
+
}),
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
case "update": {
|
|
825
|
+
if (!args.id?.trim()) {
|
|
826
|
+
return {
|
|
827
|
+
content: JSON.stringify({
|
|
828
|
+
success: false,
|
|
829
|
+
error: "Для action=update нужен id.",
|
|
830
|
+
}),
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
const workspace = updateWorkspace(args.id, {
|
|
834
|
+
name: args.name,
|
|
835
|
+
path: args.path,
|
|
836
|
+
color: args.color,
|
|
837
|
+
});
|
|
838
|
+
if (!workspace) {
|
|
839
|
+
return {
|
|
840
|
+
content: JSON.stringify({
|
|
841
|
+
success: false,
|
|
842
|
+
error: "Workspace не найден.",
|
|
843
|
+
}),
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
return {
|
|
847
|
+
content: JSON.stringify({
|
|
848
|
+
success: true,
|
|
849
|
+
workspace: {
|
|
850
|
+
...workspace,
|
|
851
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
852
|
+
},
|
|
853
|
+
}),
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
case "delete": {
|
|
857
|
+
if (!args.id?.trim()) {
|
|
858
|
+
return {
|
|
859
|
+
content: JSON.stringify({
|
|
860
|
+
success: false,
|
|
861
|
+
error: "Для action=delete нужен id.",
|
|
862
|
+
}),
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
const deleted = deleteWorkspace(args.id);
|
|
866
|
+
return {
|
|
867
|
+
content: JSON.stringify({
|
|
868
|
+
success: deleted,
|
|
869
|
+
message: deleted
|
|
870
|
+
? "Workspace удалён. Задачи сохранены, привязка очищена."
|
|
871
|
+
: "Workspace не найден.",
|
|
872
|
+
}),
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
catch (err) {
|
|
878
|
+
return {
|
|
879
|
+
content: JSON.stringify({
|
|
880
|
+
success: false,
|
|
881
|
+
error: err instanceof Error ? err.message : String(err),
|
|
882
|
+
}),
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
});
|
|
886
|
+
/** matrix_control — результаты, отмена и очистка матриц. */
|
|
887
|
+
const matrixControlExecute = wrapExecute(async (args) => {
|
|
888
|
+
if (args.action === "cleanup") {
|
|
889
|
+
const removed = await cleanupOrphanedMatrixTasks();
|
|
890
|
+
return {
|
|
891
|
+
content: JSON.stringify({
|
|
892
|
+
success: true,
|
|
893
|
+
message: removed.length > 0
|
|
894
|
+
? `Удалено осиротевших задач: ${removed.length}.`
|
|
895
|
+
: "Осиротевших задач не найдено.",
|
|
896
|
+
removed,
|
|
897
|
+
}),
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
const name = args.name?.trim();
|
|
901
|
+
if (!name) {
|
|
902
|
+
return {
|
|
903
|
+
content: JSON.stringify({
|
|
904
|
+
success: false,
|
|
905
|
+
error: `Для action=${args.action} нужен name матрицы.`,
|
|
906
|
+
}),
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
if (args.action === "cancel") {
|
|
910
|
+
try {
|
|
911
|
+
const result = await cancelMatrixRun(name);
|
|
912
|
+
return {
|
|
913
|
+
content: JSON.stringify({
|
|
914
|
+
success: true,
|
|
915
|
+
message: result.message,
|
|
916
|
+
cancelled: result.cancelled,
|
|
917
|
+
}),
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
catch (err) {
|
|
921
|
+
return {
|
|
922
|
+
content: JSON.stringify({
|
|
923
|
+
success: false,
|
|
924
|
+
error: err instanceof Error ? err.message : String(err),
|
|
925
|
+
}),
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
try {
|
|
930
|
+
const report = aggregateMatrixResults(name);
|
|
931
|
+
return { content: JSON.stringify({ success: true, report }) };
|
|
932
|
+
}
|
|
933
|
+
catch (err) {
|
|
934
|
+
return {
|
|
935
|
+
content: JSON.stringify({
|
|
936
|
+
success: false,
|
|
937
|
+
error: err instanceof Error ? err.message : String(err),
|
|
938
|
+
}),
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
});
|
|
942
|
+
export default Plugin.define({
|
|
943
|
+
id: "opencode-windows-scheduler",
|
|
944
|
+
setup: async (ctx) => {
|
|
945
|
+
// Папка проекта — рабочая директория задач по умолчанию. Благодаря ей
|
|
946
|
+
// `opencode run` подхватывает opencode.json с MCP-серверами проекта.
|
|
947
|
+
projectDirectory = ctx.location?.directory || process.cwd();
|
|
948
|
+
// Спринт 12: SQLite — основное хранилище. Открываем БД, при первом запуске
|
|
949
|
+
// автоматически переносим данные из JSON, затем восстанавливаем прерванные
|
|
950
|
+
// запуски. Ошибки миграции не должны мешать плагину стартовать.
|
|
951
|
+
initDb();
|
|
952
|
+
try {
|
|
953
|
+
await migrateJsonToDb();
|
|
954
|
+
}
|
|
955
|
+
catch (err) {
|
|
956
|
+
console.error(`[migrate] Не удалось мигрировать JSON → SQLite: ${err instanceof Error ? err.message : String(err)}`);
|
|
957
|
+
}
|
|
958
|
+
try {
|
|
959
|
+
recoverInterruptedRuns();
|
|
960
|
+
}
|
|
961
|
+
catch (err) {
|
|
962
|
+
console.error(`[recovery] Не удалось восстановить незавершённые запуски: ${err instanceof Error ? err.message : String(err)}`);
|
|
963
|
+
}
|
|
964
|
+
checkJsonBackups();
|
|
965
|
+
// Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
|
|
966
|
+
const lockManager = new LockManager(LOCK_DIR);
|
|
967
|
+
await lockManager.initialize();
|
|
968
|
+
// Восстановление пропущенных запусков (catch-up): если OpenCode был закрыт,
|
|
969
|
+
// а задача должна была выполниться (с nextRun прошло >5 мин и в истории нет
|
|
970
|
+
// записи после этого времени) — запускаем её немедленно.
|
|
971
|
+
void (async () => {
|
|
972
|
+
try {
|
|
973
|
+
const definitions = await loadTaskDefinitions();
|
|
974
|
+
const history = await loadHistory();
|
|
975
|
+
const now = new Date();
|
|
976
|
+
const catchUpThresholdMs = 5 * 60 * 1000;
|
|
977
|
+
// Сначала запускаем задачи с более высоким приоритетом (10 — максимум).
|
|
978
|
+
const prioritized = [...definitions].sort((a, b) => (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5));
|
|
979
|
+
for (const def of prioritized) {
|
|
980
|
+
// Catch-up имеет смысл только для cron-задач.
|
|
981
|
+
if ((def.triggerType ?? "cron") !== "cron")
|
|
982
|
+
continue;
|
|
983
|
+
if (!def.schedule)
|
|
984
|
+
continue;
|
|
985
|
+
const prevRun = previousRunTime(def.schedule, now);
|
|
986
|
+
if (!prevRun)
|
|
987
|
+
continue;
|
|
988
|
+
const ageMs = now.getTime() - prevRun.getTime();
|
|
989
|
+
if (ageMs < catchUpThresholdMs)
|
|
990
|
+
continue;
|
|
991
|
+
// Есть ли запись в истории после предполагаемого времени запуска?
|
|
992
|
+
const ranAfter = history.some((r) => r.taskName.toLowerCase() === def.name.toLowerCase() &&
|
|
993
|
+
new Date(r.startedAt).getTime() >= prevRun.getTime());
|
|
994
|
+
if (ranAfter)
|
|
995
|
+
continue;
|
|
996
|
+
// Запускаем задачу и пишем в лог.
|
|
997
|
+
try {
|
|
998
|
+
await scheduler.runTask(def.name);
|
|
999
|
+
console.log(`[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`);
|
|
1000
|
+
}
|
|
1001
|
+
catch (err) {
|
|
1002
|
+
console.error(`[windows-scheduler] Не удалось восстановить задачу "${def.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
catch (err) {
|
|
1007
|
+
console.error(`[windows-scheduler] Catch-up ошибка: ${err instanceof Error ? err.message : String(err)}`);
|
|
1008
|
+
}
|
|
1009
|
+
})();
|
|
1010
|
+
// Файловые триггеры (File Watchers): задачи с triggerType === "file"
|
|
1011
|
+
// запускаются при изменении watchPath через chokidar (с дебаунсом).
|
|
1012
|
+
const fileWatcherManager = new FileWatchManager(async (taskName) => {
|
|
1013
|
+
try {
|
|
1014
|
+
await scheduler.runTask(taskName);
|
|
1015
|
+
console.log(`[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`);
|
|
1016
|
+
}
|
|
1017
|
+
catch (err) {
|
|
1018
|
+
console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${err instanceof Error ? err.message : String(err)}`);
|
|
1019
|
+
}
|
|
1020
|
+
});
|
|
1021
|
+
void fileWatcherManager.refresh();
|
|
1022
|
+
const registration = await ctx.tool.transform((editor) => {
|
|
1023
|
+
// editor.add регистрирует новые инструменты плагина с codemode: true,
|
|
1024
|
+
// чтобы они были видны в Code Mode. Встроенные schedule_* отключены
|
|
1025
|
+
// через "experimental": { "schedules": false } в opencode.jsonc.
|
|
1026
|
+
editor.add({
|
|
1027
|
+
name: "schedule_task",
|
|
1028
|
+
input: scheduleTaskSchema,
|
|
1029
|
+
description: `Creates a task in the OS scheduler (${scheduler.title}) with a cron schedule, optional Quality Gate, DAG dependencies, retry policy and matrix fan-out. ` +
|
|
1030
|
+
"Every run goes through a timeout + lock-file wrapper, so overlapping runs are skipped. " +
|
|
1031
|
+
"Without workingDirectory the task runs in the current project folder, where opencode run picks up the project's opencode.json and MCP servers.",
|
|
1032
|
+
options: { codemode: true },
|
|
1033
|
+
execute: scheduleTaskExecute,
|
|
1034
|
+
});
|
|
1035
|
+
editor.add({
|
|
1036
|
+
name: "list_tasks",
|
|
1037
|
+
input: listTasksSchema,
|
|
1038
|
+
description: `Lists plugin tasks from the scheduler (${scheduler.title}) with schedule, status, next chained task and working directory. ` +
|
|
1039
|
+
"Matrix parents include a per-clone summary.",
|
|
1040
|
+
options: { codemode: true },
|
|
1041
|
+
execute: listTasksExecute,
|
|
1042
|
+
});
|
|
1043
|
+
editor.add({
|
|
1044
|
+
name: "update_task",
|
|
1045
|
+
input: updateTaskSchema,
|
|
1046
|
+
description: "Partially updates an existing task: omitted fields keep their current values, empty strings/arrays clear them. " +
|
|
1047
|
+
"Matrix changes are synced (clones are diffed, running clones are never touched); pass matrix: null to remove the matrix and its clones.",
|
|
1048
|
+
options: { codemode: true },
|
|
1049
|
+
execute: updateTaskExecute,
|
|
1050
|
+
});
|
|
1051
|
+
editor.add({
|
|
1052
|
+
name: "delete_task",
|
|
1053
|
+
input: deleteTaskSchema,
|
|
1054
|
+
description: `Deletes a task from the scheduler (${scheduler.title}) by name. ` +
|
|
1055
|
+
"Deleting a matrix parent also deletes its clones and aggregator; deleting a single clone is refused (delete the whole matrix instead).",
|
|
1056
|
+
options: { codemode: true },
|
|
1057
|
+
execute: deleteTaskExecute,
|
|
1058
|
+
});
|
|
1059
|
+
editor.add({
|
|
1060
|
+
name: "run_task_now",
|
|
1061
|
+
input: runTaskNowSchema,
|
|
1062
|
+
description: `Runs a task immediately in the scheduler (${scheduler.title}) for testing. ` +
|
|
1063
|
+
"Runs through the timeout + lock wrapper. For a matrix parent this starts the fan-out instead of the parent itself.",
|
|
1064
|
+
options: { codemode: true },
|
|
1065
|
+
execute: runTaskNowExecute,
|
|
1066
|
+
});
|
|
1067
|
+
editor.add({
|
|
1068
|
+
name: "pause_task",
|
|
1069
|
+
input: pauseTaskSchema,
|
|
1070
|
+
description: "Pauses a task in the OS scheduler. For a matrix parent every clone is paused (the parent itself never runs).",
|
|
1071
|
+
options: { codemode: true },
|
|
1072
|
+
execute: pauseTaskExecute,
|
|
1073
|
+
});
|
|
1074
|
+
editor.add({
|
|
1075
|
+
name: "resume_task",
|
|
1076
|
+
input: resumeTaskSchema,
|
|
1077
|
+
description: "Resumes a previously paused task. For a matrix parent every clone is resumed.",
|
|
1078
|
+
options: { codemode: true },
|
|
1079
|
+
execute: resumeTaskExecute,
|
|
1080
|
+
});
|
|
1081
|
+
editor.add({
|
|
1082
|
+
name: "get_history",
|
|
1083
|
+
input: getHistorySchema,
|
|
1084
|
+
description: "Returns recent run history (status, duration, tokens, cost, model, Quality Gate and pre/post-flight results). " +
|
|
1085
|
+
"Filter by taskName and/or status; newest first.",
|
|
1086
|
+
options: { codemode: true },
|
|
1087
|
+
execute: getHistoryExecute,
|
|
1088
|
+
});
|
|
1089
|
+
editor.add({
|
|
1090
|
+
name: "get_task_logs",
|
|
1091
|
+
input: getTaskLogsSchema,
|
|
1092
|
+
description: "Returns the tail of a task's log file written by the run wrapper. Use it to diagnose failed runs.",
|
|
1093
|
+
options: { codemode: true },
|
|
1094
|
+
execute: getTaskLogsExecute,
|
|
1095
|
+
});
|
|
1096
|
+
editor.add({
|
|
1097
|
+
name: "dry_run",
|
|
1098
|
+
input: dryRunSchema,
|
|
1099
|
+
description: "Simulates a task pipeline (or every task when name is omitted): execution order, DAG dependencies, matrix fan-out, estimated duration/cost and warnings. Nothing is executed.",
|
|
1100
|
+
options: { codemode: true },
|
|
1101
|
+
execute: dryRunExecute,
|
|
1102
|
+
});
|
|
1103
|
+
editor.add({
|
|
1104
|
+
name: "manage_workspaces",
|
|
1105
|
+
input: manageWorkspacesSchema,
|
|
1106
|
+
description: "Manages multi-repo workspaces: list, add, update or delete. Tasks can target a workspace by id (cwd = workspace path) or fan out to several with matrix.workspaceIds.",
|
|
1107
|
+
options: { codemode: true },
|
|
1108
|
+
execute: manageWorkspacesExecute,
|
|
1109
|
+
});
|
|
1110
|
+
editor.add({
|
|
1111
|
+
name: "matrix_control",
|
|
1112
|
+
input: matrixControlSchema,
|
|
1113
|
+
description: "Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones) or cleanup (delete orphaned clones and aggregators whose parent is gone).",
|
|
1114
|
+
options: { codemode: true },
|
|
1115
|
+
execute: matrixControlExecute,
|
|
1116
|
+
});
|
|
1117
|
+
});
|
|
1118
|
+
// Нативный скилл плагина: агент видит краткое описание в списке доступных
|
|
1119
|
+
// скиллов и подгружает инструкцию только когда задача действительно про
|
|
1120
|
+
// автоматизацию по расписанию. Файлы скилла лежат в пакете (`skills/...`),
|
|
1121
|
+
// поэтому ручная установка в `.opencode/skills` не нужна.
|
|
1122
|
+
let skillRegistration;
|
|
1123
|
+
try {
|
|
1124
|
+
const skill = loadSchedulerSkill();
|
|
1125
|
+
if (skill && ctx.skill?.transform) {
|
|
1126
|
+
skillRegistration = await ctx.skill.transform((editor) => {
|
|
1127
|
+
editor.add({
|
|
1128
|
+
id: skill.id,
|
|
1129
|
+
name: skill.name,
|
|
1130
|
+
description: skill.description,
|
|
1131
|
+
path: skill.path,
|
|
1132
|
+
content: skill.content,
|
|
1133
|
+
});
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
catch (err) {
|
|
1138
|
+
console.error(`[windows-scheduler] Не удалось зарегистрировать скилл "${SCHEDULER_SKILL_ID}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1139
|
+
}
|
|
1140
|
+
// Регистрируем RPC-методы, вызываемые из GUI-панели.
|
|
1141
|
+
// Общая логика создания задачи вынесена в schedulerCreateTask, чтобы
|
|
1142
|
+
// schedule_task и create_task использовали один и тот же путь.
|
|
1143
|
+
const rpcRegistration = await ctx.rpc.register(SchedulerRpc, {
|
|
1144
|
+
get_tasks: async () => {
|
|
1145
|
+
return { tasks: await collectTasksView() };
|
|
1146
|
+
},
|
|
1147
|
+
create_task: async (input) => {
|
|
1148
|
+
console.log("[windows-scheduler] create_task input:", input);
|
|
1149
|
+
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, } = input;
|
|
1150
|
+
try {
|
|
1151
|
+
await schedulerCreateTask(name, schedule, prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix);
|
|
1152
|
+
return { success: true, message: `Задача "${name}" успешно создана.` };
|
|
1153
|
+
}
|
|
1154
|
+
catch (err) {
|
|
1155
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1156
|
+
return { success: false, message };
|
|
1157
|
+
}
|
|
1158
|
+
},
|
|
1159
|
+
delete_task: async (input) => {
|
|
1160
|
+
const { name } = input;
|
|
1161
|
+
try {
|
|
1162
|
+
const { removed } = await deleteTaskWithFamily(name);
|
|
1163
|
+
return {
|
|
1164
|
+
success: true,
|
|
1165
|
+
message: removed.length > 0
|
|
1166
|
+
? `Матрица "${name}" удалена вместе с ${removed.length} задачами (клоны и агрегатор).`
|
|
1167
|
+
: `Задача "${name}" успешно удалена.`,
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
catch (err) {
|
|
1171
|
+
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
1172
|
+
}
|
|
1173
|
+
},
|
|
1174
|
+
cancel_matrix: async (input) => {
|
|
1175
|
+
const { name } = input;
|
|
1176
|
+
try {
|
|
1177
|
+
const result = await cancelMatrixRun(name);
|
|
1178
|
+
return {
|
|
1179
|
+
success: true,
|
|
1180
|
+
message: result.message,
|
|
1181
|
+
cancelled: result.cancelled,
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
catch (err) {
|
|
1185
|
+
return {
|
|
1186
|
+
success: false,
|
|
1187
|
+
message: err instanceof Error ? err.message : String(err),
|
|
1188
|
+
cancelled: [],
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
},
|
|
1192
|
+
cleanup_matrix_orphans: async () => {
|
|
1193
|
+
try {
|
|
1194
|
+
const removed = await cleanupOrphanedMatrixTasks();
|
|
1195
|
+
return {
|
|
1196
|
+
success: true,
|
|
1197
|
+
message: removed.length > 0
|
|
1198
|
+
? `Удалено осиротевших задач: ${removed.length}.`
|
|
1199
|
+
: "Осиротевших задач не найдено.",
|
|
1200
|
+
removed,
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
catch (err) {
|
|
1204
|
+
return {
|
|
1205
|
+
success: false,
|
|
1206
|
+
message: err instanceof Error ? err.message : String(err),
|
|
1207
|
+
removed: [],
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
},
|
|
1211
|
+
run_task: async (input) => {
|
|
1212
|
+
const { name } = input;
|
|
1213
|
+
try {
|
|
1214
|
+
// Matrix-родитель не выполняется сам: запускаем его клоны (fan-out).
|
|
1215
|
+
const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
|
|
1216
|
+
if (definition?.matrix) {
|
|
1217
|
+
const matrixResult = await runMatrix(definition);
|
|
1218
|
+
const total = definition.matrix.workspaceIds.length;
|
|
1219
|
+
const message = `Матрица "${name}": запущено ${matrixResult.started.length} из ${total}` +
|
|
1220
|
+
(matrixResult.skipped.length ? `, пропущено ${matrixResult.skipped.length}` : "") +
|
|
1221
|
+
(matrixResult.errors.length ? `. Ошибки: ${matrixResult.errors.join("; ")}` : ".");
|
|
1222
|
+
return { success: matrixResult.success, message };
|
|
1223
|
+
}
|
|
1224
|
+
// Контроль параллелизма: не позволяем запускать новую задачу,
|
|
1225
|
+
// если уже running столько же (или больше), сколько maxConcurrent.
|
|
1226
|
+
const settings = await loadSettings();
|
|
1227
|
+
if (settings.maxConcurrent > 0) {
|
|
1228
|
+
const allTasks = await scheduler.listTasks();
|
|
1229
|
+
const runningCount = allTasks.filter((t) => /running|выполняется/i.test(t.status ?? "")).length;
|
|
1230
|
+
if (runningCount >= settings.maxConcurrent) {
|
|
1231
|
+
return {
|
|
1232
|
+
success: false,
|
|
1233
|
+
message: "Достигнут лимит одновременных задач. Дождитесь завершения текущих.",
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
const result = await scheduler.runTask(name);
|
|
1238
|
+
// История и метрики пишутся PowerShell-обёрткой (ps-wrapper.ts) при любом запуске,
|
|
1239
|
+
// в том числе инициированном из GUI, — дублировать запись здесь не нужно.
|
|
1240
|
+
if (result.alreadyRunning) {
|
|
1241
|
+
// Мягкое предупреждение: задача уже идёт, это не ошибка запуска.
|
|
1242
|
+
return { success: true, message: `Задача "${name}" уже выполняется.` };
|
|
1243
|
+
}
|
|
1244
|
+
return { success: true, message: `Задача "${name}" запущена.` };
|
|
1245
|
+
}
|
|
1246
|
+
catch (err) {
|
|
1247
|
+
return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
|
|
1248
|
+
}
|
|
1249
|
+
},
|
|
1250
|
+
emit_event: async (input) => {
|
|
1251
|
+
const { eventName, payload } = input;
|
|
1252
|
+
const normalized = eventName?.trim();
|
|
1253
|
+
if (!normalized) {
|
|
1254
|
+
return { success: false, message: "Не передано имя события (eventName).", triggered: [] };
|
|
1255
|
+
}
|
|
1256
|
+
// Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
|
|
1257
|
+
const definitions = await loadTaskDefinitions();
|
|
1258
|
+
const matched = definitions
|
|
1259
|
+
.filter((def) => (def.triggerType ?? "cron") === "mcp-event")
|
|
1260
|
+
.filter((def) => def.mcpEvent?.event?.trim().toLowerCase() === normalized.toLowerCase())
|
|
1261
|
+
.filter((def) => matchesEventFilter(def.mcpEvent?.filter, payload))
|
|
1262
|
+
.sort((a, b) => (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5));
|
|
1263
|
+
const triggered = [];
|
|
1264
|
+
for (const def of matched) {
|
|
1265
|
+
try {
|
|
1266
|
+
await scheduler.runTask(def.name);
|
|
1267
|
+
triggered.push(def.name);
|
|
1268
|
+
console.log(`[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`);
|
|
1269
|
+
}
|
|
1270
|
+
catch (err) {
|
|
1271
|
+
console.error(`[windows-scheduler] Не удалось запустить "${def.name}" по событию "${normalized}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
return {
|
|
1275
|
+
success: true,
|
|
1276
|
+
triggered,
|
|
1277
|
+
message: `Событие "${normalized}" обработано. Запущено задач: ${triggered.length}.`,
|
|
1278
|
+
};
|
|
1279
|
+
},
|
|
1280
|
+
pause_task: async (input) => {
|
|
1281
|
+
const { name } = input;
|
|
1282
|
+
const result = await pauseOrResumeTask(name, true);
|
|
1283
|
+
return { success: result.success, message: result.message };
|
|
1284
|
+
},
|
|
1285
|
+
resume_task: async (input) => {
|
|
1286
|
+
const { name } = input;
|
|
1287
|
+
const result = await pauseOrResumeTask(name, false);
|
|
1288
|
+
return { success: result.success, message: result.message };
|
|
1289
|
+
},
|
|
1290
|
+
update_task: async (input) => {
|
|
1291
|
+
return await updateTaskFromInput(input);
|
|
1292
|
+
},
|
|
1293
|
+
get_task_logs: async (input) => {
|
|
1294
|
+
const { name } = input;
|
|
1295
|
+
const result = await getTaskLogs(name);
|
|
1296
|
+
if (result.error) {
|
|
1297
|
+
return { success: false, logs: "", error: result.error };
|
|
1298
|
+
}
|
|
1299
|
+
return { success: true, logs: result.logs };
|
|
1300
|
+
},
|
|
1301
|
+
get_history: async (input) => {
|
|
1302
|
+
const { limit } = input;
|
|
1303
|
+
const records = await loadHistory();
|
|
1304
|
+
return { records: records.slice(0, limit ?? 10) };
|
|
1305
|
+
},
|
|
1306
|
+
get_metrics: async () => {
|
|
1307
|
+
return await loadMetrics();
|
|
1308
|
+
},
|
|
1309
|
+
get_dashboard_port: async () => {
|
|
1310
|
+
return { port: getDashboardPort() };
|
|
1311
|
+
},
|
|
1312
|
+
get_platform: async () => {
|
|
1313
|
+
return { platform: scheduler.platform, title: scheduler.title };
|
|
1314
|
+
},
|
|
1315
|
+
dry_run: async (input) => {
|
|
1316
|
+
const { taskName } = input;
|
|
1317
|
+
try {
|
|
1318
|
+
const report = await simulatePipeline(taskName);
|
|
1319
|
+
return { ...report };
|
|
1320
|
+
}
|
|
1321
|
+
catch (err) {
|
|
1322
|
+
return {
|
|
1323
|
+
success: false,
|
|
1324
|
+
taskName,
|
|
1325
|
+
tasks: [],
|
|
1326
|
+
totals: { estimatedDurationSec: null, estimatedCostUsd: null, estimatedTokens: null },
|
|
1327
|
+
warnings: [],
|
|
1328
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
},
|
|
1332
|
+
dry_run_all: async () => {
|
|
1333
|
+
const tasks = await loadTaskDefinitions();
|
|
1334
|
+
const reports = [];
|
|
1335
|
+
let allSuccess = true;
|
|
1336
|
+
for (const task of tasks) {
|
|
1337
|
+
try {
|
|
1338
|
+
reports.push(await simulatePipeline(task.name));
|
|
1339
|
+
}
|
|
1340
|
+
catch (err) {
|
|
1341
|
+
allSuccess = false;
|
|
1342
|
+
reports.push({
|
|
1343
|
+
success: false,
|
|
1344
|
+
taskName: task.name,
|
|
1345
|
+
tasks: [],
|
|
1346
|
+
totals: { estimatedDurationSec: null, estimatedCostUsd: null, estimatedTokens: null },
|
|
1347
|
+
warnings: [],
|
|
1348
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return { success: allSuccess, reports };
|
|
1353
|
+
},
|
|
1354
|
+
get_matrix_results: async (input) => {
|
|
1355
|
+
const { parentId } = input;
|
|
1356
|
+
const target = (parentId ?? "").trim();
|
|
1357
|
+
if (!target) {
|
|
1358
|
+
return { success: false, error: "Не передан parentId матрицы." };
|
|
1359
|
+
}
|
|
1360
|
+
try {
|
|
1361
|
+
const report = aggregateMatrixResults(target);
|
|
1362
|
+
return { success: true, report };
|
|
1363
|
+
}
|
|
1364
|
+
catch (err) {
|
|
1365
|
+
return {
|
|
1366
|
+
success: false,
|
|
1367
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
},
|
|
1371
|
+
expand_matrix_preview: async (input) => {
|
|
1372
|
+
const { name, workspaceIds, strategy, failureMode, aggregation } = input;
|
|
1373
|
+
try {
|
|
1374
|
+
const clones = expandMatrixTask({
|
|
1375
|
+
name: (name ?? "").trim() || "task",
|
|
1376
|
+
schedule: "* * * * *",
|
|
1377
|
+
prompt: "preview",
|
|
1378
|
+
matrix: {
|
|
1379
|
+
workspaceIds: Array.isArray(workspaceIds) ? workspaceIds : [],
|
|
1380
|
+
strategy,
|
|
1381
|
+
failureMode,
|
|
1382
|
+
aggregation,
|
|
1383
|
+
},
|
|
1384
|
+
});
|
|
1385
|
+
return {
|
|
1386
|
+
success: true,
|
|
1387
|
+
clones: clones.map((clone) => ({
|
|
1388
|
+
name: clone.name,
|
|
1389
|
+
workspaceId: clone.workspaceId ?? "",
|
|
1390
|
+
workspaceName: clone.workspaceId
|
|
1391
|
+
? getWorkspace(clone.workspaceId)?.name ?? null
|
|
1392
|
+
: null,
|
|
1393
|
+
})),
|
|
1394
|
+
};
|
|
1395
|
+
}
|
|
1396
|
+
catch (err) {
|
|
1397
|
+
return {
|
|
1398
|
+
success: false,
|
|
1399
|
+
clones: [],
|
|
1400
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
},
|
|
1404
|
+
get_workspaces: async () => {
|
|
1405
|
+
return {
|
|
1406
|
+
workspaces: listWorkspaces().map((workspace) => ({
|
|
1407
|
+
...workspace,
|
|
1408
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
1409
|
+
})),
|
|
1410
|
+
};
|
|
1411
|
+
},
|
|
1412
|
+
add_workspace: async (input) => {
|
|
1413
|
+
try {
|
|
1414
|
+
const { name, path: workspacePath, color } = input;
|
|
1415
|
+
const workspace = addWorkspace({ name, path: workspacePath, color });
|
|
1416
|
+
return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
|
|
1417
|
+
}
|
|
1418
|
+
catch (err) {
|
|
1419
|
+
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
1420
|
+
}
|
|
1421
|
+
},
|
|
1422
|
+
update_workspace: async (input) => {
|
|
1423
|
+
try {
|
|
1424
|
+
const { id, name, path: workspacePath, color } = input;
|
|
1425
|
+
const workspace = updateWorkspace(id, { name, path: workspacePath, color });
|
|
1426
|
+
if (!workspace) {
|
|
1427
|
+
return { success: false, error: "Workspace не найден." };
|
|
1428
|
+
}
|
|
1429
|
+
return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
|
|
1430
|
+
}
|
|
1431
|
+
catch (err) {
|
|
1432
|
+
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
1433
|
+
}
|
|
1434
|
+
},
|
|
1435
|
+
delete_workspace: async (input) => {
|
|
1436
|
+
try {
|
|
1437
|
+
const { id } = input;
|
|
1438
|
+
const deleted = deleteWorkspace(id);
|
|
1439
|
+
return {
|
|
1440
|
+
success: deleted,
|
|
1441
|
+
message: deleted
|
|
1442
|
+
? "Workspace удалён. Задачи сохранены, привязка очищена."
|
|
1443
|
+
: "Workspace не найден.",
|
|
1444
|
+
};
|
|
1445
|
+
}
|
|
1446
|
+
catch (err) {
|
|
1447
|
+
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
1448
|
+
}
|
|
1449
|
+
},
|
|
1450
|
+
get_settings: async () => {
|
|
1451
|
+
return await loadSettings();
|
|
1452
|
+
},
|
|
1453
|
+
save_settings: async (input) => {
|
|
1454
|
+
const { maxConcurrent, winterMode, notifications } = input;
|
|
1455
|
+
const current = await loadSettings();
|
|
1456
|
+
if (maxConcurrent === undefined &&
|
|
1457
|
+
winterMode === undefined &&
|
|
1458
|
+
notifications === undefined) {
|
|
1459
|
+
return {
|
|
1460
|
+
success: false,
|
|
1461
|
+
maxConcurrent: current.maxConcurrent,
|
|
1462
|
+
winterMode: current.winterMode,
|
|
1463
|
+
notifications: current.notifications,
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
const settings = await saveSettings({ maxConcurrent, winterMode, notifications });
|
|
1467
|
+
return {
|
|
1468
|
+
success: true,
|
|
1469
|
+
maxConcurrent: settings.maxConcurrent,
|
|
1470
|
+
winterMode: settings.winterMode,
|
|
1471
|
+
notifications: settings.notifications,
|
|
1472
|
+
};
|
|
1473
|
+
},
|
|
1474
|
+
test_notification: async () => {
|
|
1475
|
+
return await sendTestNotification();
|
|
1476
|
+
},
|
|
1477
|
+
get_templates: async () => {
|
|
1478
|
+
try {
|
|
1479
|
+
return { templates: await loadTemplates() };
|
|
1480
|
+
}
|
|
1481
|
+
catch (err) {
|
|
1482
|
+
console.error("[windows-scheduler] get_templates error:", err);
|
|
1483
|
+
return { templates: [] };
|
|
1484
|
+
}
|
|
1485
|
+
},
|
|
1486
|
+
save_template: async (input) => {
|
|
1487
|
+
try {
|
|
1488
|
+
const source = input;
|
|
1489
|
+
if (!source?.name?.trim() || !source?.prompt?.trim()) {
|
|
1490
|
+
return {
|
|
1491
|
+
success: false,
|
|
1492
|
+
error: "Нужны непустые название шаблона и промпт.",
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
const template = await saveTemplate({
|
|
1496
|
+
...source,
|
|
1497
|
+
name: source.name,
|
|
1498
|
+
prompt: source.prompt,
|
|
1499
|
+
triggerType: source.triggerType === "file"
|
|
1500
|
+
? "file"
|
|
1501
|
+
: source.triggerType === "mcp-event"
|
|
1502
|
+
? "mcp-event"
|
|
1503
|
+
: source.triggerType
|
|
1504
|
+
? "cron"
|
|
1505
|
+
: undefined,
|
|
1506
|
+
});
|
|
1507
|
+
return { success: true, template };
|
|
1508
|
+
}
|
|
1509
|
+
catch (err) {
|
|
1510
|
+
return {
|
|
1511
|
+
success: false,
|
|
1512
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
},
|
|
1516
|
+
delete_template: async (input) => {
|
|
1517
|
+
const { id } = input;
|
|
1518
|
+
if (!id) {
|
|
1519
|
+
return { success: false, error: "Не передан id шаблона." };
|
|
1520
|
+
}
|
|
1521
|
+
try {
|
|
1522
|
+
await deleteTemplate(id);
|
|
1523
|
+
return { success: true };
|
|
1524
|
+
}
|
|
1525
|
+
catch (err) {
|
|
1526
|
+
return {
|
|
1527
|
+
success: false,
|
|
1528
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
},
|
|
1532
|
+
export_tasks: async (input) => {
|
|
1533
|
+
try {
|
|
1534
|
+
const tasks = await scheduler.listTasks();
|
|
1535
|
+
const exportTasks = tasks.map((t) => ({
|
|
1536
|
+
...t,
|
|
1537
|
+
name: t.taskName || "",
|
|
1538
|
+
}));
|
|
1539
|
+
const { data, count } = await buildExportJson(exportTasks);
|
|
1540
|
+
return { success: true, data, count };
|
|
1541
|
+
}
|
|
1542
|
+
catch (err) {
|
|
1543
|
+
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
1544
|
+
}
|
|
1545
|
+
},
|
|
1546
|
+
import_tasks: async (input) => {
|
|
1547
|
+
const { data } = input;
|
|
1548
|
+
if (!data) {
|
|
1549
|
+
return { success: false, error: "Не переданы данные для импорта." };
|
|
1550
|
+
}
|
|
1551
|
+
try {
|
|
1552
|
+
const parsed = parseImportJson(data);
|
|
1553
|
+
if (parsed.tasks.length === 0) {
|
|
1554
|
+
return {
|
|
1555
|
+
success: false,
|
|
1556
|
+
error: "В файле нет задач для импорта.",
|
|
1557
|
+
errors: parsed.errors,
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
const imported = [];
|
|
1561
|
+
const errors = [...parsed.errors];
|
|
1562
|
+
for (const def of parsed.tasks) {
|
|
1563
|
+
try {
|
|
1564
|
+
await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId);
|
|
1565
|
+
await saveTaskDefinition(def);
|
|
1566
|
+
imported.push(def.name);
|
|
1567
|
+
}
|
|
1568
|
+
catch (err) {
|
|
1569
|
+
errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
return {
|
|
1573
|
+
success: imported.length > 0,
|
|
1574
|
+
imported: imported.length,
|
|
1575
|
+
errors: errors.length ? errors : undefined,
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
catch (err) {
|
|
1579
|
+
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
1580
|
+
}
|
|
1581
|
+
},
|
|
1582
|
+
});
|
|
1583
|
+
// Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
|
|
1584
|
+
// чьи родители были удалены в прошлых сессиях.
|
|
1585
|
+
void cleanupOrphanedMatrixTasks().catch((err) => {
|
|
1586
|
+
console.log(`[matrix] Не удалось очистить осиротевшие задачи: ${err instanceof Error ? err.message : String(err)}`);
|
|
1587
|
+
});
|
|
1588
|
+
// Локальный веб-дашборд (Спринт 5): HTTP-сервер на 3782 (фолбэки 4782/5782).
|
|
1589
|
+
// Повторный вызов не создаёт второй сервер — защита от двойного запуска
|
|
1590
|
+
// реализована внутри startDashboardServer.
|
|
1591
|
+
const dashboard = await startDashboardServer({
|
|
1592
|
+
getTasks: collectTasksView,
|
|
1593
|
+
runTask: (name) => runTaskEntry(name),
|
|
1594
|
+
deleteTask: async (name) => {
|
|
1595
|
+
await deleteTaskWithFamily(name);
|
|
1596
|
+
},
|
|
1597
|
+
cancelMatrix: (name) => cancelMatrixRun(name),
|
|
1598
|
+
cleanupMatrixOrphans: () => cleanupOrphanedMatrixTasks(),
|
|
1599
|
+
});
|
|
1600
|
+
if (dashboard) {
|
|
1601
|
+
console.log(`[windows-scheduler] Открыть дашборд в браузере: http://localhost:${dashboard.port}`);
|
|
1602
|
+
}
|
|
1603
|
+
return () => {
|
|
1604
|
+
rpcRegistration.dispose();
|
|
1605
|
+
registration.dispose();
|
|
1606
|
+
void skillRegistration?.dispose();
|
|
1607
|
+
void fileWatcherManager.stop();
|
|
1608
|
+
// При выгрузке плагина обязательно закрываем HTTP-сервер дашборда,
|
|
1609
|
+
// затем соединение SQLite (чекпойнт WAL выполняется в closeDb).
|
|
1610
|
+
void closeDashboardServer().finally(() => closeDb());
|
|
1611
|
+
};
|
|
1612
|
+
},
|
|
1613
|
+
});
|
|
1614
|
+
/**
|
|
1615
|
+
* Дополнительные настройки матрицы (Спринт 17): matrix.concurrency и
|
|
1616
|
+
* matrix.overrides. Валидирует и нормализует, бросая понятные ошибки.
|
|
1617
|
+
*/
|
|
1618
|
+
function resolveMatrixExtraConfig(name, matrix, ids) {
|
|
1619
|
+
const extra = {};
|
|
1620
|
+
if (matrix.concurrency !== undefined && matrix.concurrency !== null) {
|
|
1621
|
+
if (typeof matrix.concurrency !== "number" ||
|
|
1622
|
+
!Number.isFinite(matrix.concurrency) ||
|
|
1623
|
+
matrix.concurrency < 1) {
|
|
1624
|
+
throw new Error(`Задача "${name}": matrix.concurrency должен быть числом не меньше 1.`);
|
|
1625
|
+
}
|
|
1626
|
+
extra.concurrency = Math.floor(matrix.concurrency);
|
|
1627
|
+
}
|
|
1628
|
+
if (matrix.overrides) {
|
|
1629
|
+
const allowed = new Set(ids);
|
|
1630
|
+
const overrides = {};
|
|
1631
|
+
for (const [key, value] of Object.entries(matrix.overrides)) {
|
|
1632
|
+
const workspaceKey = key.trim();
|
|
1633
|
+
if (!allowed.has(workspaceKey)) {
|
|
1634
|
+
throw new Error(`Задача "${name}": matrix.overrides содержит workspace "${workspaceKey}", ` +
|
|
1635
|
+
`которого нет в workspaceIds.`);
|
|
1636
|
+
}
|
|
1637
|
+
if (!value || typeof value !== "object")
|
|
1638
|
+
continue;
|
|
1639
|
+
const override = {};
|
|
1640
|
+
for (const field of [
|
|
1641
|
+
"prompt",
|
|
1642
|
+
"model",
|
|
1643
|
+
"qualityGate",
|
|
1644
|
+
"beforeScript",
|
|
1645
|
+
"afterScript",
|
|
1646
|
+
]) {
|
|
1647
|
+
const raw = value[field];
|
|
1648
|
+
if (typeof raw === "string" && raw.trim())
|
|
1649
|
+
override[field] = raw.trim();
|
|
1650
|
+
}
|
|
1651
|
+
if (Object.keys(override).length > 0)
|
|
1652
|
+
overrides[workspaceKey] = override;
|
|
1653
|
+
}
|
|
1654
|
+
if (Object.keys(overrides).length > 0)
|
|
1655
|
+
extra.overrides = overrides;
|
|
1656
|
+
}
|
|
1657
|
+
return extra;
|
|
1658
|
+
}
|
|
1659
|
+
/**
|
|
1660
|
+
* Общая логика создания задачи: используется и schedule_task (инструмент),
|
|
1661
|
+
* и create_task (RPC-метод для GUI).
|
|
1662
|
+
*/
|
|
1663
|
+
async function schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, matrixParentId,
|
|
1664
|
+
/** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
|
|
1665
|
+
matrixMode = "create") {
|
|
1666
|
+
const normalizedModel = model?.trim() || undefined;
|
|
1667
|
+
const normalizedPriority = normalizePriority(priority);
|
|
1668
|
+
const normalizedBefore = beforeScript?.trim() || undefined;
|
|
1669
|
+
const normalizedAfter = afterScript?.trim() || undefined;
|
|
1670
|
+
const normalizedMcpEvent = mcpEvent && mcpEvent.event?.trim()
|
|
1671
|
+
? {
|
|
1672
|
+
server: mcpEvent.server?.trim() || "",
|
|
1673
|
+
event: mcpEvent.event.trim(),
|
|
1674
|
+
...(mcpEvent.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
|
|
1675
|
+
}
|
|
1676
|
+
: undefined;
|
|
1677
|
+
let effectiveTriggerType = triggerType ?? "cron";
|
|
1678
|
+
// Role-scoped: нормализуем списки инструментов (trim, дедуп без регистра).
|
|
1679
|
+
// Пустой allowedTools — осознанная блокировка: «белый список из нуля
|
|
1680
|
+
// инструментов» это почти наверняка ошибка конфигурации.
|
|
1681
|
+
const normalizeToolList = (raw) => {
|
|
1682
|
+
if (!Array.isArray(raw))
|
|
1683
|
+
return undefined;
|
|
1684
|
+
const cleaned = Array.from(new Map(raw
|
|
1685
|
+
.filter((t) => typeof t === "string")
|
|
1686
|
+
.map((t) => t.trim())
|
|
1687
|
+
.filter(Boolean)
|
|
1688
|
+
.map((t) => [t.toLowerCase(), t])).values());
|
|
1689
|
+
return cleaned.length > 0 ? cleaned : undefined;
|
|
1690
|
+
};
|
|
1691
|
+
if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
|
|
1692
|
+
throw new Error(`Задача "${name}": пустой allowedTools запрещён — задайте список инструментов или уберите поле.`);
|
|
1693
|
+
}
|
|
1694
|
+
const normalizedAllowedTools = normalizeToolList(allowedTools);
|
|
1695
|
+
const normalizedDeniedTools = normalizeToolList(deniedTools);
|
|
1696
|
+
// Matrix (fan-out, Спринт 15): валидируем до создания файлов, чтобы не
|
|
1697
|
+
// оставить «полу-созданную» задачу. Родитель сам не выполняется — он шаблон.
|
|
1698
|
+
let normalizedMatrix;
|
|
1699
|
+
if (matrix) {
|
|
1700
|
+
if (workspaceId?.trim()) {
|
|
1701
|
+
throw new Error(`Задача "${name}": нельзя одновременно workspaceId и matrix.workspaceIds.`);
|
|
1702
|
+
}
|
|
1703
|
+
const ids = Array.from(new Set((Array.isArray(matrix.workspaceIds) ? matrix.workspaceIds : [])
|
|
1704
|
+
.filter((id) => typeof id === "string")
|
|
1705
|
+
.map((id) => id.trim())
|
|
1706
|
+
.filter(Boolean)));
|
|
1707
|
+
if (ids.length === 0) {
|
|
1708
|
+
throw new Error(`Задача "${name}": matrix.workspaceIds не может быть пустым.`);
|
|
1709
|
+
}
|
|
1710
|
+
for (const id of ids) {
|
|
1711
|
+
const ws = getWorkspace(id);
|
|
1712
|
+
if (!ws) {
|
|
1713
|
+
throw new Error(`Задача "${name}": workspace "${id}" не найден.`);
|
|
1714
|
+
}
|
|
1715
|
+
try {
|
|
1716
|
+
validateWorkspacePath(ws.path);
|
|
1717
|
+
}
|
|
1718
|
+
catch {
|
|
1719
|
+
throw new Error(`Задача "${name}": workspace "${ws.name}" недоступен по пути "${ws.path}".`);
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
normalizedMatrix = {
|
|
1723
|
+
workspaceIds: ids,
|
|
1724
|
+
strategy: matrix.strategy === "sequential" ? "sequential" : "parallel",
|
|
1725
|
+
failureMode: matrix.failureMode === "stop" ? "stop" : "continue",
|
|
1726
|
+
aggregation: matrix.aggregation === "per-task" ? "per-task" : "summary",
|
|
1727
|
+
...(matrix.createAggregator ? { createAggregator: true } : {}),
|
|
1728
|
+
...resolveMatrixExtraConfig(name, matrix, ids),
|
|
1729
|
+
};
|
|
1730
|
+
}
|
|
1731
|
+
// Matrix-родитель и её клоны регистрируются как ручные задачи (ONCE 2099):
|
|
1732
|
+
// клоны стартует только runMatrix(), иначе cron запускал бы их независимо.
|
|
1733
|
+
if (normalizedMatrix || matrixParentId) {
|
|
1734
|
+
effectiveTriggerType = "file";
|
|
1735
|
+
}
|
|
1736
|
+
// MCP-триггер без имени события бессмыслен — валидируем до создания файлов.
|
|
1737
|
+
if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
|
|
1738
|
+
throw new Error("Для MCP-триггера нужно указать имя события (mcpEvent.event).");
|
|
1739
|
+
}
|
|
1740
|
+
// Валидируем cron-выражение до создания файлов. Для file/mcp-event
|
|
1741
|
+
// расписание не используется вовсе.
|
|
1742
|
+
if (effectiveTriggerType === "cron") {
|
|
1743
|
+
try {
|
|
1744
|
+
convertCronToSchTasks(schedule);
|
|
1745
|
+
}
|
|
1746
|
+
catch (err) {
|
|
1747
|
+
throw new Error(err.message || String(err));
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
const sanitized = sanitizeName(name);
|
|
1751
|
+
const lockFile = lockFilePath(sanitized);
|
|
1752
|
+
const logFile = path.join(LOG_DIR, `${sanitized}.log`);
|
|
1753
|
+
// Workspace имеет приоритет над workingDirectory: одна задача = один repo
|
|
1754
|
+
// = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
|
|
1755
|
+
const normalizedWorkspaceId = workspaceId?.trim() || undefined;
|
|
1756
|
+
const workspace = normalizedWorkspaceId ? getWorkspace(normalizedWorkspaceId) : undefined;
|
|
1757
|
+
if (normalizedWorkspaceId && !workspace) {
|
|
1758
|
+
throw new Error(`Workspace '${normalizedWorkspaceId}' не найден.`);
|
|
1759
|
+
}
|
|
1760
|
+
if (workspace) {
|
|
1761
|
+
try {
|
|
1762
|
+
validateWorkspacePath(workspace.path);
|
|
1763
|
+
}
|
|
1764
|
+
catch {
|
|
1765
|
+
throw new Error(`Workspace '${workspace.name}' недоступен по пути '${workspace.path}'`);
|
|
1766
|
+
}
|
|
1767
|
+
if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
|
|
1768
|
+
console.warn(`[workspace] Задача "${name}": workingDirectory "${workingDirectory.trim()}" ` +
|
|
1769
|
+
`игнорируется, cwd = workspace "${workspace.name}" (${workspace.path}).`);
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
const effectiveWorkingDirectory = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
1773
|
+
let promptFile;
|
|
1774
|
+
try {
|
|
1775
|
+
promptFile = await writePromptFile(sanitized, prompt);
|
|
1776
|
+
await fs.mkdir(LOG_DIR, { recursive: true });
|
|
1777
|
+
await fs.writeFile(logFile, "", "utf8");
|
|
1778
|
+
}
|
|
1779
|
+
catch (err) {
|
|
1780
|
+
throw new Error(`Не удалось подготовить файлы задачи: ${err.message || String(err)}`);
|
|
1781
|
+
}
|
|
1782
|
+
// Обёртка зависит от платформы:
|
|
1783
|
+
// - Windows: .cmd → PowerShell-скрипт (lock, таймаут, метрики);
|
|
1784
|
+
// - Linux/macOS: .sh с тем же набором гарантий.
|
|
1785
|
+
let wrapperPath;
|
|
1786
|
+
try {
|
|
1787
|
+
if (scheduler.platform === "win32") {
|
|
1788
|
+
await ensureWrapper();
|
|
1789
|
+
wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools);
|
|
1790
|
+
}
|
|
1791
|
+
else {
|
|
1792
|
+
wrapperPath = await writeBashWrapper({
|
|
1793
|
+
sanitizedName: sanitized,
|
|
1794
|
+
taskName: name,
|
|
1795
|
+
promptFile,
|
|
1796
|
+
timeoutSeconds: timeoutSeconds ?? 3600,
|
|
1797
|
+
lockFile,
|
|
1798
|
+
workdir: effectiveWorkingDirectory,
|
|
1799
|
+
logFile,
|
|
1800
|
+
recorderFile: recorderPath,
|
|
1801
|
+
qualityGate,
|
|
1802
|
+
model: normalizedModel,
|
|
1803
|
+
beforeScript: normalizedBefore,
|
|
1804
|
+
afterScript: normalizedAfter,
|
|
1805
|
+
workspaceName: workspace?.name,
|
|
1806
|
+
allowedTools: normalizedAllowedTools,
|
|
1807
|
+
deniedTools: normalizedDeniedTools,
|
|
1808
|
+
});
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
catch (err) {
|
|
1812
|
+
throw new Error(`Не удалось создать обёртку задачи: ${err.message || String(err)}`);
|
|
1813
|
+
}
|
|
1814
|
+
try {
|
|
1815
|
+
// Бэкенд сам преобразует cron в родное расписание ОС.
|
|
1816
|
+
await scheduler.createTask({
|
|
1817
|
+
name,
|
|
1818
|
+
command: wrapperPath,
|
|
1819
|
+
schedule,
|
|
1820
|
+
timeoutSeconds: timeoutSeconds ?? 3600,
|
|
1821
|
+
triggerType: effectiveTriggerType,
|
|
1822
|
+
workingDirectory: effectiveWorkingDirectory,
|
|
1823
|
+
logFile,
|
|
1824
|
+
model: normalizedModel,
|
|
1825
|
+
priority: normalizedPriority,
|
|
1826
|
+
});
|
|
1827
|
+
}
|
|
1828
|
+
catch (err) {
|
|
1829
|
+
throw new Error(err instanceof Error ? err.message : String(err));
|
|
1830
|
+
}
|
|
1831
|
+
// Сохраняем определение задачи для последующего экспорта/импорта.
|
|
1832
|
+
const existingQueue = matrixMode === "sync" ? getTask(name)?.matrixQueue : undefined;
|
|
1833
|
+
const taskDefinition = {
|
|
1834
|
+
name,
|
|
1835
|
+
schedule,
|
|
1836
|
+
prompt,
|
|
1837
|
+
timeoutSeconds,
|
|
1838
|
+
model: normalizedModel,
|
|
1839
|
+
priority: normalizedPriority,
|
|
1840
|
+
beforeScript: normalizedBefore,
|
|
1841
|
+
afterScript: normalizedAfter,
|
|
1842
|
+
mcpEvent: normalizedMcpEvent,
|
|
1843
|
+
workingDirectory: workspace ? undefined : workingDirectory?.trim() || undefined,
|
|
1844
|
+
workspaceId: workspace?.id,
|
|
1845
|
+
retryCount,
|
|
1846
|
+
retryDelay,
|
|
1847
|
+
qualityGate,
|
|
1848
|
+
nextTaskOnSuccess,
|
|
1849
|
+
nextTaskOnError,
|
|
1850
|
+
triggerType: effectiveTriggerType,
|
|
1851
|
+
watchPath: normalizedMatrix ? undefined : watchPath,
|
|
1852
|
+
allowedTools: normalizedAllowedTools,
|
|
1853
|
+
deniedTools: normalizedDeniedTools,
|
|
1854
|
+
matrix: normalizedMatrix,
|
|
1855
|
+
isMatrixParent: normalizedMatrix ? true : undefined,
|
|
1856
|
+
matrixParentId,
|
|
1857
|
+
// Очередь concurrency-лимита переживает обновление определения.
|
|
1858
|
+
...(existingQueue && existingQueue.length > 0
|
|
1859
|
+
? { matrixQueue: existingQueue }
|
|
1860
|
+
: {}),
|
|
1861
|
+
dependsOn: Array.isArray(dependsOn) && dependsOn.length > 0
|
|
1862
|
+
? Array.from(new Set(dependsOn
|
|
1863
|
+
.filter((dep) => typeof dep === "string")
|
|
1864
|
+
.map((dep) => dep.trim())
|
|
1865
|
+
.filter(Boolean)))
|
|
1866
|
+
: undefined,
|
|
1867
|
+
};
|
|
1868
|
+
try {
|
|
1869
|
+
await saveTaskDefinition(taskDefinition);
|
|
1870
|
+
}
|
|
1871
|
+
catch {
|
|
1872
|
+
// Не критично — основная задача уже создана.
|
|
1873
|
+
}
|
|
1874
|
+
// Matrix (fan-out): создаём клоны по workspace и, при необходимости,
|
|
1875
|
+
// виртуальную задачу matrix-complete, которая запускается DAG-движком.
|
|
1876
|
+
// Спринт 17: при обновлении (matrixMode === "sync") клоны не пересоздаются
|
|
1877
|
+
// с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
|
|
1878
|
+
if (normalizedMatrix) {
|
|
1879
|
+
const createClone = async (clone) => {
|
|
1880
|
+
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);
|
|
1881
|
+
};
|
|
1882
|
+
const removeChild = async (child) => {
|
|
1883
|
+
try {
|
|
1884
|
+
await scheduler.deleteTask(child);
|
|
1885
|
+
}
|
|
1886
|
+
catch {
|
|
1887
|
+
// Старого клона могло уже не быть в планировщике.
|
|
1888
|
+
}
|
|
1889
|
+
try {
|
|
1890
|
+
await removeTaskDefinition(child);
|
|
1891
|
+
}
|
|
1892
|
+
catch {
|
|
1893
|
+
// Не критично.
|
|
1894
|
+
}
|
|
1895
|
+
};
|
|
1896
|
+
// Создаёт/обновляет/удаляет matrix-complete по текущему определению.
|
|
1897
|
+
const syncAggregator = async () => {
|
|
1898
|
+
const aggregatorName = matrixCompleteName(name);
|
|
1899
|
+
if (!normalizedMatrix.createAggregator) {
|
|
1900
|
+
if (getTask(aggregatorName))
|
|
1901
|
+
await removeChild(aggregatorName);
|
|
1902
|
+
return undefined;
|
|
1903
|
+
}
|
|
1904
|
+
const cloneNames = listMatrixClones(name).map((clone) => clone.name);
|
|
1905
|
+
if (cloneNames.length === 0)
|
|
1906
|
+
return undefined;
|
|
1907
|
+
await schedulerCreateTask(aggregatorName, schedule, `Матрица "${name}" завершена. Проверь результаты клонов: ` +
|
|
1908
|
+
`${cloneNames.join(", ")}.`, timeoutSeconds, undefined, undefined, undefined, undefined, undefined, undefined, "file", undefined, cloneNames, normalizedModel, normalizedPriority);
|
|
1909
|
+
return aggregatorName;
|
|
1910
|
+
};
|
|
1911
|
+
if (matrixMode === "sync") {
|
|
1912
|
+
const syncResult = await syncMatrixFamily(taskDefinition, {
|
|
1913
|
+
removeChild,
|
|
1914
|
+
createChild: createClone,
|
|
1915
|
+
updateChild: createClone,
|
|
1916
|
+
syncAggregator,
|
|
1917
|
+
});
|
|
1918
|
+
if (syncResult.warnings.length > 0) {
|
|
1919
|
+
console.log(`[matrix] ${name}: ${syncResult.warnings.join(" ")}`);
|
|
1920
|
+
}
|
|
1921
|
+
if (syncResult.created.length > 0 ||
|
|
1922
|
+
syncResult.updated.length > 0 ||
|
|
1923
|
+
syncResult.removed.length > 0) {
|
|
1924
|
+
console.log(`[matrix] ${name}: синхронизация — создано ${syncResult.created.length}, ` +
|
|
1925
|
+
`обновлено ${syncResult.updated.length}, удалено ${syncResult.removed.length}, ` +
|
|
1926
|
+
`занято ${syncResult.running.length}`);
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
else {
|
|
1930
|
+
for (const child of removeMatrixChildren(name)) {
|
|
1931
|
+
await removeChild(child);
|
|
1932
|
+
}
|
|
1933
|
+
const clones = expandMatrixTask(taskDefinition);
|
|
1934
|
+
for (const clone of clones) {
|
|
1935
|
+
await createClone(clone);
|
|
1936
|
+
}
|
|
1937
|
+
await syncAggregator();
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
|
|
1943
|
+
* на клоны, а не выполняет свой промпт.
|
|
1944
|
+
*/
|
|
1945
|
+
async function runTaskEntry(name) {
|
|
1946
|
+
const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
|
|
1947
|
+
if (definition?.matrix) {
|
|
1948
|
+
await runMatrix(definition);
|
|
1949
|
+
return { alreadyRunning: false };
|
|
1950
|
+
}
|
|
1951
|
+
return scheduler.runTask(name);
|
|
1952
|
+
}
|
|
1953
|
+
/**
|
|
1954
|
+
* Собирает задачи плагина в формате, который отдают оба потребителя:
|
|
1955
|
+
* RPC get_tasks (GUI) и инструмент list_tasks (агент).
|
|
1956
|
+
*/
|
|
1957
|
+
async function collectTasksView() {
|
|
1958
|
+
const tasks = await scheduler.listTasks();
|
|
1959
|
+
// Читаем историю один раз, чтобы определить финальный статус по последней записи.
|
|
1960
|
+
const history = await loadHistory();
|
|
1961
|
+
const lastByTask = new Map();
|
|
1962
|
+
for (const record of history) {
|
|
1963
|
+
lastByTask.set(record.taskName, {
|
|
1964
|
+
status: record.status,
|
|
1965
|
+
error: record.error,
|
|
1966
|
+
});
|
|
1967
|
+
}
|
|
1968
|
+
// Читаем определения задач один раз (расписание, повторы, цепочки, директория).
|
|
1969
|
+
const defs = await loadTaskDefinitions();
|
|
1970
|
+
const workspaces = listWorkspaces();
|
|
1971
|
+
const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
1972
|
+
return tasks.map((t) => {
|
|
1973
|
+
// Все бэкенды возвращают короткие имена (без папки планировщика).
|
|
1974
|
+
const name = t.taskName || "";
|
|
1975
|
+
// Приоритет 1: статус, который сообщает планировщик ОС.
|
|
1976
|
+
let status = mapStatus(t.status);
|
|
1977
|
+
// Приоритет 2: если последняя запись в истории — error/timeout, перебиваем на error.
|
|
1978
|
+
const last = lastByTask.get(name);
|
|
1979
|
+
if (last && (last.status === "error" || last.status === "timeout")) {
|
|
1980
|
+
status = "error";
|
|
1981
|
+
}
|
|
1982
|
+
else if (last && last.status === "success") {
|
|
1983
|
+
status = "success";
|
|
1984
|
+
}
|
|
1985
|
+
const def = defs.find((d) => d.name.toLowerCase() === name.toLowerCase());
|
|
1986
|
+
const workspace = def?.workspaceId ? workspaceById.get(def.workspaceId) : undefined;
|
|
1987
|
+
// Matrix-родитель: статус = агрегат по клонам (success/error/partial/running).
|
|
1988
|
+
const matrixAggregate = def?.matrix ? aggregateMatrixResults(name) : null;
|
|
1989
|
+
if (matrixAggregate && matrixAggregate.status !== "empty") {
|
|
1990
|
+
status = matrixAggregate.status === "running" ? "running" : matrixAggregate.status;
|
|
1991
|
+
}
|
|
1992
|
+
return {
|
|
1993
|
+
name,
|
|
1994
|
+
schedule: def?.schedule ?? "",
|
|
1995
|
+
status,
|
|
1996
|
+
nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
|
|
1997
|
+
model: def?.model ?? null,
|
|
1998
|
+
priority: def?.priority ?? 5,
|
|
1999
|
+
beforeScript: def?.beforeScript ?? null,
|
|
2000
|
+
afterScript: def?.afterScript ?? null,
|
|
2001
|
+
mcpEvent: def?.mcpEvent ?? null,
|
|
2002
|
+
retryCount: def?.retryCount ?? 0,
|
|
2003
|
+
retryDelay: def?.retryDelay ?? 0,
|
|
2004
|
+
qualityGate: def?.qualityGate ?? null,
|
|
2005
|
+
nextTaskOnSuccess: def?.nextTaskOnSuccess ?? null,
|
|
2006
|
+
nextTaskOnError: def?.nextTaskOnError ?? null,
|
|
2007
|
+
dependsOn: Array.isArray(def?.dependsOn) ? def.dependsOn : [],
|
|
2008
|
+
triggerType: def?.triggerType ?? "cron",
|
|
2009
|
+
watchPath: def?.watchPath ?? null,
|
|
2010
|
+
workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
|
|
2011
|
+
workspaceId: workspace?.id ?? def?.workspaceId ?? null,
|
|
2012
|
+
workspaceName: workspace?.name ?? null,
|
|
2013
|
+
workspaceColor: workspace?.color ?? null,
|
|
2014
|
+
allowedTools: Array.isArray(def?.allowedTools) ? def.allowedTools : null,
|
|
2015
|
+
deniedTools: Array.isArray(def?.deniedTools) ? def.deniedTools : null,
|
|
2016
|
+
matrix: def?.matrix ?? null,
|
|
2017
|
+
matrixParentId: def?.matrixParentId ?? null,
|
|
2018
|
+
isMatrixParent: Boolean(def?.matrix),
|
|
2019
|
+
matrixSummary: matrixAggregate
|
|
2020
|
+
? {
|
|
2021
|
+
totalCount: matrixAggregate.totalCount,
|
|
2022
|
+
successCount: matrixAggregate.successCount,
|
|
2023
|
+
errorCount: matrixAggregate.errorCount,
|
|
2024
|
+
pendingCount: matrixAggregate.pendingCount,
|
|
2025
|
+
status: matrixAggregate.status,
|
|
2026
|
+
message: matrixAggregate.message,
|
|
2027
|
+
}
|
|
2028
|
+
: null,
|
|
2029
|
+
prompt: def?.prompt ?? "",
|
|
2030
|
+
};
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
/**
|
|
2034
|
+
* Проверяет фильтр MCP-события.
|
|
2035
|
+
*
|
|
2036
|
+
* Поддерживаются два формата:
|
|
2037
|
+
* - `key=value` — сравнивается с верхнеуровневым полем payload (регистр значения важен);
|
|
2038
|
+
* - regex/подстрока — проверяется по сериализованному payload (без учёта регистра).
|
|
2039
|
+
* Пустой фильтр пропускает любое событие.
|
|
2040
|
+
*/
|
|
2041
|
+
function matchesEventFilter(filter, payload) {
|
|
2042
|
+
const raw = (filter ?? "").trim();
|
|
2043
|
+
if (!raw)
|
|
2044
|
+
return true;
|
|
2045
|
+
let text;
|
|
2046
|
+
try {
|
|
2047
|
+
text = JSON.stringify(payload ?? {});
|
|
2048
|
+
}
|
|
2049
|
+
catch {
|
|
2050
|
+
text = String(payload ?? "");
|
|
2051
|
+
}
|
|
2052
|
+
const pair = /^([A-Za-z0-9_.-]+)\s*=\s*(.*)$/.exec(raw);
|
|
2053
|
+
if (pair && payload !== null && typeof payload === "object") {
|
|
2054
|
+
const fieldValue = payload[pair[1]];
|
|
2055
|
+
const expected = pair[2].trim().replace(/^["']|["']$/g, "");
|
|
2056
|
+
return String(fieldValue ?? "") === expected;
|
|
2057
|
+
}
|
|
2058
|
+
try {
|
|
2059
|
+
return new RegExp(raw, "i").test(text);
|
|
2060
|
+
}
|
|
2061
|
+
catch {
|
|
2062
|
+
return text.toLowerCase().includes(raw.toLowerCase());
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
/** Превращает текстовый статус планировщика в короткий статус для GUI. */
|
|
2066
|
+
function mapStatus(status) {
|
|
2067
|
+
if (!status)
|
|
2068
|
+
return "unknown";
|
|
2069
|
+
const s = status.toLowerCase();
|
|
2070
|
+
if (s.includes("running") || s.includes("выполняется"))
|
|
2071
|
+
return "running";
|
|
2072
|
+
if (s.includes("ready") || s.includes("готов"))
|
|
2073
|
+
return "success";
|
|
2074
|
+
if (s.includes("disabled"))
|
|
2075
|
+
return "unknown";
|
|
2076
|
+
return "unknown";
|
|
2077
|
+
}
|