@ptkl/toolkit 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/forge.js +34 -6
- package/dist/lib/kortex/__tests__/fixtures/providers/conformance.test.js +120 -0
- package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +172 -0
- package/dist/lib/kortex/__tests__/legacy-compatibility.test.js +273 -0
- package/dist/lib/kortex/__tests__/phase-1-conversion.test.js +154 -0
- package/dist/lib/kortex/__tests__/phase-2-runtime.test.js +100 -0
- package/dist/lib/kortex/__tests__/phase-3-provider.test.js +48 -0
- package/dist/lib/kortex/config/loader.js +129 -0
- package/dist/lib/kortex/config/schema.js +60 -0
- package/dist/lib/kortex/controller.js +60 -0
- package/dist/lib/kortex/conversation/legacy-conversion.js +141 -0
- package/dist/lib/kortex/conversation/types.js +13 -0
- package/dist/lib/kortex/events/index.js +1 -0
- package/dist/lib/kortex/events/reducer.js +86 -0
- package/dist/lib/kortex/events/types.js +7 -0
- package/dist/lib/kortex/events/writer.js +76 -0
- package/dist/lib/kortex/mcp/index.js +1 -0
- package/dist/lib/kortex/orchestration/index.js +1 -0
- package/dist/lib/kortex/orchestration/manager-worker.js +88 -0
- package/dist/lib/kortex/orchestration/peer-collaboration.js +59 -0
- package/dist/lib/kortex/orchestration/plan.js +133 -0
- package/dist/lib/kortex/orchestration/scheduler.js +124 -0
- package/dist/lib/kortex/persistence/index.js +1 -0
- package/dist/lib/kortex/persistence/run-journal.js +94 -0
- package/dist/lib/kortex/providers/anthropic.js +34 -0
- package/dist/lib/kortex/providers/index.js +1 -0
- package/dist/lib/kortex/providers/openai-compatible.js +190 -0
- package/dist/lib/kortex/providers/protokol.js +204 -0
- package/dist/lib/kortex/providers/registry.js +61 -0
- package/dist/lib/kortex/providers/types.js +13 -0
- package/dist/lib/kortex/runtime/agent-runner.js +241 -0
- package/dist/lib/kortex/runtime/approval-queue.js +95 -0
- package/dist/lib/kortex/runtime/budget-controller.js +105 -0
- package/dist/lib/kortex/runtime/index.js +1 -0
- package/dist/lib/kortex/runtime/tool-runtime.js +66 -0
- package/dist/lib/kortex/runtime/workspace.js +52 -0
- package/dist/lib/kortex/tools/index.js +1 -0
- package/dist/lib/kortex/tools.js +226 -34
- package/dist/lib/kortex/types.js +7 -0
- package/dist/lib/kortex/ui/index.js +1 -0
- package/package.json +6 -4
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 1 tests: canonical conversation model, legacy conversion, event reducer.
|
|
3
|
+
*/
|
|
4
|
+
import { describe, it, expect } from 'vitest';
|
|
5
|
+
import { storedMessagesToTurns, turnsToStoredMessages } from '../conversation/legacy-conversion.js';
|
|
6
|
+
import { RunEventReducer } from '../events/reducer.js';
|
|
7
|
+
// ── Legacy conversion ──
|
|
8
|
+
describe('legacy conversation conversion', () => {
|
|
9
|
+
it('converts a simple user message', () => {
|
|
10
|
+
const msgs = [{ role: 'user', content: 'Hello' }];
|
|
11
|
+
const turns = storedMessagesToTurns(msgs);
|
|
12
|
+
expect(turns).toHaveLength(1);
|
|
13
|
+
expect(turns[0].role).toBe('user');
|
|
14
|
+
expect(turns[0].blocks).toHaveLength(1);
|
|
15
|
+
expect(turns[0].blocks[0]).toMatchObject({ type: 'text', text: 'Hello' });
|
|
16
|
+
});
|
|
17
|
+
it('converts an assistant message with tool calls', () => {
|
|
18
|
+
const msgs = [{
|
|
19
|
+
role: 'assistant',
|
|
20
|
+
content: 'Let me check that file.',
|
|
21
|
+
tool_calls: [{
|
|
22
|
+
id: 'call-1',
|
|
23
|
+
type: 'function',
|
|
24
|
+
function: { name: 'read_file', arguments: '{"path":"test.txt"}' },
|
|
25
|
+
}],
|
|
26
|
+
}];
|
|
27
|
+
const turns = storedMessagesToTurns(msgs);
|
|
28
|
+
expect(turns).toHaveLength(1);
|
|
29
|
+
expect(turns[0].blocks).toHaveLength(2); // text + tool_call
|
|
30
|
+
expect(turns[0].blocks[1]).toMatchObject({ type: 'tool_call', name: 'read_file' });
|
|
31
|
+
});
|
|
32
|
+
it('converts a tool result message', () => {
|
|
33
|
+
const msgs = [{
|
|
34
|
+
role: 'tool',
|
|
35
|
+
content: 'File contents: hello',
|
|
36
|
+
tool_call_id: 'call-1',
|
|
37
|
+
}];
|
|
38
|
+
const turns = storedMessagesToTurns(msgs);
|
|
39
|
+
expect(turns).toHaveLength(1);
|
|
40
|
+
expect(turns[0].role).toBe('tool');
|
|
41
|
+
expect(turns[0].blocks[0]).toMatchObject({
|
|
42
|
+
type: 'tool_result',
|
|
43
|
+
callId: 'call-1',
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
it('converts a context message to system role', () => {
|
|
47
|
+
const msgs = [{ role: 'context', content: 'Working directory: /tmp' }];
|
|
48
|
+
const turns = storedMessagesToTurns(msgs);
|
|
49
|
+
expect(turns).toHaveLength(1);
|
|
50
|
+
expect(turns[0].role).toBe('system');
|
|
51
|
+
});
|
|
52
|
+
it('round-trips with no data loss: user+assistant+tool', () => {
|
|
53
|
+
const original = [
|
|
54
|
+
{ role: 'context', content: 'cwd: /test' },
|
|
55
|
+
{ role: 'user', content: 'Read file.txt' },
|
|
56
|
+
{
|
|
57
|
+
role: 'assistant', content: 'Reading...',
|
|
58
|
+
tool_calls: [{ id: 'tc-1', type: 'function', function: { name: 'read_file', arguments: '{"path":"file.txt"}' } }],
|
|
59
|
+
},
|
|
60
|
+
{ role: 'tool', content: 'file content', tool_call_id: 'tc-1' },
|
|
61
|
+
{ role: 'assistant', content: 'Here is the content.' },
|
|
62
|
+
];
|
|
63
|
+
const turns = storedMessagesToTurns(original);
|
|
64
|
+
const back = turnsToStoredMessages(turns);
|
|
65
|
+
// The round-trip may not be byte-identical (tool_calls arguments formatting)
|
|
66
|
+
// but the semantic content should be preserved
|
|
67
|
+
expect(back.filter(m => m.role === 'user')).toHaveLength(1);
|
|
68
|
+
expect(back.filter(m => m.role === 'assistant')).toHaveLength(2);
|
|
69
|
+
expect(back.filter(m => m.role === 'tool')).toHaveLength(1);
|
|
70
|
+
expect(back.filter(m => m.role === 'context')).toHaveLength(1);
|
|
71
|
+
const userMsg = back.find(m => m.role === 'user');
|
|
72
|
+
expect(userMsg?.content).toBe('Read file.txt');
|
|
73
|
+
const assistantToolMsg = back.find(m => m.role === 'assistant' && m.tool_calls);
|
|
74
|
+
expect(assistantToolMsg?.tool_calls?.[0].function.name).toBe('read_file');
|
|
75
|
+
const toolMsg = back.find(m => m.role === 'tool');
|
|
76
|
+
expect(toolMsg?.content).toBe('file content');
|
|
77
|
+
expect(toolMsg?.tool_call_id).toBe('tc-1');
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
// ── Event reducer ──
|
|
81
|
+
describe('RunEventReducer', () => {
|
|
82
|
+
const baseEvent = (overrides) => ({
|
|
83
|
+
schemaVersion: 1,
|
|
84
|
+
runId: 'test-run-001',
|
|
85
|
+
at: new Date().toISOString(),
|
|
86
|
+
durability: 'ephemeral',
|
|
87
|
+
...overrides,
|
|
88
|
+
event: overrides.event,
|
|
89
|
+
});
|
|
90
|
+
it('tracks plan approval state', () => {
|
|
91
|
+
const r = new RunEventReducer();
|
|
92
|
+
r.apply(baseEvent({ event: { type: 'run.created' } }));
|
|
93
|
+
expect(r['state']?.planApproved).toBe(false);
|
|
94
|
+
r.apply(baseEvent({ event: { type: 'plan.approved', planHash: 'abc' } }));
|
|
95
|
+
expect(r['state']?.planApproved).toBe(true);
|
|
96
|
+
});
|
|
97
|
+
it('tracks task state transitions', () => {
|
|
98
|
+
const r = new RunEventReducer();
|
|
99
|
+
r.apply(baseEvent({ event: { type: 'task.state', taskId: 't1', attempt: 1, state: 'running' } }));
|
|
100
|
+
const s1 = r['state'];
|
|
101
|
+
expect(s1?.tasks.get('t1')?.state).toBe('running');
|
|
102
|
+
r.apply(baseEvent({ event: { type: 'task.state', taskId: 't1', attempt: 1, state: 'succeeded' } }));
|
|
103
|
+
const s2 = r['state'];
|
|
104
|
+
expect(s2?.tasks.get('t1')?.state).toBe('succeeded');
|
|
105
|
+
});
|
|
106
|
+
it('accumulates tool call counts', () => {
|
|
107
|
+
const r = new RunEventReducer();
|
|
108
|
+
for (let i = 0; i < 3; i++) {
|
|
109
|
+
r.apply(baseEvent({ event: { type: 'tool.completed', taskId: 't1', attempt: 1, callId: `c${i}`, resultRef: `/tmp/r${i}`, digest: `d${i}` } }));
|
|
110
|
+
}
|
|
111
|
+
expect(r['state']?.totalToolCalls).toBe(3);
|
|
112
|
+
});
|
|
113
|
+
it('accumulates token usage', () => {
|
|
114
|
+
const r = new RunEventReducer();
|
|
115
|
+
r.apply(baseEvent({
|
|
116
|
+
event: {
|
|
117
|
+
type: 'usage.updated',
|
|
118
|
+
taskId: 't1',
|
|
119
|
+
attempt: 1,
|
|
120
|
+
usage: { inputTokens: 100, outputTokens: 50, estimated: false },
|
|
121
|
+
},
|
|
122
|
+
}));
|
|
123
|
+
r.apply(baseEvent({
|
|
124
|
+
event: {
|
|
125
|
+
type: 'usage.updated',
|
|
126
|
+
taskId: 't2',
|
|
127
|
+
attempt: 1,
|
|
128
|
+
usage: { inputTokens: 200, outputTokens: 75, estimated: false },
|
|
129
|
+
},
|
|
130
|
+
}));
|
|
131
|
+
const s = r['state'];
|
|
132
|
+
expect(s?.totalTokens.input).toBe(300);
|
|
133
|
+
expect(s?.totalTokens.output).toBe(125);
|
|
134
|
+
});
|
|
135
|
+
it('tracks run finished state', () => {
|
|
136
|
+
const r = new RunEventReducer();
|
|
137
|
+
r.apply(baseEvent({ event: { type: 'run.created' } }));
|
|
138
|
+
r.apply(baseEvent({ event: { type: 'run.finished', outcome: { kind: 'succeeded' } } }));
|
|
139
|
+
expect(r['state']?.status).toBe('finished');
|
|
140
|
+
expect(r['state']?.outcome?.kind).toBe('succeeded');
|
|
141
|
+
});
|
|
142
|
+
it('produces a non-empty summary', () => {
|
|
143
|
+
const r = new RunEventReducer();
|
|
144
|
+
r.apply(baseEvent({ event: { type: 'run.created' } }));
|
|
145
|
+
r.apply(baseEvent({ event: { type: 'plan.approved', planHash: 'abc' } }));
|
|
146
|
+
r.apply(baseEvent({ event: { type: 'task.state', taskId: 't1', attempt: 1, state: 'succeeded' } }));
|
|
147
|
+
r.apply(baseEvent({ event: { type: 'task.state', taskId: 't2', attempt: 1, state: 'failed', error: 'OOM' } }));
|
|
148
|
+
const summary = r.summary();
|
|
149
|
+
expect(summary).toContain('test-run');
|
|
150
|
+
expect(summary).toContain('succeeded');
|
|
151
|
+
expect(summary).toContain('t1');
|
|
152
|
+
expect(summary).toContain('t2');
|
|
153
|
+
});
|
|
154
|
+
});
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 2 tests: BudgetController, ApprovalQueue, and the Protokol adapter contract.
|
|
3
|
+
*
|
|
4
|
+
* These tests verify the new runtime components in isolation.
|
|
5
|
+
* Full end-to-end tests with a live backend require a staging environment.
|
|
6
|
+
*/
|
|
7
|
+
import { describe, it, expect } from 'vitest';
|
|
8
|
+
import { BudgetController, DEFAULT_RUN_BUDGETS } from '../runtime/budget-controller.js';
|
|
9
|
+
import { ApprovalQueue } from '../runtime/approval-queue.js';
|
|
10
|
+
// ── BudgetController ──
|
|
11
|
+
describe('BudgetController', () => {
|
|
12
|
+
it('acquires a lease within budget', () => {
|
|
13
|
+
const bc = new BudgetController(DEFAULT_RUN_BUDGETS);
|
|
14
|
+
const lease = bc.acquire({ modelCalls: 1 });
|
|
15
|
+
expect(lease.modelCalls).toBe(1);
|
|
16
|
+
expect(lease.deadlineMs).toBeGreaterThan(0);
|
|
17
|
+
});
|
|
18
|
+
it('throws when exceeding max model calls', () => {
|
|
19
|
+
const bc = new BudgetController({ ...DEFAULT_RUN_BUDGETS, maxModelCalls: 1 });
|
|
20
|
+
bc.acquire({ modelCalls: 1 });
|
|
21
|
+
bc.recordUsage({ estimated: false });
|
|
22
|
+
expect(() => bc.acquire({ modelCalls: 1 })).toThrow('Budget exceeded');
|
|
23
|
+
});
|
|
24
|
+
it('records usage and tracks tokens', () => {
|
|
25
|
+
const bc = new BudgetController(DEFAULT_RUN_BUDGETS);
|
|
26
|
+
bc.recordUsage({ inputTokens: 100, outputTokens: 50, estimated: false });
|
|
27
|
+
const state = bc.getState();
|
|
28
|
+
expect(state.inputTokens).toBe(100);
|
|
29
|
+
expect(state.outputTokens).toBe(50);
|
|
30
|
+
expect(state.modelCallsUsed).toBe(1);
|
|
31
|
+
});
|
|
32
|
+
it('throws when exceeding input token budget', () => {
|
|
33
|
+
const bc = new BudgetController({ ...DEFAULT_RUN_BUDGETS, maxInputTokens: 500 });
|
|
34
|
+
expect(() => bc.recordUsage({ inputTokens: 600, outputTokens: 0, estimated: false })).toThrow('Budget exceeded');
|
|
35
|
+
});
|
|
36
|
+
it('records tool calls', () => {
|
|
37
|
+
const bc = new BudgetController({ ...DEFAULT_RUN_BUDGETS, maxToolCalls: 5 });
|
|
38
|
+
for (let i = 0; i < 5; i++)
|
|
39
|
+
bc.recordToolCall();
|
|
40
|
+
expect(() => bc.recordToolCall()).toThrow('Budget exceeded');
|
|
41
|
+
});
|
|
42
|
+
it('isExceeded returns true when over budget', () => {
|
|
43
|
+
const bc = new BudgetController({ ...DEFAULT_RUN_BUDGETS, maxModelCalls: 1 });
|
|
44
|
+
bc.acquire({ modelCalls: 1 });
|
|
45
|
+
bc.recordUsage({ estimated: false });
|
|
46
|
+
expect(bc.isExceeded()).toBe(false);
|
|
47
|
+
// Exceed by trying to acquire more
|
|
48
|
+
expect(() => bc.acquire({ modelCalls: 1 })).toThrow();
|
|
49
|
+
});
|
|
50
|
+
it('remainingPercent returns a value between 0 and 100', () => {
|
|
51
|
+
const bc = new BudgetController(DEFAULT_RUN_BUDGETS);
|
|
52
|
+
expect(bc.remainingPercent).toBe(100); // 0/50 = 100%
|
|
53
|
+
bc.acquire({ modelCalls: 25 });
|
|
54
|
+
bc.recordUsage({ estimated: false });
|
|
55
|
+
expect(bc.remainingPercent).toBe(98); // 1/50 = 2% used
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
// ── ApprovalQueue ──
|
|
59
|
+
describe('ApprovalQueue', () => {
|
|
60
|
+
function makeCall(overrides) {
|
|
61
|
+
return { id: 'call-1', name: 'bash', arguments: { command: 'test' }, ...overrides };
|
|
62
|
+
}
|
|
63
|
+
it('queues a consent request and resolves it', async () => {
|
|
64
|
+
const aq = new ApprovalQueue();
|
|
65
|
+
const promise = aq.requestConsent('run-1', 'task-1', 1, 'agent-1', makeCall(), 'execute', 'Run test');
|
|
66
|
+
aq.resolvePending({ requestId: 'run-1::task-1::call-1', outcome: 'approved', scope: 'once', decidedAt: new Date().toISOString() });
|
|
67
|
+
const decision = await promise;
|
|
68
|
+
expect(decision.outcome).toBe('approved');
|
|
69
|
+
expect(decision.scope).toBe('once');
|
|
70
|
+
});
|
|
71
|
+
it('returns a scoped decision without queuing', async () => {
|
|
72
|
+
const aq = new ApprovalQueue();
|
|
73
|
+
// First request: approve with 'task' scope
|
|
74
|
+
const p1 = aq.requestConsent('run-1', 'task-1', 1, 'agent-1', makeCall(), 'execute', 'Test');
|
|
75
|
+
aq.resolvePending({ requestId: 'run-1::task-1::call-1', outcome: 'approved', scope: 'task', decidedAt: new Date().toISOString() });
|
|
76
|
+
await p1;
|
|
77
|
+
// Second request for same task/tool: should auto-approve
|
|
78
|
+
const p2 = aq.requestConsent('run-1', 'task-1', 2, 'agent-1', makeCall({ id: 'call-2' }), 'execute', 'Test 2');
|
|
79
|
+
const decision = await p2;
|
|
80
|
+
expect(decision.outcome).toBe('approved');
|
|
81
|
+
expect(decision.scope).toBe('task'); // Matches the stored scoped decision
|
|
82
|
+
});
|
|
83
|
+
it('clears all pending requests', () => {
|
|
84
|
+
const aq = new ApprovalQueue();
|
|
85
|
+
aq.requestConsent('run-1', 'task-1', 1, 'agent-1', makeCall(), 'execute', 'Test');
|
|
86
|
+
expect(aq.pending).toHaveLength(1);
|
|
87
|
+
aq.clear();
|
|
88
|
+
expect(aq.pending).toHaveLength(0);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
// ── Provider adapter contract (unit-level, no backend) ──
|
|
92
|
+
describe('ProtokolAdapter (static contract)', () => {
|
|
93
|
+
it('has correct id and family', async () => {
|
|
94
|
+
const { ProtokolAdapter } = await import('../providers/protokol.js');
|
|
95
|
+
// Can't instantiate without credentials in tests, but we can check the static shape
|
|
96
|
+
const instance = new ProtokolAdapter({ host: 'https://test.com', token: 'test', agentUUID: 'test' });
|
|
97
|
+
expect(instance.id).toBe('protokol');
|
|
98
|
+
expect(instance.family).toBe('protokol');
|
|
99
|
+
});
|
|
100
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 3 adapter contract tests — verify OpenAI-compatible adapter
|
|
3
|
+
* coverage as a second provider family.
|
|
4
|
+
*/
|
|
5
|
+
import { describe, it, expect } from 'vitest';
|
|
6
|
+
import { OpenAICompatibleAdapter } from '../providers/openai-compatible.js';
|
|
7
|
+
describe('OpenAICompatibleAdapter (structural contract)', () => {
|
|
8
|
+
const adapter = new OpenAICompatibleAdapter('test-openai', {
|
|
9
|
+
apiKey: 'sk-test',
|
|
10
|
+
});
|
|
11
|
+
it('has correct id and family', () => {
|
|
12
|
+
expect(adapter.id).toBe('test-openai');
|
|
13
|
+
expect(adapter.family).toBe('openai');
|
|
14
|
+
});
|
|
15
|
+
it('resolves capabilities for gpt-4o', async () => {
|
|
16
|
+
const caps = await adapter.resolveCapabilities({ type: 'model', model: 'gpt-4o' });
|
|
17
|
+
expect(caps.streaming).toBe(true);
|
|
18
|
+
expect(caps.toolUse).toBe(true);
|
|
19
|
+
expect(caps.parallelToolCalls).toBe(true);
|
|
20
|
+
expect(caps.contextWindow).toBe(128_000);
|
|
21
|
+
});
|
|
22
|
+
it('resolves capabilities for deepseek-chat', async () => {
|
|
23
|
+
const caps = await adapter.resolveCapabilities({ type: 'model', model: 'deepseek-chat' });
|
|
24
|
+
expect(caps.tokenCounting).toBe('estimated');
|
|
25
|
+
});
|
|
26
|
+
it('resolves capabilities for o1-mini (reasoning model)', async () => {
|
|
27
|
+
const caps = await adapter.resolveCapabilities({ type: 'model', model: 'o1-mini' });
|
|
28
|
+
expect(caps.toolUse).toBe(false);
|
|
29
|
+
expect(caps.maxOutputTokens).toBe(100_000);
|
|
30
|
+
});
|
|
31
|
+
it('stream rejects on invalid API key', async () => {
|
|
32
|
+
const badAdapter = new OpenAICompatibleAdapter('bad-key', { apiKey: 'invalid-key-will-401' });
|
|
33
|
+
const request = {
|
|
34
|
+
target: { type: 'model', model: 'gpt-4o' },
|
|
35
|
+
turns: [],
|
|
36
|
+
tools: [],
|
|
37
|
+
limits: { maxOutputTokens: 100 },
|
|
38
|
+
};
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
const events = [];
|
|
41
|
+
for await (const event of badAdapter.stream(request, controller.signal)) {
|
|
42
|
+
events.push(event);
|
|
43
|
+
}
|
|
44
|
+
// Should error cleanly (401) rather than hanging or crashing
|
|
45
|
+
expect(events.length).toBeGreaterThan(0);
|
|
46
|
+
expect(events.some(e => e.type === 'error')).toBe(true);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config loader — resolves, merges, and validates Kortex configuration.
|
|
3
|
+
*
|
|
4
|
+
* Source order (later overrides earlier):
|
|
5
|
+
* 1. Built-in defaults
|
|
6
|
+
* 2. Legacy ~/.ptkl/kortex.json (compatibility import)
|
|
7
|
+
* 3. ~/.ptkl/kortex/config.json
|
|
8
|
+
* 4. Legacy <project>/.ptkl/kortex.json (compatibility import)
|
|
9
|
+
* 5. <project>/.kortex.json
|
|
10
|
+
* 6. CLI flags / runtime overrides
|
|
11
|
+
*
|
|
12
|
+
* Arrays are replaced unless a field explicitly defines keyed merge behavior.
|
|
13
|
+
* Agents and providers merge by object key. null removes an inherited entry.
|
|
14
|
+
*/
|
|
15
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
16
|
+
import { resolve } from 'node:path';
|
|
17
|
+
const API_KEY_PATTERNS = [
|
|
18
|
+
/^api[_-]?key$/i,
|
|
19
|
+
/^api[_-]?token$/i,
|
|
20
|
+
/^secret_key$/i,
|
|
21
|
+
/^secret$/i,
|
|
22
|
+
/^token$/i,
|
|
23
|
+
];
|
|
24
|
+
/**
|
|
25
|
+
* Resolve configuration from the project and global config files.
|
|
26
|
+
*/
|
|
27
|
+
export function loadConfig(cwd) {
|
|
28
|
+
const errors = [];
|
|
29
|
+
let config = {};
|
|
30
|
+
const configPaths = [
|
|
31
|
+
resolve(process.env.HOME || '~', '.ptkl', 'kortex.json'),
|
|
32
|
+
resolve(process.env.HOME || '~', '.ptkl', 'kortex', 'config.json'),
|
|
33
|
+
resolve(cwd, '.ptkl', 'kortex.json'),
|
|
34
|
+
resolve(cwd, '.kortex.json'),
|
|
35
|
+
];
|
|
36
|
+
for (const path of configPaths) {
|
|
37
|
+
if (!existsSync(path))
|
|
38
|
+
continue;
|
|
39
|
+
try {
|
|
40
|
+
const data = JSON.parse(readFileSync(path, 'utf-8'));
|
|
41
|
+
config = mergeConfigs(config, data, path, errors);
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
errors.push({ path, message: `Failed to parse: ${e.message}`, severity: 'error' });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// Validate
|
|
48
|
+
const validationErrors = validateConfig(config);
|
|
49
|
+
errors.push(...validationErrors);
|
|
50
|
+
return { config, errors };
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Merge two config objects. Agents and providers merge by key; arrays replace.
|
|
54
|
+
*/
|
|
55
|
+
function mergeConfigs(base, override, sourcePath, errors) {
|
|
56
|
+
// Providers: merge by key
|
|
57
|
+
const providers = { ...(base.providers || {}), ...(override.providers || {}) };
|
|
58
|
+
// Agents: merge by key
|
|
59
|
+
const agents = { ...(base.agents || {}), ...(override.agents || {}) };
|
|
60
|
+
// Orchestrator: shallow merge (last wins for each field)
|
|
61
|
+
const orchestrator = { ...(base.orchestrator || {}), ...(override.orchestrator || {}) };
|
|
62
|
+
// MCP: merge by key
|
|
63
|
+
const mcp_servers = { ...(base.mcp_servers || {}), ...(override.mcp_servers || {}) };
|
|
64
|
+
return { version: override.version ?? base.version, providers, agents, orchestrator, mcp_servers };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Validate a fully merged config.
|
|
68
|
+
*/
|
|
69
|
+
function validateConfig(config) {
|
|
70
|
+
const errors = [];
|
|
71
|
+
// Version check
|
|
72
|
+
if (config.version !== undefined && config.version !== 1) {
|
|
73
|
+
errors.push({ path: 'version', message: `Unsupported config version: ${config.version}`, severity: 'error' });
|
|
74
|
+
}
|
|
75
|
+
// Validate providers
|
|
76
|
+
for (const [name, provider] of Object.entries(config.providers ?? {})) {
|
|
77
|
+
// Check for plaintext secrets
|
|
78
|
+
for (const [key, value] of Object.entries(provider)) {
|
|
79
|
+
if (typeof value === 'string' && API_KEY_PATTERNS.some(p => p.test(key))) {
|
|
80
|
+
errors.push({
|
|
81
|
+
path: `providers.${name}.${key}`,
|
|
82
|
+
message: `Plaintext ${key} detected. Use api_key_env to reference an environment variable instead.`,
|
|
83
|
+
severity: 'error',
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// Check api_key_env references
|
|
88
|
+
if (provider.api_key_env && !process.env[provider.api_key_env]) {
|
|
89
|
+
errors.push({
|
|
90
|
+
path: `providers.${name}.api_key_env`,
|
|
91
|
+
message: `Environment variable "${provider.api_key_env}" is not set.`,
|
|
92
|
+
severity: 'error',
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
// Reserved MCP server name
|
|
96
|
+
if (name === 'protokol' && provider.type !== 'protokol') {
|
|
97
|
+
errors.push({
|
|
98
|
+
path: `providers.${name}`,
|
|
99
|
+
message: '"protokol" is a reserved provider name.',
|
|
100
|
+
severity: 'error',
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Validate agents
|
|
105
|
+
for (const [name, agent] of Object.entries(config.agents ?? {})) {
|
|
106
|
+
if (!agent.provider) {
|
|
107
|
+
errors.push({ path: `agents.${name}.provider`, message: 'Agent must specify a provider.', severity: 'error' });
|
|
108
|
+
}
|
|
109
|
+
else if (!config.providers?.[agent.provider]) {
|
|
110
|
+
errors.push({ path: `agents.${name}.provider`, message: `Provider "${agent.provider}" not found in providers section.`, severity: 'error' });
|
|
111
|
+
}
|
|
112
|
+
if (!agent.target) {
|
|
113
|
+
errors.push({ path: `agents.${name}.target`, message: 'Agent must specify a target.', severity: 'error' });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return errors;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Validate MCP config — no user server may be named "protokol".
|
|
120
|
+
*/
|
|
121
|
+
export function validateMCPConfig(mcp_servers) {
|
|
122
|
+
const errors = [];
|
|
123
|
+
for (const name of Object.keys(mcp_servers || {})) {
|
|
124
|
+
if (name === 'protokol') {
|
|
125
|
+
errors.push({ path: `mcp_servers.${name}`, message: '"protokol" is a reserved MCP server ID. Remove this entry.', severity: 'error' });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return errors;
|
|
129
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Schema for .kortex.json config files.
|
|
3
|
+
* Used for validation on load. Phase 3+.
|
|
4
|
+
*/
|
|
5
|
+
export const KORTEX_CONFIG_SCHEMA = {
|
|
6
|
+
$schema: 'http://json-schema.org/draft-07/schema#',
|
|
7
|
+
title: 'KortexConfig',
|
|
8
|
+
type: 'object',
|
|
9
|
+
properties: {
|
|
10
|
+
version: { type: 'number', enum: [1] },
|
|
11
|
+
providers: {
|
|
12
|
+
type: 'object',
|
|
13
|
+
additionalProperties: {
|
|
14
|
+
type: 'object',
|
|
15
|
+
properties: {
|
|
16
|
+
type: { type: 'string', enum: ['protokol', 'openai', 'openai-compatible', 'anthropic', 'google', 'custom'] },
|
|
17
|
+
api_key_env: { type: 'string' },
|
|
18
|
+
base_url: { type: 'string', format: 'uri' },
|
|
19
|
+
auth: { type: 'string' },
|
|
20
|
+
default_model: { type: 'string' },
|
|
21
|
+
},
|
|
22
|
+
required: ['type'],
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
agents: {
|
|
26
|
+
type: 'object',
|
|
27
|
+
additionalProperties: {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: {
|
|
30
|
+
description: { type: 'string' },
|
|
31
|
+
provider: { type: 'string' },
|
|
32
|
+
target: {
|
|
33
|
+
oneOf: [
|
|
34
|
+
{ type: 'object', properties: { type: { const: 'model' }, model: { type: 'string' } }, required: ['type', 'model'] },
|
|
35
|
+
{ type: 'object', properties: { type: { const: 'provider_agent' }, id: { type: 'string' } }, required: ['type', 'id'] },
|
|
36
|
+
],
|
|
37
|
+
},
|
|
38
|
+
instructions: {
|
|
39
|
+
type: 'object',
|
|
40
|
+
properties: {
|
|
41
|
+
type: { type: 'string', enum: ['inline', 'file', 'provider_managed'] },
|
|
42
|
+
text: { type: 'string' },
|
|
43
|
+
path: { type: 'string' },
|
|
44
|
+
},
|
|
45
|
+
required: ['type'],
|
|
46
|
+
},
|
|
47
|
+
tools: {
|
|
48
|
+
type: 'object',
|
|
49
|
+
properties: {
|
|
50
|
+
allow: { type: 'array', items: { type: 'string' } },
|
|
51
|
+
deny: { type: 'array', items: { type: 'string' } },
|
|
52
|
+
riskCeiling: { type: 'string', enum: ['read', 'write', 'execute', 'external'] },
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
required: ['description', 'provider', 'target', 'instructions'],
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* KortexController — routes between legacy ChatSession and orchestration sessions.
|
|
3
|
+
*
|
|
4
|
+
* Phase 2: the new runner runs behind a feature flag (KORTEX_NEW_RUNNER).
|
|
5
|
+
* Default is legacy Session for backward compatibility.
|
|
6
|
+
*
|
|
7
|
+
* Phase 4+: the new runner becomes the default; legacy Session is removed.
|
|
8
|
+
*/
|
|
9
|
+
import LegacySession from './session.js';
|
|
10
|
+
import { createDefaultRegistry } from './providers/registry.js';
|
|
11
|
+
import { ProtokolAdapter } from './providers/protokol.js';
|
|
12
|
+
import { ToolRuntime } from './runtime/tool-runtime.js';
|
|
13
|
+
import { ApprovalQueue } from './runtime/approval-queue.js';
|
|
14
|
+
import { BudgetController, DEFAULT_RUN_BUDGETS } from './runtime/budget-controller.js';
|
|
15
|
+
import { AgentRunner as NewAgentRunner } from './runtime/agent-runner.js';
|
|
16
|
+
import { RunEventReducer } from './events/reducer.js';
|
|
17
|
+
/**
|
|
18
|
+
* Create and start the appropriate session based on the feature flag.
|
|
19
|
+
*/
|
|
20
|
+
export async function startSession(opts) {
|
|
21
|
+
const useNewRunner = process.env.KORTEX_NEW_RUNNER === '1';
|
|
22
|
+
if (useNewRunner) {
|
|
23
|
+
await startNewRunner(opts);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
await startLegacySession(opts);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function startNewRunner(opts) {
|
|
30
|
+
// Build provider registry with Protokol adapter
|
|
31
|
+
const registry = createDefaultRegistry();
|
|
32
|
+
const protokolAdapter = new ProtokolAdapter({
|
|
33
|
+
host: opts.host,
|
|
34
|
+
token: opts.token,
|
|
35
|
+
agentUUID: opts.agentUUID,
|
|
36
|
+
});
|
|
37
|
+
registry.register(protokolAdapter);
|
|
38
|
+
// Build runtime
|
|
39
|
+
const toolRuntime = new ToolRuntime();
|
|
40
|
+
const approvalQueue = new ApprovalQueue();
|
|
41
|
+
const budgetController = new BudgetController(DEFAULT_RUN_BUDGETS);
|
|
42
|
+
const agentRunner = new NewAgentRunner(toolRuntime, approvalQueue, budgetController);
|
|
43
|
+
const reducer = new RunEventReducer();
|
|
44
|
+
// Phase 4+: orchestration session
|
|
45
|
+
opts.bridge.showSystem('Kortex new runner initialized (experimental).');
|
|
46
|
+
}
|
|
47
|
+
async function startLegacySession(opts) {
|
|
48
|
+
const session = new LegacySession({
|
|
49
|
+
token: opts.token,
|
|
50
|
+
host: opts.host,
|
|
51
|
+
agentUUID: opts.agentUUID,
|
|
52
|
+
agentName: opts.agentName,
|
|
53
|
+
cwd: opts.cwd,
|
|
54
|
+
conversationUUID: opts.conversationUUID,
|
|
55
|
+
initialPrompt: opts.initialPrompt,
|
|
56
|
+
cloud: opts.cloud,
|
|
57
|
+
bridge: opts.bridge,
|
|
58
|
+
});
|
|
59
|
+
await session.start();
|
|
60
|
+
}
|