Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/ai-scheduled-task-capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,17 @@

执行身份由最后保存任务的人决定。未绑定身份的旧任务按项目 Owner、独立任务记录的 Owner 的顺序查找个人凭据。Codex 和 Claude Code 优先使用执行账号的默认个人执行机器上的「账号登录」,需要 Runner 0.10.2 或以上版本,并启用对应 CLI。默认机器离线或未启用账号登录时,任务改用执行账号在个人配置中填写的 API Key,以所选 CLI 和模型在云端执行。Key 缺失或执行失败时记录具体原因。CodeBuddy 缺少个人 Key 时可以使用平台共享 Key,模型限于管理员允许的列表。保存时会校验可用的凭据。

工具访问范围由执行账号和项目决定。关闭页面后任务继续执行,直到 CLI 结束或在会话页停止。MCP 网关在本轮结束时关闭。
工具访问范围由执行账号和项目决定。AI 定时任务可配置每轮执行时限 `timeoutMinutes`(1–240 分钟,默认 30 分钟,旧任务自动使用默认值)。关闭页面后任务继续执行,直到 CLI 结束、达到时限或用户在会话页停止。超时会停止 CLI 及本轮 MCP 调用,并在执行记录中显示失败原因。已派发的 SOP 按自己的生命周期运行。

定时提示词直接调用 `runs_start` 或 `issues_dispatch` 取得运行 ID,通过 `runs_retry` 重试时沿用原运行 ID。如果模型把这些操作放进结束会话的草稿,平台会让它继续本轮并直接调用对应工具。提示词要求等待 SOP 结果时,使用 `runs_wait` 传入该 ID。服务端每次最多等 25 秒,读到成功、失败、取消、待人工处理或暂停就返回。窗口到期仍在运行时返回 `timedOut: true`,调用方可以继续等待同一运行。

由于任务以保存人(或项目 Owner)身份、完全权限执行,`/api/schedule-jobs` 的新建、修改、立即运行和删除都要求项目写权限(Owner、平台管理员或非 viewer 成员),列表只返回调用者所在项目的任务;按 id 保存时既校验原项目也校验目标项目。执行身份只由服务端决定,请求里的 `ownerUserId`、`runAsUserId` 不生效。项目记录已不存在的任务只允许平台管理员或该任务原 Owner 管理。

## 实现与验证

- `internal/httpapi/assistant_schedule.go`:按所选模型的 CLI 选择执行账号,不再给这一轮单独设超时。
- `internal/httpapi/assistant_schedule.go`:按所选模型的 CLI 选择执行账号,并把每轮时限传给对话执行。
- `internal/httpapi/assistant_tasks.go`:定时任务打开一轮普通对话(`executeGeneration` → `POST /api/assistant/chat`),系统提示词、技能、流式和停止都走主页路径;跑完再把结果写回任务。
- `internal/httpapi/agent_tool_session.go`:工具网关跟当前轮次的 context 一起结束,没有 5 分钟或固定时长的轮次上限。
- `internal/httpapi/agent_tool_session.go`:工具网关随当前轮次结束,在途调用随执行取消。
- `TestScheduledAssistantCanDispatchSOP`:通过定时执行链路调用真实平台派发接口,使用内存测试数据和仅含审批节点的 SOP。
- `TestScheduledAssistantNativeGatewayKeepsWorkspaceAndTerminalReply`:模拟 CLI 通过本地回环网关提交最终回复,验证执行前会话、租约控制器初始化、绑定和附件留存。

