@myrialabs/clopen 0.3.0 → 0.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/backend/engine/adapters/claude/message-converter.ts +76 -25
- package/backend/engine/adapters/claude/stream.ts +8 -1
- package/backend/engine/adapters/opencode/message-converter.ts +85 -49
- package/dist/assets/{index-B95VOHJY.js → index-7DYhZPkW.js} +2 -2
- package/dist/assets/{main-D1QNkcRL.js → main-8urnNoR7.js} +158 -169
- package/dist/assets/main-TEa2MRnh.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +4 -4
- package/shared/constants/engines.ts +2 -2
- package/shared/types/unified/index.ts +22 -0
- package/shared/types/unified/tool.ts +147 -6
- package/dist/assets/main-rtLiuU_x.css +0 -1
|
@@ -19,8 +19,10 @@ import type {
|
|
|
19
19
|
SDKCompactBoundaryMessage,
|
|
20
20
|
SDKRateLimitEvent,
|
|
21
21
|
} from '@anthropic-ai/claude-agent-sdk';
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
// Infer block/usage types from the agent SDK so we stay in sync with whichever
|
|
23
|
+
// @anthropic-ai/sdk version claude-agent-sdk bundles internally.
|
|
24
|
+
type BetaContentBlock = SDKAssistantMessage['message']['content'][number];
|
|
25
|
+
type BetaUsage = SDKAssistantMessage['message']['usage'];
|
|
24
26
|
import type {
|
|
25
27
|
EngineOutput,
|
|
26
28
|
UserMessage,
|
|
@@ -39,6 +41,7 @@ import type {
|
|
|
39
41
|
TokenUsage,
|
|
40
42
|
StopReason,
|
|
41
43
|
} from '$shared/types/unified';
|
|
44
|
+
import { toCanonicalToolName } from '$shared/types/unified';
|
|
42
45
|
|
|
43
46
|
// ============================================================
|
|
44
47
|
// Helper Mappers
|
|
@@ -124,11 +127,12 @@ export function mapAssistantContent(sdkContent: BetaContentBlock[]): AssistantCo
|
|
|
124
127
|
case 'text':
|
|
125
128
|
blocks.push({ type: 'text', text: block.text });
|
|
126
129
|
break;
|
|
127
|
-
case 'tool_use':
|
|
130
|
+
case 'tool_use': {
|
|
131
|
+
const rawName = block.name === 'Task' ? 'Agent' : block.name;
|
|
128
132
|
blocks.push({
|
|
129
133
|
type: 'tool_use',
|
|
130
134
|
id: block.id,
|
|
131
|
-
name:
|
|
135
|
+
name: toCanonicalToolName(rawName),
|
|
132
136
|
input: convertToolInput(block.name, block.input as Record<string, unknown>),
|
|
133
137
|
result: null,
|
|
134
138
|
subActivities: [],
|
|
@@ -136,6 +140,7 @@ export function mapAssistantContent(sdkContent: BetaContentBlock[]): AssistantCo
|
|
|
136
140
|
interrupted: false,
|
|
137
141
|
} as ToolUseBlock);
|
|
138
142
|
break;
|
|
143
|
+
}
|
|
139
144
|
}
|
|
140
145
|
}
|
|
141
146
|
return blocks;
|
|
@@ -196,22 +201,28 @@ export function convertAssistantMessage(msg: SDKAssistantMessage): EngineOutput[
|
|
|
196
201
|
const content = betaMessage.content;
|
|
197
202
|
const outputs: EngineOutput[] = [];
|
|
198
203
|
|
|
199
|
-
// Extract thinking blocks → ReasoningMessage
|
|
204
|
+
// Extract thinking blocks → ReasoningMessage. Skip emission when all
|
|
205
|
+
// thinking blocks are empty (e.g. when adaptive thinking is in 'omitted'
|
|
206
|
+
// mode and only signatures arrive); otherwise we'd persist a blank
|
|
207
|
+
// reasoning entry that confuses the UI.
|
|
200
208
|
const thinkingBlocks = content.filter(b => b.type === 'thinking');
|
|
201
209
|
if (thinkingBlocks.length > 0) {
|
|
202
210
|
const reasoningText = thinkingBlocks
|
|
203
211
|
.map(b => b.type === 'thinking' ? b.thinking : '')
|
|
204
|
-
.join('\n')
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
212
|
+
.join('\n')
|
|
213
|
+
.trim();
|
|
214
|
+
if (reasoningText) {
|
|
215
|
+
const reasoning: ReasoningMessage = {
|
|
216
|
+
type: 'reasoning',
|
|
217
|
+
createdAt: new Date().toISOString(),
|
|
218
|
+
messageId: crypto.randomUUID(),
|
|
219
|
+
sessionId,
|
|
220
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
221
|
+
engine: { type: 'claude-code', provider: 'anthropic', model: { id: betaMessage.model || '', name: '' }, account: { id: 0, name: '' } },
|
|
222
|
+
text: reasoningText,
|
|
223
|
+
};
|
|
224
|
+
outputs.push(reasoning);
|
|
225
|
+
}
|
|
215
226
|
}
|
|
216
227
|
|
|
217
228
|
// Build AssistantMessage with non-thinking content
|
|
@@ -254,8 +265,26 @@ export function convertUserMessage(msg: SDKUserMessage): UserMessage {
|
|
|
254
265
|
};
|
|
255
266
|
}
|
|
256
267
|
|
|
268
|
+
/**
|
|
269
|
+
* Stateful per-stream tracking. The SDK emits content_block_stop without a
|
|
270
|
+
* content_block payload, so we must remember which block indices belong to
|
|
271
|
+
* thinking blocks to emit the correct `reasoning` flag on stop. A Map per
|
|
272
|
+
* converter instance keeps state isolated between concurrent queries.
|
|
273
|
+
*/
|
|
274
|
+
export interface StreamConverterState {
|
|
275
|
+
/** index → true when the block is a thinking block */
|
|
276
|
+
reasoningBlocks: Map<number, boolean>;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export function createStreamConverterState(): StreamConverterState {
|
|
280
|
+
return { reasoningBlocks: new Map() };
|
|
281
|
+
}
|
|
282
|
+
|
|
257
283
|
/** Convert SDKPartialAssistantMessage (stream_event) → TextDeltaEvent | StreamLifecycleEvent */
|
|
258
|
-
export function convertStreamEvent(
|
|
284
|
+
export function convertStreamEvent(
|
|
285
|
+
msg: SDKPartialAssistantMessage,
|
|
286
|
+
state: StreamConverterState,
|
|
287
|
+
): EngineOutput[] {
|
|
259
288
|
const sessionId = msg.session_id;
|
|
260
289
|
const event = msg.event;
|
|
261
290
|
const outputs: EngineOutput[] = [];
|
|
@@ -275,7 +304,9 @@ export function convertStreamEvent(msg: SDKPartialAssistantMessage): EngineOutpu
|
|
|
275
304
|
|
|
276
305
|
case 'content_block_start': {
|
|
277
306
|
const blockType = event.content_block.type;
|
|
278
|
-
|
|
307
|
+
const isReasoning = blockType === 'thinking' || blockType === 'redacted_thinking';
|
|
308
|
+
state.reasoningBlocks.set(event.index, isReasoning);
|
|
309
|
+
if (isReasoning) {
|
|
279
310
|
outputs.push({ type: 'stream_event', event: 'start', sessionId, reasoning: true } as StreamLifecycleEvent);
|
|
280
311
|
} else if (blockType === 'text') {
|
|
281
312
|
outputs.push({ type: 'stream_event', event: 'start', sessionId, reasoning: false } as StreamLifecycleEvent);
|
|
@@ -308,7 +339,9 @@ export function convertStreamEvent(msg: SDKPartialAssistantMessage): EngineOutpu
|
|
|
308
339
|
}
|
|
309
340
|
|
|
310
341
|
case 'content_block_stop': {
|
|
311
|
-
|
|
342
|
+
const isReasoning = state.reasoningBlocks.get(event.index) === true;
|
|
343
|
+
state.reasoningBlocks.delete(event.index);
|
|
344
|
+
outputs.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: isReasoning } as StreamLifecycleEvent);
|
|
312
345
|
break;
|
|
313
346
|
}
|
|
314
347
|
}
|
|
@@ -389,14 +422,32 @@ export function convertRateLimit(msg: SDKRateLimitEvent): RateLimitEvent | null
|
|
|
389
422
|
// ============================================================
|
|
390
423
|
|
|
391
424
|
/**
|
|
392
|
-
*
|
|
425
|
+
* Create a stateful per-stream SDK message converter.
|
|
426
|
+
*
|
|
427
|
+
* Returns a generator function that converts a single SDKMessage into zero or
|
|
428
|
+
* more EngineOutput events. The closure tracks per-block reasoning state so
|
|
429
|
+
* `content_block_stop` events can carry the correct `reasoning` flag (the SDK
|
|
430
|
+
* does not include the block payload on stop).
|
|
393
431
|
*
|
|
394
|
-
*
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
432
|
+
* Use one converter per query; do not share across concurrent streams.
|
|
433
|
+
*/
|
|
434
|
+
export function createSdkMessageConverter(): (msg: SDKMessage) => Generator<EngineOutput> {
|
|
435
|
+
const state = createStreamConverterState();
|
|
436
|
+
return function* convertSdkMessage(msg: SDKMessage): Generator<EngineOutput> {
|
|
437
|
+
yield* dispatchSdkMessage(msg, state);
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Stateless dispatcher kept for backwards compatibility. Allocates a fresh
|
|
443
|
+
* state on every call, so block-stop reasoning tracking only works within a
|
|
444
|
+
* single SDK message. Prefer `createSdkMessageConverter()` for streaming.
|
|
398
445
|
*/
|
|
399
446
|
export function* convertSdkMessage(msg: SDKMessage): Generator<EngineOutput> {
|
|
447
|
+
yield* dispatchSdkMessage(msg, createStreamConverterState());
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Generator<EngineOutput> {
|
|
400
451
|
switch (msg.type) {
|
|
401
452
|
case 'assistant':
|
|
402
453
|
for (const output of convertAssistantMessage(msg as SDKAssistantMessage)) {
|
|
@@ -410,7 +461,7 @@ export function* convertSdkMessage(msg: SDKMessage): Generator<EngineOutput> {
|
|
|
410
461
|
break;
|
|
411
462
|
|
|
412
463
|
case 'stream_event':
|
|
413
|
-
for (const output of convertStreamEvent(msg as SDKPartialAssistantMessage)) {
|
|
464
|
+
for (const output of convertStreamEvent(msg as SDKPartialAssistantMessage, state)) {
|
|
414
465
|
yield output;
|
|
415
466
|
}
|
|
416
467
|
break;
|
|
@@ -22,7 +22,7 @@ import type {
|
|
|
22
22
|
} from '@anthropic-ai/claude-agent-sdk';
|
|
23
23
|
import type { EngineOutput } from '$shared/types/unified';
|
|
24
24
|
import type { StructuredGenerationOptions } from '../../types';
|
|
25
|
-
import {
|
|
25
|
+
import { createSdkMessageConverter, toSdkUserMessage } from './message-converter';
|
|
26
26
|
import { resolveOsPath } from '$backend/utils/paths';
|
|
27
27
|
import { setupEnvironmentOnce, getEngineEnv } from './environment';
|
|
28
28
|
import { handleStreamError } from './error-handler';
|
|
@@ -119,6 +119,10 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
119
119
|
systemPrompt: { type: "preset", preset: "claude_code" },
|
|
120
120
|
settingSources: ["user", "project", "local"],
|
|
121
121
|
forkSession: true,
|
|
122
|
+
// Explicit adaptive thinking with summarized display so Opus 4.6+ emits
|
|
123
|
+
// visible thinking_delta events; without this the SDK can default to
|
|
124
|
+
// 'omitted' and reasoning blocks arrive empty.
|
|
125
|
+
thinking: { type: 'adaptive', display: 'summarized' },
|
|
122
126
|
// Custom permission handler: blocks on AskUserQuestion until user answers,
|
|
123
127
|
// auto-allows everything else. Works alongside bypassPermissions.
|
|
124
128
|
canUseTool: async (_toolName, input, canUseToolOptions) => {
|
|
@@ -173,6 +177,9 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
173
177
|
|
|
174
178
|
this.activeQuery = queryInstance;
|
|
175
179
|
|
|
180
|
+
// Per-query stateful converter so block-stop reasoning tracking persists
|
|
181
|
+
// across the stream of SDK messages.
|
|
182
|
+
const convertSdkMessage = createSdkMessageConverter();
|
|
176
183
|
for await (const sdkMessage of queryInstance) {
|
|
177
184
|
// Convert SDK message → EngineOutput (may yield 0-N events per SDK message)
|
|
178
185
|
yield* convertSdkMessage(sdkMessage);
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { resolveOpenCodeToolName } from '../../../mcp';
|
|
13
|
+
import { toCanonicalToolName } from '$shared/types/unified';
|
|
13
14
|
import type { Message as OCMessage, Part, ToolPart, AssistantMessage } from '@opencode-ai/sdk';
|
|
14
15
|
import type {
|
|
15
16
|
EngineOutput,
|
|
@@ -134,14 +135,15 @@ const TOOL_NAME_MAP: Record<string, string> = {
|
|
|
134
135
|
'read_mcp_resource': 'ReadMcpResource',
|
|
135
136
|
};
|
|
136
137
|
|
|
137
|
-
/** Map Open Code tool name to
|
|
138
|
+
/** Map Open Code tool name to canonical UI tool name. */
|
|
138
139
|
export function mapToolName(openCodeToolName: string): string {
|
|
139
140
|
// Check if this is a custom MCP tool (resolves via single source in backend/mcp)
|
|
140
141
|
const mcpName = resolveOpenCodeToolName(openCodeToolName);
|
|
141
142
|
if (mcpName) return mcpName;
|
|
142
143
|
|
|
143
144
|
const lower = openCodeToolName.toLowerCase();
|
|
144
|
-
|
|
145
|
+
const mapped = TOOL_NAME_MAP[lower] || TOOL_NAME_MAP[openCodeToolName] || openCodeToolName;
|
|
146
|
+
return toCanonicalToolName(mapped);
|
|
145
147
|
}
|
|
146
148
|
|
|
147
149
|
// ============================================================
|
|
@@ -445,21 +447,28 @@ export function convertUserMessage(
|
|
|
445
447
|
/**
|
|
446
448
|
* Convert Open Code assistant message + parts → EngineOutput[]
|
|
447
449
|
*
|
|
450
|
+
* Follows the Claude Code pattern: every tool_use block is emitted with
|
|
451
|
+
* `result: null`, and completed/errored tools emit a separate UserMessage
|
|
452
|
+
* with the tool_result so the frontend has a single stitching path.
|
|
453
|
+
*
|
|
448
454
|
* Splits content into separate messages:
|
|
449
|
-
* - Consecutive text blocks → one message
|
|
450
|
-
* - Each tool_use block → its own message
|
|
455
|
+
* - Consecutive text blocks → one assistant message
|
|
456
|
+
* - Each tool_use block → its own assistant message (+ optional tool_result user message)
|
|
451
457
|
*/
|
|
452
458
|
export function convertAssistantMessages(
|
|
453
459
|
ocMessage: OCMessage,
|
|
454
460
|
ocParts: Part[],
|
|
455
461
|
sessionId: string
|
|
456
462
|
): EngineOutput[] {
|
|
457
|
-
// 1.
|
|
458
|
-
|
|
463
|
+
// 1. Parse parts into (block, optional trailing tool_result) entries.
|
|
464
|
+
type Entry =
|
|
465
|
+
| { kind: 'text'; block: TextBlock }
|
|
466
|
+
| { kind: 'tool'; block: ToolUseBlock; result: ToolResult | null };
|
|
467
|
+
const entries: Entry[] = [];
|
|
459
468
|
|
|
460
469
|
for (const part of ocParts) {
|
|
461
470
|
if (part.type === 'text') {
|
|
462
|
-
|
|
471
|
+
entries.push({ kind: 'text', block: { type: 'text', text: part.text || '' } as TextBlock });
|
|
463
472
|
} else if (part.type === 'tool') {
|
|
464
473
|
const toolPart = part as ToolPart;
|
|
465
474
|
const claudeName = mapToolName(toolPart.tool || 'unknown');
|
|
@@ -485,59 +494,66 @@ export function convertAssistantMessages(
|
|
|
485
494
|
};
|
|
486
495
|
}
|
|
487
496
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
497
|
+
entries.push({
|
|
498
|
+
kind: 'tool',
|
|
499
|
+
block: {
|
|
500
|
+
type: 'tool_use',
|
|
501
|
+
id: toolUseId,
|
|
502
|
+
name: claudeName,
|
|
503
|
+
input: normalizedInput,
|
|
504
|
+
result: null,
|
|
505
|
+
subActivities: [],
|
|
506
|
+
skillPrompt: null,
|
|
507
|
+
interrupted: false,
|
|
508
|
+
} as ToolUseBlock,
|
|
493
509
|
result,
|
|
494
|
-
|
|
495
|
-
skillPrompt: null,
|
|
496
|
-
interrupted: false,
|
|
497
|
-
} as ToolUseBlock);
|
|
510
|
+
});
|
|
498
511
|
} else if (part.type === 'subtask') {
|
|
499
|
-
const subtaskPart = part as
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
512
|
+
const subtaskPart = part as { id?: string; prompt?: string; description?: string; agent?: string };
|
|
513
|
+
entries.push({
|
|
514
|
+
kind: 'tool',
|
|
515
|
+
block: {
|
|
516
|
+
type: 'tool_use',
|
|
517
|
+
id: subtaskPart.id || crypto.randomUUID(),
|
|
518
|
+
name: 'Agent',
|
|
519
|
+
input: {
|
|
520
|
+
prompt: subtaskPart.prompt || '',
|
|
521
|
+
description: subtaskPart.description || '',
|
|
522
|
+
subagentType: subtaskPart.agent || 'general-purpose',
|
|
523
|
+
},
|
|
524
|
+
result: null,
|
|
525
|
+
subActivities: [],
|
|
526
|
+
skillPrompt: null,
|
|
527
|
+
interrupted: false,
|
|
528
|
+
} as ToolUseBlock,
|
|
509
529
|
result: null,
|
|
510
|
-
|
|
511
|
-
skillPrompt: null,
|
|
512
|
-
interrupted: false,
|
|
513
|
-
} as ToolUseBlock);
|
|
530
|
+
});
|
|
514
531
|
}
|
|
515
532
|
// Skip: reasoning, step-start, step-finish, snapshot, patch, agent, retry, compaction
|
|
516
533
|
}
|
|
517
534
|
|
|
518
|
-
// 2.
|
|
519
|
-
|
|
520
|
-
|
|
535
|
+
// 2. Collapse consecutive text entries into groups; each tool entry is its own group.
|
|
536
|
+
type Group =
|
|
537
|
+
| { kind: 'text'; blocks: TextBlock[] }
|
|
538
|
+
| { kind: 'tool'; entry: Extract<Entry, { kind: 'tool' }> };
|
|
539
|
+
const groups: Group[] = [];
|
|
540
|
+
let textBuf: TextBlock[] = [];
|
|
521
541
|
|
|
522
|
-
for (const
|
|
523
|
-
if (
|
|
524
|
-
|
|
542
|
+
for (const entry of entries) {
|
|
543
|
+
if (entry.kind === 'text') {
|
|
544
|
+
textBuf.push(entry.block);
|
|
525
545
|
} else {
|
|
526
|
-
if (
|
|
527
|
-
groups.push(
|
|
528
|
-
|
|
546
|
+
if (textBuf.length > 0) {
|
|
547
|
+
groups.push({ kind: 'text', blocks: textBuf });
|
|
548
|
+
textBuf = [];
|
|
529
549
|
}
|
|
530
|
-
groups.push(
|
|
550
|
+
groups.push({ kind: 'tool', entry });
|
|
531
551
|
}
|
|
532
552
|
}
|
|
533
|
-
if (
|
|
534
|
-
|
|
535
|
-
}
|
|
536
|
-
if (groups.length === 0) {
|
|
537
|
-
groups.push([{ type: 'text', text: '' } as TextBlock]);
|
|
538
|
-
}
|
|
553
|
+
if (textBuf.length > 0) groups.push({ kind: 'text', blocks: textBuf });
|
|
554
|
+
if (groups.length === 0) groups.push({ kind: 'text', blocks: [{ type: 'text', text: '' } as TextBlock] });
|
|
539
555
|
|
|
540
|
-
// 3. Build unified messages from groups
|
|
556
|
+
// 3. Build unified messages from groups.
|
|
541
557
|
const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
|
|
542
558
|
const providerID = assistantMsg?.providerID || '';
|
|
543
559
|
const modelID = assistantMsg?.modelID || '';
|
|
@@ -550,7 +566,7 @@ export function convertAssistantMessages(
|
|
|
550
566
|
for (let i = 0; i < groups.length; i++) {
|
|
551
567
|
const isLast = i === groups.length - 1;
|
|
552
568
|
const group = groups[i];
|
|
553
|
-
const hasToolUse = group.
|
|
569
|
+
const hasToolUse = group.kind === 'tool';
|
|
554
570
|
|
|
555
571
|
let stopReason: StopReason | null;
|
|
556
572
|
if (isLast) {
|
|
@@ -561,6 +577,8 @@ export function convertAssistantMessages(
|
|
|
561
577
|
stopReason = null;
|
|
562
578
|
}
|
|
563
579
|
|
|
580
|
+
const content: AssistantContentBlock[] = group.kind === 'text' ? group.blocks : [group.entry.block];
|
|
581
|
+
|
|
564
582
|
const msg: UnifiedAssistantMessage = {
|
|
565
583
|
type: 'assistant',
|
|
566
584
|
createdAt: new Date().toISOString(),
|
|
@@ -568,11 +586,29 @@ export function convertAssistantMessages(
|
|
|
568
586
|
sessionId,
|
|
569
587
|
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
570
588
|
engine: { type: 'opencode' as const, provider: providerID, model: { id: modelID, name: '' }, account: { id: 0, name: '' } },
|
|
571
|
-
content
|
|
589
|
+
content,
|
|
572
590
|
stopReason,
|
|
573
591
|
usage: isLast ? usage : null,
|
|
574
592
|
};
|
|
575
593
|
messages.push(msg);
|
|
594
|
+
|
|
595
|
+
// For completed/errored tools, emit a paired tool_result user message —
|
|
596
|
+
// matches the Claude Code adapter's contract.
|
|
597
|
+
if (group.kind === 'tool' && group.entry.result) {
|
|
598
|
+
const result = group.entry.result;
|
|
599
|
+
const toolResultMsg: UserMessage = {
|
|
600
|
+
type: 'user',
|
|
601
|
+
createdAt: new Date().toISOString(),
|
|
602
|
+
messageId: crypto.randomUUID(),
|
|
603
|
+
sessionId,
|
|
604
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
605
|
+
engine: { type: 'opencode' as const, provider: providerID, model: { id: modelID, name: '' }, account: { id: 0, name: '' } },
|
|
606
|
+
sender: { id: '', name: '' },
|
|
607
|
+
content: [result],
|
|
608
|
+
synthetic: true,
|
|
609
|
+
};
|
|
610
|
+
messages.push(toolResultMsg);
|
|
611
|
+
}
|
|
576
612
|
}
|
|
577
613
|
|
|
578
614
|
return messages;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-
|
|
2
|
-
import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-D1QNkcRL.js";class v{projectContexts=new Map;currentProjectId=null;constructor(){}getOrCreateProjectContext(e,s){let t=this.projectContexts.get(e);return t||(t={projectId:e,projectPath:s,sessionIds:[],activeSessionId:null,lastActiveAt:new Date,sessionOutputs:new Map,sessionCommandHistories:new Map},this.projectContexts.set(e,t),this.persistContexts()),t}async switchToProject(e,s){this.currentProjectId&&this.currentProjectId!==e&&(await this.saveCurrentProjectState(),await this.hideProjectTerminalSessions(this.currentProjectId));const t=this.getOrCreateProjectContext(e,s);this.currentProjectId!==e&&c.clearAllSessions(),t.sessionIds.length===0?await this.createProjectTerminalSessions(e,s):await this.showProjectTerminalSessions(t),this.currentProjectId=e,t.lastActiveAt=new Date,this.persistContexts(),await this.checkAndRestoreActiveStreams(e)}async createProjectTerminalSessions(e,s){const t=this.getOrCreateProjectContext(e,s),n=await h.listProjectSessions(e);if(n.length>0){d.log("terminal",`Found ${n.length} existing PTY sessions for project ${e}`),n.sort((r,l)=>r.sessionId.localeCompare(l.sessionId));for(const r of n){const l=r.sessionId.split("-"),f=l[l.length-1]||"1",I={id:r.sessionId,name:`Terminal ${f}`,directory:r.cwd||s,lines:[],commandHistory:[],isActive:!1,createdAt:new Date(r.createdAt),lastUsedAt:new Date(r.lastActivityAt),shellType:"Unknown",terminalBuffer:void 0,projectId:e,projectPath:s};c.addSession(I),m.createSession(r.sessionId,e,s,r.cwd||s),t.sessionIds.push(r.sessionId);const u=r.sessionId.match(/terminal-(\d+)/);u&&c.updateNextSessionId(parseInt(u[1],10)+1)}let o=n[0].sessionId;if(typeof sessionStorage<"u")try{const r=sessionStorage.getItem(`terminal-active-session-${e}`);r&&t.sessionIds.includes(r)&&(o=r)}catch{}t.activeSessionId=o,c.switchToSession(t.activeSessionId),this.persistContexts();return}const i=c.createNewSession(s,s,e),a=c.getSession(i);a&&(a.directory=s),m.createSession(i,e,s,s),t.sessionIds.push(i),t.activeSessionId=i,c.switchToSession(i),this.persistContexts()}async hideProjectTerminalSessions(e){const s=this.projectContexts.get(e);if(s){for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}for(const t of s.sessionIds)h.cleanupListeners(t);c.clearAllSessions()}}async showProjectTerminalSessions(e){c.clearAllSessions();const{terminalPersistenceManager:s}=await p(async()=>{const{terminalPersistenceManager:n}=await import("./main-D1QNkcRL.js").then(i=>i.p);return{terminalPersistenceManager:n}},__vite__mapDeps([0,1])),t=s.getAllActiveStreams();if(e.sessionIds.length>0)for(const n of e.sessionIds){const i=n.split("-"),a=i[i.length-1]||"1",o={id:n,name:`Terminal ${a}`,directory:e.projectPath,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};let r=!1,l=null;for(const u of t)if(u.projectId===e.projectId){const g=u.sessionId.split("-");if(g[g.length-1]===a){r=!0,l=u;break}}o.lines=[];const f=e.sessionCommandHistories.get(n);f&&(o.commandHistory=f);const I=m.getSession(n);if(I&&(f&&(I.commandHistory=f),o.directory=e.projectPath,(r||I.isExecuting)&&(c.setExecutingState(n,!0),l&&(I.isExecuting=!0,I.streamId=l.streamId,I.lastCommand=l.command))),c.addSession(o),!I||I.projectId!==e.projectId){const u=m.createSession(n,e.projectId,e.projectPath,e.projectPath);r&&l&&(u.isExecuting=!0,u.streamId=l.streamId,u.lastCommand=l.command)}else m.updateSession(n,{projectId:e.projectId,projectPath:e.projectPath,workingDirectory:e.projectPath})}else{const n=c.createNewSession(e.projectPath,e.projectPath,e.projectId);m.createSession(n,e.projectId,e.projectPath,e.projectPath),e.sessionIds.push(n),e.activeSessionId=n}e.activeSessionId&&e.sessionIds.includes(e.activeSessionId)?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId)),this.persistContexts()}async restoreProjectTerminalSessions(e){for(const s of e.sessionIds){const t=c.getSession(s),n=m.getSession(s);if(!t)if(n)this.restoreSessionToStore(n);else{const i=c.createNewSession(e.projectPath,e.projectPath,e.projectId),a=e.sessionIds.indexOf(s);a!==-1&&(e.sessionIds[a]=i),m.updateSession(i,{projectId:e.projectId,projectPath:e.projectPath}),e.activeSessionId===s&&(e.activeSessionId=i)}}e.activeSessionId?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId))}restoreSessionToStore(e,s){const t=e.projectPath||e.workingDirectory,n=e.id.split("-"),i=n[n.length-1]||"1",a={id:e.id,name:`Terminal ${i}`,directory:t,lines:[],commandHistory:e.commandHistory||[],isActive:!1,createdAt:e.createdAt||new Date,lastUsedAt:e.lastUsedAt||new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};if(s&&s.sessionOutputs.has(e.id)){const o=s.sessionOutputs.get(e.id);o&&(a.lines=o.map(r=>({content:r.content,type:r.type,timestamp:r.timestamp})))}c.addSession(a)}async saveCurrentProjectState(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!e)return;const s=c.activeSessionId;s&&(e.activeSessionId=s);for(const t of e.sessionIds){const n=c.getSession(t);if(n){const i=n.lines.map(o=>({content:o.content,type:o.type,timestamp:o.timestamp||new Date}));e.sessionOutputs.set(t,i);let a=0;for(const o of n.lines)(o.type==="output"||o.type==="error")&&a++;e.sessionOutputs.set(`${t}-metadata`,{outputCount:a}),n.commandHistory&&n.commandHistory.length>0&&e.sessionCommandHistories.set(t,n.commandHistory),m.updateSession(t,{commandHistory:n.commandHistory,workingDirectory:n.directory,projectId:this.currentProjectId,projectPath:e.projectPath})}}this.persistContexts()}saveAllProjectStates(){this.currentProjectId&&this.saveCurrentProjectState();for(const[e,s]of this.projectContexts.entries())if(e!==this.currentProjectId)for(const t of s.sessionIds){const n=m.getSession(t);n&&n.commandHistory&&s.sessionCommandHistories.set(t,n.commandHistory)}this.persistContexts()}addTerminalToCurrentProject(e,s){const t=e||this.currentProjectId;if(!t)return null;let n=this.projectContexts.get(t);if(!n&&s&&(n=this.getOrCreateProjectContext(t,s)),!n)return null;e&&e!==this.currentProjectId&&(this.currentProjectId=e);const i=c.createNewSession(n.projectPath,n.projectPath,t),a=c.getSession(i);return a&&(a.directory=n.projectPath),m.createSession(i,t,n.projectPath,n.projectPath),n.sessionIds.push(i),n.activeSessionId=i,this.persistContexts(),i}async removeTerminalFromCurrentProject(e){if(!this.currentProjectId)return!1;const s=this.projectContexts.get(this.currentProjectId);return!s||s.sessionIds.length<=1?!1:(s.sessionIds=s.sessionIds.filter(t=>t!==e),s.activeSessionId===e&&s.sessionIds.length>0&&(s.activeSessionId=s.sessionIds[0]),await c.closeSession(e),m.removeSession(e),this.persistContexts(),!0)}removeSessionFromContext(e){d.log("terminal",`🗑️ [projectManager] Removing session from context: ${e}`);for(const[s,t]of this.projectContexts.entries()){const n=t.sessionIds.indexOf(e);if(n!==-1){d.log("terminal",`🗑️ [projectManager] Found session in project: ${s}`),d.log("terminal",`🗑️ [projectManager] Sessions before: ${t.sessionIds.join(", ")}`),t.sessionIds.splice(n,1),t.sessionOutputs.delete(e),t.sessionOutputs.delete(`${e}-metadata`),t.sessionCommandHistories.delete(e),t.activeSessionId===e&&(t.activeSessionId=t.sessionIds[0]||null,d.log("terminal",`🗑️ [projectManager] Updated activeSessionId to: ${t.activeSessionId}`)),d.log("terminal",`🗑️ [projectManager] Sessions after: ${t.sessionIds.join(", ")}`),m.removeSession(e),this.persistContexts(),d.log("terminal","🗑️ [projectManager] Context persisted");return}}d.log("terminal","🗑️ [projectManager] Session not found in any project context")}getProjectSessions(e){return this.projectContexts.get(e)?.sessionIds||[]}hasRunningTerminals(e){const s=this.projectContexts.get(e);return s?s.sessionIds.some(t=>m.getSession(t)?.isExecuting||!1):!1}getTerminalCount(e){return this.projectContexts.get(e)?.sessionIds.length||0}persistContexts(){for(const[e,s]of this.projectContexts.entries())for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}}loadPersistedContexts(){}clearAll(){this.projectContexts.clear(),this.currentProjectId=null}initialize(){typeof window>"u"||this.setupCollaborativeListeners()}setupCollaborativeListeners(){p(async()=>{const{default:e}=await import("./main-D1QNkcRL.js").then(s=>s.w);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{e.on("terminal:tab-created",s=>{if(d.log("terminal",`📥 Received terminal:tab-created: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already exists locally, skipping`);return}if(c.getSession(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already in store, skipping`);return}d.log("terminal",`➕ Adding remote terminal tab: ${s.sessionId}`);const i=s.sessionId.split("-"),a=i[i.length-1]||"1",o={id:s.sessionId,name:`Terminal ${a}`,directory:s.currentDirectory,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:this.currentProjectId,projectPath:t.projectPath};c.addSession(o),t.sessionIds.push(s.sessionId),m.createSession(s.sessionId,this.currentProjectId,t.projectPath,s.currentDirectory);const r=s.sessionId.match(/terminal-(\d+)/);r&&c.updateNextSessionId(parseInt(r[1],10)+1)}),e.on("terminal:tab-closed",s=>{if(d.log("terminal",`📥 Received terminal:tab-closed: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(!t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} not in our context, skipping`);return}if(!c.getSession(s.sessionId)){this.removeSessionFromContext(s.sessionId);return}d.log("terminal",`➖ Removing remote terminal tab: ${s.sessionId}`),this.removeSessionFromContext(s.sessionId),c.removeSessionFromStore(s.sessionId)}),d.log("terminal","✅ Terminal collaborative listeners registered")}),P(()=>{this.validateSessionsAfterReconnect()})}async validateSessionsAfterReconnect(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!(!e||e.sessionIds.length===0)){d.log("terminal","Validating terminal sessions after reconnect...");try{const s=await h.listProjectSessions(this.currentProjectId),t=new Set(s.map(i=>i.sessionId)),n=e.sessionIds.filter(i=>!t.has(i));if(n.length===0){d.log("terminal","All terminal sessions still alive after reconnect");return}d.log("terminal",`Found ${n.length} dead terminal session(s) after reconnect, cleaning up`);for(const i of n)this.removeSessionFromContext(i),c.removeSessionFromStore(i),h.cleanupListeners(i);e.sessionIds.length===0&&(d.log("terminal","All terminal sessions dead after reconnect, creating new session"),await this.createProjectTerminalSessions(this.currentProjectId,e.projectPath))}catch(s){d.error("terminal","Failed to validate terminal sessions after reconnect:",s)}}}getProjectIndicator(e){const s=this.projectContexts.get(e);if(!s)return{hasTerminals:!1,runningCount:0,totalCount:0};let t=0;const n=new Set;for(const o of s.sessionIds)if(m.getSession(o)?.isExecuting){const l=o.split("-"),f=l[l.length-1];n.add(f),t++}const i=S.getAllActiveStreams(),a=new Set;for(const o of i)if(!a.has(o.streamId)&&o.projectId===e){const r=o.sessionId.split("-"),l=r[r.length-1];n.has(l)||s.sessionIds.some(I=>{const u=I.split("-");return u[u.length-1]===l})&&(n.add(l),t++),a.add(o.streamId)}return{hasTerminals:s.sessionIds.length>0,runningCount:t,totalCount:s.sessionIds.length}}async checkAndRestoreActiveStreams(e){if(typeof window>"u")return;const s=this.projectContexts.get(e);if(!s)return;const{terminalPersistenceManager:t}=await p(async()=>{const{terminalPersistenceManager:a}=await import("./main-D1QNkcRL.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-D1QNkcRL.js").then(o=>o.i);return{backgroundTerminalService:a}},__vite__mapDeps([0,1])),i=t.getAllActiveStreams();for(const a of i)if(a.projectId===e){const o=a.sessionId.split("-"),r=o[o.length-1];for(const l of s.sessionIds){const f=l.split("-");if(f[f.length-1]===r&&m.getSession(l)){m.startExecution(l,a.command,a.streamId),c.setExecutingState(l,!0);break}}}}}const j=new v,T=Object.freeze(Object.defineProperty({__proto__:null,terminalProjectManager:j},Symbol.toStringTag,{value:"Module"})),A=Object.freeze(Object.defineProperty({__proto__:null,terminalPersistenceManager:S,terminalProjectManager:j,terminalService:h,terminalSessionManager:m},Symbol.toStringTag,{value:"Module"}));export{A as i,T as p};
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-8urnNoR7.js","assets/main-TEa2MRnh.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as c,a as h,d,b as m,c as S,_ as p,o as P}from"./main-8urnNoR7.js";class v{projectContexts=new Map;currentProjectId=null;constructor(){}getOrCreateProjectContext(e,s){let t=this.projectContexts.get(e);return t||(t={projectId:e,projectPath:s,sessionIds:[],activeSessionId:null,lastActiveAt:new Date,sessionOutputs:new Map,sessionCommandHistories:new Map},this.projectContexts.set(e,t),this.persistContexts()),t}async switchToProject(e,s){this.currentProjectId&&this.currentProjectId!==e&&(await this.saveCurrentProjectState(),await this.hideProjectTerminalSessions(this.currentProjectId));const t=this.getOrCreateProjectContext(e,s);this.currentProjectId!==e&&c.clearAllSessions(),t.sessionIds.length===0?await this.createProjectTerminalSessions(e,s):await this.showProjectTerminalSessions(t),this.currentProjectId=e,t.lastActiveAt=new Date,this.persistContexts(),await this.checkAndRestoreActiveStreams(e)}async createProjectTerminalSessions(e,s){const t=this.getOrCreateProjectContext(e,s),n=await h.listProjectSessions(e);if(n.length>0){d.log("terminal",`Found ${n.length} existing PTY sessions for project ${e}`),n.sort((r,l)=>r.sessionId.localeCompare(l.sessionId));for(const r of n){const l=r.sessionId.split("-"),f=l[l.length-1]||"1",I={id:r.sessionId,name:`Terminal ${f}`,directory:r.cwd||s,lines:[],commandHistory:[],isActive:!1,createdAt:new Date(r.createdAt),lastUsedAt:new Date(r.lastActivityAt),shellType:"Unknown",terminalBuffer:void 0,projectId:e,projectPath:s};c.addSession(I),m.createSession(r.sessionId,e,s,r.cwd||s),t.sessionIds.push(r.sessionId);const u=r.sessionId.match(/terminal-(\d+)/);u&&c.updateNextSessionId(parseInt(u[1],10)+1)}let o=n[0].sessionId;if(typeof sessionStorage<"u")try{const r=sessionStorage.getItem(`terminal-active-session-${e}`);r&&t.sessionIds.includes(r)&&(o=r)}catch{}t.activeSessionId=o,c.switchToSession(t.activeSessionId),this.persistContexts();return}const i=c.createNewSession(s,s,e),a=c.getSession(i);a&&(a.directory=s),m.createSession(i,e,s,s),t.sessionIds.push(i),t.activeSessionId=i,c.switchToSession(i),this.persistContexts()}async hideProjectTerminalSessions(e){const s=this.projectContexts.get(e);if(s){for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}for(const t of s.sessionIds)h.cleanupListeners(t);c.clearAllSessions()}}async showProjectTerminalSessions(e){c.clearAllSessions();const{terminalPersistenceManager:s}=await p(async()=>{const{terminalPersistenceManager:n}=await import("./main-8urnNoR7.js").then(i=>i.p);return{terminalPersistenceManager:n}},__vite__mapDeps([0,1])),t=s.getAllActiveStreams();if(e.sessionIds.length>0)for(const n of e.sessionIds){const i=n.split("-"),a=i[i.length-1]||"1",o={id:n,name:`Terminal ${a}`,directory:e.projectPath,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};let r=!1,l=null;for(const u of t)if(u.projectId===e.projectId){const g=u.sessionId.split("-");if(g[g.length-1]===a){r=!0,l=u;break}}o.lines=[];const f=e.sessionCommandHistories.get(n);f&&(o.commandHistory=f);const I=m.getSession(n);if(I&&(f&&(I.commandHistory=f),o.directory=e.projectPath,(r||I.isExecuting)&&(c.setExecutingState(n,!0),l&&(I.isExecuting=!0,I.streamId=l.streamId,I.lastCommand=l.command))),c.addSession(o),!I||I.projectId!==e.projectId){const u=m.createSession(n,e.projectId,e.projectPath,e.projectPath);r&&l&&(u.isExecuting=!0,u.streamId=l.streamId,u.lastCommand=l.command)}else m.updateSession(n,{projectId:e.projectId,projectPath:e.projectPath,workingDirectory:e.projectPath})}else{const n=c.createNewSession(e.projectPath,e.projectPath,e.projectId);m.createSession(n,e.projectId,e.projectPath,e.projectPath),e.sessionIds.push(n),e.activeSessionId=n}e.activeSessionId&&e.sessionIds.includes(e.activeSessionId)?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId)),this.persistContexts()}async restoreProjectTerminalSessions(e){for(const s of e.sessionIds){const t=c.getSession(s),n=m.getSession(s);if(!t)if(n)this.restoreSessionToStore(n);else{const i=c.createNewSession(e.projectPath,e.projectPath,e.projectId),a=e.sessionIds.indexOf(s);a!==-1&&(e.sessionIds[a]=i),m.updateSession(i,{projectId:e.projectId,projectPath:e.projectPath}),e.activeSessionId===s&&(e.activeSessionId=i)}}e.activeSessionId?c.switchToSession(e.activeSessionId):e.sessionIds.length>0&&(e.activeSessionId=e.sessionIds[0],c.switchToSession(e.activeSessionId))}restoreSessionToStore(e,s){const t=e.projectPath||e.workingDirectory,n=e.id.split("-"),i=n[n.length-1]||"1",a={id:e.id,name:`Terminal ${i}`,directory:t,lines:[],commandHistory:e.commandHistory||[],isActive:!1,createdAt:e.createdAt||new Date,lastUsedAt:e.lastUsedAt||new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:e.projectId,projectPath:e.projectPath};if(s&&s.sessionOutputs.has(e.id)){const o=s.sessionOutputs.get(e.id);o&&(a.lines=o.map(r=>({content:r.content,type:r.type,timestamp:r.timestamp})))}c.addSession(a)}async saveCurrentProjectState(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!e)return;const s=c.activeSessionId;s&&(e.activeSessionId=s);for(const t of e.sessionIds){const n=c.getSession(t);if(n){const i=n.lines.map(o=>({content:o.content,type:o.type,timestamp:o.timestamp||new Date}));e.sessionOutputs.set(t,i);let a=0;for(const o of n.lines)(o.type==="output"||o.type==="error")&&a++;e.sessionOutputs.set(`${t}-metadata`,{outputCount:a}),n.commandHistory&&n.commandHistory.length>0&&e.sessionCommandHistories.set(t,n.commandHistory),m.updateSession(t,{commandHistory:n.commandHistory,workingDirectory:n.directory,projectId:this.currentProjectId,projectPath:e.projectPath})}}this.persistContexts()}saveAllProjectStates(){this.currentProjectId&&this.saveCurrentProjectState();for(const[e,s]of this.projectContexts.entries())if(e!==this.currentProjectId)for(const t of s.sessionIds){const n=m.getSession(t);n&&n.commandHistory&&s.sessionCommandHistories.set(t,n.commandHistory)}this.persistContexts()}addTerminalToCurrentProject(e,s){const t=e||this.currentProjectId;if(!t)return null;let n=this.projectContexts.get(t);if(!n&&s&&(n=this.getOrCreateProjectContext(t,s)),!n)return null;e&&e!==this.currentProjectId&&(this.currentProjectId=e);const i=c.createNewSession(n.projectPath,n.projectPath,t),a=c.getSession(i);return a&&(a.directory=n.projectPath),m.createSession(i,t,n.projectPath,n.projectPath),n.sessionIds.push(i),n.activeSessionId=i,this.persistContexts(),i}async removeTerminalFromCurrentProject(e){if(!this.currentProjectId)return!1;const s=this.projectContexts.get(this.currentProjectId);return!s||s.sessionIds.length<=1?!1:(s.sessionIds=s.sessionIds.filter(t=>t!==e),s.activeSessionId===e&&s.sessionIds.length>0&&(s.activeSessionId=s.sessionIds[0]),await c.closeSession(e),m.removeSession(e),this.persistContexts(),!0)}removeSessionFromContext(e){d.log("terminal",`🗑️ [projectManager] Removing session from context: ${e}`);for(const[s,t]of this.projectContexts.entries()){const n=t.sessionIds.indexOf(e);if(n!==-1){d.log("terminal",`🗑️ [projectManager] Found session in project: ${s}`),d.log("terminal",`🗑️ [projectManager] Sessions before: ${t.sessionIds.join(", ")}`),t.sessionIds.splice(n,1),t.sessionOutputs.delete(e),t.sessionOutputs.delete(`${e}-metadata`),t.sessionCommandHistories.delete(e),t.activeSessionId===e&&(t.activeSessionId=t.sessionIds[0]||null,d.log("terminal",`🗑️ [projectManager] Updated activeSessionId to: ${t.activeSessionId}`)),d.log("terminal",`🗑️ [projectManager] Sessions after: ${t.sessionIds.join(", ")}`),m.removeSession(e),this.persistContexts(),d.log("terminal","🗑️ [projectManager] Context persisted");return}}d.log("terminal","🗑️ [projectManager] Session not found in any project context")}getProjectSessions(e){return this.projectContexts.get(e)?.sessionIds||[]}hasRunningTerminals(e){const s=this.projectContexts.get(e);return s?s.sessionIds.some(t=>m.getSession(t)?.isExecuting||!1):!1}getTerminalCount(e){return this.projectContexts.get(e)?.sessionIds.length||0}persistContexts(){for(const[e,s]of this.projectContexts.entries())for(const t of s.sessionIds){const n=m.getSession(t);n&&n.isExecuting&&n.streamId&&S.saveActiveStream(t,n.streamId,n.lastCommand||"",e)}}loadPersistedContexts(){}clearAll(){this.projectContexts.clear(),this.currentProjectId=null}initialize(){typeof window>"u"||this.setupCollaborativeListeners()}setupCollaborativeListeners(){p(async()=>{const{default:e}=await import("./main-8urnNoR7.js").then(s=>s.w);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{e.on("terminal:tab-created",s=>{if(d.log("terminal",`📥 Received terminal:tab-created: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already exists locally, skipping`);return}if(c.getSession(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} already in store, skipping`);return}d.log("terminal",`➕ Adding remote terminal tab: ${s.sessionId}`);const i=s.sessionId.split("-"),a=i[i.length-1]||"1",o={id:s.sessionId,name:`Terminal ${a}`,directory:s.currentDirectory,lines:[],commandHistory:[],isActive:!1,createdAt:new Date,lastUsedAt:new Date,shellType:"Unknown",terminalBuffer:void 0,projectId:this.currentProjectId,projectPath:t.projectPath};c.addSession(o),t.sessionIds.push(s.sessionId),m.createSession(s.sessionId,this.currentProjectId,t.projectPath,s.currentDirectory);const r=s.sessionId.match(/terminal-(\d+)/);r&&c.updateNextSessionId(parseInt(r[1],10)+1)}),e.on("terminal:tab-closed",s=>{if(d.log("terminal",`📥 Received terminal:tab-closed: ${s.sessionId}`),!this.currentProjectId)return;const t=this.projectContexts.get(this.currentProjectId);if(!t)return;if(!t.sessionIds.includes(s.sessionId)){d.log("terminal",`✓ Terminal tab ${s.sessionId} not in our context, skipping`);return}if(!c.getSession(s.sessionId)){this.removeSessionFromContext(s.sessionId);return}d.log("terminal",`➖ Removing remote terminal tab: ${s.sessionId}`),this.removeSessionFromContext(s.sessionId),c.removeSessionFromStore(s.sessionId)}),d.log("terminal","✅ Terminal collaborative listeners registered")}),P(()=>{this.validateSessionsAfterReconnect()})}async validateSessionsAfterReconnect(){if(!this.currentProjectId)return;const e=this.projectContexts.get(this.currentProjectId);if(!(!e||e.sessionIds.length===0)){d.log("terminal","Validating terminal sessions after reconnect...");try{const s=await h.listProjectSessions(this.currentProjectId),t=new Set(s.map(i=>i.sessionId)),n=e.sessionIds.filter(i=>!t.has(i));if(n.length===0){d.log("terminal","All terminal sessions still alive after reconnect");return}d.log("terminal",`Found ${n.length} dead terminal session(s) after reconnect, cleaning up`);for(const i of n)this.removeSessionFromContext(i),c.removeSessionFromStore(i),h.cleanupListeners(i);e.sessionIds.length===0&&(d.log("terminal","All terminal sessions dead after reconnect, creating new session"),await this.createProjectTerminalSessions(this.currentProjectId,e.projectPath))}catch(s){d.error("terminal","Failed to validate terminal sessions after reconnect:",s)}}}getProjectIndicator(e){const s=this.projectContexts.get(e);if(!s)return{hasTerminals:!1,runningCount:0,totalCount:0};let t=0;const n=new Set;for(const o of s.sessionIds)if(m.getSession(o)?.isExecuting){const l=o.split("-"),f=l[l.length-1];n.add(f),t++}const i=S.getAllActiveStreams(),a=new Set;for(const o of i)if(!a.has(o.streamId)&&o.projectId===e){const r=o.sessionId.split("-"),l=r[r.length-1];n.has(l)||s.sessionIds.some(I=>{const u=I.split("-");return u[u.length-1]===l})&&(n.add(l),t++),a.add(o.streamId)}return{hasTerminals:s.sessionIds.length>0,runningCount:t,totalCount:s.sessionIds.length}}async checkAndRestoreActiveStreams(e){if(typeof window>"u")return;const s=this.projectContexts.get(e);if(!s)return;const{terminalPersistenceManager:t}=await p(async()=>{const{terminalPersistenceManager:a}=await import("./main-8urnNoR7.js").then(o=>o.p);return{terminalPersistenceManager:a}},__vite__mapDeps([0,1])),{backgroundTerminalService:n}=await p(async()=>{const{backgroundTerminalService:a}=await import("./main-8urnNoR7.js").then(o=>o.i);return{backgroundTerminalService:a}},__vite__mapDeps([0,1])),i=t.getAllActiveStreams();for(const a of i)if(a.projectId===e){const o=a.sessionId.split("-"),r=o[o.length-1];for(const l of s.sessionIds){const f=l.split("-");if(f[f.length-1]===r&&m.getSession(l)){m.startExecution(l,a.command,a.streamId),c.setExecutingState(l,!0);break}}}}}const j=new v,T=Object.freeze(Object.defineProperty({__proto__:null,terminalProjectManager:j},Symbol.toStringTag,{value:"Module"})),A=Object.freeze(Object.defineProperty({__proto__:null,terminalPersistenceManager:S,terminalProjectManager:j,terminalService:h,terminalSessionManager:m},Symbol.toStringTag,{value:"Module"}));export{A as i,T as p};
|