mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 00:53:38 +02:00
fix: preserve warm Codex turns with incremental managed file checkpoints (#14735)
## Thinking Path > - Paperclip manages AI agents and keeps their instructions and files durable. > - Native Codex runners can keep a process alive between compatible turns. > - Managed file collection stopped that process after each turn, which defeated warm reuse. > - Agent folders can contain large images and other files, so full copies on every turn are expensive. > - This change keeps one managed directory for the live session and saves only file changes after each turn. > - Ownership, authorization, instruction changes, and process retirement still control when reuse is safe. ## Linked Issues or Issue Description Related: #13710 introduced native warm session reuse. This fixes managed file collection that still forced those sessions to stop. No duplicate open PR or issue was found. **What happened?** With managed instructions and warm native Codex enabled, consecutive turns reused a Daytona sandbox but started a new runner process each time. The managed directory collector required process termination before saving files. **Expected behavior** Compatible turns keep the same process and managed `AGENT_HOME`. Each completed turn saves added, changed, and deleted files before the next turn starts. Unchanged large files do not transfer again. **Steps to reproduce** 1. Use a native Codex agent with managed instructions and a reusable Daytona environment. 2. Enable warm session reuse and run three turns on the same task. 3. Write a large binary on the first turn, edit a small note on each turn, and delete a file on the second turn. 4. Compare process identity across turns and read the canonical files through the public agent-files API. **Paperclip version or commit** Reproduced on `d30b03bd8c17604cdab1533eeeeb087aba30e8b1`. **Deployment mode** Local server with remote Daytona execution; cloud native runner uses the same path. ## What Changed - Retain the managed directory only for the verified owner of a live native Codex session. - Checkpoint each completed turn before releasing the session for reuse. Retry unstable captures, then stop and collect when a warm checkpoint cannot be validated. - Compare metadata and cached hashes, stream only changed file payloads, record deletions, and validate path, content, quota, and authorization before saving. - Rotate sessions when canonical files, loaded instructions, credentials, or launch policy change. Fence stale collection and cleanup callbacks from later owners. - Keep cleanup and recovery aware of the current session owner. Recheck canonical files under the writer lock at handoff, attach the successor collector before fallible bookkeeping, and emit one final save receipt on checkpoint fallback. Preserve storage warnings across unchanged checkpoints. - Add regression coverage and a three-turn Daytona test with independent public API file checks, an unchanged 8 MiB binary, deletion checks, and strict process identity checks. - Document checkpoint consistency, lifecycle behavior, and local run-log counters. - Replace a timing assumption in the Daytona teardown test with explicit transfer-arrival gates after CI exposed an unset release callback. ## Verification - Full local `pnpm -r typecheck` and `pnpm build` passed. Server checks were repeated after the final storage-warning fix. - Runner E2E typecheck and 749 runner E2E unit tests passed. - Focused file checkpoint, directory ownership, instruction collection, native session, and merge tests passed. After review fixes, the managed-directory and native-session suites passed 550 tests, including intervening canonical edits, same-run fresh restore, failed handoff collection, and one-call fallback collection. Server typecheck passed again. The Daytona plugin suite passed 218 tests. The quota-warning regression failed before the fix and passed afterward. - Three real Daytona campaigns passed before the final handoff review fixes. The latest kept PID 547 across all three turns. The first checkpoint copied 8,388,635 bytes; the next two copied 36 and 54 bytes. Public API reads verified the binary, note contents, and deletion after every turn. Test cleanup deleted the sandbox. - The final head was also deployed to an isolated cloud staging instance and passed three UI-triggered native Codex turns with managed instructions. All three retained the same process ID/start time, native session, provider session, runner instance, and Daytona sandbox. Checkpoints copied 8,388,643 bytes on turn 1, then only 52 and 78 bytes on turns 2 and 3; those warm captures also hashed only 52 and 78 bytes. Independent canonical API reads verified every byte of the unchanged 8 MiB binary and the exact note contents after every turn; the deleted file returned 404 after turns 2 and 3. After restoring the original lifecycle and agent-auth configuration, removing the temporary secret, pausing the test agent, and deleting both test sandboxes, independent canonical API reads still verified the entire binary, the final 78-byte three-line note, and the deletion. The native runner flag remained enabled and the final serving revision remained the PR head. - Two earlier staging attempts are preserved as failures and are excluded from the acceptance result: a saved ChatGPT login failed with a provider routing 401, and its subsequent stopped-sandbox retry failed before provider startup with a closed-lease admission error. The successful campaign used a fresh sandbox and a temporary encrypted API-key binding. The stopped-lease retry remains unexplained; this campaign does not establish recovery of that failed sandbox. - All [Paperclip CI gates](https://github.com/paperclipai/paperclip/actions/runs/36750397355) pass on `26ef2ef56a389259246809805c0b34a4747eb86b`, including full test partitions, build, typecheck, runner verification, E2E shards, and the Canary clean public-npm install. Greptile reviewed that exact head at 5/5 with no unresolved review threads or outstanding findings. - Full local repository coverage used the existing CI partitions, but the 40,000-file Git streaming stress test timed out and its local retry was interrupted by macOS thermal emergency sleep; this is not a green full local suite claim. The exact stress test passed on the final head in [CI server shard 2/12](https://github.com/paperclipai/paperclip/actions/runs/36750397355/job/110008294290), in 111.9 seconds. - Repeat the live test with configured credentials and a Linux runner artifact: `pnpm test:e2e:runner -- --id daytona-warm-continuity.runner-codex.daytona.warm-three-turn`. ## Risks - This is a file-level checkpoint, not an atomic snapshot of the whole folder. Background writes after a capture are saved by the next checkpoint or final stopped collection. - Metadata scans still visit all paths. Modified files transfer in full; unchanged files do not rehash or transfer. - Incorrect ownership or reuse could collect the wrong directory. Run ownership fences, current authorization, stable capture validation, and stopped collection fallbacks are covered by tests. - Warm reuse remains opt-in. No database migration or fleet default changes. ## Model Used OpenAI GPT-6 through Codex, with reasoning, code editing, tool use, and test execution. The exact serving model ID and context-window size are not exposed by this session. ## 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
d432dc7fa3
commit
b54b2dc35c
23 files changed
+1195
-92
No files matched your search
@@ -276,6 +276,7 @@ import {
|
||||
buildNativeHarnessBackupManifest,
|
||||
cancelNativeSession,
|
||||
closeWarmNativeSessionsForEnvironment,
|
||||
reserveWarmNativeInstructionDirectory,
|
||||
closeIdleWarmNativeSessionsForRestart,
|
||||
createGovernedWaitEventObservation,
|
||||
createRemoteRunnerProcessLauncher,
|
||||
@@ -5918,6 +5919,121 @@ describe("native session same-turn steering", () => {
|
||||
});
|
||||
|
||||
describe("native warm session supervision", () => {
|
||||
describe("managed directory warm checkpoints", () => {
|
||||
const result = { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: "turn", normalizedSessionId: "managed", providerSessionId: "provider", driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
async function start(name: string, checkpoint = true) {
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1;
|
||||
const close = vi.fn(async () => undefined);
|
||||
const session = { close };
|
||||
const collectStopped = vi.fn(async () => undefined);
|
||||
const checkpointWarm = vi.fn(async () => checkpoint);
|
||||
const target = { kind: "remote" as const, transport: "sandbox" as const, environmentId: name, remoteCwd: `/tmp/${name}`, sandboxLeaseAcquisition: { outcome: "created" as const, providerLeaseId: name } };
|
||||
const copy = { runId: current.binding.runId, root: `/tmp/${name}/home`, collectStopped, checkpointWarm, hasChanges: vi.fn(async () => true) };
|
||||
state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.(session); return result; });
|
||||
const run = (next: NativeExecutionInputV1, nextCopy = copy) => executePaperclipNativeSession({
|
||||
db: leaseDb(next), execution: next, runnerInstanceId: name, runnerExecutionTarget: target, instructionWorkingCopy: nextCopy });
|
||||
await run(current);
|
||||
const reserve = (canReuse: () => Promise<boolean>, nextTarget = target) => reserveWarmNativeInstructionDirectory({
|
||||
companyId: current.binding.companyId, agentId: current.binding.agentId, previousRunId: current.binding.runId,
|
||||
runId: `${name}-two`, target: nextTarget, canReuse });
|
||||
return { current, copy, close, session, target, run, reserve };
|
||||
}
|
||||
afterEach(async () => { await closeIdleWarmNativeSessionsForRestart(); });
|
||||
|
||||
it("saves each turn while retaining the provider and collects only the latest directory owner at retirement", async () => {
|
||||
const f = await start("managed-retained");
|
||||
expect(f.copy.checkpointWarm).toHaveBeenCalledOnce();
|
||||
expect(f.copy.hasChanges).not.toHaveBeenCalled();
|
||||
expect(f.close).not.toHaveBeenCalled();
|
||||
const reservation = await f.reserve(async () => true);
|
||||
expect(reservation?.reuseRunId).toBe(f.current.binding.runId);
|
||||
const secondCopy = { ...f.copy, runId: "managed-retained-two", collectStopped: vi.fn(async () => undefined) };
|
||||
reservation!.adopt(secondCopy.root, secondCopy.collectStopped);
|
||||
state.execute.mockImplementationOnce(async options => {
|
||||
expect(options.existingSession).toBe(f.session);
|
||||
await options.onSession?.(f.session); return result;
|
||||
});
|
||||
await f.run({ ...f.current, binding: { ...f.current.binding, runId: secondCopy.runId } }, secondCopy);
|
||||
await reservation!.release();
|
||||
expect(f.close).not.toHaveBeenCalled();
|
||||
expect(f.copy.checkpointWarm).toHaveBeenCalledTimes(2);
|
||||
await closeWarmNativeSessionsForEnvironment({ environmentId: f.target.environmentId, reason: "test retirement" });
|
||||
expect(f.close).toHaveBeenCalledOnce();
|
||||
expect(f.copy.collectStopped).not.toHaveBeenCalled();
|
||||
expect(secondCopy.collectStopped).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("stops before collecting when a checkpoint cannot stabilize", async () => {
|
||||
const f = await start("managed-fallback", false);
|
||||
expect(f.close).toHaveBeenCalledOnce();
|
||||
expect(f.copy.collectStopped).toHaveBeenCalledOnce();
|
||||
expect(f.close.mock.invocationCallOrder[0]).toBeLessThan(f.copy.collectStopped.mock.invocationCallOrder[0]!);
|
||||
});
|
||||
|
||||
it.each(["canonical-edit", "replaced-environment", "authorization-error"])("retires before admission for %s", async reason => {
|
||||
const f = await start(`managed-${reason}`);
|
||||
const validation = vi.fn(async () => { if (reason === "authorization-error") throw new Error("authorization revoked"); return reason !== "canonical-edit"; });
|
||||
const attempt = f.reserve(validation, reason === "replaced-environment" ? { ...f.target, remoteCwd: "/different" } : f.target);
|
||||
if (reason === "authorization-error") await expect(attempt).rejects.toThrow("authorization revoked");
|
||||
else expect(await attempt).toBeNull();
|
||||
expect(f.close).toHaveBeenCalledOnce();
|
||||
expect(f.copy.collectStopped).toHaveBeenCalledOnce();
|
||||
if (reason === "replaced-environment") expect(validation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains failed containment for retry and forbids warm reuse until it succeeds", async () => {
|
||||
const f = await start("managed-stop-failure");
|
||||
f.close.mockRejectedValueOnce(new Error("containment failed"));
|
||||
await expect(f.reserve(async () => false)).rejects.toThrow("containment failed");
|
||||
expect(f.copy.collectStopped).not.toHaveBeenCalled();
|
||||
const canReuse = vi.fn(async () => true);
|
||||
expect(await f.reserve(canReuse)).toBeNull();
|
||||
expect(canReuse).not.toHaveBeenCalled();
|
||||
expect(f.close).toHaveBeenCalledTimes(2);
|
||||
expect(f.copy.collectStopped).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("cleans up the successor if preparation fails after directory handoff", async () => {
|
||||
const f = await start("managed-failed-preparation");
|
||||
const reservation = await f.reserve(async () => true);
|
||||
const collectSuccessor = vi.fn(async () => undefined);
|
||||
reservation!.adopt(f.copy.root, collectSuccessor);
|
||||
await reservation!.release();
|
||||
await reservation!.release();
|
||||
expect(f.close).toHaveBeenCalledOnce();
|
||||
expect(f.copy.collectStopped).not.toHaveBeenCalled();
|
||||
expect(collectSuccessor).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("preserves a handed-off directory when configuration rotates the old provider", async () => {
|
||||
const f = await start("managed-policy-rotation");
|
||||
const reservation = await f.reserve(async () => true);
|
||||
const nextCopy = { ...f.copy, runId: "managed-policy-rotation-two", collectStopped: vi.fn(async () => undefined) };
|
||||
reservation!.adopt(nextCopy.root, nextCopy.collectStopped);
|
||||
const replacement = { close: vi.fn(async () => undefined) };
|
||||
state.execute.mockImplementationOnce(async options => {
|
||||
expect(options.existingSession).toBeUndefined();
|
||||
expect(f.close).toHaveBeenCalledOnce();
|
||||
expect(nextCopy.collectStopped).not.toHaveBeenCalled();
|
||||
await options.onSession?.(replacement); return result;
|
||||
});
|
||||
await f.run({ ...f.current, binding: { ...f.current.binding, runId: nextCopy.runId },
|
||||
session: { ...f.current.session, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 120_000 } } }, nextCopy);
|
||||
await reservation!.release();
|
||||
expect(nextCopy.collectStopped).not.toHaveBeenCalled();
|
||||
await closeWarmNativeSessionsForEnvironment({ environmentId: f.target.environmentId, reason: "test" });
|
||||
expect(nextCopy.collectStopped).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("cannot reuse a provider with a different registered directory", async () => {
|
||||
const f = await start("managed-root-replaced");
|
||||
state.execute.mockImplementationOnce(async options => { expect(options.existingSession).toBeUndefined(); return result; });
|
||||
await f.run({ ...f.current, binding: { ...f.current.binding, runId: "managed-root-two" } }, { ...f.copy, root: "/new/home" });
|
||||
expect(f.close).toHaveBeenCalledOnce();
|
||||
expect(f.copy.collectStopped).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
{ changed: false, closeFails: false },
|
||||
{ changed: true, closeFails: false },
|
||||
|
||||
@@ -391,6 +391,9 @@ function clearNativeRuntimeRequestResolutions(runId: string): void {
|
||||
}
|
||||
|
||||
type WarmNativeSession = {
|
||||
agentId: string;
|
||||
instructionCopy?: { runId: string; root?: string; targetIdentity: string; collectStopped: () => Promise<void> };
|
||||
preparingRunId?: string;
|
||||
managedAiCredentialIdentity?: string;
|
||||
credentialRunId?: string;
|
||||
githubAccess?: NativeGitHubAccess;
|
||||
@@ -408,10 +411,13 @@ type WarmNativeSession = {
|
||||
lastActivityAt: string;
|
||||
};
|
||||
|
||||
async function closeWarmNativeSession(entry: WarmNativeSession, reason: string) {
|
||||
async function closeWarmNativeSession(entry: WarmNativeSession, reason: string, preserveInstructionsForRunId?: string) {
|
||||
// Revoke before awaiting process retirement/checkpoint IO.
|
||||
const stopping = entry.githubAccess?.stop();
|
||||
try { await entry.session.close({ reason }); }
|
||||
try {
|
||||
await entry.session.close({ reason });
|
||||
if (entry.instructionCopy?.runId !== preserveInstructionsForRunId) await entry.instructionCopy?.collectStopped();
|
||||
}
|
||||
finally { await stopping; }
|
||||
}
|
||||
|
||||
@@ -420,6 +426,56 @@ const warmNativeSessions = new Map<string, WarmNativeSession>();
|
||||
// not inspect or quarantine that owner's state until the save has finished.
|
||||
const closingWarmNativeSessions = new Map<string, Promise<void>>();
|
||||
|
||||
function instructionTargetIdentity(target?: AdapterExecutionTarget | null): string {
|
||||
return JSON.stringify(target?.kind === "remote" ? {
|
||||
environmentId: target.environmentId, cwd: target.remoteCwd,
|
||||
providerLeaseId: target.transport === "sandbox" ? target.sandboxLeaseAcquisition?.providerLeaseId : target.spec,
|
||||
} : { kind: "local", environmentId: target?.environmentId });
|
||||
}
|
||||
|
||||
/** Reserve the actual live owner before handing its directory to another run.
|
||||
* A persisted conversation alone is not proof that a working tree is reusable. */
|
||||
export async function reserveWarmNativeInstructionDirectory(input: {
|
||||
companyId: string; agentId: string; previousRunId: string; runId: string; target?: AdapterExecutionTarget | null;
|
||||
canReuse: () => Promise<boolean>;
|
||||
}): Promise<{ reuseRunId: string; adopt: (root: string, collectStopped: () => Promise<void>) => void; release: () => Promise<void> } | null> {
|
||||
for (const [id, entry] of warmNativeSessions) {
|
||||
if (entry.companyId !== input.companyId || entry.agentId !== input.agentId || entry.instructionCopy?.runId !== input.previousRunId) continue;
|
||||
if (entry.busy || entry.preparingRunId) throw new Error("native_session_supervisor_busy");
|
||||
if (entry.idleTimer) clearTimeout(entry.idleTimer);
|
||||
entry.idleTimer = null;
|
||||
entry.preparingRunId = input.runId;
|
||||
const retire = async (reason: string) => {
|
||||
entry.closeOnReleaseReason = reason;
|
||||
try {
|
||||
await closeWarmNativeSession(entry, reason);
|
||||
if (warmNativeSessions.get(id) === entry) warmNativeSessions.delete(id);
|
||||
} finally {
|
||||
// Failed containment remains registered and cannot be adopted. The next
|
||||
// admission retries retirement instead of launching over a live owner.
|
||||
entry.preparingRunId = undefined;
|
||||
}
|
||||
};
|
||||
let reusable = false;
|
||||
const targetProven = input.target?.kind !== "remote" || input.target.transport !== "sandbox" || Boolean(input.target.sandboxLeaseAcquisition?.providerLeaseId);
|
||||
try { reusable = targetProven && !entry.closeOnReleaseReason && entry.instructionCopy.targetIdentity === instructionTargetIdentity(input.target) && await input.canReuse(); }
|
||||
finally {
|
||||
if (!reusable) {
|
||||
await retire("managed agent files changed or environment replaced");
|
||||
}
|
||||
}
|
||||
if (!reusable) return null;
|
||||
return { reuseRunId: input.previousRunId, adopt: (root, collectStopped) => {
|
||||
entry.instructionCopy = { runId: input.runId, root, targetIdentity: instructionTargetIdentity(input.target), collectStopped };
|
||||
}, release: async () => {
|
||||
if (warmNativeSessions.get(id) === entry && entry.preparingRunId === input.runId) {
|
||||
await retire("managed warm turn preparation ended without attachment");
|
||||
}
|
||||
} };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close idle native sessions before an operator destroys their remote
|
||||
* environment. A warm runner owns a long-lived sandbox command stream, so the
|
||||
@@ -457,7 +513,7 @@ async function closeIdleWarmNativeSessions(input: {
|
||||
if (input.environmentId !== undefined && entry.environmentId !== input.environmentId) {
|
||||
continue;
|
||||
}
|
||||
if (entry.busy || executingRunnerdSessionScopes.has(sessionId)) {
|
||||
if (entry.busy || entry.preparingRunId || executingRunnerdSessionScopes.has(sessionId)) {
|
||||
// A busy turn can complete while another idle session is checkpointing.
|
||||
// Fence that entry now so its eventual release cannot leave a new idle
|
||||
// owner behind after the shutdown sweep has already passed it.
|
||||
@@ -7181,9 +7237,12 @@ export async function executePaperclipNativeSession(input: {
|
||||
chatAttachmentReadScope?: NativeChatAttachmentReadScope;
|
||||
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
|
||||
onEvent?: (event: AdapterRuntimeEvent) => Promise<void>;
|
||||
/** Only this run's registered private instruction entry.
|
||||
* Probe at terminal; persist only after owned shutdown. */
|
||||
/** Only this run's registered directory. Validate a warm checkpoint at the
|
||||
* terminal boundary, or collect after owned shutdown when it cannot settle. */
|
||||
instructionWorkingCopy?: {
|
||||
runId?: string;
|
||||
root?: string;
|
||||
checkpointWarm?: () => Promise<boolean>;
|
||||
hasChanges: () => Promise<boolean>;
|
||||
collectStopped: () => Promise<void>;
|
||||
};
|
||||
@@ -8055,6 +8114,8 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
if (warmSessionId !== null && warmConfigDigest !== null) {
|
||||
const entry = warmNativeSessions.get(warmSessionId);
|
||||
if (entry) {
|
||||
if (entry.preparingRunId && entry.preparingRunId !== input.execution.binding.runId) throw new Error("native_session_supervisor_busy");
|
||||
entry.preparingRunId = undefined;
|
||||
// Old run-scoped environments still require process replacement. A
|
||||
// session-owned broker can change run authority without replacing it.
|
||||
const hasBrokerCapability = Boolean(
|
||||
@@ -8067,6 +8128,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
if (
|
||||
entry.closeOnReleaseReason !== undefined ||
|
||||
entry.configDigest !== warmConfigDigest ||
|
||||
entry.instructionCopy?.root !== input.instructionWorkingCopy?.root ||
|
||||
entry.managedAiCredentialIdentity !== input.managedAiCredentialIdentity ||
|
||||
credentialRunChanged ||
|
||||
Boolean(entry.githubAccess) !== Boolean(input.managedGitHub) ||
|
||||
@@ -8080,7 +8142,10 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
if (entry.busy) throw new Error("native_session_supervisor_busy");
|
||||
if (entry.idleTimer !== null) clearTimeout(entry.idleTimer);
|
||||
warmNativeSessions.delete(warmSessionId);
|
||||
await closeWarmNativeSession(entry, "warm native session configuration changed");
|
||||
// Preparation may already have handed this directory to the incoming
|
||||
// run. Retiring the old transport must not delete the new run's root;
|
||||
// its own stop callback owns collection from this point forward.
|
||||
await closeWarmNativeSession(entry, "warm native session configuration changed", input.execution.binding.runId);
|
||||
persistedWarmSession = loadWarmNativeCheckpoint(
|
||||
input.execution,
|
||||
warmConfigDigest,
|
||||
@@ -8417,6 +8482,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
existing.session = session;
|
||||
} else
|
||||
warmNativeSessions.set(warmSessionId, {
|
||||
agentId: input.execution.binding.agentId,
|
||||
managedAiCredentialIdentity: input.managedAiCredentialIdentity,
|
||||
githubAuthenticationMode:
|
||||
input.runnerEnvironment?.PAPERCLIP_GITHUB_AUTH_MODE,
|
||||
@@ -8441,6 +8507,11 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
idleTimer: null,
|
||||
lastActivityAt: new Date().toISOString(),
|
||||
});
|
||||
const owner = warmNativeSessions.get(warmSessionId);
|
||||
if (owner && input.instructionWorkingCopy?.runId) owner.instructionCopy = {
|
||||
runId: input.instructionWorkingCopy.runId, root: input.instructionWorkingCopy.root, targetIdentity: instructionTargetIdentity(input.runnerExecutionTarget),
|
||||
collectStopped: input.instructionWorkingCopy.collectStopped,
|
||||
};
|
||||
} else if (!session && warmSessionId !== null) {
|
||||
const existing = warmNativeSessions.get(warmSessionId);
|
||||
// onSession(null) quarantines a transport that can no longer
|
||||
@@ -9090,7 +9161,8 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
const instructionCopy = input.instructionWorkingCopy;
|
||||
const ownedSession = warmNativeSessions.get(warmSessionId);
|
||||
const collectInstructions = Boolean(instructionCopy && ownedSession?.ownerToken === warmSessionOwnerToken &&
|
||||
await instructionCopy.hasChanges());
|
||||
(instructionCopy.checkpointWarm ? !await instructionCopy.checkpointWarm() : await instructionCopy.hasChanges()));
|
||||
const collectedByOwner = ownedSession?.instructionCopy?.collectStopped === instructionCopy?.collectStopped;
|
||||
if (collectInstructions && ownedSession) {
|
||||
// Keep the unchanged warm path intact. A changed private instruction copy
|
||||
// requires the existing checkpoint-and-close boundary before collection.
|
||||
@@ -9102,7 +9174,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
lifecyclePolicy.idleTimeoutMs,
|
||||
false,
|
||||
);
|
||||
if (collectInstructions) await instructionCopy!.collectStopped();
|
||||
if (collectInstructions && !collectedByOwner) await instructionCopy!.collectStopped();
|
||||
}
|
||||
const adapterResult: AdapterExecutionResult = {
|
||||
exitCode: native.terminal.runTerminalState === "succeeded" ? 0 : 1,
|
||||
|
||||
Reference in new issue
Block a user