-
Notifications
You must be signed in to change notification settings - Fork 841
Expand file tree
/
Copy pathClaudianService.ts
More file actions
1817 lines (1585 loc) · 63.1 KB
/
Copy pathClaudianService.ts
File metadata and controls
1817 lines (1585 loc) · 63.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Claudian - Claude Agent SDK wrapper
*
* Handles communication with Claude via the Agent SDK. Manages streaming,
* session persistence, permission modes, and security hooks.
*
* Architecture:
* - Persistent query for active chat conversation (eliminates cold-start latency)
* - Cold-start queries for inline edit, title generation
* - MessageChannel for message queueing and turn management
* - Dynamic updates (model, thinking tokens, permission mode, MCP servers)
*/
import type {
CanUseTool,
McpServerConfig,
Options,
PermissionMode as SDKPermissionMode,
PermissionResult,
Query,
RewindFilesResult,
SDKMessage,
SDKUserMessage,
SlashCommand as SDKSlashCommand,
} from '@anthropic-ai/claude-agent-sdk';
import { query as agentQuery } from '@anthropic-ai/claude-agent-sdk';
import { randomUUID } from 'crypto';
import * as fs from 'fs';
import { Notice } from 'obsidian';
import * as os from 'os';
import * as path from 'path';
import type ClaudianPlugin from '../../main';
import { stripCurrentNoteContext } from '../../utils/context';
import { getEnhancedPath, getMissingNodeError, parseEnvironmentVariables } from '../../utils/env';
import { getPathAccessType, getVaultPath } from '../../utils/path';
import {
buildContextFromHistory,
buildPromptWithHistoryContext,
getLastUserMessage,
isAuthenticationError,
isSessionExpiredError,
} from '../../utils/session';
import {
createBlocklistHook,
createVaultRestrictionHook,
} from '../hooks';
import type { McpServerManager } from '../mcp';
import { isSessionInitEvent, isStreamChunk, transformSDKMessage } from '../sdk';
import {
buildPermissionUpdates,
getActionDescription,
} from '../security';
import { TOOL_ASK_USER_QUESTION, TOOL_ENTER_PLAN_MODE, TOOL_EXIT_PLAN_MODE, TOOL_SKILL } from '../tools/toolNames';
import type {
ApprovalDecision,
ChatMessage,
Conversation,
ExitPlanModeCallback,
ExitPlanModeDecision,
ImageAttachment,
PermissionMode,
SlashCommand,
StreamChunk,
} from '../types';
import { isAdaptiveThinkingModel, THINKING_BUDGETS } from '../types';
import { MessageChannel } from './MessageChannel';
import {
type ColdStartQueryContext,
type PersistentQueryContext,
QueryOptionsBuilder,
type QueryOptionsContext,
} from './QueryOptionsBuilder';
import { SessionManager } from './SessionManager';
import {
type ClosePersistentQueryOptions,
createResponseHandler,
isTurnCompleteMessage,
type PersistentQueryConfig,
type ResponseHandler,
type UserContentBlock,
} from './types';
export type { ApprovalDecision };
export interface ApprovalCallbackOptions {
decisionReason?: string;
blockedPath?: string;
agentID?: string;
}
export type ApprovalCallback = (
toolName: string,
input: Record<string, unknown>,
description: string,
options?: ApprovalCallbackOptions,
) => Promise<ApprovalDecision>;
export type AskUserQuestionCallback = (
input: Record<string, unknown>,
signal?: AbortSignal,
) => Promise<Record<string, string> | null>;
export interface QueryOptions {
allowedTools?: string[];
model?: string;
/** MCP servers @-mentioned in the prompt. */
mcpMentions?: Set<string>;
/** MCP servers enabled via UI selector (in addition to @-mentioned servers). */
enabledMcpServers?: Set<string>;
/** Force cold-start query (bypass persistent query). */
forceColdStart?: boolean;
/** Session-specific external context paths (directories with full access). */
externalContextPaths?: string[];
}
export interface EnsureReadyOptions {
/** Session ID to resume. Auto-resolved from sessionManager if not provided. */
sessionId?: string;
/** External context paths to include. */
externalContextPaths?: string[];
/** Force restart even if query is running (for session switch, crash recovery). */
force?: boolean;
/** Preserve response handlers across restart (for mid-turn crash recovery). */
preserveHandlers?: boolean;
}
export class ClaudianService {
private plugin: ClaudianPlugin;
private abortController: AbortController | null = null;
private approvalCallback: ApprovalCallback | null = null;
private approvalDismisser: (() => void) | null = null;
private askUserQuestionCallback: AskUserQuestionCallback | null = null;
private exitPlanModeCallback: ExitPlanModeCallback | null = null;
private permissionModeSyncCallback: ((sdkMode: string) => void) | null = null;
private vaultPath: string | null = null;
private currentExternalContextPaths: string[] = [];
private readyStateListeners = new Set<(ready: boolean) => void>();
// Modular components
private sessionManager = new SessionManager();
private mcpManager: McpServerManager;
private persistentQuery: Query | null = null;
private messageChannel: MessageChannel | null = null;
private queryAbortController: AbortController | null = null;
private responseHandlers: ResponseHandler[] = [];
private responseConsumerRunning = false;
private responseConsumerPromise: Promise<void> | null = null;
private shuttingDown = false;
// Tracked configuration for detecting changes that require restart
private currentConfig: PersistentQueryConfig | null = null;
// Current allowed tools for canUseTool enforcement (null = no restriction)
private currentAllowedTools: string[] | null = null;
private pendingResumeAt?: string;
private pendingForkSession = false;
// Last sent message for crash recovery (Phase 1.3)
private lastSentMessage: SDKUserMessage | null = null;
private lastSentQueryOptions: QueryOptions | null = null;
private crashRecoveryAttempted = false;
private coldStartInProgress = false; // Prevent consumer error restarts during cold-start
constructor(plugin: ClaudianPlugin, mcpManager: McpServerManager) {
this.plugin = plugin;
this.mcpManager = mcpManager;
}
onReadyStateChange(listener: (ready: boolean) => void): () => void {
this.readyStateListeners.add(listener);
try {
listener(this.isReady());
} catch {
// Ignore listener errors
}
return () => {
this.readyStateListeners.delete(listener);
};
}
private notifyReadyStateChange(): void {
if (this.readyStateListeners.size === 0) {
return;
}
const isReady = this.isReady();
for (const listener of this.readyStateListeners) {
try {
listener(isReady);
} catch {
// Ignore listener errors
}
}
}
setPendingResumeAt(uuid: string | undefined): void {
this.pendingResumeAt = uuid;
}
/** One-shot: consumed on the next query, then cleared by routeMessage on session init. */
applyForkState(conv: Pick<Conversation, 'sessionId' | 'sdkSessionId' | 'forkSource'>): string | null {
const isPending = !conv.sessionId && !conv.sdkSessionId && !!conv.forkSource;
this.pendingForkSession = isPending;
if (isPending) {
this.pendingResumeAt = conv.forkSource!.resumeAt;
} else {
this.pendingResumeAt = undefined;
}
return conv.sessionId ?? conv.forkSource?.sessionId ?? null;
}
async reloadMcpServers(): Promise<void> {
await this.mcpManager.loadServers();
}
/**
* Ensures the persistent query is running with current configuration.
* Unified API that replaces preWarm() and restartPersistentQuery().
*
* Behavior:
* - If not running → start (if paths available)
* - If running and force=true → close and restart
* - If running and config changed → close and restart
* - If running and config unchanged → no-op
*
* Note: When restart is needed, the query is closed BEFORE checking if we can
* start a new one. This ensures fallback to cold-start if CLI becomes unavailable.
*
* @returns true if the query was (re)started, false otherwise
*/
async ensureReady(options?: EnsureReadyOptions): Promise<boolean> {
const vaultPath = getVaultPath(this.plugin.app);
// Track external context paths for dynamic updates (empty list clears)
if (options && options.externalContextPaths !== undefined) {
this.currentExternalContextPaths = options.externalContextPaths;
}
// Auto-resolve session ID from sessionManager if not explicitly provided
const effectiveSessionId = options?.sessionId ?? this.sessionManager.getSessionId() ?? undefined;
const externalContextPaths = options?.externalContextPaths ?? this.currentExternalContextPaths;
// Case 1: Not running → try to start
if (!this.persistentQuery) {
if (!vaultPath) return false;
const cliPath = this.plugin.getResolvedClaudeCliPath();
if (!cliPath) return false;
await this.startPersistentQuery(vaultPath, cliPath, effectiveSessionId, externalContextPaths);
return true;
}
// Case 2: Force restart (session switch, crash recovery)
// Close FIRST, then try to start new one (allows fallback if CLI unavailable)
if (options?.force) {
this.closePersistentQuery('forced restart', { preserveHandlers: options.preserveHandlers });
if (!vaultPath) return false;
const cliPath = this.plugin.getResolvedClaudeCliPath();
if (!cliPath) return false;
await this.startPersistentQuery(vaultPath, cliPath, effectiveSessionId, externalContextPaths);
return true;
}
// Case 3: Check if config changed → restart if needed
// We need vaultPath and cliPath to build config for comparison
if (!vaultPath) return false;
const cliPath = this.plugin.getResolvedClaudeCliPath();
if (!cliPath) return false;
const newConfig = this.buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths);
if (this.needsRestart(newConfig)) {
// Close FIRST, then try to start new one (allows fallback if CLI unavailable)
this.closePersistentQuery('config changed', { preserveHandlers: options?.preserveHandlers });
// Re-check CLI path as it might have changed during close
const cliPathAfterClose = this.plugin.getResolvedClaudeCliPath();
if (cliPathAfterClose) {
await this.startPersistentQuery(vaultPath, cliPathAfterClose, effectiveSessionId, externalContextPaths);
return true;
}
// CLI unavailable after close - query is closed, will fallback to cold-start
return false;
}
// Case 4: Running and config unchanged → no-op
return false;
}
/**
* Starts the persistent query for the active chat conversation.
*/
private async startPersistentQuery(
vaultPath: string,
cliPath: string,
resumeSessionId?: string,
externalContextPaths?: string[]
): Promise<void> {
if (this.persistentQuery) {
return;
}
this.shuttingDown = false;
this.vaultPath = vaultPath;
this.messageChannel = new MessageChannel();
if (resumeSessionId) {
this.messageChannel.setSessionId(resumeSessionId);
this.sessionManager.setSessionId(resumeSessionId, this.plugin.settings.model);
}
this.queryAbortController = new AbortController();
const config = this.buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths);
this.currentConfig = config;
// await is intentional: yields to microtask queue so fire-and-forget callers
// (e.g. setSessionId → ensureReady) don't synchronously set persistentQuery
const resumeSessionAt = this.pendingResumeAt;
const options = await this.buildPersistentQueryOptions(
vaultPath,
cliPath,
resumeSessionId,
resumeSessionAt,
externalContextPaths
);
this.persistentQuery = agentQuery({
prompt: this.messageChannel,
options,
});
if (this.pendingResumeAt === resumeSessionAt) {
this.pendingResumeAt = undefined;
}
this.attachPersistentQueryStdinErrorHandler(this.persistentQuery);
this.startResponseConsumer();
this.notifyReadyStateChange();
}
private attachPersistentQueryStdinErrorHandler(query: Query): void {
const stdin = (query as { transport?: { processStdin?: NodeJS.WritableStream } }).transport?.processStdin;
if (!stdin || typeof stdin.on !== 'function' || typeof stdin.once !== 'function') {
return;
}
const handler = (error: NodeJS.ErrnoException) => {
if (this.shuttingDown || this.isPipeError(error)) {
return;
}
this.closePersistentQuery('stdin error');
};
stdin.on('error', handler);
stdin.once('close', () => {
stdin.removeListener('error', handler);
});
}
private isPipeError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false;
const e = error as { code?: string; message?: string };
return e.code === 'EPIPE' || (typeof e.message === 'string' && e.message.includes('EPIPE'));
}
/**
* Closes the persistent query and cleans up resources.
*/
closePersistentQuery(_reason?: string, options?: ClosePersistentQueryOptions): void {
if (!this.persistentQuery) {
return;
}
const preserveHandlers = options?.preserveHandlers ?? false;
this.shuttingDown = true;
// Close the message channel (ends the async iterable)
this.messageChannel?.close();
// Interrupt the query
void this.persistentQuery.interrupt().catch(() => {
// Silence abort/interrupt errors during shutdown
});
// Abort as backup
this.queryAbortController?.abort();
if (!preserveHandlers) {
// Notify all handlers before clearing so generators don't hang forever.
// This ensures queryViaPersistent() exits its while(!state.done) loop.
for (const handler of this.responseHandlers) {
handler.onDone();
}
}
// Reset shuttingDown synchronously. The consumer loop sees shuttingDown=true
// on its next iteration check (line 549) and breaks. The messageChannel.close()
// above also terminates the for-await loop. Resetting here allows new queries
// to proceed immediately without waiting for consumer loop teardown.
this.shuttingDown = false;
this.notifyReadyStateChange();
// Clear state
this.persistentQuery = null;
this.messageChannel = null;
this.queryAbortController = null;
this.responseConsumerRunning = false;
this.responseConsumerPromise = null;
this.currentConfig = null;
if (!preserveHandlers) {
this.responseHandlers = [];
this.currentAllowedTools = null;
}
// NOTE: Do NOT reset crashRecoveryAttempted here.
// It's reset in queryViaPersistent after a successful message send,
// or in resetSession/setSessionId when switching sessions.
// Resetting it here would cause infinite restart loops on persistent errors.
}
/**
* Checks if the persistent query needs to be restarted based on configuration changes.
*/
private needsRestart(newConfig: PersistentQueryConfig): boolean {
return QueryOptionsBuilder.needsRestart(this.currentConfig, newConfig);
}
/**
* Builds configuration object for tracking changes.
*/
private buildPersistentQueryConfig(
vaultPath: string,
cliPath: string,
externalContextPaths?: string[]
): PersistentQueryConfig {
return QueryOptionsBuilder.buildPersistentQueryConfig(
this.buildQueryOptionsContext(vaultPath, cliPath),
externalContextPaths
);
}
/**
* Builds the base query options context from current state.
*/
private buildQueryOptionsContext(vaultPath: string, cliPath: string): QueryOptionsContext {
const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables());
const enhancedPath = getEnhancedPath(customEnv.PATH, cliPath);
return {
vaultPath,
cliPath,
settings: this.plugin.settings,
customEnv,
enhancedPath,
mcpManager: this.mcpManager,
pluginManager: this.plugin.pluginManager,
};
}
/**
* Builds SDK options for the persistent query.
*/
private buildPersistentQueryOptions(
vaultPath: string,
cliPath: string,
resumeSessionId?: string,
resumeSessionAt?: string,
externalContextPaths?: string[]
): Options {
const baseContext = this.buildQueryOptionsContext(vaultPath, cliPath);
const hooks = this.buildHooks();
const ctx: PersistentQueryContext = {
...baseContext,
abortController: this.queryAbortController ?? undefined,
resume: resumeSessionId
? { sessionId: resumeSessionId, sessionAt: resumeSessionAt, fork: this.pendingForkSession || undefined }
: undefined,
canUseTool: this.createApprovalCallback(),
hooks,
externalContextPaths,
};
return QueryOptionsBuilder.buildPersistentQueryOptions(ctx);
}
/**
* Builds the hooks for SDK options.
* Hooks need access to `this` for dynamic settings, so they're built here.
*
* @param externalContextPaths - Optional external context paths for cold-start queries.
* If not provided, the closure reads this.currentExternalContextPaths at execution
* time (for persistent queries where the value may change dynamically).
*/
private buildHooks(externalContextPaths?: string[]) {
const blocklistHook = createBlocklistHook(() => ({
blockedCommands: this.plugin.settings.blockedCommands,
enableBlocklist: this.plugin.settings.enableBlocklist,
}));
if (this.plugin.settings.allowExternalAccess) {
return { PreToolUse: [blocklistHook] };
}
const vaultRestrictionHook = createVaultRestrictionHook({
getPathAccessType: (p) => {
if (!this.vaultPath) return 'vault';
// For cold-start queries, use the passed externalContextPaths.
// For persistent queries, read this.currentExternalContextPaths at execution time
// so dynamic updates are reflected.
const paths = externalContextPaths ?? this.currentExternalContextPaths;
return getPathAccessType(
p,
paths,
this.plugin.settings.allowedExportPaths,
this.vaultPath
);
},
});
return {
PreToolUse: [blocklistHook, vaultRestrictionHook],
};
}
/**
* Starts the background consumer loop that routes chunks to handlers.
*/
private startResponseConsumer(): void {
if (this.responseConsumerRunning) {
return;
}
this.responseConsumerRunning = true;
// Track which query this consumer is for, to detect if we were replaced
const queryForThisConsumer = this.persistentQuery;
this.responseConsumerPromise = (async () => {
if (!this.persistentQuery) return;
try {
for await (const message of this.persistentQuery) {
if (this.shuttingDown) break;
await this.routeMessage(message);
}
} catch (error) {
// Skip error handling if this consumer was replaced by a new one.
// This prevents race conditions where the OLD consumer's error handler
// interferes with the NEW handler after a restart (e.g., from applyDynamicUpdates).
if (this.persistentQuery !== queryForThisConsumer && this.persistentQuery !== null) {
return;
}
// Skip restart if cold-start is in progress (it will handle session capture)
if (!this.shuttingDown && !this.coldStartInProgress) {
const handler = this.responseHandlers[this.responseHandlers.length - 1];
const errorInstance = error instanceof Error ? error : new Error(String(error));
const messageToReplay = this.lastSentMessage;
if (!this.crashRecoveryAttempted && messageToReplay && handler && !handler.sawAnyChunk) {
this.crashRecoveryAttempted = true;
try {
await this.ensureReady({ force: true, preserveHandlers: true });
if (!this.messageChannel) {
throw new Error('Persistent query restart did not create message channel');
}
await this.applyDynamicUpdates(this.lastSentQueryOptions ?? undefined, { preserveHandlers: true });
this.messageChannel.enqueue(messageToReplay);
return;
} catch (restartError) {
// If restart failed due to auth error, notify with actionable message
if (isAuthenticationError(restartError)) {
handler.onError(new Error('Authentication failed — your Claude OAuth token has expired. Please run `claude auth login` in your terminal to re-authenticate, then restart Claudian.'));
new Notice('Claude authentication expired. Run "claude auth login" in terminal to fix.', 10000);
return;
}
// If restart failed due to session expiration, invalidate session
// so next query triggers noSessionButHasHistory → history rebuild
if (isSessionExpiredError(restartError)) {
this.sessionManager.invalidateSession();
}
handler.onError(errorInstance);
return;
}
}
// Notify active handler of error
if (handler) {
// Check if original error is an auth error — give actionable message
if (isAuthenticationError(errorInstance)) {
handler.onError(new Error('Authentication failed — your Claude OAuth token has expired. Please run `claude auth login` in your terminal to re-authenticate, then restart Claudian.'));
new Notice('Claude authentication expired. Run "claude auth login" in terminal to fix.', 10000);
return;
}
handler.onError(errorInstance);
}
// Crash recovery: restart persistent query to prepare for next user message.
if (!this.crashRecoveryAttempted) {
this.crashRecoveryAttempted = true;
try {
await this.ensureReady({ force: true });
} catch (restartError) {
// If restart failed due to auth error, don't bother retrying
if (isAuthenticationError(restartError)) {
new Notice('Claude authentication expired. Run "claude auth login" in terminal to fix.', 10000);
return;
}
// If restart failed due to session expiration, invalidate session
// so next query triggers noSessionButHasHistory → history rebuild
if (isSessionExpiredError(restartError)) {
this.sessionManager.invalidateSession();
}
// Restart failed - next query will start fresh.
}
}
}
} finally {
// Only clear the flag if this consumer wasn't replaced by a new one (e.g., after restart)
// If ensureReady() restarted, it starts a new consumer which sets the flag true,
// so we shouldn't clear it here.
if (this.persistentQuery === queryForThisConsumer || this.persistentQuery === null) {
this.responseConsumerRunning = false;
}
}
})();
}
/** @param modelOverride - Optional model override for cold-start queries */
private getTransformOptions(modelOverride?: string) {
return {
intendedModel: modelOverride ?? this.plugin.settings.model,
customContextLimits: this.plugin.settings.customContextLimits,
};
}
/**
* Routes an SDK message to the active response handler.
*
* Design: Only one handler exists at a time because MessageChannel enforces
* single-turn processing. When a turn is active, new messages are queued/merged.
* The next message only dequeues after onTurnComplete(), which calls onDone()
* on the current handler. A new handler is registered only when the next query starts.
*/
private async routeMessage(message: SDKMessage): Promise<void> {
// Note: Session expiration errors are handled in catch blocks (queryViaSDK, handleAbort)
// The SDK throws errors as exceptions, not as message types
// Safe to use last handler - design guarantees single handler at a time
const handler = this.responseHandlers[this.responseHandlers.length - 1];
if (handler && this.isStreamTextEvent(message)) {
handler.markStreamTextSeen();
}
// Transform SDK message to StreamChunks
for (const event of transformSDKMessage(message, this.getTransformOptions())) {
if (isSessionInitEvent(event)) {
// Fork: suppress needsHistoryRebuild since SDK returns a different session ID by design
const wasFork = this.pendingForkSession;
this.sessionManager.captureSession(event.sessionId);
if (wasFork) {
this.sessionManager.clearHistoryRebuild();
this.pendingForkSession = false;
}
this.messageChannel?.setSessionId(event.sessionId);
if (event.agents) {
try { this.plugin.agentManager.setBuiltinAgentNames(event.agents); } catch { /* non-critical */ }
}
if (event.permissionMode && this.permissionModeSyncCallback) {
try { this.permissionModeSyncCallback(event.permissionMode); } catch { /* non-critical */ }
}
} else if (isStreamChunk(event)) {
if (message.type === 'assistant' && handler?.sawStreamText && event.type === 'text') {
continue;
}
// SDK auto-approves EnterPlanMode (checkPermissions → allow),
// so canUseTool is never called. Detect the tool_use in the stream
// and fire the sync callback to update the UI.
if (event.type === 'tool_use' && event.name === TOOL_ENTER_PLAN_MODE) {
if (this.currentConfig) {
this.currentConfig.permissionMode = 'plan';
}
if (this.permissionModeSyncCallback) {
try { this.permissionModeSyncCallback('plan'); } catch { /* non-critical */ }
}
}
if (handler) {
// Add sessionId to usage chunks (consistent with cold-start path)
if (event.type === 'usage') {
handler.onChunk({ ...event, sessionId: this.sessionManager.getSessionId() });
} else {
handler.onChunk(event);
}
}
}
}
if (message.type === 'assistant' && message.uuid && handler) {
handler.onChunk({ type: 'sdk_assistant_uuid', uuid: message.uuid });
}
// Check for turn completion
if (isTurnCompleteMessage(message)) {
// Signal turn complete to message channel
this.messageChannel?.onTurnComplete();
// Notify handler
if (handler) {
handler.resetStreamText();
handler.onDone();
}
}
}
private registerResponseHandler(handler: ResponseHandler): void {
this.responseHandlers.push(handler);
}
private unregisterResponseHandler(handlerId: string): void {
const idx = this.responseHandlers.findIndex(h => h.id === handlerId);
if (idx >= 0) {
this.responseHandlers.splice(idx, 1);
}
}
isPersistentQueryActive(): boolean {
return this.persistentQuery !== null && !this.shuttingDown;
}
/**
* Sends a query to Claude and streams the response.
*
* Query selection:
* - Persistent query: default chat conversation
* - Cold-start query: only when forceColdStart is set
*/
async *query(
prompt: string,
images?: ImageAttachment[],
conversationHistory?: ChatMessage[],
queryOptions?: QueryOptions
): AsyncGenerator<StreamChunk> {
const vaultPath = getVaultPath(this.plugin.app);
if (!vaultPath) {
yield { type: 'error', content: 'Could not determine vault path' };
return;
}
const resolvedClaudePath = this.plugin.getResolvedClaudeCliPath();
if (!resolvedClaudePath) {
yield { type: 'error', content: 'Claude CLI not found. Please install Claude Code CLI.' };
return;
}
const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables());
const enhancedPath = getEnhancedPath(customEnv.PATH, resolvedClaudePath);
const missingNodeError = getMissingNodeError(resolvedClaudePath, enhancedPath);
if (missingNodeError) {
yield { type: 'error', content: missingNodeError };
return;
}
// Rebuild history if needed before choosing persistent vs cold-start
let promptToSend = prompt;
let forceColdStart = false;
// Clear interrupted flag - persistent query handles interruption gracefully,
// no need to force cold-start just because user cancelled previous response
if (this.sessionManager.wasInterrupted()) {
this.sessionManager.clearInterrupted();
}
// Session mismatch recovery: SDK returned a different session ID (context lost)
// Inject history to restore context without forcing cold-start
if (this.sessionManager.needsHistoryRebuild() && conversationHistory && conversationHistory.length > 0) {
const historyContext = buildContextFromHistory(conversationHistory);
const actualPrompt = stripCurrentNoteContext(prompt);
promptToSend = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory);
this.sessionManager.clearHistoryRebuild();
}
const noSessionButHasHistory = !this.sessionManager.getSessionId() &&
conversationHistory && conversationHistory.length > 0;
if (noSessionButHasHistory) {
const historyContext = buildContextFromHistory(conversationHistory!);
const actualPrompt = stripCurrentNoteContext(prompt);
promptToSend = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory!);
// Note: Do NOT call invalidateSession() here. The cold-start will capture
// a new session ID anyway, and invalidating would break any persistent query
// restart that happens during the cold-start (causing SESSION MISMATCH).
forceColdStart = true;
}
const effectiveQueryOptions = forceColdStart
? { ...queryOptions, forceColdStart: true }
: queryOptions;
if (forceColdStart) {
// Set flag BEFORE closing to prevent consumer error from triggering restart
this.coldStartInProgress = true;
this.closePersistentQuery('session invalidated');
}
// Determine query path: persistent vs cold-start
const shouldUsePersistent = !effectiveQueryOptions?.forceColdStart;
if (shouldUsePersistent) {
// Start persistent query if not running
if (!this.persistentQuery && !this.shuttingDown) {
await this.startPersistentQuery(
vaultPath,
resolvedClaudePath,
this.sessionManager.getSessionId() ?? undefined
);
}
if (this.persistentQuery && !this.shuttingDown) {
// Use persistent query path
try {
yield* this.queryViaPersistent(promptToSend, images, vaultPath, resolvedClaudePath, effectiveQueryOptions);
return;
} catch (error) {
// Authentication errors are non-recoverable — don't retry
if (isAuthenticationError(error)) {
this.closePersistentQuery('authentication error');
yield { type: 'error', content: 'Authentication failed — your Claude OAuth token has expired. Please run `claude auth login` in your terminal to re-authenticate, then restart Claudian.' };
new Notice('Claude authentication expired. Run "claude auth login" in terminal to fix.', 10000);
return;
}
if (isSessionExpiredError(error) && conversationHistory && conversationHistory.length > 0) {
this.sessionManager.invalidateSession();
const retryRequest = this.buildHistoryRebuildRequest(prompt, conversationHistory);
this.coldStartInProgress = true;
this.abortController = new AbortController();
try {
yield* this.queryViaSDK(
retryRequest.prompt,
vaultPath,
resolvedClaudePath,
// Use current message's images, fallback to history images
images ?? retryRequest.images,
effectiveQueryOptions
);
} catch (retryError) {
if (isAuthenticationError(retryError)) {
yield { type: 'error', content: 'Authentication failed — your Claude OAuth token has expired. Please run `claude auth login` in your terminal to re-authenticate, then restart Claudian.' };
new Notice('Claude authentication expired. Run "claude auth login" in terminal to fix.', 10000);
} else {
const msg = retryError instanceof Error ? retryError.message : 'Unknown error';
yield { type: 'error', content: msg };
}
} finally {
this.coldStartInProgress = false;
this.abortController = null;
}
return;
}
throw error;
}
}
}
// Cold-start path (existing logic)
// Set flag to prevent consumer error restarts from interfering
this.coldStartInProgress = true;
this.abortController = new AbortController();
try {
yield* this.queryViaSDK(promptToSend, vaultPath, resolvedClaudePath, images, effectiveQueryOptions);
} catch (error) {
// Authentication errors are non-recoverable — don't retry
if (isAuthenticationError(error)) {
yield { type: 'error', content: 'Authentication failed — your Claude OAuth token has expired. Please run `claude auth login` in your terminal to re-authenticate, then restart Claudian.' };
new Notice('Claude authentication expired. Run "claude auth login" in terminal to fix.', 10000);
return;
}
if (isSessionExpiredError(error) && conversationHistory && conversationHistory.length > 0) {
this.sessionManager.invalidateSession();
const retryRequest = this.buildHistoryRebuildRequest(prompt, conversationHistory);
try {
yield* this.queryViaSDK(
retryRequest.prompt,
vaultPath,
resolvedClaudePath,
// Use current message's images, fallback to history images
images ?? retryRequest.images,
effectiveQueryOptions
);
} catch (retryError) {
if (isAuthenticationError(retryError)) {
yield { type: 'error', content: 'Authentication failed — your Claude OAuth token has expired. Please run `claude auth login` in your terminal to re-authenticate, then restart Claudian.' };
new Notice('Claude authentication expired. Run "claude auth login" in terminal to fix.', 10000);
} else {
const msg = retryError instanceof Error ? retryError.message : 'Unknown error';
yield { type: 'error', content: msg };
}
}
return;
}
const msg = error instanceof Error ? error.message : 'Unknown error';
yield { type: 'error', content: msg };
} finally {
this.coldStartInProgress = false;
this.abortController = null;
}
}
private buildHistoryRebuildRequest(
prompt: string,
conversationHistory: ChatMessage[]
): { prompt: string; images?: ImageAttachment[] } {
const historyContext = buildContextFromHistory(conversationHistory);
const actualPrompt = stripCurrentNoteContext(prompt);
const fullPrompt = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory);
const lastUserMessage = getLastUserMessage(conversationHistory);
return {
prompt: fullPrompt,
images: lastUserMessage?.images,
};
}
/**
* Query via persistent query (Phase 1.5).
* Uses the message channel to send messages without cold-start latency.
*/
private async *queryViaPersistent(
prompt: string,
images: ImageAttachment[] | undefined,
vaultPath: string,
cliPath: string,
queryOptions?: QueryOptions
): AsyncGenerator<StreamChunk> {
if (!this.persistentQuery || !this.messageChannel) {
// Fallback to cold-start if persistent query not available
yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions);
return;
}
// Set allowed tools for canUseTool enforcement
// undefined = no restriction, [] = no tools, [...] = restricted
if (queryOptions?.allowedTools !== undefined) {
this.currentAllowedTools = queryOptions.allowedTools.length > 0
? [...queryOptions.allowedTools, TOOL_SKILL]
: [];
} else {
this.currentAllowedTools = null;
}
// Save allowedTools before applyDynamicUpdates - restart would clear it
const savedAllowedTools = this.currentAllowedTools;
// Apply dynamic updates before sending (Phase 1.6)
await this.applyDynamicUpdates(queryOptions);
// Restore allowedTools in case restart cleared it
this.currentAllowedTools = savedAllowedTools;
// Check if applyDynamicUpdates triggered a restart that failed
// (e.g., CLI path not found, vault path missing)
if (!this.persistentQuery || !this.messageChannel) {
yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions);
return;
}
if (!this.responseConsumerRunning) {
yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions);
return;
}
const message = this.buildSDKUserMessage(prompt, images);
yield { type: 'sdk_user_uuid', uuid: message.uuid! };
// Create a promise-based handler to yield chunks
// Use a mutable state object to work around TypeScript's control flow analysis
const state = {
chunks: [] as StreamChunk[],
resolveChunk: null as ((chunk: StreamChunk | null) => void) | null,
done: false,
error: null as Error | null,
};
const handlerId = `handler-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const handler = createResponseHandler({