@openclaw/copilot 2026.7.2-beta.7 → 2026.8.1-beta.3

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.
@@ -6,24 +6,5 @@ function normalizeCompatibilityConfig({ cfg }) {
6
6
  changes: []
7
7
  };
8
8
  }
9
- /**
10
- * Session-state ownership claim for the copilot agent runtime.
11
- *
12
- * - id / label: Identify the extension in doctor output.
13
- * - providerIds: The subscription Copilot providers.
14
- * - runtimeIds: Our harness id (matches harness.ts `id` field).
15
- * - cliSessionKeys: Session keys this harness writes; doctor uses
16
- * this when pruning stale CLI session state.
17
- * - authProfilePrefixes: Conventional prefix for any auth profile
18
- * created/consumed by this extension.
19
- */
20
- const sessionRouteStateOwners = [{
21
- id: "copilot",
22
- label: "GitHub Copilot agent runtime",
23
- providerIds: ["github-copilot"],
24
- runtimeIds: ["copilot"],
25
- cliSessionKeys: ["copilot"],
26
- authProfilePrefixes: ["github-copilot:"]
27
- }];
28
9
  //#endregion
29
- export { legacyConfigRules, normalizeCompatibilityConfig, sessionRouteStateOwners };
10
+ export { legacyConfigRules, normalizeCompatibilityConfig };
@@ -1,3 +1,4 @@
1
+ import { filterStringRecord, normalizeOptionalString, readNonEmptyStringPreservingWhitespace } from "openclaw/plugin-sdk/string-coerce-runtime";
1
2
  import { buildAgentHookContextChannelFields, compactWithSafetyTimeout, getModelProviderRequestTransport, projectSettledTurnFinalizationAttemptResult, resolveCompactionTimeoutMs, runAgentHarnessAfterCompactionHook, runAgentHarnessBeforeCompactionHook } from "openclaw/plugin-sdk/agent-harness-runtime";
2
3
  import { createHash, randomBytes } from "node:crypto";
3
4
  import { homedir } from "node:os";
