opencode-windows-scheduler 1.5.1 → 1.5.4

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 (80) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/LICENSE +21 -21
  3. package/README.md +3 -2
  4. package/ROADMAP-STRATEGY.md +5 -4
  5. package/ROADMAP.md +502 -103
  6. package/dist/core/audit.d.ts +27 -0
  7. package/dist/core/audit.d.ts.map +1 -1
  8. package/dist/core/audit.js +60 -0
  9. package/dist/core/local-ai.d.ts +52 -0
  10. package/dist/core/local-ai.d.ts.map +1 -0
  11. package/dist/core/local-ai.js +119 -0
  12. package/dist/core/ps-wrapper.d.ts +2 -30
  13. package/dist/core/ps-wrapper.d.ts.map +1 -1
  14. package/dist/core/ps-wrapper.js +258 -49
  15. package/dist/core/secrets.d.ts +10 -3
  16. package/dist/core/secrets.d.ts.map +1 -1
  17. package/dist/core/secrets.js +28 -4
  18. package/dist/core/triage-chain.d.ts +34 -0
  19. package/dist/core/triage-chain.d.ts.map +1 -0
  20. package/dist/core/triage-chain.js +70 -0
  21. package/dist/core/triage-rules.d.ts +23 -0
  22. package/dist/core/triage-rules.d.ts.map +1 -0
  23. package/dist/core/triage-rules.js +174 -0
  24. package/dist/core/triage-shadow.d.ts +47 -0
  25. package/dist/core/triage-shadow.d.ts.map +1 -0
  26. package/dist/core/triage-shadow.js +48 -0
  27. package/dist/core/triage.d.ts +76 -0
  28. package/dist/core/triage.d.ts.map +1 -0
  29. package/dist/core/triage.js +271 -0
  30. package/dist/core/wrappers/bash.d.ts +1 -0
  31. package/dist/core/wrappers/bash.d.ts.map +1 -1
  32. package/dist/core/wrappers/bash.js +91 -5
  33. package/dist/gui-experimental.cjs +1 -0
  34. package/dist/i18n.d.ts.map +1 -1
  35. package/dist/i18n.js +34 -7
  36. package/dist/index.d.ts +27 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +194 -6
  39. package/dist/notifications.d.ts.map +1 -1
  40. package/dist/notifications.js +9 -1
  41. package/dist/rpc.d.ts +259 -0
  42. package/dist/rpc.d.ts.map +1 -1
  43. package/dist/rpc.js +58 -0
  44. package/dist/settings.d.ts +80 -0
  45. package/dist/settings.d.ts.map +1 -1
  46. package/dist/settings.js +199 -0
  47. package/dist/workspaces.d.ts +2 -2
  48. package/dist/workspaces.d.ts.map +1 -1
  49. package/dist/workspaces.js +6 -4
  50. package/docs/ARCHITECTURE.md +69 -10
  51. package/docs/FEATURES.md +37 -7
  52. package/docs/LOCAL-AI.md +202 -0
  53. package/docs/MIGRATION.md +17 -0
  54. package/docs/README.ru.md +5 -4
  55. package/docs/spikes/local-model-structured-output.md +81 -0
  56. package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
  57. package/docs/spikes/ollama-qwen3-4b.json +163 -0
  58. package/gui-experimental.cjs +8 -8
  59. package/locales/en.json +32 -0
  60. package/locales/ru.json +32 -0
  61. package/package.json +9 -2
  62. package/scripts/bench-local.mjs +321 -0
  63. package/scripts/spike-local-structured.mjs +182 -0
  64. package/skills/scheduled-job-best-practices/references/recipes.md +40 -0
  65. package/src/core/audit.ts +89 -0
  66. package/src/core/local-ai.ts +173 -0
  67. package/src/core/ps-wrapper.ts +265 -48
  68. package/src/core/secrets.ts +34 -10
  69. package/src/core/triage-chain.ts +116 -0
  70. package/src/core/triage-rules.ts +215 -0
  71. package/src/core/triage-shadow.ts +96 -0
  72. package/src/core/triage.ts +366 -0
  73. package/src/core/wrappers/bash.ts +112 -5
  74. package/src/gui.tsx +4761 -4533
  75. package/src/i18n.ts +32 -9
  76. package/src/index.ts +239 -4
  77. package/src/notifications.ts +16 -0
  78. package/src/rpc.ts +58 -0
  79. package/src/settings.ts +318 -0
  80. package/src/workspaces.ts +9 -4
