@yefengr/steward 0.1.1 → 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/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,9 +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
- var attemptKindSchema = z.enum(["new", "rework"]);
123
+ var taskTypeSchema = z.enum(["discussion", "implementation"]);
124
+ var attemptKindSchema = z.enum([
125
+ "new",
126
+ "rework",
127
+ "resume"
128
+ ]);
54
129
  var attemptResultSchema = z.enum([
55
130
  "delivered",
56
131
  "interrupted",
@@ -75,7 +150,8 @@ var taskContentSchema = z.strictObject({
75
150
  acceptance: textSchema,
76
151
  notes: textSchema,
77
152
  agent: agentSchema,
78
- machineId: uuidSchema.nullable()
153
+ machineId: uuidSchema.nullable(),
154
+ type: taskTypeSchema
79
155
  });
80
156
  var taskSchema = taskContentSchema.extend({
81
157
  id: uuidSchema,
@@ -89,7 +165,9 @@ var taskSchema = taskContentSchema.extend({
89
165
  updatedAt: timestampSchema,
90
166
  waiting: waitingReasonSchema.nullable(),
91
167
  needsVerification: z.boolean(),
92
- needsResponse: z.boolean()
168
+ needsResponse: z.boolean(),
169
+ discussionEndRequested: z.boolean().default(false),
170
+ type: taskTypeSchema.default("implementation")
93
171
  });
94
172
  var attemptSchema = z.strictObject({
95
173
  id: uuidSchema,
@@ -98,7 +176,7 @@ var attemptSchema = z.strictObject({
98
176
  machineName: z.string(),
99
177
  agent: agentSchema,
100
178
  kind: attemptKindSchema,
101
- sessionId: tmuxSessionSchema,
179
+ sessionId: piSessionIdSchema,
102
180
  tmuxSession: tmuxSessionSchema.nullable(),
103
181
  claimedAt: timestampSchema,
104
182
  startedAt: timestampSchema.nullable(),
@@ -181,11 +259,13 @@ z.strictObject({
181
259
  questions: z.array(questionSchema),
182
260
  deliveries: z.array(deliverySchema),
183
261
  attempts: z.array(attemptSchema),
184
- events: z.array(taskEventSchema)
262
+ events: z.array(taskEventSchema),
263
+ sessionOperation: webSessionOperationSchema.optional()
185
264
  });
186
265
  taskContentSchema.partial().required({ title: true }).extend({ projectId: projectIdSchema });
187
- taskContentSchema.partial().extend({ version: z.int().positive() }).refine((input) => Object.keys(input).some((key) => key !== "version"));
266
+ taskContentSchema.omit({ type: true }).partial().extend({ version: z.int().positive() }).refine((input) => Object.keys(input).some((key) => key !== "version"));
188
267
  z.strictObject({ task: taskSchema });
268
+ z.strictObject({ attemptId: uuidSchema });
189
269
  z.strictObject({ deliveryId: uuidSchema }).extend({ feedback: nonEmptyTextSchema });
190
270
  var webMachineSchema = z.strictObject({
191
271
  id: uuidSchema,
@@ -212,6 +292,7 @@ z.strictObject({ machines: z.array(webMachineSchema) });
212
292
  var launcherHeartbeatRequestSchema = requestIdSchema.extend({
213
293
  launcherVersion: z.string().trim().min(1).max(128),
214
294
  slots: slotsSchema,
295
+ sessionControl: z.literal(true).optional(),
215
296
  projects: z.array(z.strictObject({
216
297
  id: projectIdSchema,
217
298
  name: z.string().trim().min(1).max(500),
@@ -223,15 +304,18 @@ var launcherHeartbeatRequestSchema = requestIdSchema.extend({
223
304
  running: z.boolean()
224
305
  })).max(1e3).refine((items) => new Set(items.map(({ id }) => id)).size === items.length)
225
306
  });
226
- var launcherHeartbeatResponseSchema = z.strictObject({ directives: z.array(z.strictObject({
227
- attemptId: uuidSchema,
228
- tmuxSession: tmuxSessionSchema,
229
- action: z.enum([
230
- "continue",
231
- "cancel",
232
- "unknown"
233
- ])
234
- })) });
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
+ });
235
319
  var claimedAttemptSchema = z.strictObject({
236
320
  id: uuidSchema,
237
321
  taskId: uuidSchema,
@@ -240,7 +324,7 @@ var claimedAttemptSchema = z.strictObject({
240
324
  sessionId: tmuxSessionSchema,
241
325
  restoreSession: z.boolean(),
242
326
  displayName: z.string().min(1).max(80),
243
- kind: attemptKindSchema
327
+ kind: z.enum(["new", "rework"])
244
328
  });
245
329
  var launcherClaimResponseSchema = z.strictObject({ attempt: claimedAttemptSchema.nullable() });
246
330
  var launcherStartedRequestSchema = requestIdSchema.extend({
@@ -253,6 +337,17 @@ var launcherExitedRequestSchema = requestIdSchema.extend({
253
337
  });
254
338
  var launcherStartedResponseSchema = okResponseSchema;
255
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 });
256
351
  z.strictObject({
257
352
  task: taskContentSchema.pick({
258
353
  title: true,
@@ -261,7 +356,8 @@ z.strictObject({
261
356
  notes: true
262
357
  }).extend({
263
358
  id: uuidSchema,
264
- projectId: projectIdSchema
359
+ projectId: projectIdSchema,
360
+ type: taskTypeSchema.default("implementation")
265
361
  }),
266
362
  attempt: z.strictObject({
267
363
  id: uuidSchema,
@@ -269,15 +365,31 @@ z.strictObject({
269
365
  }),
270
366
  workspace: z.strictObject({
271
367
  path: z.string(),
272
- 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()
273
375
  }),
274
376
  decisions: z.array(decisionSchema.extend({ confirmedByUser: z.literal(true) })),
275
377
  deliveries: z.array(deliverySchema),
276
378
  questions: z.array(questionSchema.extend({ status: z.literal("open") }))
277
379
  });
380
+ z.strictObject({
381
+ type: taskTypeSchema,
382
+ discussionEndRequested: z.boolean(),
383
+ deliverySaved: z.boolean(),
384
+ waitId: uuidSchema.nullable()
385
+ });
386
+ requestIdSchema.extend({ waitId: uuidSchema });
278
387
  var agentProgressRequestSchema = requestIdSchema.extend({ text: nonEmptyTextSchema });
279
388
  agentProgressRequestSchema.extend({ context: textSchema });
280
- z.strictObject({ questionId: uuidSchema });
389
+ z.strictObject({
390
+ questionId: uuidSchema,
391
+ waitId: uuidSchema.optional()
392
+ });
281
393
  requestIdSchema.extend({ status: z.enum(["resolved", "withdrawn"]) });
282
394
  agentProgressRequestSchema.extend({ confirmedByUser: z.boolean() });
283
395
  deliveryContentSchema.extend(requestIdSchema.shape);
@@ -359,11 +471,12 @@ var editableContent = taskContentSchema.pick({
359
471
  acceptance: true,
360
472
  notes: true
361
473
  });
474
+ var creatableContent = editableContent.extend({ type: taskContentSchema.shape.type });
362
475
  var mutationSource = {
363
476
  requestId: uuidSchema,
364
477
  sessionId: z.string().trim().min(1).max(200)
365
478
  };
366
- editableContent.partial().required({ title: true }).extend({
479
+ creatableContent.partial().required({ title: true }).extend({
367
480
  projectId: projectIdSchema,
368
481
  ...mutationSource
369
482
  });
@@ -551,6 +664,7 @@ async function platformFetch(url, init, proxy = SYSTEM_PROXY) {
551
664
  }
552
665
  // apps/launcher/dist/platform.js
553
666
  var REQUEST_TIMEOUT_MS$1 = 4e3;
667
+ var legacyHeartbeatResponse = launcherHeartbeatResponseSchema.omit({ sessionOperations: true }).strip();
554
668
  var PlatformError = class extends Error {
555
669
  code;
556
670
  startedAlreadySaved;
@@ -600,14 +714,27 @@ function platformClient(config, fetcher, getMachineToken = () => config.machineT
600
714
  }
601
715
  return {
602
716
  claim: (requestId) => post("claim", { requestId }, launcherClaimResponseSchema),
603
- 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),
604
731
  report: (e) => post(`attempts/${e.id}/${e.kind}`, e.body, e.kind === "started" ? launcherStartedResponseSchema : launcherExitedResponseSchema, e.kind === "started")
605
732
  };
606
733
  }
607
734
  // apps/launcher/dist/tmux.js
608
735
  var runFile = promisify(execFile);
609
736
  var escapedTmuxArg = (value) => value.endsWith(";") ? `${value.slice(0, -1)}\\;` : value;
610
- var instructions = "先调用 steward_task 读取完整任务背景。按项目规则和任务授权工作,在关键节点调用 steward_progress。需要用户决定时调用 steward_ask 并等待回应。用 steward_deliver 保存交付,处理完收尾后调用 steward_finish。";
737
+ var instructions = "先调用 steward_task 读取完整任务背景,确认任务类型后再行动。遵守项目规则和任务授权;需要用户回应时调用 steward_ask 并在当前会话等待。实现任务按目标执行和验证,在关键节点调用 steward_progress,完成后调用 steward_deliver 和 steward_finish。讨论任务围绕目标交流,即使已经有结论也不自动收尾;只有收到 Steward 确认的结束请求才整理结论和未决事项、保存交付并退出。";
611
738
  var targetFor = (id) => `steward-${id}`;
612
739
  var tmuxHealthText = {
613
740
  ready: "tmux 可用",
@@ -618,10 +745,23 @@ function commandFailure(error) {
618
745
  return error.code === "ENOENT" ? "missing" : "unavailable";
619
746
  }
620
747
  var TmuxError = class extends Error {
621
- constructor() {
748
+ notStarted;
749
+ constructor(notStarted = false) {
622
750
  super("无法完成 tmux 操作,将在下次循环重新核对。");
751
+ this.notStarted = notStarted;
623
752
  }
624
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
+ }
625
765
  function displayName(title) {
626
766
  return title.replace(/[^\p{L}\p{N} _-]/gu, " ").trim().replace(/^[ -]+/u, "").slice(0, 79).replace(/[\uD800-\uDBFF]$/u, "").trimEnd() || "Pi task";
627
767
  }
@@ -676,6 +816,50 @@ function tmuxClient(config, options) {
676
816
  if (!Array.isArray(sessions)) return "unavailable";
677
817
  return sessions.includes(target) ? "present" : "absent";
678
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
+ },
679
863
  async launch(target, claim, projectPath) {
680
864
  const message = `${claim.kind === "rework" ? "返修本任务。" : "开始执行本任务。"}${instructions}`;
681
865
  try {
@@ -708,6 +892,44 @@ function tmuxClient(config, options) {
708
892
  throw new TmuxError();
709
893
  }
710
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
+ },
711
933
  async cancel(target) {
712
934
  try {
713
935
  await exec([
@@ -721,7 +943,325 @@ function tmuxClient(config, options) {
721
943
  }
722
944
  };
723
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
+ };
724
1263
  // apps/launcher/dist/launcher.js
1264
+ var managedId = (operation) => operation.step === "stop" ? operation.attemptId : operation.replacementId;
725
1265
  var TERMINAL_REPORT_ERRORS = /* @__PURE__ */ new Set([
726
1266
  "attempt_ended",
727
1267
  "forbidden",
@@ -735,8 +1275,19 @@ var Launcher = class {
735
1275
  nextOutboxRetryAt = 0;
736
1276
  outboxBackoff = HEARTBEAT_INTERVAL_MS;
737
1277
  lastTmuxHealth = "ready";
1278
+ control;
738
1279
  constructor(options) {
739
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
+ });
740
1291
  }
741
1292
  get state() {
742
1293
  return this.options.state;
@@ -747,6 +1298,9 @@ var Launcher = class {
747
1298
  now() {
748
1299
  return (this.options.now ?? Date.now)();
749
1300
  }
1301
+ monotonicNow() {
1302
+ return this.options.monotonicNow?.() ?? performance.now();
1303
+ }
750
1304
  async retryable(run) {
751
1305
  try {
752
1306
  return await run();
@@ -756,9 +1310,18 @@ var Launcher = class {
756
1310
  return;
757
1311
  }
758
1312
  }
1313
+ pendingOperationFor(attemptId) {
1314
+ return this.state.sessionOperations?.find(({ replacementId }) => replacementId === attemptId);
1315
+ }
759
1316
  async flush() {
760
1317
  if (this.now() < this.nextOutboxRetryAt) return false;
1318
+ let deferred = false;
761
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
+ }
762
1325
  let confirmed = true;
763
1326
  try {
764
1327
  await this.options.platform.report(event);
@@ -776,10 +1339,10 @@ var Launcher = class {
776
1339
  this.outboxBackoff = HEARTBEAT_INTERVAL_MS;
777
1340
  this.nextOutboxRetryAt = 0;
778
1341
  this.state.outbox = this.state.outbox.filter(({ body }) => body.requestId !== event.body.requestId);
779
- if (event.kind === "exited" && confirmed) this.remove(event.id);
1342
+ if (event.kind === "exited" && confirmed && !operation) this.remove(event.id);
780
1343
  else this.persist();
781
1344
  }
782
- return true;
1345
+ return !deferred;
783
1346
  }
784
1347
  remove(id) {
785
1348
  this.state.executions = this.state.executions.filter((record) => record.id !== id);
@@ -813,6 +1376,24 @@ var Launcher = class {
813
1376
  });
814
1377
  this.persist();
815
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
+ }
816
1397
  async observe() {
817
1398
  const attempts = [];
818
1399
  for (const record of this.state.executions) {
@@ -822,8 +1403,13 @@ var Launcher = class {
822
1403
  this.options.warn?.("tmux 会话核对失败,保留本地尝试。");
823
1404
  continue;
824
1405
  }
825
- if (status === "present") this.started(record);
826
- 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
+ }
827
1413
  attempts.push({
828
1414
  id: record.id,
829
1415
  tmuxSession: record.target,
@@ -834,18 +1420,25 @@ var Launcher = class {
834
1420
  }
835
1421
  async heartbeat() {
836
1422
  const attempts = await this.observe();
1423
+ const requestStartedAt = {
1424
+ wall: this.now(),
1425
+ monotonic: this.monotonicNow()
1426
+ };
837
1427
  const response = await this.retryable(() => this.options.platform.heartbeat({
838
1428
  requestId: randomUUID(),
839
1429
  launcherVersion: this.options.version,
1430
+ sessionControl: true,
840
1431
  slots: this.options.config.slots,
841
1432
  projects: this.options.config.projects,
842
1433
  attempts
843
1434
  }));
844
- if (response) {
845
- this.state.lastHeartbeatAt = this.now();
846
- this.persist();
847
- }
848
- return response;
1435
+ if (!response) return;
1436
+ this.state.lastHeartbeatAt = this.now();
1437
+ this.persist();
1438
+ return {
1439
+ response,
1440
+ requestStartedAt
1441
+ };
849
1442
  }
850
1443
  async startPrepared(record) {
851
1444
  const claim = record.claim;
@@ -883,17 +1476,51 @@ var Launcher = class {
883
1476
  await this.retryable(() => this.options.tmux.cancel(target));
884
1477
  if (await this.options.tmux.inspect(target) !== "absent") return;
885
1478
  }
886
- this.exited(record);
887
- } else if (status === "present") this.started(record);
1479
+ if (this.absenceConfirmed(record)) this.exited(record);
1480
+ } else if (status === "present") await this.observePresent(record);
888
1481
  else if (action === "continue" && record.phase === "prepared") await this.startPrepared(record);
889
- else if (record.phase !== "prepared") this.exited(record);
1482
+ else if (record.phase !== "prepared" && this.absenceConfirmed(record)) this.exited(record);
890
1483
  }
891
- 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);
892
1508
  for (const directive of response.directives) {
1509
+ if (protectedIds.has(directive.attemptId)) continue;
893
1510
  if (claimPending && !this.state.executions.some(({ id }) => id === directive.attemptId)) continue;
894
1511
  await this.applyDirective(directive);
895
1512
  }
896
- 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
+ }
897
1524
  const pending = new Set(this.state.outbox.map(({ id }) => id));
898
1525
  for (const record of [...this.state.executions]) {
899
1526
  if (active.has(record.id)) continue;
@@ -935,7 +1562,11 @@ var Launcher = class {
935
1562
  await this.reconcile(heartbeat, !!this.state.claimRequestId);
936
1563
  if (!flushed || !await this.flush() || replayed) return;
937
1564
  const slots = this.options.config.slots;
938
- 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;
939
1570
  if (!await this.claim()) return;
940
1571
  const afterClaim = await this.heartbeat();
941
1572
  if (!afterClaim) return;
@@ -1181,7 +1812,9 @@ var execution = z.strictObject({
1181
1812
  "exited"
1182
1813
  ]),
1183
1814
  claim: claimedAttemptSchema.optional(),
1184
- startedAt: timestampSchema.optional()
1815
+ startedAt: timestampSchema.optional(),
1816
+ pid: z.int().min(2).max(2147483647).optional(),
1817
+ sessionOperationId: uuidSchema.optional()
1185
1818
  }).refine(({ id, target, phase, claim, startedAt }) => target === `steward-${id}` && (!claim || claim.id === id) && (phase !== "prepared" || !!claim) && (phase !== "launching" || startedAt !== void 0));
1186
1819
  var event = z.discriminatedUnion("kind", [z.strictObject({
1187
1820
  kind: z.literal("started"),
@@ -1192,11 +1825,26 @@ var event = z.discriminatedUnion("kind", [z.strictObject({
1192
1825
  id: uuidSchema,
1193
1826
  body: launcherExitedRequestSchema
1194
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));
1195
1842
  var stateSchema = z.strictObject({
1196
1843
  version: z.literal(1),
1197
1844
  claimRequestId: uuidSchema.optional(),
1198
1845
  lastHeartbeatAt: timestampSchema.optional(),
1199
1846
  executions: z.array(execution),
1847
+ sessionOperations: z.array(sessionOperation).optional(),
1200
1848
  outbox: z.array(event)
1201
1849
  });
1202
1850
  function loadState(path) {