@openclaw/copilot 2026.9.7 → 2026.10.1-beta.1

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,16 +1,19 @@
1
- import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-BAWs53-w.mjs";
2
- import { n as normalizeCopilotUsage, r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.mjs";
3
- import { asNonArrayRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
1
+ import { a as createCopilotByokProxy, i as createPromptError, n as resolveCopilotProvider, o as createCopilotByokAuth, s as resolveCopilotAuth } from "./harness-BeLT-JyA.mjs";
2
+ import { n as normalizeCopilotUsage, r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge--rLPdCvV.mjs";
3
+ import { asNonArrayRecord, asOptionalObjectRecord, asOptionalRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
4
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
+ import { raceWithTimeout, withTimeout } from "openclaw/plugin-sdk/time-runtime";
6
7
  import { formatErrorMessage, toErrorObject, toStringifiedError, toStringifiedError as toCopilotError } from "openclaw/plugin-sdk/error-runtime";
8
+ import { createDeferred } from "openclaw/plugin-sdk/concurrency-runtime";
7
9
  import { parseDateStringTimestampMs } from "openclaw/plugin-sdk/number-runtime";
8
10
  import { createAgentHarnessToolSurfaceRuntime, normalizeAcceptedSessionSpawnResult } from "openclaw/plugin-sdk/agent-harness-tool-runtime";
9
11
  import fsp from "node:fs/promises";
10
12
  import { resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
11
13
  import { convertMcpCallToolResult } from "@github/copilot-sdk";
14
+ import { textResult } from "openclaw/plugin-sdk/tool-results";
12
15
  import { isDeepStrictEqual } from "node:util";
13
- import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
16
+ import { createDeferred as createDeferred$1 } from "openclaw/plugin-sdk/extension-shared";
14
17
  import { appendSessionTranscriptMessageByIdentityStrict, appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity, readVisibleSessionTranscriptMessageEntries } from "openclaw/plugin-sdk/session-transcript-runtime";
15
18
  //#region extensions/copilot/src/attempt-types.ts
16
19
  const BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS = 5e3;
@@ -166,25 +169,22 @@ const MISSING_SESSION_MESSAGE_PATTERNS = [
166
169
  /\bsession .* does not exist\b/i,
167
170
  /\bno such session\b/i
168
171
  ];
169
- function readErrorField(error, key) {
170
- if (!error || typeof error !== "object") return;
171
- return error[key];
172
- }
173
172
  function classifyResumeFailure(error) {
174
- if (readErrorField(error, "status") === 404) return {
173
+ const record = asOptionalObjectRecord(error);
174
+ if (record?.status === 404) return {
175
175
  recoverable: true,
176
176
  kind: "missing"
177
177
  };
178
- if (readErrorField(error, "statusCode") === 404) return {
178
+ if (record?.statusCode === 404) return {
179
179
  recoverable: true,
180
180
  kind: "missing"
181
181
  };
182
- const code = readErrorField(error, "code");
182
+ const code = record?.code;
183
183
  if (typeof code === "string" && MISSING_SESSION_CODES.has(code)) return {
184
184
  recoverable: true,
185
185
  kind: "missing"
186
186
  };
187
- const message = readErrorField(error, "message");
187
+ const message = record?.message;
188
188
  if (typeof message === "string" && MISSING_SESSION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return {
189
189
  recoverable: true,
190
190
  kind: "missing"
@@ -295,12 +295,6 @@ function createResult(params, state) {
295
295
  ...state.yieldAcknowledgment ? { yieldAcknowledgment: state.yieldAcknowledgment } : {}
296
296
  };
297
297
  }
298
- function createPromptError$1(code, message, cause) {
299
- const error = new Error(message);
300
- error.code = code;
301
- if (cause !== void 0) error.cause = cause;
302
- return error;
303
- }
304
298
  function createSessionConfig(params, sdkModelId, sdkTools, resolvedAuth, resolvedProvider, systemMessageContent, effectiveWorkspaceDir, effectiveCwd, onUserInputRequest, options) {
305
299
  const settledToolFinalization = options.operation === "settled-tool-finalization";
306
300
  const permissionPolicy = settledToolFinalization ? rejectAllPolicy : params.permissionPolicy ?? rejectAllPolicy;
@@ -415,18 +409,18 @@ function resolvePoolAcquire(params) {
415
409
  resolvedApiKey: readNonEmptyString(params.resolvedApiKey),
416
410
  authProfileId: readNonEmptyString(params.authProfileId)
417
411
  });
418
- const auth = provider.mode === "byok" ? createCopilotByokAuth({
412
+ const authContext = {
419
413
  agentId: readNonEmptyString(params.agentId),
420
414
  agentDir: readNonEmptyString(params.agentDir),
421
415
  workspaceDir: readNonEmptyString(params.workspaceDir),
422
- copilotHome: readNonEmptyString(params.copilotHome),
416
+ copilotHome: readNonEmptyString(params.copilotHome)
417
+ };
418
+ const auth = provider.mode === "byok" ? createCopilotByokAuth({
419
+ ...authContext,
423
420
  authProfileId: provider.authProfileId,
424
421
  authProfileVersion: provider.authProfileVersion
425
422
  }) : resolveCopilotAuth({
426
- agentId: readNonEmptyString(params.agentId),
427
- agentDir: readNonEmptyString(params.agentDir),
428
- workspaceDir: readNonEmptyString(params.workspaceDir),
429
- copilotHome: readNonEmptyString(params.copilotHome),
423
+ ...authContext,
430
424
  auth: params.auth,
431
425
  resolvedApiKey: readNonEmptyString(params.resolvedApiKey),
432
426
  authProfileId: readNonEmptyString(params.authProfileId),
@@ -639,18 +633,17 @@ function attachEventBridge(session, options) {
639
633
  let deltaChain = Promise.resolve();
640
634
  let agentEventChain = Promise.resolve();
641
635
  let compactionChain = Promise.resolve();
642
- let compactionIdle = Promise.resolve();
643
- let resolveCompactionIdle;
636
+ let compactionIdle;
644
637
  let observedSessionIdle = false;
645
- let resolveSessionIdle;
646
- const sessionIdle = new Promise((resolve) => {
647
- resolveSessionIdle = resolve;
648
- });
638
+ const sessionIdle = createDeferred();
649
639
  let firstDeltaError;
650
640
  let detached = false;
651
641
  let unconsumedDurableReasoning = false;
652
642
  const unsubscribeFns = [];
653
- registerListener(session, unsubscribeFns, "user.message", (event) => {
643
+ const listen = (eventType, handler) => {
644
+ unsubscribeFns.push(session.on(eventType, handler));
645
+ };
646
+ listen("user.message", (event) => {
654
647
  if (!isRootSessionEvent(event) || event.ephemeral === true) return;
655
648
  flushPendingAssistantProjection();
656
649
  const projection = options.transcriptProjection;
@@ -674,17 +667,17 @@ function attachEventBridge(session, options) {
674
667
  }
675
668
  });
676
669
  });
677
- registerListener(session, unsubscribeFns, "system.message", (event) => {
670
+ listen("system.message", (event) => {
678
671
  if (!isRootSessionEvent(event) || event.ephemeral === true) return;
679
672
  options.transcriptProjection?.journal.markReplayIncomplete();
680
673
  });
681
- registerListener(session, unsubscribeFns, "skill.invoked", (event) => {
674
+ listen("skill.invoked", (event) => {
682
675
  if (isRootSessionEvent(event) && event.ephemeral !== true) options.transcriptProjection?.journal.markReplayIncomplete();
683
676
  });
684
- registerListener(session, unsubscribeFns, "system.notification", (event) => {
677
+ listen("system.notification", (event) => {
685
678
  if (isRootSessionEvent(event) && event.ephemeral !== true) options.transcriptProjection?.journal.markReplayIncomplete();
686
679
  });
687
- registerListener(session, unsubscribeFns, "assistant.message_delta", (event) => {
680
+ listen("assistant.message_delta", (event) => {
688
681
  if (!isRootSessionEvent(event)) return;
689
682
  const messageId = readNonEmptyStringPreservingWhitespace(event.data.messageId) ?? "assistant-message";
690
683
  const delta = event.data.deltaContent;
@@ -707,40 +700,37 @@ function attachEventBridge(session, options) {
707
700
  });
708
701
  deltaChain.catch(() => void 0);
709
702
  });
710
- registerListener(session, unsubscribeFns, "assistant.reasoning_delta", (event) => {
703
+ listen("assistant.reasoning_delta", (event) => {
711
704
  if (!isRootSessionEvent(event)) return;
712
705
  const reasoningId = readNonEmptyStringPreservingWhitespace(event.data.reasoningId) ?? "assistant-reasoning";
713
706
  const delta = event.data.deltaContent;
714
707
  if (!delta) return;
715
708
  reasoningById.set(reasoningId, `${reasoningById.get(reasoningId) ?? ""}${delta}`);
716
709
  });
717
- registerListener(session, unsubscribeFns, "assistant.reasoning", (event) => {
710
+ listen("assistant.reasoning", (event) => {
718
711
  if (!isRootSessionEvent(event) || event.ephemeral === true) return;
719
712
  reasoningById.set(event.data.reasoningId, event.data.content);
720
713
  durableReasoningById.set(event.data.reasoningId, event.data.content);
721
714
  unconsumedDurableReasoning = true;
722
715
  });
723
- registerListener(session, unsubscribeFns, "assistant.turn_start", (event) => {
716
+ listen("assistant.turn_start", (event) => {
724
717
  if (isRootSessionEvent(event)) markUnconsumedReasoningIncomplete();
725
718
  });
726
- registerListener(session, unsubscribeFns, "assistant.message", (event) => {
727
- if (!isRootSessionEvent(event) || event.ephemeral === true) return;
728
- handleAssistantMessage(event);
729
- });
730
- registerListener(session, unsubscribeFns, "assistant.usage", (event) => {
719
+ listen("assistant.message", handleAssistantMessage);
720
+ listen("assistant.usage", (event) => {
731
721
  if (!isRootSessionEvent(event)) return;
732
722
  usage = normalizeCopilotUsage(event.data);
733
723
  const apiCallId = readNonEmptyStringPreservingWhitespace(event.data.apiCallId);
734
724
  if (apiCallId && usage) usageByApiCallId.set(apiCallId, usage);
735
725
  if (apiCallId) flushPendingAssistantProjection(apiCallId);
736
726
  });
737
- registerListener(session, unsubscribeFns, "tool.user_requested", (event) => {
727
+ listen("tool.user_requested", (event) => {
738
728
  if (isRootSessionEvent(event) && event.ephemeral !== true) {
739
729
  userRequestedToolCallIds.add(event.data.toolCallId);
740
730
  options.transcriptProjection?.journal.markReplayIncomplete();
741
731
  }
742
732
  });
743
- registerListener(session, unsubscribeFns, "tool.execution_start", (event) => {
733
+ listen("tool.execution_start", (event) => {
744
734
  flushPendingAssistantProjectionForToolCall(event.data.toolCallId);
745
735
  if (isRootSessionEvent(event)) startedCount += 1;
746
736
  toolMetaIndexByCallId.set(event.data.toolCallId, toolMetas.length);
@@ -759,7 +749,7 @@ function attachEventBridge(session, options) {
759
749
  })
760
750
  });
761
751
  });
762
- registerListener(session, unsubscribeFns, "tool.execution_complete", (event) => {
752
+ listen("tool.execution_complete", (event) => {
763
753
  flushPendingAssistantProjectionForToolCall(event.data.toolCallId);
764
754
  if (isRootSessionEvent(event)) completedCount += 1;
765
755
  const toolMetaIndex = toolMetaIndexByCallId.get(event.data.toolCallId);
@@ -818,7 +808,7 @@ function attachEventBridge(session, options) {
818
808
  });
819
809
  }
820
810
  });
821
- registerListener(session, unsubscribeFns, "session.plan_changed", (event) => {
811
+ listen("session.plan_changed", (event) => {
822
812
  enqueueAgentEvent({
823
813
  stream: "plan",
824
814
  data: {
@@ -830,7 +820,7 @@ function attachEventBridge(session, options) {
830
820
  }
831
821
  });
832
822
  });
833
- registerListener(session, unsubscribeFns, "exit_plan_mode.requested", (event) => {
823
+ listen("exit_plan_mode.requested", (event) => {
834
824
  const steps = splitPlanText(event.data.planContent).map((step) => ({
835
825
  step,
836
826
  status: "pending"
@@ -850,7 +840,7 @@ function attachEventBridge(session, options) {
850
840
  }
851
841
  });
852
842
  });
853
- registerListener(session, unsubscribeFns, "exit_plan_mode.completed", (event) => {
843
+ listen("exit_plan_mode.completed", (event) => {
854
844
  enqueueAgentEvent({
855
845
  stream: "plan",
856
846
  data: {
@@ -866,16 +856,14 @@ function attachEventBridge(session, options) {
866
856
  }
867
857
  });
868
858
  });
869
- registerListener(session, unsubscribeFns, "session.compaction_start", (event) => {
859
+ listen("session.compaction_start", (event) => {
870
860
  if (!isRootSessionEvent(event)) return;
871
861
  observedCompaction = true;
872
- if (activeCompactionCount === 0) compactionIdle = new Promise((resolve) => {
873
- resolveCompactionIdle = resolve;
874
- });
862
+ if (activeCompactionCount === 0) compactionIdle = createDeferred();
875
863
  activeCompactionCount += 1;
876
864
  enqueueCompactionCallback(options.onCompactionStart);
877
865
  });
878
- registerListener(session, unsubscribeFns, "session.compaction_complete", (event) => {
866
+ listen("session.compaction_complete", (event) => {
879
867
  if (event.data.success) try {
880
868
  options.onContextCompacted?.();
881
869
  } catch {}
@@ -886,23 +874,22 @@ function attachEventBridge(session, options) {
886
874
  success: event.data.success
887
875
  }));
888
876
  if (activeCompactionCount === 0) {
889
- resolveCompactionIdle?.();
890
- resolveCompactionIdle = void 0;
877
+ compactionIdle?.resolve();
878
+ compactionIdle = void 0;
891
879
  }
892
880
  });
893
- registerListener(session, unsubscribeFns, "session.idle", (event) => {
881
+ listen("session.idle", (event) => {
894
882
  if (!isRootSessionEvent(event)) return;
895
883
  markUnconsumedReasoningIncomplete();
896
884
  flushPendingAssistantProjection();
897
885
  observedSessionIdle = true;
898
- resolveSessionIdle?.();
899
- resolveSessionIdle = void 0;
886
+ sessionIdle.resolve();
900
887
  });
901
- registerListener(session, unsubscribeFns, "session.error", (event) => {
888
+ listen("session.error", (event) => {
902
889
  markUnconsumedReasoningIncomplete();
903
890
  if (!options.isAborted()) streamError = createPromptError(event.data.errorCode ?? event.data.errorType, event.data.message);
904
891
  });
905
- registerListener(session, unsubscribeFns, "abort", (event) => {
892
+ listen("abort", (event) => {
906
893
  markUnconsumedReasoningIncomplete();
907
894
  if (!options.isAborted()) streamError = createPromptError("session_aborted", `[copilot-attempt] session aborted: ${event.data.reason}`);
908
895
  });
@@ -916,16 +903,14 @@ function attachEventBridge(session, options) {
916
903
  awaitCompactionChain() {
917
904
  return compactionChain;
918
905
  },
919
- async awaitCompactionCompletion() {
920
- await awaitStableCompaction();
921
- },
906
+ awaitCompactionCompletion: awaitStableCompaction,
922
907
  awaitSessionIdle() {
923
- return observedSessionIdle ? Promise.resolve() : sessionIdle;
908
+ return observedSessionIdle ? Promise.resolve() : sessionIdle.promise;
924
909
  },
925
910
  settleCompactionWait() {
926
911
  activeCompactionCount = 0;
927
- resolveCompactionIdle?.();
928
- resolveCompactionIdle = void 0;
912
+ compactionIdle?.resolve();
913
+ compactionIdle = void 0;
929
914
  },
930
915
  awaitDeltaChain() {
931
916
  return deltaChain;
@@ -1088,19 +1073,13 @@ function attachEventBridge(session, options) {
1088
1073
  agentEventChain = agentEventChain.then(invoke, invoke).catch(() => void 0);
1089
1074
  }
1090
1075
  async function awaitStableCompaction() {
1091
- const idle = activeCompactionCount > 0 ? compactionIdle : void 0;
1076
+ const idle = activeCompactionCount > 0 ? compactionIdle?.promise : void 0;
1092
1077
  if (idle) await idle;
1093
1078
  const callbacks = compactionChain;
1094
1079
  await callbacks;
1095
1080
  if (activeCompactionCount > 0 || compactionChain !== callbacks) await awaitStableCompaction();
1096
1081
  }
1097
1082
  }
1098
- function createPromptError(code, message, cause) {
1099
- const error = new Error(message);
1100
- error.code = code;
1101
- if (cause !== void 0) error.cause = cause;
1102
- return error;
1103
- }
1104
1083
  function ensureMessageAccumulator(messagesById, messageId) {
1105
1084
  let entry = messagesById.get(messageId);
1106
1085
  if (!entry) {
@@ -1124,16 +1103,6 @@ function isRootSessionEvent(event) {
1124
1103
  function splitPlanText(text) {
1125
1104
  return (text ?? "").split(/\r?\n/).map((line) => line.trim().replace(/^[-*]\s+/, "")).filter((line) => line.length > 0);
1126
1105
  }
1127
- function registerListener(session, unsubscribeFns, eventType, handler) {
1128
- const maybeUnsubscribe = session.on(eventType, handler);
1129
- if (typeof maybeUnsubscribe === "function") {
1130
- unsubscribeFns.push(maybeUnsubscribe);
1131
- return;
1132
- }
1133
- unsubscribeFns.push(() => {
1134
- session.off?.(eventType, handler);
1135
- });
1136
- }
1137
1106
  //#endregion
1138
1107
  //#region extensions/copilot/src/attempt-cleanup.ts
1139
1108
  async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now) {
@@ -1153,50 +1122,40 @@ async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now
1153
1122
  else runAgentEndSideEffects(hookParams);
1154
1123
  return result;
1155
1124
  }
1156
- function deferBackgroundCompactionCleanup(params) {
1157
- return (async () => {
1158
- let outcome = "deadline";
1159
- try {
1160
- outcome = await awaitDeferredCleanupBeforeDeadline({
1161
- abortSignal: params.abortSignal,
1162
- awaitSessionIdle: params.awaitSessionIdle,
1163
- bridge: params.bridge,
1164
- timeoutMs: params.timeoutMs
1165
- });
1166
- } catch {} finally {
1167
- if (outcome !== "completed") {
1168
- await cancelBackgroundCompactionBeforeTeardown(params.session);
1169
- params.bridge.settleCompactionWait();
1170
- }
1171
- params.bridge.detach();
1172
- await params.bridge.awaitAgentEventChain();
1173
- try {
1174
- await params.session.disconnect();
1175
- } catch {}
1176
- params.cleanupToolBridge?.();
1177
- await params.cleanupByokProxy?.();
1178
- if (outcome !== "completed" && params.deleteSessionOnIncompleteCleanup && params.sdkSessionId) try {
1179
- await params.handle.client.deleteSession(params.sdkSessionId);
1180
- } catch {}
1181
- try {
1182
- await params.pool.release(params.handle);
1183
- } catch {}
1125
+ async function deferBackgroundCompactionCleanup(params) {
1126
+ let outcome = "deadline";
1127
+ try {
1128
+ outcome = await awaitDeferredCleanupBeforeDeadline({
1129
+ abortSignal: params.abortSignal,
1130
+ awaitSessionIdle: params.awaitSessionIdle,
1131
+ bridge: params.bridge,
1132
+ timeoutMs: params.timeoutMs
1133
+ });
1134
+ } catch {} finally {
1135
+ if (outcome !== "completed") {
1136
+ await cancelBackgroundCompactionBeforeTeardown(params.session);
1137
+ params.bridge.settleCompactionWait();
1184
1138
  }
1185
- return outcome;
1186
- })();
1139
+ params.bridge.detach();
1140
+ await params.bridge.awaitAgentEventChain();
1141
+ try {
1142
+ await params.session.disconnect();
1143
+ } catch {}
1144
+ params.cleanupToolBridge?.();
1145
+ await params.cleanupByokProxy?.();
1146
+ if (outcome !== "completed" && params.deleteSessionOnIncompleteCleanup && params.sdkSessionId) try {
1147
+ await params.handle.client.deleteSession(params.sdkSessionId);
1148
+ } catch {}
1149
+ try {
1150
+ await params.pool.release(params.handle);
1151
+ } catch {}
1152
+ }
1153
+ return outcome;
1187
1154
  }
1188
1155
  async function cancelBackgroundCompactionBeforeTeardown(session) {
1189
1156
  const cancelBackgroundCompaction = session.rpc?.history?.cancelBackgroundCompaction;
1190
1157
  if (!cancelBackgroundCompaction) return;
1191
- let timeoutId;
1192
- const deadline = new Promise((resolve) => {
1193
- timeoutId = setTimeout(resolve, BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS);
1194
- });
1195
- try {
1196
- await Promise.race([Promise.resolve().then(() => cancelBackgroundCompaction()).catch(() => void 0), deadline]);
1197
- } finally {
1198
- if (timeoutId !== void 0) clearTimeout(timeoutId);
1199
- }
1158
+ await withTimeout(Promise.resolve().then(() => cancelBackgroundCompaction()), BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS).catch(() => void 0);
1200
1159
  }
1201
1160
  async function awaitDeferredCleanupBeforeDeadline(params) {
1202
1161
  if (params.abortSignal?.aborted) return "aborted";
@@ -1210,19 +1169,10 @@ async function awaitDeferredCleanupBeforeDeadline(params) {
1210
1169
  resolveAbort = () => resolve("aborted");
1211
1170
  params.abortSignal?.addEventListener("abort", resolveAbort, { once: true });
1212
1171
  });
1213
- let timeoutId;
1214
- const deadline = new Promise((resolve) => {
1215
- timeoutId = setTimeout(() => resolve("deadline"), params.timeoutMs);
1216
- });
1217
1172
  try {
1218
- return await Promise.race([
1219
- completion,
1220
- aborted,
1221
- deadline
1222
- ]);
1173
+ return await raceWithTimeout(Promise.race([completion, aborted]), params.timeoutMs, () => "deadline");
1223
1174
  } finally {
1224
1175
  params.abortSignal?.removeEventListener("abort", resolveAbort);
1225
- if (timeoutId !== void 0) clearTimeout(timeoutId);
1226
1176
  }
1227
1177
  }
1228
1178
  //#endregion
@@ -1255,8 +1205,12 @@ function registerCopilotActiveRun(params) {
1255
1205
  acceptanceReported = true;
1256
1206
  options?.onQueueAccepted?.(accepted);
1257
1207
  };
1258
- if (await claimPendingUserInputAnswer(text, options)) {
1208
+ if (await claimPendingUserInputAnswer(text, options).catch((error) => {
1209
+ options?.onQueueSettled?.();
1210
+ throw error;
1211
+ })) {
1259
1212
  reportAcceptance(true);
1213
+ options?.onQueueSettled?.();
1260
1214
  return;
1261
1215
  }
1262
1216
  let messageId;
@@ -1272,10 +1226,13 @@ function registerCopilotActiveRun(params) {
1272
1226
  reportAcceptance(true);
1273
1227
  } catch (error) {
1274
1228
  reportAcceptance(false);
1229
+ options?.onQueueSettled?.();
1275
1230
  throw error;
1276
1231
  }
1277
- if (options?.waitForTranscriptCommit === true) try {
1278
- await waitForPersistenceReceipt(params.transcriptJournal.waitForSdkUserPersisted(messageId), options.deliveryTimeoutMs);
1232
+ const receipt = options?.waitForTranscriptCommit === true || options?.onQueueSettled ? params.transcriptJournal.waitForSdkUserPersisted(messageId) : void 0;
1233
+ if (receipt && options?.onQueueSettled) receipt.then(options.onQueueSettled, options.onQueueSettled);
1234
+ if (receipt && options?.waitForTranscriptCommit === true) try {
1235
+ await waitForPersistenceReceipt(receipt, options.deliveryTimeoutMs);
1279
1236
  } catch (error) {
1280
1237
  return {
1281
1238
  transcriptCommit: "unconfirmed",
@@ -1317,16 +1274,9 @@ function registerCopilotActiveRun(params) {
1317
1274
  return activeRunHandle;
1318
1275
  }
1319
1276
  async function waitForPersistenceReceipt(receipt, requestedTimeoutMs) {
1320
- const timeoutMs = typeof requestedTimeoutMs === "number" && Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0 ? requestedTimeoutMs : DEFAULT_STEERING_DELIVERY_TIMEOUT_MS;
1321
- let timer;
1322
- try {
1323
- await Promise.race([receipt, new Promise((_, reject) => {
1324
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Copilot steering transcript receipt timed out")), timeoutMs);
1325
- timer.unref?.();
1326
- })]);
1327
- } finally {
1328
- if (timer) clearTimeout(timer);
1329
- }
1277
+ await raceWithTimeout(receipt, typeof requestedTimeoutMs === "number" && Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0 ? requestedTimeoutMs : DEFAULT_STEERING_DELIVERY_TIMEOUT_MS, () => {
1278
+ throw new Error("Copilot steering transcript receipt timed out");
1279
+ }, { ref: false });
1330
1280
  }
1331
1281
  //#endregion
1332
1282
  //#region extensions/copilot/src/attempt-transcript-replay.ts
@@ -1418,7 +1368,6 @@ async function completeCopilotAttempt(params) {
1418
1368
  assistantTranscriptIdempotencyKey: transcript?.assistantTranscriptIdempotencyKey,
1419
1369
  contextEngineTerminalAnchor: transcript?.terminalAnchor,
1420
1370
  nativeReplayInvalid: transcript?.replayInvalid === true || nativeSessionHistoryUnvalidated,
1421
- now,
1422
1371
  promptError,
1423
1372
  resumeFailureRecovered,
1424
1373
  sdkSessionId,
@@ -1696,16 +1645,10 @@ function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution)
1696
1645
  failure: { error: errorMessage },
1697
1646
  ...ownerMutation ? { ownerMutation } : {}
1698
1647
  });
1699
- notifyToolResult(sanitizeToolResult({
1700
- content: [{
1701
- type: "text",
1702
- text: message
1703
- }],
1704
- details: {
1705
- status: "failed",
1706
- error: errorMessage
1707
- }
1708
- }), true);
1648
+ notifyToolResult(sanitizeToolResult(textResult(message, {
1649
+ status: "failed",
1650
+ error: errorMessage
1651
+ })), true);
1709
1652
  notifyToolCompleted({
1710
1653
  toolName: sourceTool.name,
1711
1654
  toolCallId: invocation.toolCallId,
@@ -1827,16 +1770,10 @@ async function executeCatalogTool(input, params) {
1827
1770
  failure: { error: message },
1828
1771
  ...ownerMutation ? { ownerMutation } : {}
1829
1772
  }))?.executedArguments ?? preparedArgs;
1830
- const failure = sanitizeToolResult({
1831
- content: [{
1832
- type: "text",
1833
- text: message
1834
- }],
1835
- details: {
1836
- status: "failed",
1837
- error: message
1838
- }
1839
- });
1773
+ const failure = sanitizeToolResult(textResult(message, {
1774
+ status: "failed",
1775
+ error: message
1776
+ }));
1840
1777
  input.attemptParams?.onAgentToolResult?.({
1841
1778
  toolName: params.toolName,
1842
1779
  result: failure,
@@ -1855,7 +1792,7 @@ async function executeCatalogTool(input, params) {
1855
1792
  }
1856
1793
  }
1857
1794
  function toToolStartArgs(args) {
1858
- return args && typeof args === "object" && !Array.isArray(args) ? args : { value: args };
1795
+ return asOptionalRecord(args) ?? { value: args };
1859
1796
  }
1860
1797
  function createFailureResult(message, error) {
1861
1798
  return {
@@ -2375,7 +2312,7 @@ function createAttemptTranscriptJournal(params) {
2375
2312
  const sdkUserPersistenceReceipt = (eventId) => {
2376
2313
  let receipt = sdkUserPersistenceReceipts.get(eventId);
2377
2314
  if (!receipt) {
2378
- receipt = createDeferred();
2315
+ receipt = createDeferred$1();
2379
2316
  receipt.promise.catch(() => void 0);
2380
2317
  sdkUserPersistenceReceipts.set(eventId, receipt);
2381
2318
  if (firstFailure) receipt.reject(firstFailure);
@@ -2506,7 +2443,7 @@ function createAttemptTranscriptJournal(params) {
2506
2443
  return {
2507
2444
  async sendSdkUser(send, recorder) {
2508
2445
  if (!recorder) return await send();
2509
- const registration = createDeferred();
2446
+ const registration = createDeferred$1();
2510
2447
  schedule(() => registration.promise);
2511
2448
  try {
2512
2449
  const messageId = await send();
@@ -2765,10 +2702,6 @@ async function runCopilotExecution(context) {
2765
2702
  if (settled || !sentTurnStarted || !session) return;
2766
2703
  session.abort().catch(() => void 0);
2767
2704
  };
2768
- const onAbort = () => {
2769
- abortActiveSession();
2770
- };
2771
- params.abortSignal?.addEventListener("abort", onAbort, { once: true });
2772
2705
  let sandbox = null;
2773
2706
  let effectiveWorkspaceDir = resolvedWorkspaceForSandbox;
2774
2707
  if (resolvedWorkspaceForSandbox) try {
@@ -2779,35 +2712,26 @@ async function runCopilotExecution(context) {
2779
2712
  sandboxSessionKey
2780
2713
  }));
2781
2714
  } catch (error) {
2782
- settled = true;
2783
- params.abortSignal?.removeEventListener("abort", onAbort);
2784
- if (abortRequested || params.abortSignal?.aborted) return finishAttempt(createResult(input, {
2715
+ if (params.abortSignal?.aborted) return finishAttempt(createResult(input, {
2785
2716
  aborted: true,
2786
2717
  externalAbort: true,
2787
2718
  messagesSnapshot: messages,
2788
- now,
2789
2719
  promptError: void 0,
2790
2720
  sdkSessionId: void 0
2791
2721
  }));
2792
2722
  return finishAttempt(createResult(input, {
2793
2723
  messagesSnapshot: messages,
2794
- now,
2795
- promptError: createPromptError$1("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error),
2724
+ promptError: createPromptError("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error),
2796
2725
  sdkSessionId: void 0
2797
2726
  }));
2798
2727
  }
2799
2728
  hookContext.workspaceDir = effectiveWorkspaceDir;
2800
2729
  const requestedCwd = readResolvedAttemptPath(input.cwd);
2801
- if (sandbox?.enabled && requestedCwd && requestedCwd !== resolvedWorkspaceForSandbox) {
2802
- settled = true;
2803
- params.abortSignal?.removeEventListener("abort", onAbort);
2804
- return finishAttempt(createResult(input, {
2805
- messagesSnapshot: messages,
2806
- now,
2807
- promptError: createPromptError$1("sandbox_cwd_override_unsupported", "[copilot-attempt] cwd override is not supported for sandboxed Copilot runs; omit cwd or use the agent workspace as cwd"),
2808
- sdkSessionId: void 0
2809
- }));
2810
- }
2730
+ if (sandbox?.enabled && requestedCwd && requestedCwd !== resolvedWorkspaceForSandbox) return finishAttempt(createResult(input, {
2731
+ messagesSnapshot: messages,
2732
+ promptError: createPromptError("sandbox_cwd_override_unsupported", "[copilot-attempt] cwd override is not supported for sandboxed Copilot runs; omit cwd or use the agent workspace as cwd"),
2733
+ sdkSessionId: void 0
2734
+ }));
2811
2735
  const effectiveCwd = sandbox?.enabled ? effectiveWorkspaceDir : requestedCwd ?? effectiveWorkspaceDir;
2812
2736
  const effectiveFsWorkspaceOnly = resolveAttemptFsWorkspaceOnly({
2813
2737
  config: input.config,
@@ -2831,8 +2755,7 @@ async function runCopilotExecution(context) {
2831
2755
  } catch (error) {
2832
2756
  return finishAttempt(createResult(input, {
2833
2757
  messagesSnapshot: messages,
2834
- now,
2835
- promptError: createPromptError$1("model_not_supported", toCopilotError(error).message, error),
2758
+ promptError: createPromptError("model_not_supported", toCopilotError(error).message, error),
2836
2759
  sdkSessionId: void 0
2837
2760
  }));
2838
2761
  }
@@ -2843,6 +2766,8 @@ async function runCopilotExecution(context) {
2843
2766
  let codeModeEngaged;
2844
2767
  let promptToolPolicy;
2845
2768
  try {
2769
+ params.abortSignal?.addEventListener("abort", abortActiveSession, { once: true });
2770
+ if (params.abortSignal?.aborted) abortActiveSession();
2846
2771
  let resultContentSourceByToolName = /* @__PURE__ */ new Map();
2847
2772
  if (!settledToolFinalization) try {
2848
2773
  assertCopilotAttemptHostCapabilities(input);
@@ -2894,8 +2819,7 @@ async function runCopilotExecution(context) {
2894
2819
  } catch (error) {
2895
2820
  return finishAttempt(createResult(input, {
2896
2821
  messagesSnapshot: messages,
2897
- now,
2898
- promptError: createPromptError$1("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error),
2822
+ promptError: createPromptError("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error),
2899
2823
  sdkSessionId: void 0
2900
2824
  }));
2901
2825
  }
@@ -2933,22 +2857,19 @@ async function runCopilotExecution(context) {
2933
2857
  });
2934
2858
  nativeSessionHistoryValidated = input.initialReplayState?.journalValidated === true;
2935
2859
  } catch (error) {
2936
- if (settledToolFinalization) throw createPromptError$1("settled_finalization_resume_failed", `[copilot-attempt] settled tool finalization could not resume the existing Copilot SDK session: ${toCopilotError(error).message}`, error);
2860
+ if (settledToolFinalization) throw createPromptError("settled_finalization_resume_failed", `[copilot-attempt] settled tool finalization could not resume the existing Copilot SDK session: ${toCopilotError(error).message}`, error);
2937
2861
  if (!classifyResumeFailure(error).recoverable) throw error;
2938
2862
  resumeFailureRecovered = true;
2939
- session = await client.createSession(sessionConfig);
2940
- nativeSessionCreatedFresh = true;
2941
- nativeSessionHistoryValidated = true;
2942
2863
  }
2943
- else {
2864
+ if (!session) {
2944
2865
  session = await client.createSession(sessionConfig);
2945
2866
  nativeSessionCreatedFresh = true;
2946
2867
  nativeSessionHistoryValidated = true;
2947
2868
  }
2948
2869
  sessionRef.current = session;
2949
2870
  sdkSessionId = readNonEmptyString(session.sessionId) ?? readNonEmptyString(session.id) ?? (resumeFailureRecovered ? void 0 : resumeSessionId);
2950
- if (!sdkSessionId) throw createPromptError$1("transcript_persistence_failed", "[copilot-attempt] canonical transcript persistence requires the Copilot SDK session id");
2951
- if (sdkSessionId && deps.onSessionEstablished && !settledToolFinalization) try {
2871
+ if (!sdkSessionId) throw createPromptError("transcript_persistence_failed", "[copilot-attempt] canonical transcript persistence requires the Copilot SDK session id");
2872
+ if (deps.onSessionEstablished && !settledToolFinalization) try {
2952
2873
  await deps.onSessionEstablished({
2953
2874
  compactionSessionConfig,
2954
2875
  sdkSessionId,
@@ -3115,14 +3036,14 @@ async function runCopilotExecution(context) {
3115
3036
  sdkSessionId
3116
3037
  });
3117
3038
  } catch {}
3118
- params.abortSignal?.removeEventListener("abort", onAbort);
3039
+ params.abortSignal?.removeEventListener("abort", abortActiveSession);
3119
3040
  } else {
3120
3041
  await bridge?.awaitCompactionChain();
3121
3042
  bridge?.detach();
3122
3043
  await bridge?.awaitAgentEventChain();
3123
3044
  cleanupToolBridge?.();
3124
3045
  await cleanupByokProxy?.();
3125
- params.abortSignal?.removeEventListener("abort", onAbort);
3046
+ params.abortSignal?.removeEventListener("abort", abortActiveSession);
3126
3047
  if (session) try {
3127
3048
  await session.disconnect();
3128
3049
  } catch (error) {
@@ -3173,13 +3094,13 @@ async function runCopilotExecution(context) {
3173
3094
  async function runCopilotAttempt(params, deps) {
3174
3095
  const now = deps.now ?? Date.now;
3175
3096
  const attemptStartedAt = now();
3176
- const { settledToolFinalization, input, createToolBridge, ringZeroSystemAgentRun, messages, modelRef, resolvedWorkspaceForSandbox, sandboxSessionKey, sessionAgentId, hookContextWindowFields, hookContext } = prepareCopilotAttemptContext(params, deps);
3097
+ const prepared = prepareCopilotAttemptContext(params, deps);
3098
+ const { settledToolFinalization, input, messages, modelRef, hookContext } = prepared;
3177
3099
  const finishAttempt = (result) => settledToolFinalization ? Promise.resolve(result) : finalizeCopilotAttempt(input, result, hookContext, attemptStartedAt, now);
3178
3100
  if (params.abortSignal?.aborted) return finishAttempt(createResult(input, {
3179
3101
  aborted: true,
3180
3102
  externalAbort: true,
3181
3103
  messagesSnapshot: messages,
3182
- now,
3183
3104
  promptError: void 0,
3184
3105
  sdkSessionId: void 0
3185
3106
  }));
@@ -3192,34 +3113,22 @@ async function runCopilotAttempt(params, deps) {
3192
3113
  } catch (error) {
3193
3114
  return finishAttempt(createResult(input, {
3194
3115
  messagesSnapshot: messages,
3195
- now,
3196
- promptError: createPromptError$1("model_not_supported", toCopilotError(error).message, error),
3116
+ promptError: createPromptError("model_not_supported", toCopilotError(error).message, error),
3197
3117
  sdkSessionId: void 0
3198
3118
  }));
3199
3119
  }
3200
3120
  const settledFinalizationSessionId = settledToolFinalization ? readNonEmptyString(input.initialReplayState?.sdkSessionId) : void 0;
3201
3121
  if (settledToolFinalization && !settledFinalizationSessionId) return finishAttempt(createResult(input, {
3202
3122
  messagesSnapshot: messages,
3203
- now,
3204
- promptError: createPromptError$1("settled_finalization_session_unavailable", "[copilot-attempt] settled tool finalization requires the existing Copilot SDK session"),
3123
+ promptError: createPromptError("settled_finalization_session_unavailable", "[copilot-attempt] settled tool finalization requires the existing Copilot SDK session"),
3205
3124
  sdkSessionId: void 0
3206
3125
  }));
3207
3126
  return await runCopilotExecution({
3127
+ ...prepared,
3208
3128
  params,
3209
3129
  deps,
3210
3130
  now,
3211
3131
  attemptStartedAt,
3212
- settledToolFinalization,
3213
- input,
3214
- createToolBridge,
3215
- ringZeroSystemAgentRun,
3216
- messages,
3217
- modelRef,
3218
- resolvedWorkspaceForSandbox,
3219
- sandboxSessionKey,
3220
- sessionAgentId,
3221
- hookContextWindowFields,
3222
- hookContext,
3223
3132
  finishAttempt,
3224
3133
  settledFinalizationSessionId
3225
3134
  });
@@ -139,11 +139,12 @@ async function createCopilotByokProxy(resolvedProvider) {
139
139
  if (!providerConfig?.baseUrl) throw new Error("[copilot-attempt] BYOK requires a provider baseUrl");
140
140
  const targetBaseUrl = new URL(providerConfig.baseUrl);
141
141
  const nonce = randomBytes(12).toString("hex");
142
- const targetPathPrefix = trimTrailingSlash(targetBaseUrl.pathname);
142
+ const targetPathPrefix = targetBaseUrl.pathname.replace(/\/+$/, "");
143
143
  const proxyPathPrefix = `/${nonce}${targetPathPrefix}`;
144
144
  const acceptsAzureSdkPaths = providerConfig.type === "azure";
145
145
  const proxyCredentialHeader = acceptsAzureSdkPaths ? createProxyCredentialHeaderName(providerConfig.headers) : void 0;
146
- const upstreamBearerAuthorization = resolveUpstreamBearerAuthorization(providerConfig);
146
+ const bearerToken = providerConfig.bearerToken?.trim();
147
+ const upstreamBearerAuthorization = bearerToken ? `Bearer ${bearerToken}` : void 0;
147
148
  const activeFetches = /* @__PURE__ */ new Set();
148
149
  const server = createServer((req, res) => {
149
150
  handleProxyRequest(req, res, {
@@ -202,20 +203,19 @@ async function handleProxyRequest(req, res, params) {
202
203
  if (!res.writableEnded) abortUpstream();
203
204
  });
204
205
  try {
205
- const isNonceProtected = isNonceProtectedProxyRequest(req, params.proxyPathPrefix);
206
- const url = resolveTargetUrl(req, params);
207
- if (!url || !isNonceProtected && (!params.proxyCredentialHeader || !hasValidProxyCredential(req, params.proxyCredentialHeader, params.proxyCredential))) {
206
+ const target = resolveTargetUrl(req, params);
207
+ if (!target || !target.nonceProtected && (!params.proxyCredentialHeader || !hasValidProxyCredential(req, params.proxyCredentialHeader, params.proxyCredential))) {
208
208
  res.writeHead(404);
209
209
  res.end("Not found");
210
210
  return;
211
211
  }
212
212
  const body = req.method === "GET" || req.method === "HEAD" ? void 0 : await readBody(req);
213
213
  guarded = await fetchWithSsrFGuard({
214
- url: url.toString(),
214
+ url: target.url.toString(),
215
215
  init: {
216
216
  method: req.method,
217
217
  headers: buildProxyRequestHeaders(req.headers, {
218
- upstreamBearerAuthorization: isNonceProtected ? params.upstreamBearerAuthorization : void 0,
218
+ upstreamBearerAuthorization: target.nonceProtected ? params.upstreamBearerAuthorization : void 0,
219
219
  proxyCredentialHeader: params.proxyCredentialHeader
220
220
  }),
221
221
  signal: upstreamAbort.signal,
@@ -246,26 +246,19 @@ async function handleProxyRequest(req, res, params) {
246
246
  }
247
247
  function resolveTargetUrl(req, params) {
248
248
  const incomingUrl = new URL(req.url ?? "/", `http://${LOOPBACK_HOST}`);
249
- if (incomingUrl.pathname !== params.proxyPathPrefix && !incomingUrl.pathname.startsWith(`${params.proxyPathPrefix}/`)) return params.acceptsAzureSdkPaths && isAzureSdkProxyPath(incomingUrl.pathname) ? resolveDirectTargetUrl(incomingUrl, params.targetBaseUrl) : void 0;
250
- const suffix = incomingUrl.pathname.slice(params.proxyPathPrefix.length);
249
+ const nonceProtected = incomingUrl.pathname === params.proxyPathPrefix || incomingUrl.pathname.startsWith(`${params.proxyPathPrefix}/`);
250
+ if (!nonceProtected && !(params.acceptsAzureSdkPaths && isAzureSdkProxyPath(incomingUrl.pathname))) return;
251
251
  const targetUrl = new URL(params.targetBaseUrl);
252
- targetUrl.pathname = `${params.targetPathPrefix}${suffix}` || "/";
253
- for (const [key, value] of incomingUrl.searchParams) targetUrl.searchParams.append(key, value);
254
- return targetUrl;
255
- }
256
- function resolveDirectTargetUrl(incomingUrl, targetBaseUrl) {
257
- const targetUrl = new URL(targetBaseUrl);
258
- targetUrl.pathname = incomingUrl.pathname;
252
+ targetUrl.pathname = nonceProtected ? `${params.targetPathPrefix}${incomingUrl.pathname.slice(params.proxyPathPrefix.length)}` || "/" : incomingUrl.pathname;
259
253
  for (const [key, value] of incomingUrl.searchParams) targetUrl.searchParams.append(key, value);
260
- return targetUrl;
254
+ return {
255
+ url: targetUrl,
256
+ nonceProtected
257
+ };
261
258
  }
262
259
  function isAzureSdkProxyPath(pathname) {
263
260
  return pathname === "/openai" || pathname.startsWith("/openai/");
264
261
  }
265
- function isNonceProtectedProxyRequest(req, proxyPathPrefix) {
266
- const incomingUrl = new URL(req.url ?? "/", `http://${LOOPBACK_HOST}`);
267
- return incomingUrl.pathname === proxyPathPrefix || incomingUrl.pathname.startsWith(`${proxyPathPrefix}/`);
268
- }
269
262
  function hasValidProxyCredential(req, headerName, expected) {
270
263
  const received = req.headers[headerName];
271
264
  if (typeof received !== "string") return false;
@@ -299,10 +292,6 @@ function buildProxyRequestHeaders(headers, params) {
299
292
  if (params.upstreamBearerAuthorization && !hasHeader(out, "authorization")) out["authorization"] = params.upstreamBearerAuthorization;
300
293
  return out;
301
294
  }
302
- function resolveUpstreamBearerAuthorization(providerConfig) {
303
- const bearerToken = providerConfig.bearerToken?.trim();
304
- return bearerToken ? `Bearer ${bearerToken}` : void 0;
305
- }
306
295
  function normalizeProxyResponseHeaders(headers) {
307
296
  const out = {};
308
297
  headers.forEach((value, key) => {
@@ -338,18 +327,24 @@ function isContentEncodingHeader(key) {
338
327
  default: return false;
339
328
  }
340
329
  }
341
- function trimTrailingSlash(pathname) {
342
- return pathname.replace(/\/+$/, "");
330
+ //#endregion
331
+ //#region extensions/copilot/src/prompt-error.ts
332
+ function createCopilotAbortError(reason) {
333
+ if (reason instanceof Error) return reason;
334
+ const error = new Error("aborted", reason ? { cause: reason } : void 0);
335
+ error.name = "AbortError";
336
+ return error;
337
+ }
338
+ function createPromptError(code, message, cause) {
339
+ const error = new Error(message);
340
+ error.code = code;
341
+ if (cause !== void 0) error.cause = cause;
342
+ return error;
343
343
  }
344
344
  //#endregion
345
345
  //#region extensions/copilot/src/history-compaction.ts
346
346
  function throwIfAborted(signal) {
347
- if (!signal?.aborted) return;
348
- const reason = "reason" in signal ? signal.reason : void 0;
349
- if (reason instanceof Error) throw reason;
350
- const error = reason ? new Error("aborted", { cause: reason }) : /* @__PURE__ */ new Error("aborted");
351
- error.name = "AbortError";
352
- throw error;
347
+ if (signal?.aborted) throw createCopilotAbortError(signal.reason);
353
348
  }
354
349
  function isStaleSdkSessionError(error) {
355
350
  const message = error instanceof Error ? error.message : String(error);
@@ -575,11 +570,7 @@ function normalizeBinding(value) {
575
570
  sdkSessionId: value.sdkSessionId.trim(),
576
571
  compatKey: value.compatKey,
577
572
  compactKey: value.compactKey,
578
- authMode: value.authMode,
579
- ...value.authMode === "gitHubToken" || value.authMode === "byok" ? {
580
- authProfileId: value.authProfileId,
581
- authProfileVersion: value.authProfileVersion
582
- } : {},
573
+ ...sessionAuthFields(value),
583
574
  updatedAt: value.updatedAt
584
575
  };
585
576
  }
@@ -597,21 +588,15 @@ async function lookupStoredBinding(store, key) {
597
588
  try {
598
589
  return normalizeAttemptBinding(await store?.lookup(key));
599
590
  } catch {
600
- try {
601
- await store?.delete(key);
602
- } catch {}
591
+ await deleteStoredBinding(store, key);
603
592
  return;
604
593
  }
605
594
  }
606
595
  async function registerStoredBinding(store, key, binding) {
607
596
  try {
608
597
  await store?.register(key, binding);
609
- return true;
610
598
  } catch {
611
- try {
612
- await store?.delete(key);
613
- } catch {}
614
- return false;
599
+ await deleteStoredBinding(store, key);
615
600
  }
616
601
  }
617
602
  async function deleteStoredBinding(store, key) {
@@ -664,11 +649,14 @@ function computeSessionKey(input, options) {
664
649
  let resolvedAgentId = "";
665
650
  let resolvedCopilotHome = "";
666
651
  try {
667
- const resolved = !options.includeAuth ? resolveCopilotAuth({
652
+ const authContext = {
668
653
  agentId: input.params.agentId ?? readAgentIdFromSessionKey(input.params.sessionKey),
669
654
  agentDir: input.params.agentDir,
670
655
  workspaceDir: input.params.workspaceDir,
671
- copilotHome: input.params.copilotHome,
656
+ copilotHome: input.params.copilotHome
657
+ };
658
+ const resolved = !options.includeAuth ? resolveCopilotAuth({
659
+ ...authContext,
672
660
  auth: { useLoggedInUser: true }
673
661
  }) : (() => {
674
662
  const modelProvider = resolveCopilotProvider({
@@ -692,17 +680,11 @@ function computeSessionKey(input, options) {
692
680
  authProfileId: input.params.authProfileId
693
681
  });
694
682
  return modelProvider.mode === "byok" ? createCopilotByokAuth({
695
- agentId: input.params.agentId ?? readAgentIdFromSessionKey(input.params.sessionKey),
696
- agentDir: input.params.agentDir,
697
- workspaceDir: input.params.workspaceDir,
698
- copilotHome: input.params.copilotHome,
683
+ ...authContext,
699
684
  authProfileId: modelProvider.authProfileId,
700
685
  authProfileVersion: modelProvider.authProfileVersion
701
686
  }) : resolveCopilotAuth({
702
- agentId: input.params.agentId ?? readAgentIdFromSessionKey(input.params.sessionKey),
703
- agentDir: input.params.agentDir,
704
- workspaceDir: input.params.workspaceDir,
705
- copilotHome: input.params.copilotHome,
687
+ ...authContext,
706
688
  auth: input.params.auth,
707
689
  resolvedApiKey: input.params.resolvedApiKey,
708
690
  authProfileId: input.params.authProfileId,
@@ -716,7 +698,6 @@ function computeSessionKey(input, options) {
716
698
  `auth.profileId=${resolved.authProfileId ?? ""}`,
717
699
  `auth.profileVersion=${resolved.authProfileVersion ?? ""}`
718
700
  ];
719
- if (!options.includeAuth) authParts = [];
720
701
  } catch {
721
702
  authParts = ["auth=unresolvable"];
722
703
  }
@@ -785,7 +766,7 @@ function createCopilotAgentHarness(options) {
785
766
  async function getPool() {
786
767
  if (options?.pool) return options.pool;
787
768
  if (!poolPromise) poolPromise = (async () => {
788
- const { createCopilotClientPool } = await import("./runtime-CWI9o_Vc.mjs");
769
+ const { createCopilotClientPool } = await import("./runtime-BiH-FQBm.mjs");
789
770
  createdPool = createCopilotClientPool(options?.poolOptions);
790
771
  return createdPool;
791
772
  })();
@@ -822,7 +803,7 @@ function createCopilotAgentHarness(options) {
822
803
  async function runHarnessAttempt(params, operation) {
823
804
  return trackOperation(async () => {
824
805
  if (disposed) throw new Error("[copilot] harness has been disposed; cannot start new attempts");
825
- const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-CRiSJYXq.mjs");
806
+ const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-Dr9LPO0j.mjs");
826
807
  if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
827
808
  const pool = await getPool();
828
809
  if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
@@ -950,7 +931,7 @@ function createCopilotAgentHarness(options) {
950
931
  async function runIsolatedCompletionV2(params) {
951
932
  return trackOperation(async () => {
952
933
  if (disposed) throw new Error("[copilot] harness has been disposed; cannot start isolated completion");
953
- const { runCopilotIsolatedCompletion } = await import("./isolated-completion-ClBsnNg8.mjs");
934
+ const { runCopilotIsolatedCompletion } = await import("./isolated-completion-B-WKqKY6.mjs");
954
935
  if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
955
936
  return await runCopilotIsolatedCompletion(params, async () => {
956
937
  const pool = await getPool();
@@ -1048,7 +1029,7 @@ function createCopilotAgentHarness(options) {
1048
1029
  };
1049
1030
  const tracked = trackedSessions.get(openclawSessionId);
1050
1031
  const currentCompactKey = computeCompactRequestKey(params);
1051
- const { resolvePoolAcquire } = await import("./attempt-CRiSJYXq.mjs");
1032
+ const { resolvePoolAcquire } = await import("./attempt-Dr9LPO0j.mjs");
1052
1033
  let resolvedPoolAcquire;
1053
1034
  try {
1054
1035
  resolvedPoolAcquire = resolvePoolAcquire(params);
@@ -1193,4 +1174,4 @@ function createCopilotAgentHarness(options) {
1193
1174
  };
1194
1175
  }
1195
1176
  //#endregion
1196
- export { resolveCopilotAuth as a, createCopilotByokAuth as i, resolveCopilotProvider as n, tokenFingerprint as o, createCopilotByokProxy as r, createCopilotAgentHarness as t };
1177
+ export { createCopilotByokProxy as a, tokenFingerprint as c, createPromptError as i, resolveCopilotProvider as n, createCopilotByokAuth as o, createCopilotAbortError as r, resolveCopilotAuth as s, createCopilotAgentHarness as t };
@@ -1,5 +1,6 @@
1
- import { n as resolveCopilotProvider, o as tokenFingerprint, r as createCopilotByokProxy } from "./harness-BAWs53-w.mjs";
2
- import { r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.mjs";
1
+ import { a as createCopilotByokProxy, c as tokenFingerprint, n as resolveCopilotProvider, r as createCopilotAbortError } from "./harness-BeLT-JyA.mjs";
2
+ import { r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge--rLPdCvV.mjs";
3
+ import { asNonArrayRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
3
4
  import { resolve } from "node:path";
4
5
  //#region extensions/copilot/src/isolated-completion.ts
5
6
  function startBestEffortCleanup(cleanup) {
@@ -10,12 +11,6 @@ function startBestEffortCleanup(cleanup) {
10
11
  function resolveReasoningEffort(thinkLevel) {
11
12
  return thinkLevel === "low" || thinkLevel === "medium" || thinkLevel === "high" || thinkLevel === "xhigh" ? thinkLevel : void 0;
12
13
  }
13
- function createAbortError(signal) {
14
- if (signal.reason instanceof Error) return signal.reason;
15
- const error = new Error("aborted", signal.reason ? { cause: signal.reason } : void 0);
16
- error.name = "AbortError";
17
- return error;
18
- }
19
14
  function createTimeoutError(timeoutMs) {
20
15
  const error = /* @__PURE__ */ new Error(`[copilot] isolated completion timed out after ${timeoutMs}ms`);
21
16
  error.name = "TimeoutError";
@@ -23,7 +18,7 @@ function createTimeoutError(timeoutMs) {
23
18
  }
24
19
  async function awaitWithinCompletionBoundary(params) {
25
20
  const signal = params.boundary.abortSignal;
26
- if (signal?.aborted) throw createAbortError(signal);
21
+ if (signal?.aborted) throw createCopilotAbortError(signal.reason);
27
22
  const remainingMs = params.boundary.deadlineMs - Date.now();
28
23
  if (remainingMs <= 0) throw createTimeoutError(params.boundary.timeoutMs);
29
24
  let boundaryError;
@@ -38,7 +33,7 @@ async function awaitWithinCompletionBoundary(params) {
38
33
  };
39
34
  timer = setTimeout(() => rejectBoundary(createTimeoutError(params.boundary.timeoutMs)), remainingMs);
40
35
  if (signal) {
41
- onAbort = () => rejectBoundary(createAbortError(signal));
36
+ onAbort = () => rejectBoundary(createCopilotAbortError(signal.reason));
42
37
  signal.addEventListener("abort", onAbort, { once: true });
43
38
  if (signal.aborted) onAbort();
44
39
  }
@@ -69,18 +64,6 @@ async function awaitWithinCompletionBoundary(params) {
69
64
  if (signal && onAbort) signal.removeEventListener("abort", onAbort);
70
65
  }
71
66
  }
72
- async function sendPrompt(params) {
73
- return await awaitWithinCompletionBoundary({
74
- boundary: params.boundary,
75
- start: async (remainingMs) => await params.session.sendAndWait({
76
- prompt: params.prompt,
77
- ...params.requestHeaders ? { requestHeaders: params.requestHeaders } : {}
78
- }, remainingMs),
79
- onBoundary: () => {
80
- params.session.abort().catch(() => void 0);
81
- }
82
- });
83
- }
84
67
  async function runCopilotIsolatedCompletion(params, getPool) {
85
68
  const reasoningEffort = resolveReasoningEffort(params.thinkLevel);
86
69
  if (params.thinkLevel !== void 0 && reasoningEffort === void 0) throw new Error(`[copilot] isolated completion does not support thinking level ${params.thinkLevel}`);
@@ -167,11 +150,16 @@ async function runCopilotIsolatedCompletion(params, getPool) {
167
150
  }
168
151
  });
169
152
  session = createdSession;
170
- const event = await sendPrompt({
153
+ const requestHeaders = sessionProvider.provider?.headers;
154
+ const event = await awaitWithinCompletionBoundary({
171
155
  boundary,
172
- prompt: params.prompt,
173
- requestHeaders: sessionProvider.provider?.headers,
174
- session: createdSession
156
+ start: async (remainingMs) => await createdSession.sendAndWait({
157
+ prompt: params.prompt,
158
+ ...requestHeaders ? { requestHeaders } : {}
159
+ }, remainingMs),
160
+ onBoundary: () => {
161
+ createdSession.abort().catch(() => void 0);
162
+ }
175
163
  });
176
164
  if (event?.type !== "assistant.message" || event.agentId !== void 0) throw new Error("[copilot] isolated completion did not return a root assistant message");
177
165
  const content = [];
@@ -183,15 +171,12 @@ async function runCopilotIsolatedCompletion(params, getPool) {
183
171
  type: "text",
184
172
  text: event.data.content
185
173
  });
186
- for (const toolRequest of event.data.toolRequests ?? []) {
187
- const toolArguments = toolRequest.arguments;
188
- content.push({
189
- type: "toolCall",
190
- id: toolRequest.toolCallId,
191
- name: toolRequest.name,
192
- arguments: toolArguments && typeof toolArguments === "object" && !Array.isArray(toolArguments) ? { ...toolArguments } : {}
193
- });
194
- }
174
+ for (const toolRequest of event.data.toolRequests ?? []) content.push({
175
+ type: "toolCall",
176
+ id: toolRequest.toolCallId,
177
+ name: toolRequest.name,
178
+ arguments: { ...asNonArrayRecord(toolRequest.arguments) }
179
+ });
195
180
  return { assistant: {
196
181
  role: "assistant",
197
182
  content,
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import path, { normalize, resolve, sep } from "node:path";
2
+ import path, { resolve, sep } from "node:path";
3
3
  import { toStringifiedError } from "openclaw/plugin-sdk/error-runtime";
4
4
  import { existsSync } from "node:fs";
5
5
  import { pathToFileURL } from "node:url";
@@ -253,14 +253,8 @@ function createCopilotClientPool(options = {}) {
253
253
  await stopEntry(entry);
254
254
  return;
255
255
  }
256
- if (entry.state.kind === "ready") {
257
- scheduleIdleStop(entry, entry.state.client);
258
- return;
259
- }
260
- if (entry.state.kind === "idle") {
261
- clearTimeout(entry.state.idleTimer);
262
- scheduleIdleStop(entry, entry.state.client);
263
- }
256
+ if (entry.state.kind === "idle") clearTimeout(entry.state.idleTimer);
257
+ scheduleIdleStop(entry, entry.state.client);
264
258
  };
265
259
  const dispose = async () => {
266
260
  if (disposeCompleted) return [];
@@ -313,7 +307,6 @@ function normalizeClientCreateOptions(options, normalizedCopilotHome) {
313
307
  }
314
308
  function normalizeCopilotHome(copilotHome) {
315
309
  let normalizedHome = resolve(copilotHome);
316
- normalizedHome = normalize(normalizedHome);
317
310
  if (normalizedHome.endsWith(sep) && normalizedHome.length > 1) normalizedHome = normalizedHome.slice(0, -1);
318
311
  if (process.platform === "win32") normalizedHome = normalizedHome.toLowerCase();
319
312
  return normalizedHome;
@@ -1,3 +1,5 @@
1
+ import { asOptionalObjectRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
2
+ import { resolveOptionalIntegerOption } from "openclaw/plugin-sdk/number-runtime";
1
3
  //#region extensions/copilot/src/session-restrictions.ts
2
4
  const COPILOT_ISOLATED_EXCLUDED_TOOLS = [
3
5
  "builtin:*",
@@ -38,27 +40,13 @@ function createCopilotIsolatedSessionRestrictions() {
38
40
  }
39
41
  //#endregion
40
42
  //#region extensions/copilot/src/usage-bridge.ts
41
- function isCopilotUsageSource(data) {
42
- return typeof data === "object" && data !== null;
43
- }
44
- function buildZeroCost() {
45
- return {
46
- cacheRead: 0,
47
- cacheWrite: 0,
48
- input: 0,
49
- output: 0,
50
- total: 0
51
- };
52
- }
53
- function coerceTokenCount(value) {
54
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : void 0;
55
- }
56
43
  function normalizeCopilotUsage(data) {
57
- if (!isCopilotUsageSource(data)) return;
58
- const input = coerceTokenCount(data.inputTokens);
59
- const output = coerceTokenCount(data.outputTokens);
60
- const cacheRead = coerceTokenCount(data.cacheReadTokens);
61
- const cacheWrite = coerceTokenCount(data.cacheWriteTokens);
44
+ const source = asOptionalObjectRecord(data);
45
+ if (!source) return;
46
+ const input = resolveOptionalIntegerOption(source.inputTokens, { min: 0 });
47
+ const output = resolveOptionalIntegerOption(source.outputTokens, { min: 0 });
48
+ const cacheRead = resolveOptionalIntegerOption(source.cacheReadTokens, { min: 0 });
49
+ const cacheWrite = resolveOptionalIntegerOption(source.cacheWriteTokens, { min: 0 });
62
50
  return {
63
51
  cacheRead,
64
52
  cacheWrite,
@@ -72,7 +60,13 @@ function buildCopilotAssistantUsage(params) {
72
60
  return {
73
61
  cacheRead: usage?.cacheRead ?? 0,
74
62
  cacheWrite: usage?.cacheWrite ?? 0,
75
- cost: buildZeroCost(),
63
+ cost: {
64
+ cacheRead: 0,
65
+ cacheWrite: 0,
66
+ input: 0,
67
+ output: 0,
68
+ total: 0
69
+ },
76
70
  input: usage?.input ?? 0,
77
71
  output: usage?.output ?? 0,
78
72
  totalTokens: usage?.total ?? 0
package/dist/harness.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createCopilotAgentHarness } from "./.setup/harness-BAWs53-w.mjs";
1
+ import { t as createCopilotAgentHarness } from "./.setup/harness-BeLT-JyA.mjs";
2
2
  export { createCopilotAgentHarness };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createCopilotAgentHarness } from "./.setup/harness-BAWs53-w.mjs";
1
+ import { t as createCopilotAgentHarness } from "./.setup/harness-BeLT-JyA.mjs";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
4
4
  //#region extensions/copilot/index.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/copilot",
3
- "version": "2026.9.7",
3
+ "version": "2026.10.1-beta.1",
4
4
  "description": "OpenClaw GitHub Copilot agent runtime plugin (registers a `github-copilot` AgentHarness backed by @github/copilot-sdk over JSON-RPC to the GitHub Copilot CLI)",
5
5
  "repository": {
6
6
  "type": "git",
@@ -24,10 +24,10 @@
24
24
  "minHostVersion": ">=2026.5.28"
25
25
  },
26
26
  "compat": {
27
- "pluginApi": ">=2026.9.7"
27
+ "pluginApi": ">=2026.10.1-beta.1"
28
28
  },
29
29
  "build": {
30
- "openclawVersion": "2026.9.7",
30
+ "openclawVersion": "2026.10.1-beta.1",
31
31
  "bundledDist": false
32
32
  },
33
33
  "release": {
@@ -47,7 +47,7 @@
47
47
  "assets/activity.svg"
48
48
  ],
49
49
  "peerDependencies": {
50
- "openclaw": ">=2026.9.7"
50
+ "openclaw": ">=2026.10.1-beta.1"
51
51
  },
52
52
  "peerDependenciesMeta": {
53
53
  "openclaw": {