Parcourir la source

feat(cli): DispatchTasks 工具 S1——contracts schema/port + core handler + 执行链路布线

按 docs/specs/workspace-task-dispatch.md 实现:
- contracts:DispatchTasks 输入/输出 schema(1-50 任务、自包含 prompt、execute 开关)
  与 TaskDispatchPort(逐项结果判别返回,失败隔离)
- core:dispatch-tasks.ts 工具(统一确认 needsApproval、OffPeak 轮 deny、
  汇总序列化)+ 注册门 includeDispatchTasks(端口在场 + 非 subagent 子会话,
  子任务不注入端口即防递归分发)
- 布线:tool/types、executor types/impl/call-runner、runtime types/deps/helpers

验证:contracts/core typecheck 通过;core lint 0 error;
contracts lint 的 6 个 max-lines 失败为上游存量文件债务,与本次无关
wubinggen il y a 1 mois
Parent
commit
fbaedaab

+ 1 - 0
apps/zcode-cli/packages/contracts/src/index.ts

@@ -28,6 +28,7 @@ export * from "./interfaces/dynamic-workflow-snippet.port.js";
 export * from "./interfaces/model-catalog.port.js";
 export * from "./interfaces/automation.port.js";
 export * from "./interfaces/off-peak.port.js";
+export * from "./interfaces/task-dispatch.port.js";
 export * from "./interfaces/topic-resource.port.js";
 export * from "./interfaces/mcp.port.js";
 

+ 31 - 0
apps/zcode-cli/packages/contracts/src/interfaces/task-dispatch.port.ts

@@ -0,0 +1,31 @@
+// ============================================================
+// Task Dispatch Port - workspace task batch creation boundary
+// ============================================================
+// 与 OffPeakPort 兄弟并列。core 工具只表达意图(清单 + 是否执行),
+// 真正的 createTask/首发命令由 host 侧实现(复用 zcodeTaskServiceAdapter
+// 的 v4 createSession 路径,统一 permissionScope 由 host 从确认结果注入)。
+// 返回逐项结果而非抛错:单项失败不阻塞其余(spec §4 失败隔离)。
+
+import type {
+  DispatchTaskItem,
+  DispatchTaskResult,
+} from "../tools/dispatch-tasks.js";
+
+export interface TaskDispatchContext {
+  /** 当前工具调用所在 session;host 用它解析 workspace 与模型选择继承。 */
+  sessionId?: string;
+  /** 用户在统一确认窗的最终决定(可改写工具入参的 execute)。 */
+  execute: boolean;
+}
+
+export interface TaskDispatchPort {
+  /**
+   * 按清单在当前 workspace 下创建任务;execute=true 时逐项首发 prompt(全并发)。
+   * 实现必须逐项隔离失败并返回完整 results 列表;仅在整批不可恢复(如端口未配置
+   * 之外的系统性错误)时抛错。
+   */
+  dispatch(
+    tasks: DispatchTaskItem[],
+    context: TaskDispatchContext,
+  ): Promise<{ results: DispatchTaskResult[] }>;
+}

+ 82 - 0
apps/zcode-cli/packages/contracts/src/tools/dispatch-tasks.ts

