瀏覽代碼

feat(dispatch): S2——tasks/dispatch 协议方法 + Host 批量 createSession 实现

- shared:tasks/dispatch 协议方法 + params/result schema(逐项结果判别,失败≤400 字符)
- services:zcodeAgentService 新增 tasks/dispatch handler——批量 v4 createSession,
  firstInput 使创建即首发(全并发语义天然满足),统一 permissionScope=session,
  单项失败隔离继续其余
- bootstrap:createProtocolTaskDispatchPort(requestClient 走协议)+ server-operations
  主会话装配 + create-app/types 选项贯通

验证:core build / bootstrap typecheck / root typecheck(含 shared+services)全部通过;
root lint 0 error;bootstrap lint 20 error 为存量大文件(server-operations 等),
本次触碰文件 0 error
wubinggen 1 月之前
父節點
當前提交
661791bd

+ 1 - 0
apps/zcode-cli/packages/bootstrap/src/app/create-app.ts

@@ -874,6 +874,7 @@ export async function createZCodeApp(options: ZCodeAppOptions): Promise<ZCodeApp
       modelCatalogPort,
       automationPort: options.automationPort,
       offPeakPort: options.offPeakPort,
+      taskDispatchPort: options.taskDispatchPort,
       topicResourcePort: options.topicResourcePort,
       appVersion,
       traceContext,

+ 2 - 0
apps/zcode-cli/packages/bootstrap/src/app/types.ts

