@openclaw/copilot 2026.7.2-beta.7 → 2026.7.34
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 +3 -1
- package/dist/{attempt-D6tQnv01.js → .setup/attempt-BohTAZ-k.mjs} +1374 -2220
- package/dist/{harness-D0K-5kNw.js → .setup/harness-D3I2IcZQ.mjs} +97 -145
- package/dist/{runtime-BY2Yi3Dg.js → .setup/runtime-BD2O8GCd.mjs} +7 -9
- package/dist/doctor-contract-api.js +2 -1
- package/dist/harness.js +1 -1
- package/dist/index.js +2 -2
- package/package.json +6 -5
|
@@ -1,728 +1,218 @@
|
|
|
1
|
-
import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-
|
|
2
|
-
import { applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHookContextChannelFields, buildEmbeddedAttemptToolRunContext,
|
|
1
|
+
import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-D3I2IcZQ.mjs";
|
|
2
|
+
import { applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHarnessUserInputAnswers, buildAgentHookContextChannelFields, buildEmbeddedAttemptToolRunContext, clearActiveEmbeddedRun, deliverAgentHarnessUserInputPrompt, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, isSubagentSessionKey, isToolResultError, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveModelAuthMode, resolveSandboxContext, resolveSessionAgentIds, resolveUserPath, runAgentEndSideEffects, runAgentHarnessAfterCompactionHook, runAgentHarnessAfterToolCallHook, runAgentHarnessBeforeCompactionHook, runAgentHarnessBeforeMessageWriteHook, runAgentHarnessLlmInputHook, runAgentHarnessLlmOutputHook, sanitizeToolResult, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import fsp from "node:fs/promises";
|
|
5
|
-
import {
|
|
6
|
-
import { createAgentHarnessToolSurfaceRuntime } from "openclaw/plugin-sdk/agent-harness-tool-runtime";
|
|
7
|
-
import { isDeepStrictEqual } from "node:util";
|
|
8
|
-
import { appendSessionTranscriptMessageByIdentityStrict, appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity, readVisibleSessionTranscriptMessageEntries } from "openclaw/plugin-sdk/session-transcript-runtime";
|
|
6
|
+
import { publishSessionTranscriptUpdateByIdentity, withSessionTranscriptWriteLock } from "openclaw/plugin-sdk/session-transcript-runtime";
|
|
9
7
|
import { createAgentHarnessTaskRuntime } from "openclaw/plugin-sdk/agent-harness-task-runtime";
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
kind: "failed",
|
|
28
|
-
source: "prompt",
|
|
29
|
-
error
|
|
30
|
-
};
|
|
8
|
+
import { createAgentHarnessToolSurfaceRuntime } from "openclaw/plugin-sdk/agent-harness-tool-runtime";
|
|
9
|
+
//#region extensions/copilot/src/compaction-bridge.ts
|
|
10
|
+
/**
|
|
11
|
+
* Shape an `InfiniteSessionConfig` for `SessionConfig.infiniteSessions`.
|
|
12
|
+
* Returns `undefined` when no fields were supplied so callers can
|
|
13
|
+
* spread conditionally and let the SDK apply its own defaults
|
|
14
|
+
* (`enabled: true`, background 0.80, buffer 0.95). Any explicitly-set
|
|
15
|
+
* value (including `enabled: false` to disable infinite sessions) is
|
|
16
|
+
* preserved.
|
|
17
|
+
*/
|
|
18
|
+
function createInfiniteSessionConfig(options) {
|
|
19
|
+
if (!options) return;
|
|
20
|
+
const result = {};
|
|
21
|
+
if (options.enabled !== void 0) result.enabled = options.enabled;
|
|
22
|
+
if (options.backgroundCompactionThreshold !== void 0) result.backgroundCompactionThreshold = options.backgroundCompactionThreshold;
|
|
23
|
+
if (options.bufferExhaustionThreshold !== void 0) result.bufferExhaustionThreshold = options.bufferExhaustionThreshold;
|
|
24
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
31
25
|
}
|
|
32
26
|
//#endregion
|
|
33
|
-
//#region extensions/copilot/src/
|
|
34
|
-
const DEFAULT_HOOK_ERROR_HANDLER = ({ hookName, error }) => {
|
|
35
|
-
console.warn(`[copilot hooks-bridge] ${hookName} handler threw:`, error);
|
|
36
|
-
};
|
|
27
|
+
//#region extensions/copilot/src/dual-write-transcripts.ts
|
|
37
28
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
29
|
+
* Mirrors the AgentMessages produced by the copilot agent runtime into the
|
|
30
|
+
* OpenClaw audit transcript that sits next to (but is distinct from) the
|
|
31
|
+
* SDK's own session storage.
|
|
32
|
+
*
|
|
33
|
+
* The OpenClaw shell (src/agents/command/attempt-execution.ts) already
|
|
34
|
+
* writes the user prompt and the terminal assistant text into the
|
|
35
|
+
* transcript at the end of each attempt. That is the bare minimum to
|
|
36
|
+
* keep `/history` working. It does NOT capture tool calls, tool
|
|
37
|
+
* results, or intermediate assistant turns — those live only in the
|
|
38
|
+
* SDK's own session file.
|
|
39
|
+
*
|
|
40
|
+
* For audit/compliance and for the codex-parity guarantees we promised
|
|
41
|
+
* in the proposal, we mirror the full `messagesSnapshot` (user +
|
|
42
|
+
* assistant + toolResult) into the OpenClaw transcript via the same
|
|
43
|
+
* plugin-sdk primitives that the codex extension uses
|
|
44
|
+
* (extensions/codex/src/app-server/transcript-mirror.ts). Both writers
|
|
45
|
+
* cooperate via idempotency-key dedupe: user entries retain a gateway
|
|
46
|
+
* turn key when present; other entries use `${idempotencyScope}:${identity}`.
|
|
47
|
+
* We skip any key already present in the transcript on disk. Both
|
|
48
|
+
* attempt-execution's untagged entries (no idempotencyKey) and our
|
|
49
|
+
* tagged mirror entries can coexist; attempt-execution dedupes its own
|
|
50
|
+
* final-assistant append via `embeddedAssistantGapFill` content match.
|
|
51
|
+
*
|
|
52
|
+
* Failures (lock contention, fs errors, etc.) are swallowed by the
|
|
53
|
+
* caller-side `dualWriteCopilotTranscriptBestEffort` wrapper used
|
|
54
|
+
* in attempt.ts so they cannot break the attempt; this module itself
|
|
55
|
+
* throws on infrastructure failure so callers can choose policy.
|
|
40
56
|
*/
|
|
41
|
-
|
|
42
|
-
if (!handler) return;
|
|
43
|
-
return async (...args) => {
|
|
44
|
-
try {
|
|
45
|
-
return await handler(...args);
|
|
46
|
-
} catch (error) {
|
|
47
|
-
try {
|
|
48
|
-
onError({
|
|
49
|
-
hookName,
|
|
50
|
-
error
|
|
51
|
-
});
|
|
52
|
-
} catch {}
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
+
const MIRROR_IDENTITY_META_KEY = "mirrorIdentity";
|
|
57
58
|
/**
|
|
58
|
-
*
|
|
59
|
-
*
|
|
59
|
+
* Tag a message with a stable logical identity for mirror dedupe.
|
|
60
|
+
* Callers should use a value that is invariant for the same logical
|
|
61
|
+
* message across re-emits (e.g. `${sdkSessionId}:assistant:${turnIndex}`)
|
|
62
|
+
* but distinct for genuinely-distinct messages. When present this
|
|
63
|
+
* identity replaces the role/content fingerprint in the idempotency
|
|
64
|
+
* key, so the dedupe survives caller-scope rotation without collapsing
|
|
65
|
+
* distinct same-content turns. Symmetric to
|
|
66
|
+
* `attachCodexMirrorIdentity` in the codex extension.
|
|
60
67
|
*/
|
|
61
|
-
function
|
|
62
|
-
|
|
63
|
-
const
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const sessionStart = isolate("onSessionStart", config.onSessionStart, onError);
|
|
71
|
-
const sessionEnd = isolate("onSessionEnd", config.onSessionEnd, onError);
|
|
72
|
-
const errorOccurred = isolate("onErrorOccurred", config.onErrorOccurred, onError);
|
|
73
|
-
if (pre) hooks.onPreToolUse = pre;
|
|
74
|
-
if (preMcp) hooks.onPreMcpToolCall = preMcp;
|
|
75
|
-
if (post) hooks.onPostToolUse = post;
|
|
76
|
-
if (postFailure) hooks.onPostToolUseFailure = postFailure;
|
|
77
|
-
if (userPrompt) hooks.onUserPromptSubmitted = async (input, invocation) => {
|
|
78
|
-
const output = await userPrompt(input, invocation);
|
|
79
|
-
try {
|
|
80
|
-
options?.onUserPromptSubmitted?.({
|
|
81
|
-
prompt: output?.modifiedPrompt ?? input.prompt,
|
|
82
|
-
...output?.additionalContext ? { additionalContext: output.additionalContext } : {}
|
|
83
|
-
});
|
|
84
|
-
} catch (error) {
|
|
85
|
-
try {
|
|
86
|
-
onError({
|
|
87
|
-
hookName: "onUserPromptSubmitted",
|
|
88
|
-
error
|
|
89
|
-
});
|
|
90
|
-
} catch {}
|
|
68
|
+
function attachCopilotMirrorIdentity(message, identity) {
|
|
69
|
+
const record = message;
|
|
70
|
+
const existing = record["__openclaw"];
|
|
71
|
+
const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
|
|
72
|
+
return {
|
|
73
|
+
...record,
|
|
74
|
+
__openclaw: {
|
|
75
|
+
...baseMeta,
|
|
76
|
+
[MIRROR_IDENTITY_META_KEY]: identity
|
|
91
77
|
}
|
|
92
|
-
return output;
|
|
93
78
|
};
|
|
94
|
-
if (sessionStart) hooks.onSessionStart = sessionStart;
|
|
95
|
-
if (sessionEnd) hooks.onSessionEnd = sessionEnd;
|
|
96
|
-
if (errorOccurred) hooks.onErrorOccurred = errorOccurred;
|
|
97
|
-
return Object.keys(hooks).length > 0 ? hooks : void 0;
|
|
98
79
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
80
|
+
function readMirrorIdentity(message) {
|
|
81
|
+
const meta = message["__openclaw"];
|
|
82
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return;
|
|
83
|
+
const id = meta[MIRROR_IDENTITY_META_KEY];
|
|
84
|
+
return typeof id === "string" && id.length > 0 ? id : void 0;
|
|
85
|
+
}
|
|
86
|
+
function fingerprintMirrorMessageContent(message) {
|
|
87
|
+
const payload = JSON.stringify({
|
|
88
|
+
role: message.role,
|
|
89
|
+
content: message.content
|
|
90
|
+
});
|
|
91
|
+
return createHash("sha256").update(payload).digest("hex").slice(0, 16);
|
|
92
|
+
}
|
|
93
|
+
function buildMirrorDedupeIdentity(message) {
|
|
94
|
+
const explicit = readMirrorIdentity(message);
|
|
95
|
+
if (explicit) return explicit;
|
|
96
|
+
return `${message.role}:${fingerprintMirrorMessageContent(message)}`;
|
|
97
|
+
}
|
|
98
|
+
async function mirrorCopilotTranscript(params) {
|
|
99
|
+
const messages = params.messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
|
|
100
|
+
if (messages.length === 0) return;
|
|
101
|
+
const transcriptTarget = resolveCopilotMirrorTranscriptTarget(params);
|
|
102
|
+
if (await withSessionTranscriptWriteLock({
|
|
103
|
+
...transcriptTarget,
|
|
104
|
+
config: params.config
|
|
105
|
+
}, async (transcript) => {
|
|
106
|
+
let didAppendMessage = false;
|
|
107
|
+
const existingIdempotencyKeys = readTranscriptIdempotencyKeys(await transcript.readEvents());
|
|
108
|
+
for (const message of messages) {
|
|
109
|
+
const dedupeIdentity = buildMirrorDedupeIdentity(message);
|
|
110
|
+
const sourceIdempotencyKey = message.idempotencyKey;
|
|
111
|
+
const idempotencyKey = (message.role === "user" && typeof sourceIdempotencyKey === "string" && sourceIdempotencyKey.trim() ? sourceIdempotencyKey.trim() : void 0) ?? (params.idempotencyScope ? `${params.idempotencyScope}:${dedupeIdentity}` : void 0);
|
|
112
|
+
if (idempotencyKey && existingIdempotencyKeys.has(idempotencyKey)) continue;
|
|
113
|
+
const transcriptMessage = {
|
|
114
|
+
...message,
|
|
115
|
+
...idempotencyKey ? { idempotencyKey } : {}
|
|
126
116
|
};
|
|
117
|
+
const nextMessage = runAgentHarnessBeforeMessageWriteHook({
|
|
118
|
+
message: transcriptMessage,
|
|
119
|
+
agentId: params.agentId,
|
|
120
|
+
sessionKey: params.sessionKey
|
|
121
|
+
});
|
|
122
|
+
if (!nextMessage) continue;
|
|
123
|
+
const messageToAppend = idempotencyKey ? {
|
|
124
|
+
...nextMessage,
|
|
125
|
+
idempotencyKey
|
|
126
|
+
} : nextMessage;
|
|
127
|
+
if (!await transcript.appendMessage({
|
|
128
|
+
message: messageToAppend,
|
|
129
|
+
idempotencyLookup: idempotencyKey ? "caller-checked" : "scan"
|
|
130
|
+
})) continue;
|
|
131
|
+
didAppendMessage = true;
|
|
132
|
+
if (idempotencyKey) existingIdempotencyKeys.add(idempotencyKey);
|
|
127
133
|
}
|
|
128
|
-
return
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
};
|
|
134
|
+
return didAppendMessage;
|
|
135
|
+
})) await publishSessionTranscriptUpdateByIdentity({
|
|
136
|
+
...transcriptTarget,
|
|
137
|
+
update: params.sessionKey ? { sessionKey: params.sessionKey } : void 0
|
|
138
|
+
});
|
|
133
139
|
}
|
|
134
|
-
function
|
|
135
|
-
|
|
140
|
+
function resolveCopilotMirrorTranscriptTarget(params) {
|
|
141
|
+
const sessionFile = params.sessionFile.trim();
|
|
142
|
+
if (!sessionFile) throw new Error("Copilot transcript mirror requires a sessionFile target");
|
|
143
|
+
return {
|
|
144
|
+
...params.agentId ? { agentId: params.agentId } : {},
|
|
145
|
+
sessionFile,
|
|
146
|
+
sessionId: params.sessionId,
|
|
147
|
+
sessionKey: params.sessionKey ?? ""
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function readTranscriptIdempotencyKeys(events) {
|
|
151
|
+
const keys = /* @__PURE__ */ new Set();
|
|
152
|
+
for (const event of events) {
|
|
153
|
+
if (!event || typeof event !== "object" || Array.isArray(event)) continue;
|
|
154
|
+
const parsed = event;
|
|
155
|
+
if (typeof parsed.message?.idempotencyKey === "string") keys.add(parsed.message.idempotencyKey);
|
|
156
|
+
}
|
|
157
|
+
return keys;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Caller-side wrapper that swallows mirror failures. attempt.ts uses
|
|
161
|
+
* this so that a transient transcript-mirror failure (lock contention,
|
|
162
|
+
* disk full, etc.) never breaks an otherwise-successful attempt. The
|
|
163
|
+
* SDK's own session file remains the source of truth in that case;
|
|
164
|
+
* the OpenClaw audit trail just misses the intermediate messages for
|
|
165
|
+
* this turn.
|
|
166
|
+
*/
|
|
167
|
+
async function dualWriteCopilotTranscriptBestEffort(params) {
|
|
136
168
|
try {
|
|
137
|
-
|
|
138
|
-
} catch {
|
|
139
|
-
|
|
169
|
+
await mirrorCopilotTranscript(params);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
console.warn("[copilot-attempt] dual-write transcript mirror failed", error);
|
|
140
172
|
}
|
|
141
173
|
}
|
|
142
174
|
//#endregion
|
|
143
|
-
//#region extensions/copilot/src/
|
|
144
|
-
function
|
|
145
|
-
|
|
146
|
-
const trimmed = value.trim();
|
|
147
|
-
return trimmed.length > 0 ? trimmed : void 0;
|
|
175
|
+
//#region extensions/copilot/src/usage-bridge.ts
|
|
176
|
+
function isCopilotUsageSource(data) {
|
|
177
|
+
return typeof data === "object" && data !== null;
|
|
148
178
|
}
|
|
149
|
-
|
|
150
|
-
* Pure pre-call decision: should attempt.ts call resumeSession or
|
|
151
|
-
* createSession?
|
|
152
|
-
*
|
|
153
|
-
* Rules:
|
|
154
|
-
* - No input → create (no-replay-state)
|
|
155
|
-
* - No (trimmed) sdkSessionId → create (no-sdk-session-id)
|
|
156
|
-
* - sdkSessionId + replayInvalid=true → create (replay-invalid),
|
|
157
|
-
* downgradedFromResume=true
|
|
158
|
-
* - sdkSessionId + replayInvalid=false → resume
|
|
159
|
-
*/
|
|
160
|
-
function decideReplayAction(input) {
|
|
161
|
-
if (!input) return {
|
|
162
|
-
action: "create",
|
|
163
|
-
downgradedFromResume: false,
|
|
164
|
-
downgradeReason: "no-replay-state"
|
|
165
|
-
};
|
|
166
|
-
const sdkSessionId = normalizeSdkSessionId(input.sdkSessionId);
|
|
167
|
-
if (!sdkSessionId) return {
|
|
168
|
-
action: "create",
|
|
169
|
-
downgradedFromResume: false,
|
|
170
|
-
downgradeReason: "no-sdk-session-id"
|
|
171
|
-
};
|
|
172
|
-
if (input.replayInvalid === true) return {
|
|
173
|
-
action: "create",
|
|
174
|
-
downgradedFromResume: true,
|
|
175
|
-
downgradeReason: "replay-invalid"
|
|
176
|
-
};
|
|
179
|
+
function buildZeroCost() {
|
|
177
180
|
return {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
+
cacheRead: 0,
|
|
182
|
+
cacheWrite: 0,
|
|
183
|
+
input: 0,
|
|
184
|
+
output: 0,
|
|
185
|
+
total: 0
|
|
181
186
|
};
|
|
182
187
|
}
|
|
183
|
-
|
|
184
|
-
"
|
|
185
|
-
"session_not_found",
|
|
186
|
-
"NotFound",
|
|
187
|
-
"ENOENT"
|
|
188
|
-
]);
|
|
189
|
-
const MISSING_SESSION_MESSAGE_PATTERNS = [
|
|
190
|
-
/\bsession not found\b/i,
|
|
191
|
-
/\bsession .* not found\b/i,
|
|
192
|
-
/\bunknown session id\b/i,
|
|
193
|
-
/\bsession id .* (does not exist|not found)\b/i,
|
|
194
|
-
/\bsession .* does not exist\b/i,
|
|
195
|
-
/\bno such session\b/i
|
|
196
|
-
];
|
|
197
|
-
function readErrorField(error, key) {
|
|
198
|
-
if (!error || typeof error !== "object") return;
|
|
199
|
-
return error[key];
|
|
188
|
+
function coerceTokenCount(value) {
|
|
189
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : void 0;
|
|
200
190
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
*/
|
|
214
|
-
function classifyResumeFailure(error) {
|
|
215
|
-
if (error === void 0 || error === null) return {
|
|
216
|
-
recoverable: false,
|
|
217
|
-
kind: "unknown"
|
|
218
|
-
};
|
|
219
|
-
if (readErrorField(error, "status") === 404) return {
|
|
220
|
-
recoverable: true,
|
|
221
|
-
kind: "missing"
|
|
222
|
-
};
|
|
223
|
-
if (readErrorField(error, "statusCode") === 404) return {
|
|
224
|
-
recoverable: true,
|
|
225
|
-
kind: "missing"
|
|
226
|
-
};
|
|
227
|
-
const code = readErrorField(error, "code");
|
|
228
|
-
if (typeof code === "string" && MISSING_SESSION_CODES.has(code)) return {
|
|
229
|
-
recoverable: true,
|
|
230
|
-
kind: "missing"
|
|
191
|
+
function normalizeCopilotUsage(data) {
|
|
192
|
+
if (!isCopilotUsageSource(data)) return;
|
|
193
|
+
const input = coerceTokenCount(data.inputTokens);
|
|
194
|
+
const output = coerceTokenCount(data.outputTokens);
|
|
195
|
+
const cacheRead = coerceTokenCount(data.cacheReadTokens);
|
|
196
|
+
const cacheWrite = coerceTokenCount(data.cacheWriteTokens);
|
|
197
|
+
return {
|
|
198
|
+
cacheRead,
|
|
199
|
+
cacheWrite,
|
|
200
|
+
input,
|
|
201
|
+
output,
|
|
202
|
+
total: (input ?? 0) + (output ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0)
|
|
231
203
|
};
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
recoverable: true,
|
|
236
|
-
kind: "missing"
|
|
237
|
-
};
|
|
238
|
-
}
|
|
204
|
+
}
|
|
205
|
+
function buildCopilotAssistantUsage(params) {
|
|
206
|
+
const usage = params.usage ?? normalizeCopilotUsage({ outputTokens: params.fallbackOutputTokens });
|
|
239
207
|
return {
|
|
240
|
-
|
|
241
|
-
|
|
208
|
+
cacheRead: usage?.cacheRead ?? 0,
|
|
209
|
+
cacheWrite: usage?.cacheWrite ?? 0,
|
|
210
|
+
cost: buildZeroCost(),
|
|
211
|
+
input: usage?.input ?? 0,
|
|
212
|
+
output: usage?.output ?? 0,
|
|
213
|
+
totalTokens: usage?.total ?? 0
|
|
242
214
|
};
|
|
243
215
|
}
|
|
244
|
-
/**
|
|
245
|
-
* Compute the `EmbeddedRunReplayMetadata` to attach to the attempt
|
|
246
|
-
* result. Worst-case-wins:
|
|
247
|
-
*
|
|
248
|
-
* hadPotentialSideEffects = priorHadPotentialSideEffects OR timedOut
|
|
249
|
-
* OR thisAttemptHadPotentialSideEffects
|
|
250
|
-
* (timeout means we cannot prove the prompt was not partially
|
|
251
|
-
* committed server-side; treat as side-effecting so the
|
|
252
|
-
* orchestrator will not blindly re-issue the same prompt).
|
|
253
|
-
*
|
|
254
|
-
* replaySafe = NOT (
|
|
255
|
-
* priorReplayInvalid
|
|
256
|
-
* OR thisAttemptDowngradedFromResume
|
|
257
|
-
* OR thisAttemptResumeFailureRecovered
|
|
258
|
-
* OR hadPotentialSideEffects
|
|
259
|
-
* )
|
|
260
|
-
*
|
|
261
|
-
* Matches the parity rule in
|
|
262
|
-
* `src/agents/pi-embedded-runner/replay-state.ts#replayMetadataFromState`.
|
|
263
|
-
*/
|
|
264
|
-
function computeReplayMetadata(input) {
|
|
265
|
-
const priorReplayInvalid = input.priorReplayInvalid === true;
|
|
266
|
-
const priorHadPotentialSideEffects = input.priorHadPotentialSideEffects === true;
|
|
267
|
-
const timedOut = input.thisAttemptTimedOut === true;
|
|
268
|
-
const thisAttemptHadPotentialSideEffects = input.thisAttemptHadPotentialSideEffects === true;
|
|
269
|
-
const downgraded = input.thisAttemptDowngradedFromResume === true;
|
|
270
|
-
const recovered = input.thisAttemptResumeFailureRecovered === true;
|
|
271
|
-
const hadPotentialSideEffects = priorHadPotentialSideEffects || timedOut || thisAttemptHadPotentialSideEffects;
|
|
272
|
-
return {
|
|
273
|
-
hadPotentialSideEffects,
|
|
274
|
-
replaySafe: !(priorReplayInvalid || downgraded || recovered || hadPotentialSideEffects)
|
|
275
|
-
};
|
|
276
|
-
}
|
|
277
|
-
const COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
278
|
-
"get",
|
|
279
|
-
"file_read",
|
|
280
|
-
"glob",
|
|
281
|
-
"grep",
|
|
282
|
-
"inspect",
|
|
283
|
-
"list",
|
|
284
|
-
"ls",
|
|
285
|
-
"memory_get",
|
|
286
|
-
"probe",
|
|
287
|
-
"query",
|
|
288
|
-
"read",
|
|
289
|
-
"search",
|
|
290
|
-
"sessions_history",
|
|
291
|
-
"sessions_list",
|
|
292
|
-
"status",
|
|
293
|
-
"tool_search",
|
|
294
|
-
"update_plan",
|
|
295
|
-
"view",
|
|
296
|
-
"web_fetch",
|
|
297
|
-
"web_search"
|
|
298
|
-
]);
|
|
299
|
-
function copilotToolMetasHavePotentialSideEffects(toolMetas) {
|
|
300
|
-
return (toolMetas ?? []).some((entry) => entry.asyncStarted === true || !isReplaySafeReadOnlyToolName(entry.toolName));
|
|
301
|
-
}
|
|
302
|
-
function isReplaySafeReadOnlyToolName(toolName) {
|
|
303
|
-
const normalized = toolName.trim().toLowerCase();
|
|
304
|
-
return COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES.has(normalized);
|
|
305
|
-
}
|
|
306
|
-
//#endregion
|
|
307
|
-
//#region extensions/copilot/src/attempt-config.ts
|
|
308
|
-
function createResult(params, state) {
|
|
309
|
-
const promptError = state.promptError;
|
|
310
|
-
const transcriptPersistenceFailed = promptError?.code === "transcript_persistence_failed";
|
|
311
|
-
const timedOut = state.timedOut === true;
|
|
312
|
-
const toolMetas = state.toolMetas ?? [];
|
|
313
|
-
const replayMetadata = params.operation === "settled-tool-finalization" ? {
|
|
314
|
-
hadPotentialSideEffects: false,
|
|
315
|
-
replaySafe: state.nativeReplayInvalid !== true && !transcriptPersistenceFailed
|
|
316
|
-
} : computeReplayMetadata({
|
|
317
|
-
priorReplayInvalid: params.initialReplayState?.replayInvalid === true || state.nativeReplayInvalid === true || transcriptPersistenceFailed,
|
|
318
|
-
priorHadPotentialSideEffects: params.initialReplayState?.hadPotentialSideEffects,
|
|
319
|
-
thisAttemptTimedOut: timedOut,
|
|
320
|
-
thisAttemptHadPotentialSideEffects: copilotToolMetasHavePotentialSideEffects(toolMetas),
|
|
321
|
-
thisAttemptDowngradedFromResume: state.downgradedFromResume,
|
|
322
|
-
thisAttemptResumeFailureRecovered: state.resumeFailureRecovered
|
|
323
|
-
});
|
|
324
|
-
const interruption = timedOut ? {
|
|
325
|
-
kind: "timeout",
|
|
326
|
-
phase: state.timedOutDuringCompaction ? "compaction" : "prompt",
|
|
327
|
-
source: state.externalAbort ? "external" : "runtime",
|
|
328
|
-
...state.aborted ? { aborted: true } : {}
|
|
329
|
-
} : state.aborted ? {
|
|
330
|
-
kind: "aborted",
|
|
331
|
-
source: state.externalAbort ? "external" : "runtime"
|
|
332
|
-
} : { kind: "ok" };
|
|
333
|
-
return {
|
|
334
|
-
terminal: promptError !== void 0 ? withPromptFailure(interruption, promptError) : interruption,
|
|
335
|
-
...state.assistantTranscriptOwned ? {
|
|
336
|
-
assistantTranscriptOwned: true,
|
|
337
|
-
...state.assistantTranscriptIdempotencyKey ? { assistantTranscriptIdempotencyKey: state.assistantTranscriptIdempotencyKey } : {}
|
|
338
|
-
} : {},
|
|
339
|
-
...state.sdkSessionId ? { sdkSessionId: state.sdkSessionId } : {},
|
|
340
|
-
...state.journalValidated !== void 0 ? { journalValidated: state.journalValidated } : {},
|
|
341
|
-
...state.codeModeEngaged !== void 0 ? { codeModeEngaged: state.codeModeEngaged } : {},
|
|
342
|
-
assistantTexts: state.assistantTexts ?? [],
|
|
343
|
-
attemptUsage: state.usage,
|
|
344
|
-
cloudCodeAssistFormatError: false,
|
|
345
|
-
currentAttemptAssistant: state.currentAttemptAssistant,
|
|
346
|
-
currentAttemptCompletedAssistant: state.currentAttemptCompletedAssistant,
|
|
347
|
-
didSendViaMessagingTool: false,
|
|
348
|
-
itemLifecycle: state.itemLifecycle ?? {
|
|
349
|
-
activeCount: 0,
|
|
350
|
-
completedCount: 0,
|
|
351
|
-
startedCount: 0
|
|
352
|
-
},
|
|
353
|
-
lastAssistant: state.lastAssistant,
|
|
354
|
-
...state.lastToolError ? { lastToolError: state.lastToolError } : {},
|
|
355
|
-
messagesSnapshot: state.messagesSnapshot,
|
|
356
|
-
messagingToolSentMediaUrls: [],
|
|
357
|
-
messagingToolSentTargets: [],
|
|
358
|
-
messagingToolSentTexts: [],
|
|
359
|
-
replayMetadata,
|
|
360
|
-
sessionFileUsed: readString$3(params.sessionFile),
|
|
361
|
-
sessionIdUsed: state.sessionIdUsed ?? readString$3(params.sessionId) ?? "copilot-session",
|
|
362
|
-
toolMetas,
|
|
363
|
-
yieldDetected: state.yieldDetected === true
|
|
364
|
-
};
|
|
365
|
-
}
|
|
366
|
-
function createPromptError$1(code, message, cause) {
|
|
367
|
-
const error = new Error(message);
|
|
368
|
-
error.code = code;
|
|
369
|
-
if (cause !== void 0) error.cause = cause;
|
|
370
|
-
return error;
|
|
371
|
-
}
|
|
372
|
-
function createSettledFinalizationSessionRestrictions() {
|
|
373
|
-
return {
|
|
374
|
-
availableTools: [],
|
|
375
|
-
coauthorEnabled: false,
|
|
376
|
-
customAgents: [],
|
|
377
|
-
customAgentsLocalOnly: true,
|
|
378
|
-
embeddingCacheStorage: "in-memory",
|
|
379
|
-
enableConfigDiscovery: false,
|
|
380
|
-
enableFileHooks: false,
|
|
381
|
-
enableHostGitOperations: false,
|
|
382
|
-
enableOnDemandInstructionDiscovery: false,
|
|
383
|
-
enableSessionStore: false,
|
|
384
|
-
enableSkills: false,
|
|
385
|
-
excludedTools: [...COPILOT_SETTLED_FINALIZATION_EXCLUDED_TOOLS],
|
|
386
|
-
includeSubAgentStreamingEvents: false,
|
|
387
|
-
infiniteSessions: { enabled: false },
|
|
388
|
-
instructionDirectories: [],
|
|
389
|
-
manageScheduleEnabled: false,
|
|
390
|
-
mcpOAuthTokenStorage: "in-memory",
|
|
391
|
-
mcpServers: {},
|
|
392
|
-
memory: { enabled: false },
|
|
393
|
-
pluginDirectories: [],
|
|
394
|
-
remoteSession: "off",
|
|
395
|
-
requestCanvasRenderer: false,
|
|
396
|
-
requestExtensions: false,
|
|
397
|
-
skillDirectories: [],
|
|
398
|
-
skipCustomInstructions: true,
|
|
399
|
-
skipEmbeddingRetrieval: true,
|
|
400
|
-
tools: []
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
function createSessionConfig(params, sdkModelId, sdkTools, resolvedAuth, resolvedProvider, systemMessageContent, effectiveWorkspaceDir, effectiveCwd, onUserInputRequest, options) {
|
|
404
|
-
const settledToolFinalization = options.operation === "settled-tool-finalization";
|
|
405
|
-
const permissionPolicy = settledToolFinalization ? rejectAllPolicy : params.permissionPolicy ?? rejectAllPolicy;
|
|
406
|
-
const hooks = settledToolFinalization ? void 0 : createHooksBridge(params.hooksConfig, options.hooksBridgeOptions);
|
|
407
|
-
return {
|
|
408
|
-
model: sdkModelId,
|
|
409
|
-
onPermissionRequest: createPermissionBridge(permissionPolicy),
|
|
410
|
-
...onUserInputRequest ? { onUserInputRequest } : {},
|
|
411
|
-
...resolvedProvider.provider ? { provider: resolvedProvider.provider } : {},
|
|
412
|
-
...hooks ? { hooks } : {},
|
|
413
|
-
...typeof params.enableSessionTelemetry === "boolean" ? { enableSessionTelemetry: params.enableSessionTelemetry } : {},
|
|
414
|
-
...settledToolFinalization ? {} : params.infiniteSessionConfig ? { infiniteSessions: params.infiniteSessionConfig } : {},
|
|
415
|
-
reasoningEffort: params.reasoningEffort,
|
|
416
|
-
tools: sdkTools,
|
|
417
|
-
availableTools: buildCopilotAvailableTools(sdkTools, options.includeAskUser),
|
|
418
|
-
...settledToolFinalization ? createSettledFinalizationSessionRestrictions() : {},
|
|
419
|
-
workingDirectory: effectiveCwd ?? effectiveWorkspaceDir ?? readResolvedAttemptPath(params.workspaceDir),
|
|
420
|
-
...!settledToolFinalization && effectiveWorkspaceDir && effectiveCwd && effectiveCwd !== effectiveWorkspaceDir ? { instructionDirectories: [effectiveWorkspaceDir] } : {},
|
|
421
|
-
...resolvedAuth.authMode === "gitHubToken" && resolvedAuth.gitHubToken ? { gitHubToken: resolvedAuth.gitHubToken } : {},
|
|
422
|
-
...settledToolFinalization ? { systemMessage: {
|
|
423
|
-
mode: "customize",
|
|
424
|
-
content: COPILOT_SETTLED_FINALIZATION_SYSTEM_MESSAGE
|
|
425
|
-
} } : systemMessageContent ? { systemMessage: {
|
|
426
|
-
mode: "append",
|
|
427
|
-
content: systemMessageContent
|
|
428
|
-
} } : {}
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
function buildCopilotAvailableTools(sdkTools, includeAskUser) {
|
|
432
|
-
const availableTools = sdkTools.map((tool) => tool.name);
|
|
433
|
-
if (includeAskUser) availableTools.push(...COPILOT_ASK_USER_AVAILABLE_TOOLS);
|
|
434
|
-
return [...new Set(availableTools)];
|
|
435
|
-
}
|
|
436
|
-
async function createMessageOptions(params, context) {
|
|
437
|
-
const attachments = createPromptImageAttachments(await resolvePromptImages(params, context));
|
|
438
|
-
const providerHeaders = context.provider.provider?.headers;
|
|
439
|
-
const requestHeaders = providerHeaders && Object.keys(providerHeaders).length > 0 ? { ...providerHeaders } : void 0;
|
|
440
|
-
return {
|
|
441
|
-
prompt: params.prompt,
|
|
442
|
-
...attachments.length > 0 ? { attachments } : {},
|
|
443
|
-
...requestHeaders ? { requestHeaders } : {}
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
function createPromptImageAttachments(images) {
|
|
447
|
-
return images.flatMap((image, index) => {
|
|
448
|
-
if (!image || typeof image !== "object" || image.type !== "image" || typeof image.data !== "string" || typeof image.mimeType !== "string") return [];
|
|
449
|
-
return [{
|
|
450
|
-
type: "blob",
|
|
451
|
-
data: image.data,
|
|
452
|
-
mimeType: image.mimeType,
|
|
453
|
-
displayName: `prompt-image-${index + 1}`
|
|
454
|
-
}];
|
|
455
|
-
});
|
|
456
|
-
}
|
|
457
|
-
async function resolvePromptImages(params, context) {
|
|
458
|
-
const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
|
|
459
|
-
if (!workspaceDir) return [];
|
|
460
|
-
const localRoots = context.workspaceOnly && context.effectiveWorkspaceDir ? [context.effectiveWorkspaceDir] : void 0;
|
|
461
|
-
return (await detectAndLoadAgentHarnessPromptImages({
|
|
462
|
-
prompt: params.prompt,
|
|
463
|
-
workspaceDir,
|
|
464
|
-
model: resolveImageCapabilityModel(params),
|
|
465
|
-
existingImages: Array.isArray(params.images) ? params.images : void 0,
|
|
466
|
-
imageOrder: Array.isArray(params.imageOrder) ? params.imageOrder : void 0,
|
|
467
|
-
media: Array.isArray(params.media) ? params.media : void 0,
|
|
468
|
-
config: params.config,
|
|
469
|
-
workspaceOnly: context.workspaceOnly,
|
|
470
|
-
localRoots,
|
|
471
|
-
sandbox: context.sandbox?.enabled && context.sandbox.fsBridge ? {
|
|
472
|
-
root: context.sandbox.workspaceDir,
|
|
473
|
-
bridge: context.sandbox.fsBridge
|
|
474
|
-
} : void 0
|
|
475
|
-
})).images;
|
|
476
|
-
}
|
|
477
|
-
function resolveImageCapabilityModel(params) {
|
|
478
|
-
const model = params.model;
|
|
479
|
-
if (model && typeof model === "object" && Array.isArray(model.input)) return { input: model.input };
|
|
480
|
-
return { input: ["image"] };
|
|
481
|
-
}
|
|
482
|
-
function createSystemMessageContent(params, workspaceBootstrapInstructions) {
|
|
483
|
-
const sections = [];
|
|
484
|
-
const bootstrap = workspaceBootstrapInstructions?.trim();
|
|
485
|
-
if (bootstrap) sections.push(bootstrap);
|
|
486
|
-
const extraSystemPrompt = readString$3(params.extraSystemPrompt)?.trim();
|
|
487
|
-
if (extraSystemPrompt && !isRawCopilotModelRun(params)) {
|
|
488
|
-
const contextHeader = params.promptMode === "minimal" ? "## Subagent Context" : "## Conversation Context";
|
|
489
|
-
sections.push(`${contextHeader}\n${extraSystemPrompt}`);
|
|
490
|
-
}
|
|
491
|
-
return sections.length > 0 ? sections.join("\n\n") : void 0;
|
|
492
|
-
}
|
|
493
|
-
function isRawCopilotModelRun(params) {
|
|
494
|
-
return params.modelRun === true || params.promptMode === "none";
|
|
495
|
-
}
|
|
496
|
-
function readString$3(value) {
|
|
497
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
498
|
-
}
|
|
499
|
-
function readResolvedAttemptPath(value) {
|
|
500
|
-
const raw = readString$3(value)?.trim();
|
|
501
|
-
if (!raw) return;
|
|
502
|
-
if (process.platform !== "win32" && /^[A-Za-z]:[\\/]/.test(raw)) return raw;
|
|
503
|
-
return resolveUserPath(raw);
|
|
504
|
-
}
|
|
505
|
-
function resolveModelRef(params) {
|
|
506
|
-
const rawModel = params.runtimeModel ?? params.model;
|
|
507
|
-
if (rawModel && typeof rawModel === "object") {
|
|
508
|
-
const model = rawModel;
|
|
509
|
-
const requestTransport = getModelProviderRequestTransport(rawModel);
|
|
510
|
-
const rawRequest = model.request;
|
|
511
|
-
return {
|
|
512
|
-
api: readString$3(model.api),
|
|
513
|
-
id: readString$3(model.id) ?? readString$3(params.modelId) ?? "unknown-model",
|
|
514
|
-
provider: readString$3(model.provider) ?? readString$3(params.provider) ?? "unknown-provider",
|
|
515
|
-
baseUrl: readString$3(model.baseUrl),
|
|
516
|
-
azureApiVersion: readString$3(model.azureApiVersion ?? model.params?.azureApiVersion),
|
|
517
|
-
headers: model.headers,
|
|
518
|
-
authHeader: model.authHeader,
|
|
519
|
-
requestAuthMode: readString$3(requestTransport?.auth?.mode ?? rawRequest?.auth?.mode),
|
|
520
|
-
requestProxy: requestTransport?.proxy ?? rawRequest?.proxy,
|
|
521
|
-
requestTls: requestTransport?.tls ?? rawRequest?.tls,
|
|
522
|
-
requestAllowPrivateNetwork: requestTransport?.allowPrivateNetwork ?? rawRequest?.allowPrivateNetwork,
|
|
523
|
-
contextTokens: model.contextTokens,
|
|
524
|
-
contextWindow: model.contextWindow,
|
|
525
|
-
maxTokens: model.maxTokens
|
|
526
|
-
};
|
|
527
|
-
}
|
|
528
|
-
return {
|
|
529
|
-
id: readString$3(typeof rawModel === "string" ? rawModel : void 0) ?? readString$3(params.modelId) ?? "unknown-model",
|
|
530
|
-
provider: readString$3(params.provider) ?? "unknown-provider"
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
|
-
function resolvePoolAcquire(params) {
|
|
534
|
-
const provider = resolveCopilotProvider({
|
|
535
|
-
model: resolveModelRef(params),
|
|
536
|
-
resolvedApiKey: readString$3(params.resolvedApiKey),
|
|
537
|
-
authProfileId: readString$3(params.authProfileId)
|
|
538
|
-
});
|
|
539
|
-
const auth = provider.mode === "byok" ? createCopilotByokAuth({
|
|
540
|
-
agentId: readString$3(params.agentId),
|
|
541
|
-
agentDir: readString$3(params.agentDir),
|
|
542
|
-
workspaceDir: readString$3(params.workspaceDir),
|
|
543
|
-
copilotHome: readString$3(params.copilotHome),
|
|
544
|
-
authProfileId: provider.authProfileId,
|
|
545
|
-
authProfileVersion: provider.authProfileVersion
|
|
546
|
-
}) : resolveCopilotAuth({
|
|
547
|
-
agentId: readString$3(params.agentId),
|
|
548
|
-
agentDir: readString$3(params.agentDir),
|
|
549
|
-
workspaceDir: readString$3(params.workspaceDir),
|
|
550
|
-
copilotHome: readString$3(params.copilotHome),
|
|
551
|
-
auth: params.auth,
|
|
552
|
-
resolvedApiKey: readString$3(params.resolvedApiKey),
|
|
553
|
-
authProfileId: readString$3(params.authProfileId),
|
|
554
|
-
profileVersion: readString$3(params.profileVersion)
|
|
555
|
-
});
|
|
556
|
-
return {
|
|
557
|
-
key: {
|
|
558
|
-
agentId: auth.agentId,
|
|
559
|
-
authMode: auth.authMode,
|
|
560
|
-
...auth.authMode === "gitHubToken" || auth.authMode === "byok" ? {
|
|
561
|
-
authProfileId: auth.authProfileId,
|
|
562
|
-
authProfileVersion: auth.authProfileVersion
|
|
563
|
-
} : {},
|
|
564
|
-
copilotHome: auth.copilotHome
|
|
565
|
-
},
|
|
566
|
-
options: {
|
|
567
|
-
copilotHome: auth.copilotHome,
|
|
568
|
-
...auth.authMode === "gitHubToken" && auth.gitHubToken ? { gitHubToken: auth.gitHubToken } : {},
|
|
569
|
-
useLoggedInUser: auth.authMode === "useLoggedInUser"
|
|
570
|
-
},
|
|
571
|
-
auth,
|
|
572
|
-
provider
|
|
573
|
-
};
|
|
574
|
-
}
|
|
575
|
-
function toError$1(error) {
|
|
576
|
-
return error instanceof Error ? error : new Error(String(error));
|
|
577
|
-
}
|
|
578
|
-
function isSdkSendAndWaitTimeoutError(error) {
|
|
579
|
-
if (error === null || typeof error !== "object") return false;
|
|
580
|
-
const message = error.message;
|
|
581
|
-
if (typeof message !== "string") return false;
|
|
582
|
-
return /^Timeout after \d+ms waiting for session\.idle$/.test(message);
|
|
583
|
-
}
|
|
584
|
-
//#endregion
|
|
585
|
-
//#region extensions/copilot/src/usage-bridge.ts
|
|
586
|
-
function isCopilotUsageSource(data) {
|
|
587
|
-
return typeof data === "object" && data !== null;
|
|
588
|
-
}
|
|
589
|
-
function buildZeroCost() {
|
|
590
|
-
return {
|
|
591
|
-
cacheRead: 0,
|
|
592
|
-
cacheWrite: 0,
|
|
593
|
-
input: 0,
|
|
594
|
-
output: 0,
|
|
595
|
-
total: 0
|
|
596
|
-
};
|
|
597
|
-
}
|
|
598
|
-
function coerceTokenCount(value) {
|
|
599
|
-
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : void 0;
|
|
600
|
-
}
|
|
601
|
-
function normalizeCopilotUsage(data) {
|
|
602
|
-
if (!isCopilotUsageSource(data)) return;
|
|
603
|
-
const input = coerceTokenCount(data.inputTokens);
|
|
604
|
-
const output = coerceTokenCount(data.outputTokens);
|
|
605
|
-
const cacheRead = coerceTokenCount(data.cacheReadTokens);
|
|
606
|
-
const cacheWrite = coerceTokenCount(data.cacheWriteTokens);
|
|
607
|
-
return {
|
|
608
|
-
cacheRead,
|
|
609
|
-
cacheWrite,
|
|
610
|
-
input,
|
|
611
|
-
output,
|
|
612
|
-
total: (input ?? 0) + (output ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0)
|
|
613
|
-
};
|
|
614
|
-
}
|
|
615
|
-
function buildCopilotAssistantUsage(params) {
|
|
616
|
-
const usage = params.usage ?? normalizeCopilotUsage({ outputTokens: params.fallbackOutputTokens });
|
|
617
|
-
return {
|
|
618
|
-
cacheRead: usage?.cacheRead ?? 0,
|
|
619
|
-
cacheWrite: usage?.cacheWrite ?? 0,
|
|
620
|
-
cost: buildZeroCost(),
|
|
621
|
-
input: usage?.input ?? 0,
|
|
622
|
-
output: usage?.output ?? 0,
|
|
623
|
-
totalTokens: usage?.total ?? 0
|
|
624
|
-
};
|
|
625
|
-
}
|
|
626
|
-
//#endregion
|
|
627
|
-
//#region extensions/copilot/src/event-bridge-transcript.ts
|
|
628
|
-
function buildAssistantMessage(params) {
|
|
629
|
-
const event = params.event;
|
|
630
|
-
const text = event ? event.data.content || params.assistantTexts.at(-1) || "" : "";
|
|
631
|
-
const reasoningText = event?.data.reasoningText ?? params.reasoningText;
|
|
632
|
-
const toolRequests = event?.data.toolRequests ?? [];
|
|
633
|
-
if (!text && !reasoningText && toolRequests.length === 0) return;
|
|
634
|
-
const content = [];
|
|
635
|
-
if (reasoningText) content.push({
|
|
636
|
-
thinking: reasoningText,
|
|
637
|
-
type: "thinking"
|
|
638
|
-
});
|
|
639
|
-
if (text) content.push({
|
|
640
|
-
text,
|
|
641
|
-
type: "text"
|
|
642
|
-
});
|
|
643
|
-
for (const request of toolRequests) content.push({
|
|
644
|
-
arguments: request.arguments ?? {},
|
|
645
|
-
id: request.toolCallId,
|
|
646
|
-
name: request.name,
|
|
647
|
-
type: "toolCall"
|
|
648
|
-
});
|
|
649
|
-
return {
|
|
650
|
-
api: params.modelRef.api ?? "openai-responses",
|
|
651
|
-
content,
|
|
652
|
-
model: event?.data.model ?? params.modelRef.id,
|
|
653
|
-
provider: params.modelRef.provider,
|
|
654
|
-
role: "assistant",
|
|
655
|
-
stopReason: toolRequests.length > 0 ? "toolUse" : "stop",
|
|
656
|
-
timestamp: params.now(),
|
|
657
|
-
usage: buildCopilotAssistantUsage({
|
|
658
|
-
fallbackOutputTokens: event?.data.outputTokens,
|
|
659
|
-
usage: params.usage
|
|
660
|
-
})
|
|
661
|
-
};
|
|
662
|
-
}
|
|
663
|
-
function resolveAssistantUsage(event, latest, byApiCallId) {
|
|
664
|
-
const apiCallId = readString$2(event?.data.apiCallId);
|
|
665
|
-
return apiCallId ? byApiCallId.get(apiCallId) ?? latest : latest;
|
|
666
|
-
}
|
|
667
|
-
function resolveEventTimestamp(timestamp, now) {
|
|
668
|
-
const parsed = Date.parse(timestamp);
|
|
669
|
-
return Number.isFinite(parsed) ? parsed : now();
|
|
670
|
-
}
|
|
671
|
-
function hasOwnKeys(value) {
|
|
672
|
-
return Boolean(value && typeof value === "object" && Object.keys(value).length > 0);
|
|
673
|
-
}
|
|
674
|
-
function projectSdkUserMetadata(attachments, source) {
|
|
675
|
-
const summaries = (attachments ?? []).map((attachment) => {
|
|
676
|
-
const { data: _data, payload: _payload, text: _text, ...summary } = attachment;
|
|
677
|
-
return summary;
|
|
678
|
-
});
|
|
679
|
-
const media = (attachments ?? []).flatMap((attachment) => {
|
|
680
|
-
if (attachment.type === "file") return [{
|
|
681
|
-
path: attachment.path,
|
|
682
|
-
contentType: attachment.mimeType
|
|
683
|
-
}];
|
|
684
|
-
return attachment.type === "selection" ? [{
|
|
685
|
-
path: attachment.filePath,
|
|
686
|
-
kind: "document"
|
|
687
|
-
}] : [];
|
|
688
|
-
});
|
|
689
|
-
if (!source && summaries.length === 0) return;
|
|
690
|
-
return {
|
|
691
|
-
...source ? { copilotSource: source } : {},
|
|
692
|
-
...summaries.length > 0 ? { copilotAttachments: summaries } : {},
|
|
693
|
-
...media.length > 0 ? { media } : {}
|
|
694
|
-
};
|
|
695
|
-
}
|
|
696
|
-
function projectToolResultDetails(data) {
|
|
697
|
-
const result = data.result;
|
|
698
|
-
const sanitizedContents = result?.contents ? sanitizeToolResult({ content: result.contents }).content : void 0;
|
|
699
|
-
const binaryResultsForLlm = result?.binaryResultsForLlm?.map((entry) => {
|
|
700
|
-
const { data: _data, ...descriptor } = entry;
|
|
701
|
-
return descriptor;
|
|
702
|
-
});
|
|
703
|
-
const citableSources = result?.citableSources?.map((source) => Object.assign({}, source, { content: sanitizeToolDetailText(source.content) }));
|
|
704
|
-
return sanitizeToolResult({
|
|
705
|
-
...result?.detailedContent ? { content: [{
|
|
706
|
-
type: "text",
|
|
707
|
-
text: result.detailedContent
|
|
708
|
-
}] } : {},
|
|
709
|
-
...result?.structuredContent ? { structuredContent: result.structuredContent } : {},
|
|
710
|
-
...sanitizedContents ? { contents: sanitizedContents } : {},
|
|
711
|
-
...binaryResultsForLlm?.length ? { binaryResultsForLlm } : {},
|
|
712
|
-
...citableSources?.length ? { citableSources } : {},
|
|
713
|
-
...data.mcpMeta || result?.mcpMeta ? { mcpMeta: data.mcpMeta ?? result?.mcpMeta } : {}
|
|
714
|
-
});
|
|
715
|
-
}
|
|
716
|
-
function sanitizeToolDetailText(text) {
|
|
717
|
-
const value = sanitizeToolResult({ content: [{
|
|
718
|
-
type: "text",
|
|
719
|
-
text
|
|
720
|
-
}] }).content?.[0]?.text;
|
|
721
|
-
return typeof value === "string" ? value : "";
|
|
722
|
-
}
|
|
723
|
-
function readString$2(value) {
|
|
724
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
725
|
-
}
|
|
726
216
|
//#endregion
|
|
727
217
|
//#region extensions/copilot/src/event-bridge.ts
|
|
728
218
|
function attachEventBridge(session, options) {
|
|
@@ -730,21 +220,11 @@ function attachEventBridge(session, options) {
|
|
|
730
220
|
const messagesById = /* @__PURE__ */ new Map();
|
|
731
221
|
const reasoningOrder = [];
|
|
732
222
|
const reasoningById = /* @__PURE__ */ new Map();
|
|
733
|
-
const durableReasoningOrder = [];
|
|
734
|
-
const durableReasoningById = /* @__PURE__ */ new Map();
|
|
735
223
|
let lastAssistantEvent;
|
|
736
|
-
let lastAssistantReasoningText;
|
|
737
224
|
let usage;
|
|
738
|
-
const usageByApiCallId = /* @__PURE__ */ new Map();
|
|
739
|
-
const handledAssistantEventIds = /* @__PURE__ */ new Set();
|
|
740
|
-
const projectedAssistantMessageIdsWithoutApiCall = /* @__PURE__ */ new Set();
|
|
741
|
-
let pendingAssistantProjection;
|
|
742
|
-
let lastAssistantProjection;
|
|
743
225
|
let streamError;
|
|
744
226
|
const toolMetas = [];
|
|
745
|
-
const
|
|
746
|
-
const projectedToolNamesByCallId = /* @__PURE__ */ new Map();
|
|
747
|
-
const userRequestedToolCallIds = /* @__PURE__ */ new Set();
|
|
227
|
+
const toolNamesByCallId = /* @__PURE__ */ new Map();
|
|
748
228
|
let startedCount = 0;
|
|
749
229
|
let completedCount = 0;
|
|
750
230
|
let activeCompactionCount = 0;
|
|
@@ -762,45 +242,10 @@ function attachEventBridge(session, options) {
|
|
|
762
242
|
});
|
|
763
243
|
let firstDeltaError;
|
|
764
244
|
let detached = false;
|
|
765
|
-
let unconsumedDurableReasoning = false;
|
|
766
245
|
const unsubscribeFns = [];
|
|
767
|
-
registerListener(session, unsubscribeFns, "user.message", (event) => {
|
|
768
|
-
if (!isRootSessionEvent(event) || event.ephemeral === true) return;
|
|
769
|
-
flushPendingAssistantProjection();
|
|
770
|
-
const projection = options.transcriptProjection;
|
|
771
|
-
if (!projection) return;
|
|
772
|
-
const source = readString$1(event.data.source);
|
|
773
|
-
const transformedContent = typeof event.data.transformedContent === "string" ? event.data.transformedContent : void 0;
|
|
774
|
-
const openClawMeta = projectSdkUserMetadata(event.data.attachments, source);
|
|
775
|
-
const idempotencyKey = `copilot-sdk:${options.getSdkSessionId() ?? "unknown"}:${event.id}`;
|
|
776
|
-
const hidden = event.data.isAutopilotContinuation === true || source === "skill-pdf";
|
|
777
|
-
projection.journal.recordSdkUser({
|
|
778
|
-
eventId: event.id,
|
|
779
|
-
autopilotContinuation: event.data.isAutopilotContinuation === true,
|
|
780
|
-
replayIncomplete: Boolean(event.data.attachments?.length || event.data.agentMode !== void 0 && event.data.agentMode !== "interactive" || transformedContent !== void 0 && transformedContent !== event.data.content),
|
|
781
|
-
message: {
|
|
782
|
-
role: "user",
|
|
783
|
-
content: event.data.content,
|
|
784
|
-
timestamp: resolveEventTimestamp(event.timestamp, projection.now),
|
|
785
|
-
idempotencyKey,
|
|
786
|
-
...hidden ? { display: false } : {},
|
|
787
|
-
...openClawMeta ? { __openclaw: openClawMeta } : {}
|
|
788
|
-
}
|
|
789
|
-
});
|
|
790
|
-
});
|
|
791
|
-
registerListener(session, unsubscribeFns, "system.message", (event) => {
|
|
792
|
-
if (!isRootSessionEvent(event) || event.ephemeral === true) return;
|
|
793
|
-
options.transcriptProjection?.journal.markReplayIncomplete();
|
|
794
|
-
});
|
|
795
|
-
registerListener(session, unsubscribeFns, "skill.invoked", (event) => {
|
|
796
|
-
if (isRootSessionEvent(event) && event.ephemeral !== true) options.transcriptProjection?.journal.markReplayIncomplete();
|
|
797
|
-
});
|
|
798
|
-
registerListener(session, unsubscribeFns, "system.notification", (event) => {
|
|
799
|
-
if (isRootSessionEvent(event) && event.ephemeral !== true) options.transcriptProjection?.journal.markReplayIncomplete();
|
|
800
|
-
});
|
|
801
246
|
registerListener(session, unsubscribeFns, "assistant.message_delta", (event) => {
|
|
802
247
|
if (!isRootSessionEvent(event)) return;
|
|
803
|
-
const messageId = readString$
|
|
248
|
+
const messageId = readString$2(event.data.messageId) ?? "assistant-message";
|
|
804
249
|
const delta = event.data.deltaContent;
|
|
805
250
|
if (!delta) return;
|
|
806
251
|
const entry = ensureMessageAccumulator(messagesById, messageOrder, messageId);
|
|
@@ -823,7 +268,7 @@ function attachEventBridge(session, options) {
|
|
|
823
268
|
});
|
|
824
269
|
registerListener(session, unsubscribeFns, "assistant.reasoning_delta", (event) => {
|
|
825
270
|
if (!isRootSessionEvent(event)) return;
|
|
826
|
-
const reasoningId = readString$
|
|
271
|
+
const reasoningId = readString$2(event.data.reasoningId) ?? "assistant-reasoning";
|
|
827
272
|
const delta = event.data.deltaContent;
|
|
828
273
|
if (!delta) return;
|
|
829
274
|
if (!reasoningById.has(reasoningId)) {
|
|
@@ -832,85 +277,29 @@ function attachEventBridge(session, options) {
|
|
|
832
277
|
}
|
|
833
278
|
reasoningById.set(reasoningId, `${reasoningById.get(reasoningId) ?? ""}${delta}`);
|
|
834
279
|
});
|
|
835
|
-
registerListener(session, unsubscribeFns, "assistant.reasoning", (event) => {
|
|
836
|
-
if (!isRootSessionEvent(event) || event.ephemeral === true) return;
|
|
837
|
-
if (!reasoningById.has(event.data.reasoningId)) reasoningOrder.push(event.data.reasoningId);
|
|
838
|
-
reasoningById.set(event.data.reasoningId, event.data.content);
|
|
839
|
-
if (!durableReasoningById.has(event.data.reasoningId)) durableReasoningOrder.push(event.data.reasoningId);
|
|
840
|
-
durableReasoningById.set(event.data.reasoningId, event.data.content);
|
|
841
|
-
unconsumedDurableReasoning = true;
|
|
842
|
-
});
|
|
843
|
-
registerListener(session, unsubscribeFns, "assistant.turn_start", (event) => {
|
|
844
|
-
if (isRootSessionEvent(event)) markUnconsumedReasoningIncomplete();
|
|
845
|
-
});
|
|
846
280
|
registerListener(session, unsubscribeFns, "assistant.message", (event) => {
|
|
847
|
-
if (!isRootSessionEvent(event)
|
|
848
|
-
|
|
281
|
+
if (!isRootSessionEvent(event)) return;
|
|
282
|
+
lastAssistantEvent = event;
|
|
283
|
+
const entry = ensureMessageAccumulator(messagesById, messageOrder, event.data.messageId);
|
|
284
|
+
if (typeof event.data.content === "string" && event.data.content.length >= entry.text.length) entry.text = event.data.content;
|
|
849
285
|
});
|
|
850
286
|
registerListener(session, unsubscribeFns, "assistant.usage", (event) => {
|
|
851
287
|
if (!isRootSessionEvent(event)) return;
|
|
852
288
|
usage = normalizeCopilotUsage(event.data);
|
|
853
|
-
const apiCallId = readString$1(event.data.apiCallId);
|
|
854
|
-
if (apiCallId && usage) usageByApiCallId.set(apiCallId, usage);
|
|
855
|
-
if (apiCallId) flushPendingAssistantProjection(apiCallId);
|
|
856
|
-
});
|
|
857
|
-
registerListener(session, unsubscribeFns, "tool.user_requested", (event) => {
|
|
858
|
-
if (isRootSessionEvent(event) && event.ephemeral !== true) {
|
|
859
|
-
userRequestedToolCallIds.add(event.data.toolCallId);
|
|
860
|
-
options.transcriptProjection?.journal.markReplayIncomplete();
|
|
861
|
-
}
|
|
862
289
|
});
|
|
863
290
|
registerListener(session, unsubscribeFns, "tool.execution_start", (event) => {
|
|
864
|
-
flushPendingAssistantProjectionForToolCall(event.data.toolCallId);
|
|
865
291
|
if (isRootSessionEvent(event)) startedCount += 1;
|
|
866
|
-
|
|
292
|
+
toolNamesByCallId.set(event.data.toolCallId, event.data.toolName);
|
|
867
293
|
toolMetas.push({ toolName: event.data.toolName });
|
|
868
294
|
});
|
|
869
295
|
registerListener(session, unsubscribeFns, "tool.execution_complete", (event) => {
|
|
870
|
-
flushPendingAssistantProjectionForToolCall(event.data.toolCallId);
|
|
871
296
|
if (isRootSessionEvent(event)) completedCount += 1;
|
|
872
|
-
const
|
|
873
|
-
const toolName = toolMetaIndex === void 0 ? void 0 : toolMetas[toolMetaIndex]?.toolName;
|
|
297
|
+
const toolName = toolNamesByCallId.get(event.data.toolCallId);
|
|
874
298
|
const meta = event.data.success ? event.data.result?.detailedContent ?? event.data.result?.content : event.data.error?.message;
|
|
875
|
-
if (toolName
|
|
876
|
-
|
|
877
|
-
toolName
|
|
878
|
-
|
|
879
|
-
};
|
|
880
|
-
const projection = options.transcriptProjection;
|
|
881
|
-
const isDurableRootCompletion = isRootSessionEvent(event) && event.ephemeral !== true;
|
|
882
|
-
const wasTrackedUserRequest = userRequestedToolCallIds.has(event.data.toolCallId);
|
|
883
|
-
const isUserRequested = event.data.isUserRequested === true || wasTrackedUserRequest;
|
|
884
|
-
const projectedToolName = projectedToolNamesByCallId.get(event.data.toolCallId);
|
|
885
|
-
if (isDurableRootCompletion) {
|
|
886
|
-
userRequestedToolCallIds.delete(event.data.toolCallId);
|
|
887
|
-
projectedToolNamesByCallId.delete(event.data.toolCallId);
|
|
888
|
-
}
|
|
889
|
-
if (projection && isDurableRootCompletion && isUserRequested) projection.journal.markReplayIncomplete();
|
|
890
|
-
if (projection && isDurableRootCompletion && !isUserRequested) {
|
|
891
|
-
const resultText = event.data.success ? event.data.result?.content ?? "" : event.data.error?.message ?? "Tool execution failed";
|
|
892
|
-
const details = projectToolResultDetails(event.data);
|
|
893
|
-
const replayIncomplete = Boolean(event.data.result?.binaryResultsForLlm?.length || event.data.result?.citableSources?.length);
|
|
894
|
-
const resolvedToolName = toolName ?? event.data.toolDescription?.name ?? projectedToolName ?? "unknown";
|
|
895
|
-
const resultContentSource = projection.resultContentSourceByToolName?.get(resolvedToolName);
|
|
896
|
-
projection.journal.recordToolResult({
|
|
897
|
-
eventId: event.id,
|
|
898
|
-
replayIncomplete,
|
|
899
|
-
message: {
|
|
900
|
-
role: "toolResult",
|
|
901
|
-
toolCallId: event.data.toolCallId,
|
|
902
|
-
toolName: resolvedToolName,
|
|
903
|
-
content: [{
|
|
904
|
-
type: "text",
|
|
905
|
-
text: sanitizeToolDetailText(resultText)
|
|
906
|
-
}],
|
|
907
|
-
...hasOwnKeys(details) ? { details } : {},
|
|
908
|
-
isError: !event.data.success,
|
|
909
|
-
timestamp: resolveEventTimestamp(event.timestamp, projection.now),
|
|
910
|
-
...resultContentSource ? { __openclaw: { resultContentSource } } : {}
|
|
911
|
-
}
|
|
912
|
-
});
|
|
913
|
-
}
|
|
299
|
+
if (toolName) toolMetas.push({
|
|
300
|
+
meta,
|
|
301
|
+
toolName
|
|
302
|
+
});
|
|
914
303
|
});
|
|
915
304
|
registerListener(session, unsubscribeFns, "session.plan_changed", (event) => {
|
|
916
305
|
enqueueAgentEvent({
|
|
@@ -925,10 +314,7 @@ function attachEventBridge(session, options) {
|
|
|
925
314
|
});
|
|
926
315
|
});
|
|
927
316
|
registerListener(session, unsubscribeFns, "exit_plan_mode.requested", (event) => {
|
|
928
|
-
const steps = splitPlanText(event.data.planContent)
|
|
929
|
-
step,
|
|
930
|
-
status: "pending"
|
|
931
|
-
}));
|
|
317
|
+
const steps = splitPlanText(event.data.planContent);
|
|
932
318
|
enqueueAgentEvent({
|
|
933
319
|
stream: "plan",
|
|
934
320
|
data: {
|
|
@@ -979,9 +365,6 @@ function attachEventBridge(session, options) {
|
|
|
979
365
|
enqueueCompactionCallback(options.onCompactionStart);
|
|
980
366
|
});
|
|
981
367
|
registerListener(session, unsubscribeFns, "session.compaction_complete", (event) => {
|
|
982
|
-
if (event.data.success) try {
|
|
983
|
-
options.onContextCompacted?.();
|
|
984
|
-
} catch {}
|
|
985
368
|
if (!isRootCompactionEvent(event)) return;
|
|
986
369
|
activeCompactionCount = Math.max(0, activeCompactionCount - 1);
|
|
987
370
|
enqueueCompactionCallback(() => options.onCompactionComplete?.({
|
|
@@ -995,25 +378,20 @@ function attachEventBridge(session, options) {
|
|
|
995
378
|
});
|
|
996
379
|
registerListener(session, unsubscribeFns, "session.idle", (event) => {
|
|
997
380
|
if (!isRootCompactionEvent(event)) return;
|
|
998
|
-
markUnconsumedReasoningIncomplete();
|
|
999
|
-
flushPendingAssistantProjection();
|
|
1000
381
|
observedSessionIdle = true;
|
|
1001
382
|
resolveSessionIdle?.();
|
|
1002
383
|
resolveSessionIdle = void 0;
|
|
1003
384
|
});
|
|
1004
385
|
registerListener(session, unsubscribeFns, "session.error", (event) => {
|
|
1005
|
-
|
|
1006
|
-
if (!options.isAborted()) streamError = createPromptError(event.data.errorCode ?? event.data.errorType, event.data.message);
|
|
386
|
+
if (!options.isAborted()) streamError = createPromptError$1(event.data.errorCode ?? event.data.errorType, event.data.message);
|
|
1007
387
|
});
|
|
1008
388
|
registerListener(session, unsubscribeFns, "abort", (event) => {
|
|
1009
|
-
|
|
1010
|
-
if (!options.isAborted()) streamError = createPromptError("session_aborted", `[copilot-attempt] session aborted: ${event.data.reason}`);
|
|
389
|
+
if (!options.isAborted()) streamError = createPromptError$1("session_aborted", `[copilot-attempt] session aborted: ${event.data.reason}`);
|
|
1011
390
|
});
|
|
1012
391
|
return {
|
|
1013
392
|
recordSendResult(result) {
|
|
1014
|
-
if (!isAssistantMessageEvent(result)
|
|
1015
|
-
|
|
1016
|
-
flushPendingAssistantProjection();
|
|
393
|
+
if (!isAssistantMessageEvent(result)) return false;
|
|
394
|
+
lastAssistantEvent = result;
|
|
1017
395
|
return true;
|
|
1018
396
|
},
|
|
1019
397
|
awaitCompactionChain() {
|
|
@@ -1036,10 +414,6 @@ function attachEventBridge(session, options) {
|
|
|
1036
414
|
awaitAgentEventChain() {
|
|
1037
415
|
return agentEventChain;
|
|
1038
416
|
},
|
|
1039
|
-
flushTranscriptProjection() {
|
|
1040
|
-
markUnconsumedReasoningIncomplete();
|
|
1041
|
-
flushPendingAssistantProjection();
|
|
1042
|
-
},
|
|
1043
417
|
hasObservedCompaction() {
|
|
1044
418
|
return observedCompaction;
|
|
1045
419
|
},
|
|
@@ -1061,111 +435,28 @@ function attachEventBridge(session, options) {
|
|
|
1061
435
|
};
|
|
1062
436
|
},
|
|
1063
437
|
buildAssistantMessage(args) {
|
|
1064
|
-
|
|
1065
|
-
return group ? buildAssistantProjectionGroup(group, args.modelRef, () => args.now(), usageByApiCallId, usage, false).message : buildAssistantMessage({
|
|
438
|
+
return buildAssistantMessage({
|
|
1066
439
|
event: lastAssistantEvent,
|
|
1067
440
|
modelRef: args.modelRef,
|
|
1068
441
|
now: args.now,
|
|
1069
|
-
|
|
1070
|
-
|
|
442
|
+
reasoningById,
|
|
443
|
+
reasoningOrder,
|
|
444
|
+
usage,
|
|
1071
445
|
assistantTexts: finalizeAssistantTexts(messageOrder, messagesById, lastAssistantEvent)
|
|
1072
446
|
});
|
|
1073
447
|
},
|
|
1074
|
-
finalizeAssistantTexts() {
|
|
1075
|
-
return finalizeAssistantTexts(messageOrder, messagesById, lastAssistantEvent);
|
|
1076
|
-
},
|
|
1077
|
-
detach() {
|
|
1078
|
-
if (detached) return;
|
|
1079
|
-
detached = true;
|
|
1080
|
-
for (const unsubscribe of [...unsubscribeFns].toReversed()) try {
|
|
1081
|
-
unsubscribe();
|
|
1082
|
-
} catch {}
|
|
1083
|
-
unsubscribeFns.length = 0;
|
|
1084
|
-
}
|
|
1085
|
-
};
|
|
1086
|
-
function handleAssistantMessage(event) {
|
|
1087
|
-
if (!isRootSessionEvent(event) || event.ephemeral === true) return;
|
|
1088
|
-
lastAssistantEvent = event;
|
|
1089
|
-
if (handledAssistantEventIds.has(event.id)) return;
|
|
1090
|
-
handledAssistantEventIds.add(event.id);
|
|
1091
|
-
for (const request of event.data.toolRequests ?? []) projectedToolNamesByCallId.set(request.toolCallId, request.name);
|
|
1092
|
-
const entry = ensureMessageAccumulator(messagesById, messageOrder, event.data.messageId);
|
|
1093
|
-
if (typeof event.data.content === "string" && event.data.content.length >= entry.text.length) entry.text = event.data.content;
|
|
1094
|
-
lastAssistantReasoningText = event.data.reasoningText ?? (joinReasoning(reasoningOrder, reasoningById) || void 0);
|
|
1095
|
-
const transcriptReasoningText = event.data.reasoningText ?? (joinReasoning(durableReasoningOrder, durableReasoningById) || void 0);
|
|
1096
|
-
reasoningOrder.length = 0;
|
|
1097
|
-
reasoningById.clear();
|
|
1098
|
-
durableReasoningOrder.length = 0;
|
|
1099
|
-
durableReasoningById.clear();
|
|
1100
|
-
unconsumedDurableReasoning = false;
|
|
1101
|
-
const chunk = {
|
|
1102
|
-
event,
|
|
1103
|
-
assistantTexts: [messagesById.get(event.data.messageId)?.text ?? ""],
|
|
1104
|
-
...lastAssistantReasoningText ? { reasoningText: lastAssistantReasoningText } : {},
|
|
1105
|
-
transcriptAssistantTexts: [event.data.content ?? ""],
|
|
1106
|
-
...transcriptReasoningText ? { transcriptReasoningText } : {}
|
|
1107
|
-
};
|
|
1108
|
-
const apiCallId = readString$1(event.data.apiCallId);
|
|
1109
|
-
if (!apiCallId) {
|
|
1110
|
-
if (projectedAssistantMessageIdsWithoutApiCall.has(event.data.messageId)) {
|
|
1111
|
-
options.transcriptProjection?.journal.markReplayIncomplete();
|
|
1112
|
-
lastAssistantProjection = { chunks: [chunk] };
|
|
1113
|
-
return;
|
|
1114
|
-
}
|
|
1115
|
-
projectedAssistantMessageIdsWithoutApiCall.add(event.data.messageId);
|
|
1116
|
-
flushPendingAssistantProjection();
|
|
1117
|
-
const group = { chunks: [chunk] };
|
|
1118
|
-
lastAssistantProjection = group;
|
|
1119
|
-
recordAssistantProjection(group);
|
|
1120
|
-
return;
|
|
1121
|
-
}
|
|
1122
|
-
if (pendingAssistantProjection?.apiCallId !== apiCallId) {
|
|
1123
|
-
flushPendingAssistantProjection();
|
|
1124
|
-
pendingAssistantProjection = {
|
|
1125
|
-
apiCallId,
|
|
1126
|
-
chunks: []
|
|
1127
|
-
};
|
|
1128
|
-
}
|
|
1129
|
-
const priorChunkIndex = pendingAssistantProjection.chunks.findIndex((candidate) => candidate.event.data.messageId === event.data.messageId);
|
|
1130
|
-
if (priorChunkIndex === -1) pendingAssistantProjection.chunks.push(chunk);
|
|
1131
|
-
else pendingAssistantProjection.chunks[priorChunkIndex] = chunk;
|
|
1132
|
-
}
|
|
1133
|
-
function flushPendingAssistantProjection(apiCallId) {
|
|
1134
|
-
const group = pendingAssistantProjection;
|
|
1135
|
-
if (!group || apiCallId !== void 0 && group.apiCallId !== apiCallId) return;
|
|
1136
|
-
pendingAssistantProjection = void 0;
|
|
1137
|
-
lastAssistantProjection = group;
|
|
1138
|
-
recordAssistantProjection(group);
|
|
1139
|
-
}
|
|
1140
|
-
function markUnconsumedReasoningIncomplete() {
|
|
1141
|
-
if (unconsumedDurableReasoning) options.transcriptProjection?.journal.markReplayIncomplete();
|
|
1142
|
-
reasoningOrder.length = 0;
|
|
1143
|
-
reasoningById.clear();
|
|
1144
|
-
durableReasoningOrder.length = 0;
|
|
1145
|
-
durableReasoningById.clear();
|
|
1146
|
-
unconsumedDurableReasoning = false;
|
|
1147
|
-
}
|
|
1148
|
-
function flushPendingAssistantProjectionForToolCall(toolCallId) {
|
|
1149
|
-
if (pendingAssistantProjection?.chunks.some((chunk) => chunk.event.data.toolRequests?.some((request) => request.toolCallId === toolCallId))) flushPendingAssistantProjection();
|
|
1150
|
-
}
|
|
1151
|
-
function recordAssistantProjection(group) {
|
|
1152
|
-
const projection = options.transcriptProjection;
|
|
1153
|
-
if (!projection) return;
|
|
1154
|
-
const { message, replayIncomplete, toolCallIds } = buildAssistantProjectionGroup(group, projection.modelRef, (event) => resolveEventTimestamp(event.timestamp, projection.now), usageByApiCallId, void 0, true);
|
|
1155
|
-
const eventId = group.chunks[0]?.event.id;
|
|
1156
|
-
if (!eventId) return;
|
|
1157
|
-
if (!message) {
|
|
1158
|
-
if (replayIncomplete) projection.journal.markReplayIncomplete();
|
|
1159
|
-
projection.journal.recordAssistantProjectionGap();
|
|
1160
|
-
return;
|
|
448
|
+
finalizeAssistantTexts() {
|
|
449
|
+
return finalizeAssistantTexts(messageOrder, messagesById, lastAssistantEvent);
|
|
450
|
+
},
|
|
451
|
+
detach() {
|
|
452
|
+
if (detached) return;
|
|
453
|
+
detached = true;
|
|
454
|
+
for (const unsubscribe of [...unsubscribeFns].toReversed()) try {
|
|
455
|
+
unsubscribe();
|
|
456
|
+
} catch {}
|
|
457
|
+
unsubscribeFns.length = 0;
|
|
1161
458
|
}
|
|
1162
|
-
|
|
1163
|
-
eventId,
|
|
1164
|
-
message,
|
|
1165
|
-
replayIncomplete,
|
|
1166
|
-
toolCallIds
|
|
1167
|
-
});
|
|
1168
|
-
}
|
|
459
|
+
};
|
|
1169
460
|
function enqueueCompactionCallback(callback) {
|
|
1170
461
|
if (!callback) return;
|
|
1171
462
|
compactionChain = compactionChain.then(callback, callback).catch(() => void 0);
|
|
@@ -1189,7 +480,42 @@ function attachEventBridge(session, options) {
|
|
|
1189
480
|
if (activeCompactionCount > 0 || compactionChain !== callbacks) await awaitStableCompaction();
|
|
1190
481
|
}
|
|
1191
482
|
}
|
|
1192
|
-
function
|
|
483
|
+
function buildAssistantMessage(params) {
|
|
484
|
+
const event = params.event;
|
|
485
|
+
const text = event ? event.data.content || params.assistantTexts[params.assistantTexts.length - 1] || "" : "";
|
|
486
|
+
const reasoningText = event?.data.reasoningText ?? joinReasoning(params.reasoningOrder, params.reasoningById);
|
|
487
|
+
const toolRequests = event?.data.toolRequests ?? [];
|
|
488
|
+
if (!text && !reasoningText && toolRequests.length === 0) return;
|
|
489
|
+
const content = [];
|
|
490
|
+
if (reasoningText) content.push({
|
|
491
|
+
thinking: reasoningText,
|
|
492
|
+
type: "thinking"
|
|
493
|
+
});
|
|
494
|
+
if (text) content.push({
|
|
495
|
+
text,
|
|
496
|
+
type: "text"
|
|
497
|
+
});
|
|
498
|
+
for (const request of toolRequests) content.push({
|
|
499
|
+
arguments: request.arguments ?? {},
|
|
500
|
+
id: request.toolCallId,
|
|
501
|
+
name: request.name,
|
|
502
|
+
type: "toolCall"
|
|
503
|
+
});
|
|
504
|
+
return {
|
|
505
|
+
api: params.modelRef.api ?? "openai-responses",
|
|
506
|
+
content,
|
|
507
|
+
model: event?.data.model ?? params.modelRef.id,
|
|
508
|
+
provider: params.modelRef.provider,
|
|
509
|
+
role: "assistant",
|
|
510
|
+
stopReason: toolRequests.length > 0 ? "toolUse" : "stop",
|
|
511
|
+
timestamp: params.now(),
|
|
512
|
+
usage: buildCopilotAssistantUsage({
|
|
513
|
+
fallbackOutputTokens: event?.data.outputTokens,
|
|
514
|
+
usage: params.usage
|
|
515
|
+
})
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
function createPromptError$1(code, message, cause) {
|
|
1193
519
|
const error = new Error(message);
|
|
1194
520
|
error.code = code;
|
|
1195
521
|
if (cause !== void 0) error.cause = cause;
|
|
@@ -1213,69 +539,6 @@ function finalizeAssistantTexts(messageOrder, messagesById, event) {
|
|
|
1213
539
|
if (event?.data.content) return [event.data.content];
|
|
1214
540
|
return [];
|
|
1215
541
|
}
|
|
1216
|
-
function buildAssistantProjectionGroup(group, modelRef, resolveTimestamp, usageByApiCallId, latestUsage, forTranscript) {
|
|
1217
|
-
const messages = group.chunks.flatMap((chunk) => {
|
|
1218
|
-
const message = buildAssistantMessage({
|
|
1219
|
-
event: chunk.event,
|
|
1220
|
-
modelRef,
|
|
1221
|
-
now: () => resolveTimestamp(chunk.event),
|
|
1222
|
-
reasoningText: forTranscript ? chunk.transcriptReasoningText : chunk.reasoningText,
|
|
1223
|
-
usage: resolveAssistantUsage(chunk.event, latestUsage, usageByApiCallId),
|
|
1224
|
-
assistantTexts: forTranscript ? chunk.transcriptAssistantTexts : chunk.assistantTexts
|
|
1225
|
-
});
|
|
1226
|
-
return message ? [message] : [];
|
|
1227
|
-
});
|
|
1228
|
-
const replayIncomplete = group.chunks.some(({ event }) => hasUnprojectedAssistantReplayState(event));
|
|
1229
|
-
const last = messages.at(-1);
|
|
1230
|
-
if (!last) return {
|
|
1231
|
-
message: void 0,
|
|
1232
|
-
replayIncomplete,
|
|
1233
|
-
toolCallIds: []
|
|
1234
|
-
};
|
|
1235
|
-
const narrative = [];
|
|
1236
|
-
let terminalThinking;
|
|
1237
|
-
const toolCallOrder = [];
|
|
1238
|
-
const toolCallsById = /* @__PURE__ */ new Map();
|
|
1239
|
-
for (const message of messages) for (const part of message.content) {
|
|
1240
|
-
if (part.type === "toolCall") {
|
|
1241
|
-
if (!toolCallsById.has(part.id)) toolCallOrder.push(part.id);
|
|
1242
|
-
toolCallsById.set(part.id, part);
|
|
1243
|
-
continue;
|
|
1244
|
-
}
|
|
1245
|
-
if (part.type === "thinking") {
|
|
1246
|
-
terminalThinking = part;
|
|
1247
|
-
continue;
|
|
1248
|
-
}
|
|
1249
|
-
const previous = narrative.at(-1);
|
|
1250
|
-
if (part.type === "text" && previous?.type === "text") narrative[narrative.length - 1] = {
|
|
1251
|
-
...previous,
|
|
1252
|
-
text: previous.text + part.text
|
|
1253
|
-
};
|
|
1254
|
-
else narrative.push(part);
|
|
1255
|
-
}
|
|
1256
|
-
const toolCalls = toolCallOrder.flatMap((id) => {
|
|
1257
|
-
const toolCall = toolCallsById.get(id);
|
|
1258
|
-
return toolCall ? [toolCall] : [];
|
|
1259
|
-
});
|
|
1260
|
-
const content = [
|
|
1261
|
-
...terminalThinking ? [terminalThinking] : [],
|
|
1262
|
-
...narrative,
|
|
1263
|
-
...toolCalls
|
|
1264
|
-
];
|
|
1265
|
-
const toolCallIds = [...toolCallOrder];
|
|
1266
|
-
return {
|
|
1267
|
-
message: {
|
|
1268
|
-
...last,
|
|
1269
|
-
content,
|
|
1270
|
-
stopReason: toolCallIds.length > 0 ? "toolUse" : "stop"
|
|
1271
|
-
},
|
|
1272
|
-
replayIncomplete,
|
|
1273
|
-
toolCallIds
|
|
1274
|
-
};
|
|
1275
|
-
}
|
|
1276
|
-
function hasUnprojectedAssistantReplayState(event) {
|
|
1277
|
-
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;
|
|
1278
|
-
}
|
|
1279
542
|
function isAssistantMessageEvent(event) {
|
|
1280
543
|
return event?.type === "assistant.message";
|
|
1281
544
|
}
|
|
@@ -1291,7 +554,7 @@ function joinReasoning(order, reasoningById) {
|
|
|
1291
554
|
function splitPlanText(text) {
|
|
1292
555
|
return (text ?? "").split(/\r?\n/).map((line) => line.trim().replace(/^[-*]\s+/, "")).filter((line) => line.length > 0);
|
|
1293
556
|
}
|
|
1294
|
-
function readString$
|
|
557
|
+
function readString$2(value) {
|
|
1295
558
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1296
559
|
}
|
|
1297
560
|
function registerListener(session, unsubscribeFns, eventType, handler) {
|
|
@@ -1300,246 +563,415 @@ function registerListener(session, unsubscribeFns, eventType, handler) {
|
|
|
1300
563
|
unsubscribeFns.push(maybeUnsubscribe);
|
|
1301
564
|
return;
|
|
1302
565
|
}
|
|
1303
|
-
unsubscribeFns.push(() => {
|
|
1304
|
-
session.off?.(eventType, handler);
|
|
1305
|
-
});
|
|
1306
|
-
}
|
|
1307
|
-
function toLintErrorObject(value, fallbackMessage) {
|
|
1308
|
-
if (value instanceof Error) return value;
|
|
1309
|
-
if (typeof value === "string") return new Error(value);
|
|
1310
|
-
const error = new Error(fallbackMessage, { cause: value });
|
|
1311
|
-
if (typeof value === "object" && value !== null || typeof value === "function") Object.assign(error, value);
|
|
1312
|
-
return error;
|
|
566
|
+
unsubscribeFns.push(() => {
|
|
567
|
+
session.off?.(eventType, handler);
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
function toLintErrorObject(value, fallbackMessage) {
|
|
571
|
+
if (value instanceof Error) return value;
|
|
572
|
+
if (typeof value === "string") return new Error(value);
|
|
573
|
+
const error = new Error(fallbackMessage, { cause: value });
|
|
574
|
+
if (typeof value === "object" && value !== null || typeof value === "function") Object.assign(error, value);
|
|
575
|
+
return error;
|
|
576
|
+
}
|
|
577
|
+
//#endregion
|
|
578
|
+
//#region extensions/copilot/src/hooks-bridge.ts
|
|
579
|
+
const DEFAULT_HOOK_ERROR_HANDLER = ({ hookName, error }) => {
|
|
580
|
+
console.warn(`[copilot hooks-bridge] ${hookName} handler threw:`, error);
|
|
581
|
+
};
|
|
582
|
+
/**
|
|
583
|
+
* Wrap a native handler so it cannot throw into the SDK. Returning undefined
|
|
584
|
+
* leaves the SDK's default decision in place.
|
|
585
|
+
*/
|
|
586
|
+
function isolate(hookName, handler, onError) {
|
|
587
|
+
if (!handler) return;
|
|
588
|
+
return async (...args) => {
|
|
589
|
+
try {
|
|
590
|
+
return await handler(...args);
|
|
591
|
+
} catch (error) {
|
|
592
|
+
try {
|
|
593
|
+
onError({
|
|
594
|
+
hookName,
|
|
595
|
+
error
|
|
596
|
+
});
|
|
597
|
+
} catch {}
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Build an SDK-shaped hook object from native per-attempt configuration.
|
|
604
|
+
* Omit the SDK hook subsystem when no handlers were configured.
|
|
605
|
+
*/
|
|
606
|
+
function createHooksBridge(config, options) {
|
|
607
|
+
if (!config) return;
|
|
608
|
+
const onError = config.onHookError ?? DEFAULT_HOOK_ERROR_HANDLER;
|
|
609
|
+
const hooks = {};
|
|
610
|
+
const pre = isolate("onPreToolUse", config.onPreToolUse, onError);
|
|
611
|
+
const preMcp = isolate("onPreMcpToolCall", config.onPreMcpToolCall, onError);
|
|
612
|
+
const post = isolate("onPostToolUse", config.onPostToolUse, onError);
|
|
613
|
+
const postFailure = isolate("onPostToolUseFailure", config.onPostToolUseFailure, onError);
|
|
614
|
+
const userPrompt = isolate("onUserPromptSubmitted", config.onUserPromptSubmitted, onError);
|
|
615
|
+
const sessionStart = isolate("onSessionStart", config.onSessionStart, onError);
|
|
616
|
+
const sessionEnd = isolate("onSessionEnd", config.onSessionEnd, onError);
|
|
617
|
+
const errorOccurred = isolate("onErrorOccurred", config.onErrorOccurred, onError);
|
|
618
|
+
if (pre) hooks.onPreToolUse = pre;
|
|
619
|
+
if (preMcp) hooks.onPreMcpToolCall = preMcp;
|
|
620
|
+
if (post) hooks.onPostToolUse = post;
|
|
621
|
+
if (postFailure) hooks.onPostToolUseFailure = postFailure;
|
|
622
|
+
if (userPrompt) hooks.onUserPromptSubmitted = async (input, invocation) => {
|
|
623
|
+
const output = await userPrompt(input, invocation);
|
|
624
|
+
try {
|
|
625
|
+
options?.onUserPromptSubmitted?.({
|
|
626
|
+
prompt: output?.modifiedPrompt ?? input.prompt,
|
|
627
|
+
...output?.additionalContext ? { additionalContext: output.additionalContext } : {}
|
|
628
|
+
});
|
|
629
|
+
} catch (error) {
|
|
630
|
+
try {
|
|
631
|
+
onError({
|
|
632
|
+
hookName: "onUserPromptSubmitted",
|
|
633
|
+
error
|
|
634
|
+
});
|
|
635
|
+
} catch {}
|
|
636
|
+
}
|
|
637
|
+
return output;
|
|
638
|
+
};
|
|
639
|
+
if (sessionStart) hooks.onSessionStart = sessionStart;
|
|
640
|
+
if (sessionEnd) hooks.onSessionEnd = sessionEnd;
|
|
641
|
+
if (errorOccurred) hooks.onErrorOccurred = errorOccurred;
|
|
642
|
+
return Object.keys(hooks).length > 0 ? hooks : void 0;
|
|
643
|
+
}
|
|
644
|
+
//#endregion
|
|
645
|
+
//#region extensions/copilot/src/native-subagent-task-mirror.ts
|
|
646
|
+
const COPILOT_NATIVE_SUBAGENT_TASK_KIND = "copilot-native";
|
|
647
|
+
const COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX = "copilot-agent:";
|
|
648
|
+
function createCopilotNativeSubagentTaskMirror(params) {
|
|
649
|
+
if (!params.scope) return;
|
|
650
|
+
return new CopilotNativeSubagentTaskMirror({
|
|
651
|
+
agentId: params.agentId,
|
|
652
|
+
now: params.now
|
|
653
|
+
}, createAgentHarnessTaskRuntime({
|
|
654
|
+
runtime: "subagent",
|
|
655
|
+
taskKind: COPILOT_NATIVE_SUBAGENT_TASK_KIND,
|
|
656
|
+
scope: params.scope,
|
|
657
|
+
runIdPrefix: COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX
|
|
658
|
+
}));
|
|
659
|
+
}
|
|
660
|
+
var CopilotNativeSubagentTaskMirror = class {
|
|
661
|
+
constructor(params, runtime) {
|
|
662
|
+
this.params = params;
|
|
663
|
+
this.runtime = runtime;
|
|
664
|
+
this.runIdByAgentId = /* @__PURE__ */ new Map();
|
|
665
|
+
this.runIdByToolCallId = /* @__PURE__ */ new Map();
|
|
666
|
+
this.terminalRunIds = /* @__PURE__ */ new Set();
|
|
667
|
+
this.activeRunIds = /* @__PURE__ */ new Set();
|
|
668
|
+
this.now = params.now ?? Date.now;
|
|
669
|
+
}
|
|
670
|
+
handleEvent(event) {
|
|
671
|
+
const toolCallId = event.data.toolCallId.trim();
|
|
672
|
+
if (!toolCallId) return;
|
|
673
|
+
const runId = this.resolveRunId(event);
|
|
674
|
+
if (event.type === "subagent.started") {
|
|
675
|
+
this.handleStarted(event, runId, toolCallId);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (event.type === "subagent.completed") {
|
|
679
|
+
this.handleCompleted(event, runId);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
this.handleFailed(event, runId);
|
|
683
|
+
}
|
|
684
|
+
finalizeActiveRuns() {
|
|
685
|
+
const eventAt = this.now();
|
|
686
|
+
for (const runId of this.activeRunIds) {
|
|
687
|
+
this.terminalRunIds.add(runId);
|
|
688
|
+
this.runtime.finalizeTaskRunByRunId({
|
|
689
|
+
runId,
|
|
690
|
+
status: "cancelled",
|
|
691
|
+
endedAt: eventAt,
|
|
692
|
+
lastEventAt: eventAt,
|
|
693
|
+
error: "Copilot native subagent ended with its parent attempt.",
|
|
694
|
+
progressSummary: "Copilot native subagent cancelled with its parent attempt.",
|
|
695
|
+
terminalSummary: "Copilot native subagent cancelled."
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
this.activeRunIds.clear();
|
|
699
|
+
}
|
|
700
|
+
handleStarted(event, runId, toolCallId) {
|
|
701
|
+
const agentId = event.agentId?.trim();
|
|
702
|
+
if (agentId ? this.runIdByAgentId.get(agentId) : this.runIdByToolCallId.get(toolCallId)) return;
|
|
703
|
+
const eventAt = this.now();
|
|
704
|
+
const label = event.data.agentDisplayName.trim() || event.data.agentName.trim();
|
|
705
|
+
const task = event.data.agentDescription.trim() || `Copilot native subagent ${label}`;
|
|
706
|
+
if (!this.runtime.tryCreateRunningTaskRun({
|
|
707
|
+
sourceId: toolCallId,
|
|
708
|
+
agentId: this.params.agentId,
|
|
709
|
+
runId,
|
|
710
|
+
label: label || "Copilot subagent",
|
|
711
|
+
task,
|
|
712
|
+
notifyPolicy: "silent",
|
|
713
|
+
deliveryStatus: "not_applicable",
|
|
714
|
+
preferMetadata: true,
|
|
715
|
+
startedAt: eventAt,
|
|
716
|
+
lastEventAt: eventAt,
|
|
717
|
+
progressSummary: "Copilot native subagent started."
|
|
718
|
+
})) return;
|
|
719
|
+
if (agentId) this.runIdByAgentId.set(agentId, runId);
|
|
720
|
+
else this.runIdByToolCallId.set(toolCallId, runId);
|
|
721
|
+
this.terminalRunIds.delete(runId);
|
|
722
|
+
this.activeRunIds.add(runId);
|
|
723
|
+
}
|
|
724
|
+
handleCompleted(event, runId) {
|
|
725
|
+
if (this.terminalRunIds.has(runId)) return;
|
|
726
|
+
const eventAt = this.now();
|
|
727
|
+
this.terminalRunIds.add(runId);
|
|
728
|
+
this.activeRunIds.delete(runId);
|
|
729
|
+
this.runtime.finalizeTaskRunByRunId({
|
|
730
|
+
runId,
|
|
731
|
+
status: "succeeded",
|
|
732
|
+
endedAt: eventAt,
|
|
733
|
+
lastEventAt: eventAt,
|
|
734
|
+
progressSummary: "Copilot native subagent completed.",
|
|
735
|
+
terminalSummary: buildCompletionSummary(event)
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
handleFailed(event, runId) {
|
|
739
|
+
if (this.terminalRunIds.has(runId)) return;
|
|
740
|
+
const eventAt = this.now();
|
|
741
|
+
this.terminalRunIds.add(runId);
|
|
742
|
+
this.activeRunIds.delete(runId);
|
|
743
|
+
this.runtime.finalizeTaskRunByRunId({
|
|
744
|
+
runId,
|
|
745
|
+
status: "failed",
|
|
746
|
+
endedAt: eventAt,
|
|
747
|
+
lastEventAt: eventAt,
|
|
748
|
+
error: event.data.error,
|
|
749
|
+
progressSummary: "Copilot native subagent failed.",
|
|
750
|
+
terminalSummary: "Copilot native subagent failed."
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
resolveRunId(event) {
|
|
754
|
+
const agentId = event.agentId?.trim();
|
|
755
|
+
if (agentId) {
|
|
756
|
+
const existing = this.runIdByAgentId.get(agentId);
|
|
757
|
+
if (existing) return existing;
|
|
758
|
+
}
|
|
759
|
+
const existing = this.runIdByToolCallId.get(event.data.toolCallId);
|
|
760
|
+
if (existing) return existing;
|
|
761
|
+
const identity = agentId || event.data.toolCallId.trim();
|
|
762
|
+
return `${COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX}${identity}`;
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
function buildCompletionSummary(event) {
|
|
766
|
+
const details = [event.data.totalToolCalls !== void 0 ? `${event.data.totalToolCalls} tool calls` : void 0, event.data.totalTokens !== void 0 ? `${event.data.totalTokens} tokens` : void 0].filter((value) => value !== void 0);
|
|
767
|
+
return details.length > 0 ? `Copilot native subagent completed (${details.join(", ")}).` : "Copilot native subagent completed.";
|
|
1313
768
|
}
|
|
1314
769
|
//#endregion
|
|
1315
|
-
//#region extensions/copilot/src/
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
return (async () => {
|
|
1335
|
-
let outcome = "deadline";
|
|
770
|
+
//#region extensions/copilot/src/permission-bridge.ts
|
|
771
|
+
/** Built-in fail-closed default. Mirrors the pre-bridge attempt.ts stub. */
|
|
772
|
+
const REJECT_ALL_FEEDBACK = "copilot agent runtime: no permission policy installed (fail-closed default)";
|
|
773
|
+
const rejectAllPolicy = () => ({
|
|
774
|
+
kind: "reject",
|
|
775
|
+
feedback: REJECT_ALL_FEEDBACK
|
|
776
|
+
});
|
|
777
|
+
/**
|
|
778
|
+
* Adapt a `CopilotPermissionPolicy` to the SDK's
|
|
779
|
+
* `PermissionHandler` shape. The returned handler always resolves
|
|
780
|
+
* (never rejects), defaulting to fail-closed when the policy returns
|
|
781
|
+
* undefined or throws.
|
|
782
|
+
*/
|
|
783
|
+
function createPermissionBridge(policy = rejectAllPolicy) {
|
|
784
|
+
return async (request, invocation) => {
|
|
785
|
+
const ctx = {
|
|
786
|
+
request,
|
|
787
|
+
sessionId: invocation.sessionId
|
|
788
|
+
};
|
|
1336
789
|
try {
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
if (outcome !== "completed") {
|
|
1345
|
-
await cancelBackgroundCompactionBeforeTeardown(params.session);
|
|
1346
|
-
params.bridge.settleCompactionWait();
|
|
1347
|
-
}
|
|
1348
|
-
params.finalizeNativeSubagents?.();
|
|
1349
|
-
params.bridge.detach();
|
|
1350
|
-
try {
|
|
1351
|
-
await params.session.disconnect();
|
|
1352
|
-
} catch {}
|
|
1353
|
-
params.cleanupToolBridge?.();
|
|
1354
|
-
await params.cleanupByokProxy?.();
|
|
1355
|
-
if (outcome !== "completed" && params.deleteSessionOnIncompleteCleanup && params.sdkSessionId) try {
|
|
1356
|
-
await params.handle.client.deleteSession(params.sdkSessionId);
|
|
1357
|
-
} catch {}
|
|
1358
|
-
try {
|
|
1359
|
-
await params.pool.release(params.handle);
|
|
1360
|
-
} catch {}
|
|
790
|
+
const result = await policy(ctx);
|
|
791
|
+
if (result !== void 0) return result;
|
|
792
|
+
} catch (error) {
|
|
793
|
+
return {
|
|
794
|
+
kind: "reject",
|
|
795
|
+
feedback: `copilot permission policy threw: ${formatError(error)}`
|
|
796
|
+
};
|
|
1361
797
|
}
|
|
1362
|
-
return
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
if (!cancelBackgroundCompaction) return;
|
|
1368
|
-
let timeoutId;
|
|
1369
|
-
const deadline = new Promise((resolve) => {
|
|
1370
|
-
timeoutId = setTimeout(resolve, BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS);
|
|
1371
|
-
});
|
|
1372
|
-
try {
|
|
1373
|
-
await Promise.race([Promise.resolve().then(() => cancelBackgroundCompaction()).catch(() => void 0), deadline]);
|
|
1374
|
-
} finally {
|
|
1375
|
-
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
1376
|
-
}
|
|
798
|
+
return {
|
|
799
|
+
kind: "reject",
|
|
800
|
+
feedback: REJECT_ALL_FEEDBACK
|
|
801
|
+
};
|
|
802
|
+
};
|
|
1377
803
|
}
|
|
1378
|
-
|
|
1379
|
-
if (
|
|
1380
|
-
const completion = (async () => {
|
|
1381
|
-
if (params.awaitSessionIdle) await params.bridge.awaitSessionIdle();
|
|
1382
|
-
await params.bridge.awaitCompactionCompletion();
|
|
1383
|
-
return "completed";
|
|
1384
|
-
})();
|
|
1385
|
-
let resolveAbort = () => void 0;
|
|
1386
|
-
const aborted = new Promise((resolve) => {
|
|
1387
|
-
resolveAbort = () => resolve("aborted");
|
|
1388
|
-
params.abortSignal?.addEventListener("abort", resolveAbort, { once: true });
|
|
1389
|
-
});
|
|
1390
|
-
let timeoutId;
|
|
1391
|
-
const deadline = new Promise((resolve) => {
|
|
1392
|
-
timeoutId = setTimeout(() => resolve("deadline"), params.timeoutMs);
|
|
1393
|
-
});
|
|
804
|
+
function formatError(error) {
|
|
805
|
+
if (error instanceof Error) return error.message;
|
|
1394
806
|
try {
|
|
1395
|
-
return
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
deadline
|
|
1399
|
-
]);
|
|
1400
|
-
} finally {
|
|
1401
|
-
params.abortSignal?.removeEventListener("abort", resolveAbort);
|
|
1402
|
-
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
807
|
+
return JSON.stringify(error);
|
|
808
|
+
} catch {
|
|
809
|
+
return String(error);
|
|
1403
810
|
}
|
|
1404
811
|
}
|
|
1405
812
|
//#endregion
|
|
1406
|
-
//#region extensions/copilot/src/
|
|
1407
|
-
function
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
813
|
+
//#region extensions/copilot/src/replay-shim.ts
|
|
814
|
+
function normalizeSdkSessionId(value) {
|
|
815
|
+
if (typeof value !== "string") return;
|
|
816
|
+
const trimmed = value.trim();
|
|
817
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Pure pre-call decision: should attempt.ts call resumeSession or
|
|
821
|
+
* createSession?
|
|
822
|
+
*
|
|
823
|
+
* Rules:
|
|
824
|
+
* - No input → create (no-replay-state)
|
|
825
|
+
* - No (trimmed) sdkSessionId → create (no-sdk-session-id)
|
|
826
|
+
* - sdkSessionId + replayInvalid=true → create (replay-invalid),
|
|
827
|
+
* downgradedFromResume=true
|
|
828
|
+
* - sdkSessionId + replayInvalid=false → resume
|
|
829
|
+
*/
|
|
830
|
+
function decideReplayAction(input) {
|
|
831
|
+
if (!input) return {
|
|
832
|
+
action: "create",
|
|
833
|
+
downgradedFromResume: false,
|
|
834
|
+
downgradeReason: "no-replay-state"
|
|
1415
835
|
};
|
|
1416
|
-
const
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
text
|
|
1422
|
-
})) return;
|
|
1423
|
-
throw new Error("Copilot runtime is not waiting for user input.");
|
|
1424
|
-
},
|
|
1425
|
-
isStreaming: () => !params.isSettled() && !params.isAborted(),
|
|
1426
|
-
isAborted: params.isAborted,
|
|
1427
|
-
isCompacting: () => params.bridge?.isCompacting() ?? false,
|
|
1428
|
-
sourceReplyDeliveryMode: params.input.sourceReplyDeliveryMode,
|
|
1429
|
-
cancel: () => {
|
|
1430
|
-
cancelGatewayQuestionBestEffort("run-cancel");
|
|
1431
|
-
params.userInputBridge.cancelPending();
|
|
1432
|
-
params.abortActiveSession();
|
|
1433
|
-
},
|
|
1434
|
-
abort: () => {
|
|
1435
|
-
cancelGatewayQuestionBestEffort("run-abort");
|
|
1436
|
-
params.userInputBridge.cancelPending();
|
|
1437
|
-
params.abortActiveSession();
|
|
1438
|
-
}
|
|
836
|
+
const sdkSessionId = normalizeSdkSessionId(input.sdkSessionId);
|
|
837
|
+
if (!sdkSessionId) return {
|
|
838
|
+
action: "create",
|
|
839
|
+
downgradedFromResume: false,
|
|
840
|
+
downgradeReason: "no-sdk-session-id"
|
|
1439
841
|
};
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
const snap = bridge?.snapshot();
|
|
1448
|
-
const assistantTexts = bridge?.finalizeAssistantTexts() ?? [];
|
|
1449
|
-
const lastAssistant = bridge?.buildAssistantMessage({
|
|
1450
|
-
modelRef,
|
|
1451
|
-
now
|
|
1452
|
-
});
|
|
1453
|
-
const transcript = transcriptJournal?.snapshot();
|
|
1454
|
-
const recorder = input.userTurnTranscriptRecorder;
|
|
1455
|
-
const currentRunUserKey = `${input.runId}:user`;
|
|
1456
|
-
const messagesSnapshot = transcript?.messagesSnapshot ?? (recorder?.isBlocked() ? removePreparedUser(messages, recorder.message, currentRunUserKey) : includePreparedUser(messages, recorder?.message, input.trigger === "memory", currentRunUserKey));
|
|
1457
|
-
const result = createResult(input, {
|
|
1458
|
-
aborted,
|
|
1459
|
-
assistantTexts,
|
|
1460
|
-
codeModeEngaged,
|
|
1461
|
-
currentAttemptAssistant: lastAssistant,
|
|
1462
|
-
currentAttemptCompletedAssistant: settledFinalizationAssistantCompleted ? lastAssistant : void 0,
|
|
1463
|
-
downgradedFromResume,
|
|
1464
|
-
externalAbort,
|
|
1465
|
-
itemLifecycle: {
|
|
1466
|
-
activeCount: Math.max((snap?.startedCount ?? 0) - (snap?.completedCount ?? 0), 0),
|
|
1467
|
-
completedCount: snap?.completedCount ?? 0,
|
|
1468
|
-
startedCount: snap?.startedCount ?? 0
|
|
1469
|
-
},
|
|
1470
|
-
lastAssistant,
|
|
1471
|
-
lastToolError,
|
|
1472
|
-
journalValidated: transcript !== void 0 && !aborted && !timedOut && promptError === void 0 && !nativeSessionHistoryUnvalidated && transcriptJournal?.hasFailed() !== true && !transcript?.replayInvalid && (!sentTurnStarted || settledToolFinalization || transcript.initialSdkUserValidated),
|
|
1473
|
-
messagesSnapshot,
|
|
1474
|
-
assistantTranscriptOwned: transcript?.assistantTranscriptOwned,
|
|
1475
|
-
assistantTranscriptIdempotencyKey: transcript?.assistantTranscriptIdempotencyKey,
|
|
1476
|
-
nativeReplayInvalid: transcript?.replayInvalid === true || nativeSessionHistoryUnvalidated,
|
|
1477
|
-
now,
|
|
1478
|
-
promptError,
|
|
1479
|
-
resumeFailureRecovered,
|
|
842
|
+
if (input.replayInvalid === true) return {
|
|
843
|
+
action: "create",
|
|
844
|
+
downgradedFromResume: true,
|
|
845
|
+
downgradeReason: "replay-invalid"
|
|
846
|
+
};
|
|
847
|
+
return {
|
|
848
|
+
action: "resume",
|
|
1480
849
|
sdkSessionId,
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
850
|
+
downgradedFromResume: false
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
const MISSING_SESSION_CODES = /* @__PURE__ */ new Set([
|
|
854
|
+
"SESSION_NOT_FOUND",
|
|
855
|
+
"session_not_found",
|
|
856
|
+
"NotFound",
|
|
857
|
+
"ENOENT"
|
|
858
|
+
]);
|
|
859
|
+
const MISSING_SESSION_MESSAGE_PATTERNS = [
|
|
860
|
+
/\bsession not found\b/i,
|
|
861
|
+
/\bsession .* not found\b/i,
|
|
862
|
+
/\bunknown session id\b/i,
|
|
863
|
+
/\bsession id .* (does not exist|not found)\b/i,
|
|
864
|
+
/\bsession .* does not exist\b/i,
|
|
865
|
+
/\bno such session\b/i
|
|
866
|
+
];
|
|
867
|
+
function readErrorField(error, key) {
|
|
868
|
+
if (!error || typeof error !== "object") return;
|
|
869
|
+
return error[key];
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Post-call: classify a resumeSession() failure so attempt.ts can
|
|
873
|
+
* decide whether to downgrade silently to createSession.
|
|
874
|
+
*
|
|
875
|
+
* Conservative: only treats clearly session-gone signals as recoverable.
|
|
876
|
+
* Structured signals (status === 404, recognised code strings) are
|
|
877
|
+
* checked first; message matching is a fallback because SDK error
|
|
878
|
+
* messages are not part of the typed contract.
|
|
879
|
+
*
|
|
880
|
+
* Everything else (transport errors, auth failures, generic Error) is
|
|
881
|
+
* unrecoverable and should surface to the outer attempt.ts try/catch
|
|
882
|
+
* which converts it to a prompt error.
|
|
883
|
+
*/
|
|
884
|
+
function classifyResumeFailure(error) {
|
|
885
|
+
if (error === void 0 || error === null) return {
|
|
886
|
+
recoverable: false,
|
|
887
|
+
kind: "unknown"
|
|
888
|
+
};
|
|
889
|
+
if (readErrorField(error, "status") === 404) return {
|
|
890
|
+
recoverable: true,
|
|
891
|
+
kind: "missing"
|
|
892
|
+
};
|
|
893
|
+
if (readErrorField(error, "statusCode") === 404) return {
|
|
894
|
+
recoverable: true,
|
|
895
|
+
kind: "missing"
|
|
896
|
+
};
|
|
897
|
+
const code = readErrorField(error, "code");
|
|
898
|
+
if (typeof code === "string" && MISSING_SESSION_CODES.has(code)) return {
|
|
899
|
+
recoverable: true,
|
|
900
|
+
kind: "missing"
|
|
901
|
+
};
|
|
902
|
+
const message = error instanceof Error ? error.message : typeof error === "object" ? typeof error.message === "string" ? error.message : void 0 : void 0;
|
|
903
|
+
if (typeof message === "string") {
|
|
904
|
+
for (const pattern of MISSING_SESSION_MESSAGE_PATTERNS) if (pattern.test(message)) return {
|
|
905
|
+
recoverable: true,
|
|
906
|
+
kind: "missing"
|
|
907
|
+
};
|
|
1510
908
|
}
|
|
1511
|
-
return
|
|
909
|
+
return {
|
|
910
|
+
recoverable: false,
|
|
911
|
+
kind: "unknown"
|
|
912
|
+
};
|
|
1512
913
|
}
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
914
|
+
/**
|
|
915
|
+
* Compute the `EmbeddedRunReplayMetadata` to attach to the attempt
|
|
916
|
+
* result. Worst-case-wins:
|
|
917
|
+
*
|
|
918
|
+
* hadPotentialSideEffects = priorHadPotentialSideEffects OR timedOut
|
|
919
|
+
* OR thisAttemptHadPotentialSideEffects
|
|
920
|
+
* (timeout means we cannot prove the prompt was not partially
|
|
921
|
+
* committed server-side; treat as side-effecting so the
|
|
922
|
+
* orchestrator will not blindly re-issue the same prompt).
|
|
923
|
+
*
|
|
924
|
+
* replaySafe = NOT (
|
|
925
|
+
* priorReplayInvalid
|
|
926
|
+
* OR thisAttemptDowngradedFromResume
|
|
927
|
+
* OR thisAttemptResumeFailureRecovered
|
|
928
|
+
* OR hadPotentialSideEffects
|
|
929
|
+
* )
|
|
930
|
+
*
|
|
931
|
+
* Matches the parity rule in
|
|
932
|
+
* `src/agents/pi-embedded-runner/replay-state.ts#replayMetadataFromState`.
|
|
933
|
+
*/
|
|
934
|
+
function computeReplayMetadata(input) {
|
|
935
|
+
const priorReplayInvalid = input.priorReplayInvalid === true;
|
|
936
|
+
const priorHadPotentialSideEffects = input.priorHadPotentialSideEffects === true;
|
|
937
|
+
const timedOut = input.thisAttemptTimedOut === true;
|
|
938
|
+
const thisAttemptHadPotentialSideEffects = input.thisAttemptHadPotentialSideEffects === true;
|
|
939
|
+
const downgraded = input.thisAttemptDowngradedFromResume === true;
|
|
940
|
+
const recovered = input.thisAttemptResumeFailureRecovered === true;
|
|
941
|
+
const hadPotentialSideEffects = priorHadPotentialSideEffects || timedOut || thisAttemptHadPotentialSideEffects;
|
|
942
|
+
return {
|
|
943
|
+
hadPotentialSideEffects,
|
|
944
|
+
replaySafe: !(priorReplayInvalid || downgraded || recovered || hadPotentialSideEffects)
|
|
945
|
+
};
|
|
1535
946
|
}
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
947
|
+
const COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
948
|
+
"get",
|
|
949
|
+
"file_read",
|
|
950
|
+
"glob",
|
|
951
|
+
"grep",
|
|
952
|
+
"inspect",
|
|
953
|
+
"list",
|
|
954
|
+
"ls",
|
|
955
|
+
"memory_get",
|
|
956
|
+
"probe",
|
|
957
|
+
"query",
|
|
958
|
+
"read",
|
|
959
|
+
"search",
|
|
960
|
+
"sessions_history",
|
|
961
|
+
"sessions_list",
|
|
962
|
+
"status",
|
|
963
|
+
"tool_search",
|
|
964
|
+
"update_plan",
|
|
965
|
+
"view",
|
|
966
|
+
"web_fetch",
|
|
967
|
+
"web_search"
|
|
968
|
+
]);
|
|
969
|
+
function copilotToolMetasHavePotentialSideEffects(toolMetas) {
|
|
970
|
+
return (toolMetas ?? []).some((entry) => entry.asyncStarted === true || !isReplaySafeReadOnlyToolName(entry.toolName));
|
|
971
|
+
}
|
|
972
|
+
function isReplaySafeReadOnlyToolName(toolName) {
|
|
973
|
+
const normalized = toolName.trim().toLowerCase();
|
|
974
|
+
return COPILOT_REPLAY_SAFE_READ_ONLY_TOOL_NAMES.has(normalized);
|
|
1543
975
|
}
|
|
1544
976
|
//#endregion
|
|
1545
977
|
//#region extensions/copilot/src/tool-bridge.ts
|
|
@@ -1559,7 +991,6 @@ function supportsModelTools(modelProvider) {
|
|
|
1559
991
|
}
|
|
1560
992
|
async function createCopilotToolBridge(input) {
|
|
1561
993
|
if (!input.allowModelTools && !supportsModelTools(input.modelProvider)) return {
|
|
1562
|
-
codeModeEngaged: false,
|
|
1563
994
|
sdkTools: [],
|
|
1564
995
|
sourceTools: []
|
|
1565
996
|
};
|
|
@@ -1583,7 +1014,6 @@ async function createCopilotToolBridge(input) {
|
|
|
1583
1014
|
includeCoreTools: true
|
|
1584
1015
|
} : toolPlan;
|
|
1585
1016
|
if (!effectiveToolPlan.constructTools) return {
|
|
1586
|
-
codeModeEngaged: false,
|
|
1587
1017
|
sdkTools: [],
|
|
1588
1018
|
sourceTools: []
|
|
1589
1019
|
};
|
|
@@ -1596,7 +1026,6 @@ async function createCopilotToolBridge(input) {
|
|
|
1596
1026
|
executeTool: (toolParams) => executeCatalogTool(input, toolParams),
|
|
1597
1027
|
forceMessageTool: shouldForceCopilotMessageTool(attemptParams),
|
|
1598
1028
|
isRawModelRun: isCopilotRawModelRun(attemptParams),
|
|
1599
|
-
model: attemptParams.model,
|
|
1600
1029
|
modelId: input.modelId,
|
|
1601
1030
|
modelProvider: input.modelProvider,
|
|
1602
1031
|
modelToolsEnabled: true,
|
|
@@ -1605,8 +1034,6 @@ async function createCopilotToolBridge(input) {
|
|
|
1605
1034
|
runtimeToolAllowlist: effectiveToolPlan.runtimeToolAllowlist,
|
|
1606
1035
|
sessionId: input.sessionId,
|
|
1607
1036
|
sessionKey: attemptParams.sandboxSessionKey ?? attemptParams.sessionKey ?? input.sessionKey,
|
|
1608
|
-
scheduledToolPolicy: attemptParams.scheduledToolPolicy,
|
|
1609
|
-
skillWorkshopProposalOnly: attemptParams.skillWorkshopProposalOnly,
|
|
1610
1037
|
sourceReplyDeliveryMode: attemptParams.sourceReplyDeliveryMode,
|
|
1611
1038
|
toolsAllow: attemptParams.toolsAllow
|
|
1612
1039
|
});
|
|
@@ -1618,7 +1045,7 @@ async function createCopilotToolBridge(input) {
|
|
|
1618
1045
|
try {
|
|
1619
1046
|
sourceTools = await createOpenClawCodingTools(toolOptions);
|
|
1620
1047
|
} catch (error) {
|
|
1621
|
-
throw createError(`[copilot-tool-bridge] createOpenClawCodingTools failed: ${toError(error).message}`, error);
|
|
1048
|
+
throw createError(`[copilot-tool-bridge] createOpenClawCodingTools failed: ${toError$1(error).message}`, error);
|
|
1622
1049
|
}
|
|
1623
1050
|
if (!Array.isArray(sourceTools)) throw new Error("[copilot-tool-bridge] createOpenClawCodingTools must return an array of tools");
|
|
1624
1051
|
const allowedSourceTools = filterCopilotToolsForAllowlist(sourceTools, toolSurfaceRuntime.runtimeToolAllowlist);
|
|
@@ -1627,13 +1054,11 @@ async function createCopilotToolBridge(input) {
|
|
|
1627
1054
|
if (duplicateNames.length > 0) throw new Error(`[copilot-tool-bridge] duplicate tool names: ${duplicateNames.join(", ")}`);
|
|
1628
1055
|
return {
|
|
1629
1056
|
cleanup: toolSurfaceRuntime.cleanup,
|
|
1630
|
-
codeModeEngaged: toolSurfaceRuntime.codeModeControlsEnabled,
|
|
1631
1057
|
sdkTools: filteredTools.map((sourceTool) => convertOpenClawToolToSdkTool(sourceTool, {
|
|
1632
1058
|
abortSignal: input.abortSignal,
|
|
1633
1059
|
beforeExecute: input.beforeExecute,
|
|
1634
1060
|
onAgentToolResult: input.attemptParams?.onAgentToolResult,
|
|
1635
|
-
onToolCompleted: input.onToolCompleted
|
|
1636
|
-
observeToolTerminal: input.attemptParams?.observeToolTerminal
|
|
1061
|
+
onToolCompleted: input.onToolCompleted
|
|
1637
1062
|
})),
|
|
1638
1063
|
sourceTools: filteredTools
|
|
1639
1064
|
};
|
|
@@ -1689,12 +1114,9 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
|
1689
1114
|
elevated: a.bashElevated
|
|
1690
1115
|
},
|
|
1691
1116
|
messageProvider: a.messageProvider ?? a.messageChannel,
|
|
1692
|
-
chatType: a.chatType,
|
|
1693
1117
|
agentAccountId: a.agentAccountId,
|
|
1694
1118
|
messageTo: a.messageTo,
|
|
1695
1119
|
messageThreadId: a.messageThreadId,
|
|
1696
|
-
nativeChannelId: a.chatId,
|
|
1697
|
-
messageActionTurnCapability: a.messageActionTurnCapability,
|
|
1698
1120
|
groupId: a.groupId,
|
|
1699
1121
|
groupChannel: a.groupChannel,
|
|
1700
1122
|
groupSpace: a.groupSpace,
|
|
@@ -1705,7 +1127,6 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
|
1705
1127
|
senderUsername: a.senderUsername,
|
|
1706
1128
|
senderE164: a.senderE164,
|
|
1707
1129
|
senderIsOwner: a.senderIsOwner,
|
|
1708
|
-
scheduledToolPolicy: a.scheduledToolPolicy,
|
|
1709
1130
|
allowGatewaySubagentBinding: a.allowGatewaySubagentBinding,
|
|
1710
1131
|
sessionKey: sandboxSessionKey,
|
|
1711
1132
|
runSessionKey,
|
|
@@ -1729,7 +1150,6 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
|
1729
1150
|
modelCompat,
|
|
1730
1151
|
modelApi: model?.api,
|
|
1731
1152
|
modelContextWindowTokens: model?.contextWindow,
|
|
1732
|
-
delegationCapability: a.delegationCapability,
|
|
1733
1153
|
modelAuthMode: resolveModelAuthMode(input.modelProvider, a.config, void 0, { workspaceDir }),
|
|
1734
1154
|
currentChannelId: a.currentChannelId,
|
|
1735
1155
|
currentMessagingTarget: a.currentMessagingTarget,
|
|
@@ -1745,8 +1165,8 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
|
1745
1165
|
enableHeartbeatTool: a.enableHeartbeatTool,
|
|
1746
1166
|
forceHeartbeatTool: a.forceHeartbeatTool,
|
|
1747
1167
|
authProfileStore: a.toolAuthProfileStore ?? a.authProfileStore,
|
|
1748
|
-
computerContextEpoch: input.computerContextEpoch,
|
|
1749
1168
|
onToolOutcome: a.onToolOutcome,
|
|
1169
|
+
memoryTurnProvenance: a.memoryTurnProvenance,
|
|
1750
1170
|
onYield: (message) => {
|
|
1751
1171
|
try {
|
|
1752
1172
|
input.onYieldDetected?.(message);
|
|
@@ -1781,16 +1201,8 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1781
1201
|
console.warn("[copilot-tool-bridge] onToolCompleted handler threw; continuing", error);
|
|
1782
1202
|
}
|
|
1783
1203
|
};
|
|
1784
|
-
const failureResult = (executedArgs, invocation, startedAt, message, error
|
|
1785
|
-
const errorMessage = toError(error).message;
|
|
1786
|
-
ctx.observeToolTerminal?.({
|
|
1787
|
-
toolCallId: invocation.toolCallId,
|
|
1788
|
-
toolName: sourceTool.name,
|
|
1789
|
-
arguments: executedArgs,
|
|
1790
|
-
executionStarted,
|
|
1791
|
-
outcome: "failure",
|
|
1792
|
-
failure: { error: errorMessage }
|
|
1793
|
-
});
|
|
1204
|
+
const failureResult = (executedArgs, invocation, startedAt, message, error) => {
|
|
1205
|
+
const errorMessage = toError$1(error).message;
|
|
1794
1206
|
notifyToolResult(sanitizeToolResult({
|
|
1795
1207
|
content: [{
|
|
1796
1208
|
type: "text",
|
|
@@ -1814,7 +1226,7 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1814
1226
|
const startedAt = Date.now();
|
|
1815
1227
|
if (ctx.abortSignal?.aborted) {
|
|
1816
1228
|
const error = /* @__PURE__ */ new Error("[copilot-tool-bridge] aborted before execution");
|
|
1817
|
-
return failureResult(args, invocation, startedAt, error.message, error
|
|
1229
|
+
return failureResult(args, invocation, startedAt, error.message, error);
|
|
1818
1230
|
}
|
|
1819
1231
|
try {
|
|
1820
1232
|
await ctx.beforeExecute?.({
|
|
@@ -1825,32 +1237,24 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1825
1237
|
toolName: sourceTool.name
|
|
1826
1238
|
});
|
|
1827
1239
|
} catch (error) {
|
|
1828
|
-
return failureResult(args, invocation, startedAt, `[copilot-tool-bridge] beforeExecute failed for tool '${sourceTool.name}': ${toError(error).message}`, error
|
|
1240
|
+
return failureResult(args, invocation, startedAt, `[copilot-tool-bridge] beforeExecute failed for tool '${sourceTool.name}': ${toError$1(error).message}`, error);
|
|
1829
1241
|
}
|
|
1830
1242
|
let preparedArgs;
|
|
1831
1243
|
try {
|
|
1832
1244
|
preparedArgs = sourceTool.prepareArguments ? sourceTool.prepareArguments(args) : args;
|
|
1833
1245
|
} catch (error) {
|
|
1834
|
-
return failureResult(args, invocation, startedAt, `[copilot-tool-bridge] prepareArguments failed for tool '${sourceTool.name}': ${toError(error).message}`, error
|
|
1246
|
+
return failureResult(args, invocation, startedAt, `[copilot-tool-bridge] prepareArguments failed for tool '${sourceTool.name}': ${toError$1(error).message}`, error);
|
|
1835
1247
|
}
|
|
1836
1248
|
let result;
|
|
1837
1249
|
try {
|
|
1838
1250
|
result = await sourceTool.execute(invocation.toolCallId, preparedArgs, ctx.abortSignal, void 0);
|
|
1839
1251
|
} catch (error) {
|
|
1840
|
-
return failureResult(preparedArgs, invocation, startedAt, `[copilot-tool-bridge] tool '${sourceTool.name}' failed: ${toError(error).message}`, error
|
|
1252
|
+
return failureResult(preparedArgs, invocation, startedAt, `[copilot-tool-bridge] tool '${sourceTool.name}' failed: ${toError$1(error).message}`, error);
|
|
1841
1253
|
}
|
|
1842
|
-
const sdkResult =
|
|
1254
|
+
const sdkResult = agentToolResultToSdk(result);
|
|
1843
1255
|
const sanitizedResult = sanitizeToolResult(result);
|
|
1844
1256
|
const resultIsError = sdkResult.resultType === "failure" || isToolResultError(sanitizedResult);
|
|
1845
1257
|
const resultError = resultIsError ? extractToolErrorMessage(sanitizedResult) : void 0;
|
|
1846
|
-
ctx.observeToolTerminal?.({
|
|
1847
|
-
toolCallId: invocation.toolCallId,
|
|
1848
|
-
toolName: sourceTool.name,
|
|
1849
|
-
arguments: preparedArgs,
|
|
1850
|
-
executionStarted: true,
|
|
1851
|
-
outcome: resultIsError ? "failure" : "success",
|
|
1852
|
-
...resultIsError ? { failure: { error: resultError ?? "tool returned an error" } } : {}
|
|
1853
|
-
});
|
|
1854
1258
|
notifyToolResult(sanitizedResult, resultIsError);
|
|
1855
1259
|
notifyToolCompleted({
|
|
1856
1260
|
toolName: sourceTool.name,
|
|
@@ -1880,24 +1284,11 @@ async function executeCatalogTool(input, params) {
|
|
|
1880
1284
|
const sourceTool = params.tool;
|
|
1881
1285
|
const startedAt = Date.now();
|
|
1882
1286
|
let preparedArgs = params.input;
|
|
1883
|
-
let executionStarted = false;
|
|
1884
|
-
let terminalObserved = false;
|
|
1885
1287
|
try {
|
|
1886
1288
|
preparedArgs = sourceTool.prepareArguments ? sourceTool.prepareArguments(params.input) : params.input;
|
|
1887
|
-
executionStarted = true;
|
|
1888
1289
|
const result = await sourceTool.execute(params.toolCallId, preparedArgs, params.signal ?? input.abortSignal, params.onUpdate);
|
|
1889
1290
|
const sanitizedResult = sanitizeToolResult(result);
|
|
1890
1291
|
const isError = isToolResultError(sanitizedResult);
|
|
1891
|
-
const error = isError ? extractToolErrorMessage(sanitizedResult) ?? "tool returned an error" : void 0;
|
|
1892
|
-
terminalObserved = true;
|
|
1893
|
-
input.attemptParams?.observeToolTerminal?.({
|
|
1894
|
-
toolCallId: params.toolCallId,
|
|
1895
|
-
toolName: params.toolName,
|
|
1896
|
-
arguments: preparedArgs,
|
|
1897
|
-
executionStarted,
|
|
1898
|
-
outcome: isError ? "failure" : "success",
|
|
1899
|
-
...error ? { failure: { error } } : {}
|
|
1900
|
-
});
|
|
1901
1292
|
input.attemptParams?.onAgentToolResult?.({
|
|
1902
1293
|
toolName: params.toolName,
|
|
1903
1294
|
result: sanitizedResult,
|
|
@@ -1908,20 +1299,12 @@ async function executeCatalogTool(input, params) {
|
|
|
1908
1299
|
toolCallId: params.toolCallId,
|
|
1909
1300
|
args: toToolStartArgs(preparedArgs),
|
|
1910
1301
|
result: sanitizedResult,
|
|
1911
|
-
...
|
|
1302
|
+
...isError ? { error: extractToolErrorMessage(sanitizedResult) ?? "tool returned an error" } : {},
|
|
1912
1303
|
startedAt
|
|
1913
1304
|
});
|
|
1914
1305
|
return result;
|
|
1915
1306
|
} catch (error) {
|
|
1916
|
-
const message = toError(error).message;
|
|
1917
|
-
if (!terminalObserved) input.attemptParams?.observeToolTerminal?.({
|
|
1918
|
-
toolCallId: params.toolCallId,
|
|
1919
|
-
toolName: params.toolName,
|
|
1920
|
-
arguments: preparedArgs,
|
|
1921
|
-
executionStarted,
|
|
1922
|
-
outcome: "failure",
|
|
1923
|
-
failure: { error: message }
|
|
1924
|
-
});
|
|
1307
|
+
const message = toError$1(error).message;
|
|
1925
1308
|
const failure = sanitizeToolResult({
|
|
1926
1309
|
content: [{
|
|
1927
1310
|
type: "text",
|
|
@@ -1950,9 +1333,54 @@ async function executeCatalogTool(input, params) {
|
|
|
1950
1333
|
function toToolStartArgs(args) {
|
|
1951
1334
|
return args && typeof args === "object" && !Array.isArray(args) ? args : { value: args };
|
|
1952
1335
|
}
|
|
1336
|
+
function agentToolResultToSdk(result) {
|
|
1337
|
+
const content = result?.content;
|
|
1338
|
+
if (content == null) return createSuccessResult("");
|
|
1339
|
+
if (!Array.isArray(content)) return createUnsupportedContentFailure(typeof content);
|
|
1340
|
+
const textParts = [];
|
|
1341
|
+
const binaryResults = [];
|
|
1342
|
+
for (const block of content) {
|
|
1343
|
+
if (!block || typeof block !== "object") return createUnsupportedContentFailure(typeof block);
|
|
1344
|
+
const kind = readString$1(block.type);
|
|
1345
|
+
if (kind === "text") {
|
|
1346
|
+
const text = readString$1(block.text, { allowEmpty: true });
|
|
1347
|
+
if (text === void 0) return createUnsupportedContentFailure(kind);
|
|
1348
|
+
textParts.push(text);
|
|
1349
|
+
continue;
|
|
1350
|
+
}
|
|
1351
|
+
if (kind === "image") {
|
|
1352
|
+
const base64Data = readString$1(block.data);
|
|
1353
|
+
const mimeType = readString$1(block.mimeType);
|
|
1354
|
+
if (!base64Data || !mimeType) return createUnsupportedContentFailure(kind);
|
|
1355
|
+
binaryResults.push({
|
|
1356
|
+
base64Data,
|
|
1357
|
+
data: base64Data,
|
|
1358
|
+
mimeType,
|
|
1359
|
+
type: "image"
|
|
1360
|
+
});
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
return createUnsupportedContentFailure(kind ?? typeof block);
|
|
1364
|
+
}
|
|
1365
|
+
return {
|
|
1366
|
+
...binaryResults.length > 0 ? { binaryResultsForLlm: binaryResults } : {},
|
|
1367
|
+
resultType: "success",
|
|
1368
|
+
textResultForLlm: textParts.join("\n")
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
function createUnsupportedContentFailure(kind) {
|
|
1372
|
+
const message = `[copilot-tool-bridge] unsupported AgentToolResult content shape: ${kind}`;
|
|
1373
|
+
return createFailureResult(message, new Error(message));
|
|
1374
|
+
}
|
|
1375
|
+
function createSuccessResult(textResultForLlm) {
|
|
1376
|
+
return {
|
|
1377
|
+
resultType: "success",
|
|
1378
|
+
textResultForLlm
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1953
1381
|
function createFailureResult(message, error) {
|
|
1954
1382
|
return {
|
|
1955
|
-
error: toError(error).message,
|
|
1383
|
+
error: toError$1(error).message,
|
|
1956
1384
|
resultType: "failure",
|
|
1957
1385
|
textResultForLlm: message
|
|
1958
1386
|
};
|
|
@@ -1992,11 +1420,8 @@ function shouldForceCopilotMessageTool(params) {
|
|
|
1992
1420
|
* so final filtering keeps aliases, groups, plugin policies, and glob
|
|
1993
1421
|
* semantics identical to the in-tree embedded runner.
|
|
1994
1422
|
*/
|
|
1995
|
-
function filterCopilotToolsForAllowlist(tools, toolsAllow
|
|
1996
|
-
|
|
1997
|
-
if (!options?.forceToolNames?.length) return filtered;
|
|
1998
|
-
const allowedNames = /* @__PURE__ */ new Set([...filtered.map((tool) => tool.name), ...options.forceToolNames]);
|
|
1999
|
-
return tools.filter((tool) => allowedNames.has(tool.name));
|
|
1423
|
+
function filterCopilotToolsForAllowlist(tools, toolsAllow) {
|
|
1424
|
+
return applyEmbeddedAttemptToolsAllow(tools, toolsAllow, { toolMeta: (tool) => getPluginToolMeta(tool) ?? readInlinePluginToolMeta(tool) });
|
|
2000
1425
|
}
|
|
2001
1426
|
function filterCopilotToolsForConstructionPlan(tools, plan, options = {}) {
|
|
2002
1427
|
if (plan.includeBaseCodingTools && plan.includeShellTools) return tools;
|
|
@@ -2026,148 +1451,78 @@ function findDuplicateToolNames(sourceTools) {
|
|
|
2026
1451
|
}
|
|
2027
1452
|
return [...counts.entries()].filter(([, count]) => count > 1).map(([name]) => name).toSorted();
|
|
2028
1453
|
}
|
|
2029
|
-
function
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
//#endregion
|
|
2033
|
-
//#region extensions/copilot/src/attempt-prepare.ts
|
|
2034
|
-
function prepareCopilotAttemptContext(params, deps) {
|
|
2035
|
-
const settledToolFinalization = deps.operation === "settled-tool-finalization";
|
|
2036
|
-
const input = settledToolFinalization ? {
|
|
2037
|
-
...params,
|
|
2038
|
-
disableTools: true,
|
|
2039
|
-
images: [],
|
|
2040
|
-
imageOrder: [],
|
|
2041
|
-
extraSystemPrompt: void 0,
|
|
2042
|
-
onAgentEvent: void 0,
|
|
2043
|
-
onAgentToolResult: void 0,
|
|
2044
|
-
onAssistantDelta: void 0,
|
|
2045
|
-
onAssistantMessageStart: void 0,
|
|
2046
|
-
onBlockReply: void 0,
|
|
2047
|
-
onBlockReplyFlush: void 0,
|
|
2048
|
-
onPartialReply: void 0,
|
|
2049
|
-
onReasoningEnd: void 0,
|
|
2050
|
-
onReasoningStream: void 0,
|
|
2051
|
-
onToolResult: void 0,
|
|
2052
|
-
onToolStreamBoundary: void 0,
|
|
2053
|
-
operation: "settled-tool-finalization"
|
|
2054
|
-
} : params;
|
|
2055
|
-
const createToolBridge = deps.createToolBridge ?? createCopilotToolBridge;
|
|
2056
|
-
const ringZeroSystemAgentRun = (deps.isHostScopedToolActive?.("openclaw") ?? isHostScopedAgentToolActive("openclaw")) && input.toolsAllow?.length === 1 && input.toolsAllow[0]?.trim().toLowerCase() === "openclaw";
|
|
2057
|
-
const messages = Array.isArray(input.messages) ? [...input.messages] : [];
|
|
2058
|
-
const modelRef = resolveModelRef(input);
|
|
2059
|
-
const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
|
|
2060
|
-
const sandboxSessionKey = readString$3(input.sandboxSessionKey) ?? readString$3(input.sessionKey) ?? readString$3(input.sessionId);
|
|
2061
|
-
const { sessionAgentId } = resolveSessionAgentIds({
|
|
2062
|
-
sessionKey: readString$3(input.sessionKey),
|
|
2063
|
-
config: input.config,
|
|
2064
|
-
agentId: readString$3(params.agentId)
|
|
2065
|
-
});
|
|
2066
|
-
const hookContextWindowFields = {
|
|
2067
|
-
...input.contextWindowInfo?.tokens ? { contextTokenBudget: input.contextWindowInfo.tokens } : input.contextTokenBudget ? { contextTokenBudget: input.contextTokenBudget } : {},
|
|
2068
|
-
...input.contextWindowInfo?.source ? { contextWindowSource: input.contextWindowInfo.source } : {},
|
|
2069
|
-
...input.contextWindowInfo?.referenceTokens ? { contextWindowReferenceTokens: input.contextWindowInfo.referenceTokens } : {}
|
|
2070
|
-
};
|
|
2071
|
-
return {
|
|
2072
|
-
settledToolFinalization,
|
|
2073
|
-
input,
|
|
2074
|
-
createToolBridge,
|
|
2075
|
-
ringZeroSystemAgentRun,
|
|
2076
|
-
messages,
|
|
2077
|
-
modelRef,
|
|
2078
|
-
resolvedWorkspaceForSandbox,
|
|
2079
|
-
sandboxSessionKey,
|
|
2080
|
-
sessionAgentId,
|
|
2081
|
-
hookContextWindowFields,
|
|
2082
|
-
hookContext: {
|
|
2083
|
-
runId: input.runId,
|
|
2084
|
-
jobId: input.jobId,
|
|
2085
|
-
agentId: sessionAgentId,
|
|
2086
|
-
sessionKey: sandboxSessionKey,
|
|
2087
|
-
sessionId: input.sessionId,
|
|
2088
|
-
workspaceDir: resolvedWorkspaceForSandbox,
|
|
2089
|
-
modelProviderId: modelRef.provider,
|
|
2090
|
-
modelId: modelRef.id,
|
|
2091
|
-
trigger: input.trigger,
|
|
2092
|
-
...input.config ? { config: input.config } : {},
|
|
2093
|
-
...hookContextWindowFields,
|
|
2094
|
-
...buildAgentHookContextChannelFields(input)
|
|
2095
|
-
}
|
|
2096
|
-
};
|
|
1454
|
+
function readString$1(value, options = {}) {
|
|
1455
|
+
if (typeof value !== "string") return;
|
|
1456
|
+
if (options.allowEmpty || value.length > 0) return value;
|
|
2097
1457
|
}
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
config: params.input.config,
|
|
2101
|
-
sessionKey: params.sandboxSessionKey,
|
|
2102
|
-
workspaceDir: params.resolvedWorkspaceForSandbox
|
|
2103
|
-
});
|
|
2104
|
-
const effectiveWorkspaceDir = sandbox?.enabled ? sandbox.workspaceAccess === "rw" ? params.resolvedWorkspaceForSandbox : sandbox.workspaceDir : params.resolvedWorkspaceForSandbox;
|
|
2105
|
-
if (sandbox?.enabled && effectiveWorkspaceDir !== params.resolvedWorkspaceForSandbox) await fsp.mkdir(effectiveWorkspaceDir, { recursive: true });
|
|
2106
|
-
return {
|
|
2107
|
-
sandbox,
|
|
2108
|
-
effectiveWorkspaceDir
|
|
2109
|
-
};
|
|
1458
|
+
function toError$1(error) {
|
|
1459
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
2110
1460
|
}
|
|
2111
1461
|
//#endregion
|
|
2112
1462
|
//#region extensions/copilot/src/user-input-bridge.ts
|
|
2113
1463
|
const COPILOT_USER_INPUT_QUESTION_ID = "answer";
|
|
2114
|
-
const DEFAULT_USER_INPUT_TIMEOUT_MS = 15 * 6e4;
|
|
2115
1464
|
function createCopilotUserInputBridge(params) {
|
|
2116
1465
|
let pending;
|
|
2117
|
-
const
|
|
1466
|
+
const resolvePending = (value) => {
|
|
1467
|
+
const current = pending;
|
|
1468
|
+
if (!current) return;
|
|
1469
|
+
pending = void 0;
|
|
1470
|
+
current.cleanup();
|
|
1471
|
+
current.resolve(value);
|
|
1472
|
+
};
|
|
2118
1473
|
return {
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
questions: [question],
|
|
2130
|
-
sessionKey: params.paramsForRun.sessionKey ?? params.paramsForRun.sessionId,
|
|
2131
|
-
agentId: params.paramsForRun.agentId,
|
|
2132
|
-
runId: params.paramsForRun.runId,
|
|
2133
|
-
timeoutMs: params.paramsForRun.timeoutMs ?? DEFAULT_USER_INPUT_TIMEOUT_MS,
|
|
2134
|
-
gatewayCall,
|
|
2135
|
-
delivery: params.paramsForRun,
|
|
2136
|
-
promptOptions: {
|
|
2137
|
-
intro: "Copilot needs input:",
|
|
2138
|
-
formatText: formatCopilotDisplayText
|
|
2139
|
-
},
|
|
2140
|
-
signal: abort.signal
|
|
2141
|
-
});
|
|
2142
|
-
if (result.status !== "answered") return emptyCopilotUserInputResponse();
|
|
2143
|
-
const selected = result.answers.answers[COPILOT_USER_INPUT_QUESTION_ID]?.[0] ?? "";
|
|
2144
|
-
return {
|
|
2145
|
-
answer: selected,
|
|
2146
|
-
wasFreeform: !isChoiceAnswer(question, selected)
|
|
1474
|
+
onUserInputRequest(request) {
|
|
1475
|
+
const question = toQuestion(request);
|
|
1476
|
+
resolvePending(emptyCopilotUserInputResponse());
|
|
1477
|
+
return new Promise((resolve) => {
|
|
1478
|
+
const abortListener = () => resolvePending(emptyCopilotUserInputResponse());
|
|
1479
|
+
const cleanup = () => params.signal?.removeEventListener("abort", abortListener);
|
|
1480
|
+
pending = {
|
|
1481
|
+
question,
|
|
1482
|
+
resolve,
|
|
1483
|
+
cleanup
|
|
2147
1484
|
};
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
1485
|
+
params.signal?.addEventListener("abort", abortListener, { once: true });
|
|
1486
|
+
if (params.signal?.aborted) {
|
|
1487
|
+
resolvePending(emptyCopilotUserInputResponse());
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
deliverAgentHarnessUserInputPrompt(params.paramsForRun, [question], {
|
|
1491
|
+
intro: "Copilot needs input:",
|
|
1492
|
+
formatText: formatCopilotDisplayText
|
|
1493
|
+
}).catch((error) => {
|
|
1494
|
+
embeddedAgentLog.warn("failed to deliver copilot user input prompt", { error });
|
|
1495
|
+
});
|
|
1496
|
+
});
|
|
1497
|
+
},
|
|
1498
|
+
handleQueuedMessage(text) {
|
|
1499
|
+
const current = pending;
|
|
1500
|
+
if (!current) return false;
|
|
1501
|
+
resolvePending(buildCopilotUserInputResponse(current.question, text));
|
|
1502
|
+
return true;
|
|
2155
1503
|
},
|
|
2156
1504
|
cancelPending() {
|
|
2157
|
-
|
|
1505
|
+
resolvePending(emptyCopilotUserInputResponse());
|
|
2158
1506
|
}
|
|
2159
1507
|
};
|
|
2160
1508
|
}
|
|
2161
1509
|
function toQuestion(request) {
|
|
2162
1510
|
return {
|
|
2163
1511
|
id: COPILOT_USER_INPUT_QUESTION_ID,
|
|
2164
|
-
header: "Copilot",
|
|
1512
|
+
header: "Copilot needs input",
|
|
2165
1513
|
question: request.question,
|
|
2166
1514
|
isOther: request.allowFreeform !== false,
|
|
2167
1515
|
isSecret: false,
|
|
2168
1516
|
options: request.choices && request.choices.length > 0 ? request.choices.map((choice) => ({ label: choice })) : null
|
|
2169
1517
|
};
|
|
2170
1518
|
}
|
|
1519
|
+
function buildCopilotUserInputResponse(question, inputText) {
|
|
1520
|
+
const selected = buildAgentHarnessUserInputAnswers([question], inputText).answers[COPILOT_USER_INPUT_QUESTION_ID]?.answers[0] ?? "";
|
|
1521
|
+
return {
|
|
1522
|
+
answer: selected,
|
|
1523
|
+
wasFreeform: !isChoiceAnswer(question, selected)
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
2171
1526
|
function emptyCopilotUserInputResponse() {
|
|
2172
1527
|
return {
|
|
2173
1528
|
answer: "",
|
|
@@ -2208,7 +1563,7 @@ const COPILOT_BOOTSTRAP_CONTEXT_ORDER = /* @__PURE__ */ new Map([
|
|
|
2208
1563
|
]);
|
|
2209
1564
|
/**
|
|
2210
1565
|
* Loads OpenClaw workspace bootstrap files (IDENTITY.md, SOUL.md,
|
|
2211
|
-
* HEARTBEAT.md, USER.md, BOOTSTRAP.md, MEMORY.md, ...) using
|
|
1566
|
+
* HEARTBEAT.md, USER.md, TOOLS.md, BOOTSTRAP.md, MEMORY.md, ...) using
|
|
2212
1567
|
* the shared core helper PI and codex both use, then renders them as a
|
|
2213
1568
|
* single string suitable for `SessionConfig.systemMessage.content` on
|
|
2214
1569
|
* the Copilot SDK.
|
|
@@ -2269,9 +1624,9 @@ async function resolveCopilotWorkspaceBootstrapContext(params) {
|
|
|
2269
1624
|
* (`src/agents/pi-embedded-runner/run/attempt.ts:603`). Files whose
|
|
2270
1625
|
* resolved relative path escapes the source workspace (parent
|
|
2271
1626
|
* traversal or absolute) are left untouched so we never pretend a
|
|
2272
|
-
* file lives inside the sandbox when it does not.
|
|
2273
|
-
* to the Copilot extension (codex keeps
|
|
2274
|
-
* rather than importing from PI).
|
|
1627
|
+
* file lives inside the sandbox when it does not. Exported for unit
|
|
1628
|
+
* tests; intentionally local to the Copilot extension (codex keeps
|
|
1629
|
+
* similar helpers extension-local rather than importing from PI).
|
|
2275
1630
|
*/
|
|
2276
1631
|
function remapCopilotBootstrapContextFiles(params) {
|
|
2277
1632
|
if (params.sourceWorkspaceDir === params.targetWorkspaceDir) return params.files;
|
|
@@ -2343,631 +1698,178 @@ function readResolvedWorkspacePath(value) {
|
|
|
2343
1698
|
if (process.platform !== "win32" && /^[A-Za-z]:[\\/]/.test(raw)) return raw.trim();
|
|
2344
1699
|
return resolveUserPath(raw);
|
|
2345
1700
|
}
|
|
2346
|
-
//#endregion
|
|
2347
|
-
//#region extensions/copilot/src/attempt
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
});
|
|
2355
|
-
const originalDeveloperInstructions = settledToolFinalization ? "" : createSystemMessageContent(input, workspaceBootstrap.instructions) ?? "";
|
|
2356
|
-
const promptBuild = settledToolFinalization || isRawCopilotModelRun(input) ? {
|
|
2357
|
-
prompt: input.prompt,
|
|
2358
|
-
developerInstructions: originalDeveloperInstructions
|
|
2359
|
-
} : await resolveAgentHarnessBeforePromptBuildResult({
|
|
2360
|
-
prompt: input.prompt,
|
|
2361
|
-
developerInstructions: originalDeveloperInstructions,
|
|
2362
|
-
messages,
|
|
2363
|
-
ctx: hookContext,
|
|
2364
|
-
bootstrapContextRunKind: input.bootstrapContextRunKind
|
|
2365
|
-
});
|
|
2366
|
-
const attemptInput = promptBuild.prompt === input.prompt ? input : {
|
|
2367
|
-
...input,
|
|
2368
|
-
prompt: promptBuild.prompt
|
|
2369
|
-
};
|
|
2370
|
-
const promptTools = filterCopilotToolsForAllowlist(sdkTools, promptBuild.toolsAllow, shouldForceCopilotMessageTool(input) ? { forceToolNames: ["message"] } : void 0);
|
|
2371
|
-
let promptImagesCount = 0;
|
|
2372
|
-
const emitLlmInput = (prompt, additionalContext) => {
|
|
2373
|
-
if (settledToolFinalization) return;
|
|
2374
|
-
runAgentHarnessLlmInputHook({
|
|
2375
|
-
event: {
|
|
2376
|
-
runId: input.runId,
|
|
2377
|
-
sessionId: input.sessionId,
|
|
2378
|
-
provider: modelRef.provider,
|
|
2379
|
-
model: modelRef.id,
|
|
2380
|
-
...promptBuild.developerInstructions ? { systemPrompt: promptBuild.developerInstructions } : {},
|
|
2381
|
-
prompt: additionalContext ? `${prompt}\n\n${additionalContext}` : prompt,
|
|
2382
|
-
historyMessages: [],
|
|
2383
|
-
imagesCount: promptImagesCount,
|
|
2384
|
-
tools: promptTools
|
|
2385
|
-
},
|
|
2386
|
-
ctx: hookContext
|
|
2387
|
-
});
|
|
2388
|
-
};
|
|
2389
|
-
const hasNativePromptHook = !settledToolFinalization && Boolean(attemptInput.hooksConfig?.onUserPromptSubmitted);
|
|
2390
|
-
const userInputBridge = createCopilotUserInputBridge({
|
|
2391
|
-
paramsForRun: attemptInput,
|
|
2392
|
-
signal
|
|
2393
|
-
});
|
|
2394
|
-
const sessionConfig = createSessionConfig(attemptInput, modelRef.id, promptTools, poolAcquire.auth, sessionProvider, promptBuild.developerInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, settledToolFinalization ? void 0 : userInputBridge.onUserInputRequest, {
|
|
2395
|
-
hooksBridgeOptions: hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0,
|
|
2396
|
-
includeAskUser: !ringZeroSystemAgentRun,
|
|
2397
|
-
operation: operation ?? "attempt"
|
|
2398
|
-
});
|
|
2399
|
-
return {
|
|
2400
|
-
attemptInput,
|
|
2401
|
-
compactionSessionConfig: byokProxy ? createSessionConfig(attemptInput, modelRef.id, promptTools, poolAcquire.auth, poolAcquire.provider, promptBuild.developerInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, settledToolFinalization ? void 0 : userInputBridge.onUserInputRequest, {
|
|
2402
|
-
hooksBridgeOptions: hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0,
|
|
2403
|
-
includeAskUser: !ringZeroSystemAgentRun,
|
|
2404
|
-
operation: operation ?? "attempt"
|
|
2405
|
-
}) : sessionConfig,
|
|
2406
|
-
emitLlmInput,
|
|
2407
|
-
hasNativePromptHook,
|
|
2408
|
-
sessionConfig,
|
|
2409
|
-
setPromptImagesCount: (count) => {
|
|
2410
|
-
promptImagesCount = count;
|
|
2411
|
-
},
|
|
2412
|
-
userInputBridge
|
|
2413
|
-
};
|
|
2414
|
-
}
|
|
2415
|
-
//#endregion
|
|
2416
|
-
//#region extensions/copilot/src/attempt-transcript-journal.ts
|
|
2417
|
-
function readTurnTaintMetadata(message) {
|
|
2418
|
-
const metadata = message["__openclaw"];
|
|
2419
|
-
return metadata && typeof metadata === "object" && !Array.isArray(metadata) ? metadata : void 0;
|
|
2420
|
-
}
|
|
2421
|
-
function isActiveTurnTainted(messages) {
|
|
2422
|
-
for (const message of messages.toReversed()) {
|
|
2423
|
-
if (message.role === "user") return false;
|
|
2424
|
-
const metadata = readTurnTaintMetadata(message);
|
|
2425
|
-
if (metadata?.turnTainted === true || metadata?.resultContentSource === "network") return true;
|
|
2426
|
-
}
|
|
2427
|
-
return false;
|
|
2428
|
-
}
|
|
2429
|
-
function withAssistantTurnTaint(message, tainted) {
|
|
2430
|
-
return tainted ? {
|
|
2431
|
-
...message,
|
|
2432
|
-
__openclaw: {
|
|
2433
|
-
...readTurnTaintMetadata(message),
|
|
2434
|
-
turnTainted: true
|
|
2435
|
-
}
|
|
2436
|
-
} : message;
|
|
2437
|
-
}
|
|
2438
|
-
function createAttemptTranscriptJournal(params) {
|
|
2439
|
-
const hiddenTurn = params.attempt.trigger === "memory";
|
|
2440
|
-
const projectDisplay = (message) => projectAgentHarnessTranscriptMessageForDisplay({
|
|
2441
|
-
hidden: hiddenTurn || message.display === false,
|
|
2442
|
-
message
|
|
2443
|
-
});
|
|
2444
|
-
const messagesSnapshot = [...params.messages];
|
|
2445
|
-
let turnTainted = isActiveTurnTainted(messagesSnapshot);
|
|
2446
|
-
const snapshotIdempotencyKeys = new Set(messagesSnapshot.flatMap((message) => {
|
|
2447
|
-
const key = readIdempotencyKey(message);
|
|
2448
|
-
return key && isCurrentJournalIdentity(key, params) ? [key] : [];
|
|
2449
|
-
}));
|
|
2450
|
-
const replaceTailUser = (current, next) => {
|
|
2451
|
-
if (isSameUserTurn(messagesSnapshot.at(-1), current, `${params.attempt.runId}:user`)) {
|
|
2452
|
-
const removed = messagesSnapshot.pop();
|
|
2453
|
-
const removedKey = removed ? readIdempotencyKey(removed) : void 0;
|
|
2454
|
-
if (removedKey && isCurrentJournalIdentity(removedKey, params)) snapshotIdempotencyKeys.delete(removedKey);
|
|
2455
|
-
}
|
|
2456
|
-
if (next) {
|
|
2457
|
-
messagesSnapshot.push(next);
|
|
2458
|
-
const nextKey = readIdempotencyKey(next);
|
|
2459
|
-
if (nextKey && isCurrentJournalIdentity(nextKey, params)) snapshotIdempotencyKeys.add(nextKey);
|
|
2460
|
-
}
|
|
2461
|
-
};
|
|
2462
|
-
const currentUser = params.attempt.userTurnTranscriptRecorder?.message;
|
|
2463
|
-
if (currentUser) replaceTailUser(currentUser, projectDisplay(currentUser));
|
|
2464
|
-
const target = resolveTranscriptTarget(params.attempt);
|
|
2465
|
-
const config = params.attempt.config;
|
|
2466
|
-
const seenEventIds = /* @__PURE__ */ new Set();
|
|
2467
|
-
const deferredUserWrites = [];
|
|
2468
|
-
let pendingTools;
|
|
2469
|
-
let queue = Promise.resolve();
|
|
2470
|
-
let firstFailure;
|
|
2471
|
-
let abortPromise;
|
|
2472
|
-
let replayInvalid = false;
|
|
2473
|
-
let initialSdkUserObserved = false;
|
|
2474
|
-
let initialSdkUserValidated = false;
|
|
2475
|
-
let persistedInitialUser;
|
|
2476
|
-
let latestAssistantKey;
|
|
2477
|
-
let assistantTranscriptOwned = false;
|
|
2478
|
-
let assistantTranscriptIdempotencyKey;
|
|
2479
|
-
const captureFailure = (error) => {
|
|
2480
|
-
if (firstFailure) return;
|
|
2481
|
-
firstFailure = error instanceof Error ? error : new Error(String(error));
|
|
2482
|
-
replayInvalid = true;
|
|
2483
|
-
pendingTools = void 0;
|
|
2484
|
-
abortPromise = params.abortSession().catch(() => void 0);
|
|
2485
|
-
};
|
|
2486
|
-
const claim = (eventId) => !firstFailure && !seenEventIds.has(eventId) && Boolean(seenEventIds.add(eventId));
|
|
2487
|
-
const schedule = (task) => {
|
|
2488
|
-
if (firstFailure) return;
|
|
2489
|
-
queue = queue.then(() => firstFailure ? void 0 : task()).catch(captureFailure);
|
|
2490
|
-
};
|
|
2491
|
-
const prepare = (write, options = {}) => {
|
|
2492
|
-
const message = structuredClone(write.message);
|
|
2493
|
-
const originalReplayPayload = structuredClone(projectReplayPayload(message));
|
|
2494
|
-
const hooked = runAgentHarnessBeforeMessageWriteHook({
|
|
2495
|
-
message: structuredClone(message),
|
|
2496
|
-
agentId: target.agentId,
|
|
2497
|
-
sessionKey: target.sessionKey
|
|
2498
|
-
});
|
|
2499
|
-
if (!hooked) return;
|
|
2500
|
-
if (!isDeepStrictEqual(originalReplayPayload, projectReplayPayload(hooked))) replayInvalid = true;
|
|
2501
|
-
const idempotencyKey = message.idempotencyKey;
|
|
2502
|
-
const taintMetadata = readTurnTaintMetadata(message);
|
|
2503
|
-
const toolIdentity = message.role === "toolResult" ? {
|
|
2504
|
-
toolCallId: message.toolCallId,
|
|
2505
|
-
toolName: message.toolName
|
|
2506
|
-
} : {};
|
|
2507
|
-
const prepared = projectDisplay({
|
|
2508
|
-
...hooked,
|
|
2509
|
-
...toolIdentity,
|
|
2510
|
-
...taintMetadata ? { __openclaw: {
|
|
2511
|
-
...readTurnTaintMetadata(hooked),
|
|
2512
|
-
...taintMetadata
|
|
2513
|
-
} } : {},
|
|
2514
|
-
...idempotencyKey ? { idempotencyKey } : {},
|
|
2515
|
-
...message.display === false ? { display: false } : {}
|
|
2516
|
-
});
|
|
2517
|
-
return options.singleton && !isCompatibleSingletonRewrite(message, prepared) ? void 0 : prepared;
|
|
2518
|
-
};
|
|
2519
|
-
const append = async (write) => {
|
|
2520
|
-
const outcome = await appendSessionTranscriptMessageByIdentityStrict({
|
|
2521
|
-
...target,
|
|
2522
|
-
...config ? { config } : {},
|
|
2523
|
-
...write.eventId ? { eventId: write.eventId } : {},
|
|
2524
|
-
idempotencyLookup: "scan",
|
|
2525
|
-
message: write.message,
|
|
2526
|
-
prepareMessageAfterIdempotencyCheck: () => prepare(write, { singleton: true })
|
|
2527
|
-
});
|
|
2528
|
-
if (outcome.kind === "suppressed") return;
|
|
2529
|
-
if (outcome.kind === "rejected") throw new Error("Transcript session changed before singleton append");
|
|
2530
|
-
if (!isDeepStrictEqual(projectReplayPayload(write.message), projectReplayPayload(outcome.result.message))) replayInvalid = true;
|
|
2531
|
-
return outcome.result;
|
|
2532
|
-
};
|
|
2533
|
-
const appendToolGroup = async (group) => {
|
|
2534
|
-
const writes = [group.assistant, ...group.order.map((id) => group.results.get(id))];
|
|
2535
|
-
const keys = writes.map((write) => readIdempotencyKey(write.message));
|
|
2536
|
-
const persistedKeys = new Set((await readVisibleSessionTranscriptMessageEntries(target)).flatMap((entry) => entry.idempotencyKey ? [entry.idempotencyKey] : []));
|
|
2537
|
-
const persistedCount = keys.filter((key) => key && persistedKeys.has(key)).length;
|
|
2538
|
-
if (persistedCount > 0 && persistedCount < writes.length) throw new Error("Copilot transcript found a partial persisted tool group");
|
|
2539
|
-
const messages = persistedCount === writes.length ? writes.map((write) => write.message) : writes.map((write) => prepare(write));
|
|
2540
|
-
if (messages.some((message) => !message) || !isCompleteToolGroup(messages, group.order)) return;
|
|
2541
|
-
const results = await appendSessionTranscriptMessagesByIdentity({
|
|
2542
|
-
...target,
|
|
2543
|
-
...config ? { config } : {},
|
|
2544
|
-
messages: writes.map((write, index) => ({
|
|
2545
|
-
eventId: write.eventId,
|
|
2546
|
-
idempotencyLookup: "scan",
|
|
2547
|
-
message: messages[index]
|
|
2548
|
-
}))
|
|
2549
|
-
});
|
|
2550
|
-
if (!isCompleteToolGroup(results.map((result) => result.message), group.order)) throw new Error("Copilot transcript replayed an invalid tool group");
|
|
2551
|
-
if (results.some((result, index) => !isDeepStrictEqual(projectReplayPayload(writes[index].message), projectReplayPayload(result.message)))) replayInvalid = true;
|
|
2552
|
-
return results;
|
|
2553
|
-
};
|
|
2554
|
-
const publish = async (appended) => {
|
|
2555
|
-
if (appended) await publishSessionTranscriptUpdateByIdentity({ ...target }).catch((error) => {
|
|
2556
|
-
console.warn("[copilot-attempt] transcript update notification failed", error);
|
|
2557
|
-
});
|
|
2558
|
-
};
|
|
2559
|
-
const accept = (result) => {
|
|
2560
|
-
if (!result) return false;
|
|
2561
|
-
const key = readIdempotencyKey(result.message);
|
|
2562
|
-
const snapshotKey = key && isCurrentJournalIdentity(key, params) ? key : void 0;
|
|
2563
|
-
if (!snapshotKey || !snapshotIdempotencyKeys.has(snapshotKey)) {
|
|
2564
|
-
messagesSnapshot.push(result.message);
|
|
2565
|
-
if (snapshotKey) snapshotIdempotencyKeys.add(snapshotKey);
|
|
2566
|
-
}
|
|
2567
|
-
return result.appended;
|
|
2568
|
-
};
|
|
2569
|
-
const ownAssistant = (key, persisted) => {
|
|
2570
|
-
if (latestAssistantKey === key) {
|
|
2571
|
-
assistantTranscriptOwned = true;
|
|
2572
|
-
assistantTranscriptIdempotencyKey = persisted ? key : void 0;
|
|
2573
|
-
}
|
|
2574
|
-
};
|
|
2575
|
-
const drainQueue = async () => {
|
|
2576
|
-
while (true) {
|
|
2577
|
-
const tail = queue;
|
|
2578
|
-
await tail;
|
|
2579
|
-
if (tail === queue) break;
|
|
2580
|
-
}
|
|
2581
|
-
};
|
|
2582
|
-
const barrier = async (boundary) => {
|
|
2583
|
-
await drainQueue();
|
|
2584
|
-
if (!firstFailure) {
|
|
2585
|
-
await Promise.resolve();
|
|
2586
|
-
await drainQueue();
|
|
2587
|
-
}
|
|
2588
|
-
if (!firstFailure && pendingTools) captureFailure(/* @__PURE__ */ new Error(`Copilot transcript reached ${boundary} with unresolved tool results: ${pendingTools.order.join(", ")}`));
|
|
2589
|
-
if (abortPromise) await abortPromise;
|
|
2590
|
-
if (firstFailure) {
|
|
2591
|
-
const error = new Error(`[copilot-attempt] canonical transcript persistence failed: ${firstFailure.message}`, { cause: firstFailure });
|
|
2592
|
-
error.code = "transcript_persistence_failed";
|
|
2593
|
-
throw error;
|
|
2594
|
-
}
|
|
2595
|
-
};
|
|
2596
|
-
return {
|
|
2597
|
-
markReplayIncomplete() {
|
|
2598
|
-
replayInvalid = true;
|
|
2599
|
-
},
|
|
2600
|
-
recordAssistantProjectionGap() {
|
|
2601
|
-
replayInvalid = true;
|
|
2602
|
-
latestAssistantKey = void 0;
|
|
2603
|
-
assistantTranscriptOwned = false;
|
|
2604
|
-
assistantTranscriptIdempotencyKey = void 0;
|
|
2605
|
-
},
|
|
2606
|
-
async persistInitialUser() {
|
|
2607
|
-
const recorder = params.attempt.userTurnTranscriptRecorder;
|
|
2608
|
-
if (!recorder) {
|
|
2609
|
-
captureFailure(/* @__PURE__ */ new Error("Copilot transcript requires a user-turn recorder"));
|
|
2610
|
-
return await barrier("user prompt");
|
|
2611
|
-
}
|
|
2612
|
-
if (recorder.isBlocked()) {
|
|
2613
|
-
replayInvalid = true;
|
|
2614
|
-
replaceTailUser(recorder.message);
|
|
2615
|
-
return;
|
|
2616
|
-
}
|
|
2617
|
-
const persistence = (async () => {
|
|
2618
|
-
const resolved = await recorder.resolveMessage();
|
|
2619
|
-
if (!resolved) throw new Error("Copilot transcript user turn resolved without a message");
|
|
2620
|
-
const outcome = await append({ message: {
|
|
2621
|
-
...resolved,
|
|
2622
|
-
idempotencyKey: `${params.attempt.runId}:user`
|
|
2623
|
-
} });
|
|
2624
|
-
replaceTailUser(currentUser);
|
|
2625
|
-
if (!outcome) {
|
|
2626
|
-
replayInvalid = true;
|
|
2627
|
-
recorder.markBlocked();
|
|
2628
|
-
return;
|
|
2629
|
-
}
|
|
2630
|
-
const persisted = outcome.message;
|
|
2631
|
-
accept(outcome);
|
|
2632
|
-
persistedInitialUser = persisted;
|
|
2633
|
-
recorder.markRuntimePersisted(persisted);
|
|
2634
|
-
params.attempt.onUserMessagePersisted?.(persisted);
|
|
2635
|
-
await publish(outcome.appended);
|
|
2636
|
-
})();
|
|
2637
|
-
recorder.markRuntimePersistencePending(persistence);
|
|
2638
|
-
await persistence.catch(captureFailure);
|
|
2639
|
-
await barrier("user prompt");
|
|
2640
|
-
},
|
|
2641
|
-
recordSdkUser(input) {
|
|
2642
|
-
if (!claim(input.eventId)) return;
|
|
2643
|
-
replayInvalid ||= input.replayIncomplete === true;
|
|
2644
|
-
if (!initialSdkUserObserved && !input.autopilotContinuation) {
|
|
2645
|
-
initialSdkUserObserved = true;
|
|
2646
|
-
if (!persistedInitialUser || userText(persistedInitialUser.content) !== userText(input.message.content)) replayInvalid = true;
|
|
2647
|
-
else initialSdkUserValidated = true;
|
|
2648
|
-
return;
|
|
2649
|
-
}
|
|
2650
|
-
initialSdkUserObserved = true;
|
|
2651
|
-
schedule(async () => {
|
|
2652
|
-
const write = {
|
|
2653
|
-
eventId: input.eventId,
|
|
2654
|
-
message: input.message
|
|
2655
|
-
};
|
|
2656
|
-
if (pendingTools) {
|
|
2657
|
-
deferredUserWrites.push(write);
|
|
2658
|
-
return;
|
|
2659
|
-
}
|
|
2660
|
-
const outcome = await append(write);
|
|
2661
|
-
if (!outcome) replayInvalid = true;
|
|
2662
|
-
await publish(accept(outcome));
|
|
2663
|
-
});
|
|
2664
|
-
},
|
|
2665
|
-
recordAssistant(input) {
|
|
2666
|
-
if (!claim(input.eventId)) return;
|
|
2667
|
-
replayInvalid ||= input.replayIncomplete === true;
|
|
2668
|
-
const message = withAssistantTurnTaint(input.message, turnTainted);
|
|
2669
|
-
const key = `copilot-sdk:${params.sdkSessionId}:${input.eventId}`;
|
|
2670
|
-
latestAssistantKey = key;
|
|
2671
|
-
assistantTranscriptOwned = false;
|
|
2672
|
-
assistantTranscriptIdempotencyKey = void 0;
|
|
2673
|
-
schedule(async () => {
|
|
2674
|
-
if (pendingTools) throw new Error("Copilot emitted an assistant message before tool results settled");
|
|
2675
|
-
const write = {
|
|
2676
|
-
eventId: input.eventId,
|
|
2677
|
-
message: {
|
|
2678
|
-
...message,
|
|
2679
|
-
idempotencyKey: key
|
|
2680
|
-
}
|
|
2681
|
-
};
|
|
2682
|
-
if (input.toolCallIds.length > 0) {
|
|
2683
|
-
pendingTools = {
|
|
2684
|
-
assistant: write,
|
|
2685
|
-
assistantKey: key,
|
|
2686
|
-
order: input.toolCallIds,
|
|
2687
|
-
results: /* @__PURE__ */ new Map()
|
|
2688
|
-
};
|
|
2689
|
-
return;
|
|
2690
|
-
}
|
|
2691
|
-
const outcome = await append(write);
|
|
2692
|
-
if (!outcome) replayInvalid = true;
|
|
2693
|
-
ownAssistant(key, Boolean(outcome));
|
|
2694
|
-
await publish(accept(outcome));
|
|
2695
|
-
});
|
|
2696
|
-
},
|
|
2697
|
-
recordToolResult(input) {
|
|
2698
|
-
if (!claim(input.eventId)) return;
|
|
2699
|
-
turnTainted ||= readTurnTaintMetadata(input.message)?.resultContentSource === "network";
|
|
2700
|
-
schedule(async () => {
|
|
2701
|
-
const group = pendingTools;
|
|
2702
|
-
if (!group || !group.order.includes(input.message.toolCallId)) throw new Error(`Copilot emitted an unmatched tool result: ${input.message.toolCallId}`);
|
|
2703
|
-
group.results.set(input.message.toolCallId, {
|
|
2704
|
-
eventId: input.eventId,
|
|
2705
|
-
message: {
|
|
2706
|
-
...input.message,
|
|
2707
|
-
idempotencyKey: `copilot-sdk:${params.sdkSessionId}:${input.eventId}`
|
|
2708
|
-
}
|
|
2709
|
-
});
|
|
2710
|
-
replayInvalid ||= input.replayIncomplete === true;
|
|
2711
|
-
if (!group.order.every((toolCallId) => group.results.has(toolCallId))) return;
|
|
2712
|
-
const results = await appendToolGroup(group);
|
|
2713
|
-
let appended = false;
|
|
2714
|
-
if (!results) {
|
|
2715
|
-
replayInvalid = true;
|
|
2716
|
-
ownAssistant(group.assistantKey, false);
|
|
2717
|
-
} else {
|
|
2718
|
-
for (const result of results) {
|
|
2719
|
-
const didAppend = accept(result);
|
|
2720
|
-
appended ||= didAppend;
|
|
2721
|
-
}
|
|
2722
|
-
ownAssistant(group.assistantKey, true);
|
|
2723
|
-
}
|
|
2724
|
-
pendingTools = void 0;
|
|
2725
|
-
for (const write of deferredUserWrites.splice(0)) {
|
|
2726
|
-
const outcome = await append(write);
|
|
2727
|
-
if (!outcome) replayInvalid = true;
|
|
2728
|
-
const didAppend = accept(outcome);
|
|
2729
|
-
appended ||= didAppend;
|
|
2730
|
-
}
|
|
2731
|
-
await publish(appended);
|
|
2732
|
-
});
|
|
2733
|
-
},
|
|
2734
|
-
barrier,
|
|
2735
|
-
hasFailed: () => firstFailure !== void 0,
|
|
2736
|
-
snapshot: () => ({
|
|
2737
|
-
assistantTranscriptOwned,
|
|
2738
|
-
assistantTranscriptIdempotencyKey,
|
|
2739
|
-
initialSdkUserValidated,
|
|
2740
|
-
messagesSnapshot: [...messagesSnapshot],
|
|
2741
|
-
replayInvalid
|
|
2742
|
-
})
|
|
2743
|
-
};
|
|
2744
|
-
}
|
|
2745
|
-
function resolveTranscriptTarget(attempt) {
|
|
2746
|
-
const sessionId = readString(attempt.sessionTarget?.sessionId);
|
|
2747
|
-
const sessionKey = readString(attempt.sessionTarget?.sessionKey);
|
|
2748
|
-
const storePath = readString(attempt.sessionTarget?.storePath);
|
|
2749
|
-
if (!sessionId || !sessionKey || !storePath) {
|
|
2750
|
-
const error = /* @__PURE__ */ new Error("[copilot-attempt] canonical transcript persistence requires an exact runtime session target");
|
|
2751
|
-
error.code = "transcript_persistence_failed";
|
|
2752
|
-
throw error;
|
|
2753
|
-
}
|
|
2754
|
-
const agentId = readString(attempt.sessionTarget?.agentId ?? attempt.agentId);
|
|
2755
|
-
return {
|
|
2756
|
-
sessionId,
|
|
2757
|
-
sessionKey,
|
|
2758
|
-
storePath,
|
|
2759
|
-
...agentId ? { agentId } : {}
|
|
2760
|
-
};
|
|
2761
|
-
}
|
|
2762
|
-
function readAssistantToolCallIds(message) {
|
|
2763
|
-
return message.role === "assistant" ? message.content.flatMap((part) => part.type === "toolCall" ? [part.id] : []) : [];
|
|
2764
|
-
}
|
|
2765
|
-
function isCompatibleSingletonRewrite(original, prepared) {
|
|
2766
|
-
return original.role === prepared.role && (original.role !== "assistant" || JSON.stringify(readAssistantToolCallIds(original)) === JSON.stringify(readAssistantToolCallIds(prepared)));
|
|
2767
|
-
}
|
|
2768
|
-
function projectReplayPayload(message) {
|
|
2769
|
-
switch (message.role) {
|
|
2770
|
-
case "user": return {
|
|
2771
|
-
role: message.role,
|
|
2772
|
-
content: message.content
|
|
2773
|
-
};
|
|
2774
|
-
case "assistant": return {
|
|
2775
|
-
role: message.role,
|
|
2776
|
-
content: message.content,
|
|
2777
|
-
api: message.api,
|
|
2778
|
-
model: message.model,
|
|
2779
|
-
provider: message.provider,
|
|
2780
|
-
stopReason: message.stopReason
|
|
2781
|
-
};
|
|
2782
|
-
case "toolResult": return {
|
|
2783
|
-
role: message.role,
|
|
2784
|
-
content: message.content,
|
|
2785
|
-
isError: message.isError,
|
|
2786
|
-
toolCallId: message.toolCallId,
|
|
2787
|
-
toolName: message.toolName
|
|
2788
|
-
};
|
|
2789
|
-
}
|
|
2790
|
-
}
|
|
2791
|
-
function readIdempotencyKey(message) {
|
|
2792
|
-
const key = message.idempotencyKey;
|
|
2793
|
-
return typeof key === "string" && key ? key : void 0;
|
|
2794
|
-
}
|
|
2795
|
-
function isCurrentJournalIdentity(key, params) {
|
|
2796
|
-
return key === `${params.attempt.runId}:user` || key.startsWith(`copilot-sdk:${params.sdkSessionId}:`);
|
|
2797
|
-
}
|
|
2798
|
-
function isCompleteToolGroup(messages, order) {
|
|
2799
|
-
const [assistant, ...results] = messages;
|
|
2800
|
-
return assistant?.role === "assistant" && JSON.stringify(readAssistantToolCallIds(assistant)) === JSON.stringify(order) && results.length === order.length && results.every((message, index) => message.role === "toolResult" && message.toolCallId === order[index]);
|
|
2801
|
-
}
|
|
2802
|
-
function isSameUserTurn(candidate, current, currentRunUserKey) {
|
|
2803
|
-
if (candidate?.role !== "user" || !current) return false;
|
|
2804
|
-
if (candidate === current) return true;
|
|
2805
|
-
const candidateKey = candidate.idempotencyKey;
|
|
2806
|
-
const currentKey = current.idempotencyKey;
|
|
2807
|
-
if (typeof candidateKey === "string" || typeof currentKey === "string") {
|
|
2808
|
-
if (typeof candidateKey === "string" && typeof currentKey === "string") return candidateKey === currentKey;
|
|
2809
|
-
if (typeof candidateKey !== "string" || typeof currentKey === "string" || !candidateKey.startsWith("copilot:") && candidateKey !== currentRunUserKey) return false;
|
|
2810
|
-
}
|
|
2811
|
-
return candidate.timestamp === current.timestamp && userText(candidate.content) === userText(current.content);
|
|
2812
|
-
}
|
|
2813
|
-
function userText(content) {
|
|
2814
|
-
if (typeof content === "string") return content;
|
|
2815
|
-
if (Array.isArray(content) && content.length === 1) {
|
|
2816
|
-
const part = content[0];
|
|
2817
|
-
if (part?.type === "text" && typeof part.text === "string") return part.text;
|
|
2818
|
-
}
|
|
2819
|
-
return JSON.stringify(content) ?? "";
|
|
2820
|
-
}
|
|
2821
|
-
function readString(value) {
|
|
2822
|
-
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
2823
|
-
}
|
|
2824
|
-
//#endregion
|
|
2825
|
-
//#region extensions/copilot/src/native-subagent-task-mirror.ts
|
|
2826
|
-
const COPILOT_NATIVE_SUBAGENT_TASK_KIND = "copilot-native";
|
|
2827
|
-
const COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX = "copilot-agent:";
|
|
2828
|
-
function createCopilotNativeSubagentTaskMirror(params) {
|
|
2829
|
-
if (!params.scope) return;
|
|
2830
|
-
return new CopilotNativeSubagentTaskMirror({
|
|
2831
|
-
agentId: params.agentId,
|
|
2832
|
-
now: params.now
|
|
2833
|
-
}, createAgentHarnessTaskRuntime({
|
|
2834
|
-
runtime: "subagent",
|
|
2835
|
-
taskKind: COPILOT_NATIVE_SUBAGENT_TASK_KIND,
|
|
2836
|
-
scope: params.scope,
|
|
2837
|
-
runIdPrefix: COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX
|
|
2838
|
-
}));
|
|
2839
|
-
}
|
|
2840
|
-
var CopilotNativeSubagentTaskMirror = class {
|
|
2841
|
-
constructor(params, runtime) {
|
|
2842
|
-
this.params = params;
|
|
2843
|
-
this.runtime = runtime;
|
|
2844
|
-
this.runIdByAgentId = /* @__PURE__ */ new Map();
|
|
2845
|
-
this.runIdByToolCallId = /* @__PURE__ */ new Map();
|
|
2846
|
-
this.terminalRunIds = /* @__PURE__ */ new Set();
|
|
2847
|
-
this.activeRunIds = /* @__PURE__ */ new Set();
|
|
2848
|
-
this.now = params.now ?? Date.now;
|
|
1701
|
+
//#endregion
|
|
1702
|
+
//#region extensions/copilot/src/attempt.ts
|
|
1703
|
+
const BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS = 5e3;
|
|
1704
|
+
const COPILOT_ASK_USER_AVAILABLE_TOOLS = ["builtin:ask_user"];
|
|
1705
|
+
async function runCopilotAgentEndHook(params, hookParams) {
|
|
1706
|
+
if (!params.messageChannel && !params.messageProvider) {
|
|
1707
|
+
await awaitAgentEndSideEffects(hookParams);
|
|
1708
|
+
return;
|
|
2849
1709
|
}
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
1710
|
+
runAgentEndSideEffects(hookParams);
|
|
1711
|
+
}
|
|
1712
|
+
async function finalizeCopilotAttempt(params, result, ctx, attemptStartedAt, now) {
|
|
1713
|
+
await runCopilotAgentEndHook(params, {
|
|
1714
|
+
event: {
|
|
1715
|
+
messages: result.messagesSnapshot,
|
|
1716
|
+
success: !result.aborted && !result.promptError && !result.timedOut,
|
|
1717
|
+
...result.promptError ? { error: toError(result.promptError).message } : result.timedOut ? { error: "Copilot SDK turn timed out." } : {},
|
|
1718
|
+
durationMs: now() - attemptStartedAt
|
|
1719
|
+
},
|
|
1720
|
+
ctx
|
|
1721
|
+
});
|
|
1722
|
+
return result;
|
|
1723
|
+
}
|
|
1724
|
+
async function awaitDeferredCleanupCompletionOrAbort(params) {
|
|
1725
|
+
const awaitCompletion = async () => {
|
|
1726
|
+
if (params.awaitSessionIdle) await params.bridge.awaitSessionIdle();
|
|
1727
|
+
await params.bridge.awaitCompactionCompletion();
|
|
1728
|
+
};
|
|
1729
|
+
if (!params.abortSignal) {
|
|
1730
|
+
await awaitCompletion();
|
|
1731
|
+
return "completed";
|
|
2863
1732
|
}
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
1733
|
+
if (params.abortSignal.aborted) return "aborted";
|
|
1734
|
+
let resolveAbort = () => void 0;
|
|
1735
|
+
const aborted = new Promise((resolve) => {
|
|
1736
|
+
resolveAbort = () => resolve("aborted");
|
|
1737
|
+
});
|
|
1738
|
+
params.abortSignal.addEventListener("abort", resolveAbort, { once: true });
|
|
1739
|
+
try {
|
|
1740
|
+
return await Promise.race([awaitCompletion().then(() => "completed"), aborted]);
|
|
1741
|
+
} finally {
|
|
1742
|
+
params.abortSignal.removeEventListener("abort", resolveAbort);
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
function deferBackgroundCompactionCleanup(params) {
|
|
1746
|
+
return (async () => {
|
|
1747
|
+
let outcome = "deadline";
|
|
1748
|
+
try {
|
|
1749
|
+
outcome = await awaitDeferredCleanupBeforeDeadline({
|
|
1750
|
+
abortSignal: params.abortSignal,
|
|
1751
|
+
awaitSessionIdle: params.awaitSessionIdle,
|
|
1752
|
+
bridge: params.bridge,
|
|
1753
|
+
timeoutMs: params.timeoutMs
|
|
2876
1754
|
});
|
|
1755
|
+
} catch {} finally {
|
|
1756
|
+
if (outcome !== "completed") {
|
|
1757
|
+
await cancelBackgroundCompactionBeforeTeardown(params.session);
|
|
1758
|
+
params.bridge.settleCompactionWait();
|
|
1759
|
+
}
|
|
1760
|
+
params.finalizeNativeSubagents?.();
|
|
1761
|
+
params.bridge.detach();
|
|
1762
|
+
try {
|
|
1763
|
+
await params.session.disconnect();
|
|
1764
|
+
} catch {}
|
|
1765
|
+
params.cleanupToolBridge?.();
|
|
1766
|
+
await params.cleanupByokProxy?.();
|
|
1767
|
+
if (outcome !== "completed" && params.sdkSessionId) try {
|
|
1768
|
+
await params.handle.client.deleteSession(params.sdkSessionId);
|
|
1769
|
+
} catch {}
|
|
1770
|
+
try {
|
|
1771
|
+
await params.pool.release(params.handle);
|
|
1772
|
+
} catch {}
|
|
2877
1773
|
}
|
|
2878
|
-
|
|
2879
|
-
}
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
notifyPolicy: "silent",
|
|
2893
|
-
deliveryStatus: "not_applicable",
|
|
2894
|
-
preferMetadata: true,
|
|
2895
|
-
startedAt: eventAt,
|
|
2896
|
-
lastEventAt: eventAt,
|
|
2897
|
-
progressSummary: "Copilot native subagent started."
|
|
2898
|
-
})) return;
|
|
2899
|
-
if (agentId) this.runIdByAgentId.set(agentId, runId);
|
|
2900
|
-
else this.runIdByToolCallId.set(toolCallId, runId);
|
|
2901
|
-
this.terminalRunIds.delete(runId);
|
|
2902
|
-
this.activeRunIds.add(runId);
|
|
1774
|
+
return outcome;
|
|
1775
|
+
})();
|
|
1776
|
+
}
|
|
1777
|
+
async function cancelBackgroundCompactionBeforeTeardown(session) {
|
|
1778
|
+
const cancelBackgroundCompaction = session.rpc?.history?.cancelBackgroundCompaction;
|
|
1779
|
+
if (!cancelBackgroundCompaction) return;
|
|
1780
|
+
let timeoutId;
|
|
1781
|
+
const deadline = new Promise((resolve) => {
|
|
1782
|
+
timeoutId = setTimeout(resolve, BACKGROUND_COMPACTION_CANCEL_TIMEOUT_MS);
|
|
1783
|
+
});
|
|
1784
|
+
try {
|
|
1785
|
+
await Promise.race([Promise.resolve().then(() => cancelBackgroundCompaction()).catch(() => void 0), deadline]);
|
|
1786
|
+
} finally {
|
|
1787
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
2903
1788
|
}
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
progressSummary: "Copilot native subagent completed.",
|
|
2915
|
-
terminalSummary: buildCompletionSummary(event)
|
|
2916
|
-
});
|
|
1789
|
+
}
|
|
1790
|
+
async function awaitDeferredCleanupBeforeDeadline(params) {
|
|
1791
|
+
let timeoutId;
|
|
1792
|
+
const deadline = new Promise((resolve) => {
|
|
1793
|
+
timeoutId = setTimeout(() => resolve("deadline"), params.timeoutMs);
|
|
1794
|
+
});
|
|
1795
|
+
try {
|
|
1796
|
+
return await Promise.race([awaitDeferredCleanupCompletionOrAbort(params), deadline]);
|
|
1797
|
+
} finally {
|
|
1798
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
2917
1799
|
}
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
1800
|
+
}
|
|
1801
|
+
async function runCopilotAttempt(params, deps) {
|
|
1802
|
+
const now = deps.now ?? Date.now;
|
|
1803
|
+
const attemptStartedAt = now();
|
|
1804
|
+
const input = params;
|
|
1805
|
+
const createToolBridge = deps.createToolBridge ?? createCopilotToolBridge;
|
|
1806
|
+
const messages = getMessagesSnapshotInput(input);
|
|
1807
|
+
const modelRef = resolveModelRef(input);
|
|
1808
|
+
const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
|
|
1809
|
+
const sandboxSessionKey = readString(input.sandboxSessionKey) ?? readString(input.sessionKey) ?? readString(input.sessionId);
|
|
1810
|
+
const { sessionAgentId } = resolveSessionAgentIds({
|
|
1811
|
+
sessionKey: readString(input.sessionKey),
|
|
1812
|
+
config: input.config,
|
|
1813
|
+
agentId: readString(params.agentId)
|
|
1814
|
+
});
|
|
1815
|
+
const hookContextWindowFields = {
|
|
1816
|
+
...input.contextWindowInfo?.tokens ? { contextTokenBudget: input.contextWindowInfo.tokens } : input.contextTokenBudget ? { contextTokenBudget: input.contextTokenBudget } : {},
|
|
1817
|
+
...input.contextWindowInfo?.source ? { contextWindowSource: input.contextWindowInfo.source } : {},
|
|
1818
|
+
...input.contextWindowInfo?.referenceTokens ? { contextWindowReferenceTokens: input.contextWindowInfo.referenceTokens } : {}
|
|
1819
|
+
};
|
|
1820
|
+
const hookContext = {
|
|
1821
|
+
runId: input.runId,
|
|
1822
|
+
jobId: input.jobId,
|
|
1823
|
+
agentId: sessionAgentId,
|
|
1824
|
+
sessionKey: sandboxSessionKey,
|
|
1825
|
+
sessionId: input.sessionId,
|
|
1826
|
+
workspaceDir: resolvedWorkspaceForSandbox,
|
|
1827
|
+
modelProviderId: modelRef.provider,
|
|
1828
|
+
modelId: modelRef.id,
|
|
1829
|
+
trigger: input.trigger,
|
|
1830
|
+
...input.config ? { config: input.config } : {},
|
|
1831
|
+
...hookContextWindowFields,
|
|
1832
|
+
...buildAgentHookContextChannelFields(input)
|
|
1833
|
+
};
|
|
1834
|
+
const finishAttempt = (result) => finalizeCopilotAttempt(input, result, hookContext, attemptStartedAt, now);
|
|
1835
|
+
if (params.abortSignal?.aborted) return finishAttempt(createResult(input, {
|
|
1836
|
+
aborted: true,
|
|
1837
|
+
externalAbort: true,
|
|
1838
|
+
messagesSnapshot: messages,
|
|
1839
|
+
now,
|
|
1840
|
+
promptError: void 0,
|
|
1841
|
+
sdkSessionId: void 0,
|
|
1842
|
+
sessionIdUsed: input.sessionId
|
|
1843
|
+
}));
|
|
1844
|
+
try {
|
|
1845
|
+
resolveCopilotProvider({
|
|
1846
|
+
model: modelRef,
|
|
1847
|
+
resolvedApiKey: readString(params.resolvedApiKey),
|
|
1848
|
+
authProfileId: readString(params.authProfileId)
|
|
2931
1849
|
});
|
|
1850
|
+
} catch (error) {
|
|
1851
|
+
return finishAttempt(createResult(input, {
|
|
1852
|
+
messagesSnapshot: messages,
|
|
1853
|
+
now,
|
|
1854
|
+
promptError: createPromptError("model_not_supported", toError(error).message, error),
|
|
1855
|
+
sdkSessionId: void 0,
|
|
1856
|
+
sessionIdUsed: input.sessionId
|
|
1857
|
+
}));
|
|
2932
1858
|
}
|
|
2933
|
-
resolveRunId(event) {
|
|
2934
|
-
const agentId = event.agentId?.trim();
|
|
2935
|
-
if (agentId) {
|
|
2936
|
-
const existing = this.runIdByAgentId.get(agentId);
|
|
2937
|
-
if (existing) return existing;
|
|
2938
|
-
}
|
|
2939
|
-
const existing = this.runIdByToolCallId.get(event.data.toolCallId);
|
|
2940
|
-
if (existing) return existing;
|
|
2941
|
-
const identity = agentId || event.data.toolCallId.trim();
|
|
2942
|
-
return `${COPILOT_NATIVE_SUBAGENT_RUN_ID_PREFIX}${identity}`;
|
|
2943
|
-
}
|
|
2944
|
-
};
|
|
2945
|
-
function buildCompletionSummary(event) {
|
|
2946
|
-
const details = [event.data.totalToolCalls !== void 0 ? `${event.data.totalToolCalls} tool calls` : void 0, event.data.totalTokens !== void 0 ? `${event.data.totalTokens} tokens` : void 0].filter((value) => value !== void 0);
|
|
2947
|
-
return details.length > 0 ? `Copilot native subagent completed (${details.join(", ")}).` : "Copilot native subagent completed.";
|
|
2948
|
-
}
|
|
2949
|
-
//#endregion
|
|
2950
|
-
//#region extensions/copilot/src/attempt-execution.ts
|
|
2951
|
-
async function runCopilotExecution(context) {
|
|
2952
|
-
const { params, deps, now, attemptStartedAt, settledToolFinalization, input, createToolBridge, ringZeroSystemAgentRun, messages, modelRef, resolvedWorkspaceForSandbox, sandboxSessionKey, sessionAgentId, hookContextWindowFields, hookContext, finishAttempt, settledFinalizationSessionId } = context;
|
|
2953
1859
|
let abortRequested = false;
|
|
2954
1860
|
let aborted = false;
|
|
2955
1861
|
let externalAbort = false;
|
|
2956
1862
|
let settled = false;
|
|
2957
1863
|
let sentTurnStarted = false;
|
|
2958
|
-
let settledFinalizationAssistantCompleted = false;
|
|
2959
1864
|
let timedOutDuringCompaction = false;
|
|
2960
1865
|
let timedOut = false;
|
|
2961
1866
|
let promptError;
|
|
2962
1867
|
let sdkSessionId;
|
|
2963
1868
|
let sessionIdUsed = input.sessionId;
|
|
2964
|
-
let nativeSessionCreatedFresh = false;
|
|
2965
|
-
let nativeSessionHistoryValidated = false;
|
|
2966
1869
|
let disconnectError;
|
|
2967
1870
|
let handle;
|
|
2968
1871
|
let session;
|
|
2969
1872
|
let bridge;
|
|
2970
|
-
let transcriptJournal;
|
|
2971
1873
|
const nativeSubagentTaskMirror = createCopilotNativeSubagentTaskMirror({
|
|
2972
1874
|
agentId: sessionAgentId,
|
|
2973
1875
|
now,
|
|
@@ -2980,13 +1882,6 @@ async function runCopilotExecution(context) {
|
|
|
2980
1882
|
let downgradedFromResume = false;
|
|
2981
1883
|
let resumeFailureRecovered = false;
|
|
2982
1884
|
let yieldDetected = false;
|
|
2983
|
-
let lastToolError;
|
|
2984
|
-
const hostObserveToolTerminal = input.observeToolTerminal;
|
|
2985
|
-
const observeToolTerminal = hostObserveToolTerminal ? (observation) => {
|
|
2986
|
-
const terminal = hostObserveToolTerminal(observation);
|
|
2987
|
-
lastToolError = terminal.lastToolError;
|
|
2988
|
-
return terminal;
|
|
2989
|
-
} : void 0;
|
|
2990
1885
|
const markExternalAbort = () => {
|
|
2991
1886
|
abortRequested = true;
|
|
2992
1887
|
externalAbort = true;
|
|
@@ -3001,15 +1896,17 @@ async function runCopilotExecution(context) {
|
|
|
3001
1896
|
abortActiveSession();
|
|
3002
1897
|
};
|
|
3003
1898
|
params.abortSignal?.addEventListener("abort", onAbort, { once: true });
|
|
1899
|
+
const resolveSandbox = deps.resolveSandboxContextOverride ?? resolveSandboxContext;
|
|
3004
1900
|
let sandbox = null;
|
|
3005
1901
|
let effectiveWorkspaceDir = resolvedWorkspaceForSandbox;
|
|
3006
1902
|
if (resolvedWorkspaceForSandbox) try {
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
resolvedWorkspaceForSandbox
|
|
3011
|
-
|
|
3012
|
-
|
|
1903
|
+
sandbox = await resolveSandbox({
|
|
1904
|
+
config: input.config,
|
|
1905
|
+
sessionKey: sandboxSessionKey,
|
|
1906
|
+
workspaceDir: resolvedWorkspaceForSandbox
|
|
1907
|
+
});
|
|
1908
|
+
effectiveWorkspaceDir = sandbox?.enabled ? sandbox.workspaceAccess === "rw" ? resolvedWorkspaceForSandbox : sandbox.workspaceDir : resolvedWorkspaceForSandbox;
|
|
1909
|
+
if (sandbox?.enabled && effectiveWorkspaceDir && effectiveWorkspaceDir !== resolvedWorkspaceForSandbox) await fsp.mkdir(effectiveWorkspaceDir, { recursive: true });
|
|
3013
1910
|
} catch (error) {
|
|
3014
1911
|
settled = true;
|
|
3015
1912
|
params.abortSignal?.removeEventListener("abort", onAbort);
|
|
@@ -3025,7 +1922,7 @@ async function runCopilotExecution(context) {
|
|
|
3025
1922
|
return finishAttempt(createResult(input, {
|
|
3026
1923
|
messagesSnapshot: messages,
|
|
3027
1924
|
now,
|
|
3028
|
-
promptError: createPromptError
|
|
1925
|
+
promptError: createPromptError("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toError(error).message}`, error),
|
|
3029
1926
|
sdkSessionId: void 0,
|
|
3030
1927
|
sessionIdUsed: input.sessionId
|
|
3031
1928
|
}));
|
|
@@ -3038,7 +1935,7 @@ async function runCopilotExecution(context) {
|
|
|
3038
1935
|
return finishAttempt(createResult(input, {
|
|
3039
1936
|
messagesSnapshot: messages,
|
|
3040
1937
|
now,
|
|
3041
|
-
promptError: createPromptError
|
|
1938
|
+
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"),
|
|
3042
1939
|
sdkSessionId: void 0,
|
|
3043
1940
|
sessionIdUsed: input.sessionId
|
|
3044
1941
|
}));
|
|
@@ -3052,14 +1949,7 @@ async function runCopilotExecution(context) {
|
|
|
3052
1949
|
sandbox,
|
|
3053
1950
|
resolvedWorkspace: resolvedWorkspaceForSandbox
|
|
3054
1951
|
}) : void 0;
|
|
3055
|
-
const
|
|
3056
|
-
const poolAcquire = settledToolFinalization ? {
|
|
3057
|
-
...resolvedPoolAcquire,
|
|
3058
|
-
options: {
|
|
3059
|
-
...resolvedPoolAcquire.options,
|
|
3060
|
-
mode: "empty"
|
|
3061
|
-
}
|
|
3062
|
-
} : resolvedPoolAcquire;
|
|
1952
|
+
const poolAcquire = resolvePoolAcquire(input);
|
|
3063
1953
|
let byokProxy;
|
|
3064
1954
|
try {
|
|
3065
1955
|
byokProxy = await createCopilotByokProxy(poolAcquire.provider);
|
|
@@ -3067,7 +1957,7 @@ async function runCopilotExecution(context) {
|
|
|
3067
1957
|
return finishAttempt(createResult(input, {
|
|
3068
1958
|
messagesSnapshot: messages,
|
|
3069
1959
|
now,
|
|
3070
|
-
promptError: createPromptError
|
|
1960
|
+
promptError: createPromptError("model_not_supported", toError(error).message, error),
|
|
3071
1961
|
sdkSessionId: void 0,
|
|
3072
1962
|
sessionIdUsed: input.sessionId
|
|
3073
1963
|
}));
|
|
@@ -3075,30 +1965,23 @@ async function runCopilotExecution(context) {
|
|
|
3075
1965
|
const cleanupByokProxy = byokProxy?.close;
|
|
3076
1966
|
const sessionProvider = byokProxy?.provider ?? poolAcquire.provider;
|
|
3077
1967
|
const sessionRef = { current: void 0 };
|
|
3078
|
-
const computerContextEpoch = { value: 0 };
|
|
3079
|
-
let codeModeEngaged;
|
|
3080
1968
|
try {
|
|
3081
|
-
let sdkTools
|
|
3082
|
-
|
|
3083
|
-
if (!settledToolFinalization) try {
|
|
1969
|
+
let sdkTools;
|
|
1970
|
+
try {
|
|
3084
1971
|
const toolBridge = await createToolBridge({
|
|
3085
1972
|
allowModelTools: poolAcquire.provider.mode === "byok",
|
|
3086
1973
|
modelProvider: modelRef.provider,
|
|
3087
1974
|
modelId: modelRef.id,
|
|
3088
|
-
agentId: readString
|
|
3089
|
-
sessionId: readString
|
|
3090
|
-
sessionKey: readString
|
|
3091
|
-
agentDir: readString
|
|
1975
|
+
agentId: readString(params.agentId) ?? "copilot",
|
|
1976
|
+
sessionId: readString(input.sessionId) ?? "copilot-session",
|
|
1977
|
+
sessionKey: readString(input.sessionKey),
|
|
1978
|
+
agentDir: readString(input.agentDir),
|
|
3092
1979
|
workspaceDir: effectiveWorkspaceDir,
|
|
3093
1980
|
cwd: effectiveCwd,
|
|
3094
1981
|
sandbox,
|
|
3095
1982
|
spawnWorkspaceDir: sandboxAwareSpawnWorkspaceDir,
|
|
3096
1983
|
abortSignal: params.abortSignal,
|
|
3097
|
-
attemptParams:
|
|
3098
|
-
...input,
|
|
3099
|
-
observeToolTerminal
|
|
3100
|
-
} : input,
|
|
3101
|
-
computerContextEpoch,
|
|
1984
|
+
attemptParams: input,
|
|
3102
1985
|
sessionRef,
|
|
3103
1986
|
onYieldDetected: () => {
|
|
3104
1987
|
yieldDetected = true;
|
|
@@ -3118,68 +2001,88 @@ async function runCopilotExecution(context) {
|
|
|
3118
2001
|
})
|
|
3119
2002
|
});
|
|
3120
2003
|
cleanupToolBridge = toolBridge.cleanup;
|
|
3121
|
-
codeModeEngaged = toolBridge.codeModeEngaged;
|
|
3122
2004
|
sdkTools = toolBridge.sdkTools;
|
|
3123
|
-
resultContentSourceByToolName = new Map(toolBridge.sourceTools.flatMap((tool) => tool.resultContentSource ? [[tool.name, tool.resultContentSource]] : []));
|
|
3124
2005
|
} catch (error) {
|
|
3125
2006
|
return finishAttempt(createResult(input, {
|
|
3126
2007
|
messagesSnapshot: messages,
|
|
3127
2008
|
now,
|
|
3128
|
-
promptError: createPromptError
|
|
2009
|
+
promptError: createPromptError("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toError(error).message}`, error),
|
|
3129
2010
|
sdkSessionId: void 0,
|
|
3130
2011
|
sessionIdUsed: input.sessionId
|
|
3131
2012
|
}));
|
|
3132
2013
|
}
|
|
3133
2014
|
handle = await deps.pool.acquire(poolAcquire.key, poolAcquire.options);
|
|
3134
2015
|
const client = handle.client;
|
|
3135
|
-
const
|
|
2016
|
+
const originalDeveloperInstructions = createSystemMessageContent(input, (await resolveCopilotWorkspaceBootstrapContext({
|
|
3136
2017
|
attempt: input,
|
|
3137
|
-
byokProxy,
|
|
3138
|
-
effectiveCwd,
|
|
3139
2018
|
effectiveWorkspaceDir,
|
|
3140
|
-
|
|
3141
|
-
|
|
2019
|
+
warn: (message) => console.warn(message)
|
|
2020
|
+
})).instructions) ?? "";
|
|
2021
|
+
const promptBuild = isRawCopilotModelRun(input) ? {
|
|
2022
|
+
prompt: input.prompt,
|
|
2023
|
+
developerInstructions: originalDeveloperInstructions
|
|
2024
|
+
} : await resolveAgentHarnessBeforePromptBuildResult({
|
|
2025
|
+
prompt: input.prompt,
|
|
2026
|
+
developerInstructions: originalDeveloperInstructions,
|
|
3142
2027
|
messages,
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
2028
|
+
ctx: hookContext,
|
|
2029
|
+
toolAuthority: {
|
|
2030
|
+
activeToolNames: sdkTools.map((tool) => tool.name),
|
|
2031
|
+
signal: params.abortSignal
|
|
2032
|
+
},
|
|
2033
|
+
bootstrapContextRunKind: input.bootstrapContextRunKind,
|
|
2034
|
+
..."beforeAgentStartResult" in input ? { beforeAgentStartResult: input.beforeAgentStartResult } : {}
|
|
2035
|
+
});
|
|
2036
|
+
const attemptInput = promptBuild.prompt === input.prompt ? input : {
|
|
2037
|
+
...input,
|
|
2038
|
+
prompt: promptBuild.prompt
|
|
2039
|
+
};
|
|
2040
|
+
let promptImagesCount = 0;
|
|
2041
|
+
const emitLlmInput = (prompt, additionalContext) => {
|
|
2042
|
+
runAgentHarnessLlmInputHook({
|
|
2043
|
+
event: {
|
|
2044
|
+
runId: input.runId,
|
|
2045
|
+
sessionId: input.sessionId,
|
|
2046
|
+
provider: modelRef.provider,
|
|
2047
|
+
model: modelRef.id,
|
|
2048
|
+
...promptBuild.developerInstructions ? { systemPrompt: promptBuild.developerInstructions } : {},
|
|
2049
|
+
prompt: additionalContext ? `${prompt}\n\n${additionalContext}` : prompt,
|
|
2050
|
+
historyMessages: [],
|
|
2051
|
+
imagesCount: promptImagesCount,
|
|
2052
|
+
tools: sdkTools
|
|
2053
|
+
},
|
|
2054
|
+
ctx: hookContext
|
|
2055
|
+
});
|
|
2056
|
+
};
|
|
2057
|
+
const hasNativePromptHook = Boolean(attemptInput.hooksConfig?.onUserPromptSubmitted);
|
|
2058
|
+
const userInputBridge = createCopilotUserInputBridge({
|
|
2059
|
+
paramsForRun: attemptInput,
|
|
3149
2060
|
signal: params.abortSignal
|
|
3150
2061
|
});
|
|
3151
|
-
const { attemptInput, compactionSessionConfig, emitLlmInput, hasNativePromptHook, sessionConfig, userInputBridge } = sessionSetup;
|
|
3152
2062
|
userInputBridgeRef = userInputBridge;
|
|
2063
|
+
const sessionConfig = createSessionConfig(attemptInput, modelRef.id, sdkTools, poolAcquire.auth, sessionProvider, promptBuild.developerInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, userInputBridge.onUserInputRequest, hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0);
|
|
2064
|
+
const compactionSessionConfig = byokProxy ? createSessionConfig(attemptInput, modelRef.id, sdkTools, poolAcquire.auth, poolAcquire.provider, promptBuild.developerInstructions || void 0, effectiveWorkspaceDir, effectiveCwd, userInputBridge.onUserInputRequest, hasNativePromptHook ? { onUserPromptSubmitted: ({ additionalContext, prompt }) => emitLlmInput(prompt, additionalContext) } : void 0) : sessionConfig;
|
|
3153
2065
|
const replayDecision = decideReplayAction({
|
|
3154
2066
|
sdkSessionId: input.initialReplayState?.sdkSessionId,
|
|
3155
2067
|
replayInvalid: input.initialReplayState?.replayInvalid
|
|
3156
2068
|
});
|
|
3157
2069
|
downgradedFromResume = replayDecision.downgradedFromResume;
|
|
3158
|
-
const resumeSessionId =
|
|
2070
|
+
const resumeSessionId = replayDecision.action === "resume" ? replayDecision.sdkSessionId : void 0;
|
|
3159
2071
|
if (resumeSessionId) try {
|
|
3160
2072
|
session = await client.resumeSession(resumeSessionId, {
|
|
3161
2073
|
...sessionConfig,
|
|
3162
2074
|
continuePendingWork: false
|
|
3163
2075
|
});
|
|
3164
|
-
nativeSessionHistoryValidated = input.initialReplayState?.journalValidated === true;
|
|
3165
2076
|
} catch (error) {
|
|
3166
|
-
if (settledToolFinalization) throw createPromptError$1("settled_finalization_resume_failed", `[copilot-attempt] settled tool finalization could not resume the existing Copilot SDK session: ${toError$1(error).message}`, error);
|
|
3167
2077
|
if (!classifyResumeFailure(error).recoverable) throw error;
|
|
3168
2078
|
resumeFailureRecovered = true;
|
|
3169
2079
|
session = await client.createSession(sessionConfig);
|
|
3170
|
-
nativeSessionCreatedFresh = true;
|
|
3171
|
-
nativeSessionHistoryValidated = true;
|
|
3172
|
-
}
|
|
3173
|
-
else {
|
|
3174
|
-
session = await client.createSession(sessionConfig);
|
|
3175
|
-
nativeSessionCreatedFresh = true;
|
|
3176
|
-
nativeSessionHistoryValidated = true;
|
|
3177
2080
|
}
|
|
2081
|
+
else session = await client.createSession(sessionConfig);
|
|
3178
2082
|
sessionRef.current = session;
|
|
3179
|
-
sdkSessionId =
|
|
3180
|
-
if (!sdkSessionId) throw createPromptError$1("transcript_persistence_failed", "[copilot-attempt] canonical transcript persistence requires the Copilot SDK session id");
|
|
2083
|
+
sdkSessionId = readSessionId(session) ?? (resumeFailureRecovered ? void 0 : resumeSessionId);
|
|
3181
2084
|
sessionIdUsed = sdkSessionId ?? input.sessionId;
|
|
3182
|
-
if (sdkSessionId && deps.onSessionEstablished
|
|
2085
|
+
if (sdkSessionId && deps.onSessionEstablished) try {
|
|
3183
2086
|
deps.onSessionEstablished({
|
|
3184
2087
|
compactionSessionConfig,
|
|
3185
2088
|
sdkSessionId,
|
|
@@ -3188,17 +2091,11 @@ async function runCopilotExecution(context) {
|
|
|
3188
2091
|
});
|
|
3189
2092
|
} catch {}
|
|
3190
2093
|
bridge = attachEventBridge(session, {
|
|
3191
|
-
onAssistantDelta:
|
|
3192
|
-
onAgentEvent:
|
|
2094
|
+
onAssistantDelta: input.onAssistantDelta,
|
|
2095
|
+
onAgentEvent: input.onAgentEvent,
|
|
3193
2096
|
onNativeSubagentEvent: (event) => nativeSubagentTaskMirror?.handleEvent(event),
|
|
3194
|
-
onContextCompacted: () => {
|
|
3195
|
-
computerContextEpoch.value += 1;
|
|
3196
|
-
delete computerContextEpoch.frameToolCallId;
|
|
3197
|
-
delete computerContextEpoch.frameImageIdentity;
|
|
3198
|
-
},
|
|
3199
2097
|
onCompactionStart: async () => {
|
|
3200
|
-
|
|
3201
|
-
const sessionFile = readString$3(input.sessionFile);
|
|
2098
|
+
const sessionFile = readString(input.sessionFile);
|
|
3202
2099
|
if (!sessionFile) return;
|
|
3203
2100
|
await runAgentHarnessBeforeCompactionHook({
|
|
3204
2101
|
sessionFile,
|
|
@@ -3206,8 +2103,7 @@ async function runCopilotExecution(context) {
|
|
|
3206
2103
|
});
|
|
3207
2104
|
},
|
|
3208
2105
|
onCompactionComplete: async ({ messagesRemoved, success }) => {
|
|
3209
|
-
|
|
3210
|
-
const sessionFile = readString$3(input.sessionFile);
|
|
2106
|
+
const sessionFile = readString(input.sessionFile);
|
|
3211
2107
|
if (!success || !sessionFile) return;
|
|
3212
2108
|
await runAgentHarnessAfterCompactionHook({
|
|
3213
2109
|
sessionFile,
|
|
@@ -3216,27 +2112,28 @@ async function runCopilotExecution(context) {
|
|
|
3216
2112
|
});
|
|
3217
2113
|
},
|
|
3218
2114
|
getSdkSessionId: () => sdkSessionId,
|
|
3219
|
-
isAborted: () => aborted
|
|
3220
|
-
transcriptProjection: {
|
|
3221
|
-
journal: transcriptJournal = createAttemptTranscriptJournal({
|
|
3222
|
-
abortSession: () => session?.abort() ?? Promise.resolve(),
|
|
3223
|
-
attempt: input,
|
|
3224
|
-
messages,
|
|
3225
|
-
sdkSessionId
|
|
3226
|
-
}),
|
|
3227
|
-
modelRef,
|
|
3228
|
-
now,
|
|
3229
|
-
resultContentSourceByToolName
|
|
3230
|
-
}
|
|
3231
|
-
});
|
|
3232
|
-
activeRunHandleRef = registerCopilotActiveRun({
|
|
3233
|
-
abortActiveSession,
|
|
3234
|
-
bridge,
|
|
3235
|
-
input,
|
|
3236
|
-
isAborted: () => aborted,
|
|
3237
|
-
isSettled: () => settled,
|
|
3238
|
-
userInputBridge
|
|
2115
|
+
isAborted: () => aborted
|
|
3239
2116
|
});
|
|
2117
|
+
const activeRunHandle = {
|
|
2118
|
+
kind: "embedded",
|
|
2119
|
+
queueMessage: async (text) => {
|
|
2120
|
+
if (userInputBridge.handleQueuedMessage(text)) return;
|
|
2121
|
+
throw new Error("Copilot runtime is not waiting for user input.");
|
|
2122
|
+
},
|
|
2123
|
+
isStreaming: () => !settled && !aborted,
|
|
2124
|
+
isCompacting: () => bridge?.isCompacting() ?? false,
|
|
2125
|
+
sourceReplyDeliveryMode: input.sourceReplyDeliveryMode,
|
|
2126
|
+
cancel: () => {
|
|
2127
|
+
userInputBridge.cancelPending();
|
|
2128
|
+
abortActiveSession();
|
|
2129
|
+
},
|
|
2130
|
+
abort: () => {
|
|
2131
|
+
userInputBridge.cancelPending();
|
|
2132
|
+
abortActiveSession();
|
|
2133
|
+
}
|
|
2134
|
+
};
|
|
2135
|
+
setActiveEmbeddedRun(input.sessionId, activeRunHandle, input.sessionKey, input.sessionFile);
|
|
2136
|
+
activeRunHandleRef = activeRunHandle;
|
|
3240
2137
|
const messageOptions = await createMessageOptions(attemptInput, {
|
|
3241
2138
|
effectiveCwd,
|
|
3242
2139
|
effectiveWorkspaceDir,
|
|
@@ -3244,22 +2141,17 @@ async function runCopilotExecution(context) {
|
|
|
3244
2141
|
sandbox,
|
|
3245
2142
|
workspaceOnly: effectiveFsWorkspaceOnly
|
|
3246
2143
|
});
|
|
3247
|
-
|
|
3248
|
-
if (!settledToolFinalization) await transcriptJournal.persistInitialUser();
|
|
2144
|
+
promptImagesCount = messageOptions.attachments?.length ?? 0;
|
|
3249
2145
|
if (abortRequested || params.abortSignal?.aborted) {
|
|
3250
2146
|
aborted = true;
|
|
3251
2147
|
externalAbort = true;
|
|
3252
2148
|
} else {
|
|
3253
2149
|
sentTurnStarted = true;
|
|
3254
|
-
input.userTurnTranscriptRecorder?.markSentToProvider?.();
|
|
3255
2150
|
if (!hasNativePromptHook) emitLlmInput(attemptInput.prompt);
|
|
3256
2151
|
const result = await session.sendAndWait(messageOptions, input.timeoutMs);
|
|
3257
2152
|
await bridge.awaitDeltaChain();
|
|
3258
2153
|
await bridge.awaitAgentEventChain();
|
|
3259
|
-
|
|
3260
|
-
await transcriptJournal.barrier("sendAndWait");
|
|
3261
|
-
settledFinalizationAssistantCompleted = settledToolFinalization && assistantCompleted;
|
|
3262
|
-
if (!assistantCompleted && !aborted) {
|
|
2154
|
+
if (!bridge.recordSendResult(result) && !aborted) {
|
|
3263
2155
|
timedOut = true;
|
|
3264
2156
|
timedOutDuringCompaction = bridge.isCompacting();
|
|
3265
2157
|
}
|
|
@@ -3267,39 +2159,21 @@ async function runCopilotExecution(context) {
|
|
|
3267
2159
|
if (!promptError && !timedOut && !aborted && snap.streamError) promptError = snap.streamError;
|
|
3268
2160
|
}
|
|
3269
2161
|
} catch (error) {
|
|
3270
|
-
if (!aborted)
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
await transcriptJournal?.barrier("timeout");
|
|
3280
|
-
} catch (transcriptError) {
|
|
3281
|
-
promptError = toError$1(transcriptError);
|
|
3282
|
-
}
|
|
3283
|
-
} else try {
|
|
3284
|
-
bridge?.flushTranscriptProjection();
|
|
3285
|
-
await transcriptJournal?.barrier("attempt error");
|
|
3286
|
-
promptError = toError$1(error);
|
|
3287
|
-
} catch (transcriptError) {
|
|
3288
|
-
promptError = toError$1(transcriptError);
|
|
2162
|
+
if (!aborted) {
|
|
2163
|
+
if (isSdkSendAndWaitTimeoutError(error)) {
|
|
2164
|
+
timedOut = true;
|
|
2165
|
+
timedOutDuringCompaction = bridge?.isCompacting() === true;
|
|
2166
|
+
try {
|
|
2167
|
+
await bridge?.awaitDeltaChain();
|
|
2168
|
+
} catch {}
|
|
2169
|
+
await bridge?.awaitAgentEventChain();
|
|
2170
|
+
} else promptError = toError(error);
|
|
3289
2171
|
}
|
|
3290
2172
|
} finally {
|
|
3291
2173
|
settled = true;
|
|
3292
|
-
try {
|
|
3293
|
-
bridge?.flushTranscriptProjection();
|
|
3294
|
-
await transcriptJournal?.barrier("bridge detach");
|
|
3295
|
-
} catch (transcriptError) {
|
|
3296
|
-
promptError = toError$1(transcriptError);
|
|
3297
|
-
}
|
|
3298
2174
|
userInputBridgeRef?.cancelPending();
|
|
3299
2175
|
if (activeRunHandleRef) clearActiveEmbeddedRun(input.sessionId, activeRunHandleRef, input.sessionKey, input.sessionFile);
|
|
3300
|
-
|
|
3301
|
-
const initialUserValidated = !sentTurnStarted || settledToolFinalization || journalSnapshot?.initialSdkUserValidated === true;
|
|
3302
|
-
if (journalSnapshot?.replayInvalid !== true && (bridge?.hasObservedCompaction() || timedOut && bridge?.hasObservedSessionIdle() === false) && bridge && session && handle) {
|
|
2176
|
+
if ((bridge?.hasObservedCompaction() || timedOut && bridge?.hasObservedSessionIdle() === false) && bridge && session && handle) {
|
|
3303
2177
|
const cleanupAbort = new AbortController();
|
|
3304
2178
|
const abortCleanup = () => cleanupAbort.abort();
|
|
3305
2179
|
if (params.abortSignal?.aborted) abortCleanup();
|
|
@@ -3310,7 +2184,6 @@ async function runCopilotExecution(context) {
|
|
|
3310
2184
|
bridge,
|
|
3311
2185
|
cleanupToolBridge,
|
|
3312
2186
|
cleanupByokProxy,
|
|
3313
|
-
deleteSessionOnIncompleteCleanup: nativeSessionCreatedFresh && initialUserValidated,
|
|
3314
2187
|
finalizeNativeSubagents: () => nativeSubagentTaskMirror?.finalizeActiveRuns(),
|
|
3315
2188
|
handle,
|
|
3316
2189
|
pool: deps.pool,
|
|
@@ -3321,7 +2194,7 @@ async function runCopilotExecution(context) {
|
|
|
3321
2194
|
cleanup.finally(() => {
|
|
3322
2195
|
params.abortSignal?.removeEventListener("abort", abortCleanup);
|
|
3323
2196
|
}).catch(() => void 0);
|
|
3324
|
-
if (sdkSessionId
|
|
2197
|
+
if (sdkSessionId) try {
|
|
3325
2198
|
deps.onDeferredCompaction?.({
|
|
3326
2199
|
abort: () => cleanupAbort.abort(),
|
|
3327
2200
|
cleanup,
|
|
@@ -3340,105 +2213,386 @@ async function runCopilotExecution(context) {
|
|
|
3340
2213
|
if (session) try {
|
|
3341
2214
|
await session.disconnect();
|
|
3342
2215
|
} catch (error) {
|
|
3343
|
-
disconnectError = toError
|
|
2216
|
+
disconnectError = toError(error);
|
|
3344
2217
|
if (!promptError && !timedOut) promptError = disconnectError;
|
|
3345
2218
|
}
|
|
3346
2219
|
if (handle) try {
|
|
3347
2220
|
await deps.pool.release(handle);
|
|
3348
2221
|
} catch (error) {
|
|
3349
|
-
const releaseFailure = toError
|
|
2222
|
+
const releaseFailure = toError(error);
|
|
3350
2223
|
if (promptError) console.warn("[copilot-attempt] pool.release failed after primary error", releaseFailure);
|
|
3351
2224
|
else releaseError = releaseFailure;
|
|
3352
2225
|
}
|
|
3353
2226
|
}
|
|
3354
2227
|
}
|
|
3355
|
-
|
|
2228
|
+
const snap = bridge?.snapshot();
|
|
2229
|
+
const assistantTexts = bridge?.finalizeAssistantTexts() ?? [];
|
|
2230
|
+
const lastAssistant = bridge?.buildAssistantMessage({
|
|
2231
|
+
modelRef,
|
|
2232
|
+
now
|
|
2233
|
+
});
|
|
2234
|
+
const syntheticUserText = readString(input.transcriptPrompt) ?? readString(input.prompt);
|
|
2235
|
+
const tailUserText = readTailUserText(messages);
|
|
2236
|
+
const tailUserIndex = messages.findLastIndex((message) => message.role === "user");
|
|
2237
|
+
const currentTurnMessages = messages.map((message, index) => {
|
|
2238
|
+
if (syntheticUserText !== tailUserText || index !== tailUserIndex) return message;
|
|
2239
|
+
return attachCopilotMirrorIdentity({
|
|
2240
|
+
...message,
|
|
2241
|
+
idempotencyKey: `${input.runId}:user`
|
|
2242
|
+
}, `${input.runId}:prompt`);
|
|
2243
|
+
});
|
|
2244
|
+
const syntheticUser = syntheticUserText && syntheticUserText !== tailUserText ? attachCopilotMirrorIdentity({
|
|
2245
|
+
role: "user",
|
|
2246
|
+
content: syntheticUserText,
|
|
2247
|
+
timestamp: now(),
|
|
2248
|
+
idempotencyKey: `${input.runId}:user`
|
|
2249
|
+
}, `${input.runId}:prompt`) : void 0;
|
|
2250
|
+
const taggedLastAssistant = lastAssistant ? attachCopilotMirrorIdentity(lastAssistant, `${input.runId}:assistant:final`) : void 0;
|
|
2251
|
+
const messagesSnapshot = [
|
|
2252
|
+
...currentTurnMessages,
|
|
2253
|
+
...syntheticUser ? [syntheticUser] : [],
|
|
2254
|
+
...taggedLastAssistant ? [taggedLastAssistant] : []
|
|
2255
|
+
];
|
|
2256
|
+
const sessionFileForMirror = readString(input.sessionFile);
|
|
2257
|
+
const openClawSessionIdForMirror = readString(input.sessionId);
|
|
2258
|
+
const mirrorScopeSessionId = sessionIdUsed ?? openClawSessionIdForMirror;
|
|
2259
|
+
if (sessionFileForMirror && openClawSessionIdForMirror && messagesSnapshot.length > 0) {
|
|
2260
|
+
const taggedMessages = messagesSnapshot.map((message, index) => {
|
|
2261
|
+
if (message.role !== "user" && message.role !== "assistant" && message.role !== "toolResult") return message;
|
|
2262
|
+
if (hasMirrorIdentity(message)) return message;
|
|
2263
|
+
return attachCopilotMirrorIdentity(message, `${sdkSessionId ?? mirrorScopeSessionId ?? "attempt"}:${message.role}:${index}`);
|
|
2264
|
+
});
|
|
2265
|
+
await dualWriteCopilotTranscriptBestEffort({
|
|
2266
|
+
sessionFile: sessionFileForMirror,
|
|
2267
|
+
sessionId: openClawSessionIdForMirror,
|
|
2268
|
+
sessionKey: readString(input.sessionKey),
|
|
2269
|
+
agentId: readString(input.agentId),
|
|
2270
|
+
messages: taggedMessages,
|
|
2271
|
+
idempotencyScope: mirrorScopeSessionId ? `copilot:${mirrorScopeSessionId}` : void 0,
|
|
2272
|
+
config: input.config
|
|
2273
|
+
}).catch((mirrorError) => {
|
|
2274
|
+
console.warn("[copilot-attempt] dual-write transcript wrapper rejected unexpectedly", mirrorError);
|
|
2275
|
+
});
|
|
2276
|
+
}
|
|
2277
|
+
const result = createResult(input, {
|
|
3356
2278
|
aborted,
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
codeModeEngaged,
|
|
2279
|
+
assistantTexts,
|
|
2280
|
+
currentAttemptAssistant: lastAssistant,
|
|
3360
2281
|
downgradedFromResume,
|
|
3361
2282
|
externalAbort,
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
modelRef,
|
|
2283
|
+
itemLifecycle: {
|
|
2284
|
+
activeCount: Math.max((snap?.startedCount ?? 0) - (snap?.completedCount ?? 0), 0),
|
|
2285
|
+
completedCount: snap?.completedCount ?? 0,
|
|
2286
|
+
startedCount: snap?.startedCount ?? 0
|
|
2287
|
+
},
|
|
2288
|
+
lastAssistant,
|
|
2289
|
+
messagesSnapshot,
|
|
3370
2290
|
now,
|
|
3371
2291
|
promptError,
|
|
3372
|
-
releaseError,
|
|
3373
2292
|
resumeFailureRecovered,
|
|
3374
2293
|
sdkSessionId,
|
|
3375
|
-
sentTurnStarted,
|
|
3376
2294
|
sessionIdUsed,
|
|
3377
|
-
settledFinalizationAssistantCompleted,
|
|
3378
|
-
settledToolFinalization,
|
|
3379
2295
|
timedOut,
|
|
3380
2296
|
timedOutDuringCompaction,
|
|
2297
|
+
toolMetas: snap ? [...snap.toolMetas] : [],
|
|
2298
|
+
usage: snap?.usage,
|
|
3381
2299
|
yieldDetected
|
|
3382
2300
|
});
|
|
2301
|
+
if (sentTurnStarted) runAgentHarnessLlmOutputHook({
|
|
2302
|
+
event: {
|
|
2303
|
+
runId: input.runId,
|
|
2304
|
+
sessionId: input.sessionId,
|
|
2305
|
+
provider: modelRef.provider,
|
|
2306
|
+
model: modelRef.id,
|
|
2307
|
+
...hookContextWindowFields,
|
|
2308
|
+
resolvedRef: input.runtimePlan?.observability.resolvedRef ?? `${modelRef.provider}/${modelRef.id}`,
|
|
2309
|
+
...input.runtimePlan?.observability.harnessId ? { harnessId: input.runtimePlan.observability.harnessId } : {},
|
|
2310
|
+
assistantTexts: result.assistantTexts,
|
|
2311
|
+
...result.lastAssistant ? { lastAssistant: result.lastAssistant } : {},
|
|
2312
|
+
...result.attemptUsage ? { usage: result.attemptUsage } : {},
|
|
2313
|
+
...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
|
|
2314
|
+
},
|
|
2315
|
+
ctx: hookContext
|
|
2316
|
+
});
|
|
2317
|
+
if (releaseError) {
|
|
2318
|
+
await finalizeCopilotAttempt(input, {
|
|
2319
|
+
...result,
|
|
2320
|
+
promptError: releaseError
|
|
2321
|
+
}, hookContext, attemptStartedAt, now);
|
|
2322
|
+
throw releaseError;
|
|
2323
|
+
}
|
|
2324
|
+
return finishAttempt(result);
|
|
3383
2325
|
}
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
const
|
|
3388
|
-
const
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
|
|
2326
|
+
function createResult(params, state) {
|
|
2327
|
+
const promptError = state.promptError;
|
|
2328
|
+
const timedOut = state.timedOut === true;
|
|
2329
|
+
const toolMetas = state.toolMetas ?? [];
|
|
2330
|
+
const replayMetadata = computeReplayMetadata({
|
|
2331
|
+
priorReplayInvalid: params.initialReplayState?.replayInvalid,
|
|
2332
|
+
priorHadPotentialSideEffects: params.initialReplayState?.hadPotentialSideEffects,
|
|
2333
|
+
thisAttemptTimedOut: timedOut,
|
|
2334
|
+
thisAttemptHadPotentialSideEffects: copilotToolMetasHavePotentialSideEffects(toolMetas),
|
|
2335
|
+
thisAttemptDowngradedFromResume: state.downgradedFromResume,
|
|
2336
|
+
thisAttemptResumeFailureRecovered: state.resumeFailureRecovered
|
|
2337
|
+
});
|
|
2338
|
+
return {
|
|
2339
|
+
aborted: state.aborted === true,
|
|
2340
|
+
...state.sdkSessionId ? { sdkSessionId: state.sdkSessionId } : {},
|
|
2341
|
+
assistantTexts: state.assistantTexts ?? [],
|
|
2342
|
+
attemptUsage: state.usage,
|
|
2343
|
+
cloudCodeAssistFormatError: false,
|
|
2344
|
+
currentAttemptAssistant: state.currentAttemptAssistant,
|
|
2345
|
+
didSendViaMessagingTool: false,
|
|
2346
|
+
externalAbort: state.externalAbort === true,
|
|
2347
|
+
idleTimedOut: false,
|
|
2348
|
+
itemLifecycle: state.itemLifecycle ?? {
|
|
2349
|
+
activeCount: 0,
|
|
2350
|
+
completedCount: 0,
|
|
2351
|
+
startedCount: 0
|
|
2352
|
+
},
|
|
2353
|
+
lastAssistant: state.lastAssistant,
|
|
2354
|
+
messagesSnapshot: state.messagesSnapshot,
|
|
2355
|
+
messagingToolSentMediaUrls: [],
|
|
2356
|
+
messagingToolSentTargets: [],
|
|
2357
|
+
messagingToolSentTexts: [],
|
|
2358
|
+
promptError,
|
|
2359
|
+
promptErrorSource: promptError ? "prompt" : null,
|
|
2360
|
+
replayMetadata,
|
|
2361
|
+
sessionFileUsed: readString(params.sessionFile),
|
|
2362
|
+
sessionIdUsed: state.sessionIdUsed ?? readString(params.sessionId) ?? "copilot-session",
|
|
2363
|
+
timedOut,
|
|
2364
|
+
timedOutDuringCompaction: state.timedOutDuringCompaction === true,
|
|
2365
|
+
toolMetas,
|
|
2366
|
+
yieldDetected: state.yieldDetected === true
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
2369
|
+
function createPromptError(code, message, cause) {
|
|
2370
|
+
const error = new Error(message);
|
|
2371
|
+
error.code = code;
|
|
2372
|
+
if (cause !== void 0) error.cause = cause;
|
|
2373
|
+
return error;
|
|
2374
|
+
}
|
|
2375
|
+
function createSessionConfig(params, sdkModelId, sdkTools, resolvedAuth, resolvedProvider, systemMessageContent, effectiveWorkspaceDir, effectiveCwd, onUserInputRequest, hooksBridgeOptions) {
|
|
2376
|
+
const permissionPolicy = params.permissionPolicy ?? rejectAllPolicy;
|
|
2377
|
+
const hooks = createHooksBridge(params.hooksConfig, hooksBridgeOptions);
|
|
2378
|
+
const infiniteSessions = createInfiniteSessionConfig(params.infiniteSessionConfig);
|
|
2379
|
+
return {
|
|
2380
|
+
model: sdkModelId,
|
|
2381
|
+
onPermissionRequest: createPermissionBridge(permissionPolicy),
|
|
2382
|
+
onUserInputRequest,
|
|
2383
|
+
...resolvedProvider.provider ? { provider: resolvedProvider.provider } : {},
|
|
2384
|
+
...hooks ? { hooks } : {},
|
|
2385
|
+
...typeof params.enableSessionTelemetry === "boolean" ? { enableSessionTelemetry: params.enableSessionTelemetry } : {},
|
|
2386
|
+
...infiniteSessions ? { infiniteSessions } : {},
|
|
2387
|
+
reasoningEffort: params.reasoningEffort,
|
|
2388
|
+
tools: sdkTools,
|
|
2389
|
+
availableTools: buildCopilotAvailableTools(sdkTools),
|
|
2390
|
+
workingDirectory: effectiveCwd ?? effectiveWorkspaceDir ?? readResolvedAttemptPath(params.workspaceDir),
|
|
2391
|
+
...effectiveWorkspaceDir && effectiveCwd && effectiveCwd !== effectiveWorkspaceDir ? { instructionDirectories: [effectiveWorkspaceDir] } : {},
|
|
2392
|
+
...resolvedAuth.authMode === "gitHubToken" && resolvedAuth.gitHubToken ? { gitHubToken: resolvedAuth.gitHubToken } : {},
|
|
2393
|
+
...systemMessageContent ? { systemMessage: {
|
|
2394
|
+
mode: "append",
|
|
2395
|
+
content: systemMessageContent
|
|
2396
|
+
} } : {}
|
|
2397
|
+
};
|
|
2398
|
+
}
|
|
2399
|
+
function buildCopilotAvailableTools(sdkTools) {
|
|
2400
|
+
return [.../* @__PURE__ */ new Set([...sdkTools.map((tool) => tool.name), ...COPILOT_ASK_USER_AVAILABLE_TOOLS])];
|
|
2401
|
+
}
|
|
2402
|
+
async function createMessageOptions(params, context) {
|
|
2403
|
+
const attachments = createPromptImageAttachments(await resolvePromptImages(params, context));
|
|
2404
|
+
const requestHeaders = resolveProviderRequestHeaders(context.provider);
|
|
2405
|
+
return {
|
|
2406
|
+
prompt: params.prompt,
|
|
2407
|
+
...attachments.length > 0 ? { attachments } : {},
|
|
2408
|
+
...requestHeaders ? { requestHeaders } : {}
|
|
2409
|
+
};
|
|
2410
|
+
}
|
|
2411
|
+
function resolveProviderRequestHeaders(provider) {
|
|
2412
|
+
const headers = provider.provider?.headers;
|
|
2413
|
+
return headers && Object.keys(headers).length > 0 ? { ...headers } : void 0;
|
|
2414
|
+
}
|
|
2415
|
+
function createPromptImageAttachments(images) {
|
|
2416
|
+
return images.flatMap((image, index) => {
|
|
2417
|
+
if (!image || typeof image !== "object" || image.type !== "image" || typeof image.data !== "string" || typeof image.mimeType !== "string") return [];
|
|
2418
|
+
return [{
|
|
2419
|
+
type: "blob",
|
|
2420
|
+
data: image.data,
|
|
2421
|
+
mimeType: image.mimeType,
|
|
2422
|
+
displayName: `prompt-image-${index + 1}`
|
|
2423
|
+
}];
|
|
2424
|
+
});
|
|
2425
|
+
}
|
|
2426
|
+
async function resolvePromptImages(params, context) {
|
|
2427
|
+
const workspaceDir = context.effectiveCwd ?? context.effectiveWorkspaceDir ?? readResolvedAttemptPath(params.cwd) ?? readResolvedAttemptPath(params.workspaceDir);
|
|
2428
|
+
if (!workspaceDir) return [];
|
|
2429
|
+
const localRoots = context.workspaceOnly && context.effectiveWorkspaceDir ? [context.effectiveWorkspaceDir] : void 0;
|
|
2430
|
+
return (await detectAndLoadAgentHarnessPromptImages({
|
|
2431
|
+
prompt: params.prompt,
|
|
2432
|
+
workspaceDir,
|
|
2433
|
+
model: resolveImageCapabilityModel(params),
|
|
2434
|
+
existingImages: Array.isArray(params.images) ? params.images : void 0,
|
|
2435
|
+
imageOrder: Array.isArray(params.imageOrder) ? params.imageOrder : void 0,
|
|
2436
|
+
config: params.config,
|
|
2437
|
+
workspaceOnly: context.workspaceOnly,
|
|
2438
|
+
localRoots,
|
|
2439
|
+
sandbox: context.sandbox?.enabled && context.sandbox.fsBridge ? {
|
|
2440
|
+
root: context.sandbox.workspaceDir,
|
|
2441
|
+
bridge: context.sandbox.fsBridge
|
|
2442
|
+
} : void 0
|
|
2443
|
+
})).images;
|
|
2444
|
+
}
|
|
2445
|
+
function resolveImageCapabilityModel(params) {
|
|
2446
|
+
const model = params.model;
|
|
2447
|
+
if (model && typeof model === "object" && Array.isArray(model.input)) return { input: model.input };
|
|
2448
|
+
return { input: ["image"] };
|
|
2449
|
+
}
|
|
2450
|
+
function createSystemMessageContent(params, workspaceBootstrapInstructions) {
|
|
2451
|
+
const sections = [];
|
|
2452
|
+
const bootstrap = workspaceBootstrapInstructions?.trim();
|
|
2453
|
+
if (bootstrap) sections.push(bootstrap);
|
|
2454
|
+
const extraSystemPrompt = readString(params.extraSystemPrompt)?.trim();
|
|
2455
|
+
if (extraSystemPrompt && !isRawCopilotModelRun(params)) {
|
|
2456
|
+
const contextHeader = params.promptMode === "minimal" ? "## Subagent Context" : "## Conversation Context";
|
|
2457
|
+
sections.push(`${contextHeader}\n${extraSystemPrompt}`);
|
|
3414
2458
|
}
|
|
3415
|
-
|
|
3416
|
-
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
|
|
3429
|
-
|
|
3430
|
-
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
2459
|
+
return sections.length > 0 ? sections.join("\n\n") : void 0;
|
|
2460
|
+
}
|
|
2461
|
+
function isRawCopilotModelRun(params) {
|
|
2462
|
+
return params.modelRun === true || params.promptMode === "none";
|
|
2463
|
+
}
|
|
2464
|
+
function getMessagesSnapshotInput(params) {
|
|
2465
|
+
return Array.isArray(params.messages) ? [...params.messages] : [];
|
|
2466
|
+
}
|
|
2467
|
+
function readTailUserText(messages) {
|
|
2468
|
+
const tail = messages[messages.length - 1];
|
|
2469
|
+
if (!tail || tail.role !== "user") return;
|
|
2470
|
+
const content = tail.content;
|
|
2471
|
+
if (typeof content === "string") return content;
|
|
2472
|
+
if (Array.isArray(content)) {
|
|
2473
|
+
for (const part of content) if (part && typeof part === "object" && part.type === "text") {
|
|
2474
|
+
const text = part.text;
|
|
2475
|
+
if (typeof text === "string" && text.length > 0) return text;
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
function hasMirrorIdentity(message) {
|
|
2480
|
+
const meta = message["__openclaw"];
|
|
2481
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return false;
|
|
2482
|
+
const id = meta.mirrorIdentity;
|
|
2483
|
+
return typeof id === "string" && id.length > 0;
|
|
2484
|
+
}
|
|
2485
|
+
function readSessionId(session) {
|
|
2486
|
+
if (!session) return;
|
|
2487
|
+
return readString(session.sessionId) ?? readString(session.id);
|
|
2488
|
+
}
|
|
2489
|
+
function readString(value) {
|
|
2490
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2491
|
+
}
|
|
2492
|
+
function readResolvedAttemptPath(value) {
|
|
2493
|
+
const raw = readString(value)?.trim();
|
|
2494
|
+
if (!raw) return;
|
|
2495
|
+
if (process.platform !== "win32" && /^[A-Za-z]:[\\/]/.test(raw)) return raw;
|
|
2496
|
+
return resolveUserPath(raw);
|
|
2497
|
+
}
|
|
2498
|
+
function resolveModelRef(params) {
|
|
2499
|
+
const rawModel = params.runtimeModel ?? params.model;
|
|
2500
|
+
if (rawModel && typeof rawModel === "object") {
|
|
2501
|
+
const model = rawModel;
|
|
2502
|
+
const requestTransport = getModelProviderRequestTransport(rawModel);
|
|
2503
|
+
const rawRequest = model.request;
|
|
2504
|
+
return {
|
|
2505
|
+
api: readString(model.api),
|
|
2506
|
+
id: readString(model.id) ?? readString(params.modelId) ?? "unknown-model",
|
|
2507
|
+
provider: readString(model.provider) ?? readString(params.provider) ?? "unknown-provider",
|
|
2508
|
+
baseUrl: readString(model.baseUrl),
|
|
2509
|
+
azureApiVersion: readString(model.azureApiVersion ?? model.params?.azureApiVersion),
|
|
2510
|
+
headers: model.headers,
|
|
2511
|
+
authHeader: model.authHeader,
|
|
2512
|
+
requestAuthMode: readString(requestTransport?.auth?.mode ?? rawRequest?.auth?.mode),
|
|
2513
|
+
requestProxy: requestTransport?.proxy ?? rawRequest?.proxy,
|
|
2514
|
+
requestTls: requestTransport?.tls ?? rawRequest?.tls,
|
|
2515
|
+
requestAllowPrivateNetwork: requestTransport?.allowPrivateNetwork ?? rawRequest?.allowPrivateNetwork,
|
|
2516
|
+
contextTokens: model.contextTokens,
|
|
2517
|
+
contextWindow: model.contextWindow,
|
|
2518
|
+
maxTokens: model.maxTokens
|
|
2519
|
+
};
|
|
2520
|
+
}
|
|
2521
|
+
return {
|
|
2522
|
+
id: readString(typeof rawModel === "string" ? rawModel : void 0) ?? readString(params.modelId) ?? "unknown-model",
|
|
2523
|
+
provider: readString(params.provider) ?? "unknown-provider"
|
|
2524
|
+
};
|
|
2525
|
+
}
|
|
2526
|
+
function resolvePoolAcquire(params) {
|
|
2527
|
+
const model = resolveModelRef(params);
|
|
2528
|
+
const provider = resolveCopilotProvider({
|
|
2529
|
+
model,
|
|
2530
|
+
resolvedApiKey: readString(params.resolvedApiKey),
|
|
2531
|
+
authProfileId: readString(params.authProfileId)
|
|
2532
|
+
});
|
|
2533
|
+
const auth = provider.mode === "byok" ? createCopilotByokAuth({
|
|
2534
|
+
agentId: readString(params.agentId),
|
|
2535
|
+
agentDir: readString(params.agentDir),
|
|
2536
|
+
workspaceDir: readString(params.workspaceDir),
|
|
2537
|
+
copilotHome: readString(params.copilotHome),
|
|
2538
|
+
authProfileId: provider.authProfileId,
|
|
2539
|
+
authProfileVersion: provider.authProfileVersion
|
|
2540
|
+
}) : resolveCopilotAuth({
|
|
2541
|
+
agentId: readString(params.agentId),
|
|
2542
|
+
agentDir: readString(params.agentDir),
|
|
2543
|
+
workspaceDir: readString(params.workspaceDir),
|
|
2544
|
+
copilotHome: readString(params.copilotHome),
|
|
2545
|
+
auth: params.auth,
|
|
2546
|
+
resolvedApiKey: readString(params.resolvedApiKey),
|
|
2547
|
+
authProfileId: readString(params.authProfileId),
|
|
2548
|
+
profileVersion: readString(params.profileVersion)
|
|
3441
2549
|
});
|
|
2550
|
+
return {
|
|
2551
|
+
key: {
|
|
2552
|
+
agentId: auth.agentId,
|
|
2553
|
+
authMode: auth.authMode,
|
|
2554
|
+
...auth.authMode === "gitHubToken" || auth.authMode === "byok" ? {
|
|
2555
|
+
authProfileId: auth.authProfileId,
|
|
2556
|
+
authProfileVersion: auth.authProfileVersion
|
|
2557
|
+
} : {},
|
|
2558
|
+
copilotHome: auth.copilotHome
|
|
2559
|
+
},
|
|
2560
|
+
options: {
|
|
2561
|
+
copilotHome: auth.copilotHome,
|
|
2562
|
+
...auth.authMode === "gitHubToken" && auth.gitHubToken ? { gitHubToken: auth.gitHubToken } : {},
|
|
2563
|
+
useLoggedInUser: auth.authMode === "useLoggedInUser"
|
|
2564
|
+
},
|
|
2565
|
+
auth,
|
|
2566
|
+
provider
|
|
2567
|
+
};
|
|
2568
|
+
}
|
|
2569
|
+
function toError(error) {
|
|
2570
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* Detect the @github/copilot-sdk `session.sendAndWait` timeout
|
|
2574
|
+
* rejection shape. The SDK's `sendAndWait` races the internal
|
|
2575
|
+
* `session.idle` event against a timer; when the timer fires first
|
|
2576
|
+
* it REJECTS the promise with
|
|
2577
|
+
* `new Error(`Timeout after ${effectiveTimeout}ms waiting for
|
|
2578
|
+
* session.idle`)` (see
|
|
2579
|
+
* `node_modules/@github/copilot-sdk/dist/session.js:156-164`), and
|
|
2580
|
+
* the SDK docs explicitly note the timeout "does not abort in-flight
|
|
2581
|
+
* agent work". The caller is therefore responsible for setting the
|
|
2582
|
+
* timed-out state and (for paths where in-flight work should be
|
|
2583
|
+
* stopped) calling `session.abort()`.
|
|
2584
|
+
*
|
|
2585
|
+
* Keep the regex anchored and narrow so unrelated errors that happen
|
|
2586
|
+
* to mention "Timeout" are NOT mis-classified. The shape is a literal
|
|
2587
|
+
* template-string concatenation in the 1.0.0-beta line; a minor
|
|
2588
|
+
* version bump that changes the wording will safely fall through to
|
|
2589
|
+
* the generic prompt-error path.
|
|
2590
|
+
*/
|
|
2591
|
+
function isSdkSendAndWaitTimeoutError(error) {
|
|
2592
|
+
if (error === null || typeof error !== "object") return false;
|
|
2593
|
+
const message = error.message;
|
|
2594
|
+
if (typeof message !== "string") return false;
|
|
2595
|
+
return /^Timeout after \d+ms waiting for session\.idle$/.test(message);
|
|
3442
2596
|
}
|
|
3443
2597
|
//#endregion
|
|
3444
2598
|
export { resolvePoolAcquire, runCopilotAttempt };
|