@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.
Files changed (41) hide show
  1. package/dist/commands/forge.js +34 -6
  2. package/dist/lib/kortex/__tests__/fixtures/providers/conformance.test.js +120 -0
  3. package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +172 -0
  4. package/dist/lib/kortex/__tests__/legacy-compatibility.test.js +273 -0
  5. package/dist/lib/kortex/__tests__/phase-1-conversion.test.js +154 -0
  6. package/dist/lib/kortex/__tests__/phase-2-runtime.test.js +100 -0
  7. package/dist/lib/kortex/__tests__/phase-3-provider.test.js +48 -0
  8. package/dist/lib/kortex/config/loader.js +129 -0
  9. package/dist/lib/kortex/config/schema.js +60 -0
  10. package/dist/lib/kortex/controller.js +60 -0
  11. package/dist/lib/kortex/conversation/legacy-conversion.js +141 -0
  12. package/dist/lib/kortex/conversation/types.js +13 -0
  13. package/dist/lib/kortex/events/index.js +1 -0
  14. package/dist/lib/kortex/events/reducer.js +86 -0
  15. package/dist/lib/kortex/events/types.js +7 -0
  16. package/dist/lib/kortex/events/writer.js +76 -0
  17. package/dist/lib/kortex/mcp/index.js +1 -0
  18. package/dist/lib/kortex/orchestration/index.js +1 -0
  19. package/dist/lib/kortex/orchestration/manager-worker.js +88 -0
  20. package/dist/lib/kortex/orchestration/peer-collaboration.js +59 -0
  21. package/dist/lib/kortex/orchestration/plan.js +133 -0
  22. package/dist/lib/kortex/orchestration/scheduler.js +124 -0
  23. package/dist/lib/kortex/persistence/index.js +1 -0
  24. package/dist/lib/kortex/persistence/run-journal.js +94 -0
  25. package/dist/lib/kortex/providers/anthropic.js +34 -0
  26. package/dist/lib/kortex/providers/index.js +1 -0
  27. package/dist/lib/kortex/providers/openai-compatible.js +190 -0
  28. package/dist/lib/kortex/providers/protokol.js +204 -0
  29. package/dist/lib/kortex/providers/registry.js +61 -0
  30. package/dist/lib/kortex/providers/types.js +13 -0
  31. package/dist/lib/kortex/runtime/agent-runner.js +241 -0
  32. package/dist/lib/kortex/runtime/approval-queue.js +95 -0
  33. package/dist/lib/kortex/runtime/budget-controller.js +105 -0
  34. package/dist/lib/kortex/runtime/index.js +1 -0
  35. package/dist/lib/kortex/runtime/tool-runtime.js +66 -0
  36. package/dist/lib/kortex/runtime/workspace.js +52 -0
  37. package/dist/lib/kortex/tools/index.js +1 -0
  38. package/dist/lib/kortex/tools.js +226 -34
  39. package/dist/lib/kortex/types.js +7 -0
  40. package/dist/lib/kortex/ui/index.js +1 -0
  41. package/package.json +6 -4