package/dist/settings.js CHANGED
@@ -3,6 +3,8 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { PLUGIN_DIR } from "./types.js";
5
5
  import { DEFAULT_LOCALE, normalizeLocale, SUPPORTED_LOCALES, messageIn, t } from "./i18n.js";
6
+ /** Дни shadow-периода по умолчанию. */
7
+ export const DEFAULT_SHADOW_DAYS = 14;
6
8
  export const SETTINGS_FILE = path.join(PLUGIN_DIR, "settings.json");
7
9
  export const DEFAULT_MAX_CONCURRENT = 1;
8
10
  export const DEFAULT_WINTER_MODE = false;
@@ -143,6 +145,19 @@ export function defaultNotifications() {
143
145
  time: "09:00",
144
146
  lastSentAt: null,
145
147
  },
148
+ triage: {
149
+ mode: "off",
150
+ baseUrl: "http://127.0.0.1:11434",
151
+ model: "qwen3:4b",
152
+ timeoutMs: 45000,
153
+ fallback: "rules",
154
+ confidenceThreshold: 0.6,
155
+ shadow: {
156
+ enabled: true,
157
+ days: DEFAULT_SHADOW_DAYS,
158
+ startedAt: null,
159
+ },
160
+ },
146
161
  };
147
162
  }
148
163
  /** Приводит значение лимита к безопасному целому (>= 0). */
@@ -224,6 +239,160 @@ function localizedTemplate(value, key, fallback) {
224
239
  const builtin = SUPPORTED_LOCALES.some((locale) => messageIn(locale, key) === raw);
225
240
  return builtin ? t(key) : raw;
226
241
  }
