GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): load configured instruction files from the first turn on… · different-ai/openwork@a552c26

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server
    • src
      • opencode-v2-instructions.ts
      • server.ts
    • test
      • opencode-v2-instructions.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/opencode-v2-instructions.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/opencode-v2-instructions.ts
+113Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,121 @@
1+
import { execFile } from "node:child_process";
2+
import { glob, readFile, realpath, stat } from "node:fs/promises";
3+
import { homedir } from "node:os";
4+
import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
5+
import { promisify } from "node:util";
6+
import { workspaceOpencodeConfigCandidates } from "@openwork/paths";
7+
import constants from "../../../constants.json" with { type: "json" };
8+
import { readJsoncFile } from "./jsonc.js";
19
import { appendOrganizationPrompts, OPENWORK_AGENT_PROMPT, OPENWORK_CONNECT_ROUTING_INSTRUCTION } from "./openwork-agent-prompt.js";
210

311
const CONNECT_DISCOVERY_INSTRUCTION = "Org-connected services, remote skills, Workflows, and Automations reach you through OpenWork Connect. Use the Code Mode catalog and search() to discover available tools, then call exact returned paths. When Connect exposes individual service tools, call them directly. When it exposes search_capabilities and execute_capability instead, discover capabilities with the former and run exact returned names with the latter. Read remote skills with the available get_skill tool. Discover on demand; only name services and skills returned by discovery or the remote skill catalog.";
412

