-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathaiService.ts
More file actions
1887 lines (1704 loc) · 72.8 KB
/
aiService.ts
File metadata and controls
1887 lines (1704 loc) · 72.8 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
import * as fs from "fs/promises";
import { EventEmitter } from "events";
import assert from "@/common/utils/assert";
import { type LanguageModel, type Tool } from "ai";
import { linkAbortSignal } from "@/node/utils/abort";
import { ensurePrivateDir } from "@/node/utils/fs";
import type { Result } from "@/common/types/result";
import { Ok, Err } from "@/common/types/result";
import type { WorkspaceMetadata } from "@/common/types/workspace";
import type { SendMessageOptions, ProvidersConfigMap } from "@/common/orpc/types";
import type { DebugLlmRequestSnapshot } from "@/common/types/debugLlmRequest";
import { EXPERIMENT_IDS } from "@/common/constants/experiments";
import type { MuxMessage } from "@/common/types/message";
import { createMuxMessage } from "@/common/types/message";
import type { Config } from "@/node/config";
import { StreamManager } from "./streamManager";
import type { InitStateManager } from "./initStateManager";
import type { SendMessageError } from "@/common/types/errors";
import { getToolsForModel } from "@/common/utils/tools/tools";
import { cloneToolPreservingDescriptors } from "@/common/utils/tools/cloneToolPreservingDescriptors";
import {
createRuntimeContextForWorkspace,
resolveWorkspaceExecutionPath,
} from "@/node/runtime/runtimeHelpers";
import { createRuntimeForWorkspaceProject } from "@/node/services/workspaceProjectRepos";
import { MultiProjectRuntime } from "@/node/runtime/multiProjectRuntime";
import { getMuxEnv, getRuntimeType } from "@/node/runtime/initHook";
import { getSrcBaseDir, isSSHRuntime } from "@/common/types/runtime";
import { ContainerManager } from "@/node/multiProject/containerManager";
import { secretsToRecord, type ExternalSecretResolver } from "@/common/types/secrets";
import { mergeMultiProjectSecrets } from "@/node/services/utils/multiProjectSecrets";
import type { MuxProviderOptions } from "@/common/types/providerOptions";
import type { MuxToolScope } from "@/common/types/toolScope";
import type { PolicyService } from "@/node/services/policyService";
import type { ProviderService } from "@/node/services/providerService";
import type { CodexOauthService } from "@/node/services/codexOauthService";
import type { BackgroundProcessManager } from "@/node/services/backgroundProcessManager";
import type { FileState, EditedFileAttachment } from "@/node/services/agentSession";
import { log } from "./log";
import {
addInterruptedSentinel,
filterEmptyAssistantMessages,
} from "@/browser/utils/messages/modelMessageTransform";
import type { PostCompactionAttachment } from "@/common/types/attachment";
import type { HistoryService } from "./historyService";
import { delegatedToolCallManager } from "./delegatedToolCallManager";
import { createErrorEvent } from "./utils/sendMessageError";
import { createAssistantMessageId } from "./utils/messageIds";
import type { SessionUsageService } from "./sessionUsageService";
import { sumUsageHistory, getTotalCost } from "@/common/utils/tokens/usageAggregator";
import { readToolInstructions } from "./systemMessage";
import type { TelemetryService } from "@/node/services/telemetryService";
import type { DevToolsService } from "@/node/services/devToolsService";
import type { ExperimentsService } from "@/node/services/experimentsService";
import type { DesktopSessionManager } from "@/node/services/desktop/DesktopSessionManager";
import type { WorkspaceMCPOverrides } from "@/common/types/mcp";
import type { MCPServerManager, MCPWorkspaceStats } from "@/node/services/mcpServerManager";
import { WorkspaceMcpOverridesService } from "./workspaceMcpOverridesService";
import type { TaskService } from "@/node/services/taskService";
import {
buildProviderOptions,
buildRequestHeaders,
resolveProviderOptionsNamespaceKey,
} from "@/common/utils/ai/providerOptions";
import { resolveModelParameterOverrides } from "@/common/utils/ai/modelParameterOverrides";
import { isPlainObject } from "@/common/utils/isPlainObject";
import { sliceMessagesFromLatestCompactionBoundary } from "@/common/utils/messages/compactionBoundary";
import { getProjects, isMultiProject } from "@/common/utils/multiProject";
import { uniqueSuffix } from "@/common/utils/hasher";
import { isWorkspaceTrustedForSharedExecution } from "@/node/services/utils/workspaceTrust";
import { MULTI_PROJECT_CONFIG_KEY } from "@/common/constants/multiProject";
import { THINKING_LEVEL_OFF, type ThinkingLevel } from "@/common/types/thinking";
import type {
ErrorEvent,
StreamAbortEvent,
StreamAbortReason,
StreamEndEvent,
} from "@/common/types/stream";
import type { ToolPolicy } from "@/common/utils/tools/toolPolicy";
import type { PTCEventWithParent } from "@/node/services/tools/code_execution";
import { MockAiStreamPlayer } from "./mock/mockAiStreamPlayer";
import { DEVTOOLS_RUN_METADATA_ID_HEADER } from "./devToolsHeaderCapture";
import { ProviderModelFactory, modelCostsIncluded } from "./providerModelFactory";
import { wrapToolsWithSystem1 } from "./system1ToolWrapper";
import { prepareMessagesForProvider } from "./messagePipeline";
import { resolveAgentForStream } from "./agentResolution";
import { buildPlanInstructions, buildStreamSystemContext } from "./streamContextBuilder";
import { getTokenizerForModel } from "@/node/utils/main/tokenizer";
import { resolveModelForMetadata } from "@/common/utils/providers/modelEntries";
import {
simulateContextLimitError,
simulateToolPolicyNoop,
type SimulationContext,
} from "./streamSimulation";
import { applyToolPolicyAndExperiments, captureMcpToolTelemetry } from "./toolAssembly";
import { getErrorMessage } from "@/common/utils/errors";
import { isProjectTrusted } from "@/node/utils/projectTrust";
const STREAM_STARTUP_DIAGNOSTIC_THRESHOLD_MS = 1_000;
// ---------------------------------------------------------------------------
// streamMessage options
// ---------------------------------------------------------------------------
/** Options bag for {@link AIService.streamMessage}. */
export interface StreamMessageOptions {
messages: MuxMessage[];
workspaceId: string;
modelString: string;
thinkingLevel?: ThinkingLevel;
toolPolicy?: ToolPolicy;
abortSignal?: AbortSignal;
additionalSystemInstructions?: string;
maxOutputTokens?: number;
muxProviderOptions?: MuxProviderOptions;
/** Internal-only flag for Copilot billing attribution; never sourced from IPC schemas. */
agentInitiated?: boolean;
agentId?: string;
/** ACP prompt correlation id used to match stream events to a specific request. */
acpPromptId?: string;
/** Tool names that should be delegated back to ACP clients for this request. */
delegatedToolNames?: string[];
recordFileState?: (filePath: string, state: FileState) => Promise<void>;
changedFileAttachments?: EditedFileAttachment[];
postCompactionAttachments?: PostCompactionAttachment[] | null;
experiments?: SendMessageOptions["experiments"];
system1Model?: string;
system1ThinkingLevel?: ThinkingLevel;
disableWorkspaceAgents?: boolean;
hasQueuedMessage?: () => boolean;
openaiTruncationModeOverride?: "auto" | "disabled";
}
// ---------------------------------------------------------------------------
// Utility: deep-clone with structuredClone fallback
// ---------------------------------------------------------------------------
/** Deep-clone a value using structuredClone (with JSON fallback). */
function safeClone<T>(value: T): T {
return typeof structuredClone === "function"
? structuredClone(value)
: (JSON.parse(JSON.stringify(value)) as T);
}
/**
* Recursively merge user-provided provider extras under Mux-built provider options.
* Mux values win on leaf conflicts; both sides' non-conflicting nested fields are preserved.
*/
function mergeProviderExtrasUnderMux(
providerExtras: Record<string, unknown>,
muxProviderNamespace: Record<string, unknown>
): Record<string, unknown> {
const merged: Record<string, unknown> = { ...providerExtras };
for (const [key, muxValue] of Object.entries(muxProviderNamespace)) {
const extraValue = merged[key];
merged[key] =
isPlainObject(extraValue) && isPlainObject(muxValue)
? mergeProviderExtrasUnderMux(extraValue, muxValue)
: muxValue;
}
return merged;
}
interface ToolExecutionContext {
toolCallId?: string;
abortSignal?: AbortSignal;
}
function isToolExecutionContext(value: unknown): value is ToolExecutionContext {
if (typeof value !== "object" || value == null || Array.isArray(value)) {
return false;
}
const record = value as Record<string, unknown>;
const toolCallId = record.toolCallId;
const abortSignal = record.abortSignal;
const validToolCallId = toolCallId == null || typeof toolCallId === "string";
const validAbortSignal = abortSignal == null || abortSignal instanceof AbortSignal;
return validToolCallId && validAbortSignal;
}
/**
* Derive the host-local project root for mux managed-file tools (fs/promises).
* Remote runtimes (ssh, docker) have a workspacePath that is a remote/container
* path — unusable by host fs. Fall back to metadata.projectPath which is always
* host-local.
*/
export function resolveMuxProjectRootForHostFs(
metadata: WorkspaceMetadata,
workspacePath: string
): string {
const runtimeType = metadata.runtimeConfig.type;
return runtimeType === "ssh" || runtimeType === "docker" ? metadata.projectPath : workspacePath;
}
function resolveMuxToolScope(
config: Config,
metadata: WorkspaceMetadata,
workspacePath: string
): MuxToolScope {
const projectConfig = config.loadConfigOrDefault().projects.get(metadata.projectPath);
if (
projectConfig?.projectKind === "system" &&
metadata.projectPath !== MULTI_PROJECT_CONFIG_KEY
) {
// Preserve ~/.mux-backed tool behavior for legacy system workspaces after removing
// Chat with Mux. Multi-project workspaces still point at a real checkout under _multi,
// so they stay project-scoped.
return {
type: "global",
muxHome: config.rootDir,
};
}
const runtimeType = metadata.runtimeConfig.type;
return {
type: "project",
muxHome: config.rootDir,
projectRoot: resolveMuxProjectRootForHostFs(metadata, workspacePath),
projectStorageAuthority:
runtimeType === "ssh" || runtimeType === "docker" ? "runtime" : "host-local",
};
}
function derivePromptCacheScope(metadata: WorkspaceMetadata): string {
return `${metadata.projectName}-${uniqueSuffix([metadata.projectPath])}`;
}
export class AIService extends EventEmitter {
private readonly streamManager: StreamManager;
private readonly historyService: HistoryService;
private readonly config: Config;
private readonly workspaceMcpOverridesService: WorkspaceMcpOverridesService;
private mcpServerManager?: MCPServerManager;
private readonly policyService?: PolicyService;
private readonly telemetryService?: TelemetryService;
private readonly opResolver?: ExternalSecretResolver;
private readonly initStateManager: InitStateManager;
private mockModeEnabled: boolean;
private mockAiStreamPlayer?: MockAiStreamPlayer;
private readonly backgroundProcessManager?: BackgroundProcessManager;
private readonly sessionUsageService?: SessionUsageService;
private readonly providerService: ProviderService;
private readonly providerModelFactory: ProviderModelFactory;
private readonly devToolsService?: DevToolsService;
private readonly experimentsService?: ExperimentsService;
// Tracks in-flight stream startup (before StreamManager emits stream-start).
// This enables user interrupts (Esc/Ctrl+C) during the UI "starting..." phase.
private readonly pendingStreamStarts = new Map<
string,
{
abortController: AbortController;
startTime: number;
syntheticMessageId: string;
acpPromptId?: string;
}
>();
/**
* Tracks queued DevTools run metadata by assistant message id so stream-end/abort
* can clear orphaned entries when a stream starts but never reaches middleware run creation.
*/
private readonly pendingDevToolsRunMetadataByMessageId = new Map<
string,
{ workspaceId: string; metadataId: string }
>();
// Debug: captured LLM request payloads for last send per workspace
private lastLlmRequestByWorkspace = new Map<string, DebugLlmRequestSnapshot>();
private taskService?: TaskService;
private extraTools?: Record<string, Tool>;
private analyticsService?: { executeRawQuery(sql: string): Promise<unknown> };
private desktopSessionManager?: DesktopSessionManager;
constructor(
config: Config,
historyService: HistoryService,
initStateManager: InitStateManager,
providerService: ProviderService,
backgroundProcessManager?: BackgroundProcessManager,
sessionUsageService?: SessionUsageService,
workspaceMcpOverridesService?: WorkspaceMcpOverridesService,
policyService?: PolicyService,
telemetryService?: TelemetryService,
devToolsService?: DevToolsService,
opResolver?: ExternalSecretResolver,
experimentsService?: ExperimentsService
) {
super();
// Increase max listeners to accommodate multiple concurrent workspace listeners
// Each workspace subscribes to stream events, and we expect >10 concurrent workspaces
this.setMaxListeners(50);
this.workspaceMcpOverridesService =
workspaceMcpOverridesService ?? new WorkspaceMcpOverridesService(config);
this.config = config;
this.historyService = historyService;
this.initStateManager = initStateManager;
this.backgroundProcessManager = backgroundProcessManager;
this.sessionUsageService = sessionUsageService;
this.policyService = policyService;
this.telemetryService = telemetryService;
this.opResolver = opResolver;
this.experimentsService = experimentsService;
this.providerService = providerService;
this.streamManager = new StreamManager(historyService, sessionUsageService, () =>
this.providerService.getConfig()
);
this.devToolsService = devToolsService;
this.providerModelFactory = new ProviderModelFactory(
config,
providerService,
policyService,
undefined,
devToolsService,
opResolver
);
void this.ensureSessionsDir();
this.setupStreamEventForwarding();
this.mockModeEnabled = false;
if (process.env.MUX_MOCK_AI === "1") {
log.info("AIService running in MUX_MOCK_AI mode");
this.enableMockMode();
}
}
setCodexOauthService(service: CodexOauthService): void {
this.providerModelFactory.codexOauthService = service;
}
setMCPServerManager(manager: MCPServerManager): void {
this.mcpServerManager = manager;
this.streamManager.setMCPServerManager(manager);
}
setTaskService(taskService: TaskService): void {
this.taskService = taskService;
}
setAnalyticsService(service: { executeRawQuery(sql: string): Promise<unknown> }): void {
this.analyticsService = service;
}
setDesktopSessionManager(desktopSessionManager: DesktopSessionManager): void {
this.desktopSessionManager = desktopSessionManager;
}
getProvidersConfig(): ProvidersConfigMap | null {
return this.providerService.getConfig();
}
/**
* Set extra tools to include in every tool call.
* Used by CLI to inject tools like set_exit_code without modifying core tool definitions.
*/
setExtraTools(tools: Record<string, Tool>): void {
this.extraTools = tools;
}
/**
* Forward all stream events from StreamManager to AIService consumers
*/
private setupStreamEventForwarding(): void {
// Simple one-to-one event forwarding from StreamManager → AIService consumers
for (const event of [
"stream-start",
"stream-delta",
"tool-call-start",
"tool-call-delta",
"tool-call-end",
"reasoning-delta",
"reasoning-end",
"usage-delta",
] as const) {
this.streamManager.on(event, (data) => this.emit(event, data));
}
// Stream errors can bypass stream-end/stream-abort. Clear any queued metadata
// so failed requests don't leak pending-run tracking entries.
this.streamManager.on("error", (data: ErrorEvent) => {
this.clearTrackedPendingDevToolsRunMetadata(data.messageId);
this.emit("error", data);
});
// stream-end needs extra logic: capture provider response for debug modal
this.streamManager.on("stream-end", (data: StreamEndEvent) => {
// Streams can end before DevTools middleware creates a run (for example when
// interrupted early). Clear any still-queued run metadata for this message.
this.clearTrackedPendingDevToolsRunMetadata(data.messageId);
// Best-effort capture of the provider response for the "Last LLM request" debug modal.
// Must never break live streaming.
try {
const snapshot = this.lastLlmRequestByWorkspace.get(data.workspaceId);
if (snapshot) {
// If messageId is missing (legacy fixtures), attach anyway.
const shouldAttach = snapshot.messageId === data.messageId || snapshot.messageId == null;
if (shouldAttach) {
const updated: DebugLlmRequestSnapshot = {
...snapshot,
response: {
capturedAt: Date.now(),
metadata: data.metadata,
parts: data.parts,
},
};
this.lastLlmRequestByWorkspace.set(data.workspaceId, safeClone(updated));
}
}
} catch (error) {
const errMsg = getErrorMessage(error);
log.warn("Failed to capture debug LLM response snapshot", { error: errMsg });
}
this.emit("stream-end", data);
});
// Handle stream-abort: dispose of partial based on abandonPartial flag
this.streamManager.on("stream-abort", (data: StreamAbortEvent) => {
// Aborts can happen before the first provider call reaches DevTools middleware.
// Clear any queued run metadata for this message to avoid memory growth.
this.clearTrackedPendingDevToolsRunMetadata(data.messageId);
void (async () => {
try {
if (data.abandonPartial) {
// Caller requested discarding partial - delete without committing
await this.historyService.deletePartial(data.workspaceId);
} else {
// Commit interrupted message to history with partial:true metadata
// This ensures /clear and /truncate can clean up interrupted messages
const partial = await this.historyService.readPartial(data.workspaceId);
if (partial) {
await this.historyService.commitPartial(data.workspaceId);
await this.historyService.deletePartial(data.workspaceId);
}
}
} catch (error) {
log.error("Failed partial cleanup during stream-abort", {
workspaceId: data.workspaceId,
error: getErrorMessage(error),
});
} finally {
// Always forward abort event to consumers (workspaceService, agentSession)
// even if partial cleanup failed — stream lifecycle consistency is higher priority.
this.emit("stream-abort", data);
}
})();
});
}
private trackPendingDevToolsRunMetadata(
messageId: string,
workspaceId: string,
metadataId: string
): void {
assert(messageId.trim().length > 0, "trackPendingDevToolsRunMetadata requires a messageId");
assert(workspaceId.trim().length > 0, "trackPendingDevToolsRunMetadata requires a workspaceId");
assert(metadataId.trim().length > 0, "trackPendingDevToolsRunMetadata requires a metadataId");
this.pendingDevToolsRunMetadataByMessageId.set(messageId, {
workspaceId,
metadataId,
});
}
private clearTrackedPendingDevToolsRunMetadata(messageId: string): void {
// StreamManager can emit stream-abort with an empty messageId during startup races.
// Treat that as "nothing to clear" instead of throwing so interruptStream remains reliable.
if (messageId.trim().length === 0) {
return;
}
const pending = this.pendingDevToolsRunMetadataByMessageId.get(messageId);
if (!pending) {
return;
}
this.pendingDevToolsRunMetadataByMessageId.delete(messageId);
this.devToolsService?.clearPendingRunMetadata(pending.workspaceId, pending.metadataId);
}
private clearTrackedPendingDevToolsRunMetadataById(
workspaceId: string,
metadataId: string
): void {
assert(
workspaceId.trim().length > 0,
"clearTrackedPendingDevToolsRunMetadataById requires a workspaceId"
);
assert(
metadataId.trim().length > 0,
"clearTrackedPendingDevToolsRunMetadataById requires a metadataId"
);
for (const [messageId, pending] of this.pendingDevToolsRunMetadataByMessageId.entries()) {
if (pending.workspaceId === workspaceId && pending.metadataId === metadataId) {
this.pendingDevToolsRunMetadataByMessageId.delete(messageId);
break;
}
}
this.devToolsService?.clearPendingRunMetadata(workspaceId, metadataId);
}
private async ensureSessionsDir(): Promise<void> {
try {
await ensurePrivateDir(this.config.sessionsDir);
} catch (error) {
log.error("Failed to create sessions directory:", error);
}
}
isMockModeEnabled(): boolean {
return this.mockModeEnabled;
}
releaseMockStreamStartGate(workspaceId: string): void {
this.mockAiStreamPlayer?.releaseStreamStartGate(workspaceId);
}
enableMockMode(): void {
this.mockModeEnabled = true;
this.mockAiStreamPlayer ??= new MockAiStreamPlayer({
aiService: this,
historyService: this.historyService,
});
}
async getWorkspaceMetadata(workspaceId: string): Promise<Result<WorkspaceMetadata>> {
try {
// Read from config.json (single source of truth)
// getAllWorkspaceMetadata() handles migration from legacy metadata.json files
const allMetadata = await this.config.getAllWorkspaceMetadata();
const metadata = allMetadata.find((m) => m.id === workspaceId);
if (!metadata) {
return Err(
`Workspace metadata not found for ${workspaceId}. Workspace may not be properly initialized.`
);
}
return Ok(metadata);
} catch (error) {
const message = getErrorMessage(error);
return Err(`Failed to read workspace metadata: ${message}`);
}
}
/**
* Create an AI SDK model from a model string (e.g., "anthropic:claude-opus-4-1").
* Delegates to ProviderModelFactory.
*/
async createModel(
modelString: string,
muxProviderOptions?: MuxProviderOptions,
opts?: { agentInitiated?: boolean; workspaceId?: string }
): Promise<Result<LanguageModel, SendMessageError>> {
return this.providerModelFactory.createModel(modelString, muxProviderOptions, opts);
}
private wrapToolsForDelegation(
workspaceId: string,
tools: Record<string, Tool>,
delegatedToolNames?: string[]
): Record<string, Tool> {
const normalizedDelegatedTools =
delegatedToolNames
?.map((toolName) => toolName.trim())
.filter((toolName) => toolName.length > 0) ?? [];
if (normalizedDelegatedTools.length === 0) {
return tools;
}
const delegatedToolSet = new Set(normalizedDelegatedTools);
const wrappedTools = { ...tools };
for (const [toolName, tool] of Object.entries(tools)) {
if (!delegatedToolSet.has(toolName)) {
continue;
}
const toolRecord = tool as Record<string, unknown>;
const execute = toolRecord.execute;
if (typeof execute !== "function") {
continue;
}
const wrappedTool = cloneToolPreservingDescriptors(tool);
const wrappedToolRecord = wrappedTool as Record<string, unknown>;
wrappedToolRecord.execute = async (_args: unknown, options: unknown) => {
const executionContext = isToolExecutionContext(options) ? options : undefined;
const toolCallId = executionContext?.toolCallId?.trim();
if (executionContext == null || toolCallId == null || toolCallId.length === 0) {
throw new Error(
`Delegated tool '${toolName}' requires a non-empty toolCallId in execute context`
);
}
const pendingResult = delegatedToolCallManager.registerPending(
workspaceId,
toolCallId,
toolName
);
const abortSignal = executionContext.abortSignal;
if (abortSignal == null) {
return pendingResult;
}
if (abortSignal.aborted) {
try {
delegatedToolCallManager.cancel(workspaceId, toolCallId, "Interrupted");
} catch {
// no-op: pending may already have resolved
}
throw new Error("Interrupted");
}
let abortListener: (() => void) | undefined;
const abortPromise = new Promise<never>((_, reject) => {
abortListener = () => {
try {
delegatedToolCallManager.cancel(workspaceId, toolCallId, "Interrupted");
} catch {
// no-op: pending may already have resolved
}
reject(new Error("Interrupted"));
};
abortSignal.addEventListener("abort", abortListener, { once: true });
});
try {
return await Promise.race([pendingResult, abortPromise]);
} finally {
if (abortListener != null) {
abortSignal.removeEventListener("abort", abortListener);
}
}
};
wrappedTools[toolName] = wrappedTool;
}
return wrappedTools;
}
private getMultiProjectExecutionDisabledMessage(workspaceId: string): string {
return `Workspace ${workspaceId} reached multi-project AI runtime execution while ${EXPERIMENT_IDS.MULTI_PROJECT_WORKSPACES} is disabled`;
}
private ensureMultiProjectRuntimeExecutionEnabled(
workspaceId: string,
metadata: WorkspaceMetadata
): Result<void, SendMessageError> {
if (!isMultiProject(metadata)) {
return Ok(undefined);
}
// Multi-project execution should already be gated before streamMessage reaches backend runtime
// orchestration. If stale workspace ids or future callsites bypass those checks, fail closed
// before constructing MultiProjectRuntime or loading shared-project secrets/tools.
if (!this.experimentsService) {
return Err({
type: "unknown",
raw: "AIService multi-project execution requires ExperimentsService to enforce the runtime gate",
});
}
if (!this.experimentsService.isExperimentEnabled(EXPERIMENT_IDS.MULTI_PROJECT_WORKSPACES)) {
return Err({
type: "unknown",
raw: this.getMultiProjectExecutionDisabledMessage(workspaceId),
});
}
return Ok(undefined);
}
/** Stream a message conversation to the AI model. */
async streamMessage(opts: StreamMessageOptions): Promise<Result<void, SendMessageError>> {
const {
messages,
workspaceId,
modelString,
thinkingLevel,
toolPolicy,
abortSignal,
additionalSystemInstructions,
maxOutputTokens,
muxProviderOptions,
agentInitiated,
agentId,
acpPromptId,
delegatedToolNames,
recordFileState,
changedFileAttachments,
postCompactionAttachments,
experiments,
system1Model,
system1ThinkingLevel,
disableWorkspaceAgents,
hasQueuedMessage,
openaiTruncationModeOverride,
} = opts;
// Support interrupts during startup (before StreamManager emits stream-start).
// We register an AbortController up-front and let stopStream() abort it.
const pendingAbortController = new AbortController();
const startTime = Date.now();
const syntheticMessageId = `starting-${startTime}-${Math.random().toString(36).substring(2, 11)}`;
// Link external abort signal (if provided).
const unlinkAbortSignal = linkAbortSignal(abortSignal, pendingAbortController);
this.pendingStreamStarts.set(workspaceId, {
abortController: pendingAbortController,
startTime,
syntheticMessageId,
acpPromptId,
});
const combinedAbortSignal = pendingAbortController.signal;
let pendingRunMetadataId: string | null = null;
const startupPhaseTimingsMs: Record<string, number> = {};
const recordStartupPhaseTiming = (phase: string, phaseStartedAt: number): void => {
startupPhaseTimingsMs[phase] = Date.now() - phaseStartedAt;
};
let logSlowStreamStartup: ((details: Record<string, unknown>) => void) | undefined;
try {
if (this.mockModeEnabled && this.mockAiStreamPlayer) {
await this.initStateManager.waitForInit(workspaceId, combinedAbortSignal);
if (combinedAbortSignal.aborted) {
return Ok(undefined);
}
return await this.mockAiStreamPlayer.play(messages, workspaceId, {
model: modelString,
thinkingLevel,
abortSignal: combinedAbortSignal,
});
}
// DEBUG: Log streamMessage call
const lastMessage = messages[messages.length - 1];
log.debug(
`[STREAM MESSAGE] workspaceId=${workspaceId} messageCount=${messages.length} lastRole=${lastMessage?.role}`
);
// Before starting a new stream, commit any existing partial to history
// This is idempotent - won't double-commit if already in chat.jsonl
const commitPartialStartedAt = Date.now();
await this.historyService.commitPartial(workspaceId);
recordStartupPhaseTiming("commitPartialMs", commitPartialStartedAt);
// Helper: clean up an assistant placeholder that was appended to history but never
// streamed (due to abort during setup). Used in two abort-check sites below.
const deleteAbortedPlaceholder = async (messageId: string): Promise<void> => {
const deleteResult = await this.historyService.deleteMessage(workspaceId, messageId);
if (!deleteResult.success) {
log.error(
`Failed to delete aborted assistant placeholder (${messageId}): ${deleteResult.error}`
);
}
};
// Mode (plan|exec|compact) is derived from the selected agent definition.
const effectiveMuxProviderOptions: MuxProviderOptions = muxProviderOptions ?? {};
const effectiveThinkingLevel: ThinkingLevel = thinkingLevel ?? THINKING_LEVEL_OFF;
// Resolve model string (xAI variant mapping + gateway routing) and create the model.
const resolveAndCreateModelStartedAt = Date.now();
const modelResult = await this.providerModelFactory.resolveAndCreateModel(
modelString,
effectiveThinkingLevel,
effectiveMuxProviderOptions,
{ agentInitiated, workspaceId }
);
recordStartupPhaseTiming("resolveAndCreateModelMs", resolveAndCreateModelStartedAt);
if (!modelResult.success) {
return Err(modelResult.error);
}
const {
effectiveModelString,
canonicalModelString,
canonicalProviderName,
routedThroughGateway,
routeProvider,
} = modelResult.data;
// Dump original messages for debugging
log.debug_obj(`${workspaceId}/1_original_messages.json`, messages);
// Filter out assistant messages with only reasoning (no text/tools)
// EXCEPTION: When extended thinking is enabled, preserve reasoning-only messages
// to comply with Extended Thinking API requirements
const preserveReasoningOnly =
canonicalProviderName === "anthropic" && effectiveThinkingLevel !== "off";
const filteredMessages = filterEmptyAssistantMessages(messages, preserveReasoningOnly);
log.debug(`Filtered ${messages.length - filteredMessages.length} empty assistant messages`);
log.debug_obj(`${workspaceId}/1a_filtered_messages.json`, filteredMessages);
// WS2 request slicing: only send the latest compaction epoch to providers.
// This is request-only; persisted history remains append-only for replay/debugging.
const providerRequestMessages = sliceMessagesFromLatestCompactionBoundary(filteredMessages);
if (providerRequestMessages !== filteredMessages) {
log.debug("Sliced provider history from latest compaction boundary", {
workspaceId,
originalCount: filteredMessages.length,
slicedCount: providerRequestMessages.length,
});
}
log.debug_obj(`${workspaceId}/1b_provider_request_messages.json`, providerRequestMessages);
// OpenAI-specific: Keep reasoning parts in history so each request can
// carry forward reasoning context without relying on previous_response_id.
if (canonicalProviderName === "openai") {
log.debug("Keeping reasoning parts for OpenAI (managed via explicit history)");
}
// Add [CONTINUE] sentinel to partial messages (for model context)
const messagesWithSentinel = addInterruptedSentinel(providerRequestMessages);
// Get workspace metadata to retrieve workspace path
const getWorkspaceMetadataStartedAt = Date.now();
const metadataResult = await this.getWorkspaceMetadata(workspaceId);
recordStartupPhaseTiming("getWorkspaceMetadataMs", getWorkspaceMetadataStartedAt);
if (!metadataResult.success) {
return Err({ type: "unknown", raw: metadataResult.error });
}
const metadata = metadataResult.data;
if (this.policyService?.isEnforced()) {
if (!this.policyService.isRuntimeAllowed(metadata.runtimeConfig)) {
return Err({
type: "policy_denied",
message: "Workspace runtime is not allowed by policy",
});
}
}
const workspaceLog = log.withFields({ workspaceId, workspaceName: metadata.name });
logSlowStreamStartup = (details: Record<string, unknown>) => {
const totalMs = Date.now() - startTime;
if (totalMs < STREAM_STARTUP_DIAGNOSTIC_THRESHOLD_MS) {
return;
}
workspaceLog.info("[stream-startup] Slow pre-stream preparation", {
workspaceId,
modelString,
totalMs,
startupPhaseTimingsMs,
...details,
});
};
const emitStartupBreadcrumb = (
startupStage:
| "waiting_for_init"
| "checking_runtime"
| "loading_workspace_context"
| "loading_tools"
| "preparing_request"
| "starting_stream"
): void => {
const breadcrumb =
startupStage === "waiting_for_init"
? {
phase: "waiting" as const,
detail: "Waiting for workspace initialization...",
}
: startupStage === "checking_runtime"
? {
phase: "starting" as const,
detail: "Checking workspace runtime...",
}
: startupStage === "loading_workspace_context"
? {
phase: "starting" as const,
detail: "Loading workspace context...",
}
: startupStage === "loading_tools"
? {
phase: "starting" as const,
detail: "Loading tools...",
}
: startupStage === "preparing_request"
? {
phase: "starting" as const,
detail: "Preparing model request...",
}
: {
phase: "starting" as const,
detail: "Starting model stream...",
};
workspaceLog.info("[stream-startup] Breadcrumb", {
startupStage,
phase: breadcrumb.phase,
detail: breadcrumb.detail,
elapsedMs: Date.now() - startTime,
});
this.emit("runtime-status", {
type: "runtime-status",
workspaceId,
phase: breadcrumb.phase,
runtimeType: metadata.runtimeConfig.type,
source: "startup",
detail: breadcrumb.detail,
});
};
const workspace = this.config.findWorkspace(workspaceId);
if (!workspace) {
return Err({ type: "unknown", raw: `Workspace ${workspaceId} not found in config` });
}
const metadataWithPath = {
...metadata,
// Existing SSH workspaces may still live at a persisted root that differs from the canonical
// hashed project layout, so stream startup seeds the runtime from config for the current
// workspace instead of always reconstructing the path from project metadata.
namedWorkspacePath: workspace.workspacePath,
};
const multiProjectExecutionGate = this.ensureMultiProjectRuntimeExecutionEnabled(
workspaceId,
metadata
);
if (!multiProjectExecutionGate.success) {
return multiProjectExecutionGate;
}
const workspaceProjectRuntimeParams = {
workspaceName: metadata.name,
workspacePath: workspace.workspacePath,
runtimeConfig: metadata.runtimeConfig,
projectPath: metadata.projectPath,
projectName: metadata.projectName,
projects: metadata.projects,
};
const singleProjectContext = isMultiProject(metadata)
? undefined
: createRuntimeContextForWorkspace(metadataWithPath);
const runtime = singleProjectContext
? singleProjectContext.runtime
: new MultiProjectRuntime(
new ContainerManager(getSrcBaseDir(metadata.runtimeConfig) ?? this.config.srcDir),
getProjects(metadata).map((project) => ({
projectPath: project.projectPath,
projectName: project.projectName,
runtime: createRuntimeForWorkspaceProject(
workspaceProjectRuntimeParams,
project.projectPath
),
})),
metadata.name
);
const workspacePath =
singleProjectContext?.workspacePath ??
(isSSHRuntime(metadata.runtimeConfig)
? resolveWorkspaceExecutionPath(metadataWithPath, runtime)
: // Non-SSH multi-project runtimes intentionally start from their shared container root so
// sibling repos stay addressable during agent/tool setup. SSH workspaces are the exception:
// upgraded legacy layouts must reuse the persisted root from config until remote layout
// detection seeds the new hashed paths.
runtime.getWorkspacePath(metadata.projectPath, metadata.name));
// Wait for init to complete before any runtime I/O operations
// (SSH/devcontainer may not be ready until init finishes pulling the container)
emitStartupBreadcrumb("waiting_for_init");
const waitForInitStartedAt = Date.now();
await this.initStateManager.waitForInit(workspaceId, combinedAbortSignal);
recordStartupPhaseTiming("waitForInitMs", waitForInitStartedAt);
if (combinedAbortSignal.aborted) {
return Ok(undefined);
}
// Verify runtime is actually reachable after init completes.
// For Docker workspaces, this checks the container exists and starts it if stopped.
// For Coder workspaces, this may start a stopped workspace and wait for it.