Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions src/adapters/core/broker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,14 @@ const RETRY_DELAYS = [20, 50, 100, 200, 400];
const sleepCell = new Int32Array(new SharedArrayBuffer(4));

/**
* Writes JSON so that a reader never sees half of it: a temporary file, then a rename. On Windows a reader (the
* agent manager) may hold the file for a moment, so EPERM / EACCES / EBUSY are tried again a few times.
* Writes text so that a reader never sees half of it: a temporary file, then a rename. On Windows a reader (the
* agent manager, an MCP client) may hold the file for a moment, so EPERM / EACCES / EBUSY are tried again a few times.
*/
export function atomicJSON(file, data) {
export function atomicWrite(file, text, { mode = 0o600 } = {}) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temp = `${file}.${process.pid}.${crypto.randomBytes(3).toString("hex")}.tmp`;
for (const op of [
() => fs.writeFileSync(temp, JSON.stringify(data, null, 2), { mode: 0o600, flush: true }),
() => fs.writeFileSync(temp, text, { mode, flush: true }),
() => fs.renameSync(temp, file),
]) {
for (let attempt = 0; ; attempt++) {
Expand All @@ -144,6 +144,11 @@ export function atomicJSON(file, data) {
}
}

/** JSON written through `atomicWrite` (a status file: private, durable and never half-written). */
export function atomicJSON(file, data) {
atomicWrite(file, JSON.stringify(data, null, 2));
}

/** The adapter's state for the agent manager: `<runtime>/status.json` (runtime is the agent's `.aichat` folder). */
export function writeStatus(runtime, status) {
atomicJSON(path.join(runtime, "status.json"), status);
Expand Down
29 changes: 28 additions & 1 deletion src/adapters/opencode-channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import path from "node:path";
import { BrokerHttp, BrokerSocket, newerVersion } from "./core/broker.mjs";
import { BrokerHttp, BrokerSocket, atomicWrite, newerVersion } from "./core/broker.mjs";
import { readUpload, saveDownload } from "./core/files.mjs";
import { composeInstructions, fetchInstructions } from "./core/instructions.mjs";

const DEFAULTS = {
url: "ws://aichat.home/ws",
Expand All @@ -48,6 +49,10 @@ const DEFAULTS = {
};

const PLUGIN_NAME = "opencode-channel";

/** What is true of this runtime only: where the tools come from and how a message reaches the model. */
const OPENCODE_RUNTIME = `Your AIChat tools are the broker's MCP server in the \`aichat\` namespace; their schemas describe them. Local files are in the \`aichat_files\` namespace: upload_file (only from outbox or the attachments folder) and get_attachment.
Incoming messages arrive as turns of this session; what you write at the end of a turn stays here, so the reply goes through send_message. This session can start anew: the notebook and the history keep what matters.`;
const PLUGIN_VERSION = typeof __AICHAT_VERSION__ === "string" ? __AICHAT_VERSION__ : "0.0.0-dev";
const SESSION_KEY = "aichat/session";
const PREVIOUS_KEY = "aichat/previousSessionIds";
Expand Down Expand Up @@ -116,6 +121,8 @@ function writeStatus(ctx, cfg, state) {
sessionID: state.sessionID || null,
// what the session really runs on, so the manager can show it next to what was configured
...(model ? { model } : {}),
// where each part of the model's instructions came from, for the manager (AIChat 4102)
...(Array.isArray(state.instructionParts) && state.instructionParts.length ? { instructions: state.instructionParts } : {}),
paused: cfg.paused === true,
connected: state.connected === true,
effective: {
Expand Down Expand Up @@ -952,6 +959,26 @@ export default {
return;
}

// The rules come from the broker; OpenCode reads ambient instructions from a file listed in opencode.jsonc, so
// the composed text goes there instead of into synthetic turns (AIChat 4094-4097).
try {
const fetched = await fetchInstructions({ httpBase: cfg.httpBase, token: cfg.token });
// an older broker (no /api/instructions) must not overwrite a file it did not write: keep the previous text
if (fetched) {
const { text, parts } = composeInstructions({
fetched,
runtime: OPENCODE_RUNTIME,
local: String(cfg.instructions ?? ""),
});
state.instructionParts = parts;
const file = path.join(runtimeDir, "instructions.md");
const next = `${text.trim()}\n`;
if (next.trim() && readTextSafe(file) !== next.trim()) atomicWrite(file, next);
}
} catch (error) {
console.warn(`[aichat] не вдалось записати .aichat/instructions.md: ${error.message}`);
}

// The server tools live on the broker's /mcp now: an older broker would leave the agent with the two local
// file utilities only, so say it plainly instead of letting the agent guess (AIChat 3862).
await apiRequest(cfg, "/api/tools")
Expand Down
33 changes: 33 additions & 0 deletions src/test/opencode-channel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ test("the plugin's own tools are only upload_file and get_attachment: the server
if (url.endsWith("/api/files") && (init.method ?? "GET") === "POST") {
return new Response(JSON.stringify({ file: { id: "f1" } }), { status: 200, headers: { "content-type": "application/json" } });
}
if (url.includes("/api/instructions")) {
return new Response(JSON.stringify({ rules: { text: "BROKER RULES", by: "admin", ts: "t" }, self: { name: "test-oc" } }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (url.includes("/api/files/f1")) {
return new Response(new TextEncoder().encode("image-bytes"), {
status: 200,
Expand Down Expand Up @@ -175,6 +181,12 @@ test("the plugin's own tools are only upload_file and get_attachment: the server
["get_attachment", "upload_file"],
"no server tools are defined in the adapter any more",
);
// the broker's rules reach OpenCode as an ambient instructions file, with this runtime's block after them
const rules = readFileSync(join(dir, ".aichat", "instructions.md"), "utf8");
assert.match(rules, /BROKER RULES/);
assert.match(rules, /You are test-oc on AIChat\./);
assert.match(rules, /aichat_files/);

const byName = new Map(tools.map((t) => [t.name, t]));

const up = await byName.get("upload_file")!.execute({ path: join(outbox, "note.txt") }, {});
Expand Down Expand Up @@ -202,6 +214,27 @@ test("the plugin's own tools are only upload_file and get_attachment: the server
}
});

test("an older broker's 404 does not overwrite the instructions file", async () => {
const dir = mkdtempSync(join(tmpdir(), "aichat-opencode-"));
const realFetch = globalThis.fetch;
try {
const plugin = await buildBundle(dir);
globalThis.fetch = (async () =>
new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "content-type": "application/json" } })) as typeof fetch;
const { ctx } = makeCtx(dir, {});
const dispose = await plugin.setup(ctx);
try {
// with no /api/instructions the adapter keeps whatever text was there before, here none
assert.equal(existsSync(join(dir, ".aichat", "instructions.md")), false);
} finally {
await dispose();
}
} finally {
globalThis.fetch = realFetch;
rmSync(dir, { recursive: true, force: true });
}
});

test("the OpenCode plugin starts a new session on .aichat/fresh and resumes it otherwise", async () => {
// A fresh start: the marker forces a new session, the old id is kept in previousSessionIds, and the marker
// is spent only after the new session exists.
Expand Down