@myrialabs/clopen 0.2.24 → 0.3.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/README.md +1 -1
- package/backend/chat/helpers.ts +2 -20
- package/backend/chat/stream-manager.ts +556 -547
- package/backend/database/migrations/029_migrate_messages_to_unified.ts +1108 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/engine-queries.ts +195 -36
- package/backend/database/queries/index.ts +1 -2
- package/backend/database/queries/message-queries.ts +84 -139
- package/backend/database/queries/session-queries.ts +167 -21
- package/backend/database/queries/snapshot-queries.ts +5 -4
- package/backend/database/queries/utils-queries.ts +2 -2
- package/backend/engine/adapters/claude/environment.ts +4 -5
- package/backend/engine/adapters/claude/message-converter.ts +552 -0
- package/backend/engine/adapters/claude/stream.ts +59 -47
- package/backend/engine/adapters/opencode/config.ts +7 -7
- package/backend/engine/adapters/opencode/message-converter.ts +328 -352
- package/backend/engine/adapters/opencode/stream.ts +84 -101
- package/backend/engine/types.ts +17 -11
- package/backend/project/status-manager.ts +10 -13
- package/backend/snapshot/helpers.ts +46 -90
- package/backend/snapshot/snapshot-service.ts +1 -1
- package/backend/utils/paths.ts +22 -1
- package/backend/ws/chat/index.ts +1 -11
- package/backend/ws/chat/stream.ts +101 -61
- package/backend/ws/engine/claude/accounts.ts +27 -7
- package/backend/ws/engine/claude/status.ts +3 -2
- package/backend/ws/engine/opencode/providers.ts +25 -24
- package/backend/ws/git/commit-message.ts +6 -8
- package/backend/ws/messages/crud.ts +4 -59
- package/backend/ws/sessions/crud.ts +78 -130
- package/backend/ws/sessions/index.ts +1 -9
- package/backend/ws/settings/crud.ts +14 -11
- package/backend/ws/snapshot/restore.ts +23 -26
- package/backend/ws/snapshot/timeline.ts +5 -5
- package/dist/assets/{index-w7Uwi2Jz.js → index-BVWBZlgD.js} +2 -2
- package/dist/assets/main-Cgbs6dR7.js +246 -0
- package/dist/assets/main-TEa2MRnh.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +4 -4
- package/shared/constants/engines.ts +141 -56
- package/shared/types/database/schema.ts +39 -40
- package/shared/types/stores/settings.ts +8 -4
- package/shared/types/unified/common.ts +21 -0
- package/shared/types/unified/display.ts +25 -0
- package/shared/types/unified/engine.ts +61 -0
- package/shared/types/unified/index.ts +130 -0
- package/shared/types/unified/message.ts +151 -0
- package/shared/types/unified/stream.ts +157 -0
- package/shared/types/unified/tool.ts +409 -0
- package/shared/utils/message-formatter.ts +9 -73
- package/shared/utils/path.ts +3 -2
- package/tsconfig.json +1 -1
- package/backend/database/queries/opencode-provider-queries.ts +0 -190
- package/backend/engine/adapters/claude/path-utils.ts +0 -38
- package/backend/ws/chat/background.ts +0 -201
- package/dist/assets/main-B4q8wX9B.js +0 -257
- package/dist/assets/main-Bfz5Urp3.css +0 -1
- package/shared/types/engine/index.ts +0 -45
- package/shared/types/messaging/index.ts +0 -242
- package/shared/types/messaging/tool.ts +0 -374
|
@@ -1,80 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Message Formatter
|
|
2
|
+
* Message Formatter
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* Used by ALL paths that return messages to the frontend:
|
|
6
|
-
* - Backend: message-queries.ts, messages/crud.ts
|
|
7
|
-
* - Frontend: chat.service.ts (stream transport → metadata)
|
|
4
|
+
* loadMessage() — DB row → UnifiedMessage
|
|
8
5
|
*
|
|
9
|
-
*
|
|
6
|
+
* After migration 029, the JSON blob in message is the single source
|
|
7
|
+
* of truth. This function is a simple JSON.parse wrapper.
|
|
10
8
|
*/
|
|
11
9
|
|
|
12
|
-
import type { DatabaseMessage
|
|
13
|
-
import type {
|
|
10
|
+
import type { DatabaseMessage } from '$shared/types/database/schema';
|
|
11
|
+
import type { UnifiedMessage } from '$shared/types/unified';
|
|
14
12
|
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
*/
|
|
19
|
-
export function formatDatabaseMessage(
|
|
20
|
-
msg: DatabaseMessage,
|
|
21
|
-
overrides?: {
|
|
22
|
-
sender_id?: string | null;
|
|
23
|
-
sender_name?: string | null;
|
|
24
|
-
}
|
|
25
|
-
): SDKMessageFormatter {
|
|
26
|
-
const sdkMessage = JSON.parse(msg.sdk_message) as EngineSDKMessage;
|
|
27
|
-
|
|
28
|
-
return {
|
|
29
|
-
...sdkMessage,
|
|
30
|
-
metadata: {
|
|
31
|
-
...buildMetadataFromDb(msg, overrides),
|
|
32
|
-
...(sdkMessage.metadata?.reasoning && { reasoning: true }),
|
|
33
|
-
...(sdkMessage.metadata?.interrupted && { interrupted: true }),
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Build metadata object from DatabaseMessage fields
|
|
40
|
-
* This is the SINGLE definition of what metadata contains from DB
|
|
41
|
-
*/
|
|
42
|
-
export function buildMetadataFromDb(
|
|
43
|
-
msg: DatabaseMessage,
|
|
44
|
-
overrides?: {
|
|
45
|
-
sender_id?: string | null;
|
|
46
|
-
sender_name?: string | null;
|
|
47
|
-
}
|
|
48
|
-
): NonNullable<SDKMessageFormatter['metadata']> {
|
|
49
|
-
return {
|
|
50
|
-
message_id: msg.id,
|
|
51
|
-
created_at: msg.timestamp,
|
|
52
|
-
parent_message_id: msg.parent_message_id || null,
|
|
53
|
-
sender_id: overrides?.sender_id ?? msg.sender_id ?? null,
|
|
54
|
-
sender_name: overrides?.sender_name ?? msg.sender_name ?? null,
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Build metadata from stream transport fields (used by frontend during stream)
|
|
60
|
-
* Produces identical structure as buildMetadataFromDb
|
|
61
|
-
*/
|
|
62
|
-
export function buildMetadataFromTransport(transport: {
|
|
63
|
-
message_id?: string;
|
|
64
|
-
timestamp?: string;
|
|
65
|
-
parent_message_id?: string | null;
|
|
66
|
-
sender_id?: string | null;
|
|
67
|
-
sender_name?: string | null;
|
|
68
|
-
engine?: string;
|
|
69
|
-
reasoning?: boolean;
|
|
70
|
-
}): NonNullable<SDKMessageFormatter['metadata']> {
|
|
71
|
-
return {
|
|
72
|
-
message_id: transport.message_id || undefined,
|
|
73
|
-
created_at: transport.timestamp || new Date().toISOString(),
|
|
74
|
-
parent_message_id: transport.parent_message_id ?? null,
|
|
75
|
-
sender_id: transport.sender_id ?? null,
|
|
76
|
-
sender_name: transport.sender_name ?? null,
|
|
77
|
-
engine: transport.engine,
|
|
78
|
-
...(transport.reasoning && { reasoning: true }),
|
|
79
|
-
};
|
|
13
|
+
/** Parse a DatabaseMessage row into a UnifiedMessage. */
|
|
14
|
+
export function loadMessage(row: DatabaseMessage): UnifiedMessage {
|
|
15
|
+
return JSON.parse(row.data) as UnifiedMessage;
|
|
80
16
|
}
|
package/shared/utils/path.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Shared path
|
|
3
|
-
*
|
|
2
|
+
* Shared path utilities (browser-safe, no Node imports).
|
|
3
|
+
* - normalizePath / pathsEqual / getRelativePath: forward-slash display/comparison
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -45,3 +45,4 @@ export function getRelativePath(fullPath: string, basePath: string): string {
|
|
|
45
45
|
|
|
46
46
|
return normalizePath(fullPath);
|
|
47
47
|
}
|
|
48
|
+
|
package/tsconfig.json
CHANGED
|
@@ -1,190 +0,0 @@
|
|
|
1
|
-
import { getDatabase } from '../index';
|
|
2
|
-
|
|
3
|
-
export interface OpenCodeProvider {
|
|
4
|
-
id: number;
|
|
5
|
-
provider_id: string;
|
|
6
|
-
name: string;
|
|
7
|
-
npm: string;
|
|
8
|
-
api_url: string | null;
|
|
9
|
-
options: string;
|
|
10
|
-
is_enabled: number;
|
|
11
|
-
created_at: string;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export interface OpenCodeAccount {
|
|
15
|
-
id: number;
|
|
16
|
-
provider_id: number;
|
|
17
|
-
name: string;
|
|
18
|
-
api_key: string;
|
|
19
|
-
is_active: number;
|
|
20
|
-
created_at: string;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** Provider with its accounts joined */
|
|
24
|
-
export interface OpenCodeProviderWithAccounts extends OpenCodeProvider {
|
|
25
|
-
accounts: OpenCodeAccount[];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export const opencodeProviderQueries = {
|
|
29
|
-
// ========================================================================
|
|
30
|
-
// Providers
|
|
31
|
-
// ========================================================================
|
|
32
|
-
|
|
33
|
-
getProviders(): OpenCodeProvider[] {
|
|
34
|
-
const db = getDatabase();
|
|
35
|
-
return db.prepare(`
|
|
36
|
-
SELECT * FROM opencode_providers
|
|
37
|
-
ORDER BY created_at ASC
|
|
38
|
-
`).all() as OpenCodeProvider[];
|
|
39
|
-
},
|
|
40
|
-
|
|
41
|
-
getEnabledProviders(): OpenCodeProvider[] {
|
|
42
|
-
const db = getDatabase();
|
|
43
|
-
return db.prepare(`
|
|
44
|
-
SELECT * FROM opencode_providers
|
|
45
|
-
WHERE is_enabled = 1
|
|
46
|
-
ORDER BY created_at ASC
|
|
47
|
-
`).all() as OpenCodeProvider[];
|
|
48
|
-
},
|
|
49
|
-
|
|
50
|
-
getProvider(id: number): OpenCodeProvider | null {
|
|
51
|
-
const db = getDatabase();
|
|
52
|
-
return db.prepare(`
|
|
53
|
-
SELECT * FROM opencode_providers WHERE id = ?
|
|
54
|
-
`).get(id) as OpenCodeProvider | null;
|
|
55
|
-
},
|
|
56
|
-
|
|
57
|
-
getProviderByProviderId(providerId: string): OpenCodeProvider | null {
|
|
58
|
-
const db = getDatabase();
|
|
59
|
-
return db.prepare(`
|
|
60
|
-
SELECT * FROM opencode_providers WHERE provider_id = ?
|
|
61
|
-
`).get(providerId) as OpenCodeProvider | null;
|
|
62
|
-
},
|
|
63
|
-
|
|
64
|
-
createProvider(data: {
|
|
65
|
-
providerId: string;
|
|
66
|
-
name: string;
|
|
67
|
-
npm: string;
|
|
68
|
-
apiUrl?: string;
|
|
69
|
-
options?: string;
|
|
70
|
-
}): OpenCodeProvider {
|
|
71
|
-
const db = getDatabase();
|
|
72
|
-
db.prepare(`
|
|
73
|
-
INSERT INTO opencode_providers (provider_id, name, npm, api_url, options)
|
|
74
|
-
VALUES (?, ?, ?, ?, ?)
|
|
75
|
-
`).run(
|
|
76
|
-
data.providerId,
|
|
77
|
-
data.name,
|
|
78
|
-
data.npm,
|
|
79
|
-
data.apiUrl || null,
|
|
80
|
-
data.options || '{}'
|
|
81
|
-
);
|
|
82
|
-
|
|
83
|
-
const inserted = db.prepare('SELECT last_insert_rowid() as id').get() as { id: number };
|
|
84
|
-
return db.prepare('SELECT * FROM opencode_providers WHERE id = ?').get(inserted.id) as OpenCodeProvider;
|
|
85
|
-
},
|
|
86
|
-
|
|
87
|
-
updateProviderOptions(id: number, options: string): void {
|
|
88
|
-
const db = getDatabase();
|
|
89
|
-
db.prepare('UPDATE opencode_providers SET options = ? WHERE id = ?').run(options, id);
|
|
90
|
-
},
|
|
91
|
-
|
|
92
|
-
toggleProvider(id: number, enabled: boolean): void {
|
|
93
|
-
const db = getDatabase();
|
|
94
|
-
db.prepare('UPDATE opencode_providers SET is_enabled = ? WHERE id = ?').run(enabled ? 1 : 0, id);
|
|
95
|
-
},
|
|
96
|
-
|
|
97
|
-
deleteProvider(id: number): void {
|
|
98
|
-
const db = getDatabase();
|
|
99
|
-
// Accounts are cascade-deleted via FK constraint
|
|
100
|
-
db.prepare('DELETE FROM opencode_providers WHERE id = ?').run(id);
|
|
101
|
-
},
|
|
102
|
-
|
|
103
|
-
// ========================================================================
|
|
104
|
-
// Accounts
|
|
105
|
-
// ========================================================================
|
|
106
|
-
|
|
107
|
-
getAccountsByProvider(providerDbId: number): OpenCodeAccount[] {
|
|
108
|
-
const db = getDatabase();
|
|
109
|
-
return db.prepare(`
|
|
110
|
-
SELECT * FROM opencode_accounts
|
|
111
|
-
WHERE provider_id = ?
|
|
112
|
-
ORDER BY created_at ASC
|
|
113
|
-
`).all(providerDbId) as OpenCodeAccount[];
|
|
114
|
-
},
|
|
115
|
-
|
|
116
|
-
getActiveAccount(providerDbId: number): OpenCodeAccount | null {
|
|
117
|
-
const db = getDatabase();
|
|
118
|
-
return db.prepare(`
|
|
119
|
-
SELECT * FROM opencode_accounts
|
|
120
|
-
WHERE provider_id = ? AND is_active = 1
|
|
121
|
-
`).get(providerDbId) as OpenCodeAccount | null;
|
|
122
|
-
},
|
|
123
|
-
|
|
124
|
-
createAccount(providerDbId: number, name: string, apiKey: string): OpenCodeAccount {
|
|
125
|
-
const db = getDatabase();
|
|
126
|
-
|
|
127
|
-
// If first account for this provider, make it active
|
|
128
|
-
const count = (db.prepare(
|
|
129
|
-
'SELECT COUNT(*) as count FROM opencode_accounts WHERE provider_id = ?'
|
|
130
|
-
).get(providerDbId) as { count: number }).count;
|
|
131
|
-
const isActive = count === 0 ? 1 : 0;
|
|
132
|
-
|
|
133
|
-
db.prepare(`
|
|
134
|
-
INSERT INTO opencode_accounts (provider_id, name, api_key, is_active)
|
|
135
|
-
VALUES (?, ?, ?, ?)
|
|
136
|
-
`).run(providerDbId, name, apiKey, isActive);
|
|
137
|
-
|
|
138
|
-
const inserted = db.prepare('SELECT last_insert_rowid() as id').get() as { id: number };
|
|
139
|
-
return db.prepare('SELECT * FROM opencode_accounts WHERE id = ?').get(inserted.id) as OpenCodeAccount;
|
|
140
|
-
},
|
|
141
|
-
|
|
142
|
-
switchAccount(accountId: number): void {
|
|
143
|
-
const db = getDatabase();
|
|
144
|
-
|
|
145
|
-
// Get the provider_id for this account
|
|
146
|
-
const account = db.prepare('SELECT * FROM opencode_accounts WHERE id = ?').get(accountId) as OpenCodeAccount | null;
|
|
147
|
-
if (!account) return;
|
|
148
|
-
|
|
149
|
-
// Deactivate all accounts for this provider, then activate the target
|
|
150
|
-
db.prepare('UPDATE opencode_accounts SET is_active = 0 WHERE provider_id = ?').run(account.provider_id);
|
|
151
|
-
db.prepare('UPDATE opencode_accounts SET is_active = 1 WHERE id = ?').run(accountId);
|
|
152
|
-
},
|
|
153
|
-
|
|
154
|
-
deleteAccount(accountId: number): void {
|
|
155
|
-
const db = getDatabase();
|
|
156
|
-
|
|
157
|
-
const account = db.prepare('SELECT * FROM opencode_accounts WHERE id = ?').get(accountId) as OpenCodeAccount | null;
|
|
158
|
-
if (!account) return;
|
|
159
|
-
|
|
160
|
-
const wasActive = account.is_active === 1;
|
|
161
|
-
db.prepare('DELETE FROM opencode_accounts WHERE id = ?').run(accountId);
|
|
162
|
-
|
|
163
|
-
// If deleted account was active, activate first remaining account for this provider
|
|
164
|
-
if (wasActive) {
|
|
165
|
-
const remaining = db.prepare(
|
|
166
|
-
'SELECT id FROM opencode_accounts WHERE provider_id = ? ORDER BY created_at ASC LIMIT 1'
|
|
167
|
-
).get(account.provider_id) as { id: number } | null;
|
|
168
|
-
if (remaining) {
|
|
169
|
-
db.prepare('UPDATE opencode_accounts SET is_active = 1 WHERE id = ?').run(remaining.id);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
},
|
|
173
|
-
|
|
174
|
-
renameAccount(accountId: number, name: string): void {
|
|
175
|
-
const db = getDatabase();
|
|
176
|
-
db.prepare('UPDATE opencode_accounts SET name = ? WHERE id = ?').run(name, accountId);
|
|
177
|
-
},
|
|
178
|
-
|
|
179
|
-
// ========================================================================
|
|
180
|
-
// Composite: Providers with Accounts
|
|
181
|
-
// ========================================================================
|
|
182
|
-
|
|
183
|
-
getProvidersWithAccounts(): OpenCodeProviderWithAccounts[] {
|
|
184
|
-
const providers = this.getProviders();
|
|
185
|
-
return providers.map(p => ({
|
|
186
|
-
...p,
|
|
187
|
-
accounts: this.getAccountsByProvider(p.id)
|
|
188
|
-
}));
|
|
189
|
-
},
|
|
190
|
-
};
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { resolve } from 'path';
|
|
2
|
-
|
|
3
|
-
export function normalizePath(projectPath: string): string {
|
|
4
|
-
let normalizedProjectPath = projectPath;
|
|
5
|
-
|
|
6
|
-
if (process.platform === 'win32') {
|
|
7
|
-
if (!projectPath.match(/^[A-Za-z]:\\/)) {
|
|
8
|
-
if (projectPath.startsWith('\\')) {
|
|
9
|
-
const currentDrive = process.cwd().substring(0, 2);
|
|
10
|
-
normalizedProjectPath = currentDrive + projectPath;
|
|
11
|
-
} else {
|
|
12
|
-
normalizedProjectPath = resolve(projectPath);
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
normalizedProjectPath = normalizedProjectPath.replace(/\//g, '\\');
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
return normalizedProjectPath;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function changeWorkingDirectory(targetPath: string): string {
|
|
23
|
-
const originalCwd = process.cwd();
|
|
24
|
-
|
|
25
|
-
try {
|
|
26
|
-
process.chdir(targetPath);
|
|
27
|
-
return originalCwd;
|
|
28
|
-
} catch (error) {
|
|
29
|
-
throw new Error(`Cannot change working directory to ${targetPath}: ${error}`);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export function restoreWorkingDirectory(originalCwd: string): void {
|
|
34
|
-
try {
|
|
35
|
-
process.chdir(originalCwd);
|
|
36
|
-
} catch (error) {
|
|
37
|
-
}
|
|
38
|
-
}
|
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Chat Background Streaming
|
|
3
|
-
*
|
|
4
|
-
* Handles background chat streaming that continues even when browser is closed.
|
|
5
|
-
* Provides HTTP endpoints for stream management and polling.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { t } from 'elysia';
|
|
9
|
-
import { createRouter } from '$shared/utils/ws-server';
|
|
10
|
-
import { streamManager } from '../../chat/stream-manager';
|
|
11
|
-
import { debug } from '$shared/utils/logger';
|
|
12
|
-
import { ws } from '$backend/utils/ws';
|
|
13
|
-
|
|
14
|
-
export const backgroundHandler = createRouter()
|
|
15
|
-
// Start background stream (fire-and-forget)
|
|
16
|
-
.on('chat:background-start', {
|
|
17
|
-
data: t.Object({
|
|
18
|
-
prompt: t.Any(), // SDKUserMessage object
|
|
19
|
-
chatSessionId: t.String(),
|
|
20
|
-
projectPath: t.Optional(t.String()),
|
|
21
|
-
messages: t.Optional(t.Array(t.Any())),
|
|
22
|
-
model: t.Optional(t.String()),
|
|
23
|
-
temperature: t.Optional(t.Number()),
|
|
24
|
-
senderId: t.Optional(t.String()),
|
|
25
|
-
senderName: t.Optional(t.String())
|
|
26
|
-
})
|
|
27
|
-
}, async ({ data, conn }) => {
|
|
28
|
-
const projectId = ws.getProjectId(conn);
|
|
29
|
-
|
|
30
|
-
try {
|
|
31
|
-
debug.log('chat', 'WS chat:background-start received:', {
|
|
32
|
-
chatSessionId: data.chatSessionId,
|
|
33
|
-
projectId,
|
|
34
|
-
messagesCount: data.messages?.length || 0
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
// Start background stream
|
|
38
|
-
const streamId = await streamManager.startStream({
|
|
39
|
-
projectPath: data.projectPath || '',
|
|
40
|
-
projectId,
|
|
41
|
-
prompt: data.prompt,
|
|
42
|
-
messages: data.messages || [],
|
|
43
|
-
chatSessionId: data.chatSessionId,
|
|
44
|
-
model: data.model,
|
|
45
|
-
temperature: data.temperature,
|
|
46
|
-
senderId: data.senderId,
|
|
47
|
-
senderName: data.senderName
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
debug.log('chat', 'Background stream started with ID:', streamId);
|
|
51
|
-
|
|
52
|
-
// Broadcast to all users in project (collaborative)
|
|
53
|
-
ws.emit.project(projectId, 'chat:background-started', {
|
|
54
|
-
streamId,
|
|
55
|
-
status: 'started'
|
|
56
|
-
});
|
|
57
|
-
} catch (error) {
|
|
58
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
59
|
-
debug.error('chat', 'WS chat:background-start error:', errorMessage);
|
|
60
|
-
|
|
61
|
-
ws.emit.project(projectId, 'chat:background-error', {
|
|
62
|
-
error: errorMessage
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
})
|
|
66
|
-
|
|
67
|
-
// Get background stream state (HTTP pattern for request-response)
|
|
68
|
-
.http('chat:background-state', {
|
|
69
|
-
data: t.Object({
|
|
70
|
-
streamId: t.Optional(t.String()),
|
|
71
|
-
chatSessionId: t.Optional(t.String()),
|
|
72
|
-
offset: t.Optional(t.Number())
|
|
73
|
-
}),
|
|
74
|
-
response: t.Object({
|
|
75
|
-
streamId: t.String(),
|
|
76
|
-
status: t.Union([
|
|
77
|
-
t.Literal('active'),
|
|
78
|
-
t.Literal('completed'),
|
|
79
|
-
t.Literal('error'),
|
|
80
|
-
t.Literal('cancelled')
|
|
81
|
-
]),
|
|
82
|
-
processId: t.String(),
|
|
83
|
-
messages: t.Array(t.Any()),
|
|
84
|
-
currentPartialText: t.Optional(t.String()),
|
|
85
|
-
currentReasoningText: t.Optional(t.String()),
|
|
86
|
-
error: t.Optional(t.String()),
|
|
87
|
-
startedAt: t.String(),
|
|
88
|
-
completedAt: t.Optional(t.String())
|
|
89
|
-
})
|
|
90
|
-
}, async ({ data, conn }) => {
|
|
91
|
-
const projectId = ws.getProjectId(conn);
|
|
92
|
-
|
|
93
|
-
// Find stream by ID or session
|
|
94
|
-
let streamState;
|
|
95
|
-
if (data.streamId) {
|
|
96
|
-
streamState = streamManager.getStream(data.streamId);
|
|
97
|
-
} else if (data.chatSessionId) {
|
|
98
|
-
streamState = streamManager.getSessionStream(data.chatSessionId, projectId);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Return a "not found" response instead of throwing
|
|
102
|
-
// This happens normally when a stream was cancelled/completed and cleaned up
|
|
103
|
-
if (!streamState) {
|
|
104
|
-
return {
|
|
105
|
-
streamId: data.streamId || data.chatSessionId || '',
|
|
106
|
-
status: 'completed' as const,
|
|
107
|
-
processId: '',
|
|
108
|
-
messages: [],
|
|
109
|
-
currentPartialText: undefined,
|
|
110
|
-
currentReasoningText: undefined,
|
|
111
|
-
error: undefined,
|
|
112
|
-
startedAt: new Date().toISOString(),
|
|
113
|
-
completedAt: new Date().toISOString()
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// Get messages from offset
|
|
118
|
-
const offset = data.offset || 0;
|
|
119
|
-
const messages = streamState.messages.slice(offset);
|
|
120
|
-
|
|
121
|
-
return {
|
|
122
|
-
streamId: streamState.streamId,
|
|
123
|
-
status: streamState.status,
|
|
124
|
-
processId: streamState.processId,
|
|
125
|
-
messages,
|
|
126
|
-
currentPartialText: streamState.currentPartialText,
|
|
127
|
-
currentReasoningText: streamState.currentReasoningText,
|
|
128
|
-
error: streamState.error,
|
|
129
|
-
startedAt: streamState.startedAt.toISOString(),
|
|
130
|
-
completedAt: streamState.completedAt?.toISOString()
|
|
131
|
-
};
|
|
132
|
-
})
|
|
133
|
-
|
|
134
|
-
// Get background stream messages (HTTP pattern for request-response)
|
|
135
|
-
.http('chat:background-messages', {
|
|
136
|
-
data: t.Object({
|
|
137
|
-
streamId: t.Optional(t.String()),
|
|
138
|
-
chatSessionId: t.Optional(t.String()),
|
|
139
|
-
offset: t.Optional(t.Number())
|
|
140
|
-
}),
|
|
141
|
-
response: t.Object({
|
|
142
|
-
messages: t.Array(t.Any()),
|
|
143
|
-
hasMore: t.Boolean(),
|
|
144
|
-
status: t.String()
|
|
145
|
-
})
|
|
146
|
-
}, async ({ data, conn }) => {
|
|
147
|
-
const projectId = ws.getProjectId(conn);
|
|
148
|
-
|
|
149
|
-
// Find stream by ID or session
|
|
150
|
-
let streamState;
|
|
151
|
-
if (data.streamId) {
|
|
152
|
-
streamState = streamManager.getStream(data.streamId);
|
|
153
|
-
} else if (data.chatSessionId) {
|
|
154
|
-
streamState = streamManager.getSessionStream(data.chatSessionId, projectId);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
if (!streamState) {
|
|
158
|
-
throw new Error('Stream not found');
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// Get messages from offset
|
|
162
|
-
const offset = data.offset || 0;
|
|
163
|
-
const messages = streamState.messages.slice(offset);
|
|
164
|
-
const hasMore = streamState.status === 'active';
|
|
165
|
-
|
|
166
|
-
return {
|
|
167
|
-
messages,
|
|
168
|
-
hasMore,
|
|
169
|
-
status: streamState.status
|
|
170
|
-
};
|
|
171
|
-
})
|
|
172
|
-
|
|
173
|
-
// Cancel background stream (HTTP pattern for request-response)
|
|
174
|
-
.http('chat:background-cancel', {
|
|
175
|
-
data: t.Object({
|
|
176
|
-
streamId: t.String()
|
|
177
|
-
}),
|
|
178
|
-
response: t.Object({
|
|
179
|
-
status: t.Literal('cancelled')
|
|
180
|
-
})
|
|
181
|
-
}, async ({ data }) => {
|
|
182
|
-
const cancelled = await streamManager.cancelStream(data.streamId);
|
|
183
|
-
|
|
184
|
-
if (!cancelled) {
|
|
185
|
-
throw new Error('Stream not found or already completed');
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
return {
|
|
189
|
-
status: 'cancelled' as const
|
|
190
|
-
};
|
|
191
|
-
})
|
|
192
|
-
|
|
193
|
-
// Event declarations (only for fire-and-forget actions)
|
|
194
|
-
.emit('chat:background-started', t.Object({
|
|
195
|
-
streamId: t.String(),
|
|
196
|
-
status: t.Literal('started')
|
|
197
|
-
}))
|
|
198
|
-
|
|
199
|
-
.emit('chat:background-error', t.Object({
|
|
200
|
-
error: t.String()
|
|
201
|
-
}));
|