@mozhi0012/pi-terminal-worker 0.2.0 → 0.4.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/README.md +220 -169
- package/dist/controller.d.ts +9 -0
- package/dist/controller.d.ts.map +1 -1
- package/dist/controller.js +106 -53
- package/dist/controller.js.map +1 -1
- package/dist/launcher.d.ts +9 -1
- package/dist/launcher.d.ts.map +1 -1
- package/dist/launcher.js +95 -22
- package/dist/launcher.js.map +1 -1
- package/dist/lifecycle.d.ts +7 -0
- package/dist/lifecycle.d.ts.map +1 -1
- package/dist/lifecycle.js +4 -0
- package/dist/lifecycle.js.map +1 -1
- package/dist/multi-worker.d.ts +20 -0
- package/dist/multi-worker.d.ts.map +1 -1
- package/dist/multi-worker.js +53 -10
- package/dist/multi-worker.js.map +1 -1
- package/dist/protocol.d.ts +2 -0
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +2 -0
- package/dist/protocol.js.map +1 -1
- package/dist/team-config.d.ts +61 -0
- package/dist/team-config.d.ts.map +1 -0
- package/dist/team-config.js +195 -0
- package/dist/team-config.js.map +1 -0
- package/dist/terminal-multiplexer.d.ts +25 -0
- package/dist/terminal-multiplexer.d.ts.map +1 -0
- package/dist/terminal-multiplexer.js +102 -0
- package/dist/terminal-multiplexer.js.map +1 -0
- package/dist/tool-policy.d.ts +36 -0
- package/dist/tool-policy.d.ts.map +1 -0
- package/dist/tool-policy.js +199 -0
- package/dist/tool-policy.js.map +1 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.d.ts.map +1 -1
- package/dist/worker.js +9 -1
- package/dist/worker.js.map +1 -1
- package/package.json +78 -72
- package/runtime/bootstrap-support.mjs +68 -49
- package/runtime/bootstrap.mjs +328 -304
- package/runtime/terminal-support.mjs +63 -0
- package/src/controller.ts +2761 -2724
- package/src/launcher.ts +592 -517
- package/src/lifecycle.ts +289 -284
- package/src/multi-worker.ts +69 -9
- package/src/protocol.ts +5 -0
- package/src/team-config.ts +255 -0
- package/src/terminal-multiplexer.ts +108 -0
- package/src/tool-policy.ts +213 -0
- package/src/worker.ts +9 -1
package/src/multi-worker.ts
CHANGED
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
} from "./controller.js";
|
|
37
37
|
import { ProtocolErrorCode, resolveChildRole, type WorkerRole } from "./protocol.js";
|
|
38
38
|
import type { WorkerInstanceMetadata } from "./lifecycle.js";
|
|
39
|
+
import { resolveTeamStart } from "./team-config.js";
|
|
39
40
|
|
|
40
41
|
/** close 结果类型 (与 ControllerManager.handleWorkerClose 一致) */
|
|
41
42
|
type CloseResult = { ok: boolean; disposition: string; message: string };
|
|
@@ -43,6 +44,9 @@ type CloseResult = { ok: boolean; disposition: string; message: string };
|
|
|
43
44
|
/** 协调器内登记的一个 Worker 实例 */
|
|
44
45
|
export interface WorkerEntry {
|
|
45
46
|
readonly role: WorkerRole;
|
|
47
|
+
/** 通过 team.yaml 启动时的 team 和角色名 */
|
|
48
|
+
readonly team?: string;
|
|
49
|
+
readonly teamRole?: string;
|
|
46
50
|
readonly controllerId: string;
|
|
47
51
|
readonly workerId: string;
|
|
48
52
|
readonly taskId: string;
|
|
@@ -83,6 +87,9 @@ export interface MultiWorkerCoordinatorOptions {
|
|
|
83
87
|
}
|
|
84
88
|
|
|
85
89
|
export interface WorkerStartParams {
|
|
90
|
+
/** skill 目录名,配合 teamRole 从其 team.yaml 解析模型与权限 */
|
|
91
|
+
team?: string;
|
|
92
|
+
teamRole?: string;
|
|
86
93
|
role?: WorkerRole;
|
|
87
94
|
cwd: string;
|
|
88
95
|
title: string;
|
|
@@ -98,6 +105,8 @@ export interface WorkerStartParams {
|
|
|
98
105
|
/** worker_list 单条有界摘要(不含报告/事件明细,明细仍走 worker_status) */
|
|
99
106
|
export interface WorkerListSummary {
|
|
100
107
|
role: WorkerRole;
|
|
108
|
+
team?: string;
|
|
109
|
+
teamRole?: string;
|
|
101
110
|
workerId: string;
|
|
102
111
|
taskId: string;
|
|
103
112
|
title: string;
|
|
@@ -197,17 +206,41 @@ export class MultiWorkerCoordinator {
|
|
|
197
206
|
public getActiveChildCount(): number {
|
|
198
207
|
let count = 0;
|
|
199
208
|
for (const entry of this.entries.values()) {
|
|
200
|
-
|
|
201
|
-
if (inst) {
|
|
202
|
-
if (entry.controller.workerManager.hasActiveInstance() &&
|
|
203
|
-
inst.taskState !== "accepted" && inst.taskState !== "abandoned") count++;
|
|
204
|
-
} else if (entry.startPromise) {
|
|
205
|
-
count++;
|
|
206
|
-
}
|
|
209
|
+
if (this.isEntryActive(entry)) count++;
|
|
207
210
|
}
|
|
208
211
|
return count;
|
|
209
212
|
}
|
|
210
213
|
|
|
214
|
+
private isEntryActive(entry: WorkerEntry): boolean {
|
|
215
|
+
const inst = entry.controller.workerManager.getInstance();
|
|
216
|
+
if (inst) {
|
|
217
|
+
return entry.controller.workerManager.hasActiveInstance() &&
|
|
218
|
+
inst.taskState !== "accepted" && inst.taskState !== "abandoned";
|
|
219
|
+
}
|
|
220
|
+
return entry.startPromise !== null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** team.yaml 的数量上限;调用方须与登记在同一轮事件循环内完成,避免并发超限 */
|
|
224
|
+
private assertTeamCapacity(team: string, teamRole: string, maxConcurrent?: number, maxForRole?: number): void {
|
|
225
|
+
let teamCount = 0;
|
|
226
|
+
let roleCount = 0;
|
|
227
|
+
for (const entry of this.entries.values()) {
|
|
228
|
+
if (entry.team !== team || !this.isEntryActive(entry)) continue;
|
|
229
|
+
teamCount++;
|
|
230
|
+
if (entry.teamRole === teamRole) roleCount++;
|
|
231
|
+
}
|
|
232
|
+
if (maxConcurrent !== undefined && teamCount >= maxConcurrent) {
|
|
233
|
+
throw new Error(
|
|
234
|
+
`[TEAM_LIMIT_REACHED] team ${team} 已有 ${teamCount} 个存活实例,达到 limits.maxConcurrent=${maxConcurrent}。请先关闭已有实例或修改 team.yaml`,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
if (maxForRole !== undefined && roleCount >= maxForRole) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
`[TEAM_LIMIT_REACHED] 角色 ${team}/${teamRole} 已有 ${roleCount} 个存活实例,达到 max=${maxForRole}。请先关闭已有实例或修改 team.yaml`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
211
244
|
/** 当前登记实例数量 */
|
|
212
245
|
public get size(): number {
|
|
213
246
|
return this.entries.size;
|
|
@@ -235,6 +268,7 @@ export class MultiWorkerCoordinator {
|
|
|
235
268
|
const inst = entry.controller.workerManager.getInstance();
|
|
236
269
|
return {
|
|
237
270
|
role: entry.role,
|
|
271
|
+
...(entry.team ? { team: entry.team, teamRole: entry.teamRole } : {}),
|
|
238
272
|
workerId: entry.workerId,
|
|
239
273
|
taskId: entry.taskId,
|
|
240
274
|
title: truncateForList(inst?.title ?? "", WORKER_LIST_MAX_TITLE),
|
|
@@ -375,16 +409,20 @@ export class MultiWorkerCoordinator {
|
|
|
375
409
|
taskId: string;
|
|
376
410
|
revision: number;
|
|
377
411
|
message: string;
|
|
412
|
+
team?: { name: string; role: string; provider: string; model: string; thinkingLevel: string; write: string; configPath: string };
|
|
378
413
|
}> {
|
|
379
414
|
// dispose 一旦开始就不再接受新的启动,避免清理后重新创建 pipe/定时器
|
|
380
415
|
if (this.isDisposed) {
|
|
381
416
|
throw new Error(`[${ProtocolErrorCode.INVALID_STATE}] 协调器已释放,不能再启动新的 Worker`);
|
|
382
417
|
}
|
|
383
|
-
const
|
|
418
|
+
const team = resolveTeamStart(params);
|
|
419
|
+
const role = resolveChildRole(team ? team.tier : params.role);
|
|
420
|
+
if (team) this.assertTeamCapacity(team.team, team.teamRole, team.maxConcurrent, team.maxForRole);
|
|
384
421
|
const ids = this.generateUniqueIdentity();
|
|
385
422
|
const controller = this.createController();
|
|
386
423
|
const entry: WorkerEntry = {
|
|
387
424
|
role,
|
|
425
|
+
...(team ? { team: team.team, teamRole: team.teamRole } : {}),
|
|
388
426
|
controllerId: ids.controllerId,
|
|
389
427
|
workerId: ids.workerId,
|
|
390
428
|
taskId: ids.taskId,
|
|
@@ -404,7 +442,14 @@ export class MultiWorkerCoordinator {
|
|
|
404
442
|
const epoch = this.epoch;
|
|
405
443
|
|
|
406
444
|
// 在途 start 由 entry 自己持有:dispose 可对每个实例独立取消+等待,互不阻塞
|
|
407
|
-
const
|
|
445
|
+
const { team: _team, teamRole: _teamRole, ...startParams } = params;
|
|
446
|
+
const startPromise = controller.handleWorkerStart(
|
|
447
|
+
team
|
|
448
|
+
? { ...startParams, role, provider: team.provider, model: team.model, thinkingLevel: team.thinkingLevel }
|
|
449
|
+
: { ...startParams, role },
|
|
450
|
+
{},
|
|
451
|
+
{ ids, toolPolicy: team?.policy },
|
|
452
|
+
);
|
|
408
453
|
entry.startPromise = startPromise;
|
|
409
454
|
try {
|
|
410
455
|
const res = await startPromise;
|
|
@@ -414,6 +459,19 @@ export class MultiWorkerCoordinator {
|
|
|
414
459
|
taskId: entry.taskId,
|
|
415
460
|
revision: res.revision,
|
|
416
461
|
message: res.message,
|
|
462
|
+
...(team
|
|
463
|
+
? {
|
|
464
|
+
team: {
|
|
465
|
+
name: team.team,
|
|
466
|
+
role: team.teamRole,
|
|
467
|
+
provider: team.provider,
|
|
468
|
+
model: team.model,
|
|
469
|
+
thinkingLevel: team.thinkingLevel,
|
|
470
|
+
write: team.write,
|
|
471
|
+
configPath: team.configPath,
|
|
472
|
+
},
|
|
473
|
+
}
|
|
474
|
+
: {}),
|
|
417
475
|
};
|
|
418
476
|
} catch (err: unknown) {
|
|
419
477
|
// 仅“进程已确认退出/参数未创建进程” (名额已释放) 才回收本次登记;
|
|
@@ -672,6 +730,8 @@ export class MultiWorkerCoordinator {
|
|
|
672
730
|
"Worker 的关键事件(交付/提问/阻塞/停止/断连等)会主动唤醒本会话:空闲时开新轮,忙碌时 followUp 排队,无需轮询。",
|
|
673
731
|
executionMode: "parallel",
|
|
674
732
|
parameters: Type.Object({
|
|
733
|
+
team: Type.Optional(Type.String({ description: "可选:skill 目录名。与 teamRole 同时提供时,模型、层级和权限都从该 skill 的 team.yaml 解析,此时不能再传 role、provider、model、thinkingLevel" })),
|
|
734
|
+
teamRole: Type.Optional(Type.String({ description: "可选:team.yaml 中定义的角色名" })),
|
|
675
735
|
role: Type.Optional(Type.Union([Type.Literal("worker"), Type.Literal("lead")], { description: "角色,默认 worker;仅顶层主控可启动 lead" })),
|
|
676
736
|
cwd: Type.String({ description: "Worker 工作的根目录 (必须为绝对路径)" }),
|
|
677
737
|
title: Type.String({ description: "Windows Terminal 窗口的标题" }),
|
package/src/protocol.ts
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
* 双向命名管道 JSONL 通讯
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
import { MAX_TOOL_POLICY_SIZE } from "./tool-policy.js";
|
|
7
|
+
|
|
6
8
|
export const PROTOCOL_VERSION = 1;
|
|
7
9
|
|
|
8
10
|
export type WorkerRole = "worker" | "lead";
|
|
@@ -178,6 +180,8 @@ export interface LaunchPayload {
|
|
|
178
180
|
model?: string;
|
|
179
181
|
/** 可选:思考级别 off|minimal|low|medium|high|xhigh|max */
|
|
180
182
|
thinkingLevel?: string;
|
|
183
|
+
/** 可选:team.yaml 解析出的工具策略 (JSON),由 bootstrap 写入 Worker 环境变量 */
|
|
184
|
+
toolPolicy?: string;
|
|
181
185
|
}
|
|
182
186
|
|
|
183
187
|
export interface TerminatePayload {
|
|
@@ -588,6 +592,7 @@ export function validatePayload(type: string, payload: unknown): unknown {
|
|
|
588
592
|
requireString(p.workerPipePath, "workerPipePath", MAX_PATH_FIELD_SIZE);
|
|
589
593
|
optionalString(p.provider, "provider", 256);
|
|
590
594
|
optionalString(p.model, "model", 256);
|
|
595
|
+
optionalString(p.toolPolicy, "toolPolicy", MAX_TOOL_POLICY_SIZE);
|
|
591
596
|
const thinkingLevel = optionalString(p.thinkingLevel, "thinkingLevel", 256);
|
|
592
597
|
if (thinkingLevel !== undefined && !(THINKING_LEVELS as readonly string[]).includes(thinkingLevel)) {
|
|
593
598
|
throw new ProtocolValidationError(
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* team.yaml:把角色的模型、权限和数量上限从 skill 提示词中分离,由插件校验并强制执行。
|
|
3
|
+
*
|
|
4
|
+
* 每次 worker_start 都重新读取文件,修改后下一次启动立即生效,不做缓存。
|
|
5
|
+
*
|
|
6
|
+
* 只读取用户级 skill 目录,不读取工作目录下的 .pi:主控启动 Worker 时目标目录可能尚未被信任,
|
|
7
|
+
* 项目文件不能决定模型和写权限。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import { parse as parseYaml } from "yaml";
|
|
14
|
+
import { THINKING_LEVELS, type WorkerRole } from "./protocol.js";
|
|
15
|
+
import { encodeToolPolicy, type ToolPolicy, type WriteMode } from "./tool-policy.js";
|
|
16
|
+
|
|
17
|
+
export const TEAM_CONFIG_FILE = "team.yaml";
|
|
18
|
+
const TEAM_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
19
|
+
const ROLE_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
20
|
+
const WRITE_MODES: readonly WriteMode[] = ["none", "scoped", "any"];
|
|
21
|
+
|
|
22
|
+
export interface TeamRoleConfig {
|
|
23
|
+
tier: WorkerRole;
|
|
24
|
+
provider: string;
|
|
25
|
+
model: string;
|
|
26
|
+
thinking: string;
|
|
27
|
+
write: WriteMode;
|
|
28
|
+
/** 本角色同时存活的实例上限 */
|
|
29
|
+
max?: number;
|
|
30
|
+
denyTools: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface TeamConfig {
|
|
34
|
+
/** 本 team 在当前主控会话内同时存活的实例上限 */
|
|
35
|
+
maxConcurrent?: number;
|
|
36
|
+
roles: Map<string, TeamRoleConfig>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** worker_start 中与 team 相关的入参 */
|
|
40
|
+
export interface TeamStartParams {
|
|
41
|
+
team?: string;
|
|
42
|
+
teamRole?: string;
|
|
43
|
+
role?: WorkerRole;
|
|
44
|
+
cwd: string;
|
|
45
|
+
provider?: string;
|
|
46
|
+
model?: string;
|
|
47
|
+
thinkingLevel?: string;
|
|
48
|
+
allowedPaths?: string[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ResolvedTeamStart {
|
|
52
|
+
team: string;
|
|
53
|
+
teamRole: string;
|
|
54
|
+
configPath: string;
|
|
55
|
+
tier: WorkerRole;
|
|
56
|
+
provider: string;
|
|
57
|
+
model: string;
|
|
58
|
+
thinkingLevel: string;
|
|
59
|
+
write: WriteMode;
|
|
60
|
+
maxConcurrent?: number;
|
|
61
|
+
maxForRole?: number;
|
|
62
|
+
policy: ToolPolicy;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function configError(message: string): Error {
|
|
66
|
+
return new Error(`[TEAM_CONFIG_ERROR] ${message}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function requirePlainObject(value: unknown, label: string): Record<string, unknown> {
|
|
70
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
71
|
+
throw configError(`${label} 必须是对象`);
|
|
72
|
+
}
|
|
73
|
+
return value as Record<string, unknown>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function rejectUnknownKeys(value: Record<string, unknown>, allowed: readonly string[], label: string): void {
|
|
77
|
+
for (const key of Object.keys(value)) {
|
|
78
|
+
if (!allowed.includes(key)) {
|
|
79
|
+
throw configError(`${label} 含未知字段 "${key}",可用字段:${allowed.join(", ")}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function requireNonEmptyString(value: unknown, label: string): string {
|
|
85
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
86
|
+
throw configError(`${label} 必须是非空字符串`);
|
|
87
|
+
}
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function optionalPositiveInteger(value: unknown, label: string): number | undefined {
|
|
92
|
+
if (value === undefined) return undefined;
|
|
93
|
+
if (!Number.isSafeInteger(value) || (value as number) <= 0) {
|
|
94
|
+
throw configError(`${label} 必须是正整数`);
|
|
95
|
+
}
|
|
96
|
+
return value as number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parseRole(value: unknown, label: string): TeamRoleConfig {
|
|
100
|
+
const raw = requirePlainObject(value, label);
|
|
101
|
+
rejectUnknownKeys(raw, ["tier", "provider", "model", "thinking", "write", "max", "denyTools"], label);
|
|
102
|
+
|
|
103
|
+
const tier = raw.tier ?? "worker";
|
|
104
|
+
if (tier !== "worker" && tier !== "lead") {
|
|
105
|
+
throw configError(`${label}.tier 必须是 worker 或 lead`);
|
|
106
|
+
}
|
|
107
|
+
const thinking = requireNonEmptyString(raw.thinking, `${label}.thinking`);
|
|
108
|
+
if (!(THINKING_LEVELS as readonly string[]).includes(thinking)) {
|
|
109
|
+
throw configError(`${label}.thinking 必须是以下之一:${THINKING_LEVELS.join(" | ")}`);
|
|
110
|
+
}
|
|
111
|
+
if (!WRITE_MODES.includes(raw.write as WriteMode)) {
|
|
112
|
+
throw configError(`${label}.write 必须是以下之一:${WRITE_MODES.join(" | ")}`);
|
|
113
|
+
}
|
|
114
|
+
const denyTools = raw.denyTools ?? [];
|
|
115
|
+
if (!Array.isArray(denyTools) || !denyTools.every((item) => typeof item === "string" && item !== "")) {
|
|
116
|
+
throw configError(`${label}.denyTools 必须是非空字符串数组`);
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
tier,
|
|
120
|
+
provider: requireNonEmptyString(raw.provider, `${label}.provider`),
|
|
121
|
+
model: requireNonEmptyString(raw.model, `${label}.model`),
|
|
122
|
+
thinking,
|
|
123
|
+
write: raw.write as WriteMode,
|
|
124
|
+
max: optionalPositiveInteger(raw.max, `${label}.max`),
|
|
125
|
+
denyTools: denyTools as string[],
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 严格解析:未知字段一律报错,防止拼错的限制项被静默忽略 */
|
|
130
|
+
export function parseTeamConfig(text: string, source: string): TeamConfig {
|
|
131
|
+
let parsed: unknown;
|
|
132
|
+
try {
|
|
133
|
+
parsed = parseYaml(text);
|
|
134
|
+
} catch (err: unknown) {
|
|
135
|
+
throw configError(`${source} 不是合法的 YAML:${err instanceof Error ? err.message : String(err)}`);
|
|
136
|
+
}
|
|
137
|
+
const raw = requirePlainObject(parsed, source);
|
|
138
|
+
rejectUnknownKeys(raw, ["version", "limits", "roles"], source);
|
|
139
|
+
if (raw.version !== 1) {
|
|
140
|
+
throw configError(`${source} 的 version 必须是 1`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
let maxConcurrent: number | undefined;
|
|
144
|
+
if (raw.limits !== undefined) {
|
|
145
|
+
const limits = requirePlainObject(raw.limits, `${source} 的 limits`);
|
|
146
|
+
rejectUnknownKeys(limits, ["maxConcurrent"], `${source} 的 limits`);
|
|
147
|
+
maxConcurrent = optionalPositiveInteger(limits.maxConcurrent, `${source} 的 limits.maxConcurrent`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const rawRoles = requirePlainObject(raw.roles, `${source} 的 roles`);
|
|
151
|
+
const roles = new Map<string, TeamRoleConfig>();
|
|
152
|
+
for (const [name, value] of Object.entries(rawRoles)) {
|
|
153
|
+
if (!ROLE_NAME_PATTERN.test(name)) {
|
|
154
|
+
throw configError(`${source} 的角色名 "${name}" 非法,只能用小写字母、数字、- 和 _,且以字母开头`);
|
|
155
|
+
}
|
|
156
|
+
roles.set(name, parseRole(value, `${source} 的 roles.${name}`));
|
|
157
|
+
}
|
|
158
|
+
if (roles.size === 0) {
|
|
159
|
+
throw configError(`${source} 至少要定义一个角色`);
|
|
160
|
+
}
|
|
161
|
+
return { maxConcurrent, roles };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function agentDir(env: NodeJS.ProcessEnv): string {
|
|
165
|
+
const configured = env.PI_CODING_AGENT_DIR?.trim();
|
|
166
|
+
if (!configured) return path.join(homedir(), ".pi", "agent");
|
|
167
|
+
if (configured === "~") return homedir();
|
|
168
|
+
return configured.startsWith("~/") || configured.startsWith("~\\")
|
|
169
|
+
? path.join(homedir(), configured.slice(2))
|
|
170
|
+
: path.resolve(configured);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function teamConfigPath(team: string, env: NodeJS.ProcessEnv = process.env): string {
|
|
174
|
+
return path.join(agentDir(env), "skills", team, TEAM_CONFIG_FILE);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 允许目录写法 dir、dir/、dir/*、dir/**;其他通配符无法精确校验,直接拒绝 */
|
|
178
|
+
export function normalizeAllowedPaths(paths: readonly string[], cwd: string): string[] {
|
|
179
|
+
return paths.map((raw) => {
|
|
180
|
+
const stripped = raw.trim().replace(/[\\/]\*{1,2}$/, "");
|
|
181
|
+
if (stripped === "" || /[*?[\]{}]/.test(stripped)) {
|
|
182
|
+
throw configError(`allowedPaths 项 "${raw}" 无法精确校验,请使用文件或目录路径(可带 /** 后缀)`);
|
|
183
|
+
}
|
|
184
|
+
return path.resolve(cwd, stripped);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 解析 worker_start 的 team 参数。未使用 team 时返回 null,保持原有行为。
|
|
190
|
+
* 文件读取是同步的:调用方可以在同一轮事件循环内完成名额检查与登记,避免并发超限。
|
|
191
|
+
*/
|
|
192
|
+
export function resolveTeamStart(
|
|
193
|
+
params: TeamStartParams,
|
|
194
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
195
|
+
): ResolvedTeamStart | null {
|
|
196
|
+
const { team, teamRole } = params;
|
|
197
|
+
if (team === undefined && teamRole === undefined) return null;
|
|
198
|
+
if (!path.isAbsolute(params.cwd)) {
|
|
199
|
+
throw configError(`cwd 必须是绝对路径: "${params.cwd}"`);
|
|
200
|
+
}
|
|
201
|
+
if (team === undefined || teamRole === undefined) {
|
|
202
|
+
throw configError("team 和 teamRole 必须同时提供");
|
|
203
|
+
}
|
|
204
|
+
if (!TEAM_NAME_PATTERN.test(team)) {
|
|
205
|
+
throw configError(`team 名称 "${team}" 非法,应为 skill 目录名`);
|
|
206
|
+
}
|
|
207
|
+
// 模型和层级以 team.yaml 为唯一来源,调用方不能在单次调用里覆盖
|
|
208
|
+
for (const field of ["role", "provider", "model", "thinkingLevel"] as const) {
|
|
209
|
+
if (params[field] !== undefined) {
|
|
210
|
+
throw configError(`使用 team 时不能同时传 ${field},请修改 team.yaml`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const configPath = teamConfigPath(team, env);
|
|
215
|
+
if (!fs.existsSync(configPath)) {
|
|
216
|
+
throw configError(`找不到 team "${team}" 的配置:${configPath}`);
|
|
217
|
+
}
|
|
218
|
+
const config = parseTeamConfig(fs.readFileSync(configPath, "utf8"), configPath);
|
|
219
|
+
const role = config.roles.get(teamRole);
|
|
220
|
+
if (!role) {
|
|
221
|
+
throw configError(`${configPath} 没有角色 "${teamRole}",可用角色:${[...config.roles.keys()].join(", ")}`);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const allowedPaths = normalizeAllowedPaths(params.allowedPaths ?? [], params.cwd);
|
|
225
|
+
if (role.write === "scoped" && allowedPaths.length === 0) {
|
|
226
|
+
throw configError(`角色 ${team}/${teamRole} 是 write: scoped,必须提供非空的 allowedPaths`);
|
|
227
|
+
}
|
|
228
|
+
if (role.write === "none" && allowedPaths.length > 0) {
|
|
229
|
+
throw configError(`角色 ${team}/${teamRole} 是只读角色 (write: none),不能提供 allowedPaths`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const policy: ToolPolicy = {
|
|
233
|
+
label: `${team}/${teamRole}`,
|
|
234
|
+
write: role.write,
|
|
235
|
+
cwd: params.cwd,
|
|
236
|
+
allowedPaths,
|
|
237
|
+
denyTools: role.denyTools,
|
|
238
|
+
};
|
|
239
|
+
// 在开窗之前发现超限,而不是启动到一半才失败
|
|
240
|
+
encodeToolPolicy(policy);
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
team,
|
|
244
|
+
teamRole,
|
|
245
|
+
configPath,
|
|
246
|
+
tier: role.tier,
|
|
247
|
+
provider: role.provider,
|
|
248
|
+
model: role.model,
|
|
249
|
+
thinkingLevel: role.thinking,
|
|
250
|
+
write: role.write,
|
|
251
|
+
maxConcurrent: config.maxConcurrent,
|
|
252
|
+
maxForRole: role.max,
|
|
253
|
+
policy,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Multi-step CLI launchers. The Windows launchWorkerWindow API remains synchronous. */
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { assertCmdSafeValues, type TerminalLaunchSpec } from "./launcher.js";
|
|
4
|
+
|
|
5
|
+
export class TerminalSpawnError extends Error {
|
|
6
|
+
constructor(public readonly backend: string, public readonly cause: Error) {
|
|
7
|
+
super(`终端后端 ${backend} 启动失败: ${cause.message}`);
|
|
8
|
+
this.name = "TerminalSpawnError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type TerminalCommandRunner = (
|
|
13
|
+
command: string, args: string[], options: { cwd: string; env: NodeJS.ProcessEnv },
|
|
14
|
+
) => Promise<string>;
|
|
15
|
+
|
|
16
|
+
export const runTerminalCommand: TerminalCommandRunner = (command, args, options) => new Promise((resolve, reject) => {
|
|
17
|
+
execFile(command, args, { ...options, shell: false, windowsHide: true, encoding: "utf8", timeout: 10_000, maxBuffer: 1024 * 1024 },
|
|
18
|
+
(error, stdout, stderr) => error ? reject(new Error(`${error.message}${stderr ? `: ${stderr.trim()}` : ""}`)) : resolve(stdout));
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export interface TerminalHandle {
|
|
22
|
+
backend: "herdr" | "tmux";
|
|
23
|
+
paneId?: string;
|
|
24
|
+
windowId?: string;
|
|
25
|
+
sessionName?: string;
|
|
26
|
+
close: () => Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Only controlled variable references are sent to the interactive shell. */
|
|
30
|
+
export function buildHerdrRunCommand(shellName: string, values: Record<string, string>): string {
|
|
31
|
+
const shell = shellName.replace(/\\/g, "/").split("/").pop()!.toLowerCase().replace(/\.exe$/, "");
|
|
32
|
+
if (shell === "powershell" || shell === "pwsh") {
|
|
33
|
+
return "& $env:PITW_BOOTSTRAP_NODE $env:PITW_BOOTSTRAP_FILE --descriptor $env:PITW_BOOTSTRAP_DESC";
|
|
34
|
+
}
|
|
35
|
+
if (shell === "cmd") {
|
|
36
|
+
assertCmdSafeValues(Object.entries(values));
|
|
37
|
+
return '"%PITW_BOOTSTRAP_NODE%" "%PITW_BOOTSTRAP_FILE%" --descriptor %PITW_BOOTSTRAP_DESC%';
|
|
38
|
+
}
|
|
39
|
+
if (["bash", "zsh", "sh", "dash", "ksh", "fish"].includes(shell)) {
|
|
40
|
+
return '"$PITW_BOOTSTRAP_NODE" "$PITW_BOOTSTRAP_FILE" --descriptor "$PITW_BOOTSTRAP_DESC"';
|
|
41
|
+
}
|
|
42
|
+
throw new Error(`不支持的 herdr pane shell: ${shellName}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function launchMultiplexer(
|
|
46
|
+
spec: TerminalLaunchSpec,
|
|
47
|
+
{ run = runTerminalCommand, assertActive = () => {} }: {
|
|
48
|
+
run?: TerminalCommandRunner;
|
|
49
|
+
assertActive?: () => void;
|
|
50
|
+
} = {},
|
|
51
|
+
): Promise<TerminalHandle> {
|
|
52
|
+
const options = { cwd: spec.cwd, env: { ...process.env } };
|
|
53
|
+
let handle: TerminalHandle | undefined;
|
|
54
|
+
function makeHandle(data: Omit<TerminalHandle, "close">, closeArgs: string[]): TerminalHandle {
|
|
55
|
+
let closing: Promise<void> | undefined;
|
|
56
|
+
return { ...data, close: () => closing ??= run(spec.command, closeArgs, options).then(() => {}, () => {}) };
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
assertActive();
|
|
60
|
+
if (spec.backend === "tmux") {
|
|
61
|
+
const output = await run(spec.command, spec.args, options);
|
|
62
|
+
const windowId = output.trim();
|
|
63
|
+
// A new session's name is already known, including if output parsing fails.
|
|
64
|
+
if (spec.tmuxSession) handle = makeHandle({ backend: "tmux", sessionName: spec.tmuxSession, windowId }, ["kill-session", "-t", spec.tmuxSession]);
|
|
65
|
+
else if (/^@\d+$/.test(windowId)) handle = makeHandle({ backend: "tmux", windowId }, ["kill-window", "-t", windowId]);
|
|
66
|
+
assertActive();
|
|
67
|
+
if (!/^@\d+$/.test(windowId)) throw new Error(`tmux 未返回窗口 ID: ${output}`);
|
|
68
|
+
return handle!;
|
|
69
|
+
}
|
|
70
|
+
if (spec.backend !== "herdr" || !spec.workerCommand) throw new Error("缺少 herdr 启动描述");
|
|
71
|
+
const values = {
|
|
72
|
+
PITW_BOOTSTRAP_NODE: spec.workerCommand[0],
|
|
73
|
+
PITW_BOOTSTRAP_FILE: spec.workerCommand[1],
|
|
74
|
+
PITW_BOOTSTRAP_DESC: spec.workerCommand[3],
|
|
75
|
+
PITW_BOOTSTRAP_HERDR: spec.command,
|
|
76
|
+
};
|
|
77
|
+
// Fixed right split preserves focus and avoids a separate layout race/CLI round-trip.
|
|
78
|
+
const split = await run(spec.command, ["pane", "split", "--current", "--direction", "right", "--cwd", spec.cwd,
|
|
79
|
+
"--no-focus", ...Object.entries(values).flatMap(([key, value]) => ["--env", `${key}=${value}`])], options);
|
|
80
|
+
const paneId = JSON.parse(split)?.result?.pane?.pane_id;
|
|
81
|
+
if (typeof paneId !== "string" || !paneId) throw new Error("herdr split 未返回 pane_id");
|
|
82
|
+
handle = makeHandle({ backend: "herdr", paneId }, ["pane", "close", paneId]);
|
|
83
|
+
assertActive();
|
|
84
|
+
try { await run(spec.command, ["pane", "rename", paneId, spec.title], options); } catch { /* title is cosmetic */ }
|
|
85
|
+
assertActive();
|
|
86
|
+
let shell: string | undefined;
|
|
87
|
+
for (let attempt = 0; attempt < 40; attempt++) {
|
|
88
|
+
const output = await run(spec.command, ["pane", "process-info", "--pane", paneId], options);
|
|
89
|
+
assertActive();
|
|
90
|
+
const info = JSON.parse(output)?.result?.process_info;
|
|
91
|
+
const process = info?.foreground_processes?.find((p: { pid: number }) => p.pid === info.shell_pid);
|
|
92
|
+
shell = process?.argv0 ?? process?.name;
|
|
93
|
+
if (shell) break;
|
|
94
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
95
|
+
assertActive();
|
|
96
|
+
}
|
|
97
|
+
if (!shell) throw new Error("herdr pane shell 尚未就绪");
|
|
98
|
+
const command = buildHerdrRunCommand(shell, values);
|
|
99
|
+
await run(spec.command, ["pane", "run", paneId, command], options);
|
|
100
|
+
assertActive();
|
|
101
|
+
return handle;
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (handle) await handle.close();
|
|
104
|
+
// A cancellation must never turn into a fallback launch in a new session.
|
|
105
|
+
assertActive();
|
|
106
|
+
throw new TerminalSpawnError(spec.backend, error instanceof Error ? error : new Error(String(error)));
|
|
107
|
+
}
|
|
108
|
+
}
|