@omerrgocmen/crewctl 1.0.0

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 (95) hide show
  1. package/README.md +182 -0
  2. package/orchestrator/LICENSE +21 -0
  3. package/orchestrator/README.md +452 -0
  4. package/orchestrator/config.default.json +65 -0
  5. package/orchestrator/roles/executor.md +49 -0
  6. package/orchestrator/roles/operator-chat.md +25 -0
  7. package/orchestrator/roles/operator.md +75 -0
  8. package/orchestrator/roles/planner.md +53 -0
  9. package/orchestrator/roles/reviewer.md +54 -0
  10. package/orchestrator/skills/acceptance-criteria.md +18 -0
  11. package/orchestrator/skills/accessibility-audit.md +16 -0
  12. package/orchestrator/skills/accessible-forms.md +16 -0
  13. package/orchestrator/skills/api-design.md +27 -0
  14. package/orchestrator/skills/api-documentation.md +16 -0
  15. package/orchestrator/skills/architecture-decision-record.md +18 -0
  16. package/orchestrator/skills/authentication-design.md +16 -0
  17. package/orchestrator/skills/authorization-review.md +16 -0
  18. package/orchestrator/skills/backward-compatibility.md +17 -0
  19. package/orchestrator/skills/changelog-writing.md +16 -0
  20. package/orchestrator/skills/ci-pipeline-design.md +16 -0
  21. package/orchestrator/skills/cli-design.md +16 -0
  22. package/orchestrator/skills/code-review.md +27 -0
  23. package/orchestrator/skills/configuration-management.md +16 -0
  24. package/orchestrator/skills/container-review.md +16 -0
  25. package/orchestrator/skills/contract-testing.md +16 -0
  26. package/orchestrator/skills/dashboard-design.md +16 -0
  27. package/orchestrator/skills/database-migration.md +16 -0
  28. package/orchestrator/skills/database-schema-design.md +16 -0
  29. package/orchestrator/skills/debugging.md +26 -0
  30. package/orchestrator/skills/dependency-review.md +16 -0
  31. package/orchestrator/skills/design-review.md +29 -0
  32. package/orchestrator/skills/design-system.md +16 -0
  33. package/orchestrator/skills/docs-api-reference.md +16 -0
  34. package/orchestrator/skills/docs-troubleshooting.md +16 -0
  35. package/orchestrator/skills/docs-tutorial.md +16 -0
  36. package/orchestrator/skills/docs-writing.md +25 -0
  37. package/orchestrator/skills/empty-error-loading-states.md +16 -0
  38. package/orchestrator/skills/end-to-end-testing.md +16 -0
  39. package/orchestrator/skills/error-handling.md +16 -0
  40. package/orchestrator/skills/frontend-design.md +28 -0
  41. package/orchestrator/skills/git-commit-writing.md +16 -0
  42. package/orchestrator/skills/graphql-design.md +16 -0
  43. package/orchestrator/skills/incident-runbook.md +18 -0
  44. package/orchestrator/skills/input-validation.md +16 -0
  45. package/orchestrator/skills/integration-testing.md +16 -0
  46. package/orchestrator/skills/interaction-design.md +16 -0
  47. package/orchestrator/skills/landing-page-design.md +16 -0
  48. package/orchestrator/skills/observability-design.md +16 -0
  49. package/orchestrator/skills/openapi-contract.md +16 -0
  50. package/orchestrator/skills/performance-profiling.md +16 -0
  51. package/orchestrator/skills/privacy-review.md +16 -0
  52. package/orchestrator/skills/property-based-testing.md +16 -0
  53. package/orchestrator/skills/pull-request-writing.md +16 -0
  54. package/orchestrator/skills/refactoring.md +16 -0
  55. package/orchestrator/skills/release-readiness.md +16 -0
  56. package/orchestrator/skills/responsive-design.md +16 -0
  57. package/orchestrator/skills/secrets-management.md +16 -0
  58. package/orchestrator/skills/secure-file-upload.md +16 -0
  59. package/orchestrator/skills/security-review.md +26 -0
  60. package/orchestrator/skills/semantic-versioning.md +17 -0
  61. package/orchestrator/skills/seo-on-page.md +16 -0
  62. package/orchestrator/skills/seo-structured-data.md +16 -0
  63. package/orchestrator/skills/seo-technical-audit.md +16 -0
  64. package/orchestrator/skills/sql-query-review.md +16 -0
  65. package/orchestrator/skills/supply-chain-security.md +16 -0
  66. package/orchestrator/skills/test-strategy.md +16 -0
  67. package/orchestrator/skills/threat-modeling.md +16 -0
  68. package/orchestrator/skills/unit-testing.md +16 -0
  69. package/orchestrator/skills/write-tests.md +28 -0
  70. package/orchestrator/src/checkpoints.js +187 -0
  71. package/orchestrator/src/cli-registry.js +579 -0
  72. package/orchestrator/src/cli.js +135 -0
  73. package/orchestrator/src/doctor.js +64 -0
  74. package/orchestrator/src/engine.js +1364 -0
  75. package/orchestrator/src/schedule.js +126 -0
  76. package/orchestrator/src/server.js +706 -0
  77. package/orchestrator/src/skill-registry.js +272 -0
  78. package/orchestrator/src/store.js +364 -0
  79. package/orchestrator/web/OrbitControls.js +1417 -0
  80. package/orchestrator/web/app.css +116 -0
  81. package/orchestrator/web/app.js +70 -0
  82. package/orchestrator/web/board.html +141 -0
  83. package/orchestrator/web/code.html +208 -0
  84. package/orchestrator/web/flow.html +736 -0
  85. package/orchestrator/web/index.html +539 -0
  86. package/orchestrator/web/jsm/postprocessing/EffectComposer.js +231 -0
  87. package/orchestrator/web/jsm/postprocessing/MaskPass.js +104 -0
  88. package/orchestrator/web/jsm/postprocessing/Pass.js +95 -0
  89. package/orchestrator/web/jsm/postprocessing/RenderPass.js +99 -0
  90. package/orchestrator/web/jsm/postprocessing/ShaderPass.js +77 -0
  91. package/orchestrator/web/jsm/postprocessing/UnrealBloomPass.js +415 -0
  92. package/orchestrator/web/jsm/shaders/CopyShader.js +45 -0
  93. package/orchestrator/web/jsm/shaders/LuminosityHighPassShader.js +66 -0
  94. package/orchestrator/web/three.module.min.js +6 -0
  95. package/package.json +51 -0