242
+ /** Приводит режим триажа к допустимому значению. */
243
+ function normalizeTriageMode(value, fallback) {
244
+ return value === "off" || value === "rules" || value === "llm" || value === "auto"
245
+ ? value
246
+ : fallback;
247
+ }
248
+ /** Приводит fallback триажа к допустимому значению. */
249
+ function normalizeTriageFallback(value, fallback) {
250
+ return value === "rules" || value === "skip" ? value : fallback;
251
+ }
252
+ /** Приводит порог уверенности к диапазону 0..1. */
253
+ function normalizeConfidence(value, fallback) {
254
+ const n = Number(value);
255
+ if (!Number.isFinite(n))
256
+ return fallback;
257
+ return Math.min(1, Math.max(0, n));
258
+ }
259
+ const TRIAGE_RULE_FIELDS = ["status", "task", "error", "cost"];
260
+ const TRIAGE_RULE_OPERATORS = [
261
+ "equals",
262
+ "contains",
263
+ "regex",
264
+ "gt",
265
+ "lt",
266
+ "gte",
267
+ "lte",
268
+ ];
269
+ const TRIAGE_RULE_CATEGORIES = [
270
+ "quality",
271
+ "timeout",
272
+ "permission",
273
+ "network",
274
+ "unknown",
275
+ ];
276
+ const TRIAGE_RULE_SEVERITIES = ["low", "medium", "high"];
277
+ /** Допустимые операторы для поля: текст сравнивается строками, cost — числами. */
278
+ function ruleOperatorAllowed(field, operator) {
279
+ return field === "cost"
280
+ ? operator !== "contains" && operator !== "regex"
281
+ : operator === "equals" || operator === "contains" || operator === "regex";
282
+ }
283
+ /** Нормализует одно правило; невалидное возвращает null (правило отбрасывается). */
284
+ function normalizeTriageRule(value) {
285
+ const raw = asRecord(value);
286
+ if (!raw)
287
+ return null;
288
+ const field = TRIAGE_RULE_FIELDS.includes(raw.field)
289
+ ? raw.field
290
+ : null;
291
+ const operator = TRIAGE_RULE_OPERATORS.includes(raw.operator)
292
+ ? raw.operator
293
+ : null;
294
+ if (!field || !operator || !ruleOperatorAllowed(field, operator))
295
+ return null;
296
+ let ruleValue;
297
+ if (field === "cost") {
298
+ const n = Number(raw.value);
299
+ if (!Number.isFinite(n) || n < 0)
300
+ return null;
301
+ ruleValue = n;
302
+ }
303
+ else {
304
+ if (typeof raw.value !== "string" || !raw.value.trim())
305
+ return null;
306
+ ruleValue = raw.value.trim().slice(0, 500);
307
+ }
308
+ if (operator === "regex") {
309
+ try {
310
+ new RegExp(String(ruleValue), "i");
311
+ }
312
+ catch {
313
+ return null;
314
+ }
315
+ }
316
+ const rule = { field, operator, value: ruleValue };
317
+ if (typeof raw.id === "string" && raw.id.trim())
318
+ rule.id = raw.id.trim().slice(0, 64);
319
+ if (TRIAGE_RULE_CATEGORIES.includes(raw.category)) {
320
+ rule.category = raw.category;
321
+ }
322
+ if (TRIAGE_RULE_SEVERITIES.includes(raw.severity)) {
323
+ rule.severity = raw.severity;
324
+ }
325
+ if (raw.confidence !== undefined)
326
+ rule.confidence = normalizeConfidence(raw.confidence, 0.8);
327
+ if (raw.action === "notify" || raw.action === "skip")
328
+ rule.action = raw.action;
329
+ if (typeof raw.reason === "string" && raw.reason.trim()) {
330
+ rule.reason = raw.reason.trim().slice(0, 300);
331
+ }
332
+ const priority = Number(raw.priority);
333
+ rule.priority = Number.isFinite(priority)
334
+ ? Math.min(10000, Math.max(-10000, Math.trunc(priority)))
335
+ : 0;
336
+ return rule;
337
+ }
338
+ /** Нормализует массив правил; undefined сохраняет встроенный набор. */
339
+ function normalizeTriageRules(value, fallback) {
340
+ if (value === undefined)
341
+ return fallback?.map((rule) => ({ ...rule }));
342
+ if (!Array.isArray(value))
343
+ return fallback?.map((rule) => ({ ...rule }));
344
+ return value
345
+ .slice(0, 200)
346
+ .map(normalizeTriageRule)
347
+ .filter((rule) => rule !== null);
348
+ }
349
+ /** Нормализует настройки shadow-режима триажа. */
350
+ function normalizeTriageShadow(value, fallback) {
351
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
352
+ return { ...fallback };
353
+ }
354
+ const raw = value;
355
+ return {
356
+ enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
357
+ days: normalizeIntInRange(raw.days, fallback.days, 1, 365),
358
+ startedAt: typeof raw.startedAt === "string" && raw.startedAt.trim()
359
+ ? raw.startedAt.trim()
360
+ : null,
361
+ };
362
+ }
363
+ /** Текущий shadow-период ещё активен? (ничего не меняет, только читает). */
364
+ export function isShadowActive(shadow) {
365
+ if (!shadow || !shadow.enabled || !shadow.startedAt)
366
+ return false;
367
+ const started = new Date(shadow.startedAt).getTime();
368
+ if (!Number.isFinite(started))
369
+ return false;
370
+ const now = Date.now();
371
+ const days = Number.isFinite(shadow.days) && shadow.days > 0 ? shadow.days : DEFAULT_SHADOW_DAYS;
372
+ return now - started < days * 24 * 60 * 60 * 1000;
373
+ }
374
+ /** Начать shadow-период, если ещё не Started. Возвращает нормализованные настройки shadow. */
375
+ export function startShadow(shadow) {
376
+ const nowIso = new Date().toISOString();
377
+ if (!shadow) {
378
+ return { enabled: true, days: DEFAULT_SHADOW_DAYS, startedAt: nowIso };
379
+ }
380
+ if (!shadow.startedAt) {
381
+ return { ...shadow, startedAt: nowIso };
382
+ }
383
+ return { ...shadow };
384
+ }
385
+ /**
386
+ * Настройки shadow после сохранения: включённый режим без даты старта
387
+ * получает текущий момент, выключенный — сбрасывает дату.
388
+ */
389
+ export function settleShadowOnSave(shadow) {
390
+ if (!shadow)
391
+ return startShadow(undefined);
392
+ if (!shadow.enabled)
393
+ return { ...shadow, startedAt: null };
394
+ return startShadow(shadow);
395
+ }
227
396
  /** Приводит настройки уведомлений к безопасному виду. */
