Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(core,server,web): memory-style prompt injection toggles for skills, vault and schedules (#257)

Yaowei Zheng4f067816149f
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index f729bc53..1e25f522 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -17,6 +17,7 @@ import {
formatModelRef,
getModel,
listInstalledSkills,
+ listScheduleNames,
loadAgentVault,
loadOrInitAgentState,
loadProjectConfig,
@@ -262,6 +263,13 @@ export class Agent {
this.state.projectId,
this.state.agentId,
);
+ // Schedule task names for the {{SCHEDULES}} roster: read fresh like the vault and Skills
+ // above (names only; the files' contents are the server-side scheduler's concern).
+ const scheduleNames = await listScheduleNames(
+ this.state.root,
+ this.state.projectId,
+ this.state.agentId,
+ );
// Memory for this Session: null when the Agent has Memory off; a temporary Workspace gets
// the user scope only (nothing written against it could ever be read back). Reads the
// current indexes every time, like the vault and Skills above.
@@ -278,7 +286,7 @@ export class Agent {
// into the prompt (so the model knows which API keys are available); values only
// go into the subprocess environment. Skills only inject metadata (name and
// description); the model reads the body on demand via shell. Memory likewise injects
- // only its index; topic bodies are read on demand.
+ // only its index; topic bodies are read on demand. Schedules inject only task names.
const systemPrompt = assembleSystemPrompt(
this.state,
sessionEnvironment(workspaceDir, sessionId, {
@@ -290,6 +298,7 @@ export class Agent {
Object.keys(vault),
installedSkills,
memory,
+ scheduleNames,
);
const rt = await this.buildRuntime({
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index 6506bd0a..cc81132f 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -30,6 +30,11 @@ import {
MODEL_ID_PLACEHOLDER,
DATE_PLACEHOLDER,
MEMORY_PLACEHOLDER,
+ VAULT_PLACEHOLDER,
+ SKILLS_PLACEHOLDER,
+ SCHEDULES_PLACEHOLDER,
+ SCHEDULE_LIST_PLACEHOLDER,
+ SCHEDULE_LIST_EMPTY_NOTE,
WORKSPACE_MEMORY_DIR_PLACEHOLDER,
WORKSPACE_MEMORY_INDEX_PLACEHOLDER,
USER_MEMORY_INDEX_PLACEHOLDER,
@@ -38,7 +43,13 @@ import {
MEMORY_INDEX_MAX_CHARS,
DEFAULT_MEMORY_PROMPT,
DEFAULT_MEMORY_WORKSPACE_PROMPT,
+ DEFAULT_VAULT_PROMPT,
+ DEFAULT_SKILLS_PROMPT,
+ DEFAULT_SCHEDULES_PROMPT,
type MemoryConfig,
+ type VaultConfig,
+ type SkillsConfig,
+ type SchedulesConfig,
agentStateVersion,
defaultAgentsMd,
defaultSystemConfig,
@@ -59,6 +70,7 @@ import {
DEFAULT_PROJECT_ID,
memoryDir,
resolveRoot,
+ scheduleDir,
scratchpadDir,
skillsDir,
systemConfigPath,
@@ -275,8 +287,9 @@ export async function resetSystemConfigToDefaults(
* The vault key-name list: the replacement value for `{{VAULT_KEYS}}`, one `- KEY` per line;
* returns an empty string when there are no keys.
* **Contains only key names, never values** — values are only injected into the exec_command
- * subprocess environment, never the model context. The statement of the vault's purpose is part
- * of the default template body (the # Vault section) and is kept even with no vault.
+ * subprocess environment, never the model context. The statement of the vault's purpose lives
+ * in `vault.prompt` (legacy templates carry it in the template body) and is kept even with no
+ * vault.
*/
function vaultKeysList(keys: string[]): string {
return keys.map((key) => `- ${key}`).join("\n");
@@ -357,6 +370,64 @@ function memorySection(
.trim();
}
+/**
+ * The `{{VAULT}}` replacement value: the Agent's `vault.prompt` (missing key falls back to the
+ * built-in default, matching memorySection and the config DTO) with its `{{VAULT_KEYS}}`
+ * injection point replaced by the key-name list. An empty string when the section is switched
+ * off (`vault.enabled === false`) or no key data was supplied at all; an empty key **list**
+ * still renders the statement, so the model is told what the vault is even when it is empty.
+ */
+function vaultSection(config: VaultConfig | undefined, keys: string[] | undefined): string {
+ if (config?.enabled === false || keys === undefined) return "";
+ const promptText = config?.prompt ?? DEFAULT_VAULT_PROMPT;
+ return promptText.split(VAULT_KEYS_PLACEHOLDER).join(vaultKeysList(keys)).trim();
+}
+
+/**
+ * The `{{SKILLS}}` replacement value: the Agent's `skills.prompt` (default fallback like
+ * memorySection) with its `{{SKILL_METADATA}}` injection point replaced by the installed
+ * Skills' metadata lines. An empty string when the section is switched off
+ * (`skills.enabled === false`) or no skill data was supplied at all; an empty skill **list**
+ * still renders the statement. Metadata only — bodies are read on demand via shell.
+ */
+function skillsSection(
+ config: SkillsConfig | undefined,
+ skills: SkillMetadata[] | undefined,
+): string {
+ if (config?.enabled === false || skills === undefined) return "";
+ const promptText = config?.prompt ?? DEFAULT_SKILLS_PROMPT;
+ return promptText.split(SKILL_METADATA_PLACEHOLDER).join(skillMetadataSection(skills)).trim();
+}
+
+/**
+ * The `{{SCHEDULE_LIST}}` roster: one `- name` line per schedule file, or the empty note so
+ * the model reads "no tasks" instead of a blank line under `Current tasks:` (the same empty
+ * handling as indexForInjection). Names only — the model opens the files it needs.
+ */
+function scheduleListForInjection(names: string[]): string {
+ if (names.length === 0) return SCHEDULE_LIST_EMPTY_NOTE;
+ return names.map((name) => `- ${name}`).join("\n");
+}
+
+/**
+ * The `{{SCHEDULES}}` replacement value: the Agent's `schedules.prompt` (default fallback like
+ * memorySection) with its `{{SCHEDULE_LIST}}` injection point replaced by the task-name
+ * roster. An empty string when the section is switched off (`schedules.enabled === false`) or
+ * no roster was supplied at all; an empty roster still renders the guidance with the empty
+ * note, so the model learns the task system before the first task exists.
+ */
+function schedulesSection(
+ config: SchedulesConfig | undefined,
+ scheduleNames: string[] | undefined,
+): string {
+ if (config?.enabled === false || scheduleNames === undefined) return "";
+ const promptText = config?.prompt ?? DEFAULT_SCHEDULES_PROMPT;
+ return promptText
+ .split(SCHEDULE_LIST_PLACEHOLDER)
+ .join(scheduleListForInjection(scheduleNames))
+ .trim();
+}
+
/**
* Guards a Skill auxiliary-file path (relative to the skill directory) before it's written:
* rejects empty, absolute, backslash-bearing, and any `..`-segment path so a file entry can never
@@ -506,6 +577,30 @@ export function skillMetadataSection(skills: SkillMetadata[]): string {
.join("\n");
}
+/**
+ * Task names of the Agent's schedule files: the `agent_state/schedule/*.toml` basenames minus
+ * the extension, sorted by name (the stable order Prompt injection wants); [] when the
+ * directory does not exist (schedules unconfigured). Names only, contents never read — the
+ * `{{SCHEDULE_LIST}}` roster needs just the identities, and file validity is the scheduler's
+ * concern (server-side).
+ */
+export async function listScheduleNames(
+ root: string,
+ projectId: string,
+ agentId: string,
+): Promise<string[]> {
+ assertValidId("project_id", projectId);
+ assertValidId("agent_id", agentId);
+ try {
+ return (await fs.readdir(scheduleDir(root, projectId, agentId), { withFileTypes: true }))
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".toml"))
+ .map((entry) => entry.name.slice(0, -".toml".length))
+ .sort((a, b) => a.localeCompare(b));
+ } catch {
+ return [];
+ }
+}
+
/**
* Windows compatibility fallback for pre-`{{SHELL}}` system prompt templates.
*
@@ -543,28 +638,40 @@ function withShellLineFallback(
return `${assembled}\n${line}`;
}
+/** The four section placeholders, expanded together in one final pass (see assembleSystemPrompt). */
+const SECTION_PLACEHOLDER_PATTERN = /\{\{(?:MEMORY|VAULT|SKILLS|SCHEDULES)\}\}/g;
+
/**
- * Renders the complete runtime system Prompt: substitutes `AGENTS.md`, vault key names, Skill
- * metadata, and the concrete Session runtime environment placeholders into the system Prompt
+ * Renders the complete runtime system Prompt: substitutes `AGENTS.md`, the per-feature section
+ * blocks, and the concrete Session runtime environment placeholders into the system Prompt
* template. The assembly layer only does placeholder substitution and adds no extra text —
- * wrapper text such as `[developer_instructions]` and the # Vault / # Skills statements are
- * written directly into the system Prompt template itself (the Prompt is fully
- * transparent and editable via `system_config.yaml`). Other files in Agent State / Workspace are
- * never auto-injected. Sole exception: on win32 a template without `{{SHELL}}` gets a
- * `- Shell:` line injected at render time (see `withShellLineFallback`).
+ * wrapper text such as `[developer_instructions]` is written directly into the system Prompt
+ * template, and the # Vault / # Skills / # Memory / # Scheduled Tasks statements live in the
+ * editable `vault.prompt` / `skills.prompt` / `memory.prompt` / `schedules.prompt` config (the
+ * Prompt is fully transparent and editable via `system_config.yaml`). Other files in Agent
+ * State / Workspace are never auto-injected. Sole exception: on win32 a template without
+ * `{{SHELL}}` gets a `- Shell:` line injected at render time (see `withShellLineFallback`).
+ *
+ * `{{VAULT}}` expands to the rendered `vault.prompt` (its `{{VAULT_KEYS}}` carrying the
+ * key-name list — names only, values never enter the context), `{{SKILLS}}` to `skills.prompt`
+ * (its `{{SKILL_METADATA}}` carrying metadata lines; bodies are read on demand), `{{MEMORY}}`
+ * to the rendered `memory.prompt` block (plus `memory.workspace_prompt` in a persistent
+ * Workspace; only its own `{{USER_MEMORY_INDEX}}` / `{{WORKSPACE_MEMORY_INDEX}}` carry Memory
+ * content, indexes capped, and `{{WORKSPACE_MEMORY_DIR}}` renders the Workspace Memory
+ * directory), and `{{SCHEDULES}}` to `schedules.prompt` (its `{{SCHEDULE_LIST}}` carrying the
+ * task-name roster). Each expands to an empty string when its feature toggle is off. A custom
+ * template that removes a placeholder gets no corresponding content injected — the Web App's
+ * feature tabs offer inserting the placeholders explicitly.
*
- * `{{VAULT_KEYS}}` is replaced with the vault key-name list (an empty string if empty/not
- * provided): this lets the model know which APIs requiring a key it can call; values are never
- * injected. `{{SKILL_METADATA}}` is replaced with the installed Skills' metadata lines (an empty
- * string if empty/not provided). `{{MEMORY}}` expands to the rendered `memory.prompt` block
- * (plus `memory.workspace_prompt` in a persistent Workspace), and to an empty string when
- * Memory is disabled — only those blocks' own `{{USER_MEMORY_INDEX}}` /
- * `{{WORKSPACE_MEMORY_INDEX}}` carry Memory content (indexes capped, topic bodies always read
- * on demand), and `{{WORKSPACE_MEMORY_DIR}}` renders the Workspace Memory directory right in
- * the workspace half. A custom template that removes a placeholder gets no corresponding
- * content injected — a template without `{{MEMORY}}` injects no Memory, and the Web App's
- * Memory tab offers inserting the placeholder explicitly. `{{PROJECT_DIR}}` resolves to the
- * Project directory — the app data root the default prompt labels "App Data Dir".
+ * The four section placeholders expand LAST and in a **single pass** (one replace over the
+ * otherwise-assembled template): every replacement product — index lines the model wrote,
+ * task names, editable section prompts — lands after all other placeholders were consumed and
+ * is itself never rescanned, so no section's content can smuggle a `{{VAULT_KEYS}}`-style
+ * token into a second expansion, and no section can trigger another section's expansion
+ * either.
+ *
+ * `{{PROJECT_DIR}}` resolves to the Project directory — the app data root the default prompt
+ * labels "App Data Dir".
* Docs: /docs/configuration § "System prompt placeholders".
*/
export function assembleSystemPrompt(
@@ -573,15 +680,38 @@ export function assembleSystemPrompt(
vaultKeys?: string[],
skillMetadata?: SkillMetadata[],
memory?: SessionMemory | null,
+ scheduleNames?: string[],
): string {
const template = state.systemConfig.system_prompt;
+ // Legacy template-level inline substitution (compatibility): system_config.yaml is baked at
+ // Agent creation and never auto-upgraded, so templates from before the {{VAULT}}/{{SKILLS}}
+ // section placeholders carry {{VAULT_KEYS}}/{{SKILL_METADATA}} directly in the template body
+ // (inside their hardcoded # Vault / # Skills sections). Those keep substituting here — but
+ // honor the new toggles: a disabled feature renders them as empty strings, so the switches
+ // work on old templates too. In a current template these tokens only appear inside
+ // vault.prompt / skills.prompt and are handled by the section renderers instead.
+ // Retirement condition: remove this template-level substitution (leaving the tokens to the
+ // section renderers alone) once pre-{{VAULT}}/{{SKILLS}} templates are no longer expected in
+ // the wild — same horizon as LEGACY_VAULT_SECTION / LEGACY_SKILLS_SECTION.
+ const inlineVaultKeys =
+ state.systemConfig.vault?.enabled === false ? "" : vaultKeysList(vaultKeys ?? []);
+ const inlineSkillMetadata =
+ state.systemConfig.skills?.enabled === false ? "" : skillMetadataSection(skillMetadata ?? []);
+ // The single-pass replacement values for the four section placeholders (see the doc comment
+ // above for why they expand last and are never rescanned).
+ const sections: Record<string, string> = {
+ [MEMORY_PLACEHOLDER]: memorySection(state.systemConfig.memory, memory),
+ [VAULT_PLACEHOLDER]: vaultSection(state.systemConfig.vault, vaultKeys),
+ [SKILLS_PLACEHOLDER]: skillsSection(state.systemConfig.skills, skillMetadata),
+ [SCHEDULES_PLACEHOLDER]: schedulesSection(state.systemConfig.schedules, scheduleNames),
+ };
const assembled = template
.split(AGENTS_MD_PLACEHOLDER)
.join(state.agentsMd.trim())
.split(VAULT_KEYS_PLACEHOLDER)
- .join(vaultKeysList(vaultKeys ?? []))
+ .join(inlineVaultKeys)
.split(SKILL_METADATA_PLACEHOLDER)
- .join(skillMetadataSection(skillMetadata ?? []))
+ .join(inlineSkillMetadata)
.split(AGENT_ID_PLACEHOLDER)
.join(sessionEnvironment?.agentId ?? state.agentId)
.split(PROJECT_DIR_PLACEHOLDER)
@@ -602,11 +732,10 @@ export function assembleSystemPrompt(
.join(sessionEnvironment?.shell ?? "")
.split(DATE_PLACEHOLDER)
.join(sessionEnvironment?.date ?? "")
- // {{MEMORY}} expands last: everything the Memory block carries (index lines the model wrote
- // included) lands after the other placeholders were consumed, so index content can never
- // smuggle a {{VAULT_KEYS}}-style token into a second expansion.
- .split(MEMORY_PLACEHOLDER)
- .join(memorySection(state.systemConfig.memory, memory))
+ // The section placeholders expand last, all four in this one replace: a replacer
+ // function's return value is spliced in verbatim (no `$`-pattern handling) and the scan
+ // continues after it, so nothing a section carries is ever expanded again.
+ .replace(SECTION_PLACEHOLDER_PATTERN, (token) => sections[token] ?? token)
.trim();
return withShellLineFallback(assembled, template, sessionEnvironment);
}
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index 605b2668..07d25179 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -9,20 +9,32 @@
*
* The system Prompt is sectioned and trimmed as needed (Role/Personality/Success
* criteria/Constraints/Stop rules/Tool use/System markers/File system/Suggested workflows); it
- * does not describe specific tools (that comes from the tool schema). AGENTS.md, Vault/Skills,
- * and Environment injection go at the end.
+ * does not describe specific tools (that comes from the tool schema). AGENTS.md and the
+ * Vault/Skills/Memory/Schedules section placeholders go at the end, before Environment.
*
* Placeholders (`{{...}}`) appear only in the trailing injection zones (AGENTS.md / Vault /
- * Skills / Environment); elsewhere the body uses angle-bracket notation such as
- * \`<app_data_dir>\`, \`<agent_id>\`, \`<session_id>\` — these are **not substituted**; the model
- * fills in the actual values from the Environment section itself.
+ * Skills / Memory / Schedules / Environment); elsewhere the body uses angle-bracket notation
+ * such as \`<app_data_dir>\`, \`<agent_id>\`, \`<session_id>\` — these are **not substituted**;
+ * the model fills in the actual values from the Environment section itself.
*/
import type { MCPServerConfig, ThinkingLevelName, ToolDefinitionConfig } from "../interfaces.js";
import type { CompactionMode } from "../omnimessage/types.js";
/** Docs: /docs/configuration § "System prompt placeholders". */
export const AGENTS_MD_PLACEHOLDER = "{{AGENTS_MD}}";
+/**
+ * Inside `vault.prompt`: the vault key-name list, one `- KEY` per line — names only, never
+ * values. Also still substituted when written directly in the template body, for templates
+ * from before the `{{VAULT}}` section placeholder (see assembleSystemPrompt's legacy inline
+ * compatibility), where it honors `vault.enabled` the same way.
+ */
export const VAULT_KEYS_PLACEHOLDER = "{{VAULT_KEYS}}";
+/**
+ * Inside `skills.prompt`: the installed Skills' metadata lines. Also still substituted when
+ * written directly in the template body, for templates from before the `{{SKILLS}}` section
+ * placeholder (see assembleSystemPrompt's legacy inline compatibility), where it honors
+ * `skills.enabled` the same way.
+ */
export const SKILL_METADATA_PLACEHOLDER = "{{SKILL_METADATA}}";
export const SESSION_ID_PLACEHOLDER = "{{SESSION_ID}}";
export const CWD_PLACEHOLDER = "{{CWD}}";
@@ -55,6 +67,32 @@ export const WORKSPACE_MEMORY_DIR_PLACEHOLDER = "{{WORKSPACE_MEMORY_DIR}}";
export const WORKSPACE_MEMORY_INDEX_PLACEHOLDER = "{{WORKSPACE_MEMORY_INDEX}}";
/** Inside either Memory prompt: the content of the User scope's `MEMORY.md` index (capped, see MEMORY_INDEX_MAX_LINES / MEMORY_INDEX_MAX_CHARS). */
export const USER_MEMORY_INDEX_PLACEHOLDER = "{{USER_MEMORY_INDEX}}";
+/**
+ * Expands to the rendered `vault.prompt` block (the # Vault section statement plus the
+ * `{{VAULT_KEYS}}` key-name list); an empty string when the Vault section is off. A template
+ * without this placeholder injects no Vault section at all — the Web App's Vault tab offers
+ * inserting it (or migrating a legacy hardcoded section) as an explicit action, nothing is
+ * spliced in automatically.
+ */
+export const VAULT_PLACEHOLDER = "{{VAULT}}";
+/**
+ * Expands to the rendered `skills.prompt` block (the # Skills section statement plus the
+ * `{{SKILL_METADATA}}` metadata lines); an empty string when the Skills section is off. A
+ * template without this placeholder injects no Skills section at all — the Web App's Skills
+ * tab offers inserting it (or migrating a legacy hardcoded section) as an explicit action,
+ * nothing is spliced in automatically.
+ */
+export const SKILLS_PLACEHOLDER = "{{SKILLS}}";
+/**
+ * Expands to the rendered `schedules.prompt` block (the # Scheduled Tasks section teaching
+ * file-based task management, plus the `{{SCHEDULE_LIST}}` task roster); an empty string when
+ * the Schedules section is off. A template without this placeholder injects no Schedules
+ * section at all — the Web App's Schedules tab offers inserting it as an explicit action,
+ * nothing is spliced in automatically.
+ */
+export const SCHEDULES_PLACEHOLDER = "{{SCHEDULES}}";
+/** Inside `schedules.prompt` only: the current schedule-file names, one `- name` per line (SCHEDULE_LIST_EMPTY_NOTE when none exist). */
+export const SCHEDULE_LIST_PLACEHOLDER = "{{SCHEDULE_LIST}}";
/**
* Context compaction config (the `compaction` section of `system_config.yaml`).
@@ -95,9 +133,56 @@ export interface MemoryConfig {
workspace_prompt?: string;
}
+/**
+ * Vault prompt-injection config (the `vault` section of `system_config.yaml`). The prompt is
+ * editable on the Web App's Vault tab and rendered into the template's `{{VAULT}}` placeholder.
+ * The toggle governs prompt injection only: with it off, vault values are still injected into
+ * shell subprocess environments — the model is just not shown the key-name roster.
+ * Docs: /docs/configuration § "Vault".
+ */
+export interface VaultConfig {
+ /** Whether the Vault section enters the model context; defaults to true. */
+ enabled?: boolean;
+ /** The `{{VAULT}}` block: the section statement carrying the `{{VAULT_KEYS}}` key-name injection point. Defaults to the built-in value. */
+ prompt?: string;
+}
+
+/**
+ * Skills prompt-injection config (the `skills` section of `system_config.yaml`). The prompt is
+ * editable on the Web App's Skills tab and rendered into the template's `{{SKILLS}}`
+ * placeholder. The toggle governs prompt injection only: with it off, installed Skills stay on
+ * disk and can still be invoked explicitly (e.g. via a [use_skills] block naming them) — the
+ * model is just not shown the roster.
+ * Docs: /docs/skills.
+ */
+export interface SkillsConfig {
+ /** Whether the Skills section enters the model context; defaults to true. */
+ enabled?: boolean;
+ /** The `{{SKILLS}}` block: the section statement carrying the `{{SKILL_METADATA}}` metadata-line injection point. Defaults to the built-in value. */
+ prompt?: string;
+}
+
+/**
+ * Schedules prompt-injection config (the `schedules` section of `system_config.yaml`). The
+ * prompt is editable on the Web App's Schedules tab and rendered into the template's
+ * `{{SCHEDULES}}` placeholder. The toggle governs prompt injection only: with it off, the
+ * server still fires configured tasks on time — the model is just not taught the file-based
+ * task system.
+ * Docs: /docs/configuration § "Schedules".
+ */
+export interface SchedulesConfig {
+ /** Whether the Scheduled Tasks section enters the model context; defaults to true. */
+ enabled?: boolean;
+ /** The `{{SCHEDULES}}` block: the file-based task-management guidance carrying the `{{SCHEDULE_LIST}}` roster injection point. Defaults to the built-in value. */
+ prompt?: string;
+}
+
/** Stands in for an index placeholder when the `MEMORY.md` does not exist yet or is blank — the model is told the store is empty rather than being handed nothing. */
export const MEMORY_INDEX_EMPTY_NOTE = "(the index is empty — nothing has been saved yet)";
+/** Stands in for `{{SCHEDULE_LIST}}` when no schedule files exist yet — the model is told the roster is empty rather than being handed nothing (mirrors MEMORY_INDEX_EMPTY_NOTE). */
+export const SCHEDULE_LIST_EMPTY_NOTE = "(no scheduled tasks defined yet)";
+
/**
* Cap on injected index lines per scope (one memory per line by convention), so a runaway
* `MEMORY.md` cannot flood the context. Only the injection is capped — the file on disk is
@@ -165,6 +250,74 @@ Workspace Memory Dir: \`{{WORKSPACE_MEMORY_DIR}}\`
Index:
{{WORKSPACE_MEMORY_INDEX}}`;
+/**
+ * The pre-`{{VAULT}}` default template's hardcoded # Vault section, frozen verbatim (its
+ * trailing inline `{{VAULT_KEYS}}` included) so `insertVaultPlaceholder` can migrate a stored
+ * legacy template by exact replacement — `system_config.yaml` is materialized at Agent
+ * creation and never auto-upgraded, so existing templates carry this text until that explicit
+ * action. Never edit this constant: it must keep matching what old yaml files actually
+ * contain, even after `DEFAULT_VAULT_PROMPT` evolves away from it.
+ *
+ * Retirement condition: remove together with `insertVaultPlaceholder`'s migration branch once
+ * pre-`{{VAULT}}` templates (Agents created before the section placeholder shipped) are no
+ * longer expected in the wild.
+ */
+export const LEGACY_VAULT_SECTION = `# Vault
+The vault holds this agent's per-agent secrets (agent_state/.vault.toml). Each entry is injected into your shell subprocesses as an environment variable — values never appear in your context. Use the variable names below in commands when a task needs them.
+${VAULT_KEYS_PLACEHOLDER}`;
+
+/**
+ * The pre-`{{SKILLS}}` default template's hardcoded # Skills section, frozen verbatim (its
+ * trailing inline `{{SKILL_METADATA}}` included) for `insertSkillsPlaceholder`'s migration
+ * branch. Same freeze rule and retirement condition as `LEGACY_VAULT_SECTION`.
+ */
+export const LEGACY_SKILLS_SECTION = `# Skills
+Skills are reusable instruction packages at \`<app_data_dir>/agents/<agent_id>/agent_state/skills/<skill_name>/SKILL.md\`. When a task matches one below, or the user asks for one (the message may start with a [use_skills] block naming them), read that SKILL.md in full with read_file, then follow it. If a request names a skill without a concrete task, ask the user what they need first.
+${SKILL_METADATA_PLACEHOLDER}`;
+
+/**
+ * Built-in default Vault Prompt: what `{{VAULT}}` expands to — currently word-for-word the
+ * section the pre-toggle default template hardcoded (the toggle refactor moved the text into
+ * editable config without changing a word), ending in the `{{VAULT_KEYS}}` key-name list.
+ * Stored per-Agent in `system_config.yaml` and editable on the Web App's Vault tab. A future
+ * wording change goes here (as a new literal); the legacy constant stays frozen.
+ */
+export const DEFAULT_VAULT_PROMPT = LEGACY_VAULT_SECTION;
+
+/**
+ * Built-in default Skills Prompt: what `{{SKILLS}}` expands to — currently word-for-word the
+ * legacy hardcoded section (same move-not-reword relationship as `DEFAULT_VAULT_PROMPT`),
+ * ending in the `{{SKILL_METADATA}}` metadata lines. Stored per-Agent in `system_config.yaml`
+ * and editable on the Web App's Skills tab.
+ */
+export const DEFAULT_SKILLS_PROMPT = LEGACY_SKILLS_SECTION;
+
+/**
+ * Built-in default Schedules Prompt: what `{{SCHEDULES}}` expands to — teaches the model to
+ * manage scheduled tasks as TOML files with its ordinary file tools (there is no dedicated
+ * tool), in template-example form like DEFAULT_MEMORY_PROMPT: the directory as a literal
+ * angle-bracket pattern resolvable from the Environment section, a fenced example, the field
+ * rules schedule-file.ts enforces, the hygiene rules, then the current roster via
+ * `{{SCHEDULE_LIST}}`. Stored per-Agent in `system_config.yaml` and editable on the Web App's
+ * Schedules tab.
+ */
+export const DEFAULT_SCHEDULES_PROMPT = `# Scheduled Tasks
+Prompts delivered to this agent on a timer: TOML files you manage with the file tools, in \`<app_data_dir>/agents/<agent_id>/agent_state/schedule/\` (create the directory if it does not exist). One task per file; the file name minus \`.toml\` is the task's name (letters, digits, \`_\` and \`-\` only). The server re-reads the directory within about 30 seconds — creating, editing or deleting a file is all it takes, there is nothing to register.
+
+\`\`\`toml
+prompt = "Check yesterday's build results and summarize the failures"
+enabled = true
+start_at = 2026-08-01T09:00:00Z
+period = "12h"
+\`\`\`
+
+Field rules: \`prompt\` (required) is the message sent when the task fires. \`enabled\` defaults to false — set it to true explicitly or the task never runs. \`start_at\` (required) is the first trigger time, an ISO 8601 instant. \`period\` is a fixed interval like \`30m\` / \`12h\` / \`7d\` (5 minutes minimum); omit it for a one-shot task. \`end_at\` (optional) must be later than start_at; a periodic task stops after it. Each trigger starts a new Session by default: \`workspace\` (optional) picks its working directory, and \`provider\` + \`model_id\` pick its model — always both or neither; omit both to use the Project's default model. Setting \`session_id\` instead sends the prompt into an existing Session, and cannot be combined with workspace / provider / model_id.
+
+Check the current tasks below before creating one so you never duplicate an existing task; change a task by editing its file in place; delete the file when a task is obsolete.
+
+Current tasks:
+${SCHEDULE_LIST_PLACEHOLDER}`;
+
/**
* System-level config for Agent State, serialized as `system_config.yaml`.
* Docs: /docs/configuration § "Agent config".
@@ -193,6 +346,12 @@ export interface SystemConfig {
compaction?: CompactionConfig;
/** Memory (enabled by default; only reaches the prompt through the template's `{{MEMORY}}` placeholder). */
memory?: MemoryConfig;
+ /** Vault section injection (enabled by default; reaches the prompt through `{{VAULT}}`, or a legacy template's inline `{{VAULT_KEYS}}`). */
+ vault?: VaultConfig;
+ /** Skills section injection (enabled by default; reaches the prompt through `{{SKILLS}}`, or a legacy template's inline `{{SKILL_METADATA}}`). */
+ skills?: SkillsConfig;
+ /** Scheduled-tasks section injection (enabled by default; only reaches the prompt through `{{SCHEDULES}}`). */
+ schedules?: SchedulesConfig;
tools?: {
/** Built-in system tool configuration (per-entry fields incl. the `call_description` toggle live on ToolDefinitionConfig). */
builtin?: ToolDefinitionConfig[];
@@ -254,16 +413,14 @@ Custom instructions from the developer-editable AGENTS.md.
{{AGENTS_MD}}
[/developer_instructions]
-# Vault
-The vault holds this agent's per-agent secrets (agent_state/.vault.toml). Each entry is injected into your shell subprocesses as an environment variable — values never appear in your context. Use the variable names below in commands when a task needs them.
-{{VAULT_KEYS}}
+{{VAULT}}
-# Skills
-Skills are reusable instruction packages at \`<app_data_dir>/agents/<agent_id>/agent_state/skills/<skill_name>/SKILL.md\`. When a task matches one below, or the user asks for one (the message may start with a [use_skills] block naming them), read that SKILL.md in full with read_file, then follow it. If a request names a skill without a concrete task, ask the user what they need first.
-{{SKILL_METADATA}}
+{{SKILLS}}
{{MEMORY}}
+{{SCHEDULES}}
+
# Environment
- Platform: {{PLATFORM}}
- OS Version: {{OS_VERSION}}
@@ -281,6 +438,19 @@ export function hasMemoryPlaceholder(template: string): boolean {
return template.includes(MEMORY_PLACEHOLDER);
}
+/**
+ * Shared insertion for the section placeholders: before the `# Environment` heading (the
+ * position the default template gives them), else appended at the end. Idempotent — a
+ * template already carrying the placeholder is returned unchanged.
+ */
+function insertSectionPlaceholder(template: string, placeholder: string): string {
+ if (template.includes(placeholder)) return template;
+ const heading = /^#+ Environment[ \t]*$/m.exec(template);
+ return heading
+ ? `${template.slice(0, heading.index)}${placeholder}\n\n${template.slice(heading.index)}`
+ : `${template.trimEnd()}\n\n${placeholder}\n`;
+}
+
/**
* Inserts the `{{MEMORY}}` placeholder into a template: before the `# Environment` heading
* (the position the default template gives it), else appended at the end. Idempotent — a
@@ -289,11 +459,63 @@ export function hasMemoryPlaceholder(template: string): boolean {
* inserts automatically.
*/
export function insertMemoryPlaceholder(template: string): string {
- if (template.includes(MEMORY_PLACEHOLDER)) return template;
- const heading = /^#+ Environment[ \t]*$/m.exec(template);
- return heading
- ? `${template.slice(0, heading.index)}${MEMORY_PLACEHOLDER}\n\n${template.slice(heading.index)}`
- : `${template.trimEnd()}\n\n${MEMORY_PLACEHOLDER}\n`;
+ return insertSectionPlaceholder(template, MEMORY_PLACEHOLDER);
+}
+
+/** Whether a template carries the `{{VAULT}}` placeholder (a legacy inline `{{VAULT_KEYS}}` still injects the key list, but no section prompt). */
+export function hasVaultPlaceholder(template: string): boolean {
+ return template.includes(VAULT_PLACEHOLDER);
+}
+
+/** Whether a template carries the `{{SKILLS}}` placeholder (a legacy inline `{{SKILL_METADATA}}` still injects the metadata lines, but no section prompt). */
+export function hasSkillsPlaceholder(template: string): boolean {
+ return template.includes(SKILLS_PLACEHOLDER);
+}
+
+/** Whether a template carries the `{{SCHEDULES}}` placeholder — without it no Scheduled Tasks section is injected. */
+export function hasSchedulesPlaceholder(template: string): boolean {
+ return template.includes(SCHEDULES_PLACEHOLDER);
+}
+
+/**
+ * Inserts the `{{VAULT}}` placeholder into a template, migration-first: a template still
+ * carrying the legacy hardcoded # Vault section verbatim gets that text replaced in place by
+ * the placeholder (the section's wording lives on as `vault.prompt`'s default, so the
+ * assembled prompt is unchanged); otherwise the placeholder is inserted before
+ * `# Environment` / appended, like `insertMemoryPlaceholder`. Idempotent, and the explicit
+ * adoption path offered by the Web App's Vault tab — nothing ever migrates automatically.
+ *
+ * Retirement condition: drop the migration branch together with `LEGACY_VAULT_SECTION` once
+ * pre-`{{VAULT}}` templates are no longer expected in the wild.
+ */
+export function insertVaultPlaceholder(template: string): string {
+ if (template.includes(VAULT_PLACEHOLDER)) return template;
+ if (template.includes(LEGACY_VAULT_SECTION)) {
+ return template.split(LEGACY_VAULT_SECTION).join(VAULT_PLACEHOLDER);
+ }
+ return insertSectionPlaceholder(template, VAULT_PLACEHOLDER);
+}
+
+/**
+ * Inserts the `{{SKILLS}}` placeholder into a template, migration-first over
+ * `LEGACY_SKILLS_SECTION` — same semantics and retirement condition as
+ * `insertVaultPlaceholder`.
+ */
+export function insertSkillsPlaceholder(template: string): string {
+ if (template.includes(SKILLS_PLACEHOLDER)) return template;
+ if (template.includes(LEGACY_SKILLS_SECTION)) {
+ return template.split(LEGACY_SKILLS_SECTION).join(SKILLS_PLACEHOLDER);
+ }
+ return insertSectionPlaceholder(template, SKILLS_PLACEHOLDER);
+}
+
+/**
+ * Inserts the `{{SCHEDULES}}` placeholder into a template: before `# Environment`, else
+ * appended (no legacy form exists — Schedules never had a hardcoded template section).
+ * Idempotent; the explicit adoption path offered by the Web App's Schedules tab.
+ */
+export function insertSchedulesPlaceholder(template: string): string {
+ return insertSectionPlaceholder(template, SCHEDULES_PLACEHOLDER);
}
/**
@@ -652,6 +874,18 @@ export function defaultSystemConfig(): SystemConfig {
prompt: DEFAULT_MEMORY_PROMPT,
workspace_prompt: DEFAULT_MEMORY_WORKSPACE_PROMPT,
},
+ vault: {
+ enabled: true,
+ prompt: DEFAULT_VAULT_PROMPT,
+ },
+ skills: {
+ enabled: true,
+ prompt: DEFAULT_SKILLS_PROMPT,
+ },
+ schedules: {
+ enabled: true,
+ prompt: DEFAULT_SCHEDULES_PROMPT,
+ },
tools: {
builtin: defaultBuiltinTools(),
mcpServers: [],
diff --git a/packages/core/test/builtin-agents.test.ts b/packages/core/test/builtin-agents.test.ts
index f318a084..4f7ef1e4 100644
--- a/packages/core/test/builtin-agents.test.ts
+++ b/packages/core/test/builtin-agents.test.ts
@@ -127,18 +127,25 @@ describe("provisionProjectAgents", () => {
describe("App Data Dir / Agent ID placeholders", () => {
it("assembleSystemPrompt injects App Data Dir and Agent ID (Skill lookup uses app-data-dir-relative paths, no .penguin dependency)", async () => {
const state = await loadOrInitAgentState({ agentId: "env_agent" });
- const prompt = assembleSystemPrompt(state, {
- sessionId: "session-x",
- cwd: "/tmp/ws",
- agentId: "env_agent",
- projectDir: "/tmp/proj",
- provider: "deepseek",
- modelId: "deepseek-v4-pro",
- platform: "linux",
- osVersion: "test",
- shell: "bash",
- date: "2026-07-08",
- });
+ // Skill data provided (an empty list) so the {{SKILLS}} section — home of the skill
+ // lookup path convention this test pins — renders.
+ const prompt = assembleSystemPrompt(
+ state,
+ {
+ sessionId: "session-x",
+ cwd: "/tmp/ws",
+ agentId: "env_agent",
+ projectDir: "/tmp/proj",
+ provider: "deepseek",
+ modelId: "deepseek-v4-pro",
+ platform: "linux",
+ osVersion: "test",
+ shell: "bash",
+ date: "2026-07-08",
+ },
+ undefined,
+ [],
+ );
expect(prompt).toContain("Agent ID: env_agent");
expect(prompt).toContain("App Data Dir: /tmp/proj");
expect(prompt).not.toContain("{{AGENT_ID}}");
diff --git a/packages/core/test/memory.test.ts b/packages/core/test/memory.test.ts
index d7358000..94c4af76 100644
--- a/packages/core/test/memory.test.ts
+++ b/packages/core/test/memory.test.ts
@@ -342,7 +342,9 @@ describe("{{MEMORY}} rendering", () => {
it("injects nothing at all when the Session has no Memory", async () => {
const state = await agentState();
- const prompt = assembleSystemPrompt(state);
+ // Skill data provided (an empty list) so the neighboring {{SKILLS}} section renders and
+ // proves it is untouched by Memory's absence.
+ const prompt = assembleSystemPrompt(state, undefined, undefined, []);
expect(prompt).not.toContain("{{MEMORY}}");
expect(prompt).not.toContain("# Memory");
expect(prompt).not.toContain(USER_LINE);
diff --git a/packages/core/test/prompt-sections.test.ts b/packages/core/test/prompt-sections.test.ts
new file mode 100644
index 00000000..b082d2ae
--- /dev/null
+++ b/packages/core/test/prompt-sections.test.ts
@@ -0,0 +1,358 @@
+/**
+ * The Vault / Skills / Schedules prompt-injection sections (the memory-style
+ * placeholder + toggle + editable prompt pattern): section rendering through the
+ * `{{VAULT}}` / `{{SKILLS}}` / `{{SCHEDULES}}` placeholders, the toggles, the default-prompt
+ * fallbacks, the single-pass expansion property, the legacy inline-placeholder
+ * compatibility, the insert/migrate helpers, and schedule-name collection.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ DEFAULT_AGENT_ID,
+ DEFAULT_PROJECT_ID,
+ VAULT_PLACEHOLDER,
+ SKILLS_PLACEHOLDER,
+ SCHEDULES_PLACEHOLDER,
+ VAULT_KEYS_PLACEHOLDER,
+ SKILL_METADATA_PLACEHOLDER,
+ LEGACY_VAULT_SECTION,
+ LEGACY_SKILLS_SECTION,
+ SCHEDULE_LIST_EMPTY_NOTE,
+ assembleSystemPrompt,
+ createAgent,
+ hasSchedulesPlaceholder,
+ hasSkillsPlaceholder,
+ hasVaultPlaceholder,
+ insertSchedulesPlaceholder,
+ insertSkillsPlaceholder,
+ insertVaultPlaceholder,
+ listScheduleNames,
+ loadOrInitAgentState,
+ scheduleDir,
+ type AgentState,
+ type SystemConfig,
+} from "../src/index.js";
+import { stubProviderKeys } from "./provider-keys.js";
+
+let root: string;
+let restoreKeys: () => void;
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-sections-"));
+ restoreKeys = stubProviderKeys();
+});
+
+afterEach(async () => {
+ restoreKeys();
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+/** Loads a default Agent State under the temp root (creates it on first call). */
+async function agentState(): Promise<AgentState> {
+ return loadOrInitAgentState({ root });
+}
+
+/** A copy of `state` with the given systemConfig fields overridden (in memory only). */
+function withConfig(state: AgentState, patch: Partial<SystemConfig>): AgentState {
+ return { ...state, systemConfig: { ...state.systemConfig, ...patch } };
+}
+
+const DEMO_SKILL = { name: "demo", description: "Demo skill.", version: 1, updated: "2026-08-01" };
+
+describe("{{VAULT}} rendering", () => {
+ it("renders the default vault section with the key-name list", async () => {
+ const prompt = assembleSystemPrompt(await agentState(), undefined, ["KEY_A", "KEY_B"]);
+ expect(prompt).toContain("# Vault");
+ expect(prompt).toContain("- KEY_A\n- KEY_B");
+ expect(prompt).not.toContain(VAULT_PLACEHOLDER);
+ expect(prompt).not.toContain(VAULT_KEYS_PLACEHOLDER);
+ });
+
+ it("still renders the statement for an empty key list, but nothing without key data", async () => {
+ const state = await agentState();
+ // Empty list: the vault's purpose statement stays (the model is told what the vault is).
+ expect(assembleSystemPrompt(state, undefined, [])).toContain("# Vault");
+ // No data at all (direct SDK render): the section is absent, no residue either.
+ const bare = assembleSystemPrompt(state);
+ expect(bare).not.toContain("# Vault");
+ expect(bare).not.toContain(VAULT_PLACEHOLDER);
+ });
+
+ it("injects nothing when the toggle is off", async () => {
+ const state = withConfig(await agentState(), { vault: { enabled: false } });
+ const prompt = assembleSystemPrompt(state, undefined, ["KEY_A"]);
+ expect(prompt).not.toContain("# Vault");
+ expect(prompt).not.toContain("- KEY_A");
+ });
+
+ it("injects nothing into a template without the placeholder — nothing is spliced in", async () => {
+ const state = withConfig(await agentState(), {
+ system_prompt: "# Role\nDo things.\n# Environment",
+ });
+ expect(assembleSystemPrompt(state, undefined, ["KEY_A"])).toBe(
+ "# Role\nDo things.\n# Environment",
+ );
+ });
+
+ it("falls back to the built-in prompt for a config that predates the vault section", async () => {
+ const state = await agentState();
+ const { vault: _vault, ...withoutVault } = state.systemConfig;
+ const legacy: AgentState = { ...state, systemConfig: withoutVault };
+ // The DTO reports the default as effective; rendering must agree.
+ const prompt = assembleSystemPrompt(legacy, undefined, ["KEY_A"]);
+ expect(prompt).toContain("# Vault");
+ expect(prompt).toContain("- KEY_A");
+ });
+
+ it("substitutes {{VAULT_KEYS}} inside a custom vault prompt", async () => {
+ const state = withConfig(await agentState(), {
+ vault: { enabled: true, prompt: `## Secrets\n${VAULT_KEYS_PLACEHOLDER}\nend` },
+ });
+ const prompt = assembleSystemPrompt(state, undefined, ["ONLY_KEY"]);
+ expect(prompt).toContain("## Secrets\n- ONLY_KEY\nend");
+ expect(prompt).not.toContain("# Vault");
+ });
+});
+
+describe("{{SKILLS}} rendering", () => {
+ it("renders the default skills section with metadata lines", async () => {
+ const prompt = assembleSystemPrompt(await agentState(), undefined, undefined, [DEMO_SKILL]);
+ expect(prompt).toContain("# Skills");
+ expect(prompt).toContain("[use_skills]");
+ expect(prompt).toContain("- `demo` — Demo skill.");
+ expect(prompt).not.toContain(SKILLS_PLACEHOLDER);
+ expect(prompt).not.toContain(SKILL_METADATA_PLACEHOLDER);
+ });
+
+ it("still renders the statement for an empty skill list, but nothing without skill data", async () => {
+ const state = await agentState();
+ expect(assembleSystemPrompt(state, undefined, undefined, [])).toContain("# Skills");
+ expect(assembleSystemPrompt(state)).not.toContain("# Skills");
+ });
+
+ it("injects nothing when the toggle is off", async () => {
+ const state = withConfig(await agentState(), { skills: { enabled: false } });
+ const prompt = assembleSystemPrompt(state, undefined, undefined, [DEMO_SKILL]);
+ expect(prompt).not.toContain("# Skills");
+ expect(prompt).not.toContain("- `demo`");
+ });
+
+ it("falls back to the built-in prompt for a config that predates the skills section", async () => {
+ const state = await agentState();
+ const { skills: _skills, ...withoutSkills } = state.systemConfig;
+ const legacy: AgentState = { ...state, systemConfig: withoutSkills };
+ expect(assembleSystemPrompt(legacy, undefined, undefined, [DEMO_SKILL])).toContain(
+ "- `demo` — Demo skill.",
+ );
+ });
+});
+
+describe("{{SCHEDULES}} rendering", () => {
+ it("renders the default schedules section with the task roster", async () => {
+ const prompt = assembleSystemPrompt(await agentState(), undefined, undefined, undefined, null, [
+ "daily-report",
+ "weekly-sync",
+ ]);
+ expect(prompt).toContain("# Scheduled Tasks");
+ expect(prompt).toContain("Current tasks:\n- daily-report\n- weekly-sync");
+ expect(prompt).not.toContain(SCHEDULES_PLACEHOLDER);
+ expect(prompt).not.toContain("{{SCHEDULE_LIST}}");
+ });
+
+ it("states the roster is empty for an empty list, and renders nothing without roster data", async () => {
+ const state = await agentState();
+ // Empty roster: the guidance still teaches the task system, with the empty note in place
+ // of a blank line (the indexForInjection convention).
+ const empty = assembleSystemPrompt(state, undefined, undefined, undefined, null, []);
+ expect(empty).toContain("# Scheduled Tasks");
+ expect(empty).toContain(`Current tasks:\n${SCHEDULE_LIST_EMPTY_NOTE}`);
+ // No roster supplied at all: the section is absent.
+ expect(assembleSystemPrompt(state)).not.toContain("# Scheduled Tasks");
+ });
+
+ it("injects nothing when the toggle is off", async () => {
+ const state = withConfig(await agentState(), { schedules: { enabled: false } });
+ const prompt = assembleSystemPrompt(state, undefined, undefined, undefined, null, ["daily"]);
+ expect(prompt).not.toContain("# Scheduled Tasks");
+ expect(prompt).not.toContain("- daily");
+ });
+
+ it("falls back to the built-in prompt for a config that predates the schedules section", async () => {
+ const state = await agentState();
+ const { schedules: _schedules, ...withoutSchedules } = state.systemConfig;
+ const legacy: AgentState = { ...state, systemConfig: withoutSchedules };
+ expect(
+ assembleSystemPrompt(legacy, undefined, undefined, undefined, null, ["daily"]),
+ ).toContain("Current tasks:\n- daily");
+ });
+});
+
+describe("single-pass section expansion", () => {
+ it("never expands section tokens carried by another section's prompt", async () => {
+ const state = withConfig(await agentState(), {
+ vault: {
+ enabled: true,
+ prompt: `# Vault\n${VAULT_KEYS_PLACEHOLDER}\nsmuggled: {{SKILLS}} {{MEMORY}} {{SCHEDULES}} {{SCHEDULE_LIST}}`,
+ },
+ });
+ const prompt = assembleSystemPrompt(state, undefined, ["KEY_A"], [DEMO_SKILL], null, ["t1"]);
+ // The vault block rendered (its own inner token replaced) …
+ expect(prompt).toContain("- KEY_A");
+ // … but the section tokens it carried stay literal text: the single pass finds tokens in
+ // the template only, and replacer output is never rescanned.
+ expect(prompt).toContain("smuggled: {{SKILLS}} {{MEMORY}} {{SCHEDULES}} {{SCHEDULE_LIST}}");
+ // The template's own {{SKILLS}}/{{SCHEDULES}} still rendered normally.
+ expect(prompt).toContain("- `demo` — Demo skill.");
+ expect(prompt).toContain("Current tasks:\n- t1");
+ });
+
+ it("never expands section tokens smuggled into memory index content", async () => {
+ const prompt = assembleSystemPrompt(
+ await agentState(),
+ undefined,
+ ["KEY_A"],
+ [DEMO_SKILL],
+ {
+ userDir: "/data/memory/user",
+ userIndex: "- [x](x.md) — {{VAULT}} {{SKILLS}} {{SCHEDULES}} {{VAULT_KEYS}}",
+ },
+ [],
+ );
+ expect(prompt).toContain("- [x](x.md) — {{VAULT}} {{SKILLS}} {{SCHEDULES}} {{VAULT_KEYS}}");
+ });
+});
+
+describe("legacy inline placeholders (pre-{{VAULT}}/{{SKILLS}} templates)", () => {
+ /** A minimal legacy-style custom template carrying the inline tokens directly in the body. */
+ function inlineState(state: AgentState, patch?: Partial<SystemConfig>): AgentState {
+ return withConfig(state, {
+ system_prompt: ["before", VAULT_KEYS_PLACEHOLDER, SKILL_METADATA_PLACEHOLDER, "after"].join(
+ "\n",
+ ),
+ ...patch,
+ });
+ }
+
+ it("still substitutes inline {{VAULT_KEYS}} / {{SKILL_METADATA}} at template level", async () => {
+ const state = inlineState(await agentState());
+ const prompt = assembleSystemPrompt(state, undefined, ["KEY_A"], [DEMO_SKILL]);
+ expect(prompt).toBe(["before", "- KEY_A", "- `demo` — Demo skill.", "after"].join("\n"));
+ });
+
+ it("renders inline tokens as empty strings when the toggles are off — the switches govern old templates too", async () => {
+ const state = inlineState(await agentState(), {
+ vault: { enabled: false },
+ skills: { enabled: false },
+ });
+ const prompt = assembleSystemPrompt(state, undefined, ["KEY_A"], [DEMO_SKILL]);
+ expect(prompt).toBe(["before", "", "", "after"].join("\n"));
+ });
+});
+
+describe("insert / migrate helpers", () => {
+ /**
+ * Reconstructs the pre-toggle default template from the current one: the section
+ * placeholders swapped back for the hardcoded sections, and no {{SCHEDULES}} line — exactly
+ * what a stored legacy `system_config.yaml` carries.
+ */
+ function legacyDefaultTemplate(current: string): string {
+ return current
+ .split(VAULT_PLACEHOLDER)
+ .join(LEGACY_VAULT_SECTION)
+ .split(SKILLS_PLACEHOLDER)
+ .join(LEGACY_SKILLS_SECTION)
+ .split(`${SCHEDULES_PLACEHOLDER}\n\n`)
+ .join("");
+ }
+
+ it("migrates a legacy default template back to the current one, placeholder by placeholder", async () => {
+ const current = (await agentState()).systemConfig.system_prompt;
+ const legacy = legacyDefaultTemplate(current);
+ expect(hasVaultPlaceholder(legacy)).toBe(false);
+ expect(hasSkillsPlaceholder(legacy)).toBe(false);
+ expect(hasSchedulesPlaceholder(legacy)).toBe(false);
+
+ // Each migration replaces its legacy section verbatim, in place; schedules (which never
+ // had a legacy section) inserts before # Environment — the three together reproduce the
+ // current default template exactly.
+ const migrated = insertSchedulesPlaceholder(
+ insertSkillsPlaceholder(insertVaultPlaceholder(legacy)),
+ );
+ expect(migrated).toBe(current);
+ });
+
+ it("is idempotent on a template that already carries the placeholders", async () => {
+ const current = (await agentState()).systemConfig.system_prompt;
+ expect(insertVaultPlaceholder(current)).toBe(current);
+ expect(insertSkillsPlaceholder(current)).toBe(current);
+ expect(insertSchedulesPlaceholder(current)).toBe(current);
+ });
+
+ it("inserts before # Environment when there is no legacy section, else appends", () => {
+ const withEnvironment = "# Role\nDo things.\n\n# Environment\n- CWD: {{CWD}}";
+ expect(insertVaultPlaceholder(withEnvironment)).toBe(
+ `# Role\nDo things.\n\n${VAULT_PLACEHOLDER}\n\n# Environment\n- CWD: {{CWD}}`,
+ );
+ const bare = "# Role\nDo things.";
+ expect(insertSkillsPlaceholder(bare)).toBe(`# Role\nDo things.\n\n${SKILLS_PLACEHOLDER}\n`);
+ expect(insertSchedulesPlaceholder(bare)).toBe(
+ `# Role\nDo things.\n\n${SCHEDULES_PLACEHOLDER}\n`,
+ );
+ });
+});
+
+describe("listScheduleNames", () => {
+ it("returns [] when the schedule directory does not exist", async () => {
+ await agentState();
+ expect(await listScheduleNames(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID)).toEqual([]);
+ });
+
+ it("lists .toml basenames sorted, ignoring other files and directories", async () => {
+ await agentState();
+ const dir = scheduleDir(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
+ await fs.mkdir(dir, { recursive: true });
+ await fs.writeFile(path.join(dir, "weekly.toml"), "", "utf8");
+ await fs.writeFile(path.join(dir, "daily.toml"), "", "utf8");
+ await fs.writeFile(path.join(dir, "notes.txt"), "", "utf8");
+ await fs.mkdir(path.join(dir, "sub.toml")); // a directory never counts as a task file
+ expect(await listScheduleNames(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID)).toEqual([
+ "daily",
+ "weekly",
+ ]);
+ });
+});
+
+describe("Session prompt integration", () => {
+ it("reaches the Session prompt with the current task roster", async () => {
+ const agent = await createAgent({ root });
+ const dir = scheduleDir(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
+ await fs.mkdir(dir, { recursive: true });
+ await fs.writeFile(path.join(dir, "daily-report.toml"), 'prompt = "p"\n', "utf8");
+ const session = await agent.createSession();
+ try {
+ const meta = session.metaMessage.payload as { system_prompt: string };
+ expect(meta.system_prompt).toContain("# Scheduled Tasks");
+ expect(meta.system_prompt).toContain("Current tasks:\n- daily-report");
+ // The section names the directory as the literal pattern the model resolves itself.
+ expect(meta.system_prompt).toContain(
+ "`<app_data_dir>/agents/<agent_id>/agent_state/schedule/`",
+ );
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("is left out of the Session prompt when the Agent config disables the section", async () => {
+ const agent = await createAgent({ root });
+ agent.state.systemConfig.schedules = { enabled: false };
+ const session = await agent.createSession();
+ try {
+ const meta = session.metaMessage.payload as { system_prompt: string };
+ expect(meta.system_prompt).not.toContain("# Scheduled Tasks");
+ } finally {
+ session.dispose();
+ }
+ });
+});
diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.ts
index c9a026b8..204c5fd5 100644
--- a/packages/core/test/state.test.ts
+++ b/packages/core/test/state.test.ts
@@ -8,6 +8,13 @@ import {
AGENTS_MD_PLACEHOLDER,
VAULT_KEYS_PLACEHOLDER,
SKILL_METADATA_PLACEHOLDER,
+ VAULT_PLACEHOLDER,
+ SKILLS_PLACEHOLDER,
+ SCHEDULES_PLACEHOLDER,
+ MEMORY_PLACEHOLDER,
+ DEFAULT_VAULT_PROMPT,
+ DEFAULT_SKILLS_PROMPT,
+ DEFAULT_SCHEDULES_PROMPT,
CWD_PLACEHOLDER,
DATE_PLACEHOLDER,
DEFAULT_AGENT_ID,
@@ -164,28 +171,46 @@ describe("loadOrInitAgentState", () => {
expect(state.systemConfig.system_prompt.indexOf(AGENTS_MD_PLACEHOLDER)).toBeLessThan(
state.systemConfig.system_prompt.indexOf("# Environment"),
);
- // The # Vault and # Skills body sections plus their placeholders: the default template
- // places them after [/developer_instructions] and before # Environment, in the order
- // Vault -> Skills (the statement text is part of the template body, kept even with no
- // keys/skills).
+ // The Vault / Skills / Memory / Schedules section placeholders: the default template
+ // places them after [/developer_instructions] and before # Environment, in that order.
+ // The section statement texts (# Vault, # Skills, [use_skills] …) moved into the
+ // editable default prompts, each carrying its inner injection point — the template body
+ // holds no inline {{VAULT_KEYS}}/{{SKILL_METADATA}} anymore (those are the legacy
+ // template form).
const tpl = state.systemConfig.system_prompt;
- expect(tpl).toContain("# Vault");
- expect(tpl).toContain(VAULT_KEYS_PLACEHOLDER);
- expect(tpl).toContain("# Skills");
- expect(tpl).toContain(SKILL_METADATA_PLACEHOLDER);
- expect(tpl).toContain("[use_skills]");
+ expect(tpl).toContain(VAULT_PLACEHOLDER);
+ expect(tpl).toContain(SKILLS_PLACEHOLDER);
+ expect(tpl).toContain(SCHEDULES_PLACEHOLDER);
+ expect(tpl).not.toContain("# Vault");
+ expect(tpl).not.toContain("# Skills");
+ expect(tpl).not.toContain(VAULT_KEYS_PLACEHOLDER);
+ expect(tpl).not.toContain(SKILL_METADATA_PLACEHOLDER);
+ expect(DEFAULT_VAULT_PROMPT).toContain("# Vault");
+ expect(DEFAULT_VAULT_PROMPT).toContain(VAULT_KEYS_PLACEHOLDER);
+ expect(DEFAULT_SKILLS_PROMPT).toContain("# Skills");
+ expect(DEFAULT_SKILLS_PROMPT).toContain(SKILL_METADATA_PLACEHOLDER);
+ expect(DEFAULT_SKILLS_PROMPT).toContain("[use_skills]");
+ expect(DEFAULT_SCHEDULES_PROMPT).toContain("# Scheduled Tasks");
+ // The per-feature injection config ships enabled with the default prompts materialized.
+ expect(state.systemConfig.vault).toEqual({ enabled: true, prompt: DEFAULT_VAULT_PROMPT });
+ expect(state.systemConfig.skills).toEqual({ enabled: true, prompt: DEFAULT_SKILLS_PROMPT });
+ expect(state.systemConfig.schedules).toEqual({
+ enabled: true,
+ prompt: DEFAULT_SCHEDULES_PROMPT,
+ });
// Tooling installs once into a shared per-Agent directory rather than per task, so a
// Session's scratchpad never becomes the home of a virtualenv. It governs every task, not
// just skill runs, so it belongs to # File system — pinned by position, since the rule
- // reads as skills-only the moment it drifts back under # Skills.
+ // reads as skills-only the moment it drifts back under # Skills (now the {{SKILLS}}
+ // block).
expect(tpl).toContain("<app_data_dir>/agents/<agent_id>/shared_env/");
expect(tpl.indexOf("# File system")).toBeLessThan(tpl.indexOf("shared_env/"));
- expect(tpl.indexOf("shared_env/")).toBeLessThan(tpl.indexOf("# Skills"));
- expect(tpl.indexOf("[/developer_instructions]")).toBeLessThan(tpl.indexOf("# Vault"));
- expect(tpl.indexOf("# Vault")).toBeLessThan(tpl.indexOf(VAULT_KEYS_PLACEHOLDER));
- expect(tpl.indexOf(VAULT_KEYS_PLACEHOLDER)).toBeLessThan(tpl.indexOf("# Skills"));
- expect(tpl.indexOf("# Skills")).toBeLessThan(tpl.indexOf(SKILL_METADATA_PLACEHOLDER));
- expect(tpl.indexOf(SKILL_METADATA_PLACEHOLDER)).toBeLessThan(tpl.indexOf("# Environment"));
+ expect(tpl.indexOf("shared_env/")).toBeLessThan(tpl.indexOf(SKILLS_PLACEHOLDER));
+ expect(tpl.indexOf("[/developer_instructions]")).toBeLessThan(tpl.indexOf(VAULT_PLACEHOLDER));
+ expect(tpl.indexOf(VAULT_PLACEHOLDER)).toBeLessThan(tpl.indexOf(SKILLS_PLACEHOLDER));
+ expect(tpl.indexOf(SKILLS_PLACEHOLDER)).toBeLessThan(tpl.indexOf(MEMORY_PLACEHOLDER));
+ expect(tpl.indexOf(MEMORY_PLACEHOLDER)).toBeLessThan(tpl.indexOf(SCHEDULES_PLACEHOLDER));
+ expect(tpl.indexOf(SCHEDULES_PLACEHOLDER)).toBeLessThan(tpl.indexOf("# Environment"));
expect(state.systemConfig.model?.max_tokens).toBe(32000);
expect(state.systemConfig.model?.thinking_level).toBe("medium");
expect(state.systemConfig.model?.timeoutMs).toBe(120000);
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index e2237f3b..9310b7e2 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -109,6 +109,12 @@ Edit this file via the CLI (`penguin config model …`) or the Web Models page
| `memory.enabled` | `true` | Whether Memory enters the context and Memory directories are prepared |
| `memory.prompt` | built-in template | Always-injected half of the `{{MEMORY}}` block, editable on the Memory tab — carries `{{USER_MEMORY_INDEX}}` |
| `memory.workspace_prompt` | built-in template | Appended only in a persistent Workspace, editable on the Memory tab — carries `{{WORKSPACE_MEMORY_INDEX}}` and `{{WORKSPACE_MEMORY_DIR}}` |
+| `vault.enabled` | `true` | Whether the vault section enters the context (with it off, values are still injected into subprocess environments — the model just doesn't see the key-name list) |
+| `vault.prompt` | built-in template | The `{{VAULT}}` block, editable on the Vault tab — carries `{{VAULT_KEYS}}` |
+| `skills.enabled` | `true` | Whether the skills section enters the context (with it off, installed skills remain explicitly invocable via `[use_skills]`) |
+| `skills.prompt` | built-in template | The `{{SKILLS}}` block, editable on the Skills tab — carries `{{SKILL_METADATA}}` |
+| `schedules.enabled` | `true` | Whether the scheduled-tasks section enters the context (with it off, the server still fires tasks — the model just isn't taught the task system) |
+| `schedules.prompt` | built-in template | The `{{SCHEDULES}}` block, editable on the Schedules tab — teaches the model file-based task management, carries `{{SCHEDULE_LIST}}` |
| `tools.builtin` | full default toolset when omitted | Tool entries: `name` / `description` / `parameters` / `permission` (`r` or `rw`) / `forModel` / `timeoutMs` / `maxOutputLength` / `call_description` (per-tool toggle for the `description` call argument, required while on; missing = kept); once written it replaces the default list wholesale |
| `tools.mcpServers` | `[]` | MCP Server configuration (`name` + `config`): transport is `stdio` / `http` / `sse`, and discovered tools join the toolset as `mcp__<server>__<tool>`; see the MCP Servers section of [Tools & Approval](/tools) |
@@ -152,9 +158,13 @@ An existing Agent always runs with its on-disk config verbatim — newer code de
| Placeholder | Injected content |
| --- | --- |
| `{{AGENTS_MD}}` | Full text of `AGENTS.md` |
-| `{{VAULT_KEYS}}` | List of Vault key names (names only) |
-| `{{SKILL_METADATA}}` | Metadata of installed Skills |
+| `{{VAULT}}` | The rendered `vault.prompt` block (the vault section); empty when `vault.enabled` is off. A template without it injects no vault section — the Vault tab offers inserting/migrating it explicitly |
+| `{{SKILLS}}` | The rendered `skills.prompt` block (the skills section); empty when `skills.enabled` is off. A template without it injects no skills section — the Skills tab offers inserting/migrating it explicitly |
| `{{MEMORY}}` | The rendered `memory.prompt` block, plus `memory.workspace_prompt` in a persistent Workspace; empty when Memory is off. A template without it injects no Memory — the Memory tab offers inserting it explicitly |
+| `{{SCHEDULES}}` | The rendered `schedules.prompt` block (the scheduled-tasks section); empty when `schedules.enabled` is off. A template without it injects no schedules section — the Schedules tab offers inserting it explicitly |
+| `{{VAULT_KEYS}}` | Inside `vault.prompt`: the Vault key-name list (names only, one `- KEY` line per key). For legacy templates, an occurrence directly in the template body is still substituted, honoring `vault.enabled` the same way |
+| `{{SKILL_METADATA}}` | Inside `skills.prompt`: the installed Skills' metadata lines. For legacy templates, an occurrence directly in the template body is still substituted, honoring `skills.enabled` the same way |
+| `{{SCHEDULE_LIST}}` | Inside `schedules.prompt`: the current task-name list (one `- name` line per task; an empty-roster note when none exist) |
| `{{USER_MEMORY_INDEX}}` | Inside the Memory prompts: content of the user scope's `MEMORY.md` index (at most 200 lines and 25,000 characters total) |
| `{{WORKSPACE_MEMORY_INDEX}}` | Inside `memory.workspace_prompt` only: content of the Workspace scope's `MEMORY.md` index (at most 200 lines and 25,000 characters total) |
| `{{WORKSPACE_MEMORY_DIR}}` | Inside `memory.workspace_prompt` only: absolute path of the current Workspace's Memory directory |
@@ -174,6 +184,10 @@ On Windows, `{{PROJECT_DIR}}` and `{{CWD}}` are injected with forward slashes
`agent_state/AGENTS.md` is the developer-editable instruction file, injected via `{{AGENTS_MD}}` and empty by default — it is also the file an optimizer edits most (see [Self-Improvement](/self-improvement)).
+The Vault / Skills / Memory / Schedules sections all follow the same placeholder + toggle + editable prompt pattern: the template holds only the `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` placeholders, the section text lives in the corresponding `*.prompt` config (edited on its settings tab), and turning `*.enabled` off empties the whole block. The four section placeholders are expanded **last, in a single pass** at assembly time: expansion products are never rescanned, so placeholder-looking text inside a memory index or a section prompt stays literal instead of triggering a second substitution.
+
+**Legacy templates**: `system_config.yaml` is materialized at Agent creation and never auto-upgraded, so an Agent created before this mechanism carries hardcoded `# Vault` / `# Skills` section text with inline `{{VAULT_KEYS}}` / `{{SKILL_METADATA}}` in its template. Such templates keep working: the inline placeholders are still substituted, and now honor the new toggles (an off switch substitutes an empty string). The matching tab reports the legacy template and offers one-click migration — replacing the old default section verbatim, in place, with the new placeholder, leaving the assembled prompt unchanged; a template whose section text was customized doesn't match the verbatim migration and is treated as missing the placeholder instead, with a one-click insert (before `# Environment`).
+
## Memory
`agent_state/memory/` is what the Agent remembers between Sessions: user feedback, project decisions, working conventions and entry points into external systems — the things that cannot be re-derived from the Workspace or its code history. It is not context compaction, which preserves one Session's short-term state.
@@ -232,7 +246,7 @@ To read, delete or ask the Agent to edit what it has saved, use the settings pag
- Key names must match `^[A-Za-z_][A-Za-z0-9_]*$` (shell environment variable naming rules);
- Values are injected only into tool subprocess environments and never enter the model context or the Trace;
-- Only key names are disclosed in the system prompt via `{{VAULT_KEYS}}`;
+- Only key names are disclosed in the system prompt: the template's `{{VAULT}}` placeholder expands to `vault.prompt` (carrying the `{{VAULT_KEYS}}` key-name list), editable on the Vault tab; with `vault.enabled` off the block is empty — values are still injected into subprocesses, the model just doesn't see the key-name list. A legacy template's inline `{{VAULT_KEYS}}` is still substituted under the same toggle, and the tab offers one-click migration (see "System prompt placeholders");
- Saving through the Web/API invalidates the Agent's cached Session runtimes: the next Task on any of its Sessions re-resumes and runs with the new values; a Task already in flight keeps the values it started with (a direct CLI file edit reaches a running server only when a Session is next created or resumed);
- Managed via `penguin config vault set/list/remove` or the Web Vault tab.
@@ -258,6 +272,8 @@ start_at = 2026-08-01T09:00:00Z
period = "12h"
```
+The template's `{{SCHEDULES}}` placeholder expands to `schedules.prompt`: it teaches the model to manage these TOML files with its own file tools (the directory, the field rules, the ~30-second automatic pickup, and the hygiene rules against duplicates), ending with the current task-name list via `{{SCHEDULE_LIST}}`. The prompt is editable on the Schedules tab; with `schedules.enabled` off the block is empty — the server still fires tasks on schedule, the model just isn't taught the task system. An Agent created before this mechanism has no such placeholder in its template; the tab offers one-click insertion.
+
## Design principle
An Agent's behavior lives entirely in editable files on disk — prompts, Skills, and configuration are data, not code. That is what makes Agents improvable by Agents: an optimizer edits exactly the same files you edit by hand. See [Self-Improvement](/self-improvement) and the [CLI Reference](/cli).
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index 3ba55d90..fdfe559f 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -109,6 +109,12 @@ output = 0.857143
| `memory.enabled` | `true` | 记忆是否进入上下文、是否为持久 Workspace 准备记忆目录 |
| `memory.prompt` | 内置模板 | `{{MEMORY}}` 区块中恒注入的一半,可在记忆标签页编辑——含 `{{USER_MEMORY_INDEX}}` |
| `memory.workspace_prompt` | 内置模板 | 仅持久 Workspace 追加,可在记忆标签页编辑——含 `{{WORKSPACE_MEMORY_INDEX}}` 与 `{{WORKSPACE_MEMORY_DIR}}` |
+| `vault.enabled` | `true` | 保险柜小节是否进入上下文(关闭后值仍注入子进程环境,只是模型看不到键名清单) |
+| `vault.prompt` | 内置模板 | `{{VAULT}}` 区块内容,可在 Vault 标签页编辑——含 `{{VAULT_KEYS}}` |
+| `skills.enabled` | `true` | 技能小节是否进入上下文(关闭后已装技能仍可被 `[use_skills]` 显式调用) |
+| `skills.prompt` | 内置模板 | `{{SKILLS}}` 区块内容,可在技能标签页编辑——含 `{{SKILL_METADATA}}` |
+| `schedules.enabled` | `true` | 定时任务小节是否进入上下文(关闭后 server 照常触发任务,只是模型不了解任务体系) |
+| `schedules.prompt` | 内置模板 | `{{SCHEDULES}}` 区块内容,可在定时任务标签页编辑——教模型用文件工具管理任务,含 `{{SCHEDULE_LIST}}` |
| `tools.builtin` | 缺省时为完整默认工具集 | 工具条目:`name` / `description` / `parameters` / `permission`(`r` 或 `rw`)/ `forModel` / `timeoutMs` / `maxOutputLength` / `call_description`(条目级开关:控制 `description` 调用参数,开启时为必填,缺省保留);一旦写出即整体替换默认列表 |
| `tools.mcpServers` | `[]` | MCP Server 配置(`name` + `config`):transport 取 `stdio` / `http` / `sse`,工具以 `mcp__<server>__<tool>` 并入工具集,详见[工具与审批](/tools)的 MCP Server 一节 |
@@ -152,9 +158,13 @@ compaction:
| 占位符 | 注入内容 |
| --- | --- |
| `{{AGENTS_MD}}` | `AGENTS.md` 的全文 |
-| `{{VAULT_KEYS}}` | Vault 的键名列表(仅键名) |
-| `{{SKILL_METADATA}}` | 已安装 Skill 的元数据 |
+| `{{VAULT}}` | 渲染后的 `vault.prompt` 区块(保险柜小节);`vault.enabled` 关闭时为空。模板没有它就不注入该小节——Vault 标签页提供显式插入/迁移 |
+| `{{SKILLS}}` | 渲染后的 `skills.prompt` 区块(技能小节);`skills.enabled` 关闭时为空。模板没有它就不注入该小节——技能标签页提供显式插入/迁移 |
| `{{MEMORY}}` | 渲染后的 `memory.prompt` 区块,持久 Workspace 下再追加 `memory.workspace_prompt`;关闭记忆时为空。模板没有它就不注入记忆——记忆标签页提供显式插入 |
+| `{{SCHEDULES}}` | 渲染后的 `schedules.prompt` 区块(定时任务小节);`schedules.enabled` 关闭时为空。模板没有它就不注入该小节——定时任务标签页提供显式插入 |
+| `{{VAULT_KEYS}}` | `vault.prompt` 内:Vault 的键名列表(仅键名,每键一行 `- KEY`)。为兼容旧模板,直接写在模板正文中的该占位符仍会被替换,并同样受 `vault.enabled` 控制 |
+| `{{SKILL_METADATA}}` | `skills.prompt` 内:已安装 Skill 的元数据行。为兼容旧模板,直接写在模板正文中的该占位符仍会被替换,并同样受 `skills.enabled` 控制 |
+| `{{SCHEDULE_LIST}}` | `schedules.prompt` 内:现有定时任务名列表(每任务一行 `- name`;无任务时为空清单说明) |
| `{{USER_MEMORY_INDEX}}` | 记忆提示词内:用户作用域 `MEMORY.md` 索引的内容(最多注入 200 行、总计 25000 字符) |
| `{{WORKSPACE_MEMORY_INDEX}}` | 仅 `memory.workspace_prompt` 内:Workspace 作用域 `MEMORY.md` 索引的内容(最多注入 200 行、总计 25000 字符) |
| `{{WORKSPACE_MEMORY_DIR}}` | 仅 `memory.workspace_prompt` 内:当前 Workspace 记忆目录的绝对路径 |
@@ -174,6 +184,10 @@ Windows 上注入的 `{{PROJECT_DIR}}` 与 `{{CWD}}` 统一使用正斜杠——
`agent_state/AGENTS.md` 是开发者可编辑的指令文件,经 `{{AGENTS_MD}}` 注入系统提示词,缺省为空——它也是优化器最常改动的文件(见[自我进化](/self-improvement))。
+Vault / 技能 / 记忆 / 定时任务四个小节均采用「段落占位符 + 开关 + 可编辑提示词」模式:模板只保留 `{{VAULT}}` / `{{SKILLS}}` / `{{MEMORY}}` / `{{SCHEDULES}}` 占位符,小节文本存于各自的 `*.prompt` 配置、在对应设置标签页编辑,`*.enabled` 关闭即整段为空。四个段落占位符在装配时**最后单趟展开**:展开产物不再被扫描,因此记忆索引或提示词正文里出现的占位符字样只会保持字面原样,不会引发二次替换。
+
+**旧模板兼容**:`system_config.yaml` 在 Agent 创建时物化、从不自动升级,早于本机制创建的 Agent 模板中是硬编码的 `# Vault` / `# Skills` 段落文字加内联 `{{VAULT_KEYS}}` / `{{SKILL_METADATA}}`。这类模板继续工作:内联占位符仍被替换,且同样受新开关控制(关闭时替换为空串)。对应标签页会提示「旧版模板」并提供一键迁移——把旧默认段落逐字原位替换为新占位符,装配结果不变;自定义改动过段落文字的模板不匹配逐字迁移,则按缺占位符处理、提供一键插入(插到 `# Environment` 之前)。
+
## 记忆
`agent_state/memory/` 保存 Agent 跨 Session 的长期记忆:用户反馈、项目决策、协作约定与外部系统入口——这些无法从 Workspace 或代码历史可靠重新推导。它不是上下文压缩:压缩保存单个 Session 的短期工作状态。
@@ -232,7 +246,7 @@ frontmatter 只有这三个字段——记忆属于哪一层由所在目录表
- 键名须匹配 `^[A-Za-z_][A-Za-z0-9_]*$`(shell 环境变量命名规则);
- 值只注入工具子进程的环境变量,永远不进入模型上下文与 Trace;
-- 系统提示词中经 `{{VAULT_KEYS}}` 只披露键名;
+- 系统提示词中只披露键名:模板的 `{{VAULT}}` 占位符展开为 `vault.prompt`(内含 `{{VAULT_KEYS}}` 键名列表),提示词可在 Vault 标签页编辑;`vault.enabled` 关闭则整段为空——值照旧注入子进程,只是模型看不到键名清单。旧模板的内联 `{{VAULT_KEYS}}` 仍被替换并受同一开关控制,标签页提供一键迁移(见「系统提示词占位符」一节);
- 经 Web/API 保存会使该 Agent 已缓存的 Session 运行时失效:其任意 Session 的下一个任务会重新恢复(resume)并使用新值;进行中的任务保持其启动时的值(CLI 直接改文件对运行中的 server 则要等 Session 下次创建或恢复时生效);
- 通过 CLI `penguin config vault set/list/remove` 或 Web 的 Vault 标签页管理。
@@ -258,6 +272,8 @@ start_at = 2026-08-01T09:00:00Z
period = "12h"
```
+模板的 `{{SCHEDULES}}` 占位符展开为 `schedules.prompt`:教模型用文件工具自行管理这些 TOML 文件(目录、字段规则、约 30 秒自动生效、防重复等卫生规则),末尾经 `{{SCHEDULE_LIST}}` 注入现有任务名列表。提示词可在定时任务标签页编辑;`schedules.enabled` 关闭则整段为空——server 照常按计划触发任务,只是模型不了解任务体系。早于本机制创建的 Agent 模板没有该占位符,标签页提供一键插入。
+
## 设计原则
Agent 的行为完整地存放于磁盘上的可编辑文件——提示词、Skill、配置都是数据而非代码。正因如此,Agent 才能被 Agent 改进:优化器编辑的与你手工编辑的是同一批文件。参见[自我进化](/self-improvement)与 [CLI 参考](/cli)。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 868eb0da..fb9bbd5b 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -550,6 +550,44 @@ export interface AgentMemoryConfigDto {
workspacePrompt: string;
}
+/**
+ * Vault prompt-injection config, edited on the Vault tab. `enabled` / `prompt` report
+ * effective values (a config with no `vault` section reads as enabled with the built-in
+ * prompt, matching core); the last two are read-only facts computed from the stored template.
+ */
+export interface AgentVaultConfigDto {
+ /** Whether the Vault section enters the model context (values are injected into subprocesses regardless). */
+ enabled: boolean;
+ /** The `{{VAULT}}` block (carries `{{VAULT_KEYS}}`). */
+ prompt: string;
+ /** Whether the stored template carries `{{VAULT}}`; POST …/vault/template-placeholder inserts (or migrates to) it explicitly. */
+ templateHasPlaceholder: boolean;
+ /** Whether the stored template still carries the legacy hardcoded # Vault section verbatim (a pre-`{{VAULT}}` Agent) — the migration case of the insert endpoint. */
+ legacySectionPresent: boolean;
+}
+
+/** Skills prompt-injection config, edited on the Skills tab; same field semantics as AgentVaultConfigDto, for `{{SKILLS}}` / `{{SKILL_METADATA}}` and the legacy # Skills section. */
+export interface AgentSkillsConfigDto {
+ /** Whether the Skills section enters the model context (installed skills remain explicitly invocable regardless). */
+ enabled: boolean;
+ /** The `{{SKILLS}}` block (carries `{{SKILL_METADATA}}`). */
+ prompt: string;
+ /** Whether the stored template carries `{{SKILLS}}`; POST …/skills/template-placeholder inserts (or migrates to) it explicitly. */
+ templateHasPlaceholder: boolean;
+ /** Whether the stored template still carries the legacy hardcoded # Skills section verbatim — the migration case of the insert endpoint. */
+ legacySectionPresent: boolean;
+}
+
+/** Schedules prompt-injection config, edited on the Schedules tab. No legacy field: Schedules never had a hardcoded template section. */
+export interface AgentSchedulesConfigDto {
+ /** Whether the Scheduled Tasks section enters the model context (the server fires configured tasks regardless). */
+ enabled: boolean;
+ /** The `{{SCHEDULES}}` block (carries `{{SCHEDULE_LIST}}`). */
+ prompt: string;
+ /** Whether the stored template carries `{{SCHEDULES}}`; POST …/schedules/template-placeholder inserts it explicitly. */
+ templateHasPlaceholder: boolean;
+}
+
/** Structured view of system_config.yaml (for the edit form). */
export interface AgentConfigDto {
name?: string;
@@ -561,6 +599,9 @@ export interface AgentConfigDto {
model?: AgentModelConfigDto;
compaction?: AgentCompactionConfigDto;
memory: AgentMemoryConfigDto;
+ vault: AgentVaultConfigDto;
+ skills: AgentSkillsConfigDto;
+ schedules: AgentSchedulesConfigDto;
toolsBuiltin: ToolDefinitionConfig[];
mcpServers: MCPServerConfig[];
}
@@ -597,6 +638,10 @@ export interface AgentConfigUpdateRequest {
model?: AgentModelConfigDto;
compaction?: AgentCompactionConfigDto;
memory?: Partial<AgentMemoryConfigDto>;
+ /** Only the writable half of the DTO — the template facts (templateHasPlaceholder / legacySectionPresent) are computed, never written. */
+ vault?: { enabled?: boolean; prompt?: string };
+ skills?: { enabled?: boolean; prompt?: string };
+ schedules?: { enabled?: boolean; prompt?: string };
toolsBuiltin?: ToolDefinitionConfig[];
mcpServers?: MCPServerConfig[];
};
diff --git a/packages/server/src/http/routes/schedules.ts b/packages/server/src/http/routes/schedules.ts
index cf4a32cf..23a90689 100644
--- a/packages/server/src/http/routes/schedules.ts
+++ b/packages/server/src/http/routes/schedules.ts
@@ -1,6 +1,7 @@
/**
* Schedule routes:
* GET|POST /api/projects/:p/agents/:a/schedules
+ * POST /api/projects/:p/agents/:a/schedules/template-placeholder # insert the {{SCHEDULES}} placeholder
* GET|PUT|DELETE /api/projects/:p/agents/:a/schedules/:name (name is the file name)
* Any member can read; only the owner can modify. The file is declarative intent:
* POST/PUT fully replace the file, validation always goes through parseScheduleFile
@@ -163,6 +164,21 @@ export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json(await readItem(deps, projectId, agentId, name), 201);
});
+ // Insert the {{SCHEDULES}} placeholder into the prompt template — the explicit adoption
+ // path mirroring memory's endpoint; idempotent config write, owner-level like this
+ // router's other mutations. Registered before /:name, though the static path wins anyway.
+ app.post("/template-placeholder", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ const view = await deps.agentConfigService.insertTemplatePlaceholder(
+ projectId,
+ agentId,
+ "schedules",
+ );
+ return c.json(view.config.schedules);
+ });
+
app.get("/:name", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
diff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.ts
index 23ef771a..e4c2767d 100644
--- a/packages/server/src/http/routes/skills.ts
+++ b/packages/server/src/http/routes/skills.ts
@@ -2,6 +2,7 @@
* Skill library & Agent-installed-Skills routes:
* GET /api/skills # library groups & metadata (any logged-in user)
* GET|POST /api/projects/:p/agents/:a/skills # installed list / install from library (any member)
+ * POST /api/projects/:p/agents/:a/skills/template-placeholder # insert/migrate the {{SKILLS}} placeholder (any member)
* POST /api/projects/:p/agents/:a/skills/archive # install one skill from an uploaded zip (any member)
* GET /api/projects/:p/agents/:a/skills/:name/archive # export one installed skill as a zip (any member)
* DELETE /api/projects/:p/agents/:a/skills/:name # uninstall (any member)
@@ -258,6 +259,21 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json(await listResponse(projectId, agentId));
});
+ // Insert (or migrate a legacy hardcoded # Skills section to) the {{SKILLS}} placeholder —
+ // the explicit adoption path mirroring memory's endpoint; idempotent config write,
+ // member-level like every other mutation on this router.
+ app.post("/template-placeholder", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ const view = await deps.agentConfigService.insertTemplatePlaceholder(
+ projectId,
+ agentId,
+ "skills",
+ );
+ return c.json(view.config.skills);
+ });
+
app.post("/", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
diff --git a/packages/server/src/http/routes/vault.ts b/packages/server/src/http/routes/vault.ts
index d733ad05..2ea5f43a 100644
--- a/packages/server/src/http/routes/vault.ts
+++ b/packages/server/src/http/routes/vault.ts
@@ -1,6 +1,8 @@
/**
* Vault environment variable routes:
* GET|PUT /api/projects/:p/agents/:a/vault (Agent-level, agent_state/.vault.toml).
+ * POST …/vault/template-placeholder inserts/migrates the {{VAULT}} placeholder in the
+ * prompt template.
* Any member can read (values masked); only the owner can modify; 404 if the Agent doesn't exist.
*/
import { Hono } from "hono";
@@ -55,5 +57,20 @@ export function vaultRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json(res);
});
+ // Insert (or migrate a legacy hardcoded # Vault section to) the {{VAULT}} placeholder —
+ // the explicit adoption path mirroring memory's endpoint; idempotent config write,
+ // owner-level like this router's other mutation.
+ app.post("/template-placeholder", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ const view = await deps.agentConfigService.insertTemplatePlaceholder(
+ projectId,
+ agentId,
+ "vault",
+ );
+ return c.json(view.config.vault);
+ });
+
return app;
}
diff --git a/packages/server/src/services/agent-config-service.ts b/packages/server/src/services/agent-config-service.ts
index 10d881d6..7a9fe64f 100644
--- a/packages/server/src/services/agent-config-service.ts
+++ b/packages/server/src/services/agent-config-service.ts
@@ -12,9 +12,20 @@ import { parseDocument, parse as parseYaml } from "yaml";
import {
DEFAULT_MEMORY_PROMPT,
DEFAULT_MEMORY_WORKSPACE_PROMPT,
+ DEFAULT_SCHEDULES_PROMPT,
+ DEFAULT_SKILLS_PROMPT,
+ DEFAULT_VAULT_PROMPT,
+ LEGACY_SKILLS_SECTION,
+ LEGACY_VAULT_SECTION,
agentsMdPath,
agentStateDir,
agentStateVersion,
+ hasSchedulesPlaceholder,
+ hasSkillsPlaceholder,
+ hasVaultPlaceholder,
+ insertSchedulesPlaceholder,
+ insertSkillsPlaceholder,
+ insertVaultPlaceholder,
VAULT_VALUE_MAX_LENGTH,
isValidVaultKey,
loadAgentVault,
@@ -34,6 +45,9 @@ import type {
AgentModelConfigDto,
AgentCompactionConfigDto,
AgentMemoryConfigDto,
+ AgentSchedulesConfigDto,
+ AgentSkillsConfigDto,
+ AgentVaultConfigDto,
VaultEntryInfo,
VaultResponse,
VaultUpdateRequest,
@@ -117,6 +131,9 @@ export class AgentConfigService {
const model = asRecord(parsed.model);
const compaction = asRecord(parsed.compaction);
const memory = asRecord(parsed.memory);
+ const vault = asRecord(parsed.vault);
+ const skills = asRecord(parsed.skills);
+ const schedules = asRecord(parsed.schedules);
const tools = asRecord(parsed.tools);
let agentsMd = "";
@@ -158,15 +175,40 @@ export class AgentConfigService {
? memory.workspace_prompt
: DEFAULT_MEMORY_WORKSPACE_PROMPT,
};
+ // Effective values like memory's, plus template facts computed from the stored template:
+ // whether the section placeholder is present, and — skills/vault only — whether the
+ // template still carries the legacy hardcoded section verbatim (the migration case;
+ // detection retires with core's LEGACY_* constants).
+ const systemPrompt = typeof parsed.system_prompt === "string" ? parsed.system_prompt : "";
+ const vaultDto: AgentVaultConfigDto = {
+ enabled: vault.enabled !== false,
+ prompt: typeof vault.prompt === "string" ? vault.prompt : DEFAULT_VAULT_PROMPT,
+ templateHasPlaceholder: hasVaultPlaceholder(systemPrompt),
+ legacySectionPresent: systemPrompt.includes(LEGACY_VAULT_SECTION),
+ };
+ const skillsDto: AgentSkillsConfigDto = {
+ enabled: skills.enabled !== false,
+ prompt: typeof skills.prompt === "string" ? skills.prompt : DEFAULT_SKILLS_PROMPT,
+ templateHasPlaceholder: hasSkillsPlaceholder(systemPrompt),
+ legacySectionPresent: systemPrompt.includes(LEGACY_SKILLS_SECTION),
+ };
+ const schedulesDto: AgentSchedulesConfigDto = {
+ enabled: schedules.enabled !== false,
+ prompt: typeof schedules.prompt === "string" ? schedules.prompt : DEFAULT_SCHEDULES_PROMPT,
+ templateHasPlaceholder: hasSchedulesPlaceholder(systemPrompt),
+ };
const config: AgentConfigDto = {
...(typeof parsed.name === "string" ? { name: parsed.name } : {}),
...(typeof parsed.description === "string" ? { description: parsed.description } : {}),
version: agentStateVersion({ version: parsed.version as number | undefined }),
- systemPrompt: typeof parsed.system_prompt === "string" ? parsed.system_prompt : "",
+ systemPrompt,
...(typeof parsed.max_turns === "number" ? { maxTurns: parsed.max_turns } : {}),
...(Object.keys(modelDto).length > 0 ? { model: modelDto } : {}),
...(Object.keys(compactionDto).length > 0 ? { compaction: compactionDto } : {}),
memory: memoryDto,
+ vault: vaultDto,
+ skills: skillsDto,
+ schedules: schedulesDto,
toolsBuiltin: Array.isArray(tools.builtin) ? (tools.builtin as ToolDefinitionConfig[]) : [],
mcpServers: Array.isArray(tools.mcpServers) ? (tools.mcpServers as MCPServerConfig[]) : [],
};
@@ -275,6 +317,24 @@ export class AgentConfigService {
setIfProvided(["memory", "prompt"], optionalString(memory, "prompt"));
setIfProvided(["memory", "workspace_prompt"], optionalString(memory, "workspacePrompt"));
}
+ // The vault / skills / schedules toggles only decide whether the section reaches the
+ // context: vault values still enter subprocess environments, installed skills stay
+ // invocable, and the scheduler keeps firing tasks.
+ if (cfg.vault !== undefined) {
+ const vault = asRecord(cfg.vault);
+ setIfProvided(["vault", "enabled"], optionalBoolean(vault, "enabled"));
+ setIfProvided(["vault", "prompt"], optionalString(vault, "prompt"));
+ }
+ if (cfg.skills !== undefined) {
+ const skills = asRecord(cfg.skills);
+ setIfProvided(["skills", "enabled"], optionalBoolean(skills, "enabled"));
+ setIfProvided(["skills", "prompt"], optionalString(skills, "prompt"));
+ }
+ if (cfg.schedules !== undefined) {
+ const schedules = asRecord(cfg.schedules);
+ setIfProvided(["schedules", "enabled"], optionalBoolean(schedules, "enabled"));
+ setIfProvided(["schedules", "prompt"], optionalString(schedules, "prompt"));
+ }
if (cfg.toolsBuiltin !== undefined) {
doc.setIn(["tools", "builtin"], validateToolsBuiltin(cfg.toolsBuiltin));
}
@@ -285,6 +345,31 @@ export class AgentConfigService {
await fs.writeFile(yamlPath, doc.toString(), "utf8");
}
+ /**
+ * Inserts a feature's section placeholder into the Agent's prompt template — the explicit
+ * adoption path mirroring the Memory tab's endpoint; nothing ever inserts automatically.
+ * For skills/vault the insert is migration-first (core's helpers): a stored template still
+ * carrying the legacy hardcoded section verbatim gets it replaced in place by the
+ * placeholder, otherwise the placeholder is inserted before `# Environment`. Idempotent;
+ * returns the refreshed config view (the route picks out the feature's DTO).
+ */
+ async insertTemplatePlaceholder(
+ projectId: string,
+ agentId: string,
+ feature: "vault" | "skills" | "schedules",
+ ): Promise<AgentConfigView> {
+ const view = await this.getConfig(projectId, agentId);
+ const insert = {
+ vault: insertVaultPlaceholder,
+ skills: insertSkillsPlaceholder,
+ schedules: insertSchedulesPlaceholder,
+ }[feature];
+ const next = insert(view.config.systemPrompt);
+ if (next === view.config.systemPrompt) return view;
+ await this.updateConfig(projectId, agentId, { config: { systemPrompt: next } });
+ return this.getConfig(projectId, agentId);
+ }
+
/** Read the Agent vault (agent_state/.vault.toml): values are always masked, plaintext is never sent to the client. */
async getVault(projectId: string, agentId: string): Promise<VaultResponse> {
await this.requireExists(projectId, agentId);
diff --git a/packages/server/test/prompt-sections.test.ts b/packages/server/test/prompt-sections.test.ts
new file mode 100644
index 00000000..e9161bd9
--- /dev/null
+++ b/packages/server/test/prompt-sections.test.ts
@@ -0,0 +1,166 @@
+/**
+ * Integration tests for the Vault / Skills / Schedules prompt-injection config (the
+ * memory-style placeholder + toggle + editable prompt pattern): the config route reports
+ * effective values plus template facts (placeholder presence, legacy-section presence),
+ * toggles and prompts round-trip through PUT …/config, and each feature's
+ * POST …/template-placeholder inserts — or, for a legacy hardcoded section, migrates to —
+ * its placeholder, with the routers' own permission models (skills member-level,
+ * vault/schedules owner-only).
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { LEGACY_SKILLS_SECTION, LEGACY_VAULT_SECTION } from "@prismshadow/penguin-core";
+import type {
+ AgentConfigResponse,
+ AgentSchedulesConfigDto,
+ AgentSkillsConfigDto,
+ AgentVaultConfigDto,
+} from "../src/api/types.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** A pre-toggle template shape: hardcoded # Vault / # Skills sections, no section placeholders. */
+const LEGACY_TEMPLATE = `# Role\nDo things.\n\n${LEGACY_VAULT_SECTION}\n\n${LEGACY_SKILLS_SECTION}\n\n{{MEMORY}}\n\n# Environment\n- CWD: {{CWD}}`;
+
+describe("prompt-injection config (vault / skills / schedules)", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ let member: ReturnType<typeof apiClient>;
+ let outsider: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let configPath: string;
+ let agentBase: string;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_a");
+ const b = await provisionUser(t.app, "member_b");
+ const c = await provisionUser(t.app, "outsider_c");
+ owner = apiClient(t.app, a.cookie);
+ member = apiClient(t.app, b.cookie);
+ outsider = apiClient(t.app, c.cookie);
+ const created = (await (
+ await owner.post("/api/projects", { projectId: "owner_a-sections", name: "sections" })
+ ).json()) as { project: { projectId: string } };
+ projectId = created.project.projectId;
+ await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" });
+ agentBase = `/api/projects/${projectId}/agents/default_agent`;
+ configPath = `${agentBase}/config`;
+ });
+
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ const getConfig = async (): Promise<AgentConfigResponse> =>
+ (await (await owner.get(configPath)).json()) as AgentConfigResponse;
+
+ it("reports the three sections on a fresh agent: enabled, default prompts, placeholders present, no legacy section", async () => {
+ const { config } = await getConfig();
+ for (const dto of [config.vault, config.skills, config.schedules]) {
+ expect(dto.enabled).toBe(true);
+ expect(dto.templateHasPlaceholder).toBe(true);
+ }
+ // A fresh default agent stores the built-in prompts in its own yaml, inner tokens included.
+ expect(config.vault.prompt).toContain("{{VAULT_KEYS}}");
+ expect(config.skills.prompt).toContain("{{SKILL_METADATA}}");
+ expect(config.schedules.prompt).toContain("{{SCHEDULE_LIST}}");
+ expect(config.vault.legacySectionPresent).toBe(false);
+ expect(config.skills.legacySectionPresent).toBe(false);
+ });
+
+ it("toggles each section through the config route", async () => {
+ for (const feature of ["vault", "skills", "schedules"] as const) {
+ const off = await owner.put(configPath, { config: { [feature]: { enabled: false } } });
+ expect(off.status).toBe(200);
+ expect(((await off.json()) as AgentConfigResponse).config[feature].enabled).toBe(false);
+ const on = await owner.put(configPath, { config: { [feature]: { enabled: true } } });
+ expect(((await on.json()) as AgentConfigResponse).config[feature].enabled).toBe(true);
+ }
+ });
+
+ it("round-trips a custom prompt, leaving the other sections untouched", async () => {
+ const put = await owner.put(configPath, {
+ config: { vault: { prompt: "# Vault\ncustom {{VAULT_KEYS}}" } },
+ });
+ expect(put.status).toBe(200);
+ const after = (await put.json()) as AgentConfigResponse;
+ expect(after.config.vault.prompt).toBe("# Vault\ncustom {{VAULT_KEYS}}");
+ expect(after.config.vault.enabled).toBe(true);
+ // The untouched sections keep their defaults.
+ expect(after.config.skills.prompt).toContain("{{SKILL_METADATA}}");
+ expect(after.config.schedules.prompt).toContain("{{SCHEDULE_LIST}}");
+ });
+
+ it("reports a legacy template and migrates its hardcoded sections placeholder by placeholder", async () => {
+ expect(
+ (await owner.put(configPath, { config: { systemPrompt: LEGACY_TEMPLATE } })).status,
+ ).toBe(200);
+ let { config } = await getConfig();
+ expect(config.vault.templateHasPlaceholder).toBe(false);
+ expect(config.vault.legacySectionPresent).toBe(true);
+ expect(config.skills.templateHasPlaceholder).toBe(false);
+ expect(config.skills.legacySectionPresent).toBe(true);
+ expect(config.schedules.templateHasPlaceholder).toBe(false);
+
+ // Migrate skills: the legacy section is replaced verbatim, in place — the {{SKILLS}}
+ // placeholder now sits exactly where the hardcoded text was.
+ const migrated = await member.post(`${agentBase}/skills/template-placeholder`, {});
+ expect(migrated.status).toBe(200);
+ const skillsDto = (await migrated.json()) as AgentSkillsConfigDto;
+ expect(skillsDto.templateHasPlaceholder).toBe(true);
+ expect(skillsDto.legacySectionPresent).toBe(false);
+ ({ config } = await getConfig());
+ expect(config.systemPrompt).toContain("{{SKILLS}}");
+ expect(config.systemPrompt).not.toContain(LEGACY_SKILLS_SECTION);
+ expect(config.systemPrompt.indexOf("{{SKILLS}}")).toBeLessThan(
+ config.systemPrompt.indexOf("{{MEMORY}}"),
+ );
+ // The vault's legacy section is untouched by the skills migration.
+ expect(config.systemPrompt).toContain(LEGACY_VAULT_SECTION);
+
+ // Migrate vault (owner-only endpoint) the same way.
+ const vaultRes = await owner.post(`${agentBase}/vault/template-placeholder`, {});
+ expect(vaultRes.status).toBe(200);
+ const vaultDto = (await vaultRes.json()) as AgentVaultConfigDto;
+ expect(vaultDto.templateHasPlaceholder).toBe(true);
+ expect(vaultDto.legacySectionPresent).toBe(false);
+ ({ config } = await getConfig());
+ expect(config.systemPrompt).not.toContain(LEGACY_VAULT_SECTION);
+ expect(config.systemPrompt.indexOf("{{VAULT}}")).toBeLessThan(
+ config.systemPrompt.indexOf("{{SKILLS}}"),
+ );
+
+ // Idempotent: a second call changes nothing and still succeeds.
+ const before = config.systemPrompt;
+ expect((await owner.post(`${agentBase}/vault/template-placeholder`, {})).status).toBe(200);
+ ({ config } = await getConfig());
+ expect(config.systemPrompt).toBe(before);
+ });
+
+ it("inserts {{SCHEDULES}} before # Environment when there is nothing to migrate", async () => {
+ expect(
+ (await owner.put(configPath, { config: { systemPrompt: LEGACY_TEMPLATE } })).status,
+ ).toBe(200);
+ const res = await owner.post(`${agentBase}/schedules/template-placeholder`, {});
+ expect(res.status).toBe(200);
+ const dto = (await res.json()) as AgentSchedulesConfigDto;
+ expect(dto.templateHasPlaceholder).toBe(true);
+ const { config } = await getConfig();
+ expect(config.systemPrompt.indexOf("{{SCHEDULES}}")).toBeGreaterThan(-1);
+ expect(config.systemPrompt.indexOf("{{SCHEDULES}}")).toBeLessThan(
+ config.systemPrompt.indexOf("# Environment"),
+ );
+ });
+
+ it("gates the vault / schedules endpoints owner-only and 404s outsiders everywhere", async () => {
+ // The endpoints follow their routers' modify conventions: skills is member-level
+ // (exercised in the migration test above); vault / schedules are owner-only.
+ expect((await member.post(`${agentBase}/vault/template-placeholder`, {})).status).toBe(403);
+ expect((await member.post(`${agentBase}/schedules/template-placeholder`, {})).status).toBe(403);
+ for (const feature of ["skills", "vault", "schedules"] as const) {
+ expect((await outsider.post(`${agentBase}/${feature}/template-placeholder`, {})).status).toBe(
+ 404,
+ );
+ }
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 7d8f1df2..965596ef 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -15,7 +15,10 @@ import type {
AgentCreateResponse,
AgentImportRequest,
AgentImportResponse,
+ AgentSchedulesConfigDto,
+ AgentSkillsConfigDto,
AgentSkillsResponse,
+ AgentVaultConfigDto,
AgentsResponse,
AgentTracesResponse,
ApprovalDecisionRequest,
@@ -210,6 +213,27 @@ export const putVault = (projectId: string, agentId: string, body: VaultUpdateRe
{ method: "PUT", body },
);
+/** Inserts the {{VAULT}} placeholder into the agent's prompt template — migrating a legacy hardcoded # Vault section verbatim when one is present (idempotent, owner-only). */
+export const insertVaultPlaceholder = (projectId: string, agentId: string) =>
+ apiFetch<AgentVaultConfigDto>(
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/vault/template-placeholder`,
+ { method: "POST", body: {} },
+ );
+
+/** Inserts the {{SKILLS}} placeholder into the agent's prompt template — migrating a legacy hardcoded # Skills section verbatim when one is present (idempotent). */
+export const insertSkillsPlaceholder = (projectId: string, agentId: string) =>
+ apiFetch<AgentSkillsConfigDto>(
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/skills/template-placeholder`,
+ { method: "POST", body: {} },
+ );
+
+/** Inserts the {{SCHEDULES}} placeholder into the agent's prompt template (idempotent, owner-only; Schedules has no legacy section to migrate). */
+export const insertSchedulesPlaceholder = (projectId: string, agentId: string) =>
+ apiFetch<AgentSchedulesConfigDto>(
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/schedules/template-placeholder`,
+ { method: "POST", body: {} },
+ );
+
// Memory (Agent-level, agent_state/memory/) -------------------------------------------------
/** Base path of an Agent's Memory API; the scope key and file name are single path segments (never a path). */
diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsx
index 65a14409..e8be5def 100644
--- a/packages/web/src/features/agents/agent-settings-page.tsx
+++ b/packages/web/src/features/agents/agent-settings-page.tsx
@@ -260,9 +260,11 @@ export function AgentSettingsPage() {
<McpServersSection agentId={agentId} initial={data.config.mcpServers} />
</div>
)}
- {tab === "skills" && <SkillsTab agentId={agentId} />}
- {tab === "vault" && <VaultTab agentId={agentId} />}
- {tab === "schedules" && <SchedulesTab agentId={agentId} />}
+ {tab === "skills" && <SkillsTab agentId={agentId} onConfigChanged={refreshConfig} />}
+ {tab === "vault" && <VaultTab agentId={agentId} onConfigChanged={refreshConfig} />}
+ {tab === "schedules" && (
+ <SchedulesTab agentId={agentId} onConfigChanged={refreshConfig} />
+ )}
</div>
</div>
</div>
diff --git a/packages/web/src/features/agents/prompt-injection-controls.tsx b/packages/web/src/features/agents/prompt-injection-controls.tsx
new file mode 100644
index 00000000..a48c1924
--- /dev/null
+++ b/packages/web/src/features/agents/prompt-injection-controls.tsx
@@ -0,0 +1,260 @@
+/**
+ * Shared prompt-injection controls for the Skills / Vault / Schedules tabs, mirroring the
+ * Memory tab's layout: an enable-switch card (label + switch, the memory tab's exact card
+ * shape) that writes immediately (so toggling never drags an unfinished prompt edit along),
+ * an amber alert when the template lacks the feature's section placeholder — with one-click
+ * insert, or one-click migration when the template still carries the legacy hardcoded
+ * section — and an editable prompt section (mono textarea + placeholder-chip reference +
+ * confirm-first save). The toggle and prompt govern prompt injection only — the feature
+ * itself keeps working with the switch off (vault values still reach subprocesses, tasks
+ * still fire, skills stay invocable).
+ *
+ * Exposed as a hook returning render slots (the useSaveConfirm convention) because the pieces
+ * straddle the host tab's own content: the switch and alert sit above it, the prompt editor
+ * below. The hook owns the config state; the tab seeds it via `applyConfig` from the
+ * getAgentConfig response it loads in parallel with its own data. `canEdit` carries the host
+ * tab's permission model (member-level on Skills, owner-only on Vault / Schedules).
+ */
+import { useCallback, useRef, useState } from "react";
+import type { ReactNode, RefObject } from "react";
+import type {
+ AgentConfigDto,
+ AgentSchedulesConfigDto,
+ AgentSkillsConfigDto,
+ AgentVaultConfigDto,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { useProject } from "../../state/project";
+import { Button } from "../../components/ui/button";
+import { Textarea } from "../../components/ui/input";
+import { Switch } from "../../components/ui/switch";
+import { useSaveConfirm } from "../../components/ui/confirm-modal";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+
+export type PromptInjectionFeature = "skills" | "vault" | "schedules";
+
+/** The strings each feature section supplies (S.skills / S.vault / S.schedule); migrate/legacyTemplate exist only where a legacy hardcoded section does. */
+interface PromptInjectionStrings {
+ enable: string;
+ templateMissing: string;
+ legacyTemplate?: string;
+ insertPlaceholder: string;
+ migrate?: string;
+ promptSection: string;
+ promptSectionHint: string;
+ promptLabel: string;
+ promptPlaceholders: ReadonlyArray<readonly [string, string]>;
+}
+
+/** The three feature DTOs share this shape; `legacySectionPresent` is absent on schedules (it never had a hardcoded section). */
+interface SectionConfigState {
+ enabled: boolean;
+ prompt: string;
+ templateHasPlaceholder: boolean;
+ legacySectionPresent?: boolean;
+}
+
+/** Same contract as the Prompt tab's inserter: execCommand keeps the textarea's native undo stack, with a state-splice fallback. */
+function insertPromptToken(
+ ref: RefObject<HTMLTextAreaElement | null>,
+ value: string,
+ setValue: (next: string) => void,
+ token: string,
+): void {
+ const el = ref.current;
+ if (el) {
+ el.focus();
+ const inserted = document.execCommand?.("insertText", false, token);
+ if (inserted) return; // onChange updates state from e.target.value
+ }
+ const start = el ? el.selectionStart : value.length;
+ const end = el ? el.selectionEnd : value.length;
+ setValue(value.slice(0, start) + token + value.slice(end));
+ requestAnimationFrame(() => {
+ if (!el) return;
+ el.focus();
+ const caret = start + token.length;
+ el.setSelectionRange(caret, caret);
+ });
+}
+
+export function usePromptInjection({
+ agentId,
+ feature,
+ strings,
+ canEdit,
+ onConfigChanged,
+}: {
+ agentId: string;
+ feature: PromptInjectionFeature;
+ strings: PromptInjectionStrings;
+ /** The host tab's permission model: false renders everything read-only (switch disabled, buttons hidden, prompt not saveable). */
+ canEdit: boolean;
+ /** Config writes happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them. */
+ onConfigChanged?: (() => void) | undefined;
+}): {
+ applyConfig: (config: AgentConfigDto) => void;
+ toggleCard: ReactNode;
+ alertStrip: ReactNode;
+ promptSection: ReactNode;
+} {
+ const { currentProject } = useProject();
+ const projectId = currentProject?.projectId ?? null;
+
+ // null until the host tab's load delivers the config (the slots render nothing until then).
+ const [state, setState] = useState<SectionConfigState | null>(null);
+ const [prompt, setPrompt] = useState("");
+ const [switchBusy, setSwitchBusy] = useState(false);
+ const promptRef = useRef<HTMLTextAreaElement>(null);
+ const { requestSave, element: saveConfirm } = useSaveConfirm();
+
+ // Stable so the host tab's load() can list it as a dependency without re-triggering itself.
+ const applyConfig = useCallback(
+ (config: AgentConfigDto) => {
+ const dto: AgentVaultConfigDto | AgentSkillsConfigDto | AgentSchedulesConfigDto =
+ config[feature];
+ setState(dto);
+ setPrompt(dto.prompt);
+ },
+ [feature],
+ );
+
+ /** The PUT body for this feature (a computed key would widen the request type, so switch explicitly). */
+ const featurePatch = (patch: { enabled?: boolean; prompt?: string }) =>
+ feature === "skills"
+ ? { config: { skills: patch } }
+ : feature === "vault"
+ ? { config: { vault: patch } }
+ : { config: { schedules: patch } };
+
+ const toggleEnabled = async (next: boolean) => {
+ if (!projectId) return;
+ setSwitchBusy(true);
+ try {
+ const res = await api.putAgentConfig(projectId, agentId, featurePatch({ enabled: next }));
+ applyConfig(res.config);
+ toastSuccess(S.common.saved);
+ onConfigChanged?.();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setSwitchBusy(false);
+ }
+ };
+
+ /** One idempotent config write: migrates the legacy section when present, else inserts the placeholder. */
+ const insertPlaceholder = async () => {
+ if (!projectId) return;
+ const insert =
+ feature === "skills"
+ ? api.insertSkillsPlaceholder
+ : feature === "vault"
+ ? api.insertVaultPlaceholder
+ : api.insertSchedulesPlaceholder;
+ try {
+ const dto = await insert(projectId, agentId);
+ setState(dto);
+ setPrompt(dto.prompt);
+ toastSuccess(S.common.saved);
+ onConfigChanged?.();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ };
+
+ /** Saves the prompt through the ordinary config write (confirm-first, like the other settings tabs). */
+ const savePrompt = () =>
+ requestSave(() => {
+ if (!projectId) return;
+ void api
+ .putAgentConfig(projectId, agentId, featurePatch({ prompt }))
+ .then((res) => {
+ applyConfig(res.config);
+ toastSuccess(S.common.saved);
+ onConfigChanged?.();
+ })
+ .catch((e: unknown) => toastError(apiErrorText(e)));
+ });
+
+ const toggleCard = state !== null && (
+ <div className="flex items-center justify-between gap-4 rounded-lg border border-gray-200 px-4 py-3 dark:border-gray-800">
+ <p className="text-sm font-medium text-gray-800 dark:text-gray-200">{strings.enable}</p>
+ <Switch
+ checked={state.enabled}
+ onChange={(v) => void toggleEnabled(v)}
+ disabled={switchBusy || !canEdit}
+ />
+ </div>
+ );
+
+ // Legacy templates get the migration wording (and the legacy strings always exist for the
+ // features that can report legacySectionPresent); everything else gets the plain insert.
+ const legacy = state?.legacySectionPresent === true;
+ const alertStrip = state !== null && !state.templateHasPlaceholder && (
+ <div className="flex items-center justify-between gap-4 rounded-lg border border-amber-300 bg-amber-50 px-4 py-3 dark:border-amber-700 dark:bg-amber-950/40">
+ <p className="text-xs text-amber-800 dark:text-amber-300">
+ {legacy ? (strings.legacyTemplate ?? strings.templateMissing) : strings.templateMissing}
+ </p>
+ {canEdit && (
+ <Button size="sm" className="shrink-0" onClick={() => void insertPlaceholder()}>
+ {legacy ? (strings.migrate ?? strings.insertPlaceholder) : strings.insertPlaceholder}
+ </Button>
+ )}
+ </div>
+ );
+
+ const promptSection = state !== null && (
+ <section className="space-y-2.5 rounded-lg border border-gray-200 p-3.5 dark:border-gray-800">
+ <div>
+ <h3 className="text-sm font-semibold text-gray-800 dark:text-gray-200">
+ {strings.promptSection}
+ </h3>
+ <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
+ {strings.promptSectionHint}
+ </p>
+ </div>
+ <Textarea
+ ref={promptRef}
+ label={strings.promptLabel}
+ mono
+ size="sm"
+ rows={12}
+ readOnly={!canEdit}
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ />
+ {/* Placeholder reference, the Prompt/Memory tab convention — a chip inserts at the cursor. */}
+ <div className="rounded-md border border-gray-200 bg-gray-50 p-3 dark:border-gray-800 dark:bg-gray-900">
+ <p className="mb-2 text-xs font-semibold text-gray-500">{S.agent.placeholdersTitle}</p>
+ <ul className="space-y-1">
+ {strings.promptPlaceholders.map(([token, desc]) => (
+ <li key={token} className="flex items-center gap-3 text-xs">
+ <button
+ type="button"
+ disabled={!canEdit}
+ onClick={() => insertPromptToken(promptRef, prompt, setPrompt, token!)}
+ title={S.memory.insertToken}
+ className="shrink-0 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono font-semibold text-gray-800 transition-colors duration-150 hover:border-gray-400 hover:bg-gray-100 disabled:pointer-events-none dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:border-gray-500 dark:hover:bg-gray-700"
+ >
+ {token}
+ </button>
+ <span className="text-gray-500 dark:text-gray-400">{desc}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ {canEdit && (
+ <div className="flex justify-end">
+ <Button size="sm" variant="primary" onClick={savePrompt}>
+ {S.common.save}
+ </Button>
+ </div>
+ )}
+ {saveConfirm}
+ </section>
+ );
+
+ return { applyConfig, toggleCard, alertStrip, promptSection };
+}
diff --git a/packages/web/src/features/agents/schedules-tab.tsx b/packages/web/src/features/agents/schedules-tab.tsx
index dbab9286..ba98e7fb 100644
--- a/packages/web/src/features/agents/schedules-tab.tsx
+++ b/packages/web/src/features/agents/schedules-tab.tsx
@@ -2,12 +2,21 @@
* Agent settings page "Schedule" tab: a table view over
* agent_state/schedule/*.toml (status badge derived from run state; "next / last
* fired" shown as two stacked rows) plus a shared create/edit modal form.
+ * Wrapping is controlled per column: compact cells (status, period, fire times,
+ * queue, actions) are nowrap, long text cells (name, target) truncate with the
+ * full value on hover, and the existing overflow-x-auto container takes over
+ * below the table's min width.
* Readable by any member; toggle/edit/delete are owner-only — PUT has whole-file
* replace semantics, so toggling also resends every field and only flips `enabled`.
* startAt/endAt use datetime-local inputs (local timezone), converted to ISO 8601 on
* submit; the "new Session each run" mode can also pick a Model — always a complete
* (provider, modelId) pair, since provider is never inferred; omitting it entirely falls
* back to the Project default. Mutual exclusivity with sessionId is validated server-side.
+ *
+ * Prompt-injection controls (usePromptInjection): the schedules.enabled switch, the
+ * {{SCHEDULES}}-placeholder alert and the editable schedules.prompt section, mirroring the
+ * Memory tab — owner-only, like the table edits. The prompt teaches the model to manage
+ * task files itself; the toggle never stops the server from firing configured tasks.
*/
import { useCallback, useEffect, useState } from "react";
import type {
@@ -37,6 +46,7 @@ import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
import { ModelSelect, PickerList } from "../chat/model-select";
import { WorkspaceSelect } from "../chat/workspace-select";
import { sameModelRef } from "../models/model-grouping";
+import { usePromptInjection } from "./prompt-injection-controls";
/** Display status → badge tone. */
const STATUS_TONE: Record<ScheduleStatus, BadgeTone> = {
@@ -198,10 +208,25 @@ function SessionSelect({
);
}
-export function SchedulesTab({ agentId }: { agentId: string }) {
+export function SchedulesTab({
+ agentId,
+ onConfigChanged,
+}: {
+ agentId: string;
+ /** Config writes (toggle / prompt / placeholder insert) happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them. */
+ onConfigChanged?: () => void;
+}) {
const { currentProject, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
const isOwner = currentProject?.role === "owner";
+ // Prompt-injection controls follow the tab's existing gate: owner-only edits.
+ const { applyConfig, toggleCard, alertStrip, promptSection } = usePromptInjection({
+ agentId,
+ feature: "schedules",
+ strings: S.schedule.injection,
+ canEdit: isOwner,
+ onConfigChanged,
+ });
const [data, setData] = useState<SchedulesResponse | null>(null);
// Tab-level error is only the initial list load failure; row/edit actions report via toast.
@@ -232,11 +257,17 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
setData(null);
setError(null);
try {
- setData(await api.listSchedules(projectId, agentId));
+ // The injection controls' state loads in parallel with the tab's own table.
+ const [schedules, configView] = await Promise.all([
+ api.listSchedules(projectId, agentId),
+ api.getAgentConfig(projectId, agentId),
+ ]);
+ setData(schedules);
+ applyConfig(configView.config);
} catch (e) {
setError(apiErrorText(e));
}
- }, [projectId, agentId]);
+ }, [projectId, agentId, applyConfig]);
useEffect(() => {
void load();
@@ -408,6 +439,9 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
)}
</div>
+ {toggleCard}
+ {alertStrip}
+
{data === null ? (
<SkeletonList rows={4} />
) : schedules.length === 0 ? (
@@ -415,15 +449,15 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
<p className="py-2 text-xs text-gray-400 dark:text-gray-500">{S.schedule.empty}</p>
) : (
<div className="overflow-x-auto overflow-y-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
- <table className="w-full min-w-[640px] text-left text-sm">
+ <table className="w-full min-w-[720px] text-left text-sm">
<thead>
<tr className="border-b border-gray-200 bg-gray-50/80 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900">
- <th className="px-3 py-2.5">{S.common.name}</th>
- <th className="px-3 py-2.5">{S.schedule.colStatus}</th>
- <th className="px-3 py-2.5">{S.schedule.colPeriod}</th>
- <th className="px-3 py-2.5">{S.schedule.colTarget}</th>
- <th className="px-3 py-2.5">{S.schedule.colFireTimes}</th>
- <th className="px-3 py-2.5">{S.schedule.colQueued}</th>
+ <th className="whitespace-nowrap px-3 py-2.5">{S.common.name}</th>
+ <th className="whitespace-nowrap px-3 py-2.5">{S.schedule.colStatus}</th>
+ <th className="whitespace-nowrap px-3 py-2.5">{S.schedule.colPeriod}</th>
+ <th className="whitespace-nowrap px-3 py-2.5">{S.schedule.colTarget}</th>
+ <th className="whitespace-nowrap px-3 py-2.5">{S.schedule.colFireTimes}</th>
+ <th className="whitespace-nowrap px-3 py-2.5">{S.schedule.colQueued}</th>
{isOwner && <th className="px-3 py-2.5" />}
</tr>
</thead>
@@ -433,8 +467,11 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
key={item.name}
className="border-b border-gray-100 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40"
>
- <td className="px-3 py-2 font-mono text-xs">{item.name}</td>
- <td className="px-3 py-2">
+ {/* Long text columns truncate with the full value on hover instead of wrapping. */}
+ <td className="max-w-40 truncate px-3 py-2 font-mono text-xs" title={item.name}>
+ {item.name}
+ </td>
+ <td className="whitespace-nowrap px-3 py-2">
{/* invalid reason is folded into the hover title. */}
<span title={item.invalidReason}>
<Badge tone={STATUS_TONE[item.status]}>
@@ -442,7 +479,7 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
</Badge>
</span>
</td>
- <td className="px-3 py-2 text-xs text-gray-500 dark:text-gray-400">
+ <td className="whitespace-nowrap px-3 py-2 text-xs text-gray-500 dark:text-gray-400">
{item.period !== undefined ? (
<span className="font-mono">{item.period}</span>
) : (
@@ -459,8 +496,9 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
S.schedule.newSession
)}
</td>
- {/* Top row: next fire time; bottom row: last fired time (both show — when absent). */}
- <td className="px-3 py-2 text-xs">
+ {/* Deliberate two-line stack — top: next fire time; bottom: last fired time
+ (both show — when absent); nowrap keeps each line whole. */}
+ <td className="whitespace-nowrap px-3 py-2 text-xs">
<span className="block text-gray-600 dark:text-gray-300">
{item.nextFireAt ? formatDateTime(item.nextFireAt) : "—"}
</span>
@@ -468,7 +506,7 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
{item.lastFiredAt ? formatDateTime(item.lastFiredAt) : "—"}
</span>
</td>
- <td className="px-3 py-2">
+ <td className="whitespace-nowrap px-3 py-2">
{item.queued && <Badge tone="brand">{S.schedule.queued}</Badge>}
</td>
{isOwner && (
@@ -531,6 +569,8 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
</Button>
)}
+ {promptSection}
+
{/* Shared create/edit modal form. */}
<Modal
open={form !== null}
diff --git a/packages/web/src/features/agents/skills-tab.tsx b/packages/web/src/features/agents/skills-tab.tsx
index 23b883c5..449737cc 100644
--- a/packages/web/src/features/agents/skills-tab.tsx
+++ b/packages/web/src/features/agents/skills-tab.tsx
@@ -11,6 +11,10 @@
* skill_exists asks before overwriting). Each row can also export the installed directory
* as a zip that round-trips through that same endpoint. Read and mutate are both
* member-level, matching the skills routes — no owner gating here.
+ *
+ * Prompt-injection controls (usePromptInjection): the skills.enabled switch, the
+ * {{SKILLS}}-placeholder alert (with legacy-template migration) and the editable
+ * skills.prompt section, mirroring the Memory tab.
*/
import { useCallback, useEffect, useState } from "react";
import type { ChangeEvent } from "react";
@@ -39,6 +43,7 @@ import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";
import { parkActiveDraft } from "../chat/draft-sessions";
import { buildImportPrompt } from "./skill-import-source";
+import { usePromptInjection } from "./prompt-injection-controls";
/** <label> version of the button look (matches Button secondary sm; the Button component only renders <button>) — same as the Overview tab's snapshot-import label. */
const UPLOAD_LABEL_CLASS =
@@ -57,12 +62,28 @@ interface PendingOverwrite {
name: string;
}
-export function SkillsTab({ agentId }: { agentId: string }) {
+export function SkillsTab({
+ agentId,
+ onConfigChanged,
+}: {
+ agentId: string;
+ /** Config writes (toggle / prompt / placeholder insert) happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them. */
+ onConfigChanged?: () => void;
+}) {
const navigate = useNavigate();
const { locale } = useLocale();
const userId = useAuth().user?.userId ?? null;
const { currentProject, agents, setCurrentAgentId, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
+ // Prompt-injection controls (toggle / template alert / prompt editor): member-level like
+ // every other mutation on this tab.
+ const { applyConfig, toggleCard, alertStrip, promptSection } = usePromptInjection({
+ agentId,
+ feature: "skills",
+ strings: S.skills.injection,
+ canEdit: true,
+ onConfigChanged,
+ });
const [skills, setSkills] = useState<SkillMetadataItem[] | null>(null);
// Tab-level error is only the initial list load failure; row/import actions report via toast or inside the modal.
@@ -83,12 +104,17 @@ export function SkillsTab({ agentId }: { agentId: string }) {
setSkills(null);
setError(null);
try {
- const res = await api.getAgentSkills(projectId, agentId);
+ // The injection controls' state loads in parallel with the tab's own list.
+ const [res, configView] = await Promise.all([
+ api.getAgentSkills(projectId, agentId),
+ api.getAgentConfig(projectId, agentId),
+ ]);
setSkills(res.skills);
+ applyConfig(configView.config);
} catch (e) {
setError(apiErrorText(e));
}
- }, [projectId, agentId]);
+ }, [projectId, agentId, applyConfig]);
useEffect(() => {
void load();
@@ -276,6 +302,9 @@ export function SkillsTab({ agentId }: { agentId: string }) {
</Button>
</div>
+ {toggleCard}
+ {alertStrip}
+
{skills === null ? (
<SkeletonList rows={4} />
) : skills.length === 0 ? (
@@ -341,6 +370,8 @@ export function SkillsTab({ agentId }: { agentId: string }) {
</div>
)}
+ {promptSection}
+
{/* Import modal: recommended chat install on top, zip upload below. */}
<Modal
open={importOpen}
diff --git a/packages/web/src/features/agents/vault-tab.tsx b/packages/web/src/features/agents/vault-tab.tsx
index c429a41c..dab2f67a 100644
--- a/packages/web/src/features/agents/vault-tab.tsx
+++ b/packages/web/src/features/agents/vault-tab.tsx
@@ -8,6 +8,10 @@
* The key name is injected into the Agent's system prompt to inform the model; the
* value is injected only into the exec_command subprocess environment, never into
* the model context.
+ *
+ * Prompt-injection controls (usePromptInjection): the vault.enabled switch, the
+ * {{VAULT}}-placeholder alert (with legacy-template migration) and the editable
+ * vault.prompt section, mirroring the Memory tab — owner-only, like the table edits.
*/
import { useCallback, useEffect, useState } from "react";
import type { VaultEntryInfo, VaultUpdateRequest } from "@prismshadow/penguin-server/api";
@@ -22,14 +26,30 @@ import { Modal } from "../../components/ui/modal";
import { ConfirmModal } from "../../components/ui/confirm-modal";
import { SkeletonList } from "../../components/ui/skeleton";
import { toastError, toastSuccess } from "../../components/ui/toast";
+import { usePromptInjection } from "./prompt-injection-controls";
/** Vault key naming rule (consistent with core/server): shell environment variable name. */
const VAULT_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
-export function VaultTab({ agentId }: { agentId: string }) {
+export function VaultTab({
+ agentId,
+ onConfigChanged,
+}: {
+ agentId: string;
+ /** Config writes (toggle / prompt / placeholder insert) happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them. */
+ onConfigChanged?: () => void;
+}) {
const { currentProject, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
const isOwner = currentProject?.role === "owner";
+ // Prompt-injection controls follow the tab's existing gate: owner-only edits.
+ const { applyConfig, toggleCard, alertStrip, promptSection } = usePromptInjection({
+ agentId,
+ feature: "vault",
+ strings: S.vault.injection,
+ canEdit: isOwner,
+ onConfigChanged,
+ });
const [entries, setEntries] = useState<VaultEntryInfo[] | null>(null);
// Tab-level error is only the initial load failure; saves/deletes report via toast.
@@ -51,12 +71,17 @@ export function VaultTab({ agentId }: { agentId: string }) {
setEntries(null);
setError(null);
try {
- const res = await api.getVault(projectId, agentId);
+ // The injection controls' state loads in parallel with the tab's own table.
+ const [res, configView] = await Promise.all([
+ api.getVault(projectId, agentId),
+ api.getAgentConfig(projectId, agentId),
+ ]);
setEntries(res.entries);
+ applyConfig(configView.config);
} catch (e) {
setError(apiErrorText(e));
}
- }, [projectId, agentId]);
+ }, [projectId, agentId, applyConfig]);
useEffect(() => {
void load();
@@ -140,6 +165,9 @@ export function VaultTab({ agentId }: { agentId: string }) {
)}
</div>
+ {toggleCard}
+ {alertStrip}
+
{entries === null ? (
<SkeletonList rows={4} />
) : entries.length === 0 ? (
@@ -191,6 +219,8 @@ export function VaultTab({ agentId }: { agentId: string }) {
</Button>
)}
+ {promptSection}
+
<Modal
open={adding}
title={S.vault.addTitle}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 8b46ca65..5f1c68bd 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -252,15 +252,25 @@ export const en: Strings = {
systemPrompt: "system_prompt template",
placeholdersTitle: "Available placeholders (click to insert)",
insertPlaceholder: "Insert at the system_prompt cursor",
- /** Order must match the default system prompt (core default-config.ts DEFAULT_SYSTEM_PROMPT). */
+ /** Order must match the default system prompt (core default-config.ts DEFAULT_SYSTEM_PROMPT). Inner tokens ({{VAULT_KEYS}} etc.) live in each feature tab's promptPlaceholders instead. */
placeholders: [
["{{AGENTS_MD}}", "Injects the AGENTS.md content"],
- ["{{VAULT_KEYS}}", "Injects the vault key-name section (empty when no keys)"],
- ["{{SKILL_METADATA}}", "Injects the installed skills' metadata lines (empty when none)"],
+ [
+ "{{VAULT}}",
+ "Injects the vault block (vault.prompt with the key-name list); empty when its toggle is off",
+ ],
+ [
+ "{{SKILLS}}",
+ "Injects the skills block (skills.prompt with installed-skill metadata); empty when its toggle is off",
+ ],
[
"{{MEMORY}}",
"Injects the memory block: memory.prompt plus memory.workspace_prompt (persistent workspaces only); empty when memory is off",
],
+ [
+ "{{SCHEDULES}}",
+ "Injects the scheduled-tasks block (schedules.prompt with the task-name roster); empty when its toggle is off",
+ ],
["{{PLATFORM}}", "Runtime platform"],
["{{OS_VERSION}}", "Operating system version"],
["{{SHELL}}", "Shell used to run commands"],
@@ -614,6 +624,26 @@ export const en: Strings = {
keyHint: "Letters, digits and underscores; must not start with a digit",
keyInvalid: "Invalid name: only letters, digits and underscores, not starting with a digit",
valueRequired: "Value must not be empty",
+ /** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
+ injection: {
+ enable: "Enable vault",
+ templateMissing:
+ "The prompt template has no {{VAULT}} placeholder, so the vault section never enters the context.",
+ legacyTemplate:
+ "The template still carries the legacy hardcoded # Vault section: one-click migration replaces it in place with the {{VAULT}} placeholder, wording unchanged, after which it is editable below.",
+ insertPlaceholder: "Insert the {{VAULT}} placeholder",
+ migrate: "Migrate to the {{VAULT}} placeholder",
+ promptSection: "Vault prompt",
+ promptSectionHint:
+ "What the template's {{VAULT}} placeholder expands to; nothing is injected when the toggle is off or the template lacks the placeholder.",
+ promptLabel: "Prompt",
+ promptPlaceholders: [
+ [
+ "{{VAULT_KEYS}}",
+ 'Vault key-name list (one "- KEY" line per key, names only — values are never injected; empty when no keys)',
+ ],
+ ] as ReadonlyArray<readonly [string, string]>,
+ },
},
schedule: {
@@ -662,6 +692,23 @@ export const en: Strings = {
modelDefault: "Project default",
deleteTitle: "Delete scheduled task",
deleteConfirm: (name: string): string => `Delete scheduled task "${name}"?`,
+ /** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
+ injection: {
+ enable: "Enable schedules",
+ templateMissing:
+ "The prompt template has no {{SCHEDULES}} placeholder, so the scheduled-tasks section never enters the context.",
+ insertPlaceholder: "Insert the {{SCHEDULES}} placeholder",
+ promptSection: "Schedules prompt",
+ promptSectionHint:
+ "What the template's {{SCHEDULES}} placeholder expands to — teaches the model to manage scheduled tasks with its file tools; nothing is injected when the toggle is off or the template lacks the placeholder.",
+ promptLabel: "Prompt",
+ promptPlaceholders: [
+ [
+ "{{SCHEDULE_LIST}}",
+ 'Current task-name list (one "- name" line per task; an empty-roster note when none exist)',
+ ],
+ ] as ReadonlyArray<readonly [string, string]>,
+ },
},
skills: {
@@ -738,6 +785,26 @@ export const en: Strings = {
importOverwriteBody: (name: string): string =>
`The skill "${name}" is already installed. Overwriting replaces all of its files (local edits included) and cannot be undone. Continue?`,
importOverwriteAction: "Overwrite",
+ /** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
+ injection: {
+ enable: "Enable skills",
+ templateMissing:
+ "The prompt template has no {{SKILLS}} placeholder, so the skills section never enters the context.",
+ legacyTemplate:
+ "The template still carries the legacy hardcoded # Skills section: one-click migration replaces it in place with the {{SKILLS}} placeholder, wording unchanged, after which it is editable below.",
+ insertPlaceholder: "Insert the {{SKILLS}} placeholder",
+ migrate: "Migrate to the {{SKILLS}} placeholder",
+ promptSection: "Skills prompt",
+ promptSectionHint:
+ "What the template's {{SKILLS}} placeholder expands to; nothing is injected when the toggle is off or the template lacks the placeholder.",
+ promptLabel: "Prompt",
+ promptPlaceholders: [
+ [
+ "{{SKILL_METADATA}}",
+ 'Installed skills\' metadata lines (one "- name — description" line per skill; empty when none)',
+ ],
+ ] as ReadonlyArray<readonly [string, string]>,
+ },
},
chat: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 7d48cf27..933835d3 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -243,15 +243,16 @@ export const zh = {
systemPrompt: "system_prompt 模板",
placeholdersTitle: "可用占位符(点击插入)",
insertPlaceholder: "插入到 system_prompt 光标处",
- /** Order must match the default system prompt (core default-config.ts DEFAULT_SYSTEM_PROMPT). */
+ /** Order must match the default system prompt (core default-config.ts DEFAULT_SYSTEM_PROMPT). Inner tokens ({{VAULT_KEYS}} 等) live in each feature tab's promptPlaceholders instead. */
placeholders: [
["{{AGENTS_MD}}", "注入 AGENTS.md 内容"],
- ["{{VAULT_KEYS}}", "注入密钥保险柜的键名小节(无键时为空)"],
- ["{{SKILL_METADATA}}", "注入已安装 Skill 的元数据行(无 Skill 时为空)"],
+ ["{{VAULT}}", "注入保险柜区块(vault.prompt,含键名清单);开关关闭时为空"],
+ ["{{SKILLS}}", "注入技能区块(skills.prompt,含已安装技能元数据);开关关闭时为空"],
[
"{{MEMORY}}",
"注入记忆区块:memory.prompt 加 memory.workspace_prompt(仅持久工作区);关闭记忆时为空",
],
+ ["{{SCHEDULES}}", "注入定时任务区块(schedules.prompt,含任务名清单);开关关闭时为空"],
["{{PLATFORM}}", "运行平台"],
["{{OS_VERSION}}", "操作系统版本"],
["{{SHELL}}", "命令执行使用的 Shell"],
@@ -590,6 +591,21 @@ export const zh = {
keyHint: "字母、数字与下划线,不能以数字开头",
keyInvalid: "键名不合法:仅字母、数字与下划线,且不能以数字开头",
valueRequired: "值不能为空",
+ /** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
+ injection: {
+ enable: "启用密钥保险柜",
+ templateMissing: "提示词模板中没有 {{VAULT}} 占位符,保险柜小节不会进入上下文。",
+ legacyTemplate:
+ "模板仍是旧版硬编码的 # Vault 段落:一键迁移会将该段落原位替换为 {{VAULT}} 占位符,措辞不变,此后可在下方编辑。",
+ insertPlaceholder: "插入 {{VAULT}} 占位符",
+ migrate: "迁移为 {{VAULT}} 占位符",
+ promptSection: "保险柜提示词",
+ promptSectionHint: "注入模板 {{VAULT}} 占位符的内容;开关关闭或模板无占位符时不注入。",
+ promptLabel: "提示词",
+ promptPlaceholders: [
+ ["{{VAULT_KEYS}}", "保险柜键名列表(每键一行「- KEY」,仅键名,值永不注入;无键时为空)"],
+ ] as ReadonlyArray<readonly [string, string]>,
+ },
},
schedule: {
@@ -638,6 +654,19 @@ export const zh = {
modelDefault: "Project 默认",
deleteTitle: "删除定时任务",
deleteConfirm: (name: string): string => `确认删除定时任务「${name}」?`,
+ /** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
+ injection: {
+ enable: "启用定时任务",
+ templateMissing: "提示词模板中没有 {{SCHEDULES}} 占位符,定时任务小节不会进入上下文。",
+ insertPlaceholder: "插入 {{SCHEDULES}} 占位符",
+ promptSection: "定时任务提示词",
+ promptSectionHint:
+ "注入模板 {{SCHEDULES}} 占位符的内容,教模型用文件工具管理定时任务;开关关闭或模板无占位符时不注入。",
+ promptLabel: "提示词",
+ promptPlaceholders: [
+ ["{{SCHEDULE_LIST}}", "现有任务名列表(每任务一行「- 名称」;无任务时注入空清单说明)"],
+ ] as ReadonlyArray<readonly [string, string]>,
+ },
},
skills: {
@@ -712,6 +741,21 @@ export const zh = {
importOverwriteBody: (name: string): string =>
`技能「${name}」已存在,覆盖安装将替换其全部文件(含本地改动),不可恢复。确认继续?`,
importOverwriteAction: "覆盖安装",
+ /** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
+ injection: {
+ enable: "启用技能",
+ templateMissing: "提示词模板中没有 {{SKILLS}} 占位符,技能小节不会进入上下文。",
+ legacyTemplate:
+ "模板仍是旧版硬编码的 # Skills 段落:一键迁移会将该段落原位替换为 {{SKILLS}} 占位符,措辞不变,此后可在下方编辑。",
+ insertPlaceholder: "插入 {{SKILLS}} 占位符",
+ migrate: "迁移为 {{SKILLS}} 占位符",
+ promptSection: "技能提示词",
+ promptSectionHint: "注入模板 {{SKILLS}} 占位符的内容;开关关闭或模板无占位符时不注入。",
+ promptLabel: "提示词",
+ promptPlaceholders: [
+ ["{{SKILL_METADATA}}", "已安装技能的元数据行(每技能一行「- 名称 — 描述」;无技能时为空)"],
+ ] as ReadonlyArray<readonly [string, string]>,
+ },
},
chat: {