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

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}`;
@@ -131,6 +131,7 @@ function readJudgeAnswer(payload, rows) {
131
131
 
132
132
  // src/server/config.ts
133
133
  var TypeRowSchema = z.object({
134
+ stableId: z.string().default(""),
134
135
  /** Whether this type takes part in judgements; a row written before the switch existed counts as on. */
135
136
  enabled: z.boolean().default(true),
136
137
  /** Criterion text the judge reads for this type. */
@@ -158,6 +159,7 @@ var Config = z.object({
158
159
  function readPluginConfig(refs) {
159
160
  const stored = refs.rows.get();
160
161
  const rows = numberTypeRows((Array.isArray(stored) ? stored : []).map((row) => ({
162
+ stableId: typeof row?.stableId === "string" ? row.stableId : "",
161
163
  enabled: row?.enabled !== false,
162
164
  description: typeof row?.description === "string" ? row.description : "",
163
165
  provider: typeof row?.provider === "string" ? row.provider : "",
@@ -204,127 +206,113 @@ function outcomeReason(outcome, decision) {
204
206
 
205
207
  // src/server/identity.ts
206
208
  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();
209
+ return session.ownEvents?.() ?? session.snapshotEvents(session.inheritedEventCount ?? 0);
213
210
  }
214
211
  function isSubagent(agent) {
215
212
  const fromHeader = agent.session.header.delegationDepth;
216
213
  const fromOptions = agent.options.subagentDepth;
217
- const depth = Math.max(
214
+ return Math.max(
218
215
  typeof fromHeader === "number" && Number.isSafeInteger(fromHeader) ? fromHeader : 0,
219
216
  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;
217
+ ) >= 1;
218
+ }
219
+ function asRecord(value) {
220
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
221
+ }
222
+ function readText(block) {
223
+ const data = asRecord(block);
224
+ return data?.type === "text" && typeof data.text === "string" ? data.text : void 0;
225
+ }
226
+ var RETURN_GUIDANCE = "Your final answer is delivered automatically if your parent is still online.";
227
+ function readInitialTask(events, parentId) {
228
+ for (const event of events) {
229
+ const inserted = asRecord(event.data)?.inserted;
230
+ const messages = event.type === "user/message" ? [event.data] : event.type === "agent/inbox/spliced" && Array.isArray(inserted) ? inserted : [];
231
+ for (const value of messages) {
232
+ const message = asRecord(value);
233
+ const source = asRecord(message?.source);
234
+ if (source?.kind !== "agent-message" || source.form !== "relay" || source.senderSessionId !== parentId) continue;
235
+ if (!Array.isArray(message?.content)) return void 0;
236
+ const [sender, ...body] = message.content;
237
+ if (!/^Agent .+ sent a message: $/.test(readText(sender) ?? "")) return void 0;
238
+ const texts = body.map(readText).filter((text2) => text2 !== void 0);
239
+ if (texts.length > 1 && texts.at(-1)?.startsWith(RETURN_GUIDANCE)) texts.pop();
240
+ return texts.join("\n").trim() || void 0;
251
241
  }
252
242
  }
253
- return "";
243
+ return void 0;
254
244
  }
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;
245
+ var DELEGATION_TOOLS = /* @__PURE__ */ new Set(["subagent", "subagent_fork"]);
246
+ function matchingCall(data, label) {
247
+ if (!DELEGATION_TOOLS.has(data.name)) return void 0;
248
+ let args = data.arguments;
249
+ if (typeof args === "string") {
250
+ try {
251
+ args = JSON.parse(args);
252
+ } catch {
253
+ return void 0;
254
+ }
255
+ }
256
+ const call = asRecord(args);
257
+ if (typeof call?.description !== "string" || call.description.trim() !== label || typeof call.prompt !== "string" || call.prompt.trim() === "") return void 0;
284
258
  return {
285
- prompt: record.prompt,
286
- ...typeof record.description === "string" ? { description: record.description } : {}
259
+ label,
260
+ text: call.prompt.trim(),
261
+ explicitRoute: call.provider !== void 0 || call.model !== void 0 || call.reasoning_effort !== void 0
287
262
  };
288
263
  }
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");
264
+ function outstandingDelegation(events, label, resumedChildId) {
265
+ const end = resumedChildId === void 0 ? events.length : events.findIndex(
266
+ (event) => event.type === "subagent/catalog" && asRecord(event.data)?.childId === resumedChildId
267
+ );
268
+ const finished = /* @__PURE__ */ new Set();
269
+ let task;
270
+ for (let index = end - 1; index >= 0; index -= 1) {
271
+ const { type, data: value } = events[index];
272
+ if (type === "step/start" || type === "step/end" || type === "turn/start" || type === "turn/end") break;
273
+ const data = asRecord(value);
274
+ if (data === void 0) continue;
275
+ switch (type) {
276
+ case "tool/result": {
277
+ const id = asRecord(data.message)?.toolCallId;
278
+ if (typeof id === "string") finished.add(`native:${id}`);
279
+ break;
280
+ }
281
+ case "tool/ptc-dispatch":
282
+ if (typeof data.subCallId === "string") finished.add(`ptc:${data.subCallId}`);
283
+ break;
284
+ case "tool/call":
285
+ case "tool/ptc-dispatch-start": {
286
+ const ptc = type === "tool/ptc-dispatch-start";
287
+ const id = ptc ? data.subCallId : data.callId;
288
+ if (typeof id !== "string" || finished.has(`${ptc ? "ptc" : "native"}:${id}`)) break;
289
+ const candidate = matchingCall(data, label);
290
+ if (candidate === void 0) break;
291
+ if (task !== void 0) return void 0;
292
+ task = candidate;
293
+ break;
294
+ }
295
+ }
307
296
  }
308
- return [];
297
+ return task;
309
298
  }
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;
299
+ function hasRecordedRoute(session, events = ownEventsOf(session)) {
300
+ return events.some((event) => event.type === "model/selection" || event.type === "request/header");
316
301
  }
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;
302
+ function readDelegatedTask(agent, parentSessionOf, resumed) {
303
+ const parentId = agent.session.header.parentSession;
304
+ if (!parentId) return void 0;
305
+ const parent = parentSessionOf(parentId);
306
+ if (parent?.header.id !== parentId) return void 0;
307
+ const own = ownEventsOf(agent.session);
308
+ if (hasRecordedRoute(agent.session, own)) return void 0;
309
+ const descriptor = [...own].reverse().find((event) => event.type === "subagent/descriptor");
310
+ const label = asRecord(descriptor?.data)?.label;
311
+ if (typeof label !== "string" || label.trim() === "") return void 0;
312
+ const task = outstandingDelegation(ownEventsOf(parent), label.trim(), resumed ? agent.id : void 0);
313
+ if (task === void 0) return void 0;
314
+ if (resumed && readInitialTask(own, parentId) !== task.text) return void 0;
315
+ return task;
328
316
  }
329
317
  async function resolveRootSessionId(startId, lookup) {
330
318
  const seen = /* @__PURE__ */ new Set([startId]);
@@ -340,93 +328,108 @@ async function resolveRootSessionId(startId, lookup) {
340
328
  return current;
341
329
  }
342
330
 
343
- // src/server/judge-client.ts
331
+ // src/server/judge-budget.ts
344
332
  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" };
333
+ var JudgeBudget = class {
334
+ startedAt = performance.now();
335
+ controller = new AbortController();
336
+ timer = setTimeout(() => this.controller.abort(), JUDGE_TIMEOUT_MS);
337
+ signal;
338
+ constructor(parent) {
339
+ this.signal = parent === void 0 ? this.controller.signal : AbortSignal.any([parent, this.controller.signal]);
350
340
  }
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 {
341
+ elapsed() {
342
+ return Math.round(performance.now() - this.startedAt);
343
+ }
344
+ expired() {
345
+ if (performance.now() - this.startedAt >= JUDGE_TIMEOUT_MS) this.controller.abort();
346
+ return this.controller.signal.aborted;
347
+ }
348
+ check() {
349
+ this.expired();
350
+ this.signal.throwIfAborted();
351
+ }
352
+ /** Stop waiting at the deadline even if the operation ignores its signal. */
353
+ async run(operation) {
354
+ this.check();
355
+ let onAbort;
356
+ const aborted = new Promise((_, reject) => {
357
+ onAbort = () => reject(this.signal.reason);
358
+ this.signal.addEventListener("abort", onAbort, { once: true });
359
+ });
360
+ try {
361
+ const result = await Promise.race([aborted, Promise.resolve().then(() => {
362
+ this.check();
363
+ return operation(this.signal);
364
+ })]);
365
+ this.check();
366
+ return result;
367
+ } finally {
368
+ this.signal.removeEventListener("abort", onAbort);
369
+ }
370
+ }
371
+ dispose() {
372
+ clearTimeout(this.timer);
373
+ }
374
+ };
375
+
376
+ // src/server/judge-client.ts
377
+ async function requestJudge(budget, endpoint, body, fetchImpl) {
378
+ return budget.run(async (signal) => {
359
379
  const response = await fetchImpl(endpoint.url.trim(), {
360
380
  method: "POST",
361
381
  headers: {
362
382
  "content-type": "application/json",
363
383
  ...endpoint.apiKey.trim() === "" ? {} : { authorization: `Bearer ${endpoint.apiKey.trim()}` }
364
384
  },
365
- body: JSON.stringify(buildProbeRequest(endpoint.model.trim())),
366
- signal: controller.signal
385
+ body: JSON.stringify(body),
386
+ signal
367
387
  });
368
- if (!response.ok) return { ok: false, latencyMs: elapsed(), reason: "unreachable" };
369
- const payload = await response.json();
370
- return readJudgeAnswer(payload, [{
388
+ signal.throwIfAborted();
389
+ if (!response.ok) throw new Error("Judge endpoint failed");
390
+ return response.json();
391
+ });
392
+ }
393
+ async function probeJudge(endpoint, fetchImpl = fetch) {
394
+ if (endpoint.url.trim() === "" || endpoint.model.trim() === "") {
395
+ return { ok: false, latencyMs: 0, reason: "unconfigured" };
396
+ }
397
+ const budget = new JudgeBudget();
398
+ try {
399
+ const payload = await requestJudge(budget, endpoint, buildProbeRequest(endpoint.model.trim()), fetchImpl);
400
+ const options = [{
371
401
  id: Number(PROBE_OPTION_ID),
372
402
  enabled: true,
373
403
  description: "",
374
404
  provider: "",
375
405
  model: "",
376
406
  effort: ""
377
- }]).kind === "row" ? { ok: true, latencyMs: elapsed() } : { ok: false, latencyMs: elapsed(), reason: "unmatched" };
407
+ }];
408
+ return readJudgeAnswer(payload, options).kind === "row" ? { ok: true, latencyMs: budget.elapsed() } : { ok: false, latencyMs: budget.elapsed(), reason: "unmatched" };
378
409
  } catch {
379
- return { ok: false, latencyMs: elapsed(), reason: timedOut ? "timeout" : "unreachable" };
410
+ return { ok: false, latencyMs: budget.elapsed(), reason: budget.expired() ? "timeout" : "unreachable" };
380
411
  } 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);
412
+ budget.dispose();
413
+ }
414
+ }
415
+ async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch, sharedBudget) {
416
+ const budget = sharedBudget ?? new JudgeBudget();
417
+ const model = endpoint.model.trim();
418
+ let metrics;
400
419
  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 };
420
+ if (endpoint.url.trim() === "" || model === "" || rows.length === 0) {
421
+ return { kind: "fallback", reason: "unreachable", latencyMs: budget.elapsed() };
414
422
  }
415
- const payload = await response.json();
423
+ budget.check();
424
+ metrics = { judgeModel: model, optionCount: rows.length, subjectLength: subject.length };
425
+ const payload = await requestJudge(budget, endpoint, buildJudgeRequest(rows, model, subject), fetchImpl);
416
426
  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 };
427
+ return decision.kind === "row" ? { kind: "matched", row: decision.row, latencyMs: budget.elapsed(), metrics } : { kind: "fallback", reason: "unmatched", latencyMs: budget.elapsed(), metrics };
424
428
  } catch {
425
- const reason = timedOut ? "timeout" : "unreachable";
426
- return { kind: "fallback", reason, latencyMs: elapsed(), prompt };
429
+ const reason = budget.expired() ? "timeout" : "unreachable";
430
+ return { kind: "fallback", reason, latencyMs: budget.elapsed(), metrics };
427
431
  } finally {
428
- clearTimeout(timer);
429
- controller.signal.removeEventListener("abort", onTimeout);
432
+ if (sharedBudget === void 0) budget.dispose();
430
433
  }
431
434
  }
432
435
 
@@ -434,9 +437,174 @@ async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch) {
434
437
  import * as fs from "node:fs/promises";
435
438
  import * as path from "node:path";
436
439
 
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
440
+ // node_modules/.pnpm/@deepseek-ai+dsh-atomic-write@0.2.3-alpha.3_@deepseek-ai+cordis@4.2.0-alpha.2_@deepseek_69d89bc51c1ad90ac0788ea4be89e3f9/node_modules/@deepseek-ai/dsh-atomic-write/lib/index.js
441
+ import { createHash, randomBytes } from "node:crypto";
442
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
443
+ import { dirname } from "node:path";
444
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
445
+
446
+ // node_modules/.pnpm/@deepseek-ai+dsh-error@0.2.3-alpha.3_@deepseek-ai+cordis@4.2.0-alpha.2/node_modules/@deepseek-ai/dsh-error/lib/index.js
447
+ var HarnessError = class extends Error {
448
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
449
+ code;
450
+ constructor(message, code, options) {
451
+ super(message, options);
452
+ this.code = code;
453
+ this.name = new.target.name;
454
+ }
455
+ };
456
+
457
+ // node_modules/.pnpm/@deepseek-ai+dsh-atomic-write@0.2.3-alpha.3_@deepseek-ai+cordis@4.2.0-alpha.2_@deepseek_69d89bc51c1ad90ac0788ea4be89e3f9/node_modules/@deepseek-ai/dsh-atomic-write/lib/index.js
458
+ var WINDOWS_TRANSIENT_RENAME_ERRORS = /* @__PURE__ */ new Set([
459
+ "EACCES",
460
+ "EBUSY",
461
+ "EPERM"
462
+ ]);
463
+ var WINDOWS_RENAME_RETRY_INITIAL_MS = 20;
464
+ var WINDOWS_RENAME_RETRY_MAX_MS = 200;
465
+ var WINDOWS_RENAME_RETRY_LIMIT = 8;
466
+ function isTransientWindowsRenameError(error) {
467
+ if (process.platform !== "win32") return false;
468
+ return WINDOWS_TRANSIENT_RENAME_ERRORS.has(error?.code ?? "");
469
+ }
470
+ async function renameAtomicTemp(temp, filename) {
471
+ let delay = WINDOWS_RENAME_RETRY_INITIAL_MS;
472
+ for (let retries = 0; ; retries += 1) {
473
+ try {
474
+ await rename(temp, filename);
475
+ return;
476
+ } catch (error) {
477
+ if (!isTransientWindowsRenameError(error)) throw error;
478
+ if (retries >= WINDOWS_RENAME_RETRY_LIMIT) throw error;
479
+ }
480
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
481
+ delay = Math.min(delay * 2, WINDOWS_RENAME_RETRY_MAX_MS);
482
+ }
483
+ }
484
+ async function writeFileAtomic(filename, content, options) {
485
+ await mkdir(dirname(filename), {
486
+ recursive: true,
487
+ ...options.dirMode === void 0 ? {} : { mode: options.dirMode }
488
+ });
489
+ const temp = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
490
+ try {
491
+ await writeFile(temp, content, {
492
+ mode: options.mode,
493
+ flag: "wx"
494
+ });
495
+ await renameAtomicTemp(temp, filename);
496
+ } catch (error) {
497
+ await rm(temp, { force: true });
498
+ throw error;
499
+ }
500
+ }
501
+ async function isLockContention(error, lockPath) {
502
+ const code = error?.code;
503
+ if (code === "EEXIST") return true;
504
+ if (code !== "EPERM") return false;
505
+ try {
506
+ await lstat(lockPath);
507
+ return true;
508
+ } catch {
509
+ return false;
510
+ }
511
+ }
512
+ function holderExited(record2) {
513
+ if (!/^\d+\n$/.test(record2)) return false;
514
+ const pid = Number(record2.trim());
515
+ if (pid === 0 || pid > 2147483647) return false;
516
+ if (pid === process.pid) return false;
517
+ try {
518
+ process.kill(pid, 0);
519
+ return false;
520
+ } catch (error) {
521
+ return error.code === "ESRCH";
522
+ }
523
+ }
524
+ async function readLockRecord(lockPath) {
525
+ try {
526
+ return await readFile(lockPath, "utf8");
527
+ } catch (error) {
528
+ return;
529
+ }
530
+ }
531
+ async function takeOverExitedLock(lockPath) {
532
+ const record2 = await readLockRecord(lockPath);
533
+ if (record2 === void 0 || !holderExited(record2)) return false;
534
+ const claim = `${lockPath}.takeover-${createHash("sha256").update(record2).digest("hex").slice(0, 16)}`;
535
+ try {
536
+ await writeFile(claim, `${process.pid}
537
+ `, {
538
+ mode: 384,
539
+ flag: "wx"
540
+ });
541
+ } catch (error) {
542
+ const code = error.code;
543
+ if (code === "EEXIST" || code === "EPERM") return false;
544
+ throw error;
545
+ }
546
+ try {
547
+ if (await readLockRecord(lockPath) !== record2 || !holderExited(record2)) return false;
548
+ try {
549
+ await rm(lockPath, { force: true });
550
+ } catch (error) {
551
+ return false;
552
+ }
553
+ return true;
554
+ } finally {
555
+ await rm(claim, { force: true }).catch((error) => {
556
+ });
557
+ }
558
+ }
559
+ var LOCK_RETRY_INITIAL_MS = 20;
560
+ var LOCK_RETRY_MAX_MS = 200;
561
+ var DEFAULT_LOCK_WAIT_MS = 2e3;
562
+ var FileLockError = class extends HarnessError {
563
+ code;
564
+ /** The contended `<filename>.lock` path. */
565
+ lockPath;
566
+ constructor(lockPath) {
567
+ super(`atomic-write: timed out waiting for the writer lock at ${lockPath}`, "FILE_LOCK_TIMEOUT");
568
+ this.name = "FileLockError";
569
+ this.code = "FILE_LOCK_TIMEOUT";
570
+ this.lockPath = lockPath;
571
+ }
572
+ };
573
+ async function withFileLock(filename, operation, options) {
574
+ const lockPath = `${filename}.lock`;
575
+ const deadline = Date.now() + (options?.waitMs ?? DEFAULT_LOCK_WAIT_MS);
576
+ let delay = LOCK_RETRY_INITIAL_MS;
577
+ let retriedUnconfirmedPermissionError = false;
578
+ for (; ; ) {
579
+ options?.signal?.throwIfAborted();
580
+ try {
581
+ await writeFile(lockPath, `${process.pid}
582
+ `, {
583
+ mode: 384,
584
+ flag: "wx"
585
+ });
586
+ break;
587
+ } catch (error) {
588
+ if (!await isLockContention(error, lockPath)) {
589
+ if (process.platform !== "win32" || error?.code !== "EPERM" || retriedUnconfirmedPermissionError) throw error;
590
+ retriedUnconfirmedPermissionError = true;
591
+ } else if (await takeOverExitedLock(lockPath)) continue;
592
+ }
593
+ if (Date.now() >= deadline) throw new FileLockError(lockPath);
594
+ await setTimeout$1(delay, void 0, { signal: options?.signal });
595
+ delay = Math.min(delay * 2, LOCK_RETRY_MAX_MS);
596
+ }
597
+ try {
598
+ options?.signal?.throwIfAborted();
599
+ return await operation();
600
+ } finally {
601
+ await rm(lockPath, { force: true });
602
+ }
603
+ }
604
+
605
+ // node_modules/.pnpm/@deepseek-ai+dsh-home-paths@0.2.3-alpha.3_@deepseek-ai+cordis@4.2.0-alpha.2/node_modules/@deepseek-ai/dsh-home-paths/lib/index.js
438
606
  import { homedir } from "node:os";
439
- import { basename, dirname, join, resolve } from "node:path";
607
+ import { basename, dirname as dirname2, join, resolve } from "node:path";
440
608
  var DSH_HOME_DIR_NAME = ".dsh";
441
609
  var DEFAULT_DSH_HOME_DISPLAY = `~/${DSH_HOME_DIR_NAME}`;
442
610
  var DSH_HOME_ENV = "DSH_HOME";
@@ -464,110 +632,121 @@ function dshHomePath(...segments) {
464
632
  // src/server/log-store.ts
465
633
  var LOG_KEEP = 200;
466
634
  var LOG_PAGE_LIMIT = 10;
635
+ var REASONS = [
636
+ "unreachable",
637
+ "timeout",
638
+ "unmatched",
639
+ "incomplete",
640
+ "unavailable-route"
641
+ ];
642
+ function record(value) {
643
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
644
+ }
645
+ function text(value) {
646
+ return typeof value === "string" ? value : "";
647
+ }
648
+ function count(value) {
649
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
650
+ }
651
+ function readMetrics(value) {
652
+ const item = record(value);
653
+ if (item === void 0) return void 0;
654
+ return {
655
+ judgeModel: text(item.judgeModel),
656
+ optionCount: count(item.optionCount),
657
+ subjectLength: count(item.subjectLength)
658
+ };
659
+ }
467
660
  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;
661
+ const item = record(value);
662
+ if (item === void 0) return void 0;
663
+ const reason = REASONS.find((candidate) => candidate === item.reason);
664
+ const metrics = readMetrics(item.metrics);
472
665
  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")
666
+ typeId: count(item.typeId) || null,
667
+ ...typeof item.typeKey === "string" && /^[0-9a-f-]{36}$/i.test(item.typeKey) ? { typeKey: item.typeKey } : {},
668
+ provider: text(item.provider),
669
+ model: text(item.model),
670
+ effort: text(item.effort),
671
+ ...reason === void 0 ? {} : { reason },
672
+ at: count(item.at),
673
+ latencyMs: count(item.latencyMs),
674
+ ...metrics === void 0 ? {} : { metrics }
483
675
  };
484
676
  }
677
+ function newest(entries) {
678
+ return entries.sort((left, right) => right.at - left.at).slice(0, LOG_KEEP);
679
+ }
485
680
  var LogStore = class {
486
681
  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. */
682
+ pending = [];
683
+ loading;
491
684
  writing = Promise.resolve();
492
- /**
493
- * @param filePath - where the log lives; defaults to this plugin's own
494
- * directory under the DSH home.
495
- */
685
+ filePath;
496
686
  constructor(filePath = dshHomePath("dsh-subagent-judge-dispatch", "judgements.json")) {
497
687
  this.filePath = filePath;
498
688
  }
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
689
  init() {
507
- this.loading ??= this.load();
690
+ this.loading ??= this.readDisk().then((entries) => {
691
+ this.entries = entries;
692
+ }).catch(() => {
693
+ });
508
694
  return this.loading;
509
695
  }
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
696
  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);
697
+ const sanitized = readEntry(entry);
698
+ if (sanitized === void 0) return;
699
+ this.pending.unshift(sanitized);
700
+ this.writing = this.writing.then(() => this.write()).catch(() => {
701
+ this.pending = newest(this.pending);
702
+ console.warn("[dsh-subagent-judge-dispatch] \u5224\u65AD\u65E5\u5FD7\u5199\u4E0D\u8FDB\u78C1\u76D8");
536
703
  });
537
704
  }
538
- /**
539
- * Read the whole kept log, newest first.
540
- * @returns a detached copy, so a reader cannot mutate the stored entries.
541
- */
542
705
  list() {
543
- return this.entries.map((entry) => ({ ...entry }));
706
+ return this.snapshot(this.entries);
707
+ }
708
+ async readLatest() {
709
+ const previous = this.entries;
710
+ const disk = await this.readDisk();
711
+ return this.snapshot(this.entries === previous ? disk : this.entries);
712
+ }
713
+ snapshot(entries) {
714
+ return newest([...this.pending, ...entries]).map((entry) => structuredClone(entry));
544
715
  }
545
- /** Wait for the initial read and the writes already started to land. */
546
716
  async flush() {
547
- if (this.loading !== null) await this.loading;
717
+ await this.loading;
548
718
  await this.writing;
549
719
  }
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)}`;
720
+ async readDisk() {
553
721
  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);
