agent-steward 0.0.5 → 0.0.6
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 +176 -1
- package/README.md +9 -7
- package/ROADMAP-STRATEGY.md +5 -5
- package/ROADMAP.md +107 -17
- package/dist/cli.js +5 -0
- package/dist/core/analytics.d.ts +6 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +20 -3
- package/dist/core/audit.d.ts +6 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +24 -0
- package/dist/core/budget.d.ts +118 -0
- package/dist/core/budget.d.ts.map +1 -0
- package/dist/core/budget.js +206 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +38 -0
- package/dist/core/dry-run.d.ts +26 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +199 -8
- package/dist/core/feedback.d.ts +192 -0
- package/dist/core/feedback.d.ts.map +1 -0
- package/dist/core/feedback.js +426 -0
- package/dist/core/gate-integrity.d.ts +36 -0
- package/dist/core/gate-integrity.d.ts.map +1 -1
- package/dist/core/gate-integrity.js +144 -1
- package/dist/core/local-ai.d.ts.map +1 -1
- package/dist/core/local-ai.js +7 -3
- package/dist/core/matrix.d.ts +8 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +57 -2
- package/dist/core/mission.d.ts +20 -0
- package/dist/core/mission.d.ts.map +1 -1
- package/dist/core/mission.js +45 -5
- package/dist/core/opencode-models.d.ts +2 -2
- package/dist/core/opencode-models.d.ts.map +1 -1
- package/dist/core/opencode-models.js +28 -21
- package/dist/core/opencode-usage.d.ts +35 -0
- package/dist/core/opencode-usage.d.ts.map +1 -0
- package/dist/core/opencode-usage.js +132 -0
- package/dist/core/pipeline-io.d.ts +1 -1
- package/dist/core/pipeline-io.d.ts.map +1 -1
- package/dist/core/pipeline-io.js +26 -12
- package/dist/core/pipeline-map.d.ts +6 -0
- package/dist/core/pipeline-map.d.ts.map +1 -1
- package/dist/core/pipeline-map.js +12 -0
- package/dist/core/ps-wrapper.d.ts +10 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +176 -5
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +76 -4
- package/dist/core/run-mode.d.ts +12 -0
- package/dist/core/run-mode.d.ts.map +1 -0
- package/dist/core/run-mode.js +17 -0
- package/dist/core/scheduler/logs.d.ts +4 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -1
- package/dist/core/scheduler/logs.js +25 -1
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +18 -8
- package/dist/core/self-analysis.d.ts +32 -2
- package/dist/core/self-analysis.d.ts.map +1 -1
- package/dist/core/self-analysis.js +38 -27
- package/dist/core/shutdown.d.ts +33 -2
- package/dist/core/shutdown.d.ts.map +1 -1
- package/dist/core/shutdown.js +58 -2
- package/dist/core/structured-log.d.ts +30 -0
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +37 -0
- package/dist/core/usage-surface.d.ts +25 -0
- package/dist/core/usage-surface.d.ts.map +1 -0
- package/dist/core/usage-surface.js +41 -0
- package/dist/core/wrappers/bash.d.ts +2 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +58 -6
- package/dist/db/history-repo.d.ts +32 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +85 -7
- package/dist/db/metrics-repo.d.ts +20 -2
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +33 -11
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +37 -17
- package/dist/db/recovery.d.ts +3 -1
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +9 -4
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +71 -56
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +70 -1
- package/dist/db/templates-repo.d.ts +2 -2
- package/dist/db/templates-repo.d.ts.map +1 -1
- package/dist/db/templates-repo.js +5 -3
- package/dist/history.d.ts +6 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +4 -2
- package/dist/hook-output.d.ts +2 -0
- package/dist/hook-output.d.ts.map +1 -0
- package/dist/hook-output.js +31 -0
- package/dist/index.d.ts +247 -53
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +999 -211
- package/dist/notifications.d.ts +31 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +132 -13
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +66 -15
- package/dist/rpc.d.ts +108 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +28 -0
- package/dist/server.d.ts +17 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +77 -12
- package/dist/settings.d.ts +42 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +82 -0
- package/dist/task-transfer.d.ts +5 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +48 -3
- package/dist/templates.d.ts +2 -2
- package/dist/templates.d.ts.map +1 -1
- package/dist/templates.js +3 -3
- package/dist/types.d.ts +22 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +34 -11
- package/docs/ARCHITECTURE.md +49 -12
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/EXECUTION-LOOP.md +6 -3
- package/docs/FEATURES.md +65 -4
- package/docs/FEATURES.zh.md +45 -2
- package/docs/QA-A2-GUI-TUI.md +205 -0
- package/docs/README.ru.md +3 -3
- package/docs/README.zh.md +2 -2
- package/gui-experimental.cjs +9 -9
- package/locales/en.json +42 -3
- package/locales/ru.json +42 -3
- package/locales/zh.json +42 -3
- package/package.json +15 -2
- package/scripts/check-eslint-baseline.mjs +139 -0
- package/scripts/gen-test-plan-counters.mjs +117 -0
- package/scripts/github-ci-fetch.ps1 +37 -0
- package/scripts/pl-commit.ps1 +112 -0
- package/scripts/qa-a2-commit.ps1 +104 -0
- package/scripts/test-home.mjs +26 -2
- package/skills/scheduled-job-best-practices/SKILL.md +95 -1
- package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
- package/src/cli.ts +5 -0
- package/src/core/analytics.ts +27 -4
- package/src/core/audit.ts +25 -0
- package/src/core/budget.ts +340 -0
- package/src/core/cron-to-schtasks.ts +42 -0
- package/src/core/dry-run.ts +233 -10
- package/src/core/feedback.ts +582 -0
- package/src/core/gate-integrity.ts +171 -1
- package/src/core/local-ai.ts +7 -3
- package/src/core/matrix.ts +63 -2
- package/src/core/mission.ts +51 -5
- package/src/core/opencode-models.ts +30 -21
- package/src/core/opencode-usage.ts +182 -0
- package/src/core/pipeline-io.ts +28 -11
- package/src/core/pipeline-map.ts +19 -0
- package/src/core/ps-wrapper.ts +173 -4
- package/src/core/record-history.ts +94 -4
- package/src/core/run-mode.ts +19 -0
- package/src/core/scheduler/logs.ts +32 -1
- package/src/core/secrets.ts +18 -11
- package/src/core/self-analysis.ts +75 -29
- package/src/core/shutdown.ts +90 -4
- package/src/core/structured-log.ts +67 -0
- package/src/core/usage-surface.ts +70 -0
- package/src/core/wrappers/bash.ts +60 -5
- package/src/db/history-repo.ts +153 -19
- package/src/db/metrics-repo.ts +38 -11
- package/src/db/migrate.ts +57 -32
- package/src/db/recovery.ts +10 -4
- package/src/db/runs-repo.ts +113 -61
- package/src/db/schema.ts +70 -1
- package/src/db/templates-repo.ts +5 -3
- package/src/gui.tsx +261 -5
- package/src/history.ts +10 -3
- package/src/hook-output.ts +39 -0
- package/src/index.ts +1407 -345
- package/src/notifications.ts +189 -39
- package/src/profiles.ts +72 -16
- package/src/rpc.ts +30 -0
- package/src/server.ts +107 -23
- package/src/settings.ts +120 -0
- package/src/task-transfer.ts +59 -6
- package/src/templates.ts +3 -3
- package/src/types.ts +23 -2
- package/src/workspaces.ts +37 -14
package/src/index.ts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import { Plugin, Rpc } from "@opencode/plugin";
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
type PluginModule as V1PluginModule,
|
|
2
|
+
import type {
|
|
3
|
+
Hooks as V1Hooks,
|
|
4
|
+
PluginInput as V1PluginInput,
|
|
5
|
+
PluginModule as V1PluginModule,
|
|
7
6
|
} from "@opencode-ai/plugin";
|
|
7
|
+
// V1 `tool()` — тривиальная identity-функция (`input => input`). Инлайним её,
|
|
8
|
+
// чтобы точка входа V2 не импортировала devDependency @opencode-ai/plugin:
|
|
9
|
+
// у пользователя OpenCode 2 этот пакет не установлен, и статический импорт
|
|
10
|
+
// ломал загрузку плагина целиком (ERR_MODULE_NOT_FOUND).
|
|
11
|
+
const v1Tool = <T>(input: T): T => input;
|
|
8
12
|
import { z } from "zod";
|
|
9
13
|
import type { Tool } from "@opencode/schema/tool";
|
|
14
|
+
import type { Skill } from "@opencode/schema/skill";
|
|
10
15
|
import { createRequire } from "node:module";
|
|
11
16
|
import { existsSync } from "node:fs";
|
|
12
17
|
import fs from "node:fs/promises";
|
|
@@ -35,20 +40,25 @@ import {
|
|
|
35
40
|
writeSessionStateFile,
|
|
36
41
|
type SessionMode,
|
|
37
42
|
} from "./core/session.js";
|
|
38
|
-
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
|
|
43
|
+
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun, gateAllowPathsFromAfterScript } from "./core/ps-wrapper.js";
|
|
39
44
|
import { getSchedulerBackend, LinuxScheduler } from "./core/scheduler/index.js";
|
|
40
45
|
import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
|
|
41
46
|
import { getTaskLogs } from "./core/scheduler/logs.js";
|
|
42
47
|
import { findSanitizedNameConflict, sanitizedConflictMessage } from "./core/task-name.js";
|
|
43
48
|
import { writeBashWrapper } from "./core/wrappers/bash.js";
|
|
44
49
|
import { normalizeTaskGuards, type TaskGuards } from "./core/guard.js";
|
|
45
|
-
import {
|
|
50
|
+
import {
|
|
51
|
+
simulatePipeline,
|
|
52
|
+
workingDirectoryDriftWarning,
|
|
53
|
+
type DryRunReport,
|
|
54
|
+
} from "./core/dry-run.js";
|
|
46
55
|
import {
|
|
47
56
|
aggregateMatrixResults,
|
|
48
57
|
cancelPendingMatrixClones,
|
|
49
58
|
expandMatrixTask,
|
|
50
59
|
findOrphanedMatrixTasks,
|
|
51
60
|
getMatrixDeletionGuard,
|
|
61
|
+
isKnownMatrix,
|
|
52
62
|
matrixCompleteName,
|
|
53
63
|
planMatrixFamilyDelete,
|
|
54
64
|
removeMatrixChildren,
|
|
@@ -56,7 +66,8 @@ import {
|
|
|
56
66
|
syncMatrixFamily,
|
|
57
67
|
} from "./core/matrix.js";
|
|
58
68
|
import { normalizeWatchPath, validateWatchGlobs } from "./core/watch-paths.js";
|
|
59
|
-
import { createShutdownGate } from "./core/shutdown.js";
|
|
69
|
+
import { createShutdownGate, type ShutdownGateState } from "./core/shutdown.js";
|
|
70
|
+
import { CHILD_RUN_ENV, isChildRunMode } from "./core/run-mode.js";
|
|
60
71
|
import { SchedulerRpc } from "./rpc.js";
|
|
61
72
|
import {
|
|
62
73
|
validatePipelineSpec,
|
|
@@ -72,10 +83,19 @@ import {
|
|
|
72
83
|
executePipelineApply,
|
|
73
84
|
type PipelineApplyPlan,
|
|
74
85
|
} from "./core/pipeline-apply.js";
|
|
75
|
-
import {
|
|
86
|
+
import {
|
|
87
|
+
pipelineExportLookupError,
|
|
88
|
+
pipelineSpecToTasks,
|
|
89
|
+
tasksToPipelineSpec,
|
|
90
|
+
} from "./core/pipeline-map.js";
|
|
76
91
|
import { stringify as yamlStringify } from "yaml";
|
|
77
92
|
import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
|
|
78
|
-
import {
|
|
93
|
+
import {
|
|
94
|
+
defaultNotifications,
|
|
95
|
+
loadSettings,
|
|
96
|
+
saveSettings,
|
|
97
|
+
type FeedbackSettings,
|
|
98
|
+
} from "./settings.js";
|
|
79
99
|
import { resolveLocale, setLocale, t, type Locale, type LocaleMode } from "./i18n.js";
|
|
80
100
|
import type {
|
|
81
101
|
AuditSettings,
|
|
@@ -85,7 +105,7 @@ import type {
|
|
|
85
105
|
PermissionSettings,
|
|
86
106
|
TriageSettings,
|
|
87
107
|
} from "./settings.js";
|
|
88
|
-
import { runMission, type MissionSpec } from "./core/mission.js";
|
|
108
|
+
import { formatLogRunMarker, runMission, type MissionSpec } from "./core/mission.js";
|
|
89
109
|
import {
|
|
90
110
|
DEFAULT_PERMISSION_POLICY,
|
|
91
111
|
buildOpencodeConfig,
|
|
@@ -94,8 +114,25 @@ import {
|
|
|
94
114
|
} from "./core/permissions.js";
|
|
95
115
|
import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
|
|
96
116
|
import { buildAnalytics } from "./core/analytics.js";
|
|
117
|
+
import {
|
|
118
|
+
buildBudgetReport,
|
|
119
|
+
evaluateBudgetGate,
|
|
120
|
+
evaluateTaskTokenBudgetGate,
|
|
121
|
+
formatBudgetSkipMessage,
|
|
122
|
+
formatTaskTokenBudgetSkipMessage,
|
|
123
|
+
startOfUtcWeek,
|
|
124
|
+
type BudgetGateDecision,
|
|
125
|
+
type BudgetSettings,
|
|
126
|
+
type TaskTokenBudgetDecision,
|
|
127
|
+
} from "./core/budget.js";
|
|
97
128
|
import { generateSelfAnalysisReport } from "./core/self-analysis.js";
|
|
98
|
-
import {
|
|
129
|
+
import {
|
|
130
|
+
getHistoryForAnalytics,
|
|
131
|
+
getHistoryForBudget,
|
|
132
|
+
listRunningRecords,
|
|
133
|
+
recordRun,
|
|
134
|
+
} from "./db/history-repo.js";
|
|
135
|
+
import { appendStructuredLog } from "./core/structured-log.js";
|
|
99
136
|
import { getAllMetrics } from "./db/metrics-repo.js";
|
|
100
137
|
import { discardDlq, listDlq, retryDlq } from "./core/dlq-api.js";
|
|
101
138
|
import {
|
|
@@ -106,10 +143,18 @@ import {
|
|
|
106
143
|
import {
|
|
107
144
|
findStuckMatrixClones,
|
|
108
145
|
maybeSendDigest,
|
|
146
|
+
notifyBudgetExceeded,
|
|
109
147
|
notifyStuckMatrix,
|
|
148
|
+
sendBugReport,
|
|
110
149
|
sendDigestNow,
|
|
111
150
|
sendTestNotification,
|
|
112
151
|
} from "./notifications.js";
|
|
152
|
+
import {
|
|
153
|
+
FEEDBACK_LIMITS,
|
|
154
|
+
flushOutbox,
|
|
155
|
+
redactText,
|
|
156
|
+
reportFeedback,
|
|
157
|
+
} from "./core/feedback.js";
|
|
113
158
|
import {
|
|
114
159
|
shadowReport,
|
|
115
160
|
resetShadowDecisions,
|
|
@@ -135,7 +180,13 @@ import type {
|
|
|
135
180
|
} from "./task-transfer.js";
|
|
136
181
|
import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
|
|
137
182
|
import type { TaskTemplate } from "./templates.js";
|
|
138
|
-
import {
|
|
183
|
+
import {
|
|
184
|
+
startDashboardServer,
|
|
185
|
+
closeDashboardServer,
|
|
186
|
+
getDashboardPort,
|
|
187
|
+
probeDashboardOn,
|
|
188
|
+
discoverDashboardPort,
|
|
189
|
+
} from "./server.js";
|
|
139
190
|
import {
|
|
140
191
|
DEFAULT_PROFILE,
|
|
141
192
|
createProfile,
|
|
@@ -165,11 +216,13 @@ import {
|
|
|
165
216
|
import {
|
|
166
217
|
deleteSecret,
|
|
167
218
|
collectSecretNames,
|
|
219
|
+
getSecret,
|
|
168
220
|
hasSecret,
|
|
169
221
|
listSecrets,
|
|
170
222
|
setSecret,
|
|
171
223
|
} from "./core/secrets.js";
|
|
172
224
|
import {
|
|
225
|
+
auditDateFilterError,
|
|
173
226
|
cleanupAuditLog,
|
|
174
227
|
readAuditLog,
|
|
175
228
|
recordAudit,
|
|
@@ -346,12 +399,91 @@ export const guardsSchema = z.object({
|
|
|
346
399
|
.describe("Semantic pre-run checks inside the working directory."),
|
|
347
400
|
}).describe("W-3: guard conditions. If a check fails, the run is skipped before opencode starts.");
|
|
348
401
|
|
|
402
|
+
/**
|
|
403
|
+
* QA-P2.1: маска glob не может быть пустой или содержать пробелы.
|
|
404
|
+
* Пробел в `** /*.md` молча сужает совпадение до файлов с пробелом в имени.
|
|
405
|
+
*/
|
|
406
|
+
const globMaskSchema = z.string().min(1).refine((mask) => !/\s/.test(mask), {
|
|
407
|
+
message: "Glob mask must be non-empty and contain no whitespace.",
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* QA-P2.1: единая проверка диапазонов для MCP и RPC.
|
|
412
|
+
* Zod-схемы защищают только MCP-путь; RPC (create_task/update_task) принимает
|
|
413
|
+
* сырой JSON и вызывает эту функцию явно, до normalizePriority(), который
|
|
414
|
+
* молча обрезает priority до 0..10.
|
|
415
|
+
* Возвращает текст ошибки или null.
|
|
416
|
+
*/
|
|
417
|
+
export function validateTaskInputRanges(input: {
|
|
418
|
+
prompt?: string;
|
|
419
|
+
timeoutSeconds?: number;
|
|
420
|
+
priority?: number;
|
|
421
|
+
retryCount?: number;
|
|
422
|
+
retryDelay?: number;
|
|
423
|
+
watchPath?: string;
|
|
424
|
+
triggerType?: string;
|
|
425
|
+
watchGlobs?: string[];
|
|
426
|
+
watchIgnore?: string[];
|
|
427
|
+
gitPaths?: string[];
|
|
428
|
+
gitIgnore?: string[];
|
|
429
|
+
}): string | null {
|
|
430
|
+
if (input.prompt !== undefined && !input.prompt.trim()) {
|
|
431
|
+
return "prompt must be a non-empty string.";
|
|
432
|
+
}
|
|
433
|
+
if (
|
|
434
|
+
input.timeoutSeconds !== undefined &&
|
|
435
|
+
(!Number.isInteger(input.timeoutSeconds) || input.timeoutSeconds <= 0)
|
|
436
|
+
) {
|
|
437
|
+
return "timeoutSeconds must be a positive integer.";
|
|
438
|
+
}
|
|
439
|
+
if (
|
|
440
|
+
input.priority !== undefined &&
|
|
441
|
+
(!Number.isInteger(input.priority) || input.priority < 0 || input.priority > 10)
|
|
442
|
+
) {
|
|
443
|
+
return "priority must be an integer between 0 and 10.";
|
|
444
|
+
}
|
|
445
|
+
if (
|
|
446
|
+
input.retryCount !== undefined &&
|
|
447
|
+
(!Number.isInteger(input.retryCount) || input.retryCount < 0)
|
|
448
|
+
) {
|
|
449
|
+
return "retryCount must be a non-negative integer.";
|
|
450
|
+
}
|
|
451
|
+
if (
|
|
452
|
+
input.retryDelay !== undefined &&
|
|
453
|
+
(!Number.isInteger(input.retryDelay) || input.retryDelay < 0)
|
|
454
|
+
) {
|
|
455
|
+
return "retryDelay must be a non-negative integer.";
|
|
456
|
+
}
|
|
457
|
+
const globFields: [string, string[] | undefined][] = [
|
|
458
|
+
["watchGlobs", input.watchGlobs],
|
|
459
|
+
["watchIgnore", input.watchIgnore],
|
|
460
|
+
["gitPaths", input.gitPaths],
|
|
461
|
+
["gitIgnore", input.gitIgnore],
|
|
462
|
+
];
|
|
463
|
+
for (const [field, masks] of globFields) {
|
|
464
|
+
if (!Array.isArray(masks)) continue;
|
|
465
|
+
for (const mask of masks) {
|
|
466
|
+
if (typeof mask !== "string" || !mask.trim() || /\s/.test(mask)) {
|
|
467
|
+
return `${field} masks must be non-empty strings without whitespace.`;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (
|
|
472
|
+
input.triggerType === "file" &&
|
|
473
|
+
input.watchPath !== undefined &&
|
|
474
|
+
!input.watchPath.trim()
|
|
475
|
+
) {
|
|
476
|
+
return "watchPath must be a non-empty path when triggerType is file.";
|
|
477
|
+
}
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
|
|
349
481
|
/** Zod-схема аргументов schedule_task */
|
|
350
482
|
export const scheduleTaskSchema = z.object({
|
|
351
483
|
name: z
|
|
352
484
|
.string()
|
|
353
485
|
.describe(
|
|
354
|
-
"Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen.",
|
|
486
|
+
"Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and ASCII hyphen '-'. Do NOT use the em dash '—' or round brackets '()': validation rejects them and the original title will be lost. Use ASCII '-' and plain words instead, e.g. 'QA-A2 - Full plugin typing epic'.",
|
|
355
487
|
),
|
|
356
488
|
schedule: z
|
|
357
489
|
.string()
|
|
@@ -406,9 +538,13 @@ export const scheduleTaskSchema = z.object({
|
|
|
406
538
|
.describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
|
|
407
539
|
prompt: z
|
|
408
540
|
.string()
|
|
541
|
+
.min(1, "prompt must be a non-empty string.")
|
|
542
|
+
.refine((value) => value.trim().length > 0, "prompt must be a non-empty string.")
|
|
409
543
|
.describe("Prompt passed to the agent on every run."),
|
|
410
544
|
timeoutSeconds: z
|
|
411
545
|
.number()
|
|
546
|
+
.int()
|
|
547
|
+
.positive()
|
|
412
548
|
.optional()
|
|
413
549
|
.describe("Run timeout in seconds (default 3600)."),
|
|
414
550
|
model: z
|
|
@@ -419,6 +555,9 @@ export const scheduleTaskSchema = z.object({
|
|
|
419
555
|
),
|
|
420
556
|
priority: z
|
|
421
557
|
.number()
|
|
558
|
+
.int()
|
|
559
|
+
.min(0)
|
|
560
|
+
.max(10)
|
|
422
561
|
.optional()
|
|
423
562
|
.describe("Task priority 0..10 (10 is the highest). Default 5 (normal)."),
|
|
424
563
|
beforeScript: z
|
|
@@ -447,10 +586,14 @@ export const scheduleTaskSchema = z.object({
|
|
|
447
586
|
),
|
|
448
587
|
retryCount: z
|
|
449
588
|
.number()
|
|
589
|
+
.int()
|
|
590
|
+
.nonnegative()
|
|
450
591
|
.optional()
|
|
451
592
|
.describe("How many times to retry a failed run (default 0)."),
|
|
452
593
|
retryDelay: z
|
|
453
594
|
.number()
|
|
595
|
+
.int()
|
|
596
|
+
.nonnegative()
|
|
454
597
|
.optional()
|
|
455
598
|
.describe("Delay between retries in seconds (default 60)."),
|
|
456
599
|
nextTaskOnSuccess: z
|
|
@@ -470,12 +613,23 @@ export const scheduleTaskSchema = z.object({
|
|
|
470
613
|
mcpEvent: z
|
|
471
614
|
.object({
|
|
472
615
|
server: z.string(),
|
|
473
|
-
event: z
|
|
616
|
+
event: z
|
|
617
|
+
.string()
|
|
618
|
+
.optional()
|
|
619
|
+
.describe(
|
|
620
|
+
"event or eventName (alias); eventName is accepted for emit_event compatibility",
|
|
621
|
+
),
|
|
622
|
+
eventName: z
|
|
623
|
+
.string()
|
|
624
|
+
.optional()
|
|
625
|
+
.describe(
|
|
626
|
+
"event or eventName (alias); eventName is accepted for emit_event compatibility",
|
|
627
|
+
),
|
|
474
628
|
filter: z.string().optional(),
|
|
475
629
|
})
|
|
476
630
|
.optional()
|
|
477
631
|
.describe(
|
|
478
|
-
"MCP event trigger: server, event
|
|
632
|
+
"MCP event trigger: server, event (or its alias eventName) and an optional filter (key=value or regex). At least one of event/eventName is required for triggerType=mcp-event.",
|
|
479
633
|
),
|
|
480
634
|
watchPath: z
|
|
481
635
|
.string()
|
|
@@ -484,13 +638,13 @@ export const scheduleTaskSchema = z.object({
|
|
|
484
638
|
"File or directory to watch when triggerType is \"file\". Can be set here or later via update_task.",
|
|
485
639
|
),
|
|
486
640
|
watchGlobs: z
|
|
487
|
-
.array(
|
|
641
|
+
.array(globMaskSchema)
|
|
488
642
|
.optional()
|
|
489
643
|
.describe(
|
|
490
644
|
"Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath.",
|
|
491
645
|
),
|
|
492
646
|
watchIgnore: z
|
|
493
|
-
.array(
|
|
647
|
+
.array(globMaskSchema)
|
|
494
648
|
.optional()
|
|
495
649
|
.describe(
|
|
496
650
|
"Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include.",
|
|
@@ -502,13 +656,13 @@ export const scheduleTaskSchema = z.object({
|
|
|
502
656
|
"Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch.",
|
|
503
657
|
),
|
|
504
658
|
gitPaths: z
|
|
505
|
-
.array(
|
|
659
|
+
.array(globMaskSchema)
|
|
506
660
|
.optional()
|
|
507
661
|
.describe(
|
|
508
662
|
"Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only).",
|
|
509
663
|
),
|
|
510
664
|
gitIgnore: z
|
|
511
|
-
.array(
|
|
665
|
+
.array(globMaskSchema)
|
|
512
666
|
.optional()
|
|
513
667
|
.describe("Only for triggerType=git: glob masks of changed files to ignore."),
|
|
514
668
|
gitPollSeconds: z
|
|
@@ -576,6 +730,15 @@ export const scheduleTaskSchema = z.object({
|
|
|
576
730
|
.describe(
|
|
577
731
|
"W-3: pre-run guard conditions. If a semantic check or shell command fails, the run is skipped (no opencode, no side effects). Combined with worktree: checks run inside the fresh worktree.",
|
|
578
732
|
),
|
|
733
|
+
tokenBudget: z
|
|
734
|
+
.number()
|
|
735
|
+
.int()
|
|
736
|
+
.min(0)
|
|
737
|
+
.max(10_000_000)
|
|
738
|
+
.optional()
|
|
739
|
+
.describe(
|
|
740
|
+
"Economics v2 (E-2): per-run token budget. 0 or omitted = no task limit (fail-open). Exceeded runs are flagged in analytics; stopping is E-2.2.",
|
|
741
|
+
),
|
|
579
742
|
matrix: matrixSchema
|
|
580
743
|
.optional()
|
|
581
744
|
.describe(
|
|
@@ -615,16 +778,37 @@ export const scheduleTaskSchema = z.object({
|
|
|
615
778
|
message: t("tool.error.onceFields"),
|
|
616
779
|
});
|
|
617
780
|
}
|
|
781
|
+
// QA-P2.1: явная пустая строка watchPath при file-триггере бессмысленна.
|
|
782
|
+
if (trigger === "file" && value.watchPath !== undefined && !value.watchPath.trim()) {
|
|
783
|
+
ctx.addIssue({
|
|
784
|
+
code: z.ZodIssueCode.custom,
|
|
785
|
+
path: ["watchPath"],
|
|
786
|
+
message: "watchPath must be a non-empty path when triggerType is file.",
|
|
787
|
+
});
|
|
788
|
+
}
|
|
618
789
|
});
|
|
619
790
|
|
|
620
791
|
const listTasksSchema = z.object({});
|
|
621
792
|
|
|
793
|
+
/** PL-43: структурированный ответ list_tasks для Code Mode (V2). */
|
|
794
|
+
const listTasksOutputSchema = z.object({
|
|
795
|
+
success: z.boolean(),
|
|
796
|
+
message: z.string(),
|
|
797
|
+
tasks: z.array(z.unknown()),
|
|
798
|
+
osAvailable: z.boolean(),
|
|
799
|
+
osError: z.string().optional(),
|
|
800
|
+
});
|
|
801
|
+
|
|
622
802
|
const deleteTaskSchema = z.object({
|
|
623
803
|
name: z.string().describe("Task name to delete."),
|
|
624
804
|
});
|
|
625
805
|
|
|
626
806
|
const runTaskNowSchema = z.object({
|
|
627
|
-
name: z
|
|
807
|
+
name: z
|
|
808
|
+
.string()
|
|
809
|
+
.describe(
|
|
810
|
+
"Task name to run immediately. While the plugin unloads the tool returns a structured PLUGIN_SHUTTING_DOWN error (message + retry hint).",
|
|
811
|
+
),
|
|
628
812
|
});
|
|
629
813
|
|
|
630
814
|
export const updateTaskSchema = z.object({
|
|
@@ -691,11 +875,11 @@ export const updateTaskSchema = z.object({
|
|
|
691
875
|
"Windows only: true runs the task without a logged-on user (/ru SYSTEM, session 0 without the user profile, mapped drives or saved credentials; usually requires an elevated shell). false/omitted keeps the task interactive-only.",
|
|
692
876
|
),
|
|
693
877
|
watchGlobs: z
|
|
694
|
-
.array(
|
|
878
|
+
.array(globMaskSchema)
|
|
695
879
|
.optional()
|
|
696
880
|
.describe("New glob masks for a file trigger. Empty array clears them."),
|
|
697
881
|
watchIgnore: z
|
|
698
|
-
.array(
|
|
882
|
+
.array(globMaskSchema)
|
|
699
883
|
.optional()
|
|
700
884
|
.describe("New ignore masks for a file trigger. Empty array clears them."),
|
|
701
885
|
gitBranch: z
|
|
@@ -703,11 +887,11 @@ export const updateTaskSchema = z.object({
|
|
|
703
887
|
.optional()
|
|
704
888
|
.describe("New git branch filter (glob, comma-separated). Empty string clears it."),
|
|
705
889
|
gitPaths: z
|
|
706
|
-
.array(
|
|
890
|
+
.array(globMaskSchema)
|
|
707
891
|
.optional()
|
|
708
892
|
.describe("New changed-file masks for a git trigger. Empty array clears them."),
|
|
709
893
|
gitIgnore: z
|
|
710
|
-
.array(
|
|
894
|
+
.array(globMaskSchema)
|
|
711
895
|
.optional()
|
|
712
896
|
.describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
|
|
713
897
|
gitPollSeconds: z
|
|
@@ -718,14 +902,26 @@ export const updateTaskSchema = z.object({
|
|
|
718
902
|
.describe("New git polling interval in seconds."),
|
|
719
903
|
prompt: z
|
|
720
904
|
.string()
|
|
905
|
+
.refine((value) => value.trim().length > 0, "prompt must be a non-empty string.")
|
|
721
906
|
.optional()
|
|
722
907
|
.describe("New prompt. Keeps the current value when omitted."),
|
|
723
|
-
timeoutSeconds: z
|
|
908
|
+
timeoutSeconds: z
|
|
909
|
+
.number()
|
|
910
|
+
.int()
|
|
911
|
+
.positive()
|
|
912
|
+
.optional()
|
|
913
|
+
.describe("New run timeout in seconds."),
|
|
724
914
|
model: z
|
|
725
915
|
.string()
|
|
726
916
|
.optional()
|
|
727
917
|
.describe("New model in OpenCode format. Empty string clears it (default model)."),
|
|
728
|
-
priority: z
|
|
918
|
+
priority: z
|
|
919
|
+
.number()
|
|
920
|
+
.int()
|
|
921
|
+
.min(0)
|
|
922
|
+
.max(10)
|
|
923
|
+
.optional()
|
|
924
|
+
.describe("New priority 0..10."),
|
|
729
925
|
beforeScript: z
|
|
730
926
|
.string()
|
|
731
927
|
.optional()
|
|
@@ -742,8 +938,8 @@ export const updateTaskSchema = z.object({
|
|
|
742
938
|
.array(z.string())
|
|
743
939
|
.optional()
|
|
744
940
|
.describe("New DAG dependencies. Empty array clears them."),
|
|
745
|
-
retryCount: z.number().optional().describe("New retry count."),
|
|
746
|
-
retryDelay: z.number().optional().describe("New retry delay in seconds."),
|
|
941
|
+
retryCount: z.number().int().nonnegative().optional().describe("New retry count."),
|
|
942
|
+
retryDelay: z.number().int().nonnegative().optional().describe("New retry delay in seconds."),
|
|
747
943
|
nextTaskOnSuccess: z
|
|
748
944
|
.string()
|
|
749
945
|
.optional()
|
|
@@ -759,11 +955,24 @@ export const updateTaskSchema = z.object({
|
|
|
759
955
|
mcpEvent: z
|
|
760
956
|
.object({
|
|
761
957
|
server: z.string(),
|
|
762
|
-
event: z
|
|
958
|
+
event: z
|
|
959
|
+
.string()
|
|
960
|
+
.optional()
|
|
961
|
+
.describe(
|
|
962
|
+
"event or eventName (alias); eventName is accepted for emit_event compatibility",
|
|
963
|
+
),
|
|
964
|
+
eventName: z
|
|
965
|
+
.string()
|
|
966
|
+
.optional()
|
|
967
|
+
.describe(
|
|
968
|
+
"event or eventName (alias); eventName is accepted for emit_event compatibility",
|
|
969
|
+
),
|
|
763
970
|
filter: z.string().optional(),
|
|
764
971
|
})
|
|
765
972
|
.optional()
|
|
766
|
-
.describe(
|
|
973
|
+
.describe(
|
|
974
|
+
"New MCP event trigger: event (or its alias eventName); at least one of them is required for triggerType=mcp-event.",
|
|
975
|
+
),
|
|
767
976
|
watchPath: z
|
|
768
977
|
.string()
|
|
769
978
|
.optional()
|
|
@@ -799,6 +1008,15 @@ export const updateTaskSchema = z.object({
|
|
|
799
1008
|
guards: guardsSchema
|
|
800
1009
|
.optional()
|
|
801
1010
|
.describe("W-3: pre-run guard conditions; a failed check skips the run."),
|
|
1011
|
+
tokenBudget: z
|
|
1012
|
+
.number()
|
|
1013
|
+
.int()
|
|
1014
|
+
.min(0)
|
|
1015
|
+
.max(10_000_000)
|
|
1016
|
+
.optional()
|
|
1017
|
+
.describe(
|
|
1018
|
+
"Economics v2 (E-2): per-run token budget. 0 or omitted = no task limit (fail-open). Pass 0 to clear a previous limit.",
|
|
1019
|
+
),
|
|
802
1020
|
matrix: matrixSchema
|
|
803
1021
|
.nullable()
|
|
804
1022
|
.optional()
|
|
@@ -824,6 +1042,18 @@ export const updateTaskSchema = z.object({
|
|
|
824
1042
|
message: t("tool.error.onceMatrixUpdate"),
|
|
825
1043
|
});
|
|
826
1044
|
}
|
|
1045
|
+
// QA-P2.1: пустой watchPath допустим только для очистки не-file триггера.
|
|
1046
|
+
if (
|
|
1047
|
+
value.triggerType === "file" &&
|
|
1048
|
+
value.watchPath !== undefined &&
|
|
1049
|
+
!value.watchPath.trim()
|
|
1050
|
+
) {
|
|
1051
|
+
ctx.addIssue({
|
|
1052
|
+
code: z.ZodIssueCode.custom,
|
|
1053
|
+
path: ["watchPath"],
|
|
1054
|
+
message: "watchPath must be a non-empty path when triggerType is file.",
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
827
1057
|
});
|
|
828
1058
|
|
|
829
1059
|
const pauseTaskSchema = z.object({
|
|
@@ -855,8 +1085,9 @@ const getHistorySchema = z.object({
|
|
|
855
1085
|
.describe("Maximum number of records to return (default 20, max 200)."),
|
|
856
1086
|
});
|
|
857
1087
|
|
|
858
|
-
const getTaskLogsSchema = z.object({
|
|
859
|
-
name: z.string().describe("Task name to read logs for."),
|
|
1088
|
+
export const getTaskLogsSchema = z.object({
|
|
1089
|
+
name: z.string().optional().describe("Task name to read logs for (alias: taskName)."),
|
|
1090
|
+
taskName: z.string().optional().describe("Alias for name; both spellings are accepted."),
|
|
860
1091
|
lines: z
|
|
861
1092
|
.number()
|
|
862
1093
|
.optional()
|
|
@@ -874,8 +1105,15 @@ const dryRunSchema = z.object({
|
|
|
874
1105
|
|
|
875
1106
|
/** pipeline_validate — проверить опencode.pipeline.yaml (путь или исходник). */
|
|
876
1107
|
export const pipelineValidateSchema = z.object({
|
|
877
|
-
path: z
|
|
878
|
-
|
|
1108
|
+
path: z
|
|
1109
|
+
.string()
|
|
1110
|
+
.optional()
|
|
1111
|
+
.describe("Путь к файлу opencode.pipeline.yaml (относительный резолвится против cwd) или source."),
|
|
1112
|
+
source: z.string().optional().describe("Исходное содержимое YAML (альтернатива path)."),
|
|
1113
|
+
workingDirectory: z
|
|
1114
|
+
.string()
|
|
1115
|
+
.optional()
|
|
1116
|
+
.describe("База для относительного path (по умолчанию cwd процесса, затем подсказки окружения)."),
|
|
879
1117
|
dryRun: z
|
|
880
1118
|
.boolean()
|
|
881
1119
|
.optional()
|
|
@@ -885,8 +1123,15 @@ export const pipelineValidateSchema = z.object({
|
|
|
885
1123
|
|
|
886
1124
|
/** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
|
|
887
1125
|
export const pipelineApplySchema = z.object({
|
|
888
|
-
path: z
|
|
889
|
-
|
|
1126
|
+
path: z
|
|
1127
|
+
.string()
|
|
1128
|
+
.optional()
|
|
1129
|
+
.describe("Путь к файлу opencode.pipeline.yaml (относительный резолвится против cwd) или source."),
|
|
1130
|
+
source: z.string().optional().describe("Исходное содержимое YAML (альтернатива path)."),
|
|
1131
|
+
workingDirectory: z
|
|
1132
|
+
.string()
|
|
1133
|
+
.optional()
|
|
1134
|
+
.describe("База для относительного path (по умолчанию cwd процесса, затем подсказки окружения)."),
|
|
890
1135
|
dryRun: z
|
|
891
1136
|
.boolean()
|
|
892
1137
|
.optional()
|
|
@@ -895,9 +1140,23 @@ export const pipelineApplySchema = z.object({
|
|
|
895
1140
|
});
|
|
896
1141
|
|
|
897
1142
|
/** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
|
|
898
|
-
export const pipelineExportSchema = z
|
|
899
|
-
|
|
900
|
-
|
|
1143
|
+
export const pipelineExportSchema = z
|
|
1144
|
+
.object({
|
|
1145
|
+
pipeline: z.string().optional().describe("Имя конвейера (pipelineName)."),
|
|
1146
|
+
pipelineName: z.string().optional().describe("Алиас параметра pipeline — имя конвейера."),
|
|
1147
|
+
})
|
|
1148
|
+
.superRefine((value, ctx) => {
|
|
1149
|
+
// QA-P3.2: разные имена в двух полях — ошибка, а не молчаливый приоритет pipeline.
|
|
1150
|
+
const explicit = value.pipeline?.trim();
|
|
1151
|
+
const alias = value.pipelineName?.trim();
|
|
1152
|
+
if (explicit && alias && explicit.toLowerCase() !== alias.toLowerCase()) {
|
|
1153
|
+
ctx.addIssue({
|
|
1154
|
+
code: z.ZodIssueCode.custom,
|
|
1155
|
+
path: ["pipelineName"],
|
|
1156
|
+
message: "Конфликт параметров: pipeline и pipelineName задают разные имена конвейера.",
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
});
|
|
901
1160
|
|
|
902
1161
|
const manageWorkspacesSchema = z.object({
|
|
903
1162
|
action: z
|
|
@@ -1003,8 +1262,8 @@ export const selfAnalysisSchema = z.object({
|
|
|
1003
1262
|
/** manage_settings — глобальные настройки планировщика. */
|
|
1004
1263
|
export const manageSettingsSchema = z.object({
|
|
1005
1264
|
action: z
|
|
1006
|
-
.enum(["get", "update"])
|
|
1007
|
-
.describe("get
|
|
1265
|
+
.enum(["get", "list", "update"])
|
|
1266
|
+
.describe("get - current settings; list - same as get (agent-friendly alias); update - merge the provided fields and save."),
|
|
1008
1267
|
maxConcurrent: z
|
|
1009
1268
|
.number()
|
|
1010
1269
|
.int()
|
|
@@ -1051,6 +1310,28 @@ export const manageSettingsSchema = z.object({
|
|
|
1051
1310
|
.describe(
|
|
1052
1311
|
"Tool permission policy for background tasks: hybrid (default; shell/question denied), secure (read-only), legacy (allow everything, 1.5.x behaviour).",
|
|
1053
1312
|
),
|
|
1313
|
+
budgets: z
|
|
1314
|
+
.object({
|
|
1315
|
+
enabled: z.boolean().optional(),
|
|
1316
|
+
dailyUsd: z.number().min(0).max(1_000_000).optional(),
|
|
1317
|
+
weeklyUsd: z.number().min(0).max(1_000_000).optional(),
|
|
1318
|
+
})
|
|
1319
|
+
.optional()
|
|
1320
|
+
.describe(
|
|
1321
|
+
"Daily/weekly USD budgets (0 = no limit). Accounting is exposed by get_analytics as report.budgets.",
|
|
1322
|
+
),
|
|
1323
|
+
feedback: z
|
|
1324
|
+
.object({
|
|
1325
|
+
enabled: z.boolean().optional(),
|
|
1326
|
+
endpoint: z.string().max(2048).optional(),
|
|
1327
|
+
includeLogs: z.boolean().optional(),
|
|
1328
|
+
contactEmail: z.string().max(254).optional(),
|
|
1329
|
+
maxPerHour: z.number().int().min(1).max(100).optional(),
|
|
1330
|
+
})
|
|
1331
|
+
.optional()
|
|
1332
|
+
.describe(
|
|
1333
|
+
"Author feedback (bug reports → GitHub Issues). disabled by default; endpoint must be https (http only for localhost).",
|
|
1334
|
+
),
|
|
1054
1335
|
});
|
|
1055
1336
|
|
|
1056
1337
|
/** manage_local_ai — настройки локального ассистента и триажа (Спринт 30.7). */
|
|
@@ -1115,8 +1396,8 @@ export const manageLocalAiSchema = z.object({
|
|
|
1115
1396
|
export const manageTemplatesSchema = z.object({
|
|
1116
1397
|
action: z
|
|
1117
1398
|
.enum(["list", "save", "delete"])
|
|
1118
|
-
.describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
|
|
1119
|
-
id: z.string().optional().describe("Template id for update
|
|
1399
|
+
.describe("list — all templates; save — create or update (id omitted = create); delete — remove by id or name."),
|
|
1400
|
+
id: z.string().optional().describe("Template id for update; for delete an id or a template name is accepted."),
|
|
1120
1401
|
name: z.string().optional().describe("Template name."),
|
|
1121
1402
|
prompt: z.string().optional().describe("Prompt text stored in the template."),
|
|
1122
1403
|
schedule: z.string().optional().describe("Cron expression."),
|
|
@@ -1135,10 +1416,24 @@ export const manageTemplatesSchema = z.object({
|
|
|
1135
1416
|
mcpEvent: z
|
|
1136
1417
|
.object({
|
|
1137
1418
|
server: z.string(),
|
|
1138
|
-
event: z
|
|
1419
|
+
event: z
|
|
1420
|
+
.string()
|
|
1421
|
+
.optional()
|
|
1422
|
+
.describe(
|
|
1423
|
+
"event or eventName (alias); eventName is accepted for emit_event compatibility",
|
|
1424
|
+
),
|
|
1425
|
+
eventName: z
|
|
1426
|
+
.string()
|
|
1427
|
+
.optional()
|
|
1428
|
+
.describe(
|
|
1429
|
+
"event or eventName (alias); eventName is accepted for emit_event compatibility",
|
|
1430
|
+
),
|
|
1139
1431
|
filter: z.string().optional(),
|
|
1140
1432
|
})
|
|
1141
|
-
.optional()
|
|
1433
|
+
.optional()
|
|
1434
|
+
.describe(
|
|
1435
|
+
"MCP event trigger: event (or its alias eventName); at least one of them is required for triggerType=mcp-event.",
|
|
1436
|
+
),
|
|
1142
1437
|
watchPath: z.string().optional(),
|
|
1143
1438
|
workingDirectory: z.string().optional(),
|
|
1144
1439
|
allowedTools: z.array(z.string()).optional(),
|
|
@@ -1171,6 +1466,22 @@ export const sendNotificationSchema = z.object({
|
|
|
1171
1466
|
.describe("For action=test: which channel to check (default all enabled)."),
|
|
1172
1467
|
});
|
|
1173
1468
|
|
|
1469
|
+
/** report_bug — отчёт о баге; по умолчанию уходит автору через приёмник F-2 (Деталь 3.8). */
|
|
1470
|
+
export const reportBugSchema = z.object({
|
|
1471
|
+
description: z.string().min(1).max(FEEDBACK_LIMITS.description).describe("Описание бага от пользователя (обязательно)."),
|
|
1472
|
+
taskName: z.string().max(FEEDBACK_LIMITS.taskName).optional().describe("Имя задачи, к которой относится баг (для прикрепления логов)."),
|
|
1473
|
+
/** Приватность: по умолчанию логи НЕ прикладываются (F-1.3). */
|
|
1474
|
+
includeLogs: z.boolean().optional().default(false).describe("Включить логи задачи (по умолчанию false)."),
|
|
1475
|
+
includeAnalytics: z.boolean().optional().default(true).describe("Включить метрики и аналитику за последние 7 дней."),
|
|
1476
|
+
/** Канал локальных уведомлений (для destination local/both). */
|
|
1477
|
+
channel: z.enum(["all", "webhook", "telegram", "native"]).optional().describe("Канал локального уведомления."),
|
|
1478
|
+
/** Направление: автор (по умолчанию), локальные каналы или оба (F-1.5). */
|
|
1479
|
+
destination: z.enum(["author", "local", "both"]).optional().default("author").describe("Куда отправить отчёт."),
|
|
1480
|
+
contactEmail: z.string().max(FEEDBACK_LIMITS.contactEmail).optional().describe("Обратный адрес (опционально)."),
|
|
1481
|
+
/** Показать точный payload без отправки (F-3.1). */
|
|
1482
|
+
dryRun: z.boolean().optional().default(false).describe("Предпросмотр без отправки."),
|
|
1483
|
+
});
|
|
1484
|
+
|
|
1174
1485
|
/** get_dashboard_info — сведения о панели управления. */
|
|
1175
1486
|
export const getDashboardInfoSchema = z.object({});
|
|
1176
1487
|
|
|
@@ -1184,6 +1495,10 @@ export const cleanupHistorySchema = z.object({
|
|
|
1184
1495
|
export const emitEventSchema = z.object({
|
|
1185
1496
|
eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
|
|
1186
1497
|
payload: z.any().optional().describe("Event payload passed to trigger filters."),
|
|
1498
|
+
server: z
|
|
1499
|
+
.string()
|
|
1500
|
+
.optional()
|
|
1501
|
+
.describe("Optional MCP source/server name (e.g. 'github'). When set, only tasks with the same mcpEvent.server are triggered."),
|
|
1187
1502
|
});
|
|
1188
1503
|
|
|
1189
1504
|
/** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
|
|
@@ -1234,6 +1549,7 @@ type TemplatesArgs = z.infer<typeof manageTemplatesSchema>;
|
|
|
1234
1549
|
type ProfilesArgs = z.infer<typeof manageProfilesSchema>;
|
|
1235
1550
|
type TransferArgs = z.infer<typeof transferTasksSchema>;
|
|
1236
1551
|
type NotificationArgs = z.infer<typeof sendNotificationSchema>;
|
|
1552
|
+
type ReportBugArgs = z.infer<typeof reportBugSchema>;
|
|
1237
1553
|
type DashboardInfoArgs = z.infer<typeof getDashboardInfoSchema>;
|
|
1238
1554
|
type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
|
|
1239
1555
|
type EmitEventArgs = z.infer<typeof emitEventSchema>;
|
|
@@ -1250,22 +1566,43 @@ type PipelineExportArgs = z.infer<typeof pipelineExportSchema>;
|
|
|
1250
1566
|
*/
|
|
1251
1567
|
let projectDirectory: string | undefined;
|
|
1252
1568
|
|
|
1569
|
+
/**
|
|
1570
|
+
* Общий контекст execute-обработчиков. Обработчики не читают поля контекста,
|
|
1571
|
+
* а контексты V1 и V2 устроены по-разному, поэтому на границе адаптеров он
|
|
1572
|
+
* сводится к `unknown`. Это позволяет не тащить `Tool.Context` из
|
|
1573
|
+
* @opencode/schema/tool в общий контракт инструментов.
|
|
1574
|
+
*/
|
|
1575
|
+
type ToolExecuteContext = unknown;
|
|
1576
|
+
|
|
1253
1577
|
/**
|
|
1254
1578
|
* Обёртка execute-функции: ловит ошибки и возвращает Tool.Result с content.
|
|
1255
|
-
* Использует Tool.Context из @opencode/schema/tool.
|
|
1256
1579
|
*/
|
|
1257
1580
|
function wrapExecute<Args>(
|
|
1258
|
-
fn: (args: Args, ctx:
|
|
1259
|
-
): (input: Args, context:
|
|
1581
|
+
fn: (args: Args, ctx: ToolExecuteContext) => Promise<Tool.Result>,
|
|
1582
|
+
): (input: Args, context: ToolExecuteContext) => Promise<Tool.Result> {
|
|
1260
1583
|
return async (input, context) => {
|
|
1261
1584
|
try {
|
|
1262
1585
|
return await fn(input, context);
|
|
1263
|
-
} catch (err
|
|
1586
|
+
} catch (err) {
|
|
1587
|
+
const shutdown =
|
|
1588
|
+
err instanceof PluginShutdownError
|
|
1589
|
+
? {
|
|
1590
|
+
code: err.code,
|
|
1591
|
+
hint: err.hint,
|
|
1592
|
+
retryable: err.retryable,
|
|
1593
|
+
shutdownState: err.state,
|
|
1594
|
+
}
|
|
1595
|
+
: {};
|
|
1596
|
+
// PL-43: тот же payload отдаём и структурированным output, и строкой
|
|
1597
|
+
// content — V1-адаптер по-прежнему читает content.
|
|
1598
|
+
const output = {
|
|
1599
|
+
success: false,
|
|
1600
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1601
|
+
...shutdown,
|
|
1602
|
+
};
|
|
1264
1603
|
return {
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1268
|
-
}),
|
|
1604
|
+
output,
|
|
1605
|
+
content: JSON.stringify(output),
|
|
1269
1606
|
};
|
|
1270
1607
|
}
|
|
1271
1608
|
};
|
|
@@ -1357,6 +1694,9 @@ function computeTaskNextRun(
|
|
|
1357
1694
|
|
|
1358
1695
|
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
1359
1696
|
const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
1697
|
+
// QA-P2.1: RPC-путь не проходит Zod — проверяем диапазоны явно.
|
|
1698
|
+
const rangeError = validateTaskInputRanges(args);
|
|
1699
|
+
if (rangeError) throw new Error(rangeError);
|
|
1360
1700
|
const {
|
|
1361
1701
|
name,
|
|
1362
1702
|
schedule,
|
|
@@ -1399,6 +1739,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1399
1739
|
legacyShell,
|
|
1400
1740
|
worktree,
|
|
1401
1741
|
guards,
|
|
1742
|
+
tokenBudget,
|
|
1402
1743
|
} = args;
|
|
1403
1744
|
|
|
1404
1745
|
let effectiveRunAt: string | undefined;
|
|
@@ -1469,8 +1810,9 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1469
1810
|
legacyShell === true,
|
|
1470
1811
|
worktree === true,
|
|
1471
1812
|
guards,
|
|
1813
|
+
tokenBudget,
|
|
1472
1814
|
);
|
|
1473
|
-
} catch (err
|
|
1815
|
+
} catch (err) {
|
|
1474
1816
|
return {
|
|
1475
1817
|
content: JSON.stringify({
|
|
1476
1818
|
success: false,
|
|
@@ -1547,30 +1889,28 @@ const listTasksExecute = wrapExecute<ListArgs>(async () => {
|
|
|
1547
1889
|
const { tasks, osAvailable, osError } = await collectTasksView();
|
|
1548
1890
|
|
|
1549
1891
|
if (tasks.length === 0) {
|
|
1550
|
-
|
|
1551
|
-
content: JSON.stringify({
|
|
1552
|
-
success: true,
|
|
1553
|
-
message: osAvailable
|
|
1554
|
-
? t("tool.task.listEmpty")
|
|
1555
|
-
: t("tool.task.listOsUnavailable"),
|
|
1556
|
-
tasks: [],
|
|
1557
|
-
osAvailable,
|
|
1558
|
-
...(osError ? { osError } : {}),
|
|
1559
|
-
}),
|
|
1560
|
-
};
|
|
1561
|
-
}
|
|
1562
|
-
|
|
1563
|
-
return {
|
|
1564
|
-
content: JSON.stringify({
|
|
1892
|
+
const output = {
|
|
1565
1893
|
success: true,
|
|
1566
1894
|
message: osAvailable
|
|
1567
|
-
? t("tool.task.
|
|
1568
|
-
: t("tool.task.
|
|
1569
|
-
tasks,
|
|
1895
|
+
? t("tool.task.listEmpty")
|
|
1896
|
+
: t("tool.task.listOsUnavailable"),
|
|
1897
|
+
tasks: [],
|
|
1570
1898
|
osAvailable,
|
|
1571
1899
|
...(osError ? { osError } : {}),
|
|
1572
|
-
}
|
|
1900
|
+
};
|
|
1901
|
+
return { output, content: JSON.stringify(output) };
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
const output = {
|
|
1905
|
+
success: true,
|
|
1906
|
+
message: osAvailable
|
|
1907
|
+
? t("tool.task.found", { count: tasks.length })
|
|
1908
|
+
: t("tool.task.foundOsUnavailable", { count: tasks.length }),
|
|
1909
|
+
tasks,
|
|
1910
|
+
osAvailable,
|
|
1911
|
+
...(osError ? { osError } : {}),
|
|
1573
1912
|
};
|
|
1913
|
+
return { output, content: JSON.stringify(output) };
|
|
1574
1914
|
});
|
|
1575
1915
|
|
|
1576
1916
|
/**
|
|
@@ -1601,7 +1941,7 @@ async function cancelMatrixRun(
|
|
|
1601
1941
|
// Удаление запущенной задачи планировщика останавливает её процесс.
|
|
1602
1942
|
try {
|
|
1603
1943
|
await scheduler.deleteTask(clone.name);
|
|
1604
|
-
} catch (err
|
|
1944
|
+
} catch (err) {
|
|
1605
1945
|
warnings.push(
|
|
1606
1946
|
t("tool.matrix.stopFailed", {
|
|
1607
1947
|
clone: clone.name,
|
|
@@ -1652,8 +1992,10 @@ async function cancelMatrixRun(
|
|
|
1652
1992
|
clone.legacyShell,
|
|
1653
1993
|
clone.worktree,
|
|
1654
1994
|
clone.guards,
|
|
1995
|
+
// QA-P0.1 (E-2.1): клон матрицы наследует tokenBudget родителя.
|
|
1996
|
+
clone.tokenBudget,
|
|
1655
1997
|
);
|
|
1656
|
-
} catch (err
|
|
1998
|
+
} catch (err) {
|
|
1657
1999
|
warnings.push(
|
|
1658
2000
|
t("tool.matrix.recreateFailed", {
|
|
1659
2001
|
clone: clone.name,
|
|
@@ -1878,11 +2220,11 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
|
|
|
1878
2220
|
: t("tool.task.deleted", { name }),
|
|
1879
2221
|
}),
|
|
1880
2222
|
};
|
|
1881
|
-
} catch (err
|
|
2223
|
+
} catch (err) {
|
|
1882
2224
|
return {
|
|
1883
2225
|
content: JSON.stringify({
|
|
1884
2226
|
success: false,
|
|
1885
|
-
error: err.message
|
|
2227
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1886
2228
|
}),
|
|
1887
2229
|
};
|
|
1888
2230
|
}
|
|
@@ -1892,15 +2234,22 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
|
|
|
1892
2234
|
const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
|
|
1893
2235
|
const { name } = args;
|
|
1894
2236
|
|
|
2237
|
+
// PL-8.1: тот же дрейф HEAD, что и в dry_run, показываем при ручном старте.
|
|
2238
|
+
const definition = getTask(name);
|
|
2239
|
+
const warning =
|
|
2240
|
+
definition?.workingDirectory && definition.createdAt
|
|
2241
|
+
? workingDirectoryDriftWarning(definition, definition.workingDirectory)
|
|
2242
|
+
: null;
|
|
2243
|
+
|
|
1895
2244
|
let alreadyRunning = false;
|
|
1896
2245
|
try {
|
|
1897
2246
|
const result = await runTaskEntry(name);
|
|
1898
2247
|
alreadyRunning = result.alreadyRunning;
|
|
1899
|
-
} catch (err
|
|
2248
|
+
} catch (err) {
|
|
1900
2249
|
return {
|
|
1901
2250
|
content: JSON.stringify({
|
|
1902
2251
|
success: false,
|
|
1903
|
-
error: err.message
|
|
2252
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1904
2253
|
}),
|
|
1905
2254
|
};
|
|
1906
2255
|
}
|
|
@@ -1911,6 +2260,7 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
|
|
|
1911
2260
|
message: alreadyRunning
|
|
1912
2261
|
? t("tool.task.alreadyRunning", { name })
|
|
1913
2262
|
: t("tool.task.started", { name }),
|
|
2263
|
+
...(warning ? { warning } : {}),
|
|
1914
2264
|
}),
|
|
1915
2265
|
};
|
|
1916
2266
|
});
|
|
@@ -1979,6 +2329,12 @@ async function updateTaskFromInput(
|
|
|
1979
2329
|
return { success: false, message: t("tool.error.taskNameMissing") };
|
|
1980
2330
|
}
|
|
1981
2331
|
|
|
2332
|
+
// QA-P2.1: RPC не проходит Zod — проверяем диапазоны явно.
|
|
2333
|
+
const rangeError = validateTaskInputRanges(input);
|
|
2334
|
+
if (rangeError) {
|
|
2335
|
+
return { success: false, message: rangeError };
|
|
2336
|
+
}
|
|
2337
|
+
|
|
1982
2338
|
const previous = getTask(name);
|
|
1983
2339
|
if (!previous) {
|
|
1984
2340
|
return { success: false, message: t("tool.error.taskNotFound", { name }) };
|
|
@@ -2166,6 +2522,8 @@ async function updateTaskFromInput(
|
|
|
2166
2522
|
input.legacyShell ?? previous.legacyShell,
|
|
2167
2523
|
input.worktree ?? previous.worktree,
|
|
2168
2524
|
input.guards ?? previous.guards,
|
|
2525
|
+
// QA-P0.1 (E-2.1): budget переживает пересоздание задачи. 0 очищает лимит.
|
|
2526
|
+
input.tokenBudget ?? previous.tokenBudget,
|
|
2169
2527
|
);
|
|
2170
2528
|
|
|
2171
2529
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
@@ -2219,7 +2577,7 @@ async function updateTaskFromInput(
|
|
|
2219
2577
|
nextRun: computeTaskNextRun(updated, { paused }),
|
|
2220
2578
|
message: t("tool.task.updated", { name }),
|
|
2221
2579
|
};
|
|
2222
|
-
} catch (err
|
|
2580
|
+
} catch (err) {
|
|
2223
2581
|
const cause = err instanceof Error ? err.message : String(err);
|
|
2224
2582
|
|
|
2225
2583
|
// Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
|
|
@@ -2249,7 +2607,7 @@ async function updateTaskFromInput(
|
|
|
2249
2607
|
restored: true,
|
|
2250
2608
|
message: t("tool.task.rollbackRestored", { cause }),
|
|
2251
2609
|
};
|
|
2252
|
-
} catch (restoreErr
|
|
2610
|
+
} catch (restoreErr) {
|
|
2253
2611
|
const restoreMessage =
|
|
2254
2612
|
restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
|
|
2255
2613
|
return {
|
|
@@ -2297,7 +2655,10 @@ async function pauseOrResumeTask(
|
|
|
2297
2655
|
message: t("tool.error.taskNotFound", { name: trimmed }),
|
|
2298
2656
|
affected: [],
|
|
2299
2657
|
warnings: [],
|
|
2300
|
-
paused
|
|
2658
|
+
// QA-P3.8: в ошибке `paused` должен отражать реальное состояние,
|
|
2659
|
+
// а не запрошенное действие (иначе resume про несуществующей задаче
|
|
2660
|
+
// сообщает paused:false, а pause — paused:true).
|
|
2661
|
+
paused: false,
|
|
2301
2662
|
nextRun: null,
|
|
2302
2663
|
pausedUntil: null,
|
|
2303
2664
|
};
|
|
@@ -2313,7 +2674,7 @@ async function pauseOrResumeTask(
|
|
|
2313
2674
|
message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
|
|
2314
2675
|
affected: [],
|
|
2315
2676
|
warnings: [],
|
|
2316
|
-
paused,
|
|
2677
|
+
paused: definition.paused ?? false,
|
|
2317
2678
|
nextRun: null,
|
|
2318
2679
|
pausedUntil: definition.pausedUntil ?? null,
|
|
2319
2680
|
};
|
|
@@ -2324,7 +2685,7 @@ async function pauseOrResumeTask(
|
|
|
2324
2685
|
message: t("tool.error.pauseDatePast", { name: trimmed }),
|
|
2325
2686
|
affected: [],
|
|
2326
2687
|
warnings: [],
|
|
2327
|
-
paused,
|
|
2688
|
+
paused: definition.paused ?? false,
|
|
2328
2689
|
nextRun: null,
|
|
2329
2690
|
pausedUntil: definition.pausedUntil ?? null,
|
|
2330
2691
|
};
|
|
@@ -2341,7 +2702,7 @@ async function pauseOrResumeTask(
|
|
|
2341
2702
|
message: t("tool.error.matrixNoClones", { name: trimmed }),
|
|
2342
2703
|
affected: [],
|
|
2343
2704
|
warnings: [],
|
|
2344
|
-
paused,
|
|
2705
|
+
paused: definition.paused ?? false,
|
|
2345
2706
|
nextRun: null,
|
|
2346
2707
|
pausedUntil: definition.pausedUntil ?? null,
|
|
2347
2708
|
};
|
|
@@ -2357,7 +2718,7 @@ async function pauseOrResumeTask(
|
|
|
2357
2718
|
await scheduler.resumeTask(target);
|
|
2358
2719
|
}
|
|
2359
2720
|
affected.push(target);
|
|
2360
|
-
} catch (err
|
|
2721
|
+
} catch (err) {
|
|
2361
2722
|
warnings.push(
|
|
2362
2723
|
`${target}: ${err instanceof Error ? err.message : String(err)}`,
|
|
2363
2724
|
);
|
|
@@ -2376,7 +2737,7 @@ async function pauseOrResumeTask(
|
|
|
2376
2737
|
if (definitionUpdates && affected.length > 0) {
|
|
2377
2738
|
try {
|
|
2378
2739
|
saveTask({ ...definition, ...definitionUpdates });
|
|
2379
|
-
} catch (err
|
|
2740
|
+
} catch (err) {
|
|
2380
2741
|
warnings.push(
|
|
2381
2742
|
t("tool.task.autosave", {
|
|
2382
2743
|
error: err instanceof Error ? err.message : String(err),
|
|
@@ -2475,7 +2836,7 @@ async function resumeExpiredPauses(): Promise<void> {
|
|
|
2475
2836
|
console.log(
|
|
2476
2837
|
`[agent-steward] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`,
|
|
2477
2838
|
);
|
|
2478
|
-
} catch (err
|
|
2839
|
+
} catch (err) {
|
|
2479
2840
|
console.error(
|
|
2480
2841
|
`[agent-steward] Не удалось автопродолжить задачу "${definition.name}": ${
|
|
2481
2842
|
err instanceof Error ? err.message : String(err)
|
|
@@ -2530,6 +2891,9 @@ async function checkStuckMatrices(): Promise<void> {
|
|
|
2530
2891
|
/** get_history — история запусков с фильтрами по задаче и статусу. */
|
|
2531
2892
|
const getHistoryExecute = wrapExecute<HistoryArgs>(async (args) => {
|
|
2532
2893
|
const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
|
|
2894
|
+
// PL-46: зависшие записи (schtasks /End) должны закрываться не только при
|
|
2895
|
+
// setup, но и при наблюдении истории — иначе остаются running навсегда.
|
|
2896
|
+
recoverInterruptedRuns();
|
|
2533
2897
|
const records = await loadHistory(args.taskName, limit, args.status);
|
|
2534
2898
|
|
|
2535
2899
|
return {
|
|
@@ -2543,7 +2907,14 @@ const getHistoryExecute = wrapExecute<HistoryArgs>(async (args) => {
|
|
|
2543
2907
|
|
|
2544
2908
|
/** get_task_logs — последние строки лога задачи. */
|
|
2545
2909
|
const getTaskLogsExecute = wrapExecute<TaskLogsArgs>(async (args) => {
|
|
2546
|
-
|
|
2910
|
+
// PL-19: MCP-клиенты передают и name, и taskName — принимаем оба написания.
|
|
2911
|
+
const taskName = args.name?.trim() || args.taskName?.trim();
|
|
2912
|
+
if (!taskName) {
|
|
2913
|
+
return {
|
|
2914
|
+
content: JSON.stringify({ success: false, logs: "", error: "Укажите name или taskName задачи" }),
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
const result = await getTaskLogs(taskName, args.lines ?? 200);
|
|
2547
2918
|
if (result.error) {
|
|
2548
2919
|
return {
|
|
2549
2920
|
content: JSON.stringify({ success: false, logs: "", error: result.error }),
|
|
@@ -2563,11 +2934,11 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
|
|
|
2563
2934
|
}
|
|
2564
2935
|
|
|
2565
2936
|
const definitions = await loadTaskDefinitions();
|
|
2566
|
-
const reports:
|
|
2937
|
+
const reports: (DryRunReport & { error?: string })[] = [];
|
|
2567
2938
|
for (const definition of definitions) {
|
|
2568
2939
|
try {
|
|
2569
2940
|
reports.push(await simulatePipeline(definition.name));
|
|
2570
|
-
} catch (err
|
|
2941
|
+
} catch (err) {
|
|
2571
2942
|
reports.push({
|
|
2572
2943
|
success: false,
|
|
2573
2944
|
taskName: definition.name,
|
|
@@ -2594,7 +2965,6 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
|
|
|
2594
2965
|
|
|
2595
2966
|
/** pipeline_validate — проверить opencode.pipeline.yaml (путь или исходник). */
|
|
2596
2967
|
const pipelineValidateExecute = wrapExecute<PipelineValidateArgs>(async (args) => {
|
|
2597
|
-
const path = args.path ?? args.source ? undefined : undefined;
|
|
2598
2968
|
if (args.path === undefined && args.source === undefined) {
|
|
2599
2969
|
return {
|
|
2600
2970
|
content: JSON.stringify({
|
|
@@ -2608,7 +2978,7 @@ const pipelineValidateExecute = wrapExecute<PipelineValidateArgs>(async (args) =
|
|
|
2608
2978
|
const parsed =
|
|
2609
2979
|
args.source !== undefined
|
|
2610
2980
|
? validatePipelineSpecFromSource(args.source)
|
|
2611
|
-
: await loadPipelineFile(args.path
|
|
2981
|
+
: await loadPipelineFile(args.path!, args.workingDirectory);
|
|
2612
2982
|
if (!parsed.ok) {
|
|
2613
2983
|
return {
|
|
2614
2984
|
content: JSON.stringify({
|
|
@@ -2639,10 +3009,20 @@ function validatePipelineSpecFromSource(source: string): PipelineParseResult {
|
|
|
2639
3009
|
/** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
|
|
2640
3010
|
const pipelineApplyExecute = wrapExecute<PipelineApplyArgs>(async (args) => {
|
|
2641
3011
|
const dryRun = args.dryRun !== false;
|
|
3012
|
+
if (args.path === undefined && args.source === undefined) {
|
|
3013
|
+
return {
|
|
3014
|
+
content: JSON.stringify({
|
|
3015
|
+
success: false,
|
|
3016
|
+
pipeline: null,
|
|
3017
|
+
errors: ["Укажите path к файлу или source с содержимым YAML"],
|
|
3018
|
+
warnings: [],
|
|
3019
|
+
}),
|
|
3020
|
+
};
|
|
3021
|
+
}
|
|
2642
3022
|
const parsed =
|
|
2643
3023
|
args.source !== undefined
|
|
2644
3024
|
? validatePipelineSpecFromSource(args.source)
|
|
2645
|
-
: await loadPipelineFile(args.path
|
|
3025
|
+
: await loadPipelineFile(args.path!, args.workingDirectory);
|
|
2646
3026
|
if (!parsed.ok) {
|
|
2647
3027
|
return {
|
|
2648
3028
|
content: JSON.stringify({
|
|
@@ -2721,7 +3101,7 @@ const pipelineApplyExecute = wrapExecute<PipelineApplyArgs>(async (args) => {
|
|
|
2721
3101
|
);
|
|
2722
3102
|
await saveTaskDefinition(task);
|
|
2723
3103
|
created++;
|
|
2724
|
-
} catch (err
|
|
3104
|
+
} catch (err) {
|
|
2725
3105
|
errors.push(`create ${task.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2726
3106
|
}
|
|
2727
3107
|
}
|
|
@@ -2778,7 +3158,7 @@ const pipelineApplyExecute = wrapExecute<PipelineApplyArgs>(async (args) => {
|
|
|
2778
3158
|
);
|
|
2779
3159
|
await saveTaskDefinition(item.task);
|
|
2780
3160
|
updated++;
|
|
2781
|
-
} catch (err
|
|
3161
|
+
} catch (err) {
|
|
2782
3162
|
errors.push(`update ${item.task.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2783
3163
|
}
|
|
2784
3164
|
}
|
|
@@ -2803,12 +3183,34 @@ const pipelineApplyExecute = wrapExecute<PipelineApplyArgs>(async (args) => {
|
|
|
2803
3183
|
/** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
|
|
2804
3184
|
const pipelineExportExecute = wrapExecute<PipelineExportArgs>(async (args) => {
|
|
2805
3185
|
const allTasks = await listTaskDefinitions();
|
|
2806
|
-
|
|
2807
|
-
|
|
3186
|
+
// QA-P3.2: два имени — это ошибка, а не молчаливый выбор первого.
|
|
3187
|
+
const explicit = args.pipeline?.trim();
|
|
3188
|
+
const alias = args.pipelineName?.trim();
|
|
3189
|
+
if (explicit && alias && explicit.toLowerCase() !== alias.toLowerCase()) {
|
|
3190
|
+
return {
|
|
3191
|
+
content: JSON.stringify({
|
|
3192
|
+
success: false,
|
|
3193
|
+
error: "Конфликт параметров: pipeline и pipelineName задают разные имена конвейера.",
|
|
3194
|
+
}),
|
|
3195
|
+
};
|
|
3196
|
+
}
|
|
3197
|
+
const pipelineName = explicit || alias;
|
|
3198
|
+
if (!pipelineName) {
|
|
3199
|
+
return {
|
|
3200
|
+
content: JSON.stringify({
|
|
3201
|
+
success: false,
|
|
3202
|
+
error: "Не задано имя конвейера: укажите pipeline или pipelineName.",
|
|
3203
|
+
}),
|
|
3204
|
+
};
|
|
3205
|
+
}
|
|
3206
|
+
const result = tasksToPipelineSpec(allTasks, pipelineName);
|
|
3207
|
+
// QA-P3.2: spec всегда создаётся, поэтому «не найден» проверяем по шагам.
|
|
3208
|
+
const lookupError = pipelineExportLookupError(allTasks, pipelineName);
|
|
3209
|
+
if (!result.spec || lookupError) {
|
|
2808
3210
|
return {
|
|
2809
3211
|
content: JSON.stringify({
|
|
2810
3212
|
success: false,
|
|
2811
|
-
error: `Конвейер "${
|
|
3213
|
+
error: lookupError ?? `Конвейер "${pipelineName}" не найден.`,
|
|
2812
3214
|
warnings: result.warnings,
|
|
2813
3215
|
}),
|
|
2814
3216
|
};
|
|
@@ -2817,7 +3219,7 @@ const pipelineExportExecute = wrapExecute<PipelineExportArgs>(async (args) => {
|
|
|
2817
3219
|
return {
|
|
2818
3220
|
content: JSON.stringify({
|
|
2819
3221
|
success: true,
|
|
2820
|
-
pipeline:
|
|
3222
|
+
pipeline: pipelineName,
|
|
2821
3223
|
steps: result.spec.steps.length,
|
|
2822
3224
|
yaml: yamlText,
|
|
2823
3225
|
warnings: result.warnings,
|
|
@@ -2838,7 +3240,7 @@ async function refreshWorkspaceEnvFiles(workspaceId: string): Promise<number> {
|
|
|
2838
3240
|
try {
|
|
2839
3241
|
writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
|
|
2840
3242
|
refreshed += 1;
|
|
2841
|
-
} catch (err
|
|
3243
|
+
} catch (err) {
|
|
2842
3244
|
// P2-21: не разрешаем задаче работать с литералом ${secret:...}.
|
|
2843
3245
|
console.error(
|
|
2844
3246
|
`[workspace] Задача "${task.name}": env-файл не обновлён — ${
|
|
@@ -2954,7 +3356,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
2954
3356
|
};
|
|
2955
3357
|
}
|
|
2956
3358
|
}
|
|
2957
|
-
} catch (err
|
|
3359
|
+
} catch (err) {
|
|
2958
3360
|
return {
|
|
2959
3361
|
content: JSON.stringify({
|
|
2960
3362
|
success: false,
|
|
@@ -3024,7 +3426,7 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
3024
3426
|
cancelled: result.cancelled,
|
|
3025
3427
|
}),
|
|
3026
3428
|
};
|
|
3027
|
-
} catch (err
|
|
3429
|
+
} catch (err) {
|
|
3028
3430
|
return {
|
|
3029
3431
|
content: JSON.stringify({
|
|
3030
3432
|
success: false,
|
|
@@ -3034,10 +3436,22 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
3034
3436
|
}
|
|
3035
3437
|
}
|
|
3036
3438
|
|
|
3439
|
+
// QA-P3.7: `results` должен так же проверять тип задачи, как `cancel`.
|
|
3440
|
+
// Иначе неизвестное имя даёт success:true с пустым отчётом вместо
|
|
3441
|
+
// внятной ошибки «задача не является матрицей».
|
|
3442
|
+
if (!isKnownMatrix(name)) {
|
|
3443
|
+
return {
|
|
3444
|
+
content: JSON.stringify({
|
|
3445
|
+
success: false,
|
|
3446
|
+
error: t("tool.error.matrixNotMatrix", { name }),
|
|
3447
|
+
}),
|
|
3448
|
+
};
|
|
3449
|
+
}
|
|
3450
|
+
|
|
3037
3451
|
try {
|
|
3038
3452
|
const report = aggregateMatrixResults(name);
|
|
3039
3453
|
return { content: JSON.stringify({ success: true, report }) };
|
|
3040
|
-
} catch (err
|
|
3454
|
+
} catch (err) {
|
|
3041
3455
|
return {
|
|
3042
3456
|
content: JSON.stringify({
|
|
3043
3457
|
success: false,
|
|
@@ -3050,42 +3464,60 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
3050
3464
|
/** get_metrics — суммарная статистика запусков. */
|
|
3051
3465
|
const getMetricsExecute = wrapExecute<MetricsArgs>(async () => {
|
|
3052
3466
|
const metrics = await loadMetrics();
|
|
3053
|
-
|
|
3467
|
+
// PL-4.1: блокировки инструментов — показатель корректности hybrid-политики.
|
|
3468
|
+
const since = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
|
|
3469
|
+
const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
|
|
3470
|
+
return { content: JSON.stringify({ success: true, metrics: { ...metrics, toolBlocked } }) };
|
|
3054
3471
|
});
|
|
3055
3472
|
|
|
3056
3473
|
/** get_analytics — аналитика запусков и стоимости за период. */
|
|
3057
3474
|
const getAnalyticsExecute = wrapExecute<AnalyticsArgs>(async (args) => {
|
|
3058
3475
|
const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
|
|
3059
|
-
const records =
|
|
3476
|
+
const records = getHistoryForAnalytics(windowDays);
|
|
3060
3477
|
const definitions = await loadTaskDefinitions();
|
|
3061
3478
|
const report = buildAnalytics(records, {
|
|
3062
3479
|
days: windowDays,
|
|
3063
3480
|
topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
|
|
3064
|
-
tasks: definitions.map((definition) => ({
|
|
3481
|
+
tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
|
|
3065
3482
|
name: definition.name,
|
|
3066
3483
|
matrixParentId: definition.matrixParentId,
|
|
3484
|
+
tokenBudget: definition.tokenBudget,
|
|
3067
3485
|
})),
|
|
3068
3486
|
});
|
|
3069
|
-
|
|
3487
|
+
// Экономика v2 (E-1.1): учёт расхода за день/неделю рядом с аналитикой.
|
|
3488
|
+
const settings = await loadSettings();
|
|
3489
|
+
const budgets = buildBudgetReport(records, settings.budgets, new Date());
|
|
3490
|
+
// PL-4.1: tool.blocked — метрика корректности прав политики, а не ошибка
|
|
3491
|
+
// запуска. Считаем за то же окно, что и аналитику; readAuditLog отдаёт total
|
|
3492
|
+
// независимо от limit, поэтому одной строки выборки достаточно для счётчика.
|
|
3493
|
+
const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000).toISOString();
|
|
3494
|
+
const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
|
|
3495
|
+
return {
|
|
3496
|
+
content: JSON.stringify({
|
|
3497
|
+
success: true,
|
|
3498
|
+
report: { ...report, budgets, toolBlocked },
|
|
3499
|
+
}),
|
|
3500
|
+
};
|
|
3070
3501
|
});
|
|
3071
3502
|
|
|
3072
3503
|
/** self_analysis — система самоанализа: здоровье, аномалии, тренды, рекомендации. */
|
|
3073
3504
|
const selfAnalysisExecute = wrapExecute<SelfAnalysisArgs>(async (args) => {
|
|
3074
3505
|
const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
|
|
3075
|
-
const records =
|
|
3506
|
+
const records = getHistoryForAnalytics(windowDays);
|
|
3076
3507
|
const definitions = await loadTaskDefinitions();
|
|
3077
3508
|
|
|
3078
3509
|
const report = generateSelfAnalysisReport(records, {
|
|
3079
3510
|
days: windowDays,
|
|
3080
3511
|
topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
|
|
3081
|
-
tasks: definitions.map((definition) => ({
|
|
3512
|
+
tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
|
|
3082
3513
|
name: definition.name,
|
|
3083
3514
|
matrixParentId: definition.matrixParentId,
|
|
3515
|
+
tokenBudget: definition.tokenBudget,
|
|
3084
3516
|
})),
|
|
3085
3517
|
});
|
|
3086
3518
|
|
|
3087
3519
|
// Фильтруем секции если нужно
|
|
3088
|
-
const result:
|
|
3520
|
+
const result: Partial<typeof report> = {
|
|
3089
3521
|
generatedAt: report.generatedAt,
|
|
3090
3522
|
windowDays: report.windowDays,
|
|
3091
3523
|
health: report.health,
|
|
@@ -3109,7 +3541,7 @@ const selfAnalysisExecute = wrapExecute<SelfAnalysisArgs>(async (args) => {
|
|
|
3109
3541
|
/** manage_settings — чтение и изменение глобальных настроек. */
|
|
3110
3542
|
const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
3111
3543
|
const current = await loadSettings();
|
|
3112
|
-
if (args.action === "get") {
|
|
3544
|
+
if (args.action === "get" || args.action === "list") {
|
|
3113
3545
|
return { content: JSON.stringify({ success: true, settings: current }) };
|
|
3114
3546
|
}
|
|
3115
3547
|
|
|
@@ -3121,7 +3553,9 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
3121
3553
|
args.history === undefined &&
|
|
3122
3554
|
args.integrations === undefined &&
|
|
3123
3555
|
args.audit === undefined &&
|
|
3124
|
-
args.permissions === undefined
|
|
3556
|
+
args.permissions === undefined &&
|
|
3557
|
+
args.budgets === undefined &&
|
|
3558
|
+
args.feedback === undefined
|
|
3125
3559
|
) {
|
|
3126
3560
|
return {
|
|
3127
3561
|
content: JSON.stringify({
|
|
@@ -3141,6 +3575,8 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
3141
3575
|
integrations: args.integrations as IntegrationSettings | undefined,
|
|
3142
3576
|
audit: args.audit as AuditSettings | undefined,
|
|
3143
3577
|
permissions: args.permissions as PermissionSettings | undefined,
|
|
3578
|
+
budgets: args.budgets as BudgetSettings | undefined,
|
|
3579
|
+
feedback: args.feedback as FeedbackSettings | undefined,
|
|
3144
3580
|
});
|
|
3145
3581
|
// Локаль процесса меняется сразу — перезапуск плагина не нужен.
|
|
3146
3582
|
setLocale(resolveLocale(settings.locale, settings.uiLocale));
|
|
@@ -3254,12 +3690,14 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
|
3254
3690
|
}
|
|
3255
3691
|
|
|
3256
3692
|
if (args.action === "delete") {
|
|
3257
|
-
|
|
3693
|
+
// PL-17/PL-28/PL-32: name — такой же алиас id, как и в репозитории.
|
|
3694
|
+
const id = args.id?.trim() || args.name?.trim();
|
|
3258
3695
|
if (!id) {
|
|
3259
3696
|
return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
|
|
3260
3697
|
}
|
|
3261
3698
|
const before = await loadTemplates();
|
|
3262
|
-
|
|
3699
|
+
// QA-P3.3: name является алиасом id при удалении.
|
|
3700
|
+
const existed = before.some((template) => template.id === id || template.name === id);
|
|
3263
3701
|
await deleteTemplate(id);
|
|
3264
3702
|
return {
|
|
3265
3703
|
content: JSON.stringify({
|
|
@@ -3427,10 +3865,12 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
|
|
|
3427
3865
|
def.legacyShell,
|
|
3428
3866
|
def.worktree,
|
|
3429
3867
|
def.guards,
|
|
3868
|
+
// QA-P0.1 (E-2.1): импорт через transfer_tasks сохраняет tokenBudget.
|
|
3869
|
+
def.tokenBudget,
|
|
3430
3870
|
);
|
|
3431
3871
|
await saveTaskDefinition(def);
|
|
3432
3872
|
imported.push(def.name);
|
|
3433
|
-
} catch (err
|
|
3873
|
+
} catch (err) {
|
|
3434
3874
|
errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
3435
3875
|
}
|
|
3436
3876
|
}
|
|
@@ -3449,9 +3889,157 @@ const sendNotificationExecute = wrapExecute<NotificationArgs>(async (args) => {
|
|
|
3449
3889
|
return { content: JSON.stringify(result) };
|
|
3450
3890
|
});
|
|
3451
3891
|
|
|
3892
|
+
/**
|
|
3893
|
+
* Общий сборщик текста баг-репорта (устраняет дублирование между MCP-тулом
|
|
3894
|
+
* и RPC-хендлером — QA-находка 3.8). Возвращает также сырые логи и метрики
|
|
3895
|
+
* для структурированного payload (F-1.1).
|
|
3896
|
+
*/
|
|
3897
|
+
async function buildBugReportText(input: {
|
|
3898
|
+
description: string;
|
|
3899
|
+
taskName?: string;
|
|
3900
|
+
includeLogs?: boolean;
|
|
3901
|
+
includeAnalytics?: boolean;
|
|
3902
|
+
}): Promise<{ text: string; logs?: string; metrics?: Record<string, number> }> {
|
|
3903
|
+
const lines: string[] = [];
|
|
3904
|
+
lines.push("🐛 *Bug report — agent-steward plugin*");
|
|
3905
|
+
lines.push(`Время: ${new Date().toISOString()}`);
|
|
3906
|
+
lines.push(`Описание: ${input.description}`);
|
|
3907
|
+
let logs: string | undefined;
|
|
3908
|
+
if (input.taskName) {
|
|
3909
|
+
lines.push(`Задача: ${input.taskName}`);
|
|
3910
|
+
if (input.includeLogs) {
|
|
3911
|
+
try {
|
|
3912
|
+
const taskLogs = await getTaskLogs(input.taskName);
|
|
3913
|
+
if (taskLogs.logs) {
|
|
3914
|
+
logs = String(taskLogs.logs).slice(0, 2000);
|
|
3915
|
+
lines.push(`\n--- Логи задачи ${input.taskName} ---`);
|
|
3916
|
+
lines.push(logs);
|
|
3917
|
+
}
|
|
3918
|
+
} catch (err) {
|
|
3919
|
+
lines.push(`\n--- Логи задачи ${input.taskName}: ошибка чтения ---`);
|
|
3920
|
+
lines.push(err instanceof Error ? err.message : String(err));
|
|
3921
|
+
}
|
|
3922
|
+
}
|
|
3923
|
+
}
|
|
3924
|
+
let metrics: Record<string, number> | undefined;
|
|
3925
|
+
if (input.includeAnalytics !== false) {
|
|
3926
|
+
try {
|
|
3927
|
+
const raw = await loadMetrics();
|
|
3928
|
+
metrics = {
|
|
3929
|
+
total: raw.total,
|
|
3930
|
+
success: raw.success,
|
|
3931
|
+
error: raw.error,
|
|
3932
|
+
partial: raw.partial ?? 0,
|
|
3933
|
+
};
|
|
3934
|
+
lines.push("\n--- Метрики ---");
|
|
3935
|
+
lines.push(`Всего запусков: ${metrics.total}`);
|
|
3936
|
+
lines.push(`Успех: ${metrics.success}`);
|
|
3937
|
+
lines.push(`Ошибок: ${metrics.error}`);
|
|
3938
|
+
if (metrics.partial) lines.push(`Частично: ${metrics.partial}`);
|
|
3939
|
+
} catch (err) {
|
|
3940
|
+
lines.push(`\n--- Метрики: ошибка чтения: ${err instanceof Error ? err.message : String(err)} ---`);
|
|
3941
|
+
}
|
|
3942
|
+
try {
|
|
3943
|
+
const records = getHistoryForAnalytics(7);
|
|
3944
|
+
const definitions = await loadTaskDefinitions();
|
|
3945
|
+
const report = buildAnalytics(records, {
|
|
3946
|
+
days: 7,
|
|
3947
|
+
topLimit: 10,
|
|
3948
|
+
tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
|
|
3949
|
+
name: definition.name,
|
|
3950
|
+
matrixParentId: definition.matrixParentId,
|
|
3951
|
+
tokenBudget: definition.tokenBudget,
|
|
3952
|
+
})),
|
|
3953
|
+
});
|
|
3954
|
+
lines.push("\n--- Аналитика (7 дней) ---");
|
|
3955
|
+
lines.push(`Всего запусков: ${report.totals.total}`);
|
|
3956
|
+
lines.push(`Успех: ${report.totals.success}`);
|
|
3957
|
+
lines.push(`Ошибок: ${report.totals.error}`);
|
|
3958
|
+
if (report.totals.partial) lines.push(`Частично: ${report.totals.partial}`);
|
|
3959
|
+
const errorTasks = report.tasks.filter((task) => task.error > 0).slice(0, 5);
|
|
3960
|
+
if (errorTasks.length > 0) {
|
|
3961
|
+
lines.push(
|
|
3962
|
+
`Задачи с ошибками: ${errorTasks.map((task) => `${task.taskName} (${task.error})`).join(", ")}`,
|
|
3963
|
+
);
|
|
3964
|
+
}
|
|
3965
|
+
} catch (err) {
|
|
3966
|
+
lines.push(`\n--- Аналитика: ошибка чтения: ${err instanceof Error ? err.message : String(err)} ---`);
|
|
3967
|
+
}
|
|
3968
|
+
}
|
|
3969
|
+
return { text: lines.join("\n"), logs, metrics };
|
|
3970
|
+
}
|
|
3971
|
+
|
|
3972
|
+
/**
|
|
3973
|
+
* Значения всех секретов из manage_secrets — используются только для
|
|
3974
|
+
* редактирования текста (F-1.4). Ни одно значение не попадает в payload.
|
|
3975
|
+
*/
|
|
3976
|
+
function collectSecretValues(): string[] {
|
|
3977
|
+
const values: string[] = [];
|
|
3978
|
+
for (const item of listSecrets()) {
|
|
3979
|
+
const value = getSecret(item.name);
|
|
3980
|
+
if (value && value.length >= 4) values.push(value);
|
|
3981
|
+
}
|
|
3982
|
+
return values;
|
|
3983
|
+
}
|
|
3984
|
+
|
|
3985
|
+
/** report_bug — отчёт о баге; по умолчанию уходит автору через приёмник F-2. */
|
|
3986
|
+
const reportBugExecute = wrapExecute<ReportBugArgs>(async (args) => {
|
|
3987
|
+
const settings = await loadSettings();
|
|
3988
|
+
const includeLogs = args.includeLogs ?? settings.feedback.includeLogs;
|
|
3989
|
+
const built = await buildBugReportText({
|
|
3990
|
+
description: args.description,
|
|
3991
|
+
taskName: args.taskName,
|
|
3992
|
+
includeLogs,
|
|
3993
|
+
includeAnalytics: args.includeAnalytics,
|
|
3994
|
+
});
|
|
3995
|
+
const secretValues = collectSecretValues();
|
|
3996
|
+
const localText = redactText(built.text, { secrets: secretValues, redactEmails: false });
|
|
3997
|
+
|
|
3998
|
+
const result = await reportFeedback({
|
|
3999
|
+
settings: settings.feedback,
|
|
4000
|
+
destination: args.destination ?? "author",
|
|
4001
|
+
dryRun: args.dryRun,
|
|
4002
|
+
description: args.description,
|
|
4003
|
+
taskName: args.taskName,
|
|
4004
|
+
contactEmail: args.contactEmail ?? settings.feedback.contactEmail,
|
|
4005
|
+
redactedLogs: includeLogs ? built.logs : undefined,
|
|
4006
|
+
metrics: built.metrics,
|
|
4007
|
+
locale: settings.locale,
|
|
4008
|
+
secrets: secretValues,
|
|
4009
|
+
sendLocal: (text) => sendBugReport(text, args.channel),
|
|
4010
|
+
localText,
|
|
4011
|
+
});
|
|
4012
|
+
return {
|
|
4013
|
+
content: JSON.stringify({
|
|
4014
|
+
...result,
|
|
4015
|
+
message:
|
|
4016
|
+
result.mode === "dryRun"
|
|
4017
|
+
? t("feedback.dryRun")
|
|
4018
|
+
: result.mode === "sent"
|
|
4019
|
+
? t("feedback.sent")
|
|
4020
|
+
: result.mode === "outbox"
|
|
4021
|
+
? t("feedback.outbox")
|
|
4022
|
+
: result.mode === "duplicate"
|
|
4023
|
+
? t("feedback.duplicate")
|
|
4024
|
+
: t("feedback.local"),
|
|
4025
|
+
}),
|
|
4026
|
+
};
|
|
4027
|
+
});
|
|
4028
|
+
|
|
3452
4029
|
/** get_dashboard_info — порт дашборда, платформа и активный профиль. */
|
|
3453
4030
|
const getDashboardInfoExecute = wrapExecute<DashboardInfoArgs>(async () => {
|
|
3454
|
-
|
|
4031
|
+
// QA-P3.5: порт из профиля/env может быть «бумажным» (4782), а живой
|
|
4032
|
+
// дашборд слушает 3782. Проверяем маркер и при необходимости находим порт
|
|
4033
|
+
// зондированием стандартных кандидатов, чтобы отчёт совпадал с реальностью.
|
|
4034
|
+
let port = getDashboardPort();
|
|
4035
|
+
let probe = port ? await probeDashboardOn(port) : null;
|
|
4036
|
+
if (!probe?.dashboard) {
|
|
4037
|
+
const discovered = await discoverDashboardPort();
|
|
4038
|
+
if (discovered) {
|
|
4039
|
+
port = discovered;
|
|
4040
|
+
probe = await probeDashboardOn(port);
|
|
4041
|
+
}
|
|
4042
|
+
}
|
|
3455
4043
|
return {
|
|
3456
4044
|
content: JSON.stringify({
|
|
3457
4045
|
success: true,
|
|
@@ -3460,6 +4048,7 @@ const getDashboardInfoExecute = wrapExecute<DashboardInfoArgs>(async () => {
|
|
|
3460
4048
|
platform: scheduler.platform,
|
|
3461
4049
|
title: scheduler.title,
|
|
3462
4050
|
profile: getProfileName(),
|
|
4051
|
+
reachable: probe?.dashboard ?? false,
|
|
3463
4052
|
}),
|
|
3464
4053
|
};
|
|
3465
4054
|
});
|
|
@@ -3486,45 +4075,112 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
|
|
|
3486
4075
|
};
|
|
3487
4076
|
});
|
|
3488
4077
|
|
|
3489
|
-
/**
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
3493
|
-
|
|
4078
|
+
/** PL-35: единый обработчик события для агентского инструмента и RPC/GUI. */
|
|
4079
|
+
type EmitEventCode = "no_subscribers" | "start_failed" | "ok";
|
|
4080
|
+
interface EmitEventResult {
|
|
4081
|
+
success: boolean;
|
|
4082
|
+
code: EmitEventCode;
|
|
4083
|
+
event: string;
|
|
4084
|
+
matched: string[];
|
|
4085
|
+
triggered: string[];
|
|
4086
|
+
failed: { name: string; error: string }[];
|
|
4087
|
+
message: string;
|
|
4088
|
+
}
|
|
4089
|
+
|
|
4090
|
+
const DEFAULT_EVENT_PRIORITY = 5;
|
|
4091
|
+
|
|
4092
|
+
/**
|
|
4093
|
+
* QV-3: проверка, что задача подписана на MCP-событие. Источник `server`
|
|
4094
|
+
* сравнивается только когда он передан вызывающим — это сохраняет обратную
|
|
4095
|
+
* совместимость со старыми вызовами emit_event без указания источника.
|
|
4096
|
+
*/
|
|
4097
|
+
export function matchesMcpEventSubscription(
|
|
4098
|
+
def: TaskDefinition,
|
|
4099
|
+
event: string,
|
|
4100
|
+
server?: string,
|
|
4101
|
+
payload?: unknown,
|
|
4102
|
+
): boolean {
|
|
4103
|
+
if ((def.triggerType ?? "cron") !== "mcp-event") return false;
|
|
4104
|
+
// PL-48: definition может хранить алиас `eventName` (PL-42), поэтому матчер
|
|
4105
|
+
// читает нормализованное событие, а не только каноническое поле `event`.
|
|
4106
|
+
const subscription = normalizeMcpEventTrigger(def.mcpEvent);
|
|
4107
|
+
if (subscription?.event.toLowerCase() !== event.toLowerCase()) return false;
|
|
4108
|
+
const expectedServer = server?.trim();
|
|
4109
|
+
if (
|
|
4110
|
+
expectedServer &&
|
|
4111
|
+
subscription.server.toLowerCase() !== expectedServer.toLowerCase()
|
|
4112
|
+
) {
|
|
4113
|
+
return false;
|
|
3494
4114
|
}
|
|
3495
|
-
|
|
4115
|
+
return matchesEventFilter(subscription.filter, payload);
|
|
4116
|
+
}
|
|
4117
|
+
|
|
4118
|
+
export async function emitEventCore(
|
|
4119
|
+
rawEventName: string | undefined,
|
|
4120
|
+
payload: unknown,
|
|
4121
|
+
server?: string,
|
|
4122
|
+
): Promise<EmitEventResult> {
|
|
4123
|
+
const event = rawEventName?.trim() ?? "";
|
|
4124
|
+
if (!event) {
|
|
4125
|
+
return {
|
|
4126
|
+
success: false,
|
|
4127
|
+
code: "no_subscribers",
|
|
4128
|
+
event,
|
|
4129
|
+
matched: [],
|
|
4130
|
+
triggered: [],
|
|
4131
|
+
failed: [],
|
|
4132
|
+
message: t("tool.event.nameRequiredShort"),
|
|
4133
|
+
};
|
|
4134
|
+
}
|
|
4135
|
+
|
|
3496
4136
|
const definitions = await loadTaskDefinitions();
|
|
3497
4137
|
const matched = definitions
|
|
3498
|
-
.filter(
|
|
3499
|
-
(def) =>
|
|
3500
|
-
def.triggerType === "mcp-event" &&
|
|
3501
|
-
def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
|
|
3502
|
-
matchesEventFilter(def.mcpEvent?.filter, payload),
|
|
3503
|
-
)
|
|
4138
|
+
.filter((def) => matchesMcpEventSubscription(def, event, server, payload))
|
|
3504
4139
|
.sort(
|
|
3505
4140
|
(a, b) =>
|
|
3506
|
-
(normalizePriority(b.priority) ??
|
|
4141
|
+
(normalizePriority(b.priority) ?? DEFAULT_EVENT_PRIORITY) -
|
|
4142
|
+
(normalizePriority(a.priority) ?? DEFAULT_EVENT_PRIORITY),
|
|
3507
4143
|
);
|
|
3508
4144
|
|
|
3509
4145
|
const triggered: string[] = [];
|
|
4146
|
+
const failed: { name: string; error: string }[] = [];
|
|
3510
4147
|
for (const def of matched) {
|
|
3511
4148
|
try {
|
|
3512
4149
|
await runTaskEntry(def.name);
|
|
3513
4150
|
triggered.push(def.name);
|
|
3514
|
-
} catch (err
|
|
3515
|
-
|
|
4151
|
+
} catch (err) {
|
|
4152
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
4153
|
+
failed.push({ name: def.name, error });
|
|
4154
|
+
console.error(`[agent-steward] emit_event: не удалось запустить ${def.name}: ${error}`);
|
|
3516
4155
|
}
|
|
3517
4156
|
}
|
|
4157
|
+
|
|
4158
|
+
const code: EmitEventCode =
|
|
4159
|
+
matched.length === 0 ? "no_subscribers" : failed.length > 0 ? "start_failed" : "ok";
|
|
4160
|
+
const message =
|
|
4161
|
+
code === "no_subscribers"
|
|
4162
|
+
? t("tool.event.none", { event })
|
|
4163
|
+
: code === "start_failed"
|
|
4164
|
+
? t("tool.event.startFailed", { count: failed.length })
|
|
4165
|
+
: t("tool.event.triggered", { count: triggered.length });
|
|
3518
4166
|
return {
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
}),
|
|
4167
|
+
success: true,
|
|
4168
|
+
code,
|
|
4169
|
+
event,
|
|
4170
|
+
matched: matched.map((def) => def.name),
|
|
4171
|
+
triggered,
|
|
4172
|
+
failed,
|
|
4173
|
+
message,
|
|
3527
4174
|
};
|
|
4175
|
+
}
|
|
4176
|
+
|
|
4177
|
+
/** emit_event — запуск задач, подписанных на MCP-событие. */
|
|
4178
|
+
const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
|
|
4179
|
+
const result = await emitEventCore(args.eventName, args.payload ?? {}, args.server);
|
|
4180
|
+
if (!result.success) {
|
|
4181
|
+
return { content: JSON.stringify({ ...result, error: result.message }) };
|
|
4182
|
+
}
|
|
4183
|
+
return { content: JSON.stringify(result) };
|
|
3528
4184
|
});
|
|
3529
4185
|
|
|
3530
4186
|
/** manage_secrets — зашифрованное хранилище секретов. */
|
|
@@ -3596,14 +4252,22 @@ const getAuditLogExecute = wrapExecute<AuditLogArgs>(async (args) => {
|
|
|
3596
4252
|
function withAudit<A>(
|
|
3597
4253
|
toolName: string,
|
|
3598
4254
|
describe: (args: A) => Omit<AuditEntryInput, "actor"> | null,
|
|
3599
|
-
execute: (args: A, context:
|
|
3600
|
-
): (args: A, context:
|
|
3601
|
-
return async (args: A, context:
|
|
4255
|
+
execute: (args: A, context: ToolExecuteContext) => Promise<Tool.Result>,
|
|
4256
|
+
): (args: A, context: ToolExecuteContext) => Promise<Tool.Result> {
|
|
4257
|
+
return async (args: A, context: ToolExecuteContext) => {
|
|
3602
4258
|
const result = await execute(args, context);
|
|
3603
4259
|
try {
|
|
3604
|
-
const
|
|
3605
|
-
const
|
|
3606
|
-
|
|
4260
|
+
const content = result.content;
|
|
4261
|
+
const raw = typeof content === "string" ? content : "";
|
|
4262
|
+
const parsed: unknown = raw ? JSON.parse(raw) : null;
|
|
4263
|
+
if (
|
|
4264
|
+
typeof parsed === "object" &&
|
|
4265
|
+
parsed !== null &&
|
|
4266
|
+
"success" in parsed &&
|
|
4267
|
+
parsed.success === false
|
|
4268
|
+
) {
|
|
4269
|
+
return result;
|
|
4270
|
+
}
|
|
3607
4271
|
const entry = describe(args);
|
|
3608
4272
|
if (entry) {
|
|
3609
4273
|
recordAudit({ ...entry, actor: "mcp", source: toolName });
|
|
@@ -3615,13 +4279,26 @@ function withAudit<A>(
|
|
|
3615
4279
|
};
|
|
3616
4280
|
}
|
|
3617
4281
|
|
|
4282
|
+
/** Поля payload-а GUI-RPC, которые читают правила аудита. */
|
|
4283
|
+
interface RpcAuditInput {
|
|
4284
|
+
name?: string;
|
|
4285
|
+
path?: string;
|
|
4286
|
+
id?: string;
|
|
4287
|
+
runId?: string;
|
|
4288
|
+
eventName?: string;
|
|
4289
|
+
taskName?: string;
|
|
4290
|
+
}
|
|
4291
|
+
|
|
4292
|
+
/** Тип обработчика GUI-RPC: конкретные аргументы известны только вызывающей стороне. */
|
|
4293
|
+
type RpcHandler = (...args: never[]) => unknown;
|
|
4294
|
+
|
|
3618
4295
|
/** Правила аудита для RPC-методов GUI (Спринт 26). */
|
|
3619
4296
|
const RPC_AUDIT_RULES: Record<
|
|
3620
4297
|
string,
|
|
3621
4298
|
{
|
|
3622
4299
|
action: string;
|
|
3623
4300
|
targetType: string;
|
|
3624
|
-
target: (input:
|
|
4301
|
+
target: (input: RpcAuditInput) => string;
|
|
3625
4302
|
}
|
|
3626
4303
|
> = {
|
|
3627
4304
|
create_task: { action: "task.create", targetType: "task", target: (i) => i.name ?? "" },
|
|
@@ -3705,19 +4382,25 @@ const RPC_AUDIT_RULES: Record<
|
|
|
3705
4382
|
* Оборачивает RPC-обработчики GUI: успешные мутации попадают в audit log
|
|
3706
4383
|
* с actor=gui. Ошибки аудита не влияют на ответ GUI.
|
|
3707
4384
|
*/
|
|
3708
|
-
function withRpcAudit<T extends Record<string,
|
|
3709
|
-
const wrapped: Record<string,
|
|
3710
|
-
|
|
4385
|
+
function withRpcAudit<T extends Record<string, RpcHandler>>(handlers: T): T {
|
|
4386
|
+
const wrapped: Record<string, RpcHandler> = {};
|
|
4387
|
+
const entries: [string, RpcHandler][] = Object.entries(handlers);
|
|
4388
|
+
for (const [name, handler] of entries) {
|
|
3711
4389
|
const rule = RPC_AUDIT_RULES[name];
|
|
3712
4390
|
if (!rule || typeof handler !== "function") {
|
|
3713
4391
|
wrapped[name] = handler;
|
|
3714
4392
|
continue;
|
|
3715
4393
|
}
|
|
3716
|
-
wrapped[name] = async (...args:
|
|
3717
|
-
const input = args[0] ?? {};
|
|
4394
|
+
wrapped[name] = async (...args: never[]) => {
|
|
4395
|
+
const input = (args[0] ?? {}) as RpcAuditInput;
|
|
3718
4396
|
const result = await handler(...args);
|
|
3719
4397
|
try {
|
|
3720
|
-
|
|
4398
|
+
const failed =
|
|
4399
|
+
typeof result === "object" &&
|
|
4400
|
+
result !== null &&
|
|
4401
|
+
"success" in result &&
|
|
4402
|
+
result.success === false;
|
|
4403
|
+
if (!failed) {
|
|
3721
4404
|
recordAudit({
|
|
3722
4405
|
action: rule.action,
|
|
3723
4406
|
targetType: rule.targetType,
|
|
@@ -3757,7 +4440,7 @@ async function refreshTriggers(): Promise<void> {
|
|
|
3757
4440
|
if (fileWatcherManager) {
|
|
3758
4441
|
try {
|
|
3759
4442
|
await fileWatcherManager.refresh();
|
|
3760
|
-
} catch (err
|
|
4443
|
+
} catch (err) {
|
|
3761
4444
|
console.error(
|
|
3762
4445
|
`[agent-steward] Не удалось обновить файловые триггеры: ${
|
|
3763
4446
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3768,7 +4451,7 @@ async function refreshTriggers(): Promise<void> {
|
|
|
3768
4451
|
if (gitTriggerManager) {
|
|
3769
4452
|
try {
|
|
3770
4453
|
await gitTriggerManager.refresh();
|
|
3771
|
-
} catch (err
|
|
4454
|
+
} catch (err) {
|
|
3772
4455
|
console.error(
|
|
3773
4456
|
`[agent-steward] Не удалось обновить git-триггеры: ${
|
|
3774
4457
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3801,7 +4484,27 @@ async function scheduleEventRun(taskName: string, reason: string): Promise<void>
|
|
|
3801
4484
|
const state = activeWindowState(now, options);
|
|
3802
4485
|
|
|
3803
4486
|
if (state.active || policy === "run") {
|
|
3804
|
-
|
|
4487
|
+
const startedAt = now.toISOString();
|
|
4488
|
+
try {
|
|
4489
|
+
await runTaskEntry(taskName);
|
|
4490
|
+
} catch (err) {
|
|
4491
|
+
// PL-53: отказ старта по событийному триггеру раньше уходил только
|
|
4492
|
+
// в console.error хоста и не оставлял следа в истории/журнале.
|
|
4493
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
4494
|
+
const runId = recordRun(taskName, "error", startedAt, 0, message);
|
|
4495
|
+
appendStructuredLog({
|
|
4496
|
+
event: "trigger.start_failed",
|
|
4497
|
+
runId,
|
|
4498
|
+
task: taskName,
|
|
4499
|
+
status: "error",
|
|
4500
|
+
startedAt,
|
|
4501
|
+
finishedAt: new Date().toISOString(),
|
|
4502
|
+
durationMs: 0,
|
|
4503
|
+
error: message,
|
|
4504
|
+
reason,
|
|
4505
|
+
});
|
|
4506
|
+
throw err;
|
|
4507
|
+
}
|
|
3805
4508
|
console.log(
|
|
3806
4509
|
`[agent-steward] Запуск задачи "${taskName}" (${reason}).`,
|
|
3807
4510
|
);
|
|
@@ -3833,7 +4536,7 @@ async function scheduleEventRun(taskName: string, reason: string): Promise<void>
|
|
|
3833
4536
|
)} мин: ${state.reason ?? "вне окна"}.`,
|
|
3834
4537
|
);
|
|
3835
4538
|
const timer = setTimeout(() => {
|
|
3836
|
-
void scheduleEventRun(taskName, reason).catch((err
|
|
4539
|
+
void scheduleEventRun(taskName, reason).catch((err) => {
|
|
3837
4540
|
console.error(
|
|
3838
4541
|
`[agent-steward] Не удалось запустить отложенную задачу "${taskName}": ${
|
|
3839
4542
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3885,7 +4588,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
3885
4588
|
initDb();
|
|
3886
4589
|
try {
|
|
3887
4590
|
await migrateJsonToDb();
|
|
3888
|
-
} catch (err
|
|
4591
|
+
} catch (err) {
|
|
3889
4592
|
console.error(
|
|
3890
4593
|
`[migrate] Не удалось мигрировать JSON → SQLite: ${
|
|
3891
4594
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3894,13 +4597,29 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
3894
4597
|
}
|
|
3895
4598
|
try {
|
|
3896
4599
|
recoverInterruptedRuns();
|
|
3897
|
-
} catch (err
|
|
4600
|
+
} catch (err) {
|
|
3898
4601
|
console.error(
|
|
3899
4602
|
`[recovery] Не удалось восстановить незавершённые запуски: ${
|
|
3900
4603
|
err instanceof Error ? err.message : String(err)
|
|
3901
4604
|
}`,
|
|
3902
4605
|
);
|
|
3903
4606
|
}
|
|
4607
|
+
// Деталь 3.8 (F-1.6): повторяем недоставленные отчёты из outbox.
|
|
4608
|
+
// Fire-and-forget: сеть не должна задерживать или ломать старт плагина.
|
|
4609
|
+
void loadSettings()
|
|
4610
|
+
.then((settings) => flushOutbox(settings.feedback))
|
|
4611
|
+
.then((result) => {
|
|
4612
|
+
if (result.sent > 0) {
|
|
4613
|
+
console.log(`[feedback] Из outbox доставлено отчётов: ${result.sent}`);
|
|
4614
|
+
}
|
|
4615
|
+
})
|
|
4616
|
+
.catch((err: unknown) => {
|
|
4617
|
+
console.error(
|
|
4618
|
+
`[feedback] Ошибка повтора outbox: ${
|
|
4619
|
+
err instanceof Error ? err.message : String(err)
|
|
4620
|
+
}`,
|
|
4621
|
+
);
|
|
4622
|
+
});
|
|
3904
4623
|
// P1-14: pid:-записи fallback'а не переживают перезагрузку. Чистим их и
|
|
3905
4624
|
// пересоздаём будущие one-shot, иначе после reboot можно убить чужой pid.
|
|
3906
4625
|
if (scheduler instanceof LinuxScheduler) {
|
|
@@ -3913,7 +4632,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
3913
4632
|
`живо ${report.kept}.`,
|
|
3914
4633
|
);
|
|
3915
4634
|
}
|
|
3916
|
-
} catch (err
|
|
4635
|
+
} catch (err) {
|
|
3917
4636
|
console.error(
|
|
3918
4637
|
`[scheduler] Не удалось очистить fallback-записи: ${
|
|
3919
4638
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3938,7 +4657,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
3938
4657
|
);
|
|
3939
4658
|
}
|
|
3940
4659
|
})
|
|
3941
|
-
.catch((err
|
|
4660
|
+
.catch((err) => {
|
|
3942
4661
|
console.error(
|
|
3943
4662
|
`[retention] Не удалось очистить историю: ${
|
|
3944
4663
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3948,7 +4667,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
3948
4667
|
|
|
3949
4668
|
// Спринт 19: автопродолжение задач, поставленных на паузу до даты.
|
|
3950
4669
|
// Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
|
|
3951
|
-
void resumeExpiredPauses().catch((err
|
|
4670
|
+
void resumeExpiredPauses().catch((err) => {
|
|
3952
4671
|
console.error(
|
|
3953
4672
|
`[agent-steward] Не удалось проверить автопродолжение: ${
|
|
3954
4673
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3956,7 +4675,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
3956
4675
|
);
|
|
3957
4676
|
});
|
|
3958
4677
|
const pausedUntilTimer = setInterval(() => {
|
|
3959
|
-
void resumeExpiredPauses().catch((err
|
|
4678
|
+
void resumeExpiredPauses().catch((err) => {
|
|
3960
4679
|
console.error(
|
|
3961
4680
|
`[agent-steward] Не удалось проверить автопродолжение: ${
|
|
3962
4681
|
err instanceof Error ? err.message : String(err)
|
|
@@ -3970,7 +4689,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
3970
4689
|
// старте и далее раз в минуту; таймер не держит процесс Node живым.
|
|
3971
4690
|
const notificationTimer = setInterval(() => {
|
|
3972
4691
|
void maybeSendDigest().catch(() => undefined);
|
|
3973
|
-
void checkStuckMatrices().catch((err
|
|
4692
|
+
void checkStuckMatrices().catch((err) => {
|
|
3974
4693
|
console.error(
|
|
3975
4694
|
`[agent-steward] Детектор зависших матриц: ${
|
|
3976
4695
|
err instanceof Error ? err.message : String(err)
|
|
@@ -4026,7 +4745,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
4026
4745
|
console.log(
|
|
4027
4746
|
`[agent-steward] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`,
|
|
4028
4747
|
);
|
|
4029
|
-
} catch (err
|
|
4748
|
+
} catch (err) {
|
|
4030
4749
|
console.error(
|
|
4031
4750
|
`[agent-steward] Не удалось восстановить задачу "${def.name}": ${
|
|
4032
4751
|
err instanceof Error ? err.message : String(err)
|
|
@@ -4034,7 +4753,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
4034
4753
|
);
|
|
4035
4754
|
}
|
|
4036
4755
|
}
|
|
4037
|
-
} catch (err
|
|
4756
|
+
} catch (err) {
|
|
4038
4757
|
console.error(
|
|
4039
4758
|
`[agent-steward] Catch-up ошибка: ${err instanceof Error ? err.message : String(err)}`,
|
|
4040
4759
|
);
|
|
@@ -4046,7 +4765,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
4046
4765
|
fileWatcherManager = new FileWatchManager(async (taskName) => {
|
|
4047
4766
|
try {
|
|
4048
4767
|
await scheduleEventRun(taskName, "изменение отслеживаемого файла");
|
|
4049
|
-
} catch (err
|
|
4768
|
+
} catch (err) {
|
|
4050
4769
|
console.error(
|
|
4051
4770
|
`[agent-steward] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${
|
|
4052
4771
|
err instanceof Error ? err.message : String(err)
|
|
@@ -4060,7 +4779,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
|
|
|
4060
4779
|
gitTriggerManager = new GitTriggerManager(async (taskName, info) => {
|
|
4061
4780
|
try {
|
|
4062
4781
|
await scheduleEventRun(taskName, `новый коммит ${info.head?.slice(0, 7) ?? ""}`);
|
|
4063
|
-
} catch (err
|
|
4782
|
+
} catch (err) {
|
|
4064
4783
|
console.error(
|
|
4065
4784
|
`[agent-steward] Не удалось запустить задачу "${taskName}" по git-триггеру: ${
|
|
4066
4785
|
err instanceof Error ? err.message : String(err)
|
|
@@ -4119,6 +4838,7 @@ export interface ToolHandlers {
|
|
|
4119
4838
|
manage_profiles: typeof manageProfilesExecute;
|
|
4120
4839
|
transfer_tasks: typeof transferTasksExecute;
|
|
4121
4840
|
send_notification: typeof sendNotificationExecute;
|
|
4841
|
+
report_bug: typeof reportBugExecute;
|
|
4122
4842
|
get_dashboard_info: typeof getDashboardInfoExecute;
|
|
4123
4843
|
cleanup_history: typeof cleanupHistoryExecute;
|
|
4124
4844
|
emit_event: typeof emitEventExecute;
|
|
@@ -4159,6 +4879,7 @@ export function createToolHandlers(_runtime: SchedulerRuntime): ToolHandlers {
|
|
|
4159
4879
|
manage_profiles: manageProfilesExecute,
|
|
4160
4880
|
transfer_tasks: transferTasksExecute,
|
|
4161
4881
|
send_notification: sendNotificationExecute,
|
|
4882
|
+
report_bug: reportBugExecute,
|
|
4162
4883
|
get_dashboard_info: getDashboardInfoExecute,
|
|
4163
4884
|
cleanup_history: cleanupHistoryExecute,
|
|
4164
4885
|
emit_event: emitEventExecute,
|
|
@@ -4214,6 +4935,8 @@ export function createShutdownHandler(
|
|
|
4214
4935
|
}
|
|
4215
4936
|
// Чекпойнт WAL выполняется в closeDb.
|
|
4216
4937
|
closeDb();
|
|
4938
|
+
// QA/PL-10: выгрузка действительно завершена — запрещаем автосброс ворот.
|
|
4939
|
+
shutdownGate.complete();
|
|
4217
4940
|
};
|
|
4218
4941
|
}
|
|
4219
4942
|
|
|
@@ -4221,13 +4944,28 @@ export function createShutdownHandler(
|
|
|
4221
4944
|
* Декларативное описание инструмента: всё, что нужно любому entrypoint'у,
|
|
4222
4945
|
* чтобы зарегистрировать его в своей версии API.
|
|
4223
4946
|
*/
|
|
4947
|
+
/**
|
|
4948
|
+
* Бивариантные сигнатуры (паттерн `bivarianceHack`). Типизированные
|
|
4949
|
+
* обработчики из `ToolHandlers` принимают конкретные `z.infer`-аргументы,
|
|
4950
|
+
* а реестр хранит их как `unknown`: вход проверен Zod-схемой инструмента
|
|
4951
|
+
* до вызова, поэтому приведение типов здесь не требуется.
|
|
4952
|
+
*/
|
|
4953
|
+
type ToolSpecExecute = {
|
|
4954
|
+
bivarianceHack(args: unknown, context: ToolExecuteContext): Promise<Tool.Result>;
|
|
4955
|
+
}["bivarianceHack"];
|
|
4956
|
+
type ToolSpecAudit = {
|
|
4957
|
+
bivarianceHack(args: unknown): Omit<AuditEntryInput, "actor"> | null;
|
|
4958
|
+
}["bivarianceHack"];
|
|
4959
|
+
|
|
4224
4960
|
export interface ToolSpec {
|
|
4225
4961
|
name: string;
|
|
4226
|
-
input:
|
|
4962
|
+
input: z.ZodTypeAny;
|
|
4963
|
+
/** PL-43: схема структурированного output (только V2 Code Mode; V1 использует content). */
|
|
4964
|
+
output?: z.ZodTypeAny;
|
|
4227
4965
|
description: string;
|
|
4228
|
-
execute:
|
|
4966
|
+
execute: ToolSpecExecute;
|
|
4229
4967
|
/** Правила аудита; null/undefined — операция не пишется в журнал. */
|
|
4230
|
-
audit?:
|
|
4968
|
+
audit?: ToolSpecAudit;
|
|
4231
4969
|
}
|
|
4232
4970
|
|
|
4233
4971
|
/**
|
|
@@ -4237,7 +4975,17 @@ export interface ToolSpec {
|
|
|
4237
4975
|
* одинаковые имена, схемы, описания и обработчики. Аудит навешивается здесь
|
|
4238
4976
|
* один раз, чтобы обе линии вели журнал одинаково.
|
|
4239
4977
|
*/
|
|
4240
|
-
export function createToolSpecs(
|
|
4978
|
+
export function createToolSpecs(
|
|
4979
|
+
runtime: SchedulerRuntime,
|
|
4980
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
4981
|
+
): ToolSpec[] {
|
|
4982
|
+
// QV-8: обёртка задач выставляет маркер дочернего прогона перед `opencode run`.
|
|
4983
|
+
// Такой ребёнок не должен получать инструменты планировщика — иначе он видит
|
|
4984
|
+
// весь surface родителя и может рекурсивно создавать задачи.
|
|
4985
|
+
if (isChildRunMode(env)) {
|
|
4986
|
+
console.log(`[qv8] ${CHILD_RUN_ENV}: инструменты планировщика не регистрируются`);
|
|
4987
|
+
return [];
|
|
4988
|
+
}
|
|
4241
4989
|
const handlers = createToolHandlers(runtime);
|
|
4242
4990
|
return [
|
|
4243
4991
|
{
|
|
@@ -4248,15 +4996,16 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4248
4996
|
"Every run goes through a timeout + lock-file wrapper, so overlapping runs are skipped. " +
|
|
4249
4997
|
"Without workingDirectory the task runs in the current project folder, where opencode run picks up the project's opencode.json and MCP servers.",
|
|
4250
4998
|
audit: (args: ScheduleArgs) => ({ action: "task.create", targetType: "task", target: args.name }),
|
|
4251
|
-
execute: handlers.schedule_task
|
|
4999
|
+
execute: handlers.schedule_task,
|
|
4252
5000
|
},
|
|
4253
5001
|
{
|
|
4254
5002
|
name: "list_tasks",
|
|
4255
5003
|
input: listTasksSchema,
|
|
5004
|
+
output: listTasksOutputSchema,
|
|
4256
5005
|
description:
|
|
4257
5006
|
`Lists plugin tasks from the scheduler (${scheduler.title}) with schedule, status, next chained task and working directory. ` +
|
|
4258
|
-
"Matrix parents include a per-clone summary.",
|
|
4259
|
-
execute: handlers.list_tasks
|
|
5007
|
+
"Matrix parents include a per-clone summary. Returns structured output in Code Mode; content remains a JSON string for V1 compatibility.",
|
|
5008
|
+
execute: handlers.list_tasks,
|
|
4260
5009
|
},
|
|
4261
5010
|
{
|
|
4262
5011
|
name: "update_task",
|
|
@@ -4265,7 +5014,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4265
5014
|
"Partially updates an existing task: omitted fields keep their current values, empty strings/arrays clear them. " +
|
|
4266
5015
|
"Matrix changes are synced (clones are diffed, running clones are never touched); pass matrix: null to remove the matrix and its clones.",
|
|
4267
5016
|
audit: (args: UpdateArgs) => ({ action: "task.update", targetType: "task", target: args.name }),
|
|
4268
|
-
execute: handlers.update_task
|
|
5017
|
+
execute: handlers.update_task,
|
|
4269
5018
|
},
|
|
4270
5019
|
{
|
|
4271
5020
|
name: "delete_task",
|
|
@@ -4274,7 +5023,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4274
5023
|
`Deletes a task from the scheduler (${scheduler.title}) by name. ` +
|
|
4275
5024
|
"Deleting a matrix parent also deletes its clones and aggregator; deleting a single clone is refused (delete the whole matrix instead).",
|
|
4276
5025
|
audit: (args: DeleteArgs) => ({ action: "task.delete", targetType: "task", target: args.name }),
|
|
4277
|
-
execute: handlers.delete_task
|
|
5026
|
+
execute: handlers.delete_task,
|
|
4278
5027
|
},
|
|
4279
5028
|
{
|
|
4280
5029
|
name: "run_task_now",
|
|
@@ -4283,7 +5032,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4283
5032
|
`Runs a task immediately in the scheduler (${scheduler.title}) for testing. ` +
|
|
4284
5033
|
"Runs through the timeout + lock wrapper. For a matrix parent this starts the fan-out instead of the parent itself.",
|
|
4285
5034
|
audit: (args: RunNowArgs) => ({ action: "task.run", targetType: "task", target: args.name }),
|
|
4286
|
-
execute: handlers.run_task_now
|
|
5035
|
+
execute: handlers.run_task_now,
|
|
4287
5036
|
},
|
|
4288
5037
|
{
|
|
4289
5038
|
name: "pause_task",
|
|
@@ -4291,7 +5040,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4291
5040
|
description:
|
|
4292
5041
|
"Pauses a task in the OS scheduler. For a matrix parent every clone is paused (the parent itself never runs).",
|
|
4293
5042
|
audit: (args: PauseArgs) => ({ action: "task.pause", targetType: "task", target: args.name }),
|
|
4294
|
-
execute: handlers.pause_task
|
|
5043
|
+
execute: handlers.pause_task,
|
|
4295
5044
|
},
|
|
4296
5045
|
{
|
|
4297
5046
|
name: "resume_task",
|
|
@@ -4299,7 +5048,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4299
5048
|
description:
|
|
4300
5049
|
"Resumes a previously paused task. For a matrix parent every clone is resumed.",
|
|
4301
5050
|
audit: (args: ResumeArgs) => ({ action: "task.resume", targetType: "task", target: args.name }),
|
|
4302
|
-
execute: handlers.resume_task
|
|
5051
|
+
execute: handlers.resume_task,
|
|
4303
5052
|
},
|
|
4304
5053
|
{
|
|
4305
5054
|
name: "get_history",
|
|
@@ -4307,21 +5056,21 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4307
5056
|
description:
|
|
4308
5057
|
"Returns recent run history (status, duration, tokens, cost, model, Quality Gate and pre/post-flight results). " +
|
|
4309
5058
|
"Filter by taskName and/or status; newest first.",
|
|
4310
|
-
execute: handlers.get_history
|
|
5059
|
+
execute: handlers.get_history,
|
|
4311
5060
|
},
|
|
4312
5061
|
{
|
|
4313
5062
|
name: "get_task_logs",
|
|
4314
5063
|
input: getTaskLogsSchema,
|
|
4315
5064
|
description:
|
|
4316
5065
|
"Returns the tail of a task's log file written by the run wrapper. Use it to diagnose failed runs.",
|
|
4317
|
-
execute: handlers.get_task_logs
|
|
5066
|
+
execute: handlers.get_task_logs,
|
|
4318
5067
|
},
|
|
4319
5068
|
{
|
|
4320
5069
|
name: "dry_run",
|
|
4321
5070
|
input: dryRunSchema,
|
|
4322
5071
|
description:
|
|
4323
5072
|
"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.",
|
|
4324
|
-
execute: handlers.dry_run
|
|
5073
|
+
execute: handlers.dry_run,
|
|
4325
5074
|
},
|
|
4326
5075
|
{
|
|
4327
5076
|
name: "manage_workspaces",
|
|
@@ -4336,7 +5085,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4336
5085
|
targetType: "workspace",
|
|
4337
5086
|
target: args.id || args.name || "",
|
|
4338
5087
|
},
|
|
4339
|
-
execute: handlers.manage_workspaces
|
|
5088
|
+
execute: handlers.manage_workspaces,
|
|
4340
5089
|
},
|
|
4341
5090
|
{
|
|
4342
5091
|
name: "matrix_control",
|
|
@@ -4351,29 +5100,31 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4351
5100
|
target: args.name || "",
|
|
4352
5101
|
}
|
|
4353
5102
|
: null,
|
|
4354
|
-
execute: handlers.matrix_control
|
|
5103
|
+
execute: handlers.matrix_control,
|
|
4355
5104
|
},
|
|
4356
5105
|
{
|
|
4357
5106
|
name: "get_metrics",
|
|
4358
5107
|
input: getMetricsSchema,
|
|
4359
5108
|
description:
|
|
4360
5109
|
"Returns aggregate run metrics: total runs, successes and failures across all tasks.",
|
|
4361
|
-
execute: handlers.get_metrics
|
|
5110
|
+
execute: handlers.get_metrics,
|
|
4362
5111
|
},
|
|
4363
5112
|
{
|
|
4364
5113
|
name: "get_analytics",
|
|
4365
5114
|
input: getAnalyticsSchema,
|
|
4366
5115
|
description:
|
|
4367
5116
|
"Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
|
|
4368
|
-
execute: handlers.get_analytics
|
|
5117
|
+
execute: handlers.get_analytics,
|
|
4369
5118
|
},
|
|
4370
5119
|
{
|
|
4371
5120
|
name: "self_analysis",
|
|
4372
5121
|
input: selfAnalysisSchema,
|
|
4373
5122
|
description:
|
|
4374
5123
|
"Generates a self-analysis report: system health score, anomaly detection, trend analysis and optimization recommendations. " +
|
|
4375
|
-
"Helps identify performance issues, cost spikes and reliability problems."
|
|
4376
|
-
|
|
5124
|
+
"Helps identify performance issues, cost spikes and reliability problems. " +
|
|
5125
|
+
"In health.components, successRate and errorRate are normalized 0..100 scores (higher is better): " +
|
|
5126
|
+
"errorRate = 100 - 100 * error / total, so it is NOT the raw error percentage.",
|
|
5127
|
+
execute: handlers.self_analysis,
|
|
4377
5128
|
},
|
|
4378
5129
|
{
|
|
4379
5130
|
name: "manage_settings",
|
|
@@ -4384,7 +5135,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4384
5135
|
args.action === "update"
|
|
4385
5136
|
? { action: "settings.update", targetType: "settings", target: "global" }
|
|
4386
5137
|
: null,
|
|
4387
|
-
execute: handlers.manage_settings
|
|
5138
|
+
execute: handlers.manage_settings,
|
|
4388
5139
|
},
|
|
4389
5140
|
{
|
|
4390
5141
|
name: "manage_local_ai",
|
|
@@ -4397,7 +5148,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4397
5148
|
args.action === "update"
|
|
4398
5149
|
? { action: "localAi.update", targetType: "settings", target: "triage" }
|
|
4399
5150
|
: null,
|
|
4400
|
-
execute: handlers.manage_local_ai
|
|
5151
|
+
execute: handlers.manage_local_ai,
|
|
4401
5152
|
},
|
|
4402
5153
|
{
|
|
4403
5154
|
name: "manage_templates",
|
|
@@ -4412,7 +5163,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4412
5163
|
targetType: "template",
|
|
4413
5164
|
target: args.id || args.name || "",
|
|
4414
5165
|
},
|
|
4415
|
-
execute: handlers.manage_templates
|
|
5166
|
+
execute: handlers.manage_templates,
|
|
4416
5167
|
},
|
|
4417
5168
|
{
|
|
4418
5169
|
name: "manage_profiles",
|
|
@@ -4427,7 +5178,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4427
5178
|
targetType: "profile",
|
|
4428
5179
|
target: args.name || "",
|
|
4429
5180
|
},
|
|
4430
|
-
execute: handlers.manage_profiles
|
|
5181
|
+
execute: handlers.manage_profiles,
|
|
4431
5182
|
},
|
|
4432
5183
|
{
|
|
4433
5184
|
name: "transfer_tasks",
|
|
@@ -4438,21 +5189,28 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4438
5189
|
args.action === "import"
|
|
4439
5190
|
? { action: "tasks.import", targetType: "tasks", target: "snapshot" }
|
|
4440
5191
|
: null,
|
|
4441
|
-
execute: handlers.transfer_tasks
|
|
5192
|
+
execute: handlers.transfer_tasks,
|
|
4442
5193
|
},
|
|
4443
5194
|
{
|
|
4444
5195
|
name: "send_notification",
|
|
4445
5196
|
input: sendNotificationSchema,
|
|
4446
5197
|
description:
|
|
4447
5198
|
"Sends a test notification through the configured channel or sends the digest immediately.",
|
|
4448
|
-
execute: handlers.send_notification
|
|
5199
|
+
execute: handlers.send_notification,
|
|
5200
|
+
},
|
|
5201
|
+
{
|
|
5202
|
+
name: "report_bug",
|
|
5203
|
+
input: reportBugSchema,
|
|
5204
|
+
description:
|
|
5205
|
+
"Sends a bug report from the plugin user to the developer via configured notification channels (Telegram/webhook/native). Includes optional task logs and recent analytics.",
|
|
5206
|
+
execute: handlers.report_bug,
|
|
4449
5207
|
},
|
|
4450
5208
|
{
|
|
4451
5209
|
name: "get_dashboard_info",
|
|
4452
5210
|
input: getDashboardInfoSchema,
|
|
4453
5211
|
description:
|
|
4454
5212
|
"Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
|
|
4455
|
-
execute: handlers.get_dashboard_info
|
|
5213
|
+
execute: handlers.get_dashboard_info,
|
|
4456
5214
|
},
|
|
4457
5215
|
{
|
|
4458
5216
|
name: "cleanup_history",
|
|
@@ -4460,7 +5218,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4460
5218
|
description:
|
|
4461
5219
|
"Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
|
|
4462
5220
|
audit: () => ({ action: "history.cleanup", targetType: "history", target: "runs" }),
|
|
4463
|
-
execute: handlers.cleanup_history
|
|
5221
|
+
execute: handlers.cleanup_history,
|
|
4464
5222
|
},
|
|
4465
5223
|
{
|
|
4466
5224
|
name: "manage_secrets",
|
|
@@ -4477,7 +5235,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4477
5235
|
targetType: "secret",
|
|
4478
5236
|
target: (args.name ?? "").trim(),
|
|
4479
5237
|
},
|
|
4480
|
-
execute: handlers.manage_secrets
|
|
5238
|
+
execute: handlers.manage_secrets,
|
|
4481
5239
|
},
|
|
4482
5240
|
{
|
|
4483
5241
|
name: "get_audit_log",
|
|
@@ -4485,14 +5243,14 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4485
5243
|
description:
|
|
4486
5244
|
"Returns the audit journal of task and settings mutations: who changed what, when and through which interface (mcp, gui, http). " +
|
|
4487
5245
|
"Filter by action, target, actor, time range and limit. Secret values are redacted.",
|
|
4488
|
-
execute: handlers.get_audit_log
|
|
5246
|
+
execute: handlers.get_audit_log,
|
|
4489
5247
|
},
|
|
4490
5248
|
{
|
|
4491
5249
|
name: "pipeline_validate",
|
|
4492
5250
|
input: pipelineValidateSchema,
|
|
4493
5251
|
description:
|
|
4494
5252
|
"Проверяет opencode.pipeline.yaml (путь к файлу или исходник): валидирует version, шаги, зависимости, циклы, cron-расписание, matrix, модель, окна запуска и другие инварианты конвейера. Не применяет изменения.",
|
|
4495
|
-
execute: handlers.pipeline_validate
|
|
5253
|
+
execute: handlers.pipeline_validate,
|
|
4496
5254
|
},
|
|
4497
5255
|
{
|
|
4498
5256
|
name: "pipeline_apply",
|
|
@@ -4504,21 +5262,21 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
|
|
|
4504
5262
|
targetType: "pipeline",
|
|
4505
5263
|
target: args.source ?? args.path ?? "",
|
|
4506
5264
|
}),
|
|
4507
|
-
execute: handlers.pipeline_apply
|
|
5265
|
+
execute: handlers.pipeline_apply,
|
|
4508
5266
|
},
|
|
4509
5267
|
{
|
|
4510
5268
|
name: "pipeline_export",
|
|
4511
5269
|
input: pipelineExportSchema,
|
|
4512
5270
|
description:
|
|
4513
5271
|
"Выгружает задачи указанного конвейера (pipelineName) как opencode.pipeline.yaml: шаги, зависимости, matrix, кастомные настройки шага.",
|
|
4514
|
-
execute: handlers.pipeline_export
|
|
5272
|
+
execute: handlers.pipeline_export,
|
|
4515
5273
|
},
|
|
4516
5274
|
{
|
|
4517
5275
|
name: "emit_event",
|
|
4518
5276
|
input: emitEventSchema,
|
|
4519
5277
|
description:
|
|
4520
5278
|
"Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
|
|
4521
|
-
execute: handlers.emit_event
|
|
5279
|
+
execute: handlers.emit_event,
|
|
4522
5280
|
},
|
|
4523
5281
|
];
|
|
4524
5282
|
}
|
|
@@ -4547,6 +5305,14 @@ async function startSchedulerDashboard(): Promise<void> {
|
|
|
4547
5305
|
const v2Plugin = Plugin.define({
|
|
4548
5306
|
id: "opencode-windows-scheduler",
|
|
4549
5307
|
setup: async (ctx) => {
|
|
5308
|
+
if (isChildRunMode()) {
|
|
5309
|
+
console.log(`[qv8] ${CHILD_RUN_ENV}: дочерний прогон, пропускаю регистрацию плагина`);
|
|
5310
|
+
return async () => undefined;
|
|
5311
|
+
}
|
|
5312
|
+
// PL-45: hot-reload/Code Mode может заново вызвать setup после того, как
|
|
5313
|
+
// хост закрыл и «завершил» ворота, не выгрузив модуль. Открываем их,
|
|
5314
|
+
// иначе все in-process запуски навсегда получают PLUGIN_SHUTTING_DOWN.
|
|
5315
|
+
shutdownGate.reset();
|
|
4550
5316
|
const runtime = await createRuntime(ctx);
|
|
4551
5317
|
const registration = await ctx.tool.transform((editor) => {
|
|
4552
5318
|
// editor.add регистрирует новые инструменты плагина с codemode: true,
|
|
@@ -4560,9 +5326,10 @@ const v2Plugin = Plugin.define({
|
|
|
4560
5326
|
editor.add({
|
|
4561
5327
|
name: spec.name,
|
|
4562
5328
|
input: spec.input,
|
|
5329
|
+
output: spec.output,
|
|
4563
5330
|
description: spec.description,
|
|
4564
5331
|
options: { codemode: true },
|
|
4565
|
-
execute
|
|
5332
|
+
execute,
|
|
4566
5333
|
});
|
|
4567
5334
|
}
|
|
4568
5335
|
});
|
|
@@ -4576,16 +5343,20 @@ const v2Plugin = Plugin.define({
|
|
|
4576
5343
|
const skill = loadSchedulerSkill();
|
|
4577
5344
|
if (skill && ctx.skill?.transform) {
|
|
4578
5345
|
skillRegistration = await ctx.skill.transform((editor) => {
|
|
5346
|
+
// QA-A2.1: V2 skill API ожидает Effect-брендированные строки
|
|
5347
|
+
// (Skill.ID / Skill.Name / AbsolutePath). Значения приходят из
|
|
5348
|
+
// собственного skill.ts, бренд живёт только на уровне типов —
|
|
5349
|
+
// приведение на границе внешнего API не меняет поведение.
|
|
4579
5350
|
editor.add({
|
|
4580
|
-
id: skill.id as
|
|
4581
|
-
name: skill.name as
|
|
5351
|
+
id: skill.id as Skill.Info["id"],
|
|
5352
|
+
name: skill.name as Skill.Info["name"],
|
|
4582
5353
|
description: skill.description,
|
|
4583
|
-
path: skill.path as
|
|
5354
|
+
path: skill.path as Skill.Info["path"],
|
|
4584
5355
|
content: skill.content,
|
|
4585
5356
|
});
|
|
4586
5357
|
});
|
|
4587
5358
|
}
|
|
4588
|
-
} catch (err
|
|
5359
|
+
} catch (err) {
|
|
4589
5360
|
console.error(
|
|
4590
5361
|
`[agent-steward] Не удалось зарегистрировать скилл "${SCHEDULER_SKILL_ID}": ${
|
|
4591
5362
|
err instanceof Error ? err.message : String(err)
|
|
@@ -4607,6 +5378,23 @@ const v2Plugin = Plugin.define({
|
|
|
4607
5378
|
},
|
|
4608
5379
|
create_task: async (input: unknown) => {
|
|
4609
5380
|
console.log("[agent-steward] create_task input:", input);
|
|
5381
|
+
// QA-P2.1: RPC обходит MCP/Zod — проверяем диапазоны явно.
|
|
5382
|
+
const rangeError = validateTaskInputRanges(input as {
|
|
5383
|
+
prompt?: string;
|
|
5384
|
+
timeoutSeconds?: number;
|
|
5385
|
+
priority?: number;
|
|
5386
|
+
retryCount?: number;
|
|
5387
|
+
retryDelay?: number;
|
|
5388
|
+
watchPath?: string;
|
|
5389
|
+
triggerType?: string;
|
|
5390
|
+
watchGlobs?: string[];
|
|
5391
|
+
watchIgnore?: string[];
|
|
5392
|
+
gitPaths?: string[];
|
|
5393
|
+
gitIgnore?: string[];
|
|
5394
|
+
});
|
|
5395
|
+
if (rangeError) {
|
|
5396
|
+
return { success: false, message: rangeError };
|
|
5397
|
+
}
|
|
4610
5398
|
const {
|
|
4611
5399
|
name,
|
|
4612
5400
|
schedule,
|
|
@@ -4640,6 +5428,7 @@ const v2Plugin = Plugin.define({
|
|
|
4640
5428
|
legacyShell,
|
|
4641
5429
|
worktree,
|
|
4642
5430
|
guards,
|
|
5431
|
+
tokenBudget,
|
|
4643
5432
|
} = input as {
|
|
4644
5433
|
name: string;
|
|
4645
5434
|
schedule?: string;
|
|
@@ -4657,7 +5446,7 @@ const v2Plugin = Plugin.define({
|
|
|
4657
5446
|
priority?: number;
|
|
4658
5447
|
beforeScript?: string;
|
|
4659
5448
|
afterScript?: string;
|
|
4660
|
-
mcpEvent?:
|
|
5449
|
+
mcpEvent?: McpEventInput;
|
|
4661
5450
|
workspaceId?: string;
|
|
4662
5451
|
allowedTools?: string[];
|
|
4663
5452
|
deniedTools?: string[];
|
|
@@ -4673,6 +5462,7 @@ const v2Plugin = Plugin.define({
|
|
|
4673
5462
|
legacyShell?: boolean;
|
|
4674
5463
|
worktree?: boolean;
|
|
4675
5464
|
guards?: TaskGuards;
|
|
5465
|
+
tokenBudget?: number;
|
|
4676
5466
|
};
|
|
4677
5467
|
let effectiveRunAt: string | undefined;
|
|
4678
5468
|
if (triggerType === "once") {
|
|
@@ -4738,6 +5528,8 @@ const v2Plugin = Plugin.define({
|
|
|
4738
5528
|
legacyShell === true,
|
|
4739
5529
|
worktree === true,
|
|
4740
5530
|
guards,
|
|
5531
|
+
// QA-P0.1 (E-2.1): создание через дашборд/RPC сохраняет tokenBudget.
|
|
5532
|
+
tokenBudget,
|
|
4741
5533
|
);
|
|
4742
5534
|
const nextRun = computeTaskNextRun({
|
|
4743
5535
|
schedule: schedule ?? "",
|
|
@@ -4753,7 +5545,7 @@ const v2Plugin = Plugin.define({
|
|
|
4753
5545
|
nextRun,
|
|
4754
5546
|
message: t("tool.task.created", { name }),
|
|
4755
5547
|
};
|
|
4756
|
-
} catch (err
|
|
5548
|
+
} catch (err) {
|
|
4757
5549
|
const message = err instanceof Error ? err.message : String(err);
|
|
4758
5550
|
return { success: false, message };
|
|
4759
5551
|
}
|
|
@@ -4772,7 +5564,7 @@ const v2Plugin = Plugin.define({
|
|
|
4772
5564
|
})
|
|
4773
5565
|
: t("tool.task.deleted", { name }),
|
|
4774
5566
|
};
|
|
4775
|
-
} catch (err
|
|
5567
|
+
} catch (err) {
|
|
4776
5568
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
4777
5569
|
}
|
|
4778
5570
|
},
|
|
@@ -4785,7 +5577,7 @@ const v2Plugin = Plugin.define({
|
|
|
4785
5577
|
message: result.message,
|
|
4786
5578
|
cancelled: result.cancelled,
|
|
4787
5579
|
};
|
|
4788
|
-
} catch (err
|
|
5580
|
+
} catch (err) {
|
|
4789
5581
|
return {
|
|
4790
5582
|
success: false,
|
|
4791
5583
|
message: err instanceof Error ? err.message : String(err),
|
|
@@ -4804,7 +5596,7 @@ const v2Plugin = Plugin.define({
|
|
|
4804
5596
|
: t("tool.matrix.orphansNone"),
|
|
4805
5597
|
removed,
|
|
4806
5598
|
};
|
|
4807
|
-
} catch (err
|
|
5599
|
+
} catch (err) {
|
|
4808
5600
|
return {
|
|
4809
5601
|
success: false,
|
|
4810
5602
|
message: err instanceof Error ? err.message : String(err),
|
|
@@ -4815,10 +5607,30 @@ const v2Plugin = Plugin.define({
|
|
|
4815
5607
|
run_task: async (input: unknown) => {
|
|
4816
5608
|
const { name } = input as { name: string };
|
|
4817
5609
|
try {
|
|
5610
|
+
const budgetGate = await checkBudgetGate();
|
|
5611
|
+
if (!budgetGate.allowed) {
|
|
5612
|
+
return {
|
|
5613
|
+
success: false,
|
|
5614
|
+
message: formatBudgetSkipMessage(budgetGate),
|
|
5615
|
+
};
|
|
5616
|
+
}
|
|
4818
5617
|
// Matrix-родитель не выполняется сам: запускаем его клоны (fan-out).
|
|
4819
5618
|
const definition = (await loadTaskDefinitions()).find(
|
|
4820
5619
|
(def) => def.name.toLowerCase() === name.trim().toLowerCase(),
|
|
4821
5620
|
);
|
|
5621
|
+
// E-2.2: тот же персональный токен-гейт, что и в runTaskEntry.
|
|
5622
|
+
if (definition?.tokenBudget) {
|
|
5623
|
+
const taskGate = checkTaskTokenBudgetGate(
|
|
5624
|
+
name,
|
|
5625
|
+
definition.tokenBudget,
|
|
5626
|
+
);
|
|
5627
|
+
if (!taskGate.allowed) {
|
|
5628
|
+
return {
|
|
5629
|
+
success: false,
|
|
5630
|
+
message: formatTaskTokenBudgetSkipMessage(taskGate),
|
|
5631
|
+
};
|
|
5632
|
+
}
|
|
5633
|
+
}
|
|
4822
5634
|
if (definition?.matrix) {
|
|
4823
5635
|
const matrixResult = await runMatrix(definition);
|
|
4824
5636
|
const total = definition.matrix.workspaceIds.length;
|
|
@@ -4865,12 +5677,24 @@ const v2Plugin = Plugin.define({
|
|
|
4865
5677
|
return { success: true, message: t("tool.task.alreadyRunning", { name }) };
|
|
4866
5678
|
}
|
|
4867
5679
|
return { success: true, message: t("tool.task.started", { name }) };
|
|
4868
|
-
} catch (err
|
|
5680
|
+
} catch (err) {
|
|
4869
5681
|
return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
|
|
4870
5682
|
}
|
|
4871
5683
|
},
|
|
4872
5684
|
run_mission: async (input: unknown) => {
|
|
4873
5685
|
try {
|
|
5686
|
+
const budgetGate = await checkBudgetGate();
|
|
5687
|
+
if (!budgetGate.allowed) {
|
|
5688
|
+
return {
|
|
5689
|
+
success: false,
|
|
5690
|
+
dryRun: false,
|
|
5691
|
+
runId: "",
|
|
5692
|
+
status: "failed",
|
|
5693
|
+
description: "",
|
|
5694
|
+
error: formatBudgetSkipMessage(budgetGate),
|
|
5695
|
+
steps: [],
|
|
5696
|
+
};
|
|
5697
|
+
}
|
|
4874
5698
|
const mission = await runMission(input as MissionSpec);
|
|
4875
5699
|
return {
|
|
4876
5700
|
success: mission.success,
|
|
@@ -4888,7 +5712,7 @@ const v2Plugin = Plugin.define({
|
|
|
4888
5712
|
...(step.error ? { error: step.error } : {}),
|
|
4889
5713
|
})),
|
|
4890
5714
|
};
|
|
4891
|
-
} catch (err
|
|
5715
|
+
} catch (err) {
|
|
4892
5716
|
return {
|
|
4893
5717
|
success: false,
|
|
4894
5718
|
dryRun: false,
|
|
@@ -4901,51 +5725,12 @@ const v2Plugin = Plugin.define({
|
|
|
4901
5725
|
}
|
|
4902
5726
|
},
|
|
4903
5727
|
emit_event: async (input: unknown) => {
|
|
4904
|
-
const { eventName, payload } = input as {
|
|
5728
|
+
const { eventName, payload, server } = input as {
|
|
4905
5729
|
eventName?: string;
|
|
4906
5730
|
payload?: unknown;
|
|
5731
|
+
server?: string;
|
|
4907
5732
|
};
|
|
4908
|
-
|
|
4909
|
-
if (!normalized) {
|
|
4910
|
-
return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
|
|
4911
|
-
}
|
|
4912
|
-
|
|
4913
|
-
// Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
|
|
4914
|
-
const definitions = await loadTaskDefinitions();
|
|
4915
|
-
const matched = definitions
|
|
4916
|
-
.filter((def) => (def.triggerType ?? "cron") === "mcp-event")
|
|
4917
|
-
.filter(
|
|
4918
|
-
(def) =>
|
|
4919
|
-
def.mcpEvent?.event?.trim().toLowerCase() === normalized.toLowerCase(),
|
|
4920
|
-
)
|
|
4921
|
-
.filter((def) => matchesEventFilter(def.mcpEvent?.filter, payload))
|
|
4922
|
-
.sort(
|
|
4923
|
-
(a, b) =>
|
|
4924
|
-
(normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5),
|
|
4925
|
-
);
|
|
4926
|
-
|
|
4927
|
-
const triggered: string[] = [];
|
|
4928
|
-
for (const def of matched) {
|
|
4929
|
-
try {
|
|
4930
|
-
await runTaskEntry(def.name);
|
|
4931
|
-
triggered.push(def.name);
|
|
4932
|
-
console.log(
|
|
4933
|
-
`[agent-steward] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`,
|
|
4934
|
-
);
|
|
4935
|
-
} catch (err: any) {
|
|
4936
|
-
console.error(
|
|
4937
|
-
`[agent-steward] Не удалось запустить "${def.name}" по событию "${normalized}": ${
|
|
4938
|
-
err instanceof Error ? err.message : String(err)
|
|
4939
|
-
}`,
|
|
4940
|
-
);
|
|
4941
|
-
}
|
|
4942
|
-
}
|
|
4943
|
-
|
|
4944
|
-
return {
|
|
4945
|
-
success: true,
|
|
4946
|
-
triggered,
|
|
4947
|
-
message: t("tool.event.processed", { event: normalized, count: triggered.length }),
|
|
4948
|
-
};
|
|
5733
|
+
return await emitEventCore(eventName, payload, server);
|
|
4949
5734
|
},
|
|
4950
5735
|
pause_task: async (input: unknown) => {
|
|
4951
5736
|
const { name, until } = input as { name: string; until?: string };
|
|
@@ -4961,8 +5746,12 @@ const v2Plugin = Plugin.define({
|
|
|
4961
5746
|
return await updateTaskFromInput(input as UpdateArgs);
|
|
4962
5747
|
},
|
|
4963
5748
|
get_task_logs: async (input: unknown) => {
|
|
4964
|
-
const { name } = input as { name
|
|
4965
|
-
const
|
|
5749
|
+
const { name, taskName } = input as { name?: string; taskName?: string };
|
|
5750
|
+
const resolved = name?.trim() || taskName?.trim();
|
|
5751
|
+
if (!resolved) {
|
|
5752
|
+
return { success: false, logs: "", error: "Укажите name или taskName задачи" };
|
|
5753
|
+
}
|
|
5754
|
+
const result = await getTaskLogs(resolved);
|
|
4966
5755
|
if (result.error) {
|
|
4967
5756
|
return { success: false, logs: "", error: result.error };
|
|
4968
5757
|
}
|
|
@@ -4983,7 +5772,10 @@ const v2Plugin = Plugin.define({
|
|
|
4983
5772
|
return { records };
|
|
4984
5773
|
},
|
|
4985
5774
|
get_metrics: async () => {
|
|
4986
|
-
|
|
5775
|
+
const metrics = await loadMetrics();
|
|
5776
|
+
const since = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
|
|
5777
|
+
const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
|
|
5778
|
+
return { ...metrics, toolBlocked };
|
|
4987
5779
|
},
|
|
4988
5780
|
cleanup_history: async (input: unknown) => {
|
|
4989
5781
|
const { retentionDays, maxRecords } = input as {
|
|
@@ -5011,7 +5803,7 @@ const v2Plugin = Plugin.define({
|
|
|
5011
5803
|
maxRecords: report.maxRecords,
|
|
5012
5804
|
vacuumed: report.vacuumed,
|
|
5013
5805
|
};
|
|
5014
|
-
} catch (err
|
|
5806
|
+
} catch (err) {
|
|
5015
5807
|
return {
|
|
5016
5808
|
success: false,
|
|
5017
5809
|
message: t("tool.history.cleanFailed", {
|
|
@@ -5034,18 +5826,25 @@ const v2Plugin = Plugin.define({
|
|
|
5034
5826
|
365,
|
|
5035
5827
|
Math.max(1, Math.floor(Number(days) || 14)),
|
|
5036
5828
|
);
|
|
5037
|
-
const records =
|
|
5829
|
+
const records = getHistoryForAnalytics(windowDays);
|
|
5038
5830
|
const definitions = await loadTaskDefinitions();
|
|
5039
5831
|
const report = buildAnalytics(records, {
|
|
5040
5832
|
days: windowDays,
|
|
5041
5833
|
topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
|
|
5042
|
-
tasks: definitions.map((definition) => ({
|
|
5834
|
+
tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
|
|
5043
5835
|
name: definition.name,
|
|
5044
5836
|
matrixParentId: definition.matrixParentId,
|
|
5837
|
+
tokenBudget: definition.tokenBudget,
|
|
5045
5838
|
})),
|
|
5046
5839
|
});
|
|
5047
|
-
|
|
5048
|
-
|
|
5840
|
+
// Экономика v2 (E-1.1): тот же учёт, что и в агент-инструменте.
|
|
5841
|
+
const settings = await loadSettings();
|
|
5842
|
+
const budgets = buildBudgetReport(records, settings.budgets, new Date());
|
|
5843
|
+
// PL-4.1: та же метрика корректности прав, что и в MCP get_analytics.
|
|
5844
|
+
const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000).toISOString();
|
|
5845
|
+
const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
|
|
5846
|
+
return { success: true, report: { ...report, budgets, toolBlocked } };
|
|
5847
|
+
} catch (err) {
|
|
5049
5848
|
return {
|
|
5050
5849
|
success: false,
|
|
5051
5850
|
report: null,
|
|
@@ -5066,19 +5865,20 @@ const v2Plugin = Plugin.define({
|
|
|
5066
5865
|
365,
|
|
5067
5866
|
Math.max(1, Math.floor(Number(days) || 14)),
|
|
5068
5867
|
);
|
|
5069
|
-
const records =
|
|
5868
|
+
const records = getHistoryForAnalytics(windowDays);
|
|
5070
5869
|
const definitions = await loadTaskDefinitions();
|
|
5071
5870
|
const report = generateSelfAnalysisReport(records, {
|
|
5072
5871
|
days: windowDays,
|
|
5073
5872
|
topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
|
|
5074
|
-
tasks: definitions.map((definition) => ({
|
|
5873
|
+
tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
|
|
5075
5874
|
name: definition.name,
|
|
5076
5875
|
matrixParentId: definition.matrixParentId,
|
|
5876
|
+
tokenBudget: definition.tokenBudget,
|
|
5077
5877
|
})),
|
|
5078
5878
|
});
|
|
5079
5879
|
|
|
5080
5880
|
// Фильтруем секции если нужно
|
|
5081
|
-
const result:
|
|
5881
|
+
const result: Partial<typeof report> = {
|
|
5082
5882
|
generatedAt: report.generatedAt,
|
|
5083
5883
|
windowDays: report.windowDays,
|
|
5084
5884
|
health: report.health,
|
|
@@ -5097,7 +5897,7 @@ const v2Plugin = Plugin.define({
|
|
|
5097
5897
|
}
|
|
5098
5898
|
|
|
5099
5899
|
return { success: true, report: result };
|
|
5100
|
-
} catch (err
|
|
5900
|
+
} catch (err) {
|
|
5101
5901
|
return {
|
|
5102
5902
|
success: false,
|
|
5103
5903
|
report: null,
|
|
@@ -5105,6 +5905,72 @@ const v2Plugin = Plugin.define({
|
|
|
5105
5905
|
};
|
|
5106
5906
|
}
|
|
5107
5907
|
},
|
|
5908
|
+
report_bug: async (input: unknown) => {
|
|
5909
|
+
const {
|
|
5910
|
+
description,
|
|
5911
|
+
taskName,
|
|
5912
|
+
includeLogs,
|
|
5913
|
+
includeAnalytics,
|
|
5914
|
+
channel,
|
|
5915
|
+
destination,
|
|
5916
|
+
contactEmail,
|
|
5917
|
+
dryRun,
|
|
5918
|
+
} = input as {
|
|
5919
|
+
description?: string;
|
|
5920
|
+
taskName?: string;
|
|
5921
|
+
includeLogs?: boolean;
|
|
5922
|
+
includeAnalytics?: boolean;
|
|
5923
|
+
channel?: "all" | "webhook" | "telegram" | "native";
|
|
5924
|
+
destination?: "author" | "local" | "both";
|
|
5925
|
+
contactEmail?: string;
|
|
5926
|
+
dryRun?: boolean;
|
|
5927
|
+
};
|
|
5928
|
+
try {
|
|
5929
|
+
if (!description || !description.trim()) {
|
|
5930
|
+
return { success: false, error: "description is required" };
|
|
5931
|
+
}
|
|
5932
|
+
const settings = await loadSettings();
|
|
5933
|
+
const logsAllowed = includeLogs ?? settings.feedback.includeLogs;
|
|
5934
|
+
const built = await buildBugReportText({
|
|
5935
|
+
description,
|
|
5936
|
+
taskName,
|
|
5937
|
+
includeLogs: logsAllowed,
|
|
5938
|
+
includeAnalytics,
|
|
5939
|
+
});
|
|
5940
|
+
const secretValues = collectSecretValues();
|
|
5941
|
+
const localText = redactText(built.text, {
|
|
5942
|
+
secrets: secretValues,
|
|
5943
|
+
redactEmails: false,
|
|
5944
|
+
});
|
|
5945
|
+
const result = await reportFeedback({
|
|
5946
|
+
settings: settings.feedback,
|
|
5947
|
+
destination: destination ?? "author",
|
|
5948
|
+
dryRun,
|
|
5949
|
+
description,
|
|
5950
|
+
taskName,
|
|
5951
|
+
contactEmail: contactEmail ?? settings.feedback.contactEmail,
|
|
5952
|
+
redactedLogs: logsAllowed ? built.logs : undefined,
|
|
5953
|
+
metrics: built.metrics,
|
|
5954
|
+
locale: settings.locale,
|
|
5955
|
+
secrets: secretValues,
|
|
5956
|
+
sendLocal: (text) => sendBugReport(text, channel),
|
|
5957
|
+
localText,
|
|
5958
|
+
});
|
|
5959
|
+
return {
|
|
5960
|
+
success: result.success,
|
|
5961
|
+
reportId: result.reportId,
|
|
5962
|
+
mode: result.mode,
|
|
5963
|
+
preview: result.preview,
|
|
5964
|
+
error: result.error,
|
|
5965
|
+
author: result.author,
|
|
5966
|
+
};
|
|
5967
|
+
} catch (err) {
|
|
5968
|
+
return {
|
|
5969
|
+
success: false,
|
|
5970
|
+
error: err instanceof Error ? err.message : String(err),
|
|
5971
|
+
};
|
|
5972
|
+
}
|
|
5973
|
+
},
|
|
5108
5974
|
get_dashboard_port: async () => {
|
|
5109
5975
|
return { port: getDashboardPort() };
|
|
5110
5976
|
},
|
|
@@ -5116,7 +5982,7 @@ const v2Plugin = Plugin.define({
|
|
|
5116
5982
|
try {
|
|
5117
5983
|
const report = await simulatePipeline(taskName);
|
|
5118
5984
|
return { ...report };
|
|
5119
|
-
} catch (err
|
|
5985
|
+
} catch (err) {
|
|
5120
5986
|
return {
|
|
5121
5987
|
success: false,
|
|
5122
5988
|
taskName,
|
|
@@ -5129,12 +5995,12 @@ const v2Plugin = Plugin.define({
|
|
|
5129
5995
|
},
|
|
5130
5996
|
dry_run_all: async () => {
|
|
5131
5997
|
const tasks = await loadTaskDefinitions();
|
|
5132
|
-
const reports:
|
|
5998
|
+
const reports: (DryRunReport & { error?: string })[] = [];
|
|
5133
5999
|
let allSuccess = true;
|
|
5134
6000
|
for (const task of tasks) {
|
|
5135
6001
|
try {
|
|
5136
6002
|
reports.push(await simulatePipeline(task.name));
|
|
5137
|
-
} catch (err
|
|
6003
|
+
} catch (err) {
|
|
5138
6004
|
allSuccess = false;
|
|
5139
6005
|
reports.push({
|
|
5140
6006
|
success: false,
|
|
@@ -5154,8 +6020,9 @@ const v2Plugin = Plugin.define({
|
|
|
5154
6020
|
source?: string;
|
|
5155
6021
|
dryRun?: boolean;
|
|
5156
6022
|
};
|
|
5157
|
-
const result = await pipelineValidateExecute({ path, source, dryRun } as PipelineValidateArgs, {}
|
|
5158
|
-
|
|
6023
|
+
const result = await pipelineValidateExecute({ path, source, dryRun } as PipelineValidateArgs, {});
|
|
6024
|
+
const parsed: unknown = JSON.parse(result.content as string);
|
|
6025
|
+
return parsed;
|
|
5159
6026
|
},
|
|
5160
6027
|
pipeline_apply: async (input: unknown) => {
|
|
5161
6028
|
const { path, source, dryRun } = input as {
|
|
@@ -5163,13 +6030,18 @@ const v2Plugin = Plugin.define({
|
|
|
5163
6030
|
source?: string;
|
|
5164
6031
|
dryRun?: boolean;
|
|
5165
6032
|
};
|
|
5166
|
-
const result = await pipelineApplyExecute({ path, source, dryRun } as PipelineApplyArgs, {}
|
|
5167
|
-
|
|
6033
|
+
const result = await pipelineApplyExecute({ path, source, dryRun } as PipelineApplyArgs, {});
|
|
6034
|
+
const parsed: unknown = JSON.parse(result.content as string);
|
|
6035
|
+
return parsed;
|
|
5168
6036
|
},
|
|
5169
6037
|
pipeline_export: async (input: unknown) => {
|
|
5170
|
-
const { pipeline } = input as { pipeline?: string };
|
|
5171
|
-
const result = await pipelineExportExecute(
|
|
5172
|
-
|
|
6038
|
+
const { pipeline, pipelineName } = input as { pipeline?: string; pipelineName?: string };
|
|
6039
|
+
const result = await pipelineExportExecute(
|
|
6040
|
+
{ pipeline: pipeline ?? pipelineName },
|
|
6041
|
+
{},
|
|
6042
|
+
);
|
|
6043
|
+
const parsed: unknown = JSON.parse(result.content as string);
|
|
6044
|
+
return parsed;
|
|
5173
6045
|
},
|
|
5174
6046
|
get_matrix_results: async (input: unknown) => {
|
|
5175
6047
|
const { parentId } = input as { parentId?: string; name?: string };
|
|
@@ -5180,7 +6052,7 @@ const v2Plugin = Plugin.define({
|
|
|
5180
6052
|
try {
|
|
5181
6053
|
const report = aggregateMatrixResults(target);
|
|
5182
6054
|
return { success: true, report };
|
|
5183
|
-
} catch (err
|
|
6055
|
+
} catch (err) {
|
|
5184
6056
|
return {
|
|
5185
6057
|
success: false,
|
|
5186
6058
|
error: err instanceof Error ? err.message : String(err),
|
|
@@ -5217,7 +6089,7 @@ const v2Plugin = Plugin.define({
|
|
|
5217
6089
|
: null,
|
|
5218
6090
|
})),
|
|
5219
6091
|
};
|
|
5220
|
-
} catch (err
|
|
6092
|
+
} catch (err) {
|
|
5221
6093
|
return {
|
|
5222
6094
|
success: false,
|
|
5223
6095
|
clones: [],
|
|
@@ -5252,7 +6124,7 @@ const v2Plugin = Plugin.define({
|
|
|
5252
6124
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
5253
6125
|
},
|
|
5254
6126
|
};
|
|
5255
|
-
} catch (err
|
|
6127
|
+
} catch (err) {
|
|
5256
6128
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
5257
6129
|
}
|
|
5258
6130
|
},
|
|
@@ -5280,7 +6152,7 @@ const v2Plugin = Plugin.define({
|
|
|
5280
6152
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
5281
6153
|
},
|
|
5282
6154
|
};
|
|
5283
|
-
} catch (err
|
|
6155
|
+
} catch (err) {
|
|
5284
6156
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
5285
6157
|
}
|
|
5286
6158
|
},
|
|
@@ -5294,7 +6166,7 @@ const v2Plugin = Plugin.define({
|
|
|
5294
6166
|
? t("tool.workspace.deleted")
|
|
5295
6167
|
: t("tool.workspace.notFound"),
|
|
5296
6168
|
};
|
|
5297
|
-
} catch (err
|
|
6169
|
+
} catch (err) {
|
|
5298
6170
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
5299
6171
|
}
|
|
5300
6172
|
},
|
|
@@ -5318,7 +6190,7 @@ const v2Plugin = Plugin.define({
|
|
|
5318
6190
|
? t("tool.profile.envVarLong", { name: current })
|
|
5319
6191
|
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
5320
6192
|
};
|
|
5321
|
-
} catch (err
|
|
6193
|
+
} catch (err) {
|
|
5322
6194
|
return {
|
|
5323
6195
|
success: false,
|
|
5324
6196
|
current: getProfileName(),
|
|
@@ -5343,7 +6215,7 @@ const v2Plugin = Plugin.define({
|
|
|
5343
6215
|
active: meta.name === getProfileName(),
|
|
5344
6216
|
},
|
|
5345
6217
|
};
|
|
5346
|
-
} catch (err
|
|
6218
|
+
} catch (err) {
|
|
5347
6219
|
return {
|
|
5348
6220
|
success: false,
|
|
5349
6221
|
error: err instanceof Error ? err.message : String(err),
|
|
@@ -5360,7 +6232,7 @@ const v2Plugin = Plugin.define({
|
|
|
5360
6232
|
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
5361
6233
|
: t("tool.profile.notFound"),
|
|
5362
6234
|
};
|
|
5363
|
-
} catch (err
|
|
6235
|
+
} catch (err) {
|
|
5364
6236
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
5365
6237
|
}
|
|
5366
6238
|
},
|
|
@@ -5368,7 +6240,7 @@ const v2Plugin = Plugin.define({
|
|
|
5368
6240
|
return await loadSettings();
|
|
5369
6241
|
},
|
|
5370
6242
|
save_settings: async (input: unknown) => {
|
|
5371
|
-
const { maxConcurrent, locale, uiLocale, winterMode, notifications, history, integrations, audit, permissions } = input as {
|
|
6243
|
+
const { maxConcurrent, locale, uiLocale, winterMode, notifications, history, integrations, audit, permissions, budgets, feedback } = input as {
|
|
5372
6244
|
maxConcurrent?: number;
|
|
5373
6245
|
locale?: LocaleMode;
|
|
5374
6246
|
uiLocale?: Locale;
|
|
@@ -5378,6 +6250,8 @@ const v2Plugin = Plugin.define({
|
|
|
5378
6250
|
integrations?: IntegrationSettings;
|
|
5379
6251
|
audit?: AuditSettings;
|
|
5380
6252
|
permissions?: PermissionSettings;
|
|
6253
|
+
budgets?: BudgetSettings;
|
|
6254
|
+
feedback?: FeedbackSettings;
|
|
5381
6255
|
};
|
|
5382
6256
|
const current = await loadSettings();
|
|
5383
6257
|
if (
|
|
@@ -5389,7 +6263,9 @@ const v2Plugin = Plugin.define({
|
|
|
5389
6263
|
history === undefined &&
|
|
5390
6264
|
integrations === undefined &&
|
|
5391
6265
|
audit === undefined &&
|
|
5392
|
-
permissions === undefined
|
|
6266
|
+
permissions === undefined &&
|
|
6267
|
+
budgets === undefined &&
|
|
6268
|
+
feedback === undefined
|
|
5393
6269
|
) {
|
|
5394
6270
|
return {
|
|
5395
6271
|
success: false,
|
|
@@ -5402,6 +6278,8 @@ const v2Plugin = Plugin.define({
|
|
|
5402
6278
|
integrations: current.integrations,
|
|
5403
6279
|
audit: current.audit,
|
|
5404
6280
|
permissions: current.permissions,
|
|
6281
|
+
budgets: current.budgets,
|
|
6282
|
+
feedback: current.feedback,
|
|
5405
6283
|
};
|
|
5406
6284
|
}
|
|
5407
6285
|
const settings = await saveSettings({
|
|
@@ -5414,6 +6292,8 @@ const v2Plugin = Plugin.define({
|
|
|
5414
6292
|
integrations,
|
|
5415
6293
|
audit,
|
|
5416
6294
|
permissions,
|
|
6295
|
+
budgets,
|
|
6296
|
+
feedback,
|
|
5417
6297
|
});
|
|
5418
6298
|
// Локаль процесса меняется сразу — перезапуск не нужен.
|
|
5419
6299
|
setLocale(resolveLocale(settings.locale, settings.uiLocale));
|
|
@@ -5428,6 +6308,8 @@ const v2Plugin = Plugin.define({
|
|
|
5428
6308
|
integrations: settings.integrations,
|
|
5429
6309
|
audit: settings.audit,
|
|
5430
6310
|
permissions: settings.permissions,
|
|
6311
|
+
budgets: settings.budgets,
|
|
6312
|
+
feedback: settings.feedback,
|
|
5431
6313
|
};
|
|
5432
6314
|
},
|
|
5433
6315
|
test_notification: async () => {
|
|
@@ -5521,7 +6403,7 @@ const v2Plugin = Plugin.define({
|
|
|
5521
6403
|
message: t("tool.secret.saved", { name: secret.name }),
|
|
5522
6404
|
secret,
|
|
5523
6405
|
};
|
|
5524
|
-
} catch (err
|
|
6406
|
+
} catch (err) {
|
|
5525
6407
|
return {
|
|
5526
6408
|
success: false,
|
|
5527
6409
|
message: err instanceof Error ? err.message : String(err),
|
|
@@ -5542,7 +6424,7 @@ const v2Plugin = Plugin.define({
|
|
|
5542
6424
|
? t("tool.secret.deleted", { name })
|
|
5543
6425
|
: t("tool.secret.notFound", { name }),
|
|
5544
6426
|
};
|
|
5545
|
-
} catch (err
|
|
6427
|
+
} catch (err) {
|
|
5546
6428
|
return {
|
|
5547
6429
|
success: false,
|
|
5548
6430
|
message: err instanceof Error ? err.message : String(err),
|
|
@@ -5558,6 +6440,10 @@ const v2Plugin = Plugin.define({
|
|
|
5558
6440
|
until?: string;
|
|
5559
6441
|
limit?: number;
|
|
5560
6442
|
};
|
|
6443
|
+
const dateError =
|
|
6444
|
+
auditDateFilterError(source.since, "since") ??
|
|
6445
|
+
auditDateFilterError(source.until, "until");
|
|
6446
|
+
if (dateError) return { success: false, message: dateError };
|
|
5561
6447
|
const result = readAuditLog({
|
|
5562
6448
|
action: source.action,
|
|
5563
6449
|
target: source.target,
|
|
@@ -5608,7 +6494,7 @@ const v2Plugin = Plugin.define({
|
|
|
5608
6494
|
get_templates: async () => {
|
|
5609
6495
|
try {
|
|
5610
6496
|
return { templates: await loadTemplates() };
|
|
5611
|
-
} catch (err
|
|
6497
|
+
} catch (err) {
|
|
5612
6498
|
console.error("[agent-steward] get_templates error:", err);
|
|
5613
6499
|
return { templates: [] };
|
|
5614
6500
|
}
|
|
@@ -5639,7 +6525,7 @@ const v2Plugin = Plugin.define({
|
|
|
5639
6525
|
: undefined,
|
|
5640
6526
|
});
|
|
5641
6527
|
return { success: true, template };
|
|
5642
|
-
} catch (err
|
|
6528
|
+
} catch (err) {
|
|
5643
6529
|
return {
|
|
5644
6530
|
success: false,
|
|
5645
6531
|
error: err instanceof Error ? err.message : String(err),
|
|
@@ -5652,9 +6538,15 @@ const v2Plugin = Plugin.define({
|
|
|
5652
6538
|
return { success: false, error: t("tool.template.needId") };
|
|
5653
6539
|
}
|
|
5654
6540
|
try {
|
|
6541
|
+
// QA-P3.3: принимаем и id, и имя шаблона; отсутствие — явная ошибка.
|
|
6542
|
+
const templates = await loadTemplates();
|
|
6543
|
+
const existed = templates.some((template) => template.id === id || template.name === id);
|
|
6544
|
+
if (!existed) {
|
|
6545
|
+
return { success: false, error: t("tool.template.notFound", { id }) };
|
|
6546
|
+
}
|
|
5655
6547
|
await deleteTemplate(id);
|
|
5656
6548
|
return { success: true };
|
|
5657
|
-
} catch (err
|
|
6549
|
+
} catch (err) {
|
|
5658
6550
|
return {
|
|
5659
6551
|
success: false,
|
|
5660
6552
|
error: err instanceof Error ? err.message : String(err),
|
|
@@ -5670,7 +6562,7 @@ const v2Plugin = Plugin.define({
|
|
|
5670
6562
|
}));
|
|
5671
6563
|
const { data, count } = await buildExportJson(exportTasks);
|
|
5672
6564
|
return { success: true, data, count };
|
|
5673
|
-
} catch (err
|
|
6565
|
+
} catch (err) {
|
|
5674
6566
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
5675
6567
|
}
|
|
5676
6568
|
},
|
|
@@ -5742,10 +6634,12 @@ const v2Plugin = Plugin.define({
|
|
|
5742
6634
|
def.legacyShell === true,
|
|
5743
6635
|
def.worktree === true,
|
|
5744
6636
|
def.guards,
|
|
6637
|
+
// QA-P0.1 (E-2.1): импорт через RPC сохраняет tokenBudget.
|
|
6638
|
+
def.tokenBudget,
|
|
5745
6639
|
);
|
|
5746
6640
|
await saveTaskDefinition(def);
|
|
5747
6641
|
imported.push(def.name);
|
|
5748
|
-
} catch (err
|
|
6642
|
+
} catch (err) {
|
|
5749
6643
|
errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
5750
6644
|
}
|
|
5751
6645
|
}
|
|
@@ -5755,7 +6649,7 @@ const v2Plugin = Plugin.define({
|
|
|
5755
6649
|
imported: imported.length,
|
|
5756
6650
|
errors: errors.length ? errors : undefined,
|
|
5757
6651
|
};
|
|
5758
|
-
} catch (err
|
|
6652
|
+
} catch (err) {
|
|
5759
6653
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
5760
6654
|
}
|
|
5761
6655
|
},
|
|
@@ -5768,7 +6662,7 @@ const v2Plugin = Plugin.define({
|
|
|
5768
6662
|
|
|
5769
6663
|
// Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
|
|
5770
6664
|
// чьи родители были удалены в прошлых сессиях.
|
|
5771
|
-
void cleanupOrphanedMatrixTasks().catch((err
|
|
6665
|
+
void cleanupOrphanedMatrixTasks().catch((err) => {
|
|
5772
6666
|
console.log(
|
|
5773
6667
|
`[matrix] Не удалось очистить осиротевшие задачи: ${
|
|
5774
6668
|
err instanceof Error ? err.message : String(err)
|
|
@@ -5790,36 +6684,49 @@ const v2Plugin = Plugin.define({
|
|
|
5790
6684
|
* Приводит результат V2-обработчика (`Tool.Result`) к формату V1 (`ToolResult`).
|
|
5791
6685
|
* V1 ждёт строку или `{ output, metadata }`; V2 отдаёт `{ content }`.
|
|
5792
6686
|
*/
|
|
5793
|
-
|
|
6687
|
+
type V1ToolResult = string | { output: string; metadata?: Tool.Result["metadata"] };
|
|
6688
|
+
|
|
6689
|
+
/** Сужает элемент content до текстового блока (остальные типы V2 не нас интересуют). */
|
|
6690
|
+
function isTextContent(part: unknown): part is { type: "text"; text: string } {
|
|
6691
|
+
return (
|
|
6692
|
+
typeof part === "object" &&
|
|
6693
|
+
part !== null &&
|
|
6694
|
+
"type" in part &&
|
|
6695
|
+
part.type === "text" &&
|
|
6696
|
+
"text" in part &&
|
|
6697
|
+
typeof part.text === "string"
|
|
6698
|
+
);
|
|
6699
|
+
}
|
|
6700
|
+
|
|
6701
|
+
export function toV1ToolResult(result: Tool.Result | string): V1ToolResult {
|
|
5794
6702
|
if (typeof result === "string") return result;
|
|
5795
|
-
|
|
5796
|
-
|
|
5797
|
-
|
|
5798
|
-
|
|
5799
|
-
|
|
5800
|
-
return { output: text, metadata: result.metadata };
|
|
6703
|
+
const metadata = result.metadata;
|
|
6704
|
+
const content = result.content;
|
|
6705
|
+
if (Array.isArray(content)) {
|
|
6706
|
+
const text = content.filter(isTextContent).map((part) => part.text).join("\n");
|
|
6707
|
+
return { output: text, metadata };
|
|
5801
6708
|
}
|
|
5802
|
-
if (typeof
|
|
5803
|
-
return { output:
|
|
6709
|
+
if (typeof content === "string") {
|
|
6710
|
+
return { output: content, metadata };
|
|
5804
6711
|
}
|
|
5805
|
-
if (typeof result
|
|
5806
|
-
return { output: result.output, metadata
|
|
6712
|
+
if (typeof result.output === "string") {
|
|
6713
|
+
return { output: result.output, metadata };
|
|
5807
6714
|
}
|
|
5808
|
-
return { output: JSON.stringify(result), metadata
|
|
6715
|
+
return { output: JSON.stringify(result), metadata };
|
|
5809
6716
|
}
|
|
5810
6717
|
|
|
5811
6718
|
/**
|
|
5812
6719
|
* V1 `tool()` принимает `z.ZodRawShape`, а спецификации хранят `z.object(...)`.
|
|
5813
6720
|
* Возвращаем именно shape, чтобы V1 не получил готовый объект схемы.
|
|
5814
6721
|
*/
|
|
5815
|
-
export function toV1ToolArgs(spec: ToolSpec):
|
|
6722
|
+
export function toV1ToolArgs(spec: ToolSpec): z.ZodRawShape {
|
|
5816
6723
|
const shape = (spec.input as { shape?: unknown } | undefined)?.shape;
|
|
5817
6724
|
if (!shape || typeof shape !== "object") {
|
|
5818
6725
|
throw new Error(
|
|
5819
6726
|
`V1-адаптер: схема инструмента "${spec.name}" должна быть z.object(...)`,
|
|
5820
6727
|
);
|
|
5821
6728
|
}
|
|
5822
|
-
return shape as
|
|
6729
|
+
return shape as z.ZodRawShape;
|
|
5823
6730
|
}
|
|
5824
6731
|
|
|
5825
6732
|
/**
|
|
@@ -5827,17 +6734,28 @@ export function toV1ToolArgs(spec: ToolSpec): Record<string, any> {
|
|
|
5827
6734
|
* V2, плюс тот же аудит. Отличие одно — у V1 `tool()` нет `codemode`, поэтому
|
|
5828
6735
|
* флаг не передаётся (см. docs/COMPATIBILITY.md).
|
|
5829
6736
|
*/
|
|
5830
|
-
|
|
5831
|
-
|
|
6737
|
+
/**
|
|
6738
|
+
* Локальное описание V1-реестра. V1-плагин тянет свою копию zod (4.1.8),
|
|
6739
|
+
* поэтому его `ToolDefinition` структурно несовместим с нашим zod (4.6.7).
|
|
6740
|
+
* Приведение типов делается один раз на границе `createV1Hooks`.
|
|
6741
|
+
*/
|
|
6742
|
+
interface V1ToolDefinition {
|
|
6743
|
+
description: string;
|
|
6744
|
+
args: z.ZodRawShape;
|
|
6745
|
+
execute(args: unknown, context: unknown): Promise<V1ToolResult>;
|
|
6746
|
+
}
|
|
6747
|
+
type V1ToolRegistry = Record<string, V1ToolDefinition>;
|
|
6748
|
+
|
|
6749
|
+
export function createV1Tools(runtime: SchedulerRuntime): V1ToolRegistry {
|
|
6750
|
+
const tools: V1ToolRegistry = {};
|
|
5832
6751
|
for (const spec of createToolSpecs(runtime)) {
|
|
5833
6752
|
const execute = spec.audit
|
|
5834
6753
|
? withAudit(spec.name, spec.audit, spec.execute)
|
|
5835
6754
|
: spec.execute;
|
|
5836
6755
|
tools[spec.name] = v1Tool({
|
|
5837
6756
|
description: spec.description,
|
|
5838
|
-
args: toV1ToolArgs(spec)
|
|
5839
|
-
execute:
|
|
5840
|
-
toV1ToolResult(await execute(args, context))) as any,
|
|
6757
|
+
args: toV1ToolArgs(spec),
|
|
6758
|
+
execute: async (args, context) => toV1ToolResult(await execute(args, context)),
|
|
5841
6759
|
});
|
|
5842
6760
|
}
|
|
5843
6761
|
return tools;
|
|
@@ -5854,13 +6772,21 @@ export async function createV1Hooks(
|
|
|
5854
6772
|
input: Pick<V1PluginInput, "directory"> = { directory: process.cwd() },
|
|
5855
6773
|
options: { startDashboard?: boolean } = {},
|
|
5856
6774
|
): Promise<V1Hooks> {
|
|
6775
|
+
if (isChildRunMode()) {
|
|
6776
|
+
console.log(`[qv8] ${CHILD_RUN_ENV}: дочерний прогон, пропускаю регистрацию плагина`);
|
|
6777
|
+
return { tool: {}, dispose: async () => undefined };
|
|
6778
|
+
}
|
|
6779
|
+
// PL-45: см. V2 setup — повторная регистрация должна открывать ворота.
|
|
6780
|
+
shutdownGate.reset();
|
|
5857
6781
|
const runtime = await createRuntime({ location: { directory: input.directory } });
|
|
5858
6782
|
const tools = createV1Tools(runtime);
|
|
5859
6783
|
if (options.startDashboard !== false) {
|
|
5860
6784
|
await startSchedulerDashboard();
|
|
5861
6785
|
}
|
|
5862
6786
|
return {
|
|
5863
|
-
|
|
6787
|
+
// QA-A2.1: граница внешнего V1 API — у плагина отдельная копия zod,
|
|
6788
|
+
// типы несовместимы структурно. Значения и поведение не меняются.
|
|
6789
|
+
tool: tools as unknown as V1Hooks["tool"],
|
|
5864
6790
|
dispose: createShutdownHandler(runtime),
|
|
5865
6791
|
};
|
|
5866
6792
|
}
|
|
@@ -5969,6 +6895,37 @@ export interface TriggerExtras {
|
|
|
5969
6895
|
gitPollSeconds?: number;
|
|
5970
6896
|
}
|
|
5971
6897
|
|
|
6898
|
+
/**
|
|
6899
|
+
* PL-42: вход нормализации mcpEvent. `eventName` — алиас `event`, который
|
|
6900
|
+
* присылает `emit_event`; оба поля необязательны, но хотя бы одно нужно
|
|
6901
|
+
* для triggerType=mcp-event (проверяется после нормализации).
|
|
6902
|
+
*/
|
|
6903
|
+
interface McpEventInput {
|
|
6904
|
+
server?: string;
|
|
6905
|
+
/** Каноническое имя события. Приоритетнее алиаса. */
|
|
6906
|
+
event?: string;
|
|
6907
|
+
/** Алиас emit_event; используется, только если event пуст. */
|
|
6908
|
+
eventName?: string;
|
|
6909
|
+
filter?: string;
|
|
6910
|
+
}
|
|
6911
|
+
|
|
6912
|
+
/**
|
|
6913
|
+
* PL-42: приводит mcpEvent к каноническому виду `{ server, event, filter? }`.
|
|
6914
|
+
* `event` имеет приоритет: если заданы оба поля и они различаются, alias
|
|
6915
|
+
* `eventName` игнорируется — так поведение старых задач не меняется.
|
|
6916
|
+
*/
|
|
6917
|
+
export function normalizeMcpEventTrigger(
|
|
6918
|
+
mcpEvent?: McpEventInput,
|
|
6919
|
+
): McpEventTrigger | undefined {
|
|
6920
|
+
const rawEvent = mcpEvent?.event?.trim() || mcpEvent?.eventName?.trim();
|
|
6921
|
+
if (!rawEvent) return undefined;
|
|
6922
|
+
return {
|
|
6923
|
+
server: mcpEvent?.server?.trim() || "",
|
|
6924
|
+
event: rawEvent,
|
|
6925
|
+
...(mcpEvent?.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
|
|
6926
|
+
};
|
|
6927
|
+
}
|
|
6928
|
+
|
|
5972
6929
|
export async function schedulerCreateTask(
|
|
5973
6930
|
name: string,
|
|
5974
6931
|
schedule: string,
|
|
@@ -5987,7 +6944,7 @@ export async function schedulerCreateTask(
|
|
|
5987
6944
|
priority?: number,
|
|
5988
6945
|
beforeScript?: string,
|
|
5989
6946
|
afterScript?: string,
|
|
5990
|
-
mcpEvent?:
|
|
6947
|
+
mcpEvent?: McpEventInput,
|
|
5991
6948
|
workspaceId?: string,
|
|
5992
6949
|
allowedTools?: string[],
|
|
5993
6950
|
deniedTools?: string[],
|
|
@@ -6029,6 +6986,8 @@ export async function schedulerCreateTask(
|
|
|
6029
6986
|
worktree?: boolean,
|
|
6030
6987
|
/** W-3: guard-условия перед запуском opencode. */
|
|
6031
6988
|
guards?: TaskGuards,
|
|
6989
|
+
/** Economics v2 (E-2): per-run token budget. 0/omitted = no limit (fail-open). */
|
|
6990
|
+
tokenBudget?: number,
|
|
6032
6991
|
): Promise<void> {
|
|
6033
6992
|
// Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
|
|
6034
6993
|
// в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
|
|
@@ -6101,6 +7060,11 @@ export async function schedulerCreateTask(
|
|
|
6101
7060
|
const guardsResult = normalizeTaskGuards(guards);
|
|
6102
7061
|
if (!guardsResult.ok) throw new Error(guardsResult.error);
|
|
6103
7062
|
const normalizedGuards = guardsResult.guards;
|
|
7063
|
+
// Economics v2 (E-2): нормализация бюджета токенов. 0/отрицание/NaN = без лимита.
|
|
7064
|
+
const normalizedTokenBudget =
|
|
7065
|
+
Number.isFinite(tokenBudget) && (tokenBudget ?? 0) > 0
|
|
7066
|
+
? Math.floor(tokenBudget!)
|
|
7067
|
+
: undefined;
|
|
6104
7068
|
// Спринт 27: дни недели, политика окна и glob/git-фильтры.
|
|
6105
7069
|
const normalizeGlobList = (raw?: string[]): string[] | undefined => {
|
|
6106
7070
|
if (!Array.isArray(raw)) return undefined;
|
|
@@ -6130,14 +7094,9 @@ export async function schedulerCreateTask(
|
|
|
6130
7094
|
triggerExtras.gitPollSeconds >= 5
|
|
6131
7095
|
? Math.floor(triggerExtras.gitPollSeconds)
|
|
6132
7096
|
: undefined;
|
|
6133
|
-
|
|
6134
|
-
|
|
6135
|
-
|
|
6136
|
-
server: mcpEvent.server?.trim() || "",
|
|
6137
|
-
event: mcpEvent.event.trim(),
|
|
6138
|
-
...(mcpEvent.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
|
|
6139
|
-
}
|
|
6140
|
-
: undefined;
|
|
7097
|
+
// PL-42: mcpEvent принимает event и его алиас eventName (emit_event).
|
|
7098
|
+
// event приоритетнее: если оба заданы и различаются, побеждает event.
|
|
7099
|
+
const normalizedMcpEvent = normalizeMcpEventTrigger(mcpEvent);
|
|
6141
7100
|
let effectiveTriggerType = triggerType ?? "cron";
|
|
6142
7101
|
// One-shot: нормализуем время до создания файлов и задачи в ОС.
|
|
6143
7102
|
// Для остальных триггеров runAt не имеет смысла и отбрасывается.
|
|
@@ -6297,8 +7256,8 @@ export async function schedulerCreateTask(
|
|
|
6297
7256
|
// Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
|
|
6298
7257
|
// имена месяцев/дней, @every, L и FRI#3.
|
|
6299
7258
|
parseCron(schedule);
|
|
6300
|
-
} catch (err
|
|
6301
|
-
throw new Error(err.message
|
|
7259
|
+
} catch (err) {
|
|
7260
|
+
throw new Error(err instanceof Error ? err.message : String(err));
|
|
6302
7261
|
}
|
|
6303
7262
|
if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
|
|
6304
7263
|
throw new Error(
|
|
@@ -6410,18 +7369,18 @@ export async function schedulerCreateTask(
|
|
|
6410
7369
|
if (effectiveWatchPath) {
|
|
6411
7370
|
try {
|
|
6412
7371
|
effectiveWatchPath = normalizeWatchPath(effectiveWatchPath, effectiveWorkingDirectory);
|
|
6413
|
-
} catch (err
|
|
7372
|
+
} catch (err) {
|
|
6414
7373
|
throw new Error(
|
|
6415
|
-
t("tool.error.taskReason", { name, error: err.message
|
|
7374
|
+
t("tool.error.taskReason", { name, error: err instanceof Error ? err.message : String(err) }),
|
|
6416
7375
|
);
|
|
6417
7376
|
}
|
|
6418
7377
|
}
|
|
6419
7378
|
try {
|
|
6420
7379
|
validateWatchGlobs(normalizedWatchGlobs);
|
|
6421
7380
|
validateWatchGlobs(normalizedWatchIgnore);
|
|
6422
|
-
} catch (err
|
|
7381
|
+
} catch (err) {
|
|
6423
7382
|
throw new Error(
|
|
6424
|
-
t("tool.error.taskReason", { name, error: err.message
|
|
7383
|
+
t("tool.error.taskReason", { name, error: err instanceof Error ? err.message : String(err) }),
|
|
6425
7384
|
);
|
|
6426
7385
|
}
|
|
6427
7386
|
|
|
@@ -6447,11 +7406,16 @@ export async function schedulerCreateTask(
|
|
|
6447
7406
|
try {
|
|
6448
7407
|
promptFile = await writePromptFile(sanitized, prompt);
|
|
6449
7408
|
await fs.mkdir(LOG_DIR, { recursive: true });
|
|
6450
|
-
|
|
6451
|
-
|
|
7409
|
+
// Не обнуляем лог: при падении до запуска обёртки (или при отказе модели)
|
|
7410
|
+
// предыдущий диагностический вывод оставался бы единственным, а новый
|
|
7411
|
+
// прогон выглядел бы как «лог пуст». Дописываем маркер ПОДГОТОВКИ —
|
|
7412
|
+
// задача создана, но ещё не запускалась (не путать с реальным Run started,
|
|
7413
|
+
// который пишется обёрткой только при фактическом запуске; QA #8).
|
|
7414
|
+
await fs.appendFile(logFile, formatLogRunMarker("prepare", name), "utf8");
|
|
7415
|
+
} catch (err) {
|
|
6452
7416
|
throw new Error(
|
|
6453
7417
|
t("tool.error.prepareFiles", {
|
|
6454
|
-
error: err.message
|
|
7418
|
+
error: err instanceof Error ? err.message : String(err),
|
|
6455
7419
|
}),
|
|
6456
7420
|
);
|
|
6457
7421
|
}
|
|
@@ -6495,6 +7459,7 @@ export async function schedulerCreateTask(
|
|
|
6495
7459
|
worktreeHelperPath,
|
|
6496
7460
|
normalizedGuards,
|
|
6497
7461
|
guardHelperPath,
|
|
7462
|
+
gateAllowPathsFromAfterScript(normalizedAfter),
|
|
6498
7463
|
);
|
|
6499
7464
|
} else {
|
|
6500
7465
|
wrapperPath = await writeBashWrapper({
|
|
@@ -6524,15 +7489,16 @@ export async function schedulerCreateTask(
|
|
|
6524
7489
|
worktreeHelper: worktreeHelperPath,
|
|
6525
7490
|
guards: normalizedGuards,
|
|
6526
7491
|
guardHelper: guardHelperPath,
|
|
7492
|
+
gateAllowPaths: gateAllowPathsFromAfterScript(normalizedAfter),
|
|
6527
7493
|
...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
|
|
6528
7494
|
? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized, getProfileName()) }
|
|
6529
7495
|
: {}),
|
|
6530
7496
|
});
|
|
6531
7497
|
}
|
|
6532
|
-
} catch (err
|
|
7498
|
+
} catch (err) {
|
|
6533
7499
|
throw new Error(
|
|
6534
7500
|
t("tool.error.wrapper", {
|
|
6535
|
-
error: err.message
|
|
7501
|
+
error: err instanceof Error ? err.message : String(err),
|
|
6536
7502
|
}),
|
|
6537
7503
|
);
|
|
6538
7504
|
}
|
|
@@ -6566,7 +7532,7 @@ export async function schedulerCreateTask(
|
|
|
6566
7532
|
notAfter: normalizedNotAfter,
|
|
6567
7533
|
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
6568
7534
|
});
|
|
6569
|
-
} catch (err
|
|
7535
|
+
} catch (err) {
|
|
6570
7536
|
await rollbackArtifacts();
|
|
6571
7537
|
throw new Error(err instanceof Error ? err.message : String(err));
|
|
6572
7538
|
}
|
|
@@ -6672,6 +7638,7 @@ export async function schedulerCreateTask(
|
|
|
6672
7638
|
legacyShell: legacyShell === true ? true : undefined,
|
|
6673
7639
|
worktree: normalizedWorktree,
|
|
6674
7640
|
guards: normalizedGuards,
|
|
7641
|
+
tokenBudget: normalizedTokenBudget,
|
|
6675
7642
|
matrix: normalizedMatrix,
|
|
6676
7643
|
isMatrixParent: normalizedMatrix ? true : undefined,
|
|
6677
7644
|
matrixParentId,
|
|
@@ -6756,6 +7723,8 @@ export async function schedulerCreateTask(
|
|
|
6756
7723
|
clone.legacyShell,
|
|
6757
7724
|
clone.worktree,
|
|
6758
7725
|
clone.guards,
|
|
7726
|
+
// QA-P0.1 (E-2.1): клон матрицы наследует tokenBudget родителя.
|
|
7727
|
+
clone.tokenBudget,
|
|
6759
7728
|
);
|
|
6760
7729
|
};
|
|
6761
7730
|
|
|
@@ -6842,7 +7811,7 @@ export async function schedulerCreateTask(
|
|
|
6842
7811
|
try {
|
|
6843
7812
|
await createClone(clone);
|
|
6844
7813
|
createdInRun.push(clone.name);
|
|
6845
|
-
} catch (err
|
|
7814
|
+
} catch (err) {
|
|
6846
7815
|
const workspaceLabel = clone.workspaceId
|
|
6847
7816
|
? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
|
|
6848
7817
|
: "без workspace";
|
|
@@ -6856,7 +7825,7 @@ export async function schedulerCreateTask(
|
|
|
6856
7825
|
}
|
|
6857
7826
|
}
|
|
6858
7827
|
await syncAggregator();
|
|
6859
|
-
} catch (err
|
|
7828
|
+
} catch (err) {
|
|
6860
7829
|
for (const child of [...createdInRun].reverse()) {
|
|
6861
7830
|
await removeChild(child);
|
|
6862
7831
|
}
|
|
@@ -6898,7 +7867,7 @@ export async function schedulerCreateTask(
|
|
|
6898
7867
|
for (const target of pauseTargets) {
|
|
6899
7868
|
try {
|
|
6900
7869
|
await scheduler.pauseTask(target);
|
|
6901
|
-
} catch (err
|
|
7870
|
+
} catch (err) {
|
|
6902
7871
|
console.warn(
|
|
6903
7872
|
`[agent-steward] Задача "${target}": пауза не восстановлена после пересоздания: ${
|
|
6904
7873
|
err instanceof Error ? err.message : String(err)
|
|
@@ -6971,6 +7940,8 @@ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<v
|
|
|
6971
7940
|
definition.legacyShell,
|
|
6972
7941
|
definition.worktree,
|
|
6973
7942
|
definition.guards,
|
|
7943
|
+
// QA-P0.1 (E-2.1): откат update не теряет tokenBudget.
|
|
7944
|
+
definition.tokenBudget,
|
|
6974
7945
|
);
|
|
6975
7946
|
}
|
|
6976
7947
|
|
|
@@ -6978,22 +7949,111 @@ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<v
|
|
|
6978
7949
|
* Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
|
|
6979
7950
|
* на клоны, а не выполняет свой промпт.
|
|
6980
7951
|
*/
|
|
7952
|
+
/** E-1.2: общий гейт бюджета для всех входов запуска задач. */
|
|
7953
|
+
async function checkBudgetGate(now: Date = new Date()): Promise<BudgetGateDecision> {
|
|
7954
|
+
const settings = await loadSettings();
|
|
7955
|
+
// Неделя — widest период бюджетов. Выбираем записи по моменту завершения
|
|
7956
|
+
// (см. getHistoryForBudget), чтобы не зависеть от окна в 20000 запусков.
|
|
7957
|
+
const records = getHistoryForBudget(startOfUtcWeek(now).toISOString());
|
|
7958
|
+
const decision = evaluateBudgetGate(records, settings.budgets, now);
|
|
7959
|
+
if (!decision.allowed) {
|
|
7960
|
+
// E-1.3: алерт не должен задерживать или ломать запуск.
|
|
7961
|
+
void notifyBudgetExceeded(decision).catch((err: unknown) => {
|
|
7962
|
+
console.error(
|
|
7963
|
+
`[agent-steward] Ошибка бюджетного алерта: ${
|
|
7964
|
+
err instanceof Error ? err.message : String(err)
|
|
7965
|
+
}`,
|
|
7966
|
+
);
|
|
7967
|
+
});
|
|
7968
|
+
}
|
|
7969
|
+
return decision;
|
|
7970
|
+
}
|
|
7971
|
+
|
|
7972
|
+
/**
|
|
7973
|
+
* E-2.2: гейт персонального токен-бюджета задачи.
|
|
7974
|
+
*
|
|
7975
|
+
* Зеркалит общий бюджетный гейт E-1.2, но читает лимит из определения задачи
|
|
7976
|
+
* и фильтрует историю по её имени. Fail-open: без лимита запуск не блокируется.
|
|
7977
|
+
*/
|
|
7978
|
+
function checkTaskTokenBudgetGate(
|
|
7979
|
+
taskName: string,
|
|
7980
|
+
tokenBudget: number | undefined,
|
|
7981
|
+
now: Date = new Date(),
|
|
7982
|
+
): TaskTokenBudgetDecision {
|
|
7983
|
+
const records = getHistoryForBudget(startOfUtcWeek(now).toISOString());
|
|
7984
|
+
return evaluateTaskTokenBudgetGate(records, taskName, tokenBudget, now);
|
|
7985
|
+
}
|
|
7986
|
+
|
|
7987
|
+
/**
|
|
7988
|
+
* PL-1.1: структурированная ошибка отказа запуска во время выгрузки плагина.
|
|
7989
|
+
* Текст `message` сохранён дословно для совместимости с существующими
|
|
7990
|
+
* вызывающими; `code` и `hint` дают кнопке повтора/оператору понятный путь.
|
|
7991
|
+
*/
|
|
7992
|
+
export class PluginShutdownError extends Error {
|
|
7993
|
+
readonly code = "PLUGIN_SHUTTING_DOWN";
|
|
7994
|
+
readonly hint: string;
|
|
7995
|
+
/** PL-10/QV-2: наблюдаемое состояние ворот в момент отказа. */
|
|
7996
|
+
readonly state: ShutdownGateState;
|
|
7997
|
+
/** PL-45: повтор возможен после перерегистрации плагина. */
|
|
7998
|
+
readonly retryable = true;
|
|
7999
|
+
|
|
8000
|
+
constructor(message: string, hint: string, state: ShutdownGateState) {
|
|
8001
|
+
super(message);
|
|
8002
|
+
this.name = "PluginShutdownError";
|
|
8003
|
+
this.hint = hint;
|
|
8004
|
+
this.state = state;
|
|
8005
|
+
}
|
|
8006
|
+
}
|
|
8007
|
+
|
|
6981
8008
|
async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }> {
|
|
6982
8009
|
if (shutdownGate.isShuttingDown()) {
|
|
6983
|
-
throw new
|
|
8010
|
+
throw new PluginShutdownError(
|
|
6984
8011
|
"Плагин выгружается: новые запуски не принимаются. Повторите после перезапуска.",
|
|
8012
|
+
"Повторите запуск после перезапуска плагина. Для once/cron-задач используйте force-маркер locks/<slug>.lock.force + Start-ScheduledTask (schtasks /run) либо отложенный запуск после перезапуска.",
|
|
8013
|
+
shutdownGate.state(),
|
|
6985
8014
|
);
|
|
6986
8015
|
}
|
|
6987
8016
|
|
|
8017
|
+
const budgetGate = await checkBudgetGate();
|
|
8018
|
+
if (!budgetGate.allowed) {
|
|
8019
|
+
throw new Error(formatBudgetSkipMessage(budgetGate));
|
|
8020
|
+
}
|
|
8021
|
+
|
|
6988
8022
|
const run = (async () => {
|
|
8023
|
+
const trimmed = name.trim();
|
|
6989
8024
|
const definition = (await loadTaskDefinitions()).find(
|
|
6990
|
-
(def) => def.name.toLowerCase() ===
|
|
8025
|
+
(def) => def.name.toLowerCase() === trimmed.toLowerCase(),
|
|
6991
8026
|
);
|
|
8027
|
+
|
|
8028
|
+
// E-2.2: остановка задачи при превышении её персонального токен-бюджета.
|
|
8029
|
+
// Пропускаем новые запуски, если завершённый прогон за текущий UTC-день
|
|
8030
|
+
// или неделю уже превысил tokenBudget (fail-open, как и E-1.2).
|
|
8031
|
+
if (definition?.tokenBudget) {
|
|
8032
|
+
const taskGate = checkTaskTokenBudgetGate(trimmed, definition.tokenBudget);
|
|
8033
|
+
if (!taskGate.allowed) {
|
|
8034
|
+
throw new Error(formatTaskTokenBudgetSkipMessage(taskGate));
|
|
8035
|
+
}
|
|
8036
|
+
}
|
|
8037
|
+
|
|
6992
8038
|
if (definition?.matrix) {
|
|
6993
8039
|
await runMatrix(definition);
|
|
6994
8040
|
return { alreadyRunning: false };
|
|
6995
8041
|
}
|
|
6996
8042
|
|
|
8043
|
+
// QA-P3.6: если задачи нет ни в определениях, ни в планировщике ОС,
|
|
8044
|
+
// не дёргаем schtasks /run — он возвращает сырую ошибку ОС. Возвращаем
|
|
8045
|
+
// структурированное «задача не найдена», как и остальные инструменты.
|
|
8046
|
+
// Legacy-задачи, живущие только в ОС (без definition), остаются запускаемыми.
|
|
8047
|
+
if (!definition) {
|
|
8048
|
+
const osTasks = await scheduler.listTasks().catch(() => []);
|
|
8049
|
+
const osExists = osTasks.some(
|
|
8050
|
+
(task) => (task.taskName ?? "").toLowerCase() === trimmed.toLowerCase(),
|
|
8051
|
+
);
|
|
8052
|
+
if (!osExists) {
|
|
8053
|
+
throw new Error(t("tool.error.taskNotFound", { name: trimmed }));
|
|
8054
|
+
}
|
|
8055
|
+
}
|
|
8056
|
+
|
|
6997
8057
|
// Любой запуск через этот вход — «сейчас», а не «по расписанию»:
|
|
6998
8058
|
// run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
|
|
6999
8059
|
// Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
|
|
@@ -7217,6 +8277,8 @@ async function collectTasksView() {
|
|
|
7217
8277
|
deniedTools: Array.isArray(def?.deniedTools) ? def.deniedTools : null,
|
|
7218
8278
|
matrix: def?.matrix ?? null,
|
|
7219
8279
|
matrixParentId: def?.matrixParentId ?? null,
|
|
8280
|
+
/** Экономика v2 (E-2): лимит токенов на запуск для аналитики дашборда. */
|
|
8281
|
+
tokenBudget: def?.tokenBudget ?? null,
|
|
7220
8282
|
isMatrixParent: Boolean(def?.matrix),
|
|
7221
8283
|
matrixSummary: matrixAggregate
|
|
7222
8284
|
? {
|