opencode-windows-scheduler 1.5.1 → 1.5.2
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 +11 -1
- package/ROADMAP.md +262 -42
- package/dist/core/audit.d.ts +27 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +60 -0
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +47 -10
- package/dist/core/secrets.d.ts +10 -3
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +28 -4
- package/dist/core/wrappers/bash.d.ts +1 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +91 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -4
- package/dist/workspaces.d.ts +2 -2
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +6 -4
- package/docs/ARCHITECTURE.md +60 -3
- package/docs/FEATURES.md +15 -5
- package/package.json +1 -1
- package/src/core/audit.ts +89 -0
- package/src/core/ps-wrapper.ts +47 -10
- package/src/core/secrets.ts +34 -10
- package/src/core/wrappers/bash.ts +112 -5
- package/src/index.ts +17 -2
- package/src/workspaces.ts +9 -4
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -355,9 +355,23 @@ Rules:
|
|
|
355
355
|
- The dashboard has **no authentication** and binds to localhost. Do not expose it.
|
|
356
356
|
- A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
|
|
357
357
|
with your user privileges. Treat task creation like granting shell access.
|
|
358
|
-
- `allowedTools` / `deniedTools` are **
|
|
359
|
-
|
|
360
|
-
|
|
358
|
+
- `allowedTools` / `deniedTools` are **enforced at the run-wrapper level** (спринт 29.2).
|
|
359
|
+
Before each `opencode run`, the wrapper passes `permissions` rules through
|
|
360
|
+
`OPENCODE_CONFIG_CONTENT`: `deniedTools` are mapped to `effect: "deny"` for the
|
|
361
|
+
corresponding OpenCode action (`shell`, `edit`, `glob`, `grep`, `webfetch`,
|
|
362
|
+
`websearch`, `question`, `subagent`, `skill`), and `allowedTools` (if specified)
|
|
363
|
+
additionally denies every action not in the list. No config file is written, so a
|
|
364
|
+
project-level `opencode.jsonc` is preserved and parallel tasks in one workdir do not
|
|
365
|
+
race. The wrapper passes `--auto` so non-denied permissions are auto-approved.
|
|
366
|
+
`allowedTools`/`deniedTools` metadata is still recorded in history for audit.
|
|
367
|
+
- **Audit of blocked tools (спринт 29.4):** when a task definition is saved,
|
|
368
|
+
`recordTaskToolBlocks()` writes one `tool.blocked` audit event per entry in
|
|
369
|
+
`deniedTools` (`target` = task name, `details.tool` = tool, plus `allowedTools`,
|
|
370
|
+
`deniedTools` and `reason`). In allow-list mode one event with `tool: "*"` records
|
|
371
|
+
that every unlisted tool is denied. The event is emitted on create and on update, so
|
|
372
|
+
changing the task policy also changes the audited details. Because the wrapper runs
|
|
373
|
+
`opencode` as an external process, the plugin cannot observe individual blocked
|
|
374
|
+
attempts at runtime; the audit reflects the enforced policy, not each refusal.
|
|
361
375
|
- Task prompts, hooks and Quality Gate scripts are **plain text** executed with your
|
|
362
376
|
user privileges; only secrets (in `secrets.json`, AES-256-GCM) are encrypted.
|
|
363
377
|
Workspace `env` can reference secrets as `${secret:NAME}`; values are masked in
|
|
@@ -369,6 +383,49 @@ Rules:
|
|
|
369
383
|
- Workspace paths are validated, but hooks are not sandboxed: only schedule jobs from
|
|
370
384
|
repositories you trust.
|
|
371
385
|
|
|
386
|
+
### Permission model
|
|
387
|
+
|
|
388
|
+
The effective policy is resolved in this order (later wins):
|
|
389
|
+
|
|
390
|
+
1. Task `allowedTools` — if present, every action not listed is denied.
|
|
391
|
+
2. Task `deniedTools` — always denied and takes priority over `allowedTools`.
|
|
392
|
+
3. The generated `opencode.jsonc` — written into the task workdir for the run.
|
|
393
|
+
4. Project `opencode.json(c)` and system config — merged by OpenCode; a closer or
|
|
394
|
+
system-level config can weaken task-scoped denies (see limitations below).
|
|
395
|
+
5. `--auto` — auto-approves everything that remains, so no interactive prompts block
|
|
396
|
+
an unattended run.
|
|
397
|
+
|
|
398
|
+
Tool mapping used by both wrappers:
|
|
399
|
+
|
|
400
|
+
| Task tool | OpenCode action |
|
|
401
|
+
| --- | --- |
|
|
402
|
+
| `bash`, `shell` | `shell` |
|
|
403
|
+
| `write`, `edit`, `apply_patch`, `remove` | `edit` |
|
|
404
|
+
| `glob`, `grep`, `webfetch`, `websearch` | same name |
|
|
405
|
+
| `question`, `subagent`, `skill` | same name |
|
|
406
|
+
|
|
407
|
+
Hooks, Quality Gates and wrapper scripts are outside this model: they run before or
|
|
408
|
+
after the agent with the user's privileges and are not filtered by tool policy.
|
|
409
|
+
|
|
410
|
+
### Permission enforcement — known limitations (spike 29.1 findings)
|
|
411
|
+
|
|
412
|
+
- `opencode run` CLI (v2.2.3) supports only `--auto` (auto-approve non-denied
|
|
413
|
+
permissions). There are **no** `--allow-tool` / `--deny-tool` CLI flags, so
|
|
414
|
+
per-task restrictions cannot be passed via arguments. Enforcement is done by
|
|
415
|
+
generating a task-scoped config and passing it through `OPENCODE_CONFIG_CONTENT`.
|
|
416
|
+
- OpenCode merges `opencode.json(c)` from the current directory up to the filesystem
|
|
417
|
+
root. A project-level `opencode.jsonc` with permissive rules can override or weaken
|
|
418
|
+
task-scoped denies (last matching rule wins, closer directory wins for merge).
|
|
419
|
+
System config (`/etc/opencode`, `%ProgramData%\opencode`) overrides project config.
|
|
420
|
+
- Nested agent calls (subagents) use their **own** permissions, not a subset of the
|
|
421
|
+
parent's. A task that denies `subagent` prevents launching subagents, but a launched
|
|
422
|
+
subagent is not further restricted by the parent task's policy.
|
|
423
|
+
- **Plan B**: if the task-scoped config passed via `OPENCODE_CONFIG_CONTENT` proves
|
|
424
|
+
insufficient, enforcement can be moved to wrapper-level tool filtering (intercepting
|
|
425
|
+
`opencode run` invocation and refusing to start when a denied tool would be needed)
|
|
426
|
+
or to a managed system-level `policies` entry that hard-denies specific tools
|
|
427
|
+
globally.
|
|
428
|
+
|
|
372
429
|
## Extension points
|
|
373
430
|
|
|
374
431
|
| Goal | Where to start |
|
package/docs/FEATURES.md
CHANGED
|
@@ -251,9 +251,17 @@ the scheduler entry.
|
|
|
251
251
|
|
|
252
252
|
### Tool restrictions
|
|
253
253
|
|
|
254
|
-
`allowedTools` and `deniedTools`
|
|
255
|
-
|
|
256
|
-
|
|
254
|
+
`allowedTools` and `deniedTools` are enforced for the `opencode run` process that the
|
|
255
|
+
task wrapper starts. The wrapper passes the generated `permissions` rules to the
|
|
256
|
+
process through `OPENCODE_CONFIG_CONTENT`; no file is written to the task workdir, so a
|
|
257
|
+
project-level `opencode.jsonc` is never overwritten. Each `deniedTools` entry becomes an
|
|
258
|
+
`effect: "deny"` rule for the matching OpenCode action, and `allowedTools` (when set)
|
|
259
|
+
denies every action that is not listed. The wrapper runs `opencode` with `--auto`, so
|
|
260
|
+
only non-denied permissions are auto-approved. Restrictions apply to the agent process,
|
|
261
|
+
not to hooks, Quality Gates or scripts, which still run with your user privileges. See
|
|
262
|
+
[ARCHITECTURE.md](ARCHITECTURE.md#permission-enforcement--known-limitations-spike-291-findings)
|
|
263
|
+
for the exact action mapping and known limitations (project/system config, nested
|
|
264
|
+
subagents).
|
|
257
265
|
|
|
258
266
|
## Orchestration
|
|
259
267
|
|
|
@@ -585,7 +593,9 @@ plugin, no installation step required.
|
|
|
585
593
|
- **No authentication on the dashboard.** Localhost only by design.
|
|
586
594
|
- **Secrets are not encrypted.** Use environment variables or an external secret
|
|
587
595
|
manager.
|
|
588
|
-
- **`allowedTools` / `deniedTools`
|
|
589
|
-
|
|
596
|
+
- **`allowedTools` / `deniedTools` restrict the agent process, not the whole job.**
|
|
597
|
+
Hooks, Quality Gates and wrapper scripts still run with your user privileges, and a
|
|
598
|
+
project-level or system `opencode.jsonc` can weaken task-scoped denies. See the
|
|
599
|
+
permission-enforcement limitations in ARCHITECTURE.md.
|
|
590
600
|
- **Matrix clones are separate tasks.** They appear in the task list (grouped under the
|
|
591
601
|
parent) and consume global concurrency slots like any other run.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-windows-scheduler",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.2",
|
|
4
4
|
"description": "OpenCode v2 plugin for scheduling and orchestrating AI agent jobs: cron, one-shot runs, DAG pipelines, matrix builds, quality gates, SQLite history, metrics and a local web dashboard. Windows, macOS and Linux. Free and open source (MIT).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "opencode-windows-scheduler contributors",
|
package/src/core/audit.ts
CHANGED
|
@@ -174,6 +174,95 @@ function rowToRecord(row: any): AuditRecord {
|
|
|
174
174
|
};
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
export interface ToolBlockedInput {
|
|
178
|
+
/** Имя задачи, для которой действует запрет. */
|
|
179
|
+
task: string;
|
|
180
|
+
/** Заблокированный инструмент (например, shell или write). */
|
|
181
|
+
tool: string;
|
|
182
|
+
actor?: AuditActor;
|
|
183
|
+
source?: string | null;
|
|
184
|
+
/** Дополнительные детали события; можно переопределить/дополнить. */
|
|
185
|
+
details?: Record<string, unknown>;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Записывает событие tool.blocked для задачи и инструмента.
|
|
190
|
+
*
|
|
191
|
+
* Детали события — обычный объект, поэтому вызывающая сторона может добавить
|
|
192
|
+
* причину, список разрешённых инструментов и любые другие поля.
|
|
193
|
+
* Возвращает id записи или null, если журнал недоступен.
|
|
194
|
+
*/
|
|
195
|
+
export function recordToolBlocked(input: ToolBlockedInput): number | null {
|
|
196
|
+
return recordAudit({
|
|
197
|
+
action: "tool.blocked",
|
|
198
|
+
targetType: "task",
|
|
199
|
+
target: input.task,
|
|
200
|
+
actor: input.actor ?? "system",
|
|
201
|
+
source: input.source ?? "policy",
|
|
202
|
+
details: { tool: input.tool, ...(input.details ?? {}) },
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Фиксирует запреты задачи из её политики allowedTools/deniedTools.
|
|
208
|
+
*
|
|
209
|
+
* Явно запрещённые инструменты попадают в аудит по одному событию на
|
|
210
|
+
* инструмент. Для режима «только разрешённые» пишется одно событие с
|
|
211
|
+
* инструментом `*`, потому что список заблокированных в этом режиме
|
|
212
|
+
* неограничен. Возвращает число записанных событий.
|
|
213
|
+
*/
|
|
214
|
+
export function recordTaskToolBlocks(
|
|
215
|
+
task: string,
|
|
216
|
+
allowedTools: readonly string[] | null | undefined,
|
|
217
|
+
deniedTools: readonly string[] | null | undefined,
|
|
218
|
+
actor: AuditActor = "system",
|
|
219
|
+
source = "policy"
|
|
220
|
+
): number {
|
|
221
|
+
const normalizedDenied = Array.from(
|
|
222
|
+
new Set(
|
|
223
|
+
(deniedTools ?? [])
|
|
224
|
+
.map((tool) => String(tool).trim())
|
|
225
|
+
.filter(Boolean)
|
|
226
|
+
)
|
|
227
|
+
);
|
|
228
|
+
const normalizedAllowed = Array.from(
|
|
229
|
+
new Set(
|
|
230
|
+
(allowedTools ?? [])
|
|
231
|
+
.map((tool) => String(tool).trim())
|
|
232
|
+
.filter(Boolean)
|
|
233
|
+
)
|
|
234
|
+
);
|
|
235
|
+
const details = {
|
|
236
|
+
reason: "deniedTools",
|
|
237
|
+
allowedTools: normalizedAllowed.length > 0 ? normalizedAllowed : null,
|
|
238
|
+
deniedTools: normalizedDenied.length > 0 ? normalizedDenied : null,
|
|
239
|
+
};
|
|
240
|
+
let written = 0;
|
|
241
|
+
for (const tool of normalizedDenied) {
|
|
242
|
+
if (recordToolBlocked({ task, tool, actor, source, details }) != null) {
|
|
243
|
+
written++;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (normalizedDenied.length === 0 && normalizedAllowed.length > 0) {
|
|
247
|
+
if (
|
|
248
|
+
recordToolBlocked({
|
|
249
|
+
task,
|
|
250
|
+
tool: "*",
|
|
251
|
+
actor,
|
|
252
|
+
source,
|
|
253
|
+
details: {
|
|
254
|
+
reason: "allowedTools",
|
|
255
|
+
allowedTools: normalizedAllowed,
|
|
256
|
+
deniedTools: null,
|
|
257
|
+
},
|
|
258
|
+
}) != null
|
|
259
|
+
) {
|
|
260
|
+
written++;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return written;
|
|
264
|
+
}
|
|
265
|
+
|
|
177
266
|
/** Читает журнал аудита (новые сверху). */
|
|
178
267
|
export function readAuditLog(filter: ReadAuditFilter = {}): ReadAuditResult {
|
|
179
268
|
const limit = Math.max(1, Math.min(5000, Math.floor(filter.limit ?? 200) || 200));
|
package/src/core/ps-wrapper.ts
CHANGED
|
@@ -261,18 +261,53 @@ try {
|
|
|
261
261
|
Write-Log "[workspace] name=$WorkspaceName, cwd=$Workdir, branch=$gitBranch, remote=$gitRemote"
|
|
262
262
|
}
|
|
263
263
|
|
|
264
|
-
#
|
|
265
|
-
#
|
|
266
|
-
#
|
|
267
|
-
|
|
268
|
-
|
|
264
|
+
# Спринт 29.2: права задачи передаются через OPENCODE_CONFIG_CONTENT.
|
|
265
|
+
# opencode run CLI (v2.2.3) не поддерживает --allow-tool/--deny-tool, а файл
|
|
266
|
+
# opencode.jsonc в Workdir мог бы перезаписать проектный конфиг.
|
|
267
|
+
$toolToAction = @{
|
|
268
|
+
"read" = "read"; "write" = "edit"; "edit" = "edit"; "apply_patch" = "edit"; "remove" = "edit"
|
|
269
|
+
"bash" = "shell"; "shell" = "shell"; "glob" = "glob"; "grep" = "grep"
|
|
270
|
+
"webfetch" = "webfetch"; "websearch" = "websearch"; "question" = "question"
|
|
271
|
+
"subagent" = "subagent"; "skill" = "skill"
|
|
272
|
+
}
|
|
273
|
+
$defaultPermissions = @(
|
|
274
|
+
@{ action = "read"; resource = "*"; effect = "allow" },
|
|
275
|
+
@{ action = "edit"; resource = "*"; effect = "allow" },
|
|
276
|
+
@{ action = "glob"; resource = "*"; effect = "allow" },
|
|
277
|
+
@{ action = "grep"; resource = "*"; effect = "allow" },
|
|
278
|
+
@{ action = "shell"; resource = "*"; effect = "allow" },
|
|
279
|
+
@{ action = "subagent"; resource = "*"; effect = "allow" },
|
|
280
|
+
@{ action = "skill"; resource = "*"; effect = "allow" },
|
|
281
|
+
@{ action = "question"; resource = "*"; effect = "allow" },
|
|
282
|
+
@{ action = "webfetch"; resource = "*"; effect = "allow" },
|
|
283
|
+
@{ action = "websearch"; resource = "*"; effect = "allow" }
|
|
284
|
+
)
|
|
285
|
+
$permissions = @()
|
|
286
|
+
foreach ($p in $defaultPermissions) { $permissions += $p }
|
|
287
|
+
if ($DeniedTools) {
|
|
269
288
|
$deniedList = @($DeniedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
289
|
+
foreach ($tool in $deniedList) {
|
|
290
|
+
$action = $toolToAction[$tool]
|
|
291
|
+
if ($action) {
|
|
292
|
+
$idx = $permissions | Where-Object { $_.action -eq $action }
|
|
293
|
+
if ($idx) { $idx.effect = "deny" }
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if ($AllowedTools) {
|
|
298
|
+
$allowedList = @($AllowedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
|
|
299
|
+
$allowedActions = @{}
|
|
300
|
+
foreach ($tool in $allowedList) {
|
|
301
|
+
$action = $toolToAction[$tool]
|
|
302
|
+
if ($action) { $allowedActions[$action] = $true }
|
|
303
|
+
}
|
|
304
|
+
foreach ($p in $permissions) {
|
|
305
|
+
if (-not $allowedActions.ContainsKey($p.action)) { $p.effect = "deny" }
|
|
274
306
|
}
|
|
275
307
|
}
|
|
308
|
+
$config = @{ "$schema" = "https://opencode.ai/config.json"; "permissions" = $permissions }
|
|
309
|
+
$env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 3 -Compress)
|
|
310
|
+
Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT"
|
|
276
311
|
|
|
277
312
|
# Pre-flight: выполняется ДО основной задачи. Ненулевой код отменяет запуск.
|
|
278
313
|
if ($BeforeScript) {
|
|
@@ -312,7 +347,9 @@ try {
|
|
|
312
347
|
$opencodeCmd = Get-Command opencode | Select-Object -ExpandProperty Source
|
|
313
348
|
|
|
314
349
|
# Формируем аргументы для opencode run (Спринт 24: сессия).
|
|
315
|
-
|
|
350
|
+
# Спринт 29.2: --auto автоодобряет не запрещённые права, а ограничения
|
|
351
|
+
# берутся из сгенерированного opencode.jsonc в Workdir.
|
|
352
|
+
$opencodeArgs = @("run", "--auto")
|
|
316
353
|
if ($Model) {
|
|
317
354
|
$opencodeArgs += @("--model", $Model)
|
|
318
355
|
}
|
package/src/core/secrets.ts
CHANGED
|
@@ -278,13 +278,18 @@ export function listSecrets(): SecretListItem[] {
|
|
|
278
278
|
});
|
|
279
279
|
}
|
|
280
280
|
|
|
281
|
-
/** Подставляет все ссылки `${secret:NAME}` в строку. */
|
|
282
|
-
export function expandSecretRefs(
|
|
283
|
-
value: string
|
|
284
|
-
|
|
285
|
-
} {
|
|
281
|
+
/** Подставляет все ссылки `${secret:NAME}` в строку. Если задан allowedSecretNames — заменяются только ссылки на имена из этого списка (scoped-инъекция), остальные оставляются без изменений. */
|
|
282
|
+
export function expandSecretRefs(
|
|
283
|
+
value: string,
|
|
284
|
+
allowedSecretNames?: string[]
|
|
285
|
+
): { value: string; missing: string[] } {
|
|
286
286
|
const missing = new Set<string>();
|
|
287
|
+
const allowed = allowedSecretNames ? new Set(allowedSecretNames) : null;
|
|
287
288
|
const result = String(value ?? "").replace(SECRET_REF_RE, (_match, name: string) => {
|
|
289
|
+
if (allowed && !allowed.has(name)) {
|
|
290
|
+
// Секрет не разрешён для этой задачи — оставляем ссылку как есть.
|
|
291
|
+
return _match;
|
|
292
|
+
}
|
|
288
293
|
const secret = getSecret(name);
|
|
289
294
|
if (secret === undefined) {
|
|
290
295
|
missing.add(name);
|
|
@@ -298,15 +303,16 @@ export function expandSecretRefs(value: string): {
|
|
|
298
303
|
/**
|
|
299
304
|
* Разворачивает ссылки во всех значениях env. Отсутствующие секреты дают
|
|
300
305
|
* пустую строку и попадают в `missing` (только имена — без значений).
|
|
306
|
+
* Если задан allowedSecretNames — инжектит в env только реально используемые секреты.
|
|
301
307
|
*/
|
|
302
|
-
export function resolveSecretRefs(
|
|
303
|
-
env: Record<string, string
|
|
304
|
-
|
|
305
|
-
} {
|
|
308
|
+
export function resolveSecretRefs(
|
|
309
|
+
env: Record<string, string>,
|
|
310
|
+
allowedSecretNames?: string[]
|
|
311
|
+
): { env: Record<string, string>; missing: string[] } {
|
|
306
312
|
const resolved: Record<string, string> = {};
|
|
307
313
|
const missing = new Set<string>();
|
|
308
314
|
for (const [key, value] of Object.entries(env ?? {})) {
|
|
309
|
-
const result = expandSecretRefs(String(value ?? ""));
|
|
315
|
+
const result = expandSecretRefs(String(value ?? ""), allowedSecretNames);
|
|
310
316
|
resolved[key] = result.value;
|
|
311
317
|
for (const name of result.missing) missing.add(name);
|
|
312
318
|
}
|
|
@@ -383,3 +389,21 @@ export function resetSecretsCache(): void {
|
|
|
383
389
|
keyCache = null;
|
|
384
390
|
valuesCache = null;
|
|
385
391
|
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Собирает уникальные имена секретов из всех переданных строк, содержащих
|
|
395
|
+
* ссылки вида ${secret:NAME}. Возвращает отсортированный список имён.
|
|
396
|
+
* Используется для scoped-инъекции: только упомянутые секреты попадают в env задачи.
|
|
397
|
+
*/
|
|
398
|
+
export function collectSecretNames(...values: (string | undefined)[]): string[] {
|
|
399
|
+
const names = new Set<string>();
|
|
400
|
+
for (const value of values) {
|
|
401
|
+
if (!value) continue;
|
|
402
|
+
SECRET_REF_RE.lastIndex = 0;
|
|
403
|
+
let match: RegExpExecArray | null;
|
|
404
|
+
while ((match = SECRET_REF_RE.exec(value)) !== null) {
|
|
405
|
+
names.add(match[1]);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return [...names].sort();
|
|
409
|
+
}
|
|
@@ -133,7 +133,12 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
|
|
|
133
133
|
`SCHEDULE_DEFER_FILE=${shellQuote(scheduleGate?.deferFile ?? "")}`,
|
|
134
134
|
`SCHEDULE_FORCE_FILE=${shellQuote(scheduleGate?.forceFile ?? "")}`,
|
|
135
135
|
`ENV_FILE=${shellQuote(envFile ?? "")}`,
|
|
136
|
-
|
|
136
|
+
// Спринт 29.2: права задачи передаются в opencode через переменную окружения.
|
|
137
|
+
// opencode run CLI не поддерживает --allow-tool/--deny-tool, а файл
|
|
138
|
+
// opencode.jsonc в Workdir мог бы перезаписать проектный конфиг.
|
|
139
|
+
`export OPENCODE_CONFIG_CONTENT=${shellQuote(buildOpencodeConfig(allowedTools, deniedTools))}`,
|
|
140
|
+
'log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT"',
|
|
141
|
+
'',
|
|
137
142
|
"# cron запускает задачи с минимальным PATH — добавляем типовые каталоги.",
|
|
138
143
|
'export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin:$HOME/.bun/bin:$PATH"',
|
|
139
144
|
"",
|
|
@@ -270,9 +275,9 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
|
|
|
270
275
|
' ;;',
|
|
271
276
|
' esac',
|
|
272
277
|
' if [ -n "$MODEL" ]; then',
|
|
273
|
-
' opencode run "${SESSION_ARGS[@]}" --model "$MODEL" "$PROMPT"',
|
|
278
|
+
' opencode run --auto "${SESSION_ARGS[@]}" --model "$MODEL" "$PROMPT"',
|
|
274
279
|
" else",
|
|
275
|
-
' opencode run "${SESSION_ARGS[@]}" "$PROMPT"',
|
|
280
|
+
' opencode run --auto "${SESSION_ARGS[@]}" "$PROMPT"',
|
|
276
281
|
" fi",
|
|
277
282
|
"}",
|
|
278
283
|
"",
|
|
@@ -286,10 +291,12 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
|
|
|
286
291
|
' kill "$WATCHDOG" 2>/dev/null || true',
|
|
287
292
|
' wait "$WATCHDOG" 2>/dev/null || true',
|
|
288
293
|
"else",
|
|
289
|
-
'
|
|
294
|
+
' opencode run --auto "${SESSION_ARGS[@]}" "$PROMPT"',
|
|
290
295
|
" EXIT_CODE=$?",
|
|
291
296
|
"fi",
|
|
292
|
-
|
|
297
|
+
'',
|
|
298
|
+
'# Конфиг прав живёт только в переменной окружения — файл не создаётся.',
|
|
299
|
+
'',
|
|
293
300
|
'if [ "$EXIT_CODE" -ne 0 ]; then',
|
|
294
301
|
' log "[scheduler] Задача \'$TASK_NAME\' завершилась с кодом $EXIT_CODE."',
|
|
295
302
|
' ERROR_MESSAGE="Код возврата $EXIT_CODE"',
|
|
@@ -380,3 +387,103 @@ export async function writeBashWrapper(
|
|
|
380
387
|
export function bashWrapperPath(sanitizedName: string): string {
|
|
381
388
|
return path.join(WRAPPER_DIR, `run-${sanitizedName}.sh`);
|
|
382
389
|
}
|
|
390
|
+
|
|
391
|
+
// Спринт 29.2: генерация содержимого opencode.jsonc с правами для задачи.
|
|
392
|
+
// opencode run CLI (v2.2.3) не поддерживает --allow-tool/--deny-tool, поэтому
|
|
393
|
+
// права задаются через временный opencode.jsonc в WORKDIR.
|
|
394
|
+
//
|
|
395
|
+
// Actions OpenCode v2: read, edit, glob, grep, shell, subagent, skill, question,
|
|
396
|
+
// webfetch, websearch. deny для shell покрывает bash/Shell, deny для edit покрывает
|
|
397
|
+
// write/edit/apply_patch/remove.
|
|
398
|
+
//
|
|
399
|
+
// Политика: всё разрешено по умолчанию (как в OpenCode), deniedTools добавляют
|
|
400
|
+
// deny-правила, allowedTools (если задан) запрещает всё, чего нет в списке.
|
|
401
|
+
// Задаёт только допустимые/actions из известного набора — неизвестные игнорируются.
|
|
402
|
+
export function buildOpencodeConfig(
|
|
403
|
+
allowedTools?: string[],
|
|
404
|
+
deniedTools?: string[]
|
|
405
|
+
): string {
|
|
406
|
+
const actions: Array<{ action: string; effect: "allow" | "deny" }> = [
|
|
407
|
+
{ action: "read", effect: "allow" },
|
|
408
|
+
{ action: "edit", effect: "allow" },
|
|
409
|
+
{ action: "glob", effect: "allow" },
|
|
410
|
+
{ action: "grep", effect: "allow" },
|
|
411
|
+
{ action: "shell", effect: "allow" },
|
|
412
|
+
{ action: "subagent", effect: "allow" },
|
|
413
|
+
{ action: "skill", effect: "allow" },
|
|
414
|
+
{ action: "question", effect: "allow" },
|
|
415
|
+
{ action: "webfetch", effect: "allow" },
|
|
416
|
+
{ action: "websearch", effect: "allow" },
|
|
417
|
+
];
|
|
418
|
+
|
|
419
|
+
const deniedSet = new Set(
|
|
420
|
+
(deniedTools ?? [])
|
|
421
|
+
.map((t) => t.trim().toLowerCase())
|
|
422
|
+
.filter(Boolean)
|
|
423
|
+
);
|
|
424
|
+
const allowedSet = new Set(
|
|
425
|
+
(allowedTools ?? [])
|
|
426
|
+
.map((t) => t.trim().toLowerCase())
|
|
427
|
+
.filter(Boolean)
|
|
428
|
+
);
|
|
429
|
+
|
|
430
|
+
const toolToAction = new Map<string, string>([
|
|
431
|
+
["read", "read"],
|
|
432
|
+
["write", "edit"],
|
|
433
|
+
["edit", "edit"],
|
|
434
|
+
["apply_patch", "edit"],
|
|
435
|
+
["remove", "edit"],
|
|
436
|
+
["bash", "shell"],
|
|
437
|
+
["shell", "shell"],
|
|
438
|
+
["glob", "glob"],
|
|
439
|
+
["grep", "grep"],
|
|
440
|
+
["webfetch", "webfetch"],
|
|
441
|
+
["websearch", "websearch"],
|
|
442
|
+
["question", "question"],
|
|
443
|
+
["subagent", "subagent"],
|
|
444
|
+
["skill", "skill"],
|
|
445
|
+
["WebFetch", "webfetch"],
|
|
446
|
+
]);
|
|
447
|
+
|
|
448
|
+
// Применяем deniedTools.
|
|
449
|
+
for (const [tool, action] of toolToAction) {
|
|
450
|
+
if (deniedSet.has(tool)) {
|
|
451
|
+
const idx = actions.findIndex((a) => a.action === action);
|
|
452
|
+
if (idx >= 0) actions[idx].effect = "deny";
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Если задан allowedTools — всё, чего нет в списке, запрещаем.
|
|
457
|
+
// deniedTools имеет приоритет (последнее правило выигрывает в OpenCode),
|
|
458
|
+
// поэтому применяем allowedTools ПОСЛЕ deniedTools — denied не перебивается.
|
|
459
|
+
if (allowedSet.size > 0) {
|
|
460
|
+
for (const entry of actions) {
|
|
461
|
+
// Если действие уже запрещено deniedTools, оставляем deny.
|
|
462
|
+
if (entry.effect === "deny") continue;
|
|
463
|
+
const tool = [...toolToAction.entries()].find(
|
|
464
|
+
([, a]) => a === entry.action
|
|
465
|
+
)?.[0];
|
|
466
|
+
if (tool && !allowedSet.has(tool)) {
|
|
467
|
+
entry.effect = "deny";
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Убираем дубликаты actions (оставляем последний эффект).
|
|
473
|
+
const deduped = new Map<string, "allow" | "deny">();
|
|
474
|
+
for (const { action, effect } of actions) deduped.set(action, effect);
|
|
475
|
+
|
|
476
|
+
const permissions = [...deduped.entries()].map(
|
|
477
|
+
([action, effect]) =>
|
|
478
|
+
` { "action": "${action}", "resource": "*", "effect": "${effect}" }`
|
|
479
|
+
);
|
|
480
|
+
|
|
481
|
+
return JSON.stringify(
|
|
482
|
+
{
|
|
483
|
+
$schema: "https://opencode.ai/config.json",
|
|
484
|
+
permissions: permissions.map((p) => JSON.parse(p)),
|
|
485
|
+
},
|
|
486
|
+
null,
|
|
487
|
+
2
|
|
488
|
+
);
|
|
489
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -112,6 +112,7 @@ import {
|
|
|
112
112
|
} from "./workspaces.js";
|
|
113
113
|
import {
|
|
114
114
|
deleteSecret,
|
|
115
|
+
collectSecretNames,
|
|
115
116
|
hasSecret,
|
|
116
117
|
listSecrets,
|
|
117
118
|
setSecret,
|
|
@@ -120,6 +121,7 @@ import {
|
|
|
120
121
|
cleanupAuditLog,
|
|
121
122
|
readAuditLog,
|
|
122
123
|
recordAudit,
|
|
124
|
+
recordTaskToolBlocks,
|
|
123
125
|
} from "./core/audit.js";
|
|
124
126
|
import type { AuditEntryInput } from "./core/audit.js";
|
|
125
127
|
|
|
@@ -5029,8 +5031,19 @@ async function schedulerCreateTask(
|
|
|
5029
5031
|
workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
5030
5032
|
|
|
5031
5033
|
// Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
|
|
5032
|
-
//
|
|
5033
|
-
const
|
|
5034
|
+
// Спринт 29.3: инжектит в env только реально используемые секреты (scoped-инъекция).
|
|
5035
|
+
const usedSecretNames = collectSecretNames(
|
|
5036
|
+
prompt,
|
|
5037
|
+
beforeScript,
|
|
5038
|
+
afterScript,
|
|
5039
|
+
qualityGate
|
|
5040
|
+
);
|
|
5041
|
+
const taskEnvFile = writeWorkspaceEnvFile(
|
|
5042
|
+
workspace,
|
|
5043
|
+
PLUGIN_DIR,
|
|
5044
|
+
sanitized,
|
|
5045
|
+
usedSecretNames
|
|
5046
|
+
);
|
|
5034
5047
|
if (taskEnvFile) {
|
|
5035
5048
|
console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
|
|
5036
5049
|
}
|
|
@@ -5263,6 +5276,8 @@ async function schedulerCreateTask(
|
|
|
5263
5276
|
};
|
|
5264
5277
|
try {
|
|
5265
5278
|
await saveTaskDefinition(taskDefinition);
|
|
5279
|
+
// Аудит политики прав: фиксируем, какие инструменты задача блокирует.
|
|
5280
|
+
recordTaskToolBlocks(name, normalizedAllowedTools, normalizedDeniedTools);
|
|
5266
5281
|
} catch {
|
|
5267
5282
|
// Не критично — основная задача уже создана.
|
|
5268
5283
|
}
|
package/src/workspaces.ts
CHANGED
|
@@ -139,13 +139,16 @@ export function readWorkspaceEnvFile(envFile?: string): Record<string, string> {
|
|
|
139
139
|
* зашифрованного хранилища (Спринт 26); отсутствующий секрет даёт пустую
|
|
140
140
|
* строку и предупреждение с именем — без значения. Никогда не бросает.
|
|
141
141
|
*/
|
|
142
|
-
export function resolveWorkspaceEnv(
|
|
142
|
+
export function resolveWorkspaceEnv(
|
|
143
|
+
workspace: Workspace | undefined,
|
|
144
|
+
allowedSecretNames?: string[]
|
|
145
|
+
): Record<string, string> {
|
|
143
146
|
if (!workspace) return {};
|
|
144
147
|
const merged = {
|
|
145
148
|
...readWorkspaceEnvFile(workspace.envFile),
|
|
146
149
|
...(workspace.env ?? {}),
|
|
147
150
|
};
|
|
148
|
-
const resolved = resolveSecretRefs(merged);
|
|
151
|
+
const resolved = resolveSecretRefs(merged, allowedSecretNames);
|
|
149
152
|
if (resolved.missing.length > 0) {
|
|
150
153
|
console.warn(
|
|
151
154
|
`[workspace] "${workspace.name}": не найдены секреты: ${resolved.missing.join(", ")}`
|
|
@@ -196,10 +199,12 @@ export function workspaceEnvDir(pluginDir: string): string {
|
|
|
196
199
|
export function writeWorkspaceEnvFile(
|
|
197
200
|
workspace: Workspace | undefined,
|
|
198
201
|
pluginDir: string,
|
|
199
|
-
sanitizedName: string
|
|
202
|
+
sanitizedName: string,
|
|
203
|
+
allowedSecretNames?: string[]
|
|
200
204
|
): string | undefined {
|
|
205
|
+
if (!workspace) return undefined;
|
|
201
206
|
const file = join(workspaceEnvDir(pluginDir), `${sanitizedName}.env`);
|
|
202
|
-
const env = resolveWorkspaceEnv(workspace);
|
|
207
|
+
const env = resolveWorkspaceEnv(workspace, allowedSecretNames);
|
|
203
208
|
const keys = Object.keys(env);
|
|
204
209
|
if (!keys.length) {
|
|
205
210
|
try {
|