@ngockhoale/ckit 0.0.0-stage → 0.1.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.
- package/.env.example +42 -0
- package/README.md +116 -2
- package/dist/src/adapters/agent/claude/errors.d.ts +13 -0
- package/dist/src/adapters/agent/claude/errors.js +16 -0
- package/dist/src/adapters/agent/claude/normalize.d.ts +11 -0
- package/dist/src/adapters/agent/claude/normalize.js +83 -0
- package/dist/src/adapters/agent/errors.d.ts +13 -0
- package/dist/src/adapters/agent/errors.js +19 -0
- package/dist/src/adapters/agent/fixtures/claude-transcript.d.ts +70 -0
- package/dist/src/adapters/agent/fixtures/claude-transcript.js +15 -0
- package/dist/src/adapters/agent/fixtures/omp-transcript.d.ts +60 -0
- package/dist/src/adapters/agent/fixtures/omp-transcript.js +14 -0
- package/dist/src/adapters/agent/normalize.d.ts +18 -0
- package/dist/src/adapters/agent/normalize.js +77 -0
- package/dist/src/adapters/agent/transport.d.ts +35 -0
- package/dist/src/adapters/agent/transport.js +39 -0
- package/dist/src/adapters/agent/worker-service.d.ts +49 -0
- package/dist/src/adapters/agent/worker-service.js +77 -0
- package/dist/src/adapters/fake/fake-advisor.d.ts +15 -0
- package/dist/src/adapters/fake/fake-advisor.js +29 -0
- package/dist/src/adapters/fake/fake-agent.d.ts +12 -0
- package/dist/src/adapters/fake/fake-agent.js +21 -0
- package/dist/src/adapters/fake/fake-store.d.ts +13 -0
- package/dist/src/adapters/fake/fake-store.js +23 -0
- package/dist/src/adapters/fake/fake-web.d.ts +12 -0
- package/dist/src/adapters/fake/fake-web.js +21 -0
- package/dist/src/adapters/fake/fault-injector.d.ts +18 -0
- package/dist/src/adapters/fake/fault-injector.js +64 -0
- package/dist/src/adapters/fake/virtual-clock.d.ts +12 -0
- package/dist/src/adapters/fake/virtual-clock.js +35 -0
- package/dist/src/adapters/launch/discover.d.ts +18 -0
- package/dist/src/adapters/launch/discover.js +55 -0
- package/dist/src/adapters/launch/executor.d.ts +117 -0
- package/dist/src/adapters/launch/executor.js +383 -0
- package/dist/src/adapters/launch/profile.d.ts +35 -0
- package/dist/src/adapters/launch/profile.js +73 -0
- package/dist/src/adapters/launch/spawn.d.ts +29 -0
- package/dist/src/adapters/launch/spawn.js +18 -0
- package/dist/src/adapters/openai/openai-advisor.d.ts +56 -0
- package/dist/src/adapters/openai/openai-advisor.js +146 -0
- package/dist/src/cli/ckit.d.ts +5 -0
- package/dist/src/cli/ckit.js +472 -0
- package/dist/src/cli/demo.d.ts +1 -0
- package/dist/src/cli/demo.js +30 -0
- package/dist/src/cli/sessions.d.ts +10 -0
- package/dist/src/cli/sessions.js +381 -0
- package/dist/src/cli/setup.d.ts +11 -0
- package/dist/src/cli/setup.js +115 -0
- package/dist/src/committee/decision.d.ts +84 -0
- package/dist/src/committee/decision.js +167 -0
- package/dist/src/committee/handover.d.ts +115 -0
- package/dist/src/committee/handover.js +191 -0
- package/dist/src/committee/no-progress.d.ts +44 -0
- package/dist/src/committee/no-progress.js +64 -0
- package/dist/src/committee/primary-registry.d.ts +15 -0
- package/dist/src/committee/primary-registry.js +60 -0
- package/dist/src/committee/reply-parser.d.ts +28 -0
- package/dist/src/committee/reply-parser.js +53 -0
- package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
- package/dist/src/committee/reviewer-scheduler.js +163 -0
- package/dist/src/committee/role-epoch.d.ts +91 -0
- package/dist/src/committee/role-epoch.js +154 -0
- package/dist/src/core/control.d.ts +18 -0
- package/dist/src/core/control.js +29 -0
- package/dist/src/core/entities.d.ts +166 -0
- package/dist/src/core/entities.js +119 -0
- package/dist/src/core/errors.d.ts +9 -0
- package/dist/src/core/errors.js +17 -0
- package/dist/src/core/events.d.ts +72 -0
- package/dist/src/core/events.js +125 -0
- package/dist/src/core/ids.d.ts +47 -0
- package/dist/src/core/ids.js +32 -0
- package/dist/src/core/machine.d.ts +55 -0
- package/dist/src/core/machine.js +110 -0
- package/dist/src/core/policy.d.ts +34 -0
- package/dist/src/core/policy.js +59 -0
- package/dist/src/core/provenance.d.ts +20 -0
- package/dist/src/core/provenance.js +21 -0
- package/dist/src/core/record.d.ts +35 -0
- package/dist/src/core/record.js +67 -0
- package/dist/src/core/replay.d.ts +10 -0
- package/dist/src/core/replay.js +36 -0
- package/dist/src/core/run-task.d.ts +20 -0
- package/dist/src/core/run-task.js +48 -0
- package/dist/src/diagnostics/doctor.d.ts +78 -0
- package/dist/src/diagnostics/doctor.js +365 -0
- package/dist/src/diagnostics/journal-lock.d.ts +38 -0
- package/dist/src/diagnostics/journal-lock.js +181 -0
- package/dist/src/evidence/linker.d.ts +44 -0
- package/dist/src/evidence/linker.js +75 -0
- package/dist/src/evidence/report-parser.d.ts +27 -0
- package/dist/src/evidence/report-parser.js +17 -0
- package/dist/src/evidence/store.d.ts +36 -0
- package/dist/src/evidence/store.js +57 -0
- package/dist/src/gui/server.d.ts +27 -0
- package/dist/src/gui/server.js +497 -0
- package/dist/src/host/checkpoint.d.ts +22 -0
- package/dist/src/host/checkpoint.js +74 -0
- package/dist/src/host/export.d.ts +52 -0
- package/dist/src/host/export.js +45 -0
- package/dist/src/host/ipc.d.ts +57 -0
- package/dist/src/host/ipc.js +124 -0
- package/dist/src/host/leases.d.ts +27 -0
- package/dist/src/host/leases.js +40 -0
- package/dist/src/host/retention.d.ts +47 -0
- package/dist/src/host/retention.js +130 -0
- package/dist/src/host/supervisor.d.ts +59 -0
- package/dist/src/host/supervisor.js +64 -0
- package/dist/src/intake/owner-intake.d.ts +31 -0
- package/dist/src/intake/owner-intake.js +97 -0
- package/dist/src/intake/types.d.ts +46 -0
- package/dist/src/intake/types.js +2 -0
- package/dist/src/intent/context-packet.d.ts +68 -0
- package/dist/src/intent/context-packet.js +76 -0
- package/dist/src/intent/idea-ledger.d.ts +50 -0
- package/dist/src/intent/idea-ledger.js +136 -0
- package/dist/src/intent/ledger.d.ts +35 -0
- package/dist/src/intent/ledger.js +40 -0
- package/dist/src/intent/registry.d.ts +51 -0
- package/dist/src/intent/registry.js +44 -0
- package/dist/src/intent/revision.d.ts +37 -0
- package/dist/src/intent/revision.js +48 -0
- package/dist/src/orchestration/dispatcher.d.ts +32 -0
- package/dist/src/orchestration/dispatcher.js +136 -0
- package/dist/src/orchestration/milestone-loop.d.ts +149 -0
- package/dist/src/orchestration/milestone-loop.js +132 -0
- package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
- package/dist/src/orchestration/recovery-coordinator.js +180 -0
- package/dist/src/orchestration/work-order-contract.d.ts +44 -0
- package/dist/src/orchestration/work-order-contract.js +85 -0
- package/dist/src/orchestration/work-queue.d.ts +56 -0
- package/dist/src/orchestration/work-queue.js +95 -0
- package/dist/src/ports/advisor.d.ts +33 -0
- package/dist/src/ports/advisor.js +2 -0
- package/dist/src/ports/agent.d.ts +31 -0
- package/dist/src/ports/agent.js +2 -0
- package/dist/src/ports/capabilities.d.ts +3 -0
- package/dist/src/ports/capabilities.js +5 -0
- package/dist/src/ports/clock.d.ts +5 -0
- package/dist/src/ports/clock.js +5 -0
- package/dist/src/ports/store.d.ts +13 -0
- package/dist/src/ports/store.js +2 -0
- package/dist/src/ports/web.d.ts +29 -0
- package/dist/src/ports/web.js +2 -0
- package/dist/src/run/api-run.d.ts +49 -0
- package/dist/src/run/api-run.js +173 -0
- package/dist/src/run/plan-run.d.ts +22 -0
- package/dist/src/run/plan-run.js +233 -0
- package/dist/src/run/plan.d.ts +36 -0
- package/dist/src/run/plan.js +119 -0
- package/dist/src/run/verify.d.ts +25 -0
- package/dist/src/run/verify.js +81 -0
- package/dist/src/security/redact.d.ts +7 -0
- package/dist/src/security/redact.js +21 -0
- package/dist/src/settings/env-config.d.ts +64 -0
- package/dist/src/settings/env-config.js +232 -0
- package/dist/src/storage/artifacts.d.ts +30 -0
- package/dist/src/storage/artifacts.js +105 -0
- package/dist/src/storage/audit.d.ts +6 -0
- package/dist/src/storage/audit.js +6 -0
- package/dist/src/storage/db.d.ts +9 -0
- package/dist/src/storage/db.js +43 -0
- package/dist/src/storage/events.d.ts +20 -0
- package/dist/src/storage/events.js +69 -0
- package/dist/src/storage/migrations.d.ts +8 -0
- package/dist/src/storage/migrations.js +48 -0
- package/dist/src/storage/outbox.d.ts +25 -0
- package/dist/src/storage/outbox.js +40 -0
- package/dist/src/storage/projections.d.ts +18 -0
- package/dist/src/storage/projections.js +40 -0
- package/dist/src/storage/reconcile.d.ts +14 -0
- package/dist/src/storage/reconcile.js +93 -0
- package/dist/src/storage/reservations.d.ts +12 -0
- package/dist/src/storage/reservations.js +80 -0
- package/dist/src/storage/store.d.ts +34 -0
- package/dist/src/storage/store.js +105 -0
- package/dist/src/team/attachments.d.ts +22 -0
- package/dist/src/team/attachments.js +211 -0
- package/dist/src/team/cli-models.d.ts +24 -0
- package/dist/src/team/cli-models.js +72 -0
- package/dist/src/team/config.d.ts +20 -0
- package/dist/src/team/config.js +111 -0
- package/dist/src/team/engine.d.ts +28 -0
- package/dist/src/team/engine.js +443 -0
- package/dist/src/team/journal.d.ts +30 -0
- package/dist/src/team/journal.js +70 -0
- package/dist/src/team/runners.d.ts +79 -0
- package/dist/src/team/runners.js +436 -0
- package/dist/src/team/secrets.d.ts +10 -0
- package/dist/src/team/secrets.js +68 -0
- package/dist/src/team/types.d.ts +155 -0
- package/dist/src/team/types.js +5 -0
- package/dist/src/tui/app.d.ts +29 -0
- package/dist/src/tui/app.js +96 -0
- package/dist/src/tui/control-model.d.ts +101 -0
- package/dist/src/tui/control-model.js +109 -0
- package/dist/src/tui/control-screens.d.ts +27 -0
- package/dist/src/tui/control-screens.js +85 -0
- package/dist/src/tui/graph-model.d.ts +34 -0
- package/dist/src/tui/graph-model.js +29 -0
- package/dist/src/tui/graph-screens.d.ts +13 -0
- package/dist/src/tui/graph-screens.js +4 -0
- package/dist/src/tui/inspector-model.d.ts +150 -0
- package/dist/src/tui/inspector-model.js +15 -0
- package/dist/src/tui/inspector-screens.d.ts +14 -0
- package/dist/src/tui/inspector-screens.js +61 -0
- package/dist/src/tui/live.d.ts +16 -0
- package/dist/src/tui/live.js +39 -0
- package/dist/src/tui/mission-action-screens.d.ts +15 -0
- package/dist/src/tui/mission-action-screens.js +105 -0
- package/dist/src/tui/mission-actions.d.ts +46 -0
- package/dist/src/tui/mission-actions.js +53 -0
- package/dist/src/tui/mission-model.d.ts +120 -0
- package/dist/src/tui/mission-model.js +164 -0
- package/dist/src/tui/mission-nav.d.ts +82 -0
- package/dist/src/tui/mission-nav.js +131 -0
- package/dist/src/tui/mission-plan-screens.d.ts +11 -0
- package/dist/src/tui/mission-plan-screens.js +40 -0
- package/dist/src/tui/mission-plan.d.ts +45 -0
- package/dist/src/tui/mission-plan.js +166 -0
- package/dist/src/tui/mission-screens.d.ts +7 -0
- package/dist/src/tui/mission-screens.js +263 -0
- package/dist/src/tui/provenance-label.d.ts +11 -0
- package/dist/src/tui/provenance-label.js +16 -0
- package/dist/src/tui/screens.d.ts +10 -0
- package/dist/src/tui/screens.js +34 -0
- package/dist/src/tui/session-outcome.d.ts +14 -0
- package/dist/src/tui/session-outcome.js +57 -0
- package/dist/src/tui/setup-model.d.ts +159 -0
- package/dist/src/tui/setup-model.js +234 -0
- package/dist/src/tui/setup-screens.d.ts +66 -0
- package/dist/src/tui/setup-screens.js +72 -0
- package/dist/src/tui/team/app.d.ts +24 -0
- package/dist/src/tui/team/app.js +228 -0
- package/dist/src/tui/team/demo-handle.d.ts +22 -0
- package/dist/src/tui/team/demo-handle.js +42 -0
- package/dist/src/tui/team/model.d.ts +81 -0
- package/dist/src/tui/team/model.js +133 -0
- package/gui/app.css +177 -0
- package/gui/app.js +675 -0
- package/gui/index.html +51 -0
- package/gui/network.js +413 -0
- package/package.json +45 -4
- package/src/storage/schema.sql +42 -0
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
// Agent runners for team mode: codex / claude-code / omp / api (real) and `simulated` (offline demo). All share one AgentRunner shape.
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { accessSync, constants, readFileSync, statSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { delimiter, isAbsolute, join } from 'node:path';
|
|
6
|
+
import { claudeSubagentObservations, envBoundaryNote, executorEnvironment, executorEnvironmentReport, parseExecutorOutput, resolveExecutable, runExecutor, selectExecutor, ExecutorResolveError } from '../adapters/launch/executor.js';
|
|
7
|
+
import { OpenAiCompatibleAdvisor } from '../adapters/openai/openai-advisor.js';
|
|
8
|
+
import { readSecret } from './secrets.js';
|
|
9
|
+
import { loadCkitConfig, resolveProjectRoot } from '../settings/env-config.js';
|
|
10
|
+
const oneLine = (s, max = 120) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
|
|
11
|
+
/** CKit advisor key to keep away from workers. The workspace may be a sub-folder of the repository that holds the CKit config, so the enclosing project is checked too. */
|
|
12
|
+
export const advisorKeyOf = (cwd) => {
|
|
13
|
+
for (const root of new Set([cwd, resolveProjectRoot(cwd)])) {
|
|
14
|
+
const r = loadCkitConfig({ projectRoot: root });
|
|
15
|
+
if (r.ok && r.config.apiKey)
|
|
16
|
+
return r.config.apiKey;
|
|
17
|
+
}
|
|
18
|
+
return '';
|
|
19
|
+
};
|
|
20
|
+
/** Pure: one parsed `codex exec --json` frame -> activity line / final-message candidate / token usage. `error` items are warnings, not fatal. */
|
|
21
|
+
export function parseCodexFrame(frame) {
|
|
22
|
+
if (!frame || typeof frame !== 'object')
|
|
23
|
+
return {};
|
|
24
|
+
const f = frame;
|
|
25
|
+
const str = (v) => typeof v === 'string' ? v : '';
|
|
26
|
+
if (f.type === 'turn.completed' && f.usage) {
|
|
27
|
+
const a = f.usage['input_tokens'], b = f.usage['output_tokens'];
|
|
28
|
+
return { tokens: (typeof a === 'number' ? a : 0) + (typeof b === 'number' ? b : 0) };
|
|
29
|
+
}
|
|
30
|
+
// codex reports the real failure on stdout (stderr only carries a stdin notice), so keep it for the failure reason.
|
|
31
|
+
if (f.type === 'error')
|
|
32
|
+
return { error: str(f.message) };
|
|
33
|
+
if (f.type === 'turn.failed') {
|
|
34
|
+
const er = f.error;
|
|
35
|
+
return { error: str(er?.message) };
|
|
36
|
+
}
|
|
37
|
+
if ((f.type !== 'item.completed' && f.type !== 'item.started') || !f.item)
|
|
38
|
+
return {};
|
|
39
|
+
const it = f.item, kind = str(it['type']);
|
|
40
|
+
if (kind === 'agent_message')
|
|
41
|
+
return f.type === 'item.completed' ? { message: str(it['text']) } : {};
|
|
42
|
+
if (f.type === 'item.started')
|
|
43
|
+
return {};
|
|
44
|
+
if (kind === 'command_execution')
|
|
45
|
+
return { activity: oneLine(`$ ${str(it['command'])}`) };
|
|
46
|
+
if (kind === 'file_change') {
|
|
47
|
+
const ch = it['changes'];
|
|
48
|
+
const paths = Array.isArray(ch) ? ch.map(c => c && typeof c === 'object' ? str(c.path) : '').filter(Boolean) : [];
|
|
49
|
+
return { activity: oneLine(`edited ${paths.length ? paths.join(', ') : 'files'}`) };
|
|
50
|
+
}
|
|
51
|
+
if (kind === 'reasoning')
|
|
52
|
+
return str(it['text']) ? { activity: oneLine(`thinking: ${str(it['text'])}`) } : {};
|
|
53
|
+
if (kind === 'error')
|
|
54
|
+
return { activity: oneLine(`warning: ${str(it['message'])}`), error: str(it['message']) };
|
|
55
|
+
return {};
|
|
56
|
+
}
|
|
57
|
+
function findOnPath(name, env) {
|
|
58
|
+
for (const dir of (env['PATH'] ?? '').split(delimiter).filter(Boolean)) {
|
|
59
|
+
if (!isAbsolute(dir))
|
|
60
|
+
continue;
|
|
61
|
+
const p = join(dir, name);
|
|
62
|
+
try {
|
|
63
|
+
if (statSync(p).isFile()) {
|
|
64
|
+
accessSync(p, constants.X_OK);
|
|
65
|
+
return p;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch { /* next */ }
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
export function codexArgs(agent, cwd, prompt, images = []) {
|
|
73
|
+
// `-i` takes several values, so it goes after the prompt: placed before, it would swallow the prompt as one more image path.
|
|
74
|
+
return ['exec', '--json', '--skip-git-repo-check', '--ephemeral', '-s', agent.access === 'write' ? 'workspace-write' : 'read-only', '-C', cwd, ...(agent.model ? ['-m', agent.model] : []), prompt.startsWith('-') ? ` ${prompt}` : prompt, ...images.slice(0, 8).flatMap(f => ['-i', f])];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Codex worker env. Same boundary as the other workers, with one documented exemption (mirrors the claude-code allowlist): a variable that
|
|
78
|
+
* codex's own config.toml names as a provider credential (`env_key = "NAME"`), or OPENAI_API_KEY (codex's built-in provider), is kept when it
|
|
79
|
+
* is inherited from the launching env even if its value equals the advisor key. An equal value there means the user points both tools at the
|
|
80
|
+
* same gateway, not that CKit copied the advisor key. Values that merely contain the key, and every other name, stay withheld.
|
|
81
|
+
*/
|
|
82
|
+
export function codexWorkerEnv(processEnv, advisorKey, configToml) {
|
|
83
|
+
const policy = executorEnvironmentReport(processEnv, advisorKey, 'omp');
|
|
84
|
+
const names = new Set(['OPENAI_API_KEY', ...[...configToml.matchAll(/^\s*env_key\s*=\s*"([A-Za-z_][A-Za-z0-9_]*)"/gm)].map(m => m[1])]);
|
|
85
|
+
const env = { ...policy.env }, withheld = policy.withheld.filter(w => {
|
|
86
|
+
const v = processEnv[w.name];
|
|
87
|
+
if (w.reason !== 'equals-advisor-key' || !names.has(w.name) || v === undefined)
|
|
88
|
+
return true;
|
|
89
|
+
env[w.name] = v;
|
|
90
|
+
return false;
|
|
91
|
+
});
|
|
92
|
+
return { env, withheld, workerAuth: policy.workerAuth };
|
|
93
|
+
}
|
|
94
|
+
const codexConfigText = (env) => {
|
|
95
|
+
try {
|
|
96
|
+
return readFileSync(join(env['CODEX_HOME'] || join(homedir(), '.codex'), 'config.toml'), 'utf8');
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return '';
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const KILL_GRACE_MS = 3000;
|
|
103
|
+
export function runCodex(agent, prompt, opts) {
|
|
104
|
+
return new Promise(resolve => {
|
|
105
|
+
const policy = opts.env ? null : codexWorkerEnv(process.env, advisorKeyOf(opts.cwd), codexConfigText(process.env));
|
|
106
|
+
const env = opts.env ?? policy.env;
|
|
107
|
+
const boundary = policy ? envBoundaryNote(policy.withheld) : null;
|
|
108
|
+
const path = findOnPath('codex', env);
|
|
109
|
+
if (!path) {
|
|
110
|
+
resolve({ ok: false, reason: 'codex not found on PATH; install it or change the agent cli' });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const grouped = process.platform !== 'win32';
|
|
114
|
+
let child;
|
|
115
|
+
try {
|
|
116
|
+
child = spawn(path, codexArgs(agent, opts.cwd, prompt, opts.images), { cwd: opts.cwd, shell: false, env, stdio: ['ignore', 'pipe', 'pipe'], ...(grouped ? { detached: true } : {}) });
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
resolve({ ok: false, reason: e instanceof Error ? e.message : 'spawn failed' });
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const errors = [];
|
|
123
|
+
let pending = '', stderr = '', last = '', tokens = null, done = false, stop = null, killTimer;
|
|
124
|
+
const signalTree = (sig) => {
|
|
125
|
+
const pid = child.pid;
|
|
126
|
+
if (grouped && typeof pid === 'number' && pid > 1) {
|
|
127
|
+
try {
|
|
128
|
+
process.kill(-pid, sig);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
catch { /* group gone */ }
|
|
132
|
+
}
|
|
133
|
+
child.kill(sig);
|
|
134
|
+
};
|
|
135
|
+
const finish = (r) => { if (done)
|
|
136
|
+
return; done = true; clearTimeout(timer); clearTimeout(killTimer); opts.signal?.removeEventListener('abort', onAbort); resolve(r); };
|
|
137
|
+
const kill = (why) => {
|
|
138
|
+
if (stop)
|
|
139
|
+
return;
|
|
140
|
+
stop = why;
|
|
141
|
+
signalTree('SIGTERM');
|
|
142
|
+
killTimer = setTimeout(() => { signalTree('SIGKILL'); finish({ ok: false, reason: why === 'timeout' ? 'timed out' : 'cancelled' }); }, KILL_GRACE_MS);
|
|
143
|
+
};
|
|
144
|
+
const timer = setTimeout(() => kill('timeout'), opts.timeoutMs);
|
|
145
|
+
const onAbort = () => kill('cancelled');
|
|
146
|
+
if (opts.signal?.aborted)
|
|
147
|
+
onAbort();
|
|
148
|
+
else
|
|
149
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
150
|
+
const handle = (line) => {
|
|
151
|
+
const t = line.trim();
|
|
152
|
+
if (!t.startsWith('{'))
|
|
153
|
+
return;
|
|
154
|
+
let frame;
|
|
155
|
+
try {
|
|
156
|
+
frame = JSON.parse(t);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const info = parseCodexFrame(frame);
|
|
162
|
+
if (info.message !== undefined && info.message.trim())
|
|
163
|
+
last = info.message;
|
|
164
|
+
if (info.tokens !== undefined)
|
|
165
|
+
tokens = info.tokens;
|
|
166
|
+
if (info.error && !errors.includes(info.error)) {
|
|
167
|
+
errors.push(info.error);
|
|
168
|
+
if (errors.length > 6)
|
|
169
|
+
errors.shift();
|
|
170
|
+
}
|
|
171
|
+
if (info.activity) {
|
|
172
|
+
try {
|
|
173
|
+
opts.onActivity?.(info.activity);
|
|
174
|
+
}
|
|
175
|
+
catch { /* observer must not break the run */ }
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
child.stdout?.on('data', (c) => { pending += c.toString('utf8'); const lines = pending.split('\n'); pending = lines.pop() ?? ''; lines.forEach(handle); });
|
|
179
|
+
child.stderr?.on('data', (c) => { stderr = (stderr + c.toString('utf8')).slice(-2000); });
|
|
180
|
+
child.on('error', e => finish({ ok: false, reason: e.message }));
|
|
181
|
+
child.on('close', code => {
|
|
182
|
+
if (pending)
|
|
183
|
+
handle(pending);
|
|
184
|
+
if (stop) {
|
|
185
|
+
finish({ ok: false, reason: stop === 'timeout' ? 'timed out' : 'cancelled' });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (code === 0 && last.trim())
|
|
189
|
+
finish({ ok: true, text: last, tokens });
|
|
190
|
+
else {
|
|
191
|
+
const noise = /^Reading additional input from stdin/;
|
|
192
|
+
const detail = [...errors, ...stderr.split('\n').map(l => l.trim()).filter(l => l && !noise.test(l))].map(l => l.slice(0, 600)).join('\n');
|
|
193
|
+
finish({ ok: false, reason: `${code === 0 ? 'codex produced no agent message' : `codex exited ${code}`}${detail ? `:\n${detail}` : ' (codex printed no error detail)'}${boundary ? `\nCKit ${boundary}. These variables hold the same value as the CKit advisor key, which is never passed to worker agents. Give this agent its own credential (a different key, or the CLI's own login), or switch the agent to another cli in Settings.` : ''}` });
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
// ---- claude / omp via the shared executor ----
|
|
199
|
+
/** Pure: claude stream-json frame -> short activity lines. */
|
|
200
|
+
export function claudeFrameActivity(frame) {
|
|
201
|
+
if (!frame || typeof frame !== 'object')
|
|
202
|
+
return [];
|
|
203
|
+
const f = frame;
|
|
204
|
+
if (f.type !== 'assistant' || !Array.isArray(f.message?.content))
|
|
205
|
+
return [];
|
|
206
|
+
const out = [];
|
|
207
|
+
for (const part of f.message.content) {
|
|
208
|
+
if (!part || typeof part !== 'object')
|
|
209
|
+
continue;
|
|
210
|
+
const p = part;
|
|
211
|
+
if (p.type === 'tool_use' && typeof p.name === 'string') {
|
|
212
|
+
const input = p.input && typeof p.input === 'object' ? Object.values(p.input).find(v => typeof v === 'string') : undefined;
|
|
213
|
+
out.push(oneLine(`tool: ${p.name}${typeof input === 'string' ? ` ${input}` : ''}`));
|
|
214
|
+
}
|
|
215
|
+
else if (p.type === 'text' && typeof p.text === 'string' && p.text.trim())
|
|
216
|
+
out.push(oneLine(p.text.trim().split('\n')[0] ?? ''));
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
export async function runExecutorAgent(agent, prompt, opts) {
|
|
221
|
+
const kind = agent.cli === 'omp' ? 'omp' : 'claude-code';
|
|
222
|
+
const spec = selectExecutor({ executor: kind, executorModel: agent.model, executorPermissionMode: kind === 'claude-code' && agent.access === 'write' ? 'acceptEdits' : null });
|
|
223
|
+
const env = opts.env ?? executorEnvironment(process.env, advisorKeyOf(opts.cwd), kind);
|
|
224
|
+
let path;
|
|
225
|
+
try {
|
|
226
|
+
path = resolveExecutable(spec, { executorPath: null }, env);
|
|
227
|
+
}
|
|
228
|
+
catch (e) {
|
|
229
|
+
return { ok: false, reason: e instanceof ExecutorResolveError ? e.message : 'executor not found' };
|
|
230
|
+
}
|
|
231
|
+
const open = new Map(); // childId -> task
|
|
232
|
+
const seen = new Set();
|
|
233
|
+
const startChild = (childId, kind, task) => {
|
|
234
|
+
if (seen.has(childId))
|
|
235
|
+
return;
|
|
236
|
+
seen.add(childId);
|
|
237
|
+
open.set(childId, task);
|
|
238
|
+
opts.onSubagent?.({ type: 'started', childId, kind, task: oneLine(task, 160) });
|
|
239
|
+
};
|
|
240
|
+
const onFrame = (frame) => {
|
|
241
|
+
if (kind !== 'claude-code')
|
|
242
|
+
return;
|
|
243
|
+
for (const o of claudeSubagentObservations(frame))
|
|
244
|
+
startChild(o.childId, o.subagentType, o.description ?? o.subagentType ?? 'subagent');
|
|
245
|
+
const f = frame;
|
|
246
|
+
const parent = typeof f?.parent_tool_use_id === 'string' ? f.parent_tool_use_id : '';
|
|
247
|
+
if (parent && open.has(parent)) {
|
|
248
|
+
for (const a of claudeFrameActivity(frame))
|
|
249
|
+
opts.onSubagent?.({ type: 'activity', childId: parent, text: a });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
for (const a of claudeFrameActivity(frame))
|
|
253
|
+
opts.onActivity?.(a);
|
|
254
|
+
const content = f?.message?.content;
|
|
255
|
+
if (Array.isArray(content))
|
|
256
|
+
for (const part of content) {
|
|
257
|
+
const p = part;
|
|
258
|
+
if (p?.type === 'tool_result' && typeof p.tool_use_id === 'string' && open.has(p.tool_use_id)) {
|
|
259
|
+
const text = typeof p.content === 'string' ? p.content : Array.isArray(p.content) ? p.content.map(c => typeof c.text === 'string' ? c.text : '').join(' ') : '';
|
|
260
|
+
opts.onSubagent?.({ type: 'finished', childId: p.tool_use_id, ok: p.is_error !== true, summary: oneLine(text || 'done', 160) });
|
|
261
|
+
open.delete(p.tool_use_id);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
const r = await runExecutor(spec, path, prompt, {
|
|
266
|
+
cwd: opts.cwd, timeoutMs: opts.timeoutMs, env, ...(opts.signal ? { signal: opts.signal } : {}), onEvent: onFrame,
|
|
267
|
+
});
|
|
268
|
+
for (const [childId] of open)
|
|
269
|
+
opts.onSubagent?.({ type: 'finished', childId, ok: r.status === 'completed', summary: r.status === 'completed' ? 'finished with the turn' : 'turn ended early' });
|
|
270
|
+
if (r.status === 'completed')
|
|
271
|
+
return r.text.trim() ? { ok: true, text: r.text, tokens: null } : { ok: false, reason: 'agent returned no text' };
|
|
272
|
+
if (r.status === 'failed')
|
|
273
|
+
return { ok: false, reason: `exit ${r.exitCode ?? '?'}${r.text.trim() ? `: ${oneLine(r.text, 200)}` : ''}${r.stderrTail ? ` (${oneLine(r.stderrTail, 200)})` : ''}` };
|
|
274
|
+
return { ok: false, reason: r.reason === 'timeout' ? 'timed out' : r.reason === 'cancelled' ? 'cancelled' : r.note };
|
|
275
|
+
}
|
|
276
|
+
export { parseExecutorOutput };
|
|
277
|
+
// ---- api: one OpenAI-compatible chat call, no tools (reuses OpenAiCompatibleAdvisor.sendTurn) ----
|
|
278
|
+
export async function runApiAgent(agent, prompt, opts) {
|
|
279
|
+
const cfg = loadCkitConfig({ projectRoot: opts.cwd });
|
|
280
|
+
if (!cfg.ok && !agent.baseUrl)
|
|
281
|
+
return { ok: false, reason: `CKit API config invalid: ${cfg.issues.map(i => i.variable).join(', ')}` };
|
|
282
|
+
const base = cfg.ok ? cfg.config : null, own = readSecret(agent.apiKeyRef);
|
|
283
|
+
if (agent.apiKeyRef && own === undefined)
|
|
284
|
+
return { ok: false, reason: `stored secret "${agent.apiKeyRef}" not found` };
|
|
285
|
+
const baseUrl = agent.baseUrl ?? base?.baseUrl ?? '', model = agent.model ?? (base ? base.primaryModel || base.model : '');
|
|
286
|
+
if (!model)
|
|
287
|
+
return { ok: false, reason: 'api agent needs a model (set agent.model)' };
|
|
288
|
+
const apiKey = own ?? base?.apiKey ?? '';
|
|
289
|
+
const c = { baseUrl, auth: apiKey ? 'bearer' : (base?.auth ?? 'none'), apiKey, timeoutMs: base?.timeoutMs ?? opts.timeoutMs, maxTokens: base?.maxTokens ?? null };
|
|
290
|
+
let reply = '';
|
|
291
|
+
const advisor = new OpenAiCompatibleAdvisor({ ...c, timeoutMs: Math.min(c.timeoutMs, opts.timeoutMs) }, { saveReply: async (_t, text) => { reply = text; return 'inline'; } }, opts.fetchImpl);
|
|
292
|
+
opts.onActivity?.(`api: ${model}`);
|
|
293
|
+
const thread = advisor.createAdvisorThread('primary', agent.id, model);
|
|
294
|
+
for await (const m of advisor.sendTurn(thread, prompt, opts.signal ? { signal: opts.signal } : {})) {
|
|
295
|
+
if (m.kind === 'completed')
|
|
296
|
+
return { ok: true, text: reply, tokens: null };
|
|
297
|
+
if (m.kind === 'rejected')
|
|
298
|
+
return { ok: false, reason: m.note };
|
|
299
|
+
if (m.kind === 'unknown')
|
|
300
|
+
return { ok: false, reason: opts.signal?.aborted ? 'cancelled' : m.note };
|
|
301
|
+
}
|
|
302
|
+
return { ok: false, reason: 'api returned no reply' };
|
|
303
|
+
}
|
|
304
|
+
/** Default dispatch by agent.cli. `simulated` agents get the scripted runner. */
|
|
305
|
+
export const dispatchRunner = (agent, prompt, opts) => {
|
|
306
|
+
switch (agent.cli) {
|
|
307
|
+
case 'codex': return runCodex(agent, prompt, opts);
|
|
308
|
+
case 'claude-code':
|
|
309
|
+
case 'omp': return runExecutorAgent(agent, prompt, opts);
|
|
310
|
+
case 'api': return runApiAgent(agent, prompt, opts);
|
|
311
|
+
case 'simulated': return createSimulatedRunner()(agent, prompt, opts);
|
|
312
|
+
default: return Promise.resolve({ ok: false, reason: `agent cli "${agent.cli}" cannot run a model turn` });
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
// ---- simulated (offline demo) ----
|
|
316
|
+
/** Engine prompts begin with `[[ckit-team stage=<s> loop=<n> turn=<i>/<n> final=<0|1>]]` and carry a `GOAL: ...` line; the simulator keys off those. */
|
|
317
|
+
export function simHeader(h) {
|
|
318
|
+
return `[[ckit-team stage=${h.stage} loop=${h.loop} turn=${h.turn}/${h.turns} final=${h.final ? 1 : 0}]]`;
|
|
319
|
+
}
|
|
320
|
+
const sleep = (ms, signal) => new Promise(res => {
|
|
321
|
+
if (signal?.aborted) {
|
|
322
|
+
res();
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const t = setTimeout(() => { signal?.removeEventListener('abort', done); res(); }, ms);
|
|
326
|
+
const done = () => { clearTimeout(t); res(); };
|
|
327
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
328
|
+
});
|
|
329
|
+
const hashOf = (s) => { let h = 0; for (const ch of s)
|
|
330
|
+
h = (h * 31 + ch.charCodeAt(0)) >>> 0; return h; };
|
|
331
|
+
export function createSimulatedRunner(options = {}) {
|
|
332
|
+
const envSpeed = Number(process.env['CKIT_TEAM_SIM_SPEED']);
|
|
333
|
+
const speed = options.speed ?? (envSpeed > 0 ? envSpeed : 1);
|
|
334
|
+
return async (agent, prompt, opts) => {
|
|
335
|
+
const hm = /\[\[ckit-team stage=(\S+) loop=(\d+) turn=(\d+)\/(\d+) final=([01])\]\]/.exec(prompt);
|
|
336
|
+
const stage = hm?.[1] ?? 'unknown', loop = Number(hm?.[2] ?? 1), turn = Number(hm?.[3] ?? 1), final = hm?.[5] === '1';
|
|
337
|
+
const goal = oneLine(/^GOAL: (.*)$/m.exec(prompt)?.[1] ?? 'the request', 100);
|
|
338
|
+
const plan = simPlan(agent, stage, loop, turn);
|
|
339
|
+
const totalMs = (2500 + hashOf(agent.id + goal) % 2500) / speed, cancelled = () => opts.signal?.aborted === true;
|
|
340
|
+
const total = plan.steps.length, per = totalMs / (total + 1);
|
|
341
|
+
for (let i = 0; i < total; i++) {
|
|
342
|
+
const st = plan.steps[i];
|
|
343
|
+
opts.onStep?.(st.label, i + 1, total);
|
|
344
|
+
if (st.children) {
|
|
345
|
+
// children overlap in time, each with 3-5 activity lines
|
|
346
|
+
await Promise.all(st.children.map(async (c, k) => {
|
|
347
|
+
const childId = `${agent.id}-${stage}${loop}-sub${k + 1}`;
|
|
348
|
+
opts.onSubagent?.({ type: 'started', childId, kind: c.kind, task: `${c.kind}: ${c.task}` });
|
|
349
|
+
const n = 3 + (hashOf(childId) % 3), gap = (per * 1.6) / (n + 1);
|
|
350
|
+
await sleep(gap * (0.3 + k * 0.25), opts.signal);
|
|
351
|
+
for (let a = 0; a < n && !cancelled(); a++) {
|
|
352
|
+
opts.onSubagent?.({ type: 'activity', childId, text: c.lines[a % c.lines.length] });
|
|
353
|
+
await sleep(gap, opts.signal);
|
|
354
|
+
}
|
|
355
|
+
opts.onSubagent?.({ type: 'finished', childId, ok: true, summary: c.summary });
|
|
356
|
+
}));
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
await sleep(per / 2, opts.signal);
|
|
360
|
+
for (const a of st.activity ?? []) {
|
|
361
|
+
if (cancelled())
|
|
362
|
+
break;
|
|
363
|
+
opts.onActivity?.(a);
|
|
364
|
+
await sleep(per / 2 / Math.max(1, st.activity?.length ?? 1), opts.signal);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (cancelled())
|
|
368
|
+
return { ok: false, reason: 'cancelled' };
|
|
369
|
+
}
|
|
370
|
+
await sleep(per, opts.signal);
|
|
371
|
+
if (cancelled())
|
|
372
|
+
return { ok: false, reason: 'cancelled' };
|
|
373
|
+
return { ok: true, text: simText(agent, stage, loop, turn, final, goal), tokens: 400 + hashOf(agent.id + prompt.length) % 900 };
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function simPlan(agent, stage, loop, turn) {
|
|
377
|
+
if (stage === 'ba-discussion')
|
|
378
|
+
return { steps: [
|
|
379
|
+
{ label: 'Reading the goal', activity: ['reading README.md', 'reading docs/PROJECT.md'] },
|
|
380
|
+
{ label: 'Drafting acceptance criteria', activity: ['thinking: who is the user and what is the smallest useful scope?', 'thinking: listing testable acceptance criteria'] },
|
|
381
|
+
{ label: 'Replying to partner', activity: ['comparing with the partner proposal'] }
|
|
382
|
+
] };
|
|
383
|
+
if (stage === 'ba-review')
|
|
384
|
+
return { steps: [
|
|
385
|
+
{ label: 'Reading the handoff', activity: ['reading handoff-ba.md'] },
|
|
386
|
+
{ label: 'Checking acceptance criteria', activity: ['$ git diff --stat', 'thinking: every criterion has evidence'] },
|
|
387
|
+
{ label: 'Writing the review', activity: ['drafting review notes'] }
|
|
388
|
+
] };
|
|
389
|
+
if (agent.team === 'implement')
|
|
390
|
+
return { steps: [
|
|
391
|
+
{ label: 'Planning', activity: ['reading src/ layout', loop > 1 ? 'reading qc-report: fixing the finding' : 'thinking: splitting the work into three parts'] },
|
|
392
|
+
{ label: 'Editing files', children: [
|
|
393
|
+
{ kind: 'ui-builder', task: 'settings toggle component', lines: ['reading src/components/Settings.tsx', 'edited src/components/ThemeToggle.tsx', 'thinking: keyboard focus and aria-pressed', 'edited src/components/Settings.tsx'], summary: 'ThemeToggle component added and wired into Settings' },
|
|
394
|
+
{ kind: 'state-wiring', task: 'persist preference in localStorage', lines: ['reading src/state/preferences.ts', 'edited src/state/theme.ts', 'thinking: fall back to system theme when storage is empty', 'edited src/state/preferences.ts'], summary: 'Preference persisted and restored on load' },
|
|
395
|
+
{ kind: 'test-writer', task: 'unit tests for theme toggle', lines: ['reading test/ conventions', 'edited test/theme-toggle.test.ts', loop > 1 ? 'edited test/theme-empty-input.test.ts' : 'thinking: happy path and stored-value cases', '$ npm test -- theme'], summary: 'Unit tests written and passing' }
|
|
396
|
+
] },
|
|
397
|
+
{ label: 'Running checks', activity: ['$ npm run build', '$ npm test'] },
|
|
398
|
+
{ label: 'Reporting', activity: ['thinking: summarising changes and how to verify'] }
|
|
399
|
+
] };
|
|
400
|
+
const second = turn > 1;
|
|
401
|
+
return { steps: [
|
|
402
|
+
{ label: 'Reviewing diff', activity: ['reading handoff-ba.md', '$ git diff'] },
|
|
403
|
+
{ label: 'Running tests', children: [
|
|
404
|
+
{ kind: 'test-runner', task: 'run the full test suite', lines: ['$ npm run build', '$ npm test', loop === 1 ? 'thinking: empty input case has no test' : 'thinking: regression test for empty input passes'], summary: loop === 1 ? 'suite green but a gap in empty-input coverage' : 'suite green including the regression test' },
|
|
405
|
+
...(second ? [] : [{ kind: 'a11y-checker', task: 'check keyboard and aria behaviour', lines: ['reading src/components/ThemeToggle.tsx', 'thinking: focus order and aria-pressed', 'thinking: contrast of both themes'], summary: 'no accessibility issues found' }])
|
|
406
|
+
] },
|
|
407
|
+
{ label: 'Discussing with the other reviewer', activity: [loop === 1 ? 'thinking: empty input is not handled' : 'thinking: edge cases now covered'] },
|
|
408
|
+
{ label: 'Writing verdict', activity: ['drafting verdict'] }
|
|
409
|
+
] };
|
|
410
|
+
}
|
|
411
|
+
function simText(agent, stage, loop, turn, final, goal) {
|
|
412
|
+
if (stage === 'ba-discussion') {
|
|
413
|
+
if (final)
|
|
414
|
+
return `# HANDOFF\n\n## Goal\n${goal}\n\n## Scope\n- Implement the smallest end-to-end slice of the request.\n- Handle empty and invalid input explicitly.\n\n## Acceptance criteria\n- [ ] The requested behaviour works for the happy path\n- [ ] Empty/invalid input returns a clear error\n- [ ] Tests cover both cases and \`npm test\` passes\n\n## Out of scope\n- UI polish, performance tuning, new dependencies\n\n## Risks\n- Ambiguous wording in the request; assumptions are listed above.`;
|
|
415
|
+
const lines = [
|
|
416
|
+
`Okay, I read "${goal}" twice. My take: ship the smallest slice first. Quick question though: what should happen when the input is bad or empty?`,
|
|
417
|
+
`Hmm, I would not cut that corner. Failing loudly is safer than a silent no-op, and it is cheap. Also, can we make every criterion testable? "Works well" is not a criterion.`,
|
|
418
|
+
`Fair point, I was being too loose. Let's fail loudly on invalid input and write three checkboxes anyone can verify. Anything you want explicitly out of scope?`,
|
|
419
|
+
`Yes: no UI polish, no new dependencies, no performance work. Agreed on the rest. I'll write it all up in the handoff now.`
|
|
420
|
+
];
|
|
421
|
+
return lines[Math.min(turn - 1, lines.length - 1)];
|
|
422
|
+
}
|
|
423
|
+
if (stage === 'implement')
|
|
424
|
+
return `Implemented "${goal}".\n\nChanged: src/feature.ts (new behaviour), test/feature.test.ts (happy path${loop > 1 ? ', empty input regression' : ''}).${loop > 1 ? '\nAddressed the QC finding: empty input is now validated and rejected with a clear error.' : ''}\nVerify: npm test (all green locally).`;
|
|
425
|
+
if (stage === 'qc') {
|
|
426
|
+
if (loop === 1)
|
|
427
|
+
return turn === 1 ? `Reviewed the diff and ran the tests: happy path passes, but empty input is not handled (src/feature.ts accepts '' and returns undefined). Acceptance criterion 2 is not met.\nVERDICT: FAIL`
|
|
428
|
+
: `Confirmed the first reviewer's finding: calling the feature with an empty string silently succeeds. No test covers it. Everything else looks fine.\nVERDICT: FAIL`;
|
|
429
|
+
return turn === 1 ? `Re-ran the tests and re-read the diff: empty input now throws a clear error and has a regression test. All acceptance criteria are met.\nVERDICT: PASS`
|
|
430
|
+
: `I agree: the earlier finding is fixed and covered by a test; no new issues found.\nVERDICT: PASS`;
|
|
431
|
+
}
|
|
432
|
+
if (stage === 'ba-review')
|
|
433
|
+
return `Checked the deliverable against the handoff: happy path, input validation and tests are all present. Acceptance criteria met; out-of-scope items untouched. Approved for delivery.`;
|
|
434
|
+
return `${agent.name}: done.`;
|
|
435
|
+
}
|
|
436
|
+
//# sourceMappingURL=runners.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
2
|
+
export declare const SECRET_NAME_RE: RegExp;
|
|
3
|
+
export declare const teamSecretsPath: (env?: Env) => string;
|
|
4
|
+
export declare const listSecretNames: (env?: Env) => string[];
|
|
5
|
+
export declare const hasSecret: (name: string, env?: Env) => boolean;
|
|
6
|
+
export declare function setSecret(name: string, value: string, env?: Env): void;
|
|
7
|
+
export declare function deleteSecret(name: string, env?: Env): boolean;
|
|
8
|
+
/** Engine-internal. undefined when absent or unreadable. */
|
|
9
|
+
export declare function readSecret(name: string | undefined, env?: Env): string | undefined;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Per-user team secret store: <userConfigDir>/team-secrets.json (dir 0700, file 0600, atomic write). Values are engine-internal; never log or emit them.
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { userConfigDir } from '../settings/env-config.js';
|
|
6
|
+
export const SECRET_NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
7
|
+
export const teamSecretsPath = (env = process.env) => join(userConfigDir(env), 'team-secrets.json');
|
|
8
|
+
function load(env) {
|
|
9
|
+
let raw;
|
|
10
|
+
try {
|
|
11
|
+
raw = readFileSync(teamSecretsPath(env), 'utf8');
|
|
12
|
+
}
|
|
13
|
+
catch (e) {
|
|
14
|
+
if (e.code === 'ENOENT')
|
|
15
|
+
return {};
|
|
16
|
+
throw e;
|
|
17
|
+
}
|
|
18
|
+
const j = JSON.parse(raw);
|
|
19
|
+
if (j === null || typeof j !== 'object' || Array.isArray(j))
|
|
20
|
+
throw new Error('team-secrets.json is malformed');
|
|
21
|
+
return Object.fromEntries(Object.entries(j).filter((e) => typeof e[1] === 'string'));
|
|
22
|
+
}
|
|
23
|
+
function save(env, data) {
|
|
24
|
+
const path = teamSecretsPath(env), dir = userConfigDir(env);
|
|
25
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
26
|
+
try {
|
|
27
|
+
chmodSync(dir, 0o700);
|
|
28
|
+
}
|
|
29
|
+
catch { /* not ours to chmod */ }
|
|
30
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
31
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
32
|
+
renameSync(tmp, path);
|
|
33
|
+
}
|
|
34
|
+
const check = (name) => { if (!SECRET_NAME_RE.test(name))
|
|
35
|
+
throw new Error(`secret name must match ${SECRET_NAME_RE}`); };
|
|
36
|
+
export const listSecretNames = (env = process.env) => { try {
|
|
37
|
+
return Object.keys(load(env)).sort();
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
} };
|
|
42
|
+
export const hasSecret = (name, env = process.env) => readSecret(name, env) !== undefined;
|
|
43
|
+
export function setSecret(name, value, env = process.env) {
|
|
44
|
+
check(name);
|
|
45
|
+
if (!value)
|
|
46
|
+
throw new Error('secret value must not be empty');
|
|
47
|
+
save(env, { ...load(env), [name]: value });
|
|
48
|
+
}
|
|
49
|
+
export function deleteSecret(name, env = process.env) {
|
|
50
|
+
const data = load(env);
|
|
51
|
+
if (!(name in data))
|
|
52
|
+
return false;
|
|
53
|
+
delete data[name];
|
|
54
|
+
save(env, data);
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
/** Engine-internal. undefined when absent or unreadable. */
|
|
58
|
+
export function readSecret(name, env = process.env) {
|
|
59
|
+
if (!name || !SECRET_NAME_RE.test(name))
|
|
60
|
+
return undefined;
|
|
61
|
+
try {
|
|
62
|
+
return load(env)[name];
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=secrets.js.map
|