@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/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,9 +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
- var attemptKindSchema = z.enum(["new", "rework"]);
122
+ var taskTypeSchema = z.enum(["discussion", "implementation"]);
123
+ var attemptKindSchema = z.enum([
124
+ "new",
125
+ "rework",
126
+ "resume"
127
+ ]);
50
128
  var attemptResultSchema = z.enum([
51
129
  "delivered",
52
130
  "interrupted",
@@ -71,7 +149,8 @@ var taskContentSchema = z.strictObject({
71
149
  acceptance: textSchema,
72
150
  notes: textSchema,
73
151
  agent: agentSchema,
74
- machineId: uuidSchema.nullable()
152
+ machineId: uuidSchema.nullable(),
153
+ type: taskTypeSchema
75
154
  });
76
155
  var taskSchema = taskContentSchema.extend({
77
156
  id: uuidSchema,
@@ -85,7 +164,9 @@ var taskSchema = taskContentSchema.extend({
85
164
  updatedAt: timestampSchema,
86
165
  waiting: waitingReasonSchema.nullable(),
87
166
  needsVerification: z.boolean(),
88
- needsResponse: z.boolean()
167
+ needsResponse: z.boolean(),
168
+ discussionEndRequested: z.boolean().default(false),
169
+ type: taskTypeSchema.default("implementation")
89
170
  });
90
171
  var attemptSchema = z.strictObject({
91
172
  id: uuidSchema,
@@ -94,7 +175,7 @@ var attemptSchema = z.strictObject({
94
175
  machineName: z.string(),
95
176
  agent: agentSchema,
96
177
  kind: attemptKindSchema,
97
- sessionId: tmuxSessionSchema,
178
+ sessionId: piSessionIdSchema,
98
179
  tmuxSession: tmuxSessionSchema.nullable(),
99
180
  claimedAt: timestampSchema,
100
181
  startedAt: timestampSchema.nullable(),
@@ -177,11 +258,13 @@ var webTaskDetailResponseSchema = z.strictObject({
177
258
  questions: z.array(questionSchema),
178
259
  deliveries: z.array(deliverySchema),
179
260
  attempts: z.array(attemptSchema),
180
- events: z.array(taskEventSchema)
261
+ events: z.array(taskEventSchema),
262
+ sessionOperation: webSessionOperationSchema.optional()
181
263
  });
182
264
  taskContentSchema.partial().required({ title: true }).extend({ projectId: projectIdSchema });
183
- taskContentSchema.partial().extend({ version: z.int().positive() }).refine((input) => Object.keys(input).some((key) => key !== "version"));
265
+ taskContentSchema.omit({ type: true }).partial().extend({ version: z.int().positive() }).refine((input) => Object.keys(input).some((key) => key !== "version"));
184
266
  var webTaskMutationResponseSchema = z.strictObject({ task: taskSchema });
267
+ z.strictObject({ attemptId: uuidSchema });
185
268
  z.strictObject({ deliveryId: uuidSchema }).extend({ feedback: nonEmptyTextSchema });
186
269
  var webMachineSchema = z.strictObject({
187
270
  id: uuidSchema,
@@ -208,6 +291,7 @@ z.strictObject({ machines: z.array(webMachineSchema) });
208
291
  var launcherHeartbeatRequestSchema = requestIdSchema.extend({
209
292
  launcherVersion: z.string().trim().min(1).max(128),
210
293
  slots: slotsSchema,
294
+ sessionControl: z.literal(true).optional(),
211
295
  projects: z.array(z.strictObject({
212
296
  id: projectIdSchema,
213
297
  name: z.string().trim().min(1).max(500),
@@ -219,15 +303,18 @@ var launcherHeartbeatRequestSchema = requestIdSchema.extend({
219
303
  running: z.boolean()
220
304
  })).max(1e3).refine((items) => new Set(items.map(({ id }) => id)).size === items.length)
221
305
  });
222
- z.strictObject({ directives: z.array(z.strictObject({
223
- attemptId: uuidSchema,
224
- tmuxSession: tmuxSessionSchema,
225
- action: z.enum([
226
- "continue",
227
- "cancel",
228
- "unknown"
229
- ])
230
- })) });
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
+ });
231
318
  var claimedAttemptSchema = z.strictObject({
232
319
  id: uuidSchema,
233
320
  taskId: uuidSchema,
@@ -236,7 +323,7 @@ var claimedAttemptSchema = z.strictObject({
236
323
  sessionId: tmuxSessionSchema,
237
324
  restoreSession: z.boolean(),
238
325
  displayName: z.string().min(1).max(80),
239
- kind: attemptKindSchema
326
+ kind: z.enum(["new", "rework"])
240
327
  });
241
328
  z.strictObject({ attempt: claimedAttemptSchema.nullable() });
242
329
  requestIdSchema.extend({
@@ -248,6 +335,16 @@ requestIdSchema.extend({
248
335
  endedAt: timestampSchema
249
336
  });
250
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 });
251
348
  var agentContextResponseSchema = z.strictObject({
252
349
  task: taskContentSchema.pick({
253
350
  title: true,
@@ -256,7 +353,8 @@ var agentContextResponseSchema = z.strictObject({
256
353
  notes: true
257
354
  }).extend({
258
355
  id: uuidSchema,
259
- projectId: projectIdSchema
356
+ projectId: projectIdSchema,
357
+ type: taskTypeSchema.default("implementation")
260
358
  }),
261
359
  attempt: z.strictObject({
262
360
  id: uuidSchema,
@@ -264,16 +362,32 @@ var agentContextResponseSchema = z.strictObject({
264
362
  }),
265
363
  workspace: z.strictObject({
266
364
  path: z.string(),
267
- 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()
268
372
  }),
269
373
  decisions: z.array(decisionSchema.extend({ confirmedByUser: z.literal(true) })),
270
374
  deliveries: z.array(deliverySchema),
271
375
  questions: z.array(questionSchema.extend({ status: z.literal("open") }))
272
376
  });
377
+ var agentControlResponseSchema = z.strictObject({
378
+ type: taskTypeSchema,
379
+ discussionEndRequested: z.boolean(),
380
+ deliverySaved: z.boolean(),
381
+ waitId: uuidSchema.nullable()
382
+ });
383
+ requestIdSchema.extend({ waitId: uuidSchema });
273
384
  var agentProgressRequestSchema = requestIdSchema.extend({ text: nonEmptyTextSchema });
274
385
  var agentProgressResponseSchema = okResponseSchema;
275
386
  var agentCreateQuestionRequestSchema = agentProgressRequestSchema.extend({ context: textSchema });
276
- var agentCreateQuestionResponseSchema = z.strictObject({ questionId: uuidSchema });
387
+ var agentCreateQuestionResponseSchema = z.strictObject({
388
+ questionId: uuidSchema,
389
+ waitId: uuidSchema.optional()
390
+ });
277
391
  var agentUpdateQuestionRequestSchema = requestIdSchema.extend({ status: z.enum(["resolved", "withdrawn"]) });
278
392
  var agentUpdateQuestionResponseSchema = okResponseSchema;
279
393
  var agentDecisionRequestSchema = agentProgressRequestSchema.extend({ confirmedByUser: z.boolean() });
@@ -358,11 +472,12 @@ var editableContent = taskContentSchema.pick({
358
472
  acceptance: true,
359
473
  notes: true
360
474
  });
475
+ var creatableContent = editableContent.extend({ type: taskContentSchema.shape.type });
361
476
  var mutationSource = {
362
477
  requestId: uuidSchema,
363
478
  sessionId: z.string().trim().min(1).max(200)
364
479
  };
365
- var managedCreateTaskRequestSchema = editableContent.partial().required({ title: true }).extend({
480
+ var managedCreateTaskRequestSchema = creatableContent.partial().required({ title: true }).extend({
366
481
  projectId: projectIdSchema,
367
482
  ...mutationSource
368
483
  });
@@ -573,6 +688,198 @@ function validatedBody(schema, body) {
573
688
  if (!parsed.success) throw new AgentError("invalid_request");
574
689
  return parsed.data;
575
690
  }
691
+ // packages/pi-extension/dist/attempt-control.js
692
+ var POLL_MS = 5e3;
693
+ var CLOSE_RETRY_MS = 3e4;
694
+ var MAX_CLOSE_TURNS = 3;
695
+ var CONTROL_ENTRY = "steward-attempt-control";
696
+ var closeInput = /^(?:请\s*)?结束讨论[。.!!]?$/u;
697
+ var pendingSchema = requestIdSchema.extend({ waitId: uuidSchema.nullable() });
698
+ function registerAttemptControl(pi, attemptId, request) {
699
+ let control;
700
+ let taskType;
701
+ let pendingReply;
702
+ let pendingEnd;
703
+ let uncertainWait = true;
704
+ let closingTurns = 0;
705
+ let nextClosingAt = 0;
706
+ let shutdownRequested = false;
707
+ let context;
708
+ let lifetime;
709
+ let timer;
710
+ let operations = Promise.resolve();
711
+ function serial(run) {
712
+ const next = operations.then(run);
713
+ operations = next.then(() => void 0, () => void 0);
714
+ return next;
715
+ }
716
+ function remember() {
717
+ if (context) pi.appendEntry(CONTROL_ENTRY, {
718
+ attemptId,
719
+ pendingReply,
720
+ pendingEnd
721
+ });
722
+ }
723
+ async function read(signal) {
724
+ const next = await request("GET", "control", agentControlResponseSchema, void 0, signal);
725
+ if (signal?.aborted) return next;
726
+ control = next;
727
+ taskType = next.type;
728
+ uncertainWait = false;
729
+ return next;
730
+ }
731
+ async function flushReply(signal) {
732
+ if (!pendingReply) return;
733
+ if (pendingReply.waitId === null) {
734
+ pendingReply.waitId = (uncertainWait || !control ? await read(signal) : control).waitId;
735
+ if (signal?.aborted) return;
736
+ remember();
737
+ }
738
+ if (pendingReply.waitId !== null) await request("POST", "reply", okResponseSchema, {
739
+ requestId: pendingReply.requestId,
740
+ waitId: pendingReply.waitId
741
+ }, signal);
742
+ if (signal?.aborted) return;
743
+ if (control && control.waitId === pendingReply.waitId) control = {
744
+ ...control,
745
+ waitId: null
746
+ };
747
+ pendingReply = void 0;
748
+ remember();
749
+ }
750
+ function finish(ctx) {
751
+ if (shutdownRequested) return;
752
+ shutdownRequested = true;
753
+ ctx.shutdown();
754
+ }
755
+ function startClosingTurn(ctx) {
756
+ if (control?.type !== "discussion" || !control.discussionEndRequested || !ctx.isIdle() || Date.now() < nextClosingAt) return;
757
+ if (closingTurns >= MAX_CLOSE_TURNS) {
758
+ if (closingTurns === MAX_CLOSE_TURNS) {
759
+ closingTurns++;
760
+ if (ctx.hasUI) ctx.ui.notify("讨论结论还未保存。请检查本轮结果,或再次发送「结束讨论」重试。", "warning");
761
+ }
762
+ return;
763
+ }
764
+ closingTurns++;
765
+ nextClosingAt = Date.now() + CLOSE_RETRY_MS;
766
+ pi.sendMessage({
767
+ customType: "steward-end-discussion",
768
+ display: true,
769
+ content: "用户已请求结束讨论。基于本次会话整理简短结论和未决事项,用 steward_deliver 保存(结论写在 summary 或 done,未决事项写在 issues)。不要继续执行未决事项;不要取消或验收任务。保存确认后调用 steward_finish。"
770
+ }, {
771
+ triggerTurn: true,
772
+ deliverAs: "followUp"
773
+ });
774
+ }
775
+ async function flushEnd(signal) {
776
+ if (!pendingEnd || !taskType) return;
777
+ if (taskType === "discussion") {
778
+ await request("POST", "end-discussion", okResponseSchema, { requestId: pendingEnd }, signal);
779
+ if (signal?.aborted) return;
780
+ if (control) control = {
781
+ ...control,
782
+ discussionEndRequested: true
783
+ };
784
+ }
785
+ pendingEnd = void 0;
786
+ remember();
787
+ }
788
+ async function sync(ctx, signal) {
789
+ if (signal.aborted || shutdownRequested) return;
790
+ try {
791
+ const state = await read(signal);
792
+ if (signal.aborted) return;
793
+ await flushEnd(signal);
794
+ await flushReply(signal);
795
+ if (signal.aborted) return;
796
+ if (state.type === "discussion" && control?.discussionEndRequested && state.deliverySaved && ctx.isIdle()) finish(ctx);
797
+ else if (!state.deliverySaved) startClosingTurn(ctx);
798
+ } catch (error) {
799
+ if (error instanceof AgentError && error.code === "attempt_ended" && !signal.aborted) lifetime?.abort();
800
+ }
801
+ }
802
+ pi.on("session_start", (_event, ctx) => {
803
+ context = ctx;
804
+ const controller = new AbortController();
805
+ lifetime = controller;
806
+ for (const entry of ctx.sessionManager.getEntries().toReversed()) {
807
+ if (entry.type !== "custom" || entry.customType !== CONTROL_ENTRY) continue;
808
+ const saved = entry.data;
809
+ if (saved?.attemptId !== attemptId) continue;
810
+ const reply = pendingSchema.safeParse(saved.pendingReply);
811
+ const end = uuidSchema.safeParse(saved.pendingEnd);
812
+ pendingReply = reply.success ? reply.data : void 0;
813
+ pendingEnd = end.success ? end.data : void 0;
814
+ break;
815
+ }
816
+ async function poll() {
817
+ await serial(() => sync(ctx, controller.signal));
818
+ if (!controller.signal.aborted && !shutdownRequested) timer = setTimeout(() => void poll(), POLL_MS).unref();
819
+ }
820
+ poll();
821
+ });
822
+ pi.on("session_shutdown", () => {
823
+ lifetime?.abort();
824
+ clearTimeout(timer);
825
+ context = void 0;
826
+ });
827
+ pi.on("input", async (event) => {
828
+ if (!event.text.trim() && !event.images?.length) return;
829
+ const end = closeInput.test(event.text.trim());
830
+ const signal = lifetime?.signal;
831
+ const operation = serial(async () => {
832
+ if (signal?.aborted) return;
833
+ if (end && taskType !== "implementation") {
834
+ pendingEnd ??= randomUUID();
835
+ closingTurns = 0;
836
+ nextClosingAt = 0;
837
+ remember();
838
+ await flushEnd(signal);
839
+ return;
840
+ }
841
+ if ((uncertainWait || control?.waitId) && !pendingReply) {
842
+ pendingReply = {
843
+ requestId: randomUUID(),
844
+ waitId: uncertainWait ? null : control?.waitId ?? null
845
+ };
846
+ remember();
847
+ }
848
+ await flushReply(signal);
849
+ }).catch(() => void 0);
850
+ if (end) await operation;
851
+ });
852
+ pi.on("before_agent_start", (event) => {
853
+ event.systemPromptOptions.promptGuidelines.push("Steward:需要用户回答明确问题时调用 steward_ask,再在原 Pi 会话提问并等待;普通对话不要调用该工具。", "若 steward_task 显示讨论(discussion),只围绕讨论目标交流;普通回合结束、没有回复或已经形成结论,都不交付也不退出。只有收到 Steward 已确认的结束请求才整理简短结论与未决事项、交付并退出。");
854
+ if (control?.type === "discussion" && control.discussionEndRequested) event.systemPromptOptions.promptGuidelines.push("Steward 已确认用户请求结束本次讨论。现在整理简短结论与未决事项,用 steward_deliver 保存(未决事项写在 issues),确认后调用 steward_finish,不继续执行未决事项。");
855
+ });
856
+ return {
857
+ finish,
858
+ get deliverySaved() {
859
+ return control?.deliverySaved === true;
860
+ },
861
+ noteTaskType(type) {
862
+ taskType = type;
863
+ },
864
+ ask(send, signal) {
865
+ return serial(async () => {
866
+ await flushReply(signal);
867
+ try {
868
+ const asked = await send();
869
+ if (asked.waitId && control) control = {
870
+ ...control,
871
+ waitId: asked.waitId
872
+ };
873
+ uncertainWait = !asked.waitId || !control;
874
+ return asked;
875
+ } catch (error) {
876
+ uncertainWait = true;
877
+ throw error;
878
+ }
879
+ });
880
+ }
881
+ };
882
+ }
576
883
  // packages/pi-extension/dist/retry-writes.js
577
884
  var MAX_PENDING_WRITES = 128;
578
885
  var UNCERTAIN_RESULT = /* @__PURE__ */ new Set([
@@ -613,6 +920,206 @@ function retryableWrites({ cancelledMayHaveSaved = false } = {}) {
613
920
  return inFlight;
614
921
  };
615
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
+ }
616
1123
  // packages/pi-extension/dist/index.js
617
1124
  var text = () => Type.String({ maxLength: 1e5 });
618
1125
  var lines = () => Type.Array(text());
@@ -642,7 +1149,7 @@ async function report(run) {
642
1149
  return result(JSON.stringify(data), data);
643
1150
  } catch (error) {
644
1151
  const code = error instanceof AgentError ? error.code : "request_failed";
645
- 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 });
646
1153
  }
647
1154
  }
648
1155
  var editableTask = {
@@ -685,14 +1192,15 @@ function registerTaskManagement(pi, options) {
685
1192
  pi.registerTool({
686
1193
  name: "steward_create_task",
687
1194
  label: "新建 Steward 待办",
688
- description: "应用户要求新建待办,不安排执行。网络请求结果未知时使用原参数重试。",
1195
+ description: "应用户要求新建待办,不安排执行。选择 discussion(讨论)或 implementation(实现,默认)。网络请求结果未知时使用原参数重试。",
689
1196
  parameters: Type.Object({
690
1197
  ...editableTask,
691
1198
  projectId: projectIdParameter,
692
1199
  title: Type.String({
693
1200
  minLength: 1,
694
1201
  maxLength: 500
695
- })
1202
+ }),
1203
+ type: Type.Optional(Type.Union([Type.Literal("discussion"), Type.Literal("implementation")]))
696
1204
  }),
697
1205
  execute: (_id, args, signal, _update, ctx) => report(() => {
698
1206
  const input = {
@@ -734,17 +1242,49 @@ function deliveryId(attemptId) {
734
1242
  function registerSteward(pi, options = { env: process.env }) {
735
1243
  registerTaskManagement(pi, options);
736
1244
  const attempt = uuidSchema.safeParse(options.env.STEWARD_ATTEMPT_ID);
1245
+ registerTaskSession(pi, attempt.success);
737
1246
  if (!attempt.success) return;
738
1247
  const request = agentClient(attempt.data, options);
1248
+ registerSessionReport(pi, request, options.env.STEWARD_RESUME === "1");
1249
+ const control = registerAttemptControl(pi, attempt.data, request);
739
1250
  const write = retryableWrites();
740
1251
  const requestId = deliveryId(attempt.data);
741
1252
  let delivered = false;
1253
+ let taskContext;
742
1254
  pi.registerTool({
743
1255
  name: "steward_task",
744
1256
  label: "读取 Steward 任务",
745
- description: "读取本次任务的目标、验收要求、决定、交付与返修反馈。",
1257
+ description: "读取本次任务的目标、验收要求、决定、交付、返修反馈及工作现场核对结果。",
746
1258
  parameters: Type.Object({}),
747
- execute: (_id, _args, signal) => report(() => request("GET", "context", agentContextResponseSchema, void 0, signal))
1259
+ execute: (_id, _args, signal, _update, ctx) => report(async () => {
1260
+ taskContext = void 0;
1261
+ const data = await request("GET", "context", agentContextResponseSchema, void 0, signal);
1262
+ control.noteTaskType(data.task.type);
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
+ };
1287
+ })
748
1288
  });
749
1289
  pi.registerTool({
750
1290
  name: "steward_progress",
@@ -764,10 +1304,10 @@ function registerSteward(pi, options = { env: process.env }) {
764
1304
  text: text(),
765
1305
  context: text()
766
1306
  }),
767
- execute: (_id, args, signal) => report(() => write("POST", "questions", args, (id) => request("POST", "questions", agentCreateQuestionResponseSchema, validatedBody(agentCreateQuestionRequestSchema, {
1307
+ execute: (_id, args, signal) => report(() => control.ask(() => write("POST", "questions", args, (id) => request("POST", "questions", agentCreateQuestionResponseSchema, validatedBody(agentCreateQuestionRequestSchema, {
768
1308
  ...args,
769
1309
  requestId: id
770
- }), signal)))
1310
+ }), signal)), signal))
771
1311
  });
772
1312
  pi.registerTool({
773
1313
  name: "steward_question_update",
@@ -818,8 +1358,8 @@ function registerSteward(pi, options = { env: process.env }) {
818
1358
  description: "交付已确认保存且本次执行已收尾时,请求 Pi 结束。",
819
1359
  parameters: Type.Object({}),
820
1360
  async execute(_id, _args, _signal, _update, ctx) {
821
- if (!delivered) return result("尚未确认保存交付,不能结束。若用户要放弃任务,请用户在平台取消或在 Pi 中直接退出。", { code: "delivery_required" });
822
- ctx.shutdown();
1361
+ if (!delivered && !control.deliverySaved) return result("尚未确认保存交付,不能结束。若用户要放弃任务,请用户在平台取消或在 Pi 中直接退出。", { code: "delivery_required" });
1362
+ control.finish(ctx);
823
1363
  return result("已请求 Pi 在本轮结束后退出。", { ok: true });
824
1364
  }
825
1365
  });