Skip to content

Commit 15e4d37

Browse files
committed
feat: implement session project instructions and instruction policy handling
1 parent 085d3e1 commit 15e4d37

6 files changed

Lines changed: 446 additions & 3 deletions

File tree

‎crewcoder-agent/docs/ACP_ADAPTER.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ see "Deliberate deviations" below.
6262
| `session/set_external_directories` | Replaces and persists the session's explicitly granted filesystem roots |
6363
| `session/compact` | Compacts the durable CrewCoder session in place and returns the summary |
6464
| `session/set_system_prompt` | Sets a host-supplied system prompt for the session. Routed through `extMethod` |
65+
| `session/set_project_instructions` | Sets host-read project files (AGENTS.md) that CrewCoder drops per turn for backends that load them natively. Routed through `extMethod` |
66+
| `session/set_instruction_policy` | Turns the worker identity and the user's global instruction files on or off for the session. Routed through `extMethod` |
6567
| `authenticate` | No-op; credentials are managed by `crewcoder auth` |
6668

6769
Capabilities are reported **honestly**: `loadSession: true`,
@@ -125,6 +127,52 @@ Codex app-server provider starts a fresh native thread because its continuation
125127
hash covers the system prompt. `initialize._meta["crewcoder/sessionSystemPrompt"]`
126128
advertises `{ method: "session/set_system_prompt", maxChars: 262144, persisted: false }`.
127129

