Skip to content
Closed
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
8 changes: 8 additions & 0 deletions defaults/devclaw/prompts/orchestrator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Orchestrator Instructions

You are the DevClaw orchestrator.

- Use DevClaw tools to manage the workflow.
- Plan, triage, and delegate, but do not implement code changes directly.
- Prefer deterministic tool actions over ad hoc coordination.
- Keep responses concise, clear, and grounded in the current project context.
94 changes: 92 additions & 2 deletions lib/dispatch/bootstrap-hook.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@
*/
import { describe, it } from "node:test";
import assert from "node:assert";
import { parseDevClawSessionKey, loadRoleInstructions } from "./bootstrap-hook.js";
import { DEFAULT_ROLE_INSTRUCTIONS } from "../setup/templates.js";
import {
isMainOrchestratorSession,
parseDevClawSessionKey,
parseMainOrchestratorSessionScope,
loadOrchestratorInstructions,
loadRoleInstructions,
} from "./bootstrap-hook.js";
import { DEFAULT_ORCHESTRATOR_INSTRUCTIONS, DEFAULT_ROLE_INSTRUCTIONS } from "../setup/templates.js";
import fs from "node:fs/promises";
import path from "node:path";
import os from "node:os";
Expand Down Expand Up @@ -57,6 +63,52 @@ describe("parseDevClawSessionKey", () => {
});
});

describe("parseMainOrchestratorSessionScope", () => {
it("should parse a real telegram topic session scope", () => {
assert.deepStrictEqual(
parseMainOrchestratorSessionScope("agent:devclaw:telegram:group:-1003581929219:topic:190"),
{ channel: "telegram", channelId: "-1003581929219", messageThreadId: "190" },
);
});

it("should parse a chat-backed orchestrator session without a topic", () => {
assert.deepStrictEqual(
parseMainOrchestratorSessionScope("agent:devclaw:discord:channel:ops-room"),
{ channel: "discord", channelId: "ops-room" },
);
});

it("should reject legacy main and unknown session shapes", () => {
assert.strictEqual(parseMainOrchestratorSessionScope("agent:devclaw:main"), null);
assert.strictEqual(parseMainOrchestratorSessionScope("agent:devclaw:foo:bar"), null);
});
});

describe("isMainOrchestratorSession", () => {
it("should recognize the legacy main session key", () => {
assert.strictEqual(isMainOrchestratorSession("agent:devclaw:main"), true);
});

it("should recognize real telegram group orchestrator sessions", () => {
assert.strictEqual(
isMainOrchestratorSession("agent:devclaw:telegram:group:-1003581929219:topic:190"),
true,
);
});

it("should reject worker subagent sessions", () => {
assert.strictEqual(
isMainOrchestratorSession("agent:devclaw:subagent:devclaw-developer-medior-cami"),
false,
);
});

it("should reject unknown non-main session shapes", () => {
assert.strictEqual(isMainOrchestratorSession("agent:devclaw:orchestrator"), false);
assert.strictEqual(isMainOrchestratorSession("agent:devclaw:foo:bar"), false);
});
});

describe("loadRoleInstructions", () => {
it("should load project-specific instructions from devclaw/projects/<project>/prompts/", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "devclaw-test-"));
Expand Down Expand Up @@ -127,3 +179,41 @@ describe("loadRoleInstructions", () => {
await fs.rm(tmpDir, { recursive: true });
});
});

describe("loadOrchestratorInstructions", () => {
it("should prefer project-specific orchestrator prompt over workspace default", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "devclaw-test-"));
const projectDir = path.join(tmpDir, "devclaw", "projects", "test-project", "prompts");
const promptsDir = path.join(tmpDir, "devclaw", "prompts");
await fs.mkdir(projectDir, { recursive: true });
await fs.mkdir(promptsDir, { recursive: true });
await fs.writeFile(path.join(projectDir, "orchestrator.md"), "project orchestrator");
await fs.writeFile(path.join(promptsDir, "orchestrator.md"), "workspace orchestrator");

const result = await loadOrchestratorInstructions(tmpDir, "test-project");
assert.strictEqual(result, "project orchestrator");

await fs.rm(tmpDir, { recursive: true });
});

it("should fall back to workspace orchestrator prompt", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "devclaw-test-"));
const promptsDir = path.join(tmpDir, "devclaw", "prompts");
await fs.mkdir(promptsDir, { recursive: true });
await fs.writeFile(path.join(promptsDir, "orchestrator.md"), "workspace orchestrator");

const result = await loadOrchestratorInstructions(tmpDir, "missing-project");
assert.strictEqual(result, "workspace orchestrator");

await fs.rm(tmpDir, { recursive: true });
});

