-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask.ts
More file actions
9177 lines (8332 loc) · 363 KB
/
Copy pathTask.ts
File metadata and controls
9177 lines (8332 loc) · 363 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 path from "path"
import os from "os"
import crypto from "crypto"
import { v7 as uuidv7 } from "uuid"
import EventEmitter from "events"
import { AskIgnoredError } from "./AskIgnoredError.js"
import { startApiRequestTimer, openedApiReqInfo, endedApiReqInfo, type StreamPhaseMarks } from "./api-req-timing.js"
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import debounce from "lodash.debounce"
import delay from "delay"
import pWaitFor from "p-wait-for"
import { serializeError } from "serialize-error"
import { Package } from "../shared/package.js"
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { formatToolInvocation } from "../tools/helpers/toolResultFormatting.js"
import {
type TaskLike,
type TaskMetadata,
type Envelope,
MAILBOX_WAKE_TURN_TEXT,
type TaskEvents,
type ProviderSettings,
type TokenUsage,
type ToolUsage,
type ToolName,
type ContextCondense,
type ContextTruncation,
type ShoferMessage,
type ShoferSay,
type ShoferAsk,
type PluginMarkerPayload,
type ToolProgressStatus,
type HistoryItem,
type CreateTaskOptions,
type TaskState,
type ModelInfo,
type ShoferApiReqCancelReason,
type ShoferApiReqInfo,
type ApiReqError,
type ToolSpan,
type ApiRequestFinishedPayload,
type AskResolvedInfo,
type TraceContext,
type TaskInteractionPayload,
type TaskHandle,
type CostLimit,
type McpToolCallResponse,
ShoferEventName,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
TelemetryEventName,
TaskStatus,
TodoItem,
getApiProtocol,
getModelId,
isRetiredProvider,
isIdleAsk,
isInteractiveAsk,
isResumableAsk,
QueuedMessage,
DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
ConsecutiveMistakeError,
MAX_MCP_TOOLS_THRESHOLD,
countEnabledMcpTools,
} from "@shofer/types"
import { TelemetryService } from "@shofer/telemetry"
// api
import { ApiHandler, ApiHandlerCreateMessageMetadata } from "../api/api-handler-types.js"
import { buildApiHandler } from "../api/index.js"
import { ApiStream, GroundingSource } from "../api/transform/stream.js"
import { maybeRemoveImageBlocks } from "../api/transform/image-cleaning.js"
// shared
import { findLastIndex } from "@shofer/types"
import { combineApiRequests } from "@shofer/types"
import { combineCommandSequences } from "@shofer/types"
import { t } from "../i18n/index.js"
import { getApiMetrics, hasTokenUsageChanged, hasToolUsageChanged } from "@shofer/types"
import { ShoferAskResponse } from "@shofer/types"
import { defaultModeSlug, getModeBySlug, resolveModeConfig } from "@shofer/types"
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { DiffStrategy, type ToolUse, type McpToolUse, type ToolParamName, toolParamNames } from "@shofer/types"
import { getModelMaxOutputTokens } from "@shofer/types"
import type { BackgroundTaskStatus } from "@shofer/types"
// services
import { McpHub } from "../services/mcp/McpHub.js"
import { getMcpHubFactory } from "../services/mcp/mcp-hub-factory.js"
// integrations
import type { DiffView } from "@shofer/types"
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { findToolName } from "./findToolName.js"
import { ShoferTerminalProcess } from "@shofer/types"
import { TerminalRegistry } from "../terminal/TerminalRegistry.js"
import { OutputInterceptor } from "../terminal/OutputInterceptor.js"
// utils
import { calculateApiCostAnthropic, calculateApiCostOpenAI } from "@shofer/types"
import { getWorkspacePath } from "../path/path.js"
import { sanitizeToolUseId } from "../utils/tool-id.js"
import { humanMessageBlock } from "../utils/user-message.js"
import { getTaskDirectoryPath } from "../utils/storage.js"
import { BlobStore, DEFAULT_BLOB_CAP_BYTES } from "../blob-store/BlobStore.js"
import {
MAX_EXPONENTIAL_BACKOFF_SECONDS,
DEFAULT_USAGE_COLLECTION_TIMEOUT_MS,
FORCED_CONTEXT_REDUCTION_PERCENT,
MAX_CONTEXT_WINDOW_RETRIES,
MCP_READY_DEADLINE_MS,
TASK_TOKEN_USAGE_EMIT_INTERVAL_MS,
TASK_SAVE_DEBOUNCE_INTERVAL_MS,
TASK_PARTIAL_APPEND_THROTTLE_MS,
} from "../constants.js"
// prompts
import { formatResponse } from "../prompts/responses.js"
import { SYSTEM_PROMPT } from "../prompts/system.js"
import { buildNativeToolsArrayWithRestrictions } from "./build-tools.js"
import { emitTaskCompleted } from "./emit-task-completed.js"
import { MAX_SUBTASK_RESULT_LENGTH } from "../tools/NewTaskTool.js"
// plugin lifecycle hooks (design §6.9)
import { pluginRegistry } from "../plugins/plugin-registry.js"
// core modules
import { ToolRepetitionDetector } from "../tools/ToolRepetitionDetector.js"
import { restoreTodoListForTask } from "../tools/UpdateTodoListTool.js"
import { FileContextTracker } from "../context-tracking/FileContextTracker.js"
import { ShoferIgnoreController } from "../ignore/ShoferIgnoreController.js"
import { ShoferProtectedController } from "../protect/ShoferProtectedController.js"
import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message/index.js"
import { NativeToolCallParser } from "../assistant-message/NativeToolCallParser.js"
import { manageContext, willManageContext } from "../context-management/index.js"
import { aggregateTaskCostsRecursive } from "../webview/aggregateTaskCosts.js"
import { type TaskProviderLike } from "../task-provider/index.js"
import { MultiSearchReplaceDiffStrategy } from "../diff/strategies/multi-search-replace.js"
import { type ApiMessage } from "../task-persistence/apiMessages.js"
import type { TaskPersistencePort } from "../task-persistence/PersistencePort.js"
import { resolveTaskPersistence } from "../task-persistence/backend.js"
import { taskMetadata } from "../task-persistence/taskMetadata.js"
import { getHost } from "@shofer/types"
import { getEnvironmentDetails } from "../environment/getEnvironmentDetails.js"
import { checkContextWindowExceededError } from "../context/context-management/context-error-handling.js"
import { isNonRetryableApiError } from "../api/providers/utils/retryable-error.js"
import { ApiRetryBudgetExceededError, resolveMaxConsecutiveApiFailures } from "./api-retry-budget.js"
import { processUserContentMentions } from "../mentions/processUserContentMentions.js"
import { getMessagesSinceLastSummary, summarizeConversation, getEffectiveApiHistory } from "../condense/index.js"
import { MessageQueueService } from "../message-queue/MessageQueueService.js"
import { Mailbox } from "../mailbox/Mailbox.js"
import { AutoApprovalHandler } from "../auto-approval/AutoApprovalHandler.js"
import { checkAutoApproval, type CheckAutoApprovalResult } from "../auto-approval/index.js"
import { MessageManager } from "../message-manager/index.js"
import { validateAndFixToolResultIds } from "./validateToolResultIds.js"
import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages.js"
import { taskLog } from "../logging/subsystems.js"
import { runWithLogTaskContext } from "../logging/logContext.js"
import { time } from "../utils/perf.js"
import {
recordLlmDuration,
incLlmCalls,
incLlmErrors,
incLlmCost,
incLlmTokens,
classifyLlmError,
} from "../metrics/registry.js"
// Tunable retry / timeout / context-recovery knobs are centralised in
// `../constants.js`. See MAX_EXPONENTIAL_BACKOFF_SECONDS,
// DEFAULT_USAGE_COLLECTION_TIMEOUT_MS, FORCED_CONTEXT_REDUCTION_PERCENT,
// MAX_CONTEXT_WINDOW_RETRIES, MCP_READY_DEADLINE_MS, and the TASK_* throttle
// intervals there.
export interface TaskOptions extends CreateTaskOptions {
provider: TaskProviderLike<Task>
apiConfiguration: ProviderSettings
consecutiveMistakeLimit?: number
task?: string
images?: string[]
historyItem?: HistoryItem
experiments?: Record<string, boolean>
startTask?: boolean
rootTask?: Task
parentTask?: Task
taskNumber?: number
onCreated?: (task: Task) => void
initialTodos?: TodoItem[]
workspacePath?: string
/**
* Working directory for this task. When set (e.g., for embedded worktree
* tasks), this overrides the default workspacePath as the task's CWD for
* tool invocations, file path resolution, and git operations.
*
* If not set, cwd defaults to workspacePath.
*/
cwd?: string
/** Initial execution state for the task's history item (e.g., for child tasks) */
initialState?: TaskState
}
/**
* Handle for an in-flight async MCP tool call, stored in {@link Task.mcpAsyncCalls}.
* Mirrors {@link TaskHandle} for background children.
*/
export interface McpAsyncCallHandle {
callId: string
serverName: string
toolName: string
status: "running" | "completed" | "error" | "cancelled"
promise: Promise<McpToolCallResponse | undefined>
abortController: AbortController
result?: McpToolCallResponse
error?: string
createdAt: number
}
export class Task extends EventEmitter<TaskEvents> implements TaskLike {
readonly taskId: string
readonly rootTaskId?: string
readonly parentTaskId?: string
childTaskId?: string
pendingNewTaskToolCallId?: string
// NEW: Track background children
backgroundChildren: Map<string, TaskHandle> = new Map()
/**
* Least-privilege peer scope restriction. Peer tools only allow
* communication with task IDs present in this set. The baseline
* always includes the parent (if any) and children this task spawns
* (dynamically added). When undefined, no peer communication is
* allowed at all — every peer-tool access is denied.
*
* Set explicitly by {@link NewTaskTool} at spawn time (baseline: parent
* only) and extended as the task spawns children.
*/
knownPeers?: Set<string>
/**
* Set while this child is parked on a question it FORWARDED to its parent.
*
* A child's `ask_followup_question` is dual-channel: the question is raised
* as an ordinary `followup` ask in the child's own chat AND delivered to the
* parent's mailbox as a `request` envelope. This field is the correlation
* between the two — `envelopeId` names the request in the parent's box,
* `question` is the text — and it exists because three things need it and
* none of them can derive it:
*
* - the parent's `reply` must unpark THIS ask ({@link answerForwardedQuestion});
* - `check_task_status` reports that the child is waiting on an answer;
* - `TaskManager` suppresses the desktop `needs_input` notification, because
* the question has a live agent audience and is not (only) the human's to
* answer.
*
* The blocking itself is `task.ask("followup", …)`, exactly as for a
* user-facing question, so either channel resolves it through
* `handleWebviewAskResponse` and the first answer wins.
*/
private _forwardedQuestion?: { envelopeId: string; question: string }
/**
* In-flight async MCP tool calls (mirrors `backgroundChildren` for MCP calls).
* Each entry tracks a fire-and-forget `McpHub.callTool()` promise plus an
* AbortController. Cleaned up inline in {@link abortTask}.
*/
mcpAsyncCalls: Map<string, McpAsyncCallHandle> = new Map()
/**
* Per-root-task USD budget cap. Stored only on root tasks; subtasks
* resolve the limit by walking up the parentTask chain via
* `resolveCostLimit()`. Unset or maxUsd <= 0 disables enforcement.
*/
costLimit?: CostLimit
/**
* Cached aggregated cost for the current API request, keyed by the
* `shoferMessages` index of the request. Avoids re-scanning history
* on every chunk of a single streaming response.
*/
private _costLimitCheckCache?: { spent: number; requestIndex: number }
/**
* Snapshot of the aggregated cost across the root task's history
* captured at the start of the current API request, BEFORE this
* request's own usage is added. Used by the in-stream check
* (`checkInFlightCostLimit`) to compute live spend as
* `_priorAggregateUsd + thisRequestCostUsd` on every `usage` chunk
* without re-scanning history each time. Reset per request boundary.
*/
private _priorAggregateUsd?: number
/**
* Per-request guard so the in-stream cost check fires its
* abort/pause/kill action AT MOST ONCE for the current API call.
* Without this, multiple `usage` chunks crossing the cap would each
* try to enforce — re-aborting an already-aborting task or stacking
* pause prompts. Reset per request boundary alongside the snapshot.
*/
private _costLimitEnforcementFiredForRequest = false
/**
* Set to `true` when the user has chosen to continue past the cost
* cap for the remainder of this task. Reset only by abort/dispose.
* Implements the "Continue without limit" branch of the pause dialog.
*/
private _costLimitBypassed = false
// Helper to check if child is alive
isBackgroundChildAlive(childId: string): boolean {
if (
this.providerRef.deref() &&
// eslint-disable-next-line @typescript-eslint/no-explicit-any
typeof (this.providerRef.deref() as any).getManagedTaskInstance === "function"
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.providerRef.deref() as any).getManagedTaskInstance(childId) !== undefined
}
return false
}
// Cleanup dead children on parent resume/load
async cleanupBackgroundChildren(): Promise<void> {
for (const [childId, handle] of this.backgroundChildren) {
if (!this.isBackgroundChildAlive(childId)) {
try {
// Use TaskManager.getTaskState() (in-memory, set synchronously
// by lifecycle events) rather than the persisted HistoryItem
// snapshot which can lag behind due to the async persistState
// fire-and-forget write.
const provider = this.providerRef.deref()
if (provider) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const taskState = (provider as any).taskManager?.getTaskState(childId)
handle.status = taskState?.lifecycle === "completed" ? "completed" : "error"
}
} catch (_) {
handle.status = "error"
}
}
}
}
/**
* Rebuild the in-memory {@link backgroundChildren} map from persisted history
* after a process restart.
*
* `backgroundChildren` is a runtime-only `Map` populated by `NewTaskTool` when
* spawning background subtasks. It is never serialized. After a VS Code /
* code-server restart, a resumed parent task starts with an empty map, so
* `check_task_status` and `cancel_tasks` — both of which gate on
* `task.backgroundChildren.get(task_id)` — reject the parent's own children
* with "Task not found in background children or peers" even though
* `list_background_tasks` (which has a persisted-history fallback) still
* shows them. This method closes that gap by repopulating the map from the
* persisted `HistoryItem` rows that carry `isBackground && parentTaskId ===
* this.taskId`.
*
* Status resolution mirrors {@link cleanupBackgroundChildren}: the live
* `TaskManager.getTaskState()` wins (set synchronously by lifecycle events);
* otherwise the persisted `HistoryItem.taskState.lifecycle` is used. Children
* whose persisted lifecycle was transient (`running`, `waiting`,
* `waiting_input`) are mapped to `idle`-equivalent handle statuses so the
* tools treat them as resumable rather than terminal.
*
* Idempotent: existing live handles are preserved (a live handle always
* reflects more-current state than the persisted snapshot).
*/
async rehydrateBackgroundChildren(): Promise<void> {
const provider = this.providerRef.deref()
if (!provider) return
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const taskHistoryStore = (provider as any).taskHistoryStore as { getAll?: () => any[] } | undefined
if (!taskHistoryStore || typeof taskHistoryStore.getAll !== "function") return
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let historyItems: any[]
try {
historyItems = taskHistoryStore.getAll() ?? []
} catch {
return
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const taskManager = (provider as any).taskManager as { getTaskState?: (id: string) => any } | undefined
for (const item of historyItems) {
// Only persisted background children of THIS task belong in the map.
if (!item || !item.isBackground) continue
if (item.parentTaskId !== this.taskId) continue
const childId: string = item.id
// Preserve any live handle already present — it is more current.
if (this.backgroundChildren.has(childId)) continue
// Resolve the most authoritative status available post-restart.
let status: BackgroundTaskStatus
const liveState = taskManager?.getTaskState?.(childId)
const lifecycle = liveState?.lifecycle ?? item.taskState?.lifecycle
switch (lifecycle) {
case "completed":
status = "completed"
break
case "error":
status = "error"
break
// Transient lifetimes do not survive a restart (sanitizeRestoredState
// downgrades them to `idle`). Map them to the resumable handle status
// so the parent can wait on / re-inspect them rather than treating
// them as gone.
case "running":
case "waiting":
case "waiting_input":
case "idle":
case "paused":
status = "running"
break
default:
status = "running"
}
this.backgroundChildren.set(childId, {
taskId: childId,
status,
createdAt: item.createdAt ?? item.ts ?? Date.now(),
parentTaskId: this.taskId,
})
}
}
readonly instanceId: string
readonly metadata: TaskMetadata
todoList?: TodoItem[]
/**
* Per-task snapshot of the pending todo list approval. Used by
* UpdateTodoListTool to detect user edits made in the webview
* between the tool's ask and the approval response.
*
* Replaces the former module-level `approvedTodoList` global
* that leaked between concurrent Task instances.
*/
pendingTodoApproval?: TodoItem[]
readonly rootTask: Task | undefined = undefined
readonly parentTask: Task | undefined = undefined
readonly taskNumber: number
readonly workspacePath: string
/** Outside-workspace dirs the user trusted for THIS task (+ subtasks) via the
* inline "Trust path" button. In-memory only; the persistent equivalent is
* allowedReadPaths/allowedWritePaths. */
readonly trustedReadPaths: string[]
readonly trustedWritePaths: string[]
/**
* Maximum characters the parent will accept as the completion result.
* Set by {@link NewTaskTool} via {@link CreateTaskOptions.softResultLength} when a parent
* spawns a child task. The child's {@link attempt_completion} tool enforces this.
* If undefined, no result length constraint applies (top-level tasks).
*/
softResultLength?: number
/**
* Soft guidance (in seconds) for how long the parent expects to wait.
* Set by {@link NewTaskTool} via {@link CreateTaskOptions.softTimeoutSec}.
* Not a hard deadline — informational only. If undefined, no time guidance applies.
*/
softTimeoutSec?: number
/**
* When true, this task's display title was assigned by its spawning parent
* (via {@link NewTaskTool}'s `title` parameter / {@link CreateTaskOptions.initialTitle})
* and is locked: the {@link SetTaskTitleTool} refuses to overwrite it. Seeded
* at construction from `initialTitle` for fresh tasks, or rehydrated from
* {@link HistoryItem.nameLocked} on restore so the lock survives restarts.
*/
nameLocked = false
/**
* The locked title value, persisted as `HistoryItem.name` on every metadata
* write while {@link nameLocked} is true. Undefined when the title is not
* parent-locked (the task's `name` is then owned by `set_task_title` / the
* auto-generated default).
*/
private lockedTitle?: string
/**
* Per-task JSON Schema override for the `attempt_completion` tool's
* `result` parameter. When set, the generic `result: string` schema is
* replaced with a structured object schema so providers with constrained
* decoding enforce an output contract at decode time.
*
* contract. When undefined, the default `result: string` schema applies.
*/
completionSchema?: Record<string, unknown>
/**
* Optional persona/role injected into this task's system prompt. Layered on
* top of the mode's
* roleDefinition for this task only; see {@link CreateTaskOptions.agentRole}.
*/
agentRole?: string
/**
* The W3C trace context of the work this task was created on behalf of, when
* its creator supplied one ({@link CreateTaskOptions.trace}).
*
* Core stores it and hands it to `beforeTaskStart` observers; it never parses
* it and never acts on it. Keeping it on the task rather than passing it
* straight through is what lets a plugin registered AFTER creation still
* learn where the run came from.
*/
readonly trace?: TraceContext
/**
* Per-task tool-group allow-list (a caller passes the declared
* `tools:` here). Intersected with the mode's groups when building the
* tool array; see {@link CreateTaskOptions.agentToolGroups}. A restriction
* only — never grants tools beyond the mode.
*/
agentToolGroups?: string[]
/**
* Per-task overrides for system-prompt components; see
* {@link CreateTaskOptions.agentContext}.
* Each key is a boolean toggle for a specific component. Absent keys
* inherit the global default.
*
* Supported keys: `include_agents_md`, `include_subfolder_rules`,
* `include_mode_rules`, `include_user_rules`, `include_skills`,
* `require_todos`, `include_system_info`, `include_mcp`.
*/
agentContext?: Record<string, boolean>
/**
* The mode associated with this task. Persisted across sessions
* to maintain user context when reopening tasks from history.
*
* ## Lifecycle
*
* ### For new tasks:
* 1. Initially `undefined` during construction
* 2. Asynchronously initialized from provider state via `initializeTaskMode()`
* 3. Falls back to `defaultModeSlug` if provider state is unavailable
*
* ### For history items:
* 1. Immediately set from `historyItem.mode` during construction
* 2. Falls back to `defaultModeSlug` if mode is not stored in history
*
* ## Important
* This property should NOT be accessed directly until `taskModeReady` promise resolves.
* Use `getTaskMode()` for async access or `taskMode` getter for sync access after initialization.
*
* @private
* @see {@link getTaskMode} - For safe async access
* @see {@link taskMode} - For sync access after initialization
* @see {@link waitForModeInitialization} - To ensure initialization is complete
*/
private _taskMode: string | undefined
/**
* Promise that resolves when the task mode has been initialized.
* This ensures async mode initialization completes before the task is used.
*
* ## Purpose
* - Prevents race conditions when accessing task mode
* - Ensures provider state is properly loaded before mode-dependent operations
* - Provides a synchronization point for async initialization
*
* ## Resolution timing
* - For history items: Resolves immediately (sync initialization)
* - For new tasks: Resolves after provider state is fetched (async initialization)
*
* @private
* @see {@link waitForModeInitialization} - Public method to await this promise
*/
private taskModeReady: Promise<void>
/**
* The API configuration name (provider profile) associated with this task.
* Persisted across sessions to maintain the provider profile when reopening tasks from history.
*
* ## Lifecycle
*
* ### For new tasks:
* 1. Initially `undefined` during construction
* 2. Asynchronously initialized from provider state via `initializeTaskApiConfigName()`
* 3. Falls back to "default" if provider state is unavailable
*
* ### For history items:
* 1. Immediately set from `historyItem.apiConfigName` during construction
* 2. Falls back to undefined if not stored in history (for backward compatibility)
*
* ## Important
* If you need a non-`undefined` provider profile (e.g., for profile-dependent operations),
* wait for `taskApiConfigReady` first (or use `getTaskApiConfigName()`).
* The sync `taskApiConfigName` getter may return `undefined` for backward compatibility.
*
* @private
* @see {@link getTaskApiConfigName} - For safe async access
* @see {@link taskApiConfigName} - For sync access after initialization
*/
private _taskApiConfigName: string | undefined
/**
* Promise that resolves when the task API config name has been initialized.
* This ensures async API config name initialization completes before the task is used.
*
* ## Purpose
* - Prevents race conditions when accessing task API config name
* - Ensures provider state is properly loaded before profile-dependent operations
* - Provides a synchronization point for async initialization
*
* ## Resolution timing
* - For history items: Resolves immediately (sync initialization)
* - For new tasks: Resolves after provider state is fetched (async initialization)
*
* @private
*/
private taskApiConfigReady: Promise<void>
providerRef: WeakRef<TaskProviderLike<Task>>
private readonly globalStoragePath: string
abort: boolean = false
/**
* Tracks the currently running initiateTaskLoop Promise.
* Used by cancelAndProcessQueuedMessages to wait for the old task loop
* to fully exit before starting a new one, preventing race conditions
* that cause duplicate messages and orphaned tool_use blocks.
*/
private _taskLoopPromise: Promise<void> | undefined = undefined
currentRequestAbortController?: AbortController
/**
* Task-lifetime AbortController. Aborted whenever the task is cancelled
* (Stop button -> abortTask) or its current run is interrupted to drain
* queued messages (Send Now -> cancelAndProcessQueuedMessages). Long-running
* in-task operations (MCP tool calls, HTTP fetches initiated by tools, etc.)
* subscribe to `abortSignal` so they can bail immediately instead of waiting
* for their own per-operation timeout.
*
* For Send Now we replace the controller before restarting the loop so the
* fresh run does not see an already-aborted signal.
*/
private _taskAbortController: AbortController = new AbortController()
public get abortSignal(): AbortSignal {
return this._taskAbortController.signal
}
skipPrevResponseIdOnce: boolean = false
// TaskStatus
idleAsk?: ShoferMessage
resumableAsk?: ShoferMessage
interactiveAsk?: ShoferMessage
didFinishAbortingStream = false
abandoned = false
abortReason?: ShoferApiReqCancelReason
isInitialized = false
isPaused: boolean = false
/**
* Soft-cancel marker for the "Send Now" flow.
*
* When the user clicks Send Now while the task is mid-stream, we want to
* interrupt the current API request and immediately restart the loop with
* the queued message — WITHOUT tearing down the task. The default abort
* path (recursivelyMakeShoferRequests catch block) calls `abortTask()` on
* `this.abort === true`, which calls `dispose()`, which wipes the message
* queue, removes the queue listener, and releases terminals. That would
* silently delete the very message we are trying to send and leave the
* webview with an orphan UI entry that cannot be dismissed.
*
* When this flag is set, callers that would otherwise fully abort the
* task on `this.abort === true` should instead unwind cleanly so
* `cancelAndProcessQueuedMessages()` can restart the loop.
*/
private _softCancelForQueuedMessage = false
// API
apiConfiguration: ProviderSettings
api: ApiHandler
private static lastGlobalApiRequestTime?: number
private autoApprovalHandler: AutoApprovalHandler
/**
* Reset the global API request timestamp. This should only be used for testing.
* @internal
*/
static resetGlobalApiRequestTime(): void {
Task.lastGlobalApiRequestTime = undefined
}
toolRepetitionDetector: ToolRepetitionDetector
shoferIgnoreController?: ShoferIgnoreController
shoferProtectedController?: ShoferProtectedController
// ===== Task Visualization — Timeline =====
/**
* Monotonic origin for all per-task timing. Set once at construction
* via `performance.now()` so every span offset is relative to the
* same starting point regardless of when the task's history was
* written.
*/
timelineOriginMs!: number
/**
* Tool spans accumulated during the current API request. Drained
* into `api_req_finished.toolSpans[]` at stream end and reset for
* each new request.
*/
_pendingToolSpans: ToolSpan[] = []
/**
* Offset from `timelineOriginMs` when the current API request was
* initiated (just before the streaming call).
*/
_pendingRequestStartOffset = 0
/**
* TTFB for the current API request in ms, or `null` when not yet
* available.
*/
_pendingTtfbMs: number | null = null
/**
* Offset (ms from request start) at which output generation began — the
* first non-reasoning chunk (text or tool call). The window between
* `_pendingTtfbMs` and this is the model's reasoning/"thinking" phase.
* `null` until the first non-reasoning chunk arrives.
*/
_pendingGenStartMs: number | null = null
/**
* Reasoning intervals CLOSED so far in the current request — every
* reasoning run the stream terminated with a non-reasoning chunk, as
* `[start, end]` offsets from the request's open.
*
* `_pendingGenStartMs` above records only the FIRST such boundary, which is
* all the `api_req_finished` span publishes; a model that interleaves
* thinking with output has more, and this is where they are kept.
*/
_pendingReasoningIntervals: Array<[number, number]> = []
/**
* Offset at which the currently-open reasoning run began, or `null` when
* the stream is not reasoning. A run still open at stream end is closed
* there by `streamPhaseFields`.
*/
_pendingReasoningOpenedAtMs: number | null = null
/**
* True while an API request is in flight and its `api_req_finished` span has
* not yet been emitted. Guards `emitApiReqFinished` against double-emit and
* lets `abortTask` flush the final request (e.g. the attempt_completion turn,
* which disposes the task before the normal post-tools emit point).
*/
_pendingApiReqNeedsEmit = false
/**
* 0-based monotonic index assigned to each API request span within
* this task.
*/
_currentRequestIndex = 0
fileContextTracker: FileContextTracker
terminalProcess?: ShoferTerminalProcess
/**
* Backgrounded command processes — an execute_command the agent moved on from
* (agent timeout, or the user chose "Proceed While Running") while it is still
* running. The foreground `terminalProcess` reference is cleared once the tool
* returns, so without this map a backgrounded command could no longer be
* terminated by the Stop button or the per-command Kill button. Keyed by
* executionId; entries are removed when the command actually completes.
*/
backgroundTerminalProcesses = new Map<string, ShoferTerminalProcess>()
// Editing
diffViewProvider: DiffView
diffStrategy?: DiffStrategy
didEditFile: boolean = false
// LLM Messages & Chat Messages
apiConversationHistory: ApiMessage[] = []
shoferMessages: ShoferMessage[] = []
/**
* Promise that resolves when `shoferMessages` has been populated.
*
* For history-resume tasks, resolves after `resumeTaskFromHistory()` loads
* messages from disk. For new tasks, resolves after `startTask()` posts the
* first user message. For non-started tasks (`startTask: false`), resolves
* immediately.
*
* Used by `createTaskWithHistoryItem` to defer `postInitState` until
* messages are available, preventing the home-screen flash when switching
* focus to a history task before its messages have loaded.
*/
messagesReady: Promise<void>
private _messagesReadyResolve!: () => void
/**
* True once `shoferMessages` and `apiConversationHistory` have been loaded
* from disk and sanitized. Set by either `preloadShoferMessages()` (called
* explicitly by `createTaskWithHistoryItem` BEFORE the task is published as
* `getCurrentTask()`) or by `resumeTaskFromHistory()` on its own.
*
* Used by `resumeTaskFromHistory()` to skip the load+sanitize prefix when
* the messages were already preloaded, avoiding redundant disk I/O and
* guaranteeing the same array is observed by both code paths.
*/
private historyPreloaded: boolean = false
/** Read-only accessor for diagnostics (see ShoferProvider home-screen-flash log). */
public get isHistoryPreloaded(): boolean {
return this.historyPreloaded
}
// Ask
private askResponse?: ShoferAskResponse
private askResponseText?: string
private askResponseImages?: string[]
public lastMessageTs?: number
/**
* UUID v7 identifying the currently-outstanding ask. Set when a
* complete (non-partial) ask enters the pWaitFor loop; cleared when
* the ask is resolved, superseded, or the task is disposed. A
* new ask() call that generates its own askId implicitly supersedes
* the previous one (no separate invalidation needed).
*
* Replaces the former `lastMessageTs` timestamp for ask identity so
* that unrelated code paths (say(), supersedePendingAsk()) can no
* longer invalidate an in-flight ask by bumping a global mutable field.
*/
private _currentAskId?: string
private autoApprovalTimeoutRef?: NodeJS.Timeout
// True while ask() is actively waiting for a response from the user/webview.
// Used by handleWebviewAskResponse() to detect stray messageResponse arrivals
// (e.g. user typing during a tool execution window when no ask is pending) and
// route them to the message queue instead of silently overwriting unread
// askResponse* slots that the next ask() call would clear.
private isAwaitingAskResponse: boolean = false
// Experiments
experimentsConfig?: Record<string, boolean>
// Tool Use
consecutiveMistakeCount: number = 0
consecutiveMistakeLimit: number
consecutiveMistakeCountForApplyDiff: Map<string, number> = new Map()
consecutiveMistakeCountForEditFile: Map<string, number> = new Map()
consecutiveNoToolUseCount: number = 0
consecutiveNoAssistantMessagesCount: number = 0
toolUsage: ToolUsage = {}
// Skill tracking — maps skill name to SKILL.md absolute path
loadedSkills: Map<string, string> = new Map()
// H15: Per-turn system prompt cache.
// The assembled prompt (base + subtask-constraints) is stable across
// round-trips within a turn; peer notifications are appended fresh.
// Cleared at turn start (initiateTaskLoop) and on context-management
// (condenseContext / handleContextWindowExceededError).
_cachedSystemPromptBase: string | null = null
_cachedSystemPromptKey: string = ""
// H16: Per-request tool-array cache.
// buildNativeToolsArrayWithRestrictions is called up to 3× per
// attemptApiRequest (context management, actual call, + Gemini
// variant). Compute once and reuse within the request scope.
_cachedToolsResult: {
tools: import("openai").default.Chat.ChatCompletionTool[]
allowedFunctionNames?: string[]
} | null = null
_cachedToolsKey: string = ""
// H15: Snapshot of the MCP server-set ID captured when the system prompt
// is built on a cache miss. Folded into the cache key so a server that
// finishes connecting mid-turn invalidates the stale prompt.
_mcpServerSetId: string = ""
// Message Queue Service
public readonly messageQueueService: MessageQueueService
private messageQueueStateChangedHandler: (() => void) | undefined
/**
* This task's mailbox — the single destination for messages from peers, the
* bus, the A2A mesh and Temporal owners. Owned exactly like
* {@link messageQueueService}, and deliberately separate from it: a human
* message is a TURN, an envelope is MAIL.
*/
public readonly mailbox: Mailbox
/**
* Settles when the mailbox has been hydrated from disk.
*
* The constructor is synchronous, so the load is kicked off there and awaited
* by anything that must see persisted mail (the environment-details digest,
* a provider delivering into a task it just rehydrated). A delivery does not
* need to await it: `deliver` re-reads nothing and the load only ADDS what
* was already durable.
*/
public readonly mailboxReady: Promise<void>
// Streaming
isWaitingForFirstChunk = false
isStreaming = false
/**
* CONSECUTIVE failed model API requests — the counter behind the retry bound
* (`api-retry-budget.ts`). Incremented wherever the loop is about to retry
* automatically, and reset to 0 the moment a request completes successfully,
* so a blip mid-task costs nothing and only a condition that is not clearing
* up can reach the ceiling.
*/
private consecutiveApiFailures = 0
currentStreamingContentIndex = 0
/**
* Assistant turns this task has run — incremented once per API request. Surfaced to
* plugins as `PluginContext.turn` so a hook that fires per *tool call* (a turn can
* issue several) can act once per turn without guessing where turn boundaries are.
*/
turnCount = 0
assistantMessageContent: AssistantMessageContent[] = []
presentAssistantMessageLocked = false
presentAssistantMessageHasPendingUpdates = false
userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolResultBlockParam)[] = []
userMessageContentReady = false
/**
* Flag indicating whether the assistant message for the current streaming session
* has been saved to API conversation history.
*
* This is critical for parallel tool calling: tools should NOT execute until
* the assistant message is saved. Otherwise, if a tool like `new_task` triggers
* `flushPendingToolResultsToHistory()`, the user message with tool_results would
* appear BEFORE the assistant message with tool_uses, causing API errors.
*
* Reset to `false` at the start of each API request.
* Set to `true` after the assistant message is saved in `recursivelyMakeShoferRequests`.
*/
assistantMessageSavedToHistory = false
/** True when TaskStarted has been emitted for the current run. Reset on each initiateTaskLoop. */
taskStartedEmitted = false
/**
* Push a tool_result block to userMessageContent, preventing duplicates.
* Duplicate tool_use_ids cause API errors.
*
* @param toolResult - The tool_result block to add
* @returns true if added, false if duplicate was skipped
*/
public pushToolResultToUserContent(toolResult: Anthropic.ToolResultBlockParam): boolean {
const existingResult = this.userMessageContent.find(
(block): block is Anthropic.ToolResultBlockParam =>
block.type === "tool_result" && block.tool_use_id === toolResult.tool_use_id,
)
if (existingResult) {
taskLog.warn(
`[Task#pushToolResultToUserContent] Skipping duplicate tool_result for tool_use_id: ${toolResult.tool_use_id}`,
)
return false
}
this.userMessageContent.push(toolResult)
return true
}
didRejectTool = false
didAlreadyUseTool = false
didToolFailInCurrentTurn = false
didExecuteAttemptCompletion = false
/**
* True once this instance reached its OWN terminal state and emitted
* `TaskCompleted` — set by `emitTaskCompleted`, so it covers every
* completion shape (`attempt_completion` and the conversational turn of a
* `toolCallingEnabled === false` task alike).
*
* It exists because a completed instance is still torn down later — a
* follow-up message rehydrates the task, and rehydration aborts the old
* instance. That abort is CLEANUP, not an abort, and `abortTask` must not
* announce it as one: a controller watching the event stream treats any
* `TaskAborted` as the turn's terminal event.
*/
completedTerminalState = false
didCompleteReadingStream = false
private _started = false
// No streaming parser is required.
assistantMessageParser?: undefined
private providerProfileChangeListener?: (config: { name: string; provider?: string }) => void
// Native tool call streaming state (track which index each tool is at)
private streamingToolCallIndices: Map<string, number> = new Map()