opencode-windows-scheduler 1.5.4 → 1.5.5
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 +65 -5
- package/CROSS_PLATFORM.md +107 -71
- package/README.md +72 -25
- package/ROADMAP-STRATEGY.md +6 -0
- package/ROADMAP.md +116 -85
- package/dist/core/analytics.d.ts +3 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +4 -0
- package/dist/core/audit.d.ts +2 -1
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +32 -1
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +21 -4
- package/dist/core/file-watcher.d.ts.map +1 -1
- package/dist/core/file-watcher.js +16 -1
- package/dist/core/git-trigger.d.ts +4 -2
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +34 -16
- package/dist/core/lock.d.ts +14 -0
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +81 -4
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +3 -2
- package/dist/core/native-notify.d.ts.map +1 -1
- package/dist/core/native-notify.js +3 -0
- package/dist/core/one-shot.d.ts +7 -1
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +15 -2
- package/dist/core/permissions.d.ts +69 -0
- package/dist/core/permissions.d.ts.map +1 -0
- package/dist/core/permissions.js +143 -0
- package/dist/core/ps-wrapper.d.ts +9 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +293 -96
- package/dist/core/record-history.d.ts +11 -0
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +106 -4
- package/dist/core/savings.d.ts +70 -0
- package/dist/core/savings.d.ts.map +1 -0
- package/dist/core/savings.js +87 -0
- package/dist/core/schedule-gate.js +7 -3
- package/dist/core/schedule-v2.js +1 -1
- package/dist/core/scheduler/index.d.ts +13 -1
- package/dist/core/scheduler/index.d.ts.map +1 -1
- package/dist/core/scheduler/index.js +35 -4
- package/dist/core/scheduler/linux.d.ts +4 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +53 -20
- package/dist/core/scheduler/mac.d.ts +2 -1
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +24 -6
- package/dist/core/scheduler/posix.d.ts +1 -1
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +2 -2
- package/dist/core/scheduler/registry.d.ts +3 -2
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/registry.js +6 -5
- package/dist/core/scheduler/windows.d.ts +49 -1
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +219 -34
- package/dist/core/secrets.d.ts +5 -3
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +86 -8
- package/dist/core/self-analysis.d.ts +117 -0
- package/dist/core/self-analysis.d.ts.map +1 -0
- package/dist/core/self-analysis.js +539 -0
- package/dist/core/session.d.ts +11 -3
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +34 -5
- package/dist/core/shutdown.d.ts +26 -0
- package/dist/core/shutdown.d.ts.map +1 -0
- package/dist/core/shutdown.js +49 -0
- package/dist/core/summary.d.ts +69 -0
- package/dist/core/summary.d.ts.map +1 -0
- package/dist/core/summary.js +250 -0
- package/dist/core/telegram.d.ts +10 -0
- package/dist/core/telegram.d.ts.map +1 -1
- package/dist/core/telegram.js +228 -47
- package/dist/core/triage-chain.d.ts +9 -3
- package/dist/core/triage-chain.d.ts.map +1 -1
- package/dist/core/triage-chain.js +15 -5
- package/dist/core/triage-compare.d.ts +68 -0
- package/dist/core/triage-compare.d.ts.map +1 -0
- package/dist/core/triage-compare.js +184 -0
- package/dist/core/triage-rules.d.ts.map +1 -1
- package/dist/core/triage-rules.js +22 -0
- package/dist/core/triage-shadow.d.ts +54 -10
- package/dist/core/triage-shadow.d.ts.map +1 -1
- package/dist/core/triage-shadow.js +138 -26
- package/dist/core/triage-worker.d.ts +55 -0
- package/dist/core/triage-worker.d.ts.map +1 -0
- package/dist/core/triage-worker.js +314 -0
- package/dist/core/triage.js +1 -1
- package/dist/core/watch-paths.d.ts +6 -0
- package/dist/core/watch-paths.d.ts.map +1 -0
- package/dist/core/watch-paths.js +62 -0
- package/dist/core/wrappers/bash.d.ts +15 -3
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +153 -120
- package/dist/db/history-repo.d.ts +1 -1
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +29 -14
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +31 -0
- package/dist/history.d.ts +2 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +3 -3
- package/dist/i18n.d.ts +25 -2
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +41 -3
- package/dist/index.d.ts +40 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +345 -71
- package/dist/integrations.d.ts +9 -1
- package/dist/integrations.d.ts.map +1 -1
- package/dist/integrations.js +34 -6
- package/dist/notifications.d.ts +30 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +287 -16
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +21 -3
- package/dist/rpc.d.ts +145 -8
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +81 -6
- package/dist/server.d.ts +20 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +136 -14
- package/dist/settings.d.ts +89 -5
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +143 -23
- package/dist/task-transfer.d.ts +8 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +2 -2
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +23 -5
- package/dist/workspaces.d.ts +9 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +25 -0
- package/docs/ARCHITECTURE.md +40 -22
- package/docs/CONCEPT.md +230 -0
- package/docs/CROSS_PLATFORM.ru.md +150 -0
- package/docs/CROSS_PLATFORM.zh.md +146 -0
- package/docs/FAQ.md +52 -0
- package/docs/FAQ.ru.md +53 -0
- package/docs/FAQ.zh.md +43 -0
- package/docs/FEATURES.md +125 -48
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +114 -16
- package/docs/README.ru.md +18 -13
- package/docs/README.zh.md +286 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/gui-experimental.cjs +8 -8
- package/locales/en.json +54 -1
- package/locales/ru.json +54 -1
- package/locales/zh.json +780 -0
- package/package.json +24 -7
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/test-locale.mjs +4 -3
- package/skills/scheduled-job-best-practices/SKILL.md +6 -3
- package/skills/scheduled-job-best-practices/references/recipes.md +1 -1
- package/src/core/analytics.ts +10 -0
- package/src/core/audit.ts +39 -1
- package/src/core/cron-to-schtasks.ts +23 -4
- package/src/core/file-watcher.ts +20 -1
- package/src/core/git-trigger.ts +34 -16
- package/src/core/lock.ts +88 -3
- package/src/core/matrix.ts +5 -1
- package/src/core/native-notify.ts +3 -0
- package/src/core/one-shot.ts +18 -2
- package/src/core/permissions.ts +200 -0
- package/src/core/ps-wrapper.ts +300 -96
- package/src/core/record-history.ts +111 -4
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +9 -3
- package/src/core/schedule-v2.ts +1 -1
- package/src/core/scheduler/index.ts +41 -3
- package/src/core/scheduler/linux.ts +67 -22
- package/src/core/scheduler/mac.ts +24 -7
- package/src/core/scheduler/posix.ts +2 -2
- package/src/core/scheduler/registry.ts +7 -5
- package/src/core/scheduler/windows.ts +237 -32
- package/src/core/secrets.ts +101 -7
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +40 -5
- package/src/core/shutdown.ts +69 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +266 -55
- package/src/core/triage-chain.ts +15 -6
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +23 -0
- package/src/core/triage-shadow.ts +176 -32
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +1 -1
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +181 -138
- package/src/db/history-repo.ts +31 -18
- package/src/db/schema.ts +31 -0
- package/src/gui.tsx +5070 -4761
- package/src/history.ts +7 -3
- package/src/i18n.ts +55 -4
- package/src/index.ts +432 -74
- package/src/integrations.ts +50 -6
- package/src/notifications.ts +465 -18
- package/src/profiles.ts +21 -3
- package/src/rpc.ts +86 -6
- package/src/server.ts +135 -16
- package/src/settings.ts +305 -46
- package/src/task-transfer.ts +10 -3
- package/src/types.ts +24 -5
- package/src/workspaces.ts +22 -0
- package/dist/gui-experimental.cjs +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,15 +6,75 @@ All notable changes to this project are documented here. Format follows [Keep a
|
|
|
6
6
|
|
|
7
7
|
### Added
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
- **Интерфейс на китайском (`locales/zh.json`):** полный перевод всех 772 ключей интерфейса (`gui.*`, `matrix.*`, `shadow.*`, `schedule.*`, `notify.*`, `tool.*`, `localAi.*`, `server.*`, `gitTrigger.*`, `dryRun.*`, `app.*`, `common.*`) с паритетом ключей и плейсхолдеров к `en.json`/`ru.json`; вместе с 5 ключами селектора языка — 777. Поддерживается через `locale: "zh"` в `manage_settings` и переключатель в шапке панели. GUI-бандл регистрирует каталог через `registerCatalog("zh", ...)`.
|
|
10
|
+
- **Режим языка `auto` (T7):** `locale: "auto"` следует за языком интерфейса OpenCode. GUI читает `ctx.locale.locale()`, маппит BCP 47 (`zh-CN`/`zh-Hans` → `zh`, `en-GB` → `en`, `ru-RU` → `ru`) и переключает панель без перезапуска; селектор языка (🌐 Авто / Русский / English / 中文) появился в шапке панели. Серверный процесс языка окна не видит, поэтому GUI присылает разрешённую локаль в новом поле `uiLocale` — уведомления, дайджест, результаты инструментов и дашборд используют её. Старые настройки `ru`/`en` читаются без миграции.
|
|
10
11
|
|
|
11
12
|
### Fixed
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
- **Ротация reuse-сессий (session.ts):** после `session delete` больше не сбрасывается `sessionId` в `undefined`. Генерируется новый `sessionId`, сохраняется в БД и в sidecar-файл `<task>.session` рядом с оболочкой; bash- и PowerShell-обёртки читают актуальный ID из sidecar перед запуском `opencode run --session`.
|
|
15
|
+
- **`get_history` RPC и агент:** фильтрация по задаче и статусу перенесена из JS в SQLite через `getHistory(taskName, limit, status)`. История конкретной задачи больше не обрезается последними 200 глобальными запусками (`loadHistory` принимает `taskName`/`limit`/`status`, жёсткий лимит 200 убран из логики фильтрации).
|
|
16
|
+
- **`schedule-gate`:** при `active === false` и `nextOpenAt === null` возвращается `3` (skip) вместо `0` (разрешить). Задача вне окна без вычисленного времени открытия больше не запускается ошибочно.
|
|
17
|
+
- **`candidatesOnDay` (schedule-v2.ts):** `notBefore` проверяется независимо от `notAfter` (ранее применялся только если заданы оба).
|
|
18
|
+
- **`sessionMaxRuns`:** явный `0` теперь снимает лимит (Zod `.min(0)`, проверка `< 0` вместо `< 1`), соответствует документации «Unset/0 — no limit».
|
|
19
|
+
- **Telegram:** при HTTP 400 «can't parse entities» добавлен `console.warn` с очищенным описанием ошибки перед откатом на plain text.
|
|
20
|
+
- **normalizeTriageRule:** регулярные выражения компилируются с флагом `iu` (unicode) вместо `i`.
|
|
21
|
+
- **Matrix:** при коллизии имён клонов выбрасывается ошибка `matrix.error.duplicateCloneName` вместо молчаливого пропуска; ключ добавлен в `locales/ru.json`, `locales/en.json`, `locales/zh.json`.
|
|
22
|
+
- **ScheduleJobArgs:** латинский regex имени заменён на `superRefine` с общим `validateTaskName` — кириллица разрешена, схема и фактическая валидация приведены к одному правилу.
|
|
23
|
+
- **update_task:** при смене регистра имени задачи ссылки в `dependsOn`/`nextTaskOnSuccess`/`nextTaskOnError` других задач обновляются на новое имя (case-insensitive поиск и замена).
|
|
24
|
+
|
|
25
|
+
## [1.5.5] - 2026-11-16
|
|
26
|
+
|
|
27
|
+
### Security
|
|
28
|
+
|
|
29
|
+
- **Политика прав задач (`permissions.ts`):** вместо разрозненных `defaultPermissions` в обёртках появился единый резолвер `src/core/permissions.ts`, а в настройках — `permissions.defaultPolicy` (`hybrid` по умолчанию, `secure`, `legacy`). `hybrid` разрешает read/edit/glob/grep/subagent/skill/webfetch/websearch и **запрещает `shell` и `question`**: задачи идут с `opencode run --auto`, поэтому команды включаются только явным `allowedTools`, флагом задачи `legacyShell` (действует только в `hybrid`) или политикой `legacy`, возвращающей поведение 1.5.x. `secure` оставляет только read/glob/grep/skill. `deniedTools` выигрывает всегда, непустой `allowedTools` превращается в allowlist и может вернуть действие, запрещённое политикой. Конфиг передаётся обёрткам через `OPENCODE_CONFIG_CONTENT`, `opencode.jsonc` не создаётся; отказы политики пишутся в аудит как `tool.blocked` с `reason: "default-policy"`, а обёртки логируют `policy=…, denied=…`. `test-permissions-policy.mjs` — 28 проверок.
|
|
30
|
+
- **Дашборд: `X-Scheduler-Client` больше не обходит проверку Origin (server.ts):** `isDashboardRequestTrusted` проверяет `Origin` первым, кастомный заголовок стал лишь дополнительным подтверждением, поэтому подделанный `X-Scheduler-Client: dashboard` с чужого Origin (ошибка CORS, XSS на странице дашборда) больше не открывает `/api/*`. Запросы без `Origin` по-прежнему требуют локальный `Host`, `Origin: null` и чужие схемы отклоняются. `test-dashboard-trust.mjs` — 10 проверок.
|
|
31
|
+
- **ACL ключа секретов на Windows (secrets.ts):** `icacls <файл> /inheritance:r /grant:r <пользователь>:F` — `secrets.key` больше не наследует права каталога и доступен только текущей учётной записи (`DOMAIN\user`); при чтении старый ключ получает ACL повторно, то есть ключи, созданные до 1.5.5, мигрируют автоматически. Сбой `icacls` не ломает работу, но один раз пишется в лог. `test-secrets.mjs` — 45 проверок, включая фактические ACE файла.
|
|
32
|
+
- **Path traversal в обёртках (ps-wrapper.ts):** `sanitizeName` вызывается внутри `writePromptFile` и `lockFilePath`, а не только на входе инструментов, поэтому имена вида `../../evil`, `..\..\evil`, `/etc/passwd`, `a/b/c` не выводят prompt и lock за пределы `PLUGIN_DIR`. `test-path-safety.mjs` — 13 проверок.
|
|
33
|
+
- **CSRF и DNS-rebinding (server.ts):** guard больше не полагается на `Host` при наличии `Origin` — cross-origin POST с `Origin: evil.com` отклоняется. Проверка распространена на все `/api/*` GET (кроме `/api/hooks`), поэтому rebinding больше не читает `/api/export-db`, историю, аудит и логи. Дашборд-клиент шлёт `X-Scheduler-Client: dashboard` во всех POST.
|
|
34
|
+
- **Подпись hook-запросов:** при `requireSignature` и ненулевом допуске времени `X-Scheduler-Timestamp` обязателен и входит в HMAC (`<timestamp>.<body>`), поэтому перехваченный запрос нельзя переиграть со свежим timestamp.
|
|
35
|
+
- **Секреты:** битый `secrets.json` карантинится в `secrets.json.corrupt-<ts>` вместо молчаливого затирания при следующей записи; отсутствующая ссылка `${secret:NAME}` остаётся литералом и попадает в `missing`.
|
|
36
|
+
- **Баш-обёртка:** промпт больше не передаётся через argv-массив с пустым `${arr[@]}` (bash 3.2); `log()` определён до первого вызова; watchdog убивает сам `opencode`, а не subshell; lock хранит PID и перехватывается только у мёртвого процесса; gate/hooks ограничены таймаутом.
|
|
37
|
+
- **Windows:** lock пишет PID, stale-порог передаётся параметром; Quality Gate и pre-flight получили таймаут; размер промпта проверяется до создания задачи; убраны отладочные `console.log` аргументов schtasks.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- **Дедуп по эмбеддингам:** исправлена инвертированная полярность (подавлялись именно важные статусы), вектор стал fixed-dimension feature hashing с L2-нормализацией, сравнение — только по одному task+status с историей векторов, а не `INSERT OR REPLACE`.
|
|
42
|
+
- **Счётчик дедупа** обновляется в транзакции `BEGIN IMMEDIATE` — гонка между процессами устранена.
|
|
43
|
+
- **Git-триггер:** ошибка `git diff` больше не выглядит как «изменений нет» (статус `error`, состояние не продвигается); glob-экранирование веток включает `[` и `]`.
|
|
44
|
+
- **Telegram:** сообщения делятся на чанки ≤4096 с учётом surrogate pairs, 429 обрабатывается с `retry_after`.
|
|
45
|
+
- **Linux:** расширенные cron-выражения уходят в минутный опрос с gate; ошибка чтения crontab больше не приводит к затиранию пользовательских заданий; блок crontab привязан к профилю.
|
|
46
|
+
- **schtasks:** код 1 больше не означает «задач нет»; pause/resume не глотают «задача не найдена»; добавлены локали-алиасы DE/FR/ES/IT/PL.
|
|
47
|
+
- **`*/N`:** преобразуется в schtasks только при `60 % N === 0`, иначе poll+gate; `previousRunTime` выравнивается по границе часа.
|
|
48
|
+
- **Триаж-воркер:** не более двух одновременных процессов, очередь дренируется освободившимся воркером, старые задания и слоты чистятся.
|
|
49
|
+
- **native-notify:** `notify-send` получает `--` перед текстом.
|
|
50
|
+
- **Документация:** синхронизированы числа инструментов/тестов/рецептов, Node ≥22.22, IANA-таймзоны; исправлено «ベンчмарк».
|
|
51
|
+
|
|
52
|
+
### Added
|
|
53
|
+
|
|
54
|
+
- **Счётчик «сэкономлено $» (Спринт 31.6):** `get_analytics` и дашборд показывают KPI «Сэкономлено» — контрфактику по истории: запуски, которые потратили токены, но не записали стоимость (локальная модель, подписка), оцениваются по эталонной облачной цене $0.01 за 1k токенов. Рядом стоят пометка «оценка» и ссылка на методику `docs/SAVINGS.md`; в отчёте появилось поле `report.savings` (`savedUsd`, `runs`, `tokens`, `byTask`). `test-savings.mjs` — 14 проверок на фиксированных данных.
|
|
55
|
+
- **Сравнение триажа «до/после» (Спринт 31.5):** RPC-метод `compare_triage` и модуль `src/core/triage-compare.ts` прогоняют одно событие под двумя наборами настроек и возвращают diff вердиктов, правил, уверенности и сообщений. `test-triage-compare.mjs` — 17 проверок.
|
|
56
|
+
|
|
57
|
+
- **Семантический дедуп по эмбеддингам (Спринт 31.1):** `notifications.embedding` (`enabled`, `suppressDuplicates`, `windowMinutes`, `threshold`, `maxVectors`) добавляет к точному дедупу сравнение похожести сообщений. Сообщение превращается в нормализованный bag-of-words вектор, векторы лежат в SQLite-таблице `notification_embeddings`, сравнение — косинусом брутфорсом по окну, без новых зависимостей и без внешней модели эмбеддингов. При совпадении выше `threshold` (по умолчанию 0.85) неважное уведомление подавляется; статусы из `importantStatuses` доставляются всегда. Старые векторы чистятся по `maxVectors`. `test-notifications-embedding.mjs` — 6 проверок.
|
|
58
|
+
- **Саммари уведомления в три строки (Спринт 31.3):** `notifications.summary` (`enabled`, `maxLines` 1..3, `maxCharsPerLine`, `timeoutMs`) просит локальную модель вернуть строгий JSON `{"lines": [...]}` и подставляет эти строки в Telegram/тост вместо шаблона. Любой отказ — нет провайдера, HTTP-ошибка, таймаут, битый JSON или несоответствие схеме — переключает на детерминированное усечение: задача и статус, текст ошибки, затем время, токены и стоимость. Саммари не блокирует и не теряет уведомление: доставка ждёт не дольше `timeoutMs` (по умолчанию 8 с). `test-notifications-summary.mjs` — 9 проверок.
|
|
59
|
+
- **Дедуп уведомлений со счётчиком повторов (Спринт 31.2):** `notifications.dedup` (`enabled`, `windowMinutes`, `suppressDuplicates`, `importantStatuses`, `maxCount`) группирует одинаковые пары «задача + статус» в окне времени. При `suppressDuplicates` неважные повторы подавляются, а статусы из `importantStatuses` (по умолчанию `error`, `timeout`) доставляются всегда и получают локализованный суффикс вида `(повтор 3)`. Счётчики хранятся в SQLite-таблице `notification_dedup`, поэтому переживают короткоживущие процессы `record-history`; окно истекло — счёт начинается заново. `test-notifications-dedup.mjs` — 14 проверок (первый запуск, подавление неважных повторов, важные повторы со счётчиком, `enabled=false`, `suppressDuplicates=false`).
|
|
60
|
+
- **Встроенные правила по стоимости и имени задачи (Спринт 31.9):** в `DEFAULT_TRIAGE_RULES` добавлены `cost-high` (стоимость запуска ≥ 1 USD, важность high) и `task-important` (deploy/release/publish/production/backup/restore/migration, high). Оба правила только уведомляют и не могут подавить доставку. В GUI появилась подсказка о покрытии встроенных правил и примере своего правила, в `docs/LOCAL-AI.md` — таблица всех девяти правил и JSON-пример с `skip` по имени задачи и порогом стоимости. `test-triage-rules.mjs` — 17 проверок.
|
|
61
|
+
- **Отдельная сюита настроек и строгая проверка OpenAI-провайдера (Спринт 31.12):** проверки триажа вынесены из `test-notifications-v2.mjs` в `test-settings.mjs` (12 проверок): дефолты, миграция старого `settings.json`, зажим enum-ов и чисел, legacy `skip → notify`, частичное сохранение и семантика `rules` (`undefined` — встроенные правила, `[]` — ни одного, свой массив заменяет встроенные). В `test-triage.mjs` ветка OpenAI-совместимого endpoint-а теперь проверяет strict-схему: `response_format.json_schema.strict`, имя `notification_triage`, обязательные поля и `additionalProperties: false`; битый JSON → fallback покрыт `test-triage-chain.mjs`.
|
|
62
|
+
- **Видимый статус подключения к провайдеру (Спринт 31.13):** в панели «Локальный ассистент» рядом с кнопкой проверки появился цветной индикатор: серый — связь не проверена, жёлтый — идёт проверка, зелёный — провайдер ответил валидным вердиктом, красный — нет связи/таймаут/ошибка модели, с текстом причины. Статус сбрасывается при изменении `mode`, `baseUrl` или `model`, поэтому старый зелёный не скрывает новый endpoint. Недоступная Ollama проверяется тестом `runLocalAiTest` (3 новые проверки в `test-local-ai.mjs`, всего 37).
|
|
63
|
+
- **Persistent-аудит решений триажа (Спринт 31.8):** каждое решение `rules`/`llm`/`auto` пишется в `audit_log` (`action: "triage.decision"`) с источником, `ruleId`, `failure`, уверенностью, латентностью, признаками `shadow`/`suppressed`, статусом и усечённым текстом ошибки (секреты маскируются). Shadow-отчёт читает журнал, поэтому переживает перезапуск `record-history` и больше не бывает пустым; `rpc.get_shadow_report` отдаёт последние 50 решений, `get_audit_log` — весь журнал. Сброс отчёта удаляет только shadow-записи. `test-triage-audit.mjs` — 27 проверок.
|
|
64
|
+
- **Асинхронный триаж (Спринт 31.7):** в режимах `llm`/`auto` `notifyTaskCompletion` больше не ждёт локальную модель: уведомление уходит сразу, а отдельный detached-процесс (`src/core/triage-worker.ts`) классифицирует событие и пишет вердикт в аудит с `async: true`. Задание передаётся через временный файл с замаскированной ошибкой; сбой запуска не влияет на доставку. В `rules` режим остаётся синхронным, потому что только правила подавляют уведомления; GUI предупреждает, что в `llm`/`auto` решение модели носит рекомендательный характер. `test-triage-async.mjs` — 32 проверки, включая реальный фоновый процесс.
|
|
65
|
+
- **Таймаут триажа 60 с (Спринт 31.10):** дефолтный `timeoutMs` поднят с 45 до 60 с — холодный старт Qwen3-4B в спайке занимал ~42 с и не укладывался в прежний лимит с запасом. В `llm`/`auto` таймаут относится только к фоновому запросу (31.7) и не задерживает уведомление; в `rules` сети нет. Обновлены дефолты настроек, GUI, `manage_local_ai`, документация и рецепт.
|
|
66
|
+
- **Документация на трёх языках:** английские `README.md` и `docs/` — основной источник. Добавлены китайские версии `docs/README.zh.md`, `docs/FEATURES.zh.md`, `docs/FAQ.zh.md`, `docs/SAVINGS.zh.md`, `docs/CROSS_PLATFORM.zh.md` и русские копии `docs/FAQ.ru.md`, `docs/SAVINGS.ru.md`, `docs/CROSS_PLATFORM.ru.md`; `docs/FAQ.md`, `docs/SAVINGS.md` и `CROSS_PLATFORM.md` переведены с русского на английский, в каждом файле есть строка `Translations:`. В README добавлен `docs/CONCEPT.md` — north-star концепция верифицируемой локально-первой оркестрации. Язык интерфейса по-прежнему `ru`/`en`: локали `locales/zh.json` нет.
|
|
67
|
+
|
|
68
|
+
### Fixed
|
|
69
|
+
|
|
70
|
+
- **Shadow-отчёт триажа всегда был пуст:** решения хранились в памяти процесса `record-history`, который завершается сразу после запуска. Журнал перенесён в SQLite; отчёт ограничен окном `startedAt + days` и не смешивает обычные решения с shadow.
|
|
71
|
+
- **test-dag.mjs падал на очистке temp-папки (Windows ENOTEMPTY):** при удалении временной директории оставались открытые SQLite-WAL-хендлы (в т.ч. модульный lazy-хендл `record-history.js`). Перед `fs.rm` добавил `wal_checkpoint(TRUNCATE)`, `db.close()`, `closeDb()` и ретрай удаления с паузой; ошибка очистки теперь предупреждает, но не фейлит тест. `npm test` стабильно зелёный (12/12 DAG-проверок, 5 прогонов подряд).
|
|
72
|
+
- **Документация утверждала, что LLM решает, отправлять ли уведомление:** на самом деле модель только классифицирует, а подавляют только правила с `action: "skip"`. `docs/LOCAL-AI.md` и `docs/FEATURES.md` исправлены.
|
|
14
73
|
|
|
15
74
|
### Changed
|
|
16
75
|
|
|
17
|
-
|
|
76
|
+
- **Понятное имя `fallback` (Спринт 31.11):** значение `fallback: "skip"` переименовано в `notify`, потому что означало «пропустить правила и отправить уведомление», а не «не отправлять». Старое имя по-прежнему принимается схемой `manage_local_ai`, RPC и `settings.json` и при загрузке нормализуется в `notify`; GUI показывает варианты `Rules` и `Notify`. Обновлены `docs/LOCAL-AI.md` и `docs/FEATURES.md`.
|
|
77
|
+
- **Задачи после обновления получают политику `hybrid`:** задачи без явных `allowedTools`/`legacyShell` больше не могут запускать `shell` и задавать `question`. Если сценарию нужны команды, добавьте `shell` в `allowedTools`, включите `legacyShell` у задачи или переключите `permissions.defaultPolicy` на `legacy`; проверка — `dry_run` и лог задачи (`policy=hybrid, denied=shell,question`).
|
|
18
78
|
|
|
19
79
|
## [1.5.4] - 2026-11-16
|
|
20
80
|
|
|
@@ -39,7 +99,7 @@ All notable changes to this project are documented here. Format follows [Keep a
|
|
|
39
99
|
- **Shadow-режим триажа (Спринт 30.6):** `notifications.triage.shadow` (`enabled`, `days` по умолчанию 14, `startedAt`). В активном периоде решения триажа записываются в память (`src/core/triage-shadow.ts`), а уведомления не подавляются: `notifyTaskCompletion` фиксирует вердикт и пропускает фильтр. Отчёт (`total`, `skips`/`wouldSuppress`, `bySource`) отдаётся через `rpc.get_shadow_report` и сбрасывается `rpc.reset_shadow_report`; в GUI — чекбокс, длительность периода и счётчики. Включение режима без даты старта автоматически начинает период при сохранении, выключение сбрасывает дату, истёкший период возвращает обычную фильтрацию. `test-triage-shadow.mjs` — 26 проверок.
|
|
40
100
|
- **`manage_local_ai` + GUI (Спринт 30.7):** инструмент `manage_local_ai` (`action: "get"|"update"|"test"`) читает и обновляет настройки триажа (`mode`, `baseUrl`, `model`, `timeoutMs`, `fallback`, `confidenceThreshold`, `shadow`) и отправляет одно синтетическое уведомление модели для проверки связи (`test`). Чистые функции слияния патча и сводки в `src/core/local-ai.ts` — без сетевых вызовов и записи на диск. GUI получает блок локального ассистента в настройках уведомлений: селектор режима, адрес API, модель, таймаут, порог уверенности, фоллбек и кнопка проверки связи. `test-local-ai.mjs` — 32 проверки. Всего тестовых сюит: 39.
|
|
41
101
|
- **Бенчмарк локальной модели (Спринт 30.8):** `scripts/bench-local.mjs` (`npm run bench:local`) измеряет латентность, долю ответов, валидных по схеме, и скорость (`tok/s` по `eval_count`/`eval_duration`), подбирает тир по объёму RAM (`rules-only` < 8 ГБ, `light` < 15 ГБ, `balanced` < 30 ГБ, `max` иначе) и пишет версионированный JSON (`schemaVersion: "1"`) для краудсорсинга. Без Ollama или модели отчёт остаётся валидным (`available: false`), код выхода 2; качественный выход 0 при ≥ 70% schema-valid. Прогон на 16 ГБ CPU-машине (Ryzen 7 5800X, qwen3:4b Q4_K_M): 2/2 schema-valid, ~28.7 tok/s, средняя латентность ~24 с.
|
|
42
|
-
- **Рецепт локальной модели (Спринт 30.9):** `docs/LOCAL-AI.md` — режимы триажа, настройки, `manage_local_ai`, выбор модели по RAM
|
|
102
|
+
- **Рецепт локальной модели (Спринт 30.9):** `docs/LOCAL-AI.md` — режимы триажа, настройки, `manage_local_ai`, выбор модели по RAM, бенчмарк, shadow-режим, fail-open и troubleshooting (включая `OLLAMA_CONTEXT_LENGTH`). В `skills/scheduled-job-best-practices/references/recipes.md` добавлен рецепт 8 «Safe rollout of local triage» с готовым JSON и командой бенчмарка.
|
|
43
103
|
- **Документация и CHANGELOG 1.5.3 (Спринт 30.10):** обновлены `docs/FEATURES.md` (25 инструментов, `manage_local_ai`, раздел Local assistant) и `docs/README.ru.md` (25 инструментов, строка `manage_local_ai`, локальный ассистент в возможностях); версия 1.5.3.
|
|
44
104
|
|
|
45
105
|
### Fixed
|
|
@@ -259,7 +319,7 @@ All notable changes to this project are documented here. Format follows [Keep a
|
|
|
259
319
|
- Agent tool descriptions are in English; runtime messages stay localized.
|
|
260
320
|
- `get_task_logs` supports a `lines` limit (1–1000).
|
|
261
321
|
- `update_task` keeps every field that is not passed, so the agent can change one setting without resending the whole task.
|
|
262
|
-
- **Built-in agent skill** `scheduled-job-best-practices`, registered by the plugin itself: guidance on schedule design, prompt structure, safety defaults, matrix concurrency, DAG rules and failure diagnosis, plus `references/recipes.md` with
|
|
322
|
+
- **Built-in agent skill** `scheduled-job-best-practices`, registered by the plugin itself: guidance on schedule design, prompt structure, safety defaults, matrix concurrency, DAG rules and failure diagnosis, plus `references/recipes.md` with eight complete examples. No manual `.opencode/skills` setup.
|
|
263
323
|
- **Documentation:** `docs/ARCHITECTURE.md` (process model, modules, backends, data model, security model), `docs/FEATURES.md` (full feature catalog with examples and limits) and `docs/MIGRATION.md` (from cron, systemd timers, launchd and Windows Task Scheduler), linked from both READMEs.
|
|
264
324
|
- `test-docs.mjs` - 30 checks that the guides exist, stay complete and ship in the npm package.
|
|
265
325
|
- **History retention:** `history.retentionDays` (default 30) and `history.maxRecords` (default 5000) in settings (`0` disables either limit); daily auto-cleanup on plugin start plus `PRAGMA incremental_vacuum`; `cleanup_history` RPC and a «🧹 История и ретеншн» panel in the GUI with last-cleanup stats and an «Очистить сейчас» button.
|
package/CROSS_PLATFORM.md
CHANGED
|
@@ -1,38 +1,40 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Cross-platform: Windows → macOS → Linux
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
The plugin is no longer tied to `schtasks`. The scheduler is an abstract layer with
|
|
4
|
+
three implementations, and run wrappers are generated for the target OS.
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
Translations: [Русский](docs/CROSS_PLATFORM.ru.md) · [中文](docs/CROSS_PLATFORM.zh.md)
|
|
7
|
+
|
|
8
|
+
## Architecture
|
|
7
9
|
|
|
8
10
|
```
|
|
9
11
|
src/
|
|
10
|
-
index.ts #
|
|
11
|
-
gui.tsx #
|
|
12
|
-
server.ts #
|
|
12
|
+
index.ts # tools, RPC, plugin lifecycle
|
|
13
|
+
gui.tsx # GUI panel (title comes from RPC)
|
|
14
|
+
server.ts # web dashboard (dynamic title)
|
|
13
15
|
core/
|
|
14
16
|
scheduler/
|
|
15
17
|
types.ts # SchedulerBackend, CreateTaskOptions, RunTaskResult
|
|
16
|
-
index.ts #
|
|
18
|
+
index.ts # factory createSchedulerBackend() + getSchedulerTitle()
|
|
17
19
|
windows.ts # WindowsScheduler (schtasks)
|
|
18
20
|
linux.ts # LinuxScheduler (crontab)
|
|
19
21
|
mac.ts # MacScheduler (launchd / LaunchAgents)
|
|
20
|
-
posix.ts #
|
|
21
|
-
registry.ts #
|
|
22
|
-
logs.ts #
|
|
22
|
+
posix.ts # shared base for Linux/macOS (task registry)
|
|
23
|
+
registry.ts # persistent task registry for POSIX backends
|
|
24
|
+
logs.ts # cross-platform task log reader
|
|
23
25
|
wrappers/
|
|
24
|
-
bash.ts #
|
|
25
|
-
ps-wrapper.ts # .ps1/.cmd
|
|
26
|
-
record-history.ts #
|
|
27
|
-
cron-to-schtasks.ts # cron → schtasks (
|
|
26
|
+
bash.ts # .sh wrapper generator for Linux/macOS
|
|
27
|
+
ps-wrapper.ts # .ps1/.cmd wrappers for Windows (unchanged)
|
|
28
|
+
record-history.ts # metrics/history + retry/chains (via backend)
|
|
29
|
+
cron-to-schtasks.ts # cron → schtasks (Windows only)
|
|
28
30
|
```
|
|
29
31
|
|
|
30
|
-
###
|
|
32
|
+
### Interface
|
|
31
33
|
|
|
32
34
|
```ts
|
|
33
35
|
interface SchedulerBackend {
|
|
34
36
|
readonly platform: NodeJS.Platform;
|
|
35
|
-
readonly title: string; //
|
|
37
|
+
readonly title: string; // "Windows Task Scheduler" / "OpenCode Scheduler"
|
|
36
38
|
createTask(options: CreateTaskOptions): Promise<void>;
|
|
37
39
|
deleteTask(name: string): Promise<void>;
|
|
38
40
|
runTask(name: string): Promise<RunTaskResult>;
|
|
@@ -42,72 +44,106 @@ interface SchedulerBackend {
|
|
|
42
44
|
}
|
|
43
45
|
```
|
|
44
46
|
|
|
45
|
-
|
|
46
|
-
`win32 → WindowsScheduler`, `darwin → MacScheduler`,
|
|
47
|
+
The factory picks an implementation from `process.platform`:
|
|
48
|
+
`win32 → WindowsScheduler`, `darwin → MacScheduler`, everything else → `LinuxScheduler`.
|
|
47
49
|
|
|
48
|
-
##
|
|
50
|
+
## How each OS works
|
|
49
51
|
|
|
50
|
-
### Windows (
|
|
51
|
-
-
|
|
52
|
-
-
|
|
53
|
-
-
|
|
54
|
-
- cron
|
|
52
|
+
### Windows (behaviour unchanged)
|
|
53
|
+
- Tasks are registered in Windows Task Scheduler via `schtasks` under `\OpenCode\windows-scheduler\`.
|
|
54
|
+
- Wrapper: `run-task.ps1` plus a per-task `run-<name>.cmd` in `%APPDATA%\opencode\windows-scheduler\wrapper`.
|
|
55
|
+
- Logs: `%APPDATA%\opencode\windows-scheduler\logs\<name>.log`.
|
|
56
|
+
- cron is converted to schtasks (`convertCronToSchTasks`) — the same pattern set as before.
|
|
55
57
|
|
|
56
58
|
### Linux
|
|
57
|
-
-
|
|
59
|
+
- Tasks live in a managed `crontab` block:
|
|
58
60
|
```
|
|
59
61
|
# >>> opencode-scheduler >>>
|
|
60
62
|
# task: my-task
|
|
61
63
|
*/5 * * * * /bin/bash '/…/wrapper/run-my-task.sh' >> '/…/logs/my-task.log' 2>&1
|
|
62
64
|
# <<< opencode-scheduler <<<
|
|
63
65
|
```
|
|
64
|
-
-
|
|
65
|
-
-
|
|
66
|
-
-
|
|
67
|
-
-
|
|
68
|
-
-
|
|
66
|
+
- Pause = a line prefixed with `# PAUSED: ` (the block is rebuilt from the registry).
|
|
67
|
+
- Tasks with a `file` trigger never reach crontab — the plugin's FileWatchManager starts them.
|
|
68
|
+
- Wrapper: `~/.config/opencode/windows-scheduler/wrapper/run-<name>.sh` (chmod 0755).
|
|
69
|
+
- Full cron syntax (unlike Windows), because crontab understands it natively.
|
|
70
|
+
- Delete/rebuild touches only its own block; other `crontab` lines are left alone.
|
|
69
71
|
|
|
70
72
|
### macOS
|
|
71
|
-
-
|
|
72
|
-
-
|
|
73
|
+
- Tasks are LaunchAgent plists at `~/Library/LaunchAgents/com.opencode.scheduler.<name>.plist`.
|
|
74
|
+
- Schedule: `StartInterval` for `* * * * *` and `*/N`, `StartCalendarInterval` for `M * * * *`,
|
|
73
75
|
`M H * * *`, `M H * * D`.
|
|
74
|
-
-
|
|
75
|
-
-
|
|
76
|
-
`~/.config/opencode/windows-scheduler/` (
|
|
77
|
-
|
|
78
|
-
###
|
|
79
|
-
- `cd`
|
|
80
|
-
-
|
|
81
|
-
-
|
|
82
|
-
-
|
|
83
|
-
- Quality Gate: `bash -lc "
|
|
84
|
-
-
|
|
85
|
-
|
|
86
|
-
- `PATH`
|
|
87
|
-
|
|
88
|
-
##
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
76
|
+
- Pause = `launchctl unload -w`, resume = `launchctl load -w`.
|
|
77
|
+
- Wrapper is the same `.sh` as on Linux; config paths:
|
|
78
|
+
`~/.config/opencode/windows-scheduler/` (or `$XDG_CONFIG_HOME`).
|
|
79
|
+
|
|
80
|
+
### Shared POSIX wrapper (`.sh`)
|
|
81
|
+
- `cd` into the working directory, `opencode run` with the prompt read from a file.
|
|
82
|
+
- Logs are appended with `>>` and prefixed with timestamps.
|
|
83
|
+
- Locking via atomic `mkdir` — protects against parallel runs.
|
|
84
|
+
- Timeout: child process + watchdog (`TERM`, then `KILL`).
|
|
85
|
+
- Quality Gate: `bash -lc "<command>"` (the `cmd.exe /c` equivalent on Windows).
|
|
86
|
+
- Metrics: `node "<record-history.js>" <task> <status> <started> <duration> <error> "-" "-"` —
|
|
87
|
+
the same contract as the PowerShell wrapper, so history/metrics/retry/chains work everywhere.
|
|
88
|
+
- `PATH` is extended with `/opt/homebrew/bin`, `/usr/local/bin`, `~/.local/bin`, `~/.bun/bin`.
|
|
89
|
+
|
|
90
|
+
## Feature matrix
|
|
91
|
+
|
|
92
|
+
| Capability | Windows | Linux | macOS |
|
|
93
|
+
|---|---|---|---|
|
|
94
|
+
| Scheduler backend | `schtasks` | `crontab` | `launchd` LaunchAgents |
|
|
95
|
+
| Native cron subset | `* * * * *`, `*/N * * * *` (N ≤ 1439, 60 % N = 0), `M * * * *`, `M H * * *`, `M H * * D` | full cron | same subset as Windows |
|
|
96
|
+
| Other cron expressions | minute-poll + schedule gate | native cron | minute-poll + schedule gate |
|
|
97
|
+
| `*/N` in day-of-month / day-of-week | not native → poll | native | not native → poll |
|
|
98
|
+
| Pause / resume | `schtasks /change /disable` / `/enable` | `# PAUSED:` line in the managed block | `launchctl unload -w` / `load -w` |
|
|
99
|
+
| File triggers | in-process `FileWatchManager` | same | same |
|
|
100
|
+
| Task wrappers | `.cmd` + `.ps1` | `.sh` | `.sh` |
|
|
101
|
+
| Logs | `%APPDATA%\opencode\windows-scheduler\logs` | `~/.config/opencode/windows-scheduler/logs` | same as Linux |
|
|
102
|
+
| `secrets.key` protection | `icacls` (owner only) + `chmod` fallback | `chmod 0600` | `chmod 0600` |
|
|
103
|
+
| Dashboard | `127.0.0.1`, dynamic title | same | same |
|
|
104
|
+
| DAG / matrix / quality gates / notifications | in-plugin, OS-independent | same | same |
|
|
105
|
+
|
|
106
|
+
### Compromises
|
|
107
|
+
|
|
108
|
+
1. **Minute-poll.** Cron expressions outside the native subset, and tasks with a non-system
|
|
109
|
+
IANA time zone, are started every minute by the OS scheduler; `schedule-gate` decides
|
|
110
|
+
whether the run proceeds. The cost is one short-lived wrapper process per task per minute.
|
|
111
|
+
2. **`M H */N * *` is deliberately not converted to `schtasks /sc DAILY /mo N`.**
|
|
112
|
+
Cron counts days from the 1st of each month and resets at month boundaries; `/mo N`
|
|
113
|
+
counts days from the task creation date and does not reset. The two schedules are not
|
|
114
|
+
equivalent, so the expression stays in poll mode. A native variant would require
|
|
115
|
+
`MONTHLY` with an explicit `/d` list, not `DAILY /mo N`.
|
|
116
|
+
3. **DST.** The gate works with local wall-clock time. A nonexistent time (spring forward)
|
|
117
|
+
is skipped; an ambiguous time (fall back) runs at the first occurrence.
|
|
118
|
+
4. **`*/N * * * *` on Windows** is native only when `60 % N = 0` and `N ≤ 1439`.
|
|
119
|
+
Otherwise the task falls back to poll mode, because `schtasks /mo N` counts from the
|
|
120
|
+
creation moment while cron counts from the start of the hour.
|
|
121
|
+
5. **POSIX wrappers, crontab and launchd have not been executed on real Linux/macOS hosts**
|
|
122
|
+
(see Limitations); syntax and escaping are covered by tests only.
|
|
123
|
+
|
|
124
|
+
## GUI and dashboard
|
|
125
|
+
- The title is dynamic: "Windows Task Scheduler" on Windows, "OpenCode Scheduler" on macOS/Linux.
|
|
126
|
+
- The title comes from the `get_platform` RPC method → `{ platform, title }`.
|
|
127
|
+
- The title is used in the GUI panel, in the error fallback panel, and in the dashboard `<title>/<h1>`.
|
|
128
|
+
- Buttons, statuses, tables, DAG and metrics do not depend on the OS.
|
|
129
|
+
- Tool descriptions (`schedule_task` and others) substitute the actual scheduler name.
|
|
130
|
+
|
|
131
|
+
## Build and checks
|
|
132
|
+
- `npm run build` — OK, no errors.
|
|
97
133
|
- `npm run build:gui` — OK (`gui-experimental.cjs`, ~47.7 kB).
|
|
98
|
-
-
|
|
99
|
-
-
|
|
100
|
-
- `cronToLaunchdSchedule`
|
|
101
|
-
-
|
|
102
|
-
-
|
|
103
|
-
-
|
|
104
|
-
|
|
105
|
-
##
|
|
106
|
-
1. `.sh
|
|
107
|
-
|
|
108
|
-
2. cron → launchd
|
|
134
|
+
- Verified at runtime:
|
|
135
|
+
- titles for win32/darwin/linux;
|
|
136
|
+
- `cronToLaunchdSchedule` on several expressions;
|
|
137
|
+
- live `listTasks()` on Windows — tasks come back with short names (no prefix);
|
|
138
|
+
- `shellQuote` escaping (quotes, spaces, Cyrillic);
|
|
139
|
+
- `dist/index.js` imports fine, `dist` does not pull `schtasks.js` directly.
|
|
140
|
+
|
|
141
|
+
## Limitations and what to verify on real machines
|
|
142
|
+
1. `.sh` wrappers and crontab/launchd were **never executed** — the current Windows box has no
|
|
143
|
+
`bash`/WSL. Syntax and escaping were checked by hand; a run on Linux and macOS is still needed.
|
|
144
|
+
2. cron → launchd supports the same limited pattern set as Windows
|
|
109
145
|
(`* * * * *`, `*/N * * * *`, `M * * * *`, `M H * * *`, `M H * * D`).
|
|
110
|
-
|
|
111
|
-
3.
|
|
112
|
-
4. `src/schtasks.ts`
|
|
113
|
-
|
|
146
|
+
Linux gets full cron.
|
|
147
|
+
3. The Windows task prefix (`\OpenCode\windows-scheduler\`) and the plugin id are kept for backwards compatibility.
|
|
148
|
+
4. `src/schtasks.ts` remains as a thin shim for old scripts (`test-create.cjs`, `test-run.cjs`);
|
|
149
|
+
all logic now lives in `core/scheduler/windows.ts`.
|
package/README.md
CHANGED
|
@@ -8,10 +8,19 @@
|
|
|
8
8
|
[](LICENSE)
|
|
9
9
|
[](package.json)
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Translations: [Russian](docs/README.ru.md) · [中文](docs/README.zh.md).
|
|
12
12
|
|
|
13
13
|
---
|
|
14
14
|
|
|
15
|
+
## Quickstart
|
|
16
|
+
|
|
17
|
+
1. Install the plugin (see [Install](#install)) and restart OpenCode.
|
|
18
|
+
2. Ask the agent to schedule your first job — one call is enough:
|
|
19
|
+
|
|
20
|
+
> Schedule a task "morning-report" that runs every day at 09:00 with the prompt: "Summarize yesterday's git commits and write the report to ~/reports/".
|
|
21
|
+
|
|
22
|
+
3. Open the dashboard to watch it run: the agent prints the URL when the task is created (default `http://localhost:4380`), or ask for it later with the `get_dashboard_info` tool. Prefer a preview without installing anything? `node scripts/demo-dashboard.mjs` starts a demo dashboard at `http://localhost:4380`.
|
|
23
|
+
|
|
15
24
|
## Why
|
|
16
25
|
|
|
17
26
|
Most schedulers for AI agents are cron wrappers: they run a prompt on a timer and write a log file. This plugin treats agent jobs as **workflows**:
|
|
@@ -20,7 +29,7 @@ Most schedulers for AI agents are cron wrappers: they run a prompt on a timer an
|
|
|
20
29
|
- **Matrix builds** — one template, N repositories, parallel or sequential, with concurrency limits and per-workspace overrides.
|
|
21
30
|
- **Quality gates** — a job is marked successful only if `npm test` (or any command) passes.
|
|
22
31
|
- **Observability** — SQLite history, metrics, logs, and a local web dashboard.
|
|
23
|
-
- **Runs without OpenCode open** - jobs are registered with the native OS scheduler (Windows Task Scheduler, launchd, crontab) and survive reboots.
|
|
32
|
+
- **Runs without OpenCode open** - cron and one-shot jobs are registered with the native OS scheduler (Windows Task Scheduler, launchd, crontab) and survive reboots. File, git and MCP-event triggers are watched inside the plugin process, so they need OpenCode running.
|
|
24
33
|
|
|
25
34
|
Everything runs on your machine. No SaaS, no telemetry, no accounts.
|
|
26
35
|
|
|
@@ -32,7 +41,7 @@ Want to see it without installing OpenCode? `node scripts/demo-dashboard.mjs` st
|
|
|
32
41
|
|
|
33
42
|
| Area | What you get |
|
|
34
43
|
|---|---|
|
|
35
|
-
| Scheduling | cron expressions, one-shot runs via `runAt` / `delaySeconds`, native OS scheduler (Windows / macOS / Linux),
|
|
44
|
+
| Scheduling | cron expressions, one-shot runs via `runAt` / `delaySeconds`, native OS scheduler (Windows / macOS / Linux), IANA timezones (native where possible, minute-poll + gate otherwise), pause/resume, session continuity (`new` / `reuse` / `last` with `sessionMaxRuns` cleanup) |
|
|
36
45
|
| Reliability | lock-file no-overlap protection, timeouts with hard kill, retries with delay, crash recovery |
|
|
37
46
|
| Quality | Quality Gate command, before/after hooks, per-task allowed/denied tool lists |
|
|
38
47
|
| Orchestration | `dependsOn` DAG, `nextTaskOnSuccess` / `nextTaskOnError` chains, matrix fan-out (parallel/sequential, `continue`/`stop`, concurrency, per-workspace overrides, aggregator task) |
|
|
@@ -40,22 +49,32 @@ Want to see it without installing OpenCode? `node scripts/demo-dashboard.mjs` st
|
|
|
40
49
|
| Multi-repo | workspaces with path validation, per-workspace runs, matrix over one parent task |
|
|
41
50
|
| Observability | SQLite history (success / error / timeout / partial / running), metrics (duration, tokens, cost), JSONL run logs with `/api/logs`, Prometheus `/metrics`, OTLP export, per-task logs, local web dashboard with 14-day analytics, history retention and CSV/JSON export |
|
|
42
51
|
| Operations | dry-run preview, export/import JSON, templates, multi-channel notifications (webhook, Telegram, native OS toasts), quiet hours, digest, encrypted secrets (`${secret:NAME}`), audit log, settings |
|
|
43
|
-
| Interfaces | OpenCode GUI panel, web dashboard,
|
|
52
|
+
| Interfaces | OpenCode GUI panel, web dashboard, 25 agent tools, built-in agent skill |
|
|
44
53
|
|
|
45
54
|
### Language
|
|
46
55
|
|
|
47
|
-
The interface ships in Russian (default)
|
|
48
|
-
(
|
|
49
|
-
`locale: "
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
56
|
+
The interface ships in Russian (default), English and Simplified Chinese. The language
|
|
57
|
+
selector sits in the scheduler panel header (🌐 Auto / Русский / English / 中文) and is
|
|
58
|
+
also available through the `manage_settings` tool (`action: "update"`, `locale: "zh"`).
|
|
59
|
+
`locale: "auto"` (the "Auto" option) follows the OpenCode interface language: the panel
|
|
60
|
+
reacts to language changes immediately, and the resolved locale is sent to the server so
|
|
61
|
+
notifications, digests and the dashboard use the same language. The switch applies
|
|
62
|
+
without a restart. Dashboard localization is still being rolled out: some client-side
|
|
63
|
+
strings remain Russian for now. Agent tool descriptions and schemas stay English by
|
|
64
|
+
design, and diagnostics printed to the console stay Russian.
|
|
65
|
+
|
|
66
|
+
Catalogs live in `locales/ru.json`, `locales/en.json` and `locales/zh.json`; every key
|
|
67
|
+
must exist in all three, otherwise CI fails.
|
|
68
|
+
|
|
69
|
+
Documentation is separate from the interface locale: the English docs are the primary
|
|
70
|
+
source, with Russian (`docs/README.ru.md`) and Simplified Chinese (`docs/README.zh.md`,
|
|
71
|
+
`docs/FEATURES.zh.md`, `docs/FAQ.zh.md`, `docs/SAVINGS.zh.md`,
|
|
72
|
+
`docs/CROSS_PLATFORM.zh.md`) translations. Translations may lag behind the English
|
|
73
|
+
originals.
|
|
55
74
|
|
|
56
75
|
## Install
|
|
57
76
|
|
|
58
|
-
Requires OpenCode v2 and Node.js
|
|
77
|
+
Requires OpenCode v2 and Node.js 22.22+ (node:sqlite and chokidar 6 require Node.js 22.22+).
|
|
59
78
|
|
|
60
79
|
```bash
|
|
61
80
|
opencode plugin add opencode-windows-scheduler
|
|
@@ -75,12 +94,6 @@ Or add the plugin to `opencode.jsonc` manually:
|
|
|
75
94
|
|
|
76
95
|
`experimental.schedules: false` disables the built-in OpenCode scheduler so the agent does not confuse built-in job tools with this plugin's tools. Restart OpenCode after changing the config.
|
|
77
96
|
|
|
78
|
-
Alternatively, install globally with npm:
|
|
79
|
-
|
|
80
|
-
```bash
|
|
81
|
-
npm install -g opencode-windows-scheduler
|
|
82
|
-
```
|
|
83
|
-
|
|
84
97
|
From source:
|
|
85
98
|
|
|
86
99
|
```bash
|
|
@@ -96,7 +109,7 @@ The agent gets the full feature set — 25 tools covering scheduling, pipelines,
|
|
|
96
109
|
|
|
97
110
|
| Tool | Arguments | What it does |
|
|
98
111
|
|---|---|---|
|
|
99
|
-
| `schedule_task` | `name`, `prompt`, `schedule` for cron or `runAt` / `delaySeconds` for one-shot, optional `session` / `sessionMaxRuns`, `timeoutSeconds`, `model`, `priority`, `beforeScript`, `afterScript`, `qualityGate`, `dependsOn`, `retryCount`, `retryDelay`, `nextTaskOnSuccess`, `nextTaskOnError`, `triggerType` (`cron`/`file`/`git`/`mcp-event`/`once`), `mcpEvent`, `watchPath`, `watchGlobs`, `watchIgnore`, `gitBranch`, `gitPaths`, `gitIgnore`, `gitPollSeconds`, `activeDays`, `windowPolicy` (`skip`/`postpone`/`run`), `workingDirectory`, `workspaceId`, `allowedTools`, `deniedTools`, `matrix` | Registers a job with the OS scheduler (cron, one-shot, file, git or MCP-event trigger) |
|
|
112
|
+
| `schedule_task` | `name`, `prompt`, `schedule` for cron or `runAt` / `delaySeconds` for one-shot, optional `session` / `sessionMaxRuns`, `timeoutSeconds`, `model`, `priority`, `beforeScript`, `afterScript`, `qualityGate`, `dependsOn`, `retryCount`, `retryDelay`, `nextTaskOnSuccess`, `nextTaskOnError`, `triggerType` (`cron`/`file`/`git`/`mcp-event`/`once`), `mcpEvent`, `watchPath`, `watchGlobs`, `watchIgnore`, `gitBranch`, `gitPaths`, `gitIgnore`, `gitPollSeconds`, `activeDays`, `windowPolicy` (`skip`/`postpone`/`run`), `workingDirectory`, `workspaceId`, `allowedTools`, `deniedTools`, `legacyShell`, `matrix` | Registers a job with the OS scheduler (cron, one-shot, file, git or MCP-event trigger) |
|
|
100
113
|
| `list_tasks` | — | Returns jobs with schedule, status, next run, chains, workspace and matrix summary |
|
|
101
114
|
| `update_task` | `name` + any field to change | Partial update; omitted fields keep their values, empty values clear them, `matrix: null` removes the matrix |
|
|
102
115
|
| `delete_task` | `name` | Deletes a job (a matrix parent deletes clones and aggregator) |
|
|
@@ -118,13 +131,31 @@ The agent gets the full feature set — 25 tools covering scheduling, pipelines,
|
|
|
118
131
|
| `send_notification` | `action` (`test`/`digest`), `channel?` (`all`/`webhook`/`telegram`/`native`) | Test the notification channels or send the digest |
|
|
119
132
|
| `get_dashboard_info` | — | Dashboard port/URL, platform, title, active profile |
|
|
120
133
|
| `cleanup_history` | `retentionDays?`, `maxRecords?` | Delete old history by age and/or record cap |
|
|
134
|
+
| `manage_secrets` | `action`, `name?`, `value?` | Create, list or delete AES-256-GCM encrypted secrets used in task `env` |
|
|
135
|
+
| `get_audit_log` | `action?`, `target?`, `actor?`, `since?`, `until?`, `limit?` | Mutation audit journal: who changed what, when and via which interface |
|
|
121
136
|
| `emit_event` | `eventName`, `payload?` | Start tasks subscribed to an MCP event |
|
|
122
137
|
|
|
123
138
|
`schedule_task` also accepts the full matrix configuration (`workspaceIds`, `strategy`, `failureMode`, `aggregation`, `concurrency`, `overrides`, `createAggregator`).
|
|
124
139
|
|
|
140
|
+
## Permissions
|
|
141
|
+
|
|
142
|
+
Agent jobs run with `opencode run --auto`, so their tool policy must be explicit. The global `permissions.defaultPolicy` setting (GUI → Settings, or `manage_settings`) chooses the baseline:
|
|
143
|
+
|
|
144
|
+
| Policy | Allowed by default | Denied by default |
|
|
145
|
+
|---|---|---|
|
|
146
|
+
| `hybrid` (default) | read, edit, glob, grep, subagent, skill, webfetch, websearch | shell, question |
|
|
147
|
+
| `secure` | read, glob, grep, skill | edit, shell, question, webfetch, websearch, subagent |
|
|
148
|
+
| `legacy` | all ten actions | — |
|
|
149
|
+
|
|
150
|
+
`deniedTools` always wins. A non-empty `allowedTools` is an allowlist: it denies every action that is not listed, and can explicitly re-enable an action denied by the policy (for example `shell`). `legacyShell: true` re-enables `shell` only under `hybrid`, for tasks migrated from older versions.
|
|
151
|
+
|
|
152
|
+
Blocked actions are written to the audit journal as `tool.blocked` with `reason: "default-policy"` and a `hint`, and each run logs the active policy.
|
|
153
|
+
|
|
154
|
+
Recommended pattern: keep `git commit`/`push`, builds and tests outside the agent, in `qualityGate` or `afterScript` (the wrapper runs them with `bash -c`), and leave the agent with `read`/`edit`. Most jobs then need no `shell` at all.
|
|
155
|
+
|
|
125
156
|
## Agent skill
|
|
126
157
|
|
|
127
|
-
The plugin registers a built-in skill, `scheduled-job-best-practices`, so the agent loads guidance only when it is relevant: cron design, self-contained prompts, Quality Gates, matrix concurrency, DAG rules and post-incident diagnosis. No manual `.opencode/skills` setup is needed. The skill ships with `references/recipes.md` —
|
|
158
|
+
The plugin registers a built-in skill, `scheduled-job-best-practices`, so the agent loads guidance only when it is relevant: cron design, self-contained prompts, Quality Gates, matrix concurrency, DAG rules and post-incident diagnosis. No manual `.opencode/skills` setup is needed. The skill ships with `references/recipes.md` — eight copy-ready configurations.
|
|
128
159
|
|
|
129
160
|
## Matrix builds
|
|
130
161
|
|
|
@@ -189,7 +220,7 @@ Tasks are **interactive only** by default: Task Scheduler starts them only while
|
|
|
189
220
|
npm install
|
|
190
221
|
npm run build # tsc
|
|
191
222
|
npm run build:gui # vite
|
|
192
|
-
npm test #
|
|
223
|
+
npm test # 58 test suites, 600+ checks
|
|
193
224
|
npm run test:en # same suites with the English locale
|
|
194
225
|
```
|
|
195
226
|
|
|
@@ -201,14 +232,30 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
|
|
|
201
232
|
## Documentation
|
|
202
233
|
|
|
203
234
|
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — process model, modules, backends, data model.
|
|
235
|
+
- [docs/CONCEPT.md](docs/CONCEPT.md) — north-star concept: verifiable local-first orchestration (in Russian).
|
|
204
236
|
- [docs/FEATURES.md](docs/FEATURES.md) — full feature catalog with examples.
|
|
237
|
+
- [docs/FAQ.md](docs/FAQ.md) — recovery scenarios, webhook replay, operational answers.
|
|
205
238
|
- [docs/MIGRATION.md](docs/MIGRATION.md) — moving from cron, systemd, launchd or Task Scheduler.
|
|
239
|
+
- [docs/SAVINGS.md](docs/SAVINGS.md) — how the "Saved $" estimate is calculated.
|
|
206
240
|
- [CROSS_PLATFORM.md](CROSS_PLATFORM.md) — Windows / macOS / Linux differences and backends.
|
|
207
241
|
|
|
242
|
+
Translations: [Русский](docs/README.ru.md) · [中文](docs/README.zh.md).
|
|
243
|
+
|
|
208
244
|
## FAQ
|
|
209
245
|
|
|
210
246
|
**Does it work when OpenCode is closed?**
|
|
211
|
-
Yes.
|
|
247
|
+
Yes, for cron and one-shot jobs. They are registered with the native OS scheduler, so they run without an open OpenCode window.
|
|
248
|
+
|
|
249
|
+
File (`file`), git (`git`) and MCP-event (`mcp-event`) triggers are watched by the plugin process (chokidar / git polling / the MCP event bus), so OpenCode must be running for those triggers to fire.
|
|
250
|
+
|
|
251
|
+
| Trigger | Runs without OpenCode? | Mechanism |
|
|
252
|
+
|---|---|---|
|
|
253
|
+
| `cron` | ✅ Yes | Native OS scheduler (Task Scheduler / launchd / crontab) |
|
|
254
|
+
| `once` | ✅ Yes | Native OS scheduler, one-shot registration |
|
|
255
|
+
| `file` | ❌ No | chokidar watcher inside the plugin process |
|
|
256
|
+
| `git` | ❌ No | Git polling inside the plugin process |
|
|
257
|
+
| `mcp-event` | ❌ No | MCP event bus inside the plugin process |
|
|
258
|
+
| `webhook` (`/api/hooks/:name`) | ❌ No | HTTP server inside the plugin process |
|
|
212
259
|
|
|
213
260
|
**Do jobs run when nobody is logged on?**
|
|
214
261
|
On Windows, only if you opt in with `runWhenLoggedOff: true`: the task is then registered as `schtasks /ru SYSTEM` and runs in session 0 without your profile, mapped drives or saved credentials. The default is interactive only — the job runs while the user is logged on. Linux crontab always runs without a login; a macOS launchd agent runs only inside a user session.
|
|
@@ -229,10 +276,10 @@ No. Windows Toast (PowerShell/WinRT), macOS Notification Center (`osascript`) an
|
|
|
229
276
|
Yes. Set `notifications.quietHours` (`enabled`, `from`, `to` in `HH:MM`). During the window successful and `partial` runs are suppressed, while failures and timeouts are always delivered.
|
|
230
277
|
|
|
231
278
|
**How do I store secrets?**
|
|
232
|
-
Use `manage_secrets` (or the
|
|
279
|
+
Use `manage_secrets` (or the **🔐 Secrets** panel in the sidebar) to create an encrypted secret. Secrets are stored in `<PLUGIN_DIR>/secrets.json` with AES-256-GCM and a key file (`secrets.key`; mode 0600 on POSIX, an ACL granting only the current Windows user on Windows). In task `env`, reference a secret as `${secret:NAME}` — the value is substituted at run time and masked in logs, history and audit. The secret name can also be set via `manage_settings` → `notifications.telegram.botToken` left empty and `OPENCODE_SCHEDULER_TELEGRAM_BOT_TOKEN` env var instead.
|
|
233
280
|
|
|
234
281
|
**Can I see who changed what?**
|
|
235
|
-
Yes. The audit log (`get_audit_log` tool,
|
|
282
|
+
Yes. The audit log (`get_audit_log` tool, **Audit log** panel, `GET /api/audit`) records every mutation — task create/update/delete/run, settings, templates, profiles, workspaces, secrets, import, history cleanup — with actor (mcp/gui/http), source, timestamp and redacted details. Retention defaults to 90 days / 10 000 records.
|
|
236
283
|
|
|
237
284
|
**How is this different from `experimental.schedules`?**
|
|
238
285
|
The built-in scheduler runs jobs while OpenCode is open. This plugin uses the native OS scheduler and adds DAG pipelines, matrix builds, quality gates, webhooks and observability.
|
package/ROADMAP-STRATEGY.md
CHANGED
|
@@ -137,3 +137,9 @@ Enforced `allowedTools` / `deniedTools` вместо advisory, scoped-инъек
|
|
|
137
137
|
3. Docker runner — после подтверждения спроса.
|
|
138
138
|
|
|
139
139
|
**Критерий месяца:** пользователь ставит плагин одной командой, получает уведомление в Telegram о падении задачи, токены и доступы не лежат открытым текстом в `tasks.json`, а интерфейс говорит на его языке.
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## Долгосрочное видение
|
|
144
|
+
|
|
145
|
+
Путь от плагина к фреймворку описан в [docs/CONCEPT.md](./docs/CONCEPT.md) (§13): локальный интеллект + мультиагентная оркестрация + абстракция слоя исполнения. Этот тактический роадмап является реализацией первых двух этапов — глубокой интеграции с OpenCode v2 и подготовки к абстракции Agent Executor Interface.
|