@openclaw/copilot 2026.10.10-beta.5 → 2026.11.5-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.
@@ -4,22 +4,33 @@ 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";
10
11
  import { fetchWithSsrFGuard, isBlockedHostnameOrIp } from "openclaw/plugin-sdk/ssrf-runtime";
11
12
  import { isNonSecretApiKeyMarker } from "openclaw/plugin-sdk/provider-auth";
12
- //#region extensions/copilot/src/auth-bridge.ts
13
+ // 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,17 +99,24 @@ 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. */
128
116
  function tokenFingerprint(token) {
129
117
  return `sha256:${createHash("sha256").update(token).digest("hex").slice(0, 12)}`;
130
118
  }
131
- //#endregion
132
- //#region extensions/copilot/src/byok-proxy.ts
119
+ // extensions/copilot/src/byok-proxy.ts
133
120
  const LOOPBACK_HOST = "127.0.0.1";
134
121
  const PROXY_CREDENTIAL_HEADER_PREFIX = "x-openclaw-copilot-byok-";
135
122
  async function createCopilotByokProxy(resolvedProvider) {
@@ -141,29 +128,77 @@ async function createCopilotByokProxy(resolvedProvider) {
141
128
  const targetPathPrefix = targetBaseUrl.pathname.replace(/\/+$/, "");
142
129
  const proxyPathPrefix = `/${nonce}${targetPathPrefix}`;
143
130
  const acceptsAzureSdkPaths = providerConfig.type === "azure";
144
- const proxyCredentialHeader = acceptsAzureSdkPaths ? createProxyCredentialHeaderName(providerConfig.headers) : void 0;
131
+ const proxyCredentialHeader = acceptsAzureSdkPaths ? `${PROXY_CREDENTIAL_HEADER_PREFIX}${randomBytes(12).toString("hex")}` : void 0;
145
132
  const bearerToken = providerConfig.bearerToken?.trim();
146
133
  const upstreamBearerAuthorization = bearerToken ? `Bearer ${bearerToken}` : void 0;
147
134
  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();
135
+ async function handleProxyRequest(req, res) {
136
+ let guarded;
137
+ const upstreamAbort = new AbortController();
138
+ activeFetches.add(upstreamAbort);
139
+ const abortUpstream = () => upstreamAbort.abort();
140
+ req.on("aborted", abortUpstream);
141
+ res.on("close", () => {
142
+ if (!res.writableEnded) abortUpstream();
165
143
  });
144
+ try {
145
+ const target = resolveTargetUrl(req);
146
+ if (!target || !target.nonceProtected && (!proxyCredentialHeader || !hasValidProxyCredential(req, proxyCredentialHeader, nonce))) {
147
+ res.writeHead(404);
148
+ res.end("Not found");
149
+ return;
150
+ }
151
+ const body = req.method === "GET" || req.method === "HEAD" ? void 0 : await readBody(req);
152
+ guarded = await fetchWithSsrFGuard({
153
+ url: target.url.toString(),
154
+ init: {
155
+ method: req.method,
156
+ headers: buildProxyRequestHeaders(req.headers, {
157
+ upstreamBearerAuthorization: target.nonceProtected ? upstreamBearerAuthorization : void 0,
158
+ proxyCredentialHeader
159
+ }),
160
+ signal: upstreamAbort.signal,
161
+ ...body ? { body } : {}
162
+ },
163
+ auditContext: "copilot-byok-provider",
164
+ requireHttps: true
165
+ });
166
+ res.writeHead(guarded.response.status, guarded.response.statusText, normalizeProxyResponseHeaders(guarded.response.headers));
167
+ if (!guarded.response.body) {
168
+ res.end();
169
+ return;
170
+ }
171
+ await pipeline(Readable.fromWeb(guarded.response.body), res);
172
+ } catch (error) {
173
+ if (res.destroyed || res.writableEnded) return;
174
+ if (res.headersSent) {
175
+ res.destroy(error instanceof Error ? error : void 0);
176
+ return;
177
+ }
178
+ res.writeHead(502);
179
+ res.end(error instanceof Error ? error.message : "BYOK provider proxy failed");
180
+ } finally {
181
+ req.off("aborted", abortUpstream);
182
+ activeFetches.delete(upstreamAbort);
183
+ await guarded?.release().catch(() => void 0);
184
+ }
185
+ }
186
+ function resolveTargetUrl(req) {
187
+ const incomingUrl = new URL(req.url ?? "/", `http://${LOOPBACK_HOST}`);
188
+ const nonceProtected = incomingUrl.pathname === proxyPathPrefix || incomingUrl.pathname.startsWith(`${proxyPathPrefix}/`);
189
+ if (!nonceProtected && !(acceptsAzureSdkPaths && (incomingUrl.pathname === "/openai" || incomingUrl.pathname.startsWith("/openai/")))) return;
190
+ const targetUrl = new URL(targetBaseUrl);
191
+ targetUrl.pathname = nonceProtected ? `${targetPathPrefix}${incomingUrl.pathname.slice(proxyPathPrefix.length)}` || "/" : incomingUrl.pathname;
192
+ for (const [key, value] of incomingUrl.searchParams) targetUrl.searchParams.append(key, value);
193
+ return {
194
+ url: targetUrl,
195
+ nonceProtected
196
+ };
197
+ }
198
+ const server = createServer((req, res) => {
199
+ handleProxyRequest(req, res);
166
200
  });
201
+ await once(server.listen(0, LOOPBACK_HOST), "listening");
167
202
  const address = server.address();
168
203
  if (!address || typeof address === "string") {
169
204
  server.close();
@@ -192,72 +227,6 @@ async function createCopilotByokProxy(resolvedProvider) {
192
227
  }
193
228
  };
194
229
  }
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
230
  function hasValidProxyCredential(req, headerName, expected) {
262
231
  const received = req.headers[headerName];
263
232
  if (typeof received !== "string") return false;
@@ -270,38 +239,25 @@ async function readBody(req) {
270
239
  for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
271
240
  return chunks.length > 0 ? Buffer.concat(chunks) : void 0;
272
241
  }
273
- function normalizeProxyRequestHeaders(headers, proxyCredentialHeader) {
242
+ function buildProxyRequestHeaders(headers, params) {
274
243
  const out = {};
275
244
  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;
245
+ if (isHopByHopHeader(key) || key.toLowerCase() === "accept-encoding" || key.toLowerCase() === params.proxyCredentialHeader) continue;
246
+ if (value !== void 0) out[key] = Array.isArray(value) ? value.join(", ") : value;
279
247
  }
280
248
  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
249
  if (params.upstreamBearerAuthorization && !hasHeader(out, "authorization")) out["authorization"] = params.upstreamBearerAuthorization;
292
250
  return out;
293
251
  }
294
252
  function normalizeProxyResponseHeaders(headers) {
295
253
  const out = {};
296
254
  headers.forEach((value, key) => {
297
- if (!isHopByHopHeader(key) && !isContentEncodingHeader(key)) out[key] = value;
255
+ if (isHopByHopHeader(key)) return;
256
+ const normalizedKey = key.toLowerCase();
257
+ if (normalizedKey !== "content-encoding" && normalizedKey !== "content-length") out[key] = value;
298
258
  });
299
259
  return out;
300
260
  }
301
- function normalizeHeaderValue(value) {
302
- if (value === void 0) return;
303
- return Array.isArray(value) ? value.join(", ") : String(value);
304
- }
305
261
  function hasHeader(headers, target) {
306
262
  return Object.keys(headers).some((key) => key.toLowerCase() === target);
307
263
  }
@@ -319,15 +275,7 @@ function isHopByHopHeader(key) {
319
275
  default: return false;
320
276
  }
321
277
  }
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
- //#endregion
330
- //#region extensions/copilot/src/prompt-error.ts
278
+ // extensions/copilot/src/prompt-error.ts
331
279
  function createCopilotAbortError(reason) {
332
280
  if (reason instanceof Error) return reason;
333
281
  const error = new Error("aborted", reason ? { cause: reason } : void 0);
@@ -340,8 +288,7 @@ function createPromptError(code, message, cause) {
340
288
  if (cause !== void 0) error.cause = cause;
341
289
  return error;
342
290
  }
343
- //#endregion
344
- //#region extensions/copilot/src/history-compaction.ts
291
+ // extensions/copilot/src/history-compaction.ts
345
292
  function throwIfAborted(signal) {
346
293
  if (signal?.aborted) throw createCopilotAbortError(signal.reason);
347
294
  }
@@ -362,8 +309,28 @@ function buildCopilotCompactionHookContext(params) {
362
309
  ...buildAgentHookContextChannelFields(params)
363
310
  };
364
311
  }
365
- //#endregion
366
- //#region extensions/copilot/src/provider-bridge.ts
312
+ async function compactTrackedSdkSession(params) {
313
+ params.assertCurrent();
314
+ throwIfAborted(params.abortSignal);
315
+ const session = await params.client.resumeSession(params.sdkSessionId, {
316
+ ...params.sessionConfig,
317
+ continuePendingWork: false,
318
+ ...params.gitHubToken ? { gitHubToken: params.gitHubToken } : {},
319
+ suppressResumeEvent: true
320
+ });
321
+ params.onSession?.(session);
322
+ const request = params.customInstructions?.trim() ? { customInstructions: params.customInstructions } : void 0;
323
+ try {
324
+ params.assertCurrent();
325
+ throwIfAborted(params.abortSignal);
326
+ return await session.rpc.history.compact(request);
327
+ } finally {
328
+ try {
329
+ await session.disconnect();
330
+ } catch {}
331
+ }
332
+ }
333
+ // extensions/copilot/src/provider-bridge.ts
367
334
  const COPILOT_BYOK_PROVIDER_ERROR = "[copilot-attempt] BYOK requires an OpenAI-compatible or Anthropic model api and a non-empty baseUrl";
368
335
  const COPILOT_BYOK_TRANSPORT_POLICY_ERROR = "[copilot-attempt] BYOK does not support OpenClaw provider request proxy, TLS, or private-network policy overrides";
369
336
  const COPILOT_BYOK_ENDPOINT_POLICY_ERROR = "[copilot-attempt] BYOK endpoint is blocked by OpenClaw SSRF policy";
@@ -488,7 +455,30 @@ function resolveProviderType(api, baseUrl, azureApiVersion) {
488
455
  type: "anthropic",
489
456
  baseUrl
490
457
  };
491
- case "azure-openai-responses": return resolveAzureProviderType(baseUrl, azureApiVersion);
458
+ case "azure-openai-responses": {
459
+ let url;
460
+ try {
461
+ url = new URL(baseUrl);
462
+ } catch {
463
+ throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
464
+ }
465
+ if (isOpenAICompatibleAzureResponsesBaseUrl(url)) return {
466
+ type: "openai",
467
+ wireApi: "responses",
468
+ baseUrl
469
+ };
470
+ if (!isTraditionalAzureOpenAIHost(url.hostname)) throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
471
+ url.pathname = "";
472
+ url.search = "";
473
+ url.hash = "";
474
+ const resolvedApiVersion = normalizeOptionalString(azureApiVersion);
475
+ return {
476
+ type: "azure",
477
+ wireApi: "responses",
478
+ baseUrl: url.toString().replace(/\/+$/, ""),
479
+ ...resolvedApiVersion ? { azure: { apiVersion: resolvedApiVersion } } : {}
480
+ };
481
+ }
492
482
  case "openai-responses": return {
493
483
  type: "openai",
494
484
  wireApi: "responses",
@@ -503,30 +493,6 @@ function resolveProviderType(api, baseUrl, azureApiVersion) {
503
493
  default: throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
504
494
  }
505
495
  }
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
496
  function isTraditionalAzureOpenAIHost(hostname) {
531
497
  return hostname.endsWith(".openai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
532
498
  }
@@ -546,21 +512,8 @@ function resolveProviderCredential(value) {
546
512
  const credential = normalizeOptionalString(value);
547
513
  return credential && !isNonSecretApiKeyMarker(credential) ? credential : void 0;
548
514
  }
549
- //#endregion
550
- //#region extensions/copilot/harness.ts
515
+ // extensions/copilot/harness.ts
551
516
  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
517
  function normalizeBinding(value) {
565
518
  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
519
  return {
@@ -615,27 +568,6 @@ async function deleteStoredBinding(store, key) {
615
568
  return false;
616
569
  }
617
570
  }
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
571
  function readAgentIdFromSessionKey(sessionKey) {
640
572
  if (typeof sessionKey !== "string") return;
641
573
  const parts = sessionKey.trim().split(":");
@@ -784,21 +716,12 @@ function createCopilotAgentHarness(options) {
784
716
  async function getPool() {
785
717
  if (options?.pool) return options.pool;
786
718
  if (!poolPromise) poolPromise = (async () => {
787
- const { createCopilotClientPool } = await import("./runtime-C0R_TFVt.mjs");
719
+ const { createCopilotClientPool } = await import("./runtime-CAM77uEc.mjs");
788
720
  createdPool = createCopilotClientPool(options?.poolOptions);
789
721
  return createdPool;
790
722
  })();
791
723
  return poolPromise;
792
724
  }
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
725
  function removeDeferredCompactionCleanup(sessionId, cleanup) {
803
726
  const cleanups = deferredCompactionCleanups.get(sessionId);
804
727
  if (!cleanups) return;
@@ -821,10 +744,8 @@ function createCopilotAgentHarness(options) {
821
744
  async function runHarnessAttempt(params, operation) {
822
745
  return trackOperation(async () => {
823
746
  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");
747
+ const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-BdJgfQV3.mjs");
826
748
  const pool = await getPool();
827
- if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
828
749
  let poolAcquire;
829
750
  try {
830
751
  poolAcquire = resolvePoolAcquire(params);
@@ -832,7 +753,7 @@ function createCopilotAgentHarness(options) {
832
753
  if (operation === "attempt" && isCopilotByokUnsupportedProviderError(error)) return runCopilotAttempt(params, { pool });
833
754
  throw error;
834
755
  }
835
- const openclawSessionId = params.sessionPersistence === "detached" || typeof params.sessionId !== "string" ? void 0 : params.sessionId;
756
+ const openclawSessionId = params.sessionPersistence === "detached" ? void 0 : params.sessionId;
836
757
  const currentCompatKey = computeSessionCompatKey(params);
837
758
  const currentCompactKey = computeAttemptCompactKey(params);
838
759
  const resumableBinding = openclawSessionId ? await bindingQueue.enqueue(openclawSessionId, async () => {
@@ -842,25 +763,10 @@ function createCopilotAgentHarness(options) {
842
763
  const binding = tracked ?? stored;
843
764
  return binding?.compatKey === currentCompatKey ? binding : void 0;
844
765
  }) : void 0;
845
- if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
846
766
  const resumableSessionId = resumableBinding?.sdkSessionId;
847
767
  if (operation === "settled-tool-finalization" && !resumableSessionId) throw new Error("[copilot] cannot safely finalize a settled tool turn without its compatible SDK session");
848
768
  const result = await runCopilotAttempt(resumableSessionId ? {
849
769
  ...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
770
  initialReplayState: {
865
771
  ...operation === "attempt" ? params.initialReplayState : void 0,
866
772
  ...resumableBinding?.journalVersion === 1 ? { journalValidated: true } : {},
@@ -891,25 +797,27 @@ function createCopilotAgentHarness(options) {
891
797
  const ownsStoredSession = storedBinding?.sdkSessionId === sdkSessionId;
892
798
  if (!ownsTrackedSession && !ownsStoredSession) return;
893
799
  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);
800
+ const bindingCleanup = cleanup.then((outcome) => bindingQueue.enqueue(openclawSessionId, async () => {
801
+ const currentTracked = trackedSessions.get(openclawSessionId);
802
+ const currentStored = await lookupStoredBinding(options?.sessionStore, openclawSessionId);
803
+ const stillOwnsTrackedSession = currentTracked?.sdkSessionId === sdkSessionId;
804
+ const stillOwnsStoredSession = currentStored?.sdkSessionId === sdkSessionId;
805
+ if (outcome === "completed") {
806
+ if (stillOwnsTrackedSession || stillOwnsStoredSession) resetBlockedStoredSessions.delete(openclawSessionId);
908
807
  return outcome;
909
- })),
910
- sessionId: openclawSessionId,
808
+ }
809
+ if (stillOwnsTrackedSession) trackedSessions.delete(openclawSessionId);
810
+ if (stillOwnsStoredSession) await deleteStoredBinding(options?.sessionStore, openclawSessionId);
811
+ if (stillOwnsTrackedSession || stillOwnsStoredSession) resetBlockedStoredSessions.add(openclawSessionId);
812
+ return outcome;
813
+ }));
814
+ const cleanups = deferredCompactionCleanups.get(openclawSessionId) ?? /* @__PURE__ */ new Map();
815
+ cleanups.set(bindingCleanup, {
816
+ abort,
911
817
  sdkSessionId
912
818
  });
819
+ deferredCompactionCleanups.set(openclawSessionId, cleanups);
820
+ bindingCleanup.then(() => removeDeferredCompactionCleanup(openclawSessionId, bindingCleanup), () => removeDeferredCompactionCleanup(openclawSessionId, bindingCleanup));
913
821
  }) : void 0
914
822
  });
915
823
  if (operation === "attempt" && openclawSessionId) {
@@ -934,12 +842,9 @@ function createCopilotAgentHarness(options) {
934
842
  async function runIsolatedCompletionV2(params) {
935
843
  return trackOperation(async () => {
936
844
  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");
845
+ const { runCopilotIsolatedCompletion } = await import("./isolated-completion-Dp_YaEKF.mjs");
939
846
  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;
847
+ return await getPool();
943
848
  });
944
849
  });
945
850
  }
@@ -948,6 +853,10 @@ function createCopilotAgentHarness(options) {
948
853
  label: options?.label ?? "GitHub Copilot agent runtime",
949
854
  autoSelection: { providerIds: [] },
950
855
  conversationToolPolicySupport: "exact",
856
+ runtimeArtifact: { async validate(binding) {
857
+ const { validateCopilotRuntimeArtifact } = await import("./runtime-artifact-D42RfCpG.mjs");
858
+ return await validateCopilotRuntimeArtifact(binding);
859
+ } },
951
860
  supports(ctx) {
952
861
  if (String(ctx.requestedRuntime ?? "").trim().toLowerCase() !== "copilot") return {
953
862
  supported: false,
@@ -990,7 +899,7 @@ function createCopilotAgentHarness(options) {
990
899
  },
991
900
  reset: (params) => trackOperation(async () => {
992
901
  if (disposed) return;
993
- const openclawSessionId = typeof params.sessionId === "string" ? params.sessionId : void 0;
902
+ const openclawSessionId = params.sessionId;
994
903
  if (!openclawSessionId) return;
995
904
  const { tracked, stored } = await bindingQueue.enqueue(openclawSessionId, async () => {
996
905
  const binding = await lookupStoredBinding(options?.sessionStore, openclawSessionId);
@@ -1018,7 +927,7 @@ function createCopilotAgentHarness(options) {
1018
927
  const hostCapabilities = params.hostCapabilities;
1019
928
  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
929
  hostCapabilities.assertActive();
1021
- const openclawSessionId = typeof params.sessionId === "string" ? params.sessionId : void 0;
930
+ const openclawSessionId = params.sessionId;
1022
931
  if (!openclawSessionId) return {
1023
932
  ok: false,
1024
933
  compacted: false,
@@ -1027,7 +936,7 @@ function createCopilotAgentHarness(options) {
1027
936
  if (await bindingQueue.enqueue(openclawSessionId, () => hasPendingDeferredCompactionCleanup(openclawSessionId))) return failedCompaction("background-compaction-pending");
1028
937
  const tracked = trackedSessions.get(openclawSessionId);
1029
938
  const currentCompactKey = computeCompactRequestKey(params);
1030
- const { resolvePoolAcquire } = await import("./attempt-Bu_STDE0.mjs");
939
+ const { resolvePoolAcquire } = await import("./attempt-BdJgfQV3.mjs");
1031
940
  let resolvedPoolAcquire;
1032
941
  try {
1033
942
  resolvedPoolAcquire = resolvePoolAcquire(params);
@@ -1140,5 +1049,4 @@ function createCopilotAgentHarness(options) {
1140
1049
  }
1141
1050
  };
1142
1051
  }
1143
- //#endregion
1144
1052
  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 };