@@ -11,6 +11,36 @@ import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
11
11
  import { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
12
12
  import * as sdk from "../lib/sdk.js";
13
13
  import { registerCommand, withProfile } from "../lib/scaffold.js";
14
+ // Total byte budget for an app's declared permissions, matching MaxForgePermissionBytes in
15
+ // appservice and maxPermissionSetBytes in platform-api. All three must move together: whichever is
16
+ // lowest becomes the real limit, and a developer would hit it at a different, more confusing point.
17
+ //
18
+ // It replaces a cap of 100 entries. That cap existed to keep the permission list inside HTTP header
19
+ // limits, and the list no longer travels in the token — platform-api stores the scoped set in Redis
20
+ // and re-attaches it when claims are parsed. The budget stays as a backstop: permission strings
21
+ // embed user-supplied resource and function names, so the declared set is unbounded and
22
+ // user-controlled even though it is no longer fatal at that size.
23
+ //
24
+ // Bytes rather than count because count was the wrong measure — 100 long permissions and 100 short
25
+ // ones are not the same thing, and the old check summed only runtime_permissions and entitlements,
26
+ // missing the grants and the permissions appended during the mint. That is how an app nominally
27
+ // capped at ~8 KB shipped a ~12 KB token and broke launch. It is sized to be unreachable for real
28
+ // apps (the largest today declares ~8 KB) rather than to act as a product limit.
29
+ const MAX_PERMISSION_BYTES = 64 * 1024;
30
+ /**
31
+ * Throws when an app's declared permissions exceed MAX_PERMISSION_BYTES.
32
+ *
33
+ * Takes grants as an optional third argument for the same reason its appservice counterpart does:
34
+ * request grants (FORGE_REQUEST_GRANTS_RFC.md) are still unimplemented, and when they land they
35
+ * belong in this sum rather than in a second, separate check.
36
+ */
37
+ function assertPermissionBytesWithinBudget(runtimePermissions = [], entitlements = [], grants = []) {
38
+ const all = [...runtimePermissions, ...entitlements, ...grants];
39
+ const bytes = all.reduce((total, permission) => total + Buffer.byteLength(permission, "utf8"), 0);
40
+ if (bytes > MAX_PERMISSION_BYTES) {
41
+ throw new Error(`Declared permissions total ${bytes} bytes across ${all.length} entries, exceeding the ${MAX_PERMISSION_BYTES} byte limit`);
42
+ }
43
+ }
14
44
  function parseJSON(label, raw) {
15
45
  try {
16
46
  return JSON.parse(raw);
@@ -314,12 +344,10 @@ class ForgeCommand {
314
344
  if (existsSync(distPath)) {
315
345
  rmSync(distPath, { recursive: true, force: true });
316
346
  }
317
- // Validate combined permissions limit
318
- const rtPerms = runtime_permissions ?? [];
319
- const ents = entitlements ?? [];
320
- if (rtPerms.length + ents.length > 100) {
321
- throw new Error(`Combined runtime_permissions (${rtPerms.length}) and entitlements (${ents.length}) must not exceed 100 entries`);
322
- }
347
+ // Validate the declared permission budget. Mirrors assertPermissionBytesWithinBudget in
348
+ // appservice and assertPermissionSetWithinBudget in platform-api — same 64 KB, so a build
349
+ // that passes here is not rejected at publish or at a user's app launch.
350
+ assertPermissionBytesWithinBudget(runtime_permissions ?? [], entitlements ?? []);
323
351
  // Normalize views: support both string entries and object entries with access/permissions
324
352
  const normalizedViews = {};
325
353
  if (views) {
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Provider conformance fixtures — recorded SSE streams for testing adapter parsing.
3
+ *
4
+ * Each fixture is an array of raw SSE text chunks that simulate the provider's
5
+ * streaming protocol. The test verifies that the refactored SSE parser produces
6
+ * the expected StreamEvents.
7
+ *
8
+ * Phase 1: text-only streams. Extended in Phase 3+ with tool call, thinking,
9
+ * error, and usage-only streams for each supported provider family.
10
+ */
11
+ import { describe, it, expect } from 'vitest';
12
+ // ── Fixture: simple text stream (two deltas + complete) ──
13
+ export const TEXT_ONLY_STREAM = [
14
+ 'event: message_start\ndata: {"model":"gpt-4o","agent_name":"Coder-A"}\n\n',
15
+ 'event: content_delta\ndata: {"delta":"Hello"}\n\n',
16
+ 'event: content_delta\ndata: {"delta":" world"}\n\n',
17
+ 'event: message_complete\ndata: {"token_usage":{"prompt_tokens":10,"completion_tokens":5}}\n\n',
18
+ ];
19
+ // ── Fixture: stream with tool calls ──
20
+ export const TOOL_CALL_STREAM = [
21
+ 'event: message_start\ndata: {}\n\n',
22
+ 'event: content_delta\ndata: {"delta":"Let me look that up."}\n\n',
23
+ 'event: message_complete\ndata: {"tool_calls":[{"id":"tc-1","type":"function","function":{"name":"read_file","arguments":"{\\"path\\":\\"test.txt\\"}"}}],"token_usage":{"prompt_tokens":20,"completion_tokens":15}}\n\n',
24
+ ];
25
+ // ── Fixture: stream with thinking blocks ──
26
+ export const THINKING_STREAM = [
27
+ 'event: message_start\ndata: {}\n\n',
28
+ 'event: thinking_delta\ndata: {"delta":"Let me reason step by step..."}\n\n',
29
+ 'event: thinking_delta\ndata: {"delta":"First, I need to check..."}\n\n',
30
+ 'event: content_delta\ndata: {"delta":"Here is the answer."}\n\n',
31
+ 'event: message_complete\ndata: {}\n\n',
32
+ ];
33
+ // ── Fixture: error stream ──
34
+ export const ERROR_STREAM = [
35
+ 'event: error\ndata: {"error":"Rate limit exceeded. Retry after 30 seconds."}\n\n',
36
+ ];
37
+ // ── Fixture: mixed agent attribution ──
38
+ export const MULTI_AGENT_STREAM = [
39
+ 'event: message_start\ndata: {"agent_name":"Coder-A"}\n\n',
40
+ 'event: content_delta\ndata: {"delta":"Implementing..."}\n\n',
41
+ 'event: message_start\ndata: {"agent_name":"Reviewer-B"}\n\n',
42
+ 'event: content_delta\ndata: {"delta":"Review findings:"}\n\n',
43
+ 'event: message_complete\ndata: {}\n\n',
44
+ ];
45
+ describe('SSE fixture parsing', () => {
46
+ // Re-import the SSE parser from the fixture file
47
+ async function* parseSSE(chunks) {
48
+ let buffer = '';
49
+ for (const chunk of chunks) {
50
+ buffer += chunk;
51
+ const parts = buffer.split('\n\n');
52
+ buffer = parts.pop() || '';
53
+ for (const part of parts) {
54
+ const lines = part.split('\n');
55
+ let event = '';
56
+ let data = '';
57
+ for (const line of lines) {
58
+ if (line.startsWith('event: '))
59
+ event = line.slice(7);
60
+ else if (line.startsWith('data: '))
61
+ data = line.slice(6);
62
+ }
63
+ if (event && data)
64
+ yield { event, data };
65
+ }
66
+ }
67
+ }
68
+ it('parses text-only stream into 4 events', async () => {
69
+ const events = [];
70
+ for await (const e of parseSSE(TEXT_ONLY_STREAM))
71
+ events.push(e);
72
+ expect(events).toHaveLength(4);
73
+ expect(events[0].event).toBe('message_start');
74
+ expect(events[1].event).toBe('content_delta');
75
+ expect(events[2].event).toBe('content_delta');
76
+ expect(events[3].event).toBe('message_complete');
77
+ });
78
+ it('parses tool call stream with one tool call', async () => {
79
+ const events = [];
80
+ for await (const e of parseSSE(TOOL_CALL_STREAM))
81
+ events.push(e);
82
+ expect(events).toHaveLength(3);
83
+ expect(events[0].event).toBe('message_start');
84
+ expect(events[1].event).toBe('content_delta');
85
+ // message_complete with tool calls data
86
+ const complete = JSON.parse(events[2].data);
87
+ expect(complete.tool_calls).toHaveLength(1);
88
+ expect(complete.tool_calls[0].function.name).toBe('read_file');
89
+ });
90
+ it('parses thinking stream with thinking_delta blocks', async () => {
91
+ const events = [];
92
+ for await (const e of parseSSE(THINKING_STREAM))
93
+ events.push(e);
94
+ expect(events).toHaveLength(5);
95
+ expect(events[0].event).toBe('message_start');
96
+ expect(events[1].event).toBe('thinking_delta');
97
+ expect(events[2].event).toBe('thinking_delta');
98
+ expect(events[3].event).toBe('content_delta');
99
+ expect(events[4].event).toBe('message_complete');
100
+ });
101
+ it('parses error stream', async () => {
102
+ const events = [];
103
+ for await (const e of parseSSE(ERROR_STREAM))
104
+ events.push(e);
105
+ expect(events).toHaveLength(1);
106
+ expect(events[0].event).toBe('error');
107
+ const err = JSON.parse(events[0].data);
108
+ expect(err.error).toContain('Rate limit');
109
+ });
110
+ it('parses multi-agent attribution', async () => {
111
+ const events = [];
112
+ for await (const e of parseSSE(MULTI_AGENT_STREAM))
113
+ events.push(e);
114
+ expect(events).toHaveLength(5);
115
+ const agentNames = events
116
+ .filter(e => e.event === 'message_start')
117
+ .map(e => JSON.parse(e.data).agent_name);
118
+ expect(agentNames).toEqual(['Coder-A', 'Reviewer-B']);
119
+ });
120
+ });
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Fixtures and tests for existing SSE streaming protocol and local conversation persistence.
3
+ *
4
+ * These capture the current wire format and storage behavior as a regression guard
5
+ * against the orchestration refactor.
6
+ */
7
+ import { describe, it, expect } from 'vitest';
8
+ import { createConversation, saveConversation, loadConversation, deleteConversation } from '../../conversations.js';
9
+ /**
10
+ * Reimplemented from session.ts line 867–896 for testability.
11
+ * This is the current parsing behavior — any refactored parser
12
+ * must produce the same output for the same input.
13
+ */
14
+ export async function* parseSSE(stream) {
15
+ let buffer = '';
16
+ for await (const chunk of stream) {
17
+ buffer += chunk.toString();
18
+ const parts = buffer.split('\n\n');
19
+ buffer = parts.pop() || '';
20
+ for (const part of parts) {
21
+ const lines = part.split('\n');
22
+ let event = '';
23
+ let data = '';
24
+ for (const line of lines) {
25
+ if (line.startsWith('event: '))
26
+ event = line.slice(7);
27
+ else if (line.startsWith('data: '))
28
+ data = line.slice(6);
29
+ }
30
+ if (event && data)
31
+ yield { event, data };
32
+ }
33
+ }
34
+ // Handle trailing data without double newline
35
+ if (buffer.trim()) {
36
+ const lines = buffer.split('\n');
37
+ let event = '';
38
+ let data = '';
39
+ for (const line of lines) {
40
+ if (line.startsWith('event: '))
41
+ event = line.slice(7);
42
+ else if (line.startsWith('data: '))
43
+ data = line.slice(6);
44
+ }
45
+ if (event && data)
46
+ yield { event, data };
47
+ }
48
+ }
49
+ // Helper to create a readable stream from a string
50
+ function stringToStream(text) {
51
+ const { Readable } = require('node:stream');
52
+ return Readable.from([text]);
53
+ }
54
+ describe('SSE parsing (current protocol)', () => {
55
+ it('parses a single event', async () => {
56
+ const stream = stringToStream('event: content_delta\ndata: {"delta":"Hello"}\n\n');
57
+ const events = [];
58
+ for await (const e of parseSSE(stream))
59
+ events.push(e);
60
+ expect(events).toHaveLength(1);
61
+ expect(events[0].event).toBe('content_delta');
62
+ expect(JSON.parse(events[0].data)).toEqual({ delta: 'Hello' });
63
+ });
64
+ it('parses multiple events', async () => {
65
+ const stream = stringToStream('event: content_delta\ndata: {"delta":"Hello"}\n\n' +
66
+ 'event: content_delta\ndata: {"delta":" world"}\n\n' +
67
+ 'event: message_complete\ndata: {"agent_name":"Proka"}\n\n');
68
+ const events = [];
69
+ for await (const e of parseSSE(stream))
70
+ events.push(e);
71
+ expect(events).toHaveLength(3);
72
+ expect(events[0].data).toBe('{"delta":"Hello"}');
73
+ expect(events[1].data).toBe('{"delta":" world"}');
74
+ expect(events[2].event).toBe('message_complete');
75
+ });
76
+ it('handles chunk boundaries gracefully', async () => {
77
+ // Simulate a stream that delivers the event in two chunks mid-way through
78
+ const { Readable } = require('node:stream');
79
+ const stream = Readable.from([
80
+ 'event: content_delta\nda',
81
+ 'ta: {"delta":"Hello"}\n\nevent: message_complete\ndata: {}\n\n',
82
+ ]);
83
+ const events = [];
84
+ for await (const e of parseSSE(stream))
85
+ events.push(e);
86
+ expect(events).toHaveLength(2);
87
+ expect(events[0].event).toBe('content_delta');
88
+ expect(events[1].event).toBe('message_complete');
89
+ });
90
+ it('parses thinking_delta events', async () => {
91
+ const stream = stringToStream('event: thinking_delta\ndata: {"delta":"Let me think..."}\n\n');
92
+ const events = [];
93
+ for await (const e of parseSSE(stream))
94
+ events.push(e);
95
+ expect(events[0].event).toBe('thinking_delta');
96
+ expect(JSON.parse(events[0].data).delta).toContain('think');
97
+ });
98
+ it('parses message_start with agent_name', async () => {
99
+ const stream = stringToStream('event: message_start\ndata: {"agent_name":"Coder-A"}\n\n');
100
+ const events = [];
101
+ for await (const e of parseSSE(stream))
102
+ events.push(e);
103
+ expect(events[0].event).toBe('message_start');
104
+ expect(JSON.parse(events[0].data).agent_name).toBe('Coder-A');
105
+ });
106
+ it('parses error events', async () => {
107
+ const stream = stringToStream('event: error\ndata: {"error":"Rate limit exceeded"}\n\n');
108
+ const events = [];
109
+ for await (const e of parseSSE(stream))
110
+ events.push(e);
111
+ expect(events[0].event).toBe('error');
112
+ expect(JSON.parse(events[0].data).error).toContain('Rate limit');
113
+ });
114
+ });
115
+ // ── Local conversation persistence ──
116
+ //
117
+ // These tests capture the current behavior of createConversation,
118
+ // saveConversation, loadConversation, listConversations, and
119
+ // deleteConversation against the file system.
120
+ describe('local conversation persistence', () => {
121
+ // The conversations module uses a hard-coded path:
122
+ // ~/.ptkl/kortex/conversations/
123
+ // We can't easily mock it, but we can test the types and validate
124
+ // the storage contract.
125
+ it('StoredConversation has the expected shape', () => {
126
+ const conv = createConversation('test-agent', 'TestAgent', '/tmp');
127
+ expect(conv.meta).toHaveProperty('uuid');
128
+ expect(conv).toHaveProperty('meta');
129
+ expect(conv.meta.agentUUID).toBe('test-agent');
130
+ expect(conv.meta.agentName).toBe('TestAgent');
131
+ expect(conv.meta.cwd).toBe('/tmp');
132
+ expect(conv.meta.messageCount).toBe(0);
133
+ expect(Array.isArray(conv.messages)).toBe(true);
134
+ expect(conv.messages).toHaveLength(0);
135
+ });
136
+ it('createConversation generates a UUID', () => {
137
+ const conv1 = createConversation('agent-1', 'Agent1', '/tmp');
138
+ const conv2 = createConversation('agent-2', 'Agent2', '/tmp');
139
+ expect(conv1.meta.uuid).not.toBe(conv2.meta.uuid);
140
+ // UUID format: 8-4-4-4-12 hex chars
141
+ expect(conv1.meta.uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
142
+ });
143
+ it('save/load round-trip preserves data', async () => {
144
+ const conv = createConversation('test-agent', 'TestAgent', '/tmp');
145
+ conv.messages = [
146
+ { role: 'context', content: 'Working directory: /tmp' },
147
+ { role: 'user', content: 'Hello' },
148
+ { role: 'assistant', content: 'Hi there!' },
149
+ ];
150
+ saveConversation(conv);
151
+ // Load from disk (may fail in read-only environments — saveConversation
152
+ // silently catches write errors, so load returns null)
153
+ const loaded = loadConversation(conv.meta.uuid);
154
+ if (loaded !== null) {
155
+ expect(loaded.meta.uuid).toBe(conv.meta.uuid);
156
+ expect(loaded.messages).toHaveLength(3);
157
+ expect(loaded.messages[1].content).toBe('Hello');
158
+ expect(loaded.meta.messageCount).toBe(2); // user + assistant = 2
159
+ deleteConversation(conv.meta.uuid);
160
+ }
161
+ });
162
+ it('createConversation with initial content', () => {
163
+ const conv = createConversation('agent-uuid', 'AgentName', '/workspace');
164
+ expect(conv.meta.uuid).toBeTruthy();
165
+ expect(conv.meta.agentUUID).toBe('agent-uuid');
166
+ expect(conv.meta.cwd).toBe('/workspace');
167
+ });
168
+ it('deleteConversation handles non-existent gracefully', () => {
169
+ // Should not throw for non-existent UUID
170
+ expect(() => deleteConversation('00000000-0000-0000-0000-000000000000')).not.toThrow();
171
+ });
172
+ });
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Baseline compatibility tests for existing Kortex tools.
3
+ *
4
+ * These capture the current behavior of the built-in tool executors
5
+ * before the orchestration refactor. They serve as regression guards:
6
+ * any refactored tool must produce the same observable output for the
7
+ * same inputs, on a known fixture directory.
8
+ *
9
+ * Run with: `npx vitest run src/lib/kortex/__tests__/legacy-compatibility.test.ts`
10
+ */
11
+ import { describe, it, expect, beforeAll } from 'vitest';
12
+ import { mkdtempSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ // The tools module — imported directly; any refactor that moves or renames
16
+ // this file must update this import path.
17
+ import { getToolDefinitions, executeTool, getToolRisk, validateToolArgs } from '../tools.js';
18
+ let cwd;
19
+ beforeAll(() => {
20
+ // Create a sandbox directory for each test file
21
+ cwd = mkdtempSync(join(tmpdir(), 'kortex-baseline-'));
22
+ // Seed with known content
23
+ writeFileSync(join(cwd, 'hello.txt'), 'Hello, world!', 'utf-8');
24
+ writeFileSync(join(cwd, 'data.json'), JSON.stringify({ key: 'value', nested: { a: 1 } }), 'utf-8');
25
+ // A small subdirectory
26
+ mkdirSync(join(cwd, 'subdir'));
27
+ writeFileSync(join(cwd, 'subdir', 'deep.txt'), 'deep content', 'utf-8');
28
+ });
29
+ // ── Smoke: tool definitions ──
30
+ describe('getToolDefinitions', () => {
31
+ it('returns at least 11 built-in tools', () => {
32
+ const tools = getToolDefinitions();
33
+ expect(tools.length).toBeGreaterThanOrEqual(11);
34
+ });
35
+ it('every tool has name, description, parameters', () => {
36
+ for (const t of getToolDefinitions()) {
37
+ expect(t.function.name).toBeTruthy();
38
+ expect(t.function.description).toBeTruthy();
39
+ expect(t.function.parameters).toBeTruthy();
40
+ }
41
+ });
42
+ it('includes read_file, write_file, edit_file, bash, git_status', () => {
43
+ const names = getToolDefinitions().map(t => t.function.name);
44
+ expect(names).toContain('read_file');
45
+ expect(names).toContain('write_file');
46
+ expect(names).toContain('edit_file');
47
+ expect(names).toContain('bash');
48
+ expect(names).toContain('git_status');
49
+ expect(names).toContain('git_diff');
50
+ expect(names).toContain('git_log');
51
+ expect(names).toContain('git_commit');
52
+ expect(names).toContain('git_branch');
53
+ expect(names).toContain('list_directory');
54
+ expect(names).toContain('search_files');
55
+ });
56
+ });
57
+ // ── File read ──
58
+ describe('read_file', () => {
59
+ const name = 'read_file';
60
+ function call(args) {
61
+ return { id: 'test-1', type: 'function', function: { name, arguments: JSON.stringify(args) } };
62
+ }
63
+ it('reads an existing file', () => {
64
+ const result = executeTool(cwd, call({ path: 'hello.txt' }));
65
+ expect(result.content).toContain('Hello, world!');
66
+ expect(result.tool_call_id).toBe('test-1');
67
+ });
68
+ it('returns line-numbered output', () => {
69
+ const result = executeTool(cwd, call({ path: 'hello.txt' }));
70
+ expect(result.content).toMatch(/^\d+\t/);
71
+ });
72
+ it('supports offset and limit', () => {
73
+ writeFileSync(join(cwd, 'lines.txt'), 'a\nb\nc\nd\ne\n', 'utf-8');
74
+ const result = executeTool(cwd, call({ path: 'lines.txt', offset: 2, limit: 3 }));
75
+ expect(result.content).toContain('b');
76
+ expect(result.content).toContain('d');
77
+ });
78
+ it('returns error for non-existent file', () => {
79
+ const result = executeTool(cwd, call({ path: 'nonexistent.txt' }));
80
+ expect(result.content).toStrictEqual(expect.stringContaining('Error:'));
81
+ });
82
+ it('returns error for directory path', () => {
83
+ const result = executeTool(cwd, call({ path: 'subdir' }));
84
+ expect(result.content).toStrictEqual(expect.stringContaining('Error:'));
85
+ });
86
+ it('truncates output beyond MAX_OUTPUT limit', () => {
87
+ const longContent = 'x'.repeat(200_000);
88
+ writeFileSync(join(cwd, 'long.txt'), longContent, 'utf-8');
89
+ const result = executeTool(cwd, call({ path: 'long.txt' }));
90
+ expect(result.content.length).toBeLessThan(150_000);
91
+ expect(result.content).toContain('(truncated)');
92
+ });
93
+ });
94
+ // ── File write ──
95
+ describe('write_file', () => {
96
+ const name = 'write_file';
97
+ function call(args) {
98
+ return { id: 'test-w', type: 'function', function: { name, arguments: JSON.stringify(args) } };
99
+ }
100
+ it('creates a new file', () => {
101
+ const result = executeTool(cwd, call({ path: 'new.txt', content: 'new content' }));
102
+ expect(result.content).toContain('File written');
103
+ expect(existsSync(join(cwd, 'new.txt'))).toBe(true);
104
+ });
105
+ it('overwrites an existing file', () => {
106
+ writeFileSync(join(cwd, 'overwrite.txt'), 'old', 'utf-8');
107
+ executeTool(cwd, call({ path: 'overwrite.txt', content: 'new' }));
108
+ const content = require('node:fs').readFileSync(join(cwd, 'overwrite.txt'), 'utf-8');
109
+ expect(content).toBe('new');
110
+ });
111
+ it('creates intermediate directories', () => {
112
+ executeTool(cwd, call({ path: 'a/b/c/deep.txt', content: 'nested' }));
113
+ expect(existsSync(join(cwd, 'a', 'b', 'c', 'deep.txt'))).toBe(true);
114
+ });
115
+ });
116
+ // ── File edit ──
117
+ describe('edit_file', () => {
118
+ const name = 'edit_file';
119
+ function call(args) {
120
+ return { id: 'test-e', type: 'function', function: { name, arguments: JSON.stringify(args) } };
121
+ }
122
+ it('replaces an exact string match', () => {
123
+ writeFileSync(join(cwd, 'edit.txt'), 'Hello, world!', 'utf-8');
124
+ const result = executeTool(cwd, call({ path: 'edit.txt', old_string: 'world', new_string: 'Kortex' }));
125
+ expect(result.content).toContain('File edited');
126
+ const content = require('node:fs').readFileSync(join(cwd, 'edit.txt'), 'utf-8');
127
+ expect(content).toBe('Hello, Kortex!');
128
+ });
129
+ it('returns error when old_string not found', () => {
130
+ const result = executeTool(cwd, call({ path: 'hello.txt', old_string: 'nonexistent', new_string: 'x' }));
131
+ expect(result.content).toStrictEqual(expect.stringContaining('Error:'));
132
+ });
133
+ it('returns error when old_string appears multiple times', () => {
134
+ writeFileSync(join(cwd, 'multi.txt'), 'a a a', 'utf-8');
135
+ const result = executeTool(cwd, call({ path: 'multi.txt', old_string: 'a', new_string: 'b' }));
136
+ expect(result.content).toStrictEqual(expect.stringContaining('Error:'));
137
+ });
138
+ });
139
+ // ── List directory ──
140
+ describe('list_directory', () => {
141
+ const name = 'list_directory';
142
+ function call(args) {
143
+ return { id: 'test-ls', type: 'function', function: { name, arguments: JSON.stringify(args) } };
144
+ }
145
+ it('lists root directory', () => {
146
+ const result = executeTool(cwd, call({}));
147
+ expect(result.content).toContain('hello.txt');
148
+ expect(result.content).toContain('subdir/');
149
+ });
150
+ it('respects depth parameter', () => {
151
+ const result = executeTool(cwd, call({ depth: 1 }));
152
+ expect(result.content).toContain('subdir/');
153
+ });
154
+ it('returns error for non-existent path', () => {
155
+ const result = executeTool(cwd, call({ path: 'nonexistent' }));
156
+ expect(result.content).toStrictEqual(expect.stringContaining('Error:'));
157
+ });
158
+ });
159
+ // ── Shell tools ──
160
+ describe('bash', () => {
161
+ const name = 'bash';
162
+ function call(args) {
163
+ return { id: 'test-sh', type: 'function', function: { name, arguments: JSON.stringify(args) } };
164
+ }
165
+ it('executes a simple command', () => {
166
+ const result = executeTool(cwd, call({ command: 'echo "hello from bash"' }));
167
+ expect(result.content).toContain('hello from bash');
168
+ });
169
+ it('captures exit code on failure', () => {
170
+ const result = executeTool(cwd, call({ command: 'exit 42' }));
171
+ expect(result.content).toContain('Exit code: 42');
172
+ });
173
+ it('clamps long output', () => {
174
+ const result = executeTool(cwd, call({ command: 'yes | head -c 200000' }));
175
+ expect(result.content.length).toBeLessThan(150_000);
176
+ });
177
+ });
178
+ describe('search_files', () => {
179
+ const name = 'search_files';
180
+ function call(args) {
181
+ return { id: 'test-grep', type: 'function', function: { name, arguments: JSON.stringify(args) } };
182
+ }
183
+ it('finds matching patterns', () => {
184
+ const result = executeTool(cwd, call({ pattern: 'Hello' }));
185
+ expect(result.content).toContain('hello.txt');
186
+ });
187
+ it('returns no matches for absent pattern', () => {
188
+ const result = executeTool(cwd, call({ pattern: 'XYZZY_NONEXISTENT' }));
189
+ expect(result.content).toContain('No matches');
190
+ });
191
+ });
192
+ // ── Security / path containment ──
193
+ describe('path containment', () => {
194
+ const readCall = {
195
+ id: 'sec-1',
196
+ type: 'function',
197
+ function: { name: 'read_file', arguments: JSON.stringify({ path: '../etc/passwd' }) },
198
+ };
199
+ const writeCall = {
200
+ id: 'sec-2',
201
+ type: 'function',
202
+ function: { name: 'write_file', arguments: JSON.stringify({ path: '../../tmp/escape_test', content: 'escaped' }) },
203
+ };
204
+ it('read_file rejects traversal outside cwd', () => {
205
+ const result = executeTool(cwd, readCall);
206
+ expect(result.content).toStrictEqual(expect.stringContaining('escapes the working directory'));
207
+ });
208
+ it('write_file rejects traversal outside cwd', () => {
209
+ const result = executeTool(cwd, writeCall);
210
+ expect(result.content).toStrictEqual(expect.stringContaining('escapes the working directory'));
211
+ });
212
+ it('write_file rejects absolute paths outside cwd', () => {
213
+ const result = executeTool(cwd, {
214
+ id: 'sec-3',
215
+ type: 'function',
216
+ function: { name: 'write_file', arguments: JSON.stringify({ path: '/tmp/kortex-escape-test', content: 'x' }) },
217
+ });
218
+ expect(result.content).toStrictEqual(expect.stringContaining('escapes the working directory'));
219
+ });
220
+ });
221
+ // ── Tool risk classification ──
222
+ describe('getToolRisk', () => {
223
+ it('classifies read tools', () => {
224
+ expect(getToolRisk('read_file')).toBe('read');
225
+ expect(getToolRisk('list_directory')).toBe('read');
226
+ expect(getToolRisk('search_files')).toBe('read');
227
+ expect(getToolRisk('git_status')).toBe('read');
228
+ expect(getToolRisk('git_diff')).toBe('read');
229
+ expect(getToolRisk('git_log')).toBe('read');
230
+ });
231
+ it('classifies write tools', () => {
232
+ expect(getToolRisk('write_file')).toBe('write');
233
+ expect(getToolRisk('edit_file')).toBe('write');
234
+ });
235
+ it('classifies bash as execute', () => {
236
+ expect(getToolRisk('bash')).toBe('execute');
237
+ expect(getToolRisk('git_branch')).toBe('write');
238
+ });
239
+ it('classifies git_commit as destructive', () => {
240
+ expect(getToolRisk('git_commit')).toBe('destructive');
241
+ });
242
+ it('classifies MCP tools as external', () => {
243
+ expect(getToolRisk('mcp_filesystem_read')).toBe('external');
244
+ expect(getToolRisk('mcp_protokol_component_list')).toBe('external');
245
+ });
246
+ it('defaults unknown tools to execute', () => {
247
+ expect(getToolRisk('unknown_tool')).toBe('execute');
248
+ });
249
+ });
250
+ // ── Argument validation ──
251
+ describe('validateToolArgs', () => {
252
+ const readFileSchema = {
253
+ type: 'object',
254
+ properties: {
255
+ path: { type: 'string' },
256
+ offset: { type: 'number' },
257
+ limit: { type: 'number' },
258
+ },
259
+ required: ['path'],
260
+ };
261
+ it('passes valid args', () => {
262
+ const errs = validateToolArgs('read_file', { path: 'file.txt', offset: 1 }, readFileSchema);
263
+ expect(errs).toHaveLength(0);
264
+ });
265
+ it('reports missing required field', () => {
266
+ const errs = validateToolArgs('read_file', {}, readFileSchema);
267
+ expect(errs.map(e => e.message).join(' ')).toContain('path');
268
+ });
269
+ it('reports type mismatch', () => {
270
+ const errs = validateToolArgs('read_file', { path: 'file.txt', offset: 'not-a-number' }, readFileSchema);
271
+ expect(errs.map(e => e.message).join(' ')).toContain('Expected number');
272
+ });
273
+ });