Expand Down
1 change: 1 addition & 0 deletions docs/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ curl -H "Authorization: Bearer $AGENTFLOW_TOKEN" "$AGENTFLOW_URL/api/health"
| `GET`, `POST` | `/api/runs` |
| `GET`, `DELETE` | `/api/runs/{runId}` |
| `GET` | `/api/runs/{runId}/stream` |
| `GET` | `/api/runs/{runId}/wait` |
| `GET` | `/api/runs/{runId}/logs` |
| `GET` | `/api/runs/{runId}/logs.txt` |
| `GET` | `/api/runs/{runId}/telemetry` |
Expand Down
46 changes: 46 additions & 0 deletions docs/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,46 @@ tags:
- name: Analytics
- name: Feedback
paths:
/api/runs/{id}/wait:
parameters:
- {name: id, in: path, required: true, schema: {type: string}}
get:
tags: [Runs]
operationId: waitForRun
summary: Wait for an SOP result or human action
description: |
Reads the current status of one SOP. Returns as soon as it is succeeded,
failed, cancelled, waiting or paused. If the wait window expires first,
the current status is returned with timedOut=true.
parameters:
- name: timeoutSec
in: query
description: Seconds to wait. Zero reads the current status immediately.
schema: {type: integer, minimum: 0, maximum: 25, default: 25}
responses:
"200":
description: Latest SOP status
content:
application/json:
schema:
type: object
required: [runId, projectId, status, terminal, timedOut]
properties:
runId: {type: string}
projectId: {type: string}
status: {type: string}
terminal: {type: boolean, description: "Status is succeeded, failed, or cancelled"}
timedOut: {type: boolean, description: The wait window ended while the run was still active or queued}
"400":
description: Invalid timeoutSec
"401":
$ref: "#/components/responses/Unauthorized"
"403":
$ref: "#/components/responses/Forbidden"
"404":
description: Run not found
"409":
description: The run is a conversation workspace
/api/runs/{id}/control:
parameters:
- {name: id, in: path, required: true, schema: {type: string}}
Expand Down Expand Up @@ -5343,6 +5383,12 @@ components:
assistantModel:
type: string
description: Model id from GET /api/assistant/models?schedule=1.
timeoutMinutes:
type: integer
minimum: 0
maximum: 240
default: 30
description: AI jobs only. Minutes allowed for each execution, including tool calls and waits. Omitted or 0 uses 30. Expiry stops the AI turn and records a failed execution. Dispatched SOPs continue independently.
ownerUserId:
type: integer
format: int64
Expand Down
3 changes: 2 additions & 1 deletion internal/application/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ func PublicOperations() []Operation {
{Name: "runs_control_get", Description: "Read the run mode (sop or workspace), waiting reason, allowed control actions and delivery acceptance. Node execution progress is separate from test results and user acceptance. Read this before changing a run's state.", Method: "GET", Path: "/api/runs/{id}/control", ReadOnly: true},
{Name: "runs_start", Description: "Start an SOP Run", Method: "POST", Path: "/api/runs"},
{Name: "runs_get", Description: "Get one Run", Method: "GET", Path: "/api/runs/{id}", ReadOnly: true},
{Name: "runs_wait", Description: "Wait for the SOP with path.id to succeed, fail, be cancelled, or need human action (waiting/paused). One call waits up to 25 seconds. If timedOut is true, the SOP is still active or queued; keep waiting on the same run ID if needed.", Method: "GET", Path: "/api/runs/{id}/wait", ReadOnly: true},
{Name: "runs_delete", Description: "Delete a finished Run", Method: "DELETE", Path: "/api/runs/{id}"},
{Name: "runs_eval_start", Description: "Manually start an LLM quality evaluation of a finished SOP run. Body: {model}. Uses the current user's CodeBuddy key and assistant model catalog.", Method: "POST", Path: "/api/runs/{id}/eval"},
{Name: "runs_eval_get", Description: "Get the latest SOP run evaluation", Method: "GET", Path: "/api/runs/{id}/eval", ReadOnly: true},
Expand Down Expand Up @@ -123,7 +124,7 @@ func PublicOperations() []Operation {
{Name: "schedule_jobs_publish", Description: "Publish a credential-free shared AI task version from an independent task. baseVersion is required for optimistic concurrency.", Method: "POST", Path: "/api/schedule-jobs/{id}/publish"},
{Name: "schedule_jobs_list", Description: "List scheduled SOP jobs", Method: "GET", Path: "/api/schedule-jobs", ReadOnly: true},
{Name: "schedule_job_executions_list", Description: "List schedule job executions newest first: status, error, durationMs, AI reply summary and the runs[] (issueId, runId) each execution dispatched. Look up a Trace ID copied from the schedule execution panel or a scheduler log line (trace=...) with query.traceId; filter by jobId or status (running/success/failed/waiting). Follow runs[].runId with runs_get.", Method: "GET", Path: "/api/schedule-job-executions", ReadOnly: true},
{Name: "schedule_jobs_save", Description: "Create or update a scheduled job. Two exclusive kinds: trigger jobs (skipDispatch=false, require workflowId) scan issues in issueStatuses (backlog/todo/in_progress/in_review/blocked; default backlog+todo), run baseline guard, and dispatch SOP with optional maxDispatch (1-10 successful issue dispatches per execution; omitted or 0 defaults to 10); AI jobs (skipDispatch=true, require assistantPrompt or sharedTaskId+sharedTaskVersion+parameterValues) run a CodeBuddy prompt only. Timing is intervalSec or 5-field cron (Asia/Shanghai). Optional notifications bind up to 3 configured project Bots (botId, events succeeded/failed, template, contentMode template/ai, aiInstruction). Use notification_bots_list to select an existing Bot. AI content reuses this task output; {{task.name}}, {{result}} and {{ai.summary}} are supported.", Method: "PUT", Path: "/api/schedule-jobs"},
{Name: "schedule_jobs_save", Description: "Create or update a scheduled job. Two exclusive kinds: trigger jobs (skipDispatch=false, require workflowId) scan issues in issueStatuses (backlog/todo/in_progress/in_review/blocked; default backlog+todo), run baseline guard, and dispatch SOP with optional maxDispatch (1-10 successful issue dispatches per execution; omitted or 0 defaults to 10); AI jobs (skipDispatch=true, require assistantPrompt or sharedTaskId+sharedTaskVersion+parameterValues) run a prompt with timeoutMinutes (1-240; omitted or 0 defaults to 30). Timing is intervalSec or 5-field cron (Asia/Shanghai). Optional notifications bind up to 3 configured project Bots (botId, events succeeded/failed, template, contentMode template/ai, aiInstruction). Use notification_bots_list to select an existing Bot. AI content reuses this task output; {{task.name}}, {{result}} and {{ai.summary}} are supported.", Method: "PUT", Path: "/api/schedule-jobs"},
{Name: "schedule_jobs_delete", Description: "Delete a scheduled SOP job", Method: "DELETE", Path: "/api/schedule-jobs/{id}"},
{Name: "schedule_jobs_run", Description: "Start a scheduled job on the server and return immediately (lastStatus=running). Closing the client does not cancel it; poll schedule_jobs_list until lastStatus leaves running.", Method: "POST", Path: "/api/schedule-jobs/{id}/run"},
{Name: "assistant_sessions_list", Description: "List the assistant conversations the caller may read: their own sessions, SOP shared sessions of authorized runs, and conversations of projects they belong to. Use it to resolve a chat session link before reading it.", Method: "GET", Path: "/api/assistant/sessions", ReadOnly: true},
Expand Down
24 changes: 24 additions & 0 deletions internal/domain/schedule_execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,30 @@ type ScheduleExecutionWindow struct {
AvgMs int64 `json:"avgMs"`
}

const (
DefaultScheduleTimeoutMinutes = 30
MaxScheduleTimeoutMinutes = 240
)

// NormalizeScheduleTimeoutMinutes validates an AI job's execution limit.
func NormalizeScheduleTimeoutMinutes(minutes int) (int, error) {
if minutes == 0 {
return DefaultScheduleTimeoutMinutes, nil
}
if minutes < 1 || minutes > MaxScheduleTimeoutMinutes {
return 0, fmt.Errorf("执行超时必须为 1–%d 分钟", MaxScheduleTimeoutMinutes)
}
return minutes, nil
}

func (j ScheduleJob) ExecutionTimeout() time.Duration {
minutes, err := NormalizeScheduleTimeoutMinutes(j.TimeoutMinutes)
if err != nil {
minutes = DefaultScheduleTimeoutMinutes
}
return time.Duration(minutes) * time.Minute
}

// ScheduleSessionFixed is ScheduleJob.SessionMode for an AI job that keeps
// running in one pinned conversation.
const ScheduleSessionFixed = "fixed"
Expand Down
3 changes: 3 additions & 0 deletions internal/domain/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ type ScheduleJob struct {
Cron string `json:"cron,omitempty"`
AssistantPrompt string `json:"assistantPrompt,omitempty"`
AssistantModel string `json:"assistantModel,omitempty"`
// TimeoutMinutes bounds one AI execution, including tool calls and SOP waits.
// Zero uses the default for jobs saved before this field existed.
TimeoutMinutes int `json:"timeoutMinutes,omitempty"`
// SessionMode picks the Studio conversation an AI job runs in: empty opens
// a new conversation for every execution; "fixed" keeps continuing
// FixedSessionID.
Expand Down
3 changes: 2 additions & 1 deletion internal/httpapi/agent_tool_lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ func TestAssistantAndScheduledTaskKeepToolsPastFiveMinutes(t *testing.T) {
if session == nil {
t.Fatal("turn has no gateway bound to its execution context")
}
agentToolSessions.purgeExpired(time.Now().Add(24 * time.Hour))
// Go past the former five-minute TTL within the default scheduled deadline.
agentToolSessions.purgeExpired(time.Now().Add(10 * time.Minute))
if _, ok := agentToolSessions.get(session.Token); !ok || ctx.Err() != nil {
t.Fatal("long-running generation lost its tools")
}
Expand Down
7 changes: 6 additions & 1 deletion internal/httpapi/agent_tool_mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,9 @@ func (h *agentToolGateway) callTerminal(session *AgentToolSession, name string,
logAgentToolEvent("terminal-invalid", "mode="+string(session.Mode), "tool="+name, "err="+truncateRunes(err.Error(), 160))
return mcpToolTextResult("草稿参数校验失败,本轮继续;请按以下错误修正后重新提交,不代表工具不可用:"+err.Error(), true), nil
}
if err := validateScheduledRunDrafts(session.ctx, reply.Drafts); err != nil {
return mcpToolTextResult(err.Error(), true), nil
}
if h.deps != nil && h.repo != nil {
if err := h.assistant().vetProposalDrafts(session, &reply); err != nil {
logAgentToolEvent("terminal-invalid", "mode="+string(session.Mode), "tool="+name, "err="+truncateRunes(err.Error(), 160))
Expand Down Expand Up @@ -410,7 +413,9 @@ func (h *agentToolGateway) dispatch(ctx context.Context, session *AgentToolSessi
if session.WorkspaceToken != "" && session.RunID != "" && strings.HasPrefix(tool.UpstreamName, "runs_") && assistantToolInput(call).Path["id"] == session.RunID {
ctx = engine.WithConversationWorkspaceToken(ctx, session.WorkspaceToken, session.RunID)
}
if session.workspaceTurn != nil && strings.HasPrefix(tool.UpstreamName, "runs_") {
// Waiting only reads status. Do not hold the workspace operation lock
// while a separate tool or turn may be advancing the run.
if session.workspaceTurn != nil && strings.HasPrefix(tool.UpstreamName, "runs_") && tool.UpstreamName != "runs_wait" {
releaseTurn := session.workspaceTurn.lockOperation()
defer releaseTurn()
ctx = session.workspaceTurn.withLease(ctx, assistantToolInput(call).Path["id"])
Expand Down
4 changes: 4 additions & 0 deletions internal/httpapi/assistant.go
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,10 @@ func (h *assistantHandlers) chat(c *gin.Context) {
continue
}
if hasRecoveredReply {
if err := validateScheduledRunDrafts(ctx, recoveredReply.Drafts); err != nil {
fail(502, err.Error())
return
}
reply = recoveredReply
} else {
fail(502, "本轮未提交回复,请再试一次")
Expand Down
5 changes: 5 additions & 0 deletions internal/httpapi/assistant_generation.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,11 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assist
g.Status = "failed"
g.Error = "会话工作区续租失败,生成已中断"
g.Failure = &domain.AssistantFailure{Code: "WORKSPACE_LEASE_LOST", Phase: "server", Message: g.Error, Suggestion: "检查已执行操作及工作区状态后再重试;可下载诊断信息排查。"}
} else if ctx.Err() == context.DeadlineExceeded {
failure := classifyAssistantFailure(ctx, ctx.Err())
failure.Message = "生成超时"
g.Error, g.Failure = failure.Message, &failure
rec.diagnostics.terminate(failure.Code, failure.Message, diagUser)
} else {
g.Status = "cancelled"
g.Error = "生成已停止"
Expand Down
20 changes: 19 additions & 1 deletion internal/httpapi/assistant_schedule.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"strings"
"time"

"agentflow/internal/domain"
"agentflow/internal/repo"
Expand All @@ -19,6 +20,8 @@ type scheduledSessionPolicy struct {
// KeepHistory keeps the conversations of earlier runs so each execution
// record can open its own; the session janitor trims them later.
KeepHistory bool
// Timeout caps the turn and its tool calls, including waits for SOP results.
Timeout time.Duration
// Opened, when set, learns the conversation as soon as it is created,
// before the prompt finishes.
Opened func(sessionID string)
Expand All @@ -35,6 +38,21 @@ func scheduledSessionPolicyFrom(ctx context.Context) scheduledSessionPolicy {
return p
}

// Terminal drafts are applied after the CLI exits, too late for a scheduled
// prompt to receive the run ID and wait for or report its outcome.
func validateScheduledRunDrafts(ctx context.Context, drafts []assistantDraft) error {
if assistantSessionOriginFrom(ctx).Source != domain.AssistantSourceScheduled {
return nil
}
for _, draft := range drafts {
switch draft.Tool {
case "issues_dispatch", "runs_start", "runs_retry":
return fmt.Errorf("本次草稿未执行。请直接调用 agentflow__%s 获取运行 ID;按任务要求等待结果时,继续用 agentflow__runs_wait 查询同一 ID", draft.Tool)
}
}
return nil
}

func (h *assistantHandlers) prepareScheduleJob(job domain.ScheduleJob) (string, error) {
msg, _, err := h.runScheduleJobPrompt(job)
return msg, err
Expand Down Expand Up @@ -89,7 +107,7 @@ func (h *assistantHandlers) runScheduleJobPromptReporting(job domain.ScheduleJob
}
ctx := withAssistantExecMode(context.Background(), assistantExecModeForApproval(AssistantApprovalAuto))
ctx = withAssistantSessionOrigin(ctx, domain.AssistantSourceScheduled, job.ID)
policy := scheduledSessionPolicy{KeepHistory: true, Opened: opened}
policy := scheduledSessionPolicy{KeepHistory: true, Timeout: job.ExecutionTimeout(), Opened: opened}
if job.UsesFixedSession() {
policy.Continue = strings.TrimSpace(job.FixedSessionID)
}
Expand Down
Loading
Loading