agent-steward 0.0.2 → 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.
Files changed (180) hide show
  1. package/CHANGELOG.md +25 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +9 -8
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +114 -999
  6. package/dist/core/cron-to-schtasks.d.ts +0 -8
  7. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  8. package/dist/core/cron-to-schtasks.js +11 -86
  9. package/dist/core/dry-run.js +1 -1
  10. package/dist/core/file-watcher.js +9 -9
  11. package/dist/core/git-trigger.js +4 -4
  12. package/dist/core/lock.js +2 -4
  13. package/dist/core/one-shot.d.ts +27 -5
  14. package/dist/core/one-shot.d.ts.map +1 -1
  15. package/dist/core/one-shot.js +53 -10
  16. package/dist/core/otel.js +2 -2
  17. package/dist/core/ps-wrapper.d.ts +1 -1
  18. package/dist/core/ps-wrapper.d.ts.map +1 -1
  19. package/dist/core/ps-wrapper.js +55 -35
  20. package/dist/core/record-history.js +22 -22
  21. package/dist/core/schedule-v2.d.ts +2 -2
  22. package/dist/core/schedule-v2.d.ts.map +1 -1
  23. package/dist/core/schedule-v2.js +7 -7
  24. package/dist/core/scheduler/at-fallback.d.ts +42 -0
  25. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  26. package/dist/core/scheduler/at-fallback.js +70 -0
  27. package/dist/core/scheduler/linux.d.ts +3 -1
  28. package/dist/core/scheduler/linux.d.ts.map +1 -1
  29. package/dist/core/scheduler/linux.js +43 -7
  30. package/dist/core/scheduler/mac.d.ts +14 -8
  31. package/dist/core/scheduler/mac.d.ts.map +1 -1
  32. package/dist/core/scheduler/mac.js +71 -22
  33. package/dist/core/scheduler/posix.d.ts.map +1 -1
  34. package/dist/core/scheduler/posix.js +12 -1
  35. package/dist/core/scheduler/registry.d.ts +2 -0
  36. package/dist/core/scheduler/registry.d.ts.map +1 -1
  37. package/dist/core/scheduler/windows.d.ts +16 -3
  38. package/dist/core/scheduler/windows.d.ts.map +1 -1
  39. package/dist/core/scheduler/windows.js +249 -96
  40. package/dist/core/secrets.js +2 -2
  41. package/dist/core/self-analysis.js +55 -55
  42. package/dist/core/summary.js +1 -1
  43. package/dist/core/triage-chain.js +1 -1
  44. package/dist/core/triage-worker.js +2 -2
  45. package/dist/core/triage.js +1 -1
  46. package/dist/core/wrappers/bash.js +33 -33
  47. package/dist/db/index.d.ts +2 -0
  48. package/dist/db/index.d.ts.map +1 -1
  49. package/dist/db/index.js +9 -1
  50. package/dist/db/run-journal.d.ts +60 -0
  51. package/dist/db/run-journal.d.ts.map +1 -0
  52. package/dist/db/run-journal.js +143 -0
  53. package/dist/db/run-resume.d.ts +48 -0
  54. package/dist/db/run-resume.d.ts.map +1 -0
  55. package/dist/db/run-resume.js +137 -0
  56. package/dist/db/runs-repo.d.ts +120 -0
  57. package/dist/db/runs-repo.d.ts.map +1 -0
  58. package/dist/db/runs-repo.js +319 -0
  59. package/dist/db/schema.d.ts +16 -2
  60. package/dist/db/schema.d.ts.map +1 -1
  61. package/dist/db/schema.js +190 -35
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +66 -36
  65. package/dist/notifications.js +18 -18
  66. package/dist/profiles.d.ts +7 -3
  67. package/dist/profiles.d.ts.map +1 -1
  68. package/dist/profiles.js +85 -7
  69. package/dist/rpc.d.ts +109 -0
  70. package/dist/rpc.d.ts.map +1 -1
  71. package/dist/rpc.js +89 -0
  72. package/dist/server.d.ts +2 -2
  73. package/dist/server.d.ts.map +1 -1
  74. package/dist/server.js +20 -19
  75. package/dist/shared/jobs-view.d.ts.map +1 -1
  76. package/dist/skill.js +1 -1
  77. package/dist/task-transfer.d.ts +1 -1
  78. package/dist/task-transfer.d.ts.map +1 -1
  79. package/dist/task-transfer.js +14 -10
  80. package/dist/types.d.ts +20 -4
  81. package/dist/types.d.ts.map +1 -1
  82. package/dist/types.js +37 -9
  83. package/dist/workspaces.js +1 -1
  84. package/docs/ARCHITECTURE.md +110 -8
  85. package/docs/COMPATIBILITY.md +10 -6
  86. package/docs/CONCEPT.md +15 -3
  87. package/docs/CROSS_PLATFORM.ru.md +11 -9
  88. package/docs/CROSS_PLATFORM.zh.md +11 -9
  89. package/docs/FAQ.md +2 -2
  90. package/docs/FAQ.ru.md +2 -2
  91. package/docs/FAQ.zh.md +2 -2
  92. package/docs/FEATURES.md +5 -4
  93. package/docs/FEATURES.zh.md +5 -4
  94. package/docs/MIGRATION.md +34 -26
  95. package/docs/README.ru.md +26 -7
  96. package/docs/README.zh.md +9 -8
  97. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  98. package/gui-experimental.cjs +8 -8
  99. package/index.js +1 -0
  100. package/locales/en.json +1 -0
  101. package/locales/ru.json +1 -0
  102. package/locales/zh.json +1 -0
  103. package/package.json +31 -10
  104. package/src/core/analytics.ts +2 -2
  105. package/src/core/audit.ts +17 -17
  106. package/src/core/cron-to-schtasks.ts +14 -93
  107. package/src/core/dry-run.ts +26 -26
  108. package/src/core/file-watcher.ts +17 -17
  109. package/src/core/git-trigger.ts +9 -9
  110. package/src/core/glob.ts +1 -1
  111. package/src/core/local-ai.ts +2 -2
  112. package/src/core/lock.ts +9 -9
  113. package/src/core/matrix.ts +31 -31
  114. package/src/core/native-notify.ts +2 -2
  115. package/src/core/one-shot.ts +63 -13
  116. package/src/core/otel.ts +4 -4
  117. package/src/core/permissions.ts +5 -5
  118. package/src/core/prometheus.ts +17 -17
  119. package/src/core/ps-wrapper.ts +57 -37
  120. package/src/core/record-history.ts +40 -40
  121. package/src/core/retention.ts +3 -3
  122. package/src/core/savings.ts +1 -1
  123. package/src/core/schedule-gate.ts +12 -12
  124. package/src/core/schedule-v2.ts +24 -24
  125. package/src/core/scheduler/at-fallback.ts +113 -0
  126. package/src/core/scheduler/index.ts +3 -3
  127. package/src/core/scheduler/linux.ts +64 -13
  128. package/src/core/scheduler/logs.ts +1 -1
  129. package/src/core/scheduler/mac.ts +112 -60
  130. package/src/core/scheduler/posix.ts +15 -1
  131. package/src/core/scheduler/registry.ts +6 -4
  132. package/src/core/scheduler/windows.ts +295 -125
  133. package/src/core/secrets.ts +13 -13
  134. package/src/core/self-analysis.ts +61 -61
  135. package/src/core/session.ts +3 -3
  136. package/src/core/structured-log.ts +3 -3
  137. package/src/core/summary.ts +25 -25
  138. package/src/core/telegram.ts +16 -16
  139. package/src/core/triage-chain.ts +4 -4
  140. package/src/core/triage-compare.ts +8 -8
  141. package/src/core/triage-rules.ts +4 -4
  142. package/src/core/triage-shadow.ts +7 -7
  143. package/src/core/triage-worker.ts +6 -6
  144. package/src/core/triage.ts +23 -23
  145. package/src/core/watch-paths.ts +1 -1
  146. package/src/core/wrappers/bash.ts +41 -41
  147. package/src/db/git-state-repo.ts +1 -1
  148. package/src/db/history-repo.ts +22 -22
  149. package/src/db/index.ts +16 -6
  150. package/src/db/metrics-repo.ts +10 -10
  151. package/src/db/migrate.ts +10 -10
  152. package/src/db/recovery.ts +3 -3
  153. package/src/db/run-journal.ts +212 -0
  154. package/src/db/run-resume.ts +220 -0
  155. package/src/db/runs-repo.ts +481 -0
  156. package/src/db/schema.ts +205 -44
  157. package/src/db/settings-repo.ts +2 -2
  158. package/src/db/tasks-repo.ts +10 -10
  159. package/src/db/templates-repo.ts +7 -7
  160. package/src/gui.tsx +1 -1
  161. package/src/history.ts +4 -4
  162. package/src/i18n.ts +7 -7
  163. package/src/index.ts +341 -304
  164. package/src/integrations.ts +6 -6
  165. package/src/notifications.ts +76 -76
  166. package/src/profiles.ts +98 -7
  167. package/src/rpc.ts +96 -1
  168. package/src/schtasks.ts +2 -2
  169. package/src/server.ts +43 -42
  170. package/src/settings.ts +44 -44
  171. package/src/shared/jobs-view.ts +60 -60
  172. package/src/skill.ts +1 -1
  173. package/src/task-transfer.ts +58 -56
  174. package/src/templates.ts +1 -1
  175. package/src/types.ts +45 -10
  176. package/src/workspaces.ts +16 -16
  177. package/dist/core/self-analysis.test.d.ts +0 -2
  178. package/dist/core/self-analysis.test.d.ts.map +0 -1
  179. package/dist/core/self-analysis.test.js +0 -219
  180. package/dist/gui-experimental.cjs +0 -1
