@openclaw/copilot 2026.9.1-beta.1 → 2026.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,16 @@
1
- import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-hh25oAuF.js";
1
+ import { a as resolveCopilotAuth, i as createCopilotByokAuth, n as resolveCopilotProvider, r as createCopilotByokProxy } from "./harness-V2lGlWa5.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, TRANSCRIPT_CREDENTIAL_SAFETY_PROMPT, applyEmbeddedAttemptToolsAllow, awaitAgentEndSideEffects, buildAgentHookContextChannelFields, buildDelegationGuidanceSection, buildEmbeddedAttemptToolRunContext, buildEmbeddedForegroundPromptContext, buildHarnessVisibleReplyGuidance, buildSkillWorkshopPromptSection, callGatewayTool, cancelPendingAgentQuestionForSession, claimPendingAgentQuestionAnswer, clearActiveEmbeddedRun, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, getPluginToolSideEffectOwnerKey, isHostScopedAgentToolActive, isSubagentSessionKey, isToolResultError, projectAgentHarnessTranscriptMessageForDisplay, resolveAgentDir, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveMainSessionDelegationMode, resolveModelAuthMode, resolveSandboxContext, resolveSessionAgentIds, resolveUserPath, runAgentEndSideEffects, runAgentHarnessAfterCompactionHook, runAgentHarnessAfterToolCallHook, runAgentHarnessBeforeCompactionHook, runAgentHarnessBeforeMessageWriteHook, runAgentHarnessGatewayQuestion, runAgentHarnessLlmInputHook, runAgentHarnessLlmOutputHook, sanitizeToolResult, setActiveEmbeddedRun } from "openclaw/plugin-sdk/agent-harness-runtime";
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, callGatewayTool, cancelPendingAgentQuestionForSession, claimPendingAgentQuestionAnswer, clearActiveEmbeddedRun, detectAndLoadAgentHarnessPromptImages, embeddedAgentLog, extractToolErrorMessage, getModelProviderRequestTransport, getPluginToolMeta, getPluginToolSideEffectOwnerKey, isHostScopedAgentToolActive, isSubagentSessionKey, isToolResultError, projectAgentHarnessTranscriptMessageForDisplay, resolveAgentDir, resolveAgentHarnessBeforePromptBuildResult, resolveAttemptFsWorkspaceOnly, resolveAttemptSpawnWorkspaceDir, resolveBootstrapContextForRun, resolveCompactionTimeoutMs, resolveEmbeddedAttemptToolConstructionPlan, resolveMainSessionDelegationMode, resolveModelAuthMode, resolveSandboxContext, resolveUserPath, 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: state.sessionIdUsed ?? readNonEmptyString(params.sessionId) ?? "copilot-session",
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: resolveModelRef(params),
485
+ model,
482
486
  resolvedApiKey: readNonEmptyString(params.resolvedApiKey),
483
487
  authProfileId: readNonEmptyString(params.authProfileId)
484
488
  });
@@ -1327,7 +1331,7 @@ function registerCopilotActiveRun(params) {
1327
1331
  }
1328
1332
  if (params.isSettled() || params.isAborted()) throw new Error("Copilot steering is unavailable after the active run ended");
1329
1333
  if (!params.canAcceptSteering()) throw new Error("Copilot steering is unavailable before initial user validation");
1330
- messageId = await params.session.send({ prompt: text });
1334
+ messageId = await params.transcriptJournal.sendSdkUser(() => params.session.send({ prompt: text }), options?.userTurnTranscriptRecorder);
1331
1335
  reportAcceptance(true);
