@lynn123411/dsh-subagent-judge-dispatch 0.6.7 → 0.6.8

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/index.js CHANGED
@@ -59,11 +59,11 @@ function composeJudgeSubject(label, taskText) {
59
59
 
60
60
  ${task}`;
61
61
  }
62
- function clipTaskText(text) {
63
- if (text.length <= SUBJECT_HEAD_CHARS + SUBJECT_TAIL_CHARS) return text;
64
- const dropped = text.length - SUBJECT_HEAD_CHARS - SUBJECT_TAIL_CHARS;
65
- const head = text.slice(0, SUBJECT_HEAD_CHARS);
66
- const tail = text.slice(text.length - SUBJECT_TAIL_CHARS);
62
+ function clipTaskText(text2) {
63
+ if (text2.length <= SUBJECT_HEAD_CHARS + SUBJECT_TAIL_CHARS) return text2;
64
+ const dropped = text2.length - SUBJECT_HEAD_CHARS - SUBJECT_TAIL_CHARS;
65
+ const head = text2.slice(0, SUBJECT_HEAD_CHARS);
66
+ const tail = text2.slice(text2.length - SUBJECT_TAIL_CHARS);
67
67
  return `${head}
68
68
  \u2026 (${dropped} characters omitted) \u2026
69
69
  ${tail}`;
@@ -204,127 +204,113 @@ function outcomeReason(outcome, decision) {
204
204
 
205
205
  // src/server/identity.ts
206
206
  function ownEventsOf(session) {
207
- if (typeof session.ownEvents === "function") return session.ownEvents();
208
- const inherited = session.inheritedEventCount;
209
- if (typeof inherited === "number" && Number.isSafeInteger(inherited) && inherited > 0) {
210
- return session.snapshotEvents(inherited);
211
- }
212
- return session.snapshotEvents();
207
+ return session.ownEvents?.() ?? session.snapshotEvents(session.inheritedEventCount ?? 0);
213
208
  }
214
209
  function isSubagent(agent) {
215
210
  const fromHeader = agent.session.header.delegationDepth;
216
211
  const fromOptions = agent.options.subagentDepth;
217
- const depth = Math.max(
212
+ return Math.max(
218
213
  typeof fromHeader === "number" && Number.isSafeInteger(fromHeader) ? fromHeader : 0,
219
214
  typeof fromOptions === "number" && Number.isSafeInteger(fromOptions) ? fromOptions : 0
220
- );
221
- return depth >= 1;
222
- }
223
- var RETURN_GUIDANCE_PREFIXES = [
224
- "Your parent agent id is ",
225
- "Your final answer is delivered automatically if your "
226
- ];
227
- function isReturnGuidance(text) {
228
- return RETURN_GUIDANCE_PREFIXES.some((prefix) => text.startsWith(prefix));
229
- }
230
- function readChildLabel(agent) {
231
- let found = "";
232
- for (const event of ownEventsOf(agent.session)) {
233
- if (event.type !== "subagent/descriptor") continue;
234
- const data = event.data;
235
- if (typeof data !== "object" || data === null) continue;
236
- const label = data.label;
237
- if (typeof label === "string" && label.trim() !== "") found = label.trim();
238
- }
239
- return found;
240
- }
241
- function readTaskText(agent) {
242
- for (const event of ownEventsOf(agent.session)) {
243
- const candidates = delegationMessagesOf(event);
244
- for (const data of candidates) {
245
- const blocks = textBlocksOf(data);
246
- if (blocks.length > 1 && isReturnGuidance(blocks[blocks.length - 1])) {
247
- blocks.pop();
248
- }
249
- const text = blocks.join("\n").trim();
250
- if (text !== "") return text;
215
+ ) >= 1;
216
+ }
217
+ function asRecord(value) {
218
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
219
+ }
220
+ function readText(block) {
221
+ const data = asRecord(block);
222
+ return data?.type === "text" && typeof data.text === "string" ? data.text : void 0;
223
+ }
224
+ var RETURN_GUIDANCE = "Your final answer is delivered automatically if your parent is still online.";
225
+ function readInitialTask(events, parentId) {
226
+ for (const event of events) {
227
+ const inserted = asRecord(event.data)?.inserted;
228
+ const messages = event.type === "user/message" ? [event.data] : event.type === "agent/inbox/spliced" && Array.isArray(inserted) ? inserted : [];
229
+ for (const value of messages) {
230
+ const message = asRecord(value);
231
+ const source = asRecord(message?.source);
232
+ if (source?.kind !== "agent-message" || source.form !== "relay" || source.senderSessionId !== parentId) continue;
233
+ if (!Array.isArray(message?.content)) return void 0;
234
+ const [sender, ...body] = message.content;
235
+ if (!/^Agent .+ sent a message: $/.test(readText(sender) ?? "")) return void 0;
236
+ const texts = body.map(readText).filter((text2) => text2 !== void 0);
237
+ if (texts.length > 1 && texts.at(-1)?.startsWith(RETURN_GUIDANCE)) texts.pop();
238
+ return texts.join("\n").trim() || void 0;
251
239
  }
252
240
  }
253
- return "";
241
+ return void 0;
254
242
  }
255
- var DELEGATION_EVENT_TYPES = /* @__PURE__ */ new Set([
256
- "tool/call",
257
- "tool/ptc-dispatch-start"
258
- ]);
259
- function readDelegatedTask(agent, parentSessionOf) {
260
- const own = readTaskText(agent);
261
- if (own !== "") return own;
262
- const parentId = agent.session.header.parentSession;
263
- if (typeof parentId !== "string" || parentId === "") return "";
264
- const parent = parentSessionOf(parentId);
265
- if (parent === void 0 || typeof parent.snapshotEvents !== "function") return "";
266
- const label = readChildLabel(agent);
267
- const events = parent.snapshotEvents();
268
- let fallback = "";
269
- for (let index = events.length - 1; index >= 0; index -= 1) {
270
- const event = events[index];
271
- if (!DELEGATION_EVENT_TYPES.has(event.type)) continue;
272
- const call = delegatedCallOf(event.data);
273
- if (call === void 0) continue;
274
- if (label !== "" && call.description === label) return call.prompt;
275
- if (fallback === "") fallback = call.prompt;
276
- }
277
- return fallback;
278
- }
279
- function delegatedCallOf(data) {
280
- const parsed = argumentsOf(data);
281
- if (typeof parsed !== "object" || parsed === null) return void 0;
282
- const record = parsed;
283
- if (typeof record.prompt !== "string" || record.prompt.trim() === "") return void 0;
243
+ var DELEGATION_TOOLS = /* @__PURE__ */ new Set(["subagent", "subagent_fork"]);
244
+ function matchingCall(data, label) {
245
+ if (!DELEGATION_TOOLS.has(data.name)) return void 0;
246
+ let args = data.arguments;
247
+ if (typeof args === "string") {
248
+ try {
249
+ args = JSON.parse(args);
250
+ } catch {
251
+ return void 0;
252
+ }
253
+ }
254
+ const call = asRecord(args);
255
+ if (typeof call?.description !== "string" || call.description.trim() !== label || typeof call.prompt !== "string" || call.prompt.trim() === "") return void 0;
284
256
  return {
285
- prompt: record.prompt,
286
- ...typeof record.description === "string" ? { description: record.description } : {}
257
+ label,
258
+ text: call.prompt.trim(),
259
+ explicitRoute: call.provider !== void 0 || call.model !== void 0 || call.reasoning_effort !== void 0
287
260
  };
288
261
  }
289
- function argumentsOf(data) {
290
- if (typeof data !== "object" || data === null) return void 0;
291
- const raw = data.arguments;
292
- if (typeof raw !== "string") return raw;
293
- try {
294
- return JSON.parse(raw);
295
- } catch {
296
- return void 0;
297
- }
298
- }
299
- function delegationMessagesOf(event) {
300
- if (event.type === "user/message") {
301
- return sourceOf(event.data)?.kind === "user" ? [event.data] : [];
302
- }
303
- if (event.type === "agent/inbox/spliced") {
304
- const inserted = event.data?.inserted;
305
- if (!Array.isArray(inserted)) return [];
306
- return inserted.filter((message) => sourceOf(message)?.kind === "user");
262
+ function outstandingDelegation(events, label, resumedChildId) {
263
+ const end = resumedChildId === void 0 ? events.length : events.findIndex(
264
+ (event) => event.type === "subagent/catalog" && asRecord(event.data)?.childId === resumedChildId
265
+ );
266
+ const finished = /* @__PURE__ */ new Set();
267
+ let task;
268
+ for (let index = end - 1; index >= 0; index -= 1) {
269
+ const { type, data: value } = events[index];
270
+ if (type === "step/start" || type === "step/end" || type === "turn/start" || type === "turn/end") break;
271
+ const data = asRecord(value);
272
+ if (data === void 0) continue;
273
+ switch (type) {
274
+ case "tool/result": {
275
+ const id = asRecord(data.message)?.toolCallId;
276
+ if (typeof id === "string") finished.add(`native:${id}`);
277
+ break;
278
+ }
279
+ case "tool/ptc-dispatch":
280
+ if (typeof data.subCallId === "string") finished.add(`ptc:${data.subCallId}`);
281
+ break;
282
+ case "tool/call":
283
+ case "tool/ptc-dispatch-start": {
284
+ const ptc = type === "tool/ptc-dispatch-start";
285
+ const id = ptc ? data.subCallId : data.callId;
286
+ if (typeof id !== "string" || finished.has(`${ptc ? "ptc" : "native"}:${id}`)) break;
287
+ const candidate = matchingCall(data, label);
288
+ if (candidate === void 0) break;
289
+ if (task !== void 0) return void 0;
290
+ task = candidate;
291
+ break;
292
+ }
293
+ }
307
294
  }
308
- return [];
295
+ return task;
309
296
  }
310
- function sourceOf(data) {
311
- if (typeof data !== "object" || data === null) return void 0;
312
- const source = data.source;
313
- if (typeof source !== "object" || source === null) return void 0;
314
- const kind = source.kind;
315
- return typeof kind === "string" ? { kind } : void 0;
297
+ function hasRecordedRoute(session, events = ownEventsOf(session)) {
298
+ return events.some((event) => event.type === "model/selection" || event.type === "request/header");
316
299
  }
317
- function textBlocksOf(data) {
318
- if (typeof data !== "object" || data === null) return [];
319
- const content = data.content;
320
- if (!Array.isArray(content)) return [];
321
- const texts = [];
322
- for (const block of content) {
323
- if (typeof block !== "object" || block === null) continue;
324
- const record = block;
325
- if (record.type === "text" && typeof record.text === "string") texts.push(record.text);
326
- }
327
- return texts;
300
+ function readDelegatedTask(agent, parentSessionOf, resumed) {
301
+ const parentId = agent.session.header.parentSession;
302
+ if (!parentId) return void 0;
303
+ const parent = parentSessionOf(parentId);
304
+ if (parent?.header.id !== parentId) return void 0;
305
+ const own = ownEventsOf(agent.session);
306
+ if (hasRecordedRoute(agent.session, own)) return void 0;
307
+ const descriptor = [...own].reverse().find((event) => event.type === "subagent/descriptor");
308
+ const label = asRecord(descriptor?.data)?.label;
309
+ if (typeof label !== "string" || label.trim() === "") return void 0;
310
+ const task = outstandingDelegation(ownEventsOf(parent), label.trim(), resumed ? agent.id : void 0);
311
+ if (task === void 0) return void 0;
312
+ if (resumed && readInitialTask(own, parentId) !== task.text) return void 0;
313
+ return task;
328
314
  }
329
315
  async function resolveRootSessionId(startId, lookup) {
330
316
  const seen = /* @__PURE__ */ new Set([startId]);
@@ -340,93 +326,108 @@ async function resolveRootSessionId(startId, lookup) {
340
326
  return current;
341
327
  }
342
328
 
343
- // src/server/judge-client.ts
329
+ // src/server/judge-budget.ts
344
330
  var JUDGE_TIMEOUT_MS = 5e3;
345
- async function probeJudge(endpoint, fetchImpl = fetch) {
346
- const startedAt = Date.now();
347
- const elapsed = () => Date.now() - startedAt;
348
- if (endpoint.url.trim() === "" || endpoint.model.trim() === "") {
349
- return { ok: false, latencyMs: elapsed(), reason: "unconfigured" };
331
+ var JudgeBudget = class {
332
+ startedAt = performance.now();
333
+ controller = new AbortController();
334
+ timer = setTimeout(() => this.controller.abort(), JUDGE_TIMEOUT_MS);
335
+ signal;
336
+ constructor(parent) {
337
+ this.signal = parent === void 0 ? this.controller.signal : AbortSignal.any([parent, this.controller.signal]);
350
338
  }
351
- const controller = new AbortController();
352
- const timer = setTimeout(() => controller.abort(), JUDGE_TIMEOUT_MS);
353
- let timedOut = false;
354
- const onTimeout = () => {
355
- timedOut = true;
356
- };
357
- controller.signal.addEventListener("abort", onTimeout);
358
- try {
339
+ elapsed() {
340
+ return Math.round(performance.now() - this.startedAt);
341
+ }
342
+ expired() {
343
+ if (performance.now() - this.startedAt >= JUDGE_TIMEOUT_MS) this.controller.abort();
344
+ return this.controller.signal.aborted;
345
+ }
346
+ check() {
347
+ this.expired();
348
+ this.signal.throwIfAborted();
349
+ }
350
+ /** Stop waiting at the deadline even if the operation ignores its signal. */
351
+ async run(operation) {
352
+ this.check();
353
+ let onAbort;
354
+ const aborted = new Promise((_, reject) => {
355
+ onAbort = () => reject(this.signal.reason);
356
+ this.signal.addEventListener("abort", onAbort, { once: true });
357
+ });
358
+ try {
359
+ const result = await Promise.race([aborted, Promise.resolve().then(() => {
360
+ this.check();
361
+ return operation(this.signal);
362
+ })]);
363
+ this.check();
364
+ return result;
365
+ } finally {
366
+ this.signal.removeEventListener("abort", onAbort);
367
+ }
368
+ }
369
+ dispose() {
370
+ clearTimeout(this.timer);
371
+ }
372
+ };
373
+
374
+ // src/server/judge-client.ts
375
+ async function requestJudge(budget, endpoint, body, fetchImpl) {
376
+ return budget.run(async (signal) => {
359
377
  const response = await fetchImpl(endpoint.url.trim(), {
360
378
  method: "POST",
361
379
  headers: {
362
380
  "content-type": "application/json",
363
381
  ...endpoint.apiKey.trim() === "" ? {} : { authorization: `Bearer ${endpoint.apiKey.trim()}` }
364
382
  },
365
- body: JSON.stringify(buildProbeRequest(endpoint.model.trim())),
366
- signal: controller.signal
383
+ body: JSON.stringify(body),
384
+ signal
367
385
  });
368
- if (!response.ok) return { ok: false, latencyMs: elapsed(), reason: "unreachable" };
369
- const payload = await response.json();
370
- return readJudgeAnswer(payload, [{
386
+ signal.throwIfAborted();
387
+ if (!response.ok) throw new Error("Judge endpoint failed");
388
+ return response.json();
389
+ });
390
+ }
391
+ async function probeJudge(endpoint, fetchImpl = fetch) {
392
+ if (endpoint.url.trim() === "" || endpoint.model.trim() === "") {
393
+ return { ok: false, latencyMs: 0, reason: "unconfigured" };
394
+ }
395
+ const budget = new JudgeBudget();
396
+ try {
397
+ const payload = await requestJudge(budget, endpoint, buildProbeRequest(endpoint.model.trim()), fetchImpl);
398
+ const options = [{
371
399
  id: Number(PROBE_OPTION_ID),
372
400
  enabled: true,
373
401
  description: "",
374
402
  provider: "",
375
403
  model: "",
376
404
  effort: ""
377
- }]).kind === "row" ? { ok: true, latencyMs: elapsed() } : { ok: false, latencyMs: elapsed(), reason: "unmatched" };
405
+ }];
406
+ return readJudgeAnswer(payload, options).kind === "row" ? { ok: true, latencyMs: budget.elapsed() } : { ok: false, latencyMs: budget.elapsed(), reason: "unmatched" };
378
407
  } catch {
379
- return { ok: false, latencyMs: elapsed(), reason: timedOut ? "timeout" : "unreachable" };
408
+ return { ok: false, latencyMs: budget.elapsed(), reason: budget.expired() ? "timeout" : "unreachable" };
380
409
  } finally {
381
- clearTimeout(timer);
382
- controller.signal.removeEventListener("abort", onTimeout);
383
- }
384
- }
385
- async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch) {
386
- const startedAt = Date.now();
387
- const elapsed = () => Date.now() - startedAt;
388
- if (endpoint.url.trim() === "" || endpoint.model.trim() === "" || rows.length === 0) {
389
- return { kind: "fallback", reason: "unreachable", latencyMs: elapsed(), prompt: "" };
390
- }
391
- const body = buildJudgeRequest(rows, endpoint.model.trim(), subject);
392
- const prompt = formatJudgeRequest(body);
393
- const controller = new AbortController();
394
- const timer = setTimeout(() => controller.abort(), JUDGE_TIMEOUT_MS);
395
- let timedOut = false;
396
- const onTimeout = () => {
397
- timedOut = true;
398
- };
399
- controller.signal.addEventListener("abort", onTimeout);
410
+ budget.dispose();
411
+ }
412
+ }
413
+ async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch, sharedBudget) {
414
+ const budget = sharedBudget ?? new JudgeBudget();
415
+ const model = endpoint.model.trim();
416
+ let metrics;
400
417
  try {
401
- const response = await fetchImpl(endpoint.url.trim(), {
402
- method: "POST",
403
- headers: {
404
- "content-type": "application/json",
405
- // Sent only when there is a key: an unauthenticated local endpoint
406
- // would otherwise receive an empty Bearer and reject the call itself.
407
- ...endpoint.apiKey.trim() === "" ? {} : { authorization: `Bearer ${endpoint.apiKey.trim()}` }
408
- },
409
- body: JSON.stringify(body),
410
- signal: controller.signal
411
- });
412
- if (!response.ok) {
413
- return { kind: "fallback", reason: "unreachable", latencyMs: elapsed(), prompt };
418
+ if (endpoint.url.trim() === "" || model === "" || rows.length === 0) {
419
+ return { kind: "fallback", reason: "unreachable", latencyMs: budget.elapsed() };
414
420
  }
415
- const payload = await response.json();
421
+ budget.check();
422
+ metrics = { judgeModel: model, optionCount: rows.length, subjectLength: subject.length };
423
+ const payload = await requestJudge(budget, endpoint, buildJudgeRequest(rows, model, subject), fetchImpl);
416
424
  const decision = readJudgeAnswer(payload, rows);
417
- if (decision.kind === "empty") {
418
- return { kind: "fallback", reason: "unmatched", latencyMs: elapsed(), prompt };
419
- }
420
- if (decision.kind === "unmatched") {
421
- return { kind: "fallback", reason: "unmatched", latencyMs: elapsed(), prompt };
422
- }
423
- return { kind: "matched", row: decision.row, latencyMs: elapsed(), prompt };
425
+ return decision.kind === "row" ? { kind: "matched", row: decision.row, latencyMs: budget.elapsed(), metrics } : { kind: "fallback", reason: "unmatched", latencyMs: budget.elapsed(), metrics };
424
426
  } catch {
425
- const reason = timedOut ? "timeout" : "unreachable";
426
- return { kind: "fallback", reason, latencyMs: elapsed(), prompt };
427
+ const reason = budget.expired() ? "timeout" : "unreachable";
428
+ return { kind: "fallback", reason, latencyMs: budget.elapsed(), metrics };
427
429
  } finally {
428
- clearTimeout(timer);
429
- controller.signal.removeEventListener("abort", onTimeout);
430
+ if (sharedBudget === void 0) budget.dispose();
430
431
  }
431
432
  }
432
433
 
@@ -434,9 +435,174 @@ async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch) {
434
435
  import * as fs from "node:fs/promises";
435
436
  import * as path from "node:path";
436
437
 
437
- // node_modules/.pnpm/@deepseek-ai+dsh-home-paths@0.2.2-rc.3_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-home-paths/lib/index.js
438
+ // node_modules/.pnpm/@deepseek-ai+dsh-atomic-write@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1_@deepseek_ca9e1604dff4cfed60dc2e8ae0867925/node_modules/@deepseek-ai/dsh-atomic-write/lib/index.js
439
+ import { createHash, randomBytes } from "node:crypto";
440
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
441
+ import { dirname } from "node:path";
442
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
443
+
444
+ // node_modules/.pnpm/@deepseek-ai+dsh-error@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1/node_modules/@deepseek-ai/dsh-error/lib/index.js
445
+ var HarnessError = class extends Error {
446
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
447
+ code;
448
+ constructor(message, code, options) {
449
+ super(message, options);
450
+ this.code = code;
451
+ this.name = new.target.name;
452
+ }
453
+ };
454
+
455
+ // node_modules/.pnpm/@deepseek-ai+dsh-atomic-write@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1_@deepseek_ca9e1604dff4cfed60dc2e8ae0867925/node_modules/@deepseek-ai/dsh-atomic-write/lib/index.js
456
+ var WINDOWS_TRANSIENT_RENAME_ERRORS = /* @__PURE__ */ new Set([
457
+ "EACCES",
458
+ "EBUSY",
459
+ "EPERM"
460
+ ]);
461
+ var WINDOWS_RENAME_RETRY_INITIAL_MS = 20;
462
+ var WINDOWS_RENAME_RETRY_MAX_MS = 200;
463
+ var WINDOWS_RENAME_RETRY_LIMIT = 8;
464
+ function isTransientWindowsRenameError(error) {
465
+ if (process.platform !== "win32") return false;
466
+ return WINDOWS_TRANSIENT_RENAME_ERRORS.has(error?.code ?? "");
467
+ }
468
+ async function renameAtomicTemp(temp, filename) {
469
+ let delay = WINDOWS_RENAME_RETRY_INITIAL_MS;
470
+ for (let retries = 0; ; retries += 1) {
471
+ try {
472
+ await rename(temp, filename);
473
+ return;
474
+ } catch (error) {
475
+ if (!isTransientWindowsRenameError(error)) throw error;
476
+ if (retries >= WINDOWS_RENAME_RETRY_LIMIT) throw error;
477
+ }
478
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
479
+ delay = Math.min(delay * 2, WINDOWS_RENAME_RETRY_MAX_MS);
480
+ }
481
+ }
482
+ async function writeFileAtomic(filename, content, options) {
483
+ await mkdir(dirname(filename), {
484
+ recursive: true,
485
+ ...options.dirMode === void 0 ? {} : { mode: options.dirMode }
486
+ });
487
+ const temp = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
488
+ try {
489
+ await writeFile(temp, content, {
490
+ mode: options.mode,
491
+ flag: "wx"
492
+ });
493
+ await renameAtomicTemp(temp, filename);
494
+ } catch (error) {
495
+ await rm(temp, { force: true });
496
+ throw error;
497
+ }
498
+ }
499
+ async function isLockContention(error, lockPath) {
500
+ const code = error?.code;
501
+ if (code === "EEXIST") return true;
502
+ if (code !== "EPERM") return false;
503
+ try {
504
+ await lstat(lockPath);
505
+ return true;
506
+ } catch {
507
+ return false;
508
+ }
509
+ }
510
+ function holderExited(record2) {
511
+ if (!/^\d+\n$/.test(record2)) return false;
512
+ const pid = Number(record2.trim());
513
+ if (pid === 0 || pid > 2147483647) return false;
514
+ if (pid === process.pid) return false;
515
+ try {
516
+ process.kill(pid, 0);
517
+ return false;
518
+ } catch (error) {
519
+ return error.code === "ESRCH";
520
+ }
521
+ }
522
+ async function readLockRecord(lockPath) {
523
+ try {
524
+ return await readFile(lockPath, "utf8");
525
+ } catch (error) {
526
+ return;
527
+ }
528
+ }
529
+ async function takeOverExitedLock(lockPath) {
530
+ const record2 = await readLockRecord(lockPath);
531
+ if (record2 === void 0 || !holderExited(record2)) return false;
532
+ const claim = `${lockPath}.takeover-${createHash("sha256").update(record2).digest("hex").slice(0, 16)}`;
533
+ try {
534
+ await writeFile(claim, `${process.pid}
535
+ `, {
536
+ mode: 384,
537
+ flag: "wx"
538
+ });
539
+ } catch (error) {
540
+ const code = error.code;
541
+ if (code === "EEXIST" || code === "EPERM") return false;
542
+ throw error;
543
+ }
544
+ try {
545
+ if (await readLockRecord(lockPath) !== record2 || !holderExited(record2)) return false;
546
+ try {
547
+ await rm(lockPath, { force: true });
548
+ } catch (error) {
549
+ return false;
550
+ }
551
+ return true;
552
+ } finally {
553
+ await rm(claim, { force: true }).catch((error) => {
554
+ });
555
+ }
556
+ }
557
+ var LOCK_RETRY_INITIAL_MS = 20;
558
+ var LOCK_RETRY_MAX_MS = 200;
559
+ var DEFAULT_LOCK_WAIT_MS = 2e3;
560
+ var FileLockError = class extends HarnessError {
561
+ code;
562
+ /** The contended `<filename>.lock` path. */
563
+ lockPath;
564
+ constructor(lockPath) {
565
+ super(`atomic-write: timed out waiting for the writer lock at ${lockPath}`, "FILE_LOCK_TIMEOUT");
566
+ this.name = "FileLockError";
567
+ this.code = "FILE_LOCK_TIMEOUT";
568
+ this.lockPath = lockPath;
569
+ }
570
+ };
571
+ async function withFileLock(filename, operation, options) {
572
+ const lockPath = `${filename}.lock`;
573
+ const deadline = Date.now() + (options?.waitMs ?? DEFAULT_LOCK_WAIT_MS);
574
+ let delay = LOCK_RETRY_INITIAL_MS;
575
+ let retriedUnconfirmedPermissionError = false;
576
+ for (; ; ) {
577
+ options?.signal?.throwIfAborted();
578
+ try {
579
+ await writeFile(lockPath, `${process.pid}
580
+ `, {
581
+ mode: 384,
582
+ flag: "wx"
583
+ });
584
+ break;
585
+ } catch (error) {
586
+ if (!await isLockContention(error, lockPath)) {
587
+ if (process.platform !== "win32" || error?.code !== "EPERM" || retriedUnconfirmedPermissionError) throw error;
588
+ retriedUnconfirmedPermissionError = true;
589
+ } else if (await takeOverExitedLock(lockPath)) continue;
590
+ }
591
+ if (Date.now() >= deadline) throw new FileLockError(lockPath);
592
+ await setTimeout$1(delay, void 0, { signal: options?.signal });
593
+ delay = Math.min(delay * 2, LOCK_RETRY_MAX_MS);
594
+ }
595
+ try {
596
+ options?.signal?.throwIfAborted();
597
+ return await operation();
598
+ } finally {
599
+ await rm(lockPath, { force: true });
600
+ }
601
+ }
602
+
603
+ // node_modules/.pnpm/@deepseek-ai+dsh-home-paths@0.2.3-alpha.2_@deepseek-ai+cordis@4.2.0-alpha.1/node_modules/@deepseek-ai/dsh-home-paths/lib/index.js
438
604
  import { homedir } from "node:os";
439
- import { basename, dirname, join, resolve } from "node:path";
605
+ import { basename, dirname as dirname2, join, resolve } from "node:path";
440
606
  var DSH_HOME_DIR_NAME = ".dsh";
441
607
  var DEFAULT_DSH_HOME_DISPLAY = `~/${DSH_HOME_DIR_NAME}`;
442
608
  var DSH_HOME_ENV = "DSH_HOME";
@@ -464,104 +630,112 @@ function dshHomePath(...segments) {
464
630
  // src/server/log-store.ts
465
631
  var LOG_KEEP = 200;
466
632
  var LOG_PAGE_LIMIT = 10;
633
+ var REASONS = [
634
+ "unreachable",
635
+ "timeout",
636
+ "unmatched",
637
+ "incomplete",
638
+ "unavailable-route"
639
+ ];
640
+ function record(value) {
641
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
642
+ }
643
+ function text(value) {
644
+ return typeof value === "string" ? value : "";
645
+ }
646
+ function count(value) {
647
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
648
+ }
649
+ function readMetrics(value) {
650
+ const item = record(value);
651
+ if (item === void 0) return void 0;
652
+ return {
653
+ judgeModel: text(item.judgeModel),
654
+ optionCount: count(item.optionCount),
655
+ subjectLength: count(item.subjectLength)
656
+ };
657
+ }
467
658
  function readEntry(value) {
468
- if (typeof value !== "object" || value === null) return void 0;
469
- const record = value;
470
- const text = (key) => typeof record[key] === "string" ? record[key] : "";
471
- const count = (key) => typeof record[key] === "number" && Number.isFinite(record[key]) ? record[key] : 0;
659
+ const item = record(value);
660
+ if (item === void 0) return void 0;
661
+ const reason = REASONS.find((candidate) => candidate === item.reason);
662
+ const metrics = readMetrics(item.metrics);
472
663
  return {
473
- typeId: typeof record.typeId === "number" ? record.typeId : null,
474
- provider: text("provider"),
475
- model: text("model"),
476
- effort: text("effort"),
477
- ...typeof record.reason === "string" ? { reason: record.reason } : {},
478
- at: count("at"),
479
- latencyMs: count("latencyMs"),
480
- parentTitle: text("parentTitle"),
481
- childLabel: text("childLabel"),
482
- prompt: text("prompt")
664
+ typeId: count(item.typeId) || null,
665
+ provider: text(item.provider),
666
+ model: text(item.model),
667
+ effort: text(item.effort),
668
+ ...reason === void 0 ? {} : { reason },
669
+ at: count(item.at),
670
+ latencyMs: count(item.latencyMs),
671
+ ...metrics === void 0 ? {} : { metrics }
483
672
  };
484
673
  }
674
+ function newest(entries) {
675
+ return entries.sort((left, right) => right.at - left.at).slice(0, LOG_KEEP);
676
+ }
485
677
  var LogStore = class {
486
678
  entries = [];
487
- filePath;
488
- /** The initial read, so an append issued before it lands cannot be overwritten by it. */
489
- loading = null;
490
- /** Writes are chained, so two appends cannot interleave their file replaces. */
679
+ pending = [];
680
+ loading;
491
681
  writing = Promise.resolve();
492
- /**
493
- * @param filePath - where the log lives; defaults to this plugin's own
494
- * directory under the DSH home.
495
- */
682
+ filePath;
496
683
  constructor(filePath = dshHomePath("dsh-subagent-judge-dispatch", "judgements.json")) {
497
684
  this.filePath = filePath;
498
685
  }
499
- /**
500
- * Load what a previous process wrote.
501
- *
502
- * A missing, unreadable or malformed file leaves the log empty; the next
503
- * append rewrites it. This method never rejects, because a broken log must
504
- * never stop a judgement.
505
- */
506
686
  init() {
507
- this.loading ??= this.load();
687
+ this.loading ??= this.readDisk().then((entries) => {
688
+ this.entries = entries;
689
+ }).catch(() => {
690
+ });
508
691
  return this.loading;
509
692
  }
510
- /** Read the file once and adopt what it holds. */
511
- async load() {
512
- try {
513
- const raw = await fs.readFile(this.filePath, "utf-8");
514
- const parsed = JSON.parse(raw);
515
- const list = Array.isArray(parsed) ? parsed : [];
516
- const stored = list.map(readEntry).filter((entry) => entry !== void 0);
517
- this.entries = [...this.entries, ...stored].slice(0, LOG_KEEP);
518
- } catch {
519
- }
520
- }
521
- /**
522
- * Append one entry, dropping the oldest beyond {@link LOG_KEEP}, and write.
523
- *
524
- * The write starts at once rather than on a timer: a judgement is rare enough
525
- * that coalescing buys nothing, and a delayed write is a record a hard exit
526
- * can lose.
527
- *
528
- * @param entry - the entry to append.
529
- */
530
693
  append(entry) {
531
- this.entries = [entry, ...this.entries].slice(0, LOG_KEEP);
532
- const previous = this.writing;
533
- const afterLoad = this.loading === null ? previous : this.loading.then(() => previous);
534
- this.writing = afterLoad.then(() => this.write()).catch((error) => {
535
- console.warn("[dsh-subagent-judge-dispatch] \u5224\u65AD\u65E5\u5FD7\u5199\u4E0D\u8FDB\u78C1\u76D8\uFF1A", error);
694
+ const sanitized = readEntry(entry);
695
+ if (sanitized === void 0) return;
696
+ this.pending.unshift(sanitized);
697
+ this.writing = this.writing.then(() => this.write()).catch(() => {
698
+ this.pending = newest(this.pending);
699
+ console.warn("[dsh-subagent-judge-dispatch] \u5224\u65AD\u65E5\u5FD7\u5199\u4E0D\u8FDB\u78C1\u76D8");
536
700
  });
537
701
  }
538
- /**
539
- * Read the whole kept log, newest first.
540
- * @returns a detached copy, so a reader cannot mutate the stored entries.
541
- */
542
702
  list() {
543
- return this.entries.map((entry) => ({ ...entry }));
703
+ return this.snapshot(this.entries);
704
+ }
705
+ async readLatest() {
706
+ const previous = this.entries;
707
+ const disk = await this.readDisk().catch(() => this.entries);
708
+ return this.snapshot(this.entries === previous ? disk : this.entries);
709
+ }
710
+ snapshot(entries) {
711
+ return newest([...this.pending, ...entries]).map((entry) => structuredClone(entry));
544
712
  }
545
- /** Wait for the initial read and the writes already started to land. */
546
713
  async flush() {
547
- if (this.loading !== null) await this.loading;
714
+ await this.loading;
548
715
  await this.writing;
549
716
  }
550
- /** Replace the file atomically, so a crash cannot leave half a document. */
551
- async write() {
552
- const temp = `${this.filePath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;
717
+ async readDisk() {
553
718
  try {
554
- await fs.mkdir(path.dirname(this.filePath), { recursive: true });
555
- await fs.writeFile(temp, JSON.stringify(this.entries, null, 2), "utf-8");
556
- await fs.rename(temp, this.filePath);
719
+ const parsed = JSON.parse(await fs.readFile(this.filePath, "utf8"));
720
+ return Array.isArray(parsed) ? newest(parsed.map(readEntry).filter((entry) => entry !== void 0)) : [];
557
721
  } catch (error) {
558
- try {
559
- await fs.unlink(temp);
560
- } catch {
561
- }
722
+ if (error instanceof SyntaxError || error.code === "ENOENT") return [];
562
723
  throw error;
563
724
  }
564
725
  }
726
+ async write() {
727
+ if (this.pending.length === 0) return;
728
+ await this.loading;
729
+ await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 448 });
730
+ await withFileLock(this.filePath, async () => {
731
+ const stored = await this.readDisk();
732
+ const count2 = this.pending.length;
733
+ const merged = newest([...this.pending, ...stored]);
734
+ await writeFileAtomic(this.filePath, JSON.stringify(merged, null, 2), { mode: 384 });
735
+ this.pending.length -= count2;
736
+ this.entries = merged;
737
+ });
738
+ }
565
739
  };