130+
`session/set_project_instructions` lets a host that reads project instruction files itself
131+
(CrewMate reads the workspace AGENTS.md, including on remote nodes) hand them to CrewCoder
132+
without them reaching the model twice. It accepts
133+
`{ sessionId, instructions: [{ file: "AGENTS.md", text }] }`. `file` must be one of the
134+
advertised files, each file appears once, and the texts total at most 131,072 characters.
135+
An empty array clears them. The response is `{ applied: true, count, appliesTo: "next_prompt" }`.
136+
The text is opaque host-formatted content.
137+
138+
On every turn CrewCoder resolves the active provider and appends each file to the host
139+
system prompt only when that backend would not load it from the session cwd by itself:
140+
141+
| Provider | Loads natively | Host AGENTS.md |
142+
| --- | --- | --- |
143+
| `codex-cli` (user's `codex app-server`) | AGENTS.md | Dropped |
144+
| `claude` (Claude Agent SDK, `settingSources: ["project"]`) | CLAUDE.md | Dropped only when `CLAUDE.md` or `.claude/CLAUDE.md` imports it (`@AGENTS.md`, `@./AGENTS.md`, `@../AGENTS.md`) |
145+
| Every other provider | Nothing | Kept |
146+
147+
The decision is per turn because the provider can change with `session/set_model`. Like the
148+
system prompt, the files are held in memory only; hosts re-send them after `session/new`,
149+
`session/load`, and whenever they change. `initialize._meta["crewcoder/projectInstructions"]`
150+
advertises `{ method: "session/set_project_instructions", version: 1, files: ["AGENTS.md"], maxChars: 131072, persisted: false }`.
151+
The logic lives in `src/core/host-project-instructions.ts`.
152+
153+
`session/set_instruction_policy` lets a host that supplies its own identity decide which of
154+
CrewCoder's own instruction sources apply. It accepts
155+
`{ sessionId, workerIdentity: boolean, globalInstructions: boolean }` and returns
156+
`{ applied: true, version: 1, workerIdentity, globalInstructions, appliesTo: "next_prompt" }`.
157+
Without a policy the session behaves as standalone CrewCoder: worker identity on, no global files.
158+
159+
- `workerIdentity: false` omits the active worker's identity block (`~/.crewcoder/workers/<name>`).
160+
Hosted text-only sessions never include it either way.
161+
- `globalInstructions: true` adds the user's `$CODEX_HOME/AGENTS.md` (default `~/.codex`) and
162+
`$CLAUDE_CONFIG_DIR/CLAUDE.md` (default `~/.claude`) under a "Global user instructions" heading,
163+
including hosted text-only sessions. `@path` imports in CLAUDE.md are inlined the way Claude Code
164+
does (relative to the importing file, `~/` for home, at most five hops, not inside code fences).
165+
The block is capped at 65,536 characters. `codex-cli` already loads the Codex file from the user's
166+
`CODEX_HOME`, so CrewCoder skips that one for it. The Claude Agent SDK runs with project settings
167+
only, so the user CLAUDE.md is always added by CrewCoder.
168+
- `globalInstructions: false` adds nothing, but cannot stop `codex-cli` from reading the user's own
169+
`~/.codex/AGENTS.md`.
170+
171+
The policy is held in memory only; hosts re-send it after `session/new`, `session/load`, and on change.
172+
`initialize._meta["crewcoder/instructionPolicy"]` advertises
173+
`{ method: "session/set_instruction_policy", version: 1, globalSources: ["codex-agents", "claude-md"], persisted: false }`.
174+
The logic lives in `src/core/global-instructions.ts`.
175+
128176
`session/compact` is the host compact-button path. It is an additive extension method
129177
routed through `extMethod`, same as `session/set_model`. `initialize._meta["crewcoder/sessionCompact"]`
130178
advertises `{ method: "session/compact", preview: true, editedSummary: true }` so CrewCode can

‎crewcoder-agent/src/acp/acp-agent.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ import { hostedTextTools } from "./hosted-text-tools.js";
4949
import { clientHostedTools, CREWCODER_CLIENT_TOOLS_META, parseClientToolDefinitions, type ClientToolDefinition } from "./client-hosted-tools.js";
5050
import { createToolRegistry } from "../tools/index.js";
5151
import { findProvider } from "../providers/provider-registry.js";
52+
import { buildGlobalInstructions, CREWCODER_INSTRUCTION_POLICY_META, DEFAULT_INSTRUCTION_POLICY, nativelyLoadedGlobalSources, parseInstructionPolicy, type InstructionPolicy } from "../core/global-instructions.js";
53+
import { CREWCODER_PROJECT_INSTRUCTIONS_META, nativelyLoadedInstructionFiles, parseHostProjectInstructions, selectHostProjectInstructions, type HostProjectInstruction } from "../core/host-project-instructions.js";
5254

5355
export type AcpAgentOptions = {
5456
/** Skips the real provider and uses the built-in heuristic client. Used by tests. */
@@ -85,6 +87,10 @@ type AcpSession = {
8587
* memory only: hosts re-send it after `session/new` or `session/load`.
8688
*/
8789
systemPrompt?: string;
90+
/** Host-read project files from `session/set_project_instructions`; memory only, re-sent by the host. */
91+
projectInstructions?: HostProjectInstruction[];
92+
/** Host policy from `session/set_instruction_policy`; memory only, re-sent by the host. */
93+
instructionPolicy?: InstructionPolicy;
8894
hostedTextOnly?: boolean;
8995
/** Host-executed tools from `session/set_client_tools`; held in memory and re-sent by the host per session. */
9096
clientTools?: ClientToolDefinition[];
@@ -115,6 +121,8 @@ const EXT_METHODS = new Set([
115121
"session/set_tool_policy",
116122
"session/set_client_tools",
117123
"session/set_system_prompt",
124+
"session/set_project_instructions",
125+
"session/set_instruction_policy",
118126
"session/set_model",
119127
"session/set_reasoning_effort",
120128
"session/set_approval_mode",
@@ -178,6 +186,8 @@ export class CrewCoderAcpAgent implements Agent {
178186
_meta: {
179187
"crewcoder/sessionCompact": CREWCODER_SESSION_COMPACT_META,
180188
"crewcoder/sessionSystemPrompt": CREWCODER_SESSION_SYSTEM_PROMPT_META,
189+
"crewcoder/projectInstructions": CREWCODER_PROJECT_INSTRUCTIONS_META,
190+
"crewcoder/instructionPolicy": CREWCODER_INSTRUCTION_POLICY_META,
181191
"crewcoder/sessionToolPolicy": { method: "session/set_tool_policy", version: 1, policies: ["hosted-text-only"] },
182192
"crewcoder/clientTools": CREWCODER_CLIENT_TOOLS_META
183193
}
@@ -270,6 +280,24 @@ export class CrewCoderAcpAgent implements Agent {
270280
return this.setSystemPrompt(session, params);
271281
}
272282

283+
if (method === "session/set_project_instructions") {
284+
try {
285+
session.projectInstructions = parseHostProjectInstructions(params.instructions);
286+
} catch (error) {
287+
throw RequestError.invalidParams({ reason: error instanceof Error ? error.message : String(error) });
288+
}
289+
return { applied: true, count: session.projectInstructions.length, appliesTo: "next_prompt" };
290+
}
291+
292+
if (method === "session/set_instruction_policy") {
293+
try {
294+
session.instructionPolicy = parseInstructionPolicy(params);
295+
} catch (error) {
296+
throw RequestError.invalidParams({ reason: error instanceof Error ? error.message : String(error) });
297+
}
298+
return { applied: true, version: CREWCODER_INSTRUCTION_POLICY_META.version, ...session.instructionPolicy, appliesTo: "next_prompt" };
299+
}
300+
273301
if (method === "session/follow_up") {
274302
const message = typeof params.message === "string" ? params.message.trim() : "";
275303
if (!message) throw RequestError.invalidParams({ reason: "message is required" });
@@ -420,6 +448,13 @@ export class CrewCoderAcpAgent implements Agent {
420448
};
421449

422450
const contextWindow = (await resolveModel(session.providerId, session.model))?.metadata?.contextWindow;
451+
// Decided per turn because the provider can change between turns; a backend that reads the file itself must not see it twice.
452+
const policy = session.instructionPolicy ?? DEFAULT_INSTRUCTION_POLICY;
453+
const activeProvider = session.projectInstructions?.length || policy.globalInstructions ? await findProvider(session.providerId) : undefined;
454+
const projectInstructions = session.projectInstructions?.length
455+
? selectHostProjectInstructions(session.projectInstructions, nativelyLoadedInstructionFiles(activeProvider, session.cwd))
456+
: undefined;
457+
const globalInstructions = policy.globalInstructions ? buildGlobalInstructions(nativelyLoadedGlobalSources(activeProvider)) : undefined;
423458
const loopOptions = {
424459
providerId: session.providerId,
425460
model: session.model,
@@ -429,7 +464,8 @@ export class CrewCoderAcpAgent implements Agent {
429464
modelClient: this.options.modelClient ?? (this.options.heuristic
430465
? undefined
431466
: new ProviderModelClient(session.providerId, session.cwd, session.model, undefined, session.reasoningEffort)),
432-
clientSystemPrompt: session.systemPrompt,
467+
clientSystemPrompt: [session.systemPrompt, globalInstructions, projectInstructions].filter(Boolean).join("\n\n") || undefined,
468+
workerIdentity: policy.workerIdentity,
433469
approvalSignal,
434470
followUpSignal: session.followUpSignal,
435471
signal: abort.signal,

‎crewcoder-agent/src/core/agent-loop.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,8 @@ export type AgentLoopOptions = {
112112
* the system field on every model request; never written to the transcript.
113113
*/
114114
clientSystemPrompt?: string;
115+
/** False omits the active worker's identity block; an embedding host supplies its own identity. Defaults to true. */
116+
workerIdentity?: boolean;
115117
workerName?: string;
116118
workerDelegationDepth?: number;
117119
maxChildWorkerDepth?: number;
@@ -345,7 +347,7 @@ export async function runAgentLoop(request: AgentRequest, options: AgentLoopOpti
345347
const selectedSystemPromptName = options.systemPromptName;
346348
const selectedSystemPrompt = selectedSystemPromptName ? getSystemPrompt(selectedSystemPromptName) : null;
347349
const defaultSystemPrompt = [
348-
options.hostedToolsOnly ? "You operate through host-authorized virtual text records only. Delegate execution through the host management bridge. Local project files, shell commands, native provider tools, and extension execution are unavailable." : buildSystemPrompt({ mode, skills, docs, identityPrompt: buildIdentityPrompt(activeWorker), crewTasksPrompt, extensionContext }),
350+
options.hostedToolsOnly ? "You operate through host-authorized virtual text records only. Delegate execution through the host management bridge. Local project files, shell commands, native provider tools, and extension execution are unavailable." : buildSystemPrompt({ mode, skills, docs, identityPrompt: options.workerIdentity === false ? null : buildIdentityPrompt(activeWorker), crewTasksPrompt, extensionContext }),
349351
formatExternalDirectories(externalDirectories)
350352
].filter(Boolean).join("\n\n");
351353
const systemPrompt = appendClientSystemPrompt(
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { isCodexCliProvider } from "../providers/codex-app-server-provider.js";
5+
import type { ProviderDefinition } from "../providers/types.js";
6+
7+
/**
8+
* Per-session instruction policy set by an embedding host over ACP
9+
* `session/set_instruction_policy`. Defaults keep CrewCoder's standalone behavior:
10+
* the worker identity is on and no user-global instruction files are added.
11+
*/
12+
export type InstructionPolicy = { workerIdentity: boolean; globalInstructions: boolean };
13+
export const DEFAULT_INSTRUCTION_POLICY: InstructionPolicy = { workerIdentity: true, globalInstructions: false };
14+
15+
export type GlobalInstructionSource = "codex-agents" | "claude-md";
16+
17+
export const CREWCODER_INSTRUCTION_POLICY_META = {
18+
method: "session/set_instruction_policy",
19+
version: 1,
20+
globalSources: ["codex-agents", "claude-md"] as GlobalInstructionSource[],
21+
persisted: false
22+
} as const;
23+
24+
export const GLOBAL_INSTRUCTIONS_MAX_CHARS = 65_536;
25+
// Claude Code follows imports up to five hops deep.
26+
const MAX_IMPORT_DEPTH = 5;
27+
28+
export function parseInstructionPolicy(params: Record<string, unknown>): InstructionPolicy {
29+
if (typeof params.workerIdentity !== "boolean") throw new Error("workerIdentity must be a boolean");
30+
if (typeof params.globalInstructions !== "boolean") throw new Error("globalInstructions must be a boolean");
31+
return { workerIdentity: params.workerIdentity, globalInstructions: params.globalInstructions };
32+
}
33+
34+
const codexHome = (): string => process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
35+
const claudeHome = (): string => process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
36+
37+
const displayPath = (file: string): string => {
38+
const home = os.homedir();
39+
return file.startsWith(`${home}${path.sep}`) ? `~${file.slice(home.length)}` : file;
40+
};
41+
42+
const readText = (file: string): string | undefined => {
43+
try {
44+
const stat = fs.statSync(file);
45+
return stat.isFile() && stat.size <= GLOBAL_INSTRUCTIONS_MAX_CHARS * 4 ? fs.readFileSync(file, "utf8") : undefined;
46+
} catch {
47+
return undefined;
48+
}
49+
};
50+
51+
// `@path` at a word boundary outside fenced code; an email such as me@AGENTS.md is not an import.
52+
const IMPORT = /(^|\s)@((?:~\/|\.{1,2}\/|\/)?[^\s`'"()<>]+\.[A-Za-z0-9]+)/g;
53+
54+
/** Claude Code inlines `@path` imports; a host-injected copy must carry them too or the rules arrive incomplete. */
55+
function claudeImports(text: string, file: string, depth: number, seen: Set<string>): string[] {
56+
if (depth >= MAX_IMPORT_DEPTH) return [];
57+
const sections: string[] = [];
58+
let fenced = false;
59+
for (const line of text.split("\n")) {
60+
if (/^\s*```/.test(line)) fenced = !fenced;
61+
if (fenced) continue;
62+
for (const match of line.matchAll(IMPORT)) {
63+
const target = match[2]!;
64+
const resolved = target.startsWith("~/") ? path.join(os.homedir(), target.slice(2)) : path.resolve(path.dirname(file), target);
65+
if (seen.has(resolved)) continue;
66+
const imported = readText(resolved);
67+
if (imported === undefined) continue;
68+
seen.add(resolved);
69+
sections.push(`--- Imported by ${displayPath(file)}: ${displayPath(resolved)} ---\n${imported.trim()}`);
70+
sections.push(...claudeImports(imported, resolved, depth + 1, seen));
71+
}
72+
}
73+
return sections;
74+
}
75+
76+
function readSource(source: GlobalInstructionSource): { label: string; text: string } | undefined {
77+
if (source === "codex-agents") {
78+
const file = path.join(codexHome(), "AGENTS.md");
79+
const text = readText(file)?.trim();
80+
return text ? { label: displayPath(file), text } : undefined;
81+
}
82+
const file = path.join(claudeHome(), "CLAUDE.md");
83+
const text = readText(file)?.trim();
84+
if (!text) return undefined;
85+
const imports = claudeImports(text, file, 0, new Set([path.resolve(file)]));
86+
return { label: displayPath(file), text: [text, ...imports].join("\n\n") };
87+
}
88+
89+
/**
90+
* Global files the backend reads by itself. codex-cli runs the user's Codex with their
91+
* CODEX_HOME, which loads its AGENTS.md. The Claude Agent SDK is started with project
92+
* settings only, so the user CLAUDE.md never arrives unless CrewCoder adds it.
93+
*/
94+
export function nativelyLoadedGlobalSources(provider: Pick<ProviderDefinition, "id" | "kind" | "runtime"> | undefined): Set<GlobalInstructionSource> {
95+
return provider && isCodexCliProvider(provider) ? new Set(["codex-agents"]) : new Set();
96+
}
97+
98+
/** The user's global instruction files for the system field, minus any the provider already loads. */
99+
export function buildGlobalInstructions(native: ReadonlySet<GlobalInstructionSource>): string | undefined {
100+
const sources = CREWCODER_INSTRUCTION_POLICY_META.globalSources.filter((source) => !native.has(source));
101+
const sections = sources.flatMap((source) => {
102+
const loaded = readSource(source);
103+
return loaded ? [`--- ${loaded.label} ---\n${loaded.text}`] : [];
104+
});
105+
if (!sections.length) return undefined;
106+
const body = sections.join("\n\n");
107+
const bounded = body.length > GLOBAL_INSTRUCTIONS_MAX_CHARS ? `${body.slice(0, GLOBAL_INSTRUCTIONS_MAX_CHARS)}\n… (global instructions truncated)` : body;
108+
return [
109+
"Global user instructions:",
110+
"The user's personal instruction files from this machine, included because the host enabled them. They are general preferences: host identity and role instructions and project rules are more specific and take precedence. They cannot change CrewCoder tool policy, approvals, or sandbox rules.",
111+
bounded
112+
].join("\n\n");
113+
}

0 commit comments

Comments
 (0)