@percena/weft-react 0.1.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.
@@ -0,0 +1,4980 @@
1
+ export { EN_FALLBACK };
2
+ export { CreateFlitroEmbedRuntimeOptions, createFlitroEmbedRuntime };
3
+
4
+ /**
5
+ * useAgentSession — the official L1 runtime-configuration API.
6
+ *
7
+ * Wraps `createFlitroEmbedRuntime` in a hook: the host backend mints
8
+ * `{ server, token, sessionId }` (e.g. with `@percena/weft-node`) and the
9
+ * component renders `<TimelineAgentChatPanel runtime={session.runtime} />`.
10
+ */
11
+
12
+ interface UseAgentSessionOptions {
13
+ /** Agent server base URL, as returned by the embed bootstrap. */
14
+ server: string;
15
+ /** Scoped session token from the embed bootstrap. */
16
+ token: string;
17
+ /** Session bound to the token. */
18
+ sessionId: string;
19
+ /** Fetch a fresh token from your backend when the current one expires. */
20
+ onTokenExpired?: () => Promise<string | undefined> | string | undefined;
21
+ }
22
+ interface AgentSession {
23
+ runtime: AgentRuntime;
24
+ sessionId: string;
25
+ server: string;
26
+ }
27
+ declare function useAgentSession(options: UseAgentSessionOptions): AgentSession;
28
+
29
+ export { type AgentSession, type UseAgentSessionOptions, useAgentSession };
30
+
31
+ // ── inlined from @weft/core ──
32
+ // -- @weft/core/index.d.ts --
33
+
34
+ /**
35
+ * Mode Types and Constants
36
+ *
37
+ * Pure types and UI configuration for permission modes.
38
+ * Note: This file imports zod for schema definitions.
39
+ * Type-only imports (PermissionMode, PermissionModeCanonical) have no runtime cost.
40
+ */
41
+
42
+ /**
43
+ * Available permission modes (internal storage keys).
44
+ *
45
+ * UI-facing canonical names are:
46
+ * - explore -> safe
47
+ * - ask -> ask
48
+ * - execute -> allow-all
49
+ */
50
+ type PermissionMode = 'safe' | 'ask' | 'allow-all';
51
+ /**
52
+ * Canonical mode names used in user-facing/session-state surfaces.
53
+ */
54
+ type PermissionModeCanonical = 'explore' | 'ask' | 'execute';
55
+
56
+ /**
57
+ * Thinking Level Configuration
58
+ *
59
+ * Six-tier thinking system for extended reasoning:
60
+ * - OFF: No extended thinking (disabled)
61
+ * - Low: Light reasoning, faster responses
62
+ * - Medium: Balanced speed and reasoning (default)
63
+ * - High: Deep reasoning for complex tasks
64
+ * - XHigh: Extra-high reasoning — Anthropic's recommended level for Opus 4.7 agentic/coding work
65
+ * - Max: Maximum effort reasoning
66
+ *
67
+ * Session-level setting with workspace defaults.
68
+ *
69
+ * Provider mappings:
70
+ * - Anthropic: adaptive thinking + effort levels (Opus 4.7+). On models that
71
+ * don't accept `xhigh`, the Anthropic SDK silently falls back to `high`.
72
+ * - Pi/OpenAI: reasoning_effort via Pi SDK levels. Pi's ceiling is `xhigh`,
73
+ * so Weft's `max` saturates there.
74
+ */
75
+ /**
76
+ * Ordered list of valid thinking level IDs. Single source of truth — the
77
+ * `ThinkingLevel` type, `THINKING_LEVELS` metadata, the Zod schema in
78
+ * `validators.ts`, and runtime validation/error messages all derive from this.
79
+ *
80
+ * Order is significant: it determines UI ordering (low → max).
81
+ */
82
+ declare const THINKING_LEVEL_IDS: readonly ["off", "low", "medium", "high", "xhigh", "max"];
83
+ type ThinkingLevel = (typeof THINKING_LEVEL_IDS)[number];
84
+ interface ThinkingLevelDefinition {
85
+ id: ThinkingLevel;
86
+ /** Translation key for the display name (resolve with t() at render site) */
87
+ nameKey: string;
88
+ /** Translation key for the description (resolve with t() at render site) */
89
+ descriptionKey: string;
90
+ }
91
+ /**
92
+ * Available thinking levels with display metadata.
93
+ * Used in UI dropdowns and for validation.
94
+ *
95
+ * Labels use translation keys — resolve with t(level.nameKey) in components.
96
+ */
97
+ declare const THINKING_LEVELS: readonly ThinkingLevelDefinition[];
98
+ /**
99
+ * Map ThinkingLevel to Anthropic SDK effort parameter.
100
+ * Used with adaptive thinking (thinking: { type: 'adaptive' }).
101
+ * Returns null for 'off' (thinking should be disabled entirely).
102
+ */
103
+ declare const THINKING_TO_EFFORT: Record<ThinkingLevel, 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null>;
104
+ /**
105
+ * Get the thinking token budget for a given level and model.
106
+ * Used as fallback for models that don't support adaptive thinking.
107
+ *
108
+ * @param level - The thinking level
109
+ * @param modelId - The model ID (e.g., 'claude-haiku-4-5-20251001')
110
+ * @returns Number of thinking tokens to allocate
111
+ */
112
+ declare function getThinkingTokens(level: ThinkingLevel, modelId: string): number;
113
+ /**
114
+ * Get the translation key for a thinking level's display name.
115
+ * Resolve with t() or i18n.t() at the call site.
116
+ */
117
+ declare function getThinkingLevelNameKey(level: ThinkingLevel): string;
118
+ /**
119
+ * Validate that a value is a valid ThinkingLevel.
120
+ */
121
+ declare function isValidThinkingLevel(value: unknown): value is ThinkingLevel;
122
+ /**
123
+ * Normalize a persisted thinking level value, handling legacy values.
124
+ * Maps the old 'think' value to 'medium' for backward compatibility.
125
+ *
126
+ * TODO: Remove the legacy 'think' compatibility path after old persisted session
127
+ * and workspace data has realistically aged out across upgrades.
128
+ *
129
+ * @returns The normalized ThinkingLevel, or undefined if the value is invalid
130
+ */
131
+ declare function normalizeThinkingLevel(value: unknown): ThinkingLevel | undefined;
132
+
133
+ /**
134
+ * Server DTO types — data shapes used by RPC handlers and SessionManager.
135
+ *
136
+ * Extracted here so handler code in @weft can import
137
+ * from @weft/protocol without reaching into the app.
138
+ */
139
+
140
+ /**
141
+ * Dynamic status ID referencing workspace status config.
142
+ * Validated at runtime via validateSessionStatus().
143
+ * Falls back to 'todo' if status doesn't exist.
144
+ */
145
+ type SessionStatus = string;
146
+ type BuiltInStatusId = 'todo' | 'in-progress' | 'needs-review' | 'done' | 'cancelled';
147
+ /**
148
+ * Electron-specific Session type (includes runtime state).
149
+ * Extends core Session with messages array and processing state.
150
+ */
151
+ interface Session {
152
+ id: string;
153
+ workspaceId: string;
154
+ workspaceName: string;
155
+ name?: string;
156
+ /** Preview of first user message (from JSONL header, for lazy-loaded sessions) */
157
+ preview?: string;
158
+ lastMessageAt: number;
159
+ messages: Message[];
160
+ isProcessing: boolean;
161
+ isFlagged?: boolean;
162
+ /** Permission mode for this session ('safe', 'ask', 'allow-all') */
163
+ permissionMode?: PermissionMode;
164
+ sessionStatus?: SessionStatus;
165
+ /** Labels (additive tags, many-per-session — bare IDs or "id::value" entries) */
166
+ labels?: string[];
167
+ lastReadMessageId?: string;
168
+ /**
169
+ * Explicit unread flag - single source of truth for NEW badge.
170
+ * Set to true when assistant message completes while user is NOT viewing.
171
+ * Set to false when user views the session (and not processing).
172
+ */
173
+ hasUnread?: boolean;
174
+ enabledSourceSlugs?: string[];
175
+ workingDirectory?: string;
176
+ sessionFolderPath?: string;
177
+ sharedUrl?: string;
178
+ sharedId?: string;
179
+ model?: string;
180
+ llmConnection?: string;
181
+ thinkingLevel?: ThinkingLevel;
182
+ lastMessageRole?: 'user' | 'assistant' | 'plan' | 'tool' | 'error';
183
+ lastFinalMessageId?: string;
184
+ isAsyncOperationOngoing?: boolean;
185
+ /** @deprecated Use isAsyncOperationOngoing instead */
186
+ isRegeneratingTitle?: boolean;
187
+ currentStatus?: {
188
+ message: string;
189
+ statusType?: string;
190
+ };
191
+ createdAt?: number;
192
+ messageCount?: number;
193
+ tokenUsage?: {
194
+ inputTokens: number;
195
+ outputTokens: number;
196
+ totalTokens: number;
197
+ contextTokens: number;
198
+ costUsd: number;
199
+ cacheReadTokens?: number;
200
+ cacheCreationTokens?: number;
201
+ /** Model's context window size in tokens (from SDK modelUsage) */
202
+ contextWindow?: number;
203
+ };
204
+ /** When true, session is hidden from session list (e.g., mini edit sessions) */
205
+ hidden?: boolean;
206
+ isArchived?: boolean;
207
+ archivedAt?: number;
208
+ supportsBranching?: boolean;
209
+ }
210
+ interface CreateSessionOptions {
211
+ name?: string;
212
+ permissionMode?: PermissionMode;
213
+ /**
214
+ * Reasoning/thinking level override. When set, takes precedence over workspace
215
+ * and global defaults. Silently ignored by the underlying SDK on non-reasoning
216
+ * models (e.g. gpt-4o) — provider drivers don't attach the reasoning param to
217
+ * the API request for models with `reasoning: false` in the Pi SDK catalog.
218
+ */
219
+ thinkingLevel?: ThinkingLevel;
220
+ /**
221
+ * Working directory for the session:
222
+ * - 'user_default' or undefined: Use workspace's configured default working directory
223
+ * - 'none': No working directory (session folder only)
224
+ * - Absolute path string: Use this specific path
225
+ */
226
+ workingDirectory?: string | 'user_default' | 'none';
227
+ model?: string;
228
+ llmConnection?: string;
229
+ systemPromptPreset?: 'default' | 'mini' | string;
230
+ hidden?: boolean;
231
+ sessionStatus?: SessionStatus;
232
+ labels?: string[];
233
+ isFlagged?: boolean;
234
+ enabledSourceSlugs?: string[];
235
+ /**
236
+ * Message ID to branch from. This is a hard context cutoff:
237
+ * the new session must not include model context from later parent messages.
238
+ */
239
+ branchFromMessageId?: string;
240
+ /** Parent session ID used together with branchFromMessageId. */
241
+ branchFromSessionId?: string;
242
+ }
243
+ interface RemoteSessionTransferPayload {
244
+ sourceSessionId: string;
245
+ name?: string;
246
+ sessionStatus?: SessionStatus;
247
+ labels?: string[];
248
+ permissionMode?: PermissionMode;
249
+ summary: string;
250
+ }
251
+ interface ImportRemoteSessionTransferResult {
252
+ sessionId: string;
253
+ }
254
+ interface PermissionModeState {
255
+ permissionMode: PermissionMode;
256
+ previousPermissionMode?: PermissionMode;
257
+ transitionDisplay?: string;
258
+ modeVersion: number;
259
+ changedAt: string;
260
+ changedBy: 'user' | 'system' | 'restore' | 'automation' | 'unknown';
261
+ }
262
+ type SessionEvent = {
263
+ type: 'text_delta';
264
+ sessionId: string;
265
+ delta: string;
266
+ turnId?: string;
267
+ } | {
268
+ type: 'text_complete';
269
+ sessionId: string;
270
+ text: string;
271
+ isIntermediate?: boolean;
272
+ turnId?: string;
273
+ parentToolUseId?: string;
274
+ timestamp?: number;
275
+ messageId?: string;
276
+ } | {
277
+ type: 'tool_start';
278
+ sessionId: string;
279
+ toolName: string;
280
+ toolUseId: string;
281
+ toolInput: Record<string, unknown>;
282
+ toolIntent?: string;
283
+ toolDisplayName?: string;
284
+ toolDisplayMeta?: ToolDisplayMeta;
285
+ turnId?: string;
286
+ parentToolUseId?: string;
287
+ timestamp?: number;
288
+ } | {
289
+ type: 'tool_result';
290
+ sessionId: string;
291
+ toolUseId: string;
292
+ toolName: string;
293
+ result: string;
294
+ turnId?: string;
295
+ parentToolUseId?: string;
296
+ isError?: boolean;
297
+ timestamp?: number;
298
+ } | {
299
+ type: 'error';
300
+ sessionId: string;
301
+ error: string;
302
+ timestamp?: number;
303
+ } | {
304
+ type: 'typed_error';
305
+ sessionId: string;
306
+ error: TypedError;
307
+ timestamp?: number;
308
+ } | {
309
+ type: 'complete';
310
+ sessionId: string;
311
+ tokenUsage?: Session['tokenUsage'];
312
+ hasUnread?: boolean;
313
+ } | {
314
+ type: 'interrupted';
315
+ sessionId: string;
316
+ message?: Message;
317
+ queuedMessages?: string[];
318
+ } | {
319
+ type: 'status';
320
+ sessionId: string;
321
+ message: string;
322
+ statusType?: 'compacting';
323
+ } | {
324
+ type: 'info';
325
+ sessionId: string;
326
+ message: string;
327
+ statusType?: 'compaction_complete';
328
+ level?: 'info' | 'warning' | 'error' | 'success';
329
+ timestamp?: number;
330
+ } | {
331
+ type: 'title_generated';
332
+ sessionId: string;
333
+ title: string;
334
+ } | {
335
+ type: 'title_regenerating';
336
+ sessionId: string;
337
+ isRegenerating: boolean;
338
+ } | {
339
+ type: 'async_operation';
340
+ sessionId: string;
341
+ isOngoing: boolean;
342
+ } | {
343
+ type: 'working_directory_changed';
344
+ sessionId: string;
345
+ workingDirectory: string;
346
+ } | {
347
+ type: 'permission_request';
348
+ sessionId: string;
349
+ request: PermissionRequest;
350
+ } | {
351
+ type: 'credential_request';
352
+ sessionId: string;
353
+ request: CredentialRequest;
354
+ } | {
355
+ type: 'permission_mode_changed';
356
+ sessionId: string;
357
+ permissionMode: PermissionMode;
358
+ previousPermissionMode?: PermissionMode;
359
+ transitionDisplay?: string;
360
+ modeVersion?: number;
361
+ changedAt?: string;
362
+ changedBy?: PermissionModeState['changedBy'];
363
+ } | {
364
+ type: 'plan_submitted';
365
+ sessionId: string;
366
+ message: Message;
367
+ } | {
368
+ type: 'sources_changed';
369
+ sessionId: string;
370
+ enabledSourceSlugs: string[];
371
+ } | {
372
+ type: 'labels_changed';
373
+ sessionId: string;
374
+ labels: string[];
375
+ } | {
376
+ type: 'connection_changed';
377
+ sessionId: string;
378
+ connectionSlug: string;
379
+ supportsBranching?: boolean;
380
+ } | {
381
+ type: 'task_backgrounded';
382
+ sessionId: string;
383
+ toolUseId: string;
384
+ taskId: string;
385
+ intent?: string;
386
+ turnId?: string;
387
+ } | {
388
+ type: 'shell_backgrounded';
389
+ sessionId: string;
390
+ toolUseId: string;
391
+ shellId: string;
392
+ intent?: string;
393
+ command?: string;
394
+ turnId?: string;
395
+ } | {
396
+ type: 'task_progress';
397
+ sessionId: string;
398
+ toolUseId: string;
399
+ elapsedSeconds: number;
400
+ turnId?: string;
401
+ } | {
402
+ type: 'task_completed';
403
+ sessionId: string;
404
+ taskId: string;
405
+ status: 'completed' | 'failed' | 'stopped';
406
+ outputFile?: string;
407
+ summary?: string;
408
+ turnId?: string;
409
+ } | {
410
+ type: 'shell_killed';
411
+ sessionId: string;
412
+ shellId: string;
413
+ } | {
414
+ type: 'user_message';
415
+ sessionId: string;
416
+ message: Message;
417
+ status: 'accepted' | 'queued' | 'processing';
418
+ optimisticMessageId?: string;
419
+ } | {
420
+ type: 'session_flagged';
421
+ sessionId: string;
422
+ } | {
423
+ type: 'session_unflagged';
424
+ sessionId: string;
425
+ } | {
426
+ type: 'session_archived';
427
+ sessionId: string;
428
+ } | {
429
+ type: 'session_unarchived';
430
+ sessionId: string;
431
+ } | {
432
+ type: 'name_changed';
433
+ sessionId: string;
434
+ name?: string;
435
+ } | {
436
+ type: 'session_model_changed';
437
+ sessionId: string;
438
+ model: string | null;
439
+ } | {
440
+ type: 'session_status_changed';
441
+ sessionId: string;
442
+ sessionStatus: SessionStatus;
443
+ } | {
444
+ type: 'session_deleted';
445
+ sessionId: string;
446
+ } | {
447
+ type: 'session_created';
448
+ sessionId: string;
449
+ } | {
450
+ type: 'session_shared';
451
+ sessionId: string;
452
+ sharedUrl: string;
453
+ } | {
454
+ type: 'session_unshared';
455
+ sessionId: string;
456
+ } | {
457
+ type: 'auth_request';
458
+ sessionId: string;
459
+ message: Message;
460
+ request: AuthRequest;
461
+ } | {
462
+ type: 'auth_completed';
463
+ sessionId: string;
464
+ requestId: string;
465
+ success: boolean;
466
+ cancelled?: boolean;
467
+ error?: string;
468
+ } | {
469
+ type: 'source_activated';
470
+ sessionId: string;
471
+ sourceSlug: string;
472
+ originalMessage: string;
473
+ } | {
474
+ type: 'usage_update';
475
+ sessionId: string;
476
+ tokenUsage: {
477
+ inputTokens: number;
478
+ contextWindow?: number;
479
+ };
480
+ } | {
481
+ type: 'message_annotations_updated';
482
+ sessionId: string;
483
+ messageId: string;
484
+ annotations: AnnotationV1[];
485
+ } | {
486
+ type: 'working_directory_error';
487
+ sessionId: string;
488
+ error: string;
489
+ };
490
+ interface SendMessageOptions {
491
+ skillSlugs?: string[];
492
+ badges?: ContentBadge[];
493
+ optimisticMessageId?: string;
494
+ }
495
+ type SessionCommand = {
496
+ type: 'flag';
497
+ } | {
498
+ type: 'unflag';
499
+ } | {
500
+ type: 'archive';
501
+ } | {
502
+ type: 'unarchive';
503
+ } | {
504
+ type: 'rename';
505
+ name: string;
506
+ } | {
507
+ type: 'setSessionStatus';
508
+ state: SessionStatus;
509
+ } | {
510
+ type: 'markRead';
511
+ } | {
512
+ type: 'markUnread';
513
+ } | {
514
+ type: 'setActiveViewing';
515
+ workspaceId: string;
516
+ } | {
517
+ type: 'setPermissionMode';
518
+ mode: PermissionMode;
519
+ } | {
520
+ type: 'setThinkingLevel';
521
+ level: ThinkingLevel;
522
+ } | {
523
+ type: 'updateWorkingDirectory';
524
+ dir: string;
525
+ } | {
526
+ type: 'setSources';
527
+ sourceSlugs: string[];
528
+ } | {
529
+ type: 'setLabels';
530
+ labels: string[];
531
+ } | {
532
+ type: 'showInFinder';
533
+ } | {
534
+ type: 'copyPath';
535
+ } | {
536
+ type: 'shareToViewer';
537
+ } | {
538
+ type: 'updateShare';
539
+ } | {
540
+ type: 'revokeShare';
541
+ } | {
542
+ type: 'refreshTitle';
543
+ } | {
544
+ type: 'setConnection';
545
+ connectionSlug: string;
546
+ } | {
547
+ type: 'setPendingPlanExecution';
548
+ planPath: string;
549
+ draftInputSnapshot?: string;
550
+ } | {
551
+ type: 'markCompactionComplete';
552
+ } | {
553
+ type: 'markPendingPlanExecutionDispatched';
554
+ } | {
555
+ type: 'clearPendingPlanExecution';
556
+ } | {
557
+ type: 'addAnnotation';
558
+ messageId: string;
559
+ annotation: AnnotationV1;
560
+ } | {
561
+ type: 'removeAnnotation';
562
+ messageId: string;
563
+ annotationId: string;
564
+ } | {
565
+ type: 'updateAnnotation';
566
+ messageId: string;
567
+ annotationId: string;
568
+ patch: Partial<AnnotationV1>;
569
+ };
570
+ interface NewChatActionParams {
571
+ input?: string;
572
+ name?: string;
573
+ }
574
+
575
+ /**
576
+ * Permission request with session context (for multi-session Electron app)
577
+ */
578
+ interface PermissionRequest extends PermissionRequest$1 {
579
+ sessionId: string;
580
+ }
581
+ interface PermissionResponseOptions {
582
+ rememberForMinutes?: number;
583
+ }
584
+
585
+ /**
586
+ * Credential request from agent — prompts user for credentials
587
+ * (e.g., API key, username/password, OAuth token)
588
+ */
589
+ interface CredentialRequest {
590
+ requestId: string;
591
+ toolName: string;
592
+ description: string;
593
+ credentialMode?: CredentialInputMode;
594
+ headerName?: string;
595
+ headerNames?: string[];
596
+ labels?: {
597
+ credential?: string;
598
+ username?: string;
599
+ password?: string;
600
+ };
601
+ hint?: string;
602
+ sourceUrl?: string;
603
+ passwordRequired?: boolean;
604
+ }
605
+ /**
606
+ * Auth request — unified auth flow (credential or OAuth)
607
+ */
608
+ interface AuthRequest {
609
+ requestId: string;
610
+ type: AuthRequestType;
611
+ sourceSlug?: string;
612
+ sourceName?: string;
613
+ description?: string;
614
+ credentialMode?: CredentialInputMode;
615
+ headerName?: string;
616
+ headerNames?: string[];
617
+ labels?: {
618
+ credential?: string;
619
+ username?: string;
620
+ password?: string;
621
+ };
622
+ hint?: string;
623
+ sourceUrl?: string;
624
+ passwordRequired?: boolean;
625
+ }
626
+ interface CredentialResponse {
627
+ type: 'credential';
628
+ value?: string;
629
+ username?: string;
630
+ password?: string;
631
+ headers?: Record<string, string>;
632
+ cancelled: boolean;
633
+ }
634
+ /** Server-side directory listing result (for remote directory browsing). */
635
+ interface DirectoryListingResult {
636
+ /** Normalized absolute path of the listed directory (after resolve(), not symlink-resolved). */
637
+ currentPath: string;
638
+ /** Parent directory path, or null if at root. */
639
+ parentPath: string | null;
640
+ /** Pre-split breadcrumb segments for display (computed server-side). */
641
+ breadcrumbs: Array<{
642
+ name: string;
643
+ path: string;
644
+ }>;
645
+ /** Server platform info. */
646
+ platform: 'win32' | 'darwin' | 'linux';
647
+ /** Whether the server truncated the directory list for safety/performance. */
648
+ truncated: boolean;
649
+ /** Total number of matching child directories before truncation. */
650
+ totalEntries: number;
651
+ /** Child directory entries. */
652
+ entries: Array<{
653
+ name: string;
654
+ path: string;
655
+ isSymlink: boolean;
656
+ }>;
657
+ }
658
+ interface FileAttachment {
659
+ type: 'image' | 'text' | 'pdf' | 'office' | 'audio' | 'unknown';
660
+ path: string;
661
+ name: string;
662
+ mimeType: string;
663
+ base64?: string;
664
+ text?: string;
665
+ size: number;
666
+ thumbnailBase64?: string;
667
+ }
668
+ interface SessionFile {
669
+ name: string;
670
+ path: string;
671
+ type: 'file' | 'directory';
672
+ size?: number;
673
+ children?: SessionFile[];
674
+ }
675
+ interface FileSearchResult {
676
+ name: string;
677
+ path: string;
678
+ type: 'file' | 'directory';
679
+ relativePath: string;
680
+ }
681
+ interface LlmConnectionSetup {
682
+ slug: string;
683
+ credential?: string;
684
+ baseUrl?: string | null;
685
+ defaultModel?: string | null;
686
+ models?: string[] | null;
687
+ piAuthProvider?: string;
688
+ modelSelectionMode?: 'automaticallySyncedFromProvider' | 'userDefined3Tier';
689
+ /** When true, reject setup if the connection doesn't already exist (reauth guard). */
690
+ updateOnly?: boolean;
691
+ /** Custom endpoint protocol for arbitrary OpenAI/Anthropic-compatible APIs */
692
+ customEndpoint?: Record<string, unknown>;
693
+ /** IAM credentials for Pi+Bedrock (piAuthProvider='amazon-bedrock') connections */
694
+ iamCredentials?: {
695
+ accessKeyId: string;
696
+ secretAccessKey: string;
697
+ sessionToken?: string;
698
+ };
699
+ /** AWS region for Pi+Bedrock connections */
700
+ awsRegion?: string;
701
+ /** Bedrock authentication method — determines auth type for Pi+Bedrock connections */
702
+ bedrockAuthMethod?: 'iam_credentials' | 'environment';
703
+ }
704
+ interface TestLlmConnectionParams {
705
+ provider: 'anthropic' | 'pi';
706
+ apiKey: string;
707
+ baseUrl?: string;
708
+ model?: string;
709
+ piAuthProvider?: string;
710
+ /** Optional custom endpoint protocol hint so setup tests mirror runtime routing */
711
+ customEndpoint?: Record<string, unknown>;
712
+ }
713
+ interface TestLlmConnectionResult {
714
+ success: boolean;
715
+ error?: string;
716
+ }
717
+ interface SkillFile {
718
+ name: string;
719
+ type: 'file' | 'directory';
720
+ size?: number;
721
+ children?: SkillFile[];
722
+ }
723
+ interface OAuthResult {
724
+ success: boolean;
725
+ error?: string;
726
+ }
727
+ interface McpValidationResult {
728
+ success: boolean;
729
+ error?: string;
730
+ tools?: string[];
731
+ }
732
+ interface McpToolWithPermission {
733
+ name: string;
734
+ description?: string;
735
+ allowed: boolean;
736
+ }
737
+ interface McpToolsResult {
738
+ success: boolean;
739
+ error?: string;
740
+ tools?: McpToolWithPermission[];
741
+ }
742
+ interface SessionSearchMatch {
743
+ sessionId: string;
744
+ lineNumber: number;
745
+ snippet: string;
746
+ }
747
+ interface SessionSearchResult {
748
+ sessionId: string;
749
+ matchCount: number;
750
+ matches: SessionSearchMatch[];
751
+ }
752
+ interface UnreadSummary {
753
+ totalUnreadSessions: number;
754
+ byWorkspace: Record<string, number>;
755
+ hasUnreadByWorkspace: Record<string, boolean>;
756
+ }
757
+ interface ShareResult {
758
+ success: boolean;
759
+ url?: string;
760
+ error?: string;
761
+ }
762
+ interface RefreshTitleResult {
763
+ success: boolean;
764
+ title?: string;
765
+ error?: string;
766
+ }
767
+ interface PlanStep {
768
+ id: string;
769
+ description: string;
770
+ tools?: string[];
771
+ status?: 'pending' | 'in_progress' | 'completed' | 'failed' | 'skipped';
772
+ }
773
+ interface Plan {
774
+ id: string;
775
+ title: string;
776
+ summary?: string;
777
+ steps: PlanStep[];
778
+ questions?: string[];
779
+ state?: 'creating' | 'refining' | 'ready' | 'executing' | 'completed' | 'cancelled';
780
+ createdAt?: number;
781
+ updatedAt?: number;
782
+ }
783
+ interface GitBashStatus {
784
+ found: boolean;
785
+ path: string | null;
786
+ platform: 'win32' | 'darwin' | 'linux';
787
+ }
788
+ interface UpdateInfo {
789
+ available: boolean;
790
+ currentVersion: string;
791
+ latestVersion: string | null;
792
+ downloadState: 'idle' | 'downloading' | 'ready' | 'installing' | 'error';
793
+ downloadProgress: number;
794
+ error?: string;
795
+ }
796
+ interface WorkspaceSettings {
797
+ name?: string;
798
+ model?: string;
799
+ permissionMode?: PermissionMode;
800
+ cyclablePermissionModes?: PermissionMode[];
801
+ thinkingLevel?: ThinkingLevel;
802
+ workingDirectory?: string;
803
+ localMcpEnabled?: boolean;
804
+ defaultLlmConnection?: string;
805
+ enabledSourceSlugs?: string[];
806
+ }
807
+ interface ClaudeOAuthResult {
808
+ success: boolean;
809
+ token?: string;
810
+ error?: string;
811
+ }
812
+ type TestAutomationAction = {
813
+ type: 'prompt';
814
+ prompt: string;
815
+ llmConnection?: string;
816
+ model?: string;
817
+ thinkingLevel?: ThinkingLevel;
818
+ } | {
819
+ type: 'webhook';
820
+ url: string;
821
+ method?: string;
822
+ headers?: Record<string, string>;
823
+ bodyFormat?: 'json' | 'form' | 'raw';
824
+ body?: unknown;
825
+ captureResponse?: boolean;
826
+ auth?: {
827
+ type: 'basic';
828
+ username: string;
829
+ password: string;
830
+ } | {
831
+ type: 'bearer';
832
+ token: string;
833
+ };
834
+ };
835
+ interface TestAutomationPayload {
836
+ workspaceId: string;
837
+ automationId?: string;
838
+ automationName?: string;
839
+ actions: TestAutomationAction[];
840
+ permissionMode?: PermissionMode;
841
+ labels?: string[];
842
+ /** Forwarded from the matcher; routes test-run sessions into a Telegram topic when paired. */
843
+ telegramTopic?: string;
844
+ }
845
+ type TestAutomationActionResult = {
846
+ type: 'prompt';
847
+ success: boolean;
848
+ stderr?: string;
849
+ sessionId?: string;
850
+ duration: number;
851
+ } | {
852
+ type: 'webhook';
853
+ success: boolean;
854
+ url: string;
855
+ statusCode: number;
856
+ error?: string;
857
+ duration: number;
858
+ };
859
+ interface TestAutomationResult {
860
+ actions: TestAutomationActionResult[];
861
+ }
862
+ type WindowCloseRequestSource = 'keyboard-shortcut' | 'window-button' | 'unknown';
863
+ interface WindowCloseRequest {
864
+ source: WindowCloseRequestSource;
865
+ }
866
+ interface BrowserInstanceInfo {
867
+ id: string;
868
+ url: string;
869
+ title: string;
870
+ favicon: string | null;
871
+ isLoading: boolean;
872
+ canGoBack: boolean;
873
+ canGoForward: boolean;
874
+ boundSessionId: string | null;
875
+ ownerType: 'session' | 'manual';
876
+ ownerSessionId: string | null;
877
+ isVisible: boolean;
878
+ agentControlActive: boolean;
879
+ themeColor: string | null;
880
+ }
881
+ interface DeepLinkNavigation {
882
+ view?: string;
883
+ tabType?: string;
884
+ tabParams?: Record<string, string>;
885
+ action?: string;
886
+ actionParams?: Record<string, string>;
887
+ }
888
+
889
+ /**
890
+ * RPC channel names — organized by domain namespace.
891
+ * Wire-format strings (values) are the stable API contract.
892
+ * Key paths are internal and may be reorganized freely.
893
+ */
894
+ declare const RPC_CHANNELS: {
895
+ readonly remote: {
896
+ readonly TEST_CONNECTION: "remote:testConnection";
897
+ };
898
+ readonly server: {
899
+ readonly GET_WORKSPACES: "server:getWorkspaces";
900
+ readonly CREATE_WORKSPACE: "server:createWorkspace";
901
+ readonly GET_STATUS: "server:getStatus";
902
+ readonly GET_HEALTH: "server:getHealth";
903
+ readonly GET_ACTIVE_SESSIONS: "server:getActiveSessions";
904
+ readonly SHUTTING_DOWN: "server:shuttingDown";
905
+ readonly STATUS_CHANGED: "server:statusChanged";
906
+ readonly HOME_DIR: "server:homeDir";
907
+ };
908
+ readonly sessions: {
909
+ readonly GET: "sessions:get";
910
+ readonly GET_UNREAD_SUMMARY: "sessions:getUnreadSummary";
911
+ readonly MARK_ALL_READ: "sessions:markAllRead";
912
+ readonly UNREAD_SUMMARY_CHANGED: "sessions:unreadSummaryChanged";
913
+ readonly CREATE: "sessions:create";
914
+ readonly DELETE: "sessions:delete";
915
+ readonly GET_MESSAGES: "sessions:getMessages";
916
+ readonly SEND_MESSAGE: "sessions:sendMessage";
917
+ readonly CANCEL: "sessions:cancel";
918
+ readonly KILL_SHELL: "sessions:killShell";
919
+ readonly RESPOND_TO_PERMISSION: "sessions:respondToPermission";
920
+ readonly RESPOND_TO_CREDENTIAL: "sessions:respondToCredential";
921
+ readonly COMMAND: "sessions:command";
922
+ readonly GET_PENDING_PLAN_EXECUTION: "sessions:getPendingPlanExecution";
923
+ readonly GET_PERMISSION_MODE_STATE: "sessions:getPermissionModeState";
924
+ readonly EVENT: "session:event";
925
+ readonly GET_MODEL: "session:getModel";
926
+ readonly SET_MODEL: "session:setModel";
927
+ readonly GET_FILES: "sessions:getFiles";
928
+ readonly GET_NOTES: "sessions:getNotes";
929
+ readonly SET_NOTES: "sessions:setNotes";
930
+ readonly WATCH_FILES: "sessions:watchFiles";
931
+ readonly UNWATCH_FILES: "sessions:unwatchFiles";
932
+ readonly FILES_CHANGED: "sessions:filesChanged";
933
+ readonly SEARCH_CONTENT: "sessions:searchContent";
934
+ readonly EXPORT: "sessions:export";
935
+ readonly IMPORT: "sessions:import";
936
+ readonly EXPORT_REMOTE_TRANSFER: "sessions:exportRemoteTransfer";
937
+ readonly IMPORT_REMOTE_TRANSFER: "sessions:importRemoteTransfer";
938
+ };
939
+ readonly transfer: {
940
+ readonly START: "transfer:start";
941
+ readonly CHUNK: "transfer:chunk";
942
+ readonly COMMIT: "transfer:commit";
943
+ readonly ABORT: "transfer:abort";
944
+ };
945
+ readonly tasks: {
946
+ readonly GET_OUTPUT: "tasks:getOutput";
947
+ };
948
+ readonly workspaces: {
949
+ readonly GET: "workspaces:get";
950
+ readonly CREATE: "workspaces:create";
951
+ readonly CHECK_SLUG: "workspaces:checkSlug";
952
+ readonly UPDATE_REMOTE: "workspaces:updateRemote";
953
+ };
954
+ readonly window: {
955
+ readonly GET_WORKSPACE: "window:getWorkspace";
956
+ readonly GET_MODE: "window:getMode";
957
+ readonly OPEN_WORKSPACE: "window:openWorkspace";
958
+ readonly OPEN_SESSION_IN_NEW_WINDOW: "window:openSessionInNewWindow";
959
+ readonly SWITCH_WORKSPACE: "window:switchWorkspace";
960
+ readonly CLOSE: "window:close";
961
+ readonly CLOSE_REQUESTED: "window:closeRequested";
962
+ readonly CONFIRM_CLOSE: "window:confirmClose";
963
+ readonly CANCEL_CLOSE: "window:cancelClose";
964
+ readonly SET_TRAFFIC_LIGHTS: "window:setTrafficLights";
965
+ readonly FOCUS_STATE: "window:focusState";
966
+ readonly GET_FOCUS_STATE: "window:getFocusState";
967
+ };
968
+ readonly file: {
969
+ readonly READ: "file:read";
970
+ readonly READ_DATA_URL: "file:readDataUrl";
971
+ readonly READ_PREVIEW_DATA_URL: "file:readPreviewDataUrl";
972
+ readonly READ_BINARY: "file:readBinary";
973
+ readonly OPEN_DIALOG: "file:openDialog";
974
+ readonly READ_ATTACHMENT: "file:readAttachment";
975
+ readonly READ_USER_ATTACHMENT: "file:readUserAttachment";
976
+ readonly STORE_ATTACHMENT: "file:storeAttachment";
977
+ readonly GENERATE_THUMBNAIL: "file:generateThumbnail";
978
+ };
979
+ readonly fs: {
980
+ readonly SEARCH: "fs:search";
981
+ readonly LIST_DIRECTORY: "fs:listDirectory";
982
+ };
983
+ readonly debug: {
984
+ readonly LOG: "debug:log";
985
+ };
986
+ readonly theme: {
987
+ readonly GET_SYSTEM_PREFERENCE: "theme:getSystemPreference";
988
+ readonly SYSTEM_CHANGED: "theme:systemChanged";
989
+ readonly APP_CHANGED: "theme:appChanged";
990
+ readonly GET_APP: "theme:getApp";
991
+ readonly GET_PRESETS: "theme:getPresets";
992
+ readonly LOAD_PRESET: "theme:loadPreset";
993
+ readonly GET_COLOR_THEME: "theme:getColorTheme";
994
+ readonly SET_COLOR_THEME: "theme:setColorTheme";
995
+ readonly BROADCAST_PREFERENCES: "theme:broadcastPreferences";
996
+ readonly PREFERENCES_CHANGED: "theme:preferencesChanged";
997
+ readonly GET_WORKSPACE_COLOR_THEME: "theme:getWorkspaceColorTheme";
998
+ readonly SET_WORKSPACE_COLOR_THEME: "theme:setWorkspaceColorTheme";
999
+ readonly GET_ALL_WORKSPACE_THEMES: "theme:getAllWorkspaceThemes";
1000
+ readonly BROADCAST_WORKSPACE_THEME: "theme:broadcastWorkspaceTheme";
1001
+ readonly WORKSPACE_THEME_CHANGED: "theme:workspaceThemeChanged";
1002
+ };
1003
+ readonly system: {
1004
+ readonly VERSIONS: "system:versions";
1005
+ readonly HOME_DIR: "system:homeDir";
1006
+ readonly IS_DEBUG_MODE: "system:isDebugMode";
1007
+ };
1008
+ readonly update: {
1009
+ readonly CHECK: "update:check";
1010
+ readonly GET_INFO: "update:getInfo";
1011
+ readonly INSTALL: "update:install";
1012
+ readonly DISMISS: "update:dismiss";
1013
+ readonly GET_DISMISSED: "update:getDismissed";
1014
+ readonly AVAILABLE: "update:available";
1015
+ readonly DOWNLOAD_PROGRESS: "update:downloadProgress";
1016
+ };
1017
+ readonly shell: {
1018
+ readonly OPEN_URL: "shell:openUrl";
1019
+ readonly OPEN_FILE: "shell:openFile";
1020
+ readonly SHOW_IN_FOLDER: "shell:showInFolder";
1021
+ };
1022
+ readonly menu: {
1023
+ readonly NEW_CHAT: "menu:newChat";
1024
+ readonly NEW_WINDOW: "menu:newWindow";
1025
+ readonly OPEN_SETTINGS: "menu:openSettings";
1026
+ readonly KEYBOARD_SHORTCUTS: "menu:keyboardShortcuts";
1027
+ readonly TOGGLE_FOCUS_MODE: "menu:toggleFocusMode";
1028
+ readonly TOGGLE_SIDEBAR: "menu:toggleSidebar";
1029
+ readonly QUIT: "menu:quit";
1030
+ readonly MINIMIZE: "menu:minimize";
1031
+ readonly MAXIMIZE: "menu:maximize";
1032
+ readonly ZOOM_IN: "menu:zoomIn";
1033
+ readonly ZOOM_OUT: "menu:zoomOut";
1034
+ readonly ZOOM_RESET: "menu:zoomReset";
1035
+ readonly TOGGLE_DEV_TOOLS: "menu:toggleDevTools";
1036
+ readonly UNDO: "menu:undo";
1037
+ readonly REDO: "menu:redo";
1038
+ readonly CUT: "menu:cut";
1039
+ readonly COPY: "menu:copy";
1040
+ readonly PASTE: "menu:paste";
1041
+ readonly SELECT_ALL: "menu:selectAll";
1042
+ };
1043
+ readonly deeplink: {
1044
+ readonly NAVIGATE: "deeplink:navigate";
1045
+ };
1046
+ readonly auth: {
1047
+ readonly LOGOUT: "auth:logout";
1048
+ readonly SHOW_LOGOUT_CONFIRMATION: "auth:showLogoutConfirmation";
1049
+ readonly SHOW_DELETE_SESSION_CONFIRMATION: "auth:showDeleteSessionConfirmation";
1050
+ };
1051
+ readonly credentials: {
1052
+ readonly HEALTH_CHECK: "credentials:healthCheck";
1053
+ };
1054
+ readonly onboarding: {
1055
+ readonly GET_AUTH_STATE: "onboarding:getAuthState";
1056
+ readonly VALIDATE_MCP: "onboarding:validateMcp";
1057
+ readonly START_MCP_OAUTH: "onboarding:startMcpOAuth";
1058
+ readonly START_CLAUDE_OAUTH: "onboarding:startClaudeOAuth";
1059
+ readonly EXCHANGE_CLAUDE_CODE: "onboarding:exchangeClaudeCode";
1060
+ readonly HAS_CLAUDE_OAUTH_STATE: "onboarding:hasClaudeOAuthState";
1061
+ readonly CLEAR_CLAUDE_OAUTH_STATE: "onboarding:clearClaudeOAuthState";
1062
+ readonly DEFER_SETUP: "onboarding:deferSetup";
1063
+ };
1064
+ readonly llmConnections: {
1065
+ readonly LIST: "LLM_Connection:list";
1066
+ readonly LIST_WITH_STATUS: "LLM_Connection:listWithStatus";
1067
+ readonly GET: "LLM_Connection:get";
1068
+ readonly GET_API_KEY: "LLM_Connection:getApiKey";
1069
+ readonly SAVE: "LLM_Connection:save";
1070
+ readonly DELETE: "LLM_Connection:delete";
1071
+ readonly TEST: "LLM_Connection:test";
1072
+ readonly SET_DEFAULT: "LLM_Connection:setDefault";
1073
+ readonly SET_WORKSPACE_DEFAULT: "LLM_Connection:setWorkspaceDefault";
1074
+ readonly REFRESH_MODELS: "LLM_Connection:refreshModels";
1075
+ readonly CHANGED: "LLM_Connection:changed";
1076
+ };
1077
+ readonly chatgpt: {
1078
+ readonly START_OAUTH: "chatgpt:startOAuth";
1079
+ readonly COMPLETE_OAUTH: "chatgpt:completeOAuth";
1080
+ readonly CANCEL_OAUTH: "chatgpt:cancelOAuth";
1081
+ readonly GET_AUTH_STATUS: "chatgpt:getAuthStatus";
1082
+ readonly LOGOUT: "chatgpt:logout";
1083
+ };
1084
+ readonly copilot: {
1085
+ readonly START_OAUTH: "copilot:startOAuth";
1086
+ readonly CANCEL_OAUTH: "copilot:cancelOAuth";
1087
+ readonly GET_AUTH_STATUS: "copilot:getAuthStatus";
1088
+ readonly LOGOUT: "copilot:logout";
1089
+ readonly DEVICE_CODE: "copilot:deviceCode";
1090
+ };
1091
+ readonly settings: {
1092
+ readonly SETUP_LLM_CONNECTION: "settings:setupLlmConnection";
1093
+ readonly TEST_LLM_CONNECTION_SETUP: "settings:testLlmConnectionSetup";
1094
+ readonly GET_DEFAULT_THINKING_LEVEL: "settings:getDefaultThinkingLevel";
1095
+ readonly SET_DEFAULT_THINKING_LEVEL: "settings:setDefaultThinkingLevel";
1096
+ readonly GET_NETWORK_PROXY: "settings:getNetworkProxy";
1097
+ readonly SET_NETWORK_PROXY: "settings:setNetworkProxy";
1098
+ readonly GET_SERVER_CONFIG: "settings:getServerConfig";
1099
+ readonly SET_SERVER_CONFIG: "settings:setServerConfig";
1100
+ readonly GET_SERVER_STATUS: "settings:getServerStatus";
1101
+ };
1102
+ readonly pi: {
1103
+ readonly GET_API_KEY_PROVIDERS: "pi:getApiKeyProviders";
1104
+ readonly GET_PROVIDER_BASE_URL: "pi:getProviderBaseUrl";
1105
+ readonly GET_PROVIDER_MODELS: "pi:getProviderModels";
1106
+ };
1107
+ readonly dialog: {
1108
+ readonly OPEN_FOLDER: "dialog:openFolder";
1109
+ };
1110
+ readonly preferences: {
1111
+ readonly READ: "preferences:read";
1112
+ readonly WRITE: "preferences:write";
1113
+ };
1114
+ readonly drafts: {
1115
+ readonly GET: "drafts:get";
1116
+ readonly SET: "drafts:set";
1117
+ readonly DELETE: "drafts:delete";
1118
+ readonly GET_ALL: "drafts:getAll";
1119
+ };
1120
+ readonly sources: {
1121
+ readonly GET: "sources:get";
1122
+ readonly CREATE: "sources:create";
1123
+ readonly DELETE: "sources:delete";
1124
+ readonly START_OAUTH: "sources:startOAuth";
1125
+ readonly SAVE_CREDENTIALS: "sources:saveCredentials";
1126
+ readonly CHANGED: "sources:changed";
1127
+ readonly GET_PERMISSIONS: "sources:getPermissions";
1128
+ readonly GET_MCP_TOOLS: "sources:getMcpTools";
1129
+ };
1130
+ readonly oauth: {
1131
+ readonly START: "oauth:start";
1132
+ readonly COMPLETE: "oauth:complete";
1133
+ readonly CANCEL: "oauth:cancel";
1134
+ readonly REVOKE: "oauth:revoke";
1135
+ };
1136
+ readonly workspace: {
1137
+ readonly GET_PERMISSIONS: "workspace:getPermissions";
1138
+ readonly READ_IMAGE: "workspace:readImage";
1139
+ readonly WRITE_IMAGE: "workspace:writeImage";
1140
+ readonly SETTINGS_GET: "workspaceSettings:get";
1141
+ readonly SETTINGS_UPDATE: "workspaceSettings:update";
1142
+ };
1143
+ readonly permissions: {
1144
+ readonly GET_DEFAULTS: "permissions:getDefaults";
1145
+ readonly DEFAULTS_CHANGED: "permissions:defaultsChanged";
1146
+ };
1147
+ readonly skills: {
1148
+ readonly GET: "skills:get";
1149
+ readonly GET_FILES: "skills:getFiles";
1150
+ readonly DELETE: "skills:delete";
1151
+ readonly OPEN_EDITOR: "skills:openEditor";
1152
+ readonly OPEN_FINDER: "skills:openFinder";
1153
+ readonly CHANGED: "skills:changed";
1154
+ };
1155
+ readonly statuses: {
1156
+ readonly LIST: "statuses:list";
1157
+ readonly REORDER: "statuses:reorder";
1158
+ readonly CHANGED: "statuses:changed";
1159
+ };
1160
+ readonly labels: {
1161
+ readonly LIST: "labels:list";
1162
+ readonly CREATE: "labels:create";
1163
+ readonly DELETE: "labels:delete";
1164
+ readonly CHANGED: "labels:changed";
1165
+ };
1166
+ readonly views: {
1167
+ readonly LIST: "views:list";
1168
+ readonly SAVE: "views:save";
1169
+ };
1170
+ readonly toolIcons: {
1171
+ readonly GET_MAPPINGS: "toolIcons:getMappings";
1172
+ };
1173
+ readonly logo: {
1174
+ readonly GET_URL: "logo:getUrl";
1175
+ };
1176
+ readonly notification: {
1177
+ readonly SHOW: "notification:show";
1178
+ readonly NAVIGATE: "notification:navigate";
1179
+ readonly GET_ENABLED: "notification:getEnabled";
1180
+ readonly SET_ENABLED: "notification:setEnabled";
1181
+ };
1182
+ readonly input: {
1183
+ readonly GET_AUTO_CAPITALISATION: "input:getAutoCapitalisation";
1184
+ readonly SET_AUTO_CAPITALISATION: "input:setAutoCapitalisation";
1185
+ readonly GET_SEND_MESSAGE_KEY: "input:getSendMessageKey";
1186
+ readonly SET_SEND_MESSAGE_KEY: "input:setSendMessageKey";
1187
+ readonly GET_SPELL_CHECK: "input:getSpellCheck";
1188
+ readonly SET_SPELL_CHECK: "input:setSpellCheck";
1189
+ };
1190
+ readonly power: {
1191
+ readonly GET_KEEP_AWAKE: "power:getKeepAwake";
1192
+ readonly SET_KEEP_AWAKE: "power:setKeepAwake";
1193
+ };
1194
+ readonly appearance: {
1195
+ readonly GET_RICH_TOOL_DESCRIPTIONS: "appearance:getRichToolDescriptions";
1196
+ readonly SET_RICH_TOOL_DESCRIPTIONS: "appearance:setRichToolDescriptions";
1197
+ };
1198
+ readonly tools: {
1199
+ readonly GET_BROWSER_TOOL_ENABLED: "tools:getBrowserToolEnabled";
1200
+ readonly SET_BROWSER_TOOL_ENABLED: "tools:setBrowserToolEnabled";
1201
+ };
1202
+ readonly caching: {
1203
+ readonly GET_EXTENDED_PROMPT_CACHE: "caching:getExtendedPromptCache";
1204
+ readonly SET_EXTENDED_PROMPT_CACHE: "caching:setExtendedPromptCache";
1205
+ readonly GET_ENABLE_1M_CONTEXT: "caching:getEnable1MContext";
1206
+ readonly SET_ENABLE_1M_CONTEXT: "caching:setEnable1MContext";
1207
+ };
1208
+ readonly badge: {
1209
+ readonly REFRESH: "badge:refresh";
1210
+ readonly SET_ICON: "badge:setIcon";
1211
+ readonly DRAW: "badge:draw";
1212
+ readonly DRAW_WINDOWS: "badge:draw-windows";
1213
+ };
1214
+ readonly releaseNotes: {
1215
+ readonly GET: "releaseNotes:get";
1216
+ readonly GET_LATEST_VERSION: "releaseNotes:getLatestVersion";
1217
+ };
1218
+ readonly git: {
1219
+ readonly GET_BRANCH: "git:getBranch";
1220
+ };
1221
+ readonly gitbash: {
1222
+ readonly CHECK: "gitbash:check";
1223
+ readonly BROWSE: "gitbash:browse";
1224
+ readonly SET_PATH: "gitbash:setPath";
1225
+ };
1226
+ readonly browserPane: {
1227
+ readonly CREATE: "browser-pane:create";
1228
+ readonly DESTROY: "browser-pane:destroy";
1229
+ readonly LIST: "browser-pane:list";
1230
+ readonly NAVIGATE: "browser-pane:navigate";
1231
+ readonly GO_BACK: "browser-pane:go-back";
1232
+ readonly GO_FORWARD: "browser-pane:go-forward";
1233
+ readonly RELOAD: "browser-pane:reload";
1234
+ readonly STOP: "browser-pane:stop";
1235
+ readonly FOCUS: "browser-pane:focus";
1236
+ readonly SNAPSHOT: "browser-pane:snapshot";
1237
+ readonly CLICK: "browser-pane:click";
1238
+ readonly FILL: "browser-pane:fill";
1239
+ readonly SELECT: "browser-pane:select";
1240
+ readonly SCREENSHOT: "browser-pane:screenshot";
1241
+ readonly EVALUATE: "browser-pane:evaluate";
1242
+ readonly SCROLL: "browser-pane:scroll";
1243
+ readonly LAUNCH: "browser-empty-state:launch";
1244
+ readonly STATE_CHANGED: "browser-pane:state-changed";
1245
+ readonly REMOVED: "browser-pane:removed";
1246
+ readonly INTERACTED: "browser-pane:interacted";
1247
+ };
1248
+ readonly automations: {
1249
+ readonly GET: "automations:get";
1250
+ readonly TEST: "automations:test";
1251
+ readonly SET_ENABLED: "automations:setEnabled";
1252
+ readonly DUPLICATE: "automations:duplicate";
1253
+ readonly DELETE: "automations:delete";
1254
+ readonly GET_HISTORY: "automations:getHistory";
1255
+ readonly GET_LAST_EXECUTED: "automations:getLastExecuted";
1256
+ readonly REPLAY: "automations:replay";
1257
+ readonly CHANGED: "automations:changed";
1258
+ };
1259
+ readonly resources: {
1260
+ readonly EXPORT: "resources:export";
1261
+ readonly IMPORT: "resources:import";
1262
+ };
1263
+ readonly messaging: {
1264
+ readonly WA_REGISTER: "messaging:wa:register";
1265
+ readonly WA_INCOMING: "messaging:wa:incoming";
1266
+ readonly WA_BUTTON_PRESS: "messaging:wa:buttonPress";
1267
+ readonly WA_STATUS: "messaging:wa:status";
1268
+ readonly WA_QR: "messaging:wa:qr";
1269
+ readonly WA_SEND: "messaging:wa:send";
1270
+ readonly WA_SEND_BUTTONS: "messaging:wa:sendButtons";
1271
+ readonly WA_SEND_TYPING: "messaging:wa:sendTyping";
1272
+ readonly WA_SEND_FILE: "messaging:wa:sendFile";
1273
+ readonly WA_CONNECT: "messaging:wa:connect";
1274
+ readonly WA_DISCONNECT: "messaging:wa:disconnect";
1275
+ readonly BINDING_CHANGED: "messaging:bindingChanged";
1276
+ readonly PLATFORM_STATUS: "messaging:platformStatus";
1277
+ /** Broadcast when the workspace's pending-senders list mutates. */
1278
+ readonly PENDING_CHANGED: "messaging:pendingChanged";
1279
+ readonly GET_CONFIG: "messaging:getConfig";
1280
+ readonly UPDATE_CONFIG: "messaging:updateConfig";
1281
+ readonly TEST_TELEGRAM: "messaging:testTelegram";
1282
+ readonly SAVE_TELEGRAM: "messaging:saveTelegram";
1283
+ readonly TEST_LARK: "messaging:testLark";
1284
+ readonly SAVE_LARK: "messaging:saveLark";
1285
+ readonly DISCONNECT: "messaging:disconnect";
1286
+ readonly FORGET: "messaging:forget";
1287
+ readonly GET_BINDINGS: "messaging:getBindings";
1288
+ readonly GENERATE_CODE: "messaging:generateCode";
1289
+ readonly UNBIND: "messaging:unbind";
1290
+ readonly UNBIND_BINDING: "messaging:unbindBinding";
1291
+ /** Workspace-supergroup pairing (Telegram forum support). UI ↔ Server. */
1292
+ readonly GENERATE_SUPERGROUP_CODE: "messaging:generateSupergroupCode";
1293
+ readonly GET_SUPERGROUP: "messaging:getSupergroup";
1294
+ readonly UNBIND_SUPERGROUP: "messaging:unbindSupergroup";
1295
+ readonly WA_START_CONNECT: "messaging:wa:startConnect";
1296
+ readonly WA_SUBMIT_PHONE: "messaging:wa:submitPhone";
1297
+ /** Broadcast to UI clients: QR string, pairing code, status, unavailable, error. */
1298
+ readonly WA_UI_EVENT: "messaging:wa:uiEvent";
1299
+ readonly GET_PLATFORM_OWNERS: "messaging:access:getOwners";
1300
+ readonly SET_PLATFORM_OWNERS: "messaging:access:setOwners";
1301
+ readonly GET_PLATFORM_ACCESS_MODE: "messaging:access:getMode";
1302
+ readonly SET_PLATFORM_ACCESS_MODE: "messaging:access:setMode";
1303
+ readonly GET_PENDING_SENDERS: "messaging:access:getPending";
1304
+ readonly DISMISS_PENDING_SENDER: "messaging:access:dismissPending";
1305
+ readonly ALLOW_PENDING_SENDER: "messaging:access:allowPending";
1306
+ readonly SET_BINDING_ACCESS: "messaging:access:setBindingAccess";
1307
+ };
1308
+ };
1309
+
1310
+ /**
1311
+ * Typed event map for server → client push channels.
1312
+ * Keys are channel string literals, values are argument tuples.
1313
+ */
1314
+
1315
+ interface BroadcastEventMap {
1316
+ [RPC_CHANNELS.sessions.EVENT]: [event: SessionEvent];
1317
+ [RPC_CHANNELS.sessions.UNREAD_SUMMARY_CHANGED]: [summary: UnreadSummary];
1318
+ [RPC_CHANNELS.sessions.FILES_CHANGED]: [sessionId: string];
1319
+ [RPC_CHANNELS.sources.CHANGED]: [workspaceId: string, sources: unknown[]];
1320
+ [RPC_CHANNELS.labels.CHANGED]: [workspaceId: string];
1321
+ [RPC_CHANNELS.statuses.CHANGED]: [workspaceId: string];
1322
+ [RPC_CHANNELS.automations.CHANGED]: [workspaceId: string];
1323
+ [RPC_CHANNELS.skills.CHANGED]: [workspaceId: string, skills: unknown[]];
1324
+ [RPC_CHANNELS.llmConnections.CHANGED]: [];
1325
+ [RPC_CHANNELS.permissions.DEFAULTS_CHANGED]: [value: null];
1326
+ [RPC_CHANNELS.theme.APP_CHANGED]: [theme: Record<string, unknown> | null];
1327
+ [RPC_CHANNELS.theme.SYSTEM_CHANGED]: [isDark: boolean];
1328
+ [RPC_CHANNELS.theme.PREFERENCES_CHANGED]: [preferences: {
1329
+ mode: string;
1330
+ colorTheme: string;
1331
+ font: string;
1332
+ }];
1333
+ [RPC_CHANNELS.theme.WORKSPACE_THEME_CHANGED]: [data: {
1334
+ workspaceId: string;
1335
+ themeId: string | null;
1336
+ }];
1337
+ [RPC_CHANNELS.update.AVAILABLE]: [info: UpdateInfo];
1338
+ [RPC_CHANNELS.update.DOWNLOAD_PROGRESS]: [progress: number];
1339
+ [RPC_CHANNELS.badge.DRAW]: [data: {
1340
+ count: number;
1341
+ iconDataUrl: string;
1342
+ }];
1343
+ [RPC_CHANNELS.badge.DRAW_WINDOWS]: [data: {
1344
+ count: number;
1345
+ }];
1346
+ [RPC_CHANNELS.window.FOCUS_STATE]: [isFocused: boolean];
1347
+ [RPC_CHANNELS.window.CLOSE_REQUESTED]: [];
1348
+ [RPC_CHANNELS.browserPane.STATE_CHANGED]: [info: BrowserInstanceInfo];
1349
+ [RPC_CHANNELS.browserPane.REMOVED]: [id: string];
1350
+ [RPC_CHANNELS.browserPane.INTERACTED]: [id: string];
1351
+ [RPC_CHANNELS.notification.NAVIGATE]: [data: {
1352
+ workspaceId: string;
1353
+ sessionId: string;
1354
+ }];
1355
+ [RPC_CHANNELS.deeplink.NAVIGATE]: [navigation: DeepLinkNavigation];
1356
+ [RPC_CHANNELS.copilot.DEVICE_CODE]: [data: {
1357
+ userCode: string;
1358
+ verificationUri: string;
1359
+ }];
1360
+ [RPC_CHANNELS.menu.NEW_CHAT]: [];
1361
+ [RPC_CHANNELS.menu.OPEN_SETTINGS]: [];
1362
+ [RPC_CHANNELS.menu.KEYBOARD_SHORTCUTS]: [];
1363
+ [RPC_CHANNELS.menu.TOGGLE_FOCUS_MODE]: [];
1364
+ [RPC_CHANNELS.menu.TOGGLE_SIDEBAR]: [];
1365
+ [RPC_CHANNELS.messaging.BINDING_CHANGED]: [workspaceId: string];
1366
+ [RPC_CHANNELS.messaging.PLATFORM_STATUS]: [workspaceId: string, platform: string, connected: boolean];
1367
+ }
1368
+
1369
+ interface ParsedMentions {
1370
+ skills: string[];
1371
+ invalidSkills: string[];
1372
+ sources: string[];
1373
+ files: string[];
1374
+ folders: string[];
1375
+ }
1376
+ interface MentionMatch {
1377
+ type: 'skill' | 'source' | 'file' | 'folder';
1378
+ id: string;
1379
+ fullMatch: string;
1380
+ startIndex: number;
1381
+ }
1382
+
1383
+ declare function parseMentions(text: string, availableSkillSlugs: string[], availableSourceSlugs: string[]): ParsedMentions;
1384
+ declare function resolveSkillMentions(text: string, skillNames: Map<string, string>): string;
1385
+ declare function resolveSourceMentions(text: string): string;
1386
+ declare function resolvePathMentions(text: string, workingDirectory?: string): Promise<string>;
1387
+ declare function resolveFileMentions(text: string, workingDirectory?: string): Promise<string>;
1388
+ declare function stripAllMentions(text: string): string;
1389
+ declare function findMentionMatches(text: string, availableSkillSlugs: string[], availableSourceSlugs: string[]): MentionMatch[];
1390
+
1391
+ export { AnnotationV1, type AuthRequest, AuthRequestType, type BroadcastEventMap, type BrowserInstanceInfo, type BuiltInStatusId, type ClaudeOAuthResult, ContentBadge, type CreateSessionOptions, CredentialInputMode, type CredentialRequest, type CredentialResponse, type DeepLinkNavigation, type DirectoryListingResult, type FileAttachment, type FileSearchResult, type GitBashStatus, type ImportRemoteSessionTransferResult, type LlmConnectionSetup, type McpToolWithPermission, type McpToolsResult, type McpValidationResult, type MentionMatch, Message, type NewChatActionParams, type OAuthResult, type ParsedMentions, type PermissionMode, type PermissionModeCanonical, type PermissionModeState, PermissionRequest$1 as PermissionRequest, type PermissionResponseOptions, type Plan, type PlanStep, type Session as ProtocolSession, RPC_CHANNELS, type RefreshTitleResult, type RemoteSessionTransferPayload, type SendMessageOptions, type SessionCommand, type SessionEvent, type SessionFile, type PermissionRequest as SessionPermissionRequest, type SessionSearchMatch, type SessionSearchResult, type ShareResult, type SkillFile, THINKING_LEVELS, THINKING_LEVEL_IDS, THINKING_TO_EFFORT, type TestAutomationAction, type TestAutomationActionResult, type TestAutomationPayload, type TestAutomationResult, type TestLlmConnectionParams, type TestLlmConnectionResult, type ThinkingLevel, ToolDisplayMeta, TypedError, type UnreadSummary, type UpdateInfo, type WindowCloseRequest, type WindowCloseRequestSource, type WorkspaceSettings, findMentionMatches, getThinkingLevelNameKey, getThinkingTokens, isValidThinkingLevel, normalizeThinkingLevel, parseMentions, resolveFileMentions, resolvePathMentions, resolveSkillMentions, resolveSourceMentions, stripAllMentions };
1392
+
1393
+ // -- @weft/core/types/index.d.ts --
1394
+ /**
1395
+ * Workspace and authentication types
1396
+ */
1397
+ /**
1398
+ * How MCP server should be authenticated (workspace-level)
1399
+ * Note: Different from SourceMcpAuthType which uses 'oauth' | 'bearer' | 'none' for individual sources
1400
+ */
1401
+ type McpAuthType = 'workspace_oauth' | 'workspace_bearer' | 'public';
1402
+ /**
1403
+ * Configuration for a remote Agent Server.
1404
+ * When set on a workspace, handler calls are proxied over WebSocket.
1405
+ */
1406
+ interface RemoteServerConfig {
1407
+ url: string;
1408
+ token: string;
1409
+ remoteWorkspaceId: string;
1410
+ }
1411
+ /**
1412
+ * Client-facing workspace DTO — safe to send over RPC to remote clients.
1413
+ * Does not expose server-internal filesystem paths.
1414
+ */
1415
+ interface WorkspaceInfo {
1416
+ id: string;
1417
+ name: string;
1418
+ slug: string;
1419
+ lastAccessedAt?: number;
1420
+ iconUrl?: string;
1421
+ mcpUrl?: string;
1422
+ mcpAuthType?: McpAuthType;
1423
+ remoteServer?: RemoteServerConfig;
1424
+ }
1425
+ /**
1426
+ * Full workspace with server-internal details.
1427
+ * Used by server code and local Electron renderer (LOCAL_ONLY channels).
1428
+ */
1429
+ interface Workspace extends WorkspaceInfo {
1430
+ rootPath: string;
1431
+ createdAt: number;
1432
+ }
1433
+ /**
1434
+ * Authentication type for AI provider
1435
+ * - api_key: Anthropic API key
1436
+ * - oauth_token: Claude Max OAuth (Anthropic)
1437
+ * - codex_oauth: ChatGPT Plus OAuth via Codex app-server
1438
+ * - codex_api_key: OpenAI API key via Codex (OpenRouter, Vercel AI Gateway compatible)
1439
+ * - provider_owned: Auth is owned by the provider tool itself
1440
+ * (Claude Code uses `~/.claude`, Codex uses `~/.codex`).
1441
+ * Weft never injects credentials — it detects and delegates.
1442
+ */
1443
+ type AuthType = 'api_key' | 'oauth_token' | 'codex_oauth' | 'codex_api_key' | 'provider_owned';
1444
+ /**
1445
+ * OAuth credentials from a fresh authentication flow.
1446
+ * Used for temporary state in UI components before saving to credential store.
1447
+ */
1448
+ interface OAuthCredentials {
1449
+ accessToken: string;
1450
+ refreshToken?: string;
1451
+ expiresAt?: number;
1452
+ clientId: string;
1453
+ tokenType: string;
1454
+ }
1455
+ interface StoredConfig {
1456
+ authType?: AuthType;
1457
+ workspaces: Workspace[];
1458
+ activeWorkspaceId: string | null;
1459
+ activeSessionId: string | null;
1460
+ model?: string;
1461
+ }
1462
+
1463
+ /**
1464
+ * Message types for conversations
1465
+ */
1466
+ /**
1467
+ * Message roles for display (runtime)
1468
+ */
1469
+ type MessageRole = 'user' | 'assistant' | 'tool' | 'error' | 'status' | 'info' | 'warning' | 'plan' | 'auth-request';
1470
+ /**
1471
+ * Credential input modes for different auth types
1472
+ */
1473
+ type CredentialInputMode = 'bearer' | 'basic' | 'header' | 'query' | 'multi-header';
1474
+ /**
1475
+ * Auth request types
1476
+ */
1477
+ type AuthRequestType = 'credential' | 'oauth' | 'oauth-google' | 'oauth-slack' | 'oauth-microsoft';
1478
+ /**
1479
+ * Auth request status
1480
+ */
1481
+ type AuthStatus = 'pending' | 'completed' | 'cancelled' | 'failed';
1482
+ /**
1483
+ * Tool execution status
1484
+ */
1485
+ type ToolStatus = 'pending' | 'executing' | 'completed' | 'error' | 'backgrounded';
1486
+ /**
1487
+ * Tool display metadata - embedded at storage time for viewer compatibility
1488
+ * Icons are base64-encoded to work in both Electron and web viewer
1489
+ */
1490
+ interface ToolDisplayMeta {
1491
+ /** Display name for the tool (e.g., "Commit", "Linear") */
1492
+ displayName: string;
1493
+ /** Base64-encoded icon as data URL (e.g., "data:image/png;base64,...") - 32x32px */
1494
+ iconDataUrl?: string;
1495
+ /** Description of what this tool does */
1496
+ description?: string;
1497
+ /** Category for grouping/styling */
1498
+ category?: 'skill' | 'source' | 'native' | 'mcp';
1499
+ }
1500
+ /**
1501
+ * Attachment type categories
1502
+ */
1503
+ type AttachmentType = 'image' | 'text' | 'pdf' | 'office' | 'audio' | 'unknown';
1504
+ /**
1505
+ * Attachment preview for display in user messages (runtime, before storage)
1506
+ */
1507
+ interface MessageAttachment {
1508
+ type: AttachmentType;
1509
+ name: string;
1510
+ mimeType: string;
1511
+ size: number;
1512
+ base64?: string;
1513
+ }
1514
+ /**
1515
+ * Content badge for inline display in user messages
1516
+ * Badges are self-contained with all display data (label, icon)
1517
+ */
1518
+ interface ContentBadge {
1519
+ /** Badge type - used for fallback icon if iconBase64 not available */
1520
+ type: 'source' | 'skill' | 'context' | 'command' | 'file' | 'folder';
1521
+ /** Display label (e.g., "Linear", "Commit") */
1522
+ label: string;
1523
+ /** Original text pattern (e.g., "@linear", "@commit") */
1524
+ rawText: string;
1525
+ /** Icon as data URL (e.g., "data:image/png;base64,...") - preserves mime type */
1526
+ iconDataUrl?: string;
1527
+ /** Start position in content string */
1528
+ start: number;
1529
+ /** End position in content string */
1530
+ end: number;
1531
+ /**
1532
+ * Collapsed label for context badges (e.g., "Edit: Permissions")
1533
+ * When set, the badge replaces the entire marked range with this label
1534
+ * and hides the original content
1535
+ */
1536
+ collapsedLabel?: string;
1537
+ /**
1538
+ * File path for file badges - stores the full path for click handler
1539
+ * Used when the badge represents a clickable file reference
1540
+ */
1541
+ filePath?: string;
1542
+ }
1543
+ /**
1544
+ * Author metadata for annotations
1545
+ */
1546
+ interface AnnotationAuthor {
1547
+ id: string;
1548
+ name?: string;
1549
+ type?: 'user' | 'agent' | 'system';
1550
+ }
1551
+ /**
1552
+ * Annotation body payloads (extensible)
1553
+ */
1554
+ type AnnotationBody = {
1555
+ type: 'highlight';
1556
+ } | {
1557
+ type: 'note';
1558
+ text: string;
1559
+ format?: 'plain' | 'markdown';
1560
+ } | {
1561
+ type: 'tag';
1562
+ value: string;
1563
+ };
1564
+ /**
1565
+ * Annotation intent (tight v1 semantics).
1566
+ */
1567
+ type AnnotationIntent = 'highlight' | 'comment' | 'question';
1568
+ /**
1569
+ * Optional lifecycle status for annotation workflows.
1570
+ */
1571
+ type AnnotationStatus = 'pending' | 'acknowledged' | 'resolved' | 'dismissed';
1572
+ /**
1573
+ * Block types for block selectors.
1574
+ */
1575
+ type AnnotationBlockType = 'paragraph' | 'code' | 'latex' | 'mermaid' | 'datatable' | 'spreadsheet' | 'image-preview' | 'pdf-preview' | 'html-preview';
1576
+ /**
1577
+ * Selector union used to anchor an annotation target.
1578
+ * Multiple selectors can be stored for robust fallback resolution.
1579
+ */
1580
+ type AnnotationSelector = {
1581
+ type: 'text-quote';
1582
+ exact: string;
1583
+ prefix?: string;
1584
+ suffix?: string;
1585
+ } | {
1586
+ type: 'text-position';
1587
+ start: number;
1588
+ end: number;
1589
+ textVersion?: string;
1590
+ } | {
1591
+ type: 'block';
1592
+ blockType: AnnotationBlockType;
1593
+ path: string;
1594
+ blockId?: string;
1595
+ } | {
1596
+ type: 'xywh';
1597
+ unit: 'pixel' | 'percent';
1598
+ x: number;
1599
+ y: number;
1600
+ w: number;
1601
+ h: number;
1602
+ page?: number;
1603
+ rotation?: number;
1604
+ } | {
1605
+ type: 'table-cell';
1606
+ rowKey: string | number;
1607
+ columnKey: string;
1608
+ };
1609
+ /**
1610
+ * Annotation target definition.
1611
+ */
1612
+ interface AnnotationTarget {
1613
+ source: {
1614
+ sessionId: string;
1615
+ messageId: string;
1616
+ };
1617
+ selectors: AnnotationSelector[];
1618
+ }
1619
+ /**
1620
+ * Persisted annotation payload (schema-versioned for migration safety).
1621
+ */
1622
+ interface AnnotationV1 {
1623
+ id: string;
1624
+ schemaVersion: 1;
1625
+ createdAt: number;
1626
+ updatedAt?: number;
1627
+ createdBy?: AnnotationAuthor;
1628
+ deletedAt?: number;
1629
+ body: AnnotationBody[];
1630
+ target: AnnotationTarget;
1631
+ /** Optional workflow intent (tight v1 semantics). */
1632
+ intent?: AnnotationIntent;
1633
+ /** Optional lifecycle status. */
1634
+ status?: AnnotationStatus;
1635
+ /** Optional reference to the conversation/thread around this annotation. */
1636
+ threadRef?: {
1637
+ threadId?: string;
1638
+ sessionId?: string;
1639
+ };
1640
+ style?: {
1641
+ color?: 'yellow' | 'green' | 'blue' | 'pink' | string;
1642
+ opacity?: number;
1643
+ };
1644
+ meta?: Record<string, unknown>;
1645
+ }
1646
+ /**
1647
+ * Stored attachment metadata (persisted to disk, no base64)
1648
+ * Created when user sends a message with attachments
1649
+ */
1650
+ interface StoredAttachment {
1651
+ id: string;
1652
+ type: AttachmentType;
1653
+ name: string;
1654
+ mimeType: string;
1655
+ size: number;
1656
+ originalSize?: number;
1657
+ storedPath: string;
1658
+ thumbnailPath?: string;
1659
+ thumbnailBase64?: string;
1660
+ markdownPath?: string;
1661
+ wasResized?: boolean;
1662
+ resizedBase64?: string;
1663
+ }
1664
+ /**
1665
+ * Runtime message type (includes transient fields like isStreaming)
1666
+ */
1667
+ interface Message {
1668
+ id: string;
1669
+ role: MessageRole;
1670
+ content: string;
1671
+ timestamp: number;
1672
+ toolName?: string;
1673
+ toolUseId?: string;
1674
+ toolInput?: Record<string, unknown>;
1675
+ toolResult?: string;
1676
+ toolStatus?: ToolStatus;
1677
+ toolDuration?: number;
1678
+ toolIntent?: string;
1679
+ toolDisplayName?: string;
1680
+ /** Tool display metadata with base64 icon - embedded at storage time for viewer */
1681
+ toolDisplayMeta?: ToolDisplayMeta;
1682
+ parentToolUseId?: string;
1683
+ taskId?: string;
1684
+ shellId?: string;
1685
+ elapsedSeconds?: number;
1686
+ isBackground?: boolean;
1687
+ attachments?: StoredAttachment[];
1688
+ badges?: ContentBadge[];
1689
+ /** Annotation payloads for this message */
1690
+ annotations?: AnnotationV1[];
1691
+ isError?: boolean;
1692
+ isStreaming?: boolean;
1693
+ isPending?: boolean;
1694
+ isQueued?: boolean;
1695
+ isIntermediate?: boolean;
1696
+ turnId?: string;
1697
+ statusType?: 'compacting' | 'compaction_complete';
1698
+ infoLevel?: 'info' | 'warning' | 'error' | 'success';
1699
+ errorCode?: string;
1700
+ errorTitle?: string;
1701
+ errorDetails?: string[];
1702
+ errorOriginal?: string;
1703
+ errorCanRetry?: boolean;
1704
+ errorActions?: Array<{
1705
+ key: string;
1706
+ label: string;
1707
+ action?: 'retry' | 'settings' | 'reauth' | 'open_url' | 'reconnect_source';
1708
+ url?: string;
1709
+ sourceSlug?: string;
1710
+ }>;
1711
+ planPath?: string;
1712
+ authRequestId?: string;
1713
+ authRequestType?: AuthRequestType;
1714
+ authSourceSlug?: string;
1715
+ authSourceName?: string;
1716
+ authStatus?: AuthStatus;
1717
+ authCredentialMode?: CredentialInputMode;
1718
+ authHeaderName?: string;
1719
+ authHeaderNames?: string[];
1720
+ authLabels?: {
1721
+ credential?: string;
1722
+ username?: string;
1723
+ password?: string;
1724
+ };
1725
+ authDescription?: string;
1726
+ authHint?: string;
1727
+ authSourceUrl?: string;
1728
+ authPasswordRequired?: boolean;
1729
+ authError?: string;
1730
+ authEmail?: string;
1731
+ authWorkspace?: string;
1732
+ }
1733
+ /**
1734
+ * Stored message format (persistence)
1735
+ * Excludes transient runtime-only fields (isStreaming, isPending)
1736
+ */
1737
+ interface StoredMessage {
1738
+ id: string;
1739
+ type: MessageRole;
1740
+ content: string;
1741
+ timestamp?: number;
1742
+ toolName?: string;
1743
+ toolUseId?: string;
1744
+ toolInput?: Record<string, unknown>;
1745
+ toolResult?: string;
1746
+ toolStatus?: ToolStatus;
1747
+ toolDuration?: number;
1748
+ toolIntent?: string;
1749
+ toolDisplayName?: string;
1750
+ /** Tool display metadata with base64 icon - embedded at storage time for viewer */
1751
+ toolDisplayMeta?: ToolDisplayMeta;
1752
+ parentToolUseId?: string;
1753
+ taskId?: string;
1754
+ shellId?: string;
1755
+ elapsedSeconds?: number;
1756
+ isBackground?: boolean;
1757
+ isError?: boolean;
1758
+ /** Stored attachments for user messages (persisted to disk) */
1759
+ attachments?: StoredAttachment[];
1760
+ /** Content badges for inline display (sources, skills) */
1761
+ badges?: ContentBadge[];
1762
+ /** Annotations persisted at message level */
1763
+ annotations?: AnnotationV1[];
1764
+ isIntermediate?: boolean;
1765
+ turnId?: string;
1766
+ statusType?: 'compacting' | 'compaction_complete';
1767
+ infoLevel?: 'info' | 'warning' | 'error' | 'success';
1768
+ errorCode?: string;
1769
+ errorTitle?: string;
1770
+ errorDetails?: string[];
1771
+ errorOriginal?: string;
1772
+ errorCanRetry?: boolean;
1773
+ errorActions?: Array<{
1774
+ key: string;
1775
+ label: string;
1776
+ action?: 'retry' | 'settings' | 'reauth' | 'open_url' | 'reconnect_source';
1777
+ url?: string;
1778
+ sourceSlug?: string;
1779
+ }>;
1780
+ planPath?: string;
1781
+ authRequestId?: string;
1782
+ authRequestType?: AuthRequestType;
1783
+ authSourceSlug?: string;
1784
+ authSourceName?: string;
1785
+ authStatus?: AuthStatus;
1786
+ authCredentialMode?: CredentialInputMode;
1787
+ authHeaderName?: string;
1788
+ authHeaderNames?: string[];
1789
+ authLabels?: {
1790
+ credential?: string;
1791
+ username?: string;
1792
+ password?: string;
1793
+ };
1794
+ authDescription?: string;
1795
+ authHint?: string;
1796
+ authSourceUrl?: string;
1797
+ authPasswordRequired?: boolean;
1798
+ authError?: string;
1799
+ authEmail?: string;
1800
+ authWorkspace?: string;
1801
+ isQueued?: boolean;
1802
+ }
1803
+ /**
1804
+ * Token usage tracking
1805
+ */
1806
+ interface TokenUsage {
1807
+ inputTokens: number;
1808
+ outputTokens: number;
1809
+ totalTokens: number;
1810
+ contextTokens: number;
1811
+ costUsd: number;
1812
+ cacheReadTokens?: number;
1813
+ cacheCreationTokens?: number;
1814
+ }
1815
+ /**
1816
+ * Recovery action for typed errors
1817
+ */
1818
+ interface RecoveryAction {
1819
+ /** Keyboard shortcut (single letter) */
1820
+ key: string;
1821
+ /** Description of the action */
1822
+ label: string;
1823
+ /** Slash command to execute (e.g., '/settings') */
1824
+ command?: string;
1825
+ /** Custom action type for special handling */
1826
+ action?: 'retry' | 'settings' | 'reauth' | 'open_url' | 'reconnect_source';
1827
+ /** URL to open (for open_url action) */
1828
+ url?: string;
1829
+ /** Source slug (for reconnect_source action) */
1830
+ sourceSlug?: string;
1831
+ }
1832
+ /**
1833
+ * Error codes for typed errors - must match AgentError.code in shared/agent/errors.ts
1834
+ */
1835
+ type ErrorCode = 'invalid_api_key' | 'invalid_credentials' | 'response_too_large' | 'expired_oauth_token' | 'token_expired' | 'rate_limited' | 'service_error' | 'service_unavailable' | 'network_error' | 'proxy_error' | 'mcp_auth_required' | 'mcp_unreachable' | 'billing_error' | 'model_no_tool_support' | 'invalid_model' | 'data_policy_error' | 'invalid_request' | 'image_too_large' | 'provider_error' | 'queued_message_replay_failed' | 'sdk_binary_missing' | 'sdk_cwd_missing' | 'unknown_error';
1836
+ /**
1837
+ * Typed error from agent
1838
+ */
1839
+ interface TypedError {
1840
+ /** Error code for programmatic handling */
1841
+ code: ErrorCode;
1842
+ /** User-friendly title */
1843
+ title: string;
1844
+ /** Detailed message explaining what went wrong */
1845
+ message: string;
1846
+ /** Suggested recovery actions */
1847
+ actions: RecoveryAction[];
1848
+ /** Whether auto-retry is possible */
1849
+ canRetry: boolean;
1850
+ /** Retry delay in ms (if canRetry is true) */
1851
+ retryDelayMs?: number;
1852
+ /** Diagnostic check results for debugging */
1853
+ details?: string[];
1854
+ /** Original error message for debugging */
1855
+ originalError?: string;
1856
+ }
1857
+ /**
1858
+ * Permission request type categories
1859
+ */
1860
+ type PermissionRequestType = 'bash' | 'file_write' | 'mcp_mutation' | 'api_mutation' | 'admin_approval';
1861
+ /**
1862
+ * Permission request from agent (e.g., bash command approval)
1863
+ */
1864
+ interface PermissionRequest {
1865
+ requestId: string;
1866
+ toolName: string;
1867
+ command?: string;
1868
+ description: string;
1869
+ type?: PermissionRequestType;
1870
+ /** Friendly app/package label for admin approval prompts */
1871
+ appName?: string;
1872
+ /** Plain-language reason shown in admin approval prompt */
1873
+ reason?: string;
1874
+ /** Plain-language impact shown in admin approval prompt */
1875
+ impact?: string;
1876
+ /** Whether native OS auth prompt is expected */
1877
+ requiresSystemPrompt?: boolean;
1878
+ /** Optional remember window for this exact command */
1879
+ rememberForMinutes?: number;
1880
+ /** Hash binding for approval integrity checks */
1881
+ commandHash?: string;
1882
+ /** Approval validity window */
1883
+ approvalTtlSeconds?: number;
1884
+ }
1885
+ /**
1886
+ * Usage data emitted by the agent runtime in 'complete' events
1887
+ * Note: This is a subset of TokenUsage - totalTokens/contextTokens are computed by consumers
1888
+ */
1889
+ interface AgentEventUsage {
1890
+ inputTokens: number;
1891
+ outputTokens: number;
1892
+ cacheReadTokens?: number;
1893
+ cacheCreationTokens?: number;
1894
+ costUsd?: number;
1895
+ /** Model's context window size in tokens (from SDK modelUsage) */
1896
+ contextWindow?: number;
1897
+ }
1898
+ /**
1899
+ * Events emitted by the agent runtime during chat
1900
+ * turnId: Correlation ID from the API's message.id, groups all events in an assistant turn
1901
+ */
1902
+ type AgentEvent = {
1903
+ type: 'status';
1904
+ message: string;
1905
+ } | {
1906
+ type: 'info';
1907
+ message: string;
1908
+ } | {
1909
+ type: 'text_delta';
1910
+ text: string;
1911
+ turnId?: string;
1912
+ parentToolUseId?: string;
1913
+ } | {
1914
+ type: 'text_complete';
1915
+ text: string;
1916
+ isIntermediate?: boolean;
1917
+ turnId?: string;
1918
+ parentToolUseId?: string;
1919
+ sdkTurnAnchor?: string;
1920
+ } | {
1921
+ type: 'tool_start';
1922
+ toolName: string;
1923
+ toolUseId: string;
1924
+ input: Record<string, unknown>;
1925
+ intent?: string;
1926
+ displayName?: string;
1927
+ turnId?: string;
1928
+ parentToolUseId?: string;
1929
+ toolDisplayMeta?: ToolDisplayMeta;
1930
+ } | {
1931
+ type: 'tool_result';
1932
+ toolUseId: string;
1933
+ toolName?: string;
1934
+ result: string;
1935
+ isError: boolean;
1936
+ input?: Record<string, unknown>;
1937
+ turnId?: string;
1938
+ parentToolUseId?: string;
1939
+ } | {
1940
+ type: 'permission_request';
1941
+ requestId: string;
1942
+ toolName: string;
1943
+ command?: string;
1944
+ description: string;
1945
+ permissionType?: PermissionRequestType;
1946
+ appName?: string;
1947
+ reason?: string;
1948
+ impact?: string;
1949
+ requiresSystemPrompt?: boolean;
1950
+ rememberForMinutes?: number;
1951
+ commandHash?: string;
1952
+ approvalTtlSeconds?: number;
1953
+ } | {
1954
+ type: 'reasoning_delta';
1955
+ text: string;
1956
+ turnId?: string;
1957
+ } | {
1958
+ type: 'reasoning';
1959
+ text: string;
1960
+ turnId?: string;
1961
+ } | {
1962
+ type: 'permission_response';
1963
+ requestId: string;
1964
+ allowed: boolean;
1965
+ remember?: boolean;
1966
+ } | {
1967
+ type: 'error';
1968
+ message: string;
1969
+ } | {
1970
+ type: 'typed_error';
1971
+ error: TypedError;
1972
+ } | {
1973
+ type: 'complete';
1974
+ usage?: AgentEventUsage;
1975
+ } | {
1976
+ type: 'working_directory_changed';
1977
+ workingDirectory: string;
1978
+ } | {
1979
+ type: 'task_backgrounded';
1980
+ toolUseId: string;
1981
+ taskId: string;
1982
+ intent?: string;
1983
+ turnId?: string;
1984
+ } | {
1985
+ type: 'shell_backgrounded';
1986
+ toolUseId: string;
1987
+ shellId: string;
1988
+ intent?: string;
1989
+ command?: string;
1990
+ turnId?: string;
1991
+ } | {
1992
+ type: 'task_progress';
1993
+ toolUseId: string;
1994
+ elapsedSeconds: number;
1995
+ turnId?: string;
1996
+ } | {
1997
+ type: 'task_completed';
1998
+ taskId: string;
1999
+ status: 'completed' | 'failed' | 'stopped';
2000
+ outputFile?: string;
2001
+ summary?: string;
2002
+ turnId?: string;
2003
+ } | {
2004
+ type: 'shell_killed';
2005
+ shellId: string;
2006
+ turnId?: string;
2007
+ } | {
2008
+ type: 'source_activated';
2009
+ sourceSlug: string;
2010
+ originalMessage: string;
2011
+ } | {
2012
+ type: 'usage_update';
2013
+ usage: Pick<AgentEventUsage, 'inputTokens' | 'contextWindow'>;
2014
+ } | {
2015
+ type: 'steer_undelivered';
2016
+ message: string;
2017
+ } | {
2018
+ type: 'compaction_started';
2019
+ } | {
2020
+ type: 'compaction_boundary';
2021
+ summary?: string;
2022
+ };
2023
+ /**
2024
+ * Generate a unique message ID
2025
+ */
2026
+ declare function generateMessageId(): string;
2027
+
2028
+ /**
2029
+ * Session types for conversation management
2030
+ *
2031
+ * Sessions are the primary isolation boundary. Each session maps 1:1
2032
+ * with an agent runtime instance and SDK conversation.
2033
+ */
2034
+
2035
+ /**
2036
+ * Session status for workflow tracking
2037
+ * Agents can update this to reflect the current state of the conversation
2038
+ */
2039
+ type SessionStatus = 'todo' | 'in_progress' | 'needs_review' | 'done' | 'cancelled';
2040
+ /**
2041
+ * Session represents a conversation scope (SDK session = our scope boundary)
2042
+ */
2043
+ interface Session {
2044
+ id: string;
2045
+ sdkSessionId?: string;
2046
+ workspaceId: string;
2047
+ name?: string;
2048
+ createdAt: number;
2049
+ lastUsedAt: number;
2050
+ isArchived?: boolean;
2051
+ isFlagged?: boolean;
2052
+ status?: SessionStatus;
2053
+ lastReadMessageId?: string;
2054
+ }
2055
+ /**
2056
+ * Stored session with conversation data (for persistence)
2057
+ */
2058
+ interface StoredSession extends Session {
2059
+ messages: StoredMessage[];
2060
+ tokenUsage: TokenUsage;
2061
+ }
2062
+ /**
2063
+ * Session metadata for listing (without loading full messages)
2064
+ * Extended with archive status for Inbox/Archive features
2065
+ */
2066
+ interface SessionMetadata {
2067
+ id: string;
2068
+ workspaceId: string;
2069
+ name?: string;
2070
+ createdAt: number;
2071
+ lastUsedAt: number;
2072
+ messageCount: number;
2073
+ preview?: string;
2074
+ sdkSessionId?: string;
2075
+ isArchived?: boolean;
2076
+ isFlagged?: boolean;
2077
+ status?: SessionStatus;
2078
+ hidden?: boolean;
2079
+ }
2080
+
2081
+ /**
2082
+ * Convert runtime Message to StoredMessage for persistence.
2083
+ *
2084
+ * Excludes transient runtime-only fields:
2085
+ * - isStreaming
2086
+ * - isPending
2087
+ */
2088
+ declare function messageToStored(msg: Message): StoredMessage;
2089
+ /**
2090
+ * Convert StoredMessage to runtime Message.
2091
+ *
2092
+ * Adds a timestamp fallback for legacy messages where timestamp was omitted.
2093
+ */
2094
+ declare function storedToMessage(stored: StoredMessage): Message;
2095
+
2096
+ /**
2097
+ * Server-level types for headless server operations.
2098
+ *
2099
+ * These types are used by the `server:` RPC namespace for
2100
+ * server status, health checks, active session discovery,
2101
+ * and headless configuration bootstrap.
2102
+ */
2103
+ interface ServerStatus {
2104
+ serverId: string;
2105
+ version: string;
2106
+ uptime: number;
2107
+ connectedClients: number;
2108
+ workspaces: {
2109
+ id: string;
2110
+ name: string;
2111
+ slug: string;
2112
+ activeSessions: number;
2113
+ automationCount: number;
2114
+ schedulerRunning: boolean;
2115
+ }[];
2116
+ memory: {
2117
+ heapUsed: number;
2118
+ heapTotal: number;
2119
+ rss: number;
2120
+ };
2121
+ }
2122
+ interface ServerHealth {
2123
+ status: 'ok' | 'degraded' | 'unhealthy';
2124
+ checks: {
2125
+ name: string;
2126
+ status: 'pass' | 'fail';
2127
+ message?: string;
2128
+ }[];
2129
+ }
2130
+ /** Session processing state — typed union, not stringly. */
2131
+ type SessionProcessingStatus = 'idle' | 'processing' | 'waiting_input' | 'error' | 'completed';
2132
+ /** Server-level active session info (cross-workspace, client-safe). */
2133
+ interface ActiveSessionInfo {
2134
+ sessionId: string;
2135
+ workspaceId: string;
2136
+ workspaceName: string;
2137
+ title?: string;
2138
+ status: SessionProcessingStatus;
2139
+ triggeredBy?: {
2140
+ automationName: string;
2141
+ timestamp: number;
2142
+ };
2143
+ createdAt: number;
2144
+ }
2145
+
2146
+ export { type ActiveSessionInfo, type AgentEvent, type AgentEventUsage, type AnnotationAuthor, type AnnotationBlockType, type AnnotationBody, type AnnotationIntent, type AnnotationSelector, type AnnotationStatus, type AnnotationTarget, type AnnotationV1, type AttachmentType, type AuthRequestType, type AuthStatus, type AuthType, type ContentBadge, type CredentialInputMode, type ErrorCode, type McpAuthType, type Message, type MessageAttachment, type MessageRole, type OAuthCredentials, type PermissionRequest, type PermissionRequestType, type RecoveryAction, type RemoteServerConfig, type ServerHealth, type ServerStatus, type Session, type SessionMetadata, type SessionProcessingStatus, type SessionStatus, type StoredAttachment, type StoredConfig, type StoredMessage, type StoredSession, type TokenUsage, type ToolDisplayMeta, type ToolStatus, type TypedError, type Workspace, type WorkspaceInfo, generateMessageId, messageToStored, storedToMessage };
2147
+
2148
+ // -- @weft/core/utils/index.d.ts --
2149
+ /**
2150
+ * Debug utility for core package
2151
+ *
2152
+ * This is a stub that can be enhanced to support debug logging.
2153
+ * Currently a no-op - use @weft debug utilities for full logging.
2154
+ */
2155
+ declare function debug(..._args: any[]): void;
2156
+
2157
+ /**
2158
+ * Cross-Platform Path Utilities
2159
+ *
2160
+ * Functions for consistent path handling across Windows, macOS, and Linux.
2161
+ * Always normalize paths to forward slashes before comparison operations.
2162
+ */
2163
+ /**
2164
+ * Normalize a path to use forward slashes for consistent cross-platform comparison.
2165
+ * Use this before comparing paths or using regex patterns on paths.
2166
+ *
2167
+ * @example
2168
+ * normalizePath('C:\\Users\\foo\\bar') // 'C:/Users/foo/bar'
2169
+ * normalizePath('/Users/foo/bar') // '/Users/foo/bar' (unchanged)
2170
+ */
2171
+ declare function normalizePath(path: string): string;
2172
+ /**
2173
+ * Check if a file path starts with a directory path (cross-platform).
2174
+ * Handles both Windows backslashes and Unix forward slashes.
2175
+ *
2176
+ * @example
2177
+ * pathStartsWith('C:\\Users\\foo\\file.txt', 'C:\\Users\\foo') // true
2178
+ * pathStartsWith('/home/user/file.txt', '/home/user') // true
2179
+ * pathStartsWith('/home/user2/file.txt', '/home/user') // false
2180
+ */
2181
+ declare function pathStartsWith(filePath: string, dirPath: string): boolean;
2182
+ /**
2183
+ * Strip a directory prefix from a path (cross-platform).
2184
+ * Returns the relative path portion after the prefix.
2185
+ *
2186
+ * @example
2187
+ * stripPathPrefix('/home/user/docs/file.txt', '/home/user') // 'docs/file.txt'
2188
+ * stripPathPrefix('C:\\foo\\bar\\baz.txt', 'C:\\foo') // 'bar/baz.txt'
2189
+ */
2190
+ declare function stripPathPrefix(filePath: string, prefix: string): string;
2191
+
2192
+ export { debug, normalizePath, pathStartsWith, stripPathPrefix };
2193
+
2194
+ // ── inlined from @weft/timeline ──
2195
+ // -- @weft/timeline/index.d.ts --
2196
+ type TimelineProvider = string;
2197
+ type TimelinePermissionScope = {
2198
+ type: 'session';
2199
+ sessionId: string;
2200
+ } | {
2201
+ type: 'workspace';
2202
+ workspaceId: string;
2203
+ } | {
2204
+ type: 'source';
2205
+ sourceSlug: string;
2206
+ } | {
2207
+ type: 'skill';
2208
+ skillSlug: string;
2209
+ } | {
2210
+ type: 'automation';
2211
+ automationId: string;
2212
+ } | {
2213
+ type: 'tool-call';
2214
+ callId: string;
2215
+ };
2216
+ type TimelineCommandOrigin = {
2217
+ type: 'user';
2218
+ id?: string;
2219
+ } | {
2220
+ type: 'automation';
2221
+ id: string;
2222
+ } | {
2223
+ type: 'scheduler';
2224
+ id?: string;
2225
+ } | {
2226
+ type: 'host';
2227
+ id?: string;
2228
+ } | {
2229
+ type: 'replay';
2230
+ id?: string;
2231
+ } | {
2232
+ type: 'system';
2233
+ id?: string;
2234
+ };
2235
+ interface ToolIntent {
2236
+ kind: string;
2237
+ command?: string;
2238
+ baseCommand?: string;
2239
+ path?: string;
2240
+ toolName?: string;
2241
+ name?: string;
2242
+ method?: string;
2243
+ url?: string;
2244
+ }
2245
+ interface TimelinePermissionRequest {
2246
+ requestId: string;
2247
+ toolName: string;
2248
+ scope?: TimelinePermissionScope;
2249
+ input?: Record<string, unknown>;
2250
+ reason?: string;
2251
+ intent?: ToolIntent;
2252
+ }
2253
+ interface TimelinePermissionResolution {
2254
+ allowed: boolean;
2255
+ remember?: boolean;
2256
+ reason?: string;
2257
+ }
2258
+ type TimelineToolStatus = 'pending' | 'running' | 'completed' | 'failed';
2259
+ type TimelineItem = {
2260
+ type: 'user_message';
2261
+ text: string;
2262
+ messageId: string;
2263
+ turnId?: string;
2264
+ } | {
2265
+ type: 'assistant_message_delta';
2266
+ text: string;
2267
+ messageId: string;
2268
+ turnId: string;
2269
+ } | {
2270
+ type: 'assistant_message';
2271
+ text: string;
2272
+ messageId: string;
2273
+ turnId: string;
2274
+ } | {
2275
+ type: 'reasoning_delta';
2276
+ text: string;
2277
+ messageId: string;
2278
+ turnId: string;
2279
+ } | {
2280
+ type: 'reasoning';
2281
+ text: string;
2282
+ messageId: string;
2283
+ turnId: string;
2284
+ } | {
2285
+ type: 'tool_call';
2286
+ callId: string;
2287
+ name: string;
2288
+ status: TimelineToolStatus;
2289
+ detail?: unknown;
2290
+ turnId?: string;
2291
+ } | {
2292
+ type: 'tool_output_delta';
2293
+ callId: string;
2294
+ text: string;
2295
+ stream?: 'stdout' | 'stderr' | string;
2296
+ turnId?: string;
2297
+ } | {
2298
+ type: 'tool_result';
2299
+ callId: string;
2300
+ result: unknown;
2301
+ isError?: boolean;
2302
+ turnId?: string;
2303
+ } | {
2304
+ type: 'permission_requested';
2305
+ request: TimelinePermissionRequest;
2306
+ } | {
2307
+ type: 'permission_resolved';
2308
+ requestId: string;
2309
+ resolution: TimelinePermissionResolution;
2310
+ } | {
2311
+ type: 'permission_policy_changed';
2312
+ policy: unknown;
2313
+ } | {
2314
+ type: 'source_state_changed';
2315
+ source: unknown;
2316
+ } | {
2317
+ type: 'skill_activated';
2318
+ skill: unknown;
2319
+ } | {
2320
+ type: 'host_state_changed';
2321
+ state: unknown;
2322
+ } | {
2323
+ type: 'automation_triggered';
2324
+ automation: {
2325
+ automationId: string;
2326
+ origin: TimelineCommandOrigin;
2327
+ detail?: unknown;
2328
+ };
2329
+ } | {
2330
+ type: 'automation_action_result';
2331
+ result: unknown;
2332
+ } | {
2333
+ type: 'runtime_capability_report';
2334
+ report: unknown;
2335
+ } | {
2336
+ type: 'runtime_fallback';
2337
+ reason: string;
2338
+ from?: string;
2339
+ to: string;
2340
+ } | {
2341
+ type: 'turn_started';
2342
+ turnId: string;
2343
+ } | {
2344
+ type: 'turn_completed';
2345
+ turnId: string;
2346
+ usage?: unknown;
2347
+ } | {
2348
+ type: 'turn_failed';
2349
+ turnId: string;
2350
+ error: unknown;
2351
+ } | {
2352
+ type: 'session_status';
2353
+ status: string;
2354
+ } | {
2355
+ type: 'tool_suspended';
2356
+ callId: string;
2357
+ name: string;
2358
+ stepId?: string;
2359
+ } | {
2360
+ type: 'tool_resumed';
2361
+ callId: string;
2362
+ name: string;
2363
+ stepId?: string;
2364
+ } | {
2365
+ type: 'compaction_started';
2366
+ } | {
2367
+ type: 'compaction_boundary';
2368
+ summary?: string;
2369
+ };
2370
+ interface TimelineRawRef {
2371
+ providerEventType?: string;
2372
+ logPath?: string;
2373
+ offset?: number;
2374
+ }
2375
+ interface TimelineEnvelope {
2376
+ sessionId: string;
2377
+ provider: TimelineProvider;
2378
+ seq: number;
2379
+ epoch: string;
2380
+ timestamp: number;
2381
+ item: TimelineItem;
2382
+ rawRef?: TimelineRawRef;
2383
+ }
2384
+ interface TimelineCursor {
2385
+ epoch: string;
2386
+ afterSeq: number;
2387
+ }
2388
+ interface TimelineFetchRequest {
2389
+ cursor?: TimelineCursor;
2390
+ limit?: number;
2391
+ }
2392
+ interface TimelineFetchResult {
2393
+ items: TimelineEnvelope[];
2394
+ nextCursor: TimelineCursor;
2395
+ hasGap: boolean;
2396
+ }
2397
+ interface CreateTimelineSequencerOptions {
2398
+ sessionId: string;
2399
+ provider: TimelineProvider;
2400
+ epoch: string;
2401
+ startSeq?: number;
2402
+ now?: () => number;
2403
+ }
2404
+ interface TimelineSequencer {
2405
+ append(item: TimelineItem, rawRef?: TimelineRawRef): TimelineEnvelope;
2406
+ }
2407
+ declare function createTimelineSequencer(options: CreateTimelineSequencerOptions): TimelineSequencer;
2408
+ declare function appendTimelineItem(envelope: TimelineEnvelope): TimelineEnvelope;
2409
+ declare function createTimelineCursor(cursor: TimelineCursor): TimelineCursor;
2410
+ declare function fetchTimeline(timeline: TimelineEnvelope[], request?: TimelineFetchRequest): TimelineFetchResult;
2411
+ declare function mergeTimeline(existing: TimelineEnvelope[], incoming: TimelineEnvelope[]): TimelineEnvelope[];
2412
+
2413
+ export { type CreateTimelineSequencerOptions, type TimelineCommandOrigin, type TimelineCursor, type TimelineEnvelope, type TimelineFetchRequest, type TimelineFetchResult, type TimelineItem, type TimelinePermissionRequest, type TimelinePermissionResolution, type TimelinePermissionScope, type TimelineProvider, type TimelineRawRef, type TimelineSequencer, type TimelineToolStatus, type ToolIntent, appendTimelineItem, createTimelineCursor, createTimelineSequencer, fetchTimeline, mergeTimeline };
2414
+
2415
+ // ── inlined from @weft/ui ──
2416
+ // -- @weft/ui/index.d.ts --
2417
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2418
+ import * as React$1 from 'react';
2419
+ import React__default, { ReactNode } from 'react';
2420
+
2421
+ type ActivityStatus = 'pending' | 'running' | 'completed' | 'error' | 'backgrounded';
2422
+ type ActivityType = 'tool' | 'thinking' | 'intermediate' | 'status' | 'plan';
2423
+ type AnnotationInteractionMode = 'interactive' | 'tooltip-only';
2424
+ type TodoStatus = 'pending' | 'in_progress' | 'completed' | 'interrupted';
2425
+ interface TodoItem {
2426
+ /** Task content/description */
2427
+ content: string;
2428
+ /** Current status */
2429
+ status: TodoStatus;
2430
+ /** Present continuous form shown when in_progress (e.g., "Running tests") */
2431
+ activeForm?: string;
2432
+ }
2433
+ interface ActivityItem {
2434
+ id: string;
2435
+ type: ActivityType;
2436
+ status: ActivityStatus;
2437
+ toolName?: string;
2438
+ toolUseId?: string;
2439
+ toolInput?: Record<string, unknown>;
2440
+ content?: string;
2441
+ intent?: string;
2442
+ /** Optional backing message id (used by plan activities for branching/annotations) */
2443
+ messageId?: string;
2444
+ /** Optional persisted annotations (used by plan activities) */
2445
+ annotations?: AnnotationV1[];
2446
+ displayName?: string;
2447
+ toolDisplayMeta?: ToolDisplayMeta;
2448
+ timestamp: number;
2449
+ error?: string;
2450
+ parentId?: string;
2451
+ depth?: number;
2452
+ statusType?: string;
2453
+ taskId?: string;
2454
+ shellId?: string;
2455
+ elapsedSeconds?: number;
2456
+ isBackground?: boolean;
2457
+ }
2458
+ interface ResponseContent {
2459
+ text: string;
2460
+ isStreaming: boolean;
2461
+ streamStartTime?: number;
2462
+ /** Whether this response is a plan (renders with plan variant) */
2463
+ isPlan?: boolean;
2464
+ /** ID of the underlying message (for branching + annotations) */
2465
+ messageId?: string;
2466
+ /** Persisted annotations attached to the response message */
2467
+ annotations?: AnnotationV1[];
2468
+ }
2469
+ /** Represents one complete assistant turn */
2470
+ interface AssistantTurn {
2471
+ type: 'assistant';
2472
+ turnId: string;
2473
+ activities: ActivityItem[];
2474
+ response?: ResponseContent;
2475
+ intent?: string;
2476
+ isStreaming: boolean;
2477
+ isComplete: boolean;
2478
+ timestamp: number;
2479
+ /** Extracted from TodoWrite tool - latest todo state in this turn */
2480
+ todos?: TodoItem[];
2481
+ }
2482
+ /** Represents a user message */
2483
+ interface UserTurn {
2484
+ type: 'user';
2485
+ message: Message;
2486
+ timestamp: number;
2487
+ }
2488
+ /** Represents a system/info/error message that stands alone */
2489
+ interface SystemTurn {
2490
+ type: 'system';
2491
+ message: Message;
2492
+ timestamp: number;
2493
+ }
2494
+ /** Represents an auth request (credential input, OAuth flow) */
2495
+ interface AuthRequestTurn {
2496
+ type: 'auth-request';
2497
+ message: Message;
2498
+ timestamp: number;
2499
+ }
2500
+ type Turn = AssistantTurn | UserTurn | SystemTurn | AuthRequestTurn;
2501
+ type OpenAnnotationRequest = {
2502
+ messageId: string;
2503
+ annotationId: string;
2504
+ mode: 'view' | 'edit';
2505
+ anchorX?: number;
2506
+ anchorY?: number;
2507
+ nonce: number;
2508
+ };
2509
+
2510
+ /**
2511
+ * turn-phase.ts
2512
+ *
2513
+ * Turn lifecycle phase detection for assistant turns.
2514
+ */
2515
+
2516
+ /**
2517
+ * Build a stable UI identity key for an assistant turn card.
2518
+ *
2519
+ * Why this exists:
2520
+ * - Backend turnId can be reused across visually split assistant cards
2521
+ * (e.g., steer/interruption boundaries).
2522
+ * - Expansion state must be keyed by UI-card identity, not raw backend turnId.
2523
+ */
2524
+ declare function getAssistantTurnUiKey(turn: AssistantTurn, index: number): string;
2525
+
2526
+ /**
2527
+ * turn-grouping.ts
2528
+ *
2529
+ * Core groupMessagesByTurn function plus internal helpers for converting
2530
+ * a flat Message[] array into grouped Turn[] for TurnCard rendering.
2531
+ */
2532
+
2533
+ /**
2534
+ * Groups messages into turns for TurnCard rendering
2535
+ *
2536
+ * Rules:
2537
+ * - User messages flush and start fresh context
2538
+ * - Tool messages + intermediate assistant messages belong to current turn
2539
+ * - Final assistant message (non-streaming, non-intermediate) flushes the turn
2540
+ * - Error/status/info messages are standalone system turns
2541
+ *
2542
+ * Note: We intentionally ignore turnId for grouping. The SDK generates a new
2543
+ * turnId for each API message, but from a user perspective, all work between
2544
+ * a user message and the final response should be ONE turn. We use isIntermediate
2545
+ * as the signal: isIntermediate=true means more work coming, isIntermediate=false
2546
+ * means final response.
2547
+ */
2548
+ declare function groupMessagesByTurn(messages: Message[]): Turn[];
2549
+
2550
+ /**
2551
+ * Global size configuration for TurnCard components.
2552
+ * Adjust these values to scale the entire component uniformly.
2553
+ */
2554
+ /** Shared size configuration for activity UI - exported for reuse in inline execution */
2555
+ declare const SIZE_CONFIG: {
2556
+ /** Base font size class for all text */
2557
+ readonly fontSize: "text-[13px]";
2558
+ /** Icon size class (width and height) */
2559
+ readonly iconSize: "w-3 h-3";
2560
+ /** Spinner text size class */
2561
+ readonly spinnerSize: "text-[10px]";
2562
+ /** Small spinner for header */
2563
+ readonly spinnerSizeSmall: "text-[8px]";
2564
+ /** Activity row height in pixels (approx for calculation) */
2565
+ readonly activityRowHeight: 24;
2566
+ /** Max visible activities before scrolling (show ~15 items) */
2567
+ readonly maxVisibleActivities: 15;
2568
+ /** Number of items before which we apply staggered animation */
2569
+ readonly staggeredAnimationLimit: 10;
2570
+ };
2571
+ type BufferReason = 'complete' | 'min_time' | 'timeout' | 'code_block' | 'list' | 'header' | 'question' | 'threshold_met' | 'high_word_count' | 'buffering';
2572
+
2573
+ /**
2574
+ * tool-display.ts
2575
+ *
2576
+ * Tool display formatting functions extracted from TurnCard.tsx.
2577
+ * No JSX — pure string/object formatting logic.
2578
+ */
2579
+
2580
+ /**
2581
+ * Determine if buffered content should be shown.
2582
+ * This is the core buffering decision function.
2583
+ *
2584
+ * @param text - The accumulated response text
2585
+ * @param isStreaming - Whether the response is still streaming
2586
+ * @param streamStartTime - When streaming started (for timeout calculation)
2587
+ * @returns Decision with reason for debugging
2588
+ */
2589
+ declare function shouldShowStreamingContent(text: string, isStreaming: boolean, streamStartTime?: number): {
2590
+ shouldShow: boolean;
2591
+ reason: BufferReason;
2592
+ wordCount: number;
2593
+ };
2594
+
2595
+ interface ResponseCardProps {
2596
+ /** The content to display (markdown) */
2597
+ text: string;
2598
+ /** Whether the content is still streaming */
2599
+ isStreaming: boolean;
2600
+ /** When streaming started - used for buffering timeout calculation */
2601
+ streamStartTime?: number;
2602
+ /** Callback to open file in editor */
2603
+ onOpenFile?: (path: string) => void;
2604
+ /** Callback to open URL */
2605
+ onOpenUrl?: (url: string) => void;
2606
+ /** Callback to open response in Monaco editor */
2607
+ onPopOut?: () => void;
2608
+ /** Card variant - 'response' for AI messages, 'plan' for plan messages */
2609
+ variant?: 'response' | 'plan';
2610
+ /** Parent session ID (used to reset local annotation/island UI state on session switches) */
2611
+ sessionId?: string;
2612
+ /** Underlying message ID for annotation actions */
2613
+ messageId?: string;
2614
+ /** Persisted annotations for this response */
2615
+ annotations?: AnnotationV1[];
2616
+ /** Callback when user accepts the plan (plan variant only) */
2617
+ onAccept?: () => void;
2618
+ /** Callback when user accepts the plan with compaction (compact first, then execute) */
2619
+ onAcceptWithCompact?: () => void;
2620
+ /** Whether this is the last response in the session (shows Accept Plan button only for last response) */
2621
+ isLastResponse?: boolean;
2622
+ /** Whether to show the Accept Plan button (default: true) */
2623
+ showAcceptPlan?: boolean;
2624
+ /** Hide footer for compact embedding (EditPopover) */
2625
+ compactMode?: boolean;
2626
+ /** Callback to branch the session from this response */
2627
+ onBranch?: (options?: {
2628
+ newPanel?: boolean;
2629
+ }) => void;
2630
+ /** Callback to add annotation from selected text */
2631
+ onAddAnnotation?: (messageId: string, annotation: AnnotationV1) => void;
2632
+ /** Callback to remove persisted annotation */
2633
+ onRemoveAnnotation?: (messageId: string, annotationId: string) => void;
2634
+ /** Callback to update persisted annotation */
2635
+ onUpdateAnnotation?: (messageId: string, annotationId: string, patch: Partial<AnnotationV1>) => void;
2636
+ /** Input send key behavior used by follow-up editor */
2637
+ sendMessageKey?: 'enter' | 'cmd-enter';
2638
+ /** Callback when follow-up is saved via "Save & Send" action */
2639
+ onSaveAndSendFollowUp?: (target: {
2640
+ messageId: string;
2641
+ annotationId: string;
2642
+ note: string;
2643
+ selectedText: string;
2644
+ }) => void;
2645
+ /** Whether there are active pending follow-up annotations in the session */
2646
+ hasActiveFollowUpAnnotations?: boolean;
2647
+ /** External request to open a specific annotation in this response */
2648
+ openAnnotationRequest?: OpenAnnotationRequest | null;
2649
+ /** Annotation interaction mode (viewer uses tooltip-only to suppress the island) */
2650
+ annotationInteractionMode?: AnnotationInteractionMode;
2651
+ }
2652
+ /**
2653
+ * ResponseCard - Unified card component for AI responses and plans
2654
+ *
2655
+ * Variants:
2656
+ * - 'response': Buffered streaming response with smart content gating
2657
+ * - 'plan': Plan message with header and Accept Plan button
2658
+ *
2659
+ * Response variant implements smart buffering:
2660
+ * - Waits for 40+ words with structure OR
2661
+ * - High-confidence patterns (code blocks, headers, lists) with lower threshold OR
2662
+ * - Timeout after 2.5 seconds
2663
+ *
2664
+ * Performance optimization: Uses throttled static snapshots instead of re-rendering
2665
+ * on every character. Content updates every 300ms during streaming, avoiding
2666
+ * expensive markdown parsing on every delta.
2667
+ */
2668
+ declare function ResponseCard({ text, isStreaming, streamStartTime, onOpenFile, onOpenUrl, onPopOut, variant, sessionId, messageId, annotations, onAccept, onAcceptWithCompact, isLastResponse, showAcceptPlan, compactMode, onBranch, onAddAnnotation, onRemoveAnnotation, onUpdateAnnotation, sendMessageKey, onSaveAndSendFollowUp, hasActiveFollowUpAnnotations, openAnnotationRequest, annotationInteractionMode, }: ResponseCardProps): react_jsx_runtime.JSX.Element | null;
2669
+
2670
+ interface TurnCardProps {
2671
+ /** Session ID for state persistence (optional in shared context) */
2672
+ sessionId?: string;
2673
+ /** Turn ID for state persistence */
2674
+ turnId: string;
2675
+ /** All activities in this turn (tools, thinking, intermediate text) */
2676
+ activities: ActivityItem[];
2677
+ /** Final response content (may be streaming) */
2678
+ response?: ResponseContent;
2679
+ /** Primary intent/goal for this turn (shown in collapsed preview) */
2680
+ intent?: string;
2681
+ /** Whether content is still being received */
2682
+ isStreaming: boolean;
2683
+ /** Whether this turn is fully complete */
2684
+ isComplete: boolean;
2685
+ /** Start in expanded state */
2686
+ defaultExpanded?: boolean;
2687
+ /** Controlled expansion state (overrides internal state) */
2688
+ isExpanded?: boolean;
2689
+ /** Callback when expansion state changes */
2690
+ onExpandedChange?: (expanded: boolean) => void;
2691
+ /** Controlled expansion state for activity groups */
2692
+ expandedActivityGroups?: Set<string>;
2693
+ /** Callback when activity group expansion changes */
2694
+ onExpandedActivityGroupsChange?: (groups: Set<string>) => void;
2695
+ /** Callback when file path is clicked */
2696
+ onOpenFile?: (path: string) => void;
2697
+ /** Callback when URL is clicked */
2698
+ onOpenUrl?: (url: string) => void;
2699
+ /** Callback to open response in Monaco editor */
2700
+ onPopOut?: (text: string) => void;
2701
+ /** Callback to open turn details in a new window */
2702
+ onOpenDetails?: () => void;
2703
+ /** Callback to open individual activity details in Monaco */
2704
+ onOpenActivityDetails?: (activity: ActivityItem) => void;
2705
+ /** Callback to open all edits/writes in multi-file diff view */
2706
+ onOpenMultiFileDiff?: () => void;
2707
+ /** Whether this turn has any Edit or Write activities */
2708
+ hasEditOrWriteActivities?: boolean;
2709
+ /** TodoWrite tool state - shown at bottom of turn */
2710
+ todos?: TodoItem[];
2711
+ /** Optional render prop for actions menu (Electron provides dropdown) */
2712
+ renderActionsMenu?: () => React$1.ReactNode;
2713
+ /** Callback when user accepts the plan (plan responses only) */
2714
+ onAcceptPlan?: () => void;
2715
+ /** Callback when user accepts the plan with compaction (compact conversation first, then execute) */
2716
+ onAcceptPlanWithCompact?: () => void;
2717
+ /** Whether this is the last response in the session (shows Accept Plan button only for last response) */
2718
+ isLastResponse?: boolean;
2719
+ /** Session folder path for stripping from file paths in tool display */
2720
+ sessionFolderPath?: string;
2721
+ /** Display mode: 'detailed' shows all info, 'informative' hides MCP/API names and params */
2722
+ displayMode?: 'informative' | 'detailed';
2723
+ /** Animate response appearance (for playground demos) */
2724
+ animateResponse?: boolean;
2725
+ /** Hide footers for compact embedding (EditPopover) */
2726
+ compactMode?: boolean;
2727
+ /** Callback to branch the session from a specific message */
2728
+ onBranch?: (messageId: string, options?: {
2729
+ newPanel?: boolean;
2730
+ }) => void;
2731
+ /** Callback to add an annotation to a response message */
2732
+ onAddAnnotation?: (messageId: string, annotation: AnnotationV1) => void;
2733
+ /** Callback to remove a persisted annotation from a response message */
2734
+ onRemoveAnnotation?: (messageId: string, annotationId: string) => void;
2735
+ /** Callback to update a persisted annotation */
2736
+ onUpdateAnnotation?: (messageId: string, annotationId: string, patch: Partial<AnnotationV1>) => void;
2737
+ /** Input send key behavior used by follow-up editor */
2738
+ sendMessageKey?: 'enter' | 'cmd-enter';
2739
+ /** Callback when follow-up is saved via "Save & Send" action */
2740
+ onSaveAndSendFollowUp?: (target: {
2741
+ messageId: string;
2742
+ annotationId: string;
2743
+ note: string;
2744
+ selectedText: string;
2745
+ }) => void;
2746
+ /** Whether there are active pending follow-up annotations in the session */
2747
+ hasActiveFollowUpAnnotations?: boolean;
2748
+ /** External request to open a specific annotation in the follow-up island */
2749
+ openAnnotationRequest?: OpenAnnotationRequest | null;
2750
+ /** Annotation interaction mode (viewer uses tooltip-only to suppress the island) */
2751
+ annotationInteractionMode?: AnnotationInteractionMode;
2752
+ }
2753
+ /**
2754
+ * TurnCard - Email-like display for one assistant turn
2755
+ *
2756
+ * Batches all activities (tools, thinking) into a collapsible section
2757
+ * with the final response displayed separately below.
2758
+ *
2759
+ * Memoized to prevent re-renders of completed turns during session switches.
2760
+ * Only complete, non-streaming turns are memoized - active turns always re-render.
2761
+ */
2762
+ declare const TurnCard: React$1.MemoExoticComponent<({ sessionId, turnId, activities, response, intent, isStreaming, isComplete, defaultExpanded, isExpanded: externalIsExpanded, onExpandedChange, expandedActivityGroups: externalExpandedActivityGroups, onExpandedActivityGroupsChange, onOpenFile, onOpenUrl, onPopOut, onOpenDetails, onOpenActivityDetails, onOpenMultiFileDiff, hasEditOrWriteActivities, todos, renderActionsMenu, onAcceptPlan, onAcceptPlanWithCompact, isLastResponse, sessionFolderPath, displayMode, animateResponse, compactMode, onBranch, onAddAnnotation, onRemoveAnnotation, onUpdateAnnotation, sendMessageKey, onSaveAndSendFollowUp, hasActiveFollowUpAnnotations, openAnnotationRequest, annotationInteractionMode, }: TurnCardProps) => react_jsx_runtime.JSX.Element | null>;
2763
+
2764
+ type InlineExecutionStatus = 'executing' | 'success' | 'error';
2765
+ interface InlineActivityItem {
2766
+ id: string;
2767
+ name: string;
2768
+ status: ActivityStatus;
2769
+ description?: string;
2770
+ }
2771
+ interface InlineExecutionProps {
2772
+ /** Current execution status */
2773
+ status: InlineExecutionStatus;
2774
+ /** Activities to display (simplified from full ActivityItem) */
2775
+ activities: InlineActivityItem[];
2776
+ /** Result message on success */
2777
+ result?: string;
2778
+ /** Error message on failure */
2779
+ error?: string;
2780
+ /** Callback to cancel execution */
2781
+ onCancel?: () => void;
2782
+ /** Callback to dismiss (on success/error) */
2783
+ onDismiss?: () => void;
2784
+ /** Callback to retry (on error) */
2785
+ onRetry?: () => void;
2786
+ /** Optional className */
2787
+ className?: string;
2788
+ }
2789
+ declare function InlineExecution({ status, activities, result, error, onCancel, onDismiss, onRetry, className, }: InlineExecutionProps): react_jsx_runtime.JSX.Element;
2790
+
2791
+ /**
2792
+ * Platform-specific actions for UI components.
2793
+ * Consumers provide these via PlatformProvider.
2794
+ */
2795
+ interface PlatformActions {
2796
+ /** Open a file in the system editor/Finder */
2797
+ onOpenFile?: (path: string) => void;
2798
+ /** Open a URL in the system browser */
2799
+ onOpenUrl?: (url: string) => void;
2800
+ /** Open a markdown preview popover */
2801
+ onOpenMarkdownPreview?: (sessionId: string, markdown: string) => void;
2802
+ /** Open turn details in a new window/panel */
2803
+ onOpenTurnDetails?: (sessionId: string, turnId: string) => void;
2804
+ /** Open activity details */
2805
+ onOpenActivityDetails?: (sessionId: string, activityId: string) => void;
2806
+ /** Open multi-file diff view for a turn */
2807
+ onOpenMultiFileDiff?: (sessionId: string, turnId: string) => void;
2808
+ /** Respond to a permission or auth request */
2809
+ onPermissionAllow?: (requestId: string, allowed: boolean, remember?: boolean) => void;
2810
+ }
2811
+ /**
2812
+ * Provider that injects platform-specific actions into the component tree.
2813
+ */
2814
+ declare function PlatformProvider({ actions, children, }: {
2815
+ actions: PlatformActions;
2816
+ children: React__default.ReactNode;
2817
+ }): react_jsx_runtime.JSX.Element;
2818
+
2819
+ interface ChatTranscriptProps {
2820
+ messages: Message[];
2821
+ platformActions?: PlatformActions;
2822
+ className?: string;
2823
+ onTurnClick?: (turnId: string) => void;
2824
+ onActivityClick?: (activity: ActivityItem) => void;
2825
+ defaultExpanded?: boolean;
2826
+ displayMode?: 'informative' | 'detailed';
2827
+ animateResponse?: boolean;
2828
+ annotationInteractionMode?: AnnotationInteractionMode;
2829
+ sessionId?: string;
2830
+ sessionFolderPath?: string;
2831
+ children?: ReactNode;
2832
+ }
2833
+ declare function ChatTranscript({ messages, platformActions, className, onTurnClick, onActivityClick, defaultExpanded, displayMode, animateResponse, annotationInteractionMode, sessionId, sessionFolderPath, children, }: ChatTranscriptProps): react_jsx_runtime.JSX.Element;
2834
+
2835
+ type SessionViewerMode = 'interactive' | 'readonly';
2836
+ interface SessionViewerProps {
2837
+ session: StoredSession;
2838
+ mode?: SessionViewerMode;
2839
+ platformActions?: PlatformActions;
2840
+ className?: string;
2841
+ onTurnClick?: (turnId: string) => void;
2842
+ onActivityClick?: (activity: ActivityItem) => void;
2843
+ defaultExpanded?: boolean;
2844
+ header?: ReactNode;
2845
+ footer?: ReactNode;
2846
+ sessionFolderPath?: string;
2847
+ }
2848
+ declare function SessionViewer({ session, mode, platformActions, className, onTurnClick, onActivityClick, defaultExpanded, header, footer, sessionFolderPath, }: SessionViewerProps): react_jsx_runtime.JSX.Element;
2849
+
2850
+ interface PendingIndicatorProps {
2851
+ isReconnecting?: boolean;
2852
+ }
2853
+ declare function PendingIndicator({ isReconnecting, }: PendingIndicatorProps): react_jsx_runtime.JSX.Element;
2854
+
2855
+ interface UserMessageBubbleProps {
2856
+ /** Message content (markdown supported) */
2857
+ content: string;
2858
+ /** Additional className for the outer container */
2859
+ className?: string;
2860
+ /** Callback when a URL is clicked */
2861
+ onUrlClick?: (url: string) => void;
2862
+ /** Callback when a file path is clicked */
2863
+ onFileClick?: (path: string) => void;
2864
+ /** Stored attachments (images, documents) */
2865
+ attachments?: StoredAttachment[];
2866
+ /** Content badges for inline display (sources, skills) */
2867
+ badges?: ContentBadge[];
2868
+ /** Whether the message is awaiting backend confirmation. User bubbles stay visually stable. */
2869
+ isPending?: boolean;
2870
+ /** Whether the message is queued (badge shown) */
2871
+ isQueued?: boolean;
2872
+ /** Compact mode - reduces padding for popover embedding */
2873
+ compactMode?: boolean;
2874
+ }
2875
+ declare function UserMessageBubble({ content, className, onUrlClick, onFileClick, attachments, badges, isQueued, compactMode, }: UserMessageBubbleProps): react_jsx_runtime.JSX.Element;
2876
+
2877
+ /**
2878
+ * SystemMessage - Displays system/info/error/warning messages
2879
+ *
2880
+ * Used for displaying non-conversational messages like errors, warnings,
2881
+ * info notices, and general system messages. Supports different visual
2882
+ * styles based on the message type.
2883
+ *
2884
+ * Error and warning types use shadow-tinted for a softer, more polished appearance.
2885
+ * System and info types use a simple bordered style.
2886
+ */
2887
+ type SystemMessageType = 'error' | 'info' | 'warning' | 'system';
2888
+ interface SystemMessageProps {
2889
+ /** Message content (markdown supported) */
2890
+ content: string;
2891
+ /** Message type determining visual style */
2892
+ type: SystemMessageType;
2893
+ /** Additional className for the outer container */
2894
+ className?: string;
2895
+ }
2896
+ /**
2897
+ * SystemMessage - Renders a styled message bubble based on type
2898
+ */
2899
+ declare function SystemMessage({ content, type, className, }: SystemMessageProps): react_jsx_runtime.JSX.Element;
2900
+
2901
+ /**
2902
+ * PermissionRequestCard - Inline permission prompt for agent tool approval
2903
+ *
2904
+ * Renders when the agent is paused awaiting user approval for a tool
2905
+ * invocation (e.g. bash command, file write, MCP mutation). Displays
2906
+ * the tool name, input preview, and reason, with Allow/Deny/Remember
2907
+ * action buttons.
2908
+ *
2909
+ * Styling follows the Weft design system:
2910
+ * - Rounded-[8px] card with shadow-minimal
2911
+ * - Accent-coloured header strip for tool identity
2912
+ * - Truncated input preview in a subtle code block
2913
+ * - Two or three action buttons (Allow, Deny, Remember)
2914
+ */
2915
+ interface PermissionRequestCardProps {
2916
+ /** Unique request ID matching the runtime permission request */
2917
+ requestId: string;
2918
+ /** Tool name requesting approval (e.g. "Bash", "Write", "Edit") */
2919
+ toolName: string;
2920
+ /** Optional scope descriptor (session, workspace, source, skill, tool-call) */
2921
+ scope?: {
2922
+ type: string;
2923
+ label?: string;
2924
+ };
2925
+ /** Optional input preview (command, file path, MCP payload) */
2926
+ input?: Record<string, unknown>;
2927
+ /** Optional reason text explaining why permission is needed */
2928
+ reason?: string;
2929
+ /** Whether this request is currently active (not yet resolved) */
2930
+ isActive?: boolean;
2931
+ /** Previous resolution if re-shown for context (allowed/denied) */
2932
+ previousResolution?: {
2933
+ allowed: boolean;
2934
+ remember?: boolean;
2935
+ reason?: string;
2936
+ };
2937
+ /** Callback when user approves the request */
2938
+ onAllow?: (requestId: string, remember?: boolean) => void;
2939
+ /** Callback when user denies the request */
2940
+ onDeny?: (requestId: string) => void;
2941
+ /** Additional className */
2942
+ className?: string;
2943
+ }
2944
+ declare function PermissionRequestCard({ requestId, toolName, scope, input, reason, isActive, previousResolution, onAllow, onDeny, className, }: PermissionRequestCardProps): react_jsx_runtime.JSX.Element;
2945
+
2946
+ interface CodeBlockProps {
2947
+ code: string;
2948
+ language?: string;
2949
+ className?: string;
2950
+ /**
2951
+ * Render mode affects code block styling:
2952
+ * - 'terminal': Minimal, keeps control chars visible
2953
+ * - 'minimal': Clean code, basic styling
2954
+ * - 'full': Rich styling with background, copy button, etc.
2955
+ */
2956
+ mode?: 'terminal' | 'minimal' | 'full';
2957
+ /**
2958
+ * Force a specific theme. If not provided, detects from document.documentElement.classList
2959
+ */
2960
+ forcedTheme?: 'light' | 'dark';
2961
+ }
2962
+ /**
2963
+ * CodeBlock - Syntax highlighted code block using Shiki
2964
+ *
2965
+ * Uses VS Code's syntax highlighting engine for accurate highlighting.
2966
+ * Lazy-loads highlighting and caches results for performance.
2967
+ */
2968
+ declare function CodeBlock({ code, language, className, mode, forcedTheme }: CodeBlockProps): react_jsx_runtime.JSX.Element;
2969
+ /**
2970
+ * InlineCode - Styled inline code span
2971
+ * Features: subtle background (3%), no border, 75% opacity text
2972
+ */
2973
+ declare function InlineCode({ children, className }: {
2974
+ children: React$1.ReactNode;
2975
+ className?: string;
2976
+ }): react_jsx_runtime.JSX.Element;
2977
+
2978
+ declare function CollapsibleMarkdownProvider({ children, }: {
2979
+ children: React.ReactNode;
2980
+ }): react_jsx_runtime.JSX.Element;
2981
+
2982
+ /**
2983
+ * Render modes for markdown content:
2984
+ *
2985
+ * - 'terminal': Raw output with minimal formatting, control chars visible
2986
+ * Best for: Debug output, raw logs, when you want to see exactly what's there
2987
+ *
2988
+ * - 'minimal': Clean rendering with syntax highlighting but no extra chrome
2989
+ * Best for: Chat messages, inline content, when you want readability without clutter
2990
+ *
2991
+ * - 'full': Rich rendering with beautiful tables, styled code blocks, proper typography
2992
+ * Best for: Documentation, long-form content, when presentation matters
2993
+ */
2994
+ type RenderMode = 'terminal' | 'minimal' | 'full';
2995
+ interface MarkdownProps {
2996
+ children: string;
2997
+ /**
2998
+ * Render mode controlling formatting level
2999
+ * @default 'minimal'
3000
+ */
3001
+ mode?: RenderMode;
3002
+ className?: string;
3003
+ /**
3004
+ * Message ID for memoization (optional)
3005
+ * When provided, memoizes parsed blocks to avoid re-parsing during streaming
3006
+ */
3007
+ id?: string;
3008
+ /**
3009
+ * Callback when a URL is clicked
3010
+ */
3011
+ onUrlClick?: (url: string) => void;
3012
+ /**
3013
+ * Callback when a file path is clicked
3014
+ */
3015
+ onFileClick?: (path: string) => void;
3016
+ /**
3017
+ * Enable collapsible headings
3018
+ * Requires wrapping in CollapsibleMarkdownProvider
3019
+ * @default false
3020
+ */
3021
+ collapsible?: boolean;
3022
+ /**
3023
+ * Hide expand button on first mermaid block (when message starts with mermaid)
3024
+ * Used in chat to avoid overlap with TurnCard's fullscreen button
3025
+ * @default true
3026
+ */
3027
+ hideFirstMermaidExpand?: boolean;
3028
+ }
3029
+ /**
3030
+ * Markdown - Customizable markdown renderer with multiple render modes
3031
+ *
3032
+ * Features:
3033
+ * - Three render modes: terminal, minimal, full
3034
+ * - Syntax highlighting via Shiki
3035
+ * - GFM support (tables, task lists, strikethrough)
3036
+ * - Clickable links and file paths
3037
+ * - Memoization for streaming performance
3038
+ */
3039
+ declare function Markdown({ children, mode, className, id, onUrlClick, onFileClick, collapsible, hideFirstMermaidExpand, }: MarkdownProps): react_jsx_runtime.JSX.Element;
3040
+ /**
3041
+ * MemoizedMarkdown - Optimized for streaming scenarios
3042
+ *
3043
+ * Splits content into blocks and memoizes each block separately,
3044
+ * so only new/changed blocks re-render during streaming.
3045
+ */
3046
+ declare const MemoizedMarkdown: React$1.MemoExoticComponent<typeof Markdown>;
3047
+
3048
+ interface AnchoredSelection {
3049
+ anchorX: number;
3050
+ anchorY: number;
3051
+ start: number;
3052
+ end: number;
3053
+ exact: string;
3054
+ selectedText?: string;
3055
+ prefix?: string;
3056
+ suffix?: string;
3057
+ }
3058
+
3059
+ /**
3060
+ * annotation-core — stub for annotation overlay core utilities.
3061
+ *
3062
+ * Provides type definitions and utility functions for annotation rendering.
3063
+ * Full implementation will be ported from the upstream source project.
3064
+ */
3065
+
3066
+ interface AnnotationOverlayRect {
3067
+ id: string;
3068
+ left: number;
3069
+ top: number;
3070
+ width: number;
3071
+ height: number;
3072
+ color: string;
3073
+ }
3074
+ type AnnotationOverlayChip = {
3075
+ id: string;
3076
+ index: number;
3077
+ left: number;
3078
+ top: number;
3079
+ sentFollowUp: boolean;
3080
+ };
3081
+ declare function hasExistingTextRangeAnnotation(annotations: AnnotationV1[], start: number, end: number): boolean;
3082
+ declare function createSelectionPreviewAnnotation(messageId: string, sessionIdOrSelection: string | AnchoredSelection, startOrSessionId?: number | string, end?: number, exact?: string): AnnotationV1;
3083
+ declare function createTextSelectionAnnotation(messageId: string, sessionId: string, start: number, end: number, exact: string, note: string): AnnotationV1;
3084
+ interface TextSegment {
3085
+ start: number;
3086
+ end: number;
3087
+ node: Text;
3088
+ }
3089
+ declare function collectTextSegments(_content: string | HTMLElement, _annotations: AnnotationV1[]): TextSegment[];
3090
+ /** Stub — full implementation will compute canonical text from DOM */
3091
+ declare function getCanonicalText(_content: string | HTMLElement): string;
3092
+ /**
3093
+ * Stub — resolves character offset within a DOM node.
3094
+ * Full implementation will walk the DOM tree to compute text offset.
3095
+ */
3096
+ declare function resolveNodeOffset(_root: string | HTMLElement, _node?: Node, _offset?: number): number | null;
3097
+
3098
+ /**
3099
+ * annotation-overlay-geometry — stub for annotation overlay geometry computation.
3100
+ */
3101
+
3102
+ interface AnnotationOverlayGeometryResult {
3103
+ rects: AnnotationOverlayRect[];
3104
+ chips: AnnotationOverlayChip[];
3105
+ unresolved: Array<{
3106
+ annotation: AnnotationV1;
3107
+ reason: string;
3108
+ }>;
3109
+ }
3110
+ declare function computeAnnotationOverlayGeometry(_containerOrOpts: HTMLElement | {
3111
+ root: HTMLElement;
3112
+ renderedAnnotations: AnnotationV1[];
3113
+ persistedAnnotations?: AnnotationV1[];
3114
+ }, _annotations?: AnnotationV1[], _content?: string): AnnotationOverlayGeometryResult;
3115
+
3116
+ interface AnnotationOverlayLayerProps {
3117
+ rects: AnnotationOverlayRect[];
3118
+ chips: AnnotationOverlayChip[];
3119
+ annotations?: AnnotationV1[];
3120
+ getTooltipText?: (annotation: AnnotationV1, index: number) => string;
3121
+ /** Whether clicking a chip should open the annotation island/details view. */
3122
+ allowChipOpen?: boolean;
3123
+ onChipOpen: (params: {
3124
+ annotationId: string;
3125
+ index: number;
3126
+ anchorX: number;
3127
+ anchorY: number;
3128
+ mode: 'view' | 'edit';
3129
+ }) => void;
3130
+ }
3131
+ declare function AnnotationOverlayLayer({ rects, chips, annotations, getTooltipText, allowChipOpen, onChipOpen, }: AnnotationOverlayLayerProps): react_jsx_runtime.JSX.Element | null;
3132
+
3133
+ /**
3134
+ * IslandTransitionConfig — type stub for annotation island transition animations.
3135
+ */
3136
+ interface IslandTransitionConfig {
3137
+ duration?: number;
3138
+ easing?: string;
3139
+ }
3140
+
3141
+ /**
3142
+ * AnnotationIslandMenu — stub for annotation island menu component.
3143
+ * Accepts all props used by TurnCard but renders nothing.
3144
+ */
3145
+
3146
+ interface AnnotationIslandMenuProps {
3147
+ anchor?: {
3148
+ x: number;
3149
+ y: number;
3150
+ } | null;
3151
+ sourceKey?: string;
3152
+ replayNonce?: number;
3153
+ isVisible?: boolean;
3154
+ activeView?: string | null;
3155
+ mode?: string;
3156
+ draft?: string;
3157
+ onDraftChange?: (draft: string) => void;
3158
+ onOpenFollowUp?: () => void;
3159
+ onCancel?: () => void;
3160
+ onRequestBack?: () => boolean;
3161
+ onRequestEdit?: () => void;
3162
+ onSubmit?: (note: string) => void;
3163
+ onSubmitAndSend?: (...args: any[]) => void;
3164
+ onDelete?: () => void;
3165
+ sendMessageKey?: string;
3166
+ transitionConfig?: Record<string, unknown> | IslandTransitionConfig;
3167
+ onExitComplete?: () => void;
3168
+ usePortal?: boolean;
3169
+ className?: string;
3170
+ }
3171
+ declare function AnnotationIslandMenu(_props: AnnotationIslandMenuProps): React$1.ReactNode;
3172
+
3173
+ /**
3174
+ * island-motion — stub for annotation island motion/animation utilities.
3175
+ */
3176
+ interface PointerSnapshot {
3177
+ x: number;
3178
+ y: number;
3179
+ timestamp: number;
3180
+ }
3181
+ declare function buildAnnotationChipEntryTransition(_snapshot?: PointerSnapshot | null): Record<string, unknown>;
3182
+ declare function buildSelectionEntryTransition(_primary?: PointerSnapshot | null, _secondary?: PointerSnapshot | null): Record<string, unknown>;
3183
+
3184
+ /**
3185
+ * Event Processor Types
3186
+ *
3187
+ * Defines the state and event types for the centralized event processor.
3188
+ * All agent events flow through a single pure function for consistent state transitions.
3189
+ */
3190
+
3191
+ /**
3192
+ * Runtime Session type — extends core Session with messages and processing state.
3193
+ * Aliased from ProtocolSession which includes all runtime fields needed by the processor.
3194
+ */
3195
+ type Session = ProtocolSession;
3196
+
3197
+ /**
3198
+ * Streaming state for a session - replaces streamingTextRef
3199
+ */
3200
+ interface StreamingState {
3201
+ content: string;
3202
+ turnId?: string;
3203
+ parentToolUseId?: string;
3204
+ }
3205
+ /**
3206
+ * Complete state for a session - combines session + streaming
3207
+ */
3208
+ interface SessionState {
3209
+ session: Session;
3210
+ streaming: StreamingState | null;
3211
+ }
3212
+ /**
3213
+ * Text delta event - streaming text content
3214
+ */
3215
+ interface TextDeltaEvent {
3216
+ type: 'text_delta';
3217
+ sessionId: string;
3218
+ delta: string;
3219
+ turnId?: string;
3220
+ /** Timestamp from canonical timeline for stable ordering */
3221
+ timestamp?: number;
3222
+ }
3223
+ /**
3224
+ * Text complete event - finalizes streaming text
3225
+ */
3226
+ interface TextCompleteEvent {
3227
+ type: 'text_complete';
3228
+ sessionId: string;
3229
+ text: string;
3230
+ turnId?: string;
3231
+ isIntermediate?: boolean;
3232
+ parentToolUseId?: string;
3233
+ /** Timestamp from main process for consistent ordering with session.jsonl */
3234
+ timestamp?: number;
3235
+ /** Authoritative message ID from main process for persistence/branching parity */
3236
+ messageId?: string;
3237
+ }
3238
+ /**
3239
+ * Tool start event - begins tool execution
3240
+ * Field names match SessionEvent from @weft/protocol
3241
+ */
3242
+ interface ToolStartEvent {
3243
+ type: 'tool_start';
3244
+ sessionId: string;
3245
+ toolUseId: string;
3246
+ toolName: string;
3247
+ toolInput?: Record<string, unknown>;
3248
+ /** Timestamp from main process for consistent ordering */
3249
+ timestamp?: number;
3250
+ turnId?: string;
3251
+ parentToolUseId?: string;
3252
+ toolIntent?: string;
3253
+ toolDisplayName?: string;
3254
+ /** Tool display metadata with base64-encoded icon for viewer compatibility */
3255
+ toolDisplayMeta?: ToolDisplayMeta;
3256
+ }
3257
+ /**
3258
+ * Tool result event - completes tool execution
3259
+ */
3260
+ interface ToolResultEvent {
3261
+ type: 'tool_result';
3262
+ sessionId: string;
3263
+ toolUseId: string;
3264
+ toolName?: string;
3265
+ result: string;
3266
+ isError?: boolean;
3267
+ turnId?: string;
3268
+ parentToolUseId?: string;
3269
+ /** Timestamp from main process for consistent ordering */
3270
+ timestamp?: number;
3271
+ }
3272
+ /**
3273
+ * Tool delta event - appends streaming output to an executing tool.
3274
+ */
3275
+ interface ToolDeltaEvent {
3276
+ type: 'tool_delta';
3277
+ sessionId: string;
3278
+ toolUseId: string;
3279
+ delta: string;
3280
+ stream?: string;
3281
+ turnId?: string;
3282
+ /** Timestamp from main process for consistent ordering */
3283
+ timestamp?: number;
3284
+ }
3285
+ /**
3286
+ * Complete event - agent loop finished
3287
+ */
3288
+ interface CompleteEvent {
3289
+ type: 'complete';
3290
+ sessionId: string;
3291
+ tokenUsage?: Session['tokenUsage'];
3292
+ /** Explicit unread flag - set by main process based on viewing state */
3293
+ hasUnread?: boolean;
3294
+ }
3295
+ /**
3296
+ * Error event - agent error occurred
3297
+ */
3298
+ interface ErrorEvent {
3299
+ type: 'error';
3300
+ sessionId: string;
3301
+ error: string;
3302
+ code?: string;
3303
+ title?: string;
3304
+ details?: string;
3305
+ original?: string;
3306
+ /** Timestamp from main process for consistent ordering */
3307
+ timestamp?: number;
3308
+ }
3309
+ /**
3310
+ * Permission request event
3311
+ * Matches SessionEvent shape from @weft/protocol
3312
+ */
3313
+ interface PermissionRequestEvent {
3314
+ type: 'permission_request';
3315
+ sessionId: string;
3316
+ request: PermissionRequest;
3317
+ }
3318
+ /**
3319
+ * Sources changed event
3320
+ */
3321
+ interface SourcesChangedEvent {
3322
+ type: 'sources_changed';
3323
+ sessionId: string;
3324
+ enabledSourceSlugs: string[];
3325
+ }
3326
+ /**
3327
+ * Labels changed event
3328
+ */
3329
+ interface LabelsChangedEvent {
3330
+ type: 'labels_changed';
3331
+ sessionId: string;
3332
+ labels: string[];
3333
+ }
3334
+ /**
3335
+ * Todo state changed event (external metadata change or agent tool)
3336
+ */
3337
+ interface SessionStatusChangedEvent {
3338
+ type: 'session_status_changed';
3339
+ sessionId: string;
3340
+ sessionStatus?: string;
3341
+ }
3342
+ /**
3343
+ * Session flagged/unflagged events (external metadata change)
3344
+ */
3345
+ interface SessionFlaggedEvent {
3346
+ type: 'session_flagged';
3347
+ sessionId: string;
3348
+ }
3349
+ interface SessionUnflaggedEvent {
3350
+ type: 'session_unflagged';
3351
+ sessionId: string;
3352
+ }
3353
+ /**
3354
+ * Session archived/unarchived events (external metadata change)
3355
+ */
3356
+ interface SessionArchivedEvent {
3357
+ type: 'session_archived';
3358
+ sessionId: string;
3359
+ }
3360
+ interface SessionUnarchivedEvent {
3361
+ type: 'session_unarchived';
3362
+ sessionId: string;
3363
+ }
3364
+ /**
3365
+ * Session name changed event (external metadata change)
3366
+ */
3367
+ interface NameChangedEvent {
3368
+ type: 'name_changed';
3369
+ sessionId: string;
3370
+ name?: string;
3371
+ }
3372
+ /**
3373
+ * Plan submitted event
3374
+ */
3375
+ interface PlanSubmittedEvent {
3376
+ type: 'plan_submitted';
3377
+ sessionId: string;
3378
+ message: Message;
3379
+ }
3380
+ /**
3381
+ * Typed error event
3382
+ */
3383
+ interface TypedErrorEvent {
3384
+ type: 'typed_error';
3385
+ sessionId: string;
3386
+ error: TypedError;
3387
+ /** Timestamp from main process for consistent ordering */
3388
+ timestamp?: number;
3389
+ }
3390
+ /**
3391
+ * Status event
3392
+ */
3393
+ interface StatusEvent {
3394
+ type: 'status';
3395
+ sessionId: string;
3396
+ message: string;
3397
+ statusType?: 'compacting';
3398
+ /** Timestamp from main process for consistent ordering */
3399
+ timestamp?: number;
3400
+ }
3401
+ /**
3402
+ * Info event
3403
+ */
3404
+ interface InfoEvent {
3405
+ type: 'info';
3406
+ sessionId: string;
3407
+ message: string;
3408
+ statusType?: 'compaction_complete';
3409
+ level?: 'info' | 'warning' | 'error' | 'success';
3410
+ /** Timestamp from main process for consistent ordering */
3411
+ timestamp?: number;
3412
+ }
3413
+ /**
3414
+ * Interrupted event
3415
+ */
3416
+ interface InterruptedEvent {
3417
+ type: 'interrupted';
3418
+ sessionId: string;
3419
+ message?: Message;
3420
+ /** Messages that were queued but not processed — should be restored to input field */
3421
+ queuedMessages?: string[];
3422
+ }
3423
+ /**
3424
+ * Title generated event
3425
+ */
3426
+ interface TitleGeneratedEvent {
3427
+ type: 'title_generated';
3428
+ sessionId: string;
3429
+ title: string;
3430
+ preview?: string;
3431
+ }
3432
+ /**
3433
+ * Title regenerating event - indicates title regeneration has started/finished
3434
+ * Used to show shimmer effect on title during regeneration
3435
+ * @deprecated Use AsyncOperationEvent instead
3436
+ */
3437
+ interface TitleRegeneratingEvent {
3438
+ type: 'title_regenerating';
3439
+ sessionId: string;
3440
+ isRegenerating: boolean;
3441
+ }
3442
+ /**
3443
+ * Generic async operation state event
3444
+ * Used to show shimmer effect during any async operation (sharing, updating, revoking, title regeneration)
3445
+ */
3446
+ interface AsyncOperationEvent {
3447
+ type: 'async_operation';
3448
+ sessionId: string;
3449
+ isOngoing: boolean;
3450
+ }
3451
+ /**
3452
+ * Working directory changed event (user-initiated via UI)
3453
+ */
3454
+ interface WorkingDirectoryChangedEvent {
3455
+ type: 'working_directory_changed';
3456
+ sessionId: string;
3457
+ workingDirectory: string;
3458
+ }
3459
+ /**
3460
+ * Working directory error event - server rejected the path (cross-platform, not found, etc.)
3461
+ */
3462
+ interface WorkingDirectoryErrorEvent {
3463
+ type: 'working_directory_error';
3464
+ sessionId: string;
3465
+ error: string;
3466
+ }
3467
+ /**
3468
+ * Permission mode changed event
3469
+ */
3470
+ interface PermissionModeChangedEvent {
3471
+ type: 'permission_mode_changed';
3472
+ sessionId: string;
3473
+ permissionMode: PermissionMode;
3474
+ previousPermissionMode?: PermissionMode;
3475
+ transitionDisplay?: string;
3476
+ modeVersion?: number;
3477
+ changedAt?: string;
3478
+ changedBy?: 'user' | 'system' | 'restore' | 'automation' | 'unknown';
3479
+ }
3480
+ /**
3481
+ * Session model changed event
3482
+ */
3483
+ interface SessionModelChangedEvent {
3484
+ type: 'session_model_changed';
3485
+ sessionId: string;
3486
+ model: string | null;
3487
+ }
3488
+ /**
3489
+ * LLM connection changed event - syncs session.llmConnection to renderer
3490
+ */
3491
+ interface LLMConnectionChangedEvent {
3492
+ type: 'connection_changed';
3493
+ sessionId: string;
3494
+ connectionSlug: string;
3495
+ supportsBranching?: boolean;
3496
+ }
3497
+ /**
3498
+ * Credential request event - prompts user for credentials
3499
+ */
3500
+ interface CredentialRequestEvent {
3501
+ type: 'credential_request';
3502
+ sessionId: string;
3503
+ request: CredentialRequest;
3504
+ }
3505
+ /**
3506
+ * Task backgrounded event - background agent started
3507
+ */
3508
+ interface TaskBackgroundedEvent {
3509
+ type: 'task_backgrounded';
3510
+ sessionId: string;
3511
+ toolUseId: string;
3512
+ taskId: string;
3513
+ intent?: string;
3514
+ turnId?: string;
3515
+ }
3516
+ /**
3517
+ * Shell backgrounded event - background bash shell started
3518
+ */
3519
+ interface ShellBackgroundedEvent {
3520
+ type: 'shell_backgrounded';
3521
+ sessionId: string;
3522
+ toolUseId: string;
3523
+ shellId: string;
3524
+ intent?: string;
3525
+ turnId?: string;
3526
+ }
3527
+ /**
3528
+ * Task progress event - live progress updates for background tasks
3529
+ */
3530
+ interface TaskProgressEvent {
3531
+ type: 'task_progress';
3532
+ sessionId: string;
3533
+ toolUseId: string;
3534
+ elapsedSeconds: number;
3535
+ turnId?: string;
3536
+ }
3537
+ /**
3538
+ * Task completed event - background task finished execution
3539
+ * Updates the tool message status and result when a background task completes.
3540
+ */
3541
+ interface TaskCompletedEvent {
3542
+ type: 'task_completed';
3543
+ sessionId: string;
3544
+ taskId: string;
3545
+ status: 'completed' | 'failed' | 'stopped';
3546
+ outputFile?: string;
3547
+ summary?: string;
3548
+ turnId?: string;
3549
+ }
3550
+ /**
3551
+ * User message event - backend confirmation of optimistic user message
3552
+ * Used for optimistic UI: frontend shows message immediately,
3553
+ * backend confirms/updates status via this event
3554
+ */
3555
+ interface UserMessageEvent {
3556
+ type: 'user_message';
3557
+ sessionId: string;
3558
+ message: Message;
3559
+ status: 'accepted' | 'queued' | 'processing';
3560
+ /** Frontend's optimistic message ID for reliable matching */
3561
+ optimisticMessageId?: string;
3562
+ }
3563
+ /**
3564
+ * Message annotation update event
3565
+ */
3566
+ interface MessageAnnotationsUpdatedEvent {
3567
+ type: 'message_annotations_updated';
3568
+ sessionId: string;
3569
+ messageId: string;
3570
+ annotations: NonNullable<Message['annotations']>;
3571
+ }
3572
+ /**
3573
+ * Session shared event - session was shared to viewer
3574
+ */
3575
+ interface SessionSharedEvent {
3576
+ type: 'session_shared';
3577
+ sessionId: string;
3578
+ sharedUrl: string;
3579
+ }
3580
+ /**
3581
+ * Session unshared event - session share was revoked
3582
+ */
3583
+ interface SessionUnsharedEvent {
3584
+ type: 'session_unshared';
3585
+ sessionId: string;
3586
+ }
3587
+ /**
3588
+ * Auth request event - unified auth flow (credential or OAuth)
3589
+ * Adds auth-request message to session and displays inline auth UI
3590
+ */
3591
+ interface AuthRequestEvent {
3592
+ type: 'auth_request';
3593
+ sessionId: string;
3594
+ message: Message;
3595
+ request: AuthRequest;
3596
+ }
3597
+ /**
3598
+ * Auth completed event - auth request was completed (success, failure, or cancelled)
3599
+ * Updates the auth-request message status
3600
+ */
3601
+ interface AuthCompletedEvent {
3602
+ type: 'auth_completed';
3603
+ sessionId: string;
3604
+ requestId: string;
3605
+ success: boolean;
3606
+ cancelled?: boolean;
3607
+ error?: string;
3608
+ }
3609
+ /**
3610
+ * Source activated event - a source was auto-activated mid-turn
3611
+ * Caller should re-send the original message to retry with the now-active source
3612
+ */
3613
+ interface SourceActivatedEvent {
3614
+ type: 'source_activated';
3615
+ sessionId: string;
3616
+ sourceSlug: string;
3617
+ originalMessage: string;
3618
+ }
3619
+ /**
3620
+ * Usage update event - real-time context usage during processing
3621
+ * Allows UI to show growing context as agent processes, not just on complete
3622
+ */
3623
+ interface UsageUpdateEvent {
3624
+ type: 'usage_update';
3625
+ sessionId: string;
3626
+ tokenUsage: {
3627
+ inputTokens: number;
3628
+ contextWindow?: number;
3629
+ };
3630
+ }
3631
+ /**
3632
+ * Union of all agent events
3633
+ */
3634
+ type ChatEvent = TextDeltaEvent | TextCompleteEvent | ToolStartEvent | ToolDeltaEvent | ToolResultEvent | CompleteEvent | ErrorEvent | TypedErrorEvent | PermissionRequestEvent | CredentialRequestEvent | SourcesChangedEvent | LabelsChangedEvent | SessionStatusChangedEvent | SessionFlaggedEvent | SessionUnflaggedEvent | SessionArchivedEvent | SessionUnarchivedEvent | NameChangedEvent | PlanSubmittedEvent | StatusEvent | InfoEvent | InterruptedEvent | TitleGeneratedEvent | TitleRegeneratingEvent | AsyncOperationEvent | WorkingDirectoryChangedEvent | WorkingDirectoryErrorEvent | PermissionModeChangedEvent | SessionModelChangedEvent | LLMConnectionChangedEvent | TaskBackgroundedEvent | ShellBackgroundedEvent | TaskProgressEvent | TaskCompletedEvent | UserMessageEvent | MessageAnnotationsUpdatedEvent | SessionSharedEvent | SessionUnsharedEvent | AuthRequestEvent | AuthCompletedEvent | SourceActivatedEvent | UsageUpdateEvent;
3635
+ /**
3636
+ * Side effects that need to be handled outside the pure processor
3637
+ */
3638
+ type Effect = {
3639
+ type: 'permission_request';
3640
+ request: PermissionRequest;
3641
+ } | {
3642
+ type: 'credential_request';
3643
+ request: CredentialRequest;
3644
+ } | {
3645
+ type: 'generate_title';
3646
+ sessionId: string;
3647
+ userMessage: string;
3648
+ } | {
3649
+ type: 'permission_mode_changed';
3650
+ sessionId: string;
3651
+ permissionMode: PermissionMode;
3652
+ previousPermissionMode?: PermissionMode;
3653
+ transitionDisplay?: string;
3654
+ modeVersion?: number;
3655
+ changedAt?: string;
3656
+ changedBy?: 'user' | 'system' | 'restore' | 'automation' | 'unknown';
3657
+ } | {
3658
+ type: 'auto_retry';
3659
+ sessionId: string;
3660
+ originalMessage: string;
3661
+ sourceSlug: string;
3662
+ } | {
3663
+ type: 'restore_input';
3664
+ text: string;
3665
+ } | {
3666
+ type: 'toast_error';
3667
+ message: string;
3668
+ };
3669
+ /**
3670
+ * Result of processing an event
3671
+ */
3672
+ interface ProcessResult {
3673
+ state: SessionState;
3674
+ /** Side effects to execute (permissions, etc.) */
3675
+ effects: Effect[];
3676
+ }
3677
+
3678
+ /**
3679
+ * Event Processor
3680
+ *
3681
+ * Central pure function that processes all agent events.
3682
+ * Guarantees consistent state transitions and always returns new references.
3683
+ *
3684
+ * Benefits:
3685
+ * - Single source of truth for event handling
3686
+ * - Pure functions - easy to test
3687
+ * - No race conditions - single update path
3688
+ * - Always new references - atom sync always works
3689
+ * - Message lookup by ID - never position-based
3690
+ */
3691
+
3692
+ /**
3693
+ * Process an agent event, returning new state and any side effects
3694
+ *
3695
+ * This is a PURE FUNCTION - no side effects, always returns new state.
3696
+ * Guaranteed to return a new session reference (no referential equality issues).
3697
+ *
3698
+ * @param state - Current session state (session + streaming)
3699
+ * @param event - Agent event to process
3700
+ * @returns New state and any side effects to execute
3701
+ */
3702
+ declare function processEvent(state: SessionState, event: ChatEvent): ProcessResult;
3703
+
3704
+ /**
3705
+ * Map a core AgentEvent to the processor's session-scoped event format.
3706
+ *
3707
+ * Core AgentEvent is the raw SDK/runtime format. The processor expects
3708
+ * session-scoped events with its own field names. Keeping this as a pure
3709
+ * function makes local-runtime, tests, and React hooks share one mapping.
3710
+ */
3711
+ declare function mapCoreEventToProcessorEvent(coreEvent: AgentEvent, sessionId: string): ChatEvent;
3712
+ declare function mapTimelineEnvelopeToProcessorEvent(envelope: TimelineEnvelope): ChatEvent;
3713
+
3714
+ /**
3715
+ * Message Operation Helpers
3716
+ *
3717
+ * Pure utility functions for finding and updating messages.
3718
+ * All lookups are by ID (turnId, toolUseId) - NEVER by position.
3719
+ */
3720
+
3721
+ /**
3722
+ * Generate a unique message ID
3723
+ * Delegates to core's generateMessageId for uniqueness
3724
+ */
3725
+ declare function generateMessageId(): string;
3726
+ /**
3727
+ * Find streaming assistant message by turnId
3728
+ * Falls back to last streaming assistant if no turnId
3729
+ */
3730
+ declare function findStreamingMessage(messages: Message[], turnId?: string): number;
3731
+ /**
3732
+ * Find assistant message by turnId (streaming or not)
3733
+ */
3734
+ declare function findAssistantMessage(messages: Message[], turnId?: string): number;
3735
+ /**
3736
+ * Find tool message by toolUseId
3737
+ */
3738
+ declare function findToolMessage(messages: Message[], toolUseId: string): number;
3739
+ /**
3740
+ * Update message at index, returning new session
3741
+ * Always creates new references (immutable update)
3742
+ * @param updateTimestamp - If true, also update lastMessageAt
3743
+ */
3744
+ declare function updateMessageAt(session: Session, index: number, updates: Partial<Message>, updateTimestamp?: boolean): Session;
3745
+ /**
3746
+ * Append message to session, returning new session
3747
+ * @param updateTimestamp - If false, don't update lastMessageAt (for intermediate/tool messages)
3748
+ */
3749
+ declare function appendMessage(session: Session, message: Message, updateTimestamp?: boolean): Session;
3750
+
3751
+ /**
3752
+ * Event Source Interface
3753
+ *
3754
+ * Generic abstraction for receiving SessionEvent streams.
3755
+ * Replaces Electron IPC (window.electronAPI.onSessionEvent) with
3756
+ * a provider-agnostic interface that works in any runtime:
3757
+ * - WebSocket (browser/server)
3758
+ * - HTTP SSE (server)
3759
+ * - stdin/stdout (CLI)
3760
+ * - In-process (testing)
3761
+ */
3762
+
3763
+ /**
3764
+ * Event source callback — receives events from the source.
3765
+ */
3766
+ type EventSourceCallback = (event: AgentEvent) => void;
3767
+ /**
3768
+ * Error callback — receives errors from the source.
3769
+ */
3770
+ type EventSourceErrorCallback = (error: Error) => void;
3771
+ /**
3772
+ * Close callback — called when the source is disconnected.
3773
+ */
3774
+ type EventSourceCloseCallback = () => void;
3775
+ /**
3776
+ * Generic event source interface.
3777
+ * Implementations provide events from different transports.
3778
+ */
3779
+ interface EventSource {
3780
+ /**
3781
+ * Start receiving events.
3782
+ * @param onEvent - Callback for each AgentEvent
3783
+ * @param onError - Callback for transport errors
3784
+ * @param onClose - Callback when source disconnects
3785
+ */
3786
+ connect(onEvent: EventSourceCallback, onError?: EventSourceErrorCallback, onClose?: EventSourceCloseCallback): void;
3787
+ /**
3788
+ * Stop receiving events and clean up resources.
3789
+ */
3790
+ disconnect(): void;
3791
+ /**
3792
+ * Check if the source is currently connected.
3793
+ */
3794
+ isConnected(): boolean;
3795
+ }
3796
+ /**
3797
+ * WebSocket-based EventSource implementation.
3798
+ * Receives SessionEvent messages over a WebSocket connection.
3799
+ */
3800
+ declare class WebSocketEventSource implements EventSource {
3801
+ private ws;
3802
+ private connected;
3803
+ private url;
3804
+ private protocols?;
3805
+ constructor(url: string, protocols?: string | string[]);
3806
+ connect(onEvent: EventSourceCallback, onError?: EventSourceErrorCallback, onClose?: EventSourceCloseCallback): void;
3807
+ disconnect(): void;
3808
+ isConnected(): boolean;
3809
+ }
3810
+ /**
3811
+ * SSE (Server-Sent Events) EventSource implementation.
3812
+ * Receives SessionEvent messages over an HTTP SSE connection.
3813
+ */
3814
+ declare class SSEEventSource implements EventSource {
3815
+ private source;
3816
+ private connected;
3817
+ private url;
3818
+ constructor(url: string);
3819
+ connect(onEvent: EventSourceCallback, onError?: EventSourceErrorCallback, onClose?: EventSourceCloseCallback): void;
3820
+ disconnect(): void;
3821
+ isConnected(): boolean;
3822
+ }
3823
+ /**
3824
+ * In-process EventSource for testing.
3825
+ * Events are pushed directly via enqueue().
3826
+ */
3827
+ declare class InProcessEventSource implements EventSource {
3828
+ private listeners;
3829
+ private connected;
3830
+ connect(onEvent: EventSourceCallback, onError?: EventSourceErrorCallback, onClose?: EventSourceCloseCallback): void;
3831
+ disconnect(): void;
3832
+ isConnected(): boolean;
3833
+ /**
3834
+ * Push an event directly to the connected listener.
3835
+ * Useful for testing and in-process scenarios.
3836
+ */
3837
+ enqueue(event: AgentEvent): void;
3838
+ /**
3839
+ * Simulate an error.
3840
+ */
3841
+ simulateError(error: Error): void;
3842
+ /**
3843
+ * Simulate a disconnect.
3844
+ */
3845
+ simulateClose(): void;
3846
+ }
3847
+
3848
+ /**
3849
+ * Event Processor Hook
3850
+ *
3851
+ * Provides the event processor for use in React apps.
3852
+ * Manages streaming state per session and returns processed events.
3853
+ *
3854
+ * Accepts an EventSource (WebSocket, SSE, in-process) instead of
3855
+ * Electron IPC (window.electronAPI). Uses React useState/useRef
3856
+ * instead of Jotai atoms for state management.
3857
+ */
3858
+
3859
+ interface UseEventProcessorOptions {
3860
+ /** EventSource to receive agent events from */
3861
+ eventSource: EventSource;
3862
+ /** Session ID to associate with incoming events */
3863
+ sessionId: string;
3864
+ /** Workspace ID for creating new sessions */
3865
+ workspaceId: string;
3866
+ /** Workspace name for creating new sessions */
3867
+ workspaceName?: string;
3868
+ /** Callback for side effects (permissions, toasts, etc.) */
3869
+ onEffect?: (effect: Effect) => void;
3870
+ /** Callback for errors from the event source */
3871
+ onError?: (error: Error) => void;
3872
+ /** Callback when event source disconnects */
3873
+ onClose?: () => void;
3874
+ }
3875
+ interface UseEventProcessorResult {
3876
+ /** Current session state (messages, processing status, etc.) */
3877
+ session: Session | null;
3878
+ /** Current streaming state for the session */
3879
+ streamingState: StreamingState | null;
3880
+ /**
3881
+ * Process an agent event and return the updated session + any side effects
3882
+ *
3883
+ * @param event - The core AgentEvent to process
3884
+ * @returns Updated session and any side effects to execute
3885
+ */
3886
+ processAgentEvent: (event: AgentEvent) => {
3887
+ session: Session;
3888
+ effects: Effect[];
3889
+ };
3890
+ /**
3891
+ * Clear streaming state for the session (e.g., on error or complete)
3892
+ */
3893
+ clearStreamingState: () => void;
3894
+ /**
3895
+ * Get current streaming state (for debugging/testing)
3896
+ */
3897
+ getStreamingState: () => StreamingState | null;
3898
+ /**
3899
+ * Whether the event source is currently connected
3900
+ */
3901
+ isConnected: boolean;
3902
+ }
3903
+ /**
3904
+ * Hook that provides the event processor connected to an EventSource.
3905
+ *
3906
+ * Manages streaming state per session using React useRef (not Jotai atoms).
3907
+ * All event processing goes through pure functions.
3908
+ *
3909
+ * Connects to the EventSource on mount and disconnects on unmount.
3910
+ */
3911
+ declare function useEventProcessor(options: UseEventProcessorOptions): UseEventProcessorResult;
3912
+
3913
+ export { type ActivityItem, type ActivityStatus, AnnotationIslandMenu, type AnnotationIslandMenuProps, type AnnotationOverlayChip, type AnnotationOverlayGeometryResult, AnnotationOverlayLayer, type AnnotationOverlayLayerProps, type AnnotationOverlayRect, type AssistantTurn, type AuthRequestTurn, type ChatEvent, ChatTranscript, type ChatTranscriptProps, CodeBlock, CollapsibleMarkdownProvider, type Effect, type EventSource, type EventSourceCallback, type EventSourceCloseCallback, type EventSourceErrorCallback, InProcessEventSource, type InlineActivityItem, InlineCode, InlineExecution, type InlineExecutionProps, type InlineExecutionStatus, type IslandTransitionConfig, Markdown, type MarkdownProps, MemoizedMarkdown, PendingIndicator, type PendingIndicatorProps, PermissionRequestCard, type PermissionRequestCardProps, type PlatformActions, PlatformProvider, type PointerSnapshot, type ProcessResult, type RenderMode, ResponseCard, type ResponseCardProps, type ResponseContent, SIZE_CONFIG, SSEEventSource, type Session, type SessionState, SessionViewer, type SessionViewerMode, type SessionViewerProps, type StreamingState, SystemMessage, type SystemMessageProps, type SystemMessageType, type SystemTurn, type TextSegment, type TodoItem, type Turn, TurnCard, type TurnCardProps, UserMessageBubble, type UserMessageBubbleProps, type UserTurn, WebSocketEventSource, appendMessage, buildAnnotationChipEntryTransition, buildSelectionEntryTransition, collectTextSegments, computeAnnotationOverlayGeometry, createSelectionPreviewAnnotation, createTextSelectionAnnotation, findAssistantMessage, findStreamingMessage, findToolMessage, generateMessageId, getAssistantTurnUiKey, getCanonicalText, groupMessagesByTurn, hasExistingTextRangeAnnotation, mapCoreEventToProcessorEvent, mapTimelineEnvelopeToProcessorEvent, processEvent, resolveNodeOffset, shouldShowStreamingContent, updateMessageAt, useEventProcessor };
3914
+
3915
+ // -- @weft/ui/lib/en-fallback.d.ts --
3916
+ /**
3917
+ * English fallback translations for UI components.
3918
+ *
3919
+ * Used by:
3920
+ * - `TurnCard.tsx` `t()` wrapper — when i18next is uninitialized or has no resource for a key
3921
+ * - `apps/demo/src/i18n-init.ts` — as the primary `en` resource bundle
3922
+ *
3923
+ * Single source of truth — add new keys here, both consumers stay synchronized.
3924
+ */
3925
+ declare const EN_FALLBACK: Record<string, string>;
3926
+
3927
+ export { EN_FALLBACK };
3928
+
3929
+ // ── inlined from @weft/runtime-core ──
3930
+ // -- @weft/runtime-core/index.d.ts --
3931
+
3932
+ declare const RUNTIME_KINDS: readonly ["native-sdk", "app-server", "compatible-sdk", "cli-fallback"];
3933
+ type AgentRuntimeKind = typeof RUNTIME_KINDS[number];
3934
+ type AgentRuntimeStatus = 'idle' | 'preflighting' | 'ready' | 'starting' | 'running' | 'waiting_for_permission' | 'turn_completed' | 'completed' | 'failed' | 'disposed';
3935
+
3936
+ /**
3937
+ * How a provider's authentication is managed.
3938
+ * Provider-neutral auth mode — covers native SDK, app-server, compatible SDK, and CLI fallback.
3939
+ */
3940
+ type ProviderAuthMode = 'provider-owned' | 'managed' | 'none';
3941
+ /**
3942
+ * Result of probing a provider's auth configuration.
3943
+ *
3944
+ * For provider-owned auth: checks whether the provider binary reports
3945
+ * authentication as configured (e.g. `claude auth status --json` returns
3946
+ * `loggedIn: true`, or `codex app-server account/read` returns an account).
3947
+ *
3948
+ * For managed auth: checks whether required env vars are present.
3949
+ * For 'none': no auth required (e.g. fake backend for testing).
3950
+ */
3951
+ interface ProviderAuthDetection {
3952
+ /** Which auth mode this provider uses */
3953
+ mode: ProviderAuthMode;
3954
+ /** Whether auth credentials are available and valid */
3955
+ configured: boolean;
3956
+ /** How auth was detected (e.g. "claude auth status --json", "env vars") */
3957
+ source: string;
3958
+ /** Whether an account was found (provider-owned: from CLI output) */
3959
+ accountPresent?: boolean;
3960
+ /** Whether OpenAI auth is required (Codex-specific) */
3961
+ requiresOpenaiAuth?: boolean;
3962
+ /** Auth method reported by provider (e.g. "oauth", "api_key") */
3963
+ method?: string;
3964
+ /** Provider name reported by CLI (e.g. "anthropic") */
3965
+ provider?: string;
3966
+ /** Error message if auth detection failed */
3967
+ error?: string;
3968
+ }
3969
+ /**
3970
+ * Narrowed auth detection for runtime capability reports.
3971
+ * Only covers provider-owned auth, which is the SDK-first default.
3972
+ */
3973
+ interface RuntimeAuthDetection extends ProviderAuthDetection {
3974
+ mode: 'provider-owned';
3975
+ }
3976
+ interface RuntimeCandidate {
3977
+ kind: AgentRuntimeKind;
3978
+ available: boolean;
3979
+ reason?: string;
3980
+ }
3981
+ interface RuntimeSelectionOptions {
3982
+ provider?: string;
3983
+ candidates: RuntimeCandidate[];
3984
+ preferredRuntime?: AgentRuntimeKind;
3985
+ allowFallback?: boolean;
3986
+ }
3987
+ interface RuntimeSelection {
3988
+ selected?: AgentRuntimeKind;
3989
+ fallback: boolean;
3990
+ fallbackReason?: string;
3991
+ error?: string;
3992
+ }
3993
+ interface RuntimeCapabilityReport extends RuntimeSelection {
3994
+ provider: string;
3995
+ candidates: RuntimeCandidate[];
3996
+ preferredRuntime?: AgentRuntimeKind;
3997
+ allowFallback: boolean;
3998
+ auth: RuntimeAuthDetection;
3999
+ policyCapabilities: RuntimePolicyCapabilities;
4000
+ sourceCapabilities: RuntimeSourceCapabilities;
4001
+ skillCapabilities: RuntimeSkillCapabilities;
4002
+ automationCapabilities: RuntimeAutomationCapabilities;
4003
+ hostToolCapabilities: RuntimeHostToolCapabilities;
4004
+ }
4005
+ interface CreateRuntimeCapabilityReportOptions extends RuntimeSelectionOptions {
4006
+ provider: string;
4007
+ auth: RuntimeAuthDetection;
4008
+ extensionCapabilities?: RuntimeExtensionCapabilities;
4009
+ }
4010
+ interface AgentRuntimeOptions {
4011
+ provider: string;
4012
+ cwd: string;
4013
+ sessionId?: string;
4014
+ model?: string;
4015
+ reasoningEffort?: string;
4016
+ permissionMode?: PermissionMode;
4017
+ authMode?: 'provider-owned';
4018
+ preferredRuntime?: AgentRuntimeKind;
4019
+ allowFallback?: boolean;
4020
+ executable?: string;
4021
+ env?: Record<string, string>;
4022
+ extensions?: RuntimeExtensionContext;
4023
+ }
4024
+ interface SendMessageOptions {
4025
+ turnId?: string;
4026
+ model?: string;
4027
+ reasoningEffort?: string;
4028
+ permissionMode?: PermissionMode;
4029
+ commandOrigin?: CommandOrigin;
4030
+ }
4031
+ type ToolPolicyDecision = {
4032
+ decision: 'allow';
4033
+ } | {
4034
+ decision: 'ask';
4035
+ reason: string;
4036
+ } | {
4037
+ decision: 'deny';
4038
+ reason: string;
4039
+ };
4040
+ interface CodexPermissionParams {
4041
+ approvalPolicy: string;
4042
+ approvalsReviewer: string;
4043
+ sandbox: string;
4044
+ }
4045
+ /**
4046
+ * Canonical PermissionMode → Codex permission parameters mapping, shared by
4047
+ * the app-server driver (thread/start, turn/start), the host controller, and
4048
+ * the CLI fallback runtime. `sandbox` is a Codex `SandboxMode` string as used
4049
+ * by `thread/start` and `codex exec --sandbox`.
4050
+ */
4051
+ declare function mapPermissionModeToCodexParams(mode: PermissionMode): CodexPermissionParams;
4052
+ /**
4053
+ * Codex app-server v2 `turn/start` takes a tagged `SandboxPolicy` object,
4054
+ * unlike `thread/start` which takes a plain `SandboxMode` string. Variant
4055
+ * fields are all serde-defaulted, so the minimal `{ type }` form is valid.
4056
+ */
4057
+ declare function mapCodexSandboxModeToSandboxPolicy(sandbox: string): {
4058
+ type: string;
4059
+ };
4060
+ type RuntimePermissionScope = {
4061
+ type: 'session';
4062
+ sessionId: string;
4063
+ } | {
4064
+ type: 'workspace';
4065
+ workspaceId: string;
4066
+ } | {
4067
+ type: 'source';
4068
+ sourceSlug: string;
4069
+ } | {
4070
+ type: 'skill';
4071
+ skillSlug: string;
4072
+ } | {
4073
+ type: 'automation';
4074
+ automationId: string;
4075
+ } | {
4076
+ type: 'tool-call';
4077
+ callId: string;
4078
+ };
4079
+ type RuntimePermissionScopeInput = string | RuntimePermissionScope;
4080
+ type RuntimeToolIntent = {
4081
+ kind: 'bash';
4082
+ command: string;
4083
+ baseCommand: string;
4084
+ } | {
4085
+ kind: 'file_write';
4086
+ path: string;
4087
+ toolName: string;
4088
+ } | {
4089
+ kind: 'mcp';
4090
+ name: string;
4091
+ } | {
4092
+ kind: 'api';
4093
+ method: string;
4094
+ path: string;
4095
+ url?: string;
4096
+ } | {
4097
+ kind: 'unknown';
4098
+ toolName: string;
4099
+ };
4100
+ interface ToolPolicyRequest {
4101
+ toolName: string;
4102
+ input?: Record<string, unknown>;
4103
+ toolIntent?: RuntimeToolIntent;
4104
+ scope?: RuntimePermissionScopeInput;
4105
+ }
4106
+ type RuntimePolicyHook = (request: ToolPolicyRequest) => ToolPolicyDecision | Promise<ToolPolicyDecision>;
4107
+ interface RuntimeFeatureCapabilities {
4108
+ supported: boolean;
4109
+ degraded?: boolean;
4110
+ reason?: string;
4111
+ }
4112
+ interface RuntimePolicyCapabilities extends RuntimeFeatureCapabilities {
4113
+ modes: PermissionMode[];
4114
+ approvals: boolean;
4115
+ toolPolicy: boolean;
4116
+ }
4117
+ interface RuntimeSourceCapabilities extends RuntimeFeatureCapabilities {
4118
+ registry?: boolean;
4119
+ credentialGateway?: boolean;
4120
+ mcpTools?: boolean;
4121
+ }
4122
+ interface RuntimeSkillCapabilities extends RuntimeFeatureCapabilities {
4123
+ registry?: boolean;
4124
+ activationPlan?: boolean;
4125
+ scopedPolicy?: boolean;
4126
+ }
4127
+ interface RuntimeAutomationCapabilities extends RuntimeFeatureCapabilities {
4128
+ eventBus: boolean;
4129
+ schedulerHost: boolean;
4130
+ promptAction: boolean;
4131
+ webhookAction: boolean;
4132
+ }
4133
+ interface RuntimeHostToolCapabilities extends RuntimeFeatureCapabilities {
4134
+ sessionTools: boolean;
4135
+ workflowTransitions: boolean;
4136
+ browserActions: boolean;
4137
+ metadataWrites: boolean;
4138
+ }
4139
+ interface RuntimeExtensionCapabilities {
4140
+ policy?: RuntimePolicyCapabilities;
4141
+ sources?: RuntimeSourceCapabilities;
4142
+ skills?: RuntimeSkillCapabilities;
4143
+ automations?: RuntimeAutomationCapabilities;
4144
+ hostTools?: RuntimeHostToolCapabilities;
4145
+ }
4146
+ interface RuntimePolicyExtension {
4147
+ mode: PermissionMode;
4148
+ hook?: RuntimePolicyHook;
4149
+ degraded?: boolean;
4150
+ }
4151
+ interface SourceSelection {
4152
+ enabledSourceSlugs: string[];
4153
+ }
4154
+ interface ProviderSourceCredentialRef {
4155
+ type: string;
4156
+ sourceSlug: string;
4157
+ workspaceId?: string;
4158
+ }
4159
+ type ProviderSourceToolDescriptor = {
4160
+ kind: 'api-source';
4161
+ sourceSlug: string;
4162
+ baseUrl: string;
4163
+ authType: string;
4164
+ defaultHeaders?: Record<string, string>;
4165
+ credentialRef?: ProviderSourceCredentialRef;
4166
+ [key: string]: unknown;
4167
+ } | {
4168
+ kind: 'local-source';
4169
+ sourceSlug: string;
4170
+ path: string;
4171
+ format?: string;
4172
+ [key: string]: unknown;
4173
+ } | {
4174
+ kind: 'mcp-server';
4175
+ sourceSlug: string;
4176
+ transport: 'stdio' | 'http' | 'sse';
4177
+ url?: string;
4178
+ command?: string;
4179
+ args?: string[];
4180
+ env?: Record<string, string>;
4181
+ headers?: Record<string, string>;
4182
+ credentialRef?: ProviderSourceCredentialRef;
4183
+ [key: string]: unknown;
4184
+ };
4185
+ interface SkillSelection {
4186
+ activeSkillSlugs: string[];
4187
+ }
4188
+ type CommandOrigin = {
4189
+ type: 'user';
4190
+ id?: string;
4191
+ } | {
4192
+ type: 'automation';
4193
+ id: string;
4194
+ } | {
4195
+ type: 'scheduler';
4196
+ id?: string;
4197
+ } | {
4198
+ type: 'host';
4199
+ id?: string;
4200
+ } | {
4201
+ type: 'replay';
4202
+ id?: string;
4203
+ } | {
4204
+ type: 'system';
4205
+ id?: string;
4206
+ };
4207
+ interface SubmitPlanRequest {
4208
+ sessionId?: string;
4209
+ planRef: string;
4210
+ origin?: CommandOrigin;
4211
+ }
4212
+ interface SubmitPlanReceipt {
4213
+ accepted: boolean;
4214
+ planRef?: string;
4215
+ reason?: string;
4216
+ }
4217
+ interface SourceAuthRequest {
4218
+ sessionId?: string;
4219
+ sourceSlug: string;
4220
+ reason?: string;
4221
+ }
4222
+ interface SourceAuthReceipt {
4223
+ ok: boolean;
4224
+ sourceSlug: string;
4225
+ reason?: string;
4226
+ }
4227
+ interface SourceActivationRequest {
4228
+ sessionId?: string;
4229
+ sourceSlug: string;
4230
+ }
4231
+ interface SourceActivationReceipt {
4232
+ ok: boolean;
4233
+ sourceSlug: string;
4234
+ availability?: 'immediate' | 'next-turn';
4235
+ reason?: string;
4236
+ }
4237
+ interface BrowserActionRequest {
4238
+ sessionId?: string;
4239
+ action: string;
4240
+ input?: unknown;
4241
+ }
4242
+ interface BrowserActionReceipt {
4243
+ ok: boolean;
4244
+ result?: unknown;
4245
+ reason?: string;
4246
+ }
4247
+ interface SpawnSessionRequest {
4248
+ parentSessionId?: string;
4249
+ prompt: string;
4250
+ model?: string;
4251
+ commandOrigin?: CommandOrigin;
4252
+ }
4253
+ interface SpawnSessionReceipt {
4254
+ sessionId: string;
4255
+ }
4256
+ interface InterSessionMessageRequest {
4257
+ sessionId: string;
4258
+ message: string;
4259
+ attachments?: Array<{
4260
+ path: string;
4261
+ name?: string;
4262
+ }>;
4263
+ commandOrigin?: CommandOrigin;
4264
+ }
4265
+ interface CommandReceipt {
4266
+ ok: boolean;
4267
+ commandId?: string;
4268
+ reason?: string;
4269
+ }
4270
+ interface SessionMetadataPatch {
4271
+ sessionId?: string;
4272
+ labels?: string[];
4273
+ status?: string;
4274
+ flagged?: boolean;
4275
+ topic?: string;
4276
+ }
4277
+ interface SessionMetadataSnapshot {
4278
+ sessionId?: string;
4279
+ labels?: string[];
4280
+ status?: string;
4281
+ flagged?: boolean;
4282
+ topic?: string;
4283
+ }
4284
+ interface SessionListRequest {
4285
+ status?: string;
4286
+ labels?: string[];
4287
+ limit?: number;
4288
+ }
4289
+ interface SessionListResult {
4290
+ sessions: SessionMetadataSnapshot[];
4291
+ }
4292
+ interface LlmToolRequest {
4293
+ prompt: string;
4294
+ model?: string;
4295
+ commandOrigin?: CommandOrigin;
4296
+ }
4297
+ interface LlmToolResult {
4298
+ text: string;
4299
+ model?: string;
4300
+ usage?: unknown;
4301
+ }
4302
+ interface ListSourcesRequest {
4303
+ sessionId?: string;
4304
+ enabledOnly?: boolean;
4305
+ }
4306
+ interface SourceSummary {
4307
+ slug: string;
4308
+ name: string;
4309
+ provider: string;
4310
+ type: string;
4311
+ enabled: boolean;
4312
+ isAuthenticated?: boolean;
4313
+ connectionStatus?: string;
4314
+ tagline?: string;
4315
+ }
4316
+ interface ListSourcesResult {
4317
+ sources: SourceSummary[];
4318
+ }
4319
+ interface GetSourceRequest {
4320
+ sessionId?: string;
4321
+ sourceSlug: string;
4322
+ }
4323
+ interface GetSourceResult {
4324
+ source: SourceSummary & {
4325
+ createdAt?: number;
4326
+ updatedAt?: number;
4327
+ mcp?: Record<string, unknown>;
4328
+ api?: Record<string, unknown>;
4329
+ local?: Record<string, unknown>;
4330
+ };
4331
+ }
4332
+ interface CreateSourceRequest {
4333
+ sessionId?: string;
4334
+ name: string;
4335
+ provider: string;
4336
+ type: string;
4337
+ mcp?: Record<string, unknown>;
4338
+ api?: Record<string, unknown>;
4339
+ local?: Record<string, unknown>;
4340
+ icon?: string;
4341
+ enabled?: boolean;
4342
+ }
4343
+ interface CreateSourceResult {
4344
+ ok: boolean;
4345
+ source?: SourceSummary;
4346
+ reason?: string;
4347
+ }
4348
+ interface UpdateSourceRequest {
4349
+ sessionId?: string;
4350
+ sourceSlug: string;
4351
+ enabled?: boolean;
4352
+ name?: string;
4353
+ icon?: string;
4354
+ tagline?: string;
4355
+ }
4356
+ interface UpdateSourceResult {
4357
+ ok: boolean;
4358
+ source?: SourceSummary;
4359
+ reason?: string;
4360
+ }
4361
+ interface DeleteSourceRequest {
4362
+ sessionId?: string;
4363
+ sourceSlug: string;
4364
+ }
4365
+ interface DeleteSourceResult {
4366
+ ok: boolean;
4367
+ sourceSlug: string;
4368
+ reason?: string;
4369
+ }
4370
+ interface ListSkillsRequest {
4371
+ sessionId?: string;
4372
+ }
4373
+ interface SkillSummary {
4374
+ slug: string;
4375
+ name: string;
4376
+ description: string;
4377
+ source: string;
4378
+ icon?: string;
4379
+ globs?: string[];
4380
+ requiredSources?: string[];
4381
+ }
4382
+ interface ListSkillsResult {
4383
+ skills: SkillSummary[];
4384
+ }
4385
+ interface GetSkillRequest {
4386
+ sessionId?: string;
4387
+ skillSlug: string;
4388
+ }
4389
+ interface GetSkillResult {
4390
+ skill: SkillSummary & {
4391
+ content: string;
4392
+ alwaysAllow?: string[];
4393
+ };
4394
+ }
4395
+ interface CreateSkillRequest {
4396
+ sessionId?: string;
4397
+ slug: string;
4398
+ name: string;
4399
+ description: string;
4400
+ content: string;
4401
+ globs?: string[];
4402
+ alwaysAllow?: string[];
4403
+ icon?: string;
4404
+ requiredSources?: string[];
4405
+ }
4406
+ interface CreateSkillResult {
4407
+ ok: boolean;
4408
+ skill?: SkillSummary;
4409
+ reason?: string;
4410
+ }
4411
+ interface UpdateSkillRequest {
4412
+ sessionId?: string;
4413
+ skillSlug: string;
4414
+ name?: string;
4415
+ description?: string;
4416
+ content?: string;
4417
+ globs?: string[];
4418
+ alwaysAllow?: string[];
4419
+ icon?: string;
4420
+ requiredSources?: string[];
4421
+ }
4422
+ interface UpdateSkillResult {
4423
+ ok: boolean;
4424
+ skill?: SkillSummary;
4425
+ reason?: string;
4426
+ }
4427
+ interface DeleteSkillRequest {
4428
+ sessionId?: string;
4429
+ skillSlug: string;
4430
+ }
4431
+ interface DeleteSkillResult {
4432
+ ok: boolean;
4433
+ skillSlug: string;
4434
+ reason?: string;
4435
+ }
4436
+ interface GetAutomationsConfigRequest {
4437
+ sessionId?: string;
4438
+ }
4439
+ interface GetAutomationsConfigResult {
4440
+ config: Record<string, unknown> | null;
4441
+ configPath: string;
4442
+ }
4443
+ interface UpdateAutomationsConfigRequest {
4444
+ sessionId?: string;
4445
+ config: Record<string, unknown>;
4446
+ }
4447
+ interface UpdateAutomationsConfigResult {
4448
+ ok: boolean;
4449
+ automationCount?: number;
4450
+ errors?: string[];
4451
+ }
4452
+ interface ListSchedulesRequest {
4453
+ sessionId?: string;
4454
+ }
4455
+ interface ScheduleSummary {
4456
+ schedulerId: string;
4457
+ workspaceId: string;
4458
+ cron: string;
4459
+ timezone: string;
4460
+ }
4461
+ interface ListSchedulesResult {
4462
+ schedules: ScheduleSummary[];
4463
+ }
4464
+ interface StartScheduleRequest {
4465
+ sessionId?: string;
4466
+ schedulerId: string;
4467
+ workspaceId: string;
4468
+ cron: string;
4469
+ timezone: string;
4470
+ }
4471
+ interface StartScheduleResult {
4472
+ schedulerId: string;
4473
+ state: 'started' | 'stopped';
4474
+ timestamp: number;
4475
+ }
4476
+ interface StopScheduleRequest {
4477
+ sessionId?: string;
4478
+ schedulerId: string;
4479
+ }
4480
+ interface StopScheduleResult {
4481
+ ok: boolean;
4482
+ schedulerId: string;
4483
+ state?: 'stopped';
4484
+ reason?: string;
4485
+ }
4486
+ interface SessionToolBridge {
4487
+ submitPlan?(request: SubmitPlanRequest): Promise<SubmitPlanReceipt>;
4488
+ requestSourceAuth?(request: SourceAuthRequest): Promise<SourceAuthReceipt>;
4489
+ activateSource?(request: SourceActivationRequest): Promise<SourceActivationReceipt>;
4490
+ runBrowserAction?(request: BrowserActionRequest): Promise<BrowserActionReceipt>;
4491
+ spawnSession?(request: SpawnSessionRequest): Promise<SpawnSessionReceipt>;
4492
+ sendSessionMessage?(request: InterSessionMessageRequest): Promise<CommandReceipt>;
4493
+ updateSessionMetadata?(request: SessionMetadataPatch): Promise<SessionMetadataSnapshot>;
4494
+ listSessions?(request: SessionListRequest): Promise<SessionListResult>;
4495
+ queryLlm?(request: LlmToolRequest): Promise<LlmToolResult>;
4496
+ listSources?(request: ListSourcesRequest): Promise<ListSourcesResult>;
4497
+ getSource?(request: GetSourceRequest): Promise<GetSourceResult>;
4498
+ createSource?(request: CreateSourceRequest): Promise<CreateSourceResult>;
4499
+ updateSource?(request: UpdateSourceRequest): Promise<UpdateSourceResult>;
4500
+ deleteSource?(request: DeleteSourceRequest): Promise<DeleteSourceResult>;
4501
+ listSkills?(request: ListSkillsRequest): Promise<ListSkillsResult>;
4502
+ getSkill?(request: GetSkillRequest): Promise<GetSkillResult>;
4503
+ createSkill?(request: CreateSkillRequest): Promise<CreateSkillResult>;
4504
+ updateSkill?(request: UpdateSkillRequest): Promise<UpdateSkillResult>;
4505
+ deleteSkill?(request: DeleteSkillRequest): Promise<DeleteSkillResult>;
4506
+ getAutomationsConfig?(request: GetAutomationsConfigRequest): Promise<GetAutomationsConfigResult>;
4507
+ updateAutomationsConfig?(request: UpdateAutomationsConfigRequest): Promise<UpdateAutomationsConfigResult>;
4508
+ listSchedules?(request: ListSchedulesRequest): Promise<ListSchedulesResult>;
4509
+ startSchedule?(request: StartScheduleRequest): Promise<StartScheduleResult>;
4510
+ stopSchedule?(request: StopScheduleRequest): Promise<StopScheduleResult>;
4511
+ }
4512
+ type SessionToolName = keyof SessionToolBridge;
4513
+ type SessionToolRequest = SubmitPlanRequest | SourceAuthRequest | SourceActivationRequest | BrowserActionRequest | SpawnSessionRequest | InterSessionMessageRequest | SessionMetadataPatch | SessionListRequest | LlmToolRequest | ListSourcesRequest | GetSourceRequest | CreateSourceRequest | UpdateSourceRequest | DeleteSourceRequest | ListSkillsRequest | GetSkillRequest | CreateSkillRequest | UpdateSkillRequest | DeleteSkillRequest | GetAutomationsConfigRequest | UpdateAutomationsConfigRequest | ListSchedulesRequest | StartScheduleRequest | StopScheduleRequest;
4514
+ interface SessionToolTimelineRef {
4515
+ epoch: string;
4516
+ seq: number;
4517
+ }
4518
+ interface SessionToolInvocationReceipt {
4519
+ ok: boolean;
4520
+ requestId: string;
4521
+ toolName: SessionToolName;
4522
+ origin?: CommandOrigin;
4523
+ policyDecision: ToolPolicyDecision;
4524
+ result?: unknown;
4525
+ reason?: string;
4526
+ timelineRefs: SessionToolTimelineRef[];
4527
+ }
4528
+ interface InvokeSessionToolOptions {
4529
+ sessionId: string;
4530
+ toolName: SessionToolName;
4531
+ request: SessionToolRequest;
4532
+ bridge: SessionToolBridge;
4533
+ policy?: RuntimePolicyHook;
4534
+ commandOrigin?: CommandOrigin;
4535
+ appendTimeline?: (item: TimelineItem) => TimelineEnvelope;
4536
+ }
4537
+ interface RuntimeHostServices {
4538
+ sessionTools?: SessionToolBridge;
4539
+ }
4540
+ interface RuntimeExtensionContext {
4541
+ policy?: RuntimePolicyExtension;
4542
+ sources?: SourceSelection;
4543
+ skills?: SkillSelection;
4544
+ commandOrigin?: CommandOrigin;
4545
+ hostServices?: RuntimeHostServices;
4546
+ }
4547
+ interface AgentCommandSink {
4548
+ sendMessage(message: string, options?: SendMessageOptions): Promise<void>;
4549
+ abort(reason?: string): Promise<void>;
4550
+ respondToPermission(requestId: string, allowed: boolean, remember?: boolean): Promise<void>;
4551
+ resumeTool?(runId: string, resumeData: Record<string, unknown>): Promise<void>;
4552
+ dispose(): Promise<void>;
4553
+ }
4554
+ interface AgentEventStream {
4555
+ connect(onEvent: (event: AgentEvent) => void, onError?: (error: Error) => void, onClose?: () => void): void;
4556
+ disconnect(): void;
4557
+ isConnected(): boolean;
4558
+ }
4559
+ interface AgentTimelineStream {
4560
+ connect(onEvent: (event: TimelineEnvelope) => void, onError?: (error: Error) => void, onClose?: () => void): void;
4561
+ disconnect(): void;
4562
+ isConnected(): boolean;
4563
+ }
4564
+ interface AgentRuntimeState {
4565
+ status: AgentRuntimeStatus;
4566
+ acceptedMessages: string[];
4567
+ queuedMessages: string[];
4568
+ lastError?: string;
4569
+ waitingPermissionRequestId?: string;
4570
+ }
4571
+ type RuntimeAction = {
4572
+ type: 'preflight_start';
4573
+ } | {
4574
+ type: 'preflight_ok';
4575
+ } | {
4576
+ type: 'preflight_error';
4577
+ error: string;
4578
+ } | {
4579
+ type: 'starting';
4580
+ } | {
4581
+ type: 'send_message';
4582
+ message: string;
4583
+ } | {
4584
+ type: 'permission_request';
4585
+ requestId: string;
4586
+ } | {
4587
+ type: 'permission_response';
4588
+ } | {
4589
+ type: 'turn_completed';
4590
+ } | {
4591
+ type: 'complete';
4592
+ } | {
4593
+ type: 'abort';
4594
+ reason?: string;
4595
+ } | {
4596
+ type: 'error';
4597
+ error: string;
4598
+ } | {
4599
+ type: 'dispose';
4600
+ };
4601
+ declare const initialRuntimeState: AgentRuntimeState;
4602
+ /**
4603
+ * Canonical state machine reducer for AgentRuntime lifecycle.
4604
+ *
4605
+ * Transitions follow the architecture spec:
4606
+ * idle → preflighting → ready → starting → running
4607
+ * running → waiting_for_permission → running
4608
+ * running → turn_completed → ready
4609
+ * running → ready (via complete with empty queue)
4610
+ * any → failed / disposed
4611
+ * any non-disposed → ready (via abort)
4612
+ *
4613
+ * `send_message` while running enqueues (session manager semantics).
4614
+ * `complete` drains the queue: if a queued message exists, it is
4615
+ * immediately accepted and the state stays running.
4616
+ */
4617
+ declare function reduceRuntimeState(state: AgentRuntimeState | undefined, action: RuntimeAction): AgentRuntimeState;
4618
+ interface AgentRuntime {
4619
+ readonly sessionId: string;
4620
+ readonly provider: string;
4621
+ readonly runtimeKind: AgentRuntimeKind;
4622
+ readonly events: AgentTimelineStream;
4623
+ readonly commands: AgentCommandSink;
4624
+ preflight(): Promise<RuntimeCapabilityReport>;
4625
+ fetchTimeline(request: TimelineFetchRequest): Promise<TimelineFetchResult>;
4626
+ getState(): AgentRuntimeState;
4627
+ }
4628
+ declare function createRuntimeExtensionContext(context?: RuntimeExtensionContext): RuntimeExtensionContext;
4629
+ declare function sanitizeProviderSourceTools(sourceTools: ProviderSourceToolDescriptor[] | undefined): ProviderSourceToolDescriptor[];
4630
+ declare function invokeSessionTool(options: InvokeSessionToolOptions): Promise<SessionToolInvocationReceipt>;
4631
+ declare function selectRuntimeCandidate(options: RuntimeSelectionOptions): RuntimeSelection;
4632
+ declare function createRuntimeCapabilityReport(options: CreateRuntimeCapabilityReportOptions): RuntimeCapabilityReport;
4633
+
4634
+ export { type AgentCommandSink, type AgentEventStream, type AgentRuntime, type AgentRuntimeKind, type AgentRuntimeOptions, type AgentRuntimeState, type AgentRuntimeStatus, type AgentTimelineStream, type BrowserActionReceipt, type BrowserActionRequest, type CodexPermissionParams, type CommandOrigin, type CommandReceipt, type CreateRuntimeCapabilityReportOptions, type CreateSkillRequest, type CreateSkillResult, type CreateSourceRequest, type CreateSourceResult, type DeleteSkillRequest, type DeleteSkillResult, type DeleteSourceRequest, type DeleteSourceResult, type GetAutomationsConfigRequest, type GetAutomationsConfigResult, type GetSkillRequest, type GetSkillResult, type GetSourceRequest, type GetSourceResult, type InterSessionMessageRequest, type InvokeSessionToolOptions, type ListSchedulesRequest, type ListSchedulesResult, type ListSkillsRequest, type ListSkillsResult, type ListSourcesRequest, type ListSourcesResult, type LlmToolRequest, type LlmToolResult, type ProviderAuthDetection, type ProviderAuthMode, type ProviderSourceCredentialRef, type ProviderSourceToolDescriptor, RUNTIME_KINDS, type RuntimeAction, type RuntimeAuthDetection, type RuntimeAutomationCapabilities, type RuntimeCandidate, type RuntimeCapabilityReport, type RuntimeExtensionCapabilities, type RuntimeExtensionContext, type RuntimeFeatureCapabilities, type RuntimeHostServices, type RuntimeHostToolCapabilities, type RuntimePermissionScope, type RuntimePermissionScopeInput, type RuntimePolicyCapabilities, type RuntimePolicyExtension, type RuntimePolicyHook, type RuntimeSelection, type RuntimeSelectionOptions, type RuntimeSkillCapabilities, type RuntimeSourceCapabilities, type RuntimeToolIntent, type ScheduleSummary, type SendMessageOptions, type SessionListRequest, type SessionListResult, type SessionMetadataPatch, type SessionMetadataSnapshot, type SessionToolBridge, type SessionToolInvocationReceipt, type SessionToolName, type SessionToolRequest, type SessionToolTimelineRef, type SkillSelection, type SkillSummary, type SourceActivationReceipt, type SourceActivationRequest, type SourceAuthReceipt, type SourceAuthRequest, type SourceSelection, type SourceSummary, type SpawnSessionReceipt, type SpawnSessionRequest, type StartScheduleRequest, type StartScheduleResult, type StopScheduleRequest, type StopScheduleResult, type SubmitPlanReceipt, type SubmitPlanRequest, type ToolPolicyDecision, type ToolPolicyRequest, type UpdateAutomationsConfigRequest, type UpdateAutomationsConfigResult, type UpdateSkillRequest, type UpdateSkillResult, type UpdateSourceRequest, type UpdateSourceResult, createRuntimeCapabilityReport, createRuntimeExtensionContext, initialRuntimeState, invokeSessionTool, mapCodexSandboxModeToSandboxPolicy, mapPermissionModeToCodexParams, reduceRuntimeState, sanitizeProviderSourceTools, selectRuntimeCandidate };
4635
+
4636
+ // ── inlined from @weft/local-chat ──
4637
+ // -- @weft/local-chat/index.d.ts --
4638
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4639
+
4640
+ interface LocalChatAuthDetection {
4641
+ provider: string;
4642
+ configured: boolean;
4643
+ source?: string;
4644
+ error?: string;
4645
+ }
4646
+ interface LocalChatRuntimeState {
4647
+ status: 'idle' | 'preflighting' | 'running' | 'ready' | 'failed' | string;
4648
+ }
4649
+ interface LocalChatEventSource {
4650
+ connect(onEvent: (event: AgentEvent) => void, onError?: (error: Error) => void, onClose?: () => void): void;
4651
+ disconnect(): void;
4652
+ isConnected(): boolean;
4653
+ }
4654
+ interface LocalChatCommandSink {
4655
+ sendMessage(message: string): Promise<void>;
4656
+ abort(reason?: string): Promise<void>;
4657
+ respondToPermission(requestId: string, allowed: boolean, remember?: boolean): Promise<void>;
4658
+ }
4659
+ interface LocalChatSessionRuntime {
4660
+ sessionId: string;
4661
+ provider: string;
4662
+ events: LocalChatEventSource;
4663
+ commands: LocalChatCommandSink;
4664
+ preflight(): Promise<LocalChatAuthDetection>;
4665
+ getState(): LocalChatRuntimeState;
4666
+ }
4667
+ interface AgentChatSessionModel {
4668
+ session: Session | null;
4669
+ turns: Turn[];
4670
+ isRunning: boolean;
4671
+ auth: LocalChatAuthDetection | null;
4672
+ error: Error | null;
4673
+ sendMessage(message: string): Promise<void>;
4674
+ abort(): Promise<void>;
4675
+ respondToPermission(requestId: string, allowed: boolean, remember?: boolean): Promise<void>;
4676
+ }
4677
+ interface UseAgentChatSessionOptions {
4678
+ runtime: LocalChatSessionRuntime;
4679
+ workspaceId?: string;
4680
+ workspaceName?: string;
4681
+ }
4682
+ interface TimelineChatPanelModel {
4683
+ session: Session;
4684
+ turns: Turn[];
4685
+ }
4686
+ type TimelineDetailKind = 'permission' | 'runtime' | 'source' | 'skill' | 'automation' | 'host' | 'tool';
4687
+ interface TimelineDetailItem {
4688
+ id: string;
4689
+ kind: TimelineDetailKind;
4690
+ title: string;
4691
+ summary?: string;
4692
+ status?: string;
4693
+ timestamp: number;
4694
+ detail: unknown;
4695
+ envelope: TimelineEnvelope;
4696
+ }
4697
+ interface TimelineAgentChatSessionModel extends TimelineChatPanelModel {
4698
+ timeline: TimelineEnvelope[];
4699
+ isRunning: boolean;
4700
+ isConnected: boolean;
4701
+ isReconnecting: boolean;
4702
+ hasGap: boolean;
4703
+ capabilityReport: RuntimeCapabilityReport | null;
4704
+ error: Error | null;
4705
+ sendMessage(message: string): Promise<void>;
4706
+ abort(): Promise<void>;
4707
+ respondToPermission(requestId: string, allowed: boolean, remember?: boolean): Promise<void>;
4708
+ }
4709
+ interface UseTimelineAgentChatSessionOptions {
4710
+ runtime: AgentRuntime;
4711
+ workspaceId?: string;
4712
+ workspaceName?: string;
4713
+ }
4714
+ declare function createAgentChatPanelModel(args: {
4715
+ session: Session | null;
4716
+ runtime: LocalChatSessionRuntime;
4717
+ auth?: LocalChatAuthDetection | null;
4718
+ error?: Error | null;
4719
+ }): Pick<AgentChatSessionModel, 'turns' | 'isRunning' | 'auth' | 'error'>;
4720
+ declare function createAgentChatPanelModelFromTimeline(args: {
4721
+ timeline: TimelineEnvelope[];
4722
+ sessionId: string;
4723
+ workspaceId: string;
4724
+ workspaceName?: string;
4725
+ }): TimelineChatPanelModel;
4726
+ declare function createTimelineAgentChatPanelModel(args: {
4727
+ timeline: TimelineEnvelope[];
4728
+ sessionId: string;
4729
+ workspaceId: string;
4730
+ workspaceName?: string;
4731
+ runtimeState: AgentRuntimeState;
4732
+ capabilityReport: RuntimeCapabilityReport | null;
4733
+ error: Error | null;
4734
+ }): Pick<TimelineAgentChatSessionModel, 'session' | 'turns' | 'isRunning' | 'capabilityReport' | 'error'>;
4735
+ declare function createTimelineDetailItems(timeline: TimelineEnvelope[]): TimelineDetailItem[];
4736
+ declare function useAgentChatSession(options: UseAgentChatSessionOptions): AgentChatSessionModel;
4737
+ declare function useTimelineAgentChatSession(options: UseTimelineAgentChatSessionOptions): TimelineAgentChatSessionModel;
4738
+
4739
+ interface AgentChatPanelProps {
4740
+ runtime: LocalChatSessionRuntime;
4741
+ workspaceId?: string;
4742
+ workspaceName?: string;
4743
+ platformActions?: PlatformActions;
4744
+ placeholder?: string;
4745
+ className?: string;
4746
+ }
4747
+ declare function AgentChatPanel({ runtime, workspaceId, workspaceName, platformActions, placeholder, className, }: AgentChatPanelProps): react_jsx_runtime.JSX.Element;
4748
+
4749
+ interface TimelineAgentChatPanelProps {
4750
+ /** Agent runtime instance from runtime-core */
4751
+ runtime: AgentRuntime;
4752
+ /** Workspace identifier */
4753
+ workspaceId?: string;
4754
+ /** Workspace display name */
4755
+ workspaceName?: string;
4756
+ /** Platform actions for file/URL handling */
4757
+ platformActions?: PlatformActions;
4758
+ /** Placeholder text for the input area */
4759
+ placeholder?: string;
4760
+ /** Whether to show the runtime status bar */
4761
+ showStatusBar?: boolean;
4762
+ /** Whether to show the runtime detail sidebar panel */
4763
+ showDetailPanel?: boolean;
4764
+ /** Additional className */
4765
+ className?: string;
4766
+ }
4767
+ declare function TimelineAgentChatPanel({ runtime, workspaceId, workspaceName, platformActions, placeholder, showStatusBar, showDetailPanel, className, }: TimelineAgentChatPanelProps): react_jsx_runtime.JSX.Element;
4768
+
4769
+ /**
4770
+ * Find the active (unresolved) permission request from timeline envelopes.
4771
+ *
4772
+ * Walks the timeline backwards to find the most recent permission_requested
4773
+ * envelope that has not been resolved by a matching permission_resolved.
4774
+ */
4775
+ declare function findActivePermissionRequest(timeline: TimelineEnvelope[]): {
4776
+ requestId: string;
4777
+ toolName: string;
4778
+ input?: Record<string, unknown>;
4779
+ reason?: string;
4780
+ scope?: {
4781
+ type: string;
4782
+ label?: string;
4783
+ };
4784
+ } | null;
4785
+
4786
+ /**
4787
+ * Convert a processor Session (returned by useAgentChatSession) into a
4788
+ * StoredSession that SessionViewer can render.
4789
+ *
4790
+ * Consumers embedding AgentChatPanel don't need this — it's called internally.
4791
+ * This utility is exported for consumers who use useAgentChatSession directly
4792
+ * and build their own panel around SessionViewer.
4793
+ */
4794
+ declare function toStoredSession(session: Session, fallbackWorkspaceId?: string): StoredSession;
4795
+ /**
4796
+ * Build an empty StoredSession placeholder for the initial state
4797
+ * before the event processor has received any events.
4798
+ */
4799
+ declare function createEmptyStoredSession(sessionId: string, workspaceId?: string, workspaceName?: string): StoredSession;
4800
+
4801
+ export { AgentChatPanel, type AgentChatPanelProps, type AgentChatSessionModel, type LocalChatAuthDetection, type LocalChatCommandSink, type LocalChatEventSource, type LocalChatRuntimeState, type LocalChatSessionRuntime, TimelineAgentChatPanel, type TimelineAgentChatPanelProps, type TimelineAgentChatSessionModel, type TimelineChatPanelModel, type TimelineDetailItem, type TimelineDetailKind, type UseAgentChatSessionOptions, type UseTimelineAgentChatSessionOptions, createAgentChatPanelModel, createAgentChatPanelModelFromTimeline, createEmptyStoredSession, createTimelineAgentChatPanelModel, createTimelineDetailItems, findActivePermissionRequest, toStoredSession, useAgentChatSession, useTimelineAgentChatSession };
4802
+
4803
+ // ── inlined from @weft/provider-flitro ──
4804
+ // -- @weft/provider-flitro/index.d.ts --
4805
+ import { FlitroHttpClient, FlitroClientOptions } from '@percena/weft-client';
4806
+ export { FlitroCapabilityReport, FlitroClientOptions, FlitroFetchSseTimelineStream, FlitroHttpClient, FlitroModelInfo, FlitroModelListResult, FlitroPatchSessionOptions, FlitroRun, FlitroSession, FlitroSseTimelineStream, FlitroSseTimelineStreamOptions, FlitroTimelineFetchResult, FlitroTimelineItem, TimelineSubscription, WeftClient, WeftClientOptions, createFlitroTimelineStream } from '@percena/weft-client';
4807
+
4808
+ /**
4809
+ * FlitroProviderRuntimeDriver
4810
+ *
4811
+ * Sends messages to the Flitro Go server and routes permission responses back.
4812
+ * Implements the same driver interface pattern as provider-claude's
4813
+ * ClaudeProviderRuntimeDriver.
4814
+ */
4815
+
4816
+ interface FlitroDriverInput {
4817
+ message: string;
4818
+ options?: SendMessageOptions;
4819
+ }
4820
+ interface FlitroProviderRuntimeDriver {
4821
+ sendMessage(input: FlitroDriverInput, sequencer: TimelineSequencer): Promise<void>;
4822
+ abort?(reason?: string): Promise<void>;
4823
+ respondToPermission?(requestId: string, allowed: boolean, remember?: boolean): Promise<void>;
4824
+ resumeTool?(runId: string, resumeData: Record<string, unknown>): Promise<void>;
4825
+ dispose?(): Promise<void>;
4826
+ }
4827
+ interface CreateFlitroDriverOptions {
4828
+ client: FlitroHttpClient;
4829
+ sessionId: string;
4830
+ /** LLM model override sent to Flitro */
4831
+ model?: string;
4832
+ /** Skill names to activate for each message */
4833
+ skillNames?: string[];
4834
+ /** MCP server names to attach */
4835
+ mcpServerNames?: string[];
4836
+ /** Default approval policy: "auto", "require_all", "deny_all" */
4837
+ approvalPolicy?: string;
4838
+ }
4839
+ /**
4840
+ * Creates a runtime driver that delegates to the Flitro server.
4841
+ *
4842
+ * sendMessage creates a Flitro Run (one message = one turn = one Run).
4843
+ * The timeline events flow back via the SSE stream set up separately.
4844
+ */
4845
+ declare function createFlitroDriver(options: CreateFlitroDriverOptions): FlitroProviderRuntimeDriver;
4846
+
4847
+ /**
4848
+ * FlitroCapabilityProbe
4849
+ *
4850
+ * Detects whether a Flitro server is reachable and authenticated, then
4851
+ * builds the RuntimeCandidate list for createFlitroRuntimeCapabilityReport.
4852
+ */
4853
+
4854
+ interface FlitroCapabilityProbeResult {
4855
+ serverAvailable: boolean;
4856
+ authenticated: boolean;
4857
+ serverReason?: string;
4858
+ authReason?: string;
4859
+ candidates: RuntimeCandidate[];
4860
+ auth: RuntimeAuthDetection;
4861
+ }
4862
+ /**
4863
+ * Probe the Flitro server and return availability + auth candidates.
4864
+ *
4865
+ * Flitro is always an "app-server" runtime kind — it runs as an external
4866
+ * process (the Go agentd binary) that the TypeScript provider communicates
4867
+ * with over HTTP.
4868
+ */
4869
+ declare function probeFlitroCapabilities(client: FlitroHttpClient): Promise<FlitroCapabilityProbeResult>;
4870
+
4871
+ /**
4872
+ * @weft/provider-flitro
4873
+ *
4874
+ * Weft Runtime Provider for the Flitro Go Agent Server.
4875
+ *
4876
+ * Flitro is the 3rd AgentRuntime alongside Claude and Codex:
4877
+ * - provider-claude → Claude Agent SDK (native-sdk) / claude -p (cli-fallback)
4878
+ * - provider-codex → Codex app-server / codex exec (cli-fallback)
4879
+ * - provider-flitro → Flitro agentd HTTP API (app-server)
4880
+ *
4881
+ * Integration model:
4882
+ * - Flitro runs as the Go backend (stateful, multi-tenant, concurrent)
4883
+ * - This provider wraps Flitro's REST+SSE API as a Weft AgentRuntime
4884
+ * - Weft policy, sources, and skills are forwarded as API parameters
4885
+ * - The Weft UI (TurnCard, etc.) consumes the canonical timeline
4886
+ */
4887
+
4888
+ interface CreateFlitroRuntimeCandidatesOptions {
4889
+ appServerAvailable: boolean;
4890
+ appServerReason?: string;
4891
+ }
4892
+ declare function createFlitroRuntimeCandidates(options: CreateFlitroRuntimeCandidatesOptions): RuntimeCandidate[];
4893
+ interface CreateFlitroRuntimeCapabilityReportOptions {
4894
+ candidates: RuntimeCandidate[];
4895
+ auth: RuntimeAuthDetection;
4896
+ allowFallback?: boolean;
4897
+ extensions?: RuntimeExtensionContext;
4898
+ }
4899
+ declare function createFlitroRuntimeCapabilityReport(options: CreateFlitroRuntimeCapabilityReportOptions): RuntimeCapabilityReport;
4900
+ interface CreateFlitroProviderRuntimeOptions extends CreateFlitroRuntimeCapabilityReportOptions {
4901
+ /** Flitro server connection options */
4902
+ server: FlitroClientOptions;
4903
+ /** Session ID — if omitted a new session is created on first sendMessage */
4904
+ sessionId?: string;
4905
+ /** Epoch string for the timeline (default: derived from sessionId) */
4906
+ epoch?: string;
4907
+ now?: () => number;
4908
+ /** LLM model to use */
4909
+ model?: string;
4910
+ /** Skills to activate per turn */
4911
+ skillNames?: string[];
4912
+ /** MCP servers to attach per turn */
4913
+ mcpServerNames?: string[];
4914
+ /** Approval policy */
4915
+ approvalPolicy?: string;
4916
+ /** Injected runtime extensions (policy, sources, etc.) */
4917
+ extensions?: RuntimeExtensionContext;
4918
+ /** Pre-built driver (for testing) */
4919
+ driver?: FlitroProviderRuntimeDriver;
4920
+ }
4921
+ /**
4922
+ * Create a Weft AgentRuntime backed by the Flitro Go server.
4923
+ *
4924
+ * Usage:
4925
+ * ```ts
4926
+ * const runtime = createFlitroProviderRuntime({
4927
+ * server: { baseUrl: 'http://localhost:8080', apiKey: 'secret' },
4928
+ * candidates: [{ kind: 'app-server', available: true }],
4929
+ * auth: { mode: 'provider-owned', configured: true, source: 'flitro' },
4930
+ * sessionId: 'my-session',
4931
+ * })
4932
+ * await runtime.preflight()
4933
+ * await runtime.commands.sendMessage('Hello!')
4934
+ * ```
4935
+ */
4936
+ declare function createFlitroProviderRuntime(options: CreateFlitroProviderRuntimeOptions): AgentRuntime;
4937
+ interface CreateFlitroEmbedRuntimeOptions {
4938
+ /** Flitro server base URL, as returned by `POST /v1/embed/sessions`. */
4939
+ baseUrl: string;
4940
+ /** Scoped session token, as returned by `POST /v1/embed/sessions`. */
4941
+ token: string;
4942
+ /** Session bound to the token, as returned by `POST /v1/embed/sessions`. */
4943
+ sessionId: string;
4944
+ /** Re-fetch a token from the host backend when the current one expires. */
4945
+ onTokenExpired?: () => Promise<string | undefined> | string | undefined;
4946
+ epoch?: string;
4947
+ now?: () => number;
4948
+ extensions?: RuntimeExtensionContext;
4949
+ }
4950
+ /**
4951
+ * Create an AgentRuntime for an embedded (third-party website) chat panel.
4952
+ *
4953
+ * The host backend bootstraps the session via Flitro's `POST /v1/embed/sessions`
4954
+ * (with its developer API key) and hands `{ baseUrl, token, sessionId }` to the
4955
+ * browser. Execution mode, permission envelope, approval policy, and the tool
4956
+ * whitelist are fixed server-side, so no runtime auth or policy configuration
4957
+ * is needed here.
4958
+ */
4959
+ declare function createFlitroEmbedRuntime(options: CreateFlitroEmbedRuntimeOptions): AgentRuntime;
4960
+ interface CreateFlitroRuntimeOptions {
4961
+ /** Flitro server connection options */
4962
+ server: FlitroClientOptions;
4963
+ sessionId?: string;
4964
+ epoch?: string;
4965
+ now?: () => number;
4966
+ model?: string;
4967
+ skillNames?: string[];
4968
+ mcpServerNames?: string[];
4969
+ approvalPolicy?: string;
4970
+ allowFallback?: boolean;
4971
+ extensions?: RuntimeExtensionContext;
4972
+ }
4973
+ /**
4974
+ * High-level factory: probes the Flitro server, then creates the runtime.
4975
+ *
4976
+ * Equivalent to the pattern used by createHostAgentRuntime() in runtime-factory.
4977
+ */
4978
+ declare function createFlitroRuntime(options: CreateFlitroRuntimeOptions): Promise<AgentRuntime>;
4979
+
4980
+ export { type CreateFlitroDriverOptions, type CreateFlitroEmbedRuntimeOptions, type CreateFlitroProviderRuntimeOptions, type CreateFlitroRuntimeCandidatesOptions, type CreateFlitroRuntimeCapabilityReportOptions, type CreateFlitroRuntimeOptions, type FlitroCapabilityProbeResult, type FlitroProviderRuntimeDriver, createFlitroDriver, createFlitroEmbedRuntime, createFlitroProviderRuntime, createFlitroRuntime, createFlitroRuntimeCandidates, createFlitroRuntimeCapabilityReport, probeFlitroCapabilities };