@lynn123411/dsh-subagent-judge-dispatch 0.6.6 → 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
@@ -1,3 +1,12 @@
1
+ // src/enablement.ts
2
+ var DEFAULT_ENABLED = true;
3
+ var SETTINGS_NAMESPACE = "dsh-subagent-judge-dispatch";
4
+ function enabledFor(overrides, fallback, sessionId) {
5
+ if (sessionId === void 0 || overrides === null || typeof overrides !== "object" || !Object.hasOwn(overrides, sessionId)) return fallback;
6
+ const choice = overrides[sessionId];
7
+ return typeof choice === "boolean" ? choice : fallback;
8
+ }
9
+
1
10
  // src/server/config.ts
2
11
  import z from "@deepseek-ai/schemastery";
3
12
 
@@ -50,11 +59,11 @@ function composeJudgeSubject(label, taskText) {
50
59
 
51
60
  ${task}`;
52
61
  }
53
- function clipTaskText(text) {
54
- if (text.length <= SUBJECT_HEAD_CHARS + SUBJECT_TAIL_CHARS) return text;
55
- const dropped = text.length - SUBJECT_HEAD_CHARS - SUBJECT_TAIL_CHARS;
56
- const head = text.slice(0, SUBJECT_HEAD_CHARS);
57
- 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);
58
67
  return `${head}
59
68
  \u2026 (${dropped} characters omitted) \u2026
60
69
  ${tail}`;
@@ -121,7 +130,6 @@ function readJudgeAnswer(payload, rows) {
121
130
  }
122
131
 
123
132
  // src/server/config.ts
124
- var SETTINGS_NAMESPACE = "dsh-subagent-judge-dispatch";
125
133
  var TypeRowSchema = z.object({
126
134
  /** Whether this type takes part in judgements; a row written before the switch existed counts as on. */
127
135
  enabled: z.boolean().default(true),
@@ -135,8 +143,9 @@ var TypeRowSchema = z.object({
135
143
  effort: z.string().default("")
136
144
  });
137
145
  var Config = z.object({
138
- /** Whether a judgement may rewrite a subagent's model and effort. */
139
- enabled: z.boolean().default(true).volatile(),
146
+ /** Default for conversations without their own choice. */
147
+ enabled: z.boolean().default(DEFAULT_ENABLED).volatile(),
148
+ sessionOverrides: z.dict(z.boolean()).default({}).volatile(),
140
149
  /** Whether judgements are written to the plugin's own log. */
141
150
  logEnabled: z.boolean().default(true).volatile(),
142
151
  /** Judge service address, as the reader typed it; the path is appended when a call is made. */
@@ -156,15 +165,16 @@ function readPluginConfig(refs) {
156
165
  effort: typeof row?.effort === "string" ? row.effort : ""
157
166
  })));
158
167
  return {
159
- enabled: refs.enabled.get() !== false,
168
+ enabled: refs.enabled.get() ?? DEFAULT_ENABLED,
169
+ sessionOverrides: refs.sessionOverrides.get(),
160
170
  logEnabled: refs.logEnabled.get() !== false,
161
171
  endpointUrl: resolveEndpointUrl(refs.endpointUrl.get()),
162
172
  judgeModel: typeof refs.judgeModel.get() === "string" ? refs.judgeModel.get() : "",
163
173
  rows
164
174
  };
165
175
  }
166
- function isJudgeUsable(config) {
167
- if (!config.enabled) return false;
176
+ function isJudgeUsable(config, rootSessionId) {
177
+ if (!enabledFor(config.sessionOverrides, config.enabled, rootSessionId)) return false;
168
178
  if (config.endpointUrl.trim() === "" || config.judgeModel.trim() === "") return false;
169
179
  return selectableRows(config.rows).length > 0;
170
180
  }
@@ -194,134 +204,121 @@ function outcomeReason(outcome, decision) {
194
204
 
195
205
  // src/server/identity.ts
196
206
  function ownEventsOf(session) {
197
- if (typeof session.ownEvents === "function") return session.ownEvents();
198
- const inherited = session.inheritedEventCount;
199
- if (typeof inherited === "number" && Number.isSafeInteger(inherited) && inherited > 0) {
200
- return session.snapshotEvents(inherited);
201
- }
202
- return session.snapshotEvents();
207
+ return session.ownEvents?.() ?? session.snapshotEvents(session.inheritedEventCount ?? 0);
203
208
  }
204
209
  function isSubagent(agent) {
205
210
  const fromHeader = agent.session.header.delegationDepth;
206
211
  const fromOptions = agent.options.subagentDepth;
207
- const depth = Math.max(
212
+ return Math.max(
208
213
  typeof fromHeader === "number" && Number.isSafeInteger(fromHeader) ? fromHeader : 0,
209
214
  typeof fromOptions === "number" && Number.isSafeInteger(fromOptions) ? fromOptions : 0
210
- );
211
- return depth >= 1;
212
- }
213
- var RETURN_GUIDANCE_PREFIXES = [
214
- "Your parent agent id is ",
215
- "Your final answer is delivered automatically if your "
216
- ];
217
- function isReturnGuidance(text) {
218
- return RETURN_GUIDANCE_PREFIXES.some((prefix) => text.startsWith(prefix));
219
- }
220
- function readChildLabel(agent) {
221
- let found = "";
222
- for (const event of ownEventsOf(agent.session)) {
223
- if (event.type !== "subagent/descriptor") continue;
224
- const data = event.data;
225
- if (typeof data !== "object" || data === null) continue;
226
- const label = data.label;
227
- if (typeof label === "string" && label.trim() !== "") found = label.trim();
228
- }
229
- return found;
230
- }
231
- function readTaskText(agent) {
232
- for (const event of ownEventsOf(agent.session)) {
233
- const candidates = delegationMessagesOf(event);
234
- for (const data of candidates) {
235
- const blocks = textBlocksOf(data);
236
- if (blocks.length > 1 && isReturnGuidance(blocks[blocks.length - 1])) {
237
- blocks.pop();
238
- }
239
- const text = blocks.join("\n").trim();
240
- 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;
241
239
  }
242
240
  }
243
- return "";
241
+ return void 0;
244
242
  }
245
- var DELEGATION_EVENT_TYPES = /* @__PURE__ */ new Set([
246
- "tool/call",
247
- "tool/ptc-dispatch-start"
248
- ]);
249
- function readDelegatedTask(agent, parentSessionOf) {
250
- const own = readTaskText(agent);
251
- if (own !== "") return own;
252
- const parentId = agent.session.header.parentSession;
253
- if (typeof parentId !== "string" || parentId === "") return "";
254
- const parent = parentSessionOf(parentId);
255
- if (parent === void 0 || typeof parent.snapshotEvents !== "function") return "";
256
- const label = readChildLabel(agent);
257
- const events = parent.snapshotEvents();
258
- let fallback = "";
259
- for (let index = events.length - 1; index >= 0; index -= 1) {
260
- const event = events[index];
261
- if (!DELEGATION_EVENT_TYPES.has(event.type)) continue;
262
- const call = delegatedCallOf(event.data);
263
- if (call === void 0) continue;
264
- if (label !== "" && call.description === label) return call.prompt;
265
- if (fallback === "") fallback = call.prompt;
266
- }
267
- return fallback;
268
- }
269
- function delegatedCallOf(data) {
270
- const parsed = argumentsOf(data);
271
- if (typeof parsed !== "object" || parsed === null) return void 0;
272
- const record = parsed;
273
- 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;
274
256
  return {
275
- prompt: record.prompt,
276
- ...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
277
260
  };
278
261
  }
279
- function argumentsOf(data) {
280
- if (typeof data !== "object" || data === null) return void 0;
281
- const raw = data.arguments;
282
- if (typeof raw !== "string") return raw;
283
- try {
284
- return JSON.parse(raw);
285
- } catch {
286
- return void 0;
287
- }
288
- }
289
- function delegationMessagesOf(event) {
290
- if (event.type === "user/message") {
291
- return sourceOf(event.data)?.kind === "user" ? [event.data] : [];
292
- }
293
- if (event.type === "agent/inbox/spliced") {
294
- const inserted = event.data?.inserted;
295
- if (!Array.isArray(inserted)) return [];
296
- 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
+ }
297
294
  }
298
- return [];
299
- }
300
- function sourceOf(data) {
301
- if (typeof data !== "object" || data === null) return void 0;
302
- const source = data.source;
303
- if (typeof source !== "object" || source === null) return void 0;
304
- const kind = source.kind;
305
- return typeof kind === "string" ? { kind } : void 0;
295
+ return task;
306
296
  }
307
- function textBlocksOf(data) {
308
- if (typeof data !== "object" || data === null) return [];
309
- const content = data.content;
310
- if (!Array.isArray(content)) return [];
311
- const texts = [];
312
- for (const block of content) {
313
- if (typeof block !== "object" || block === null) continue;
314
- const record = block;
315
- if (record.type === "text" && typeof record.text === "string") texts.push(record.text);
316
- }
317
- return texts;
297
+ function hasRecordedRoute(session, events = ownEventsOf(session)) {
298
+ return events.some((event) => event.type === "model/selection" || event.type === "request/header");
318
299
  }
319
- function resolveRootSessionId(startId, lookup) {
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;
314
+ }
315
+ async function resolveRootSessionId(startId, lookup) {
320
316
  const seen = /* @__PURE__ */ new Set([startId]);
321
317
  let current = startId;
322
318
  for (let hop = 0; hop < 32; hop += 1) {
323
- const session = lookup(current);
324
- const parent = session?.header.parentSession;
319
+ const header = await lookup(current);
320
+ if (header === void 0 || header.origin !== "subagent" && (header.delegationDepth ?? 0) < 1) return current;
321
+ const parent = header.parentSession;
325
322
  if (typeof parent !== "string" || parent === "" || seen.has(parent)) return current;
326
323
  seen.add(parent);
327
324
  current = parent;
@@ -329,93 +326,108 @@ function resolveRootSessionId(startId, lookup) {
329
326
  return current;
330
327
  }
331
328
 
332
- // src/server/judge-client.ts
329
+ // src/server/judge-budget.ts
333
330
  var JUDGE_TIMEOUT_MS = 5e3;
334
- async function probeJudge(endpoint, fetchImpl = fetch) {
335
- const startedAt = Date.now();
336
- const elapsed = () => Date.now() - startedAt;
337
- if (endpoint.url.trim() === "" || endpoint.model.trim() === "") {
338
- 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]);
339
338
  }
340
- const controller = new AbortController();
341
- const timer = setTimeout(() => controller.abort(), JUDGE_TIMEOUT_MS);
342
- let timedOut = false;
343
- const onTimeout = () => {
344
- timedOut = true;
345
- };
346
- controller.signal.addEventListener("abort", onTimeout);
347
- 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) => {
348
377
  const response = await fetchImpl(endpoint.url.trim(), {
349
378
  method: "POST",
350
379
  headers: {
351
380
  "content-type": "application/json",
352
381
  ...endpoint.apiKey.trim() === "" ? {} : { authorization: `Bearer ${endpoint.apiKey.trim()}` }
353
382
  },
354
- body: JSON.stringify(buildProbeRequest(endpoint.model.trim())),
355
- signal: controller.signal
383
+ body: JSON.stringify(body),
384
+ signal
356
385
  });
357
- if (!response.ok) return { ok: false, latencyMs: elapsed(), reason: "unreachable" };
358
- const payload = await response.json();
359
- 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 = [{
360
399
  id: Number(PROBE_OPTION_ID),
361
400
  enabled: true,
362
401
  description: "",
363
402
  provider: "",
364
403
  model: "",
365
404
  effort: ""
366
- }]).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" };
367
407
  } catch {
368
- return { ok: false, latencyMs: elapsed(), reason: timedOut ? "timeout" : "unreachable" };
408
+ return { ok: false, latencyMs: budget.elapsed(), reason: budget.expired() ? "timeout" : "unreachable" };
369
409
  } finally {
370
- clearTimeout(timer);
371
- controller.signal.removeEventListener("abort", onTimeout);
372
- }
373
- }
374
- async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch) {
375
- const startedAt = Date.now();
376
- const elapsed = () => Date.now() - startedAt;
377
- if (endpoint.url.trim() === "" || endpoint.model.trim() === "" || rows.length === 0) {
378
- return { kind: "fallback", reason: "unreachable", latencyMs: elapsed(), prompt: "" };
379
- }
380
- const body = buildJudgeRequest(rows, endpoint.model.trim(), subject);
381
- const prompt = formatJudgeRequest(body);
382
- const controller = new AbortController();
383
- const timer = setTimeout(() => controller.abort(), JUDGE_TIMEOUT_MS);
384
- let timedOut = false;
385
- const onTimeout = () => {
386
- timedOut = true;
387
- };
388
- 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;
389
417
  try {
390
- const response = await fetchImpl(endpoint.url.trim(), {
391
- method: "POST",
392
- headers: {
393
- "content-type": "application/json",
394
- // Sent only when there is a key: an unauthenticated local endpoint
395
- // would otherwise receive an empty Bearer and reject the call itself.
396
- ...endpoint.apiKey.trim() === "" ? {} : { authorization: `Bearer ${endpoint.apiKey.trim()}` }
397
- },
398
- body: JSON.stringify(body),
399
- signal: controller.signal
400
- });
401
- if (!response.ok) {
402
- 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() };
403
420
  }
404
- 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);
405
424
  const decision = readJudgeAnswer(payload, rows);
406
- if (decision.kind === "empty") {
407
- return { kind: "fallback", reason: "unmatched", latencyMs: elapsed(), prompt };
408
- }
409
- if (decision.kind === "unmatched") {
410
- return { kind: "fallback", reason: "unmatched", latencyMs: elapsed(), prompt };
411
- }
412
- 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 };
413
426
  } catch {
414
- const reason = timedOut ? "timeout" : "unreachable";
415
- return { kind: "fallback", reason, latencyMs: elapsed(), prompt };
427
+ const reason = budget.expired() ? "timeout" : "unreachable";
428
+ return { kind: "fallback", reason, latencyMs: budget.elapsed(), metrics };
416
429
  } finally {
417
- clearTimeout(timer);
418
- controller.signal.removeEventListener("abort", onTimeout);
430
+ if (sharedBudget === void 0) budget.dispose();
419
431
  }
420
432
  }
421
433
 
@@ -423,9 +435,174 @@ async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch) {
423
435
  import * as fs from "node:fs/promises";
424
436
  import * as path from "node:path";
425
437
 
426
- // 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
427
604
  import { homedir } from "node:os";
428
- import { basename, dirname, join, resolve } from "node:path";
605
+ import { basename, dirname as dirname2, join, resolve } from "node:path";
429
606
  var DSH_HOME_DIR_NAME = ".dsh";
430
607
  var DEFAULT_DSH_HOME_DISPLAY = `~/${DSH_HOME_DIR_NAME}`;
431
608
  var DSH_HOME_ENV = "DSH_HOME";
@@ -453,104 +630,112 @@ function dshHomePath(...segments) {
453
630
  // src/server/log-store.ts
454
631
  var LOG_KEEP = 200;
455
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
+ }
456
658
  function readEntry(value) {
457
- if (typeof value !== "object" || value === null) return void 0;
458
- const record = value;
459
- const text = (key) => typeof record[key] === "string" ? record[key] : "";
460
- 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);
461
663
  return {
462
- typeId: typeof record.typeId === "number" ? record.typeId : null,
463
- provider: text("provider"),
464
- model: text("model"),
465
- effort: text("effort"),
466
- ...typeof record.reason === "string" ? { reason: record.reason } : {},
467
- at: count("at"),
468
- latencyMs: count("latencyMs"),
469
- parentTitle: text("parentTitle"),
470
- childLabel: text("childLabel"),
471
- 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 }
472
672
  };
473
673
  }
674
+ function newest(entries) {
675
+ return entries.sort((left, right) => right.at - left.at).slice(0, LOG_KEEP);
676
+ }
474
677
  var LogStore = class {
475
678
  entries = [];
476
- filePath;
477
- /** The initial read, so an append issued before it lands cannot be overwritten by it. */
478
- loading = null;
479
- /** Writes are chained, so two appends cannot interleave their file replaces. */
679
+ pending = [];
680
+ loading;
480
681
  writing = Promise.resolve();
481
- /**
482
- * @param filePath - where the log lives; defaults to this plugin's own
483
- * directory under the DSH home.
484
- */
682
+ filePath;
485
683
  constructor(filePath = dshHomePath("dsh-subagent-judge-dispatch", "judgements.json")) {
486
684
  this.filePath = filePath;
487
685
  }
488
- /**
489
- * Load what a previous process wrote.
490
- *
491
- * A missing, unreadable or malformed file leaves the log empty; the next
492
- * append rewrites it. This method never rejects, because a broken log must
493
- * never stop a judgement.
494
- */
495
686
  init() {
496
- this.loading ??= this.load();
687
+ this.loading ??= this.readDisk().then((entries) => {
688
+ this.entries = entries;
689
+ }).catch(() => {
690
+ });
497
691
  return this.loading;
498
692
  }
499
- /** Read the file once and adopt what it holds. */
500
- async load() {
501
- try {
502
- const raw = await fs.readFile(this.filePath, "utf-8");
503
- const parsed = JSON.parse(raw);
504
- const list = Array.isArray(parsed) ? parsed : [];
505
- const stored = list.map(readEntry).filter((entry) => entry !== void 0);
506
- this.entries = [...this.entries, ...stored].slice(0, LOG_KEEP);
507
- } catch {
508
- }
509
- }
510
- /**
511
- * Append one entry, dropping the oldest beyond {@link LOG_KEEP}, and write.
512
- *
513
- * The write starts at once rather than on a timer: a judgement is rare enough
514
- * that coalescing buys nothing, and a delayed write is a record a hard exit
515
- * can lose.
516
- *
517
- * @param entry - the entry to append.
518
- */
519
693
  append(entry) {
520
- this.entries = [entry, ...this.entries].slice(0, LOG_KEEP);
521
- const previous = this.writing;
522
- const afterLoad = this.loading === null ? previous : this.loading.then(() => previous);
523
- this.writing = afterLoad.then(() => this.write()).catch((error) => {
524
- 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");
525
700
  });
526
701
  }
527
- /**
528
- * Read the whole kept log, newest first.
529
- * @returns a detached copy, so a reader cannot mutate the stored entries.
530
- */
531
702
  list() {
532
- 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));
533
712
  }
534
- /** Wait for the initial read and the writes already started to land. */
535
713
  async flush() {
536
- if (this.loading !== null) await this.loading;
714
+ await this.loading;
537
715
  await this.writing;
538
716
  }
539
- /** Replace the file atomically, so a crash cannot leave half a document. */
540
- async write() {
541
- const temp = `${this.filePath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;
717
+ async readDisk() {
542
718
  try {
543
- await fs.mkdir(path.dirname(this.filePath), { recursive: true });
544
- await fs.writeFile(temp, JSON.stringify(this.entries, null, 2), "utf-8");
545
- 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)) : [];
546
721
  } catch (error) {
547
- try {
548
- await fs.unlink(temp);
549
- } catch {
550
- }
722
+ if (error instanceof SyntaxError || error.code === "ENOENT") return [];
551
723
  throw error;
552
724
  }
553
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
+ }
554
739
  };