1332
1336
  } catch (error) {
1333
1337
  reportAcceptance(false);
@@ -1345,6 +1349,7 @@ function registerCopilotActiveRun(params) {
1345
1349
  const activeRunHandle = {
1346
1350
  kind: "embedded",
1347
1351
  runId: params.input.runId,
1352
+ startedAtMs: params.startedAtMs,
1348
1353
  toolAuthorityFingerprint: params.input.toolAuthorityFingerprint,
1349
1354
  claimPendingUserInputAnswer,
1350
1355
  cancelPendingUserInput,
@@ -1389,7 +1394,7 @@ async function waitForPersistenceReceipt(receipt, requestedTimeoutMs) {
1389
1394
  //#endregion
1390
1395
  //#region extensions/copilot/src/attempt-finalize.ts
1391
1396
  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, sessionIdUsed, settledFinalizationAssistantCompleted, settledToolFinalization, timedOut, timedOutDuringCompaction, yieldDetected, yieldAcknowledgment } = params;
1397
+ 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
1398
  const snap = bridge?.snapshot();
1394
1399
  const assistantTexts = bridge?.finalizeAssistantTexts() ?? [];
1395
1400
  const lastAssistant = bridge?.buildAssistantMessage({
@@ -1401,6 +1406,7 @@ async function completeCopilotAttempt(params) {
1401
1406
  const currentRunUserKey = `${input.runId}:user`;
1402
1407
  const messagesSnapshot = transcript?.messagesSnapshot ?? (recorder?.isBlocked() ? removePreparedUser(messages, recorder.message, currentRunUserKey) : includePreparedUser(messages, recorder?.message, input.trigger === "memory", currentRunUserKey));
1403
1408
  const result = createResult(input, {
1409
+ acceptedSessionSpawns,
1404
1410
  aborted,
1405
1411
  assistantTexts,
1406
1412
  codeModeEngaged,
@@ -1425,7 +1431,6 @@ async function completeCopilotAttempt(params) {
1425
1431
  promptError,
1426
1432
  resumeFailureRecovered,
1427
1433
  sdkSessionId,
1428
- sessionIdUsed,
1429
1434
  timedOut,
1430
1435
  timedOutDuringCompaction,
1431
1436
  toolMetas: snap ? [...snap.toolMetas] : [],
@@ -1522,21 +1527,12 @@ async function createCopilotToolBridge(input) {
1522
1527
  disableTools: attemptParams.disableTools,
1523
1528
  forceMessageTool: shouldForceCopilotMessageTool(attemptParams),
1524
1529
  isRawModelRun: isRawCopilotModelRun(attemptParams),
1525
- toolsAllow: attemptParams.toolsAllow
1530
+ toolsAllow: buildEmbeddedAttemptToolRunContext({
1531
+ ...attemptParams,
1532
+ forceMessageTool: shouldForceCopilotMessageTool(attemptParams)
1533
+ }).runtimeToolAllowlist
1526
1534
  });
1527
- const effectiveToolPlan = hasNonWildcardGlobAllowlist(toolPlan.runtimeToolAllowlist) ? {
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 {
1535
+ if (!toolPlan.constructTools) return {
1540
1536
  codeModeEngaged: false,
1541
1537
  promptToolPolicy: EMPTY_PROMPT_TOOL_POLICY,
1542
1538
  sourceTools: []
@@ -1544,19 +1540,21 @@ async function createCopilotToolBridge(input) {
1544
1540
  const createOpenClawCodingTools = input.createOpenClawCodingTools ?? (await import("openclaw/plugin-sdk/agent-harness")).createOpenClawCodingTools;
1545
1541
  const toolSurfaceRuntime = createAgentHarnessToolSurfaceRuntime({
1546
1542
  abortSignal: input.abortSignal,
1547
- agentId: input.agentId,
1543
+ agentId: attemptParams.sandboxAgentId ?? input.agentId,
1548
1544
  config: attemptParams.config,
1545
+ codeModeOverride: attemptParams.codeModeOverride,
1549
1546
  disableTools: attemptParams.disableTools,
1550
1547
  executeTool: (toolParams) => executeCatalogTool(input, toolParams),
1551
1548
  forceMessageTool: shouldForceCopilotMessageTool(attemptParams),
1552
1549
  isRawModelRun: isRawCopilotModelRun(attemptParams),
1553
1550
  model: attemptParams.model,
1551
+ contextTokenBudget: attemptParams.contextTokenBudget,
1554
1552
  modelId: input.modelId,
1555
1553
  modelProvider: input.modelProvider,
1556
1554
  modelToolsEnabled: true,
1557
1555
  prompt: attemptParams.prompt,
1558
1556
  runId: attemptParams.runId,
1559
- runtimeToolAllowlist: effectiveToolPlan.runtimeToolAllowlist,
1557
+ runtimeToolAllowlist: toolPlan.runtimeToolAllowlist,
1560
1558
  sessionId: input.sessionId,
1561
1559
  sessionKey: attemptParams.sandboxSessionKey ?? attemptParams.sessionKey ?? input.sessionKey,
1562
1560
  scheduledToolPolicy: attemptParams.scheduledToolPolicy,
@@ -1564,7 +1562,7 @@ async function createCopilotToolBridge(input) {
1564
1562
  toolsAllow: attemptParams.toolsAllow
1565
1563
  });
1566
1564
  const toolOptions = buildOpenClawCodingToolsOptions(input, {
1567
- ...effectiveToolPlan,
1565
+ ...toolPlan,
1568
1566
  runtimeToolAllowlist: toolSurfaceRuntime.runtimeToolAllowlist
1569
1567
  }, toolSurfaceRuntime);
1570
1568
  let sourceTools;
@@ -1582,7 +1580,7 @@ async function createCopilotToolBridge(input) {
1582
1580
  } catch (error) {
1583
1581
  throw createError(`[copilot-tool-bridge] createOpenClawCodingTools failed: ${toStringifiedError(error).message}`, error);
1584
1582
  }
1585
- const plannedSourceTools = filterCopilotToolsForConstructionPlan(applyEmbeddedAttemptToolsAllow(sourceTools, toolSurfaceRuntime.runtimeToolAllowlist, { toolMeta: (tool) => getPluginToolMeta(tool) ?? readInlinePluginToolMeta(tool) }), effectiveToolPlan.codingToolConstructionPlan, { preserveToolNames: toolSurfaceRuntime.runtimeToolAllowlist });
1583
+ const plannedSourceTools = filterCopilotToolsForConstructionPlan(applyEmbeddedAttemptToolsAllow(sourceTools, toolSurfaceRuntime.runtimeToolAllowlist, { toolMeta: (tool) => getPluginToolMeta(tool) ?? readInlinePluginToolMeta(tool) }), toolPlan.codingToolConstructionPlan, { preserveToolNames: toolSurfaceRuntime.runtimeToolAllowlist });
1586
1584
  const compactedTools = toolSurfaceRuntime.compactTools(plannedSourceTools, { localModelLeanApplied: true });
1587
1585
  const newlyConstructedTools = compactedTools.tools.filter((tool) => !boundSourceTools.has(tool));
1588
1586
  const boundNewlyConstructedTools = newlyConstructedTools.length > 0 ? hostCapabilities.bindToolSurface(newlyConstructedTools, bindingOptions) : newlyConstructedTools;
@@ -1603,7 +1601,14 @@ async function createCopilotToolBridge(input) {
1603
1601
  cleanup: toolSurfaceRuntime.cleanup,
1604
1602
  codeModeEngaged: toolSurfaceRuntime.codeModeControlsEnabled,
1605
1603
  promptToolPolicy: { apply: (params = {}) => {
1606
- const result = compactedTools.promptToolPolicy.apply(params);
1604
+ const result = compactedTools.promptToolPolicy.apply({
1605
+ ...params,
1606
+ toolsAllow: buildEmbeddedAttemptToolRunContext({
1607
+ ...attemptParams,
1608
+ toolsAllow: params.toolsAllow,
1609
+ forceMessageTool: shouldForceCopilotMessageTool(attemptParams)
1610
+ }).runtimeToolAllowlist
1611
+ });
1607
1612
  const directToolNames = new Set(result.tools.map((tool) => tool.name));
1608
1613
  return {
1609
1614
  tools: sdkTools.filter((tool) => directToolNames.has(tool.name)),
@@ -1614,26 +1619,9 @@ async function createCopilotToolBridge(input) {
1614
1619
  };
1615
1620
  }
1616
1621
  /**
1617
- * Builds the full `createOpenClawCodingTools` options bag mirroring the
1618
- * PI in-tree call at `src/agents/pi-embedded-runner/run/attempt.ts:1029-1117`.
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.
1622
+ * Bridged tools skip SDK permission prompts, so host wrappers need the complete
1623
+ * attempt context and prepared sandbox/construction policy to enforce access.
1624
+ * Missing fields here silently weaken or misapply the native harness contract.
1637
1625
  */
1638
1626
  function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
1639
1627
  const a = input.attemptParams;
@@ -1653,13 +1641,8 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
1653
1641
  const modelCompat = model && typeof model === "object" && "compat" in model && model.compat && typeof model.compat === "object" ? model.compat : void 0;
1654
1642
  return {
1655
1643
  agentId: input.agentId,
1656
- ...buildEmbeddedAttemptToolRunContext({
1657
- trigger: a.trigger,
1658
- jobId: a.jobId,
1659
- memoryFlushWritePath: a.memoryFlushWritePath,
1660
- toolsAllow: a.toolsAllow,
1661
- conversationToolPolicy: a.conversationToolPolicy
1662
- }),
1644
+ policyAgentId: a.sandboxAgentId ?? input.agentId,
1645
+ ...buildEmbeddedAttemptToolRunContext(a),
1663
1646
  exec: {
1664
1647
  ...a.execOverrides,
1665
1648
  elevated: a.bashElevated
@@ -1707,7 +1690,7 @@ function buildOpenClawCodingToolsOptions(input, toolPlan, toolSurfaceRuntime) {
1707
1690
  toolConstructionPlan: toolPlan.codingToolConstructionPlan,
1708
1691
  modelCompat,
1709
1692
  modelApi: model?.api,
1710
- modelContextWindowTokens: model?.contextWindow,
1693
+ modelContextWindowTokens: a.contextTokenBudget ?? model?.contextWindow,
1711
1694
  delegationCapability: a.delegationCapability,
1712
1695
  modelAuthMode: resolveModelAuthMode(input.modelProvider, a.config, void 0, { workspaceDir }),
1713
1696
  currentChannelId: a.currentChannelId,
@@ -1856,6 +1839,7 @@ function convertOpenClawToolToSdkTool(sourceTool, ctx) {
1856
1839
  } : executeOnce;
1857
1840
  return {
1858
1841
  description: sourceTool.description,
1842
+ defer: sourceTool.catalogMode === "direct-only" ? "never" : void 0,
1859
1843
  handler,
1860
1844
  name: sourceTool.name,
1861
1845
  overridesBuiltInTool: true,
@@ -1976,12 +1960,6 @@ function filterCopilotToolsForConstructionPlan(tools, plan, options = {}) {
1976
1960
  return true;
1977
1961
  });
1978
1962
  }
1979
- function hasNonWildcardGlobAllowlist(toolsAllow) {
1980
- return (toolsAllow ?? []).some((entry) => {
1981
- const trimmed = entry.trim();
1982
- return trimmed !== "*" && trimmed.includes("*");
1983
- });
1984
- }
1985
1963
  function readInlinePluginToolMeta(tool) {
1986
1964
  const pluginId = tool.pluginId;
1987
1965
  return typeof pluginId === "string" && pluginId.trim() ? { pluginId } : void 0;
@@ -2025,7 +2003,7 @@ function prepareCopilotAttemptContext(params, deps) {
2025
2003
  const modelRef = resolveModelRef(input);
2026
2004
  const resolvedWorkspaceForSandbox = readResolvedAttemptPath(input.workspaceDir) ?? readResolvedAttemptPath(input.cwd);
2027
2005
  const sandboxSessionKey = readNonEmptyString(input.sandboxSessionKey) ?? readNonEmptyString(input.sessionKey) ?? readNonEmptyString(input.sessionId);
2028
- const { sessionAgentId } = resolveSessionAgentIds({
2006
+ const { sessionAgentId } = resolveSessionAgentIdsStrict({
2029
2007
  sessionKey: readNonEmptyString(input.sessionKey),
2030
2008
  config: input.config,
2031
2009
  agentId: readNonEmptyString(params.agentId)
@@ -2050,7 +2028,7 @@ function prepareCopilotAttemptContext(params, deps) {
2050
2028
  runId: input.runId,
2051
2029
  jobId: input.jobId,
2052
2030
  agentId: sessionAgentId,
2053
- sessionKey: sandboxSessionKey,
2031
+ sessionKey: readNonEmptyString(input.sessionKey) ?? sandboxSessionKey,
2054
2032
  sessionId: input.sessionId,
2055
2033
  workspaceDir: resolvedWorkspaceForSandbox,
2056
2034
  modelProviderId: modelRef.provider,
@@ -2070,6 +2048,7 @@ async function resolveCopilotAttemptSandbox(params) {
2070
2048
  const resolveSandbox = params.deps.resolveSandboxContextOverride ?? resolveSandboxContext;
2071
2049
  const sandbox = params.input.sandbox !== void 0 ? params.input.sandbox : await resolveSandbox({
2072
2050
  config: params.input.config,
2051
+ agentId: params.input.sandboxAgentId,
2073
2052
  sessionKey: params.sandboxSessionKey,
2074
2053
  workspaceDir: params.resolvedWorkspaceForSandbox
2075
2054
  });
@@ -2110,7 +2089,7 @@ function buildCopilotPromptGuidance(params) {
2110
2089
  sourceReplyDeliveryMode: params.attempt.sourceReplyDeliveryMode,
2111
2090
  messageToolAvailable: callableTools.has("message")
2112
2091
  }),
2113
- TRANSCRIPT_CREDENTIAL_SAFETY_PROMPT,
2092
+ buildCredentialSafetyPrompt(params.attempt.disableTools !== true && callableTools.has("secrets") ? "secrets" : void 0),
2114
2093
  params.workspaceBootstrapInstructions?.trim(),
2115
2094
  extraSystemPrompt ? `${isMinimal ? "## Subagent Context" : "## Conversation Context"}\n${extraSystemPrompt}` : void 0
2116
2095
  ].filter((section) => section?.trim()).join("\n\n") || void 0;
@@ -2118,7 +2097,7 @@ function buildCopilotPromptGuidance(params) {
2118
2097
  //#endregion
2119
2098
  //#region extensions/copilot/src/user-input-bridge.ts
2120
2099
  const COPILOT_USER_INPUT_QUESTION_ID = "answer";
2121
- const DEFAULT_USER_INPUT_TIMEOUT_MS = 15 * 6e4;
2100
+ const DEFAULT_USER_INPUT_TIMEOUT_MS = 9e5;
2122
2101
  function createCopilotUserInputBridge(params) {
2123
2102
  let pending;
2124
2103
  const gatewayCall = params.gatewayCall ?? callGatewayTool;
@@ -2455,6 +2434,41 @@ async function createCopilotSessionSetup(params) {
2455
2434
  };
2456
2435
  }
2457
2436
  //#endregion
2437
+ //#region extensions/copilot/src/attempt-transcript-replay.ts
2438
+ function readAssistantToolCallIds(message) {
2439
+ return message.role === "assistant" ? message.content.flatMap((part) => part.type === "toolCall" ? [part.id] : []) : [];
2440
+ }
2441
+ function isCompatibleSingletonRewrite(original, prepared) {
2442
+ return original.role === prepared.role && (original.role !== "assistant" || JSON.stringify(readAssistantToolCallIds(original)) === JSON.stringify(readAssistantToolCallIds(prepared)));
2443
+ }
2444
+ function projectReplayPayload(message) {
2445
+ switch (message.role) {
2446
+ case "user": return {
2447
+ role: message.role,
2448
+ content: message.content
2449
+ };
2450
+ case "assistant": return {
2451
+ role: message.role,
2452
+ content: message.content,
2453
+ api: message.api,
2454
+ model: message.model,
2455
+ provider: message.provider,
2456
+ stopReason: message.stopReason
2457
+ };
2458
+ case "toolResult": return {
2459
+ role: message.role,
2460
+ content: message.content,
2461
+ isError: message.isError,
2462
+ toolCallId: message.toolCallId,
2463
+ toolName: message.toolName
2464
+ };
2465
+ }
2466
+ }
2467
+ function isCompleteToolGroup(messages, order) {
2468
+ const [assistant, ...results] = messages;
2469
+ 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]);
2470
+ }
2471
+ //#endregion
2458
2472
  //#region extensions/copilot/src/attempt-transcript-journal.ts
2459
2473
  function readTurnTaintMetadata(message) {
2460
2474
  const metadata = message["__openclaw"];
@@ -2511,6 +2525,7 @@ function createAttemptTranscriptJournal(params) {
2511
2525
  let queue = Promise.resolve();
2512
2526
  let firstFailure;
2513
2527
  const sdkUserPersistenceReceipts = /* @__PURE__ */ new Map();
2528
+ const sdkUserRecorders = /* @__PURE__ */ new Map();
2514
2529
  let abortPromise;
2515
2530
  let replayInvalid = false;
2516
2531
  let initialSdkUserObserved = false;
@@ -2531,7 +2546,8 @@ function createAttemptTranscriptJournal(params) {
2531
2546
  const sdkUserPersistenceReceipt = (eventId) => {
2532
2547
  let receipt = sdkUserPersistenceReceipts.get(eventId);
2533
2548
  if (!receipt) {
2534
- receipt = createPersistenceReceipt();
2549
+ receipt = createDeferred();
2550
+ receipt.promise.catch(() => void 0);
2535
2551
  sdkUserPersistenceReceipts.set(eventId, receipt);
2536
2552
  if (firstFailure) receipt.reject(firstFailure);
2537
2553
  }
@@ -2548,7 +2564,8 @@ function createAttemptTranscriptJournal(params) {
2548
2564
  const hooked = runAgentHarnessBeforeMessageWriteHook({
2549
2565
  message: structuredClone(message),
2550
2566
  agentId: target.agentId,
2551
- sessionKey: target.sessionKey
2567
+ sessionKey: target.sessionKey,
2568
+ prepareAssistantTranscriptMessage: options.singleton && !hiddenTurn ? params.attempt.prepareAssistantTranscriptMessage : void 0
2552
2569
  });
2553
2570
  if (!hooked) return;
2554
2571
  if (!isDeepStrictEqual(originalReplayPayload, projectReplayPayload(hooked))) replayInvalid = true;
@@ -2566,6 +2583,7 @@ function createAttemptTranscriptJournal(params) {
2566
2583
  ...taintMetadata
2567
2584
  } } : {},
2568
2585
  ...idempotencyKey ? { idempotencyKey } : {},
2586
+ ...message.role === "user" && message.provenance ? { provenance: message.provenance } : {},
2569
2587
  ...message.display === false ? { display: false } : {}
2570
2588
  });
2571
2589
  return options.singleton && !isCompatibleSingletonRewrite(message, prepared) ? void 0 : prepared;
@@ -2579,9 +2597,13 @@ function createAttemptTranscriptJournal(params) {
2579
2597
  message: write.message,
2580
2598
  prepareMessageAfterIdempotencyCheck: () => prepare(write, { singleton: true })
2581
2599
  });
2582
- if (outcome.kind === "suppressed") return;
2600
+ if (outcome.kind === "suppressed") {
2601
+ write.recorder?.markBlocked();
2602
+ return;
2603
+ }
2583
2604
  if (outcome.kind === "rejected") throw new Error("Transcript session changed before singleton append");
2584
2605
  if (!isDeepStrictEqual(projectReplayPayload(write.message), projectReplayPayload(outcome.result.message))) replayInvalid = true;
2606
+ if (outcome.result.message.role === "user") write.recorder?.markRuntimePersisted(outcome.result.message, outcome.result.anchor);
2585
2607
  return outcome.result;
2586
2608
  };
2587
2609
  const appendToolGroup = async (group) => {
@@ -2649,6 +2671,20 @@ function createAttemptTranscriptJournal(params) {
2649
2671
  }
2650
2672
  };
2651
2673
  return {
2674
+ async sendSdkUser(send, recorder) {
2675
+ if (!recorder) return await send();
2676
+ const registration = createDeferred();
2677
+ schedule(() => registration.promise);
2678
+ try {
2679
+ const messageId = await send();
2680
+ sdkUserRecorders.set(messageId, recorder);
2681
+ recorder.markSentToProvider?.();
2682
+ recorder.markRuntimePersistencePending(sdkUserPersistenceReceipt(messageId).promise);
2683
+ return messageId;
2684
+ } finally {
2685
+ registration.resolve();
2686
+ }
2687
+ },
2652
2688
  markReplayIncomplete() {
2653
2689
  replayInvalid = true;
2654
2690
  },
@@ -2711,9 +2747,16 @@ function createAttemptTranscriptJournal(params) {
2711
2747
  }
2712
2748
  initialSdkUserObserved = true;
2713
2749
  schedule(async () => {
2750
+ const recorder = sdkUserRecorders.get(input.eventId);
2751
+ sdkUserRecorders.delete(input.eventId);
2752
+ const provenance = (await recorder?.resolveMessage())?.provenance;
2714
2753
  const write = {
2715
2754
  eventId: input.eventId,
2716
- message: input.message
2755
+ message: provenance ? {
2756
+ ...input.message,
2757
+ provenance
2758
+ } : input.message,
2759
+ recorder
2717
2760
  };
2718
2761
  if (pendingTools) {
2719
2762
  deferredUserWrites.push(write);
@@ -2783,10 +2826,7 @@ function createAttemptTranscriptJournal(params) {
2783
2826
  replayInvalid = true;
2784
2827
  ownAssistant(group.assistantKey, false);
2785
2828
  } else {
2786
- for (const result of results) {
2787
- const didAppend = accept(result);
2788
- appended ||= didAppend;
2789
- }
2829
+ for (const result of results) appended = accept(result) || appended;
2790
2830
  ownAssistant(group.assistantKey, true, results.at(-1)?.anchor);
2791
2831
  }
2792
2832
  pendingTools = void 0;
@@ -2798,8 +2838,7 @@ function createAttemptTranscriptJournal(params) {
2798
2838
  if (write.eventId) sdkUserPersistenceReceipt(write.eventId).reject(/* @__PURE__ */ new Error("Copilot steering user write was suppressed"));
2799
2839
  continue;
2800
2840
  }
2801
- const didAppend = accept(outcome);
2802
- appended ||= didAppend;
2841
+ appended = accept(outcome) || appended;
2803
2842
  if (write.eventId) deferredReceipts.push(sdkUserPersistenceReceipt(write.eventId));
2804
2843
  }
2805
2844
  await publish(appended);
@@ -2821,31 +2860,6 @@ function createAttemptTranscriptJournal(params) {
2821
2860
  })
2822
2861
  };
2823
2862
  }
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
2863
  function resolveTranscriptTarget(attempt) {
2850
2864
  const sessionId = normalizeOptionalString(attempt.sessionTarget?.sessionId);
2851
2865
  const sessionKey = normalizeOptionalString(attempt.sessionTarget?.sessionKey);
@@ -2863,35 +2877,6 @@ function resolveTranscriptTarget(attempt) {
2863
2877
  ...agentId ? { agentId } : {}
2864
2878
  };
2865
2879
  }
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
2880
  function readIdempotencyKey(message) {
2896
2881
  const key = message.idempotencyKey;
2897
2882
  return typeof key === "string" && key ? key : void 0;
@@ -2899,10 +2884,6 @@ function readIdempotencyKey(message) {
2899
2884
  function isCurrentJournalIdentity(key, params) {
2900
2885
  return key === `${params.attempt.runId}:user` || key.startsWith(`copilot-sdk:${params.sdkSessionId}:`);
2901
2886
  }
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
2887
  function isSameUserTurn(candidate, current, currentRunUserKey) {
2907
2888
  if (candidate?.role !== "user" || !current) return false;
2908
2889
  if (candidate === current) return true;
@@ -3061,7 +3042,6 @@ async function runCopilotExecution(context) {
3061
3042
  let timedOut = false;
3062
3043
  let promptError;
3063
3044
  let sdkSessionId;
3064
- let sessionIdUsed = input.sessionId;
3065
3045
  let nativeSessionCreatedFresh = false;
3066
3046
  let nativeSessionHistoryValidated = false;
3067
3047
  let disconnectError;
@@ -3083,6 +3063,7 @@ async function runCopilotExecution(context) {
3083
3063
  let resumeFailureRecovered = false;
3084
3064
  let yieldDetected = false;
3085
3065
  let yieldAcknowledgment;
3066
+ const acceptedSessionSpawns = [];
3086
3067
  let lastToolError;
3087
3068
  const hostObserveToolTerminal = input.observeToolTerminal;
3088
3069
  const observeToolTerminal = hostObserveToolTerminal ? (observation) => {
@@ -3122,15 +3103,13 @@ async function runCopilotExecution(context) {
3122
3103
  messagesSnapshot: messages,
3123
3104
  now,
3124
3105
  promptError: void 0,
3125
- sdkSessionId: void 0,
3126
- sessionIdUsed: input.sessionId
3106
+ sdkSessionId: void 0
3127
3107
  }));
3128
3108
  return finishAttempt(createResult(input, {
3129
3109
  messagesSnapshot: messages,
3130
3110
  now,
3131
3111
  promptError: createPromptError$1("sandbox_resolution_failure", `[copilot-attempt] sandbox resolution failed: ${toCopilotError(error).message}`, error),
3132
- sdkSessionId: void 0,
3133
- sessionIdUsed: input.sessionId
3112
+ sdkSessionId: void 0
3134
3113
  }));
3135
3114
  }
3136
3115
  hookContext.workspaceDir = effectiveWorkspaceDir;
@@ -3142,8 +3121,7 @@ async function runCopilotExecution(context) {
3142
3121
  messagesSnapshot: messages,
3143
3122
  now,
3144
3123
  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
3124
+ sdkSessionId: void 0
3147
3125
  }));
3148
3126
  }
3149
3127
  const effectiveCwd = sandbox?.enabled ? effectiveWorkspaceDir : requestedCwd ?? effectiveWorkspaceDir;
@@ -3171,8 +3149,7 @@ async function runCopilotExecution(context) {
3171
3149
  messagesSnapshot: messages,
3172
3150
  now,
3173
3151
  promptError: createPromptError$1("model_not_supported", toCopilotError(error).message, error),
3174
- sdkSessionId: void 0,
3175
- sessionIdUsed: input.sessionId
3152
+ sdkSessionId: void 0
3176
3153
  }));
3177
3154
  }
3178
3155
  const cleanupByokProxy = byokProxy?.close;
@@ -3208,19 +3185,29 @@ async function runCopilotExecution(context) {
3208
3185
  yieldDetected = true;
3209
3186
  yieldAcknowledgment = acknowledgment;
3210
3187
  },
3211
- onToolCompleted: ({ args, error, result, startedAt, toolCallId, toolName }) => runAgentHarnessAfterToolCallHook({
3212
- toolName,
3213
- toolCallId,
3214
- runId: input.runId,
3215
- agentId: sessionAgentId,
3216
- sessionId: input.sessionId,
3217
- sessionKey: sandboxSessionKey,
3218
- channelId: hookContext.channelId,
3219
- startArgs: args,
3220
- ...result !== void 0 ? { result } : {},
3221
- ...error ? { error } : {},
3222
- startedAt
3223
- })
3188
+ onToolCompleted: async ({ args, error, result, startedAt, toolCallId, toolName }) => {
3189
+ const acceptedSessionSpawnDetails = toolName === "sessions_spawn" && !error ? asOptionalRecord(asOptionalRecord(result)?.details) : void 0;
3190
+ const runId = normalizeOptionalString(acceptedSessionSpawnDetails?.runId);
3191
+ const childSessionKey = normalizeOptionalString(acceptedSessionSpawnDetails?.childSessionKey);
3192
+ if (acceptedSessionSpawnDetails?.status === "accepted" && runId && childSessionKey) acceptedSessionSpawns.push({
3193
+ runId,
3194
+ childSessionKey,
3195
+ expectsCompletionMessage: acceptedSessionSpawnDetails.expectsCompletionMessage === true
3196
+ });
3197
+ await runAgentHarnessAfterToolCallHook({
3198
+ toolName,
3199
+ toolCallId,
3200
+ runId: input.runId,
3201
+ agentId: sessionAgentId,
3202
+ sessionId: input.sessionId,
3203
+ sessionKey: hookContext.sessionKey,
3204
+ channelId: hookContext.channelId,
3205
+ startArgs: args,
3206
+ ...result !== void 0 ? { result } : {},
3207
+ ...error ? { error } : {},
3208
+ startedAt
3209
+ });
3210
+ }
3224
3211
  });
3225
3212
  cleanupToolBridge = toolBridge.cleanup;
3226
3213
  codeModeEngaged = toolBridge.codeModeEngaged;
@@ -3231,8 +3218,7 @@ async function runCopilotExecution(context) {
3231
3218
  messagesSnapshot: messages,
3232
3219
  now,
3233
3220
  promptError: createPromptError$1("tool_bridge_failure", `[copilot-attempt] tool-bridge construction failed: ${toCopilotError(error).message}`, error),
3234
- sdkSessionId: void 0,
3235
- sessionIdUsed: input.sessionId
3221
+ sdkSessionId: void 0
3236
3222
  }));
3237
3223
  }
3238
3224
  handle = await deps.pool.acquire(poolAcquire.key, poolAcquire.options);
@@ -3284,7 +3270,6 @@ async function runCopilotExecution(context) {
3284
3270
  sessionRef.current = session;
3285
3271
  sdkSessionId = readNonEmptyString(session.sessionId) ?? readNonEmptyString(session.id) ?? (resumeFailureRecovered ? void 0 : resumeSessionId);
3286
3272
  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
3273
  if (sdkSessionId && deps.onSessionEstablished && !settledToolFinalization) try {
3289
3274
  deps.onSessionEstablished({
3290
3275
  compactionSessionConfig,
@@ -3346,6 +3331,7 @@ async function runCopilotExecution(context) {
3346
3331
  abortActiveSession,
3347
3332
  bridge,
3348
3333
  canAcceptSteering: () => initialSdkUserValidated,
3334
+ startedAtMs: input.startedAtMs,
3349
3335
  input,
3350
3336
  isAborted: () => aborted,
3351
3337
  isSettled: () => settled,
@@ -3384,25 +3370,27 @@ async function runCopilotExecution(context) {
3384
3370
  if (!promptError && !timedOut && !aborted && snap.streamError) promptError = snap.streamError;
3385
3371
  }
3386
3372
  } catch (error) {
3387
- if (!aborted) if (isSdkSendAndWaitTimeoutError(error)) {
3388
- timedOut = true;
3389
- timedOutDuringCompaction = bridge?.isCompacting() === true;
3390
- try {
3391
- await bridge?.awaitDeltaChain();
3392
- } catch {}
3393
- await bridge?.awaitAgentEventChain();
3394
- bridge?.flushTranscriptProjection();
3395
- try {
3396
- await transcriptJournal?.barrier("timeout");
3373
+ if (!aborted) {
3374
+ if (isSdkSendAndWaitTimeoutError(error)) {
3375
+ timedOut = true;
3376
+ timedOutDuringCompaction = bridge?.isCompacting() === true;
3377
+ try {
3378
+ await bridge?.awaitDeltaChain();
3379
+ } catch {}
3380
+ await bridge?.awaitAgentEventChain();
3381
+ bridge?.flushTranscriptProjection();
3382
+ try {
3383
+ await transcriptJournal?.barrier("timeout");
3384
+ } catch (transcriptError) {
3385
+ promptError = toCopilotError(transcriptError);
3386
+ }
3387
+ } else try {
3388
+ bridge?.flushTranscriptProjection();
3389
+ await transcriptJournal?.barrier("attempt error");
3390
+ promptError = toCopilotError(error);
3397
3391
  } catch (transcriptError) {
3398
3392
  promptError = toCopilotError(transcriptError);
3399
3393
  }
3400
- } else try {
3401
- bridge?.flushTranscriptProjection();
3402
- await transcriptJournal?.barrier("attempt error");
3403
- promptError = toCopilotError(error);
3404
- } catch (transcriptError) {
3405
- promptError = toCopilotError(transcriptError);
3406
3394
  }
3407
3395
  } finally {
3408
3396
  settled = true;
@@ -3473,6 +3461,7 @@ async function runCopilotExecution(context) {
3473
3461
  }
3474
3462
  }
3475
3463
  return await completeCopilotAttempt({
3464
+ acceptedSessionSpawns,
3476
3465
  aborted,
3477
3466
  attemptStartedAt,
3478
3467
  bridge,
@@ -3493,7 +3482,6 @@ async function runCopilotExecution(context) {
3493
3482
  resumeFailureRecovered,
3494
3483
  sdkSessionId,
3495
3484
  sentTurnStarted,
3496
- sessionIdUsed,
3497
3485
  settledFinalizationAssistantCompleted,
3498
3486
  settledToolFinalization,
3499
3487
  timedOut,
@@ -3515,8 +3503,7 @@ async function runCopilotAttempt(params, deps) {
3515
3503
  messagesSnapshot: messages,
3516
3504
  now,
3517
3505
  promptError: void 0,
3518
- sdkSessionId: void 0,
3519
- sessionIdUsed: input.sessionId
3506
+ sdkSessionId: void 0
3520
3507
  }));
3521
3508
  try {
3522
3509
  resolveCopilotProvider({
@@ -3529,8 +3516,7 @@ async function runCopilotAttempt(params, deps) {
3529
3516
  messagesSnapshot: messages,
3530
3517
  now,
3531
3518
  promptError: createPromptError$1("model_not_supported", toCopilotError(error).message, error),
3532
- sdkSessionId: void 0,
3533
- sessionIdUsed: input.sessionId
3519
+ sdkSessionId: void 0
3534
3520
  }));
3535
3521
  }
3536
3522
  const settledFinalizationSessionId = settledToolFinalization ? readNonEmptyString(input.initialReplayState?.sdkSessionId) : void 0;
@@ -3538,8 +3524,7 @@ async function runCopilotAttempt(params, deps) {
3538
3524
  messagesSnapshot: messages,
3539
3525
  now,
3540
3526
  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
3527
+ sdkSessionId: void 0
3543
3528
  }));
3544
3529
  return await runCopilotExecution({
3545
3530
  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 { finished } from "node:stream/promises";
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
- return resolve(join(openClawHome ? resolve(openClawHome) : safeHomeDir(args.homeDir), ".openclaw", "agents", args.agentId, "copilot"));
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 canInjectBearerAuthorization = isNonceProtectedProxyRequest(req, params.proxyPathPrefix);
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, { upstreamBearerAuthorization: canInjectBearerAuthorization ? params.upstreamBearerAuthorization : void 0 }),
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: toFetchBody(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 finished(Readable.fromWeb(guarded.response.body).pipe(res));
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 toFetchBody(body) {
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
- if (isBlockedHostnameOrIp(url.hostname.toLowerCase().replace(/\.+$/, ""))) throw new Error(COPILOT_BYOK_ENDPOINT_POLICY_ERROR);
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-DvZQV_8v.js");
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-NJAPbYd4.js");
891
+ const { resolvePoolAcquire, runCopilotAttempt } = await import("./attempt-Ls_qYja7.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-GNSNtOHz.js");
1022
+ const { runCopilotIsolatedCompletion } = await import("./isolated-completion-DxQ0E51R.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
- return projectSettledTurnFinalizationAttemptResult(await runHarnessAttempt(attempt, "settled-tool-finalization"));
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-NJAPbYd4.js");
1114
+ const { resolvePoolAcquire } = await import("./attempt-Ls_qYja7.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-hh25oAuF.js";
1
+ import { t as createCopilotAgentHarness } from "./harness-V2lGlWa5.js";
2
2
  export { createCopilotAgentHarness };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createCopilotAgentHarness } from "./harness-hh25oAuF.js";
1
+ import { t as createCopilotAgentHarness } from "./harness-V2lGlWa5.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
- const sessionStore = api.runtime.state.openSyncKeyedStore({
20
+ let sessionStore;
21
+ const getSessionStore = () => sessionStore ??= api.runtime.state.openSyncKeyedStore({
21
22
  namespace: "sdk-sessions",
22
23
  maxEntries: 5e3,
23
- defaultTtlMs: 2160 * 60 * 60 * 1e3
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-hh25oAuF.js";
1
+ import { n as resolveCopilotProvider, o as tokenFingerprint, r as createCopilotByokProxy } from "./harness-V2lGlWa5.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
@@ -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
- return await import(pathToFileURL(createRequire(path.join(fallbackDir, "package.json")).resolve("@github/copilot-sdk")).href);
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 = 300 * 1e3;
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/copilot",
3
- "version": "2026.9.1-beta.1",
3
+ "version": "2026.9.1",
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.1-beta.1"
27
+ "pluginApi": ">=2026.9.1"
28
28
  },
29
29
  "build": {
30
- "openclawVersion": "2026.9.1-beta.1",
30
+ "openclawVersion": "2026.9.1",
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.1-beta.1"
48
+ "openclaw": ">=2026.9.1"
49
49
  },
50
50
  "peerDependenciesMeta": {
51
51
  "openclaw": {