@@ -0,0 +1,579 @@
1
+ const { spawn, spawnSync } = require("child_process");
2
+ const fs = require("fs");
3
+ const os = require("os");
4
+ const path = require("path");
5
+
6
+ const isWin = process.platform === "win32";
7
+
8
+ const DEFINITIONS = {
9
+ codex: {
10
+ command: "codex",
11
+ versionArgs: ["--version"],
12
+ defaultArgs: ["exec", "--skip-git-repo-check"],
13
+ // Codex calisirken surekli ilerleme akitir; 3 dakikalik sessizlik gercek bir takilmadir.
14
+ silenceTimeoutSeconds: 180,
15
+ description: "OpenAI Codex kodlama, hata ayiklama ve inceleme agenti",
16
+ capabilities: ["implementation", "debugging", "testing", "review", "analysis"],
17
+ roleFile: "roles/executor.md",
18
+ },
19
+ claude: {
20
+ command: "claude",
21
+ versionArgs: ["--version"],
22
+ defaultArgs: ["-p", "--permission-mode", "acceptEdits", "--output-format", "text"],
23
+ description: "Claude Code uygulama, analiz ve test agenti",
24
+ capabilities: ["implementation", "debugging", "testing", "review", "web"],
25
+ roleFile: "roles/executor.md",
26
+ },
27
+ gemini: {
28
+ command: "gemini",
29
+ versionArgs: ["--version"],
30
+ // Argumansiz gemini interaktif TUI acar ve izin bekler; yolo ile otonom, stdin'den prompt alir.
31
+ defaultArgs: ["--approval-mode", "yolo"],
32
+ // Gemini de akis halinde cikti verir; uzun sessizlik takilma isaretidir.
33
+ silenceTimeoutSeconds: 180,
34
+ description: "Gemini CLI analiz, uygulama ve web arastirma agenti",
35
+ capabilities: ["implementation", "planning", "analysis", "research", "web"],
36
+ roleFile: "roles/executor.md",
37
+ },
38
+ opencode: {
39
+ command: "opencode",
40
+ versionArgs: ["--version"],
41
+ // OpenCode saglayici/model kombinasyonuna gore uzun sure sessiz kalabilir. Varsayilan
42
+ // agent timeout'u, basarili bir calismayi SIGTERM ile yarida kesmeyecek kadar genis tut.
43
+ timeoutSeconds: 1800,
44
+ silenceTimeoutSeconds: 180,
45
+ // Bazi eski OpenCode surumleri --auto bayragini tanimaz. Otonom izinler
46
+ // engine tarafinda OPENCODE_CONFIG_CONTENT ile surumden bagimsiz aktarilir.
47
+ defaultArgs: ["run", "--format", "json", "Attached file contains the full task. Follow it exactly, make the changes, and report what you did.", "--file", "{PROMPT_FILE}"],
48
+ description: "OpenCode coklu saglayici kodlama, uygulama ve inceleme agenti",
49
+ capabilities: ["implementation", "debugging", "testing", "review", "analysis", "research"],
50
+ roleFile: "roles/executor.md",
51
+ install: {
52
+ windows: "npm install -g opencode-ai (alternatif: choco install opencode / scoop install opencode)",
53
+ macos: "brew install anomalyco/tap/opencode (alternatif: npm install -g opencode-ai)",
54
+ linux: "curl -fsSL https://opencode.ai/install | bash (alternatif: npm install -g opencode-ai)",
55
+ auth: "opencode auth login",
56
+ },
57
+ },
58
+ };
59
+ const RESOLVED = new Map();
60
+ let OPEN_CODE_MODELS = [];
61
+
62
+ function selectOpenCodeModel(models) {
63
+ const list = Array.isArray(models) ? models.map(String).filter(Boolean) : [];
64
+ const priorities = [
65
+ (x) => x === "opencode/big-pickle",
66
+ (x) => /^opencode\/.+free$/i.test(x),
67
+ (x) => x.startsWith("opencode/"),
68
+ (x) => x.startsWith("opencode-go/"),
69
+ (x) => x.startsWith("minimax-coding-plan/"),
70
+ (x) => !x.startsWith("ollama/"),
71
+ ];
72
+ for (const match of priorities) {
73
+ const found = list.find(match);
74
+ if (found) return found;
75
+ }
76
+ return "";
77
+ }
78
+
79
+ // `opencode models` ciktisindan saglayici/model satirlarini ayiklar. Baslik, bos satir ve
80
+ // log gurultusunu eler; her "saglayici/model" bicimli satir gecerli sayilir.
81
+ function parseOpenCodeModels(stdout) {
82
+ const found = new Set();
83
+ for (const line of String(stdout || "").split(/\r?\n/)) {
84
+ const model = line.trim();
85
+ if (/^[A-Za-z0-9._-]+\/.+/.test(model) && !/\s/.test(model)) found.add(model);
86
+ }
87
+ return [...found];
88
+ }
89
+
90
+ function listOpenCodeModels(command) {
91
+ try {
92
+ // Tum saglayicilarin listesi sorgulanir. Kullanicilarin ucretli abonelikleri
93
+ // (opencode-go, minimax-coding-plan vb.) ayri saglayici olarak gorunur; yalnizca
94
+ // "opencode" saglayicisini sorgulamak bu modelleri gizliyor ve kurulum yanlislikla
95
+ // "hazir degil" sayiliyordu. Otomatik oneri siralamasini selectOpenCodeModel yapar.
96
+ const result = spawnSync(command, ["models"], {
97
+ encoding: "utf8", timeout: 20000, windowsHide: true,
98
+ shell: isWin && (!path.isAbsolute(command) || /\.(cmd|bat)$/i.test(command)),
99
+ });
100
+ if (result.status !== 0) return [];
101
+ return parseOpenCodeModels(result.stdout);
102
+ } catch { return []; }
103
+ }
104
+
105
+ function adapterId(command) {
106
+ const base = path.basename(String(command || "")).toLowerCase().replace(/\.(cmd|bat|exe|ps1)$/, "");
107
+ if (base.includes("codex")) return "codex";
108
+ if (base.includes("claude")) return "claude";
109
+ if (base.includes("gemini")) return "gemini";
110
+ if (base.includes("opencode")) return "opencode";
111
+ return "custom";
112
+ }
113
+
114
+ // Farkli paket yoneticileri / kurulum araclari CLI'lari farkli dizinlere koyar. Her PC'de
115
+ // calismasi icin yaygin npm/pnpm/yarn/bun/volta/scoop/winget/choco/homebrew konumlarini tarariz.
116
+ function commonCandidates(id) {
117
+ const home = os.homedir();
118
+ if (isWin) {
119
+ const APPDATA = process.env.APPDATA, LOCAL = process.env.LOCALAPPDATA, PD = process.env.ProgramData;
120
+ const exts = ["cmd", "exe", "ps1", "bat", ""];
121
+ const bases = [
122
+ APPDATA && path.join(APPDATA, "npm"),
123
+ LOCAL && path.join(LOCAL, "pnpm"),
124
+ LOCAL && path.join(LOCAL, "Yarn", "bin"),
125
+ LOCAL && path.join(LOCAL, "Microsoft", "WinGet", "Links"),
126
+ LOCAL && path.join(LOCAL, "Programs", id),
127
+ path.join(home, ".bun", "bin"),
128
+ path.join(home, ".volta", "bin"),
129
+ path.join(home, "scoop", "shims"),
130
+ PD && path.join(PD, "chocolatey", "bin"),
131
+ path.join(home, ".local", "bin"),
132
+ path.join(home, "AppData", "Roaming", "npm"),
133
+ ].filter(Boolean);
134
+ const out = [];
135
+ for (const base of bases) for (const ext of exts) out.push(path.join(base, ext ? `${id}.${ext}` : id));
136
+ return out;
137
+ }
138
+ return [
139
+ path.join(home, ".local", "bin", id),
140
+ path.join(home, "bin", id),
141
+ path.join(home, ".bun", "bin", id),
142
+ path.join(home, ".volta", "bin", id),
143
+ path.join(home, ".npm-global", "bin", id),
144
+ path.join(home, ".yarn", "bin", id),
145
+ path.join(home, ".local", "share", "pnpm", id),
146
+ `/usr/local/bin/${id}`,
147
+ `/opt/homebrew/bin/${id}`,
148
+ `/usr/bin/${id}`,
149
+ `/snap/bin/${id}`,
150
+ ];
151
+ }
152
+
153
+ // Bilinen bir CLI komutu adapter alanindan daha guvenilir kaynaktir. Eski veya elle
154
+ // duzenlenmis config'te adapter=claude + cmd=codex gibi bir celiski varsa hedef CLI'nin
155
+ // guvenli varsayilan argumanlarina donulur; boylece bir CLI'ye digerinin bayragi gitmez.
156
+ function normalizeAgentAdapter(agent) {
157
+ if (!agent || typeof agent !== "object") return false;
158
+ const configured = String(agent.adapter || "").trim().toLowerCase();
159
+ const inferred = adapterId(agent.cmd);
160
+ const adapter = inferred !== "custom" ? inferred : (DEFINITIONS[configured] ? configured : "custom");
161
+ let changed = false;
162
+ if (inferred !== "custom" && configured && configured !== inferred) {
163
+ agent.args = DEFINITIONS[inferred].defaultArgs.slice();
164
+ delete agent.model;
165
+ delete agent.modelOverride;
166
+ changed = true;
167
+ }
168
+ if (agent.adapter !== adapter) {
169
+ agent.adapter = adapter;
170
+ changed = true;
171
+ }
172
+ return changed;
173
+ }
174
+
175
+ function normalizeAgentAdapters(cfg) {
176
+ if (!cfg?.agents || typeof cfg.agents !== "object") return false;
177
+ let changed = false;
178
+ for (const agent of Object.values(cfg.agents)) if (normalizeAgentAdapter(agent)) changed = true;
179
+ return changed;
180
+ }
181
+
182
+ // cfg verilirse cfg.cliSettings[adapter] o CLI'nin varsayilan model ayari olarak uygulanir.
183
+ // Oncelik: agent.model (profil bazli) > cliSettings[adapter].model (global) > CLI varsayilani.
184
+ function effectiveAgent(agent, cfg) {
185
+ const copy = { ...agent, args: Array.isArray(agent.args) ? agent.args.map(String) : [] };
186
+ normalizeAgentAdapter(copy);
187
+ const adapter = copy.adapter;
188
+ const commandAdapter = adapterId(copy.cmd);
189
+ const settings = (cfg && cfg.cliSettings && cfg.cliSettings[adapter]) || {};
190
+ if (!copy.silenceTimeoutSeconds && DEFINITIONS[adapter]?.silenceTimeoutSeconds) copy.silenceTimeoutSeconds = DEFINITIONS[adapter].silenceTimeoutSeconds;
191
+ if (commandAdapter === adapter && RESOLVED.has(adapter) && !path.isAbsolute(copy.cmd)) copy.cmd = RESOLVED.get(adapter);
192
+ if (adapter === "codex") {
193
+ const commands = new Set(["exec", "review", "resume", "apply"]);
194
+ if (!copy.args.some((arg) => commands.has(arg))) copy.args.unshift("exec", "--skip-git-repo-check");
195
+ else if (copy.args.includes("exec") && !copy.args.includes("--skip-git-repo-check")) copy.args.splice(copy.args.indexOf("exec") + 1, 0, "--skip-git-repo-check");
196
+ const model = String(copy.model || settings.model || "").trim();
197
+ const effort = ["low", "medium", "high", "xhigh", "max", "ultra"].includes(String(settings.reasoningEffort)) ? String(settings.reasoningEffort) : "";
198
+ const serviceTier = /^[A-Za-z0-9._-]{1,64}$/.test(String(settings.serviceTier || "")) ? String(settings.serviceTier) : "";
199
+ if (model && !copy.args.includes("--model") && !copy.args.includes("-m")) copy.args.push("--model", model);
200
+ if (effort && !copy.args.some((arg) => String(arg).startsWith("model_reasoning_effort="))) copy.args.push("-c", `model_reasoning_effort="${effort}"`);
201
+ if (serviceTier && !copy.args.some((arg) => String(arg).startsWith("service_tier="))) copy.args.push("-c", `service_tier="${serviceTier}"`);
202
+ }
203
+ if (adapter === "claude") {
204
+ if (!copy.args.includes("-p") && !copy.args.includes("--print")) copy.args.unshift("-p");
205
+ if (!copy.args.includes("--output-format")) copy.args.push("--output-format", "text");
206
+ }
207
+ if (adapter === "gemini") {
208
+ // Otonom, non-interaktif calisma icin onay modu sart; yoksa izin bekleyip takilir.
209
+ if (!copy.args.includes("--approval-mode") && !copy.args.includes("-y") && !copy.args.includes("--yolo")) copy.args.push("--approval-mode", "yolo");
210
+ }
211
+ if (adapter === "opencode") {
212
+ if (!copy.args.includes("run")) copy.args.unshift("run");
213
+ // config.json'da eski otomatik profil kalmis olsa da uyumsuz bayragi temizle.
214
+ copy.args = copy.args.filter((arg) => arg !== "--auto");
215
+ const formatAt = copy.args.indexOf("--format");
216
+ if (formatAt >= 0) copy.args.splice(formatAt, 2);
217
+ copy.args.splice(copy.args.indexOf("run") + 1, 0, "--format", "json");
218
+ const hasModel = copy.args.includes("--model") || copy.args.includes("-m");
219
+ const model = copy.model || String(settings.model || "").trim() || selectOpenCodeModel(OPEN_CODE_MODELS);
220
+ if (!hasModel && model) copy.args.splice(copy.args.indexOf("run") + 3, 0, "--model", model);
221
+ if (model) copy.model = model;
222
+ if (!copy.args.includes("{PROMPT}") && !copy.args.includes("{PROMPT_FILE}")) {
223
+ copy.args.push("Attached file contains the full task. Follow it exactly, make the changes, and report what you did.", "--file", "{PROMPT_FILE}");
224
+ }
225
+ }
226
+ return copy;
227
+ }
228
+
229
+ function probeCommand(command, definition) {
230
+ try {
231
+ const result = spawnSync(command, definition.versionArgs, {
232
+ encoding: "utf8",
233
+ timeout: 12000,
234
+ windowsHide: true,
235
+ shell: isWin && (!path.isAbsolute(command) || /\.(cmd|bat)$/i.test(command)),
236
+ });
237
+ const output = String(result.stdout || result.stderr || "").trim().split(/\r?\n/)[0];
238
+ return { installed: result.status === 0, version: result.status === 0 ? output : "", error: result.status === 0 ? "" : output, resolvedCommand: result.status === 0 ? command : "" };
239
+ } catch (error) {
240
+ return { installed: false, version: "", error: error.message, resolvedCommand: "" };
241
+ }
242
+ }
243
+
244
+ function probe(id, definition) {
245
+ let result = probeCommand(definition.command, definition);
246
+ let installedPath = "";
247
+ if (!result.installed) {
248
+ for (const candidate of commonCandidates(id)) {
249
+ if (!fs.existsSync(candidate)) continue;
250
+ if (!installedPath) installedPath = candidate;
251
+ result = probeCommand(candidate, definition);
252
+ if (result.installed) break;
253
+ }
254
+ // Bazi CLI'lar (or. gemini) --version cagrisinda cmd.exe uzerinden yavas acildigi icin
255
+ // zaman asimina ugrar. Ikili dosya diskte mevcutsa, versiyon okunamasa bile "kurulu" say;
256
+ // aksi halde kurulu CLI yanlislikla devre disi birakiliyordu.
257
+ if (!result.installed && installedPath) {
258
+ result = { installed: true, version: "kurulu", error: "", resolvedCommand: installedPath };
259
+ }
260
+ }
261
+ if (result.installed) RESOLVED.set(id, result.resolvedCommand);
262
+ if (result.installed && id === "opencode") {
263
+ OPEN_CODE_MODELS = listOpenCodeModels(result.resolvedCommand || definition.command);
264
+ result.models = OPEN_CODE_MODELS.slice();
265
+ result.recommendedModel = selectOpenCodeModel(OPEN_CODE_MODELS);
266
+ result.ready = Boolean(result.recommendedModel);
267
+ result.readinessError = result.ready ? "" : (OPEN_CODE_MODELS.length
268
+ ? "Kullanilabilir otomatik OpenCode modeli bulunamadi. Ayarlardan erisilebilir bir model secin."
269
+ : "OpenCode kurulu, ancak model listesi okunamadi. Once saglayici girisini tamamlayin.");
270
+ }
271
+ return result;
272
+ }
273
+
274
+ function discoverInstalled() {
275
+ return Object.entries(DEFINITIONS).map(([id, definition]) => ({ id, ...definition, ...probe(id, definition) }));
276
+ }
277
+
278
+ // Tek kaynak: hem gercek gorev calistirici (engine.runCli) hem saglik testi ve model
279
+ // listeleme ayni komut kurulumunu kullanir. Bare npm CLI adlarini where.exe ile fiziksel
280
+ // yola cevirmiyoruz; cmd.exe PATHEXT/PATH cozumlemesini Unicode olarak kendisi yapar.
281
+ function buildCommand(command, args) {
282
+ if (!isWin) return { file: command, args, shell: false };
283
+ const bare = !path.isAbsolute(command) && !/[\\/]/.test(command);
284
+ if (bare) return { file: command, args, shell: true };
285
+ if (!/\.(cmd|bat)$/i.test(command)) return { file: command, args, shell: false };
286
+ const quote = (value) => `"${String(value).replace(/"/g, '""')}"`;
287
+ return { file: process.env.ComSpec || "cmd.exe", args: ["/d", "/s", "/c", `"${[command, ...args].map(quote).join(" ")}"`], shell: false, verbatim: true };
288
+ }
289
+
290
+ function healthPrompt(id) {
291
+ return [
292
+ "CLI_TEAM_HEALTH_CHECK",
293
+ `Bu ${id} cli aracinin kullanilabilirlik testidir.`,
294
+ "Yalnizca HEALTH_OK yaz.",
295
+ "Dosya olusturma, degistirme, silme, komut calistirma veya dis sisteme istek gonderme.",
296
+ ].join("\n");
297
+ }
298
+
299
+ // Normal gorev calistiricisi {PROMPT}/{PROMPT_FILE} yer tutucularini cagridan once
300
+ // doldurur. Health check de ayni sozlesmeyi kullanmali; aksi halde OpenCode literal
301
+ // `{PROMPT_FILE}` yolunu acmaya calisir ve saglikli agent katalogdan yanlislikla elenir.
302
+ function preparePromptArgs(args, prompt) {
303
+ let tempDir = "", promptFile = "", useStdin = true;
304
+ const prepared = (Array.isArray(args) ? args : []).map((arg) => {
305
+ const value = String(arg);
306
+ if (value.includes("{PROMPT}")) {
307
+ useStdin = false;
308
+ return value.replaceAll("{PROMPT}", prompt);
309
+ }
310
+ if (value.includes("{PROMPT_FILE}")) {
311
+ useStdin = false;
312
+ if (!promptFile) {
313
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "cli-team-health-"));
314
+ promptFile = path.join(tempDir, "prompt.md");
315
+ fs.writeFileSync(promptFile, prompt, "utf8");
316
+ }
317
+ return value.replaceAll("{PROMPT_FILE}", promptFile);
318
+ }
319
+ return value;
320
+ });
321
+ return {
322
+ args: prepared,
323
+ useStdin,
324
+ promptFile,
325
+ cleanup() { if (tempDir) { try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {} } },
326
+ };
327
+ }
328
+
329
+ // Tek kaynak: OpenCode icin otonom izinler surumden bagimsiz olarak OPENCODE_CONFIG_CONTENT
330
+ // ile aktarilir. Hem engine.runCli hem saglik testi bu ortami kullanir ki test ile gercek
331
+ // calistirma ayni izinlerle calissin.
332
+ function agentEnvironment(agent) {
333
+ const env = { ...process.env };
334
+ if (agent.adapter !== "opencode") return env;
335
+ let inline = {};
336
+ try { inline = JSON.parse(env.OPENCODE_CONFIG_CONTENT || "{}"); } catch {}
337
+ env.OPENCODE_CONFIG_CONTENT = JSON.stringify({ ...inline, permission: { "*": "allow" } });
338
+ return env;
339
+ }
340
+
341
+ function classifyHealthFailure(text) {
342
+ const raw = String(text || "");
343
+ if (/requires a newer version|upgrade to the latest|version.*unsupported|unsupported.*version|model metadata.*not found|unsupported.*model/i.test(raw)) return { status: "version-incompatible", label: "Sürüm uyumsuz", detail: raw };
344
+ if (/api key|unauthorized|unauthenticated|authentication|login required|not logged in|sign in|giriÅŸ gerekli/i.test(raw)) return { status: "auth-required", label: "Giriş gerekli", detail: raw };
345
+ if (/rate.?limit|quota|too many requests|billing|credit/i.test(raw)) return { status: "quota", label: "Kota veya ödeme gerekli", detail: raw };
346
+ if (/timeout|timed out|zaman aşım/i.test(raw)) return { status: "timeout", label: "Yanıt zaman aşımına uğradı", detail: raw };
347
+ return { status: "failed", label: "Test başarısız", detail: raw };
348
+ }
349
+
350
+ function testInstalledCli(id, options = {}) {
351
+ const definition = DEFINITIONS[id];
352
+ if (!definition) return Promise.resolve({ id, installed: false, health: { status: "unknown", label: "Bilinmiyor", detail: "Tanımsız CLI" } });
353
+ const found = probe(id, definition);
354
+ if (!found.installed) return Promise.resolve({ id, installed: false, version: found.version, error: found.error, health: { status: "not-installed", label: "Kurulu değil", detail: found.error || "CLI bulunamadı" } });
355
+ const agent = effectiveAgent({ adapter: id, cmd: definition.command, args: definition.defaultArgs.slice() }, options.cfg);
356
+ const prompt = healthPrompt(id);
357
+ const prepared = preparePromptArgs(agent.args, prompt);
358
+ const command = buildCommand(agent.cmd, prepared.args);
359
+ const timeoutMs = Math.max(10000, Number(options.timeoutMs || 45000));
360
+ return new Promise((resolve) => {
361
+ let stdout = "", stderr = "", settled = false;
362
+ let child;
363
+ try {
364
+ child = spawn(command.file, command.args, { env: agentEnvironment(agent), shell: command.shell, windowsHide: true, windowsVerbatimArguments: !!command.verbatim });
365
+ } catch (error) {
366
+ prepared.cleanup();
367
+ return resolve({ id, installed: true, version: found.version, health: classifyHealthFailure(error.message) });
368
+ }
369
+ const timer = setTimeout(() => {
370
+ if (settled) return;
371
+ settled = true;
372
+ try { child.kill(); } catch {}
373
+ prepared.cleanup();
374
+ resolve({ id, installed: true, version: found.version, health: { status: "timeout", label: "Yanıt zaman aşımına uğradı", detail: `Sağlık testi ${Math.round(timeoutMs / 1000)} saniyede tamamlanmadı.` } });
375
+ }, timeoutMs);
376
+ child.stdout?.setEncoding("utf8");
377
+ child.stderr?.setEncoding("utf8");
378
+ child.stdout?.on("data", (data) => { stdout += String(data); });
379
+ child.stderr?.on("data", (data) => { stderr += String(data); });
380
+ child.on("error", (error) => {
381
+ if (settled) return;
382
+ settled = true;
383
+ clearTimeout(timer);
384
+ prepared.cleanup();
385
+ const failure = classifyHealthFailure(error.message);
386
+ resolve({ id, installed: true, version: found.version, health: failure });
387
+ });
388
+ child.on("close", (code) => {
389
+ if (settled) return;
390
+ settled = true;
391
+ clearTimeout(timer);
392
+ prepared.cleanup();
393
+ const raw = `${stdout}\n${stderr}`.trim();
394
+ if (code === 0 && /HEALTH_OK/i.test(raw)) resolve({ id, installed: true, version: found.version, health: { status: "ready", label: "Hazır", detail: "Gerçek sağlık testi başarılı." } });
395
+ else resolve({ id, installed: true, version: found.version, health: classifyHealthFailure(raw || `Çıkış kodu ${code}`) });
396
+ });
397
+ child.stdin?.on("error", () => {});
398
+ child.stdin?.end(prepared.useStdin ? prompt : "");
399
+ });
400
+ }
401
+
402
+ async function healthCheckAll(discovered = discoverInstalled(), options = {}) {
403
+ const results = await Promise.all(discovered.map((item) => testInstalledCli(item.id, options)));
404
+ return discovered.map((item) => ({ ...item, ...(results.find((result) => result.id === item.id) || {}) }));
405
+ }
406
+
407
+ function listCodexModels(options = {}) {
408
+ const command = buildCommand("codex", ["app-server", "--listen", "stdio://"]);
409
+ const timeoutMs = Math.max(5000, Number(options.timeoutMs || 20000));
410
+ return new Promise((resolve, reject) => {
411
+ let buffer = "", settled = false, modelRequestSent = false;
412
+ let child;
413
+ const finish = (error, value) => {
414
+ if (settled) return;
415
+ settled = true;
416
+ clearTimeout(timer);
417
+ try { child?.kill(); } catch {}
418
+ if (error) reject(error); else resolve(value);
419
+ };
420
+ const timer = setTimeout(() => finish(new Error(`Codex model listesi ${Math.round(timeoutMs / 1000)} saniyede alınamadı.`)), timeoutMs);
421
+ try { child = spawn(command.file, command.args, { shell: command.shell, windowsHide: true, windowsVerbatimArguments: !!command.verbatim }); }
422
+ catch (error) { finish(error); return; }
423
+ child.stdout?.setEncoding("utf8");
424
+ child.stderr?.setEncoding("utf8");
425
+ child.stdout?.on("data", (chunk) => {
426
+ buffer += String(chunk);
427
+ const lines = buffer.split(/\r?\n/);
428
+ buffer = lines.pop() || "";
429
+ for (const line of lines) {
430
+ let message;
431
+ try { message = JSON.parse(line); } catch { continue; }
432
+ if (message.id === 1 && !modelRequestSent) {
433
+ modelRequestSent = true;
434
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 2, method: "model/list", params: { includeHidden: false, limit: 200 } })}\n`);
435
+ } else if (message.id === 2) {
436
+ if (message.error) { finish(new Error(message.error.message || "Codex model listesi alınamadı.")); return; }
437
+ const models = Array.isArray(message.result?.data) ? message.result.data : [];
438
+ finish(null, models.filter((model) => model && model.hidden !== true).map((model) => ({
439
+ id: String(model.id || model.model || ""),
440
+ model: String(model.model || model.id || ""),
441
+ displayName: String(model.displayName || model.id || model.model || ""),
442
+ description: String(model.description || ""),
443
+ defaultReasoningEffort: String(model.defaultReasoningEffort || "medium"),
444
+ reasoningEfforts: (model.supportedReasoningEfforts || []).map((item) => ({
445
+ id: String(item.reasoningEffort || item.id || ""),
446
+ description: String(item.description || ""),
447
+ })).filter((item) => item.id),
448
+ serviceTiers: (model.serviceTiers || []).map((item) => ({
449
+ id: String(item.id || ""),
450
+ name: String(item.name || item.id || ""),
451
+ description: String(item.description || ""),
452
+ })).filter((item) => item.id),
453
+ additionalSpeedTiers: Array.isArray(model.additionalSpeedTiers) ? model.additionalSpeedTiers.map(String) : [],
454
+ defaultServiceTier: model.defaultServiceTier ? String(model.defaultServiceTier) : "",
455
+ isDefault: model.isDefault === true,
456
+ })).filter((model) => model.id));
457
+ }
458
+ }
459
+ });
460
+ child.stderr?.on("data", () => {});
461
+ child.on("error", finish);
462
+ child.stdin?.on("error", () => {});
463
+ child.stdin?.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { clientInfo: { name: "crewctl", version: "1.0.0", title: "CrewCtl" } } })}\n`);
464
+ });
465
+ }
466
+
467
+ function addMissingAgents(cfg, discovered) {
468
+ cfg.agents ||= {};
469
+ const ignored = new Set(Array.isArray(cfg.discoveryIgnoredAdapters) ? cfg.discoveryIgnoredAdapters.map(String) : []);
470
+ let changed = normalizeAgentAdapters(cfg);
471
+ for (const cli of discovered) {
472
+ const usable = cli.installed && (cli.id !== "opencode" || cli.ready !== false || Boolean(cfg.cliSettings?.opencode?.model));
473
+ const matchingEntries = Object.entries(cfg.agents).filter(([, agent]) => (agent.adapter || adapterId(agent.cmd)) === cli.id);
474
+ const existingEntry = matchingEntries.find(([, agent]) => !agent.autoDiscovered) || matchingEntries[0];
475
+ const existing = existingEntry?.[1];
476
+ // Kullanici otomatik bulunan bir profili sildiyse bu karar kalicidir. O adapter'a ait
477
+ // elle olusturulmus profil varsa ona dokunma; yalnizca autoDiscovered kaydini temizle.
478
+ if (ignored.has(cli.id)) {
479
+ for (const [name, agent] of matchingEntries) {
480
+ if (!agent.autoDiscovered) continue;
481
+ delete cfg.agents[name];
482
+ changed = true;
483
+ }
484
+ continue;
485
+ }
486
+ if (existing) {
487
+ if (usable && existing.autoDiscovered && existing.unavailablePlaceholder) {
488
+ existing.enabled = true;
489
+ existing.args = cli.defaultArgs.slice();
490
+ delete existing.unavailablePlaceholder;
491
+ changed = true;
492
+ }
493
+ // Eski surumler otomatik oneriyi agent.model alanina yaziyordu. Bu alan global
494
+ // CLI ayarini ezdigi icin, kullanici tarafindan acikca override olarak isaretlenmemis
495
+ // otomatik profiller modeli daima CLI ayarindan/otomatik secimden miras alir.
496
+ if (cli.id === "opencode" && existing.autoDiscovered && existing.model && existing.modelOverride !== true) {
497
+ delete existing.model;
498
+ changed = true;
499
+ }
500
+ if (cli.installed && cli.id === "opencode" && existing.autoDiscovered && Number(existing.timeoutSeconds || 0) < cli.timeoutSeconds) {
501
+ existing.timeoutSeconds = cli.timeoutSeconds;
502
+ changed = true;
503
+ }
504
+ if (!usable && existing.autoDiscovered && existing.enabled !== false) {
505
+ existing.enabled = false;
506
+ existing.unavailablePlaceholder = true;
507
+ changed = true;
508
+ }
509
+ continue;
510
+ }
511
+ // OpenCode adapteri her cihazda katalogda gorunur. Kurulu degilse guvenli
512
+ // sekilde devre disi placeholder olur; taramada bulundugunda otomatik etkinlesir.
513
+ if (!cli.installed && cli.id !== "opencode") continue;
514
+ let name = `${cli.id}-auto`, suffix = 2;
515
+ while (cfg.agents[name]) name = `${cli.id}-auto-${suffix++}`;
516
+ cfg.agents[name] = {
517
+ adapter: cli.id,
518
+ cmd: cli.command,
519
+ args: cli.defaultArgs.slice(),
520
+ enabled: usable,
521
+ description: cli.description,
522
+ capabilities: cli.capabilities.slice(),
523
+ roleFile: cli.roleFile,
524
+ costTier: "standard",
525
+ timeoutSeconds: cli.timeoutSeconds || 1200,
526
+ ...(cli.silenceTimeoutSeconds ? { silenceTimeoutSeconds: cli.silenceTimeoutSeconds } : {}),
527
+ autoDiscovered: true,
528
+ ...(!usable ? { unavailablePlaceholder: true } : {}),
529
+ };
530
+ changed = true;
531
+ }
532
+ return changed;
533
+ }
534
+
535
+ // Operator, uzman agent'lardan BAGIMSIZ bir CLI secimidir (claude/codex/gemini/opencode).
536
+ // operator.md rolunu bu CLI giyer; uzman agent'lar operatorun ALTINDA delege edilir.
537
+ // Bir uzman agent silinse bile operator etkilenmez.
538
+ function operatorSpec(cli, cfg) {
539
+ const op = (cfg && cfg.operator) || {};
540
+ const definition = DEFINITIONS[cli];
541
+ // Standart CLI'lar DEFINITIONS'tan cozulur. cfg.operator.cmd verilirse (ozel/test operatoru)
542
+ // dogrudan o komut kullanilir; boylece operator, uzman agent'lardan tamamen bagimsiz kalir.
543
+ const cmd = op.cmd || (definition && definition.command);
544
+ if (!cmd) return null;
545
+ const args = op.cmd ? (Array.isArray(op.args) ? op.args.slice() : []) : (definition ? definition.defaultArgs.slice() : []);
546
+ // Model/effort/tier secimi CLI bazlidir (cfg.cliSettings) ve effectiveAgent icinde uygulanir;
547
+ // ayni ayar o CLI'yi kullanan operator ve tum uzman agent'lar icin gecerlidir.
548
+ const timeoutSeconds = op.timeoutSeconds || (cfg && cfg.agentTimeoutSeconds) || 900;
549
+ const silenceTimeoutSeconds = op.silenceTimeoutSeconds || (definition && definition.silenceTimeoutSeconds) || (cfg && cfg.cliSilenceTimeoutSeconds) || 300;
550
+ const adapter = definition ? cli : (op.adapter || adapterId(cmd));
551
+ return effectiveAgent({ adapter, cmd, args, timeoutSeconds, silenceTimeoutSeconds }, cfg);
552
+ }
553
+
554
+ // Operator gecerli, kurulu bir CLI olmali. Eski semada operator.agent (uzman agent adi)
555
+ // tutuluyordu; burada operator.cli'ye tasinir. Kurulu degilse ilk kurulu CLI'ye gecilir.
556
+ function ensureValidOperator(cfg, discovered) {
557
+ cfg.operator ||= {};
558
+ let changed = false;
559
+ if (cfg.operator.roleFile !== "roles/operator.md") { cfg.operator.roleFile = "roles/operator.md"; changed = true; }
560
+ if (!cfg.operator.cli) {
561
+ const legacy = cfg.operator.agent;
562
+ const source = legacy && cfg.agents?.[legacy] ? cfg.agents[legacy].cmd : legacy;
563
+ cfg.operator.cli = adapterId(source || "codex");
564
+ changed = true;
565
+ }
566
+ if ("agent" in cfg.operator) { delete cfg.operator.agent; changed = true; }
567
+ const installed = Array.isArray(discovered) ? discovered
568
+ .filter((x) => x.installed && (x.id !== "opencode" || x.ready !== false || Boolean(cfg.cliSettings?.opencode?.model)))
569
+ .map((x) => x.id) : null;
570
+ const known = !!DEFINITIONS[cfg.operator.cli];
571
+ const availableOnHost = !installed || installed.length === 0 || installed.includes(cfg.operator.cli);
572
+ if (!known || !availableOnHost) {
573
+ const fallback = (installed && installed[0]) || Object.keys(DEFINITIONS)[0];
574
+ if (fallback && fallback !== cfg.operator.cli) { cfg.operator.cli = fallback; changed = true; }
575
+ }
576
+ return changed;
577
+ }
578
+
579
+ module.exports = { DEFINITIONS, KNOWN_CLIS: Object.keys(DEFINITIONS), adapterId, normalizeAgentAdapter, normalizeAgentAdapters, effectiveAgent, preparePromptArgs, operatorSpec, buildCommand, agentEnvironment, discoverInstalled, healthCheckAll, listCodexModels, selectOpenCodeModel, parseOpenCodeModels, addMissingAgents, ensureValidOperator };