it("should fall back to package default orchestrator prompt when present", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "devclaw-test-"));

const result = await loadOrchestratorInstructions(tmpDir, "missing-project");
assert.strictEqual(result, DEFAULT_ORCHESTRATOR_INSTRUCTIONS ?? "");

await fs.rm(tmpDir, { recursive: true });
});
});
208 changes: 183 additions & 25 deletions lib/dispatch/bootstrap-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import fs from "node:fs/promises";
import path from "node:path";
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import type { PluginContext } from "../context.js";
import { getProject, readProjects } from "../projects/index.js";
import { getSessionKeyRolePattern } from "../roles/index.js";
import { DATA_DIR } from "../setup/migrate-layout.js";
import { DEFAULT_ROLE_INSTRUCTIONS } from "../setup/templates.js";
import { DEFAULT_ORCHESTRATOR_INSTRUCTIONS, DEFAULT_ROLE_INSTRUCTIONS } from "../setup/templates.js";

/**
* Parse a DevClaw subagent session key to extract project name and role.
Expand Down Expand Up @@ -50,7 +51,7 @@ export function parseDevClawSessionKey(
/**
* Result of loading role instructions — includes the source for traceability.
*/
export type RoleInstructionsResult = {
export type PromptInstructionsResult = {
content: string;
/** Which file the instructions were loaded from, or null if none found. */
source: string | null;
Expand Down Expand Up @@ -78,13 +79,13 @@ export async function loadRoleInstructions(
projectName: string,
role: string,
opts: { withSource: true },
): Promise<RoleInstructionsResult>;
): Promise<PromptInstructionsResult>;
export async function loadRoleInstructions(
workspaceDir: string,
projectName: string,
role: string,
opts?: { withSource: true },
): Promise<string | RoleInstructionsResult> {
): Promise<string | PromptInstructionsResult> {
const dataDir = path.join(workspaceDir, DATA_DIR);

const candidates = [
Expand Down Expand Up @@ -115,6 +116,118 @@ export async function loadRoleInstructions(
return "";
}

export async function loadOrchestratorInstructions(
workspaceDir: string,
projectName?: string,
): Promise<string>;
export async function loadOrchestratorInstructions(
workspaceDir: string,
projectName: string | undefined,
opts: { withSource: true },
): Promise<PromptInstructionsResult>;
export async function loadOrchestratorInstructions(
workspaceDir: string,
projectName?: string,
opts?: { withSource: true },
): Promise<string | PromptInstructionsResult> {
const dataDir = path.join(workspaceDir, DATA_DIR);
const candidates = [
...(projectName
? [path.join(dataDir, "projects", projectName, "prompts", "orchestrator.md")]
: []),
path.join(dataDir, "prompts", "orchestrator.md"),
];

for (const filePath of candidates) {
try {
const content = await fs.readFile(filePath, "utf-8");
if (opts?.withSource) return { content, source: filePath };
return content;
} catch {
/* not found, try next */
}
}

if (DEFAULT_ORCHESTRATOR_INSTRUCTIONS) {
if (opts?.withSource) {
return { content: DEFAULT_ORCHESTRATOR_INSTRUCTIONS, source: "package-default" };
}
return DEFAULT_ORCHESTRATOR_INSTRUCTIONS;
}

if (opts?.withSource) return { content: "", source: null };
return "";
}

const MAIN_SESSION_PATTERNS = [
/^agent:[^:]+:main$/,
/^agent:[^:]+:(telegram|whatsapp|discord|slack):(group|dm|channel):[^:]+(?::topic:[^:]+)?$/,
];

export function isMainOrchestratorSession(sessionKey: string): boolean {
return MAIN_SESSION_PATTERNS.some((pattern) => pattern.test(sessionKey));
}

export type OrchestratorSessionScope = {
channel: string;
channelId: string;
messageThreadId?: string;
};

export function parseMainOrchestratorSessionScope(
sessionKey: string,
): OrchestratorSessionScope | null {
const match = sessionKey.match(
/^agent:[^:]+:(telegram|whatsapp|discord|slack):(group|dm|channel):([^:]+)(?::topic:([^:]+))?$/,
);
if (!match) return null;
return {
channel: match[1],
channelId: match[3],
...(match[4] ? { messageThreadId: match[4] } : {}),
};
}

async function resolveProjectNameForBootstrap(
workspaceDir: string,
context: Record<string, unknown>,
sessionKey?: string,
): Promise<string | undefined> {
const sessionScope = sessionKey ? parseMainOrchestratorSessionScope(sessionKey) : null;
const channelId =
(typeof context.channelId === "string" && context.channelId.trim() ? context.channelId : undefined) ??
(typeof context.conversationId === "string" && context.conversationId.trim()
? context.conversationId
: undefined) ??
(typeof context.peerId === "string" && context.peerId.trim() ? context.peerId : undefined) ??
sessionScope?.channelId;

if (!channelId) return undefined;

const messageThreadId =
typeof context.messageThreadId === "number" || typeof context.messageThreadId === "string"
? context.messageThreadId
: typeof context.threadId === "number" || typeof context.threadId === "string"
? context.threadId
: sessionScope?.messageThreadId;

try {
const data = await readProjects(workspaceDir);
const project = getProject(data, {
channelId,
channel:
typeof context.channel === "string" && context.channel.trim()
? context.channel
: sessionScope?.channel ?? "telegram",
accountId: typeof context.accountId === "string" ? context.accountId : undefined,
messageThreadId,
});
return project?.name;
} catch {
return undefined;
}
}

/**
* Register the agent:bootstrap hook for DevClaw worker sessions.
*
Expand All @@ -136,10 +249,18 @@ export function registerBootstrapHook(api: OpenClawPluginApi, ctx: PluginContext
if (!sessionKey) return;

const parsed = parseDevClawSessionKey(sessionKey);
if (!parsed) return;
const isOrchestrator = isMainOrchestratorSession(sessionKey);
if (!parsed && !isOrchestrator) return;

const context = event.context as {
workspaceDir?: string;
channelId?: string;
conversationId?: string;
peerId?: string;
channel?: string;
accountId?: string;
threadId?: number | string;
messageThreadId?: number | string;
bootstrapFiles?: Array<{
name: string;
path: string;
Expand All @@ -154,37 +275,74 @@ export function registerBootstrapHook(api: OpenClawPluginApi, ctx: PluginContext
const agentsEntry = bootstrapFiles.find((f) => f.name === "AGENTS.md");
if (!agentsEntry) return;

// Load role instructions from workspace (project-specific → default fallback)
const workspaceDir = context.workspaceDir;
if (!workspaceDir) {
agentsEntry.content = "";
agentsEntry.missing = true;
ctx.logger.info(
`agent:bootstrap: stripped AGENTS.md for ${parsed.role} worker in "${parsed.projectName}" (no workspaceDir)`,
if (parsed) {
agentsEntry.content = "";
agentsEntry.missing = true;
ctx.logger.info(
`agent:bootstrap: stripped AGENTS.md for ${parsed.role} worker in "${parsed.projectName}" (no workspaceDir)`,
);
}
return;
}

if (parsed) {
const { content, source } = await loadRoleInstructions(
workspaceDir,
parsed.projectName,
parsed.role,
{ withSource: true },
);

if (content.trim()) {
agentsEntry.content = content;
agentsEntry.missing = false;
ctx.logger.info(
`agent:bootstrap: injected ${parsed.role} instructions for "${parsed.projectName}" from ${source}`,
);
} else {
agentsEntry.content = "";
agentsEntry.missing = true;
ctx.logger.info(
`agent:bootstrap: stripped AGENTS.md for ${parsed.role} worker in "${parsed.projectName}" (no role instructions found)`,
);
}
return;
}

const { content, source } = await loadRoleInstructions(
const projectName = await resolveProjectNameForBootstrap(
workspaceDir,
parsed.projectName,
parsed.role,
{ withSource: true },
context as Record<string, unknown>,
sessionKey,
);
const { content, source } = await loadOrchestratorInstructions(workspaceDir, projectName, {
withSource: true,
});
if (!content.trim()) return;

if (content.trim()) {
agentsEntry.content = content;
agentsEntry.missing = false;
ctx.logger.info(
`agent:bootstrap: injected ${parsed.role} instructions for "${parsed.projectName}" from ${source}`,
);
const existing = bootstrapFiles.find((f) => f.name === "orchestrator.md");
if (existing) {
existing.content = content;
existing.missing = false;
} else {
agentsEntry.content = "";
agentsEntry.missing = true;
ctx.logger.info(
`agent:bootstrap: stripped AGENTS.md for ${parsed.role} worker in "${parsed.projectName}" (no role instructions found)`,
);
bootstrapFiles.push({
name: "orchestrator.md",
path: path.join(workspaceDir, "orchestrator.md"),
content,
missing: false,
});
}

const synthetic = bootstrapFiles.find((f) => f.name === "DEVCLAW_ORCHESTRATOR_PROMPT.md");
if (synthetic) {
synthetic.content = "";
synthetic.missing = true;
}

ctx.logger.info(
`agent:bootstrap: injected orchestrator instructions${projectName ? ` for "${projectName}"` : ""} from ${source}`,
);
},
{
name: "devclaw-bootstrap-role-instructions",
Expand Down
Loading