@ptkl/toolkit 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -30
- package/dist/bin/toolkit.js +37 -3
- package/dist/commands/__tests__/apiUsers.test.js +16 -0
- package/dist/commands/__tests__/forge-requires.test.js +58 -0
- package/dist/commands/__tests__/profile.test.js +65 -0
- package/dist/commands/apiUsers.js +12 -0
- package/dist/commands/forge.js +82 -6
- package/dist/commands/profile.js +84 -76
- 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/dist/lib/oauth/CallbackPages.js +82 -0
- package/dist/lib/oauth/CallbackServer.js +84 -0
- package/dist/lib/oauth/OAuthClient.js +81 -0
- package/dist/lib/oauth/OAuthError.js +17 -0
- package/dist/lib/oauth/OAuthLogin.js +60 -0
- package/dist/lib/oauth/OAuthSession.js +100 -0
- package/dist/lib/oauth/Pkce.js +19 -0
- package/dist/lib/oauth/ProfileLogin.js +76 -0
- package/dist/lib/oauth/RefreshLock.js +61 -0
- package/dist/lib/oauth/ScopePreset.js +38 -0
- package/dist/lib/oauth/__tests__/mockServer.js +29 -0
- package/dist/lib/oauth/__tests__/oauth.test.js +347 -0
- package/dist/lib/util.js +9 -2
- package/package.json +6 -4
package/dist/commands/profile.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
2
|
import util from "../lib/util.js";
|
|
3
3
|
import cli from "../lib/cli.js";
|
|
4
|
-
import { APIUser, Users as User } from "@ptkl/sdk";
|
|
5
4
|
import password from '@inquirer/password';
|
|
5
|
+
import ProfileLogin from "../lib/oauth/ProfileLogin.js";
|
|
6
|
+
import OAuthSession from "../lib/oauth/OAuthSession.js";
|
|
6
7
|
class ProfileCommand {
|
|
7
8
|
register() {
|
|
8
9
|
return new Command('profile')
|
|
@@ -10,19 +11,37 @@ class ProfileCommand {
|
|
|
10
11
|
.version('0.1.0')
|
|
11
12
|
.action(this.action)
|
|
12
13
|
.addCommand(new Command('new')
|
|
13
|
-
.description('Create new profile')
|
|
14
|
+
.description('Create new profile (OAuth browser login by default; --legacy for an API user)')
|
|
14
15
|
.option("-n, --name <name>")
|
|
15
|
-
.option("-u, --username <username>")
|
|
16
|
-
.option("-p, --password [
|
|
16
|
+
.option("-u, --username <username>", "API-user username (with --legacy)")
|
|
17
|
+
.option("-p, --password [secret]", "API-user secret (with --legacy; prompted if omitted)")
|
|
17
18
|
.option("-P, --project <project>")
|
|
18
19
|
.option("-h, --host <host>")
|
|
20
|
+
.option("--legacy", "Use API-user credentials (username + secret) instead of OAuth (implied by -u, -p, -t)")
|
|
21
|
+
.option("--client-id <id>", "OAuth client id (default: stored, $PTKL_OAUTH_CLIENT_ID, or the built-in CLI client)")
|
|
22
|
+
.option("--scope <list>", "Comma-separated permissions (or pattern:<regex>) replacing the OAuth preset")
|
|
23
|
+
.option("--add-scope <list>", "Comma-separated permissions (or pattern:<regex>) added to the OAuth preset")
|
|
24
|
+
.option("--port <port>", "OAuth loopback callback port (default: random free port)")
|
|
25
|
+
.option("--no-browser", "Print the OAuth URL instead of opening a browser")
|
|
19
26
|
.action(this.new))
|
|
20
27
|
.addCommand(new Command('auth')
|
|
21
|
-
.description('Profile auth')
|
|
22
|
-
.
|
|
28
|
+
.description('Profile auth (OAuth browser login by default; --legacy for an API user or token)')
|
|
29
|
+
.argument('[name]', 'Profile name (default: active profile)')
|
|
30
|
+
.option("-u, --username <username>", "API-user username (with --legacy)")
|
|
31
|
+
.option("-p, --password [secret]", "API-user secret (with --legacy; prompted if omitted)")
|
|
23
32
|
.option("-t, --token <token>")
|
|
24
33
|
.option("-P, --project <project>")
|
|
34
|
+
.option("--legacy", "Use API-user credentials (username + secret) instead of OAuth (implied by -u, -p, -t)")
|
|
35
|
+
.option("--client-id <id>", "OAuth client id (default: stored, $PTKL_OAUTH_CLIENT_ID, or the built-in CLI client)")
|
|
36
|
+
.option("--scope <list>", "Comma-separated permissions (or pattern:<regex>) replacing the OAuth preset")
|
|
37
|
+
.option("--add-scope <list>", "Comma-separated permissions (or pattern:<regex>) added to the OAuth preset")
|
|
38
|
+
.option("--port <port>", "OAuth loopback callback port (default: random free port)")
|
|
39
|
+
.option("--no-browser", "Print the OAuth URL instead of opening a browser")
|
|
25
40
|
.action(this.auth))
|
|
41
|
+
.addCommand(new Command('logout')
|
|
42
|
+
.description('Revoke the OAuth refresh token and clear stored tokens')
|
|
43
|
+
.argument('[name]', 'Profile name (default: active profile)')
|
|
44
|
+
.action(this.logout))
|
|
26
45
|
.addCommand(new Command('list')
|
|
27
46
|
.description('List all available profiles')
|
|
28
47
|
.action(this.list))
|
|
@@ -39,6 +58,14 @@ class ProfileCommand {
|
|
|
39
58
|
.argument('<name>')
|
|
40
59
|
.action(this.inspect));
|
|
41
60
|
}
|
|
61
|
+
/** The API-user secret: the flag value (with a warning) or a secure prompt. */
|
|
62
|
+
static async secret(flag) {
|
|
63
|
+
if (typeof flag === 'string' && flag.length > 0) {
|
|
64
|
+
console.warn('WARNING: a secret passed on the command line may be visible in shell history; use -p without a value to be prompted.');
|
|
65
|
+
return flag;
|
|
66
|
+
}
|
|
67
|
+
return password({ message: 'Enter API-user secret:' });
|
|
68
|
+
}
|
|
42
69
|
action() {
|
|
43
70
|
const currentProfile = util.getCurrentProfile();
|
|
44
71
|
cli.write(currentProfile?.name ?? "profile not selected");
|
|
@@ -46,40 +73,22 @@ class ProfileCommand {
|
|
|
46
73
|
async new(options) {
|
|
47
74
|
// try to find profile with the name
|
|
48
75
|
const { name, username, project, host } = options;
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
console.warn('⚠️ WARNING: Providing password via CLI argument is insecure and may be visible in shell history.');
|
|
54
|
-
console.warn('⚠️ Consider using --password flag without a value to be prompted securely.\n');
|
|
55
|
-
}
|
|
56
|
-
else {
|
|
57
|
-
// Prompt for password securely (either --password flag was used without value, or not provided at all)
|
|
58
|
-
userPassword = await password({
|
|
59
|
-
message: 'Enter password:',
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
let token = "";
|
|
63
|
-
// if username is email then login to platform as user
|
|
64
|
-
if (username && username.includes('@')) {
|
|
65
|
-
const user = new User({
|
|
66
|
-
host,
|
|
67
|
-
});
|
|
68
|
-
try {
|
|
69
|
-
const { data } = await user.auth(username, userPassword, project);
|
|
70
|
-
token = "SESSION:" + data.token;
|
|
76
|
+
if (!ProfileLogin.useLegacy(options)) {
|
|
77
|
+
for (const [flag, v] of [["--name", name], ["--host", host], ["--project", project]]) {
|
|
78
|
+
if (!v)
|
|
79
|
+
throw new Error(`${flag} is required`);
|
|
71
80
|
}
|
|
72
|
-
|
|
73
|
-
throw
|
|
81
|
+
if ((util.getProfiles() ?? []).some((p) => p.name == name)) {
|
|
82
|
+
throw new Error(`Profile with ${name} already exist`);
|
|
74
83
|
}
|
|
84
|
+
await ProfileLogin.login({ name, host, project }, options, (l) => cli.write(l));
|
|
85
|
+
cli.write(`Logged in. Profile '${name}' saved.`);
|
|
86
|
+
return;
|
|
75
87
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const { data } = await user.auth(username, userPassword, project);
|
|
81
|
-
token = data.Token;
|
|
82
|
-
}
|
|
88
|
+
if (!username)
|
|
89
|
+
throw new Error("--username (API-user username) is required with --legacy");
|
|
90
|
+
const secret = await ProfileCommand.secret(options.password);
|
|
91
|
+
const token = await ProfileLogin.apiUserToken(host, username, secret, project);
|
|
83
92
|
const profiles = util.getProfiles() ?? [];
|
|
84
93
|
// try to find that the profile with the name already exist
|
|
85
94
|
const profile = profiles.find((p) => p.name == name);
|
|
@@ -95,47 +104,46 @@ class ProfileCommand {
|
|
|
95
104
|
});
|
|
96
105
|
util.updateProfiles(profiles);
|
|
97
106
|
}
|
|
98
|
-
async auth(options) {
|
|
99
|
-
|
|
107
|
+
async auth(name, options) {
|
|
108
|
+
const profile = name
|
|
109
|
+
? (util.getProfiles() ?? []).find((p) => p.name == name)
|
|
110
|
+
: util.getCurrentProfile();
|
|
111
|
+
if (!profile)
|
|
112
|
+
throw new Error(`Profile with ${name} doesn't exist`);
|
|
113
|
+
if (!ProfileLogin.useLegacy(options)) {
|
|
114
|
+
const project = options.project ?? profile.project;
|
|
115
|
+
if (!project)
|
|
116
|
+
throw new Error("--project is required");
|
|
117
|
+
await ProfileLogin.login({ name: profile.name, host: profile.host, project }, options, (l) => cli.write(l));
|
|
118
|
+
cli.write(`Logged in. Profile '${profile.name}' updated.`);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
100
121
|
let { token, project } = options;
|
|
101
|
-
|
|
102
|
-
const profile = util.getCurrentProfile();
|
|
122
|
+
const username = ProfileLogin.legacyUsername(profile, options.username);
|
|
103
123
|
if (!token) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
throw error;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
else {
|
|
129
|
-
const user = new APIUser({
|
|
130
|
-
host: profile.host,
|
|
131
|
-
});
|
|
132
|
-
const { data } = await user.auth(profile.username, userPassword, project ?? profile.project);
|
|
133
|
-
token = data.Token;
|
|
134
|
-
}
|
|
124
|
+
if (!username)
|
|
125
|
+
throw new Error("No username for this profile; pass -u <API-user username>");
|
|
126
|
+
const secret = await ProfileCommand.secret(options.password);
|
|
127
|
+
token = await ProfileLogin.apiUserToken(profile.host, username, secret, project ?? profile.project);
|
|
128
|
+
}
|
|
129
|
+
util.updateProfile({
|
|
130
|
+
...ProfileLogin.toLegacy(profile, { username, token }),
|
|
131
|
+
project: project ?? profile.project,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
async logout(name) {
|
|
135
|
+
const profile = name
|
|
136
|
+
? (util.getProfiles() ?? []).find((p) => p.name == name)
|
|
137
|
+
: util.getCurrentProfile();
|
|
138
|
+
if (!profile)
|
|
139
|
+
throw new Error(`Profile with ${name} doesn't exist`);
|
|
140
|
+
if (OAuthSession.isOAuth(profile)) {
|
|
141
|
+
await new OAuthSession().logout(profile);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
util.updateProfile({ ...profile, token: "" });
|
|
135
145
|
}
|
|
136
|
-
|
|
137
|
-
profile.token = token;
|
|
138
|
-
util.updateProfile(profile);
|
|
146
|
+
cli.write(`Logged out of '${profile.name}'.`);
|
|
139
147
|
}
|
|
140
148
|
list() {
|
|
141
149
|
const profiles = util.getProfiles() ?? [];
|
|
@@ -171,7 +179,7 @@ class ProfileCommand {
|
|
|
171
179
|
let profiles = util.getProfiles() ?? [];
|
|
172
180
|
// try to find that the profile with the name already exist
|
|
173
181
|
const profile = profiles.find((p) => p.name == name);
|
|
174
|
-
console.log(profile);
|
|
182
|
+
console.log(profile && OAuthSession.masked(profile));
|
|
175
183
|
}
|
|
176
184
|
}
|
|
177
185
|
export default new ProfileCommand;
|
|
@@ -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
|
+
});
|