722
+ const parsed = JSON.parse(await fs.readFile(this.filePath, "utf8"));
723
+ if (!Array.isArray(parsed)) throw new Error("Invalid log format");
724
+ return newest(parsed.map(readEntry).filter((entry) => entry !== void 0));
557
725
  } catch (error) {
558
- try {
559
- await fs.unlink(temp);
560
- } catch {
561
- }
726
+ if (error.code === "ENOENT") return [];
562
727
  throw error;
563
728
  }
564
729
  }
730
+ async write() {
731
+ if (this.pending.length === 0) return;
732
+ await this.loading;
733
+ await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 448 });
734
+ await withFileLock(this.filePath, async () => {
735
+ const stored = await this.readDisk();
736
+ const count2 = this.pending.length;
737
+ const merged = newest([...this.pending, ...stored]);
738
+ await writeFileAtomic(this.filePath, JSON.stringify(merged, null, 2), { mode: 384 });
739
+ this.pending.length -= count2;
740
+ this.entries = merged;
741
+ });
742
+ }
565
743
  };
566
744
 
567
745
  // src/server/router.ts
568
746
  var LOG_ROUTE_PATH = "/api/dsh-subagent-judge-dispatch/log";
569
747
  var PREVIEW_ROUTE_PATH = "/api/dsh-subagent-judge-dispatch/preview";
