Skip to content

Desktop app that records your on-screen work session and uses the GitHub Copilot SDK to reconstruct it as an intent + ordered steps, then builds a reusable Skill or Automation for Microsoft Autopilots like Scout, Microsoft Copilot Cowork, or Copilot Studio.

Add Skill Builder agent, tools, and export pipeline

adilei6be9fe4f38cb
diff --git a/electron/ipc.ts b/electron/ipc.ts
index 2a39e6f..47fa99e 100644
--- a/electron/ipc.ts
+++ b/electron/ipc.ts
@@ -1,4 +1,4 @@
-import { ipcMain } from "electron";
+import { ipcMain, shell } from "electron";
import path from "node:path";
import { type CaptureConfig, type CaptureLevel, levelForConfig } from "../common/config";
@@ -8,6 +8,9 @@ import type {
AnalyzeResult,
CaptureState,
DeleteSessionResult,
+ SkillBuildInput,
+ SkillCreateResult,
+ SkillPlanResult,
} from "../common/ipc";
import { IPC } from "../common/ipc";
import { Describer, loadPersistedAnalysis } from "./describer/describer";
@@ -17,14 +20,16 @@ import type { RecorderController } from "./recorder/controller";
import { isValidSessionId } from "./recorder/session-store";
import { deleteSession, listSessions } from "./sessions";
import type { SettingsStore } from "./settings";
+import { loadPersistedSkill, SkillBuilder } from "./skillbuilder/builder";
const log = createLogger("IPC");
-/** Wire the renderer-facing invoke channels to the recorder, describer, doctor + settings. */
+/** Wire the renderer-facing invoke channels to the recorder, describer, builder, doctor + settings. */
export function registerIpc(
recorder: RecorderController,
settings: SettingsStore,
describer: Describer,
+ builder: SkillBuilder,
): void {
const captureState = (): CaptureState => {
const config = settings.resolve();
@@ -130,8 +135,12 @@ export function registerIpc(
if (describer.isAnalyzing(sessionId)) {
return { ok: false, error: "This recording is being analyzed. Cancel that first, then delete." };
}
+ if (builder.isBuilding(sessionId)) {
+ return { ok: false, error: "This recording is being turned into a skill. Cancel that first, then delete." };
+ }
try {
await describer.forget(sessionId); // release any idle agent holding the folder
+ await builder.forget(sessionId);
await deleteSession(sessionId);
recorder.forgetSession(sessionId); // clear the "last completed" pointer if it was this one
return { ok: true };
@@ -141,5 +150,43 @@ export function registerIpc(
return { ok: false, error };
}
});
+
+ ipcMain.handle(IPC.buildSkill, async (_event, input: SkillBuildInput): Promise<SkillPlanResult> => {
+ if (!isValidSessionId(input?.sessionId)) return { ok: false, error: "Unknown session." };
+ try {
+ const plan = await builder.build(input);
+ return { ok: true, plan };
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ log.warn("build skill failed:", error);
+ return { ok: false, error };
+ }
+ });
+
+ ipcMain.handle(IPC.createSkill, async (_event, sessionId: string): Promise<SkillCreateResult> => {
+ if (!isValidSessionId(sessionId)) return { ok: false, error: "Unknown session." };
+ try {
+ const { skill, path: file } = await builder.create(sessionId);
+ return { ok: true, skill, path: file };
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ log.warn("create skill failed:", error);
+ return { ok: false, error };
+ }
+ });
+
+ ipcMain.handle(IPC.getSkill, (_event, sessionId: string) =>
+ isValidSessionId(sessionId) ? loadPersistedSkill(sessionId) : null,
+ );
+
+ ipcMain.handle(IPC.cancelSkill, async (_event, sessionId: string) => {
+ if (isValidSessionId(sessionId)) await builder.cancel(sessionId);
+ return { ok: true };
+ });
+
+ ipcMain.handle(IPC.revealSkill, (_event, file: string) => {
+ if (typeof file === "string" && file) shell.showItemInFolder(file);
+ return { ok: true };
+ });
}
diff --git a/electron/main.ts b/electron/main.ts
index e04181f..369d126 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -8,6 +8,7 @@ import { registerIpc } from "./ipc";
import { createLogger } from "./logger";
import { RecorderController } from "./recorder/controller";
import { SettingsStore } from "./settings";
+import { SkillBuilder } from "./skillbuilder/builder";
import { createTray } from "./tray";
import { VideoRecorder } from "./video/recorder";
import { createLibraryWindow, createRecorderWindow, redockLibrary } from "./window";
@@ -33,6 +34,7 @@ function broadcast(channel: string, payload: unknown): void {
}
const describer = new Describer((progress) => broadcast(IPC.analyzeProgress, progress));
+const builder = new SkillBuilder((progress) => broadcast(IPC.skillProgress, progress));
/** Open, focus, and re-dock the Sessions library window (creating it lazily). */
function openLibrary(): void {
@@ -54,12 +56,13 @@ function openLibrary(): void {
recorderHome = null;
// Drop idle agent conversations now that the library is gone.
void describer.evictIdle();
+ void builder.evictIdle();
});
}
app.whenReady().then(() => {
settings = new SettingsStore();
- registerIpc(recorder, settings, describer);
+ registerIpc(recorder, settings, describer, builder);
log.info("Capture level:", settings.level);
ipcMain.handle(IPC.openLibrary, () => openLibrary());
@@ -102,6 +105,7 @@ app.on("will-quit", () => {
globalShortcut.unregisterAll();
if (recorder.state === "recording") void recorder.stop();
void describer.dispose();
+ void builder.dispose();
});
diff --git a/electron/skillbuilder/builder.ts b/electron/skillbuilder/builder.ts
new file mode 100644
index 0000000..cd6cbea
--- /dev/null
+++ b/electron/skillbuilder/builder.ts
@@ -0,0 +1,332 @@
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { approveAll, CopilotClient, type CopilotSession } from "@github/copilot-sdk";
+
+import {
+ BuiltSkillSchema,
+ renderSkillMarkdown,
+ slugifySkillName,
+ toBuiltSkill,
+ type BuiltSkill,
+ type SkillArchitecture,
+ type SkillPlan,
+ type SkillSubmission,
+} from "../../common/skill";
+import type { SkillBuildInput, SkillBuildProgress } from "../../common/ipc";
+import { loadPersistedAnalysis } from "../describer/describer";
+import { createLogger } from "../logger";
+import { isValidSessionId, sessionDir } from "../recorder/session-store";
+import { SKILL_BUILDER_INSTRUCTIONS } from "./instructions";
+import { catalogueFor } from "./scout-catalog";
+import { createSkillBuilderTools } from "./tools";
+
+const log = createLogger("SkillBuilder");
+
+const TURN_TIMEOUT_MS = 180_000;
+const MAX_LIVE_SESSIONS = 4;
+
+const KICKOFF_PROMPT =
+ "Read get_analysis (and get_timeline where the tool mapping needs evidence), then call " +
+ "propose_plan with how you'll generalize this task, its inputs, and the native tools you'll use. " +
+ "Stop after propose_plan so the user can review it.";
+
+const CREATE_PROMPT =
+ "The user approved the plan. Now call submit_skill with the final SKILL.md name, description, " +
+ "allowed-tools, and a generalized, native-tool-first instructions body.";
+
+const msg = (err: unknown) => (err instanceof Error ? err.message : String(err));
+
+/** Root folder Scout auto-loads user skills from (overridable for dev/tests). */
+function skillsRoot(): string {
+ const override = process.env.SKILL_RECORDER_SKILLS_DIR;
+ if (override) return path.resolve(override);
+ return path.join(os.homedir(), ".copilot", "skills");
+}
+
+interface LiveBuild {
+ sessionId: string;
+ sessionDir: string;
+ architecture: SkillArchitecture;
+ copilot: CopilotSession;
+ holder: { plan: SkillPlan | undefined; submission: SkillSubmission | undefined };
+ /** Last plan proposed this build (kept so submit can reference it). */
+ lastPlan: SkillPlan | null;
+}
+
+function readJson<T>(file: string): T | null {
+ if (!existsSync(file)) return null;
+ try {
+ return JSON.parse(readFileSync(file, "utf8")) as T;
+ } catch {
+ return null;
+ }
+}
+
+/** Load a previously built + persisted skill for a session, if any. */
+export function loadPersistedSkill(sessionId: string): BuiltSkill | null {
+ if (!isValidSessionId(sessionId)) return null;
+ const raw = readJson<unknown>(path.join(sessionDir(sessionId), "skill.json"));
+ if (!raw) return null;
+ const parsed = BuiltSkillSchema.safeParse(raw);
+ return parsed.success ? parsed.data : null;
+}
+
+/**
+ * Drives the multi-turn GitHub Copilot CLI agent that turns an *approved* analysis
+ * into a generalized, native-tool-first skill for a target architecture. Owns one
+ * shared {@link CopilotClient}; keeps one live conversation per recording so the
+ * plan → refine → build flow stays in a single session. Streams progress out via a
+ * callback and writes the final SKILL.md into the target agent's skills folder.
+ */
+export class SkillBuilder {
+ private client: CopilotClient | null = null;
+ private clientStart: Promise<CopilotClient> | null = null;
+ private model: string | undefined;
+ private readonly live = new Map<string, LiveBuild>();
+ private readonly active = new Set<string>();
+
+ constructor(private readonly emitProgress: (p: SkillBuildProgress) => void) {}
+
+ /** Propose a plan (first pass) or refine the current one with NL feedback. */
+ async build(input: SkillBuildInput): Promise<SkillPlan> {
+ const { sessionId, architecture, feedback } = input;
+ if (this.active.has(sessionId)) throw new Error("A build is already running for this session.");
+ if (!catalogueFor(architecture)) {
+ throw new Error("That target architecture isn't available yet. Choose Scout.");
+ }
+ const analysis = loadPersistedAnalysis(sessionId);
+ if (!analysis) throw new Error("There is no analysis for this recording yet.");
+ if (!analysis.approved) throw new Error("Approve the analysis before building a skill from it.");
+
+ this.active.add(sessionId);
+ try {
+ const refining = Boolean(feedback && feedback.trim());
+ this.emit(sessionId, "start", refining ? "Refining the plan…" : "Planning the skill…");
+ let live = this.live.get(sessionId);
+ if (!refining || !live) {
+ await this.disposeLive(sessionId); // fresh conversation for a fresh plan
+ live = await this.createLive(sessionId, architecture);
+ }
+ const prompt = refining ? renderRefinePrompt(feedback!.trim(), live.lastPlan) : KICKOFF_PROMPT;
+ return await this.runProposeTurn(live, prompt);
+ } finally {
+ this.active.delete(sessionId);
+ }
+ }
+
+ /** Finalize the approved plan into a SKILL.md and export it. */
+ async create(sessionId: string): Promise<{ skill: BuiltSkill; path: string }> {
+ if (this.active.has(sessionId)) throw new Error("Wait for the current step to finish.");
+ const live = this.live.get(sessionId);
+ if (!live) throw new Error("Propose a plan first, then create the skill.");
+ if (!live.lastPlan) throw new Error("There is no proposed plan to build from yet.");
+
+ this.active.add(sessionId);
+ try {
+ this.emit(sessionId, "drafting", "Writing the skill…");
+ live.holder.submission = undefined;
+ try {
+ await live.copilot.sendAndWait(CREATE_PROMPT, TURN_TIMEOUT_MS);
+ } catch (err) {
+ await live.copilot.abort().catch(() => undefined);
+ throw new Error(`Skill build failed: ${msg(err)}`);
+ }
+ const submission = live.holder.submission;
+ if (!submission) throw new Error("The agent finished without submitting a skill.");
+ const built = toBuiltSkill(sessionId, live.architecture, submission, live.lastPlan);
+ const exportPath = this.exportSkill(built);
+ const finalSkill: BuiltSkill = { ...built, exportedPath: exportPath, exportedAt: Date.now() };
+ this.persist(live.sessionDir, finalSkill);
+ this.emit(sessionId, "done", `Skill exported to ${exportPath}`);
+ return { skill: finalSkill, path: exportPath };
+ } finally {
+ this.active.delete(sessionId);
+ }
+ }
+
+ async cancel(sessionId: string): Promise<void> {
+ const live = this.live.get(sessionId);
+ if (live) await live.copilot.abort().catch(() => undefined);
+ }
+
+ isBuilding(sessionId: string): boolean {
+ return this.active.has(sessionId);
+ }
+
+ async forget(sessionId: string): Promise<void> {
+ await this.disposeLive(sessionId);
+ }
+
+ async evictIdle(): Promise<void> {
+ for (const [id, live] of this.live) {
+ if (this.active.has(id)) continue;
+ this.live.delete(id);
+ await live.copilot.disconnect().catch(() => undefined);
+ }
+ }
+
+ async dispose(): Promise<void> {
+ for (const [id] of this.live) await this.disposeLive(id);
+ if (this.client) await this.client.stop().catch(() => undefined);
+ this.client = null;
+ this.clientStart = null;
+ }
+
+ // --- internals -----------------------------------------------------------
+
+ private emit(sessionId: string, phase: SkillBuildProgress["phase"], message: string): void {
+ this.emitProgress({ sessionId, phase, message });
+ }
+
+ private async ensureClient(): Promise<CopilotClient> {
+ if (this.client) return this.client;
+ if (this.clientStart) return this.clientStart;
+ this.clientStart = (async () => {
+ const client = new CopilotClient();
+ await client.start();
+ const auth = await client.getAuthStatus();
+ if (!auth.isAuthenticated) {
+ await client.stop().catch(() => undefined);
+ throw new Error(
+ "GitHub Copilot CLI is not signed in. Open a terminal, run `copilot`, sign in, then try again.",
+ );
+ }
+ this.model = process.env.SKILL_RECORDER_MODEL || undefined;
+ log.info("Copilot ready", auth.login ? `as ${auth.login}` : "");
+ this.client = client;
+ return client;
+ })();
+ try {
+ return await this.clientStart;
+ } catch (err) {
+ this.clientStart = null;
+ throw err;
+ }
+ }
+
+ private async createLive(sessionId: string, architecture: SkillArchitecture): Promise<LiveBuild> {
+ const dir = sessionDir(sessionId);
+ const analysis = loadPersistedAnalysis(sessionId);
+ if (!analysis) throw new Error("There is no analysis for this recording yet.");
+
+ const holder: LiveBuild["holder"] = { plan: undefined, submission: undefined };
+ const tools = createSkillBuilderTools({
+ sessionDir: dir,
+ architecture,
+ analysis,
+ onProgress: (m) => this.emit(sessionId, "working", m),
+ onPlan: (p) => {
+ holder.plan = p;
+ },
+ onSubmit: (s) => {
+ holder.submission = s;
+ },
+ });
+
+ const catalogue = catalogueFor(architecture) ?? "";
+ const systemContent = `${SKILL_BUILDER_INSTRUCTIONS}\n\n${catalogue}`.trim();
+
+ const client = await this.ensureClient();
+ const copilot = await client.createSession({
+ systemMessage: { mode: "append", content: systemContent },
+ tools,
+ onPermissionRequest: approveAll,
+ workingDirectory: dir,
+ enableHostGitOperations: false,
+ infiniteSessions: { enabled: false },
+ availableTools: tools.map((t) => t.name),
+ ...(this.model ? { model: this.model } : {}),
+ });
+
+ const live: LiveBuild = {
+ sessionId,
+ sessionDir: dir,
+ architecture,
+ copilot,
+ holder,
+ lastPlan: null,
+ };
+ this.live.set(sessionId, live);
+ this.evictOverflow(sessionId);
+ return live;
+ }
+
+ private evictOverflow(keep: string): void {
+ for (const [id, live] of this.live) {
+ if (this.live.size <= MAX_LIVE_SESSIONS) break;
+ if (id === keep || this.active.has(id)) continue;
+ this.live.delete(id);
+ void live.copilot.disconnect().catch(() => undefined);
+ }
+ }
+
+ private async disposeLive(sessionId: string): Promise<void> {
+ const live = this.live.get(sessionId);
+ if (!live) return;
+ this.live.delete(sessionId);
+ await live.copilot.disconnect().catch(() => undefined);
+ }
+
+ private async runProposeTurn(live: LiveBuild, prompt: string): Promise<SkillPlan> {
+ live.holder.plan = undefined;
+ this.emit(live.sessionId, "working", "Thinking…");
+ try {
+ await live.copilot.sendAndWait(prompt, TURN_TIMEOUT_MS);
+ } catch (err) {
+ await live.copilot.abort().catch(() => undefined);
+ throw new Error(`Planning failed: ${msg(err)}`);
+ }
+ const plan = live.holder.plan;
+ if (!plan) throw new Error("The agent finished without proposing a plan.");
+ live.lastPlan = plan;
+ this.emit(live.sessionId, "done", "Plan ready for your review.");
+ return plan;
+ }
+
+ /** Write the SKILL.md into the target agent's skills folder; returns its path. */
+ private exportSkill(skill: BuiltSkill): string {
+ const root = skillsRoot();
+ const name = slugifySkillName(skill.name);
+ const prior = loadPersistedSkill(skill.sessionId);
+ // Re-export to the same folder if this session already exported one; otherwise
+ // pick a fresh, non-colliding directory so we never clobber an unrelated skill.
+ let dir = prior?.exportedPath ? path.dirname(prior.exportedPath) : path.join(root, name);
+ if (!prior?.exportedPath && existsSync(dir)) {
+ let n = 2;
+ while (existsSync(path.join(root, `${name}-${n}`))) n++;
+ dir = path.join(root, `${name}-${n}`);
+ }
+ mkdirSync(dir, { recursive: true });
+ const file = path.join(dir, "SKILL.md");
+ writeFileSync(file, renderSkillMarkdown(skill));
+ return file;
+ }
+
+ private persist(dir: string, skill: BuiltSkill): void {
+ try {
+ writeFileSync(path.join(dir, "skill.json"), JSON.stringify(skill, null, 2));
+ } catch (err) {
+ log.warn("failed to persist skill:", msg(err));
+ }
+ }
+}
+
+function renderRefinePrompt(feedback: string, prior: SkillPlan | null): string {
+ const lines = [
+ "The user reviewed your proposed plan and wants changes. Revise the plan and call",
+ "propose_plan again (do not write the skill yet).",
+ "",
+ ];
+ if (prior) {
+ lines.push(`Current plan: ${prior.title} (${prior.name})`);
+ lines.push(`- generalization: ${prior.generalization || "(none)"}`);
+ if (prior.inputs.length) {
+ lines.push(`- inputs: ${prior.inputs.map((i) => `${i.name} [${i.source}]`).join(", ")}`);
+ }
+ lines.push("");
+ }
+ lines.push(`Their feedback: ${feedback}`);
+ return lines.join("\n");
+}
diff --git a/electron/skillbuilder/instructions.ts b/electron/skillbuilder/instructions.ts
new file mode 100644
index 0000000..1dedf43
--- /dev/null
+++ b/electron/skillbuilder/instructions.ts
@@ -0,0 +1,103 @@
+/**
+ * The Skill Builder **brief** — the agent's system message (appended to the SDK
+ * foundation, then followed by the target architecture's capability catalogue).
+ * It turns an *approved* recording analysis into a runnable, GENERALIZED skill for
+ * the chosen agent, preferring that agent's native built-in tools over UI replay.
+ *
+ * The flow is two-phase so the user stays in control:
+ * 1. **propose_plan** — infer the generalization + inputs + native-tool mapping
+ * and show it. The user may refine it in natural language (more turns).
+ * 2. **submit_skill** — only after the user approves, write the final SKILL.md.
+ */
+export const SKILL_BUILDER_INSTRUCTIONS = `
+# Role: Skill Builder
+
+You turn a recording of one task the user did into a reusable **skill** for an AI
+agent. The recording was already reconstructed into an approved **intent** and an
+ordered list of **steps** (call get_analysis to read it). Your job is to generalize
+that one run into a procedure the agent can repeat, targeting the architecture whose
+native capabilities are described in the **catalogue below**.
+
+## Two phases — never skip the plan
+
+1. **Propose a plan first.** Call **propose_plan** with how you'll generalize the
+ task, the inputs it needs, and which native tools you'll use. STOP after this —
+ the user reviews it and may reply with natural-language changes. If they do,
+ call **propose_plan** again with the revision. Only ONE proposal per turn.
+2. **Build only when told.** When the user's message says the plan is approved
+ (e.g. "approved", "create it", "looks good"), call **submit_skill** with the
+ final SKILL.md name, description, allowed-tools, and instructions body.
+
+## Generalize from the intent (the core job)
+
+- The recording is ONE example. Use the intent to separate the essential procedure
+ from the incidental specifics.
+- If the user acted on a specific set (e.g. submitted a form for **3** rows of a
+ sheet), the skill must handle **every** item (N) — it iterates over the whole
+ collection; it does NOT hardcode the 3 examples.
+- Keep what's essential ("submit one form per record"); drop what's incidental (the
+ 3 particular records, the exact window positions, timing).
+
+## Inputs — keep it simple
+
+For each thing the task needs from outside (a file, a URL, a value), pick ONE source
+and record it in the plan's \`inputs\`. Use the fewest inputs that make it runnable.
+Sources (only these):
+- **ask** — the skill asks the user for it at run time (a path, URL, or value).
+- **discover** — the agent FINDS it on the local OS with native file tools instead
+ of asking, e.g. "read the most recent *.csv in ~/Downloads". Prefer this when the
+ recording clearly points at a discoverable local file.
+- **constant** — bake in a genuinely fixed value (e.g. one specific URL the task
+ always uses).
+
+Infer the most likely source for each input yourself and show it in the plan; the
+user can override any of them in plain language.
+
+## Prefer native tools (read the catalogue below)
+
+- Map each recorded action to the target's native capability. Searching Teams becomes
+ a WorkIQ call, not simulated clicks; reading a local file becomes the file tools;
+ editing a spreadsheet becomes the built-in spreadsheet skill.
+- Only fall back to browser automation for genuine UI-only steps with no API, and to
+ the shell as a last resort (gated by \`allowed-tools\`).
+- Record your choices in the plan's \`toolMapping\`, and set \`allowedTools\` to the
+ patterns the skill actually needs.
+- Rely ONLY on the built-in tools and skills in the catalogue — never on a skill the
+ user might have added.
+
+## Write a good SKILL.md (authoring principles)
+
+You're authoring a skill another agent will load later, so write it the way a skill
+should be written, not as a transcript of this one recording:
+
+- **Description is the trigger.** The \`description\` is how the agent decides to reach
+ for this skill, so put ALL the "when to use this" cues there — what it does AND the
+ situations/phrases that should invoke it. Be specific and a little assertive so it
+ isn't under-triggered. Keep the body for HOW, not WHEN.
+- **Imperative voice, and say why.** Write instructions as commands to the agent
+ ("Read the sheet, then for each row…"). Briefly explain why a step matters instead
+ of stacking heavy-handed "MUST" rules — the agent follows reasoning better than nagging.
+- **Generalize, don't overfit.** Describe the repeatable procedure and the SHAPE of the
+ inputs, never the specific values from the recording. Cover the obvious edge cases
+ briefly (empty collection, a missing file, an item that fails).
+- **Keep it tight and skimmable.** Aim for a short body: a one-line "When to use", then
+ the ordered procedure, then input handling and edge cases. Use a short output-format
+ template or a tiny Input/Output example only where it removes ambiguity.
+- **No surprises.** The skill must do exactly what its description says — no hidden
+ side effects, destructive steps, or data exfiltration the user wouldn't expect.
+ Destructive or send/create actions should pause for the user's confirmation.
+
+## Your tools
+
+- **get_analysis** — the approved intent + ordered steps you're generalizing. Read first.
+- **get_timeline** — the deterministic timeline (apps, URLs, hosts, commands, clipboard
+ counts) behind those steps. Use it to ground the native-tool mapping in real evidence.
+- **propose_plan({ name, title, description, summary, generalization, inputs, toolMapping,
+ steps, allowedTools })** — your reviewable plan. Call once per turn, then stop.
+- **submit_skill({ name, description, allowedTools, body })** — the final skill. \`body\`
+ is the SKILL.md instructions (imperative, generalized, native-tool-first). Call this
+ only after the user approves the plan.
+
+Start by reading get_analysis (and get_timeline where the tool mapping needs evidence),
+then call propose_plan. Do not write the skill body until the plan is approved.
+`.trim();
diff --git a/electron/skillbuilder/scout-catalog.ts b/electron/skillbuilder/scout-catalog.ts
new file mode 100644
index 0000000..dfd935e
--- /dev/null
+++ b/electron/skillbuilder/scout-catalog.ts
@@ -0,0 +1,99 @@
+import type { SkillArchitecture } from "../../common/skill";
+
+/**
+ * A **static, versioned** snapshot of the target agent's native capabilities,
+ * embedded into the builder's system prompt. End users won't have the Scout repo
+ * checked out, so we catalogue Scout's BUILT-IN tools and BUILT-IN (shipped)
+ * skills here — authored by inspecting `~/projects/m` — and ship it as a constant.
+ *
+ * IMPORTANT: built-ins only. Do NOT list user-installed or repo-local skills; a
+ * generated skill can only rely on what every Scout install ships with. Refresh
+ * this when Scout's native tools/skills change.
+ */
+export const SCOUT_CATALOGUE_VERSION = "2026-07-25";
+
+const SCOUT_CATALOGUE = `
+# Target: Microsoft Scout — native capability catalogue (built-ins only)
+
+A Scout **skill** is a \`SKILL.md\` file: optional YAML frontmatter followed by a
+markdown **instructions body**. Scout auto-loads user skills from
+\`~/.copilot/skills/<name>/SKILL.md\`.
+
+Frontmatter fields:
+- \`name\` — kebab-case, \`^[a-z0-9-]+$\`.
+- \`description\` — one line of trigger keywords (when Scout should reach for this skill).
+- \`allowed-tools\` (optional) — a YAML list of tool patterns the skill may use, e.g.
+ \`Bash(git *)\`, \`Read\`, \`Write\`, \`Grep\`, \`Glob\`. Omit it to allow the default set.
+
+The body is plain instructions written TO the Scout agent (imperative voice): when
+to use the skill, the procedure to follow, and how to handle inputs and edge cases.
+
+## Native tools, in the order to PREFER them
+
+Prefer a real native tool/API over replaying UI clicks. Only fall back down this list.
+
+1. **WorkIQ (\`workiq_*\`) — Microsoft 365.** Use for anything in Teams, Outlook mail,
+ Calendar, SharePoint/OneDrive, or the org directory. Read tools are auto-approved;
+ send/create/update/delete need the user's approval at run time.
+ - Teams / chat: \`workiq_search_chats\`, \`workiq_list_chats\`, \`workiq_get_chat\`,
+ \`workiq_list_chat_messages\`, \`workiq_send_chat_message\`, \`workiq_reply_to_chat_message\`.
+ - Email: \`workiq_search_emails\`, \`workiq_list_emails\`, \`workiq_get_email\`,
+ \`workiq_send_email\`, \`workiq_create_draft\`, \`workiq_reply_to_email\`, \`workiq_forward_email\`.
+ - Calendar: \`workiq_get_schedule\`, \`workiq_list_events\`, \`workiq_get_event\`,
+ \`workiq_create_event\`, \`workiq_update_event\`, \`workiq_find_meeting_times\`, \`workiq_respond_to_event\`.
+ - Files: \`workiq_search_files\`, \`workiq_list_files\`, \`workiq_get_recent_files\`,
+ \`workiq_download_file\`, \`workiq_upload_file\`.
+ - People: \`workiq_search_people\`, \`workiq_get_my_profile\`, \`workiq_get_my_manager\`,
+ \`workiq_get_relevant_people\`.
+2. **SDK built-ins — local files, code, and the web.** \`view\` (read a file), \`glob\`
+ (find files by pattern), \`grep\` (search file contents), \`web_fetch\` (fetch a URL).
+ These are how a skill DISCOVERS inputs on the local OS instead of asking the user.
+3. **Browser automation (\`browser_*\`, Playwright).** Only when there is no API/WorkIQ
+ equivalent — a web app you must drive through its UI. Key tools: \`browser_navigate\`,
+ \`browser_snapshot\` (always snapshot before you act — it returns the element refs),
+ \`browser_click\`, \`browser_type\`, \`browser_fill_form\`, \`browser_select_option\`,
+ \`browser_press_key\`, \`browser_wait_for\`, \`browser_take_screenshot\`.
+4. **Shell (\`bash\`) — last resort.** Gate it with an \`allowed-tools\` pattern such as
+ \`Bash(git *)\` so only the needed commands are permitted.
+
+## Built-in skills you can lean on
+
+When the task matches one of Scout's shipped skills, USE it (write the body to invoke it)
+instead of reinventing the procedure. Built-in skills:
+- **pptx** — create, read, or edit PowerPoint (.pptx).
+- **docx** — create, read, or edit Word (.docx).
+- **xlsx** — create, read, or edit Excel/CSV (.xlsx, .csv).
+- **loop** — edit Microsoft Loop documents in the browser.
+- **web-artifacts-builder** — build self-contained interactive HTML apps/dashboards.
+- **expense-report** — Dynamics 365 expense workflows (internal builds only).
+- **excalidraw** — generate Excalidraw diagrams (internal builds only).
+
+Assume ONLY the tools and skills listed above exist. Do not depend on any other
+skill being installed.
+
+## Recorded action → native capability (examples)
+
+| Recording shows | Prefer |
+| --- | --- |
+| Searching / reading a Teams chat | \`workiq_search_chats\` → \`workiq_list_chat_messages\` |
+| Reading / searching Outlook mail | \`workiq_search_emails\` / \`workiq_list_emails\` / \`workiq_get_email\` |
+| Checking a calendar / free-busy | \`workiq_get_schedule\` / \`workiq_list_events\` |
+| Sending a message, email, or invite | \`workiq_send_chat_message\` / \`workiq_send_email\` / \`workiq_create_event\` (approval) |
+| Opening / reading a local file or folder | \`view\` / \`glob\` / \`grep\` |
+| Reading a public web page | \`web_fetch\` |
+| Editing a spreadsheet / doc / deck | the \`xlsx\` / \`docx\` / \`pptx\` built-in skill |
+| Filling a form on a web app with no API | \`browser_navigate\` + \`browser_snapshot\` + \`browser_fill_form\`/\`browser_type\`/\`browser_click\` |
+
+## Writing the SKILL.md body
+
+- Write a GENERALIZED procedure: if the recording acted on N specific items, the body
+ loops over ALL items of that kind, not the specific examples that were recorded.
+- Resolve each input via the plan (ask the user / discover on the local OS / constant).
+- Prefer the native tools above; only use the browser for genuine UI-only steps.
+- Keep it concise and imperative. Include a short "When to use" and the ordered steps.
+`.trim();
+
+/** The catalogue for a target architecture, or null if none is available yet. */
+export function catalogueFor(architecture: SkillArchitecture): string | null {
+ return architecture === "scout" ? SCOUT_CATALOGUE : null;
+}
diff --git a/electron/skillbuilder/tools.ts b/electron/skillbuilder/tools.ts
new file mode 100644
index 0000000..11251f7
--- /dev/null
+++ b/electron/skillbuilder/tools.ts
@@ -0,0 +1,229 @@
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+
+import type { Tool } from "@github/copilot-sdk";
+
+import type { Analysis } from "../../common/analysis";
+import type { SessionBundle } from "../../common/bundle";
+import {
+ SkillPlanSchema,
+ SkillSubmissionSchema,
+ type SkillArchitecture,
+ type SkillPlan,
+ type SkillSubmission,
+} from "../../common/skill";
+
+/** Everything the builder's tools are bound to for one session. */
+export interface SkillToolContext {
+ sessionDir: string;
+ architecture: SkillArchitecture;
+ /** The approved analysis being generalized (the builder's input). */
+ analysis: Analysis;
+ /** Streamed to the UI as the agent works. */
+ onProgress?: (message: string) => void;
+ /** Called when the agent proposes a (validated) plan for review. */
+ onPlan: (plan: SkillPlan) => void;
+ /** Called when the agent submits the final (validated) skill. */
+ onSubmit: (submission: SkillSubmission) => void;
+}
+
+function readBundle(sessionDir: string): SessionBundle | null {
+ const p = path.join(sessionDir, "bundle.json");
+ if (!existsSync(p)) return null;
+ try {
+ return JSON.parse(readFileSync(p, "utf8")) as SessionBundle;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Build the custom in-process tools exposed to one Skill Builder session. The
+ * agent reads the approved analysis (get_analysis) and its deterministic timeline
+ * (get_timeline), then proposes a reviewable plan (propose_plan) and — once the
+ * user approves — submits the final skill (submit_skill). Both submissions are
+ * zod-validated; the architecture is injected server-side so the agent can't set it.
+ */
+export function createSkillBuilderTools(ctx: SkillToolContext): Tool[] {
+ const { sessionDir, architecture, analysis, onPlan, onSubmit } = ctx;
+ const progress = (m: string) => ctx.onProgress?.(m);
+
+ const getAnalysis: Tool = {
+ name: "get_analysis",
+ description:
+ "Return the approved analysis you are generalizing: the overall intent and the ordered list of steps (with each step's title, detail, apps, and evidence). Read this first.",
+ parameters: { type: "object", properties: {}, additionalProperties: false },
+ handler: () => {
+ progress("Reading the approved analysis…");
+ const view = {
+ intent: analysis.intent,
+ intentRationale: analysis.intentRationale,
+ stepCount: analysis.steps.length,
+ steps: analysis.steps.map((s) => ({
+ id: s.id,
+ title: s.title,
+ detail: s.detail,
+ apps: s.apps,
+ evidence: s.evidence,
+ })),
+ };
+ return JSON.stringify(view, null, 2);
+ },
+ };
+
+ const getTimeline: Tool = {
+ name: "get_timeline",
+ description:
+ "Return the deterministic timeline behind the analysis: ordered steps with their app, window titles, hosts, URLs, terminal commands, clipboard counts and markers. Use it to ground your native-tool mapping in real evidence.",
+ parameters: { type: "object", properties: {}, additionalProperties: false },
+ handler: () => {
+ progress("Reading the timeline…");
+ const bundle = readBundle(sessionDir);
+ if (!bundle) {
+ return "No timeline is available (bundle.json missing). Work from get_analysis instead.";
+ }
+ const view = {
+ durationMs: bundle.session.durationMs,
+ platform: bundle.session.platform,
+ steps: bundle.steps.map((s) => ({
+ index: s.index,
+ app: s.app,
+ titles: s.titles,
+ hosts: s.hosts,
+ urls: s.urls,
+ commands: s.commands,
+ clipboardCount: s.clipboardCount,
+ markers: s.markers,
+ summary: s.summary,
+ })),
+ };
+ return JSON.stringify(view, null, 2);
+ },
+ };
+
+ const proposePlan: Tool = {
+ name: "propose_plan",
+ description:
+ "Propose your reviewable plan for the skill: how you'll generalize the task, the inputs it needs and where each comes from, the native tools you'll use, the generalized steps, and the allowed-tools. Call this once per turn, then STOP so the user can review or refine it. Do NOT write the skill body yet.",
+ parameters: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "kebab-case skill id, e.g. \"submit-expense-records\"." },
+ title: { type: "string", description: "Human-friendly title, e.g. \"Submit expense records\"." },
+ description: {
+ type: "string",
+ description: "Trigger-oriented one-liner (becomes the SKILL.md description).",
+ },
+ summary: { type: "string", description: "Plain-language summary of what the skill does." },
+ generalization: {
+ type: "string",
+ description:
+ "How the recorded specifics become a repeatable procedure (the loop/collection insight).",
+ },
+ inputs: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ name: { type: "string" },
+ description: { type: "string" },
+ source: {
+ type: "string",
+ enum: ["ask", "discover", "constant"],
+ description: "ask the user / discover on the local OS / a baked-in constant.",
+ },
+ detail: {
+ type: "string",
+ description:
+ "For discover: how to find it. For constant: the value. For ask: what to ask for.",
+ },
+ },
+ required: ["name", "source"],
+ additionalProperties: false,
+ },
+ },
+ toolMapping: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ action: { type: "string", description: "What the recording showed." },
+ tool: { type: "string", description: "The native tool/skill chosen." },
+ note: { type: "string" },
+ },
+ required: ["action", "tool"],
+ additionalProperties: false,
+ },
+ },
+ steps: {
+ type: "array",
+ items: { type: "string" },
+ description: "The generalized procedure as ordered plain-language steps.",
+ },
+ allowedTools: {
+ type: "array",
+ items: { type: "string" },
+ description: "allowed-tools frontmatter patterns, e.g. \"Bash(git *)\", \"Read\", \"Write\".",
+ },
+ },
+ required: ["name", "title", "description"],
+ additionalProperties: false,
+ },
+ handler: (raw) => {
+ const merged = { ...(raw as Record<string, unknown>), architecture };
+ const parsed = SkillPlanSchema.safeParse(merged);
+ if (!parsed.success) {
+ return {
+ textResultForLlm:
+ "propose_plan rejected — the payload did not match the schema. Fix these and call again:\n" +
+ parsed.error.issues.map((i) => `- ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n"),
+ resultType: "failure",
+ };
+ }
+ progress("Proposed a plan for your review.");
+ onPlan(parsed.data);
+ return "Plan recorded and shown to the user. Stop now and wait for their review or refinement.";
+ },
+ };
+
+ const submitSkill: Tool = {
+ name: "submit_skill",
+ description:
+ "Submit the final skill AFTER the user approves the plan: the SKILL.md name, description, allowed-tools, and the markdown instructions body. The body must be a generalized, native-tool-first procedure written imperatively to the agent.",
+ parameters: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "kebab-case skill id (matches the approved plan)." },
+ description: { type: "string", description: "SKILL.md description (trigger keywords)." },
+ allowedTools: {
+ type: "array",
+ items: { type: "string" },
+ description: "allowed-tools frontmatter patterns.",
+ },
+ body: {
+ type: "string",
+ description:
+ "The SKILL.md instructions body (markdown, everything after the frontmatter): when to use it, the generalized ordered procedure, how each input is resolved, and which native tools/skills to use.",
+ },
+ },
+ required: ["name", "description", "body"],
+ additionalProperties: false,
+ },
+ handler: (raw) => {
+ const parsed = SkillSubmissionSchema.safeParse(raw);
+ if (!parsed.success) {
+ return {
+ textResultForLlm:
+ "submit_skill rejected — the payload did not match the schema. Fix these and call again:\n" +
+ parsed.error.issues.map((i) => `- ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n"),
+ resultType: "failure",
+ };
+ }
+ progress("Received the finished skill.");
+ onSubmit(parsed.data);
+ return "Skill recorded. You may stop now.";
+ },
+ };
+
+ return [getAnalysis, getTimeline, proposePlan, submitSkill];
+}