@openclaw/copilot 2026.9.5 → 2026.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,17 @@
1
- import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-Dj0L75Tk.mjs";
1
+ import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-BAWs53-w.mjs";
2
2
  import { n as normalizeCopilotUsage, r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.mjs";
3
- import { asNonArrayRecord, asOptionalRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
4
- import { SKILL_WORKSHOP_TOOL_NAME, applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHookContextChannelFields, buildCredentialSafetyPrompt, buildDelegationGuidanceSection, buildEmbeddedAttemptToolRunContext, buildEmbeddedForegroundPromptContext, buildHarnessVisibleReplyGuidance, buildSkillWorkshopPromptSection, cancelPendingAgentQuestionForSession, claimPendingAgentQuestionAnswer, clearActiveEmbeddedRun, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, getPluginToolSideEffectOwnerKey, isHostScopedAgentToolActive, isSubagentSessionKey, isToolResultError, projectAgentHarnessTranscriptMessageForDisplay, resolveAgentDir, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveMainSessionDelegationMode, resolveModelAuthMode, resolveSandboxContext, resolveUserPath, restorePreparedUserTurnOperationalMetaForRuntime, runAgentEndSideEffects, runAgentHarnessAfterCompactionHook, runAgentHarnessAfterToolCallHook, runAgentHarnessBeforeCompactionHook, runAgentHarnessBeforeMessageWriteHook, runAgentHarnessGatewayQuestion, runAgentHarnessLlmInputHook, runAgentHarnessLlmOutputHook, sanitizeToolResult, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
3
+ import { asNonArrayRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
4
+ import { SKILL_WORKSHOP_TOOL_NAME, applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHookContextChannelFields, buildCredentialSafetyPrompt, buildDelegationGuidanceSection, buildEmbeddedAttemptToolRunContext, buildEmbeddedForegroundPromptContext, buildHarnessVisibleReplyGuidance, buildSkillWorkshopPromptSection, cancelPendingAgentQuestionForSession, claimPendingAgentQuestionAnswer, clearActiveEmbeddedRun, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, emitAgentEvent, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, getPluginToolSideEffectOwnerKey, isHostScopedAgentToolActive, isSubagentSessionKey, isToolResultError, projectAgentHarnessTranscriptMessageForDisplay, projectAgentToolActivity, resolveAgentDir, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveMainSessionDelegationMode, resolveModelAuthMode, resolveSandboxContext, resolveUserPath, restorePreparedUserTurnOperationalMetaForRuntime, runAgentEndSideEffects, runAgentHarnessAfterCompactionHook, runAgentHarnessAfterToolCallHook, runAgentHarnessBeforeCompactionHook, runAgentHarnessBeforeMessageWriteHook, runAgentHarnessGatewayQuestion, runAgentHarnessLlmInputHook, runAgentHarnessLlmOutputHook, sanitizeToolResult, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
5
5
  import path from "node:path";
6
6
  import { formatErrorMessage, toErrorObject, toStringifiedError, toStringifiedError as toCopilotError } from "openclaw/plugin-sdk/error-runtime";
7
7
  import { parseDateStringTimestampMs } from "openclaw/plugin-sdk/number-runtime";
8
+ import { createAgentHarnessToolSurfaceRuntime, normalizeAcceptedSessionSpawnResult } from "openclaw/plugin-sdk/agent-harness-tool-runtime";
8
9
  import fsp from "node:fs/promises";
9
10
  import { resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
10
11
  import { convertMcpCallToolResult } from "@github/copilot-sdk";
11
- import { createAgentHarnessToolSurfaceRuntime } from "openclaw/plugin-sdk/agent-harness-tool-runtime";
12
12
  import { isDeepStrictEqual } from "node:util";
13
13
  import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
14
14
  import { appendSessionTranscriptMessageByIdentityStrict, appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity, readVisibleSessionTranscriptMessageEntries } from "openclaw/plugin-sdk/session-transcript-runtime";
15
- import { createAgentHarnessTaskRuntime } from "openclaw/plugin-sdk/agent-harness-task-runtime";
16
15
  //#region extensions/copilot/src/attempt-types.ts
17
16
  const BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS = 5e3;
18
17
  const COPILOT_ASK_USER_AVAILABLE_TOOLS = ["builtin:ask_user"];
@@ -102,18 +101,11 @@ function createHooksBridge(config, options) {
102
101
  }
103
102
  //#endregion
104
103
  //#region extensions/copilot/src/permission-bridge.ts
105
- /** Built-in fail-closed default. Mirrors the pre-bridge attempt.ts stub. */
106
104
  const REJECT_ALL_FEEDBACK = "copilot agent runtime: no permission policy installed (fail-closed default)";
107
105
  const rejectAllPolicy = () => ({
108
106
  kind: "reject",
109
107
  feedback: REJECT_ALL_FEEDBACK
110
108
  });
111
- /**
112
- * Adapt a `CopilotPermissionPolicy` to the SDK's
113
- * `PermissionHandler` shape. The returned handler always resolves
114
- * (never rejects), defaulting to fail-closed when the policy returns
115
- * undefined or throws.
116
- */
117
109
  function createPermissionBridge(policy = rejectAllPolicy) {
118
110
  return async (request, invocation) => {
119
111
  const ctx = {
@@ -137,27 +129,13 @@ function createPermissionBridge(policy = rejectAllPolicy) {
137
129
  }
138
130
  //#endregion
139
131
  //#region extensions/copilot/src/replay-shim.ts
140
- function normalizeSdkSessionId(value) {
141
- return normalizeOptionalString(value);
142
- }
143
- /**
144
- * Pure pre-call decision: should attempt.ts call resumeSession or
145
- * createSession?
146
- *
147
- * Rules:
148
- * - No input → create (no-replay-state)
149
- * - No (trimmed) sdkSessionId → create (no-sdk-session-id)
150
- * - sdkSessionId + replayInvalid=true → create (replay-invalid),
151
- * downgradedFromResume=true
152
- * - sdkSessionId + replayInvalid=false → resume
153
- */
154
132
  function decideReplayAction(input) {
155
133
  if (!input) return {
156
134
  action: "create",
157
135
  downgradedFromResume: false,
158
136
  downgradeReason: "no-replay-state"
159
137
  };
160
- const sdkSessionId = normalizeSdkSessionId(input.sdkSessionId);
138
+ const sdkSessionId = normalizeOptionalString(input.sdkSessionId);
161
139
  if (!sdkSessionId) return {
162
140
  action: "create",
163
141
  downgradedFromResume: false,
@@ -192,24 +170,7 @@ function readErrorField(error, key) {
192
170
  if (!error || typeof error !== "object") return;
193
171
  return error[key];
194
172
  }
195
- /**
196
- * Post-call: classify a resumeSession() failure so attempt.ts can
197
- * decide whether to downgrade silently to createSession.
198
- *
199
- * Conservative: only treats clearly session-gone signals as recoverable.
200
- * Structured signals (status === 404, recognised code strings) are
201
- * checked first; message matching is a fallback because SDK error
202
- * messages are not part of the typed contract.
203
- *
204
- * Everything else (transport errors, auth failures, generic Error) is
205
- * unrecoverable and should surface to the outer attempt.ts try/catch
206
- * which converts it to a prompt error.
207
- */
208
173
  function classifyResumeFailure(error) {
209
- if (error === void 0 || error === null) return {
210
- recoverable: false,
211
- kind: "unknown"
212
- };
213
174
  if (readErrorField(error, "status") === 404) return {
214
175
  recoverable: true,
215
176
  kind: "missing"
@@ -223,38 +184,16 @@ function classifyResumeFailure(error) {
223
184
  recoverable: true,
224
185
  kind: "missing"
225
186
  };
226
- const message = error instanceof Error ? error.message : typeof error === "object" ? typeof error.message === "string" ? error.message : void 0 : void 0;
227
- if (typeof message === "string") {
228
- for (const pattern of MISSING_SESSION_MESSAGE_PATTERNS) if (pattern.test(message)) return {
229
- recoverable: true,
230
- kind: "missing"
231
- };
232
- }
187
+ const message = readErrorField(error, "message");
188
+ if (typeof message === "string" && MISSING_SESSION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return {
189
+ recoverable: true,
190
+ kind: "missing"
191
+ };
233
192
  return {
234
193
  recoverable: false,
235
194
  kind: "unknown"
236
195
  };
237
196
  }
238
- /**
239
- * Compute the `EmbeddedRunReplayMetadata` to attach to the attempt
240
- * result. Worst-case-wins:
241
- *
242
- * hadPotentialSideEffects = priorHadPotentialSideEffects OR timedOut
243
- * OR thisAttemptHadPotentialSideEffects
244
- * (timeout means we cannot prove the prompt was not partially
245
- * committed server-side; treat as side-effecting so the
246
- * orchestrator will not blindly re-issue the same prompt).
247
- *
248
- * replaySafe = NOT (
249
- * priorReplayInvalid
250
- * OR thisAttemptDowngradedFromResume
251
- * OR thisAttemptResumeFailureRecovered
252
- * OR hadPotentialSideEffects
253
- * )
254
- *
255
- * Matches the parity rule in
256
- * `src/agents/pi-embedded-runner/replay-state.ts#replayMetadataFromState`.
257
- */
258
197
  function computeReplayMetadata(input) {
259
198
  const priorReplayInvalid = input.priorReplayInvalid === true;
260
199
  const priorHadPotentialSideEffects = input.priorHadPotentialSideEffects === true;
@@ -291,11 +230,7 @@ const COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set([
291
230
  "web_search"
292
231
  ]);
293
232
  function copilotToolMetasHavePotentialSideEffects(toolMetas) {
294
- return (toolMetas ?? []).some((entry) => entry.asyncStarted === true || !isReplaySafeReadOnlyToolName(entry.toolName));
295
- }
296
- function isReplaySafeReadOnlyToolName(toolName) {
297
- const normalized = toolName.trim().toLowerCase();
298
- return COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES.has(normalized);
233
+ return (toolMetas ?? []).some((entry) => entry.asyncStarted === true || !COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES.has(entry.toolName.trim().toLowerCase()));
299
234
  }
300
235
  //#endregion
301
236
  //#region extensions/copilot/src/attempt-config.ts
@@ -400,7 +335,12 @@ function buildCopilotAvailableTools(sdkTools, includeAskUser) {
400
335
  return [...new Set(availableTools)];
401
336
  }
402
337
  async function createMessageOptions(params, context) {
403
- const attachments = createPromptImageAttachments(await resolvePromptImages(params, context));
338
+ const attachments = (await resolvePromptImages(params, context)).map((image, index) => ({
339
+ type: "blob",
340
+ data: image.data,
341
+ mimeType: image.mimeType,
342
+ displayName: `prompt-image-${index + 1}`
343
+ }));
404
344
  const providerHeaders = context.provider.provider?.headers;
405
345
  const requestHeaders = providerHeaders && Object.keys(providerHeaders).length > 0 ? { ...providerHeaders } : void 0;
406
346
  return {
@@ -409,17 +349,6 @@ async function createMessageOptions(params, context) {
409
349
  ...requestHeaders ? { requestHeaders } : {}
410
350
  };
411
351
  }
412
- function createPromptImageAttachments(images) {
413
- return images.flatMap((image, index) => {
414
- if (!image || typeof image !== "object" || image.type !== "image" || typeof image.data !== "string" || typeof image.mimeType !== "string") return [];
415
- return [{
416
- type: "blob",
417
- data: image.data,
418
- mimeType: image.mimeType,
419
- displayName: `prompt-image-${index + 1}`
420
- }];
421
- });
422
- }
423
352
  async function resolvePromptImages(params, context) {
424
353
  const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
425
354
  if (!workspaceDir) return [];
@@ -565,6 +494,63 @@ function buildAssistantMessage(params) {
565
494
  })
566
495
  };
567
496
  }
497
+ function buildAssistantProjectionGroup(group, modelRef, resolveTimestamp, usageByApiCallId, latestUsage, forTranscript) {
498
+ const messages = group.chunks.flatMap((chunk) => {
499
+ const message = buildAssistantMessage({
500
+ event: chunk.event,
501
+ modelRef,
502
+ now: () => resolveTimestamp(chunk.event),
503
+ reasoningText: forTranscript ? chunk.transcriptReasoningText : chunk.reasoningText,
504
+ usage: resolveAssistantUsage(chunk.event, latestUsage, usageByApiCallId),
505
+ assistantTexts: forTranscript ? chunk.transcriptAssistantTexts : chunk.assistantTexts
506
+ });
507
+ return message ? [message] : [];
508
+ });
509
+ const replayIncomplete = group.chunks.some(({ event }) => hasUnprojectedAssistantReplayState(event));
510
+ const last = messages.at(-1);
511
+ if (!last) return {
512
+ message: void 0,
513
+ replayIncomplete,
514
+ toolCallIds: []
515
+ };
516
+ const narrative = [];
517
+ let terminalThinking;
518
+ const toolCallsById = /* @__PURE__ */ new Map();
519
+ for (const message of messages) for (const part of message.content) {
520
+ if (part.type === "toolCall") {
521
+ toolCallsById.set(part.id, part);
522
+ continue;
523
+ }
524
+ if (part.type === "thinking") {
525
+ terminalThinking = part;
526
+ continue;
527
+ }
528
+ const previous = narrative.at(-1);
529
+ if (part.type === "text" && previous?.type === "text") narrative[narrative.length - 1] = {
530
+ ...previous,
531
+ text: previous.text + part.text
532
+ };
533
+ else narrative.push(part);
534
+ }
535
+ const content = [
536
+ ...terminalThinking ? [terminalThinking] : [],
537
+ ...narrative,
538
+ ...toolCallsById.values()
539
+ ];
540
+ const toolCallIds = [...toolCallsById.keys()];
541
+ return {
542
+ message: {
543
+ ...last,
544
+ content,
545
+ stopReason: toolCallIds.length > 0 ? "toolUse" : "stop"
546
+ },
547
+ replayIncomplete,
548
+ toolCallIds
549
+ };
550
+ }
551
+ function hasUnprojectedAssistantReplayState(event) {
552
+ return event.data.citations !== void 0 || event.data.serverTools !== void 0 || event.data.reasoningWireField !== void 0 || event.data.reasoningOpaque !== void 0 || event.data.encryptedContent !== void 0 || event.data.toolRequests?.some((request) => request.type === "custom") === true;
553
+ }
568
554
  function resolveAssistantUsage(event, latest, byApiCallId) {
569
555
  const apiCallId = readNonEmptyStringPreservingWhitespace(event?.data.apiCallId);
570
556
  return apiCallId ? byApiCallId.get(apiCallId) ?? latest : latest;
@@ -627,11 +613,8 @@ function sanitizeToolDetailText(text) {
627
613
  //#endregion
628
614
  //#region extensions/copilot/src/event-bridge.ts
629
615
  function attachEventBridge(session, options) {
630
- const messageOrder = [];
631
616
  const messagesById = /* @__PURE__ */ new Map();
632
- const reasoningOrder = [];
633
617
  const reasoningById = /* @__PURE__ */ new Map();
634
- const durableReasoningOrder = [];
635
618
  const durableReasoningById = /* @__PURE__ */ new Map();
636
619
  let lastAssistantEvent;
637
620
  let lastAssistantReasoningText;
@@ -644,6 +627,8 @@ function attachEventBridge(session, options) {
644
627
  let streamError;
645
628
  const toolMetas = [];
646
629
  const toolMetaIndexByCallId = /* @__PURE__ */ new Map();
630
+ const toolCallsById = /* @__PURE__ */ new Map();
631
+ const preparedToolCompletions = /* @__PURE__ */ new Set();
647
632
  const projectedToolNamesByCallId = /* @__PURE__ */ new Map();
648
633
  const userRequestedToolCallIds = /* @__PURE__ */ new Set();
649
634
  let startedCount = 0;
@@ -704,7 +689,7 @@ function attachEventBridge(session, options) {
704
689
  const messageId = readNonEmptyStringPreservingWhitespace(event.data.messageId) ?? "assistant-message";
705
690
  const delta = event.data.deltaContent;
706
691
  if (!delta) return;
707
- const entry = ensureMessageAccumulator(messagesById, messageOrder, messageId);
692
+ const entry = ensureMessageAccumulator(messagesById, messageId);
708
693
  entry.text += delta;
709
694
  const onAssistantDelta = options.onAssistantDelta;
710
695
  if (!onAssistantDelta) return;
@@ -727,17 +712,11 @@ function attachEventBridge(session, options) {
727
712
  const reasoningId = readNonEmptyStringPreservingWhitespace(event.data.reasoningId) ?? "assistant-reasoning";
728
713
  const delta = event.data.deltaContent;
729
714
  if (!delta) return;
730
- if (!reasoningById.has(reasoningId)) {
731
- reasoningById.set(reasoningId, "");
732
- reasoningOrder.push(reasoningId);
733
- }
734
715
  reasoningById.set(reasoningId, `${reasoningById.get(reasoningId) ?? ""}${delta}`);
735
716
  });
736
717
  registerListener(session, unsubscribeFns, "assistant.reasoning", (event) => {
737
718
  if (!isRootSessionEvent(event) || event.ephemeral === true) return;
738
- if (!reasoningById.has(event.data.reasoningId)) reasoningOrder.push(event.data.reasoningId);
739
719
  reasoningById.set(event.data.reasoningId, event.data.content);
740
- if (!durableReasoningById.has(event.data.reasoningId)) durableReasoningOrder.push(event.data.reasoningId);
741
720
  durableReasoningById.set(event.data.reasoningId, event.data.content);
742
721
  unconsumedDurableReasoning = true;
743
722
  });
@@ -766,12 +745,38 @@ function attachEventBridge(session, options) {
766
745
  if (isRootSessionEvent(event)) startedCount += 1;
767
746
  toolMetaIndexByCallId.set(event.data.toolCallId, toolMetas.length);
768
747
  toolMetas.push({ toolName: event.data.toolName });
748
+ toolCallsById.set(event.data.toolCallId, {
749
+ args: event.data.arguments,
750
+ root: isRootSessionEvent(event)
751
+ });
752
+ if (isRootSessionEvent(event)) enqueueAgentEvent({
753
+ stream: "item",
754
+ data: projectAgentToolActivity({
755
+ toolCallId: event.data.toolCallId,
756
+ name: event.data.toolName,
757
+ phase: "start",
758
+ args: event.data.arguments
759
+ })
760
+ });
769
761
  });
770
762
  registerListener(session, unsubscribeFns, "tool.execution_complete", (event) => {
771
763
  flushPendingAssistantProjectionForToolCall(event.data.toolCallId);
772
764
  if (isRootSessionEvent(event)) completedCount += 1;
773
765
  const toolMetaIndex = toolMetaIndexByCallId.get(event.data.toolCallId);
774
766
  const toolName = toolMetaIndex === void 0 ? void 0 : toolMetas[toolMetaIndex]?.toolName;
767
+ const args = toolCallsById.get(event.data.toolCallId)?.args;
768
+ toolCallsById.delete(event.data.toolCallId);
769
+ const completionPrepared = preparedToolCompletions.delete(event.data.toolCallId);
770
+ if (toolName && isRootSessionEvent(event) && !completionPrepared) enqueueAgentEvent({
771
+ stream: "item",
772
+ data: projectAgentToolActivity({
773
+ toolCallId: event.data.toolCallId,
774
+ name: toolName,
775
+ phase: "result",
776
+ args,
777
+ isError: !event.data.success
778
+ })
779
+ });
775
780
  const meta = event.data.success ? event.data.result?.detailedContent ?? event.data.result?.content : event.data.error?.message;
776
781
  if (toolName && toolMetaIndex !== void 0) toolMetas[toolMetaIndex] = {
777
782
  ...meta ? { meta } : {},
@@ -861,17 +866,8 @@ function attachEventBridge(session, options) {
861
866
  }
862
867
  });
863
868
  });
864
- registerListener(session, unsubscribeFns, "subagent.started", (event) => {
865
- forwardNativeSubagentEvent(event);
866
- });
867
- registerListener(session, unsubscribeFns, "subagent.completed", (event) => {
868
- forwardNativeSubagentEvent(event);
869
- });
870
- registerListener(session, unsubscribeFns, "subagent.failed", (event) => {
871
- forwardNativeSubagentEvent(event);
872
- });
873
869
  registerListener(session, unsubscribeFns, "session.compaction_start", (event) => {
874
- if (!isRootCompactionEvent(event)) return;
870
+ if (!isRootSessionEvent(event)) return;
875
871
  observedCompaction = true;
876
872
  if (activeCompactionCount === 0) compactionIdle = new Promise((resolve) => {
877
873
  resolveCompactionIdle = resolve;
@@ -883,7 +879,7 @@ function attachEventBridge(session, options) {
883
879
  if (event.data.success) try {
884
880
  options.onContextCompacted?.();
885
881
  } catch {}
886
- if (!isRootCompactionEvent(event)) return;
882
+ if (!isRootSessionEvent(event)) return;
887
883
  activeCompactionCount = Math.max(0, activeCompactionCount - 1);
888
884
  enqueueCompactionCallback(() => options.onCompactionComplete?.({
889
885
  ...event.data.messagesRemoved !== void 0 ? { messagesRemoved: event.data.messagesRemoved } : {},
@@ -895,7 +891,7 @@ function attachEventBridge(session, options) {
895
891
  }
896
892
  });
897
893
  registerListener(session, unsubscribeFns, "session.idle", (event) => {
898
- if (!isRootCompactionEvent(event)) return;
894
+ if (!isRootSessionEvent(event)) return;
899
895
  markUnconsumedReasoningIncomplete();
900
896
  flushPendingAssistantProjection();
901
897
  observedSessionIdle = true;
@@ -952,7 +948,7 @@ function attachEventBridge(session, options) {
952
948
  },
953
949
  snapshot() {
954
950
  return {
955
- assistantTexts: finalizeAssistantTexts(messageOrder, messagesById, lastAssistantEvent),
951
+ assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent),
956
952
  completedCount,
957
953
  lastAssistantEvent,
958
954
  startedCount,
@@ -969,11 +965,24 @@ function attachEventBridge(session, options) {
969
965
  now: args.now,
970
966
  reasoningText: lastAssistantReasoningText,
971
967
  usage: resolveAssistantUsage(lastAssistantEvent, usage, usageByApiCallId),
972
- assistantTexts: finalizeAssistantTexts(messageOrder, messagesById, lastAssistantEvent)
968
+ assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent)
973
969
  });
974
970
  },
975
971
  finalizeAssistantTexts() {
976
- return finalizeAssistantTexts(messageOrder, messagesById, lastAssistantEvent);
972
+ return finalizeAssistantTexts(messagesById, lastAssistantEvent);
973
+ },
974
+ completeTool(tool) {
975
+ const owner = toolCallsById.get(tool.parentToolCallId ?? tool.toolCallId);
976
+ if (detached || !owner?.root) return;
977
+ if (!tool.parentToolCallId) preparedToolCompletions.add(tool.toolCallId);
978
+ enqueueAgentEvent({
979
+ stream: "item",
980
+ data: projectAgentToolActivity({
981
+ ...tool,
982
+ name: tool.toolName,
983
+ phase: "result"
984
+ })
985
+ });
977
986
  },
978
987
  detach() {
979
988
  if (detached) return;
@@ -990,13 +999,11 @@ function attachEventBridge(session, options) {
990
999
  if (handledAssistantEventIds.has(event.id)) return;
991
1000
  handledAssistantEventIds.add(event.id);
992
1001
  for (const request of event.data.toolRequests ?? []) projectedToolNamesByCallId.set(request.toolCallId, request.name);
993
- const entry = ensureMessageAccumulator(messagesById, messageOrder, event.data.messageId);
1002
+ const entry = ensureMessageAccumulator(messagesById, event.data.messageId);
994
1003
  if (typeof event.data.content === "string" && event.data.content.length >= entry.text.length) entry.text = event.data.content;
995
- lastAssistantReasoningText = event.data.reasoningText ?? (joinReasoning(reasoningOrder, reasoningById) || void 0);
996
- const transcriptReasoningText = event.data.reasoningText ?? (joinReasoning(durableReasoningOrder, durableReasoningById) || void 0);
997
- reasoningOrder.length = 0;
1004
+ lastAssistantReasoningText = event.data.reasoningText ?? ([...reasoningById.values()].join("") || void 0);
1005
+ const transcriptReasoningText = event.data.reasoningText ?? ([...durableReasoningById.values()].join("") || void 0);
998
1006
  reasoningById.clear();
999
- durableReasoningOrder.length = 0;
1000
1007
  durableReasoningById.clear();
1001
1008
  unconsumedDurableReasoning = false;
1002
1009
  const chunk = {
@@ -1040,9 +1047,7 @@ function attachEventBridge(session, options) {
1040
1047
  }
1041
1048
  function markUnconsumedReasoningIncomplete() {
1042
1049
  if (unconsumedDurableReasoning) options.transcriptProjection?.journal.markReplayIncomplete();
1043
- reasoningOrder.length = 0;
1044
1050
  reasoningById.clear();
1045
- durableReasoningOrder.length = 0;
1046
1051
  durableReasoningById.clear();
1047
1052
  unconsumedDurableReasoning = false;
1048
1053
  }
@@ -1072,16 +1077,16 @@ function attachEventBridge(session, options) {
1072
1077
  compactionChain = compactionChain.then(callback, callback).catch(() => void 0);
1073
1078
  }
1074
1079
  function enqueueAgentEvent(event) {
1080
+ if (options.runId) emitAgentEvent({
1081
+ runId: options.runId,
1082
+ sessionKey: options.sessionKey,
1083
+ ...event
1084
+ });
1075
1085
  const callback = options.onAgentEvent;
1076
1086
  if (!callback) return;
1077
1087
  const invoke = () => callback(event);
1078
1088
  agentEventChain = agentEventChain.then(invoke, invoke).catch(() => void 0);
1079
1089
  }
1080
- function forwardNativeSubagentEvent(event) {
1081
- try {
1082
- options.onNativeSubagentEvent?.(event);
1083
- } catch {}
1084
- }
1085
1090
  async function awaitStableCompaction() {
1086
1091
  const idle = activeCompactionCount > 0 ? compactionIdle : void 0;
1087
1092
  if (idle) await idle;
@@ -1096,99 +1101,26 @@ function createPromptError(code, message, cause) {
1096
1101
  if (cause !== void 0) error.cause = cause;
1097
1102
  return error;
1098
1103
  }
1099
- function ensureMessageAccumulator(messagesById, messageOrder, messageId) {
1104
+ function ensureMessageAccumulator(messagesById, messageId) {
1100
1105
  let entry = messagesById.get(messageId);
1101
1106
  if (!entry) {
1102
- entry = {
1103
- messageId,
1104
- text: ""
1105
- };
1107
+ entry = { text: "" };
1106
1108
  messagesById.set(messageId, entry);
1107
- messageOrder.push(messageId);
1108
1109
  }
1109
1110
  return entry;
1110
1111
  }
1111
- function finalizeAssistantTexts(messageOrder, messagesById, event) {
1112
- const texts = messageOrder.map((messageId) => messagesById.get(messageId)?.text ?? "").filter((text) => text.length > 0);
1112
+ function finalizeAssistantTexts(messagesById, event) {
1113
+ const texts = [...messagesById.values()].map((message) => message.text).filter((text) => text.length > 0);
1113
1114
  if (texts.length > 0) return texts;
1114
1115
  if (event?.data.content) return [event.data.content];
1115
1116
  return [];
1116
1117
  }
1117
- function buildAssistantProjectionGroup(group, modelRef, resolveTimestamp, usageByApiCallId, latestUsage, forTranscript) {
1118
- const messages = group.chunks.flatMap((chunk) => {
1119
- const message = buildAssistantMessage({
1120
- event: chunk.event,
1121
- modelRef,
1122
- now: () => resolveTimestamp(chunk.event),
1123
- reasoningText: forTranscript ? chunk.transcriptReasoningText : chunk.reasoningText,
1124
- usage: resolveAssistantUsage(chunk.event, latestUsage, usageByApiCallId),
1125
- assistantTexts: forTranscript ? chunk.transcriptAssistantTexts : chunk.assistantTexts
1126
- });
1127
- return message ? [message] : [];
1128
- });
1129
- const replayIncomplete = group.chunks.some(({ event }) => hasUnprojectedAssistantReplayState(event));
1130
- const last = messages.at(-1);
1131
- if (!last) return {
1132
- message: void 0,
1133
- replayIncomplete,
1134
- toolCallIds: []
1135
- };
1136
- const narrative = [];
1137
- let terminalThinking;
1138
- const toolCallOrder = [];
1139
- const toolCallsById = /* @__PURE__ */ new Map();
1140
- for (const message of messages) for (const part of message.content) {
1141
- if (part.type === "toolCall") {
1142
- if (!toolCallsById.has(part.id)) toolCallOrder.push(part.id);
1143
- toolCallsById.set(part.id, part);
1144
- continue;
1145
- }
1146
- if (part.type === "thinking") {
1147
- terminalThinking = part;
1148
- continue;
1149
- }
1150
- const previous = narrative.at(-1);
1151
- if (part.type === "text" && previous?.type === "text") narrative[narrative.length - 1] = {
1152
- ...previous,
1153
- text: previous.text + part.text
1154
- };
1155
- else narrative.push(part);
1156
- }
1157
- const toolCalls = toolCallOrder.flatMap((id) => {
1158
- const toolCall = toolCallsById.get(id);
1159
- return toolCall ? [toolCall] : [];
1160
- });
1161
- const content = [
1162
- ...terminalThinking ? [terminalThinking] : [],
1163
- ...narrative,
1164
- ...toolCalls
1165
- ];
1166
- const toolCallIds = [...toolCallOrder];
1167
- return {
1168
- message: {
1169
- ...last,
1170
- content,
1171
- stopReason: toolCallIds.length > 0 ? "toolUse" : "stop"
1172
- },
1173
- replayIncomplete,
1174
- toolCallIds
1175
- };
1176
- }
1177
- function hasUnprojectedAssistantReplayState(event) {
1178
- return event.data.citations !== void 0 || event.data.serverTools !== void 0 || event.data.reasoningWireField !== void 0 || event.data.reasoningOpaque !== void 0 || event.data.encryptedContent !== void 0 || event.data.toolRequests?.some((request) => request.type === "custom") === true;
1179
- }
1180
1118
  function isAssistantMessageEvent(event) {
1181
1119
  return event?.type === "assistant.message";
1182
1120
  }
1183
1121
  function isRootSessionEvent(event) {
1184
1122
  return event.agentId === void 0;
1185
1123
  }
1186
- function isRootCompactionEvent(event) {
1187
- return isRootSessionEvent(event);
1188
- }
1189
- function joinReasoning(order, reasoningById) {
1190
- return order.map((reasoningId) => reasoningById.get(reasoningId) ?? "").join("");
1191
- }
1192
1124
  function splitPlanText(text) {
1193
1125
  return (text ?? "").split(/\r?\n/).map((line) => line.trim().replace(/^[-*]\s+/, "")).filter((line) => line.length > 0);
1194
1126
  }
@@ -1224,7 +1156,6 @@ async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now
1224
1156
  function deferBackgroundCompactionCleanup(params) {
1225
1157
  return (async () => {
1226
1158
  let outcome = "deadline";
1227
- let finalizationError;
1228
1159
  try {
1229
1160
  outcome = await awaitDeferredCleanupBeforeDeadline({
1230
1161
  abortSignal: params.abortSignal,
@@ -1237,12 +1168,8 @@ function deferBackgroundCompactionCleanup(params) {
1237
1168
  await cancelBackgroundCompactionBeforeTeardown(params.session);
1238
1169
  params.bridge.settleCompactionWait();
1239
1170
  }
1240
- try {
1241
- params.finalizeNativeSubagents?.();
1242
- } catch (error) {
1243
- finalizationError = toCopilotError(error);
1244
- }
1245
1171
  params.bridge.detach();
1172
+ await params.bridge.awaitAgentEventChain();
1246
1173
  try {
1247
1174
  await params.session.disconnect();
1248
1175
  } catch {}
@@ -1255,7 +1182,6 @@ function deferBackgroundCompactionCleanup(params) {
1255
1182
  await params.pool.release(params.handle);
1256
1183
  } catch {}
1257
1184
  }
1258
- if (finalizationError) throw finalizationError;
1259
1185
  return outcome;
1260
1186
  })();
1261
1187
  }
@@ -1445,6 +1371,17 @@ function isCompleteToolGroup(messages, order) {
1445
1371
  const [assistant, ...results] = messages;
1446
1372
  return assistant?.role === "assistant" && JSON.stringify(readAssistantToolCallIds(assistant)) === JSON.stringify(order) && results.length === order.length && results.every((message, index) => message.role === "toolResult" && message.toolCallId === order[index]);
1447
1373
  }
1374
+ function isSameUserTurn(candidate, current, currentRunUserKey) {
1375
+ if (candidate?.role !== "user" || !current) return false;
1376
+ if (candidate === current) return true;
1377
+ const candidateKey = candidate.idempotencyKey;
1378
+ const currentKey = current.idempotencyKey;
1379
+ if (typeof candidateKey === "string" || typeof currentKey === "string") {
1380
+ if (typeof candidateKey === "string" && typeof currentKey === "string") return candidateKey === currentKey;
1381
+ if (typeof candidateKey !== "string" || typeof currentKey === "string" || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
1382
+ }
1383
+ return candidate.timestamp === current.timestamp && userText(candidate.content) === userText(current.content);
1384
+ }
1448
1385
  //#endregion
1449
1386
  //#region extensions/copilot/src/attempt-finalize.ts
1450
1387
  async function completeCopilotAttempt(params) {
@@ -1523,22 +1460,11 @@ function includePreparedUser(messages, prepared, hidden, currentRunUserKey) {
1523
1460
  hidden: hidden || prepared.display === false,
1524
1461
  message: prepared
1525
1462
  });
1526
- if (isSamePreparedUser(messages.at(-1), projected, currentRunUserKey)) return [...messages.slice(0, -1), projected];
1463
+ if (isSameUserTurn(messages.at(-1), projected, currentRunUserKey)) return [...messages.slice(0, -1), projected];
1527
1464
  return [...messages, projected];
1528
1465
  }
1529
1466
  function removePreparedUser(messages, prepared, currentRunUserKey) {
1530
- return prepared && isSamePreparedUser(messages.at(-1), prepared, currentRunUserKey) ? messages.slice(0, -1) : messages;
1531
- }
1532
- function isSamePreparedUser(candidate, prepared, currentRunUserKey) {
1533
- if (candidate?.role !== "user") return false;
1534
- if (candidate === prepared) return true;
1535
- const candidateKey = candidate.idempotencyKey;
1536
- const preparedKey = prepared.idempotencyKey;
1537
- if (typeof candidateKey === "string" || typeof preparedKey === "string") {
1538
- if (typeof candidateKey === "string" && typeof preparedKey === "string") return candidateKey === preparedKey;
1539
- if (typeof candidateKey !== "string" || typeof preparedKey === "string" || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
1540
- }
1541
- return candidate.timestamp === prepared.timestamp && userText(candidate.content) === userText(prepared.content);
1467
+ return prepared && isSameUserTurn(messages.at(-1), prepared, currentRunUserKey) ? messages.slice(0, -1) : messages;
1542
1468
  }
1543
1469
  //#endregion
1544
1470
  //#region extensions/copilot/src/attempt-mode.ts
@@ -1552,16 +1478,6 @@ const EMPTY_PROMPT_TOOL_POLICY = { apply: () => ({
1552
1478
  callableToolNames: []
1553
1479
  }) };
1554
1480
  const SUPPORTED_TOOL_PROVIDERS = /* @__PURE__ */ new Set(["github-copilot"]);
1555
- const BASE_COPILOT_CODING_TOOL_NAMES = /* @__PURE__ */ new Set([
1556
- "edit",
1557
- "read",
1558
- "write"
1559
- ]);
1560
- const SHELL_COPILOT_CODING_TOOL_NAMES = /* @__PURE__ */ new Set([
1561
- "apply_patch",
1562
- "exec",
1563
- "process"
1564
- ]);
1565
1481
  async function createCopilotToolBridge(input) {
1566
1482
  if (!input.allowModelTools && !SUPPORTED_TOOL_PROVIDERS.has(input.modelProvider)) return {
1567
1483
  codeModeEngaged: false,
@@ -1584,8 +1500,8 @@ async function createCopilotToolBridge(input) {
1584
1500
  sourceTools: []
1585
1501
  };
1586
1502
  const toolSurfaceRuntime = createAgentHarnessToolSurfaceRuntime({
1587
- abortSignal: input.abortSignal,
1588
- agentId: attemptParams.sandboxAgentId ?? input.agentId,
1503
+ abortSignal: attemptParams.abortSignal,
1504
+ agentId: input.agentId,
1589
1505
  config: attemptParams.config,
1590
1506
  codeModeOverride: attemptParams.codeModeOverride,
1591
1507
  disableTools: attemptParams.disableTools,
@@ -1597,11 +1513,12 @@ async function createCopilotToolBridge(input) {
1597
1513
  modelId: input.modelId,
1598
1514
  modelProvider: input.modelProvider,
1599
1515
  modelToolsEnabled: true,
1516
+ supportsDeferredToolCalls: false,
1600
1517
  prompt: attemptParams.prompt,
1601
1518
  runId: attemptParams.runId,
1602
1519
  runtimeToolAllowlist: toolPlan.runtimeToolAllowlist,
1603
1520
  sessionId: input.sessionId,
1604
- sessionKey: attemptParams.sandboxSessionKey ?? attemptParams.sessionKey ?? input.sessionKey,
1521
+ sessionKey: attemptParams.sessionKey,
1605
1522
  scheduledToolPolicy: attemptParams.scheduledToolPolicy,
1606
1523
  sourceReplyDeliveryMode: attemptParams.sourceReplyDeliveryMode,
1607
1524
  toolsAllow: attemptParams.toolsAllow
@@ -1610,30 +1527,16 @@ async function createCopilotToolBridge(input) {
1610
1527
  ...toolPlan,
1611
1528
  runtimeToolAllowlist: toolSurfaceRuntime.runtimeToolAllowlist
1612
1529
  }, toolSurfaceRuntime);
1613
- let sourceTools;
1614
- const boundSourceTools = /* @__PURE__ */ new Set();
1615
1530
  const hostCapabilities = attemptParams.hostCapabilities;
1616
1531
  if (!hostCapabilities) throw new Error("Copilot attempt tools require host-bound capabilities.");
1617
1532
  const bindingCwd = toolOptions.cwd ?? toolOptions.workspaceDir;
1618
1533
  const bindingOptions = bindingCwd ? { cwd: bindingCwd } : void 0;
1619
- try {
1620
- let boundTools;
1621
- if (input.createOpenClawCodingTools) {
1622
- const constructedTools = await input.createOpenClawCodingTools(toolOptions);
1623
- if (!Array.isArray(constructedTools)) throw new Error("createOpenClawCodingTools must return an array of tools");
1624
- boundTools = hostCapabilities.bindToolSurface(constructedTools, bindingOptions);
1625
- } else {
1626
- const createToolSurface = hostCapabilities.createToolSurface;
1627
- if (!createToolSurface) throw new Error("Copilot tool construction requires a current host capability");
1628
- boundTools = createToolSurface(toolOptions, bindingOptions);
1629
- }
1630
- sourceTools = boundTools;
1631
- for (const tool of boundTools) boundSourceTools.add(tool);
1632
- } catch (error) {
1633
- throw createError(`[copilot-tool-bridge] createOpenClawCodingTools failed: ${toStringifiedError(error).message}`, error);
1634
- }
1635
- const plannedSourceTools = filterCopilotToolsForConstructionPlan(applyEmbeddedAttemptToolsAllow(sourceTools, toolSurfaceRuntime.runtimeToolAllowlist, { toolMeta: (tool) => getPluginToolMeta(tool) ?? readInlinePluginToolMeta(tool) }), toolPlan.codingToolConstructionPlan, { preserveToolNames: toolSurfaceRuntime.runtimeToolAllowlist });
1636
- const compactedTools = toolSurfaceRuntime.compactTools(plannedSourceTools, { localModelLeanApplied: true });
1534
+ const createToolSurface = hostCapabilities.createToolSurface;
1535
+ if (!createToolSurface) throw new Error("Copilot tool construction requires a current host capability");
1536
+ const sourceTools = createToolSurface(toolOptions, bindingOptions);
1537
+ const boundSourceTools = new Set(sourceTools);
1538
+ const allowedSourceTools = applyEmbeddedAttemptToolsAllow(sourceTools, toolSurfaceRuntime.runtimeToolAllowlist, { toolMeta: getPluginToolMeta });
1539
+ const compactedTools = toolSurfaceRuntime.compactTools(allowedSourceTools, { localModelLeanApplied: true });
1637
1540
  const newlyConstructedTools = compactedTools.tools.filter((tool) => !boundSourceTools.has(tool));
1638
1541
  const boundNewlyConstructedTools = newlyConstructedTools.length > 0 ? hostCapabilities.bindToolSurface(newlyConstructedTools, bindingOptions) : newlyConstructedTools;
1639
1542
  if (boundNewlyConstructedTools.length !== newlyConstructedTools.length) throw new Error("Copilot host capability changed the tool surface length.");
@@ -1670,7 +1573,8 @@ async function createCopilotToolBridge(input) {
1670
1573
  const directToolNames = new Set(result.tools.map((tool) => tool.name));
1671
1574
  return {
1672
1575
  tools: sdkTools.filter((tool) => directToolNames.has(tool.name)),
1673
- callableToolNames: result.callableToolNames
1576
+ callableToolNames: result.callableToolNames,
1577
+ toolSchemaDirectoryPrompt: result.toolSchemaDirectoryPrompt
1674
1578
  };
1675
1579
  }
1676
1580
  },
@@ -1684,8 +1588,8 @@ async function createCopilotToolBridge(input) {
1684
1588
  */
1685
1589
  function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
1686
1590
  const a = input.attemptParams;
1687
- const sandboxSessionKey = a.sandboxSessionKey?.trim() || a.sessionKey?.trim() || input.sessionKey || input.sessionId;
1688
- const liveSessionKey = a.sessionKey ?? input.sessionKey;
1591
+ const sandboxSessionKey = a.sandboxSessionKey?.trim() || a.sessionKey?.trim() || input.sessionId;
1592
+ const liveSessionKey = a.sessionKey;
1689
1593
  const runSessionKey = liveSessionKey && liveSessionKey !== sandboxSessionKey ? liveSessionKey : void 0;
1690
1594
  const workspaceDir = input.workspaceDir ?? a.workspaceDir;
1691
1595
  const cwd = input.cwd ?? a.cwd;
@@ -1721,7 +1625,7 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
1721
1625
  spawnWorkspaceDir: input.spawnWorkspaceDir,
1722
1626
  config: toolSurfaceRuntime?.config ?? a.config,
1723
1627
  skillsSnapshot: a.skillsSnapshot,
1724
- abortSignal: input.abortSignal,
1628
+ abortSignal: a.abortSignal,
1725
1629
  modelProvider: input.modelProvider,
1726
1630
  modelId: input.modelId,
1727
1631
  includeCoreTools: toolPlan.includeCoreTools,
@@ -1782,7 +1686,7 @@ function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution)
1782
1686
  };
1783
1687
  const failureResult = (executedArgs, invocation, startedAt, message, error, executionStarted) => {
1784
1688
  const errorMessage = toStringifiedError(error).message;
1785
- input.attemptParams.observeToolTerminal?.({
1689
+ const terminal = input.attemptParams.observeToolTerminal?.({
1786
1690
  toolCallId: invocation.toolCallId,
1787
1691
  toolName: sourceTool.name,
1788
1692
  result: error,
@@ -1805,7 +1709,8 @@ function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution)
1805
1709
  notifyToolCompleted({
1806
1710
  toolName: sourceTool.name,
1807
1711
  toolCallId: invocation.toolCallId,
1808
- args: toToolStartArgs(executedArgs),
1712
+ args: toToolStartArgs(terminal?.executedArguments ?? executedArgs),
1713
+ isError: true,
1809
1714
  error: errorMessage,
1810
1715
  startedAt
1811
1716
  });
@@ -1813,21 +1718,10 @@ function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution)
1813
1718
  };
1814
1719
  const executeOnce = async (args, invocation) => {
1815
1720
  const startedAt = Date.now();
1816
- if (input.abortSignal?.aborted) {
1721
+ if (input.attemptParams.abortSignal?.aborted) {
1817
1722
  const error = /* @__PURE__ */ new Error("[copilot-tool-bridge] aborted before execution");
1818
1723
  return failureResult(args, invocation, startedAt, error.message, error, false);
1819
1724
  }
1820
- try {
1821
- await input.beforeExecute?.({
1822
- args,
1823
- invocation,
1824
- sourceTool,
1825
- toolCallId: invocation.toolCallId,
1826
- toolName: sourceTool.name
1827
- });
1828
- } catch (error) {
1829
- return failureResult(args, invocation, startedAt, `[copilot-tool-bridge] beforeExecute failed for tool '${sourceTool.name}': ${toStringifiedError(error).message}`, error, false);
1830
- }
1831
1725
  let preparedArgs;
1832
1726
  try {
1833
1727
  preparedArgs = sourceTool.prepareArguments ? sourceTool.prepareArguments(args) : args;
@@ -1836,7 +1730,7 @@ function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution)
1836
1730
  }
1837
1731
  let result;
1838
1732
  try {
1839
- result = await sourceTool.execute(invocation.toolCallId, preparedArgs, input.abortSignal, void 0);
1733
+ result = await sourceTool.execute(invocation.toolCallId, preparedArgs, input.attemptParams.abortSignal, void 0);
1840
1734
  } catch (error) {
1841
1735
  return failureResult(preparedArgs, invocation, startedAt, `[copilot-tool-bridge] tool '${sourceTool.name}' failed: ${toStringifiedError(error).message}`, error, true);
1842
1736
  }
@@ -1847,7 +1741,7 @@ function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution)
1847
1741
  isError: resultIsError
1848
1742
  });
1849
1743
  const resultError = resultIsError ? extractToolErrorMessage(sanitizedResult) : void 0;
1850
- input.attemptParams.observeToolTerminal?.({
1744
+ const terminal = input.attemptParams.observeToolTerminal?.({
1851
1745
  toolCallId: invocation.toolCallId,
1852
1746
  toolName: sourceTool.name,
1853
1747
  result,
@@ -1861,8 +1755,9 @@ function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution)
1861
1755
  notifyToolCompleted({
1862
1756
  toolName: sourceTool.name,
1863
1757
  toolCallId: invocation.toolCallId,
1864
- args: toToolStartArgs(preparedArgs),
1758
+ args: toToolStartArgs(terminal?.executedArguments ?? preparedArgs),
1865
1759
  result: sanitizedResult,
1760
+ isError: resultIsError,
1866
1761
  ...resultError ? { error: resultError } : {},
1867
1762
  startedAt
1868
1763
  });
@@ -1889,12 +1784,12 @@ async function executeCatalogTool(input, params) {
1889
1784
  try {
1890
1785
  preparedArgs = sourceTool.prepareArguments ? sourceTool.prepareArguments(params.input) : params.input;
1891
1786
  executionStarted = true;
1892
- const result = await sourceTool.execute(params.toolCallId, preparedArgs, params.signal ?? input.abortSignal, params.onUpdate);
1787
+ const result = await sourceTool.execute(params.toolCallId, preparedArgs, params.signal ?? input.attemptParams.abortSignal, params.onUpdate);
1893
1788
  const sanitizedResult = sanitizeToolResult(result);
1894
1789
  const isError = isToolResultError(sanitizedResult);
1895
1790
  const error = isError ? extractToolErrorMessage(sanitizedResult) ?? "tool returned an error" : void 0;
1896
1791
  terminalObserved = true;
1897
- input.attemptParams?.observeToolTerminal?.({
1792
+ const terminal = input.attemptParams?.observeToolTerminal?.({
1898
1793
  toolCallId: params.toolCallId,
1899
1794
  toolName: params.toolName,
1900
1795
  result,
@@ -1912,15 +1807,17 @@ async function executeCatalogTool(input, params) {
1912
1807
  await input.onToolCompleted?.({
1913
1808
  toolName: params.toolName,
1914
1809
  toolCallId: params.toolCallId,
1915
- args: toToolStartArgs(preparedArgs),
1810
+ parentToolCallId: params.parentToolCallId,
1811
+ args: toToolStartArgs(terminal?.executedArguments ?? preparedArgs),
1916
1812
  result: sanitizedResult,
1813
+ isError,
1917
1814
  ...error ? { error } : {},
1918
1815
  startedAt
1919
1816
  });
1920
1817
  return result;
1921
1818
  } catch (error) {
1922
1819
  const message = toStringifiedError(error).message;
1923
- if (!terminalObserved) input.attemptParams?.observeToolTerminal?.({
1820
+ if (!terminalObserved) preparedArgs = (input.attemptParams?.observeToolTerminal?.({
1924
1821
  toolCallId: params.toolCallId,
1925
1822
  toolName: params.toolName,
1926
1823
  result: error,
@@ -1929,7 +1826,7 @@ async function executeCatalogTool(input, params) {
1929
1826
  outcome: "failure",
1930
1827
  failure: { error: message },
1931
1828
  ...ownerMutation ? { ownerMutation } : {}
1932
- });
1829
+ }))?.executedArguments ?? preparedArgs;
1933
1830
  const failure = sanitizeToolResult({
1934
1831
  content: [{
1935
1832
  type: "text",
@@ -1948,7 +1845,9 @@ async function executeCatalogTool(input, params) {
1948
1845
  await input.onToolCompleted?.({
1949
1846
  toolName: params.toolName,
1950
1847
  toolCallId: params.toolCallId,
1848
+ parentToolCallId: params.parentToolCallId,
1951
1849
  args: toToolStartArgs(preparedArgs),
1850
+ isError: true,
1952
1851
  error: message,
1953
1852
  startedAt
1954
1853
  });
@@ -1965,38 +1864,10 @@ function createFailureResult(message, error) {
1965
1864
  textResultForLlm: message
1966
1865
  };
1967
1866
  }
1968
- function createError(message, cause) {
1969
- const error = new Error(message);
1970
- error.cause = cause;
1971
- return error;
1972
- }
1973
- /**
1974
- * Mirrors PI's `shouldForceMessageTool` semantics: a message tool is
1975
- * forced when the caller asked for it explicitly or when the source
1976
- * reply delivery mode is `message_tool_only`, but never when
1977
- * `disableMessageTool` is set (the suppress flag always wins). Compare
1978
- * `src/agents/pi-embedded-runner/run/attempt.ts:1361-1366` and the
1979
- * codex equivalent at
1980
- * `extensions/codex/src/app-server/run-attempt.ts:4253-4258`.
1981
- */
1982
1867
  function shouldForceCopilotMessageTool(params) {
1983
1868
  if (params.disableMessageTool === true) return false;
1984
1869
  return params.forceMessageTool === true || params.sourceReplyDeliveryMode === "message_tool_only";
1985
1870
  }
1986
- function filterCopilotToolsForConstructionPlan(tools, plan, options = {}) {
1987
- if (plan.includeBaseCodingTools && plan.includeShellTools) return tools;
1988
- const preserveToolNames = new Set(options.preserveToolNames);
1989
- return tools.filter((tool) => {
1990
- if (preserveToolNames.has(tool.name)) return true;
1991
- if (!plan.includeBaseCodingTools && BASE_COPILOT_CODING_TOOL_NAMES.has(tool.name)) return false;
1992
- if (!plan.includeShellTools && SHELL_COPILOT_CODING_TOOL_NAMES.has(tool.name)) return false;
1993
- return true;
1994
- });
1995
- }
1996
- function readInlinePluginToolMeta(tool) {
1997
- const pluginId = tool.pluginId;
1998
- return typeof pluginId === "string" && pluginId.trim() ? { pluginId } : void 0;
1999
- }
2000
1871
  function findDuplicateToolNames(sourceTools) {
2001
1872
  const counts = /* @__PURE__ */ new Map();
2002
1873
  for (const sourceTool of sourceTools) {
@@ -2117,6 +1988,7 @@ function buildCopilotPromptGuidance(params) {
2117
1988
  }).join("\n") : void 0;
2118
1989
  return [
2119
1990
  COPILOT_HARNESS_IDENTITY,
1991
+ params.toolSchemaDirectoryPrompt,
2120
1992
  callableTools.has(SKILL_WORKSHOP_TOOL_NAME) ? buildSkillWorkshopPromptSection().join("\n") : void 0,
2121
1993
  delegationGuidance,
2122
1994
  buildHarnessVisibleReplyGuidance({
@@ -2226,26 +2098,6 @@ const COPILOT_BOOTSTRAP_CONTEXT_ORDER = /* @__PURE__ */ new Map([
2226
2098
  ["user.md", 60],
2227
2099
  ["memory.md", 70]
2228
2100
  ]);
2229
- /**
2230
- * Loads OpenClaw workspace bootstrap files (IDENTITY.md, SOUL.md,
2231
- * HEARTBEAT.md, USER.md, BOOTSTRAP.md, MEMORY.md, ...) using
2232
- * the shared core helper PI and codex both use, then renders them as a
2233
- * single string suitable for `SessionConfig.systemMessage.content` on
2234
- * the Copilot SDK.
2235
- *
2236
- * Returns `instructions: undefined` when there are no relevant files
2237
- * (after filtering out SDK-native docs) so the caller can omit the
2238
- * `systemMessage` field entirely rather than passing an empty string.
2239
- *
2240
- * Mirrors codex's `buildCodexWorkspaceBootstrapContext` /
2241
- * `renderCodexWorkspaceBootstrapInstructions` pair
2242
- * (`extensions/codex/src/app-server/run-attempt.ts:2877,3047`). The
2243
- * shape divergence — codex returns instructions inside the same object
2244
- * as bootstrapFiles+contextFiles for its developerInstructions field;
2245
- * copilot exposes the rendered string for SDK `systemMessage` — is the
2246
- * intended difference between the two runtimes' system-prompt
2247
- * surfaces.
2248
- */
2249
2101
  async function resolveCopilotWorkspaceBootstrapContext(params) {
2250
2102
  const { attempt } = params;
2251
2103
  const workspaceDir = readResolvedWorkspacePath(attempt.workspaceDir);
@@ -2283,17 +2135,6 @@ async function resolveCopilotWorkspaceBootstrapContext(params) {
2283
2135
  };
2284
2136
  }
2285
2137
  }
2286
- /**
2287
- * Rewrites context-file paths from a source workspace root to a
2288
- * target workspace root, mirroring PI's
2289
- * `remapInjectedContextFilesToWorkspace`
2290
- * (`src/agents/pi-embedded-runner/run/attempt.ts:603`). Files whose
2291
- * resolved relative path escapes the source workspace (parent
2292
- * traversal or absolute) are left untouched so we never pretend a
2293
- * file lives inside the sandbox when it does not. Intentionally local
2294
- * to the Copilot extension (codex keeps similar helpers extension-local
2295
- * rather than importing from PI).
2296
- */
2297
2138
  function remapCopilotBootstrapContextFiles(params) {
2298
2139
  if (params.sourceWorkspaceDir === params.targetWorkspaceDir) return params.files;
2299
2140
  return params.files.map((file) => {
@@ -2308,16 +2149,6 @@ function remapCopilotBootstrapContextFiles(params) {
2308
2149
  function isRelativePathInsideOrEqual(relativePath) {
2309
2150
  return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
2310
2151
  }
2311
- /**
2312
- * Renders bootstrap context files into a single string for
2313
- * `SessionConfig.systemMessage.content` (append mode). Returns
2314
- * `undefined` when no relevant files remain after filtering, so the
2315
- * caller can skip setting `systemMessage` altogether.
2316
- *
2317
- * Files whose basename matches a doc the Copilot SDK already loads
2318
- * natively (see {@link COPILOT_NATIVE_PROJECT_DOC_BASENAMES}) are
2319
- * dropped to avoid duplication with SDK-managed sections.
2320
- */
2321
2152
  function renderCopilotWorkspaceBootstrapInstructions(contextFiles) {
2322
2153
  const files = contextFiles.filter((file) => {
2323
2154
  const baseName = getCopilotContextFileBasename(file.path);
@@ -2400,6 +2231,7 @@ async function createCopilotSessionSetup(params) {
2400
2231
  return buildCopilotPromptGuidance({
2401
2232
  attempt: input,
2402
2233
  callableToolNames: promptPolicyResult.callableToolNames,
2234
+ toolSchemaDirectoryPrompt: promptPolicyResult.toolSchemaDirectoryPrompt,
2403
2235
  requireExplicitMessageTarget: promptToolPolicy.requireExplicitMessageTarget,
2404
2236
  workspaceBootstrapInstructions: workspaceBootstrap.instructions
2405
2237
  });
@@ -2447,18 +2279,15 @@ async function createCopilotSessionSetup(params) {
2447
2279
  signal
2448
2280
  });
2449
2281
  })();
2450
- const sessionConfig = createSessionConfig(attemptInput, modelRef.id, promptTools, poolAcquire.auth, sessionProvider, finalDeveloperInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, userInputBridge?.onUserInputRequest, {
2282
+ const buildSessionConfig = (provider) => createSessionConfig(attemptInput, modelRef.id, promptTools, poolAcquire.auth, provider, finalDeveloperInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, userInputBridge?.onUserInputRequest, {
2451
2283
  hooksBridgeOptions: hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0,
2452
2284
  includeAskUser,
2453
2285
  operation: operation ?? "attempt"
2454
2286
  });
2287
+ const sessionConfig = buildSessionConfig(sessionProvider);
2455
2288
  return {
2456
2289
  attemptInput,
2457
- compactionSessionConfig: byokProxy ? createSessionConfig(attemptInput, modelRef.id, promptTools, poolAcquire.auth, poolAcquire.provider, finalDeveloperInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, userInputBridge?.onUserInputRequest, {
2458
- hooksBridgeOptions: hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0,
2459
- includeAskUser,
2460
- operation: operation ?? "attempt"
2461
- }) : sessionConfig,
2290
+ compactionSessionConfig: byokProxy ? buildSessionConfig(poolAcquire.provider) : sessionConfig,
2462
2291
  emitLlmInput,
2463
2292
  hasNativePromptHook,
2464
2293
  sessionConfig,
@@ -2888,151 +2717,6 @@ function readIdempotencyKey(message) {
2888
2717
  function isCurrentJournalIdentity(key, params) {
2889
2718
  return key === `${params.attempt.runId}:user` || key.startsWith(`copilot-sdk:${params.sdkSessionId}:`);
2890
2719
  }
2891
- function isSameUserTurn(candidate, current, currentRunUserKey) {
2892
- if (candidate?.role !== "user" || !current) return false;
2893
- if (candidate === current) return true;
2894
- const candidateKey = candidate.idempotencyKey;
2895
- const currentKey = current.idempotencyKey;
2896
- if (typeof candidateKey === "string" || typeof currentKey === "string") {
2897
- if (typeof candidateKey === "string" && typeof currentKey === "string") return candidateKey === currentKey;
2898
- if (typeof candidateKey !== "string" || typeof currentKey === "string" || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
2899
- }
2900
- return candidate.timestamp === current.timestamp && userText(candidate.content) === userText(current.content);
2901
- }
2902
- //#endregion
2903
- //#region extensions/copilot/src/native-subagent-task-mirror.ts
2904
- const COPILOT_NATIVE_SUBAGENT_TASK_KIND = "copilot-native";
2905
- const COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX = "copilot-agent:";
2906
- function createCopilotNativeSubagentTaskMirror(params) {
2907
- if (!params.scope) return;
2908
- return new CopilotNativeSubagentTaskMirror({
2909
- agentId: params.agentId,
2910
- now: params.now
2911
- }, createAgentHarnessTaskRuntime({
2912
- runtime: "subagent",
2913
- taskKind: COPILOT_NATIVE_SUBAGENT_TASK_KIND,
2914
- scope: params.scope,
2915
- runIdPrefix: COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX
2916
- }));
2917
- }
2918
- var CopilotNativeSubagentTaskMirror = class {
2919
- constructor(params, runtime) {
2920
- this.params = params;
2921
- this.runtime = runtime;
2922
- this.runIdByAgentId = /* @__PURE__ */ new Map();
2923
- this.runIdByToolCallId = /* @__PURE__ */ new Map();
2924
- this.activeRuns = /* @__PURE__ */ new Map();
2925
- this.now = params.now ?? Date.now;
2926
- }
2927
- handleEvent(event) {
2928
- const toolCallId = event.data.toolCallId.trim();
2929
- if (!toolCallId) return;
2930
- const runId = this.resolveRunId(event);
2931
- if (event.type === "subagent.started") {
2932
- this.handleStarted(event, runId, toolCallId);
2933
- return;
2934
- }
2935
- if (event.type === "subagent.completed") {
2936
- this.handleCompleted(event, runId);
2937
- return;
2938
- }
2939
- this.handleFailed(event, runId);
2940
- }
2941
- finalizeActiveRuns() {
2942
- const eventAt = this.now();
2943
- let failure;
2944
- for (const runId of this.activeRuns.keys()) try {
2945
- this.finalizeRun({
2946
- runId,
2947
- status: "cancelled",
2948
- endedAt: eventAt,
2949
- lastEventAt: eventAt,
2950
- error: "Subagent ended with its parent attempt.",
2951
- progressSummary: "Subagent cancelled with its parent attempt.",
2952
- terminalSummary: "Subagent cancelled."
2953
- });
2954
- } catch (error) {
2955
- failure ??= { error };
2956
- }
2957
- if (failure) throw failure.error;
2958
- }
2959
- handleStarted(event, runId, toolCallId) {
2960
- const agentId = event.agentId?.trim();
2961
- if (agentId ? this.runIdByAgentId.get(agentId) : this.runIdByToolCallId.get(toolCallId)) return;
2962
- const eventAt = this.now();
2963
- const label = event.data.agentDisplayName.trim() || event.data.agentName.trim();
2964
- const task = event.data.agentDescription.trim() || `Subagent ${label}`;
2965
- const taskRecord = this.runtime.tryCreateRunningTaskRun({
2966
- sourceId: toolCallId,
2967
- agentId: this.params.agentId,
2968
- runId,
2969
- label: label || "Subagent",
2970
- task,
2971
- notifyPolicy: "silent",
2972
- deliveryStatus: "not_applicable",
2973
- preferMetadata: true,
2974
- startedAt: eventAt,
2975
- lastEventAt: eventAt,
2976
- progressSummary: "Subagent started."
2977
- });
2978
- if (!taskRecord) return;
2979
- if (agentId) this.runIdByAgentId.set(agentId, runId);
2980
- else this.runIdByToolCallId.set(toolCallId, runId);
2981
- this.activeRuns.set(runId, { taskId: taskRecord.taskId });
2982
- }
2983
- handleCompleted(event, runId) {
2984
- const eventAt = this.now();
2985
- this.finalizeRun({
2986
- runId,
2987
- status: "succeeded",
2988
- endedAt: eventAt,
2989
- lastEventAt: eventAt,
2990
- progressSummary: "Subagent completed.",
2991
- terminalSummary: buildCompletionSummary(event)
2992
- });
2993
- }
2994
- handleFailed(event, runId) {
2995
- const eventAt = this.now();
2996
- this.finalizeRun({
2997
- runId,
2998
- status: "failed",
2999
- endedAt: eventAt,
3000
- lastEventAt: eventAt,
3001
- error: event.data.error,
3002
- progressSummary: "Subagent failed.",
3003
- terminalSummary: "Subagent failed."
3004
- });
3005
- }
3006
- finalizeRun(params) {
3007
- const run = this.activeRuns.get(params.runId);
3008
- if (!run) return;
3009
- run.terminal ??= params;
3010
- const matchesRun = (task) => task.taskId === run.taskId && task.runId === params.runId;
3011
- const before = this.runtime.listTaskRecords().find(matchesRun);
3012
- if (!before || before.status !== "queued" && before.status !== "running") {
3013
- this.activeRuns.delete(params.runId);
3014
- return;
3015
- }
3016
- const current = this.runtime.finalizeTaskRunByRunId(run.terminal).find(matchesRun) ?? this.runtime.listTaskRecords().find(matchesRun);
3017
- if (current?.status === "queued" || current?.status === "running") throw new Error(`Native subagent task finalization did not persist: ${params.runId}`);
3018
- this.activeRuns.delete(params.runId);
3019
- }
3020
- resolveRunId(event) {
3021
- const agentId = event.agentId?.trim();
3022
- if (agentId) {
3023
- const existing = this.runIdByAgentId.get(agentId);
3024
- if (existing) return existing;
3025
- }
3026
- const existing = this.runIdByToolCallId.get(event.data.toolCallId);
3027
- if (existing) return existing;
3028
- const identity = agentId || event.data.toolCallId.trim();
3029
- return `${COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX}${identity}`;
3030
- }
3031
- };
3032
- function buildCompletionSummary(event) {
3033
- const details = [event.data.totalToolCalls !== void 0 ? `${event.data.totalToolCalls} tool calls` : void 0, event.data.totalTokens !== void 0 ? `${event.data.totalTokens} tokens` : void 0].filter((value) => value !== void 0);
3034
- return details.length > 0 ? `Subagent completed (${details.join(", ")}).` : "Subagent completed.";
3035
- }
3036
2720
  //#endregion
3037
2721
  //#region extensions/copilot/src/attempt-execution.ts
3038
2722
  async function runCopilotExecution(context) {
@@ -3055,11 +2739,6 @@ async function runCopilotExecution(context) {
3055
2739
  let bridge;
3056
2740
  let transcriptJournal;
3057
2741
  let initialSdkUserValidated = false;
3058
- const nativeSubagentTaskMirror = createCopilotNativeSubagentTaskMirror({
3059
- agentId: sessionAgentId,
3060
- now,
3061
- scope: input.agentHarnessTaskRuntimeScope
3062
- });
3063
2742
  let activeRunHandleRef;
3064
2743
  let userInputBridgeRef;
3065
2744
  let cleanupToolBridge;
@@ -3173,13 +2852,11 @@ async function runCopilotExecution(context) {
3173
2852
  modelId: modelRef.id,
3174
2853
  agentId: readNonEmptyString(params.agentId) ?? "copilot",
3175
2854
  sessionId: readNonEmptyString(input.sessionId) ?? "copilot-session",
3176
- sessionKey: readNonEmptyString(input.sessionKey),
3177
2855
  agentDir: readNonEmptyString(input.agentDir),
3178
2856
  workspaceDir: effectiveWorkspaceDir,
3179
2857
  cwd: effectiveCwd,
3180
2858
  sandbox,
3181
2859
  spawnWorkspaceDir: sandboxAwareSpawnWorkspaceDir,
3182
- abortSignal: params.abortSignal,
3183
2860
  attemptParams: observeToolTerminal ? {
3184
2861
  ...input,
3185
2862
  observeToolTerminal
@@ -3190,15 +2867,11 @@ async function runCopilotExecution(context) {
3190
2867
  yieldDetected = true;
3191
2868
  yieldAcknowledgment = acknowledgment;
3192
2869
  },
3193
- onToolCompleted: async ({ args, error, result, startedAt, toolCallId, toolName }) => {
3194
- const acceptedSessionSpawnDetails = toolName === "sessions_spawn" && !error ? asOptionalRecord(asOptionalRecord(result)?.details) : void 0;
3195
- const runId = normalizeOptionalString(acceptedSessionSpawnDetails?.runId);
3196
- const childSessionKey = normalizeOptionalString(acceptedSessionSpawnDetails?.childSessionKey);
3197
- if (acceptedSessionSpawnDetails?.status === "accepted" && runId && childSessionKey) acceptedSessionSpawns.push({
3198
- runId,
3199
- childSessionKey,
3200
- expectsCompletionMessage: acceptedSessionSpawnDetails.expectsCompletionMessage === true
3201
- });
2870
+ onToolCompleted: async (completion) => {
2871
+ bridge?.completeTool(completion);
2872
+ const { args, error, result, startedAt, toolCallId, toolName } = completion;
2873
+ const acceptedSessionSpawn = toolName === "sessions_spawn" && !completion.isError ? normalizeAcceptedSessionSpawnResult(result) : null;
2874
+ if (acceptedSessionSpawn) acceptedSessionSpawns.push(acceptedSessionSpawn);
3202
2875
  await runAgentHarnessAfterToolCallHook({
3203
2876
  toolName,
3204
2877
  toolCallId,
@@ -3293,9 +2966,10 @@ async function runCopilotExecution(context) {
3293
2966
  sdkSessionId
3294
2967
  });
3295
2968
  bridge = attachEventBridge(session, {
2969
+ runId: input.runId,
2970
+ sessionKey: input.sessionKey,
3296
2971
  onAssistantDelta: settledToolFinalization ? void 0 : input.onAssistantDelta,
3297
2972
  onAgentEvent: settledToolFinalization ? void 0 : input.onAgentEvent,
3298
- onNativeSubagentEvent: (event) => nativeSubagentTaskMirror?.handleEvent(event),
3299
2973
  onContextCompacted: () => {
3300
2974
  computerContextEpoch.value += 1;
3301
2975
  delete computerContextEpoch.frameToolCallId;
@@ -3425,7 +3099,6 @@ async function runCopilotExecution(context) {
3425
3099
  cleanupToolBridge,
3426
3100
  cleanupByokProxy,
3427
3101
  deleteSessionOnIncompleteCleanup: nativeSessionCreatedFresh && initialUserValidated,
3428
- finalizeNativeSubagents: () => nativeSubagentTaskMirror?.finalizeActiveRuns(),
3429
3102
  handle,
3430
3103
  pool: deps.pool,
3431
3104
  sdkSessionId,
@@ -3445,15 +3118,10 @@ async function runCopilotExecution(context) {
3445
3118
  params.abortSignal?.removeEventListener("abort", onAbort);
3446
3119
  } else {
3447
3120
  await bridge?.awaitCompactionChain();
3121
+ bridge?.detach();
3448
3122
  await bridge?.awaitAgentEventChain();
3449
- try {
3450
- nativeSubagentTaskMirror?.finalizeActiveRuns();
3451
- } catch (error) {
3452
- promptError ??= toCopilotError(error);
3453
- }
3454
3123
  cleanupToolBridge?.();
3455
3124
  await cleanupByokProxy?.();
3456
- bridge?.detach();
3457
3125
  params.abortSignal?.removeEventListener("abort", onAbort);
3458
3126
  if (session) try {
3459
3127
  await session.disconnect();