opencode-windows-scheduler 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/README.md +9 -3
  3. package/ROADMAP-STRATEGY.md +11 -11
  4. package/ROADMAP.md +2 -7
  5. package/dist/core/audit.d.ts +68 -0
  6. package/dist/core/audit.d.ts.map +1 -0
  7. package/dist/core/audit.js +206 -0
  8. package/dist/core/secrets.d.ts +57 -0
  9. package/dist/core/secrets.d.ts.map +1 -0
  10. package/dist/core/secrets.js +331 -0
  11. package/dist/core/structured-log.d.ts.map +1 -1
  12. package/dist/core/structured-log.js +9 -0
  13. package/dist/db/schema.d.ts +1 -1
  14. package/dist/db/schema.d.ts.map +1 -1
  15. package/dist/db/schema.js +15 -0
  16. package/dist/index.d.ts +24 -4
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +342 -19
  19. package/dist/rpc.d.ts +400 -0
  20. package/dist/rpc.d.ts.map +1 -1
  21. package/dist/rpc.js +146 -0
  22. package/dist/server.d.ts.map +1 -1
  23. package/dist/server.js +67 -0
  24. package/dist/settings.d.ts +16 -0
  25. package/dist/settings.d.ts.map +1 -1
  26. package/dist/settings.js +29 -0
  27. package/dist/workspaces.d.ts +8 -2
  28. package/dist/workspaces.d.ts.map +1 -1
  29. package/dist/workspaces.js +21 -4
  30. package/docs/ARCHITECTURE.md +13 -5
  31. package/docs/FEATURES.md +29 -1
  32. package/docs/README.ru.md +13 -3
  33. package/gui-experimental.cjs +4 -4
  34. package/package.json +4 -2
  35. package/src/core/audit.ts +291 -0
  36. package/src/core/secrets.ts +385 -0
  37. package/src/core/structured-log.ts +9 -0
  38. package/src/db/schema.ts +15 -0
  39. package/src/gui.tsx +323 -0
  40. package/src/index.ts +452 -19
  41. package/src/rpc.ts +157 -0
  42. package/src/server.ts +67 -0
  43. package/src/settings.ts +51 -0
  44. package/src/workspaces.ts +22 -4
package/src/index.ts CHANGED
@@ -40,6 +40,7 @@ import { SchedulerRpc } from "./rpc.js";
40
40
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
41
41
  import { loadSettings, saveSettings } from "./settings.js";
