mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
fix(runner): preserve task context when tool connections change (#14963)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use tools through company-scoped connections and provider sessions. > - Resolving a tool connection currently forces a fresh session even when the provider can load new tools into the existing conversation. > - A fresh provider conversation can receive too little history to continue the task. > - This pull request adds explicit tool-refresh capabilities and uses them in both runner paths. > - Fresh attempts receive bounded task history with source IDs and retrieval instructions. > - The benefit is that agents can continue the same task after a connection changes. ## Linked Issues or Issue Description **What happened?** A resolved tool connection forced a fresh provider conversation. The new conversation could lose the original goal and prior answers. Claude also rejected resume when only the MCP server set changed. **Expected behavior** Resume the provider conversation when its harness can refresh tools. When a fresh session is required, supply enough bounded history to continue the task. Preserve company, agent, task, workspace, model, instruction, and skill checks. **Steps to reproduce** 1. Start a conversation and agree on a task and its constraints. 2. Request and connect a tool needed for the task. 3. Continue the conversation after the connection resolves. 4. Check that the agent remembers the task and can use the new tool. **Paperclip version or commit** The bug was reproduced on master at `c46e41e81`. This branch is rebased on current master. **Deployment mode** Self-hosted server. Both legacy adapters and the native runner are affected. Related public work: Refs #13282 for task-backed conversations. Refs #13057 for the broader session-compaction proposal. Refs #14659 for another report about local CLI session continuity. This change fixes tool-connection continuation. Provider authentication repairs keep their existing recovery behavior. ## What Changed - Expose tool-refresh support in native harness descriptors and legacy adapter metadata. - Request tool refresh after connection resolution. Keep provider authentication repair as a fresh-session wake. - Reload current tools and credentials while retaining supported Claude, Codex, Grok, and other provider conversations. - Allow MCP-only changes during qualified native recovery. Keep all other compatibility checks. - Refresh managed-provider and ACPX tool bindings when attaching a new run. - Add a fresh-session handoff for both runner paths. Bound database reads, excerpts, and the final packet to 24,000 bytes. - Include the original request, recent messages, decisions, plans, prior answers, and source IDs. Mark omitted content. Apply reset boundaries, wake cutoffs, quarantine, and secret redaction. - Add regression tests and document the capabilities and handoff behavior. ## Verification - `pnpm -r typecheck` and `pnpm build` passed. Rust formatting passed. - Final review fixes passed 314 server tests, 333 adapter utility tests, 139 native-session runtime tests, and 12 managed-provider Rust tests. They verify historical quarantine, raised budgets across attachment, no history reads on successful resume, and handoff delivery on fresh retry. - Broader branch verification also passed 1,401 adapter utility tests, 1,047 runner TypeScript tests, 43 Grok adapter tests, and 311 Rust core tests. - Live Claude CLI and Grok ACP probes preserved the provider session ID, recalled a prior task constraint, and called a newly added read-only MCP tool. - GitHub CI passed on `b21486d18084a7aa4cafbe8e012f7cad6585d9cc`: 55 successful checks and 4 skipped checks. This includes all test shards, all eight browser shards, runner checks, and the Grok clean public npm install canary. [CI run](https://github.com/paperclipai/paperclip/actions/runs/37057514976). - A full local test attempt encountered a separate Git snapshot timeout. All affected local suites passed after the final edits, and the full CI test gates passed. - Review the capability matrix in `packages/paperclip-runner/README.md`. Repeat the four reproduction steps with a supported provider and with an unsupported harness. ## Risks - Provider tool refresh can fail. Existing recovery falls back to a fresh conversation where policy permits it. - A new transport can replace an old process while preserving the provider conversation. Tests cover current credentials and unchanged identity. - Long history can omit older context. Explicit markers and source IDs let the agent retrieve needed context within task scope. - Unknown and unqualified harnesses use the fresh-session path. No database migration is required. ## Model Used OpenAI Codex, GPT-6, with reasoning, tool use, code execution, and live provider testing. The exact model ID and context-window size are not exposed in this session. Claude and Grok also ran as test subjects. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
43f391e807
commit
2ec82c5774
50 files changed
+1061
-66
No files matched your search
@@ -37,6 +37,7 @@ import {
|
||||
type AcpxEngineExecutorOptions,
|
||||
} from "./execute.js";
|
||||
import { ACPX_HANDSHAKE_TIMEOUT_MS } from "./constants.js";
|
||||
import { sessionCodec } from "./session-codec.js";
|
||||
import { runChildProcess } from "../server-utils.js";
|
||||
import { createPromptContextFixture } from "../test-fixtures/prompt-context.js";
|
||||
import { setExpensiveWorkspaceGitExecutor } from "../git-workspace-sync.js";
|
||||
@@ -2713,6 +2714,24 @@ describe("shared ACPX engine runtime behavior", () => {
|
||||
expect(first.result.sessionParams?.configFingerprint).not.toBe(second.result.sessionParams?.configFingerprint);
|
||||
});
|
||||
|
||||
it.each(["claude", "codex", "grok", "gemini", "kimi"])("resumes %s with added and removed MCP servers and current credentials", async (agent) => {
|
||||
const root = await makeTempRoot();
|
||||
const config = { agent, cwd: root, stateDir: path.join(root, "state"), paperclipRuntimeSkills: [], paperclipSkillSync: { desiredSkills: [] } };
|
||||
const first = await runExecutor(config);
|
||||
const server = { name: "github", url: "https://example.test/github/mcp", connectionId: "github", token: "current-token" };
|
||||
const second = await runExecutor(config, {
|
||||
runtime: { sessionParams: sessionCodec.deserialize(first.result.sessionParams), taskKey: "default" },
|
||||
runtimeMcp: { getServers: () => [server] }, context: { refreshTools: true },
|
||||
});
|
||||
expect(second.sessionInputs[0]?.resumeSessionId).toBe("backend-session");
|
||||
expect(second.result.sessionParams?.configFingerprint).toBe(first.result.sessionParams?.configFingerprint);
|
||||
expect(second.runtimeOptions[0]?.mcpServers).toEqual([{ type: "http", name: "github", url: server.url, headers: [{ name: "Authorization", value: "Bearer current-token" }] }]);
|
||||
expect(JSON.stringify(sessionCodec.serialize(second.result.sessionParams ?? null))).not.toContain("current-token");
|
||||
const third = await runExecutor(config, { runtime: { sessionParams: sessionCodec.deserialize(second.result.sessionParams) }, context: { refreshTools: true } });
|
||||
expect(third.sessionInputs[0]?.resumeSessionId).toBe("backend-session");
|
||||
expect(third.runtimeOptions[0]?.mcpServers).toEqual([]);
|
||||
});
|
||||
|
||||
it("injects runtime MCP servers and fingerprints their identity without persisting bearer tokens", async () => {
|
||||
const root = await makeTempRoot();
|
||||
const baseConfig = {
|
||||
|
||||
@@ -74,6 +74,8 @@ import {
|
||||
readPaperclipIssueWorkModeFromContext,
|
||||
renderTemplate,
|
||||
resolvePaperclipInstanceRootForAdapter,
|
||||
hydrateFreshSessionHandoff,
|
||||
selectInitialCommunicationGuidance,
|
||||
selectPaperclipPromptSections,
|
||||
resolveLegacyPaperclipDesiredSkillNames,
|
||||
removeMaintainerOnlySkillSymlinks,
|
||||
@@ -1541,6 +1543,7 @@ function buildSessionParams(input: {
|
||||
mode: prepared.mode,
|
||||
stateDir: prepared.stateDir,
|
||||
configFingerprint: prepared.fingerprint,
|
||||
mcpFingerprint: shortHash(prepared.mcpIdentity),
|
||||
...(prepared.requestedModel ? { model: prepared.requestedModel } : {}),
|
||||
...(prepared.requestedThinkingEffort ? { thinkingEffort: prepared.requestedThinkingEffort } : {}),
|
||||
...(prepared.fastMode ? { fastMode: true } : {}),
|
||||
@@ -2208,7 +2211,9 @@ async function buildRuntime(input: {
|
||||
defaultMode: paperclipClaudeSettings.defaultMode,
|
||||
}
|
||||
: null,
|
||||
mcpServers: mcpIdentity,
|
||||
// Qualified built-in ACP harnesses reconnect to the supplied MCP servers
|
||||
// on session/load. Keep their conversation identity independent of tools.
|
||||
mcpServers: ["claude", "codex", "grok", "gemini", "kimi"].includes(acpxAgent) ? [] : mcpIdentity,
|
||||
secretManifestHash: shortHash(secretManifest),
|
||||
// Fold the resolved adapter env (all applied user-configured values —
|
||||
// plain, secret_ref, and stable PAPERCLIP_* config such as an explicit
|
||||
@@ -3021,7 +3026,8 @@ async function buildPrompt(ctx: AdapterExecutionContext, resumedSession: boolean
|
||||
!resumedSession && bootstrapPromptTemplate.trim().length > 0
|
||||
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
||||
: "";
|
||||
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, { resumedSession });
|
||||
await hydrateFreshSessionHandoff(ctx, { resumedSession });
|
||||
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, { resumedSession, includeCommunicationGuidance: false });
|
||||
const externalChatTurn = isPaperclipExternalChatTurn(context.paperclipWake);
|
||||
const shouldUseResumeDeltaPrompt = resumedSession && wakePrompt.length > 0;
|
||||
const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix;
|
||||
@@ -3035,6 +3041,7 @@ async function buildPrompt(ctx: AdapterExecutionContext, resumedSession: boolean
|
||||
const prompt = joinPromptSections([
|
||||
promptInstructionsPrefix,
|
||||
renderedBootstrapPrompt,
|
||||
selectInitialCommunicationGuidance(context, { resumedSession }),
|
||||
wakePrompt,
|
||||
sessionHandoffNote,
|
||||
taskContextNote,
|
||||
@@ -4221,7 +4228,14 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
|
||||
// same session still sees it. The borrow clears the entry's idle timer, so
|
||||
// the reused runtime cannot expire under its own timer while this run uses
|
||||
// it (today's `clearWarmHandleTimer(cached)` after the reuse decision).
|
||||
const cached = canResume ? hostStore.borrow(prepared.sessionKey) : undefined;
|
||||
let cached = canResume ? hostStore.borrow(prepared.sessionKey) : undefined;
|
||||
if (cached && (ctx.context.refreshTools === true
|
||||
|| asString(previousParams.mcpFingerprint, "") !== shortHash(prepared.mcpIdentity)
|
||||
// MCP bearer credentials are run-scoped, even for an unchanged catalog.
|
||||
|| prepared.mcpServers.length > 0)) {
|
||||
await hostStore.discard(prepared.sessionKey);
|
||||
cached = undefined;
|
||||
}
|
||||
childStderrState = cached?.childStderrState ?? { logPath: null, pendingLiveLine: "" };
|
||||
processIdentitySink = cached?.processIdentitySink ?? {
|
||||
current: ctx.onSpawn,
|
||||
|
||||
@@ -30,6 +30,7 @@ export const sessionCodec: AdapterSessionCodec = {
|
||||
...(readString(record.mode) ? { mode: readString(record.mode) } : {}),
|
||||
...(readString(record.stateDir) ? { stateDir: readString(record.stateDir) } : {}),
|
||||
...(readString(record.configFingerprint) ? { configFingerprint: readString(record.configFingerprint) } : {}),
|
||||
...(readString(record.mcpFingerprint) ? { mcpFingerprint: readString(record.mcpFingerprint) } : {}),
|
||||
...(readString(record.workspaceId) ? { workspaceId: readString(record.workspaceId) } : {}),
|
||||
...(readString(record.repoUrl) ? { repoUrl: readString(record.repoUrl) } : {}),
|
||||
...(readString(record.repoRef) ? { repoRef: readString(record.repoRef) } : {}),
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
resolvePaperclipDesiredSkillNames,
|
||||
selectPaperclipTaskMarkdown,
|
||||
selectInitialCommunicationGuidance,
|
||||
hydrateFreshSessionHandoff,
|
||||
runningProcesses,
|
||||
runChildProcess,
|
||||
sanitizeSshRemoteEnv,
|
||||
@@ -3091,6 +3092,9 @@ describe("selectPaperclipTaskMarkdown", () => {
|
||||
expect(selectInitialCommunicationGuidance({ paperclipTaskCommunicationGuidance: " Slack preference " })).toBe("Slack preference");
|
||||
expect(selectInitialCommunicationGuidance(context, { resumedSession: true })).toBe("");
|
||||
expect(selectInitialCommunicationGuidance({})).toBe("");
|
||||
const handoffContext = { ...context, paperclipFreshSessionHandoffMarkdown: "Prior goal and approved decisions" };
|
||||
expect(selectInitialCommunicationGuidance(handoffContext, { resumedSession: true })).toBe("");
|
||||
expect(selectInitialCommunicationGuidance(handoffContext, { resumedSession: false })).toContain("Prior goal and approved decisions");
|
||||
expect(selectPaperclipTaskMarkdown(context, { resumedSession: true })).toBe(compactMarkdown);
|
||||
expect(selectPaperclipTaskMarkdown(context, { includeCommunicationGuidance: false })).toBe(fullMarkdown);
|
||||
context.paperclipWake = { ...wake("issue_monitor_recovery"), recovery: { cause: "process_lost" } } as typeof context.paperclipWake;
|
||||
@@ -3098,6 +3102,20 @@ describe("selectPaperclipTaskMarkdown", () => {
|
||||
expect(selectPaperclipTaskMarkdown(context, { resumedSession: false }).match(/Saved initial guidance/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reads history only at a fresh provider attempt, including resume fallback", async () => {
|
||||
let reads = 0;
|
||||
const ctx = { context: {} as Record<string, unknown>, getFreshSessionHandoff: async () => {
|
||||
reads += 1;
|
||||
return "Original goal and prior answer";
|
||||
} };
|
||||
await hydrateFreshSessionHandoff(ctx, { resumedSession: true });
|
||||
expect(reads).toBe(0);
|
||||
expect(ctx.context.paperclipFreshSessionHandoffMarkdown).toBeUndefined();
|
||||
await hydrateFreshSessionHandoff(ctx, { resumedSession: false });
|
||||
expect(reads).toBe(1);
|
||||
expect(selectInitialCommunicationGuidance(ctx.context)).toContain("Original goal and prior answer");
|
||||
});
|
||||
|
||||
it("falls back to the full markdown when no compact variant exists", () => {
|
||||
expect(
|
||||
selectPaperclipTaskMarkdown(
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
normalizeLegacyRunnerProvider,
|
||||
} from "./paperclip-runner-permissions.js";
|
||||
import type {
|
||||
AdapterExecutionContext,
|
||||
AdapterRuntimeToolAccess,
|
||||
AdapterSkillEntry,
|
||||
AdapterSkillSnapshot,
|
||||
@@ -2175,12 +2176,25 @@ export function isAssignmentShapedPaperclipWakeReason(
|
||||
|
||||
// Select at the actual provider attempt boundary so a failed resume restores
|
||||
// the original snapshot once when retrying with a fresh session.
|
||||
export async function hydrateFreshSessionHandoff(
|
||||
ctx: Pick<AdapterExecutionContext, "context" | "getFreshSessionHandoff">,
|
||||
options: { resumedSession?: boolean } = {},
|
||||
): Promise<void> {
|
||||
if (options.resumedSession === true || !ctx.getFreshSessionHandoff) return;
|
||||
const handoff = await ctx.getFreshSessionHandoff();
|
||||
if (handoff) ctx.context.paperclipFreshSessionHandoffMarkdown = handoff;
|
||||
else delete ctx.context.paperclipFreshSessionHandoffMarkdown;
|
||||
}
|
||||
|
||||
export function selectInitialCommunicationGuidance(
|
||||
context: Record<string, unknown> | null | undefined,
|
||||
options: { resumedSession?: boolean } = {},
|
||||
): string {
|
||||
return options.resumedSession === true
|
||||
? "" : asString(context?.paperclipTaskCommunicationGuidance, "").trim();
|
||||
? "" : joinPromptSections([
|
||||
asString(context?.paperclipTaskCommunicationGuidance, "").trim(),
|
||||
asString(context?.paperclipFreshSessionHandoffMarkdown, "").trim(),
|
||||
]);
|
||||
}
|
||||
|
||||
// Picks the task-context markdown variant for adapters that inject it into the
|
||||
|
||||
@@ -42,6 +42,7 @@ export const LEGACY_SESSIONED_ADAPTER_TYPES = new Set([
|
||||
"cursor_cloud",
|
||||
"cursor",
|
||||
"gemini_local",
|
||||
"grok_local",
|
||||
"hermes_local",
|
||||
"kimi_local",
|
||||
"opencode_local",
|
||||
@@ -74,6 +75,11 @@ export const ADAPTER_SESSION_MANAGEMENT: Record<string, AdapterSessionManagement
|
||||
nativeContextManagement: "unknown",
|
||||
defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY,
|
||||
},
|
||||
grok_local: {
|
||||
supportsSessionResume: true,
|
||||
nativeContextManagement: "unknown",
|
||||
defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY,
|
||||
},
|
||||
kimi_local: {
|
||||
supportsSessionResume: true,
|
||||
nativeContextManagement: "unknown",
|
||||
|
||||
@@ -213,6 +213,8 @@ export interface AdapterExecutionContext {
|
||||
runtime: AdapterRuntime;
|
||||
config: Record<string, unknown>;
|
||||
context: Record<string, unknown>;
|
||||
/** Build bounded history only when an actual provider attempt starts fresh. */
|
||||
getFreshSessionHandoff?: () => Promise<string | null>;
|
||||
runtimeCommandSpec?: AdapterRuntimeCommandSpec | null;
|
||||
executionTarget?: AdapterExecutionTarget | null;
|
||||
/**
|
||||
@@ -463,6 +465,8 @@ export interface ServerAdapterModule {
|
||||
syncSkills?: (ctx: AdapterSkillContext, desiredSkills: string[]) => Promise<AdapterSkillSnapshot>;
|
||||
sessionCodec?: AdapterSessionCodec;
|
||||
sessionManagement?: import("./session-compaction.js").AdapterSessionManagement;
|
||||
/** Selected harness can resume its conversation with this run's tool bindings. */
|
||||
supportsToolRefreshOnResume?: boolean | ((config: Record<string, unknown>) => boolean);
|
||||
supportsLocalAgentJwt?: boolean;
|
||||
/** How this adapter receives Paperclip's run-scoped control tools. */
|
||||
runtimeToolDelivery?: AdapterRuntimeToolDelivery;
|
||||
|
||||
Reference in new issue
Block a user