package/src/core/otel.ts CHANGED
@@ -42,7 +42,7 @@ function doubleAttr(key: string, value: number | null | undefined): OtlpAttribut
42
42
  return { key, value: { doubleValue: value } };
43
43
  }
44
44
 
45
- function compact(attrs: Array<OtlpAttribute | null>): OtlpAttribute[] {
45
+ function compact(attrs: (OtlpAttribute | null)[]): OtlpAttribute[] {
46
46
  return attrs.filter((attr): attr is OtlpAttribute => attr != null);
47
47
  }
48
48
 
@@ -58,7 +58,7 @@ function hashIds(record: StoredHistoryRecord): { traceId: string; spanId: string
58
58
  .createHash("sha256")
59
59
  .update(
60
60
  `${record.taskName}|${record.startedAt}|${record.id ?? 0}`,
61
- "utf8"
61
+ "utf8",
62
62
  )
63
63
  .digest("hex");
64
64
  return { traceId: digest.slice(0, 32), spanId: digest.slice(32, 48) };
@@ -107,7 +107,7 @@ export function buildOtlpExport(records: StoredHistoryRecord[]): Record<string,
107
107
  {
108
108
  resource: {
109
109
  attributes: compact([
110
- stringAttr("service.name", "opencode-windows-scheduler"),
110
+ stringAttr("service.name", "agent-steward"),
111
111
  stringAttr("service.version", version),
112
112
  stringAttr("scheduler.profile", getProfileName()),
113
113
  stringAttr("scheduler.backend", getSchedulerTitle()),
@@ -116,7 +116,7 @@ export function buildOtlpExport(records: StoredHistoryRecord[]): Record<string,
116
116
  scopeSpans: [
117
117
  {
118
118
  scope: {
119
- name: "opencode-windows-scheduler",
119
+ name: "agent-steward",
120
120
  version,
121
121
  },
122
122
  spans,
@@ -93,7 +93,7 @@ export interface EffectivePermissions {
93
93
  /** Приводит произвольное значение к известной политике. */
94
94
  export function normalizePolicy(
95
95
  value: unknown,
96
- fallback: PermissionPolicy = DEFAULT_PERMISSION_POLICY
96
+ fallback: PermissionPolicy = DEFAULT_PERMISSION_POLICY,
97
97
  ): PermissionPolicy {
98
98
  return typeof value === "string" &&
99
99
  (PERMISSION_POLICIES as readonly string[]).includes(value)
@@ -103,14 +103,14 @@ export function normalizePolicy(
103
103
 
104
104
  /** Нормализует список инструментов: trim, lower-case, без пустых и дублей. */
105
105
  export function normalizeToolList(
106
- value: readonly string[] | null | undefined
106
+ value: readonly string[] | null | undefined,
107
107
  ): string[] {
108
108
  return Array.from(
109
109
  new Set(
110
110
  (value ?? [])
111
111
  .map((tool) => String(tool).trim().toLowerCase())
112
- .filter(Boolean)
113
- )
112
+ .filter(Boolean),
113
+ ),
114
114
  );
115
115
  }
116
116
 
@@ -186,7 +186,7 @@ export function buildOpencodeConfig(input: PermissionInput = {}): string {
186
186
  permissions: effective.permissions,
187
187
  },
188
188
  null,
189
- 2
189
+ 2,
190
190
  );
191
191
  }
192
192
 
@@ -53,7 +53,7 @@ function metric(
53
53
  name: string,
54
54
  type: "counter" | "gauge" | "histogram",
55
55
  help: string,
56
- samples: Array<{ labels?: Record<string, string | number>; value: number }>
56
+ samples: { labels?: Record<string, string | number>; value: number }[],
57
57
  ): void {
58
58
  lines.push(`# HELP ${name} ${help}`);
59
59
  lines.push(`# TYPE ${name} ${type}`);
@@ -115,20 +115,20 @@ export function renderPrometheusMetrics(): string {
115
115
  "opencode_scheduler_queue_depth",
116
116
  "gauge",
117
117
  "Количество незавершённых запусков (глубина очереди).",
118
- [{ value: queueDepth }]
118
+ [{ value: queueDepth }],
119
119
  );
120
120
  metric(
121
121
  lines,
122
122
  "opencode_scheduler_history_records",
123
123
  "gauge",
124
124
  "Количество записей в истории запусков.",
125
- [{ value: historyRecords }]
125
+ [{ value: historyRecords }],
126
126
  );
127
127
 
128
- const runSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
129
- const errorSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
130
- const tokenSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
131
- const costSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
128
+ const runSamples: { labels: Record<string, string | number>; value: number }[] = [];
129
+ const errorSamples: { labels: Record<string, string | number>; value: number }[] = [];
130
+ const tokenSamples: { labels: Record<string, string | number>; value: number }[] = [];
131
+ const costSamples: { labels: Record<string, string | number>; value: number }[] = [];
132
132
  for (const row of metrics) {
133
133
  runSamples.push({
134
134
  labels: { task: row.taskName, status: "success" },
@@ -151,32 +151,32 @@ export function renderPrometheusMetrics(): string {
151
151
  "opencode_scheduler_runs_total",
152
152
  "counter",
153
153
  "Количество завершённых запусков по задачам и статусам.",
154
- runSamples
154
+ runSamples,
155
155
  );
156
156
  metric(
157
157
  lines,
158
158
  "opencode_scheduler_errors_total",
159
159
  "counter",
160
160
  "Количество ошибок и таймаутов по задачам (partial не входит).",
161
- errorSamples
161
+ errorSamples,
162
162
  );
163
163
  metric(
164
164
  lines,
165
165
  "opencode_scheduler_tokens_total",
166
166
  "counter",
167
167
  "Суммарное количество токенов по задачам.",
168
- tokenSamples
168
+ tokenSamples,
169
169
  );
170
170
  metric(
171
171
  lines,
172
172
  "opencode_scheduler_cost_usd_total",
173
173
  "counter",
174
174
  "Суммарная стоимость запусков в USD по задачам.",
175
- costSamples
175
+ costSamples,
176
176
  );
177
177
 
178
178
  lines.push(
179
- "# HELP opencode_scheduler_run_duration_seconds Длительность запусков в секундах."
179
+ "# HELP opencode_scheduler_run_duration_seconds Длительность запусков в секундах.",
180
180
  );
181
181
  lines.push("# TYPE opencode_scheduler_run_duration_seconds histogram");
182
182
  const taskNames = Array.from(durations.keys()).sort((a, b) => a.localeCompare(b));
@@ -189,19 +189,19 @@ export function renderPrometheusMetrics(): string {
189
189
  `opencode_scheduler_run_duration_seconds_bucket${labels({
190
190
  task,
191
191
  le: DURATION_BUCKETS_SECONDS[i],
192
- })} ${cumulative}`
192
+ })} ${cumulative}`,
193
193
  );
194
194
  }
195
195
  lines.push(
196
- `opencode_scheduler_run_duration_seconds_bucket${labels({ task, le: "+Inf" })} ${stats.count}`
196
+ `opencode_scheduler_run_duration_seconds_bucket${labels({ task, le: "+Inf" })} ${stats.count}`,
197
197
  );
198
198
  lines.push(
199
199
  `opencode_scheduler_run_duration_seconds_sum${labels({ task })} ${formatNumber(
200
- stats.sumSeconds
201
- )}`
200
+ stats.sumSeconds,
201
+ )}`,
202
202
  );
203
203
  lines.push(
204
- `opencode_scheduler_run_duration_seconds_count${labels({ task })} ${stats.count}`
204
+ `opencode_scheduler_run_duration_seconds_count${labels({ task })} ${stats.count}`,
205
205
  );
206
206
  }
207
207
  if (taskNames.length === 0) {
@@ -55,7 +55,11 @@ export const WRAPPER_SCRIPT = `param(
55
55
  [int]$GateTimeoutSeconds = 300,
56
56
  [int]$StaleLockMaxAgeMs = 86400000,
57
57
  [string]$PermissionsB64 = "",
58
- [string]$PolicyB64 = ""
58
+ [string]$PolicyB64 = "",
59
+ [string]$ModelB64 = "",
60
+ [string]$WorkspaceNameB64 = "",
61
+ [string]$AllowedToolsB64 = "",
62
+ [string]$DeniedToolsB64 = ""
59
63
  )
60
64
 
61
65
  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
@@ -63,6 +67,23 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
63
67
 
64
68
  $ErrorActionPreference = "Continue"
65
69
 
70
+ # P2-11: свободный текст (модель, имя workspace, списки инструментов) приходит
71
+ # в base64, чтобы символы подстановки PowerShell/cmd не разворачивались.
72
+ function ConvertFrom-B64Text {
73
+ param([string]$Value)
74
+ if (-not $Value) { return "" }
75
+ try {
76
+ return [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Value))
77
+ } catch {
78
+ return ""
79
+ }
80
+ }
81
+
82
+ if ($ModelB64) { $Model = ConvertFrom-B64Text $ModelB64 }
83
+ if ($WorkspaceNameB64) { $WorkspaceName = ConvertFrom-B64Text $WorkspaceNameB64 }
84
+ if ($AllowedToolsB64) { $AllowedTools = ConvertFrom-B64Text $AllowedToolsB64 }
85
+ if ($DeniedToolsB64) { $DeniedTools = ConvertFrom-B64Text $DeniedToolsB64 }
86
+
66
87
  function Write-Log {
67
88
  param([string]$Message)
68
89
  $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
@@ -99,7 +120,7 @@ if ($LogFile) {
99
120
  } catch {}
100
121
  }
101
122
 
102
- Write-Log "[windows-scheduler] Запуск задачи '$TaskName'..."
123
+ Write-Log "[agent-steward] Запуск задачи '$TaskName'..."
103
124
 
104
125
  $startTime = Get-Date
105
126
  $script:exitCode = 0
@@ -179,11 +200,11 @@ if ($LockFile) {
179
200
  }
180
201
  }
181
202
  if (-not $script:lockAcquired) {
182
- Write-Log "[windows-scheduler] Запуск задачи '$TaskName' пропущен: удерживается активная блокировка."
203
+ Write-Log "[agent-steward] Запуск задачи '$TaskName' пропущен: удерживается активная блокировка."
183
204
  exit 0
184
205
  }
185
206
  } catch {
186
- Write-Log "[windows-scheduler] Не удалось захватить блокировку задачи '$TaskName': $_"
207
+ Write-Log "[agent-steward] Не удалось захватить блокировку задачи '$TaskName': $_"
187
208
  exit 0
188
209
  }
189
210
  }
@@ -247,7 +268,7 @@ function Invoke-HookScript {
247
268
  try { & taskkill.exe /F /T /PID $proc.Id 2>$null | Out-Null } catch {}
248
269
  try { $proc.WaitForExit(5000) | Out-Null } catch {}
249
270
  $code = 124
250
- Write-Log "[windows-scheduler] Таймаут хука ($timeout с): $Command"
271
+ Write-Log "[agent-steward] Таймаут хука ($timeout с): $Command"
251
272
  } else {
252
273
  try { $proc.WaitForExit() } catch {}
253
274
  $code = $proc.ExitCode
@@ -265,7 +286,7 @@ function Invoke-HookScript {
265
286
  }
266
287
  return $code
267
288
  } catch {
268
- Write-Log "[windows-scheduler] Не удалось выполнить хук: $_"
289
+ Write-Log "[agent-steward] Не удалось выполнить хук: $_"
269
290
  return 1
270
291
  } finally {
271
292
  Remove-Item -LiteralPath $hookFile -Force -ErrorAction SilentlyContinue
@@ -358,7 +379,7 @@ function Invoke-OpenCodeOnce {
358
379
  }
359
380
 
360
381
  if ($script:timedOut) {
361
- Write-Log "[windows-scheduler] Таймаут: задача '$TaskName' превысила лимит $TimeoutSeconds с — процесс остановлен."
382
+ Write-Log "[agent-steward] Таймаут: задача '$TaskName' превысила лимит $TimeoutSeconds с — процесс остановлен."
362
383
  $script:errorMessage = "Таймаут: превышено $TimeoutSeconds с"
363
384
  return 124
364
385
  }
@@ -600,17 +621,17 @@ try {
600
621
 
601
622
  # Pre-flight: выполняется ДО основной задачи. Ненулевой код отменяет запуск.
602
623
  if ($BeforeScript) {
603
- Write-Log "[windows-scheduler] Pre-flight: $BeforeScript"
624
+ Write-Log "[agent-steward] Pre-flight: $BeforeScript"
604
625
  $preCode = Invoke-HookScript -Command $BeforeScript
605
626
  if ($preCode -ne 0) {
606
- Write-Log "[windows-scheduler] ОШИБКА: Pre-flight script failed (код $preCode)."
627
+ Write-Log "[agent-steward] ОШИБКА: Pre-flight script failed (код $preCode)."
607
628
  $script:preFlightStatus = "error"
608
629
  $script:errorMessage = "Pre-flight script failed"
609
630
  $script:exitCode = 1
610
631
  $script:skipMainTask = $true
611
632
  } else {
612
633
  $script:preFlightStatus = "success"
613
- Write-Log "[windows-scheduler] Pre-flight успешно завершён."
634
+ Write-Log "[agent-steward] Pre-flight успешно завершён."
614
635
  }
615
636
  }
616
637
 
@@ -633,9 +654,9 @@ try {
633
654
  Set-Item -Path ("env:" + $matches[1]) -Value $matches[2]
634
655
  }
635
656
  }
636
- Write-Log "[windows-scheduler] Переменные окружения workspace загружены."
657
+ Write-Log "[agent-steward] Переменные окружения workspace загружены."
637
658
  } catch {
638
- Write-Log "[windows-scheduler] Не удалось загрузить env-файл workspace: $($_.Exception.Message)"
659
+ Write-Log "[agent-steward] Не удалось загрузить env-файл workspace: $($_.Exception.Message)"
639
660
  }
640
661
  }
641
662
 
@@ -658,7 +679,7 @@ try {
658
679
  $fromFile = (Get-Content -LiteralPath $SessionFile -Raw -ErrorAction Stop).Trim()
659
680
  if ($fromFile) { $effectiveSessionId = $fromFile }
660
681
  } catch {
661
- Write-Log "[windows-scheduler] Не удалось прочитать файл сессии: $($_.Exception.Message)"
682
+ Write-Log "[agent-steward] Не удалось прочитать файл сессии: $($_.Exception.Message)"
662
683
  }
663
684
  }
664
685
  if ($effectiveSessionId) {
@@ -682,7 +703,7 @@ try {
682
703
  $attempt++
683
704
  if ($attempt -gt 1) {
684
705
  $waitSeconds = [Math]::Max(0, $RetryDelaySeconds)
685
- Write-Log "[windows-scheduler] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
706
+ Write-Log "[agent-steward] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
686
707
  if ($waitSeconds -gt 0) { Start-Sleep -Seconds $waitSeconds }
687
708
  $script:errorMessage = ""
688
709
  }
@@ -691,47 +712,47 @@ try {
691
712
  # Таймаут повторять бессмысленно: каждая попытка снова съест весь лимит.
692
713
  if ($script:timedOut) { break }
693
714
  if ($attempt -lt $maxAttempts) {
694
- Write-Log "[windows-scheduler] Попытка $attempt завершилась с кодом $($script:exitCode)."
715
+ Write-Log "[agent-steward] Попытка $attempt завершилась с кодом $($script:exitCode)."
695
716
  }
696
717
  }
697
718
 
698
719
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
699
720
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
700
721
  if ($QualityGate -and $script:exitCode -eq 0) {
701
- Write-Log "[windows-scheduler] Запуск Quality Gate: $QualityGate"
722
+ Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
702
723
  # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
703
724
  $gateCode = Invoke-HookScript -Command $QualityGate
704
725
 
705
726
  if ($gateCode -eq 124) {
706
- Write-Log "[windows-scheduler] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
727
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
707
728
  $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
708
729
  $script:exitCode = 1
709
730
  } elseif ($gateCode -ne 0) {
710
- Write-Log "[windows-scheduler] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
731
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
711
732
  $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
712
733
  $script:exitCode = 1
713
734
  } else {
714
- Write-Log "[windows-scheduler] Quality Gate пройден."
735
+ Write-Log "[agent-steward] Quality Gate пройден."
715
736
  }
716
737
  }
717
738
 
718
739
  if ($script:exitCode -ne 0) {
719
- Write-Log "[windows-scheduler] Задача '$TaskName' завершилась с кодом $script:exitCode."
740
+ Write-Log "[agent-steward] Задача '$TaskName' завершилась с кодом $script:exitCode."
720
741
  } else {
721
- Write-Log "[windows-scheduler] Задача '$TaskName' успешно завершена."
742
+ Write-Log "[agent-steward] Задача '$TaskName' успешно завершена."
722
743
  }
723
744
  } # конец блока основной задачи
724
745
  } catch {
725
- Write-Log "[windows-scheduler] Ошибка выполнения задачи '$TaskName': $_"
746
+ Write-Log "[agent-steward] Ошибка выполнения задачи '$TaskName': $_"
726
747
  $script:errorMessage = "Ошибка выполнения задачи: $_"
727
748
  $script:exitCode = 1
728
749
  } finally {
729
750
  # Post-flight: выполняется ВСЕГДА, даже если основная задача упала.
730
751
  if ($AfterScript) {
731
- Write-Log "[windows-scheduler] Post-flight: $AfterScript"
752
+ Write-Log "[agent-steward] Post-flight: $AfterScript"
732
753
  $postCode = Invoke-HookScript -Command $AfterScript
733
754
  if ($postCode -ne 0) {
734
- Write-Log "[windows-scheduler] ОШИБКА: Post-flight script failed (код $postCode)."
755
+ Write-Log "[agent-steward] ОШИБКА: Post-flight script failed (код $postCode)."
735
756
  $script:postFlightStatus = "error"
736
757
  if ($script:exitCode -eq 0) {
737
758
  $script:errorMessage = "Post-flight script failed"
@@ -739,7 +760,7 @@ try {
739
760
  }
740
761
  } else {
741
762
  $script:postFlightStatus = "success"
742
- Write-Log "[windows-scheduler] Post-flight успешно завершён."
763
+ Write-Log "[agent-steward] Post-flight успешно завершён."
743
764
  }
744
765
  }
745
766
 
@@ -870,7 +891,7 @@ export function lockFilePath(taskName: string): string {
870
891
  async function writeHookFile(
871
892
  sanitizedName: string,
872
893
  kind: "before" | "after" | "gate",
873
- command: string
894
+ command: string,
874
895
  ): Promise<string> {
875
896
  const dir = path.join(WRAPPER_DIR, "hooks");
876
897
  await fs.mkdir(dir, { recursive: true });
@@ -909,7 +930,7 @@ export async function writeWrapperCmd(
909
930
  gateTimeoutSeconds?: number,
910
931
  permissionsConfig?: string,
911
932
  policyMeta?: unknown,
912
- sessionFile?: string
933
+ sessionFile?: string,
913
934
  ): Promise<string> {
914
935
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
915
936
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
@@ -961,29 +982,28 @@ export async function writeWrapperCmd(
961
982
  if (model?.trim()) {
962
983
  const safeModel = model.replace(/[\r\n"]+/g, "").trim();
963
984
  if (safeModel) {
964
- psArgs.push(`-Model "${safeModel}"`);
985
+ const modelB64 = Buffer.from(safeModel, "utf8").toString("base64");
986
+ psArgs.push(`-ModelB64 "${modelB64}"`);
965
987
  }
966
988
  }
967
989
 
968
990
  if (workspaceName?.trim()) {
969
- const safeWorkspace = workspaceName.replace(/[\r\n"]+/g, "'").trim();
970
- if (safeWorkspace) {
971
- psArgs.push(`-WorkspaceName "${safeWorkspace}"`);
972
- }
991
+ const workspaceB64 = Buffer.from(workspaceName.trim(), "utf8").toString("base64");
992
+ psArgs.push(`-WorkspaceNameB64 "${workspaceB64}"`);
973
993
  }
974
994
 
975
995
  // Role-scoped tools (спринт 14): передаём списки одной строкой через запятую.
976
996
  for (const [flag, list] of [
977
- ["-AllowedTools", allowedTools],
978
- ["-DeniedTools", deniedTools],
997
+ ["-AllowedToolsB64", allowedTools],
998
+ ["-DeniedToolsB64", deniedTools],
979
999
  ] as const) {
980
1000
  const joined = (Array.isArray(list) ? list : [])
981
1001
  .map((item) => String(item).trim())
982
1002
  .filter(Boolean)
983
1003
  .join(",");
984
1004
  if (joined) {
985
- const safe = joined.replace(/[\r\n"]+/g, "'");
986
- psArgs.push(`${flag} "${safe}"`);
1005
+ const b64 = Buffer.from(joined, "utf8").toString("base64");
1006
+ psArgs.push(`${flag} "${b64}"`);
987
1007
  }
988
1008
  }
989
1009
 
@@ -1085,7 +1105,7 @@ export async function writeWrapperCmd(
1085
1105
  gateArgs.push(`>> "${logFile.trim()}" 2>&1`);
1086
1106
  }
1087
1107
  lines.push(gateArgs.join(" "));
1088
- lines.push(`if "%errorlevel%"=="3" exit /b 0`);
1108
+ lines.push("if \"%errorlevel%\"==\"3\" exit /b 0");
1089
1109
  }
1090
1110
 
1091
1111
  lines.push(psArgs.join(" "));