@openclaw/copilot 2026.9.1-beta.1 → 2026.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attempt-NJAPbYd4.js → attempt-BJ2mxTkh.js} +206 -211
- package/dist/{harness-hh25oAuF.js → harness-CIPB8kLr.js} +48 -23
- package/dist/harness.js +1 -1
- package/dist/index.js +10 -5
- package/dist/{isolated-completion-GNSNtOHz.js → isolated-completion-OGrJ9ITR.js} +19 -8
- package/dist/{runtime-DvZQV_8v.js → runtime-LtZ5NAjV.js} +4 -5
- package/openclaw.plugin.json +0 -1
- package/package.json +4 -4
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-
|
|
1
|
+
import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-CIPB8kLr.js";
|
|
2
2
|
import { n as normalizeCopilotUsage, r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.js";
|
|
3
|
-
import { asNonArrayRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
4
|
-
import { SKILL_WORKSHOP_TOOL_NAME,
|
|
3
|
+
import { asNonArrayRecord, asOptionalRecord, normalizeOptionalString, normalizeUniqueStringEntries, readNonBlankString, readNonEmptyStringPreservingWhitespace, readNonEmptyStringPreservingWhitespace as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
4
|
+
import { SKILL_WORKSHOP_TOOL_NAME, applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHookContextChannelFields, buildCredentialSafetyPrompt, buildDelegationGuidanceSection, buildEmbeddedAttemptToolRunContext, buildEmbeddedForegroundPromptContext, buildHarnessVisibleReplyGuidance, buildSkillWorkshopPromptSection, cancelPendingAgentQuestionForSession, claimPendingAgentQuestionAnswer, clearActiveEmbeddedRun, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, getPluginToolSideEffectOwnerKey, isHostScopedAgentToolActive, isSubagentSessionKey, isToolResultError, projectAgentHarnessTranscriptMessageForDisplay, resolveAgentDir, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveMainSessionDelegationMode, resolveModelAuthMode, resolveSandboxContext, resolveUserPath, restorePreparedUserTurnOperationalMetaForRuntime, runAgentEndSideEffects, runAgentHarnessAfterCompactionHook, runAgentHarnessAfterToolCallHook, runAgentHarnessBeforeCompactionHook, runAgentHarnessBeforeMessageWriteHook, runAgentHarnessGatewayQuestion, runAgentHarnessLlmInputHook, runAgentHarnessLlmOutputHook, sanitizeToolResult, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { formatErrorMessage, toErrorObject, toStringifiedError, toStringifiedError as toCopilotError } from "openclaw/plugin-sdk/error-runtime";
|
|
7
7
|
import { parseDateStringTimestampMs } from "openclaw/plugin-sdk/number-runtime";
|
|
8
8
|
import fsp from "node:fs/promises";
|
|
9
|
+
import { resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
|
|
9
10
|
import { convertMcpCallToolResult } from "@github/copilot-sdk";
|
|
10
11
|
import { createAgentHarnessToolSurfaceRuntime } from "openclaw/plugin-sdk/agent-harness-tool-runtime";
|
|
11
12
|
import { isDeepStrictEqual } from "node:util";
|
|
13
|
+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
|
|
12
14
|
import { appendSessionTranscriptMessageByIdentityStrict, appendSessionTranscriptMessagesByIdentity, publishSessionTranscriptUpdateByIdentity, readVisibleSessionTranscriptMessageEntries } from "openclaw/plugin-sdk/session-transcript-runtime";
|
|
13
15
|
import { createAgentHarnessTaskRuntime } from "openclaw/plugin-sdk/agent-harness-task-runtime";
|
|
14
16
|
//#region extensions/copilot/src/attempt-types.ts
|
|
@@ -324,6 +326,7 @@ function createResult(params, state) {
|
|
|
324
326
|
} : { kind: "ok" };
|
|
325
327
|
return {
|
|
326
328
|
terminal: promptError !== void 0 ? withPromptFailure(interruption, promptError) : interruption,
|
|
329
|
+
...state.acceptedSessionSpawns?.length ? { acceptedSessionSpawns: state.acceptedSessionSpawns } : {},
|
|
327
330
|
...state.assistantTranscriptOwned ? {
|
|
328
331
|
assistantTranscriptOwned: true,
|
|
329
332
|
...state.assistantTranscriptIdempotencyKey ? { assistantTranscriptIdempotencyKey: state.assistantTranscriptIdempotencyKey } : {}
|
|
@@ -351,7 +354,7 @@ function createResult(params, state) {
|
|
|
351
354
|
messagingToolSentTexts: [],
|
|
352
355
|
replayMetadata,
|
|
353
356
|
sessionFileUsed: readNonEmptyString(params.sessionFile),
|
|
354
|
-
sessionIdUsed:
|
|
357
|
+
sessionIdUsed: params.sessionId,
|
|
355
358
|
toolMetas,
|
|
356
359
|
yieldDetected: state.yieldDetected === true,
|
|
357
360
|
...state.yieldAcknowledgment ? { yieldAcknowledgment: state.yieldAcknowledgment } : {}
|
|
@@ -477,8 +480,9 @@ function resolveModelRef(params) {
|
|
|
477
480
|
};
|
|
478
481
|
}
|
|
479
482
|
function resolvePoolAcquire(params) {
|
|
483
|
+
const model = resolveModelRef(params);
|
|
480
484
|
const provider = resolveCopilotProvider({
|
|
481
|
-
model
|
|
485
|
+
model,
|
|
482
486
|
resolvedApiKey: readNonEmptyString(params.resolvedApiKey),
|
|
483
487
|
authProfileId: readNonEmptyString(params.authProfileId)
|
|
484
488
|
});
|
|
@@ -1319,15 +1323,20 @@ function registerCopilotActiveRun(params) {
|
|
|
1319
1323
|
acceptanceReported = true;
|
|
1320
1324
|
options?.onQueueAccepted?.(accepted);
|
|
1321
1325
|
};
|
|
1326
|
+
if (await claimPendingUserInputAnswer(text, options)) {
|
|
1327
|
+
reportAcceptance(true);
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1322
1330
|
let messageId;
|
|
1323
1331
|
try {
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
return;
|
|
1327
|
-
}
|
|
1332
|
+
const recorder = options?.userTurnTranscriptRecorder;
|
|
1333
|
+
const sourceMessage = recorder ? await recorder.resolveMessage() : void 0;
|
|
1328
1334
|
if (params.isSettled() || params.isAborted()) throw new Error("Copilot steering is unavailable after the active run ended");
|
|
1329
1335
|
if (!params.canAcceptSteering()) throw new Error("Copilot steering is unavailable before initial user validation");
|
|
1330
|
-
messageId = await params.session.send({
|
|
1336
|
+
messageId = await params.transcriptJournal.sendSdkUser(() => params.session.send({
|
|
1337
|
+
prompt: text,
|
|
1338
|
+
...typeof sourceMessage?.content === "string" ? { displayPrompt: sourceMessage.content } : {}
|
|
1339
|
+
}), recorder);
|
|
1331
1340
|
reportAcceptance(true);
|
|
1332
1341
|
} catch (error) {
|
|
1333
1342
|
reportAcceptance(false);
|
|
@@ -1345,6 +1354,7 @@ function registerCopilotActiveRun(params) {
|
|
|
1345
1354
|
const activeRunHandle = {
|
|
1346
1355
|
kind: "embedded",
|
|
1347
1356
|
runId: params.input.runId,
|
|
1357
|
+
startedAtMs: params.startedAtMs,
|
|
1348
1358
|
toolAuthorityFingerprint: params.input.toolAuthorityFingerprint,
|
|
1349
1359
|
claimPendingUserInputAnswer,
|
|
1350
1360
|
cancelPendingUserInput,
|
|
@@ -1389,7 +1399,7 @@ async function waitForPersistenceReceipt(receipt, requestedTimeoutMs) {
|
|
|
1389
1399
|
//#endregion
|
|
1390
1400
|
//#region extensions/copilot/src/attempt-finalize.ts
|
|
1391
1401
|
async function completeCopilotAttempt(params) {
|
|
1392
|
-
const { aborted, attemptStartedAt, bridge, codeModeEngaged, downgradedFromResume, externalAbort, hookContext, hookContextWindowFields, input, lastToolError, messages, nativeSessionHistoryUnvalidated, transcriptJournal, modelRef, now, promptError, releaseError, resumeFailureRecovered, sdkSessionId, sentTurnStarted,
|
|
1402
|
+
const { acceptedSessionSpawns, aborted, attemptStartedAt, bridge, codeModeEngaged, downgradedFromResume, externalAbort, hookContext, hookContextWindowFields, input, lastToolError, messages, nativeSessionHistoryUnvalidated, transcriptJournal, modelRef, now, promptError, releaseError, resumeFailureRecovered, sdkSessionId, sentTurnStarted, settledFinalizationAssistantCompleted, settledToolFinalization, timedOut, timedOutDuringCompaction, yieldDetected, yieldAcknowledgment } = params;
|
|
1393
1403
|
const snap = bridge?.snapshot();
|
|
1394
1404
|
const assistantTexts = bridge?.finalizeAssistantTexts() ?? [];
|
|
1395
1405
|
const lastAssistant = bridge?.buildAssistantMessage({
|
|
@@ -1401,6 +1411,7 @@ async function completeCopilotAttempt(params) {
|
|
|
1401
1411
|
const currentRunUserKey = `${input.runId}:user`;
|
|
1402
1412
|
const messagesSnapshot = transcript?.messagesSnapshot ?? (recorder?.isBlocked() ? removePreparedUser(messages, recorder.message, currentRunUserKey) : includePreparedUser(messages, recorder?.message, input.trigger === "memory", currentRunUserKey));
|
|
1403
1413
|
const result = createResult(input, {
|
|
1414
|
+
acceptedSessionSpawns,
|
|
1404
1415
|
aborted,
|
|
1405
1416
|
assistantTexts,
|
|
1406
1417
|
codeModeEngaged,
|
|
@@ -1425,7 +1436,6 @@ async function completeCopilotAttempt(params) {
|
|
|
1425
1436
|
promptError,
|
|
1426
1437
|
resumeFailureRecovered,
|
|
1427
1438
|
sdkSessionId,
|
|
1428
|
-
sessionIdUsed,
|
|
1429
1439
|
timedOut,
|
|
1430
1440
|
timedOutDuringCompaction,
|
|
1431
1441
|
toolMetas: snap ? [...snap.toolMetas] : [],
|
|
@@ -1522,21 +1532,12 @@ async function createCopilotToolBridge(input) {
|
|
|
1522
1532
|
disableTools: attemptParams.disableTools,
|
|
1523
1533
|
forceMessageTool: shouldForceCopilotMessageTool(attemptParams),
|
|
1524
1534
|
isRawModelRun: isRawCopilotModelRun(attemptParams),
|
|
1525
|
-
toolsAllow:
|
|
1535
|
+
toolsAllow: buildEmbeddedAttemptToolRunContext({
|
|
1536
|
+
...attemptParams,
|
|
1537
|
+
forceMessageTool: shouldForceCopilotMessageTool(attemptParams)
|
|
1538
|
+
}).runtimeToolAllowlist
|
|
1526
1539
|
});
|
|
1527
|
-
|
|
1528
|
-
...toolPlan,
|
|
1529
|
-
codingToolConstructionPlan: {
|
|
1530
|
-
includeBaseCodingTools: true,
|
|
1531
|
-
includeChannelTools: true,
|
|
1532
|
-
includeOpenClawTools: true,
|
|
1533
|
-
includePluginTools: true,
|
|
1534
|
-
includeShellTools: true
|
|
1535
|
-
},
|
|
1536
|
-
constructTools: true,
|
|
1537
|
-
includeCoreTools: true
|
|
1538
|
-
} : toolPlan;
|
|
1539
|
-
if (!effectiveToolPlan.constructTools) return {
|
|
1540
|
+
if (!toolPlan.constructTools) return {
|
|
1540
1541
|
codeModeEngaged: false,
|
|
1541
1542
|
promptToolPolicy: EMPTY_PROMPT_TOOL_POLICY,
|
|
1542
1543
|
sourceTools: []
|
|
@@ -1544,19 +1545,21 @@ async function createCopilotToolBridge(input) {
|
|
|
1544
1545
|
const createOpenClawCodingTools = input.createOpenClawCodingTools ?? (await import("openclaw/plugin-sdk/agent-harness")).createOpenClawCodingTools;
|
|
1545
1546
|
const toolSurfaceRuntime = createAgentHarnessToolSurfaceRuntime({
|
|
1546
1547
|
abortSignal: input.abortSignal,
|
|
1547
|
-
agentId: input.agentId,
|
|
1548
|
+
agentId: attemptParams.sandboxAgentId ?? input.agentId,
|
|
1548
1549
|
config: attemptParams.config,
|
|
1550
|
+
codeModeOverride: attemptParams.codeModeOverride,
|
|
1549
1551
|
disableTools: attemptParams.disableTools,
|
|
1550
1552
|
executeTool: (toolParams) => executeCatalogTool(input, toolParams),
|
|
1551
1553
|
forceMessageTool: shouldForceCopilotMessageTool(attemptParams),
|
|
1552
1554
|
isRawModelRun: isRawCopilotModelRun(attemptParams),
|
|
1553
1555
|
model: attemptParams.model,
|
|
1556
|
+
contextTokenBudget: attemptParams.contextTokenBudget,
|
|
1554
1557
|
modelId: input.modelId,
|
|
1555
1558
|
modelProvider: input.modelProvider,
|
|
1556
1559
|
modelToolsEnabled: true,
|
|
1557
1560
|
prompt: attemptParams.prompt,
|
|
1558
1561
|
runId: attemptParams.runId,
|
|
1559
|
-
runtimeToolAllowlist:
|
|
1562
|
+
runtimeToolAllowlist: toolPlan.runtimeToolAllowlist,
|
|
1560
1563
|
sessionId: input.sessionId,
|
|
1561
1564
|
sessionKey: attemptParams.sandboxSessionKey ?? attemptParams.sessionKey ?? input.sessionKey,
|
|
1562
1565
|
scheduledToolPolicy: attemptParams.scheduledToolPolicy,
|
|
@@ -1564,7 +1567,7 @@ async function createCopilotToolBridge(input) {
|
|
|
1564
1567
|
toolsAllow: attemptParams.toolsAllow
|
|
1565
1568
|
});
|
|
1566
1569
|
const toolOptions = buildOpenClawCodingToolsOptions(input, {
|
|
1567
|
-
...
|
|
1570
|
+
...toolPlan,
|
|
1568
1571
|
runtimeToolAllowlist: toolSurfaceRuntime.runtimeToolAllowlist
|
|
1569
1572
|
}, toolSurfaceRuntime);
|
|
1570
1573
|
let sourceTools;
|
|
@@ -1582,7 +1585,7 @@ async function createCopilotToolBridge(input) {
|
|
|
1582
1585
|
} catch (error) {
|
|
1583
1586
|
throw createError(`[copilot-tool-bridge] createOpenClawCodingTools failed: ${toStringifiedError(error).message}`, error);
|
|
1584
1587
|
}
|
|
1585
|
-
const plannedSourceTools = filterCopilotToolsForConstructionPlan(applyEmbeddedAttemptToolsAllow(sourceTools, toolSurfaceRuntime.runtimeToolAllowlist, { toolMeta: (tool) => getPluginToolMeta(tool) ?? readInlinePluginToolMeta(tool) }),
|
|
1588
|
+
const plannedSourceTools = filterCopilotToolsForConstructionPlan(applyEmbeddedAttemptToolsAllow(sourceTools, toolSurfaceRuntime.runtimeToolAllowlist, { toolMeta: (tool) => getPluginToolMeta(tool) ?? readInlinePluginToolMeta(tool) }), toolPlan.codingToolConstructionPlan, { preserveToolNames: toolSurfaceRuntime.runtimeToolAllowlist });
|
|
1586
1589
|
const compactedTools = toolSurfaceRuntime.compactTools(plannedSourceTools, { localModelLeanApplied: true });
|
|
1587
1590
|
const newlyConstructedTools = compactedTools.tools.filter((tool) => !boundSourceTools.has(tool));
|
|
1588
1591
|
const boundNewlyConstructedTools = newlyConstructedTools.length > 0 ? hostCapabilities.bindToolSurface(newlyConstructedTools, bindingOptions) : newlyConstructedTools;
|
|
@@ -1592,18 +1595,29 @@ async function createCopilotToolBridge(input) {
|
|
|
1592
1595
|
const exposedTools = compactedTools.tools.map((tool) => newlyBoundTools.get(tool) ?? tool);
|
|
1593
1596
|
const duplicateNames = findDuplicateToolNames(exposedTools);
|
|
1594
1597
|
if (duplicateNames.length > 0) throw new Error(`[copilot-tool-bridge] duplicate tool names: ${duplicateNames.join(", ")}`);
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1598
|
+
let sequentialBarrier = Promise.resolve();
|
|
1599
|
+
const pendingCalls = /* @__PURE__ */ new Set();
|
|
1600
|
+
const scheduleToolExecution = (executionMode, execute) => {
|
|
1601
|
+
const run = (executionMode === "sequential" ? Promise.all(pendingCalls) : sequentialBarrier).then(execute);
|
|
1602
|
+
const settled = run.then(() => void 0, () => void 0);
|
|
1603
|
+
pendingCalls.add(settled);
|
|
1604
|
+
settled.then(() => pendingCalls.delete(settled));
|
|
1605
|
+
if (executionMode === "sequential") sequentialBarrier = settled;
|
|
1606
|
+
return run;
|
|
1607
|
+
};
|
|
1608
|
+
const sdkTools = exposedTools.map((sourceTool) => convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution));
|
|
1602
1609
|
return {
|
|
1603
1610
|
cleanup: toolSurfaceRuntime.cleanup,
|
|
1604
1611
|
codeModeEngaged: toolSurfaceRuntime.codeModeControlsEnabled,
|
|
1605
1612
|
promptToolPolicy: { apply: (params = {}) => {
|
|
1606
|
-
const result = compactedTools.promptToolPolicy.apply(
|
|
1613
|
+
const result = compactedTools.promptToolPolicy.apply({
|
|
1614
|
+
...params,
|
|
1615
|
+
toolsAllow: buildEmbeddedAttemptToolRunContext({
|
|
1616
|
+
...attemptParams,
|
|
1617
|
+
toolsAllow: params.toolsAllow,
|
|
1618
|
+
forceMessageTool: shouldForceCopilotMessageTool(attemptParams)
|
|
1619
|
+
}).runtimeToolAllowlist
|
|
1620
|
+
});
|
|
1607
1621
|
const directToolNames = new Set(result.tools.map((tool) => tool.name));
|
|
1608
1622
|
return {
|
|
1609
1623
|
tools: sdkTools.filter((tool) => directToolNames.has(tool.name)),
|
|
@@ -1614,26 +1628,9 @@ async function createCopilotToolBridge(input) {
|
|
|
1614
1628
|
};
|
|
1615
1629
|
}
|
|
1616
1630
|
/**
|
|
1617
|
-
*
|
|
1618
|
-
*
|
|
1619
|
-
*
|
|
1620
|
-
* Why PI parity matters: bridged OpenClaw tools register with the SDK
|
|
1621
|
-
* as `overridesBuiltInTool: true, skipPermission: true` (see
|
|
1622
|
-
* `convertOpenClawToolToSdkTool` below). That means the wrapped-tool
|
|
1623
|
-
* enforcement layer
|
|
1624
|
-
* (`src/agents/pi-tools.before-tool-call.ts → wrapToolWithBeforeToolCallHook`)
|
|
1625
|
-
* is the single gate for permission, owner-only allowlists, loop
|
|
1626
|
-
* detection, trusted-plugin policies, and two-phase plugin approvals.
|
|
1627
|
-
* That layer reads its context from the fields forwarded here; missing
|
|
1628
|
-
* fields silently degrade policy decisions. See docs/plugins/copilot.md.
|
|
1629
|
-
*
|
|
1630
|
-
* The shared embedded-runner tool plan is forwarded so the bridge does
|
|
1631
|
-
* not construct broad tool families only to filter them later. That
|
|
1632
|
-
* preserves PI allowlist semantics such as `write` not materializing
|
|
1633
|
-
* `apply_patch`.
|
|
1634
|
-
* Sandbox is forwarded via the explicit `sandbox` field on
|
|
1635
|
-
* {@link CopilotToolBridgeInput}; callers resolve it via
|
|
1636
|
-
* `resolveSandboxContext` before constructing the bridge.
|
|
1631
|
+
* Bridged tools skip SDK permission prompts, so host wrappers need the complete
|
|
1632
|
+
* attempt context and prepared sandbox/construction policy to enforce access.
|
|
1633
|
+
* Missing fields here silently weaken or misapply the native harness contract.
|
|
1637
1634
|
*/
|
|
1638
1635
|
function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
1639
1636
|
const a = input.attemptParams;
|
|
@@ -1653,19 +1650,18 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
|
1653
1650
|
const modelCompat = model && typeof model === "object" && "compat" in model && model.compat && typeof model.compat === "object" ? model.compat : void 0;
|
|
1654
1651
|
return {
|
|
1655
1652
|
agentId: input.agentId,
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
jobId: a.jobId,
|
|
1659
|
-
memoryFlushWritePath: a.memoryFlushWritePath,
|
|
1660
|
-
toolsAllow: a.toolsAllow,
|
|
1661
|
-
conversationToolPolicy: a.conversationToolPolicy
|
|
1662
|
-
}),
|
|
1653
|
+
policyAgentId: a.sandboxAgentId ?? input.agentId,
|
|
1654
|
+
...buildEmbeddedAttemptToolRunContext(a),
|
|
1663
1655
|
exec: {
|
|
1664
1656
|
...a.execOverrides,
|
|
1665
1657
|
elevated: a.bashElevated
|
|
1666
1658
|
},
|
|
1667
1659
|
messageProvider: a.messageProvider ?? a.messageChannel,
|
|
1668
1660
|
messageChannel: a.messageChannel,
|
|
1661
|
+
...a.onToolResult ? { questionPrompt: {
|
|
1662
|
+
send: a.onToolResult,
|
|
1663
|
+
...a.messageChannel ? { messageChannel: a.messageChannel } : {}
|
|
1664
|
+
} } : {},
|
|
1669
1665
|
toolBindings: a.toolBindings,
|
|
1670
1666
|
chatType: a.chatType,
|
|
1671
1667
|
agentAccountId: a.agentAccountId,
|
|
@@ -1707,7 +1703,7 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
|
1707
1703
|
toolConstructionPlan: toolPlan.codingToolConstructionPlan,
|
|
1708
1704
|
modelCompat,
|
|
1709
1705
|
modelApi: model?.api,
|
|
1710
|
-
modelContextWindowTokens: model?.contextWindow,
|
|
1706
|
+
modelContextWindowTokens: a.contextTokenBudget ?? model?.contextWindow,
|
|
1711
1707
|
delegationCapability: a.delegationCapability,
|
|
1712
1708
|
modelAuthMode: resolveModelAuthMode(input.modelProvider, a.config, void 0, { workspaceDir }),
|
|
1713
1709
|
currentChannelId: a.currentChannelId,
|
|
@@ -1737,15 +1733,14 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
|
|
|
1737
1733
|
}
|
|
1738
1734
|
};
|
|
1739
1735
|
}
|
|
1740
|
-
function convertOpenClawToolToSdkTool(sourceTool,
|
|
1736
|
+
function convertOpenClawToolToSdkTool(sourceTool, input, scheduleToolExecution) {
|
|
1741
1737
|
if (typeof sourceTool.name !== "string" || sourceTool.name.trim().length === 0) throw new Error("[copilot-tool-bridge] tool name must be a non-empty string");
|
|
1742
1738
|
if (typeof sourceTool.execute !== "function") throw new Error(`[copilot-tool-bridge] tool '${sourceTool.name}' must define an execute function`);
|
|
1743
1739
|
const ownerKey = getPluginToolSideEffectOwnerKey(sourceTool);
|
|
1744
1740
|
const ownerMutation = ownerKey ? { ownerKey } : void 0;
|
|
1745
|
-
let sequentialLock = Promise.resolve();
|
|
1746
1741
|
const notifyToolResult = (result, isError) => {
|
|
1747
1742
|
try {
|
|
1748
|
-
|
|
1743
|
+
input.attemptParams.onAgentToolResult?.({
|
|
1749
1744
|
toolName: sourceTool.name,
|
|
1750
1745
|
result,
|
|
1751
1746
|
isError
|
|
@@ -1756,7 +1751,7 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1756
1751
|
};
|
|
1757
1752
|
const notifyToolCompleted = (completion) => {
|
|
1758
1753
|
try {
|
|
1759
|
-
Promise.resolve(
|
|
1754
|
+
Promise.resolve(input.onToolCompleted?.(completion)).catch((error) => {
|
|
1760
1755
|
console.warn("[copilot-tool-bridge] onToolCompleted handler threw; continuing", error);
|
|
1761
1756
|
});
|
|
1762
1757
|
} catch (error) {
|
|
@@ -1765,7 +1760,7 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1765
1760
|
};
|
|
1766
1761
|
const failureResult = (executedArgs, invocation, startedAt, message, error, executionStarted) => {
|
|
1767
1762
|
const errorMessage = toStringifiedError(error).message;
|
|
1768
|
-
|
|
1763
|
+
input.attemptParams.observeToolTerminal?.({
|
|
1769
1764
|
toolCallId: invocation.toolCallId,
|
|
1770
1765
|
toolName: sourceTool.name,
|
|
1771
1766
|
arguments: executedArgs,
|
|
@@ -1795,12 +1790,12 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1795
1790
|
};
|
|
1796
1791
|
const executeOnce = async (args, invocation) => {
|
|
1797
1792
|
const startedAt = Date.now();
|
|
1798
|
-
if (
|
|
1793
|
+
if (input.abortSignal?.aborted) {
|
|
1799
1794
|
const error = /* @__PURE__ */ new Error("[copilot-tool-bridge] aborted before execution");
|
|
1800
1795
|
return failureResult(args, invocation, startedAt, error.message, error, false);
|
|
1801
1796
|
}
|
|
1802
1797
|
try {
|
|
1803
|
-
await
|
|
1798
|
+
await input.beforeExecute?.({
|
|
1804
1799
|
args,
|
|
1805
1800
|
invocation,
|
|
1806
1801
|
sourceTool,
|
|
@@ -1818,7 +1813,7 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1818
1813
|
}
|
|
1819
1814
|
let result;
|
|
1820
1815
|
try {
|
|
1821
|
-
result = await sourceTool.execute(invocation.toolCallId, preparedArgs,
|
|
1816
|
+
result = await sourceTool.execute(invocation.toolCallId, preparedArgs, input.abortSignal, void 0);
|
|
1822
1817
|
} catch (error) {
|
|
1823
1818
|
return failureResult(preparedArgs, invocation, startedAt, `[copilot-tool-bridge] tool '${sourceTool.name}' failed: ${toStringifiedError(error).message}`, error, true);
|
|
1824
1819
|
}
|
|
@@ -1829,7 +1824,7 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1829
1824
|
isError: resultIsError
|
|
1830
1825
|
});
|
|
1831
1826
|
const resultError = resultIsError ? extractToolErrorMessage(sanitizedResult) : void 0;
|
|
1832
|
-
|
|
1827
|
+
input.attemptParams.observeToolTerminal?.({
|
|
1833
1828
|
toolCallId: invocation.toolCallId,
|
|
1834
1829
|
toolName: sourceTool.name,
|
|
1835
1830
|
arguments: preparedArgs,
|
|
@@ -1849,14 +1844,10 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
|
|
|
1849
1844
|
});
|
|
1850
1845
|
return sdkResult;
|
|
1851
1846
|
};
|
|
1852
|
-
const handler = sourceTool.executionMode === "sequential" ? (args, invocation) => {
|
|
1853
|
-
const run = sequentialLock.then(() => executeOnce(args, invocation), () => executeOnce(args, invocation));
|
|
1854
|
-
sequentialLock = run.then(() => void 0, () => void 0);
|
|
1855
|
-
return run;
|
|
1856
|
-
} : executeOnce;
|
|
1857
1847
|
return {
|
|
1858
1848
|
description: sourceTool.description,
|
|
1859
|
-
|
|
1849
|
+
defer: sourceTool.catalogMode === "direct-only" ? "never" : void 0,
|
|
1850
|
+
handler: (args, invocation) => scheduleToolExecution(sourceTool.executionMode, () => executeOnce(args, invocation)),
|
|
1860
1851
|
name: sourceTool.name,
|
|
1861
1852
|
overridesBuiltInTool: true,
|
|
1862
1853
|
parameters: sourceTool.parameters,
|
|
@@ -1976,12 +1967,6 @@ function filterCopilotToolsForConstructionPlan(tools, plan, options = {}) {
|
|
|
1976
1967
|
return true;
|
|
1977
1968
|
});
|
|
1978
1969
|
}
|
|
1979
|
-
function hasNonWildcardGlobAllowlist(toolsAllow) {
|
|
1980
|
-
return (toolsAllow ?? []).some((entry) => {
|
|
1981
|
-
const trimmed = entry.trim();
|
|
1982
|
-
return trimmed !== "*" && trimmed.includes("*");
|
|
1983
|
-
});
|
|
1984
|
-
}
|
|
1985
1970
|
function readInlinePluginToolMeta(tool) {
|
|
1986
1971
|
const pluginId = tool.pluginId;
|
|
1987
1972
|
return typeof pluginId === "string" && pluginId.trim() ? { pluginId } : void 0;
|
|
@@ -2025,7 +2010,7 @@ function prepareCopilotAttemptContext(params, deps) {
|
|
|
2025
2010
|
const modelRef = resolveModelRef(input);
|
|
2026
2011
|
const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
|
|
2027
2012
|
const sandboxSessionKey = readNonEmptyString(input.sandboxSessionKey) ?? readNonEmptyString(input.sessionKey) ?? readNonEmptyString(input.sessionId);
|
|
2028
|
-
const { sessionAgentId } =
|
|
2013
|
+
const { sessionAgentId } = resolveSessionAgentIdsStrict({
|
|
2029
2014
|
sessionKey: readNonEmptyString(input.sessionKey),
|
|
2030
2015
|
config: input.config,
|
|
2031
2016
|
agentId: readNonEmptyString(params.agentId)
|
|
@@ -2050,7 +2035,7 @@ function prepareCopilotAttemptContext(params, deps) {
|
|
|
2050
2035
|
runId: input.runId,
|
|
2051
2036
|
jobId: input.jobId,
|
|
2052
2037
|
agentId: sessionAgentId,
|
|
2053
|
-
sessionKey: sandboxSessionKey,
|
|
2038
|
+
sessionKey: readNonEmptyString(input.sessionKey) ?? sandboxSessionKey,
|
|
2054
2039
|
sessionId: input.sessionId,
|
|
2055
2040
|
workspaceDir: resolvedWorkspaceForSandbox,
|
|
2056
2041
|
modelProviderId: modelRef.provider,
|
|
@@ -2070,6 +2055,7 @@ async function resolveCopilotAttemptSandbox(params) {
|
|
|
2070
2055
|
const resolveSandbox = params.deps.resolveSandboxContextOverride ?? resolveSandboxContext;
|
|
2071
2056
|
const sandbox = params.input.sandbox !== void 0 ? params.input.sandbox : await resolveSandbox({
|
|
2072
2057
|
config: params.input.config,
|
|
2058
|
+
agentId: params.input.sandboxAgentId,
|
|
2073
2059
|
sessionKey: params.sandboxSessionKey,
|
|
2074
2060
|
workspaceDir: params.resolvedWorkspaceForSandbox
|
|
2075
2061
|
});
|
|
@@ -2110,7 +2096,7 @@ function buildCopilotPromptGuidance(params) {
|
|
|
2110
2096
|
sourceReplyDeliveryMode: params.attempt.sourceReplyDeliveryMode,
|
|
2111
2097
|
messageToolAvailable: callableTools.has("message")
|
|
2112
2098
|
}),
|
|
2113
|
-
|
|
2099
|
+
buildCredentialSafetyPrompt(params.attempt.disableTools !== true && callableTools.has("secrets") ? "secrets" : void 0),
|
|
2114
2100
|
params.workspaceBootstrapInstructions?.trim(),
|
|
2115
2101
|
extraSystemPrompt ? `${isMinimal ? "## Subagent Context" : "## Conversation Context"}\n${extraSystemPrompt}` : void 0
|
|
2116
2102
|
].filter((section) => section?.trim()).join("\n\n") || void 0;
|
|
@@ -2118,10 +2104,9 @@ function buildCopilotPromptGuidance(params) {
|
|
|
2118
2104
|
//#endregion
|
|
2119
2105
|
//#region extensions/copilot/src/user-input-bridge.ts
|
|
2120
2106
|
const COPILOT_USER_INPUT_QUESTION_ID = "answer";
|
|
2121
|
-
const DEFAULT_USER_INPUT_TIMEOUT_MS =
|
|
2107
|
+
const DEFAULT_USER_INPUT_TIMEOUT_MS = 9e5;
|
|
2122
2108
|
function createCopilotUserInputBridge(params) {
|
|
2123
2109
|
let pending;
|
|
2124
|
-
const gatewayCall = params.gatewayCall ?? callGatewayTool;
|
|
2125
2110
|
return {
|
|
2126
2111
|
async onUserInputRequest(request) {
|
|
2127
2112
|
pending?.abort(/* @__PURE__ */ new Error("Copilot user input request replaced"));
|
|
@@ -2138,7 +2123,7 @@ function createCopilotUserInputBridge(params) {
|
|
|
2138
2123
|
agentId: params.paramsForRun.agentId,
|
|
2139
2124
|
runId: params.paramsForRun.runId,
|
|
2140
2125
|
timeoutMs: params.paramsForRun.timeoutMs ?? DEFAULT_USER_INPUT_TIMEOUT_MS,
|
|
2141
|
-
gatewayCall,
|
|
2126
|
+
gatewayCall: params.gatewayCall,
|
|
2142
2127
|
delivery: params.paramsForRun,
|
|
2143
2128
|
promptOptions: {
|
|
2144
2129
|
intro: "Copilot needs input:",
|
|
@@ -2455,6 +2440,41 @@ async function createCopilotSessionSetup(params) {
|
|
|
2455
2440
|
};
|
|
2456
2441
|
}
|
|
2457
2442
|
//#endregion
|
|
2443
|
+
//#region extensions/copilot/src/attempt-transcript-replay.ts
|
|
2444
|
+
function readAssistantToolCallIds(message) {
|
|
2445
|
+
return message.role === "assistant" ? message.content.flatMap((part) => part.type === "toolCall" ? [part.id] : []) : [];
|
|
2446
|
+
}
|
|
2447
|
+
function isCompatibleSingletonRewrite(original, prepared) {
|
|
2448
|
+
return original.role === prepared.role && (original.role !== "assistant" || JSON.stringify(readAssistantToolCallIds(original)) === JSON.stringify(readAssistantToolCallIds(prepared)));
|
|
2449
|
+
}
|
|
2450
|
+
function projectReplayPayload(message) {
|
|
2451
|
+
switch (message.role) {
|
|
2452
|
+
case "user": return {
|
|
2453
|
+
role: message.role,
|
|
2454
|
+
content: message.content
|
|
2455
|
+
};
|
|
2456
|
+
case "assistant": return {
|
|
2457
|
+
role: message.role,
|
|
2458
|
+
content: message.content,
|
|
2459
|
+
api: message.api,
|
|
2460
|
+
model: message.model,
|
|
2461
|
+
provider: message.provider,
|
|
2462
|
+
stopReason: message.stopReason
|
|
2463
|
+
};
|
|
2464
|
+
case "toolResult": return {
|
|
2465
|
+
role: message.role,
|
|
2466
|
+
content: message.content,
|
|
2467
|
+
isError: message.isError,
|
|
2468
|
+
toolCallId: message.toolCallId,
|
|
2469
|
+
toolName: message.toolName
|
|
2470
|
+
};
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
function isCompleteToolGroup(messages, order) {
|
|
2474
|
+
const [assistant, ...results] = messages;
|
|
2475
|
+
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]);
|
|
2476
|
+
}
|
|
2477
|
+
//#endregion
|
|
2458
2478
|
//#region extensions/copilot/src/attempt-transcript-journal.ts
|
|
2459
2479
|
function readTurnTaintMetadata(message) {
|
|
2460
2480
|
const metadata = message["__openclaw"];
|
|
@@ -2511,6 +2531,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2511
2531
|
let queue = Promise.resolve();
|
|
2512
2532
|
let firstFailure;
|
|
2513
2533
|
const sdkUserPersistenceReceipts = /* @__PURE__ */ new Map();
|
|
2534
|
+
const sdkUserRecorders = /* @__PURE__ */ new Map();
|
|
2514
2535
|
let abortPromise;
|
|
2515
2536
|
let replayInvalid = false;
|
|
2516
2537
|
let initialSdkUserObserved = false;
|
|
@@ -2531,7 +2552,8 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2531
2552
|
const sdkUserPersistenceReceipt = (eventId) => {
|
|
2532
2553
|
let receipt = sdkUserPersistenceReceipts.get(eventId);
|
|
2533
2554
|
if (!receipt) {
|
|
2534
|
-
receipt =
|
|
2555
|
+
receipt = createDeferred();
|
|
2556
|
+
receipt.promise.catch(() => void 0);
|
|
2535
2557
|
sdkUserPersistenceReceipts.set(eventId, receipt);
|
|
2536
2558
|
if (firstFailure) receipt.reject(firstFailure);
|
|
2537
2559
|
}
|
|
@@ -2548,7 +2570,8 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2548
2570
|
const hooked = runAgentHarnessBeforeMessageWriteHook({
|
|
2549
2571
|
message: structuredClone(message),
|
|
2550
2572
|
agentId: target.agentId,
|
|
2551
|
-
sessionKey: target.sessionKey
|
|
2573
|
+
sessionKey: target.sessionKey,
|
|
2574
|
+
prepareAssistantTranscriptMessage: options.singleton && !hiddenTurn ? params.attempt.prepareAssistantTranscriptMessage : void 0
|
|
2552
2575
|
});
|
|
2553
2576
|
if (!hooked) return;
|
|
2554
2577
|
if (!isDeepStrictEqual(originalReplayPayload, projectReplayPayload(hooked))) replayInvalid = true;
|
|
@@ -2558,7 +2581,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2558
2581
|
toolCallId: message.toolCallId,
|
|
2559
2582
|
toolName: message.toolName
|
|
2560
2583
|
} : {};
|
|
2561
|
-
const
|
|
2584
|
+
const projected = projectDisplay({
|
|
2562
2585
|
...hooked,
|
|
2563
2586
|
...toolIdentity,
|
|
2564
2587
|
...taintMetadata ? { __openclaw: {
|
|
@@ -2566,8 +2589,13 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2566
2589
|
...taintMetadata
|
|
2567
2590
|
} } : {},
|
|
2568
2591
|
...idempotencyKey ? { idempotencyKey } : {},
|
|
2592
|
+
...message.role === "user" && message.provenance ? { provenance: message.provenance } : {},
|
|
2569
2593
|
...message.display === false ? { display: false } : {}
|
|
2570
2594
|
});
|
|
2595
|
+
const prepared = message.role === "user" ? restorePreparedUserTurnOperationalMetaForRuntime({
|
|
2596
|
+
runtimeMessage: projected,
|
|
2597
|
+
preparedMessage: message
|
|
2598
|
+
}) : projected;
|
|
2571
2599
|
return options.singleton && !isCompatibleSingletonRewrite(message, prepared) ? void 0 : prepared;
|
|
2572
2600
|
};
|
|
2573
2601
|
const append = async (write) => {
|
|
@@ -2579,9 +2607,13 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2579
2607
|
message: write.message,
|
|
2580
2608
|
prepareMessageAfterIdempotencyCheck: () => prepare(write, { singleton: true })
|
|
2581
2609
|
});
|
|
2582
|
-
if (outcome.kind === "suppressed")
|
|
2610
|
+
if (outcome.kind === "suppressed") {
|
|
2611
|
+
write.recorder?.markBlocked();
|
|
2612
|
+
return;
|
|
2613
|
+
}
|
|
2583
2614
|
if (outcome.kind === "rejected") throw new Error("Transcript session changed before singleton append");
|
|
2584
2615
|
if (!isDeepStrictEqual(projectReplayPayload(write.message), projectReplayPayload(outcome.result.message))) replayInvalid = true;
|
|
2616
|
+
if (outcome.result.message.role === "user") write.recorder?.markRuntimePersisted(outcome.result.message, outcome.result.anchor, { appended: outcome.result.appended });
|
|
2585
2617
|
return outcome.result;
|
|
2586
2618
|
};
|
|
2587
2619
|
const appendToolGroup = async (group) => {
|
|
@@ -2649,6 +2681,20 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2649
2681
|
}
|
|
2650
2682
|
};
|
|
2651
2683
|
return {
|
|
2684
|
+
async sendSdkUser(send, recorder) {
|
|
2685
|
+
if (!recorder) return await send();
|
|
2686
|
+
const registration = createDeferred();
|
|
2687
|
+
schedule(() => registration.promise);
|
|
2688
|
+
try {
|
|
2689
|
+
const messageId = await send();
|
|
2690
|
+
sdkUserRecorders.set(messageId, recorder);
|
|
2691
|
+
recorder.markSentToProvider?.();
|
|
2692
|
+
recorder.markRuntimePersistencePending(sdkUserPersistenceReceipt(messageId).promise);
|
|
2693
|
+
return messageId;
|
|
2694
|
+
} finally {
|
|
2695
|
+
registration.resolve();
|
|
2696
|
+
}
|
|
2697
|
+
},
|
|
2652
2698
|
markReplayIncomplete() {
|
|
2653
2699
|
replayInvalid = true;
|
|
2654
2700
|
},
|
|
@@ -2687,7 +2733,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2687
2733
|
accept(outcome);
|
|
2688
2734
|
persistedInitialUser = persisted;
|
|
2689
2735
|
terminalAnchor = outcome.anchor;
|
|
2690
|
-
recorder.markRuntimePersisted(persisted, outcome.anchor);
|
|
2736
|
+
recorder.markRuntimePersisted(persisted, outcome.anchor, { appended: outcome.appended });
|
|
2691
2737
|
params.attempt.onUserMessagePersisted?.(persisted);
|
|
2692
2738
|
await publish(outcome.appended);
|
|
2693
2739
|
})();
|
|
@@ -2711,9 +2757,16 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2711
2757
|
}
|
|
2712
2758
|
initialSdkUserObserved = true;
|
|
2713
2759
|
schedule(async () => {
|
|
2760
|
+
const recorder = sdkUserRecorders.get(input.eventId);
|
|
2761
|
+
sdkUserRecorders.delete(input.eventId);
|
|
2762
|
+
const preparedMessage = await recorder?.resolveMessage();
|
|
2714
2763
|
const write = {
|
|
2715
2764
|
eventId: input.eventId,
|
|
2716
|
-
message:
|
|
2765
|
+
message: restorePreparedUserTurnOperationalMetaForRuntime({
|
|
2766
|
+
runtimeMessage: input.message,
|
|
2767
|
+
preparedMessage
|
|
2768
|
+
}),
|
|
2769
|
+
recorder
|
|
2717
2770
|
};
|
|
2718
2771
|
if (pendingTools) {
|
|
2719
2772
|
deferredUserWrites.push(write);
|
|
@@ -2783,10 +2836,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2783
2836
|
replayInvalid = true;
|
|
2784
2837
|
ownAssistant(group.assistantKey, false);
|
|
2785
2838
|
} else {
|
|
2786
|
-
for (const result of results)
|
|
2787
|
-
const didAppend = accept(result);
|
|
2788
|
-
appended ||= didAppend;
|
|
2789
|
-
}
|
|
2839
|
+
for (const result of results) appended = accept(result) || appended;
|
|
2790
2840
|
ownAssistant(group.assistantKey, true, results.at(-1)?.anchor);
|
|
2791
2841
|
}
|
|
2792
2842
|
pendingTools = void 0;
|
|
@@ -2798,8 +2848,7 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2798
2848
|
if (write.eventId) sdkUserPersistenceReceipt(write.eventId).reject(/* @__PURE__ */ new Error("Copilot steering user write was suppressed"));
|
|
2799
2849
|
continue;
|
|
2800
2850
|
}
|
|
2801
|
-
|
|
2802
|
-
appended ||= didAppend;
|
|
2851
|
+
appended = accept(outcome) || appended;
|
|
2803
2852
|
if (write.eventId) deferredReceipts.push(sdkUserPersistenceReceipt(write.eventId));
|
|
2804
2853
|
}
|
|
2805
2854
|
await publish(appended);
|
|
@@ -2821,31 +2870,6 @@ function createAttemptTranscriptJournal(params) {
|
|
|
2821
2870
|
})
|
|
2822
2871
|
};
|
|
2823
2872
|
}
|
|
2824
|
-
function createPersistenceReceipt() {
|
|
2825
|
-
let settled = false;
|
|
2826
|
-
let rejectPromise;
|
|
2827
|
-
let resolvePromise;
|
|
2828
|
-
const promise = new Promise((resolve, reject) => {
|
|
2829
|
-
resolvePromise = resolve;
|
|
2830
|
-
rejectPromise = reject;
|
|
2831
|
-
});
|
|
2832
|
-
promise.catch(() => void 0);
|
|
2833
|
-
return {
|
|
2834
|
-
promise,
|
|
2835
|
-
reject(error) {
|
|
2836
|
-
if (!settled) {
|
|
2837
|
-
settled = true;
|
|
2838
|
-
rejectPromise?.(error);
|
|
2839
|
-
}
|
|
2840
|
-
},
|
|
2841
|
-
resolve() {
|
|
2842
|
-
if (!settled) {
|
|
2843
|
-
settled = true;
|
|
2844
|
-
resolvePromise?.();
|
|
2845
|
-
}
|
|
2846
|
-
}
|
|
2847
|
-
};
|
|
2848
|
-
}
|
|
2849
2873
|
function resolveTranscriptTarget(attempt) {
|
|
2850
2874
|
const sessionId = normalizeOptionalString(attempt.sessionTarget?.sessionId);
|
|
2851
2875
|
const sessionKey = normalizeOptionalString(attempt.sessionTarget?.sessionKey);
|
|
@@ -2863,35 +2887,6 @@ function resolveTranscriptTarget(attempt) {
|
|
|
2863
2887
|
...agentId ? { agentId } : {}
|
|
2864
2888
|
};
|
|
2865
2889
|
}
|
|
2866
|
-
function readAssistantToolCallIds(message) {
|
|
2867
|
-
return message.role === "assistant" ? message.content.flatMap((part) => part.type === "toolCall" ? [part.id] : []) : [];
|
|
2868
|
-
}
|
|
2869
|
-
function isCompatibleSingletonRewrite(original, prepared) {
|
|
2870
|
-
return original.role === prepared.role && (original.role !== "assistant" || JSON.stringify(readAssistantToolCallIds(original)) === JSON.stringify(readAssistantToolCallIds(prepared)));
|
|
2871
|
-
}
|
|
2872
|
-
function projectReplayPayload(message) {
|
|
2873
|
-
switch (message.role) {
|
|
2874
|
-
case "user": return {
|
|
2875
|
-
role: message.role,
|
|
2876
|
-
content: message.content
|
|
2877
|
-
};
|
|
2878
|
-
case "assistant": return {
|
|
2879
|
-
role: message.role,
|
|
2880
|
-
content: message.content,
|
|
2881
|
-
api: message.api,
|
|
2882
|
-
model: message.model,
|
|
2883
|
-
provider: message.provider,
|
|
2884
|
-
stopReason: message.stopReason
|
|
2885
|
-
};
|
|
2886
|
-
case "toolResult": return {
|
|
2887
|
-
role: message.role,
|
|
2888
|
-
content: message.content,
|
|
2889
|
-
isError: message.isError,
|
|
2890
|
-
toolCallId: message.toolCallId,
|
|
2891
|
-
toolName: message.toolName
|
|
2892
|
-
};
|
|
2893
|
-
}
|
|
2894
|
-
}
|
|
2895
2890
|
function readIdempotencyKey(message) {
|
|
2896
2891
|
const key = message.idempotencyKey;
|
|
2897
2892
|
return typeof key === "string" && key ? key : void 0;
|
|
@@ -2899,10 +2894,6 @@ function readIdempotencyKey(message) {
|
|
|
2899
2894
|
function isCurrentJournalIdentity(key, params) {
|
|
2900
2895
|
return key === `${params.attempt.runId}:user` || key.startsWith(`copilot-sdk:${params.sdkSessionId}:`);
|
|
2901
2896
|
}
|
|
2902
|
-
function isCompleteToolGroup(messages, order) {
|
|
2903
|
-
const [assistant, ...results] = messages;
|
|
2904
|
-
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]);
|
|
2905
|
-
}
|
|
2906
2897
|
function isSameUserTurn(candidate, current, currentRunUserKey) {
|
|
2907
2898
|
if (candidate?.role !== "user" || !current) return false;
|
|
2908
2899
|
if (candidate === current) return true;
|
|
@@ -3061,7 +3052,6 @@ async function runCopilotExecution(context) {
|
|
|
3061
3052
|
let timedOut = false;
|
|
3062
3053
|
let promptError;
|
|
3063
3054
|
let sdkSessionId;
|
|
3064
|
-
let sessionIdUsed = input.sessionId;
|
|
3065
3055
|
let nativeSessionCreatedFresh = false;
|
|
3066
3056
|
let nativeSessionHistoryValidated = false;
|
|
3067
3057
|
let disconnectError;
|
|
@@ -3083,6 +3073,7 @@ async function runCopilotExecution(context) {
|
|
|
3083
3073
|
let resumeFailureRecovered = false;
|
|
3084
3074
|
let yieldDetected = false;
|
|
3085
3075
|
let yieldAcknowledgment;
|
|
3076
|
+
const acceptedSessionSpawns = [];
|
|
3086
3077
|
let lastToolError;
|
|
3087
3078
|
const hostObserveToolTerminal = input.observeToolTerminal;
|
|
3088
3079
|
const observeToolTerminal = hostObserveToolTerminal ? (observation) => {
|
|
@@ -3122,15 +3113,13 @@ async function runCopilotExecution(context) {
|
|
|
3122
3113
|
messagesSnapshot: messages,
|
|
3123
3114
|
now,
|
|
3124
3115
|
promptError: void 0,
|
|
3125
|
-
sdkSessionId: void 0
|
|
3126
|
-
sessionIdUsed: input.sessionId
|
|
3116
|
+
sdkSessionId: void 0
|
|
3127
3117
|
}));
|
|
3128
3118
|
return finishAttempt(createResult(input, {
|
|
3129
3119
|
messagesSnapshot: messages,
|
|
3130
3120
|
now,
|
|
3131
3121
|
promptError: createPromptError$1("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error),
|
|
3132
|
-
sdkSessionId: void 0
|
|
3133
|
-
sessionIdUsed: input.sessionId
|
|
3122
|
+
sdkSessionId: void 0
|
|
3134
3123
|
}));
|
|
3135
3124
|
}
|
|
3136
3125
|
hookContext.workspaceDir = effectiveWorkspaceDir;
|
|
@@ -3142,8 +3131,7 @@ async function runCopilotExecution(context) {
|
|
|
3142
3131
|
messagesSnapshot: messages,
|
|
3143
3132
|
now,
|
|
3144
3133
|
promptError: createPromptError$1("sandbox_cwd_override_unsupported", "[copilot-attempt] cwd override is not supported for sandboxed Copilot runs; omit cwd or use the agent workspace as cwd"),
|
|
3145
|
-
sdkSessionId: void 0
|
|
3146
|
-
sessionIdUsed: input.sessionId
|
|
3134
|
+
sdkSessionId: void 0
|
|
3147
3135
|
}));
|
|
3148
3136
|
}
|
|
3149
3137
|
const effectiveCwd = sandbox?.enabled ? effectiveWorkspaceDir : requestedCwd ?? effectiveWorkspaceDir;
|
|
@@ -3171,8 +3159,7 @@ async function runCopilotExecution(context) {
|
|
|
3171
3159
|
messagesSnapshot: messages,
|
|
3172
3160
|
now,
|
|
3173
3161
|
promptError: createPromptError$1("model_not_supported", toCopilotError(error).message, error),
|
|
3174
|
-
sdkSessionId: void 0
|
|
3175
|
-
sessionIdUsed: input.sessionId
|
|
3162
|
+
sdkSessionId: void 0
|
|
3176
3163
|
}));
|
|
3177
3164
|
}
|
|
3178
3165
|
const cleanupByokProxy = byokProxy?.close;
|
|
@@ -3208,19 +3195,29 @@ async function runCopilotExecution(context) {
|
|
|
3208
3195
|
yieldDetected = true;
|
|
3209
3196
|
yieldAcknowledgment = acknowledgment;
|
|
3210
3197
|
},
|
|
3211
|
-
onToolCompleted: ({ args, error, result, startedAt, toolCallId, toolName }) =>
|
|
3212
|
-
toolName
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3198
|
+
onToolCompleted: async ({ args, error, result, startedAt, toolCallId, toolName }) => {
|
|
3199
|
+
const acceptedSessionSpawnDetails = toolName === "sessions_spawn" && !error ? asOptionalRecord(asOptionalRecord(result)?.details) : void 0;
|
|
3200
|
+
const runId = normalizeOptionalString(acceptedSessionSpawnDetails?.runId);
|
|
3201
|
+
const childSessionKey = normalizeOptionalString(acceptedSessionSpawnDetails?.childSessionKey);
|
|
3202
|
+
if (acceptedSessionSpawnDetails?.status === "accepted" && runId && childSessionKey) acceptedSessionSpawns.push({
|
|
3203
|
+
runId,
|
|
3204
|
+
childSessionKey,
|
|
3205
|
+
expectsCompletionMessage: acceptedSessionSpawnDetails.expectsCompletionMessage === true
|
|
3206
|
+
});
|
|
3207
|
+
await runAgentHarnessAfterToolCallHook({
|
|
3208
|
+
toolName,
|
|
3209
|
+
toolCallId,
|
|
3210
|
+
runId: input.runId,
|
|
3211
|
+
agentId: sessionAgentId,
|
|
3212
|
+
sessionId: input.sessionId,
|
|
3213
|
+
sessionKey: hookContext.sessionKey,
|
|
3214
|
+
channelId: hookContext.channelId,
|
|
3215
|
+
startArgs: args,
|
|
3216
|
+
...result !== void 0 ? { result } : {},
|
|
3217
|
+
...error ? { error } : {},
|
|
3218
|
+
startedAt
|
|
3219
|
+
});
|
|
3220
|
+
}
|
|
3224
3221
|
});
|
|
3225
3222
|
cleanupToolBridge = toolBridge.cleanup;
|
|
3226
3223
|
codeModeEngaged = toolBridge.codeModeEngaged;
|
|
@@ -3231,8 +3228,7 @@ async function runCopilotExecution(context) {
|
|
|
3231
3228
|
messagesSnapshot: messages,
|
|
3232
3229
|
now,
|
|
3233
3230
|
promptError: createPromptError$1("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error),
|
|
3234
|
-
sdkSessionId: void 0
|
|
3235
|
-
sessionIdUsed: input.sessionId
|
|
3231
|
+
sdkSessionId: void 0
|
|
3236
3232
|
}));
|
|
3237
3233
|
}
|
|
3238
3234
|
handle = await deps.pool.acquire(poolAcquire.key, poolAcquire.options);
|
|
@@ -3284,7 +3280,6 @@ async function runCopilotExecution(context) {
|
|
|
3284
3280
|
sessionRef.current = session;
|
|
3285
3281
|
sdkSessionId = readNonEmptyString(session.sessionId) ?? readNonEmptyString(session.id) ?? (resumeFailureRecovered ? void 0 : resumeSessionId);
|
|
3286
3282
|
if (!sdkSessionId) throw createPromptError$1("transcript_persistence_failed", "[copilot-attempt] canonical transcript persistence requires the Copilot SDK session id");
|
|
3287
|
-
sessionIdUsed = sdkSessionId ?? input.sessionId;
|
|
3288
3283
|
if (sdkSessionId && deps.onSessionEstablished && !settledToolFinalization) try {
|
|
3289
3284
|
deps.onSessionEstablished({
|
|
3290
3285
|
compactionSessionConfig,
|
|
@@ -3346,6 +3341,7 @@ async function runCopilotExecution(context) {
|
|
|
3346
3341
|
abortActiveSession,
|
|
3347
3342
|
bridge,
|
|
3348
3343
|
canAcceptSteering: () => initialSdkUserValidated,
|
|
3344
|
+
startedAtMs: input.startedAtMs,
|
|
3349
3345
|
input,
|
|
3350
3346
|
isAborted: () => aborted,
|
|
3351
3347
|
isSettled: () => settled,
|
|
@@ -3384,25 +3380,27 @@ async function runCopilotExecution(context) {
|
|
|
3384
3380
|
if (!promptError && !timedOut && !aborted && snap.streamError) promptError = snap.streamError;
|
|
3385
3381
|
}
|
|
3386
3382
|
} catch (error) {
|
|
3387
|
-
if (!aborted)
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3383
|
+
if (!aborted) {
|
|
3384
|
+
if (isSdkSendAndWaitTimeoutError(error)) {
|
|
3385
|
+
timedOut = true;
|
|
3386
|
+
timedOutDuringCompaction = bridge?.isCompacting() === true;
|
|
3387
|
+
try {
|
|
3388
|
+
await bridge?.awaitDeltaChain();
|
|
3389
|
+
} catch {}
|
|
3390
|
+
await bridge?.awaitAgentEventChain();
|
|
3391
|
+
bridge?.flushTranscriptProjection();
|
|
3392
|
+
try {
|
|
3393
|
+
await transcriptJournal?.barrier("timeout");
|
|
3394
|
+
} catch (transcriptError) {
|
|
3395
|
+
promptError = toCopilotError(transcriptError);
|
|
3396
|
+
}
|
|
3397
|
+
} else try {
|
|
3398
|
+
bridge?.flushTranscriptProjection();
|
|
3399
|
+
await transcriptJournal?.barrier("attempt error");
|
|
3400
|
+
promptError = toCopilotError(error);
|
|
3397
3401
|
} catch (transcriptError) {
|
|
3398
3402
|
promptError = toCopilotError(transcriptError);
|
|
3399
3403
|
}
|
|
3400
|
-
} else try {
|
|
3401
|
-
bridge?.flushTranscriptProjection();
|
|
3402
|
-
await transcriptJournal?.barrier("attempt error");
|
|
3403
|
-
promptError = toCopilotError(error);
|
|
3404
|
-
} catch (transcriptError) {
|
|
3405
|
-
promptError = toCopilotError(transcriptError);
|
|
3406
3404
|
}
|
|
3407
3405
|
} finally {
|
|
3408
3406
|
settled = true;
|
|
@@ -3473,6 +3471,7 @@ async function runCopilotExecution(context) {
|
|
|
3473
3471
|
}
|
|
3474
3472
|
}
|
|
3475
3473
|
return await completeCopilotAttempt({
|
|
3474
|
+
acceptedSessionSpawns,
|
|
3476
3475
|
aborted,
|
|
3477
3476
|
attemptStartedAt,
|
|
3478
3477
|
bridge,
|
|
@@ -3493,7 +3492,6 @@ async function runCopilotExecution(context) {
|
|
|
3493
3492
|
resumeFailureRecovered,
|
|
3494
3493
|
sdkSessionId,
|
|
3495
3494
|
sentTurnStarted,
|
|
3496
|
-
sessionIdUsed,
|
|
3497
3495
|
settledFinalizationAssistantCompleted,
|
|
3498
3496
|
settledToolFinalization,
|
|
3499
3497
|
timedOut,
|
|
@@ -3515,8 +3513,7 @@ async function runCopilotAttempt(params, deps) {
|
|
|
3515
3513
|
messagesSnapshot: messages,
|
|
3516
3514
|
now,
|
|
3517
3515
|
promptError: void 0,
|
|
3518
|
-
sdkSessionId: void 0
|
|
3519
|
-
sessionIdUsed: input.sessionId
|
|
3516
|
+
sdkSessionId: void 0
|
|
3520
3517
|
}));
|
|
3521
3518
|
try {
|
|
3522
3519
|
resolveCopilotProvider({
|
|
@@ -3529,8 +3526,7 @@ async function runCopilotAttempt(params, deps) {
|
|
|
3529
3526
|
messagesSnapshot: messages,
|
|
3530
3527
|
now,
|
|
3531
3528
|
promptError: createPromptError$1("model_not_supported", toCopilotError(error).message, error),
|
|
3532
|
-
sdkSessionId: void 0
|
|
3533
|
-
sessionIdUsed: input.sessionId
|
|
3529
|
+
sdkSessionId: void 0
|
|
3534
3530
|
}));
|
|
3535
3531
|
}
|
|
3536
3532
|
const settledFinalizationSessionId = settledToolFinalization ? readNonEmptyString(input.initialReplayState?.sdkSessionId) : void 0;
|
|
@@ -3538,8 +3534,7 @@ async function runCopilotAttempt(params, deps) {
|
|
|
3538
3534
|
messagesSnapshot: messages,
|
|
3539
3535
|
now,
|
|
3540
3536
|
promptError: createPromptError$1("settled_finalization_session_unavailable", "[copilot-attempt] settled tool finalization requires the existing Copilot SDK session"),
|
|
3541
|
-
sdkSessionId: void 0
|
|
3542
|
-
sessionIdUsed: input.sessionId
|
|
3537
|
+
sdkSessionId: void 0
|
|
3543
3538
|
}));
|
|
3544
3539
|
return await runCopilotExecution({
|
|
3545
3540
|
params,
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { filterStringRecord, normalizeOptionalString, readNonEmptyStringPreservingWhitespace } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
2
2
|
import { buildAgentHookContextChannelFields, compactWithSafetyTimeout, getModelProviderRequestTransport, projectSettledTurnFinalizationAttemptResult, resolveCompactionTimeoutMs, runAgentHarnessAfterCompactionHook, runAgentHarnessBeforeCompactionHook } from "openclaw/plugin-sdk/agent-harness-runtime";
|
|
3
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { join, resolve } from "node:path";
|
|
6
6
|
import { createServer } from "node:http";
|
|
7
7
|
import { Readable } from "node:stream";
|
|
8
|
-
import {
|
|
8
|
+
import { pipeline } from "node:stream/promises";
|
|
9
9
|
import { fetchWithSsrFGuard, isBlockedHostnameOrIp } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
10
10
|
import { isNonSecretApiKeyMarker } from "openclaw/plugin-sdk/provider-auth";
|
|
11
11
|
//#region extensions/copilot/src/auth-bridge.ts
|
|
@@ -157,7 +157,8 @@ function resolveCopilotHome(args) {
|
|
|
157
157
|
if (args.explicit) return resolve(args.explicit);
|
|
158
158
|
if (args.agentDir) return resolve(join(args.agentDir, "copilot"));
|
|
159
159
|
const openClawHome = readNonEmptyStringPreservingWhitespace(args.env.OPENCLAW_HOME);
|
|
160
|
-
|
|
160
|
+
const rootHome = openClawHome ? resolve(openClawHome) : safeHomeDir(args.homeDir);
|
|
161
|
+
return resolve(join(rootHome, ".openclaw", "agents", args.agentId, "copilot"));
|
|
161
162
|
}
|
|
162
163
|
function safeHomeDir(homeDir) {
|
|
163
164
|
try {
|
|
@@ -205,6 +206,7 @@ function tokenFingerprint(token) {
|
|
|
205
206
|
//#endregion
|
|
206
207
|
//#region extensions/copilot/src/byok-proxy.ts
|
|
207
208
|
const LOOPBACK_HOST = "127.0.0.1";
|
|
209
|
+
const PROXY_CREDENTIAL_HEADER_PREFIX = "x-openclaw-copilot-byok-";
|
|
208
210
|
async function createCopilotByokProxy(resolvedProvider) {
|
|
209
211
|
if (resolvedProvider.mode !== "byok") return;
|
|
210
212
|
const providerConfig = resolvedProvider.provider;
|
|
@@ -214,6 +216,7 @@ async function createCopilotByokProxy(resolvedProvider) {
|
|
|
214
216
|
const targetPathPrefix = trimTrailingSlash(targetBaseUrl.pathname);
|
|
215
217
|
const proxyPathPrefix = `/${nonce}${targetPathPrefix}`;
|
|
216
218
|
const acceptsAzureSdkPaths = providerConfig.type === "azure";
|
|
219
|
+
const proxyCredentialHeader = acceptsAzureSdkPaths ? createProxyCredentialHeaderName(providerConfig.headers) : void 0;
|
|
217
220
|
const upstreamBearerAuthorization = resolveUpstreamBearerAuthorization(providerConfig);
|
|
218
221
|
const activeFetches = /* @__PURE__ */ new Set();
|
|
219
222
|
const server = createServer((req, res) => {
|
|
@@ -221,6 +224,8 @@ async function createCopilotByokProxy(resolvedProvider) {
|
|
|
221
224
|
acceptsAzureSdkPaths,
|
|
222
225
|
activeFetches,
|
|
223
226
|
proxyPathPrefix,
|
|
227
|
+
proxyCredential: nonce,
|
|
228
|
+
proxyCredentialHeader,
|
|
224
229
|
targetBaseUrl,
|
|
225
230
|
targetPathPrefix,
|
|
226
231
|
upstreamBearerAuthorization
|
|
@@ -245,7 +250,8 @@ async function createCopilotByokProxy(resolvedProvider) {
|
|
|
245
250
|
...resolvedProvider,
|
|
246
251
|
provider: {
|
|
247
252
|
...providerConfig,
|
|
248
|
-
baseUrl: sdkBaseUrl
|
|
253
|
+
baseUrl: sdkBaseUrl,
|
|
254
|
+
...proxyCredentialHeader ? { headers: buildSdkProviderHeaders(providerConfig.headers, proxyCredentialHeader, nonce) } : {}
|
|
249
255
|
}
|
|
250
256
|
},
|
|
251
257
|
close: async () => {
|
|
@@ -267,9 +273,9 @@ async function handleProxyRequest(req, res, params) {
|
|
|
267
273
|
if (!res.writableEnded) abortUpstream();
|
|
268
274
|
});
|
|
269
275
|
try {
|
|
270
|
-
const
|
|
276
|
+
const isNonceProtected = isNonceProtectedProxyRequest(req, params.proxyPathPrefix);
|
|
271
277
|
const url = resolveTargetUrl(req, params);
|
|
272
|
-
if (!url) {
|
|
278
|
+
if (!url || !isNonceProtected && (!params.proxyCredentialHeader || !hasValidProxyCredential(req, params.proxyCredentialHeader, params.proxyCredential))) {
|
|
273
279
|
res.writeHead(404);
|
|
274
280
|
res.end("Not found");
|
|
275
281
|
return;
|
|
@@ -279,9 +285,12 @@ async function handleProxyRequest(req, res, params) {
|
|
|
279
285
|
url: url.toString(),
|
|
280
286
|
init: {
|
|
281
287
|
method: req.method,
|
|
282
|
-
headers: buildProxyRequestHeaders(req.headers, {
|
|
288
|
+
headers: buildProxyRequestHeaders(req.headers, {
|
|
289
|
+
upstreamBearerAuthorization: isNonceProtected ? params.upstreamBearerAuthorization : void 0,
|
|
290
|
+
proxyCredentialHeader: params.proxyCredentialHeader
|
|
291
|
+
}),
|
|
283
292
|
signal: upstreamAbort.signal,
|
|
284
|
-
...body ? { body
|
|
293
|
+
...body ? { body } : {}
|
|
285
294
|
},
|
|
286
295
|
auditContext: "copilot-byok-provider",
|
|
287
296
|
requireHttps: true
|
|
@@ -291,7 +300,7 @@ async function handleProxyRequest(req, res, params) {
|
|
|
291
300
|
res.end();
|
|
292
301
|
return;
|
|
293
302
|
}
|
|
294
|
-
await
|
|
303
|
+
await pipeline(Readable.fromWeb(guarded.response.body), res);
|
|
295
304
|
} catch (error) {
|
|
296
305
|
if (res.destroyed || res.writableEnded) return;
|
|
297
306
|
if (res.headersSent) {
|
|
@@ -328,28 +337,42 @@ function isNonceProtectedProxyRequest(req, proxyPathPrefix) {
|
|
|
328
337
|
const incomingUrl = new URL(req.url ?? "/", `http://${LOOPBACK_HOST}`);
|
|
329
338
|
return incomingUrl.pathname === proxyPathPrefix || incomingUrl.pathname.startsWith(`${proxyPathPrefix}/`);
|
|
330
339
|
}
|
|
340
|
+
function hasValidProxyCredential(req, headerName, expected) {
|
|
341
|
+
const received = req.headers[headerName];
|
|
342
|
+
if (typeof received !== "string") return false;
|
|
343
|
+
const receivedBytes = Buffer.from(received);
|
|
344
|
+
const expectedBytes = Buffer.from(expected);
|
|
345
|
+
return receivedBytes.length === expectedBytes.length && timingSafeEqual(receivedBytes, expectedBytes);
|
|
346
|
+
}
|
|
331
347
|
async function readBody(req) {
|
|
332
348
|
const chunks = [];
|
|
333
349
|
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
334
350
|
return chunks.length > 0 ? Buffer.concat(chunks) : void 0;
|
|
335
351
|
}
|
|
336
|
-
function
|
|
337
|
-
const copy = new Uint8Array(body.byteLength);
|
|
338
|
-
copy.set(body);
|
|
339
|
-
return copy;
|
|
340
|
-
}
|
|
341
|
-
function normalizeProxyRequestHeaders(headers) {
|
|
352
|
+
function normalizeProxyRequestHeaders(headers, proxyCredentialHeader) {
|
|
342
353
|
const out = {};
|
|
343
354
|
for (const [key, value] of Object.entries(headers)) {
|
|
344
|
-
if (isHopByHopHeader(key) || key.toLowerCase() === "accept-encoding") continue;
|
|
355
|
+
if (isHopByHopHeader(key) || key.toLowerCase() === "accept-encoding" || key.toLowerCase() === proxyCredentialHeader) continue;
|
|
345
356
|
const normalized = normalizeHeaderValue(value);
|
|
346
357
|
if (normalized !== void 0) out[key] = normalized;
|
|
347
358
|
}
|
|
348
359
|
out["accept-encoding"] = "identity";
|
|
349
360
|
return out;
|
|
350
361
|
}
|
|
362
|
+
function buildSdkProviderHeaders(headers, proxyCredentialHeader, proxyCredential) {
|
|
363
|
+
return {
|
|
364
|
+
...headers,
|
|
365
|
+
[proxyCredentialHeader]: proxyCredential
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function createProxyCredentialHeaderName(headers) {
|
|
369
|
+
for (;;) {
|
|
370
|
+
const name = `${PROXY_CREDENTIAL_HEADER_PREFIX}${randomBytes(12).toString("hex")}`;
|
|
371
|
+
if (!headers || !hasHeader(headers, name)) return name;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
351
374
|
function buildProxyRequestHeaders(headers, params) {
|
|
352
|
-
const out = normalizeProxyRequestHeaders(headers);
|
|
375
|
+
const out = normalizeProxyRequestHeaders(headers, params.proxyCredentialHeader);
|
|
353
376
|
if (params.upstreamBearerAuthorization && !hasHeader(out, "authorization")) out["authorization"] = params.upstreamBearerAuthorization;
|
|
354
377
|
return out;
|
|
355
378
|
}
|
|
@@ -504,7 +527,8 @@ function assertByokEndpointHostAllowed(baseUrl) {
|
|
|
504
527
|
if (url.protocol !== "https:") throw new Error(COPILOT_BYOK_ENDPOINT_POLICY_ERROR);
|
|
505
528
|
if (url.username || url.password) throw new Error(COPILOT_BYOK_ENDPOINT_POLICY_ERROR);
|
|
506
529
|
for (const key of url.searchParams.keys()) if (CREDENTIAL_QUERY_PARAM_NAMES.has(normalizeCredentialQueryParamName(key))) throw new Error(COPILOT_BYOK_ENDPOINT_POLICY_ERROR);
|
|
507
|
-
|
|
530
|
+
const hostname = url.hostname.toLowerCase().replace(/\.+$/, "");
|
|
531
|
+
if (isBlockedHostnameOrIp(hostname)) throw new Error(COPILOT_BYOK_ENDPOINT_POLICY_ERROR);
|
|
508
532
|
}
|
|
509
533
|
function normalizeCredentialQueryParamName(name) {
|
|
510
534
|
const stripped = name.replace(QUERY_PARAM_NAME_SEPARATOR_RE, "");
|
|
@@ -827,7 +851,7 @@ function createCopilotAgentHarness(options) {
|
|
|
827
851
|
async function getPool() {
|
|
828
852
|
if (options?.pool) return options.pool;
|
|
829
853
|
if (!poolPromise) poolPromise = (async () => {
|
|
830
|
-
const { createCopilotClientPool } = await import("./runtime-
|
|
854
|
+
const { createCopilotClientPool } = await import("./runtime-LtZ5NAjV.js");
|
|
831
855
|
createdPool = createCopilotClientPool(options?.poolOptions);
|
|
832
856
|
return createdPool;
|
|
833
857
|
})();
|
|
@@ -864,7 +888,7 @@ function createCopilotAgentHarness(options) {
|
|
|
864
888
|
async function runHarnessAttempt(params, operation) {
|
|
865
889
|
const attemptPromise = (async () => {
|
|
866
890
|
if (disposed) throw new Error("[copilot] harness has been disposed; cannot start new attempts");
|
|
867
|
-
const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-
|
|
891
|
+
const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-BJ2mxTkh.js");
|
|
868
892
|
if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
|
|
869
893
|
const pool = await getPool();
|
|
870
894
|
if (disposed) throw new Error("[copilot] harness was disposed while starting an attempt");
|
|
@@ -995,7 +1019,7 @@ function createCopilotAgentHarness(options) {
|
|
|
995
1019
|
async function runIsolatedCompletionV2(params) {
|
|
996
1020
|
const completionPromise = (async () => {
|
|
997
1021
|
if (disposed) throw new Error("[copilot] harness has been disposed; cannot start isolated completion");
|
|
998
|
-
const { runCopilotIsolatedCompletion } = await import("./isolated-completion-
|
|
1022
|
+
const { runCopilotIsolatedCompletion } = await import("./isolated-completion-OGrJ9ITR.js");
|
|
999
1023
|
if (disposed) throw new Error("[copilot] harness was disposed while starting isolated completion");
|
|
1000
1024
|
return await runCopilotIsolatedCompletion(params, async () => {
|
|
1001
1025
|
const pool = await getPool();
|
|
@@ -1052,7 +1076,8 @@ function createCopilotAgentHarness(options) {
|
|
|
1052
1076
|
runAttempt: (params) => runHarnessAttempt(params, "attempt"),
|
|
1053
1077
|
runIsolatedCompletionV2,
|
|
1054
1078
|
finalizeSettledTurn: async ({ attempt }) => {
|
|
1055
|
-
|
|
1079
|
+
const result = await runHarnessAttempt(attempt, "settled-tool-finalization");
|
|
1080
|
+
return projectSettledTurnFinalizationAttemptResult(result);
|
|
1056
1081
|
},
|
|
1057
1082
|
async reset(params) {
|
|
1058
1083
|
const openclawSessionId = typeof params.sessionId === "string" ? params.sessionId : void 0;
|
|
@@ -1086,7 +1111,7 @@ function createCopilotAgentHarness(options) {
|
|
|
1086
1111
|
};
|
|
1087
1112
|
const tracked = trackedSessions.get(openclawSessionId);
|
|
1088
1113
|
const currentCompactKey = computeCompactRequestKey(params);
|
|
1089
|
-
const { resolvePoolAcquire } = await import("./attempt-
|
|
1114
|
+
const { resolvePoolAcquire } = await import("./attempt-BJ2mxTkh.js");
|
|
1090
1115
|
let resolvedPoolAcquire;
|
|
1091
1116
|
let currentAuth;
|
|
1092
1117
|
try {
|
package/dist/harness.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createCopilotAgentHarness } from "./harness-
|
|
1
|
+
import { t as createCopilotAgentHarness } from "./harness-CIPB8kLr.js";
|
|
2
2
|
export { createCopilotAgentHarness };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as createCopilotAgentHarness } from "./harness-
|
|
1
|
+
import { t as createCopilotAgentHarness } from "./harness-CIPB8kLr.js";
|
|
2
2
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
3
3
|
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
4
4
|
//#region extensions/copilot/index.ts
|
|
@@ -15,16 +15,21 @@ var copilot_default = definePluginEntry({
|
|
|
15
15
|
name: "GitHub Copilot agent runtime",
|
|
16
16
|
description: "Registers the GitHub Copilot agent runtime.",
|
|
17
17
|
register(api) {
|
|
18
|
-
if (api.registrationMode !== "full") return;
|
|
18
|
+
if (api.registrationMode !== "full" && api.registrationMode !== "discovery" && api.registrationMode !== "tool-discovery") return;
|
|
19
19
|
const poolOptions = readPoolOptions(api.pluginConfig);
|
|
20
|
-
|
|
20
|
+
let sessionStore;
|
|
21
|
+
const getSessionStore = () => sessionStore ??= api.runtime.state.openSyncKeyedStore({
|
|
21
22
|
namespace: "sdk-sessions",
|
|
22
23
|
maxEntries: 5e3,
|
|
23
|
-
defaultTtlMs:
|
|
24
|
+
defaultTtlMs: 7776e6
|
|
24
25
|
});
|
|
25
26
|
api.registerAgentHarness(createCopilotAgentHarness({
|
|
26
27
|
...poolOptions ? { poolOptions } : {},
|
|
27
|
-
sessionStore
|
|
28
|
+
sessionStore: {
|
|
29
|
+
register: (key, value, options) => getSessionStore().register(key, value, options),
|
|
30
|
+
lookup: (key) => getSessionStore().lookup(key),
|
|
31
|
+
delete: (key) => getSessionStore().delete(key)
|
|
32
|
+
}
|
|
28
33
|
}));
|
|
29
34
|
}
|
|
30
35
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as resolveCopilotProvider, o as tokenFingerprint, r as createCopilotByokProxy } from "./harness-
|
|
1
|
+
import { n as resolveCopilotProvider, o as tokenFingerprint, r as createCopilotByokProxy } from "./harness-CIPB8kLr.js";
|
|
2
2
|
import { r as createCopilotIsolatedSessionRestrictions, t as buildCopilotAssistantUsage } from "./usage-bridge-Cpa-ZYwL.js";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
4
|
//#region extensions/copilot/src/isolated-completion.ts
|
|
@@ -26,14 +26,12 @@ async function awaitWithinCompletionBoundary(params) {
|
|
|
26
26
|
if (signal?.aborted) throw createAbortError(signal);
|
|
27
27
|
const remainingMs = params.boundary.deadlineMs - Date.now();
|
|
28
28
|
if (remainingMs <= 0) throw createTimeoutError(params.boundary.timeoutMs);
|
|
29
|
-
let boundaryWon = false;
|
|
30
29
|
let boundaryError;
|
|
31
30
|
let timer;
|
|
32
31
|
let onAbort;
|
|
33
32
|
const boundary = new Promise((_resolve, reject) => {
|
|
34
33
|
const rejectBoundary = (error) => {
|
|
35
|
-
if (
|
|
36
|
-
boundaryWon = true;
|
|
34
|
+
if (boundaryError) return;
|
|
37
35
|
boundaryError = error;
|
|
38
36
|
params.onBoundary?.();
|
|
39
37
|
reject(error);
|
|
@@ -45,15 +43,27 @@ async function awaitWithinCompletionBoundary(params) {
|
|
|
45
43
|
if (signal.aborted) onAbort();
|
|
46
44
|
}
|
|
47
45
|
});
|
|
46
|
+
const assertCurrent = () => {
|
|
47
|
+
if (boundaryError) throw boundaryError;
|
|
48
|
+
params.boundary.assertCurrent?.();
|
|
49
|
+
};
|
|
48
50
|
const operation = Promise.resolve().then(() => {
|
|
49
|
-
|
|
51
|
+
assertCurrent();
|
|
50
52
|
return params.start(remainingMs);
|
|
51
|
-
}).then(
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
}).then((value) => {
|
|
54
|
+
try {
|
|
55
|
+
assertCurrent();
|
|
56
|
+
return value;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
startBestEffortCleanup(async () => await params.cleanupLate?.(value));
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
54
61
|
});
|
|
55
62
|
try {
|
|
56
63
|
return await Promise.race([operation, boundary]);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
params.boundary.assertCurrent?.();
|
|
66
|
+
throw error;
|
|
57
67
|
} finally {
|
|
58
68
|
if (timer) clearTimeout(timer);
|
|
59
69
|
if (signal && onAbort) signal.removeEventListener("abort", onAbort);
|
|
@@ -76,6 +86,7 @@ async function runCopilotIsolatedCompletion(params, getPool) {
|
|
|
76
86
|
if (params.thinkLevel !== void 0 && reasoningEffort === void 0) throw new Error(`[copilot] isolated completion does not support thinking level ${params.thinkLevel}`);
|
|
77
87
|
const boundary = {
|
|
78
88
|
abortSignal: params.abortSignal,
|
|
89
|
+
assertCurrent: params.assertCurrent,
|
|
79
90
|
deadlineMs: Date.now() + params.timeoutMs,
|
|
80
91
|
timeoutMs: params.timeoutMs
|
|
81
92
|
};
|
|
@@ -38,7 +38,8 @@ async function doLoad(options) {
|
|
|
38
38
|
const fallbackPath = path.join(fallbackDir, "node_modules", "@github", "copilot-sdk");
|
|
39
39
|
if (!existsSync(fallbackPath)) throw createMissingSdkError(primaryErr, void 0, fallbackPath);
|
|
40
40
|
const fallbackImport = options.fallbackImport ?? (async () => {
|
|
41
|
-
|
|
41
|
+
const entry = createRequire(path.join(fallbackDir, "package.json")).resolve("@github/copilot-sdk");
|
|
42
|
+
return await import(pathToFileURL(entry).href);
|
|
42
43
|
});
|
|
43
44
|
try {
|
|
44
45
|
return await fallbackImport(fallbackPath);
|
|
@@ -82,7 +83,7 @@ function summarizeError(value) {
|
|
|
82
83
|
}
|
|
83
84
|
//#endregion
|
|
84
85
|
//#region extensions/copilot/src/runtime.ts
|
|
85
|
-
const DEFAULT_IDLE_TTL_MS =
|
|
86
|
+
const DEFAULT_IDLE_TTL_MS = 3e5;
|
|
86
87
|
const POOL_DISPOSED_MESSAGE = "[copilot-pool] pool disposed";
|
|
87
88
|
function createCopilotClientPool(options = {}) {
|
|
88
89
|
const sdkFactory = options.sdkFactory ?? (async (clientOptions) => {
|
|
@@ -262,9 +263,7 @@ function createCopilotClientPool(options = {}) {
|
|
|
262
263
|
case "stopping":
|
|
263
264
|
case "stopped": return;
|
|
264
265
|
case "ready":
|
|
265
|
-
case "idle":
|
|
266
|
-
if (entry.state.client !== handle.client) return;
|
|
267
|
-
break;
|
|
266
|
+
case "idle": if (entry.state.client !== handle.client) return;
|
|
268
267
|
}
|
|
269
268
|
if (entry.refCount <= 0) return;
|
|
270
269
|
entry.refCount -= 1;
|
package/openclaw.plugin.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openclaw/copilot",
|
|
3
|
-
"version": "2026.9.
|
|
3
|
+
"version": "2026.9.2",
|
|
4
4
|
"description": "OpenClaw GitHub Copilot agent runtime plugin (registers a `github-copilot` AgentHarness backed by @github/copilot-sdk over JSON-RPC to the GitHub Copilot CLI)",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
"minHostVersion": ">=2026.5.28"
|
|
25
25
|
},
|
|
26
26
|
"compat": {
|
|
27
|
-
"pluginApi": ">=2026.9.
|
|
27
|
+
"pluginApi": ">=2026.9.2"
|
|
28
28
|
},
|
|
29
29
|
"build": {
|
|
30
|
-
"openclawVersion": "2026.9.
|
|
30
|
+
"openclawVersion": "2026.9.2",
|
|
31
31
|
"bundledDist": false
|
|
32
32
|
},
|
|
33
33
|
"release": {
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"README.md"
|
|
46
46
|
],
|
|
47
47
|
"peerDependencies": {
|
|
48
|
-
"openclaw": ">=2026.9.
|
|
48
|
+
"openclaw": ">=2026.9.2"
|
|
49
49
|
},
|
|
50
50
|
"peerDependenciesMeta": {
|
|
51
51
|
"openclaw": {
|