-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathtaskService.ts
More file actions
4945 lines (4381 loc) · 172 KB
/
taskService.ts
File metadata and controls
4945 lines (4381 loc) · 172 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 assert from "node:assert/strict";
import * as fsPromises from "fs/promises";
import type { z } from "zod";
import { MutexMap } from "@/node/utils/concurrency/mutexMap";
import { AsyncMutex } from "@/node/utils/concurrency/asyncMutex";
import type { Config, Workspace as WorkspaceConfigEntry } from "@/node/config";
import type { AIService } from "@/node/services/aiService";
import type { WorkspaceService } from "@/node/services/workspaceService";
import type { HistoryService } from "@/node/services/historyService";
import type { InitStateManager } from "@/node/services/initStateManager";
import { log } from "@/node/services/log";
import {
discoverAgentDefinitions,
getSkipScopesAboveForKnownScope,
readAgentDefinition,
resolveAgentFrontmatter,
} from "@/node/services/agentDefinitions/agentDefinitionsService";
import { resolveAgentInheritanceChain } from "@/node/services/agentDefinitions/resolveAgentInheritanceChain";
import { isAgentEffectivelyDisabled } from "@/node/services/agentDefinitions/agentEnablement";
import { orchestrateFork } from "@/node/services/utils/forkOrchestrator";
import { createRuntimeForWorkspace } from "@/node/runtime/runtimeHelpers";
import { MultiProjectRuntime } from "@/node/runtime/multiProjectRuntime";
import { runBackgroundInit } from "@/node/runtime/runtimeFactory";
import type { InitLogger, Runtime } from "@/node/runtime/Runtime";
import { readPlanFile } from "@/node/utils/runtime/helpers";
import { routePlanToExecutor } from "@/node/services/planExecutorRouter";
import {
coerceNonEmptyString,
tryReadGitHeadCommitSha,
findWorkspaceEntry,
} from "@/node/services/taskUtils";
import { validateWorkspaceName } from "@/common/utils/validation/workspaceValidation";
import {
TASK_GROUP_KIND,
getTaskGroupCount,
normalizeTaskGroupKind,
normalizeTaskGroupLabel,
type TaskGroupKind,
} from "@/common/utils/tools/taskGroups";
import { stripTrailingSlashes } from "@/node/utils/pathUtils";
import { Ok, Err, type Result } from "@/common/types/result";
import {
DEFAULT_TASK_SETTINGS,
normalizeTaskSettings,
type PlanSubagentExecutorRouting,
type TaskSettings,
} from "@/common/types/tasks";
import { createMuxMessage, type MuxMessage } from "@/common/types/message";
import {
createCompactionSummaryMessageId,
createTaskReportMessageId,
} from "@/node/services/utils/messageIds";
import { defaultModel, normalizeToCanonical } from "@/common/utils/ai/models";
import { EXPERIMENT_IDS } from "@/common/constants/experiments";
import { DEFAULT_RUNTIME_CONFIG } from "@/common/constants/workspace";
import type { RuntimeConfig } from "@/common/types/runtime";
import type { WorkspaceMetadata } from "@/common/types/workspace";
import { AgentIdSchema } from "@/common/orpc/schemas";
import { normalizeAgentId } from "@/common/utils/agentIds";
import { GitPatchArtifactService } from "@/node/services/gitPatchArtifactService";
import { getWorkspaceProjectRepos } from "@/node/services/workspaceProjectRepos";
import type { ThinkingLevel } from "@/common/types/thinking";
import type { ErrorEvent, StreamEndEvent } from "@/common/types/stream";
import { isDynamicToolPart, type DynamicToolPart } from "@/common/types/toolParts";
import {
AgentReportToolArgsSchema,
TaskToolResultSchema,
TaskToolArgsSchema,
} from "@/common/utils/tools/toolDefinitions";
import { isPlanLikeInResolvedChain, isToolEnabledInResolvedChain } from "@/common/utils/agentTools";
import { formatSendMessageError } from "@/node/services/utils/sendMessageError";
import { enforceThinkingPolicy } from "@/common/utils/thinking/policy";
import {
PLAN_AUTO_ROUTING_STATUS_EMOJI,
PLAN_AUTO_ROUTING_STATUS_MESSAGE,
} from "@/common/constants/planAutoRoutingStatus";
import { taskQueueDebug } from "@/node/services/taskQueueDebug";
import { readSubagentGitPatchArtifact } from "@/node/services/subagentGitPatchArtifacts";
import {
readSubagentReportArtifact,
readSubagentReportArtifactsFile,
upsertSubagentReportArtifact,
} from "@/node/services/subagentReportArtifacts";
import { secretsToRecord, type ExternalSecretResolver } from "@/common/types/secrets";
import { getErrorMessage } from "@/common/utils/errors";
import { isNonRetryableStreamError } from "@/common/utils/messages/retryEligibility";
import { hasCompletedAgentReport } from "@/common/utils/agentTaskCompletion";
import { isWorkspaceArchived } from "@/common/utils/archive";
export type TaskKind = "agent";
export type AgentTaskStatus = NonNullable<WorkspaceConfigEntry["taskStatus"]>;
/**
* Resolved per-agent AI settings (canonical model + optional thinking level).
*
* `thinkingLevel` is optional because internal callers read these settings off of
* partial workspace metadata where the field may be missing on older entries.
*/
interface ResolvedWorkspaceAiSettings {
model: string;
thinkingLevel?: ThinkingLevel;
}
export interface AgentTaskStatusLookup {
exists: boolean;
taskStatus: AgentTaskStatus | null;
}
export interface TaskCreateArgs {
parentWorkspaceId: string;
kind: TaskKind;
/** Preferred identifier (matches agent definition id). */
agentId?: string;
/** @deprecated Legacy alias for agentId (kept for on-disk compatibility). */
agentType?: string;
prompt: string;
/** Human-readable title for the task (displayed in sidebar) */
title: string;
modelString?: string;
thinkingLevel?: ThinkingLevel;
parentRuntimeAiSettings?: { modelString?: string; thinkingLevel?: ThinkingLevel };
/** Shared grouping metadata when one tool call spawns multiple sibling tasks. */
bestOf?: {
groupId: string;
index: number;
total: number;
kind?: TaskGroupKind;
label?: string;
};
/** Experiments to inherit to subagent */
experiments?: {
programmaticToolCalling?: boolean;
programmaticToolCallingExclusive?: boolean;
execSubagentHardRestart?: boolean;
};
}
export interface TaskCreateResult {
taskId: string;
kind: TaskKind;
status: "queued" | "running";
}
export interface TerminateAgentTaskResult {
/** Task IDs terminated (includes descendants). */
terminatedTaskIds: string[];
}
export interface DescendantAgentTaskInfo {
taskId: string;
status: AgentTaskStatus;
parentWorkspaceId: string;
agentType?: string;
workspaceName?: string;
title?: string;
createdAt?: string;
modelString?: string;
thinkingLevel?: ThinkingLevel;
depth: number;
}
type AgentTaskWorkspaceEntry = WorkspaceConfigEntry & { projectPath: string };
const COMPLETED_REPORT_CACHE_MAX_ENTRIES = 128;
/** Maximum consecutive auto-resumes before stopping. Prevents infinite loops when descendants are stuck. */
// Task-recovery paths must stay deterministic and editing-capable even when
// workspace/default agent preferences evolve (e.g., auto router defaults).
const TASK_RECOVERY_FALLBACK_AGENT_ID = "exec";
const MAX_CONSECUTIVE_PARENT_AUTO_RESUMES = 3;
interface AgentTaskIndex {
byId: Map<string, AgentTaskWorkspaceEntry>;
childrenByParent: Map<string, string[]>;
parentById: Map<string, string>;
}
interface PendingTaskWaiter {
taskId: string;
resolve: (report: { reportMarkdown: string; title?: string }) => void;
reject: (error: Error) => void;
cleanup: () => void;
requestingWorkspaceId?: string;
backgroundOnMessageQueued: boolean;
}
interface PendingTaskStartWaiter {
start: () => void;
cleanup: () => void;
}
interface CompletedAgentReportCacheEntry {
reportMarkdown: string;
title?: string;
// Ancestor workspace IDs captured when the report was cached.
// Used to keep descendant-scope checks working even if the task workspace is cleaned up.
ancestorWorkspaceIds: string[];
}
interface ParentAutoResumeHint {
agentId?: string;
}
function isTypedWorkspaceEvent(value: unknown, type: string): boolean {
return (
typeof value === "object" &&
value !== null &&
"type" in value &&
(value as { type: unknown }).type === type &&
"workspaceId" in value &&
typeof (value as { workspaceId: unknown }).workspaceId === "string"
);
}
function isStreamEndEvent(value: unknown): value is StreamEndEvent {
return isTypedWorkspaceEvent(value, "stream-end");
}
function isErrorEvent(value: unknown): value is ErrorEvent {
return isTypedWorkspaceEvent(value, "error");
}
function hasAncestorWorkspaceId(
entry: { ancestorWorkspaceIds?: unknown } | null | undefined,
ancestorWorkspaceId: string
): boolean {
const ids = entry?.ancestorWorkspaceIds;
return Array.isArray(ids) && ids.includes(ancestorWorkspaceId);
}
function isSuccessfulToolResult(value: unknown): boolean {
return (
typeof value === "object" &&
value !== null &&
"success" in value &&
(value as { success?: unknown }).success === true
);
}
function sanitizeAgentTypeForName(agentType: string): string {
const normalized = agentType
.trim()
.toLowerCase()
.replace(/[^a-z0-9_-]/g, "_")
.replace(/_+/g, "_")
.replace(/-+/g, "-")
.replace(/^[_-]+|[_-]+$/g, "");
return normalized.length > 0 ? normalized : "agent";
}
function buildAgentWorkspaceName(agentType: string, workspaceId: string): string {
const safeType = sanitizeAgentTypeForName(agentType);
const base = `agent_${safeType}_${workspaceId}`;
// Hard cap to validation limit (64). Ensure stable suffix is preserved.
if (base.length <= 64) return base;
const suffix = `_${workspaceId}`;
const maxPrefixLen = 64 - suffix.length;
const prefix = `agent_${safeType}`.slice(0, Math.max(0, maxPrefixLen));
const name = `${prefix}${suffix}`;
return name.length <= 64 ? name : `agent_${workspaceId}`.slice(0, 64);
}
function getIsoNow(): string {
return new Date().toISOString();
}
async function readTaskBaseCommitShaByProjectPath(params: {
workspaceId: string;
workspaceName: string;
workspacePath: string;
runtimeConfig: RuntimeConfig;
projectPath: string;
projectName: string;
projects?: WorkspaceMetadata["projects"];
runtime: Runtime;
}): Promise<Record<string, string>> {
const projectRepos = getWorkspaceProjectRepos({
workspaceId: params.workspaceId,
workspaceName: params.workspaceName,
workspacePath: params.workspacePath,
runtimeConfig: params.runtimeConfig,
projectPath: params.projectPath,
projectName: params.projectName,
projects: params.projects,
});
const taskBaseCommitShaByProjectPath: Record<string, string> = {};
for (const projectRepo of projectRepos) {
const taskBaseCommitSha = await tryReadGitHeadCommitSha(params.runtime, projectRepo.repoCwd);
if (taskBaseCommitSha) {
taskBaseCommitShaByProjectPath[projectRepo.projectPath] = taskBaseCommitSha;
}
}
return taskBaseCommitShaByProjectPath;
}
export class ForegroundWaitBackgroundedError extends Error {
constructor() {
super("Foreground wait sent to background due to queued message");
this.name = "ForegroundWaitBackgroundedError";
}
}
export class TaskService {
// Serialize stream-end processing per workspace to avoid races when
// finalizing reported tasks and cleanup state transitions.
private readonly workspaceEventLocks = new MutexMap<string>();
// Separate parent-scoped lock for deferred best-of fallback/finalization. This path can run
// concurrently from multiple child stream-end handlers for the same parent, and it must remain
// safe even when the parent stream-end already holds workspaceEventLocks for the parent itself.
private readonly deferredBestOfLocks = new MutexMap<string>();
private readonly mutex = new AsyncMutex();
private readonly pendingWaitersByTaskId = new Map<string, PendingTaskWaiter[]>();
private readonly pendingStartWaitersByTaskId = new Map<string, PendingTaskStartWaiter[]>();
// Tracks workspaces currently blocked in a foreground wait (e.g. a task tool call awaiting
// agent_report). Used to avoid scheduler deadlocks when maxParallelAgentTasks is low and tasks
// spawn nested tasks in the foreground.
private readonly foregroundAwaitCountByWorkspaceId = new Map<string, number>();
private readonly backgroundableForegroundWaitersByWorkspaceId = new Map<
string,
Set<PendingTaskWaiter>
>();
private readonly userBackgroundedTaskIds = new Set<string>();
// Cache completed reports so callers can retrieve them without re-reading disk.
// Bounded by max entries; disk persistence is the source of truth for restart-safety.
private readonly completedReportsByTaskId = new Map<string, CompletedAgentReportCacheEntry>();
private readonly gitPatchArtifactService: GitPatchArtifactService;
private readonly handoffInProgress = new Set<string>();
/**
* Hard-interrupted parent workspaces must not auto-resume until the next user message.
* This closes races where descendants could report between parent interrupt and cascade cleanup.
*/
private interruptedParentWorkspaceIds = new Set<string>();
/** Tracks consecutive auto-resumes per workspace. Reset when a user message is sent. */
private consecutiveAutoResumes = new Map<string, number>();
private markTaskQueueBackgrounded(taskId: string): void {
this.userBackgroundedTaskIds.add(taskId);
}
private markTaskForegroundRelevant(taskId: string): void {
this.userBackgroundedTaskIds.delete(taskId);
}
private isTaskQueueBackgrounded(taskId: string): boolean {
return this.userBackgroundedTaskIds.has(taskId);
}
constructor(
private readonly config: Config,
private readonly historyService: HistoryService,
private readonly aiService: AIService,
private readonly workspaceService: WorkspaceService,
private readonly initStateManager: InitStateManager,
private readonly opResolver?: ExternalSecretResolver
) {
this.gitPatchArtifactService = new GitPatchArtifactService(config);
this.aiService.on("stream-end", (payload: unknown) => {
if (!isStreamEndEvent(payload)) return;
void this.workspaceEventLocks
.withLock(payload.workspaceId, async () => {
await this.handleStreamEnd(payload);
})
.catch((error: unknown) => {
log.error("TaskService.handleStreamEnd failed", { error });
});
});
this.aiService.on("error", (payload: unknown) => {
if (!isErrorEvent(payload)) return;
void this.workspaceEventLocks
.withLock(payload.workspaceId, async () => {
await this.handleTaskStreamError(payload);
})
.catch((error: unknown) => {
log.error("TaskService.handleTaskStreamError failed", { error });
});
});
}
// Prefer per-agent settings so tasks inherit the correct agent defaults;
// fall back to legacy workspace settings for older configs.
private resolveWorkspaceAISettings(
workspace: {
aiSettingsByAgent?: Record<string, ResolvedWorkspaceAiSettings>;
aiSettings?: ResolvedWorkspaceAiSettings;
},
agentId: string | undefined
): ResolvedWorkspaceAiSettings | undefined {
const normalizedAgentId =
typeof agentId === "string" && agentId.trim().length > 0
? normalizeAgentId(agentId, "")
: undefined;
return (
(normalizedAgentId ? workspace.aiSettingsByAgent?.[normalizedAgentId] : undefined) ??
workspace.aiSettings
);
}
private resolveTaskAISettings(params: {
cfg: ReturnType<Config["loadConfigOrDefault"]>;
parentMeta: {
aiSettingsByAgent?: Record<string, ResolvedWorkspaceAiSettings>;
aiSettings?: ResolvedWorkspaceAiSettings;
};
agentId: string;
modelString?: string;
thinkingLevel?: ThinkingLevel;
parentRuntimeAiSettings?: { modelString?: string; thinkingLevel?: ThinkingLevel };
}): {
taskModelString: string;
canonicalModel: string;
effectiveThinkingLevel: ThinkingLevel;
} {
const parentAiSettings = this.resolveWorkspaceAISettings(params.parentMeta, params.agentId);
// Sub-agent defaults take priority over UI agent defaults per field for any agent invoked as a sub-agent.
const subagentDefault = params.cfg.subagentAiDefaults?.[params.agentId];
const agentDefault = params.cfg.agentAiDefaults?.[params.agentId];
const parentRuntimeAiSettings = params.parentRuntimeAiSettings;
const taskModelString =
coerceNonEmptyString(params.modelString) ??
coerceNonEmptyString(subagentDefault?.modelString) ??
coerceNonEmptyString(agentDefault?.modelString) ??
coerceNonEmptyString(parentRuntimeAiSettings?.modelString) ??
coerceNonEmptyString(parentAiSettings?.model) ??
defaultModel;
const canonicalModel = normalizeToCanonical(taskModelString).trim();
assert(canonicalModel.length > 0, "resolveTaskAISettings: resolved model must be non-empty");
const requestedThinkingLevel: ThinkingLevel =
params.thinkingLevel ??
subagentDefault?.thinkingLevel ??
agentDefault?.thinkingLevel ??
parentRuntimeAiSettings?.thinkingLevel ??
parentAiSettings?.thinkingLevel ??
"off";
const effectiveThinkingLevel = enforceThinkingPolicy(canonicalModel, requestedThinkingLevel);
return { taskModelString, canonicalModel, effectiveThinkingLevel };
}
/**
* Derives auto-resume send options (agentId, model, thinkingLevel) from durable
* conversation metadata, so synthetic resumes preserve the parent's active agent.
*
* Precedence: stream-end event metadata → last assistant message in history → workspace AI settings → defaults.
*/
private async resolveParentAutoResumeOptions(
parentWorkspaceId: string,
parentEntry: {
workspace: {
aiSettingsByAgent?: Record<string, ResolvedWorkspaceAiSettings>;
aiSettings?: ResolvedWorkspaceAiSettings;
};
},
fallbackModel: string,
hint?: ParentAutoResumeHint
): Promise<{ model: string; agentId: string; thinkingLevel?: ThinkingLevel }> {
// 1) Try stream-end hint metadata (available in handleStreamEnd path)
let agentId = hint?.agentId;
// 2) Fall back to latest assistant message metadata in history (restart-safe)
if (!agentId) {
try {
const historyResult = await this.historyService.getLastMessages(parentWorkspaceId, 20);
if (historyResult.success) {
for (let i = historyResult.data.length - 1; i >= 0; i--) {
const msg = historyResult.data[i];
if (msg?.role === "assistant" && msg.metadata?.agentId) {
agentId = msg.metadata.agentId;
break;
}
}
}
} catch {
// Best-effort; fall through to defaults
}
}
// 3) Default
// Keep task auto-resume recovery on exec even if the workspace default agent changes.
// This path needs a deterministic editing-capable fallback for legacy/incomplete metadata.
agentId = agentId ?? TASK_RECOVERY_FALLBACK_AGENT_ID;
const aiSettings = this.resolveWorkspaceAISettings(parentEntry.workspace, agentId);
return {
model: aiSettings?.model ?? fallbackModel,
agentId,
thinkingLevel: aiSettings?.thinkingLevel,
};
}
private async isPlanLikeTaskWorkspace(entry: {
projectPath: string;
workspace: Pick<
WorkspaceConfigEntry,
"id" | "name" | "path" | "runtimeConfig" | "agentId" | "agentType"
>;
}): Promise<boolean> {
assert(entry.projectPath.length > 0, "isPlanLikeTaskWorkspace: projectPath must be non-empty");
const rawAgentId = coerceNonEmptyString(entry.workspace.agentId ?? entry.workspace.agentType);
if (!rawAgentId) {
return false;
}
const normalizedAgentId = rawAgentId.trim().toLowerCase();
const parsedAgentId = AgentIdSchema.safeParse(normalizedAgentId);
if (!parsedAgentId.success) {
return normalizedAgentId === "plan";
}
const workspacePath = coerceNonEmptyString(entry.workspace.path);
const workspaceName = coerceNonEmptyString(entry.workspace.name) ?? entry.workspace.id;
const runtimeConfig = entry.workspace.runtimeConfig ?? DEFAULT_RUNTIME_CONFIG;
if (!workspacePath || !workspaceName) {
return parsedAgentId.data === "plan";
}
try {
const runtime = createRuntimeForWorkspace({
runtimeConfig,
projectPath: entry.projectPath,
name: workspaceName,
});
const agentDefinition = await readAgentDefinition(runtime, workspacePath, parsedAgentId.data);
const chain = await resolveAgentInheritanceChain({
runtime,
workspacePath,
agentId: agentDefinition.id,
agentDefinition,
workspaceId: entry.workspace.id ?? workspaceName,
});
if (agentDefinition.id === "compact") {
return false;
}
return isPlanLikeInResolvedChain(chain);
} catch (error: unknown) {
log.debug("Failed to resolve task agent mode; falling back to agentId check", {
workspaceId: entry.workspace.id,
agentId: parsedAgentId.data,
error: error instanceof Error ? error.message : String(error),
});
return parsedAgentId.data === "plan";
}
}
private getTaskWorkspaceAgentResolutionContext(args: {
projectPath: string;
workspace: Pick<WorkspaceConfigEntry, "id" | "name" | "path" | "runtimeConfig">;
}): {
workspaceName: string;
runtime: Runtime;
workspacePath: string;
} | null {
assert(
args.projectPath.length > 0,
"getTaskWorkspaceAgentResolutionContext: projectPath must be non-empty"
);
const workspaceName = coerceNonEmptyString(args.workspace.name) ?? args.workspace.id;
if (!workspaceName) {
return null;
}
const runtimeConfig = args.workspace.runtimeConfig ?? DEFAULT_RUNTIME_CONFIG;
const runtime = createRuntimeForWorkspace({
runtimeConfig,
projectPath: args.projectPath,
name: workspaceName,
});
const workspacePath =
coerceNonEmptyString(args.workspace.path) ??
runtime.getWorkspacePath(args.projectPath, workspaceName);
if (!workspacePath) {
return null;
}
return {
workspaceName,
runtime,
workspacePath,
};
}
private async isAgentEnabledForTaskWorkspace(args: {
workspaceId: string;
projectPath: string;
workspace: Pick<WorkspaceConfigEntry, "id" | "name" | "path" | "runtimeConfig">;
agentId: "exec" | "orchestrator";
}): Promise<boolean> {
assert(
args.workspaceId.length > 0,
"isAgentEnabledForTaskWorkspace: workspaceId must be non-empty"
);
assert(
args.projectPath.length > 0,
"isAgentEnabledForTaskWorkspace: projectPath must be non-empty"
);
const resolutionContext = this.getTaskWorkspaceAgentResolutionContext({
projectPath: args.projectPath,
workspace: args.workspace,
});
if (!resolutionContext) {
return false;
}
try {
const resolvedFrontmatter = await resolveAgentFrontmatter(
resolutionContext.runtime,
resolutionContext.workspacePath,
args.agentId
);
const cfg = this.config.loadConfigOrDefault();
const effectivelyDisabled = isAgentEffectivelyDisabled({
cfg,
agentId: args.agentId,
resolvedFrontmatter,
});
return !effectivelyDisabled;
} catch (error: unknown) {
log.warn("Failed to resolve task handoff target agent availability", {
workspaceId: args.workspaceId,
agentId: args.agentId,
error: getErrorMessage(error),
});
return false;
}
}
private async canAgentSpawnTasksInWorkspace(args: {
workspaceId: string;
projectPath: string;
workspace: Pick<WorkspaceConfigEntry, "id" | "name" | "path" | "runtimeConfig">;
agentId: "orchestrator";
}): Promise<boolean> {
assert(
args.workspaceId.length > 0,
"canAgentSpawnTasksInWorkspace: workspaceId must be non-empty"
);
assert(
args.projectPath.length > 0,
"canAgentSpawnTasksInWorkspace: projectPath must be non-empty"
);
const resolutionContext = this.getTaskWorkspaceAgentResolutionContext({
projectPath: args.projectPath,
workspace: args.workspace,
});
if (!resolutionContext) {
return false;
}
try {
const cfg = this.config.loadConfigOrDefault();
const resolvedFrontmatter = await resolveAgentFrontmatter(
resolutionContext.runtime,
resolutionContext.workspacePath,
args.agentId
);
const effectivelyDisabled = isAgentEffectivelyDisabled({
cfg,
agentId: args.agentId,
resolvedFrontmatter,
});
if (effectivelyDisabled) {
return false;
}
const agentDefinition = await readAgentDefinition(
resolutionContext.runtime,
resolutionContext.workspacePath,
args.agentId
);
const chain = await resolveAgentInheritanceChain({
runtime: resolutionContext.runtime,
workspacePath: resolutionContext.workspacePath,
agentId: agentDefinition.id,
agentDefinition,
workspaceId: args.workspaceId,
});
const taskSettings = cfg.taskSettings ?? DEFAULT_TASK_SETTINGS;
const taskDepth = this.getTaskDepth(cfg, args.workspaceId);
const disableTaskToolsForDepth = taskDepth >= taskSettings.maxTaskNestingDepth;
return !disableTaskToolsForDepth && isToolEnabledInResolvedChain("task", chain);
} catch (error: unknown) {
log.warn("Failed to resolve task handoff target task-spawning capability", {
workspaceId: args.workspaceId,
agentId: args.agentId,
error: getErrorMessage(error),
});
return false;
}
}
private async resolvePlanAutoHandoffTargetAgentId(args: {
workspaceId: string;
entry: {
projectPath: string;
workspace: Pick<
WorkspaceConfigEntry,
"id" | "name" | "path" | "runtimeConfig" | "taskModelString"
>;
};
routing: PlanSubagentExecutorRouting;
planContent: string | null;
}): Promise<"exec" | "orchestrator"> {
assert(
args.workspaceId.length > 0,
"resolvePlanAutoHandoffTargetAgentId: workspaceId must be non-empty"
);
assert(
args.routing === "exec" || args.routing === "orchestrator" || args.routing === "auto",
"resolvePlanAutoHandoffTargetAgentId: routing must be exec, orchestrator, or auto"
);
const resolveOrchestratorAvailability = async (): Promise<"exec" | "orchestrator"> => {
const orchestratorEnabled = await this.isAgentEnabledForTaskWorkspace({
workspaceId: args.workspaceId,
projectPath: args.entry.projectPath,
workspace: args.entry.workspace,
agentId: "orchestrator",
});
if (orchestratorEnabled) {
return "orchestrator";
}
// If orchestrator is disabled/unavailable, fall back to exec before mutating
// workspace agent state so the handoff stream can still proceed.
log.warn("Plan-task auto-handoff falling back to exec because orchestrator is unavailable", {
workspaceId: args.workspaceId,
});
return "exec";
};
if (args.routing === "exec") {
return "exec";
}
if (args.routing === "orchestrator") {
return resolveOrchestratorAvailability();
}
if (!args.planContent || args.planContent.trim().length === 0) {
log.warn("Plan-task auto-handoff auto-routing has no plan content; defaulting to exec", {
workspaceId: args.workspaceId,
});
return "exec";
}
const orchestratorCanSpawnTasks = await this.canAgentSpawnTasksInWorkspace({
workspaceId: args.workspaceId,
projectPath: args.entry.projectPath,
workspace: args.entry.workspace,
agentId: "orchestrator",
});
if (!orchestratorCanSpawnTasks) {
log.warn(
"Plan-task auto-handoff auto-routing defaulting to exec because orchestrator cannot orchestrate in this workspace",
{
workspaceId: args.workspaceId,
}
);
return "exec";
}
const modelString = normalizeToCanonical(
coerceNonEmptyString(args.entry.workspace.taskModelString) ?? defaultModel
);
assert(
modelString.trim().length > 0,
"resolvePlanAutoHandoffTargetAgentId: modelString must be non-empty"
);
const modelResult = await this.aiService.createModel(modelString, undefined, {
agentInitiated: true,
workspaceId: args.workspaceId,
});
if (!modelResult.success) {
log.warn("Plan-task auto-handoff auto-routing failed to create model; defaulting to exec", {
workspaceId: args.workspaceId,
model: modelString,
error: modelResult.error,
});
return "exec";
}
const decision = await routePlanToExecutor({
model: modelResult.data,
planContent: args.planContent,
});
log.info("Plan-task auto-handoff routing decision", {
workspaceId: args.workspaceId,
target: decision.target,
reasoning: decision.reasoning,
model: modelString,
});
if (decision.target === "orchestrator") {
return resolveOrchestratorAvailability();
}
return "exec";
}
private async emitWorkspaceMetadata(workspaceId: string): Promise<void> {
assert(workspaceId.length > 0, "emitWorkspaceMetadata: workspaceId must be non-empty");
const allMetadata = await this.config.getAllWorkspaceMetadata();
const metadata = allMetadata.find((m) => m.id === workspaceId) ?? null;
this.workspaceService.emit("metadata", { workspaceId, metadata });
}
private configureMultiProjectRuntimeEnvResolver(runtime: Runtime): void {
if (!(runtime instanceof MultiProjectRuntime)) {
return;
}
const projectEnvCache = new Map<string, Record<string, string>>();
runtime.envResolver = async (runtimeProjectPath: string) => {
const normalizedRuntimeProjectPath = stripTrailingSlashes(runtimeProjectPath);
const cachedEnv = projectEnvCache.get(normalizedRuntimeProjectPath);
if (cachedEnv) {
return cachedEnv;
}
const projectEnv = await secretsToRecord(
this.config.getEffectiveSecrets(normalizedRuntimeProjectPath),
this.opResolver
);
projectEnvCache.set(normalizedRuntimeProjectPath, projectEnv);
return projectEnv;
};
}
private async editWorkspaceEntry(
workspaceId: string,
updater: (workspace: WorkspaceConfigEntry) => void,
options?: { allowMissing?: boolean }
): Promise<boolean> {
assert(workspaceId.length > 0, "editWorkspaceEntry: workspaceId must be non-empty");
let found = false;
await this.config.editConfig((config) => {
for (const [_projectPath, project] of config.projects) {
const ws = project.workspaces.find((w) => w.id === workspaceId);
if (!ws) continue;
updater(ws);
found = true;
return config;
}
if (options?.allowMissing) {
return config;
}
throw new Error(`editWorkspaceEntry: workspace ${workspaceId} not found`);
});
return found;
}
async initialize(): Promise<void> {
const startupStartedAt = Date.now();
const startupConfig = this.config.loadConfigOrDefault();
const queuedTaskCountAtStartup = this.listAgentTaskWorkspaces(startupConfig).filter(
(task) => task.taskStatus === "queued" && typeof task.id === "string"
).length;
log.info("[startup] TaskService.initialize starting", {
queuedTaskCountAtStartup,
});
const maybeStartQueuedTasksStartedAt = Date.now();
await this.maybeStartQueuedTasks();
const maybeStartQueuedTasksMs = Date.now() - maybeStartQueuedTasksStartedAt;
const config = this.config.loadConfigOrDefault();
const awaitingReportTasks = this.listAgentTaskWorkspaces(config).filter(
(t) => t.taskStatus === "awaiting_report"
);
const runningTasks = this.listAgentTaskWorkspaces(config).filter(
(t) => t.taskStatus === "running"
);
let resumedAwaitingReportCount = 0;
let skippedAwaitingReportDueToActiveDescendants = 0;
let failedAwaitingReportCount = 0;
for (const task of awaitingReportTasks) {
if (!task.id) continue;
// Avoid resuming a task while it still has active descendants (it shouldn't report yet).
const hasActiveDescendants = this.hasActiveDescendantAgentTasks(config, task.id);
if (hasActiveDescendants) {
skippedAwaitingReportDueToActiveDescendants += 1;
continue;
}
const resumed = await this.promptTaskForRequiredCompletionTool(task.id, {
reason: "startup",
});
if (!resumed) {
failedAwaitingReportCount += 1;
continue;
}
resumedAwaitingReportCount += 1;
}
let resumedRunningCount = 0;
let skippedRunningDueToActiveDescendants = 0;
let failedRunningCount = 0;
for (const task of runningTasks) {
if (!task.id) continue;
// Best-effort: if mux restarted mid-stream, nudge the agent to continue and report.
// Only do this when the task has no running descendants, to avoid duplicate spawns.
const hasActiveDescendants = this.hasActiveDescendantAgentTasks(config, task.id);
if (hasActiveDescendants) {
skippedRunningDueToActiveDescendants += 1;
continue;
}
const isPlanLike = await this.isPlanLikeTaskWorkspace({
projectPath: task.projectPath,
workspace: task,
});
const model = task.taskModelString ?? defaultModel;
const agentId = task.agentId ?? TASK_RECOVERY_FALLBACK_AGENT_ID;
log.info("[startup] Resuming running task", {
taskId: task.id,
taskName: task.name,
projectPath: task.projectPath,
model,
agentId,
isPlanLike,
});
const resumeStartedAt = Date.now();
const sendResult = await this.workspaceService.sendMessage(
task.id,
isPlanLike
? "Mux restarted while this task was running. Continue where you left off. " +
"When you have a final plan, call propose_plan exactly once."
: "Mux restarted while this task was running. Continue where you left off. " +
"When you have a final answer, call agent_report exactly once.",
{
model,
agentId,
thinkingLevel: task.taskThinkingLevel,
experiments: task.taskExperiments,
},
{ synthetic: true, agentInitiated: true }
);
const durationMs = Date.now() - resumeStartedAt;
if (!sendResult.success) {
failedRunningCount += 1;
log.error("Failed to resume running task on startup", {
taskId: task.id,
taskName: task.name,
projectPath: task.projectPath,
model,
agentId,
isPlanLike,
durationMs,
error: sendResult.error,
});
continue;
}
resumedRunningCount += 1;
log.info("[startup] Resumed running task", {
taskId: task.id,
taskName: task.name,
projectPath: task.projectPath,
model,
agentId,
isPlanLike,
durationMs,
});
}