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/dist/index.js CHANGED
@@ -34,6 +34,8 @@ import { migrateJsonToDb } from "./db/migrate.js";
34
34
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
35
35
  import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
36
36
  import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
37
+ import { deleteSecret, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
38
+ import { readAuditLog, recordAudit, } from "./core/audit.js";
37
39
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
38
40
  const require = createRequire(import.meta.url);
39
41
  const resolvedRecorder = require.resolve("./core/record-history.js");
@@ -533,6 +535,10 @@ export const manageSettingsSchema = z.object({
533
535
  .any()
534
536
  .optional()
535
537
  .describe("Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."),
538
+ audit: z
539
+ .any()
540
+ .optional()
541
+ .describe("Audit log settings patch (enabled, retentionDays, maxRecords)."),
536
542
  });
537
543
  /** manage_templates — пользовательские шаблоны задач. */
538
544
  export const manageTemplatesSchema = z.object({
@@ -602,6 +608,29 @@ export const emitEventSchema = z.object({
602
608
  eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
603
609
  payload: z.any().optional().describe("Event payload passed to trigger filters."),
604
610
  });
611
+ /** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
612
+ export const manageSecretsSchema = z.object({
613
+ action: z
614
+ .enum(["list", "set", "delete"])
615
+ .describe("list — secret names and previews; set — create or replace; delete — remove by name."),
616
+ name: z
617
+ .string()
618
+ .optional()
619
+ .describe("Secret name ([A-Za-z0-9_.-], max 64 chars). Required for set/delete."),
620
+ value: z.string().optional().describe("Secret value (required for set). Never returned by list."),
621
+ });
622
+ /** get_audit_log — журнал мутаций задач и настроек (Спринт 26). */
623
+ export const getAuditLogSchema = z.object({
624
+ action: z.string().optional().describe("Filter by action, for example task.create."),
625
+ target: z.string().optional().describe("Filter by target name or id."),
626
+ actor: z
627
+ .string()
628
+ .optional()
629
+ .describe("Filter by actor: mcp (agent), gui (dashboard), http (webhook/API)."),
630
+ since: z.string().optional().describe("ISO timestamp lower bound."),
631
+ until: z.string().optional().describe("ISO timestamp upper bound."),
632
+ limit: z.number().int().min(1).max(5000).optional().describe("Max records (default 200)."),
633
+ });
605
634
  /**
606
635
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
607
636
  * директория задачи по умолчанию, чтобы `opencode run` подхватил opencode.json
@@ -1545,11 +1574,12 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1545
1574
  args.winterMode === undefined &&
1546
1575
  args.notifications === undefined &&
1547
1576
  args.history === undefined &&
1548
- args.integrations === undefined) {
1577
+ args.integrations === undefined &&
1578
+ args.audit === undefined) {
1549
1579
  return {
1550
1580
  content: JSON.stringify({
1551
1581
  success: false,
1552
- error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history или integrations.",
1582
+ error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
1553
1583
  settings: current,
1554
1584
  }),
1555
1585
  };
@@ -1560,6 +1590,7 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1560
1590
  notifications: args.notifications,
1561
1591
  history: args.history,
1562
1592
  integrations: args.integrations,
1593
+ audit: args.audit,
1563
1594
  });
1564
1595
  return { content: JSON.stringify({ success: true, settings }) };
1565
1596
  });
@@ -1764,6 +1795,180 @@ const emitEventExecute = wrapExecute(async (args) => {
1764
1795
  }),
1765
1796
  };
1766
1797
  });
1798
+ /** manage_secrets — зашифрованное хранилище секретов. */
1799
+ const manageSecretsExecute = wrapExecute(async (args) => {
1800
+ if (args.action === "list") {
1801
+ return { content: JSON.stringify({ success: true, secrets: listSecrets() }) };
1802
+ }
1803
+ const name = (args.name ?? "").trim();
1804
+ if (!name) {
1805
+ return {
1806
+ content: JSON.stringify({
1807
+ success: false,
1808
+ error: "Для set/delete нужно имя секрета.",
1809
+ }),
1810
+ };
1811
+ }
1812
+ if (args.action === "delete") {
1813
+ const existed = hasSecret(name);
1814
+ deleteSecret(name);
1815
+ return {
1816
+ content: JSON.stringify({
1817
+ success: existed,
1818
+ message: existed
1819
+ ? `Секрет ${name} удалён.`
1820
+ : `Секрет ${name} не найден.`,
1821
+ }),
1822
+ };
1823
+ }
1824
+ const value = args.value;
1825
+ if (typeof value !== "string" || value.length === 0) {
1826
+ return {
1827
+ content: JSON.stringify({
1828
+ success: false,
1829
+ error: "Для action=set нужно непустое значение value.",
1830
+ }),
1831
+ };
1832
+ }
1833
+ const item = setSecret(name, value);
1834
+ return {
1835
+ content: JSON.stringify({
1836
+ success: true,
1837
+ message: `Секрет ${item.name} сохранён в зашифрованном виде.`,
1838
+ secret: item,
1839
+ }),
1840
+ };
1841
+ });
1842
+ /** get_audit_log — чтение журнала мутаций. */
1843
+ const getAuditLogExecute = wrapExecute(async (args) => {
1844
+ const result = readAuditLog({
1845
+ action: args.action,
1846
+ target: args.target,
1847
+ actor: args.actor,
1848
+ since: args.since,
1849
+ until: args.until,
1850
+ limit: args.limit,
1851
+ });
1852
+ return { content: JSON.stringify({ success: true, ...result }) };
1853
+ });
1854
+ /**
1855
+ * Оборачивает execute инструмента, записывая успешную мутацию в audit log.
1856
+ * Аудит не должен ломать сам инструмент, поэтому ошибки проглатываются.
1857
+ */
1858
+ function withAudit(toolName, describe, execute) {
1859
+ return async (args, context) => {
1860
+ const result = await execute(args, context);
1861
+ try {
1862
+ const raw = String(result?.content ?? "");
1863
+ const parsed = raw ? JSON.parse(raw) : null;
1864
+ if (parsed?.success === false)
1865
+ return result;
1866
+ const entry = describe(args);
1867
+ if (entry) {
1868
+ recordAudit({ ...entry, actor: "mcp", source: toolName });
1869
+ }
1870
+ }
1871
+ catch {
1872
+ // Аудит — вспомогательная функция: не мешает основной операции.
1873
+ }
1874
+ return result;
1875
+ };
1876
+ }
1877
+ /** Правила аудита для RPC-методов GUI (Спринт 26). */
1878
+ const RPC_AUDIT_RULES = {
1879
+ create_task: { action: "task.create", targetType: "task", target: (i) => i.name ?? "" },
1880
+ update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
1881
+ delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
1882
+ run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
1883
+ pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
1884
+ resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
1885
+ cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
1886
+ cleanup_matrix_orphans: {
1887
+ action: "matrix.cleanup",
1888
+ targetType: "matrix",
1889
+ target: () => "orphans",
1890
+ },
1891
+ cleanup_history: {
1892
+ action: "history.cleanup",
1893
+ targetType: "history",
1894
+ target: () => "runs",
1895
+ },
1896
+ emit_event: { action: "event.emit", targetType: "event", target: (i) => i.eventName ?? "" },
1897
+ add_workspace: {
1898
+ action: "workspace.add",
1899
+ targetType: "workspace",
1900
+ target: (i) => i.name ?? i.path ?? "",
1901
+ },
1902
+ update_workspace: {
1903
+ action: "workspace.update",
1904
+ targetType: "workspace",
1905
+ target: (i) => i.id ?? "",
1906
+ },
1907
+ delete_workspace: {
1908
+ action: "workspace.delete",
1909
+ targetType: "workspace",
1910
+ target: (i) => i.id ?? "",
1911
+ },
1912
+ set_profile: { action: "profile.switch", targetType: "profile", target: (i) => i.name ?? "" },
1913
+ create_profile: {
1914
+ action: "profile.create",
1915
+ targetType: "profile",
1916
+ target: (i) => i.name ?? "",
1917
+ },
1918
+ delete_profile: {
1919
+ action: "profile.delete",
1920
+ targetType: "profile",
1921
+ target: (i) => i.name ?? "",
1922
+ },
1923
+ import_tasks: { action: "tasks.import", targetType: "tasks", target: () => "snapshot" },
1924
+ save_settings: { action: "settings.update", targetType: "settings", target: () => "global" },
1925
+ save_template: {
1926
+ action: "template.save",
1927
+ targetType: "template",
1928
+ target: (i) => i.id ?? i.name ?? "",
1929
+ },
1930
+ delete_template: {
1931
+ action: "template.delete",
1932
+ targetType: "template",
1933
+ target: (i) => i.id ?? "",
1934
+ },
1935
+ save_secret: { action: "secret.set", targetType: "secret", target: (i) => i.name ?? "" },
1936
+ delete_secret: { action: "secret.delete", targetType: "secret", target: (i) => i.name ?? "" },
1937
+ };
1938
+ /**
1939
+ * Оборачивает RPC-обработчики GUI: успешные мутации попадают в audit log
1940
+ * с actor=gui. Ошибки аудита не влияют на ответ GUI.
1941
+ */
1942
+ function withRpcAudit(handlers) {
1943
+ const wrapped = {};
1944
+ for (const [name, handler] of Object.entries(handlers)) {
1945
+ const rule = RPC_AUDIT_RULES[name];
1946
+ if (!rule || typeof handler !== "function") {
1947
+ wrapped[name] = handler;
1948
+ continue;
1949
+ }
1950
+ wrapped[name] = async (...args) => {
1951
+ const input = args[0] ?? {};
1952
+ const result = await handler(...args);
1953
+ try {
1954
+ if (result?.success !== false) {
1955
+ recordAudit({
1956
+ action: rule.action,
1957
+ targetType: rule.targetType,
1958
+ target: rule.target(input),
1959
+ actor: "gui",
1960
+ source: name,
1961
+ });
1962
+ }
1963
+ }
1964
+ catch {
1965
+ // Журнал не должен ломать GUI-операцию.
1966
+ }
1967
+ return result;
1968
+ };
1969
+ }
1970
+ return wrapped;
1971
+ }
1767
1972
  /**
1768
1973
  * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
1769
1974
  * обновлять после создания/изменения/удаления задачи. Раньше refresh()
@@ -1910,7 +2115,7 @@ export default Plugin.define({
1910
2115
  "Every run goes through a timeout + lock-file wrapper, so overlapping runs are skipped. " +
1911
2116
  "Without workingDirectory the task runs in the current project folder, where opencode run picks up the project's opencode.json and MCP servers.",
1912
2117
  options: { codemode: true },
1913
- execute: scheduleTaskExecute,
2118
+ execute: withAudit("schedule_task", (args) => ({ action: "task.create", targetType: "task", target: args.name }), scheduleTaskExecute),
1914
2119
  });
1915
2120
  editor.add({
1916
2121
  name: "list_tasks",
@@ -1926,7 +2131,7 @@ export default Plugin.define({
1926
2131
  description: "Partially updates an existing task: omitted fields keep their current values, empty strings/arrays clear them. " +
1927
2132
  "Matrix changes are synced (clones are diffed, running clones are never touched); pass matrix: null to remove the matrix and its clones.",
1928
2133
  options: { codemode: true },
1929
- execute: updateTaskExecute,
2134
+ execute: withAudit("update_task", (args) => ({ action: "task.update", targetType: "task", target: args.name }), updateTaskExecute),
1930
2135
  });
1931
2136
  editor.add({
1932
2137
  name: "delete_task",
@@ -1934,7 +2139,7 @@ export default Plugin.define({
1934
2139
  description: `Deletes a task from the scheduler (${scheduler.title}) by name. ` +
1935
2140
  "Deleting a matrix parent also deletes its clones and aggregator; deleting a single clone is refused (delete the whole matrix instead).",
1936
2141
  options: { codemode: true },
1937
- execute: deleteTaskExecute,
2142
+ execute: withAudit("delete_task", (args) => ({ action: "task.delete", targetType: "task", target: args.name }), deleteTaskExecute),
1938
2143
  });
1939
2144
  editor.add({
1940
2145
  name: "run_task_now",
@@ -1942,21 +2147,21 @@ export default Plugin.define({
1942
2147
  description: `Runs a task immediately in the scheduler (${scheduler.title}) for testing. ` +
1943
2148
  "Runs through the timeout + lock wrapper. For a matrix parent this starts the fan-out instead of the parent itself.",
1944
2149
  options: { codemode: true },
1945
- execute: runTaskNowExecute,
2150
+ execute: withAudit("run_task_now", (args) => ({ action: "task.run", targetType: "task", target: args.name }), runTaskNowExecute),
1946
2151
  });
1947
2152
  editor.add({
1948
2153
  name: "pause_task",
1949
2154
  input: pauseTaskSchema,
1950
2155
  description: "Pauses a task in the OS scheduler. For a matrix parent every clone is paused (the parent itself never runs).",
1951
2156
  options: { codemode: true },
1952
- execute: pauseTaskExecute,
2157
+ execute: withAudit("pause_task", (args) => ({ action: "task.pause", targetType: "task", target: args.name }), pauseTaskExecute),
1953
2158
  });
1954
2159
  editor.add({
1955
2160
  name: "resume_task",
1956
2161
  input: resumeTaskSchema,
1957
2162
  description: "Resumes a previously paused task. For a matrix parent every clone is resumed.",
1958
2163
  options: { codemode: true },
1959
- execute: resumeTaskExecute,
2164
+ execute: withAudit("resume_task", (args) => ({ action: "task.resume", targetType: "task", target: args.name }), resumeTaskExecute),
1960
2165
  });
1961
2166
  editor.add({
1962
2167
  name: "get_history",
@@ -1985,14 +2190,26 @@ export default Plugin.define({
1985
2190
  input: manageWorkspacesSchema,
1986
2191
  description: "Manages multi-repo workspaces: list, add, update or delete. Tasks can target a workspace by id (cwd = workspace path) or fan out to several with matrix.workspaceIds.",
1987
2192
  options: { codemode: true },
1988
- execute: manageWorkspacesExecute,
2193
+ execute: withAudit("manage_workspaces", (args) => args.action === "list"
2194
+ ? null
2195
+ : {
2196
+ action: `workspace.${args.action}`,
2197
+ targetType: "workspace",
2198
+ target: args.id || args.name || "",
2199
+ }, manageWorkspacesExecute),
1989
2200
  });
1990
2201
  editor.add({
1991
2202
  name: "matrix_control",
1992
2203
  input: matrixControlSchema,
1993
2204
  description: "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).",
1994
2205
  options: { codemode: true },
1995
- execute: matrixControlExecute,
2206
+ execute: withAudit("matrix_control", (args) => args.action === "cancel" || args.action === "cleanup"
2207
+ ? {
2208
+ action: `matrix.${args.action}`,
2209
+ targetType: "matrix",
2210
+ target: args.name || "",
2211
+ }
2212
+ : null, matrixControlExecute),
1996
2213
  });
1997
2214
  editor.add({
1998
2215
  name: "get_metrics",
@@ -2013,28 +2230,44 @@ export default Plugin.define({
2013
2230
  input: manageSettingsSchema,
2014
2231
  description: "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.",
2015
2232
  options: { codemode: true },
2016
- execute: manageSettingsExecute,
2233
+ execute: withAudit("manage_settings", (args) => args.action === "update"
2234
+ ? { action: "settings.update", targetType: "settings", target: "global" }
2235
+ : null, manageSettingsExecute),
2017
2236
  });
2018
2237
  editor.add({
2019
2238
  name: "manage_templates",
2020
2239
  input: manageTemplatesSchema,
2021
2240
  description: "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
2022
2241
  options: { codemode: true },
2023
- execute: manageTemplatesExecute,
2242
+ execute: withAudit("manage_templates", (args) => args.action === "list"
2243
+ ? null
2244
+ : {
2245
+ action: `template.${args.action}`,
2246
+ targetType: "template",
2247
+ target: args.id || args.name || "",
2248
+ }, manageTemplatesExecute),
2024
2249
  });
2025
2250
  editor.add({
2026
2251
  name: "manage_profiles",
2027
2252
  input: manageProfilesSchema,
2028
2253
  description: "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
2029
2254
  options: { codemode: true },
2030
- execute: manageProfilesExecute,
2255
+ execute: withAudit("manage_profiles", (args) => args.action === "list"
2256
+ ? null
2257
+ : {
2258
+ action: `profile.${args.action}`,
2259
+ targetType: "profile",
2260
+ target: args.name || "",
2261
+ }, manageProfilesExecute),
2031
2262
  });
2032
2263
  editor.add({
2033
2264
  name: "transfer_tasks",
2034
2265
  input: transferTasksSchema,
2035
2266
  description: "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
2036
2267
  options: { codemode: true },
2037
- execute: transferTasksExecute,
2268
+ execute: withAudit("transfer_tasks", (args) => args.action === "import"
2269
+ ? { action: "tasks.import", targetType: "tasks", target: "snapshot" }
2270
+ : null, transferTasksExecute),
2038
2271
  });
2039
2272
  editor.add({
2040
2273
  name: "send_notification",
@@ -2055,7 +2288,30 @@ export default Plugin.define({
2055
2288
  input: cleanupHistorySchema,
2056
2289
  description: "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
2057
2290
  options: { codemode: true },
2058
- execute: cleanupHistoryExecute,
2291
+ execute: withAudit("cleanup_history", () => ({ action: "history.cleanup", targetType: "history", target: "runs" }), cleanupHistoryExecute),
2292
+ });
2293
+ editor.add({
2294
+ name: "manage_secrets",
2295
+ input: manageSecretsSchema,
2296
+ description: "Manages the encrypted secret store: list (names and masked previews), set (create or replace) or delete. " +
2297
+ "Secrets are encrypted with AES-256-GCM at rest and referenced from workspace env as ${secret:NAME}; " +
2298
+ "values are never returned by list and are redacted from logs and audit details.",
2299
+ options: { codemode: true },
2300
+ execute: withAudit("manage_secrets", (args) => args.action === "list"
2301
+ ? null
2302
+ : {
2303
+ action: `secret.${args.action}`,
2304
+ targetType: "secret",
2305
+ target: (args.name ?? "").trim(),
2306
+ }, manageSecretsExecute),
2307
+ });
2308
+ editor.add({
2309
+ name: "get_audit_log",
2310
+ input: getAuditLogSchema,
2311
+ description: "Returns the audit journal of task and settings mutations: who changed what, when and through which interface (mcp, gui, http). " +
2312
+ "Filter by action, target, actor, time range and limit. Secret values are redacted.",
2313
+ options: { codemode: true },
2314
+ execute: getAuditLogExecute,
2059
2315
  });
2060
2316
  editor.add({
2061
2317
  name: "emit_event",
@@ -2090,7 +2346,7 @@ export default Plugin.define({
2090
2346
  // Регистрируем RPC-методы, вызываемые из GUI-панели.
2091
2347
  // Общая логика создания задачи вынесена в schedulerCreateTask, чтобы
2092
2348
  // schedule_task и create_task использовали один и тот же путь.
2093
- const rpcRegistration = await ctx.rpc.register(SchedulerRpc, {
2349
+ const rpcHandlers = {
2094
2350
  get_tasks: async () => {
2095
2351
  return { tasks: await collectTasksView() };
2096
2352
  },
@@ -2573,13 +2829,14 @@ export default Plugin.define({
2573
2829
  return await loadSettings();
2574
2830
  },
2575
2831
  save_settings: async (input) => {
2576
- const { maxConcurrent, winterMode, notifications, history, integrations } = input;
2832
+ const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input;
2577
2833
  const current = await loadSettings();
2578
2834
  if (maxConcurrent === undefined &&
2579
2835
  winterMode === undefined &&
2580
2836
  notifications === undefined &&
2581
2837
  history === undefined &&
2582
- integrations === undefined) {
2838
+ integrations === undefined &&
2839
+ audit === undefined) {
2583
2840
  return {
2584
2841
  success: false,
2585
2842
  maxConcurrent: current.maxConcurrent,
@@ -2587,6 +2844,7 @@ export default Plugin.define({
2587
2844
  notifications: current.notifications,
2588
2845
  history: current.history,
2589
2846
  integrations: current.integrations,
2847
+ audit: current.audit,
2590
2848
  };
2591
2849
  }
2592
2850
  const settings = await saveSettings({
@@ -2595,6 +2853,7 @@ export default Plugin.define({
2595
2853
  notifications,
2596
2854
  history,
2597
2855
  integrations,
2856
+ audit,
2598
2857
  });
2599
2858
  return {
2600
2859
  success: true,
@@ -2603,6 +2862,7 @@ export default Plugin.define({
2603
2862
  notifications: settings.notifications,
2604
2863
  history: settings.history,
2605
2864
  integrations: settings.integrations,
2865
+ audit: settings.audit,
2606
2866
  };
2607
2867
  },
2608
2868
  test_notification: async () => {
@@ -2612,6 +2872,68 @@ export default Plugin.define({
2612
2872
  // Ручная отправка не сдвигает плановое расписание дайджеста.
2613
2873
  return await sendDigestNow({ updateLastSentAt: false });
2614
2874
  },
2875
+ // --- Спринт 26: секреты и аудит -------------------------------------
2876
+ list_secrets: async () => {
2877
+ return { success: true, secrets: listSecrets() };
2878
+ },
2879
+ save_secret: async (input) => {
2880
+ try {
2881
+ const source = (input ?? {});
2882
+ const name = (source.name ?? "").trim();
2883
+ if (!name) {
2884
+ return { success: false, message: "Нужно имя секрета." };
2885
+ }
2886
+ if (typeof source.value !== "string" || source.value.length === 0) {
2887
+ return { success: false, message: "Нужно непустое значение секрета." };
2888
+ }
2889
+ const secret = setSecret(name, source.value);
2890
+ return {
2891
+ success: true,
2892
+ message: `Секрет ${secret.name} сохранён в зашифрованном виде.`,
2893
+ secret,
2894
+ };
2895
+ }
2896
+ catch (err) {
2897
+ return {
2898
+ success: false,
2899
+ message: err instanceof Error ? err.message : String(err),
2900
+ };
2901
+ }
2902
+ },
2903
+ delete_secret: async (input) => {
2904
+ try {
2905
+ const name = ((input ?? {}).name ?? "").trim();
2906
+ if (!name) {
2907
+ return { success: false, message: "Нужно имя секрета." };
2908
+ }
2909
+ const existed = hasSecret(name);
2910
+ deleteSecret(name);
2911
+ return {
2912
+ success: existed,
2913
+ message: existed
2914
+ ? `Секрет ${name} удалён.`
2915
+ : `Секрет ${name} не найден.`,
2916
+ };
2917
+ }
2918
+ catch (err) {
2919
+ return {
2920
+ success: false,
2921
+ message: err instanceof Error ? err.message : String(err),
2922
+ };
2923
+ }
2924
+ },
2925
+ get_audit: async (input) => {
2926
+ const source = (input ?? {});
2927
+ const result = readAuditLog({
2928
+ action: source.action,
2929
+ target: source.target,
2930
+ actor: source.actor,
2931
+ since: source.since,
2932
+ until: source.until,
2933
+ limit: source.limit,
2934
+ });
2935
+ return { success: true, ...result };
2936
+ },
2615
2937
  get_templates: async () => {
2616
2938
  try {
2617
2939
  return { templates: await loadTemplates() };
@@ -2717,7 +3039,8 @@ export default Plugin.define({
2717
3039
  return { success: false, error: err instanceof Error ? err.message : String(err) };
2718
3040
  }
2719
3041
  },
2720
- });
3042
+ };
3043
+ const rpcRegistration = await ctx.rpc.register(SchedulerRpc, withRpcAudit(rpcHandlers));
2721
3044
  // Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
2722
3045
  // чьи родители были удалены в прошлых сессиях.
2723
3046
  void cleanupOrphanedMatrixTasks().catch((err) => {