@openclaw/copilot 2026.9.6 → 2026.9.8
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.
- package/assets/icon.png +0 -0
- package/dist/.setup/{attempt-DKgdMTpc.mjs → attempt-CRiSJYXq.mjs} +50 -371
- package/dist/.setup/{harness-BH2_ctMF.mjs → harness-BAWs53-w.mjs} +58 -146
- package/dist/.setup/{isolated-completion-CpLMQyd3.mjs → isolated-completion-ClBsnNg8.mjs} +1 -1
- package/dist/.setup/{runtime-D6DFeSZX.mjs → runtime-CWI9o_Vc.mjs} +28 -47
- package/dist/harness.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +5 -5
package/assets/icon.png
CHANGED
|
Binary file
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-
|
|
1
|
+
import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-BAWs53-w.mjs";
|
|
2
2
|
import { n as normalizeCopilotUsage, r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.mjs";
|
|
3
3
|
import { asNonArrayRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
4
4
|
import { SKILL_WORKSHOP_TOOL_NAME, applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHookContextChannelFields, buildCredentialSafetyPrompt, buildDelegationGuidanceSection, buildEmbeddedAttemptToolRunContext, buildEmbeddedForegroundPromptContext, buildHarnessVisibleReplyGuidance, buildSkillWorkshopPromptSection, cancelPendingAgentQuestionForSession, claimPendingAgentQuestionAnswer, clearActiveEmbeddedRun, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, emitAgentEvent, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, getPluginToolSideEffectOwnerKey, isHostScopedAgentToolActive, isSubagentSessionKey, isToolResultError, projectAgentHarnessTranscriptMessageForDisplay, projectAgentToolActivity, resolveAgentDir, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveMainSessionDelegationMode, resolveModelAuthMode, resolveSandboxContext, resolveUserPath, restorePreparedUserTurnOperationalMetaForRuntime, runAgentEndSideEffects, runAgentHarnessAfterCompactionHook, runAgentHarnessAfterToolCallHook, runAgentHarnessBeforeCompactionHook, runAgentHarnessBeforeMessageWriteHook, runAgentHarnessGatewayQuestion, runAgentHarnessLlmInputHook, runAgentHarnessLlmOutputHook, sanitizeToolResult, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
@@ -12,7 +12,6 @@ import { convertMcpCallToolResult } from "@github/copilot-sdk";
|
|
|
12
12
|
import { isDeepStrictEqual } from "node:util";
|
|
13
13
|
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
|
|
14
14
|
import { appendSessionTranscriptMessageByIdentityStrict, appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity, readVisibleSessionTranscriptMessageEntries } from "openclaw/plugin-sdk/session-transcript-runtime";
|
|
15
|
-
import { createAgentHarnessTaskRuntime } from "openclaw/plugin-sdk/agent-harness-task-runtime";
|
|
16
15
|
//#region extensions/copilot/src/attempt-types.ts
|
|
17
16
|
const BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS = 5e3;
|
|
18
17
|
const COPILOT_ASK_USER_AVAILABLE_TOOLS = ["builtin:ask_user"];
|
|
@@ -102,18 +101,11 @@ function createHooksBridge(config, options) {
|
|
|
102
101
|
}
|
|
103
102
|
//#endregion
|
|
104
103
|
//#region extensions/copilot/src/permission-bridge.ts
|
|
105
|
-
/** Built-in fail-closed default. Mirrors the pre-bridge attempt.ts stub. */
|
|
106
104
|
const REJECT_ALL_FEEDBACK = "copilot agent runtime: no permission policy installed (fail-closed default)";
|
|
107
105
|
const rejectAllPolicy = () => ({
|
|
108
106
|
kind: "reject",
|
|
109
107
|
feedback: REJECT_ALL_FEEDBACK
|
|
110
108
|
});
|
|
111
|
-
/**
|
|
112
|
-
* Adapt a `CopilotPermissionPolicy` to the SDK's
|
|
113
|
-
* `PermissionHandler` shape. The returned handler always resolves
|
|
114
|
-
* (never rejects), defaulting to fail-closed when the policy returns
|
|
115
|
-
* undefined or throws.
|
|
116
|
-
*/
|
|
117
109
|
function createPermissionBridge(policy = rejectAllPolicy) {
|
|
118
110
|
return async (request, invocation) => {
|
|
119
111
|
const ctx = {
|
|
@@ -137,27 +129,13 @@ function createPermissionBridge(policy = rejectAllPolicy) {
|
|
|
137
129
|
}
|
|
138
130
|
//#endregion
|
|
139
131
|
//#region extensions/copilot/src/replay-shim.ts
|
|
140
|
-
function normalizeSdkSessionId(value) {
|
|
141
|
-
return normalizeOptionalString(value);
|
|
142
|
-
}
|
|
143
|
-
/**
|
|
144
|
-
* Pure pre-call decision: should attempt.ts call resumeSession or
|
|
145
|
-
* createSession?
|
|
146
|
-
*
|
|
147
|
-
* Rules:
|
|
148
|
-
* - No input → create (no-replay-state)
|
|
149
|
-
* - No (trimmed) sdkSessionId → create (no-sdk-session-id)
|
|
150
|
-
* - sdkSessionId + replayInvalid=true → create (replay-invalid),
|
|
151
|
-
* downgradedFromResume=true
|
|
152
|
-
* - sdkSessionId + replayInvalid=false → resume
|
|
153
|
-
*/
|
|
154
132
|
function decideReplayAction(input) {
|
|
155
133
|
if (!input) return {
|
|
156
134
|
action: "create",
|
|
157
135
|
downgradedFromResume: false,
|
|
158
136
|
downgradeReason: "no-replay-state"
|
|
159
137
|
};
|
|
160
|
-
const sdkSessionId =
|
|
138
|
+
const sdkSessionId = normalizeOptionalString(input.sdkSessionId);
|
|
161
139
|
if (!sdkSessionId) return {
|
|
162
140
|
action: "create",
|
|
163
141
|
downgradedFromResume: false,
|
|
@@ -192,24 +170,7 @@ function readErrorField(error, key) {
|
|
|
192
170
|
if (!error || typeof error !== "object") return;
|
|
193
171
|
return error[key];
|
|
194
172
|
}
|
|
195
|
-
/**
|
|
196
|
-
* Post-call: classify a resumeSession() failure so attempt.ts can
|
|
197
|
-
* decide whether to downgrade silently to createSession.
|
|
198
|
-
*
|
|
199
|
-
* Conservative: only treats clearly session-gone signals as recoverable.
|
|
200
|
-
* Structured signals (status === 404, recognised code strings) are
|
|
201
|
-
* checked first; message matching is a fallback because SDK error
|
|
202
|
-
* messages are not part of the typed contract.
|
|
203
|
-
*
|
|
204
|
-
* Everything else (transport errors, auth failures, generic Error) is
|
|
205
|
-
* unrecoverable and should surface to the outer attempt.ts try/catch
|
|
206
|
-
* which converts it to a prompt error.
|
|
207
|
-
*/
|
|
208
173
|
function classifyResumeFailure(error) {
|
|
209
|
-
if (error === void 0 || error === null) return {
|
|
210
|
-
recoverable: false,
|
|
211
|
-
kind: "unknown"
|
|
212
|
-
};
|
|
213
174
|
if (readErrorField(error, "status") === 404) return {
|
|
214
175
|
recoverable: true,
|
|
215
176
|
kind: "missing"
|
|
@@ -223,38 +184,16 @@ function classifyResumeFailure(error) {
|
|
|
223
184
|
recoverable: true,
|
|
224
185
|
kind: "missing"
|
|
225
186
|
};
|
|
226
|
-
const message = error
|
|
227
|
-
if (typeof message === "string") {
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
};
|
|
232
|
-
}
|
|
187
|
+
const message = readErrorField(error, "message");
|
|
188
|
+
if (typeof message === "string" && MISSING_SESSION_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return {
|
|
189
|
+
recoverable: true,
|
|
190
|
+
kind: "missing"
|
|
191
|
+
};
|
|
233
192
|
return {
|
|
234
193
|
recoverable: false,
|
|
235
194
|
kind: "unknown"
|
|
236
195
|
};
|
|
237
196
|
}
|
|
238
|
-
/**
|
|
239
|
-
* Compute the `EmbeddedRunReplayMetadata` to attach to the attempt
|
|
240
|
-
* result. Worst-case-wins:
|
|
241
|
-
*
|
|
242
|
-
* hadPotentialSideEffects = priorHadPotentialSideEffects OR timedOut
|
|
243
|
-
* OR thisAttemptHadPotentialSideEffects
|
|
244
|
-
* (timeout means we cannot prove the prompt was not partially
|
|
245
|
-
* committed server-side; treat as side-effecting so the
|
|
246
|
-
* orchestrator will not blindly re-issue the same prompt).
|
|
247
|
-
*
|
|
248
|
-
* replaySafe = NOT (
|
|
249
|
-
* priorReplayInvalid
|
|
250
|
-
* OR thisAttemptDowngradedFromResume
|
|
251
|
-
* OR thisAttemptResumeFailureRecovered
|
|
252
|
-
* OR hadPotentialSideEffects
|
|
253
|
-
* )
|
|
254
|
-
*
|
|
255
|
-
* Matches the parity rule in
|
|
256
|
-
* `src/agents/pi-embedded-runner/replay-state.ts#replayMetadataFromState`.
|
|
257
|
-
*/
|
|
258
197
|
function computeReplayMetadata(input) {
|
|
259
198
|
const priorReplayInvalid = input.priorReplayInvalid === true;
|
|
260
199
|
const priorHadPotentialSideEffects = input.priorHadPotentialSideEffects === true;
|
|
@@ -291,11 +230,7 @@ const COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
|
291
230
|
"web_search"
|
|
292
231
|
]);
|
|
293
232
|
function copilotToolMetasHavePotentialSideEffects(toolMetas) {
|
|
294
|
-
return (toolMetas ?? []).some((entry) => entry.asyncStarted === true || !
|
|
295
|
-
}
|
|
296
|
-
function isReplaySafeReadOnlyToolName(toolName) {
|
|
297
|
-
const normalized = toolName.trim().toLowerCase();
|
|
298
|
-
return COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES.has(normalized);
|
|
233
|
+
return (toolMetas ?? []).some((entry) => entry.asyncStarted === true || !COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES.has(entry.toolName.trim().toLowerCase()));
|
|
299
234
|
}
|
|
300
235
|
//#endregion
|
|
301
236
|
//#region extensions/copilot/src/attempt-config.ts
|
|
@@ -400,7 +335,12 @@ function buildCopilotAvailableTools(sdkTools, includeAskUser) {
|
|
|
400
335
|
return [...new Set(availableTools)];
|
|
401
336
|
}
|
|
402
337
|
async function createMessageOptions(params, context) {
|
|
403
|
-
const attachments =
|
|
338
|
+
const attachments = (await resolvePromptImages(params, context)).map((image, index) => ({
|
|
339
|
+
type: "blob",
|
|
340
|
+
data: image.data,
|
|
341
|
+
mimeType: image.mimeType,
|
|
342
|
+
displayName: `prompt-image-${index + 1}`
|
|
343
|
+
}));
|
|
404
344
|
const providerHeaders = context.provider.provider?.headers;
|
|
405
345
|
const requestHeaders = providerHeaders && Object.keys(providerHeaders).length > 0 ? { ...providerHeaders } : void 0;
|
|
406
346
|
return {
|
|
@@ -409,17 +349,6 @@ async function createMessageOptions(params, context) {
|
|
|
409
349
|
...requestHeaders ? { requestHeaders } : {}
|
|
410
350
|
};
|
|
411
351
|
}
|
|
412
|
-
function createPromptImageAttachments(images) {
|
|
413
|
-
return images.flatMap((image, index) => {
|
|
414
|
-
if (!image || typeof image !== "object" || image.type !== "image" || typeof image.data !== "string" || typeof image.mimeType !== "string") return [];
|
|
415
|
-
return [{
|
|
416
|
-
type: "blob",
|
|
417
|
-
data: image.data,
|
|
418
|
-
mimeType: image.mimeType,
|
|
419
|
-
displayName: `prompt-image-${index + 1}`
|
|
420
|
-
}];
|
|
421
|
-
});
|
|
422
|
-
}
|
|
423
352
|
async function resolvePromptImages(params, context) {
|
|
424
353
|
const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
|
|
425
354
|
if (!workspaceDir) return [];
|
|
@@ -586,11 +515,9 @@ function buildAssistantProjectionGroup(group, modelRef, resolveTimestamp, usageB
|
|
|
586
515
|
};
|
|
587
516
|
const narrative = [];
|
|
588
517
|
let terminalThinking;
|
|
589
|
-
const toolCallOrder = [];
|
|
590
518
|
const toolCallsById = /* @__PURE__ */ new Map();
|
|
591
519
|
for (const message of messages) for (const part of message.content) {
|
|
592
520
|
if (part.type === "toolCall") {
|
|
593
|
-
if (!toolCallsById.has(part.id)) toolCallOrder.push(part.id);
|
|
594
521
|
toolCallsById.set(part.id, part);
|
|
595
522
|
continue;
|
|
596
523
|
}
|
|
@@ -605,16 +532,12 @@ function buildAssistantProjectionGroup(group, modelRef, resolveTimestamp, usageB
|
|
|
605
532
|
};
|
|
606
533
|
else narrative.push(part);
|
|
607
534
|
}
|
|
608
|
-
const toolCalls = toolCallOrder.flatMap((id) => {
|
|
609
|
-
const toolCall = toolCallsById.get(id);
|
|
610
|
-
return toolCall ? [toolCall] : [];
|
|
611
|
-
});
|
|
612
535
|
const content = [
|
|
613
536
|
...terminalThinking ? [terminalThinking] : [],
|
|
614
537
|
...narrative,
|
|
615
|
-
...
|
|
538
|
+
...toolCallsById.values()
|
|
616
539
|
];
|
|
617
|
-
const toolCallIds = [...
|
|
540
|
+
const toolCallIds = [...toolCallsById.keys()];
|
|
618
541
|
return {
|
|
619
542
|
message: {
|
|
620
543
|
...last,
|
|
@@ -690,11 +613,8 @@ function sanitizeToolDetailText(text) {
|
|
|
690
613
|
//#endregion
|
|
691
614
|
//#region extensions/copilot/src/event-bridge.ts
|
|
692
615
|
function attachEventBridge(session, options) {
|
|
693
|
-
const messageOrder = [];
|
|
694
616
|
const messagesById = /* @__PURE__ */ new Map();
|
|
695
|
-
const reasoningOrder = [];
|
|
696
617
|
const reasoningById = /* @__PURE__ */ new Map();
|
|
697
|
-
const durableReasoningOrder = [];
|
|
698
618
|
const durableReasoningById = /* @__PURE__ */ new Map();
|
|
699
619
|
let lastAssistantEvent;
|
|
700
620
|
let lastAssistantReasoningText;
|
|
@@ -769,7 +689,7 @@ function attachEventBridge(session, options) {
|
|
|
769
689
|
const messageId = readNonEmptyStringPreservingWhitespace(event.data.messageId) ?? "assistant-message";
|
|
770
690
|
const delta = event.data.deltaContent;
|
|
771
691
|
if (!delta) return;
|
|
772
|
-
const entry = ensureMessageAccumulator(messagesById,
|
|
692
|
+
const entry = ensureMessageAccumulator(messagesById, messageId);
|
|
773
693
|
entry.text += delta;
|
|
774
694
|
const onAssistantDelta = options.onAssistantDelta;
|
|
775
695
|
if (!onAssistantDelta) return;
|
|
@@ -792,17 +712,11 @@ function attachEventBridge(session, options) {
|
|
|
792
712
|
const reasoningId = readNonEmptyStringPreservingWhitespace(event.data.reasoningId) ?? "assistant-reasoning";
|
|
793
713
|
const delta = event.data.deltaContent;
|
|
794
714
|
if (!delta) return;
|
|
795
|
-
if (!reasoningById.has(reasoningId)) {
|
|
796
|
-
reasoningById.set(reasoningId, "");
|
|
797
|
-
reasoningOrder.push(reasoningId);
|
|
798
|
-
}
|
|
799
715
|
reasoningById.set(reasoningId, `${reasoningById.get(reasoningId) ?? ""}${delta}`);
|
|
800
716
|
});
|
|
801
717
|
registerListener(session, unsubscribeFns, "assistant.reasoning", (event) => {
|
|
802
718
|
if (!isRootSessionEvent(event) || event.ephemeral === true) return;
|
|
803
|
-
if (!reasoningById.has(event.data.reasoningId)) reasoningOrder.push(event.data.reasoningId);
|
|
804
719
|
reasoningById.set(event.data.reasoningId, event.data.content);
|
|
805
|
-
if (!durableReasoningById.has(event.data.reasoningId)) durableReasoningOrder.push(event.data.reasoningId);
|
|
806
720
|
durableReasoningById.set(event.data.reasoningId, event.data.content);
|
|
807
721
|
unconsumedDurableReasoning = true;
|
|
808
722
|
});
|
|
@@ -952,17 +866,8 @@ function attachEventBridge(session, options) {
|
|
|
952
866
|
}
|
|
953
867
|
});
|
|
954
868
|
});
|
|
955
|
-
registerListener(session, unsubscribeFns, "subagent.started", (event) => {
|
|
956
|
-
forwardNativeSubagentEvent(event);
|
|
957
|
-
});
|
|
958
|
-
registerListener(session, unsubscribeFns, "subagent.completed", (event) => {
|
|
959
|
-
forwardNativeSubagentEvent(event);
|
|
960
|
-
});
|
|
961
|
-
registerListener(session, unsubscribeFns, "subagent.failed", (event) => {
|
|
962
|
-
forwardNativeSubagentEvent(event);
|
|
963
|
-
});
|
|
964
869
|
registerListener(session, unsubscribeFns, "session.compaction_start", (event) => {
|
|
965
|
-
if (!
|
|
870
|
+
if (!isRootSessionEvent(event)) return;
|
|
966
871
|
observedCompaction = true;
|
|
967
872
|
if (activeCompactionCount === 0) compactionIdle = new Promise((resolve) => {
|
|
968
873
|
resolveCompactionIdle = resolve;
|
|
@@ -974,7 +879,7 @@ function attachEventBridge(session, options) {
|
|
|
974
879
|
if (event.data.success) try {
|
|
975
880
|
options.onContextCompacted?.();
|
|
976
881
|
} catch {}
|
|
977
|
-
if (!
|
|
882
|
+
if (!isRootSessionEvent(event)) return;
|
|
978
883
|
activeCompactionCount = Math.max(0, activeCompactionCount - 1);
|
|
979
884
|
enqueueCompactionCallback(() => options.onCompactionComplete?.({
|
|
980
885
|
...event.data.messagesRemoved !== void 0 ? { messagesRemoved: event.data.messagesRemoved } : {},
|
|
@@ -986,7 +891,7 @@ function attachEventBridge(session, options) {
|
|
|
986
891
|
}
|
|
987
892
|
});
|
|
988
893
|
registerListener(session, unsubscribeFns, "session.idle", (event) => {
|
|
989
|
-
if (!
|
|
894
|
+
if (!isRootSessionEvent(event)) return;
|
|
990
895
|
markUnconsumedReasoningIncomplete();
|
|
991
896
|
flushPendingAssistantProjection();
|
|
992
897
|
observedSessionIdle = true;
|
|
@@ -1043,7 +948,7 @@ function attachEventBridge(session, options) {
|
|
|
1043
948
|
},
|
|
1044
949
|
snapshot() {
|
|
1045
950
|
return {
|
|
1046
|
-
assistantTexts: finalizeAssistantTexts(
|
|
951
|
+
assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent),
|
|
1047
952
|
completedCount,
|
|
1048
953
|
lastAssistantEvent,
|
|
1049
954
|
startedCount,
|
|
@@ -1060,11 +965,11 @@ function attachEventBridge(session, options) {
|
|
|
1060
965
|
now: args.now,
|
|
1061
966
|
reasoningText: lastAssistantReasoningText,
|
|
1062
967
|
usage: resolveAssistantUsage(lastAssistantEvent, usage, usageByApiCallId),
|
|
1063
|
-
assistantTexts: finalizeAssistantTexts(
|
|
968
|
+
assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent)
|
|
1064
969
|
});
|
|
1065
970
|
},
|
|
1066
971
|
finalizeAssistantTexts() {
|
|
1067
|
-
return finalizeAssistantTexts(
|
|
972
|
+
return finalizeAssistantTexts(messagesById, lastAssistantEvent);
|
|
1068
973
|
},
|
|
1069
974
|
completeTool(tool) {
|
|
1070
975
|
const owner = toolCallsById.get(tool.parentToolCallId ?? tool.toolCallId);
|
|
@@ -1094,13 +999,11 @@ function attachEventBridge(session, options) {
|
|
|
1094
999
|
if (handledAssistantEventIds.has(event.id)) return;
|
|
1095
1000
|
handledAssistantEventIds.add(event.id);
|
|
1096
1001
|
for (const request of event.data.toolRequests ?? []) projectedToolNamesByCallId.set(request.toolCallId, request.name);
|
|
1097
|
-
const entry = ensureMessageAccumulator(messagesById,
|
|
1002
|
+
const entry = ensureMessageAccumulator(messagesById, event.data.messageId);
|
|
1098
1003
|
if (typeof event.data.content === "string" && event.data.content.length >= entry.text.length) entry.text = event.data.content;
|
|
1099
|
-
lastAssistantReasoningText = event.data.reasoningText ?? (
|
|
1100
|
-
const transcriptReasoningText = event.data.reasoningText ?? (
|
|
1101
|
-
reasoningOrder.length = 0;
|
|
1004
|
+
lastAssistantReasoningText = event.data.reasoningText ?? ([...reasoningById.values()].join("") || void 0);
|
|
1005
|
+
const transcriptReasoningText = event.data.reasoningText ?? ([...durableReasoningById.values()].join("") || void 0);
|
|
1102
1006
|
reasoningById.clear();
|
|
1103
|
-
durableReasoningOrder.length = 0;
|
|
1104
1007
|
durableReasoningById.clear();
|
|
1105
1008
|
unconsumedDurableReasoning = false;
|
|
1106
1009
|
const chunk = {
|
|
@@ -1144,9 +1047,7 @@ function attachEventBridge(session, options) {
|
|
|
1144
1047
|
}
|
|
1145
1048
|
function markUnconsumedReasoningIncomplete() {
|
|
1146
1049
|
if (unconsumedDurableReasoning) options.transcriptProjection?.journal.markReplayIncomplete();
|
|
1147
|
-
reasoningOrder.length = 0;
|
|
1148
1050
|
reasoningById.clear();
|
|
1149
|
-
durableReasoningOrder.length = 0;
|
|
1150
1051
|
durableReasoningById.clear();
|
|
1151
1052
|
unconsumedDurableReasoning = false;
|
|
1152
1053
|
}
|
|
@@ -1186,11 +1087,6 @@ function attachEventBridge(session, options) {
|
|
|
1186
1087
|
const invoke = () => callback(event);
|
|
1187
1088
|
agentEventChain = agentEventChain.then(invoke, invoke).catch(() => void 0);
|
|
1188
1089
|
}
|
|
1189
|
-
function forwardNativeSubagentEvent(event) {
|
|
1190
|
-
try {
|
|
1191
|
-
options.onNativeSubagentEvent?.(event);
|
|
1192
|
-
} catch {}
|
|
1193
|
-
}
|
|
1194
1090
|
async function awaitStableCompaction() {
|
|
1195
1091
|
const idle = activeCompactionCount > 0 ? compactionIdle : void 0;
|
|
1196
1092
|
if (idle) await idle;
|
|
@@ -1205,20 +1101,16 @@ function createPromptError(code, message, cause) {
|
|
|
1205
1101
|
if (cause !== void 0) error.cause = cause;
|
|
1206
1102
|
return error;
|
|
1207
1103
|
}
|
|
1208
|
-
function ensureMessageAccumulator(messagesById,
|
|
1104
|
+
function ensureMessageAccumulator(messagesById, messageId) {
|
|
1209
1105
|
let entry = messagesById.get(messageId);
|
|
1210
1106
|
if (!entry) {
|
|
1211
|
-
entry = {
|
|
1212
|
-
messageId,
|
|
1213
|
-
text: ""
|
|
1214
|
-
};
|
|
1107
|
+
entry = { text: "" };
|
|
1215
1108
|
messagesById.set(messageId, entry);
|
|
1216
|
-
messageOrder.push(messageId);
|
|
1217
1109
|
}
|
|
1218
1110
|
return entry;
|
|
1219
1111
|
}
|
|
1220
|
-
function finalizeAssistantTexts(
|
|
1221
|
-
const texts =
|
|
1112
|
+
function finalizeAssistantTexts(messagesById, event) {
|
|
1113
|
+
const texts = [...messagesById.values()].map((message) => message.text).filter((text) => text.length > 0);
|
|
1222
1114
|
if (texts.length > 0) return texts;
|
|
1223
1115
|
if (event?.data.content) return [event.data.content];
|
|
1224
1116
|
return [];
|
|
@@ -1229,12 +1121,6 @@ function isAssistantMessageEvent(event) {
|
|
|
1229
1121
|
function isRootSessionEvent(event) {
|
|
1230
1122
|
return event.agentId === void 0;
|
|
1231
1123
|
}
|
|
1232
|
-
function isRootCompactionEvent(event) {
|
|
1233
|
-
return isRootSessionEvent(event);
|
|
1234
|
-
}
|
|
1235
|
-
function joinReasoning(order, reasoningById) {
|
|
1236
|
-
return order.map((reasoningId) => reasoningById.get(reasoningId) ?? "").join("");
|
|
1237
|
-
}
|
|
1238
1124
|
function splitPlanText(text) {
|
|
1239
1125
|
return (text ?? "").split(/\r?\n/).map((line) => line.trim().replace(/^[-*]\s+/, "")).filter((line) => line.length > 0);
|
|
1240
1126
|
}
|
|
@@ -1270,7 +1156,6 @@ async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now
|
|
|
1270
1156
|
function deferBackgroundCompactionCleanup(params) {
|
|
1271
1157
|
return (async () => {
|
|
1272
1158
|
let outcome = "deadline";
|
|
1273
|
-
let finalizationError;
|
|
1274
1159
|
try {
|
|
1275
1160
|
outcome = await awaitDeferredCleanupBeforeDeadline({
|
|
1276
1161
|
abortSignal: params.abortSignal,
|
|
@@ -1283,12 +1168,8 @@ function deferBackgroundCompactionCleanup(params) {
|
|
|
1283
1168
|
await cancelBackgroundCompactionBeforeTeardown(params.session);
|
|
1284
1169
|
params.bridge.settleCompactionWait();
|
|
1285
1170
|
}
|
|
1286
|
-
try {
|
|
1287
|
-
params.finalizeNativeSubagents?.();
|
|
1288
|
-
} catch (error) {
|
|
1289
|
-
finalizationError = toCopilotError(error);
|
|
1290
|
-
}
|
|
1291
1171
|
params.bridge.detach();
|
|
1172
|
+
await params.bridge.awaitAgentEventChain();
|
|
1292
1173
|
try {
|
|
1293
1174
|
await params.session.disconnect();
|
|
1294
1175
|
} catch {}
|
|
@@ -1301,7 +1182,6 @@ function deferBackgroundCompactionCleanup(params) {
|
|
|
1301
1182
|
await params.pool.release(params.handle);
|
|
1302
1183
|
} catch {}
|
|
1303
1184
|
}
|
|
1304
|
-
if (finalizationError) throw finalizationError;
|
|
1305
1185
|
return outcome;
|
|
1306
1186
|
})();
|
|
1307
1187
|
}
|
|
@@ -1491,6 +1371,17 @@ function isCompleteToolGroup(messages, order) {
|
|
|
1491
1371
|
const [assistant, ...results] = messages;
|
|
1492
1372
|
return assistant?.role === "assistant" && JSON.stringify(readAssistantToolCallIds(assistant)) === JSON.stringify(order) && results.length === order.length && results.every((message, index) => message.role === "toolResult" && message.toolCallId === order[index]);
|
|
1493
1373
|
}
|
|
1374
|
+
function isSameUserTurn(candidate, current, currentRunUserKey) {
|
|
1375
|
+
if (candidate?.role !== "user" || !current) return false;
|
|
1376
|
+
if (candidate === current) return true;
|
|
1377
|
+
const candidateKey = candidate.idempotencyKey;
|
|
1378
|
+
const currentKey = current.idempotencyKey;
|
|
1379
|
+
if (typeof candidateKey === "string" || typeof currentKey === "string") {
|
|
1380
|
+
if (typeof candidateKey === "string" && typeof currentKey === "string") return candidateKey === currentKey;
|
|
1381
|
+
if (typeof candidateKey !== "string" || typeof currentKey === "string" || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
|
|
1382
|
+
}
|
|
1383
|
+
return candidate.timestamp === current.timestamp && userText(candidate.content) === userText(current.content);
|
|
1384
|
+
}
|
|
1494
1385
|
//#endregion
|
|
1495
1386
|
//#region extensions/copilot/src/attempt-finalize.ts
|
|
1496
1387
|
async function completeCopilotAttempt(params) {
|
|
@@ -1569,22 +1460,11 @@ function includePreparedUser(messages, prepared, hidden, currentRunUserKey) {
|
|
|
1569
1460
|
hidden: hidden || prepared.display === false,
|
|
1570
1461
|
message: prepared
|
|
1571
1462
|
});
|
|
1572
|
-
if (
|
|
1463
|
+
if (isSameUserTurn(messages.at(-1), projected, currentRunUserKey)) return [...messages.slice(0, -1), projected];
|
|
1573
1464
|
return [...messages, projected];
|
|
1574
1465
|
}
|
|
1575
1466
|
function removePreparedUser(messages, prepared, currentRunUserKey) {
|
|
1576
|
-
return prepared &&
|
|
1577
|
-
}
|
|
1578
|
-
function isSamePreparedUser(candidate, prepared, currentRunUserKey) {
|
|
1579
|
-
if (candidate?.role !== "user") return false;
|
|
1580
|
-
if (candidate === prepared) return true;
|
|
1581
|
-
const candidateKey = candidate.idempotencyKey;
|
|
1582
|
-
const preparedKey = prepared.idempotencyKey;
|
|
1583
|
-
if (typeof candidateKey === "string" || typeof preparedKey === "string") {
|
|
1584
|
-
if (typeof candidateKey === "string" && typeof preparedKey === "string") return candidateKey === preparedKey;
|
|
1585
|
-
if (typeof candidateKey !== "string" || typeof preparedKey === "string" || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
|
|
1586
|
-
}
|
|
1587
|
-
return candidate.timestamp === prepared.timestamp && userText(candidate.content) === userText(prepared.content);
|
|
1467
|
+
return prepared && isSameUserTurn(messages.at(-1), prepared, currentRunUserKey) ? messages.slice(0, -1) : messages;
|
|
1588
1468
|
}
|
|
1589
1469
|
//#endregion
|
|
1590
1470
|
//#region extensions/copilot/src/attempt-mode.ts
|
|
@@ -1621,7 +1501,7 @@ async function createCopilotToolBridge(input) {
|
|
|
1621
1501
|
};
|
|
1622
1502
|
const toolSurfaceRuntime = createAgentHarnessToolSurfaceRuntime({
|
|
1623
1503
|
abortSignal: attemptParams.abortSignal,
|
|
1624
|
-
agentId:
|
|
1504
|
+
agentId: input.agentId,
|
|
1625
1505
|
config: attemptParams.config,
|
|
1626
1506
|
codeModeOverride: attemptParams.codeModeOverride,
|
|
1627
1507
|
disableTools: attemptParams.disableTools,
|
|
@@ -1638,7 +1518,7 @@ async function createCopilotToolBridge(input) {
|
|
|
1638
1518
|
runId: attemptParams.runId,
|
|
1639
1519
|
runtimeToolAllowlist: toolPlan.runtimeToolAllowlist,
|
|
1640
1520
|
sessionId: input.sessionId,
|
|
1641
|
-
sessionKey: attemptParams.
|
|
1521
|
+
sessionKey: attemptParams.sessionKey,
|
|
1642
1522
|
scheduledToolPolicy: attemptParams.scheduledToolPolicy,
|
|
1643
1523
|
sourceReplyDeliveryMode: attemptParams.sourceReplyDeliveryMode,
|
|
1644
1524
|
toolsAllow: attemptParams.toolsAllow
|
|
@@ -2218,26 +2098,6 @@ const COPILOT_BOOTSTRAP_CONTEXT_ORDER = /* @__PURE__ */ new Map([
|
|
|
2218
2098
|
["user.md", 60],
|
|
2219
2099
|
["memory.md", 70]
|
|
2220
2100
|
]);
|
|
2221
|
-
/**
|
|
2222
|
-
* Loads OpenClaw workspace bootstrap files (IDENTITY.md, SOUL.md,
|
|
2223
|
-
* HEARTBEAT.md, USER.md, BOOTSTRAP.md, MEMORY.md, ...) using
|
|
2224
|
-
* the shared core helper PI and codex both use, then renders them as a
|
|
2225
|
-
* single string suitable for `SessionConfig.systemMessage.content` on
|
|
2226
|
-
* the Copilot SDK.
|
|
2227
|
-
*
|
|
2228
|
-
* Returns `instructions: undefined` when there are no relevant files
|
|
2229
|
-
* (after filtering out SDK-native docs) so the caller can omit the
|
|
2230
|
-
* `systemMessage` field entirely rather than passing an empty string.
|
|
2231
|
-
*
|
|
2232
|
-
* Mirrors codex's `buildCodexWorkspaceBootstrapContext` /
|
|
2233
|
-
* `renderCodexWorkspaceBootstrapInstructions` pair
|
|
2234
|
-
* (`extensions/codex/src/app-server/run-attempt.ts:2877,3047`). The
|
|
2235
|
-
* shape divergence — codex returns instructions inside the same object
|
|
2236
|
-
* as bootstrapFiles+contextFiles for its developerInstructions field;
|
|
2237
|
-
* copilot exposes the rendered string for SDK `systemMessage` — is the
|
|
2238
|
-
* intended difference between the two runtimes' system-prompt
|
|
2239
|
-
* surfaces.
|
|
2240
|
-
*/
|
|
2241
2101
|
async function resolveCopilotWorkspaceBootstrapContext(params) {
|
|
2242
2102
|
const { attempt } = params;
|
|
2243
2103
|
const workspaceDir = readResolvedWorkspacePath(attempt.workspaceDir);
|
|
@@ -2275,17 +2135,6 @@ async function resolveCopilotWorkspaceBootstrapContext(params) {
|
|
|
2275
2135
|
};
|
|
2276
2136
|
}
|
|
2277
2137
|
}
|
|
2278
|
-
/**
|
|
2279
|
-
* Rewrites context-file paths from a source workspace root to a
|
|
2280
|
-
* target workspace root, mirroring PI's
|
|
2281
|
-
* `remapInjectedContextFilesToWorkspace`
|
|
2282
|
-
* (`src/agents/pi-embedded-runner/run/attempt.ts:603`). Files whose
|
|
2283
|
-
* resolved relative path escapes the source workspace (parent
|
|
2284
|
-
* traversal or absolute) are left untouched so we never pretend a
|
|
2285
|
-
* file lives inside the sandbox when it does not. Intentionally local
|
|
2286
|
-
* to the Copilot extension (codex keeps similar helpers extension-local
|
|
2287
|
-
* rather than importing from PI).
|
|
2288
|
-
*/
|
|
2289
2138
|
function remapCopilotBootstrapContextFiles(params) {
|
|
2290
2139
|
if (params.sourceWorkspaceDir === params.targetWorkspaceDir) return params.files;
|
|
2291
2140
|
return params.files.map((file) => {
|
|
@@ -2300,16 +2149,6 @@ function remapCopilotBootstrapContextFiles(params) {
|
|
|
2300
2149
|
function isRelativePathInsideOrEqual(relativePath) {
|
|
2301
2150
|
return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
|
|
2302
2151
|
}
|
|
2303
|
-
/**
|
|
2304
|
-
* Renders bootstrap context files into a single string for
|
|
2305
|
-
* `SessionConfig.systemMessage.content` (append mode). Returns
|
|
2306
|
-
* `undefined` when no relevant files remain after filtering, so the
|
|
2307
|
-
* caller can skip setting `systemMessage` altogether.
|
|
2308
|
-
*
|
|
2309
|
-
* Files whose basename matches a doc the Copilot SDK already loads
|
|
2310
|
-
* natively (see {@link COPILOT_NATIVE_PROJECT_DOC_BASENAMES}) are
|
|
2311
|
-
* dropped to avoid duplication with SDK-managed sections.
|
|
2312
|
-
*/
|
|
2313
2152
|
function renderCopilotWorkspaceBootstrapInstructions(contextFiles) {
|
|
2314
2153
|
const files = contextFiles.filter((file) => {
|
|
2315
2154
|
const baseName = getCopilotContextFileBasename(file.path);
|
|
@@ -2440,18 +2279,15 @@ async function createCopilotSessionSetup(params) {
|
|
|
2440
2279
|
signal
|
|
2441
2280
|
});
|
|
2442
2281
|
})();
|
|
2443
|
-
const
|
|
2282
|
+
const buildSessionConfig = (provider) => createSessionConfig(attemptInput, modelRef.id, promptTools, poolAcquire.auth, provider, finalDeveloperInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, userInputBridge?.onUserInputRequest, {
|
|
2444
2283
|
hooksBridgeOptions: hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0,
|
|
2445
2284
|
includeAskUser,
|
|
2446
2285
|
operation: operation ?? "attempt"
|
|
2447
2286
|
});
|
|
2287
|
+
const sessionConfig = buildSessionConfig(sessionProvider);
|
|
2448
2288
|
return {
|
|
2449
2289
|
attemptInput,
|
|
2450
|
-
compactionSessionConfig: byokProxy ?
|
|
2451
|
-
hooksBridgeOptions: hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0,
|
|
2452
|
-
includeAskUser,
|
|
2453
|
-
operation: operation ?? "attempt"
|
|
2454
|
-
}) : sessionConfig,
|
|
2290
|
+
compactionSessionConfig: byokProxy ? buildSessionConfig(poolAcquire.provider) : sessionConfig,
|
|
2455
2291
|
emitLlmInput,
|
|
2456
2292
|
hasNativePromptHook,
|
|
2457
2293
|
sessionConfig,
|
|
@@ -2881,151 +2717,6 @@ function readIdempotencyKey(message) {
|
|
|
2881
2717
|
function isCurrentJournalIdentity(key, params) {
|
|
2882
2718
|
return key === `${params.attempt.runId}:user` || key.startsWith(`copilot-sdk:${params.sdkSessionId}:`);
|
|
2883
2719
|
}
|
|
2884
|
-
function isSameUserTurn(candidate, current, currentRunUserKey) {
|
|
2885
|
-
if (candidate?.role !== "user" || !current) return false;
|
|
2886
|
-
if (candidate === current) return true;
|
|
2887
|
-
const candidateKey = candidate.idempotencyKey;
|
|
2888
|
-
const currentKey = current.idempotencyKey;
|
|
2889
|
-
if (typeof candidateKey === "string" || typeof currentKey === "string") {
|
|
2890
|
-
if (typeof candidateKey === "string" && typeof currentKey === "string") return candidateKey === currentKey;
|
|
2891
|
-
if (typeof candidateKey !== "string" || typeof currentKey === "string" || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
|
|
2892
|
-
}
|
|
2893
|
-
return candidate.timestamp === current.timestamp && userText(candidate.content) === userText(current.content);
|
|
2894
|
-
}
|
|
2895
|
-
//#endregion
|
|
2896
|
-
//#region extensions/copilot/src/native-subagent-task-mirror.ts
|
|
2897
|
-
const COPILOT_NATIVE_SUBAGENT_TASK_KIND = "copilot-native";
|
|
2898
|
-
const COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX = "copilot-agent:";
|
|
2899
|
-
function createCopilotNativeSubagentTaskMirror(params) {
|
|
2900
|
-
if (!params.scope) return;
|
|
2901
|
-
return new CopilotNativeSubagentTaskMirror({
|
|
2902
|
-
agentId: params.agentId,
|
|
2903
|
-
now: params.now
|
|
2904
|
-
}, createAgentHarnessTaskRuntime({
|
|
2905
|
-
runtime: "subagent",
|
|
2906
|
-
taskKind: COPILOT_NATIVE_SUBAGENT_TASK_KIND,
|
|
2907
|
-
scope: params.scope,
|
|
2908
|
-
runIdPrefix: COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX
|
|
2909
|
-
}));
|
|
2910
|
-
}
|
|
2911
|
-
var CopilotNativeSubagentTaskMirror = class {
|
|
2912
|
-
constructor(params, runtime) {
|
|
2913
|
-
this.params = params;
|
|
2914
|
-
this.runtime = runtime;
|
|
2915
|
-
this.runIdByAgentId = /* @__PURE__ */ new Map();
|
|
2916
|
-
this.runIdByToolCallId = /* @__PURE__ */ new Map();
|
|
2917
|
-
this.activeRuns = /* @__PURE__ */ new Map();
|
|
2918
|
-
this.now = params.now ?? Date.now;
|
|
2919
|
-
}
|
|
2920
|
-
handleEvent(event) {
|
|
2921
|
-
const toolCallId = event.data.toolCallId.trim();
|
|
2922
|
-
if (!toolCallId) return;
|
|
2923
|
-
const runId = this.resolveRunId(event);
|
|
2924
|
-
if (event.type === "subagent.started") {
|
|
2925
|
-
this.handleStarted(event, runId, toolCallId);
|
|
2926
|
-
return;
|
|
2927
|
-
}
|
|
2928
|
-
if (event.type === "subagent.completed") {
|
|
2929
|
-
this.handleCompleted(event, runId);
|
|
2930
|
-
return;
|
|
2931
|
-
}
|
|
2932
|
-
this.handleFailed(event, runId);
|
|
2933
|
-
}
|
|
2934
|
-
finalizeActiveRuns() {
|
|
2935
|
-
const eventAt = this.now();
|
|
2936
|
-
let failure;
|
|
2937
|
-
for (const runId of this.activeRuns.keys()) try {
|
|
2938
|
-
this.finalizeRun({
|
|
2939
|
-
runId,
|
|
2940
|
-
status: "cancelled",
|
|
2941
|
-
endedAt: eventAt,
|
|
2942
|
-
lastEventAt: eventAt,
|
|
2943
|
-
error: "Subagent ended with its parent attempt.",
|
|
2944
|
-
progressSummary: "Subagent cancelled with its parent attempt.",
|
|
2945
|
-
terminalSummary: "Subagent cancelled."
|
|
2946
|
-
});
|
|
2947
|
-
} catch (error) {
|
|
2948
|
-
failure ??= { error };
|
|
2949
|
-
}
|
|
2950
|
-
if (failure) throw failure.error;
|
|
2951
|
-
}
|
|
2952
|
-
handleStarted(event, runId, toolCallId) {
|
|
2953
|
-
const agentId = event.agentId?.trim();
|
|
2954
|
-
if (agentId ? this.runIdByAgentId.get(agentId) : this.runIdByToolCallId.get(toolCallId)) return;
|
|
2955
|
-
const eventAt = this.now();
|
|
2956
|
-
const label = event.data.agentDisplayName.trim() || event.data.agentName.trim();
|
|
2957
|
-
const task = event.data.agentDescription.trim() || `Subagent ${label}`;
|
|
2958
|
-
const taskRecord = this.runtime.tryCreateRunningTaskRun({
|
|
2959
|
-
sourceId: toolCallId,
|
|
2960
|
-
agentId: this.params.agentId,
|
|
2961
|
-
runId,
|
|
2962
|
-
label: label || "Subagent",
|
|
2963
|
-
task,
|
|
2964
|
-
notifyPolicy: "silent",
|
|
2965
|
-
deliveryStatus: "not_applicable",
|
|
2966
|
-
preferMetadata: true,
|
|
2967
|
-
startedAt: eventAt,
|
|
2968
|
-
lastEventAt: eventAt,
|
|
2969
|
-
progressSummary: "Subagent started."
|
|
2970
|
-
});
|
|
2971
|
-
if (!taskRecord) return;
|
|
2972
|
-
if (agentId) this.runIdByAgentId.set(agentId, runId);
|
|
2973
|
-
else this.runIdByToolCallId.set(toolCallId, runId);
|
|
2974
|
-
this.activeRuns.set(runId, { taskId: taskRecord.taskId });
|
|
2975
|
-
}
|
|
2976
|
-
handleCompleted(event, runId) {
|
|
2977
|
-
const eventAt = this.now();
|
|
2978
|
-
this.finalizeRun({
|
|
2979
|
-
runId,
|
|
2980
|
-
status: "succeeded",
|
|
2981
|
-
endedAt: eventAt,
|
|
2982
|
-
lastEventAt: eventAt,
|
|
2983
|
-
progressSummary: "Subagent completed.",
|
|
2984
|
-
terminalSummary: buildCompletionSummary(event)
|
|
2985
|
-
});
|
|
2986
|
-
}
|
|
2987
|
-
handleFailed(event, runId) {
|
|
2988
|
-
const eventAt = this.now();
|
|
2989
|
-
this.finalizeRun({
|
|
2990
|
-
runId,
|
|
2991
|
-
status: "failed",
|
|
2992
|
-
endedAt: eventAt,
|
|
2993
|
-
lastEventAt: eventAt,
|
|
2994
|
-
error: event.data.error,
|
|
2995
|
-
progressSummary: "Subagent failed.",
|
|
2996
|
-
terminalSummary: "Subagent failed."
|
|
2997
|
-
});
|
|
2998
|
-
}
|
|
2999
|
-
finalizeRun(params) {
|
|
3000
|
-
const run = this.activeRuns.get(params.runId);
|
|
3001
|
-
if (!run) return;
|
|
3002
|
-
run.terminal ??= params;
|
|
3003
|
-
const matchesRun = (task) => task.taskId === run.taskId && task.runId === params.runId;
|
|
3004
|
-
const before = this.runtime.listTaskRecords().find(matchesRun);
|
|
3005
|
-
if (!before || before.status !== "queued" && before.status !== "running") {
|
|
3006
|
-
this.activeRuns.delete(params.runId);
|
|
3007
|
-
return;
|
|
3008
|
-
}
|
|
3009
|
-
const current = this.runtime.finalizeTaskRunByRunId(run.terminal).find(matchesRun) ?? this.runtime.listTaskRecords().find(matchesRun);
|
|
3010
|
-
if (current?.status === "queued" || current?.status === "running") throw new Error(`Native subagent task finalization did not persist: ${params.runId}`);
|
|
3011
|
-
this.activeRuns.delete(params.runId);
|
|
3012
|
-
}
|
|
3013
|
-
resolveRunId(event) {
|
|
3014
|
-
const agentId = event.agentId?.trim();
|
|
3015
|
-
if (agentId) {
|
|
3016
|
-
const existing = this.runIdByAgentId.get(agentId);
|
|
3017
|
-
if (existing) return existing;
|
|
3018
|
-
}
|
|
3019
|
-
const existing = this.runIdByToolCallId.get(event.data.toolCallId);
|
|
3020
|
-
if (existing) return existing;
|
|
3021
|
-
const identity = agentId || event.data.toolCallId.trim();
|
|
3022
|
-
return `${COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX}${identity}`;
|
|
3023
|
-
}
|
|
3024
|
-
};
|
|
3025
|
-
function buildCompletionSummary(event) {
|
|
3026
|
-
const details = [event.data.totalToolCalls !== void 0 ? `${event.data.totalToolCalls} tool calls` : void 0, event.data.totalTokens !== void 0 ? `${event.data.totalTokens} tokens` : void 0].filter((value) => value !== void 0);
|
|
3027
|
-
return details.length > 0 ? `Subagent completed (${details.join(", ")}).` : "Subagent completed.";
|
|
3028
|
-
}
|
|
3029
2720
|
//#endregion
|
|
3030
2721
|
//#region extensions/copilot/src/attempt-execution.ts
|
|
3031
2722
|
async function runCopilotExecution(context) {
|
|
@@ -3048,11 +2739,6 @@ async function runCopilotExecution(context) {
|
|
|
3048
2739
|
let bridge;
|
|
3049
2740
|
let transcriptJournal;
|
|
3050
2741
|
let initialSdkUserValidated = false;
|
|
3051
|
-
const nativeSubagentTaskMirror = createCopilotNativeSubagentTaskMirror({
|
|
3052
|
-
agentId: sessionAgentId,
|
|
3053
|
-
now,
|
|
3054
|
-
scope: input.agentHarnessTaskRuntimeScope
|
|
3055
|
-
});
|
|
3056
2742
|
let activeRunHandleRef;
|
|
3057
2743
|
let userInputBridgeRef;
|
|
3058
2744
|
let cleanupToolBridge;
|
|
@@ -3284,7 +2970,6 @@ async function runCopilotExecution(context) {
|
|
|
3284
2970
|
sessionKey: input.sessionKey,
|
|
3285
2971
|
onAssistantDelta: settledToolFinalization ? void 0 : input.onAssistantDelta,
|
|
3286
2972
|
onAgentEvent: settledToolFinalization ? void 0 : input.onAgentEvent,
|
|
3287
|
-
onNativeSubagentEvent: (event) => nativeSubagentTaskMirror?.handleEvent(event),
|
|
3288
2973
|
onContextCompacted: () => {
|
|
3289
2974
|
computerContextEpoch.value += 1;
|
|
3290
2975
|
delete computerContextEpoch.frameToolCallId;
|
|
@@ -3414,7 +3099,6 @@ async function runCopilotExecution(context) {
|
|
|
3414
3099
|
cleanupToolBridge,
|
|
3415
3100
|
cleanupByokProxy,
|
|
3416
3101
|
deleteSessionOnIncompleteCleanup: nativeSessionCreatedFresh && initialUserValidated,
|
|
3417
|
-
finalizeNativeSubagents: () => nativeSubagentTaskMirror?.finalizeActiveRuns(),
|
|
3418
3102
|
handle,
|
|
3419
3103
|
pool: deps.pool,
|
|
3420
3104
|
sdkSessionId,
|
|
@@ -3434,15 +3118,10 @@ async function runCopilotExecution(context) {
|
|
|
3434
3118
|
params.abortSignal?.removeEventListener("abort", onAbort);
|
|
3435
3119
|
} else {
|
|
3436
3120
|
await bridge?.awaitCompactionChain();
|
|
3121
|
+
bridge?.detach();
|
|
3437
3122
|
await bridge?.awaitAgentEventChain();
|
|
3438
|
-
try {
|
|
3439
|
-
nativeSubagentTaskMirror?.finalizeActiveRuns();
|
|
3440
|
-
} catch (error) {
|
|
3441
|
-
promptError ??= toCopilotError(error);
|
|
3442
|
-
}
|
|
3443
3123
|
cleanupToolBridge?.();
|
|
3444
3124
|
await cleanupByokProxy?.();
|
|
3445
|
-
bridge?.detach();
|
|
3446
3125
|
params.abortSignal?.removeEventListener("abort", onAbort);
|
|
3447
3126
|
if (session) try {
|
|
3448
3127
|
await session.disconnect();
|
|
@@ -10,49 +10,6 @@ import { pipeline } from "node:stream/promises";
|
|
|
10
10
|
import { fetchWithSsrFGuard, isBlockedHostnameOrIp } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
11
11
|
import { isNonSecretApiKeyMarker } from "openclaw/plugin-sdk/provider-auth";
|
|
12
12
|
//#region extensions/copilot/src/auth-bridge.ts
|
|
13
|
-
/**
|
|
14
|
-
* Pure functional auth resolver for the copilot agent runtime.
|
|
15
|
-
*
|
|
16
|
-
* Scope:
|
|
17
|
-
*
|
|
18
|
-
* - Consumes the resolved auth signals that core's harness contract
|
|
19
|
-
* already carries on `EmbeddedRunAttemptParams` (=
|
|
20
|
-
* `AgentHarnessAttemptParams`): `resolvedApiKey`, `authProfileId`,
|
|
21
|
-
* `authProfileIdSource`. Core resolves these from the agent's
|
|
22
|
-
* `AuthProfileStore` via `provider-usage.auth.ts:resolveProviderAuths`
|
|
23
|
-
* before invoking the harness, so the harness does not re-perform
|
|
24
|
-
* the lookup (and could not, due to the package boundary in
|
|
25
|
-
* `tsconfig.package-boundary.base.json`).
|
|
26
|
-
* - Reads optional explicit overrides from the harness attempt params
|
|
27
|
-
* (`auth.useLoggedInUser`, `auth.gitHubToken`) for direct CLI / test
|
|
28
|
-
* use cases.
|
|
29
|
-
* - Falls back to OPENCLAW_GITHUB_TOKEN, COPILOT_GITHUB_TOKEN,
|
|
30
|
-
* GH_TOKEN, or GITHUB_TOKEN env vars (in that precedence) when
|
|
31
|
-
* no contract-resolved token is given; synthesises a stable,
|
|
32
|
-
* non-reversible pool fingerprint so token rotation busts the
|
|
33
|
-
* client pool cleanly.
|
|
34
|
-
* - Computes a per-agent `copilotHome` default
|
|
35
|
-
* (`<openClawHome>/.openclaw/agents/<agentId>/copilot`, or
|
|
36
|
-
* `<agentDir>/copilot` when an agent directory is supplied) that
|
|
37
|
-
* respects `OPENCLAW_HOME` for the home directory root.
|
|
38
|
-
* - Defaults to `useLoggedInUser` when no token signal is available.
|
|
39
|
-
*
|
|
40
|
-
* Precedence (highest to lowest):
|
|
41
|
-
* 1. `auth.useLoggedInUser === true` (explicit user opt-in)
|
|
42
|
-
* 2. `auth.gitHubToken` (explicit override; requires
|
|
43
|
-
* `profileId` + `profileVersion`)
|
|
44
|
-
* 3. `resolvedApiKey` + `authProfileId` from the contract (core's
|
|
45
|
-
* AuthProfileStore-resolved token — the production main path for
|
|
46
|
-
* a configured `github-copilot` auth profile)
|
|
47
|
-
* 4. OPENCLAW_GITHUB_TOKEN, then COPILOT_GITHUB_TOKEN, then
|
|
48
|
-
* GH_TOKEN, then GITHUB_TOKEN env vars (mirrors the
|
|
49
|
-
* shipped `github-copilot` provider precedence so headless
|
|
50
|
-
* users who already follow the documented
|
|
51
|
-
* COPILOT_GITHUB_TOKEN / GH_TOKEN setup get the token they
|
|
52
|
-
* configured rather than silently falling through to the
|
|
53
|
-
* logged-in CLI user.)
|
|
54
|
-
* 5. `useLoggedInUser` (default)
|
|
55
|
-
*/
|
|
56
13
|
const COPILOT_TOKEN_PROFILE_ERROR = "[copilot-attempt] gitHubToken auth requires profileId+profileVersion (pool keying safety; per Q5/Q1 decisions)";
|
|
57
14
|
const COPILOT_DEFAULT_AGENT_ID = "copilot";
|
|
58
15
|
function createCopilotByokAuth(input) {
|
|
@@ -71,16 +28,6 @@ function createCopilotByokAuth(input) {
|
|
|
71
28
|
authProfileVersion: input.authProfileVersion?.trim() || "byok:unfingerprinted"
|
|
72
29
|
};
|
|
73
30
|
}
|
|
74
|
-
/**
|
|
75
|
-
* Resolve copilot auth + copilotHome.
|
|
76
|
-
*
|
|
77
|
-
* Synchronous because we intentionally do not perform any I/O or
|
|
78
|
-
* cross-package credential lookups here (see file header for rationale).
|
|
79
|
-
*
|
|
80
|
-
* Throws if `gitHubToken` is supplied via `params.auth.gitHubToken`
|
|
81
|
-
* WITHOUT both `profileId` and `profileVersion` (the existing invariant
|
|
82
|
-
* from attempt.ts; preserves pool-key safety per Q5/Q1).
|
|
83
|
-
*/
|
|
84
31
|
function resolveCopilotAuth(input) {
|
|
85
32
|
const env = input.env ?? process.env;
|
|
86
33
|
const homeDir = input.homeDir ?? homedir;
|
|
@@ -88,7 +35,6 @@ function resolveCopilotAuth(input) {
|
|
|
88
35
|
const copilotHome = resolveCopilotHome({
|
|
89
36
|
explicit: readNonEmptyStringPreservingWhitespace(input.copilotHome),
|
|
90
37
|
agentDir: readNonEmptyStringPreservingWhitespace(input.agentDir),
|
|
91
|
-
workspaceDir: readNonEmptyStringPreservingWhitespace(input.workspaceDir),
|
|
92
38
|
agentId,
|
|
93
39
|
env,
|
|
94
40
|
homeDir
|
|
@@ -136,23 +82,9 @@ function resolveCopilotAuth(input) {
|
|
|
136
82
|
agentId
|
|
137
83
|
};
|
|
138
84
|
}
|
|
139
|
-
/**
|
|
140
|
-
* Validate + sanitise an agent id for use in filesystem paths and pool
|
|
141
|
-
* keys.
|
|
142
|
-
*
|
|
143
|
-
* Mirrors the shape constraints documented by core's `normalizeAgentId`
|
|
144
|
-
* / `isValidAgentId` in `src/routing/session-key.ts` (alnum + `-_`,
|
|
145
|
-
* starts with alnum, lowercase, <=64 chars). We re-implement here
|
|
146
|
-
* because the package boundary prevents importing from `src/`. Any
|
|
147
|
-
* caller that passes an invalid id falls back to the shared default
|
|
148
|
-
* (`COPILOT_DEFAULT_AGENT_ID`) rather than throwing - the harness's
|
|
149
|
-
* job is to keep running with a safe default, not to validate config.
|
|
150
|
-
*/
|
|
151
85
|
function sanitizeAgentId(value) {
|
|
152
86
|
const trimmed = (value ?? "").trim().toLowerCase();
|
|
153
|
-
|
|
154
|
-
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(trimmed)) return COPILOT_DEFAULT_AGENT_ID;
|
|
155
|
-
return trimmed;
|
|
87
|
+
return /^[a-z0-9][a-z0-9_-]{0,63}$/.test(trimmed) ? trimmed : COPILOT_DEFAULT_AGENT_ID;
|
|
156
88
|
}
|
|
157
89
|
function resolveCopilotHome(args) {
|
|
158
90
|
if (args.explicit) return resolve(args.explicit);
|
|
@@ -193,14 +125,7 @@ function readEnvTokenFallback(env) {
|
|
|
193
125
|
profileVersion: tokenFingerprint(value)
|
|
194
126
|
};
|
|
195
127
|
}
|
|
196
|
-
/**
|
|
197
|
-
* Non-reversible 12-hex-char fingerprint of a token, prefixed with
|
|
198
|
-
* `sha256:` for forward-compat. Used as the pool-key profileVersion when
|
|
199
|
-
* a token comes from env: rotation -> different fingerprint -> pool
|
|
200
|
-
* entry invalidated cleanly. 48 bits of entropy is sufficient
|
|
201
|
-
* collision resistance for a per-agent client pool; never log the
|
|
202
|
-
* fingerprint alongside an account id.
|
|
203
|
-
*/
|
|
128
|
+
/** Pool invalidation fingerprint; never log it alongside an account id. */
|
|
204
129
|
function tokenFingerprint(token) {
|
|
205
130
|
return `sha256:${createHash("sha256").update(token).digest("hex").slice(0, 12)}`;
|
|
206
131
|
}
|
|
@@ -252,7 +177,10 @@ async function createCopilotByokProxy(resolvedProvider) {
|
|
|
252
177
|
provider: {
|
|
253
178
|
...providerConfig,
|
|
254
179
|
baseUrl: sdkBaseUrl,
|
|
255
|
-
...proxyCredentialHeader ? { headers:
|
|
180
|
+
...proxyCredentialHeader ? { headers: {
|
|
181
|
+
...providerConfig.headers,
|
|
182
|
+
[proxyCredentialHeader]: nonce
|
|
183
|
+
} } : {}
|
|
256
184
|
}
|
|
257
185
|
},
|
|
258
186
|
close: async () => {
|
|
@@ -360,12 +288,6 @@ function normalizeProxyRequestHeaders(headers, proxyCredentialHeader) {
|
|
|
360
288
|
out["accept-encoding"] = "identity";
|
|
361
289
|
return out;
|
|
362
290
|
}
|
|
363
|
-
function buildSdkProviderHeaders(headers, proxyCredentialHeader, proxyCredential) {
|
|
364
|
-
return {
|
|
365
|
-
...headers,
|
|
366
|
-
[proxyCredentialHeader]: proxyCredential
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
291
|
function createProxyCredentialHeaderName(headers) {
|
|
370
292
|
for (;;) {
|
|
371
293
|
const name = `${PROXY_CREDENTIAL_HEADER_PREFIX}${randomBytes(12).toString("hex")}`;
|
|
@@ -417,8 +339,34 @@ function isContentEncodingHeader(key) {
|
|
|
417
339
|
}
|
|
418
340
|
}
|
|
419
341
|
function trimTrailingSlash(pathname) {
|
|
420
|
-
|
|
421
|
-
|
|
342
|
+
return pathname.replace(/\/+$/, "");
|
|
343
|
+
}
|
|
344
|
+
//#endregion
|
|
345
|
+
//#region extensions/copilot/src/history-compaction.ts
|
|
346
|
+
function throwIfAborted(signal) {
|
|
347
|
+
if (!signal?.aborted) return;
|
|
348
|
+
const reason = "reason" in signal ? signal.reason : void 0;
|
|
349
|
+
if (reason instanceof Error) throw reason;
|
|
350
|
+
const error = reason ? new Error("aborted", { cause: reason }) : /* @__PURE__ */ new Error("aborted");
|
|
351
|
+
error.name = "AbortError";
|
|
352
|
+
throw error;
|
|
353
|
+
}
|
|
354
|
+
function isStaleSdkSessionError(error) {
|
|
355
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
356
|
+
return /\b(404|not found|no such session|unknown session|stale|deleted|does not exist)\b/i.test(message);
|
|
357
|
+
}
|
|
358
|
+
function buildCopilotCompactionHookContext(params) {
|
|
359
|
+
return {
|
|
360
|
+
...params.runId ? { runId: params.runId } : {},
|
|
361
|
+
agentId: params.agentId,
|
|
362
|
+
sessionKey: params.sessionKey,
|
|
363
|
+
sessionId: params.sessionId,
|
|
364
|
+
workspaceDir: params.workspaceDir,
|
|
365
|
+
modelProviderId: params.provider,
|
|
366
|
+
modelId: params.model,
|
|
367
|
+
trigger: params.trigger,
|
|
368
|
+
...buildAgentHookContextChannelFields(params)
|
|
369
|
+
};
|
|
422
370
|
}
|
|
423
371
|
//#endregion
|
|
424
372
|
//#region extensions/copilot/src/provider-bridge.ts
|
|
@@ -465,7 +413,7 @@ function resolveCopilotProvider(params) {
|
|
|
465
413
|
if (params.model.provider.trim().toLowerCase() === "github-copilot") return { mode: "github-copilot" };
|
|
466
414
|
const baseUrl = normalizeOptionalString(params.model.baseUrl);
|
|
467
415
|
if (!baseUrl) throw new Error(COPILOT_BYOK_PROVIDER_ERROR);
|
|
468
|
-
|
|
416
|
+
assertByokEndpointHostAllowed(baseUrl);
|
|
469
417
|
if (hasUnsupportedTransportPolicy(params.model)) throw new Error(COPILOT_BYOK_TRANSPORT_POLICY_ERROR);
|
|
470
418
|
const api = normalizeOptionalString(params.model.api)?.toLowerCase() ?? "openai-responses";
|
|
471
419
|
const provider = resolveProviderType(api, baseUrl, params.model.azureApiVersion);
|
|
@@ -506,10 +454,11 @@ function isCopilotByokUnsupportedProviderError(error) {
|
|
|
506
454
|
return error instanceof Error && (error.message === COPILOT_BYOK_PROVIDER_ERROR || error.message === COPILOT_BYOK_TRANSPORT_POLICY_ERROR || error.message === COPILOT_BYOK_ENDPOINT_POLICY_ERROR);
|
|
507
455
|
}
|
|
508
456
|
function supportsCopilotByokProviderShape(model) {
|
|
509
|
-
|
|
457
|
+
const baseUrl = normalizeOptionalString(model.baseUrl);
|
|
458
|
+
if (!baseUrl || hasUnsupportedTransportPolicy(model)) return false;
|
|
510
459
|
try {
|
|
511
|
-
resolveProviderType(normalizeOptionalString(model.api)?.toLowerCase() ?? "openai-responses",
|
|
512
|
-
assertByokEndpointHostAllowed(
|
|
460
|
+
resolveProviderType(normalizeOptionalString(model.api)?.toLowerCase() ?? "openai-responses", baseUrl, void 0);
|
|
461
|
+
assertByokEndpointHostAllowed(baseUrl);
|
|
513
462
|
return true;
|
|
514
463
|
} catch {
|
|
515
464
|
return false;
|
|
@@ -539,9 +488,6 @@ function normalizeCredentialQueryParamName(name) {
|
|
|
539
488
|
return stripped.toLowerCase().replace(/[-_]/g, "");
|
|
540
489
|
}
|
|
541
490
|
}
|
|
542
|
-
function assertByokEndpointAllowed(baseUrl) {
|
|
543
|
-
assertByokEndpointHostAllowed(baseUrl);
|
|
544
|
-
}
|
|
545
491
|
function resolveProviderType(api, baseUrl, azureApiVersion) {
|
|
546
492
|
switch (api) {
|
|
547
493
|
case "anthropic-messages": return {
|
|
@@ -619,7 +565,7 @@ function sessionAuthFields(auth) {
|
|
|
619
565
|
function sessionAuthMatches(stored, current) {
|
|
620
566
|
if (stored.authMode !== current.authMode) return false;
|
|
621
567
|
if (stored.authMode === "useLoggedInUser") return true;
|
|
622
|
-
return
|
|
568
|
+
return stored.authProfileId === current.authProfileId && stored.authProfileVersion === current.authProfileVersion;
|
|
623
569
|
}
|
|
624
570
|
function normalizeBinding(value) {
|
|
625
571
|
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;
|
|
@@ -676,19 +622,8 @@ async function deleteStoredBinding(store, key) {
|
|
|
676
622
|
return false;
|
|
677
623
|
}
|
|
678
624
|
}
|
|
679
|
-
function throwIfAborted(signal) {
|
|
680
|
-
if (!signal?.aborted) return;
|
|
681
|
-
const reason = "reason" in signal ? signal.reason : void 0;
|
|
682
|
-
if (reason instanceof Error) throw reason;
|
|
683
|
-
const error = reason ? new Error("aborted", { cause: reason }) : /* @__PURE__ */ new Error("aborted");
|
|
684
|
-
error.name = "AbortError";
|
|
685
|
-
throw error;
|
|
686
|
-
}
|
|
687
|
-
function isStaleSdkSessionError(error) {
|
|
688
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
689
|
-
return /\b(404|not found|no such session|unknown session|stale|deleted|does not exist)\b/i.test(message);
|
|
690
|
-
}
|
|
691
625
|
async function compactTrackedSdkSession(params) {
|
|
626
|
+
params.assertCurrent();
|
|
692
627
|
throwIfAborted(params.abortSignal);
|
|
693
628
|
const session = await params.client.resumeSession(params.sdkSessionId, {
|
|
694
629
|
...params.sessionConfig,
|
|
@@ -699,6 +634,7 @@ async function compactTrackedSdkSession(params) {
|
|
|
699
634
|
params.onSession?.(session);
|
|
700
635
|
const request = params.customInstructions?.trim() ? { customInstructions: params.customInstructions } : void 0;
|
|
701
636
|
try {
|
|
637
|
+
params.assertCurrent();
|
|
702
638
|
throwIfAborted(params.abortSignal);
|
|
703
639
|
return await session.rpc.history.compact(request);
|
|
704
640
|
} finally {
|
|
@@ -827,19 +763,6 @@ function computeCompactRequestKey(params) {
|
|
|
827
763
|
includeAuth: false
|
|
828
764
|
});
|
|
829
765
|
}
|
|
830
|
-
function buildCopilotCompactionHookContext(params) {
|
|
831
|
-
return {
|
|
832
|
-
...params.runId ? { runId: params.runId } : {},
|
|
833
|
-
agentId: params.agentId,
|
|
834
|
-
sessionKey: params.sessionKey,
|
|
835
|
-
sessionId: params.sessionId,
|
|
836
|
-
workspaceDir: params.workspaceDir,
|
|
837
|
-
modelProviderId: params.provider,
|
|
838
|
-
modelId: params.model,
|
|
839
|
-
trigger: params.trigger,
|
|
840
|
-
...buildAgentHookContextChannelFields(params)
|
|
841
|
-
};
|
|
842
|
-
}
|
|
843
766
|
function createCopilotAgentHarness(options) {
|
|
844
767
|
let poolPromise;
|
|
845
768
|
let createdPool;
|
|
@@ -862,7 +785,7 @@ function createCopilotAgentHarness(options) {
|
|
|
862
785
|
async function getPool() {
|
|
863
786
|
if (options?.pool) return options.pool;
|
|
864
787
|
if (!poolPromise) poolPromise = (async () => {
|
|
865
|
-
const { createCopilotClientPool } = await import("./runtime-
|
|
788
|
+
const { createCopilotClientPool } = await import("./runtime-CWI9o_Vc.mjs");
|
|
866
789
|
createdPool = createCopilotClientPool(options?.poolOptions);
|
|
867
790
|
return createdPool;
|
|
868
791
|
})();
|
|
@@ -897,9 +820,9 @@ function createCopilotAgentHarness(options) {
|
|
|
897
820
|
await Promise.allSettled(pending.map(([cleanup]) => cleanup));
|
|
898
821
|
}
|
|
899
822
|
async function runHarnessAttempt(params, operation) {
|
|
900
|
-
|
|
823
|
+
return trackOperation(async () => {
|
|
901
824
|
if (disposed) throw new Error("[copilot] harness has been disposed; cannot start new attempts");
|
|
902
|
-
const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-
|
|
825
|
+
const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-CRiSJYXq.mjs");
|
|
903
826
|
if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
|
|
904
827
|
const pool = await getPool();
|
|
905
828
|
if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
|
|
@@ -939,11 +862,8 @@ function createCopilotAgentHarness(options) {
|
|
|
939
862
|
onToolResult: void 0,
|
|
940
863
|
onToolStreamBoundary: void 0
|
|
941
864
|
} : {},
|
|
942
|
-
initialReplayState:
|
|
943
|
-
...
|
|
944
|
-
sdkSessionId: resumableSessionId
|
|
945
|
-
} : {
|
|
946
|
-
...params.initialReplayState,
|
|
865
|
+
initialReplayState: {
|
|
866
|
+
...operation === "attempt" ? params.initialReplayState : void 0,
|
|
947
867
|
...resumableBinding?.journalVersion === 1 ? { journalValidated: true } : {},
|
|
948
868
|
sdkSessionId: resumableSessionId
|
|
949
869
|
}
|
|
@@ -1025,31 +945,19 @@ function createCopilotAgentHarness(options) {
|
|
|
1025
945
|
});
|
|
1026
946
|
}
|
|
1027
947
|
return result;
|
|
1028
|
-
})
|
|
1029
|
-
inFlight.add(attemptPromise);
|
|
1030
|
-
try {
|
|
1031
|
-
return await attemptPromise;
|
|
1032
|
-
} finally {
|
|
1033
|
-
inFlight.delete(attemptPromise);
|
|
1034
|
-
}
|
|
948
|
+
});
|
|
1035
949
|
}
|
|
1036
950
|
async function runIsolatedCompletionV2(params) {
|
|
1037
|
-
|
|
951
|
+
return trackOperation(async () => {
|
|
1038
952
|
if (disposed) throw new Error("[copilot] harness has been disposed; cannot start isolated completion");
|
|
1039
|
-
const { runCopilotIsolatedCompletion } = await import("./isolated-completion-
|
|
953
|
+
const { runCopilotIsolatedCompletion } = await import("./isolated-completion-ClBsnNg8.mjs");
|
|
1040
954
|
if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
|
|
1041
955
|
return await runCopilotIsolatedCompletion(params, async () => {
|
|
1042
956
|
const pool = await getPool();
|
|
1043
957
|
if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
|
|
1044
958
|
return pool;
|
|
1045
959
|
});
|
|
1046
|
-
})
|
|
1047
|
-
inFlight.add(completionPromise);
|
|
1048
|
-
try {
|
|
1049
|
-
return await completionPromise;
|
|
1050
|
-
} finally {
|
|
1051
|
-
inFlight.delete(completionPromise);
|
|
1052
|
-
}
|
|
960
|
+
});
|
|
1053
961
|
}
|
|
1054
962
|
return {
|
|
1055
963
|
id: options?.id ?? "copilot",
|
|
@@ -1123,6 +1031,9 @@ function createCopilotAgentHarness(options) {
|
|
|
1123
1031
|
}),
|
|
1124
1032
|
compact: (params) => trackOperation(async () => {
|
|
1125
1033
|
if (disposed) return;
|
|
1034
|
+
const hostCapabilities = params.hostCapabilities;
|
|
1035
|
+
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.");
|
|
1036
|
+
hostCapabilities.assertActive();
|
|
1126
1037
|
const openclawSessionId = typeof params.sessionId === "string" ? params.sessionId : void 0;
|
|
1127
1038
|
if (!openclawSessionId) return {
|
|
1128
1039
|
ok: false,
|
|
@@ -1137,9 +1048,8 @@ function createCopilotAgentHarness(options) {
|
|
|
1137
1048
|
};
|
|
1138
1049
|
const tracked = trackedSessions.get(openclawSessionId);
|
|
1139
1050
|
const currentCompactKey = computeCompactRequestKey(params);
|
|
1140
|
-
const { resolvePoolAcquire } = await import("./attempt-
|
|
1051
|
+
const { resolvePoolAcquire } = await import("./attempt-CRiSJYXq.mjs");
|
|
1141
1052
|
let resolvedPoolAcquire;
|
|
1142
|
-
let currentAuth;
|
|
1143
1053
|
try {
|
|
1144
1054
|
resolvedPoolAcquire = resolvePoolAcquire(params);
|
|
1145
1055
|
} catch (error) {
|
|
@@ -1151,7 +1061,7 @@ function createCopilotAgentHarness(options) {
|
|
|
1151
1061
|
};
|
|
1152
1062
|
throw error;
|
|
1153
1063
|
}
|
|
1154
|
-
|
|
1064
|
+
const currentAuth = sessionAuthFields(resolvedPoolAcquire.auth);
|
|
1155
1065
|
const compatibleTracked = tracked?.compactKey === currentCompactKey && sessionAuthMatches(tracked, currentAuth) ? tracked : void 0;
|
|
1156
1066
|
if (!compatibleTracked) return {
|
|
1157
1067
|
ok: false,
|
|
@@ -1187,8 +1097,10 @@ function createCopilotAgentHarness(options) {
|
|
|
1187
1097
|
sessionFile: params.sessionFile,
|
|
1188
1098
|
ctx: hookContext
|
|
1189
1099
|
});
|
|
1100
|
+
hostCapabilities.assertActive();
|
|
1190
1101
|
compactResult = await compactWithSafetyTimeout((abortSignal) => compactTrackedSdkSession({
|
|
1191
1102
|
abortSignal,
|
|
1103
|
+
assertCurrent: hostCapabilities.assertActive,
|
|
1192
1104
|
client,
|
|
1193
1105
|
customInstructions: params.customInstructions,
|
|
1194
1106
|
gitHubToken: compatibleTracked?.clientOptions.gitHubToken ?? (resolvedPoolAcquire?.auth.authMode === "gitHubToken" ? resolvedPoolAcquire.auth.gitHubToken : void 0),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as resolveCopilotProvider, o as tokenFingerprint, r as createCopilotByokProxy } from "./harness-
|
|
1
|
+
import { n as resolveCopilotProvider, o as tokenFingerprint, r as createCopilotByokProxy } from "./harness-BAWs53-w.mjs";
|
|
2
2
|
import { r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.mjs";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
//#region extensions/copilot/src/isolated-completion.ts
|
|
@@ -5,7 +5,7 @@ import { existsSync } from "node:fs";
|
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
6
|
import { resolveStateDir } from "openclaw/plugin-sdk/state-paths";
|
|
7
7
|
//#region extensions/copilot/package.json
|
|
8
|
-
var dependencies = { "@github/copilot-sdk": "1.0.
|
|
8
|
+
var dependencies = { "@github/copilot-sdk": "1.0.14" };
|
|
9
9
|
//#endregion
|
|
10
10
|
//#region extensions/copilot/src/sdk-loader.ts
|
|
11
11
|
function resolveCopilotSdkFallbackDir(env = process.env) {
|
|
@@ -90,7 +90,6 @@ function createCopilotClientPool(options = {}) {
|
|
|
90
90
|
return new (await (loadCopilotSdk())).CopilotClient(clientOptions);
|
|
91
91
|
});
|
|
92
92
|
const idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
|
|
93
|
-
const now = options.now ?? Date.now;
|
|
94
93
|
const entries = /* @__PURE__ */ new Map();
|
|
95
94
|
const releasedHandles = /* @__PURE__ */ new WeakSet();
|
|
96
95
|
let disposed = false;
|
|
@@ -102,11 +101,6 @@ function createCopilotClientPool(options = {}) {
|
|
|
102
101
|
};
|
|
103
102
|
const stopReadyOrIdleEntry = (entry, client, idleTimer) => {
|
|
104
103
|
if (idleTimer) clearTimeout(idleTimer);
|
|
105
|
-
if (entry.stopRan) {
|
|
106
|
-
if (entry.state.kind === "stopping") return entry.state.promise;
|
|
107
|
-
if (entry.state.kind === "stopped") return Promise.resolve([]);
|
|
108
|
-
}
|
|
109
|
-
entry.stopRan = true;
|
|
110
104
|
const stopPromise = (async () => {
|
|
111
105
|
try {
|
|
112
106
|
return await client.stop();
|
|
@@ -147,22 +141,11 @@ function createCopilotClientPool(options = {}) {
|
|
|
147
141
|
client,
|
|
148
142
|
idleTimer: setTimeout(() => {
|
|
149
143
|
stopEntry(entry);
|
|
150
|
-
}, idleTtlMs)
|
|
151
|
-
idleSinceMs: now()
|
|
144
|
+
}, idleTtlMs)
|
|
152
145
|
};
|
|
153
146
|
};
|
|
154
147
|
const createEntry = (key, cacheKey, clientOptions) => {
|
|
155
|
-
const
|
|
156
|
-
key,
|
|
157
|
-
cacheKey,
|
|
158
|
-
refCount: 1,
|
|
159
|
-
stopRan: false,
|
|
160
|
-
state: {
|
|
161
|
-
kind: "creating",
|
|
162
|
-
promise: Promise.resolve(void 0)
|
|
163
|
-
}
|
|
164
|
-
};
|
|
165
|
-
const createPromise = (async () => {
|
|
148
|
+
const createPromise = Promise.resolve().then(async () => {
|
|
166
149
|
try {
|
|
167
150
|
const client = await sdkFactory(clientOptions);
|
|
168
151
|
entry.state = {
|
|
@@ -175,10 +158,15 @@ function createCopilotClientPool(options = {}) {
|
|
|
175
158
|
maybeDeleteEntry(entry);
|
|
176
159
|
throw toStringifiedError(error);
|
|
177
160
|
}
|
|
178
|
-
})
|
|
179
|
-
entry
|
|
180
|
-
|
|
181
|
-
|
|
161
|
+
});
|
|
162
|
+
const entry = {
|
|
163
|
+
key,
|
|
164
|
+
cacheKey,
|
|
165
|
+
refCount: 1,
|
|
166
|
+
state: {
|
|
167
|
+
kind: "creating",
|
|
168
|
+
promise: createPromise
|
|
169
|
+
}
|
|
182
170
|
};
|
|
183
171
|
entries.set(cacheKey, entry);
|
|
184
172
|
return {
|
|
@@ -195,36 +183,29 @@ function createCopilotClientPool(options = {}) {
|
|
|
195
183
|
const existing = entries.get(cacheKey);
|
|
196
184
|
if (!existing) {
|
|
197
185
|
const created = createEntry(key, cacheKey, clientOptions);
|
|
198
|
-
|
|
199
|
-
|
|
186
|
+
const client = await created.createPromise;
|
|
187
|
+
if (disposed) {
|
|
188
|
+
await stopEntry(created.entry);
|
|
189
|
+
throw createDisposedError();
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
key: created.entry.key,
|
|
193
|
+
client
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
switch (existing.state.kind) {
|
|
197
|
+
case "creating": {
|
|
198
|
+
existing.refCount += 1;
|
|
199
|
+
const client = await existing.state.promise;
|
|
200
200
|
if (disposed) {
|
|
201
|
-
await stopEntry(
|
|
201
|
+
await stopEntry(existing);
|
|
202
202
|
throw createDisposedError();
|
|
203
203
|
}
|
|
204
204
|
return {
|
|
205
|
-
key:
|
|
205
|
+
key: existing.key,
|
|
206
206
|
client
|
|
207
207
|
};
|
|
208
|
-
} catch (error) {
|
|
209
|
-
throw toStringifiedError(error);
|
|
210
208
|
}
|
|
211
|
-
}
|
|
212
|
-
switch (existing.state.kind) {
|
|
213
|
-
case "creating":
|
|
214
|
-
existing.refCount += 1;
|
|
215
|
-
try {
|
|
216
|
-
const client = await existing.state.promise;
|
|
217
|
-
if (disposed) {
|
|
218
|
-
await stopEntry(existing);
|
|
219
|
-
throw createDisposedError();
|
|
220
|
-
}
|
|
221
|
-
return {
|
|
222
|
-
key: existing.key,
|
|
223
|
-
client
|
|
224
|
-
};
|
|
225
|
-
} catch (error) {
|
|
226
|
-
throw toStringifiedError(error);
|
|
227
|
-
}
|
|
228
209
|
case "ready":
|
|
229
210
|
existing.refCount += 1;
|
|
230
211
|
return {
|
package/dist/harness.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createCopilotAgentHarness } from "./.setup/harness-
|
|
1
|
+
import { t as createCopilotAgentHarness } from "./.setup/harness-BAWs53-w.mjs";
|
|
2
2
|
export { createCopilotAgentHarness };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as createCopilotAgentHarness } from "./.setup/harness-
|
|
1
|
+
import { t as createCopilotAgentHarness } from "./.setup/harness-BAWs53-w.mjs";
|
|
2
2
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
3
3
|
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
4
4
|
//#region extensions/copilot/index.ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openclaw/copilot",
|
|
3
|
-
"version": "2026.9.
|
|
3
|
+
"version": "2026.9.8",
|
|
4
4
|
"description": "OpenClaw GitHub Copilot agent runtime plugin (registers a `github-copilot` AgentHarness backed by @github/copilot-sdk over JSON-RPC to the GitHub Copilot CLI)",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"type": "module",
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@github/copilot-sdk": "1.0.
|
|
11
|
+
"@github/copilot-sdk": "1.0.14"
|
|
12
12
|
},
|
|
13
13
|
"devDependencies": {
|
|
14
14
|
"@openclaw/plugin-sdk": "workspace:*"
|
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
"minHostVersion": ">=2026.5.28"
|
|
25
25
|
},
|
|
26
26
|
"compat": {
|
|
27
|
-
"pluginApi": ">=2026.9.
|
|
27
|
+
"pluginApi": ">=2026.9.8"
|
|
28
28
|
},
|
|
29
29
|
"build": {
|
|
30
|
-
"openclawVersion": "2026.9.
|
|
30
|
+
"openclawVersion": "2026.9.8",
|
|
31
31
|
"bundledDist": false
|
|
32
32
|
},
|
|
33
33
|
"release": {
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"assets/activity.svg"
|
|
48
48
|
],
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"openclaw": ">=2026.9.
|
|
50
|
+
"openclaw": ">=2026.9.8"
|
|
51
51
|
},
|
|
52
52
|
"peerDependenciesMeta": {
|
|
53
53
|
"openclaw": {
|