Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(scheduled): manage project automations through Agent tools

Jack839bf332bd3b
diff --git a/apps/desktop/src/features/scheduled/ScheduledEditor.tsx b/apps/desktop/src/features/scheduled/ScheduledEditor.tsx
index 304ede136..4cc1c6de1 100644
--- a/apps/desktop/src/features/scheduled/ScheduledEditor.tsx
+++ b/apps/desktop/src/features/scheduled/ScheduledEditor.tsx
@@ -118,7 +118,7 @@ export function ScheduledEditor({
)}
</div>
{(cadence === "daily" || cadence === "weekly") && (
- <p className="dest-row-meta">{hour}:{minute}</p>
+ <p className="dest-row-meta">{hour}:{minute} · {t("scheduled.exactTimeHint")}</p>
)}
{cadence === "weekly" && (
<p className="dest-row-meta" aria-live="polite">
diff --git a/crates/host-core/src/permissions.rs b/crates/host-core/src/permissions.rs
index 19771c19e..87506e595 100644
--- a/crates/host-core/src/permissions.rs
+++ b/crates/host-core/src/permissions.rs
@@ -126,7 +126,7 @@ pub struct PermissionManager {
impl PermissionManager {
pub fn tool_risk_with_declared(tool_name: &str, declared: Option<&str>) -> Risk {
match tool_name {
- "Read" | "Glob" | "Grep" => Risk::Low,
+ "Read" | "Glob" | "Grep" | "ScheduledTaskList" => Risk::Low,
"Write" | "Edit" | "Bash" => Risk::High,
name if name.starts_with("plugin_") => match declared {
Some("low") => Risk::Low,
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 21cef3dd4..9e4e9766c 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1,4 +1,5 @@
mod scheduled_rpc;
+mod scheduled_tools;
use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};
use std::path::{Path, PathBuf};
@@ -3119,7 +3120,13 @@ async fn handle_request(
scheduled_rpc::handle(&st, method, params)
}
- "tools.list" => Ok(json!({ "tools": tools::builtin_tool_defs() })),
+ "tools.list" => {
+ let mut definitions = tools::builtin_tool_defs();
+ if let Some(items) = definitions.as_array_mut() {
+ items.extend(scheduled_tools::definitions());
+ }
+ Ok(json!({ "tools": definitions }))
+ }
"tools.execute" => {
let call_started = std::time::Instant::now();
let p: ToolsExecuteParams = serde_json::from_value(params.clone())
@@ -3617,6 +3624,9 @@ async fn handle_request(
&durable_mode,
)
.await
+ } else if scheduled_tools::recognizes(&p.tool_name) {
+ let st = state.lock().await;
+ scheduled_tools::execute(&st, &p)
} else {
tools::execute_tool_with_path_access(
ws_path.as_deref(),
diff --git a/crates/host-core/src/rpc/scheduled_tools.rs b/crates/host-core/src/rpc/scheduled_tools.rs
new file mode 100644
index 000000000..075f449a5
--- /dev/null
+++ b/crates/host-core/src/rpc/scheduled_tools.rs
@@ -0,0 +1,351 @@
+use super::{rpc_err, scheduled_rpc, AppState, JsonRpcError};
+use crate::{
+ scheduled, sessions,
+ tools::{ToolsExecuteParams, ToolsExecuteResult},
+};
+use serde_json::{json, Value};
+
+pub fn recognizes(name: &str) -> bool {
+ matches!(
+ name,
+ "ScheduledTaskList" | "ScheduledTaskCreate" | "ScheduledTaskUpdate" | "ScheduledTaskDelete"
+ )
+}
+
+pub fn definitions() -> Vec<Value> {
+ let fields = json!({
+ "title":{"type":"string","minLength":1,"maxLength":80},
+ "prompt":{"type":"string","minLength":1,"maxLength":64000},
+ "cadence":{"type":"string","enum":["manual","hourly","daily","weekly"]},
+ "enabled":{"type":"boolean"},
+ "schedule":{"type":"object","additionalProperties":false,"required":["hour","minute","weekday"],"properties":{
+ "hour":{"type":"integer","minimum":0,"maximum":23},
+ "minute":{"type":"integer","minimum":0,"maximum":59},
+ "weekday":{"type":"integer","minimum":0,"maximum":6},
+ "weekdays":{"type":"array","minItems":1,"maxItems":7,"uniqueItems":true,"items":{"type":"integer","minimum":0,"maximum":6}}
+ }}
+ });
+ ["ScheduledTaskList", "ScheduledTaskCreate", "ScheduledTaskUpdate", "ScheduledTaskDelete"].into_iter().map(|name| {
+ let mut properties = if matches!(name, "ScheduledTaskCreate" | "ScheduledTaskUpdate") { fields.clone() } else { json!({}) };
+ if matches!(name, "ScheduledTaskUpdate" | "ScheduledTaskDelete") { properties["id"] = json!({"type":"string"}); }
+ let required = match name { "ScheduledTaskCreate" => json!(["title","prompt","cadence"]), "ScheduledTaskList" => json!([]), _ => json!(["id"]) };
+ json!({"name":name,"description":"Manage scheduled tasks in the calling session's project.","risk":if name == "ScheduledTaskList" {"low"} else {"medium"},"parameters":{"type":"object","additionalProperties":false,"properties":properties,"required":required}})
+ }).collect()
+}
+
+fn invalid(message: &str) -> JsonRpcError {
+ rpc_err(1002, message, "INVALID_PARAMS")
+}
+
+fn execute_inner(st: &AppState, p: &ToolsExecuteParams) -> Result<Value, JsonRpcError> {
+ let session = sessions::get_session(&st.db, &p.session_id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .ok_or_else(|| rpc_err(1007, "session not found", "SESSION_NOT_FOUND"))?;
+ if sessions::session_mode(&st.db, &p.session_id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .as_deref()
+ != Some("agent")
+ {
+ return Err(rpc_err(
+ 1002,
+ "scheduled tools require Agent mode",
+ "TOOL_DISABLED_IN_PLAN",
+ ));
+ }
+ let workspace = session.summary.project_path;
+ let args = p
+ .args
+ .as_object()
+ .ok_or_else(|| invalid("arguments must be an object"))?;
+ let allowed: &[&str] = match p.tool_name.as_str() {
+ "ScheduledTaskList" => &[],
+ "ScheduledTaskCreate" => &["title", "prompt", "cadence", "schedule", "enabled"],
+ "ScheduledTaskUpdate" => &["id", "title", "prompt", "cadence", "schedule", "enabled"],
+ "ScheduledTaskDelete" => &["id"],
+ _ => return Err(invalid("unknown scheduled tool")),
+ };
+ if args.keys().any(|key| !allowed.contains(&key.as_str())) {
+ return Err(invalid("unsupported scheduled task field"));
+ }
+ if p.tool_name == "ScheduledTaskList" {
+ let tasks =
+ scheduled::list_tasks(&st.db).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ return Ok(
+ json!({"tasks": tasks.into_iter().filter(|task| task.workspace_path == workspace).collect::<Vec<_>>() }),
+ );
+ }
+ let existing = if p.tool_name != "ScheduledTaskCreate" {
+ let id = args
+ .get("id")
+ .and_then(Value::as_str)
+ .ok_or_else(|| invalid("id required"))?;
+ Some(
+ scheduled::get_task(&st.db, id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .filter(|task| task.workspace_path == workspace)
+ .ok_or_else(|| rpc_err(1007, "task not found in this project", "NOT_FOUND"))?,
+ )
+ } else {
+ None
+ };
+ for (key, limit) in [("title", 80), ("prompt", 64000)] {
+ if let Some(value) = args.get(key) {
+ let value = value
+ .as_str()
+ .ok_or_else(|| invalid("title and prompt must be strings"))?;
+ if value.trim().is_empty() || value.chars().count() > limit {
+ return Err(invalid("invalid title or prompt length"));
+ }
+ } else if p.tool_name == "ScheduledTaskCreate" {
+ return Err(invalid("title and prompt required"));
+ }
+ }
+ if args.get("enabled").is_some_and(|value| !value.is_boolean()) {
+ return Err(invalid("enabled must be a boolean"));
+ }
+ let cadence = match args.get("cadence") {
+ Some(value) => value
+ .as_str()
+ .filter(|v| matches!(*v, "manual" | "hourly" | "daily" | "weekly"))
+ .ok_or_else(|| invalid("invalid cadence"))?,
+ None => existing
+ .as_ref()
+ .map(|task| task.cadence.as_str())
+ .unwrap_or("manual"),
+ };
+ let mut input = p.args.clone();
+ if let Some(schedule) = args.get("schedule") {
+ let parsed: scheduled::timing::Schedule =
+ serde_json::from_value(schedule.clone()).map_err(|e| invalid(&e.to_string()))?;
+ parsed.validate().map_err(|e| invalid(&e.to_string()))?;
+ }
+ if p.tool_name == "ScheduledTaskCreate" {
+ if !args.contains_key("cadence") {
+ return Err(invalid("cadence required"));
+ }
+ if cadence == "hourly" && !args.contains_key("schedule") {
+ input["schedule"] = json!({"hour":0,"minute":0,"weekday":0});
+ } else if cadence == "manual" {
+ input["schedule"] = Value::Null;
+ }
+ }
+ if p.tool_name != "ScheduledTaskDelete"
+ && cadence != "manual"
+ && input.get("schedule").is_none()
+ && existing
+ .as_ref()
+ .and_then(|task| task.schedule.as_ref())
+ .is_none()
+ {
+ return Err(invalid("a schedule is required for automatic execution"));
+ }
+ let method = match p.tool_name.as_str() {
+ "ScheduledTaskCreate" => "scheduled.create",
+ "ScheduledTaskUpdate" => "scheduled.update",
+ _ => "scheduled.delete",
+ };
+ scheduled_rpc::handle_in_workspace(st, method, input, workspace)
+}
+
+pub fn execute(st: &AppState, p: &ToolsExecuteParams) -> ToolsExecuteResult {
+ let started = std::time::Instant::now();
+ let result = execute_inner(st, p);
+ let (ok, content, error_code) = match result {
+ Ok(content) => (true, content, None),
+ Err(error) => {
+ let code = error
+ .data
+ .as_ref()
+ .and_then(|data| data["errorCode"].as_str())
+ .unwrap_or("INTERNAL")
+ .to_string();
+ (
+ false,
+ json!({"error":error.message,"code":code}),
+ Some(code),
+ )
+ }
+ };
+ ToolsExecuteResult {
+ tool_call_id: p.tool_call_id.clone(),
+ ok,
+ is_error: (!ok).then_some(true),
+ content,
+ duration_ms: started.elapsed().as_millis() as u64,
+ denied: None,
+ error_code,
+ command_shell_id: None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Arc;
+ use tokio::sync::{mpsc, Mutex};
+
+ async fn call(state: &Arc<Mutex<AppState>>, session: &str, name: &str, args: Value) -> Value {
+ super::super::handle_request(
+ state.clone(),
+ "tools.execute",
+ json!({
+ "sessionId":session,"toolCallId":uuid::Uuid::new_v4().to_string(),
+ "toolName":name,"args":args,"mode":"agent"
+ }),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap()
+ }
+
+ #[tokio::test]
+ async fn scheduled_tools_crud_preserves_exact_time_and_session_project() {
+ let dir = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let other = tempfile::tempdir().unwrap();
+ let mut st = AppState::open(dir.path()).unwrap();
+ st.handshook = true;
+ st.db
+ .set_setting("app", &json!({"defaultPermissionMode":"auto"}))
+ .unwrap();
+ let path = st.workspace.set(project.path()).path;
+ let session = sessions::create_session(
+ &st.db,
+ None,
+ Some("agent".into()),
+ None,
+ None,
+ Some(path.clone()),
+ )
+ .unwrap();
+ let other_path = st.workspace.set(other.path()).path;
+ let other_session = sessions::create_session(
+ &st.db,
+ None,
+ Some("agent".into()),
+ None,
+ None,
+ Some(other_path),
+ )
+ .unwrap();
+ let plan = sessions::create_session(
+ &st.db,
+ None,
+ Some("plan".into()),
+ None,
+ None,
+ Some(path.clone()),
+ )
+ .unwrap();
+ let state = Arc::new(Mutex::new(st));
+ let created = call(
+ &state,
+ &session.id,
+ "ScheduledTaskCreate",
+ json!({
+ "title":"Review", "prompt":"Review project", "cadence":"daily", "enabled":false,
+ "schedule":{"hour":14,"minute":0,"weekday":0}
+ }),
+ )
+ .await;
+ assert_eq!(created["ok"], true, "{created}");
+ assert_eq!(created["content"]["task"]["enabled"], false);
+ let id = created["content"]["task"]["id"].as_str().unwrap();
+ assert_eq!(created["content"]["task"]["workspacePath"], path);
+ let listed = call(&state, &session.id, "ScheduledTaskList", json!({})).await;
+ assert_eq!(listed["content"]["tasks"][0]["id"], id);
+ let hidden = call(&state, &other_session.id, "ScheduledTaskList", json!({})).await;
+ assert_eq!(hidden["content"]["tasks"], json!([]));
+ let forbidden = call(
+ &state,
+ &other_session.id,
+ "ScheduledTaskUpdate",
+ json!({"id":id,"title":"Wrong project"}),
+ )
+ .await;
+ assert_eq!(forbidden["errorCode"], "NOT_FOUND");
+ let denied = call(&state, &plan.id, "ScheduledTaskDelete", json!({"id":id})).await;
+ assert_eq!(denied["errorCode"], "TOOL_DISABLED_IN_PLAN");
+ let update = call(
+ &state,
+ &session.id,
+ "ScheduledTaskUpdate",
+ json!({"id":id,"schedule":{"hour":15,"minute":30,"weekday":0},"enabled":false}),
+ )
+ .await;
+ assert_eq!(update["ok"], true, "{update}");
+ assert_eq!(update["content"]["task"]["schedule"]["minute"], 30);
+ assert_eq!(update["content"]["task"]["enabled"], false);
+ let invalid = call(
+ &state,
+ &session.id,
+ "ScheduledTaskUpdate",
+ json!({"id":id,"schedule":{"hour":25,"minute":0,"weekday":0}}),
+ )
+ .await;
+ assert_eq!(invalid["errorCode"], "INVALID_PARAMS");
+ let injected = call(
+ &state,
+ &session.id,
+ "ScheduledTaskUpdate",
+ json!({"id":id,"workspacePath":"elsewhere"}),
+ )
+ .await;
+ assert_eq!(injected["errorCode"], "INVALID_PARAMS");
+ let title = call(
+ &state,
+ &session.id,
+ "ScheduledTaskUpdate",
+ json!({"id":id,"title":"Updated"}),
+ )
+ .await;
+ assert_eq!(title["content"]["task"]["schedule"]["hour"], 15);
+ assert_eq!(title["content"]["task"]["schedule"]["minute"], 30);
+ let deleted = call(&state, &session.id, "ScheduledTaskDelete", json!({"id":id})).await;
+ assert_eq!(deleted["ok"], true, "{deleted}");
+ assert_eq!(
+ call(&state, &session.id, "ScheduledTaskList", json!({})).await["content"]["tasks"],
+ json!([])
+ );
+ }
+
+ #[test]
+ fn scheduled_mutations_require_approval_outside_auto_mode() {
+ use crate::permissions::{PermissionDecision, PermissionManager};
+ let permissions = PermissionManager::default();
+ let grants = std::collections::HashMap::new();
+ for tool in [
+ "ScheduledTaskCreate",
+ "ScheduledTaskUpdate",
+ "ScheduledTaskDelete",
+ ] {
+ assert!(permissions
+ .evaluate_auto_with_permission_mode("session", tool, "agent", "ask", &grants)
+ .is_none());
+ assert!(permissions
+ .evaluate_auto_with_permission_mode(
+ "session",
+ tool,
+ "agent",
+ "accept-edits",
+ &grants
+ )
+ .is_none());
+ assert!(matches!(
+ permissions
+ .evaluate_auto_with_permission_mode("session", tool, "plan", "auto", &grants),
+ Some(PermissionDecision::Deny)
+ ));
+ }
+ assert!(matches!(
+ permissions.evaluate_auto_with_permission_mode(
+ "session",
+ "ScheduledTaskList",
+ "agent",
+ "ask",
+ &grants
+ ),
+ Some(PermissionDecision::AllowOnce)
+ ));
+ }
+}
diff --git a/docs/adr/scheduled-desktop-automations.md b/docs/adr/scheduled-desktop-automations.md
index 0228869f0..d2ab1a643 100644
--- a/docs/adr/scheduled-desktop-automations.md
+++ b/docs/adr/scheduled-desktop-automations.md
@@ -57,3 +57,15 @@ automation depend on extension availability. A second agent loop would bypass
existing admission, persistence and permissions. Both are rejected. The pi
agent implementation remains the execution engine.
+## Conversation management
+
+Expose project-scoped CRUD as on-demand Agent tools using the existing
+`tools.execute` permission and audit pipeline. A thin Host adapter reuses the
+scheduled RPC handlers with the calling session's project, so background
+conversations cannot retarget tasks when the foreground workspace changes.
+List is read-only; mutations keep normal approvals. Plan/Goal stay denied.
+
+The UI offers four time periods (09:00, 14:00, 19:00, 22:00) to keep setup
+simple. AI tools retain precise local time configuration, and the form preserves
+those custom times. Direct database access or renderer-mediated tool mutation
+would duplicate ownership or bypass permission gates and is rejected.
diff --git a/docs/guide/automations.md b/docs/guide/automations.md
index 43334d219..159a2298a 100644
--- a/docs/guide/automations.md
+++ b/docs/guide/automations.md
@@ -44,3 +44,14 @@ Scheduled tasks now execute while the desktop is running, with hourly intervals
configuration, editing, pause/resume, a visible clock entry and run history.
Existing data stays readable; old cadence-only records do not start automatically.
+## Manage tasks in a conversation
+
+In Agent mode, ask to create, list, update or delete scheduled tasks in the
+conversation's project. For example: “Change the project review to 15:30.”
+The AI uses ScheduledTaskList/Create/Update/Delete through the normal tool
+permission pipeline; Ask mode requests approval for mutations. Plan/Goal
+cannot use these tools. Tasks from another project are not visible or writable.
+
+An exact time set by AI appears as Custom in the form. Editing the name or
+prompt preserves it; selecting a period explicitly replaces it with that
+period's default time.
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 0ede6ddab..d4813a4ad 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1192,3 +1192,21 @@ Tool outcomes (`TOOL_DENIED`, `TOOL_TIMEOUT`, `PATH_OUTSIDE_WORKSPACE`,
produce the documented durable statuses and events
13. Bash validates the pinned shell ID/dialect, streams stdout/stderr, enforces
the 60s default/bounded override, and shuts down the complete process tree
+
+## Scheduled automation tools
+
+Agent mode advertises on-demand ScheduledTaskList, ScheduledTaskCreate,
+ScheduledTaskUpdate and ScheduledTaskDelete tools. They run through
+`tools.execute`, including existing permissions and audit records, and reuse
+the scheduled RPC domain handlers. List is low risk; mutations require normal
+approval in Ask/Accept Edits. Plan/Goal deny all four even under Auto.
+
+The Host rechecks durable session mode and derives project scope from the
+calling session, never the foreground workspace or model-supplied paths.
+Create binds that scope; list filters it; update/delete require matching scope.
+Unknown fields, invalid cadence, empty title/prompt, invalid time and invalid
+weekday selections are rejected before mutation. Delete refuses active runs.
+Create requires title, prompt and cadence; automatic daily/weekly tasks require
+a schedule. Update takes an existing ID and partial fields, preserving all
+unspecified configuration. Exact local times remain supported despite the
+UI's four period presets. No new DB schema or transport is introduced.
diff --git a/docs/zh-CN/guide/automations.md b/docs/zh-CN/guide/automations.md
index 64aedf480..076ec5bfa 100644
--- a/docs/zh-CN/guide/automations.md
+++ b/docs/zh-CN/guide/automations.md
@@ -34,3 +34,11 @@ description: 配置本地周期任务并查看运行结果。
补齐应用运行期间的自动执行、每小时间隔循环、时分设置和星期多选、编辑、暂停/启用、侧边栏
时钟入口和运行记录。旧数据保持兼容,仅设置了周期的旧任务不会自动启动。
+## 在对话中管理任务
+
+在 Agent 模式下,可要求 AI 创建、查询、修改或删除当前对话所属项目的定时任务,
+例如“把项目巡检改到 15:30”。通过正常工具权限流程执行;Ask 模式下修改操作需要授权,
+Plan/Goal 模式不支持这些工具。不能查看或修改其他项目的任务。
+
+AI 设置的具体时间会在表单中显示为自定义时间。修改名称、提示词时保留它;
+只有明确选择某个时段,才替换成该时段的默认时间。
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index aa2e0cb2e..6d79161f4 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -973,3 +973,15 @@ JSON-RPC 错误携带一个数字 `code` 以及 `data.errorCode`,后者是来
产生记录的持久状态和事件
13. Bash 验证固定 shell ID/dialect,传输 stdout/stderr,强制执行
60s default/bounded 覆盖,并关闭整个进程树
+
+## 定时任务工具
+
+Agent 模式按需提供 ScheduledTaskList、ScheduledTaskCreate、ScheduledTaskUpdate、
+ScheduledTaskDelete。通过 tools.execute 复用现有授权、审计和定时任务领域处理器。
+查询为低风险;Ask/Accept Edits 下修改需授权。Plan/Goal 即使在 Auto 下也拒绝。
+
+Host 重新检查会话的持久化模式,按调用会话的项目限制访问,不使用前台项目或模型传入路径。
+创建时绑定该项目,查询过滤项目,修改/删除要求项目匹配。未知字段、非法周期、空标题或
+提示词、非法时间和星期在写入前拒绝;不能删除运行中的任务。创建需 title、prompt、cadence;
+每天/每周自动任务需 schedule。修改使用已存在的 ID 并保留未指定字段。界面虽只提供四个
+时段,工具仍支持具体本地时间。不新增数据库 schema 或传输协议。
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 572831bf8..7f13d9daa 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1,3 +1,4 @@
+import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { randomUUID } from "node:crypto";
import {
settledDelegationMessage,
@@ -2670,6 +2671,7 @@ Delegation rules:
const externalPathHint =
" An explicit path outside the workspace and session scratch roots requires permission unless the effective mode is Auto.";
const describe = (toolName: string): string => {
+ if (scheduledToolDescriptions[toolName]) return scheduledToolDescriptions[toolName];
switch (toolName) {
case "BrowserPreview":
return "Open a workspace HTML file in PI-Desktop's built-in browser panel. `path` is workspace-relative (e.g. \"demo/index.html\"). The preview live-reloads on later edits to the file or its sibling assets, so call once per page.";
@@ -3101,7 +3103,7 @@ Delegation rules:
label: toolName,
description: describe(toolName),
parameters: Type.Object(
- parameters[toolName] ?? { command: Type.String() },
+ scheduledToolParameters[toolName] ?? parameters[toolName] ?? { command: Type.String() },
),
// Normalizing here, above the write lock, means every consumer below
// this line — the lock key, the host call, the transcript record — sees
@@ -3180,7 +3182,7 @@ Delegation rules:
]
: ["Read", "Glob", "Grep", "BrowserPreview", "Bash"];
if (this.mode === "agent") {
- tools.push("PluginScaffold", "PluginPack");
+ tools.push("PluginScaffold", "PluginPack", ...Object.keys(scheduledToolParameters));
}
const builtins = tools.map(exec);
diff --git a/packages/agent-runtime/src/scheduled-tools.ts b/packages/agent-runtime/src/scheduled-tools.ts
new file mode 100644
index 000000000..32cefc676
--- /dev/null
+++ b/packages/agent-runtime/src/scheduled-tools.ts
@@ -0,0 +1,25 @@
+import { Type } from "@earendil-works/pi-ai";
+
+const schedule = Type.Object({
+ hour: Type.Integer({ minimum: 0, maximum: 23 }),
+ minute: Type.Integer({ minimum: 0, maximum: 59 }),
+ weekday: Type.Integer({ minimum: 0, maximum: 6, description: "Monday=0. Use 0 for daily/hourly schedules." }),
+ weekdays: Type.Optional(Type.Array(Type.Integer({ minimum: 0, maximum: 6 }), { minItems: 1, maxItems: 7, uniqueItems: true })),
+}, { additionalProperties: false });
+const cadence = Type.Union([Type.Literal("manual"), Type.Literal("hourly"), Type.Literal("daily"), Type.Literal("weekly")]);
+const title = Type.String({ minLength: 1, maxLength: 80 });
+const prompt = Type.String({ minLength: 1, maxLength: 64000 });
+
+export const scheduledToolParameters: Record<string, Parameters<typeof Type.Object>[0]> = {
+ ScheduledTaskList: {},
+ ScheduledTaskCreate: { title, prompt, cadence, schedule: Type.Optional(schedule), enabled: Type.Optional(Type.Boolean()) },
+ ScheduledTaskUpdate: { id: Type.String(), title: Type.Optional(title), prompt: Type.Optional(prompt), cadence: Type.Optional(cadence), schedule: Type.Optional(schedule), enabled: Type.Optional(Type.Boolean()) },
+ ScheduledTaskDelete: { id: Type.String() },
+};
+
+export const scheduledToolDescriptions: Record<string, string> = {
+ ScheduledTaskList: "List scheduled automations in this conversation's project, including IDs, exact times and enabled state. Use before updating or deleting; never guess IDs.",
+ ScheduledTaskCreate: "Create a scheduled automation in this conversation's project. Requires app running. Hourly waits one hour; daily/weekly require a local-time schedule. Time defaults: morning 09:00, afternoon 14:00, evening 19:00, night 22:00; use an exact requested time when given. Weekly may select multiple weekdays. Never create a recurring task unless the user requests it.",
+ ScheduledTaskUpdate: "Update a listed automation in this conversation's project. Change its exact local hour/minute, prompt, cadence, title, or enabled flag (false pauses, true resumes). Preserve unspecified fields. For a time change, supply the full schedule and retain its existing weekdays. Only modify the task requested by the user.",
+ ScheduledTaskDelete: "Delete a listed automation and its run history in this conversation's project, only when the user requests deletion. A currently running task cannot be deleted.",
+};
diff --git a/scripts/e2e-scheduled.mjs b/scripts/e2e-scheduled.mjs
index 8fc81747a..3f28f324c 100644
--- a/scripts/e2e-scheduled.mjs
+++ b/scripts/e2e-scheduled.mjs
@@ -334,6 +334,37 @@ try {
acceptDelete = true;
await click("Delete");
await waitFor(async () => (await invoke("scheduledList")).tasks.length === 0, 5000, "confirmed deletion");
+ await evaluate(`document.querySelector('[data-nav="home"]').click()`);
+ await waitFor(() => evaluate(`document.querySelector('.page-title')?.textContent !== 'Scheduled'`), 5000, "leave tasks before conversation CRUD");
+ const chat = (await invoke("sessionCreate", { title: "Scheduled AI CRUD", mode: "agent", projectPath: project, providerId: provider.id, modelId: "fixture", permissionMode: "auto" })).session;
+ for (const scenario of ["create", "read", "update", "delete"]) {
+ model.setScenario(scenario);
+ await invoke("agentPrompt", { sessionId: chat.id, content: `${scenario} the scheduled task; for update use 15:30.`, viewingSessionId: chat.id });
+ await waitFor(async () => {
+ const session = (await invoke("sessionGet", chat.id)).session;
+ return session.messages.some(message => message.role === "assistant" && JSON.stringify(message).includes(`SCHEDULE_AI_${scenario.toUpperCase()}_OK`));
+ }, 60_000, `AI ${scenario} turn`);
+ const tasks = (await invoke("scheduledList")).tasks;
+ if (scenario === "delete") assert.equal(tasks.length, 0);
+ else { assert.equal(tasks[0].id, model.taskId); assert.equal(tasks[0].enabled, false); }
+ if (scenario === "update") {
+ assert.equal(tasks[0].schedule.hour,15);
+ assert.equal(tasks[0].schedule.minute,30);
+ await evaluate(`document.querySelector('[data-nav="scheduled"]').click()`);
+ await waitFor(() => evaluate(`document.body.innerText.includes('AI managed task')`),15000,"AI task appears on page");
+ await click("Edit task");
+ assert.equal(await evaluate(`document.querySelector('button[aria-label="Time"]').textContent.trim()`),'Custom · 15:30');
+ await screenshot('after-ai-custom-time.png');
+ await fill('form input','AI managed task renamed');
+ await click('Save task');
+ await waitFor(() => evaluate(`!document.querySelector('form')`),5000,'save without resetting AI time');
+ assert.equal((await invoke('scheduledList')).tasks[0].schedule.minute,30);
+ assert.equal((await invoke('scheduledList')).tasks[0].enabled,false);
+ }
+ }
+ assert.ok(model.results.some(result => result.name === 'ScheduledTaskDelete' && result.value.ok));
+ if (evidence) writeFileSync(join(evidence,'ai-crud.json'),JSON.stringify(model.results,null,2));
+ console.log('PASS normal conversation AI tools: discover, create, list, update exact time, preserve UI custom time, delete');
console.log(
"PASS scheduled user path: create, time, weekday dropdown/multiple selection, validation, keyboard, hourly interval, edit, pause/resume, manual run, transcript, automatic run, delete",
);