513
export const OPENWORK_V2_INSTRUCTION_KEY = "openwork.context";
14+
export const OPENWORK_V2_CONFIGURED_INSTRUCTION_KEY = "openwork.configured-instructions";
15+
16+
/**
17+
* The pinned OpenCode 2.0.26 accepts the config `instructions` array but never
18+
* loads it; 2.0.30 does (anomalyco/opencode#55539). After that pin bump the
19+
* server only deletes this entry, clearing it from sessions that carried it.
20+
*/
21+
export const ENGINE_IGNORES_CONFIGURED_INSTRUCTIONS = constants.opencodeV2Version === "2.0.26";
22+
23+
// Leaves room for JSON escaping under the engine's 256 KiB entry limit.
24+
const CONFIGURED_INSTRUCTIONS_MAX_BYTES = 192 * 1024;
25+
26+
const execFileAsync = promisify(execFile);
27+
28+
// Bun's node:fs glob never matches dot paths such as `.opencode/AGENTS.md`.
29+
async function matchFiles(pattern: string, cwd: string) {
30+
const matches: string[] = [];
31+
const found = typeof process.versions.bun === "string"
32+
? new Bun.Glob(pattern).scan({ cwd, dot: true })
33+
: glob(pattern, { cwd });
34+
for await (const match of found) matches.push(match);
35+
return matches.sort();
36+
}
37+
38+
function insideRoot(root: string, path: string) {
39+
const rel = relative(root, path);
40+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
41+
}
42+
43+
// Instruction documents only, never a file the engine asks before any agent
44+
// reads (its default `*.env` and `*.env.*` read rules, `.env.example` aside).
45+
function instructionDocument(path: string) {
46+
const name = basename(path);
47+
return /\.(?:md|mdc|markdown|txt)$/i.test(name) && !/\.env(?:$|\.(?!example$))/i.test(name);
48+
}
49+
50+
/** The paths git ignores; none outside a repository or without git. Tracked files are never ignored. */
51+
async function gitIgnored(cwd: string, paths: string[]) {
52+
if (paths.length === 0) return new Set<string>();
53+
try {
54+
const run = execFileAsync("git", ["check-ignore", "-z", "--stdin"], { cwd, timeout: 5_000 });
55+
run.child.stdin?.end(paths.join("\0"));
56+
const { stdout } = await run;
57+
return new Set(stdout.split("\0").filter(Boolean));
58+
} catch (error) {
59+
// Exit 1: nothing ignored. Without a repository there are no ignore rules;
60+
// a checkout git cannot read, or any other failure, throws.
61+
const { code, stderr } = error as { code?: unknown; stderr?: unknown };
62+
if (code === 1) return new Set<string>();
63+
if (code === 128 && typeof stderr === "string" && /not a git repository/i.test(stderr)) return new Set<string>();
64+
if (code === "ENOENT" && !(await stat(join(cwd, ".git")).catch(() => null))) return new Set<string>();
65+
throw error;
66+
}
67+
}
68+
69+
/**
70+
* The workspace config's `instructions` files rendered the way OpenCode does,
71+
* or null when none load. A workspace's config may come from someone else, so
72+
* it can only send instruction documents that are part of the workspace:
73+
* Markdown or text files inside it that git does not ignore. Local files such
74+
* as `.env` or ignored notes, URLs and paths outside the workspace never load.
75+
*/
76+
export async function readConfiguredInstructions(workspaceRoot: string): Promise<string | null> {
77+
const sources = new Set<string>();
78+
for (const path of workspaceOpencodeConfigCandidates(workspaceRoot)) {
79+
const { data } = await readJsoncFile<{ instructions?: unknown }>(path, {}, { allowInvalid: true });
80+
if (!Array.isArray(data?.instructions)) continue;
81+
for (const source of data.instructions) if (typeof source === "string") sources.add(source);
82+
}
83+
if (sources.size === 0) return null;
84+
const root = await realpath(workspaceRoot);
85+
const files: { path: string; real: string; name: string }[] = [];
86+
const seen = new Set<string>();
87+
for (const source of sources) {
88+
if (/^https?:\/\//i.test(source)) continue;
89+
const expanded = source.startsWith("~/") ? join(homedir(), source.slice(2)) : source;
90+
// Bun's glob ignores absolute patterns, so every match starts from the workspace.
91+
const pattern = (isAbsolute(expanded) ? relative(workspaceRoot, expanded) : expanded).split(sep).join("/");
92+
if (pattern === ".." || pattern.startsWith("../")) continue;
93+
for (const match of await matchFiles(pattern, workspaceRoot)) {
94+
const path = resolve(workspaceRoot, match);
95+
const real = await realpath(path).catch(() => null);
96+
if (!real || seen.has(real) || !insideRoot(root, real)) continue;
97+
// A link is judged by both its own name and the file it points to.
98+
if (!instructionDocument(path) || !instructionDocument(real)) continue;
99+
seen.add(real);
100+
// Git judges the file itself: a link's own path may cross a linked folder.
101+
files.push({ path, real, name: relative(root, real) });
102+
}
103+
}
104+
const ignored = await gitIgnored(workspaceRoot, files.map((file) => file.name));
105+
const blocks: string[] = [];
106+
let bytes = 0;
107+
for (const file of files) {
108+
if (ignored.has(file.name)) continue;
109+
const content = await readFile(file.real, "utf8").catch(() => null);
110+
if (content === null) continue;
111+
const block = `Instructions from: ${file.path}\n${content}`;
112+
const size = Buffer.byteLength(block);
113+
if (bytes + size > CONFIGURED_INSTRUCTIONS_MAX_BYTES) continue;
114+
bytes += size;
115+
blocks.push(block);
116+
}
117+
return blocks.length > 0 ? blocks.join("\n\n") : null;
118+
}
6119

7120
/**
8121
* Discover remote skills on demand through Connect; native skills are workspace
Collapse file

‎apps/server/src/server.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/server.ts
+29-8Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,13 @@ import { warmEngineFolder, type EngineFolderWarmupResult } from "./engine-folder
4343
import { addPlugin, listPlugins, normalizePluginSpec, removePlugin } from "./plugins.js";
4444
import { sanitizePortableOpencodeConfig } from "./portable-opencode.js";
4545
import { addMcp, listMcp, removeMcp, setMcpEnabled } from "./mcp.js";
46-
import { buildOpenWorkV2Instructions, OPENWORK_V2_INSTRUCTION_KEY } from "./opencode-v2-instructions.js";
46+
import {
47+
buildOpenWorkV2Instructions,
48+
ENGINE_IGNORES_CONFIGURED_INSTRUCTIONS,
49+
OPENWORK_V2_CONFIGURED_INSTRUCTION_KEY,
50+
OPENWORK_V2_INSTRUCTION_KEY,
51+
readConfiguredInstructions,
52+
} from "./opencode-v2-instructions.js";
4753
import {
4854
callMcpAppTool,
4955
listMcpAppCatalog,
@@ -1501,8 +1507,8 @@ async function forwardOpencodeV2Request(input: {
15011507
target.searchParams.set("location[directory]", executionDirectory);
15021508
}
15031509

1504-
if (method !== "GET" && method !== "HEAD"
1505-
&& decodeURIComponent(forwardedPath).endsWith(`/instructions/entries/${OPENWORK_V2_INSTRUCTION_KEY}`)) {
1510+
if (method !== "GET" && method !== "HEAD" && [OPENWORK_V2_INSTRUCTION_KEY, OPENWORK_V2_CONFIGURED_INSTRUCTION_KEY]
1511+
.some((key) => decodeURIComponent(forwardedPath).endsWith(`/instructions/entries/${key}`))) {
15061512
throw new ApiError(403, "engine_instructions_managed", "OpenWork instructions are managed by the server");
15071513
}
15081514

@@ -1522,11 +1528,26 @@ async function forwardOpencodeV2Request(input: {
15221528
// The organization's Prompts arrive with the cloud provider sync.
15231529
const organizationPrompts = (await readGlobalRuntimeOpencodeConfig(input.config)).managedPrompt;
15241530
const value = buildOpenWorkV2Instructions(connectReady, organizationPrompts);
1525-
const instructionUrl = new URL(target);
1526-
instructionUrl.pathname = `/api/experimental/session/${encodeURIComponent(sessionId)}/instructions/entries/${OPENWORK_V2_INSTRUCTION_KEY}`;
1527-
const synced = await engineFetch(instructionUrl.toString(), {
1528-
method: "PUT", headers: internalHeaders, body: JSON.stringify({ value }), signal: AbortSignal.timeout(15_000),
1529-
});
1531+
// The pinned engine never loads the config's `instructions` files, so send
1532+
// them as their own entry, and clear it once the engine does. Best effort:
1533+
// a failure leaves the entry as it was and never blocks the turn.
1534+
const configured = ENGINE_IGNORES_CONFIGURED_INSTRUCTIONS
1535+
? await readConfiguredInstructions(input.workspace.path).catch(() => undefined)
1536+
: null;
1537+
const entryUrl = (key: string) => {
1538+
const url = new URL(target);
1539+
url.pathname = `/api/experimental/session/${encodeURIComponent(sessionId)}/instructions/entries/${key}`;
1540+
return url.toString();
1541+
};
1542+
const [synced] = await Promise.all([
1543+
engineFetch(entryUrl(OPENWORK_V2_INSTRUCTION_KEY), {
1544+
method: "PUT", headers: internalHeaders, body: JSON.stringify({ value }), signal: AbortSignal.timeout(15_000),
1545+
}),
1546+
configured !== undefined && engineFetch(entryUrl(OPENWORK_V2_CONFIGURED_INSTRUCTION_KEY), configured === null
1547+
? { method: "DELETE", headers: internalHeaders, signal: AbortSignal.timeout(15_000) }
1548+
: { method: "PUT", headers: internalHeaders, body: JSON.stringify({ value: configured }), signal: AbortSignal.timeout(15_000) })
1549+
.catch(() => null),
1550+
]);
15301551
if (!synced.ok) throw new ApiError(502, "engine_instruction_sync_failed", "OpenWork instructions could not be updated");
15311552
}
15321553

Collapse file

‎apps/server/test/opencode-v2-instructions.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/test/opencode-v2-instructions.test.ts
+59-1Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import assert from "node:assert/strict";
2+
import { execFileSync } from "node:child_process";
3+
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
4+
import { tmpdir } from "node:os";
5+
import { join } from "node:path";
26
import { test } from "node:test";
3-
import { buildOpenWorkV2Instructions } from "../src/opencode-v2-instructions.js";
7+
import { buildOpenWorkV2Instructions, readConfiguredInstructions } from "../src/opencode-v2-instructions.js";
48

59
test("V2 instructions support both individual Connect tools and capability search", () => {
610
const instructions = buildOpenWorkV2Instructions(true);
@@ -17,3 +21,57 @@ test("V2 instructions do not claim Connect is available when disconnected", () =
1721
assert.equal(buildOpenWorkV2Instructions(false).connect,
1822
"OpenWork Connect is not connected for this request. Do not claim remote capabilities are available.");
1923
});
24+
25+
test("configured instructions load workspace files the engine skips", async () => {
26+
const base = await mkdtemp(join(tmpdir(), "openwork-configured-instructions-"));
27+
try {
28+
const workspace = join(base, "workspace");
29+
await mkdir(join(workspace, ".opencode"), { recursive: true });
30+
await mkdir(join(workspace, "rules"));
31+
await writeFile(join(base, "outside.md"), "outside rules");
32+
await writeFile(join(workspace, ".opencode", "AGENTS.md"), "project rules");
33+
await writeFile(join(workspace, "rules", "b.md"), "rule b");
34+
await writeFile(join(workspace, "rules", "a.md"), "rule a");
35+
await symlink(join(base, "outside.md"), join(workspace, "rules", "c.md"));
36+
await writeFile(join(workspace, "opencode.jsonc"), `{
37+
// Same file twice, a glob, paths outside the workspace and a URL.
38+
"instructions": [".opencode/AGENTS.md", "rules/*.md", "../outside.md", "${join(base, "outside.md")}", "https://example.com/rules.md"],
39+
}`);
40+
await writeFile(join(workspace, ".opencode", "opencode.json"), JSON.stringify({ instructions: [".opencode/AGENTS.md"] }));
41+
42+
assert.equal(await readConfiguredInstructions(workspace), [
43+
`Instructions from: ${join(workspace, ".opencode", "AGENTS.md")}\nproject rules`,
44+
`Instructions from: ${join(workspace, "rules", "a.md")}\nrule a`,
45+
`Instructions from: ${join(workspace, "rules", "b.md")}\nrule b`,
46+
].join("\n\n"));
47+
48+
await writeFile(join(workspace, "opencode.jsonc"), "{}");
49+
await rm(join(workspace, ".opencode", "opencode.json"));
50+
assert.equal(await readConfiguredInstructions(workspace), null);
51+
} finally {
52+
await rm(base, { recursive: true, force: true });
53+
}
54+
});
55+
56+
test("configured instructions never send local or secret files", async () => {
57+
const workspace = await mkdtemp(join(tmpdir(), "openwork-configured-instructions-git-"));
58+
try {
59+
execFileSync("git", ["init", "-q"], { cwd: workspace });
60+
await mkdir(join(workspace, "rules"));
61+
await writeFile(join(workspace, ".gitignore"), "private.md\n");
62+
await writeFile(join(workspace, "CONTRIBUTING.md"), "shared rules");
63+
await writeFile(join(workspace, "private.md"), "ignored notes");
64+
await writeFile(join(workspace, ".env"), "TOKEN=secret");
65+
await writeFile(join(workspace, "deploy.env.md"), "TOKEN=secret");
66+
await writeFile(join(workspace, "credentials.json"), "{\"token\":\"secret\"}");
67+
await symlink(join(workspace, ".env"), join(workspace, "rules", "env.md"));
68+
await symlink(join(workspace, "private.md"), join(workspace, "rules", "private-link.md"));
69+
await writeFile(join(workspace, "opencode.json"), JSON.stringify({
70+
instructions: ["CONTRIBUTING.md", "private.md", ".env", "deploy.env.md", "credentials.json", "rules/*.md"],
71+
}));
72+
73+
assert.equal(await readConfiguredInstructions(workspace), `Instructions from: ${join(workspace, "CONTRIBUTING.md")}\nshared rules`);
74+
} finally {
75+
await rm(workspace, { recursive: true, force: true });
76+
}
77+
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.