@openclaw/copilot 2026.11.3 → 2026.11.5-beta.2

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.
@@ -4,6 +4,7 @@ import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
4
4
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
5
5
  import { homedir } from "node:os";
6
6
  import { join, resolve } from "node:path";
7
+ import { once } from "node:events";
7
8
  import { createServer } from "node:http";
8
9
  import { Readable } from "node:stream";
9
10
  import { pipeline } from "node:stream/promises";
@@ -12,14 +13,24 @@ import { isNonSecretApiKeyMarker } from "openclaw/plugin-sdk/provider-auth";
12
13
  //#region extensions/copilot/src/auth-bridge.ts
13
14
  const COPILOT_TOKEN_PROFILE_ERROR = "[copilot-attempt] gitHubToken auth requires profileId+profileVersion (pool keying safety; per Q5/Q1 decisions)";
14
15
  const COPILOT_DEFAULT_AGENT_ID = "copilot";
16
+ function sessionAuthFields(auth) {
17
+ return auth.authMode === "gitHubToken" || auth.authMode === "byok" ? {
18
+ authMode: auth.authMode,
19
+ authProfileId: auth.authProfileId,
20
+ authProfileVersion: auth.authProfileVersion
21
+ } : { authMode: "useLoggedInUser" };
22
+ }
23
+ function sessionAuthMatches(stored, current) {
24
+ if (stored.authMode !== current.authMode) return false;
25
+ if (stored.authMode === "useLoggedInUser") return true;
26
+ return stored.authProfileId === current.authProfileId && stored.authProfileVersion === current.authProfileVersion;
27
+ }
15
28
  function createCopilotByokAuth(input) {
16
29
  return {
17
30
  ...resolveCopilotAuth({
18
31
  agentId: input.agentId,
19
32
  agentDir: input.agentDir,
20
33
  copilotHome: input.copilotHome,
21
- env: input.env,
22
- homeDir: input.homeDir,
23
34
  auth: { useLoggedInUser: true }
24
35
  }),
25
36
  authMode: "byok",
@@ -28,16 +39,18 @@ function createCopilotByokAuth(input) {
28
39
  };
29
40
  }
30
41
  function resolveCopilotAuth(input) {
31
- const env = input.env ?? process.env;
32
- const homeDir = input.homeDir ?? homedir;
33
- const agentId = sanitizeAgentId(input.agentId);
34
- const copilotHome = resolveCopilotHome({
35
- explicit: readNonEmptyStringPreservingWhitespace(input.copilotHome),
36
- agentDir: readNonEmptyStringPreservingWhitespace(input.agentDir),
37
- agentId,
38
- env,
39
- homeDir
40
- });
42
+ const normalizedAgentId = (input.agentId ?? "").trim().toLowerCase();
43
+ const agentId = /^[a-z0-9][a-z0-9_-]{0,63}$/.test(normalizedAgentId) ? normalizedAgentId : COPILOT_DEFAULT_AGENT_ID;
44
+ const explicitHome = readNonEmptyStringPreservingWhitespace(input.copilotHome);
45
+ const agentDir = readNonEmptyStringPreservingWhitespace(input.agentDir);
46
+ let copilotHome;
47
+ if (explicitHome) copilotHome = resolve(explicitHome);
48
+ else if (agentDir) copilotHome = resolve(join(agentDir, "copilot"));
49
+ else {
50
+ const openClawHome = readNonEmptyStringPreservingWhitespace(process.env.OPENCLAW_HOME);
51
+ const rootHome = openClawHome ? resolve(openClawHome) : homedir();
52
+ copilotHome = resolve(join(rootHome, ".openclaw", "agents", agentId, "copilot"));
53
+ }
41
54
  const explicitToken = readNonEmptyStringPreservingWhitespace(input.auth?.gitHubToken);
42
55
  const explicitProfileId = readNonEmptyStringPreservingWhitespace(input.auth?.profileId) ?? readNonEmptyStringPreservingWhitespace(input.authProfileId);
43
56
  const explicitProfileVersion = readNonEmptyStringPreservingWhitespace(input.auth?.profileVersion) ?? readNonEmptyStringPreservingWhitespace(input.profileVersion);
@@ -66,40 +79,7 @@ function resolveCopilotAuth(input) {
66
79
  copilotHome,
67
80
  agentId
68
81
  };
69
- const envFallback = readEnvTokenFallback(env);
70
- if (envFallback) return {
71
- authMode: "gitHubToken",
72
- gitHubToken: envFallback.token,
73
- authProfileId: envFallback.profileId,
74
- authProfileVersion: envFallback.profileVersion,
75
- copilotHome,
76
- agentId
77
- };
78
- return {
79
- authMode: "useLoggedInUser",
80
- copilotHome,
81
- agentId
82
- };
83
- }
84
- function sanitizeAgentId(value) {
85
- const trimmed = (value ?? "").trim().toLowerCase();
86
- return /^[a-z0-9][a-z0-9_-]{0,63}$/.test(trimmed) ? trimmed : COPILOT_DEFAULT_AGENT_ID;
87
- }
88
- function resolveCopilotHome(args) {
89
- if (args.explicit) return resolve(args.explicit);
90
- if (args.agentDir) return resolve(join(args.agentDir, "copilot"));
91
- const openClawHome = readNonEmptyStringPreservingWhitespace(args.env.OPENCLAW_HOME);
92
- const rootHome = openClawHome ? resolve(openClawHome) : safeHomeDir(args.homeDir);
93
- return resolve(join(rootHome, ".openclaw", "agents", args.agentId, "copilot"));
94
- }
95
- function safeHomeDir(homeDir) {
96
- try {
97
- const value = homeDir();
98
- if (typeof value === "string" && value.length > 0) return value;
99
- } catch {}
100
- return process.cwd();
101
- }
102
- function readEnvTokenFallback(env) {
82
+ const env = process.env;
103
83
  const candidates = [
104
84
  {
105
85
  name: "OPENCLAW_GITHUB_TOKEN",
@@ -119,9 +99,17 @@ function readEnvTokenFallback(env) {
119
99
  }
120
100
  ];
121
101
  for (const { name, value } of candidates) if (value) return {
122
- token: value,
123
- profileId: `env:${name}`,
124
- profileVersion: tokenFingerprint(value)
102
+ authMode: "gitHubToken",
103
+ gitHubToken: value,
104
+ authProfileId: `env:${name}`,
105
+ authProfileVersion: tokenFingerprint(value),
106
+ copilotHome,
107
+ agentId
108
+ };
109
+ return {
110
+ authMode: "useLoggedInUser",
111
+ copilotHome,
112
+ agentId
125
113
  };
126
114
  }
127
115
  /** Pool invalidation fingerprint; never log it alongside an account id. */
@@ -141,29 +129,77 @@ async function createCopilotByokProxy(resolvedProvider) {
141
129
  const targetPathPrefix = targetBaseUrl.pathname.replace(/\/+$/, "");
142
130
  const proxyPathPrefix = `/${nonce}${targetPathPrefix}`;
143
131
  const acceptsAzureSdkPaths = providerConfig.type === "azure";
144
- const proxyCredentialHeader = acceptsAzureSdkPaths ? createProxyCredentialHeaderName(providerConfig.headers) : void 0;
132
+ const proxyCredentialHeader = acceptsAzureSdkPaths ? `${PROXY_CREDENTIAL_HEADER_PREFIX}${randomBytes(12).toString("hex")}` : void 0;
145
133
  const bearerToken = providerConfig.bearerToken?.trim();
146
134
  const upstreamBearerAuthorization = bearerToken ? `Bearer ${bearerToken}` : void 0;
147
135
  const activeFetches = /* @__PURE__ */ new Set();
148
- const server = createServer((req, res) => {
149
- handleProxyRequest(req, res, {
150
- acceptsAzureSdkPaths,
151
- activeFetches,
152
- proxyPathPrefix,
153
- proxyCredential: nonce,
154
- proxyCredentialHeader,
155
- targetBaseUrl,
156
- targetPathPrefix,
157
- upstreamBearerAuthorization
158
- });
159
- });
160
- await new Promise((resolve, reject) => {
161
- server.once("error", reject);
162
- server.listen(0, LOOPBACK_HOST, () => {
163
- server.off("error", reject);
164
- resolve();
136
+ async function handleProxyRequest(req, res) {
137
+ let guarded;
138
+ const upstreamAbort = new AbortController();
139
+ activeFetches.add(upstreamAbort);
140
+ const abortUpstream = () => upstreamAbort.abort();
141
+ req.on("aborted", abortUpstream);
142
+ res.on("close", () => {
143
+ if (!res.writableEnded) abortUpstream();
165
144
  });
145
+ try {
146
+ const target = resolveTargetUrl(req);
147
+ if (!target || !target.nonceProtected && (!proxyCredentialHeader || !hasValidProxyCredential(req, proxyCredentialHeader, nonce))) {
148
+ res.writeHead(404);
149
+ res.end("Not found");
150
+ return;
151
+ }
152
+ const body = req.method === "GET" || req.method === "HEAD" ? void 0 : await readBody(req);
153
+ guarded = await fetchWithSsrFGuard({
154
+ url: target.url.toString(),
155
+ init: {
156
+ method: req.method,
157
+ headers: buildProxyRequestHeaders(req.headers, {
158
+ upstreamBearerAuthorization: target.nonceProtected ? upstreamBearerAuthorization : void 0,
159
+ proxyCredentialHeader
160
+ }),
161
+ signal: upstreamAbort.signal,
162
+ ...body ? { body } : {}
163
+ },
164
+ auditContext: "copilot-byok-provider",
165
+ requireHttps: true
166
+ });
167
+ res.writeHead(guarded.response.status, guarded.response.statusText, normalizeProxyResponseHeaders(guarded.response.headers));
168
+ if (!guarded.response.body) {
169
+ res.end();
170
+ return;
171
+ }
172
+ await pipeline(Readable.fromWeb(guarded.response.body), res);
173
+ } catch (error) {
174
+ if (res.destroyed || res.writableEnded) return;
175
+ if (res.headersSent) {
176
+ res.destroy(error instanceof Error ? error : void 0);
177
+ return;
178
+ }
179
+ res.writeHead(502);
180
+ res.end(error instanceof Error ? error.message : "BYOK provider proxy failed");
181
+ } finally {
182
+ req.off("aborted", abortUpstream);
183
+ activeFetches.delete(upstreamAbort);
184
+ await guarded?.release().catch(() => void 0);
185
+ }
186
+ }
187
+ function resolveTargetUrl(req) {
188
+ const incomingUrl = new URL(req.url ?? "/", `http://${LOOPBACK_HOST}`);
189
+ const nonceProtected = incomingUrl.pathname === proxyPathPrefix || incomingUrl.pathname.startsWith(`${proxyPathPrefix}/`);
190
+ if (!nonceProtected && !(acceptsAzureSdkPaths && (incomingUrl.pathname === "/openai" || incomingUrl.pathname.startsWith("/openai/")))) return;
191
+ const targetUrl = new URL(targetBaseUrl);
192
+ targetUrl.pathname = nonceProtected ? `${targetPathPrefix}${incomingUrl.pathname.slice(proxyPathPrefix.length)}` || "/" : incomingUrl.pathname;
193
+ for (const [key, value] of incomingUrl.searchParams) targetUrl.searchParams.append(key, value);
194
+ return {
195
+ url: targetUrl,
196
+ nonceProtected
197
+ };
198
+ }
199
+ const server = createServer((req, res) => {
200
+ handleProxyRequest(req, res);
166
201
  });
202
+ await once(server.listen(0, LOOPBACK_HOST), "listening");
167
203
  const address = server.address();
168
204
  if (!address || typeof address === "string") {
169
205
  server.close();
@@ -192,72 +228,6 @@ async function createCopilotByokProxy(resolvedProvider) {
192
228
  }
193
229
  };
194
230
  }
195
- async function handleProxyRequest(req, res, params) {
196
- let guarded;
197
- const upstreamAbort = new AbortController();
198
- params.activeFetches.add(upstreamAbort);
199
- const abortUpstream = () => upstreamAbort.abort();
200
- req.on("aborted", abortUpstream);
201
- res.on("close", () => {
202
- if (!res.writableEnded) abortUpstream();
203
- });
204
- try {
205
- const target = resolveTargetUrl(req, params);
206
- if (!target || !target.nonceProtected && (!params.proxyCredentialHeader || !hasValidProxyCredential(req, params.proxyCredentialHeader, params.proxyCredential))) {
207
- res.writeHead(404);
208
- res.end("Not found");
209
- return;
210
- }
211
- const body = req.method === "GET" || req.method === "HEAD" ? void 0 : await readBody(req);
212
- guarded = await fetchWithSsrFGuard({
213
- url: target.url.toString(),
214
- init: {
215
- method: req.method,
216
- headers: buildProxyRequestHeaders(req.headers, {
217
- upstreamBearerAuthorization: target.nonceProtected ? params.upstreamBearerAuthorization : void 0,
218
- proxyCredentialHeader: params.proxyCredentialHeader
219
- }),
220
- signal: upstreamAbort.signal,
221
- ...body ? { body } : {}
222
- },
223
- auditContext: "copilot-byok-provider",
224
- requireHttps: true
225
- });
226
- res.writeHead(guarded.response.status, guarded.response.statusText, normalizeProxyResponseHeaders(guarded.response.headers));
227
- if (!guarded.response.body) {
228
- res.end();
229
- return;
230
- }
231
- await pipeline(Readable.fromWeb(guarded.response.body), res);
232
- } catch (error) {
233
- if (res.destroyed || res.writableEnded) return;
234
- if (res.headersSent) {
235
- res.destroy(error instanceof Error ? error : void 0);
236
- return;
237
- }
238
- res.writeHead(502);
239
- res.end(error instanceof Error ? error.message : "BYOK provider proxy failed");
240
- } finally {
241
- req.off("aborted", abortUpstream);
242
- params.activeFetches.delete(upstreamAbort);
243
- await guarded?.release().catch(() => void 0);
244
- }
245
- }
246
- function resolveTargetUrl(req, params) {
247
- const incomingUrl = new URL(req.url ?? "/", `http://${LOOPBACK_HOST}`);
248
- const nonceProtected = incomingUrl.pathname === params.proxyPathPrefix || incomingUrl.pathname.startsWith(`${params.proxyPathPrefix}/`);
249
- if (!nonceProtected && !(params.acceptsAzureSdkPaths && isAzureSdkProxyPath(incomingUrl.pathname))) return;
250
- const targetUrl = new URL(params.targetBaseUrl);
251
- targetUrl.pathname = nonceProtected ? `${params.targetPathPrefix}${incomingUrl.pathname.slice(params.proxyPathPrefix.length)}` || "/" : incomingUrl.pathname;
252
- for (const [key, value] of incomingUrl.searchParams) targetUrl.searchParams.append(key, value);
253
- return {
254
- url: targetUrl,
255
- nonceProtected
256
- };
257
- }
258
- function isAzureSdkProxyPath(pathname) {
259
- return pathname === "/openai" || pathname.startsWith("/openai/");
260
- }
261
231
  function hasValidProxyCredential(req, headerName, expected) {
262
232
  const received = req.headers[headerName];
263
233
  if (typeof received !== "string") return false;
@@ -270,38 +240,25 @@ async function readBody(req) {
270
240
  for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
271
241
  return chunks.length > 0 ? Buffer.concat(chunks) : void 0;
272
242
  }
273
- function normalizeProxyRequestHeaders(headers, proxyCredentialHeader) {
243
+ function buildProxyRequestHeaders(headers, params) {
274
244
  const out = {};
275
245
  for (const [key, value] of Object.entries(headers)) {
276
- if (isHopByHopHeader(key) || key.toLowerCase() === "accept-encoding" || key.toLowerCase() === proxyCredentialHeader) continue;
277
- const normalized = normalizeHeaderValue(value);
278
- if (normalized !== void 0) out[key] = normalized;
246
+ if (isHopByHopHeader(key) || key.toLowerCase() === "accept-encoding" || key.toLowerCase() === params.proxyCredentialHeader) continue;
247
+ if (value !== void 0) out[key] = Array.isArray(value) ? value.join(", ") : value;
279
248
  }
280
249
  out["accept-encoding"] = "identity";
281
- return out;
282
- }
283
- function createProxyCredentialHeaderName(headers) {
284
- for (;;) {
285
- const name = `${PROXY_CREDENTIAL_HEADER_PREFIX}${randomBytes(12).toString("hex")}`;
286
- if (!headers || !hasHeader(headers, name)) return name;
287
- }
288
- }
289
- function buildProxyRequestHeaders(headers, params) {
290
- const out = normalizeProxyRequestHeaders(headers, params.proxyCredentialHeader);
291
250
  if (params.upstreamBearerAuthorization && !hasHeader(out, "authorization")) out["authorization"] = params.upstreamBearerAuthorization;
292
251
  return out;
293
252
  }
294
253
  function normalizeProxyResponseHeaders(headers) {
295
254
  const out = {};
296
255
  headers.forEach((value, key) => {
297
- if (!isHopByHopHeader(key) && !isContentEncodingHeader(key)) out[key] = value;
256
+ if (isHopByHopHeader(key)) return;
257
+ const normalizedKey = key.toLowerCase();
258
+ if (normalizedKey !== "content-encoding" && normalizedKey !== "content-length") out[key] = value;
298
259
  });
299
260
  return out;
300
261
  }
301
- function normalizeHeaderValue(value) {
302
- if (value === void 0) return;
303
- return Array.isArray(value) ? value.join(", ") : String(value);
304
- }
305
262
  function hasHeader(headers, target) {
306
263
  return Object.keys(headers).some((key) => key.toLowerCase() === target);
307
264
  }
@@ -319,13 +276,6 @@ function isHopByHopHeader(key) {
319
276
  default: return false;
320
277
  }
321
278
  }
322
- function isContentEncodingHeader(key) {
323
- switch (key.toLowerCase()) {
324
- case "content-encoding":
325
- case "content-length": return true;
326
- default: return false;
327
- }
328
- }
329
279
  //#endregion
330
280
  //#region extensions/copilot/src/prompt-error.ts
331
281
  function createCopilotAbortError(reason) {
@@ -362,6 +312,27 @@ function buildCopilotCompactionHookContext(params) {
362
312
  ...buildAgentHookContextChannelFields(params)
363
313
  };
364
314
  }
315
+ async function compactTrackedSdkSession(params) {
316
+ params.assertCurrent();
317
+ throwIfAborted(params.abortSignal);
318
+ const session = await params.client.resumeSession(params.sdkSessionId, {
319
+ ...params.sessionConfig,
320
+ continuePendingWork: false,
321
+ ...params.gitHubToken ? { gitHubToken: params.gitHubToken } : {},
322
+ suppressResumeEvent: true
323
+ });
324
+ params.onSession?.(session);
325
+ const request = params.customInstructions?.trim() ? { customInstructions: params.customInstructions } : void 0;
326
+ try {
327
+ params.assertCurrent();
328
+ throwIfAborted(params.abortSignal);
329
+ return await session.rpc.history.compact(request);
330
+ } finally {
331
+ try {
332
+ await session.disconnect();
333
+ } catch {}
334
+ }
335
+ }
365
336
  //#endregion
366
337
  //#region extensions/copilot/src/provider-bridge.ts
367
338
  const COPILOT_BYOK_PROVIDER_ERROR = "[copilot-attempt] BYOK requires an OpenAI-compatible or Anthropic model api and a non-empty baseUrl";
@@ -488,7 +459,30 @@ function resolveProviderType(api, baseUrl, azureApiVersion) {
488
459
  type: "anthropic",
489
460
  baseUrl
490
461
  };
491
- case "azure-openai-responses": return resolveAzureProviderType(baseUrl, azureApiVersion);
462
+ case "azure-openai-responses": {
463
+ let url;
464
+ try {
465
+ url = new URL(baseUrl);
466
+ } catch {
467
+ throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
468
+ }
469
+ if (isOpenAICompatibleAzureResponsesBaseUrl(url)) return {
470
+ type: "openai",
471
+ wireApi: "responses",
472
+ baseUrl
473
+ };
474
+ if (!isTraditionalAzureOpenAIHost(url.hostname)) throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
475
+ url.pathname = "";
476
+ url.search = "";
477
+ url.hash = "";
478
+ const resolvedApiVersion = normalizeOptionalString(azureApiVersion);
479
+ return {
480
+ type: "azure",
481
+ wireApi: "responses",
482
+ baseUrl: url.toString().replace(/\/+$/, ""),
483
+ ...resolvedApiVersion ? { azure: { apiVersion: resolvedApiVersion } } : {}
484
+ };
485
+ }
492
486
  case "openai-responses": return {
493
487
  type: "openai",
494
488
  wireApi: "responses",
@@ -503,30 +497,6 @@ function resolveProviderType(api, baseUrl, azureApiVersion) {
503
497
  default: throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
504
498
  }
505
499
  }
506
- function resolveAzureProviderType(baseUrl, apiVersion) {
507
- let url;
508
- try {
509
- url = new URL(baseUrl);
510
- } catch {
511
- throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
512
- }
513
- if (isOpenAICompatibleAzureResponsesBaseUrl(url)) return {
514
- type: "openai",
515
- wireApi: "responses",
516
- baseUrl
517
- };
518
- if (!isTraditionalAzureOpenAIHost(url.hostname)) throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
519
- url.pathname = "";
520
- url.search = "";
521
- url.hash = "";
522
- const resolvedApiVersion = normalizeOptionalString(apiVersion);
523
- return {
524
- type: "azure",
525
- wireApi: "responses",
526
- baseUrl: url.toString().replace(/\/+$/, ""),
527
- ...resolvedApiVersion ? { azure: { apiVersion: resolvedApiVersion } } : {}
528
- };
529
- }
530
500
  function isTraditionalAzureOpenAIHost(hostname) {
531
501
  return hostname.endsWith(".openai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
532
502
  }
@@ -549,18 +519,6 @@ function resolveProviderCredential(value) {
549
519
  //#endregion
550
520
  //#region extensions/copilot/harness.ts
551
521
  const COPILOT_PROVIDER_IDS = /* @__PURE__ */ new Set(["github-copilot"]);
552
- function sessionAuthFields(auth) {
553
- return auth.authMode === "gitHubToken" || auth.authMode === "byok" ? {
554
- authMode: auth.authMode,
555
- authProfileId: auth.authProfileId,
556
- authProfileVersion: auth.authProfileVersion
557
- } : { authMode: "useLoggedInUser" };
558
- }
559
- function sessionAuthMatches(stored, current) {
560
- if (stored.authMode !== current.authMode) return false;
561
- if (stored.authMode === "useLoggedInUser") return true;
562
- return stored.authProfileId === current.authProfileId && stored.authProfileVersion === current.authProfileVersion;
563
- }
564
522
  function normalizeBinding(value) {
565
523
  if (!value || value.schemaVersion !== 2 || typeof value.sdkSessionId !== "string" || value.sdkSessionId.trim() === "" || typeof value.compatKey !== "string" || value.compatKey.trim() === "" || typeof value.compactKey !== "string" || value.compactKey.trim() === "" || value.journalVersion !== void 0 && value.journalVersion !== 1 || value.authMode !== "gitHubToken" && value.authMode !== "byok" && value.authMode !== "useLoggedInUser" || (value.authMode === "gitHubToken" || value.authMode === "byok") && (typeof value.authProfileId !== "string" || value.authProfileId.trim() === "" || typeof value.authProfileVersion !== "string" || value.authProfileVersion.trim() === "") || typeof value.updatedAt !== "number" || !Number.isFinite(value.updatedAt)) return;
566
524
  return {
@@ -615,27 +573,6 @@ async function deleteStoredBinding(store, key) {
615
573
  return false;
616
574
  }
617
575
  }
618
- async function compactTrackedSdkSession(params) {
619
- params.assertCurrent();
620
- throwIfAborted(params.abortSignal);
621
- const session = await params.client.resumeSession(params.sdkSessionId, {
622
- ...params.sessionConfig,
623
- continuePendingWork: false,
624
- ...params.gitHubToken ? { gitHubToken: params.gitHubToken } : {},
625
- suppressResumeEvent: true
626
- });
627
- params.onSession?.(session);
628
- const request = params.customInstructions?.trim() ? { customInstructions: params.customInstructions } : void 0;
629
- try {
630
- params.assertCurrent();
631
- throwIfAborted(params.abortSignal);
632
- return await session.rpc.history.compact(request);
633
- } finally {
634
- try {
635
- await session.disconnect();
636
- } catch {}
637
- }
638
- }
639
576
  function readAgentIdFromSessionKey(sessionKey) {
640
577
  if (typeof sessionKey !== "string") return;
641
578
  const parts = sessionKey.trim().split(":");
@@ -784,21 +721,12 @@ function createCopilotAgentHarness(options) {
784
721
  async function getPool() {
785
722
  if (options?.pool) return options.pool;
786
723
  if (!poolPromise) poolPromise = (async () => {
787
- const { createCopilotClientPool } = await import("./runtime-C0R_TFVt.mjs");
724
+ const { createCopilotClientPool } = await import("./runtime-CtTtYION.mjs");
788
725
  createdPool = createCopilotClientPool(options?.poolOptions);
789
726
  return createdPool;
790
727
  })();
791
728
  return poolPromise;
792
729
  }
793
- function trackDeferredCompactionCleanup(params) {
794
- const cleanups = deferredCompactionCleanups.get(params.sessionId) ?? /* @__PURE__ */ new Map();
795
- cleanups.set(params.cleanup, {
796
- abort: params.abort,
797
- sdkSessionId: params.sdkSessionId
798
- });
799
- deferredCompactionCleanups.set(params.sessionId, cleanups);
800
- params.cleanup.then(() => removeDeferredCompactionCleanup(params.sessionId, params.cleanup), () => removeDeferredCompactionCleanup(params.sessionId, params.cleanup));
801
- }
802
730
  function removeDeferredCompactionCleanup(sessionId, cleanup) {
803
731
  const cleanups = deferredCompactionCleanups.get(sessionId);
804
732
  if (!cleanups) return;
@@ -821,10 +749,8 @@ function createCopilotAgentHarness(options) {
821
749
  async function runHarnessAttempt(params, operation) {
822
750
  return trackOperation(async () => {
823
751
  if (disposed) throw new Error("[copilot] harness has been disposed; cannot start new attempts");
824
- const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-Bu_STDE0.mjs");
825
- if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
752
+ const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-BE9PBSA2.mjs");
826
753
  const pool = await getPool();
827
- if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
828
754
  let poolAcquire;
829
755
  try {
830
756
  poolAcquire = resolvePoolAcquire(params);
@@ -832,7 +758,7 @@ function createCopilotAgentHarness(options) {
832
758
  if (operation === "attempt" && isCopilotByokUnsupportedProviderError(error)) return runCopilotAttempt(params, { pool });
833
759
  throw error;
834
760
  }
835
- const openclawSessionId = params.sessionPersistence === "detached" || typeof params.sessionId !== "string" ? void 0 : params.sessionId;
761
+ const openclawSessionId = params.sessionPersistence === "detached" ? void 0 : params.sessionId;
836
762
  const currentCompatKey = computeSessionCompatKey(params);
837
763
  const currentCompactKey = computeAttemptCompactKey(params);
838
764
  const resumableBinding = openclawSessionId ? await bindingQueue.enqueue(openclawSessionId, async () => {
@@ -842,25 +768,10 @@ function createCopilotAgentHarness(options) {
842
768
  const binding = tracked ?? stored;
843
769
  return binding?.compatKey === currentCompatKey ? binding : void 0;
844
770
  }) : void 0;
845
- if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
846
771
  const resumableSessionId = resumableBinding?.sdkSessionId;
847
772
  if (operation === "settled-tool-finalization" && !resumableSessionId) throw new Error("[copilot] cannot safely finalize a settled tool turn without its compatible SDK session");
848
773
  const result = await runCopilotAttempt(resumableSessionId ? {
849
774
  ...params,
850
- ...operation === "settled-tool-finalization" ? {
851
- disableTools: true,
852
- onAgentEvent: void 0,
853
- onAgentToolResult: void 0,
854
- onAssistantDelta: void 0,
855
- onAssistantMessageStart: void 0,
856
- onBlockReply: void 0,
857
- onBlockReplyFlush: void 0,
858
- onPartialReply: void 0,
859
- onReasoningEnd: void 0,
860
- onReasoningStream: void 0,
861
- onToolResult: void 0,
862
- onToolStreamBoundary: void 0
863
- } : {},
864
775
  initialReplayState: {
865
776
  ...operation === "attempt" ? params.initialReplayState : void 0,
866
777
  ...resumableBinding?.journalVersion === 1 ? { journalValidated: true } : {},
@@ -891,25 +802,27 @@ function createCopilotAgentHarness(options) {
891
802
  const ownsStoredSession = storedBinding?.sdkSessionId === sdkSessionId;
892
803
  if (!ownsTrackedSession && !ownsStoredSession) return;
893
804
  resetBlockedStoredSessions.add(openclawSessionId);
894
- trackDeferredCompactionCleanup({
895
- abort,
896
- cleanup: cleanup.then((outcome) => bindingQueue.enqueue(openclawSessionId, async () => {
897
- const currentTracked = trackedSessions.get(openclawSessionId);
898
- const currentStored = await lookupStoredBinding(options?.sessionStore, openclawSessionId);
899
- const stillOwnsTrackedSession = currentTracked?.sdkSessionId === sdkSessionId;
900
- const stillOwnsStoredSession = currentStored?.sdkSessionId === sdkSessionId;
901
- if (outcome === "completed") {
902
- if (stillOwnsTrackedSession || stillOwnsStoredSession) resetBlockedStoredSessions.delete(openclawSessionId);
903
- return outcome;
904
- }
905
- if (stillOwnsTrackedSession) trackedSessions.delete(openclawSessionId);
906
- if (stillOwnsStoredSession) await deleteStoredBinding(options?.sessionStore, openclawSessionId);
907
- if (stillOwnsTrackedSession || stillOwnsStoredSession) resetBlockedStoredSessions.add(openclawSessionId);
805
+ const bindingCleanup = cleanup.then((outcome) => bindingQueue.enqueue(openclawSessionId, async () => {
806
+ const currentTracked = trackedSessions.get(openclawSessionId);
807
+ const currentStored = await lookupStoredBinding(options?.sessionStore, openclawSessionId);
808
+ const stillOwnsTrackedSession = currentTracked?.sdkSessionId === sdkSessionId;
809
+ const stillOwnsStoredSession = currentStored?.sdkSessionId === sdkSessionId;
810
+ if (outcome === "completed") {
811
+ if (stillOwnsTrackedSession || stillOwnsStoredSession) resetBlockedStoredSessions.delete(openclawSessionId);
908
812
  return outcome;
909
- })),
910
- sessionId: openclawSessionId,
813
+ }
814
+ if (stillOwnsTrackedSession) trackedSessions.delete(openclawSessionId);
815
+ if (stillOwnsStoredSession) await deleteStoredBinding(options?.sessionStore, openclawSessionId);
816
+ if (stillOwnsTrackedSession || stillOwnsStoredSession) resetBlockedStoredSessions.add(openclawSessionId);
817
+ return outcome;
818
+ }));
819
+ const cleanups = deferredCompactionCleanups.get(openclawSessionId) ?? /* @__PURE__ */ new Map();
820
+ cleanups.set(bindingCleanup, {
821
+ abort,
911
822
  sdkSessionId
912
823
  });
824
+ deferredCompactionCleanups.set(openclawSessionId, cleanups);
825
+ bindingCleanup.then(() => removeDeferredCompactionCleanup(openclawSessionId, bindingCleanup), () => removeDeferredCompactionCleanup(openclawSessionId, bindingCleanup));
913
826
  }) : void 0
914
827
  });
915
828
  if (operation === "attempt" && openclawSessionId) {
@@ -934,12 +847,9 @@ function createCopilotAgentHarness(options) {
934
847
  async function runIsolatedCompletionV2(params) {
935
848
  return trackOperation(async () => {
936
849
  if (disposed) throw new Error("[copilot] harness has been disposed; cannot start isolated completion");
937
- const { runCopilotIsolatedCompletion } = await import("./isolated-completion-CrN9i842.mjs");
938
- if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
850
+ const { runCopilotIsolatedCompletion } = await import("./isolated-completion-BeHQ8_kK.mjs");
939
851
  return await runCopilotIsolatedCompletion(params, async () => {
940
- const pool = await getPool();
941
- if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
942
- return pool;
852
+ return await getPool();
943
853
  });
944
854
  });
945
855
  }
@@ -948,6 +858,10 @@ function createCopilotAgentHarness(options) {
948
858
  label: options?.label ?? "GitHub Copilot agent runtime",
949
859
  autoSelection: { providerIds: [] },
950
860
  conversationToolPolicySupport: "exact",
861
+ runtimeArtifact: { async validate(binding) {
862
+ const { validateCopilotRuntimeArtifact } = await import("./runtime-artifact-CS6Ndnjs.mjs");
863
+ return await validateCopilotRuntimeArtifact(binding);
864
+ } },
951
865
  supports(ctx) {
952
866
  if (String(ctx.requestedRuntime ?? "").trim().toLowerCase() !== "copilot") return {
953
867
  supported: false,
@@ -990,7 +904,7 @@ function createCopilotAgentHarness(options) {
990
904
  },
991
905
  reset: (params) => trackOperation(async () => {
992
906
  if (disposed) return;
993
- const openclawSessionId = typeof params.sessionId === "string" ? params.sessionId : void 0;
907
+ const openclawSessionId = params.sessionId;
994
908
  if (!openclawSessionId) return;
995
909
  const { tracked, stored } = await bindingQueue.enqueue(openclawSessionId, async () => {
996
910
  const binding = await lookupStoredBinding(options?.sessionStore, openclawSessionId);
@@ -1018,7 +932,7 @@ function createCopilotAgentHarness(options) {
1018
932
  const hostCapabilities = params.hostCapabilities;
1019
933
  if (hostCapabilities?.kind !== "agent-harness-host-capability" || hostCapabilities.version !== 1 || typeof hostCapabilities.assertActive !== "function" || typeof hostCapabilities.retainSourceAuthority !== "function") throw new Error("This host did not provide compaction source authority. Update OpenClaw before compacting this session.");
1020
934
  hostCapabilities.assertActive();
1021
- const openclawSessionId = typeof params.sessionId === "string" ? params.sessionId : void 0;
935
+ const openclawSessionId = params.sessionId;
1022
936
  if (!openclawSessionId) return {
1023
937
  ok: false,
1024
938
  compacted: false,
@@ -1027,7 +941,7 @@ function createCopilotAgentHarness(options) {
1027
941
  if (await bindingQueue.enqueue(openclawSessionId, () => hasPendingDeferredCompactionCleanup(openclawSessionId))) return failedCompaction("background-compaction-pending");
1028
942
  const tracked = trackedSessions.get(openclawSessionId);
1029
943
  const currentCompactKey = computeCompactRequestKey(params);
1030
- const { resolvePoolAcquire } = await import("./attempt-Bu_STDE0.mjs");
944
+ const { resolvePoolAcquire } = await import("./attempt-BE9PBSA2.mjs");
1031
945
  let resolvedPoolAcquire;
1032
946
  try {
1033
947
  resolvedPoolAcquire = resolvePoolAcquire(params);