@az-zephyr/slate 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/LICENSE +21 -0
- package/README.en.md +107 -0
- package/README.md +106 -2
- package/bin/slate.mjs +226 -0
- package/dist/agent/chunk-BVWXAL54.js +3654 -0
- package/dist/agent/cli.js +6 -0
- package/dist/agent/multi.js +59 -0
- package/dist/api/001_initial.sql +127 -0
- package/dist/api/002_project_assistant.sql +24 -0
- package/dist/api/003_card_decisions.sql +20 -0
- package/dist/api/004_card_default_agent.sql +3 -0
- package/dist/api/005_card_attachments.sql +24 -0
- package/dist/api/006_comment_attachments.sql +7 -0
- package/dist/api/007_participant_last_outcome.sql +6 -0
- package/dist/api/008_output_attachments.sql +7 -0
- package/dist/api/009_card_agent_runs.sql +23 -0
- package/dist/api/server.js +4567 -0
- package/dist/api/server.js.map +1 -0
- package/dist/web/assets/abnfDiagram-XWFEHMT6-DmNFXSdi.js +1 -0
- package/dist/web/assets/architectureDiagram-CSQXQB3N-BTCN41JR.js +36 -0
- package/dist/web/assets/blockDiagram-BEDRHYPZ-BUJZDqr0.js +140 -0
- package/dist/web/assets/bpmnIcons-APHXDYXF-ByGoYv9M.js +1 -0
- package/dist/web/assets/c4Diagram-M2UUVUY5-CoTmMGy5.js +38 -0
- package/dist/web/assets/chunk-2Q5K7J3B-DN1oTl6j.js +1 -0
- package/dist/web/assets/chunk-3BJB4PZV-f0-m4Ag2.js +1 -0
- package/dist/web/assets/chunk-3GCGMST5-79GFiiwz.js +1 -0
- package/dist/web/assets/chunk-5VM5RSS4-D8XyNr_K.js +15 -0
- package/dist/web/assets/chunk-7U7NFRK5-CwjNfj8w.js +88 -0
- package/dist/web/assets/chunk-CNRTWJTD-CrX82YZ2.js +1 -0
- package/dist/web/assets/chunk-D5HYT7QG-DLlJaHjh.js +1 -0
- package/dist/web/assets/chunk-EBZ3SEQC-DYMBSe-a.js +2 -0
- package/dist/web/assets/chunk-JWPE2WC7-D7hN7LFG.js +1 -0
- package/dist/web/assets/chunk-KTR4FSNJ-DNqOwqFL.js +1 -0
- package/dist/web/assets/chunk-XXDRQBXY-ZgzK0pt4.js +1 -0
- package/dist/web/assets/classDiagram-v2-IZLYA2OM-CA7bnKxc.js +217 -0
- package/dist/web/assets/cose-bilkent-JH36ORCC-DOKkzmxA.js +1 -0
- package/dist/web/assets/cynefin-EF2NZ3EQ-C-bSVtsc.js +141 -0
- package/dist/web/assets/cynefinDiagram-NJNITYFG-C37MEEtf.js +62 -0
- package/dist/web/assets/cytoscape.esm-Bw5aGq32.js +332 -0
- package/dist/web/assets/d3-scale-4DPf7zan.js +1 -0
- package/dist/web/assets/dagre-KIHZ2IZ3-9ncwFAl9.js +4 -0
- package/dist/web/assets/diagram-7YQZDPLS-B5nOmdUq.js +41 -0
- package/dist/web/assets/diagram-QBROCOUO-C2R6lDiO.js +200 -0
- package/dist/web/assets/diagram-RJJCUUZO-C6CCweHA.js +30 -0
- package/dist/web/assets/diagram-WERXNKYE-BMvmqzmc.js +24 -0
- package/dist/web/assets/diagram-YHHI257C-mq9rFYCr.js +3 -0
- package/dist/web/assets/diagram-YR4HJLHV-GnLZxfuk.js +24 -0
- package/dist/web/assets/ebnfDiagram-N527522P-BD49AZHw.js +1 -0
- package/dist/web/assets/elk-O5DQBFGD-BPi3gK_q.js +27 -0
- package/dist/web/assets/erDiagram-GT5GOJPG-v00zB8rw.js +99 -0
- package/dist/web/assets/flowDiagram-JAYNFW54-DIf4aoDB.js +213 -0
- package/dist/web/assets/ganttDiagram-3PRQTZWP-DRl_shHP.js +292 -0
- package/dist/web/assets/gitGraphDiagram-VXDFKS5L-2RrHppJt.js +106 -0
- package/dist/web/assets/graph-Bn3Yngep.js +1 -0
- package/dist/web/assets/grid-E2QIVN74-BuI-3sqA.js +1 -0
- package/dist/web/assets/index-5BTf4y0R.css +1 -0
- package/dist/web/assets/index-CtfDl2Kw.js +358 -0
- package/dist/web/assets/infoDiagram-ATMJ4U3S-afgUHtXU.js +2 -0
- package/dist/web/assets/ishikawaDiagram-S3EKX5GW-BsIUfApm.js +70 -0
- package/dist/web/assets/journeyDiagram-POQNLL5X-BM1Liuxy.js +139 -0
- package/dist/web/assets/kanban-definition-BH5XI6FM-Bz439vDv.js +89 -0
- package/dist/web/assets/katex-Be3d8Y4U.js +257 -0
- package/dist/web/assets/mermaid.core-CDkqDmQh.js +314 -0
- package/dist/web/assets/mindmap-definition-WVAN44T4-DcgvDd37.js +98 -0
- package/dist/web/assets/pegDiagram-D4NLKWP3-Bs1FcfRL.js +1 -0
- package/dist/web/assets/pieDiagram-36ENHN4W-CX3-kIFy.js +39 -0
- package/dist/web/assets/quadrantDiagram-ZQUDMS73-CrSg-66H.js +7 -0
- package/dist/web/assets/railroadDiagram-JIZHGYPL-DBm7mKc_.js +1 -0
- package/dist/web/assets/render-VIF2ZAQL-CjnzRbOQ.js +2 -0
- package/dist/web/assets/requirementDiagram-AXW2TVFA--vkT5OaJ.js +84 -0
- package/dist/web/assets/sankeyDiagram-FBCJTAIF-CXyuNpgP.js +40 -0
- package/dist/web/assets/sequenceDiagram-3LA2ROMG-Cfn5c7T5.js +169 -0
- package/dist/web/assets/sizeCapture-2Q2CQKSF-CQJexuw3.js +1 -0
- package/dist/web/assets/stateDiagram-v2-XZFR63ZJ-W23Y_4Yd.js +291 -0
- package/dist/web/assets/swimlanes-YQL5WMAO-B8ymV9uv.js +1 -0
- package/dist/web/assets/swimlanesDiagram-BA3ZWDFA-ClHf-9J2.js +8 -0
- package/dist/web/assets/timeline-definition-7Z437IG3-BElgSf_v.js +120 -0
- package/dist/web/assets/usecaseDiagram-RDK6N6HP-BfopeYcl.js +370 -0
- package/dist/web/assets/vennDiagram-SHRQU5PJ-034PLwGh.js +34 -0
- package/dist/web/assets/wardleyDiagram-F3OXNVQS-Cmiyei3a.js +78 -0
- package/dist/web/assets/xychartDiagram-GDYJKCDI-DxF4glgl.js +7 -0
- package/dist/web/index.html +13 -0
- package/package.json +42 -4
- package/scripts/git-worktree.mjs +63 -0
- package/scripts/slate-cli.mjs +851 -0
- package/skills/slate-card/SKILL.md +109 -0
|
@@ -0,0 +1,3654 @@
|
|
|
1
|
+
// src/cli.ts
|
|
2
|
+
import { mkdir as mkdir5 } from "fs/promises";
|
|
3
|
+
import path10 from "path";
|
|
4
|
+
import { parseArgs } from "util";
|
|
5
|
+
|
|
6
|
+
// ../../packages/contracts/src/index.ts
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
var cardStatusSchema = z.enum(["todo", "doing", "review", "done"]);
|
|
9
|
+
var agentAllowedStatusSchema = z.enum(["todo", "doing", "review"]);
|
|
10
|
+
var prioritySchema = z.enum(["high", "medium", "low"]);
|
|
11
|
+
var driverTypeSchema = z.enum(["codex", "claude-code", "antigravity"]);
|
|
12
|
+
var driverLabels = {
|
|
13
|
+
codex: "Codex",
|
|
14
|
+
"claude-code": "Claude Code",
|
|
15
|
+
antigravity: "Antigravity"
|
|
16
|
+
};
|
|
17
|
+
var authModeSchema = z.enum(["device_flow", "local_session", "api_key", "none"]);
|
|
18
|
+
var loginStateSchema = z.enum(["unknown", "logged_in", "logged_out", "expired", "error"]);
|
|
19
|
+
var loginRequestStatusSchema = z.enum([
|
|
20
|
+
"pending",
|
|
21
|
+
"starting",
|
|
22
|
+
"waiting_user",
|
|
23
|
+
"succeeded",
|
|
24
|
+
"failed",
|
|
25
|
+
"cancelled",
|
|
26
|
+
"expired"
|
|
27
|
+
]);
|
|
28
|
+
var parallelModeSchema = z.enum(["auto", "worktree", "isolated_dir", "shared"]);
|
|
29
|
+
var shortText = z.string().trim().min(1).max(200);
|
|
30
|
+
var optionalShortText = z.string().trim().max(200).default("");
|
|
31
|
+
var tagSchema = z.string().trim().min(1).max(40);
|
|
32
|
+
var pathText = z.string().trim().max(1e3);
|
|
33
|
+
var longText = z.string().trim().max(5e4);
|
|
34
|
+
var checklistItemSchema = z.object({
|
|
35
|
+
id: z.string().trim().min(1).max(64),
|
|
36
|
+
text: z.string().trim().min(1).max(500),
|
|
37
|
+
done: z.boolean().default(false),
|
|
38
|
+
updatedBy: z.string().trim().max(200).optional()
|
|
39
|
+
}).strict();
|
|
40
|
+
var checklistSchema = z.array(checklistItemSchema).max(100).refine((items) => new Set(items.map((i) => i.id)).size === items.length, "\u6E05\u5355\u9879 ID \u4E0D\u80FD\u91CD\u590D");
|
|
41
|
+
var httpUrlSchema = (max) => z.string().trim().url().max(max).refine((v) => /^https?:\/\//i.test(v), "\u4EC5\u652F\u6301 http/https \u94FE\u63A5");
|
|
42
|
+
var ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;
|
|
43
|
+
var CARD_MAX_ATTACHMENTS = 20;
|
|
44
|
+
var COMMENT_MAX_ATTACHMENTS = 10;
|
|
45
|
+
var IMAGE_ATTACHMENT_MIME_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
|
|
46
|
+
var IMAGE_ATTACHMENT_ACCEPT = IMAGE_ATTACHMENT_MIME_TYPES.join(",");
|
|
47
|
+
var attachmentKindSchema = z.enum(["image", "file"]);
|
|
48
|
+
var attachmentCloneSchema = z.object({
|
|
49
|
+
projectId: z.string().uuid(),
|
|
50
|
+
attachmentIds: z.array(z.string().uuid()).min(1).max(CARD_MAX_ATTACHMENTS)
|
|
51
|
+
}).strict();
|
|
52
|
+
var OUTPUT_CONTENT_MAX_CHARS = 2e5;
|
|
53
|
+
var cardOutputInputSchema = z.object({
|
|
54
|
+
label: shortText.optional(),
|
|
55
|
+
path: pathText.optional(),
|
|
56
|
+
branch: z.string().trim().max(200).optional(),
|
|
57
|
+
summary: z.string().trim().max(2e3).optional(),
|
|
58
|
+
url: httpUrlSchema(2e3).optional(),
|
|
59
|
+
content: z.string().max(OUTPUT_CONTENT_MAX_CHARS).optional(),
|
|
60
|
+
filename: z.string().trim().min(1).max(255).optional(),
|
|
61
|
+
mimeType: z.string().trim().min(1).max(128).optional(),
|
|
62
|
+
attachmentId: z.string().uuid().optional()
|
|
63
|
+
}).strict().superRefine((val, ctx) => {
|
|
64
|
+
const hasIdentity = Boolean(
|
|
65
|
+
val.label || val.filename || val.attachmentId || val.path?.trim() || val.branch?.trim() || val.url
|
|
66
|
+
);
|
|
67
|
+
if (!hasIdentity) {
|
|
68
|
+
ctx.addIssue({
|
|
69
|
+
code: z.ZodIssueCode.custom,
|
|
70
|
+
path: ["filename"],
|
|
71
|
+
message: "\u8BF7\u81F3\u5C11\u63D0\u4F9B filename\u3001label\u3001attachmentId\u3001path\u3001branch \u6216 url \u4E4B\u4E00"
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
if (val.content !== void 0 && val.attachmentId !== void 0) {
|
|
75
|
+
ctx.addIssue({
|
|
76
|
+
code: z.ZodIssueCode.custom,
|
|
77
|
+
path: ["content"],
|
|
78
|
+
message: "content \u4E0E attachmentId \u4E0D\u80FD\u540C\u65F6\u4F20\u5165"
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (val.content !== void 0 && val.content.trim().length === 0) {
|
|
82
|
+
ctx.addIssue({
|
|
83
|
+
code: z.ZodIssueCode.custom,
|
|
84
|
+
path: ["content"],
|
|
85
|
+
message: "content \u4E0D\u80FD\u4E3A\u7A7A"
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
if (val.content === void 0 && (val.filename !== void 0 || val.mimeType !== void 0)) {
|
|
89
|
+
ctx.addIssue({
|
|
90
|
+
code: z.ZodIssueCode.custom,
|
|
91
|
+
path: [val.filename !== void 0 ? "filename" : "mimeType"],
|
|
92
|
+
message: "filename / mimeType \u4EC5\u5728\u4F20\u5165 content \u65F6\u53EF\u7528"
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
var projectCreateSchema = z.object({
|
|
97
|
+
name: shortText,
|
|
98
|
+
description: z.string().trim().max(2e3).default(""),
|
|
99
|
+
rootPath: pathText.default(""),
|
|
100
|
+
defaultAgentId: z.string().uuid().nullable().optional(),
|
|
101
|
+
parallelMode: parallelModeSchema.default("auto")
|
|
102
|
+
}).strict();
|
|
103
|
+
var projectUpdateSchema = z.object({
|
|
104
|
+
name: shortText.optional(),
|
|
105
|
+
description: z.string().trim().max(2e3).optional(),
|
|
106
|
+
rootPath: pathText.optional(),
|
|
107
|
+
defaultAgentId: z.string().uuid().nullable().optional(),
|
|
108
|
+
parallelMode: parallelModeSchema.optional()
|
|
109
|
+
}).strict();
|
|
110
|
+
var agentRegisterSchema = z.object({
|
|
111
|
+
name: shortText,
|
|
112
|
+
driver: driverTypeSchema,
|
|
113
|
+
authMode: authModeSchema.optional(),
|
|
114
|
+
projectId: z.string().uuid().nullable().optional()
|
|
115
|
+
}).strict();
|
|
116
|
+
var agentUpdateSchema = z.object({
|
|
117
|
+
name: shortText.optional(),
|
|
118
|
+
enabled: z.boolean().optional(),
|
|
119
|
+
projectId: z.string().uuid().nullable().optional()
|
|
120
|
+
}).strict();
|
|
121
|
+
var agentPresenceReportSchema = z.object({
|
|
122
|
+
adapterInstanceId: z.string().trim().min(1).max(80),
|
|
123
|
+
hostLabel: z.string().trim().min(1).max(200),
|
|
124
|
+
sseConnected: z.boolean(),
|
|
125
|
+
lastEventCursor: z.string().regex(/^\d+$/),
|
|
126
|
+
driver: driverTypeSchema.optional(),
|
|
127
|
+
authMode: authModeSchema.optional(),
|
|
128
|
+
loginState: loginStateSchema,
|
|
129
|
+
loginMessage: z.string().trim().max(500).optional()
|
|
130
|
+
}).strict();
|
|
131
|
+
var agentLoginProgressSchema = z.object({
|
|
132
|
+
status: z.enum(["starting", "waiting_user", "succeeded", "failed", "cancelled", "expired"]),
|
|
133
|
+
verificationUri: httpUrlSchema(500).optional(),
|
|
134
|
+
userCode: z.string().trim().min(1).max(40).optional(),
|
|
135
|
+
expiresAt: z.string().trim().datetime({ offset: true }).max(40).optional(),
|
|
136
|
+
message: z.string().trim().max(500).optional()
|
|
137
|
+
}).strict();
|
|
138
|
+
var cardCreateSchema = z.object({
|
|
139
|
+
projectId: z.string().uuid(),
|
|
140
|
+
parentId: z.string().uuid().nullable().optional(),
|
|
141
|
+
defaultAgentId: z.string().uuid().nullable().optional(),
|
|
142
|
+
title: shortText,
|
|
143
|
+
body: longText.default(""),
|
|
144
|
+
status: cardStatusSchema.default("todo"),
|
|
145
|
+
priority: prioritySchema.default("medium"),
|
|
146
|
+
tags: z.array(tagSchema).max(20).default([]),
|
|
147
|
+
checklist: checklistSchema.default([]),
|
|
148
|
+
mentions: z.array(z.string().uuid()).max(10).default([]),
|
|
149
|
+
attachmentIds: z.array(z.string().uuid()).max(CARD_MAX_ATTACHMENTS).default([]),
|
|
150
|
+
skipDefaultAgent: z.boolean().default(false)
|
|
151
|
+
}).strict();
|
|
152
|
+
var checklistOpAddSchema = z.object({
|
|
153
|
+
op: z.literal("add"),
|
|
154
|
+
id: z.string().trim().min(1).max(64).optional(),
|
|
155
|
+
text: z.string().trim().min(1).max(500),
|
|
156
|
+
done: z.boolean().default(false)
|
|
157
|
+
}).strict();
|
|
158
|
+
var checklistOpUpdateSchema = z.object({
|
|
159
|
+
op: z.literal("update"),
|
|
160
|
+
id: z.string().trim().min(1).max(64),
|
|
161
|
+
text: z.string().trim().min(1).max(500).optional(),
|
|
162
|
+
done: z.boolean().optional()
|
|
163
|
+
}).strict();
|
|
164
|
+
var checklistOpRemoveSchema = z.object({
|
|
165
|
+
op: z.literal("remove"),
|
|
166
|
+
id: z.string().trim().min(1).max(64)
|
|
167
|
+
}).strict();
|
|
168
|
+
var checklistOpSchema = z.discriminatedUnion("op", [checklistOpAddSchema, checklistOpUpdateSchema, checklistOpRemoveSchema]).superRefine((op, ctx) => {
|
|
169
|
+
if (op.op === "update" && op.text === void 0 && op.done === void 0) {
|
|
170
|
+
ctx.addIssue({
|
|
171
|
+
code: z.ZodIssueCode.custom,
|
|
172
|
+
message: "update \u64CD\u4F5C\u81F3\u5C11\u9700\u8981\u63D0\u4F9B text \u6216 done \u4E4B\u4E00"
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
var cardUpdateSchema = z.object({
|
|
177
|
+
title: shortText.optional(),
|
|
178
|
+
body: longText.optional(),
|
|
179
|
+
priority: prioritySchema.optional(),
|
|
180
|
+
tags: z.array(tagSchema).max(20).optional(),
|
|
181
|
+
checklist: checklistSchema.optional(),
|
|
182
|
+
checklistOps: z.array(checklistOpSchema).min(1).max(50).optional(),
|
|
183
|
+
expectedVersion: z.number().int().min(1).optional(),
|
|
184
|
+
parentId: z.string().uuid().nullable().optional(),
|
|
185
|
+
defaultAgentId: z.string().uuid().nullable().optional(),
|
|
186
|
+
position: z.number().int().min(0).optional(),
|
|
187
|
+
summary: optionalShortText.optional()
|
|
188
|
+
}).strict().refine((v) => !(v.checklist !== void 0 && v.checklistOps !== void 0), {
|
|
189
|
+
message: "checklist \u4E0E checklistOps \u4E0D\u80FD\u540C\u65F6\u4F20\u5165\uFF0C\u8BF7\u4E8C\u9009\u4E00\uFF08\u5E76\u53D1\u573A\u666F\u63A8\u8350 checklistOps\uFF09",
|
|
190
|
+
path: ["checklistOps"]
|
|
191
|
+
});
|
|
192
|
+
var cardStatusChangeSchema = z.object({
|
|
193
|
+
status: cardStatusSchema,
|
|
194
|
+
position: z.number().int().min(0).optional(),
|
|
195
|
+
note: z.string().trim().max(2e3).optional()
|
|
196
|
+
}).strict();
|
|
197
|
+
var commentCreateSchema = z.object({
|
|
198
|
+
text: z.string().trim().max(2e4).default(""),
|
|
199
|
+
mentions: z.array(z.string().uuid()).max(10).default([]),
|
|
200
|
+
attachmentIds: z.array(z.string().uuid()).max(COMMENT_MAX_ATTACHMENTS).default([]),
|
|
201
|
+
replyTo: z.string().uuid().optional(),
|
|
202
|
+
relatesTo: z.string().uuid().optional()
|
|
203
|
+
}).strict().refine((v) => v.text.length > 0 || v.attachmentIds.length > 0, "\u8BF7\u8F93\u5165\u8BC4\u8BBA\u5185\u5BB9\u6216\u6DFB\u52A0\u9644\u4EF6");
|
|
204
|
+
var participantOutcomeSchema = z.enum(["completed", "no_write", "failed", "stopped"]);
|
|
205
|
+
var cardRunStatusSchema = z.enum(["running", "completed", "no_write", "failed", "stopped"]);
|
|
206
|
+
var cardRunStepKindSchema = z.enum(["slate", "command", "tool", "message", "status"]);
|
|
207
|
+
var CARD_RUN_STEP_BATCH_MAX = 20;
|
|
208
|
+
var cardRunStepInputSchema = z.object({
|
|
209
|
+
kind: cardRunStepKindSchema,
|
|
210
|
+
title: z.string().trim().min(1).max(200),
|
|
211
|
+
detail: z.string().trim().max(400).optional(),
|
|
212
|
+
at: z.string().trim().datetime({ offset: true }).max(40).optional()
|
|
213
|
+
}).strict();
|
|
214
|
+
var cardRunStepsAppendSchema = z.object({
|
|
215
|
+
runId: z.string().uuid(),
|
|
216
|
+
eventId: z.string().uuid().optional(),
|
|
217
|
+
steps: z.array(cardRunStepInputSchema).min(1).max(CARD_RUN_STEP_BATCH_MAX)
|
|
218
|
+
}).strict();
|
|
219
|
+
var processingReportSchema = z.object({
|
|
220
|
+
runId: z.string().uuid().optional(),
|
|
221
|
+
eventId: z.string().uuid().optional(),
|
|
222
|
+
activityText: z.string().trim().max(300).default(""),
|
|
223
|
+
workDir: pathText.optional(),
|
|
224
|
+
branch: z.string().trim().max(200).optional()
|
|
225
|
+
}).strict();
|
|
226
|
+
var processingClearSchema = z.object({
|
|
227
|
+
runId: z.string().uuid().optional(),
|
|
228
|
+
eventId: z.string().uuid().optional(),
|
|
229
|
+
outcome: participantOutcomeSchema.optional(),
|
|
230
|
+
summary: z.string().trim().max(300).optional()
|
|
231
|
+
}).strict();
|
|
232
|
+
var decisionOptionSchema = z.object({
|
|
233
|
+
id: z.string().trim().min(1).max(64),
|
|
234
|
+
label: z.string().trim().min(1).max(120),
|
|
235
|
+
description: z.string().trim().max(400).optional(),
|
|
236
|
+
recommended: z.boolean().default(false)
|
|
237
|
+
}).strict();
|
|
238
|
+
var cardDecisionCreateSchema = z.object({
|
|
239
|
+
question: z.string().trim().min(1).max(2e3),
|
|
240
|
+
context: z.string().trim().max(2e3).optional(),
|
|
241
|
+
options: z.array(decisionOptionSchema).min(2).max(6).refine((opts) => new Set(opts.map((o) => o.id)).size === opts.length, "\u51B3\u7B56\u9009\u9879 ID \u4E0D\u80FD\u91CD\u590D").optional()
|
|
242
|
+
}).strict();
|
|
243
|
+
var cardDecisionResolveSchema = z.object({
|
|
244
|
+
optionId: z.string().trim().min(1).max(64).optional(),
|
|
245
|
+
note: z.string().trim().max(4e3).optional(),
|
|
246
|
+
wakeAgent: z.boolean().default(true)
|
|
247
|
+
}).strict().refine((v) => Boolean(v.optionId || v.note?.trim()), "\u8BF7\u9009\u62E9\u4E00\u4E2A\u9009\u9879\u6216\u586B\u5199\u56DE\u590D\u5185\u5BB9");
|
|
248
|
+
var assistantRunKindSchema = z.enum(["card_draft", "assistant_chat"]);
|
|
249
|
+
var assistantPresetSchema = z.enum(["focus", "risk", "cleanup", "summary"]);
|
|
250
|
+
var assistantRunStatusSchema = z.enum(["queued", "running", "succeeded", "failed", "cancelled"]);
|
|
251
|
+
var assistantRunOptionsSchema = z.object({
|
|
252
|
+
includeExistingCards: z.boolean().default(true),
|
|
253
|
+
readWorkspace: z.boolean().default(true),
|
|
254
|
+
allowMultipleCards: z.boolean().default(false)
|
|
255
|
+
}).strict();
|
|
256
|
+
var assistantCardDraftSchema = z.object({
|
|
257
|
+
title: shortText,
|
|
258
|
+
body: longText.default(""),
|
|
259
|
+
status: agentAllowedStatusSchema.default("todo"),
|
|
260
|
+
priority: prioritySchema.default("medium"),
|
|
261
|
+
tags: z.array(tagSchema).max(20).default([]),
|
|
262
|
+
checklist: z.array(z.string().trim().min(1).max(500)).max(50).default([]),
|
|
263
|
+
suggestedAgentIds: z.array(z.string().uuid()).max(10).default([]),
|
|
264
|
+
parentId: z.string().uuid().nullable().optional(),
|
|
265
|
+
duplicateOfCardId: z.string().uuid().nullable().optional(),
|
|
266
|
+
duplicateReason: z.string().trim().max(500).optional()
|
|
267
|
+
}).strict();
|
|
268
|
+
var assistantCardRefSchema = z.object({
|
|
269
|
+
cardId: z.string().uuid(),
|
|
270
|
+
title: shortText,
|
|
271
|
+
status: cardStatusSchema,
|
|
272
|
+
note: z.string().trim().max(200).optional()
|
|
273
|
+
}).strict();
|
|
274
|
+
var assistantProposalActionSchema = z.discriminatedUnion("type", [
|
|
275
|
+
z.object({
|
|
276
|
+
id: z.string().trim().min(1).max(64),
|
|
277
|
+
type: z.literal("create_card"),
|
|
278
|
+
summary: shortText,
|
|
279
|
+
draft: assistantCardDraftSchema,
|
|
280
|
+
mentions: z.array(z.string().uuid()).max(10).default([]),
|
|
281
|
+
skipDefaultAgent: z.boolean().default(false)
|
|
282
|
+
}).strict(),
|
|
283
|
+
z.object({
|
|
284
|
+
id: z.string().trim().min(1).max(64),
|
|
285
|
+
type: z.literal("update_card"),
|
|
286
|
+
cardId: z.string().uuid(),
|
|
287
|
+
cardTitle: shortText,
|
|
288
|
+
summary: shortText,
|
|
289
|
+
patch: z.object({
|
|
290
|
+
title: shortText.optional(),
|
|
291
|
+
priority: prioritySchema.optional(),
|
|
292
|
+
tags: z.array(tagSchema).max(20).optional(),
|
|
293
|
+
status: cardStatusSchema.optional()
|
|
294
|
+
}).strict()
|
|
295
|
+
}).strict(),
|
|
296
|
+
z.object({
|
|
297
|
+
id: z.string().trim().min(1).max(64),
|
|
298
|
+
type: z.literal("archive_card"),
|
|
299
|
+
cardId: z.string().uuid(),
|
|
300
|
+
cardTitle: shortText,
|
|
301
|
+
summary: shortText
|
|
302
|
+
}).strict()
|
|
303
|
+
]);
|
|
304
|
+
var assistantRunResultSchema = z.object({
|
|
305
|
+
reply: z.string().trim().max(5e4).default(""),
|
|
306
|
+
clarifyQuestion: z.string().trim().max(1e3).optional(),
|
|
307
|
+
splitSuggestion: z.string().trim().max(500).optional(),
|
|
308
|
+
cardRefs: z.array(assistantCardRefSchema).max(30).refine((refs) => new Set(refs.map((r) => r.cardId)).size === refs.length, "\u5F15\u7528\u5361\u7247 ID \u4E0D\u80FD\u91CD\u590D").default([]),
|
|
309
|
+
drafts: z.array(assistantCardDraftSchema).max(20).default([]),
|
|
310
|
+
proposals: z.array(assistantProposalActionSchema).max(30).refine((items) => new Set(items.map((i) => i.id)).size === items.length, "\u63D0\u6848 ID \u4E0D\u80FD\u91CD\u590D").default([])
|
|
311
|
+
}).strict();
|
|
312
|
+
var assistantRunCreateSchema = z.object({
|
|
313
|
+
projectId: z.string().uuid(),
|
|
314
|
+
agentId: z.string().uuid(),
|
|
315
|
+
kind: assistantRunKindSchema,
|
|
316
|
+
prompt: z.string().trim().min(1).max(2e4),
|
|
317
|
+
threadId: z.string().uuid().optional(),
|
|
318
|
+
preset: assistantPresetSchema.optional(),
|
|
319
|
+
options: assistantRunOptionsSchema.optional(),
|
|
320
|
+
attachmentIds: z.array(z.string().uuid()).max(CARD_MAX_ATTACHMENTS).default([])
|
|
321
|
+
}).strict();
|
|
322
|
+
var assistantRunProgressSchema = z.object({
|
|
323
|
+
status: z.enum(["running", "succeeded", "failed", "cancelled"]),
|
|
324
|
+
activityText: z.string().trim().max(300).optional(),
|
|
325
|
+
sessionId: z.string().trim().max(200).optional(),
|
|
326
|
+
result: assistantRunResultSchema.optional(),
|
|
327
|
+
errorMessage: z.string().trim().max(2e3).optional()
|
|
328
|
+
}).strict();
|
|
329
|
+
var assistantRunStreamSchema = z.object({
|
|
330
|
+
text: z.string().max(5e4),
|
|
331
|
+
stage: z.enum(["streaming", "structuring"]).default("streaming"),
|
|
332
|
+
activityText: z.string().trim().max(300).optional()
|
|
333
|
+
}).strict();
|
|
334
|
+
var assistantProposalApplySchema = z.object({
|
|
335
|
+
actions: z.array(assistantProposalActionSchema).min(1).max(30)
|
|
336
|
+
}).strict();
|
|
337
|
+
|
|
338
|
+
// src/api.ts
|
|
339
|
+
import http from "http";
|
|
340
|
+
var BoardApi = class {
|
|
341
|
+
constructor(cred, fetcher = fetch, httpRequest = http.request) {
|
|
342
|
+
this.cred = cred;
|
|
343
|
+
this.fetcher = fetcher;
|
|
344
|
+
this.httpRequest = httpRequest;
|
|
345
|
+
this.base = cred.apiBase;
|
|
346
|
+
}
|
|
347
|
+
cred;
|
|
348
|
+
fetcher;
|
|
349
|
+
httpRequest;
|
|
350
|
+
base;
|
|
351
|
+
async request(suffix, init = {}) {
|
|
352
|
+
const response = await this.fetcher(`${this.base}${suffix}`, {
|
|
353
|
+
...init,
|
|
354
|
+
headers: {
|
|
355
|
+
authorization: `Bearer ${this.cred.token}`,
|
|
356
|
+
...init.body ? { "content-type": "application/json" } : {},
|
|
357
|
+
...init.headers ?? {}
|
|
358
|
+
},
|
|
359
|
+
redirect: "error",
|
|
360
|
+
signal: init.signal ?? AbortSignal.timeout(15e3)
|
|
361
|
+
});
|
|
362
|
+
if (!response.ok) {
|
|
363
|
+
const body = await response.json().catch(() => null);
|
|
364
|
+
const rawMessage = body && typeof body === "object" && typeof body.message === "string" && body.message.trim() ? body.message : "\u8BF7\u6C42\u5931\u8D25";
|
|
365
|
+
const safeMessage = this.cred.token ? rawMessage.replaceAll(this.cred.token, "[redacted]") : rawMessage;
|
|
366
|
+
throw new Error(`\u770B\u677F API ${response.status}: ${safeMessage}`);
|
|
367
|
+
}
|
|
368
|
+
return await response.json();
|
|
369
|
+
}
|
|
370
|
+
me() {
|
|
371
|
+
return this.request("/agents/me");
|
|
372
|
+
}
|
|
373
|
+
project(projectId) {
|
|
374
|
+
return this.request(`/projects/${projectId}`);
|
|
375
|
+
}
|
|
376
|
+
card(cardId, options) {
|
|
377
|
+
const qs = new URLSearchParams();
|
|
378
|
+
if (options?.includeRevisions !== void 0) {
|
|
379
|
+
qs.set("includeRevisions", options.includeRevisions ? "true" : "false");
|
|
380
|
+
}
|
|
381
|
+
if (options?.eventLimit !== void 0) {
|
|
382
|
+
qs.set("eventLimit", String(options.eventLimit));
|
|
383
|
+
}
|
|
384
|
+
const suffix = qs.size > 0 ? `/cards/${cardId}?${qs.toString()}` : `/cards/${cardId}`;
|
|
385
|
+
return this.request(suffix);
|
|
386
|
+
}
|
|
387
|
+
events(cursor, limit = 100) {
|
|
388
|
+
const qs = new URLSearchParams({ cursor, limit: String(limit) });
|
|
389
|
+
if (this.cred.projectId) qs.set("projectId", this.cred.projectId);
|
|
390
|
+
return this.request(`/events?${qs.toString()}`);
|
|
391
|
+
}
|
|
392
|
+
comment(cardId, text, relatesTo) {
|
|
393
|
+
return this.request(`/cards/${cardId}/comments`, {
|
|
394
|
+
method: "POST",
|
|
395
|
+
body: JSON.stringify({ text, ...relatesTo ? { relatesTo } : {} })
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
processing(cardId, body) {
|
|
399
|
+
return this.request(`/cards/${cardId}/processing`, {
|
|
400
|
+
method: "POST",
|
|
401
|
+
body: JSON.stringify(body)
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
processingClear(cardId, body = {}) {
|
|
405
|
+
return this.request(`/cards/${cardId}/processing/clear`, {
|
|
406
|
+
method: "POST",
|
|
407
|
+
body: JSON.stringify(body)
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
appendRunSteps(cardId, body) {
|
|
411
|
+
return this.request(
|
|
412
|
+
`/cards/${cardId}/runs/steps`,
|
|
413
|
+
{
|
|
414
|
+
method: "POST",
|
|
415
|
+
body: JSON.stringify(body)
|
|
416
|
+
}
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
presence(report) {
|
|
420
|
+
return this.request("/agents/presence", {
|
|
421
|
+
method: "POST",
|
|
422
|
+
body: JSON.stringify(report)
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
loginProgress(requestId, body) {
|
|
426
|
+
return this.request(`/agents/login/${requestId}/progress`, {
|
|
427
|
+
method: "POST",
|
|
428
|
+
body: JSON.stringify(body)
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
claimAssistantRun() {
|
|
432
|
+
return this.request("/agents/assistant-runs/claim", {
|
|
433
|
+
method: "POST",
|
|
434
|
+
body: JSON.stringify({})
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
reportAssistantRunProgress(runId, body) {
|
|
438
|
+
return this.request(`/agents/assistant-runs/${runId}/progress`, {
|
|
439
|
+
method: "POST",
|
|
440
|
+
body: JSON.stringify(body)
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
streamAssistantRun(runId, body) {
|
|
444
|
+
return this.request(`/agents/assistant-runs/${runId}/stream`, {
|
|
445
|
+
method: "POST",
|
|
446
|
+
body: JSON.stringify(body)
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
eventStream(signal, onFrame) {
|
|
450
|
+
const qs = this.cred.projectId ? `?${new URLSearchParams({ projectId: this.cred.projectId }).toString()}` : "";
|
|
451
|
+
const url = new URL(`${this.base}/events/stream${qs}`);
|
|
452
|
+
return new Promise((resolve, reject) => {
|
|
453
|
+
if (signal.aborted) {
|
|
454
|
+
resolve();
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
let settled = false;
|
|
458
|
+
let responseReceived = false;
|
|
459
|
+
const done = (err) => {
|
|
460
|
+
if (settled) return;
|
|
461
|
+
settled = true;
|
|
462
|
+
signal.removeEventListener("abort", abort);
|
|
463
|
+
if (err && !signal.aborted) reject(err);
|
|
464
|
+
else resolve();
|
|
465
|
+
};
|
|
466
|
+
const req = this.httpRequest(
|
|
467
|
+
{
|
|
468
|
+
hostname: url.hostname,
|
|
469
|
+
port: url.port || void 0,
|
|
470
|
+
path: url.pathname + url.search,
|
|
471
|
+
method: "GET",
|
|
472
|
+
headers: { authorization: `Bearer ${this.cred.token}`, accept: "text/event-stream" }
|
|
473
|
+
},
|
|
474
|
+
(res) => {
|
|
475
|
+
responseReceived = true;
|
|
476
|
+
if (res.statusCode !== 200) {
|
|
477
|
+
res.resume();
|
|
478
|
+
done(new Error(`SSE \u72B6\u6001\u7801 ${res.statusCode}`));
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
let buf = "";
|
|
482
|
+
res.setEncoding("utf8");
|
|
483
|
+
res.on("data", (chunk) => {
|
|
484
|
+
buf = (buf + chunk).replaceAll("\r\n", "\n");
|
|
485
|
+
for (let idx = buf.indexOf("\n\n"); idx >= 0; idx = buf.indexOf("\n\n")) {
|
|
486
|
+
if (settled || signal.aborted) break;
|
|
487
|
+
const block = buf.slice(0, idx);
|
|
488
|
+
buf = buf.slice(idx + 2);
|
|
489
|
+
let event = "message";
|
|
490
|
+
const dataLines = [];
|
|
491
|
+
for (const line of block.split("\n")) {
|
|
492
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
493
|
+
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
|
|
494
|
+
}
|
|
495
|
+
if (dataLines.length) {
|
|
496
|
+
try {
|
|
497
|
+
onFrame({ event, data: dataLines.join("\n") });
|
|
498
|
+
} catch (err) {
|
|
499
|
+
req.destroy();
|
|
500
|
+
done(err instanceof Error ? err : new Error(String(err)));
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
res.on("end", () => done());
|
|
507
|
+
res.on("close", () => done(res.complete ? void 0 : new Error("SSE \u8FDE\u63A5\u4E2D\u65AD")));
|
|
508
|
+
res.on("error", (err) => done(err));
|
|
509
|
+
}
|
|
510
|
+
);
|
|
511
|
+
const abort = () => {
|
|
512
|
+
req.destroy();
|
|
513
|
+
done();
|
|
514
|
+
};
|
|
515
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
516
|
+
req.on("error", (err) => done(err));
|
|
517
|
+
req.on("close", () => {
|
|
518
|
+
if (!responseReceived) done(new Error("SSE \u8FDE\u63A5\u4E2D\u65AD"));
|
|
519
|
+
});
|
|
520
|
+
req.end();
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
// src/assistant.ts
|
|
526
|
+
import { existsSync as existsSync2 } from "fs";
|
|
527
|
+
import { copyFile, mkdir as mkdir4, rm } from "fs/promises";
|
|
528
|
+
import path4 from "path";
|
|
529
|
+
|
|
530
|
+
// src/assistant/parser.ts
|
|
531
|
+
var VALID_PRIORITIES = /* @__PURE__ */ new Set(["high", "medium", "low"]);
|
|
532
|
+
var VALID_AGENT_STATUSES = /* @__PURE__ */ new Set(["todo", "doing", "review"]);
|
|
533
|
+
var VALID_STATUSES = /* @__PURE__ */ new Set(["todo", "doing", "review", "done"]);
|
|
534
|
+
var FENCE_START_RE = /```(?:slate-json|json)\b/i;
|
|
535
|
+
function extractVisibleStreamState(raw) {
|
|
536
|
+
const trimmedStart = raw.trimStart();
|
|
537
|
+
if (!trimmedStart) return { text: "", stage: "streaming" };
|
|
538
|
+
if (trimmedStart.startsWith("{") || FENCE_START_RE.test(trimmedStart.slice(0, 16))) {
|
|
539
|
+
return { text: "", stage: "structuring" };
|
|
540
|
+
}
|
|
541
|
+
const fenceMatch = FENCE_START_RE.exec(raw);
|
|
542
|
+
if (fenceMatch) {
|
|
543
|
+
return {
|
|
544
|
+
text: raw.slice(0, fenceMatch.index).trimEnd(),
|
|
545
|
+
stage: "structuring"
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
const safe = raw.replace(
|
|
549
|
+
/(?:\r?\n)?`{1,3}(?:s(?:l(?:a(?:t(?:e(?:-j(?:s(?:o(?:n)?)?)?)?)?)?)?)?|j(?:s(?:o(?:n)?)?)?)?$/i,
|
|
550
|
+
""
|
|
551
|
+
);
|
|
552
|
+
return {
|
|
553
|
+
text: safe.trimEnd(),
|
|
554
|
+
stage: "streaming"
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
function extractJsonObject(raw) {
|
|
558
|
+
const trimmed = raw.trim();
|
|
559
|
+
if (!trimmed) return null;
|
|
560
|
+
const fenced = [...trimmed.matchAll(/```(?:slate-json|json)?\s*([\s\S]*?)```/gi)];
|
|
561
|
+
for (let i = fenced.length - 1; i >= 0; i--) {
|
|
562
|
+
const candidate = fenced[i]?.[1]?.trim();
|
|
563
|
+
if (!candidate) continue;
|
|
564
|
+
try {
|
|
565
|
+
const parsed = JSON.parse(candidate);
|
|
566
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
567
|
+
return parsed;
|
|
568
|
+
}
|
|
569
|
+
} catch {
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const firstBrace = trimmed.indexOf("{");
|
|
573
|
+
const lastBrace = trimmed.lastIndexOf("}");
|
|
574
|
+
if (firstBrace >= 0 && lastBrace > firstBrace) {
|
|
575
|
+
try {
|
|
576
|
+
const parsed = JSON.parse(trimmed.slice(firstBrace, lastBrace + 1));
|
|
577
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
578
|
+
return parsed;
|
|
579
|
+
}
|
|
580
|
+
} catch {
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
function resolveAgentIds(raw, agents) {
|
|
586
|
+
if (!Array.isArray(raw)) return [];
|
|
587
|
+
const byId = new Set(agents.map((a) => a.id));
|
|
588
|
+
const byName = new Map(agents.map((a) => [a.name.toLowerCase(), a.id]));
|
|
589
|
+
const out = [];
|
|
590
|
+
for (const item of raw) {
|
|
591
|
+
if (typeof item !== "string") continue;
|
|
592
|
+
const clean = item.trim().replace(/^@/, "");
|
|
593
|
+
if (byId.has(clean)) out.push(clean);
|
|
594
|
+
else {
|
|
595
|
+
const found = byName.get(clean.toLowerCase());
|
|
596
|
+
if (found) out.push(found);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return Array.from(new Set(out)).slice(0, 10);
|
|
600
|
+
}
|
|
601
|
+
function sanitizeDraft(raw, cardsById, agents) {
|
|
602
|
+
if (!raw || typeof raw !== "object") return null;
|
|
603
|
+
const obj = raw;
|
|
604
|
+
const title = typeof obj.title === "string" ? obj.title.trim().slice(0, 200) : "";
|
|
605
|
+
if (!title) return null;
|
|
606
|
+
const body = typeof obj.body === "string" ? obj.body.trim().slice(0, 5e4) : "";
|
|
607
|
+
const status = typeof obj.status === "string" && VALID_AGENT_STATUSES.has(obj.status) ? obj.status : "todo";
|
|
608
|
+
const priority = typeof obj.priority === "string" && VALID_PRIORITIES.has(obj.priority) ? obj.priority : "medium";
|
|
609
|
+
const tags = Array.isArray(obj.tags) ? Array.from(
|
|
610
|
+
new Set(
|
|
611
|
+
obj.tags.filter((t) => typeof t === "string").map((t) => t.trim().slice(0, 40)).filter(Boolean)
|
|
612
|
+
)
|
|
613
|
+
).slice(0, 20) : [];
|
|
614
|
+
const checklist = Array.isArray(obj.checklist) ? obj.checklist.map(
|
|
615
|
+
(item) => typeof item === "string" ? item : item && typeof item === "object" && typeof item.text === "string" ? item.text : ""
|
|
616
|
+
).map((s) => s.trim().slice(0, 500)).filter(Boolean).slice(0, 50) : [];
|
|
617
|
+
const suggestedAgentIds = resolveAgentIds(obj.suggestedAgentIds, agents);
|
|
618
|
+
const parentId = typeof obj.parentId === "string" && cardsById.has(obj.parentId) ? obj.parentId : null;
|
|
619
|
+
const duplicateOfCardId = typeof obj.duplicateOfCardId === "string" && cardsById.has(obj.duplicateOfCardId) ? obj.duplicateOfCardId : null;
|
|
620
|
+
const duplicateReason = duplicateOfCardId && typeof obj.duplicateReason === "string" && obj.duplicateReason.trim() ? obj.duplicateReason.trim().slice(0, 500) : void 0;
|
|
621
|
+
return {
|
|
622
|
+
title,
|
|
623
|
+
body,
|
|
624
|
+
status,
|
|
625
|
+
priority,
|
|
626
|
+
tags,
|
|
627
|
+
checklist,
|
|
628
|
+
suggestedAgentIds,
|
|
629
|
+
parentId,
|
|
630
|
+
duplicateOfCardId,
|
|
631
|
+
...duplicateReason ? { duplicateReason } : {}
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
function allocateProposalId(rawId, usedIds, nextAuto) {
|
|
635
|
+
const raw = typeof rawId === "string" ? rawId.trim().slice(0, 64) : "";
|
|
636
|
+
if (!raw) {
|
|
637
|
+
let candidate = `p-${nextAuto()}`;
|
|
638
|
+
while (usedIds.has(candidate)) {
|
|
639
|
+
candidate = `p-${nextAuto()}`;
|
|
640
|
+
}
|
|
641
|
+
usedIds.add(candidate);
|
|
642
|
+
return candidate;
|
|
643
|
+
}
|
|
644
|
+
if (!usedIds.has(raw)) {
|
|
645
|
+
usedIds.add(raw);
|
|
646
|
+
return raw;
|
|
647
|
+
}
|
|
648
|
+
let suffixIdx = 2;
|
|
649
|
+
while (true) {
|
|
650
|
+
const suffix = `-${suffixIdx++}`;
|
|
651
|
+
const candidate = `${raw.slice(0, 64 - suffix.length)}${suffix}`;
|
|
652
|
+
if (!usedIds.has(candidate)) {
|
|
653
|
+
usedIds.add(candidate);
|
|
654
|
+
return candidate;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
function buildFallbackDraft(prompt, body) {
|
|
659
|
+
const fallbackTitle = prompt.split(/[\n。!?]/)[0]?.trim().slice(0, 80) || "\u65B0\u5EFA\u4EFB\u52A1";
|
|
660
|
+
return {
|
|
661
|
+
title: fallbackTitle,
|
|
662
|
+
body,
|
|
663
|
+
status: "todo",
|
|
664
|
+
priority: "medium",
|
|
665
|
+
tags: [],
|
|
666
|
+
checklist: [],
|
|
667
|
+
suggestedAgentIds: [],
|
|
668
|
+
parentId: null,
|
|
669
|
+
duplicateOfCardId: null
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function sanitizeCardRefs(rawRefs, cardsById) {
|
|
673
|
+
if (!Array.isArray(rawRefs)) return [];
|
|
674
|
+
const cardRefs = [];
|
|
675
|
+
const seen = /* @__PURE__ */ new Set();
|
|
676
|
+
for (const item of rawRefs) {
|
|
677
|
+
if (!item || typeof item !== "object") continue;
|
|
678
|
+
const obj = item;
|
|
679
|
+
const id = typeof obj.cardId === "string" ? obj.cardId : "";
|
|
680
|
+
const card = cardsById.get(id);
|
|
681
|
+
if (!card || seen.has(id)) continue;
|
|
682
|
+
seen.add(id);
|
|
683
|
+
const note = typeof obj.note === "string" && obj.note.trim() ? obj.note.trim().slice(0, 200) : void 0;
|
|
684
|
+
cardRefs.push({ cardId: card.id, title: card.title, status: card.status, ...note ? { note } : {} });
|
|
685
|
+
}
|
|
686
|
+
return cardRefs;
|
|
687
|
+
}
|
|
688
|
+
function sanitizeProposals(rawProposals, cardsById, agents) {
|
|
689
|
+
if (!Array.isArray(rawProposals)) return [];
|
|
690
|
+
const proposals = [];
|
|
691
|
+
let idx = 1;
|
|
692
|
+
const usedProposalIds = /* @__PURE__ */ new Set();
|
|
693
|
+
const nextAuto = () => idx++;
|
|
694
|
+
for (const item of rawProposals) {
|
|
695
|
+
if (!item || typeof item !== "object") continue;
|
|
696
|
+
const obj = item;
|
|
697
|
+
const summary = typeof obj.summary === "string" ? obj.summary.trim().slice(0, 200) : "";
|
|
698
|
+
if (obj.type === "archive_card") {
|
|
699
|
+
const card = typeof obj.cardId === "string" ? cardsById.get(obj.cardId) : void 0;
|
|
700
|
+
if (!card) continue;
|
|
701
|
+
const id = allocateProposalId(obj.id, usedProposalIds, nextAuto);
|
|
702
|
+
proposals.push({
|
|
703
|
+
id,
|
|
704
|
+
type: "archive_card",
|
|
705
|
+
cardId: card.id,
|
|
706
|
+
cardTitle: card.title,
|
|
707
|
+
summary: (summary || `\u5F52\u6863\u5361\u7247\u300A${card.title}\u300B`).slice(0, 200)
|
|
708
|
+
});
|
|
709
|
+
} else if (obj.type === "update_card") {
|
|
710
|
+
const card = typeof obj.cardId === "string" ? cardsById.get(obj.cardId) : void 0;
|
|
711
|
+
const rawPatch = obj.patch && typeof obj.patch === "object" ? obj.patch : null;
|
|
712
|
+
if (!card || !rawPatch) continue;
|
|
713
|
+
const patch = {};
|
|
714
|
+
if (typeof rawPatch.title === "string" && rawPatch.title.trim()) {
|
|
715
|
+
patch.title = rawPatch.title.trim().slice(0, 200);
|
|
716
|
+
}
|
|
717
|
+
if (typeof rawPatch.priority === "string" && VALID_PRIORITIES.has(rawPatch.priority)) {
|
|
718
|
+
patch.priority = rawPatch.priority;
|
|
719
|
+
}
|
|
720
|
+
if (Array.isArray(rawPatch.tags)) {
|
|
721
|
+
patch.tags = rawPatch.tags.filter((t) => typeof t === "string").map((t) => t.trim().slice(0, 40)).filter(Boolean).slice(0, 20);
|
|
722
|
+
}
|
|
723
|
+
if (typeof rawPatch.status === "string" && VALID_STATUSES.has(rawPatch.status)) {
|
|
724
|
+
patch.status = rawPatch.status;
|
|
725
|
+
}
|
|
726
|
+
if (Object.keys(patch).length === 0) continue;
|
|
727
|
+
const id = allocateProposalId(obj.id, usedProposalIds, nextAuto);
|
|
728
|
+
proposals.push({
|
|
729
|
+
id,
|
|
730
|
+
type: "update_card",
|
|
731
|
+
cardId: card.id,
|
|
732
|
+
cardTitle: card.title,
|
|
733
|
+
summary: (summary || `\u66F4\u65B0\u5361\u7247\u300A${card.title}\u300B`).slice(0, 200),
|
|
734
|
+
patch
|
|
735
|
+
});
|
|
736
|
+
} else if (obj.type === "create_card") {
|
|
737
|
+
const draft = sanitizeDraft(obj.draft, cardsById, agents);
|
|
738
|
+
if (!draft) continue;
|
|
739
|
+
const mentions = resolveAgentIds(obj.mentions ?? draft.suggestedAgentIds, agents);
|
|
740
|
+
const id = allocateProposalId(obj.id, usedProposalIds, nextAuto);
|
|
741
|
+
proposals.push({
|
|
742
|
+
id,
|
|
743
|
+
type: "create_card",
|
|
744
|
+
summary: (summary || `\u65B0\u5EFA\u5361\u7247\u300A${draft.title}\u300B`).slice(0, 200),
|
|
745
|
+
draft,
|
|
746
|
+
mentions,
|
|
747
|
+
skipDefaultAgent: Boolean(obj.skipDefaultAgent)
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
return proposals;
|
|
752
|
+
}
|
|
753
|
+
function parseAssistantOutput(rawText, payload) {
|
|
754
|
+
const cardsById = new Map(payload.cards.map((c) => [c.id, c]));
|
|
755
|
+
const parsed = extractJsonObject(rawText);
|
|
756
|
+
if (!parsed) {
|
|
757
|
+
const cleanReply = rawText.trim().slice(0, 5e4) || "\u5DF2\u5B8C\u6210\u6574\u7406\u3002";
|
|
758
|
+
if (payload.run.kind === "card_draft") {
|
|
759
|
+
return {
|
|
760
|
+
reply: "\u5DF2\u6574\u7406\u4E3A\u8349\u7A3F\uFF0C\u8BF7\u6838\u5BF9\u540E\u521B\u5EFA\u3002",
|
|
761
|
+
cardRefs: [],
|
|
762
|
+
drafts: [buildFallbackDraft(payload.run.prompt, cleanReply)],
|
|
763
|
+
proposals: []
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
return { reply: cleanReply, cardRefs: [], drafts: [], proposals: [] };
|
|
767
|
+
}
|
|
768
|
+
const jsonReply = typeof parsed.reply === "string" ? parsed.reply.trim().slice(0, 5e4) : "";
|
|
769
|
+
const proseBeforeFence = extractVisibleStreamState(rawText).text.trim().slice(0, 5e4);
|
|
770
|
+
const reply = jsonReply || proseBeforeFence;
|
|
771
|
+
const clarifyQuestion = typeof parsed.clarifyQuestion === "string" && parsed.clarifyQuestion.trim() ? parsed.clarifyQuestion.trim().slice(0, 1e3) : void 0;
|
|
772
|
+
const splitSuggestion = typeof parsed.splitSuggestion === "string" && parsed.splitSuggestion.trim() ? parsed.splitSuggestion.trim().slice(0, 500) : void 0;
|
|
773
|
+
const cardRefs = sanitizeCardRefs(parsed.cardRefs, cardsById);
|
|
774
|
+
const drafts = [];
|
|
775
|
+
if (Array.isArray(parsed.drafts)) {
|
|
776
|
+
for (const d of parsed.drafts) {
|
|
777
|
+
const clean = sanitizeDraft(d, cardsById, payload.agents);
|
|
778
|
+
if (clean) drafts.push(clean);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (payload.run.kind === "card_draft" && drafts.length === 0) {
|
|
782
|
+
drafts.push(buildFallbackDraft(payload.run.prompt, reply || payload.run.prompt));
|
|
783
|
+
}
|
|
784
|
+
const proposals = sanitizeProposals(parsed.proposals, cardsById, payload.agents);
|
|
785
|
+
return {
|
|
786
|
+
reply: reply || (payload.run.kind === "card_draft" ? "\u5DF2\u6574\u7406\u4E3A\u53EF\u7F16\u8F91\u8349\u7A3F\uFF0C\u8BF7\u6838\u5BF9\u540E\u521B\u5EFA\u3002" : "\u5DF2\u5B8C\u6210\u770B\u677F\u5206\u6790\u3002"),
|
|
787
|
+
...clarifyQuestion ? { clarifyQuestion } : {},
|
|
788
|
+
...splitSuggestion ? { splitSuggestion } : {},
|
|
789
|
+
cardRefs: cardRefs.slice(0, 30),
|
|
790
|
+
drafts: drafts.slice(0, 20),
|
|
791
|
+
proposals: proposals.slice(0, 30)
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// src/local.ts
|
|
796
|
+
import { randomUUID } from "crypto";
|
|
797
|
+
import { existsSync } from "fs";
|
|
798
|
+
import { mkdir as mkdir2, open, readdir, readFile, rename, stat as stat2, unlink } from "fs/promises";
|
|
799
|
+
import path2 from "path";
|
|
800
|
+
import { fileURLToPath } from "url";
|
|
801
|
+
import { z as z2 } from "zod";
|
|
802
|
+
|
|
803
|
+
// ../../scripts/git-worktree.mjs
|
|
804
|
+
import { execFileSync } from "child_process";
|
|
805
|
+
import { mkdir, stat } from "fs/promises";
|
|
806
|
+
import { homedir } from "os";
|
|
807
|
+
import path from "path";
|
|
808
|
+
var gitBin;
|
|
809
|
+
function execGit(args, options = {}) {
|
|
810
|
+
if (gitBin) return execFileSync(gitBin, args, options);
|
|
811
|
+
for (const bin of ["git", "/opt/homebrew/bin/git", "/usr/local/bin/git", "/usr/bin/git"]) {
|
|
812
|
+
try {
|
|
813
|
+
const out = execFileSync(bin, args, options);
|
|
814
|
+
gitBin = bin;
|
|
815
|
+
return out;
|
|
816
|
+
} catch (err) {
|
|
817
|
+
if (err?.code !== "EPERM" && err?.code !== "ENOENT") throw err;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
return execFileSync("git", args, options);
|
|
821
|
+
}
|
|
822
|
+
function resolveUserPath(rawPath) {
|
|
823
|
+
const p = rawPath.trim();
|
|
824
|
+
if (p === "~") return homedir();
|
|
825
|
+
return p.startsWith("~/") || p.startsWith("~\\") ? path.resolve(homedir(), p.slice(2)) : path.resolve(p);
|
|
826
|
+
}
|
|
827
|
+
var tryGit = (args) => {
|
|
828
|
+
try {
|
|
829
|
+
execGit(args, { stdio: "ignore" });
|
|
830
|
+
return true;
|
|
831
|
+
} catch {
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
var isGitRepoWithCommit = (dir) => tryGit(["-C", dir, "rev-parse", "--is-inside-work-tree"]) && tryGit(["-C", dir, "rev-parse", "--verify", "HEAD"]);
|
|
836
|
+
function resolveCardWorktreeTarget(repoDir, { cardId, agentId, driver }) {
|
|
837
|
+
const [c, a] = [String(cardId).slice(0, 8), String(agentId).slice(0, 8)];
|
|
838
|
+
return { worktreeDir: path.join(repoDir, ".slate-worktrees", c, a), branch: `slate/${c}/${driver}-${a}` };
|
|
839
|
+
}
|
|
840
|
+
async function ensureWorktree(repoDir, worktreeDir, branch) {
|
|
841
|
+
try {
|
|
842
|
+
if ((await stat(worktreeDir)).isDirectory()) return { ok: true, created: false, workDir: worktreeDir, branch };
|
|
843
|
+
return { ok: false, created: false, error: `\u76EE\u6807\u8DEF\u5F84\u5DF2\u5B58\u5728\u4F46\u4E0D\u662F\u76EE\u5F55\uFF1A${worktreeDir}` };
|
|
844
|
+
} catch {
|
|
845
|
+
}
|
|
846
|
+
await mkdir(path.dirname(worktreeDir), { recursive: true });
|
|
847
|
+
try {
|
|
848
|
+
tryGit(["-C", repoDir, "worktree", "prune"]);
|
|
849
|
+
const hasBranch = tryGit(["-C", repoDir, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`]);
|
|
850
|
+
const addArgs = hasBranch ? [worktreeDir, branch] : ["-b", branch, worktreeDir, "HEAD"];
|
|
851
|
+
execGit(["-C", repoDir, "worktree", "add", ...addArgs], { stdio: "pipe" });
|
|
852
|
+
return { ok: true, created: true, workDir: worktreeDir, branch };
|
|
853
|
+
} catch (err) {
|
|
854
|
+
const msg = err?.stderr ? String(err.stderr).trim() : "";
|
|
855
|
+
return { ok: false, created: false, error: msg || (err instanceof Error ? err.message : "\u521B\u5EFA Git worktree \u5931\u8D25") };
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// src/local.ts
|
|
860
|
+
function resolvePackageRoot() {
|
|
861
|
+
if (process.env.SLATE_PACKAGE_ROOT) return path2.resolve(process.env.SLATE_PACKAGE_ROOT);
|
|
862
|
+
const currentDir = path2.dirname(fileURLToPath(import.meta.url));
|
|
863
|
+
for (const rel of ["../../..", "../.."]) {
|
|
864
|
+
const candidate = path2.resolve(currentDir, rel);
|
|
865
|
+
if (existsSync(path2.join(candidate, "scripts/slate-cli.mjs"))) return candidate;
|
|
866
|
+
}
|
|
867
|
+
return path2.resolve(currentDir, "../../..");
|
|
868
|
+
}
|
|
869
|
+
var root = resolvePackageRoot();
|
|
870
|
+
var local = process.env.SLATE_HOME ? path2.resolve(process.env.SLATE_HOME) : path2.join(root, ".local");
|
|
871
|
+
var sandboxDefault = process.env.SLATE_SANDBOX ? path2.resolve(process.env.SLATE_HOME ? local : root, process.env.SLATE_SANDBOX) : process.env.SLATE_HOME ? path2.join(local, "sandbox") : path2.resolve(root, "../slate-agent-sandbox");
|
|
872
|
+
var credentialSchema = z2.object({
|
|
873
|
+
apiBase: z2.string().url(),
|
|
874
|
+
token: z2.string().regex(/^[A-Za-z0-9_-]{16,256}$/),
|
|
875
|
+
agentId: z2.string().uuid(),
|
|
876
|
+
name: z2.string().min(1),
|
|
877
|
+
driver: driverTypeSchema,
|
|
878
|
+
projectId: z2.string().uuid().nullable().optional()
|
|
879
|
+
});
|
|
880
|
+
function assertLocalApi(base) {
|
|
881
|
+
const url = new URL(base);
|
|
882
|
+
if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== "/v1") {
|
|
883
|
+
throw new Error("API \u5FC5\u987B\u662F\u672C\u673A\u56DE\u73AF /v1 \u5730\u5740");
|
|
884
|
+
}
|
|
885
|
+
return base;
|
|
886
|
+
}
|
|
887
|
+
async function atomicJson(file, value) {
|
|
888
|
+
await mkdir2(path2.dirname(file), { recursive: true, mode: 448 });
|
|
889
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
890
|
+
const handle = await open(temp, "wx", 384);
|
|
891
|
+
try {
|
|
892
|
+
try {
|
|
893
|
+
await handle.writeFile(JSON.stringify(value, null, 2));
|
|
894
|
+
} finally {
|
|
895
|
+
await handle.close();
|
|
896
|
+
}
|
|
897
|
+
await rename(temp, file);
|
|
898
|
+
} catch (error) {
|
|
899
|
+
await unlink(temp).catch(() => {
|
|
900
|
+
});
|
|
901
|
+
throw error;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
async function loadCredential(file) {
|
|
905
|
+
const info = await stat2(file);
|
|
906
|
+
if (!info.isFile() || (info.mode & 63) !== 0) {
|
|
907
|
+
throw new Error("\u51ED\u636E\u5FC5\u987B\u662F\u6743\u9650 0600 \u7684\u672C\u673A\u6587\u4EF6");
|
|
908
|
+
}
|
|
909
|
+
const cred = credentialSchema.parse(JSON.parse(await readFile(file, "utf8")));
|
|
910
|
+
assertLocalApi(cred.apiBase);
|
|
911
|
+
return cred;
|
|
912
|
+
}
|
|
913
|
+
var agentMeSchema = z2.object({
|
|
914
|
+
id: z2.string().uuid(),
|
|
915
|
+
name: z2.string().min(1),
|
|
916
|
+
driver: driverTypeSchema,
|
|
917
|
+
projectId: z2.string().uuid().nullable().optional()
|
|
918
|
+
});
|
|
919
|
+
var agentRegisterResponseSchema = z2.object({
|
|
920
|
+
agent: z2.object({
|
|
921
|
+
id: z2.string().uuid(),
|
|
922
|
+
name: z2.string().min(1),
|
|
923
|
+
driver: driverTypeSchema,
|
|
924
|
+
projectId: z2.string().uuid().nullable()
|
|
925
|
+
}),
|
|
926
|
+
token: z2.string().regex(/^[A-Za-z0-9_-]{16,256}$/)
|
|
927
|
+
});
|
|
928
|
+
async function ensureCredential(options) {
|
|
929
|
+
const baseDir = options.localDir ?? local;
|
|
930
|
+
const fetcher = options.fetcher ?? fetch;
|
|
931
|
+
const normalizedProjectId = typeof options.projectId === "string" ? options.projectId.trim() : options.projectId;
|
|
932
|
+
const expectedProjectId = normalizedProjectId === void 0 || normalizedProjectId === null ? null : z2.string().uuid("\u9879\u76EE ID \u5FC5\u987B\u662F\u5408\u6CD5 UUID").parse(normalizedProjectId);
|
|
933
|
+
const requestedName = options.name?.trim() || void 0;
|
|
934
|
+
await mkdir2(baseDir, { recursive: true, mode: 448 });
|
|
935
|
+
if (options.explicitFile) {
|
|
936
|
+
const file2 = path2.resolve(options.explicitFile);
|
|
937
|
+
const credential2 = await loadCredential(file2);
|
|
938
|
+
if (options.projectId !== void 0 && (credential2.projectId ?? null) !== expectedProjectId) {
|
|
939
|
+
throw new Error(
|
|
940
|
+
`\u51ED\u636E\u6587\u4EF6\u6240\u5C5E\u9879\u76EE\uFF08${credential2.projectId ?? "\u5168\u5C40"}\uFF09\u4E0E\u6307\u5B9A\u7684\u9879\u76EE\uFF08${expectedProjectId ?? "\u5168\u5C40"}\uFF09\u4E0D\u5339\u914D`
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
return { file: file2, credential: credential2 };
|
|
944
|
+
}
|
|
945
|
+
const apiBase = assertLocalApi(options.apiBase ?? "http://127.0.0.1:3100/v1");
|
|
946
|
+
const prefix = `agent-${options.driver}-`;
|
|
947
|
+
const files = (await readdir(baseDir)).filter((n) => n.startsWith(prefix) && n.endsWith(".json")).sort();
|
|
948
|
+
for (const name of files) {
|
|
949
|
+
const file2 = path2.join(baseDir, name);
|
|
950
|
+
try {
|
|
951
|
+
const cred = await loadCredential(file2);
|
|
952
|
+
if (cred.apiBase !== apiBase || cred.driver !== options.driver) continue;
|
|
953
|
+
const res = await fetcher(`${apiBase}/agents/me`, {
|
|
954
|
+
headers: { authorization: `Bearer ${cred.token}` },
|
|
955
|
+
signal: AbortSignal.timeout(5e3),
|
|
956
|
+
redirect: "error"
|
|
957
|
+
});
|
|
958
|
+
if (!res.ok) continue;
|
|
959
|
+
const parsedMe = agentMeSchema.safeParse(await res.json().catch(() => null));
|
|
960
|
+
if (!parsedMe.success) continue;
|
|
961
|
+
const me = parsedMe.data;
|
|
962
|
+
const serverProjectId = me.projectId ?? null;
|
|
963
|
+
if (me.id !== cred.agentId || me.driver !== options.driver) continue;
|
|
964
|
+
if (serverProjectId !== expectedProjectId) continue;
|
|
965
|
+
if (requestedName && me.name !== requestedName) continue;
|
|
966
|
+
const synced = {
|
|
967
|
+
...cred,
|
|
968
|
+
name: me.name,
|
|
969
|
+
projectId: serverProjectId
|
|
970
|
+
};
|
|
971
|
+
if (me.name !== cred.name || serverProjectId !== (cred.projectId ?? null)) {
|
|
972
|
+
await atomicJson(file2, synced).catch(() => {
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
return { file: file2, credential: synced };
|
|
976
|
+
} catch {
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
const displayName = requestedName || driverLabels[options.driver];
|
|
980
|
+
const regRes = await fetcher(`${apiBase}/agents`, {
|
|
981
|
+
method: "POST",
|
|
982
|
+
headers: { "content-type": "application/json" },
|
|
983
|
+
body: JSON.stringify({
|
|
984
|
+
name: displayName,
|
|
985
|
+
driver: options.driver,
|
|
986
|
+
projectId: expectedProjectId
|
|
987
|
+
}),
|
|
988
|
+
signal: AbortSignal.timeout(5e3),
|
|
989
|
+
redirect: "error"
|
|
990
|
+
});
|
|
991
|
+
if (!regRes.ok) {
|
|
992
|
+
const body = await regRes.json().catch(() => null);
|
|
993
|
+
const detail = body && typeof body === "object" && typeof body.message === "string" && body.message.trim() ? body.message.trim() : "\u8BF7\u786E\u8BA4\u770B\u677F API \u5DF2\u542F\u52A8";
|
|
994
|
+
throw new Error(`\u81EA\u52A8\u6CE8\u518C\u672C\u673A ${displayName} \u5931\u8D25\uFF08HTTP ${regRes.status}\uFF09\uFF1A${detail}`);
|
|
995
|
+
}
|
|
996
|
+
const created = agentRegisterResponseSchema.parse(await regRes.json());
|
|
997
|
+
const credential = {
|
|
998
|
+
apiBase,
|
|
999
|
+
token: created.token,
|
|
1000
|
+
agentId: created.agent.id,
|
|
1001
|
+
name: created.agent.name,
|
|
1002
|
+
driver: created.agent.driver,
|
|
1003
|
+
projectId: created.agent.projectId
|
|
1004
|
+
};
|
|
1005
|
+
const file = path2.join(baseDir, `agent-${credential.driver}-${credential.agentId}.json`);
|
|
1006
|
+
await atomicJson(file, credential);
|
|
1007
|
+
return { file, credential };
|
|
1008
|
+
}
|
|
1009
|
+
async function processLock(agentId) {
|
|
1010
|
+
await mkdir2(local, { recursive: true, mode: 448 });
|
|
1011
|
+
const file = path2.join(local, `agent-loop-${agentId}.lock`);
|
|
1012
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1013
|
+
try {
|
|
1014
|
+
const handle = await open(file, "wx", 384);
|
|
1015
|
+
await handle.writeFile(String(process.pid));
|
|
1016
|
+
await handle.close();
|
|
1017
|
+
return async () => {
|
|
1018
|
+
await unlink(file).catch(() => {
|
|
1019
|
+
});
|
|
1020
|
+
};
|
|
1021
|
+
} catch (e) {
|
|
1022
|
+
if (e.code !== "EEXIST") throw e;
|
|
1023
|
+
const pid = Number(await readFile(file, "utf8"));
|
|
1024
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) {
|
|
1025
|
+
await unlink(file).catch(() => {
|
|
1026
|
+
});
|
|
1027
|
+
continue;
|
|
1028
|
+
}
|
|
1029
|
+
try {
|
|
1030
|
+
process.kill(pid, 0);
|
|
1031
|
+
} catch (err) {
|
|
1032
|
+
if (err.code === "ESRCH") {
|
|
1033
|
+
await unlink(file).catch(() => {
|
|
1034
|
+
});
|
|
1035
|
+
continue;
|
|
1036
|
+
}
|
|
1037
|
+
throw err;
|
|
1038
|
+
}
|
|
1039
|
+
throw new Error(`Agent (${agentId}) \u5DF2\u6709\u63A5\u5165\u8FDB\u7A0B\u5728\u8FD0\u884C\uFF08PID ${pid}\uFF09`);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
throw new Error("\u83B7\u53D6 Agent \u8FDB\u7A0B\u9501\u5931\u8D25");
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// src/assistant/prompt.ts
|
|
1046
|
+
function formatAssistantAttachments(attachments) {
|
|
1047
|
+
if (!attachments || attachments.length === 0) return [];
|
|
1048
|
+
return [
|
|
1049
|
+
`\u7528\u6237\u968F\u672C\u6B21\u8BF7\u6C42\u9644\u5E26\u4E86 ${attachments.length} \u4E2A\u672C\u673A\u9644\u4EF6\uFF08\u8BF7\u4F18\u5148\u67E5\u770B\u8FD9\u4E9B\u56FE\u7247\u6216\u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9\uFF0C\u518D\u636E\u6B64\u751F\u6210\u6807\u9898\u3001\u4EFB\u52A1\u6587\u6863\u4E0E\u6E05\u5355\uFF09\uFF1A
|
|
1050
|
+
${attachments.map(
|
|
1051
|
+
(a, idx) => `${idx + 1}. [${a.kind === "image" ? "\u56FE\u7247" : "\u6587\u4EF6"}] ${a.filename}\uFF08${a.mimeType}\uFF0C${a.sizeBytes} bytes\uFF09-> ${a.localPath}`
|
|
1052
|
+
).join("\n")}`
|
|
1053
|
+
];
|
|
1054
|
+
}
|
|
1055
|
+
function buildAssistantPrompt(payload, agentName, driver, attachmentsOverride, options) {
|
|
1056
|
+
const { run, project, cards, agents } = payload;
|
|
1057
|
+
const effectiveAttachments = attachmentsOverride ?? payload.attachments ?? [];
|
|
1058
|
+
const compactCards = cards.map((c) => ({
|
|
1059
|
+
id: c.id,
|
|
1060
|
+
title: c.title,
|
|
1061
|
+
status: c.status,
|
|
1062
|
+
priority: c.priority,
|
|
1063
|
+
tags: c.tags,
|
|
1064
|
+
bodyPreview: c.bodyPreview.slice(0, 180),
|
|
1065
|
+
checklist: `${c.checklistDone}/${c.checklistTotal}`,
|
|
1066
|
+
participants: c.participants.map((p) => ({
|
|
1067
|
+
name: p.agentName,
|
|
1068
|
+
processing: p.processing,
|
|
1069
|
+
activityText: p.activityText
|
|
1070
|
+
})),
|
|
1071
|
+
updatedAt: c.updatedAt
|
|
1072
|
+
}));
|
|
1073
|
+
const compactAgents = agents.map((a) => ({ id: a.id, name: a.name, driver: a.driver, online: a.online }));
|
|
1074
|
+
const readOnlyCliRule = options?.hasReadOnlyCli ? "1. \u7EDD\u5BF9\u4E0D\u8981\u4FEE\u6539\u4EFB\u4F55\u672C\u5730\u6587\u4EF6\uFF0C\u4E0D\u8981\u8FD0\u884C git \u5199\u64CD\u4F5C\uFF0C\u4E5F\u4E0D\u8981\u6267\u884C\u4EFB\u4F55\u5199\u5165\u770B\u677F\u7684\u547D\u4EE4\u3002\u4F60\u53EF\u4EE5\u6309\u9700\u4F7F\u7528 PATH \u4E0A\u7684\u53EA\u8BFB `slate` CLI\uFF08\u4EC5\u9650 `slate list` / `slate read <cardId>` / `slate events [cursor] [limit] [cardId]` / `slate agents`\uFF09\u6DF1\u5165\u67E5\u770B\u5361\u7247\u5B8C\u6574\u6B63\u6587\u3001\u8BC4\u8BBA\u4E0E\u5F85\u786E\u8BA4\u9879\uFF1B\u6240\u6709\u770B\u677F\u53D8\u66F4\u5FC5\u987B\u901A\u8FC7\u6700\u7EC8 `proposals` \u4EA4\u7ED9\u4EBA\u786E\u8BA4\u3002" : "1. \u7EDD\u5BF9\u4E0D\u8981\u4FEE\u6539\u4EFB\u4F55\u672C\u5730\u6587\u4EF6\uFF0C\u4E0D\u8981\u8FD0\u884C git \u5199\u64CD\u4F5C\uFF0C\u4E5F\u4E0D\u8981\u8C03\u7528 `slate` CLI \u5199\u5165\u770B\u677F\u3002";
|
|
1075
|
+
const common = [
|
|
1076
|
+
`\u4F60\u662F Slate \u770B\u677F\u7684\u9879\u76EE\u7EA7\u52A9\u624B\u300C${agentName}\u300D\uFF08\u9A71\u52A8\uFF1A${driver}\uFF09\u3002`,
|
|
1077
|
+
"\u3010\u4E25\u683C\u7EA6\u675F\u3011\u672C\u8F6E\u4E3A\u53EA\u8BFB\u5206\u6790\u4E0E\u8349\u7A3F\u5EFA\u8BAE\u6A21\u5F0F\uFF1A",
|
|
1078
|
+
readOnlyCliRule,
|
|
1079
|
+
"2. \u8F93\u51FA\u5206\u4E3A\u4E24\u6BB5\uFF08\u4F7F\u7528\u7B80\u4F53\u4E2D\u6587\uFF0C\u7B80\u6D01\u514B\u5236\uFF09\uFF1A\u5148\u76F4\u63A5\u8F93\u51FA\u7ED9\u4EBA\u9605\u8BFB\u7684\u4E2D\u6587\u6B63\u6587\uFF08\u4E0D\u8981\u52A0\u989D\u5916\u6807\u9898\u524D\u7F00\uFF09\uFF0C\u6700\u540E\u7D27\u8DDF\u4E00\u4E2A ```slate-json ... ``` \u4EE3\u7801\u5757\u653E\u7ED3\u6784\u5316\u6570\u636E\u3002",
|
|
1080
|
+
`\u9879\u76EE\u4FE1\u606F\uFF1A${JSON.stringify({ id: project.id, name: project.name, description: project.description, hasRootPath: Boolean(project.rootPath) })}`,
|
|
1081
|
+
`\u5728\u7EBF\u4E0E\u5DF2\u6CE8\u518C Agent\uFF1A${JSON.stringify(compactAgents)}`,
|
|
1082
|
+
run.options.includeExistingCards ? `\u5F53\u524D\u9879\u76EE\u770B\u677F\u5361\u7247\uFF08\u5171 ${compactCards.length} \u5F20\uFF09\uFF1A${JSON.stringify(compactCards)}` : "\uFF08\u7528\u6237\u9009\u62E9\u672C\u8F6E\u4E0D\u53C2\u8003\u73B0\u6709\u5361\u7247\uFF09",
|
|
1083
|
+
run.options.readWorkspace && project.rootPath?.trim() ? [
|
|
1084
|
+
`\u5DF2\u5F00\u542F\u53EA\u8BFB\u5DE5\u4F5C\u533A\uFF08${resolveUserPath(project.rootPath)}\uFF09\uFF0C\u8BF7\u6309\u9700\u53EA\u8BFB\u62BD\u67E5\uFF08\u4E25\u7981\u5199\u5165\u6216\u4FEE\u6539\u4EFB\u4F55\u6587\u4EF6\uFF09\uFF1A`,
|
|
1085
|
+
"- \u62C6\u5361\u89C4\u5212\u3001\u5B9A\u4F4D\u4EE3\u7801\u95EE\u9898\u3001\u6838\u5BF9\u6280\u672F\u65B9\u6848\u6216\u6392\u67E5\u98CE\u9669\u65F6\uFF0C\u4E3B\u52A8\u53EA\u8BFB\u67E5\u9605\u76F8\u5173\u76EE\u5F55\u548C\u6587\u4EF6\uFF08\u5148\u5B9A\u4F4D\u76EE\u5F55\u4E0E\u5173\u952E\u6587\u4EF6\u518D\u7CBE\u8BFB\uFF09\uFF0C\u8BA9\u6807\u9898\u3001\u6587\u6863\u4E0E\u6E05\u5355\u8D34\u5408\u771F\u5B9E\u4EE3\u7801\uFF1B",
|
|
1086
|
+
"- \u7EAF\u770B\u677F\u6C47\u603B\u3001\u8FDB\u5EA6\u68B3\u7406\u6216\u53BB\u91CD\u6E05\u7406\u7B49\u5361\u7247\u7EA7\u6574\u7406\u4EE5\u770B\u677F\u5361\u7247\u4FE1\u606F\u4E3A\u4E3B\uFF0C\u4EC5\u5728\u9700\u8981\u6838\u5BF9\u771F\u5B9E\u5B9E\u73B0\u65F6\u6309\u9700\u62BD\u67E5\uFF0C\u907F\u514D\u65E0\u610F\u4E49\u5168\u4ED3\u76F2\u626B\u62D6\u6162\u54CD\u5E94\u3002"
|
|
1087
|
+
].join("\n") : "\u672C\u8F6E\u4E0D\u9700\u8981\u626B\u63CF\u4EE3\u7801\u4ED3\u5E93\uFF0C\u76F4\u63A5\u57FA\u4E8E\u9879\u76EE\u4E0E\u5361\u7247\u4FE1\u606F\u5B8C\u6210\u6574\u7406\u3002",
|
|
1088
|
+
...formatAssistantAttachments(effectiveAttachments)
|
|
1089
|
+
];
|
|
1090
|
+
const fieldSplitRule = [
|
|
1091
|
+
"\u3010\u5B57\u6BB5\u5206\u5DE5\u539F\u5219\uFF08\u4E25\u7981 body \u4E0E checklist \u91CD\u590D\uFF09\u3011",
|
|
1092
|
+
"- `body`\uFF08\u4EFB\u52A1\u6D3B\u6587\u6863\uFF09\uFF1A\u6C89\u6DC0\u76EE\u6807\u80CC\u666F\u3001\u8FB9\u754C\u7EA6\u675F\u4E0E\u5173\u952E\u53D6\u820D\uFF08\u8D77\u8349\u9636\u6BB5\u5199 1~3 \u53E5\u7B80\u6D01\u80CC\u666F\u76EE\u6807\u4E0E\u8FB9\u754C\u7EA6\u675F\u5373\u53EF\uFF0C\u6267\u884C\u671F\u518D\u6309\u9700\u8865\u5145\u8BBE\u8BA1\u53D6\u820D\u4E0E\u9A8C\u8BC1\u7ED3\u8BBA\uFF09\uFF1B\u82E5\u65E0\u989D\u5916\u7EA6\u675F\u65E0\u9700\u51D1\u5B57\u6570\uFF0C**\u4E25\u7981\u5728 body \u4E2D\u7F57\u5217\u5177\u4F53\u6B65\u9AA4\u6216\u590D\u8FF0 checklist**\u3002",
|
|
1093
|
+
"- `checklist`\uFF08\u4EFB\u52A1\u6E05\u5355\uFF09\uFF1A\u53EA\u653E\u53EF\u6267\u884C\u3001\u53EF\u52FE\u9009\u7684\u5177\u4F53\u52A8\u4F5C\u6761\u76EE\uFF08\u505A\u5B8C\u4E00\u6761\u52FE\u4E00\u6761\uFF09\uFF0C\u4E0D\u8981\u5199\u7A7A\u6CDB\u80CC\u666F\u6216\u91CD\u590D\u76EE\u6807\u3002"
|
|
1094
|
+
].join("\n");
|
|
1095
|
+
if (run.kind === "card_draft") {
|
|
1096
|
+
const multiRule = run.options.allowMultipleCards ? "\u7528\u6237\u660E\u786E\u8981\u6C42\u62C6\u5206\u591A\u5F20\u5361\u7247\uFF1A\u8BF7\u6309\u72EC\u7ACB\u4EA4\u4ED8\u76EE\u6807\u8F93\u51FA 2~6 \u5F20\u7ED3\u6784\u6E05\u6670\u3001\u7C92\u5EA6\u9002\u4E2D\u7684\u5361\u7247\u8349\u7A3F\u5230 `drafts` \u6570\u7EC4\uFF0C\u6BCF\u5F20\u5361\u4E25\u683C\u9075\u5FAA\u4E0A\u8FF0 body \u4E0E checklist \u5206\u5DE5\u3002" : [
|
|
1097
|
+
"\u3010\u5355\u5361\u4F18\u5148\u539F\u5219\u3011Slate \u7684\u5355\u5F20\u5361\u7247\u5DF2\u81EA\u5E26\u300C\u4EFB\u52A1\u6587\u6863 + \u591A\u6761\u4EFB\u52A1\u6E05\u5355\uFF08checklist\uFF09+ \u5355\u5361\u591A Agent \u771F\u5E76\u884C\u300D\u3002",
|
|
1098
|
+
"\u56E0\u6B64\u8BF7\u9ED8\u8BA4\u53EA\u8F93\u51FA **1 \u5F20**\u7ED3\u6784\u5316\u5361\u7247\u5230 `drafts`\uFF08\u628A\u540C\u76EE\u6807\u4E0B\u7684\u591A\u6B65\u9AA4\u62C6\u6210 `checklist` \u6570\u7EC4\uFF0C\u4E0D\u8981\u628A\u4E00\u4EF6\u4E8B\u5F3A\u884C\u62C6\u6210\u591A\u5F20\u5361\uFF09\u3002",
|
|
1099
|
+
'\u5982\u679C\u7528\u6237\u8F93\u5165\u91CC\u660E\u663E\u5305\u542B\u591A\u4EF6\u5F7C\u6B64\u5B8C\u5168\u65E0\u5173\u3001\u9700\u8981\u72EC\u7ACB\u9A8C\u6536\u7684\u4E8B\u9879\uFF0C\u4F9D\u7136\u5148\u5728 `drafts` \u91CC\u7ED9 1 \u5F20\u4E3B\u5361\uFF0C\u540C\u65F6\u5728 `splitSuggestion` \u5B57\u6BB5\u7528\u4E00\u53E5\u8BDD\u63D0\u793A\uFF08\u5982\uFF1A"\u68C0\u6D4B\u5230 3 \u4EF6\u72EC\u7ACB\u4E8B\u9879\uFF0C\u53EF\u6309\u9700\u5207\u6362\u4E3A\u62C6\u6210 3 \u5F20\u5361"\uFF09\u3002'
|
|
1100
|
+
].join("\n");
|
|
1101
|
+
return [
|
|
1102
|
+
...common,
|
|
1103
|
+
multiRule,
|
|
1104
|
+
fieldSplitRule,
|
|
1105
|
+
"\u82E5\u53D1\u73B0\u4E0E\u73B0\u6709\u67D0\u5F20\u5361\u7247\u9AD8\u5EA6\u76F8\u4F3C\uFF0C\u5728\u8BE5\u8349\u7A3F\u586B\u5199 `duplicateOfCardId`\uFF08\u5FC5\u987B\u662F\u4E0A\u9762\u5217\u8868\u4E2D\u7684\u771F\u5B9E\u5361\u7247 id\uFF09\u548C\u7B80\u77ED `duplicateReason`\u3002",
|
|
1106
|
+
'\u82E5\u7528\u6237\u610F\u56FE\u6781\u5176\u6A21\u7CCA\uFF08\u4F8B\u5982\u53EA\u6709\u4E24\u4E09\u4E2A\u5B57\u5982"\u4F18\u5316\u4E00\u4E0B"\uFF09\uFF0C\u53EF\u4EE5\u586B\u5199 `clarifyQuestion`\uFF08\u6700\u591A 1 \u4E2A\u7B80\u77ED\u8FFD\u95EE\uFF09\uFF0C\u4F46\u4ECD\u5FC5\u987B\u7ED9\u51FA 1 \u4EFD\u53EF\u7F16\u8F91\u8349\u7A3F\u3002',
|
|
1107
|
+
"\u8BF7\u5148\u7528 1~2 \u53E5\u7B80\u6D01\u4E2D\u6587\u8BF4\u660E\u4F60\u7684\u6574\u7406\u601D\u8DEF\uFF08\u8BE5\u6BB5\u6587\u5B57\u4F1A\u5B9E\u65F6\u5C55\u793A\u7ED9\u7528\u6237\uFF09\uFF0C\u7136\u540E\u5728\u672B\u5C3E\u4E25\u683C\u9644\u5E26\u5982\u4E0B ```slate-json \u4EE3\u7801\u5757\uFF1A",
|
|
1108
|
+
"```slate-json",
|
|
1109
|
+
JSON.stringify(
|
|
1110
|
+
{
|
|
1111
|
+
clarifyQuestion: "(\u53EF\u9009\uFF0C\u4EC5\u8F93\u5165\u660E\u663E\u6A21\u7CCA\u65F6\u586B\u5199)",
|
|
1112
|
+
splitSuggestion: "(\u53EF\u9009\uFF0C\u4EC5\u68C0\u6D4B\u5230\u591A\u4EF6\u5B8C\u5168\u65E0\u5173\u4E8B\u9879\u65F6\u586B\u5199)",
|
|
1113
|
+
drafts: [
|
|
1114
|
+
{
|
|
1115
|
+
title: "\u6E05\u6670\u5177\u4F53\u7684\u4EFB\u52A1\u6807\u9898",
|
|
1116
|
+
body: "1~3 \u53E5\u80CC\u666F\u76EE\u6807\u4E0E\u8FB9\u754C\u7EA6\u675F\uFF08\u4E0D\u5217\u6B65\u9AA4\u3001\u4E0D\u91CD\u590D checklist\uFF09",
|
|
1117
|
+
status: "todo",
|
|
1118
|
+
priority: "medium",
|
|
1119
|
+
tags: ["\u524D\u7AEF"],
|
|
1120
|
+
checklist: ["\u5177\u4F53\u53EF\u52FE\u9009\u52A8\u4F5C\u4E00", "\u5177\u4F53\u53EF\u52FE\u9009\u52A8\u4F5C\u4E8C"],
|
|
1121
|
+
suggestedAgentIds: ["(\u53EF\u9009\uFF0C\u4ECE\u4E0A\u9762 Agent \u5217\u8868\u4E2D\u9009 id)"],
|
|
1122
|
+
duplicateOfCardId: null,
|
|
1123
|
+
duplicateReason: ""
|
|
1124
|
+
}
|
|
1125
|
+
]
|
|
1126
|
+
},
|
|
1127
|
+
null,
|
|
1128
|
+
2
|
|
1129
|
+
),
|
|
1130
|
+
"```",
|
|
1131
|
+
`\u7528\u6237\u5EFA\u5361\u610F\u56FE\uFF1A
|
|
1132
|
+
${run.prompt}`
|
|
1133
|
+
].join("\n\n");
|
|
1134
|
+
}
|
|
1135
|
+
return [
|
|
1136
|
+
...common,
|
|
1137
|
+
"\u8BF7\u57FA\u4E8E\u5F53\u524D\u9879\u76EE\u5361\u7247\u56DE\u7B54\u7528\u6237\u95EE\u9898\uFF1A",
|
|
1138
|
+
"- \u5148\u76F4\u63A5\u7528\u7CBE\u70BC\u3001\u76F4\u767D\u7684\u4E2D\u6587\u5199\u51FA\u5206\u6790\u7ED3\u8BBA\uFF08\u4E0D\u8981\u5E9F\u8BDD\uFF0C\u8BE5\u6BB5\u6587\u5B57\u4F1A\u5B9E\u65F6\u6D41\u5F0F\u5C55\u793A\u7ED9\u7528\u6237\uFF09\u3002",
|
|
1139
|
+
"- \u7136\u540E\u5728\u56DE\u590D\u672B\u5C3E\u9644\u4E00\u4E2A ```slate-json \u4EE3\u7801\u5757\uFF0C\u5305\u542B `cardRefs`\uFF08\u91CD\u70B9\u63D0\u5230\u7684\u771F\u5B9E\u5361\u7247 ID\uFF09\u4E0E `proposals`\uFF08\u9700\u8981\u6539\u5361/\u5EFA\u5361/\u5F52\u6863\u65F6\u7684\u5F85\u786E\u8BA4\u63D0\u6848\uFF0C\u7EAF\u53EA\u8BFB\u95EE\u7B54\u65F6\u8FD4\u56DE `[]`\uFF09\u3002",
|
|
1140
|
+
fieldSplitRule,
|
|
1141
|
+
"\u672B\u5C3E\u7ED3\u6784\u5316\u5757\u793A\u4F8B\uFF1A",
|
|
1142
|
+
"```slate-json",
|
|
1143
|
+
JSON.stringify(
|
|
1144
|
+
{
|
|
1145
|
+
cardRefs: [{ cardId: "\u771F\u5B9E\u5361\u7247UUID", title: "\u5361\u7247\u6807\u9898", status: "doing", note: "\u7B80\u77ED\u6807\u6CE8" }],
|
|
1146
|
+
proposals: [
|
|
1147
|
+
{
|
|
1148
|
+
id: "p1",
|
|
1149
|
+
type: "archive_card",
|
|
1150
|
+
cardId: "\u771F\u5B9E\u5361\u7247UUID",
|
|
1151
|
+
cardTitle: "\u5361\u7247\u6807\u9898",
|
|
1152
|
+
summary: "\u5F52\u6863\u5DF2\u5B8C\u6210\u5361\u7247\u300Axxx\u300B"
|
|
1153
|
+
},
|
|
1154
|
+
{
|
|
1155
|
+
id: "p2",
|
|
1156
|
+
type: "update_card",
|
|
1157
|
+
cardId: "\u771F\u5B9E\u5361\u7247UUID",
|
|
1158
|
+
cardTitle: "\u5361\u7247\u6807\u9898",
|
|
1159
|
+
summary: "\u5C06\u300Axxx\u300B\u8C03\u6574\u4E3A\u9AD8\u4F18\u5148",
|
|
1160
|
+
patch: { priority: "high" }
|
|
1161
|
+
},
|
|
1162
|
+
{
|
|
1163
|
+
id: "p3",
|
|
1164
|
+
type: "create_card",
|
|
1165
|
+
summary: "\u65B0\u5EFA\u5B50\u5361\u300Axxx\u300B",
|
|
1166
|
+
draft: {
|
|
1167
|
+
title: "\u5B50\u5361\u6807\u9898",
|
|
1168
|
+
body: "1~2 \u53E5\u76EE\u6807\u4E0E\u8FB9\u754C\u7EA6\u675F\uFF08\u4E0D\u91CD\u590D checklist\uFF09",
|
|
1169
|
+
status: "todo",
|
|
1170
|
+
priority: "medium",
|
|
1171
|
+
tags: ["\u524D\u7AEF"],
|
|
1172
|
+
checklist: ["\u5177\u4F53\u53EF\u52FE\u9009\u52A8\u4F5C\u4E00"],
|
|
1173
|
+
suggestedAgentIds: [],
|
|
1174
|
+
parentId: null
|
|
1175
|
+
},
|
|
1176
|
+
mentions: [],
|
|
1177
|
+
skipDefaultAgent: false
|
|
1178
|
+
}
|
|
1179
|
+
]
|
|
1180
|
+
},
|
|
1181
|
+
null,
|
|
1182
|
+
2
|
|
1183
|
+
),
|
|
1184
|
+
"```",
|
|
1185
|
+
`\u7528\u6237\u8BF7\u6C42\uFF08preset=${run.preset ?? "custom"}\uFF09\uFF1A
|
|
1186
|
+
${run.prompt}`
|
|
1187
|
+
].join("\n\n");
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
// src/workspace.ts
|
|
1191
|
+
import { chmod, mkdir as mkdir3, readFile as readFile2, writeFile } from "fs/promises";
|
|
1192
|
+
import path3 from "path";
|
|
1193
|
+
import { pathToFileURL } from "url";
|
|
1194
|
+
async function prepareCardWorkspace(options) {
|
|
1195
|
+
const { project, cardId, agentId, driver, credentialFile, runId } = options;
|
|
1196
|
+
const baseLocalDir = options.localDir ?? local;
|
|
1197
|
+
const baseSandboxDir = options.sandboxDir ?? sandboxDefault;
|
|
1198
|
+
const cardShort = cardId.slice(0, 8);
|
|
1199
|
+
const actorShort = agentId.slice(0, 8);
|
|
1200
|
+
const hasRoot = Boolean(project.rootPath?.trim());
|
|
1201
|
+
let workDir;
|
|
1202
|
+
let branch = null;
|
|
1203
|
+
let projectRoot = null;
|
|
1204
|
+
let gitAvailable = false;
|
|
1205
|
+
let isSandboxOrIsolated = true;
|
|
1206
|
+
if (hasRoot) {
|
|
1207
|
+
const resolvedRoot = resolveUserPath(project.rootPath);
|
|
1208
|
+
await mkdir3(resolvedRoot, { recursive: true });
|
|
1209
|
+
projectRoot = resolvedRoot;
|
|
1210
|
+
gitAvailable = isGitRepoWithCommit(resolvedRoot);
|
|
1211
|
+
const mode = project.parallelMode;
|
|
1212
|
+
if (mode === "worktree" && gitAvailable) {
|
|
1213
|
+
const target = resolveCardWorktreeTarget(resolvedRoot, { cardId, agentId, driver });
|
|
1214
|
+
if ((await ensureWorktree(resolvedRoot, target.worktreeDir, target.branch)).ok) {
|
|
1215
|
+
workDir = target.worktreeDir;
|
|
1216
|
+
branch = target.branch;
|
|
1217
|
+
isSandboxOrIsolated = false;
|
|
1218
|
+
} else {
|
|
1219
|
+
workDir = path3.join(resolvedRoot, ".slate-actors", cardShort, actorShort);
|
|
1220
|
+
await mkdir3(workDir, { recursive: true });
|
|
1221
|
+
}
|
|
1222
|
+
} else if (mode === "shared") {
|
|
1223
|
+
workDir = resolvedRoot;
|
|
1224
|
+
isSandboxOrIsolated = false;
|
|
1225
|
+
} else {
|
|
1226
|
+
workDir = path3.join(resolvedRoot, ".slate-actors", cardShort, actorShort);
|
|
1227
|
+
await mkdir3(workDir, { recursive: true });
|
|
1228
|
+
}
|
|
1229
|
+
} else {
|
|
1230
|
+
workDir = path3.join(baseSandboxDir, "cards", cardId, "actors", agentId);
|
|
1231
|
+
await mkdir3(workDir, { recursive: true });
|
|
1232
|
+
}
|
|
1233
|
+
const runtimeConfigFile = path3.join(baseLocalDir, "runtimes", `${agentId}-${cardId}.json`);
|
|
1234
|
+
await atomicJson(runtimeConfigFile, {
|
|
1235
|
+
credentialFile,
|
|
1236
|
+
cardId,
|
|
1237
|
+
projectId: project.id,
|
|
1238
|
+
agentId,
|
|
1239
|
+
driver,
|
|
1240
|
+
parallelMode: project.parallelMode,
|
|
1241
|
+
projectRoot,
|
|
1242
|
+
workDir,
|
|
1243
|
+
branch,
|
|
1244
|
+
runId
|
|
1245
|
+
});
|
|
1246
|
+
const binDir = path3.join(baseLocalDir, "bins", `${agentId}-${cardId}`);
|
|
1247
|
+
await mkdir3(binDir, { recursive: true, mode: 448 });
|
|
1248
|
+
const launcher = `#!${process.execPath}
|
|
1249
|
+
import { main } from ${JSON.stringify(pathToFileURL(path3.join(root, "scripts/slate-cli.mjs")).href)};
|
|
1250
|
+
process.exitCode = await main(${JSON.stringify(runtimeConfigFile)});
|
|
1251
|
+
`;
|
|
1252
|
+
const slateBin = path3.join(binDir, "slate");
|
|
1253
|
+
await writeFile(slateBin, launcher, { mode: 448 });
|
|
1254
|
+
await chmod(slateBin, 448);
|
|
1255
|
+
const sourceSkill = path3.join(root, "skills/slate-card/SKILL.md");
|
|
1256
|
+
let skillPath = sourceSkill;
|
|
1257
|
+
if (isSandboxOrIsolated) {
|
|
1258
|
+
const skillContent = await readFile2(sourceSkill, "utf8");
|
|
1259
|
+
const relSkillDir = driver === "claude-code" ? ".claude/skills/slate-card" : ".agents/skills/slate-card";
|
|
1260
|
+
const targetDir = path3.join(workDir, relSkillDir);
|
|
1261
|
+
await mkdir3(targetDir, { recursive: true, mode: 448 });
|
|
1262
|
+
skillPath = path3.join(targetDir, "SKILL.md");
|
|
1263
|
+
await writeFile(skillPath, skillContent, { mode: 384 });
|
|
1264
|
+
const guideFile = driver === "claude-code" ? "CLAUDE.md" : "AGENTS.md";
|
|
1265
|
+
await writeFile(
|
|
1266
|
+
path3.join(workDir, guideFile),
|
|
1267
|
+
`\u8BF7\u9605\u8BFB\u5E76\u9075\u5FAA ${relSkillDir}/SKILL.md\uFF0C\u4F7F\u7528 PATH \u4E0A\u7684 slate CLI \u8BFB\u5199\u4E0E\u7F16\u8F91\u4EFB\u52A1\u5361\u7247\u3002
|
|
1268
|
+
`,
|
|
1269
|
+
{ mode: 384 }
|
|
1270
|
+
);
|
|
1271
|
+
}
|
|
1272
|
+
return { workDir, branch, projectRoot, gitAvailable, binDir, skillPath, runtimeConfigFile };
|
|
1273
|
+
}
|
|
1274
|
+
async function prepareAssistantReadOnlyCli(options) {
|
|
1275
|
+
const { projectId, agentId, credentialFile, runId } = options;
|
|
1276
|
+
const runtimeConfigFile = path3.join(local, "runtimes", `assistant-${agentId}-${projectId}.json`);
|
|
1277
|
+
await atomicJson(runtimeConfigFile, {
|
|
1278
|
+
credentialFile,
|
|
1279
|
+
projectId,
|
|
1280
|
+
runId,
|
|
1281
|
+
readOnly: true
|
|
1282
|
+
});
|
|
1283
|
+
const binDir = path3.join(local, "bins", `assistant-${agentId}-${projectId}`);
|
|
1284
|
+
await mkdir3(binDir, { recursive: true, mode: 448 });
|
|
1285
|
+
const launcher = `#!${process.execPath}
|
|
1286
|
+
import { main } from ${JSON.stringify(pathToFileURL(path3.join(root, "scripts/slate-cli.mjs")).href)};
|
|
1287
|
+
process.exitCode = await main(${JSON.stringify(runtimeConfigFile)});
|
|
1288
|
+
`;
|
|
1289
|
+
const slateBin = path3.join(binDir, "slate");
|
|
1290
|
+
await writeFile(slateBin, launcher, { mode: 448 });
|
|
1291
|
+
await chmod(slateBin, 448);
|
|
1292
|
+
return { binDir, runtimeConfigFile };
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// src/assistant.ts
|
|
1296
|
+
var AssistantRunner = class {
|
|
1297
|
+
constructor(api, driver, options) {
|
|
1298
|
+
this.api = api;
|
|
1299
|
+
this.driver = driver;
|
|
1300
|
+
this.options = options;
|
|
1301
|
+
}
|
|
1302
|
+
api;
|
|
1303
|
+
driver;
|
|
1304
|
+
options;
|
|
1305
|
+
active;
|
|
1306
|
+
drainPromise;
|
|
1307
|
+
dirty = false;
|
|
1308
|
+
stopped = false;
|
|
1309
|
+
log(msg) {
|
|
1310
|
+
this.options.log?.(`[${this.options.agentName}] ${msg}`);
|
|
1311
|
+
}
|
|
1312
|
+
trigger() {
|
|
1313
|
+
if (this.stopped) return;
|
|
1314
|
+
this.dirty = true;
|
|
1315
|
+
if (this.drainPromise) return;
|
|
1316
|
+
const loop = this.drain().finally(() => {
|
|
1317
|
+
if (this.drainPromise === loop) {
|
|
1318
|
+
this.drainPromise = void 0;
|
|
1319
|
+
}
|
|
1320
|
+
if (this.dirty && !this.stopped) {
|
|
1321
|
+
this.trigger();
|
|
1322
|
+
}
|
|
1323
|
+
});
|
|
1324
|
+
this.drainPromise = loop;
|
|
1325
|
+
}
|
|
1326
|
+
abortRun(runId) {
|
|
1327
|
+
if (this.active && this.active.runId === runId) {
|
|
1328
|
+
this.log(`\u6536\u5230\u53D6\u6D88\u6307\u4EE4\uFF0C\u4E2D\u6B62\u52A9\u624B\u4EFB\u52A1 ${runId.slice(0, 8)}`);
|
|
1329
|
+
this.active.controller.abort();
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
async drain() {
|
|
1333
|
+
while (this.dirty && !this.stopped) {
|
|
1334
|
+
this.dirty = false;
|
|
1335
|
+
let claimed = null;
|
|
1336
|
+
try {
|
|
1337
|
+
const res = await this.api.claimAssistantRun();
|
|
1338
|
+
claimed = res.claimed;
|
|
1339
|
+
} catch (err) {
|
|
1340
|
+
this.log(`\u62C9\u53D6\u52A9\u624B\u4EFB\u52A1\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}`);
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
if (!claimed) return;
|
|
1344
|
+
if (this.stopped) {
|
|
1345
|
+
await this.api.reportAssistantRunProgress(claimed.run.id, { status: "cancelled", activityText: "\u5DF2\u53D6\u6D88" }).catch(() => {
|
|
1346
|
+
});
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
const controller = new AbortController();
|
|
1350
|
+
this.active = { runId: claimed.run.id, controller };
|
|
1351
|
+
try {
|
|
1352
|
+
await this.execute(claimed, controller.signal);
|
|
1353
|
+
} catch (err) {
|
|
1354
|
+
this.log(`\u52A9\u624B\u4EFB\u52A1\u6267\u884C\u5F02\u5E38\uFF1A${err instanceof Error ? err.message : String(err)}`);
|
|
1355
|
+
} finally {
|
|
1356
|
+
if (this.active?.runId === claimed.run.id) {
|
|
1357
|
+
this.active = void 0;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
this.dirty = true;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
async execute(payload, signal) {
|
|
1364
|
+
const { run, project } = payload;
|
|
1365
|
+
this.log(`\u5F00\u59CB\u5904\u7406\u9879\u76EE\u52A9\u624B\u4EFB\u52A1 ${run.id.slice(0, 8)} (${run.kind})`);
|
|
1366
|
+
const fallbackDir = path4.join(local, "assistant-sandbox", project.id);
|
|
1367
|
+
const emptyBinDir = path4.join(local, "assistant-empty-bin");
|
|
1368
|
+
await Promise.all([
|
|
1369
|
+
mkdir4(fallbackDir, { recursive: true, mode: 448 }),
|
|
1370
|
+
mkdir4(emptyBinDir, { recursive: true, mode: 448 })
|
|
1371
|
+
]);
|
|
1372
|
+
let binDir = emptyBinDir;
|
|
1373
|
+
let hasReadOnlyCli = false;
|
|
1374
|
+
if (this.options.credentialFile) {
|
|
1375
|
+
const cliPreparer = this.options.cliPreparer ?? prepareAssistantReadOnlyCli;
|
|
1376
|
+
const prepared = await cliPreparer({
|
|
1377
|
+
projectId: project.id,
|
|
1378
|
+
agentId: this.options.agentId,
|
|
1379
|
+
credentialFile: this.options.credentialFile,
|
|
1380
|
+
runId: run.id
|
|
1381
|
+
});
|
|
1382
|
+
binDir = prepared.binDir;
|
|
1383
|
+
hasReadOnlyCli = true;
|
|
1384
|
+
}
|
|
1385
|
+
const resolvedRoot = project.rootPath?.trim() ? resolveUserPath(project.rootPath) : "";
|
|
1386
|
+
const workDir = run.options.readWorkspace && resolvedRoot && existsSync2(resolvedRoot) ? resolvedRoot : fallbackDir;
|
|
1387
|
+
const rawAttachments = payload.attachments ?? [];
|
|
1388
|
+
let stagedDir = null;
|
|
1389
|
+
let effectiveAttachments = rawAttachments;
|
|
1390
|
+
if (rawAttachments.some((att) => Boolean(att.localPath) && existsSync2(att.localPath))) {
|
|
1391
|
+
const targetDir = path4.join(fallbackDir, "attachments", run.id);
|
|
1392
|
+
stagedDir = targetDir;
|
|
1393
|
+
await mkdir4(targetDir, { recursive: true, mode: 448 });
|
|
1394
|
+
effectiveAttachments = await Promise.all(
|
|
1395
|
+
rawAttachments.map(async (att, idx) => {
|
|
1396
|
+
if (!att.localPath || !existsSync2(att.localPath)) return att;
|
|
1397
|
+
const safeName = `${idx + 1}-${att.filename.replace(/[^a-zA-Z0-9._-]/g, "_")}`;
|
|
1398
|
+
const stagedPath = path4.join(targetDir, safeName);
|
|
1399
|
+
try {
|
|
1400
|
+
await copyFile(att.localPath, stagedPath);
|
|
1401
|
+
return { ...att, localPath: stagedPath };
|
|
1402
|
+
} catch {
|
|
1403
|
+
return att;
|
|
1404
|
+
}
|
|
1405
|
+
})
|
|
1406
|
+
);
|
|
1407
|
+
}
|
|
1408
|
+
const imagePaths = effectiveAttachments.filter((a) => a.kind === "image" && Boolean(a.localPath) && existsSync2(a.localPath)).map((a) => a.localPath);
|
|
1409
|
+
const addDirs = stagedDir && workDir !== fallbackDir ? [stagedDir] : [];
|
|
1410
|
+
const prompt = buildAssistantPrompt(payload, this.options.agentName, this.driver.type, effectiveAttachments, {
|
|
1411
|
+
hasReadOnlyCli
|
|
1412
|
+
});
|
|
1413
|
+
const recordFile = path4.join(this.options.recordsDir, `assistant-${run.id}.json`);
|
|
1414
|
+
let lastPush = 0;
|
|
1415
|
+
const pushActivity = (text) => {
|
|
1416
|
+
const now = Date.now();
|
|
1417
|
+
if (now - lastPush < 2e3) return;
|
|
1418
|
+
lastPush = now;
|
|
1419
|
+
void this.api.reportAssistantRunProgress(run.id, {
|
|
1420
|
+
status: "running",
|
|
1421
|
+
activityText: text.slice(0, 280)
|
|
1422
|
+
}).catch(() => {
|
|
1423
|
+
});
|
|
1424
|
+
};
|
|
1425
|
+
let lastStreamPush = 0;
|
|
1426
|
+
let lastStreamPayload = "";
|
|
1427
|
+
let lastStreamStage = null;
|
|
1428
|
+
let streamTimer;
|
|
1429
|
+
let pendingStream = null;
|
|
1430
|
+
const flushStream = () => {
|
|
1431
|
+
streamTimer = void 0;
|
|
1432
|
+
if (!pendingStream || !this.api.streamAssistantRun || signal.aborted) return;
|
|
1433
|
+
const next = pendingStream;
|
|
1434
|
+
pendingStream = null;
|
|
1435
|
+
const key = `${next.stage}:${next.text}`;
|
|
1436
|
+
if (key === lastStreamPayload) return;
|
|
1437
|
+
lastStreamPayload = key;
|
|
1438
|
+
lastStreamPush = Date.now();
|
|
1439
|
+
void this.api.streamAssistantRun(run.id, next).catch(() => {
|
|
1440
|
+
});
|
|
1441
|
+
};
|
|
1442
|
+
const pushDelta = (rawAccumulated) => {
|
|
1443
|
+
if (!this.api.streamAssistantRun || signal.aborted) return;
|
|
1444
|
+
const visible = extractVisibleStreamState(rawAccumulated);
|
|
1445
|
+
const activityText = visible.stage === "structuring" ? run.kind === "card_draft" ? "\u6B63\u5728\u7EC4\u88C5\u53EF\u7F16\u8F91\u8349\u7A3F\u4E0E\u4EFB\u52A1\u6E05\u5355\u2026" : "\u6B63\u5728\u6574\u7406\u5361\u7247\u5F15\u7528\u4E0E\u5F85\u786E\u8BA4\u63D0\u6848\u2026" : void 0;
|
|
1446
|
+
pendingStream = {
|
|
1447
|
+
text: visible.text,
|
|
1448
|
+
stage: visible.stage,
|
|
1449
|
+
...activityText ? { activityText } : {}
|
|
1450
|
+
};
|
|
1451
|
+
const stageChanged = visible.stage !== lastStreamStage;
|
|
1452
|
+
lastStreamStage = visible.stage;
|
|
1453
|
+
const elapsed = Date.now() - lastStreamPush;
|
|
1454
|
+
if (stageChanged || elapsed >= 120) {
|
|
1455
|
+
if (streamTimer) clearTimeout(streamTimer);
|
|
1456
|
+
flushStream();
|
|
1457
|
+
} else if (!streamTimer) {
|
|
1458
|
+
streamTimer = setTimeout(flushStream, 120 - elapsed);
|
|
1459
|
+
}
|
|
1460
|
+
};
|
|
1461
|
+
const runOnce = (sessionId) => this.driver.run({
|
|
1462
|
+
prompt,
|
|
1463
|
+
workDir,
|
|
1464
|
+
binDir,
|
|
1465
|
+
signal,
|
|
1466
|
+
recordFile,
|
|
1467
|
+
sessionId,
|
|
1468
|
+
...imagePaths.length > 0 ? { imagePaths } : {},
|
|
1469
|
+
...addDirs.length > 0 ? { addDirs } : {},
|
|
1470
|
+
readOnly: true,
|
|
1471
|
+
streamPartial: true,
|
|
1472
|
+
onSessionStarted: async (sid) => {
|
|
1473
|
+
await this.api.reportAssistantRunProgress(run.id, { status: "running", sessionId: sid }).catch(() => {
|
|
1474
|
+
});
|
|
1475
|
+
},
|
|
1476
|
+
onActivity: pushActivity,
|
|
1477
|
+
onDelta: pushDelta
|
|
1478
|
+
});
|
|
1479
|
+
let res;
|
|
1480
|
+
try {
|
|
1481
|
+
res = await runOnce(run.sessionId ?? void 0);
|
|
1482
|
+
if (run.sessionId && res.resumeUnavailable && !signal.aborted) {
|
|
1483
|
+
res = await runOnce(void 0);
|
|
1484
|
+
}
|
|
1485
|
+
} finally {
|
|
1486
|
+
if (streamTimer) clearTimeout(streamTimer);
|
|
1487
|
+
if (stagedDir) await rm(stagedDir, { recursive: true, force: true }).catch(() => {
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
if (res.authFailure) this.options.onAuthChanged?.();
|
|
1491
|
+
if (res.aborted || signal.aborted) {
|
|
1492
|
+
await this.api.reportAssistantRunProgress(run.id, { status: "cancelled", activityText: "\u5DF2\u53D6\u6D88" }).catch(() => {
|
|
1493
|
+
});
|
|
1494
|
+
return;
|
|
1495
|
+
}
|
|
1496
|
+
if (res.authFailure) {
|
|
1497
|
+
await this.api.reportAssistantRunProgress(run.id, {
|
|
1498
|
+
status: "failed",
|
|
1499
|
+
activityText: "\u767B\u5F55\u72B6\u6001\u5DF2\u5931\u6548",
|
|
1500
|
+
errorMessage: res.authFailure.loginMessage ?? "\u672C\u673A CLI \u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u540E\u91CD\u8BD5"
|
|
1501
|
+
}).catch(() => {
|
|
1502
|
+
});
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
if (res.outerExit !== 0 || !res.completed) {
|
|
1506
|
+
await this.api.reportAssistantRunProgress(run.id, {
|
|
1507
|
+
status: "failed",
|
|
1508
|
+
activityText: "\u6267\u884C\u5931\u8D25",
|
|
1509
|
+
errorMessage: res.errorMessage ?? `\u672C\u5730 CLI \u9000\u51FA\u5F02\u5E38\uFF08code=${res.outerExit ?? "signal"}\uFF09`
|
|
1510
|
+
}).catch(() => {
|
|
1511
|
+
});
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
const parsed = parseAssistantOutput(res.finalOutput ?? "", payload);
|
|
1515
|
+
await this.api.reportAssistantRunProgress(run.id, {
|
|
1516
|
+
status: "succeeded",
|
|
1517
|
+
activityText: run.kind === "card_draft" ? "\u8349\u7A3F\u5DF2\u5C31\u7EEA" : "\u5206\u6790\u5B8C\u6210",
|
|
1518
|
+
...res.sessionId ? { sessionId: res.sessionId } : {},
|
|
1519
|
+
result: parsed
|
|
1520
|
+
}).catch(() => {
|
|
1521
|
+
});
|
|
1522
|
+
this.log(
|
|
1523
|
+
`\u5B8C\u6210\u52A9\u624B\u4EFB\u52A1 ${run.id.slice(0, 8)} (drafts=${parsed.drafts.length}, proposals=${parsed.proposals.length})`
|
|
1524
|
+
);
|
|
1525
|
+
}
|
|
1526
|
+
async stop() {
|
|
1527
|
+
this.stopped = true;
|
|
1528
|
+
this.active?.controller.abort();
|
|
1529
|
+
await this.drainPromise;
|
|
1530
|
+
}
|
|
1531
|
+
};
|
|
1532
|
+
|
|
1533
|
+
// src/drivers/antigravity.ts
|
|
1534
|
+
import { spawn } from "child_process";
|
|
1535
|
+
import { existsSync as existsSync3, statSync as statSync2 } from "fs";
|
|
1536
|
+
import { homedir as homedir2 } from "os";
|
|
1537
|
+
import path6 from "path";
|
|
1538
|
+
|
|
1539
|
+
// src/sessions.ts
|
|
1540
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
1541
|
+
import { z as z3 } from "zod";
|
|
1542
|
+
var sessionIdSchema = z3.string().trim().min(1).max(200);
|
|
1543
|
+
var bindingSchema = z3.object({
|
|
1544
|
+
sessionId: sessionIdSchema,
|
|
1545
|
+
lastEventId: z3.string().uuid(),
|
|
1546
|
+
lastEventSeq: z3.string().regex(/^\d+$/),
|
|
1547
|
+
workDir: z3.string().min(1).optional(),
|
|
1548
|
+
updatedAt: z3.string()
|
|
1549
|
+
});
|
|
1550
|
+
var storeSchema = z3.object({
|
|
1551
|
+
version: z3.literal(2),
|
|
1552
|
+
cards: z3.record(z3.string().uuid(), bindingSchema)
|
|
1553
|
+
});
|
|
1554
|
+
var CardSessions = class {
|
|
1555
|
+
constructor(file) {
|
|
1556
|
+
this.file = file;
|
|
1557
|
+
}
|
|
1558
|
+
file;
|
|
1559
|
+
cards = {};
|
|
1560
|
+
saves = Promise.resolve();
|
|
1561
|
+
async init() {
|
|
1562
|
+
try {
|
|
1563
|
+
const parsed = storeSchema.parse(JSON.parse(await readFile3(this.file, "utf8")));
|
|
1564
|
+
this.cards = parsed.cards;
|
|
1565
|
+
} catch (e) {
|
|
1566
|
+
if (e.code === "ENOENT") {
|
|
1567
|
+
this.cards = {};
|
|
1568
|
+
return;
|
|
1569
|
+
}
|
|
1570
|
+
this.cards = {};
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
get(cardId) {
|
|
1574
|
+
return this.cards[cardId];
|
|
1575
|
+
}
|
|
1576
|
+
async set(cardId, binding) {
|
|
1577
|
+
this.cards[cardId] = bindingSchema.parse(binding);
|
|
1578
|
+
const snapshot = structuredClone({ version: 2, cards: this.cards });
|
|
1579
|
+
this.saves = this.saves.catch(() => {
|
|
1580
|
+
}).then(() => atomicJson(this.file, snapshot));
|
|
1581
|
+
await this.saves;
|
|
1582
|
+
}
|
|
1583
|
+
};
|
|
1584
|
+
|
|
1585
|
+
// src/drivers/types.ts
|
|
1586
|
+
import { accessSync, constants, statSync } from "fs";
|
|
1587
|
+
import path5 from "path";
|
|
1588
|
+
function detectAuthFailure(text, driverLabel, loginHint) {
|
|
1589
|
+
const clean = stripAnsi(text);
|
|
1590
|
+
if (/oauth access token has expired|token has expired|token_expired|please run \/login|re-authenticate to continue|authentication_error|invalid_grant/i.test(
|
|
1591
|
+
clean
|
|
1592
|
+
) || /\b401\b/.test(clean) && /oauth|token|unauthori[sz]ed|auth|login|expired|credential/i.test(clean)) {
|
|
1593
|
+
return { loginState: "expired", loginMessage: `${driverLabel} \u4EE4\u724C\u5DF2\u8FC7\u671F\uFF0C${loginHint}` };
|
|
1594
|
+
}
|
|
1595
|
+
if (/not logged in|please log ?in|login required|unauthenticated/i.test(clean)) {
|
|
1596
|
+
return { loginState: "logged_out", loginMessage: `${driverLabel} \u5C1A\u672A\u767B\u5F55\uFF0C${loginHint}` };
|
|
1597
|
+
}
|
|
1598
|
+
return null;
|
|
1599
|
+
}
|
|
1600
|
+
function isExecutableFile(filePath) {
|
|
1601
|
+
try {
|
|
1602
|
+
if (!statSync(filePath).isFile()) return false;
|
|
1603
|
+
accessSync(filePath, constants.X_OK);
|
|
1604
|
+
return true;
|
|
1605
|
+
} catch {
|
|
1606
|
+
return false;
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
function findExecutable(candidates, pathNames) {
|
|
1610
|
+
for (const candidate of candidates) {
|
|
1611
|
+
if (!candidate) continue;
|
|
1612
|
+
if (isExecutableFile(candidate)) return candidate;
|
|
1613
|
+
}
|
|
1614
|
+
const dirs = (process.env.PATH ?? "").split(path5.delimiter).filter(Boolean);
|
|
1615
|
+
for (const dir of dirs) {
|
|
1616
|
+
for (const name of pathNames) {
|
|
1617
|
+
const full = path5.join(dir, name);
|
|
1618
|
+
if (isExecutableFile(full)) return full;
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
return null;
|
|
1622
|
+
}
|
|
1623
|
+
function baseEnv(binDir, extraKeys = []) {
|
|
1624
|
+
const env = {};
|
|
1625
|
+
const keys = ["HOME", "USER", "LOGNAME", "PATH", "TMPDIR", "SHELL", "LANG", "TERM", ...extraKeys];
|
|
1626
|
+
for (const k of keys) {
|
|
1627
|
+
if (process.env[k]) env[k] = process.env[k];
|
|
1628
|
+
}
|
|
1629
|
+
env.PATH = binDir + path5.delimiter + (env.PATH ?? "");
|
|
1630
|
+
return env;
|
|
1631
|
+
}
|
|
1632
|
+
var stripAnsi = (text) => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
|
|
1633
|
+
var SLATE_SUBCOMMAND_LABELS = {
|
|
1634
|
+
read: "\u8BFB\u53D6\u5361\u7247",
|
|
1635
|
+
show: "\u8BFB\u53D6\u5361\u7247",
|
|
1636
|
+
list: "\u68C0\u7D22\u5361\u7247\u5217\u8868",
|
|
1637
|
+
events: "\u62C9\u53D6\u5361\u7247\u4E8B\u4EF6",
|
|
1638
|
+
agents: "\u67E5\u770B\u9879\u76EE\u534F\u4F5C\u8005",
|
|
1639
|
+
create: "\u65B0\u5EFA\u6216\u62C6\u5206\u5B50\u5361",
|
|
1640
|
+
update: "\u66F4\u65B0\u5361\u7247\u5185\u5BB9",
|
|
1641
|
+
status: "\u5207\u6362\u5361\u7247\u72B6\u6001",
|
|
1642
|
+
comment: "\u53D1\u8868\u5361\u7247\u8BC4\u8BBA",
|
|
1643
|
+
ask: "\u53D1\u8D77\u5F85\u786E\u8BA4\u51B3\u7B56",
|
|
1644
|
+
output: "\u6302\u8F7D\u4EFB\u52A1\u4EA7\u51FA",
|
|
1645
|
+
upload: "\u4E0A\u4F20\u6258\u7BA1\u9644\u4EF6",
|
|
1646
|
+
worktree: "\u7533\u8BF7\u72EC\u7ACB Git \u5206\u652F"
|
|
1647
|
+
};
|
|
1648
|
+
function compactOneLine(text, max = 240) {
|
|
1649
|
+
return text.replace(/\s+/g, " ").trim().slice(0, max);
|
|
1650
|
+
}
|
|
1651
|
+
function classifyCommandStep(command) {
|
|
1652
|
+
const compact = compactOneLine(command, 260);
|
|
1653
|
+
const slateMatch = compact.match(
|
|
1654
|
+
/(?:^|[\s;&|(])slate\s+(read|show|list|events|agents|create|update|status|comment|ask|output|upload|worktree)\b/
|
|
1655
|
+
);
|
|
1656
|
+
if (slateMatch?.[1]) {
|
|
1657
|
+
const subcmd = slateMatch[1];
|
|
1658
|
+
const label = SLATE_SUBCOMMAND_LABELS[subcmd] ?? subcmd;
|
|
1659
|
+
return {
|
|
1660
|
+
kind: "slate",
|
|
1661
|
+
title: `\u8C03\u7528 slate ${subcmd}\uFF08${label}\uFF09`,
|
|
1662
|
+
...compact ? { detail: compact } : {}
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
return {
|
|
1666
|
+
kind: "command",
|
|
1667
|
+
title: "\u6267\u884C\u547D\u4EE4",
|
|
1668
|
+
...compact ? { detail: compact } : {}
|
|
1669
|
+
};
|
|
1670
|
+
}
|
|
1671
|
+
function firstStringField(input, keys) {
|
|
1672
|
+
if (!input) return void 0;
|
|
1673
|
+
for (const key of keys) {
|
|
1674
|
+
const value = input[key];
|
|
1675
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
1676
|
+
}
|
|
1677
|
+
return void 0;
|
|
1678
|
+
}
|
|
1679
|
+
function classifyToolStep(toolName, input) {
|
|
1680
|
+
const normalized = toolName.trim().toLowerCase();
|
|
1681
|
+
if (normalized === "bash" || normalized === "run_command" || normalized === "command_execution" || normalized === "shell") {
|
|
1682
|
+
const cmd = firstStringField(input, ["command", "CommandLine", "cmd"]);
|
|
1683
|
+
if (cmd) return classifyCommandStep(cmd);
|
|
1684
|
+
return { kind: "command", title: "\u6267\u884C\u547D\u4EE4" };
|
|
1685
|
+
}
|
|
1686
|
+
if (normalized === "read" || normalized === "read_file" || normalized === "view_file") {
|
|
1687
|
+
const target = firstStringField(input, ["file_path", "path", "Path", "AbsolutePath"]);
|
|
1688
|
+
return {
|
|
1689
|
+
kind: "tool",
|
|
1690
|
+
title: "\u8BFB\u53D6\u6587\u4EF6",
|
|
1691
|
+
...target ? { detail: compactOneLine(target, 240) } : {}
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
if (normalized === "edit" || normalized === "multiedit" || normalized === "write" || normalized === "edit_file" || normalized === "write_file" || normalized === "replace_file_content" || normalized === "multi_replace_file_content" || normalized === "write_to_file") {
|
|
1695
|
+
const target = firstStringField(input, ["file_path", "path", "Path", "TargetFile"]);
|
|
1696
|
+
return {
|
|
1697
|
+
kind: "tool",
|
|
1698
|
+
title: normalized.includes("write") ? "\u5199\u5165\u6587\u4EF6" : "\u7F16\u8F91\u6587\u4EF6",
|
|
1699
|
+
...target ? { detail: compactOneLine(target, 240) } : {}
|
|
1700
|
+
};
|
|
1701
|
+
}
|
|
1702
|
+
if (normalized === "grep" || normalized === "glob" || normalized === "grep_search" || normalized === "find_by_name") {
|
|
1703
|
+
const query = firstStringField(input, ["pattern", "Query", "Pattern", "path", "SearchPath"]);
|
|
1704
|
+
return {
|
|
1705
|
+
kind: "tool",
|
|
1706
|
+
title: "\u68C0\u7D22\u5DE5\u4F5C\u533A",
|
|
1707
|
+
...query ? { detail: compactOneLine(query, 240) } : {}
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
if (normalized === "websearch" || normalized === "search_web" || normalized === "webfetch" || normalized === "read_url_content") {
|
|
1711
|
+
const query = firstStringField(input, ["query", "url", "Url"]);
|
|
1712
|
+
return {
|
|
1713
|
+
kind: "tool",
|
|
1714
|
+
title: "\u67E5\u9605\u5916\u90E8\u8D44\u6599",
|
|
1715
|
+
...query ? { detail: compactOneLine(query, 240) } : {}
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
const detail = firstStringField(input, ["command", "CommandLine", "file_path", "path", "Path", "query", "url"]);
|
|
1719
|
+
return {
|
|
1720
|
+
kind: "tool",
|
|
1721
|
+
title: `\u8C03\u7528\u5DE5\u5177\uFF1A${toolName.slice(0, 120)}`,
|
|
1722
|
+
...detail ? { detail: compactOneLine(detail, 240) } : {}
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
// src/drivers/antigravity.ts
|
|
1727
|
+
function agyArgs(prompt, sessionId, options) {
|
|
1728
|
+
const args = ["--output-format", "stream-json"];
|
|
1729
|
+
if (options?.readOnly) {
|
|
1730
|
+
args.push("--mode", "plan", "--sandbox");
|
|
1731
|
+
} else {
|
|
1732
|
+
const skipPermissions = options?.skipPermissions ?? (process.env.AGY_SKIP_PERMISSIONS === "1" || process.env.AGY_SKIP_PERMISSIONS === "true");
|
|
1733
|
+
if (skipPermissions) {
|
|
1734
|
+
args.push("--dangerously-skip-permissions");
|
|
1735
|
+
} else if (process.env.AGY_MODE) {
|
|
1736
|
+
args.push("--mode", process.env.AGY_MODE);
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
const addDirs = [...new Set((options?.addDirs ?? []).map((d) => d.trim()).filter(Boolean))];
|
|
1740
|
+
for (const dir of addDirs) {
|
|
1741
|
+
args.push("--add-dir", dir);
|
|
1742
|
+
}
|
|
1743
|
+
if (process.env.AGY_MODEL) args.push("--model", process.env.AGY_MODEL);
|
|
1744
|
+
if (process.env.AGY_EFFORT) args.push("--effort", process.env.AGY_EFFORT);
|
|
1745
|
+
if (sessionId) args.push("--resume", sessionIdSchema.parse(sessionId));
|
|
1746
|
+
args.push(`-p=${prompt}`);
|
|
1747
|
+
return args;
|
|
1748
|
+
}
|
|
1749
|
+
function recordRecentEvent(state, entry) {
|
|
1750
|
+
const list = state.recentEvents ?? [];
|
|
1751
|
+
list.push(entry);
|
|
1752
|
+
if (list.length > 12) list.splice(0, list.length - 12);
|
|
1753
|
+
state.recentEvents = list;
|
|
1754
|
+
}
|
|
1755
|
+
function extractAgyStderrSummary(stderr) {
|
|
1756
|
+
const lines = stripAnsi(stderr).split(/\r?\n/).map((l) => l.trim()).filter(Boolean).filter((l) => !/^warning:/i.test(l));
|
|
1757
|
+
if (lines.length === 0) return void 0;
|
|
1758
|
+
const errorLine = lines.find((l) => /^(error|failed|flag needs)/i.test(l)) ?? lines[0];
|
|
1759
|
+
return errorLine?.slice(0, 300);
|
|
1760
|
+
}
|
|
1761
|
+
function applyAgyStreamLine(line, state, callbacks) {
|
|
1762
|
+
let ev;
|
|
1763
|
+
try {
|
|
1764
|
+
ev = JSON.parse(line);
|
|
1765
|
+
} catch {
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
const stepUpdate = ev.step_update && typeof ev.step_update === "object" ? ev.step_update : void 0;
|
|
1769
|
+
const resultObj = ev.result && typeof ev.result === "object" ? ev.result : void 0;
|
|
1770
|
+
const sid = typeof ev.conversation_id === "string" && ev.conversation_id || typeof ev.session_id === "string" && ev.session_id || typeof ev.conversationId === "string" && ev.conversationId || typeof stepUpdate?.conversation_id === "string" && stepUpdate.conversation_id || typeof resultObj?.conversation_id === "string" && resultObj.conversation_id || void 0;
|
|
1771
|
+
if (sid && !state.sessionId) {
|
|
1772
|
+
state.sessionId = sid;
|
|
1773
|
+
callbacks?.onSessionId?.(sid);
|
|
1774
|
+
}
|
|
1775
|
+
if (ev.event === "init") {
|
|
1776
|
+
const initObj = ev.init && typeof ev.init === "object" ? ev.init : void 0;
|
|
1777
|
+
recordRecentEvent(state, {
|
|
1778
|
+
event: "init",
|
|
1779
|
+
...typeof initObj?.permission_mode === "string" ? { state: initObj.permission_mode } : {}
|
|
1780
|
+
});
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
if (ev.event === "step_update" && stepUpdate) {
|
|
1784
|
+
const stepType = typeof stepUpdate.step_type === "string" ? stepUpdate.step_type : "";
|
|
1785
|
+
const stepState = typeof stepUpdate.state === "string" ? stepUpdate.state : void 0;
|
|
1786
|
+
const stepIndex = typeof stepUpdate.step_index === "number" ? stepUpdate.step_index : void 0;
|
|
1787
|
+
if (stepType && stepType !== "agent_response") {
|
|
1788
|
+
recordRecentEvent(state, { event: "step_update", stepType, ...stepState ? { state: stepState } : {} });
|
|
1789
|
+
} else if (stepType === "agent_response" && stepState === "DONE") {
|
|
1790
|
+
recordRecentEvent(state, { event: "step_update", stepType, state: stepState });
|
|
1791
|
+
}
|
|
1792
|
+
if (stepType === "agent_response" && typeof stepUpdate.text_delta === "string") {
|
|
1793
|
+
if (stepIndex !== void 0 && stepIndex !== state.activeStepIndex) {
|
|
1794
|
+
state.activeStepIndex = stepIndex;
|
|
1795
|
+
state.activeStepText = "";
|
|
1796
|
+
}
|
|
1797
|
+
state.activeStepText = (state.activeStepText ?? "") + stepUpdate.text_delta;
|
|
1798
|
+
if (state.activeStepText.trim()) {
|
|
1799
|
+
state.finalOutput = state.activeStepText;
|
|
1800
|
+
callbacks?.onDelta?.(state.activeStepText);
|
|
1801
|
+
callbacks?.onActivity?.(state.activeStepText.replace(/\s+/g, " ").slice(0, 120));
|
|
1802
|
+
}
|
|
1803
|
+
} else if (stepType === "agent_response" && stepState === "DONE" && state.activeStepText?.trim()) {
|
|
1804
|
+
const key = `msg:${stepIndex ?? "final"}`;
|
|
1805
|
+
const emitted = state.emittedStepKeys ?? /* @__PURE__ */ new Set();
|
|
1806
|
+
state.emittedStepKeys = emitted;
|
|
1807
|
+
if (!emitted.has(key)) {
|
|
1808
|
+
emitted.add(key);
|
|
1809
|
+
callbacks?.onStep?.({
|
|
1810
|
+
kind: "message",
|
|
1811
|
+
title: "\u9636\u6BB5\u56DE\u590D",
|
|
1812
|
+
detail: state.activeStepText.replace(/\s+/g, " ").trim().slice(0, 240)
|
|
1813
|
+
});
|
|
1814
|
+
}
|
|
1815
|
+
} else if (stepType && stepType !== "user_input" && stepType !== "system_message" && stepType !== "agent_response") {
|
|
1816
|
+
const toolName = typeof stepUpdate.tool_name === "string" && stepUpdate.tool_name || typeof stepUpdate.name === "string" && stepUpdate.name || stepType;
|
|
1817
|
+
callbacks?.onActivity?.(`\u8C03\u7528\u5DE5\u5177\uFF1A${toolName}`);
|
|
1818
|
+
const key = stepIndex !== void 0 ? `tool:${stepIndex}:${toolName}` : `tool:${toolName}`;
|
|
1819
|
+
const emitted = state.emittedStepKeys ?? /* @__PURE__ */ new Set();
|
|
1820
|
+
state.emittedStepKeys = emitted;
|
|
1821
|
+
if (!emitted.has(key)) {
|
|
1822
|
+
emitted.add(key);
|
|
1823
|
+
const args = stepUpdate.args && typeof stepUpdate.args === "object" ? stepUpdate.args : stepUpdate.input && typeof stepUpdate.input === "object" ? stepUpdate.input : stepUpdate;
|
|
1824
|
+
callbacks?.onStep?.(classifyToolStep(toolName, args));
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
if (ev.event === "result" && resultObj) {
|
|
1830
|
+
state.sawResultEvent = true;
|
|
1831
|
+
const status = typeof resultObj.status === "string" ? resultObj.status.toUpperCase() : "";
|
|
1832
|
+
recordRecentEvent(state, { event: "result", ...status ? { status } : {} });
|
|
1833
|
+
state.completed = status === "SUCCESS" || status === "" && resultObj.is_error !== true;
|
|
1834
|
+
if (typeof resultObj.response === "string" && resultObj.response.trim()) {
|
|
1835
|
+
state.finalOutput = resultObj.response;
|
|
1836
|
+
}
|
|
1837
|
+
if (!state.completed) {
|
|
1838
|
+
const errText = typeof resultObj.error === "string" && resultObj.error.trim() || typeof resultObj.message === "string" && resultObj.message.trim() || typeof resultObj.response === "string" && resultObj.response.trim() || void 0;
|
|
1839
|
+
if (errText) state.errorMessage = errText.slice(0, 300);
|
|
1840
|
+
}
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
if (ev.event === "error" || ev.type === "error") {
|
|
1844
|
+
state.sawResultEvent = true;
|
|
1845
|
+
state.completed = false;
|
|
1846
|
+
recordRecentEvent(state, { event: "error" });
|
|
1847
|
+
const errText = typeof ev.error === "string" && ev.error.trim() || typeof ev.message === "string" && ev.message.trim() || void 0;
|
|
1848
|
+
if (errText) state.errorMessage = errText.slice(0, 300);
|
|
1849
|
+
return;
|
|
1850
|
+
}
|
|
1851
|
+
if (ev.type === "result" || ev.type === "turn.completed" || ev.type === "done") {
|
|
1852
|
+
state.sawResultEvent = true;
|
|
1853
|
+
state.completed = ev.is_error !== true;
|
|
1854
|
+
recordRecentEvent(state, { event: String(ev.type) });
|
|
1855
|
+
if (typeof ev.result === "string" && ev.result.trim()) {
|
|
1856
|
+
state.finalOutput = ev.result;
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
if (typeof ev.text === "string" && ev.text.trim()) {
|
|
1860
|
+
state.finalOutput = ev.text;
|
|
1861
|
+
callbacks?.onDelta?.(ev.text);
|
|
1862
|
+
callbacks?.onActivity?.(ev.text.replace(/\s+/g, " ").slice(0, 120));
|
|
1863
|
+
} else if (ev.type === "assistant") {
|
|
1864
|
+
const msg = ev.message;
|
|
1865
|
+
const texts = msg?.content?.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n").trim();
|
|
1866
|
+
if (texts) {
|
|
1867
|
+
state.finalOutput = texts;
|
|
1868
|
+
callbacks?.onDelta?.(texts);
|
|
1869
|
+
callbacks?.onActivity?.(texts.replace(/\s+/g, " ").slice(0, 120));
|
|
1870
|
+
}
|
|
1871
|
+
} else if (ev.type === "tool_use" && typeof ev.name === "string") {
|
|
1872
|
+
callbacks?.onActivity?.(`\u8C03\u7528\u5DE5\u5177\uFF1A${ev.name}`);
|
|
1873
|
+
const input = ev.input && typeof ev.input === "object" ? ev.input : void 0;
|
|
1874
|
+
callbacks?.onStep?.(classifyToolStep(ev.name, input));
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
function createAntigravityDriver() {
|
|
1878
|
+
let runtimeAuthFailure = null;
|
|
1879
|
+
const latestLocalMtime = () => {
|
|
1880
|
+
let max = 0;
|
|
1881
|
+
for (const p of [
|
|
1882
|
+
path6.join(homedir2(), ".gemini/antigravity"),
|
|
1883
|
+
path6.join(homedir2(), ".gemini/antigravity/user_config.json"),
|
|
1884
|
+
path6.join(homedir2(), ".gemini/config")
|
|
1885
|
+
]) {
|
|
1886
|
+
try {
|
|
1887
|
+
max = Math.max(max, statSync2(p).mtimeMs);
|
|
1888
|
+
} catch {
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
return max;
|
|
1892
|
+
};
|
|
1893
|
+
const resolveBin = () => findExecutable(
|
|
1894
|
+
[process.env.AGY_BIN, path6.join(homedir2(), ".local/bin/agy"), "/opt/homebrew/bin/agy", "/usr/local/bin/agy"],
|
|
1895
|
+
["agy"]
|
|
1896
|
+
);
|
|
1897
|
+
return {
|
|
1898
|
+
type: "antigravity",
|
|
1899
|
+
authMode: "local_session",
|
|
1900
|
+
binaryPath: resolveBin,
|
|
1901
|
+
async checkAuth(_signal) {
|
|
1902
|
+
const bin = resolveBin();
|
|
1903
|
+
if (!bin) return { loginState: "error", loginMessage: "\u672C\u673A\u672A\u5B89\u88C5 Antigravity CLI\uFF08\u672A\u627E\u5230 agy\uFF09" };
|
|
1904
|
+
if (runtimeAuthFailure) {
|
|
1905
|
+
if (latestLocalMtime() > runtimeAuthFailure.detectedAtMs) {
|
|
1906
|
+
runtimeAuthFailure = null;
|
|
1907
|
+
} else {
|
|
1908
|
+
return runtimeAuthFailure.failure;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
const hasLocalDir = existsSync3(path6.join(homedir2(), ".gemini/antigravity"));
|
|
1912
|
+
return hasLocalDir ? { loginState: "logged_in" } : { loginState: "logged_out", loginMessage: "\u672A\u68C0\u6D4B\u5230\u672C\u673A Antigravity \u76EE\u5F55\uFF0C\u8BF7\u5148\u8FD0\u884C agy \u5B8C\u6210\u767B\u5F55" };
|
|
1913
|
+
},
|
|
1914
|
+
async run(options) {
|
|
1915
|
+
const bin = resolveBin();
|
|
1916
|
+
const result = {
|
|
1917
|
+
driver: "antigravity",
|
|
1918
|
+
sessionId: null,
|
|
1919
|
+
outerExit: null,
|
|
1920
|
+
signal: null,
|
|
1921
|
+
completed: false,
|
|
1922
|
+
aborted: false
|
|
1923
|
+
};
|
|
1924
|
+
if (!bin) {
|
|
1925
|
+
result.errorMessage = "\u672C\u673A\u672A\u627E\u5230 agy \u53EF\u6267\u884C\u6587\u4EF6";
|
|
1926
|
+
return result;
|
|
1927
|
+
}
|
|
1928
|
+
const args = agyArgs(options.prompt, options.sessionId, {
|
|
1929
|
+
skipPermissions: options.skipPermissions,
|
|
1930
|
+
readOnly: options.readOnly,
|
|
1931
|
+
addDirs: options.addDirs
|
|
1932
|
+
});
|
|
1933
|
+
const recordedArgs = args.map((a) => a.startsWith("-p=") ? `-p=<prompt:${options.prompt.length} chars>` : a);
|
|
1934
|
+
const env = baseEnv(options.binDir, ["AGY_ACCOUNT"]);
|
|
1935
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1936
|
+
let sessionSave;
|
|
1937
|
+
let stderrTail = "";
|
|
1938
|
+
let recentEvents = [];
|
|
1939
|
+
await atomicJson(options.recordFile, { ...result, args: recordedArgs, startedAt });
|
|
1940
|
+
if (options.signal.aborted) {
|
|
1941
|
+
result.aborted = true;
|
|
1942
|
+
return result;
|
|
1943
|
+
}
|
|
1944
|
+
await new Promise((resolve) => {
|
|
1945
|
+
const child = spawn(bin, args, { cwd: options.workDir, env, stdio: ["pipe", "pipe", "pipe"], detached: true });
|
|
1946
|
+
let buf = "";
|
|
1947
|
+
let stderr = "";
|
|
1948
|
+
let stdoutTail = "";
|
|
1949
|
+
let closed = false;
|
|
1950
|
+
let spawnFailed = false;
|
|
1951
|
+
let killTimer;
|
|
1952
|
+
const streamState = { sessionId: null, completed: false, sawResultEvent: false };
|
|
1953
|
+
const stop = () => {
|
|
1954
|
+
if (closed || result.aborted) return;
|
|
1955
|
+
result.aborted = true;
|
|
1956
|
+
if (!child.pid) return;
|
|
1957
|
+
try {
|
|
1958
|
+
process.kill(-child.pid, "SIGTERM");
|
|
1959
|
+
} catch {
|
|
1960
|
+
}
|
|
1961
|
+
killTimer = setTimeout(() => {
|
|
1962
|
+
try {
|
|
1963
|
+
process.kill(-child.pid, "SIGKILL");
|
|
1964
|
+
} catch {
|
|
1965
|
+
}
|
|
1966
|
+
}, 3e3);
|
|
1967
|
+
};
|
|
1968
|
+
const handleLine = (line) => {
|
|
1969
|
+
stdoutTail = `${stdoutTail}
|
|
1970
|
+
${line}`.slice(-8192);
|
|
1971
|
+
applyAgyStreamLine(line, streamState, {
|
|
1972
|
+
onSessionId: (sid) => {
|
|
1973
|
+
result.sessionId = sid;
|
|
1974
|
+
sessionSave = options.onSessionStarted(sid);
|
|
1975
|
+
void sessionSave.catch(stop);
|
|
1976
|
+
},
|
|
1977
|
+
onActivity: options.onActivity,
|
|
1978
|
+
onStep: options.onStep,
|
|
1979
|
+
onDelta: options.onDelta
|
|
1980
|
+
});
|
|
1981
|
+
result.completed = streamState.completed;
|
|
1982
|
+
if (streamState.finalOutput !== void 0) result.finalOutput = streamState.finalOutput;
|
|
1983
|
+
if (streamState.errorMessage !== void 0) result.errorMessage = streamState.errorMessage;
|
|
1984
|
+
};
|
|
1985
|
+
options.signal.addEventListener("abort", stop, { once: true });
|
|
1986
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
1987
|
+
buf += chunk;
|
|
1988
|
+
for (let idx = buf.indexOf("\n"); idx >= 0; idx = buf.indexOf("\n")) {
|
|
1989
|
+
handleLine(buf.slice(0, idx));
|
|
1990
|
+
buf = buf.slice(idx + 1);
|
|
1991
|
+
}
|
|
1992
|
+
if (buf.length > 1024 * 1024) buf = buf.slice(-65536);
|
|
1993
|
+
});
|
|
1994
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
1995
|
+
stderr = (stderr + chunk).slice(-8192);
|
|
1996
|
+
});
|
|
1997
|
+
child.once("error", () => {
|
|
1998
|
+
spawnFailed = true;
|
|
1999
|
+
});
|
|
2000
|
+
child.once("close", (code, sig) => {
|
|
2001
|
+
if (buf.trim()) handleLine(buf);
|
|
2002
|
+
closed = true;
|
|
2003
|
+
result.outerExit = spawnFailed ? -1 : code;
|
|
2004
|
+
result.signal = sig;
|
|
2005
|
+
stderrTail = stripAnsi(stderr).trim().slice(-2e3);
|
|
2006
|
+
recentEvents = streamState.recentEvents ?? [];
|
|
2007
|
+
const combinedErr = `${stderr}
|
|
2008
|
+
${stdoutTail}
|
|
2009
|
+
${result.errorMessage ?? ""}`;
|
|
2010
|
+
const authErr = detectAuthFailure(combinedErr, "Antigravity", "\u8BF7\u5728\u672C\u673A\u91CD\u65B0\u767B\u5F55 Antigravity");
|
|
2011
|
+
if (authErr) {
|
|
2012
|
+
result.authFailure = authErr;
|
|
2013
|
+
result.completed = false;
|
|
2014
|
+
result.errorMessage = authErr.loginMessage;
|
|
2015
|
+
runtimeAuthFailure = { failure: authErr, detectedAtMs: Date.now() };
|
|
2016
|
+
} else {
|
|
2017
|
+
if (result.completed && code === 0) runtimeAuthFailure = null;
|
|
2018
|
+
if (!result.aborted && (code !== 0 || !result.completed) && !result.errorMessage) {
|
|
2019
|
+
result.errorMessage = extractAgyStderrSummary(stderr) ?? (code === 0 && !streamState.sawResultEvent ? "Antigravity CLI \u672A\u8FD4\u56DE\u5B8C\u6210\u4E8B\u4EF6\u5373\u9000\u51FA\uFF08\u53EF\u80FD\u88AB\u6743\u9650\u5BA1\u6279\u6216\u5185\u90E8\u5F02\u5E38\u4E2D\u65AD\uFF09" : void 0);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
if (options.sessionId && !result.completed && !result.authFailure && /conversation|resume|not found/i.test(`${stderr}
|
|
2023
|
+
${result.errorMessage ?? ""}`)) {
|
|
2024
|
+
result.resumeUnavailable = true;
|
|
2025
|
+
}
|
|
2026
|
+
clearTimeout(killTimer);
|
|
2027
|
+
options.signal.removeEventListener("abort", stop);
|
|
2028
|
+
resolve();
|
|
2029
|
+
});
|
|
2030
|
+
if (options.signal.aborted) stop();
|
|
2031
|
+
child.stdin.on("error", () => {
|
|
2032
|
+
});
|
|
2033
|
+
child.stdin.end();
|
|
2034
|
+
});
|
|
2035
|
+
try {
|
|
2036
|
+
await sessionSave;
|
|
2037
|
+
} finally {
|
|
2038
|
+
await atomicJson(options.recordFile, {
|
|
2039
|
+
...result,
|
|
2040
|
+
args: recordedArgs,
|
|
2041
|
+
...recentEvents.length > 0 ? { recentEvents } : {},
|
|
2042
|
+
...stderrTail && (!result.completed || result.outerExit !== 0) ? { stderrTail } : {},
|
|
2043
|
+
startedAt,
|
|
2044
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2045
|
+
});
|
|
2046
|
+
}
|
|
2047
|
+
return result;
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
// src/drivers/claude-code.ts
|
|
2053
|
+
import { spawn as spawn2 } from "child_process";
|
|
2054
|
+
import { statSync as statSync3 } from "fs";
|
|
2055
|
+
import { homedir as homedir3 } from "os";
|
|
2056
|
+
import path7 from "path";
|
|
2057
|
+
function claudeArgs(sessionId, opts) {
|
|
2058
|
+
const args = ["-p", "--output-format", "stream-json", "--verbose"];
|
|
2059
|
+
if (opts?.readOnly) {
|
|
2060
|
+
args.push(
|
|
2061
|
+
"--permission-mode",
|
|
2062
|
+
"dontAsk",
|
|
2063
|
+
"--allowedTools",
|
|
2064
|
+
"Read,Grep,Glob,LS,Bash(slate *)",
|
|
2065
|
+
"--disallowedTools",
|
|
2066
|
+
"Edit,Write,NotebookEdit"
|
|
2067
|
+
);
|
|
2068
|
+
} else if (opts?.skipPermissions) {
|
|
2069
|
+
args.push("--dangerously-skip-permissions");
|
|
2070
|
+
} else {
|
|
2071
|
+
args.push("--permission-mode", "acceptEdits");
|
|
2072
|
+
}
|
|
2073
|
+
const addDirs = [...new Set((opts?.addDirs ?? []).map((d) => d.trim()).filter(Boolean))];
|
|
2074
|
+
for (const dir of addDirs) {
|
|
2075
|
+
args.push("--add-dir", dir);
|
|
2076
|
+
}
|
|
2077
|
+
if (opts?.streamPartial) args.push("--include-partial-messages");
|
|
2078
|
+
if (process.env.CLAUDE_MODEL) args.push("--model", process.env.CLAUDE_MODEL);
|
|
2079
|
+
if (sessionId) args.push("--resume", sessionIdSchema.parse(sessionId));
|
|
2080
|
+
return args;
|
|
2081
|
+
}
|
|
2082
|
+
function parseClaudeAuthStatus(output, code) {
|
|
2083
|
+
const cleaned = stripAnsi(output);
|
|
2084
|
+
const start = cleaned.indexOf("{");
|
|
2085
|
+
const end = cleaned.lastIndexOf("}");
|
|
2086
|
+
if (start >= 0 && end > start) {
|
|
2087
|
+
try {
|
|
2088
|
+
const parsed = JSON.parse(cleaned.slice(start, end + 1));
|
|
2089
|
+
if (parsed.loggedIn === true) {
|
|
2090
|
+
const meta = [parsed.authMethod, parsed.subscriptionType].filter(Boolean).join(" \xB7 ");
|
|
2091
|
+
return {
|
|
2092
|
+
loginState: "logged_in",
|
|
2093
|
+
...meta ? { loginMessage: `\u5DF2\u901A\u8FC7 claude auth status \u786E\u8BA4\uFF08${meta}\uFF09` } : {}
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
if (parsed.loggedIn === false) {
|
|
2097
|
+
return { loginState: "logged_out", loginMessage: "Claude Code \u5C1A\u672A\u767B\u5F55\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u8FD0\u884C claude auth login" };
|
|
2098
|
+
}
|
|
2099
|
+
} catch {
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
if (code !== 0) return { loginState: "error", loginMessage: "\u65E0\u6CD5\u68C0\u67E5 Claude Code \u767B\u5F55\u72B6\u6001" };
|
|
2103
|
+
return { loginState: "unknown", loginMessage: "\u65E0\u6CD5\u89E3\u6790 claude auth status \u8F93\u51FA" };
|
|
2104
|
+
}
|
|
2105
|
+
function createClaudeCodeDriver() {
|
|
2106
|
+
let runtimeAuthFailure = null;
|
|
2107
|
+
const latestCredMtime = () => {
|
|
2108
|
+
let max = 0;
|
|
2109
|
+
for (const p of [
|
|
2110
|
+
path7.join(homedir3(), ".claude.json"),
|
|
2111
|
+
path7.join(homedir3(), ".claude", ".credentials.json"),
|
|
2112
|
+
path7.join(homedir3(), ".claude")
|
|
2113
|
+
]) {
|
|
2114
|
+
try {
|
|
2115
|
+
max = Math.max(max, statSync3(p).mtimeMs);
|
|
2116
|
+
} catch {
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
return max;
|
|
2120
|
+
};
|
|
2121
|
+
const resolveBin = () => findExecutable(
|
|
2122
|
+
[
|
|
2123
|
+
process.env.CLAUDE_BIN,
|
|
2124
|
+
path7.join(homedir3(), ".local/bin/claude"),
|
|
2125
|
+
path7.join(homedir3(), ".claude/local/claude"),
|
|
2126
|
+
"/opt/homebrew/bin/claude",
|
|
2127
|
+
"/usr/local/bin/claude"
|
|
2128
|
+
],
|
|
2129
|
+
["claude"]
|
|
2130
|
+
);
|
|
2131
|
+
return {
|
|
2132
|
+
type: "claude-code",
|
|
2133
|
+
authMode: process.env.ANTHROPIC_API_KEY ? "api_key" : "local_session",
|
|
2134
|
+
binaryPath: resolveBin,
|
|
2135
|
+
async checkAuth(signal) {
|
|
2136
|
+
const bin = resolveBin();
|
|
2137
|
+
if (!bin) return { loginState: "error", loginMessage: "\u672C\u673A\u672A\u5B89\u88C5 Claude Code CLI\uFF08\u672A\u627E\u5230 claude\uFF09" };
|
|
2138
|
+
if (process.env.ANTHROPIC_API_KEY) return { loginState: "logged_in", loginMessage: "\u5DF2\u68C0\u6D4B\u5230 ANTHROPIC_API_KEY" };
|
|
2139
|
+
if (runtimeAuthFailure) {
|
|
2140
|
+
if (latestCredMtime() > runtimeAuthFailure.detectedAtMs) {
|
|
2141
|
+
runtimeAuthFailure = null;
|
|
2142
|
+
} else {
|
|
2143
|
+
return runtimeAuthFailure.failure;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
const combined = AbortSignal.any([signal, AbortSignal.timeout(8e3)]);
|
|
2147
|
+
let output = "";
|
|
2148
|
+
const code = await new Promise((resolve) => {
|
|
2149
|
+
if (combined.aborted) {
|
|
2150
|
+
resolve(null);
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
const env = {};
|
|
2154
|
+
for (const k of ["HOME", "USER", "LOGNAME", "PATH", "TMPDIR", "SHELL", "LANG", "TERM"]) {
|
|
2155
|
+
if (process.env[k]) env[k] = process.env[k];
|
|
2156
|
+
}
|
|
2157
|
+
const child = spawn2(bin, ["auth", "status"], { env, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
2158
|
+
let killTimer;
|
|
2159
|
+
const stop = () => {
|
|
2160
|
+
if (!child.pid) return;
|
|
2161
|
+
try {
|
|
2162
|
+
process.kill(-child.pid, "SIGTERM");
|
|
2163
|
+
} catch {
|
|
2164
|
+
}
|
|
2165
|
+
killTimer = setTimeout(() => {
|
|
2166
|
+
try {
|
|
2167
|
+
process.kill(-child.pid, "SIGKILL");
|
|
2168
|
+
} catch {
|
|
2169
|
+
}
|
|
2170
|
+
}, 3e3);
|
|
2171
|
+
};
|
|
2172
|
+
combined.addEventListener("abort", stop, { once: true });
|
|
2173
|
+
for (const s of [child.stdout, child.stderr]) {
|
|
2174
|
+
s.setEncoding("utf8");
|
|
2175
|
+
s.on("data", (chunk) => {
|
|
2176
|
+
output = (output + chunk).slice(-16384);
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
const finish = (c) => {
|
|
2180
|
+
clearTimeout(killTimer);
|
|
2181
|
+
combined.removeEventListener("abort", stop);
|
|
2182
|
+
resolve(c);
|
|
2183
|
+
};
|
|
2184
|
+
child.on("error", () => finish(null));
|
|
2185
|
+
child.on("close", finish);
|
|
2186
|
+
});
|
|
2187
|
+
return parseClaudeAuthStatus(output, code);
|
|
2188
|
+
},
|
|
2189
|
+
async run(options) {
|
|
2190
|
+
const bin = resolveBin();
|
|
2191
|
+
const result = {
|
|
2192
|
+
driver: "claude-code",
|
|
2193
|
+
sessionId: null,
|
|
2194
|
+
outerExit: null,
|
|
2195
|
+
signal: null,
|
|
2196
|
+
completed: false,
|
|
2197
|
+
aborted: false
|
|
2198
|
+
};
|
|
2199
|
+
if (!bin) {
|
|
2200
|
+
result.errorMessage = "\u672C\u673A\u672A\u627E\u5230 claude \u53EF\u6267\u884C\u6587\u4EF6";
|
|
2201
|
+
return result;
|
|
2202
|
+
}
|
|
2203
|
+
const args = claudeArgs(options.sessionId, {
|
|
2204
|
+
streamPartial: options.streamPartial,
|
|
2205
|
+
skipPermissions: options.skipPermissions,
|
|
2206
|
+
readOnly: options.readOnly,
|
|
2207
|
+
addDirs: options.addDirs
|
|
2208
|
+
});
|
|
2209
|
+
const env = baseEnv(options.binDir, ["ANTHROPIC_API_KEY", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX"]);
|
|
2210
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2211
|
+
let sessionSave;
|
|
2212
|
+
await atomicJson(options.recordFile, { ...result, args, startedAt });
|
|
2213
|
+
if (options.signal.aborted) {
|
|
2214
|
+
result.aborted = true;
|
|
2215
|
+
return result;
|
|
2216
|
+
}
|
|
2217
|
+
await new Promise((resolve) => {
|
|
2218
|
+
const child = spawn2(bin, args, { cwd: options.workDir, env, stdio: ["pipe", "pipe", "pipe"], detached: true });
|
|
2219
|
+
let buf = "";
|
|
2220
|
+
let stdoutTail = "";
|
|
2221
|
+
let stderr = "";
|
|
2222
|
+
let streamedText = "";
|
|
2223
|
+
let closed = false;
|
|
2224
|
+
let spawnFailed = false;
|
|
2225
|
+
let killTimer;
|
|
2226
|
+
const emittedToolIds = /* @__PURE__ */ new Set();
|
|
2227
|
+
const stop = () => {
|
|
2228
|
+
if (closed || result.aborted) return;
|
|
2229
|
+
result.aborted = true;
|
|
2230
|
+
if (!child.pid) return;
|
|
2231
|
+
try {
|
|
2232
|
+
process.kill(-child.pid, "SIGTERM");
|
|
2233
|
+
} catch {
|
|
2234
|
+
}
|
|
2235
|
+
killTimer = setTimeout(() => {
|
|
2236
|
+
try {
|
|
2237
|
+
process.kill(-child.pid, "SIGKILL");
|
|
2238
|
+
} catch {
|
|
2239
|
+
}
|
|
2240
|
+
}, 3e3);
|
|
2241
|
+
};
|
|
2242
|
+
const handleLine = (line) => {
|
|
2243
|
+
stdoutTail = `${stdoutTail}
|
|
2244
|
+
${line}`.slice(-8192);
|
|
2245
|
+
try {
|
|
2246
|
+
const ev = JSON.parse(line);
|
|
2247
|
+
const sid = typeof ev.session_id === "string" ? ev.session_id : void 0;
|
|
2248
|
+
if (sid && !result.sessionId) {
|
|
2249
|
+
result.sessionId = sid;
|
|
2250
|
+
sessionSave = options.onSessionStarted(sid);
|
|
2251
|
+
void sessionSave.catch(stop);
|
|
2252
|
+
}
|
|
2253
|
+
if (ev.type === "stream_event") {
|
|
2254
|
+
const inner = ev.event;
|
|
2255
|
+
if (inner?.type === "content_block_delta" && inner.delta?.type === "text_delta" && typeof inner.delta.text === "string") {
|
|
2256
|
+
streamedText += inner.delta.text;
|
|
2257
|
+
if (streamedText.trim()) {
|
|
2258
|
+
result.finalOutput = streamedText;
|
|
2259
|
+
options.onDelta?.(streamedText);
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
2263
|
+
if (ev.type === "result") {
|
|
2264
|
+
result.completed = ev.is_error !== true;
|
|
2265
|
+
if (typeof ev.result === "string" && ev.result.trim()) {
|
|
2266
|
+
result.finalOutput = ev.result;
|
|
2267
|
+
options.onDelta?.(ev.result);
|
|
2268
|
+
}
|
|
2269
|
+
if (ev.is_error === true && typeof ev.result === "string") {
|
|
2270
|
+
const authErr = detectAuthFailure(ev.result, "Claude Code", "\u8BF7\u5728\u672C\u673A\u7EC8\u7AEF\u8FD0\u884C claude \u540E\u6267\u884C /login");
|
|
2271
|
+
if (authErr) result.authFailure = authErr;
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
if (ev.type === "assistant") {
|
|
2275
|
+
const msg = ev.message;
|
|
2276
|
+
const texts = msg?.content?.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n").trim();
|
|
2277
|
+
if (texts) {
|
|
2278
|
+
streamedText = texts;
|
|
2279
|
+
result.finalOutput = texts;
|
|
2280
|
+
options.onDelta?.(texts);
|
|
2281
|
+
options.onStep?.({
|
|
2282
|
+
kind: "message",
|
|
2283
|
+
title: "\u9636\u6BB5\u56DE\u590D",
|
|
2284
|
+
detail: texts.replace(/\s+/g, " ").slice(0, 240)
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
for (const block of msg?.content ?? []) {
|
|
2288
|
+
if (block.type !== "tool_use" || !block.name) continue;
|
|
2289
|
+
if (block.id && emittedToolIds.has(block.id)) continue;
|
|
2290
|
+
if (block.id) emittedToolIds.add(block.id);
|
|
2291
|
+
options.onStep?.(classifyToolStep(block.name, block.input));
|
|
2292
|
+
}
|
|
2293
|
+
const first = msg?.content?.find((c) => c.type === "text" || c.type === "tool_use");
|
|
2294
|
+
if (first?.type === "tool_use" && first.name) options.onActivity?.(`\u8C03\u7528\u5DE5\u5177\uFF1A${first.name}`);
|
|
2295
|
+
else if (first?.type === "text" && first.text)
|
|
2296
|
+
options.onActivity?.(first.text.replace(/\s+/g, " ").slice(0, 120));
|
|
2297
|
+
}
|
|
2298
|
+
} catch {
|
|
2299
|
+
}
|
|
2300
|
+
};
|
|
2301
|
+
options.signal.addEventListener("abort", stop, { once: true });
|
|
2302
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
2303
|
+
buf += chunk;
|
|
2304
|
+
for (let idx = buf.indexOf("\n"); idx >= 0; idx = buf.indexOf("\n")) {
|
|
2305
|
+
handleLine(buf.slice(0, idx));
|
|
2306
|
+
buf = buf.slice(idx + 1);
|
|
2307
|
+
}
|
|
2308
|
+
if (buf.length > 1024 * 1024) buf = buf.slice(-65536);
|
|
2309
|
+
});
|
|
2310
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
2311
|
+
stderr = (stderr + chunk).slice(-8192);
|
|
2312
|
+
});
|
|
2313
|
+
child.once("error", () => {
|
|
2314
|
+
spawnFailed = true;
|
|
2315
|
+
});
|
|
2316
|
+
child.once("close", (code, sig) => {
|
|
2317
|
+
if (buf.trim()) handleLine(buf);
|
|
2318
|
+
closed = true;
|
|
2319
|
+
result.outerExit = spawnFailed ? -1 : code;
|
|
2320
|
+
result.signal = sig;
|
|
2321
|
+
if (!result.authFailure) {
|
|
2322
|
+
const authErr = detectAuthFailure(
|
|
2323
|
+
`${stderr}
|
|
2324
|
+
${stdoutTail}`,
|
|
2325
|
+
"Claude Code",
|
|
2326
|
+
"\u8BF7\u5728\u672C\u673A\u7EC8\u7AEF\u8FD0\u884C claude \u540E\u6267\u884C /login"
|
|
2327
|
+
);
|
|
2328
|
+
if (authErr) result.authFailure = authErr;
|
|
2329
|
+
}
|
|
2330
|
+
if (result.authFailure) {
|
|
2331
|
+
result.completed = false;
|
|
2332
|
+
result.errorMessage = result.authFailure.loginMessage;
|
|
2333
|
+
runtimeAuthFailure = { failure: result.authFailure, detectedAtMs: Date.now() };
|
|
2334
|
+
} else {
|
|
2335
|
+
if (!result.completed && code === 0 && !result.aborted) result.completed = true;
|
|
2336
|
+
if (result.completed && code === 0) runtimeAuthFailure = null;
|
|
2337
|
+
}
|
|
2338
|
+
if (options.sessionId && !result.completed && !result.authFailure && /session|resume|not found/i.test(stderr)) {
|
|
2339
|
+
result.resumeUnavailable = true;
|
|
2340
|
+
}
|
|
2341
|
+
clearTimeout(killTimer);
|
|
2342
|
+
options.signal.removeEventListener("abort", stop);
|
|
2343
|
+
resolve();
|
|
2344
|
+
});
|
|
2345
|
+
if (options.signal.aborted) stop();
|
|
2346
|
+
child.stdin.on("error", () => {
|
|
2347
|
+
});
|
|
2348
|
+
child.stdin.end(options.prompt);
|
|
2349
|
+
});
|
|
2350
|
+
try {
|
|
2351
|
+
await sessionSave;
|
|
2352
|
+
} finally {
|
|
2353
|
+
await atomicJson(options.recordFile, { ...result, args, startedAt, finishedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
2354
|
+
}
|
|
2355
|
+
return result;
|
|
2356
|
+
}
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
|
|
2360
|
+
// src/drivers/codex.ts
|
|
2361
|
+
import { spawn as spawn3 } from "child_process";
|
|
2362
|
+
import { homedir as homedir4 } from "os";
|
|
2363
|
+
import path8 from "path";
|
|
2364
|
+
var DEFAULT_MODEL = process.env.CODEX_MODEL ?? "gpt-6.1-sol";
|
|
2365
|
+
var DEFAULT_EFFORT = process.env.CODEX_REASONING_EFFORT ?? "xhigh";
|
|
2366
|
+
function codexArgs(workDir, sessionId, opts) {
|
|
2367
|
+
const images = [...new Set((opts?.imagePaths ?? []).map((p) => p.trim()).filter(Boolean))];
|
|
2368
|
+
const permissionArgs = opts?.readOnly ? ["--sandbox", "read-only"] : opts?.skipPermissions ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--approve-for-me"];
|
|
2369
|
+
const args = [
|
|
2370
|
+
"exec",
|
|
2371
|
+
"--ignore-user-config",
|
|
2372
|
+
"-m",
|
|
2373
|
+
DEFAULT_MODEL,
|
|
2374
|
+
"-c",
|
|
2375
|
+
`model_reasoning_effort="${DEFAULT_EFFORT}"`,
|
|
2376
|
+
...permissionArgs,
|
|
2377
|
+
"--skip-git-repo-check"
|
|
2378
|
+
];
|
|
2379
|
+
if (sessionId === void 0) {
|
|
2380
|
+
for (const img of images) args.push("-i", img);
|
|
2381
|
+
}
|
|
2382
|
+
args.push("--cd", workDir, "--json", "-c", 'shell_environment_policy.inherit="all"');
|
|
2383
|
+
if (sessionId !== void 0) {
|
|
2384
|
+
args.push("resume");
|
|
2385
|
+
for (const img of images) args.push("-i", img);
|
|
2386
|
+
args.push(sessionIdSchema.parse(sessionId));
|
|
2387
|
+
}
|
|
2388
|
+
return [...args, "-"];
|
|
2389
|
+
}
|
|
2390
|
+
function parseCodexLoginStatus(output, code) {
|
|
2391
|
+
if (code !== 0) return { loginState: "error", loginMessage: "\u65E0\u6CD5\u68C0\u67E5 Codex \u767B\u5F55\u72B6\u6001" };
|
|
2392
|
+
if (/expired|过期/i.test(output)) return { loginState: "expired", loginMessage: "Codex \u767B\u5F55\u5DF2\u8FC7\u671F" };
|
|
2393
|
+
if (/not logged in|logged out|未登录/i.test(output))
|
|
2394
|
+
return { loginState: "logged_out", loginMessage: "Codex \u5C1A\u672A\u767B\u5F55" };
|
|
2395
|
+
if (/logged in/i.test(output)) return { loginState: "logged_in" };
|
|
2396
|
+
return { loginState: "error", loginMessage: "\u65E0\u6CD5\u8BC6\u522B Codex \u767B\u5F55\u72B6\u6001" };
|
|
2397
|
+
}
|
|
2398
|
+
function parseCodexDeviceOutput(output) {
|
|
2399
|
+
const text = stripAnsi(output);
|
|
2400
|
+
const verificationUri = text.match(/https:\/\/[^\s<>"']+/g)?.find((value) => {
|
|
2401
|
+
try {
|
|
2402
|
+
const u = new URL(value);
|
|
2403
|
+
return !u.username && !u.password && u.pathname.endsWith("/codex/device");
|
|
2404
|
+
} catch {
|
|
2405
|
+
return false;
|
|
2406
|
+
}
|
|
2407
|
+
});
|
|
2408
|
+
const userCode = text.match(/\b[A-Z0-9]{4}-[A-Z0-9]{5}\b/)?.[0];
|
|
2409
|
+
return verificationUri && userCode ? { verificationUri, userCode } : null;
|
|
2410
|
+
}
|
|
2411
|
+
function createCodexDriver() {
|
|
2412
|
+
const resolveBin = () => findExecutable(
|
|
2413
|
+
[
|
|
2414
|
+
process.env.CODEX_BIN,
|
|
2415
|
+
path8.join(path8.dirname(process.execPath), "codex"),
|
|
2416
|
+
path8.join(homedir4(), ".local/bin/codex"),
|
|
2417
|
+
"/opt/homebrew/bin/codex",
|
|
2418
|
+
"/usr/local/bin/codex"
|
|
2419
|
+
],
|
|
2420
|
+
["codex"]
|
|
2421
|
+
);
|
|
2422
|
+
function spawnLoginCmd(args, signal, onOutput) {
|
|
2423
|
+
const bin = resolveBin();
|
|
2424
|
+
if (!bin) return Promise.resolve({ code: null });
|
|
2425
|
+
return new Promise((resolve) => {
|
|
2426
|
+
if (signal.aborted) {
|
|
2427
|
+
resolve({ code: null });
|
|
2428
|
+
return;
|
|
2429
|
+
}
|
|
2430
|
+
const env = {};
|
|
2431
|
+
for (const k of ["HOME", "USER", "LOGNAME", "PATH", "TMPDIR", "SHELL", "LANG", "TERM", "CODEX_HOME"]) {
|
|
2432
|
+
if (process.env[k]) env[k] = process.env[k];
|
|
2433
|
+
}
|
|
2434
|
+
const child = spawn3(bin, args, { env, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
2435
|
+
let killTimer;
|
|
2436
|
+
const stop = () => {
|
|
2437
|
+
if (!child.pid) return;
|
|
2438
|
+
try {
|
|
2439
|
+
process.kill(-child.pid, "SIGTERM");
|
|
2440
|
+
} catch {
|
|
2441
|
+
}
|
|
2442
|
+
killTimer = setTimeout(() => {
|
|
2443
|
+
try {
|
|
2444
|
+
process.kill(-child.pid, "SIGKILL");
|
|
2445
|
+
} catch {
|
|
2446
|
+
}
|
|
2447
|
+
}, 3e3);
|
|
2448
|
+
};
|
|
2449
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
2450
|
+
for (const s of [child.stdout, child.stderr]) {
|
|
2451
|
+
s.setEncoding("utf8");
|
|
2452
|
+
s.on("data", onOutput);
|
|
2453
|
+
}
|
|
2454
|
+
const finish = (code) => {
|
|
2455
|
+
clearTimeout(killTimer);
|
|
2456
|
+
signal.removeEventListener("abort", stop);
|
|
2457
|
+
resolve({ code });
|
|
2458
|
+
};
|
|
2459
|
+
child.on("error", () => finish(null));
|
|
2460
|
+
child.on("close", finish);
|
|
2461
|
+
});
|
|
2462
|
+
}
|
|
2463
|
+
return {
|
|
2464
|
+
type: "codex",
|
|
2465
|
+
authMode: "device_flow",
|
|
2466
|
+
binaryPath: resolveBin,
|
|
2467
|
+
async checkAuth(signal) {
|
|
2468
|
+
const bin = resolveBin();
|
|
2469
|
+
if (!bin) return { loginState: "error", loginMessage: "\u672C\u673A\u672A\u627E\u5230 codex \u53EF\u6267\u884C\u6587\u4EF6" };
|
|
2470
|
+
let output = "";
|
|
2471
|
+
const res = await spawnLoginCmd(
|
|
2472
|
+
["login", "status"],
|
|
2473
|
+
AbortSignal.any([signal, AbortSignal.timeout(8e3)]),
|
|
2474
|
+
(chunk) => {
|
|
2475
|
+
output = (output + chunk).slice(-16384);
|
|
2476
|
+
}
|
|
2477
|
+
);
|
|
2478
|
+
return parseCodexLoginStatus(stripAnsi(output), res.code);
|
|
2479
|
+
},
|
|
2480
|
+
startDeviceLogin(signal, onOutput) {
|
|
2481
|
+
return spawnLoginCmd(["login", "--device-auth"], signal, onOutput);
|
|
2482
|
+
},
|
|
2483
|
+
parseDeviceOutput: parseCodexDeviceOutput,
|
|
2484
|
+
async run(options) {
|
|
2485
|
+
const bin = resolveBin();
|
|
2486
|
+
const result = {
|
|
2487
|
+
driver: "codex",
|
|
2488
|
+
sessionId: null,
|
|
2489
|
+
outerExit: null,
|
|
2490
|
+
signal: null,
|
|
2491
|
+
completed: false,
|
|
2492
|
+
aborted: false
|
|
2493
|
+
};
|
|
2494
|
+
if (!bin) {
|
|
2495
|
+
result.errorMessage = "\u672C\u673A\u672A\u627E\u5230 codex \u53EF\u6267\u884C\u6587\u4EF6";
|
|
2496
|
+
return result;
|
|
2497
|
+
}
|
|
2498
|
+
const args = codexArgs(options.workDir, options.sessionId, {
|
|
2499
|
+
skipPermissions: options.skipPermissions,
|
|
2500
|
+
readOnly: options.readOnly,
|
|
2501
|
+
imagePaths: options.imagePaths
|
|
2502
|
+
});
|
|
2503
|
+
const env = baseEnv(options.binDir, ["CODEX_HOME", "OPENAI_API_KEY"]);
|
|
2504
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2505
|
+
let sessionSave;
|
|
2506
|
+
await atomicJson(options.recordFile, { ...result, args, startedAt });
|
|
2507
|
+
if (options.signal.aborted) {
|
|
2508
|
+
result.aborted = true;
|
|
2509
|
+
return result;
|
|
2510
|
+
}
|
|
2511
|
+
await new Promise((resolve) => {
|
|
2512
|
+
const child = spawn3(bin, args, { cwd: options.workDir, env, stdio: ["pipe", "pipe", "pipe"], detached: true });
|
|
2513
|
+
let buf = "";
|
|
2514
|
+
let stderr = "";
|
|
2515
|
+
let streamedText = "";
|
|
2516
|
+
let sawTurn = false;
|
|
2517
|
+
let closed = false;
|
|
2518
|
+
let spawnFailed = false;
|
|
2519
|
+
let killTimer;
|
|
2520
|
+
const emittedItemIds = /* @__PURE__ */ new Set();
|
|
2521
|
+
const stop = () => {
|
|
2522
|
+
if (closed || result.aborted) return;
|
|
2523
|
+
result.aborted = true;
|
|
2524
|
+
if (!child.pid) return;
|
|
2525
|
+
try {
|
|
2526
|
+
process.kill(-child.pid, "SIGTERM");
|
|
2527
|
+
} catch {
|
|
2528
|
+
}
|
|
2529
|
+
killTimer = setTimeout(() => {
|
|
2530
|
+
try {
|
|
2531
|
+
process.kill(-child.pid, "SIGKILL");
|
|
2532
|
+
} catch {
|
|
2533
|
+
}
|
|
2534
|
+
}, 3e3);
|
|
2535
|
+
};
|
|
2536
|
+
const handleLine = (line) => {
|
|
2537
|
+
try {
|
|
2538
|
+
const ev = JSON.parse(line);
|
|
2539
|
+
const type = typeof ev.type === "string" ? ev.type : "";
|
|
2540
|
+
if (type.startsWith("turn.") || type.startsWith("item.")) sawTurn = true;
|
|
2541
|
+
if (type === "thread.started" && !result.sessionId && typeof ev.thread_id === "string") {
|
|
2542
|
+
result.sessionId = ev.thread_id;
|
|
2543
|
+
sessionSave = options.onSessionStarted(ev.thread_id);
|
|
2544
|
+
void sessionSave.catch(stop);
|
|
2545
|
+
}
|
|
2546
|
+
if (type === "turn.completed") result.completed = true;
|
|
2547
|
+
if (type === "turn.failed" || type === "error") result.completed = false;
|
|
2548
|
+
if (type.endsWith(".delta") && typeof ev.delta === "string") {
|
|
2549
|
+
streamedText += ev.delta;
|
|
2550
|
+
if (streamedText.trim()) {
|
|
2551
|
+
result.finalOutput = streamedText;
|
|
2552
|
+
options.onDelta?.(streamedText);
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
if (type === "item.started" || type === "item.updated" || type === "item.completed") {
|
|
2556
|
+
const item = ev.item;
|
|
2557
|
+
const itemId = typeof item?.id === "string" ? item.id : void 0;
|
|
2558
|
+
if (item?.type === "command_execution" && typeof item.command === "string") {
|
|
2559
|
+
options.onActivity?.(`\u6267\u884C\u547D\u4EE4\uFF1A${item.command.slice(0, 80)}`);
|
|
2560
|
+
const key = itemId ? `cmd:${itemId}` : `cmd:${item.command}`;
|
|
2561
|
+
if (!emittedItemIds.has(key)) {
|
|
2562
|
+
emittedItemIds.add(key);
|
|
2563
|
+
options.onStep?.(classifyCommandStep(item.command));
|
|
2564
|
+
}
|
|
2565
|
+
} else if (item?.type === "mcp_tool_call") {
|
|
2566
|
+
const toolName = typeof item.tool === "string" && item.tool || typeof item.name === "string" && item.name || "mcp_tool";
|
|
2567
|
+
options.onActivity?.(`\u8C03\u7528\u5DE5\u5177\uFF1A${toolName.slice(0, 80)}`);
|
|
2568
|
+
const key = itemId ? `tool:${itemId}` : `tool:${toolName}`;
|
|
2569
|
+
if (!emittedItemIds.has(key)) {
|
|
2570
|
+
emittedItemIds.add(key);
|
|
2571
|
+
const args2 = item.arguments && typeof item.arguments === "object" ? item.arguments : void 0;
|
|
2572
|
+
options.onStep?.(classifyToolStep(toolName, args2));
|
|
2573
|
+
}
|
|
2574
|
+
} else if (item?.type === "file_change" && type === "item.completed") {
|
|
2575
|
+
const key = itemId ? `file:${itemId}` : void 0;
|
|
2576
|
+
if (!key || !emittedItemIds.has(key)) {
|
|
2577
|
+
if (key) emittedItemIds.add(key);
|
|
2578
|
+
const changes = Array.isArray(item.changes) ? item.changes : [];
|
|
2579
|
+
const paths = changes.map(
|
|
2580
|
+
(c) => c && typeof c === "object" && typeof c.path === "string" ? c.path : ""
|
|
2581
|
+
).filter(Boolean).slice(0, 4);
|
|
2582
|
+
options.onStep?.({
|
|
2583
|
+
kind: "tool",
|
|
2584
|
+
title: "\u4FEE\u6539\u6587\u4EF6",
|
|
2585
|
+
...paths.length > 0 ? { detail: paths.join(", ").slice(0, 240) } : {}
|
|
2586
|
+
});
|
|
2587
|
+
}
|
|
2588
|
+
} else if (item?.type === "web_search") {
|
|
2589
|
+
const query = typeof item.query === "string" ? item.query : void 0;
|
|
2590
|
+
const key = itemId ? `web:${itemId}` : `web:${query ?? ""}`;
|
|
2591
|
+
if (!emittedItemIds.has(key)) {
|
|
2592
|
+
emittedItemIds.add(key);
|
|
2593
|
+
options.onStep?.({
|
|
2594
|
+
kind: "tool",
|
|
2595
|
+
title: "\u67E5\u9605\u5916\u90E8\u8D44\u6599",
|
|
2596
|
+
...query ? { detail: query.slice(0, 240) } : {}
|
|
2597
|
+
});
|
|
2598
|
+
}
|
|
2599
|
+
} else if (item?.type === "agent_message" && typeof item.text === "string") {
|
|
2600
|
+
if (item.text.trim()) {
|
|
2601
|
+
streamedText = item.text;
|
|
2602
|
+
result.finalOutput = item.text;
|
|
2603
|
+
options.onDelta?.(item.text);
|
|
2604
|
+
if (type === "item.completed") {
|
|
2605
|
+
const key = itemId ? `msg:${itemId}` : void 0;
|
|
2606
|
+
if (!key || !emittedItemIds.has(key)) {
|
|
2607
|
+
if (key) emittedItemIds.add(key);
|
|
2608
|
+
options.onStep?.({
|
|
2609
|
+
kind: "message",
|
|
2610
|
+
title: "\u9636\u6BB5\u56DE\u590D",
|
|
2611
|
+
detail: item.text.replace(/\s+/g, " ").trim().slice(0, 240)
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
}
|
|
2616
|
+
options.onActivity?.(item.text.replace(/\s+/g, " ").slice(0, 120));
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
} catch {
|
|
2620
|
+
}
|
|
2621
|
+
};
|
|
2622
|
+
options.signal.addEventListener("abort", stop, { once: true });
|
|
2623
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
2624
|
+
buf += chunk;
|
|
2625
|
+
for (let idx = buf.indexOf("\n"); idx >= 0; idx = buf.indexOf("\n")) {
|
|
2626
|
+
handleLine(buf.slice(0, idx));
|
|
2627
|
+
buf = buf.slice(idx + 1);
|
|
2628
|
+
}
|
|
2629
|
+
if (buf.length > 1024 * 1024) buf = buf.slice(-65536);
|
|
2630
|
+
});
|
|
2631
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
2632
|
+
stderr = (stderr + chunk).slice(-8192);
|
|
2633
|
+
});
|
|
2634
|
+
child.once("error", () => {
|
|
2635
|
+
spawnFailed = true;
|
|
2636
|
+
});
|
|
2637
|
+
child.once("close", (code, sig) => {
|
|
2638
|
+
if (buf.trim()) handleLine(buf);
|
|
2639
|
+
closed = true;
|
|
2640
|
+
result.outerExit = spawnFailed ? -1 : code;
|
|
2641
|
+
result.signal = sig;
|
|
2642
|
+
if (options.sessionId && !result.sessionId && !sawTurn && !result.aborted && !sig && !spawnFailed && code !== null && code > 0 && /thread\/resume/i.test(stderr)) {
|
|
2643
|
+
result.resumeUnavailable = true;
|
|
2644
|
+
}
|
|
2645
|
+
clearTimeout(killTimer);
|
|
2646
|
+
options.signal.removeEventListener("abort", stop);
|
|
2647
|
+
resolve();
|
|
2648
|
+
});
|
|
2649
|
+
if (options.signal.aborted) stop();
|
|
2650
|
+
child.stdin.on("error", () => {
|
|
2651
|
+
});
|
|
2652
|
+
child.stdin.end(options.prompt);
|
|
2653
|
+
});
|
|
2654
|
+
try {
|
|
2655
|
+
await sessionSave;
|
|
2656
|
+
} finally {
|
|
2657
|
+
await atomicJson(options.recordFile, { ...result, args, startedAt, finishedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
2658
|
+
}
|
|
2659
|
+
return result;
|
|
2660
|
+
}
|
|
2661
|
+
};
|
|
2662
|
+
}
|
|
2663
|
+
|
|
2664
|
+
// src/drivers/index.ts
|
|
2665
|
+
function createDriver(type) {
|
|
2666
|
+
if (type === "codex") return createCodexDriver();
|
|
2667
|
+
if (type === "claude-code") return createClaudeCodeDriver();
|
|
2668
|
+
return createAntigravityDriver();
|
|
2669
|
+
}
|
|
2670
|
+
function detectInstalledDrivers() {
|
|
2671
|
+
const all = ["codex", "claude-code", "antigravity"];
|
|
2672
|
+
return all.filter((type) => createDriver(type).binaryPath() !== null);
|
|
2673
|
+
}
|
|
2674
|
+
|
|
2675
|
+
// src/loop.ts
|
|
2676
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2677
|
+
import { existsSync as existsSync4, statSync as statSync4 } from "fs";
|
|
2678
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
2679
|
+
import path9 from "path";
|
|
2680
|
+
var DEFAULT_MAX_CONCURRENCY = 5;
|
|
2681
|
+
var MAX_ALLOWED_CONCURRENCY = 16;
|
|
2682
|
+
function parseMaxConcurrency(raw) {
|
|
2683
|
+
if (raw === void 0 || raw === "") return DEFAULT_MAX_CONCURRENCY;
|
|
2684
|
+
const parsed = typeof raw === "number" ? raw : Number(raw.trim());
|
|
2685
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_ALLOWED_CONCURRENCY) {
|
|
2686
|
+
throw new Error(`\u5E76\u53D1\u6570\u5FC5\u987B\u662F 1\uFF5E${MAX_ALLOWED_CONCURRENCY} \u4E4B\u95F4\u7684\u6574\u6570`);
|
|
2687
|
+
}
|
|
2688
|
+
return parsed;
|
|
2689
|
+
}
|
|
2690
|
+
function isTargetedToAgent(event, agentId) {
|
|
2691
|
+
if (event.actorKind !== "human") return false;
|
|
2692
|
+
const targets = Array.isArray(event.data.targetActorIds) ? event.data.targetActorIds : [];
|
|
2693
|
+
return targets.includes(agentId);
|
|
2694
|
+
}
|
|
2695
|
+
function formatAttachmentLines(attachments, heading) {
|
|
2696
|
+
if (!attachments || attachments.length === 0) return [];
|
|
2697
|
+
return [
|
|
2698
|
+
heading,
|
|
2699
|
+
...attachments.map(
|
|
2700
|
+
(a, idx) => `${idx + 1}. [${a.kind === "image" ? "\u56FE\u7247" : "\u6587\u4EF6"}] ${a.filename}\uFF08${a.mimeType}\uFF0C${a.sizeBytes} bytes\uFF09-> ${a.localPath}`
|
|
2701
|
+
)
|
|
2702
|
+
];
|
|
2703
|
+
}
|
|
2704
|
+
function resolveEventAttachments(card, event) {
|
|
2705
|
+
const hydrated = card.events.find((e) => e.id === event.id)?.attachments;
|
|
2706
|
+
if (hydrated && hydrated.length > 0) return hydrated;
|
|
2707
|
+
return event.attachments ?? [];
|
|
2708
|
+
}
|
|
2709
|
+
function resolveEventsAttachments(card, events) {
|
|
2710
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2711
|
+
const out = [];
|
|
2712
|
+
for (const event of events) {
|
|
2713
|
+
for (const att of resolveEventAttachments(card, event)) {
|
|
2714
|
+
if (seen.has(att.id)) continue;
|
|
2715
|
+
seen.add(att.id);
|
|
2716
|
+
out.push(att);
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
return out;
|
|
2720
|
+
}
|
|
2721
|
+
function collectImagePaths(attachments) {
|
|
2722
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2723
|
+
const out = [];
|
|
2724
|
+
for (const a of attachments) {
|
|
2725
|
+
if (a.kind !== "image" || !a.localPath || seen.has(a.localPath)) continue;
|
|
2726
|
+
if (!existsSync4(a.localPath)) continue;
|
|
2727
|
+
seen.add(a.localPath);
|
|
2728
|
+
out.push(a.localPath);
|
|
2729
|
+
}
|
|
2730
|
+
return out;
|
|
2731
|
+
}
|
|
2732
|
+
function isExistingDir(dirPath) {
|
|
2733
|
+
if (!dirPath) return false;
|
|
2734
|
+
try {
|
|
2735
|
+
return statSync4(dirPath).isDirectory();
|
|
2736
|
+
} catch {
|
|
2737
|
+
return false;
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
function findSelfParticipant(participants, agentId, agentName) {
|
|
2741
|
+
return participants.find((p) => agentId ? p.agentId === agentId : p.agentName === agentName);
|
|
2742
|
+
}
|
|
2743
|
+
function findExistingParticipantWorktree(participants, workspace, identity) {
|
|
2744
|
+
if (workspace.branch) return null;
|
|
2745
|
+
const self = findSelfParticipant(participants, identity.agentId, identity.agentName);
|
|
2746
|
+
if (!self?.branch || !isExistingDir(self.workDir)) return null;
|
|
2747
|
+
return { workDir: self.workDir, branch: self.branch };
|
|
2748
|
+
}
|
|
2749
|
+
function buildPrompt(options) {
|
|
2750
|
+
const { agentName, driver, card, event, coalescedEvents, workspace, binding, project, agentId } = options;
|
|
2751
|
+
const triggerEvents = coalescedEvents && coalescedEvents.length > 0 ? coalescedEvents : [event];
|
|
2752
|
+
const triggerEventIds = new Set(triggerEvents.map((e) => e.id));
|
|
2753
|
+
const selfParticipant = findSelfParticipant(card.participants, agentId, agentName);
|
|
2754
|
+
const siblings = card.participants.filter((p) => p !== selfParticipant).map((p) => ({
|
|
2755
|
+
name: p.agentName,
|
|
2756
|
+
driver: p.driver,
|
|
2757
|
+
state: p.state,
|
|
2758
|
+
workDir: p.workDir,
|
|
2759
|
+
branch: p.branch,
|
|
2760
|
+
activityText: p.activityText
|
|
2761
|
+
}));
|
|
2762
|
+
const projectRoot = workspace.projectRoot !== void 0 ? workspace.projectRoot : project?.rootPath?.trim() ? resolveUserPath(project.rootPath) : null;
|
|
2763
|
+
const existingWorktree = findExistingParticipantWorktree(card.participants, workspace, { agentId, agentName });
|
|
2764
|
+
const gitAvailable = Boolean(workspace.gitAvailable);
|
|
2765
|
+
const worktreePromptLines = [];
|
|
2766
|
+
if (projectRoot && path9.resolve(workspace.workDir) !== path9.resolve(projectRoot)) {
|
|
2767
|
+
worktreePromptLines.push(`\u9879\u76EE\u539F\u76EE\u5F55\uFF08\u53EA\u8BFB\u67E5\u9605/\u53C2\u8003\uFF09\uFF1A${projectRoot}\u3002`);
|
|
2768
|
+
}
|
|
2769
|
+
if (existingWorktree) {
|
|
2770
|
+
worktreePromptLines.push(
|
|
2771
|
+
`\u4F60\u6B64\u524D\u5DF2\u4E3A\u672C\u5361\u521B\u5EFA\u8FC7\u72EC\u7ACB Git worktree\uFF1A${existingWorktree.workDir}\uFF08\u5206\u652F\uFF1A${existingWorktree.branch}\uFF09\uFF0C\u5982\u9700\u7EE7\u7EED\u6539\u4EE3\u7801\u8BF7\u76F4\u63A5\u5728\u8BE5\u76EE\u5F55\u4E2D\u64CD\u4F5C\u3002`
|
|
2772
|
+
);
|
|
2773
|
+
} else if (gitAvailable && !workspace.branch && project?.parallelMode !== "shared") {
|
|
2774
|
+
worktreePromptLines.push(
|
|
2775
|
+
"\u5982\u672C\u4EFB\u52A1\u4EC5\u9700\u8C03\u7814\u3001\u8BC4\u5BA1\u3001\u5199\u65B9\u6848\u6216\u4EA7\u51FA\u6587\u6863\uFF0C\u8BF7\u76F4\u63A5\u53EA\u8BFB\u67E5\u9605\u9879\u76EE\u76EE\u5F55\u5E76\u5728\u4E13\u5C5E\u76EE\u5F55\u5B8C\u6210\uFF1B\u5982\u786E\u5B9E\u9700\u8981\u4FEE\u6539\u4EE3\u7801\u4ED3\u5E93\u6587\u4EF6\u5E76\u9A8C\u8BC1\u6D4B\u8BD5\uFF0C\u53EF\u8FD0\u884C slate worktree \u7533\u8BF7\u72EC\u7ACB Git \u5206\u652F\u4E0E\u9694\u79BB\u76EE\u5F55\u3002"
|
|
2776
|
+
);
|
|
2777
|
+
}
|
|
2778
|
+
const eventAttachments = resolveEventsAttachments(card, triggerEvents);
|
|
2779
|
+
const eventAttachmentLines = formatAttachmentLines(
|
|
2780
|
+
eventAttachments,
|
|
2781
|
+
`\u672C\u6B21\u89E6\u53D1\u8BC4\u8BBA\u9644\u5E26\u4EE5\u4E0B ${eventAttachments.length} \u4E2A\u65B0\u9644\u4EF6\uFF08\u8BF7\u52A1\u5FC5\u4F18\u5148\u67E5\u770B\u8FD9\u4E9B\u622A\u56FE\u6216\u6587\u4EF6\uFF09\uFF1A`
|
|
2782
|
+
);
|
|
2783
|
+
const cardAttachmentLines = formatAttachmentLines(
|
|
2784
|
+
card.attachments,
|
|
2785
|
+
`\u672C\u5361\u7247\u9644\u5E26\u4EE5\u4E0B ${card.attachments?.length ?? 0} \u4E2A\u8F93\u5165\u9644\u4EF6\uFF08\u8BF7\u4F18\u5148\u9605\u8BFB\u6216\u67E5\u770B\u5BF9\u5E94\u672C\u673A\u6587\u4EF6\uFF09\uFF1A`
|
|
2786
|
+
);
|
|
2787
|
+
const hasStartTransition = triggerEvents.some((e) => e.type === "status_changed");
|
|
2788
|
+
const commonHeader = [
|
|
2789
|
+
`\u4F60\u662F Slate \u770B\u677F\u534F\u4F5C\u8005\u300C${agentName}\u300D\uFF08\u9A71\u52A8\uFF1A${driver}\uFF09\u3002`,
|
|
2790
|
+
`\u8BF7\u9605\u8BFB\u5E76\u9075\u5FAA\u534F\u4F5C\u8BF4\u660E\uFF1A${workspace.skillPath}\uFF0C\u4F7F\u7528 PATH \u4E0A\u7684 \`slate\` CLI \u76F4\u63A5\u7F16\u8F91\u5361\u7247\u6B63\u6587/\u6E05\u5355\u3001\u5207\u6362\u72B6\u6001\u3001\u6302\u8F7D\u4EA7\u51FA\u548C\u53D1\u8868\u8BC4\u8BBA\u3002`,
|
|
2791
|
+
`\u4F60\u7684\u5F53\u524D\u4E13\u5C5E\u5DE5\u4F5C\u76EE\u5F55\uFF1A${workspace.workDir}${workspace.branch ? `\uFF08Git \u5206\u652F\uFF1A${workspace.branch}\uFF09` : ""}\u3002`,
|
|
2792
|
+
...worktreePromptLines,
|
|
2793
|
+
...hasStartTransition ? ["\u7528\u6237\u5DF2\u5C06\u6B64\u4EFB\u52A1\u79FB\u5165\u300C\u8FDB\u884C\u4E2D\u300D\u5E76\u6307\u6D3E\u7ED9\u4F60\u5F00\u59CB\u6267\u884C\uFF0C\u8BF7\u9605\u8BFB\u5361\u7247\u5185\u5BB9\u4E0E\u6E05\u5355\u5E76\u63A8\u8FDB\u5B8C\u6210\u3002"] : [],
|
|
2794
|
+
...eventAttachmentLines,
|
|
2795
|
+
...cardAttachmentLines,
|
|
2796
|
+
...siblings.length ? [`\u540C\u5361\u5E76\u884C/\u5386\u53F2\u534F\u4F5C\u8005\uFF08\u4F60\u53EF\u4EE5\u53EA\u8BFB\u67E5\u770B\u5BF9\u65B9\u76EE\u5F55\u6216\u5206\u652F\uFF0C\u4E0D\u8981\u76F4\u63A5\u4FEE\u6539\u5BF9\u65B9\u5DE5\u4F5C\u533A\uFF09\uFF1A${JSON.stringify(siblings)}`] : []
|
|
2797
|
+
];
|
|
2798
|
+
const hydratedEvents = triggerEvents.map((ev) => {
|
|
2799
|
+
const atts = resolveEventAttachments(card, ev);
|
|
2800
|
+
return atts.length > 0 ? { ...ev, attachments: atts } : ev;
|
|
2801
|
+
});
|
|
2802
|
+
const triggerLine = hydratedEvents.length > 1 ? `\u7528\u6237\u8FDE\u7EED\u53D1\u6765\u4E86 ${hydratedEvents.length} \u6761\u89E6\u53D1\u4E8B\u4EF6\uFF0C\u5DF2\u81EA\u52A8\u5408\u5E76\u5230\u672C\u8F6E\u4E00\u6B21\u6027\u5904\u7406\uFF08\u6309\u65F6\u95F4\u987A\u5E8F\uFF0CJSON\uFF09\uFF1A${JSON.stringify(hydratedEvents)}` : `\u672C\u6B21\u89E6\u53D1\u4E8B\u4EF6${binding ? "" : "\uFF08JSON\uFF09"}\uFF1A${JSON.stringify(hydratedEvents[0])}`;
|
|
2803
|
+
if (binding) {
|
|
2804
|
+
const lastSeq = BigInt(binding.lastEventSeq);
|
|
2805
|
+
const addedEvents = card.events.filter((e) => !triggerEventIds.has(e.id) && BigInt(e.serverSeq) > lastSeq);
|
|
2806
|
+
return [
|
|
2807
|
+
...commonHeader,
|
|
2808
|
+
"\u8FD9\u662F\u540C\u4E00\u5F20\u5361\u7247\u7684\u7EE7\u7EED\uFF1B\u5982\u8BB0\u5FC6\u4E0E\u5F53\u524D\u5361\u7247\u6B63\u6587/\u72B6\u6001\u4E0D\u4E00\u81F4\uFF0C\u4EE5\u4EE5\u4E0B\u6700\u65B0\u5361\u7247\u6570\u636E\u4E3A\u51C6\u3002",
|
|
2809
|
+
triggerLine,
|
|
2810
|
+
`\u5361\u7247\u6700\u65B0\u5185\u5BB9\uFF1A${JSON.stringify({
|
|
2811
|
+
id: card.id,
|
|
2812
|
+
title: card.title,
|
|
2813
|
+
status: card.status,
|
|
2814
|
+
priority: card.priority,
|
|
2815
|
+
tags: card.tags,
|
|
2816
|
+
body: card.body,
|
|
2817
|
+
checklist: card.checklist,
|
|
2818
|
+
outputs: card.outputs,
|
|
2819
|
+
attachments: card.attachments ?? [],
|
|
2820
|
+
version: card.version
|
|
2821
|
+
})}`,
|
|
2822
|
+
`\u81EA\u4E0A\u6B21\u4EE5\u6765\u7684\u65B0\u589E\u6D3B\u52A8\uFF1A${JSON.stringify(addedEvents)}`
|
|
2823
|
+
].join("\n");
|
|
2824
|
+
}
|
|
2825
|
+
const { revisions: _omittedRevisions, events: allEvents, ...cardWithoutRevisions } = card;
|
|
2826
|
+
const maxInitialEvents = 30;
|
|
2827
|
+
let visibleEvents = allEvents;
|
|
2828
|
+
let eventsTruncated = Boolean(card.eventsTruncated);
|
|
2829
|
+
if (allEvents.length > maxInitialEvents) {
|
|
2830
|
+
const tail = allEvents.slice(-maxInitialEvents);
|
|
2831
|
+
const tailIds = new Set(tail.map((e) => e.id));
|
|
2832
|
+
const missingTriggers = allEvents.filter((e) => triggerEventIds.has(e.id) && !tailIds.has(e.id));
|
|
2833
|
+
visibleEvents = [...missingTriggers, ...tail];
|
|
2834
|
+
eventsTruncated = true;
|
|
2835
|
+
}
|
|
2836
|
+
const initialCardSnapshot = {
|
|
2837
|
+
...cardWithoutRevisions,
|
|
2838
|
+
events: visibleEvents,
|
|
2839
|
+
revisionsOmitted: true,
|
|
2840
|
+
...eventsTruncated ? { eventsTruncated: true, totalEventCount: card.totalEventCount ?? allEvents.length } : {}
|
|
2841
|
+
};
|
|
2842
|
+
return [
|
|
2843
|
+
...commonHeader,
|
|
2844
|
+
"\u8BF4\u660E\uFF1A\u4EE5\u4E0B\u5361\u7247\u5FEB\u7167\u9ED8\u8BA4\u4E0D\u542B\u5386\u53F2\u5BA1\u8BA1 revisions\uFF0C\u82E5\u9700\u66F4\u65E9\u4E8B\u4EF6\u65F6\u95F4\u7EBF\u8BF7\u4F7F\u7528 `slate events` \u5206\u9875\u62C9\u53D6\u3002",
|
|
2845
|
+
`\u5F53\u524D\u5B8C\u6574\u5361\u7247\u6570\u636E\uFF08JSON\uFF09\uFF1A${JSON.stringify(initialCardSnapshot)}`,
|
|
2846
|
+
triggerLine
|
|
2847
|
+
].join("\n");
|
|
2848
|
+
}
|
|
2849
|
+
var AgentLoop = class {
|
|
2850
|
+
constructor(api, driver, options) {
|
|
2851
|
+
this.api = api;
|
|
2852
|
+
this.driver = driver;
|
|
2853
|
+
this.options = options;
|
|
2854
|
+
this.maxConcurrency = parseMaxConcurrency(options.maxConcurrency);
|
|
2855
|
+
this.sessions = new CardSessions(options.sessionsFile);
|
|
2856
|
+
}
|
|
2857
|
+
api;
|
|
2858
|
+
driver;
|
|
2859
|
+
options;
|
|
2860
|
+
state;
|
|
2861
|
+
onIdle;
|
|
2862
|
+
loginBlocked = false;
|
|
2863
|
+
get busy() {
|
|
2864
|
+
return this.active.size > 0;
|
|
2865
|
+
}
|
|
2866
|
+
get activeCount() {
|
|
2867
|
+
return this.active.size;
|
|
2868
|
+
}
|
|
2869
|
+
maxConcurrency;
|
|
2870
|
+
active = /* @__PURE__ */ new Map();
|
|
2871
|
+
activeWorkDirs = /* @__PURE__ */ new Set();
|
|
2872
|
+
deferredWorkDirs = /* @__PURE__ */ new Map();
|
|
2873
|
+
stopped = false;
|
|
2874
|
+
saves = Promise.resolve();
|
|
2875
|
+
sessions;
|
|
2876
|
+
log(msg) {
|
|
2877
|
+
this.options.log?.(`[${this.options.agentName}] ${msg}`);
|
|
2878
|
+
}
|
|
2879
|
+
async save() {
|
|
2880
|
+
const snapshot = structuredClone(this.state);
|
|
2881
|
+
this.saves = this.saves.catch(() => {
|
|
2882
|
+
}).then(() => atomicJson(this.options.cursorFile, snapshot));
|
|
2883
|
+
await this.saves;
|
|
2884
|
+
}
|
|
2885
|
+
async init() {
|
|
2886
|
+
await this.sessions.init();
|
|
2887
|
+
try {
|
|
2888
|
+
const parsed = JSON.parse(await readFile4(this.options.cursorFile, "utf8"));
|
|
2889
|
+
if (parsed.version !== 2 || parsed.agentId !== this.options.agentId || !/^\d+$/.test(parsed.cursor) || !Array.isArray(parsed.jobs)) {
|
|
2890
|
+
throw new Error("reset");
|
|
2891
|
+
}
|
|
2892
|
+
this.state = parsed;
|
|
2893
|
+
for (const job of this.state.jobs) {
|
|
2894
|
+
if (job.phase === "running") job.phase = "recover";
|
|
2895
|
+
}
|
|
2896
|
+
} catch {
|
|
2897
|
+
this.state = { version: 2, agentId: this.options.agentId, cursor: "0", jobs: [] };
|
|
2898
|
+
if (!this.options.cardId) {
|
|
2899
|
+
let more = true;
|
|
2900
|
+
while (more) {
|
|
2901
|
+
const page = await this.api.events(this.state.cursor);
|
|
2902
|
+
this.state.cursor = page.nextCursor;
|
|
2903
|
+
more = page.hasMore;
|
|
2904
|
+
}
|
|
2905
|
+
this.log(`\u9996\u6B21\u542F\u52A8\uFF0C\u4ECE\u5F53\u524D\u4E8B\u4EF6\u6E38\u6807 ${this.state.cursor} \u5F00\u59CB\u76D1\u542C`);
|
|
2906
|
+
}
|
|
2907
|
+
}
|
|
2908
|
+
await this.save();
|
|
2909
|
+
}
|
|
2910
|
+
abortCard(cardId, upToSeq) {
|
|
2911
|
+
let cancelledQueued = 0;
|
|
2912
|
+
for (const job of this.state.jobs) {
|
|
2913
|
+
if (job.phase !== "queued" || job.event.cardId !== cardId) continue;
|
|
2914
|
+
if (upToSeq !== void 0 && BigInt(job.event.serverSeq) > BigInt(upToSeq)) continue;
|
|
2915
|
+
job.phase = "done";
|
|
2916
|
+
cancelledQueued += 1;
|
|
2917
|
+
}
|
|
2918
|
+
const hasRemainingQueued = this.state.jobs.some((j) => j.phase === "queued" && j.event.cardId === cardId);
|
|
2919
|
+
if (!hasRemainingQueued) {
|
|
2920
|
+
this.deferredWorkDirs.delete(cardId);
|
|
2921
|
+
}
|
|
2922
|
+
if (cancelledQueued > 0) {
|
|
2923
|
+
this.log(`\u6536\u5230\u505C\u6B62\u6307\u4EE4\uFF0C\u53D6\u6D88\u5361\u7247 ${cardId.slice(0, 8)} \u7684 ${cancelledQueued} \u6761\u6392\u961F\u4E8B\u4EF6`);
|
|
2924
|
+
}
|
|
2925
|
+
const activeRun = this.active.get(cardId);
|
|
2926
|
+
if (activeRun) {
|
|
2927
|
+
this.log(`\u6536\u5230\u505C\u6B62\u6307\u4EE4\uFF0C\u4E2D\u6B62\u5361\u7247 ${cardId.slice(0, 8)} \u7684\u6267\u884C`);
|
|
2928
|
+
activeRun.controller.abort();
|
|
2929
|
+
}
|
|
2930
|
+
}
|
|
2931
|
+
releaseWorkDir(workDirKey) {
|
|
2932
|
+
this.activeWorkDirs.delete(workDirKey);
|
|
2933
|
+
for (const [cardId, blockedDir] of this.deferredWorkDirs) {
|
|
2934
|
+
if (blockedDir === workDirKey) {
|
|
2935
|
+
this.deferredWorkDirs.delete(cardId);
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
findNextRunnableJob() {
|
|
2940
|
+
for (const job of this.state.jobs) {
|
|
2941
|
+
if (job.phase !== "queued" && job.phase !== "recover") continue;
|
|
2942
|
+
const cardId = job.event.cardId;
|
|
2943
|
+
if (this.active.has(cardId)) continue;
|
|
2944
|
+
const blockedDir = this.deferredWorkDirs.get(cardId);
|
|
2945
|
+
if (blockedDir) {
|
|
2946
|
+
if (this.activeWorkDirs.has(blockedDir)) continue;
|
|
2947
|
+
this.deferredWorkDirs.delete(cardId);
|
|
2948
|
+
}
|
|
2949
|
+
return job;
|
|
2950
|
+
}
|
|
2951
|
+
return void 0;
|
|
2952
|
+
}
|
|
2953
|
+
dispatch() {
|
|
2954
|
+
while (this.active.size < this.maxConcurrency && !this.stopped && !this.loginBlocked) {
|
|
2955
|
+
const nextJob = this.findNextRunnableJob();
|
|
2956
|
+
if (!nextJob) break;
|
|
2957
|
+
const cardId = nextJob.event.cardId;
|
|
2958
|
+
const batch = nextJob.phase === "queued" ? this.state.jobs.filter((j) => j.phase === "queued" && j.event.cardId === cardId) : [nextJob];
|
|
2959
|
+
const run = {
|
|
2960
|
+
cardId,
|
|
2961
|
+
jobs: batch,
|
|
2962
|
+
controller: new AbortController(),
|
|
2963
|
+
promise: Promise.resolve()
|
|
2964
|
+
};
|
|
2965
|
+
this.active.set(cardId, run);
|
|
2966
|
+
run.promise = this.runCard(run);
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
async runCard(run) {
|
|
2970
|
+
let deferred = false;
|
|
2971
|
+
try {
|
|
2972
|
+
const outcome = await this.handle(run, run.controller.signal);
|
|
2973
|
+
deferred = outcome === "deferred";
|
|
2974
|
+
} catch (err) {
|
|
2975
|
+
this.log(`\u5904\u7406\u5F02\u5E38\uFF1A${err instanceof Error ? err.message : String(err)}`);
|
|
2976
|
+
for (const j of run.jobs) j.phase = "done";
|
|
2977
|
+
run.jobs.at(-1).phase = "recover";
|
|
2978
|
+
await this.save().catch(() => {
|
|
2979
|
+
});
|
|
2980
|
+
} finally {
|
|
2981
|
+
this.active.delete(run.cardId);
|
|
2982
|
+
if (run.workDir) {
|
|
2983
|
+
this.releaseWorkDir(run.workDir);
|
|
2984
|
+
}
|
|
2985
|
+
if (deferred) {
|
|
2986
|
+
this.dispatch();
|
|
2987
|
+
} else {
|
|
2988
|
+
this.onIdle?.();
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
2992
|
+
async tick() {
|
|
2993
|
+
const page = await this.api.events(this.state.cursor);
|
|
2994
|
+
for (const ev of page.events) {
|
|
2995
|
+
if (this.options.cardId && ev.cardId !== this.options.cardId) continue;
|
|
2996
|
+
if (!isTargetedToAgent(ev, this.options.agentId)) continue;
|
|
2997
|
+
if (ev.type === "agent_stop_requested") {
|
|
2998
|
+
this.abortCard(ev.cardId, ev.serverSeq);
|
|
2999
|
+
continue;
|
|
3000
|
+
}
|
|
3001
|
+
if (!["card_created", "comment", "status_changed"].includes(ev.type)) continue;
|
|
3002
|
+
if (this.state.jobs.some((j) => j.event.id === ev.id)) continue;
|
|
3003
|
+
this.state.jobs.push({ event: ev, phase: "queued" });
|
|
3004
|
+
}
|
|
3005
|
+
this.state.cursor = page.nextCursor;
|
|
3006
|
+
await this.save();
|
|
3007
|
+
this.dispatch();
|
|
3008
|
+
return page.hasMore;
|
|
3009
|
+
}
|
|
3010
|
+
async handle(run, signal) {
|
|
3011
|
+
const jobs = run.jobs;
|
|
3012
|
+
const firstJob = jobs[0];
|
|
3013
|
+
const card = await this.api.card(firstJob.event.cardId, { includeRevisions: false });
|
|
3014
|
+
if (firstJob.phase === "recover") {
|
|
3015
|
+
await this.api.comment(
|
|
3016
|
+
card.id,
|
|
3017
|
+
`\u68C0\u6D4B\u5230\u4E0A\u6B21\u6267\u884C\u610F\u5916\u4E2D\u65AD\uFF0C\u5DF2\u4FDD\u7559\u5DE5\u4F5C\u76EE\u5F55\u6587\u4EF6\uFF0C\u672A\u81EA\u52A8\u91CD\u8DD1\u3002\u5982\u9700\u7EE7\u7EED\u8BF7\u76F4\u63A5 @${this.options.agentName}\u3002`,
|
|
3018
|
+
firstJob.event.id
|
|
3019
|
+
);
|
|
3020
|
+
firstJob.phase = "done";
|
|
3021
|
+
await this.save();
|
|
3022
|
+
return "completed";
|
|
3023
|
+
}
|
|
3024
|
+
const binding = this.sessions.get(card.id);
|
|
3025
|
+
const pendingJobs = [];
|
|
3026
|
+
for (const j of jobs) {
|
|
3027
|
+
if (binding && BigInt(j.event.serverSeq) <= BigInt(binding.lastEventSeq)) {
|
|
3028
|
+
j.phase = "done";
|
|
3029
|
+
} else {
|
|
3030
|
+
pendingJobs.push(j);
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
if (pendingJobs.length === 0) {
|
|
3034
|
+
await this.save();
|
|
3035
|
+
return "completed";
|
|
3036
|
+
}
|
|
3037
|
+
const latestJob = pendingJobs.at(-1);
|
|
3038
|
+
const coalescedEvents = pendingJobs.map((j) => j.event);
|
|
3039
|
+
const coalescedEventIds = new Set(coalescedEvents.map((e) => e.id));
|
|
3040
|
+
const project = await this.api.project(card.projectId);
|
|
3041
|
+
const preparer = this.options.workspacePreparer ?? prepareCardWorkspace;
|
|
3042
|
+
const workspace = await preparer({
|
|
3043
|
+
project,
|
|
3044
|
+
cardId: card.id,
|
|
3045
|
+
agentId: this.options.agentId,
|
|
3046
|
+
driver: this.driver.type,
|
|
3047
|
+
credentialFile: this.options.credentialFile,
|
|
3048
|
+
runId: latestJob.event.id
|
|
3049
|
+
});
|
|
3050
|
+
if (signal.aborted) {
|
|
3051
|
+
if (!this.stopped) {
|
|
3052
|
+
for (const j of pendingJobs) j.phase = "done";
|
|
3053
|
+
await this.save();
|
|
3054
|
+
await this.api.comment(card.id, `\u5DF2\u505C\u6B62\u672C\u8F6E\u6267\u884C\uFF08\u5DE5\u4F5C\u76EE\u5F55\u4FDD\u7559\uFF1A${workspace.workDir}\uFF09\u3002`, latestJob.event.id);
|
|
3055
|
+
}
|
|
3056
|
+
return "completed";
|
|
3057
|
+
}
|
|
3058
|
+
const workDirKey = path9.resolve(workspace.workDir);
|
|
3059
|
+
if (this.activeWorkDirs.has(workDirKey)) {
|
|
3060
|
+
this.deferredWorkDirs.set(card.id, workDirKey);
|
|
3061
|
+
this.log(`\u5DE5\u4F5C\u76EE\u5F55 ${workspace.workDir} \u6B63\u88AB\u5176\u4ED6\u5361\u7247\u5360\u7528\uFF0C\u5361\u7247 ${card.id.slice(0, 8)} \u6682\u7F13\u6392\u961F`);
|
|
3062
|
+
return "deferred";
|
|
3063
|
+
}
|
|
3064
|
+
this.deferredWorkDirs.delete(card.id);
|
|
3065
|
+
this.activeWorkDirs.add(workDirKey);
|
|
3066
|
+
run.workDir = workDirKey;
|
|
3067
|
+
if (pendingJobs.length > 1) {
|
|
3068
|
+
this.log(`\u5408\u5E76\u5361\u7247 ${card.id.slice(0, 8)} \u7684 ${pendingJobs.length} \u6761\u8FDE\u7EED\u6392\u961F\u4E8B\u4EF6\u4E3A 1 \u8F6E\u6267\u884C`);
|
|
3069
|
+
}
|
|
3070
|
+
for (const j of pendingJobs) j.phase = "running";
|
|
3071
|
+
await this.save();
|
|
3072
|
+
const existingWorktree = findExistingParticipantWorktree(card.participants, workspace, {
|
|
3073
|
+
agentId: this.options.agentId,
|
|
3074
|
+
agentName: this.options.agentName
|
|
3075
|
+
});
|
|
3076
|
+
const reportedWorkDir = existingWorktree?.workDir ?? workspace.workDir;
|
|
3077
|
+
const reportedBranch = workspace.branch ?? existingWorktree?.branch ?? void 0;
|
|
3078
|
+
const runId = randomUUID2();
|
|
3079
|
+
let latestActivity = "\u6B63\u5728\u9605\u8BFB\u5361\u7247\u5E76\u51C6\u5907\u6267\u884C\u2026";
|
|
3080
|
+
let lastPush = 0;
|
|
3081
|
+
const pushActivity = (text, force = false) => {
|
|
3082
|
+
latestActivity = text.slice(0, 280);
|
|
3083
|
+
const now = Date.now();
|
|
3084
|
+
if (!force && now - lastPush < 3e3) return;
|
|
3085
|
+
lastPush = now;
|
|
3086
|
+
void this.api.processing(card.id, {
|
|
3087
|
+
runId,
|
|
3088
|
+
eventId: latestJob.event.id,
|
|
3089
|
+
activityText: latestActivity
|
|
3090
|
+
}).catch(() => {
|
|
3091
|
+
});
|
|
3092
|
+
};
|
|
3093
|
+
const pendingSteps = [];
|
|
3094
|
+
let lastStepSignature = "";
|
|
3095
|
+
let stepFlushTimer;
|
|
3096
|
+
let stepFlushes = Promise.resolve();
|
|
3097
|
+
const flushSteps = () => {
|
|
3098
|
+
if (stepFlushTimer) {
|
|
3099
|
+
clearTimeout(stepFlushTimer);
|
|
3100
|
+
stepFlushTimer = void 0;
|
|
3101
|
+
}
|
|
3102
|
+
if (!this.api.appendRunSteps || pendingSteps.length === 0) return stepFlushes;
|
|
3103
|
+
const chunks = [];
|
|
3104
|
+
while (pendingSteps.length > 0) {
|
|
3105
|
+
chunks.push(pendingSteps.splice(0, CARD_RUN_STEP_BATCH_MAX));
|
|
3106
|
+
}
|
|
3107
|
+
const append = this.api.appendRunSteps.bind(this.api);
|
|
3108
|
+
for (const steps of chunks) {
|
|
3109
|
+
stepFlushes = stepFlushes.catch(() => {
|
|
3110
|
+
}).then(() => append(card.id, { runId, eventId: latestJob.event.id, steps }).then(() => void 0));
|
|
3111
|
+
}
|
|
3112
|
+
return stepFlushes;
|
|
3113
|
+
};
|
|
3114
|
+
const pushStep = (step) => {
|
|
3115
|
+
if (!this.api.appendRunSteps) return;
|
|
3116
|
+
const title = step.title.trim().slice(0, 200);
|
|
3117
|
+
if (!title) return;
|
|
3118
|
+
const detail = step.detail?.trim().slice(0, 400);
|
|
3119
|
+
const sig = `${step.kind}|${title}|${detail ?? ""}`;
|
|
3120
|
+
if (sig === lastStepSignature) return;
|
|
3121
|
+
lastStepSignature = sig;
|
|
3122
|
+
pendingSteps.push({
|
|
3123
|
+
kind: step.kind,
|
|
3124
|
+
title,
|
|
3125
|
+
...detail ? { detail } : {},
|
|
3126
|
+
at: step.at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
3127
|
+
});
|
|
3128
|
+
if (pendingSteps.length >= 8) {
|
|
3129
|
+
void flushSteps();
|
|
3130
|
+
} else if (!stepFlushTimer) {
|
|
3131
|
+
stepFlushTimer = setTimeout(() => {
|
|
3132
|
+
void flushSteps();
|
|
3133
|
+
}, 500);
|
|
3134
|
+
}
|
|
3135
|
+
};
|
|
3136
|
+
let timer;
|
|
3137
|
+
let clearPayload = {
|
|
3138
|
+
runId,
|
|
3139
|
+
eventId: latestJob.event.id,
|
|
3140
|
+
outcome: "failed",
|
|
3141
|
+
summary: "\u6267\u884C\u8FC7\u7A0B\u53D1\u751F\u5F02\u5E38"
|
|
3142
|
+
};
|
|
3143
|
+
try {
|
|
3144
|
+
await this.api.processing(card.id, {
|
|
3145
|
+
runId,
|
|
3146
|
+
eventId: latestJob.event.id,
|
|
3147
|
+
activityText: latestActivity,
|
|
3148
|
+
workDir: reportedWorkDir,
|
|
3149
|
+
...reportedBranch ? { branch: reportedBranch } : {}
|
|
3150
|
+
});
|
|
3151
|
+
timer = setInterval(() => pushActivity(latestActivity, true), 3e4);
|
|
3152
|
+
const onSessionStarted = (sessionId) => this.sessions.set(card.id, {
|
|
3153
|
+
sessionId,
|
|
3154
|
+
lastEventId: latestJob.event.id,
|
|
3155
|
+
lastEventSeq: latestJob.event.serverSeq,
|
|
3156
|
+
workDir: workspace.workDir,
|
|
3157
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3158
|
+
});
|
|
3159
|
+
const reusableBinding = binding && binding.workDir === workspace.workDir ? binding : void 0;
|
|
3160
|
+
if (binding && !reusableBinding) {
|
|
3161
|
+
this.log(
|
|
3162
|
+
`\u5DE5\u4F5C\u76EE\u5F55\u5DF2\u53D8\u66F4\uFF08${binding.workDir ?? "\u672A\u8BB0\u5F55"} -> ${workspace.workDir}\uFF09\uFF0C\u653E\u5F03\u65E7\u4F1A\u8BDD\u5E76\u6539\u7528\u5B8C\u6574\u5361\u7247\u4E0A\u4E0B\u6587\u65B0\u5EFA\u4F1A\u8BDD`
|
|
3163
|
+
);
|
|
3164
|
+
}
|
|
3165
|
+
pushStep({
|
|
3166
|
+
kind: "status",
|
|
3167
|
+
title: reusableBinding ? "\u7EED\u8DD1\u5361\u7247\u4F1A\u8BDD" : "\u5F00\u59CB\u6267\u884C\u672C\u8F6E\u4EFB\u52A1",
|
|
3168
|
+
detail: reportedBranch ? `${reportedBranch} \xB7 ${reportedWorkDir}` : reportedWorkDir
|
|
3169
|
+
});
|
|
3170
|
+
const eventAttachments = resolveEventsAttachments(card, coalescedEvents);
|
|
3171
|
+
const runOnce = (prev) => {
|
|
3172
|
+
const addedEventAttachments = prev ? card.events.filter((e) => !coalescedEventIds.has(e.id) && BigInt(e.serverSeq) > BigInt(prev.lastEventSeq)).flatMap((e) => e.attachments ?? []) : [];
|
|
3173
|
+
const imagePaths = prev ? collectImagePaths([...addedEventAttachments, ...eventAttachments]) : collectImagePaths([...card.attachments ?? [], ...eventAttachments]);
|
|
3174
|
+
return this.driver.run({
|
|
3175
|
+
prompt: buildPrompt({
|
|
3176
|
+
agentName: this.options.agentName,
|
|
3177
|
+
driver: this.driver.type,
|
|
3178
|
+
card,
|
|
3179
|
+
event: latestJob.event,
|
|
3180
|
+
coalescedEvents,
|
|
3181
|
+
workspace,
|
|
3182
|
+
binding: prev,
|
|
3183
|
+
project,
|
|
3184
|
+
agentId: this.options.agentId
|
|
3185
|
+
}),
|
|
3186
|
+
workDir: workspace.workDir,
|
|
3187
|
+
binDir: workspace.binDir,
|
|
3188
|
+
signal,
|
|
3189
|
+
recordFile: `${this.options.recordsDir}/${this.options.agentId}-${latestJob.event.id}.json`,
|
|
3190
|
+
sessionId: prev?.sessionId,
|
|
3191
|
+
...imagePaths.length > 0 ? { imagePaths } : {},
|
|
3192
|
+
skipPermissions: true,
|
|
3193
|
+
onSessionStarted,
|
|
3194
|
+
onActivity: (text) => pushActivity(text),
|
|
3195
|
+
onStep: (step) => pushStep(step)
|
|
3196
|
+
});
|
|
3197
|
+
};
|
|
3198
|
+
let result = await runOnce(reusableBinding);
|
|
3199
|
+
if (reusableBinding && result.resumeUnavailable && !signal.aborted) {
|
|
3200
|
+
this.log("\u65E0\u6CD5\u6062\u590D\u65E7\u4F1A\u8BDD\uFF0C\u6539\u7528\u5B8C\u6574\u5361\u7247\u4E0A\u4E0B\u6587\u65B0\u5EFA\u4F1A\u8BDD");
|
|
3201
|
+
pushStep({ kind: "status", title: "\u65E7\u4F1A\u8BDD\u4E0D\u53EF\u6062\u590D\uFF0C\u6539\u7528\u5B8C\u6574\u5361\u7247\u4E0A\u4E0B\u6587\u65B0\u5EFA\u4F1A\u8BDD" });
|
|
3202
|
+
result = await runOnce(void 0);
|
|
3203
|
+
}
|
|
3204
|
+
this.log(`\u5B8C\u6210\u6267\u884C card=${card.id.slice(0, 8)} exit=${result.outerExit} completed=${result.completed}`);
|
|
3205
|
+
if (result.authFailure) {
|
|
3206
|
+
this.options.onAuthChanged?.();
|
|
3207
|
+
}
|
|
3208
|
+
if (this.stopped && result.aborted) {
|
|
3209
|
+
clearPayload = {
|
|
3210
|
+
runId,
|
|
3211
|
+
eventId: latestJob.event.id,
|
|
3212
|
+
outcome: "stopped",
|
|
3213
|
+
summary: "\u63A5\u5165\u8FDB\u7A0B\u9000\u51FA\uFF0C\u672C\u8F6E\u6267\u884C\u5DF2\u4E2D\u65AD"
|
|
3214
|
+
};
|
|
3215
|
+
for (const j of pendingJobs) j.phase = "done";
|
|
3216
|
+
latestJob.phase = "recover";
|
|
3217
|
+
await this.save();
|
|
3218
|
+
return "completed";
|
|
3219
|
+
}
|
|
3220
|
+
if (result.aborted) {
|
|
3221
|
+
clearPayload = { runId, eventId: latestJob.event.id, outcome: "stopped", summary: "\u5DF2\u505C\u6B62\u672C\u8F6E\u6267\u884C" };
|
|
3222
|
+
await this.api.comment(card.id, `\u5DF2\u505C\u6B62\u672C\u8F6E\u6267\u884C\uFF08\u5DE5\u4F5C\u76EE\u5F55\u4FDD\u7559\uFF1A${workspace.workDir}\uFF09\u3002`, latestJob.event.id);
|
|
3223
|
+
} else if (result.authFailure) {
|
|
3224
|
+
const msg = (result.authFailure.loginMessage ?? "\u4EE4\u724C\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u5728\u672C\u673A\u91CD\u65B0\u767B\u5F55").slice(0, 280);
|
|
3225
|
+
clearPayload = { runId, eventId: latestJob.event.id, outcome: "failed", summary: msg };
|
|
3226
|
+
await this.api.comment(
|
|
3227
|
+
card.id,
|
|
3228
|
+
`\u767B\u5F55\u72B6\u6001\u5DF2\u5931\u6548\uFF1A${result.authFailure.loginMessage ?? "\u4EE4\u724C\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u5728\u672C\u673A\u91CD\u65B0\u767B\u5F55"}\u3002\u5B8C\u6210\u540E\u53EF\u518D\u6B21 @${this.options.agentName} \u7EE7\u7EED\u3002`,
|
|
3229
|
+
latestJob.event.id
|
|
3230
|
+
);
|
|
3231
|
+
} else if (result.outerExit !== 0 || !result.completed) {
|
|
3232
|
+
const reason = (result.errorMessage ?? `\u9000\u51FA\u7801 ${result.outerExit ?? "signal"}`).slice(0, 280);
|
|
3233
|
+
clearPayload = { runId, eventId: latestJob.event.id, outcome: "failed", summary: reason };
|
|
3234
|
+
await this.api.comment(
|
|
3235
|
+
card.id,
|
|
3236
|
+
`\u672C\u8F6E CLI \u6267\u884C\u672A\u6B63\u5E38\u5B8C\u6210\uFF08${result.errorMessage ?? `\u9000\u51FA\u7801 ${result.outerExit ?? "signal"}`}\uFF09\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u73AF\u5883\u540E\u91CD\u8BD5\u3002`,
|
|
3237
|
+
latestJob.event.id
|
|
3238
|
+
);
|
|
3239
|
+
} else {
|
|
3240
|
+
clearPayload = { runId, eventId: latestJob.event.id, outcome: "completed" };
|
|
3241
|
+
}
|
|
3242
|
+
for (const j of pendingJobs) j.phase = "done";
|
|
3243
|
+
await this.save();
|
|
3244
|
+
return "completed";
|
|
3245
|
+
} finally {
|
|
3246
|
+
if (timer) clearInterval(timer);
|
|
3247
|
+
await flushSteps().catch(() => {
|
|
3248
|
+
});
|
|
3249
|
+
await this.api.processingClear(card.id, clearPayload).catch(() => {
|
|
3250
|
+
});
|
|
3251
|
+
}
|
|
3252
|
+
}
|
|
3253
|
+
async stop() {
|
|
3254
|
+
this.stopped = true;
|
|
3255
|
+
const running = [...this.active.values()];
|
|
3256
|
+
for (const run of running) {
|
|
3257
|
+
run.controller.abort();
|
|
3258
|
+
}
|
|
3259
|
+
await Promise.allSettled(running.map((run) => run.promise));
|
|
3260
|
+
await this.save();
|
|
3261
|
+
}
|
|
3262
|
+
};
|
|
3263
|
+
|
|
3264
|
+
// src/presence.ts
|
|
3265
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
3266
|
+
import { hostname } from "os";
|
|
3267
|
+
function delay(ms, signal) {
|
|
3268
|
+
return new Promise((resolve) => {
|
|
3269
|
+
const done = () => {
|
|
3270
|
+
clearTimeout(t);
|
|
3271
|
+
signal.removeEventListener("abort", done);
|
|
3272
|
+
resolve();
|
|
3273
|
+
};
|
|
3274
|
+
const t = setTimeout(done, ms);
|
|
3275
|
+
signal.addEventListener("abort", done, { once: true });
|
|
3276
|
+
if (signal.aborted) done();
|
|
3277
|
+
});
|
|
3278
|
+
}
|
|
3279
|
+
var AgentPresenceReporter = class {
|
|
3280
|
+
constructor(api, driver, loop, log = () => {
|
|
3281
|
+
}) {
|
|
3282
|
+
this.api = api;
|
|
3283
|
+
this.driver = driver;
|
|
3284
|
+
this.loop = loop;
|
|
3285
|
+
this.log = log;
|
|
3286
|
+
}
|
|
3287
|
+
api;
|
|
3288
|
+
driver;
|
|
3289
|
+
loop;
|
|
3290
|
+
log;
|
|
3291
|
+
adapterInstanceId = randomUUID3();
|
|
3292
|
+
hostLabel = hostname();
|
|
3293
|
+
sseConnected = false;
|
|
3294
|
+
stopping = new AbortController();
|
|
3295
|
+
timer;
|
|
3296
|
+
reporting;
|
|
3297
|
+
activeLogin;
|
|
3298
|
+
handled = /* @__PURE__ */ new Set();
|
|
3299
|
+
dirty = false;
|
|
3300
|
+
async start() {
|
|
3301
|
+
this.timer = setInterval(() => {
|
|
3302
|
+
void this.report();
|
|
3303
|
+
}, 1e4);
|
|
3304
|
+
await this.report();
|
|
3305
|
+
}
|
|
3306
|
+
connectionChanged = (sseConnected) => {
|
|
3307
|
+
this.sseConnected = sseConnected;
|
|
3308
|
+
void this.report();
|
|
3309
|
+
};
|
|
3310
|
+
command = () => {
|
|
3311
|
+
void this.report();
|
|
3312
|
+
};
|
|
3313
|
+
report() {
|
|
3314
|
+
if (this.stopping.signal.aborted) return Promise.resolve();
|
|
3315
|
+
this.dirty = true;
|
|
3316
|
+
if (this.reporting) return this.reporting;
|
|
3317
|
+
this.reporting = (async () => {
|
|
3318
|
+
while (this.dirty && !this.stopping.signal.aborted) {
|
|
3319
|
+
this.dirty = false;
|
|
3320
|
+
try {
|
|
3321
|
+
const auth = await this.driver.checkAuth(this.stopping.signal);
|
|
3322
|
+
if (this.stopping.signal.aborted) break;
|
|
3323
|
+
const ack = await this.api.presence({
|
|
3324
|
+
adapterInstanceId: this.adapterInstanceId,
|
|
3325
|
+
hostLabel: this.hostLabel,
|
|
3326
|
+
sseConnected: this.sseConnected,
|
|
3327
|
+
lastEventCursor: this.loop.state.cursor,
|
|
3328
|
+
driver: this.driver.type,
|
|
3329
|
+
authMode: this.driver.authMode,
|
|
3330
|
+
loginState: auth.loginState,
|
|
3331
|
+
...auth.loginMessage ? { loginMessage: auth.loginMessage } : {}
|
|
3332
|
+
});
|
|
3333
|
+
if (!this.stopping.signal.aborted) this.acceptLogin(ack.pendingLoginRequest);
|
|
3334
|
+
} catch {
|
|
3335
|
+
if (!this.stopping.signal.aborted) this.log("\u5FC3\u8DF3\u4E0A\u62A5\u6682\u4E0D\u53EF\u7528\uFF0C\u4E0B\u4E00\u5468\u671F\u91CD\u8BD5");
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
3338
|
+
})().finally(() => {
|
|
3339
|
+
this.reporting = void 0;
|
|
3340
|
+
});
|
|
3341
|
+
return this.reporting;
|
|
3342
|
+
}
|
|
3343
|
+
acceptLogin(req) {
|
|
3344
|
+
if (this.activeLogin && (!req || req.id !== this.activeLogin.id || !["pending", "starting", "waiting_user"].includes(req.status))) {
|
|
3345
|
+
this.activeLogin.controller.abort();
|
|
3346
|
+
}
|
|
3347
|
+
if (req?.status !== "pending" || this.activeLogin || this.handled.has(req.id)) return;
|
|
3348
|
+
if (!this.driver.startDeviceLogin || !this.driver.parseDeviceOutput) return;
|
|
3349
|
+
const controller = new AbortController();
|
|
3350
|
+
this.handled.add(req.id);
|
|
3351
|
+
this.loop.loginBlocked = true;
|
|
3352
|
+
const done = this.runDeviceLogin(req, AbortSignal.any([controller.signal, this.stopping.signal])).catch(() => {
|
|
3353
|
+
if (!this.stopping.signal.aborted) this.log("\u8BBE\u5907\u767B\u5F55\u672A\u5B8C\u6210");
|
|
3354
|
+
}).finally(() => {
|
|
3355
|
+
this.activeLogin = void 0;
|
|
3356
|
+
this.loop.loginBlocked = false;
|
|
3357
|
+
if (!this.stopping.signal.aborted) {
|
|
3358
|
+
this.loop.onIdle?.();
|
|
3359
|
+
void this.report();
|
|
3360
|
+
}
|
|
3361
|
+
});
|
|
3362
|
+
this.activeLogin = { id: req.id, controller, done };
|
|
3363
|
+
}
|
|
3364
|
+
async runDeviceLogin(req, signal) {
|
|
3365
|
+
const timeout = new AbortController();
|
|
3366
|
+
const progressError = new AbortController();
|
|
3367
|
+
const parsedExpires = new Date(req.expiresAt).getTime();
|
|
3368
|
+
const deadline = Number.isFinite(parsedExpires) ? Math.min(Date.now() + 16 * 6e4, parsedExpires) : Date.now() + 16 * 6e4;
|
|
3369
|
+
const timer = setTimeout(() => timeout.abort(), Math.max(0, deadline - Date.now()));
|
|
3370
|
+
const stopped = AbortSignal.any([signal, timeout.signal, progressError.signal]);
|
|
3371
|
+
const progress = (body) => this.api.loginProgress(req.id, body);
|
|
3372
|
+
let output = "";
|
|
3373
|
+
let waiting;
|
|
3374
|
+
let waitingReported = false;
|
|
3375
|
+
try {
|
|
3376
|
+
await progress({
|
|
3377
|
+
status: "starting",
|
|
3378
|
+
message: this.loop.busy ? "\u7B49\u5F85\u5F53\u524D\u4EFB\u52A1\u7ED3\u675F\u540E\u542F\u52A8\u767B\u5F55" : "\u6B63\u5728\u672C\u673A\u542F\u52A8\u8BBE\u5907\u6388\u6743\u767B\u5F55"
|
|
3379
|
+
});
|
|
3380
|
+
while (this.loop.busy && !stopped.aborted) await delay(250, stopped);
|
|
3381
|
+
if (stopped.aborted) {
|
|
3382
|
+
if (timeout.signal.aborted && !signal.aborted) {
|
|
3383
|
+
await progress({
|
|
3384
|
+
status: "expired",
|
|
3385
|
+
message: "\u8BBE\u5907\u767B\u5F55\u5DF2\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5"
|
|
3386
|
+
});
|
|
3387
|
+
}
|
|
3388
|
+
return;
|
|
3389
|
+
}
|
|
3390
|
+
const result = await this.driver.startDeviceLogin(stopped, (chunk) => {
|
|
3391
|
+
if (waiting || stopped.aborted) return;
|
|
3392
|
+
output = (output + chunk).slice(-16384);
|
|
3393
|
+
const parsed = this.driver.parseDeviceOutput(output);
|
|
3394
|
+
if (parsed) {
|
|
3395
|
+
output = "";
|
|
3396
|
+
waiting = progress({
|
|
3397
|
+
status: "waiting_user",
|
|
3398
|
+
...parsed,
|
|
3399
|
+
expiresAt: new Date(Math.min(Date.now() + 15 * 6e4, deadline)).toISOString(),
|
|
3400
|
+
message: "\u8BF7\u5728\u5B98\u65B9\u9875\u9762\u8F93\u5165\u9A8C\u8BC1\u7801\u5B8C\u6210\u767B\u5F55"
|
|
3401
|
+
}).then(() => {
|
|
3402
|
+
waitingReported = true;
|
|
3403
|
+
}).catch(() => {
|
|
3404
|
+
progressError.abort();
|
|
3405
|
+
});
|
|
3406
|
+
}
|
|
3407
|
+
});
|
|
3408
|
+
await waiting;
|
|
3409
|
+
if (signal.aborted) return;
|
|
3410
|
+
if (timeout.signal.aborted) {
|
|
3411
|
+
await progress({
|
|
3412
|
+
status: "expired",
|
|
3413
|
+
message: "\u8BBE\u5907\u767B\u5F55\u5DF2\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5"
|
|
3414
|
+
});
|
|
3415
|
+
return;
|
|
3416
|
+
}
|
|
3417
|
+
if (!waitingReported || result.code !== 0) {
|
|
3418
|
+
await progress({
|
|
3419
|
+
status: "failed",
|
|
3420
|
+
message: "\u8BBE\u5907\u767B\u5F55\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5"
|
|
3421
|
+
});
|
|
3422
|
+
return;
|
|
3423
|
+
}
|
|
3424
|
+
const auth = await this.driver.checkAuth(this.stopping.signal);
|
|
3425
|
+
if (signal.aborted) return;
|
|
3426
|
+
const ok = auth.loginState === "logged_in";
|
|
3427
|
+
await progress({
|
|
3428
|
+
status: ok ? "succeeded" : "failed",
|
|
3429
|
+
message: ok ? "\u672C\u673A\u5DF2\u786E\u8BA4\u767B\u5F55\u6210\u529F" : "\u8BBE\u5907\u767B\u5F55\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u8BD5"
|
|
3430
|
+
});
|
|
3431
|
+
} finally {
|
|
3432
|
+
clearTimeout(timer);
|
|
3433
|
+
}
|
|
3434
|
+
}
|
|
3435
|
+
async stop() {
|
|
3436
|
+
clearInterval(this.timer);
|
|
3437
|
+
this.stopping.abort();
|
|
3438
|
+
this.activeLogin?.controller.abort();
|
|
3439
|
+
await Promise.allSettled([this.reporting, this.activeLogin?.done]);
|
|
3440
|
+
}
|
|
3441
|
+
};
|
|
3442
|
+
|
|
3443
|
+
// src/watch.ts
|
|
3444
|
+
function delay2(ms, signal) {
|
|
3445
|
+
return new Promise((resolve) => {
|
|
3446
|
+
const done = () => {
|
|
3447
|
+
clearTimeout(t);
|
|
3448
|
+
signal.removeEventListener("abort", done);
|
|
3449
|
+
resolve();
|
|
3450
|
+
};
|
|
3451
|
+
const t = setTimeout(done, ms);
|
|
3452
|
+
signal.addEventListener("abort", done, { once: true });
|
|
3453
|
+
if (signal.aborted) done();
|
|
3454
|
+
});
|
|
3455
|
+
}
|
|
3456
|
+
async function watchEvents(loop, openStream, signal, log = () => {
|
|
3457
|
+
}, presence, assistant) {
|
|
3458
|
+
let dirty = false;
|
|
3459
|
+
let draining = false;
|
|
3460
|
+
const drain = async () => {
|
|
3461
|
+
dirty = true;
|
|
3462
|
+
if (draining) return;
|
|
3463
|
+
draining = true;
|
|
3464
|
+
try {
|
|
3465
|
+
while (dirty && !signal.aborted) {
|
|
3466
|
+
dirty = false;
|
|
3467
|
+
let more = true;
|
|
3468
|
+
while (more && !signal.aborted) {
|
|
3469
|
+
more = await loop.tick();
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
} catch {
|
|
3473
|
+
if (!signal.aborted) log("\u62C9\u53D6\u4E8B\u4EF6\u6682\u5931\u8D25\uFF0C\u7A0D\u540E\u91CD\u8BD5");
|
|
3474
|
+
} finally {
|
|
3475
|
+
draining = false;
|
|
3476
|
+
}
|
|
3477
|
+
};
|
|
3478
|
+
loop.onIdle = () => {
|
|
3479
|
+
void drain();
|
|
3480
|
+
};
|
|
3481
|
+
await drain();
|
|
3482
|
+
assistant?.trigger();
|
|
3483
|
+
const fallback = setInterval(() => {
|
|
3484
|
+
void drain();
|
|
3485
|
+
assistant?.trigger();
|
|
3486
|
+
}, 3e4);
|
|
3487
|
+
try {
|
|
3488
|
+
while (!signal.aborted) {
|
|
3489
|
+
const attempt = new AbortController();
|
|
3490
|
+
let staleTimer;
|
|
3491
|
+
const bump = () => {
|
|
3492
|
+
clearTimeout(staleTimer);
|
|
3493
|
+
staleTimer = setTimeout(() => attempt.abort(), 35e3);
|
|
3494
|
+
};
|
|
3495
|
+
const combined = AbortSignal.any([signal, attempt.signal]);
|
|
3496
|
+
bump();
|
|
3497
|
+
try {
|
|
3498
|
+
await openStream(combined, (frame) => {
|
|
3499
|
+
if (combined.aborted) return;
|
|
3500
|
+
bump();
|
|
3501
|
+
if (frame.event === "ready") {
|
|
3502
|
+
presence?.connectionChanged(true);
|
|
3503
|
+
void drain();
|
|
3504
|
+
assistant?.trigger();
|
|
3505
|
+
} else if (frame.event === "wake") {
|
|
3506
|
+
void drain();
|
|
3507
|
+
} else if (frame.event === "command") {
|
|
3508
|
+
try {
|
|
3509
|
+
const payload = JSON.parse(frame.data);
|
|
3510
|
+
if (payload && typeof payload === "object") {
|
|
3511
|
+
if (payload.command === "stop-agent" && payload.cardId) loop.abortCard(payload.cardId);
|
|
3512
|
+
else if (payload.command === "assistant-run") assistant?.trigger();
|
|
3513
|
+
else if (payload.command === "stop-assistant-run" && payload.runId) assistant?.abortRun(payload.runId);
|
|
3514
|
+
else presence?.command();
|
|
3515
|
+
} else {
|
|
3516
|
+
presence?.command();
|
|
3517
|
+
}
|
|
3518
|
+
} catch {
|
|
3519
|
+
presence?.command();
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
});
|
|
3523
|
+
} catch {
|
|
3524
|
+
} finally {
|
|
3525
|
+
clearTimeout(staleTimer);
|
|
3526
|
+
presence?.connectionChanged(false);
|
|
3527
|
+
}
|
|
3528
|
+
if (!signal.aborted) {
|
|
3529
|
+
await delay2(1500, signal);
|
|
3530
|
+
if (!signal.aborted) void drain();
|
|
3531
|
+
}
|
|
3532
|
+
}
|
|
3533
|
+
} finally {
|
|
3534
|
+
clearInterval(fallback);
|
|
3535
|
+
}
|
|
3536
|
+
}
|
|
3537
|
+
|
|
3538
|
+
// src/cli.ts
|
|
3539
|
+
async function runAgentProcess(options) {
|
|
3540
|
+
const maxConcurrency = parseMaxConcurrency(options.maxConcurrency ?? process.env.SLATE_AGENT_CONCURRENCY);
|
|
3541
|
+
await mkdir5(local, { recursive: true, mode: 448 });
|
|
3542
|
+
const { file, credential } = await ensureCredential({
|
|
3543
|
+
driver: options.driver,
|
|
3544
|
+
name: options.name,
|
|
3545
|
+
apiBase: options.apiBase,
|
|
3546
|
+
explicitFile: options.credentialFile,
|
|
3547
|
+
projectId: options.projectId
|
|
3548
|
+
});
|
|
3549
|
+
const release = await processLock(credential.agentId);
|
|
3550
|
+
const recordsDir = path10.join(local, "agent-runs");
|
|
3551
|
+
await mkdir5(recordsDir, { recursive: true, mode: 448 });
|
|
3552
|
+
const driver = createDriver(credential.driver);
|
|
3553
|
+
const api = new BoardApi(credential);
|
|
3554
|
+
let presence;
|
|
3555
|
+
const loop = new AgentLoop(api, driver, {
|
|
3556
|
+
agentId: credential.agentId,
|
|
3557
|
+
agentName: credential.name,
|
|
3558
|
+
credentialFile: file,
|
|
3559
|
+
cursorFile: path10.join(local, `agent-cursor-${credential.agentId}.json`),
|
|
3560
|
+
sessionsFile: path10.join(local, `agent-sessions-${credential.agentId}.json`),
|
|
3561
|
+
recordsDir,
|
|
3562
|
+
cardId: options.cardId,
|
|
3563
|
+
maxConcurrency,
|
|
3564
|
+
onAuthChanged: () => {
|
|
3565
|
+
void presence?.report();
|
|
3566
|
+
},
|
|
3567
|
+
log: console.log
|
|
3568
|
+
});
|
|
3569
|
+
presence = new AgentPresenceReporter(api, driver, loop, (msg) => console.log(`[${credential.name}] ${msg}`));
|
|
3570
|
+
const assistant = new AssistantRunner(api, driver, {
|
|
3571
|
+
agentId: credential.agentId,
|
|
3572
|
+
agentName: credential.name,
|
|
3573
|
+
credentialFile: file,
|
|
3574
|
+
recordsDir,
|
|
3575
|
+
onAuthChanged: () => {
|
|
3576
|
+
void presence?.report();
|
|
3577
|
+
},
|
|
3578
|
+
log: console.log
|
|
3579
|
+
});
|
|
3580
|
+
const internalStop = new AbortController();
|
|
3581
|
+
const stopSignal = options.signal ? AbortSignal.any([options.signal, internalStop.signal]) : internalStop.signal;
|
|
3582
|
+
const onExitSignal = () => internalStop.abort();
|
|
3583
|
+
if (!options.signal) {
|
|
3584
|
+
process.on("SIGINT", onExitSignal);
|
|
3585
|
+
process.on("SIGTERM", onExitSignal);
|
|
3586
|
+
}
|
|
3587
|
+
try {
|
|
3588
|
+
await loop.init();
|
|
3589
|
+
await presence.start();
|
|
3590
|
+
const bin = driver.binaryPath() ?? "\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6";
|
|
3591
|
+
const scopeSuffix = credential.projectId ? ` \xB7 \u9879\u76EE=${credential.projectId}` : "";
|
|
3592
|
+
console.log(
|
|
3593
|
+
`[${credential.name}] \u5DF2\u63A5\u5165\u770B\u677F (${credential.driver})${scopeSuffix} \xB7 \u5E76\u53D1=${maxConcurrency} \xB7 CLI=${bin} \xB7 \u51ED\u636E=${path10.basename(file)}`
|
|
3594
|
+
);
|
|
3595
|
+
await watchEvents(
|
|
3596
|
+
loop,
|
|
3597
|
+
api.eventStream.bind(api),
|
|
3598
|
+
stopSignal,
|
|
3599
|
+
(msg) => console.log(`[${credential.name}] ${msg}`),
|
|
3600
|
+
presence,
|
|
3601
|
+
assistant
|
|
3602
|
+
);
|
|
3603
|
+
} finally {
|
|
3604
|
+
if (!options.signal) {
|
|
3605
|
+
process.off("SIGINT", onExitSignal);
|
|
3606
|
+
process.off("SIGTERM", onExitSignal);
|
|
3607
|
+
}
|
|
3608
|
+
await assistant.stop().catch(() => {
|
|
3609
|
+
});
|
|
3610
|
+
await presence.stop().catch(() => {
|
|
3611
|
+
});
|
|
3612
|
+
await loop.stop().catch(() => {
|
|
3613
|
+
});
|
|
3614
|
+
await release();
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
if (process.argv[1] && import.meta.url === `file://${process.argv[1]}` && path10.basename(process.argv[1]).startsWith("cli.")) {
|
|
3618
|
+
const rawArgs = process.argv.slice(2);
|
|
3619
|
+
const cleanArgs = rawArgs[0] === "--" ? rawArgs.slice(1) : rawArgs;
|
|
3620
|
+
const { values } = parseArgs({
|
|
3621
|
+
args: cleanArgs,
|
|
3622
|
+
options: {
|
|
3623
|
+
driver: { type: "string", default: "codex" },
|
|
3624
|
+
name: { type: "string" },
|
|
3625
|
+
api: { type: "string" },
|
|
3626
|
+
credential: { type: "string" },
|
|
3627
|
+
project: { type: "string" },
|
|
3628
|
+
card: { type: "string" },
|
|
3629
|
+
concurrency: { type: "string" }
|
|
3630
|
+
},
|
|
3631
|
+
strict: true
|
|
3632
|
+
});
|
|
3633
|
+
try {
|
|
3634
|
+
await runAgentProcess({
|
|
3635
|
+
driver: driverTypeSchema.parse(values.driver),
|
|
3636
|
+
name: values.name,
|
|
3637
|
+
apiBase: values.api,
|
|
3638
|
+
credentialFile: values.credential,
|
|
3639
|
+
projectId: values.project,
|
|
3640
|
+
cardId: values.card,
|
|
3641
|
+
maxConcurrency: parseMaxConcurrency(values.concurrency ?? process.env.SLATE_AGENT_CONCURRENCY)
|
|
3642
|
+
});
|
|
3643
|
+
} catch (err) {
|
|
3644
|
+
console.error(`Agent \u542F\u52A8\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}`);
|
|
3645
|
+
process.exitCode = 1;
|
|
3646
|
+
}
|
|
3647
|
+
}
|
|
3648
|
+
|
|
3649
|
+
export {
|
|
3650
|
+
driverTypeSchema,
|
|
3651
|
+
detectInstalledDrivers,
|
|
3652
|
+
parseMaxConcurrency,
|
|
3653
|
+
runAgentProcess
|
|
3654
|
+
};
|