@yefengr/steward 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/extension.js CHANGED
@@ -3,11 +3,14 @@ import { z } from "zod";
3
3
  import { Type } from "typebox";
4
4
  import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
- import { resolve } from "node:path";
7
- import { spawn } from "node:child_process";
6
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
+ import { execFile, spawn } from "node:child_process";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import * as http from "node:http";
10
10
  import * as https from "node:https";
11
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
12
+ import { open, realpath } from "node:fs/promises";
13
+ import { promisify } from "node:util";
11
14
  // packages/contract/dist/core.js
12
15
  var taskStatusSchema = z.enum([
13
16
  "unscheduled",
@@ -28,7 +31,11 @@ var errorCodeSchema = z.enum([
28
31
  "machine_required",
29
32
  "attempt_ended",
30
33
  "rate_limited",
31
- "internal_error"
34
+ "internal_error",
35
+ "session_machine_offline",
36
+ "session_unsupported",
37
+ "session_record_missing",
38
+ "session_slots_full"
32
39
  ]);
33
40
  var errorResponseSchema = z.strictObject({ error: z.strictObject({
34
41
  code: errorCodeSchema,
@@ -44,10 +51,80 @@ var tmuxSessionSchema = z.string().startsWith("steward-").refine((value) => uuid
44
51
  z.strictObject({});
45
52
  var okResponseSchema = z.strictObject({ ok: z.literal(true) });
46
53
  var requestIdSchema = z.strictObject({ requestId: uuidSchema });
54
+ // packages/contract/dist/session-control.js
55
+ var absoluteWorkspacePathSchema = z.string().max(4096).regex(/^\/[^\0]*$/u);
56
+ var piSessionIdSchema = z.string().max(256).regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/u);
57
+ var piSessionLocatorSchema = z.strictObject({
58
+ path: absoluteWorkspacePathSchema,
59
+ sessionId: piSessionIdSchema,
60
+ sessionFile: absoluteWorkspacePathSchema
61
+ });
62
+ requestIdSchema.extend({ locator: piSessionLocatorSchema });
63
+ var sessionOperationModeSchema = z.enum(["restart", "restore"]);
64
+ var sessionOperationFailureSchema = z.enum([
65
+ "session_workspace_unavailable",
66
+ "session_record_missing",
67
+ "session_config_unsupported",
68
+ "session_stop_failed",
69
+ "session_launch_failed",
70
+ "session_timeout"
71
+ ]);
72
+ var operation = z.strictObject({
73
+ id: uuidSchema,
74
+ attemptId: uuidSchema,
75
+ mode: sessionOperationModeSchema
76
+ });
77
+ var webSessionOperationSchema = operation.extend({
78
+ status: z.enum([
79
+ "pending",
80
+ "succeeded",
81
+ "failed"
82
+ ]),
83
+ failure: sessionOperationFailureSchema.nullable(),
84
+ needsExitVerification: z.literal(true).optional()
85
+ });
86
+ requestIdSchema.extend({
87
+ attemptId: uuidSchema,
88
+ mode: sessionOperationModeSchema
89
+ });
90
+ var permission = operation.extend({
91
+ locator: piSessionLocatorSchema,
92
+ validForMs: z.int().positive()
93
+ });
94
+ var launcherSessionDirectiveSchema = z.discriminatedUnion("step", [
95
+ permission.extend({
96
+ step: z.literal("stop"),
97
+ sourceEnded: z.boolean()
98
+ }),
99
+ permission.extend({
100
+ step: z.literal("launch"),
101
+ replacementId: uuidSchema
102
+ }),
103
+ operation.extend({
104
+ step: z.literal("cleanup"),
105
+ replacementId: uuidSchema
106
+ })
107
+ ]);
108
+ z.discriminatedUnion("result", [requestIdSchema.extend({
109
+ result: z.literal("stopped"),
110
+ step: z.literal("stop")
111
+ }), requestIdSchema.extend({
112
+ result: z.literal("failed"),
113
+ step: z.enum([
114
+ "stop",
115
+ "launch",
116
+ "cleanup"
117
+ ]),
118
+ failure: sessionOperationFailureSchema
119
+ })]);
47
120
  // packages/contract/dist/models.js
48
121
  var titleSchema = z.string().trim().min(1).max(500);
49
122
  var taskTypeSchema = z.enum(["discussion", "implementation"]);
50
- var attemptKindSchema = z.enum(["new", "rework"]);
123
+ var attemptKindSchema = z.enum([
124
+ "new",
125
+ "rework",
126
+ "resume"
127
+ ]);
51
128
  var attemptResultSchema = z.enum([
52
129
  "delivered",
53
130
  "interrupted",
@@ -98,7 +175,7 @@ var attemptSchema = z.strictObject({
98
175
  machineName: z.string(),
99
176
  agent: agentSchema,
100
177
  kind: attemptKindSchema,
101
- sessionId: tmuxSessionSchema,
178
+ sessionId: piSessionIdSchema,
102
179
  tmuxSession: tmuxSessionSchema.nullable(),
103
180
  claimedAt: timestampSchema,
104
181
  startedAt: timestampSchema.nullable(),
@@ -181,7 +258,8 @@ var webTaskDetailResponseSchema = z.strictObject({
181
258
  questions: z.array(questionSchema),
182
259
  deliveries: z.array(deliverySchema),
183
260
  attempts: z.array(attemptSchema),
184
- events: z.array(taskEventSchema)
261
+ events: z.array(taskEventSchema),
262
+ sessionOperation: webSessionOperationSchema.optional()
185
263
  });
186
264
  taskContentSchema.partial().required({ title: true }).extend({ projectId: projectIdSchema });
187
265
  taskContentSchema.omit({ type: true }).partial().extend({ version: z.int().positive() }).refine((input) => Object.keys(input).some((key) => key !== "version"));
@@ -213,6 +291,7 @@ z.strictObject({ machines: z.array(webMachineSchema) });
213
291
  var launcherHeartbeatRequestSchema = requestIdSchema.extend({
214
292
  launcherVersion: z.string().trim().min(1).max(128),
215
293
  slots: slotsSchema,
294
+ sessionControl: z.literal(true).optional(),
216
295
  projects: z.array(z.strictObject({
217
296
  id: projectIdSchema,
218
297
  name: z.string().trim().min(1).max(500),
@@ -224,24 +303,28 @@ var launcherHeartbeatRequestSchema = requestIdSchema.extend({
224
303
  running: z.boolean()
225
304
  })).max(1e3).refine((items) => new Set(items.map(({ id }) => id)).size === items.length)
226
305
  });
227
- z.strictObject({ directives: z.array(z.strictObject({
228
- attemptId: uuidSchema,
229
- tmuxSession: tmuxSessionSchema,
230
- action: z.enum([
231
- "continue",
232
- "cancel",
233
- "unknown"
234
- ])
235
- })) });
306
+ z.strictObject({
307
+ directives: z.array(z.strictObject({
308
+ attemptId: uuidSchema,
309
+ tmuxSession: tmuxSessionSchema,
310
+ action: z.enum([
311
+ "continue",
312
+ "cancel",
313
+ "unknown"
314
+ ])
315
+ })),
316
+ sessionOperations: z.array(launcherSessionDirectiveSchema).optional()
317
+ });
236
318
  var claimedAttemptSchema = z.strictObject({
237
319
  id: uuidSchema,
238
320
  taskId: uuidSchema,
239
321
  projectId: projectIdSchema,
240
322
  agent: z.literal("pi"),
241
- sessionId: tmuxSessionSchema,
323
+ sessionId: piSessionIdSchema,
242
324
  restoreSession: z.boolean(),
325
+ sessionLocator: piSessionLocatorSchema.optional(),
243
326
  displayName: z.string().min(1).max(80),
244
- kind: attemptKindSchema
327
+ kind: z.enum(["new", "rework"])
245
328
  });
246
329
  z.strictObject({ attempt: claimedAttemptSchema.nullable() });
247
330
  requestIdSchema.extend({
@@ -253,6 +336,16 @@ requestIdSchema.extend({
253
336
  endedAt: timestampSchema
254
337
  });
255
338
  // packages/contract/dist/agent.js
339
+ var gitBranch = z.string().min(1).max(1024).regex(/^[^\0\r\n]+$/u);
340
+ var attemptWorkspaceSchema = piSessionLocatorSchema.extend({
341
+ gitKind: z.enum([
342
+ "non_git",
343
+ "primary",
344
+ "linked"
345
+ ]),
346
+ gitBranch: gitBranch.nullable()
347
+ }).refine(({ gitKind, gitBranch }) => gitKind !== "non_git" || gitBranch === null);
348
+ var agentWorkspaceRequestSchema = requestIdSchema.extend({ workspace: attemptWorkspaceSchema });
256
349
  var agentContextResponseSchema = z.strictObject({
257
350
  task: taskContentSchema.pick({
258
351
  title: true,
@@ -270,7 +363,13 @@ var agentContextResponseSchema = z.strictObject({
270
363
  }),
271
364
  workspace: z.strictObject({
272
365
  path: z.string(),
273
- requirements: z.array(nonEmptyTextSchema)
366
+ requirements: z.array(nonEmptyTextSchema),
367
+ previous: z.strictObject({
368
+ attemptId: uuidSchema,
369
+ machineId: uuidSchema,
370
+ sameMachine: z.boolean(),
371
+ workspace: attemptWorkspaceSchema.nullable()
372
+ }).nullable().optional()
274
373
  }),
275
374
  decisions: z.array(decisionSchema.extend({ confirmedByUser: z.literal(true) })),
276
375
  deliveries: z.array(deliverySchema),
@@ -822,6 +921,215 @@ function retryableWrites({ cancelledMayHaveSaved = false } = {}) {
822
921
  return inFlight;
823
922
  };
824
923
  }
924
+ // packages/pi-extension/dist/workspace.js
925
+ var run = promisify(execFile);
926
+ var GIT_TIMEOUT_MS = 2e3;
927
+ var HEADER_LIMIT = 32768;
928
+ async function git(cwd, ...args) {
929
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")));
930
+ return (await run("git", [
931
+ "-C",
932
+ cwd,
933
+ ...args
934
+ ], {
935
+ env: {
936
+ ...env,
937
+ LC_ALL: "C"
938
+ },
939
+ timeout: GIT_TIMEOUT_MS
940
+ })).stdout;
941
+ }
942
+ async function gitLayout(cwd) {
943
+ let output;
944
+ try {
945
+ output = await git(cwd, "rev-parse", "--is-inside-work-tree", "--absolute-git-dir", "--path-format=absolute", "--git-common-dir");
946
+ } catch (error) {
947
+ const { code, stderr } = error;
948
+ if (code === 128 && stderr?.startsWith("fatal: not a git repository (or any of the parent directories):")) return {
949
+ kind: "non_git",
950
+ branch: null
951
+ };
952
+ throw error;
953
+ }
954
+ const [inside, gitDir, commonDir, end, ...extra] = output.split("\n");
955
+ if (inside !== "true" || !gitDir || !commonDir || end !== "" || extra.length || !isAbsolute(gitDir) || !isAbsolute(commonDir)) throw new Error("git_layout");
956
+ const [local, common] = await Promise.all([realpath(gitDir), realpath(commonDir)]);
957
+ let branch;
958
+ try {
959
+ const ref = (await git(cwd, "symbolic-ref", "--quiet", "HEAD")).trimEnd();
960
+ if (!ref.startsWith("refs/heads/")) throw new Error("git_branch");
961
+ branch = ref.slice(11);
962
+ } catch (error) {
963
+ if (error.code !== 1) throw error;
964
+ branch = null;
965
+ }
966
+ return {
967
+ kind: common === local ? "primary" : "linked",
968
+ branch,
969
+ common
970
+ };
971
+ }
972
+ function sameRepository(registered, current) {
973
+ if (registered.kind === "non_git" || current.kind === "non_git") return registered.kind === current.kind;
974
+ return registered.common === current.common;
975
+ }
976
+ async function readHeader(path) {
977
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
978
+ try {
979
+ if (!(await file.stat()).isFile()) throw new Error("session_file");
980
+ const buf = Buffer.alloc(HEADER_LIMIT);
981
+ const { bytesRead } = await file.read(buf, 0, buf.length, 0);
982
+ const end = buf.subarray(0, bytesRead).indexOf(10);
983
+ if (end < 0) throw new Error("session_header");
984
+ const header = JSON.parse(buf.toString("utf8", 0, end));
985
+ if (header.type !== "session" || !header.id || !header.cwd || !isAbsolute(header.cwd)) throw new Error("session_header");
986
+ return {
987
+ id: header.id,
988
+ path: await realpath(header.cwd)
989
+ };
990
+ } finally {
991
+ await file.close();
992
+ }
993
+ }
994
+ async function currentSessionLocator(ctx, requireLoaded) {
995
+ const session = ctx.sessionManager.getSessionFile();
996
+ const sessionCwd = ctx.sessionManager.getCwd();
997
+ if (!session || !isAbsolute(session) || !isAbsolute(sessionCwd) || !isAbsolute(ctx.cwd)) return void 0;
998
+ const [path, cwd] = await Promise.all([realpath(ctx.cwd), realpath(sessionCwd)]);
999
+ if (path !== cwd) return void 0;
1000
+ const sessionId = ctx.sessionManager.getSessionId();
1001
+ const sessionFile = await realpath(session).catch(async (error) => {
1002
+ if (requireLoaded || error.code !== "ENOENT") throw error;
1003
+ const parent = await realpath(dirname(session)).catch(() => dirname(session));
1004
+ return join(parent, basename(session));
1005
+ });
1006
+ if (requireLoaded) {
1007
+ const header = await readHeader(sessionFile);
1008
+ if (header.id !== sessionId || header.path !== path || !ctx.sessionManager.getEntries().some((entry) => entry.type === "message" && (entry.message.role === "user" || entry.message.role === "assistant"))) return void 0;
1009
+ }
1010
+ return piSessionLocatorSchema.parse({
1011
+ path,
1012
+ sessionId,
1013
+ sessionFile
1014
+ });
1015
+ }
1016
+ async function currentWorkspace(ctx, registeredPath) {
1017
+ try {
1018
+ const [path, registered] = await Promise.all([realpath(ctx.cwd), realpath(registeredPath)]);
1019
+ const [layout, registeredLayout] = await Promise.all([gitLayout(path), gitLayout(registered)]);
1020
+ if (!sameRepository(registeredLayout, layout) || layout.kind === "non_git" && path !== registered) throw new Error("workspace");
1021
+ const sessionId = ctx.sessionManager.getSessionId();
1022
+ const session = ctx.sessionManager.getSessionFile();
1023
+ if (!session || !isAbsolute(session) || await realpath(ctx.sessionManager.getCwd()) !== path) throw new Error("session");
1024
+ const sessionFile = await realpath(session);
1025
+ const header = await readHeader(sessionFile);
1026
+ if (header.id !== sessionId || header.path !== path) throw new Error("session");
1027
+ return attemptWorkspaceSchema.parse({
1028
+ path,
1029
+ gitKind: layout.kind,
1030
+ gitBranch: layout.branch,
1031
+ sessionId,
1032
+ sessionFile
1033
+ });
1034
+ } catch {
1035
+ throw new AgentError("workspace_unavailable");
1036
+ }
1037
+ }
1038
+ async function checkReworkWorkspace(ctx, data) {
1039
+ if (data.task.type !== "implementation" || data.attempt.kind === "resume") return void 0;
1040
+ const previous = data.workspace.previous;
1041
+ if (previous === void 0 && data.attempt.kind !== "rework" && data.deliveries.at(-1)?.review !== "rework") return void 0;
1042
+ if (!previous) return "not_recorded";
1043
+ if (!previous.sameMachine) return "different_machine";
1044
+ const saved = previous.workspace;
1045
+ if (!saved) return "not_recorded";
1046
+ try {
1047
+ const [path, registered, sessionFile] = await Promise.all([
1048
+ realpath(saved.path),
1049
+ realpath(data.workspace.path),
1050
+ realpath(saved.sessionFile)
1051
+ ]);
1052
+ if (path !== saved.path || sessionFile !== saved.sessionFile) return "mismatch";
1053
+ const [layout, registeredLayout, header] = await Promise.all([
1054
+ gitLayout(path),
1055
+ gitLayout(registered),
1056
+ readHeader(sessionFile)
1057
+ ]);
1058
+ if (!sameRepository(registeredLayout, layout) || layout.kind === "non_git" && path !== registered || layout.kind !== saved.gitKind || layout.branch !== saved.gitBranch || header.id !== saved.sessionId || header.path !== path) return "mismatch";
1059
+ if (layout.kind !== "non_git" && layout.branch === null) return "unverifiable";
1060
+ if (await realpath(ctx.cwd) !== path) return "switch_required";
1061
+ const session = ctx.sessionManager.getSessionFile();
1062
+ if (session && ctx.sessionManager.getSessionId() === saved.sessionId && await realpath(session) === sessionFile && await realpath(ctx.sessionManager.getCwd()) === path) return "confirmed";
1063
+ return "switch_required";
1064
+ } catch {
1065
+ return "unavailable";
1066
+ }
1067
+ }
1068
+ // packages/pi-extension/dist/session-report.js
1069
+ var RETRY_MS = 3e3;
1070
+ var MAX_TRIES = 5;
1071
+ var TERMINAL = /* @__PURE__ */ new Set([
1072
+ "attempt_ended",
1073
+ "not_found",
1074
+ "invalid_request",
1075
+ "invalid_response",
1076
+ "forbidden"
1077
+ ]);
1078
+ function registerSessionReport(pi, request, resumed) {
1079
+ let active;
1080
+ let queue = Promise.resolve();
1081
+ function serial(run) {
1082
+ const result = queue.then(run);
1083
+ queue = result.catch(() => void 0);
1084
+ return result;
1085
+ }
1086
+ pi.on("session_start", (_event, ctx) => {
1087
+ active?.abort();
1088
+ const controller = new AbortController();
1089
+ active = controller;
1090
+ const { signal } = controller;
1091
+ async function send() {
1092
+ const locator = await currentSessionLocator(ctx, resumed);
1093
+ if (!locator || signal.aborted) return;
1094
+ const body = {
1095
+ requestId: randomUUID(),
1096
+ locator
1097
+ };
1098
+ for (let tries = 0; tries < MAX_TRIES && !signal.aborted; tries++) try {
1099
+ await request("POST", "session", okResponseSchema, body, signal);
1100
+ return;
1101
+ } catch (error) {
1102
+ if (TERMINAL.has(error.code) || tries === 4) return;
1103
+ await setTimeout$1(RETRY_MS, void 0, {
1104
+ signal,
1105
+ ref: false
1106
+ });
1107
+ }
1108
+ }
1109
+ serial(send).catch(() => void 0);
1110
+ });
1111
+ pi.on("session_shutdown", () => active?.abort());
1112
+ return { workspace(run) {
1113
+ return serial(run);
1114
+ } };
1115
+ }
1116
+ // packages/pi-extension/dist/task-session.js
1117
+ var SOURCE_ENTRY = "steward-launch-source";
1118
+ var SOURCE = "steward-launcher";
1119
+ function registerTaskSession(pi, active) {
1120
+ const hasSource = (entries) => entries.some((entry) => entry.type === "custom" && entry.customType === SOURCE_ENTRY && entry.data === SOURCE);
1121
+ if (active) pi.on("session_start", (_event, ctx) => {
1122
+ if (!hasSource(ctx.sessionManager.getEntries())) pi.appendEntry(SOURCE_ENTRY, SOURCE);
1123
+ });
1124
+ pi.on("before_agent_start", (event, ctx) => {
1125
+ const rules = event.systemPromptOptions.promptGuidelines;
1126
+ if (!active) {
1127
+ if (hasSource(ctx.sessionManager.getEntries())) rules.push("会话历史来源:此 Pi 会话或其来源会话由 Steward 任务台后台启动。当前未绑定 Steward 执行尝试;历史任务指令不授予回报、交付或收尾权限。");
1128
+ return;
1129
+ }
1130
+ rules.push("会话来源:此 Pi 执行由 Steward 任务台后台启动。先调用 steward_task,确认本次任务类型、授权、项目规则和工作现场,再行动。接回仍在运行的会话或切换工作树后,任务规则仍有效。", "只读任务不创建工作树。Git 实现任务默认使用独立工作树和分支,保留登记目录中的既有改动。根据当前可用的 Pi 能力完成创建、迁移或切换,不预设工具。没有可用工作树能力时,说明限制并取得用户明确确认后才可在主分支实施。", "返修首次写入前,依据 steward_task 核对上次实现的机器、路径、Git 分支和 Pi 会话。上次使用独立工作树时,使用 Pi 已有能力复用同一个工作树和对应会话,不创建替代工作树。核对结果为 switch_required 时,先切换,再调用 steward_task,只有 confirmed 才表示原现场已核对。其他返修结果表示现场缺失、不匹配或无法确认;若出现这些结果,或无法切换,暂停修改并用 steward_ask 请用户确认。", "实现所用目录和分支确认后、首次写入前,调用 steward_record_workspace 保存当前实际目录、Git 分支和 Pi 会话。工作树创建或迁移成功后,在目标会话调用,不在待离开的会话调用。现场变更后或交付前再确认记录,记录失败不得声称已保存。", "实现任务按授权执行,在关键节点用 steward_progress 回报;验证完毕后用 steward_deliver 交付,确认保存后用 steward_finish 收尾。");
1131
+ });
1132
+ }
825
1133
  // packages/pi-extension/dist/index.js
826
1134
  var text = () => Type.String({ maxLength: 1e5 });
827
1135
  var lines = () => Type.Array(text());
@@ -851,7 +1159,7 @@ async function report(run) {
851
1159
  return result(JSON.stringify(data), data);
852
1160
  } catch (error) {
853
1161
  const code = error instanceof AgentError ? error.code : "request_failed";
854
- return result(`Steward 请求失败(${code})。${code === "cancelled" ? "请求已取消。" : code === "helper_unavailable" ? "请重新安装 Steward。" : code === "proxy_unsupported" ? "显式代理需要使用 Node 24.20.0 或更高版本运行 Pi。" : code === "invalid_request" ? "请检查工具参数后重试。" : code === "attempt_ended" ? "本次尝试已结束,请检查平台状态。" : code === "conflict" ? "请核对平台状态。交付请求重试时请保留原参数。" : code === "pending_writes_full" ? "待确认的请求已达上限,请先使用原参数重试已有请求。" : code === "invalid_config" ? "请检查本机配置及 0600 文件权限后重试。" : "请稍后使用相同参数重试。"}`, { code });
1162
+ return result(`Steward 请求失败(${code})。${code === "cancelled" ? "请求已取消。" : code === "helper_unavailable" ? "请重新安装 Steward。" : code === "proxy_unsupported" ? "显式代理需要使用 Node 24.20.0 或更高版本运行 Pi。" : code === "invalid_request" ? "请检查工具参数后重试。" : code === "task_context_required" ? "请先调用 steward_task 确认任务类型;只为实现任务记录工作现场。" : code === "workspace_unavailable" ? "无法核对当前目录、Git 或持久化 Pi 会话;请核对本机现场,必要时向用户确认。" : code === "attempt_ended" ? "本次尝试已结束,请检查平台状态。" : code === "conflict" ? "请核对平台状态。交付请求重试时请保留原参数。" : code === "pending_writes_full" ? "待确认的请求已达上限,请先使用原参数重试已有请求。" : code === "invalid_config" ? "请检查本机配置及 0600 文件权限后重试。" : "请稍后使用相同参数重试。"}`, { code });
855
1163
  }
856
1164
  }
857
1165
  var editableTask = {
@@ -944,21 +1252,51 @@ function deliveryId(attemptId) {
944
1252
  function registerSteward(pi, options = { env: process.env }) {
945
1253
  registerTaskManagement(pi, options);
946
1254
  const attempt = uuidSchema.safeParse(options.env.STEWARD_ATTEMPT_ID);
1255
+ registerTaskSession(pi, attempt.success);
947
1256
  if (!attempt.success) return;
948
1257
  const request = agentClient(attempt.data, options);
1258
+ const sessionReport = registerSessionReport(pi, request, options.env.STEWARD_RESUME === "1");
949
1259
  const control = registerAttemptControl(pi, attempt.data, request);
950
1260
  const write = retryableWrites();
951
1261
  const requestId = deliveryId(attempt.data);
952
1262
  let delivered = false;
1263
+ let taskContext;
953
1264
  pi.registerTool({
954
1265
  name: "steward_task",
955
1266
  label: "读取 Steward 任务",
956
- description: "读取本次任务的目标、验收要求、决定、交付与返修反馈。",
1267
+ description: "读取本次任务的目标、验收要求、决定、交付、返修反馈及工作现场核对结果。",
957
1268
  parameters: Type.Object({}),
958
- execute: (_id, _args, signal) => report(async () => {
1269
+ execute: (_id, _args, signal, _update, ctx) => report(async () => {
1270
+ taskContext = void 0;
959
1271
  const data = await request("GET", "context", agentContextResponseSchema, void 0, signal);
960
1272
  control.noteTaskType(data.task.type);
961
- return data;
1273
+ taskContext = data;
1274
+ const reworkWorkspace = await checkReworkWorkspace(ctx, data);
1275
+ return reworkWorkspace ? {
1276
+ ...data,
1277
+ reworkWorkspace
1278
+ } : data;
1279
+ })
1280
+ });
1281
+ pi.registerTool({
1282
+ name: "steward_record_workspace",
1283
+ label: "记录 Steward 工作现场",
1284
+ description: "实现任务确认工作空间后,保存当前 Pi 会话的实际工作目录、Git 分支和会话定位。迁移或切换后在目标会话调用。",
1285
+ parameters: Type.Object({}),
1286
+ execute: (_id, _args, signal, _update, ctx) => report(async () => {
1287
+ if (taskContext?.task.type !== "implementation") throw new AgentError("task_context_required");
1288
+ const registeredPath = taskContext.workspace.path;
1289
+ return sessionReport.workspace(async () => {
1290
+ const workspace = await currentWorkspace(ctx, registeredPath);
1291
+ await write("POST", "workspace", workspace, (requestId) => request("POST", "workspace", okResponseSchema, validatedBody(agentWorkspaceRequestSchema, {
1292
+ workspace,
1293
+ requestId
1294
+ }), signal));
1295
+ return {
1296
+ ok: true,
1297
+ workspace
1298
+ };
1299
+ });
962
1300
  })
963
1301
  });
964
1302
  pi.registerTool({