agent-steward 0.0.3 → 0.0.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.
Files changed (287) hide show
  1. package/CHANGELOG.md +154 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +54 -9
  4. package/ROADMAP-STRATEGY.md +23 -20
  5. package/ROADMAP.md +140 -143
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  9. package/dist/core/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +18 -1
  14. package/dist/core/execution.d.ts +203 -0
  15. package/dist/core/execution.d.ts.map +1 -0
  16. package/dist/core/execution.js +309 -0
  17. package/dist/core/gate-integrity.d.ts +35 -0
  18. package/dist/core/gate-integrity.d.ts.map +1 -0
  19. package/dist/core/gate-integrity.js +132 -0
  20. package/dist/core/git-trigger.d.ts.map +1 -1
  21. package/dist/core/git-trigger.js +14 -2
  22. package/dist/core/guard-run.d.ts +4 -0
  23. package/dist/core/guard-run.d.ts.map +1 -0
  24. package/dist/core/guard-run.js +101 -0
  25. package/dist/core/guard.d.ts +52 -0
  26. package/dist/core/guard.d.ts.map +1 -0
  27. package/dist/core/guard.js +362 -0
  28. package/dist/core/lock.d.ts +61 -4
  29. package/dist/core/lock.d.ts.map +1 -1
  30. package/dist/core/lock.js +213 -26
  31. package/dist/core/matrix.d.ts.map +1 -1
  32. package/dist/core/matrix.js +75 -15
  33. package/dist/core/mission.d.ts +83 -0
  34. package/dist/core/mission.d.ts.map +1 -0
  35. package/dist/core/mission.js +334 -0
  36. package/dist/core/one-shot.d.ts +5 -1
  37. package/dist/core/one-shot.d.ts.map +1 -1
  38. package/dist/core/one-shot.js +33 -8
  39. package/dist/core/opencode-cli.d.ts +28 -0
  40. package/dist/core/opencode-cli.d.ts.map +1 -0
  41. package/dist/core/opencode-cli.js +74 -0
  42. package/dist/core/opencode-models.d.ts +62 -0
  43. package/dist/core/opencode-models.d.ts.map +1 -0
  44. package/dist/core/opencode-models.js +277 -0
  45. package/dist/core/pipeline-apply.d.ts +38 -0
  46. package/dist/core/pipeline-apply.d.ts.map +1 -0
  47. package/dist/core/pipeline-apply.js +117 -0
  48. package/dist/core/pipeline-io.d.ts +13 -0
  49. package/dist/core/pipeline-io.d.ts.map +1 -0
  50. package/dist/core/pipeline-io.js +64 -0
  51. package/dist/core/pipeline-map.d.ts +46 -0
  52. package/dist/core/pipeline-map.d.ts.map +1 -0
  53. package/dist/core/pipeline-map.js +196 -0
  54. package/dist/core/pipeline-spec.d.ts +109 -0
  55. package/dist/core/pipeline-spec.d.ts.map +1 -0
  56. package/dist/core/pipeline-spec.js +554 -0
  57. package/dist/core/ps-wrapper.d.ts +19 -2
  58. package/dist/core/ps-wrapper.d.ts.map +1 -1
  59. package/dist/core/ps-wrapper.js +261 -63
  60. package/dist/core/record-history.d.ts +15 -0
  61. package/dist/core/record-history.d.ts.map +1 -1
  62. package/dist/core/record-history.js +183 -58
  63. package/dist/core/router/dispatch.d.ts +36 -0
  64. package/dist/core/router/dispatch.d.ts.map +1 -0
  65. package/dist/core/router/dispatch.js +59 -0
  66. package/dist/core/router/escalation.d.ts +47 -0
  67. package/dist/core/router/escalation.d.ts.map +1 -0
  68. package/dist/core/router/escalation.js +87 -0
  69. package/dist/core/router/planner.d.ts +53 -0
  70. package/dist/core/router/planner.d.ts.map +1 -0
  71. package/dist/core/router/planner.js +113 -0
  72. package/dist/core/router/rules.d.ts +46 -0
  73. package/dist/core/router/rules.d.ts.map +1 -0
  74. package/dist/core/router/rules.js +91 -0
  75. package/dist/core/run-panel-api.d.ts +94 -0
  76. package/dist/core/run-panel-api.d.ts.map +1 -0
  77. package/dist/core/run-panel-api.js +169 -0
  78. package/dist/core/schedule-gate.js +5 -1
  79. package/dist/core/schedule-v2.d.ts +34 -0
  80. package/dist/core/schedule-v2.d.ts.map +1 -1
  81. package/dist/core/schedule-v2.js +91 -5
  82. package/dist/core/scheduler/at-fallback.d.ts +55 -2
  83. package/dist/core/scheduler/at-fallback.d.ts.map +1 -1
  84. package/dist/core/scheduler/at-fallback.js +135 -5
  85. package/dist/core/scheduler/linux.d.ts +18 -2
  86. package/dist/core/scheduler/linux.d.ts.map +1 -1
  87. package/dist/core/scheduler/linux.js +63 -20
  88. package/dist/core/scheduler/mac.d.ts +44 -2
  89. package/dist/core/scheduler/mac.d.ts.map +1 -1
  90. package/dist/core/scheduler/mac.js +126 -15
  91. package/dist/core/scheduler/posix.d.ts.map +1 -1
  92. package/dist/core/scheduler/posix.js +25 -1
  93. package/dist/core/scheduler/registry.d.ts +11 -0
  94. package/dist/core/scheduler/registry.d.ts.map +1 -1
  95. package/dist/core/scheduler/registry.js +83 -21
  96. package/dist/core/scheduler/run-now.d.ts +16 -0
  97. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  98. package/dist/core/scheduler/run-now.js +28 -0
  99. package/dist/core/scheduler/windows.d.ts.map +1 -1
  100. package/dist/core/scheduler/windows.js +15 -12
  101. package/dist/core/secrets.d.ts.map +1 -1
  102. package/dist/core/secrets.js +125 -28
  103. package/dist/core/session.d.ts.map +1 -1
  104. package/dist/core/session.js +18 -11
  105. package/dist/core/structured-log.d.ts +7 -1
  106. package/dist/core/structured-log.d.ts.map +1 -1
  107. package/dist/core/task-name.d.ts +24 -0
  108. package/dist/core/task-name.d.ts.map +1 -0
  109. package/dist/core/task-name.js +40 -0
  110. package/dist/core/worktree-run.d.ts +4 -0
  111. package/dist/core/worktree-run.d.ts.map +1 -0
  112. package/dist/core/worktree-run.js +164 -0
  113. package/dist/core/worktree.d.ts +115 -0
  114. package/dist/core/worktree.d.ts.map +1 -0
  115. package/dist/core/worktree.js +462 -0
  116. package/dist/core/wrappers/bash.d.ts +17 -0
  117. package/dist/core/wrappers/bash.d.ts.map +1 -1
  118. package/dist/core/wrappers/bash.js +224 -28
  119. package/dist/db/capability-repo.d.ts +124 -0
  120. package/dist/db/capability-repo.d.ts.map +1 -0
  121. package/dist/db/capability-repo.js +267 -0
  122. package/dist/db/history-repo.d.ts +46 -5
  123. package/dist/db/history-repo.d.ts.map +1 -1
  124. package/dist/db/history-repo.js +107 -25
  125. package/dist/db/index.d.ts +4 -0
  126. package/dist/db/index.d.ts.map +1 -1
  127. package/dist/db/index.js +39 -1
  128. package/dist/db/metrics-repo.js +2 -2
  129. package/dist/db/migrate.d.ts.map +1 -1
  130. package/dist/db/migrate.js +3 -1
  131. package/dist/db/recovery.d.ts.map +1 -1
  132. package/dist/db/recovery.js +5 -4
  133. package/dist/db/run-context.d.ts +103 -0
  134. package/dist/db/run-context.d.ts.map +1 -0
  135. package/dist/db/run-context.js +224 -0
  136. package/dist/db/run-dlq.d.ts +100 -0
  137. package/dist/db/run-dlq.d.ts.map +1 -0
  138. package/dist/db/run-dlq.js +191 -0
  139. package/dist/db/run-journal.d.ts +33 -5
  140. package/dist/db/run-journal.d.ts.map +1 -1
  141. package/dist/db/run-journal.js +78 -14
  142. package/dist/db/run-resume.d.ts +10 -2
  143. package/dist/db/run-resume.d.ts.map +1 -1
  144. package/dist/db/run-resume.js +39 -13
  145. package/dist/db/runs-repo.d.ts +32 -7
  146. package/dist/db/runs-repo.d.ts.map +1 -1
  147. package/dist/db/runs-repo.js +50 -11
  148. package/dist/db/schema.d.ts +2 -2
  149. package/dist/db/schema.d.ts.map +1 -1
  150. package/dist/db/schema.js +216 -3
  151. package/dist/db/settings-repo.d.ts +11 -0
  152. package/dist/db/settings-repo.d.ts.map +1 -1
  153. package/dist/db/settings-repo.js +25 -0
  154. package/dist/db/step-idempotency.d.ts +51 -0
  155. package/dist/db/step-idempotency.d.ts.map +1 -0
  156. package/dist/db/step-idempotency.js +136 -0
  157. package/dist/history.d.ts +1 -1
  158. package/dist/history.d.ts.map +1 -1
  159. package/dist/i18n.d.ts +5 -0
  160. package/dist/i18n.d.ts.map +1 -1
  161. package/dist/i18n.js +11 -4
  162. package/dist/index.d.ts +140 -6
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +480 -18
  165. package/dist/notifications.d.ts +22 -0
  166. package/dist/notifications.d.ts.map +1 -1
  167. package/dist/notifications.js +36 -8
  168. package/dist/profiles.d.ts.map +1 -1
  169. package/dist/profiles.js +25 -4
  170. package/dist/rpc.d.ts +924 -0
  171. package/dist/rpc.d.ts.map +1 -1
  172. package/dist/rpc.js +352 -0
  173. package/dist/server.d.ts +46 -0
  174. package/dist/server.d.ts.map +1 -1
  175. package/dist/server.js +172 -53
  176. package/dist/settings.d.ts +2 -2
  177. package/dist/settings.d.ts.map +1 -1
  178. package/dist/settings.js +3 -3
  179. package/dist/shared/jobs-view.d.ts +1 -1
  180. package/dist/shared/jobs-view.d.ts.map +1 -1
  181. package/dist/shared/jobs-view.js +2 -0
  182. package/dist/task-transfer.d.ts +16 -0
  183. package/dist/task-transfer.d.ts.map +1 -1
  184. package/dist/task-transfer.js +16 -0
  185. package/dist/types.d.ts.map +1 -1
  186. package/dist/types.js +7 -0
  187. package/dist/workspaces.d.ts +25 -3
  188. package/dist/workspaces.d.ts.map +1 -1
  189. package/dist/workspaces.js +43 -8
  190. package/docs/ARCHITECTURE.md +498 -58
  191. package/docs/COMPATIBILITY.md +2 -2
  192. package/docs/CONCEPT.md +185 -91
  193. package/docs/CROSS_PLATFORM.ru.md +20 -0
  194. package/docs/CROSS_PLATFORM.zh.md +18 -0
  195. package/docs/EXECUTION-LOOP.md +211 -0
  196. package/docs/FEATURES.md +65 -4
  197. package/docs/FEATURES.zh.md +52 -4
  198. package/docs/MIGRATION.md +2 -2
  199. package/docs/PIPELINE.md +293 -0
  200. package/docs/README.ru.md +44 -5
  201. package/docs/README.zh.md +46 -6
  202. package/docs/SAFETY.md +142 -0
  203. package/docs/SAVINGS.md +29 -0
  204. package/docs/SAVINGS.ru.md +29 -0
  205. package/docs/SAVINGS.zh.md +18 -0
  206. package/gui-experimental.cjs +9 -8
  207. package/locales/en.json +84 -1
  208. package/locales/ru.json +84 -1
  209. package/locales/zh.json +84 -1
  210. package/opencode.pipeline.yaml +35 -0
  211. package/package.json +46 -2
  212. package/scripts/audit-bundle.mjs +215 -0
  213. package/scripts/test-home.mjs +83 -0
  214. package/src/cli.ts +412 -0
  215. package/src/core/dlq-api.ts +98 -0
  216. package/src/core/dry-run.ts +27 -3
  217. package/src/core/execution.ts +538 -0
  218. package/src/core/file-watcher.ts +2 -2
  219. package/src/core/gate-integrity.ts +160 -0
  220. package/src/core/git-trigger.ts +18 -5
  221. package/src/core/guard-run.ts +119 -0
  222. package/src/core/guard.ts +431 -0
  223. package/src/core/lock.ts +244 -30
  224. package/src/core/matrix.ts +95 -50
  225. package/src/core/mission.ts +485 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/one-shot.ts +36 -8
  228. package/src/core/opencode-cli.ts +103 -0
  229. package/src/core/opencode-models.ts +315 -0
  230. package/src/core/pipeline-apply.ts +158 -0
  231. package/src/core/pipeline-io.ts +79 -0
  232. package/src/core/pipeline-map.ts +264 -0
  233. package/src/core/pipeline-spec.ts +775 -0
  234. package/src/core/ps-wrapper.ts +274 -64
  235. package/src/core/record-history.ts +229 -104
  236. package/src/core/router/dispatch.ts +94 -0
  237. package/src/core/router/escalation.ts +129 -0
  238. package/src/core/router/planner.ts +166 -0
  239. package/src/core/router/rules.ts +115 -0
  240. package/src/core/run-panel-api.ts +262 -0
  241. package/src/core/schedule-gate.ts +7 -3
  242. package/src/core/schedule-v2.ts +114 -5
  243. package/src/core/scheduler/at-fallback.ts +190 -5
  244. package/src/core/scheduler/linux.ts +72 -21
  245. package/src/core/scheduler/logs.ts +2 -2
  246. package/src/core/scheduler/mac.ts +174 -14
  247. package/src/core/scheduler/posix.ts +20 -1
  248. package/src/core/scheduler/registry.ts +107 -26
  249. package/src/core/scheduler/run-now.ts +32 -0
  250. package/src/core/scheduler/windows.ts +19 -15
  251. package/src/core/secrets.ts +131 -31
  252. package/src/core/session.ts +23 -10
  253. package/src/core/structured-log.ts +22 -5
  254. package/src/core/task-name.ts +67 -0
  255. package/src/core/telegram.ts +2 -2
  256. package/src/core/triage-worker.ts +7 -7
  257. package/src/core/triage.ts +2 -2
  258. package/src/core/worktree-run.ts +199 -0
  259. package/src/core/worktree.ts +600 -0
  260. package/src/core/wrappers/bash.ts +239 -27
  261. package/src/db/capability-repo.ts +402 -0
  262. package/src/db/history-repo.ts +151 -22
  263. package/src/db/index.ts +37 -1
  264. package/src/db/metrics-repo.ts +2 -2
  265. package/src/db/migrate.ts +3 -1
  266. package/src/db/recovery.ts +5 -4
  267. package/src/db/run-context.ts +370 -0
  268. package/src/db/run-dlq.ts +310 -0
  269. package/src/db/run-journal.ts +100 -13
  270. package/src/db/run-resume.ts +65 -13
  271. package/src/db/runs-repo.ts +66 -13
  272. package/src/db/schema.ts +218 -3
  273. package/src/db/settings-repo.ts +31 -0
  274. package/src/db/step-idempotency.ts +185 -0
  275. package/src/gui.tsx +692 -13
  276. package/src/history.ts +1 -1
  277. package/src/i18n.ts +12 -4
  278. package/src/index.ts +648 -8
  279. package/src/notifications.ts +38 -8
  280. package/src/profiles.ts +26 -4
  281. package/src/rpc.ts +379 -0
  282. package/src/server.ts +206 -54
  283. package/src/settings.ts +5 -5
  284. package/src/shared/jobs-view.ts +3 -1
  285. package/src/task-transfer.ts +31 -0
  286. package/src/types.ts +9 -0
  287. package/src/workspaces.ts +58 -9
