@ngockhoale/ckit 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +70 -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 +384 -0
- package/dist/src/cli/demo.d.ts +1 -0
- package/dist/src/cli/demo.js +30 -0
- package/dist/src/cli/lifecycle.d.ts +19 -0
- package/dist/src/cli/lifecycle.js +90 -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 +113 -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 +157 -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 +677 -0
- package/gui/index.html +51 -0
- package/gui/network.js +413 -0
- package/package.json +44 -4
- package/src/storage/schema.sql +42 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// OpenAI-compatible Chat Completions advisor (ADR-017). Non-streaming, one HTTP request per send, never retries.
|
|
2
|
+
import { redactSecretText } from '../../security/redact.js';
|
|
3
|
+
const defaultFetch = (url, init) => fetch(url, init);
|
|
4
|
+
const NOTE_MAX = 200;
|
|
5
|
+
/** Error codes that prove the request was never written to a server (DNS, refused connect, TLS verification before the request). */
|
|
6
|
+
const NEVER_SENT_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'CERT_HAS_EXPIRED', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'ERR_TLS_CERT_ALTNAME_INVALID', 'CERT_NOT_YET_VALID', 'CERT_UNTRUSTED']);
|
|
7
|
+
function codesOf(error, depth = 0) {
|
|
8
|
+
if (typeof error !== 'object' || error === null || depth > 3)
|
|
9
|
+
return [];
|
|
10
|
+
const e = error;
|
|
11
|
+
const own = typeof e.code === 'string' ? [e.code] : [];
|
|
12
|
+
const nested = Array.isArray(e.errors) ? e.errors.flatMap(x => codesOf(x, depth + 1)) : [];
|
|
13
|
+
return [...own, ...codesOf(e.cause, depth + 1), ...nested];
|
|
14
|
+
}
|
|
15
|
+
/** never-sent only when a cause code proves it and no code says otherwise; no code, or any other code, is unknown. */
|
|
16
|
+
export function isNeverSent(error) {
|
|
17
|
+
const codes = codesOf(error?.cause ?? error);
|
|
18
|
+
return codes.length > 0 && codes.every(c => NEVER_SENT_CODES.has(c));
|
|
19
|
+
}
|
|
20
|
+
export class OpenAiCompatibleAdvisor {
|
|
21
|
+
config;
|
|
22
|
+
store;
|
|
23
|
+
fetchImpl;
|
|
24
|
+
name = 'openai-compatible';
|
|
25
|
+
isSimulated = false;
|
|
26
|
+
/** Number of HTTP requests this instance has issued (for tests and audit). */
|
|
27
|
+
requests = 0;
|
|
28
|
+
prompts = new Map();
|
|
29
|
+
constructor(config, store, fetchImpl = defaultFetch) {
|
|
30
|
+
this.config = config;
|
|
31
|
+
this.store = store;
|
|
32
|
+
this.fetchImpl = fetchImpl;
|
|
33
|
+
}
|
|
34
|
+
createAdvisorThread(role, id, model, system) {
|
|
35
|
+
return { id, role, model, messages: system === undefined ? [] : [{ role: 'system', content: system }] };
|
|
36
|
+
}
|
|
37
|
+
/** Registers the prompt text a later dispatch({promptRef}) will send on `thread`. */
|
|
38
|
+
registerPrompt(promptRef, thread, text) { this.prompts.set(promptRef, { thread, text }); }
|
|
39
|
+
async *dispatch(req) {
|
|
40
|
+
const entry = this.prompts.get(req.promptRef);
|
|
41
|
+
if (!entry) {
|
|
42
|
+
yield { kind: 'unknown', reason: 'adapter-fault', note: 'prompt not registered' };
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
yield* this.sendTurn(entry.thread, entry.text);
|
|
46
|
+
}
|
|
47
|
+
redact(text) { return redactSecretText(text, this.config.apiKey ? [this.config.apiKey] : []); }
|
|
48
|
+
note(body) { return this.redact(body).replace(/\s+/g, ' ').slice(0, NOTE_MAX); }
|
|
49
|
+
/** Sends exactly one request. The user text is appended to the thread only when sent; the reply only when valid. */
|
|
50
|
+
async *sendTurn(thread, userText, opts = {}) {
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
let timedOut = false;
|
|
53
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, this.config.timeoutMs);
|
|
54
|
+
const onAbort = () => controller.abort();
|
|
55
|
+
if (opts.signal?.aborted)
|
|
56
|
+
controller.abort();
|
|
57
|
+
else
|
|
58
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
59
|
+
const cleanup = () => { clearTimeout(timer); opts.signal?.removeEventListener('abort', onAbort); };
|
|
60
|
+
try {
|
|
61
|
+
const messages = [...thread.messages, { role: 'user', content: userText }];
|
|
62
|
+
const body = { model: thread.model, messages, stream: false };
|
|
63
|
+
if (this.config.maxTokens !== null)
|
|
64
|
+
body['max_tokens'] = this.config.maxTokens;
|
|
65
|
+
const headers = { 'content-type': 'application/json' };
|
|
66
|
+
if (this.config.auth === 'bearer')
|
|
67
|
+
headers['authorization'] = `Bearer ${this.config.apiKey}`;
|
|
68
|
+
let res;
|
|
69
|
+
let raw;
|
|
70
|
+
this.requests++;
|
|
71
|
+
try {
|
|
72
|
+
res = await this.fetchImpl(`${this.config.baseUrl}/chat/completions`, { method: 'POST', headers, body: JSON.stringify(body), signal: controller.signal });
|
|
73
|
+
if (res.status >= 200 && res.status < 300)
|
|
74
|
+
yield { kind: 'ack' };
|
|
75
|
+
raw = await res.text();
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (timedOut) {
|
|
79
|
+
yield { kind: 'unknown', reason: 'timeout', note: `no response within ${this.config.timeoutMs}ms` };
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (controller.signal.aborted) {
|
|
83
|
+
yield { kind: 'unknown', reason: 'adapter-fault', note: 'cancelled' };
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (isNeverSent(error)) {
|
|
87
|
+
yield { kind: 'rejected', reason: 'connect', delivery: 'never-sent', status: null, note: `connection failed before the request was sent: ${this.note(error instanceof Error ? error.message : 'error')}` };
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
yield { kind: 'unknown', reason: 'adapter-fault', note: 'transport failure; delivery unknown' };
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const status = res.status;
|
|
94
|
+
if (status < 200 || status >= 300) {
|
|
95
|
+
if (status >= 500) {
|
|
96
|
+
yield { kind: 'unknown', reason: 'adapter-fault', note: `http ${status}: ${this.note(raw)}` };
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const [reason, hint] = status === 401 || status === 403 ? ['auth', 'check CKIT_OPENAI_API_KEY / CKIT_OPENAI_AUTH']
|
|
100
|
+
: status === 404 ? ['not-found', 'check CKIT_OPENAI_BASE_URL and CKIT_OPENAI_MODEL']
|
|
101
|
+
: status === 429 ? ['rate-limited', 'endpoint is rate limiting; nothing was resent']
|
|
102
|
+
: ['client-error', 'request was rejected by the endpoint'];
|
|
103
|
+
yield { kind: 'rejected', reason, delivery: 'refused', status, note: `http ${status}: ${hint}: ${this.note(raw)}` };
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
let content;
|
|
107
|
+
try {
|
|
108
|
+
content = JSON.parse(raw).choices?.[0]?.message?.content;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
yield { kind: 'unknown', reason: 'adapter-fault', note: 'malformed JSON response' };
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (typeof content !== 'string' || content.trim() === '') {
|
|
115
|
+
yield { kind: 'unknown', reason: 'adapter-fault', note: 'response has no choices[0].message.content' };
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
thread.messages.push({ role: 'user', content: userText }, { role: 'assistant', content });
|
|
119
|
+
const resultRef = await this.store.saveReply(thread, this.redact(content));
|
|
120
|
+
yield { kind: 'completed', resultRef };
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
cleanup();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** Single GET {base}/models. Returns a status class only. Used only by `ckit doctor --check-connection`. */
|
|
128
|
+
export async function checkConnection(config, fetchImpl = defaultFetch) {
|
|
129
|
+
const controller = new AbortController();
|
|
130
|
+
const timer = setTimeout(() => controller.abort(), 10_000);
|
|
131
|
+
try {
|
|
132
|
+
const headers = {};
|
|
133
|
+
if (config.auth === 'bearer')
|
|
134
|
+
headers['authorization'] = `Bearer ${config.apiKey}`;
|
|
135
|
+
const res = await fetchImpl(`${config.baseUrl}/models`, { method: 'GET', headers, signal: controller.signal });
|
|
136
|
+
const s = res.status;
|
|
137
|
+
return { http: s, status: s >= 200 && s < 300 ? 'ok' : s === 401 || s === 403 ? 'auth' : s === 404 ? 'not-found' : s >= 500 ? 'server-error' : 'client-error' };
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return { http: null, status: controller.signal.aborted ? 'timeout' : 'unreachable' };
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
//# sourceMappingURL=openai-advisor.js.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import type { MissionViewOptions } from '../tui/mission-model.js';
|
|
3
|
+
/** Mission options for `ckit tui`: one read-only Plan snapshot, REPLAY mode (no side effects); the Actions panel is bound to nothing, so every control is disabled with a reason. */
|
|
4
|
+
export declare function buildTuiMissionOptions(cwd: string, width?: number): Promise<MissionViewOptions>;
|
|
5
|
+
export declare function main(args?: string[]): Promise<number>;
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { open, mkdir, readFile, realpath, writeFile, rename } from 'node:fs/promises';
|
|
4
|
+
import { resolve, join } from 'node:path';
|
|
5
|
+
import React from 'react';
|
|
6
|
+
import { render } from 'ink';
|
|
7
|
+
import { FakeAdvisor } from '../adapters/fake/fake-advisor.js';
|
|
8
|
+
import { projectEvents } from '../core/replay.js';
|
|
9
|
+
import { recordEvent } from '../core/record.js';
|
|
10
|
+
import { sessionId, taskId, projectId } from '../core/ids.js';
|
|
11
|
+
import { validateEnvelope } from '../core/events.js';
|
|
12
|
+
import { runTask } from '../core/run-task.js';
|
|
13
|
+
import { App } from '../tui/app.js';
|
|
14
|
+
import { LiveApp } from '../tui/live.js';
|
|
15
|
+
import { SetupModel } from '../tui/setup-model.js';
|
|
16
|
+
import { readMissionPlan } from '../tui/mission-plan.js';
|
|
17
|
+
import { outcomeLines, summarizeSessionOutcome } from '../tui/session-outcome.js';
|
|
18
|
+
import { provenanceLabel } from '../tui/provenance-label.js';
|
|
19
|
+
import { MissionPlanPanel } from '../tui/mission-plan-screens.js';
|
|
20
|
+
import { MissionActionPanel } from '../tui/mission-action-screens.js';
|
|
21
|
+
import { openDatabase } from '../storage/db.js';
|
|
22
|
+
import { CheckpointStore } from '../host/checkpoint.js';
|
|
23
|
+
import { SessionSupervisor } from '../host/supervisor.js';
|
|
24
|
+
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
|
25
|
+
import { fileURLToPath } from 'node:url';
|
|
26
|
+
import { withJournalLock } from '../diagnostics/journal-lock.js';
|
|
27
|
+
import { buildDiagnosticBundle, describeConnection, formatDoctorReport, projectKey, runDoctor } from '../diagnostics/doctor.js';
|
|
28
|
+
import { hasAnyAdvisorConfig, loadCkitConfig, maskedConfigSummary, resolveProjectRoot } from '../settings/env-config.js';
|
|
29
|
+
import { checkConnection } from '../adapters/openai/openai-advisor.js';
|
|
30
|
+
import { describeWorkerEnv, describeWorkerPermission, executorEnvironmentReport, resolveExecutable, selectExecutor } from '../adapters/launch/executor.js';
|
|
31
|
+
import { runSetup } from './setup.js';
|
|
32
|
+
import { runInstallCommand, runUpdateCommand } from './lifecycle.js';
|
|
33
|
+
import { runGuiCommand } from '../gui/server.js';
|
|
34
|
+
import { loadTeamConfig, writeDefaultTeamConfig } from '../team/config.js';
|
|
35
|
+
import { startTeamRun } from '../team/engine.js';
|
|
36
|
+
import { TeamApp } from '../tui/team/app.js';
|
|
37
|
+
import { runBackup, runRestore, showOpen, showReplay, showSessions } from './sessions.js';
|
|
38
|
+
import { artifactRef } from '../core/ids.js';
|
|
39
|
+
import { containsSecretText, credentialKeyPattern, redactSecretText } from '../security/redact.js';
|
|
40
|
+
function makeTuiSetupModel(events, cwd) {
|
|
41
|
+
const active = [...projectEvents(events).values()].find(state => state.phase !== 'closed');
|
|
42
|
+
if (!active?.task)
|
|
43
|
+
return undefined;
|
|
44
|
+
const db = openDatabase(join(cwd, STATE_DIR, 'state.sqlite'));
|
|
45
|
+
db.migrate();
|
|
46
|
+
const model = new SetupModel({ cwd, ownerId: 'tui-owner', taskId: active.task.id, goal: active.task.title, sessionId: active.sessionId, checkpointStore: new CheckpointStore(db), sessionSupervisor: new SessionSupervisor({ db, cwd, ownerId: 'tui-owner', sessionId: active.sessionId, leaseTtlMs: 30000 }) });
|
|
47
|
+
return { model, close: () => db.close() };
|
|
48
|
+
}
|
|
49
|
+
const STATE_DIR = '.ckit';
|
|
50
|
+
const PROJECT_FILE = 'project.json';
|
|
51
|
+
const EVENTS_FILE = 'events.json';
|
|
52
|
+
const SESSIONS_FILE = 'sessions.json';
|
|
53
|
+
function safeCwd(value) { return containsSecretText(value) ? '[REDACTED PATH]' : value; }
|
|
54
|
+
function randomId(prefix) { return `${prefix}-${randomBytes(6).toString('hex')}`; }
|
|
55
|
+
function safeText(value) {
|
|
56
|
+
if (!value.trim())
|
|
57
|
+
throw new TypeError('goal must not be empty');
|
|
58
|
+
if (containsSecretText(value))
|
|
59
|
+
throw new TypeError('goal appears to contain secret material; refusing to persist it');
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
async function canonicalProject(cwd = process.cwd()) {
|
|
63
|
+
const canonicalCwd = await realpath(resolve(cwd));
|
|
64
|
+
const binding = { version: 1, canonicalCwd, projectId: projectKey(canonicalCwd) };
|
|
65
|
+
const stateDir = join(canonicalCwd, STATE_DIR);
|
|
66
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
67
|
+
const path = join(stateDir, PROJECT_FILE);
|
|
68
|
+
try {
|
|
69
|
+
const existing = JSON.parse(await readFile(path, 'utf8'));
|
|
70
|
+
if (existing.version !== 1 || existing.canonicalCwd !== canonicalCwd || existing.projectId !== binding.projectId)
|
|
71
|
+
throw new TypeError('project binding does not match canonical cwd');
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error.code !== 'ENOENT')
|
|
75
|
+
throw error;
|
|
76
|
+
await writeFile(path, `${JSON.stringify(binding)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
77
|
+
}
|
|
78
|
+
return { binding, stateDir };
|
|
79
|
+
}
|
|
80
|
+
async function readEvents(path) {
|
|
81
|
+
let raw;
|
|
82
|
+
try {
|
|
83
|
+
raw = await readFile(path, 'utf8');
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (error.code === 'ENOENT')
|
|
87
|
+
return [];
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
const parsed = JSON.parse(raw);
|
|
91
|
+
if (!Array.isArray(parsed))
|
|
92
|
+
throw new TypeError('event journal must be an array');
|
|
93
|
+
return parsed.map(validateEnvelope);
|
|
94
|
+
}
|
|
95
|
+
async function writeEvents(stateDir, events) {
|
|
96
|
+
const path = join(stateDir, EVENTS_FILE), temp = join(stateDir, `events-${randomBytes(6).toString('hex')}.tmp`);
|
|
97
|
+
const file = await open(temp, 'wx', 0o600);
|
|
98
|
+
try {
|
|
99
|
+
await file.writeFile(`${JSON.stringify(events)}\n`, 'utf8');
|
|
100
|
+
await file.sync();
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
await file.close();
|
|
104
|
+
}
|
|
105
|
+
await rename(temp, path);
|
|
106
|
+
}
|
|
107
|
+
async function readSessions(path) {
|
|
108
|
+
try {
|
|
109
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
110
|
+
if (!Array.isArray(parsed))
|
|
111
|
+
throw new TypeError('session index must be an array');
|
|
112
|
+
return parsed.map(value => {
|
|
113
|
+
if (!value || typeof value !== 'object')
|
|
114
|
+
throw new TypeError('invalid session metadata');
|
|
115
|
+
const session = value;
|
|
116
|
+
if (session.version !== 1 || typeof session.sessionId !== 'string' || typeof session.taskId !== 'string' || typeof session.goal !== 'string' || typeof session.createdAt !== 'string')
|
|
117
|
+
throw new TypeError('invalid session metadata');
|
|
118
|
+
return { ...session, sessionId: sessionId(session.sessionId), taskId: taskId(session.taskId) };
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (error.code === 'ENOENT')
|
|
123
|
+
return [];
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function createTask(goalArg) {
|
|
128
|
+
const goal = safeText(goalArg);
|
|
129
|
+
const { binding, stateDir } = await canonicalProject(resolveProjectRoot(process.cwd()));
|
|
130
|
+
await withJournalLock(stateDir, async () => {
|
|
131
|
+
const path = join(stateDir, EVENTS_FILE), previous = await readEvents(path);
|
|
132
|
+
const sid = sessionId(randomId('session')), tid = taskId(randomId('task'));
|
|
133
|
+
const context = { sessionId: sid, taskId: tid, projectId: projectId(binding.projectId), source: 'simulated', at: () => new Date().toISOString() };
|
|
134
|
+
const env = recordEvent(context, { actor: { role: 'owner' }, payload: { type: 'TaskCreated', title: goal } });
|
|
135
|
+
await writeEvents(stateDir, [...previous, env]);
|
|
136
|
+
const sessionPath = join(stateDir, SESSIONS_FILE), sessions = await readSessions(sessionPath);
|
|
137
|
+
const next = { version: 1, sessionId: sid, taskId: tid, goal, createdAt: env.at };
|
|
138
|
+
const temp = `${sessionPath}.${randomBytes(6).toString('hex')}.tmp`;
|
|
139
|
+
await writeFile(temp, `${JSON.stringify([...sessions, next])}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
140
|
+
await rename(temp, sessionPath);
|
|
141
|
+
console.log(`[SIMULATED] Created owner task ${tid} in ${safeCwd(binding.canonicalCwd)}: ${redactSecretText(goal)}`);
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
async function getProjectEvents() {
|
|
145
|
+
const { binding, stateDir } = await canonicalProject(resolveProjectRoot(process.cwd()));
|
|
146
|
+
const events = await readEvents(join(stateDir, EVENTS_FILE));
|
|
147
|
+
for (const event of events)
|
|
148
|
+
if (event.projectId !== binding.projectId)
|
|
149
|
+
throw new TypeError('event journal contains an event for another project');
|
|
150
|
+
projectEvents(events);
|
|
151
|
+
return { binding, events };
|
|
152
|
+
}
|
|
153
|
+
async function showStatus() {
|
|
154
|
+
const { binding, events } = await getProjectEvents();
|
|
155
|
+
const grouped = projectEvents(events);
|
|
156
|
+
console.log(`Project: ${safeCwd(binding.canonicalCwd)}`);
|
|
157
|
+
if (grouped.size === 0) {
|
|
158
|
+
console.log('No recorded sessions.');
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
for (const state of grouped.values()) {
|
|
162
|
+
const first = events.find(event => event.sessionId === state.sessionId);
|
|
163
|
+
const marker = first === undefined ? 'SIMULATED' : provenanceLabel(first.provenance);
|
|
164
|
+
console.log(`[${marker}] ${state.sessionId} ${state.phase}${state.task ? ` — ${redactSecretText(state.task.title)}` : ''}`);
|
|
165
|
+
const summary = state.phase === 'closed' ? summarizeSessionOutcome(events.filter(event => event.sessionId === state.sessionId)) : null;
|
|
166
|
+
if (summary !== null)
|
|
167
|
+
for (const line of outcomeLines(summary))
|
|
168
|
+
console.log(` ${line}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const DOCTOR_USAGE = 'usage: ckit doctor [--bundle] [--agent=<absolute path>] [--check-connection]';
|
|
172
|
+
/** Offline advisor-config state for doctor: reads the dotenv file only, never the network. */
|
|
173
|
+
function advisorDoctorState(root) {
|
|
174
|
+
if (!hasAnyAdvisorConfig(root))
|
|
175
|
+
return { state: 'unconfigured' };
|
|
176
|
+
const loaded = loadCkitConfig({ projectRoot: root });
|
|
177
|
+
return loaded.ok ? { state: 'ok', summary: maskedConfigSummary(loaded.config), versionHint: !/\/v\d+(\/|$)/i.test(new URL(loaded.config.baseUrl).pathname) } : { state: 'invalid', variables: [...new Set(loaded.issues.map(issue => issue.variable))], problems: loaded.issues.map(issue => ({ variable: issue.variable, problem: issue.problem })) };
|
|
178
|
+
}
|
|
179
|
+
/** Executor as the team/advisor config resolves it (same selectExecutor/resolveExecutable); undefined when the advisor config is absent or invalid. */
|
|
180
|
+
function executorDoctorState(root) {
|
|
181
|
+
if (!hasAnyAdvisorConfig(root))
|
|
182
|
+
return undefined;
|
|
183
|
+
const loaded = loadCkitConfig({ projectRoot: root });
|
|
184
|
+
if (!loaded.ok)
|
|
185
|
+
return undefined;
|
|
186
|
+
const spec = selectExecutor(loaded.config);
|
|
187
|
+
try {
|
|
188
|
+
return { state: 'resolved', kind: spec.kind, path: resolveExecutable(spec, loaded.config) };
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
return { state: 'unresolved', kind: spec.kind, problem: error instanceof Error ? error.message : 'unresolvable' };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
async function showDoctor(flags) {
|
|
195
|
+
let bundle = false, agent, wantConnection = false;
|
|
196
|
+
for (const flag of flags) {
|
|
197
|
+
if (flag === '--bundle' && !bundle)
|
|
198
|
+
bundle = true;
|
|
199
|
+
else if (flag === '--check-connection' && !wantConnection)
|
|
200
|
+
wantConnection = true;
|
|
201
|
+
else if (flag.startsWith('--agent=') && agent === undefined && flag.length > 8)
|
|
202
|
+
agent = flag.slice(8);
|
|
203
|
+
else
|
|
204
|
+
throw new TypeError(DOCTOR_USAGE);
|
|
205
|
+
}
|
|
206
|
+
const cwd = process.cwd();
|
|
207
|
+
const root = resolveProjectRoot(cwd);
|
|
208
|
+
const configuredExecutor = executorDoctorState(root);
|
|
209
|
+
const report = await runDoctor({ cwd, advisor: advisorDoctorState(root), ...(wantConnection ? { connectionCheck: true } : {}), ...(configuredExecutor ? { configuredExecutor } : {}), ...(agent !== undefined ? { executable: { path: agent } } : {}) });
|
|
210
|
+
let connectionFailed = false;
|
|
211
|
+
if (wantConnection) {
|
|
212
|
+
// The only network action in doctor: exactly one GET {base}/models, explicitly requested.
|
|
213
|
+
const loaded = loadCkitConfig({ projectRoot: root });
|
|
214
|
+
if (!loaded.ok) {
|
|
215
|
+
console.log('connection: not checked (advisor configuration is not valid)');
|
|
216
|
+
connectionFailed = true;
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
const result = await checkConnection(loaded.config);
|
|
220
|
+
console.log(`connection: ${describeConnection(result)}`);
|
|
221
|
+
connectionFailed = result.status !== 'ok' && result.status !== 'not-found';
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (bundle) {
|
|
225
|
+
const environment = Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== undefined && (['LANG', 'LC_ALL', 'TERM', 'SHELL', 'NODE_OPTIONS'].includes(entry[0]) || (entry[0] !== 'PATH' && credentialKeyPattern.test(entry[0])))));
|
|
226
|
+
console.log(JSON.stringify(buildDiagnosticBundle(report, { cwd, environment })));
|
|
227
|
+
}
|
|
228
|
+
else
|
|
229
|
+
console.log(formatDoctorReport(report));
|
|
230
|
+
if (!bundle) {
|
|
231
|
+
const loaded = loadCkitConfig({ projectRoot: root });
|
|
232
|
+
if (loaded.ok) {
|
|
233
|
+
const kind = selectExecutor(loaded.config).kind;
|
|
234
|
+
console.log(describeWorkerEnv(executorEnvironmentReport(process.env, loaded.config.apiKey, kind)));
|
|
235
|
+
console.log(describeWorkerPermission(kind, loaded.config.executorPermissionMode));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return report.overall === 'fail' || connectionFailed ? 1 : 0;
|
|
239
|
+
}
|
|
240
|
+
/** Mission options for `ckit tui`: one read-only Plan snapshot, REPLAY mode (no side effects); the Actions panel is bound to nothing, so every control is disabled with a reason. */
|
|
241
|
+
export async function buildTuiMissionOptions(cwd, width = Math.max(20, (process.stdout.columns ?? 80) - 4)) {
|
|
242
|
+
const plan = await readMissionPlan(cwd);
|
|
243
|
+
// Read-only and request-free: the dotenv file and artifact files are read locally; content is redacted again.
|
|
244
|
+
const loaded = loadCkitConfig({ projectRoot: resolveProjectRoot(cwd) });
|
|
245
|
+
const key = loaded.ok ? loaded.config.apiKey : '';
|
|
246
|
+
const resolveContent = (ref) => {
|
|
247
|
+
try {
|
|
248
|
+
return redactSecretText(readFileSync(join(cwd, STATE_DIR, 'artifacts', artifactRef(ref)), 'utf8'), key ? [key] : []);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return undefined;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
return { mode: 'REPLAY', resolveContent, ...(loaded.ok ? { configSummary: maskedConfigSummary(loaded.config) } : {}), panels: { plan: (selection, ctx) => React.createElement(MissionPlanPanel, { snapshot: plan, selection, width, view: ctx.view }), actions: (selection, ctx) => React.createElement(MissionActionPanel, { active: ctx.active, mode: ctx.mode, selection, bindings: {}, view: ctx.view }) } };
|
|
255
|
+
}
|
|
256
|
+
async function showTui() {
|
|
257
|
+
const { binding, events } = await getProjectEvents();
|
|
258
|
+
const cwd = realpathSync(resolveProjectRoot(process.cwd()));
|
|
259
|
+
if (cwd !== binding.canonicalCwd)
|
|
260
|
+
throw new Error('TUI cwd does not match project binding');
|
|
261
|
+
const setup = makeTuiSetupModel(events, cwd);
|
|
262
|
+
const base = { events, ...(setup ? { setupModel: setup.model } : {}) };
|
|
263
|
+
const mission = await buildTuiMissionOptions(cwd);
|
|
264
|
+
try {
|
|
265
|
+
// Ctrl-C quits through Ink's default exitOnCtrlC; `q` unmounts via onQuit.
|
|
266
|
+
// TTY: live follow — re-reads the journal (read-only) so a run in another terminal shows up as it happens.
|
|
267
|
+
if (process.stdin.isTTY) {
|
|
268
|
+
const load = async () => (await getProjectEvents()).events;
|
|
269
|
+
const instance = render(React.createElement(LiveApp, { initial: events, load, ...(setup ? { setupModel: setup.model } : {}), viewOptions: { viewKeys: true, mission, onQuit: () => instance.unmount() } }));
|
|
270
|
+
await instance.waitUntilExit();
|
|
271
|
+
}
|
|
272
|
+
else
|
|
273
|
+
render(React.createElement(App, base)).unmount();
|
|
274
|
+
}
|
|
275
|
+
finally {
|
|
276
|
+
setup?.close();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const TEAM_USAGE = 'usage: ckit team "<goal>" | ckit team --demo [--speed=<n>] | ckit team --init [--force]';
|
|
280
|
+
async function showTeam(args) {
|
|
281
|
+
const root = resolveProjectRoot(process.cwd());
|
|
282
|
+
if (args[0] === '--init') {
|
|
283
|
+
console.log(`wrote ${writeDefaultTeamConfig(root, args.includes('--force'))}`);
|
|
284
|
+
return 0;
|
|
285
|
+
}
|
|
286
|
+
const demo = args.includes('--demo');
|
|
287
|
+
const speedArg = args.find(a => a.startsWith('--speed='));
|
|
288
|
+
const simSpeed = speedArg ? Number(speedArg.slice('--speed='.length)) : 1;
|
|
289
|
+
const goals = args.filter(a => !a.startsWith('--'));
|
|
290
|
+
if ((!demo && goals.length !== 1) || goals.length > 1 || !(simSpeed > 0))
|
|
291
|
+
throw new TypeError(TEAM_USAGE);
|
|
292
|
+
const goal = goals[0] ?? 'Add a dark-mode toggle to the settings page';
|
|
293
|
+
const loaded = loadTeamConfig(root);
|
|
294
|
+
if (!loaded.ok) {
|
|
295
|
+
console.error(`team config invalid:\n${loaded.errors.join('\n')}`);
|
|
296
|
+
return 2;
|
|
297
|
+
}
|
|
298
|
+
const handle = startTeamRun({ projectRoot: root, goal, config: loaded.config, simulated: demo, simSpeed });
|
|
299
|
+
if (process.stdin.isTTY) {
|
|
300
|
+
const instance = render(React.createElement(TeamApp, { handle, goal, onQuit: () => instance.unmount() }));
|
|
301
|
+
await instance.waitUntilExit();
|
|
302
|
+
handle.stop();
|
|
303
|
+
}
|
|
304
|
+
const outcome = await handle.done;
|
|
305
|
+
console.log(`team run ${handle.runId}: ${outcome} (${handle.runDir})`);
|
|
306
|
+
return outcome === 'delivered' ? 0 : 1;
|
|
307
|
+
}
|
|
308
|
+
async function showDemo() {
|
|
309
|
+
const { state, events } = await runTask({ sessionId: randomId('session'), taskId: randomId('task'), title: 'Offline demo (SIMULATED)', promptRef: 'sim://prompt/ckit-demo', advisor: new FakeAdvisor() });
|
|
310
|
+
for (const event of events)
|
|
311
|
+
console.log(`[SIMULATED] ${JSON.stringify(event)}`);
|
|
312
|
+
console.log(`phase=${state.phase} outcome=${state.outcome ?? 'n/a'} events=${events.length}`);
|
|
313
|
+
return state.phase === 'closed' ? 0 : 1;
|
|
314
|
+
}
|
|
315
|
+
// dist/src/cli/ckit.js -> package root; package.json ships in every npm tarball.
|
|
316
|
+
async function packageVersion() {
|
|
317
|
+
const pkg = JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8'));
|
|
318
|
+
if (typeof pkg.version !== 'string')
|
|
319
|
+
throw new TypeError('package version unavailable');
|
|
320
|
+
return pkg.version;
|
|
321
|
+
}
|
|
322
|
+
export async function main(args = process.argv.slice(2)) {
|
|
323
|
+
try {
|
|
324
|
+
const [command, ...rest] = args;
|
|
325
|
+
switch (command) {
|
|
326
|
+
case 'new':
|
|
327
|
+
if (rest.length !== 1)
|
|
328
|
+
throw new TypeError('usage: ckit new <goal>');
|
|
329
|
+
await createTask(rest[0] ?? '');
|
|
330
|
+
return 0;
|
|
331
|
+
case 'status':
|
|
332
|
+
if (rest.length !== 0)
|
|
333
|
+
throw new TypeError('usage: ckit status');
|
|
334
|
+
await showStatus();
|
|
335
|
+
return 0;
|
|
336
|
+
case 'demo':
|
|
337
|
+
if (rest.length !== 0)
|
|
338
|
+
throw new TypeError('usage: ckit demo');
|
|
339
|
+
return await showDemo();
|
|
340
|
+
case 'tui':
|
|
341
|
+
if (rest.length !== 0)
|
|
342
|
+
throw new TypeError('usage: ckit tui');
|
|
343
|
+
await showTui();
|
|
344
|
+
return 0;
|
|
345
|
+
case 'setup': return await runSetup(rest);
|
|
346
|
+
case 'install': return await runInstallCommand(rest);
|
|
347
|
+
case 'update': return await runUpdateCommand(rest);
|
|
348
|
+
case 'gui': return await runGuiCommand(rest);
|
|
349
|
+
case 'team': return await showTeam(rest);
|
|
350
|
+
case 'doctor': return await showDoctor(rest);
|
|
351
|
+
case 'sessions': return await showSessions(rest);
|
|
352
|
+
case 'open': return await showOpen(rest);
|
|
353
|
+
case 'replay': return await showReplay(rest);
|
|
354
|
+
case 'backup': return await runBackup(rest);
|
|
355
|
+
case 'restore': return await runRestore(rest);
|
|
356
|
+
case '--version':
|
|
357
|
+
case 'version':
|
|
358
|
+
if (rest.length !== 0)
|
|
359
|
+
throw new TypeError('usage: ckit --version');
|
|
360
|
+
console.log(await packageVersion());
|
|
361
|
+
return 0;
|
|
362
|
+
// Bare `ckit` in a terminal opens the GUI first; first-run setup happens there (Settings view). Non-interactive callers still get the usage text.
|
|
363
|
+
case undefined: if (process.stdin.isTTY === true && process.stdout.isTTY === true)
|
|
364
|
+
return await runGuiCommand([]);
|
|
365
|
+
// falls through
|
|
366
|
+
default: throw new TypeError('usage: ckit (no command: opens the GUI) | ckit <install|update [--check]|new <goal>|status|demo|tui|gui [--port=<n>] [--no-open]|team "<goal>"|team --demo|team --init|setup [--path]|sessions|open <sessionId>|replay <sessionId>|backup <dest-dir>|restore <backup-dir> (each takes [--project=<path>])|doctor [--bundle] [--agent=<path>] [--check-connection]|--version>');
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
console.error(`ckit: ${error instanceof Error ? redactSecretText(error.message) : 'operation failed'}`);
|
|
371
|
+
return 1;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// Compare real paths: an installed `ckit` runs through a node_modules/.bin symlink.
|
|
375
|
+
const invokedPath = (path) => { try {
|
|
376
|
+
return realpathSync(path);
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
return resolve(path);
|
|
380
|
+
} };
|
|
381
|
+
if (process.argv[1] !== undefined && invokedPath(process.argv[1]) === invokedPath(fileURLToPath(import.meta.url))) {
|
|
382
|
+
main().then(code => { process.exitCode = code; }, () => { process.exitCode = 1; });
|
|
383
|
+
}
|
|
384
|
+
//# sourceMappingURL=ckit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// CKit minimal offline demo (T01-01/T01-05 groundwork): one task flow against the
|
|
2
|
+
// SIMULATED advisor adapter. No external send, no model call, no live integration claim.
|
|
3
|
+
// Prints the structured event stream — the same envelopes a future TUI will render (ADR-014).
|
|
4
|
+
import { runTask } from '../core/run-task.js';
|
|
5
|
+
import { FakeAdvisor } from '../adapters/fake/fake-advisor.js';
|
|
6
|
+
const banner = '=== CKit demo — SIMULATED adapter only; NOT live integration evidence ===';
|
|
7
|
+
async function main() {
|
|
8
|
+
const faultArg = process.argv.find((a) => a.startsWith('--fault='));
|
|
9
|
+
const fault = (faultArg?.split('=')[1] ?? 'none');
|
|
10
|
+
console.log(banner);
|
|
11
|
+
const { state, events } = await runTask({
|
|
12
|
+
sessionId: 'session-demo00001',
|
|
13
|
+
taskId: 'task-demo000001',
|
|
14
|
+
title: 'Demo: draft a changelog section (simulated advisor)',
|
|
15
|
+
promptRef: 'sim://prompt/demo-001',
|
|
16
|
+
advisor: new FakeAdvisor({ fault }),
|
|
17
|
+
});
|
|
18
|
+
for (const env of events) {
|
|
19
|
+
const marker = env.provenance.source === 'simulated' ? '[SIMULATED]' : `[LIVE ${env.provenance.ref}]`;
|
|
20
|
+
console.log(`${marker} ${JSON.stringify(env)}`);
|
|
21
|
+
}
|
|
22
|
+
console.log(`final phase=${state.phase} outcome=${state.outcome ?? 'n/a'} events=${events.length}`);
|
|
23
|
+
console.log(banner);
|
|
24
|
+
return state.phase === 'closed' ? 0 : 1;
|
|
25
|
+
}
|
|
26
|
+
main().then((code) => process.exit(code), (err) => {
|
|
27
|
+
console.error('demo failed:', err);
|
|
28
|
+
process.exit(1);
|
|
29
|
+
});
|
|
30
|
+
//# sourceMappingURL=demo.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const PACKAGE_NAME = "@ngockhoale/ckit";
|
|
2
|
+
export declare function installedVersion(): string;
|
|
3
|
+
export interface InstallResult {
|
|
4
|
+
readonly root: string;
|
|
5
|
+
readonly configFile: string;
|
|
6
|
+
readonly created: boolean;
|
|
7
|
+
readonly gitignoreUpdated: boolean;
|
|
8
|
+
}
|
|
9
|
+
/** Prepares `cwd` (exactly that folder, never a parent) for CKit: writes the default .ckit/team.json when missing; keeps an existing one untouched. */
|
|
10
|
+
export declare function installProject(cwd: string): InstallResult;
|
|
11
|
+
export declare function runInstallCommand(args: readonly string[]): Promise<number>;
|
|
12
|
+
/** Runs npm; returns exit status and captured stdout (stdout is '' when inherited). */
|
|
13
|
+
export type NpmRunner = (args: readonly string[], inherit: boolean) => {
|
|
14
|
+
status: number;
|
|
15
|
+
stdout: string;
|
|
16
|
+
};
|
|
17
|
+
/** true when version a is newer than b (numeric major.minor.patch; with equal numbers a release beats a pre-release). */
|
|
18
|
+
export declare function isNewer(a: string, b: string): boolean;
|
|
19
|
+
export declare function runUpdateCommand(args: readonly string[], npm?: NpmRunner, current?: string, log?: (line: string) => void): Promise<number>;
|