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