@@ -0,0 +1,485 @@
1
+ /**
2
+ * AB-8: ad-hoc миссия (`run_mission`) — полоса B execution model.
3
+ *
4
+ * Миссия проходит тот же путь, что и зарегистрированная задача:
5
+ * `createRun → план → маршрут → исполнение → GATE → ledger`. Отличие только
6
+ * в источнике входа: задача не создаётся и не регистрируется в планировщике
7
+ * ОС. Исполнение идёт через обёртку (lock, таймаут, политика прав, Quality
8
+ * Gate, запись истории), но без `schtasks`/`crontab`/`launchd`.
9
+ */
10
+
11
+ import { spawn } from "node:child_process";
12
+ import crypto from "node:crypto";
13
+ import fs from "node:fs/promises";
14
+ import { createRequire } from "node:module";
15
+ import path from "node:path";
16
+ import { LOG_DIR, sanitizeName } from "../types.js";
17
+ import {
18
+ buildExecutionPlan,
19
+ createAdHocRunContext,
20
+ describeExecutionPlan,
21
+ executeExecutionPlan,
22
+ type ExecutionPlan,
23
+ type ExecutionResult,
24
+ type RunContext,
25
+ type RunPermissionPolicy,
26
+ type StepExecutor,
27
+ } from "./execution.js";
28
+ import { buildOpencodeConfig } from "./permissions.js";
29
+ import {
30
+ ensureWrapper,
31
+ lockFilePath,
32
+ writePromptFile,
33
+ writeWrapperCmd,
34
+ } from "./ps-wrapper.js";
35
+ import {
36
+ generateSessionId,
37
+ normalizeSessionMode,
38
+ sessionStatePath,
39
+ writeSessionStateFile,
40
+ type SessionMode,
41
+ } from "./session.js";
42
+ import { writeBashWrapper } from "./wrappers/bash.js";
43
+
44
+ /** AB-8.1: спецификация ad-hoc миссии (цель + safety-контракт). */
45
+ export interface MissionSpec {
46
+ /** Цель миссии — тот же промпт, что получил бы OpenCode. */
47
+ prompt: string;
48
+ /** Рабочая директория; по умолчанию — cwd процесса. */
49
+ cwd?: string;
50
+ /** Имя запуска в ledger; по умолчанию генерируется `ad-hoc-*`. */
51
+ taskName?: string;
52
+ /** Тип задачи для маршрутизатора; по умолчанию `mission` (local/direct). */
53
+ taskType?: string;
54
+ /** Модель OpenCode (пусто — модель по умолчанию). */
55
+ model?: string;
56
+ /** Режим сессии OpenCode. */
57
+ session?: SessionMode;
58
+ /** Идентификатор сессии для `session=reuse`. */
59
+ sessionId?: string;
60
+ /** Таймаут исполнения в секундах (по умолчанию 3600). */
61
+ timeoutSeconds?: number;
62
+ /** Quality Gate: команда, ненулевой код которой проваливает миссию. */
63
+ gate?: string;
64
+ /** Таймаут Quality Gate в секундах (по умолчанию 300). */
65
+ gateTimeoutSeconds?: number;
66
+ /** Политика прав: hybrid (по умолчанию), secure, legacy. */
67
+ policy?: RunPermissionPolicy;
68
+ /** Allowlist инструментов; непустой список блокирует остальные. */
69
+ allowedTools?: string[];
70
+ /** Denylist инструментов; выигрывает у allowlist. */
71
+ deniedTools?: string[];
72
+ /** Только построить план и показать трассировку, не исполняя. */
73
+ dryRun?: boolean;
74
+ }
75
+
76
+ /** Результат ad-hoc миссии. */
77
+ export interface MissionResult {
78
+ success: boolean;
79
+ dryRun: boolean;
80
+ runId: string | null;
81
+ status: ExecutionResult["status"] | "planned";
82
+ plan: ExecutionPlan;
83
+ description: string;
84
+ steps: ExecutionResult["steps"];
85
+ error: string | null;
86
+ logFile: string | null;
87
+ }
88
+
89
+ /** Зависимости для тестов: позволяют подменить исполнение без OpenCode. */
90
+ export interface MissionDependencies {
91
+ executor?: StepExecutor;
92
+ /** Хук после подготовки: тест может проверить отсутствие задач в ОС. */
93
+ onPrepared?: (info: { taskName: string; cwd: string }) => void;
94
+ }
95
+
96
+ const DEFAULT_TIMEOUT_SECONDS = 3600;
97
+ const MAX_TIMEOUT_SECONDS = 24 * 60 * 60;
98
+
99
+ /** Активные ad-hoc миссии по workspace — защита от двух миссий в одном репо. */
100
+ const activeWorkspaces = new Map<string, string>();
101
+
102
+ const requireFromCore = createRequire(import.meta.url);
103
+
104
+ /** Путь к скомпилированному record-history.js (как в index.ts). */
105
+ function recorderPath(): string {
106
+ const resolved = requireFromCore.resolve("./record-history.js");
107
+ if (!resolved.endsWith(".ts")) return resolved;
108
+ return resolved
109
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
110
+ .replace(/\.ts$/, ".js");
111
+ }
112
+
113
+ function assertNonEmpty(value: unknown, label: string): string {
114
+ if (typeof value !== "string" || value.trim() === "") {
115
+ throw new Error(`Пустое поле миссии: ${label}.`);
116
+ }
117
+ return value.trim();
118
+ }
119
+
120
+ function positiveInt(value: unknown, label: string, fallback: number): number {
121
+ if (value === undefined || value === null) return fallback;
122
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
123
+ throw new Error(`Поле миссии "${label}" должно быть целым положительным числом.`);
124
+ }
125
+ return Math.min(value, MAX_TIMEOUT_SECONDS);
126
+ }
127
+
128
+ function normalizeTools(value: unknown, label: string): string[] | undefined {
129
+ if (value === undefined) return undefined;
130
+ if (!Array.isArray(value)) {
131
+ throw new Error(`Поле миссии "${label}" должно быть массивом строк.`);
132
+ }
133
+ const list = value
134
+ .filter((item): item is string => typeof item === "string")
135
+ .map((item) => item.trim())
136
+ .filter(Boolean);
137
+ return list.length > 0 ? list : undefined;
138
+ }
139
+
140
+ function newMissionName(): string {
141
+ const stamp = Date.now().toString(36);
142
+ const random = crypto.randomBytes(4).toString("hex");
143
+ return `ad-hoc-${stamp}-${random}`;
144
+ }
145
+
146
+ /**
147
+ * AB-8.1: валидирует и нормализует вход. Возвращает безопасную копию спеки,
148
+ * чтобы CLI/RPC/GUI не могли передать нестроковые поля в обёртку.
149
+ */
150
+ export function normalizeMissionSpec(input: MissionSpec): MissionSpec {
151
+ if (!input || typeof input !== "object") {
152
+ throw new Error("Спецификация миссии должна быть объектом.");
153
+ }
154
+ const prompt = assertNonEmpty(input.prompt, "prompt");
155
+ const cwd = input.cwd?.trim() ? path.resolve(input.cwd.trim()) : process.cwd();
156
+ const taskName = input.taskName?.trim() ? input.taskName.trim() : undefined;
157
+ if (taskName && taskName.length > 200) {
158
+ throw new Error("Имя миссии длиннее 200 символов.");
159
+ }
160
+ const session = normalizeSessionMode(input.session);
161
+ if (!session) {
162
+ throw new Error('Поле "session" должно быть new, reuse или last.');
163
+ }
164
+ if (session === "reuse" && input.sessionId !== undefined && !/^ses_[A-Za-z0-9]{10,64}$/.test(input.sessionId)) {
165
+ throw new Error('Поле "sessionId" должно иметь формат ses_<id>.');
166
+ }
167
+ const policy = input.policy ?? "hybrid";
168
+ if (policy !== "hybrid" && policy !== "secure" && policy !== "legacy") {
169
+ throw new Error('Поле "policy" должно быть hybrid, secure или legacy.');
170
+ }
171
+ const allowedTools = normalizeTools(input.allowedTools, "allowedTools");
172
+ const deniedTools = normalizeTools(input.deniedTools, "deniedTools");
173
+ const denied = new Set((deniedTools ?? []).map((tool) => tool.toLowerCase()));
174
+ const conflict = (allowedTools ?? []).find((tool) => denied.has(tool.toLowerCase()));
175
+ if (conflict) {
176
+ throw new Error(`Инструмент "${conflict}" одновременно разрешён и запрещён.`);
177
+ }
178
+ return {
179
+ prompt,
180
+ cwd,
181
+ taskName,
182
+ taskType: input.taskType?.trim() || undefined,
183
+ model: input.model?.trim() || undefined,
184
+ session,
185
+ sessionId: input.sessionId?.trim() || undefined,
186
+ timeoutSeconds: positiveInt(
187
+ input.timeoutSeconds,
188
+ "timeoutSeconds",
189
+ DEFAULT_TIMEOUT_SECONDS,
190
+ ),
191
+ gate: input.gate?.trim() || undefined,
192
+ gateTimeoutSeconds:
193
+ input.gateTimeoutSeconds === undefined
194
+ ? undefined
195
+ : positiveInt(input.gateTimeoutSeconds, "gateTimeoutSeconds", 300),
196
+ policy,
197
+ allowedTools,
198
+ deniedTools,
199
+ dryRun: input.dryRun === true,
200
+ };
201
+ }
202
+
203
+ /** Создаёт RunContext ad-hoc миссии (без task definition). */
204
+ export function createMissionContext(spec: MissionSpec): RunContext {
205
+ return createAdHocRunContext(spec.prompt, {
206
+ cwd: spec.cwd,
207
+ taskName: spec.taskName,
208
+ taskType: spec.taskType ?? "mission",
209
+ policy: spec.policy ?? "hybrid",
210
+ profile: {
211
+ model: spec.model,
212
+ session: spec.session ?? "new",
213
+ sessionId: spec.sessionId,
214
+ },
215
+ safety: {
216
+ policy: spec.policy ?? "hybrid",
217
+ allowedTools: spec.allowedTools,
218
+ deniedTools: spec.deniedTools,
219
+ },
220
+ metadata: {
221
+ mission: true,
222
+ gate: spec.gate ?? null,
223
+ timeoutSeconds: spec.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS,
224
+ },
225
+ });
226
+ }
227
+
228
+ interface WrapperPlan {
229
+ wrapperPath: string;
230
+ logFile: string;
231
+ }
232
+
233
+ /** Готовит обёртку с lock/таймаутом/политикой/Quality Gate, но без ОС. */
234
+ async function prepareWrapper(
235
+ spec: MissionSpec,
236
+ context: RunContext,
237
+ taskName: string,
238
+ ): Promise<WrapperPlan> {
239
+ const sanitized = sanitizeName(taskName);
240
+ const logFile = path.join(LOG_DIR, `${sanitized}.log`);
241
+ const promptFile = await writePromptFile(taskName, spec.prompt);
242
+ await fs.mkdir(LOG_DIR, { recursive: true });
243
+ try {
244
+ await fs.writeFile(logFile, "", "utf8");
245
+ } catch (error) {
246
+ // Обёртки пишут лог через >> и создают файл сами: предварительная очистка
247
+ // нужна только чтобы убрать лог прошлого прогона. Не срываем миссию из-за
248
+ // прав доступа к каталогу логов.
249
+ console.warn(
250
+ `[agent-steward] Не удалось очистить лог миссии (${logFile}): ${error instanceof Error ? error.message : String(error)}`,
251
+ );
252
+ }
253
+ const lockFile = lockFilePath(taskName);
254
+ const sessionMode = spec.session ?? "new";
255
+ let sessionId = spec.sessionId;
256
+ if (sessionMode === "reuse" && !sessionId) {
257
+ sessionId = generateSessionId();
258
+ }
259
+ if (sessionMode === "reuse") {
260
+ await writeSessionStateFile(taskName, sessionId);
261
+ }
262
+ const sessionFile = sessionMode === "reuse" ? sessionStatePath(taskName) : undefined;
263
+ const timeoutSeconds = spec.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
264
+
265
+ if (process.platform === "win32") {
266
+ const permissionsConfig = buildOpencodeConfig({
267
+ policy: context.safety.policy,
268
+ allowedTools: spec.allowedTools,
269
+ deniedTools: spec.deniedTools,
270
+ });
271
+ await ensureWrapper();
272
+ const wrapperPath = await writeWrapperCmd(
273
+ sanitized,
274
+ taskName,
275
+ promptFile,
276
+ timeoutSeconds,
277
+ lockFile,
278
+ context.cwd,
279
+ logFile,
280
+ recorderPath(),
281
+ spec.gate,
282
+ spec.model,
283
+ undefined,
284
+ undefined,
285
+ undefined,
286
+ spec.allowedTools,
287
+ spec.deniedTools,
288
+ undefined,
289
+ undefined,
290
+ sessionMode,
291
+ sessionId,
292
+ spec.gateTimeoutSeconds,
293
+ permissionsConfig,
294
+ { policy: context.safety.policy, legacyShell: false },
295
+ sessionFile,
296
+ );
297
+ return { wrapperPath, logFile };
298
+ }
299
+
300
+ const wrapperPath = await writeBashWrapper({
301
+ sanitizedName: sanitized,
302
+ taskName,
303
+ promptFile,
304
+ timeoutSeconds,
305
+ lockFile,
306
+ workdir: context.cwd,
307
+ logFile,
308
+ recorderFile: recorderPath(),
309
+ qualityGate: spec.gate,
310
+ model: spec.model,
311
+ policy: context.safety.policy,
312
+ allowedTools: spec.allowedTools,
313
+ deniedTools: spec.deniedTools,
314
+ sessionMode,
315
+ sessionId,
316
+ sessionFile,
317
+ gateTimeoutSeconds: spec.gateTimeoutSeconds,
318
+ });
319
+ return { wrapperPath, logFile };
320
+ }
321
+
322
+ /** Прямой запуск обёртки: ОС-задача не создаётся, процесс ждём здесь. */
323
+ async function runWrapperProcess(
324
+ wrapperPath: string,
325
+ cwd: string,
326
+ timeoutSeconds: number,
327
+ ): Promise<{ output: string; error: string | null }> {
328
+ const timeoutMs = (timeoutSeconds + 120) * 1000;
329
+ return new Promise((resolve) => {
330
+ const child =
331
+ process.platform === "win32"
332
+ ? spawn(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `"${wrapperPath}"`], {
333
+ cwd,
334
+ windowsHide: true,
335
+ env: process.env,
336
+ })
337
+ : spawn("bash", [wrapperPath], {
338
+ cwd,
339
+ windowsHide: true,
340
+ env: process.env,
341
+ });
342
+
343
+ let stdout = "";
344
+ let stderr = "";
345
+ let settled = false;
346
+ const append = (target: "out" | "err", chunk: Buffer) => {
347
+ const text = chunk.toString("utf8");
348
+ if (target === "out") stdout = (stdout + text).slice(-200_000);
349
+ else stderr = (stderr + text).slice(-200_000);
350
+ };
351
+ child.stdout?.on("data", (chunk: Buffer) => append("out", chunk));
352
+ child.stderr?.on("data", (chunk: Buffer) => append("err", chunk));
353
+
354
+ const timer = setTimeout(() => {
355
+ if (settled) return;
356
+ settled = true;
357
+ child.kill("SIGKILL");
358
+ resolve({
359
+ output: stdout,
360
+ error: `Миссия превысила внешний таймаут ${timeoutSeconds + 120} с.`,
361
+ });
362
+ }, timeoutMs);
363
+ timer.unref?.();
364
+
365
+ const finish = (error: string | null) => {
366
+ if (settled) return;
367
+ settled = true;
368
+ clearTimeout(timer);
369
+ resolve({ output: [stdout.trim(), stderr.trim()].filter(Boolean).join("\n"), error });
370
+ };
371
+
372
+ child.on("error", (error) => finish(error.message));
373
+ child.on("close", (code, signal) => {
374
+ if (code === 0) {
375
+ finish(null);
376
+ return;
377
+ }
378
+ finish(
379
+ `Обёртка миссии завершилась с кодом ${code ?? "null"}${
380
+ signal ? ` (сигнал ${signal})` : ""
381
+ }.`,
382
+ );
383
+ });
384
+ });
385
+ }
386
+
387
+ function createWrapperExecutor(
388
+ wrapperPath: string,
389
+ spec: MissionSpec,
390
+ ): StepExecutor {
391
+ return {
392
+ id: "mission-wrapper",
393
+ supports: (route) => route.executor !== null,
394
+ async execute() {
395
+ const { output, error } = await runWrapperProcess(
396
+ wrapperPath,
397
+ spec.cwd ?? process.cwd(),
398
+ spec.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS,
399
+ );
400
+ return error ? { output, error } : { output };
401
+ },
402
+ };
403
+ }
404
+
405
+ /**
406
+ * AB-8: единая точка входа ad-hoc миссии для CLI, RPC и GUI.
407
+ *
408
+ * Инварианты EXECUTION-LOOP §2.1: нет записи в планировщике ОС, работают
409
+ * GATE, политика прав, ledger (`runs`/`run_steps`) и аудит; параллельные
410
+ * обычные миссии в одном workspace не допускаются.
411
+ *
412
+ * W-3 (контракт dryRun): `dryRun: true` строит план и описание, но не захватывает
413
+ * `activeWorkspaces` и не пишет ledger (`runs`/`run_steps`) — это контракт, а не
414
+ * утечка контекста. Поэтому несколько dry-run в одном `cwd` проходят параллельно.
415
+ */
416
+ export async function runMission(
417
+ input: MissionSpec,
418
+ dependencies: MissionDependencies = {},
419
+ ): Promise<MissionResult> {
420
+ const spec = normalizeMissionSpec(input);
421
+ const taskName = spec.taskName ?? newMissionName();
422
+ spec.taskName = taskName;
423
+ const context = createMissionContext(spec);
424
+ const plan = await buildExecutionPlan(context);
425
+ const description = describeExecutionPlan(plan);
426
+
427
+ if (spec.dryRun) {
428
+ dependencies.onPrepared?.({ taskName, cwd: context.cwd });
429
+ return {
430
+ success: true,
431
+ dryRun: true,
432
+ runId: null,
433
+ status: "planned",
434
+ plan,
435
+ description,
436
+ steps: [],
437
+ error: null,
438
+ logFile: null,
439
+ };
440
+ }
441
+
442
+ const workspaceKey = path.resolve(context.cwd);
443
+ const running = activeWorkspaces.get(workspaceKey);
444
+ if (running) {
445
+ throw new Error(
446
+ `В workspace ${workspaceKey} уже выполняется миссия "${running}". Дождитесь её завершения.`,
447
+ );
448
+ }
449
+ activeWorkspaces.set(workspaceKey, taskName);
450
+
451
+ try {
452
+ let executor = dependencies.executor;
453
+ let logFile: string | null = null;
454
+ if (!executor) {
455
+ const prepared = await prepareWrapper(spec, context, taskName);
456
+ logFile = prepared.logFile;
457
+ executor = createWrapperExecutor(prepared.wrapperPath, spec);
458
+ }
459
+ dependencies.onPrepared?.({ taskName, cwd: context.cwd });
460
+
461
+ const result = await executeExecutionPlan(plan, {
462
+ executors: [executor],
463
+ stopOnError: true,
464
+ metadata: {
465
+ adHoc: true,
466
+ gate: spec.gate ?? null,
467
+ timeoutSeconds: spec.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS,
468
+ },
469
+ });
470
+
471
+ return {
472
+ success: result.status === "passed",
473
+ dryRun: false,
474
+ runId: result.runId,
475
+ status: result.status,
476
+ plan,
477
+ description,
478
+ steps: result.steps,
479
+ error: result.error,
480
+ logFile,
481
+ };
482
+ } finally {
483
+ activeWorkspaces.delete(workspaceKey);
484
+ }
485
+ }
@@ -148,7 +148,7 @@ export async function sendNativeNotification(
148
148
  });
