@openclaw/copilot 2026.11.3 → 2026.11.5-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/dist/.setup/{attempt-Bu_STDE0.mjs → attempt-BE9PBSA2.mjs} +455 -632
- package/dist/.setup/{harness-Je_2Cj-D.mjs → harness-CZqo28FI.mjs} +184 -270
- package/dist/.setup/{isolated-completion-CrN9i842.mjs → isolated-completion-BeHQ8_kK.mjs} +20 -40
- package/dist/.setup/runtime-CtTtYION.mjs +153 -0
- package/dist/.setup/runtime-artifact-CS6Ndnjs.mjs +56 -0
- package/dist/.setup/sdk-loader-Ii715SxJ.mjs +146 -0
- package/dist/.setup/session-restrictions-kky_Sm86.mjs +226 -0
- package/dist/.source-module-urls/f7f35489a89dbc0fc6d0e80a0da5720af5de227b511e490a2415ffe55b1bc471.json +1 -0
- package/dist/harness.js +1 -2
- package/dist/index.js +1 -1
- package/package.json +5 -5
- package/dist/.setup/runtime-C0R_TFVt.mjs +0 -219
- package/dist/.setup/usage-bridge--rLPdCvV.mjs +0 -76
|
@@ -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-CZqo28FI.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-kky_Sm86.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
|
//#region 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"];
|
|
@@ -37,101 +37,6 @@ function assertCopilotAttemptHostCapabilities(params) {
|
|
|
37
37
|
if (!params.hostCapabilities) throw new Error("[copilot-attempt] ordinary attempts require host capabilities");
|
|
38
38
|
}
|
|
39
39
|
//#endregion
|
|
40
|
-
//#region extensions/copilot/src/hooks-bridge.ts
|
|
41
|
-
const DEFAULT_HOOK_ERROR_HANDLER = ({ hookName, error }) => {
|
|
42
|
-
console.warn(`[copilot hooks-bridge] ${hookName} handler threw:`, error);
|
|
43
|
-
};
|
|
44
|
-
/**
|
|
45
|
-
* Wrap a native handler so it cannot throw into the SDK. Returning undefined
|
|
46
|
-
* leaves the SDK's default decision in place.
|
|
47
|
-
*/
|
|
48
|
-
function isolate(hookName, handler, onError) {
|
|
49
|
-
if (!handler) return;
|
|
50
|
-
return async (...args) => {
|
|
51
|
-
try {
|
|
52
|
-
return await handler(...args);
|
|
53
|
-
} catch (error) {
|
|
54
|
-
try {
|
|
55
|
-
onError({
|
|
56
|
-
hookName,
|
|
57
|
-
error
|
|
58
|
-
});
|
|
59
|
-
} catch {}
|
|
60
|
-
return;
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Build an SDK-shaped hook object from native per-attempt configuration.
|
|
66
|
-
* Omit the SDK hook subsystem when no handlers were configured.
|
|
67
|
-
*/
|
|
68
|
-
function createHooksBridge(config, options) {
|
|
69
|
-
if (!config) return;
|
|
70
|
-
const onError = config.onHookError ?? DEFAULT_HOOK_ERROR_HANDLER;
|
|
71
|
-
const hooks = {};
|
|
72
|
-
const pre = isolate("onPreToolUse", config.onPreToolUse, onError);
|
|
73
|
-
const preMcp = isolate("onPreMcpToolCall", config.onPreMcpToolCall, onError);
|
|
74
|
-
const post = isolate("onPostToolUse", config.onPostToolUse, onError);
|
|
75
|
-
const postFailure = isolate("onPostToolUseFailure", config.onPostToolUseFailure, onError);
|
|
76
|
-
const userPrompt = isolate("onUserPromptSubmitted", config.onUserPromptSubmitted, onError);
|
|
77
|
-
const sessionStart = isolate("onSessionStart", config.onSessionStart, onError);
|
|
78
|
-
const sessionEnd = isolate("onSessionEnd", config.onSessionEnd, onError);
|
|
79
|
-
const errorOccurred = isolate("onErrorOccurred", config.onErrorOccurred, onError);
|
|
80
|
-
if (pre) hooks.onPreToolUse = pre;
|
|
81
|
-
if (preMcp) hooks.onPreMcpToolCall = preMcp;
|
|
82
|
-
if (post) hooks.onPostToolUse = post;
|
|
83
|
-
if (postFailure) hooks.onPostToolUseFailure = postFailure;
|
|
84
|
-
if (userPrompt) hooks.onUserPromptSubmitted = async (input, invocation) => {
|
|
85
|
-
const output = await userPrompt(input, invocation);
|
|
86
|
-
try {
|
|
87
|
-
options?.onUserPromptSubmitted?.({
|
|
88
|
-
prompt: output?.modifiedPrompt ?? input.prompt,
|
|
89
|
-
...output?.additionalContext ? { additionalContext: output.additionalContext } : {}
|
|
90
|
-
});
|
|
91
|
-
} catch (error) {
|
|
92
|
-
try {
|
|
93
|
-
onError({
|
|
94
|
-
hookName: "onUserPromptSubmitted",
|
|
95
|
-
error
|
|
96
|
-
});
|
|
97
|
-
} catch {}
|
|
98
|
-
}
|
|
99
|
-
return output;
|
|
100
|
-
};
|
|
101
|
-
if (sessionStart) hooks.onSessionStart = sessionStart;
|
|
102
|
-
if (sessionEnd) hooks.onSessionEnd = sessionEnd;
|
|
103
|
-
if (errorOccurred) hooks.onErrorOccurred = errorOccurred;
|
|
104
|
-
return Object.keys(hooks).length > 0 ? hooks : void 0;
|
|
105
|
-
}
|
|
106
|
-
//#endregion
|
|
107
|
-
//#region extensions/copilot/src/permission-bridge.ts
|
|
108
|
-
const REJECT_ALL_FEEDBACK = "copilot agent runtime: no permission policy installed (denied by default)";
|
|
109
|
-
const rejectAllPolicy = () => ({
|
|
110
|
-
kind: "reject",
|
|
111
|
-
feedback: REJECT_ALL_FEEDBACK
|
|
112
|
-
});
|
|
113
|
-
function createPermissionBridge(policy = rejectAllPolicy) {
|
|
114
|
-
return async (request, invocation) => {
|
|
115
|
-
const ctx = {
|
|
116
|
-
request,
|
|
117
|
-
sessionId: invocation.sessionId
|
|
118
|
-
};
|
|
119
|
-
try {
|
|
120
|
-
const result = await policy(ctx);
|
|
121
|
-
if (result !== void 0) return result;
|
|
122
|
-
} catch (error) {
|
|
123
|
-
return {
|
|
124
|
-
kind: "reject",
|
|
125
|
-
feedback: `copilot permission policy threw: ${formatErrorMessage(error)}`
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
return {
|
|
129
|
-
kind: "reject",
|
|
130
|
-
feedback: REJECT_ALL_FEEDBACK
|
|
131
|
-
};
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
//#endregion
|
|
135
40
|
//#region extensions/copilot/src/replay-shim.ts
|
|
136
41
|
const MISSING_SESSION_CODES = /* @__PURE__ */ new Set([
|
|
137
42
|
"SESSION_NOT_FOUND",
|
|
@@ -221,6 +126,7 @@ function createResult(params, state) {
|
|
|
221
126
|
} : { kind: "ok" };
|
|
222
127
|
return {
|
|
223
128
|
terminal: promptError !== void 0 ? withPromptFailure(interruption, promptError) : interruption,
|
|
129
|
+
...state.runtimeArtifact ? { runtimeArtifact: state.runtimeArtifact } : {},
|
|
224
130
|
...state.acceptedSessionSpawns?.length ? { acceptedSessionSpawns: state.acceptedSessionSpawns } : {},
|
|
225
131
|
...state.assistantTranscriptOwned ? {
|
|
226
132
|
assistantTranscriptOwned: true,
|
|
@@ -255,79 +161,42 @@ function createResult(params, state) {
|
|
|
255
161
|
...state.yieldAcknowledgment ? { yieldAcknowledgment: state.yieldAcknowledgment } : {}
|
|
256
162
|
};
|
|
257
163
|
}
|
|
258
|
-
function createSessionConfig(params, sdkModelId, sdkTools, resolvedAuth, resolvedProvider, systemMessageContent, effectiveWorkspaceDir, effectiveCwd, onUserInputRequest, options) {
|
|
259
|
-
const settledToolFinalization = options.operation === "settled-tool-finalization";
|
|
260
|
-
const permissionPolicy = settledToolFinalization ? rejectAllPolicy : params.permissionPolicy ?? rejectAllPolicy;
|
|
261
|
-
const hooks = settledToolFinalization ? void 0 : createHooksBridge(params.hooksConfig, options.hooksBridgeOptions);
|
|
262
|
-
return {
|
|
263
|
-
model: sdkModelId,
|
|
264
|
-
onPermissionRequest: createPermissionBridge(permissionPolicy),
|
|
265
|
-
...onUserInputRequest ? { onUserInputRequest } : {},
|
|
266
|
-
...resolvedProvider.provider ? { provider: resolvedProvider.provider } : {},
|
|
267
|
-
...hooks ? { hooks } : {},
|
|
268
|
-
...typeof params.enableSessionTelemetry === "boolean" ? { enableSessionTelemetry: params.enableSessionTelemetry } : {},
|
|
269
|
-
...settledToolFinalization ? {} : params.infiniteSessionConfig ? { infiniteSessions: params.infiniteSessionConfig } : {},
|
|
270
|
-
reasoningEffort: params.reasoningEffort,
|
|
271
|
-
tools: sdkTools,
|
|
272
|
-
availableTools: buildCopilotAvailableTools(sdkTools, options.includeAskUser),
|
|
273
|
-
...settledToolFinalization ? createCopilotIsolatedSessionRestrictions() : {},
|
|
274
|
-
workingDirectory: effectiveCwd ?? effectiveWorkspaceDir ?? readResolvedAttemptPath(params.workspaceDir),
|
|
275
|
-
...!settledToolFinalization && effectiveWorkspaceDir && effectiveCwd && effectiveCwd !== effectiveWorkspaceDir ? { instructionDirectories: [effectiveWorkspaceDir] } : {},
|
|
276
|
-
...resolvedAuth.authMode === "gitHubToken" && resolvedAuth.gitHubToken ? { gitHubToken: resolvedAuth.gitHubToken } : {},
|
|
277
|
-
...settledToolFinalization ? { systemMessage: {
|
|
278
|
-
mode: "customize",
|
|
279
|
-
content: COPILOT_SETTLED_FINALIZATION_SYSTEM_MESSAGE
|
|
280
|
-
} } : systemMessageContent ? { systemMessage: {
|
|
281
|
-
mode: "append",
|
|
282
|
-
content: systemMessageContent
|
|
283
|
-
} } : {}
|
|
284
|
-
};
|
|
285
|
-
}
|
|
286
|
-
function buildCopilotAvailableTools(sdkTools, includeAskUser) {
|
|
287
|
-
const availableTools = sdkTools.map((tool) => tool.name);
|
|
288
|
-
if (includeAskUser) availableTools.push(...COPILOT_ASK_USER_AVAILABLE_TOOLS);
|
|
289
|
-
return [...new Set(availableTools)];
|
|
290
|
-
}
|
|
291
164
|
async function createMessageOptions(params, context) {
|
|
292
|
-
|
|
165
|
+
async function resolvePromptImages() {
|
|
166
|
+
const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
|
|
167
|
+
if (!workspaceDir) return [];
|
|
168
|
+
const localRoots = context.workspaceOnly && context.effectiveWorkspaceDir ? [context.effectiveWorkspaceDir] : void 0;
|
|
169
|
+
const model = params.model;
|
|
170
|
+
return (await detectAndLoadAgentHarnessPromptImages({
|
|
171
|
+
prompt: params.prompt,
|
|
172
|
+
workspaceDir,
|
|
173
|
+
model: { input: typeof model === "object" ? model.input ?? ["image"] : ["image"] },
|
|
174
|
+
existingImages: params.images,
|
|
175
|
+
imageOrder: params.imageOrder,
|
|
176
|
+
media: params.media,
|
|
177
|
+
config: params.config,
|
|
178
|
+
workspaceOnly: context.workspaceOnly,
|
|
179
|
+
localRoots,
|
|
180
|
+
sandbox: context.sandbox?.enabled && context.sandbox.fsBridge ? {
|
|
181
|
+
root: context.sandbox.workspaceDir,
|
|
182
|
+
bridge: context.sandbox.fsBridge
|
|
183
|
+
} : void 0
|
|
184
|
+
})).images;
|
|
185
|
+
}
|
|
186
|
+
const attachments = (await resolvePromptImages()).map((image, index) => ({
|
|
293
187
|
type: "blob",
|
|
294
188
|
data: image.data,
|
|
295
189
|
mimeType: image.mimeType,
|
|
296
190
|
displayName: `prompt-image-${index + 1}`
|
|
297
191
|
}));
|
|
298
192
|
const providerHeaders = context.provider.provider?.headers;
|
|
299
|
-
const requestHeaders = providerHeaders && Object.keys(providerHeaders).length > 0 ?
|
|
193
|
+
const requestHeaders = providerHeaders && Object.keys(providerHeaders).length > 0 ? providerHeaders : void 0;
|
|
300
194
|
return {
|
|
301
195
|
prompt: params.prompt,
|
|
302
196
|
...attachments.length > 0 ? { attachments } : {},
|
|
303
197
|
...requestHeaders ? { requestHeaders } : {}
|
|
304
198
|
};
|
|
305
199
|
}
|
|
306
|
-
async function resolvePromptImages(params, context) {
|
|
307
|
-
const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
|
|
308
|
-
if (!workspaceDir) return [];
|
|
309
|
-
const localRoots = context.workspaceOnly && context.effectiveWorkspaceDir ? [context.effectiveWorkspaceDir] : void 0;
|
|
310
|
-
return (await detectAndLoadAgentHarnessPromptImages({
|
|
311
|
-
prompt: params.prompt,
|
|
312
|
-
workspaceDir,
|
|
313
|
-
model: resolveImageCapabilityModel(params),
|
|
314
|
-
existingImages: Array.isArray(params.images) ? params.images : void 0,
|
|
315
|
-
imageOrder: Array.isArray(params.imageOrder) ? params.imageOrder : void 0,
|
|
316
|
-
media: Array.isArray(params.media) ? params.media : void 0,
|
|
317
|
-
config: params.config,
|
|
318
|
-
workspaceOnly: context.workspaceOnly,
|
|
319
|
-
localRoots,
|
|
320
|
-
sandbox: context.sandbox?.enabled && context.sandbox.fsBridge ? {
|
|
321
|
-
root: context.sandbox.workspaceDir,
|
|
322
|
-
bridge: context.sandbox.fsBridge
|
|
323
|
-
} : void 0
|
|
324
|
-
})).images;
|
|
325
|
-
}
|
|
326
|
-
function resolveImageCapabilityModel(params) {
|
|
327
|
-
const model = params.model;
|
|
328
|
-
if (model && typeof model === "object" && Array.isArray(model.input)) return { input: model.input };
|
|
329
|
-
return { input: ["image"] };
|
|
330
|
-
}
|
|
331
200
|
function readResolvedAttemptPath(value) {
|
|
332
201
|
const raw = readNonEmptyString(value)?.trim();
|
|
333
202
|
if (!raw) return;
|
|
@@ -411,159 +280,6 @@ function isSdkSendAndWaitTimeoutError(error) {
|
|
|
411
280
|
return /^Timeout after \d+ms waiting for session\.idle$/.test(message);
|
|
412
281
|
}
|
|
413
282
|
//#endregion
|
|
414
|
-
//#region extensions/copilot/src/event-bridge-transcript.ts
|
|
415
|
-
function buildAssistantMessage(params) {
|
|
416
|
-
const event = params.event;
|
|
417
|
-
const text = event ? event.data.content || params.assistantTexts.at(-1) || "" : "";
|
|
418
|
-
const reasoningText = event?.data.reasoningText ?? params.reasoningText;
|
|
419
|
-
const toolRequests = event?.data.toolRequests ?? [];
|
|
420
|
-
if (!text && !reasoningText && toolRequests.length === 0) return;
|
|
421
|
-
const content = [];
|
|
422
|
-
if (reasoningText) content.push({
|
|
423
|
-
thinking: reasoningText,
|
|
424
|
-
type: "thinking"
|
|
425
|
-
});
|
|
426
|
-
if (text) content.push({
|
|
427
|
-
text,
|
|
428
|
-
type: "text"
|
|
429
|
-
});
|
|
430
|
-
for (const request of toolRequests) content.push({
|
|
431
|
-
arguments: asNonArrayRecord(request.arguments),
|
|
432
|
-
id: request.toolCallId,
|
|
433
|
-
name: request.name,
|
|
434
|
-
type: "toolCall"
|
|
435
|
-
});
|
|
436
|
-
return {
|
|
437
|
-
api: params.modelRef.api ?? "openai-responses",
|
|
438
|
-
content,
|
|
439
|
-
model: event?.data.model ?? params.modelRef.id,
|
|
440
|
-
provider: params.modelRef.provider,
|
|
441
|
-
role: "assistant",
|
|
442
|
-
stopReason: toolRequests.length > 0 ? "toolUse" : "stop",
|
|
443
|
-
timestamp: params.now(),
|
|
444
|
-
usage: buildCopilotAssistantUsage({
|
|
445
|
-
fallbackOutputTokens: event?.data.outputTokens,
|
|
446
|
-
usage: params.usage
|
|
447
|
-
})
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
function buildAssistantProjectionGroup(group, modelRef, resolveTimestamp, usageByApiCallId, latestUsage, forTranscript) {
|
|
451
|
-
const messages = group.chunks.flatMap((chunk) => {
|
|
452
|
-
const message = buildAssistantMessage({
|
|
453
|
-
event: chunk.event,
|
|
454
|
-
modelRef,
|
|
455
|
-
now: () => resolveTimestamp(chunk.event),
|
|
456
|
-
reasoningText: forTranscript ? chunk.transcriptReasoningText : chunk.reasoningText,
|
|
457
|
-
usage: resolveAssistantUsage(chunk.event, latestUsage, usageByApiCallId),
|
|
458
|
-
assistantTexts: forTranscript ? chunk.transcriptAssistantTexts : chunk.assistantTexts
|
|
459
|
-
});
|
|
460
|
-
return message ? [message] : [];
|
|
461
|
-
});
|
|
462
|
-
const replayIncomplete = group.chunks.some(({ event }) => hasUnprojectedAssistantReplayState(event));
|
|
463
|
-
const last = messages.at(-1);
|
|
464
|
-
if (!last) return {
|
|
465
|
-
message: void 0,
|
|
466
|
-
replayIncomplete,
|
|
467
|
-
toolCallIds: []
|
|
468
|
-
};
|
|
469
|
-
const narrative = [];
|
|
470
|
-
let terminalThinking;
|
|
471
|
-
const toolCallsById = /* @__PURE__ */ new Map();
|
|
472
|
-
for (const message of messages) for (const part of message.content) {
|
|
473
|
-
if (part.type === "toolCall") {
|
|
474
|
-
toolCallsById.set(part.id, part);
|
|
475
|
-
continue;
|
|
476
|
-
}
|
|
477
|
-
if (part.type === "thinking") {
|
|
478
|
-
terminalThinking = part;
|
|
479
|
-
continue;
|
|
480
|
-
}
|
|
481
|
-
const previous = narrative.at(-1);
|
|
482
|
-
if (part.type === "text" && previous?.type === "text") narrative[narrative.length - 1] = {
|
|
483
|
-
...previous,
|
|
484
|
-
text: previous.text + part.text
|
|
485
|
-
};
|
|
486
|
-
else narrative.push(part);
|
|
487
|
-
}
|
|
488
|
-
const content = [
|
|
489
|
-
...terminalThinking ? [terminalThinking] : [],
|
|
490
|
-
...narrative,
|
|
491
|
-
...toolCallsById.values()
|
|
492
|
-
];
|
|
493
|
-
const toolCallIds = [...toolCallsById.keys()];
|
|
494
|
-
return {
|
|
495
|
-
message: {
|
|
496
|
-
...last,
|
|
497
|
-
content,
|
|
498
|
-
stopReason: toolCallIds.length > 0 ? "toolUse" : "stop"
|
|
499
|
-
},
|
|
500
|
-
replayIncomplete,
|
|
501
|
-
toolCallIds
|
|
502
|
-
};
|
|
503
|
-
}
|
|
504
|
-
function hasUnprojectedAssistantReplayState(event) {
|
|
505
|
-
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;
|
|
506
|
-
}
|
|
507
|
-
function resolveAssistantUsage(event, latest, byApiCallId) {
|
|
508
|
-
const apiCallId = readNonEmptyStringPreservingWhitespace(event?.data.apiCallId);
|
|
509
|
-
return apiCallId ? byApiCallId.get(apiCallId) ?? latest : latest;
|
|
510
|
-
}
|
|
511
|
-
function resolveEventTimestamp(timestamp, now) {
|
|
512
|
-
return parseDateStringTimestampMs(timestamp) ?? now();
|
|
513
|
-
}
|
|
514
|
-
function hasOwnKeys(value) {
|
|
515
|
-
return Boolean(value && typeof value === "object" && Object.keys(value).length > 0);
|
|
516
|
-
}
|
|
517
|
-
function projectSdkUserMetadata(attachments, source) {
|
|
518
|
-
const summaries = (attachments ?? []).map((attachment) => {
|
|
519
|
-
const { data: _data, payload: _payload, text: _text, ...summary } = attachment;
|
|
520
|
-
return summary;
|
|
521
|
-
});
|
|
522
|
-
const media = (attachments ?? []).flatMap((attachment) => {
|
|
523
|
-
if (attachment.type === "file") return [{
|
|
524
|
-
path: attachment.path,
|
|
525
|
-
contentType: attachment.mimeType
|
|
526
|
-
}];
|
|
527
|
-
return attachment.type === "selection" ? [{
|
|
528
|
-
path: attachment.filePath,
|
|
529
|
-
kind: "document"
|
|
530
|
-
}] : [];
|
|
531
|
-
});
|
|
532
|
-
if (!source && summaries.length === 0) return;
|
|
533
|
-
return {
|
|
534
|
-
...source ? { copilotSource: source } : {},
|
|
535
|
-
...summaries.length > 0 ? { copilotAttachments: summaries } : {},
|
|
536
|
-
...media.length > 0 ? { media } : {}
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
function projectToolResultDetails(data) {
|
|
540
|
-
const result = data.result;
|
|
541
|
-
const sanitizedContents = result?.contents ? sanitizeToolResult({ content: result.contents }).content : void 0;
|
|
542
|
-
const binaryResultsForLlm = result?.binaryResultsForLlm?.map((entry) => {
|
|
543
|
-
const { data: _data, ...descriptor } = entry;
|
|
544
|
-
return descriptor;
|
|
545
|
-
});
|
|
546
|
-
const citableSources = result?.citableSources?.map((source) => Object.assign({}, source, { content: sanitizeToolDetailText(source.content) }));
|
|
547
|
-
return sanitizeToolResult({
|
|
548
|
-
...result?.detailedContent ? { content: [{
|
|
549
|
-
type: "text",
|
|
550
|
-
text: result.detailedContent
|
|
551
|
-
}] } : {},
|
|
552
|
-
...result?.structuredContent ? { structuredContent: result.structuredContent } : {},
|
|
553
|
-
...sanitizedContents ? { contents: sanitizedContents } : {},
|
|
554
|
-
...binaryResultsForLlm?.length ? { binaryResultsForLlm } : {},
|
|
555
|
-
...citableSources?.length ? { citableSources } : {},
|
|
556
|
-
...data.mcpMeta || result?.mcpMeta ? { mcpMeta: data.mcpMeta ?? result?.mcpMeta } : {}
|
|
557
|
-
});
|
|
558
|
-
}
|
|
559
|
-
function sanitizeToolDetailText(text) {
|
|
560
|
-
const value = sanitizeToolResult({ content: [{
|
|
561
|
-
type: "text",
|
|
562
|
-
text
|
|
563
|
-
}] }).content?.[0]?.text;
|
|
564
|
-
return typeof value === "string" ? value : "";
|
|
565
|
-
}
|
|
566
|
-
//#endregion
|
|
567
283
|
//#region extensions/copilot/src/event-bridge.ts
|
|
568
284
|
function attachEventBridge(session, options) {
|
|
569
285
|
const messagesById = /* @__PURE__ */ new Map();
|
|
@@ -589,7 +305,6 @@ function attachEventBridge(session, options) {
|
|
|
589
305
|
let activeCompactionCount = 0;
|
|
590
306
|
let observedCompaction = false;
|
|
591
307
|
let deltaQueue = Promise.resolve();
|
|
592
|
-
let deltaChain = Promise.resolve();
|
|
593
308
|
let agentEventChain = Promise.resolve();
|
|
594
309
|
let compactionChain = Promise.resolve();
|
|
595
310
|
let compactionIdle;
|
|
@@ -645,17 +360,11 @@ function attachEventBridge(session, options) {
|
|
|
645
360
|
if (!onAssistantDelta) return;
|
|
646
361
|
const payload = {
|
|
647
362
|
delta,
|
|
648
|
-
|
|
649
|
-
text,
|
|
650
|
-
usage
|
|
363
|
+
text
|
|
651
364
|
};
|
|
652
|
-
deltaQueue = deltaQueue.then(() => onAssistantDelta(payload)
|
|
365
|
+
deltaQueue = deltaQueue.then(() => onAssistantDelta(payload)).catch((error) => {
|
|
653
366
|
firstDeltaError ??= error;
|
|
654
367
|
});
|
|
655
|
-
deltaChain = deltaQueue.then(() => {
|
|
656
|
-
if (firstDeltaError !== void 0) throw toErrorObject(firstDeltaError, "Non-Error thrown");
|
|
657
|
-
});
|
|
658
|
-
deltaChain.catch(() => void 0);
|
|
659
368
|
});
|
|
660
369
|
listenRoot("assistant.reasoning_delta", (event) => {
|
|
661
370
|
const reasoningId = readNonEmptyStringPreservingWhitespace(event.data.reasoningId) ?? "assistant-reasoning";
|
|
@@ -862,8 +571,9 @@ function attachEventBridge(session, options) {
|
|
|
862
571
|
compactionIdle?.resolve();
|
|
863
572
|
compactionIdle = void 0;
|
|
864
573
|
},
|
|
865
|
-
awaitDeltaChain() {
|
|
866
|
-
|
|
574
|
+
async awaitDeltaChain() {
|
|
575
|
+
await deltaQueue;
|
|
576
|
+
if (firstDeltaError !== void 0) throw toErrorObject(firstDeltaError, "Non-Error thrown");
|
|
867
577
|
},
|
|
868
578
|
awaitAgentEventChain() {
|
|
869
579
|
return agentEventChain;
|
|
@@ -883,18 +593,16 @@ function attachEventBridge(session, options) {
|
|
|
883
593
|
},
|
|
884
594
|
snapshot() {
|
|
885
595
|
return {
|
|
886
|
-
assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent),
|
|
887
596
|
completedCount,
|
|
888
|
-
lastAssistantEvent,
|
|
889
597
|
startedCount,
|
|
890
598
|
streamError,
|
|
891
|
-
toolMetas: toolMetas
|
|
892
|
-
usage
|
|
599
|
+
toolMetas: [...toolMetas],
|
|
600
|
+
usage
|
|
893
601
|
};
|
|
894
602
|
},
|
|
895
603
|
buildAssistantMessage(args) {
|
|
896
604
|
const group = pendingAssistantProjection ?? lastAssistantProjection;
|
|
897
|
-
|
|
605
|
+
const message = group ? buildAssistantProjectionGroup(group, args.modelRef, () => args.now(), usageByApiCallId, usage, false).message : buildAssistantMessage({
|
|
898
606
|
event: lastAssistantEvent,
|
|
899
607
|
modelRef: args.modelRef,
|
|
900
608
|
now: args.now,
|
|
@@ -902,6 +610,7 @@ function attachEventBridge(session, options) {
|
|
|
902
610
|
usage: resolveAssistantUsage(lastAssistantEvent, usage, usageByApiCallId),
|
|
903
611
|
assistantTexts: finalizeAssistantTexts(messagesById, lastAssistantEvent)
|
|
904
612
|
});
|
|
613
|
+
return message?.content.length ? message : void 0;
|
|
905
614
|
},
|
|
906
615
|
finalizeAssistantTexts() {
|
|
907
616
|
return finalizeAssistantTexts(messagesById, lastAssistantEvent);
|
|
@@ -922,7 +631,7 @@ function attachEventBridge(session, options) {
|
|
|
922
631
|
detach() {
|
|
923
632
|
if (detached) return;
|
|
924
633
|
detached = true;
|
|
925
|
-
for (const unsubscribe of
|
|
634
|
+
for (const unsubscribe of unsubscribeFns.toReversed()) try {
|
|
926
635
|
unsubscribe();
|
|
927
636
|
} catch {}
|
|
928
637
|
unsubscribeFns.length = 0;
|
|
@@ -1045,6 +754,28 @@ function splitPlanText(text) {
|
|
|
1045
754
|
}
|
|
1046
755
|
//#endregion
|
|
1047
756
|
//#region extensions/copilot/src/attempt-cleanup.ts
|
|
757
|
+
/** Deletion follows disconnect even when disconnect fails; the first cleanup failure wins. */
|
|
758
|
+
async function disconnectCopilotSession(params) {
|
|
759
|
+
let failure;
|
|
760
|
+
try {
|
|
761
|
+
await params.session.disconnect();
|
|
762
|
+
} catch (error) {
|
|
763
|
+
failure = toCopilotError(error);
|
|
764
|
+
}
|
|
765
|
+
if (params.deleteSessionId) try {
|
|
766
|
+
await params.client.deleteSession(params.deleteSessionId);
|
|
767
|
+
} catch (error) {
|
|
768
|
+
failure ??= toCopilotError(error);
|
|
769
|
+
}
|
|
770
|
+
if (failure) throw failure;
|
|
771
|
+
}
|
|
772
|
+
function preserveCopilotAttemptCleanupError(primary, error) {
|
|
773
|
+
if (primary) {
|
|
774
|
+
console.warn("[copilot-attempt] detached session cleanup failed after primary error", error);
|
|
775
|
+
return primary;
|
|
776
|
+
}
|
|
777
|
+
return toCopilotError(error);
|
|
778
|
+
}
|
|
1048
779
|
async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now) {
|
|
1049
780
|
const failure = result.terminal.kind === "failed" ? { error: result.terminal.error } : result.terminal.kind === "ok" ? void 0 : result.terminal.failure;
|
|
1050
781
|
const aborted = result.terminal.kind === "aborted" && result.terminal.source !== "yield_cleanup";
|
|
@@ -1064,13 +795,21 @@ async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now
|
|
|
1064
795
|
}
|
|
1065
796
|
async function deferBackgroundCompactionCleanup(params) {
|
|
1066
797
|
let outcome = "deadline";
|
|
798
|
+
let cleanupError;
|
|
1067
799
|
try {
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
800
|
+
const { abortSignal, awaitSessionIdle, bridge, timeoutMs } = params;
|
|
801
|
+
if (abortSignal?.aborted) outcome = "aborted";
|
|
802
|
+
else {
|
|
803
|
+
const completion = (async () => {
|
|
804
|
+
if (awaitSessionIdle) await bridge.awaitSessionIdle();
|
|
805
|
+
await bridge.awaitCompactionCompletion();
|
|
806
|
+
return "completed";
|
|
807
|
+
})();
|
|
808
|
+
outcome = await raceWithTimeout(completion, timeoutMs, () => "deadline", {
|
|
809
|
+
signal: abortSignal,
|
|
810
|
+
onAbort: () => "aborted"
|
|
811
|
+
});
|
|
812
|
+
}
|
|
1074
813
|
} catch {} finally {
|
|
1075
814
|
if (outcome !== "completed") {
|
|
1076
815
|
await cancelBackgroundCompactionBeforeTeardown(params.session);
|
|
@@ -1078,18 +817,28 @@ async function deferBackgroundCompactionCleanup(params) {
|
|
|
1078
817
|
}
|
|
1079
818
|
params.bridge.detach();
|
|
1080
819
|
await params.bridge.awaitAgentEventChain();
|
|
1081
|
-
try {
|
|
1082
|
-
await params.session.disconnect();
|
|
1083
|
-
} catch {}
|
|
1084
820
|
params.cleanupToolBridge?.();
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
821
|
+
try {
|
|
822
|
+
await params.cleanupByokProxy?.();
|
|
823
|
+
} catch (error) {
|
|
824
|
+
cleanupError ??= toCopilotError(error);
|
|
825
|
+
}
|
|
826
|
+
try {
|
|
827
|
+
await disconnectCopilotSession({
|
|
828
|
+
session: params.session,
|
|
829
|
+
client: params.handle.client,
|
|
830
|
+
deleteSessionId: params.deleteSessionOnCleanup || outcome !== "completed" && params.deleteSessionOnIncompleteCleanup ? params.sdkSessionId : void 0
|
|
831
|
+
});
|
|
832
|
+
} catch (error) {
|
|
833
|
+
if (params.deleteSessionOnCleanup) cleanupError ??= toCopilotError(error);
|
|
834
|
+
}
|
|
1089
835
|
try {
|
|
1090
836
|
await params.pool.release(params.handle);
|
|
1091
|
-
} catch {
|
|
837
|
+
} catch (error) {
|
|
838
|
+
if (params.deleteSessionOnCleanup) cleanupError ??= toCopilotError(error);
|
|
839
|
+
}
|
|
1092
840
|
}
|
|
841
|
+
if (cleanupError) throw cleanupError;
|
|
1093
842
|
return outcome;
|
|
1094
843
|
}
|
|
1095
844
|
async function cancelBackgroundCompactionBeforeTeardown(session) {
|
|
@@ -1097,18 +846,6 @@ async function cancelBackgroundCompactionBeforeTeardown(session) {
|
|
|
1097
846
|
if (!cancelBackgroundCompaction) return;
|
|
1098
847
|
await withTimeout(Promise.resolve().then(() => cancelBackgroundCompaction()), BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS).catch(() => void 0);
|
|
1099
848
|
}
|
|
1100
|
-
async function awaitDeferredCleanupBeforeDeadline(params) {
|
|
1101
|
-
if (params.abortSignal?.aborted) return "aborted";
|
|
1102
|
-
const completion = (async () => {
|
|
1103
|
-
if (params.awaitSessionIdle) await params.bridge.awaitSessionIdle();
|
|
1104
|
-
await params.bridge.awaitCompactionCompletion();
|
|
1105
|
-
return "completed";
|
|
1106
|
-
})();
|
|
1107
|
-
return await raceWithTimeout(completion, params.timeoutMs, () => "deadline", {
|
|
1108
|
-
signal: params.abortSignal,
|
|
1109
|
-
onAbort: () => "aborted"
|
|
1110
|
-
});
|
|
1111
|
-
}
|
|
1112
849
|
//#endregion
|
|
1113
850
|
//#region extensions/copilot/src/attempt-active-run.ts
|
|
1114
851
|
const DEFAULT_STEERING_DELIVERY_TIMEOUT_MS = 12e4;
|
|
@@ -1123,7 +860,7 @@ function registerCopilotActiveRun(params) {
|
|
|
1123
860
|
});
|
|
1124
861
|
};
|
|
1125
862
|
const claimPendingUserInputAnswer = async (text, options) => {
|
|
1126
|
-
if (options?.isInboundUserMessage !== true || options.images?.length) return false;
|
|
863
|
+
if (options?.isInboundUserMessage !== true || options.allowPendingUserInputAnswer === false || options.images?.length) return false;
|
|
1127
864
|
return await claimPendingAgentQuestionAnswer({
|
|
1128
865
|
sessionKey: params.input.sessionKey ?? params.input.sessionId,
|
|
1129
866
|
text,
|
|
@@ -1203,19 +940,20 @@ function registerCopilotActiveRun(params) {
|
|
|
1203
940
|
params.abortActiveSession();
|
|
1204
941
|
}
|
|
1205
942
|
};
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
943
|
+
return {
|
|
944
|
+
handle: activeRunHandle,
|
|
945
|
+
attachment: setActiveEmbeddedRun(params.input.sessionId, activeRunHandle, params.input.sessionKey, params.input.sessionFile, params.agentId)
|
|
946
|
+
};
|
|
1209
947
|
}
|
|
1210
948
|
async function waitForPersistenceReceipt(receipt, requestedTimeoutMs) {
|
|
1211
|
-
await raceWithTimeout(receipt,
|
|
949
|
+
await raceWithTimeout(receipt, requestedTimeoutMs !== void 0 && Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0 ? requestedTimeoutMs : DEFAULT_STEERING_DELIVERY_TIMEOUT_MS, () => {
|
|
1212
950
|
throw new Error("Copilot steering transcript receipt timed out");
|
|
1213
951
|
}, { ref: false });
|
|
1214
952
|
}
|
|
1215
953
|
//#endregion
|
|
1216
954
|
//#region extensions/copilot/src/attempt-transcript-replay.ts
|
|
1217
955
|
function readIdempotencyKey(message) {
|
|
1218
|
-
const key = message.idempotencyKey;
|
|
956
|
+
const key = "idempotencyKey" in message ? message.idempotencyKey : void 0;
|
|
1219
957
|
return typeof key === "string" && key ? key : void 0;
|
|
1220
958
|
}
|
|
1221
959
|
function userText(content) {
|
|
@@ -1264,9 +1002,9 @@ function isSameUserTurn(candidate, current, currentRunUserKey) {
|
|
|
1264
1002
|
if (candidate === current) return true;
|
|
1265
1003
|
const candidateKey = candidate.idempotencyKey;
|
|
1266
1004
|
const currentKey = current.idempotencyKey;
|
|
1267
|
-
if (
|
|
1268
|
-
if (
|
|
1269
|
-
if (
|
|
1005
|
+
if (candidateKey !== void 0 || currentKey !== void 0) {
|
|
1006
|
+
if (candidateKey !== void 0 && currentKey !== void 0) return candidateKey === currentKey;
|
|
1007
|
+
if (candidateKey === void 0 || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
|
|
1270
1008
|
}
|
|
1271
1009
|
return candidate.timestamp === current.timestamp && userText(candidate.content) === userText(current.content);
|
|
1272
1010
|
}
|
|
@@ -1285,6 +1023,7 @@ async function completeCopilotAttempt(params) {
|
|
|
1285
1023
|
const currentRunUserKey = `${input.runId}:user`;
|
|
1286
1024
|
const messagesSnapshot = transcript?.messagesSnapshot ?? (recorder?.isBlocked() ? removePreparedUser(messages, recorder.message, currentRunUserKey) : includePreparedUser(messages, recorder?.message, input.trigger === "memory", currentRunUserKey));
|
|
1287
1025
|
const result = createResult(input, {
|
|
1026
|
+
runtimeArtifact: params.runtimeArtifact,
|
|
1288
1027
|
acceptedSessionSpawns,
|
|
1289
1028
|
aborted,
|
|
1290
1029
|
assistantTexts,
|
|
@@ -1311,7 +1050,7 @@ async function completeCopilotAttempt(params) {
|
|
|
1311
1050
|
sdkSessionId,
|
|
1312
1051
|
timedOut,
|
|
1313
1052
|
timedOutDuringCompaction,
|
|
1314
|
-
toolMetas: snap
|
|
1053
|
+
toolMetas: snap?.toolMetas ?? [],
|
|
1315
1054
|
usage: snap?.usage,
|
|
1316
1055
|
yieldDetected,
|
|
1317
1056
|
yieldAcknowledgment
|
|
@@ -1354,11 +1093,186 @@ function removePreparedUser(messages, prepared, currentRunUserKey) {
|
|
|
1354
1093
|
return prepared && isSameUserTurn(messages.at(-1), prepared, currentRunUserKey) ? messages.slice(0, -1) : messages;
|
|
1355
1094
|
}
|
|
1356
1095
|
//#endregion
|
|
1096
|
+
//#region extensions/copilot/src/attempt-prepare.ts
|
|
1097
|
+
function prepareCopilotAttemptContext(params, deps) {
|
|
1098
|
+
const settledToolFinalization = deps.operation === "settled-tool-finalization";
|
|
1099
|
+
if (!settledToolFinalization) assertCopilotAttemptHostCapabilities(params);
|
|
1100
|
+
const { hostCapabilities: _hostCapabilities, ...capabilityFreeParams } = params;
|
|
1101
|
+
const input = settledToolFinalization ? {
|
|
1102
|
+
...capabilityFreeParams,
|
|
1103
|
+
disableTools: true,
|
|
1104
|
+
images: [],
|
|
1105
|
+
imageOrder: [],
|
|
1106
|
+
extraSystemPrompt: void 0,
|
|
1107
|
+
onAgentEvent: void 0,
|
|
1108
|
+
onAgentToolResult: void 0,
|
|
1109
|
+
onAssistantDelta: void 0,
|
|
1110
|
+
onAssistantMessageStart: void 0,
|
|
1111
|
+
onBlockReply: void 0,
|
|
1112
|
+
onBlockReplyFlush: void 0,
|
|
1113
|
+
onPartialReply: void 0,
|
|
1114
|
+
onReasoningEnd: void 0,
|
|
1115
|
+
onReasoningStream: void 0,
|
|
1116
|
+
onToolResult: void 0,
|
|
1117
|
+
onToolStreamBoundary: void 0,
|
|
1118
|
+
operation: "settled-tool-finalization"
|
|
1119
|
+
} : params;
|
|
1120
|
+
const ringZeroSystemAgentRun = isHostScopedAgentToolActive("openclaw") && input.toolsAllow?.length === 1 && input.toolsAllow[0]?.trim().toLowerCase() === "openclaw";
|
|
1121
|
+
const messages = [...input.messages ?? []];
|
|
1122
|
+
const modelRef = resolveModelRef(input);
|
|
1123
|
+
const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
|
|
1124
|
+
const sandboxSessionKey = readNonEmptyString(input.sandboxSessionKey) ?? readNonEmptyString(input.sessionKey) ?? readNonEmptyString(input.sessionId);
|
|
1125
|
+
const { sessionAgentId } = resolveSessionAgentIdsStrict({
|
|
1126
|
+
sessionKey: readNonEmptyString(input.sessionKey),
|
|
1127
|
+
config: input.config,
|
|
1128
|
+
agentId: readNonEmptyString(params.agentId)
|
|
1129
|
+
});
|
|
1130
|
+
const hookContextWindowFields = {
|
|
1131
|
+
...input.contextWindowInfo?.tokens ? { contextTokenBudget: input.contextWindowInfo.tokens } : input.contextTokenBudget ? { contextTokenBudget: input.contextTokenBudget } : {},
|
|
1132
|
+
...input.contextWindowInfo?.source ? { contextWindowSource: input.contextWindowInfo.source } : {},
|
|
1133
|
+
...input.contextWindowInfo?.referenceTokens ? { contextWindowReferenceTokens: input.contextWindowInfo.referenceTokens } : {}
|
|
1134
|
+
};
|
|
1135
|
+
return {
|
|
1136
|
+
settledToolFinalization,
|
|
1137
|
+
input,
|
|
1138
|
+
ringZeroSystemAgentRun,
|
|
1139
|
+
messages,
|
|
1140
|
+
modelRef,
|
|
1141
|
+
resolvedWorkspaceForSandbox,
|
|
1142
|
+
sandboxSessionKey,
|
|
1143
|
+
sessionAgentId,
|
|
1144
|
+
hookContextWindowFields,
|
|
1145
|
+
hookContext: {
|
|
1146
|
+
runId: input.runId,
|
|
1147
|
+
jobId: input.jobId,
|
|
1148
|
+
agentId: sessionAgentId,
|
|
1149
|
+
sessionKey: readNonEmptyString(input.sessionKey) ?? sandboxSessionKey,
|
|
1150
|
+
sessionId: input.sessionId,
|
|
1151
|
+
workspaceDir: resolvedWorkspaceForSandbox,
|
|
1152
|
+
modelProviderId: modelRef.provider,
|
|
1153
|
+
modelId: modelRef.id,
|
|
1154
|
+
trigger: input.trigger,
|
|
1155
|
+
inputProvenance: input.inputProvenance,
|
|
1156
|
+
foregroundPromptContext: buildEmbeddedForegroundPromptContext({
|
|
1157
|
+
...input,
|
|
1158
|
+
agentId: sessionAgentId
|
|
1159
|
+
}, input.agentDir ?? resolveAgentDir(input.config ?? {}, sessionAgentId)),
|
|
1160
|
+
...input.config ? { config: input.config } : {},
|
|
1161
|
+
...hookContextWindowFields,
|
|
1162
|
+
...buildAgentHookContextChannelFields(input)
|
|
1163
|
+
}
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
async function resolveCopilotAttemptSandbox(params) {
|
|
1167
|
+
const sandbox = params.input.sandbox !== void 0 ? params.input.sandbox : await resolveSandboxContext({
|
|
1168
|
+
config: params.input.config,
|
|
1169
|
+
agentId: params.input.sandboxAgentId,
|
|
1170
|
+
sessionKey: params.sandboxSessionKey,
|
|
1171
|
+
workspaceDir: params.resolvedWorkspaceForSandbox
|
|
1172
|
+
});
|
|
1173
|
+
const effectiveWorkspaceDir = sandbox?.enabled ? sandbox.workspaceAccess === "rw" ? params.resolvedWorkspaceForSandbox : sandbox.workspaceDir : params.resolvedWorkspaceForSandbox;
|
|
1174
|
+
if (sandbox?.enabled && effectiveWorkspaceDir !== params.resolvedWorkspaceForSandbox) await fsp.mkdir(effectiveWorkspaceDir, { recursive: true });
|
|
1175
|
+
return {
|
|
1176
|
+
sandbox,
|
|
1177
|
+
effectiveWorkspaceDir
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
//#endregion
|
|
1357
1181
|
//#region extensions/copilot/src/attempt-mode.ts
|
|
1358
1182
|
function isRawCopilotModelRun(params) {
|
|
1359
1183
|
return params.modelRun === true || params.promptMode === "none";
|
|
1360
1184
|
}
|
|
1361
1185
|
//#endregion
|
|
1186
|
+
//#region extensions/copilot/src/hooks-bridge.ts
|
|
1187
|
+
const DEFAULT_HOOK_ERROR_HANDLER = ({ hookName, error }) => {
|
|
1188
|
+
console.warn(`[copilot hooks-bridge] ${hookName} handler threw:`, error);
|
|
1189
|
+
};
|
|
1190
|
+
/**
|
|
1191
|
+
* Wrap a native handler so it cannot throw into the SDK. Returning undefined
|
|
1192
|
+
* leaves the SDK's default decision in place.
|
|
1193
|
+
*/
|
|
1194
|
+
function isolate(hookName, handler, onError) {
|
|
1195
|
+
if (!handler) return;
|
|
1196
|
+
return async (...args) => {
|
|
1197
|
+
try {
|
|
1198
|
+
return await handler(...args);
|
|
1199
|
+
} catch (error) {
|
|
1200
|
+
try {
|
|
1201
|
+
onError({
|
|
1202
|
+
hookName,
|
|
1203
|
+
error
|
|
1204
|
+
});
|
|
1205
|
+
} catch {}
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Build an SDK-shaped hook object from native per-attempt configuration.
|
|
1212
|
+
* Omit the SDK hook subsystem when no handlers were configured.
|
|
1213
|
+
*/
|
|
1214
|
+
function createHooksBridge(config, options) {
|
|
1215
|
+
if (!config) return;
|
|
1216
|
+
const onError = config.onHookError ?? DEFAULT_HOOK_ERROR_HANDLER;
|
|
1217
|
+
const hooks = {
|
|
1218
|
+
onPreToolUse: isolate("onPreToolUse", config.onPreToolUse, onError),
|
|
1219
|
+
onPreMcpToolCall: isolate("onPreMcpToolCall", config.onPreMcpToolCall, onError),
|
|
1220
|
+
onPostToolUse: isolate("onPostToolUse", config.onPostToolUse, onError),
|
|
1221
|
+
onPostToolUseFailure: isolate("onPostToolUseFailure", config.onPostToolUseFailure, onError),
|
|
1222
|
+
onSessionStart: isolate("onSessionStart", config.onSessionStart, onError),
|
|
1223
|
+
onSessionEnd: isolate("onSessionEnd", config.onSessionEnd, onError),
|
|
1224
|
+
onErrorOccurred: isolate("onErrorOccurred", config.onErrorOccurred, onError)
|
|
1225
|
+
};
|
|
1226
|
+
const userPrompt = isolate("onUserPromptSubmitted", config.onUserPromptSubmitted, onError);
|
|
1227
|
+
if (userPrompt) hooks.onUserPromptSubmitted = async (input, invocation) => {
|
|
1228
|
+
const output = await userPrompt(input, invocation);
|
|
1229
|
+
try {
|
|
1230
|
+
options?.onUserPromptSubmitted?.({
|
|
1231
|
+
prompt: output?.modifiedPrompt ?? input.prompt,
|
|
1232
|
+
...output?.additionalContext ? { additionalContext: output.additionalContext } : {}
|
|
1233
|
+
});
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
try {
|
|
1236
|
+
onError({
|
|
1237
|
+
hookName: "onUserPromptSubmitted",
|
|
1238
|
+
error
|
|
1239
|
+
});
|
|
1240
|
+
} catch {}
|
|
1241
|
+
}
|
|
1242
|
+
return output;
|
|
1243
|
+
};
|
|
1244
|
+
for (const key of Object.keys(hooks)) if (hooks[key] === void 0) delete hooks[key];
|
|
1245
|
+
return Object.keys(hooks).length > 0 ? hooks : void 0;
|
|
1246
|
+
}
|
|
1247
|
+
//#endregion
|
|
1248
|
+
//#region extensions/copilot/src/permission-bridge.ts
|
|
1249
|
+
const REJECT_ALL_FEEDBACK = "copilot agent runtime: no permission policy installed (denied by default)";
|
|
1250
|
+
const rejectAllPolicy = () => ({
|
|
1251
|
+
kind: "reject",
|
|
1252
|
+
feedback: REJECT_ALL_FEEDBACK
|
|
1253
|
+
});
|
|
1254
|
+
function createPermissionBridge(policy = rejectAllPolicy) {
|
|
1255
|
+
return async (request, invocation) => {
|
|
1256
|
+
const ctx = {
|
|
1257
|
+
request,
|
|
1258
|
+
sessionId: invocation.sessionId
|
|
1259
|
+
};
|
|
1260
|
+
try {
|
|
1261
|
+
const result = await policy(ctx);
|
|
1262
|
+
if (result !== void 0) return result;
|
|
1263
|
+
} catch (error) {
|
|
1264
|
+
return {
|
|
1265
|
+
kind: "reject",
|
|
1266
|
+
feedback: `copilot permission policy threw: ${formatErrorMessage(error)}`
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
return {
|
|
1270
|
+
kind: "reject",
|
|
1271
|
+
feedback: REJECT_ALL_FEEDBACK
|
|
1272
|
+
};
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
//#endregion
|
|
1362
1276
|
//#region extensions/copilot/src/tool-bridge.ts
|
|
1363
1277
|
const EMPTY_PROMPT_TOOL_POLICY = { apply: () => ({
|
|
1364
1278
|
tools: [],
|
|
@@ -1416,7 +1330,6 @@ async function createCopilotToolBridge(input) {
|
|
|
1416
1330
|
runtimeToolAllowlist: toolSurfaceRuntime.runtimeToolAllowlist
|
|
1417
1331
|
}, toolSurfaceRuntime);
|
|
1418
1332
|
const hostCapabilities = attemptParams.hostCapabilities;
|
|
1419
|
-
if (!hostCapabilities) throw new Error("Copilot attempt tools require host-bound capabilities.");
|
|
1420
1333
|
const bindingCwd = toolOptions.cwd ?? toolOptions.workspaceDir;
|
|
1421
1334
|
const bindingOptions = bindingCwd ? { cwd: bindingCwd } : void 0;
|
|
1422
1335
|
const createToolSurfaceAsync = hostCapabilities.createToolSurfaceAsync;
|
|
@@ -1427,7 +1340,6 @@ async function createCopilotToolBridge(input) {
|
|
|
1427
1340
|
const compactedTools = toolSurfaceRuntime.compactTools(allowedSourceTools, { localModelLeanApplied: true });
|
|
1428
1341
|
const newlyConstructedTools = compactedTools.tools.filter((tool) => !boundSourceTools.has(tool));
|
|
1429
1342
|
const boundNewlyConstructedTools = newlyConstructedTools.length > 0 ? hostCapabilities.bindToolSurface(newlyConstructedTools, bindingOptions) : newlyConstructedTools;
|
|
1430
|
-
if (boundNewlyConstructedTools.length !== newlyConstructedTools.length) throw new Error("Copilot host capability changed the tool surface length.");
|
|
1431
1343
|
const newlyBoundTools = /* @__PURE__ */ new Map();
|
|
1432
1344
|
for (let index = 0; index < newlyConstructedTools.length; index += 1) newlyBoundTools.set(newlyConstructedTools[index], boundNewlyConstructedTools[index]);
|
|
1433
1345
|
const exposedTools = compactedTools.tools.map((tool) => newlyBoundTools.get(tool) ?? tool);
|
|
@@ -1436,7 +1348,9 @@ async function createCopilotToolBridge(input) {
|
|
|
1436
1348
|
const runInAttemptContext = AsyncLocalStorage.snapshot();
|
|
1437
1349
|
let sequentialBarrier = Promise.resolve();
|
|
1438
1350
|
const pendingCalls = /* @__PURE__ */ new Set();
|
|
1351
|
+
let acceptingCalls = true;
|
|
1439
1352
|
const scheduleToolExecution = (executionMode, execute) => {
|
|
1353
|
+
if (!acceptingCalls) return Promise.reject(/* @__PURE__ */ new Error("[copilot-tool-bridge] attempt is closing"));
|
|
1440
1354
|
const run = (executionMode === "sequential" ? Promise.all(pendingCalls) : sequentialBarrier).then(() => runInAttemptContext(execute));
|
|
1441
1355
|
const settled = run.then(() => void 0, () => void 0);
|
|
1442
1356
|
pendingCalls.add(settled);
|
|
@@ -1447,6 +1361,10 @@ async function createCopilotToolBridge(input) {
|
|
|
1447
1361
|
const sdkTools = exposedTools.map((sourceTool) => convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution));
|
|
1448
1362
|
return {
|
|
1449
1363
|
cleanup: toolSurfaceRuntime.cleanup,
|
|
1364
|
+
settle: async () => {
|
|
1365
|
+
acceptingCalls = false;
|
|
1366
|
+
await Promise.all(pendingCalls);
|
|
1367
|
+
},
|
|
1450
1368
|
codeModeEngaged: toolSurfaceRuntime.codeModeControlsEnabled,
|
|
1451
1369
|
promptToolPolicy: {
|
|
1452
1370
|
requireExplicitMessageTarget: toolOptions.requireExplicitMessageTarget,
|
|
@@ -1485,8 +1403,8 @@ async function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRunti
|
|
|
1485
1403
|
const agentDir = input.agentDir ?? a.agentDir;
|
|
1486
1404
|
const sandbox = input.sandbox ?? void 0;
|
|
1487
1405
|
const model = a.model;
|
|
1488
|
-
const modelHasVision =
|
|
1489
|
-
const modelCompat = model
|
|
1406
|
+
const modelHasVision = model?.input?.includes("image") ?? false;
|
|
1407
|
+
const modelCompat = model?.compat;
|
|
1490
1408
|
return {
|
|
1491
1409
|
agentId: input.agentId,
|
|
1492
1410
|
policyAgentId: a.sandboxAgentId ?? input.agentId,
|
|
@@ -1532,8 +1450,6 @@ async function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRunti
|
|
|
1532
1450
|
requireExplicitMessageTarget: a.requireExplicitMessageTarget ?? isSubagentSessionKey(liveSessionKey),
|
|
1533
1451
|
disableMessageTool: a.disableMessageTool,
|
|
1534
1452
|
forceMessageTool: a.forceMessageTool,
|
|
1535
|
-
enableHeartbeatTool: a.enableHeartbeatTool,
|
|
1536
|
-
forceHeartbeatTool: a.forceHeartbeatTool,
|
|
1537
1453
|
authProfileStore: a.toolAuthProfileStore ?? a.authProfileStore,
|
|
1538
1454
|
computerContextEpoch: input.computerContextEpoch,
|
|
1539
1455
|
onToolOutcome: a.onToolOutcome,
|
|
@@ -1549,8 +1465,6 @@ async function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRunti
|
|
|
1549
1465
|
};
|
|
1550
1466
|
}
|
|
1551
1467
|
function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution) {
|
|
1552
|
-
if (typeof sourceTool.name !== "string" || sourceTool.name.trim().length === 0) throw new Error("[copilot-tool-bridge] tool name must be a non-empty string");
|
|
1553
|
-
if (typeof sourceTool.execute !== "function") throw new Error(`[copilot-tool-bridge] tool '${sourceTool.name}' must define an execute function`);
|
|
1554
1468
|
const ownerKey = getPluginToolSideEffectOwnerKey(sourceTool);
|
|
1555
1469
|
const ownerMutation = ownerKey ? { ownerKey } : void 0;
|
|
1556
1470
|
const notifyToolResult = (result, isError) => {
|
|
@@ -1747,138 +1661,10 @@ function shouldForceCopilotMessageTool(params) {
|
|
|
1747
1661
|
}
|
|
1748
1662
|
function findDuplicateToolNames(sourceTools) {
|
|
1749
1663
|
const counts = /* @__PURE__ */ new Map();
|
|
1750
|
-
for (const sourceTool of sourceTools)
|
|
1751
|
-
if (typeof sourceTool.name !== "string" || sourceTool.name.length === 0) continue;
|
|
1752
|
-
counts.set(sourceTool.name, (counts.get(sourceTool.name) ?? 0) + 1);
|
|
1753
|
-
}
|
|
1664
|
+
for (const sourceTool of sourceTools) counts.set(sourceTool.name, (counts.get(sourceTool.name) ?? 0) + 1);
|
|
1754
1665
|
return [...counts.entries()].filter(([, count]) => count > 1).map(([name]) => name).toSorted();
|
|
1755
1666
|
}
|
|
1756
1667
|
//#endregion
|
|
1757
|
-
//#region extensions/copilot/src/attempt-prepare.ts
|
|
1758
|
-
function prepareCopilotAttemptContext(params, deps) {
|
|
1759
|
-
const settledToolFinalization = deps.operation === "settled-tool-finalization";
|
|
1760
|
-
if (!settledToolFinalization) assertCopilotAttemptHostCapabilities(params);
|
|
1761
|
-
const { hostCapabilities: _hostCapabilities, ...capabilityFreeParams } = params;
|
|
1762
|
-
const input = settledToolFinalization ? {
|
|
1763
|
-
...capabilityFreeParams,
|
|
1764
|
-
disableTools: true,
|
|
1765
|
-
images: [],
|
|
1766
|
-
imageOrder: [],
|
|
1767
|
-
extraSystemPrompt: void 0,
|
|
1768
|
-
onAgentEvent: void 0,
|
|
1769
|
-
onAgentToolResult: void 0,
|
|
1770
|
-
onAssistantDelta: void 0,
|
|
1771
|
-
onAssistantMessageStart: void 0,
|
|
1772
|
-
onBlockReply: void 0,
|
|
1773
|
-
onBlockReplyFlush: void 0,
|
|
1774
|
-
onPartialReply: void 0,
|
|
1775
|
-
onReasoningEnd: void 0,
|
|
1776
|
-
onReasoningStream: void 0,
|
|
1777
|
-
onToolResult: void 0,
|
|
1778
|
-
onToolStreamBoundary: void 0,
|
|
1779
|
-
operation: "settled-tool-finalization"
|
|
1780
|
-
} : params;
|
|
1781
|
-
const createToolBridge = deps.createToolBridge ?? createCopilotToolBridge;
|
|
1782
|
-
const ringZeroSystemAgentRun = (deps.isHostScopedToolActive?.("openclaw") ?? isHostScopedAgentToolActive("openclaw")) && input.toolsAllow?.length === 1 && input.toolsAllow[0]?.trim().toLowerCase() === "openclaw";
|
|
1783
|
-
const messages = Array.isArray(input.messages) ? [...input.messages] : [];
|
|
1784
|
-
const modelRef = resolveModelRef(input);
|
|
1785
|
-
const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
|
|
1786
|
-
const sandboxSessionKey = readNonEmptyString(input.sandboxSessionKey) ?? readNonEmptyString(input.sessionKey) ?? readNonEmptyString(input.sessionId);
|
|
1787
|
-
const { sessionAgentId } = resolveSessionAgentIdsStrict({
|
|
1788
|
-
sessionKey: readNonEmptyString(input.sessionKey),
|
|
1789
|
-
config: input.config,
|
|
1790
|
-
agentId: readNonEmptyString(params.agentId)
|
|
1791
|
-
});
|
|
1792
|
-
const hookContextWindowFields = {
|
|
1793
|
-
...input.contextWindowInfo?.tokens ? { contextTokenBudget: input.contextWindowInfo.tokens } : input.contextTokenBudget ? { contextTokenBudget: input.contextTokenBudget } : {},
|
|
1794
|
-
...input.contextWindowInfo?.source ? { contextWindowSource: input.contextWindowInfo.source } : {},
|
|
1795
|
-
...input.contextWindowInfo?.referenceTokens ? { contextWindowReferenceTokens: input.contextWindowInfo.referenceTokens } : {}
|
|
1796
|
-
};
|
|
1797
|
-
return {
|
|
1798
|
-
settledToolFinalization,
|
|
1799
|
-
input,
|
|
1800
|
-
createToolBridge,
|
|
1801
|
-
ringZeroSystemAgentRun,
|
|
1802
|
-
messages,
|
|
1803
|
-
modelRef,
|
|
1804
|
-
resolvedWorkspaceForSandbox,
|
|
1805
|
-
sandboxSessionKey,
|
|
1806
|
-
sessionAgentId,
|
|
1807
|
-
hookContextWindowFields,
|
|
1808
|
-
hookContext: {
|
|
1809
|
-
runId: input.runId,
|
|
1810
|
-
jobId: input.jobId,
|
|
1811
|
-
agentId: sessionAgentId,
|
|
1812
|
-
sessionKey: readNonEmptyString(input.sessionKey) ?? sandboxSessionKey,
|
|
1813
|
-
sessionId: input.sessionId,
|
|
1814
|
-
workspaceDir: resolvedWorkspaceForSandbox,
|
|
1815
|
-
modelProviderId: modelRef.provider,
|
|
1816
|
-
modelId: modelRef.id,
|
|
1817
|
-
trigger: input.trigger,
|
|
1818
|
-
inputProvenance: input.inputProvenance,
|
|
1819
|
-
foregroundPromptContext: buildEmbeddedForegroundPromptContext({
|
|
1820
|
-
...input,
|
|
1821
|
-
agentId: sessionAgentId
|
|
1822
|
-
}, input.agentDir ?? resolveAgentDir(input.config ?? {}, sessionAgentId)),
|
|
1823
|
-
...input.config ? { config: input.config } : {},
|
|
1824
|
-
...hookContextWindowFields,
|
|
1825
|
-
...buildAgentHookContextChannelFields(input)
|
|
1826
|
-
}
|
|
1827
|
-
};
|
|
1828
|
-
}
|
|
1829
|
-
async function resolveCopilotAttemptSandbox(params) {
|
|
1830
|
-
const resolveSandbox = params.deps.resolveSandboxContextOverride ?? resolveSandboxContext;
|
|
1831
|
-
const sandbox = params.input.sandbox !== void 0 ? params.input.sandbox : await resolveSandbox({
|
|
1832
|
-
config: params.input.config,
|
|
1833
|
-
agentId: params.input.sandboxAgentId,
|
|
1834
|
-
sessionKey: params.sandboxSessionKey,
|
|
1835
|
-
workspaceDir: params.resolvedWorkspaceForSandbox
|
|
1836
|
-
});
|
|
1837
|
-
const effectiveWorkspaceDir = sandbox?.enabled ? sandbox.workspaceAccess === "rw" ? params.resolvedWorkspaceForSandbox : sandbox.workspaceDir : params.resolvedWorkspaceForSandbox;
|
|
1838
|
-
if (sandbox?.enabled && effectiveWorkspaceDir !== params.resolvedWorkspaceForSandbox) await fsp.mkdir(effectiveWorkspaceDir, { recursive: true });
|
|
1839
|
-
return {
|
|
1840
|
-
sandbox,
|
|
1841
|
-
effectiveWorkspaceDir
|
|
1842
|
-
};
|
|
1843
|
-
}
|
|
1844
|
-
//#endregion
|
|
1845
|
-
//#region extensions/copilot/src/prompt-guidance.ts
|
|
1846
|
-
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.";
|
|
1847
|
-
function buildCopilotPromptGuidance(params) {
|
|
1848
|
-
if (isRawCopilotModelRun(params.attempt)) return;
|
|
1849
|
-
const callableTools = new Set(normalizeUniqueStringEntries(params.callableToolNames));
|
|
1850
|
-
const hasSessionsSpawn = callableTools.has("sessions_spawn");
|
|
1851
|
-
const isMinimal = params.attempt.promptMode === "minimal";
|
|
1852
|
-
const extraSystemPrompt = readNonEmptyStringPreservingWhitespace(params.attempt.extraSystemPrompt)?.trim();
|
|
1853
|
-
const delegationGuidance = params.attempt.disableTools !== true && params.attempt.delegationCapability !== "report_only" ? buildDelegationGuidanceSection({
|
|
1854
|
-
mode: resolveMainSessionDelegationMode({
|
|
1855
|
-
config: params.attempt.config,
|
|
1856
|
-
agentId: params.attempt.agentId,
|
|
1857
|
-
sessionKey: params.attempt.sessionKey
|
|
1858
|
-
}),
|
|
1859
|
-
isMinimal,
|
|
1860
|
-
hiddenDelegationTool: hasSessionsSpawn ? "`sessions_spawn`" : "",
|
|
1861
|
-
hasVisibleSessionSpawn: hasSessionsSpawn,
|
|
1862
|
-
hasSessionsYield: callableTools.has("sessions_yield"),
|
|
1863
|
-
hasSubagentsList: callableTools.has("subagents"),
|
|
1864
|
-
hasSessionsSend: callableTools.has("sessions_send")
|
|
1865
|
-
}).join("\n") : void 0;
|
|
1866
|
-
return [
|
|
1867
|
-
COPILOT_HARNESS_IDENTITY,
|
|
1868
|
-
params.toolSchemaDirectoryPrompt,
|
|
1869
|
-
callableTools.has(SKILL_WORKSHOP_TOOL_NAME) ? buildSkillWorkshopPromptSection().join("\n") : void 0,
|
|
1870
|
-
delegationGuidance,
|
|
1871
|
-
buildHarnessVisibleReplyGuidance({
|
|
1872
|
-
sourceReplyDeliveryMode: params.attempt.sourceReplyDeliveryMode,
|
|
1873
|
-
messageToolAvailable: callableTools.has("message"),
|
|
1874
|
-
requireExplicitMessageTarget: params.requireExplicitMessageTarget
|
|
1875
|
-
}),
|
|
1876
|
-
buildCredentialSafetyPrompt({ controlToolsAvailable: params.attempt.disableTools !== true && (callableTools.has("openclaw") || callableTools.has("gateway")) }),
|
|
1877
|
-
params.workspaceBootstrapInstructions?.trim(),
|
|
1878
|
-
extraSystemPrompt ? `${isMinimal ? "## Subagent Context" : "## Conversation Context"}\n${extraSystemPrompt}` : void 0
|
|
1879
|
-
].filter((section) => section?.trim()).join("\n\n") || void 0;
|
|
1880
|
-
}
|
|
1881
|
-
//#endregion
|
|
1882
1668
|
//#region extensions/copilot/src/user-input-bridge.ts
|
|
1883
1669
|
const COPILOT_USER_INPUT_QUESTION_ID = "answer";
|
|
1884
1670
|
const DEFAULT_USER_INPUT_TIMEOUT_MS = 9e5;
|
|
@@ -1889,9 +1675,6 @@ function createCopilotUserInputBridge(params) {
|
|
|
1889
1675
|
pending?.abort(/* @__PURE__ */ new Error("Copilot user input request replaced"));
|
|
1890
1676
|
const abort = new AbortController();
|
|
1891
1677
|
pending = abort;
|
|
1892
|
-
const abortFromRun = () => abort.abort(params.signal?.reason);
|
|
1893
|
-
params.signal?.addEventListener("abort", abortFromRun, { once: true });
|
|
1894
|
-
if (params.signal?.aborted) abortFromRun();
|
|
1895
1678
|
try {
|
|
1896
1679
|
const question = toQuestion(request);
|
|
1897
1680
|
const result = await runAgentHarnessGatewayQuestion({
|
|
@@ -1906,7 +1689,7 @@ function createCopilotUserInputBridge(params) {
|
|
|
1906
1689
|
intro: "Copilot needs input:",
|
|
1907
1690
|
formatText: formatCopilotDisplayText
|
|
1908
1691
|
},
|
|
1909
|
-
signal: abort.signal
|
|
1692
|
+
signal: params.signal ? AbortSignal.any([params.signal, abort.signal]) : abort.signal
|
|
1910
1693
|
});
|
|
1911
1694
|
if (result.status !== "answered") return emptyCopilotUserInputResponse();
|
|
1912
1695
|
const selected = result.answers.answers[COPILOT_USER_INPUT_QUESTION_ID]?.[0] ?? "";
|
|
@@ -1918,7 +1701,6 @@ function createCopilotUserInputBridge(params) {
|
|
|
1918
1701
|
embeddedAgentLog.warn("failed to bridge copilot user input through gateway", { error });
|
|
1919
1702
|
return emptyCopilotUserInputResponse();
|
|
1920
1703
|
} finally {
|
|
1921
|
-
params.signal?.removeEventListener("abort", abortFromRun);
|
|
1922
1704
|
if (pending === abort) pending = void 0;
|
|
1923
1705
|
}
|
|
1924
1706
|
},
|
|
@@ -1947,21 +1729,8 @@ function isChoiceAnswer(question, answer) {
|
|
|
1947
1729
|
return Boolean(answer && question.options?.some((option) => option.label.toLowerCase() === answer.toLowerCase()));
|
|
1948
1730
|
}
|
|
1949
1731
|
function formatCopilotDisplayText(value) {
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
function sanitizeCopilotDisplayText(value) {
|
|
1953
|
-
let safe = "";
|
|
1954
|
-
for (const character of value) {
|
|
1955
|
-
const codePoint = character.codePointAt(0);
|
|
1956
|
-
safe += codePoint != null && isUnsafeDisplayCodePoint(codePoint) ? "?" : character;
|
|
1957
|
-
}
|
|
1958
|
-
return safe;
|
|
1959
|
-
}
|
|
1960
|
-
function escapeCopilotChatText(value) {
|
|
1961
|
-
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("@", "@").replaceAll("`", "`").replaceAll("[", "[").replaceAll("]", "]").replaceAll("(", "(").replaceAll(")", ")").replaceAll("*", "∗").replaceAll("_", "_").replaceAll("~", "~").replaceAll("|", "|");
|
|
1962
|
-
}
|
|
1963
|
-
function isUnsafeDisplayCodePoint(codePoint) {
|
|
1964
|
-
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;
|
|
1732
|
+
const safe = sanitizeChatDisplayText(value).trim();
|
|
1733
|
+
return escapeChatDisplayText(safe || "<unknown>");
|
|
1965
1734
|
}
|
|
1966
1735
|
//#endregion
|
|
1967
1736
|
//#region extensions/copilot/src/workspace-bootstrap.ts
|
|
@@ -1977,62 +1746,50 @@ const COPILOT_BOOTSTRAP_CONTEXT_ORDER = /* @__PURE__ */ new Map([
|
|
|
1977
1746
|
]);
|
|
1978
1747
|
async function loadCopilotWorkspaceInstructions(params) {
|
|
1979
1748
|
const { attempt } = params;
|
|
1980
|
-
const workspaceDir =
|
|
1749
|
+
const workspaceDir = readResolvedAttemptPath(attempt.workspaceDir);
|
|
1981
1750
|
if (!workspaceDir) return;
|
|
1982
1751
|
try {
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1752
|
+
const sourceContextFiles = (await resolveBootstrapContextForRun({
|
|
1753
|
+
workspaceDir,
|
|
1754
|
+
config: attempt.config,
|
|
1755
|
+
sessionKey: readNonBlankString(attempt.sessionKey),
|
|
1756
|
+
sessionId: readNonBlankString(attempt.sessionId),
|
|
1757
|
+
chatType: attempt.chatType,
|
|
1758
|
+
agentId: readNonBlankString(attempt.agentId),
|
|
1759
|
+
warn: params.warn,
|
|
1760
|
+
contextMode: attempt.bootstrapContextMode,
|
|
1761
|
+
runKind: attempt.bootstrapContextRunKind
|
|
1762
|
+
})).contextFiles;
|
|
1763
|
+
const targetWorkspaceDir = readResolvedAttemptPath(params.effectiveWorkspaceDir) ?? workspaceDir;
|
|
1764
|
+
const files = (workspaceDir === targetWorkspaceDir ? sourceContextFiles : sourceContextFiles.map((file) => {
|
|
1765
|
+
const relative = path.relative(workspaceDir, file.path);
|
|
1766
|
+
if (!isRelativePathInsideOrEqual(relative)) return file;
|
|
1767
|
+
return Object.assign({}, file, { path: relative === "" ? targetWorkspaceDir : path.join(targetWorkspaceDir, relative) });
|
|
1768
|
+
})).filter((file) => {
|
|
1769
|
+
const baseName = getCopilotContextFileBasename(file.path);
|
|
1770
|
+
return baseName.length > 0 && !COPILOT_NATIVE_PROJECT_DOC_BASENAMES.has(baseName);
|
|
1771
|
+
}).toSorted(compareCopilotContextFiles);
|
|
1772
|
+
if (files.length === 0) return;
|
|
1773
|
+
const hasSoulFile = files.some((file) => getCopilotContextFileBasename(file.path) === "soul.md");
|
|
1774
|
+
const lines = [
|
|
1775
|
+
"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.",
|
|
1776
|
+
"",
|
|
1777
|
+
"# Project Context",
|
|
1778
|
+
"",
|
|
1779
|
+
"The following project context files have been loaded:"
|
|
1780
|
+
];
|
|
1781
|
+
if (hasSoulFile) lines.push("SOUL.md: persona/tone. Follow it unless higher-priority instructions override.");
|
|
1782
|
+
lines.push("");
|
|
1783
|
+
for (const file of files) lines.push(`## ${file.path}`, "", file.content, "");
|
|
1784
|
+
return lines.join("\n").trim();
|
|
1998
1785
|
} catch (error) {
|
|
1999
1786
|
params.warn?.(`[copilot-attempt] failed to load workspace bootstrap instructions: ${error instanceof Error ? error.message : String(error)}`);
|
|
2000
1787
|
return;
|
|
2001
1788
|
}
|
|
2002
1789
|
}
|
|
2003
|
-
function remapCopilotBootstrapContextFiles(params) {
|
|
2004
|
-
if (params.sourceWorkspaceDir === params.targetWorkspaceDir) return params.files;
|
|
2005
|
-
return params.files.map((file) => {
|
|
2006
|
-
const relative = path.relative(params.sourceWorkspaceDir, file.path);
|
|
2007
|
-
if (!isRelativePathInsideOrEqual(relative)) return file;
|
|
2008
|
-
return {
|
|
2009
|
-
...file,
|
|
2010
|
-
path: relative === "" ? params.targetWorkspaceDir : path.join(params.targetWorkspaceDir, relative)
|
|
2011
|
-
};
|
|
2012
|
-
});
|
|
2013
|
-
}
|
|
2014
1790
|
function isRelativePathInsideOrEqual(relativePath) {
|
|
2015
1791
|
return relativePath === "" || relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath);
|
|
2016
1792
|
}
|
|
2017
|
-
function renderCopilotWorkspaceBootstrapInstructions(contextFiles) {
|
|
2018
|
-
const files = contextFiles.filter((file) => {
|
|
2019
|
-
const baseName = getCopilotContextFileBasename(file.path);
|
|
2020
|
-
return baseName.length > 0 && !COPILOT_NATIVE_PROJECT_DOC_BASENAMES.has(baseName);
|
|
2021
|
-
}).toSorted(compareCopilotContextFiles);
|
|
2022
|
-
if (files.length === 0) return;
|
|
2023
|
-
const hasSoulFile = files.some((file) => getCopilotContextFileBasename(file.path) === "soul.md");
|
|
2024
|
-
const lines = [
|
|
2025
|
-
"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.",
|
|
2026
|
-
"",
|
|
2027
|
-
"# Project Context",
|
|
2028
|
-
"",
|
|
2029
|
-
"The following project context files have been loaded:"
|
|
2030
|
-
];
|
|
2031
|
-
if (hasSoulFile) lines.push("SOUL.md: persona/tone. Follow it unless higher-priority instructions override.");
|
|
2032
|
-
lines.push("");
|
|
2033
|
-
for (const file of files) lines.push(`## ${file.path}`, "", file.content, "");
|
|
2034
|
-
return lines.join("\n").trim();
|
|
2035
|
-
}
|
|
2036
1793
|
function compareCopilotContextFiles(left, right) {
|
|
2037
1794
|
const leftBase = getCopilotContextFileBasename(left.path);
|
|
2038
1795
|
const rightBase = getCopilotContextFileBasename(right.path);
|
|
@@ -2051,16 +1808,11 @@ function normalizeCopilotContextFilePath(filePath) {
|
|
|
2051
1808
|
function getCopilotContextFileBasename(filePath) {
|
|
2052
1809
|
return normalizeCopilotContextFilePath(filePath).split("/").pop() ?? "";
|
|
2053
1810
|
}
|
|
2054
|
-
function readResolvedWorkspacePath(value) {
|
|
2055
|
-
const raw = readNonBlankString(value);
|
|
2056
|
-
if (!raw) return;
|
|
2057
|
-
if (process.platform !== "win32" && /^[A-Za-z]:[\\/]/.test(raw)) return raw.trim();
|
|
2058
|
-
return resolveUserPath(raw);
|
|
2059
|
-
}
|
|
2060
1811
|
//#endregion
|
|
2061
1812
|
//#region extensions/copilot/src/attempt-session-setup.ts
|
|
1813
|
+
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.";
|
|
2062
1814
|
async function createCopilotSessionSetup(params) {
|
|
2063
|
-
const { attempt: input, byokProxy, effectiveCwd, effectiveWorkspaceDir, hookContext, modelRef, messages,
|
|
1815
|
+
const { attempt: input, byokProxy, effectiveCwd, effectiveWorkspaceDir, hookContext, modelRef, messages, poolAcquire, ringZeroSystemAgentRun, promptToolPolicy, sessionProvider, settledToolFinalization, signal } = params;
|
|
2064
1816
|
const ordinaryAttemptInput = settledToolFinalization ? void 0 : (() => {
|
|
2065
1817
|
assertCopilotAttemptHostCapabilities(input);
|
|
2066
1818
|
return input;
|
|
@@ -2093,13 +1845,44 @@ async function createCopilotSessionSetup(params) {
|
|
|
2093
1845
|
toolsAllow,
|
|
2094
1846
|
forceToolNames
|
|
2095
1847
|
});
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
1848
|
+
if (isRawCopilotModelRun(input)) return;
|
|
1849
|
+
const callableTools = new Set(normalizeUniqueStringEntries(promptPolicyResult.callableToolNames));
|
|
1850
|
+
const hasSessionsSpawn = callableTools.has("sessions_spawn");
|
|
1851
|
+
const isMinimal = input.promptMode === "minimal";
|
|
1852
|
+
const extraSystemPrompt = readNonEmptyStringPreservingWhitespace(input.extraSystemPrompt)?.trim();
|
|
1853
|
+
const delegationGuidance = input.disableTools !== true && input.delegationCapability !== "report_only" ? buildDelegationGuidanceSection({
|
|
1854
|
+
mode: resolveMainSessionDelegationMode({
|
|
1855
|
+
config: input.config,
|
|
1856
|
+
agentId: input.agentId,
|
|
1857
|
+
sessionKey: input.sessionKey
|
|
1858
|
+
}),
|
|
1859
|
+
isMinimal,
|
|
1860
|
+
hiddenDelegationTool: hasSessionsSpawn ? "`sessions_spawn`" : "",
|
|
1861
|
+
hasVisibleSessionSpawn: hasSessionsSpawn,
|
|
1862
|
+
hasSessionsYield: callableTools.has("sessions_yield"),
|
|
1863
|
+
hasSubagentsList: callableTools.has("subagents"),
|
|
1864
|
+
hasSessionsSend: callableTools.has("sessions_send")
|
|
1865
|
+
}).join("\n") : void 0;
|
|
1866
|
+
return [
|
|
1867
|
+
COPILOT_HARNESS_IDENTITY,
|
|
1868
|
+
promptPolicyResult.toolSchemaDirectoryPrompt,
|
|
1869
|
+
callableTools.has(SKILL_WORKSHOP_TOOL_NAME) ? buildSkillWorkshopPromptSection().join("\n") : void 0,
|
|
1870
|
+
delegationGuidance,
|
|
1871
|
+
buildHarnessVisibleReplyGuidance({
|
|
1872
|
+
sourceReplyDeliveryMode: input.sourceReplyDeliveryMode,
|
|
1873
|
+
messageToolAvailable: callableTools.has("message"),
|
|
1874
|
+
currentConversation: {
|
|
1875
|
+
agentSessionKey: input.sessionKey,
|
|
1876
|
+
currentChannelProvider: input.messageChannel ?? input.messageProvider,
|
|
1877
|
+
currentChannelId: input.currentChannelId,
|
|
1878
|
+
currentMessagingTarget: input.currentMessagingTarget
|
|
1879
|
+
},
|
|
1880
|
+
requireExplicitMessageTarget: promptToolPolicy.requireExplicitMessageTarget
|
|
1881
|
+
}),
|
|
1882
|
+
buildCredentialSafetyPrompt({ controlToolsAvailable: input.disableTools !== true && (callableTools.has("openclaw") || callableTools.has("gateway")) }),
|
|
1883
|
+
workspaceBootstrapInstructions?.trim(),
|
|
1884
|
+
extraSystemPrompt ? `${isMinimal ? "## Subagent Context" : "## Conversation Context"}\n${extraSystemPrompt}` : void 0
|
|
1885
|
+
].filter((section) => section?.trim()).join("\n\n") || void 0;
|
|
2103
1886
|
} },
|
|
2104
1887
|
messages,
|
|
2105
1888
|
ctx: hookContext,
|
|
@@ -2144,11 +1927,36 @@ async function createCopilotSessionSetup(params) {
|
|
|
2144
1927
|
signal
|
|
2145
1928
|
});
|
|
2146
1929
|
})();
|
|
2147
|
-
const buildSessionConfig = (provider) =>
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
1930
|
+
const buildSessionConfig = (provider) => {
|
|
1931
|
+
const onUserInputRequest = userInputBridge?.onUserInputRequest;
|
|
1932
|
+
const permissionPolicy = settledToolFinalization ? rejectAllPolicy : attemptInput.permissionPolicy ?? rejectAllPolicy;
|
|
1933
|
+
const hooks = settledToolFinalization ? void 0 : createHooksBridge(attemptInput.hooksConfig, hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0);
|
|
1934
|
+
const availableTools = promptTools.map((tool) => tool.name);
|
|
1935
|
+
if (includeAskUser) availableTools.push(...COPILOT_ASK_USER_AVAILABLE_TOOLS);
|
|
1936
|
+
return {
|
|
1937
|
+
model: modelRef.id,
|
|
1938
|
+
onPermissionRequest: createPermissionBridge(permissionPolicy),
|
|
1939
|
+
...onUserInputRequest ? { onUserInputRequest } : {},
|
|
1940
|
+
...provider.provider ? { provider: provider.provider } : {},
|
|
1941
|
+
...hooks ? { hooks } : {},
|
|
1942
|
+
...attemptInput.enableSessionTelemetry !== void 0 ? { enableSessionTelemetry: attemptInput.enableSessionTelemetry } : {},
|
|
1943
|
+
...settledToolFinalization ? {} : attemptInput.infiniteSessionConfig ? { infiniteSessions: attemptInput.infiniteSessionConfig } : {},
|
|
1944
|
+
reasoningEffort: attemptInput.reasoningEffort,
|
|
1945
|
+
tools: promptTools,
|
|
1946
|
+
availableTools: [...new Set(availableTools)],
|
|
1947
|
+
...settledToolFinalization ? createCopilotIsolatedSessionRestrictions() : {},
|
|
1948
|
+
workingDirectory: effectiveCwd ?? effectiveWorkspaceDir ?? readResolvedAttemptPath(attemptInput.workspaceDir),
|
|
1949
|
+
...!settledToolFinalization && effectiveWorkspaceDir && effectiveCwd && effectiveCwd !== effectiveWorkspaceDir ? { instructionDirectories: [effectiveWorkspaceDir] } : {},
|
|
1950
|
+
...poolAcquire.auth.authMode === "gitHubToken" && poolAcquire.auth.gitHubToken ? { gitHubToken: poolAcquire.auth.gitHubToken } : {},
|
|
1951
|
+
...settledToolFinalization ? { systemMessage: {
|
|
1952
|
+
mode: "customize",
|
|
1953
|
+
content: COPILOT_SETTLED_FINALIZATION_SYSTEM_MESSAGE
|
|
1954
|
+
} } : finalDeveloperInstructions ? { systemMessage: {
|
|
1955
|
+
mode: "append",
|
|
1956
|
+
content: finalDeveloperInstructions
|
|
1957
|
+
} } : {}
|
|
1958
|
+
};
|
|
1959
|
+
};
|
|
2152
1960
|
const sessionConfig = buildSessionConfig(sessionProvider);
|
|
2153
1961
|
return {
|
|
2154
1962
|
attemptInput,
|
|
@@ -2210,6 +2018,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2210
2018
|
const hiddenTurn = params.attempt.trigger === "memory";
|
|
2211
2019
|
const projectDisplay = (message) => projectAgentHarnessTranscriptMessageForDisplay({
|
|
2212
2020
|
hidden: hiddenTurn || message.display === false,
|
|
2021
|
+
inputProvenance: params.attempt.inputProvenance,
|
|
2213
2022
|
message
|
|
2214
2023
|
});
|
|
2215
2024
|
const messagesSnapshot = [...params.messages];
|
|
@@ -2286,7 +2095,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2286
2095
|
};
|
|
2287
2096
|
const prepare = (write, options = {}) => {
|
|
2288
2097
|
assertMemoryOwnerCurrent();
|
|
2289
|
-
const message =
|
|
2098
|
+
const message = write.message;
|
|
2290
2099
|
const originalReplayPayload = projectReplayPayload(message);
|
|
2291
2100
|
const hooked = runAgentHarnessBeforeMessageWriteHook({
|
|
2292
2101
|
message: structuredClone(message),
|
|
@@ -2294,6 +2103,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2294
2103
|
sessionKey: owner.kind === "durable" ? owner.target.sessionKey : params.attempt.sessionKey,
|
|
2295
2104
|
prepareAssistantTranscriptMessage: options.singleton && !hiddenTurn ? params.attempt.prepareAssistantTranscriptMessage : void 0
|
|
2296
2105
|
});
|
|
2106
|
+
assertMemoryOwnerCurrent();
|
|
2297
2107
|
if (!hooked) return;
|
|
2298
2108
|
if (!isDeepStrictEqual(originalReplayPayload, projectReplayPayload(hooked))) replayInvalid = true;
|
|
2299
2109
|
const idempotencyKey = message.idempotencyKey;
|
|
@@ -2359,7 +2169,10 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2359
2169
|
const persistedKeys = owner.kind === "memory" ? new Set(owner.manager.getEntries().flatMap((entry) => {
|
|
2360
2170
|
const key = entry.type === "message" ? readIdempotencyKey(entry.message) : void 0;
|
|
2361
2171
|
return key ? [key] : [];
|
|
2362
|
-
})) :
|
|
2172
|
+
})) : (await withSessionTranscriptWrite(owner.target, (transcript) => transcript.readMessageFacts({
|
|
2173
|
+
idempotencyKeys: keys.filter((key) => key !== void 0),
|
|
2174
|
+
activeBranchOnly: true
|
|
2175
|
+
}))).existingIdempotencyKeys;
|
|
2363
2176
|
const persistedCount = keys.filter((key) => key && persistedKeys.has(key)).length;
|
|
2364
2177
|
if (persistedCount > 0 && persistedCount < writes.length) throw new Error("Copilot transcript found a partial persisted tool group");
|
|
2365
2178
|
const messages = persistedCount === writes.length ? writes.map((write) => write.message) : writes.map((write) => prepare(write));
|
|
@@ -2640,7 +2453,7 @@ function isCurrentJournalIdentity(key, params) {
|
|
|
2640
2453
|
//#endregion
|
|
2641
2454
|
//#region extensions/copilot/src/attempt-execution.ts
|
|
2642
2455
|
async function runCopilotExecution(context) {
|
|
2643
|
-
const { params, deps, now, attemptStartedAt, settledToolFinalization, input,
|
|
2456
|
+
const { params, deps, now, attemptStartedAt, settledToolFinalization, input, ringZeroSystemAgentRun, messages, modelRef, resolvedWorkspaceForSandbox, sandboxSessionKey, sessionAgentId, hookContextWindowFields, hookContext, finishAttempt, settledFinalizationSessionId } = context;
|
|
2644
2457
|
let abortRequested = false;
|
|
2645
2458
|
let aborted = false;
|
|
2646
2459
|
let externalAbort = false;
|
|
@@ -2651,17 +2464,19 @@ async function runCopilotExecution(context) {
|
|
|
2651
2464
|
let timedOut = false;
|
|
2652
2465
|
let promptError;
|
|
2653
2466
|
let sdkSessionId;
|
|
2467
|
+
let runtimeArtifact;
|
|
2654
2468
|
let nativeSessionCreatedFresh = false;
|
|
2655
2469
|
let nativeSessionHistoryValidated = false;
|
|
2656
|
-
let disconnectError;
|
|
2657
2470
|
let handle;
|
|
2658
2471
|
let session;
|
|
2659
2472
|
let bridge;
|
|
2660
2473
|
let transcriptJournal;
|
|
2661
2474
|
let initialSdkUserValidated = false;
|
|
2662
|
-
let
|
|
2475
|
+
let activeRunRegistrationRef;
|
|
2663
2476
|
let userInputBridgeRef;
|
|
2664
2477
|
let cleanupToolBridge;
|
|
2478
|
+
let settleToolCalls;
|
|
2479
|
+
const detached = input.sessionPersistence === "detached";
|
|
2665
2480
|
let releaseError;
|
|
2666
2481
|
let downgradedFromResume = false;
|
|
2667
2482
|
let resumeFailureRecovered = false;
|
|
@@ -2681,6 +2496,7 @@ async function runCopilotExecution(context) {
|
|
|
2681
2496
|
aborted = true;
|
|
2682
2497
|
};
|
|
2683
2498
|
const abortActiveSession = () => {
|
|
2499
|
+
if (abortRequested) return;
|
|
2684
2500
|
markExternalAbort();
|
|
2685
2501
|
if (settled || !sentTurnStarted || !session) return;
|
|
2686
2502
|
session.abort().catch(() => void 0);
|
|
@@ -2689,7 +2505,6 @@ async function runCopilotExecution(context) {
|
|
|
2689
2505
|
let effectiveWorkspaceDir = resolvedWorkspaceForSandbox;
|
|
2690
2506
|
if (resolvedWorkspaceForSandbox) try {
|
|
2691
2507
|
({sandbox, effectiveWorkspaceDir} = await resolveCopilotAttemptSandbox({
|
|
2692
|
-
deps,
|
|
2693
2508
|
input,
|
|
2694
2509
|
resolvedWorkspaceForSandbox,
|
|
2695
2510
|
sandboxSessionKey
|
|
@@ -2699,21 +2514,18 @@ async function runCopilotExecution(context) {
|
|
|
2699
2514
|
aborted: true,
|
|
2700
2515
|
externalAbort: true,
|
|
2701
2516
|
messagesSnapshot: messages,
|
|
2702
|
-
promptError: void 0
|
|
2703
|
-
sdkSessionId: void 0
|
|
2517
|
+
promptError: void 0
|
|
2704
2518
|
}));
|
|
2705
2519
|
return finishAttempt(createResult(input, {
|
|
2706
2520
|
messagesSnapshot: messages,
|
|
2707
|
-
promptError: createPromptError("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error)
|
|
2708
|
-
sdkSessionId: void 0
|
|
2521
|
+
promptError: createPromptError("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error)
|
|
2709
2522
|
}));
|
|
2710
2523
|
}
|
|
2711
2524
|
hookContext.workspaceDir = effectiveWorkspaceDir;
|
|
2712
2525
|
const requestedCwd = readResolvedAttemptPath(input.cwd);
|
|
2713
2526
|
if (sandbox?.enabled && requestedCwd && requestedCwd !== resolvedWorkspaceForSandbox) return finishAttempt(createResult(input, {
|
|
2714
2527
|
messagesSnapshot: messages,
|
|
2715
|
-
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")
|
|
2716
|
-
sdkSessionId: void 0
|
|
2528
|
+
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")
|
|
2717
2529
|
}));
|
|
2718
2530
|
const effectiveCwd = sandbox?.enabled ? effectiveWorkspaceDir : requestedCwd ?? effectiveWorkspaceDir;
|
|
2719
2531
|
const effectiveFsWorkspaceOnly = resolveAttemptFsWorkspaceOnly({
|
|
@@ -2738,8 +2550,7 @@ async function runCopilotExecution(context) {
|
|
|
2738
2550
|
} catch (error) {
|
|
2739
2551
|
return finishAttempt(createResult(input, {
|
|
2740
2552
|
messagesSnapshot: messages,
|
|
2741
|
-
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
2742
|
-
sdkSessionId: void 0
|
|
2553
|
+
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
2743
2554
|
}));
|
|
2744
2555
|
}
|
|
2745
2556
|
const cleanupByokProxy = byokProxy?.close;
|
|
@@ -2749,12 +2560,13 @@ async function runCopilotExecution(context) {
|
|
|
2749
2560
|
let codeModeEngaged;
|
|
2750
2561
|
let promptToolPolicy;
|
|
2751
2562
|
try {
|
|
2563
|
+
if (!settledToolFinalization && effectiveCwd && !sandbox?.enabled) input.hostCapabilities?.prepareContinuationRetryCount?.({ cwd: effectiveCwd });
|
|
2752
2564
|
params.abortSignal?.addEventListener("abort", abortActiveSession, { once: true });
|
|
2753
2565
|
if (params.abortSignal?.aborted) abortActiveSession();
|
|
2754
2566
|
let resultContentSourceByToolName = /* @__PURE__ */ new Map();
|
|
2755
2567
|
if (!settledToolFinalization) try {
|
|
2756
2568
|
assertCopilotAttemptHostCapabilities(input);
|
|
2757
|
-
const toolBridge = await
|
|
2569
|
+
const toolBridge = await createCopilotToolBridge({
|
|
2758
2570
|
allowModelTools: poolAcquire.provider.mode === "byok",
|
|
2759
2571
|
modelProvider: modelRef.provider,
|
|
2760
2572
|
modelId: modelRef.id,
|
|
@@ -2796,17 +2608,20 @@ async function runCopilotExecution(context) {
|
|
|
2796
2608
|
}
|
|
2797
2609
|
});
|
|
2798
2610
|
cleanupToolBridge = toolBridge.cleanup;
|
|
2611
|
+
settleToolCalls = toolBridge.settle;
|
|
2799
2612
|
codeModeEngaged = toolBridge.codeModeEngaged;
|
|
2800
2613
|
promptToolPolicy = toolBridge.promptToolPolicy;
|
|
2801
2614
|
resultContentSourceByToolName = new Map(toolBridge.sourceTools.flatMap((tool) => tool.resultContentSource ? [[tool.name, tool.resultContentSource]] : []));
|
|
2802
2615
|
} catch (error) {
|
|
2803
2616
|
return finishAttempt(createResult(input, {
|
|
2804
2617
|
messagesSnapshot: messages,
|
|
2805
|
-
promptError: createPromptError("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error)
|
|
2806
|
-
sdkSessionId: void 0
|
|
2618
|
+
promptError: createPromptError("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error)
|
|
2807
2619
|
}));
|
|
2808
2620
|
}
|
|
2809
|
-
|
|
2621
|
+
const artifactRequest = input.captureRuntimeArtifact || input.expectedRuntimeArtifact ? { expected: input.expectedRuntimeArtifact } : void 0;
|
|
2622
|
+
handle = artifactRequest ? await deps.pool.acquire(poolAcquire.key, poolAcquire.options, artifactRequest) : await deps.pool.acquire(poolAcquire.key, poolAcquire.options);
|
|
2623
|
+
runtimeArtifact = handle.runtimeArtifact;
|
|
2624
|
+
if (artifactRequest && !runtimeArtifact) throw new Error("[copilot] verified attempt requires a captured runtime artifact");
|
|
2810
2625
|
const client = handle.client;
|
|
2811
2626
|
const sessionSetup = await createCopilotSessionSetup({
|
|
2812
2627
|
attempt: input,
|
|
@@ -2816,7 +2631,6 @@ async function runCopilotExecution(context) {
|
|
|
2816
2631
|
hookContext,
|
|
2817
2632
|
modelRef,
|
|
2818
2633
|
messages,
|
|
2819
|
-
operation: deps.operation,
|
|
2820
2634
|
poolAcquire,
|
|
2821
2635
|
ringZeroSystemAgentRun,
|
|
2822
2636
|
promptToolPolicy,
|
|
@@ -2826,7 +2640,7 @@ async function runCopilotExecution(context) {
|
|
|
2826
2640
|
});
|
|
2827
2641
|
const { attemptInput, compactionSessionConfig, emitLlmInput, hasNativePromptHook, sessionConfig, userInputBridge } = sessionSetup;
|
|
2828
2642
|
userInputBridgeRef = userInputBridge;
|
|
2829
|
-
const previousSessionId = normalizeOptionalString(input.initialReplayState?.sdkSessionId);
|
|
2643
|
+
const previousSessionId = detached ? void 0 : normalizeOptionalString(input.initialReplayState?.sdkSessionId);
|
|
2830
2644
|
downgradedFromResume = Boolean(previousSessionId && input.initialReplayState?.replayInvalid === true);
|
|
2831
2645
|
const resumeSessionId = settledToolFinalization ? settledFinalizationSessionId : downgradedFromResume ? void 0 : previousSessionId;
|
|
2832
2646
|
if (resumeSessionId) try {
|
|
@@ -2907,7 +2721,7 @@ async function runCopilotExecution(context) {
|
|
|
2907
2721
|
if (!settledToolFinalization) {
|
|
2908
2722
|
assertCopilotAttemptHostCapabilities(input);
|
|
2909
2723
|
if (!userInputBridge) throw new Error("[copilot-attempt] ordinary attempts require a user-input bridge");
|
|
2910
|
-
|
|
2724
|
+
activeRunRegistrationRef = registerCopilotActiveRun({
|
|
2911
2725
|
abortActiveSession,
|
|
2912
2726
|
agentId: sessionAgentId,
|
|
2913
2727
|
bridge,
|
|
@@ -2975,6 +2789,7 @@ async function runCopilotExecution(context) {
|
|
|
2975
2789
|
}
|
|
2976
2790
|
} finally {
|
|
2977
2791
|
settled = true;
|
|
2792
|
+
if (detached) await settleToolCalls?.();
|
|
2978
2793
|
try {
|
|
2979
2794
|
bridge?.flushTranscriptProjection();
|
|
2980
2795
|
await transcriptJournal?.barrier("bridge detach");
|
|
@@ -2982,34 +2797,35 @@ async function runCopilotExecution(context) {
|
|
|
2982
2797
|
promptError = toCopilotError(transcriptError);
|
|
2983
2798
|
}
|
|
2984
2799
|
userInputBridgeRef?.cancelPending();
|
|
2985
|
-
if (
|
|
2986
|
-
|
|
2987
|
-
clearActiveEmbeddedRun(input.sessionId,
|
|
2800
|
+
if (activeRunRegistrationRef) {
|
|
2801
|
+
const { attachment, handle: activeRunHandle } = activeRunRegistrationRef;
|
|
2802
|
+
clearActiveEmbeddedRun(input.sessionId, activeRunHandle, input.sessionKey, input.sessionFile, void 0, attachment);
|
|
2988
2803
|
}
|
|
2989
2804
|
const journalSnapshot = transcriptJournal?.snapshot();
|
|
2990
2805
|
const initialUserValidated = !sentTurnStarted || settledToolFinalization || journalSnapshot?.initialSdkUserValidated === true;
|
|
2991
2806
|
if (journalSnapshot?.replayInvalid !== true && (bridge?.hasObservedCompaction() || timedOut && bridge?.hasObservedSessionIdle() === false) && bridge && session && handle) {
|
|
2992
2807
|
const cleanupAbort = new AbortController();
|
|
2993
|
-
const abortCleanup = () => cleanupAbort.abort();
|
|
2994
|
-
if (params.abortSignal?.aborted) abortCleanup();
|
|
2995
|
-
else params.abortSignal?.addEventListener("abort", abortCleanup, { once: true });
|
|
2996
2808
|
const cleanup = deferBackgroundCompactionCleanup({
|
|
2997
|
-
abortSignal: cleanupAbort.signal,
|
|
2809
|
+
abortSignal: params.abortSignal ? AbortSignal.any([params.abortSignal, cleanupAbort.signal]) : cleanupAbort.signal,
|
|
2998
2810
|
awaitSessionIdle: !bridge.hasObservedSessionIdle(),
|
|
2999
2811
|
bridge,
|
|
3000
2812
|
cleanupToolBridge,
|
|
3001
2813
|
cleanupByokProxy,
|
|
3002
2814
|
deleteSessionOnIncompleteCleanup: nativeSessionCreatedFresh && initialUserValidated,
|
|
2815
|
+
deleteSessionOnCleanup: detached && nativeSessionCreatedFresh,
|
|
3003
2816
|
handle,
|
|
3004
2817
|
pool: deps.pool,
|
|
3005
2818
|
sdkSessionId,
|
|
3006
2819
|
session,
|
|
3007
2820
|
timeoutMs: resolveCompactionTimeoutMs(input.config)
|
|
3008
2821
|
});
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
}
|
|
3012
|
-
|
|
2822
|
+
if (detached) try {
|
|
2823
|
+
await cleanup;
|
|
2824
|
+
} catch (error) {
|
|
2825
|
+
promptError = preserveCopilotAttemptCleanupError(promptError, error);
|
|
2826
|
+
}
|
|
2827
|
+
else cleanup.catch(() => void 0);
|
|
2828
|
+
if (!detached && sdkSessionId && !settledToolFinalization) try {
|
|
3013
2829
|
await deps.onDeferredCompaction?.({
|
|
3014
2830
|
abort: () => cleanupAbort.abort(),
|
|
3015
2831
|
cleanup,
|
|
@@ -3022,13 +2838,22 @@ async function runCopilotExecution(context) {
|
|
|
3022
2838
|
bridge?.detach();
|
|
3023
2839
|
await bridge?.awaitAgentEventChain();
|
|
3024
2840
|
cleanupToolBridge?.();
|
|
3025
|
-
|
|
2841
|
+
try {
|
|
2842
|
+
await cleanupByokProxy?.();
|
|
2843
|
+
} catch (error) {
|
|
2844
|
+
if (detached) promptError = preserveCopilotAttemptCleanupError(promptError, error);
|
|
2845
|
+
else releaseError = toCopilotError(error);
|
|
2846
|
+
}
|
|
3026
2847
|
params.abortSignal?.removeEventListener("abort", abortActiveSession);
|
|
3027
|
-
if (session) try {
|
|
3028
|
-
await
|
|
2848
|
+
if (session && handle) try {
|
|
2849
|
+
await disconnectCopilotSession({
|
|
2850
|
+
session,
|
|
2851
|
+
client: handle.client,
|
|
2852
|
+
deleteSessionId: detached && nativeSessionCreatedFresh ? sdkSessionId : void 0
|
|
2853
|
+
});
|
|
3029
2854
|
} catch (error) {
|
|
3030
|
-
|
|
3031
|
-
if (!promptError && !timedOut) promptError =
|
|
2855
|
+
if (detached) promptError = preserveCopilotAttemptCleanupError(promptError, error);
|
|
2856
|
+
else if (!promptError && !timedOut) promptError = toCopilotError(error);
|
|
3032
2857
|
}
|
|
3033
2858
|
if (handle) try {
|
|
3034
2859
|
await deps.pool.release(handle);
|
|
@@ -3059,6 +2884,7 @@ async function runCopilotExecution(context) {
|
|
|
3059
2884
|
promptError,
|
|
3060
2885
|
releaseError,
|
|
3061
2886
|
resumeFailureRecovered,
|
|
2887
|
+
runtimeArtifact,
|
|
3062
2888
|
sdkSessionId,
|
|
3063
2889
|
sentTurnStarted,
|
|
3064
2890
|
settledFinalizationAssistantCompleted,
|
|
@@ -3072,7 +2898,7 @@ async function runCopilotExecution(context) {
|
|
|
3072
2898
|
//#endregion
|
|
3073
2899
|
//#region extensions/copilot/src/attempt.ts
|
|
3074
2900
|
async function runCopilotAttempt(params, deps) {
|
|
3075
|
-
const now =
|
|
2901
|
+
const now = Date.now;
|
|
3076
2902
|
const attemptStartedAt = now();
|
|
3077
2903
|
const prepared = prepareCopilotAttemptContext(params, deps);
|
|
3078
2904
|
const { settledToolFinalization, input, messages, modelRef, hookContext } = prepared;
|
|
@@ -3081,8 +2907,7 @@ async function runCopilotAttempt(params, deps) {
|
|
|
3081
2907
|
aborted: true,
|
|
3082
2908
|
externalAbort: true,
|
|
3083
2909
|
messagesSnapshot: messages,
|
|
3084
|
-
promptError: void 0
|
|
3085
|
-
sdkSessionId: void 0
|
|
2910
|
+
promptError: void 0
|
|
3086
2911
|
}));
|
|
3087
2912
|
try {
|
|
3088
2913
|
resolveCopilotProvider({
|
|
@@ -3093,15 +2918,13 @@ async function runCopilotAttempt(params, deps) {
|
|
|
3093
2918
|
} catch (error) {
|
|
3094
2919
|
return finishAttempt(createResult(input, {
|
|
3095
2920
|
messagesSnapshot: messages,
|
|
3096
|
-
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
3097
|
-
sdkSessionId: void 0
|
|
2921
|
+
promptError: createPromptError("model_not_supported", toCopilotError(error).message, error)
|
|
3098
2922
|
}));
|
|
3099
2923
|
}
|
|
3100
2924
|
const settledFinalizationSessionId = settledToolFinalization ? readNonEmptyString(input.initialReplayState?.sdkSessionId) : void 0;
|
|
3101
2925
|
if (settledToolFinalization && !settledFinalizationSessionId) return finishAttempt(createResult(input, {
|
|
3102
2926
|
messagesSnapshot: messages,
|
|
3103
|
-
promptError: createPromptError("settled_finalization_session_unavailable", "[copilot-attempt] settled tool finalization requires the existing Copilot SDK session")
|
|
3104
|
-
sdkSessionId: void 0
|
|
2927
|
+
promptError: createPromptError("settled_finalization_session_unavailable", "[copilot-attempt] settled tool finalization requires the existing Copilot SDK session")
|
|
3105
2928
|
}));
|
|
3106
2929
|
return await runCopilotExecution({
|
|
3107
2930
|
...prepared,
|