mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
Fix Copilot materialization rollback and cover replay identity
Roll back only files and directories created by a failed materialization. Cover partial writes, retry, foreign entries, and session replay isolation. Refresh the Copilot v7 source binding. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
913f374191
commit
654ec2a9cc
9 files changed
+199
-49
No files matched your search
@@ -223,7 +223,7 @@ impl AcpxProviderDescriptor {
|
||||
"1.0.88",
|
||||
None,
|
||||
None,
|
||||
"sha256:9f98bf11135944aa8df56635d5c2e24b6a073e23a752cdf86cb9c044bfea74a5",
|
||||
"sha256:b11721382293b39c1d6dd363eae547b5eae0ccca2cd5dcafc9127cc060ee9526",
|
||||
),
|
||||
"grok" => (
|
||||
"grok-4.7",
|
||||
@@ -2812,7 +2812,7 @@ mod tests {
|
||||
"copilot",
|
||||
"@github/copilot",
|
||||
"1.0.88",
|
||||
"sha256:9f98bf11135944aa8df56635d5c2e24b6a073e23a752cdf86cb9c044bfea74a5",
|
||||
"sha256:b11721382293b39c1d6dd363eae547b5eae0ccca2cd5dcafc9127cc060ee9526",
|
||||
None,
|
||||
None,
|
||||
"explicit-model",
|
||||
|
||||
@@ -7,7 +7,7 @@ import { COPILOT_VERSION, materializePinnedCopilotBinary, resolveCopilotDistribu
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 384 * 1024 * 1024;
|
||||
const PROFILE_DIGEST = "sha256:9f98bf11135944aa8df56635d5c2e24b6a073e23a752cdf86cb9c044bfea74a5";
|
||||
const PROFILE_DIGEST = "sha256:b11721382293b39c1d6dd363eae547b5eae0ccca2cd5dcafc9127cc060ee9526";
|
||||
|
||||
/** Build-time only; outputRoot is the exact runner-owned platform asset directory. */
|
||||
export async function buildPinnedCopilotDistribution({ outputRoot, platform = process.platform, architecture = process.arch }, { fetchImpl = fetch } = {}) {
|
||||
|
||||
@@ -9,8 +9,8 @@ export const COPILOT_INNER_DISTRIBUTIONS = Object.freeze({
|
||||
});
|
||||
export const COPILOT_MESSAGE_MAPPING_ANCHOR = 'case"assistant.message_start":return null;case"assistant.message_delta":return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e.data.deltaContent}};case"assistant.message":return null;';
|
||||
export const COPILOT_MESSAGE_MAPPING_REPLACEMENT = 'case"assistant.message_start":return{sessionUpdate:"agent_message_chunk",messageId:e.data.messageId,content:{type:"text",text:""}};case"assistant.message_delta":return{sessionUpdate:"agent_message_chunk",messageId:e.data.messageId,content:{type:"text",text:e.data.deltaContent}};case"assistant.message":return null;';
|
||||
const REPLAY_ANCHOR = 'case"assistant.message":return t.data.content?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.data.content}}:null;';
|
||||
const REPLAY_REPLACEMENT = 'case"assistant.message":return{sessionUpdate:"agent_message_chunk",messageId:t.data.messageId,content:{type:"text",text:t.data.content??""}};';
|
||||
export const COPILOT_REPLAY_MAPPING_ANCHOR = 'case"assistant.message":return t.data.content?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.data.content}}:null;';
|
||||
export const COPILOT_REPLAY_MAPPING_REPLACEMENT = 'case"assistant.message":return{sessionUpdate:"agent_message_chunk",messageId:t.data.messageId,content:{type:"text",text:t.data.content??""}};';
|
||||
const hash = bytes => createHash("sha256").update(bytes).digest("hex");
|
||||
const MAX_TAR_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
@@ -34,7 +34,7 @@ export function readPinnedCopilotInnerDistribution(binary, target) {
|
||||
export function patchPinnedCopilotMessageIdentity(bytes) {
|
||||
if (!Buffer.isBuffer(bytes) || hash(bytes) !== COPILOT_APP_SHA256) throw new Error("Copilot message mapping source digest mismatch");
|
||||
let source = bytes.toString("utf8");
|
||||
for (const [anchor, replacement] of [[COPILOT_MESSAGE_MAPPING_ANCHOR, COPILOT_MESSAGE_MAPPING_REPLACEMENT], [REPLAY_ANCHOR, REPLAY_REPLACEMENT]]) {
|
||||
for (const [anchor, replacement] of [[COPILOT_MESSAGE_MAPPING_ANCHOR, COPILOT_MESSAGE_MAPPING_REPLACEMENT], [COPILOT_REPLAY_MAPPING_ANCHOR, COPILOT_REPLAY_MAPPING_REPLACEMENT]]) {
|
||||
if (source.indexOf(anchor) < 0 || source.indexOf(anchor) !== source.lastIndexOf(anchor)) throw new Error("Copilot message mapping patch anchor is not unique");
|
||||
source = source.replace(anchor, replacement);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { runInNewContext } from "node:vm";
|
||||
import { COPILOT_MESSAGE_MAPPING_REPLACEMENT, patchPinnedCopilotMessageIdentity, readCopilotInnerTar, readPinnedCopilotInnerDistribution } from "./copilot-inner-distribution.mjs";
|
||||
import { COPILOT_MESSAGE_MAPPING_REPLACEMENT, COPILOT_REPLAY_MAPPING_REPLACEMENT, patchPinnedCopilotMessageIdentity, readCopilotInnerTar, readPinnedCopilotInnerDistribution } from "./copilot-inner-distribution.mjs";
|
||||
|
||||
function file(name, content = "data", { type = "0", mode = 0o644, prefix = "" } = {}) {
|
||||
const bytes = Buffer.from(content); const h = Buffer.alloc(512);
|
||||
@@ -60,3 +60,21 @@ test("ordered mapping retains native IDs including an empty start and never echo
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(events.map(map).filter(Boolean))).map(e => [e.messageId, e.content.text]),
|
||||
[["first", ""], ["first", "same"], ["second", ""], ["second", "sa"], ["second", "me"], ["empty-final", ""]]);
|
||||
});
|
||||
|
||||
test("the patched replay branch emits full messages once, with ordered identities and empty finals", () => {
|
||||
const live = runInNewContext(`e=>{switch(e.type){${COPILOT_MESSAGE_MAPPING_REPLACEMENT}default:return null}}`);
|
||||
const replay = runInNewContext(`t=>{switch(t.type){${COPILOT_REPLAY_MAPPING_REPLACEMENT}default:return null}}`);
|
||||
const history = [
|
||||
{ type: "assistant.message", data: { messageId: "old-first", content: "same" } },
|
||||
{ type: "assistant.message", data: { messageId: "old-second", content: "same" } },
|
||||
{ type: "assistant.message", data: { messageId: "old-empty", content: "" } },
|
||||
];
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(history.map(replay))).map(e => [e.messageId, e.content.text]),
|
||||
[["old-first", "same"], ["old-second", "same"], ["old-empty", ""]]);
|
||||
assert.deepEqual(history.map(live), [null, null, null]);
|
||||
// Completion has opposite roles: historical content is replayed once, while
|
||||
// the active mapper must not echo text already emitted as live deltas.
|
||||
const final = history[0];
|
||||
assert.equal(replay(final).content.text, "same");
|
||||
assert.equal(live(final), null);
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants, closeSync, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { constants, closeSync, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
@@ -38,48 +38,78 @@ export function materializePinnedCopilotBinary(options = {}) {
|
||||
const sourceDigest = createHash("sha256").update(bytes).digest("hex");
|
||||
if (sourceDigest !== distribution.executableDigest) throw new Error("Copilot executable digest does not match its pinned distribution");
|
||||
const inner = readPinnedCopilotInnerDistribution(bytes, `${options.platform ?? process.platform}-${options.architecture ?? process.arch}`);
|
||||
let target = source;
|
||||
if (options.targetDirectory !== undefined) {
|
||||
const directory = realpathSync(options.targetDirectory);
|
||||
if (!lstatSync(directory).isDirectory()) throw new Error("Copilot target must be a directory");
|
||||
target = join(directory, "copilot");
|
||||
// Refuse replacement and links, including a previous incompatible materialization.
|
||||
const fd = openSync(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o755);
|
||||
let success = false;
|
||||
try {
|
||||
writeFileSync(fd, bytes);
|
||||
fchmodSync(fd, 0o755);
|
||||
fsyncSync(fd);
|
||||
success = true;
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
if (!success) unlinkSync(target);
|
||||
}
|
||||
}
|
||||
const entries = [{ path: "copilot", sha256: sourceDigest, size: bytes.length, executable: true }];
|
||||
const output = options.targetDirectory === undefined ? packageRoot : realpathSync(options.targetDirectory);
|
||||
const target = options.targetDirectory === undefined ? source : join(output, "copilot");
|
||||
const entries = [{ path: "copilot", sha256: sourceDigest, size: bytes.length, executable: true }];
|
||||
const files = options.targetDirectory === undefined ? [] : [{ path: "copilot", bytes, executable: true }];
|
||||
// Preserve every embedded asset; only the hash-pinned app's message mapping
|
||||
// changes. Never import or execute any archive entry during materialization.
|
||||
mkdirSync(join(output, "distribution"), { mode: 0o755 });
|
||||
for (const [path, entry] of inner) {
|
||||
const relative = `distribution/${path}`;
|
||||
const destination = join(output, relative);
|
||||
mkdirSync(dirname(destination), { recursive: true, mode: 0o755 });
|
||||
if (realpathSync(dirname(destination)) !== dirname(destination)) throw new Error("Copilot inner destination redirects through links");
|
||||
writeFileSync(destination, entry.bytes, { flag: "wx", mode: entry.executable ? 0o755 : 0o644 });
|
||||
files.push({ path: relative, ...entry });
|
||||
entries.push({ path: relative, sha256: createHash("sha256").update(entry.bytes).digest("hex"), size: entry.bytes.length, executable: entry.executable });
|
||||
}
|
||||
entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
||||
const closureSha256 = createHash("sha256").update(JSON.stringify(entries)).digest("hex");
|
||||
const manifestPath = join(options.targetDirectory === undefined ? packageRoot : realpathSync(options.targetDirectory), ".paperclip-copilot-closure.json");
|
||||
const closure = `${JSON.stringify({ schema: "paperclip.native_distribution_closure.v1", entries })}\n`;
|
||||
try { writeFileSync(manifestPath, closure, { flag: "wx", mode: 0o644 }); }
|
||||
catch (error) {
|
||||
if (error.code !== "EEXIST" || readPinnedFile(manifestPath, 256 * 1024).toString("utf8") !== closure) throw error;
|
||||
}
|
||||
const manifestPath = join(output, ".paperclip-copilot-closure.json");
|
||||
files.push({ path: ".paperclip-copilot-closure.json", bytes: Buffer.from(`${JSON.stringify({ schema: "paperclip.native_distribution_closure.v1", entries })}\n`), executable: false });
|
||||
writeCopilotMaterialization(output, files);
|
||||
return { packageName: distribution.packageName, version: COPILOT_VERSION, sourceDigest, target, manifestPath, closureSha256 };
|
||||
}
|
||||
|
||||
/** Build-only writer for already verified entries; never grants launch authority.
|
||||
* Roll back only entries this invocation exclusively created, even when a write
|
||||
* failed partway through. Never recursively remove a caller's output directory.
|
||||
*/
|
||||
export function writeCopilotMaterialization(output, files) {
|
||||
if (realpathSync(output) !== output || !lstatSync(output).isDirectory()) throw new Error("Copilot target must be an owned real directory");
|
||||
const root = lstatSync(output, { bigint: true });
|
||||
const created = [];
|
||||
const same = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
||||
const assertRoot = () => {
|
||||
const current = lstatSync(output, { bigint: true });
|
||||
if (!current.isDirectory() || !same(root, current) || realpathSync(output) !== output) throw new Error("Copilot output identity changed");
|
||||
};
|
||||
try {
|
||||
for (const entry of files) {
|
||||
if (typeof entry.path !== "string" || entry.path.includes("\\") || entry.path.split("/").some(part => !part || part === "." || part === "..")) throw new Error("Unsafe Copilot output entry");
|
||||
assertRoot();
|
||||
const parts = entry.path.split("/");
|
||||
for (let i = 1; i < parts.length; i++) {
|
||||
const directory = join(output, ...parts.slice(0, i));
|
||||
try {
|
||||
mkdirSync(directory, { mode: 0o755 });
|
||||
created.push({ path: directory, stat: lstatSync(directory, { bigint: true }), directory: true });
|
||||
} catch (error) { if (error.code !== "EEXIST") throw error; }
|
||||
if (!lstatSync(directory).isDirectory() || realpathSync(directory) !== directory) throw new Error("Copilot inner destination redirects through links");
|
||||
}
|
||||
const path = join(output, entry.path);
|
||||
const mode = entry.executable ? 0o755 : 0o644;
|
||||
const fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, mode);
|
||||
try {
|
||||
created.push({ path, stat: fstatSync(fd, { bigint: true }), directory: false });
|
||||
writeFileSync(fd, entry.bytes);
|
||||
fchmodSync(fd, mode);
|
||||
fsyncSync(fd);
|
||||
} finally { closeSync(fd); }
|
||||
}
|
||||
} catch (error) {
|
||||
const cleanupErrors = [];
|
||||
for (const entry of created.reverse()) {
|
||||
try {
|
||||
assertRoot();
|
||||
if (realpathSync(dirname(entry.path)) !== dirname(entry.path)) throw new Error("Copilot cleanup parent identity changed");
|
||||
let current;
|
||||
try { current = lstatSync(entry.path, { bigint: true }); } catch (missing) { if (missing.code === "ENOENT") continue; throw missing; }
|
||||
if (!same(entry.stat, current) || (entry.directory ? !current.isDirectory() : !current.isFile())) throw new Error("Copilot cleanup entry identity changed");
|
||||
if (entry.directory) rmdirSync(entry.path); else unlinkSync(entry.path);
|
||||
} catch (cleanupError) { cleanupErrors.push(cleanupError); }
|
||||
}
|
||||
if (cleanupErrors.length) throw new AggregateError([error, ...cleanupErrors], "Copilot materialization failed and owned cleanup is incomplete");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function readPinnedFile(path, maxBytes, executable = false) {
|
||||
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { chmod, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import * as fs from "node:fs";
|
||||
import { syncBuiltinESMExports } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, test } from "node:test";
|
||||
import { COPILOT_DISTRIBUTIONS, materializePinnedCopilotBinary, resolveCopilotDistribution } from "./materialize-copilot-binary.mjs";
|
||||
import { COPILOT_DISTRIBUTIONS, materializePinnedCopilotBinary, resolveCopilotDistribution, writeCopilotMaterialization } from "./materialize-copilot-binary.mjs";
|
||||
const directories = [];
|
||||
afterEach(async () => { await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))); });
|
||||
async function fixture(version = "1.0.88") {
|
||||
const root = await mkdtemp(join(tmpdir(), "paperclip-copilot-materializer-")); directories.push(root);
|
||||
await writeFile(join(root, "package.json"), JSON.stringify({ name: "@github/copilot-linux-x64", version }));
|
||||
await writeFile(join(root, "copilot"), "#!/bin/sh\nexit 98\n", { mode: 0o755 });
|
||||
return root;
|
||||
return fs.realpathSync(root);
|
||||
}
|
||||
test("pins every requested platform and rejects unqualified platforms", () => {
|
||||
assert.deepEqual(Object.keys(COPILOT_DISTRIBUTIONS), ["darwin-arm64", "darwin-x64", "linux-x64"]);
|
||||
@@ -38,3 +40,82 @@ test("refuses executable symlinks, directory entries and writable binaries", asy
|
||||
await rm(binary); await mkdir(binary);
|
||||
assert.throws(() => materializePinnedCopilotBinary({ packageRoot, platform: "linux", architecture: "x64" }), /regular file/);
|
||||
});
|
||||
|
||||
const outputFiles = () => [
|
||||
{ path: "copilot", bytes: Buffer.from("verified executable"), executable: true },
|
||||
{ path: "distribution/nested/first.js", bytes: Buffer.from("verified first asset"), executable: false },
|
||||
{ path: "distribution/nested/last.js", bytes: Buffer.from("verified last asset"), executable: false },
|
||||
{ path: ".paperclip-copilot-closure.json", bytes: Buffer.from("verified closure"), executable: false },
|
||||
];
|
||||
|
||||
test("partial inner writes roll back only owned entries and permit a clean retry", async t => {
|
||||
const root = await fixture(); const output = join(root, "output"); await mkdir(output);
|
||||
await writeFile(join(output, "caller-file"), "preserve");
|
||||
const originalWrite = fs.writeFileSync; let calls = 0;
|
||||
const mocked = t.mock.method(fs.default, "writeFileSync", (fd, bytes, ...args) => {
|
||||
if (++calls === 3) { originalWrite(fd, bytes.subarray(0, 3)); throw Object.assign(new Error("injected partial write"), { code: "ENOSPC" }); }
|
||||
return originalWrite(fd, bytes, ...args);
|
||||
});
|
||||
syncBuiltinESMExports();
|
||||
try { assert.throws(() => writeCopilotMaterialization(output, outputFiles()), /injected partial write/); }
|
||||
finally { mocked.mock.restore(); syncBuiltinESMExports(); }
|
||||
assert.deepEqual(await readdir(output), ["caller-file"]);
|
||||
assert.equal(await readFile(join(output, "caller-file"), "utf8"), "preserve");
|
||||
writeCopilotMaterialization(output, outputFiles());
|
||||
for (const file of outputFiles()) assert.deepEqual(await readFile(join(output, file.path)), file.bytes);
|
||||
});
|
||||
|
||||
test("failure preserves preexisting binary, directories, assets and closure", async () => {
|
||||
for (const collision of outputFiles()) {
|
||||
const root = await fixture(); const output = join(root, "output"); await mkdir(output);
|
||||
await mkdir(join(output, "distribution/nested"), { recursive: true });
|
||||
await writeFile(join(output, collision.path), "preexisting");
|
||||
assert.throws(() => writeCopilotMaterialization(output, outputFiles()), /EEXIST/);
|
||||
assert.equal(await readFile(join(output, collision.path), "utf8"), "preexisting");
|
||||
const kept = (await readdir(join(output, "distribution/nested"))).sort();
|
||||
assert.deepEqual(kept, collision.path.startsWith("distribution/") ? [collision.path.split("/").at(-1)] : []);
|
||||
assert.equal(fs.statSync(join(output, "distribution")).isDirectory(), true);
|
||||
}
|
||||
});
|
||||
|
||||
test("rollback refuses a replaced owned entry and never removes foreign files", async t => {
|
||||
const root = await fixture(); const output = join(root, "output"); await mkdir(output);
|
||||
const originalWrite = fs.writeFileSync; let calls = 0;
|
||||
const mocked = t.mock.method(fs.default, "writeFileSync", (fd, bytes, ...args) => {
|
||||
if (++calls === 3) {
|
||||
fs.renameSync(join(output, "copilot"), join(output, "caller-retained-copy"));
|
||||
originalWrite(join(output, "copilot"), "foreign replacement", { flag: "wx" });
|
||||
throw new Error("injected replacement race");
|
||||
}
|
||||
return originalWrite(fd, bytes, ...args);
|
||||
});
|
||||
syncBuiltinESMExports();
|
||||
try { assert.throws(() => writeCopilotMaterialization(output, outputFiles()), error => error instanceof AggregateError && error.errors.some(e => /entry identity changed/.test(e.message))); }
|
||||
finally { mocked.mock.restore(); syncBuiltinESMExports(); }
|
||||
assert.equal(await readFile(join(output, "copilot"), "utf8"), "foreign replacement");
|
||||
assert.equal(await readFile(join(output, "caller-retained-copy"), "utf8"), "verified executable");
|
||||
});
|
||||
|
||||
test("owned cleanup never follows a preexisting destination symlink", async () => {
|
||||
const root = await fixture(); const output = join(root, "output"); const outside = join(root, "outside");
|
||||
await mkdir(output); await mkdir(outside); await symlink(outside, join(output, "distribution"));
|
||||
assert.throws(() => writeCopilotMaterialization(output, outputFiles()), /redirects through links/);
|
||||
assert.deepEqual(await readdir(outside), []);
|
||||
assert.deepEqual(await readdir(output), ["distribution"]);
|
||||
});
|
||||
|
||||
test("in-place failure leaves the pinned source executable untouched", async t => {
|
||||
const root = await fixture(); const before = await readFile(join(root, "copilot"));
|
||||
const originalWrite = fs.writeFileSync; let calls = 0;
|
||||
const mocked = t.mock.method(fs.default, "writeFileSync", (fd, bytes, ...args) => {
|
||||
if (++calls === 2) { originalWrite(fd, bytes.subarray(0, 2)); throw new Error("injected asset failure"); }
|
||||
return originalWrite(fd, bytes, ...args);
|
||||
});
|
||||
syncBuiltinESMExports();
|
||||
try { assert.throws(() => writeCopilotMaterialization(root, outputFiles().slice(1)), /injected asset failure/); }
|
||||
finally { mocked.mock.restore(); syncBuiltinESMExports(); }
|
||||
assert.deepEqual((await readdir(root)).sort(), ["copilot", "package.json"]);
|
||||
assert.deepEqual(await readFile(join(root, "copilot")), before);
|
||||
writeCopilotMaterialization(root, outputFiles().slice(1));
|
||||
assert.deepEqual(await readFile(join(root, "copilot")), before);
|
||||
});
|
||||
@@ -3,36 +3,52 @@ import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { COPILOT_MESSAGE_MAPPING_REPLACEMENT, COPILOT_REPLAY_MAPPING_REPLACEMENT } from "../../../scripts/copilot-inner-distribution.mjs";
|
||||
import { createAcpRuntime, createAgentRegistry, createRuntimeStore, type AcpRuntimeEvent } from "acpx/runtime";
|
||||
|
||||
// The process is a deterministic ACP transport peer, never a provider/model.
|
||||
// Exercise the installed ACPX normalization path rather than duplicating it.
|
||||
const peer = String.raw`
|
||||
const send=m=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\n');
|
||||
const live=e=>{switch(e.type){${COPILOT_MESSAGE_MAPPING_REPLACEMENT}default:return null}};
|
||||
const replay=t=>{switch(t.type){${COPILOT_REPLAY_MAPPING_REPLACEMENT}default:return live(t)}};
|
||||
const update=u=>{if(u)send({method:'session/update',params:{sessionId:'copilot-message-session',update:u}})};
|
||||
let turn=0;
|
||||
require('node:readline').createInterface({input:process.stdin}).on('line',line=>{
|
||||
const m=JSON.parse(line);
|
||||
if(m.method==='initialize')send({id:m.id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[]}});
|
||||
else if(m.method==='session/new')send({id:m.id,result:{sessionId:'copilot-message-session'}});
|
||||
else if(m.method==='session/load'){
|
||||
// Native loadSession awaits replaySessionHistory before its response. These
|
||||
// are persisted full-message events, not a second copy of active deltas.
|
||||
for(const e of [
|
||||
{type:'assistant.message',data:{messageId:'history:first',content:'SAME'}},
|
||||
{type:'assistant.message',data:{messageId:'history:second',content:'SAME'}},
|
||||
{type:'assistant.message',data:{messageId:'history:empty',content:''}},
|
||||
])update(replay(e));
|
||||
send({id:m.id,result:{}});
|
||||
}
|
||||
else if(m.method==='session/prompt'){
|
||||
turn++;
|
||||
for(const [id,text] of [[turn+':first',''],[turn+':first','SAME'],[turn+':second',''],[turn+':second','SA'],[turn+':second','ME'],[turn+':empty-final','']]){
|
||||
send({method:'session/update',params:{sessionId:'copilot-message-session',update:{sessionUpdate:'agent_message_chunk',messageId:id,content:{type:'text',text}}}});
|
||||
update(live({type:text===''?'assistant.message_start':'assistant.message_delta',data:{messageId:id,deltaContent:text}}));
|
||||
if(text==='ME')update(live({type:'assistant.message',data:{messageId:id,content:'SAME'}}));
|
||||
}
|
||||
send({id:m.id,result:{stopReason:'end_turn'}});
|
||||
}
|
||||
});`;
|
||||
|
||||
it("actual ACPX preserves empty native starts and distinct equal-text IDs across warm turns", async () => {
|
||||
it.each([false, true])("actual ACPX keeps load replay outside live warm turns (resume=%s)", async resume => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "copilot-message-acpx-"));
|
||||
const children: ReturnType<typeof spawn>[] = [];
|
||||
const wire: string[] = [];
|
||||
const runtime = createAcpRuntime({ cwd: directory, permissionMode: "deny-all",
|
||||
agentRegistry: createAgentRegistry({ overrides: { copilot: "fixture" } }), sessionStore: createRuntimeStore({ stateDir: join(directory, "state") }),
|
||||
spawnAgent: () => { const child = spawn(process.execPath, ["-e", peer], { cwd: directory, env: {}, stdio: ["pipe", "pipe", "pipe"] }); children.push(child); return child; },
|
||||
spawnAgent: () => { const child = spawn(process.execPath, ["-e", peer], { cwd: directory, env: {}, stdio: ["pipe", "pipe", "pipe"] }); child.stdout!.on("data", chunk => wire.push(chunk.toString())); children.push(child); return child; },
|
||||
});
|
||||
let handle;
|
||||
try {
|
||||
handle = await runtime.ensureSession({ sessionKey: "copilot-message-identity", agent: "copilot", mode: "persistent", cwd: directory });
|
||||
handle = await runtime.ensureSession({ sessionKey: "copilot-message-identity", agent: "copilot", mode: "persistent", cwd: directory, ...(resume ? { resumeSessionId: "copilot-message-session" } : {}) });
|
||||
for (let n = 1; n <= 3; n++) {
|
||||
const turn = runtime.startTurn({ handle, text: "fixture", mode: "prompt", requestId: `fixture-${n}`, timeoutMs: 2000 });
|
||||
const events: AcpRuntimeEvent[] = [];
|
||||
@@ -43,6 +59,11 @@ it("actual ACPX preserves empty native starts and distinct equal-text IDs across
|
||||
]);
|
||||
}
|
||||
expect(children).toHaveLength(1);
|
||||
const updates = wire.join("").split("\n").filter(Boolean).map(line => JSON.parse(line)).filter(frame => frame.method === "session/update").map(frame => frame.params.update);
|
||||
expect(updates.slice(0, resume ? 3 : 0).map(update => [update.messageId, update.content.text])).toEqual(resume ? [
|
||||
["history:first", "SAME"], ["history:second", "SAME"], ["history:empty", ""],
|
||||
] : []);
|
||||
expect(updates).toHaveLength(18 + (resume ? 3 : 0));
|
||||
} finally {
|
||||
if (handle) await runtime.close({ handle, reason: "message identity fixture complete" });
|
||||
for (const child of children) if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
||||
|
||||
@@ -75,7 +75,7 @@ export const QUALIFIED_ACPX_PROFILES: Readonly<
|
||||
acpxVersion: QUALIFIED_ACPX_VERSION, agent: "copilot", agentProfileVersion: 7,
|
||||
agentServerPackage: "@github/copilot", agentServerVersion: "1.0.88",
|
||||
agentRuntimePackage: null, agentRuntimeVersion: null,
|
||||
commandDigest: "sha256:9f98bf11135944aa8df56635d5c2e24b6a073e23a752cdf86cb9c044bfea74a5",
|
||||
commandDigest: "sha256:b11721382293b39c1d6dd363eae547b5eae0ccca2cd5dcafc9127cc060ee9526",
|
||||
// Authenticated discovery has not established a qualification model. Never
|
||||
// turn this empty declaration into a default; callers must select an ID.
|
||||
qualificationModel: "", reportedModelId: "", permissionPolicy: "interactive",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"commandDigest": "sha256:9f98bf11135944aa8df56635d5c2e24b6a073e23a752cdf86cb9c044bfea74a5",
|
||||
"commandDigest": "sha256:b11721382293b39c1d6dd363eae547b5eae0ccca2cd5dcafc9127cc060ee9526",
|
||||
"declaration": {
|
||||
"schema": "paperclip.acpx_profile_declaration.v1",
|
||||
"agent": "copilot",
|
||||
@@ -9,11 +9,11 @@
|
||||
"protocolPolicyRevision": "copilot-agent-manual-v1",
|
||||
"acpxPatchSha256": "79aad2d688b03362e8cfcbf7a08f78a8383869f6882a9c9ed66f1d18efb94f2b",
|
||||
"policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3",
|
||||
"distributionSourceSha256": "5440e6f2b1e294487ab26fc1c70f0a6200a70733f1e59fdd82f91fbeff321d7e",
|
||||
"distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107",
|
||||
"agentFilesBinding": "registered-runtime-context-v1",
|
||||
"systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1",
|
||||
"sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1",
|
||||
"innerDistributionSourceSha256": "0ecc1bbbe35f21a7a595807b49809679974fb59bc18955f85fe2e138f403e2aa",
|
||||
"innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a",
|
||||
"upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0",
|
||||
"patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679",
|
||||
"messageIdentityContract": "copilot-native-message-id-v1",
|
||||
|
||||
Reference in new issue
Block a user