-
-
Notifications
You must be signed in to change notification settings - Fork 80.9k
Expand file tree
/
Copy pathattempt.ts
More file actions
4946 lines (4811 loc) · 197 KB
/
Copy pathattempt.ts
File metadata and controls
4946 lines (4811 loc) · 197 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 fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { AssistantMessage } from "@earendil-works/pi-ai";
import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent";
import { isAcpRuntimeSpawnAvailable } from "../../../acp/runtime/availability.js";
import { buildHierarchyReinforcementMessage } from "../../../auto-reply/handoff-summarizer.js";
import { filterHeartbeatTranscriptArtifacts } from "../../../auto-reply/heartbeat-filter.js";
import { stripInboundMetadata } from "../../../auto-reply/reply/strip-inbound-meta.js";
import { getRuntimeConfig } from "../../../config/config.js";
import { resolveStorePath } from "../../../config/sessions/paths.js";
import {
loadSessionStore,
runQuotaSuspensionMaintenance,
updateSessionStoreEntry,
} from "../../../config/sessions/store.js";
import {
bindOwnedSessionTranscriptWrites,
withOwnedSessionTranscriptWrites,
} from "../../../config/sessions/transcript-write-context.js";
import { resolveContextEngineOwnerPluginId } from "../../../context-engine/registry.js";
import type { AssembleResult } from "../../../context-engine/types.js";
import { emitTrustedDiagnosticEvent } from "../../../infra/diagnostic-events.js";
import {
createChildDiagnosticTraceContext,
createDiagnosticTraceContextFromActiveScope,
freezeDiagnosticTraceContext,
} from "../../../infra/diagnostic-trace-context.js";
import { isEmbeddedMode } from "../../../infra/embedded-mode.js";
import { formatErrorMessage } from "../../../infra/errors.js";
import { resolveHeartbeatSummaryForAgent } from "../../../infra/heartbeat-summary.js";
import { getMachineDisplayName } from "../../../infra/machine-name.js";
import { MAX_IMAGE_BYTES } from "../../../media/constants.js";
import { listRegisteredPluginAgentPromptGuidance } from "../../../plugins/command-registry-state.js";
import { getCurrentPluginMetadataSnapshot } from "../../../plugins/current-plugin-metadata-snapshot.js";
import { buildAgentHookContextChannelFields } from "../../../plugins/hook-agent-context.js";
import { resolveBlockMessage } from "../../../plugins/hook-decision-types.js";
import { getGlobalHookRunner } from "../../../plugins/hook-runner-global.js";
import {
extractModelCompat,
resolveToolCallArgumentsEncoding,
} from "../../../plugins/provider-model-compat.js";
import {
resolveProviderSystemPromptContribution,
resolveProviderTextTransforms,
transformProviderSystemPrompt,
} from "../../../plugins/provider-runtime.js";
import { getPluginToolMeta } from "../../../plugins/tools.js";
import { isAcpSessionKey, isSubagentSessionKey } from "../../../routing/session-key.js";
import { annotateInterSessionPromptText } from "../../../sessions/input-provenance.js";
import { normalizeOptionalString } from "../../../shared/string-coerce.js";
import {
buildTrajectoryArtifacts,
buildTrajectoryRunMetadata,
} from "../../../trajectory/metadata.js";
import {
createTrajectoryRuntimeRecorder,
toTrajectoryToolDefinitions,
} from "../../../trajectory/runtime.js";
import { resolveUserPath } from "../../../utils.js";
import { normalizeMessageChannel } from "../../../utils/message-channel.js";
import { isReasoningTagProvider } from "../../../utils/provider-utils.js";
import { resolveAgentDir, resolveSessionAgentIds } from "../../agent-scope.js";
import { createAnthropicPayloadLogger } from "../../anthropic-payload-log.js";
import { listActiveProcessSessionReferences } from "../../bash-process-references.js";
import {
analyzeBootstrapBudget,
buildBootstrapPromptWarning,
buildBootstrapPromptWarningNotice,
buildBootstrapTruncationReportMeta,
buildBootstrapInjectionStats,
} from "../../bootstrap-budget.js";
import {
FULL_BOOTSTRAP_COMPLETED_CUSTOM_TYPE,
buildBootstrapContextForFiles,
hasCompletedBootstrapTurn,
isWorkspaceBootstrapPending,
makeBootstrapWarn,
resolveBootstrapFilesForRun,
resolveContextInjectionMode,
} from "../../bootstrap-files.js";
import { createCacheTrace } from "../../cache-trace.js";
import {
listChannelSupportedActions,
resolveChannelMessageToolHints,
resolveChannelReactionGuidance,
} from "../../channel-tools.js";
import {
addClientToolsToCodeModeCatalog,
applyCodeModeCatalog,
CODE_MODE_EXEC_TOOL_NAME,
CODE_MODE_WAIT_TOOL_NAME,
createCodeModeTools,
resolveCodeModeConfig,
} from "../../code-mode.js";
import { DEFAULT_CONTEXT_TOKENS } from "../../defaults.js";
import { resolveOpenClawReferencePaths } from "../../docs-path.js";
import { isTimeoutError } from "../../failover-error.js";
import { resolveHeartbeatPromptForSystemPrompt } from "../../heartbeat-system-prompt.js";
import { resolveImageSanitizationLimits } from "../../image-sanitization.js";
import { stripHistoricalRuntimeContextCustomMessages } from "../../internal-runtime-context.js";
import { filterLocalModelLeanTools, isLocalModelLeanEnabled } from "../../local-model-lean.js";
import { resolveModelAuthMode } from "../../model-auth.js";
import { resolveDefaultModelForAgent } from "../../model-selection.js";
import { supportsModelTools } from "../../model-tool-support.js";
import { createBundleLspToolRuntime } from "../../pi-bundle-lsp-runtime.js";
import {
getOrCreateSessionMcpRuntime,
materializeBundleMcpToolsForRun,
} from "../../pi-bundle-mcp-tools.js";
import type { EmbeddedContextFile } from "../../pi-embedded-helpers.js";
import {
downgradeOpenAIFunctionCallReasoningPairs,
downgradeOpenAIReasoningBlocks,
isCloudCodeAssistFormatError,
resolveBootstrapMaxChars,
resolveBootstrapPromptTruncationWarningMode,
resolveBootstrapTotalMaxChars,
} from "../../pi-embedded-helpers.js";
import { countActiveToolExecutions } from "../../pi-embedded-subscribe.handlers.tools.js";
import { subscribeEmbeddedPiSession } from "../../pi-embedded-subscribe.js";
import { createPreparedEmbeddedPiSettingsManager } from "../../pi-project-settings.js";
import {
applyPiAutoCompactionGuard,
applyPiCompactionSettingsFromConfig,
isSilentOverflowProneModel,
resolveEffectiveCompactionMode,
} from "../../pi-settings.js";
import {
createClientToolNameConflictError,
findClientToolNameConflicts,
toClientToolDefinitions,
} from "../../pi-tool-definition-adapter.js";
import {
createOpenClawCodingTools,
resolveProcessToolScopeKey,
resolveToolLoopDetectionConfig,
} from "../../pi-tools.js";
import {
resolveEffectiveToolPolicy,
resolveGroupToolPolicy,
resolveInheritedToolPolicyForSession,
resolveSubagentToolPolicyForSession,
} from "../../pi-tools.policy.js";
import { wrapStreamFnTextTransforms } from "../../plugin-text-transforms.js";
import { resolveAgentPromptSurfaceForSessionKey } from "../../prompt-surface.js";
import { describeProviderRequestRoutingSummary } from "../../provider-attribution.js";
import { registerProviderStreamForModel } from "../../provider-stream.js";
import { runAgentCleanupStep } from "../../run-cleanup-timeout.js";
import { collectRuntimeChannelCapabilities } from "../../runtime-capabilities.js";
import {
logAgentRuntimeToolDiagnostics,
normalizeAgentRuntimeTools,
} from "../../runtime-plan/tools.js";
import { resolveSandboxContext } from "../../sandbox.js";
import { resolveSandboxRuntimeStatus } from "../../sandbox/runtime-status.js";
import { repairSessionFileIfNeeded } from "../../session-file-repair.js";
import { guardSessionManager } from "../../session-tool-result-guard-wrapper.js";
import {
sanitizeToolUseResultPairing,
stripToolResultDetails,
} from "../../session-transcript-repair.js";
import {
acquireSessionWriteLock,
resolveSessionLockMaxHoldFromTimeout,
resolveSessionWriteLockOptions,
} from "../../session-write-lock.js";
import { detectRuntimeShell } from "../../shell-utils.js";
import {
applySkillEnvOverrides,
applySkillEnvOverridesFromSnapshot,
resolveSkillsPromptForRun,
} from "../../skills.js";
import { buildActiveSubagentSystemPromptAddition } from "../../subagent-active-context.js";
import {
isSubagentEnvelopeSession,
resolveSubagentCapabilityStore,
} from "../../subagent-capabilities.js";
import { resolveSystemPromptOverride } from "../../system-prompt-override.js";
import { buildSystemPromptParams } from "../../system-prompt-params.js";
import { buildSystemPromptReport } from "../../system-prompt-report.js";
import { appendModelIdentitySystemPrompt } from "../../system-prompt.js";
import { resolveAgentTimeoutMs } from "../../timeout.js";
import {
buildEmptyExplicitToolAllowlistError,
collectExplicitToolAllowlistSources,
} from "../../tool-allowlist-guard.js";
import { UNKNOWN_TOOL_THRESHOLD } from "../../tool-loop-detection.js";
import { normalizeToolName } from "../../tool-policy.js";
import {
addClientToolsToToolSearchCatalog,
applyToolSearchCatalog,
clearToolSearchCatalog,
createToolSearchCatalogRef,
projectToolSearchTargetTranscriptMessages,
resolveToolSearchConfig,
TOOL_CALL_RAW_TOOL_NAME,
TOOL_DESCRIBE_RAW_TOOL_NAME,
TOOL_SEARCH_CODE_MODE_TOOL_NAME,
TOOL_SEARCH_RAW_TOOL_NAME,
type ToolSearchCatalogRef,
type ToolSearchCatalogToolExecutor,
type ToolSearchTargetTranscriptProjection,
} from "../../tool-search.js";
import { shouldAllowProviderOwnedThinkingReplay } from "../../transcript-policy.js";
import { normalizeUsage, type NormalizedUsage } from "../../usage.js";
import { DEFAULT_BOOTSTRAP_FILENAME, type WorkspaceBootstrapFile } from "../../workspace.js";
import { isRunnerAbortError } from "../abort.js";
import { isCacheTtlEligibleProvider, readLastCacheTtlTimestamp } from "../cache-ttl.js";
import { resolveCompactionTimeoutMs } from "../compaction-safety-timeout.js";
import { runContextEngineMaintenance } from "../context-engine-maintenance.js";
import { applyFinalEffectiveToolPolicy } from "../effective-tool-policy.js";
import { buildEmbeddedExtensionFactories } from "../extensions.js";
import {
applyExtraParamsToAgent,
resolveAgentTransportOverride,
resolveExplicitSettingsTransport,
resolveExtraParams,
resolvePreparedExtraParams,
} from "../extra-params.js";
import { prepareGooglePromptCacheStreamFn } from "../google-prompt-cache.js";
import { getHistoryLimitFromSessionKey, limitHistoryTurns } from "../history.js";
import { log } from "../logger.js";
import { buildEmbeddedMessageActionDiscoveryInput } from "../message-action-discovery-input.js";
import { createCodexNativeWebSearchWrapper } from "../openai-stream-wrappers.js";
import {
collectPromptCacheToolNames,
beginPromptCacheObservation,
completePromptCacheObservation,
type PromptCacheBreak,
type PromptCacheChange,
} from "../prompt-cache-observability.js";
import { resolveCacheRetention } from "../prompt-cache-retention.js";
import {
normalizeAssistantReplayContent,
sanitizeSessionHistory,
validateReplayTurns,
} from "../replay-history.js";
import { observeReplayMetadata, replayMetadataFromState } from "../replay-state.js";
import { createEmbeddedPiResourceLoader } from "../resource-loader.js";
import {
clearActiveEmbeddedRun,
type EmbeddedPiQueueHandle,
setActiveEmbeddedRun,
updateActiveEmbeddedRunSnapshot,
} from "../runs.js";
import { buildEmbeddedSandboxInfo } from "../sandbox-info.js";
import { prewarmSessionFile, trackSessionManagerAccess } from "../session-manager-cache.js";
import { prepareSessionManagerForRun } from "../session-manager-init.js";
import { resolveEmbeddedRunSkillEntries } from "../skills-runtime.js";
import {
describeEmbeddedAgentStreamStrategy,
resetEmbeddedAgentBaseStreamFnCacheForTest,
resolveEmbeddedAgentApiKey,
resolveEmbeddedAgentBaseStreamFn,
resolveEmbeddedAgentStreamFn,
} from "../stream-resolution.js";
import { applySystemPromptOverrideToSession } from "../system-prompt.js";
import { dropReasoningFromHistory, dropThinkingBlocks } from "../thinking.js";
import {
collectAllowedToolNames,
collectCoreBuiltinToolNames,
collectRegisteredToolNames,
PI_RESERVED_TOOL_NAMES,
toSessionToolAllowlist,
} from "../tool-name-allowlist.js";
import {
installContextEngineLoopHook,
installToolResultContextGuard,
} from "../tool-result-context-guard.js";
import {
resolveLiveToolResultMaxChars,
truncateOversizedToolResultsInSessionManager,
} from "../tool-result-truncation.js";
import { splitSdkTools } from "../tool-split.js";
import { mapThinkingLevel } from "../utils.js";
import { flushPendingToolResultsAfterIdle } from "../wait-for-idle-before-flush.js";
import { abortable as abortableWithSignal } from "./abortable.js";
import { createEmbeddedAgentSessionWithResourceLoader } from "./attempt-session.js";
import {
applyEmbeddedAttemptToolsAllow,
mergeForcedEmbeddedAttemptToolsAllow,
resolveEmbeddedAttemptToolConstructionPlan,
shouldCreateBundleLspRuntimeForAttempt,
shouldCreateBundleMcpRuntimeForAttempt,
} from "./attempt-tool-construction-plan.js";
import {
resolveAttemptTrajectoryTerminal,
resolveTerminalAssistantTexts,
} from "./attempt-trajectory-status.js";
export { buildContextEnginePromptCacheInfo } from "./attempt.context-engine-helpers.js";
import {
rotateTranscriptAfterCompaction,
shouldRotateCompactionTranscript,
} from "../compaction-successor-transcript.js";
import { resolveAttemptWorkspaceBootstrapRouting } from "./attempt-bootstrap-routing.js";
import { configureEmbeddedAttemptHttpRuntime } from "./attempt-http-runtime.js";
import {
createEmbeddedRunStageTracker,
formatEmbeddedRunStageSummary,
shouldWarnEmbeddedRunStageSummary,
} from "./attempt-stage-timing.js";
import { buildAttemptSystemPrompt } from "./attempt-system-prompt.js";
import {
assembleAttemptContextEngine,
buildLoopPromptCacheInfo,
buildContextEnginePromptCacheInfo,
findCurrentAttemptAssistantMessage,
finalizeAttemptContextEngineTurn,
resolvePromptCacheTouchTimestamp,
resolveAttemptBootstrapContext,
runAttemptContextEngineBootstrap,
} from "./attempt.context-engine-helpers.js";
import {
diagnosticErrorCategory,
wrapStreamFnWithDiagnosticModelCallEvents,
} from "./attempt.model-diagnostic-events.js";
import {
buildAfterTurnRuntimeContext,
buildAfterTurnRuntimeContextFromUsage,
prependSystemPromptAddition,
resolveAttemptFsWorkspaceOnly,
resolveAttemptPrependSystemContext,
resolvePromptBuildHookResult,
resolvePromptModeForSession,
resolvePromptSubmissionSkipReason,
shouldWarnOnOrphanedUserRepair,
shouldInjectHeartbeatPrompt,
} from "./attempt.prompt-helpers.js";
import {
createEmbeddedAttemptSessionLockController,
installPromptSubmissionLockRelease,
installSessionExternalHookWriteLock,
installSessionEventWriteLock,
} from "./attempt.session-lock.js";
import {
createYieldAbortedResponse,
persistSessionsYieldContextMessage,
queueSessionsYieldInterruptMessage,
stripSessionsYieldArtifacts,
waitForSessionsYieldAbortSettle,
} from "./attempt.sessions-yield.js";
import { wrapStreamFnHandleSensitiveStopReason } from "./attempt.stop-reason-recovery.js";
import {
buildEmbeddedSubscriptionParams,
cleanupEmbeddedAttemptResources,
} from "./attempt.subscription-cleanup.js";
import {
appendAttemptCacheTtlIfNeeded,
composeSystemPromptWithHookContext,
resolveAttemptSpawnWorkspaceDir,
shouldPersistCompletedBootstrapTurn,
} from "./attempt.thread-helpers.js";
import {
shouldRepairMalformedToolCallArguments,
wrapStreamFnDecodeXaiToolCallArguments,
wrapStreamFnRepairMalformedToolCallArguments,
} from "./attempt.tool-call-argument-repair.js";
import {
shouldApplyReplayToolCallIdSanitizer,
sanitizeReplayToolCallIdsForStream,
wrapStreamFnSanitizeMalformedToolCalls,
wrapStreamFnTrimToolCallNames,
} from "./attempt.tool-call-normalization.js";
import { buildEmbeddedAttemptToolRunContext } from "./attempt.tool-run-context.js";
import { resolveAttemptTranscriptPolicy } from "./attempt.transcript-policy.js";
import { waitForCompactionRetryWithAggregateTimeout } from "./compaction-retry-aggregate-timeout.js";
import {
resolveRunTimeoutDuringCompaction,
resolveRunTimeoutWithCompactionGraceMs,
selectCompactionTimeoutSnapshot,
shouldFlagCompactionTimeout,
} from "./compaction-timeout.js";
import { resolveFinalAssistantVisibleText } from "./helpers.js";
import {
installHistoryImagePruneContextTransform,
pruneProcessedHistoryImages,
} from "./history-image-prune.js";
import { detectAndLoadPromptImages } from "./images.js";
import {
buildAttemptReplayMetadata,
resolveSilentToolResultReplyPayload,
shouldTreatEmptyAssistantReplyAsSilent,
} from "./incomplete-turn.js";
import { resolveLlmIdleTimeoutMs, streamWithIdleTimeout } from "./llm-idle-timeout.js";
import { resolveMessageMergeStrategy } from "./message-merge-strategy.js";
import { installMessageToolOnlyTerminalHook } from "./message-tool-terminal.js";
import {
MID_TURN_PRECHECK_ERROR_MESSAGE,
isMidTurnPrecheckSignal,
type MidTurnPrecheckRequest,
} from "./midturn-precheck.js";
import {
PREEMPTIVE_OVERFLOW_ERROR_TEXT,
formatPrePromptPrecheckLog,
shouldPreemptivelyCompactBeforePrompt,
} from "./preemptive-compaction.js";
import {
buildCurrentInboundPrompt,
buildRuntimeContextSystemContext,
queueRuntimeContextForNextTurn,
resolveRuntimeContextPromptParts,
} from "./runtime-context-prompt.js";
import type { EmbeddedRunAttemptParams, EmbeddedRunAttemptResult } from "./types.js";
export {
appendAttemptCacheTtlIfNeeded,
composeSystemPromptWithHookContext,
resolveAttemptSpawnWorkspaceDir,
} from "./attempt.thread-helpers.js";
export {
buildAfterTurnRuntimeContext,
buildAfterTurnRuntimeContextFromUsage,
mergeOrphanedTrailingUserPrompt,
prependSystemPromptAddition,
resolveAttemptFsWorkspaceOnly,
resolveAttemptPrependSystemContext,
resolvePromptBuildHookResult,
resolvePromptModeForSession,
shouldWarnOnOrphanedUserRepair,
shouldInjectHeartbeatPrompt,
} from "./attempt.prompt-helpers.js";
export {
persistSessionsYieldContextMessage,
queueSessionsYieldInterruptMessage,
stripSessionsYieldArtifacts,
} from "./attempt.sessions-yield.js";
export {
decodeHtmlEntitiesInObject,
wrapStreamFnRepairMalformedToolCallArguments,
} from "./attempt.tool-call-argument-repair.js";
export {
wrapStreamFnSanitizeMalformedToolCalls,
wrapStreamFnTrimToolCallNames,
} from "./attempt.tool-call-normalization.js";
export {
resetEmbeddedAgentBaseStreamFnCacheForTest,
resolveEmbeddedAgentBaseStreamFn,
resolveEmbeddedAgentStreamFn,
};
const MAX_BTW_SNAPSHOT_MESSAGES = 100;
const TOOL_SEARCH_CONTROL_ALLOWLIST_NAMES = [
TOOL_SEARCH_CODE_MODE_TOOL_NAME,
TOOL_SEARCH_RAW_TOOL_NAME,
TOOL_DESCRIBE_RAW_TOOL_NAME,
TOOL_CALL_RAW_TOOL_NAME,
];
export function buildCallableToolNamesForEmptyAllowlistCheck(params: {
effectiveToolNames: string[];
autoAddedToolSearchControlNames?: Set<string>;
toolSearchCatalogToolCount: number;
}): string[] {
return [
...params.effectiveToolNames.filter(
(toolName) => !params.autoAddedToolSearchControlNames?.has(toolName),
),
...Array.from(
{ length: params.toolSearchCatalogToolCount },
(_, index) => `tool-search:${index}`,
),
];
}
export function buildAutoAddedToolSearchControlNamesForAllowlistCheck(params: {
toolSearchControlsEnabled: boolean;
explicitAllowlistSources: Array<{ entries: string[] }>;
controlNames?: readonly string[];
}): Set<string> | undefined {
if (!params.toolSearchControlsEnabled) {
return undefined;
}
const explicitlyAllowed = new Set(
params.explicitAllowlistSources.flatMap((source) =>
source.entries.map((entry) => normalizeToolName(entry)),
),
);
return new Set(
(params.controlNames ?? TOOL_SEARCH_CONTROL_ALLOWLIST_NAMES).filter(
(controlName) => !explicitlyAllowed.has(normalizeToolName(controlName)),
),
);
}
export type ToolSearchRunPlan = {
visibleAllowedToolNames: Set<string>;
replayAllowedToolNames: Set<string>;
autoAddedControlNames?: Set<string>;
emptyAllowlistCallableNames: string[];
};
type CollectAllowedToolNamesParams = Parameters<typeof collectAllowedToolNames>[0];
function collectExplicitlyAllowedClientToolNames(params: {
clientTools?: CollectAllowedToolNamesParams["clientTools"];
explicitAllowlistSources: Array<{ entries: string[] }>;
}): string[] {
const explicitNames = new Set(
params.explicitAllowlistSources.flatMap((source) =>
source.entries.map((entry) => normalizeToolName(entry)),
),
);
return (params.clientTools ?? [])
.map((tool) => tool.function?.name)
.filter((name): name is string => Boolean(name?.trim()))
.filter((name) => explicitNames.has(normalizeToolName(name)));
}
export function buildToolSearchRunPlan(params: {
visibleTools: CollectAllowedToolNamesParams["tools"];
uncompactedTools: CollectAllowedToolNamesParams["tools"];
clientTools?: CollectAllowedToolNamesParams["clientTools"];
catalogRegistered: boolean;
catalogToolCount: number;
controlsEnabled: boolean;
controlNames?: readonly string[];
explicitAllowlistSources: Array<{ entries: string[] }>;
}): ToolSearchRunPlan {
const visibleAllowedToolNames = collectAllowedToolNames({
tools: params.visibleTools,
clientTools: params.catalogRegistered ? undefined : params.clientTools,
});
const replayAllowedToolNames = collectAllowedToolNames({
tools: params.uncompactedTools,
clientTools: params.clientTools,
});
if (params.controlsEnabled) {
for (const controlName of params.controlNames ?? TOOL_SEARCH_CONTROL_ALLOWLIST_NAMES) {
if (visibleAllowedToolNames.has(controlName)) {
replayAllowedToolNames.add(controlName);
}
}
}
const autoAddedControlNames = buildAutoAddedToolSearchControlNamesForAllowlistCheck({
toolSearchControlsEnabled: params.controlsEnabled,
explicitAllowlistSources: params.explicitAllowlistSources,
controlNames: params.controlNames,
});
const clientCatalogCallableNames = params.catalogRegistered
? collectExplicitlyAllowedClientToolNames({
clientTools: params.clientTools,
explicitAllowlistSources: params.explicitAllowlistSources,
}).map((name) => `tool-search-client:${name}`)
: [];
return {
visibleAllowedToolNames,
replayAllowedToolNames,
autoAddedControlNames,
emptyAllowlistCallableNames: [
...buildCallableToolNamesForEmptyAllowlistCheck({
effectiveToolNames: [...visibleAllowedToolNames],
autoAddedToolSearchControlNames: autoAddedControlNames,
toolSearchCatalogToolCount: params.catalogToolCount,
}),
...clientCatalogCallableNames,
],
};
}
export function resolveUnknownToolGuardThreshold(loopDetection?: {
enabled?: boolean;
unknownToolThreshold?: number;
}): number {
// The unknown-tool guard is a safety net against the model hallucinating a
// tool name or calling a tool that has since been removed from the allowlist
// (for example after a `skills.allowBundled` config change). After `threshold`
// consecutive unknown-tool attempts the stream wrapper rewrites the assistant
// message content to tell the model to stop, which breaks otherwise-infinite
// Tool-not-found loops against the provider. Unlike the genericRepeat /
// pingPong / pollNoProgress detectors this guard has no false-positive
// surface because the tool is objectively not registered in this run, so it
// stays on regardless of `tools.loopDetection.enabled`.
const raw = loopDetection?.unknownToolThreshold;
if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) {
return Math.floor(raw);
}
return UNKNOWN_TOOL_THRESHOLD;
}
export function isPrimaryBootstrapRun(sessionKey?: string): boolean {
return !isSubagentSessionKey(sessionKey) && !isAcpSessionKey(sessionKey);
}
function isRelativePathInsideOrEqual(relativePath: string): boolean {
return (
relativePath === "" ||
(relativePath !== ".." &&
!relativePath.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relativePath))
);
}
export function remapInjectedContextFilesToWorkspace(params: {
files: EmbeddedContextFile[];
sourceWorkspaceDir: string;
targetWorkspaceDir: string;
}): EmbeddedContextFile[] {
if (params.sourceWorkspaceDir === params.targetWorkspaceDir) {
return params.files;
}
return params.files.map((file) => {
const relative = path.relative(params.sourceWorkspaceDir, file.path);
const canRemap = isRelativePathInsideOrEqual(relative);
return canRemap
? {
...file,
path:
relative === ""
? params.targetWorkspaceDir
: path.join(params.targetWorkspaceDir, relative),
}
: file;
});
}
function summarizeMessagePayload(msg: AgentMessage): { textChars: number; imageBlocks: number } {
const content = (msg as { content?: unknown }).content;
if (typeof content === "string") {
return { textChars: content.length, imageBlocks: 0 };
}
if (!Array.isArray(content)) {
return { textChars: 0, imageBlocks: 0 };
}
let textChars = 0;
let imageBlocks = 0;
for (const block of content) {
if (!block || typeof block !== "object") {
continue;
}
const typedBlock = block as { type?: unknown; text?: unknown };
if (typedBlock.type === "image") {
imageBlocks++;
continue;
}
if (typeof typedBlock.text === "string") {
textChars += typedBlock.text.length;
}
}
return { textChars, imageBlocks };
}
function summarizeSessionContext(messages: AgentMessage[]): {
roleCounts: string;
totalTextChars: number;
totalImageBlocks: number;
maxMessageTextChars: number;
} {
const roleCounts = new Map<string, number>();
let totalTextChars = 0;
let totalImageBlocks = 0;
let maxMessageTextChars = 0;
for (const msg of messages) {
const role = typeof msg.role === "string" ? msg.role : "unknown";
roleCounts.set(role, (roleCounts.get(role) ?? 0) + 1);
const payload = summarizeMessagePayload(msg);
totalTextChars += payload.textChars;
totalImageBlocks += payload.imageBlocks;
if (payload.textChars > maxMessageTextChars) {
maxMessageTextChars = payload.textChars;
}
}
return {
roleCounts:
[...roleCounts.entries()]
.toSorted((a, b) => a[0].localeCompare(b[0]))
.map(([role, count]) => `${role}:${count}`)
.join(",") || "none",
totalTextChars,
totalImageBlocks,
maxMessageTextChars,
};
}
export type EmbeddedPiActiveSessionSteerTarget = {
agent?: unknown;
getSteeringMessages?(): readonly string[];
steer(text: string): Promise<void>;
subscribe(listener: (event: unknown) => void): () => void;
};
const DEFAULT_QUEUE_TRANSCRIPT_COMMIT_TIMEOUT_MS = 120_000;
function extractQueuedUserMessageText(message: unknown): string | undefined {
if (!message || typeof message !== "object") {
return undefined;
}
const record = message as { content?: unknown; role?: unknown };
if (record.role !== "user") {
return undefined;
}
if (typeof record.content === "string") {
return record.content;
}
if (!Array.isArray(record.content)) {
return undefined;
}
const text = record.content
.map((block) => {
if (!block || typeof block !== "object") {
return undefined;
}
const typedBlock = block as { text?: unknown; type?: unknown };
return typedBlock.type === "text" && typeof typedBlock.text === "string"
? typedBlock.text
: undefined;
})
.filter((part): part is string => part !== undefined)
.join("");
return text || undefined;
}
function isQueuedUserMessageEnd(event: unknown, text: string): boolean {
if (!event || typeof event !== "object") {
return false;
}
const record = event as { message?: unknown; type?: unknown };
return record.type === "message_end" && extractQueuedUserMessageText(record.message) === text;
}
function isTerminalActiveSessionEvent(event: unknown): boolean {
return Boolean(
event && typeof event === "object" && (event as { type?: unknown }).type === "agent_end",
);
}
function isAutoRetryStartEvent(event: unknown): boolean {
return Boolean(
event && typeof event === "object" && (event as { type?: unknown }).type === "auto_retry_start",
);
}
function isCompactionStartEvent(event: unknown): boolean {
return Boolean(
event && typeof event === "object" && (event as { type?: unknown }).type === "compaction_start",
);
}
function getPiSteeringQueueMessages(agent: unknown): unknown[] | undefined {
if (!agent || typeof agent !== "object") {
return undefined;
}
const queue = (agent as { steeringQueue?: unknown }).steeringQueue;
if (!queue || typeof queue !== "object") {
return undefined;
}
const messages = (queue as { messages?: unknown }).messages;
return Array.isArray(messages) ? messages : undefined;
}
async function cancelQueuedSteeringMessage(
activeSession: EmbeddedPiActiveSessionSteerTarget,
text: string,
): Promise<boolean> {
const queuedMessages = getPiSteeringQueueMessages(activeSession.agent);
if (!queuedMessages) {
return false;
}
// Pi exposes only all-queue clears publicly; mutate the exact pending message
// so unrelated queued messages keep their full payloads.
const queueIndex = queuedMessages.findIndex(
(message) => extractQueuedUserMessageText(message) === text,
);
if (queueIndex === -1) {
return false;
}
queuedMessages.splice(queueIndex, 1);
const uiSteeringMessages = activeSession.getSteeringMessages?.();
if (Array.isArray(uiSteeringMessages)) {
const uiIndex = uiSteeringMessages.indexOf(text);
if (uiIndex !== -1) {
uiSteeringMessages.splice(uiIndex, 1);
}
}
return true;
}
export const testing = {
cancelQueuedSteeringMessage,
resolveAttemptStreamAuthProfileId,
steerAndWaitForTranscriptCommit,
};
function resolveAttemptStreamAuthProfileId(
params: Pick<EmbeddedRunAttemptParams, "authProfileId" | "runtimePlan">,
): string | undefined {
return params.runtimePlan?.auth.forwardedAuthProfileId;
}
async function steerAndWaitForTranscriptCommit(
activeSession: EmbeddedPiActiveSessionSteerTarget,
text: string,
timeoutMs: number,
): Promise<void> {
await new Promise<void>((resolve, reject) => {
let settled = false;
let unsubscribe: (() => void) | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
let terminalTimer: ReturnType<typeof setTimeout> | undefined;
const finish = (err?: unknown) => {
if (settled) {
return;
}
settled = true;
if (timer) {
clearTimeout(timer);
}
if (terminalTimer) {
clearTimeout(terminalTimer);
}
unsubscribe?.();
if (err) {
reject(err);
return;
}
resolve();
};
const rejectAfterCancellation = (message: string) => {
void cancelQueuedSteeringMessage(activeSession, text)
.then((removed) => {
if (!removed) {
log.warn("failed to find queued steering message for cancellation");
}
})
.catch((err: unknown) => {
log.warn(`failed to cancel queued steering message: ${String(err)}`);
})
.finally(() => {
finish(new Error(message));
});
};
const scheduleTerminalCancellation = () => {
if (terminalTimer) {
return;
}
terminalTimer = setTimeout(() => {
terminalTimer = undefined;
rejectAfterCancellation(
"active session ended before queued steering message was committed to the transcript",
);
}, 0);
terminalTimer.unref?.();
};
timer = setTimeout(
() => {
rejectAfterCancellation(
"queued steering message was not committed to the transcript before timeout",
);
},
Math.max(1, timeoutMs),
);
timer.unref?.();
unsubscribe = activeSession.subscribe((event) => {
if (isAutoRetryStartEvent(event) || isCompactionStartEvent(event)) {
if (terminalTimer) {
clearTimeout(terminalTimer);
terminalTimer = undefined;
}
return;
}
if (isQueuedUserMessageEnd(event, text)) {
finish();
return;
}
if (isTerminalActiveSessionEvent(event)) {
// AgentSession emits agent_end before announcing auto-retry or
// auto-compaction continuations. Defer cancellation one tick so those
// continuation events can keep draining this message.
scheduleTerminalCancellation();
}
});
activeSession.steer(text).catch((err: unknown) => {
finish(err);
});
});
}
async function steerActiveSessionWithOptionalDeliveryWait(
activeSession: EmbeddedPiActiveSessionSteerTarget,
text: string,
options: { deliveryTimeoutMs?: number; waitForTranscriptCommit?: boolean } | undefined,
): Promise<void> {
if (options?.waitForTranscriptCommit !== true) {
await activeSession.steer(text);
return;
}
await steerAndWaitForTranscriptCommit(
activeSession,
text,
options.deliveryTimeoutMs ?? DEFAULT_QUEUE_TRANSCRIPT_COMMIT_TIMEOUT_MS,
);
}
export function normalizeMessagesForLlmBoundary(messages: AgentMessage[]): AgentMessage[] {
const normalized = stripToolResultDetails(normalizeAssistantReplayContent(messages));
const withoutHistoricalInboundMetadata =
stripHistoricalInboundMetadataFromUserMessages(normalized);
return stripHistoricalRuntimeContextCustomMessages(withoutHistoricalInboundMetadata);
}
function stripHistoricalInboundMetadataFromUserMessages(messages: AgentMessage[]): AgentMessage[] {
const activeUserMessageIndex = findActiveUserMessageIndex(messages);
let changed = false;
const nextMessages = messages.map((message, index) => {
if (message.role !== "user" || index === activeUserMessageIndex) {
return message;
}
const content = (message as { content?: unknown }).content;
if (typeof content === "string") {
const stripped = stripInboundMetadata(content);
if (stripped === content) {
return message;
}
changed = true;
return { ...message, content: stripped } as AgentMessage;
}
if (!Array.isArray(content)) {
return message;
}
let contentChanged = false;
const nextContent = content.map((block) => {
if (!block || typeof block !== "object") {
return block;
}
const textBlock = block as { type?: unknown; text?: unknown };
if (textBlock.type !== "text" || typeof textBlock.text !== "string") {
return block;
}
const stripped = stripInboundMetadata(textBlock.text);
if (stripped === textBlock.text) {
return block;
}
contentChanged = true;
return Object.assign({}, block, { text: stripped });
});
if (!contentChanged) {
return message;
}
changed = true;
return { ...message, content: nextContent } as AgentMessage;
});
return changed ? nextMessages : messages;
}
function findActiveUserMessageIndex(messages: AgentMessage[]): number {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (!message) {
continue;
}
if (message.role === "user") {
return index;
}
if (message.role === "assistant" && !isToolCallAssistantMessage(message)) {
return -1;
}
}
return -1;
}
function isToolCallAssistantMessage(message: AgentMessage): boolean {
if (message.role !== "assistant") {
return false;
}
const content = (message as { content?: unknown }).content;
if (!Array.isArray(content)) {
return false;
}
return content.some((block) => {
if (!block || typeof block !== "object") {
return false;
}
const type = (block as { type?: unknown }).type;
return type === "toolCall" || type === "toolUse" || type === "functionCall";
});
}
function cloneHookMessages(messages: AgentMessage[]): AgentMessage[] {
return messages.map((message) => structuredClone(message));
}
function sessionMessagesContainIdempotencyKey(
messages: AgentMessage[],
idempotencyKey: string,
): boolean {
return messages.some(
(message) =>
typeof (message as { idempotencyKey?: unknown }).idempotencyKey === "string" &&
(message as { idempotencyKey?: unknown }).idempotencyKey === idempotencyKey,
);
}
function flushSessionManagerFile(sessionManager: ReturnType<typeof guardSessionManager>): void {
(sessionManager as unknown as { _rewriteFile?: () => void })["_rewriteFile"]?.();