Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Let commander create / edit skills in the main conversation; flatten container parsing to arrays

wyt703e768d3b89
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index c974f604..08b2ac82 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -1094,80 +1094,91 @@ export interface ExtractedFields {
interactive?: boolean;
}
-export function extractAgentFieldBlocks(text: string): { cleanText: string; fields: ExtractedFields } {
- if (!text || text.indexOf('<agent>') < 0) return { cleanText: text, fields: {} };
+function _parseAgentBlock(inner: string): ExtractedFields {
const fields: ExtractedFields = {};
- // Only parse the FIRST container in a turn — the LLM is instructed to
- // emit one per reply. Subsequent containers (shouldn't happen) still get
- // stripped below via the global-flag replace.
- const first = text.match(/<agent>([\s\S]*?)<\/agent>/);
- if (first) {
- const inner = first[1];
- const aidM = inner.match(AGENT_CHILD_RE('agent_id'));
- if (aidM) {
- const v = aidM[1].trim();
- if (safeId(v)) fields.agent_id = v;
- }
- const nameM = inner.match(AGENT_CHILD_RE('name'));
- if (nameM) {
- const v = nameM[1].trim();
- if (v) fields.name = v;
- }
- const descM = inner.match(AGENT_CHILD_RE('description'));
- if (descM) {
- const v = descM[1].trim();
- if (v) fields.description = v;
- }
- const descZhM = inner.match(AGENT_CHILD_RE('description_zh'));
- if (descZhM) {
- const v = descZhM[1].trim();
- if (v) fields.description_zh = v;
- }
- const descEnM = inner.match(AGENT_CHILD_RE('description_en'));
- if (descEnM) {
- const v = descEnM[1].trim();
- if (v) fields.description_en = v;
- }
- const wfM = inner.match(AGENT_CHILD_RE('workflow'));
- if (wfM) {
- const v = wfM[1].trim();
- if (v) fields.workflow = v;
- }
- const skM = inner.match(AGENT_CHILD_RE('skills'));
- if (skM) {
- // One skill_id per line; empty body / all-blanks → explicit []
- // (zero skills). Non-safeId entries are dropped with no warning.
- fields.skill_list = skM[1]
- .split(/\r?\n/)
- .map((s) => s.trim())
- .filter((s) => s.length > 0 && safeId(s));
- }
- const inM = inner.match(AGENT_CHILD_RE('inputs'));
- if (inM) {
- const trimmed = inM[1].trim();
- if (trimmed === '' || trimmed === '[]') {
- fields.inputs = [];
- } else {
- try {
- const parsed = JSON.parse(trimmed);
- fields.inputs = validateAgentInputs(parsed);
- } catch (err) {
- log.warn(`<inputs> JSON parse failed: ${(err as Error).message}`);
- // Leave fields.inputs unset — malformed JSON shouldn't erase the
- // previous schema; let the next turn re-emit and fix it.
- }
+ const aidM = inner.match(AGENT_CHILD_RE('agent_id'));
+ if (aidM) {
+ const v = aidM[1].trim();
+ if (safeId(v)) fields.agent_id = v;
+ }
+ const nameM = inner.match(AGENT_CHILD_RE('name'));
+ if (nameM) {
+ const v = nameM[1].trim();
+ if (v) fields.name = v;
+ }
+ const descM = inner.match(AGENT_CHILD_RE('description'));
+ if (descM) {
+ const v = descM[1].trim();
+ if (v) fields.description = v;
+ }
+ const descZhM = inner.match(AGENT_CHILD_RE('description_zh'));
+ if (descZhM) {
+ const v = descZhM[1].trim();
+ if (v) fields.description_zh = v;
+ }
+ const descEnM = inner.match(AGENT_CHILD_RE('description_en'));
+ if (descEnM) {
+ const v = descEnM[1].trim();
+ if (v) fields.description_en = v;
+ }
+ const wfM = inner.match(AGENT_CHILD_RE('workflow'));
+ if (wfM) {
+ const v = wfM[1].trim();
+ if (v) fields.workflow = v;
+ }
+ const skM = inner.match(AGENT_CHILD_RE('skills'));
+ if (skM) {
+ // One skill_id per line; empty body / all-blanks → explicit []
+ // (zero skills). Non-safeId entries are dropped with no warning.
+ fields.skill_list = skM[1]
+ .split(/\r?\n/)
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0 && safeId(s));
+ }
+ const inM = inner.match(AGENT_CHILD_RE('inputs'));
+ if (inM) {
+ const trimmed = inM[1].trim();
+ if (trimmed === '' || trimmed === '[]') {
+ fields.inputs = [];
+ } else {
+ try {
+ const parsed = JSON.parse(trimmed);
+ fields.inputs = validateAgentInputs(parsed);
+ } catch (err) {
+ log.warn(`<inputs> JSON parse failed: ${(err as Error).message}`);
+ // Leave fields.inputs unset — malformed JSON shouldn't erase the
+ // previous schema; let the next turn re-emit and fix it.
}
}
- const itM = inner.match(AGENT_CHILD_RE('interactive'));
- if (itM) {
- const v = itM[1].trim().toLowerCase();
- if (v === 'true') fields.interactive = true;
- else if (v === 'false') fields.interactive = false;
- // Any other body → leave key omitted; previous flag survives.
- }
+ }
+ const itM = inner.match(AGENT_CHILD_RE('interactive'));
+ if (itM) {
+ const v = itM[1].trim().toLowerCase();
+ if (v === 'true') fields.interactive = true;
+ else if (v === 'false') fields.interactive = false;
+ // Any other body → leave key omitted; previous flag survives.
+ }
+ return fields;
+}
+
+/**
+ * Extract every `<agent>...</agent>` container in emission order. Each
+ * block is parsed independently; a malformed sub-tag in one block does
+ * not affect the others. Returns `blocks: []` when no container exists.
+ */
+export function extractAgentFieldBlocks(
+ text: string,
+): { cleanText: string; blocks: ExtractedFields[] } {
+ if (!text || text.indexOf('<agent>') < 0) return { cleanText: text, blocks: [] };
+ const blocks: ExtractedFields[] = [];
+ // Iterate every container with the global-flag regex (NOT just the
+ // first). `AGENT_CONTAINER_RE` carries `/g` so successive `.exec` calls
+ // walk forward; we use `matchAll` for a flat collection.
+ for (const m of text.matchAll(AGENT_CONTAINER_RE)) {
+ blocks.push(_parseAgentBlock(m[1]));
}
const cleaned = text.replace(AGENT_CONTAINER_RE, '').replace(/\n{3,}/g, '\n\n').trim();
- return { cleanText: cleaned, fields };
+ return { cleanText: cleaned, blocks };
}
function agentChatDir(userId: string, agentId: string): string {
@@ -1323,7 +1334,9 @@ export async function sendToAgentEditChat(userId: string, agentId: string, conte
return { ok: false, message: errMsg, error: result.error || '' };
}
- const { cleanText, fields } = extractAgentFieldBlocks(result.text);
+ const { cleanText, blocks } = extractAgentFieldBlocks(result.text);
+ // Inline edit chat is bound to one agent; apply only the first block.
+ const fields = blocks[0] || {};
const updated: ExtractedFields = {};
if (Object.keys(fields).length) {
await updateCustomAgent(agentId, fields);
@@ -1391,7 +1404,9 @@ export async function* streamSendToAgentEditChat(
const synthesizedProgress: string[] = [];
if (etype === 'final') {
const raw = event.text || '';
- const { cleanText, fields } = extractAgentFieldBlocks(raw);
+ const { cleanText, blocks } = extractAgentFieldBlocks(raw);
+ // Inline edit chat is bound to one agent; apply only the first block.
+ const fields = blocks[0] || {};
if (Object.keys(fields).length) {
await updateCustomAgent(agentId, fields);
Object.assign(updated, fields);
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 53fbbbb6..149b2fba 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -36,8 +36,9 @@ import {
import {
resolveRecipients, parseMentions, buildMention,
extractFormFromFinal, computeFormId, ChatFormPayload,
- extractAgentFieldBlocks, decodeSubmission,
+ extractAgentFieldBlocks, extractSkillContainers, decodeSubmission,
} from './router';
+import * as skillsFeat from '../skills';
import {
setPlan, updateStep, readPlan, formatPlanAnnouncement, formatPlanForPrompt,
PlanSetInput, StepStatus, PlanFile,
@@ -269,7 +270,8 @@ export interface EnqueueParams {
attachments?: string[];
produced?: string[];
form?: ChatFormPayload;
- created_agent?: { agent_id: string; name: string };
+ created_agents?: Array<{ agent_id: string; name: string; kind?: 'created' | 'updated' }>;
+ created_skills?: Array<{ skill_id: string; name: string; kind?: 'created' | 'updated' }>;
plan_announcement?: boolean;
/** Override resolved recipients (commander emitting plan announcement
* uses this to force `to=[user]`). Otherwise router decides. */
@@ -533,7 +535,8 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
...(params.attachments && params.attachments.length ? { attachments: params.attachments } : {}),
...(params.produced && params.produced.length ? { produced: params.produced } : {}),
...(params.form ? { form: params.form } : {}),
- ...(params.created_agent ? { created_agent: params.created_agent } : {}),
+ ...(params.created_agents && params.created_agents.length ? { created_agents: params.created_agents } : {}),
+ ...(params.created_skills && params.created_skills.length ? { created_skills: params.created_skills } : {}),
...(params.plan_announcement ? { plan_announcement: true } : {}),
...(params.dispatch ? { dispatch: true } : {}),
...(params.process && params.process.length ? { process: params.process } : {}),
@@ -1009,7 +1012,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// failed) live in plan_executor.onTurnFinished.
let workingText = finalText || '';
let form: ChatFormPayload | undefined;
- let createdAgent: { agent_id: string; name: string; kind: 'created' | 'updated' } | undefined;
+ const createdAgents: Array<{ agent_id: string; name: string; kind: 'created' | 'updated' }> = [];
+ const createdSkills: Array<{ skill_id: string; name: string; kind: 'created' | 'updated' }> = [];
if (actor.kind === 'agent' && workingText) {
const r = extractFormFromFinal(workingText, actor.id);
@@ -1025,48 +1029,79 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
}
} else if (isCommander && workingText) {
const r = extractAgentFieldBlocks(workingText);
- if (Object.keys(r.fields).length) {
+ if (r.blocks.length) {
workingText = r.cleanText;
- // `<agent_id>` present → edit an existing custom agent;
- // absent → create a new one. Same `<agent>` container shape;
- // the dispatch decision is single-bit.
- const editId = r.fields.agent_id;
- try {
- if (editId) {
- const target = await agentsFeat.getAgent(editId);
- if (!target) {
- workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent edit failed: agent not found (id=${editId}).</span>`;
- } else if (target.source !== 'custom') {
- // Built-in agent — read-only here; the dev-mode inline edit chat
- // remains the only path that can mutate builtins (per §6).
- workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Built-in agents can't be edited from the main chat; fork one in the right-hand detail panel and edit there.</span>`;
- } else if (agentsFeat.isCliAgent(target)) {
- // CLI-backed agent — runtime / model / args are owned by the
- // create-modal + edit-form, not the LLM. Same constraint as
- // chat_agent_setup_cli.md applies to the commander flow.
- workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ External agents can only be edited from the right-hand detail panel.</span>`;
+ // Apply each `<agent>` block independently. A failed block appends
+ // its own warning span to workingText and is omitted from
+ // createdAgents — the chip slot only fills when the spec was
+ // actually written. Subsequent blocks still attempt their own apply.
+ for (const fields of r.blocks) {
+ if (!Object.keys(fields).length) continue;
+ const editId = fields.agent_id;
+ try {
+ if (editId) {
+ const target = await agentsFeat.getAgent(editId);
+ if (!target) {
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent edit failed: agent not found (id=${editId}).</span>`;
+ } else if (target.source !== 'custom') {
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Built-in agents can't be edited from the main chat; fork one in the right-hand detail panel and edit there.</span>`;
+ } else if (agentsFeat.isCliAgent(target)) {
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ External agents can only be edited from the right-hand detail panel.</span>`;
+ } else {
+ const updated = await agentsFeat.updateCustomAgent(editId, fields);
+ if (updated) {
+ createdAgents.push({ agent_id: updated.agent_id, name: updated.name, kind: 'updated' });
+ } else {
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent update failed.</span>`;
+ }
+ }
} else {
- const updated = await agentsFeat.updateCustomAgent(editId, r.fields);
- if (updated) {
- createdAgent = { agent_id: updated.agent_id, name: updated.name, kind: 'updated' };
+ const ag = await agentsFeat.createAgentFromBlocks(fields);
+ if (ag) {
+ createdAgents.push({ agent_id: ag.agent_id, name: ag.name, kind: 'created' });
} else {
- workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent update failed.</span>`;
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent creation failed: missing required field(s) (name / workflow).</span>`;
}
}
- } else {
- const ag = await agentsFeat.createAgentFromBlocks(r.fields);
- if (ag) {
- createdAgent = { agent_id: ag.agent_id, name: ag.name, kind: 'created' };
+ } catch (err) {
+ const verb = editId ? 'edit' : 'create';
+ log.error(`${verb}-agent failed cid=${cid}: ${(err as Error).message}`);
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent ${verb} failed: ${(err as Error).message}</span>`;
+ }
+ }
+ }
+
+ // `<skill>` container — parallel to `<agent>` above. Commander only.
+ // The container is independent of `<agent>`; both can co-exist in one
+ // turn in principle, though the prompt encourages one-at-a-time. Best-
+ // effort: a rejected file path within the container does not abort the
+ // remaining writes, mirroring the per-skill edit chat. The localized
+ // error string returned by `applySkillContainerFromCommander` already
+ // covers built-in / not-found / charset / collision cases — bus only
+ // appends the pill.
+ const skillR = extractSkillContainers(workingText);
+ if (skillR.containers.length) {
+ workingText = skillR.cleanText;
+ // Apply each `<skill>` container independently. A failed container
+ // appends its own warning span and is omitted from createdSkills —
+ // the chip slot only fills when the spec was actually written.
+ for (const container of skillR.containers) {
+ try {
+ const result = await skillsFeat.applySkillContainerFromCommander(container);
+ if (result.ok && result.skillId && result.name && result.kind) {
+ createdSkills.push({ skill_id: result.skillId, name: result.name, kind: result.kind });
+ if (result.rejected && result.rejected.length) {
+ const list = result.rejected.map((p) => `\`${p}\``).join(', ');
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Some skill files were rejected: ${list}</span>`;
+ }
} else {
- // Append failure marker to text — onTurnFinished will surface
- // it as a normal `persist` outcome.
- workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent creation failed: missing required field(s) (name / workflow).</span>`;
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ ${result.error || 'Skill operation failed.'}</span>`;
}
+ } catch (err) {
+ const verb = container.skillId ? 'edit' : 'create';
+ log.error(`${verb}-skill failed cid=${cid}: ${(err as Error).message}`);
+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Skill ${verb} failed: ${(err as Error).message}</span>`;
}
- } catch (err) {
- const verb = editId ? 'edit' : 'create';
- log.error(`${verb}-agent failed cid=${cid}: ${(err as Error).message}`);
- workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent ${verb} failed: ${(err as Error).message}</span>`;
}
}
}
@@ -1097,7 +1132,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
aborted,
...(form ? { form } : {}),
produced,
- ...(createdAgent ? { createdAgent } : {}),
+ ...(createdAgents.length ? { createdAgents } : {}),
+ ...(createdSkills.length ? { createdSkills } : {}),
trigger,
activityEvents,
});
@@ -1110,7 +1146,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
text: workingText || '(no reply)',
...(form ? { form } : {}),
...(produced.length ? { produced } : {}),
- ...(createdAgent ? { createdAgent } : {}),
+ ...(createdAgents.length ? { createdAgents } : {}),
+ ...(createdSkills.length ? { createdSkills } : {}),
};
}
@@ -1195,7 +1232,10 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
text: outcome.text,
...(outcome.form ? { form: outcome.form } : {}),
...(outcome.produced && outcome.produced.length ? { produced: outcome.produced } : {}),
- ...(outcome.createdAgent ? { created_agent: outcome.createdAgent } : {}),
+ ...(outcome.createdAgents && outcome.createdAgents.length ? { created_agents: outcome.createdAgents } : {}),
+ ...(outcome.createdSkills && outcome.createdSkills.length
+ ? { created_skills: outcome.createdSkills.map((s) => ({ skill_id: s.skill_id, name: s.name })) }
+ : {}),
...(pendingPlan && actor.kind === 'commander'
? { plan_announcement: true, forceTo: [USER_ID] } : {}),
...(processItems.length ? { process: processItems } : {}),
@@ -1262,7 +1302,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
+ ` outcome=${outcome.kind}`
+ ` events=${activityEvents}`
+ (form ? ' form=1' : '')
- + (createdAgent ? ` created_agent=${createdAgent.agent_id}` : '')
+ + (createdAgents.length ? ` created_agents=${createdAgents.map(a => a.agent_id).join(',')}` : '')
+ + (createdSkills.length ? ` created_skills=${createdSkills.map(s => s.skill_id).join(',')}` : '')
+ (produced.length ? ` produced=${produced.length}` : '')
+ (item.triggered_step !== undefined ? ` step=${item.triggered_step}` : '')
+ (errText ? ` err=${errText}` : '')
diff --git a/src/main/features/group_chat/plan_executor.ts b/src/main/features/group_chat/plan_executor.ts
index 0b4c8e5b..3a9d7efd 100644
--- a/src/main/features/group_chat/plan_executor.ts
+++ b/src/main/features/group_chat/plan_executor.ts
@@ -122,12 +122,16 @@ export interface TurnFinishedEvent {
form?: ChatFormPayload;
/** Files written via local-exec tools during this turn. */
produced: string[];
- /** Agent created or updated from `<agent>...</agent>` (commander only).
- * `kind: 'created'` is the original quick-create flow; `kind: 'updated'`
- * means an existing custom agent was patched in place — same chip slot,
- * different label on the renderer side. Executor records but doesn't
- * drive on it. */
- createdAgent?: { agent_id: string; name: string; kind: 'created' | 'updated' };
+ /** Agents created or updated from `<agent>...</agent>` containers
+ * (commander only). One entry per successfully applied container.
+ * `kind: 'created'` is the quick-create flow; `kind: 'updated'` means an
+ * existing custom agent was patched. Executor records but doesn't drive
+ * on it. */
+ createdAgents?: Array<{ agent_id: string; name: string; kind: 'created' | 'updated' }>;
+ /** Skills created or updated from `<skill>...</skill>` containers
+ * (commander only). One entry per successfully applied container.
+ * Same shape as `createdAgents` entries; rendered as separate chips. */
+ createdSkills?: Array<{ skill_id: string; name: string; kind: 'created' | 'updated' }>;
/** What kind of trigger caused this turn. Drives the state transition. */
trigger: TurnTrigger;
/** Number of non-error, non-final, non-done events the LLM stream emitted.
@@ -146,7 +150,14 @@ export interface TurnFinishedEvent {
* turn produces no user-visible output.
*/
export type TurnOutcome =
- | { kind: 'persist'; text: string; form?: ChatFormPayload; produced?: string[]; createdAgent?: { agent_id: string; name: string; kind: 'created' | 'updated' } }
+ | {
+ kind: 'persist';
+ text: string;
+ form?: ChatFormPayload;
+ produced?: string[];
+ createdAgents?: Array<{ agent_id: string; name: string; kind: 'created' | 'updated' }>;
+ createdSkills?: Array<{ skill_id: string; name: string; kind: 'created' | 'updated' }>;
+ }
| { kind: 'silent' };
export interface ReconcileCtx {
@@ -331,7 +342,7 @@ async function outcomeForUserDirectTurn(uid: string, cid: string, evt: TurnFinis
// checking these signals first we'd fall through to the "agent empty"
// branch below and replace the actor's form with "(no reply)", losing
// the form widget entirely (the user-reported bug).
- const hasSideEffect = !!evt.form || !!evt.createdAgent || (evt.produced && evt.produced.length > 0);
+ const hasSideEffect = !!evt.form || (!!evt.createdAgents && evt.createdAgents.length > 0) || (!!evt.createdSkills && evt.createdSkills.length > 0) || (evt.produced && evt.produced.length > 0);
if ((evt.finalText && evt.finalText.trim()) || hasSideEffect) {
// When the stream errored mid-turn but partial text / side effects
// already landed, append the error pill instead of dropping the
@@ -345,7 +356,8 @@ async function outcomeForUserDirectTurn(uid: string, cid: string, evt: TurnFinis
text: body,
...(evt.form ? { form: evt.form } : {}),
...(evt.produced.length ? { produced: evt.produced } : {}),
- ...(evt.createdAgent ? { createdAgent: evt.createdAgent } : {}),
+ ...(evt.createdAgents && evt.createdAgents.length ? { createdAgents: evt.createdAgents } : {}),
+ ...(evt.createdSkills && evt.createdSkills.length ? { createdSkills: evt.createdSkills } : {}),
};
}
// Empty final, no side effects.
@@ -443,7 +455,8 @@ async function applyPlanStepTurn(
kind: 'persist',
text: evt.finalText,
...(evt.produced.length ? { produced: evt.produced } : {}),
- ...(evt.createdAgent ? { createdAgent: evt.createdAgent } : {}),
+ ...(evt.createdAgents && evt.createdAgents.length ? { createdAgents: evt.createdAgents } : {}),
+ ...(evt.createdSkills && evt.createdSkills.length ? { createdSkills: evt.createdSkills } : {}),
};
}
@@ -528,14 +541,15 @@ function errorBubble(msg: string): string {
*/
function abortOutcome(evt: TurnFinishedEvent): TurnOutcome {
const partial = (evt.finalText || '').trim();
- const hasSideEffect = !!evt.form || !!evt.createdAgent || (evt.produced && evt.produced.length > 0);
+ const hasSideEffect = !!evt.form || (!!evt.createdAgents && evt.createdAgents.length > 0) || (!!evt.createdSkills && evt.createdSkills.length > 0) || (evt.produced && evt.produced.length > 0);
if (!partial && !hasSideEffect) return { kind: 'silent' };
return {
kind: 'persist',
text: evt.finalText || '',
...(evt.form ? { form: evt.form } : {}),
...(evt.produced && evt.produced.length ? { produced: evt.produced } : {}),
- ...(evt.createdAgent ? { createdAgent: evt.createdAgent } : {}),
+ ...(evt.createdAgents && evt.createdAgents.length ? { createdAgents: evt.createdAgents } : {}),
+ ...(evt.createdSkills && evt.createdSkills.length ? { createdSkills: evt.createdSkills } : {}),
};
}
diff --git a/src/main/features/group_chat/router.ts b/src/main/features/group_chat/router.ts
index 163d68c0..7ac83274 100644
--- a/src/main/features/group_chat/router.ts
+++ b/src/main/features/group_chat/router.ts
@@ -402,3 +402,8 @@ export function encodeSubmission(
export type { ExtractedFields };
export { extractAgentFieldBlocks } from '../agents';
+
+// ── Skill-container parser (re-exported from features/skills) ────────────
+
+export type { SkillContainerExtracted, SkillContainerResult } from '../skills';
+export { extractSkillContainers } from '../skills';
diff --git a/src/main/features/group_chat/visibility.ts b/src/main/features/group_chat/visibility.ts
index 23de732b..9e3b7341 100644
--- a/src/main/features/group_chat/visibility.ts
+++ b/src/main/features/group_chat/visibility.ts
@@ -50,9 +50,13 @@ export interface GroupMessage {
/** Form widget payload — only on agent messages whose final text contained
* a fenced agent-input-form block. */
form?: import('./router').ChatFormPayload;
- /** Quick-created agent meta — only on commander messages whose final text
- * contained an `<agent>` container. */
- created_agent?: { agent_id: string; name: string };
+ /** Quick-created / quick-edited agent meta — populated when the commander's
+ * final text contained one or more `<agent>` containers. One entry per
+ * successfully applied container; failed applications are not recorded. */
+ created_agents?: Array<{ agent_id: string; name: string; kind?: 'created' | 'updated' }>;
+ /** Mirror of `created_agents` for skills — populated when the commander's
+ * final text contained one or more `<skill>` containers. */
+ created_skills?: Array<{ skill_id: string; name: string; kind?: 'created' | 'updated' }>;
/** Marks this message as a plan announcement (rendered with a folded
* plan card in UI). Set by `plan_set` first-time emission. */
plan_announcement?: boolean;
diff --git a/src/main/features/skills.ts b/src/main/features/skills.ts
index 00e39ad7..5a767018 100644
--- a/src/main/features/skills.ts
+++ b/src/main/features/skills.ts
@@ -45,6 +45,7 @@ import {
} from '../storage';
import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';
import { readDisabledSets, setSkillEnabled } from './component_enabled';
+import { findOuterTagRanges } from '../util/markdown-prose-code';
const SKILL_TREE_IGNORE: ReadonlySet<string> = new Set(['.DS_Store', '__pycache__', '.git', 'node_modules']);
// Starts with a letter, then letters/digits/_/-; single spaces are allowed
@@ -1041,6 +1042,189 @@ export function extractSkillFileBlocks(text: string): { cleanText: string; files
return { cleanText: compact, files };
}
+// ── Commander `<skill>` container ────────────────────────────────────────
+// Outer container the commander emits to create / patch a skill mid-turn
+// (parallel to `extractAgentFieldBlocks`). Only the inner `<<<skill-file>>>`
+// blocks are processed; stray blocks outside the container stay visible as
+// prose so the LLM gets feedback on its own malformed output rather than
+// silently writing files.
+//
+// **Prose/code guard**: `findOuterTagRanges` skips `<skill>` mentions that
+// fall inside fenced ``` code blocks or inline backtick spans, so an LLM
+// teaching the user the protocol (e.g. "the format is `<skill>...</skill>`"
+// or showing it in a fenced example) doesn't accidentally trigger a real
+// skill write. Same guard the renderer uses (`strip-structural-blocks.js`).
+const OPEN_TAG = '<skill>';
+const CLOSE_TAG = '</skill>';
+const SKILL_ID_RE = /<skill_id>\s*([\s\S]*?)\s*<\/skill_id>/;
+
+export interface SkillContainerExtracted {
+ /** Empty/undefined → create flow; non-empty → edit flow targeting this id. */
+ skillId?: string;
+ /** All `<<<skill-file>>>` blocks parsed from inside the container. */
+ files: SkillFileBlock[];
+}
+
+function _parseSkillContainer(inner: string): SkillContainerExtracted {
+ const idM = inner.match(SKILL_ID_RE);
+ const skillId = idM ? idM[1].trim() : '';
+ const { files } = extractSkillFileBlocks(inner);
+ return { ...(skillId ? { skillId } : {}), files };
+}
+
+/**
+ * Extract every `<skill>...</skill>` container in emission order. Each
+ * container is parsed independently. Returns `containers: []` when none
+ * is present.
+ *
+ * Containers inside fenced code blocks / inline backtick spans are
+ * NOT extracted (prose/code guard); unclosed containers (no `</skill>`
+ * before EOF — should not happen on final-event text but guarded
+ * defensively) are skipped from `containers` but stripped from
+ * `cleanText` so half-baked tokens don't leak into the bubble.
+ */
+export function extractSkillContainers(
+ text: string,
+): { cleanText: string; containers: SkillContainerExtracted[] } {
+ if (!text || text.indexOf(OPEN_TAG) < 0) return { cleanText: text, containers: [] };
+ const ranges = findOuterTagRanges(text, 'skill');
+ if (!ranges.length) return { cleanText: text, containers: [] };
+ const containers: SkillContainerExtracted[] = [];
+ let cleaned = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ cleaned += text.slice(cursor, s);
+ const block = text.slice(s, e);
+ if (block.startsWith(OPEN_TAG) && block.endsWith(CLOSE_TAG)) {
+ const inner = block.slice(OPEN_TAG.length, block.length - CLOSE_TAG.length);
+ containers.push(_parseSkillContainer(inner));
+ }
+ cursor = e;
+ }
+ cleaned += text.slice(cursor);
+ cleaned = cleaned.replace(/\n{3,}/g, '\n\n').trim();
+ return { cleanText: cleaned, containers };
+}
+
+export interface SkillContainerResult {
+ ok: boolean;
+ /** 'created' for the no-skill-id branch; 'updated' for the edit branch.
+ * Undefined on `ok: false`. */
+ kind?: 'created' | 'updated';
+ /** Resolved skill id after the operation — for `created`: the id we
+ * allocated; for `updated`: the post-rename id when SKILL.md frontmatter
+ * changed `name`, otherwise the original id. */
+ skillId?: string;
+ /** Display name from SKILL.md frontmatter (post-write). */
+ name?: string;
+ /** Paths successfully written, in container order. */
+ written?: string[];
+ /** Paths whose write was rejected (path-escape, missing dir, etc.). Never
+ * causes total failure — best-effort policy mirrors the skill-edit chat. */
+ rejected?: string[];
+ /** Total-failure cause when `ok: false`. Already localized via `t()`. */
+ error?: string;
+}
+
+/** Apply a parsed `<skill>` container from commander. Routes to create vs
+ * edit by `container.skillId`. Built-in skills are read-only here — same
+ * policy as the per-skill edit chat outside dev mode. Best-effort writes
+ * per-file: a single rejected path doesn't roll back earlier successes
+ * (matches `streamSendToSkillChat`'s file-by-file outcome). */
+export async function applySkillContainerFromCommander(
+ container: SkillContainerExtracted,
+): Promise<SkillContainerResult> {
+ if (!container.files.length && !container.skillId) {
+ return { ok: false, error: t('skills.errors.container_empty') };
+ }
+ if (container.skillId) {
+ return _applySkillContainerEdit(container.skillId, container.files);
+ }
+ return _applySkillContainerCreate(container.files);
+}
+
+async function _applySkillContainerCreate(files: SkillFileBlock[]): Promise<SkillContainerResult> {
+ // SKILL.md is mandatory in the create branch — that's where the skill id
+ // (frontmatter `name`) and bilingual descriptions are sourced from.
+ const skillMd = files.find((f) => f.path.toUpperCase() === 'SKILL.MD');
+ if (!skillMd) return { ok: false, error: t('skills.errors.create_missing_skill_md') };
+ const { meta } = splitSkillMd(skillMd.content || '');
+ const name = (meta.name || '').trim();
+ if (!name) return { ok: false, error: t('skills.errors.create_missing_name') };
+ const validateErr = validateSkillName(name);
+ if (validateErr) return { ok: false, error: validateErr };
+ // Collision checks — same gates as the IPC create path so commander and
+ // detail panel produce identical failure modes.
+ if (fs.existsSync(customSkillDir(name))) {
+ return { ok: false, error: t('skills.errors.skill_exists', { name }) };
+ }
+ if (fs.existsSync(path.join(BUILTIN_SKILLS_DIR, name))) {
+ return { ok: false, error: t('skills.errors.builtin_conflict', { name }) };
+ }
+ // Seed description from the frontmatter so the registry never sees a
+ // transient empty-description state between createCustomSkill (which
+ // writes boilerplate SKILL.md) and the SKILL.md block write below.
+ const desc = migrateDescriptionPair(meta as any);
+ const seedDescription = desc.description_zh || desc.description_en || '';
+ const created = await createCustomSkill(name, seedDescription);
+ if (!created) return { ok: false, error: t('skills.errors.create_failed') };
+
+ const written: string[] = [];
+ const rejected: string[] = [];
+ for (const fb of files) {
+ if (writeCustomSkillFile(name, fb.path, fb.content)) written.push(fb.path);
+ else rejected.push(fb.path);
+ }
+ if (written.length) log.info(`commander created skill=${name} files=${written.length}`);
+ return {
+ ok: true,
+ kind: 'created',
+ skillId: name,
+ name,
+ written,
+ ...(rejected.length ? { rejected } : {}),
+ };
+}
+
+async function _applySkillContainerEdit(skillId: string, files: SkillFileBlock[]): Promise<SkillContainerResult> {
+ const skill = await getSkillForEdit(skillId);
+ if (!skill) return { ok: false, error: t('skills.errors.skill_not_found', { id: skillId }) };
+ // Built-in skills are dev-mode-only via the detail-panel edit chat; the
+ // commander flow always rejects regardless of dev mode (mirrors the agent
+ // edit policy at `bus.ts` post-stream parsing).
+ if (skill.source !== 'custom') {
+ return { ok: false, error: t('errors.builtin_skill_not_editable') };
+ }
+ const written: string[] = [];
+ const rejected: string[] = [];
+ let touchedSkillMd = false;
+ for (const fb of files) {
+ if (await writeSkillFileForEdit(skillId, fb.path, fb.content)) {
+ written.push(fb.path);
+ if (fb.path.toUpperCase() === 'SKILL.MD') touchedSkillMd = true;
+ } else {
+ rejected.push(fb.path);
+ }
+ }
+ // Auto-rename when SKILL.md frontmatter `name` differs from the dir id —
+ // same hook as the per-skill edit chat (`streamSendToSkillChat`).
+ let resolvedId = skillId;
+ if (touchedSkillMd) {
+ const newId = await _renameSkillByFrontmatterIfNeeded(skillId);
+ if (newId && newId !== skillId) resolvedId = newId;
+ }
+ const post = await getSkillForEdit(resolvedId);
+ if (written.length) log.info(`commander updated skill=${skillId}${resolvedId !== skillId ? ` -> ${resolvedId}` : ''} files=${written.length}`);
+ return {
+ ok: true,
+ kind: 'updated',
+ skillId: resolvedId,
+ name: post?.name || resolvedId,
+ written,
+ ...(rejected.length ? { rejected } : {}),
+ };
+}
+
function skillFilesBlock(files: SkillFileInfo[]): string {
if (!files.length) return ' (empty)';
return files.map((f) => ` - ${f.path} (${f.bytes || 0} B)`).join('\n');
diff --git a/src/main/locales/en.json b/src/main/locales/en.json
index 4a2f0683..38bb8dd3 100644
--- a/src/main/locales/en.json
+++ b/src/main/locales/en.json
@@ -44,6 +44,10 @@
"skills.errors.builtin_conflict": "Skill name \"{name}\" conflicts with a built-in skill. Please choose another name.",
"skills.errors.url_scheme": "URL must start with http(s)://",
"skills.errors.create_failed": "Failed to create skill",
+ "skills.errors.container_empty": "Empty `<skill>` container — nothing to write",
+ "skills.errors.create_missing_skill_md": "Cannot create skill: missing SKILL.md block",
+ "skills.errors.create_missing_name": "Cannot create skill: SKILL.md frontmatter is missing the `name` field",
+ "skills.errors.skill_not_found": "Skill not found: {id}",
"skills.errors.path_not_absolute": "Please select an absolute-path directory",
"skills.errors.dir_inaccessible": "Directory is not accessible",
"skills.errors.path_not_dir": "Please select a directory (not a file)",
diff --git a/src/main/locales/zh.json b/src/main/locales/zh.json
index d30d58ee..ff2f6b3f 100644
--- a/src/main/locales/zh.json
+++ b/src/main/locales/zh.json
@@ -44,6 +44,10 @@
"skills.errors.builtin_conflict": "技能名「{name}」与内置技能冲突,请换一个名称",
"skills.errors.url_scheme": "URL 必须以 http(s):// 开头",
"skills.errors.create_failed": "创建技能失败",
+ "skills.errors.container_empty": "`<skill>` 容器为空,没有要写入的内容",
+ "skills.errors.create_missing_skill_md": "无法创建技能:缺少 SKILL.md 块",
+ "skills.errors.create_missing_name": "无法创建技能:SKILL.md 头部缺少 `name` 字段",
+ "skills.errors.skill_not_found": "技能不存在:{id}",
"skills.errors.path_not_absolute": "请选择一个绝对路径的目录",
"skills.errors.dir_inaccessible": "目录无法访问",
"skills.errors.path_not_dir": "请选择目录(不是文件)",
diff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.md
index aa4df548..ea9a62bd 100644
--- a/src/main/prompts/chat_commander.md
+++ b/src/main/prompts/chat_commander.md
@@ -220,7 +220,7 @@ plan_set({
## Creating or editing an agent
-Both flows emit ONE `<agent>...</agent>` container in this turn and end (do NOT call `dispatch_to`). The container shape is identical; whether the system creates a new agent or patches an existing one is decided by a single optional first child:
+Emit one `<agent>...</agent>` container per agent being created or edited this turn — typically one; emit several only when a single user request spans distinct agents (e.g. "tighten the workflow on A and B"). Each container is parsed and applied independently. End the turn after (do NOT call `dispatch_to`). The container shape is identical; whether the system creates a new agent or patches an existing one is decided by a single optional first child:
**Do NOT call `write_file` / `bash` to dump the `<agent>` container as a file** (e.g. `<name>-agent-definition.xml`). The container is a contract between the LLM and the server: the server parses the inline container in your reply and persists it to `agent.json`. An extra `write_file` only leaks an unused XML file into the user's workspace — there is no downstream consumer for it. Pitfall: this has already shipped a stray `GEO-agent-definition.xml` to the workspace once.
@@ -324,6 +324,76 @@ Pattern (also written in user UI language): briefly state what was crystallized,
---
+## Creating or editing a skill
+
+Emit one `<skill>...</skill>` container per skill being created or edited this turn — typically one; emit several only when a single user request spans distinct skills. Each container is parsed and applied independently. The container wraps an optional `<skill_id>` plus one or more `<<<skill-file>>>` blocks; the `<skill_id>` decides create vs edit. End the turn after (do NOT call `dispatch_to`).
+
+**Do NOT call `write_file` / `bash` to dump the container or any inner block as a file** — the server parses them inline and persists each block to `<skill_dir>/<path>`. An extra `write_file` only leaks an unused scratch file into the workspace.
+
+### When to create vs edit
+
+- **No `<skill_id>`** → create a brand-new skill. Triggered by "make / write me a skill that does X" / "把这个能力封装成 skill". The new skill's id comes from the SKILL.md frontmatter `name` field; you choose it.
+- **With `<skill_id>X</skill_id>`** → patch an existing custom skill X. Triggered when the user asks to adjust some specific skill — `X` MUST come from the `## Available skills` block; do NOT invent.
+
+### Quality bar (applies to both)
+
+> The skill detail panel hosts a dedicated edit chat that owns the long-form authoring rules for SKILL.md. The principles below are the shared subset every author must keep — the difference between a skill the LLM picks at runtime and one that's effectively dead.
+
+- **SKILL.md frontmatter has exactly three fields, all required**: `name`, `description_zh`, `description_en`. No `requires` / `external_deps` / `tags` / `version` / single-language `description`. External dependencies go in the body's "External dependencies" section as plain text.
+- **`name` is the skill id AND the directory name** — strict ASCII charset: letters / digits / `_` / `-` (single internal spaces between word groups allowed). No Chinese / pinyin / `.` / `/`. Pick a short descriptive English slug (e.g. `social-fetch`, `code-reviewer`). The validator rejects any other charset and the create fails. **`name` is NOT translated to the user's UI language** — it's an identifier, not display copy.
+- **`description_zh` + `description_en`** decide whether the LLM picks the skill at runtime. Write each independently in the **same three-part formula** described in the agent section above (① one-line function ; ② quoted real user phrasings ; ③ trigger keywords). Don't direct-translate.
+- **SKILL.md body** is API-doc style: when to use / how to call / return format / external dependencies / examples. **Prefer guide-type (no script)**: if the task can be done with main-conversation generic tools (file IO / `kb_search` / `web_fetch` / `bash` / etc.), the body lists 3–7 actionable steps and `scripts/` is empty. Add `scripts/<basename>.<ext>` ONLY when the task needs dedicated code (complex parsing / signature verification / third-party API state). Each skill stands alone — do NOT reference other skill ids inside the body.
+- **Script invocation template** (when you do write one): `$ORKAS_NODE $ORKAS_PC_DIR/bin/run-skill.cjs <skill-id> <basename> [-- args...]` (no `bash` prefix; the bash tool runs `command` itself). Default extension `.py` (also allowed: `.ts/.mjs/.js/.sh/.rb`); cross-platform required.
+
+### `<<<skill-file>>>` block + container format
+
+Each file under the skill directory is written via:
+
+```
+<<<skill-file path=<rel-path>
+…full file content…
+>>>
+```
+
+- `path=` is **relative to the skill directory** (e.g. `SKILL.md` / `scripts/fetch.py`); `..` and absolute paths are rejected.
+- Each block is a **whole-file replacement** of `path`; partial edits → read the file first, then write the full new version.
+- A single `<skill>` container may contain multiple blocks (SKILL.md + scripts + examples). Failures within one block do not roll back earlier successful writes; the rejected paths surface as an error pill in this turn's reply.
+
+Container shape:
+
+```
+<skill>
+<skill_id>(omit when creating; required when editing)</skill_id>
+<<<skill-file path=SKILL.md
+---
+name: short-ascii-id
+description_zh: ① 一句功能 ;② 适合"用户原话1""用户原话2";③ 触发词:词1、词2、…
+description_en: ① one-line function ; ② For: "user phrasing 1", "user phrasing 2" ; ③ Triggers: word1, word2, …
+---
+
+# Body sections per the Quality bar above
+>>>
+<<<skill-file path=scripts/<basename>.py
+…optional implementation script…
+>>>
+</skill>
+```
+
+### Editing an existing skill — required loop
+
+1. **Read the current SKILL.md** via the `read_file(<ROOT>/<id>/SKILL.md)` pattern in the `## Available skills` block header. Never rewrite from memory — `<<<skill-file>>>` is whole-file replacement; emitting a partial SKILL.md wipes the rest of the body.
+2. **If `Source: builtin`** → reply with one prose line in the user's UI language saying built-in skills can't be edited from the main conversation; the user can fork a custom copy from the detail panel. Then stop. **Do not emit `<skill>`**.
+3. **Emit `<skill>` with `<skill_id>` first**, then only the `<<<skill-file>>>` blocks you're changing. SKILL.md edits may change `name`; the system auto-renames the directory to match.
+
+### The conversation prose outside the container is what the user sees
+
+Talk about what the skill does / when it gets invoked / what you adjusted this round, in the user's UI language. **The conversation prose must NOT contain** any of: `frontmatter` / `description` field / `description_zh` / `description_en` / `<skill>` / `<skill_id>` / `<<<skill-file>>>` / "three-part formula" / "guide-type" / "executable" / id / hex strings.
+
+Wrong: "I wrote `SKILL.md` frontmatter with `description_zh` + `description_en` in three-part form."
+Right: "I wrote a skill `social-fetch` that scrapes posts on the platforms you mentioned and produces a sentiment summary. It gets invoked when you ask things like 分析一下小红书最近的 X 话题."
+
+---
+
## Resources you can use
### Knowledge base (KB)
diff --git a/src/main/util/markdown-prose-code.ts b/src/main/util/markdown-prose-code.ts
new file mode 100644
index 00000000..8f5b725b
--- /dev/null
+++ b/src/main/util/markdown-prose-code.ts
@@ -0,0 +1,168 @@
+// Backend port of the renderer's `_splitMarkdownProseCode` +
+// `_findOuterTagRanges` (lives in `src/renderer/modules/strip-structural-blocks.js`).
+// Used to give the post-stream container extractors (`<skill>` here, and
+// long-term `<agent>` once that flow's WIP refactor settles) a prose/code
+// guard: an LLM mentioning `<skill>` inside a fenced ``` block or inline
+// backtick span (e.g., teaching the user the protocol) must NOT cause
+// the backend to falsely "extract" the example as a real container and
+// persist nonexistent files.
+//
+// Logic mirror is intentional — the renderer already pins set A / set B
+// fixtures (`test/renderer/strip-structural-blocks.test.ts`); the backend port has
+// its own fixtures (`test/main/util/markdown-prose-code.test.ts`) that
+// cross-check the same shapes against this TS implementation. Both
+// copies must stay in sync; if you change one, change the other and
+// extend BOTH fixture sets.
+//
+// Why duplicated rather than shared: renderer is vanilla JS without
+// imports (PC/CLAUDE.md §8); main is TS with strict layering (§3, no
+// renderer imports). The pure logic is small (~80 lines) and the cost
+// of two copies + a sync convention is lower than introducing a build
+// step or a cross-layer require.
+
+export interface ProseCodeSegment {
+ kind: 'prose' | 'code';
+ text: string;
+}
+
+/** Split a markdown buffer into alternating prose / code segments. "Code" =
+ * fenced ``` / ~~~ blocks (≤3-space indent, info-string allowed) plus
+ * inline backtick spans; everything else is prose. Mid-stream unclosed
+ * fences and unclosed inline backticks are treated as code through
+ * end-of-buffer, matching the renderer's behavior. */
+export function splitMarkdownProseCode(text: string): ProseCodeSegment[] {
+ const segs: ProseCodeSegment[] = [];
+ if (!text) return segs;
+ const n = text.length;
+ let proseStart = 0;
+ const flushProse = (end: number) => {
+ if (end > proseStart) segs.push({ kind: 'prose', text: text.slice(proseStart, end) });
+ };
+ let i = 0;
+ while (i < n) {
+ const lineStart = i === 0 || text[i - 1] === '\n';
+ if (lineStart) {
+ let j = i;
+ let indent = 0;
+ while (indent < 3 && text[j] === ' ') { j++; indent++; }
+ const ch = text[j];
+ if (ch === '`' || ch === '~') {
+ let count = 0;
+ while (text[j + count] === ch) count++;
+ if (count >= 3) {
+ let k = j + count;
+ while (k < n && text[k] !== '\n') k++;
+ let scan = k < n ? k + 1 : n;
+ let close = -1;
+ while (scan < n) {
+ let s = scan;
+ let pad = 0;
+ while (pad < 3 && text[s] === ' ') { s++; pad++; }
+ if (text[s] === ch) {
+ let cc = 0;
+ while (text[s + cc] === ch) cc++;
+ if (cc >= count) {
+ let lineEnd = s + cc;
+ while (lineEnd < n && text[lineEnd] !== '\n') lineEnd++;
+ close = lineEnd;
+ break;
+ }
+ }
+ while (scan < n && text[scan] !== '\n') scan++;
+ if (scan < n) scan++;
+ }
+ flushProse(i);
+ const endIdx = close >= 0 ? close : n;
+ segs.push({ kind: 'code', text: text.slice(i, endIdx) });
+ proseStart = endIdx;
+ i = endIdx;
+ continue;
+ }
+ }
+ }
+ if (text[i] === '`') {
+ let count = 0;
+ while (text[i + count] === '`') count++;
+ let j = i + count;
+ let close = -1;
+ while (j < n) {
+ if (text[j] === '`') {
+ let cc = 0;
+ while (text[j + cc] === '`') cc++;
+ if (cc === count) { close = j + cc; break; }
+ j += cc;
+ } else {
+ j++;
+ }
+ }
+ if (close > 0) {
+ flushProse(i);
+ segs.push({ kind: 'code', text: text.slice(i, close) });
+ proseStart = close;
+ i = close;
+ continue;
+ }
+ flushProse(i);
+ segs.push({ kind: 'code', text: text.slice(i, n) });
+ proseStart = n;
+ i = n;
+ continue;
+ }
+ i++;
+ }
+ flushProse(n);
+ return segs;
+}
+
+/** Find every `<TAG>...</TAG>` (or unclosed `<TAG>...EOF`) range whose
+ * OPENING tag falls in an outer prose segment. The tagged container is
+ * treated as one atomic unit — once the opening tag is in prose, we walk
+ * to the matching `</TAG>` (or EOF) regardless of what's inside, so
+ * backticks / fences / quotes authored inside the body don't fragment
+ * the container. Boundary check (next char must be `>`, whitespace, or
+ * `/`) keeps `<skill>` lookup from also matching `<skills>` and similar
+ * same-prefix siblings.
+ *
+ * Mirror of renderer's `_findOuterTagRanges` (`strip-structural-blocks.js`); see
+ * module header for the sync convention. */
+export function findOuterTagRanges(text: string, tagName: string): Array<[number, number]> {
+ if (!text || !tagName) return [];
+ const openLeader = `<${tagName}`;
+ const closeLiteral = `</${tagName}>`;
+ if (text.indexOf(openLeader) < 0) return [];
+ const segs = splitMarkdownProseCode(text);
+ const ranges: Array<[number, number]> = [];
+ let pos = 0;
+ for (const seg of segs) {
+ const segStart = pos;
+ pos += seg.text.length;
+ if (seg.kind !== 'prose') continue;
+ let from = segStart;
+ while (from < pos) {
+ const last = ranges.length ? ranges[ranges.length - 1] : null;
+ if (last && from < last[1]) from = last[1];
+ if (from >= pos) break;
+ const openIdx = text.indexOf(openLeader, from);
+ if (openIdx < 0 || openIdx >= pos) break;
+ const next = text.charCodeAt(openIdx + openLeader.length);
+ const isBoundary = next === 62 /* > */ || next === 32 /* space */
+ || next === 9 /* \t */ || next === 10 /* \n */ || next === 13 /* \r */
+ || next === 47 /* / */;
+ if (!isBoundary) {
+ from = openIdx + openLeader.length;
+ continue;
+ }
+ const tagEnd = text.indexOf('>', openIdx + openLeader.length);
+ if (tagEnd < 0) {
+ ranges.push([openIdx, text.length]);
+ from = text.length;
+ break;
+ }
+ const closeIdx = text.indexOf(closeLiteral, tagEnd + 1);
+ const endPos = closeIdx < 0 ? text.length : closeIdx + closeLiteral.length;
+ ranges.push([openIdx, endPos]);
+ from = endPos;
+ }
+ }
+ return ranges;
+}
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 4abee743..8d1e4d12 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -744,7 +744,7 @@
<script src="./modules/avatar-picker.js"></script>
<script src="./modules/chat-input-form.js"></script>
<script src="./modules/chat-lightbox.js"></script>
- <script src="./modules/strip-agent.js"></script>
+ <script src="./modules/strip-structural-blocks.js"></script>
<script src="./modules/conversation.js"></script>
<script src="./modules/plan-rail.js"></script>
<script src="./modules/queue-draft.js"></script>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 0d4d9ee3..71485296 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -157,9 +157,11 @@
"chat.create_agent_btn": "Create agent",
"chat.create_agent_inline": "Distill the above into an agent",
"chat.create_agent_message": "Distill the conversation above into a new agent.",
- "chat.created_agent_chip": "Open: {name}",
+ "chat.created_agent_chip": "Open agent: {name}",
+ "chat.created_skill_chip": "Open skill: {name}",
"chat.create_agent_failed": "Failed to create agent: {reason}",
"chat.create_agent_streaming_placeholder": "Assembling agent config…",
+ "chat.create_skill_streaming_placeholder": "Assembling skill files…",
"chat.skill_file_streaming_placeholder": "Writing {path}…",
"chat.skill_file_streaming_placeholder_unknown": "Writing file…",
"skills.title": "Skills",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index c1a2d821..17992a42 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -157,9 +157,11 @@
"chat.create_agent_btn": "创建智能体",
"chat.create_agent_inline": "把以上对话沉淀为智能体",
"chat.create_agent_message": "帮我把以上对话整理成一个新的智能体。",
- "chat.created_agent_chip": "查看详情:{name}",
+ "chat.created_agent_chip": "查看智能体:{name}",
+ "chat.created_skill_chip": "查看技能:{name}",
"chat.create_agent_failed": "智能体创建失败:{reason}",
"chat.create_agent_streaming_placeholder": "正在整理智能体配置…",
+ "chat.create_skill_streaming_placeholder": "正在整理技能配置…",
"chat.skill_file_streaming_placeholder": "正在写入 {path}…",
"chat.skill_file_streaming_placeholder_unknown": "正在写入文件…",
"skills.title": "技能库",
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index dcfd3300..af0c2e57 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -606,6 +606,22 @@ async function _refreshGroupMembers(cid) {
} catch (_) { /* non-fatal */ }
return _groupMembersCache.get(cid) || [];
}
+// Read-side normalizer: jsonl records written before the multi-edit
+// migration carry singular `created_agent`; new ones carry plural
+// `created_agents`. Returns the array, or `null` when neither field is set.
+function _normalizeCreatedAgents(gm) {
+ if (!gm) return null;
+ if (Array.isArray(gm.created_agents) && gm.created_agents.length) return gm.created_agents;
+ if (gm.created_agent && gm.created_agent.agent_id) return [gm.created_agent];
+ return null;
+}
+function _normalizeCreatedSkills(gm) {
+ if (!gm) return null;
+ if (Array.isArray(gm.created_skills) && gm.created_skills.length) return gm.created_skills;
+ if (gm.created_skill && gm.created_skill.skill_id) return [gm.created_skill];
+ return null;
+}
+
function _groupMsgToLegacy(gm) {
if (!gm || typeof gm !== 'object') return gm;
if (gm.role !== undefined) return gm; // already legacy shape
@@ -629,7 +645,8 @@ function _groupMsgToLegacy(gm) {
...(Array.isArray(gm.attachments) && gm.attachments.length ? { attachments: gm.attachments } : {}),
...(Array.isArray(gm.produced) && gm.produced.length ? { produced: gm.produced } : {}),
...(gm.form ? { form: gm.form } : {}),
- ...(gm.created_agent ? { created_agent: gm.created_agent } : {}),
+ ...(_normalizeCreatedAgents(gm) ? { created_agents: _normalizeCreatedAgents(gm) } : {}),
+ ...(_normalizeCreatedSkills(gm) ? { created_skills: _normalizeCreatedSkills(gm) } : {}),
...(gm.plan_announcement ? { _plan_announcement: true } : {}),
...(Array.isArray(gm.process) && gm.process.length ? { process: gm.process } : {}),
};
@@ -956,36 +973,70 @@ function _renderMessageProducedHtml(absPaths) {
return `<div class="chat-msg-produced">${items.join('')}</div>`;
}
-// Render a "view details" chip on an assistant bubble when a new agent was
-// quick-created from that turn. Click → jump to agents tab + select the new
-// agent. Same visual slot as produced chips (inside the bubble, below
-// content), but in .is-custom green to signal "new custom artifact created".
-function _renderMessageCreatedAgentHtml(payload) {
- if (!payload || !payload.agent_id) return '';
- const name = payload.name || payload.agent_id;
- // Label is intentionally neutral ("view details / Open: …") — works for both
- // `kind: 'created'` and `kind: 'updated'`; the commander's surrounding
- // prose tells the user which one happened. Don't split the i18n key just
- // to track the verb — the chip is a CTA into the agent panel, not a
- // status badge.
- return `<div class="chat-msg-created-agent">
- <span class="chat-msg-created-agent-chip" data-agent-id="${escapeHtml(payload.agent_id)}" title="${escapeHtml(name)}">
+// Render one or more "view details" chips on an assistant bubble — one chip
+// per agent quick-created or quick-edited in that turn. Same visual slot as
+// produced chips (inside the bubble, below content), in .is-custom green.
+// Label is neutral ("view details") for both `kind: 'created'` and
+// `kind: 'updated'`; the commander's surrounding prose tells the user which.
+function _renderMessageCreatedAgentHtml(list) {
+ const arr = Array.isArray(list) ? list : (list ? [list] : []);
+ const chips = arr
+ .filter((p) => p && p.agent_id)
+ .map((p) => {
+ const name = p.name || p.agent_id;
+ return `<span class="chat-msg-created-agent-chip" data-agent-id="${escapeHtml(p.agent_id)}" title="${escapeHtml(name)}">
<span class="chat-msg-created-agent-icon">◆</span>
<span class="chat-msg-created-agent-label">${escapeHtml(t('chat.created_agent_chip', { name }))}</span>
- </span>
- </div>`;
+ </span>`;
+ })
+ .join('');
+ return chips ? `<div class="chat-msg-created-agent">${chips}</div>` : '';
}
function _hydrateMessageCreatedAgentChip(msgDiv) {
- const chip = msgDiv.querySelector('.chat-msg-created-agent-chip');
- if (!chip) return;
- chip.addEventListener('click', () => {
- const aid = chip.dataset.agentId;
- if (!aid) return;
- setView('agents');
- if (typeof _showAgentsDetailView === 'function') _showAgentsDetailView(aid);
- else if (typeof selectAgent === 'function') selectAgent(aid);
- });
+ const chips = msgDiv.querySelectorAll('.chat-msg-created-agent-chip');
+ for (const chip of chips) {
+ if (chip.dataset.bound === '1') continue;
+ chip.dataset.bound = '1';
+ chip.addEventListener('click', () => {
+ const aid = chip.dataset.agentId;
+ if (!aid) return;
+ setView('agents');
+ if (typeof _showAgentsDetailView === 'function') _showAgentsDetailView(aid);
+ else if (typeof selectAgent === 'function') selectAgent(aid);
+ });
+ }
+}
+
+// Skill mirror of the agent chip. Commander writes only custom skills,
+// so the chip always opens the custom-source detail view.
+function _renderMessageCreatedSkillHtml(list) {
+ const arr = Array.isArray(list) ? list : (list ? [list] : []);
+ const chips = arr
+ .filter((p) => p && p.skill_id)
+ .map((p) => {
+ const name = p.name || p.skill_id;
+ return `<span class="chat-msg-created-agent-chip" data-skill-id="${escapeHtml(p.skill_id)}" title="${escapeHtml(name)}">
+ <span class="chat-msg-created-agent-icon">◆</span>
+ <span class="chat-msg-created-agent-label">${escapeHtml(t('chat.created_skill_chip', { name }))}</span>
+ </span>`;
+ })
+ .join('');
+ return chips ? `<div class="chat-msg-created-agent">${chips}</div>` : '';
+}
+
+function _hydrateMessageCreatedSkillChip(msgDiv) {
+ const chips = msgDiv.querySelectorAll('.chat-msg-created-agent-chip[data-skill-id]');
+ for (const chip of chips) {
+ if (chip.dataset.bound === '1') continue;
+ chip.dataset.bound = '1';
+ chip.addEventListener('click', () => {
+ const sid = chip.dataset.skillId;
+ if (!sid) return;
+ setView('skills');
+ if (typeof _showSkillsDetailView === 'function') _showSkillsDetailView('custom', sid);
+ });
+ }
}
function _hydrateMessageProducedChips(msgDiv) {
@@ -1442,7 +1493,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
// stored raw text. Assistant messages get a defensive structural-block
// strip covering `<agent>` / `<agent-input-form>` / `<agent-input-submission>`
// in case the backend's extractor missed a format variant (see
- // `_stripSurvivingStructuralBlocks` in strip-agent.js).
+ // `_stripSurvivingStructuralBlocks` in strip-structural-blocks.js).
let displayContent = rawContent;
if (!isHtmlSnippet) {
if (role === 'user') displayContent = _stripSubmissionTagForDisplay(rawContent);
@@ -1458,8 +1509,13 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
const producedHtml = (role === 'assistant' && Array.isArray(message.produced) && message.produced.length)
? _renderMessageProducedHtml(message.produced)
: '';
- const createdAgentHtml = (role === 'assistant' && message.created_agent)
- ? _renderMessageCreatedAgentHtml(message.created_agent)
+ const createdAgentsList = role === 'assistant' ? _normalizeCreatedAgents(message) : null;
+ const createdAgentHtml = createdAgentsList
+ ? _renderMessageCreatedAgentHtml(createdAgentsList)
+ : '';
+ const createdSkillsList = role === 'assistant' ? _normalizeCreatedSkills(message) : null;
+ const createdSkillHtml = createdSkillsList
+ ? _renderMessageCreatedSkillHtml(createdSkillsList)
: '';
// Group-chat header sits **above** the bubble, outside it: sender name +
// timestamp on one row. Same DOM strip for historical (loaded via
@@ -1487,7 +1543,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
msgDiv.innerHTML = `
${headerHtml}
<div class="chat-bubble">${planAnnHtml}${contentHtml}${attachmentsHtml}</div>
- <div class="chat-msg-actions" data-role="msg-actions">${producedHtml}${createdAgentHtml}</div>
+ <div class="chat-msg-actions" data-role="msg-actions">${producedHtml}${createdAgentHtml}${createdSkillHtml}</div>
`;
if (typeof opts.msgIndex === 'number') msgDiv.dataset.msgIndex = String(opts.msgIndex);
if (message._msg_id) msgDiv.dataset.msgId = String(message._msg_id);
@@ -1509,6 +1565,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
if (attachmentsHtml) _hydrateMessageAttachmentThumbs(msgDiv, opts.cid || currentCid);
if (producedHtml) _hydrateMessageProducedChips(msgDiv);
if (createdAgentHtml) _hydrateMessageCreatedAgentChip(msgDiv);
+ if (createdSkillHtml) _hydrateMessageCreatedSkillChip(msgDiv);
// Interactive input-form widget (assistant messages only). Appended inside
// the bubble after markdown + chips so it reads as "reply text → confirm
// this form". See chat-input-form.js for the widget implementation.
@@ -2999,10 +3056,11 @@ function _handleStreamEvent(cid, msg, ev, { archive = false } = {}) {
_mountChatInputForm(host, msg, { role: 'assistant', form: ev.form }, { cid });
}
}
- // Created-agent chip also arrives on the final event payload — attach
+ // Created-agent chips also arrive on the final event payload — attach
// here in case the relay event was missed (e.g. on reconnect / replay).
- if (ev.created_agent && ev.created_agent.agent_id) {
- _mountCreatedAgentChip(msg, ev.created_agent);
+ const finalCreated = _normalizeCreatedAgents(ev);
+ if (finalCreated) {
+ for (const payload of finalCreated) _mountCreatedAgentChip(msg, payload);
}
} else if (ev.type === 'error') {
_streamingSetError(msg, ev.text);
@@ -3156,9 +3214,15 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
ph.dataset.produced = JSON.stringify(gm.produced);
}
- // Created-agent chip (commander quick-create) — same actions row.
- if (gm.created_agent && gm.created_agent.agent_id) {
- _mountCreatedAgentChip(ph, gm.created_agent);
+ // Created-agent chips (commander quick-create / quick-edit) — same actions row.
+ const gmCreated = _normalizeCreatedAgents(gm);
+ if (gmCreated) {
+ for (const payload of gmCreated) _mountCreatedAgentChip(ph, payload);
+ }
+ // Created-skill chip (commander skill create / edit).
+ const gmSkills = _normalizeCreatedSkills(gm);
+ if (gmSkills) {
+ for (const payload of gmSkills) _mountCreatedSkillChip(ph, payload);
}
// Form widget (agent → user input form).
@@ -3395,14 +3459,11 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
}
}
-// Append the "view details" chip into a streaming bubble. Idempotent: duplicate
-// calls (relay event + final-event payload) are de-duped by checking for an
-// existing `.chat-msg-created-agent` child.
+// Append a "view details" chip into a streaming bubble. Idempotent per
+// agent_id — repeat calls for the same id no-op; calls for different ids
+// accumulate into the same `.chat-msg-created-agent` row.
function _mountCreatedAgentChip(msg, payload) {
if (!msg || !payload || !payload.agent_id) return;
- // Chip lives in the below-bubble action row alongside produced files +
- // archive button (same visual footer slot). Lazily allocate the row
- // for streaming placeholders that didn't get one at creation.
let actionsRow = msg.querySelector('[data-role="msg-actions"]');
if (!actionsRow) {
actionsRow = document.createElement('div');
@@ -3410,18 +3471,58 @@ function _mountCreatedAgentChip(msg, payload) {
actionsRow.dataset.role = 'msg-actions';
msg.appendChild(actionsRow);
}
- if (actionsRow.querySelector('.chat-msg-created-agent')) return;
- const wrap = document.createElement('div');
- wrap.innerHTML = _renderMessageCreatedAgentHtml(payload);
- const node = wrap.firstElementChild;
- if (!node) return;
- actionsRow.appendChild(node);
+ const aid = payload.agent_id;
+ if (actionsRow.querySelector(`.chat-msg-created-agent-chip[data-agent-id="${CSS.escape(aid)}"]`)) return;
+ let wrap = actionsRow.querySelector('.chat-msg-created-agent');
+ if (!wrap) {
+ wrap = document.createElement('div');
+ wrap.className = 'chat-msg-created-agent';
+ actionsRow.appendChild(wrap);
+ }
+ // Render an array of one + extract the inner chip(s) so we append into
+ // the existing wrap rather than nesting `.chat-msg-created-agent` rows.
+ const tmp = document.createElement('div');
+ tmp.innerHTML = _renderMessageCreatedAgentHtml([payload]);
+ const newChips = tmp.querySelectorAll('.chat-msg-created-agent-chip');
+ for (const chip of newChips) wrap.appendChild(chip);
_hydrateMessageCreatedAgentChip(msg);
// Refresh the agents-cache lazily so the user sees the new agent in the
// sidebar list when they jump over. Non-fatal if it fails.
try { if (typeof loadAgents === 'function') loadAgents(true); } catch (_) {}
}
+// Skill mirror of `_mountCreatedAgentChip`. Idempotent per skill_id;
+// repeat calls for the same id no-op, calls for different ids accumulate
+// into the same chip row. Skill chips and agent chips share CSS but are
+// distinguished by `data-agent-id` vs `data-skill-id`, so they coexist in
+// separate `.chat-msg-created-agent` wrappers.
+function _mountCreatedSkillChip(msg, payload) {
+ if (!msg || !payload || !payload.skill_id) return;
+ let actionsRow = msg.querySelector('[data-role="msg-actions"]');
+ if (!actionsRow) {
+ actionsRow = document.createElement('div');
+ actionsRow.className = 'chat-msg-actions';
+ actionsRow.dataset.role = 'msg-actions';
+ msg.appendChild(actionsRow);
+ }
+ const sid = payload.skill_id;
+ if (actionsRow.querySelector(`.chat-msg-created-agent-chip[data-skill-id="${CSS.escape(sid)}"]`)) return;
+ // Find or create a wrapper that already holds skill chips. `:has(...)`
+ // keeps us from accidentally appending into the agent-chip wrapper.
+ let wrap = actionsRow.querySelector('.chat-msg-created-agent:has(.chat-msg-created-agent-chip[data-skill-id])');
+ if (!wrap) {
+ wrap = document.createElement('div');
+ wrap.className = 'chat-msg-created-agent';
+ actionsRow.appendChild(wrap);
+ }
+ const tmp = document.createElement('div');
+ tmp.innerHTML = _renderMessageCreatedSkillHtml([payload]);
+ const newChips = tmp.querySelectorAll('.chat-msg-created-agent-chip');
+ for (const chip of newChips) wrap.appendChild(chip);
+ _hydrateMessageCreatedSkillChip(msg);
+ try { if (typeof loadSkills === 'function') loadSkills(true); } catch (_) {}
+}
+
// Hide the `<agent-input-submission form_id=... agent_id=...>{json}
// </agent-input-submission>` XML tag from a user message body at render
// time. The tag is required in the stored raw text so the LLM can parse
@@ -3429,7 +3530,7 @@ function _mountCreatedAgentChip(msg, payload) {
// bulleted summary above it already tells them what they confirmed.
function _stripSubmissionTagForDisplay(text) {
if (!text || text.indexOf('<agent-input-submission') < 0) return text;
- // Atomic-container strip with prose/code guard via strip-agent.js.
+ // Atomic-container strip with prose/code guard via strip-structural-blocks.js.
// Same class of fragmentation / set-B leak as `<agent>` — see that
// file's header for the invariant matrix.
const out = _stripOuterTagBlocks(text, 'agent-input-submission');
@@ -3438,9 +3539,9 @@ function _stripSubmissionTagForDisplay(text) {
}
// `_splitMarkdownProseCode`, `_findOuterAgentRanges`, `_stripSurvivingAgentBlocks`,
-// `_replaceOuterAgentBlocks` are defined in `./strip-agent.js` (loaded earlier
+// `_replaceOuterAgentBlocks` are defined in `./strip-structural-blocks.js` (loaded earlier
// in `index.html`). They live in their own file so vitest can pin the set-A /
-// set-B fixtures (`test/renderer/strip-agent.test.ts`) — see that file for
+// set-B fixtures (`test/renderer/strip-structural-blocks.test.ts`) — see that file for
// the invariant matrix. Wrap the i18n-aware placeholder here and delegate.
//
// Wrap placeholder text in an HTML `<em>` instead of markdown `_text_`:
@@ -3458,7 +3559,7 @@ function _stripAgentCreateBlocksForStream(buf) {
}
// `<<<skill-file path=X ... >>>` blocks (skill edit chat). Different fence
-// shape from `<agent>` (see strip-agent.js header) but same user-facing
+// shape from `<agent>` (see strip-structural-blocks.js header) but same user-facing
// contract: streaming placeholder hides the raw block + reveals the file
// being written. The path attribute (when present) flows into the
// localised "Writing X…" label so the placeholder is informative;
@@ -3472,6 +3573,20 @@ function _stripSkillFileBlocksForStream(buf) {
});
}
+// `<skill>` container (commander create / edit). Pure logic lives in
+// `strip-structural-blocks.js::_stripSkillCreateContainer` — see that header for the
+// closed-vs-unclosed mode rules. This wrapper only builds the i18n-aware
+// fallback placeholder and delegates so DOM / i18n / escapeHtml stay out
+// of the pure-function module (parallel to how `_stripAgentCreateBlocksForStream`
+// composes `_replaceOuterAgentBlocks`). Set A / set B fixtures pinned in
+// `test/renderer/strip-structural-blocks.test.ts`.
+function _stripSkillCreateBlocksForStream(buf) {
+ return _stripSkillCreateContainer(
+ buf,
+ _streamPlaceholderHtml('chat.create_skill_streaming_placeholder'),
+ );
+}
+
function _stripAgentFormBlockForStream(buf) {
// Primary: XML `<agent-input-form>...</agent-input-form>` (symmetric
// with submission reply tag, token-stable). Legacy: fenced
@@ -3481,7 +3596,7 @@ function _stripAgentFormBlockForStream(buf) {
// actual form widget.
if (!buf) return buf;
const placeholder = _streamPlaceholderHtml('chat.form.streaming_placeholder');
- // XML branch: atomic-container handling via strip-agent.js — same
+ // XML branch: atomic-container handling via strip-structural-blocks.js — same
// prose/code guard as `<agent>` so a fenced ```xml example or inline
// backtick mention of `<agent-input-form>` survives instead of being
// eaten as a real form.
@@ -3531,9 +3646,11 @@ function _streamingAppendFinalDelta(msg, piece) {
msg._streamRafScheduled = false;
msg._streamRafHandle = null;
const buf = msg.dataset.streamBuf || '';
- const display = _stripAgentCreateBlocksForStream(
- _stripAgentFormBlockForStream(
- _stripSkillFileBlocksForStream(buf),
+ const display = _stripSkillCreateBlocksForStream(
+ _stripAgentCreateBlocksForStream(
+ _stripAgentFormBlockForStream(
+ _stripSkillFileBlocksForStream(buf),
+ ),
),
);
finalEl.innerHTML = `<div class="markdown-body">${_renderMessageMarkdown(display)}</div>`;
diff --git a/src/renderer/modules/strip-structural-blocks.js b/src/renderer/modules/strip-structural-blocks.js
new file mode 100644
index 00000000..ce9b2a51
--- /dev/null
+++ b/src/renderer/modules/strip-structural-blocks.js
@@ -0,0 +1,427 @@
+// Pure string functions for atomic-container stripping of LLM-emitted
+// structural blocks surfacing in renderer text. Two delimiter families,
+// both Agent and Skill flows:
+//
+// **XML-tag containers** (handled via `tagName` parameter):
+// - `<agent>` — commander create / edit agent container
+// - `<agent-input-form>` — agent's form widget (streaming placeholder)
+// - `<agent-input-submission>` — user form-reply tag (display strip)
+// - `<skill>` — commander create / edit skill container
+// (`_stripSkillCreateContainer`: closed →
+// strip outer + `<skill_id>`, keep inner
+// per-file placeholders; unclosed → fallback)
+//
+// **Custom-fence blocks** (`<<<delim ... \n>>>`):
+// - `<<<skill-file path=X ... >>>` — file-write block, used by BOTH the
+// per-skill edit chat AND the commander's `<skill>` container body.
+//
+// The two families coexist because their **content shapes differ**: XML-tag
+// containers wrap structured LLM-generated prose (sub-fields like
+// `<workflow>` / `<inputs>` / `<skill_id>`) and balanced-tag parsing is the
+// natural fit; the skill-file block wraps **arbitrary file content**
+// (Python, TypeScript, HTML, JSX, configs) that routinely contains naked
+// `<` / `>` characters, so a literal three-char fence is required to avoid
+// colliding with body content. Same justification as the LLM-side prompts
+// (`chat_agent_setup.md` / `chat_commander.md` chose XML for `<agent>` / `<skill>`,
+// `chat_skill_setup.md` chose `<<<>>>` for file blocks).
+//
+// Both families share the same prose/code guard — if any of them is
+// mentioned literally inside a fenced code block or inline backtick span
+// (e.g., a protocol explanation), the literal mention must survive; the
+// real container must still be stripped/replaced atomically even when its
+// body contains backticks / fences / quotes (otherwise the prose/code split
+// fragments the container and the post-fragment suffix leaks past — the
+// 34e27fcb / a3110e61 / follow-up cycle on `<agent>`).
+//
+// Lives in a standalone file so vitest can `require()` it under Node and
+// pin the set-A vs set-B invariants — regressions in this category aren't
+// catchable by typecheck or eyeball review. Matching test file:
+// `test/renderer/strip-structural-blocks.test.ts`.
+//
+// CommonJS-export tail at the bottom is the ONLY allowed escape from the
+// renderer's "no export/import" rule (PC/CLAUDE.md §8) — it's guarded by
+// `typeof module`, evaluates to a no-op in the browser (where `module` is
+// undefined), and is purely a test bridge for pure functions. Don't
+// extend this convention to non-pure renderer code.
+
+// Split a markdown buffer into alternating prose / code segments. "Code" =
+// fenced ``` / ~~~ blocks (≤3-space indent, info-string allowed) plus inline
+// backtick spans; everything else is prose. Used by the `<agent>` container
+// strippers so coding scenarios — where the LLM legitimately quotes `<agent>`
+// inside a code sample to explain how this app's structured-output protocol
+// works — don't see the bubble silently truncated. Mid-stream unclosed fences
+// and unclosed inline backticks are treated as code through end-of-buffer,
+// matching how the markdown renderer would paint them.
+function _splitMarkdownProseCode(text) {
+ const segs = [];
+ if (!text) return segs;
+ const n = text.length;
+ let proseStart = 0;
+ const flushProse = (end) => {
+ if (end > proseStart) segs.push({ kind: 'prose', text: text.slice(proseStart, end) });
+ };
+ let i = 0;
+ while (i < n) {
+ const lineStart = i === 0 || text[i - 1] === '\n';
+ if (lineStart) {
+ let j = i;
+ let indent = 0;
+ while (indent < 3 && text[j] === ' ') { j++; indent++; }
+ const ch = text[j];
+ if (ch === '`' || ch === '~') {
+ let count = 0;
+ while (text[j + count] === ch) count++;
+ if (count >= 3) {
+ let k = j + count;
+ while (k < n && text[k] !== '\n') k++;
+ let scan = k < n ? k + 1 : n;
+ let close = -1;
+ while (scan < n) {
+ let s = scan;
+ let pad = 0;
+ while (pad < 3 && text[s] === ' ') { s++; pad++; }
+ if (text[s] === ch) {
+ let cc = 0;
+ while (text[s + cc] === ch) cc++;
+ if (cc >= count) {
+ let lineEnd = s + cc;
+ while (lineEnd < n && text[lineEnd] !== '\n') lineEnd++;
+ close = lineEnd;
+ break;
+ }
+ }
+ while (scan < n && text[scan] !== '\n') scan++;
+ if (scan < n) scan++;
+ }
+ flushProse(i);
+ const endIdx = close >= 0 ? close : n;
+ segs.push({ kind: 'code', text: text.slice(i, endIdx) });
+ proseStart = endIdx;
+ i = endIdx;
+ continue;
+ }
+ }
+ }
+ if (text[i] === '`') {
+ let count = 0;
+ while (text[i + count] === '`') count++;
+ let j = i + count;
+ let close = -1;
+ while (j < n) {
+ if (text[j] === '`') {
+ let cc = 0;
+ while (text[j + cc] === '`') cc++;
+ if (cc === count) { close = j + cc; break; }
+ j += cc;
+ } else {
+ j++;
+ }
+ }
+ if (close > 0) {
+ flushProse(i);
+ segs.push({ kind: 'code', text: text.slice(i, close) });
+ proseStart = close;
+ i = close;
+ continue;
+ }
+ flushProse(i);
+ segs.push({ kind: 'code', text: text.slice(i, n) });
+ proseStart = n;
+ i = n;
+ continue;
+ }
+ i++;
+ }
+ flushProse(n);
+ return segs;
+}
+
+// Find every `<TAG>...</TAG>` (or unclosed `<TAG>...EOF`) range whose
+// OPENING tag falls in an outer prose segment. The tagged container is
+// treated as one atomic unit — once the opening tag is in prose, we walk
+// to the matching `</TAG>` (or EOF) regardless of what's inside, so
+// backticks / fences / quotes authored inside the body don't fragment
+// the container and let the post-fragment suffix (often including the
+// closing tag) leak past the stripper. The outer-context check still
+// preserves literal mentions of the tag inside fenced code / inline
+// backtick spans (coding-explanation case).
+//
+// Generalized over `tagName` so the same atomic-container guarantee
+// covers `<agent>` (commander create/edit container), `<agent-input-form>`
+// (agent's form widget), and `<agent-input-submission>` (user form-reply
+// tag). Open form: `<tagName>` OR `<tagName attr="..." attr="...">`.
+// Close form: `</tagName>`. The boundary check (next char must be `>`,
+// whitespace, or `/`) prevents `<agent>` lookup from also matching
+// `<agent-input-form>` and similar siblings.
+//
+// Granularity invariant: the guard (prose/code classification) is
+// evaluated at the entity's OPENING boundary, NOT per-fragment inside.
+// Re-anchoring inside would re-introduce the leak.
+function _findOuterTagRanges(text, tagName) {
+ if (!text || !tagName) return [];
+ const openLeader = `<${tagName}`;
+ const closeLiteral = `</${tagName}>`;
+ if (text.indexOf(openLeader) < 0) return [];
+ const segs = _splitMarkdownProseCode(text);
+ const ranges = [];
+ let pos = 0;
+ for (const seg of segs) {
+ const segStart = pos;
+ pos += seg.text.length;
+ if (seg.kind !== 'prose') continue;
+ let from = segStart;
+ while (from < pos) {
+ const last = ranges.length ? ranges[ranges.length - 1] : null;
+ if (last && from < last[1]) from = last[1];
+ if (from >= pos) break;
+ const openIdx = text.indexOf(openLeader, from);
+ if (openIdx < 0 || openIdx >= pos) break;
+ // Boundary check: next char after `<tagName` must be `>` / whitespace
+ // / `/` so we don't match `<agent>` against `<agent-input-form>`.
+ const next = text.charCodeAt(openIdx + openLeader.length);
+ const isBoundary = next === 62 /* > */ || next === 32 /* space */
+ || next === 9 /* \t */ || next === 10 /* \n */ || next === 13 /* \r */
+ || next === 47 /* / */;
+ if (!isBoundary) {
+ from = openIdx + openLeader.length;
+ continue;
+ }
+ // Walk past attributes to the closing `>` of the open tag, then to
+ // `</tagName>` (or EOF). Unclosed open-tag mid-stream → swallow rest
+ // of buffer atomically.
+ const tagEnd = text.indexOf('>', openIdx + openLeader.length);
+ if (tagEnd < 0) {
+ ranges.push([openIdx, text.length]);
+ from = text.length;
+ break;
+ }
+ const closeIdx = text.indexOf(closeLiteral, tagEnd + 1);
+ const endPos = closeIdx < 0 ? text.length : closeIdx + closeLiteral.length;
+ ranges.push([openIdx, endPos]);
+ from = endPos;
+ }
+ }
+ return ranges;
+}
+
+// Strip every outer `<tagName>` container from `text` entirely. Used at
+// final-render time and at user-message-display time as a safety strip.
+function _stripOuterTagBlocks(text, tagName) {
+ if (!text) return text;
+ const ranges = _findOuterTagRanges(text, tagName);
+ if (!ranges.length) return text;
+ let out = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ out += text.slice(cursor, s);
+ cursor = e;
+ }
+ out += text.slice(cursor);
+ return out;
+}
+
+// Replace every outer `<tagName>` container with `placeholder`. Used at
+// streaming time to keep the bubble clean while the LLM is still typing
+// the body.
+function _replaceOuterTagBlocks(buf, tagName, placeholder) {
+ if (!buf) return buf;
+ const ranges = _findOuterTagRanges(buf, tagName);
+ if (!ranges.length) return buf;
+ let out = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ out += buf.slice(cursor, s) + placeholder;
+ cursor = e;
+ }
+ out += buf.slice(cursor);
+ return out;
+}
+
+// `<agent>`-specific wrappers. The final-time variant collapses runs of
+// blank lines and trims — that post-processing matters at the bubble
+// boundary (commander wraps the container in surrounding prose; clean
+// visual gap matters).
+function _findOuterAgentRanges(text) {
+ return _findOuterTagRanges(text, 'agent');
+}
+function _stripSurvivingAgentBlocks(text) {
+ if (!text) return text;
+ const out = _stripOuterTagBlocks(text, 'agent');
+ if (out === text) return text;
+ return out.replace(/\n{3,}/g, '\n\n').trim();
+}
+function _replaceOuterAgentBlocks(buf, placeholder) {
+ return _replaceOuterTagBlocks(buf, 'agent', placeholder);
+}
+
+// Defense-in-depth final-time strip for **every** structural container
+// that may surface in assistant / user message text:
+// - `<agent>` — primary case, commander create/edit
+// - `<agent-input-form>` — agent's form widget; main is supposed to
+// extract the payload + mount the widget so this never reaches final,
+// but if the main extractor misses a variant the raw XML lands in the
+// bubble alongside the widget. Strip silently rather than render raw.
+// - `<agent-input-submission>` — user form-reply tag; user-side render
+// already strips it via _stripSubmissionTagForDisplay, but if it ever
+// leaks into assistant text (LLM hallucination / quoting), strip too.
+//
+// Each tag is removed independently via the same atomic-container helper
+// so the prose/code guard applies uniformly — a literal mention inside a
+// fenced block / inline backtick survives all three. After all three
+// strip passes, collapse blank-line runs and trim, identical to the
+// `<agent>`-only post-processing.
+// `<<<skill-file path=X attr=V\n...content...\n>>>` block ranges. Different
+// from XML-tag containers: the body is **arbitrary file content** (Python,
+// TypeScript, HTML, JSX, configs) which routinely contains naked `<` / `>`
+// characters, so we use a literal three-char fence instead of a balanced
+// XML tag — same reason `chat_skill_setup.md` chose this shape on the LLM
+// side. The opener is `<<<skill-file` followed by attribute pairs and a
+// newline; the closer is `\n>>>` (must be at line start, mirrors backend
+// `SKILL_FILE_BLOCK_RE` in `features/skills.ts`).
+//
+// Outer-context check (prose vs code segment) is shared with the tag
+// finder: a literal `<<<skill-file` mentioned inside a fenced code block
+// or inline backtick (LLM showing the protocol to a user) must NOT be
+// recognised as a real block.
+const SKILL_FILE_OPEN = '<<<skill-file';
+const SKILL_FILE_CLOSE = '\n>>>';
+
+function _findOuterSkillFileRanges(text) {
+ if (!text || text.indexOf(SKILL_FILE_OPEN) < 0) return [];
+ const segs = _splitMarkdownProseCode(text);
+ const ranges = [];
+ let pos = 0;
+ for (const seg of segs) {
+ const segStart = pos;
+ pos += seg.text.length;
+ if (seg.kind !== 'prose') continue;
+ let from = segStart;
+ while (from < pos) {
+ const last = ranges.length ? ranges[ranges.length - 1] : null;
+ if (last && from < last[1]) from = last[1];
+ if (from >= pos) break;
+ const openIdx = text.indexOf(SKILL_FILE_OPEN, from);
+ if (openIdx < 0 || openIdx >= pos) break;
+ // Mirror agent's atomic-container guarantee: once the opener is in an
+ // outer prose segment, walk to `\n>>>` regardless of what's inside
+ // (file content can contain backticks, inline code, fences, anything).
+ // Unclosed opener mid-stream → swallow rest of buffer atomically so
+ // partial file content doesn't leak into the bubble.
+ const closeIdx = text.indexOf(SKILL_FILE_CLOSE, openIdx + SKILL_FILE_OPEN.length);
+ const endPos = closeIdx < 0 ? text.length : closeIdx + SKILL_FILE_CLOSE.length;
+ ranges.push([openIdx, endPos]);
+ from = endPos;
+ }
+ }
+ return ranges;
+}
+
+function _stripOuterSkillFileBlocks(text) {
+ if (!text) return text;
+ const ranges = _findOuterSkillFileRanges(text);
+ if (!ranges.length) return text;
+ let out = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ out += text.slice(cursor, s);
+ cursor = e;
+ }
+ out += text.slice(cursor);
+ return out;
+}
+
+// Pull the `path=X` attribute value out of a captured block — used by the
+// streaming placeholder so the user sees "writing <basename>…" instead of
+// a generic "writing file…". Tolerant of attribute order; quotes are not
+// expected (LLM emits `path=SKILL.md` per the spec) but stripped if found.
+function _extractSkillFilePath(blockText) {
+ const m = /\bpath=("([^"]*)"|'([^']*)'|(\S+))/.exec(blockText || '');
+ if (!m) return '';
+ return m[2] || m[3] || m[4] || '';
+}
+
+function _replaceOuterSkillFileBlocks(buf, makePlaceholder) {
+ if (!buf) return buf;
+ const ranges = _findOuterSkillFileRanges(buf);
+ if (!ranges.length) return buf;
+ let out = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ out += buf.slice(cursor, s);
+ out += makePlaceholder(_extractSkillFilePath(buf.slice(s, e)));
+ cursor = e;
+ }
+ out += buf.slice(cursor);
+ return out;
+}
+
+// Streaming-time strip for the commander's `<skill>` container. Two modes:
+// - **Closed** `<skill>...</skill>` → strip outer tags + any `<skill_id>`
+// sub-tag, keep the inner content. The inner `<<<skill-file>>>` blocks
+// have already been transformed into per-file placeholders by an
+// earlier pipeline pass; surfacing those gives the user "Writing X…"
+// progress that matches the per-skill edit chat.
+// - **Unclosed** (LLM still streaming the container) → replace the whole
+// half-open range with `fallbackPlaceholder` so naked `<skill>` /
+// `<skill_id>` tokens never bleed into the bubble.
+// Pure function: no DOM / i18n / escapeHtml. Caller passes the
+// already-built placeholder string. Companion `_stripSurvivingSkillContainer`
+// below is the final-time safety net (no placeholder; just removes raw
+// containers a buggy LLM might leak past the backend extractor).
+function _stripSkillCreateContainer(buf, fallbackPlaceholder) {
+ if (!buf || buf.indexOf('<skill>') < 0) return buf;
+ const ranges = _findOuterTagRanges(buf, 'skill');
+ if (!ranges.length) return buf;
+ let out = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ out += buf.slice(cursor, s);
+ const block = buf.slice(s, e);
+ if (block.endsWith('</skill>')) {
+ out += block
+ .replace(/^<skill>\s*/, '')
+ .replace(/\s*<\/skill>$/, '')
+ .replace(/<skill_id>[\s\S]*?<\/skill_id>\s*/g, '');
+ } else {
+ out += fallbackPlaceholder;
+ }
+ cursor = e;
+ }
+ out += buf.slice(cursor);
+ return out.replace(/\n{3,}/g, '\n\n');
+}
+
+function _stripSurvivingStructuralBlocks(text) {
+ if (!text) return text;
+ let out = text;
+ for (const tag of ['agent', 'agent-input-form', 'agent-input-submission', 'skill']) {
+ out = _stripOuterTagBlocks(out, tag);
+ }
+ // `<<<skill-file>>>` blocks: backend `extractSkillFileBlocks` strips them
+ // server-side at final-event time, but a stream aborted mid-block leaves
+ // the closing `\n>>>` absent → backend regex won't match → raw delimiters
+ // would otherwise reach the bubble. Final-time renderer safety strip
+ // covers that edge.
+ out = _stripOuterSkillFileBlocks(out);
+ if (out === text) return text;
+ return out.replace(/\n{3,}/g, '\n\n').trim();
+}
+
+// Test bridge — see file header. No-op in the browser (`module` undefined).
+if (typeof module !== 'undefined' && typeof module.exports === 'object') {
+ module.exports = {
+ _splitMarkdownProseCode,
+ _findOuterTagRanges,
+ _stripOuterTagBlocks,
+ _replaceOuterTagBlocks,
+ _findOuterAgentRanges,
+ _stripSurvivingAgentBlocks,
+ _replaceOuterAgentBlocks,
+ _findOuterSkillFileRanges,
+ _stripOuterSkillFileBlocks,
+ _replaceOuterSkillFileBlocks,
+ _extractSkillFilePath,
+ _stripSkillCreateContainer,
+ _stripSurvivingStructuralBlocks,
+ };
+}
diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.ts
index b2090bc4..e53bfad9 100644
--- a/test/main/features/agents.test.ts
+++ b/test/main/features/agents.test.ts
@@ -248,10 +248,10 @@ describe('agents › isValidAgentId', () => {
});
describe('agents › extractAgentFieldBlocks', () => {
- it('returns original text with empty fields when no marker', async () => {
+ it('returns original text with empty blocks when no marker', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('just prose');
- expect(r.fields).toEqual({});
+ expect(r.blocks).toEqual([]);
expect(r.cleanText).toBe('just prose');
});
@@ -270,7 +270,8 @@ describe('agents › extractAgentFieldBlocks', () => {
'after',
].join('\n');
const r = a.extractAgentFieldBlocks(text);
- expect(r.fields).toEqual({
+ expect(r.blocks).toHaveLength(1);
+ expect(r.blocks[0]).toEqual({
name: 'Planner',
description: 'Plans things',
workflow: 'step 1\nstep 2',
@@ -281,17 +282,64 @@ describe('agents › extractAgentFieldBlocks', () => {
expect(r.cleanText).not.toContain('</agent>');
});
+ it('extracts every <agent> container in emission order (multi-agent turn)', async () => {
+ const a = await loadAgents();
+ const text = [
+ 'prose',
+ '<agent>',
+ '<agent_id>aaaaaaaaaaaa</agent_id>',
+ '<workflow>w-A</workflow>',
+ '</agent>',
+ 'middle',
+ '<agent>',
+ '<agent_id>bbbbbbbbbbbb</agent_id>',
+ '<workflow>w-B</workflow>',
+ '</agent>',
+ 'tail',
+ ].join('\n');
+ const r = a.extractAgentFieldBlocks(text);
+ expect(r.blocks).toHaveLength(2);
+ expect(r.blocks[0].agent_id).toBe('aaaaaaaaaaaa');
+ expect(r.blocks[0].workflow).toBe('w-A');
+ expect(r.blocks[1].agent_id).toBe('bbbbbbbbbbbb');
+ expect(r.blocks[1].workflow).toBe('w-B');
+ expect(r.cleanText).not.toContain('<agent>');
+ expect(r.cleanText).toContain('prose');
+ expect(r.cleanText).toContain('middle');
+ expect(r.cleanText).toContain('tail');
+ });
+
+ it('parses each block independently — a malformed sub-tag in one does not affect the other', async () => {
+ const a = await loadAgents();
+ const text = [
+ '<agent>',
+ '<agent_id>aaaaaaaaaaaa</agent_id>',
+ '<workflow>good-A</workflow>',
+ '<inputs>not-json{</inputs>',
+ '</agent>',
+ '<agent>',
+ '<agent_id>bbbbbbbbbbbb</agent_id>',
+ '<workflow>good-B</workflow>',
+ '</agent>',
+ ].join('\n');
+ const r = a.extractAgentFieldBlocks(text);
+ expect(r.blocks).toHaveLength(2);
+ expect(r.blocks[0].workflow).toBe('good-A');
+ expect('inputs' in r.blocks[0]).toBe(false); // malformed JSON → key omitted
+ expect(r.blocks[1].workflow).toBe('good-B');
+ });
+
it('ignores child tags with empty body', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><name> </name></agent>');
- expect(r.fields).toEqual({});
+ expect(r.blocks).toEqual([{}]);
});
it('extracts <skills> child into string[] (one id per line)', async () => {
const a = await loadAgents();
const text = '<agent><skills>\nsocial-fetch\nmulti-analysis\n</skills></agent>';
const r = a.extractAgentFieldBlocks(text);
- expect(r.fields.skill_list).toEqual(['social-fetch', 'multi-analysis']);
+ expect(r.blocks[0].skill_list).toEqual(['social-fetch', 'multi-analysis']);
});
it('treats empty <skills> child as explicit [] (zero skills)', async () => {
@@ -299,20 +347,20 @@ describe('agents › extractAgentFieldBlocks', () => {
// Empty tag must be distinguishable from an absent tag — the former
// means "this agent needs NO skills", the latter means "leave unchanged".
const r = a.extractAgentFieldBlocks('<agent><skills>\n\n</skills></agent>');
- expect(r.fields.skill_list).toEqual([]);
+ expect(r.blocks[0].skill_list).toEqual([]);
});
it('filters non-safeId entries from <skills> child', async () => {
const a = await loadAgents();
const text = '<agent><skills>\nok-1\n../evil\n \ngood_2\n</skills></agent>';
const r = a.extractAgentFieldBlocks(text);
- expect(r.fields.skill_list).toEqual(['ok-1', 'good_2']);
+ expect(r.blocks[0].skill_list).toEqual(['ok-1', 'good_2']);
});
it('does not set skill_list when no <skills> child present', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><name>A</name></agent>');
- expect('skill_list' in r.fields).toBe(false);
+ expect('skill_list' in r.blocks[0]).toBe(false);
});
// <interactive> drives the input-box auto-target. Each branch matters:
@@ -322,34 +370,34 @@ describe('agents › extractAgentFieldBlocks', () => {
it('extracts <interactive>true</interactive> as boolean true', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><interactive>true</interactive></agent>');
- expect(r.fields.interactive).toBe(true);
+ expect(r.blocks[0].interactive).toBe(true);
});
it('extracts <interactive>false</interactive> as boolean false', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><interactive>false</interactive></agent>');
- expect(r.fields.interactive).toBe(false);
+ expect(r.blocks[0].interactive).toBe(false);
});
it('accepts case-insensitive TRUE/False', async () => {
const a = await loadAgents();
expect(a.extractAgentFieldBlocks('<agent><interactive>TRUE</interactive></agent>')
- .fields.interactive).toBe(true);
+ .blocks[0].interactive).toBe(true);
expect(a.extractAgentFieldBlocks('<agent><interactive>False</interactive></agent>')
- .fields.interactive).toBe(false);
+ .blocks[0].interactive).toBe(false);
});
it('omits interactive key when child is absent', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><name>A</name></agent>');
- expect('interactive' in r.fields).toBe(false);
+ expect('interactive' in r.blocks[0]).toBe(false);
});
it('omits interactive key for non-boolean bodies (no silent flip)', async () => {
const a = await loadAgents();
- expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive>yes</interactive></agent>').fields).toBe(false);
- expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive>1</interactive></agent>').fields).toBe(false);
- expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive></interactive></agent>').fields).toBe(false);
+ expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive>yes</interactive></agent>').blocks[0]).toBe(false);
+ expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive>1</interactive></agent>').blocks[0]).toBe(false);
+ expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive></interactive></agent>').blocks[0]).toBe(false);
});
});
@@ -480,7 +528,7 @@ describe('agents › extractAgentFieldBlocks › inputs', () => {
'tail',
].join('\n');
const r = a.extractAgentFieldBlocks(txt);
- expect(r.fields.inputs).toEqual([
+ expect(r.blocks[0].inputs).toEqual([
{ id: 'kw', label: '关键词', type: 'text', default: '' },
]);
expect(r.cleanText).not.toContain('<agent>');
@@ -490,19 +538,19 @@ describe('agents › extractAgentFieldBlocks › inputs', () => {
it('treats empty inputs child as explicit []', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><inputs>\n\n</inputs></agent>');
- expect(r.fields.inputs).toEqual([]);
+ expect(r.blocks[0].inputs).toEqual([]);
});
it('omits inputs key when JSON is malformed (does NOT erase existing schema)', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><inputs>\nnot-json{\n</inputs></agent>');
- expect('inputs' in r.fields).toBe(false);
+ expect('inputs' in r.blocks[0]).toBe(false);
});
it('does not set inputs when no <inputs> child present', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><name>A</name></agent>');
- expect('inputs' in r.fields).toBe(false);
+ expect('inputs' in r.blocks[0]).toBe(false);
});
});
diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.ts
index 47312284..537fd6ca 100644
--- a/test/main/features/skills.test.ts
+++ b/test/main/features/skills.test.ts
@@ -231,6 +231,268 @@ describe('skills › extractSkillFileBlocks', () => {
});
});
+describe('skills › extractSkillContainers', () => {
+ // Pure text-munging regex around the commander's `<skill>` container.
+ // Hard rule (PC/CLAUDE.md §9): set A pins real shapes the matcher must
+ // accept; set B pins look-alike shapes the matcher must NOT process.
+ // Adding a guard / branch later requires extending both sets — silent
+ // regressions in this file have shipped before through the `<agent>`
+ // strip-regex path.
+
+ // ── Set A: real shapes (must extract) ──────────────────────────────────
+ it('A1: edit container with skill_id + single SKILL.md block', async () => {
+ const s = await loadSkills();
+ const text = 'prose before\n<skill>\n<skill_id>foo</skill_id>\n<<<skill-file path=SKILL.md\n---\nname: "foo"\n---\n\n# body\n>>>\n</skill>\nprose after';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toHaveLength(1);
+ expect(r.containers[0].skillId).toBe('foo');
+ expect(r.containers[0].files.map((f: any) => f.path)).toEqual(['SKILL.md']);
+ expect(r.containers[0].files[0].content).toContain('name: "foo"');
+ expect(r.cleanText).toContain('prose before');
+ expect(r.cleanText).toContain('prose after');
+ expect(r.cleanText).not.toContain('<skill>');
+ expect(r.cleanText).not.toContain('<<<skill-file');
+ });
+
+ it('A2: create container (no skill_id) with multiple blocks', async () => {
+ const s = await loadSkills();
+ const text = '<skill>\n<<<skill-file path=SKILL.md\n---\nname: "abc"\ndescription_en: "desc"\n---\n\n# body\n>>>\n<<<skill-file path=scripts/foo.py\nprint("hi")\n>>>\n</skill>';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toHaveLength(1);
+ expect(r.containers[0].skillId).toBeUndefined();
+ expect(r.containers[0].files.map((f: any) => f.path)).toEqual(['SKILL.md', 'scripts/foo.py']);
+ });
+
+ it('A3: skill_id with whitespace + leading blank line is trimmed', async () => {
+ const s = await loadSkills();
+ const text = '<skill>\n<skill_id>\n bar \n</skill_id>\n<<<skill-file path=SKILL.md\nbody\n>>>\n</skill>';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers[0].skillId).toBe('bar');
+ });
+
+ it('A4: every container is parsed in emission order; all stripped from cleanText', async () => {
+ const s = await loadSkills();
+ const text = '<skill>\n<skill_id>first</skill_id>\n<<<skill-file path=SKILL.md\nA\n>>>\n</skill>\nmid\n<skill>\n<skill_id>second</skill_id>\n<<<skill-file path=SKILL.md\nB\n>>>\n</skill>';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toHaveLength(2);
+ expect(r.containers[0].skillId).toBe('first');
+ expect(r.containers[1].skillId).toBe('second');
+ expect(r.cleanText).toContain('mid');
+ expect(r.cleanText).not.toContain('<skill>');
+ });
+
+ // ── Set B: look-alike shapes (must NOT extract / must NOT mis-route) ───
+ it('B1: bare prose without `<skill>` returns empty containers, untouched cleanText', async () => {
+ const s = await loadSkills();
+ const r = s.extractSkillContainers('I will write a skill that does X');
+ expect(r.containers).toEqual([]);
+ expect(r.cleanText).toBe('I will write a skill that does X');
+ });
+
+ it('B2: agent <skills> sub-tag must NOT match skill container', async () => {
+ const s = await loadSkills();
+ // The <skills> tag inside an <agent> container is a list, not the
+ // commander's <skill>. Matching it would silently treat agent edits
+ // as skill writes.
+ const text = '<agent>\n<skills>\nfoo-skill\n</skills>\n</agent>';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toEqual([]);
+ expect(r.cleanText).toBe(text);
+ });
+
+ it('B3: stray `<<<skill-file>>>` outside any `<skill>` container is left visible (LLM feedback)', async () => {
+ const s = await loadSkills();
+ // The block is visible prose, NOT processed. cleanText should still
+ // contain it so the LLM sees it didn't take effect and self-corrects
+ // next turn. Pre-emptive global stripping would silently swallow the
+ // mistake.
+ const text = 'before\n<<<skill-file path=foo.md\nbody\n>>>\nafter';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toEqual([]);
+ expect(r.cleanText).toContain('<<<skill-file');
+ });
+
+ it('B4: unclosed `<skill>` tag is stripped from cleanText but not extracted', async () => {
+ const s = await loadSkills();
+ // Final-event text shouldn't have unclosed containers, but if one
+ // slips through (mid-stream truncation / abort), don't extract it
+ // (no closing tag = container intent unclear). Range-based clean
+ // still removes the half-open tokens so naked `<skill>` doesn't
+ // pollute the bubble.
+ const text = '<skill>\n<skill_id>x</skill_id>\nno closing tag here';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toEqual([]);
+ expect(r.cleanText).not.toContain('<skill>');
+ expect(r.cleanText).not.toContain('<skill_id>');
+ });
+
+ // ── Set B (prose/code guard): containers inside code regions ──────────
+ // Without this guard the LLM teaching/quoting the protocol to the user
+ // — by emitting a fenced ```...``` example or an inline `<skill>...</skill>`
+ // span — would falsely trigger a real skill write. This is the "agent
+ // section line 229 / chat_skill_setup.md showing protocol" risk surface.
+
+ it('B5: `<skill>` inside fenced ```xml block must NOT match', async () => {
+ const s = await loadSkills();
+ const text = 'Here is the format:\n```xml\n<skill>\n<skill_id>example</skill_id>\n<<<skill-file path=SKILL.md\nname: "example"\n>>>\n</skill>\n```\nThat is the shape.';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toEqual([]);
+ expect(r.cleanText).toBe(text); // Untouched — it's prose teaching, not a real op.
+ });
+
+ it('B6: `<skill>` inside inline backtick span must NOT match', async () => {
+ const s = await loadSkills();
+ const text = 'Wrap your spec inside `<skill>...</skill>` and the system will pick it up.';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toEqual([]);
+ expect(r.cleanText).toBe(text);
+ });
+
+ it('B7: real container AFTER a code-fence example — only the real one is extracted', async () => {
+ const s = await loadSkills();
+ // Critical: this is the failure mode the guard prevents — a naive
+ // regex would match the FIRST `<skill>` (the fenced example) and
+ // try to write fictional files, ignoring the real container below.
+ const text = 'Format:\n```xml\n<skill>\n<skill_id>example</skill_id>\n</skill>\n```\nAnd here is the real one:\n<skill>\n<skill_id>real</skill_id>\n<<<skill-file path=SKILL.md\nbody\n>>>\n</skill>';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toHaveLength(1);
+ expect(r.containers[0].skillId).toBe('real');
+ expect(r.cleanText).toContain('```xml');
+ expect(r.cleanText).toContain('<skill>\n<skill_id>example</skill_id>'); // fenced example survives
+ });
+});
+
+describe('skills › applySkillContainerFromCommander › create', () => {
+ it('creates skill from frontmatter `name`, writes all blocks', async () => {
+ const s = await loadSkills();
+ const skillMdContent = '---\nname: "social-fetch"\ndescription_zh: "抓取并分析"\ndescription_en: "Fetch and analyze"\n---\n\n# When to use\n…\n';
+ const r = await s.applySkillContainerFromCommander({
+ files: [
+ { path: 'SKILL.md', content: skillMdContent },
+ { path: 'scripts/fetch.py', content: 'print("hi")\n' },
+ ],
+ });
+ expect(r.ok).toBe(true);
+ expect(r.kind).toBe('created');
+ expect(r.skillId).toBe('social-fetch');
+ expect(r.written).toEqual(['SKILL.md', 'scripts/fetch.py']);
+ const md = fs.readFileSync(path.join(customSkillsDir(), 'social-fetch', 'SKILL.md'), 'utf8');
+ expect(md).toContain('description_en: "Fetch and analyze"');
+ expect(md).toContain('# When to use');
+ });
+
+ it('rejects create when SKILL.md block is missing', async () => {
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ files: [{ path: 'scripts/x.py', content: 'pass' }],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/SKILL.md|缺少/);
+ });
+
+ it('rejects create when frontmatter has no `name`', async () => {
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ files: [{ path: 'SKILL.md', content: '---\ndescription_en: "x"\n---\n\nbody\n' }],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/name|缺少/);
+ });
+
+ it('rejects create when name has Chinese characters (charset gate)', async () => {
+ const s = await loadSkills();
+ // Hard requirement from product: skill name must be ASCII only.
+ const r = await s.applySkillContainerFromCommander({
+ files: [{ path: 'SKILL.md', content: '---\nname: "中文技能"\n---\n\nbody\n' }],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/name|invalid|名称/);
+ });
+
+ it('rejects create on collision with existing custom skill', async () => {
+ writeCustomSkill('dup');
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ files: [{ path: 'SKILL.md', content: '---\nname: "dup"\n---\n\nbody\n' }],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/already exists|已存在/);
+ });
+});
+
+describe('skills › applySkillContainerFromCommander › edit', () => {
+ it('writes blocks to existing custom skill', async () => {
+ writeCustomSkill('beta', 'name: "beta"\ndescription_en: "old"', 'old body');
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ skillId: 'beta',
+ files: [{ path: 'scripts/run.py', content: 'pass\n' }],
+ });
+ expect(r.ok).toBe(true);
+ expect(r.kind).toBe('updated');
+ expect(r.skillId).toBe('beta');
+ expect(r.written).toEqual(['scripts/run.py']);
+ expect(fs.existsSync(path.join(customSkillsDir(), 'beta', 'scripts/run.py'))).toBe(true);
+ });
+
+ it('rejects edit on builtin skill (read-only outside dev panel)', async () => {
+ fs.mkdirSync(path.join(builtinSkillsDir(), 'shipped'), { recursive: true });
+ fs.writeFileSync(
+ path.join(builtinSkillsDir(), 'shipped', 'SKILL.md'),
+ '---\nname: "shipped"\n---\n\nbody\n',
+ );
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ skillId: 'shipped',
+ files: [{ path: 'SKILL.md', content: '---\nname: "shipped"\n---\n\ntampered\n' }],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/built-in|内置/i);
+ // Original body preserved.
+ expect(fs.readFileSync(path.join(builtinSkillsDir(), 'shipped', 'SKILL.md'), 'utf8'))
+ .toContain('body');
+ });
+
+ it('rejects edit when skill does not exist', async () => {
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ skillId: 'nonexistent',
+ files: [{ path: 'SKILL.md', content: '---\nname: "nonexistent"\n---\n\nbody\n' }],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/not found|不存在/i);
+ });
+
+ it('auto-renames the dir when SKILL.md `name` changes', async () => {
+ writeCustomSkill('oldname', 'name: "oldname"\ndescription_en: "x"', 'body');
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ skillId: 'oldname',
+ files: [{ path: 'SKILL.md', content: '---\nname: "newname"\ndescription_en: "x"\n---\n\nbody\n' }],
+ });
+ expect(r.ok).toBe(true);
+ expect(r.skillId).toBe('newname');
+ expect(fs.existsSync(path.join(customSkillsDir(), 'oldname'))).toBe(false);
+ expect(fs.existsSync(path.join(customSkillsDir(), 'newname'))).toBe(true);
+ });
+
+ it('best-effort: one rejected path does not roll back successful writes', async () => {
+ writeCustomSkill('keep', 'name: "keep"\ndescription_en: "x"', 'body');
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ skillId: 'keep',
+ files: [
+ { path: 'good.txt', content: 'kept' },
+ { path: '../escape', content: 'should reject' },
+ ],
+ });
+ expect(r.ok).toBe(true);
+ expect(r.written).toEqual(['good.txt']);
+ expect(r.rejected).toEqual(['../escape']);
+ expect(fs.readFileSync(path.join(customSkillsDir(), 'keep', 'good.txt'), 'utf8')).toBe('kept');
+ });
+});
+
describe('skills › hashTree', () => {
it('returns empty string for missing dir', async () => {
const s = await loadSkills();
diff --git a/test/renderer/strip-structural-blocks.test.ts b/test/renderer/strip-structural-blocks.test.ts
new file mode 100644
index 00000000..861bd345
--- /dev/null
+++ b/test/renderer/strip-structural-blocks.test.ts
@@ -0,0 +1,740 @@
+// Pin the set-A vs set-B invariants for the `<agent>` container strippers.
+// Without these fixtures, the next "fix one shape, regress another" round
+// is invisible to typecheck and reviewer eyeballs — same class of bug has
+// already burned us across 34e27fcb / a3110e61 / a follow-up.
+//
+// Set A — real `<agent>` containers that MUST be stripped (final) /
+// replaced by a single placeholder (streaming):
+// A1. Plain closed container, no special tokens inside.
+// A2. Closed container whose `<workflow>` quotes tool / value names with
+// INLINE BACKTICKS — the shape that broke streaming and forced the
+// most recent rewrite. This is the load-bearing fixture.
+// A3. Closed container whose body has a multi-line FENCED CODE BLOCK
+// inside (e.g., LLM showing an example payload). The container is
+// still atomic at the OUTER level even though its body opens a
+// fence.
+// A4. Unclosed `<agent>` mid-stream — strip / replace from the opener
+// through end-of-buffer.
+// A5. Two closed containers in one buffer — both stripped, prose between
+// them preserved.
+//
+// Set B — literal `<agent>` mentions that MUST be preserved:
+// B1. Inside a fenced ```xml code block (the original 34e27fcb case).
+// B2. Inside an inline backtick span.
+// B3. Inside an UNCLOSED inline backtick (mid-stream code-explanation).
+//
+// Mixed: real container + literal mention coexisting in one buffer — only
+// the real container goes, the literal mention stays put.
+//
+// Adding a new guard / branch to any of these strippers? Add a fixture
+// for the motivating shape AND keep the existing fixtures green. Don't
+// rely on "I checked it manually" — that's the loop these tests exist
+// to break.
+
+import { describe, it, expect } from 'vitest';
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const strip = require('../../src/renderer/modules/strip-structural-blocks.js');
+const {
+ _splitMarkdownProseCode,
+ _findOuterTagRanges,
+ _stripOuterTagBlocks,
+ _replaceOuterTagBlocks,
+ _findOuterAgentRanges,
+ _stripSurvivingAgentBlocks,
+ _replaceOuterAgentBlocks,
+ _stripSkillCreateContainer,
+ _stripSurvivingStructuralBlocks,
+} = strip as {
+ _splitMarkdownProseCode: (text: string) => Array<{ kind: 'prose' | 'code'; text: string }>;
+ _findOuterTagRanges: (text: string, tagName: string) => Array<[number, number]>;
+ _stripOuterTagBlocks: (text: string, tagName: string) => string;
+ _replaceOuterTagBlocks: (buf: string, tagName: string, placeholder: string) => string;
+ _findOuterAgentRanges: (text: string) => Array<[number, number]>;
+ _stripSurvivingAgentBlocks: (text: string) => string;
+ _replaceOuterAgentBlocks: (buf: string, placeholder: string) => string;
+ _stripSkillCreateContainer: (buf: string, fallbackPlaceholder: string) => string;
+ _stripSurvivingStructuralBlocks: (text: string) => string;
+};
+
+const PH = '⟨PLACEHOLDER⟩';
+
+// --- Set A: real containers ------------------------------------------------
+
+describe('set A — real <agent> containers must be stripped / replaced', () => {
+ it('A1. plain closed container', () => {
+ const buf = 'preface\n<agent>\n<name>Foo</name>\n</agent>\ntail';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe('preface\n\ntail');
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(`preface\n${PH}\ntail`);
+ });
+
+ it('A2. container body contains INLINE BACKTICKS (the screenshot bug)', () => {
+ const buf = [
+ 'before',
+ '<agent>',
+ '<workflow>',
+ '1. Read inputs',
+ ' - `bash` — read user submission',
+ ' - normalize to `agent` / `skill` / `agent_and_skill`',
+ '</workflow>',
+ '</agent>',
+ 'after',
+ ].join('\n');
+ const stripped = _stripSurvivingAgentBlocks(buf);
+ expect(stripped).not.toContain('<agent>');
+ expect(stripped).not.toContain('</agent>');
+ expect(stripped).not.toContain('<workflow>');
+ expect(stripped).not.toContain('`bash`');
+ expect(stripped).not.toContain('agent_and_skill');
+ expect(stripped).toBe('before\n\nafter');
+
+ const replaced = _replaceOuterAgentBlocks(buf, PH);
+ expect(replaced).toBe(`before\n${PH}\nafter`);
+ // Exactly one placeholder — no leak after it.
+ expect(replaced.split(PH).length - 1).toBe(1);
+ });
+
+ it('A3. container body contains a fenced code block', () => {
+ const buf = [
+ 'before',
+ '<agent>',
+ '<description_en>',
+ 'See example:',
+ '```json',
+ '{"k": "v"}',
+ '```',
+ '</description_en>',
+ '</agent>',
+ 'after',
+ ].join('\n');
+ expect(_stripSurvivingAgentBlocks(buf)).toBe('before\n\nafter');
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(`before\n${PH}\nafter`);
+ });
+
+ it('A4. unclosed <agent> mid-stream', () => {
+ const buf = 'streaming…\n<agent>\n<name>Foo</name>\n<workflow>step `bash` —';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe('streaming…');
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(`streaming…\n${PH}`);
+ });
+
+ it('A5. two closed containers in one buffer', () => {
+ const buf = '<agent><name>A</name></agent>\nmid\n<agent><name>B</name></agent>';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe('mid');
+ const replaced = _replaceOuterAgentBlocks(buf, PH);
+ expect(replaced).toBe(`${PH}\nmid\n${PH}`);
+ expect(replaced.split(PH).length - 1).toBe(2);
+ });
+});
+
+// --- Set B: literal mentions must survive ---------------------------------
+
+describe('set B — literal <agent> in code must be preserved', () => {
+ it('B1. inside a fenced ```xml block', () => {
+ const buf = 'Use this format:\n```xml\n<agent><name>X</name></agent>\n```\nafter';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe(buf.trim());
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(buf);
+ });
+
+ it('B2. inside an inline backtick span', () => {
+ const buf = 'Wrap your spec in `<agent>...</agent>` to declare it.';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe(buf);
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(buf);
+ });
+
+ it('B3. inside an UNCLOSED inline backtick mid-stream', () => {
+ const buf = 'You write `<agent>';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe(buf);
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(buf);
+ });
+});
+
+// --- Mixed: container + literal mention coexisting -------------------------
+
+describe('mixed — real container + literal mention in one buffer', () => {
+ it('only the real container is replaced; quoted example survives', () => {
+ const buf = [
+ 'Example format:',
+ '```xml',
+ '<agent><name>Example</name></agent>',
+ '```',
+ 'And here is the actual one:',
+ '<agent>',
+ '<name>Real</name>',
+ '<workflow>step uses `bash`</workflow>',
+ '</agent>',
+ 'done.',
+ ].join('\n');
+ const stripped = _stripSurvivingAgentBlocks(buf);
+ // Quoted example inside ```xml stays.
+ expect(stripped).toContain('```xml');
+ expect(stripped).toContain('<agent><name>Example</name></agent>');
+ // Real one's tags / interior gone.
+ expect(stripped).not.toContain('<name>Real</name>');
+ expect(stripped).not.toContain('<workflow>');
+ expect(stripped).not.toContain('`bash`');
+
+ const replaced = _replaceOuterAgentBlocks(buf, PH);
+ expect(replaced).toContain('<agent><name>Example</name></agent>');
+ expect(replaced).toContain(PH);
+ expect(replaced).not.toContain('<name>Real</name>');
+ expect(replaced.split(PH).length - 1).toBe(1);
+ });
+});
+
+// --- Granularity invariant ------------------------------------------------
+
+describe('granularity invariant — the guard is anchored at the opening tag', () => {
+ it('range covers from <agent> opener to </agent> close, atomic across interior backticks', () => {
+ const buf = 'x\n<agent>a `b` c</agent>\ny';
+ const ranges = _findOuterAgentRanges(buf);
+ expect(ranges).toHaveLength(1);
+ const [start, end] = ranges[0];
+ expect(buf.slice(start, end)).toBe('<agent>a `b` c</agent>');
+ });
+
+ it('opener inside fenced code → no range produced', () => {
+ const buf = '```\n<agent>x</agent>\n```';
+ expect(_findOuterAgentRanges(buf)).toEqual([]);
+ });
+
+ it('opener inside inline backticks → no range produced', () => {
+ const buf = 'see `<agent>` token';
+ expect(_findOuterAgentRanges(buf)).toEqual([]);
+ });
+});
+
+// --- Empty / no-op inputs --------------------------------------------------
+
+describe('empty / no-op inputs', () => {
+ it('returns input unchanged when no <agent> token present', () => {
+ expect(_stripSurvivingAgentBlocks('hello world')).toBe('hello world');
+ expect(_replaceOuterAgentBlocks('hello world', PH)).toBe('hello world');
+ expect(_findOuterAgentRanges('hello world')).toEqual([]);
+ });
+
+ it('handles empty / falsy input', () => {
+ expect(_stripSurvivingAgentBlocks('')).toBe('');
+ expect(_replaceOuterAgentBlocks('', PH)).toBe('');
+ expect(_findOuterAgentRanges('')).toEqual([]);
+ });
+});
+
+// --- Sanity check on the prose/code splitter (used by the rangefinder) ----
+
+// --- Generic tagName parameter: the same matrix must hold for ----------
+// `<agent-input-form>` and `<agent-input-submission>`. Both currently lack
+// the prose/code guard in their original strippers; these fixtures lock
+// down the unified atomic-container behavior.
+
+describe('<agent-input-form> — set A (real form blocks must be replaced)', () => {
+ it('A1. plain XML form block, JSON body', () => {
+ const buf = 'lead-in\n<agent-input-form>\n[{"name":"topic","type":"text"}]\n</agent-input-form>\ntrail';
+ expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH))
+ .toBe('lead-in\n' + PH + '\ntrail');
+ });
+
+ it('A2. unclosed mid-stream form block', () => {
+ const buf = 'streaming…\n<agent-input-form>\n[{"name":"topic"';
+ expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH))
+ .toBe('streaming…\n' + PH);
+ });
+
+ it('A3. body containing inline backticks (label like "Use `bash`")', () => {
+ const buf = '<agent-input-form>\n[{"name":"x","label":"Use `bash` here"}]\n</agent-input-form>';
+ expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH)).toBe(PH);
+ });
+});
+
+describe('<agent-input-form> — set B (literal mentions must survive)', () => {
+ it('B1. inside a fenced ```xml block (protocol explanation)', () => {
+ const buf = 'Format:\n```xml\n<agent-input-form>\n[]\n</agent-input-form>\n```\nend';
+ expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH)).toBe(buf);
+ });
+
+ it('B2. inside an inline backtick span', () => {
+ const buf = 'Wrap fields in `<agent-input-form>` — the agent emits this.';
+ expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH)).toBe(buf);
+ });
+
+ it('B3. UNCLOSED inline backtick mid-stream (the streaming case)', () => {
+ const buf = 'Use `<agent-input-form>';
+ expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH)).toBe(buf);
+ });
+});
+
+describe('<agent-input-submission> — set A (real submission tags stripped)', () => {
+ it('A1. submission tag with attributes and JSON body', () => {
+ const buf = 'You confirmed:\n<agent-input-submission form_id="abc12345" agent_id="my-agent">\n{"topic":"x"}\n</agent-input-submission>';
+ expect(_stripOuterTagBlocks(buf, 'agent-input-submission'))
+ .toBe('You confirmed:\n');
+ });
+
+ it('A2. body whose JSON value contains backticks', () => {
+ const buf = 'You confirmed:\n<agent-input-submission form_id="abc12345" agent_id="my-agent">\n{"q":"run `bash` and `sh`"}\n</agent-input-submission>\nthanks';
+ const out = _stripOuterTagBlocks(buf, 'agent-input-submission');
+ expect(out).not.toContain('agent-input-submission');
+ expect(out).not.toContain('`bash`');
+ expect(out).toBe('You confirmed:\n\nthanks');
+ });
+});
+
+describe('<agent-input-submission> — set B (literal mentions survive)', () => {
+ it('B1. inside a fenced ```xml block', () => {
+ const buf = 'Reply format:\n```xml\n<agent-input-submission form_id="x" agent_id="y">\n{}\n</agent-input-submission>\n```';
+ expect(_stripOuterTagBlocks(buf, 'agent-input-submission')).toBe(buf);
+ });
+
+ it('B2. inside an inline backtick span', () => {
+ const buf = 'Use `<agent-input-submission ...>` to reply.';
+ expect(_stripOuterTagBlocks(buf, 'agent-input-submission')).toBe(buf);
+ });
+
+ it('B3. UNCLOSED inline backtick (defense-in-depth, even though the tag normally only appears in user messages and not mid-stream)', () => {
+ const buf = 'see `<agent-input-submission';
+ expect(_stripOuterTagBlocks(buf, 'agent-input-submission')).toBe(buf);
+ });
+});
+
+// --- Boundary check: tagName lookup must not bleed across siblings -------
+
+describe('boundary check — `<agent>` lookup must not match `<agent-input-form>`', () => {
+ it('a buffer containing only <agent-input-form> has no <agent> ranges', () => {
+ const buf = '<agent-input-form>\n[]\n</agent-input-form>';
+ expect(_findOuterTagRanges(buf, 'agent')).toEqual([]);
+ expect(_findOuterTagRanges(buf, 'agent-input-form')).toHaveLength(1);
+ });
+
+ it('a buffer containing only <agent-input-submission ...> has no <agent> ranges', () => {
+ const buf = '<agent-input-submission form_id="x" agent_id="y">{}</agent-input-submission>';
+ expect(_findOuterTagRanges(buf, 'agent')).toEqual([]);
+ expect(_findOuterTagRanges(buf, 'agent-input-submission')).toHaveLength(1);
+ });
+
+ it('mixed buffer — each tag matches independently', () => {
+ const buf = [
+ '<agent><name>A</name></agent>',
+ '<agent-input-form>\n[]\n</agent-input-form>',
+ '<agent-input-submission form_id="f" agent_id="a">{}</agent-input-submission>',
+ ].join('\n');
+ expect(_findOuterTagRanges(buf, 'agent')).toHaveLength(1);
+ expect(_findOuterTagRanges(buf, 'agent-input-form')).toHaveLength(1);
+ expect(_findOuterTagRanges(buf, 'agent-input-submission')).toHaveLength(1);
+ });
+});
+
+// --- Final-time defense-in-depth strip ----------------------------------
+// `_stripSurvivingStructuralBlocks` is the safety net at `_streamingSetFinal`
+// + persisted-render time. It must:
+// - strip every real outer container of all three tag families
+// - preserve every literal mention inside fenced code / inline backticks
+// - leave clean prose (no leftover blank-line runs)
+
+describe('_stripSurvivingStructuralBlocks (final-time safety strip)', () => {
+ it('strips a real <agent> container', () => {
+ const buf = 'lead\n<agent><name>X</name></agent>\ntail';
+ expect(_stripSurvivingStructuralBlocks(buf)).toBe('lead\n\ntail');
+ });
+
+ it('strips a surviving <agent-input-form> (main extractor missed it)', () => {
+ const buf = 'lead\n<agent-input-form>\n[]\n</agent-input-form>\ntail';
+ expect(_stripSurvivingStructuralBlocks(buf)).toBe('lead\n\ntail');
+ });
+
+ it('strips a hallucinated <agent-input-submission> in assistant text', () => {
+ const buf = 'lead\n<agent-input-submission form_id="f" agent_id="a">{}</agent-input-submission>\ntail';
+ expect(_stripSurvivingStructuralBlocks(buf)).toBe('lead\n\ntail');
+ });
+
+ it('strips all three tags coexisting in one buffer', () => {
+ const buf = [
+ 'before',
+ '<agent><name>A</name></agent>',
+ 'mid1',
+ '<agent-input-form>\n[]\n</agent-input-form>',
+ 'mid2',
+ '<agent-input-submission form_id="f" agent_id="a">{}</agent-input-submission>',
+ 'after',
+ ].join('\n');
+ const out = _stripSurvivingStructuralBlocks(buf);
+ expect(out).not.toContain('<agent>');
+ expect(out).not.toContain('<agent-input-form>');
+ expect(out).not.toContain('<agent-input-submission');
+ expect(out).toContain('before');
+ expect(out).toContain('mid1');
+ expect(out).toContain('mid2');
+ expect(out).toContain('after');
+ });
+
+ it('preserves every literal mention inside fenced code', () => {
+ const buf = [
+ 'Three protocol tags:',
+ '```xml',
+ '<agent><name>X</name></agent>',
+ '<agent-input-form>\n[]\n</agent-input-form>',
+ '<agent-input-submission form_id="f" agent_id="a">{}</agent-input-submission>',
+ '```',
+ 'end',
+ ].join('\n');
+ const out = _stripSurvivingStructuralBlocks(buf);
+ expect(out).toContain('<agent><name>X</name></agent>');
+ expect(out).toContain('<agent-input-form>');
+ expect(out).toContain('<agent-input-submission');
+ });
+
+ it('preserves every literal mention inside inline backticks', () => {
+ const buf = 'Use `<agent>`, `<agent-input-form>`, `<agent-input-submission ...>` for the three tags.';
+ expect(_stripSurvivingStructuralBlocks(buf)).toBe(buf);
+ });
+
+ it('mixed: real <agent> + literal forms in code → only <agent> stripped', () => {
+ const buf = [
+ 'spec:',
+ '```xml',
+ '<agent-input-form>\n[]\n</agent-input-form>',
+ '```',
+ '<agent><name>Real</name></agent>',
+ 'after',
+ ].join('\n');
+ const out = _stripSurvivingStructuralBlocks(buf);
+ expect(out).toContain('<agent-input-form>');
+ expect(out).not.toContain('<name>Real</name>');
+ expect(out).toContain('after');
+ });
+
+ it('no-op when buffer has none of the three tags', () => {
+ const buf = 'plain prose with no structural tags';
+ expect(_stripSurvivingStructuralBlocks(buf)).toBe(buf);
+ });
+
+ it('handles empty input', () => {
+ expect(_stripSurvivingStructuralBlocks('')).toBe('');
+ });
+});
+
+// --- Custom-fence blocks: `<<<skill-file path=X ... >>>` ----------------
+// Different delimiter family from XML tags above (see strip-structural-blocks.js
+// header). The skill-file block wraps **arbitrary file content** that may
+// contain naked `<` / `>` chars (Python, TypeScript, HTML, JSX, configs);
+// using XML tags would force the LLM to escape — instead the LLM-side
+// prompt (`chat_skill_setup.md`) declares a literal `<<<` / `\n>>>` fence
+// pair. The renderer must still apply the same prose/code outer-context
+// guard so a literal `<<<skill-file ...>>>` mention inside a fenced code
+// block / inline backtick (LLM explaining the protocol to the user)
+// survives, while a real block (containing arbitrary file content with
+// naked backticks / fences inside) is stripped/replaced atomically.
+
+const skill = require('../../src/renderer/modules/strip-structural-blocks.js');
+const {
+ _findOuterSkillFileRanges,
+ _stripOuterSkillFileBlocks,
+ _replaceOuterSkillFileBlocks,
+ _extractSkillFilePath,
+} = skill as {
+ _findOuterSkillFileRanges: (text: string) => Array<[number, number]>;
+ _stripOuterSkillFileBlocks: (text: string) => string;
+ _replaceOuterSkillFileBlocks: (buf: string, makePlaceholder: (path: string) => string) => string;
+ _extractSkillFilePath: (blockText: string) => string;
+};
+
+const SKILL_PH = (path: string) => `⟨SKILL:${path || '?'}⟩`;
+
+describe('skill-file — set A (real <<<skill-file>>> blocks must be replaced)', () => {
+ it('A1. plain closed block, SKILL.md frontmatter body', () => {
+ const buf = [
+ 'wrote it for you.',
+ '<<<skill-file path=SKILL.md',
+ '---',
+ 'name: foo',
+ 'description_zh: 中文',
+ 'description_en: English',
+ '---',
+ '',
+ '# body',
+ '>>>',
+ 'done.',
+ ].join('\n');
+ expect(_stripOuterSkillFileBlocks(buf)).toBe('wrote it for you.\n\ndone.');
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe('wrote it for you.\n⟨SKILL:SKILL.md⟩\ndone.');
+ });
+
+ it('A2. block body contains naked `<` `>` (HTML / JSX / generic types) — atomic strip', () => {
+ // The whole reason we use a literal fence instead of XML tags: file
+ // content routinely has these chars. Strip must not be confused by them.
+ const buf = [
+ 'before',
+ '<<<skill-file path=scripts/render.tsx',
+ 'function Foo(): JSX.Element { return <div>{x < y && y > z}</div>; }',
+ 'type Bag<T> = Array<T>;',
+ '>>>',
+ 'after',
+ ].join('\n');
+ expect(_stripOuterSkillFileBlocks(buf)).toBe('before\n\nafter');
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe('before\n⟨SKILL:scripts/render.tsx⟩\nafter');
+ });
+
+ it('A3. block body contains a fenced code block (markdown SKILL.md with ``` examples)', () => {
+ const buf = [
+ 'before',
+ '<<<skill-file path=SKILL.md',
+ '# Usage',
+ '```bash',
+ 'python3 scripts/run.py "topic"',
+ '```',
+ '>>>',
+ 'after',
+ ].join('\n');
+ expect(_stripOuterSkillFileBlocks(buf)).toBe('before\n\nafter');
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe('before\n⟨SKILL:SKILL.md⟩\nafter');
+ });
+
+ it('A4. unclosed block mid-stream — swallow to EOF', () => {
+ const buf = 'streaming…\n<<<skill-file path=SKILL.md\n---\nname: foo\n# partial body still arr';
+ expect(_stripOuterSkillFileBlocks(buf)).toBe('streaming…\n');
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe('streaming…\n⟨SKILL:SKILL.md⟩');
+ });
+
+ it('A5. two closed blocks in one buffer (e.g., SKILL.md + scripts/foo.py written same turn)', () => {
+ const buf = [
+ 'wrote two files.',
+ '<<<skill-file path=SKILL.md',
+ 'a',
+ '>>>',
+ 'and',
+ '<<<skill-file path=scripts/foo.py',
+ 'print("hi")',
+ '>>>',
+ 'done.',
+ ].join('\n');
+ expect(_stripOuterSkillFileBlocks(buf)).toBe('wrote two files.\n\nand\n\ndone.');
+ const replaced = _replaceOuterSkillFileBlocks(buf, SKILL_PH);
+ expect(replaced).toContain('⟨SKILL:SKILL.md⟩');
+ expect(replaced).toContain('⟨SKILL:scripts/foo.py⟩');
+ expect(replaced.match(/⟨SKILL:/g)?.length).toBe(2);
+ });
+});
+
+describe('skill-file — set B (literal <<<skill-file>>> mentions must survive)', () => {
+ it('B1. inside a fenced ```text block (LLM showing the protocol to the user)', () => {
+ const buf = [
+ 'Use this format to write a file:',
+ '```',
+ '<<<skill-file path=SKILL.md',
+ 'content',
+ '>>>',
+ '```',
+ 'after',
+ ].join('\n');
+ expect(_stripOuterSkillFileBlocks(buf)).toBe(buf);
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe(buf);
+ });
+
+ it('B2. inside an inline backtick span', () => {
+ const buf = 'Wrap content in `<<<skill-file path=X>>>...>>>` to write it.';
+ expect(_stripOuterSkillFileBlocks(buf)).toBe(buf);
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe(buf);
+ });
+
+ it('B3. inside an UNCLOSED inline backtick (mid-stream code-explanation)', () => {
+ const buf = 'You can write `<<<skill-file path=SKILL.md';
+ expect(_stripOuterSkillFileBlocks(buf)).toBe(buf);
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe(buf);
+ });
+});
+
+describe('skill-file — mixed (real block + literal mention coexisting)', () => {
+ it('only the real block goes; quoted protocol example stays', () => {
+ const buf = [
+ 'Format reference:',
+ '```',
+ '<<<skill-file path=PATH',
+ 'content',
+ '>>>',
+ '```',
+ 'And here is the actual write:',
+ '<<<skill-file path=SKILL.md',
+ 'real body',
+ '>>>',
+ 'done.',
+ ].join('\n');
+ const stripped = _stripOuterSkillFileBlocks(buf);
+ expect(stripped).toContain('```');
+ expect(stripped).toContain('<<<skill-file path=PATH'); // literal mention preserved
+ expect(stripped).not.toContain('real body');
+ expect(stripped).toContain('done.');
+
+ const replaced = _replaceOuterSkillFileBlocks(buf, SKILL_PH);
+ expect(replaced).toContain('<<<skill-file path=PATH'); // literal mention preserved
+ expect(replaced).toContain('⟨SKILL:SKILL.md⟩');
+ expect(replaced).not.toContain('real body');
+ // Exactly one placeholder (only the real block; the in-fence example doesn't count).
+ expect(replaced.match(/⟨SKILL:/g)?.length).toBe(1);
+ });
+});
+
+describe('skill-file — _extractSkillFilePath', () => {
+ it('extracts the path attribute regardless of trailing attrs', () => {
+ expect(_extractSkillFilePath('<<<skill-file path=SKILL.md')).toBe('SKILL.md');
+ expect(_extractSkillFilePath('<<<skill-file path=scripts/foo.py extra=1')).toBe('scripts/foo.py');
+ });
+
+ it('tolerates quoted forms even though the spec says unquoted', () => {
+ expect(_extractSkillFilePath('<<<skill-file path="SKILL.md"')).toBe('SKILL.md');
+ expect(_extractSkillFilePath("<<<skill-file path='scripts/run.sh'")).toBe('scripts/run.sh');
+ });
+
+ it('returns empty string when path attr is missing', () => {
+ expect(_extractSkillFilePath('<<<skill-file')).toBe('');
+ expect(_extractSkillFilePath('')).toBe('');
+ });
+});
+
+describe('skill-file — _stripSurvivingStructuralBlocks final-time safety', () => {
+ it('strips a surviving <<<skill-file>>> block (backend extractor missed it: stream aborted before \\n>>>)', () => {
+ const buf = 'lead\n<<<skill-file path=SKILL.md\n# partial body never closed';
+ expect(_stripSurvivingStructuralBlocks(buf)).toBe('lead');
+ });
+
+ it('coexists with XML-tag strip: real <agent> + real <<<skill-file>>> + literal mentions', () => {
+ const buf = [
+ 'before',
+ '<agent><name>A</name></agent>',
+ 'mid',
+ '<<<skill-file path=SKILL.md',
+ 'real body',
+ '>>>',
+ 'after',
+ '```',
+ '<agent><name>QuotedExample</name></agent>', // literal in code stays
+ '<<<skill-file path=Q>>>...>>>', // inline-ish in code stays
+ '```',
+ 'end',
+ ].join('\n');
+ const out = _stripSurvivingStructuralBlocks(buf);
+ expect(out).not.toContain('<name>A</name>');
+ expect(out).not.toContain('real body');
+ expect(out).toContain('<name>QuotedExample</name>'); // protected by ``` fence
+ expect(out).toContain('mid');
+ expect(out).toContain('after');
+ expect(out).toContain('end');
+ });
+});
+
+// Streaming-time skill-container stripper. Unique surface vs `<agent>`:
+// closed containers must keep their inner content (per-file placeholders)
+// while still hiding outer `<skill>` / `<skill_id>` scaffolding; unclosed
+// containers must collapse to a single fallback placeholder. Adding a
+// guard / branch here later requires extending the fixture set with the
+// new motivating shape — patch isn't done until the new fixture is green
+// AND every previous fixture still passes (PC/CLAUDE.md §9 hard rule).
+describe('_stripSkillCreateContainer — set A (real shapes)', () => {
+ it('A1. closed container with skill_id + per-file placeholder body', () => {
+ // The earlier pipeline pass replaces `<<<skill-file>>>` with the
+ // per-file placeholder; we feed the post-pass shape and expect the
+ // outer `<skill>` shell + `<skill_id>` to vanish, body retained.
+ const buf = 'preface\n<skill>\n<skill_id>foo</skill_id>\n[Writing SKILL.md…]\n</skill>\ntail';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toContain('preface');
+ expect(out).toContain('[Writing SKILL.md…]');
+ expect(out).toContain('tail');
+ expect(out).not.toContain('<skill>');
+ expect(out).not.toContain('</skill>');
+ expect(out).not.toContain('<skill_id>');
+ expect(out).not.toContain('foo');
+ expect(out).not.toContain('⟨FALLBACK⟩');
+ });
+
+ it('A2. closed container WITHOUT skill_id (create flow)', () => {
+ const buf = '<skill>\n[Writing SKILL.md…]\n[Writing scripts/foo.py…]\n</skill>';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toContain('[Writing SKILL.md…]');
+ expect(out).toContain('[Writing scripts/foo.py…]');
+ expect(out).not.toContain('<skill>');
+ });
+
+ it('A3. unclosed container collapses to fallback placeholder', () => {
+ // Mid-stream: `<skill>` opened, no `</skill>` yet. Inner content may
+ // still be raw `<skill_id>` / token fragments — the fallback hides
+ // ALL of it until the closer arrives.
+ const buf = 'before\n<skill>\n<skill_id>foo</skill_id>\nhalf-stre';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toContain('before');
+ expect(out).toContain('⟨FALLBACK⟩');
+ expect(out).not.toContain('<skill_id>');
+ expect(out).not.toContain('half-stre');
+ });
+
+ it('A4. multiple closed containers in one buffer (rare; both stripped)', () => {
+ const buf = '<skill>\n<skill_id>a</skill_id>\nA-body\n</skill>\nmid\n<skill>\nB-body\n</skill>';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toContain('A-body');
+ expect(out).toContain('mid');
+ expect(out).toContain('B-body');
+ expect(out).not.toContain('<skill>');
+ expect(out).not.toContain('<skill_id>');
+ });
+
+ it('A5. interior whitespace trim — opening newline + closing newline both eaten', () => {
+ const buf = '<skill>\n\nINNER\n\n</skill>';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toContain('INNER');
+ // The `\s*` strips on both sides should keep the line count tame —
+ // no triple-newline runs left over from the surgery.
+ expect(/\n{3,}/.test(out)).toBe(false);
+ });
+});
+
+describe('_stripSkillCreateContainer — set B (look-alikes must NOT match)', () => {
+ it('B1. agent <skills> sub-tag must NOT trigger skill-container handling', () => {
+ // The agent flow's `<skills>` list lives inside an `<agent>` container.
+ // The boundary check (`<skill>` open token) must reject `<skills>` —
+ // matching it would silently swallow the agent's skill list.
+ const buf = '<agent>\n<skills>\nfoo-skill\n</skills>\n</agent>';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toBe(buf);
+ });
+
+ it('B2. literal `<skill>` inside a fenced ```xml block (protocol explanation)', () => {
+ // LLM showing the user the protocol shape inside a code fence must
+ // not be processed as a real container.
+ const buf = 'See:\n```xml\n<skill>\n<skill_id>foo</skill_id>\n</skill>\n```\nend';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toBe(buf);
+ });
+
+ it('B3. literal `<skill>` inside an inline backtick span', () => {
+ const buf = 'use the `<skill>` container to wrap things';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toBe(buf);
+ });
+
+ it('B4. bare prose with no `<skill>` token returns input unchanged', () => {
+ const buf = 'I will write a skill that does X';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toBe(buf);
+ });
+
+ it('B5. empty / falsy input', () => {
+ expect(_stripSkillCreateContainer('', '⟨FALLBACK⟩')).toBe('');
+ expect(_stripSkillCreateContainer(undefined as any, '⟨FALLBACK⟩')).toBe(undefined);
+ });
+});
+
+describe('_splitMarkdownProseCode sanity', () => {
+ it('keeps inline backtick spans as code segments', () => {
+ const segs = _splitMarkdownProseCode('a `b` c');
+ expect(segs.map((s) => s.kind)).toEqual(['prose', 'code', 'prose']);
+ expect(segs[1].text).toBe('`b`');
+ });
+
+ it('treats unclosed inline backtick as code through EOF', () => {
+ const segs = _splitMarkdownProseCode('a `b');
+ expect(segs.map((s) => s.kind)).toEqual(['prose', 'code']);
+ expect(segs[1].text).toBe('`b');
+ });
+
+ it('treats fenced block as code, including info string line', () => {
+ const segs = _splitMarkdownProseCode('intro\n```xml\n<x/>\n```\nend');
+ expect(segs.map((s) => s.kind)).toEqual(['prose', 'code', 'prose']);
+ expect(segs[1].text).toContain('```xml');
+ expect(segs[1].text).toContain('```');
+ });
+});