@yefengr/steward 0.2.0 → 0.3.0

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,15 +303,18 @@ 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,
@@ -241,7 +323,7 @@ var claimedAttemptSchema = z.strictObject({
241
323
  sessionId: tmuxSessionSchema,
242
324
  restoreSession: z.boolean(),
243
325
  displayName: z.string().min(1).max(80),
244
- kind: attemptKindSchema
326
+ kind: z.enum(["new", "rework"])
245
327
  });
246
328
  z.strictObject({ attempt: claimedAttemptSchema.nullable() });
247
329
  requestIdSchema.extend({
@@ -253,6 +335,16 @@ requestIdSchema.extend({
253
335
  endedAt: timestampSchema
254
336
  });
255
337
  // packages/contract/dist/agent.js
338
+ var gitBranch = z.string().min(1).max(1024).regex(/^[^\0\r\n]+$/u);
339
+ var attemptWorkspaceSchema = piSessionLocatorSchema.extend({
340
+ gitKind: z.enum([
341
+ "non_git",
342
+ "primary",
343
+ "linked"
344
+ ]),
345
+ gitBranch: gitBranch.nullable()
346
+ }).refine(({ gitKind, gitBranch }) => gitKind !== "non_git" || gitBranch === null);
347
+ var agentWorkspaceRequestSchema = requestIdSchema.extend({ workspace: attemptWorkspaceSchema });
256
348
  var agentContextResponseSchema = z.strictObject({
257
349
  task: taskContentSchema.pick({
258
350
  title: true,
@@ -270,7 +362,13 @@ var agentContextResponseSchema = z.strictObject({
270
362
  }),
271
363
  workspace: z.strictObject({
272
364
  path: z.string(),
273
- requirements: z.array(nonEmptyTextSchema)
365
+ requirements: z.array(nonEmptyTextSchema),
366
+ previous: z.strictObject({
367
+ attemptId: uuidSchema,
368
+ machineId: uuidSchema,
369
+ sameMachine: z.boolean(),
370
+ workspace: attemptWorkspaceSchema.nullable()
371
+ }).nullable().optional()
274
372
  }),
275
373
  decisions: z.array(decisionSchema.extend({ confirmedByUser: z.literal(true) })),
276
374
  deliveries: z.array(deliverySchema),
@@ -822,6 +920,206 @@ function retryableWrites({ cancelledMayHaveSaved = false } = {}) {
822
920
  return inFlight;
823
921
  };
824
922
  }
923
+ // packages/pi-extension/dist/workspace.js
924
+ var run = promisify(execFile);
925
+ var GIT_TIMEOUT_MS = 2e3;
926
+ var HEADER_LIMIT = 32768;
927
+ async function git(cwd, ...args) {
928
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")));
929
+ return (await run("git", [
930
+ "-C",
931
+ cwd,
932
+ ...args
933
+ ], {
934
+ env: {
935
+ ...env,
936
+ LC_ALL: "C"
937
+ },
938
+ timeout: GIT_TIMEOUT_MS
939
+ })).stdout;
940
+ }
941
+ async function gitLayout(cwd) {
942
+ let output;
943
+ try {
944
+ output = await git(cwd, "rev-parse", "--is-inside-work-tree", "--absolute-git-dir", "--path-format=absolute", "--git-common-dir");
945
+ } catch (error) {
946
+ const { code, stderr } = error;
947
+ if (code === 128 && stderr?.startsWith("fatal: not a git repository (or any of the parent directories):")) return {
948
+ kind: "non_git",
949
+ branch: null
950
+ };
951
+ throw error;
952
+ }
953
+ const [inside, gitDir, commonDir, end, ...extra] = output.split("\n");
954
+ if (inside !== "true" || !gitDir || !commonDir || end !== "" || extra.length || !isAbsolute(gitDir) || !isAbsolute(commonDir)) throw new Error("git_layout");
955
+ const [local, common] = await Promise.all([realpath(gitDir), realpath(commonDir)]);
956
+ let branch;
957
+ try {
958
+ const ref = (await git(cwd, "symbolic-ref", "--quiet", "HEAD")).trimEnd();
959
+ if (!ref.startsWith("refs/heads/")) throw new Error("git_branch");
960
+ branch = ref.slice(11);
961
+ } catch (error) {
962
+ if (error.code !== 1) throw error;
963
+ branch = null;
964
+ }
965
+ return {
966
+ kind: common === local ? "primary" : "linked",
967
+ branch,
968
+ common
969
+ };
970
+ }
971
+ function sameRepository(registered, current) {
972
+ if (registered.kind === "non_git" || current.kind === "non_git") return registered.kind === current.kind;
973
+ return registered.common === current.common;
974
+ }
975
+ async function readHeader(path) {
976
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
977
+ try {
978
+ if (!(await file.stat()).isFile()) throw new Error("session_file");
979
+ const buf = Buffer.alloc(HEADER_LIMIT);
980
+ const { bytesRead } = await file.read(buf, 0, buf.length, 0);
981
+ const end = buf.subarray(0, bytesRead).indexOf(10);
982
+ if (end < 0) throw new Error("session_header");
983
+ const header = JSON.parse(buf.toString("utf8", 0, end));
984
+ if (header.type !== "session" || !header.id || !header.cwd || !isAbsolute(header.cwd)) throw new Error("session_header");
985
+ return {
986
+ id: header.id,
987
+ path: await realpath(header.cwd)
988
+ };
989
+ } finally {
990
+ await file.close();
991
+ }
992
+ }
993
+ async function currentSessionLocator(ctx, requireLoaded) {
994
+ const session = ctx.sessionManager.getSessionFile();
995
+ const sessionCwd = ctx.sessionManager.getCwd();
996
+ if (!session || !isAbsolute(session) || !isAbsolute(sessionCwd) || !isAbsolute(ctx.cwd)) return void 0;
997
+ const [path, cwd] = await Promise.all([realpath(ctx.cwd), realpath(sessionCwd)]);
998
+ if (path !== cwd) return void 0;
999
+ const sessionId = ctx.sessionManager.getSessionId();
1000
+ const sessionFile = await realpath(session).catch(async (error) => {
1001
+ if (requireLoaded || error.code !== "ENOENT") throw error;
1002
+ const parent = await realpath(dirname(session)).catch(() => dirname(session));
1003
+ return join(parent, basename(session));
1004
+ });
1005
+ if (requireLoaded) {
1006
+ const header = await readHeader(sessionFile);
1007
+ 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;
1008
+ }
1009
+ return piSessionLocatorSchema.parse({
1010
+ path,
1011
+ sessionId,
1012
+ sessionFile
1013
+ });
1014
+ }
1015
+ async function currentWorkspace(ctx, registeredPath) {
1016
+ try {
1017
+ const [path, registered] = await Promise.all([realpath(ctx.cwd), realpath(registeredPath)]);
1018
+ const [layout, registeredLayout] = await Promise.all([gitLayout(path), gitLayout(registered)]);
1019
+ if (!sameRepository(registeredLayout, layout) || layout.kind === "non_git" && path !== registered) throw new Error("workspace");
1020
+ const sessionId = ctx.sessionManager.getSessionId();
1021
+ const session = ctx.sessionManager.getSessionFile();
1022
+ if (!session || !isAbsolute(session) || await realpath(ctx.sessionManager.getCwd()) !== path) throw new Error("session");
1023
+ const sessionFile = await realpath(session);
1024
+ const header = await readHeader(sessionFile);
1025
+ if (header.id !== sessionId || header.path !== path) throw new Error("session");
1026
+ return attemptWorkspaceSchema.parse({
1027
+ path,
1028
+ gitKind: layout.kind,
1029
+ gitBranch: layout.branch,
1030
+ sessionId,
1031
+ sessionFile
1032
+ });
1033
+ } catch {
1034
+ throw new AgentError("workspace_unavailable");
1035
+ }
1036
+ }
1037
+ async function checkReworkWorkspace(ctx, data) {
1038
+ if (data.task.type !== "implementation" || data.attempt.kind === "resume") return void 0;
1039
+ const previous = data.workspace.previous;
1040
+ if (previous === void 0 && data.attempt.kind !== "rework" && data.deliveries.at(-1)?.review !== "rework") return void 0;
1041
+ if (!previous) return "not_recorded";
1042
+ if (!previous.sameMachine) return "different_machine";
1043
+ const saved = previous.workspace;
1044
+ if (!saved) return "not_recorded";
1045
+ try {
1046
+ const [path, registered, sessionFile] = await Promise.all([
1047
+ realpath(saved.path),
1048
+ realpath(data.workspace.path),
1049
+ realpath(saved.sessionFile)
1050
+ ]);
1051
+ if (path !== saved.path || sessionFile !== saved.sessionFile) return "mismatch";
1052
+ const [layout, registeredLayout, header] = await Promise.all([
1053
+ gitLayout(path),
1054
+ gitLayout(registered),
1055
+ readHeader(sessionFile)
1056
+ ]);
1057
+ 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";
1058
+ if (layout.kind !== "non_git" && layout.branch === null) return "unverifiable";
1059
+ if (await realpath(ctx.cwd) !== path) return "switch_required";
1060
+ const session = ctx.sessionManager.getSessionFile();
1061
+ if (session && ctx.sessionManager.getSessionId() === saved.sessionId && await realpath(session) === sessionFile && await realpath(ctx.sessionManager.getCwd()) === path) return "confirmed";
1062
+ return "switch_required";
1063
+ } catch {
1064
+ return "unavailable";
1065
+ }
1066
+ }
1067
+ // packages/pi-extension/dist/session-report.js
1068
+ var RETRY_MS = 3e3;
1069
+ var MAX_TRIES = 5;
1070
+ var TERMINAL = /* @__PURE__ */ new Set([
1071
+ "attempt_ended",
1072
+ "not_found",
1073
+ "invalid_request",
1074
+ "invalid_response",
1075
+ "forbidden"
1076
+ ]);
1077
+ function registerSessionReport(pi, request, resumed) {
1078
+ let active;
1079
+ pi.on("session_start", (_event, ctx) => {
1080
+ active?.abort();
1081
+ const controller = new AbortController();
1082
+ active = controller;
1083
+ const { signal } = controller;
1084
+ async function send() {
1085
+ const locator = await currentSessionLocator(ctx, resumed);
1086
+ if (!locator) return;
1087
+ const body = {
1088
+ requestId: randomUUID(),
1089
+ locator
1090
+ };
1091
+ for (let tries = 0; tries < MAX_TRIES && !signal.aborted; tries++) try {
1092
+ await request("POST", "session", okResponseSchema, body, signal);
1093
+ return;
1094
+ } catch (error) {
1095
+ if (TERMINAL.has(error.code) || tries === 4) return;
1096
+ await setTimeout$1(RETRY_MS, void 0, {
1097
+ signal,
1098
+ ref: false
1099
+ });
1100
+ }
1101
+ }
1102
+ send().catch(() => void 0);
1103
+ });
1104
+ pi.on("session_shutdown", () => active?.abort());
1105
+ }
1106
+ // packages/pi-extension/dist/task-session.js
1107
+ var SOURCE_ENTRY = "steward-launch-source";
1108
+ var SOURCE = "steward-launcher";
1109
+ function registerTaskSession(pi, active) {
1110
+ const hasSource = (entries) => entries.some((entry) => entry.type === "custom" && entry.customType === SOURCE_ENTRY && entry.data === SOURCE);
1111
+ if (active) pi.on("session_start", (_event, ctx) => {
1112
+ if (!hasSource(ctx.sessionManager.getEntries())) pi.appendEntry(SOURCE_ENTRY, SOURCE);
1113
+ });
1114
+ pi.on("before_agent_start", (event, ctx) => {
1115
+ const rules = event.systemPromptOptions.promptGuidelines;
1116
+ if (!active) {
1117
+ if (hasSource(ctx.sessionManager.getEntries())) rules.push("会话历史来源:此 Pi 会话或其来源会话由 Steward 任务台后台启动。当前未绑定 Steward 执行尝试;历史任务指令不授予回报、交付或收尾权限。");
1118
+ return;
1119
+ }
1120
+ 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 收尾。");
1121
+ });
1122
+ }
825
1123
  // packages/pi-extension/dist/index.js
826
1124
  var text = () => Type.String({ maxLength: 1e5 });
827
1125
  var lines = () => Type.Array(text());
@@ -851,7 +1149,7 @@ async function report(run) {
851
1149
  return result(JSON.stringify(data), data);
852
1150
  } catch (error) {
853
1151
  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 });
1152
+ 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
1153
  }
856
1154
  }
857
1155
  var editableTask = {
@@ -944,21 +1242,48 @@ function deliveryId(attemptId) {
944
1242
  function registerSteward(pi, options = { env: process.env }) {
945
1243
  registerTaskManagement(pi, options);
946
1244
  const attempt = uuidSchema.safeParse(options.env.STEWARD_ATTEMPT_ID);
1245
+ registerTaskSession(pi, attempt.success);
947
1246
  if (!attempt.success) return;
948
1247
  const request = agentClient(attempt.data, options);
1248
+ registerSessionReport(pi, request, options.env.STEWARD_RESUME === "1");
949
1249
  const control = registerAttemptControl(pi, attempt.data, request);
950
1250
  const write = retryableWrites();
951
1251
  const requestId = deliveryId(attempt.data);
952
1252
  let delivered = false;
1253
+ let taskContext;
953
1254
  pi.registerTool({
954
1255
  name: "steward_task",
955
1256
  label: "读取 Steward 任务",
956
- description: "读取本次任务的目标、验收要求、决定、交付与返修反馈。",
1257
+ description: "读取本次任务的目标、验收要求、决定、交付、返修反馈及工作现场核对结果。",
957
1258
  parameters: Type.Object({}),
958
- execute: (_id, _args, signal) => report(async () => {
1259
+ execute: (_id, _args, signal, _update, ctx) => report(async () => {
1260
+ taskContext = void 0;
959
1261
  const data = await request("GET", "context", agentContextResponseSchema, void 0, signal);
960
1262
  control.noteTaskType(data.task.type);
961
- return data;
1263
+ taskContext = data;
1264
+ const reworkWorkspace = await checkReworkWorkspace(ctx, data);
1265
+ return reworkWorkspace ? {
1266
+ ...data,
1267
+ reworkWorkspace
1268
+ } : data;
1269
+ })
1270
+ });
1271
+ pi.registerTool({
1272
+ name: "steward_record_workspace",
1273
+ label: "记录 Steward 工作现场",
1274
+ description: "实现任务确认工作空间后,保存当前 Pi 会话的实际工作目录、Git 分支和会话定位。迁移或切换后在目标会话调用。",
1275
+ parameters: Type.Object({}),
1276
+ execute: (_id, _args, signal, _update, ctx) => report(async () => {
1277
+ if (taskContext?.task.type !== "implementation") throw new AgentError("task_context_required");
1278
+ const workspace = await currentWorkspace(ctx, taskContext.workspace.path);
1279
+ await write("POST", "workspace", workspace, (requestId) => request("POST", "workspace", okResponseSchema, validatedBody(agentWorkspaceRequestSchema, {
1280
+ workspace,
1281
+ requestId
1282
+ }), signal));
1283
+ return {
1284
+ ok: true,
1285
+ workspace
1286
+ };
962
1287
  })
963
1288
  });
964
1289
  pi.registerTool({
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { accessSync, closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { accessSync, closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir, hostname } from "node:os";
4
4
  import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { setTimeout } from "node:timers/promises";
@@ -31,7 +31,11 @@ var errorCodeSchema = z.enum([
31
31
  "machine_required",
32
32
  "attempt_ended",
33
33
  "rate_limited",
34
- "internal_error"
34
+ "internal_error",
35
+ "session_machine_offline",
36
+ "session_unsupported",
37
+ "session_record_missing",
38
+ "session_slots_full"
35
39
  ]);
36
40
  var errorResponseSchema = z.strictObject({ error: z.strictObject({
37
41
  code: errorCodeSchema,
@@ -48,10 +52,80 @@ z.strictObject({});
48
52
  var okResponseSchema = z.strictObject({ ok: z.literal(true) });
49
53
  var requestIdSchema = z.strictObject({ requestId: uuidSchema });
50
54
  var HEARTBEAT_INTERVAL_MS = 15e3;
55
+ // packages/contract/dist/session-control.js
56
+ var absoluteWorkspacePathSchema = z.string().max(4096).regex(/^\/[^\0]*$/u);
57
+ var piSessionIdSchema = z.string().max(256).regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/u);
58
+ var piSessionLocatorSchema = z.strictObject({
59
+ path: absoluteWorkspacePathSchema,
60
+ sessionId: piSessionIdSchema,
61
+ sessionFile: absoluteWorkspacePathSchema
62
+ });
63
+ requestIdSchema.extend({ locator: piSessionLocatorSchema });
64
+ var sessionOperationModeSchema = z.enum(["restart", "restore"]);
65
+ var sessionOperationFailureSchema = z.enum([
66
+ "session_workspace_unavailable",
67
+ "session_record_missing",
68
+ "session_config_unsupported",
69
+ "session_stop_failed",
70
+ "session_launch_failed",
71
+ "session_timeout"
72
+ ]);
73
+ var operation = z.strictObject({
74
+ id: uuidSchema,
75
+ attemptId: uuidSchema,
76
+ mode: sessionOperationModeSchema
77
+ });
78
+ var webSessionOperationSchema = operation.extend({
79
+ status: z.enum([
80
+ "pending",
81
+ "succeeded",
82
+ "failed"
83
+ ]),
84
+ failure: sessionOperationFailureSchema.nullable(),
85
+ needsExitVerification: z.literal(true).optional()
86
+ });
87
+ requestIdSchema.extend({
88
+ attemptId: uuidSchema,
89
+ mode: sessionOperationModeSchema
90
+ });
91
+ var permission = operation.extend({
92
+ locator: piSessionLocatorSchema,
93
+ validForMs: z.int().positive()
94
+ });
95
+ var launcherSessionDirectiveSchema = z.discriminatedUnion("step", [
96
+ permission.extend({
97
+ step: z.literal("stop"),
98
+ sourceEnded: z.boolean()
99
+ }),
100
+ permission.extend({
101
+ step: z.literal("launch"),
102
+ replacementId: uuidSchema
103
+ }),
104
+ operation.extend({
105
+ step: z.literal("cleanup"),
106
+ replacementId: uuidSchema
107
+ })
108
+ ]);
109
+ var launcherSessionReportSchema = z.discriminatedUnion("result", [requestIdSchema.extend({
110
+ result: z.literal("stopped"),
111
+ step: z.literal("stop")
112
+ }), requestIdSchema.extend({
113
+ result: z.literal("failed"),
114
+ step: z.enum([
115
+ "stop",
116
+ "launch",
117
+ "cleanup"
118
+ ]),
119
+ failure: sessionOperationFailureSchema
120
+ })]);
51
121
  // packages/contract/dist/models.js
52
122
  var titleSchema = z.string().trim().min(1).max(500);
53
123
  var taskTypeSchema = z.enum(["discussion", "implementation"]);
54
- var attemptKindSchema = z.enum(["new", "rework"]);
124
+ var attemptKindSchema = z.enum([
125
+ "new",
126
+ "rework",
127
+ "resume"
128
+ ]);
55
129
  var attemptResultSchema = z.enum([
56
130
  "delivered",
57
131
  "interrupted",
@@ -102,7 +176,7 @@ var attemptSchema = z.strictObject({
102
176
  machineName: z.string(),
103
177
  agent: agentSchema,
104
178
  kind: attemptKindSchema,
105
- sessionId: tmuxSessionSchema,
179
+ sessionId: piSessionIdSchema,
106
180
  tmuxSession: tmuxSessionSchema.nullable(),
107
181
  claimedAt: timestampSchema,
108
182
  startedAt: timestampSchema.nullable(),
@@ -185,7 +259,8 @@ z.strictObject({
185
259
  questions: z.array(questionSchema),
186
260
  deliveries: z.array(deliverySchema),
187
261
  attempts: z.array(attemptSchema),
188
- events: z.array(taskEventSchema)
262
+ events: z.array(taskEventSchema),
263
+ sessionOperation: webSessionOperationSchema.optional()
189
264
  });
190
265
  taskContentSchema.partial().required({ title: true }).extend({ projectId: projectIdSchema });
191
266
  taskContentSchema.omit({ type: true }).partial().extend({ version: z.int().positive() }).refine((input) => Object.keys(input).some((key) => key !== "version"));
@@ -217,6 +292,7 @@ z.strictObject({ machines: z.array(webMachineSchema) });
217
292
  var launcherHeartbeatRequestSchema = requestIdSchema.extend({
218
293
  launcherVersion: z.string().trim().min(1).max(128),
219
294
  slots: slotsSchema,
295
+ sessionControl: z.literal(true).optional(),
220
296
  projects: z.array(z.strictObject({
221
297
  id: projectIdSchema,
222
298
  name: z.string().trim().min(1).max(500),
@@ -228,15 +304,18 @@ var launcherHeartbeatRequestSchema = requestIdSchema.extend({
228
304
  running: z.boolean()
229
305
  })).max(1e3).refine((items) => new Set(items.map(({ id }) => id)).size === items.length)
230
306
  });
231
- var launcherHeartbeatResponseSchema = z.strictObject({ directives: z.array(z.strictObject({
232
- attemptId: uuidSchema,
233
- tmuxSession: tmuxSessionSchema,
234
- action: z.enum([
235
- "continue",
236
- "cancel",
237
- "unknown"
238
- ])
239
- })) });
307
+ var launcherHeartbeatResponseSchema = z.strictObject({
308
+ directives: z.array(z.strictObject({
309
+ attemptId: uuidSchema,
310
+ tmuxSession: tmuxSessionSchema,
311
+ action: z.enum([
312
+ "continue",
313
+ "cancel",
314
+ "unknown"
315
+ ])
316
+ })),
317
+ sessionOperations: z.array(launcherSessionDirectiveSchema).optional()
318
+ });
240
319
  var claimedAttemptSchema = z.strictObject({
241
320
  id: uuidSchema,
242
321
  taskId: uuidSchema,
@@ -245,7 +324,7 @@ var claimedAttemptSchema = z.strictObject({
245
324
  sessionId: tmuxSessionSchema,
246
325
  restoreSession: z.boolean(),
247
326
  displayName: z.string().min(1).max(80),
248
- kind: attemptKindSchema
327
+ kind: z.enum(["new", "rework"])
249
328
  });
250
329
  var launcherClaimResponseSchema = z.strictObject({ attempt: claimedAttemptSchema.nullable() });
251
330
  var launcherStartedRequestSchema = requestIdSchema.extend({
@@ -258,6 +337,17 @@ var launcherExitedRequestSchema = requestIdSchema.extend({
258
337
  });
259
338
  var launcherStartedResponseSchema = okResponseSchema;
260
339
  var launcherExitedResponseSchema = okResponseSchema;
340
+ // packages/contract/dist/agent.js
341
+ var gitBranch = z.string().min(1).max(1024).regex(/^[^\0\r\n]+$/u);
342
+ var attemptWorkspaceSchema = piSessionLocatorSchema.extend({
343
+ gitKind: z.enum([
344
+ "non_git",
345
+ "primary",
346
+ "linked"
347
+ ]),
348
+ gitBranch: gitBranch.nullable()
349
+ }).refine(({ gitKind, gitBranch }) => gitKind !== "non_git" || gitBranch === null);
350
+ requestIdSchema.extend({ workspace: attemptWorkspaceSchema });
261
351
  z.strictObject({
262
352
  task: taskContentSchema.pick({
263
353
  title: true,
@@ -275,7 +365,13 @@ z.strictObject({
275
365
  }),
276
366
  workspace: z.strictObject({
277
367
  path: z.string(),
278
- requirements: z.array(nonEmptyTextSchema)
368
+ requirements: z.array(nonEmptyTextSchema),
369
+ previous: z.strictObject({
370
+ attemptId: uuidSchema,
371
+ machineId: uuidSchema,
372
+ sameMachine: z.boolean(),
373
+ workspace: attemptWorkspaceSchema.nullable()
374
+ }).nullable().optional()
279
375
  }),
280
376
  decisions: z.array(decisionSchema.extend({ confirmedByUser: z.literal(true) })),
281
377
  deliveries: z.array(deliverySchema),
@@ -568,6 +664,7 @@ async function platformFetch(url, init, proxy = SYSTEM_PROXY) {
568
664
  }
569
665
  // apps/launcher/dist/platform.js
570
666
  var REQUEST_TIMEOUT_MS$1 = 4e3;
667
+ var legacyHeartbeatResponse = launcherHeartbeatResponseSchema.omit({ sessionOperations: true }).strip();
571
668
  var PlatformError = class extends Error {
572
669
  code;
573
670
  startedAlreadySaved;
@@ -617,7 +714,20 @@ function platformClient(config, fetcher, getMachineToken = () => config.machineT
617
714
  }
618
715
  return {
619
716
  claim: (requestId) => post("claim", { requestId }, launcherClaimResponseSchema),
620
- heartbeat: (body) => post("heartbeat", body, launcherHeartbeatResponseSchema),
717
+ heartbeat: async (body) => {
718
+ if (!body.sessionControl) return post("heartbeat", body, legacyHeartbeatResponse);
719
+ try {
720
+ return await post("heartbeat", body, launcherHeartbeatResponseSchema);
721
+ } catch (error) {
722
+ if (!(error instanceof PlatformError) || error.code !== "invalid_request") throw error;
723
+ return post("heartbeat", {
724
+ ...body,
725
+ sessionControl: void 0,
726
+ requestId: randomUUID()
727
+ }, legacyHeartbeatResponse);
728
+ }
729
+ },
730
+ reportSession: (id, body) => post(`session-operations/${id}/report`, body, okResponseSchema),
621
731
  report: (e) => post(`attempts/${e.id}/${e.kind}`, e.body, e.kind === "started" ? launcherStartedResponseSchema : launcherExitedResponseSchema, e.kind === "started")
622
732
  };
623
733
  }
@@ -635,10 +745,23 @@ function commandFailure(error) {
635
745
  return error.code === "ENOENT" ? "missing" : "unavailable";
636
746
  }
637
747
  var TmuxError = class extends Error {
638
- constructor() {
748
+ notStarted;
749
+ constructor(notStarted = false) {
639
750
  super("无法完成 tmux 操作,将在下次循环重新核对。");
751
+ this.notStarted = notStarted;
640
752
  }
641
753
  };
754
+ function parsePid(value) {
755
+ const pid = /^[1-9][0-9]*$/u.test(value) ? Number(value) : NaN;
756
+ return pid > 1 && pid <= 2147483647 ? pid : void 0;
757
+ }
758
+ function resumeCommandDidNotStart(error, target) {
759
+ const { code, killed, signal, stderr } = error;
760
+ if (code === "ENOENT" || code === "EACCES") return true;
761
+ if (code !== 1 || killed || signal || typeof stderr !== "string") return false;
762
+ const message = stderr.trimEnd();
763
+ return message === `duplicate session: ${target}` || message === `invalid session name: ${target}` || /^(?:create window failed: )?fork failed(?:: [^\r\n]+)?$/u.test(message);
764
+ }
642
765
  function displayName(title) {
643
766
  return title.replace(/[^\p{L}\p{N} _-]/gu, " ").trim().replace(/^[ -]+/u, "").slice(0, 79).replace(/[\uD800-\uDBFF]$/u, "").trimEnd() || "Pi task";
644
767
  }
@@ -693,6 +816,50 @@ function tmuxClient(config, options) {
693
816
  if (!Array.isArray(sessions)) return "unavailable";
694
817
  return sessions.includes(target) ? "present" : "absent";
695
818
  },
819
+ async panePid(target) {
820
+ try {
821
+ const { stdout } = await exec([
822
+ "list-panes",
823
+ "-s",
824
+ "-t",
825
+ `=${target}`,
826
+ "-F",
827
+ "#{session_name} #{pane_pid}"
828
+ ]);
829
+ const [name, pid, extra] = stdout.trimEnd().split(" ");
830
+ return name === target && pid !== void 0 && extra === void 0 ? parsePid(pid) : void 0;
831
+ } catch {
832
+ return;
833
+ }
834
+ },
835
+ async hasResumeIdentity(attemptId) {
836
+ const target = `=${targetFor(attemptId)}`;
837
+ try {
838
+ if ((await exec([
839
+ "show-environment",
840
+ "-t",
841
+ target,
842
+ "STEWARD_ATTEMPT_ID"
843
+ ])).stdout !== `STEWARD_ATTEMPT_ID=${attemptId}\n`) return false;
844
+ return (await exec([
845
+ "show-environment",
846
+ "-t",
847
+ target,
848
+ "STEWARD_RESUME"
849
+ ])).stdout === "STEWARD_RESUME=1\n";
850
+ } catch {
851
+ return false;
852
+ }
853
+ },
854
+ processStatus(pid) {
855
+ if (parsePid(String(pid)) === void 0) return "unavailable";
856
+ try {
857
+ process.kill(pid, 0);
858
+ return "alive";
859
+ } catch (error) {
860
+ return error.code === "ESRCH" ? "dead" : "unavailable";
861
+ }
862
+ },
696
863
  async launch(target, claim, projectPath) {
697
864
  const message = `${claim.kind === "rework" ? "返修本任务。" : "开始执行本任务。"}${instructions}`;
698
865
  try {
@@ -725,6 +892,44 @@ function tmuxClient(config, options) {
725
892
  throw new TmuxError();
726
893
  }
727
894
  },
895
+ async launchResume(target, attemptId, locator) {
896
+ if (target !== targetFor(attemptId)) throw new TmuxError(true);
897
+ try {
898
+ const { stdout } = await exec([
899
+ "new-session",
900
+ "-d",
901
+ "-s",
902
+ target,
903
+ "-P",
904
+ "-F",
905
+ "#{pane_pid}",
906
+ "-c",
907
+ `${locator.path.replaceAll("#", "##")}/.`,
908
+ "-e",
909
+ `STEWARD_ATTEMPT_ID=${attemptId}`,
910
+ "-e",
911
+ escapedTmuxArg(`STEWARD_CONFIG=${options.configPath}`),
912
+ "-e",
913
+ "STEWARD_RESUME=1",
914
+ "-e",
915
+ escapedTmuxArg(`PATH=${path}`),
916
+ "--",
917
+ ...[
918
+ config.pi.command,
919
+ ...config.pi.extraArgs,
920
+ "-e",
921
+ options.extensionPath,
922
+ "--session",
923
+ locator.sessionFile
924
+ ].map(escapedTmuxArg)
925
+ ]);
926
+ const pid = parsePid(stdout.trim());
927
+ if (pid !== void 0) return pid;
928
+ } catch (error) {
929
+ throw new TmuxError(resumeCommandDidNotStart(error, target));
930
+ }
931
+ throw new TmuxError();
932
+ },
728
933
  async cancel(target) {
729
934
  try {
730
935
  await exec([
@@ -738,7 +943,325 @@ function tmuxClient(config, options) {
738
943
  }
739
944
  };
740
945
  }
946
+ // apps/launcher/dist/session-control.js
947
+ var MAX_HEADER_BYTES = 65536;
948
+ var HEADER_READ_BLOCK_BYTES = 4096;
949
+ var validElapsed = (elapsed, validForMs) => elapsed >= 0 && elapsed < validForMs;
950
+ var VALUE_FLAGS = /* @__PURE__ */ new Set([
951
+ "--provider",
952
+ "--model",
953
+ "--models",
954
+ "--thinking",
955
+ "--extension",
956
+ "-e",
957
+ "--tools",
958
+ "-t",
959
+ "--exclude-tools",
960
+ "-xt",
961
+ "--theme",
962
+ "--use-theme"
963
+ ]);
964
+ var SWITCH_FLAGS = /* @__PURE__ */ new Set([
965
+ "--approve",
966
+ "-a",
967
+ "--no-approve",
968
+ "-na",
969
+ "--no-tools",
970
+ "-nt",
971
+ "--no-builtin-tools",
972
+ "-nbt",
973
+ "--offline",
974
+ "--no-extensions",
975
+ "-ne",
976
+ "--no-context-files",
977
+ "-nc",
978
+ "--no-skills",
979
+ "-ns"
980
+ ]);
981
+ function supportsResumeArgs(args) {
982
+ for (let i = 0; i < args.length; i++) {
983
+ const flag = args[i];
984
+ if (flag === void 0) return false;
985
+ if (SWITCH_FLAGS.has(flag)) continue;
986
+ if (!VALUE_FLAGS.has(flag)) return false;
987
+ const value = args[++i];
988
+ if (!value || /^[-@]|[\0\r\n]/u.test(value)) return false;
989
+ }
990
+ return true;
991
+ }
992
+ function readHeader(file) {
993
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
994
+ try {
995
+ if (!fstatSync(fd).isFile()) throw new Error();
996
+ const bytes = Buffer.alloc(MAX_HEADER_BYTES);
997
+ for (let offset = 0; offset < bytes.length;) {
998
+ const count = readSync(fd, bytes, offset, Math.min(HEADER_READ_BLOCK_BYTES, bytes.length - offset), null);
999
+ if (!count) return JSON.parse(bytes.toString("utf8", 0, offset));
1000
+ const newline = bytes.subarray(offset, offset + count).indexOf(10);
1001
+ if (newline >= 0) return JSON.parse(bytes.toString("utf8", 0, offset + newline));
1002
+ offset += count;
1003
+ }
1004
+ throw new Error();
1005
+ } finally {
1006
+ closeSync(fd);
1007
+ }
1008
+ }
1009
+ function validateLocator(locator) {
1010
+ try {
1011
+ if (realpathSync(locator.path) !== locator.path || !statSync(locator.path).isDirectory()) return "session_workspace_unavailable";
1012
+ accessSync(locator.path, constants.R_OK | constants.X_OK);
1013
+ } catch {
1014
+ return "session_workspace_unavailable";
1015
+ }
1016
+ let header;
1017
+ try {
1018
+ if (realpathSync(locator.sessionFile) !== locator.sessionFile) return "session_record_missing";
1019
+ header = readHeader(locator.sessionFile);
1020
+ } catch {
1021
+ return "session_record_missing";
1022
+ }
1023
+ if (header?.type !== "session" || header.id !== locator.sessionId) return "session_record_missing";
1024
+ try {
1025
+ if (typeof header.cwd !== "string" || !isAbsolute(header.cwd) || realpathSync(header.cwd) !== locator.path) return "session_workspace_unavailable";
1026
+ } catch {
1027
+ return "session_workspace_unavailable";
1028
+ }
1029
+ }
1030
+ var SessionControl = class {
1031
+ options;
1032
+ constructor(options) {
1033
+ this.options = options;
1034
+ }
1035
+ get state() {
1036
+ return this.options.state;
1037
+ }
1038
+ get tmux() {
1039
+ return this.options.tmux;
1040
+ }
1041
+ save() {
1042
+ this.options.save();
1043
+ }
1044
+ record(id) {
1045
+ return this.state.executions.find((item) => item.id === id);
1046
+ }
1047
+ rememberPid(record, pid) {
1048
+ if (record.pid === void 0) {
1049
+ record.pid = pid;
1050
+ this.save();
1051
+ }
1052
+ return record.pid === pid;
1053
+ }
1054
+ finish(op, failure) {
1055
+ if (!failure && op.step !== "stop") return;
1056
+ op.report = failure ? {
1057
+ requestId: randomUUID(),
1058
+ result: "failed",
1059
+ step: op.step,
1060
+ failure
1061
+ } : {
1062
+ requestId: randomUUID(),
1063
+ result: "stopped",
1064
+ step: "stop"
1065
+ };
1066
+ this.save();
1067
+ }
1068
+ definitelyDead(pid) {
1069
+ return pid !== void 0 && this.tmux.processStatus(pid) === "dead";
1070
+ }
1071
+ async sourceGone(attemptId) {
1072
+ if (await this.tmux.inspect(targetFor(attemptId)) !== "absent") return false;
1073
+ const pid = this.record(attemptId)?.pid;
1074
+ return pid === void 0 || this.definitelyDead(pid);
1075
+ }
1076
+ async replacementGone(op) {
1077
+ const id = op.replacementId;
1078
+ if (id === void 0 || id === op.attemptId) return false;
1079
+ const record = this.record(id);
1080
+ if (record && record.sessionOperationId !== op.id) return false;
1081
+ if (await this.tmux.inspect(targetFor(id)) !== "absent" || !await this.sourceGone(op.attemptId)) return false;
1082
+ return record?.pid !== void 0 ? this.definitelyDead(record.pid) : op.launchIssued === false;
1083
+ }
1084
+ async remainsStopped(target, pid, mayRecheck = () => true) {
1085
+ for (let i = 0; i < 3; i++) {
1086
+ if (await this.tmux.inspect(target) === "absent" && this.definitelyDead(pid)) return true;
1087
+ if (i === 2 || !mayRecheck()) break;
1088
+ await setTimeout(50);
1089
+ if (!mayRecheck()) break;
1090
+ }
1091
+ return false;
1092
+ }
1093
+ invalid(locator) {
1094
+ return validateLocator(locator) ?? (supportsResumeArgs(this.options.extraArgs) ? void 0 : "session_config_unsupported");
1095
+ }
1096
+ async stop(directive, op, valid) {
1097
+ const invalid = this.invalid(directive.locator);
1098
+ if (invalid) {
1099
+ this.finish(op, invalid);
1100
+ return;
1101
+ }
1102
+ const target = targetFor(directive.attemptId);
1103
+ const existing = this.record(directive.attemptId);
1104
+ const status = await this.tmux.inspect(target);
1105
+ if (status === "absent") {
1106
+ const pid = existing?.pid;
1107
+ if (pid === void 0 && directive.sourceEnded || this.definitelyDead(pid) || op.stopIssued && pid !== void 0 && await this.remainsStopped(target, pid, valid)) this.finish(op);
1108
+ else this.finish(op, "session_stop_failed");
1109
+ return;
1110
+ }
1111
+ if (op.stopIssued && existing?.pid !== void 0 && await this.remainsStopped(target, existing.pid, valid)) {
1112
+ this.finish(op);
1113
+ return;
1114
+ }
1115
+ if (status !== "present" || directive.sourceEnded || op.stopIssued || existing?.phase === "exited") {
1116
+ this.finish(op, "session_stop_failed");
1117
+ return;
1118
+ }
1119
+ const pid = await this.tmux.panePid(target);
1120
+ if (pid === void 0 || this.tmux.processStatus(pid) !== "alive") {
1121
+ this.finish(op, "session_stop_failed");
1122
+ return;
1123
+ }
1124
+ const record = existing ?? {
1125
+ id: directive.attemptId,
1126
+ target,
1127
+ phase: "observed"
1128
+ };
1129
+ if (!existing) this.state.executions.push(record);
1130
+ if (!this.rememberPid(record, pid)) {
1131
+ this.finish(op, "session_stop_failed");
1132
+ return;
1133
+ }
1134
+ if (!valid()) return;
1135
+ op.stopIssued = true;
1136
+ this.save();
1137
+ if (!valid()) {
1138
+ delete op.stopIssued;
1139
+ this.save();
1140
+ return;
1141
+ }
1142
+ await this.tryCancel(target);
1143
+ this.finish(op, await this.remainsStopped(target, pid, valid) ? void 0 : "session_stop_failed");
1144
+ }
1145
+ async launch(directive, op, valid) {
1146
+ const id = directive.replacementId;
1147
+ const target = targetFor(id);
1148
+ if (id === directive.attemptId) return;
1149
+ const existing = this.record(id);
1150
+ if (op.launchIssued || existing) {
1151
+ if (existing?.sessionOperationId === op.id && op.launchIssued === false && await this.replacementGone(op)) {
1152
+ existing.phase = "exited";
1153
+ this.finish(op, "session_launch_failed");
1154
+ }
1155
+ return;
1156
+ }
1157
+ if (await this.tmux.inspect(target) !== "absent" || !await this.sourceGone(directive.attemptId)) return;
1158
+ const invalid = this.invalid(directive.locator);
1159
+ if (invalid) {
1160
+ op.launchIssued = false;
1161
+ this.finish(op, invalid);
1162
+ return;
1163
+ }
1164
+ if (!valid()) return;
1165
+ const record = {
1166
+ id,
1167
+ target,
1168
+ phase: "launching",
1169
+ startedAt: this.options.now(),
1170
+ sessionOperationId: op.id
1171
+ };
1172
+ const previouslyIssued = op.launchIssued;
1173
+ op.launchIssued = true;
1174
+ this.state.executions.push(record);
1175
+ this.save();
1176
+ if (!valid()) {
1177
+ op.launchIssued = previouslyIssued;
1178
+ this.state.executions = this.state.executions.filter((item) => item !== record);
1179
+ this.save();
1180
+ return;
1181
+ }
1182
+ try {
1183
+ const pid = await this.tmux.launchResume(target, id, directive.locator);
1184
+ this.rememberPid(record, pid);
1185
+ if (await this.tmux.inspect(target) === "present" && await this.tmux.panePid(target) === pid) this.options.started(record);
1186
+ } catch (error) {
1187
+ if (!(error instanceof TmuxError)) throw error;
1188
+ if (error.notStarted) {
1189
+ op.launchIssued = false;
1190
+ this.save();
1191
+ if (await this.replacementGone(op)) {
1192
+ record.phase = "exited";
1193
+ this.finish(op, "session_launch_failed");
1194
+ }
1195
+ }
1196
+ this.options.warn?.(error.message);
1197
+ }
1198
+ }
1199
+ async cleanup(directive, op) {
1200
+ if (directive.replacementId === directive.attemptId) return;
1201
+ const target = targetFor(directive.replacementId);
1202
+ const record = this.record(directive.replacementId);
1203
+ if (record && record.sessionOperationId !== op.id) return;
1204
+ const status = await this.tmux.inspect(target);
1205
+ if (status === "absent") {
1206
+ if (await this.replacementGone(op)) this.finish(op, "session_timeout");
1207
+ return;
1208
+ }
1209
+ if (status !== "present") return;
1210
+ const pid = await this.tmux.panePid(target);
1211
+ if (pid === void 0 || record?.pid !== void 0 && record.pid !== pid || op.stopIssued && record?.pid !== pid) return;
1212
+ if (!await this.tmux.hasResumeIdentity(directive.replacementId)) return;
1213
+ const candidate = record ?? {
1214
+ id: directive.replacementId,
1215
+ target,
1216
+ phase: "observed",
1217
+ sessionOperationId: op.id
1218
+ };
1219
+ if (await this.tmux.panePid(target) !== pid || this.tmux.processStatus(pid) !== "alive") return;
1220
+ if (!record) this.state.executions.push(candidate);
1221
+ candidate.pid = pid;
1222
+ op.stopIssued = true;
1223
+ this.save();
1224
+ await this.tryCancel(target);
1225
+ if (await this.remainsStopped(target, pid) && await this.sourceGone(directive.attemptId)) this.finish(op, "session_timeout");
1226
+ }
1227
+ async tryCancel(target) {
1228
+ try {
1229
+ await this.tmux.cancel(target);
1230
+ } catch (error) {
1231
+ if (!(error instanceof TmuxError)) throw error;
1232
+ this.options.warn?.(error.message);
1233
+ }
1234
+ }
1235
+ async apply(directive, requestStartedAt) {
1236
+ const { id, attemptId, step } = directive;
1237
+ const valid = () => step === "cleanup" || validElapsed(this.options.now() - requestStartedAt.wall, directive.validForMs) && validElapsed(this.options.monotonicNow() - requestStartedAt.monotonic, directive.validForMs);
1238
+ if (!valid()) return;
1239
+ const operations = this.state.sessionOperations ??= [];
1240
+ let op = operations.find((item) => item.id === id);
1241
+ const replacementId = step === "stop" ? void 0 : directive.replacementId;
1242
+ if (op && (op.attemptId !== attemptId || op.replacementId !== void 0 && op.replacementId !== replacementId)) return;
1243
+ if (op && op.step !== step && (step === "stop" || op.step === "cleanup")) return;
1244
+ if (op?.step !== step) {
1245
+ op = {
1246
+ id,
1247
+ attemptId,
1248
+ step,
1249
+ replacementId,
1250
+ launchIssued: op?.launchIssued ?? (op && op.step === "stop" ? false : void 0)
1251
+ };
1252
+ const previous = operations.findIndex((item) => item.id === id);
1253
+ if (previous < 0) operations.push(op);
1254
+ else operations[previous] = op;
1255
+ this.save();
1256
+ }
1257
+ if (op.report) return;
1258
+ if (step === "stop") await this.stop(directive, op, valid);
1259
+ else if (step === "launch") await this.launch(directive, op, valid);
1260
+ else await this.cleanup(directive, op);
1261
+ }
1262
+ };
741
1263
  // apps/launcher/dist/launcher.js
1264
+ var managedId = (operation) => operation.step === "stop" ? operation.attemptId : operation.replacementId;
742
1265
  var TERMINAL_REPORT_ERRORS = /* @__PURE__ */ new Set([
743
1266
  "attempt_ended",
744
1267
  "forbidden",
@@ -752,8 +1275,19 @@ var Launcher = class {
752
1275
  nextOutboxRetryAt = 0;
753
1276
  outboxBackoff = HEARTBEAT_INTERVAL_MS;
754
1277
  lastTmuxHealth = "ready";
1278
+ control;
755
1279
  constructor(options) {
756
1280
  this.options = options;
1281
+ this.control = new SessionControl({
1282
+ state: options.state,
1283
+ tmux: options.tmux,
1284
+ save: () => this.persist(),
1285
+ now: () => this.now(),
1286
+ monotonicNow: () => this.monotonicNow(),
1287
+ extraArgs: options.config.pi.extraArgs,
1288
+ started: (record) => this.started(record),
1289
+ warn: options.warn
1290
+ });
757
1291
  }
758
1292
  get state() {
759
1293
  return this.options.state;
@@ -764,6 +1298,9 @@ var Launcher = class {
764
1298
  now() {
765
1299
  return (this.options.now ?? Date.now)();
766
1300
  }
1301
+ monotonicNow() {
1302
+ return this.options.monotonicNow?.() ?? performance.now();
1303
+ }
767
1304
  async retryable(run) {
768
1305
  try {
769
1306
  return await run();
@@ -773,9 +1310,18 @@ var Launcher = class {
773
1310
  return;
774
1311
  }
775
1312
  }
1313
+ pendingOperationFor(attemptId) {
1314
+ return this.state.sessionOperations?.find(({ replacementId }) => replacementId === attemptId);
1315
+ }
776
1316
  async flush() {
777
1317
  if (this.now() < this.nextOutboxRetryAt) return false;
1318
+ let deferred = false;
778
1319
  for (const event of [...this.state.outbox]) {
1320
+ const operation = this.pendingOperationFor(event.id);
1321
+ if (event.kind === "exited" && operation && !await this.control.replacementGone(operation)) {
1322
+ deferred = true;
1323
+ continue;
1324
+ }
779
1325
  let confirmed = true;
780
1326
  try {
781
1327
  await this.options.platform.report(event);
@@ -793,10 +1339,10 @@ var Launcher = class {
793
1339
  this.outboxBackoff = HEARTBEAT_INTERVAL_MS;
794
1340
  this.nextOutboxRetryAt = 0;
795
1341
  this.state.outbox = this.state.outbox.filter(({ body }) => body.requestId !== event.body.requestId);
796
- if (event.kind === "exited" && confirmed) this.remove(event.id);
1342
+ if (event.kind === "exited" && confirmed && !operation) this.remove(event.id);
797
1343
  else this.persist();
798
1344
  }
799
- return true;
1345
+ return !deferred;
800
1346
  }
801
1347
  remove(id) {
802
1348
  this.state.executions = this.state.executions.filter((record) => record.id !== id);
@@ -830,6 +1376,24 @@ var Launcher = class {
830
1376
  });
831
1377
  this.persist();
832
1378
  }
1379
+ async observePresent(record) {
1380
+ const pendingResume = record.sessionOperationId && record.phase === "launching";
1381
+ if (record.pid === void 0 || pendingResume) {
1382
+ const pid = await this.options.tmux.panePid(record.target);
1383
+ if (pendingResume && (pid === void 0 || record.pid !== void 0 && record.pid !== pid)) return false;
1384
+ if (pid !== void 0 && record.pid === void 0) {
1385
+ if (pendingResume && (!await this.options.tmux.hasResumeIdentity(record.id) || await this.options.tmux.panePid(record.target) !== pid)) return false;
1386
+ record.pid = pid;
1387
+ this.persist();
1388
+ }
1389
+ }
1390
+ this.started(record);
1391
+ return true;
1392
+ }
1393
+ absenceConfirmed(record) {
1394
+ if (record.pid !== void 0) return this.options.tmux.processStatus(record.pid) === "dead";
1395
+ return record.sessionOperationId === void 0;
1396
+ }
833
1397
  async observe() {
834
1398
  const attempts = [];
835
1399
  for (const record of this.state.executions) {
@@ -839,8 +1403,13 @@ var Launcher = class {
839
1403
  this.options.warn?.("tmux 会话核对失败,保留本地尝试。");
840
1404
  continue;
841
1405
  }
842
- if (status === "present") this.started(record);
843
- if (status === "absent" && record.phase !== "prepared") this.exited(record);
1406
+ if (status === "present" && !await this.observePresent(record)) continue;
1407
+ if (status === "absent" && record.phase !== "prepared") {
1408
+ if (!this.absenceConfirmed(record)) continue;
1409
+ const operation = this.pendingOperationFor(record.id);
1410
+ if (operation && !await this.control.replacementGone(operation)) continue;
1411
+ this.exited(record);
1412
+ }
844
1413
  attempts.push({
845
1414
  id: record.id,
846
1415
  tmuxSession: record.target,
@@ -851,18 +1420,25 @@ var Launcher = class {
851
1420
  }
852
1421
  async heartbeat() {
853
1422
  const attempts = await this.observe();
1423
+ const requestStartedAt = {
1424
+ wall: this.now(),
1425
+ monotonic: this.monotonicNow()
1426
+ };
854
1427
  const response = await this.retryable(() => this.options.platform.heartbeat({
855
1428
  requestId: randomUUID(),
856
1429
  launcherVersion: this.options.version,
1430
+ sessionControl: true,
857
1431
  slots: this.options.config.slots,
858
1432
  projects: this.options.config.projects,
859
1433
  attempts
860
1434
  }));
861
- if (response) {
862
- this.state.lastHeartbeatAt = this.now();
863
- this.persist();
864
- }
865
- return response;
1435
+ if (!response) return;
1436
+ this.state.lastHeartbeatAt = this.now();
1437
+ this.persist();
1438
+ return {
1439
+ response,
1440
+ requestStartedAt
1441
+ };
866
1442
  }
867
1443
  async startPrepared(record) {
868
1444
  const claim = record.claim;
@@ -900,17 +1476,51 @@ var Launcher = class {
900
1476
  await this.retryable(() => this.options.tmux.cancel(target));
901
1477
  if (await this.options.tmux.inspect(target) !== "absent") return;
902
1478
  }
903
- this.exited(record);
904
- } else if (status === "present") this.started(record);
1479
+ if (this.absenceConfirmed(record)) this.exited(record);
1480
+ } else if (status === "present") await this.observePresent(record);
905
1481
  else if (action === "continue" && record.phase === "prepared") await this.startPrepared(record);
906
- else if (record.phase !== "prepared") this.exited(record);
1482
+ else if (record.phase !== "prepared" && this.absenceConfirmed(record)) this.exited(record);
907
1483
  }
908
- async reconcile(response, claimPending = false) {
1484
+ async reconcileSessionOperations(operations, requestStartedAt) {
1485
+ const protectedIds = /* @__PURE__ */ new Set();
1486
+ for (const directive of operations) {
1487
+ protectedIds.add(directive.attemptId);
1488
+ protectedIds.add(managedId(directive));
1489
+ await this.control.apply(directive, requestStartedAt);
1490
+ const operation = this.state.sessionOperations?.find(({ id, step, attemptId, replacementId }) => id === directive.id && step === directive.step && attemptId === directive.attemptId && (step === "stop" || replacementId === managedId(directive)));
1491
+ if (!operation?.report || operation.reportAcknowledged) continue;
1492
+ if (operation.step !== "stop" && !await this.control.replacementGone(operation)) continue;
1493
+ try {
1494
+ await this.options.platform.reportSession(operation.id, operation.report);
1495
+ } catch (error) {
1496
+ if (!(error instanceof PlatformError)) throw error;
1497
+ this.options.warn?.(error.message);
1498
+ if (!TERMINAL_REPORT_ERRORS.has(error.code)) continue;
1499
+ }
1500
+ operation.reportAcknowledged = true;
1501
+ this.persist();
1502
+ }
1503
+ return protectedIds;
1504
+ }
1505
+ async reconcile({ response, requestStartedAt }, claimPending = false) {
1506
+ const operations = response.sessionOperations ?? [];
1507
+ const protectedIds = await this.reconcileSessionOperations(operations, requestStartedAt);
909
1508
  for (const directive of response.directives) {
1509
+ if (protectedIds.has(directive.attemptId)) continue;
910
1510
  if (claimPending && !this.state.executions.some(({ id }) => id === directive.attemptId)) continue;
911
1511
  await this.applyDirective(directive);
912
1512
  }
913
- const active = new Set(response.directives.map(({ attemptId }) => attemptId));
1513
+ const active = /* @__PURE__ */ new Set([...response.directives.map(({ attemptId }) => attemptId), ...protectedIds]);
1514
+ const localOperations = this.state.sessionOperations;
1515
+ if (localOperations) {
1516
+ const live = new Set(operations.map(({ id }) => id));
1517
+ const ordinary = new Set(response.directives.map(({ attemptId }) => attemptId));
1518
+ const keep = localOperations.filter((item) => live.has(item.id) || !item.reportAcknowledged && (item.replacementId === void 0 || !ordinary.has(item.replacementId)));
1519
+ if (keep.length !== localOperations.length) {
1520
+ this.state.sessionOperations = keep;
1521
+ this.persist();
1522
+ }
1523
+ }
914
1524
  const pending = new Set(this.state.outbox.map(({ id }) => id));
915
1525
  for (const record of [...this.state.executions]) {
916
1526
  if (active.has(record.id)) continue;
@@ -952,7 +1562,11 @@ var Launcher = class {
952
1562
  await this.reconcile(heartbeat, !!this.state.claimRequestId);
953
1563
  if (!flushed || !await this.flush() || replayed) return;
954
1564
  const slots = this.options.config.slots;
955
- if ((/* @__PURE__ */ new Set([...heartbeat.directives.map(({ attemptId }) => attemptId), ...this.state.executions.filter(({ phase }) => phase !== "exited").map(({ id }) => id)])).size >= slots || !await this.canClaim()) return;
1565
+ if ((/* @__PURE__ */ new Set([
1566
+ ...heartbeat.response.directives.map(({ attemptId }) => attemptId),
1567
+ ...(heartbeat.response.sessionOperations ?? []).map(managedId),
1568
+ ...this.state.executions.filter(({ phase }) => phase !== "exited").map(({ id }) => id)
1569
+ ])).size >= slots || !await this.canClaim()) return;
956
1570
  if (!await this.claim()) return;
957
1571
  const afterClaim = await this.heartbeat();
958
1572
  if (!afterClaim) return;
@@ -1198,7 +1812,9 @@ var execution = z.strictObject({
1198
1812
  "exited"
1199
1813
  ]),
1200
1814
  claim: claimedAttemptSchema.optional(),
1201
- startedAt: timestampSchema.optional()
1815
+ startedAt: timestampSchema.optional(),
1816
+ pid: z.int().min(2).max(2147483647).optional(),
1817
+ sessionOperationId: uuidSchema.optional()
1202
1818
  }).refine(({ id, target, phase, claim, startedAt }) => target === `steward-${id}` && (!claim || claim.id === id) && (phase !== "prepared" || !!claim) && (phase !== "launching" || startedAt !== void 0));
1203
1819
  var event = z.discriminatedUnion("kind", [z.strictObject({
1204
1820
  kind: z.literal("started"),
@@ -1209,11 +1825,26 @@ var event = z.discriminatedUnion("kind", [z.strictObject({
1209
1825
  id: uuidSchema,
1210
1826
  body: launcherExitedRequestSchema
1211
1827
  })]);
1828
+ var sessionOperation = z.strictObject({
1829
+ id: uuidSchema,
1830
+ attemptId: uuidSchema,
1831
+ replacementId: uuidSchema.optional(),
1832
+ step: z.enum([
1833
+ "stop",
1834
+ "launch",
1835
+ "cleanup"
1836
+ ]),
1837
+ stopIssued: z.boolean().optional(),
1838
+ launchIssued: z.boolean().optional(),
1839
+ report: launcherSessionReportSchema.optional(),
1840
+ reportAcknowledged: z.boolean().optional()
1841
+ }).refine(({ step, replacementId, report }) => step === "stop" === (replacementId === void 0) && (!report || report.step === step));
1212
1842
  var stateSchema = z.strictObject({
1213
1843
  version: z.literal(1),
1214
1844
  claimRequestId: uuidSchema.optional(),
1215
1845
  lastHeartbeatAt: timestampSchema.optional(),
1216
1846
  executions: z.array(execution),
1847
+ sessionOperations: z.array(sessionOperation).optional(),
1217
1848
  outbox: z.array(event)
1218
1849
  });
1219
1850
  function loadState(path) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yefengr/steward",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Task Steward macOS launcher and task extension",
5
5
  "repository": {
6
6
  "type": "git",