@yefengr/steward 0.0.0-stage → 0.1.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 +573 -0
- package/dist/index.js +1242 -0
- package/package.json +20 -4
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1242 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
3
|
+
import { accessSync, closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir, hostname } from "node:os";
|
|
5
|
+
import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
6
|
+
import { setTimeout } from "node:timers/promises";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { parseArgs, promisify } from "node:util";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
11
|
+
import { DatabaseSync } from "node:sqlite";
|
|
12
|
+
// packages/contract/dist/core.js
|
|
13
|
+
var taskStatusSchema = z.enum([
|
|
14
|
+
"unscheduled",
|
|
15
|
+
"queued",
|
|
16
|
+
"running",
|
|
17
|
+
"review",
|
|
18
|
+
"done",
|
|
19
|
+
"interrupted",
|
|
20
|
+
"cancelled"
|
|
21
|
+
]);
|
|
22
|
+
var agentSchema = z.enum(["pi", "claude"]);
|
|
23
|
+
var errorCodeSchema = z.enum([
|
|
24
|
+
"unauthorized",
|
|
25
|
+
"forbidden",
|
|
26
|
+
"not_found",
|
|
27
|
+
"invalid_request",
|
|
28
|
+
"conflict",
|
|
29
|
+
"machine_required",
|
|
30
|
+
"attempt_ended",
|
|
31
|
+
"rate_limited",
|
|
32
|
+
"internal_error"
|
|
33
|
+
]);
|
|
34
|
+
var errorResponseSchema = z.strictObject({ error: z.strictObject({
|
|
35
|
+
code: errorCodeSchema,
|
|
36
|
+
message: z.string()
|
|
37
|
+
}) });
|
|
38
|
+
var uuidSchema = z.uuid();
|
|
39
|
+
var projectIdSchema = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/);
|
|
40
|
+
var timestampSchema = z.int().nonnegative();
|
|
41
|
+
var textSchema = z.string().max(1e5);
|
|
42
|
+
var nonEmptyTextSchema = textSchema.refine((value) => value.trim().length > 0);
|
|
43
|
+
var machineTokenSchema = z.string().regex(/^stm_[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/);
|
|
44
|
+
var tmuxSessionSchema = z.string().startsWith("steward-").refine((value) => uuidSchema.safeParse(value.slice(8)).success);
|
|
45
|
+
z.strictObject({});
|
|
46
|
+
var okResponseSchema = z.strictObject({ ok: z.literal(true) });
|
|
47
|
+
var requestIdSchema = z.strictObject({ requestId: uuidSchema });
|
|
48
|
+
var HEARTBEAT_INTERVAL_MS = 15e3;
|
|
49
|
+
// packages/contract/dist/models.js
|
|
50
|
+
var titleSchema = z.string().trim().min(1).max(500);
|
|
51
|
+
var attemptKindSchema = z.enum(["new", "rework"]);
|
|
52
|
+
var attemptResultSchema = z.enum([
|
|
53
|
+
"delivered",
|
|
54
|
+
"interrupted",
|
|
55
|
+
"cancelled"
|
|
56
|
+
]);
|
|
57
|
+
var waitingReasonSchema = z.enum([
|
|
58
|
+
"previous_attempt_active",
|
|
59
|
+
"machine_unassigned",
|
|
60
|
+
"machine_project_unregistered",
|
|
61
|
+
"machine_offline",
|
|
62
|
+
"slots_full"
|
|
63
|
+
]);
|
|
64
|
+
var questionStatusSchema = z.enum([
|
|
65
|
+
"open",
|
|
66
|
+
"resolved",
|
|
67
|
+
"withdrawn"
|
|
68
|
+
]);
|
|
69
|
+
var slotsSchema = z.int().min(0).max(1e3);
|
|
70
|
+
var taskContentSchema = z.strictObject({
|
|
71
|
+
title: titleSchema,
|
|
72
|
+
goal: textSchema,
|
|
73
|
+
acceptance: textSchema,
|
|
74
|
+
notes: textSchema,
|
|
75
|
+
agent: agentSchema,
|
|
76
|
+
machineId: uuidSchema.nullable()
|
|
77
|
+
});
|
|
78
|
+
var taskSchema = taskContentSchema.extend({
|
|
79
|
+
id: uuidSchema,
|
|
80
|
+
projectId: projectIdSchema,
|
|
81
|
+
status: taskStatusSchema,
|
|
82
|
+
reworkPending: z.boolean(),
|
|
83
|
+
position: z.int().positive(),
|
|
84
|
+
createdBy: z.enum(["user", "agent"]),
|
|
85
|
+
version: z.int().positive(),
|
|
86
|
+
createdAt: timestampSchema,
|
|
87
|
+
updatedAt: timestampSchema,
|
|
88
|
+
waiting: waitingReasonSchema.nullable(),
|
|
89
|
+
needsVerification: z.boolean(),
|
|
90
|
+
needsResponse: z.boolean()
|
|
91
|
+
});
|
|
92
|
+
var attemptSchema = z.strictObject({
|
|
93
|
+
id: uuidSchema,
|
|
94
|
+
taskId: uuidSchema,
|
|
95
|
+
machineId: uuidSchema,
|
|
96
|
+
machineName: z.string(),
|
|
97
|
+
agent: agentSchema,
|
|
98
|
+
kind: attemptKindSchema,
|
|
99
|
+
sessionId: tmuxSessionSchema,
|
|
100
|
+
tmuxSession: tmuxSessionSchema.nullable(),
|
|
101
|
+
claimedAt: timestampSchema,
|
|
102
|
+
startedAt: timestampSchema.nullable(),
|
|
103
|
+
leaseExpiresAt: timestampSchema,
|
|
104
|
+
cancelRequested: z.boolean(),
|
|
105
|
+
endedAt: timestampSchema.nullable(),
|
|
106
|
+
exitCode: z.int().nullable(),
|
|
107
|
+
result: attemptResultSchema.nullable(),
|
|
108
|
+
needsVerification: z.boolean()
|
|
109
|
+
});
|
|
110
|
+
var deliveryContentSchema = z.strictObject({
|
|
111
|
+
summary: nonEmptyTextSchema,
|
|
112
|
+
done: z.array(textSchema),
|
|
113
|
+
notCovered: z.array(textSchema),
|
|
114
|
+
verification: z.array(textSchema),
|
|
115
|
+
howTo: z.array(textSchema),
|
|
116
|
+
issues: z.array(textSchema),
|
|
117
|
+
baseCommit: textSchema.optional(),
|
|
118
|
+
commit: textSchema.optional(),
|
|
119
|
+
reportRef: textSchema.optional()
|
|
120
|
+
});
|
|
121
|
+
var deliverySchema = deliveryContentSchema.extend({
|
|
122
|
+
id: uuidSchema,
|
|
123
|
+
taskId: uuidSchema,
|
|
124
|
+
attemptId: uuidSchema,
|
|
125
|
+
version: z.int().positive(),
|
|
126
|
+
review: z.enum(["accepted", "rework"]).nullable(),
|
|
127
|
+
feedback: textSchema.nullable(),
|
|
128
|
+
reviewedAt: timestampSchema.nullable(),
|
|
129
|
+
createdAt: timestampSchema
|
|
130
|
+
});
|
|
131
|
+
var decisionSchema = z.strictObject({
|
|
132
|
+
id: uuidSchema,
|
|
133
|
+
taskId: uuidSchema,
|
|
134
|
+
attemptId: uuidSchema.nullable(),
|
|
135
|
+
text: nonEmptyTextSchema,
|
|
136
|
+
confirmedByUser: z.boolean(),
|
|
137
|
+
createdAt: timestampSchema
|
|
138
|
+
});
|
|
139
|
+
var progressSchema = z.strictObject({
|
|
140
|
+
id: uuidSchema,
|
|
141
|
+
taskId: uuidSchema,
|
|
142
|
+
attemptId: uuidSchema,
|
|
143
|
+
text: nonEmptyTextSchema,
|
|
144
|
+
createdAt: timestampSchema
|
|
145
|
+
});
|
|
146
|
+
var questionSchema = progressSchema.extend({
|
|
147
|
+
context: textSchema,
|
|
148
|
+
status: questionStatusSchema,
|
|
149
|
+
updatedAt: timestampSchema
|
|
150
|
+
});
|
|
151
|
+
var taskEventSchema = z.strictObject({
|
|
152
|
+
id: uuidSchema,
|
|
153
|
+
taskId: uuidSchema,
|
|
154
|
+
attemptId: uuidSchema.nullable(),
|
|
155
|
+
actor: z.enum([
|
|
156
|
+
"user",
|
|
157
|
+
"launcher",
|
|
158
|
+
"agent"
|
|
159
|
+
]),
|
|
160
|
+
kind: z.string(),
|
|
161
|
+
payload: z.record(z.string(), z.json()),
|
|
162
|
+
createdAt: timestampSchema
|
|
163
|
+
});
|
|
164
|
+
z.strictObject({ password: z.string().min(1).max(1024) });
|
|
165
|
+
z.strictObject({ authenticated: z.boolean() });
|
|
166
|
+
var webProjectSchema = z.strictObject({
|
|
167
|
+
id: projectIdSchema,
|
|
168
|
+
name: z.string(),
|
|
169
|
+
lastMachineId: uuidSchema.nullable(),
|
|
170
|
+
createdAt: timestampSchema,
|
|
171
|
+
counts: z.record(taskStatusSchema, z.int().nonnegative())
|
|
172
|
+
});
|
|
173
|
+
z.strictObject({ projects: z.array(webProjectSchema) });
|
|
174
|
+
z.strictObject({ tasks: z.array(taskSchema) });
|
|
175
|
+
z.strictObject({
|
|
176
|
+
task: taskSchema,
|
|
177
|
+
decisions: z.array(decisionSchema),
|
|
178
|
+
progress: z.array(progressSchema),
|
|
179
|
+
questions: z.array(questionSchema),
|
|
180
|
+
deliveries: z.array(deliverySchema),
|
|
181
|
+
attempts: z.array(attemptSchema),
|
|
182
|
+
events: z.array(taskEventSchema)
|
|
183
|
+
});
|
|
184
|
+
taskContentSchema.partial().required({ title: true }).extend({ projectId: projectIdSchema });
|
|
185
|
+
taskContentSchema.partial().extend({ version: z.int().positive() }).refine((input) => Object.keys(input).some((key) => key !== "version"));
|
|
186
|
+
z.strictObject({ task: taskSchema });
|
|
187
|
+
z.strictObject({ deliveryId: uuidSchema }).extend({ feedback: nonEmptyTextSchema });
|
|
188
|
+
var webMachineSchema = z.strictObject({
|
|
189
|
+
id: uuidSchema,
|
|
190
|
+
name: z.string(),
|
|
191
|
+
online: z.boolean(),
|
|
192
|
+
slots: slotsSchema,
|
|
193
|
+
occupiedSlots: z.int().nonnegative(),
|
|
194
|
+
lastSeenAt: timestampSchema.nullable(),
|
|
195
|
+
launcherVersion: z.string().nullable(),
|
|
196
|
+
revokedAt: timestampSchema.nullable(),
|
|
197
|
+
projects: z.array(z.strictObject({
|
|
198
|
+
id: projectIdSchema,
|
|
199
|
+
name: z.string()
|
|
200
|
+
})),
|
|
201
|
+
activeTasks: z.array(z.strictObject({
|
|
202
|
+
id: uuidSchema,
|
|
203
|
+
projectId: projectIdSchema,
|
|
204
|
+
title: z.string(),
|
|
205
|
+
attemptId: uuidSchema
|
|
206
|
+
}))
|
|
207
|
+
});
|
|
208
|
+
z.strictObject({ machines: z.array(webMachineSchema) });
|
|
209
|
+
// packages/contract/dist/launcher.js
|
|
210
|
+
var launcherHeartbeatRequestSchema = requestIdSchema.extend({
|
|
211
|
+
launcherVersion: z.string().trim().min(1).max(128),
|
|
212
|
+
slots: slotsSchema,
|
|
213
|
+
projects: z.array(z.strictObject({
|
|
214
|
+
id: projectIdSchema,
|
|
215
|
+
name: z.string().trim().min(1).max(500),
|
|
216
|
+
path: z.string().max(4096).regex(/^\/[^\0]*$/)
|
|
217
|
+
})).max(1e3).refine((items) => new Set(items.map(({ id }) => id)).size === items.length),
|
|
218
|
+
attempts: z.array(z.strictObject({
|
|
219
|
+
id: uuidSchema,
|
|
220
|
+
tmuxSession: tmuxSessionSchema,
|
|
221
|
+
running: z.boolean()
|
|
222
|
+
})).max(1e3).refine((items) => new Set(items.map(({ id }) => id)).size === items.length)
|
|
223
|
+
});
|
|
224
|
+
var launcherHeartbeatResponseSchema = z.strictObject({ directives: z.array(z.strictObject({
|
|
225
|
+
attemptId: uuidSchema,
|
|
226
|
+
tmuxSession: tmuxSessionSchema,
|
|
227
|
+
action: z.enum([
|
|
228
|
+
"continue",
|
|
229
|
+
"cancel",
|
|
230
|
+
"unknown"
|
|
231
|
+
])
|
|
232
|
+
})) });
|
|
233
|
+
var claimedAttemptSchema = z.strictObject({
|
|
234
|
+
id: uuidSchema,
|
|
235
|
+
taskId: uuidSchema,
|
|
236
|
+
projectId: projectIdSchema,
|
|
237
|
+
agent: z.literal("pi"),
|
|
238
|
+
sessionId: tmuxSessionSchema,
|
|
239
|
+
restoreSession: z.boolean(),
|
|
240
|
+
displayName: z.string().min(1).max(80),
|
|
241
|
+
kind: attemptKindSchema
|
|
242
|
+
});
|
|
243
|
+
var launcherClaimResponseSchema = z.strictObject({ attempt: claimedAttemptSchema.nullable() });
|
|
244
|
+
var launcherStartedRequestSchema = requestIdSchema.extend({
|
|
245
|
+
tmuxSession: tmuxSessionSchema,
|
|
246
|
+
startedAt: timestampSchema
|
|
247
|
+
});
|
|
248
|
+
var launcherExitedRequestSchema = requestIdSchema.extend({
|
|
249
|
+
exitCode: z.int().nullable(),
|
|
250
|
+
endedAt: timestampSchema
|
|
251
|
+
});
|
|
252
|
+
var launcherStartedResponseSchema = okResponseSchema;
|
|
253
|
+
var launcherExitedResponseSchema = okResponseSchema;
|
|
254
|
+
z.strictObject({
|
|
255
|
+
task: taskContentSchema.pick({
|
|
256
|
+
title: true,
|
|
257
|
+
goal: true,
|
|
258
|
+
acceptance: true,
|
|
259
|
+
notes: true
|
|
260
|
+
}).extend({
|
|
261
|
+
id: uuidSchema,
|
|
262
|
+
projectId: projectIdSchema
|
|
263
|
+
}),
|
|
264
|
+
attempt: z.strictObject({
|
|
265
|
+
id: uuidSchema,
|
|
266
|
+
kind: attemptKindSchema
|
|
267
|
+
}),
|
|
268
|
+
workspace: z.strictObject({
|
|
269
|
+
path: z.string(),
|
|
270
|
+
requirements: z.array(nonEmptyTextSchema)
|
|
271
|
+
}),
|
|
272
|
+
decisions: z.array(decisionSchema.extend({ confirmedByUser: z.literal(true) })),
|
|
273
|
+
deliveries: z.array(deliverySchema),
|
|
274
|
+
questions: z.array(questionSchema.extend({ status: z.literal("open") }))
|
|
275
|
+
});
|
|
276
|
+
var agentProgressRequestSchema = requestIdSchema.extend({ text: nonEmptyTextSchema });
|
|
277
|
+
agentProgressRequestSchema.extend({ context: textSchema });
|
|
278
|
+
z.strictObject({ questionId: uuidSchema });
|
|
279
|
+
requestIdSchema.extend({ status: z.enum(["resolved", "withdrawn"]) });
|
|
280
|
+
agentProgressRequestSchema.extend({ confirmedByUser: z.boolean() });
|
|
281
|
+
deliveryContentSchema.extend(requestIdSchema.shape);
|
|
282
|
+
z.strictObject({
|
|
283
|
+
deliveryId: uuidSchema,
|
|
284
|
+
version: z.int().positive()
|
|
285
|
+
});
|
|
286
|
+
// packages/contract/dist/local-config.js
|
|
287
|
+
var absolutePath = z.string().max(4096).regex(/^\/[^\0]*$/);
|
|
288
|
+
var tmuxArgument = z.string().max(4096).refine((arg) => !arg.includes("\0") && !arg.endsWith(";"));
|
|
289
|
+
var localConfigSchema = z.strictObject({
|
|
290
|
+
platformUrl: z.url(),
|
|
291
|
+
allowHttpLoopback: z.literal(true).optional(),
|
|
292
|
+
machineToken: machineTokenSchema,
|
|
293
|
+
slots: slotsSchema,
|
|
294
|
+
projects: launcherHeartbeatRequestSchema.shape.projects,
|
|
295
|
+
pi: z.strictObject({
|
|
296
|
+
command: tmuxArgument.pipe(z.string().min(1)),
|
|
297
|
+
extraArgs: z.array(tmuxArgument).max(64)
|
|
298
|
+
}),
|
|
299
|
+
path: z.array(absolutePath.refine((path) => !path.includes(":"))).min(1).max(128)
|
|
300
|
+
}).refine(({ platformUrl, allowHttpLoopback }) => {
|
|
301
|
+
let url;
|
|
302
|
+
try {
|
|
303
|
+
url = new URL(platformUrl);
|
|
304
|
+
} catch {
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) return false;
|
|
308
|
+
return url.protocol === "https:" || allowHttpLoopback === true && url.protocol === "http:" && ["127.0.0.1", "[::1]"].includes(url.hostname);
|
|
309
|
+
}, { path: ["platformUrl"] });
|
|
310
|
+
var pairingCodeSchema = z.string().regex(/^[0-9A-F]{10}$/);
|
|
311
|
+
var machineName = z.string().trim().min(1).max(128).refine((name) => !/[\p{Cc}]/u.test(name));
|
|
312
|
+
var createPairingRequestSchema = z.strictObject({
|
|
313
|
+
name: machineName,
|
|
314
|
+
tokenHash: z.string().regex(/^[0-9a-f]{64}$/)
|
|
315
|
+
});
|
|
316
|
+
var createPairingResponseSchema = z.strictObject({
|
|
317
|
+
code: pairingCodeSchema,
|
|
318
|
+
expiresAt: timestampSchema
|
|
319
|
+
});
|
|
320
|
+
z.strictObject({ machineToken: machineTokenSchema });
|
|
321
|
+
var pairingStatusResponseSchema = z.strictObject({ status: z.enum([
|
|
322
|
+
"pending",
|
|
323
|
+
"approved",
|
|
324
|
+
"expired"
|
|
325
|
+
]) });
|
|
326
|
+
z.strictObject({ code: pairingCodeSchema });
|
|
327
|
+
z.strictObject({
|
|
328
|
+
name: machineName,
|
|
329
|
+
expiresAt: timestampSchema
|
|
330
|
+
});
|
|
331
|
+
z.strictObject({
|
|
332
|
+
machineId: uuidSchema,
|
|
333
|
+
name: machineName
|
|
334
|
+
});
|
|
335
|
+
// apps/launcher/dist/config.js
|
|
336
|
+
function configPath(env = process.env, home = homedir()) {
|
|
337
|
+
return resolve(env.STEWARD_CONFIG ?? join(home, ".config", "pi-steward", "config.json"));
|
|
338
|
+
}
|
|
339
|
+
function readConfig(path, optional = false) {
|
|
340
|
+
let data;
|
|
341
|
+
try {
|
|
342
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
343
|
+
try {
|
|
344
|
+
const stat = fstatSync(fd);
|
|
345
|
+
if (!stat.isFile() || (stat.mode & 511) !== 384 || stat.uid !== process.getuid?.()) throw new Error("config_permissions");
|
|
346
|
+
data = JSON.parse(readFileSync(fd, "utf8"));
|
|
347
|
+
} finally {
|
|
348
|
+
closeSync(fd);
|
|
349
|
+
}
|
|
350
|
+
} catch (error) {
|
|
351
|
+
if (optional && error.code === "ENOENT") return void 0;
|
|
352
|
+
if (error instanceof Error && error.message === "config_permissions") throw new Error("配置必须为当前用户所有的普通文件,权限须为 0600。");
|
|
353
|
+
throw new Error("无法读取配置,请运行 init 或检查配置文件是否为有效 JSON。");
|
|
354
|
+
}
|
|
355
|
+
const result = localConfigSchema.safeParse(data);
|
|
356
|
+
if (!result.success) {
|
|
357
|
+
const fields = new Set(result.error.issues.map(({ path }) => String(path[0] ?? "root")));
|
|
358
|
+
throw new Error(`配置字段无效:${[...fields].join("、")}。`);
|
|
359
|
+
}
|
|
360
|
+
return result.data;
|
|
361
|
+
}
|
|
362
|
+
function writeConfig(path, config, replace = false) {
|
|
363
|
+
const data = localConfigSchema.parse(config);
|
|
364
|
+
mkdirSync(dirname(path), {
|
|
365
|
+
recursive: true,
|
|
366
|
+
mode: 448
|
|
367
|
+
});
|
|
368
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
369
|
+
const fd = openSync(temporary, "wx", 384);
|
|
370
|
+
try {
|
|
371
|
+
try {
|
|
372
|
+
writeFileSync(fd, `${JSON.stringify(data, null, 2)}\n`);
|
|
373
|
+
fsyncSync(fd);
|
|
374
|
+
} finally {
|
|
375
|
+
closeSync(fd);
|
|
376
|
+
}
|
|
377
|
+
if (replace) renameSync(temporary, path);
|
|
378
|
+
else linkSync(temporary, path);
|
|
379
|
+
} finally {
|
|
380
|
+
rmSync(temporary, { force: true });
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
// apps/launcher/dist/platform.js
|
|
384
|
+
var REQUEST_TIMEOUT_MS$1 = 4e3;
|
|
385
|
+
var PlatformError = class extends Error {
|
|
386
|
+
code;
|
|
387
|
+
startedAlreadySaved;
|
|
388
|
+
constructor(code, startedAlreadySaved = false) {
|
|
389
|
+
super(`平台请求失败(${code})。`);
|
|
390
|
+
this.code = code;
|
|
391
|
+
this.startedAlreadySaved = startedAlreadySaved;
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
function platformClient(config, fetcher = fetch, getMachineToken = () => config.machineToken) {
|
|
395
|
+
const origin = new URL(config.platformUrl).origin;
|
|
396
|
+
async function post(path, body, schema, startedReport = false) {
|
|
397
|
+
let machineToken;
|
|
398
|
+
try {
|
|
399
|
+
machineToken = getMachineToken();
|
|
400
|
+
} catch {
|
|
401
|
+
throw new PlatformError("unauthorized");
|
|
402
|
+
}
|
|
403
|
+
let res;
|
|
404
|
+
let data;
|
|
405
|
+
try {
|
|
406
|
+
res = await fetcher(`${origin}/api/v1/launcher/${path}`, {
|
|
407
|
+
method: "POST",
|
|
408
|
+
redirect: "error",
|
|
409
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS$1),
|
|
410
|
+
headers: {
|
|
411
|
+
Authorization: `Bearer ${machineToken}`,
|
|
412
|
+
"Content-Type": "application/json"
|
|
413
|
+
},
|
|
414
|
+
body: JSON.stringify(body)
|
|
415
|
+
});
|
|
416
|
+
data = await res.json();
|
|
417
|
+
} catch {
|
|
418
|
+
throw new PlatformError("network_error");
|
|
419
|
+
}
|
|
420
|
+
if (!res.ok) {
|
|
421
|
+
const parsed = errorResponseSchema.safeParse(data);
|
|
422
|
+
if (!parsed.success) throw new PlatformError("invalid_response");
|
|
423
|
+
const { code, message } = parsed.data.error;
|
|
424
|
+
throw new PlatformError(code, startedReport && res.status === 409 && code === "conflict" && message === "Attempt already has a start report");
|
|
425
|
+
}
|
|
426
|
+
const parsed = schema.safeParse(data);
|
|
427
|
+
if (!parsed.success) throw new PlatformError("invalid_response");
|
|
428
|
+
return parsed.data;
|
|
429
|
+
}
|
|
430
|
+
return {
|
|
431
|
+
claim: (requestId) => post("claim", { requestId }, launcherClaimResponseSchema),
|
|
432
|
+
heartbeat: (body) => post("heartbeat", body, launcherHeartbeatResponseSchema),
|
|
433
|
+
report: (e) => post(`attempts/${e.id}/${e.kind}`, e.body, e.kind === "started" ? launcherStartedResponseSchema : launcherExitedResponseSchema, e.kind === "started")
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
// apps/launcher/dist/tmux.js
|
|
437
|
+
var runFile = promisify(execFile);
|
|
438
|
+
var escapedTmuxArg = (value) => value.endsWith(";") ? `${value.slice(0, -1)}\\;` : value;
|
|
439
|
+
var instructions = "先调用 steward_task 读取完整任务背景。按项目规则和任务授权工作,在关键节点调用 steward_progress。需要用户决定时调用 steward_ask 并等待回应。用 steward_deliver 保存交付,处理完收尾后调用 steward_finish。";
|
|
440
|
+
var targetFor = (id) => `steward-${id}`;
|
|
441
|
+
var TmuxError = class extends Error {
|
|
442
|
+
constructor() {
|
|
443
|
+
super("无法完成 tmux 操作,将在下次循环重新核对。");
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
function displayName(title) {
|
|
447
|
+
return title.replace(/[^\p{L}\p{N} _-]/gu, " ").trim().replace(/^[ -]+/u, "").slice(0, 79).replace(/[\uD800-\uDBFF]$/u, "").trimEnd() || "Pi task";
|
|
448
|
+
}
|
|
449
|
+
function tmuxClient(config, options) {
|
|
450
|
+
const path = config.path.join(":");
|
|
451
|
+
const env = {
|
|
452
|
+
...options.env ?? process.env,
|
|
453
|
+
PATH: path,
|
|
454
|
+
LC_ALL: "C"
|
|
455
|
+
};
|
|
456
|
+
delete env.TMUX;
|
|
457
|
+
delete env.TMUX_PANE;
|
|
458
|
+
delete env.TMUX_TMPDIR;
|
|
459
|
+
const run = options.run ?? runFile;
|
|
460
|
+
const socket = options.socket ? ["-S", options.socket] : ["-L", "steward"];
|
|
461
|
+
const exec = (args) => run("tmux", [
|
|
462
|
+
...socket,
|
|
463
|
+
"-u",
|
|
464
|
+
"-f",
|
|
465
|
+
"/dev/null",
|
|
466
|
+
...args
|
|
467
|
+
], {
|
|
468
|
+
env,
|
|
469
|
+
timeout: 3e3
|
|
470
|
+
});
|
|
471
|
+
return {
|
|
472
|
+
async inspect(target) {
|
|
473
|
+
try {
|
|
474
|
+
const { stdout } = await exec([
|
|
475
|
+
"list-sessions",
|
|
476
|
+
"-F",
|
|
477
|
+
"#{session_name}"
|
|
478
|
+
]);
|
|
479
|
+
return stdout.split("\n").includes(target) ? "present" : "absent";
|
|
480
|
+
} catch (error) {
|
|
481
|
+
const { code, stderr } = error;
|
|
482
|
+
if (code === 1 && typeof stderr === "string" && /^(?:no server running on [^\n]+|error connecting to [^\n]+ \(No such file or directory\))\n?$/u.test(stderr)) return "absent";
|
|
483
|
+
return "unavailable";
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
async launch(target, claim, projectPath) {
|
|
487
|
+
const message = `${claim.kind === "rework" ? "返修本任务。" : "开始执行本任务。"}${instructions}`;
|
|
488
|
+
try {
|
|
489
|
+
await exec([
|
|
490
|
+
"new-session",
|
|
491
|
+
"-d",
|
|
492
|
+
"-s",
|
|
493
|
+
target,
|
|
494
|
+
"-c",
|
|
495
|
+
`${projectPath.replaceAll("#", "##")}/.`,
|
|
496
|
+
"-e",
|
|
497
|
+
`STEWARD_ATTEMPT_ID=${claim.id}`,
|
|
498
|
+
"-e",
|
|
499
|
+
escapedTmuxArg(`STEWARD_CONFIG=${options.configPath}`),
|
|
500
|
+
"-e",
|
|
501
|
+
escapedTmuxArg(`PATH=${path}`),
|
|
502
|
+
"--",
|
|
503
|
+
config.pi.command,
|
|
504
|
+
...config.pi.extraArgs,
|
|
505
|
+
"-e",
|
|
506
|
+
options.extensionPath,
|
|
507
|
+
"--session-id",
|
|
508
|
+
claim.sessionId,
|
|
509
|
+
"-n",
|
|
510
|
+
displayName(claim.displayName),
|
|
511
|
+
"--",
|
|
512
|
+
message
|
|
513
|
+
]);
|
|
514
|
+
} catch {
|
|
515
|
+
throw new TmuxError();
|
|
516
|
+
}
|
|
517
|
+
},
|
|
518
|
+
async cancel(target) {
|
|
519
|
+
try {
|
|
520
|
+
await exec([
|
|
521
|
+
"kill-session",
|
|
522
|
+
"-t",
|
|
523
|
+
`=${target}`
|
|
524
|
+
]);
|
|
525
|
+
} catch {
|
|
526
|
+
throw new TmuxError();
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
// apps/launcher/dist/launcher.js
|
|
532
|
+
var TERMINAL_REPORT_ERRORS = /* @__PURE__ */ new Set([
|
|
533
|
+
"attempt_ended",
|
|
534
|
+
"forbidden",
|
|
535
|
+
"not_found",
|
|
536
|
+
"invalid_request",
|
|
537
|
+
"conflict"
|
|
538
|
+
]);
|
|
539
|
+
var MAX_OUTBOX_BACKOFF_MS = 12e4;
|
|
540
|
+
var Launcher = class {
|
|
541
|
+
options;
|
|
542
|
+
nextOutboxRetryAt = 0;
|
|
543
|
+
outboxBackoff = HEARTBEAT_INTERVAL_MS;
|
|
544
|
+
constructor(options) {
|
|
545
|
+
this.options = options;
|
|
546
|
+
}
|
|
547
|
+
get state() {
|
|
548
|
+
return this.options.state;
|
|
549
|
+
}
|
|
550
|
+
persist() {
|
|
551
|
+
this.options.save(this.state);
|
|
552
|
+
}
|
|
553
|
+
now() {
|
|
554
|
+
return (this.options.now ?? Date.now)();
|
|
555
|
+
}
|
|
556
|
+
async retryable(run) {
|
|
557
|
+
try {
|
|
558
|
+
return await run();
|
|
559
|
+
} catch (error) {
|
|
560
|
+
if (!(error instanceof PlatformError || error instanceof TmuxError)) throw error;
|
|
561
|
+
this.options.warn?.(error.message);
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
async flush() {
|
|
566
|
+
if (this.now() < this.nextOutboxRetryAt) return false;
|
|
567
|
+
for (const event of [...this.state.outbox]) {
|
|
568
|
+
let confirmed = true;
|
|
569
|
+
try {
|
|
570
|
+
await this.options.platform.report(event);
|
|
571
|
+
} catch (error) {
|
|
572
|
+
if (!(error instanceof PlatformError)) throw error;
|
|
573
|
+
if (!TERMINAL_REPORT_ERRORS.has(error.code)) {
|
|
574
|
+
this.options.warn?.(error.message);
|
|
575
|
+
this.nextOutboxRetryAt = this.now() + this.outboxBackoff;
|
|
576
|
+
this.outboxBackoff = Math.min(MAX_OUTBOX_BACKOFF_MS, this.outboxBackoff * 2);
|
|
577
|
+
return false;
|
|
578
|
+
}
|
|
579
|
+
confirmed = error.code === "attempt_ended" || event.kind === "started" && error.startedAlreadySaved;
|
|
580
|
+
if (!confirmed) this.options.warn?.(`平台终态拒绝事件 ${event.kind}(${event.id},${error.code})。`);
|
|
581
|
+
}
|
|
582
|
+
this.outboxBackoff = HEARTBEAT_INTERVAL_MS;
|
|
583
|
+
this.nextOutboxRetryAt = 0;
|
|
584
|
+
this.state.outbox = this.state.outbox.filter(({ body }) => body.requestId !== event.body.requestId);
|
|
585
|
+
if (event.kind === "exited" && confirmed) this.remove(event.id);
|
|
586
|
+
else this.persist();
|
|
587
|
+
}
|
|
588
|
+
return true;
|
|
589
|
+
}
|
|
590
|
+
remove(id) {
|
|
591
|
+
this.state.executions = this.state.executions.filter((record) => record.id !== id);
|
|
592
|
+
this.persist();
|
|
593
|
+
}
|
|
594
|
+
started(record) {
|
|
595
|
+
if (record.phase === "observed") return;
|
|
596
|
+
record.phase = "observed";
|
|
597
|
+
this.state.outbox.push({
|
|
598
|
+
kind: "started",
|
|
599
|
+
id: record.id,
|
|
600
|
+
body: {
|
|
601
|
+
requestId: randomUUID(),
|
|
602
|
+
tmuxSession: record.target,
|
|
603
|
+
startedAt: record.startedAt ?? this.now()
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
this.persist();
|
|
607
|
+
}
|
|
608
|
+
exited(record) {
|
|
609
|
+
if (record.phase === "exited") return;
|
|
610
|
+
record.phase = "exited";
|
|
611
|
+
this.state.outbox.push({
|
|
612
|
+
kind: "exited",
|
|
613
|
+
id: record.id,
|
|
614
|
+
body: {
|
|
615
|
+
requestId: randomUUID(),
|
|
616
|
+
exitCode: null,
|
|
617
|
+
endedAt: this.now()
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
this.persist();
|
|
621
|
+
}
|
|
622
|
+
async observe() {
|
|
623
|
+
const attempts = [];
|
|
624
|
+
for (const record of this.state.executions) {
|
|
625
|
+
if (record.phase === "exited") continue;
|
|
626
|
+
const status = await this.options.tmux.inspect(record.target);
|
|
627
|
+
if (status === "unavailable") {
|
|
628
|
+
this.options.warn?.("tmux 会话核对失败,保留本地尝试。");
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
if (status === "present") this.started(record);
|
|
632
|
+
if (status === "absent" && record.phase !== "prepared") this.exited(record);
|
|
633
|
+
attempts.push({
|
|
634
|
+
id: record.id,
|
|
635
|
+
tmuxSession: record.target,
|
|
636
|
+
running: status === "present"
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
return attempts;
|
|
640
|
+
}
|
|
641
|
+
async heartbeat() {
|
|
642
|
+
const attempts = await this.observe();
|
|
643
|
+
const response = await this.retryable(() => this.options.platform.heartbeat({
|
|
644
|
+
requestId: randomUUID(),
|
|
645
|
+
launcherVersion: this.options.version,
|
|
646
|
+
slots: this.options.config.slots,
|
|
647
|
+
projects: this.options.config.projects,
|
|
648
|
+
attempts
|
|
649
|
+
}));
|
|
650
|
+
if (response) {
|
|
651
|
+
this.state.lastHeartbeatAt = this.now();
|
|
652
|
+
this.persist();
|
|
653
|
+
}
|
|
654
|
+
return response;
|
|
655
|
+
}
|
|
656
|
+
async startPrepared(record) {
|
|
657
|
+
const claim = record.claim;
|
|
658
|
+
const project = this.options.config.projects.find(({ id }) => id === claim.projectId);
|
|
659
|
+
if (!project) {
|
|
660
|
+
this.exited(record);
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
record.phase = "launching";
|
|
664
|
+
record.startedAt = this.now();
|
|
665
|
+
this.persist();
|
|
666
|
+
if (await this.retryable(async () => {
|
|
667
|
+
await this.options.tmux.launch(record.target, claim, project.path);
|
|
668
|
+
return true;
|
|
669
|
+
})) this.started(record);
|
|
670
|
+
}
|
|
671
|
+
async applyDirective(directive) {
|
|
672
|
+
const { attemptId: id, tmuxSession: target, action } = directive;
|
|
673
|
+
if (target !== targetFor(id)) return;
|
|
674
|
+
let record = this.state.executions.find((item) => item.id === id);
|
|
675
|
+
if (record?.phase === "exited" || action === "continue" && record?.phase === "observed") return;
|
|
676
|
+
const status = await this.options.tmux.inspect(target);
|
|
677
|
+
if (status === "unavailable") return;
|
|
678
|
+
if (!record) {
|
|
679
|
+
record = {
|
|
680
|
+
id,
|
|
681
|
+
target,
|
|
682
|
+
phase: "observed"
|
|
683
|
+
};
|
|
684
|
+
this.state.executions.push(record);
|
|
685
|
+
if (status === "present") this.persist();
|
|
686
|
+
}
|
|
687
|
+
if (action === "cancel") {
|
|
688
|
+
if (status === "present") {
|
|
689
|
+
await this.retryable(() => this.options.tmux.cancel(target));
|
|
690
|
+
if (await this.options.tmux.inspect(target) !== "absent") return;
|
|
691
|
+
}
|
|
692
|
+
this.exited(record);
|
|
693
|
+
} else if (status === "present") this.started(record);
|
|
694
|
+
else if (action === "continue" && record.phase === "prepared") await this.startPrepared(record);
|
|
695
|
+
else if (record.phase !== "prepared") this.exited(record);
|
|
696
|
+
}
|
|
697
|
+
async reconcile(response, claimPending = false) {
|
|
698
|
+
for (const directive of response.directives) {
|
|
699
|
+
if (claimPending && !this.state.executions.some(({ id }) => id === directive.attemptId)) continue;
|
|
700
|
+
await this.applyDirective(directive);
|
|
701
|
+
}
|
|
702
|
+
const active = new Set(response.directives.map(({ attemptId }) => attemptId));
|
|
703
|
+
const pending = new Set(this.state.outbox.map(({ id }) => id));
|
|
704
|
+
for (const record of [...this.state.executions]) {
|
|
705
|
+
if (active.has(record.id)) continue;
|
|
706
|
+
if (record.phase === "exited" && !pending.has(record.id)) this.remove(record.id);
|
|
707
|
+
else if (record.phase === "prepared" && await this.options.tmux.inspect(record.target) === "absent") this.remove(record.id);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
async claim() {
|
|
711
|
+
if (!this.state.claimRequestId) {
|
|
712
|
+
this.state.claimRequestId = randomUUID();
|
|
713
|
+
this.persist();
|
|
714
|
+
}
|
|
715
|
+
const requestId = this.state.claimRequestId;
|
|
716
|
+
const result = await this.retryable(() => this.options.platform.claim(requestId));
|
|
717
|
+
if (!result) return false;
|
|
718
|
+
delete this.state.claimRequestId;
|
|
719
|
+
const claim = result.attempt;
|
|
720
|
+
if (claim && !this.state.executions.some(({ id }) => id === claim.id)) this.state.executions.push({
|
|
721
|
+
id: claim.id,
|
|
722
|
+
target: targetFor(claim.id),
|
|
723
|
+
phase: "prepared",
|
|
724
|
+
claim
|
|
725
|
+
});
|
|
726
|
+
this.persist();
|
|
727
|
+
return !!claim;
|
|
728
|
+
}
|
|
729
|
+
async tick() {
|
|
730
|
+
const flushed = await this.flush();
|
|
731
|
+
const replayed = !!this.state.claimRequestId;
|
|
732
|
+
if (replayed) await this.claim();
|
|
733
|
+
const heartbeat = await this.heartbeat();
|
|
734
|
+
if (!heartbeat) return;
|
|
735
|
+
await this.reconcile(heartbeat, !!this.state.claimRequestId);
|
|
736
|
+
if (!flushed || !await this.flush() || replayed) return;
|
|
737
|
+
const slots = this.options.config.slots;
|
|
738
|
+
if ((/* @__PURE__ */ new Set([...heartbeat.directives.map(({ attemptId }) => attemptId), ...this.state.executions.filter(({ phase }) => phase !== "exited").map(({ id }) => id)])).size >= slots) return;
|
|
739
|
+
if (!await this.claim()) return;
|
|
740
|
+
const afterClaim = await this.heartbeat();
|
|
741
|
+
if (!afterClaim) return;
|
|
742
|
+
await this.reconcile(afterClaim);
|
|
743
|
+
await this.flush();
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
// apps/launcher/dist/service.js
|
|
747
|
+
var LABEL = "dev.pi-steward.launcher";
|
|
748
|
+
var DEFAULT_PATH = [
|
|
749
|
+
"/opt/homebrew/bin",
|
|
750
|
+
"/usr/local/bin",
|
|
751
|
+
"/usr/bin",
|
|
752
|
+
"/bin",
|
|
753
|
+
"/usr/sbin",
|
|
754
|
+
"/sbin"
|
|
755
|
+
];
|
|
756
|
+
var exec = promisify(execFile);
|
|
757
|
+
function binaryDir(name, path) {
|
|
758
|
+
return path.find((folder) => {
|
|
759
|
+
try {
|
|
760
|
+
accessSync(join(folder, name), constants.X_OK);
|
|
761
|
+
return true;
|
|
762
|
+
} catch {
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
function launcherPath(env = process.env) {
|
|
768
|
+
const current = (env.PATH ?? "").split(delimiter).filter((path) => isAbsolute(path) && !path.includes(":"));
|
|
769
|
+
const executableDirs = [
|
|
770
|
+
"pi",
|
|
771
|
+
"tmux",
|
|
772
|
+
"git"
|
|
773
|
+
].map((name) => binaryDir(name, current)).filter((dir) => dir !== void 0);
|
|
774
|
+
return [.../* @__PURE__ */ new Set([
|
|
775
|
+
...executableDirs,
|
|
776
|
+
dirname(process.execPath),
|
|
777
|
+
...DEFAULT_PATH
|
|
778
|
+
])];
|
|
779
|
+
}
|
|
780
|
+
function checkPrerequisites(path, pi) {
|
|
781
|
+
if ([pi, "tmux"].filter((command) => !binaryDir(isAbsolute(command) ? command.split("/").at(-1) : command, isAbsolute(command) ? [dirname(command)] : path)).length) throw new Error("找不到 Pi 或 tmux,请检查安装和配置中的 PATH。");
|
|
782
|
+
}
|
|
783
|
+
function initConfig(path, env = process.env) {
|
|
784
|
+
mkdirSync(dirname(path), {
|
|
785
|
+
recursive: true,
|
|
786
|
+
mode: 448
|
|
787
|
+
});
|
|
788
|
+
writeFileSync(path, `${JSON.stringify({
|
|
789
|
+
platformUrl: "https://steward.example.com",
|
|
790
|
+
machineToken: "请填入机器令牌",
|
|
791
|
+
slots: 1,
|
|
792
|
+
projects: [],
|
|
793
|
+
pi: {
|
|
794
|
+
command: "pi",
|
|
795
|
+
extraArgs: []
|
|
796
|
+
},
|
|
797
|
+
path: launcherPath(env)
|
|
798
|
+
}, null, 2)}\n`, {
|
|
799
|
+
mode: 384,
|
|
800
|
+
flag: "wx"
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
var xml = (value) => value.replace(/[&<>"']/gu, (ch) => ({
|
|
804
|
+
"&": "&",
|
|
805
|
+
"<": "<",
|
|
806
|
+
">": ">",
|
|
807
|
+
"\"": """,
|
|
808
|
+
"'": "'"
|
|
809
|
+
})[ch]);
|
|
810
|
+
function launchService(options) {
|
|
811
|
+
const plist = join(options.home, "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
812
|
+
const logs = join(options.home, "Library", "Logs", "pi-steward");
|
|
813
|
+
const domain = `gui/${options.uid}`;
|
|
814
|
+
const run = options.launchctl ?? ((args) => exec("/bin/launchctl", args, { timeout: 1e4 }));
|
|
815
|
+
return {
|
|
816
|
+
async isLoaded() {
|
|
817
|
+
try {
|
|
818
|
+
await run(["print", `${domain}/${LABEL}`]);
|
|
819
|
+
return true;
|
|
820
|
+
} catch {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
},
|
|
824
|
+
async install() {
|
|
825
|
+
mkdirSync(dirname(plist), {
|
|
826
|
+
recursive: true,
|
|
827
|
+
mode: 448
|
|
828
|
+
});
|
|
829
|
+
mkdirSync(logs, {
|
|
830
|
+
recursive: true,
|
|
831
|
+
mode: 448
|
|
832
|
+
});
|
|
833
|
+
writeFileSync(plist, `<?xml version="1.0" encoding="UTF-8"?>
|
|
834
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
835
|
+
<plist version="1.0"><dict>
|
|
836
|
+
<key>Label</key><string>${LABEL}</string>
|
|
837
|
+
<key>ProgramArguments</key><array><string>${xml(options.node)}</string><string>${xml(options.launcher)}</string><string>run</string></array>
|
|
838
|
+
<key>EnvironmentVariables</key><dict><key>STEWARD_CONFIG</key><string>${xml(options.config)}</string></dict>
|
|
839
|
+
<key>RunAtLoad</key><true/>
|
|
840
|
+
<key>KeepAlive</key><true/>
|
|
841
|
+
<key>StandardOutPath</key><string>${xml(join(logs, "launcher.log"))}</string>
|
|
842
|
+
<key>StandardErrorPath</key><string>${xml(join(logs, "launcher-error.log"))}</string>
|
|
843
|
+
</dict></plist>
|
|
844
|
+
`, {
|
|
845
|
+
mode: 384,
|
|
846
|
+
flag: "wx"
|
|
847
|
+
});
|
|
848
|
+
try {
|
|
849
|
+
await run([
|
|
850
|
+
"bootstrap",
|
|
851
|
+
domain,
|
|
852
|
+
plist
|
|
853
|
+
]);
|
|
854
|
+
} catch {
|
|
855
|
+
rmSync(plist, { force: true });
|
|
856
|
+
throw new Error("launchctl bootstrap 失败,请在 Mac 登录会话中检查服务状态。");
|
|
857
|
+
}
|
|
858
|
+
},
|
|
859
|
+
async uninstall() {
|
|
860
|
+
try {
|
|
861
|
+
await run(["bootout", `${domain}/${LABEL}`]);
|
|
862
|
+
} catch {
|
|
863
|
+
throw new Error(`launchctl bootout 失败,已保留 plist:${JSON.stringify(plist)}。在当前 Mac 登录会话用 launchctl print ${domain}/${LABEL} 核对。若服务仍加载,修复原因后重试卸载。若已确认卸载,可按需备份并手动移走该 plist,再重新安装。`);
|
|
864
|
+
}
|
|
865
|
+
rmSync(plist, { force: true });
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
// apps/launcher/dist/pairing.js
|
|
870
|
+
var POLL_INTERVAL_MS = 2e3;
|
|
871
|
+
var REQUEST_TIMEOUT_MS = 4e3;
|
|
872
|
+
var MAX_WAIT_MS = 72e4;
|
|
873
|
+
var newToken = () => `stm_${randomBytes(32).toString("base64url")}`;
|
|
874
|
+
function client(origin, fetcher) {
|
|
875
|
+
async function post(operation, input, output) {
|
|
876
|
+
let response;
|
|
877
|
+
try {
|
|
878
|
+
response = await fetcher(`${origin}/api/v1/pairing/${operation}`, {
|
|
879
|
+
method: "POST",
|
|
880
|
+
redirect: "error",
|
|
881
|
+
headers: { "Content-Type": "application/json" },
|
|
882
|
+
body: JSON.stringify(input),
|
|
883
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
884
|
+
});
|
|
885
|
+
} catch {
|
|
886
|
+
throw new Error("无法连接 Steward。稍后可再次运行 stew pair 继续。");
|
|
887
|
+
}
|
|
888
|
+
const data = await response.json().catch(() => void 0);
|
|
889
|
+
if (!response.ok) {
|
|
890
|
+
const error = errorResponseSchema.safeParse(data);
|
|
891
|
+
if (error.data?.error.code === "conflict") throw new Error("此电脑的配对请求与已有记录冲突,请在 Steward 中核对。");
|
|
892
|
+
if (error.data?.error.code === "rate_limited") throw new Error("配对请求过多,请稍后重试。");
|
|
893
|
+
throw new Error("Steward 无法处理配对请求,请检查平台地址和版本。");
|
|
894
|
+
}
|
|
895
|
+
const parsed = output.safeParse(data);
|
|
896
|
+
if (!parsed.success) throw new Error("Steward 返回了无效的配对结果。");
|
|
897
|
+
return parsed.data;
|
|
898
|
+
}
|
|
899
|
+
return {
|
|
900
|
+
create: (name, tokenHash) => post("create", createPairingRequestSchema.parse({
|
|
901
|
+
name,
|
|
902
|
+
tokenHash
|
|
903
|
+
}), createPairingResponseSchema),
|
|
904
|
+
status: (machineToken) => post("status", { machineToken }, pairingStatusResponseSchema)
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
async function pairMachine(options) {
|
|
908
|
+
const { path, name, origin } = options;
|
|
909
|
+
const pendingPath = `${path}.pairing`;
|
|
910
|
+
const existing = readConfig(path, true);
|
|
911
|
+
const api = client(origin, options.fetcher ?? fetch);
|
|
912
|
+
if (existing) {
|
|
913
|
+
if (new URL(existing.platformUrl).origin !== origin) throw new Error("这台电脑已配置其他 Steward 平台,请检查本地配置。");
|
|
914
|
+
if ((await api.status(existing.machineToken)).status === "approved") {
|
|
915
|
+
rmSync(pendingPath, { force: true });
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
let config = readConfig(pendingPath, true);
|
|
920
|
+
if (config && config.platformUrl !== origin) throw new Error("尚有其他 Steward 平台的配对请求,请先在原地址继续。");
|
|
921
|
+
if (!config) {
|
|
922
|
+
config = localConfigSchema.parse({
|
|
923
|
+
slots: 1,
|
|
924
|
+
projects: [],
|
|
925
|
+
pi: {
|
|
926
|
+
command: "pi",
|
|
927
|
+
extraArgs: []
|
|
928
|
+
},
|
|
929
|
+
path: launcherPath(),
|
|
930
|
+
...existing,
|
|
931
|
+
platformUrl: origin,
|
|
932
|
+
allowHttpLoopback: options.allowHttpLoopback,
|
|
933
|
+
machineToken: newToken()
|
|
934
|
+
});
|
|
935
|
+
writeConfig(pendingPath, config);
|
|
936
|
+
}
|
|
937
|
+
const elapsed = options.elapsed ?? (() => performance.now());
|
|
938
|
+
const wait = options.wait ?? (() => setTimeout(POLL_INTERVAL_MS));
|
|
939
|
+
if ((await api.status(config.machineToken)).status !== "approved") {
|
|
940
|
+
const hashed = createHash("sha256").update(config.machineToken).digest("hex");
|
|
941
|
+
const fingerprint = createHash("sha256").update("steward:machine-name:").update(config.machineToken).digest("hex").slice(0, 8);
|
|
942
|
+
const displayName = `${name.slice(0, 116).replace(/[\uD800-\uDBFF]$/u, "").trimEnd()} · ${fingerprint}`;
|
|
943
|
+
const { code } = await api.create(displayName, hashed);
|
|
944
|
+
options.display(code, `${origin}/pair`, displayName);
|
|
945
|
+
const deadline = elapsed() + MAX_WAIT_MS;
|
|
946
|
+
for (;;) {
|
|
947
|
+
const { status } = await api.status(config.machineToken);
|
|
948
|
+
if (status === "approved") break;
|
|
949
|
+
if (status === "expired") throw new Error("配对码已过期。请再次运行 stew pair 获取新码。");
|
|
950
|
+
if (elapsed() >= deadline) throw new Error("等待配对确认超时。请再次运行 stew pair 核对。");
|
|
951
|
+
await wait();
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
writeConfig(path, config, Boolean(existing));
|
|
955
|
+
rmSync(pendingPath, { force: true });
|
|
956
|
+
}
|
|
957
|
+
// apps/launcher/dist/state.js
|
|
958
|
+
var execution = z.strictObject({
|
|
959
|
+
id: uuidSchema,
|
|
960
|
+
target: tmuxSessionSchema,
|
|
961
|
+
phase: z.enum([
|
|
962
|
+
"prepared",
|
|
963
|
+
"launching",
|
|
964
|
+
"observed",
|
|
965
|
+
"exited"
|
|
966
|
+
]),
|
|
967
|
+
claim: claimedAttemptSchema.optional(),
|
|
968
|
+
startedAt: timestampSchema.optional()
|
|
969
|
+
}).refine(({ id, target, phase, claim, startedAt }) => target === `steward-${id}` && (!claim || claim.id === id) && (phase !== "prepared" || !!claim) && (phase !== "launching" || startedAt !== void 0));
|
|
970
|
+
var event = z.discriminatedUnion("kind", [z.strictObject({
|
|
971
|
+
kind: z.literal("started"),
|
|
972
|
+
id: uuidSchema,
|
|
973
|
+
body: launcherStartedRequestSchema
|
|
974
|
+
}), z.strictObject({
|
|
975
|
+
kind: z.literal("exited"),
|
|
976
|
+
id: uuidSchema,
|
|
977
|
+
body: launcherExitedRequestSchema
|
|
978
|
+
})]);
|
|
979
|
+
var stateSchema = z.strictObject({
|
|
980
|
+
version: z.literal(1),
|
|
981
|
+
claimRequestId: uuidSchema.optional(),
|
|
982
|
+
lastHeartbeatAt: timestampSchema.optional(),
|
|
983
|
+
executions: z.array(execution),
|
|
984
|
+
outbox: z.array(event)
|
|
985
|
+
});
|
|
986
|
+
function loadState(path) {
|
|
987
|
+
try {
|
|
988
|
+
return stateSchema.parse(JSON.parse(readFileSync(path, "utf8")));
|
|
989
|
+
} catch (error) {
|
|
990
|
+
if (error.code === "ENOENT") return {
|
|
991
|
+
version: 1,
|
|
992
|
+
executions: [],
|
|
993
|
+
outbox: []
|
|
994
|
+
};
|
|
995
|
+
throw new Error("本地启动器状态不可读取。请保留原文件供核对。");
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
function saveState(path, state) {
|
|
999
|
+
mkdirSync(dirname(path), {
|
|
1000
|
+
recursive: true,
|
|
1001
|
+
mode: 448
|
|
1002
|
+
});
|
|
1003
|
+
const temp = `${path}.${randomUUID()}.tmp`;
|
|
1004
|
+
const fd = openSync(temp, "wx", 384);
|
|
1005
|
+
try {
|
|
1006
|
+
try {
|
|
1007
|
+
writeFileSync(fd, JSON.stringify(state));
|
|
1008
|
+
fsyncSync(fd);
|
|
1009
|
+
} finally {
|
|
1010
|
+
closeSync(fd);
|
|
1011
|
+
}
|
|
1012
|
+
renameSync(temp, path);
|
|
1013
|
+
} finally {
|
|
1014
|
+
rmSync(temp, { force: true });
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
function acquireRunLock(statePath, message = "无法取得启动器锁,请确认只有一个 run 实例。") {
|
|
1018
|
+
mkdirSync(dirname(statePath), {
|
|
1019
|
+
recursive: true,
|
|
1020
|
+
mode: 448
|
|
1021
|
+
});
|
|
1022
|
+
const lockPath = `${statePath}.lock`;
|
|
1023
|
+
closeSync(openSync(lockPath, "a", 384));
|
|
1024
|
+
const db = new DatabaseSync(lockPath, { timeout: 0 });
|
|
1025
|
+
try {
|
|
1026
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1027
|
+
} catch {
|
|
1028
|
+
db.close();
|
|
1029
|
+
throw new Error(message);
|
|
1030
|
+
}
|
|
1031
|
+
return () => db.close();
|
|
1032
|
+
}
|
|
1033
|
+
// apps/launcher/dist/projects.js
|
|
1034
|
+
function addProject(configFile, directory = process.cwd()) {
|
|
1035
|
+
const release = acquireRunLock(`${configFile}.write`, "已有 Steward 命令正在更新配置,请稍后重试。");
|
|
1036
|
+
try {
|
|
1037
|
+
const config = readConfig(configFile);
|
|
1038
|
+
let path;
|
|
1039
|
+
try {
|
|
1040
|
+
const root = execFileSync("git", [
|
|
1041
|
+
"-C",
|
|
1042
|
+
directory,
|
|
1043
|
+
"rev-parse",
|
|
1044
|
+
"--show-toplevel"
|
|
1045
|
+
], {
|
|
1046
|
+
encoding: "utf8",
|
|
1047
|
+
stdio: [
|
|
1048
|
+
"ignore",
|
|
1049
|
+
"pipe",
|
|
1050
|
+
"ignore"
|
|
1051
|
+
],
|
|
1052
|
+
timeout: 3e3
|
|
1053
|
+
});
|
|
1054
|
+
path = realpathSync(root.replace(/\n$/u, ""));
|
|
1055
|
+
} catch {
|
|
1056
|
+
throw new Error("请在要登记的 Git 项目目录下运行 stew add。");
|
|
1057
|
+
}
|
|
1058
|
+
const existing = config.projects.find((project) => project.path === path);
|
|
1059
|
+
if (existing) return {
|
|
1060
|
+
project: existing,
|
|
1061
|
+
added: false
|
|
1062
|
+
};
|
|
1063
|
+
const project = {
|
|
1064
|
+
id: `project-${createHash("sha256").update(config.machineToken).update("\0").update(path).digest("hex")}`,
|
|
1065
|
+
name: basename(path).trim() || "Git project",
|
|
1066
|
+
path
|
|
1067
|
+
};
|
|
1068
|
+
const updated = localConfigSchema.safeParse({
|
|
1069
|
+
...config,
|
|
1070
|
+
projects: [...config.projects, project]
|
|
1071
|
+
});
|
|
1072
|
+
if (!updated.success) throw new Error("项目目录不符合登记要求,或已达到项目数量上限。");
|
|
1073
|
+
writeConfig(configFile, updated.data, true);
|
|
1074
|
+
return {
|
|
1075
|
+
project,
|
|
1076
|
+
added: true
|
|
1077
|
+
};
|
|
1078
|
+
} finally {
|
|
1079
|
+
release();
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
// apps/launcher/dist/index.js
|
|
1083
|
+
var home = homedir();
|
|
1084
|
+
var configFile = configPath();
|
|
1085
|
+
var stateFile = join(home, "Library", "Application Support", "pi-steward", "launcher-state.json");
|
|
1086
|
+
var { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
1087
|
+
var packagedExtension = fileURLToPath(new URL("./extension.js", import.meta.url));
|
|
1088
|
+
var extensionPath = existsSync(packagedExtension) ? packagedExtension : fileURLToPath(new URL("../../../packages/pi-extension/dist/index.js", import.meta.url));
|
|
1089
|
+
async function run() {
|
|
1090
|
+
const config = readConfig(configFile);
|
|
1091
|
+
const release = acquireRunLock(stateFile);
|
|
1092
|
+
const stop = new AbortController();
|
|
1093
|
+
const onSignal = () => stop.abort();
|
|
1094
|
+
process.on("SIGTERM", onSignal);
|
|
1095
|
+
process.on("SIGINT", onSignal);
|
|
1096
|
+
try {
|
|
1097
|
+
const origin = new URL(config.platformUrl).origin;
|
|
1098
|
+
const platform = platformClient(config);
|
|
1099
|
+
const launcher = new Launcher({
|
|
1100
|
+
config,
|
|
1101
|
+
version,
|
|
1102
|
+
state: loadState(stateFile),
|
|
1103
|
+
save: (state) => saveState(stateFile, state),
|
|
1104
|
+
platform,
|
|
1105
|
+
tmux: tmuxClient(config, {
|
|
1106
|
+
configPath: configFile,
|
|
1107
|
+
extensionPath
|
|
1108
|
+
}),
|
|
1109
|
+
warn: (text) => console.error(text)
|
|
1110
|
+
});
|
|
1111
|
+
while (!stop.signal.aborted) {
|
|
1112
|
+
const start = performance.now();
|
|
1113
|
+
try {
|
|
1114
|
+
const current = readConfig(configFile);
|
|
1115
|
+
if (new URL(current.platformUrl).origin !== origin) throw new Error("platform_origin_changed");
|
|
1116
|
+
config.machineToken = current.machineToken;
|
|
1117
|
+
config.projects = current.projects;
|
|
1118
|
+
} catch {
|
|
1119
|
+
console.error("无法重新读取当前平台配置,将在下次心跳重试。");
|
|
1120
|
+
await setTimeout(HEARTBEAT_INTERVAL_MS, void 0, { signal: stop.signal }).catch(() => void 0);
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
await launcher.tick();
|
|
1124
|
+
if (stop.signal.aborted) break;
|
|
1125
|
+
await setTimeout(Math.max(0, HEARTBEAT_INTERVAL_MS - (performance.now() - start)), void 0, { signal: stop.signal }).catch((error) => {
|
|
1126
|
+
if (!stop.signal.aborted) throw error;
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
} finally {
|
|
1130
|
+
process.off("SIGTERM", onSignal);
|
|
1131
|
+
process.off("SIGINT", onSignal);
|
|
1132
|
+
release();
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
async function pair(args) {
|
|
1136
|
+
const { values } = parseArgs({
|
|
1137
|
+
args,
|
|
1138
|
+
options: {
|
|
1139
|
+
url: { type: "string" },
|
|
1140
|
+
"allow-http-loopback": { type: "boolean" }
|
|
1141
|
+
}
|
|
1142
|
+
});
|
|
1143
|
+
const saved = readConfig(configFile, true) ?? readConfig(`${configFile}.pairing`, true);
|
|
1144
|
+
const allowHttpLoopback = values["allow-http-loopback"] || saved?.allowHttpLoopback ? true : void 0;
|
|
1145
|
+
const platformUrl = values.url ?? saved?.platformUrl ?? "https://steward.yefengr.cn";
|
|
1146
|
+
if (!localConfigSchema.shape.platformUrl.safeParse(platformUrl).success) throw new Error("Steward 地址无效。");
|
|
1147
|
+
const url = new URL(platformUrl);
|
|
1148
|
+
const loopback = ["127.0.0.1", "[::1]"].includes(url.hostname);
|
|
1149
|
+
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash || !(url.protocol === "https:" || allowHttpLoopback && loopback && url.protocol === "http:")) throw new Error("请输入不带路径的 HTTPS 平台地址。");
|
|
1150
|
+
const release = acquireRunLock(`${configFile}.write`, "已有 Steward 命令正在更新配置,请稍后重试。");
|
|
1151
|
+
try {
|
|
1152
|
+
await pairMachine({
|
|
1153
|
+
path: configFile,
|
|
1154
|
+
name: hostname().replace(/[\p{Cc}]/gu, "").trim().slice(0, 128) || "Mac",
|
|
1155
|
+
origin: url.origin,
|
|
1156
|
+
allowHttpLoopback,
|
|
1157
|
+
display: (code, link, computer) => {
|
|
1158
|
+
console.log(`电脑名称 ${computer}\n配对码 ${code}\n请登录 ${link} 并输入配对码,核对电脑名称后确认。`);
|
|
1159
|
+
execFile("/usr/bin/open", [link], { timeout: 5e3 }, () => {});
|
|
1160
|
+
}
|
|
1161
|
+
});
|
|
1162
|
+
console.log("此电脑已配对。运行 stew start 启动后台服务。");
|
|
1163
|
+
} finally {
|
|
1164
|
+
release();
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
async function main(command, ...args) {
|
|
1168
|
+
const service = launchService({
|
|
1169
|
+
home,
|
|
1170
|
+
uid: process.getuid?.() ?? -1,
|
|
1171
|
+
node: process.execPath,
|
|
1172
|
+
launcher: fileURLToPath(import.meta.url),
|
|
1173
|
+
config: configFile
|
|
1174
|
+
});
|
|
1175
|
+
switch (command) {
|
|
1176
|
+
case "pair": return pair(args);
|
|
1177
|
+
case "start": {
|
|
1178
|
+
if (process.platform !== "darwin") throw new Error("Steward 后台服务需要 macOS。");
|
|
1179
|
+
const config = readConfig(configFile);
|
|
1180
|
+
checkPrerequisites(config.path, config.pi.command);
|
|
1181
|
+
if (!existsSync(extensionPath)) throw new Error("找不到随包安装的 Steward Pi 扩展。");
|
|
1182
|
+
await service.install();
|
|
1183
|
+
console.log("后台服务已启动。进入项目目录运行 stew add,稍后可在网页查看电脑是否在线。");
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
case "add": {
|
|
1187
|
+
const { project, added } = addProject(configFile);
|
|
1188
|
+
console.log(`${added ? "已登记" : "已登记过"}项目「${project.name}」。后台服务运行时,项目会在下一次心跳同步。`);
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
case void 0: {
|
|
1192
|
+
const config = readConfig(configFile, true);
|
|
1193
|
+
if (!config) console.log("尚未配对。运行 stew pair 接入这台电脑。");
|
|
1194
|
+
else if (!await service.isLoaded()) console.log("此电脑已配对。运行 stew start 启动后台服务。");
|
|
1195
|
+
else if (!config.projects.length) console.log("后台服务已加载。进入项目目录运行 stew add。");
|
|
1196
|
+
else console.log(`后台服务已加载,已登记 ${config.projects.length} 个项目。运行 stew status 查看本机状态。`);
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
case "--version":
|
|
1200
|
+
console.log(version);
|
|
1201
|
+
return;
|
|
1202
|
+
case "run": return run();
|
|
1203
|
+
case "init":
|
|
1204
|
+
initConfig(configFile);
|
|
1205
|
+
console.log(`配置模板已写入 ${configFile},请填写平台地址、机器令牌和项目。`);
|
|
1206
|
+
return;
|
|
1207
|
+
case "install":
|
|
1208
|
+
readConfig(configFile);
|
|
1209
|
+
return service.install();
|
|
1210
|
+
case "uninstall": return service.uninstall();
|
|
1211
|
+
case "status": {
|
|
1212
|
+
const config = readConfig(configFile);
|
|
1213
|
+
const state = loadState(stateFile);
|
|
1214
|
+
const online = state.lastHeartbeatAt !== void 0 && Date.now() - state.lastHeartbeatAt < 45e3;
|
|
1215
|
+
const tmux = tmuxClient(config, {
|
|
1216
|
+
configPath: configFile,
|
|
1217
|
+
extensionPath
|
|
1218
|
+
});
|
|
1219
|
+
console.log(`${new URL(config.platformUrl).origin} | ${online ? "在线" : "离线"} | ${config.projects.length} 个项目 | ${config.slots} 个名额`);
|
|
1220
|
+
for (const { target, phase } of state.executions) {
|
|
1221
|
+
const status = phase === "exited" ? "待上报退出" : {
|
|
1222
|
+
present: "运行中",
|
|
1223
|
+
absent: "未运行",
|
|
1224
|
+
unavailable: "无法核对"
|
|
1225
|
+
}[await tmux.inspect(target)];
|
|
1226
|
+
console.log(`${target} | ${status}`);
|
|
1227
|
+
}
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
case "--help":
|
|
1231
|
+
console.log("用法:stew [pair|start|add|status]");
|
|
1232
|
+
return;
|
|
1233
|
+
default:
|
|
1234
|
+
console.error("用法:stew [pair|start|add|status]");
|
|
1235
|
+
process.exitCode = 1;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
main(process.argv[2], ...process.argv.slice(3)).catch((error) => {
|
|
1239
|
+
console.error(error.code === "EEXIST" ? "目标文件已存在。" : error.code ? "启动器操作失败,请检查本地目录权限和配置。" : error.message);
|
|
1240
|
+
process.exitCode = 1;
|
|
1241
|
+
});
|
|
1242
|
+
export {};
|