228
397
  function normalizeNotifications(value, fallback) {
229
398
  const fallbackWebhook = fallback.webhook ?? defaultNotifications().webhook;
@@ -234,6 +403,8 @@ function normalizeNotifications(value, fallback) {
234
403
  const fallbackTelegram = fallback.telegram ?? defaultNotifications().telegram;
235
404
  const fallbackNative = fallback.native ?? defaultNotifications().native;
236
405
  const fallbackQuiet = fallback.quietHours ?? defaultNotifications().quietHours;
406
+ const fallbackTriage = fallback.triage ?? defaultNotifications().triage;
407
+ const fallbackShadow = fallbackTriage.shadow ?? defaultNotifications().triage.shadow;
237
408
  const raw = asRecord(value);
238
409
  if (!raw) {
239
410
  return {
@@ -249,6 +420,11 @@ function normalizeNotifications(value, fallback) {
249
420
  telegram: { ...fallbackTelegram },
250
421
  native: { ...fallbackNative },
251
422
  quietHours: { ...fallbackQuiet },
423
+ triage: {
424
+ ...fallbackTriage,
425
+ rules: fallbackTriage.rules?.map((rule) => ({ ...rule })),
426
+ shadow: { ...fallbackShadow },
427
+ },
252
428
  dashboardUrl: fallback.dashboardUrl ?? "",
253
429
  };
254
430
  }
@@ -260,12 +436,17 @@ function normalizeNotifications(value, fallback) {
260
436
  const rawTelegram = asRecord(raw.telegram);
261
437
  const rawNative = asRecord(raw.native);
262
438
  const rawQuiet = asRecord(raw.quietHours);
439
+ const rawTriage = asRecord(raw.triage);
263
440
  const frequency = rawDigest?.frequency === "weekly" || rawDigest?.frequency === "daily"
264
441
  ? rawDigest.frequency
265
442
  : fallbackDigest.frequency;
266
443
  const lastSentAt = typeof rawDigest?.lastSentAt === "string" && rawDigest.lastSentAt.trim()
267
444
  ? rawDigest.lastSentAt.trim()
268
445
  : null;
446
+ // `rules` отсутствует, если используется встроенный набор. Ключ с явным
447
+ // `undefined` нельзя отдавать по RPC: JSON-схема превращает неописанные
448
+ // поля в Schema.Json, которая отвергает undefined ("Expected JSON value").
449
+ const triageRules = normalizeTriageRules(rawTriage?.rules, fallbackTriage.rules);
269
450
  return {
270
451
  enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
271
452
  onlyOnError: typeof raw.onlyOnError === "boolean" ? raw.onlyOnError : fallback.onlyOnError,
@@ -350,6 +531,18 @@ function normalizeNotifications(value, fallback) {
350
531
  time: normalizeDailyTime(rawDigest?.time, fallbackDigest.time),
351
532
  lastSentAt,
352
533
  },
534
+ triage: {
535
+ mode: normalizeTriageMode(rawTriage?.mode, fallbackTriage.mode),
536
+ baseUrl: normalizeHttpBase(rawTriage?.baseUrl, fallbackTriage.baseUrl),
537
+ model: typeof rawTriage?.model === "string" && rawTriage.model.trim()
538
+ ? rawTriage.model.trim().slice(0, 200)
539
+ : fallbackTriage.model,
540
+ timeoutMs: normalizeIntInRange(rawTriage?.timeoutMs, fallbackTriage.timeoutMs, 1000, 120000),
541
+ fallback: normalizeTriageFallback(rawTriage?.fallback, fallbackTriage.fallback),
542
+ confidenceThreshold: normalizeConfidence(rawTriage?.confidenceThreshold, fallbackTriage.confidenceThreshold),
543
+ ...(triageRules !== undefined ? { rules: triageRules } : {}),
544
+ shadow: normalizeTriageShadow(rawTriage?.shadow, fallbackShadow),
545
+ },
353
546
  };
354
547
  }
355
548
  /** Приводит настройки интеграций к безопасному виду. */
@@ -445,6 +638,12 @@ export async function saveSettings(patch) {
445
638
  next.integrations.hooks.secret = generated.secret;
446
639
  }
447
640
  }
641
+ // Удобство: включённый shadow-режим без даты старта стартует при первом сохранении.
642
+ // Иначе shadow не логировал бы решения, а триаж реально подавлял бы уведомления.
643
+ const triage = next.notifications.triage;
644
+ if (triage) {
645
+ triage.shadow = settleShadowOnSave(triage.shadow);
646
+ }
448
647
  await fs.mkdir(PLUGIN_DIR, { recursive: true });
449
648
  await fs.writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2), "utf8");
450
649
  return next;
@@ -54,7 +54,7 @@ export declare function readWorkspaceEnvFile(envFile?: string): Record<string, s
54
54
  * зашифрованного хранилища (Спринт 26); отсутствующий секрет даёт пустую
55
55
  * строку и предупреждение с именем — без значения. Никогда не бросает.
56
56
  */