@@ -84,16 +85,16 @@ function resolveCopilotAuth(input) {
84
85
  const homeDir = input.homeDir ?? homedir;
85
86
  const agentId = sanitizeAgentId(input.agentId);
86
87
  const copilotHome = resolveCopilotHome({
87
- explicit: readString$1(input.copilotHome),
88
- agentDir: readString$1(input.agentDir),
89
- workspaceDir: readString$1(input.workspaceDir),
88
+ explicit: readNonEmptyStringPreservingWhitespace(input.copilotHome),
89
+ agentDir: readNonEmptyStringPreservingWhitespace(input.agentDir),
90
+ workspaceDir: readNonEmptyStringPreservingWhitespace(input.workspaceDir),
90
91
  agentId,
91
92
  env,
92
93
  homeDir
93
94
  });
94
- const explicitToken = readString$1(input.auth?.gitHubToken);
95
- const explicitProfileId = readString$1(input.auth?.profileId) ?? readString$1(input.authProfileId);
96
- const explicitProfileVersion = readString$1(input.auth?.profileVersion) ?? readString$1(input.profileVersion);
95
+ const explicitToken = readNonEmptyStringPreservingWhitespace(input.auth?.gitHubToken);
96
+ const explicitProfileId = readNonEmptyStringPreservingWhitespace(input.auth?.profileId) ?? readNonEmptyStringPreservingWhitespace(input.authProfileId);
97
+ const explicitProfileVersion = readNonEmptyStringPreservingWhitespace(input.auth?.profileVersion) ?? readNonEmptyStringPreservingWhitespace(input.profileVersion);
97
98
  if (input.auth?.useLoggedInUser === true) return {
98
99
  authMode: "useLoggedInUser",
99
100
  copilotHome,
@@ -110,11 +111,11 @@ function resolveCopilotAuth(input) {
110
111
  agentId
111
112
  };
112
113
  }
113
- const contractToken = readString$1(input.resolvedApiKey);
114
+ const contractToken = readNonEmptyStringPreservingWhitespace(input.resolvedApiKey);
114
115
  if (contractToken) return {
115
116
  authMode: "gitHubToken",
116
117
  gitHubToken: contractToken,
117
- authProfileId: readString$1(input.authProfileId) ?? "pi:resolved",
118
+ authProfileId: readNonEmptyStringPreservingWhitespace(input.authProfileId) ?? "pi:resolved",
118
119
  authProfileVersion: tokenFingerprint(contractToken),
119
120
  copilotHome,
120
121
  agentId
@@ -155,7 +156,7 @@ function sanitizeAgentId(value) {
155
156
  function resolveCopilotHome(args) {
156
157
  if (args.explicit) return resolve(args.explicit);
157
158
  if (args.agentDir) return resolve(join(args.agentDir, "copilot"));
158
- const openClawHome = readString$1(args.env.OPENCLAW_HOME);
159
+ const openClawHome = readNonEmptyStringPreservingWhitespace(args.env.OPENCLAW_HOME);
159
160
  return resolve(join(openClawHome ? resolve(openClawHome) : safeHomeDir(args.homeDir), ".openclaw", "agents", args.agentId, "copilot"));
160
161
  }
161
162
  function safeHomeDir(homeDir) {
@@ -169,19 +170,19 @@ function readEnvTokenFallback(env) {
169
170
  const candidates = [
170
171
  {
171
172
  name: "OPENCLAW_GITHUB_TOKEN",
172
- value: readString$1(env.OPENCLAW_GITHUB_TOKEN)
173
+ value: readNonEmptyStringPreservingWhitespace(env.OPENCLAW_GITHUB_TOKEN)
173
174
  },
174
175
  {
175
176
  name: "COPILOT_GITHUB_TOKEN",
176
- value: readString$1(env.COPILOT_GITHUB_TOKEN)
177
+ value: readNonEmptyStringPreservingWhitespace(env.COPILOT_GITHUB_TOKEN)
177
178
  },
178
179
  {
179
180
  name: "GH_TOKEN",
180
- value: readString$1(env.GH_TOKEN)
181
+ value: readNonEmptyStringPreservingWhitespace(env.GH_TOKEN)
181
182
  },
182
183
  {
183
184
  name: "GITHUB_TOKEN",
184
- value: readString$1(env.GITHUB_TOKEN)
185
+ value: readNonEmptyStringPreservingWhitespace(env.GITHUB_TOKEN)
185
186
  }
186
187
  ];
187
188
  for (const { name, value } of candidates) if (value) return {
@@ -201,9 +202,6 @@ function readEnvTokenFallback(env) {
201
202
  function tokenFingerprint(token) {
202
203
  return `sha256:${createHash("sha256").update(token).digest("hex").slice(0, 12)}`;
203
204
  }
204
- function readString$1(value) {
205
- return typeof value === "string" && value.length > 0 ? value : void 0;
206
- }
207
205
  //#endregion
208
206
  //#region extensions/copilot/src/byok-proxy.ts
209
207
  const LOOPBACK_HOST = "127.0.0.1";
@@ -441,15 +439,15 @@ const QUERY_PARAM_NAME_SEPARATOR_RE = /[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu;
441
439
  */
442
440
  function resolveCopilotProvider(params) {
443
441
  if (params.model.provider.trim().toLowerCase() === "github-copilot") return { mode: "github-copilot" };
444
- const baseUrl = readString(params.model.baseUrl);
442
+ const baseUrl = normalizeOptionalString(params.model.baseUrl);
445
443
  if (!baseUrl) throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
446
444
  assertByokEndpointAllowed(baseUrl);
447
445
  if (hasUnsupportedTransportPolicy(params.model)) throw new Error(COPILOT_BYOK_TRANSPORT_POLICY_ERROR);
448
- const api = readString(params.model.api)?.toLowerCase() ?? "openai-responses";
446
+ const api = normalizeOptionalString(params.model.api)?.toLowerCase() ?? "openai-responses";
449
447
  const provider = resolveProviderType(api, baseUrl, params.model.azureApiVersion);
450
448
  const resolvedApiKey = resolveProviderCredential(params.resolvedApiKey);
451
- const headers = resolveProviderHeaders(params.model.headers);
452
- const requestAuthMode = readString(params.model.requestAuthMode)?.toLowerCase();
449
+ const headers = filterStringRecord(params.model.headers);
450
+ const requestAuthMode = normalizeOptionalString(params.model.requestAuthMode)?.toLowerCase();
453
451
  const usePreparedRequestAuth = requestAuthMode !== void 0 && requestAuthMode !== "provider-default";
454
452
  return {
455
453
  mode: "byok",
@@ -484,10 +482,10 @@ function isCopilotByokUnsupportedProviderError(error) {
484
482
  return error instanceof Error && (error.message === COPILOT_BYOK_PROVIDER_ERROR || error.message === COPILOT_BYOK_TRANSPORT_POLICY_ERROR || error.message === COPILOT_BYOK_ENDPOINT_POLICY_ERROR);
485
483
  }
486
484
  function supportsCopilotByokProviderShape(model) {
487
- if (!readString(model.baseUrl) || hasUnsupportedTransportPolicy(model)) return false;
485
+ if (!normalizeOptionalString(model.baseUrl) || hasUnsupportedTransportPolicy(model)) return false;
488
486
  try {
489
- resolveProviderType(readString(model.api)?.toLowerCase() ?? "openai-responses", readString(model.baseUrl), void 0);
490
- assertByokEndpointHostAllowed(readString(model.baseUrl));
487
+ resolveProviderType(normalizeOptionalString(model.api)?.toLowerCase() ?? "openai-responses", normalizeOptionalString(model.baseUrl), void 0);
488
+ assertByokEndpointHostAllowed(normalizeOptionalString(model.baseUrl));
491
489
  return true;
492
490
  } catch {
493
491
  return false;
@@ -556,7 +554,7 @@ function resolveAzureProviderType(baseUrl, apiVersion) {
556
554
  url.pathname = "";
557
555
  url.search = "";
558
556
  url.hash = "";
559
- const resolvedApiVersion = readString(apiVersion);
557
+ const resolvedApiVersion = normalizeOptionalString(apiVersion);
560
558
  return {
561
559
  type: "azure",
562
560
  wireApi: "responses",
@@ -579,18 +577,10 @@ function stableSerialize(value) {
579
577
  if (value && typeof value === "object") return `{${Object.entries(value).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableSerialize(entry)}`).join(",")}}`;
580
578
  return JSON.stringify(value) ?? "null";
581
579
  }
582
- function readString(value) {
583
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
584
- }
585
580
  function resolveProviderCredential(value) {
586
- const credential = readString(value);
581
+ const credential = normalizeOptionalString(value);
587
582
  return credential && !isNonSecretApiKeyMarker(credential) ? credential : void 0;
588
583
  }
589
- function resolveProviderHeaders(headers) {
590
- if (!headers) return;
591
- const resolved = Object.fromEntries(Object.entries(headers).filter(([, value]) => typeof value === "string"));
592
- return Object.keys(resolved).length > 0 ? resolved : void 0;
593
- }
594
584
  //#endregion
595
585
  //#region extensions/copilot/harness.ts
596
586
  const COPILOT_PROVIDER_IDS = /* @__PURE__ */ new Set(["github-copilot"]);
@@ -697,31 +687,35 @@ function readAgentIdFromSessionKey(sessionKey) {
697
687
  const parts = sessionKey.trim().split(":");
698
688
  return parts[0] === "agent" && parts[1]?.trim() ? parts[1].trim() : void 0;
699
689
  }
700
- function computeSessionKey(params, options) {
701
- const p = params;
702
- const modelObj = p.model && typeof p.model === "object" ? p.model : p.runtimeModel && typeof p.runtimeModel === "object" ? p.runtimeModel : { id: typeof p.model === "string" ? p.model : void 0 };
703
- const provider = modelObj.provider ?? (typeof p.provider === "string" ? p.provider : "");
704
- const modelId = modelObj.id ?? (typeof p.modelId === "string" ? p.modelId : void 0) ?? (typeof p.model === "string" ? p.model : "");
705
- const requestTransport = p.model && typeof p.model === "object" ? getModelProviderRequestTransport(p.model) : void 0;
706
- const requestAuthMode = readSessionString(requestTransport?.auth?.mode ?? modelObj.request?.auth?.mode);
707
- const azureApiVersion = readSessionString(modelObj.azureApiVersion ?? modelObj.params?.azureApiVersion);
690
+ function computeSessionKey(input, options) {
691
+ const attempt = input.kind === "attempt" ? input.params : void 0;
692
+ const compact = input.kind === "compact" ? input.params : void 0;
693
+ const attemptModel = attempt?.model;
694
+ const compactModel = compact?.model;
695
+ const rawModel = attemptModel ?? compactModel;
696
+ const modelObj = rawModel && typeof rawModel === "object" ? rawModel : compact?.runtimeModel ?? { id: typeof rawModel === "string" ? rawModel : void 0 };
697
+ const provider = normalizeOptionalString(modelObj.provider) ?? attempt?.provider ?? compact?.provider ?? "";
698
+ const modelId = normalizeOptionalString(modelObj.id) ?? attempt?.modelId ?? compact?.modelId ?? (typeof compactModel === "string" ? compactModel : "");
699
+ const requestTransport = rawModel && typeof rawModel === "object" ? getModelProviderRequestTransport(rawModel) : void 0;
700
+ const requestAuthMode = normalizeOptionalString(requestTransport?.auth?.mode ?? modelObj.request?.auth?.mode);
701
+ const azureApiVersion = normalizeOptionalString(modelObj.azureApiVersion ?? modelObj.params?.azureApiVersion);
708
702
  let authParts;
709
703
  let resolvedAgentId = "";
710
704
  let resolvedCopilotHome = "";
711
705
  try {
712
706
  const resolved = !options.includeAuth ? resolveCopilotAuth({
713
- agentId: typeof p.agentId === "string" ? p.agentId : readAgentIdFromSessionKey(p.sessionKey),
714
- agentDir: typeof p.agentDir === "string" ? p.agentDir : void 0,
715
- workspaceDir: typeof p.workspaceDir === "string" ? p.workspaceDir : void 0,
716
- copilotHome: typeof p.copilotHome === "string" ? p.copilotHome : void 0,
707
+ agentId: input.params.agentId ?? readAgentIdFromSessionKey(input.params.sessionKey),
708
+ agentDir: input.params.agentDir,
709
+ workspaceDir: input.params.workspaceDir,
710
+ copilotHome: input.params.copilotHome,
717
711
  auth: { useLoggedInUser: true }
718
712
  }) : (() => {
719
713
  const modelProvider = resolveCopilotProvider({
720
714
  model: {
721
- api: modelObj.api,
715
+ api: normalizeOptionalString(modelObj.api),
722
716
  id: modelId,
723
717
  provider,
724
- baseUrl: modelObj.baseUrl,
718
+ baseUrl: normalizeOptionalString(modelObj.baseUrl),
725
719
  azureApiVersion,
726
720
  headers: modelObj.headers,
727
721
  authHeader: modelObj.authHeader,
@@ -733,25 +727,25 @@ function computeSessionKey(params, options) {
733
727
  contextWindow: modelObj.contextWindow,
734
728
  maxTokens: modelObj.maxTokens
735
729
  },
736
- resolvedApiKey: typeof p.resolvedApiKey === "string" ? p.resolvedApiKey : void 0,
737
- authProfileId: typeof p.authProfileId === "string" ? p.authProfileId : void 0
730
+ resolvedApiKey: input.params.resolvedApiKey,
731
+ authProfileId: input.params.authProfileId
738
732
  });
739
733
  return modelProvider.mode === "byok" ? createCopilotByokAuth({
740
- agentId: typeof p.agentId === "string" ? p.agentId : readAgentIdFromSessionKey(p.sessionKey),
741
- agentDir: typeof p.agentDir === "string" ? p.agentDir : void 0,
742
- workspaceDir: typeof p.workspaceDir === "string" ? p.workspaceDir : void 0,
743
- copilotHome: typeof p.copilotHome === "string" ? p.copilotHome : void 0,
734
+ agentId: input.params.agentId ?? readAgentIdFromSessionKey(input.params.sessionKey),
735
+ agentDir: input.params.agentDir,
736
+ workspaceDir: input.params.workspaceDir,
737
+ copilotHome: input.params.copilotHome,
744
738
  authProfileId: modelProvider.authProfileId,
745
739
  authProfileVersion: modelProvider.authProfileVersion
746
740
  }) : resolveCopilotAuth({
747
- agentId: typeof p.agentId === "string" ? p.agentId : readAgentIdFromSessionKey(p.sessionKey),
748
- agentDir: typeof p.agentDir === "string" ? p.agentDir : void 0,
749
- workspaceDir: typeof p.workspaceDir === "string" ? p.workspaceDir : void 0,
750
- copilotHome: typeof p.copilotHome === "string" ? p.copilotHome : void 0,
751
- auth: p.auth,
752
- resolvedApiKey: typeof p.resolvedApiKey === "string" ? p.resolvedApiKey : void 0,
753
- authProfileId: typeof p.authProfileId === "string" ? p.authProfileId : void 0,
754
- profileVersion: typeof p.profileVersion === "string" ? p.profileVersion : void 0
741
+ agentId: input.params.agentId ?? readAgentIdFromSessionKey(input.params.sessionKey),
742
+ agentDir: input.params.agentDir,
743
+ workspaceDir: input.params.workspaceDir,
744
+ copilotHome: input.params.copilotHome,
745
+ auth: input.params.auth,
746
+ resolvedApiKey: input.params.resolvedApiKey,
747
+ authProfileId: input.params.authProfileId,
748
+ profileVersion: input.params.profileVersion
755
749
  });
756
750
  })();
757
751
  resolvedAgentId = resolved.agentId;
@@ -768,30 +762,42 @@ function computeSessionKey(params, options) {
768
762
  return [
769
763
  `provider=${provider}`,
770
764
  `model=${modelId}`,
771
- ...options.includeApi ? [`api=${modelObj.api ?? ""}`] : [],
765
+ ...options.includeApi ? [`api=${normalizeOptionalString(modelObj.api) ?? ""}`] : [],
772
766
  ...options.includeApi ? [`baseUrlFingerprint=${fingerprintSessionValue(modelObj.baseUrl)}`] : [],
773
- `cwd=${p.cwd ?? p.workspaceDir ?? ""}`,
767
+ `cwd=${input.params.cwd ?? input.params.workspaceDir ?? ""}`,
774
768
  `agentId=${resolvedAgentId}`,
775
- `agentDir=${p.agentDir ?? ""}`,
776
- `copilotHome=${p.copilotHome ?? ""}`,
769
+ `agentDir=${input.params.agentDir ?? ""}`,
770
+ `copilotHome=${input.params.copilotHome ?? ""}`,
777
771
  `resolvedCopilotHome=${resolvedCopilotHome}`,
778
772
  ...options.includeAuth ? authParts : []
779
773
  ].join("|");
780
774
  }
781
- function readSessionString(value) {
782
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
783
- }
784
775
  function fingerprintSessionValue(value) {
785
776
  return typeof value === "string" && value ? tokenFingerprint(value) : "";
786
777
  }
787
778
  function computeSessionCompatKey(params) {
788
- return computeSessionKey(params, {
779
+ return computeSessionKey({
780
+ kind: "attempt",
781
+ params
782
+ }, {
789
783
  includeApi: true,
790
784
  includeAuth: true
791
785
  });
792
786
  }
793
- function computeSessionCompactKey(params) {
794
- return computeSessionKey(params, {
787
+ function computeAttemptCompactKey(params) {
788
+ return computeSessionKey({
789
+ kind: "attempt",
790
+ params
791
+ }, {
792
+ includeApi: false,
793
+ includeAuth: false
794
+ });
795
+ }
796
+ function computeCompactRequestKey(params) {
797
+ return computeSessionKey({
798
+ kind: "compact",
799
+ params
800
+ }, {
795
801
  includeApi: false,
796
802
  includeAuth: false
797
803
  });
@@ -821,7 +827,7 @@ function createCopilotAgentHarness(options) {
821
827
  async function getPool() {
822
828
  if (options?.pool) return options.pool;
823
829
  if (!poolPromise) poolPromise = (async () => {
824
- const { createCopilotClientPool } = await import("./runtime-BY2Yi3Dg.js");
830
+ const { createCopilotClientPool } = await import("./runtime-C2t8Iz5R.js");
825
831
  createdPool = createCopilotClientPool(options?.poolOptions);
826
832
  return createdPool;
827
833
  })();
@@ -858,7 +864,7 @@ function createCopilotAgentHarness(options) {
858
864
  async function runHarnessAttempt(params, operation) {
859
865
  const attemptPromise = (async () => {
860
866
  if (disposed) throw new Error("[copilot] harness has been disposed; cannot start new attempts");
861
- const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-D6tQnv01.js");
867
+ const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-DsIndF6T.js");
862
868
  if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
863
869
  const pool = await getPool();
864
870
  if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
@@ -871,7 +877,7 @@ function createCopilotAgentHarness(options) {
871
877
  }
872
878
  const openclawSessionId = typeof params.sessionId === "string" ? params.sessionId : void 0;
873
879
  const currentCompatKey = computeSessionCompatKey(params);
874
- const currentCompactKey = computeSessionCompactKey(params);
880
+ const currentCompactKey = computeAttemptCompactKey(params);
875
881
  const compactionCleanupPending = openclawSessionId !== void 0 && hasPendingDeferredCompactionCleanup(openclawSessionId);
876
882
  const replayBlocked = openclawSessionId !== void 0 && (compactionCleanupPending || resetBlockedStoredSessions.has(openclawSessionId));
877
883
  const tracked = openclawSessionId && !replayBlocked ? trackedSessions.get(openclawSessionId) : void 0;
@@ -986,10 +992,29 @@ function createCopilotAgentHarness(options) {
986
992
  inFlight.delete(attemptPromise);
987
993
  }
988
994
  }
995
+ async function runIsolatedCompletionV2(params) {
996
+ const completionPromise = (async () => {
997
+ if (disposed) throw new Error("[copilot] harness has been disposed; cannot start isolated completion");
998
+ const { runCopilotIsolatedCompletion } = await import("./isolated-completion-D9VIGPmy.js");
999
+ if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
1000
+ return await runCopilotIsolatedCompletion(params, async () => {
1001
+ const pool = await getPool();
1002
+ if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
1003
+ return pool;
1004
+ });
1005
+ })();
1006
+ inFlight.add(completionPromise);
1007
+ try {
1008
+ return await completionPromise;
1009
+ } finally {
1010
+ inFlight.delete(completionPromise);
1011
+ }
1012
+ }
989
1013
  return {
990
1014
  id: options?.id ?? "copilot",
991
1015
  label: options?.label ?? "GitHub Copilot agent runtime",
992
1016
  autoSelection: { providerIds: [] },
1017
+ conversationToolPolicySupport: "exact",
993
1018
  supports(ctx) {
994
1019
  if (String(ctx.requestedRuntime ?? "").trim().toLowerCase() !== "copilot") return {
995
1020
  supported: false,
@@ -1025,6 +1050,7 @@ function createCopilotAgentHarness(options) {
1025
1050
  };
1026
1051
  },
1027
1052
  runAttempt: (params) => runHarnessAttempt(params, "attempt"),
1053
+ runIsolatedCompletionV2,
1028
1054
  finalizeSettledTurn: async ({ attempt }) => {
1029
1055
  return projectSettledTurnFinalizationAttemptResult(await runHarnessAttempt(attempt, "settled-tool-finalization"));
1030
1056
  },
@@ -1059,8 +1085,8 @@ function createCopilotAgentHarness(options) {
1059
1085
  failure: { reason: "background-compaction-pending" }
1060
1086
  };
1061
1087
  const tracked = trackedSessions.get(openclawSessionId);
1062
- const currentCompactKey = computeSessionCompactKey(params);
1063
- const { resolvePoolAcquire } = await import("./attempt-D6tQnv01.js");
1088
+ const currentCompactKey = computeCompactRequestKey(params);
1089
+ const { resolvePoolAcquire } = await import("./attempt-DsIndF6T.js");
1064
1090
  let resolvedPoolAcquire;
1065
1091
  let currentAuth;
1066
1092
  try {
@@ -1200,4 +1226,4 @@ function createCopilotAgentHarness(options) {
1200
1226
  };
1201
1227
  }
1202
1228
  //#endregion
1203
- export { resolveCopilotAuth as a, createCopilotByokAuth as i, resolveCopilotProvider as n, createCopilotByokProxy as r, createCopilotAgentHarness as t };
1229
+ export { resolveCopilotAuth as a, createCopilotByokAuth as i, resolveCopilotProvider as n, tokenFingerprint as o, createCopilotByokProxy as r, createCopilotAgentHarness as t };
package/dist/harness.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createCopilotAgentHarness } from "./harness-D0K-5kNw.js";
1
+ import { t as createCopilotAgentHarness } from "./harness-BJ_IcIJk.js";
2
2
  export { createCopilotAgentHarness };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createCopilotAgentHarness } from "./harness-D0K-5kNw.js";
1
+ import { t as createCopilotAgentHarness } from "./harness-BJ_IcIJk.js";
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
@@ -0,0 +1,207 @@
1
+ import { n as resolveCopilotProvider, o as tokenFingerprint, r as createCopilotByokProxy } from "./harness-BJ_IcIJk.js";
2
+ import { r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.js";
3
+ import { resolve } from "node:path";
4
+ //#region extensions/copilot/src/isolated-completion.ts
5
+ function startBestEffortCleanup(cleanup) {
6
+ try {
7
+ cleanup().catch(() => void 0);
8
+ } catch {}
9
+ }
10
+ function resolveReasoningEffort(thinkLevel) {
11
+ return thinkLevel === "low" || thinkLevel === "medium" || thinkLevel === "high" || thinkLevel === "xhigh" ? thinkLevel : void 0;
12
+ }
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
+ function createTimeoutError(timeoutMs) {
20
+ const error = /* @__PURE__ */ new Error(`[copilot] isolated completion timed out after ${timeoutMs}ms`);
21
+ error.name = "TimeoutError";
22
+ return error;
23
+ }
24
+ async function awaitWithinCompletionBoundary(params) {
25
+ const signal = params.boundary.abortSignal;
26
+ if (signal?.aborted) throw createAbortError(signal);
27
+ const remainingMs = params.boundary.deadlineMs - Date.now();
28
+ if (remainingMs <= 0) throw createTimeoutError(params.boundary.timeoutMs);
29
+ let boundaryWon = false;
30
+ let boundaryError;
31
+ let timer;
32
+ let onAbort;
33
+ const boundary = new Promise((_resolve, reject) => {
34
+ const rejectBoundary = (error) => {
35
+ if (boundaryWon) return;
36
+ boundaryWon = true;
37
+ boundaryError = error;
38
+ params.onBoundary?.();
39
+ reject(error);
40
+ };
41
+ timer = setTimeout(() => rejectBoundary(createTimeoutError(params.boundary.timeoutMs)), remainingMs);
42
+ if (signal) {
43
+ onAbort = () => rejectBoundary(createAbortError(signal));
44
+ signal.addEventListener("abort", onAbort, { once: true });
45
+ if (signal.aborted) onAbort();
46
+ }
47
+ });
48
+ const operation = Promise.resolve().then(() => {
49
+ if (boundaryWon) throw boundaryError ?? createTimeoutError(params.boundary.timeoutMs);
50
+ return params.start(remainingMs);
51
+ }).then(async (value) => {
52
+ if (boundaryWon) await params.cleanupLate?.(value);
53
+ return value;
54
+ });
55
+ try {
56
+ return await Promise.race([operation, boundary]);
57
+ } finally {
58
+ if (timer) clearTimeout(timer);
59
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
60
+ }
61
+ }
62
+ async function sendPrompt(params) {
63
+ return await awaitWithinCompletionBoundary({
64
+ boundary: params.boundary,
65
+ start: async (remainingMs) => await params.session.sendAndWait({
66
+ prompt: params.prompt,
67
+ ...params.requestHeaders ? { requestHeaders: params.requestHeaders } : {}
68
+ }, remainingMs),
69
+ onBoundary: () => {
70
+ params.session.abort().catch(() => void 0);
71
+ }
72
+ });
73
+ }
74
+ async function runCopilotIsolatedCompletion(params, getPool) {
75
+ const reasoningEffort = resolveReasoningEffort(params.thinkLevel);
76
+ if (params.thinkLevel !== void 0 && reasoningEffort === void 0) throw new Error(`[copilot] isolated completion does not support thinking level ${params.thinkLevel}`);
77
+ const boundary = {
78
+ abortSignal: params.abortSignal,
79
+ deadlineMs: Date.now() + params.timeoutMs,
80
+ timeoutMs: params.timeoutMs
81
+ };
82
+ if (params.authorization.owner !== "host") throw new Error("[copilot] isolated completion requires host-prepared authorization");
83
+ const authorization = params.authorization;
84
+ const { auth, model } = authorization;
85
+ const apiKey = auth.apiKey?.trim();
86
+ if (!apiKey) throw new Error("[copilot] isolated completion requires the prepared credential");
87
+ const resolvedProvider = resolveCopilotProvider({
88
+ model: {
89
+ api: model.api,
90
+ id: model.id,
91
+ provider: model.provider,
92
+ baseUrl: model.baseUrl,
93
+ headers: model.headers,
94
+ authHeader: model.authHeader,
95
+ contextTokens: model.contextTokens,
96
+ contextWindow: model.contextWindow,
97
+ maxTokens: params.streamParams?.maxTokens ?? model.maxTokens,
98
+ azureApiVersion: typeof model.params?.azureApiVersion === "string" ? model.params.azureApiVersion : void 0
99
+ },
100
+ resolvedApiKey: apiKey,
101
+ authProfileId: auth.profileId
102
+ });
103
+ const pool = await awaitWithinCompletionBoundary({
104
+ boundary,
105
+ start: getPool
106
+ });
107
+ const byokProxy = await awaitWithinCompletionBoundary({
108
+ boundary,
109
+ start: async () => await createCopilotByokProxy(resolvedProvider),
110
+ cleanupLate: async (proxy) => await proxy?.close()
111
+ });
112
+ const sessionProvider = byokProxy?.provider ?? resolvedProvider;
113
+ const githubAuth = sessionProvider.mode === "github-copilot";
114
+ const copilotHome = resolve(params.agentDir, "copilot");
115
+ const authProfileId = auth.profileId?.trim() || "prepared";
116
+ const authProfileVersion = authorization.sourceAuthFingerprint?.trim() || tokenFingerprint(apiKey);
117
+ let handle;
118
+ let session;
119
+ try {
120
+ const acquiredHandle = await awaitWithinCompletionBoundary({
121
+ boundary,
122
+ start: async () => await pool.acquire({
123
+ agentId: params.agentId,
124
+ authMode: githubAuth ? "gitHubToken" : "byok",
125
+ authProfileId,
126
+ authProfileVersion,
127
+ copilotHome,
128
+ clientMode: "empty"
129
+ }, {
130
+ copilotHome,
131
+ mode: "empty",
132
+ useLoggedInUser: false,
133
+ ...githubAuth ? { gitHubToken: apiKey } : {}
134
+ }),
135
+ cleanupLate: async (lateHandle) => await pool.release(lateHandle)
136
+ });
137
+ handle = acquiredHandle;
138
+ const sessionConfig = {
139
+ ...createCopilotIsolatedSessionRestrictions(),
140
+ model: model.id,
141
+ ...githubAuth ? { gitHubToken: apiKey } : {},
142
+ ...sessionProvider.provider ? { provider: sessionProvider.provider } : {},
143
+ ...reasoningEffort ? { reasoningEffort } : {},
144
+ systemMessage: {
145
+ mode: "replace",
146
+ content: params.systemPrompt
147
+ },
148
+ workingDirectory: params.workspaceDir
149
+ };
150
+ const createdSession = await awaitWithinCompletionBoundary({
151
+ boundary,
152
+ start: async () => await acquiredHandle.client.createSession(sessionConfig),
153
+ cleanupLate: async (lateSession) => {
154
+ startBestEffortCleanup(async () => await lateSession.abort());
155
+ startBestEffortCleanup(async () => await lateSession.disconnect());
156
+ }
157
+ });
158
+ session = createdSession;
159
+ const event = await sendPrompt({
160
+ boundary,
161
+ prompt: params.prompt,
162
+ requestHeaders: sessionProvider.provider?.headers,
163
+ session: createdSession
164
+ });
165
+ if (event?.type !== "assistant.message" || event.agentId !== void 0) throw new Error("[copilot] isolated completion did not return a root assistant message");
166
+ const content = [];
167
+ if (event.data.reasoningText) content.push({
168
+ type: "thinking",
169
+ thinking: event.data.reasoningText
170
+ });
171
+ if (event.data.content) content.push({
172
+ type: "text",
173
+ text: event.data.content
174
+ });
175
+ for (const toolRequest of event.data.toolRequests ?? []) {
176
+ const toolArguments = toolRequest.arguments;
177
+ content.push({
178
+ type: "toolCall",
179
+ id: toolRequest.toolCallId,
180
+ name: toolRequest.name,
181
+ arguments: toolArguments && typeof toolArguments === "object" && !Array.isArray(toolArguments) ? { ...toolArguments } : {}
182
+ });
183
+ }
184
+ return { assistant: {
185
+ role: "assistant",
186
+ content,
187
+ api: model.api,
188
+ provider: model.provider,
189
+ model: event.data.model ?? model.id,
190
+ stopReason: event.data.toolRequests?.length ? "toolUse" : "stop",
191
+ timestamp: Date.now(),
192
+ usage: buildCopilotAssistantUsage({ fallbackOutputTokens: event.data.outputTokens })
193
+ } };
194
+ } finally {
195
+ if (session) {
196
+ const sessionToClose = session;
197
+ startBestEffortCleanup(async () => await sessionToClose.disconnect());
198
+ }
199
+ if (byokProxy) startBestEffortCleanup(async () => await byokProxy.close());
200
+ if (handle) {
201
+ const handleToRelease = handle;
202
+ startBestEffortCleanup(async () => await pool.release(handleToRelease));
203
+ }
204
+ }
205
+ }
206
+ //#endregion
207
+ export { runCopilotIsolatedCompletion };