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.

Replace inputs with inline value pills; deterministic export (#51)

adilei3343b56d6b35
diff --git a/common/automation.ts b/common/automation.ts
index 2e63032..d00b8bb 100644
--- a/common/automation.ts
+++ b/common/automation.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
-import { SkillArchitecture, SkillInputSchema, slugifySkillName } from "./skill";
+import { SkillArchitecture, slugifySkillName } from "./skill";
+import { migrateLegacyInputsToValues, renderValues, ValueSchema } from "./values";
/**
* The Automation Builder's contract — the automation-flavoured sibling of
@@ -94,7 +95,9 @@ export type AutomationStepDraft = z.infer<typeof AutomationStepDraftSchema>;
* The agent's proposed plan, shown to the user before any automation is written.
* This is what `propose_automation_plan` submits and what the user refines in NL.
*/
-export const AutomationPlanSchema = z.object({
+export const AutomationPlanSchema = z.preprocess(
+ migrateLegacyInputsToValues,
+ z.object({
/** Target architecture this plan is written for. */
architecture: SkillArchitecture,
/** kebab-case automation id, e.g. "daily-lead-digest". */
@@ -109,16 +112,17 @@ export const AutomationPlanSchema = z.object({
generalization: z.string().default(""),
/** The proposed trigger (schedule + optional condition). */
trigger: AutomationTriggerSchema,
- /** Inputs the automation needs and where each comes from (informational; the
- * automation resolves them inside its step prompts). */
- inputs: z.array(SkillInputSchema).default([]),
+ /** Named fixed literals (URLs / paths / constants) the step prompts reference by
+ * `{{id}}`; substituted deterministically at export. */
+ values: z.array(ValueSchema).default([]),
/** The generalized procedure, as ordered label + prompt steps. */
steps: z.array(AutomationStepDraftSchema).default([]),
/** Optional per-automation model override. */
model: z.string().default(""),
/** Built-in Scout skills the steps rely on (for the user's awareness). */
skillNames: z.array(z.string()).default([]),
-});
+ }),
+);
export type AutomationPlan = z.infer<typeof AutomationPlanSchema>;
/**
@@ -136,6 +140,8 @@ export const AutomationSubmissionSchema = z.object({
condition: z.string().default(""),
conditionCheckInterval: z.number().int().positive().optional(),
model: z.string().default(""),
+ /** Fixed values substituted into the step prompts at export (the pill literals). */
+ values: z.array(ValueSchema).default([]),
/** The generalized, ordered steps (each an NL prompt). */
steps: z.array(AutomationStepDraftSchema).min(1),
});
@@ -155,6 +161,8 @@ export const BuiltAutomationSchema = z.object({
conditionCheckInterval: z.number().int().positive().optional(),
model: z.string().default(""),
steps: z.array(AutomationStepDraftSchema),
+ /** Fixed values substituted into the step prompts at export (the pill literals). */
+ values: z.array(ValueSchema).default([]),
/** The plan the automation was built from (for the UI / re-export). */
plan: AutomationPlanSchema.nullable().default(null),
createdAt: z.number(),
@@ -184,6 +192,7 @@ export function toBuiltAutomation(
conditionCheckInterval: submission.conditionCheckInterval,
model: submission.model,
steps: submission.steps,
+ values: submission.values,
plan,
createdAt: Date.now(),
});
@@ -201,6 +210,7 @@ export function planToAutomationSubmission(plan: AutomationPlan): AutomationSubm
condition: plan.trigger.condition,
conditionCheckInterval: plan.trigger.conditionCheckInterval,
model: plan.model,
+ values: plan.values,
steps: plan.steps,
});
}
@@ -249,7 +259,10 @@ export function toAutomationImport(a: BuiltAutomation): Record<string, unknown>
description: a.description,
triggerType: a.triggerType,
schedule: scheduleToScout(a.schedule),
- steps: a.steps.map((s) => ({ label: s.label, prompt: s.prompt })),
+ steps: a.steps.map((s) => ({
+ label: renderValues(s.label, a.values),
+ prompt: renderValues(s.prompt, a.values),
+ })),
};
if (a.triggerType === "condition" && a.condition) obj.condition = a.condition;
if (a.conditionCheckInterval) obj.conditionCheckInterval = a.conditionCheckInterval;
diff --git a/common/ipc.ts b/common/ipc.ts
index bc0eb6c..67c7ec6 100644
--- a/common/ipc.ts
+++ b/common/ipc.ts
@@ -427,7 +427,7 @@ export interface SkillRecorderApi {
buildSkill(input: SkillBuildInput): Promise<SkillPlanResult>;
/**
* Finalize the (user-edited) skill plan and place its SKILL.md. The edited plan the
- * user sees is authoritative — the body is written from exactly these inputs and steps.
+ * user sees is authoritative — the body is written from exactly these values and steps.
* `placement` picks the destination: `"install"` writes into the target agent's live
* skills folder (Scout); `"export"` prompts for a folder and downloads it there (the
* only option for Cowork). Defaults to `"install"`.
diff --git a/common/skill.ts b/common/skill.ts
index 6871624..4697372 100644
--- a/common/skill.ts
+++ b/common/skill.ts
@@ -1,9 +1,11 @@
import { z } from "zod";
+import { migrateLegacyInputsToValues, renderValues, ValueSchema } from "./values";
+
/**
* The Skill Builder's contract. From an *approved* {@link Analysis} the multi-turn
* Copilot agent first proposes a **plan** ({@link SkillPlan}) — how it will
- * generalize the recorded task, what inputs it needs, and which of the target
+ * generalize the recorded task, what fixed values it needs, and which of the target
* architecture's native tools it will use — which the user refines in natural
* language. On confirmation the agent submits the final **built skill**
* ({@link BuiltSkill}), which is rendered to a `SKILL.md` and exported into the
@@ -89,45 +91,6 @@ export const TARGETS: readonly BuildTarget[] = [
},
] as const;
-/**
- * Where a skill's input comes from at run time — a small spectrum of "known now /
- * known at run time / found by the agent":
- * - **fixed** — a genuinely constant value baked into the skill: a canonical URL or
- * a specific file path that is the SAME on every run.
- * - **provided** — the skill asks the user for it when it runs (a path, URL, value).
- * - **locate** — the agent finds it on the device with native file tools (e.g. "the
- * most recent *.csv in ~/Downloads") because it varies run-to-run.
- */
-export const SkillInputSource = z.enum(["fixed", "provided", "locate"]);
-export type SkillInputSource = z.infer<typeof SkillInputSource>;
-
-/** Source values from earlier builds (`ask/discover/constant`), mapped to current names. */
-const LEGACY_INPUT_SOURCE: Record<string, SkillInputSource> = {
- ask: "provided",
- discover: "locate",
- constant: "fixed",
-};
-
-/** Accepts both current and legacy source strings, so older persisted plans/skills load. */
-export const SkillInputSourceCompat = z.preprocess(
- (v) => (typeof v === "string" && v in LEGACY_INPUT_SOURCE ? LEGACY_INPUT_SOURCE[v] : v),
- SkillInputSource,
-);
-
-export const SkillInputSchema = z.object({
- /** Short name for the input, e.g. "records spreadsheet". */
- name: z.string(),
- /** What it is and how it's used in the task. */
- description: z.string().default(""),
- source: SkillInputSourceCompat,
- /**
- * Source-specific detail: the fixed value or path (for `fixed`), what to ask the
- * user for (for `provided`), or how to find it on the device (for `locate`).
- */
- detail: z.string().default(""),
-});
-export type SkillInput = z.infer<typeof SkillInputSchema>;
-
/**
* A generalized step is either a **calculation** (reads, derives, decides, or formats
* — no external side effect) or an **action** (changes the world: submit, send, create,
@@ -156,7 +119,9 @@ export type PlanStep = z.infer<typeof PlanStepSchema>;
* The agent's proposed plan, shown to the user before any skill is written.
* This is what `propose_plan` submits and what the user refines in NL.
*/
-export const SkillPlanSchema = z.object({
+export const SkillPlanSchema = z.preprocess(
+ migrateLegacyInputsToValues,
+ z.object({
/** Target architecture this plan is written for. */
architecture: SkillArchitecture,
/** kebab-case skill id, e.g. "submit-expense-records". */
@@ -169,12 +134,14 @@ export const SkillPlanSchema = z.object({
summary: z.string().default(""),
/** How the recorded specifics are generalized (the loop/collection insight). */
generalization: z.string().default(""),
- inputs: z.array(SkillInputSchema).default([]),
+ /** Named fixed literals (URLs / paths / constants) the steps reference by `{{id}}`. */
+ values: z.array(ValueSchema).default([]),
/** The generalized procedure as ordered, typed steps (calculations + actions). */
steps: z.array(PlanStepSchema).default([]),
/** Proposed `allowed-tools` frontmatter patterns, e.g. "Bash(git *)". */
allowedTools: z.array(z.string()).default([]),
-});
+ }),
+);
export type SkillPlan = z.infer<typeof SkillPlanSchema>;
/**
@@ -203,6 +170,8 @@ export const BuiltSkillSchema = z.object({
allowedTools: z.array(z.string()).default([]),
/** The markdown instructions body. */
body: z.string(),
+ /** Fixed values substituted into the body at render time (the pill literals). */
+ values: z.array(ValueSchema).default([]),
/** The plan the skill was built from (for the UI / re-export). */
plan: SkillPlanSchema.nullable().default(null),
createdAt: z.number(),
@@ -238,6 +207,7 @@ export function toBuiltSkill(
description: submission.description,
allowedTools: submission.allowedTools,
body: submission.body,
+ values: plan?.values ?? [],
plan,
createdAt: Date.now(),
});
@@ -246,8 +216,9 @@ export function toBuiltSkill(
/**
* Render a {@link BuiltSkill} to the exact `SKILL.md` text Scout parses:
* YAML frontmatter (`name`, `description`, optional `allowed-tools`) followed by
- * the instructions body. The description is emitted as a double-quoted scalar so
- * colons/commas in it never break the YAML.
+ * the instructions body, with each `{{id}}` value token substituted for its literal.
+ * The description is emitted as a double-quoted scalar so colons/commas in it never
+ * break the YAML.
*/
export function renderSkillMarkdown(skill: BuiltSkill): string {
const lines: string[] = ["---", `name: ${slugifySkillName(skill.name)}`];
@@ -259,6 +230,6 @@ export function renderSkillMarkdown(skill: BuiltSkill): string {
for (const t of tools) lines.push(` - ${t}`);
}
lines.push("---", "");
- lines.push(skill.body.trim(), "");
+ lines.push(renderValues(skill.body, skill.values).trim(), "");
return lines.join("\n");
}
diff --git a/common/values.ts b/common/values.ts
new file mode 100644
index 0000000..b4c6bc8
--- /dev/null
+++ b/common/values.ts
@@ -0,0 +1,105 @@
+import { z } from "zod";
+
+/**
+ * A **value** is a named fixed literal (a URL, path, repo slug, or constant) that a
+ * plan's steps reference by a `{{id}}` token. It replaces the old free-standing
+ * "inputs" construct: the literal lives *inside* the step template and is substituted
+ * deterministically at the final render boundary (`SKILL.md` / `automation.json`), so
+ * what the user edits in the review UI is exactly what ships — no second agent turn
+ * needed to honor an edit. In the review UI each token renders as an inline, editable
+ * "pill" whose label is the value's `name` and whose text is the value's `value`.
+ */
+export const ValueSchema = z.object({
+ /** Token key referenced in step/body text as `{{id}}`; normalized to `[a-z0-9_]`. */
+ id: z.string().transform(slugifyValueId),
+ /** Human label shown on the editable pill, e.g. "Blog Backlog v2 URL". */
+ name: z.string().default(""),
+ /** The fixed literal substituted in for the token (the URL / path / constant). */
+ value: z.string().default(""),
+});
+export type Value = z.infer<typeof ValueSchema>;
+
+/** Normalize arbitrary text into a safe token id (`[a-z0-9_]+`, ≤40 chars). */
+export function slugifyValueId(raw: string): string {
+ const id = raw
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "_")
+ .replace(/^_+|_+$/g, "")
+ .slice(0, 40)
+ .replace(/_+$/g, "");
+ return id || "value";
+}
+
+/** A parsed run of template text: either literal text or a `{{id}}` token reference. */
+export type TextSegment = { kind: "text"; text: string } | { kind: "token"; id: string };
+
+/** Matches `{{ id }}` (optional inner whitespace); id is `[a-z0-9_]+`, case-insensitive. */
+const TOKEN_RE = /\{\{\s*([a-z0-9_]+)\s*\}\}/gi;
+
+/** Split template text into literal + token segments (drives the pill renderer). */
+export function tokenize(text: string): TextSegment[] {
+ const out: TextSegment[] = [];
+ let last = 0;
+ for (const m of text.matchAll(TOKEN_RE)) {
+ const at = m.index ?? 0;
+ if (at > last) out.push({ kind: "text", text: text.slice(last, at) });
+ out.push({ kind: "token", id: m[1].toLowerCase() });
+ last = at + m[0].length;
+ }
+ if (last < text.length) out.push({ kind: "text", text: text.slice(last) });
+ return out;
+}
+
+/** The distinct token ids referenced in text, in first-seen order. */
+export function tokenIds(text: string): string[] {
+ const ids: string[] = [];
+ for (const m of text.matchAll(TOKEN_RE)) {
+ const id = m[1].toLowerCase();
+ if (!ids.includes(id)) ids.push(id);
+ }
+ return ids;
+}
+
+/** Deterministically substitute `{{id}}` → the matching value's literal. Unknown tokens
+ * are left untouched (surfaced to the UI/validation via {@link unresolvedTokens}). */
+export function renderValues(text: string, values: Value[]): string {
+ if (!text) return text;
+ const map = new Map(values.map((v) => [v.id, v.value]));
+ return text.replace(TOKEN_RE, (whole, id: string) => {
+ const hit = map.get(id.toLowerCase());
+ return hit === undefined ? whole : hit;
+ });
+}
+
+/** Token ids referenced in text that have no matching declared value (for validation/UI). */
+export function unresolvedTokens(text: string, values: Value[]): string[] {
+ const known = new Set(values.map((v) => v.id));
+ return tokenIds(text).filter((id) => !known.has(id));
+}
+
+/**
+ * Back-compat: older persisted plans carried an `inputs[]` construct with a `source`
+ * (fixed / provided / locate, or the even older constant / ask / discover). Only the
+ * genuinely *fixed* ones map cleanly onto values; the rest were runtime- or
+ * agent-resolved and now live as plain prose in the steps, so they are dropped. Used by
+ * the plan schemas' `preprocess` so old drafts keep loading.
+ */
+export function migrateLegacyInputsToValues(raw: unknown): unknown {
+ if (!raw || typeof raw !== "object") return raw;
+ const obj = raw as Record<string, unknown>;
+ // New-shape plans already carry `values`; leave them untouched.
+ if (Array.isArray(obj.values)) return raw;
+ if (!Array.isArray(obj.inputs)) return raw;
+ const values = (obj.inputs as unknown[])
+ .map((i) => (i && typeof i === "object" ? (i as Record<string, unknown>) : null))
+ .filter((i): i is Record<string, unknown> => {
+ const src = i?.source;
+ return typeof i?.name === "string" && (src === "fixed" || src === "constant");
+ })
+ .map((i) => ({
+ id: slugifyValueId(String(i.name)),
+ name: String(i.name),
+ value: typeof i.detail === "string" ? i.detail : "",
+ }));
+ return { ...obj, values };
+}
diff --git a/electron/automationbuilder/builder.ts b/electron/automationbuilder/builder.ts
index 3f6c20c..66a3d4d 100644
--- a/electron/automationbuilder/builder.ts
+++ b/electron/automationbuilder/builder.ts
@@ -47,8 +47,8 @@ interface LiveBuild extends BaseLive {
sessionDir: string;
architecture: SkillArchitecture;
copilot: CopilotSession;
- holder: { plan: AutomationPlan | undefined; submission: AutomationSubmission | undefined };
- /** Last plan proposed this build (kept so submit can reference it). */
+ holder: { plan: AutomationPlan | undefined };
+ /** Last plan proposed this build (kept so create can reference it). */
lastPlan: AutomationPlan | null;
}
@@ -108,25 +108,31 @@ export class AutomationBuilder extends AgentBuilder<LiveBuild> {
}
}
- /** Finalize the user-edited plan into an automation bundle and export it. The plan
- * fully determines the bundle (trigger + ordered prompt-steps), so this builds it
- * directly — no extra agent turn — and the export matches the reviewed tiles exactly. */
+ /** Finalize the user-edited plan into an automation bundle and export it. The reviewed
+ * plan fully determines the bundle, so this is deterministic — no agent turn. Each step
+ * prompt's `{{id}}` value tokens are substituted for their literals at render time
+ * ({@link toAutomationImport}), so what the user reviewed is exactly what ships. Throws
+ * if the plan has no steps (a bundle needs ≥1). */
async create(sessionId: string, editedPlan?: AutomationPlan): Promise<{ automation: BuiltAutomation; path: string }> {
if (this.active.has(sessionId)) throw new Error("Wait for the current step to finish.");
+ const held = this.live.get(sessionId);
// Prefer the user's edited plan from the review tiles; fall back to the last
// proposed plan for older callers that don't pass one.
- const plan = editedPlan ? AutomationPlanSchema.parse(editedPlan) : this.live.get(sessionId)?.lastPlan ?? null;
+ const plan = editedPlan ? AutomationPlanSchema.parse(editedPlan) : held?.lastPlan ?? null;
if (!plan) throw new Error("There is no plan to build from yet.");
+ // The reviewed tiles are the whole payload: validate ≥1 step and carry the
+ // trigger/schedule/name/description/model/values verbatim. No second agent turn.
+ let submission: AutomationSubmission;
+ try {
+ submission = planToAutomationSubmission(plan);
+ } catch {
+ throw new Error("Add at least one step before you create the automation.");
+ }
+ if (held) held.lastPlan = plan;
this.active.add(sessionId);
try {
this.emit(sessionId, "drafting", "Writing the automation…");
- let submission: AutomationSubmission;
- try {
- submission = planToAutomationSubmission(plan);
- } catch {
- throw new Error("Add at least one step before you create the automation.");
- }
const built = toBuiltAutomation(sessionId, plan.architecture, submission, plan);
const exportPath = this.exportAutomation(built);
const finalAutomation: BuiltAutomation = { ...built, exportedPath: exportPath, exportedAt: Date.now() };
@@ -149,7 +155,7 @@ export class AutomationBuilder extends AgentBuilder<LiveBuild> {
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 holder: LiveBuild["holder"] = { plan: undefined };
const tools = [
...createReadTools({
sessionDir: dir,
@@ -162,9 +168,6 @@ export class AutomationBuilder extends AgentBuilder<LiveBuild> {
onPlan: (p) => {
holder.plan = p;
},
- onSubmit: (s) => {
- holder.submission = s;
- },
}),
];
@@ -239,6 +242,7 @@ export class AutomationBuilder extends AgentBuilder<LiveBuild> {
}
}
+/** Render the current plan into a compact spec for the refine prompt (the propose turn). */
function renderRefinePrompt(feedback: string, prior: AutomationPlan | null): string {
const lines = [
"The user reviewed your proposed plan and wants changes. Revise the plan and call",
diff --git a/electron/automationbuilder/instructions.ts b/electron/automationbuilder/instructions.ts
index a6e0909..9719370 100644
--- a/electron/automationbuilder/instructions.ts
+++ b/electron/automationbuilder/instructions.ts
@@ -6,10 +6,11 @@
* **steps**, each a natural-language prompt that prefers the agent's native tools.
*
* Two-phase, so the user stays in control:
- * 1. **propose_automation_plan** — infer the generalization, a default schedule, and
- * the native-tool-first steps, then show it. The user refines it in natural
- * language (more turns).
- * 2. **submit_automation** — only after the user approves, emit the final automation.
+ * 1. **propose_automation_plan** — infer the generalization, a default schedule, the
+ * fixed values (referenced as \`{{id}}\` tokens), and the native-tool-first steps,
+ * then show it. The user refines it in natural language (more turns).
+ * 2. The reviewed plan **is** the automation — when the user approves, the app builds
+ * and exports it deterministically (no second agent turn).
*/
export const AUTOMATION_BUILDER_INSTRUCTIONS = `
# Role: Automation Builder
@@ -24,13 +25,14 @@ whose native capabilities are described in the **catalogue below**.
## Two phases — never skip the plan
1. **Propose a plan first.** Call **propose_automation_plan** with how you'll generalize
- the task, the trigger (propose a sensible default **schedule**), and the ordered
- prompt-steps. STOP after this — the user reviews it and may reply with natural-language
- changes (especially to the schedule). If they do, call **propose_automation_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_automation** with the final
- name, description, trigger, and steps.
+ the task, the trigger (propose a sensible default **schedule**), the fixed values it
+ hard-codes (as \`{{id}}\` tokens), and the ordered prompt-steps. STOP after this — the
+ user reviews it and may reply with natural-language changes (especially to the schedule).
+ If they do, call **propose_automation_plan** again with the revision. Only ONE proposal
+ per turn.
+2. **The reviewed plan is the automation.** When the user approves (e.g. "approved",
+ "create it", "looks good"), the app builds and exports it deterministically — there is
+ no separate submit step. Just refine the plan until they're happy, then stop.
## Propose the trigger (you must infer it)
@@ -71,18 +73,26 @@ Each step has a short **label** and a **prompt** — an imperative instruction t
and cloud CLIs. Only fall back to the browser for genuine UI-only steps (a web app with
no API and no CLI). Write shell commands for the device OS (zsh/bash on macOS,
PowerShell on Windows).
-- **Resolve inputs inside the prompt.** An automation runs unattended and can't stop to ask
- a human, so tell the agent to LOCATE inputs on the device / read them from M365, or use a
- genuinely fixed value. Avoid inputs the user must provide at run time.
+- **Self-resolving prompts.** An automation runs unattended and can't stop to ask a human,
+ so each prompt must get what it needs on its own: reference a genuinely fixed literal by
+ its \`{{id}}\` token, and for anything that varies, tell the agent to LOCATE it on the
+ device / read it from M365. Never depend on a value a human must type at run time.
- **No surprises.** Keep destructive or send/create actions explicit in their step so the
user sees them in the plan. The automation must do exactly what its description says.
- Keep it to a few ordered steps (roughly 2–6); each prompt tight and imperative.
-## Inputs (informational)
+## Fixed values → tokens
-List the things the task needs from outside in the plan's \`inputs\` with a likely source
-(locate / fixed — avoid provided). These are for the user's awareness; the automation
-resolves them inside the step prompts.
+Pull every literal that is **the same on every run** — a canonical URL, a file path, a repo
+slug, an API constant — out into the plan's \`values\` as \`{ id, name, value }\` (\`id\` a short
+snake_case key, \`name\` a human label for the editable pill, \`value\` the exact literal). Then
+reference it from a step prompt by its \`{{id}}\` token instead of writing the literal — e.g.
+"gh pr list -R {{repo}}". The user edits the value once (the pill) and it substitutes
+everywhere when the automation is built.
+
+Do NOT create a value for anything discovered at run time or that varies run-to-run — an
+automation locates those itself (tell it to in the step prompt). Never make a value for
+something a human would have to provide.
## Your tools
@@ -91,12 +101,11 @@ resolves them inside the step prompts.
counts) behind those steps. Use it to ground the native-tool mapping and the schedule
in real evidence.
- **propose_automation_plan({ name, title, description, summary, generalization, trigger,
- inputs, steps, model, skillNames })** — your reviewable plan. Call once per turn, then stop.
-- **submit_automation({ name, description, triggerType, schedule, condition?,
- conditionCheckInterval?, model?, steps })** — the final automation. Call only after the
- user approves the plan.
+ values, steps, model, skillNames })** — your reviewable plan; each value is \`{ id, name,
+ value }\` referenced from step prompts as \`{{id}}\`. Call once per turn, then stop. The
+ reviewed plan is the whole automation — the app builds and exports it deterministically,
+ so there is no submit tool.
Start by reading get_analysis (and get_timeline where the mapping or schedule needs
-evidence), then call propose_automation_plan. Do not submit the automation until the plan
-is approved.
+evidence), then call propose_automation_plan and stop; the app builds the approved plan.
`.trim();
diff --git a/electron/automationbuilder/scout-automation-catalog.ts b/electron/automationbuilder/scout-automation-catalog.ts
index 1275dd6..c2a8c4c 100644
--- a/electron/automationbuilder/scout-automation-catalog.ts
+++ b/electron/automationbuilder/scout-automation-catalog.ts
@@ -42,9 +42,9 @@ in plain language.
- Write prompts that GENERALIZE: if the recording acted on N specific items, the prompt tells
the agent to handle every item of that kind, not the specific examples recorded.
- Prompts should prefer Scout's native tools (below) over UI replay, and say briefly why.
-- Resolve inputs inside the prompts: tell the agent to locate them on the device, read
- them from M365, or (only if unavoidable) that they're fixed values. An unattended automation
- can't stop to ask a human, so avoid user-provided inputs — locate or fix them instead.
+- Self-resolving prompts: reference a genuinely fixed literal by its \`{{id}}\` value token,
+ and for anything that varies tell the agent to locate it on the device or read it from M365.
+ An unattended automation can't stop to ask a human, so never depend on a user-provided value.
- Keep destructive or send/create actions explicit so the user sees them in the plan.
${SCOUT_NATIVE_CAPABILITIES}
diff --git a/electron/automationbuilder/tools.ts b/electron/automationbuilder/tools.ts
index 26470bf..c3fce9a 100644
--- a/electron/automationbuilder/tools.ts
+++ b/electron/automationbuilder/tools.ts
@@ -2,9 +2,7 @@ import type { Tool } from "@github/copilot-sdk";
import {
AutomationPlanSchema,
- AutomationSubmissionSchema,
type AutomationPlan,
- type AutomationSubmission,
} from "../../common/automation";
import type { SkillArchitecture } from "../../common/skill";
@@ -15,8 +13,6 @@ export interface AutomationToolContext {
onProgress?: (message: string) => void;
/** Called when the agent proposes a (validated) plan for review. */
onPlan: (plan: AutomationPlan) => void;
- /** Called when the agent submits the final (validated) automation. */
- onSubmit: (submission: AutomationSubmission) => void;
}
/** A wall-clock time-of-day object, reused across the schedule fields. */
@@ -84,7 +80,7 @@ const stepsSchema = {
prompt: {
type: "string" as const,
description:
- "The natural-language instruction to the agent for this step: generalized over the whole collection, native-tool-first, resolving inputs itself (an automation runs unattended).",
+ "The natural-language instruction to the agent for this step: generalized over the whole collection, native-tool-first, and self-resolving (an automation runs unattended). Reference any fixed value by its {{id}} token instead of writing the literal (e.g. \"gh pr list -R {{repo}}\").",
},
},
required: ["prompt"],
@@ -95,18 +91,19 @@ const stepsSchema = {
/**
* Build the automation-specific tools exposed to one Automation Builder session. The
* agent reads the recording via the shared read-tools (get_analysis / get_timeline),
- * proposes a reviewable plan (propose_automation_plan) with a default schedule, then —
- * once the user approves — submits the final automation (submit_automation). Both
- * submissions are zod-validated; the architecture is injected server-side.
+ * then proposes a reviewable plan (propose_automation_plan) with a default schedule and
+ * STOPS. The reviewed plan is the whole payload — the build is deterministic, so there is
+ * no separate submit tool. The plan is zod-validated; the architecture is injected
+ * server-side.
*/
export function createAutomationBuilderTools(ctx: AutomationToolContext): Tool[] {
- const { architecture, onPlan, onSubmit } = ctx;
+ const { architecture, onPlan } = ctx;
const progress = (m: string) => ctx.onProgress?.(m);
const proposePlan: Tool = {
name: "propose_automation_plan",
description:
- "Propose your reviewable plan for the automation: how you'll generalize the task, the trigger (propose a sensible default schedule), the inputs it needs, and the generalized ordered prompt-steps. Call this once per turn, then STOP so the user can review or refine it (especially the schedule). Do NOT submit the automation yet.",
+ "Propose your reviewable plan for the automation: how you'll generalize the task, the trigger (propose a sensible default schedule), the fixed values it hard-codes (each referenced by a {{id}} token in the step prompts), and the generalized ordered prompt-steps. Call this once per turn, then STOP so the user can review or refine it (especially the schedule).",
parameters: {
type: "object",
properties: {
@@ -144,25 +141,27 @@ export function createAutomationBuilderTools(ctx: AutomationToolContext): Tool[]
required: ["schedule"],
additionalProperties: false,
},
- inputs: {
+ values: {
type: "array",
- description: "Inputs the automation needs (informational; resolved inside the step prompts).",
+ description:
+ "Genuinely FIXED literals the procedure hard-codes — a canonical URL, file path, repo slug, or constant that is the SAME every run. Each becomes an inline, editable pill in the review UI and is substituted for its {{id}} token when the automation is built. Do NOT create a value for anything discovered at run time or that varies run-to-run — write those as plain step instructions.",
items: {
type: "object",
properties: {
- name: { type: "string" },
- description: { type: "string" },
- source: {
+ id: {
type: "string",
- enum: ["fixed", "provided", "locate"],
- description: "Prefer locate/fixed — an automation runs unattended and can't ask the user.",
+ description: "snake_case token key referenced in step prompts as {{id}}, e.g. \"repo\".",
},
- detail: {
+ name: {
type: "string",
- description: "For fixed: the value/path. For locate: how to find it.",
+ description: "Short human label shown on the pill, e.g. \"Target repo\".",
+ },
+ value: {
+ type: "string",
+ description: "The exact fixed literal (the URL / path / repo slug / constant).",
},
},
- required: ["name", "source"],
+ required: ["id", "name", "value"],
additionalProperties: false,
},
},
@@ -194,51 +193,5 @@ export function createAutomationBuilderTools(ctx: AutomationToolContext): Tool[]
},
};
- const submitAutomation: Tool = {
- name: "submit_automation",
- description:
- "Submit the final automation AFTER the user approves the plan: name, description, the trigger (triggerType + schedule, plus condition for condition triggers), and the generalized ordered prompt-steps.",
- parameters: {
- type: "object",
- properties: {
- name: { type: "string", description: "kebab-case automation id (matches the approved plan)." },
- description: { type: "string", description: "What the automation does and when it runs." },
- triggerType: {
- type: "string",
- enum: ["schedule", "condition"],
- description: "schedule (default) or condition.",
- },
- schedule: scheduleSchema,
- condition: {
- type: "string",
- description: "For triggerType=condition: the NL condition to check before running.",
- },
- conditionCheckInterval: {
- type: "integer",
- minimum: 1,
- description: "For triggerType=condition: minutes between condition checks.",
- },
- model: { type: "string", description: "Optional per-automation model override." },
- steps: stepsSchema,
- },
- required: ["name", "schedule", "steps"],
- additionalProperties: false,
- },
- handler: (raw) => {
- const parsed = AutomationSubmissionSchema.safeParse(raw);
- if (!parsed.success) {
- return {
- textResultForLlm:
- "submit_automation 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 automation.");
- onSubmit(parsed.data);
- return "Automation recorded. You may stop now.";
- },
- };
-
- return [proposePlan, submitAutomation];
+ return [proposePlan];
}
diff --git a/electron/skillbuilder/builder.ts b/electron/skillbuilder/builder.ts
index 5c8ea00..6041f0f 100644
--- a/electron/skillbuilder/builder.ts
+++ b/electron/skillbuilder/builder.ts
@@ -15,6 +15,7 @@ import {
type SkillPlan,
type SkillSubmission,
} from "../../common/skill";
+import { unresolvedTokens } from "../../common/values";
import type { SkillBuildInput, SkillBuildProgress } from "../../common/ipc";
import { AgentBuilder, type BaseLive } from "../builders/agent-builder";
import { createReadTools } from "../builders/read-tools";
@@ -31,15 +32,16 @@ const TURN_TIMEOUT_MS = 180_000;
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 (fixed / provided / locate), and its " +
- "ordered steps (each a short title + description, with the native tool it uses). " +
- "Stop after propose_plan so the user can review it.";
+ "propose_plan with how you'll generalize this task, its fixed values (each an id + name + " +
+ "value, referenced from steps as {{id}}), and its ordered steps (each a short title + " +
+ "description, with the native tool it uses). Stop after propose_plan so the user can review it.";
const CREATE_PROMPT =
"The user reviewed and edited the plan below. Build the SKILL.md from EXACTLY this plan — do not " +
- "add, drop, reorder, or rename its inputs or steps. Call submit_skill with a generalized, " +
- "native-tool-first instructions body that follows these inputs and steps faithfully (the name and " +
- "description are already decided — you may echo them).";
+ "add, drop, reorder, or rename its values or steps. Call submit_skill with a generalized, " +
+ "native-tool-first instructions body that follows these steps faithfully and references each fixed " +
+ "value by its {{id}} token (never inline the literal). The name and description are already decided — " +
+ "you may echo them.";
const msg = (err: unknown) => (err instanceof Error ? err.message : String(err));
@@ -129,9 +131,11 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {
}
/** Finalize the user-edited plan into a SKILL.md and place it. The edited plan is
- * authoritative: its name/description/inputs/steps are used verbatim and only the
- * markdown body is written by the agent. `target` picks the destination — installed
- * into the agent's live skills folder, or exported (downloaded) to a user-picked dir. */
+ * authoritative: its name/description/values/steps are used verbatim and only the
+ * markdown body is written by the agent (which references each fixed value by its
+ * `{{id}}` token; `renderSkillMarkdown` substitutes the literals). `target` picks the
+ * destination — installed into the agent's live skills folder, or exported (downloaded)
+ * to a user-picked dir. */
async create(
sessionId: string,
editedPlan?: SkillPlan,
@@ -161,6 +165,13 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {
}
const submission = live.holder.submission as SkillSubmission | undefined;
if (!submission) throw new Error("The agent finished without submitting a skill.");
+ // Lint the authored body: the agent is given each value as `{{id}} — name` (never the
+ // literal), so it can only reference tokens. Any token that doesn't match a declared
+ // value would ship un-substituted, so surface it (the render leaves unknown tokens as-is).
+ const unknownTokens = unresolvedTokens(submission.body, plan.values);
+ if (unknownTokens.length) {
+ log.warn(`skill body references unknown value tokens: ${unknownTokens.map((t) => `{{${t}}}`).join(", ")}`);
+ }
// The frontmatter comes from the edited plan (authoritative); only the body is
// the agent's generated prose. allowed-tools may be tightened by the agent to the
// final steps, but never emptied below what the plan declared.
@@ -310,9 +321,12 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {
function renderPlanForPrompt(plan: SkillPlan): string {
const lines = [`Title: ${plan.title}`, `Name: ${plan.name}`, `Description: ${plan.description}`];
if (plan.generalization) lines.push(`Generalization: ${plan.generalization}`);
- if (plan.inputs.length) {
- lines.push("", "Inputs:");
- for (const i of plan.inputs) lines.push(`- ${i.name} [${i.source}]${i.detail ? `: ${i.detail}` : ""}`);
+ if (plan.values.length) {
+ lines.push(
+ "",
+ "Values (reference each by its {{id}} token in the body — never write the literal value yourself):",
+ );
+ for (const v of plan.values) lines.push(`- {{${v.id}}}${v.name ? ` — ${v.name}` : ""}`);
}
if (plan.steps.length) {
lines.push("", "Steps (in order):");
@@ -336,8 +350,8 @@ function renderRefinePrompt(feedback: string, prior: SkillPlan | null): string {
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(", ")}`);
+ if (prior.values.length) {
+ lines.push(`- values: ${prior.values.map((v) => v.name || v.id).join(", ")}`);
}
lines.push("");
}
diff --git a/electron/skillbuilder/instructions.ts b/electron/skillbuilder/instructions.ts
index a0e5630..f6a58a6 100644
--- a/electron/skillbuilder/instructions.ts
+++ b/electron/skillbuilder/instructions.ts
@@ -5,9 +5,9 @@
* 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, the inputs, and the ordered
- * calculation/action steps (each with its native tool), and show it. The user
- * may refine it in natural language (more turns).
+ * 1. **propose_plan** — infer the generalization, the fixed values (referenced as
+ * \`{{id}}\` tokens), and the ordered calculation/action steps (each with its native
+ * tool), 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 = `
@@ -22,9 +22,10 @@ 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.
+ task, the fixed values it hard-codes (as \`{{id}}\` tokens), 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.
@@ -39,24 +40,23 @@ native capabilities are described in the **catalogue below**.
- 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
+## Fixed values → tokens
-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):
-- **fixed** — a value that is the SAME on every run, baked into the skill: a canonical
- URL, or a specific file path that never moves. Put the value/path in \`detail\`.
-- **provided** — the skill asks the user for it at run time (a path, URL, or value).
-- **locate** — the agent FINDS it on the device with native file tools, e.g. "read the
- most recent *.csv in ~/Downloads". Use this when the target varies run-to-run.
+Some steps reference a literal that is **the same on every run** — a canonical URL, a
+file path that never moves, a repo slug, an API constant. Pull each of those out into
+the plan's \`values\` as \`{ id, name, value }\`:
+- \`id\` — a short snake_case key, e.g. \`backlog_url\`.
+- \`name\` — a human label shown on an editable pill in the review UI, e.g. "Blog Backlog v2 URL".
+- \`value\` — the exact literal (the URL / path / repo slug / constant).
-The rule: if the exact value/path is specified and never changes, it's **fixed**; if it
-varies from run to run, it's **provided** or **locate**. Don't mark a file **fixed** just
-because the recording used one path — if next run's file will differ, it's **locate** (or
-**provided**) so the skill doesn't over-pin to one machine.
+Then **reference it from the step text by its \`{{id}}\` token** instead of writing the
+literal — e.g. "open {{backlog_url}} and read the table". The user edits any value in one
+place (the pill) and it substitutes everywhere it's used when the skill is written.
-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.
+Only create a value for something **genuinely fixed**. If a target varies from run to run
+(e.g. "the most recent *.csv in ~/Downloads"), do NOT make it a value — write it as a plain
+step instruction telling the agent to locate it. Never over-pin to one machine's path just
+because the recording used it once.
## Prefer native tools (read the catalogue below)
@@ -99,7 +99,7 @@ should be written, not as a transcript of this one recording:
("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
+ data, 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
@@ -112,13 +112,14 @@ should be written, not as a transcript of this one recording:
- **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, steps,
- allowedTools })** — your reviewable plan. Each input has a \`source\` (fixed / provided /
- locate); each step has a short \`title\`, a \`text\` description, a \`kind\` (calculation /
- action), and its \`tool\`. Call once per turn, then stop.
+- **propose_plan({ name, title, description, summary, generalization, values, steps,
+ allowedTools })** — your reviewable plan. Each value is \`{ id, name, value }\` (a fixed
+ literal referenced from steps as \`{{id}}\`); each step has a short \`title\`, a \`text\`
+ description, a \`kind\` (calculation / action), and its \`tool\`. 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.
+ is the SKILL.md instructions (imperative, generalized, native-tool-first). Reference each
+ fixed value by its \`{{id}}\` token — never inline the literal. 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.
diff --git a/electron/skillbuilder/tools.ts b/electron/skillbuilder/tools.ts
index 2a04ef0..99ce61d 100644
--- a/electron/skillbuilder/tools.ts
+++ b/electron/skillbuilder/tools.ts
@@ -33,7 +33,7 @@ export function createSkillBuilderTools(ctx: SkillToolContext): Tool[] {
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 (fixed / provided / locate), the ordered steps (each with a short title, a description, and the native tool it uses), 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.",
+ "Propose your reviewable plan for the skill: how you'll generalize the task, the fixed values it hard-codes (each a small id + human name + the literal, referenced from the steps by a {{id}} token), the ordered steps (each with a short title, a description, and the native tool it uses), 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: {
@@ -49,26 +49,27 @@ export function createSkillBuilderTools(ctx: SkillToolContext): Tool[] {
description:
"How the recorded specifics become a repeatable procedure (the loop/collection insight).",
},
- inputs: {
+ values: {
type: "array",
+ description:
+ "Genuinely FIXED literals the procedure hard-codes — a canonical URL, file path, repo slug, or constant that is the SAME every run. Each becomes an inline, editable pill in the review UI and is substituted for its {{id}} token when the skill is written. Do NOT create a value for anything discovered at run time or that varies run-to-run — write those as plain step instructions.",
items: {
type: "object",
properties: {
- name: { type: "string" },
- description: { type: "string" },
- source: {
+ id: {
type: "string",
- enum: ["fixed", "provided", "locate"],
- description:
- "fixed = a URL/path/value that's the SAME every run; provided = ask the user at run time; locate = the agent finds it on the device (varies run-to-run).",
+ description: "snake_case token key referenced in step text as {{id}}, e.g. \"backlog_url\".",
},
- detail: {
+ name: {
type: "string",
- description:
- "For fixed: the value/path. For provided: what to ask for. For locate: how to find it.",
+ description: "Short human label shown on the pill, e.g. \"Blog Backlog v2 URL\".",
+ },
+ value: {
+ type: "string",
+ description: "The exact fixed literal (the URL / path / repo slug / constant).",
},
},
- required: ["name", "source"],
+ required: ["id", "name", "value"],
additionalProperties: false,
},
},
@@ -90,7 +91,8 @@ export function createSkillBuilderTools(ctx: SkillToolContext): Tool[] {
},
text: {
type: "string",
- description: "Imperative, generalized description of the step.",
+ description:
+ "Imperative, generalized description of the step. Reference any fixed value by its {{id}} token instead of writing the literal (e.g. \"open {{backlog_url}} and read the table\").",
},
tool: {
type: "string",
@@ -145,7 +147,7 @@ export function createSkillBuilderTools(ctx: SkillToolContext): Tool[] {
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.",
+ "The SKILL.md instructions body (markdown, everything after the frontmatter): when to use it, the generalized ordered procedure, and which native tools/skills to use. Reference each fixed value by its {{id}} token exactly (e.g. {{backlog_url}}) — never write the literal value yourself; it is substituted in when the skill is written.",
},
},
required: ["name", "description", "body"],
diff --git a/evals/README.md b/evals/README.md
index d72ecdb..8474fc4 100644
--- a/evals/README.md
+++ b/evals/README.md
@@ -203,15 +203,16 @@ the builder, not the describer.
**Rubric** (`score.ts`) — beyond the `mustUseAny` / `forbidden` native-tool checks,
each scenario asserts the shape of the proposed `SkillPlan`:
-- **input sources** — `expectInputSources` requires the plan to classify at least
- one input with each listed `source` (`fixed` / `provided` / `locate`), proving the
- vocabulary is applied, not just present.
+- **fixed values** — `minValues` requires the plan to declare at least that many fixed
+ `values`, and the scorer additionally checks that every `{{token}}` a step references
+ resolves to a declared value (no stale/unknown tokens survive to the artifact).
- **typed steps** — `minCalculations` / `minActions` require the procedure to be
split into `calculation` (no side effect) and `action` (changes the world) steps.
**Coverage.** Five scenarios. Two target **Scout**: `price-tracker-skill` (a canonical
-page URL → **fixed** input, `web_fetch` + the `xlsx` skill, calculations then an
-append) and `github-issue-triage-skill` (the gh-vs-browser case as a skill —
+page URL → a fixed **value** referenced as `{{…}}`, `web_fetch` + the `xlsx` skill,
+calculations then an append) and `github-issue-triage-skill` (the gh-vs-browser case as a
+skill —
must use `gh`, forbid the browser, and drive the mutating comment/label actions). Three
target **Cowork** (Microsoft 365 Copilot), whose catalogue has **no browser automation**
— each asserts the right M365 `server/Tool` is reached for while playwright/`click` and
diff --git a/evals/skillbuilder/run.ts b/evals/skillbuilder/run.ts
index 9150e48..8f666a1 100644
--- a/evals/skillbuilder/run.ts
+++ b/evals/skillbuilder/run.ts
@@ -1,8 +1,8 @@
// Skill builder eval harness: runs the real SkillBuilder against each fixed
// scenario and scores the PROPOSED PLAN's shape — the richer contract the builder
-// now emits: typed inputs (each with a `source`), and an ordered list of typed
-// steps (calculation vs action, each with its native tool and an optional
-// confirmation pause).
+// now emits: fixed **values** referenced from step text as `{{id}}` tokens, and an
+// ordered list of typed steps (calculation vs action, each with its native tool and an
+// optional confirmation pause).
//
// For every scenario it seeds the scenario's FIXED approved analysis (analysis.json)
// + a minimal timeline (bundle.json) into a temp sessions root, runs the real
@@ -123,8 +123,8 @@ function printResult(r: Result): void {
console.error(` ✗ error: ${r.error}`);
return;
}
- for (const inp of r.plan?.inputs ?? []) {
- console.error(` input · ${inp.name} [${inp.source}]`);
+ for (const val of r.plan?.values ?? []) {
+ console.error(` value · {{${val.id}}} ${val.name}${val.value ? ` = ${val.value}` : ""}`);
}
for (const [i, s] of (r.plan?.steps ?? []).entries()) {
const tool = s.tool ? ` {${s.tool}}` : "";
diff --git a/evals/skillbuilder/scenario.ts b/evals/skillbuilder/scenario.ts
index 5da4c70..9862fd5 100644
--- a/evals/skillbuilder/scenario.ts
+++ b/evals/skillbuilder/scenario.ts
@@ -3,19 +3,19 @@
// A sibling of evals/builder/ (which guards the AutomationBuilder). This one guards
// the SkillBuilder — the stage that turns an approved analysis into a reusable
// SKILL.md plan. It exists to exercise the richer skill *plan* shape the builder now
-// proposes: typed inputs (each with a `source`), and an ordered list of typed
-// `steps` (calculation vs action, each with its native tool and an optional
-// confirmation pause). Like the automation harness, each scenario ships a FIXED
-// approved analysis so a failure points at the builder, not the describer.
+// proposes: fixed **values** referenced from step text as `{{id}}` tokens, and an
+// ordered list of typed `steps` (calculation vs action, each with its native tool and
+// an optional confirmation pause). Like the automation harness, each scenario ships a
+// FIXED approved analysis so a failure points at the builder, not the describer.
import type { AnalysisSubmission } from "../../common/analysis";
-import type { SkillArchitecture, SkillInputSource } from "../../common/skill";
+import type { SkillArchitecture } from "../../common/skill";
/**
* Deterministic rubric for a proposed SkillPlan. Beyond the native-tool check the
- * automation harness does, it asserts the plan's *structure* — that inputs are
- * classified with the right source vocabulary and that the procedure is split into
- * calculations and actions with confirmation on the risky ones.
+ * automation harness does, it asserts the plan's *structure* — that genuinely fixed
+ * literals are pulled out as `values` (and every `{{token}}` a step references resolves
+ * to one), and that the procedure is split into calculations and actions.
*/
export interface SkillRubric {
/**
@@ -26,10 +26,8 @@ export interface SkillRubric {
mustUseAny: string[][];
/** None of these may appear in the steps or allowed-tools — signals of the WRONG tool. */
forbidden: string[];
- /** Each listed source must be assigned to at least one input (proves the vocabulary is used). */
- expectInputSources?: SkillInputSource[];
- /** The plan must declare at least this many inputs. Default 1. */
- minInputs?: number;
+ /** The plan must declare at least this many fixed values. Default 0. */
+ minValues?: number;
/** The plan must contain at least this many `calculation` steps. Default 1. */
minCalculations?: number;
/** The plan must contain at least this many `action` steps. Default 1. */
diff --git a/evals/skillbuilder/scenarios.ts b/evals/skillbuilder/scenarios.ts
index 40ed5ef..0c655a5 100644
--- a/evals/skillbuilder/scenarios.ts
+++ b/evals/skillbuilder/scenarios.ts
@@ -91,8 +91,7 @@ const priceTracker: SkillBuilderScenario = {
rubric: {
mustUseAny: [["web_fetch"], ["xlsx"]],
forbidden: [],
- expectInputSources: ["fixed"],
- minInputs: 1,
+ minValues: 1,
minCalculations: 1,
minActions: 1,
},
@@ -172,7 +171,7 @@ const githubIssueTriage: SkillBuilderScenario = {
rubric: {
mustUseAny: [["gh "], ["gh issue", "gh api"]],
forbidden: ["playwright", "browser_", "click", "navigate to github", "github.com/acme"],
- minInputs: 1,
+ minValues: 1,
minCalculations: 1,
minActions: 1,
},
@@ -250,7 +249,6 @@ const coworkTeamsDigest: SkillBuilderScenario = {
rubric: {
mustUseAny: [["m365_teams"], ["postchannelmessage", "postmessage", "replytochannelmessage"]],
forbidden: ["playwright", "browser_", "click", "teams.microsoft.com"],
- minInputs: 1,
minCalculations: 1,
minActions: 1,
},
@@ -321,7 +319,6 @@ const coworkOutlookReply: SkillBuilderScenario = {
rubric: {
mustUseAny: [["outlook/"], ["replytomessage", "senddraftmessage", "createdraftmessage", "replyalltomessage"]],
forbidden: ["playwright", "browser_", "click", "outlook.office.com", "outlook.office365.com"],
- minInputs: 1,
minCalculations: 1,
minActions: 1,
},
@@ -394,7 +391,6 @@ const coworkCalendarSchedule: SkillBuilderScenario = {
["createevent"],
],
forbidden: ["playwright", "browser_", "click", "outlook.office.com"],
- minInputs: 1,
minCalculations: 1,
minActions: 1,
},
diff --git a/evals/skillbuilder/score.ts b/evals/skillbuilder/score.ts
index 73fabd4..824df4a 100644
--- a/evals/skillbuilder/score.ts
+++ b/evals/skillbuilder/score.ts
@@ -2,12 +2,13 @@
//
// Where the automation scorer only checks native-tool choice over free-text step
// prompts, a SkillPlan is structured — so we score both the tool choice AND the
-// shape the builder is now supposed to produce: inputs classified with the right
-// `source`, an ordered procedure split into calculations and actions, and a
-// confirmation pause on the risky ones. Each is a cheap, exact check so a run is
-// repeatable and a failure names the missing piece.
+// shape the builder is now supposed to produce: genuinely fixed literals pulled out
+// as `values` (with every `{{token}}` a step references resolving to one), and an
+// ordered procedure split into calculations and actions. Each is a cheap, exact check
+// so a run is repeatable and a failure names the missing piece.
import type { SkillPlan } from "../../common/skill";
+import { unresolvedTokens } from "../../common/values";
import type { SkillRubric } from "./scenario";
export interface SkillCheck {
@@ -53,23 +54,19 @@ export function scoreSkill(plan: SkillPlan, rubric: SkillRubric): SkillScoreResu
});
}
- // Inputs: at least N, and every expected source classified on at least one input.
- const minInputs = rubric.minInputs ?? 1;
+ // Values: at least N declared, and every {{token}} used in a step resolves to one.
+ const minValues = rubric.minValues ?? 0;
checks.push({
- name: `declares >= ${minInputs} input(s)`,
- pass: plan.inputs.length >= minInputs,
- detail: `found ${plan.inputs.length}`,
+ name: `declares >= ${minValues} value(s)`,
+ pass: plan.values.length >= minValues,
+ detail: `found ${plan.values.length}`,
+ });
+ const unresolved = [...new Set(plan.steps.flatMap((s) => unresolvedTokens(s.text, plan.values)))];
+ checks.push({
+ name: "every {{token}} in steps resolves to a value",
+ pass: unresolved.length === 0,
+ detail: unresolved.length ? `unresolved: ${unresolved.map((t) => `{{${t}}}`).join(", ")}` : undefined,
});
- for (const source of rubric.expectInputSources ?? []) {
- const hit = plan.inputs.filter((i) => i.source === source);
- checks.push({
- name: `an input is source "${source}"`,
- pass: hit.length > 0,
- detail: hit.length
- ? `${hit.map((i) => JSON.stringify(i.name)).join(", ")}`
- : `sources present: ${[...new Set(plan.inputs.map((i) => i.source))].join(", ") || "none"}`,
- });
- }
// Steps: split into calculations and actions.
const calculations = plan.steps.filter((s) => s.kind === "calculation");
diff --git a/src/App.css b/src/App.css
index 9c0fd40..7bdb027 100644
--- a/src/App.css
+++ b/src/App.css
@@ -2364,87 +2364,113 @@ button:focus-visible,
color: var(--muted) !important;
}
-/* Inputs — each with a source badge (the "how it gets this" signal) */
-.sb-inputs {
- list-style: none;
- margin: 0;
- padding: 0;
- display: flex;
- flex-direction: column;
- gap: 8px;
-}
-
-.input-row {
- display: flex;
- flex-direction: column;
- gap: 3px;
- background: var(--surface);
- border: 1px solid var(--line);
- border-radius: 9px;
- padding: 10px 12px;
+/* Value pills — a fixed value referenced from step text as {{id}}. In read mode each
+ token renders as a named, inline chip; click it to edit the literal that substitutes
+ into the exported SKILL.md / automation.json. One value, edited once, applies everywhere. */
+.val-pill {
+ font: inherit;
+ font-weight: 600;
+ color: var(--brand-ink);
+ background: var(--signal-dim);
+ border: 1px solid transparent;
+ border-radius: 6px;
+ padding: 0 6px;
+ margin: 0 1px;
+ cursor: text;
}
-.input-main {
- display: flex;
- align-items: center;
- gap: 9px;
+.val-pill:hover {
+ border-color: var(--signal);
}
-.input-name {
- font-size: 13.5px;
- font-weight: 600;
- color: var(--text);
+/* A declared value with no literal yet — a dashed, muted chip inviting a value. */
+.val-pill-empty {
+ color: var(--muted);
+ background: var(--surface-2);
+ border: 1px dashed var(--line);
}
-.src-badge {
+/* A {{token}} with no matching value — flagged so it's caught before export. */
+.val-pill-unresolved {
font-family: var(--mono);
- font-size: 10px;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- border-radius: 20px;
- padding: 2px 9px;
- white-space: nowrap;
+ font-size: 0.9em;
+ color: var(--warn);
+ background: rgba(var(--warn-rgb), 0.12);
+ border-radius: 6px;
+ padding: 0 5px;
}
-.src-provided {
- color: var(--brand-ink);
- background: var(--signal-dim);
+/* The pill's active state while its editor popover is open. */
+.val-pill-active {
+ border-color: var(--signal);
+ box-shadow: 0 0 0 2px rgba(var(--brand-rgb), 0.25);
}
-.src-locate {
- color: var(--go);
- background: rgba(var(--go-rgb), 0.12);
+/* Floating value editor anchored under a pill (portaled to <body> so nothing clips it). */
+.val-pop {
+ position: fixed;
+ z-index: 1000;
+ width: 340px;
+ max-width: calc(100vw - 16px);
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ padding: 10px;
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.28);
}
-
-.src-fixed {
+.val-pop-label {
+ font-size: 11px;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
color: var(--muted);
- background: var(--surface-2);
}
-
-/* Per-input source switcher (skill plan) — a pill-shaped select tinted by source. */
-.src-select {
+.val-pop-input {
+ width: 100%;
+ box-sizing: border-box;
font-family: var(--mono);
- font-size: 10px;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- border: 1px solid var(--line);
- border-radius: 20px;
- padding: 2px 9px;
- white-space: nowrap;
- cursor: pointer;
- -webkit-appearance: none;
- appearance: none;
+ font-size: 12.5px;
+ line-height: 1.5;
+ color: var(--text);
+ background: var(--surface-2);
+ border: 1px solid var(--signal);
+ border-radius: 6px;
+ padding: 6px 8px;
+ min-height: 1.8em;
+ resize: none;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+.val-pop-input:focus {
+ outline: none;
+}
+.val-pop-hint {
+ font-size: 11px;
+ color: var(--muted);
}
-.src-select:disabled {
- opacity: 0.6;
+/* Inline prose editor: pills stay as atomic, non-editable chips while the wording around
+ them is edited, so the raw {{token}} is never shown. */
+.token-edit {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ cursor: text;
+}
+.token-edit:focus {
+ outline: none;
+}
+.token-edit .val-pill {
cursor: default;
+ user-select: none;
}
-.input-detail {
- font-size: 12.5px;
- line-height: 1.45;
- color: var(--muted);
+/* A step body that carries pills flows inline (mixed text + chips), not preformatted. */
+.ed-detail.has-pills {
+ white-space: normal;
}
/* Steps — ordered calculations + actions, each with its native tool. */
@@ -2722,11 +2748,11 @@ button:focus-visible,
line-height: 1.5;
color: var(--muted);
}
-.ed-tool {
- flex: none;
+/* Read-only annotation of the native tool a captured step used (not user-editable). */
+.step-tool {
font-family: var(--mono);
font-size: 12px;
- color: var(--text);
+ color: var(--muted);
}
.ed-title {
font-size: 18px;
@@ -2765,10 +2791,6 @@ button:focus-visible,
.ed-input.ed-title {
font-weight: 620;
}
-.ed-input.ed-tool {
- font-family: var(--mono);
- font-size: 12px;
-}
/* Header title/description sit flush with the plan header (no shift on click). */
.sb-title.ed-read,
@@ -2797,18 +2819,7 @@ button:focus-visible,
background: transparent;
}
-/* --- pill button (source / kind), read → select on click ----------------- */
-.pill-btn {
- flex: none;
- border: none;
- background: none;
- padding: 0;
- margin: 0;
- cursor: pointer;
- line-height: 1;
-}
-
-/* --- inline select (used by pills + schedule) ---------------------------- */
+/* --- inline select (used by the schedule editor) ------------------------- */
.tile-select {
flex: none;
background: var(--surface-2);
diff --git a/src/Library.tsx b/src/Library.tsx
index 340e3b3..edf03a9 100644
--- a/src/Library.tsx
+++ b/src/Library.tsx
@@ -26,7 +26,6 @@ import {
AnalysisStepTiles,
AutomationStepTiles,
EditableText,
- InputTiles,
ScheduleEditor,
SkillStepTiles,
} from "./plan-edit";
@@ -1064,20 +1063,17 @@ function SkillBuilderView({
onChange={(v) => updatePlan({ description: v })}
/>
- <div className="sb-sec">
- <span className="eyebrow">Inputs</span>
- <p className="sb-refine-hint">
- What the skill needs each run. Click a field to edit; set each as fixed, provided by you, or found by the agent.
- </p>
- <InputTiles inputs={plan.inputs} onChange={(inputs) => updatePlan({ inputs })} />
- </div>
-
<div className="sb-sec">
<span className="eyebrow">What the skill will do</span>
<p className="sb-refine-hint">
- Click any step to edit. Reorder, add or remove as needed.
+ Click any step to edit, or a highlighted value to change it. Reorder, add or remove as needed.
</p>
- <SkillStepTiles steps={plan.steps} onChange={(steps) => updatePlan({ steps })} />
+ <SkillStepTiles
+ steps={plan.steps}
+ onChange={(steps) => updatePlan({ steps })}
+ values={plan.values}
+ onChangeValues={(values) => updatePlan({ values })}
+ />
</div>
</div>
)}
@@ -1337,20 +1333,17 @@ function AutomationBuilderView({
)}
</div>
- <div className="sb-sec">
- <span className="eyebrow">Inputs</span>
- <p className="sb-refine-hint">
- What the automation needs each run. Click a field to edit; set each as fixed, provided by you, or found by the agent.
- </p>
- <InputTiles inputs={plan.inputs} onChange={(inputs) => updatePlan({ inputs })} />
- </div>
-
<div className="sb-sec">
<span className="eyebrow">What the automation will do</span>
<p className="sb-refine-hint">
- Click any step to edit. Reorder, add or remove as needed.
+ Click any step to edit, or a highlighted value to change it. Reorder, add or remove as needed.
</p>
- <AutomationStepTiles steps={plan.steps} onChange={(steps) => updatePlan({ steps })} />
+ <AutomationStepTiles
+ steps={plan.steps}
+ onChange={(steps) => updatePlan({ steps })}
+ values={plan.values}
+ onChangeValues={(values) => updatePlan({ values })}
+ />
</div>
</div>
)}
diff --git a/src/plan-edit.tsx b/src/plan-edit.tsx
index 39de1d4..6623131 100644
--- a/src/plan-edit.tsx
+++ b/src/plan-edit.tsx
@@ -1,4 +1,12 @@
-import { useEffect, useRef, useState, type ReactNode } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from "react";
+import { createPortal } from "react-dom";
import type { AnalysisStep } from "../common/analysis";
import {
@@ -7,7 +15,8 @@ import {
type AutomationStepDraft,
type TimeOfDay,
} from "../common/automation";
-import type { PlanStep, SkillInput } from "../common/skill";
+import type { PlanStep } from "../common/skill";
+import { tokenize, type Value } from "../common/values";
/* --- shared array helpers (pure) ----------------------------------------- */
@@ -27,27 +36,6 @@ export function moveItem<T>(arr: T[], i: number, dir: -1 | 1): T[] {
return out;
}
-/* --- shared vocab (input source) ----------------------------------------- */
-
-export const SOURCE_LABEL: Record<SkillInput["source"], string> = {
- fixed: "Fixed value",
- provided: "You provide it",
- locate: "The agent finds it",
-};
-
-const SOURCE_OPTIONS: { value: SkillInput["source"]; label: string }[] = [
- { value: "fixed", label: "Fixed value" },
- { value: "provided", label: "You provide it" },
- { value: "locate", label: "The agent finds it" },
-];
-
-const SOURCE_HINT: Record<SkillInput["source"], string> = {
- fixed: "The exact URL / path / value, baked in",
- provided: "What to ask you for when it runs",
- locate: "How the agent should find it on your device",
-};
-
-
/* --- EditableText: reads as plain text, becomes an input on click --------- */
export function EditableText({
@@ -163,55 +151,6 @@ export function EditableText({
);
}
-/* --- EditablePill: reads as a tinted pill, becomes a select on click ------ */
-
-function EditablePill<T extends string>({
- value,
- options,
- onChange,
- pill,
- selectClassName = "",
-}: {
- value: T;
- options: { value: T; label: string }[];
- onChange: (next: T) => void;
- pill: ReactNode;
- selectClassName?: string;
-}) {
- const [editing, setEditing] = useState(false);
- const ref = useRef<HTMLSelectElement>(null);
-
- useEffect(() => {
- if (editing) ref.current?.focus();
- }, [editing]);
-
- if (editing) {
- return (
- <select
- ref={ref}
- className={`tile-select ${selectClassName}`}
- value={value}
- onChange={(e) => {
- onChange(e.target.value as T);
- setEditing(false);
- }}
- onBlur={() => setEditing(false)}
- >
- {options.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
- );
- }
- return (
- <button type="button" className="pill-btn" title="Click to change" onClick={() => setEditing(true)}>
- {pill}
- </button>
- );
-}
-
/* --- reusable row controls (hover-revealed by CSS) ----------------------- */
function RowControls({
@@ -222,7 +161,7 @@ function RowControls({
}: {
index: number;
count: number;
- /** Omit to hide reorder arrows (e.g. for unordered inputs). */
+ /** Omit to hide reorder arrows (e.g. for an unordered set). */
onMove?: (dir: -1 | 1) => void;
onRemove: () => void;
}) {
@@ -271,55 +210,387 @@ function newId(prefix: string): string {
return `${prefix}${Date.now().toString(36)}${uidCounter.toString(36)}`;
}
-/* --- Inputs (a SET — editable, add/remove, but NOT reorderable) ----------- */
+/* --- Value pills: a {{token}} rendered as a named, inline-editable chip ---- */
-export function InputTiles({
- inputs,
+/** Size a textarea to its content so a long value (e.g. a URL) is fully visible. */
+function autoGrowTextarea(el: HTMLTextAreaElement) {
+ el.style.height = "auto";
+ el.style.height = `${el.scrollHeight}px`;
+}
+
+/** One `{{id}}` reference. Shows the value's human name as an inline chip; clicking opens a
+ * small popover (portaled, anchored to the chip) with the value's name as a label and a
+ * full-width, auto-growing field for the literal that substitutes in at export. Open state
+ * is controlled by the parent so only one popover is ever open — even when the same token
+ * appears more than once in a step. An unknown token (no matching value) renders as a
+ * flagged, non-editable chip so it's caught before shipping. */
+function ValuePill({
+ token,
+ value,
+ open,
+ onOpen,
+ onClose,
onChange,
}: {
- inputs: SkillInput[];
- onChange: (next: SkillInput[]) => void;
+ token: string;
+ value: Value | undefined;
+ open: boolean;
+ onOpen: () => void;
+ onClose: () => void;
+ onChange: (next: Value) => void;
}) {
- const patch = (i: number, part: Partial<SkillInput>) =>
- onChange(replaceAt(inputs, i, { ...inputs[i], ...part }));
+ const btnRef = useRef<HTMLButtonElement | null>(null);
+ // Unknown token: no value to edit — flag it so the user (or agent) fixes it before export.
+ if (!value) {
+ return (
+ <span className="val-pill val-pill-unresolved" title="No value is defined for this token">
+ {`{{${token}}}`}
+ </span>
+ );
+ }
+
+ const label = value.name || token;
return (
- <div className="tiles">
- {inputs.map((inp, i) => (
- <div key={i} className="tile input-tile">
- <div className="tile-head">
- <EditableText
- className="ed-name"
- value={inp.name}
- placeholder="Input name"
- ariaLabel="Input name"
- onChange={(v) => patch(i, { name: v })}
- />
- <EditablePill
- value={inp.source}
- options={SOURCE_OPTIONS}
- onChange={(v) => patch(i, { source: v })}
- pill={<span className={`src-badge src-${inp.source}`}>{SOURCE_LABEL[inp.source]}</span>}
- />
- <RowControls index={i} count={inputs.length} onRemove={() => onChange(removeAt(inputs, i))} />
- </div>
- <EditableText
- as="p"
- multiline
- className="ed-detail"
- value={inp.detail}
- placeholder={SOURCE_HINT[inp.source]}
- ariaLabel="Input detail"
- hideEmpty
- onChange={(v) => patch(i, { detail: v })}
- />
- </div>
- ))}
- <AddTile
- label="Add input"
- onAdd={() => onChange([...inputs, { name: "", description: "", source: "provided", detail: "" }])}
+ <>
+ <button
+ ref={btnRef}
+ type="button"
+ className={`val-pill${value.value.trim() ? "" : " val-pill-empty"}${open ? " val-pill-active" : ""}`}
+ title={`${label}${value.value ? `: ${value.value}` : ""} — click to edit`}
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpen();
+ }}
+ >
+ {label}
+ </button>
+ {open && (
+ <ValuePopover
+ anchorRef={btnRef}
+ label={label}
+ value={value.value}
+ onCommit={(next) => {
+ onClose();
+ if (next !== value.value) onChange({ ...value, value: next });
+ }}
+ onCancel={onClose}
+ />
+ )}
+ </>
+ );
+}
+
+/** A small floating editor for one value's literal, anchored under its pill and portaled to
+ * <body> so scroll/overflow containers can't clip it. The sentence layout stays put while
+ * the card floats above. Commits on Enter or click-outside; Escape cancels. */
+function ValuePopover({
+ anchorRef,
+ label,
+ value,
+ onCommit,
+ onCancel,
+}: {
+ anchorRef: RefObject<HTMLButtonElement | null>;
+ label: string;
+ value: string;
+ onCommit: (next: string) => void;
+ onCancel: () => void;
+}) {
+ const cardRef = useRef<HTMLDivElement | null>(null);
+ const taRef = useRef<HTMLTextAreaElement | null>(null);
+ const [draft, setDraft] = useState(value);
+ const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
+
+ const reposition = useCallback(() => {
+ const anchor = anchorRef.current;
+ const card = cardRef.current;
+ if (!anchor || !card) return;
+ const a = anchor.getBoundingClientRect();
+ const cw = card.offsetWidth;
+ const ch = card.offsetHeight;
+ const m = 8; // viewport margin
+ const left = Math.max(m, Math.min(a.left, window.innerWidth - cw - m));
+ let top = a.bottom + 6;
+ if (top + ch > window.innerHeight - m) {
+ const above = a.top - ch - 6;
+ top = above >= m ? above : Math.max(m, window.innerHeight - ch - m);
+ }
+ setPos({ top, left });
+ }, [anchorRef]);
+
+ // Focus the field and grow it to fit the value on open.
+ useEffect(() => {
+ const el = taRef.current;
+ if (!el) return;
+ el.focus();
+ el.setSelectionRange(el.value.length, el.value.length);
+ autoGrowTextarea(el);
+ }, []);
+
+ // Position after layout, and re-measure as the field grows.
+ useLayoutEffect(() => {
+ reposition();
+ }, [reposition, draft]);
+
+ // Stay anchored on scroll/resize; commit when the user clicks outside the card.
+ const commitRef = useRef(onCommit);
+ commitRef.current = onCommit;
+ useEffect(() => {
+ const onScroll = () => reposition();
+ const onDocPointer = (e: MouseEvent) => {
+ const t = e.target as Node;
+ if (cardRef.current?.contains(t) || anchorRef.current?.contains(t)) return;
+ commitRef.current(taRef.current?.value ?? "");
+ };
+ window.addEventListener("scroll", onScroll, true);
+ window.addEventListener("resize", onScroll);
+ document.addEventListener("mousedown", onDocPointer, true);
+ return () => {
+ window.removeEventListener("scroll", onScroll, true);
+ window.removeEventListener("resize", onScroll);
+ document.removeEventListener("mousedown", onDocPointer, true);
+ };
+ }, [reposition, anchorRef]);
+
+ return createPortal(
+ <div
+ ref={cardRef}
+ className="val-pop"
+ role="dialog"
+ aria-label={`Edit ${label}`}
+ style={{
+ top: pos?.top ?? -9999,
+ left: pos?.left ?? -9999,
+ visibility: pos ? "visible" : "hidden",
+ }}
+ // The card is portaled to <body>, but React bubbles its synthetic events through the
+ // component tree — so without this, a click inside would reach the step's read-mode
+ // <p onClick> and switch it into the prose editor, unmounting this popover.
+ onMouseDown={(e) => e.stopPropagation()}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="val-pop-label">{label}</div>
+ <textarea
+ ref={taRef}
+ className="val-pop-input"
+ rows={1}
+ value={draft}
+ spellCheck={false}
+ aria-label={`${label} value`}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ autoGrowTextarea(e.target);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ } else if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ onCommit(draft);
+ }
+ }}
/>
- </div>
+ <div className="val-pop-hint">Esc to cancel · ⏎ to save</div>
+ </div>,
+ document.body,
+ );
+}
+
+/** Serialize the pill editor's DOM back to `{{id}}` template text: text nodes are kept
+ * verbatim and each atomic pill chip (a `[data-token]` element) becomes its `{{id}}`, so
+ * the round-trip is exact and the raw token is never typed by the user. */
+function serializeTokenNode(node: Node): string {
+ if (node.nodeType === Node.TEXT_NODE) return node.nodeValue ?? "";
+ if (node.nodeType !== Node.ELEMENT_NODE) return "";
+ const el = node as HTMLElement;
+ const tok = el.dataset.token;
+ if (tok) return `{{${tok}}}`;
+ if (el.tagName === "BR") return "\n";
+ let out = "";
+ el.childNodes.forEach((c) => (out += serializeTokenNode(c)));
+ return out;
+}
+
+function serializeTokenEditor(root: HTMLElement): string {
+ let out = "";
+ root.childNodes.forEach((c) => (out += serializeTokenNode(c)));
+ return out;
+}
+
+/** Populate the pill editor: prose becomes editable text nodes, and each `{{id}}` becomes
+ * an atomic, non-editable chip that looks exactly like its read-mode pill — so editing the
+ * wording around a value never exposes the raw `{{token}}`. */
+function buildTokenEditor(root: HTMLElement, text: string, values: Value[]): void {
+ const byId = new Map(values.map((v) => [v.id, v]));
+ root.replaceChildren();
+ for (const seg of tokenize(text)) {
+ if (seg.kind === "text") {
+ root.appendChild(document.createTextNode(seg.text));
+ continue;
+ }
+ const v = byId.get(seg.id);
+ const chip = document.createElement("span");
+ chip.dataset.token = seg.id;
+ chip.contentEditable = "false";
+ if (!v) {
+ chip.className = "val-pill val-pill-unresolved";
+ chip.textContent = `{{${seg.id}}}`;
+ } else {
+ chip.className = `val-pill${v.value.trim() ? "" : " val-pill-empty"}`;
+ chip.textContent = v.name || seg.id;
+ }
+ root.appendChild(chip);
+ }
+}
+
+/** Step body that renders `{{id}}` tokens as editable {@link ValuePill}s. In read mode a
+ * pill shows the value's name and click-edits its literal; clicking the prose opens an
+ * inline editor where pills stay atomic chips (never raw tokens) and only the surrounding
+ * wording is editable. Editing prose updates the step text; editing a pill updates the
+ * shared value. */
+function TokenText({
+ text,
+ onChangeText,
+ values,
+ onChangeValues,
+ placeholder,
+ ariaLabel,
+}: {
+ text: string;
+ onChangeText: (next: string) => void;
+ values: Value[];
+ onChangeValues: (next: Value[]) => void;
+ placeholder: string;
+ ariaLabel: string;
+}) {
+ const [editing, setEditing] = useState(false);
+ const editorRef = useRef<HTMLDivElement | null>(null);
+ const cancelRef = useRef(false);
+ // Index (into `segments`) of the token whose editor popover is open, or null. Kept here so
+ // at most one popover is ever open — even when a token appears more than once in the step.
+ const [openIndex, setOpenIndex] = useState<number | null>(null);
+
+ useEffect(() => {
+ if (!editing) return;
+ const el = editorRef.current;
+ if (!el) return;
+ // Snapshot the current text/values into the editor once; it stays uncontrolled while
+ // focused so keystrokes and the caret aren't clobbered by re-renders.
+ buildTokenEditor(el, text, values);
+ el.focus();
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ range.collapse(false);
+ const sel = window.getSelection();
+ sel?.removeAllRanges();
+ sel?.addRange(range);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [editing]);
+
+ const begin = () => {
+ setOpenIndex(null);
+ setEditing(true);
+ };
+ const commit = () => {
+ if (cancelRef.current) {
+ cancelRef.current = false;
+ setEditing(false);
+ return;
+ }
+ const el = editorRef.current;
+ const next = el ? serializeTokenEditor(el) : text;
+ setEditing(false);
+ if (next !== text) onChangeText(next);
+ };
+ const updateValue = (next: Value) =>
+ onChangeValues(values.map((v) => (v.id === next.id ? next : v)));
+
+ if (editing) {
+ return (
+ <div
+ ref={editorRef}
+ className="ed-input ed-input-multi ed-detail token-edit has-pills"
+ contentEditable
+ suppressContentEditableWarning
+ role="textbox"
+ aria-multiline="true"
+ aria-label={ariaLabel}
+ onBlur={commit}
+ onMouseDown={(e) => {
+ // Clicking a pill chip inside the editor edits that value (not the prose): commit
+ // the wording, then open that token's popover (first occurrence) in read mode.
+ const chip = (e.target as HTMLElement).closest("[data-token]") as HTMLElement | null;
+ if (!chip) return;
+ e.preventDefault();
+ const id = chip.dataset.token ?? null;
+ const el = editorRef.current;
+ const next = el ? serializeTokenEditor(el) : text;
+ cancelRef.current = true; // neutralize the blur-commit that unmounting would fire
+ setEditing(false);
+ if (next !== text) onChangeText(next);
+ if (id) {
+ const idx = tokenize(next).findIndex((s) => s.kind === "token" && s.id === id);
+ if (idx >= 0) setOpenIndex(idx);
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ cancelRef.current = true;
+ editorRef.current?.blur();
+ } else if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ editorRef.current?.blur();
+ }
+ }}
+ />
+ );
+ }
+
+ const empty = text.trim().length === 0;
+ const segments = empty ? [] : tokenize(text);
+ const byId = new Map(values.map((v) => [v.id, v]));
+
+ return (
+ <p
+ className={`ed-read ed-read-multi ed-detail${empty ? " ed-empty" : " has-pills"}`}
+ tabIndex={0}
+ role="textbox"
+ aria-label={ariaLabel}
+ title="Click to edit"
+ onClick={(e) => {
+ // A click on a pill edits its value (via popover), not the surrounding prose.
+ const t = e.target as HTMLElement;
+ if (t.closest(".val-pill")) return;
+ begin();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ begin();
+ }
+ }}
+ >
+ {empty
+ ? placeholder
+ : segments.map((seg, i) =>
+ seg.kind === "token" ? (
+ <ValuePill
+ key={i}
+ token={seg.id}
+ value={byId.get(seg.id)}
+ open={openIndex === i}
+ onOpen={() => setOpenIndex(i)}
+ onClose={() => setOpenIndex(null)}
+ onChange={updateValue}
+ />
+ ) : (
+ <span key={i}>{seg.text}</span>
+ ),
+ )}
+ </p>
);
}
@@ -328,9 +599,13 @@ export function InputTiles({
export function SkillStepTiles({
steps,
onChange,
+ values,
+ onChangeValues,
}: {
steps: PlanStep[];
onChange: (next: PlanStep[]) => void;
+ values: Value[];
+ onChangeValues: (next: Value[]) => void;
}) {
const patch = (i: number, part: Partial<PlanStep>) =>
onChange(replaceAt(steps, i, { ...steps[i], ...part }));
@@ -355,25 +630,21 @@ export function SkillStepTiles({
onRemove={() => onChange(removeAt(steps, i))}
/>
</div>
- <EditableText
- as="p"
- multiline
- className="ed-detail"
- value={s.text}
+ <TokenText
+ text={s.text}
+ onChangeText={(v) => patch(i, { text: v })}
+ values={values}
+ onChangeValues={onChangeValues}
placeholder="What happens in this step?"
ariaLabel="Step description"
- onChange={(v) => patch(i, { text: v })}
/>
- <div className="tile-foot">
- <EditableText
- className="ed-tool"
- value={s.tool}
- placeholder="+ native tool"
- ariaLabel="Native tool"
- hideEmpty
- onChange={(v) => patch(i, { tool: v })}
- />
- </div>
+ {s.tool?.trim() && (
+ <div className="tile-foot">
+ <span className="step-tool" title="Native tool this step uses">
+ {s.tool}
+ </span>
+ </div>
+ )}
</div>
))}
<AddTile
@@ -389,9 +660,13 @@ export function SkillStepTiles({
export function AutomationStepTiles({
steps,
onChange,
+ values,
+ onChangeValues,
}: {
steps: AutomationStepDraft[];
onChange: (next: AutomationStepDraft[]) => void;
+ values: Value[];
+ onChangeValues: (next: Value[]) => void;
}) {
const patch = (i: number, part: Partial<AutomationStepDraft>) =>
onChange(replaceAt(steps, i, { ...steps[i], ...part }));
@@ -416,14 +691,13 @@ export function AutomationStepTiles({
onRemove={() => onChange(removeAt(steps, i))}
/>
</div>
- <EditableText
- as="p"
- multiline
- className="ed-detail"
- value={s.prompt}
+ <TokenText
+ text={s.prompt}
+ onChangeText={(v) => patch(i, { prompt: v })}
+ values={values}
+ onChangeValues={onChangeValues}
placeholder="The instruction the agent runs for this step"
ariaLabel="Step instruction"
- onChange={(v) => patch(i, { prompt: v })}
/>
</div>
))}