@kangyishuai/dsh-casefile 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/actions.js CHANGED
@@ -10,6 +10,7 @@ import { buildAttestation } from "./core/attestation.js";
10
10
  import { buildSpecPack, redactPack, renderSpecMarkdown, writeSpecPack } from "./core/brief.js";
11
11
  import { createCheckers } from "./core/checks.js";
12
12
  import { hashTree, shortDigest } from "./core/digest.js";
13
+ import { awaitLogin } from "./core/login-wait.js";
13
14
  import { gradeCapabilities } from "./core/manifest.js";
14
15
  import {
15
16
  CasefileInputError,
@@ -206,8 +207,14 @@ export function createActions(options) {
206
207
  */
207
208
  async addEvidence(projectId, input, exec) {
208
209
  const project = requireProject(projectId);
210
+ // 产物接管:/tmp 里的东西会被清理,清了 sha256 就无法复算,项目只能停在 investigating。
211
+ const archived =
212
+ typeof input?.artifactPath === "string" && input.artifactPath.trim() !== ""
213
+ ? store.archiveArtifact(project.id, input.artifactPath)
214
+ : null;
209
215
  const record = normalizeEvidence({
210
216
  ...input,
217
+ artifact: archived,
211
218
  sessionId: input?.sessionId ?? sessionOf(exec) ?? null,
212
219
  });
213
220
  store.appendRecord(project.id, "evidence", record);
@@ -969,6 +976,8 @@ export function createActions(options) {
969
976
  ].join("\n");
970
977
  const created = await sessions.create({ cwd });
971
978
  const sessionId = String(created.sessionId);
979
+ // builder 只该收到规格包:把它登记为"只读会话",写类工具会拒绝它。
980
+ store.recordBuilderSession(sessionId);
972
981
  await sessions.prompt({ sessionId, text: prompt });
973
982
  const record = {
974
983
  id: newId("builder"),
@@ -1120,6 +1129,42 @@ export function createActions(options) {
1120
1129
  return { ...overview, summary: summarizeOverview(overview) };
1121
1130
  },
1122
1131
 
1132
+ // ---------- 等登录(人机协作) ----------
1133
+
1134
+ /**
1135
+ * 轮询等用户完成登录。带超时,不假装成功。
1136
+ * @param {string} projectId
1137
+ * @param {{
1138
+ * endpoint: string, urlPrefix?: string, readyJs?: string,
1139
+ * pollMs?: number, timeoutMs?: number,
1140
+ * }} input
1141
+ * @returns {Promise<Record<string, any>>}
1142
+ */
1143
+ async awaitLogin(projectId, input) {
1144
+ const project = requireProject(projectId);
1145
+ const endpoint = String(input?.endpoint ?? "").trim();
1146
+ if (endpoint === "") {
1147
+ throw new CasefileInputError(
1148
+ "invalid-input",
1149
+ "endpoint 不能为空(形如 http://127.0.0.1:9223)",
1150
+ );
1151
+ }
1152
+ const result = await awaitLogin({
1153
+ endpoint,
1154
+ urlPrefix: input?.urlPrefix,
1155
+ readyJs: input?.readyJs,
1156
+ pollMs: input?.pollMs,
1157
+ timeoutMs: input?.timeoutMs,
1158
+ });
1159
+ store.audit(project.id, {
1160
+ actor: "agent",
1161
+ action: "access/await-login",
1162
+ target: endpoint,
1163
+ detail: { status: result.status, attempts: result.attempts, waitedMs: result.waitedMs },
1164
+ });
1165
+ return result;
1166
+ },
1167
+
1123
1168
  // ---------- 覆盖率 / 关闭 / 报告(M3 收尾) ----------
1124
1169
 
1125
1170
  /**
@@ -0,0 +1,205 @@
1
+ // @ts-check
2
+ // core/login-wait.js:等用户完成登录(轮询 CDP 页面就绪条件)。
3
+ //
4
+ // 为什么需要它:登录态页面要人参与(输账号/扫码/二次验证)。agent 不能干等,
5
+ // 也不能假装成功——所以做成"带超时的轮询 + 明确状态":
6
+ // - ready:就绪判据为真,可以继续采集
7
+ // - timeout:到点还没好,保留现场,调用方决定是否重来
8
+ // - error:端点/页面不可用(不存在、CDP 层失败)
9
+ // 判据用一段 JS 表达式(返回 boolean),由调用方给出——casefile 不猜"登录成功"长什么样。
10
+
11
+ /**
12
+ * @typedef {{
13
+ * status: "ready" | "timeout" | "error",
14
+ * attempts: number,
15
+ * waitedMs: number,
16
+ * pollMs: number,
17
+ * timeoutMs: number,
18
+ * lastValue: boolean | null,
19
+ * hint: string,
20
+ * detail?: string,
21
+ * }} LoginWaitResult
22
+ */
23
+
24
+ /** 默认轮询参数。 */
25
+ export const LOGIN_WAIT_DEFAULTS = {
26
+ pollMs: 2000,
27
+ timeoutMs: 180000,
28
+ readyJs: '!document.querySelector("input[type=password]")',
29
+ };
30
+
31
+ /**
32
+ * 在 CDP 端点上找一个 HTTP(S) 页面 target。
33
+ * @param {string} endpoint 形如 http://127.0.0.1:9223
34
+ * @param {string} [urlPrefix] 只选 URL 以它开头的页面
35
+ * @returns {Promise<{ id: string, url: string } | null>}
36
+ */
37
+ export async function findPageTarget(endpoint, urlPrefix) {
38
+ const base = String(endpoint).replace(/\/+$/, "");
39
+ const response = await fetch(`${base}/json/list`, { signal: AbortSignal.timeout(10000) });
40
+ if (!response.ok) throw new Error(`target discovery failed: HTTP ${response.status}`);
41
+ const targets = await response.json();
42
+ const pages = (Array.isArray(targets) ? targets : []).filter(
43
+ (/** @type {any} */ item) => item?.type === "page" && /^https?:/u.test(String(item.url ?? "")),
44
+ );
45
+ if (pages.length === 0) return null;
46
+ const picked =
47
+ (urlPrefix
48
+ ? pages.find((/** @type {any} */ item) => String(item.url).startsWith(urlPrefix))
49
+ : null) ?? pages[0];
50
+ return { id: String(picked.id), url: String(picked.url) };
51
+ }
52
+
53
+ /**
54
+ * 在页面里求值(一次性 WebSocket,用完即断)。
55
+ * @param {string} wsUrl
56
+ * @param {string} expression
57
+ * @returns {Promise<boolean>}
58
+ */
59
+ async function evaluateOnce(wsUrl, expression) {
60
+ return await new Promise((resolve, reject) => {
61
+ const socket = new WebSocket(wsUrl);
62
+ const timer = setTimeout(() => {
63
+ try {
64
+ socket.close();
65
+ } catch {
66
+ // 关闭失败不影响超时语义
67
+ }
68
+ reject(new Error("evaluate timeout"));
69
+ }, 10000);
70
+ socket.onopen = () => {
71
+ socket.send(
72
+ JSON.stringify({
73
+ id: 1,
74
+ method: "Runtime.evaluate",
75
+ params: { expression, returnByValue: true },
76
+ }),
77
+ );
78
+ };
79
+ socket.onerror = () => {
80
+ clearTimeout(timer);
81
+ reject(new Error("cdp socket error"));
82
+ };
83
+ socket.onmessage = (/** @type {any} */ event) => {
84
+ let message;
85
+ try {
86
+ message = JSON.parse(String(event.data));
87
+ } catch {
88
+ return;
89
+ }
90
+ if (message.id !== 1) return;
91
+ clearTimeout(timer);
92
+ try {
93
+ socket.close();
94
+ } catch {
95
+ // 忽略
96
+ }
97
+ if (message.error) {
98
+ reject(new Error(`cdp error: ${JSON.stringify(message.error)}`));
99
+ return;
100
+ }
101
+ resolve(message.result?.result?.value === true);
102
+ };
103
+ });
104
+ }
105
+
106
+ /**
107
+ * 轮询等登录就绪。
108
+ * @param {{
109
+ * endpoint: string,
110
+ * urlPrefix?: string,
111
+ * readyJs?: string,
112
+ * pollMs?: number,
113
+ * timeoutMs?: number,
114
+ * sleep?: (ms: number) => Promise<void>,
115
+ * probe?: (wsUrl: string, expression: string) => Promise<boolean>,
116
+ * }} input
117
+ * @returns {Promise<LoginWaitResult>}
118
+ */
119
+ export async function awaitLogin(input) {
120
+ const pollMs =
121
+ Number.isInteger(input.pollMs) && Number(input.pollMs) > 0
122
+ ? Number(input.pollMs)
123
+ : LOGIN_WAIT_DEFAULTS.pollMs;
124
+ const timeoutMs =
125
+ Number.isInteger(input.timeoutMs) && Number(input.timeoutMs) > 0
126
+ ? Number(input.timeoutMs)
127
+ : LOGIN_WAIT_DEFAULTS.timeoutMs;
128
+ const readyJs =
129
+ typeof input.readyJs === "string" && input.readyJs.trim() !== ""
130
+ ? input.readyJs
131
+ : LOGIN_WAIT_DEFAULTS.readyJs;
132
+ const sleep = input.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
133
+ const probe = input.probe ?? evaluateOnce;
134
+ const started = Date.now();
135
+ let attempts = 0;
136
+ /** @type {boolean | null} */
137
+ let lastValue = null;
138
+
139
+ while (Date.now() - started < timeoutMs) {
140
+ attempts += 1;
141
+ try {
142
+ const endpoint = String(input.endpoint ?? "").replace(/\/+$/, "");
143
+ const response = await fetch(`${endpoint}/json/list`, { signal: AbortSignal.timeout(10000) });
144
+ if (!response.ok) throw new Error(`target discovery failed: HTTP ${response.status}`);
145
+ const targets = await response.json();
146
+ const pages = (Array.isArray(targets) ? targets : []).filter(
147
+ (/** @type {any} */ item) =>
148
+ item?.type === "page" && /^https?:/u.test(String(item.url ?? "")),
149
+ );
150
+ const wanted = input.urlPrefix;
151
+ const picked =
152
+ (wanted
153
+ ? pages.find((/** @type {any} */ item) => String(item.url).startsWith(wanted))
154
+ : null) ?? pages[0];
155
+ if (!picked) {
156
+ lastValue = null;
157
+ await sleep(pollMs);
158
+ continue;
159
+ }
160
+ lastValue = await probe(String(picked.webSocketDebuggerUrl), readyJs);
161
+ if (lastValue === true) {
162
+ return {
163
+ status: "ready",
164
+ attempts,
165
+ waitedMs: Date.now() - started,
166
+ pollMs,
167
+ timeoutMs,
168
+ lastValue,
169
+ hint: "已就绪:可以继续采集了。",
170
+ };
171
+ }
172
+ } catch (error) {
173
+ const message = error instanceof Error ? error.message : String(error);
174
+ // 端点还没起来 / 页面还没开也属于"等",只有明确不可恢复才报错
175
+ // 端点还没起来(浏览器没启动 / 端口没开)属于可以继续等,不该立刻判失败;
176
+ // 等满 timeoutMs 后由循环出口统一报 timeout。
177
+ if (/ECONNREFUSED|ECONNRESET|fetch failed|target discovery failed/u.test(message)) {
178
+ lastValue = null;
179
+ await sleep(pollMs);
180
+ continue;
181
+ }
182
+ return {
183
+ status: "error",
184
+ attempts,
185
+ waitedMs: Date.now() - started,
186
+ pollMs,
187
+ timeoutMs,
188
+ lastValue,
189
+ hint: "CDP 端点或页面不可用;确认带 --remote-debugging-port 的浏览器已启动并打开了目标页。",
190
+ detail: message.slice(0, 500),
191
+ };
192
+ }
193
+ await sleep(pollMs);
194
+ }
195
+
196
+ return {
197
+ status: "timeout",
198
+ attempts,
199
+ waitedMs: Date.now() - started,
200
+ pollMs,
201
+ timeoutMs,
202
+ lastValue,
203
+ hint: "等待超时:登录还没完成。现场保留,你可以登录后重新调用,或调大 timeoutMs。",
204
+ };
205
+ }
package/lib/core/model.js CHANGED
@@ -219,11 +219,6 @@ export function normalizeProjectInput(input) {
219
219
  };
220
220
  }
221
221
 
222
- /**
223
- * 规范化一条证据(只投影 REA 的结论)。
224
- * @param {Record<string, any>} input
225
- * @returns {Record<string, any>}
226
- */
227
222
  /**
228
223
  * 外部生产者(谁采的、用什么方式采的、用户是否明示确认过)。
229
224
  * casefile 自己不采集:它只记录产出者,责任与合法性归操作者。
@@ -258,6 +253,34 @@ export function normalizeProducer(raw) {
258
253
  return Object.keys(producer).length === 0 ? null : producer;
259
254
  }
260
255
 
256
+ /**
257
+ * 规范化一条证据(只投影 REA 的结论)。
258
+ * @param {Record<string, any>} input
259
+ * @returns {Record<string, any>}
260
+ */
261
+ /**
262
+ * 归档产物元信息(由 store.archiveArtifact 产出,这里只做形状校验)。
263
+ * @param {any} raw
264
+ * @returns {Record<string, any> | null}
265
+ */
266
+ export function normalizeArtifact(raw) {
267
+ if (raw == null) return null;
268
+ if (typeof raw !== "object" || Array.isArray(raw)) {
269
+ throw new CasefileInputError("invalid-input", "artifact 必须是对象");
270
+ }
271
+ const sha256 = text(raw.sha256, "artifact.sha256", { max: 128 });
272
+ const file = text(raw.file, "artifact.file", { max: 400 });
273
+ return {
274
+ sha256,
275
+ bytes: Number.isInteger(raw.bytes) && raw.bytes >= 0 ? raw.bytes : 0,
276
+ file,
277
+ originalName:
278
+ raw.originalName == null
279
+ ? null
280
+ : text(raw.originalName, "artifact.originalName", { max: 200 }),
281
+ };
282
+ }
283
+
261
284
  /**
262
285
  * 规范化一条证据(只投影 REA 的结论)。
263
286
  * @param {Record<string, any>} input
@@ -278,6 +301,7 @@ export function normalizeEvidence(input) {
278
301
  summary: text(input?.summary, "summary", { max: 4000 }),
279
302
  refs: textList(input?.refs, "refs"),
280
303
  producer: normalizeProducer(input?.producer),
304
+ artifact: normalizeArtifact(input?.artifact),
281
305
  claimIds: idList(input?.claimIds, "claimIds"),
282
306
  };
283
307
  }
package/lib/core/store.js CHANGED
@@ -11,15 +11,18 @@
11
11
  // - JSONL append-only,修改用新记录 + supersedes(M0 先只追加);
12
12
  // - 所有路径从 dataRoot 派生,不写死 ~/.dsh(可在临时目录里测)。
13
13
 
14
+ import { createHash } from "node:crypto";
14
15
  import {
16
+ appendFileSync,
15
17
  existsSync,
16
18
  mkdirSync,
17
19
  readdirSync,
18
20
  readFileSync,
19
21
  renameSync,
22
+ statSync,
20
23
  writeFileSync,
21
24
  } from "node:fs";
22
- import { dirname, join } from "node:path";
25
+ import { basename, dirname, extname, join } from "node:path";
23
26
  import {
24
27
  CasefileInputError,
25
28
  ID_RE,
@@ -363,6 +366,73 @@ export class CaseStore {
363
366
  return candidate;
364
367
  }
365
368
 
369
+ /**
370
+ * 把外部采集产物归档进项目目录,返回归档后的元信息。
371
+ * 目的:/tmp 里的产物会被清理,清了就无法复算 sha256,项目只能停在 investigating。
372
+ * @param {string} projectId
373
+ * @param {string} sourcePath 绝对路径的现成产物
374
+ * @returns {{ sha256: string, bytes: number, file: string, originalName: string }}
375
+ */
376
+ archiveArtifact(projectId, sourcePath) {
377
+ const source = String(sourcePath ?? "").trim();
378
+ if (source === "" || !existsSync(source)) {
379
+ throw new CasefileInputError("invalid-input", `产物不存在:${source || "(空)"}`);
380
+ }
381
+ const stat = statSync(source);
382
+ if (!stat.isFile()) {
383
+ throw new CasefileInputError("invalid-input", `不是普通文件:${source}`);
384
+ }
385
+ const bytes = readFileSync(source);
386
+ const digest = createHash("sha256").update(bytes).digest("hex");
387
+ const dir = join(this.projectDir(projectId), "artifacts");
388
+ mkdirSync(dir, { recursive: true });
389
+ const name = basename(source);
390
+ const ext = extname(name);
391
+ const file = join("artifacts", `${digest.slice(0, 16)}${ext}`);
392
+ const target = join(this.projectDir(projectId), file);
393
+ // 同样的内容只存一份:同一 sha256 已存在就直接复用
394
+ if (!existsSync(target)) writeFileSync(target, bytes);
395
+ return { sha256: digest, bytes: bytes.length, file, originalName: name };
396
+ }
397
+
398
+ /**
399
+ * 记录一个 builder 子会话 id(数据根级,不分项目)。
400
+ * builder 只该收到规格包,不该写账本——写类工具遇到它会拒绝。
401
+ * @param {string} sessionId
402
+ */
403
+ recordBuilderSession(sessionId) {
404
+ const id = String(sessionId ?? "").trim();
405
+ if (id === "") return;
406
+ const file = join(this.dataRoot, "builder-sessions.jsonl");
407
+ appendFileSync(
408
+ file,
409
+ `${JSON.stringify({ sessionId: id, at: new Date().toISOString() })}\n`,
410
+ "utf8",
411
+ );
412
+ }
413
+
414
+ /**
415
+ * 读 builder 会话 id 集合。
416
+ * @returns {Set<string>}
417
+ */
418
+ listBuilderSessions() {
419
+ const file = join(this.dataRoot, "builder-sessions.jsonl");
420
+ if (!existsSync(file)) return new Set();
421
+ /** @type {Set<string>} */
422
+ const out = new Set();
423
+ for (const line of readFileSync(file, "utf8").split("\n")) {
424
+ const text = line.trim();
425
+ if (text === "") continue;
426
+ try {
427
+ const record = JSON.parse(text);
428
+ if (typeof record?.sessionId === "string") out.add(record.sessionId);
429
+ } catch {
430
+ // 坏行跳过:这份索引是"宁可少拦"的辅助数据,坏了不影响主记录。
431
+ }
432
+ }
433
+ return out;
434
+ }
435
+
366
436
  /**
367
437
  * 项目列表(跳过坏项目并告警)。
368
438
  * @returns {Record<string, any>[]}
package/lib/service.js CHANGED
@@ -210,7 +210,10 @@ export class CasefileService extends TypertRemoteService {
210
210
  closeObligation: (projectId, id, input) => this.actions.closeObligation(projectId, id, input),
211
211
  reopenObligation: (projectId, id, note) => this.actions.reopenObligation(projectId, id, note),
212
212
  overview: () => this.actions.overview(),
213
+ awaitLogin: (projectId, input) => this.actions.awaitLogin(projectId, input),
213
214
  runCycle: (projectId, input) => this.actions.runCycle(projectId, input),
215
+ isBuilderSession: (sessionId) =>
216
+ this.store.listBuilderSessions().has(String(sessionId ?? "")),
214
217
  closeProject: (projectId, options) => this.actions.closeProject(projectId, options),
215
218
  closePreview: (projectId, options) => this.actions.closePreview(projectId, options),
216
219
  exportReport: (projectId) => this.actions.exportReport(projectId),
@@ -457,6 +460,19 @@ export class CasefileService extends TypertRemoteService {
457
460
  }
458
461
  }
459
462
 
463
+ /**
464
+ * @param {string} projectId
465
+ * @param {Record<string, any>} input
466
+ * @returns {Promise<Record<string, any>>}
467
+ */
468
+ async awaitLogin(projectId, input) {
469
+ try {
470
+ return await this.actions.awaitLogin(projectId, /** @type {any} */ (input));
471
+ } catch (error) {
472
+ fail(error);
473
+ }
474
+ }
475
+
460
476
  /**
461
477
  * @param {string} projectId
462
478
  * @param {Record<string, any>} input
@@ -663,6 +679,7 @@ declareRemote(CasefileService, "listChecks");
663
679
  declareRemote(CasefileService, "closeObligation");
664
680
  declareRemote(CasefileService, "reopenObligation");
665
681
  declareRemote(CasefileService, "overview");
682
+ declareRemote(CasefileService, "awaitLogin");
666
683
  declareRemote(CasefileService, "runCycle");
667
684
  declareRemote(CasefileService, "closeProject");
668
685
  declareRemote(CasefileService, "exportReport");
package/lib/tools.js CHANGED
@@ -17,6 +17,7 @@ export const TOOL_NAMES = /** @type {const} */ ({
17
17
  feature: "case_feature",
18
18
  unknown: "case_unknown",
19
19
  obligation: "case_obligation",
20
+ access: "case_access",
20
21
  build: "case_build",
21
22
  check: "case_check",
22
23
  brief: "case_brief",
@@ -84,6 +85,35 @@ function assertAction(action, allowed) {
84
85
  * @returns {any[]}
85
86
  */
86
87
  export function buildToolDefinitions(handlers, projectOf) {
88
+ /**
89
+ * @param {any} args
90
+ * @param {any} exec
91
+ * @returns {string}
92
+ */
93
+ /**
94
+ * builder 子会话只该收到规格包,不得写账本。
95
+ * 写类工具在开跑前统一过这道门:exec.agent.id 命中 builder 登记就拒绝。
96
+ * @param {any} exec
97
+ * @returns {Promise<void>}
98
+ */
99
+ /**
100
+ * builder 子会话只该收到规格包,不得写账本。
101
+ * @param {any} exec
102
+ * @returns {Promise<void>}
103
+ */
104
+ const assertWriter = async (exec) => {
105
+ const sessionId = exec?.agent?.id;
106
+ if (typeof sessionId !== "string" || sessionId === "") return;
107
+ const lookup = handlers.isBuilderSession;
108
+ if (typeof lookup !== "function") return;
109
+ if (await lookup(sessionId)) {
110
+ throw Object.assign(
111
+ new Error("builder 会话不能写案卷:它只该收到规格包。写证据/结论/义务请在主线会话里做。"),
112
+ { code: "builder-readonly" },
113
+ );
114
+ }
115
+ };
116
+
87
117
  /**
88
118
  * @param {any} args
89
119
  * @param {any} exec
@@ -138,6 +168,7 @@ export function buildToolDefinitions(handlers, projectOf) {
138
168
  /** @param {any} args @param {any} exec */
139
169
  async execute(args, exec) {
140
170
  return run(async () => {
171
+ await assertWriter(exec);
141
172
  switch (args.action) {
142
173
  case "open": {
143
174
  if (typeof args.title !== "string" || args.title.trim() === "") {
@@ -221,6 +252,11 @@ export function buildToolDefinitions(handlers, projectOf) {
221
252
  description:
222
253
  "产出该证据的工具标识(REA 工具名,或外部工具如 scrapling/StealthyFetcher)",
223
254
  },
255
+ artifactPath: {
256
+ type: "string",
257
+ description:
258
+ "可选:把外部采集产物(HTML/HAR/截图)归档进项目目录并记录 sha256;/tmp 产物会被清理,归档后才能长期复算",
259
+ },
224
260
  producer: {
225
261
  type: "object",
226
262
  additionalProperties: false,
@@ -262,6 +298,7 @@ export function buildToolDefinitions(handlers, projectOf) {
262
298
  /** @param {any} args @param {any} exec */
263
299
  async execute(args, exec) {
264
300
  return run(async () => {
301
+ await assertWriter(exec);
265
302
  const action = assertAction(args.action, ["add", "list", "show"]);
266
303
  const id = projectId(args, exec);
267
304
  if (action === "add") {
@@ -320,6 +357,7 @@ export function buildToolDefinitions(handlers, projectOf) {
320
357
  /** @param {any} args @param {any} exec */
321
358
  async execute(args, exec) {
322
359
  return run(async () => {
360
+ await assertWriter(exec);
323
361
  const action = assertAction(args.action, ["add", "list", "search", "select"]);
324
362
  const id = projectId(args, exec);
325
363
  if (action === "add") {
@@ -372,6 +410,7 @@ export function buildToolDefinitions(handlers, projectOf) {
372
410
  /** @param {any} args @param {any} exec */
373
411
  async execute(args, exec) {
374
412
  return run(async () => {
413
+ await assertWriter(exec);
375
414
  const action = assertAction(args.action, ["add", "list"]);
376
415
  const id = projectId(args, exec);
377
416
  if (action === "add") {
@@ -411,6 +450,7 @@ export function buildToolDefinitions(handlers, projectOf) {
411
450
  /** @param {any} args @param {any} exec */
412
451
  async execute(args, exec) {
413
452
  return run(async () => {
453
+ await assertWriter(exec);
414
454
  const action = assertAction(args.action, ["add", "list", "resolve"]);
415
455
  const id = projectId(args, exec);
416
456
  if (action === "add") {
@@ -475,6 +515,7 @@ export function buildToolDefinitions(handlers, projectOf) {
475
515
  /** @param {any} args @param {any} exec */
476
516
  async execute(args, exec) {
477
517
  return run(async () => {
518
+ await assertWriter(exec);
478
519
  const action = assertAction(args.action, ["add", "list", "close", "reopen"]);
479
520
  const id = projectId(args, exec);
480
521
  if (action === "add") {
@@ -502,6 +543,52 @@ export function buildToolDefinitions(handlers, projectOf) {
502
543
  },
503
544
  },
504
545
 
546
+ {
547
+ name: TOOL_NAMES.access,
548
+ description:
549
+ "访问协助:await-login 轮询等人完成登录(带超时,就绪/超时/错误三态,不假装成功)。用于登录态页面采集前。",
550
+ parameters: {
551
+ type: "object",
552
+ additionalProperties: false,
553
+ properties: {
554
+ action: { type: "string", enum: ["await-login"] },
555
+ projectId: PROJECT_ID,
556
+ endpoint: { type: "string", description: "CDP 端点,形如 http://127.0.0.1:9223" },
557
+ urlPrefix: { type: "string", description: "只选 URL 以它开头的页面" },
558
+ readyJs: {
559
+ type: "string",
560
+ description: "就绪判据(返回 boolean 的 JS 表达式),默认「页面里没有密码输入框」",
561
+ },
562
+ pollMs: { type: "integer", description: "轮询间隔,默认 2000" },
563
+ timeoutMs: { type: "integer", description: "最长等待,默认 180000(3 分钟)" },
564
+ },
565
+ required: ["action"],
566
+ },
567
+ output: { schema: TOOL_OUTPUT_SCHEMA, render: renderToolResult },
568
+ /** @param {any} args @param {any} exec */
569
+ async execute(args, exec) {
570
+ return run(async () => {
571
+ await assertWriter(exec);
572
+ assertAction(args.action, ["await-login"]);
573
+ const id = projectId(args, exec);
574
+ const result = await handlers.awaitLogin(id, {
575
+ endpoint: args.endpoint,
576
+ urlPrefix: args.urlPrefix,
577
+ readyJs: args.readyJs,
578
+ pollMs: args.pollMs,
579
+ timeoutMs: args.timeoutMs,
580
+ });
581
+ return {
582
+ ...result,
583
+ summary:
584
+ result.status === "ready"
585
+ ? `已就绪(等了 ${result.waitedMs}ms,${result.attempts} 次探测)`
586
+ : `${result.status}:${result.hint}`,
587
+ };
588
+ });
589
+ },
590
+ },
591
+
505
592
  {
506
593
  name: TOOL_NAMES.build,
507
594
  description:
@@ -532,6 +619,7 @@ export function buildToolDefinitions(handlers, projectOf) {
532
619
  /** @param {any} args @param {any} exec */
533
620
  async execute(args, exec) {
534
621
  return run(async () => {
622
+ await assertWriter(exec);
535
623
  const action = assertAction(args.action, ["start", "status", "agent", "loop", "cycle"]);
536
624
  const id = projectId(args, exec);
537
625
  if (action === "cycle") {
@@ -638,6 +726,7 @@ export function buildToolDefinitions(handlers, projectOf) {
638
726
  /** @param {any} args @param {any} exec */
639
727
  async execute(args, exec) {
640
728
  return run(async () => {
729
+ await assertWriter(exec);
641
730
  const action = assertAction(args.action, ["run", "list", "loop"]);
642
731
  const id = projectId(args, exec);
643
732
  if (action === "run") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-casefile",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Evidence-first reverse-engineering workbench on top of REA: observations become citable evidence, a handoff spec pack, and recomputable acceptance checks. No bridge, no engine.",
5
5
  "keywords": [
6
6
  "dsh",