57
- export declare function resolveWorkspaceEnv(workspace: Workspace | undefined): Record<string, string>;
57
+ export declare function resolveWorkspaceEnv(workspace: Workspace | undefined, allowedSecretNames?: string[]): Record<string, string>;
58
58
  /** Маскирует значение секрета для логов. */
59
59
  export declare function maskSecretValue(): string;
60
60
  /**
@@ -74,7 +74,7 @@ export declare function workspaceEnvDir(pluginDir: string): string;
74
74
  * Возвращает путь к файлу или undefined, если у workspace нет переменных.
75
75
  * Пустой env удаляет ранее созданный файл. На POSIX права 0600.
76
76
  */
77
- export declare function writeWorkspaceEnvFile(workspace: Workspace | undefined, pluginDir: string, sanitizedName: string): string | undefined;
77
+ export declare function writeWorkspaceEnvFile(workspace: Workspace | undefined, pluginDir: string, sanitizedName: string, allowedSecretNames?: string[]): string | undefined;
78
78
  /** Проверяет, что путь существует и является директорией. */
79
79
  export declare function validateWorkspacePath(workspacePath: string): void;
80
80
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"workspaces.d.ts","sourceRoot":"","sources":["../src/workspaces.ts"],"names":[],"mappings":"AAQA;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wEAAwE;IACxE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CA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AgB,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAI9D;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAM/E;AAED,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,KAAK,EAAE,iBAAiB,GAAG,SAAS,CA2ChE;AAED,yCAAyC;AACzC,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,oBAAoB,GAAG,SAAS,CAgElF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAenD;AAED,kDAAkD;AAClD,wBAAgB,eAAe,IAAI,MAAM,CAGxC"}
@@ -93,14 +93,14 @@ export function readWorkspaceEnvFile(envFile) {
93
93
  * зашифрованного хранилища (Спринт 26); отсутствующий секрет даёт пустую
94
94
  * строку и предупреждение с именем — без значения. Никогда не бросает.
95
95
  */
96
- export function resolveWorkspaceEnv(workspace) {
96
+ export function resolveWorkspaceEnv(workspace, allowedSecretNames) {
97
97
  if (!workspace)
98
98
  return {};
99
99
  const merged = {
100
100
  ...readWorkspaceEnvFile(workspace.envFile),
101
101
  ...(workspace.env ?? {}),
102
102
  };
103
- const resolved = resolveSecretRefs(merged);
103
+ const resolved = resolveSecretRefs(merged, allowedSecretNames);
104
104
  if (resolved.missing.length > 0) {
105
105
  console.warn(`[workspace] "${workspace.name}": не найдены секреты: ${resolved.missing.join(", ")}`);
106
106
  }
@@ -143,9 +143,11 @@ export function workspaceEnvDir(pluginDir) {
143
143
  * Возвращает путь к файлу или undefined, если у workspace нет переменных.
144
144
  * Пустой env удаляет ранее созданный файл. На POSIX права 0600.
145
145
  */
146
- export function writeWorkspaceEnvFile(workspace, pluginDir, sanitizedName) {
146
+ export function writeWorkspaceEnvFile(workspace, pluginDir, sanitizedName, allowedSecretNames) {
147
+ if (!workspace)
148
+ return undefined;
147
149
  const file = join(workspaceEnvDir(pluginDir), `${sanitizedName}.env`);
148
- const env = resolveWorkspaceEnv(workspace);
150
+ const env = resolveWorkspaceEnv(workspace, allowedSecretNames);
149
151
  const keys = Object.keys(env);
150
152
  if (!keys.length) {
151
153
  try {
@@ -33,15 +33,16 @@ model, the modules, the data model and the extension points.
33
33
  The wrapper reports the result back to the database, not to the plugin host.
34
34
  4. **One source of truth for definitions is SQLite.** OS entries are derived artifacts:
35
35
  they can always be recreated from the database with export/import.
36
- 5. **Local first.** No network services, no telemetry, no accounts. The dashboard binds
37
- to localhost only.
36
+ 5. **Local first.** No network services, no telemetry, no accounts by default. The dashboard binds
37
+ to localhost only. Local AI triage (Ollama) is optional and connects only when explicitly enabled
38
+ via `manage_local_ai`.
38
39
 
39
40
  ## Process model
40
41
 
41
42
  ```
42
43
  ┌─────────────────────────────┐
43
44
  │ OpenCode (plugin host) │
44
- │ • agent tools (12) │
45
+ │ • agent tools (25) │
45
46
  │ • sidebar GUI (gui.tsx) │
46
47
  │ • RPC ↔ sidebar │
47
48
  │ • dashboard HTTP server │
@@ -121,7 +122,7 @@ from their clones instead of their own last run.
121
122
 
122
123
  | Path | Role |
123
124
  | --- | --- |
124
- | `src/index.ts` | Plugin lifecycle, 24 agent tools, RPC handlers, task CRUD, view assembly |
125
+ | `src/index.ts` | Plugin lifecycle, 25 agent tools, RPC handlers, task CRUD, view assembly |
125
126
  | `src/rpc.ts` | JSON-schema contracts for every RPC method |
126
127
  | `src/gui.tsx` | OpenCode sidebar panel (SolidJS, built to `gui-experimental.cjs`) |
127
128
  | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
@@ -130,7 +131,7 @@ from their clones instead of their own last run.
130
131
  | `src/profiles.ts` | Profile directory resolution: per-profile plugin dir (base for `default`, `<base>/profiles/<name>` for named profiles); profile name, marker, port, create/delete/switch |
131
132
  | `src/workspaces.ts` | Workspace registry and path validation; env pairs and `.env` file resolution with secret masking |
132
133
  | `src/templates.ts` | Reusable task templates |
133
- | `src/settings.ts` | Plugin settings: notifications, history retention, audit, interface locale |
134
+ | `src/settings.ts` | Plugin settings: notifications, history retention, audit, interface locale, local AI/triage |
134
135
  | `src/i18n.ts` | Interface locale (`ru` default, `en`), JSON catalogs in `locales/`, ICU subset (`{param}`, `plural`) via built-in `Intl`, fallback to `ru` |
135
136
  | `src/notifications.ts` | Multi-channel delivery (webhook, Telegram, native OS) with retries/backoff, templates, task filters, quiet hours, matrix and stuck-clone notifications, daily/weekly digest |
136
137
  | `src/core/telegram.ts` | Telegram Bot API `sendMessage`: parse-mode escaping, dashboard link, token validation and masking |
@@ -149,6 +150,7 @@ from their clones instead of their own last run.
149
150
  | `src/core/dry-run.ts` | Pipeline simulation (no execution) |
150
151
  | `src/core/lock.ts` | Single-instance lock manager |
151
152
  | `src/core/file-watcher.ts` | chokidar-based file triggers |
153
+ | `src/core/local-ai.ts` | Local AI triage: LLM classifier with rules fallback, shadow mode, fail-open, manage_local_ai backing |
152
154
  | `src/core/cron-to-schtasks.ts` | Cron → Task Scheduler translation |
153
155
  | `src/core/schedule-v2.ts` | Extended cron parser/matcher, timezone math, launch windows, poll-mode decisions |
154
156
  | `src/core/schedule-gate.ts` | Wrapper-side gate: cron re-check (poll mode), window postpone, defer-file |
@@ -311,9 +313,9 @@ never requires a manual migration.
311
313
 
312
314
  | Interface | Audience | Entry point |
313
315
  | --- | --- | --- |
314
- | Agent tools | AI agent | 24 tools registered via `ctx.tool.transform` |
316
+ | Agent tools | AI agent | 25 tools registered via `ctx.tool.transform` |
315
317
  | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
316
- | RPC | Sidebar GUI | `src/rpc.ts` contracts, ~30 methods |
318
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, 44 methods |
317
319
  | Sidebar GUI | Human | `gui-experimental.cjs` |
318
320
  | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
319
321
 
@@ -355,9 +357,23 @@ Rules:
355
357
  - The dashboard has **no authentication** and binds to localhost. Do not expose it.
356
358
  - A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
357
359
  with your user privileges. Treat task creation like granting shell access.
358
- - `allowedTools` / `deniedTools` are **metadata passed to the run**, not a sandbox.
359
- They are recorded in history for audit, but they do not constrain `opencode` at the
360
- OS level.
360
+ - `allowedTools` / `deniedTools` are **enforced at the run-wrapper level** (спринт 29.2).
361
+ Before each `opencode run`, the wrapper passes `permissions` rules through
362
+ `OPENCODE_CONFIG_CONTENT`: `deniedTools` are mapped to `effect: "deny"` for the
363
+ corresponding OpenCode action (`shell`, `edit`, `glob`, `grep`, `webfetch`,
364
+ `websearch`, `question`, `subagent`, `skill`), and `allowedTools` (if specified)
365
+ additionally denies every action not in the list. No config file is written, so a
366
+ project-level `opencode.jsonc` is preserved and parallel tasks in one workdir do not
367
+ race. The wrapper passes `--auto` so non-denied permissions are auto-approved.
368
+ `allowedTools`/`deniedTools` metadata is still recorded in history for audit.
369
+ - **Audit of blocked tools (спринт 29.4):** when a task definition is saved,
370
+ `recordTaskToolBlocks()` writes one `tool.blocked` audit event per entry in
371
+ `deniedTools` (`target` = task name, `details.tool` = tool, plus `allowedTools`,
372
+ `deniedTools` and `reason`). In allow-list mode one event with `tool: "*"` records
373
+ that every unlisted tool is denied. The event is emitted on create and on update, so
374
+ changing the task policy also changes the audited details. Because the wrapper runs
375
+ `opencode` as an external process, the plugin cannot observe individual blocked
376
+ attempts at runtime; the audit reflects the enforced policy, not each refusal.
361
377
  - Task prompts, hooks and Quality Gate scripts are **plain text** executed with your
362
378
  user privileges; only secrets (in `secrets.json`, AES-256-GCM) are encrypted.
363
379
  Workspace `env` can reference secrets as `${secret:NAME}`; values are masked in
@@ -369,6 +385,49 @@ Rules:
369
385
  - Workspace paths are validated, but hooks are not sandboxed: only schedule jobs from
370
386
  repositories you trust.
371
387
 
388
+ ### Permission model
389
+
390
+ The effective policy is resolved in this order (later wins):
391
+
392
+ 1. Task `allowedTools` — if present, every action not listed is denied.
393
+ 2. Task `deniedTools` — always denied and takes priority over `allowedTools`.
394
+ 3. The generated `opencode.jsonc` — written into the task workdir for the run.
395
+ 4. Project `opencode.json(c)` and system config — merged by OpenCode; a closer or
396
+ system-level config can weaken task-scoped denies (see limitations below).
397
+ 5. `--auto` — auto-approves everything that remains, so no interactive prompts block
398
+ an unattended run.
399
+
400
+ Tool mapping used by both wrappers:
401
+
402
+ | Task tool | OpenCode action |
403
+ | --- | --- |
404
+ | `bash`, `shell` | `shell` |
405
+ | `write`, `edit`, `apply_patch`, `remove` | `edit` |
406
+ | `glob`, `grep`, `webfetch`, `websearch` | same name |
407
+ | `question`, `subagent`, `skill` | same name |
408
+
409
+ Hooks, Quality Gates and wrapper scripts are outside this model: they run before or
410
+ after the agent with the user's privileges and are not filtered by tool policy.
411
+
412
+ ### Permission enforcement — known limitations (spike 29.1 findings)
413
+
414
+ - `opencode run` CLI (v2.2.3) supports only `--auto` (auto-approve non-denied
415
+ permissions). There are **no** `--allow-tool` / `--deny-tool` CLI flags, so
416
+ per-task restrictions cannot be passed via arguments. Enforcement is done by
417
+ generating a task-scoped config and passing it through `OPENCODE_CONFIG_CONTENT`.
418
+ - OpenCode merges `opencode.json(c)` from the current directory up to the filesystem
419
+ root. A project-level `opencode.jsonc` with permissive rules can override or weaken
420
+ task-scoped denies (last matching rule wins, closer directory wins for merge).
421
+ System config (`/etc/opencode`, `%ProgramData%\opencode`) overrides project config.
422
+ - Nested agent calls (subagents) use their **own** permissions, not a subset of the
423
+ parent's. A task that denies `subagent` prevents launching subagents, but a launched
424
+ subagent is not further restricted by the parent task's policy.
425
+ - **Plan B**: if the task-scoped config passed via `OPENCODE_CONFIG_CONTENT` proves
426
+ insufficient, enforcement can be moved to wrapper-level tool filtering (intercepting
427
+ `opencode run` invocation and refusing to start when a denied tool would be needed)
428
+ or to a managed system-level `policies` entry that hard-denies specific tools
429
+ globally.
430
+
372
431
  ## Extension points
373
432
 
374
433
  | Goal | Where to start |
package/docs/FEATURES.md CHANGED
@@ -251,9 +251,17 @@ the scheduler entry.
251
251
 
252
252
  ### Tool restrictions
253
253
 
254
- `allowedTools` and `deniedTools` declare the intended role of the job. They are
255
- recorded in history for audit. They are **metadata, not a sandbox**: they do not
256
- restrict `opencode` at runtime today.
254
+ `allowedTools` and `deniedTools` are enforced for the `opencode run` process that the
255
+ task wrapper starts. The wrapper passes the generated `permissions` rules to the
256
+ process through `OPENCODE_CONFIG_CONTENT`; no file is written to the task workdir, so a
257
+ project-level `opencode.jsonc` is never overwritten. Each `deniedTools` entry becomes an
258
+ `effect: "deny"` rule for the matching OpenCode action, and `allowedTools` (when set)
259
+ denies every action that is not listed. The wrapper runs `opencode` with `--auto`, so
260
+ only non-denied permissions are auto-approved. Restrictions apply to the agent process,
261
+ not to hooks, Quality Gates or scripts, which still run with your user privileges. See
262
+ [ARCHITECTURE.md](ARCHITECTURE.md#permission-enforcement--known-limitations-spike-291-findings)
263
+ for the exact action mapping and known limitations (project/system config, nested
264
+ subagents).
257
265
 
258
266
  ## Orchestration
259
267
 
@@ -549,10 +557,10 @@ the `cleanup_history` RPC and the GUI's «Очистить сейчас» button
549
557
 
550
558
  ## Agent interface
551
559
 
552
- Twenty-four tools: `schedule_task`, `list_tasks`, `update_task`, `delete_task`,
560
+ Twenty-five tools: `schedule_task`, `list_tasks`, `update_task`, `delete_task`,
553
561
  `run_task_now`, `pause_task`, `resume_task`, `get_history`, `get_task_logs`, `dry_run`,
554
562
  `manage_workspaces`, `matrix_control` (results/cancel/cleanup/preview), `get_metrics`,
555
- `get_analytics`, `manage_settings`, `manage_templates`, `manage_profiles`,
563
+ `get_analytics`, `manage_settings`, `manage_local_ai`, `manage_templates`, `manage_profiles`,
556
564
  `transfer_tasks`, `send_notification`, `get_dashboard_info`, `cleanup_history`,
557
565
  `manage_secrets`, `get_audit_log`,
558
566
  `emit_event`.
@@ -562,6 +570,26 @@ least privilege, Quality Gates, timeout, matrix concurrency, DAG rules and a
562
570
  create → dry-run → run-now → inspect loop. It is registered automatically by the
563
571
  plugin, no installation step required.
564
572
 
573
+ The `manage_local_ai` tool reads, updates and tests the local triage settings
574
+ (`action: "get" | "update" | "test"`); see [LOCAL-AI.md](LOCAL-AI.md).
575
+
576
+ ## Local assistant (triage)
577
+
578
+ An optional offline model classifies failed and partial runs to decide whether a
579
+ notification is worth sending. It is opt-in and fail-open: without a model the
580
+ rules engine or direct delivery takes over, and notifications are never blocked.
581
+ It never changes run status, retries, Quality Gates, DAG dependencies or history.
582
+
583
+ - `mode`: `off` (default), `rules`, `llm` or `auto` (model, then rules).
584
+ - `fallback`: `rules` (default) or `skip` when the model fails or is unsure.
585
+ - `confidenceThreshold`: minimum model confidence (0..1).
586
+ - Shadow mode logs decisions without suppressing notifications, so triage can be
587
+ evaluated safely before it is enforced.
588
+
589
+ Setup, model tiers by RAM, the `npm run bench:local` benchmark, shadow workflow
590
+ and troubleshooting (including `OLLAMA_CONTEXT_LENGTH`) are documented in
591
+ [LOCAL-AI.md](LOCAL-AI.md).
592
+
565
593
  ## Platform support
566
594
 
567
595
  | Capability | Windows | Linux | macOS |
@@ -585,7 +613,9 @@ plugin, no installation step required.
585
613
  - **No authentication on the dashboard.** Localhost only by design.
586
614
  - **Secrets are not encrypted.** Use environment variables or an external secret
587
615
  manager.
588
- - **`allowedTools` / `deniedTools` are advisory.** They document intent and are
589
- recorded in history; enforcement is not implemented.
616
+ - **`allowedTools` / `deniedTools` restrict the agent process, not the whole job.**
617
+ Hooks, Quality Gates and wrapper scripts still run with your user privileges, and a
618
+ project-level or system `opencode.jsonc` can weaken task-scoped denies. See the
619
+ permission-enforcement limitations in ARCHITECTURE.md.
590
620
  - **Matrix clones are separate tasks.** They appear in the task list (grouped under the
591
621
  parent) and consume global concurrency slots like any other run.