42
42
  import type {
43
+ AuditSettings,
43
44
  HistorySettings,
44
45
  IntegrationSettings,
45
46
  NotificationSettings,
@@ -99,6 +100,18 @@ import {
99
100
  writeWorkspaceEnvFile,
100
101
  maskEnvForLog,
101
102
  } from "./workspaces.js";
103
+ import {
104
+ deleteSecret,
105
+ hasSecret,
106
+ listSecrets,
107
+ setSecret,
108
+ } from "./core/secrets.js";
109
+ import {
110
+ cleanupAuditLog,
111
+ readAuditLog,
112
+ recordAudit,
113
+ } from "./core/audit.js";
114
+ import type { AuditEntryInput } from "./core/audit.js";
102
115
 
103
116
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
104
117
  const require = createRequire(import.meta.url);
@@ -695,6 +708,10 @@ export const manageSettingsSchema = z.object({
695
708
  .describe(
696
709
  "Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."
697
710
  ),
711
+ audit: z
712
+ .any()
713
+ .optional()
714
+ .describe("Audit log settings patch (enabled, retentionDays, maxRecords)."),
698
715
  });
699
716
 
700
717
  /** manage_templates — пользовательские шаблоны задач. */
@@ -772,6 +789,31 @@ export const emitEventSchema = z.object({
772
789
  payload: z.any().optional().describe("Event payload passed to trigger filters."),
773
790
  });
774
791
 
792
+ /** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
793
+ export const manageSecretsSchema = z.object({
794
+ action: z
795
+ .enum(["list", "set", "delete"])
796
+ .describe("list — secret names and previews; set — create or replace; delete — remove by name."),
797
+ name: z
798
+ .string()
799
+ .optional()
800
+ .describe("Secret name ([A-Za-z0-9_.-], max 64 chars). Required for set/delete."),
801
+ value: z.string().optional().describe("Secret value (required for set). Never returned by list."),
802
+ });
803
+
804
+ /** get_audit_log — журнал мутаций задач и настроек (Спринт 26). */
805
+ export const getAuditLogSchema = z.object({
806
+ action: z.string().optional().describe("Filter by action, for example task.create."),
807
+ target: z.string().optional().describe("Filter by target name or id."),
808
+ actor: z
809
+ .string()
810
+ .optional()
811
+ .describe("Filter by actor: mcp (agent), gui (dashboard), http (webhook/API)."),
812
+ since: z.string().optional().describe("ISO timestamp lower bound."),
813
+ until: z.string().optional().describe("ISO timestamp upper bound."),
814
+ limit: z.number().int().min(1).max(5000).optional().describe("Max records (default 200)."),
815
+ });
816
+
775
817
  type ScheduleArgs = z.infer<typeof scheduleTaskSchema>;
776
818
  type ListArgs = z.infer<typeof listTasksSchema>;
777
819
  type DeleteArgs = z.infer<typeof deleteTaskSchema>;
@@ -794,6 +836,8 @@ type NotificationArgs = z.infer<typeof sendNotificationSchema>;
794
836
  type DashboardInfoArgs = z.infer<typeof getDashboardInfoSchema>;
795
837
  type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
796
838
  type EmitEventArgs = z.infer<typeof emitEventSchema>;
839
+ type SecretsArgs = z.infer<typeof manageSecretsSchema>;
840
+ type AuditLogArgs = z.infer<typeof getAuditLogSchema>;
797
841
 
798
842
  /**
799
843
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -1966,13 +2010,14 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
1966
2010
  args.winterMode === undefined &&
1967
2011
  args.notifications === undefined &&
1968
2012
  args.history === undefined &&
1969
- args.integrations === undefined
2013
+ args.integrations === undefined &&
2014
+ args.audit === undefined
1970
2015
  ) {
1971
2016
  return {
1972
2017
  content: JSON.stringify({
1973
2018
  success: false,
1974
2019
  error:
1975
- "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history или integrations.",
2020
+ "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
1976
2021
  settings: current,
1977
2022
  }),
1978
2023
  };
@@ -1984,6 +2029,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
1984
2029
  notifications: args.notifications as NotificationSettings | undefined,
1985
2030
  history: args.history as HistorySettings | undefined,
1986
2031
  integrations: args.integrations as IntegrationSettings | undefined,
2032
+ audit: args.audit as AuditSettings | undefined,
1987
2033
  });
1988
2034
  return { content: JSON.stringify({ success: true, settings }) };
1989
2035
  });
@@ -2243,6 +2289,197 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
2243
2289
  };
2244
2290
  });
2245
2291
 
2292
+ /** manage_secrets — зашифрованное хранилище секретов. */
2293
+ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
2294
+ if (args.action === "list") {
2295
+ return { content: JSON.stringify({ success: true, secrets: listSecrets() }) };
2296
+ }
2297
+
2298
+ const name = (args.name ?? "").trim();
2299
+ if (!name) {
2300
+ return {
2301
+ content: JSON.stringify({
2302
+ success: false,
2303
+ error: "Для set/delete нужно имя секрета.",
2304
+ }),
2305
+ };
2306
+ }
2307
+
2308
+ if (args.action === "delete") {
2309
+ const existed = hasSecret(name);
2310
+ deleteSecret(name);
2311
+ return {
2312
+ content: JSON.stringify({
2313
+ success: existed,
2314
+ message: existed
2315
+ ? `Секрет ${name} удалён.`
2316
+ : `Секрет ${name} не найден.`,
2317
+ }),
2318
+ };
2319
+ }
2320
+
2321
+ const value = args.value;
2322
+ if (typeof value !== "string" || value.length === 0) {
2323
+ return {
2324
+ content: JSON.stringify({
2325
+ success: false,
2326
+ error: "Для action=set нужно непустое значение value.",
2327
+ }),
2328
+ };
2329
+ }
2330
+
2331
+ const item = setSecret(name, value);
2332
+ return {
2333
+ content: JSON.stringify({
2334
+ success: true,
2335
+ message: `Секрет ${item.name} сохранён в зашифрованном виде.`,
2336
+ secret: item,
2337
+ }),
2338
+ };
2339
+ });
2340
+
2341
+ /** get_audit_log — чтение журнала мутаций. */
2342
+ const getAuditLogExecute = wrapExecute<AuditLogArgs>(async (args) => {
2343
+ const result = readAuditLog({
2344
+ action: args.action,
2345
+ target: args.target,
2346
+ actor: args.actor,
2347
+ since: args.since,
2348
+ until: args.until,
2349
+ limit: args.limit,
2350
+ });
2351
+ return { content: JSON.stringify({ success: true, ...result }) };
2352
+ });
2353
+
2354
+ /**
2355
+ * Оборачивает execute инструмента, записывая успешную мутацию в audit log.
2356
+ * Аудит не должен ломать сам инструмент, поэтому ошибки проглатываются.
2357
+ */
2358
+ function withAudit<A>(
2359
+ toolName: string,
2360
+ describe: (args: A) => Omit<AuditEntryInput, "actor"> | null,
2361
+ execute: (args: A, context: Tool.Context) => Promise<Tool.Result>
2362
+ ): (args: A, context: Tool.Context) => Promise<Tool.Result> {
2363
+ return async (args: A, context: Tool.Context) => {
2364
+ const result = await execute(args, context);
2365
+ try {
2366
+ const raw = String((result as any)?.content ?? "");
2367
+ const parsed = raw ? JSON.parse(raw) : null;
2368
+ if (parsed?.success === false) return result;
2369
+ const entry = describe(args);
2370
+ if (entry) {
2371
+ recordAudit({ ...entry, actor: "mcp", source: toolName });
2372
+ }
2373
+ } catch {
2374
+ // Аудит — вспомогательная функция: не мешает основной операции.
2375
+ }
2376
+ return result;
2377
+ };
2378
+ }
2379
+
2380
+ /** Правила аудита для RPC-методов GUI (Спринт 26). */
2381
+ const RPC_AUDIT_RULES: Record<
2382
+ string,
2383
+ {
2384
+ action: string;
2385
+ targetType: string;
2386
+ target: (input: any) => string;
2387
+ }
2388
+ > = {
2389
+ create_task: { action: "task.create", targetType: "task", target: (i) => i.name ?? "" },
2390
+ update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
2391
+ delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
2392
+ run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
2393
+ pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
2394
+ resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
2395
+ cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
2396
+ cleanup_matrix_orphans: {
2397
+ action: "matrix.cleanup",
2398
+ targetType: "matrix",
2399
+ target: () => "orphans",
2400
+ },
2401
+ cleanup_history: {
2402
+ action: "history.cleanup",
2403
+ targetType: "history",
2404
+ target: () => "runs",
2405
+ },
2406
+ emit_event: { action: "event.emit", targetType: "event", target: (i) => i.eventName ?? "" },
2407
+ add_workspace: {
2408
+ action: "workspace.add",
2409
+ targetType: "workspace",
2410
+ target: (i) => i.name ?? i.path ?? "",
2411
+ },
2412
+ update_workspace: {
2413
+ action: "workspace.update",
2414
+ targetType: "workspace",
2415
+ target: (i) => i.id ?? "",
2416
+ },
2417
+ delete_workspace: {
2418
+ action: "workspace.delete",
2419
+ targetType: "workspace",
2420
+ target: (i) => i.id ?? "",
2421
+ },
2422
+ set_profile: { action: "profile.switch", targetType: "profile", target: (i) => i.name ?? "" },
2423
+ create_profile: {
2424
+ action: "profile.create",
2425
+ targetType: "profile",
2426
+ target: (i) => i.name ?? "",
2427
+ },
2428
+ delete_profile: {
2429
+ action: "profile.delete",
2430
+ targetType: "profile",
2431
+ target: (i) => i.name ?? "",
2432
+ },
2433
+ import_tasks: { action: "tasks.import", targetType: "tasks", target: () => "snapshot" },
2434
+ save_settings: { action: "settings.update", targetType: "settings", target: () => "global" },
2435
+ save_template: {
2436
+ action: "template.save",
2437
+ targetType: "template",
2438
+ target: (i) => i.id ?? i.name ?? "",
2439
+ },
2440
+ delete_template: {
2441
+ action: "template.delete",
2442
+ targetType: "template",
2443
+ target: (i) => i.id ?? "",
2444
+ },
2445
+ save_secret: { action: "secret.set", targetType: "secret", target: (i) => i.name ?? "" },
2446
+ delete_secret: { action: "secret.delete", targetType: "secret", target: (i) => i.name ?? "" },
2447
+ };
2448
+
2449
+ /**
2450
+ * Оборачивает RPC-обработчики GUI: успешные мутации попадают в audit log
2451
+ * с actor=gui. Ошибки аудита не влияют на ответ GUI.
2452
+ */
2453
+ function withRpcAudit<T extends Record<string, (...args: any[]) => any>>(handlers: T): T {
2454
+ const wrapped: Record<string, (...args: any[]) => any> = {};
2455
+ for (const [name, handler] of Object.entries(handlers)) {
2456
+ const rule = RPC_AUDIT_RULES[name];
2457
+ if (!rule || typeof handler !== "function") {
2458
+ wrapped[name] = handler;
2459
+ continue;
2460
+ }
2461
+ wrapped[name] = async (...args: any[]) => {
2462
+ const input = args[0] ?? {};
2463
+ const result = await handler(...args);
2464
+ try {
2465
+ if ((result as any)?.success !== false) {
2466
+ recordAudit({
2467
+ action: rule.action,
2468
+ targetType: rule.targetType,
2469
+ target: rule.target(input),
2470
+ actor: "gui",
2471
+ source: name,
2472
+ });
2473
+ }
2474
+ } catch {
2475
+ // Журнал не должен ломать GUI-операцию.
2476
+ }
2477
+ return result;
2478
+ };
2479
+ }
2480
+ return wrapped as T;
2481
+ }
2482
+
2246
2483
  /**
2247
2484
  * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
2248
2485
  * обновлять после создания/изменения/удаления задачи. Раньше refresh()
@@ -2440,7 +2677,11 @@ export default Plugin.define({
2440
2677
  "Every run goes through a timeout + lock-file wrapper, so overlapping runs are skipped. " +
2441
2678
  "Without workingDirectory the task runs in the current project folder, where opencode run picks up the project's opencode.json and MCP servers.",
2442
2679
  options: { codemode: true },
2443
- execute: scheduleTaskExecute as any,
2680
+ execute: withAudit<ScheduleArgs>(
2681
+ "schedule_task",
2682
+ (args) => ({ action: "task.create", targetType: "task", target: args.name }),
2683
+ scheduleTaskExecute as any
2684
+ ) as any,
2444
2685
  });
2445
2686
 
2446
2687
  editor.add({
@@ -2460,7 +2701,11 @@ export default Plugin.define({
2460
2701
  "Partially updates an existing task: omitted fields keep their current values, empty strings/arrays clear them. " +
2461
2702
  "Matrix changes are synced (clones are diffed, running clones are never touched); pass matrix: null to remove the matrix and its clones.",
2462
2703
  options: { codemode: true },
2463
- execute: updateTaskExecute as any,
2704
+ execute: withAudit<UpdateArgs>(
2705
+ "update_task",
2706
+ (args) => ({ action: "task.update", targetType: "task", target: args.name }),
2707
+ updateTaskExecute as any
2708
+ ) as any,
2464
2709
  });
2465
2710
 
2466
2711
  editor.add({
@@ -2470,7 +2715,11 @@ export default Plugin.define({
2470
2715
  `Deletes a task from the scheduler (${scheduler.title}) by name. ` +
2471
2716
  "Deleting a matrix parent also deletes its clones and aggregator; deleting a single clone is refused (delete the whole matrix instead).",
2472
2717
  options: { codemode: true },
2473
- execute: deleteTaskExecute as any,
2718
+ execute: withAudit<DeleteArgs>(
2719
+ "delete_task",
2720
+ (args) => ({ action: "task.delete", targetType: "task", target: args.name }),
2721
+ deleteTaskExecute as any
2722
+ ) as any,
2474
2723
  });
2475
2724
 
2476
2725
  editor.add({
@@ -2480,7 +2729,11 @@ export default Plugin.define({
2480
2729
  `Runs a task immediately in the scheduler (${scheduler.title}) for testing. ` +
2481
2730
  "Runs through the timeout + lock wrapper. For a matrix parent this starts the fan-out instead of the parent itself.",
2482
2731
  options: { codemode: true },
2483
- execute: runTaskNowExecute as any,
2732
+ execute: withAudit<RunNowArgs>(
2733
+ "run_task_now",
2734
+ (args) => ({ action: "task.run", targetType: "task", target: args.name }),
2735
+ runTaskNowExecute as any
2736
+ ) as any,
2484
2737
  });
2485
2738
 
2486
2739
  editor.add({
@@ -2489,7 +2742,11 @@ export default Plugin.define({
2489
2742
  description:
2490
2743
  "Pauses a task in the OS scheduler. For a matrix parent every clone is paused (the parent itself never runs).",
2491
2744
  options: { codemode: true },
2492
- execute: pauseTaskExecute as any,
2745
+ execute: withAudit<PauseArgs>(
2746
+ "pause_task",
2747
+ (args) => ({ action: "task.pause", targetType: "task", target: args.name }),
2748
+ pauseTaskExecute as any
2749
+ ) as any,
2493
2750
  });
2494
2751
 
2495
2752
  editor.add({
@@ -2498,7 +2755,11 @@ export default Plugin.define({
2498
2755
  description:
2499
2756
  "Resumes a previously paused task. For a matrix parent every clone is resumed.",
2500
2757
  options: { codemode: true },
2501
- execute: resumeTaskExecute as any,
2758
+ execute: withAudit<ResumeArgs>(
2759
+ "resume_task",
2760
+ (args) => ({ action: "task.resume", targetType: "task", target: args.name }),
2761
+ resumeTaskExecute as any
2762
+ ) as any,
2502
2763
  });
2503
2764
 
2504
2765
  editor.add({
@@ -2535,7 +2796,18 @@ export default Plugin.define({
2535
2796
  description:
2536
2797
  "Manages multi-repo workspaces: list, add, update or delete. Tasks can target a workspace by id (cwd = workspace path) or fan out to several with matrix.workspaceIds.",
2537
2798
  options: { codemode: true },
2538
- execute: manageWorkspacesExecute as any,
2799
+ execute: withAudit<WorkspacesArgs>(
2800
+ "manage_workspaces",
2801
+ (args) =>
2802
+ args.action === "list"
2803
+ ? null
2804
+ : {
2805
+ action: `workspace.${args.action}`,
2806
+ targetType: "workspace",
2807
+ target: args.id || args.name || "",
2808
+ },
2809
+ manageWorkspacesExecute as any
2810
+ ) as any,
2539
2811
  });
2540
2812
 
2541
2813
  editor.add({
@@ -2544,7 +2816,18 @@ export default Plugin.define({
2544
2816
  description:
2545
2817
  "Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones), cleanup (delete orphaned clones and aggregators whose parent is gone) or preview (expand a matrix config into clone names without creating anything).",
2546
2818
  options: { codemode: true },
2547
- execute: matrixControlExecute as any,
2819
+ execute: withAudit<MatrixControlArgs>(
2820
+ "matrix_control",
2821
+ (args) =>
2822
+ args.action === "cancel" || args.action === "cleanup"
2823
+ ? {
2824
+ action: `matrix.${args.action}`,
2825
+ targetType: "matrix",
2826
+ target: args.name || "",
2827
+ }
2828
+ : null,
2829
+ matrixControlExecute as any
2830
+ ) as any,
2548
2831
  });
2549
2832
 
2550
2833
  editor.add({
@@ -2571,7 +2854,14 @@ export default Plugin.define({
2571
2854
  description:
2572
2855
  "Reads or updates global scheduler settings: maxConcurrent, winterMode, notifications (webhook, Telegram, native OS notifications, quiet hours, filters, matrix alerts, digest) and history retention. Updates are merged into the current settings.",
2573
2856
  options: { codemode: true },
2574
- execute: manageSettingsExecute as any,
2857
+ execute: withAudit<SettingsArgs>(
2858
+ "manage_settings",
2859
+ (args) =>
2860
+ args.action === "update"
2861
+ ? { action: "settings.update", targetType: "settings", target: "global" }
2862
+ : null,
2863
+ manageSettingsExecute as any
2864
+ ) as any,
2575
2865
  });
2576
2866
 
2577
2867
  editor.add({
@@ -2580,7 +2870,18 @@ export default Plugin.define({
2580
2870
  description:
2581
2871
  "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
2582
2872
  options: { codemode: true },
2583
- execute: manageTemplatesExecute as any,
2873
+ execute: withAudit<TemplatesArgs>(
2874
+ "manage_templates",
2875
+ (args) =>
2876
+ args.action === "list"
2877
+ ? null
2878
+ : {
2879
+ action: `template.${args.action}`,
2880
+ targetType: "template",
2881
+ target: args.id || args.name || "",
2882
+ },
2883
+ manageTemplatesExecute as any
2884
+ ) as any,
2584
2885
  });
2585
2886
 
2586
2887
  editor.add({
@@ -2589,7 +2890,18 @@ export default Plugin.define({
2589
2890
  description:
2590
2891
  "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
2591
2892
  options: { codemode: true },
2592
- execute: manageProfilesExecute as any,
2893
+ execute: withAudit<ProfilesArgs>(
2894
+ "manage_profiles",
2895
+ (args) =>
2896
+ args.action === "list"
2897
+ ? null
2898
+ : {
2899
+ action: `profile.${args.action}`,
2900
+ targetType: "profile",
2901
+ target: args.name || "",
2902
+ },
2903
+ manageProfilesExecute as any
2904
+ ) as any,
2593
2905
  });
2594
2906
 
2595
2907
  editor.add({
@@ -2598,7 +2910,14 @@ export default Plugin.define({
2598
2910
  description:
2599
2911
  "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
2600
2912
  options: { codemode: true },
2601
- execute: transferTasksExecute as any,
2913
+ execute: withAudit<TransferArgs>(
2914
+ "transfer_tasks",
2915
+ (args) =>
2916
+ args.action === "import"
2917
+ ? { action: "tasks.import", targetType: "tasks", target: "snapshot" }
2918
+ : null,
2919
+ transferTasksExecute as any
2920
+ ) as any,
2602
2921
  });
2603
2922
 
2604
2923
  editor.add({
@@ -2625,7 +2944,43 @@ export default Plugin.define({
2625
2944
  description:
2626
2945
  "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
2627
2946
  options: { codemode: true },
2628
- execute: cleanupHistoryExecute as any,
2947
+ execute: withAudit<CleanupHistoryArgs>(
2948
+ "cleanup_history",
2949
+ () => ({ action: "history.cleanup", targetType: "history", target: "runs" }),
2950
+ cleanupHistoryExecute as any
2951
+ ) as any,
2952
+ });
2953
+
2954
+ editor.add({
2955
+ name: "manage_secrets",
2956
+ input: manageSecretsSchema,
2957
+ description:
2958
+ "Manages the encrypted secret store: list (names and masked previews), set (create or replace) or delete. " +
2959
+ "Secrets are encrypted with AES-256-GCM at rest and referenced from workspace env as ${secret:NAME}; " +
2960
+ "values are never returned by list and are redacted from logs and audit details.",
2961
+ options: { codemode: true },
2962
+ execute: withAudit<SecretsArgs>(
2963
+ "manage_secrets",
2964
+ (args) =>
2965
+ args.action === "list"
2966
+ ? null
2967
+ : {
2968
+ action: `secret.${args.action}`,
2969
+ targetType: "secret",
2970
+ target: (args.name ?? "").trim(),
2971
+ },
2972
+ manageSecretsExecute as any
2973
+ ) as any,
2974
+ });
2975
+
2976
+ editor.add({
2977
+ name: "get_audit_log",
2978
+ input: getAuditLogSchema,
2979
+ description:
2980
+ "Returns the audit journal of task and settings mutations: who changed what, when and through which interface (mcp, gui, http). " +
2981
+ "Filter by action, target, actor, time range and limit. Secret values are redacted.",
2982
+ options: { codemode: true },
2983
+ execute: getAuditLogExecute as any,
2629
2984
  });
2630
2985
 
2631
2986
  editor.add({
@@ -2667,7 +3022,7 @@ export default Plugin.define({
2667
3022
  // Регистрируем RPC-методы, вызываемые из GUI-панели.
2668
3023
  // Общая логика создания задачи вынесена в schedulerCreateTask, чтобы
2669
3024
  // schedule_task и create_task использовали один и тот же путь.
2670
- const rpcRegistration = await ctx.rpc.register(SchedulerRpc, {
3025
+ const rpcHandlers = {
2671
3026
  get_tasks: async () => {
2672
3027
  return { tasks: await collectTasksView() };
2673
3028
  },
@@ -3286,12 +3641,13 @@ export default Plugin.define({
3286
3641
  return await loadSettings();
3287
3642
  },
3288
3643
  save_settings: async (input: unknown) => {
3289
- const { maxConcurrent, winterMode, notifications, history, integrations } = input as {
3644
+ const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input as {
3290
3645
  maxConcurrent?: number;
3291
3646
  winterMode?: boolean;
3292
3647
  notifications?: NotificationSettings;
3293
3648
  history?: HistorySettings;
3294
3649
  integrations?: IntegrationSettings;
3650
+ audit?: AuditSettings;
3295
3651
  };
3296
3652
  const current = await loadSettings();
3297
3653
  if (
@@ -3299,7 +3655,8 @@ export default Plugin.define({
3299
3655
  winterMode === undefined &&
3300
3656
  notifications === undefined &&
3301
3657
  history === undefined &&
3302
- integrations === undefined
3658
+ integrations === undefined &&
3659
+ audit === undefined
3303
3660
  ) {
3304
3661
  return {
3305
3662
  success: false,
@@ -3308,6 +3665,7 @@ export default Plugin.define({
3308
3665
  notifications: current.notifications,
3309
3666
  history: current.history,
3310
3667
  integrations: current.integrations,
3668
+ audit: current.audit,
3311
3669
  };
3312
3670
  }
3313
3671
  const settings = await saveSettings({
@@ -3316,6 +3674,7 @@ export default Plugin.define({
3316
3674
  notifications,
3317
3675
  history,
3318
3676
  integrations,
3677
+ audit,
3319
3678
  });
3320
3679
  return {
3321
3680
  success: true,
@@ -3324,6 +3683,7 @@ export default Plugin.define({
3324
3683
  notifications: settings.notifications,
3325
3684
  history: settings.history,
3326
3685
  integrations: settings.integrations,
3686
+ audit: settings.audit,
3327
3687
  };
3328
3688
  },
3329
3689
  test_notification: async () => {
@@ -3333,6 +3693,74 @@ export default Plugin.define({
3333
3693
  // Ручная отправка не сдвигает плановое расписание дайджеста.
3334
3694
  return await sendDigestNow({ updateLastSentAt: false });
3335
3695
  },
3696
+
3697
+ // --- Спринт 26: секреты и аудит -------------------------------------
3698
+ list_secrets: async () => {
3699
+ return { success: true, secrets: listSecrets() };
3700
+ },
3701
+ save_secret: async (input: unknown) => {
3702
+ try {
3703
+ const source = (input ?? {}) as { name?: string; value?: string };
3704
+ const name = (source.name ?? "").trim();
3705
+ if (!name) {
3706
+ return { success: false, message: "Нужно имя секрета." };
3707
+ }
3708
+ if (typeof source.value !== "string" || source.value.length === 0) {
3709
+ return { success: false, message: "Нужно непустое значение секрета." };
3710
+ }
3711
+ const secret = setSecret(name, source.value);
3712
+ return {
3713
+ success: true,
3714
+ message: `Секрет ${secret.name} сохранён в зашифрованном виде.`,
3715
+ secret,
3716
+ };
3717
+ } catch (err: any) {
3718
+ return {
3719
+ success: false,
3720
+ message: err instanceof Error ? err.message : String(err),
3721
+ };
3722
+ }
3723
+ },
3724
+ delete_secret: async (input: unknown) => {
3725
+ try {
3726
+ const name = (((input ?? {}) as { name?: string }).name ?? "").trim();
3727
+ if (!name) {
3728
+ return { success: false, message: "Нужно имя секрета." };
3729
+ }
3730
+ const existed = hasSecret(name);
3731
+ deleteSecret(name);
3732
+ return {
3733
+ success: existed,
3734
+ message: existed
3735
+ ? `Секрет ${name} удалён.`
3736
+ : `Секрет ${name} не найден.`,
3737
+ };
3738
+ } catch (err: any) {
3739
+ return {
3740
+ success: false,
3741
+ message: err instanceof Error ? err.message : String(err),
3742
+ };
3743
+ }
3744
+ },
3745
+ get_audit: async (input: unknown) => {
3746
+ const source = (input ?? {}) as {
3747
+ action?: string;
3748
+ target?: string;
3749
+ actor?: string;
3750
+ since?: string;
3751
+ until?: string;
3752
+ limit?: number;
3753
+ };
3754
+ const result = readAuditLog({
3755
+ action: source.action,
3756
+ target: source.target,
3757
+ actor: source.actor,
3758
+ since: source.since,
3759
+ until: source.until,
3760
+ limit: source.limit,
3761
+ });
3762
+ return { success: true, ...result };
3763
+ },
3336
3764
  get_templates: async () => {
3337
3765
  try {
3338
3766
  return { templates: await loadTemplates() };
@@ -3469,7 +3897,12 @@ export default Plugin.define({
3469
3897
  return { success: false, error: err instanceof Error ? err.message : String(err) };
3470
3898
  }
3471
3899
  },
3472
- });
3900
+ };
3901
+
3902
+ const rpcRegistration = await ctx.rpc.register(
3903
+ SchedulerRpc,
3904
+ withRpcAudit(rpcHandlers) as typeof rpcHandlers
3905
+ );
3473
3906
 
3474
3907
  // Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
3475
3908
  // чьи родители были удалены в прошлых сессиях.