@openclaw/copilot 2026.10.10 → 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.
- package/README.md +18 -0
- package/dist/.setup/{attempt-CEEb21Ox.mjs → attempt-BdJgfQV3.mjs} +452 -627
- package/dist/.setup/{harness-DgLcZThQ.mjs → harness-Djqx8viF.mjs} +184 -270
- package/dist/.setup/{isolated-completion-mqRIO1Uo.mjs → isolated-completion-Dp_YaEKF.mjs} +20 -40
- package/dist/.setup/runtime-CAM77uEc.mjs +152 -0
- package/dist/.setup/runtime-artifact-D42RfCpG.mjs +55 -0
- package/dist/.setup/sdk-loader-BXVlNPFC.mjs +144 -0
- package/dist/.setup/session-restrictions-BrC08l2U.mjs +223 -0
- package/dist/.source-module-urls/f7f35489a89dbc0fc6d0e80a0da5720af5de227b511e490a2415ffe55b1bc471.json +1 -1
- package/dist/harness.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +5 -5
- package/dist/.setup/runtime-DO5cz1WW.mjs +0 -216
- package/dist/.setup/usage-bridge-B9LRA1-s.mjs +0 -74
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import { a as createCopilotByokProxy, i as createPromptError, n as resolveCopilotProvider, o as createCopilotByokAuth, s as resolveCopilotAuth } from "./harness-
|
|
2
|
-
import { n as
|
|
3
|
-
import {
|
|
1
|
+
import { a as createCopilotByokProxy, i as createPromptError, n as resolveCopilotProvider, o as createCopilotByokAuth, s as resolveCopilotAuth } from "./harness-Djqx8viF.mjs";
|
|
2
|
+
import { a as projectSdkUserMetadata, c as resolveEventTimestamp, i as hasOwnKeys, l as sanitizeToolDetailText, n as buildAssistantMessage, o as projectToolResultDetails, r as buildAssistantProjectionGroup, s as resolveAssistantUsage, t as createCopilotIsolatedSessionRestrictions, u as normalizeCopilotUsage } from "./session-restrictions-BrC08l2U.mjs";
|
|
3
|
+
import { asOptionalObjectRecord, asOptionalRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
4
4
|
import { SKILL_WORKSHOP_TOOL_NAME, applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHookContextChannelFields, buildCredentialSafetyPrompt, buildDelegationGuidanceSection, buildEmbeddedAttemptToolRunContext, buildEmbeddedForegroundPromptContext, buildHarnessVisibleReplyGuidance, buildSkillWorkshopPromptSection, cancelPendingAgentQuestionForSession, claimPendingAgentQuestionAnswer, clearActiveEmbeddedRun, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, emitAgentEvent, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, getPluginToolSideEffectOwnerKey, isHostScopedAgentToolActive, isSubagentSessionKey, isToolResultError, projectAgentHarnessTranscriptMessageForDisplay, projectAgentToolActivity, resolveAgentDir, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveMainSessionDelegationMode, resolveModelAuthModeAsync, resolveSandboxContext, resolveUserPath, restorePreparedUserTurnOperationalMetaForRuntime, runAgentEndSideEffectsAsync, runAgentHarnessAfterCompactionHook, runAgentHarnessAfterToolCallHook, runAgentHarnessBeforeCompactionHook, runAgentHarnessBeforeMessageWriteHook, runAgentHarnessGatewayQuestion, runAgentHarnessLlmInputHook, runAgentHarnessLlmOutputHook, sanitizeToolResult, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { raceWithTimeout, withTimeout } from "openclaw/plugin-sdk/time-runtime";
|
|
7
7
|
import { formatErrorMessage, toErrorObject, toStringifiedError, toStringifiedError as toCopilotError } from "openclaw/plugin-sdk/error-runtime";
|
|
8
8
|
import { createDeferred } from "openclaw/plugin-sdk/concurrency-runtime";
|
|
9
|
-
import { parseDateStringTimestampMs } from "openclaw/plugin-sdk/number-runtime";
|
|
10
9
|
import { createAgentHarnessToolSurfaceRuntimeAsync, normalizeAcceptedSessionSpawnResult } from "openclaw/plugin-sdk/agent-harness-tool-runtime";
|
|
11
10
|
import fsp from "node:fs/promises";
|
|
12
11
|
import { resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
|
|
13
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
14
13
|
import { convertMcpCallToolResult } from "@github/copilot-sdk";
|
|
15
14
|
import { textResult } from "openclaw/plugin-sdk/tool-results";
|
|
15
|
+
import { escapeChatDisplayText, sanitizeChatDisplayText } from "openclaw/plugin-sdk/string-normalization-runtime";
|
|
16
16
|
import { isDeepStrictEqual } from "node:util";
|
|
17
17
|
import { createDeferred as createDeferred$1 } from "openclaw/plugin-sdk/extension-shared";
|
|
18
|
-
import { appendSessionTranscriptMessageByIdentityStrict, appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity,
|
|
18
|
+
import { appendSessionTranscriptMessageByIdentityStrict, appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity, withSessionTranscriptWrite } from "openclaw/plugin-sdk/session-transcript-runtime";
|
|
19
19
|
// extensions/copilot/src/attempt-types.ts
|
|
20
20
|
const BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS = 5e3;
|
|
21
21
|
const COPILOT_ASK_USER_AVAILABLE_TOOLS = ["builtin:ask_user"];
|
|
@@ -36,99 +36,6 @@ function withPromptFailure(terminal, error) {
|
|
|
36
36
|
function assertCopilotAttemptHostCapabilities(params) {
|
|
37
37
|
if (!params.hostCapabilities) throw new Error("[copilot-attempt] ordinary attempts require host capabilities");
|
|
38
38
|
}
|
|
39
|
-
// extensions/copilot/src/hooks-bridge.ts
|
|
40
|
-
const DEFAULT_HOOK_ERROR_HANDLER = ({ hookName, error }) => {
|
|
41
|
-
console.warn(`[copilot hooks-bridge] ${hookName} handler threw:`, error);
|
|
42
|
-
};
|
|
43
|
-
/**
|
|
44
|
-
* Wrap a native handler so it cannot throw into the SDK. Returning undefined
|
|
45
|
-
* leaves the SDK's default decision in place.
|
|
46
|
-
*/
|
|
47
|
-
function isolate(hookName, handler, onError) {
|
|
48
|
-
if (!handler) return;
|
|
49
|
-
return async (...args) => {
|
|
50
|
-
try {
|
|
51
|
-
return await handler(...args);
|
|
52
|
-
} catch (error) {
|
|
53
|
-
try {
|
|
54
|
-
onError({
|
|
55
|
-
hookName,
|
|
56
|
-
error
|
|
57
|
-
});
|
|
58
|
-
} catch {}
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Build an SDK-shaped hook object from native per-attempt configuration.
|
|
65
|
-
* Omit the SDK hook subsystem when no handlers were configured.
|
|
66
|
-
*/
|
|
67
|
-
function createHooksBridge(config, options) {
|
|
68
|
-
if (!config) return;
|
|
69
|
-
const onError = config.onHookError ?? DEFAULT_HOOK_ERROR_HANDLER;
|
|
70
|
-
const hooks = {};
|
|
71
|
-
const pre = isolate("onPreToolUse", config.onPreToolUse, onError);
|
|
72
|
-
const preMcp = isolate("onPreMcpToolCall", config.onPreMcpToolCall, onError);
|
|
73
|
-
const post = isolate("onPostToolUse", config.onPostToolUse, onError);
|
|
74
|
-
const postFailure = isolate("onPostToolUseFailure", config.onPostToolUseFailure, onError);
|
|
75
|
-
const userPrompt = isolate("onUserPromptSubmitted", config.onUserPromptSubmitted, onError);
|
|
76
|
-
const sessionStart = isolate("onSessionStart", config.onSessionStart, onError);
|
|
77
|
-
const sessionEnd = isolate("onSessionEnd", config.onSessionEnd, onError);
|
|
78
|
-
const errorOccurred = isolate("onErrorOccurred", config.onErrorOccurred, onError);
|
|
79
|
-
if (pre) hooks.onPreToolUse = pre;
|
|
80
|
-
if (preMcp) hooks.onPreMcpToolCall = preMcp;
|
|
81
|
-
if (post) hooks.onPostToolUse = post;
|
|
82
|
-
if (postFailure) hooks.onPostToolUseFailure = postFailure;
|
|
83
|
-
if (userPrompt) hooks.onUserPromptSubmitted = async (input, invocation) => {
|
|
84
|
-
const output = await userPrompt(input, invocation);
|
|
85
|
-
try {
|
|
86
|
-
options?.onUserPromptSubmitted?.({
|
|
87
|
-
prompt: output?.modifiedPrompt ?? input.prompt,
|
|
88
|
-
...output?.additionalContext ? { additionalContext: output.additionalContext } : {}
|
|
89
|
-
});
|
|
90
|
-
} catch (error) {
|
|
91
|
-
try {
|
|
92
|
-
onError({
|
|
93
|
-
hookName: "onUserPromptSubmitted",
|
|
94
|
-
error
|
|
95
|
-
});
|
|
96
|
-
} catch {}
|
|
97
|
-
}
|
|
98
|
-
return output;
|
|
99
|
-
};
|
|
100
|
-
if (sessionStart) hooks.onSessionStart = sessionStart;
|
|
101
|
-
if (sessionEnd) hooks.onSessionEnd = sessionEnd;
|
|
102
|
-
if (errorOccurred) hooks.onErrorOccurred = errorOccurred;
|
|
103
|
-
return Object.keys(hooks).length > 0 ? hooks : void 0;
|
|
104
|
-
}
|
|
105
|
-
// extensions/copilot/src/permission-bridge.ts
|
|
106
|
-
const REJECT_ALL_FEEDBACK = "copilot agent runtime: no permission policy installed (denied by default)";
|
|
107
|
-
const rejectAllPolicy = () => ({
|
|
108
|
-
kind: "reject",
|
|
109
|
-
feedback: REJECT_ALL_FEEDBACK
|
|
110
|
-
});
|
|
111
|
-
function createPermissionBridge(policy = rejectAllPolicy) {
|
|
112
|
-
return async (request, invocation) => {
|
|
113
|
-
const ctx = {
|
|
114
|
-
request,
|
|
115
|
-
sessionId: invocation.sessionId
|
|
116
|
-
};
|
|
117
|
-
try {
|
|
118
|
-
const result = await policy(ctx);
|
|
119
|
-
if (result !== void 0) return result;
|
|
120
|
-
} catch (error) {
|
|
121
|
-
return {
|
|
122
|
-
kind: "reject",
|
|
123
|
-
feedback: `copilot permission policy threw: ${formatErrorMessage(error)}`
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
return {
|
|
127
|
-
kind: "reject",
|
|
128
|
-
feedback: REJECT_ALL_FEEDBACK
|
|
129
|
-
};
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
39
|
// extensions/copilot/src/replay-shim.ts
|
|
133
40
|
const MISSING_SESSION_CODES = /* @__PURE__ */ new Set([
|
|
134
41
|
"SESSION_NOT_FOUND",
|
|
@@ -217,6 +124,7 @@ function createResult(params, state) {
|
|
|
217
124
|
} : { kind: "ok" };
|
|
218
125
|
return {
|
|
219
126
|
terminal: promptError !== void 0 ? withPromptFailure(interruption, promptError) : interruption,
|
|
127
|
+
...state.runtimeArtifact ? { runtimeArtifact: state.runtimeArtifact } : {},
|
|
220
128
|
...state.acceptedSessionSpawns?.length ? { acceptedSessionSpawns: state.acceptedSessionSpawns } : {},
|
|
221
129
|
...state.assistantTranscriptOwned ? {
|
|
222
130
|
assistantTranscriptOwned: true,
|
|
@@ -251,79 +159,42 @@ function createResult(params, state) {
|
|
|
251
159
|
...state.yieldAcknowledgment ? { yieldAcknowledgment: state.yieldAcknowledgment } : {}
|
|
252
160
|
};
|
|
253
161
|
}
|
|
254
|
-
function createSessionConfig(params, sdkModelId, sdkTools, resolvedAuth, resolvedProvider, systemMessageContent, effectiveWorkspaceDir, effectiveCwd, onUserInputRequest, options) {
|
|
255
|
-
const settledToolFinalization = options.operation === "settled-tool-finalization";
|
|
256
|
-
const permissionPolicy = settledToolFinalization ? rejectAllPolicy : params.permissionPolicy ?? rejectAllPolicy;
|
|
257
|
-
const hooks = settledToolFinalization ? void 0 : createHooksBridge(params.hooksConfig, options.hooksBridgeOptions);
|
|
258
|
-
return {
|
|
259
|
-
model: sdkModelId,
|
|
260
|
-
onPermissionRequest: createPermissionBridge(permissionPolicy),
|
|
261
|
-
...onUserInputRequest ? { onUserInputRequest } : {},
|
|
262
|
-
...resolvedProvider.provider ? { provider: resolvedProvider.provider } : {},
|
|
263
|
-
...hooks ? { hooks } : {},
|
|
264
|
-
...typeof params.enableSessionTelemetry === "boolean" ? { enableSessionTelemetry: params.enableSessionTelemetry } : {},
|
|
265
|
-
...settledToolFinalization ? {} : params.infiniteSessionConfig ? { infiniteSessions: params.infiniteSessionConfig } : {},
|
|
266
|
-
reasoningEffort: params.reasoningEffort,
|
|
267
|
-
tools: sdkTools,
|
|
268
|
-
availableTools: buildCopilotAvailableTools(sdkTools, options.includeAskUser),
|
|
269
|
-
...settledToolFinalization ? createCopilotIsolatedSessionRestrictions() : {},
|
|
270
|
-
workingDirectory: effectiveCwd ?? effectiveWorkspaceDir ?? readResolvedAttemptPath(params.workspaceDir),
|
|
271
|
-
...!settledToolFinalization && effectiveWorkspaceDir && effectiveCwd && effectiveCwd !== effectiveWorkspaceDir ? { instructionDirectories: [effectiveWorkspaceDir] } : {},
|
|
272
|
-
...resolvedAuth.authMode === "gitHubToken" && resolvedAuth.gitHubToken ? { gitHubToken: resolvedAuth.gitHubToken } : {},
|
|
273
|
-
...settledToolFinalization ? { systemMessage: {
|
|
274
|
-
mode: "customize",
|
|
275
|
-
content: COPILOT_SETTLED_FINALIZATION_SYSTEM_MESSAGE
|
|
276
|
-
} } : systemMessageContent ? { systemMessage: {
|
|
277
|
-
mode: "append",
|
|
278
|
-
content: systemMessageContent
|
|
279
|
-
} } : {}
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
function buildCopilotAvailableTools(sdkTools, includeAskUser) {
|
|
283
|
-
const availableTools = sdkTools.map((tool) => tool.name);
|
|
284
|
-
if (includeAskUser) availableTools.push(...COPILOT_ASK_USER_AVAILABLE_TOOLS);
|
|
285
|
-
return [...new Set(availableTools)];
|
|
286
|
-
}
|
|
287
162
|
async function createMessageOptions(params, context) {
|
|
288
|
-
|
|
163
|
+
async function resolvePromptImages() {
|
|
164
|
+
const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
|
|
165
|
+
if (!workspaceDir) return [];
|
|
166
|
+
const localRoots = context.workspaceOnly && context.effectiveWorkspaceDir ? [context.effectiveWorkspaceDir] : void 0;
|
|
167
|
+
const model = params.model;
|
|
168
|
+
return (await detectAndLoadAgentHarnessPromptImages({
|
|
169
|
+
prompt: params.prompt,
|
|
170
|
+
workspaceDir,
|
|
171
|
+
model: { input: typeof model === "object" ? model.input ?? ["image"] : ["image"] },
|
|
172
|
+
existingImages: params.images,
|
|
173
|
+
imageOrder: params.imageOrder,
|
|
174
|
+
media: params.media,
|
|
175
|
+
config: params.config,
|
|
176
|
+
workspaceOnly: context.workspaceOnly,
|
|
177
|
+
localRoots,
|
|
178
|
+
sandbox: context.sandbox?.enabled && context.sandbox.fsBridge ? {
|
|
179
|
+
root: context.sandbox.workspaceDir,
|
|
180
|
+
bridge: context.sandbox.fsBridge
|
|
181
|
+
} : void 0
|
|
182
|
+
})).images;
|
|
183
|
+
}
|
|
184
|
+
const attachments = (await resolvePromptImages()).map((image, index) => ({
|
|
289
185
|
type: "blob",
|
|
290
186
|
data: image.data,
|
|
291
187
|
mimeType: image.mimeType,
|
|
292
188
|
displayName: `prompt-image-${index + 1}`
|
|
293
189
|
}));
|
|
294
190
|
const providerHeaders = context.provider.provider?.headers;
|
|
295
|
-
const requestHeaders = providerHeaders && Object.keys(providerHeaders).length > 0 ?
|
|
191
|
+
const requestHeaders = providerHeaders && Object.keys(providerHeaders).length > 0 ? providerHeaders : void 0;
|
|
296
192
|
return {
|
|
297
193
|
prompt: params.prompt,
|
|
298
194
|
...attachments.length > 0 ? { attachments } : {},
|
|
299
195
|
...requestHeaders ? { requestHeaders } : {}
|
|
300
196
|
};
|
|
301
197
|
}
|
|
302
|
-
async function resolvePromptImages(params, context) {
|
|
303
|
-
const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
|
|
304
|
-
if (!workspaceDir) return [];
|
|
305
|
-
const localRoots = context.workspaceOnly && context.effectiveWorkspaceDir ? [context.effectiveWorkspaceDir] : void 0;
|
|
306
|
-
return (await detectAndLoadAgentHarnessPromptImages({
|
|
307
|
-
prompt: params.prompt,
|
|
308
|
-
workspaceDir,
|
|
309
|
-
model: resolveImageCapabilityModel(params),
|
|
310
|
-
existingImages: Array.isArray(params.images) ? params.images : void 0,
|
|
311
|
-
imageOrder: Array.isArray(params.imageOrder) ? params.imageOrder : void 0,
|
|
312
|
-
media: Array.isArray(params.media) ? params.media : void 0,
|
|
313
|
-
config: params.config,
|
|
314
|
-
workspaceOnly: context.workspaceOnly,
|
|
315
|
-
localRoots,
|
|
316
|
-
sandbox: context.sandbox?.enabled && context.sandbox.fsBridge ? {
|
|
317
|
-
root: context.sandbox.workspaceDir,
|
|
318
|
-
bridge: context.sandbox.fsBridge
|
|
319
|
-
} : void 0
|
|
320
|
-
})).images;
|
|
321
|
-
}
|
|
322
|
-
function resolveImageCapabilityModel(params) {
|
|
323
|
-
const model = params.model;
|
|
324
|
-
if (model && typeof model === "object" && Array.isArray(model.input)) return { input: model.input };
|
|
325
|
-
return { input: ["image"] };
|
|
326
|
-
}
|
|
327
198
|
function readResolvedAttemptPath(value) {
|
|
328
199
|
const raw = readNonEmptyString(value)?.trim();
|
|
329
200
|
if (!raw) return;
|
|
@@ -406,158 +277,6 @@ function isSdkSendAndWaitTimeoutError(error) {
|
|
|
406
277
|
if (typeof message !== "string") return false;
|
|
407
278
|
return /^Timeout after \d+ms waiting for session\.idle$/.test(message);
|
|
408
279
|
}
|
|
409
|
-
// extensions/copilot/src/event-bridge-transcript.ts
|
|
410
|
-
function buildAssistantMessage(params) {
|
|
411
|
-
const event = params.event;
|
|
412
|
-
const text = event ? event.data.content || params.assistantTexts.at(-1) || "" : "";
|
|
413
|
-
const reasoningText = event?.data.reasoningText ?? params.reasoningText;
|
|
414
|
-
const toolRequests = event?.data.toolRequests ?? [];
|
|
415
|
-
if (!text && !reasoningText && toolRequests.length === 0) return;
|
|
416
|
-
const content = [];
|
|
417
|
-
if (reasoningText) content.push({
|
|
418
|
-
thinking: reasoningText,
|
|
419
|
-
type: "thinking"
|
|
420
|
-
});
|
|
421
|
-
if (text) content.push({
|
|
422
|
-
text,
|
|
423
|
-
type: "text"
|
|
424
|
-
});
|
|
425
|
-
for (const request of toolRequests) content.push({
|
|
426
|
-
arguments: asNonArrayRecord(request.arguments),
|
|
427
|
-
id: request.toolCallId,
|
|
428
|
-
name: request.name,
|
|
429
|
-
type: "toolCall"
|
|
430
|
-
});
|
|
431
|
-
return {
|
|
432
|
-
api: params.modelRef.api ?? "openai-responses",
|
|
433
|
-
content,
|
|
434
|
-
model: event?.data.model ?? params.modelRef.id,
|
|
435
|
-
provider: params.modelRef.provider,
|
|
436
|
-
role: "assistant",
|
|
437
|
-
stopReason: toolRequests.length > 0 ? "toolUse" : "stop",
|
|
438
|
-
timestamp: params.now(),
|
|
439
|
-
usage: buildCopilotAssistantUsage({
|
|
440
|
-
fallbackOutputTokens: event?.data.outputTokens,
|
|
441
|
-
usage: params.usage
|
|
442
|
-
})
|
|
443
|
-
};
|
|
444
|
-
}
|
|
445
|
-
function buildAssistantProjectionGroup(group, modelRef, resolveTimestamp, usageByApiCallId, latestUsage, forTranscript) {
|
|
446
|
-
const messages = group.chunks.flatMap((chunk) => {
|
|
447
|
-
const message = buildAssistantMessage({
|
|
448
|
-
event: chunk.event,
|
|
449
|
-
modelRef,
|
|
450
|
-
now: () => resolveTimestamp(chunk.event),
|
|
451
|
-
reasoningText: forTranscript ? chunk.transcriptReasoningText : chunk.reasoningText,
|
|
452
|
-
usage: resolveAssistantUsage(chunk.event, latestUsage, usageByApiCallId),
|
|
453
|
-
assistantTexts: forTranscript ? chunk.transcriptAssistantTexts : chunk.assistantTexts
|
|
454
|
-
});
|
|
455
|
-
return message ? [message] : [];
|
|
456
|
-
});
|
|
457
|
-
const replayIncomplete = group.chunks.some(({ event }) => hasUnprojectedAssistantReplayState(event));
|
|
458
|
-
const last = messages.at(-1);
|
|
459
|
-
if (!last) return {
|
|
460
|
-
message: void 0,
|
|
461
|
-
replayIncomplete,
|
|
462
|
-
toolCallIds: []
|
|
463
|
-
};
|
|
464
|
-
const narrative = [];
|
|
465
|
-
let terminalThinking;
|
|
466
|
-
const toolCallsById = /* @__PURE__ */ new Map();
|
|
467
|
-
for (const message of messages) for (const part of message.content) {
|
|
468
|
-
if (part.type === "toolCall") {
|
|
469
|
-
toolCallsById.set(part.id, part);
|
|
470
|
-
continue;
|
|
471
|
-
}
|
|
472
|
-
if (part.type === "thinking") {
|
|
473
|
-
terminalThinking = part;
|
|
474
|
-
continue;
|
|
475
|
-
}
|
|
476
|
-
const previous = narrative.at(-1);
|
|
477
|
-
if (part.type === "text" && previous?.type === "text") narrative[narrative.length - 1] = {
|
|
478
|
-
...previous,
|
|
479
|
-
text: previous.text + part.text
|
|
480
|
-
};
|
|
481
|
-
else narrative.push(part);
|
|
482
|
-
}
|
|
483
|
-
const content = [
|
|
484
|
-
...terminalThinking ? [terminalThinking] : [],
|
|
485
|
-
...narrative,
|
|
486
|
-
...toolCallsById.values()
|
|
487
|
-
];
|
|
488
|
-
const toolCallIds = [...toolCallsById.keys()];
|
|
489
|
-
return {
|
|
490
|
-
message: {
|
|
491
|
-
...last,
|
|
492
|
-
content,
|
|
493
|
-
stopReason: toolCallIds.length > 0 ? "toolUse" : "stop"
|
|
494
|
-
},
|
|
495
|
-
replayIncomplete,
|
|
496
|
-
toolCallIds
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
function hasUnprojectedAssistantReplayState(event) {
|
|
500
|
-
return event.data.citations !== void 0 || event.data.serverTools !== void 0 || event.data.reasoningWireField !== void 0 || event.data.reasoningOpaque !== void 0 || event.data.encryptedContent !== void 0 || event.data.toolRequests?.some((request) => request.type === "custom") === true;
|
|
501
|
-
}
|
|
502
|
-
function resolveAssistantUsage(event, latest, byApiCallId) {
|
|
503
|
-
const apiCallId = readNonEmptyStringPreservingWhitespace(event?.data.apiCallId);
|
|
504
|
-
return apiCallId ? byApiCallId.get(apiCallId) ?? latest : latest;
|
|
505
|
-
}
|
|
506
|
-
function resolveEventTimestamp(timestamp, now) {
|
|
507
|
-
return parseDateStringTimestampMs(timestamp) ?? now();
|
|
508
|
-
}
|
|
509
|
-
function hasOwnKeys(value) {
|
|
510
|
-
return Boolean(value && typeof value === "object" && Object.keys(value).length > 0);
|
|
511
|
-
}
|
|
512
|
-
function projectSdkUserMetadata(attachments, source) {
|
|
513
|
-
const summaries = (attachments ?? []).map((attachment) => {
|
|
514
|
-
const { data: _data, payload: _payload, text: _text, ...summary } = attachment;
|
|
515
|
-
return summary;
|
|
516
|
-
});
|
|
517
|
-
const media = (attachments ?? []).flatMap((attachment) => {
|
|
518
|
-
if (attachment.type === "file") return [{
|
|
519
|
-
path: attachment.path,
|
|
520
|
-
contentType: attachment.mimeType
|
|
521
|
-
}];
|
|
522
|
-
return attachment.type === "selection" ? [{
|
|
523
|
-
path: attachment.filePath,
|
|
524
|
-
kind: "document"
|
|
525
|
-
}] : [];
|
|
526
|
-
});
|
|
527
|
-
if (!source && summaries.length === 0) return;
|
|
528
|
-
return {
|
|
529
|
-
...source ? { copilotSource: source } : {},
|
|
530
|
-
...summaries.length > 0 ? { copilotAttachments: summaries } : {},
|
|
531
|
-
...media.length > 0 ? { media } : {}
|
|
532
|
-
};
|
|
533
|
-
}
|
|
534
|
-
function projectToolResultDetails(data) {
|
|
535
|
-
const result = data.result;
|
|
536
|
-
const sanitizedContents = result?.contents ? sanitizeToolResult({ content: result.contents }).content : void 0;
|
|
537
|
-
const binaryResultsForLlm = result?.binaryResultsForLlm?.map((entry) => {
|
|
538
|
-
const { data: _data, ...descriptor } = entry;
|
|
539
|
-
return descriptor;
|
|
540
|
-
});
|
|
541
|
-
const citableSources = result?.citableSources?.map((source) => Object.assign({}, source, { content: sanitizeToolDetailText(source.content) }));
|
|
542
|
-
return sanitizeToolResult({
|
|
543
|
-
...result?.detailedContent ? { content: [{
|
|
544
|
-
type: "text",
|
|
545
|
-
text: result.detailedContent
|
|
546
|
-
}] } : {},
|
|
547
|
-
...result?.structuredContent ? { structuredContent: result.structuredContent } : {},
|
|
548
|
-
...sanitizedContents ? { contents: sanitizedContents } : {},
|
|
549
|
-
...binaryResultsForLlm?.length ? { binaryResultsForLlm } : {},
|
|
550
|
-
...citableSources?.length ? { citableSources } : {},
|
|
551
|
-
...data.mcpMeta || result?.mcpMeta ? { mcpMeta: data.mcpMeta ?? result?.mcpMeta } : {}
|
|
552
|
-
});
|
|
553
|
-
}
|
|
554
|
-
function sanitizeToolDetailText(text) {
|
|
555
|
-
const value = sanitizeToolResult({ content: [{
|
|
556
|
-
type: "text",
|
|
557
|
-
text
|
|
558
|
-
}] }).content?.[0]?.text;
|
|
559
|
-
return typeof value === "string" ? value : "";
|
|
560
|
-
}
|
|
561
280
|
// extensions/copilot/src/event-bridge.ts
|
|
562
281
|
function attachEventBridge(session, options) {
|
|
563
282
|
const messagesById = /* @__PURE__ */ new Map();
|
|
@@ -583,7 +302,6 @@ function attachEventBridge(session, options) {
|
|
|
583
302
|
let activeCompactionCount = 0;
|
|
584
303
|
let observedCompaction = false;
|
|
585
304
|
let deltaQueue = Promise.resolve();
|
|
586
|
-
let deltaChain = Promise.resolve();
|
|
587
305
|
let agentEventChain = Promise.resolve();
|
|
588
306
|
let compactionChain = Promise.resolve();
|
|
589
307
|
let compactionIdle;
|
|
@@ -639,17 +357,11 @@ function attachEventBridge(session, options) {
|
|
|
639
357
|
if (!onAssistantDelta) return;
|
|
640
358
|
const payload = {
|
|
641
359
|
delta,
|
|
642
|
-
|
|
643
|
-
text,
|
|
644
|
-
usage
|
|
360
|
+
text
|
|
645
361
|
};
|
|
646
|
-
deltaQueue = deltaQueue.then(() => onAssistantDelta(payload)
|
|
362
|
+
deltaQueue = deltaQueue.then(() => onAssistantDelta(payload)).catch((error) => {
|
|
647
363
|
firstDeltaError ??= error;
|
|
648
364
|
});
|
|
649
|
-
deltaChain = deltaQueue.then(() => {
|
|
650
|
-
if (firstDeltaError !== void 0) throw toErrorObject(firstDeltaError, "Non-Error thrown");
|
|
651
|
-
});
|
|
652
|
-
deltaChain.catch(() => void 0);
|
|
653
365
|
});
|
|
654
366
|
listenRoot("assistant.reasoning_delta", (event) => {
|
|
655
367
|
const reasoningId = readNonEmptyStringPreservingWhitespace(event.data.reasoningId) ?? "assistant-reasoning";
|
|
@@ -856,8 +568,9 @@ function attachEventBridge(session, options) {
|
|
|
856
568
|
compactionIdle?.resolve();
|
|
857
569
|
compactionIdle = void 0;
|
|
858
570
|
},
|
|
859
|
-
awaitDeltaChain() {
|
|
860
|
-
|
|
571
|
+
async awaitDeltaChain() {
|
|
572
|
+
await deltaQueue;
|
|
573
|
+
if (firstDeltaError !== void 0) throw toErrorObject(firstDeltaError, "Non-Error thrown");
|
|
861
574
|
},
|
|
862
575
|
awaitAgentEventChain() {
|
|
863
576
|
return agentEventChain;
|
|
@@ -877,18 +590,16 @@ function attachEventBridge(session, options) {
|
|
|
877
590
|
},
|
|
878
591
|
snapshot() {
|
|
879
592
|
return {
|
|
880
|
-
assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent),
|
|
881
593
|
completedCount,
|
|
882
|
-
lastAssistantEvent,
|
|
883
594
|
startedCount,
|
|
884
595
|
streamError,
|
|
885
|
-
toolMetas: toolMetas
|
|
886
|
-
usage
|
|
596
|
+
toolMetas: [...toolMetas],
|
|
597
|
+
usage
|
|
887
598
|
};
|
|
888
599
|
},
|
|
889
600
|
buildAssistantMessage(args) {
|
|
890
601
|
const group = pendingAssistantProjection ?? lastAssistantProjection;
|
|
891
|
-
|
|
602
|
+
const message = group ? buildAssistantProjectionGroup(group, args.modelRef, () => args.now(), usageByApiCallId, usage, false).message : buildAssistantMessage({
|
|
892
603
|
event: lastAssistantEvent,
|
|
893
604
|
modelRef: args.modelRef,
|
|
894
605
|
now: args.now,
|
|
@@ -896,6 +607,7 @@ function attachEventBridge(session, options) {
|
|
|
896
607
|
usage: resolveAssistantUsage(lastAssistantEvent, usage, usageByApiCallId),
|
|
897
608
|
assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent)
|
|
898
609
|
});
|
|
610
|
+
return message?.content.length ? message : void 0;
|
|
899
611
|
},
|
|
900
612
|
finalizeAssistantTexts() {
|
|
901
613
|
return finalizeAssistantTexts(messagesById, lastAssistantEvent);
|
|
@@ -916,7 +628,7 @@ function attachEventBridge(session, options) {
|
|
|
916
628
|
detach() {
|
|
917
629
|
if (detached) return;
|
|
918
630
|
detached = true;
|
|
919
|
-
for (const unsubscribe of
|
|
631
|
+
for (const unsubscribe of unsubscribeFns.toReversed()) try {
|
|
920
632
|
unsubscribe();
|
|
921
633
|
} catch {}
|
|
922
634
|
unsubscribeFns.length = 0;
|
|
@@ -1038,6 +750,28 @@ function splitPlanText(text) {
|
|
|
1038
750
|
return (text ?? "").split(/\r?\n/).map((line) => line.trim().replace(/^[-*]\s+/, "")).filter((line) => line.length > 0);
|
|
1039
751
|
}
|
|
1040
752
|
// extensions/copilot/src/attempt-cleanup.ts
|
|
753
|
+
/** Deletion follows disconnect even when disconnect fails; the first cleanup failure wins. */
|
|
754
|
+
async function disconnectCopilotSession(params) {
|
|
755
|
+
let failure;
|
|
756
|
+
try {
|
|
757
|
+
await params.session.disconnect();
|
|
758
|
+
} catch (error) {
|
|
759
|
+
failure = toCopilotError(error);
|
|
760
|
+
}
|
|
761
|
+
if (params.deleteSessionId) try {
|
|
762
|
+
await params.client.deleteSession(params.deleteSessionId);
|
|
763
|
+
} catch (error) {
|
|
764
|
+
failure ??= toCopilotError(error);
|
|
765
|
+
}
|
|
766
|
+
if (failure) throw failure;
|
|
767
|
+
}
|
|
768
|
+
function preserveCopilotAttemptCleanupError(primary, error) {
|
|
769
|
+
if (primary) {
|
|
770
|
+
console.warn("[copilot-attempt] detached session cleanup failed after primary error", error);
|
|
771
|
+
return primary;
|
|
772
|
+
}
|
|
773
|
+
return toCopilotError(error);
|
|
774
|
+
}
|
|
1041
775
|
async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now) {
|
|
1042
776
|
const failure = result.terminal.kind === "failed" ? { error: result.terminal.error } : result.terminal.kind === "ok" ? void 0 : result.terminal.failure;
|
|
1043
777
|
const aborted = result.terminal.kind === "aborted" && result.terminal.source !== "yield_cleanup";
|
|
@@ -1057,13 +791,21 @@ async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now
|
|
|
1057
791
|
}
|
|
1058
792
|
async function deferBackgroundCompactionCleanup(params) {
|
|
1059
793
|
let outcome = "deadline";
|
|
794
|
+
let cleanupError;
|
|
1060
795
|
try {
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
796
|
+
const { abortSignal, awaitSessionIdle, bridge, timeoutMs } = params;
|
|
797
|
+
if (abortSignal?.aborted) outcome = "aborted";
|
|
798
|
+
else {
|
|
799
|
+
const completion = (async () => {
|
|
800
|
+
if (awaitSessionIdle) await bridge.awaitSessionIdle();
|
|
801
|
+
await bridge.awaitCompactionCompletion();
|
|
802
|
+
return "completed";
|
|
803
|
+
})();
|
|
804
|
+
outcome = await raceWithTimeout(completion, timeoutMs, () => "deadline", {
|
|
805
|
+
signal: abortSignal,
|
|
806
|
+
onAbort: () => "aborted"
|
|
807
|
+
});
|
|
808
|
+
}
|
|
1067
809
|
} catch {} finally {
|
|
1068
810
|
if (outcome !== "completed") {
|
|
1069
811
|
await cancelBackgroundCompactionBeforeTeardown(params.session);
|
|
@@ -1071,18 +813,28 @@ async function deferBackgroundCompactionCleanup(params) {
|
|
|
1071
813
|
}
|
|
1072
814
|
params.bridge.detach();
|
|
1073
815
|
await params.bridge.awaitAgentEventChain();
|
|
1074
|
-
try {
|
|
1075
|
-
await params.session.disconnect();
|
|
1076
|
-
} catch {}
|
|
1077
816
|
params.cleanupToolBridge?.();
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
817
|
+
try {
|
|
818
|
+
await params.cleanupByokProxy?.();
|
|
819
|
+
} catch (error) {
|
|
820
|
+
cleanupError ??= toCopilotError(error);
|
|
821
|
+
}
|
|
822
|
+
try {
|
|
823
|
+
await disconnectCopilotSession({
|
|
824
|
+
session: params.session,
|
|
825
|
+
client: params.handle.client,
|
|
826
|
+
deleteSessionId: params.deleteSessionOnCleanup || outcome !== "completed" && params.deleteSessionOnIncompleteCleanup ? params.sdkSessionId : void 0
|
|
827
|
+
});
|
|
828
|
+
} catch (error) {
|
|
829
|
+
if (params.deleteSessionOnCleanup) cleanupError ??= toCopilotError(error);
|
|
830
|
+
}
|
|
1082
831
|
try {
|
|
1083
832
|
await params.pool.release(params.handle);
|
|
1084
|
-
} catch {
|
|
833
|
+
} catch (error) {
|
|
834
|
+
if (params.deleteSessionOnCleanup) cleanupError ??= toCopilotError(error);
|
|
835
|
+
}
|
|
1085
836
|
}
|
|
837
|
+
if (cleanupError) throw cleanupError;
|
|
1086
838
|
return outcome;
|
|
1087
839
|
}
|
|
1088
840
|
async function cancelBackgroundCompactionBeforeTeardown(session) {
|
|
@@ -1090,18 +842,6 @@ async function cancelBackgroundCompactionBeforeTeardown(session) {
|
|
|
1090
842
|
if (!cancelBackgroundCompaction) return;
|
|
1091
843
|
await withTimeout(Promise.resolve().then(() => cancelBackgroundCompaction()), BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS).catch(() => void 0);
|
|
1092
844
|
}
|
|
1093
|
-
async function awaitDeferredCleanupBeforeDeadline(params) {
|
|
1094
|
-
if (params.abortSignal?.aborted) return "aborted";
|
|
1095
|
-
const completion = (async () => {
|
|
1096
|
-
if (params.awaitSessionIdle) await params.bridge.awaitSessionIdle();
|
|
1097
|
-
await params.bridge.awaitCompactionCompletion();
|
|
1098
|
-
return "completed";
|
|
1099
|
-
})();
|
|
1100
|
-
return await raceWithTimeout(completion, params.timeoutMs, () => "deadline", {
|
|
1101
|
-
signal: params.abortSignal,
|
|
1102
|
-
onAbort: () => "aborted"
|
|
1103
|
-
});
|
|
1104
|
-
}
|
|
1105
845
|
// extensions/copilot/src/attempt-active-run.ts
|
|
1106
846
|
const DEFAULT_STEERING_DELIVERY_TIMEOUT_MS = 12e4;
|
|
1107
847
|
function registerCopilotActiveRun(params) {
|
|
@@ -1115,7 +855,7 @@ function registerCopilotActiveRun(params) {
|
|
|
1115
855
|
});
|
|
1116
856
|
};
|
|
1117
857
|
const claimPendingUserInputAnswer = async (text, options) => {
|
|
1118
|
-
if (options?.isInboundUserMessage !== true || options.images?.length) return false;
|
|
858
|
+
if (options?.isInboundUserMessage !== true || options.allowPendingUserInputAnswer === false || options.images?.length) return false;
|
|
1119
859
|
return await claimPendingAgentQuestionAnswer({
|
|
1120
860
|
sessionKey: params.input.sessionKey ?? params.input.sessionId,
|
|
1121
861
|
text,
|
|
@@ -1195,18 +935,19 @@ function registerCopilotActiveRun(params) {
|
|
|
1195
935
|
params.abortActiveSession();
|
|
1196
936
|
}
|
|
1197
937
|
};
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
938
|
+
return {
|
|
939
|
+
handle: activeRunHandle,
|
|
940
|
+
attachment: setActiveEmbeddedRun(params.input.sessionId, activeRunHandle, params.input.sessionKey, params.input.sessionFile, params.agentId)
|
|
941
|
+
};
|
|
1201
942
|
}
|
|
1202
943
|
async function waitForPersistenceReceipt(receipt, requestedTimeoutMs) {
|
|
1203
|
-
await raceWithTimeout(receipt,
|
|
944
|
+
await raceWithTimeout(receipt, requestedTimeoutMs !== void 0 && Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0 ? requestedTimeoutMs : DEFAULT_STEERING_DELIVERY_TIMEOUT_MS, () => {
|
|
1204
945
|
throw new Error("Copilot steering transcript receipt timed out");
|
|
1205
946
|
}, { ref: false });
|
|
1206
947
|
}
|
|
1207
948
|
// extensions/copilot/src/attempt-transcript-replay.ts
|
|
1208
949
|
function readIdempotencyKey(message) {
|
|
1209
|
-
const key = message.idempotencyKey;
|
|
950
|
+
const key = "idempotencyKey" in message ? message.idempotencyKey : void 0;
|
|
1210
951
|
return typeof key === "string" && key ? key : void 0;
|
|
1211
952
|
}
|
|
1212
953
|
function userText(content) {
|
|
@@ -1255,9 +996,9 @@ function isSameUserTurn(candidate, current, currentRunUserKey) {
|
|
|
1255
996
|
if (candidate === current) return true;
|
|
1256
997
|
const candidateKey = candidate.idempotencyKey;
|
|
1257
998
|
const currentKey = current.idempotencyKey;
|
|
1258
|
-
if (
|
|
1259
|
-
if (
|
|
1260
|
-
if (
|
|
999
|
+
if (candidateKey !== void 0 || currentKey !== void 0) {
|
|
1000
|
+
if (candidateKey !== void 0 && currentKey !== void 0) return candidateKey === currentKey;
|
|
1001
|
+
if (candidateKey === void 0 || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
|
|
1261
1002
|
}
|
|
1262
1003
|
return candidate.timestamp === current.timestamp && userText(candidate.content) === userText(current.content);
|
|
1263
1004
|
}
|
|
@@ -1275,6 +1016,7 @@ async function completeCopilotAttempt(params) {
|
|
|
1275
1016
|
const currentRunUserKey = `${input.runId}:user`;
|
|
1276
1017
|
const messagesSnapshot = transcript?.messagesSnapshot ?? (recorder?.isBlocked() ? removePreparedUser(messages, recorder.message, currentRunUserKey) : includePreparedUser(messages, recorder?.message, input.trigger === "memory", currentRunUserKey));
|
|
1277
1018
|
const result = createResult(input, {
|
|
1019
|
+
runtimeArtifact: params.runtimeArtifact,
|
|
1278
1020
|
acceptedSessionSpawns,
|
|
1279
1021
|
aborted,
|
|
1280
1022
|
assistantTexts,
|
|
@@ -1301,7 +1043,7 @@ async function completeCopilotAttempt(params) {
|
|
|
1301
1043
|
sdkSessionId,
|
|
1302
1044
|
timedOut,
|
|
1303
1045
|
timedOutDuringCompaction,
|
|
1304
|
-
toolMetas: snap
|
|
1046
|
+
toolMetas: snap?.toolMetas ?? [],
|
|
1305
1047
|
usage: snap?.usage,
|
|
1306
1048
|
yieldDetected,
|
|
1307
1049
|
yieldAcknowledgment
|
|
@@ -1343,10 +1085,182 @@ function includePreparedUser(messages, prepared, hidden, currentRunUserKey) {
|
|
|
1343
1085
|
function removePreparedUser(messages, prepared, currentRunUserKey) {
|
|
1344
1086
|
return prepared && isSameUserTurn(messages.at(-1), prepared, currentRunUserKey) ? messages.slice(0, -1) : messages;
|
|
1345
1087
|
}
|
|
1088
|
+
// extensions/copilot/src/attempt-prepare.ts
|
|
1089
|
+
function prepareCopilotAttemptContext(params, deps) {
|
|
1090
|
+
const settledToolFinalization = deps.operation === "settled-tool-finalization";
|
|
1091
|
+
if (!settledToolFinalization) assertCopilotAttemptHostCapabilities(params);
|
|
1092
|
+
const { hostCapabilities: _hostCapabilities, ...capabilityFreeParams } = params;
|
|
1093
|
+
const input = settledToolFinalization ? {
|
|
1094
|
+
...capabilityFreeParams,
|
|
1095
|
+
disableTools: true,
|
|
1096
|
+
images: [],
|
|
1097
|
+
imageOrder: [],
|
|
1098
|
+
extraSystemPrompt: void 0,
|
|
1099
|
+
onAgentEvent: void 0,
|
|
1100
|
+
onAgentToolResult: void 0,
|
|
1101
|
+
onAssistantDelta: void 0,
|
|
1102
|
+
onAssistantMessageStart: void 0,
|
|
1103
|
+
onBlockReply: void 0,
|
|
1104
|
+
onBlockReplyFlush: void 0,
|
|
1105
|
+
onPartialReply: void 0,
|
|
1106
|
+
onReasoningEnd: void 0,
|
|
1107
|
+
onReasoningStream: void 0,
|
|
1108
|
+
onToolResult: void 0,
|
|
1109
|
+
onToolStreamBoundary: void 0,
|
|
1110
|
+
operation: "settled-tool-finalization"
|
|
1111
|
+
} : params;
|
|
1112
|
+
const ringZeroSystemAgentRun = isHostScopedAgentToolActive("openclaw") && input.toolsAllow?.length === 1 && input.toolsAllow[0]?.trim().toLowerCase() === "openclaw";
|
|
1113
|
+
const messages = [...input.messages ?? []];
|
|
1114
|
+
const modelRef = resolveModelRef(input);
|
|
1115
|
+
const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
|
|
1116
|
+
const sandboxSessionKey = readNonEmptyString(input.sandboxSessionKey) ?? readNonEmptyString(input.sessionKey) ?? readNonEmptyString(input.sessionId);
|
|
1117
|
+
const { sessionAgentId } = resolveSessionAgentIdsStrict({
|
|
1118
|
+
sessionKey: readNonEmptyString(input.sessionKey),
|
|
1119
|
+
config: input.config,
|
|
1120
|
+
agentId: readNonEmptyString(params.agentId)
|
|
1121
|
+
});
|
|
1122
|
+
const hookContextWindowFields = {
|
|
1123
|
+
...input.contextWindowInfo?.tokens ? { contextTokenBudget: input.contextWindowInfo.tokens } : input.contextTokenBudget ? { contextTokenBudget: input.contextTokenBudget } : {},
|
|
1124
|
+
...input.contextWindowInfo?.source ? { contextWindowSource: input.contextWindowInfo.source } : {},
|
|
1125
|
+
...input.contextWindowInfo?.referenceTokens ? { contextWindowReferenceTokens: input.contextWindowInfo.referenceTokens } : {}
|
|
1126
|
+
};
|
|
1127
|
+
return {
|
|
1128
|
+
settledToolFinalization,
|
|
1129
|
+
input,
|
|
1130
|
+
ringZeroSystemAgentRun,
|
|
1131
|
+
messages,
|
|
1132
|
+
modelRef,
|
|
1133
|
+
resolvedWorkspaceForSandbox,
|
|
1134
|
+
sandboxSessionKey,
|
|
1135
|
+
sessionAgentId,
|
|
1136
|
+
hookContextWindowFields,
|
|
1137
|
+
hookContext: {
|
|
1138
|
+
runId: input.runId,
|
|
1139
|
+
jobId: input.jobId,
|
|
1140
|
+
agentId: sessionAgentId,
|
|
1141
|
+
sessionKey: readNonEmptyString(input.sessionKey) ?? sandboxSessionKey,
|
|
1142
|
+
sessionId: input.sessionId,
|
|
1143
|
+
workspaceDir: resolvedWorkspaceForSandbox,
|
|
1144
|
+
modelProviderId: modelRef.provider,
|
|
1145
|
+
modelId: modelRef.id,
|
|
1146
|
+
trigger: input.trigger,
|
|
1147
|
+
inputProvenance: input.inputProvenance,
|
|
1148
|
+
foregroundPromptContext: buildEmbeddedForegroundPromptContext({
|
|
1149
|
+
...input,
|
|
1150
|
+
agentId: sessionAgentId
|
|
1151
|
+
}, input.agentDir ?? resolveAgentDir(input.config ?? {}, sessionAgentId)),
|
|
1152
|
+
...input.config ? { config: input.config } : {},
|
|
1153
|
+
...hookContextWindowFields,
|
|
1154
|
+
...buildAgentHookContextChannelFields(input)
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
async function resolveCopilotAttemptSandbox(params) {
|
|
1159
|
+
const sandbox = params.input.sandbox !== void 0 ? params.input.sandbox : await resolveSandboxContext({
|
|
1160
|
+
config: params.input.config,
|
|
1161
|
+
agentId: params.input.sandboxAgentId,
|
|
1162
|
+
sessionKey: params.sandboxSessionKey,
|
|
1163
|
+
workspaceDir: params.resolvedWorkspaceForSandbox
|
|
1164
|
+
});
|
|
1165
|
+
const effectiveWorkspaceDir = sandbox?.enabled ? sandbox.workspaceAccess === "rw" ? params.resolvedWorkspaceForSandbox : sandbox.workspaceDir : params.resolvedWorkspaceForSandbox;
|
|
1166
|
+
if (sandbox?.enabled && effectiveWorkspaceDir !== params.resolvedWorkspaceForSandbox) await fsp.mkdir(effectiveWorkspaceDir, { recursive: true });
|
|
1167
|
+
return {
|
|
1168
|
+
sandbox,
|
|
1169
|
+
effectiveWorkspaceDir
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1346
1172
|
// extensions/copilot/src/attempt-mode.ts
|
|
1347
1173
|
function isRawCopilotModelRun(params) {
|
|
1348
1174
|
return params.modelRun === true || params.promptMode === "none";
|
|
1349
1175
|
}
|
|
1176
|
+
// extensions/copilot/src/hooks-bridge.ts
|
|
1177
|
+
const DEFAULT_HOOK_ERROR_HANDLER = ({ hookName, error }) => {
|
|
1178
|
+
console.warn(`[copilot hooks-bridge] ${hookName} handler threw:`, error);
|
|
1179
|
+
};
|
|
1180
|
+
/**
|
|
1181
|
+
* Wrap a native handler so it cannot throw into the SDK. Returning undefined
|
|
1182
|
+
* leaves the SDK's default decision in place.
|
|
1183
|
+
*/
|
|
1184
|
+
function isolate(hookName, handler, onError) {
|
|
1185
|
+
if (!handler) return;
|
|
1186
|
+
return async (...args) => {
|
|
1187
|
+
try {
|
|
1188
|
+
return await handler(...args);
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
try {
|
|
1191
|
+
onError({
|
|
1192
|
+
hookName,
|
|
1193
|
+
error
|
|
1194
|
+
});
|
|
1195
|
+
} catch {}
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Build an SDK-shaped hook object from native per-attempt configuration.
|
|
1202
|
+
* Omit the SDK hook subsystem when no handlers were configured.
|
|
1203
|
+
*/
|
|
1204
|
+
function createHooksBridge(config, options) {
|
|
1205
|
+
if (!config) return;
|
|
1206
|
+
const onError = config.onHookError ?? DEFAULT_HOOK_ERROR_HANDLER;
|
|
1207
|
+
const hooks = {
|
|
1208
|
+
onPreToolUse: isolate("onPreToolUse", config.onPreToolUse, onError),
|
|
1209
|
+
onPreMcpToolCall: isolate("onPreMcpToolCall", config.onPreMcpToolCall, onError),
|
|
1210
|
+
onPostToolUse: isolate("onPostToolUse", config.onPostToolUse, onError),
|
|
1211
|
+
onPostToolUseFailure: isolate("onPostToolUseFailure", config.onPostToolUseFailure, onError),
|
|
1212
|
+
onSessionStart: isolate("onSessionStart", config.onSessionStart, onError),
|
|
1213
|
+
onSessionEnd: isolate("onSessionEnd", config.onSessionEnd, onError),
|
|
1214
|
+
onErrorOccurred: isolate("onErrorOccurred", config.onErrorOccurred, onError)
|
|
1215
|
+
};
|
|
1216
|
+
const userPrompt = isolate("onUserPromptSubmitted", config.onUserPromptSubmitted, onError);
|
|
1217
|
+
if (userPrompt) hooks.onUserPromptSubmitted = async (input, invocation) => {
|
|
1218
|
+
const output = await userPrompt(input, invocation);
|
|
1219
|
+
try {
|
|
1220
|
+
options?.onUserPromptSubmitted?.({
|
|
1221
|
+
prompt: output?.modifiedPrompt ?? input.prompt,
|
|
1222
|
+
...output?.additionalContext ? { additionalContext: output.additionalContext } : {}
|
|
1223
|
+
});
|
|
1224
|
+
} catch (error) {
|
|
1225
|
+
try {
|
|
1226
|
+
onError({
|
|
1227
|
+
hookName: "onUserPromptSubmitted",
|
|
1228
|
+
error
|
|
1229
|
+
});
|
|
1230
|
+
} catch {}
|
|
1231
|
+
}
|
|
1232
|
+
return output;
|
|
1233
|
+
};
|
|
1234
|
+
for (const key of Object.keys(hooks)) if (hooks[key] === void 0) delete hooks[key];
|
|
1235
|
+
return Object.keys(hooks).length > 0 ? hooks : void 0;
|
|
1236
|
+
}
|
|
1237
|
+
// extensions/copilot/src/permission-bridge.ts
|
|
1238
|
+
const REJECT_ALL_FEEDBACK = "copilot agent runtime: no permission policy installed (denied by default)";
|
|
1239
|
+
const rejectAllPolicy = () => ({
|
|
1240
|
+
kind: "reject",
|
|
1241
|
+
feedback: REJECT_ALL_FEEDBACK
|
|
1242
|
+
});
|
|
1243
|
+
function createPermissionBridge(policy = rejectAllPolicy) {
|
|
1244
|
+
return async (request, invocation) => {
|
|
1245
|
+
const ctx = {
|
|
1246
|
+
request,
|
|
1247
|
+
sessionId: invocation.sessionId
|
|
1248
|
+
};
|
|
1249
|
+
try {
|
|
1250
|
+
const result = await policy(ctx);
|
|
1251
|
+
if (result !== void 0) return result;
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
return {
|
|
1254
|
+
kind: "reject",
|
|
1255
|
+
feedback: `copilot permission policy threw: ${formatErrorMessage(error)}`
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
return {
|
|
1259
|
+
kind: "reject",
|
|
1260
|
+
feedback: REJECT_ALL_FEEDBACK
|
|
1261
|
+
};
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1350
1264
|
// extensions/copilot/src/tool-bridge.ts
|
|
1351
1265
|
const EMPTY_PROMPT_TOOL_POLICY = { apply: () => ({
|
|
1352
1266
|
tools: [],
|
|
@@ -1404,7 +1318,6 @@ async function createCopilotToolBridge(input) {
|
|
|
1404
1318
|
runtimeToolAllowlist: toolSurfaceRuntime.runtimeToolAllowlist
|
|
1405
1319
|
}, toolSurfaceRuntime);
|
|
1406
1320
|
const hostCapabilities = attemptParams.hostCapabilities;
|
|
1407
|
-
if (!hostCapabilities) throw new Error("Copilot attempt tools require host-bound capabilities.");
|
|
1408
1321
|
const bindingCwd = toolOptions.cwd ?? toolOptions.workspaceDir;
|
|
1409
1322
|
const bindingOptions = bindingCwd ? { cwd: bindingCwd } : void 0;
|
|
1410
1323
|
const createToolSurfaceAsync = hostCapabilities.createToolSurfaceAsync;
|
|
@@ -1415,7 +1328,6 @@ async function createCopilotToolBridge(input) {
|
|
|
1415
1328
|
const compactedTools = toolSurfaceRuntime.compactTools(allowedSourceTools, { localModelLeanApplied: true });
|
|
1416
1329
|
const newlyConstructedTools = compactedTools.tools.filter((tool) => !boundSourceTools.has(tool));
|
|
1417
1330
|
const boundNewlyConstructedTools = newlyConstructedTools.length > 0 ? hostCapabilities.bindToolSurface(newlyConstructedTools, bindingOptions) : newlyConstructedTools;
|
|
1418
|
-
if (boundNewlyConstructedTools.length !== newlyConstructedTools.length) throw new Error("Copilot host capability changed the tool surface length.");
|
|
1419
1331
|
const newlyBoundTools = /* @__PURE__ */ new Map();
|
|
1420
1332
|
for (let index = 0; index < newlyConstructedTools.length; index += 1) newlyBoundTools.set(newlyConstructedTools[index], boundNewlyConstructedTools[index]);
|
|
1421
1333
|
const exposedTools = compactedTools.tools.map((tool) => newlyBoundTools.get(tool) ?? tool);
|
|
@@ -1424,7 +1336,9 @@ async function createCopilotToolBridge(input) {
|
|
|
1424
1336
|
const runInAttemptContext = AsyncLocalStorage.snapshot();
|
|
1425
1337
|
let sequentialBarrier = Promise.resolve();
|
|
1426
1338
|
const pendingCalls = /* @__PURE__ */ new Set();
|
|
1339
|
+
let acceptingCalls = true;
|
|
1427
1340
|
const scheduleToolExecution = (executionMode, execute) => {
|
|
1341
|
+
if (!acceptingCalls) return Promise.reject(/* @__PURE__ */ new Error("[copilot-tool-bridge] attempt is closing"));
|
|
1428
1342
|
const run = (executionMode === "sequential" ? Promise.all(pendingCalls) : sequentialBarrier).then(() => runInAttemptContext(execute));
|
|
1429
1343
|
const settled = run.then(() => void 0, () => void 0);
|
|
1430
1344
|
pendingCalls.add(settled);
|
|
@@ -1435,6 +1349,10 @@ async function createCopilotToolBridge(input) {
|
|
|
1435
1349
|
const sdkTools = exposedTools.map((sourceTool) => convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution));
|
|
1436
1350
|
return {
|
|
1437
1351
|
cleanup: toolSurfaceRuntime.cleanup,
|
|
1352
|
+
settle: async () => {
|
|
1353
|
+
acceptingCalls = false;
|
|
1354
|
+
await Promise.all(pendingCalls);
|
|
1355
|
+
},
|
|
1438
1356
|
codeModeEngaged: toolSurfaceRuntime.codeModeControlsEnabled,
|
|
1439
1357
|
promptToolPolicy: {
|
|
1440
1358
|
requireExplicitMessageTarget: toolOptions.requireExplicitMessageTarget,
|
|
@@ -1473,8 +1391,8 @@ async function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRunti
|
|
|
1473
1391
|
const agentDir = input.agentDir ?? a.agentDir;
|
|
1474
1392
|
const sandbox = input.sandbox ?? void 0;
|
|
1475
1393
|
const model = a.model;
|
|
1476
|
-
const modelHasVision =
|
|
1477
|
-
const modelCompat = model
|
|
1394
|
+
const modelHasVision = model?.input?.includes("image") ?? false;
|
|
1395
|
+
const modelCompat = model?.compat;
|
|
1478
1396
|
return {
|
|
1479
1397
|
agentId: input.agentId,
|
|
1480
1398
|
policyAgentId: a.sandboxAgentId ?? input.agentId,
|
|
@@ -1520,8 +1438,6 @@ async function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRunti
|
|
|
1520
1438
|
requireExplicitMessageTarget: a.requireExplicitMessageTarget ?? isSubagentSessionKey(liveSessionKey),
|
|
1521
1439
|
disableMessageTool: a.disableMessageTool,
|
|
1522
1440
|
forceMessageTool: a.forceMessageTool,
|
|
1523
|
-
enableHeartbeatTool: a.enableHeartbeatTool,
|
|
1524
|
-
forceHeartbeatTool: a.forceHeartbeatTool,
|
|
1525
1441
|
authProfileStore: a.toolAuthProfileStore ?? a.authProfileStore,
|
|
1526
1442
|
computerContextEpoch: input.computerContextEpoch,
|
|
1527
1443
|
onToolOutcome: a.onToolOutcome,
|
|
@@ -1537,8 +1453,6 @@ async function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRunti
|
|
|
1537
1453
|
};
|
|
1538
1454
|
}
|
|
1539
1455
|
function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution) {
|
|
1540
|
-
if (typeof sourceTool.name !== "string" || sourceTool.name.trim().length === 0) throw new Error("[copilot-tool-bridge] tool name must be a non-empty string");
|
|
1541
|
-
if (typeof sourceTool.execute !== "function") throw new Error(`[copilot-tool-bridge] tool '${sourceTool.name}' must define an execute function`);
|
|
1542
1456
|
const ownerKey = getPluginToolSideEffectOwnerKey(sourceTool);
|
|
1543
1457
|
const ownerMutation = ownerKey ? { ownerKey } : void 0;
|
|
1544
1458
|
const notifyToolResult = (result, isError) => {
|
|
@@ -1735,135 +1649,9 @@ function shouldForceCopilotMessageTool(params) {
|
|
|
1735
1649
|
}
|
|
1736
1650
|
function findDuplicateToolNames(sourceTools) {
|
|
1737
1651
|
const counts = /* @__PURE__ */ new Map();
|
|
1738
|
-
for (const sourceTool of sourceTools)
|
|
1739
|
-
if (typeof sourceTool.name !== "string" || sourceTool.name.length === 0) continue;
|
|
1740
|
-
counts.set(sourceTool.name, (counts.get(sourceTool.name) ?? 0) + 1);
|
|
1741
|
-
}
|
|
1652
|
+
for (const sourceTool of sourceTools) counts.set(sourceTool.name, (counts.get(sourceTool.name) ?? 0) + 1);
|
|
1742
1653
|
return [...counts.entries()].filter(([, count]) => count > 1).map(([name]) => name).toSorted();
|
|
1743
1654
|
}
|
|
1744
|
-
// extensions/copilot/src/attempt-prepare.ts
|
|
1745
|
-
function prepareCopilotAttemptContext(params, deps) {
|
|
1746
|
-
const settledToolFinalization = deps.operation === "settled-tool-finalization";
|
|
1747
|
-
if (!settledToolFinalization) assertCopilotAttemptHostCapabilities(params);
|
|
1748
|
-
const { hostCapabilities: _hostCapabilities, ...capabilityFreeParams } = params;
|
|
1749
|
-
const input = settledToolFinalization ? {
|
|
1750
|
-
...capabilityFreeParams,
|
|
1751
|
-
disableTools: true,
|
|
1752
|
-
images: [],
|
|
1753
|
-
imageOrder: [],
|
|
1754
|
-
extraSystemPrompt: void 0,
|
|
1755
|
-
onAgentEvent: void 0,
|
|
1756
|
-
onAgentToolResult: void 0,
|
|
1757
|
-
onAssistantDelta: void 0,
|
|
1758
|
-
onAssistantMessageStart: void 0,
|
|
1759
|
-
onBlockReply: void 0,
|
|
1760
|
-
onBlockReplyFlush: void 0,
|
|
1761
|
-
onPartialReply: void 0,
|
|
1762
|
-
onReasoningEnd: void 0,
|
|
1763
|
-
onReasoningStream: void 0,
|
|
1764
|
-
onToolResult: void 0,
|
|
1765
|
-
onToolStreamBoundary: void 0,
|
|
1766
|
-
operation: "settled-tool-finalization"
|
|
1767
|
-
} : params;
|
|
1768
|
-
const createToolBridge = deps.createToolBridge ?? createCopilotToolBridge;
|
|
1769
|
-
const ringZeroSystemAgentRun = (deps.isHostScopedToolActive?.("openclaw") ?? isHostScopedAgentToolActive("openclaw")) && input.toolsAllow?.length === 1 && input.toolsAllow[0]?.trim().toLowerCase() === "openclaw";
|
|
1770
|
-
const messages = Array.isArray(input.messages) ? [...input.messages] : [];
|
|
1771
|
-
const modelRef = resolveModelRef(input);
|
|
1772
|
-
const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
|
|
1773
|
-
const sandboxSessionKey = readNonEmptyString(input.sandboxSessionKey) ?? readNonEmptyString(input.sessionKey) ?? readNonEmptyString(input.sessionId);
|
|
1774
|
-
const { sessionAgentId } = resolveSessionAgentIdsStrict({
|
|
1775
|
-
sessionKey: readNonEmptyString(input.sessionKey),
|
|
1776
|
-
config: input.config,
|
|
1777
|
-
agentId: readNonEmptyString(params.agentId)
|
|
1778
|
-
});
|
|
1779
|
-
const hookContextWindowFields = {
|
|
1780
|
-
...input.contextWindowInfo?.tokens ? { contextTokenBudget: input.contextWindowInfo.tokens } : input.contextTokenBudget ? { contextTokenBudget: input.contextTokenBudget } : {},
|
|
1781
|
-
...input.contextWindowInfo?.source ? { contextWindowSource: input.contextWindowInfo.source } : {},
|
|
1782
|
-
...input.contextWindowInfo?.referenceTokens ? { contextWindowReferenceTokens: input.contextWindowInfo.referenceTokens } : {}
|
|
1783
|
-
};
|
|
1784
|
-
return {
|
|
1785
|
-
settledToolFinalization,
|
|
1786
|
-
input,
|
|
1787
|
-
createToolBridge,
|
|
1788
|
-
ringZeroSystemAgentRun,
|
|
1789
|
-
messages,
|
|
1790
|
-
modelRef,
|
|
1791
|
-
resolvedWorkspaceForSandbox,
|
|
1792
|
-
sandboxSessionKey,
|
|
1793
|
-
sessionAgentId,
|
|
1794
|
-
hookContextWindowFields,
|
|
1795
|
-
hookContext: {
|
|
1796
|
-
runId: input.runId,
|
|
1797
|
-
jobId: input.jobId,
|
|
1798
|
-
agentId: sessionAgentId,
|
|
1799
|
-
sessionKey: readNonEmptyString(input.sessionKey) ?? sandboxSessionKey,
|
|
1800
|
-
sessionId: input.sessionId,
|
|
1801
|
-
workspaceDir: resolvedWorkspaceForSandbox,
|
|
1802
|
-
modelProviderId: modelRef.provider,
|
|
1803
|
-
modelId: modelRef.id,
|
|
1804
|
-
trigger: input.trigger,
|
|
1805
|
-
inputProvenance: input.inputProvenance,
|
|
1806
|
-
foregroundPromptContext: buildEmbeddedForegroundPromptContext({
|
|
1807
|
-
...input,
|
|
1808
|
-
agentId: sessionAgentId
|
|
1809
|
-
}, input.agentDir ?? resolveAgentDir(input.config ?? {}, sessionAgentId)),
|
|
1810
|
-
...input.config ? { config: input.config } : {},
|
|
1811
|
-
...hookContextWindowFields,
|
|
1812
|
-
...buildAgentHookContextChannelFields(input)
|
|
1813
|
-
}
|
|
1814
|
-
};
|
|
1815
|
-
}
|
|
1816
|
-
async function resolveCopilotAttemptSandbox(params) {
|
|
1817
|
-
const resolveSandbox = params.deps.resolveSandboxContextOverride ?? resolveSandboxContext;
|
|
1818
|
-
const sandbox = params.input.sandbox !== void 0 ? params.input.sandbox : await resolveSandbox({
|
|
1819
|
-
config: params.input.config,
|
|
1820
|
-
agentId: params.input.sandboxAgentId,
|
|
1821
|
-
sessionKey: params.sandboxSessionKey,
|
|
1822
|
-
workspaceDir: params.resolvedWorkspaceForSandbox
|
|
1823
|
-
});
|
|
1824
|
-
const effectiveWorkspaceDir = sandbox?.enabled ? sandbox.workspaceAccess === "rw" ? params.resolvedWorkspaceForSandbox : sandbox.workspaceDir : params.resolvedWorkspaceForSandbox;
|
|
1825
|
-
if (sandbox?.enabled && effectiveWorkspaceDir !== params.resolvedWorkspaceForSandbox) await fsp.mkdir(effectiveWorkspaceDir, { recursive: true });
|
|
1826
|
-
return {
|
|
1827
|
-
sandbox,
|
|
1828
|
-
effectiveWorkspaceDir
|
|
1829
|
-
};
|
|
1830
|
-
}
|
|
1831
|
-
// extensions/copilot/src/prompt-guidance.ts
|
|
1832
|
-
const COPILOT_HARNESS_IDENTITY = "You are a personal agent running inside OpenClaw. Your available OpenClaw capabilities are policy-filtered for this turn; use only the exact tools exposed to you.";
|
|
1833
|
-
function buildCopilotPromptGuidance(params) {
|
|
1834
|
-
if (isRawCopilotModelRun(params.attempt)) return;
|
|
1835
|
-
const callableTools = new Set(normalizeUniqueStringEntries(params.callableToolNames));
|
|
1836
|
-
const hasSessionsSpawn = callableTools.has("sessions_spawn");
|
|
1837
|
-
const isMinimal = params.attempt.promptMode === "minimal";
|
|
1838
|
-
const extraSystemPrompt = readNonEmptyStringPreservingWhitespace(params.attempt.extraSystemPrompt)?.trim();
|
|
1839
|
-
const delegationGuidance = params.attempt.disableTools !== true && params.attempt.delegationCapability !== "report_only" ? buildDelegationGuidanceSection({
|
|
1840
|
-
mode: resolveMainSessionDelegationMode({
|
|
1841
|
-
config: params.attempt.config,
|
|
1842
|
-
agentId: params.attempt.agentId,
|
|
1843
|
-
sessionKey: params.attempt.sessionKey
|
|
1844
|
-
}),
|
|
1845
|
-
isMinimal,
|
|
1846
|
-
hiddenDelegationTool: hasSessionsSpawn ? "`sessions_spawn`" : "",
|
|
1847
|
-
hasVisibleSessionSpawn: hasSessionsSpawn,
|
|
1848
|
-
hasSessionsYield: callableTools.has("sessions_yield"),
|
|
1849
|
-
hasSubagentsList: callableTools.has("subagents"),
|
|
1850
|
-
hasSessionsSend: callableTools.has("sessions_send")
|
|
1851
|
-
}).join("\n") : void 0;
|
|
1852
|
-
return [
|
|
1853
|
-
COPILOT_HARNESS_IDENTITY,
|
|
1854
|
-
params.toolSchemaDirectoryPrompt,
|
|
1855
|
-
callableTools.has(SKILL_WORKSHOP_TOOL_NAME) ? buildSkillWorkshopPromptSection().join("\n") : void 0,
|
|
1856
|
-
delegationGuidance,
|
|
1857
|
-
buildHarnessVisibleReplyGuidance({
|
|
1858
|
-
sourceReplyDeliveryMode: params.attempt.sourceReplyDeliveryMode,
|
|
1859
|
-
messageToolAvailable: callableTools.has("message"),
|
|
1860
|
-
requireExplicitMessageTarget: params.requireExplicitMessageTarget
|
|
1861
|
-
}),
|
|
1862
|
-
buildCredentialSafetyPrompt({ controlToolsAvailable: params.attempt.disableTools !== true && (callableTools.has("openclaw") || callableTools.has("gateway")) }),
|
|
1863
|
-
params.workspaceBootstrapInstructions?.trim(),
|
|
1864
|
-
extraSystemPrompt ? `${isMinimal ? "## Subagent Context" : "## Conversation Context"}\n${extraSystemPrompt}` : void 0
|
|
1865
|
-
].filter((section) => section?.trim()).join("\n\n") || void 0;
|
|
1866
|
-
}
|
|
1867
1655
|
// extensions/copilot/src/user-input-bridge.ts
|
|
1868
1656
|
const COPILOT_USER_INPUT_QUESTION_ID = "answer";
|
|
1869
1657
|
const DEFAULT_USER_INPUT_TIMEOUT_MS = 9e5;
|
|
@@ -1874,9 +1662,6 @@ function createCopilotUserInputBridge(params) {
|
|
|
1874
1662
|
pending?.abort(/* @__PURE__ */ new Error("Copilot user input request replaced"));
|
|
1875
1663
|
const abort = new AbortController();
|
|
1876
1664
|
pending = abort;
|
|
1877
|
-
const abortFromRun = () => abort.abort(params.signal?.reason);
|
|
1878
|
-
params.signal?.addEventListener("abort", abortFromRun, { once: true });
|
|
1879
|
-
if (params.signal?.aborted) abortFromRun();
|
|
1880
1665
|
try {
|
|
1881
1666
|
const question = toQuestion(request);
|
|
1882
1667
|
const result = await runAgentHarnessGatewayQuestion({
|
|
@@ -1891,7 +1676,7 @@ function createCopilotUserInputBridge(params) {
|
|
|
1891
1676
|
intro: "Copilot needs input:",
|
|
1892
1677
|
formatText: formatCopilotDisplayText
|
|
1893
1678
|
},
|
|
1894
|
-
signal: abort.signal
|
|
1679
|
+
signal: params.signal ? AbortSignal.any([params.signal, abort.signal]) : abort.signal
|
|
1895
1680
|
});
|
|
1896
1681
|
if (result.status !== "answered") return emptyCopilotUserInputResponse();
|
|
1897
1682
|
const selected = result.answers.answers[COPILOT_USER_INPUT_QUESTION_ID]?.[0] ?? "";
|
|
@@ -1903,7 +1688,6 @@ function createCopilotUserInputBridge(params) {
|
|
|
1903
1688
|
embeddedAgentLog.warn("failed to bridge copilot user input through gateway", { error });
|
|
1904
1689
|
return emptyCopilotUserInputResponse();
|
|
1905
1690
|
} finally {
|
|
1906
|
-
params.signal?.removeEventListener("abort", abortFromRun);
|
|
1907
1691
|
if (pending === abort) pending = void 0;
|
|
1908
1692
|
}
|
|
1909
1693
|
},
|
|
@@ -1932,21 +1716,8 @@ function isChoiceAnswer(question, answer) {
|
|
|
1932
1716
|
return Boolean(answer && question.options?.some((option) => option.label.toLowerCase() === answer.toLowerCase()));
|
|
1933
1717
|
}
|
|
1934
1718
|
function formatCopilotDisplayText(value) {
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
function sanitizeCopilotDisplayText(value) {
|
|
1938
|
-
let safe = "";
|
|
1939
|
-
for (const character of value) {
|
|
1940
|
-
const codePoint = character.codePointAt(0);
|
|
1941
|
-
safe += codePoint != null && isUnsafeDisplayCodePoint(codePoint) ? "?" : character;
|
|
1942
|
-
}
|
|
1943
|
-
return safe;
|
|
1944
|
-
}
|
|
1945
|
-
function escapeCopilotChatText(value) {
|
|
1946
|
-
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("@", "@").replaceAll("`", "`").replaceAll("[", "[").replaceAll("]", "]").replaceAll("(", "(").replaceAll(")", ")").replaceAll("*", "∗").replaceAll("_", "_").replaceAll("~", "~").replaceAll("|", "|");
|
|
1947
|
-
}
|
|
1948
|
-
function isUnsafeDisplayCodePoint(codePoint) {
|
|
1949
|
-
return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint === 173 || codePoint === 1564 || codePoint === 6158 || codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8288 && codePoint <= 8303 || codePoint === 65279 || codePoint >= 65529 && codePoint <= 65531 || codePoint >= 917504 && codePoint <= 917631;
|
|
1719
|
+
const safe = sanitizeChatDisplayText(value).trim();
|
|
1720
|
+
return escapeChatDisplayText(safe || "<unknown>");
|
|
1950
1721
|
}
|
|
1951
1722
|
// extensions/copilot/src/workspace-bootstrap.ts
|
|
1952
1723
|
const COPILOT_NATIVE_PROJECT_DOC_BASENAMES = /* @__PURE__ */ new Set(["agents.md"]);
|
|
@@ -1961,62 +1732,50 @@ const COPILOT_BOOTSTRAP_CONTEXT_ORDER = /* @__PURE__ */ new Map([
|
|
|
1961
1732
|
]);
|
|
1962
1733
|
async function loadCopilotWorkspaceInstructions(params) {
|
|
1963
1734
|
const { attempt } = params;
|
|
1964
|
-
const workspaceDir =
|
|
1735
|
+
const workspaceDir = readResolvedAttemptPath(attempt.workspaceDir);
|
|
1965
1736
|
if (!workspaceDir) return;
|
|
1966
1737
|
try {
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1738
|
+
const sourceContextFiles = (await resolveBootstrapContextForRun({
|
|
1739
|
+
workspaceDir,
|
|
1740
|
+
config: attempt.config,
|
|
1741
|
+
sessionKey: readNonBlankString(attempt.sessionKey),
|
|
1742
|
+
sessionId: readNonBlankString(attempt.sessionId),
|
|
1743
|
+
chatType: attempt.chatType,
|
|
1744
|
+
agentId: readNonBlankString(attempt.agentId),
|
|
1745
|
+
warn: params.warn,
|
|
1746
|
+
contextMode: attempt.bootstrapContextMode,
|
|
1747
|
+
runKind: attempt.bootstrapContextRunKind
|
|
1748
|
+
})).contextFiles;
|
|
1749
|
+
const targetWorkspaceDir = readResolvedAttemptPath(params.effectiveWorkspaceDir) ?? workspaceDir;
|
|
1750
|
+
const files = (workspaceDir === targetWorkspaceDir ? sourceContextFiles : sourceContextFiles.map((file) => {
|
|
1751
|
+
const relative = path.relative(workspaceDir, file.path);
|
|
1752
|
+
if (!isRelativePathInsideOrEqual(relative)) return file;
|
|
1753
|
+
return Object.assign({}, file, { path: relative === "" ? targetWorkspaceDir : path.join(targetWorkspaceDir, relative) });
|
|
1754
|
+
})).filter((file) => {
|
|
1755
|
+
const baseName = getCopilotContextFileBasename(file.path);
|
|
1756
|
+
return baseName.length > 0 && !COPILOT_NATIVE_PROJECT_DOC_BASENAMES.has(baseName);
|
|
1757
|
+
}).toSorted(compareCopilotContextFiles);
|
|
1758
|
+
if (files.length === 0) return;
|
|
1759
|
+
const hasSoulFile = files.some((file) => getCopilotContextFileBasename(file.path) === "soul.md");
|
|
1760
|
+
const lines = [
|
|
1761
|
+
"OpenClaw loaded these user-editable workspace files. Treat them as project/user context. The Copilot SDK loads AGENTS.md natively from its instruction directories, so AGENTS.md is not repeated here.",
|
|
1762
|
+
"",
|
|
1763
|
+
"# Project Context",
|
|
1764
|
+
"",
|
|
1765
|
+
"The following project context files have been loaded:"
|
|
1766
|
+
];
|
|
1767
|
+
if (hasSoulFile) lines.push("SOUL.md: persona/tone. Follow it unless higher-priority instructions override.");
|
|
1768
|
+
lines.push("");
|
|
1769
|
+
for (const file of files) lines.push(`## ${file.path}`, "", file.content, "");
|
|
1770
|
+
return lines.join("\n").trim();
|
|
1982
1771
|
} catch (error) {
|
|
1983
1772
|
params.warn?.(`[copilot-attempt] failed to load workspace bootstrap instructions: ${error instanceof Error ? error.message : String(error)}`);
|
|
1984
1773
|
return;
|
|
1985
1774
|
}
|
|
1986
1775
|
}
|
|
1987
|
-
function remapCopilotBootstrapContextFiles(params) {
|
|
1988
|
-
if (params.sourceWorkspaceDir === params.targetWorkspaceDir) return params.files;
|
|
1989
|
-
return params.files.map((file) => {
|
|
1990
|
-
const relative = path.relative(params.sourceWorkspaceDir, file.path);
|
|
1991
|
-
if (!isRelativePathInsideOrEqual(relative)) return file;
|
|
1992
|
-
return {
|
|
1993
|
-
...file,
|
|
1994
|
-
path: relative === "" ? params.targetWorkspaceDir : path.join(params.targetWorkspaceDir, relative)
|
|
1995
|
-
};
|
|
1996
|
-
});
|
|
1997
|
-
}
|
|
1998
1776
|
function isRelativePathInsideOrEqual(relativePath) {
|
|
1999
1777
|
return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
|
|
2000
1778
|
}
|
|
2001
|
-
function renderCopilotWorkspaceBootstrapInstructions(contextFiles) {
|
|
2002
|
-
const files = contextFiles.filter((file) => {
|
|
2003
|
-
const baseName = getCopilotContextFileBasename(file.path);
|
|
2004
|
-
return baseName.length > 0 && !COPILOT_NATIVE_PROJECT_DOC_BASENAMES.has(baseName);
|
|
2005
|
-
}).toSorted(compareCopilotContextFiles);
|
|
2006
|
-
if (files.length === 0) return;
|
|
2007
|
-
const hasSoulFile = files.some((file) => getCopilotContextFileBasename(file.path) === "soul.md");
|
|
2008
|
-
const lines = [
|
|
2009
|
-
"OpenClaw loaded these user-editable workspace files. Treat them as project/user context. The Copilot SDK loads AGENTS.md natively from its instruction directories, so AGENTS.md is not repeated here.",
|
|
2010
|
-
"",
|
|
2011
|
-
"# Project Context",
|
|
2012
|
-
"",
|
|
2013
|
-
"The following project context files have been loaded:"
|
|
2014
|
-
];
|
|
2015
|
-
if (hasSoulFile) lines.push("SOUL.md: persona/tone. Follow it unless higher-priority instructions override.");
|
|
2016
|
-
lines.push("");
|
|
2017
|
-
for (const file of files) lines.push(`## ${file.path}`, "", file.content, "");
|
|
2018
|
-
return lines.join("\n").trim();
|
|
2019
|
-
}
|
|
2020
1779
|
function compareCopilotContextFiles(left, right) {
|
|
2021
1780
|
const leftBase = getCopilotContextFileBasename(left.path);
|
|
2022
1781
|
const rightBase = getCopilotContextFileBasename(right.path);
|
|
@@ -2035,15 +1794,10 @@ function normalizeCopilotContextFilePath(filePath) {
|
|
|
2035
1794
|
function getCopilotContextFileBasename(filePath) {
|
|
2036
1795
|
return normalizeCopilotContextFilePath(filePath).split("/").pop() ?? "";
|
|
2037
1796
|
}
|
|
2038
|
-
function readResolvedWorkspacePath(value) {
|
|
2039
|
-
const raw = readNonBlankString(value);
|
|
2040
|
-
if (!raw) return;
|
|
2041
|
-
if (process.platform !== "win32" && /^[A-Za-z]:[\\/]/.test(raw)) return raw.trim();
|
|
2042
|
-
return resolveUserPath(raw);
|
|
2043
|
-
}
|
|
2044
1797
|
// extensions/copilot/src/attempt-session-setup.ts
|
|
1798
|
+
const COPILOT_HARNESS_IDENTITY = "You are a personal agent running inside OpenClaw. Your available OpenClaw capabilities are policy-filtered for this turn; use only the exact tools exposed to you.";
|
|
2045
1799
|
async function createCopilotSessionSetup(params) {
|
|
2046
|
-
const { attempt: input, byokProxy, effectiveCwd, effectiveWorkspaceDir, hookContext, modelRef, messages,
|
|
1800
|
+
const { attempt: input, byokProxy, effectiveCwd, effectiveWorkspaceDir, hookContext, modelRef, messages, poolAcquire, ringZeroSystemAgentRun, promptToolPolicy, sessionProvider, settledToolFinalization, signal } = params;
|
|
2047
1801
|
const ordinaryAttemptInput = settledToolFinalization ? void 0 : (() => {
|
|
2048
1802
|
assertCopilotAttemptHostCapabilities(input);
|
|
2049
1803
|
return input;
|
|
@@ -2076,13 +1830,44 @@ async function createCopilotSessionSetup(params) {
|
|
|
2076
1830
|
toolsAllow,
|
|
2077
1831
|
forceToolNames
|
|
2078
1832
|
});
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
1833
|
+
if (isRawCopilotModelRun(input)) return;
|
|
1834
|
+
const callableTools = new Set(normalizeUniqueStringEntries(promptPolicyResult.callableToolNames));
|
|
1835
|
+
const hasSessionsSpawn = callableTools.has("sessions_spawn");
|
|
1836
|
+
const isMinimal = input.promptMode === "minimal";
|
|
1837
|
+
const extraSystemPrompt = readNonEmptyStringPreservingWhitespace(input.extraSystemPrompt)?.trim();
|
|
1838
|
+
const delegationGuidance = input.disableTools !== true && input.delegationCapability !== "report_only" ? buildDelegationGuidanceSection({
|
|
1839
|
+
mode: resolveMainSessionDelegationMode({
|
|
1840
|
+
config: input.config,
|
|
1841
|
+
agentId: input.agentId,
|
|
1842
|
+
sessionKey: input.sessionKey
|
|
1843
|
+
}),
|
|
1844
|
+
isMinimal,
|
|
1845
|
+
hiddenDelegationTool: hasSessionsSpawn ? "`sessions_spawn`" : "",
|
|
1846
|
+
hasVisibleSessionSpawn: hasSessionsSpawn,
|
|
1847
|
+
hasSessionsYield: callableTools.has("sessions_yield"),
|
|
1848
|
+
hasSubagentsList: callableTools.has("subagents"),
|
|
1849
|
+
hasSessionsSend: callableTools.has("sessions_send")
|
|
1850
|
+
}).join("\n") : void 0;
|
|
1851
|
+
return [
|
|
1852
|
+
COPILOT_HARNESS_IDENTITY,
|
|
1853
|
+
promptPolicyResult.toolSchemaDirectoryPrompt,
|
|
1854
|
+
callableTools.has(SKILL_WORKSHOP_TOOL_NAME) ? buildSkillWorkshopPromptSection().join("\n") : void 0,
|
|
1855
|
+
delegationGuidance,
|
|
1856
|
+
buildHarnessVisibleReplyGuidance({
|
|
1857
|
+
sourceReplyDeliveryMode: input.sourceReplyDeliveryMode,
|
|
1858
|
+
messageToolAvailable: callableTools.has("message"),
|
|
1859
|
+
currentConversation: {
|
|
1860
|
+
agentSessionKey: input.sessionKey,
|
|
1861
|
+
currentChannelProvider: input.messageChannel ?? input.messageProvider,
|
|
1862
|
+
currentChannelId: input.currentChannelId,
|
|
1863
|
+
currentMessagingTarget: input.currentMessagingTarget
|
|
1864
|
+
},
|
|
1865
|
+
requireExplicitMessageTarget: promptToolPolicy.requireExplicitMessageTarget
|
|
1866
|
+
}),
|
|
1867
|
+
buildCredentialSafetyPrompt({ controlToolsAvailable: input.disableTools !== true && (callableTools.has("openclaw") || callableTools.has("gateway")) }),
|
|
1868
|
+
workspaceBootstrapInstructions?.trim(),
|
|
1869
|
+
extraSystemPrompt ? `${isMinimal ? "## Subagent Context" : "## Conversation Context"}\n${extraSystemPrompt}` : void 0
|
|
1870
|
+
].filter((section) => section?.trim()).join("\n\n") || void 0;
|
|
2086
1871
|
} },
|
|
2087
1872
|
messages,
|
|
2088
1873
|
ctx: hookContext,
|
|
@@ -2127,11 +1912,36 @@ async function createCopilotSessionSetup(params) {
|
|
|
2127
1912
|
signal
|
|
2128
1913
|
});
|
|
2129
1914
|
})();
|
|
2130
|
-
const buildSessionConfig = (provider) =>
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
1915
|
+
const buildSessionConfig = (provider) => {
|
|
1916
|
+
const onUserInputRequest = userInputBridge?.onUserInputRequest;
|
|
1917
|
+
const permissionPolicy = settledToolFinalization ? rejectAllPolicy : attemptInput.permissionPolicy ?? rejectAllPolicy;
|
|
1918
|
+
const hooks = settledToolFinalization ? void 0 : createHooksBridge(attemptInput.hooksConfig, hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0);
|
|
1919
|
+
const availableTools = promptTools.map((tool) => tool.name);
|
|
1920
|
+
if (includeAskUser) availableTools.push(...COPILOT_ASK_USER_AVAILABLE_TOOLS);
|
|
1921
|
+
return {
|
|
1922
|
+
model: modelRef.id,
|
|
1923
|
+
onPermissionRequest: createPermissionBridge(permissionPolicy),
|
|
1924
|
+
...onUserInputRequest ? { onUserInputRequest } : {},
|
|
1925
|
+
...provider.provider ? { provider: provider.provider } : {},
|
|
1926
|
+
...hooks ? { hooks } : {},
|
|
1927
|
+
...attemptInput.enableSessionTelemetry !== void 0 ? { enableSessionTelemetry: attemptInput.enableSessionTelemetry } : {},
|
|
1928
|
+
...settledToolFinalization ? {} : attemptInput.infiniteSessionConfig ? { infiniteSessions: attemptInput.infiniteSessionConfig } : {},
|
|
1929
|
+
reasoningEffort: attemptInput.reasoningEffort,
|
|
1930
|
+
tools: promptTools,
|
|
1931
|
+
availableTools: [...new Set(availableTools)],
|
|
1932
|
+
...settledToolFinalization ? createCopilotIsolatedSessionRestrictions() : {},
|
|
1933
|
+
workingDirectory: effectiveCwd ?? effectiveWorkspaceDir ?? readResolvedAttemptPath(attemptInput.workspaceDir),
|
|
1934
|
+
...!settledToolFinalization && effectiveWorkspaceDir && effectiveCwd && effectiveCwd !== effectiveWorkspaceDir ? { instructionDirectories: [effectiveWorkspaceDir] } : {},
|
|
1935
|
+
...poolAcquire.auth.authMode === "gitHubToken" && poolAcquire.auth.gitHubToken ? { gitHubToken: poolAcquire.auth.gitHubToken } : {},
|
|
1936
|
+
...settledToolFinalization ? { systemMessage: {
|
|
1937
|
+
mode: "customize",
|
|
1938
|
+
content: COPILOT_SETTLED_FINALIZATION_SYSTEM_MESSAGE
|
|
1939
|
+
} } : finalDeveloperInstructions ? { systemMessage: {
|
|
1940
|
+
mode: "append",
|
|
1941
|
+
content: finalDeveloperInstructions
|
|
1942
|
+
} } : {}
|
|
1943
|
+
};
|
|
1944
|
+
};
|
|
2135
1945
|
const sessionConfig = buildSessionConfig(sessionProvider);
|
|
2136
1946
|
return {
|
|
2137
1947
|
attemptInput,
|
|
@@ -2191,6 +2001,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2191
2001
|
const hiddenTurn = params.attempt.trigger === "memory";
|
|
2192
2002
|
const projectDisplay = (message) => projectAgentHarnessTranscriptMessageForDisplay({
|
|
2193
2003
|
hidden: hiddenTurn || message.display === false,
|
|
2004
|
+
inputProvenance: params.attempt.inputProvenance,
|
|
2194
2005
|
message
|
|
2195
2006
|
});
|
|
2196
2007
|
const messagesSnapshot = [...params.messages];
|
|
@@ -2267,7 +2078,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2267
2078
|
};
|
|
2268
2079
|
const prepare = (write, options = {}) => {
|
|
2269
2080
|
assertMemoryOwnerCurrent();
|
|
2270
|
-
const message =
|
|
2081
|
+
const message = write.message;
|
|
2271
2082
|
const originalReplayPayload = projectReplayPayload(message);
|
|
2272
2083
|
const hooked = runAgentHarnessBeforeMessageWriteHook({
|
|
2273
2084
|
message: structuredClone(message),
|
|
@@ -2275,6 +2086,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2275
2086
|
sessionKey: owner.kind === "durable" ? owner.target.sessionKey : params.attempt.sessionKey,
|
|
2276
2087
|
prepareAssistantTranscriptMessage: options.singleton && !hiddenTurn ? params.attempt.prepareAssistantTranscriptMessage : void 0
|
|
2277
2088
|
});
|
|
2089
|
+
assertMemoryOwnerCurrent();
|
|
2278
2090
|
if (!hooked) return;
|
|
2279
2091
|
if (!isDeepStrictEqual(originalReplayPayload, projectReplayPayload(hooked))) replayInvalid = true;
|
|
2280
2092
|
const idempotencyKey = message.idempotencyKey;
|
|
@@ -2340,7 +2152,10 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2340
2152
|
const persistedKeys = owner.kind === "memory" ? new Set(owner.manager.getEntries().flatMap((entry) => {
|
|
2341
2153
|
const key = entry.type === "message" ? readIdempotencyKey(entry.message) : void 0;
|
|
2342
2154
|
return key ? [key] : [];
|
|
2343
|
-
})) :
|
|
2155
|
+
})) : (await withSessionTranscriptWrite(owner.target, (transcript) => transcript.readMessageFacts({
|
|
2156
|
+
idempotencyKeys: keys.filter((key) => key !== void 0),
|
|
2157
|
+
activeBranchOnly: true
|
|
2158
|
+
}))).existingIdempotencyKeys;
|
|
2344
2159
|
const persistedCount = keys.filter((key) => key && persistedKeys.has(key)).length;
|
|
2345
2160
|
if (persistedCount > 0 && persistedCount < writes.length) throw new Error("Copilot transcript found a partial persisted tool group");
|
|
2346
2161
|
const messages = persistedCount === writes.length ? writes.map((write) => write.message) : writes.map((write) => prepare(write));
|
|
@@ -2620,7 +2435,7 @@ function isCurrentJournalIdentity(key, params) {
|
|
|
2620
2435
|
}
|
|
2621
2436
|
// extensions/copilot/src/attempt-execution.ts
|
|
2622
2437
|
async function runCopilotExecution(context) {
|
|
2623
|
-
const { params, deps, now, attemptStartedAt, settledToolFinalization, input,
|
|
2438
|
+
const { params, deps, now, attemptStartedAt, settledToolFinalization, input, ringZeroSystemAgentRun, messages, modelRef, resolvedWorkspaceForSandbox, sandboxSessionKey, sessionAgentId, hookContextWindowFields, hookContext, finishAttempt, settledFinalizationSessionId } = context;
|
|
2624
2439
|
let abortRequested = false;
|
|
2625
2440
|
let aborted = false;
|
|
2626
2441
|
let externalAbort = false;
|
|
@@ -2631,17 +2446,19 @@ async function runCopilotExecution(context) {
|
|
|
2631
2446
|
let timedOut = false;
|
|
2632
2447
|
let promptError;
|
|
2633
2448
|
let sdkSessionId;
|
|
2449
|
+
let runtimeArtifact;
|
|
2634
2450
|
let nativeSessionCreatedFresh = false;
|
|
2635
2451
|
let nativeSessionHistoryValidated = false;
|
|
2636
|
-
let disconnectError;
|
|
2637
2452
|
let handle;
|
|
2638
2453
|
let session;
|
|
2639
2454
|
let bridge;
|
|
2640
2455
|
let transcriptJournal;
|
|
2641
2456
|
let initialSdkUserValidated = false;
|
|
2642
|
-
let
|
|
2457
|
+
let activeRunRegistrationRef;
|
|
2643
2458
|
let userInputBridgeRef;
|
|
2644
2459
|
let cleanupToolBridge;
|
|
2460
|
+
let settleToolCalls;
|
|
2461
|
+
const detached = input.sessionPersistence === "detached";
|
|
2645
2462
|
let releaseError;
|
|
2646
2463
|
let downgradedFromResume = false;
|
|
2647
2464
|
let resumeFailureRecovered = false;
|
|
@@ -2661,6 +2478,7 @@ async function runCopilotExecution(context) {
|
|
|
2661
2478
|
aborted = true;
|
|
2662
2479
|
};
|
|
2663
2480
|
const abortActiveSession = () => {
|
|
2481
|
+
if (abortRequested) return;
|
|
2664
2482
|
markExternalAbort();
|
|
2665
2483
|
if (settled || !sentTurnStarted || !session) return;
|
|
2666
2484
|
session.abort().catch(() => void 0);
|
|
@@ -2669,7 +2487,6 @@ async function runCopilotExecution(context) {
|
|
|
2669
2487
|
let effectiveWorkspaceDir = resolvedWorkspaceForSandbox;
|
|
2670
2488
|
if (resolvedWorkspaceForSandbox) try {
|
|
2671
2489
|
({sandbox, effectiveWorkspaceDir} = await resolveCopilotAttemptSandbox({
|
|
2672
|
-
deps,
|
|
2673
2490
|
input,
|
|
2674
2491
|
resolvedWorkspaceForSandbox,
|
|
2675
2492
|
sandboxSessionKey
|
|
@@ -2679,21 +2496,18 @@ async function runCopilotExecution(context) {
|
|
|
2679
2496
|
aborted: true,
|
|
2680
2497
|
externalAbort: true,
|
|
2681
2498
|
messagesSnapshot: messages,
|
|
2682
|
-
promptError: void 0
|
|
2683
|
-
sdkSessionId: void 0
|
|
2499
|
+
promptError: void 0
|
|
2684
2500
|
}));
|
|
2685
2501
|
return finishAttempt(createResult(input, {
|
|
2686
2502
|
messagesSnapshot: messages,
|
|
2687
|
-
promptError: createPromptError("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error)
|
|
2688
|
-
sdkSessionId: void 0
|
|
2503
|
+
promptError: createPromptError("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error)
|
|
2689
2504
|
}));
|
|
2690
2505
|
}
|
|
2691
2506
|
hookContext.workspaceDir = effectiveWorkspaceDir;
|
|
2692
2507
|
const requestedCwd = readResolvedAttemptPath(input.cwd);
|
|
2693
2508
|
if (sandbox?.enabled && requestedCwd && requestedCwd !== resolvedWorkspaceForSandbox) return finishAttempt(createResult(input, {
|
|
2694
2509
|
messagesSnapshot: messages,
|
|
2695
|
-
promptError: createPromptError("sandbox_cwd_override_unsupported", "[copilot-attempt] cwd override is not supported for sandboxed Copilot runs; omit cwd or use the agent workspace as cwd")
|
|
2696
|
-
sdkSessionId: void 0
|
|
2510
|
+
promptError: createPromptError("sandbox_cwd_override_unsupported", "[copilot-attempt] cwd override is not supported for sandboxed Copilot runs; omit cwd or use the agent workspace as cwd")
|
|
2697
2511
|
}));
|
|
2698
2512
|
const effectiveCwd = sandbox?.enabled ? effectiveWorkspaceDir : requestedCwd ?? effectiveWorkspaceDir;
|
|
2699
2513
|
const effectiveFsWorkspaceOnly = resolveAttemptFsWorkspaceOnly({
|
|
@@ -2718,8 +2532,7 @@ async function runCopilotExecution(context) {
|
|
|
2718
2532
|
} catch (error) {
|
|
2719
2533
|
return finishAttempt(createResult(input, {
|
|
2720
2534
|
messagesSnapshot: messages,
|
|
2721
|
-
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
2722
|
-
sdkSessionId: void 0
|
|
2535
|
+
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
2723
2536
|
}));
|
|
2724
2537
|
}
|
|
2725
2538
|
const cleanupByokProxy = byokProxy?.close;
|
|
@@ -2729,12 +2542,13 @@ async function runCopilotExecution(context) {
|
|
|
2729
2542
|
let codeModeEngaged;
|
|
2730
2543
|
let promptToolPolicy;
|
|
2731
2544
|
try {
|
|
2545
|
+
if (!settledToolFinalization && effectiveCwd && !sandbox?.enabled) input.hostCapabilities?.prepareContinuationRetryCount?.({ cwd: effectiveCwd });
|
|
2732
2546
|
params.abortSignal?.addEventListener("abort", abortActiveSession, { once: true });
|
|
2733
2547
|
if (params.abortSignal?.aborted) abortActiveSession();
|
|
2734
2548
|
let resultContentSourceByToolName = /* @__PURE__ */ new Map();
|
|
2735
2549
|
if (!settledToolFinalization) try {
|
|
2736
2550
|
assertCopilotAttemptHostCapabilities(input);
|
|
2737
|
-
const toolBridge = await
|
|
2551
|
+
const toolBridge = await createCopilotToolBridge({
|
|
2738
2552
|
allowModelTools: poolAcquire.provider.mode === "byok",
|
|
2739
2553
|
modelProvider: modelRef.provider,
|
|
2740
2554
|
modelId: modelRef.id,
|
|
@@ -2776,17 +2590,20 @@ async function runCopilotExecution(context) {
|
|
|
2776
2590
|
}
|
|
2777
2591
|
});
|
|
2778
2592
|
cleanupToolBridge = toolBridge.cleanup;
|
|
2593
|
+
settleToolCalls = toolBridge.settle;
|
|
2779
2594
|
codeModeEngaged = toolBridge.codeModeEngaged;
|
|
2780
2595
|
promptToolPolicy = toolBridge.promptToolPolicy;
|
|
2781
2596
|
resultContentSourceByToolName = new Map(toolBridge.sourceTools.flatMap((tool) => tool.resultContentSource ? [[tool.name, tool.resultContentSource]] : []));
|
|
2782
2597
|
} catch (error) {
|
|
2783
2598
|
return finishAttempt(createResult(input, {
|
|
2784
2599
|
messagesSnapshot: messages,
|
|
2785
|
-
promptError: createPromptError("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error)
|
|
2786
|
-
sdkSessionId: void 0
|
|
2600
|
+
promptError: createPromptError("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error)
|
|
2787
2601
|
}));
|
|
2788
2602
|
}
|
|
2789
|
-
|
|
2603
|
+
const artifactRequest = input.captureRuntimeArtifact || input.expectedRuntimeArtifact ? { expected: input.expectedRuntimeArtifact } : void 0;
|
|
2604
|
+
handle = artifactRequest ? await deps.pool.acquire(poolAcquire.key, poolAcquire.options, artifactRequest) : await deps.pool.acquire(poolAcquire.key, poolAcquire.options);
|
|
2605
|
+
runtimeArtifact = handle.runtimeArtifact;
|
|
2606
|
+
if (artifactRequest && !runtimeArtifact) throw new Error("[copilot] verified attempt requires a captured runtime artifact");
|
|
2790
2607
|
const client = handle.client;
|
|
2791
2608
|
const sessionSetup = await createCopilotSessionSetup({
|
|
2792
2609
|
attempt: input,
|
|
@@ -2796,7 +2613,6 @@ async function runCopilotExecution(context) {
|
|
|
2796
2613
|
hookContext,
|
|
2797
2614
|
modelRef,
|
|
2798
2615
|
messages,
|
|
2799
|
-
operation: deps.operation,
|
|
2800
2616
|
poolAcquire,
|
|
2801
2617
|
ringZeroSystemAgentRun,
|
|
2802
2618
|
promptToolPolicy,
|
|
@@ -2806,7 +2622,7 @@ async function runCopilotExecution(context) {
|
|
|
2806
2622
|
});
|
|
2807
2623
|
const { attemptInput, compactionSessionConfig, emitLlmInput, hasNativePromptHook, sessionConfig, userInputBridge } = sessionSetup;
|
|
2808
2624
|
userInputBridgeRef = userInputBridge;
|
|
2809
|
-
const previousSessionId = normalizeOptionalString(input.initialReplayState?.sdkSessionId);
|
|
2625
|
+
const previousSessionId = detached ? void 0 : normalizeOptionalString(input.initialReplayState?.sdkSessionId);
|
|
2810
2626
|
downgradedFromResume = Boolean(previousSessionId && input.initialReplayState?.replayInvalid === true);
|
|
2811
2627
|
const resumeSessionId = settledToolFinalization ? settledFinalizationSessionId : downgradedFromResume ? void 0 : previousSessionId;
|
|
2812
2628
|
if (resumeSessionId) try {
|
|
@@ -2887,7 +2703,7 @@ async function runCopilotExecution(context) {
|
|
|
2887
2703
|
if (!settledToolFinalization) {
|
|
2888
2704
|
assertCopilotAttemptHostCapabilities(input);
|
|
2889
2705
|
if (!userInputBridge) throw new Error("[copilot-attempt] ordinary attempts require a user-input bridge");
|
|
2890
|
-
|
|
2706
|
+
activeRunRegistrationRef = registerCopilotActiveRun({
|
|
2891
2707
|
abortActiveSession,
|
|
2892
2708
|
agentId: sessionAgentId,
|
|
2893
2709
|
bridge,
|
|
@@ -2955,6 +2771,7 @@ async function runCopilotExecution(context) {
|
|
|
2955
2771
|
}
|
|
2956
2772
|
} finally {
|
|
2957
2773
|
settled = true;
|
|
2774
|
+
if (detached) await settleToolCalls?.();
|
|
2958
2775
|
try {
|
|
2959
2776
|
bridge?.flushTranscriptProjection();
|
|
2960
2777
|
await transcriptJournal?.barrier("bridge detach");
|
|
@@ -2962,34 +2779,35 @@ async function runCopilotExecution(context) {
|
|
|
2962
2779
|
promptError = toCopilotError(transcriptError);
|
|
2963
2780
|
}
|
|
2964
2781
|
userInputBridgeRef?.cancelPending();
|
|
2965
|
-
if (
|
|
2966
|
-
|
|
2967
|
-
clearActiveEmbeddedRun(input.sessionId,
|
|
2782
|
+
if (activeRunRegistrationRef) {
|
|
2783
|
+
const { attachment, handle: activeRunHandle } = activeRunRegistrationRef;
|
|
2784
|
+
clearActiveEmbeddedRun(input.sessionId, activeRunHandle, input.sessionKey, input.sessionFile, void 0, attachment);
|
|
2968
2785
|
}
|
|
2969
2786
|
const journalSnapshot = transcriptJournal?.snapshot();
|
|
2970
2787
|
const initialUserValidated = !sentTurnStarted || settledToolFinalization || journalSnapshot?.initialSdkUserValidated === true;
|
|
2971
2788
|
if (journalSnapshot?.replayInvalid !== true && (bridge?.hasObservedCompaction() || timedOut && bridge?.hasObservedSessionIdle() === false) && bridge && session && handle) {
|
|
2972
2789
|
const cleanupAbort = new AbortController();
|
|
2973
|
-
const abortCleanup = () => cleanupAbort.abort();
|
|
2974
|
-
if (params.abortSignal?.aborted) abortCleanup();
|
|
2975
|
-
else params.abortSignal?.addEventListener("abort", abortCleanup, { once: true });
|
|
2976
2790
|
const cleanup = deferBackgroundCompactionCleanup({
|
|
2977
|
-
abortSignal: cleanupAbort.signal,
|
|
2791
|
+
abortSignal: params.abortSignal ? AbortSignal.any([params.abortSignal, cleanupAbort.signal]) : cleanupAbort.signal,
|
|
2978
2792
|
awaitSessionIdle: !bridge.hasObservedSessionIdle(),
|
|
2979
2793
|
bridge,
|
|
2980
2794
|
cleanupToolBridge,
|
|
2981
2795
|
cleanupByokProxy,
|
|
2982
2796
|
deleteSessionOnIncompleteCleanup: nativeSessionCreatedFresh && initialUserValidated,
|
|
2797
|
+
deleteSessionOnCleanup: detached && nativeSessionCreatedFresh,
|
|
2983
2798
|
handle,
|
|
2984
2799
|
pool: deps.pool,
|
|
2985
2800
|
sdkSessionId,
|
|
2986
2801
|
session,
|
|
2987
2802
|
timeoutMs: resolveCompactionTimeoutMs(input.config)
|
|
2988
2803
|
});
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
}
|
|
2992
|
-
|
|
2804
|
+
if (detached) try {
|
|
2805
|
+
await cleanup;
|
|
2806
|
+
} catch (error) {
|
|
2807
|
+
promptError = preserveCopilotAttemptCleanupError(promptError, error);
|
|
2808
|
+
}
|
|
2809
|
+
else cleanup.catch(() => void 0);
|
|
2810
|
+
if (!detached && sdkSessionId && !settledToolFinalization) try {
|
|
2993
2811
|
await deps.onDeferredCompaction?.({
|
|
2994
2812
|
abort: () => cleanupAbort.abort(),
|
|
2995
2813
|
cleanup,
|
|
@@ -3002,13 +2820,22 @@ async function runCopilotExecution(context) {
|
|
|
3002
2820
|
bridge?.detach();
|
|
3003
2821
|
await bridge?.awaitAgentEventChain();
|
|
3004
2822
|
cleanupToolBridge?.();
|
|
3005
|
-
|
|
2823
|
+
try {
|
|
2824
|
+
await cleanupByokProxy?.();
|
|
2825
|
+
} catch (error) {
|
|
2826
|
+
if (detached) promptError = preserveCopilotAttemptCleanupError(promptError, error);
|
|
2827
|
+
else releaseError = toCopilotError(error);
|
|
2828
|
+
}
|
|
3006
2829
|
params.abortSignal?.removeEventListener("abort", abortActiveSession);
|
|
3007
|
-
if (session) try {
|
|
3008
|
-
await
|
|
2830
|
+
if (session && handle) try {
|
|
2831
|
+
await disconnectCopilotSession({
|
|
2832
|
+
session,
|
|
2833
|
+
client: handle.client,
|
|
2834
|
+
deleteSessionId: detached && nativeSessionCreatedFresh ? sdkSessionId : void 0
|
|
2835
|
+
});
|
|
3009
2836
|
} catch (error) {
|
|
3010
|
-
|
|
3011
|
-
if (!promptError && !timedOut) promptError =
|
|
2837
|
+
if (detached) promptError = preserveCopilotAttemptCleanupError(promptError, error);
|
|
2838
|
+
else if (!promptError && !timedOut) promptError = toCopilotError(error);
|
|
3012
2839
|
}
|
|
3013
2840
|
if (handle) try {
|
|
3014
2841
|
await deps.pool.release(handle);
|
|
@@ -3039,6 +2866,7 @@ async function runCopilotExecution(context) {
|
|
|
3039
2866
|
promptError,
|
|
3040
2867
|
releaseError,
|
|
3041
2868
|
resumeFailureRecovered,
|
|
2869
|
+
runtimeArtifact,
|
|
3042
2870
|
sdkSessionId,
|
|
3043
2871
|
sentTurnStarted,
|
|
3044
2872
|
settledFinalizationAssistantCompleted,
|
|
@@ -3051,7 +2879,7 @@ async function runCopilotExecution(context) {
|
|
|
3051
2879
|
}
|
|
3052
2880
|
// extensions/copilot/src/attempt.ts
|
|
3053
2881
|
async function runCopilotAttempt(params, deps) {
|
|
3054
|
-
const now =
|
|
2882
|
+
const now = Date.now;
|
|
3055
2883
|
const attemptStartedAt = now();
|
|
3056
2884
|
const prepared = prepareCopilotAttemptContext(params, deps);
|
|
3057
2885
|
const { settledToolFinalization, input, messages, modelRef, hookContext } = prepared;
|
|
@@ -3060,8 +2888,7 @@ async function runCopilotAttempt(params, deps) {
|
|
|
3060
2888
|
aborted: true,
|
|
3061
2889
|
externalAbort: true,
|
|
3062
2890
|
messagesSnapshot: messages,
|
|
3063
|
-
promptError: void 0
|
|
3064
|
-
sdkSessionId: void 0
|
|
2891
|
+
promptError: void 0
|
|
3065
2892
|
}));
|
|
3066
2893
|
try {
|
|
3067
2894
|
resolveCopilotProvider({
|
|
@@ -3072,15 +2899,13 @@ async function runCopilotAttempt(params, deps) {
|
|
|
3072
2899
|
} catch (error) {
|
|
3073
2900
|
return finishAttempt(createResult(input, {
|
|
3074
2901
|
messagesSnapshot: messages,
|
|
3075
|
-
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
3076
|
-
sdkSessionId: void 0
|
|
2902
|
+
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
3077
2903
|
}));
|
|
3078
2904
|
}
|
|
3079
2905
|
const settledFinalizationSessionId = settledToolFinalization ? readNonEmptyString(input.initialReplayState?.sdkSessionId) : void 0;
|
|
3080
2906
|
if (settledToolFinalization && !settledFinalizationSessionId) return finishAttempt(createResult(input, {
|
|
3081
2907
|
messagesSnapshot: messages,
|
|
3082
|
-
promptError: createPromptError("settled_finalization_session_unavailable", "[copilot-attempt] settled tool finalization requires the existing Copilot SDK session")
|
|
3083
|
-
sdkSessionId: void 0
|
|
2908
|
+
promptError: createPromptError("settled_finalization_session_unavailable", "[copilot-attempt] settled tool finalization requires the existing Copilot SDK session")
|
|
3084
2909
|
}));
|
|
3085
2910
|
return await runCopilotExecution({
|
|
3086
2911
|
...prepared,
|