566
740
 
567
741
  // src/server/router.ts
@@ -594,8 +768,8 @@ function createFetchRoutes(face) {
594
768
  fetch: async () => {
595
769
  try {
596
770
  const config = face.config();
597
- const text = buildPreview(selectableRows(config.rows), config.judgeModel.trim());
598
- return sendJson(200, { ok: true, preview: text });
771
+ const text2 = buildPreview(selectableRows(config.rows), config.judgeModel.trim());
772
+ return sendJson(200, { ok: true, preview: text2 });
599
773
  } catch (err) {
600
774
  return sendJson(500, { ok: false, error: describe(err) });
601
775
  }
@@ -627,7 +801,7 @@ function describe(err) {
627
801
 
628
802
  // src/index.ts
629
803
  var name = SETTINGS_NAMESPACE;
630
- var inject = ["credentials", "sessions", "sessionTitle"];
804
+ var inject = ["credentials", "sessions"];
631
805
  var JUDGED_LIMIT = 500;
632
806
  var JudgedChildren = class {
633
807
  seen = /* @__PURE__ */ new Set();
@@ -645,9 +819,10 @@ var JudgedChildren = class {
645
819
  };
646
820
  function apply(ctx, config) {
647
821
  const log = new LogStore();
822
+ const lifetime = new AbortController();
648
823
  const judged = new JudgedChildren();
649
824
  let apiKey = "";
650
- const logReady = log.init();
825
+ void log.init();
651
826
  const resolvedConfig = () => readPluginConfig(config);
652
827
  const refreshKey = async () => {
653
828
  try {
@@ -666,51 +841,64 @@ function apply(ctx, config) {
666
841
  "dsh-subagent-judge-dispatch: settings page policy"
667
842
  );
668
843
  });
669
- ctx.on("agent/created", async (payload) => {
670
- const agent = payload?.agent;
671
- if (agent === void 0 || !isSubagent(agent) || judged.has(agent.id)) return;
844
+ ctx.on("agent/created", async ({ agent, source, signal }) => {
845
+ const cancellation = signal === void 0 ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);
846
+ if (agent === void 0 || !isSubagent(agent) || judged.has(agent.id) || cancellation.aborted) return;
847
+ if (source !== "startup" && source !== "resume") return;
848
+ const budget = new JudgeBudget(cancellation);
672
849
  try {
673
850
  const lookup = (id) => ctx.sessions.get(id);
674
851
  const parentId = agent.session.header.parentSession;
675
- const rootId = parentId ? await resolveRootSessionId(
676
- parentId,
677
- async (id) => lookup(id)?.header ?? (await ctx.get("sessionPersistence")?.stat(id))?.header
678
- ) : void 0;
852
+ const rootId = parentId ? await budget.run(() => resolveRootSessionId(parentId, async (id) => {
853
+ budget.check();
854
+ return lookup(id)?.header ?? (await ctx.get("sessionPersistence")?.stat(id))?.header;
855
+ })) : void 0;
679
856
  const cfg = resolvedConfig();
680
- if (!isJudgeUsable(cfg, rootId) || judged.has(agent.id)) return;
857
+ if (cancellation.aborted || !isJudgeUsable(cfg, rootId) || judged.has(agent.id)) return;
858
+ const task = readDelegatedTask(agent, lookup, source === "resume");
859
+ if (task === void 0 || task.explicitRoute) return;
681
860
  judged.add(agent.id);
682
- const label = readChildLabel(agent);
683
- const taskText = readDelegatedTask(agent, lookup);
861
+ const { label, text: taskText } = task;
684
862
  const inherited = agent.model.current() ?? { provider: "", model: "" };
685
863
  const outcome = await judgeTaskType(
686
864
  { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },
687
865
  selectableRows(cfg.rows),
688
- composeJudgeSubject(label, taskText)
866
+ composeJudgeSubject(label, taskText),
867
+ fetch,
868
+ budget
689
869
  );
690
- const decision = decideRewrite(outcome);
870
+ let decision = decideRewrite(outcome);
871
+ let routeFailure;
691
872
  if (decision.kind === "rewrite") {
692
- agent.model.select({
693
- provider: decision.rewrite.provider,
694
- model: decision.rewrite.model,
695
- reasoningEffort: decision.rewrite.reasoningEffort
696
- });
873
+ const route = decision.rewrite;
874
+ const llm = ctx.get("llm");
875
+ const allowed = () => ctx.get("subagentModelSelection")?.allowedRoutes()?.some(
876
+ (pair) => pair.provider === route.provider && pair.model === route.model
877
+ ) === true;
878
+ try {
879
+ if (llm === void 0 || !allowed()) throw new Error("Unavailable child route");
880
+ await budget.run((preflightSignal) => llm.resolveCallConfig(route, preflightSignal));
881
+ if (!allowed()) throw new Error("Child route no longer allowed");
882
+ if (cancellation.aborted || !isJudgeUsable(resolvedConfig(), rootId) || hasRecordedRoute(agent.session)) return;
883
+ budget.check();
884
+ agent.model.select(route);
885
+ } catch {
886
+ decision = { kind: "none" };
887
+ routeFailure = budget.expired() ? "timeout" : "unavailable-route";
888
+ }
697
889
  }
698
- if (cfg.logEnabled) {
699
- await logReady;
700
- log.append(buildEntry(ctx, rootId, inherited, decision, outcome, label, taskText));
890
+ if (resolvedConfig().logEnabled && !cancellation.aborted) {
891
+ log.append(buildEntry(inherited, decision, outcome, budget.elapsed(), routeFailure));
701
892
  }
702
893
  } catch {
894
+ } finally {
895
+ budget.dispose();
703
896
  }
704
897
  });
705
898
  ctx.inject(["connection"], (connectionCtx) => {
706
899
  const routes = createFetchRoutes({
707
900
  config: resolvedConfig,
708
- // 路由可能在磁盘读完之后才被问到,也可能在之前:先等那一次读,别把「还没读完」
709
- // 报成「一条都没有」。
710
- log: async () => {
711
- await logReady;
712
- return log.list();
713
- },
901
+ log: () => log.readLatest(),
714
902
  apiKey: () => apiKey
715
903
  });
716
904
  const disposers = routes.map(
@@ -723,14 +911,15 @@ function apply(ctx, config) {
723
911
  });
724
912
  ctx.effect(
725
913
  () => () => {
726
- void log.flush();
914
+ lifetime.abort();
915
+ return log.flush();
727
916
  },
728
917
  "dsh-subagent-judge-dispatch: judgement log flush"
729
918
  );
730
919
  }
731
- function buildEntry(ctx, rootId, resolved, decision, outcome, label, taskText) {
920
+ function buildEntry(resolved, decision, outcome, latencyMs, routeFailure) {
732
921
  const matched = decision.kind === "rewrite";
733
- const reason = outcomeReason(outcome, decision);
922
+ const reason = routeFailure ?? outcomeReason(outcome, decision);
734
923
  return {
735
924
  typeId: matched && outcome.kind === "matched" ? outcome.row.id : null,
736
925
  provider: matched ? decision.rewrite.provider : resolved.provider,
@@ -738,27 +927,10 @@ function buildEntry(ctx, rootId, resolved, decision, outcome, label, taskText) {
738
927
  effort: matched ? decision.rewrite.reasoningEffort : typeof resolved.reasoningEffort === "string" ? resolved.reasoningEffort : "",
739
928
  ...reason === void 0 ? {} : { reason },
740
929
  at: Date.now(),
741
- latencyMs: outcome.latencyMs,
742
- parentTitle: readParentTitle(ctx, rootId),
743
- childLabel: truncate(label !== "" ? label : taskText),
744
- prompt: outcome.prompt
930
+ latencyMs,
931
+ ...outcome.metrics === void 0 ? {} : { metrics: outcome.metrics }
745
932
  };
746
933
  }
747
- function readParentTitle(ctx, rootId) {
748
- if (rootId === void 0) return "";
749
- try {
750
- const session = ctx.sessions.get(rootId);
751
- if (session === void 0) return rootId;
752
- const title = ctx.sessionTitle.get(session)?.title;
753
- return typeof title === "string" && title.trim() !== "" ? title.trim() : rootId;
754
- } catch {
755
- return rootId;
756
- }
757
- }
758
- function truncate(text, max = 60) {
759
- const collapsed = text.replace(/\s+/g, " ").trim();
760
- return collapsed.length <= max ? collapsed : `${collapsed.slice(0, max - 1)}\u2026`;
761
- }
762
934
  export {
763
935
  Config,
764
936
  JUDGE_API_KEY_REF,