agent-steward 0.0.4 → 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.
- package/CHANGELOG.md +134 -2
- package/CROSS_PLATFORM.md +19 -0
- package/README.md +52 -7
- package/ROADMAP-STRATEGY.md +21 -18
- package/ROADMAP.md +140 -159
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +351 -0
- package/dist/core/execution.d.ts +203 -0
- package/dist/core/execution.d.ts.map +1 -0
- package/dist/core/execution.js +309 -0
- package/dist/core/gate-integrity.d.ts +35 -0
- package/dist/core/gate-integrity.d.ts.map +1 -0
- package/dist/core/gate-integrity.js +132 -0
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +14 -2
- package/dist/core/guard-run.d.ts +4 -0
- package/dist/core/guard-run.d.ts.map +1 -0
- package/dist/core/guard-run.js +101 -0
- package/dist/core/guard.d.ts +52 -0
- package/dist/core/guard.d.ts.map +1 -0
- package/dist/core/guard.js +362 -0
- package/dist/core/lock.d.ts +41 -0
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +141 -29
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +75 -15
- package/dist/core/mission.d.ts +83 -0
- package/dist/core/mission.d.ts.map +1 -0
- package/dist/core/mission.js +334 -0
- package/dist/core/pipeline-apply.d.ts +38 -0
- package/dist/core/pipeline-apply.d.ts.map +1 -0
- package/dist/core/pipeline-apply.js +117 -0
- package/dist/core/pipeline-io.d.ts +13 -0
- package/dist/core/pipeline-io.d.ts.map +1 -0
- package/dist/core/pipeline-io.js +64 -0
- package/dist/core/pipeline-map.d.ts +46 -0
- package/dist/core/pipeline-map.d.ts.map +1 -0
- package/dist/core/pipeline-map.js +196 -0
- package/dist/core/pipeline-spec.d.ts +109 -0
- package/dist/core/pipeline-spec.d.ts.map +1 -0
- package/dist/core/pipeline-spec.js +554 -0
- package/dist/core/ps-wrapper.d.ts +19 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +250 -62
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +130 -29
- package/dist/core/router/rules.d.ts.map +1 -1
- package/dist/core/router/rules.js +6 -0
- package/dist/core/scheduler/linux.d.ts +8 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +34 -9
- package/dist/core/scheduler/mac.d.ts +44 -2
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +126 -15
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +15 -12
- package/dist/core/structured-log.d.ts +7 -1
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/worktree-run.d.ts +4 -0
- package/dist/core/worktree-run.d.ts.map +1 -0
- package/dist/core/worktree-run.js +164 -0
- package/dist/core/worktree.d.ts +115 -0
- package/dist/core/worktree.d.ts.map +1 -0
- package/dist/core/worktree.js +462 -0
- package/dist/core/wrappers/bash.d.ts +17 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +175 -24
- package/dist/db/capability-repo.d.ts +43 -2
- package/dist/db/capability-repo.d.ts.map +1 -1
- package/dist/db/capability-repo.js +96 -11
- package/dist/db/history-repo.d.ts +38 -5
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +88 -25
- package/dist/db/metrics-repo.js +2 -2
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +5 -4
- package/dist/db/run-journal.d.ts +33 -5
- package/dist/db/run-journal.d.ts.map +1 -1
- package/dist/db/run-journal.js +78 -14
- package/dist/db/run-resume.d.ts +5 -0
- package/dist/db/run-resume.d.ts.map +1 -1
- package/dist/db/run-resume.js +9 -2
- package/dist/db/runs-repo.d.ts +19 -2
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +22 -6
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +63 -2
- package/dist/history.d.ts +1 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/i18n.d.ts +5 -0
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +11 -4
- package/dist/index.d.ts +136 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +378 -14
- package/dist/notifications.d.ts +22 -0
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +36 -8
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +25 -4
- package/dist/rpc.d.ts +246 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +117 -0
- package/dist/server.d.ts +15 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +77 -18
- package/dist/settings.d.ts +2 -2
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +3 -3
- package/dist/shared/jobs-view.d.ts +1 -1
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/shared/jobs-view.js +2 -0
- package/dist/task-transfer.d.ts +16 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +16 -0
- package/docs/ARCHITECTURE.md +281 -65
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/CONCEPT.md +18 -4
- package/docs/CROSS_PLATFORM.ru.md +20 -0
- package/docs/CROSS_PLATFORM.zh.md +18 -0
- package/docs/EXECUTION-LOOP.md +22 -7
- package/docs/FEATURES.md +65 -4
- package/docs/FEATURES.zh.md +52 -4
- package/docs/MIGRATION.md +2 -2
- package/docs/PIPELINE.md +293 -0
- package/docs/README.ru.md +42 -3
- package/docs/README.zh.md +43 -3
- package/docs/SAFETY.md +23 -3
- package/gui-experimental.cjs +9 -8
- package/locales/en.json +17 -1
- package/locales/ru.json +17 -1
- package/locales/zh.json +17 -1
- package/opencode.pipeline.yaml +35 -0
- package/package.json +23 -4
- package/scripts/test-home.mjs +83 -0
- package/src/cli.ts +412 -0
- package/src/core/dry-run.ts +2 -2
- package/src/core/execution.ts +538 -0
- package/src/core/file-watcher.ts +2 -2
- package/src/core/gate-integrity.ts +160 -0
- package/src/core/git-trigger.ts +18 -5
- package/src/core/guard-run.ts +119 -0
- package/src/core/guard.ts +431 -0
- package/src/core/lock.ts +178 -37
- package/src/core/matrix.ts +95 -50
- package/src/core/mission.ts +485 -0
- package/src/core/native-notify.ts +1 -1
- package/src/core/pipeline-apply.ts +158 -0
- package/src/core/pipeline-io.ts +79 -0
- package/src/core/pipeline-map.ts +264 -0
- package/src/core/pipeline-spec.ts +775 -0
- package/src/core/ps-wrapper.ts +263 -63
- package/src/core/record-history.ts +164 -77
- package/src/core/router/rules.ts +6 -0
- package/src/core/schedule-gate.ts +1 -1
- package/src/core/scheduler/at-fallback.ts +1 -1
- package/src/core/scheduler/linux.ts +40 -11
- package/src/core/scheduler/logs.ts +2 -2
- package/src/core/scheduler/mac.ts +174 -14
- package/src/core/scheduler/registry.ts +2 -2
- package/src/core/scheduler/windows.ts +19 -15
- package/src/core/secrets.ts +8 -8
- package/src/core/structured-log.ts +22 -5
- package/src/core/telegram.ts +2 -2
- package/src/core/triage-worker.ts +7 -7
- package/src/core/triage.ts +2 -2
- package/src/core/worktree-run.ts +199 -0
- package/src/core/worktree.ts +600 -0
- package/src/core/wrappers/bash.ts +190 -23
- package/src/db/capability-repo.ts +127 -10
- package/src/db/history-repo.ts +129 -22
- package/src/db/metrics-repo.ts +2 -2
- package/src/db/recovery.ts +5 -4
- package/src/db/run-journal.ts +100 -13
- package/src/db/run-resume.ts +17 -1
- package/src/db/runs-repo.ts +36 -6
- package/src/db/schema.ts +65 -2
- package/src/gui.tsx +177 -13
- package/src/history.ts +1 -1
- package/src/i18n.ts +12 -4
- package/src/index.ts +524 -4
- package/src/notifications.ts +38 -8
- package/src/profiles.ts +26 -4
- package/src/rpc.ts +128 -0
- package/src/server.ts +94 -18
- package/src/settings.ts +5 -5
- package/src/shared/jobs-view.ts +3 -1
- package/src/task-transfer.ts +31 -0
package/src/notifications.ts
CHANGED
|
@@ -639,13 +639,43 @@ function embeddingKey(taskName: string, status: string): string {
|
|
|
639
639
|
return `emb:${(taskName + "|" + status).toLowerCase()}`;
|
|
640
640
|
}
|
|
641
641
|
|
|
642
|
-
/**
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
642
|
+
/**
|
|
643
|
+
* CJK-символы: хирагана, катакана, хань, совместимые идеограммы, хангыль.
|
|
644
|
+
* Регэксп без `g`, проверяется посимвольно.
|
|
645
|
+
*/
|
|
646
|
+
const CJK_CHAR_RE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/;
|
|
647
|
+
|
|
648
|
+
/** Латиница, кириллица, цифры и диакритика — как раньше, но без вырезания CJK. */
|
|
649
|
+
const TOKEN_CHUNK_RE =
|
|
650
|
+
/[a-z\u00c0-\u024f\u0400-\u04ff0-9]+|[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]+/g;
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Простой токенизатор: слова, цифры, нижний регистр.
|
|
654
|
+
*
|
|
655
|
+
* B14: CJK-блоки больше не вырезаются. Иероглифы не разделены пробелами,
|
|
656
|
+
* поэтому слово режется на перекрывающиеся биграммы («任务失败» → «任务»,
|
|
657
|
+
* «务失», «失败»); одиночный иероглиф остаётся униграммой. Это даёт
|
|
658
|
+
* ненулевой вектор для `zh`/`ja`/`ko` и работает без словарей и
|
|
659
|
+
* `Intl.Segmenter`, одинаково на всех платформах.
|
|
660
|
+
*/
|
|
661
|
+
export function tokenize(text: string): string[] {
|
|
662
|
+
const tokens: string[] = [];
|
|
663
|
+
for (const match of text.toLowerCase().matchAll(TOKEN_CHUNK_RE)) {
|
|
664
|
+
const chunk = match[0];
|
|
665
|
+
if (CJK_CHAR_RE.test(chunk[0])) {
|
|
666
|
+
const chars = Array.from(chunk);
|
|
667
|
+
if (chars.length === 1) {
|
|
668
|
+
tokens.push(chars[0]);
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
for (let i = 0; i < chars.length - 1; i++) {
|
|
672
|
+
tokens.push(chars[i] + chars[i + 1]);
|
|
673
|
+
}
|
|
674
|
+
} else {
|
|
675
|
+
tokens.push(chunk);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
return tokens;
|
|
649
679
|
}
|
|
650
680
|
|
|
651
681
|
/**
|
|
@@ -659,7 +689,7 @@ function tokenize(text: string): string[] {
|
|
|
659
689
|
* Вес — 1 + log(tf), L2-нормализация; знак из старшего бита хеша снижает
|
|
660
690
|
* влияние коллизий.
|
|
661
691
|
*/
|
|
662
|
-
function textToVector(text: string): number[] {
|
|
692
|
+
export function textToVector(text: string): number[] {
|
|
663
693
|
const tokens = tokenize(text);
|
|
664
694
|
const vec: number[] = new Array(EMBEDDING_DIMENSION).fill(0);
|
|
665
695
|
if (tokens.length === 0) return vec;
|
package/src/profiles.ts
CHANGED
|
@@ -253,16 +253,38 @@ export function listProfiles(): ProfileInfo[] {
|
|
|
253
253
|
});
|
|
254
254
|
}
|
|
255
255
|
|
|
256
|
-
/**
|
|
256
|
+
/**
|
|
257
|
+
* Порты, зарезервированные за профилем default: основной (PREFERRED_PORT
|
|
258
|
+
* в server.ts) и запасной. У default может не быть profile.json, поэтому
|
|
259
|
+
* в listProfiles() его порт — null, и раньше аллокатор выдавал 3782 второму
|
|
260
|
+
* профилю: два дашборда дрались за один порт.
|
|
261
|
+
*/
|
|
262
|
+
const DEFAULT_PROFILE_PORTS = new Set([3782, 4782]);
|
|
263
|
+
const FIRST_PROFILE_PORT = 3783;
|
|
264
|
+
const LAST_PORT = 65535;
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Свободный порт для нового профиля (B4.2).
|
|
268
|
+
*
|
|
269
|
+
* Исключает зарезервированные порты default, порты из profile.json всех
|
|
270
|
+
* профилей и порт, заданный через OPENCODE_SCHEDULER_PORT. Сканирует диапазон
|
|
271
|
+
* от 3783 до 65535 и берёт первый не занятый — прежняя формула
|
|
272
|
+
* `3782 + used.size` могла выдать уже занятый порт (например, при
|
|
273
|
+
* зарезервированном 3783 и одном профиле).
|
|
274
|
+
*/
|
|
257
275
|
function allocateProfilePort(): number {
|
|
258
|
-
const used = new Set<number>();
|
|
276
|
+
const used = new Set<number>(DEFAULT_PROFILE_PORTS);
|
|
259
277
|
for (const profile of listProfiles()) {
|
|
260
278
|
if (profile.port) used.add(profile.port);
|
|
261
279
|
}
|
|
262
|
-
|
|
280
|
+
const fromEnv = Number(process.env.OPENCODE_SCHEDULER_PORT);
|
|
281
|
+
if (Number.isFinite(fromEnv) && fromEnv >= 1 && fromEnv <= LAST_PORT) {
|
|
282
|
+
used.add(Math.floor(fromEnv));
|
|
283
|
+
}
|
|
284
|
+
for (let port = FIRST_PROFILE_PORT; port <= LAST_PORT; port += 1) {
|
|
263
285
|
if (!used.has(port)) return port;
|
|
264
286
|
}
|
|
265
|
-
|
|
287
|
+
throw new Error("Не удалось выделить порт профилю: свободных портов не осталось.");
|
|
266
288
|
}
|
|
267
289
|
|
|
268
290
|
/**
|
package/src/rpc.ts
CHANGED
|
@@ -306,6 +306,54 @@ const DeleteTaskOutput = {
|
|
|
306
306
|
|
|
307
307
|
const RunTaskOutput = DeleteTaskOutput;
|
|
308
308
|
|
|
309
|
+
const RunMissionInput = {
|
|
310
|
+
type: "object" as const,
|
|
311
|
+
properties: {
|
|
312
|
+
prompt: { type: "string" },
|
|
313
|
+
cwd: { type: "string" },
|
|
314
|
+
taskName: { type: "string" },
|
|
315
|
+
taskType: { type: "string" },
|
|
316
|
+
model: { type: "string" },
|
|
317
|
+
session: { type: "string", enum: ["new", "reuse", "last"] },
|
|
318
|
+
sessionId: { type: "string" },
|
|
319
|
+
timeoutSeconds: { type: "number" },
|
|
320
|
+
gate: { type: "string" },
|
|
321
|
+
gateTimeoutSeconds: { type: "number" },
|
|
322
|
+
policy: { type: "string", enum: ["hybrid", "secure", "legacy"] },
|
|
323
|
+
allowedTools: { type: "array", items: { type: "string" } },
|
|
324
|
+
deniedTools: { type: "array", items: { type: "string" } },
|
|
325
|
+
dryRun: { type: "boolean" },
|
|
326
|
+
},
|
|
327
|
+
required: ["prompt"],
|
|
328
|
+
} as const;
|
|
329
|
+
|
|
330
|
+
const RunMissionOutput = {
|
|
331
|
+
type: "object" as const,
|
|
332
|
+
properties: {
|
|
333
|
+
success: { type: "boolean" },
|
|
334
|
+
dryRun: { type: "boolean" },
|
|
335
|
+
runId: { type: "string" },
|
|
336
|
+
status: { type: "string" },
|
|
337
|
+
description: { type: "string" },
|
|
338
|
+
error: { type: "string" },
|
|
339
|
+
steps: {
|
|
340
|
+
type: "array",
|
|
341
|
+
items: {
|
|
342
|
+
type: "object",
|
|
343
|
+
properties: {
|
|
344
|
+
stepName: { type: "string" },
|
|
345
|
+
taskType: { type: "string" },
|
|
346
|
+
target: { type: "string" },
|
|
347
|
+
status: { type: "string" },
|
|
348
|
+
attempt: { type: "number" },
|
|
349
|
+
error: { type: "string" },
|
|
350
|
+
},
|
|
351
|
+
},
|
|
352
|
+
},
|
|
353
|
+
},
|
|
354
|
+
required: ["success", "dryRun", "status", "description"],
|
|
355
|
+
} as const;
|
|
356
|
+
|
|
309
357
|
const GetTaskLogsInput = NameOnly;
|
|
310
358
|
|
|
311
359
|
const GetTaskLogsOutput = {
|
|
@@ -1665,6 +1713,82 @@ const DryRunAllOutput = {
|
|
|
1665
1713
|
required: ["success", "reports"],
|
|
1666
1714
|
} as const;
|
|
1667
1715
|
|
|
1716
|
+
/* === Pipeline-as-code (спринт 32) === */
|
|
1717
|
+
|
|
1718
|
+
const PipelineValidateInput = {
|
|
1719
|
+
type: "object" as const,
|
|
1720
|
+
properties: {
|
|
1721
|
+
path: { type: "string" },
|
|
1722
|
+
source: { type: "string" },
|
|
1723
|
+
dryRun: { type: "boolean" },
|
|
1724
|
+
},
|
|
1725
|
+
additionalProperties: false,
|
|
1726
|
+
} as const;
|
|
1727
|
+
|
|
1728
|
+
const PipelineIssue = {
|
|
1729
|
+
type: "object" as const,
|
|
1730
|
+
properties: {
|
|
1731
|
+
path: { type: "string" },
|
|
1732
|
+
message: { type: "string" },
|
|
1733
|
+
},
|
|
1734
|
+
required: ["path", "message"],
|
|
1735
|
+
} as const;
|
|
1736
|
+
|
|
1737
|
+
const PipelineValidationOutput = {
|
|
1738
|
+
type: "object" as const,
|
|
1739
|
+
properties: {
|
|
1740
|
+
ok: { type: "boolean" },
|
|
1741
|
+
errors: { type: "array", items: PipelineIssue },
|
|
1742
|
+
warnings: { type: "array", items: PipelineIssue },
|
|
1743
|
+
spec: {},
|
|
1744
|
+
},
|
|
1745
|
+
required: ["ok", "errors", "warnings"],
|
|
1746
|
+
} as const;
|
|
1747
|
+
|
|
1748
|
+
const PipelineApplyInput = {
|
|
1749
|
+
type: "object" as const,
|
|
1750
|
+
properties: {
|
|
1751
|
+
path: { type: "string" },
|
|
1752
|
+
source: { type: "string" },
|
|
1753
|
+
dryRun: { type: "boolean" },
|
|
1754
|
+
},
|
|
1755
|
+
additionalProperties: false,
|
|
1756
|
+
} as const;
|
|
1757
|
+
|
|
1758
|
+
const PipelineApplyOutput = {
|
|
1759
|
+
type: "object" as const,
|
|
1760
|
+
properties: {
|
|
1761
|
+
created: { type: "number" },
|
|
1762
|
+
updated: { type: "number" },
|
|
1763
|
+
unchanged: { type: "number" },
|
|
1764
|
+
stale: { type: "number" },
|
|
1765
|
+
warnings: { type: "array", items: { type: "string" } },
|
|
1766
|
+
errors: { type: "array", items: PipelineIssue },
|
|
1767
|
+
},
|
|
1768
|
+
required: ["created", "updated", "unchanged", "stale"],
|
|
1769
|
+
} as const;
|
|
1770
|
+
|
|
1771
|
+
const PipelineExportInput = {
|
|
1772
|
+
type: "object" as const,
|
|
1773
|
+
properties: {
|
|
1774
|
+
pipeline: { type: "string" },
|
|
1775
|
+
},
|
|
1776
|
+
required: ["pipeline"],
|
|
1777
|
+
additionalProperties: false,
|
|
1778
|
+
} as const;
|
|
1779
|
+
|
|
1780
|
+
const PipelineExportOutput = {
|
|
1781
|
+
type: "object" as const,
|
|
1782
|
+
properties: {
|
|
1783
|
+
ok: { type: "boolean" },
|
|
1784
|
+
spec: {},
|
|
1785
|
+
error: { type: "string" },
|
|
1786
|
+
},
|
|
1787
|
+
required: ["ok"],
|
|
1788
|
+
} as const;
|
|
1789
|
+
|
|
1790
|
+
/* === end Pipeline-as-code === */
|
|
1791
|
+
|
|
1668
1792
|
/** Детальный отчёт по одному клону матрицы. */
|
|
1669
1793
|
const MatrixCloneResult = {
|
|
1670
1794
|
type: "object" as const,
|
|
@@ -1872,6 +1996,7 @@ export const SchedulerRpc = Rpc.define({
|
|
|
1872
1996
|
create_task: { input: CreateTaskInput, output: CreateTaskOutput },
|
|
1873
1997
|
delete_task: { input: DeleteTaskInput, output: DeleteTaskOutput },
|
|
1874
1998
|
run_task: { input: RunTaskInput, output: RunTaskOutput },
|
|
1999
|
+
run_mission: { input: RunMissionInput, output: RunMissionOutput },
|
|
1875
2000
|
pause_task: { input: PauseResumeInput, output: DeleteTaskOutput },
|
|
1876
2001
|
resume_task: { input: PauseResumeInput, output: DeleteTaskOutput },
|
|
1877
2002
|
update_task: { input: UpdateTaskInput, output: UpdateTaskOutput },
|
|
@@ -1882,6 +2007,9 @@ export const SchedulerRpc = Rpc.define({
|
|
|
1882
2007
|
get_platform: { input: GetPlatformInput, output: GetPlatformOutput },
|
|
1883
2008
|
dry_run: { input: DryRunInput, output: DryRunReportOutput },
|
|
1884
2009
|
dry_run_all: { input: GetTasksInput, output: DryRunAllOutput },
|
|
2010
|
+
pipeline_validate: { input: PipelineValidateInput, output: PipelineValidationOutput },
|
|
2011
|
+
pipeline_apply: { input: PipelineApplyInput, output: PipelineApplyOutput },
|
|
2012
|
+
pipeline_export: { input: PipelineExportInput, output: PipelineExportOutput },
|
|
1885
2013
|
get_matrix_results: {
|
|
1886
2014
|
input: GetMatrixResultsInput,
|
|
1887
2015
|
output: GetMatrixResultsOutput,
|
package/src/server.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
2
3
|
import fs from "node:fs/promises";
|
|
3
4
|
import { execFile } from "node:child_process";
|
|
4
5
|
import { promisify } from "node:util";
|
|
@@ -9,7 +10,7 @@ import { getSchedulerTitle } from "./core/scheduler/index.js";
|
|
|
9
10
|
import { getPluginVersion } from "./version.js";
|
|
10
11
|
import { checkpointDb, getDbFile, getDbStatus } from "./db/index.js";
|
|
11
12
|
import { listWorkspaces } from "./workspaces.js";
|
|
12
|
-
import { getProfileName, getProfilePort } from "./profiles.js";
|
|
13
|
+
import { DEFAULT_PROFILE, getProfileName, getProfilePort } from "./profiles.js";
|
|
13
14
|
import { simulatePipeline } from "./core/dry-run.js";
|
|
14
15
|
import { loadSettings } from "./settings.js";
|
|
15
16
|
import {
|
|
@@ -69,6 +70,14 @@ function normalizeProcessName(name: string): string {
|
|
|
69
70
|
const DASHBOARD_HEADER = "x-plugin-dashboard";
|
|
70
71
|
const DASHBOARD_MARKER = "agent-steward";
|
|
71
72
|
|
|
73
|
+
/**
|
|
74
|
+
* Профиль, которому принадлежит ответившее приложение (B4).
|
|
75
|
+
* Маркер DASHBOARD_MARKER одинаков у всех профилей, поэтому без этого
|
|
76
|
+
* заголовка второй профиль принимал чужой дашборд за свой: переиспользовал
|
|
77
|
+
* чужой порт и показывал данные другого профиля.
|
|
78
|
+
*/
|
|
79
|
+
const PROFILE_HEADER = "x-plugin-profile";
|
|
80
|
+
|
|
72
81
|
/** Переопределение портов (используется в тестах; по умолчанию 3782/4782). */
|
|
73
82
|
export interface DashboardPorts {
|
|
74
83
|
preferred?: number;
|
|
@@ -426,14 +435,23 @@ export async function startDashboardServer(
|
|
|
426
435
|
return null;
|
|
427
436
|
}
|
|
428
437
|
|
|
429
|
-
// Порт занят: если это уже наш дашборд (другой
|
|
430
|
-
// в том же процессе/сессии), переиспользуем его,
|
|
431
|
-
|
|
438
|
+
// Порт занят: если это уже наш дашборд того же профиля (другой
|
|
439
|
+
// экземпляр плагина в том же процессе/сессии), переиспользуем его,
|
|
440
|
+
// а не вешаем второй порт. Дашборд другого профиля не наш: его нельзя
|
|
441
|
+
// ни переиспользовать (покажет чужие данные), ни снимать как зомби.
|
|
442
|
+
const probe = port !== 0 ? await probeDashboardOn(port) : null;
|
|
443
|
+
if (probe?.dashboard && probe.profile === getProfileName()) {
|
|
432
444
|
console.log(
|
|
433
445
|
`[agent-steward] Дашборд уже запущен на http://localhost:${port} — переиспользуем его.`,
|
|
434
446
|
);
|
|
435
447
|
return { port };
|
|
436
448
|
}
|
|
449
|
+
if (probe?.dashboard && probe.profile !== getProfileName()) {
|
|
450
|
+
console.warn(
|
|
451
|
+
`[agent-steward] Порт ${port} занят дашбордом профиля "${probe.profile}" — не трогаем, пробуем другой порт.`,
|
|
452
|
+
);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
437
455
|
|
|
438
456
|
// Порт занят чужим или старым процессом: пробуем снять зомби
|
|
439
457
|
// (только node/bun этого плагина) и повторить bind.
|
|
@@ -669,16 +687,34 @@ async function getProcessInfoPosix(
|
|
|
669
687
|
}
|
|
670
688
|
}
|
|
671
689
|
|
|
672
|
-
|
|
673
|
-
|
|
690
|
+
export interface DashboardProbe {
|
|
691
|
+
/** На порту отвечает наш дашборд (маркер-заголовок совпал). */
|
|
692
|
+
dashboard: boolean;
|
|
693
|
+
/** Профиль ответившего дашборда; null, если это не дашборд. */
|
|
694
|
+
profile: string | null;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Проверяет по маркер-заголовку, что на порту отвечает наш дашборд,
|
|
699
|
+
* и определяет его профиль (B4.1).
|
|
700
|
+
*
|
|
701
|
+
* Заголовок профиля появился в B4.1. Более старые сборки его не отдают —
|
|
702
|
+
* таких считаем профилем `default`: до появления профилей база была одна,
|
|
703
|
+
* а значит старый процесс работал именно с default.
|
|
704
|
+
*/
|
|
705
|
+
export async function probeDashboardOn(port: number): Promise<DashboardProbe> {
|
|
674
706
|
try {
|
|
675
707
|
const res = await fetch(`http://127.0.0.1:${port}/`, {
|
|
676
708
|
method: "GET",
|
|
677
709
|
signal: AbortSignal.timeout(1500),
|
|
678
710
|
});
|
|
679
|
-
|
|
711
|
+
if (res.headers.get(DASHBOARD_HEADER) !== DASHBOARD_MARKER) {
|
|
712
|
+
return { dashboard: false, profile: null };
|
|
713
|
+
}
|
|
714
|
+
const profile = res.headers.get(PROFILE_HEADER)?.trim() || DEFAULT_PROFILE;
|
|
715
|
+
return { dashboard: true, profile };
|
|
680
716
|
} catch {
|
|
681
|
-
return false;
|
|
717
|
+
return { dashboard: false, profile: null };
|
|
682
718
|
}
|
|
683
719
|
}
|
|
684
720
|
|
|
@@ -789,7 +825,10 @@ async function handleRequest(
|
|
|
789
825
|
|
|
790
826
|
// Статический HTML-файл — страница дашборда.
|
|
791
827
|
if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
792
|
-
|
|
828
|
+
const nonce = randomBytes(16).toString("base64");
|
|
829
|
+
send(res, 200, "text/html; charset=utf-8", renderPage(nonce), {
|
|
830
|
+
"Content-Security-Policy": dashboardCsp(nonce),
|
|
831
|
+
});
|
|
793
832
|
return;
|
|
794
833
|
}
|
|
795
834
|
|
|
@@ -1380,16 +1419,43 @@ function sanitizeError(err: any): string {
|
|
|
1380
1419
|
}
|
|
1381
1420
|
|
|
1382
1421
|
/** Отправляет ответ с телом и закрывает соединение. */
|
|
1383
|
-
function send(
|
|
1422
|
+
function send(
|
|
1423
|
+
res: http.ServerResponse,
|
|
1424
|
+
status: number,
|
|
1425
|
+
contentType: string,
|
|
1426
|
+
body: string,
|
|
1427
|
+
extraHeaders?: Record<string, string>,
|
|
1428
|
+
): void {
|
|
1384
1429
|
res.writeHead(status, {
|
|
1385
1430
|
"Content-Type": contentType,
|
|
1386
1431
|
"Cache-Control": "no-store",
|
|
1387
1432
|
"X-Content-Type-Options": "nosniff",
|
|
1388
1433
|
[DASHBOARD_HEADER]: DASHBOARD_MARKER,
|
|
1434
|
+
[PROFILE_HEADER]: getProfileName(),
|
|
1435
|
+
...extraHeaders,
|
|
1389
1436
|
});
|
|
1390
1437
|
res.end(body);
|
|
1391
1438
|
}
|
|
1392
1439
|
|
|
1440
|
+
/**
|
|
1441
|
+
* CSP страницы дашборда: defense in depth к экранированию (B3.4).
|
|
1442
|
+
* Единственный инлайн-скрипт помечается nonce, внешние скрипты запрещены;
|
|
1443
|
+
* инлайн-стили остаются разрешёнными, потому что разметка использует style="…".
|
|
1444
|
+
*/
|
|
1445
|
+
function dashboardCsp(nonce: string): string {
|
|
1446
|
+
return [
|
|
1447
|
+
"default-src 'none'",
|
|
1448
|
+
`script-src 'nonce-${nonce}'`,
|
|
1449
|
+
"style-src 'unsafe-inline'",
|
|
1450
|
+
"connect-src 'self'",
|
|
1451
|
+
"img-src 'self' data:",
|
|
1452
|
+
"base-uri 'none'",
|
|
1453
|
+
"form-action 'none'",
|
|
1454
|
+
"frame-ancestors 'none'",
|
|
1455
|
+
"object-src 'none'",
|
|
1456
|
+
].join("; ");
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1393
1459
|
/** Отправляет бинарный файл (скачивание .db-бэкапа). */
|
|
1394
1460
|
function sendBuffer(
|
|
1395
1461
|
res: http.ServerResponse,
|
|
@@ -1409,6 +1475,7 @@ function sendBuffer(
|
|
|
1409
1475
|
"Cache-Control": "no-store",
|
|
1410
1476
|
"X-Content-Type-Options": "nosniff",
|
|
1411
1477
|
[DASHBOARD_HEADER]: DASHBOARD_MARKER,
|
|
1478
|
+
[PROFILE_HEADER]: getProfileName(),
|
|
1412
1479
|
});
|
|
1413
1480
|
res.end(body);
|
|
1414
1481
|
}
|
|
@@ -1432,6 +1499,7 @@ function sendAttachment(
|
|
|
1432
1499
|
"Cache-Control": "no-store",
|
|
1433
1500
|
"X-Content-Type-Options": "nosniff",
|
|
1434
1501
|
[DASHBOARD_HEADER]: DASHBOARD_MARKER,
|
|
1502
|
+
[PROFILE_HEADER]: getProfileName(),
|
|
1435
1503
|
});
|
|
1436
1504
|
res.end(body);
|
|
1437
1505
|
}
|
|
@@ -1471,7 +1539,7 @@ async function collectTasksWithMetrics(deps: DashboardDeps) {
|
|
|
1471
1539
|
* Данные тянутся fetch'ем с JSON-API и перерисовываются каждые 5 секунд.
|
|
1472
1540
|
* Внутри строковой константы не используются бэктики и ${}, чтобы не экранировать.
|
|
1473
1541
|
*/
|
|
1474
|
-
function renderPage(): string {
|
|
1542
|
+
function renderPage(nonce: string): string {
|
|
1475
1543
|
return `<!DOCTYPE html>
|
|
1476
1544
|
<html lang="${getLocale()}">
|
|
1477
1545
|
<head>
|
|
@@ -1756,7 +1824,7 @@ function renderPage(): string {
|
|
|
1756
1824
|
</div>
|
|
1757
1825
|
<div id="toast" role="status" aria-live="polite"></div>
|
|
1758
1826
|
|
|
1759
|
-
<script>
|
|
1827
|
+
<script nonce="${nonce}">
|
|
1760
1828
|
(function () {
|
|
1761
1829
|
'use strict';
|
|
1762
1830
|
|
|
@@ -1779,10 +1847,17 @@ function renderPage(): string {
|
|
|
1779
1847
|
// P3-29: тяжёлая аналитика обновляется реже остальных блоков.
|
|
1780
1848
|
var ANALYTICS_INTERVAL_MS = 60000;
|
|
1781
1849
|
|
|
1850
|
+
// Экранирование для текстового и атрибутного контекста.
|
|
1851
|
+
// Раньше использовался div.innerHTML: он превращает & < > в сущности,
|
|
1852
|
+
// но оставляет кавычки как есть, а результат подставляется в
|
|
1853
|
+
// title="…", style="…", data-*="…" и href="…" — это и был вектор XSS.
|
|
1782
1854
|
function esc(s) {
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1855
|
+
return String(s == null ? '' : s)
|
|
1856
|
+
.replace(/&/g, '&')
|
|
1857
|
+
.replace(/</g, '<')
|
|
1858
|
+
.replace(/>/g, '>')
|
|
1859
|
+
.replace(/"/g, '"')
|
|
1860
|
+
.replace(/'/g, ''');
|
|
1786
1861
|
}
|
|
1787
1862
|
|
|
1788
1863
|
function toast(msg, kind) {
|
|
@@ -1852,7 +1927,7 @@ function renderPage(): string {
|
|
|
1852
1927
|
);
|
|
1853
1928
|
throw new Error('Сервер вернул не JSON. Проверьте консоль.');
|
|
1854
1929
|
}
|
|
1855
|
-
if (marker !== 'opencode-windows-scheduler') {
|
|
1930
|
+
if (marker !== 'agent-steward' && marker !== 'opencode-windows-scheduler') {
|
|
1856
1931
|
console.warn(
|
|
1857
1932
|
'В ответе нет заголовка x-plugin-dashboard — возможно, это не дашборд плагина.'
|
|
1858
1933
|
);
|
|
@@ -2232,8 +2307,9 @@ function renderPage(): string {
|
|
|
2232
2307
|
var text = String(value == null ? '' : value);
|
|
2233
2308
|
return text.length > max ? text.slice(0, max - 1) + '…' : text;
|
|
2234
2309
|
}
|
|
2310
|
+
// esc() уже экранирует кавычки, отдельная подмена " больше не нужна.
|
|
2235
2311
|
function attr(value) {
|
|
2236
|
-
return esc(
|
|
2312
|
+
return esc(value);
|
|
2237
2313
|
}
|
|
2238
2314
|
function statusClass(status) {
|
|
2239
2315
|
if (status === 'success') return ' okg';
|
|
@@ -2719,7 +2795,7 @@ function renderPage(): string {
|
|
|
2719
2795
|
})();
|
|
2720
2796
|
</script>
|
|
2721
2797
|
|
|
2722
|
-
<script>
|
|
2798
|
+
<script nonce="${nonce}">
|
|
2723
2799
|
(function () {
|
|
2724
2800
|
var flakes = ['❄', '❅', '❆'];
|
|
2725
2801
|
for (var i = 0; i < 18; i++) {
|
package/src/settings.ts
CHANGED
|
@@ -2,7 +2,7 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { PLUGIN_DIR } from "./types.js";
|
|
5
|
-
import { DEFAULT_LOCALE, normalizeLocale, normalizeLocaleMode, SUPPORTED_LOCALES, messageIn, t, type Locale, type LocaleMode } from "./i18n.js";
|
|
5
|
+
import { DEFAULT_LOCALE, DEFAULT_LOCALE_MODE, normalizeLocale, normalizeLocaleMode, SUPPORTED_LOCALES, messageIn, t, type Locale, type LocaleMode } from "./i18n.js";
|
|
6
6
|
import {
|
|
7
7
|
DEFAULT_PERMISSION_POLICY,
|
|
8
8
|
normalizePolicy,
|
|
@@ -362,8 +362,8 @@ export interface SchedulerSettings {
|
|
|
362
362
|
/** Максимум одновременно выполняющихся задач. 0 — без ограничения. */
|
|
363
363
|
maxConcurrent: number;
|
|
364
364
|
/**
|
|
365
|
-
* Язык интерфейса (Спринт 28, режим `auto` — T7): `
|
|
366
|
-
* `en`/`zh` — явный
|
|
365
|
+
* Язык интерфейса (Спринт 28, режим `auto` — T7): `auto` по умолчанию —
|
|
366
|
+
* следовать за языком OpenCode; `ru`/`en`/`zh` — явный выбор пользователя.
|
|
367
367
|
*/
|
|
368
368
|
locale: LocaleMode;
|
|
369
369
|
/**
|
|
@@ -1266,7 +1266,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
|
|
|
1266
1266
|
parsed?.maxConcurrent,
|
|
1267
1267
|
DEFAULT_MAX_CONCURRENT,
|
|
1268
1268
|
),
|
|
1269
|
-
locale: normalizeLocaleMode(parsed?.locale,
|
|
1269
|
+
locale: normalizeLocaleMode(parsed?.locale, DEFAULT_LOCALE_MODE),
|
|
1270
1270
|
uiLocale: normalizeLocale(parsed?.uiLocale, DEFAULT_LOCALE),
|
|
1271
1271
|
winterMode: normalizeWinterMode(
|
|
1272
1272
|
parsed?.winterMode,
|
|
@@ -1290,7 +1290,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
|
|
|
1290
1290
|
} catch {
|
|
1291
1291
|
return {
|
|
1292
1292
|
maxConcurrent: DEFAULT_MAX_CONCURRENT,
|
|
1293
|
-
locale:
|
|
1293
|
+
locale: DEFAULT_LOCALE_MODE,
|
|
1294
1294
|
uiLocale: DEFAULT_LOCALE,
|
|
1295
1295
|
winterMode: DEFAULT_WINTER_MODE,
|
|
1296
1296
|
notifications: fallbackNotifications,
|
package/src/shared/jobs-view.ts
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "../task-transfer.js";
|
|
7
7
|
import type { ScheduledTaskInfo } from "../types.js";
|
|
8
8
|
|
|
9
|
-
export type JobStatus = "running" | "success" | "error" | "partial" | "idle" | "unknown"
|
|
9
|
+
export type JobStatus = "running" | "success" | "error" | "partial" | "skipped" | "idle" | "unknown"
|
|
10
10
|
|
|
11
11
|
export interface JobView {
|
|
12
12
|
name: string
|
|
@@ -117,6 +117,8 @@ export function statusIcon(status: JobStatus): string {
|
|
|
117
117
|
return "✓";
|
|
118
118
|
case "partial":
|
|
119
119
|
return "◐";
|
|
120
|
+
case "skipped":
|
|
121
|
+
return "⏭";
|
|
120
122
|
case "idle":
|
|
121
123
|
// Задача создана, но ещё ни разу не запускалась.
|
|
122
124
|
return "○";
|
package/src/task-transfer.ts
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
validateLaunchWindow,
|
|
15
15
|
} from "./core/schedule-v2.js";
|
|
16
16
|
import { isValidSessionId } from "./core/session.js";
|
|
17
|
+
import { normalizeTaskGuards, type TaskGuards } from "./core/guard.js";
|
|
17
18
|
|
|
18
19
|
/** Триггер задачи по событию из MCP-шины. */
|
|
19
20
|
export interface McpEventTrigger {
|
|
@@ -158,6 +159,13 @@ export interface TaskDefinition {
|
|
|
158
159
|
* перечислить shell в allowedTools.
|
|
159
160
|
*/
|
|
160
161
|
legacyShell?: boolean;
|
|
162
|
+
/**
|
|
163
|
+
* W-1: запускать задачу в одноразовом git worktree, созданном от HEAD
|
|
164
|
+
* рабочей директории. По умолчанию выключено. Требует git-репозиторий.
|
|
165
|
+
*/
|
|
166
|
+
worktree?: boolean;
|
|
167
|
+
/** W-3: guard-условия перед запуском (semantic-проверки и shell-команда). */
|
|
168
|
+
guards?: TaskGuards;
|
|
161
169
|
/** Настройки fan-out матрицы (родитель). */
|
|
162
170
|
matrix?: MatrixConfig;
|
|
163
171
|
/** Для клона матрицы — имя родительской задачи-шаблона. */
|
|
@@ -225,6 +233,14 @@ export interface TaskDefinition {
|
|
|
225
233
|
runWhenLoggedOff?: boolean;
|
|
226
234
|
/** Когда задача была создана — защита от ложного catch-up сразу после создания. */
|
|
227
235
|
createdAt?: string;
|
|
236
|
+
/**
|
|
237
|
+
* Спринт 32 (Pipeline-as-code): имя pipeline, из которого создан шаг.
|
|
238
|
+
* Хранится в definition_json и позволяет apply отличать «свои» задачи
|
|
239
|
+
* от созданных вручную. Не участвует в запуске.
|
|
240
|
+
*/
|
|
241
|
+
pipelineName?: string;
|
|
242
|
+
/** Спринт 32: стабильный id шага внутри pipeline (для diff/apply). */
|
|
243
|
+
pipelineStepId?: string;
|
|
228
244
|
}
|
|
229
245
|
|
|
230
246
|
const PREFIX = `\\OpenCode\\${TASK_FOLDER_NAME}\\`;
|
|
@@ -397,6 +413,10 @@ export async function buildExportJson(
|
|
|
397
413
|
...(definition?.paused === true ? { paused: true } : {}),
|
|
398
414
|
// Спринт 27.5.10: режим входа переживает перенос между профилями.
|
|
399
415
|
...(definition?.runWhenLoggedOff === true ? { runWhenLoggedOff: true } : {}),
|
|
416
|
+
// W-1: изоляция запуска в одноразовом git worktree.
|
|
417
|
+
...(definition?.worktree === true ? { worktree: true } : {}),
|
|
418
|
+
// W-3: guard-условия переживают перенос между профилями.
|
|
419
|
+
...(definition?.guards ? { guards: definition.guards } : {}),
|
|
400
420
|
...(Array.isArray(definition?.allowedTools) && definition.allowedTools.length > 0
|
|
401
421
|
? { allowedTools: definition.allowedTools }
|
|
402
422
|
: {}),
|
|
@@ -720,6 +740,15 @@ export function parseImportJson(raw: string): ParsedImport {
|
|
|
720
740
|
// Спринт 27.5.10: режим входа. Только явный `true` делает задачу фоновой;
|
|
721
741
|
// всё остальное (false, null, строка) означает интерактивную задачу.
|
|
722
742
|
const runWhenLoggedOffFlag = source.runWhenLoggedOff === true;
|
|
743
|
+
// W-1: одноразовый git worktree; только явный `true`.
|
|
744
|
+
const worktreeFlag = source.worktree === true;
|
|
745
|
+
// W-3: guard-условия. Ошибка нормализации попадает в общий список ошибок
|
|
746
|
+
// импорта; валидная конфигурация переносится вместе с задачей.
|
|
747
|
+
const guardsResult = normalizeTaskGuards(source.guards);
|
|
748
|
+
if (!guardsResult.ok) {
|
|
749
|
+
errors.push(`Запись ${position}${name ? ` (${name})` : ""}: ${guardsResult.error}`);
|
|
750
|
+
}
|
|
751
|
+
const guards = guardsResult.ok ? guardsResult.guards : undefined;
|
|
723
752
|
|
|
724
753
|
// Ограничения инструментов (Спринт 14): массив непустых строк без дублей.
|
|
725
754
|
// Пустой allowedTools отклоняется с явной ошибкой (избегаем «запрещено всё»).
|
|
@@ -934,6 +963,8 @@ export function parseImportJson(raw: string): ParsedImport {
|
|
|
934
963
|
...(pausedFlag ? { paused: true } : {}),
|
|
935
964
|
// Спринт 27.5.10: сохраняем режим входа при переносе задачи.
|
|
936
965
|
...(runWhenLoggedOffFlag ? { runWhenLoggedOff: true } : {}),
|
|
966
|
+
...(worktreeFlag ? { worktree: true } : {}),
|
|
967
|
+
...(guards ? { guards } : {}),
|
|
937
968
|
...(mcpEvent ? { mcpEvent } : {}),
|
|
938
969
|
...(allowedTools !== undefined ? { allowedTools } : {}),
|
|
939
970
|
...(deniedTools !== undefined ? { deniedTools } : {}),
|