149
149
  }
150
150
  return { success: true };
151
- } catch (err: any) {
151
+ } catch (err: unknown) {
152
152
  return {
153
153
  success: false,
154
154
  error: err instanceof Error ? err.message : String(err),
@@ -143,17 +143,45 @@ export function buildWindowsOneShotFlags(
143
143
  /**
144
144
  * Форматирует Date по шаблону локали Windows (.NET-формат, как возвращает
145
145
  * (Get-Culture).DateTimeFormat.ShortDatePattern). Поддерживает d/dd, M/MM,
146
- * y/yy/yyyy. Неизвестные символы копируются как есть.
146
+ * MMM/MMMM (название месяца), y/yy/yyyy. Неизвестные символы копируются как есть.
147
+ *
148
+ * P2-26: раньше последовательные replace(/MM/) и replace(/M/) превращали
149
+ * «MMM» в число месяца («2030. 011 2.»). Теперь разбор идёт одним проходом
150
+ * по токенам, поэтому MMM/MMMM не пересекаются с MM/M.
147
151
  */
148
152
  export function formatDateByLocalePattern(date: Date, pattern: string): string {
149
153
  const pad2 = (v: number) => String(v).padStart(2, "0");
150
- return pattern
151
- .replace(/yyyy/g, String(date.getFullYear()))
152
- .replace(/yy/g, String(date.getFullYear()).slice(-2))
153
- .replace(/MM/g, pad2(date.getMonth() + 1))
154
- .replace(/M/g, String(date.getMonth() + 1))
155
- .replace(/dd/g, pad2(date.getDate()))
156
- .replace(/d/g, String(date.getDate()));
154
+ const monthShort = new Intl.DateTimeFormat(undefined, {
155
+ month: "short",
156
+ }).format(date);
157
+ const monthLong = new Intl.DateTimeFormat(undefined, {
158
+ month: "long",
159
+ }).format(date);
160
+ return pattern.replace(
161
+ /yyyy|yy|MMMM|MMM|MM|M|dd|d/g,
162
+ (token) => {
163
+ switch (token) {
164
+ case "yyyy":
165
+ return String(date.getFullYear());
166
+ case "yy":
167
+ return String(date.getFullYear()).slice(-2);
168
+ case "MMMM":
169
+ return monthLong;
170
+ case "MMM":
171
+ return monthShort;
172
+ case "MM":
173
+ return pad2(date.getMonth() + 1);
174
+ case "M":
175
+ return String(date.getMonth() + 1);
176
+ case "dd":
177
+ return pad2(date.getDate());
178
+ case "d":
179
+ return String(date.getDate());
180
+ default:
181
+ return token;
182
+ }
183
+ },
184
+ );
157
185
  }
158
186
 
159
187
  /** Формат `at -t`: YYYYMMDDHHMM в локальном времени системы. */
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Кроссплатформенный запуск OpenCode CLI.
3
+ *
4
+ * На Windows `opencode` — это `opencode.cmd`. Node с 18.20/20.12 запрещает
5
+ * запускать `.cmd`/`.bat` через `execFile` без shell (EINVAL), а имя без
6
+ * расширения не находится вовсе (ENOENT). Поэтому на Windows команда идёт
7
+ * через `cmd.exe /d /s /c` — ровно так же, как в `opencode-models.ts`.
8
+ *
9
+ * Модуль не бросает: результат запуска возвращается объектом, чтобы вызывающий
10
+ * сам решал, писать предупреждение или продолжать молча.
11
+ */
12
+ import { execFile } from "node:child_process";
13
+
14
+ /** Готовая команда для `execFile`/`execFileSync`. */
15
+ export interface OpencodeCommand {
16
+ file: string;
17
+ args: string[];
18
+ }
19
+
20
+ /** Аргументы без спецсимволов cmd.exe можно передавать как есть. */
21
+ const SAFE_ARG = /^[A-Za-z0-9_.,:@/\\+=-]+$/;
22
+
23
+ /** Результат запуска CLI. */
24
+ export interface RunOpencodeResult {
25
+ ok: boolean;
26
+ stdout: string;
27
+ stderr: string;
28
+ /** Текст ошибки запуска (только при ok = false). */
29
+ error?: string;
30
+ }
31
+
32
+ /**
33
+ * Экранирует аргумент для командной строки cmd.exe.
34
+ * Бросает на переводы строк: они разрывают команду на две.
35
+ */
36
+ export function quoteCmdArg(arg: string): string {
37
+ if (/[\r\n]/.test(arg)) {
38
+ throw new Error("Аргумент командной строки не может содержать перевод строки");
39
+ }
40
+ if (SAFE_ARG.test(arg)) return arg;
41
+ return `"${arg.replace(/"/g, '""')}"`;
42
+ }
43
+
44
+ /** Команда запуска OpenCode для указанной платформы (чистая функция). */
45
+ export function opencodeCommandFor(
46
+ platform: NodeJS.Platform,
47
+ args: string[],
48
+ ): OpencodeCommand {
49
+ if (platform !== "win32") return { file: "opencode", args: args.slice() };
50
+ const line = ["opencode", ...args].map(quoteCmdArg).join(" ");
51
+ return { file: "cmd.exe", args: ["/d", "/s", "/c", line] };
52
+ }
53
+
54
+ /** Команда запуска OpenCode на текущей платформе. */
55
+ export function opencodeCommand(args: string[]): OpencodeCommand {
56
+ return opencodeCommandFor(process.platform, args);
57
+ }
58
+
59
+ /**
60
+ * Запускает OpenCode CLI и ждёт завершения. Никогда не бросает.
61
+ * `timeoutMs` защищает от зависшего процесса: CLI не должен держать ротацию.
62
+ */
63
+ export function runOpencode(
64
+ args: string[],
65
+ timeoutMs = 30_000,
66
+ ): Promise<RunOpencodeResult> {
67
+ let command: OpencodeCommand;
68
+ try {
69
+ command = opencodeCommand(args);
70
+ } catch (error) {
71
+ return Promise.resolve({
72
+ ok: false,
73
+ stdout: "",
74
+ stderr: "",
75
+ error: error instanceof Error ? error.message : String(error),
76
+ });
77
+ }
78
+
79
+ return new Promise<RunOpencodeResult>((resolve) => {
80
+ execFile(
81
+ command.file,
82
+ command.args,
83
+ {
84
+ timeout: timeoutMs,
85
+ windowsHide: true,
86
+ encoding: "utf8",
87
+ maxBuffer: 4 * 1024 * 1024,
88
+ },
89
+ (error, stdout, stderr) => {
90
+ if (error) {
91
+ resolve({
92
+ ok: false,
93
+ stdout: String(stdout ?? ""),
94
+ stderr: String(stderr ?? ""),
95
+ error: error.message,
96
+ });
97
+ return;
98
+ }
99
+ resolve({ ok: true, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
100
+ },
101
+ );
102
+ });
103
+ }