@@ -0,0 +1,82 @@
+// ============================================================
+// Dispatch Tasks tool - workspace-level task batch dispatch
+// ============================================================
+// 设计合同见根目录 docs/specs/workspace-task-dispatch.md。
+// 关键约束:
+// - 子会话不继承本对话历史,prompt 必须自包含;schema description 里显式告知模型。
+// - execute 可被用户在统一确认窗改写(仅创建 / 创建并执行),host 端以确认结果为准。
+// - 失败隔离:单项失败不阻塞其余,输出为逐项结果的有界列表,不回灌子会话正文。
+
+import { z } from "zod";
+import { toToolJsonSchema } from "./json-schema.js";
+
+const nonEmptyString = z.string().trim().min(1);
+
+export const DISPATCH_TASKS_MAX_TASKS = 50;
+export const DISPATCH_TASKS_TITLE_MAX_CHARS = 120;
+
+export const DispatchTaskItemSchema = z
+  .object({
+    id: nonEmptyString
+      .max(64)
+      .describe(
+        "Short stable slug for this task, unique within this dispatch (for example 'fix-login-crash'). Used by dependsOn references and the result summary.",
+      ),
+    title: nonEmptyString
+      .max(DISPATCH_TASKS_TITLE_MAX_CHARS)
+      .describe(
+        "Concise task title shown in the workspace task list, for example '修复登录页崩溃'. No file paths.",
+      ),
+    prompt: nonEmptyString.describe(
+      "Self-contained instructions for this task. The new session does NOT inherit this conversation's history, so restate all needed context (files, symptoms, acceptance criteria) inside the prompt.",
+    ),
+    dependsOn: z
+      .array(nonEmptyString.max(64))
+      .max(DISPATCH_TASKS_MAX_TASKS)
+      .optional()
+      .describe(
+        "Ids of tasks this one logically depends on. Display-only in v1 (all tasks run concurrently); kept for future ordered execution.",
+      ),
+  })
+  .strict();
+export type DispatchTaskItem = z.infer<typeof DispatchTaskItemSchema>;
+
+export const DispatchTasksInputSchema = z
+  .object({
+    tasks: z.array(DispatchTaskItemSchema).min(1).max(DISPATCH_TASKS_MAX_TASKS).describe(
+      "The organized task list to create under the current workspace. Deduplicate overlapping items first; each item must be independently actionable.",
+    ),
+    execute: z
+      .boolean()
+      .default(true)
+      .describe(
+        "Whether to also start executing each task after creation. The user can override this in the confirmation dialog (create-only mode leaves tasks as drafts).",
+      ),
+  })
+  .strict();
+export type DispatchTasksInput = z.infer<typeof DispatchTasksInputSchema>;
+export const DispatchTasksInputJsonSchema = toToolJsonSchema(DispatchTasksInputSchema);
+
+/** 单项终态;failure 仅在 status 为 failed 时出现一行摘要,不带堆栈。 */
+export const DispatchTaskResultSchema = z
+  .object({
+    id: nonEmptyString.max(64),
+    title: z.string(),
+    status: z.enum(["created", "started", "failed"]),
+    sessionId: nonEmptyString.optional(),
+    failure: z.string().max(400).optional(),
+  })
+  .strict();
+export type DispatchTaskResult = z.infer<typeof DispatchTaskResultSchema>;
+
+export const DispatchTasksOutputSchema = z
+  .object({
+    executed: z.boolean(),
+    createdCount: z.number().int().nonnegative(),
+    failedCount: z.number().int().nonnegative(),
+    results: z.array(DispatchTaskResultSchema).max(DISPATCH_TASKS_MAX_TASKS),
+    message: nonEmptyString,
+  })
+  .strict();
+export type DispatchTasksOutput = z.infer<typeof DispatchTasksOutputSchema>;
+export const DispatchTasksOutputJsonSchema = toToolJsonSchema(DispatchTasksOutputSchema);

+ 1 - 0
apps/zcode-cli/packages/contracts/src/tools/index.ts

@@ -19,6 +19,7 @@ export * from "./skill.js";
 export * from "./todo.js";
 export * from "./automation.js";
 export * from "./off-peak.js";
+export * from "./dispatch-tasks.js";
 export * from "./target.js";
 export * from "./plan-mode.js";
 export * from "./ask-user-question.js";

+ 1 - 0
apps/zcode-cli/packages/core/src/runtime/deps.ts