@@ -37,6 +37,7 @@ import type {
   ModelToolCall,
   ModelUsage,
   OffPeakPort,
+  TaskDispatchPort,
   TopicResourcePort,
   PdfDocumentPort,
   PermissionBrokerPort,
@@ -203,6 +204,7 @@ export interface ZCodeAppOptions {
   onWorkflowEvent?: (event: WorkflowEvent) => void | Promise<void>;
   automationPort?: AutomationPort;
   offPeakPort?: OffPeakPort;
+  taskDispatchPort?: TaskDispatchPort;
   topicResourcePort?: TopicResourcePort;
   /** 首次真实用户执行或 cold-resume fallback 时解析一次,之后由 app 生命周期缓存。 */
   resolveInitialBashShellSelection?: () => Promise<ExecutionShellSelection | undefined>;

+ 4 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts

@@ -114,6 +114,7 @@ import { buildAppUsageSnapshot, resolveTzOffsetMs } from "./usage-stats-builder.
 import { createProtocolInteractionBroker } from "./interaction-broker.js";
 import { createProtocolAutomationPort } from "./automation-port.js";
 import { createProtocolOffPeakPort } from "./offpeak-port.js";
+import { createProtocolTaskDispatchPort } from "./task-dispatch-port.js";
 import { createProtocolTopicResourcePort } from "./topic-resource-port.js";
 import { createProtocolBrowserControlBroker } from "./browser-control-broker.js";
 import { mapComputerUseOperationEvent } from "./computer-use-operation-event.js";
@@ -3419,6 +3420,9 @@ async function createRecord(
     context.appRuntimePreferences.offPeakToolEnabled === true
       ? { offPeakPort: createProtocolOffPeakPort(context, () => ownSessionRecord) }
       : {}),
+    // 任务分发端口:无条件注入(主会话装配点;subagent 子会话不经过这里,
+    // runtime-tools 的 includeDispatchTasks 门再挡一层)。
+    taskDispatchPort: createProtocolTaskDispatchPort(context),
     resolveInitialBashShellSelection: startupPreferences.resolveInitialBashShellSelection,
     ...(startupPreferences.subagentRuntimeConfigEnabled &&
     !(workspace.workspaceIdentity && isRemoteWorkspaceIdentity(workspace.workspaceIdentity))

+ 50 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/task-dispatch-port.ts

@@ -0,0 +1,50 @@
+// ============================================================
+// Task Dispatch Protocol Port
+// ============================================================
+// 设计合同:docs/specs/workspace-task-dispatch.md。
+// 与 offpeak-port 的取舍:
+// - 无会话绑定守卫:每个分发任务都是新会话,不存在「同会话双任务」竞态。
+// - 无递归防护需求:宿主只给主会话注入端口(includeDispatchTasks 门 +
+//   taskType !== "subagent_child"),子任务会话里工具不可见。
+// - execute 以确认结果为准:统一确认窗批准后由调用链回填(工具入参只是建议值)。
+// - 失败分类不跨协议保真为枚举:单项失败是一行文本摘要(≤400),整批
+//   requestClient 异常直接抛错(配置/网络级问题由 handler 翻译)。
+
+import type { DispatchTaskResult, TaskDispatchPort } from "@zcode/contracts";
+import {
+  zcodeProtocolMethods,
+  zcodeTaskDispatchResultSchema,
+} from "@zcode/shared";
+import type { ZCodeProtocolAgentServerContext } from "./server-types.js";
+
+export function createProtocolTaskDispatchPort(
+  context: ZCodeProtocolAgentServerContext,
+): TaskDispatchPort {
+  return {
+    async dispatch(tasks, dispatchContext) {
+      const result = await context.requestClient(
+        zcodeProtocolMethods.taskDispatch,
+        {
+          tasks: tasks.map((task) => ({
+            id: task.id,
+            title: task.title,
+            prompt: task.prompt,
+            ...(task.dependsOn ? { dependsOn: task.dependsOn } : {}),
+          })),
+          execute: dispatchContext.execute,
+          ...(dispatchContext.sessionId ? { originSessionId: dispatchContext.sessionId } : {}),
+        },
+        zcodeTaskDispatchResultSchema,
+      );
+      return {
+        results: result.results.map((item) => ({
+          id: item.id,
+          title: item.title,
+          status: item.status,
+          ...(item.sessionId ? { sessionId: item.sessionId } : {}),
+          ...(item.failure ? { failure: item.failure } : {}),
+        })) satisfies DispatchTaskResult[],
+      };
+    },
+  };
+}

+ 86 - 0
packages/services/src/zcode-agent/zcodeAgentService.ts

@@ -3,6 +3,11 @@ import {
   allowRequestVerificationHeaders,
   requestVerificationInteractionAvailable,
 } from "@zcode/shared";
+import { z } from "zod";
+import {
+  assertV4CommandAckOk,
+  createHostCommandEnvelope,
+} from "./zcodeV4HostCommand.js";
 import { zcodeMcpUiSamplingResultSchema } from "@zcode/shared";
 import { MCP_APPS_SAMPLING_TRANSPORT_TIMEOUT_MS } from "@zcode/shared/mcp-apps";
 import {
@@ -98,6 +103,8 @@ import {
   zcodeAutomationListParamsSchema,
   zcodeAutomationUpdateParamsSchema,
   zcodeOffPeakCreateParamsSchema,
+  zcodeTaskDispatchParamsSchema,
+  zcodeTaskDispatchResultSchema,
   zcodeOffPeakListParamsSchema,
   OFF_PEAK_PROVIDER_IDS,
   zcodeComputerUseOperationEventSchema,
@@ -2971,6 +2978,85 @@ export function createZCodeAgentService(
           return;
         }
 
+        // 项目级任务分发(docs/specs/workspace-task-dispatch.md):批量 v4 createSession。
+        // firstInput 使"创建即首发"天然满足全并发执行——每个会话的 agent turn 在创建
+        // 完成后立即启动,创建循环本身只是快速的命令下发。单项失败隔离(spec §4)。
+        if (request.method === zcodeProtocolMethods.taskDispatch) {
+          const parsed = zcodeTaskDispatchParamsSchema.safeParse(request.params);
+          if (!parsed.success) {
+            void client.respondError(request.id, {
+              code: -32602,
+              message: "Invalid task dispatch params",
+              data: parsed.error.flatten(),
+            });
+            return;
+          }
+          void (async () => {
+            try {
+              const results: z.infer<typeof zcodeTaskDispatchResultSchema>["results"] = [];
+              for (const item of parsed.data.tasks) {
+                try {
+                  // 与 sendConversationCommandV4 同一条受控通道:getClient(含账号配置
+                  // 同步在 createSession 命令路径内完成)→ buildConversationCommandEnvelope
+                  // → V4 command。这里直调工厂内函数而非 service 方法(handler 在方法
+                  // 对象装配前注册,方法名不在作用域)。
+                  const commandClient = await getClient(workspace);
+                  const envelope = await buildConversationCommandEnvelope({
+                    workspacePath: workspace.workspacePath,
+                    ...(workspace.workspaceIdentity
+                      ? { workspaceIdentity: workspace.workspaceIdentity }
+                      : {}),
+                    envelope: createHostCommandEnvelope({
+                      type: "createSession",
+                      sessionId: null,
+                      payload: {
+                        workspaceId:
+                          workspace.workspaceIdentity?.trim() || workspace.workspacePath,
+                        // 统一权限确认的授权落点:整批共用 session 级权限范围。
+                        permissionScope: "session",
+                        ...(parsed.data.execute
+                          ? { firstInput: { text: item.prompt } }
+                          : {}),
+                      },
+                    }),
+                  });
+                  const ack = assertV4CommandAckOk(
+                    "createSession",
+                    await commandClient.request(V4_METHODS.command, envelope, commandAckSchema),
+                    `dispatch ${item.id}`,
+                  );
+                  const sessionId =
+                    ack.result?.type === "createSession" ? ack.result.sessionId : undefined;
+                  results.push({
+                    id: item.id,
+                    title: item.title,
+                    status: parsed.data.execute ? "started" : "created",
+                    ...(sessionId ? { sessionId } : {}),
+                  });
+                } catch (error) {
+                  // 失败隔离:单项失败带一行摘要继续其余(不带堆栈,对齐协议 schema 上限)。
+                  results.push({
+                    id: item.id,
+                    title: item.title,
+                    status: "failed",
+                    failure: (error instanceof Error ? error.message : String(error)).slice(
+                      0,
+                      400,
+                    ),
+                  });
+                }
+              }
+              await client.respond(request.id, { results });
+            } catch (error) {
+              await client.respondError(request.id, {
+                code: -32603,
+                message: error instanceof Error ? error.message : String(error),
+              });
+            }
+          })();
+          return;
+        }
+
         if (request.method === zcodeProtocolMethods.automationList) {
           const parsed = zcodeAutomationListParamsSchema.safeParse(request.params ?? {});
           if (!parsed.success) {

+ 41 - 0
packages/shared/src/zcode-protocol/index.ts

@@ -4071,6 +4071,45 @@ export const zcodeOffPeakListResultSchema = z
   .strict();
 export type ZCodeOffPeakListProtocolResult = z.infer<typeof zcodeOffPeakListResultSchema>;
 
+// ── 项目级任务分发(docs/specs/workspace-task-dispatch.md)──
+// 镜像 contracts 的 DispatchTaskItem/DispatchTaskResult;zod v3/v4 边界不 import contracts。
+export const zcodeTaskDispatchItemSchema = z
+  .object({
+    id: nonEmptyString.max(64),
+    title: nonEmptyString.max(120),
+    prompt: nonEmptyString,
+    dependsOn: z.array(nonEmptyString.max(64)).optional(),
+  })
+  .strict();
+export type ZCodeTaskDispatchItemProtocol = z.infer<typeof zcodeTaskDispatchItemSchema>;
+
+export const zcodeTaskDispatchParamsSchema = z
+  .object({
+    tasks: z.array(zcodeTaskDispatchItemSchema).min(1).max(50),
+    // 用户在统一确认窗的最终决定;CLI 端口从确认结果回填(工具入参只是模型建议值)。
+    execute: z.boolean(),
+    // 发起会话;host 用它解析 workspace 与模型选择继承(对称 offPeak/create 的 boundSessionId)。
+    originSessionId: nonEmptyString.optional(),
+  })
+  .strict();
+export type ZCodeTaskDispatchProtocolParams = z.infer<typeof zcodeTaskDispatchParamsSchema>;
+
+// 逐项结果(失败隔离:单项失败不阻塞其余,一行 failure 摘要不带堆栈)。
+export const zcodeTaskDispatchResultItemSchema = 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 const zcodeTaskDispatchResultSchema = z
+  .object({ results: z.array(zcodeTaskDispatchResultItemSchema).max(50) })
+  .strict();
+export type ZCodeTaskDispatchProtocolResult = z.infer<typeof zcodeTaskDispatchResultSchema>;
+
 export const zcodeProtocolMethods = {
   runtimeCapabilities: "runtime/capabilities",
   computerUseOperationEvent: "computer-use/operation-event",
@@ -4187,6 +4226,8 @@ export const zcodeProtocolMethods = {
   // Off-Peak 会话内创建:与 automation 兄弟并列的独立方法族。
   offPeakCreate: "offPeak/create",
   offPeakList: "offPeak/list",
+  // 项目级任务分发:主会话工具 → host 批量 createSession(v4 firstInput 即首发)。
+  taskDispatch: "tasks/dispatch",
   // @deprecated:host 消费已清零(zcodeAgentService 改走 v4/usage/stats)。
   // 仅剩 CLI server 的 wire 兼容 case;随旧词整体删除时一并移除。
   usageStats: "usage/stats",