555
740
 
556
741
  // src/server/router.ts
@@ -583,8 +768,8 @@ function createFetchRoutes(face) {
583
768
  fetch: async () => {
584
769
  try {
585
770
  const config = face.config();
586
- const text = buildPreview(selectableRows(config.rows), config.judgeModel.trim());
587
- 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 });
588
773
  } catch (err) {
589
774
  return sendJson(500, { ok: false, error: describe(err) });
590
775
  }
@@ -616,7 +801,7 @@ function describe(err) {
616
801
 
617
802
  // src/index.ts
618
803
  var name = SETTINGS_NAMESPACE;
619
- var inject = ["credentials", "sessions", "sessionTitle"];
804
+ var inject = ["credentials", "sessions"];
620
805
  var JUDGED_LIMIT = 500;
621
806
  var JudgedChildren = class {
622
807
  seen = /* @__PURE__ */ new Set();
@@ -634,9 +819,10 @@ var JudgedChildren = class {
634
819
  };
635
820
  function apply(ctx, config) {
636
821
  const log = new LogStore();
822
+ const lifetime = new AbortController();
637
823
  const judged = new JudgedChildren();
638
824
  let apiKey = "";
639
- const logReady = log.init();
825
+ void log.init();
640
826
  const resolvedConfig = () => readPluginConfig(config);
641
827
  const refreshKey = async () => {
642
828
  try {
@@ -655,47 +841,64 @@ function apply(ctx, config) {
655
841
  "dsh-subagent-judge-dispatch: settings page policy"
656
842
  );
657
843
  });
658
- ctx.on("agent/created", async (payload) => {
659
- const agent = payload?.agent;
660
- if (agent === void 0) return;
661
- const cfg = resolvedConfig();
662
- if (!isSubagent(agent) || !cfg.enabled) return;
663
- if (judged.has(agent.id)) return;
664
- if (!isJudgeUsable(cfg)) return;
665
- judged.add(agent.id);
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);
666
849
  try {
667
- const label = readChildLabel(agent);
668
- const taskText = readDelegatedTask(agent, (id) => ctx.sessions.get(id));
850
+ const lookup = (id) => ctx.sessions.get(id);
851
+ const parentId = agent.session.header.parentSession;
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;
856
+ const cfg = resolvedConfig();
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;
860
+ judged.add(agent.id);
861
+ const { label, text: taskText } = task;
669
862
  const inherited = agent.model.current() ?? { provider: "", model: "" };
670
863
  const outcome = await judgeTaskType(
671
864
  { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },
672
865
  selectableRows(cfg.rows),
673
- composeJudgeSubject(label, taskText)
866
+ composeJudgeSubject(label, taskText),
867
+ fetch,
868
+ budget
674
869
  );
675
- const decision = decideRewrite(outcome);
870
+ let decision = decideRewrite(outcome);
871
+ let routeFailure;
676
872
  if (decision.kind === "rewrite") {
677
- agent.model.select({
678
- provider: decision.rewrite.provider,
679
- model: decision.rewrite.model,
680
- reasoningEffort: decision.rewrite.reasoningEffort
681
- });
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
+ }
682
889
  }
683
- if (cfg.logEnabled) {
684
- await logReady;
685
- log.append(buildEntry(ctx, agent, inherited, decision, outcome, label, taskText));
890
+ if (resolvedConfig().logEnabled && !cancellation.aborted) {
891
+ log.append(buildEntry(inherited, decision, outcome, budget.elapsed(), routeFailure));
686
892
  }
687
893
  } catch {
894
+ } finally {
895
+ budget.dispose();
688
896
  }
689
897
  });
690
898
  ctx.inject(["connection"], (connectionCtx) => {
691
899
  const routes = createFetchRoutes({
692
900
  config: resolvedConfig,
693
- // 路由可能在磁盘读完之后才被问到,也可能在之前:先等那一次读,别把「还没读完」
694
- // 报成「一条都没有」。
695
- log: async () => {
696
- await logReady;
697
- return log.list();
698
- },
901
+ log: () => log.readLatest(),
699
902
  apiKey: () => apiKey
700
903
  });
701
904
  const disposers = routes.map(
@@ -708,14 +911,15 @@ function apply(ctx, config) {
708
911
  });
709
912
  ctx.effect(
710
913
  () => () => {
711
- void log.flush();
914
+ lifetime.abort();
915
+ return log.flush();
712
916
  },
713
917
  "dsh-subagent-judge-dispatch: judgement log flush"
714
918
  );
715
919
  }
716
- function buildEntry(ctx, agent, resolved, decision, outcome, label, taskText) {
920
+ function buildEntry(resolved, decision, outcome, latencyMs, routeFailure) {
717
921
  const matched = decision.kind === "rewrite";
718
- const reason = outcomeReason(outcome, decision);
922
+ const reason = routeFailure ?? outcomeReason(outcome, decision);
719
923
  return {
720
924
  typeId: matched && outcome.kind === "matched" ? outcome.row.id : null,
721
925
  provider: matched ? decision.rewrite.provider : resolved.provider,
@@ -723,28 +927,10 @@ function buildEntry(ctx, agent, resolved, decision, outcome, label, taskText) {
723
927
  effort: matched ? decision.rewrite.reasoningEffort : typeof resolved.reasoningEffort === "string" ? resolved.reasoningEffort : "",
724
928
  ...reason === void 0 ? {} : { reason },
725
929
  at: Date.now(),
726
- latencyMs: outcome.latencyMs,
727
- parentTitle: readParentTitle(ctx, agent.session.header.parentSession),
728
- childLabel: truncate(label !== "" ? label : taskText),
729
- prompt: outcome.prompt
930
+ latencyMs,
931
+ ...outcome.metrics === void 0 ? {} : { metrics: outcome.metrics }
730
932
  };
731
933
  }
732
- function readParentTitle(ctx, parentId) {
733
- if (typeof parentId !== "string" || parentId === "") return "";
734
- try {
735
- const rootId = resolveRootSessionId(parentId, (id) => ctx.sessions.get(id));
736
- const session = ctx.sessions.get(rootId);
737
- if (session === void 0) return rootId;
738
- const title = ctx.sessionTitle.get(session)?.title;
739
- return typeof title === "string" && title.trim() !== "" ? title.trim() : rootId;
740
- } catch {
741
- return parentId;
742
- }
743
- }
744
- function truncate(text, max = 60) {
745
- const collapsed = text.replace(/\s+/g, " ").trim();
746
- return collapsed.length <= max ? collapsed : `${collapsed.slice(0, max - 1)}\u2026`;
747
- }
748
934
  export {
749
935
  Config,
750
936
  JUDGE_API_KEY_REF,