570
748
  var PROBE_ROUTE_PATH = "/api/dsh-subagent-judge-dispatch/probe";
749
+ var SAMPLE_ROUTE_PATH = "/api/dsh-subagent-judge-dispatch/sample";
571
750
  function sendJson(status, body) {
572
751
  return new Response(JSON.stringify(body), {
573
752
  status,
@@ -594,8 +773,8 @@ function createFetchRoutes(face) {
594
773
  fetch: async () => {
595
774
  try {
596
775
  const config = face.config();
597
- const text = buildPreview(selectableRows(config.rows), config.judgeModel.trim());
598
- return sendJson(200, { ok: true, preview: text });
776
+ const text2 = buildPreview(selectableRows(config.rows), config.judgeModel.trim());
777
+ return sendJson(200, { ok: true, preview: text2 });
599
778
  } catch (err) {
600
779
  return sendJson(500, { ok: false, error: describe(err) });
601
780
  }
@@ -619,7 +798,22 @@ function createFetchRoutes(face) {
619
798
  }
620
799
  }
621
800
  };
622
- return [log, preview, probe];
801
+ const sample = {
802
+ path: SAMPLE_ROUTE_PATH,
803
+ methods: ["POST"],
804
+ requestBody: "buffered",
805
+ fetch: async (request) => {
806
+ try {
807
+ const body = await request.json();
808
+ const task = typeof body === "object" && body !== null && "task" in body ? body.task : void 0;
809
+ if (typeof task !== "string" || task.trim() === "" || task.length > 1e4) return sendJson(400, { ok: false });
810
+ return sendJson(200, await face.sample(task));
811
+ } catch {
812
+ return sendJson(500, { ok: false });
813
+ }
814
+ }
815
+ };
816
+ return [log, preview, probe, sample];
623
817
  }
624
818
  function describe(err) {
625
819
  return err instanceof Error ? err.message : String(err);
@@ -627,7 +821,7 @@ function describe(err) {
627
821
 
628
822
  // src/index.ts
629
823
  var name = SETTINGS_NAMESPACE;
630
- var inject = ["credentials", "sessions", "sessionTitle"];
824
+ var inject = ["credentials", "sessions"];
631
825
  var JUDGED_LIMIT = 500;
632
826
  var JudgedChildren = class {
633
827
  seen = /* @__PURE__ */ new Set();
@@ -645,9 +839,10 @@ var JudgedChildren = class {
645
839
  };
646
840
  function apply(ctx, config) {
647
841
  const log = new LogStore();
842
+ const lifetime = new AbortController();
648
843
  const judged = new JudgedChildren();
649
844
  let apiKey = "";
650
- const logReady = log.init();
845
+ void log.init();
651
846
  const resolvedConfig = () => readPluginConfig(config);
652
847
  const refreshKey = async () => {
653
848
  try {
@@ -666,52 +861,102 @@ function apply(ctx, config) {
666
861
  "dsh-subagent-judge-dispatch: settings page policy"
667
862
  );
668
863
  });
669
- ctx.on("agent/created", async (payload) => {
670
- const agent = payload?.agent;
671
- if (agent === void 0 || !isSubagent(agent) || judged.has(agent.id)) return;
864
+ ctx.on("agent/created", async ({ agent, source, signal }) => {
865
+ const cancellation = signal === void 0 ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);
866
+ if (agent === void 0 || !isSubagent(agent) || judged.has(agent.id) || cancellation.aborted) return;
867
+ if (source !== "startup" && source !== "resume") return;
868
+ const budget = new JudgeBudget(cancellation);
672
869
  try {
673
870
  const lookup = (id) => ctx.sessions.get(id);
674
871
  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;
872
+ const rootId = parentId ? await budget.run(() => resolveRootSessionId(parentId, async (id) => {
873
+ budget.check();
874
+ return lookup(id)?.header ?? (await ctx.get("sessionPersistence")?.stat(id))?.header;
875
+ })) : void 0;
679
876
  const cfg = resolvedConfig();
680
- if (!isJudgeUsable(cfg, rootId) || judged.has(agent.id)) return;
877
+ if (cancellation.aborted || !isJudgeUsable(cfg, rootId) || judged.has(agent.id)) return;
878
+ const task = readDelegatedTask(agent, lookup, source === "resume");
879
+ if (task === void 0 || task.explicitRoute) return;
681
880
  judged.add(agent.id);
682
- const label = readChildLabel(agent);
683
- const taskText = readDelegatedTask(agent, lookup);
881
+ const { label, text: taskText } = task;
684
882
  const inherited = agent.model.current() ?? { provider: "", model: "" };
685
883
  const outcome = await judgeTaskType(
686
884
  { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },
687
885
  selectableRows(cfg.rows),
688
- composeJudgeSubject(label, taskText)
886
+ composeJudgeSubject(label, taskText),
887
+ fetch,
888
+ budget
689
889
  );
690
- const decision = decideRewrite(outcome);
890
+ let decision = decideRewrite(outcome);
891
+ let routeFailure;
691
892
  if (decision.kind === "rewrite") {
692
- agent.model.select({
693
- provider: decision.rewrite.provider,
694
- model: decision.rewrite.model,
695
- reasoningEffort: decision.rewrite.reasoningEffort
696
- });
893
+ const route = decision.rewrite;
894
+ const llm = ctx.get("llm");
895
+ const allowed = () => ctx.get("subagentModelSelection")?.allowedRoutes()?.some(
896
+ (pair) => pair.provider === route.provider && pair.model === route.model
897
+ ) === true;
898
+ try {
899
+ if (llm === void 0 || !allowed()) throw new Error("Unavailable child route");
900
+ await budget.run((preflightSignal) => llm.resolveCallConfig(route, preflightSignal));
901
+ if (!allowed()) throw new Error("Child route no longer allowed");
902
+ if (cancellation.aborted || !isJudgeUsable(resolvedConfig(), rootId) || hasRecordedRoute(agent.session)) return;
903
+ budget.check();
904
+ agent.model.select(route);
905
+ } catch {
906
+ decision = { kind: "none" };
907
+ routeFailure = budget.expired() ? "timeout" : "unavailable-route";
908
+ }
697
909
  }
698
- if (cfg.logEnabled) {
699
- await logReady;
700
- log.append(buildEntry(ctx, rootId, inherited, decision, outcome, label, taskText));
910
+ if (resolvedConfig().logEnabled && !cancellation.aborted) {
911
+ log.append(buildEntry(inherited, decision, outcome, budget.elapsed(), routeFailure));
701
912
  }
702
913
  } catch {
914
+ } finally {
915
+ budget.dispose();
703
916
  }
704
917
  });
705
918
  ctx.inject(["connection"], (connectionCtx) => {
706
919
  const routes = createFetchRoutes({
707
920
  config: resolvedConfig,
708
- // 路由可能在磁盘读完之后才被问到,也可能在之前:先等那一次读,别把「还没读完」
709
- // 报成「一条都没有」。
710
- log: async () => {
711
- await logReady;
712
- return log.list();
713
- },
714
- apiKey: () => apiKey
921
+ log: () => log.readLatest(),
922
+ apiKey: () => apiKey,
923
+ sample: async (task) => {
924
+ const cfg = resolvedConfig();
925
+ const budget = new JudgeBudget(lifetime.signal);
926
+ try {
927
+ const outcome = await judgeTaskType(
928
+ { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },
929
+ selectableRows(cfg.rows),
930
+ composeJudgeSubject("", task),
931
+ fetch,
932
+ budget
933
+ );
934
+ const decision = decideRewrite(outcome);
935
+ if (decision.kind !== "rewrite") return { ok: false, reason: outcomeReason(outcome, decision) };
936
+ const route = decision.rewrite;
937
+ const llm = ctx.get("llm");
938
+ const allowed = () => ctx.get("subagentModelSelection")?.allowedRoutes()?.some(
939
+ (pair) => pair.provider === route.provider && pair.model === route.model
940
+ ) === true;
941
+ try {
942
+ if (llm === void 0 || !allowed()) throw new Error("Unavailable child route");
943
+ await budget.run((signal) => llm.resolveCallConfig(route, signal));
944
+ if (!allowed()) throw new Error("Child route no longer allowed");
945
+ budget.check();
946
+ return { ok: true, typeId: outcome.kind === "matched" ? outcome.row.id : null, route, valid: true };
947
+ } catch {
948
+ return {
949
+ ok: false,
950
+ typeId: outcome.kind === "matched" ? outcome.row.id : null,
951
+ route,
952
+ valid: false,
953
+ reason: budget.expired() ? "timeout" : "unavailable-route"
954
+ };
955
+ }
956
+ } finally {
957
+ budget.dispose();
958
+ }
959
+ }
715
960
  });
716
961
  const disposers = routes.map(
717
962
  (route) => connectionCtx.connection.fetch.register(route)
@@ -723,42 +968,27 @@ function apply(ctx, config) {
723
968
  });
724
969
  ctx.effect(
725
970
  () => () => {
726
- void log.flush();
971
+ lifetime.abort();
972
+ return log.flush();
727
973
  },
728
974
  "dsh-subagent-judge-dispatch: judgement log flush"
729
975
  );
730
976
  }
731
- function buildEntry(ctx, rootId, resolved, decision, outcome, label, taskText) {
977
+ function buildEntry(resolved, decision, outcome, latencyMs, routeFailure) {
732
978
  const matched = decision.kind === "rewrite";
733
- const reason = outcomeReason(outcome, decision);
979
+ const reason = routeFailure ?? outcomeReason(outcome, decision);
734
980
  return {
735
981
  typeId: matched && outcome.kind === "matched" ? outcome.row.id : null,
982
+ ...matched && outcome.kind === "matched" && outcome.row.stableId ? { typeKey: outcome.row.stableId } : {},
736
983
  provider: matched ? decision.rewrite.provider : resolved.provider,
737
984
  model: matched ? decision.rewrite.model : resolved.model,
738
985
  effort: matched ? decision.rewrite.reasoningEffort : typeof resolved.reasoningEffort === "string" ? resolved.reasoningEffort : "",
739
986
  ...reason === void 0 ? {} : { reason },
740
987
  at: Date.now(),
741
- latencyMs: outcome.latencyMs,
742
- parentTitle: readParentTitle(ctx, rootId),
743
- childLabel: truncate(label !== "" ? label : taskText),
744
- prompt: outcome.prompt
988
+ latencyMs,
989
+ ...outcome.metrics === void 0 ? {} : { metrics: outcome.metrics }
745
990
  };
746
991
  }
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
992
  export {
763
993
  Config,
764
994
  JUDGE_API_KEY_REF,