agent-steward 0.0.1 → 0.0.3
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 +399 -0
- package/CROSS_PLATFORM.md +151 -0
- package/README.md +307 -15
- package/ROADMAP-STRATEGY.md +196 -0
- package/ROADMAP.md +184 -0
- package/dist/core/analytics.d.ts +132 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +290 -0
- package/dist/core/audit.d.ts +96 -0
- package/dist/core/audit.d.ts.map +1 -0
- package/dist/core/audit.js +297 -0
- package/dist/core/cron-to-schtasks.d.ts +12 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +175 -0
- package/dist/core/dry-run.d.ts +102 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +447 -0
- package/dist/core/file-watcher.d.ts +31 -0
- package/dist/core/file-watcher.d.ts.map +1 -0
- package/dist/core/file-watcher.js +186 -0
- package/dist/core/git-trigger.d.ts +82 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +312 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/local-ai.d.ts +52 -0
- package/dist/core/local-ai.d.ts.map +1 -0
- package/dist/core/local-ai.js +119 -0
- package/dist/core/lock.d.ts +57 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +193 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +724 -0
- package/dist/core/native-notify.d.ts +36 -0
- package/dist/core/native-notify.d.ts.map +1 -0
- package/dist/core/native-notify.js +113 -0
- package/dist/core/one-shot.d.ts +90 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +182 -0
- package/dist/core/otel.d.ts +4 -0
- package/dist/core/otel.d.ts.map +1 -0
- package/dist/core/otel.js +98 -0
- 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/prometheus.d.ts +23 -0
- package/dist/core/prometheus.d.ts.map +1 -0
- package/dist/core/prometheus.js +146 -0
- package/dist/core/ps-wrapper.d.ts +73 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +1091 -0
- package/dist/core/record-history.d.ts +25 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +471 -0
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -0
- 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.d.ts +2 -0
- package/dist/core/schedule-gate.d.ts.map +1 -0
- package/dist/core/schedule-gate.js +211 -0
- package/dist/core/schedule-v2.d.ts +116 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +586 -0
- package/dist/core/scheduler/at-fallback.d.ts +42 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +70 -0
- package/dist/core/scheduler/index.d.ts +32 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +63 -0
- package/dist/core/scheduler/linux.d.ts +46 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +261 -0
- package/dist/core/scheduler/logs.d.ts +11 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -0
- package/dist/core/scheduler/logs.js +34 -0
- package/dist/core/scheduler/mac.d.ts +46 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +256 -0
- package/dist/core/scheduler/posix.d.ts +40 -0
- package/dist/core/scheduler/posix.d.ts.map +1 -0
- package/dist/core/scheduler/posix.js +100 -0
- package/dist/core/scheduler/registry.d.ts +43 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +57 -0
- package/dist/core/scheduler/types.d.ts +86 -0
- package/dist/core/scheduler/types.d.ts.map +1 -0
- package/dist/core/scheduler/types.js +1 -0
- package/dist/core/scheduler/windows.d.ts +112 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +749 -0
- package/dist/core/secrets.d.ts +66 -0
- package/dist/core/secrets.d.ts.map +1 -0
- package/dist/core/secrets.js +433 -0
- 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 +42 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/session.js +134 -0
- 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/structured-log.d.ts +84 -0
- package/dist/core/structured-log.d.ts.map +1 -0
- package/dist/core/structured-log.js +146 -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 +55 -0
- package/dist/core/telegram.d.ts.map +1 -0
- package/dist/core/telegram.js +344 -0
- package/dist/core/triage-chain.d.ts +40 -0
- package/dist/core/triage-chain.d.ts.map +1 -0
- package/dist/core/triage-chain.js +80 -0
- 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 +23 -0
- package/dist/core/triage-rules.d.ts.map +1 -0
- package/dist/core/triage-rules.js +196 -0
- package/dist/core/triage-shadow.d.ts +91 -0
- package/dist/core/triage-shadow.d.ts.map +1 -0
- package/dist/core/triage-shadow.js +160 -0
- 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.d.ts +76 -0
- package/dist/core/triage.d.ts.map +1 -0
- package/dist/core/triage.js +271 -0
- 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 +95 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +413 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/history-repo.d.ts +110 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +300 -0
- package/dist/db/index.d.ts +49 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +128 -0
- package/dist/db/metrics-repo.d.ts +46 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +103 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +244 -0
- package/dist/db/recovery.d.ts +11 -0
- package/dist/db/recovery.d.ts.map +1 -0
- package/dist/db/recovery.js +38 -0
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +48 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +137 -0
- package/dist/db/runs-repo.d.ts +120 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +319 -0
- package/dist/db/schema.d.ts +38 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +325 -0
- package/dist/db/settings-repo.d.ts +8 -0
- package/dist/db/settings-repo.d.ts.map +1 -0
- package/dist/db/settings-repo.js +27 -0
- package/dist/db/tasks-repo.d.ts +26 -0
- package/dist/db/tasks-repo.d.ts.map +1 -0
- package/dist/db/tasks-repo.js +120 -0
- package/dist/db/templates-repo.d.ts +17 -0
- package/dist/db/templates-repo.d.ts.map +1 -0
- package/dist/db/templates-repo.js +57 -0
- package/dist/history.d.ts +60 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +70 -0
- package/dist/i18n.d.ts +75 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +357 -0
- package/dist/index.d.ts +858 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5209 -0
- package/dist/integrations.d.ts +72 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +233 -0
- package/dist/notifications.d.ts +199 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +967 -0
- package/dist/profiles.d.ts +64 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +305 -0
- package/dist/rpc.d.ts +3915 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +1596 -0
- package/dist/schtasks.d.ts +32 -0
- package/dist/schtasks.d.ts.map +1 -0
- package/dist/schtasks.js +45 -0
- package/dist/server.d.ts +128 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2414 -0
- package/dist/settings.d.ts +389 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +770 -0
- package/dist/shared/jobs-view.d.ts +59 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +146 -0
- package/dist/skill.d.ts +15 -0
- package/dist/skill.d.ts.map +1 -0
- package/dist/skill.js +93 -0
- package/dist/task-transfer.d.ts +252 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +632 -0
- package/dist/templates.d.ts +57 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +16 -0
- package/dist/types.d.ts +112 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +158 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/dist/workspaces.d.ts +113 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +393 -0
- package/docs/ARCHITECTURE.md +559 -0
- package/docs/COMPATIBILITY.md +237 -0
- package/docs/CONCEPT.md +242 -0
- package/docs/CROSS_PLATFORM.ru.md +152 -0
- package/docs/CROSS_PLATFORM.zh.md +148 -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 +699 -0
- package/docs/FEATURES.zh.md +656 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +363 -0
- package/docs/README.ru.md +287 -0
- package/docs/README.zh.md +306 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/docs/dashboard.png +0 -0
- package/docs/spikes/local-model-structured-output.md +81 -0
- package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
- package/docs/spikes/ollama-qwen3-4b.json +163 -0
- package/gui-experimental.cjs +9 -0
- package/index.js +2 -0
- package/locales/en.json +781 -0
- package/locales/ru.json +781 -0
- package/locales/zh.json +781 -0
- package/package.json +154 -13
- package/scripts/bench-local.mjs +321 -0
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/demo-dashboard.mjs +209 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/spike-local-structured.mjs +182 -0
- package/scripts/test-locale.mjs +45 -0
- package/skills/scheduled-job-best-practices/SKILL.md +158 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
- package/src/core/analytics.ts +424 -0
- package/src/core/audit.ts +418 -0
- package/src/core/cron-to-schtasks.ts +209 -0
- package/src/core/dry-run.ts +601 -0
- package/src/core/file-watcher.ts +245 -0
- package/src/core/git-trigger.ts +391 -0
- package/src/core/glob.ts +226 -0
- package/src/core/local-ai.ts +173 -0
- package/src/core/lock.ts +219 -0
- package/src/core/matrix.ts +947 -0
- package/src/core/native-notify.ts +157 -0
- package/src/core/one-shot.ts +239 -0
- package/src/core/otel.ts +128 -0
- package/src/core/permissions.ts +200 -0
- package/src/core/prometheus.ts +215 -0
- package/src/core/ps-wrapper.ts +1160 -0
- package/src/core/record-history.ts +615 -0
- package/src/core/retention.ts +141 -0
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +253 -0
- package/src/core/schedule-v2.ts +668 -0
- package/src/core/scheduler/at-fallback.ts +113 -0
- package/src/core/scheduler/index.ts +82 -0
- package/src/core/scheduler/linux.ts +308 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +322 -0
- package/src/core/scheduler/posix.ts +128 -0
- package/src/core/scheduler/registry.ts +101 -0
- package/src/core/scheduler/types.ts +90 -0
- package/src/core/scheduler/windows.ts +881 -0
- package/src/core/secrets.ts +503 -0
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +150 -0
- package/src/core/shutdown.ts +69 -0
- package/src/core/structured-log.ts +214 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +436 -0
- package/src/core/triage-chain.ts +125 -0
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +238 -0
- package/src/core/triage-shadow.ts +240 -0
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +366 -0
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +532 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/history-repo.ts +492 -0
- package/src/db/index.ts +176 -0
- package/src/db/metrics-repo.ts +170 -0
- package/src/db/migrate.ts +328 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +220 -0
- package/src/db/runs-repo.ts +481 -0
- package/src/db/schema.ts +349 -0
- package/src/db/settings-repo.ts +31 -0
- package/src/db/tasks-repo.ts +162 -0
- package/src/db/templates-repo.ts +77 -0
- package/src/gui.tsx +5222 -0
- package/src/history.ts +128 -0
- package/src/i18n.ts +413 -0
- package/src/index.ts +6642 -0
- package/src/integrations.ts +297 -0
- package/src/notifications.ts +1346 -0
- package/src/profiles.ts +345 -0
- package/src/rpc.ts +1704 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +2663 -0
- package/src/settings.ts +1369 -0
- package/src/shared/jobs-view.ts +188 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +946 -0
- package/src/templates.ts +67 -0
- package/src/tui-v1.tsx +341 -0
- package/src/tui.tsx +329 -0
- package/src/types.ts +226 -0
- package/src/version.ts +27 -0
- package/src/workspaces.ts +487 -0
package/src/profiles.ts
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Профили (Спринт 21): каждый профиль — отдельная директория со своей БД,
|
|
7
|
+
* настройками, логами, обёртками и портом дашборда. Профиль `default`
|
|
8
|
+
* использует базовую директорию плагина (как раньше — без миграции), остальные
|
|
9
|
+
* живут в `<base>/profiles/<name>`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_PROFILE = "default";
|
|
13
|
+
|
|
14
|
+
/** Файл-маркер активного профиля (когда переменная окружения не задана). */
|
|
15
|
+
const ACTIVE_PROFILE_FILE = "active-profile";
|
|
16
|
+
|
|
17
|
+
/** Метаданные профиля: имя и порт дашборда. */
|
|
18
|
+
export interface ProfileMeta {
|
|
19
|
+
name: string;
|
|
20
|
+
port: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Описание профиля для RPC/GUI. */
|
|
24
|
+
export interface ProfileInfo {
|
|
25
|
+
name: string;
|
|
26
|
+
dir: string;
|
|
27
|
+
port: number | null;
|
|
28
|
+
isDefault: boolean;
|
|
29
|
+
active: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Базовая директория плагина (до профилей).
|
|
34
|
+
*
|
|
35
|
+
* Windows: %APPDATA%\opencode\agent-steward.
|
|
36
|
+
* macOS/Linux: $XDG_CONFIG_HOME/opencode/agent-steward или
|
|
37
|
+
* ~/.config/opencode/agent-steward.
|
|
38
|
+
* OPENCODE_SCHEDULER_HOME переопределяет всё (тесты, кастомные установки).
|
|
39
|
+
*
|
|
40
|
+
* При первом запуске после переименования данные из исторической
|
|
41
|
+
* .../opencode/windows-scheduler копируются в новую директорию (legacy
|
|
42
|
+
* остаётся на месте как резервная копия).
|
|
43
|
+
*/
|
|
44
|
+
export function getBasePluginDir(): string {
|
|
45
|
+
const custom = process.env.OPENCODE_SCHEDULER_HOME?.trim();
|
|
46
|
+
if (custom) return path.resolve(custom);
|
|
47
|
+
|
|
48
|
+
const root = path.join(pluginConfigRoot(), "opencode");
|
|
49
|
+
const target = path.join(root, "agent-steward");
|
|
50
|
+
const legacy = path.join(root, "windows-scheduler");
|
|
51
|
+
|
|
52
|
+
if (fs.existsSync(target) || !fs.existsSync(legacy)) return target;
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
migrateLegacyBaseDir(legacy, target);
|
|
56
|
+
return target;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
// Не теряем доступ к данным: продолжаем работать в старой директории.
|
|
59
|
+
console.error(
|
|
60
|
+
`[agent-steward] Не удалось перенести данные из "${legacy}" в "${target}": ${
|
|
61
|
+
error instanceof Error ? error.message : String(error)
|
|
62
|
+
}. Использую старую директорию.`,
|
|
63
|
+
);
|
|
64
|
+
return legacy;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Корень конфигурации пользователя (без .../opencode). */
|
|
69
|
+
function pluginConfigRoot(): string {
|
|
70
|
+
if (process.platform === "win32") {
|
|
71
|
+
return process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
|
|
72
|
+
}
|
|
73
|
+
return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const MIGRATION_MARKER = ".migrated-from-windows-scheduler";
|
|
77
|
+
|
|
78
|
+
/** Расширения текстовых файлов, в которых могут быть абсолютные пути. */
|
|
79
|
+
const PATH_REWRITE_EXTENSIONS = new Set([
|
|
80
|
+
".json",
|
|
81
|
+
".cmd",
|
|
82
|
+
".sh",
|
|
83
|
+
".bash",
|
|
84
|
+
".ps1",
|
|
85
|
+
".txt",
|
|
86
|
+
]);
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Копирует legacy-директорию в новую и переписывает в текстовых файлах
|
|
90
|
+
* абсолютные пути старой директории на новую. Копия делается во временную
|
|
91
|
+
* директорию и переименовывается атомарно, чтобы не оставить половину данных.
|
|
92
|
+
*/
|
|
93
|
+
function migrateLegacyBaseDir(legacy: string, target: string): void {
|
|
94
|
+
const temp = `${target}.migrating-${process.pid}`;
|
|
95
|
+
fs.rmSync(temp, { recursive: true, force: true });
|
|
96
|
+
fs.cpSync(legacy, temp, { recursive: true });
|
|
97
|
+
|
|
98
|
+
rewriteAbsolutePaths(temp, legacy, target);
|
|
99
|
+
fs.writeFileSync(
|
|
100
|
+
path.join(temp, MIGRATION_MARKER),
|
|
101
|
+
`${new Date().toISOString()}\n`,
|
|
102
|
+
"utf8",
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
fs.renameSync(temp, target);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
fs.rmSync(temp, { recursive: true, force: true });
|
|
109
|
+
// Параллельный процесс мог успеть создать target — это не ошибка.
|
|
110
|
+
if (fs.existsSync(target)) return;
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function rewriteAbsolutePaths(root: string, from: string, to: string): void {
|
|
116
|
+
const variants = [
|
|
117
|
+
from,
|
|
118
|
+
from.replace(/\\/g, "/"),
|
|
119
|
+
from.replace(/\\/g, "\\\\"),
|
|
120
|
+
].filter((value, index, all) => value && all.indexOf(value) === index);
|
|
121
|
+
|
|
122
|
+
const walk = (dir: string): void => {
|
|
123
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
124
|
+
const full = path.join(dir, entry.name);
|
|
125
|
+
if (entry.isDirectory()) {
|
|
126
|
+
walk(full);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (!PATH_REWRITE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const text = fs.readFileSync(full, "utf8");
|
|
133
|
+
let next = text;
|
|
134
|
+
for (const variant of variants) {
|
|
135
|
+
next = next.split(variant).join(variant.includes("\\\\") ? to.replace(/\\/g, "\\\\") : variant.includes("/") ? to.replace(/\\/g, "/") : to);
|
|
136
|
+
}
|
|
137
|
+
if (next !== text) fs.writeFileSync(full, next, "utf8");
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
walk(root);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Нормализует имя профиля: нижний регистр, только [a-z0-9_-]. */
|
|
145
|
+
export function sanitizeProfileName(value: string | null | undefined): string {
|
|
146
|
+
const normalized = (value ?? "")
|
|
147
|
+
.trim()
|
|
148
|
+
.toLowerCase()
|
|
149
|
+
.replace(/[^a-z0-9_-]+/g, "-")
|
|
150
|
+
.replace(/^-+|-+$/g, "")
|
|
151
|
+
.slice(0, 40);
|
|
152
|
+
return normalized || DEFAULT_PROFILE;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Валидация имени профиля (без «исправления»): пусто/кривые символы — ошибка. */
|
|
156
|
+
export function validateProfileName(value: string): string | null {
|
|
157
|
+
const trimmed = (value ?? "").trim().toLowerCase();
|
|
158
|
+
if (!trimmed) return "Имя профиля не может быть пустым.";
|
|
159
|
+
if (!/^[a-z][a-z0-9_-]{0,39}$/.test(trimmed)) {
|
|
160
|
+
return "Имя профиля: только латиница, цифры, «-» и «_», до 40 символов, не с цифры.";
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Читает имя активного профиля из файла-маркера (если есть). */
|
|
166
|
+
function readActiveProfileMarker(base: string): string | null {
|
|
167
|
+
try {
|
|
168
|
+
const raw = fs.readFileSync(path.join(base, ACTIVE_PROFILE_FILE), "utf8").trim();
|
|
169
|
+
return raw ? sanitizeProfileName(raw) : null;
|
|
170
|
+
} catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Имя текущего профиля: OPENCODE_SCHEDULER_PROFILE > файл-маркер > default.
|
|
177
|
+
*/
|
|
178
|
+
export function getProfileName(): string {
|
|
179
|
+
const fromEnv = process.env.OPENCODE_SCHEDULER_PROFILE?.trim();
|
|
180
|
+
if (fromEnv) return sanitizeProfileName(fromEnv);
|
|
181
|
+
return readActiveProfileMarker(getBasePluginDir()) ?? DEFAULT_PROFILE;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Директория профиля: default — базовая, остальные — <base>/profiles/<name>. */
|
|
185
|
+
export function getProfileDir(name: string = getProfileName()): string {
|
|
186
|
+
const base = getBasePluginDir();
|
|
187
|
+
const normalized = sanitizeProfileName(name);
|
|
188
|
+
if (normalized === DEFAULT_PROFILE) return base;
|
|
189
|
+
return path.join(base, "profiles", normalized);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Путь к метаданным профиля. */
|
|
193
|
+
function profileMetaFile(name: string): string {
|
|
194
|
+
return path.join(getProfileDir(name), "profile.json");
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Читает profile.json профиля (или null, если файла нет/он битый). */
|
|
198
|
+
export function readProfileMeta(name: string): ProfileMeta | null {
|
|
199
|
+
try {
|
|
200
|
+
const raw = fs.readFileSync(profileMetaFile(name), "utf8");
|
|
201
|
+
const parsed = JSON.parse(raw) as Partial<ProfileMeta>;
|
|
202
|
+
const profileName = sanitizeProfileName(parsed?.name ?? name);
|
|
203
|
+
const port = Number(parsed?.port);
|
|
204
|
+
return {
|
|
205
|
+
name: profileName,
|
|
206
|
+
port: Number.isFinite(port) && port >= 1 && port <= 65535 ? Math.floor(port) : 0,
|
|
207
|
+
};
|
|
208
|
+
} catch {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Порт дашборда профиля: env > profile.json > null (дефолтная логика сервера). */
|
|
214
|
+
export function getProfilePort(name: string = getProfileName()): number | null {
|
|
215
|
+
const fromEnv = Number(process.env.OPENCODE_SCHEDULER_PORT);
|
|
216
|
+
if (Number.isFinite(fromEnv) && fromEnv >= 1 && fromEnv <= 65535) {
|
|
217
|
+
return Math.floor(fromEnv);
|
|
218
|
+
}
|
|
219
|
+
const meta = readProfileMeta(name);
|
|
220
|
+
if (meta && meta.port > 0) return meta.port;
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Список существующих профилей (default всегда первый). */
|
|
225
|
+
export function listProfiles(): ProfileInfo[] {
|
|
226
|
+
const base = getBasePluginDir();
|
|
227
|
+
const active = getProfileName();
|
|
228
|
+
const names = new Set<string>([DEFAULT_PROFILE]);
|
|
229
|
+
|
|
230
|
+
const profilesRoot = path.join(base, "profiles");
|
|
231
|
+
try {
|
|
232
|
+
for (const entry of fs.readdirSync(profilesRoot, { withFileTypes: true })) {
|
|
233
|
+
if (!entry.isDirectory()) continue;
|
|
234
|
+
const candidate = sanitizeProfileName(entry.name);
|
|
235
|
+
if (candidate === DEFAULT_PROFILE) continue;
|
|
236
|
+
names.add(candidate);
|
|
237
|
+
}
|
|
238
|
+
} catch {
|
|
239
|
+
// profiles/ ещё нет — только default.
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return Array.from(names)
|
|
243
|
+
.sort((a, b) => (a === DEFAULT_PROFILE ? -1 : b === DEFAULT_PROFILE ? 1 : a.localeCompare(b)))
|
|
244
|
+
.map((name) => {
|
|
245
|
+
const meta = readProfileMeta(name);
|
|
246
|
+
return {
|
|
247
|
+
name,
|
|
248
|
+
dir: getProfileDir(name),
|
|
249
|
+
port: meta && meta.port > 0 ? meta.port : null,
|
|
250
|
+
isDefault: name === DEFAULT_PROFILE,
|
|
251
|
+
active: name === active,
|
|
252
|
+
};
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Свободный порт для нового профиля: 3782+N, занятые profile.json пропускаются. */
|
|
257
|
+
function allocateProfilePort(): number {
|
|
258
|
+
const used = new Set<number>();
|
|
259
|
+
for (const profile of listProfiles()) {
|
|
260
|
+
if (profile.port) used.add(profile.port);
|
|
261
|
+
}
|
|
262
|
+
for (let port = 3782; port < 3882; port += 1) {
|
|
263
|
+
if (!used.has(port)) return port;
|
|
264
|
+
}
|
|
265
|
+
return 3782 + used.size;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Создаёт профиль: директорию + profile.json. Для default просто гарантирует
|
|
270
|
+
* базовую директорию. Возвращает метаданные профиля.
|
|
271
|
+
*/
|
|
272
|
+
export function createProfile(name: string, port?: number): ProfileMeta {
|
|
273
|
+
const error = validateProfileName(name);
|
|
274
|
+
if (error) throw new Error(error);
|
|
275
|
+
const normalized = sanitizeProfileName(name);
|
|
276
|
+
const dir = getProfileDir(normalized);
|
|
277
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
278
|
+
|
|
279
|
+
const existing = readProfileMeta(normalized);
|
|
280
|
+
const assigned =
|
|
281
|
+
Number.isFinite(Number(port)) && Number(port) > 0
|
|
282
|
+
? Math.floor(Number(port))
|
|
283
|
+
: existing && existing.port > 0
|
|
284
|
+
? existing.port
|
|
285
|
+
: allocateProfilePort();
|
|
286
|
+
|
|
287
|
+
const meta: ProfileMeta = { name: normalized, port: assigned };
|
|
288
|
+
fs.writeFileSync(profileMetaFile(normalized), `${JSON.stringify(meta, null, 2)}\n`, "utf8");
|
|
289
|
+
return meta;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Удаляет профиль (кроме default). Возвращает true, если директория удалена. */
|
|
293
|
+
export async function deleteProfile(name: string): Promise<boolean> {
|
|
294
|
+
if (name === DEFAULT_PROFILE) {
|
|
295
|
+
throw new Error("Профиль default удалить нельзя.");
|
|
296
|
+
}
|
|
297
|
+
const normalized = sanitizeProfileName(name);
|
|
298
|
+
// Имя, которое санитизировалось в default (например, кириллица или пустая строка),
|
|
299
|
+
// не соответствует существующему не-default профилю — такого профиля нет.
|
|
300
|
+
if (normalized === DEFAULT_PROFILE) return false;
|
|
301
|
+
const dir = getProfileDir(normalized);
|
|
302
|
+
if (!fs.existsSync(dir)) return false;
|
|
303
|
+
|
|
304
|
+
// T-05: перед удалением директории профиля снимаем ЕГО задачи ОС,
|
|
305
|
+
// иначе после удаления профиля остаются «сироты» в schtasks/crontab/launchd.
|
|
306
|
+
// Бэкенд создаётся в пространстве имён удаляемого профиля (не активного!),
|
|
307
|
+
// и удаление задач дожидается завершения до fs.rmSync.
|
|
308
|
+
// Динамический import — чтобы не создавать циклическую зависимость
|
|
309
|
+
// profiles.ts → scheduler/index.ts → types.ts (TASK_FOLDER_NAME IIFE).
|
|
310
|
+
// Ошибки снятия не фатальны — директорию всё равно чистим.
|
|
311
|
+
try {
|
|
312
|
+
const { removeScheduledTasksForProfile } = await import("./core/scheduler/index.js");
|
|
313
|
+
await removeScheduledTasksForProfile(normalized);
|
|
314
|
+
} catch {
|
|
315
|
+
// Планировщик недоступен (нет schtasks/launchd/crontab) — не прерываем удаление.
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
319
|
+
|
|
320
|
+
// Если удалили активный профиль — возвращаем маркер на default.
|
|
321
|
+
const base = getBasePluginDir();
|
|
322
|
+
if (readActiveProfileMarker(base) === normalized) {
|
|
323
|
+
setActiveProfile(DEFAULT_PROFILE);
|
|
324
|
+
}
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Переключает активный профиль через файл-маркер. Изменение подхватится при
|
|
330
|
+
* следующем запуске OpenCode (директории вычисляются при загрузке модуля).
|
|
331
|
+
*/
|
|
332
|
+
export function setActiveProfile(name: string): void {
|
|
333
|
+
const normalized = sanitizeProfileName(name);
|
|
334
|
+
if (normalized !== DEFAULT_PROFILE && !fs.existsSync(getProfileDir(normalized))) {
|
|
335
|
+
throw new Error(`Профиль "${normalized}" не существует. Сначала создайте его.`);
|
|
336
|
+
}
|
|
337
|
+
const base = getBasePluginDir();
|
|
338
|
+
fs.mkdirSync(base, { recursive: true });
|
|
339
|
+
fs.writeFileSync(path.join(base, ACTIVE_PROFILE_FILE), `${normalized}\n`, "utf8");
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** true, если профиль переключается переменной окружения (маркер не поможет). */
|
|
343
|
+
export function isProfilePinnedByEnv(): boolean {
|
|
344
|
+
return Boolean(process.env.OPENCODE_SCHEDULER_PROFILE?.trim());
|
|
345
|
+
}
|