@@ -116,6 +116,7 @@ export type {
   AttachmentStorageMetadata,
   AutomationPort,
   OffPeakPort,
+  TaskDispatchPort,
   TopicResourcePort,
   BackgroundExecutionSnapshot,
   BackgroundTaskCancelResult,

+ 5 - 0
apps/zcode-cli/packages/core/src/runtime/helpers/runtime-tools.ts

@@ -68,6 +68,10 @@ function registerRuntimeBuiltInTools(runtime: AgentRuntimeInternal, deps: AgentR
     // offPeakPort 只在 host 下发 offPeakToolEnabled 时注入(灰度/远程门在 host 端),
     // 端口存在即代表曝光允许;subagent 子会话与 automation 同规则不暴露。
     includeOffPeak: Boolean(deps.offPeakPort) && runtime.config.taskType !== "subagent_child",
+    // 任务分发与 off-peak 同规则:端口在场(宿主主会话注入)+ 非 subagent 子会话。
+    // 子任务会话不注入端口,天然防递归分发(spec TD-5)。
+    includeDispatchTasks:
+      Boolean(deps.taskDispatchPort) && runtime.config.taskType !== "subagent_child",
     // 动态工作流灰度门:与 off-peak 相反,
     // 这里不能用端口在场做判据——十个工具的端口在任何 CLI 里都装配齐全,灰度是 Host 的决定。
     // 取值收在 tool-allowlist.ts,与分支刷新那个入口共用同一个推导。
@@ -189,6 +193,7 @@ function createRuntimeToolExecutor(
     artifactStore: deps.artifactStore,
     automationPort: deps.automationPort,
     offPeakPort: deps.offPeakPort,
+    taskDispatchPort: deps.taskDispatchPort,
     topicResourcePort: deps.topicResourcePort,
     sessionStore: deps.sessionStore,
     sessionModePort: createRuntimeSessionModePort(runtime),

+ 2 - 0
apps/zcode-cli/packages/core/src/runtime/types.ts

@@ -74,6 +74,7 @@ import type {
   ExecutionShellSelection,
   AutomationPort,
   OffPeakPort,
+  TaskDispatchPort,
   TopicResourcePort,
   FileSystemPort,
   HttpClientPort,
@@ -384,6 +385,7 @@ export interface AgentRuntimeDeps {
   artifactStore?: ToolArtifactStorePort;
   automationPort?: AutomationPort;
   offPeakPort?: OffPeakPort;
+  taskDispatchPort?: TaskDispatchPort;
   topicResourcePort?: TopicResourcePort;
   contextSourcePort?: ContextSourcePort;
   eventSink?: SessionEventSink;

+ 1 - 0
apps/zcode-cli/packages/core/src/tool/executor/call-runner.ts

@@ -438,6 +438,7 @@ async function executeToolCallImpl(
         artifactStore: deps.artifactStore,
         automationPort: deps.automationPort,
         offPeakPort: deps.offPeakPort,
+        taskDispatchPort: deps.taskDispatchPort,
         topicResourcePort: deps.topicResourcePort,
         sessionStore: deps.sessionStore,
         sessionModePort: deps.sessionModePort,

+ 1 - 0
apps/zcode-cli/packages/core/src/tool/executor/impl.ts

@@ -60,6 +60,7 @@ export class ToolExecutorImpl implements ToolExecutor {
       artifactStore: options.artifactStore,
       automationPort: options.automationPort,
       offPeakPort: options.offPeakPort,
+      taskDispatchPort: options.taskDispatchPort,
       topicResourcePort: options.topicResourcePort,
       sessionStore: options.sessionStore,
       sessionModePort: options.sessionModePort,

+ 3 - 0
apps/zcode-cli/packages/core/src/tool/executor/types.ts

@@ -18,6 +18,7 @@ import type {
   Model,
   ModelCatalogPort,
   OffPeakPort,
+  TaskDispatchPort,
   TopicResourcePort,
   PdfDocumentPort,
   PermissionBrokerPort,
@@ -107,6 +108,7 @@ export interface ToolExecutorOptions {
   artifactStore?: ToolArtifactStorePort;
   automationPort?: AutomationPort;
   offPeakPort?: OffPeakPort;
+  taskDispatchPort?: TaskDispatchPort;
   topicResourcePort?: TopicResourcePort;
   sessionStore?: SessionStorePort;
   sessionModePort?: SessionModePort;
@@ -221,6 +223,7 @@ export interface ToolExecutorDeps {
   artifactStore?: ToolArtifactStorePort;
   automationPort?: AutomationPort;
   offPeakPort?: OffPeakPort;
+  taskDispatchPort?: TaskDispatchPort;
   topicResourcePort?: TopicResourcePort;
   sessionStore?: SessionStorePort;
   sessionModePort?: SessionModePort;

+ 156 - 0
apps/zcode-cli/packages/core/src/tool/handlers/dispatch-tasks.ts

@@ -0,0 +1,156 @@
+// ============================================================
+// Dispatch Tasks Tool Handler
+// ============================================================
+// 设计合同:docs/specs/workspace-task-dispatch.md(根目录)。
+// 边界要点(勿照抄 OffPeak 的方向):
+// - deny:闲时派发轮禁用(复用 assertNotOffPeakTurn);子任务/actor 会话由
+//   bootstrap 的工具可见面过滤(同 offPeakPort 的 includeOffPeak 门),handler
+//   不重复判断宿主注入事实。
+// - 统一确认:permission.needsApproval=true,reason 内带清单摘要——这是
+//   「一次授权全部」的落点;execute 的最终值由确认结果回写(port context)。
+// - 失败隔离:port 返回逐项 results,handler 只做汇总序列化,不再吞错。
+
+import {
+  CoreErrorType,
+  createCoreError,
+  DispatchTasksInputSchema,
+  DispatchTasksOutputJsonSchema,
+  DispatchTasksInputJsonSchema,
+  DispatchTasksOutputSchema,
+  type DispatchTasksOutput,
+  type ToolPermissionSpec,
+} from "@zcode/contracts";
+import type { ToolEntry, ToolExecutionContext, ToolHandler } from "../types.js";
+import { assertNotOffPeakTurn } from "./off-peak.js";
+
+const DISPATCH_TOOL_TIMEOUT_MS = 120_000;
+const DISPATCH_MODEL_BYTES = 32_000;
+
+function assertDispatchPort(
+  context: ToolExecutionContext,
+): asserts context is ToolExecutionContext & {
+  taskDispatchPort: NonNullable<ToolExecutionContext["taskDispatchPort"]>;
+} {
+  if (context.taskDispatchPort) return;
+  throw createCoreError(
+    CoreErrorType.ConfigurationError,
+    "TaskDispatchPort is not configured for DispatchTasks",
+    {
+      context: {
+        toolCallId: context.toolCallId,
+        toolName: "DispatchTasks",
+      },
+      recoverable: false,
+    },
+  );
+}
+
+export const dispatchTasksHandler: ToolHandler = async (input, context) => {
+  assertNotOffPeakTurn(context, "DispatchTasks", {
+    hint: "Dispatch tasks from a regular conversation instead.",
+  });
+  const parsed = DispatchTasksInputSchema.parse(input);
+  assertDispatchPort(context);
+
+  const { results } = await context.taskDispatchPort.dispatch(parsed.tasks, {
+    sessionId: context.sessionId,
+    // 确认窗批准即视为对整批的统一授权;execute 以用户在确认窗的最终选择为准
+    //(host 侧回写,工具入参只是模型建议值)。
+    execute: parsed.execute,
+  });
+
+  const createdCount = results.filter((r) => r.status !== "failed").length;
+  const failedCount = results.length - createdCount;
+  const executed = parsed.execute;
+  const summaryLines = results.map((r) => {
+    if (r.status === "failed") {
+      return `- [failed] ${r.id}: ${r.title} — ${r.failure ?? "unknown error"}`;
+    }
+    const state = r.status === "started" ? "started" : "created";
+    return `- [${state}] ${r.id}: ${r.title}`;
+  });
+  const message = executed
+    ? `Dispatched ${createdCount} task(s) under the current workspace (${failedCount} failed). Task list:\n${summaryLines.join("\n")}`
+    : `Created ${createdCount} draft task(s) under the current workspace (${failedCount} failed); they are NOT executing. Task list:\n${summaryLines.join("\n")}`;
+
+  return {
+    executed,
+    createdCount,
+    failedCount,
+    results,
+    message,
+  } satisfies DispatchTasksOutput;
+};
+
+function dispatchPermission(): ToolPermissionSpec {
+  return {
+    permission: "dispatchTasks",
+    reason: "DispatchTasks creates tasks under the current workspace and (if confirmed) starts executing them with the granted permission scope. Confirming grants this scope to ALL tasks in the batch.",
+    riskLevel: "medium" as const,
+    sideEffectScope: "workspace" as const,
+    needsApproval: true,
+    patternSources: ["toolName", "input"],
+    denyPriority: "beforeAsk" as const,
+  };
+}
+
+const dispatchResultBudget = {
+  maxInlineBytes: DISPATCH_MODEL_BYTES,
+  maxModelBytes: DISPATCH_MODEL_BYTES,
+  strategy: "truncate" as const,
+  preview: {
+    maxBytes: DISPATCH_MODEL_BYTES,
+    direction: "head" as const,
+  },
+};
+
+const dispatchTimeout = {
+  defaultMs: DISPATCH_TOOL_TIMEOUT_MS,
+  maxMs: DISPATCH_TOOL_TIMEOUT_MS,
+  allowCallOverride: false,
+};
+
+export const dispatchTasksToolEntry: ToolEntry = {
+  capability:
+    "Organize a batch of bugs/requests into a task list and create them under the current workspace, optionally executing them concurrently",
+  metadata: {
+    name: "DispatchTasks",
+    description:
+      "Create multiple independent tasks under the current workspace from one organized list (typical use: the user pastes a pile of bugs). Each task becomes a real task in the workspace task list with its own session. The user confirms ONCE for the whole batch (task list + shared permission scope) and can switch between create-only and create-and-execute. All tasks run concurrently when executed; one failure does not block the others.",
+    modelInstructions: [
+      "Use this only when the user clearly wants multiple independent tasks handled as a batch (a pile of bugs, a list of small fixes). For a single piece of work, use a normal conversation instead.",
+      "First deduplicate and merge overlapping items, then emit the final list in ONE call. Do not call this tool repeatedly for the same batch.",
+      "Every prompt MUST be self-contained: the new sessions do NOT inherit this conversation's history. Restate files, symptoms and acceptance criteria inside each prompt.",
+      "Set execute=false only when the user explicitly asks to create tasks without running them now.",
+      "After a successful dispatch, reply with a brief summary only; the workspace task list is the authoritative view.",
+    ],
+    readOnly: false,
+    destructive: false,
+    concurrentSafe: false,
+    timeoutMs: DISPATCH_TOOL_TIMEOUT_MS,
+    maxOutputBytes: DISPATCH_MODEL_BYTES,
+    sideEffectScope: "workspace",
+    riskLevel: "medium",
+    needsApproval: true,
+  },
+  handler: dispatchTasksHandler,
+  inputSchema: DispatchTasksInputJsonSchema,
+  outputSchema: DispatchTasksOutputJsonSchema,
+  runtimeInputSchema: DispatchTasksInputSchema,
+  runtimeOutputSchema: DispatchTasksOutputSchema,
+  permission: dispatchPermission(),
+  resultBudget: dispatchResultBudget,
+  timeout: dispatchTimeout,
+  cancellation: {
+    supported: false,
+    cleanup: "none",
+    userVisibleMessage:
+      "DispatchTasks was cancelled; already-created tasks remain in the workspace task list",
+  },
+  trace: {
+    required: true,
+    propagateToAdapters: true,
+    recordInput: "summary",
+    recordOutput: "summary",
+  },
+};

+ 9 - 0
apps/zcode-cli/packages/core/src/tool/handlers/index.ts

@@ -45,6 +45,7 @@ import {
   cronUpdateToolEntry,
 } from "./cron.js";
 import { offPeakCreateToolEntry, offPeakListToolEntry } from "./off-peak.js";
+import { dispatchTasksToolEntry } from "./dispatch-tasks.js";
 import {
   createEnterPlanModeToolEntry,
   enterPlanModeToolEntry,
@@ -93,6 +94,9 @@ export const builtInTools: ToolEntry[] = [
   cronDeleteToolEntry,
   offPeakCreateToolEntry,
   offPeakListToolEntry,
+  // 项目级任务分发(docs/specs/workspace-task-dispatch.md):与 OffPeak 同款
+  // 端口在场门(includeDispatchTasks),子会话/actor 由宿主不注入端口即不可见。
+  dispatchTasksToolEntry,
   enterPlanModeToolEntry,
   exitPlanModeToolEntry,
   askUserQuestionToolEntry,
@@ -188,6 +192,8 @@ interface RegisterBuiltInToolsOptions {
   includeAutomation?: boolean;
   /** Off-Peak 会话内创建工具面;由 host 的 offPeakToolEnabled flag(灰度/远程门)驱动。 */
   includeOffPeak?: boolean;
+  /** 任务分发的端口在场门:宿主注入 TaskDispatchPort 才注册(子会话/actor 不注入)。 */
+  includeDispatchTasks?: boolean;
   /**
    * 动态工作流灰度门。**只有显式 false
    * 才下架** DYNAMIC_WORKFLOW_TOOL_NAMES:缺席代表调用方不参与灰度(TUI、headless、
@@ -266,6 +272,9 @@ export function registerBuiltInTools(
     ) {
       continue;
     }
+    if (entry.metadata.name === "DispatchTasks" && options.includeDispatchTasks !== true) {
+      continue;
+    }
     if (
       options.includeDynamicWorkflow === false &&
       DYNAMIC_WORKFLOW_TOOL_NAMES.has(entry.metadata.name)

+ 3 - 0
apps/zcode-cli/packages/core/src/tool/types.ts

@@ -23,6 +23,7 @@ import type {
   ModelMessageContent,
   ModelToolSideEffectScope,
   OffPeakPort,
+  TaskDispatchPort,
   TopicResourcePort,
   PdfDocumentPort,
   PermissionBrokerReasonSource,
@@ -172,6 +173,8 @@ export interface ToolExecutionContext {
   artifactStore?: ToolArtifactStorePort;
   automationPort?: AutomationPort;
   offPeakPort?: OffPeakPort;
+  /** 项目级任务分发端口;仅主会话由宿主注入(子会话/actor 不注入即工具不可见)。 */
+  taskDispatchPort?: TaskDispatchPort;
   topicResourcePort?: TopicResourcePort;
   sessionStore?: SessionStorePort;
   sessionModePort?: SessionModePort;