@lynn123411/dsh-subagent-judge-dispatch 0.6.10 → 0.6.11

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.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/enablement.ts", "../src/server/config.ts", "../src/server/endpoint.ts", "../src/server/judge-prompt.ts", "../src/server/credentials.ts", "../src/server/dispatch.ts", "../src/server/identity.ts", "../src/server/judge-budget.ts", "../src/server/judge-client.ts", "../src/server/log-store.ts", "../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", "../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", "../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", "../src/server/router.ts", "../src/index.ts"],
4
- "sourcesContent": ["/** Shared by the host and the conversation menu. */\nexport const DEFAULT_ENABLED = true;\nexport const SETTINGS_NAMESPACE = 'dsh-subagent-judge-dispatch';\n\nexport type SessionOverrides = Readonly<Record<string, boolean>>;\n\n/** An explicit choice takes precedence over the plugin default. */\nexport function enabledFor(overrides: unknown, fallback: boolean, sessionId?: string): boolean {\n if (sessionId === undefined || overrides === null || typeof overrides !== 'object'\n || !Object.hasOwn(overrides, sessionId)) return fallback;\n const choice = (overrides as SessionOverrides)[sessionId];\n return typeof choice === 'boolean' ? choice : fallback;\n}\n", "/**\n * This plugin's Config schema and the live read face the wiring consumes.\n *\n * Every field is `volatile()`, which is what lets the configuration card on the\n * Plugins page commit an edit into these refs without remounting the plugin:\n * the wiring reads the current value on every delegation rather than a snapshot\n * taken when the Host loaded.\n *\n * The type-list rows carry no sequence number. The page numbers the rows the\n * judge is offered \u2014 switched on and filled in \u2014 counting from 1 in array\n * order; the judge answers with that number, and the log shows it, so a number\n * can never be duplicated and the reader never has to maintain one. A row that\n * is switched off or not filled in keeps its place in the list but carries no\n * number, which is why the numbers offered to the judge stay continuous.\n */\n\nimport type { Volatile } from '@deepseek-ai/cordis';\nimport z from '@deepseek-ai/schemastery';\nimport type Schema from '@deepseek-ai/schemastery';\nimport { resolveEndpointUrl } from './endpoint.ts';\nimport { numberTypeRows, selectableRows } from './judge-prompt.ts';\nimport type { TypeRow } from './types.ts';\nimport { DEFAULT_ENABLED, enabledFor, type SessionOverrides } from '../enablement.ts';\n\n/** One type-list row as the configuration document stores it. */\nconst TypeRowSchema = z.object({\n stableId: z.string().default(''),\n /** Whether this type takes part in judgements; a row written before the switch existed counts as on. */\n enabled: z.boolean().default(true),\n /** Criterion text the judge reads for this type. */\n description: z.string().default(''),\n /** Provider route of the model this type runs on. */\n provider: z.string().default(''),\n /** Model id interpreted by that provider. */\n model: z.string().default(''),\n /** Reasoning effort id this type runs at. */\n effort: z.string().default(''),\n});\n\n/** This plugin's live configuration. */\nexport const Config: Schema = z.object({\n /** Default for conversations without their own choice. */\n enabled: z.boolean().default(DEFAULT_ENABLED).volatile(),\n sessionOverrides: z.dict(z.boolean()).default({}).volatile(),\n /** Whether judgements are written to the plugin's own log. */\n logEnabled: z.boolean().default(true).volatile(),\n /** Judge service address, as the reader typed it; the path is appended when a call is made. */\n endpointUrl: z.string().default('').volatile(),\n /** Judge model id. */\n judgeModel: z.string().default('').volatile(),\n /** The task-type list, in page order. */\n rows: z.array(TypeRowSchema).default([]).volatile(),\n});\n\n/** Fields of this plugin's Config as the runtime resolved them. */\nexport interface PluginConfigRefs {\n readonly enabled: Volatile<boolean>;\n readonly sessionOverrides: Volatile<SessionOverrides>;\n readonly logEnabled: Volatile<boolean>;\n readonly endpointUrl: Volatile<string>;\n readonly judgeModel: Volatile<string>;\n readonly rows: Volatile<StoredRow[]>;\n}\n\n/** One stored row, before the page assigns its sequence number. */\nexport interface StoredRow {\n stableId?: string;\n /** Whether this type takes part in judgements. */\n enabled: boolean;\n description: string;\n provider: string;\n model: string;\n effort: string;\n}\n\n/** A detached plain read of this plugin's configuration. */\nexport interface ResolvedConfig {\n enabled: boolean;\n sessionOverrides: SessionOverrides;\n logEnabled: boolean;\n /** Full judge URL: the stored address with the service path applied. */\n endpointUrl: string;\n judgeModel: string;\n rows: TypeRow[];\n}\n\n/**\n * Read the current committed value of every Config field, numbering the rows.\n * @param refs - the runtime-resolved Config object.\n * @returns a detached plain config value.\n */\nexport function readPluginConfig(refs: PluginConfigRefs): ResolvedConfig {\n const stored = refs.rows.get();\n // The number is positional, so deleting, moving, switching off or filling in\n // a row renumbers the rest. A log entry written before that edit may therefore\n // name a different type; the reader accepted that when choosing continuous\n // numbering. A row that is not offered keeps its place and carries number 0.\n const rows: TypeRow[] = numberTypeRows((Array.isArray(stored) ? stored : []).map((row) => ({\n stableId: typeof row?.stableId === 'string' ? row.stableId : '',\n enabled: row?.enabled !== false,\n description: typeof row?.description === 'string' ? row.description : '',\n provider: typeof row?.provider === 'string' ? row.provider : '',\n model: typeof row?.model === 'string' ? row.model : '',\n effort: typeof row?.effort === 'string' ? row.effort : '',\n })));\n return {\n enabled: refs.enabled.get() ?? DEFAULT_ENABLED,\n sessionOverrides: refs.sessionOverrides.get(),\n logEnabled: refs.logEnabled.get() !== false,\n endpointUrl: resolveEndpointUrl(refs.endpointUrl.get()),\n judgeModel: typeof refs.judgeModel.get() === 'string' ? refs.judgeModel.get() : '',\n rows,\n };\n}\n\n/**\n * Whether a delegation would be judged given the root conversation's choice\n * and the available judgement service and task types.\n */\nexport function isJudgeUsable(config: ResolvedConfig, rootSessionId?: string): boolean {\n if (!enabledFor(config.sessionOverrides, config.enabled, rootSessionId)) return false;\n if (config.endpointUrl.trim() === '' || config.judgeModel.trim() === '') return false;\n return selectableRows(config.rows).length > 0;\n}\n", "/**\n * Where a judgement is sent: the address the reader typed, with the service's\n * path appended when it does not already carry one.\n *\n * The page asks for the address only. Which path the service lives at is\n * decided here rather than asked as a second setting: an address that already\n * names one of the known paths is used as it is, and anything shorter gets the\n * default. This module imports nothing, so both halves can share the rule.\n */\n\n/** Paths the service is reached at; the first is the one appended by default. */\nconst ENDPOINT_PATHS = ['/v1/systemone', '/systemone'] as const;\n\n/**\n * Turn the typed address into the URL a request is sent to.\n *\n * An address that already ends with one of the known paths is left as it is, so\n * a stored full URL \u2014 or one pasted from elsewhere \u2014 is never doubled. An\n * address that stops at the default path's own prefix (`\u2026/v1`) only needs the\n * rest of it. Everything shorter gets the default path.\n *\n * @param input - the address the reader typed.\n * @returns the URL to call, or '' when no address is set.\n */\nexport function resolveEndpointUrl(input: unknown): string {\n const trimmed = typeof input === 'string' ? input.trim() : '';\n if (trimmed === '') return '';\n const address = trimmed.replace(/\\/+$/, '');\n if (ENDPOINT_PATHS.some((path) => address.endsWith(path))) return address;\n if (address.endsWith('/v1')) return `${address}/systemone`;\n return `${address}/v1/systemone`;\n}\n", "/**\n * The judgement request the plugin sends, and the answer it reads back.\n *\n * Two pure functions live here, so the whole \"what did the judge decide\"\n * question is answerable without a Host, a socket, or a timer:\n *\n * - {@link buildJudgeRequest} turns the type list plus the task text into the\n * exact body that goes out.\n * - {@link readJudgeAnswer} turns whatever came back into a decision, treating\n * every malformed, empty or off-list answer as \"no decision\" rather than\n * inventing one.\n *\n * The list rules live here as well, because the criteria map IS the list: which\n * rows are offered ({@link selectableRows}) and what number each carries\n * ({@link numberTypeRows}).\n *\n * The protocol is the System One one: POST a body of `{ model, state,\n * questions }`, where each question is a `choice` carrying an `instructions`\n * line and a `criteria` map of option id to the text that option means. The\n * answer names the chosen option id.\n */\n\nimport type { TypeRow } from './types.ts';\n\n/** The one question key the plugin asks. */\nconst QUESTION_KEY = 'task_type';\n\n/**\n * The question's instructions line.\n *\n * It says what to weigh, not what the types are: the types themselves arrive as\n * the criteria map, so the reader's own descriptions are the whole criterion\n * list and nothing here can drift from them.\n */\nexport const QUESTION_INSTRUCTIONS =\n 'Which single task type below does the delegated job best match? '\n + 'Weigh what the job actually requires, not how it is phrased. '\n + 'Answer with the number of exactly one listed type.';\n\n/** The option id the connectivity check offers: the only one it offers. */\nexport const PROBE_OPTION_ID = '1';\n\n/** The task text the connectivity check sends. */\nconst PROBE_TASK_TEXT = '\u8FDE\u63A5\u6D4B\u8BD5\uFF1A\u8FD9\u662F\u4E00\u6B21\u5224\u65AD\u670D\u52A1\u7684\u8FDE\u901A\u6027\u68C0\u67E5\u3002';\n\n/**\n * The connectivity check's instructions.\n *\n * It asks for the one option that exists, so an endpoint that understands the\n * protocol at all can answer it: answering it wrong is a failure of the\n * protocol, not of the reader's task list.\n */\nconst PROBE_INSTRUCTIONS =\n 'Answer with the number of the one option listed below.';\n\n/** The single criterion the connectivity check offers. */\nconst PROBE_CRITERION = '\u786E\u8BA4\u8FD9\u6B21\u8C03\u7528\u53EF\u4EE5\u5B8C\u6210\u3002';\n\n/** One option of the judge's question. */\nexport interface JudgeChoice {\n type: 'choice';\n instructions: string;\n criteria: Record<string, string>;\n}\n\n/** The exact body sent to the judge endpoint. */\nexport interface JudgeRequest {\n model: string;\n state: { message: string };\n questions: { [QUESTION_KEY]: JudgeChoice };\n}\n\n/**\n * Whether one row is complete enough to be offered to the judge.\n *\n * A row needs its provider, model and effort: a half-filled row could otherwise\n * be chosen and then have nothing to write, which would turn the reader's\n * unfinished edit into a delegation that silently lost its route. This is the\n * ONE place that rule lives \u2014 the page, the config gate and the rewrite all ask\n * this function rather than restating the three comparisons.\n *\n * The parameter is narrowed to the three fields the rule reads, so the page's\n * draft row (which carries no sequence number) and the server's numbered row\n * both satisfy it without either shape being converted into the other.\n *\n * @param row - one row, numbered or drafted.\n * @returns whether the judge may choose it.\n */\nexport function isSelectableRow(row: Pick<TypeRow, 'provider' | 'model' | 'effort'>): boolean {\n return row.provider.trim() !== '' && row.model.trim() !== '' && row.effort.trim() !== '';\n}\n\n/**\n * Whether one row is switched on.\n *\n * A row that is switched off stays in the list \u2014 the reader keeps it there to\n * turn it back on later \u2014 but takes no part in a judgement and carries no\n * number. A missing value counts as switched on, so a row written before the\n * switch existed keeps working.\n *\n * The parameter is narrowed to the one field the rule reads, so a stored row, a\n * numbered row and the page's draft row all satisfy it.\n *\n * @param row - one row, stored or drafted.\n * @returns whether the row takes part in judgements.\n */\nexport function isRowEnabled(row: { enabled?: boolean }): boolean {\n return row.enabled !== false;\n}\n\n/** The fields a row must carry to be judged: the switch, and the route it runs on. */\ntype RowOffering = { enabled?: boolean } & Pick<TypeRow, 'provider' | 'model' | 'effort'>;\n\n/**\n * Whether one row is offered to the judge: switched on, and its route filled in.\n *\n * The two conditions are one rule because the judge's list is exactly the rows\n * that pass both \u2014 a row switched off is one the reader does not want judged,\n * and a half-filled row could be chosen and then have nothing to write.\n *\n * @param row - one row, stored, numbered or drafted.\n * @returns whether the judge may choose it.\n */\nexport function isOfferedRow(row: RowOffering): boolean {\n return isRowEnabled(row) && isSelectableRow(row);\n}\n\n/**\n * Which rows may be offered to the judge.\n * @param rows - every row on the page, in page order.\n * @returns the rows the judge may choose, in page order.\n */\nexport function selectableRows(rows: readonly TypeRow[]): TypeRow[] {\n return rows.filter(isOfferedRow);\n}\n\n/**\n * Number the rows the judge is offered, in list order.\n *\n * The number is positional and never stored: switching a row off, filling one\n * in, or moving it renumbers the rest. A row that is not offered carries 0 \u2014 it\n * has no number to be answered with \u2014 so the criteria map is numbered 1..n with\n * no gaps, and the preview, the request and the answer all read the same list.\n *\n * @param rows - the rows as the page holds them, in page order.\n * @returns the rows with their numbers applied, in the same order.\n */\nexport function numberTypeRows<T extends RowOffering>(\n rows: readonly T[],\n): (T & { id: number })[] {\n let next = 0;\n return rows.map((row) => {\n if (!isOfferedRow(row)) return { ...row, id: 0 };\n next += 1;\n return { ...row, id: next };\n });\n}\n\n/**\n * How much of a delegated task's opening the judge reads.\n *\n * The judge answers one multiple-choice question; the opening of a task says\n * what kind of job it is, and the rest is usually detail the choice does not\n * turn on. Bounding it keeps the request small and keeps one enormous\n * delegation from crowding out the type list it is being weighed against.\n */\nexport const SUBJECT_HEAD_CHARS = 1400;\n\n/**\n * How much of a task's closing the judge reads.\n *\n * Supplementary requirements are written at the end \u2014 \"also run the review\" \u2014\n * so the tail is kept rather than the middle.\n */\nexport const SUBJECT_TAIL_CHARS = 400;\n\n/** Opening words of the label line the judge reads above the task. */\nconst LABEL_PREFIX = 'Delegation label: ';\n\n/**\n * Build the subject the judge is asked to classify.\n *\n * Two parts, in the order the reader would put them: the delegation's own label\n * \u2014 a summary the delegating agent wrote, which carries its intent \u2014 and then\n * the task text itself. The label alone is a display phrase of a few words, too\n * little to classify by; the task text alone loses that intent when it opens\n * with boilerplate.\n *\n * @param label - the delegation label, or '' when the child has none.\n * @param taskText - the delegated task text, or '' when it cannot be read.\n * @returns the subject to send, bounded to {@link SUBJECT_HEAD_CHARS} plus\n * {@link SUBJECT_TAIL_CHARS} characters of task text.\n */\nexport function composeJudgeSubject(label: string, taskText: string): string {\n const task = clipTaskText(taskText.trim());\n const heading = label.trim();\n if (heading === '') return task;\n return task === '' ? LABEL_PREFIX + heading : `${LABEL_PREFIX}${heading}\\n\\n${task}`;\n}\n\n/**\n * Bound a task text to its opening and closing.\n *\n * The dropped middle is named rather than silently removed, so a reader looking\n * at the logged request can tell truncation from a short task. The marker is\n * English like the rest of the protocol, so it reads as a note from the plugin\n * rather than as part of the task, whatever language the task is written in.\n *\n * @param text - the task text.\n * @returns the text, or its head and tail around a count of what was dropped.\n */\nfunction clipTaskText(text: string): string {\n if (text.length <= SUBJECT_HEAD_CHARS + SUBJECT_TAIL_CHARS) return text;\n const dropped = text.length - SUBJECT_HEAD_CHARS - SUBJECT_TAIL_CHARS;\n const head = text.slice(0, SUBJECT_HEAD_CHARS);\n const tail = text.slice(text.length - SUBJECT_TAIL_CHARS);\n return `${head}\\n\u2026 (${dropped} characters omitted) \u2026\\n${tail}`;\n}\n\n/**\n * Build the exact body sent to the judge endpoint.\n *\n * @param rows - the selectable rows, in page order.\n * @param model - the judge model id.\n * @param subject - the text the judge classifies, from {@link composeJudgeSubject}.\n * @returns the request body.\n */\nexport function buildJudgeRequest(\n rows: readonly TypeRow[],\n model: string,\n subject: string,\n): JudgeRequest {\n const criteria: Record<string, string> = {};\n for (const row of rows) criteria[String(row.id)] = row.description;\n return {\n model,\n state: { message: subject },\n questions: {\n [QUESTION_KEY]: {\n type: 'choice',\n instructions: QUESTION_INSTRUCTIONS,\n criteria,\n },\n },\n };\n}\n\n/**\n * Build the body the connectivity check sends.\n *\n * It carries its own single option rather than the reader's task types: the\n * question the button answers is \"does this endpoint and model work\", and that\n * question has an answer before any type list exists. Requiring a finished list\n * first would make the check unable to tell a reader with an empty list from a\n * reader whose endpoint is down.\n *\n * @param model - the judge model id.\n * @returns the request body.\n */\nexport function buildProbeRequest(model: string): JudgeRequest {\n return {\n model,\n state: { message: PROBE_TASK_TEXT },\n questions: {\n [QUESTION_KEY]: {\n type: 'choice',\n instructions: PROBE_INSTRUCTIONS,\n criteria: { [PROBE_OPTION_ID]: PROBE_CRITERION },\n },\n },\n };\n}\n\n/**\n * Serialize one request body the way the page shows it.\n *\n * Both the preview and a logged judgement display this text, while the call\n * itself sends the same object compacted onto the wire. Deriving both from one\n * body is what keeps the shown text from describing a different request than\n * the one that went out.\n *\n * @param body - the request body.\n * @returns the pretty-printed JSON.\n */\nexport function formatJudgeRequest(body: JudgeRequest): string {\n return JSON.stringify(body, null, 2);\n}\n\n/**\n * The text the configuration page's preview shows.\n *\n * It is the request body minus the subject, because no delegation exists until\n * one happens; the preview marks both spots the subject will fill rather than\n * inventing a task. The two markers are told apart, because the real subject is\n * a label line followed by the task text and the preview should read that way.\n *\n * @param rows - the selectable rows, in page order.\n * @param model - the judge model id.\n * @returns the pretty-printed preview text.\n */\nexport function buildPreview(rows: readonly TypeRow[], model: string): string {\n return formatJudgeRequest(\n buildJudgeRequest(rows, model, composeJudgeSubject('\uFF08\u6D3E\u5DE5\u65F6\u624D\u586B\uFF1A\u6D3E\u5DE5\u6807\u7B7E\uFF09', '\uFF08\u6D3E\u5DE5\u65F6\u624D\u586B\uFF1A\u4EFB\u52A1\u6B63\u6587\uFF09')),\n );\n}\n\n/** What reading the judge's answer produced. */\nexport type JudgeDecision =\n | { kind: 'row'; row: TypeRow }\n | { kind: 'empty' }\n | { kind: 'unmatched' };\n\n/**\n * Find the chosen option id inside whatever the endpoint answered.\n *\n * The protocol's own shape is `answers.<key>.choice`; the two fallbacks are the\n * ones the reference clients read, so an endpoint that answers the shorter way\n * still works. Anything else \u2014 a missing body, a non-string, an empty string \u2014\n * yields `undefined` and is treated as no answer.\n *\n * @param payload - the decoded response body.\n * @returns the chosen option id, or undefined when the body names none.\n */\nexport function readChoice(payload: unknown): string | undefined {\n if (typeof payload !== 'object' || payload === null) return undefined;\n const body = payload as Record<string, unknown>;\n const answers = body.answers;\n const fromAnswers =\n typeof answers === 'object' && answers !== null\n ? (answers as Record<string, unknown>)[QUESTION_KEY]\n : undefined;\n const candidate = fromAnswers ?? body[QUESTION_KEY];\n if (typeof candidate === 'object' && candidate !== null) {\n const choice = (candidate as Record<string, unknown>).choice;\n if (typeof choice === 'string' && choice.trim() !== '') return choice.trim();\n if (typeof choice === 'number' && Number.isFinite(choice)) return String(choice);\n return undefined;\n }\n if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim();\n if (typeof candidate === 'number' && Number.isFinite(candidate)) return String(candidate);\n return undefined;\n}\n\n/**\n * Turn the judge's answer into a decision.\n *\n * The choice is the type row's number. Matching is by that number's numeric\n * value, so an endpoint that answers `\"3\"` and one that answers `3` agree; a\n * number no listed row carries is `unmatched`, and a body naming no choice at\n * all is `empty`. Both travel to the log as their own reason, because \"it\n * answered nothing\" and \"it answered something I do not have\" send the reader\n * to different fixes.\n *\n * @param payload - the decoded response body.\n * @param rows - the selectable rows, in page order.\n * @returns the decision.\n */\nexport function readJudgeAnswer(payload: unknown, rows: readonly TypeRow[]): JudgeDecision {\n const choice = readChoice(payload);\n if (choice === undefined) return { kind: 'empty' };\n const wanted = Number(choice);\n if (!Number.isFinite(wanted)) return { kind: 'unmatched' };\n const row = rows.find((candidate) => candidate.id === wanted);\n return row === undefined ? { kind: 'unmatched' } : { kind: 'row', row };\n}\n", "/**\n * Where the judgement key lives, and the Host service it is read through.\n *\n * The reference name is a constant of the plugin rather than a setting: the\n * page asks for the key itself and stores it write-only through the DSH\n * credentials service, so a reader never has to know what a \"credential\n * reference\" is, and no surface can point the plugin at somebody else's key.\n * This module imports nothing, so both halves can share the literal.\n *\n * The key value crosses in one direction only: it is written, and read back by\n * the Host half alone. The browser face reads a status-only view.\n */\n\n/** Credential reference the judgement key is stored under. */\nexport const JUDGE_API_KEY_REF = 'SUBAGENT_JUDGE_API_KEY';\n\n/** Minimal structural shape of the Host's `ctx.credentials` service. */\nexport interface CredentialsServiceLike {\n /** Resolve a reference to its stored or inherited value. */\n resolve(ref: string): Promise<{ value: string; source?: string } | undefined>;\n /** Status-only view of a reference; never returns the plaintext value. */\n describe(ref: string): Promise<{ configured: boolean; source?: string; writable: boolean }>;\n /** Store a non-empty value under a reference. */\n set(ref: string, value: string): Promise<void>;\n}\n\n/** Minimal structural shape of the browser's `ctx.remote.credentials` face. */\nexport interface CredentialsRemoteLike {\n describe(refs: string[]): Promise<\n { ok: true; value: Record<string, { configured: boolean; source?: string; writable: boolean }> }\n | { ok: false; error: { message: string } }\n >;\n set(ref: string, value: string): Promise<{ ok: true } | { ok: false; error: { message: string } }>;\n}\n", "/**\n * The decision half: given what the judge said, decide exactly what to write\n * onto a subagent's next model call \u2014 or write nothing at all.\n *\n * This module holds the one rule that matters most, so it is a pure function\n * that a test can drive directly: **any** judgement that did not end in a\n * usable row writes nothing. Not \"writes the inherited values\", not \"writes a\n * partial route\" \u2014 nothing. Writing anything is a replacement, so a fallback\n * that wrote the parent's own values back would still be an overwrite, and a\n * partial write would drop the inherited reasoning effort\n * (`resolveChildAgentOptions` deletes it when a route changes without one).\n */\n\nimport { isOfferedRow } from './judge-prompt.ts';\nimport type { FallbackReason, JudgeOutcome, TypeRow } from './types.ts';\n\n/** The three fields a rewrite carries, all present or none at all. */\nexport interface RouteRewrite {\n provider: string;\n model: string;\n reasoningEffort: string;\n}\n\n/** What to write for one judged subagent. */\nexport type DispatchDecision =\n | { kind: 'rewrite'; rewrite: RouteRewrite }\n | { kind: 'none' };\n\n/**\n * Turn a judgement into the rewrite it authorises.\n *\n * The three fields travel as one object because they must be written as one:\n * a route change without an explicit effort makes the Host drop the inherited\n * effort, so a caller can never be handed two of the three.\n *\n * @param outcome - what the judge call produced.\n * @returns the rewrite, or `none` when the child must inherit unchanged.\n */\nexport function decideRewrite(outcome: JudgeOutcome): DispatchDecision {\n if (outcome.kind !== 'matched') return { kind: 'none' };\n const row: TypeRow = outcome.row;\n // A row the judge could select but that is switched off or missing a piece is\n // not a rewrite this plugin may make; leaving the child alone is always safe.\n if (!isOfferedRow(row)) return { kind: 'none' };\n return {\n kind: 'rewrite',\n rewrite: {\n provider: row.provider.trim(),\n model: row.model.trim(),\n reasoningEffort: row.effort.trim(),\n },\n };\n}\n\n/**\n * Why a delegation ended up inheriting, as the log reports it.\n *\n * The judge answering nothing, the judge answering a number this list does not\n * have, an unreachable endpoint and an expired budget are four different fixes\n * for the reader \u2014 \"it answered nothing\" points at the endpoint, \"no listed\n * type\" points at the descriptions. A selected row that turned out to be switched\n * off or missing a field is a fifth: the judgement worked, the row it named was\n * not usable.\n *\n * A judgement that produced a rewrite has no reason at all.\n *\n * @param outcome - what the judge call produced.\n * @param decision - what was written for it.\n * @returns the reason to record, or undefined when the rewrite landed.\n */\nexport function outcomeReason(\n outcome: JudgeOutcome,\n decision: DispatchDecision,\n): FallbackReason | undefined {\n if (decision.kind === 'rewrite') return undefined;\n if (outcome.kind !== 'matched') return outcome.reason;\n return 'incomplete';\n}\n\n", "/** Durable session facts used to identify a child and its initial task. */\nexport interface SessionLike {\n readonly header: SessionHeaderLike;\n readonly inheritedEventCount?: number;\n ownEvents?(): readonly SessionEventLike[];\n snapshotEvents(from?: number): readonly SessionEventLike[];\n}\n\nexport interface SessionHeaderLike {\n readonly id: string;\n readonly parentSession?: string;\n readonly delegationDepth?: number;\n readonly origin?: 'subagent';\n}\n\nexport interface SessionEventLike {\n readonly type: string;\n readonly data?: unknown;\n}\n\nexport interface AgentLike {\n readonly id: string;\n readonly options: { readonly subagentDepth?: number };\n readonly session: SessionLike;\n}\n\nfunction ownEventsOf(session: SessionLike): readonly SessionEventLike[] {\n return session.ownEvents?.() ?? session.snapshotEvents(session.inheritedEventCount ?? 0);\n}\n\nexport function isSubagent(agent: AgentLike): boolean {\n const fromHeader = agent.session.header.delegationDepth;\n const fromOptions = agent.options.subagentDepth;\n return Math.max(\n typeof fromHeader === 'number' && Number.isSafeInteger(fromHeader) ? fromHeader : 0,\n typeof fromOptions === 'number' && Number.isSafeInteger(fromOptions) ? fromOptions : 0,\n ) >= 1;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined;\n}\n\nfunction readText(block: unknown): string | undefined {\n const data = asRecord(block);\n return data?.type === 'text' && typeof data.text === 'string' ? data.text : undefined;\n}\n\nconst RETURN_GUIDANCE = 'Your final answer is delivered automatically if your parent is still online.';\n\n/** Read the first accepted parent relay, excluding the sender line and result-delivery guidance. */\nfunction readInitialTask(events: readonly SessionEventLike[], parentId: string): string | undefined {\n for (const event of events) {\n const inserted = asRecord(event.data)?.inserted;\n const messages = event.type === 'user/message' ? [event.data]\n : event.type === 'agent/inbox/spliced' && Array.isArray(inserted) ? inserted : [];\n for (const value of messages) {\n const message = asRecord(value);\n const source = asRecord(message?.source);\n if (source?.kind !== 'agent-message' || source.form !== 'relay' || source.senderSessionId !== parentId) continue;\n if (!Array.isArray(message?.content)) return undefined;\n const [sender, ...body] = message.content;\n if (!/^Agent .+ sent a message: $/.test(readText(sender) ?? '')) return undefined;\n const texts = body.map(readText).filter((text): text is string => text !== undefined);\n if (texts.length > 1 && texts.at(-1)?.startsWith(RETURN_GUIDANCE)) texts.pop();\n return texts.join('\\n').trim() || undefined;\n }\n }\n return undefined;\n}\n\nconst DELEGATION_TOOLS: ReadonlySet<unknown> = new Set(['subagent', 'subagent_fork']);\n\ninterface DelegatedTask {\n label: string;\n text: string;\n explicitRoute: boolean;\n}\n\nfunction matchingCall(data: Record<string, unknown>, label: string): DelegatedTask | undefined {\n if (!DELEGATION_TOOLS.has(data.name)) return undefined;\n let args = data.arguments;\n if (typeof args === 'string') {\n try { args = JSON.parse(args); } catch { return undefined; }\n }\n const call = asRecord(args);\n if (typeof call?.description !== 'string' || call.description.trim() !== label ||\n typeof call.prompt !== 'string' || call.prompt.trim() === '') return undefined;\n return {\n label,\n text: call.prompt.trim(),\n explicitRoute: call.provider !== undefined || call.model !== undefined || call.reasoning_effort !== undefined,\n };\n}\n\n/** Find unfinished calls in the step that created the child. */\nfunction outstandingDelegation(\n events: readonly SessionEventLike[],\n label: string,\n resumedChildId?: string,\n): DelegatedTask | undefined {\n const end = resumedChildId === undefined ? events.length : events.findIndex((event) =>\n event.type === 'subagent/catalog' && asRecord(event.data)?.childId === resumedChildId,\n );\n const finished = new Set<string>();\n let task: DelegatedTask | undefined;\n for (let index = end - 1; index >= 0; index -= 1) {\n const { type, data: value } = events[index];\n if (type === 'step/start' || type === 'step/end' || type === 'turn/start' || type === 'turn/end') break;\n const data = asRecord(value);\n if (data === undefined) continue;\n switch (type) {\n case 'tool/result': {\n const id = asRecord(data.message)?.toolCallId;\n if (typeof id === 'string') finished.add(`native:${id}`);\n break;\n }\n case 'tool/ptc-dispatch':\n if (typeof data.subCallId === 'string') finished.add(`ptc:${data.subCallId}`);\n break;\n case 'tool/call': case 'tool/ptc-dispatch-start': {\n const ptc = type === 'tool/ptc-dispatch-start';\n const id = ptc ? data.subCallId : data.callId;\n if (typeof id !== 'string' || finished.has(`${ptc ? 'ptc' : 'native'}:${id}`)) break;\n const candidate = matchingCall(data, label);\n if (candidate === undefined) break;\n if (task !== undefined) return undefined;\n task = candidate;\n break;\n }\n }\n }\n return task;\n}\n\n/** Keep a route already selected or used by this child. */\nexport function hasRecordedRoute(session: SessionLike, events = ownEventsOf(session)): boolean {\n return events.some((event) => event.type === 'model/selection' || event.type === 'request/header');\n}\n\n/** Read a uniquely identified task and the route choice made by its caller. */\nexport function readDelegatedTask(\n agent: AgentLike,\n parentSessionOf: (id: string) => SessionLike | undefined,\n resumed: boolean,\n): DelegatedTask | undefined {\n const parentId = agent.session.header.parentSession;\n if (!parentId) return undefined;\n const parent = parentSessionOf(parentId);\n if (parent?.header.id !== parentId) return undefined;\n const own = ownEventsOf(agent.session);\n if (hasRecordedRoute(agent.session, own)) return undefined;\n const descriptor = [...own].reverse().find((event) => event.type === 'subagent/descriptor');\n const label = asRecord(descriptor?.data)?.label;\n if (typeof label !== 'string' || label.trim() === '') return undefined;\n const task = outstandingDelegation(ownEventsOf(parent), label.trim(), resumed ? agent.id : undefined);\n if (task === undefined) return undefined;\n if (resumed && readInitialTask(own, parentId) !== task.text) return undefined;\n return task;\n}\n\n/**\n * Walk up a child's lineage to the top-level conversation that started it.\n *\n * A nested subagent's direct parent is another subagent, and the log's job is to\n * name the conversation the reader recognises \u2014 so the walk continues until a\n * session is a top-level conversation. A normal session fork is itself a\n * conversation, even when its header names a parent. The walk is bounded to\n * tolerate a damaged lineage.\n *\n * @param startId - the child's direct parent session id.\n * @param lookup - reads the header of a live or persisted session.\n * @returns the top-level session id, or the last id reached when the walk stops.\n */\nexport async function resolveRootSessionId(\n startId: string,\n lookup: (id: string) => SessionHeaderLike | undefined | Promise<SessionHeaderLike | undefined>,\n): Promise<string> {\n const seen = new Set<string>([startId]);\n let current = startId;\n for (let hop = 0; hop < 32; hop += 1) {\n const header = await lookup(current);\n if (header === undefined || (header.origin !== 'subagent' && (header.delegationDepth ?? 0) < 1)) return current;\n const parent = header.parentSession;\n if (typeof parent !== 'string' || parent === '' || seen.has(parent)) return current;\n seen.add(parent);\n current = parent;\n }\n return current;\n}\n", "/** The total time available for the judge request and route preflight. */\nconst JUDGE_TIMEOUT_MS = 5000;\n\nexport class JudgeBudget {\n private readonly startedAt = performance.now();\n private readonly controller = new AbortController();\n private readonly timer = setTimeout(() => this.controller.abort(), JUDGE_TIMEOUT_MS);\n readonly signal: AbortSignal;\n\n constructor(parent?: AbortSignal) {\n this.signal = parent === undefined\n ? this.controller.signal\n : AbortSignal.any([parent, this.controller.signal]);\n }\n\n elapsed(): number {\n return Math.round(performance.now() - this.startedAt);\n }\n\n expired(): boolean {\n if (performance.now() - this.startedAt >= JUDGE_TIMEOUT_MS) this.controller.abort();\n return this.controller.signal.aborted;\n }\n\n check(): void {\n this.expired();\n this.signal.throwIfAborted();\n }\n\n /** Stop waiting at the deadline even if the operation ignores its signal. */\n async run<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {\n this.check();\n let onAbort!: () => void;\n const aborted = new Promise<never>((_, reject) => {\n onAbort = () => reject(this.signal.reason);\n this.signal.addEventListener('abort', onAbort, { once: true });\n });\n try {\n const result = await Promise.race([aborted, Promise.resolve().then(() => {\n this.check();\n return operation(this.signal);\n })]);\n this.check();\n return result;\n } finally {\n this.signal.removeEventListener('abort', onAbort);\n }\n }\n\n dispose(): void {\n clearTimeout(this.timer);\n }\n}\n", "import { JudgeBudget } from './judge-budget.ts';\nimport { PROBE_OPTION_ID, buildJudgeRequest, buildProbeRequest, readJudgeAnswer } from './judge-prompt.ts';\nimport type { JudgeMetrics, JudgeOutcome, ProbeOutcome, TypeRow } from './types.ts';\n\nexport interface JudgeEndpoint {\n url: string;\n model: string;\n apiKey: string;\n}\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\nasync function requestJudge(\n budget: JudgeBudget, endpoint: JudgeEndpoint, body: unknown, fetchImpl: FetchLike,\n): Promise<unknown> {\n return budget.run(async (signal) => {\n const response = await fetchImpl(endpoint.url.trim(), {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...endpoint.apiKey.trim() === '' ? {} : { authorization: `Bearer ${endpoint.apiKey.trim()}` },\n },\n body: JSON.stringify(body),\n signal,\n });\n signal.throwIfAborted();\n if (!response.ok) throw new Error('Judge endpoint failed');\n return response.json();\n });\n}\n\n/** Test the endpoint with one fixed option, independent of the configured task types. */\nexport async function probeJudge(\n endpoint: JudgeEndpoint, fetchImpl: FetchLike = fetch,\n): Promise<ProbeOutcome> {\n if (endpoint.url.trim() === '' || endpoint.model.trim() === '') {\n return { ok: false, latencyMs: 0, reason: 'unconfigured' };\n }\n const budget = new JudgeBudget();\n try {\n const payload = await requestJudge(budget, endpoint, buildProbeRequest(endpoint.model.trim()), fetchImpl);\n const options = [{\n id: Number(PROBE_OPTION_ID), enabled: true, description: '', provider: '', model: '', effort: '',\n }];\n return readJudgeAnswer(payload, options).kind === 'row'\n ? { ok: true, latencyMs: budget.elapsed() }\n : { ok: false, latencyMs: budget.elapsed(), reason: 'unmatched' };\n } catch {\n return { ok: false, latencyMs: budget.elapsed(), reason: budget.expired() ? 'timeout' : 'unreachable' };\n } finally {\n budget.dispose();\n }\n}\n\n/** Classify one task using the caller\u2019s deadline when it also needs to preflight a route. */\nexport async function judgeTaskType(\n endpoint: JudgeEndpoint, rows: readonly TypeRow[], subject: string,\n fetchImpl: FetchLike = fetch, sharedBudget?: JudgeBudget,\n): Promise<JudgeOutcome> {\n const budget = sharedBudget ?? new JudgeBudget();\n const model = endpoint.model.trim();\n let metrics: JudgeMetrics | undefined;\n try {\n if (endpoint.url.trim() === '' || model === '' || rows.length === 0) {\n return { kind: 'fallback', reason: 'unreachable', latencyMs: budget.elapsed() };\n }\n budget.check();\n metrics = { judgeModel: model, optionCount: rows.length, subjectLength: subject.length };\n const payload = await requestJudge(budget, endpoint, buildJudgeRequest(rows, model, subject), fetchImpl);\n const decision = readJudgeAnswer(payload, rows);\n return decision.kind === 'row'\n ? { kind: 'matched', row: decision.row, latencyMs: budget.elapsed(), metrics }\n : { kind: 'fallback', reason: 'unmatched', latencyMs: budget.elapsed(), metrics };\n } catch {\n const reason = budget.expired() ? 'timeout' : 'unreachable';\n return { kind: 'fallback', reason, latencyMs: budget.elapsed(), metrics };\n } finally {\n if (sharedBudget === undefined) budget.dispose();\n }\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write';\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths';\nimport type { FallbackReason, JudgeMetrics, LogEntry } from './types.ts';\n\nexport const LOG_KEEP = 200;\nexport const LOG_PAGE_LIMIT = 10;\n\nconst REASONS: readonly FallbackReason[] = [\n 'unreachable', 'timeout', 'unmatched', 'incomplete', 'unavailable-route',\n];\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined;\n}\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction count(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;\n}\n\nfunction readMetrics(value: unknown): JudgeMetrics | undefined {\n const item = record(value);\n if (item === undefined) return undefined;\n return {\n judgeModel: text(item.judgeModel),\n optionCount: count(item.optionCount),\n subjectLength: count(item.subjectLength),\n };\n}\n\n/** Allow-list the fields written and served so stored request text cannot be replayed. */\nfunction readEntry(value: unknown): LogEntry | undefined {\n const item = record(value);\n if (item === undefined) return undefined;\n const reason = REASONS.find((candidate) => candidate === item.reason);\n const metrics = readMetrics(item.metrics);\n return {\n typeId: count(item.typeId) || null,\n ...typeof item.typeKey === 'string' && /^[0-9a-f-]{36}$/i.test(item.typeKey) ? { typeKey: item.typeKey } : {},\n provider: text(item.provider),\n model: text(item.model),\n effort: text(item.effort),\n ...reason === undefined ? {} : { reason },\n at: count(item.at),\n latencyMs: count(item.latencyMs),\n ...metrics === undefined ? {} : { metrics },\n };\n}\n\nfunction newest(entries: LogEntry[]): LogEntry[] {\n return entries.sort((left, right) => right.at - left.at).slice(0, LOG_KEEP);\n}\n\n/** A bounded, newest-first log shared by the Host processes in one DSH home. */\nexport class LogStore {\n private entries: LogEntry[] = [];\n private pending: LogEntry[] = [];\n private loading?: Promise<void>;\n private writing: Promise<void> = Promise.resolve();\n\n private readonly filePath: string;\n\n constructor(filePath = dshHomePath('dsh-subagent-judge-dispatch', 'judgements.json')) {\n this.filePath = filePath;\n }\n\n init(): Promise<void> {\n this.loading ??= this.readDisk().then((entries) => {\n this.entries = entries;\n }).catch(() => {});\n return this.loading;\n }\n\n append(entry: LogEntry): void {\n const sanitized = readEntry(entry);\n if (sanitized === undefined) return;\n this.pending.unshift(sanitized);\n this.writing = this.writing.then(() => this.write()).catch(() => {\n this.pending = newest(this.pending);\n console.warn('[dsh-subagent-judge-dispatch] \u5224\u65AD\u65E5\u5FD7\u5199\u4E0D\u8FDB\u78C1\u76D8');\n });\n }\n\n list(): LogEntry[] {\n return this.snapshot(this.entries);\n }\n\n async readLatest(): Promise<LogEntry[]> {\n const previous = this.entries;\n const disk = await this.readDisk();\n // A local commit can complete while the file read observes its old inode.\n return this.snapshot(this.entries === previous ? disk : this.entries);\n }\n\n private snapshot(entries: LogEntry[]): LogEntry[] {\n return newest([...this.pending, ...entries]).map((entry) => structuredClone(entry));\n }\n\n async flush(): Promise<void> {\n await this.loading;\n await this.writing;\n }\n\n private async readDisk(): Promise<LogEntry[]> {\n try {\n const parsed: unknown = JSON.parse(await fs.readFile(this.filePath, 'utf8'));\n if (!Array.isArray(parsed)) throw new Error('Invalid log format');\n return newest(parsed.map(readEntry).filter((entry): entry is LogEntry => entry !== undefined));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n }\n\n private async write(): Promise<void> {\n if (this.pending.length === 0) return;\n await this.loading;\n await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 0o700 });\n await withFileLock(this.filePath, async () => {\n const stored = await this.readDisk();\n const count = this.pending.length;\n const merged = newest([...this.pending, ...stored]);\n await writeFileAtomic(this.filePath, JSON.stringify(merged, null, 2), { mode: 0o600 });\n this.pending.length -= count;\n this.entries = merged;\n });\n }\n}\n", "import { createHash, randomBytes } from \"node:crypto\";\nimport { lstat, mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as setTimeout$1 } from \"node:timers/promises\";\nimport { HarnessError } from \"@deepseek-ai/dsh-error\";\n//#region lib/types/index.js\n/**\n* Atomic file replacement and writer coordination.\n* `writeFileAtomic` writes a random-suffix sibling with exclusive create and\n* the caller's permission bits, then renames it over the target, so readers\n* observe either the old or the new complete content and a replaced file ends\n* up with exactly the stated mode. `withFileLock` serializes cross-process\n* writers of one file through a `wx`-created `<file>.lock` sibling, so a\n* read-modify-write cycle can never resurrect a state another writer just\n* replaced; readers stay lock-free because the rename commit is atomic. A lock\n* whose recorded holder process no longer exists is taken over.\n* @module @deepseek-ai/dsh-atomic-write\n*/\nconst WINDOWS_TRANSIENT_RENAME_ERRORS = new Set([\n\t\"EACCES\",\n\t\"EBUSY\",\n\t\"EPERM\"\n]);\nconst WINDOWS_RENAME_RETRY_INITIAL_MS = 20;\nconst WINDOWS_RENAME_RETRY_MAX_MS = 200;\nconst WINDOWS_RENAME_RETRY_LIMIT = 8;\n/** Whether Windows reported temporary interference with an atomic replacement. */\nfunction isTransientWindowsRenameError(error) {\n\tif (process.platform !== \"win32\") return false;\n\treturn WINDOWS_TRANSIENT_RENAME_ERRORS.has(error?.code ?? \"\");\n}\n/** Replace the target after bounded retries for transient Windows interference. */\nasync function renameAtomicTemp(temp, filename) {\n\tlet delay = WINDOWS_RENAME_RETRY_INITIAL_MS;\n\tfor (let retries = 0;; retries += 1) {\n\t\ttry {\n\t\t\tawait rename(temp, filename);\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tif (!isTransientWindowsRenameError(error)) throw error;\n\t\t\tif (retries >= WINDOWS_RENAME_RETRY_LIMIT) throw error;\n\t\t}\n\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\tdelay = Math.min(delay * 2, WINDOWS_RENAME_RETRY_MAX_MS);\n\t}\n}\n/**\n* Replace `filename` with `content` in one atomic step, creating parent\n* directories. The content is first written to a random-suffix sibling opened\n* with exclusive create (`wx`): the open refuses to follow a symlink planted\n* at the temp path, and the fresh inode carries `options.mode` through the\n* rename, so replacing a wider-permission file narrows it without a chmod\n* race. The rename also replaces a symlinked target itself instead of writing\n* through to its referent, and the same-directory sibling keeps the rename on\n* one filesystem. Windows replacement retries transient `EACCES`, `EBUSY`,\n* and `EPERM` failures for a bounded interval while the complete temp file\n* remains the rename source. On any remaining failure the temp file is\n* removed and the failure rethrown. Crash durability (fsync) is out of scope.\n* @param filename - final path receiving the content.\n* @param content - complete next file content.\n* @param options - permission bits for the replacement inode.\n*/\nasync function writeFileAtomic(filename, content, options) {\n\tawait mkdir(dirname(filename), {\n\t\trecursive: true,\n\t\t...options.dirMode === void 0 ? {} : { mode: options.dirMode }\n\t});\n\tconst temp = `${filename}.${randomBytes(6).toString(\"hex\")}.tmp`;\n\ttry {\n\t\tawait writeFile(temp, content, {\n\t\t\tmode: options.mode,\n\t\t\tflag: \"wx\"\n\t\t});\n\t\tawait renameAtomicTemp(temp, filename);\n\t} catch (error) {\n\t\tawait rm(temp, { force: true });\n\t\tthrow error;\n\t}\n}\n/** Whether an exclusive create found an existing lock. */\nasync function isLockContention(error, lockPath) {\n\tconst code = error?.code;\n\tif (code === \"EEXIST\") return true;\n\tif (code !== \"EPERM\") return false;\n\ttry {\n\t\tawait lstat(lockPath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether the holder a `<pid>\\n` record names is proven gone: a signal probe finds no such process. */\nfunction holderExited(record) {\n\tif (!/^\\d+\\n$/.test(record)) return false;\n\tconst pid = Number(record.trim());\n\tif (pid === 0 || pid > 2147483647) return false;\n\tif (pid === process.pid) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn false;\n\t} catch (error) {\n\t\treturn error.code === \"ESRCH\";\n\t}\n}\n/** The lock file's content, or undefined when it cannot be read. */\nasync function readLockRecord(lockPath) {\n\ttry {\n\t\treturn await readFile(lockPath, \"utf8\");\n\t} catch (error) {\n\t\treturn;\n\t}\n}\n/**\n* Remove the lock when its recorded holder exited. Contenders that read the\n* same record serialize on a claim file named after it. Under the claim, the\n* claimant re-reads the lock and probes its PID again, and removes it only\n* when it still holds that record and that PID is still gone: the record's\n* holder can no longer release it, and no other contender can remove it\n* without the claim, so a removal never deletes a lock another contender\n* acquired after the dead holder's, including one whose holder reused the PID.\n* @returns Whether this call removed the dead holder's lock.\n*/\nasync function takeOverExitedLock(lockPath) {\n\tconst record = await readLockRecord(lockPath);\n\tif (record === void 0 || !holderExited(record)) return false;\n\tconst claim = `${lockPath}.takeover-${createHash(\"sha256\").update(record).digest(\"hex\").slice(0, 16)}`;\n\ttry {\n\t\tawait writeFile(claim, `${process.pid}\\n`, {\n\t\t\tmode: 384,\n\t\t\tflag: \"wx\"\n\t\t});\n\t} catch (error) {\n\t\tconst code = error.code;\n\t\tif (code === \"EEXIST\" || code === \"EPERM\") return false;\n\t\tthrow error;\n\t}\n\ttry {\n\t\tif (await readLockRecord(lockPath) !== record || !holderExited(record)) return false;\n\t\ttry {\n\t\t\tawait rm(lockPath, { force: true });\n\t\t} catch (error) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t} finally {\n\t\tawait rm(claim, { force: true }).catch((error) => {});\n\t}\n}\n/**\n* Retry cadence for a contended lock. These stay robustness invariants of the\n* cross-process write protocol rather than deployment tunables: they govern how\n* often a contender asks, which no caller has a reason to vary.\n*/\nconst LOCK_RETRY_INITIAL_MS = 20;\nconst LOCK_RETRY_MAX_MS = 200;\n/**\n* How long a contender waits when the caller states no limit \u2014 sized for the\n* render-and-rename cycle every call site had when this package was written.\n* Expiry fails the contender rather than guessing whether the existing lock\n* still has an owner. How long is *worth* waiting is a property of the\n* operation the lock holder runs, which is why {@link FileLockOptions.waitMs}\n* exists; the value here is the floor for an operation that does file work\n* alone.\n*/\nconst DEFAULT_LOCK_WAIT_MS = 2e3;\n/**\n* A {@link withFileLock} acquisition failure. `FILE_LOCK_TIMEOUT`: another\n* writer still held the lock at the wait deadline and the operation did not\n* start, so the caller may retry after that writer finishes.\n*/\nvar FileLockError = class extends HarnessError {\n\tcode;\n\t/** The contended `<filename>.lock` path. */\n\tlockPath;\n\tconstructor(lockPath) {\n\t\tsuper(`atomic-write: timed out waiting for the writer lock at ${lockPath}`, \"FILE_LOCK_TIMEOUT\");\n\t\tthis.name = \"FileLockError\";\n\t\tthis.code = \"FILE_LOCK_TIMEOUT\";\n\t\tthis.lockPath = lockPath;\n\t}\n};\n/**\n* Hold the cross-process writer lock for `filename` around one operation. The\n* lock is a `wx`-created sibling (`<filename>.lock`); paired with the\n* rename-based commit of {@link writeFileAtomic}, readers stay lock-free and\n* only writers contend. `EEXIST` is contention directly; an `EPERM` is\n* contention only when a fresh `lstat` confirms the lock path exists, covering\n* Windows exclusive-create behavior. Windows retries one unconfirmed EPERM\n* because the holder can release before the probe; a repeated unconfirmed\n* permission error is rethrown. The lock records its holder's PID. A contender\n* removes the lock and retries at once when no process with that PID exists\n* (`ESRCH`); any other lock, including one whose holder exists under another\n* user (`EPERM`) or whose record is incomplete, is waited for. Contention backs\n* off exponentially and times out after the deadline. A holder whose PID a\n* live process reused keeps its lock until an operator removes it. Takeover\n* proves only that the recorded process exited: an operation that starts other\n* writers must stop them with it or leave its successor a way to find them.\n* PIDs are compared on the contender's host, so writers on other hosts or in\n* other PID namespaces sharing the file are unsupported and could both hold\n* the lock. The parent directory must exist.\n* @param filename - the file whose writers this lock serializes.\n* @param operation - the read-render-commit cycle to run while holding the lock.\n* @param options - acquisition options; omitted waits {@link DEFAULT_LOCK_WAIT_MS}.\n* @returns the operation's result; the lock releases on both outcomes.\n* @throws {FileLockError} `FILE_LOCK_TIMEOUT` when the lock is still held at the deadline.\n*/\nasync function withFileLock(filename, operation, options) {\n\tconst lockPath = `${filename}.lock`;\n\tconst deadline = Date.now() + (options?.waitMs ?? DEFAULT_LOCK_WAIT_MS);\n\tlet delay = LOCK_RETRY_INITIAL_MS;\n\tlet retriedUnconfirmedPermissionError = false;\n\tfor (;;) {\n\t\toptions?.signal?.throwIfAborted();\n\t\ttry {\n\t\t\tawait writeFile(lockPath, `${process.pid}\\n`, {\n\t\t\t\tmode: 384,\n\t\t\t\tflag: \"wx\"\n\t\t\t});\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!await isLockContention(error, lockPath)) {\n\t\t\t\tif (process.platform !== \"win32\" || error?.code !== \"EPERM\" || retriedUnconfirmedPermissionError) throw error;\n\t\t\t\tretriedUnconfirmedPermissionError = true;\n\t\t\t} else if (await takeOverExitedLock(lockPath)) continue;\n\t\t}\n\t\tif (Date.now() >= deadline) throw new FileLockError(lockPath);\n\t\tawait setTimeout$1(delay, void 0, { signal: options?.signal });\n\t\tdelay = Math.min(delay * 2, LOCK_RETRY_MAX_MS);\n\t}\n\ttry {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn await operation();\n\t} finally {\n\t\tawait rm(lockPath, { force: true });\n\t}\n}\n//#endregion\nexport { FileLockError, withFileLock, writeFileAtomic };\n", "//#region lib/types/index.js\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic \u2014\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\nexport { HarnessError };\n", "import { opendir, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\n//#region lib/types/index.js\n/**\n* Shared filesystem path helpers for DeepSeek Harness user data.\n*\n* @module @deepseek-ai/dsh-home-paths\n*/\n/** Directory name for the default DeepSeek Harness home under the OS home. */\nconst DSH_HOME_DIR_NAME = \".dsh\";\n/** Stable user-facing display form for the default DeepSeek Harness home. */\nconst DEFAULT_DSH_HOME_DISPLAY = `~/${DSH_HOME_DIR_NAME}`;\n/** Environment variable that overrides the default DeepSeek Harness home. */\nconst DSH_HOME_ENV = \"DSH_HOME\";\n/** Directory name for the default shared agent configuration root under the OS home. */\nconst AGENTS_HOME_DIR_NAME = \".agents\";\n/** Stable user-facing display form for the default shared agent configuration root. */\nconst DEFAULT_AGENTS_HOME_DISPLAY = `~/${AGENTS_HOME_DIR_NAME}`;\n/** Environment variable that overrides the default shared agent configuration root. */\nconst AGENTS_HOME_ENV = \"DSH_AGENTS_HOME\";\n/**\n* Give a native filesystem watcher one canonical spelling of a path, even\n* when its final components do not exist yet. The deepest existing ancestor\n* is resolved through {@link realpath}; when a suffix is missing, that\n* ancestor is also proved to be an enumerable directory before the suffix is\n* restored. This prevents Windows from treating a regular-file ancestor as\n* ordinary absence, and prevents short-name aliases from being mixed with\n* long paths emitted by the native watcher backend.\n* @param path - Watch target or root, resolved against the current directory.\n* @returns the target with its existing ancestor canonicalized.\n* @throws when ancestor traversal encounters an error other than absence, or\n* the existing ancestor of a missing suffix is not an enumerable directory.\n*/\nasync function canonicalizeWatchPath(path) {\n\tlet current = resolve(path);\n\tconst missing = [];\n\twhile (true) try {\n\t\tconst canonical = await realpath(current);\n\t\tif (missing.length > 0) await (await opendir(canonical)).close();\n\t\treturn join(canonical, ...missing.reverse());\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t\tconst parent = dirname(current);\n\t\t/* v8 ignore next -- a filesystem root exists, so traversal resolves before this guard */\n\t\tif (parent === current) throw error;\n\t\tmissing.push(basename(current));\n\t\tcurrent = parent;\n\t}\n}\n/**\n* Resolve the default DeepSeek Harness home using Node's platform path rules.\n* @returns the absolute default harness home path.\n*/\nfunction defaultDshHome() {\n\treturn join(homedir(), DSH_HOME_DIR_NAME);\n}\n/**\n* Resolve the default shared agent configuration root using Node's platform path rules.\n* @returns the absolute default shared agent configuration root.\n*/\nfunction defaultAgentsHome() {\n\treturn join(homedir(), AGENTS_HOME_DIR_NAME);\n}\n/**\n* Expand supported tilde prefixes against the operating-system home.\n* @param path - configured path that may begin with `~`, `~/`, or `~\\`.\n* @returns the expanded path, or the original value when no supported prefix is present.\n*/\nfunction expandHomePath(path) {\n\tif (path === \"~\") return homedir();\n\tif (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) return join(homedir(), path.slice(2));\n\treturn path;\n}\n/**\n* Resolve one user-data root from an explicit path, an environment override, and a default.\n* @param configured - explicit path, which has highest precedence.\n* @param env - environment mapping to read.\n* @param envName - environment variable that overrides the default.\n* @param fallback - default root, used when neither the explicit path nor the environment provides one.\n* @returns the normalized absolute root.\n*/\nfunction resolveRoot(configured, env, envName, fallback) {\n\tconst fromEnv = env[envName];\n\treturn resolve(expandHomePath(configured ?? (fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : fallback())));\n}\n/**\n* Label one resolved user-data root symbolically for user-facing display.\n* @param resolvedRoot - absolute path returned by the matching resolver.\n* @param defaultRoot - absolute default root whose symbolic label applies to a match.\n* @param defaultLabel - symbolic label for the default root.\n* @param envName - environment variable name that labels any other root.\n* @returns the symbolic label.\n*/\nfunction rootDisplay(resolvedRoot, defaultRoot, defaultLabel, envName) {\n\treturn resolvedRoot === resolve(defaultRoot) ? defaultLabel : `$${envName}`;\n}\n/**\n* Resolve the single-root DeepSeek Harness home.\n*\n* Precedence, highest first: an explicit configured path, `$DSH_HOME`, then\n* `~/.dsh`. The harness keeps all user data under one root. An empty or\n* whitespace-only `$DSH_HOME` is treated as unset, so a blank override never\n* resolves the home to the current working directory.\n* @param configured - explicit harness-home override, which has highest precedence.\n* @param env - environment mapping used to read `DSH_HOME`.\n* @returns the normalized absolute harness home path.\n*/\nfunction resolveDshHome(configured, env = process.env) {\n\treturn resolveRoot(configured, env, DSH_HOME_ENV, defaultDshHome);\n}\n/**\n* Resolve the shared agent configuration root.\n*\n* Precedence, highest first: an explicit configured path, `$DSH_AGENTS_HOME`,\n* then `~/.agents`. The root holds configuration shared with other agent tools,\n* so it stays independent of the DeepSeek Harness home. An empty or\n* whitespace-only `$DSH_AGENTS_HOME` is treated as unset, so a blank override\n* never resolves the root to the current working directory.\n* @param configured - explicit shared-root override, which has highest precedence.\n* @param env - environment mapping used to read `DSH_AGENTS_HOME`.\n* @returns the normalized absolute shared agent configuration root.\n*/\nfunction resolveAgentsHome(configured, env = process.env) {\n\treturn resolveRoot(configured, env, AGENTS_HOME_ENV, defaultAgentsHome);\n}\n/**\n* Join path segments onto the resolved DeepSeek Harness home. It addresses the\n* existing top-level entries; a new path uses {@link dshPath} with its category.\n* @param segments - path segments appended to the Harness home; an empty list returns the home itself.\n* @returns the normalized absolute joined path.\n*/\nfunction dshHomePath(...segments) {\n\treturn join(resolveDshHome(), ...segments);\n}\n/**\n* Join path segments onto the resolved Harness home's `cache` directory without creating it; no arguments returns the directory itself.\n* @param optionsOrSegment - explicit home override, or the first path segment; omission uses the default home resolution.\n* @param segments - additional path segments after the first child, if any.\n* @returns the normalized absolute cache path.\n*/\nfunction dshCachePath(optionsOrSegment = {}, ...segments) {\n\tif (typeof optionsOrSegment === \"string\") return dshPath(\"cache\", optionsOrSegment, ...segments);\n\treturn dshPath({\n\t\tcategory: \"cache\",\n\t\tdshHome: optionsOrSegment.dshHome\n\t}, ...segments);\n}\n/**\n* Join path segments onto one category directory of the Harness home without\n* creating it. An owner passes its own directory name, normally its package\n* name without the `@deepseek-ai/dsh-` prefix, as the first segment.\n* @param location - category under the resolved home, or a category with an explicit home override.\n* @param segments - path segments appended to the category directory; an empty list returns the directory itself.\n* @returns the normalized absolute path.\n*/\nfunction dshPath(location, ...segments) {\n\tconst { category, dshHome } = typeof location === \"string\" ? {\n\t\tcategory: location,\n\t\tdshHome: void 0\n\t} : location;\n\treturn join(resolveDshHome(dshHome), category, ...segments);\n}\n/**\n* Describe a resolved harness home symbolically for user-facing display.\n*\n* It never returns an absolute machine path: the default home is labelled\n* `~/.dsh`, and any configured home is labelled `$DSH_HOME`.\n* @param resolvedHome - the absolute path returned by {@link resolveDshHome}.\n* @returns `~/.dsh` for the default home, otherwise `$DSH_HOME`.\n*/\nfunction dshHomeDisplay(resolvedHome) {\n\treturn rootDisplay(resolvedHome, defaultDshHome(), DEFAULT_DSH_HOME_DISPLAY, DSH_HOME_ENV);\n}\n/**\n* Describe a resolved shared agent configuration root symbolically for user-facing display.\n*\n* It never returns an absolute machine path: the default root is labelled\n* `~/.agents`, and any configured root is labelled `$DSH_AGENTS_HOME`.\n* @param resolvedHome - the absolute path returned by {@link resolveAgentsHome}.\n* @returns `~/.agents` for the default root, otherwise `$DSH_AGENTS_HOME`.\n*/\nfunction agentsHomeDisplay(resolvedHome) {\n\treturn rootDisplay(resolvedHome, defaultAgentsHome(), DEFAULT_AGENTS_HOME_DISPLAY, AGENTS_HOME_ENV);\n}\n//#endregion\nexport { AGENTS_HOME_DIR_NAME, AGENTS_HOME_ENV, DEFAULT_AGENTS_HOME_DISPLAY, DEFAULT_DSH_HOME_DISPLAY, DSH_HOME_DIR_NAME, DSH_HOME_ENV, agentsHomeDisplay, canonicalizeWatchPath, defaultAgentsHome, defaultDshHome, dshCachePath, dshHomeDisplay, dshHomePath, dshPath, expandHomePath, resolveAgentsHome, resolveDshHome };\n", "/**\n * This plugin's exact Fetch routes, carried by Connection's authenticated\n * `/api` transport below the shared channel.\n *\n * Configuration and credentials use DSH services. These four exact routes\n * serve the log, prompt preview, connectivity probe and sample judgement.\n * The physical /api carrier requires authentication; Connection's shared Fetch\n * handler checks that the admitted Peer is an owner before invoking any exact\n * route. The exact-route callback receives only Request, not the Peer.\n */\n\nimport type { ConnectionFetchRoute } from '@deepseek-ai/dsh-client-connection';\nimport { buildPreview, selectableRows } from './judge-prompt.ts';\nimport { LOG_PAGE_LIMIT } from './log-store.ts';\nimport { probeJudge } from './judge-client.ts';\nimport type { ResolvedConfig } from './config.ts';\nimport type { LogEntry } from './types.ts';\n\n/** Runtime log route path. */\nexport const LOG_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/log';\n\n/** Exact judge-prompt preview route path. */\nexport const PREVIEW_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/preview';\n\n/** Judge endpoint probe route path. */\nexport const PROBE_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/probe';\nexport const SAMPLE_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/sample';\n\nfunction sendJson(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json; charset=utf-8' },\n });\n}\n\n/** What one probe reports back to the page. */\nexport interface ProbeResult {\n ok: boolean;\n latencyMs: number;\n /** Which failure it was, when it failed. */\n reason?: string;\n}\n\n/** The Host-side face the routes read. */\nexport interface DispatchRouteFace {\n /** Current committed configuration. */\n config(): ResolvedConfig;\n /** Read the whole kept log, newest first; may resolve once the file has been read. */\n log(): LogEntry[] | Promise<LogEntry[]>;\n /** The judge key resolved from credentials, or '' when unset. */\n apiKey(): string;\n sample(task: string): Promise<unknown>;\n}\n\n/**\n * Build this plugin's Fetch routes.\n * @param face - the Host-side reads the routes serve.\n * @returns the routes to register on Connection.\n */\nexport function createFetchRoutes(face: DispatchRouteFace): ConnectionFetchRoute[] {\n const log: ConnectionFetchRoute = {\n path: LOG_ROUTE_PATH,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n // The page shows only the tail of the log; the file keeps the rest.\n return sendJson(200, { ok: true, entries: (await face.log()).slice(0, LOG_PAGE_LIMIT) });\n } catch (err) {\n return sendJson(500, { ok: false, error: describe(err) });\n }\n },\n };\n\n const preview: ConnectionFetchRoute = {\n path: PREVIEW_ROUTE_PATH,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n const config = face.config();\n // Built by the same function the real call uses, so what the page shows\n // cannot drift from what goes out.\n const text = buildPreview(selectableRows(config.rows), config.judgeModel.trim());\n return sendJson(200, { ok: true, preview: text });\n } catch (err) {\n return sendJson(500, { ok: false, error: describe(err) });\n }\n },\n };\n\n const probe: ConnectionFetchRoute = {\n path: PROBE_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n const config = face.config();\n // \u53EA\u95EE\u300C\u8FD9\u4E2A\u5730\u5740\u4E0E\u6A21\u578B\u7B54\u4E0D\u7B54\u5F97\u4E0A\u6765\u300D\uFF0C\u6240\u4EE5\u4E0D\u95EE\u7C7B\u578B\u6E05\u5355\uFF1A\u6E05\u5355\u662F\u5224\u65AD\u65F6\u624D\n // \u9700\u8981\u7684\u8F93\u5165\uFF0C\u62FF\u5B83\u5F53\u4F5C\u80FD\u4E0D\u80FD\u6D4B\u7684\u524D\u63D0\uFF0C\u4F1A\u8BA9\u7A7A\u6E05\u5355\u7684\u8BFB\u8005\u4EE5\u4E3A\u670D\u52A1\u574F\u4E86\u3002\n const outcome = await probeJudge({\n url: config.endpointUrl,\n model: config.judgeModel,\n apiKey: face.apiKey(),\n });\n return sendJson(200, { ...outcome } satisfies ProbeResult);\n } catch (err) {\n return sendJson(500, { ok: false, error: describe(err) });\n }\n },\n };\n\n const sample: ConnectionFetchRoute = {\n path: SAMPLE_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request) => {\n try {\n const body: unknown = await request.json();\n const task = typeof body === 'object' && body !== null && 'task' in body ? body.task : undefined;\n if (typeof task !== 'string' || task.trim() === '' || task.length > 10000) return sendJson(400, { ok: false });\n return sendJson(200, await face.sample(task));\n } catch {\n return sendJson(500, { ok: false });\n }\n },\n };\n return [log, preview, probe, sample];\n}\n\n/** One-line error text for a route failure. */\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n", "import type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection';\nimport { SETTINGS_NAMESPACE } from './enablement.ts';\nimport {\n isJudgeUsable,\n readPluginConfig,\n type PluginConfigRefs,\n type ResolvedConfig,\n} from './server/config.ts';\nimport { JUDGE_API_KEY_REF, type CredentialsServiceLike } from './server/credentials.ts';\nimport { decideRewrite, outcomeReason } from './server/dispatch.ts';\nimport {\n hasRecordedRoute,\n isSubagent,\n readDelegatedTask,\n resolveRootSessionId,\n type SessionHeaderLike,\n type SessionLike,\n} from './server/identity.ts';\nimport { JudgeBudget } from './server/judge-budget.ts';\nimport { judgeTaskType } from './server/judge-client.ts';\nimport { composeJudgeSubject, selectableRows } from './server/judge-prompt.ts';\nimport { LogStore } from './server/log-store.ts';\nimport { createFetchRoutes } from './server/router.ts';\nimport type { FallbackReason, LogEntry } from './server/types.ts';\n\n/**\n * Stable Cordis loader name; the same literal as the `id` of this plugin's row\n * in `cordis.patch.yml` and as its settings namespace.\n */\nexport const name = SETTINGS_NAMESPACE;\n\n/**\n * Declared services. `credentials` is the DSH-owned secret surface the judge key\n * is read through. `sessions` finds the task the parent delegated. The Fetch\n * routes ride Connection's authenticated transport, which only a Web carrier composes, so they are taken\n * through `ctx.inject` and the plugin still loads without one.\n */\nexport const inject = ['credentials', 'sessions'];\n\nexport { Config } from './server/config.ts';\nexport { JUDGE_API_KEY_REF } from './server/credentials.ts';\n\n/** Minimal structural shape of this plugin's own `settings` usage. */\ninterface SettingsLike {\n configure(presentation: { auto?: boolean }, owner?: unknown): () => void;\n}\n\n/**\n * The Host context surface this plugin uses.\n *\n * Declared structurally rather than by extending `Context`: the fields read here\n * (`inject` with a narrower dependency list, `on` for one waterfall event) are a\n * subset with a deliberately looser signature, and widening `inject` to satisfy\n * the interface would hide the services this plugin actually declares through\n * the exported `inject` table.\n */\ninterface HostContext {\n credentials: CredentialsServiceLike;\n sessions: { get(id: string): unknown };\n settings: SettingsLike;\n fiber: unknown;\n get(name: 'sessionPersistence'): { stat(id: string): Promise<{ header: SessionHeaderLike } | undefined> } | undefined;\n get(name: 'subagentModelSelection'): { allowedRoutes(): readonly ModelRoute[] | undefined } | undefined;\n get(name: 'llm'): { resolveCallConfig(selection: RouteSelection, signal?: AbortSignal): Promise<unknown> } | undefined;\n on(event: string, listener: (...args: any[]) => unknown): () => void;\n effect(factory: () => void | (() => void | Promise<void>), label?: string): unknown;\n inject(names: string[] | string, callback: (ctx: HostContext) => void | (() => void)): void;\n}\n\n/** The route a child runs on; the three fields travel together. */\ninterface ModelRoute {\n provider: string;\n model: string;\n}\n\ninterface RouteSelection extends ModelRoute {\n reasoningEffort?: string;\n}\n\n/** The Agent model face this plugin uses: read the inherited route, select the judged one. */\ninterface AgentModelLike {\n current(): RouteSelection | undefined;\n select(selection: RouteSelection): void;\n}\n\n/** Which Agent fields this plugin reads when a child is created. */\ninterface RequestAgent {\n id: string;\n options: { subagentDepth?: number };\n session: SessionLike;\n model: AgentModelLike;\n}\n\n/** How many judged children to remember before forgetting the oldest. */\nconst JUDGED_LIMIT = 500;\n\n/**\n * The set of children already judged, bounded so a long-running instance cannot\n * grow without limit.\n *\n * Insertion order is eviction order: a `Set` iterates oldest-first, so the one\n * entry that goes is always the earliest judgement. Forgetting a very old child\n * costs at most one extra judgement should it somehow make another request,\n * which is strictly better than an unbounded map keyed by every subagent ever\n * delegated.\n */\nclass JudgedChildren {\n private readonly seen = new Set<string>();\n\n /** Record a child as judged, forgetting the oldest entry past the cap. */\n add(id: string): void {\n this.seen.add(id);\n if (this.seen.size <= JUDGED_LIMIT) return;\n const oldest = this.seen.values().next();\n if (!oldest.done) this.seen.delete(oldest.value);\n }\n\n /** Whether this child has already been judged. */\n has(id: string): boolean {\n return this.seen.has(id);\n }\n}\n\n/**\n * Mount the host half: judge every subagent once, write the route the judgement\n * chose, and keep the log the Plugins page reads.\n *\n * @param ctx - DSH Host context.\n * @param config - this plugin's runtime-resolved Config (every field a live ref).\n */\nexport function apply(ctx: HostContext, config: PluginConfigRefs): void {\n const log = new LogStore();\n const lifetime = new AbortController();\n /** Children already judged, so a ten-step child is asked about once. */\n const judged = new JudgedChildren();\n let apiKey = '';\n\n void log.init();\n\n const resolvedConfig = (): ResolvedConfig => readPluginConfig(config);\n\n /** Re-read the judge key; a key set outside the page takes effect at once. */\n const refreshKey = async (): Promise<void> => {\n try {\n apiKey = ((await ctx.credentials.resolve(JUDGE_API_KEY_REF))?.value ?? '').trim();\n } catch {\n apiKey = '';\n }\n };\n void refreshKey();\n ctx.on('credentials/reference-updated', () => {\n void refreshKey();\n });\n\n // Settings are read and written through the Plugins page's own card; DSH must\n // not also derive a generic settings form for the same entry.\n ctx.inject(['settings'], (child) => {\n child.effect(\n () => child.settings.configure({ auto: false }, child.fiber),\n 'dsh-subagent-judge-dispatch: settings page policy'\n );\n });\n\n /**\n * The delegation hook: one judgement per subagent, then the route it chose.\n *\n * Runs on `agent/created`, which the Host awaits before releasing the child's\n * queued work: the route selected here is the one the child's first step\n * prepares with.\n *\n * Never throws and never cancels: every failure path writes nothing, which is\n * what makes a judge outage cost latency and nothing else. The judgement is\n * awaited because the Host awaits this hook, so it can add up to the judge\n * budget to that one delegation.\n */\n ctx.on('agent/created', async ({ agent, source, signal }: {\n agent?: RequestAgent; source: string; signal?: AbortSignal;\n }) => {\n const cancellation = signal === undefined ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);\n if (agent === undefined || !isSubagent(agent) || judged.has(agent.id) || cancellation.aborted) return;\n if (source !== 'startup' && source !== 'resume') return;\n\n const budget = new JudgeBudget(cancellation);\n try {\n const lookup = (id: string) => ctx.sessions.get(id) as SessionLike | undefined;\n const parentId = agent.session.header.parentSession;\n const rootId = parentId ? await budget.run(() => resolveRootSessionId(parentId, async (id) => {\n budget.check();\n return lookup(id)?.header ?? (await ctx.get('sessionPersistence')?.stat(id))?.header;\n })) : undefined;\n const cfg = resolvedConfig();\n if (cancellation.aborted || !isJudgeUsable(cfg, rootId) || judged.has(agent.id)) return;\n const task = readDelegatedTask(agent, lookup, source === 'resume');\n if (task === undefined || task.explicitRoute) return;\n judged.add(agent.id);\n\n const { label, text: taskText } = task;\n const inherited = agent.model.current() ?? { provider: '', model: '' };\n const outcome = await judgeTaskType(\n { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },\n selectableRows(cfg.rows),\n composeJudgeSubject(label, taskText),\n fetch,\n budget,\n );\n let decision = decideRewrite(outcome);\n let routeFailure: FallbackReason | undefined;\n if (decision.kind === 'rewrite') {\n const route = decision.rewrite;\n const llm = ctx.get('llm');\n const allowed = (): boolean => ctx.get('subagentModelSelection')?.allowedRoutes()?.some(\n (pair) => pair.provider === route.provider && pair.model === route.model,\n ) === true;\n try {\n if (llm === undefined || !allowed()) throw new Error('Unavailable child route');\n await budget.run((preflightSignal) => llm.resolveCallConfig(route, preflightSignal));\n if (!allowed()) throw new Error('Child route no longer allowed');\n if (cancellation.aborted || !isJudgeUsable(resolvedConfig(), rootId) || hasRecordedRoute(agent.session)) return;\n budget.check();\n agent.model.select(route);\n } catch {\n decision = { kind: 'none' };\n routeFailure = budget.expired() ? 'timeout' : 'unavailable-route';\n }\n }\n\n if (resolvedConfig().logEnabled && !cancellation.aborted) {\n log.append(buildEntry(inherited, decision, outcome, budget.elapsed(), routeFailure));\n }\n } catch {\n // A judge outage, an unreadable parent log or a Host rejection of the\n // selection costs this delegation latency and nothing else.\n } finally {\n budget.dispose();\n }\n });\n\n // The three reads only the Host can answer. Connection's /api transport is\n // composed by a Web carrier; without one the plugin loads and simply has no\n // HTTP surface.\n ctx.inject(['connection'], (connectionCtx) => {\n const routes = createFetchRoutes({\n config: resolvedConfig,\n log: () => log.readLatest(),\n apiKey: () => apiKey,\n sample: async (task) => {\n const cfg = resolvedConfig();\n const budget = new JudgeBudget(lifetime.signal);\n try {\n const outcome = await judgeTaskType(\n { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },\n selectableRows(cfg.rows), composeJudgeSubject('', task), fetch, budget,\n );\n const decision = decideRewrite(outcome);\n if (decision.kind !== 'rewrite') return { ok: false, reason: outcomeReason(outcome, decision) };\n const route = decision.rewrite;\n const llm = ctx.get('llm');\n const allowed = () => ctx.get('subagentModelSelection')?.allowedRoutes()?.some(\n (pair) => pair.provider === route.provider && pair.model === route.model,\n ) === true;\n try {\n if (llm === undefined || !allowed()) throw new Error('Unavailable child route');\n await budget.run((signal) => llm.resolveCallConfig(route, signal));\n if (!allowed()) throw new Error('Child route no longer allowed');\n budget.check();\n return { ok: true, typeId: outcome.kind === 'matched' ? outcome.row.id : null, route, valid: true };\n } catch {\n return { ok: false, typeId: outcome.kind === 'matched' ? outcome.row.id : null, route, valid: false,\n reason: budget.expired() ? 'timeout' : 'unavailable-route' };\n }\n } finally {\n budget.dispose();\n }\n },\n });\n const disposers = routes.map((route) =>\n (connectionCtx as HostContext & { connection: HostConnectionHandle }).connection.fetch.register(route)\n );\n return () => {\n for (const dispose of disposers) void Promise.resolve(dispose()).catch(() => {});\n };\n });\n\n // \u6BCF\u6B21\u8FFD\u52A0\u90FD\u7ACB\u523B\u5F00\u5199\uFF1B\u5378\u8F7D\u65F6\u518D\u7B49\u4E00\u6B21\u5728\u98DE\u7684\u5199\u843D\u5730\uFF0C\u5378\u8F7D\u4E0D\u4E22\u6700\u540E\u90A3\u6761\u3002\n ctx.effect(\n () => () => {\n lifetime.abort();\n return log.flush();\n },\n 'dsh-subagent-judge-dispatch: judgement log flush',\n );\n}\n\n/**\n * Build the log row for one judged delegation.\n *\n * A fallback row reports the route the child actually keeps \u2014 the main agent's\n * resolved provider, model and effort \u2014 rather than a blank, because the point\n * of the row is what the child ran on.\n */\nfunction buildEntry(\n resolved: RouteSelection,\n decision: ReturnType<typeof decideRewrite>,\n outcome: Awaited<ReturnType<typeof judgeTaskType>>,\n latencyMs: number,\n routeFailure: FallbackReason | undefined,\n): LogEntry {\n const matched = decision.kind === 'rewrite';\n const reason = routeFailure ?? outcomeReason(outcome, decision);\n return {\n typeId: matched && outcome.kind === 'matched' ? outcome.row.id : null,\n ...matched && outcome.kind === 'matched' && outcome.row.stableId ? { typeKey: outcome.row.stableId } : {},\n provider: matched ? decision.rewrite.provider : resolved.provider,\n model: matched ? decision.rewrite.model : resolved.model,\n effort: matched\n ? decision.rewrite.reasoningEffort\n : typeof resolved.reasoningEffort === 'string' ? resolved.reasoningEffort : '',\n ...reason === undefined ? {} : { reason },\n at: Date.now(),\n latencyMs,\n ...outcome.metrics === undefined ? {} : { metrics: outcome.metrics },\n };\n}\n"],
5
- "mappings": ";AACO,IAAM,kBAAkB;AACxB,IAAM,qBAAqB;AAK3B,SAAS,WAAW,WAAoB,UAAmB,WAA6B;AAC7F,MAAI,cAAc,UAAa,cAAc,QAAQ,OAAO,cAAc,YACrE,CAAC,OAAO,OAAO,WAAW,SAAS,EAAG,QAAO;AAClD,QAAM,SAAU,UAA+B,SAAS;AACxD,SAAO,OAAO,WAAW,YAAY,SAAS;AAChD;;;ACKA,OAAO,OAAO;;;ACNd,IAAM,iBAAiB,CAAC,iBAAiB,YAAY;AAa9C,SAAS,mBAAmB,OAAwB;AACzD,QAAM,UAAU,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;AAC3D,MAAI,YAAY,GAAI,QAAO;AAC3B,QAAM,UAAU,QAAQ,QAAQ,QAAQ,EAAE;AAC1C,MAAI,eAAe,KAAK,CAACA,UAAS,QAAQ,SAASA,KAAI,CAAC,EAAG,QAAO;AAClE,MAAI,QAAQ,SAAS,KAAK,EAAG,QAAO,GAAG,OAAO;AAC9C,SAAO,GAAG,OAAO;AACnB;;;ACNA,IAAM,eAAe;AASd,IAAM,wBACX;AAKK,IAAM,kBAAkB;AAG/B,IAAM,kBAAkB;AASxB,IAAM,qBAC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,UACA,UACA,SACA,WACA,cACU;AACV,QAAM,UAAU,SAAS,SAAS;AAClC,QAAM,SAAS,gBAAgB,cAAc,SAAS,QAAQ;AAC9D,SAAO;AAAA,IACL,QAAQ,WAAW,QAAQ,SAAS,YAAY,QAAQ,IAAI,KAAK;AAAA,IACjE,GAAG,WAAW,QAAQ,SAAS,aAAa,QAAQ,IAAI,WAAW,EAAE,SAAS,QAAQ,IAAI,SAAS,IAAI,CAAC;AAAA,IACxG,UAAU,UAAU,SAAS,QAAQ,WAAW,SAAS;AAAA,IACzD,OAAO,UAAU,SAAS,QAAQ,QAAQ,SAAS;AAAA,IACnD,QAAQ,UACJ,SAAS,QAAQ,kBACjB,OAAO,SAAS,oBAAoB,WAAW,SAAS,kBAAkB;AAAA,IAC9E,GAAG,WAAW,SAAY,CAAC,IAAI,EAAE,OAAO;AAAA,IACxC,IAAI,KAAK,IAAI;AAAA,IACb;AAAA,IACA,GAAG,QAAQ,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;AAAA,EACrE;AACF;",
4
+ "sourcesContent": ["/** Shared by the host and the conversation menu. */\nexport const DEFAULT_ENABLED = true;\nexport const SETTINGS_NAMESPACE = 'dsh-subagent-judge-dispatch';\n\nexport type SessionOverrides = Readonly<Record<string, boolean>>;\n\n/** An explicit choice takes precedence over the plugin default. */\nexport function enabledFor(overrides: unknown, fallback: boolean, sessionId?: string): boolean {\n if (sessionId === undefined || overrides === null || typeof overrides !== 'object'\n || !Object.hasOwn(overrides, sessionId)) return fallback;\n const choice = (overrides as SessionOverrides)[sessionId];\n return typeof choice === 'boolean' ? choice : fallback;\n}\n", "/**\n * This plugin's Config schema and the live read face the wiring consumes.\n *\n * Every field is `volatile()`, which is what lets the configuration card on the\n * Plugins page commit an edit into these refs without remounting the plugin:\n * the wiring reads the current value on every delegation rather than a snapshot\n * taken when the Host loaded.\n *\n * The type-list rows carry no sequence number. The page numbers the rows the\n * judge is offered \u2014 switched on and filled in \u2014 counting from 1 in array\n * order; the judge answers with that number, and the log shows it, so a number\n * can never be duplicated and the reader never has to maintain one. A row that\n * is switched off or not filled in keeps its place in the list but carries no\n * number, which is why the numbers offered to the judge stay continuous.\n */\n\nimport type { Volatile } from '@deepseek-ai/cordis';\nimport z from '@deepseek-ai/schemastery';\nimport type Schema from '@deepseek-ai/schemastery';\nimport { resolveEndpointUrl } from './endpoint.ts';\nimport { numberTypeRows, selectableRows } from './judge-prompt.ts';\nimport type { TypeRow } from './types.ts';\nimport { DEFAULT_ENABLED, enabledFor, type SessionOverrides } from '../enablement.ts';\n\n/** One type-list row as the configuration document stores it. */\nconst TypeRowSchema = z.object({\n stableId: z.string().default(''),\n /** Whether this type takes part in judgements; a row written before the switch existed counts as on. */\n enabled: z.boolean().default(true),\n /** Criterion text the judge reads for this type. */\n description: z.string().default(''),\n /** Provider route of the model this type runs on. */\n provider: z.string().default(''),\n /** Model id interpreted by that provider. */\n model: z.string().default(''),\n /** Reasoning effort id this type runs at. */\n effort: z.string().default(''),\n});\n\n/** This plugin's live configuration. */\nexport const Config: Schema = z.object({\n /** Default for conversations without their own choice. */\n enabled: z.boolean().default(DEFAULT_ENABLED).volatile(),\n sessionOverrides: z.dict(z.boolean()).default({}).volatile(),\n /** Whether judgements are written to the plugin's own log. */\n logEnabled: z.boolean().default(true).volatile(),\n /** Judge service address, as the reader typed it; the path is appended when a call is made. */\n endpointUrl: z.string().default('').volatile(),\n /** Judge model id. */\n judgeModel: z.string().default('').volatile(),\n /** The task-type list, in page order. */\n rows: z.array(TypeRowSchema).default([]).volatile(),\n});\n\n/** Fields of this plugin's Config as the runtime resolved them. */\nexport interface PluginConfigRefs {\n readonly enabled: Volatile<boolean>;\n readonly sessionOverrides: Volatile<SessionOverrides>;\n readonly logEnabled: Volatile<boolean>;\n readonly endpointUrl: Volatile<string>;\n readonly judgeModel: Volatile<string>;\n readonly rows: Volatile<StoredRow[]>;\n}\n\n/** One stored row, before the page assigns its sequence number. */\nexport interface StoredRow {\n stableId?: string;\n /** Whether this type takes part in judgements. */\n enabled: boolean;\n description: string;\n provider: string;\n model: string;\n effort: string;\n}\n\n/** A detached plain read of this plugin's configuration. */\nexport interface ResolvedConfig {\n enabled: boolean;\n sessionOverrides: SessionOverrides;\n logEnabled: boolean;\n /** Full judge URL: the stored address with the service path applied. */\n endpointUrl: string;\n judgeModel: string;\n rows: TypeRow[];\n}\n\n/**\n * Read the current committed value of every Config field, numbering the rows.\n * @param refs - the runtime-resolved Config object.\n * @returns a detached plain config value.\n */\nexport function readPluginConfig(refs: PluginConfigRefs): ResolvedConfig {\n const stored = refs.rows.get();\n // The number is positional, so deleting, moving, switching off or filling in\n // a row renumbers the rest. A log entry written before that edit may therefore\n // name a different type; the reader accepted that when choosing continuous\n // numbering. A row that is not offered keeps its place and carries number 0.\n const rows: TypeRow[] = numberTypeRows((Array.isArray(stored) ? stored : []).map((row) => ({\n stableId: typeof row?.stableId === 'string' ? row.stableId : '',\n enabled: row?.enabled !== false,\n description: typeof row?.description === 'string' ? row.description : '',\n provider: typeof row?.provider === 'string' ? row.provider : '',\n model: typeof row?.model === 'string' ? row.model : '',\n effort: typeof row?.effort === 'string' ? row.effort : '',\n })));\n return {\n enabled: refs.enabled.get() ?? DEFAULT_ENABLED,\n sessionOverrides: refs.sessionOverrides.get(),\n logEnabled: refs.logEnabled.get() !== false,\n endpointUrl: resolveEndpointUrl(refs.endpointUrl.get()),\n judgeModel: typeof refs.judgeModel.get() === 'string' ? refs.judgeModel.get() : '',\n rows,\n };\n}\n\n/**\n * Whether a delegation would be judged given the root conversation's choice\n * and the available judgement service and task types.\n */\nexport function isJudgeUsable(config: ResolvedConfig, rootSessionId?: string): boolean {\n if (!enabledFor(config.sessionOverrides, config.enabled, rootSessionId)) return false;\n if (config.endpointUrl.trim() === '' || config.judgeModel.trim() === '') return false;\n return selectableRows(config.rows).length > 0;\n}\n", "/**\n * Where a judgement is sent: the address the reader typed, with the service's\n * path appended when it does not already carry one.\n *\n * The page asks for the address only. Which path the service lives at is\n * decided here rather than asked as a second setting: an address that already\n * names one of the known paths is used as it is, and anything shorter gets the\n * default. This module imports nothing, so both halves can share the rule.\n */\n\n/** Paths the service is reached at; the first is the one appended by default. */\nconst ENDPOINT_PATHS = ['/v1/systemone', '/systemone'] as const;\n\n/**\n * Turn the typed address into the URL a request is sent to.\n *\n * An address that already ends with one of the known paths is left as it is, so\n * a stored full URL \u2014 or one pasted from elsewhere \u2014 is never doubled. An\n * address that stops at the default path's own prefix (`\u2026/v1`) only needs the\n * rest of it. Everything shorter gets the default path.\n *\n * @param input - the address the reader typed.\n * @returns the URL to call, or '' when no address is set.\n */\nexport function resolveEndpointUrl(input: unknown): string {\n const trimmed = typeof input === 'string' ? input.trim() : '';\n const url = URL.parse(trimmed);\n if (url === null) return trimmed;\n const pathname = url.pathname.replace(/\\/+$/, '');\n url.pathname = ENDPOINT_PATHS.some((path) => pathname.endsWith(path))\n ? pathname\n : pathname + (pathname.endsWith('/v1') ? '/systemone' : ENDPOINT_PATHS[0]);\n return url.href;\n}\n", "/**\n * The judgement request the plugin sends, and the answer it reads back.\n *\n * Two pure functions live here, so the whole \"what did the judge decide\"\n * question is answerable without a Host, a socket, or a timer:\n *\n * - {@link buildJudgeRequest} turns the type list plus the task text into the\n * exact body that goes out.\n * - {@link readJudgeAnswer} turns whatever came back into a decision, treating\n * every malformed, empty or off-list answer as \"no decision\" rather than\n * inventing one.\n *\n * The list rules live here as well, because the criteria map IS the list: which\n * rows are offered ({@link selectableRows}) and what number each carries\n * ({@link numberTypeRows}).\n *\n * The protocol is the System One one: POST a body of `{ model, state,\n * questions }`, where each question is a `choice` carrying an `instructions`\n * line and a `criteria` map of option id to the text that option means. The\n * answer names the chosen option id.\n */\n\nimport type { TypeRow } from './types.ts';\n\n/** The one question key the plugin asks. */\nconst QUESTION_KEY = 'task_type';\n\n/**\n * The question's instructions line.\n *\n * It says what to weigh, not what the types are: the types themselves arrive as\n * the criteria map, so the reader's own descriptions are the whole criterion\n * list and nothing here can drift from them.\n */\nexport const QUESTION_INSTRUCTIONS =\n 'Which single task type below does the delegated job best match? '\n + 'Weigh what the job actually requires, not how it is phrased. '\n + 'Answer with the number of exactly one listed type.';\n\n/** The option id the connectivity check offers: the only one it offers. */\nexport const PROBE_OPTION_ID = '1';\n\n/** The task text the connectivity check sends. */\nconst PROBE_TASK_TEXT = '\u8FDE\u63A5\u6D4B\u8BD5\uFF1A\u8FD9\u662F\u4E00\u6B21\u5224\u65AD\u670D\u52A1\u7684\u8FDE\u901A\u6027\u68C0\u67E5\u3002';\n\n/**\n * The connectivity check's instructions.\n *\n * It asks for the one option that exists, so an endpoint that understands the\n * protocol at all can answer it: answering it wrong is a failure of the\n * protocol, not of the reader's task list.\n */\nconst PROBE_INSTRUCTIONS =\n 'Answer with the number of the one option listed below.';\n\n/** The single criterion the connectivity check offers. */\nconst PROBE_CRITERION = '\u786E\u8BA4\u8FD9\u6B21\u8C03\u7528\u53EF\u4EE5\u5B8C\u6210\u3002';\n\n/** One option of the judge's question. */\nexport interface JudgeChoice {\n type: 'choice';\n instructions: string;\n criteria: Record<string, string>;\n}\n\n/** The exact body sent to the judge endpoint. */\nexport interface JudgeRequest {\n model: string;\n state: { message: string };\n questions: { [QUESTION_KEY]: JudgeChoice };\n}\n\n/**\n * Whether one row is complete enough to be offered to the judge.\n *\n * A row needs its provider, model and effort: a half-filled row could otherwise\n * be chosen and then have nothing to write, which would turn the reader's\n * unfinished edit into a delegation that silently lost its route. This is the\n * ONE place that rule lives \u2014 the page, the config gate and the rewrite all ask\n * this function rather than restating the three comparisons.\n *\n * The parameter is narrowed to the three fields the rule reads, so the page's\n * draft row (which carries no sequence number) and the server's numbered row\n * both satisfy it without either shape being converted into the other.\n *\n * @param row - one row, numbered or drafted.\n * @returns whether the judge may choose it.\n */\nexport function isSelectableRow(row: Pick<TypeRow, 'provider' | 'model' | 'effort'>): boolean {\n return row.provider.trim() !== '' && row.model.trim() !== '' && row.effort.trim() !== '';\n}\n\n/**\n * Whether one row is switched on.\n *\n * A row that is switched off stays in the list \u2014 the reader keeps it there to\n * turn it back on later \u2014 but takes no part in a judgement and carries no\n * number. A missing value counts as switched on, so a row written before the\n * switch existed keeps working.\n *\n * The parameter is narrowed to the one field the rule reads, so a stored row, a\n * numbered row and the page's draft row all satisfy it.\n *\n * @param row - one row, stored or drafted.\n * @returns whether the row takes part in judgements.\n */\nexport function isRowEnabled(row: { enabled?: boolean }): boolean {\n return row.enabled !== false;\n}\n\n/** The fields a row must carry to be judged: the switch, and the route it runs on. */\ntype RowOffering = { enabled?: boolean } & Pick<TypeRow, 'provider' | 'model' | 'effort'>;\n\n/**\n * Whether one row is offered to the judge: switched on, and its route filled in.\n *\n * The two conditions are one rule because the judge's list is exactly the rows\n * that pass both \u2014 a row switched off is one the reader does not want judged,\n * and a half-filled row could be chosen and then have nothing to write.\n *\n * @param row - one row, stored, numbered or drafted.\n * @returns whether the judge may choose it.\n */\nexport function isOfferedRow(row: RowOffering): boolean {\n return isRowEnabled(row) && isSelectableRow(row);\n}\n\n/**\n * Which rows may be offered to the judge.\n * @param rows - every row on the page, in page order.\n * @returns the rows the judge may choose, in page order.\n */\nexport function selectableRows(rows: readonly TypeRow[]): TypeRow[] {\n return rows.filter(isOfferedRow);\n}\n\n/**\n * Number the rows the judge is offered, in list order.\n *\n * The number is positional and never stored: switching a row off, filling one\n * in, or moving it renumbers the rest. A row that is not offered carries 0 \u2014 it\n * has no number to be answered with \u2014 so the criteria map is numbered 1..n with\n * no gaps, and the preview, the request and the answer all read the same list.\n *\n * @param rows - the rows as the page holds them, in page order.\n * @returns the rows with their numbers applied, in the same order.\n */\nexport function numberTypeRows<T extends RowOffering>(\n rows: readonly T[],\n): (T & { id: number })[] {\n let next = 0;\n return rows.map((row) => {\n if (!isOfferedRow(row)) return { ...row, id: 0 };\n next += 1;\n return { ...row, id: next };\n });\n}\n\n/**\n * How much of a delegated task's opening the judge reads.\n *\n * The judge answers one multiple-choice question; the opening of a task says\n * what kind of job it is, and the rest is usually detail the choice does not\n * turn on. Bounding it keeps the request small and keeps one enormous\n * delegation from crowding out the type list it is being weighed against.\n */\nexport const SUBJECT_HEAD_CHARS = 1400;\n\n/**\n * How much of a task's closing the judge reads.\n *\n * Supplementary requirements are written at the end \u2014 \"also run the review\" \u2014\n * so the tail is kept rather than the middle.\n */\nexport const SUBJECT_TAIL_CHARS = 400;\n\n/** Opening words of the label line the judge reads above the task. */\nconst LABEL_PREFIX = 'Delegation label: ';\n\n/**\n * Build the subject the judge is asked to classify.\n *\n * Two parts, in the order the reader would put them: the delegation's own label\n * \u2014 a summary the delegating agent wrote, which carries its intent \u2014 and then\n * the task text itself. The label alone is a display phrase of a few words, too\n * little to classify by; the task text alone loses that intent when it opens\n * with boilerplate.\n *\n * @param label - the delegation label, or '' when the child has none.\n * @param taskText - the delegated task text, or '' when it cannot be read.\n * @returns the subject to send, bounded to {@link SUBJECT_HEAD_CHARS} plus\n * {@link SUBJECT_TAIL_CHARS} characters of task text.\n */\nexport function composeJudgeSubject(label: string, taskText: string): string {\n const task = clipTaskText(taskText.trim());\n const heading = label.trim();\n if (heading === '') return task;\n return task === '' ? LABEL_PREFIX + heading : `${LABEL_PREFIX}${heading}\\n\\n${task}`;\n}\n\n/**\n * Bound a task text to its opening and closing.\n *\n * The dropped middle is named rather than silently removed, so a reader looking\n * at the logged request can tell truncation from a short task. The marker is\n * English like the rest of the protocol, so it reads as a note from the plugin\n * rather than as part of the task, whatever language the task is written in.\n *\n * @param text - the task text.\n * @returns the text, or its head and tail around a count of what was dropped.\n */\nfunction clipTaskText(text: string): string {\n if (text.length <= SUBJECT_HEAD_CHARS + SUBJECT_TAIL_CHARS) return text;\n const dropped = text.length - SUBJECT_HEAD_CHARS - SUBJECT_TAIL_CHARS;\n const head = text.slice(0, SUBJECT_HEAD_CHARS);\n const tail = text.slice(text.length - SUBJECT_TAIL_CHARS);\n return `${head}\\n\u2026 (${dropped} characters omitted) \u2026\\n${tail}`;\n}\n\n/**\n * Build the exact body sent to the judge endpoint.\n *\n * @param rows - the selectable rows, in page order.\n * @param model - the judge model id.\n * @param subject - the text the judge classifies, from {@link composeJudgeSubject}.\n * @returns the request body.\n */\nexport function buildJudgeRequest(\n rows: readonly TypeRow[],\n model: string,\n subject: string,\n): JudgeRequest {\n const criteria: Record<string, string> = {};\n for (const row of rows) criteria[String(row.id)] = row.description;\n return {\n model,\n state: { message: subject },\n questions: {\n [QUESTION_KEY]: {\n type: 'choice',\n instructions: QUESTION_INSTRUCTIONS,\n criteria,\n },\n },\n };\n}\n\n/**\n * Build the body the connectivity check sends.\n *\n * It carries its own single option rather than the reader's task types: the\n * question the button answers is \"does this endpoint and model work\", and that\n * question has an answer before any type list exists. Requiring a finished list\n * first would make the check unable to tell a reader with an empty list from a\n * reader whose endpoint is down.\n *\n * @param model - the judge model id.\n * @returns the request body.\n */\nexport function buildProbeRequest(model: string): JudgeRequest {\n return {\n model,\n state: { message: PROBE_TASK_TEXT },\n questions: {\n [QUESTION_KEY]: {\n type: 'choice',\n instructions: PROBE_INSTRUCTIONS,\n criteria: { [PROBE_OPTION_ID]: PROBE_CRITERION },\n },\n },\n };\n}\n\n/**\n * Serialize one request body the way the page shows it.\n *\n * Both the preview and a logged judgement display this text, while the call\n * itself sends the same object compacted onto the wire. Deriving both from one\n * body is what keeps the shown text from describing a different request than\n * the one that went out.\n *\n * @param body - the request body.\n * @returns the pretty-printed JSON.\n */\nexport function formatJudgeRequest(body: JudgeRequest): string {\n return JSON.stringify(body, null, 2);\n}\n\n/**\n * The text the configuration page's preview shows.\n *\n * It is the request body minus the subject, because no delegation exists until\n * one happens; the preview marks both spots the subject will fill rather than\n * inventing a task. The two markers are told apart, because the real subject is\n * a label line followed by the task text and the preview should read that way.\n *\n * @param rows - the selectable rows, in page order.\n * @param model - the judge model id.\n * @returns the pretty-printed preview text.\n */\nexport function buildPreview(rows: readonly TypeRow[], model: string): string {\n return formatJudgeRequest(\n buildJudgeRequest(rows, model, composeJudgeSubject('\uFF08\u6D3E\u5DE5\u65F6\u624D\u586B\uFF1A\u6D3E\u5DE5\u6807\u7B7E\uFF09', '\uFF08\u6D3E\u5DE5\u65F6\u624D\u586B\uFF1A\u4EFB\u52A1\u6B63\u6587\uFF09')),\n );\n}\n\n/** What reading the judge's answer produced. */\nexport type JudgeDecision =\n | { kind: 'row'; row: TypeRow }\n | { kind: 'empty' }\n | { kind: 'unmatched' };\n\n/**\n * Find the chosen option id inside whatever the endpoint answered.\n *\n * The protocol's own shape is `answers.<key>.choice`; the two fallbacks are the\n * ones the reference clients read, so an endpoint that answers the shorter way\n * still works. Anything else \u2014 a missing body, a non-string, an empty string \u2014\n * yields `undefined` and is treated as no answer.\n *\n * @param payload - the decoded response body.\n * @returns the chosen option id, or undefined when the body names none.\n */\nexport function readChoice(payload: unknown): string | undefined {\n if (typeof payload !== 'object' || payload === null) return undefined;\n const body = payload as Record<string, unknown>;\n const answers = body.answers;\n const fromAnswers =\n typeof answers === 'object' && answers !== null\n ? (answers as Record<string, unknown>)[QUESTION_KEY]\n : undefined;\n const candidate = fromAnswers ?? body[QUESTION_KEY];\n if (typeof candidate === 'object' && candidate !== null) {\n const choice = (candidate as Record<string, unknown>).choice;\n if (typeof choice === 'string' && choice.trim() !== '') return choice.trim();\n if (typeof choice === 'number' && Number.isFinite(choice)) return String(choice);\n return undefined;\n }\n if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim();\n if (typeof candidate === 'number' && Number.isFinite(candidate)) return String(candidate);\n return undefined;\n}\n\n/**\n * Turn the judge's answer into a decision.\n *\n * The choice is the type row's number. Matching is by that number's numeric\n * value, so an endpoint that answers `\"3\"` and one that answers `3` agree; a\n * number no listed row carries is `unmatched`, and a body naming no choice at\n * all is `empty`. Both travel to the log as their own reason, because \"it\n * answered nothing\" and \"it answered something I do not have\" send the reader\n * to different fixes.\n *\n * @param payload - the decoded response body.\n * @param rows - the selectable rows, in page order.\n * @returns the decision.\n */\nexport function readJudgeAnswer(payload: unknown, rows: readonly TypeRow[]): JudgeDecision {\n const choice = readChoice(payload);\n if (choice === undefined) return { kind: 'empty' };\n const wanted = Number(choice);\n if (!Number.isFinite(wanted)) return { kind: 'unmatched' };\n const row = rows.find((candidate) => candidate.id === wanted);\n return row === undefined ? { kind: 'unmatched' } : { kind: 'row', row };\n}\n", "/**\n * Where the judgement key lives, and the Host service it is read through.\n *\n * The reference name is a constant of the plugin rather than a setting: the\n * page asks for the key itself and stores it write-only through the DSH\n * credentials service, so a reader never has to know what a \"credential\n * reference\" is, and no surface can point the plugin at somebody else's key.\n * This module imports nothing, so both halves can share the literal.\n *\n * The key value crosses in one direction only: it is written, and read back by\n * the Host half alone. The browser face reads a status-only view.\n */\n\n/** Credential reference the judgement key is stored under. */\nexport const JUDGE_API_KEY_REF = 'SUBAGENT_JUDGE_API_KEY';\n\n/** Minimal structural shape of the Host's `ctx.credentials` service. */\nexport interface CredentialsServiceLike {\n /** Resolve a reference to its stored or inherited value. */\n resolve(ref: string): Promise<{ value: string; source?: string } | undefined>;\n /** Status-only view of a reference; never returns the plaintext value. */\n describe(ref: string): Promise<{ configured: boolean; source?: string; writable: boolean }>;\n /** Store a non-empty value under a reference. */\n set(ref: string, value: string): Promise<void>;\n}\n\n/** Minimal structural shape of the browser's `ctx.remote.credentials` face. */\nexport interface CredentialsRemoteLike {\n describe(refs: string[]): Promise<\n { ok: true; value: Record<string, { configured: boolean; source?: string; writable: boolean }> }\n | { ok: false; error: { message: string } }\n >;\n set(ref: string, value: string): Promise<{ ok: true } | { ok: false; error: { message: string } }>;\n}\n", "/**\n * The decision half: given what the judge said, decide exactly what to write\n * onto a subagent's next model call \u2014 or write nothing at all.\n *\n * This module holds the one rule that matters most, so it is a pure function\n * that a test can drive directly: **any** judgement that did not end in a\n * usable row writes nothing. Not \"writes the inherited values\", not \"writes a\n * partial route\" \u2014 nothing. Writing anything is a replacement, so a fallback\n * that wrote the parent's own values back would still be an overwrite, and a\n * partial write would drop the inherited reasoning effort\n * (`resolveChildAgentOptions` deletes it when a route changes without one).\n */\n\nimport { isOfferedRow } from './judge-prompt.ts';\nimport type { FallbackReason, JudgeOutcome, TypeRow } from './types.ts';\n\n/** The three fields a rewrite carries, all present or none at all. */\nexport interface RouteRewrite {\n provider: string;\n model: string;\n reasoningEffort: string;\n}\n\n/** What to write for one judged subagent. */\nexport type DispatchDecision =\n | { kind: 'rewrite'; rewrite: RouteRewrite }\n | { kind: 'none' };\n\n/**\n * Turn a judgement into the rewrite it authorises.\n *\n * The three fields travel as one object because they must be written as one:\n * a route change without an explicit effort makes the Host drop the inherited\n * effort, so a caller can never be handed two of the three.\n *\n * @param outcome - what the judge call produced.\n * @returns the rewrite, or `none` when the child must inherit unchanged.\n */\nexport function decideRewrite(outcome: JudgeOutcome): DispatchDecision {\n if (outcome.kind !== 'matched') return { kind: 'none' };\n const row: TypeRow = outcome.row;\n // A row the judge could select but that is switched off or missing a piece is\n // not a rewrite this plugin may make; leaving the child alone is always safe.\n if (!isOfferedRow(row)) return { kind: 'none' };\n return {\n kind: 'rewrite',\n rewrite: {\n provider: row.provider.trim(),\n model: row.model.trim(),\n reasoningEffort: row.effort.trim(),\n },\n };\n}\n\n/**\n * Why a delegation ended up inheriting, as the log reports it.\n *\n * The judge answering nothing, the judge answering a number this list does not\n * have, an unreachable endpoint and an expired budget are four different fixes\n * for the reader \u2014 \"it answered nothing\" points at the endpoint, \"no listed\n * type\" points at the descriptions. A selected row that turned out to be switched\n * off or missing a field is a fifth: the judgement worked, the row it named was\n * not usable.\n *\n * A judgement that produced a rewrite has no reason at all.\n *\n * @param outcome - what the judge call produced.\n * @param decision - what was written for it.\n * @returns the reason to record, or undefined when the rewrite landed.\n */\nexport function outcomeReason(\n outcome: JudgeOutcome,\n decision: DispatchDecision,\n): FallbackReason | undefined {\n if (decision.kind === 'rewrite') return undefined;\n if (outcome.kind !== 'matched') return outcome.reason;\n return 'incomplete';\n}\n\n", "/** Durable session facts used to identify a child and its initial task. */\nexport interface SessionLike {\n readonly header: SessionHeaderLike;\n readonly inheritedEventCount?: number;\n ownEvents?(): readonly SessionEventLike[];\n snapshotEvents(from?: number): readonly SessionEventLike[];\n}\n\nexport interface SessionHeaderLike {\n readonly id: string;\n readonly parentSession?: string;\n readonly delegationDepth?: number;\n readonly origin?: 'subagent';\n}\n\nexport interface SessionEventLike {\n readonly type: string;\n readonly data?: unknown;\n}\n\nexport interface AgentLike {\n readonly id: string;\n readonly options: { readonly subagentDepth?: number };\n readonly session: SessionLike;\n}\n\nfunction ownEventsOf(session: SessionLike): readonly SessionEventLike[] {\n return session.ownEvents?.() ?? session.snapshotEvents(session.inheritedEventCount ?? 0);\n}\n\nexport function isSubagent(agent: AgentLike): boolean {\n const fromHeader = agent.session.header.delegationDepth;\n const fromOptions = agent.options.subagentDepth;\n return Math.max(\n typeof fromHeader === 'number' && Number.isSafeInteger(fromHeader) ? fromHeader : 0,\n typeof fromOptions === 'number' && Number.isSafeInteger(fromOptions) ? fromOptions : 0,\n ) >= 1;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined;\n}\n\nfunction readText(block: unknown): string | undefined {\n const data = asRecord(block);\n return data?.type === 'text' && typeof data.text === 'string' ? data.text : undefined;\n}\n\nconst RETURN_GUIDANCE = 'Your final answer is delivered automatically if your parent is still online.';\n\n/** Read the first accepted parent relay, excluding the sender line and result-delivery guidance. */\nfunction readInitialTask(events: readonly SessionEventLike[], parentId: string): string | undefined {\n for (const event of events) {\n const inserted = asRecord(event.data)?.inserted;\n const messages = event.type === 'user/message' ? [event.data]\n : event.type === 'agent/inbox/spliced' && Array.isArray(inserted) ? inserted : [];\n for (const value of messages) {\n const message = asRecord(value);\n const source = asRecord(message?.source);\n if (source?.kind !== 'agent-message' || source.form !== 'relay' || source.senderSessionId !== parentId) continue;\n if (!Array.isArray(message?.content)) return undefined;\n const [sender, ...body] = message.content;\n if (!/^Agent .+ sent a message: $/.test(readText(sender) ?? '')) return undefined;\n const texts = body.map(readText).filter((text): text is string => text !== undefined);\n if (texts.length > 1 && texts.at(-1)?.startsWith(RETURN_GUIDANCE)) texts.pop();\n return texts.join('\\n').trim() || undefined;\n }\n }\n return undefined;\n}\n\nconst DELEGATION_TOOLS: ReadonlySet<unknown> = new Set(['subagent', 'subagent_fork']);\n\ninterface DelegatedTask {\n label: string;\n text: string;\n explicitRoute: boolean;\n}\n\nfunction matchingCall(data: Record<string, unknown>, label: string): DelegatedTask | undefined {\n if (!DELEGATION_TOOLS.has(data.name)) return undefined;\n let args = data.arguments;\n if (typeof args === 'string') {\n try { args = JSON.parse(args); } catch { return undefined; }\n }\n const call = asRecord(args);\n if (typeof call?.description !== 'string' || call.description.trim() !== label ||\n typeof call.prompt !== 'string' || call.prompt.trim() === '') return undefined;\n return {\n label,\n text: call.prompt.trim(),\n explicitRoute: call.provider !== undefined || call.model !== undefined || call.reasoning_effort !== undefined,\n };\n}\n\n/** Find unfinished calls in the step that created the child. */\nfunction outstandingDelegation(\n events: readonly SessionEventLike[],\n label: string,\n resumedChildId?: string,\n): DelegatedTask | undefined {\n const end = resumedChildId === undefined ? events.length : events.findIndex((event) =>\n event.type === 'subagent/catalog' && asRecord(event.data)?.childId === resumedChildId,\n );\n const finished = new Set<string>();\n let task: DelegatedTask | undefined;\n for (let index = end - 1; index >= 0; index -= 1) {\n const { type, data: value } = events[index];\n if (type === 'step/start' || type === 'step/end' || type === 'turn/start' || type === 'turn/end') break;\n const data = asRecord(value);\n if (data === undefined) continue;\n switch (type) {\n case 'tool/result': {\n const id = asRecord(data.message)?.toolCallId;\n if (typeof id === 'string') finished.add(`native:${id}`);\n break;\n }\n case 'tool/ptc-dispatch':\n if (typeof data.subCallId === 'string') finished.add(`ptc:${data.subCallId}`);\n break;\n case 'tool/call': case 'tool/ptc-dispatch-start': {\n const ptc = type === 'tool/ptc-dispatch-start';\n const id = ptc ? data.subCallId : data.callId;\n if (typeof id !== 'string' || finished.has(`${ptc ? 'ptc' : 'native'}:${id}`)) break;\n const candidate = matchingCall(data, label);\n if (candidate === undefined) break;\n if (task !== undefined) return undefined;\n task = candidate;\n break;\n }\n }\n }\n return task;\n}\n\n/** Keep a route already selected or used by this child. */\nexport function hasRecordedRoute(session: SessionLike, resumed: boolean, events = ownEventsOf(session)): boolean {\n // The Host writes the initial route immediately after the first descriptor,\n // before agent/created. A fresh delegation's tool arguments tell us whether\n // that initial choice was explicit. Any other selection still takes priority.\n const descriptor = events.findIndex((event) => event.type === 'subagent/descriptor');\n const initialSelection = !resumed && descriptor !== -1 ? descriptor + 1 : -1;\n return events.some((event, index) => event.type === 'request/header' ||\n (event.type === 'model/selection' && index !== initialSelection));\n}\n\n/** Read a uniquely identified task and the route choice made by its caller. */\nexport function readDelegatedTask(\n agent: AgentLike,\n parentSessionOf: (id: string) => SessionLike | undefined,\n resumed: boolean,\n): DelegatedTask | undefined {\n const parentId = agent.session.header.parentSession;\n if (!parentId) return undefined;\n const parent = parentSessionOf(parentId);\n if (parent?.header.id !== parentId) return undefined;\n const own = ownEventsOf(agent.session);\n if (hasRecordedRoute(agent.session, resumed, own)) return undefined;\n const descriptor = [...own].reverse().find((event) => event.type === 'subagent/descriptor');\n const label = asRecord(descriptor?.data)?.label;\n if (typeof label !== 'string' || label.trim() === '') return undefined;\n const task = outstandingDelegation(ownEventsOf(parent), label.trim(), resumed ? agent.id : undefined);\n if (task === undefined) return undefined;\n if (resumed && readInitialTask(own, parentId) !== task.text) return undefined;\n return task;\n}\n\n/**\n * Walk up a child's lineage to the top-level conversation that started it.\n *\n * A nested subagent's direct parent is another subagent, and the log's job is to\n * name the conversation the reader recognises \u2014 so the walk continues until a\n * session is a top-level conversation. A normal session fork is itself a\n * conversation, even when its header names a parent. The walk is bounded to\n * tolerate a damaged lineage.\n *\n * @param startId - the child's direct parent session id.\n * @param lookup - reads the header of a live or persisted session.\n * @returns the top-level session id, or the last id reached when the walk stops.\n */\nexport async function resolveRootSessionId(\n startId: string,\n lookup: (id: string) => SessionHeaderLike | undefined | Promise<SessionHeaderLike | undefined>,\n): Promise<string> {\n const seen = new Set<string>([startId]);\n let current = startId;\n for (let hop = 0; hop < 32; hop += 1) {\n const header = await lookup(current);\n if (header === undefined || (header.origin !== 'subagent' && (header.delegationDepth ?? 0) < 1)) return current;\n const parent = header.parentSession;\n if (typeof parent !== 'string' || parent === '' || seen.has(parent)) return current;\n seen.add(parent);\n current = parent;\n }\n return current;\n}\n", "/** The total time available for the judge request and route preflight. */\nconst JUDGE_TIMEOUT_MS = 5000;\n\nexport class JudgeBudget {\n private readonly startedAt = performance.now();\n private readonly controller = new AbortController();\n private readonly timer = setTimeout(() => this.controller.abort(), JUDGE_TIMEOUT_MS);\n readonly signal: AbortSignal;\n\n constructor(parent?: AbortSignal) {\n this.signal = parent === undefined\n ? this.controller.signal\n : AbortSignal.any([parent, this.controller.signal]);\n }\n\n elapsed(): number {\n return Math.round(performance.now() - this.startedAt);\n }\n\n expired(): boolean {\n if (performance.now() - this.startedAt >= JUDGE_TIMEOUT_MS) this.controller.abort();\n return this.controller.signal.aborted;\n }\n\n check(): void {\n this.expired();\n this.signal.throwIfAborted();\n }\n\n /** Stop waiting at the deadline even if the operation ignores its signal. */\n async run<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {\n this.check();\n let onAbort!: () => void;\n const aborted = new Promise<never>((_, reject) => {\n onAbort = () => reject(this.signal.reason);\n this.signal.addEventListener('abort', onAbort, { once: true });\n });\n try {\n const result = await Promise.race([aborted, Promise.resolve().then(() => {\n this.check();\n return operation(this.signal);\n })]);\n this.check();\n return result;\n } finally {\n this.signal.removeEventListener('abort', onAbort);\n }\n }\n\n dispose(): void {\n clearTimeout(this.timer);\n }\n}\n", "import { JudgeBudget } from './judge-budget.ts';\nimport { PROBE_OPTION_ID, buildJudgeRequest, buildProbeRequest, readJudgeAnswer } from './judge-prompt.ts';\nimport type { JudgeMetrics, JudgeOutcome, ProbeOutcome, TypeRow } from './types.ts';\n\nexport interface JudgeEndpoint {\n url: string;\n model: string;\n apiKey: string;\n}\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\nasync function requestJudge(\n budget: JudgeBudget, endpoint: JudgeEndpoint, body: unknown, fetchImpl: FetchLike,\n): Promise<unknown> {\n return budget.run(async (signal) => {\n const response = await fetchImpl(endpoint.url.trim(), {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...endpoint.apiKey.trim() === '' ? {} : { authorization: `Bearer ${endpoint.apiKey.trim()}` },\n },\n body: JSON.stringify(body),\n signal,\n });\n signal.throwIfAborted();\n if (!response.ok) throw new Error('Judge endpoint failed');\n return response.json();\n });\n}\n\n/** Test the endpoint with one fixed option, independent of the configured task types. */\nexport async function probeJudge(\n endpoint: JudgeEndpoint, fetchImpl: FetchLike = fetch,\n): Promise<ProbeOutcome> {\n if (endpoint.url.trim() === '' || endpoint.model.trim() === '') {\n return { ok: false, latencyMs: 0, reason: 'unconfigured' };\n }\n const budget = new JudgeBudget();\n try {\n const payload = await requestJudge(budget, endpoint, buildProbeRequest(endpoint.model.trim()), fetchImpl);\n const options = [{\n id: Number(PROBE_OPTION_ID), enabled: true, description: '', provider: '', model: '', effort: '',\n }];\n return readJudgeAnswer(payload, options).kind === 'row'\n ? { ok: true, latencyMs: budget.elapsed() }\n : { ok: false, latencyMs: budget.elapsed(), reason: 'unmatched' };\n } catch {\n return { ok: false, latencyMs: budget.elapsed(), reason: budget.expired() ? 'timeout' : 'unreachable' };\n } finally {\n budget.dispose();\n }\n}\n\n/** Classify one task using the caller\u2019s deadline when it also needs to preflight a route. */\nexport async function judgeTaskType(\n endpoint: JudgeEndpoint, rows: readonly TypeRow[], subject: string,\n fetchImpl: FetchLike = fetch, sharedBudget?: JudgeBudget,\n): Promise<JudgeOutcome> {\n const budget = sharedBudget ?? new JudgeBudget();\n const model = endpoint.model.trim();\n let metrics: JudgeMetrics | undefined;\n try {\n if (endpoint.url.trim() === '' || model === '' || rows.length === 0) {\n return { kind: 'fallback', reason: 'unreachable', latencyMs: budget.elapsed() };\n }\n budget.check();\n metrics = { judgeModel: model, optionCount: rows.length, subjectLength: subject.length };\n const payload = await requestJudge(budget, endpoint, buildJudgeRequest(rows, model, subject), fetchImpl);\n const decision = readJudgeAnswer(payload, rows);\n return decision.kind === 'row'\n ? { kind: 'matched', row: decision.row, latencyMs: budget.elapsed(), metrics }\n : { kind: 'fallback', reason: 'unmatched', latencyMs: budget.elapsed(), metrics };\n } catch {\n const reason = budget.expired() ? 'timeout' : 'unreachable';\n return { kind: 'fallback', reason, latencyMs: budget.elapsed(), metrics };\n } finally {\n if (sharedBudget === undefined) budget.dispose();\n }\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write';\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths';\nimport type { FallbackReason, JudgeMetrics, LogEntry } from './types.ts';\n\nexport const LOG_KEEP = 200;\nexport const LOG_PAGE_LIMIT = 10;\n\nconst REASONS: readonly FallbackReason[] = [\n 'unreachable', 'timeout', 'unmatched', 'incomplete', 'unavailable-route',\n];\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined;\n}\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction count(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;\n}\n\nfunction readMetrics(value: unknown): JudgeMetrics | undefined {\n const item = record(value);\n if (item === undefined) return undefined;\n return {\n judgeModel: text(item.judgeModel),\n optionCount: count(item.optionCount),\n subjectLength: count(item.subjectLength),\n };\n}\n\n/** Keep only the fields displayed or used by the log. */\nfunction readEntry(value: unknown): LogEntry | undefined {\n const item = record(value);\n if (item === undefined) return undefined;\n const reason = REASONS.find((candidate) => candidate === item.reason);\n const metrics = readMetrics(item.metrics);\n return {\n typeId: count(item.typeId) || null,\n ...typeof item.typeDescription === 'string' ? { typeDescription: item.typeDescription } : {},\n ...typeof item.taskText === 'string' ? { taskText: item.taskText } : {},\n ...typeof item.typeKey === 'string' && /^[0-9a-f-]{36}$/i.test(item.typeKey) ? { typeKey: item.typeKey } : {},\n provider: text(item.provider),\n model: text(item.model),\n effort: text(item.effort),\n ...reason === undefined ? {} : { reason },\n at: count(item.at),\n latencyMs: count(item.latencyMs),\n ...metrics === undefined ? {} : { metrics },\n };\n}\n\nfunction newest(entries: LogEntry[]): LogEntry[] {\n return entries.sort((left, right) => right.at - left.at).slice(0, LOG_KEEP);\n}\n\n/** A bounded, newest-first log shared by the Host processes in one DSH home. */\nexport class LogStore {\n private entries: LogEntry[] = [];\n private pending: LogEntry[] = [];\n private loading?: Promise<void>;\n private writing: Promise<void> = Promise.resolve();\n\n private readonly filePath: string;\n\n constructor(filePath = dshHomePath('dsh-subagent-judge-dispatch', 'judgements.json')) {\n this.filePath = filePath;\n }\n\n init(): Promise<void> {\n this.loading ??= this.readDisk().then((entries) => {\n this.entries = entries;\n }).catch(() => {});\n return this.loading;\n }\n\n append(entry: LogEntry): void {\n const sanitized = readEntry(entry);\n if (sanitized === undefined) return;\n this.pending.unshift(sanitized);\n this.writing = this.writing.then(() => this.write()).catch(() => {\n this.pending = newest(this.pending);\n console.warn('[dsh-subagent-judge-dispatch] \u5224\u65AD\u65E5\u5FD7\u5199\u4E0D\u8FDB\u78C1\u76D8');\n });\n }\n\n list(): LogEntry[] {\n return this.snapshot(this.entries);\n }\n\n async readLatest(): Promise<LogEntry[]> {\n const previous = this.entries;\n const disk = await this.readDisk();\n // A local commit can complete while the file read observes its old inode.\n return this.snapshot(this.entries === previous ? disk : this.entries);\n }\n\n private snapshot(entries: LogEntry[]): LogEntry[] {\n return newest([...this.pending, ...entries]).map((entry) => structuredClone(entry));\n }\n\n async flush(): Promise<void> {\n await this.loading;\n await this.writing;\n }\n\n private async readDisk(): Promise<LogEntry[]> {\n try {\n const parsed: unknown = JSON.parse(await fs.readFile(this.filePath, 'utf8'));\n if (!Array.isArray(parsed)) throw new Error('Invalid log format');\n return newest(parsed.map(readEntry).filter((entry): entry is LogEntry => entry !== undefined));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n }\n\n private async write(): Promise<void> {\n if (this.pending.length === 0) return;\n await this.loading;\n await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 0o700 });\n await withFileLock(this.filePath, async () => {\n const stored = await this.readDisk();\n const count = this.pending.length;\n const merged = newest([...this.pending, ...stored]);\n await writeFileAtomic(this.filePath, JSON.stringify(merged, null, 2), { mode: 0o600 });\n this.pending.length -= count;\n this.entries = merged;\n });\n }\n}\n", "import { createHash, randomBytes } from \"node:crypto\";\nimport { lstat, mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as setTimeout$1 } from \"node:timers/promises\";\nimport { HarnessError } from \"@deepseek-ai/dsh-error\";\n//#region lib/types/index.js\n/**\n* Atomic file replacement and writer coordination.\n* `writeFileAtomic` writes a random-suffix sibling with exclusive create and\n* the caller's permission bits, then renames it over the target, so readers\n* observe either the old or the new complete content and a replaced file ends\n* up with exactly the stated mode. `withFileLock` serializes cross-process\n* writers of one file through a `wx`-created `<file>.lock` sibling, so a\n* read-modify-write cycle can never resurrect a state another writer just\n* replaced; readers stay lock-free because the rename commit is atomic. A lock\n* whose recorded holder process no longer exists is taken over.\n* @module @deepseek-ai/dsh-atomic-write\n*/\nconst WINDOWS_TRANSIENT_RENAME_ERRORS = new Set([\n\t\"EACCES\",\n\t\"EBUSY\",\n\t\"EPERM\"\n]);\nconst WINDOWS_RENAME_RETRY_INITIAL_MS = 20;\nconst WINDOWS_RENAME_RETRY_MAX_MS = 200;\nconst WINDOWS_RENAME_RETRY_LIMIT = 8;\n/** Whether Windows reported temporary interference with an atomic replacement. */\nfunction isTransientWindowsRenameError(error) {\n\tif (process.platform !== \"win32\") return false;\n\treturn WINDOWS_TRANSIENT_RENAME_ERRORS.has(error?.code ?? \"\");\n}\n/** Replace the target after bounded retries for transient Windows interference. */\nasync function renameAtomicTemp(temp, filename) {\n\tlet delay = WINDOWS_RENAME_RETRY_INITIAL_MS;\n\tfor (let retries = 0;; retries += 1) {\n\t\ttry {\n\t\t\tawait rename(temp, filename);\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tif (!isTransientWindowsRenameError(error)) throw error;\n\t\t\tif (retries >= WINDOWS_RENAME_RETRY_LIMIT) throw error;\n\t\t}\n\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\tdelay = Math.min(delay * 2, WINDOWS_RENAME_RETRY_MAX_MS);\n\t}\n}\n/**\n* Replace `filename` with `content` in one atomic step, creating parent\n* directories. The content is first written to a random-suffix sibling opened\n* with exclusive create (`wx`): the open refuses to follow a symlink planted\n* at the temp path, and the fresh inode carries `options.mode` through the\n* rename, so replacing a wider-permission file narrows it without a chmod\n* race. The rename also replaces a symlinked target itself instead of writing\n* through to its referent, and the same-directory sibling keeps the rename on\n* one filesystem. Windows replacement retries transient `EACCES`, `EBUSY`,\n* and `EPERM` failures for a bounded interval while the complete temp file\n* remains the rename source. On any remaining failure the temp file is\n* removed and the failure rethrown. Crash durability (fsync) is out of scope.\n* @param filename - final path receiving the content.\n* @param content - complete next file content.\n* @param options - permission bits for the replacement inode.\n*/\nasync function writeFileAtomic(filename, content, options) {\n\tawait mkdir(dirname(filename), {\n\t\trecursive: true,\n\t\t...options.dirMode === void 0 ? {} : { mode: options.dirMode }\n\t});\n\tconst temp = `${filename}.${randomBytes(6).toString(\"hex\")}.tmp`;\n\ttry {\n\t\tawait writeFile(temp, content, {\n\t\t\tmode: options.mode,\n\t\t\tflag: \"wx\"\n\t\t});\n\t\tawait renameAtomicTemp(temp, filename);\n\t} catch (error) {\n\t\tawait rm(temp, { force: true });\n\t\tthrow error;\n\t}\n}\n/** Whether an exclusive create found an existing lock. */\nasync function isLockContention(error, lockPath) {\n\tconst code = error?.code;\n\tif (code === \"EEXIST\") return true;\n\tif (code !== \"EPERM\") return false;\n\ttry {\n\t\tawait lstat(lockPath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether the holder a `<pid>\\n` record names is proven gone: a signal probe finds no such process. */\nfunction holderExited(record) {\n\tif (!/^\\d+\\n$/.test(record)) return false;\n\tconst pid = Number(record.trim());\n\tif (pid === 0 || pid > 2147483647) return false;\n\tif (pid === process.pid) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn false;\n\t} catch (error) {\n\t\treturn error.code === \"ESRCH\";\n\t}\n}\n/** The lock file's content, or undefined when it cannot be read. */\nasync function readLockRecord(lockPath) {\n\ttry {\n\t\treturn await readFile(lockPath, \"utf8\");\n\t} catch (error) {\n\t\treturn;\n\t}\n}\n/**\n* Remove the lock when its recorded holder exited. Contenders that read the\n* same record serialize on a claim file named after it. Under the claim, the\n* claimant re-reads the lock and probes its PID again, and removes it only\n* when it still holds that record and that PID is still gone: the record's\n* holder can no longer release it, and no other contender can remove it\n* without the claim, so a removal never deletes a lock another contender\n* acquired after the dead holder's, including one whose holder reused the PID.\n* @returns Whether this call removed the dead holder's lock.\n*/\nasync function takeOverExitedLock(lockPath) {\n\tconst record = await readLockRecord(lockPath);\n\tif (record === void 0 || !holderExited(record)) return false;\n\tconst claim = `${lockPath}.takeover-${createHash(\"sha256\").update(record).digest(\"hex\").slice(0, 16)}`;\n\ttry {\n\t\tawait writeFile(claim, `${process.pid}\\n`, {\n\t\t\tmode: 384,\n\t\t\tflag: \"wx\"\n\t\t});\n\t} catch (error) {\n\t\tconst code = error.code;\n\t\tif (code === \"EEXIST\" || code === \"EPERM\") return false;\n\t\tthrow error;\n\t}\n\ttry {\n\t\tif (await readLockRecord(lockPath) !== record || !holderExited(record)) return false;\n\t\ttry {\n\t\t\tawait rm(lockPath, { force: true });\n\t\t} catch (error) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t} finally {\n\t\tawait rm(claim, { force: true }).catch((error) => {});\n\t}\n}\n/**\n* Retry cadence for a contended lock. These stay robustness invariants of the\n* cross-process write protocol rather than deployment tunables: they govern how\n* often a contender asks, which no caller has a reason to vary.\n*/\nconst LOCK_RETRY_INITIAL_MS = 20;\nconst LOCK_RETRY_MAX_MS = 200;\n/**\n* How long a contender waits when the caller states no limit \u2014 sized for the\n* render-and-rename cycle every call site had when this package was written.\n* Expiry fails the contender rather than guessing whether the existing lock\n* still has an owner. How long is *worth* waiting is a property of the\n* operation the lock holder runs, which is why {@link FileLockOptions.waitMs}\n* exists; the value here is the floor for an operation that does file work\n* alone.\n*/\nconst DEFAULT_LOCK_WAIT_MS = 2e3;\n/**\n* A {@link withFileLock} acquisition failure. `FILE_LOCK_TIMEOUT`: another\n* writer still held the lock at the wait deadline and the operation did not\n* start, so the caller may retry after that writer finishes.\n*/\nvar FileLockError = class extends HarnessError {\n\tcode;\n\t/** The contended `<filename>.lock` path. */\n\tlockPath;\n\tconstructor(lockPath) {\n\t\tsuper(`atomic-write: timed out waiting for the writer lock at ${lockPath}`, \"FILE_LOCK_TIMEOUT\");\n\t\tthis.name = \"FileLockError\";\n\t\tthis.code = \"FILE_LOCK_TIMEOUT\";\n\t\tthis.lockPath = lockPath;\n\t}\n};\n/**\n* Hold the cross-process writer lock for `filename` around one operation. The\n* lock is a `wx`-created sibling (`<filename>.lock`); paired with the\n* rename-based commit of {@link writeFileAtomic}, readers stay lock-free and\n* only writers contend. `EEXIST` is contention directly; an `EPERM` is\n* contention only when a fresh `lstat` confirms the lock path exists, covering\n* Windows exclusive-create behavior. Windows retries one unconfirmed EPERM\n* because the holder can release before the probe; a repeated unconfirmed\n* permission error is rethrown. The lock records its holder's PID. A contender\n* removes the lock and retries at once when no process with that PID exists\n* (`ESRCH`); any other lock, including one whose holder exists under another\n* user (`EPERM`) or whose record is incomplete, is waited for. Contention backs\n* off exponentially and times out after the deadline. A holder whose PID a\n* live process reused keeps its lock until an operator removes it. Takeover\n* proves only that the recorded process exited: an operation that starts other\n* writers must stop them with it or leave its successor a way to find them.\n* PIDs are compared on the contender's host, so writers on other hosts or in\n* other PID namespaces sharing the file are unsupported and could both hold\n* the lock. The parent directory must exist.\n* @param filename - the file whose writers this lock serializes.\n* @param operation - the read-render-commit cycle to run while holding the lock.\n* @param options - acquisition options; omitted waits {@link DEFAULT_LOCK_WAIT_MS}.\n* @returns the operation's result; the lock releases on both outcomes.\n* @throws {FileLockError} `FILE_LOCK_TIMEOUT` when the lock is still held at the deadline.\n*/\nasync function withFileLock(filename, operation, options) {\n\tconst lockPath = `${filename}.lock`;\n\tconst deadline = Date.now() + (options?.waitMs ?? DEFAULT_LOCK_WAIT_MS);\n\tlet delay = LOCK_RETRY_INITIAL_MS;\n\tlet retriedUnconfirmedPermissionError = false;\n\tfor (;;) {\n\t\toptions?.signal?.throwIfAborted();\n\t\ttry {\n\t\t\tawait writeFile(lockPath, `${process.pid}\\n`, {\n\t\t\t\tmode: 384,\n\t\t\t\tflag: \"wx\"\n\t\t\t});\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tif (!await isLockContention(error, lockPath)) {\n\t\t\t\tif (process.platform !== \"win32\" || error?.code !== \"EPERM\" || retriedUnconfirmedPermissionError) throw error;\n\t\t\t\tretriedUnconfirmedPermissionError = true;\n\t\t\t} else if (await takeOverExitedLock(lockPath)) continue;\n\t\t}\n\t\tif (Date.now() >= deadline) throw new FileLockError(lockPath);\n\t\tawait setTimeout$1(delay, void 0, { signal: options?.signal });\n\t\tdelay = Math.min(delay * 2, LOCK_RETRY_MAX_MS);\n\t}\n\ttry {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn await operation();\n\t} finally {\n\t\tawait rm(lockPath, { force: true });\n\t}\n}\n//#endregion\nexport { FileLockError, withFileLock, writeFileAtomic };\n", "//#region lib/types/index.js\n/**\n* Harness error base with a stable machine-routable code and chained cause.\n* Package errors extend it so tool results and replay can retain failure class.\n* @module @deepseek-ai/dsh-error\n*/\n/**\n* Base class for all harness errors. Carries a `code` (stable, programmatic \u2014\n* e.g. `NO_ADAPTER`, `INVALID_ARGS`) distinct from the\n* human-readable `message`, and supports `cause` chaining via the standard\n* `ErrorOptions`. `name` defaults to the subclass constructor name.\n*/\nvar HarnessError = class extends Error {\n\t/** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */\n\tcode;\n\tconstructor(message, code, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = new.target.name;\n\t}\n};\n//#endregion\nexport { HarnessError };\n", "import { opendir, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, resolve } from \"node:path\";\n//#region lib/types/index.js\n/**\n* Shared filesystem path helpers for DeepSeek Harness user data.\n*\n* @module @deepseek-ai/dsh-home-paths\n*/\n/** Directory name for the default DeepSeek Harness home under the OS home. */\nconst DSH_HOME_DIR_NAME = \".dsh\";\n/** Stable user-facing display form for the default DeepSeek Harness home. */\nconst DEFAULT_DSH_HOME_DISPLAY = `~/${DSH_HOME_DIR_NAME}`;\n/** Environment variable that overrides the default DeepSeek Harness home. */\nconst DSH_HOME_ENV = \"DSH_HOME\";\n/** Directory name for the default shared agent configuration root under the OS home. */\nconst AGENTS_HOME_DIR_NAME = \".agents\";\n/** Stable user-facing display form for the default shared agent configuration root. */\nconst DEFAULT_AGENTS_HOME_DISPLAY = `~/${AGENTS_HOME_DIR_NAME}`;\n/** Environment variable that overrides the default shared agent configuration root. */\nconst AGENTS_HOME_ENV = \"DSH_AGENTS_HOME\";\n/**\n* Give a native filesystem watcher one canonical spelling of a path, even\n* when its final components do not exist yet. The deepest existing ancestor\n* is resolved through {@link realpath}; when a suffix is missing, that\n* ancestor is also proved to be an enumerable directory before the suffix is\n* restored. This prevents Windows from treating a regular-file ancestor as\n* ordinary absence, and prevents short-name aliases from being mixed with\n* long paths emitted by the native watcher backend.\n* @param path - Watch target or root, resolved against the current directory.\n* @returns the target with its existing ancestor canonicalized.\n* @throws when ancestor traversal encounters an error other than absence, or\n* the existing ancestor of a missing suffix is not an enumerable directory.\n*/\nasync function canonicalizeWatchPath(path) {\n\tlet current = resolve(path);\n\tconst missing = [];\n\twhile (true) try {\n\t\tconst canonical = await realpath(current);\n\t\tif (missing.length > 0) await (await opendir(canonical)).close();\n\t\treturn join(canonical, ...missing.reverse());\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t\tconst parent = dirname(current);\n\t\t/* v8 ignore next -- a filesystem root exists, so traversal resolves before this guard */\n\t\tif (parent === current) throw error;\n\t\tmissing.push(basename(current));\n\t\tcurrent = parent;\n\t}\n}\n/**\n* Resolve the default DeepSeek Harness home using Node's platform path rules.\n* @returns the absolute default harness home path.\n*/\nfunction defaultDshHome() {\n\treturn join(homedir(), DSH_HOME_DIR_NAME);\n}\n/**\n* Resolve the default shared agent configuration root using Node's platform path rules.\n* @returns the absolute default shared agent configuration root.\n*/\nfunction defaultAgentsHome() {\n\treturn join(homedir(), AGENTS_HOME_DIR_NAME);\n}\n/**\n* Expand supported tilde prefixes against the operating-system home.\n* @param path - configured path that may begin with `~`, `~/`, or `~\\`.\n* @returns the expanded path, or the original value when no supported prefix is present.\n*/\nfunction expandHomePath(path) {\n\tif (path === \"~\") return homedir();\n\tif (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) return join(homedir(), path.slice(2));\n\treturn path;\n}\n/**\n* Resolve one user-data root from an explicit path, an environment override, and a default.\n* @param configured - explicit path, which has highest precedence.\n* @param env - environment mapping to read.\n* @param envName - environment variable that overrides the default.\n* @param fallback - default root, used when neither the explicit path nor the environment provides one.\n* @returns the normalized absolute root.\n*/\nfunction resolveRoot(configured, env, envName, fallback) {\n\tconst fromEnv = env[envName];\n\treturn resolve(expandHomePath(configured ?? (fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : fallback())));\n}\n/**\n* Label one resolved user-data root symbolically for user-facing display.\n* @param resolvedRoot - absolute path returned by the matching resolver.\n* @param defaultRoot - absolute default root whose symbolic label applies to a match.\n* @param defaultLabel - symbolic label for the default root.\n* @param envName - environment variable name that labels any other root.\n* @returns the symbolic label.\n*/\nfunction rootDisplay(resolvedRoot, defaultRoot, defaultLabel, envName) {\n\treturn resolvedRoot === resolve(defaultRoot) ? defaultLabel : `$${envName}`;\n}\n/**\n* Resolve the single-root DeepSeek Harness home.\n*\n* Precedence, highest first: an explicit configured path, `$DSH_HOME`, then\n* `~/.dsh`. The harness keeps all user data under one root. An empty or\n* whitespace-only `$DSH_HOME` is treated as unset, so a blank override never\n* resolves the home to the current working directory.\n* @param configured - explicit harness-home override, which has highest precedence.\n* @param env - environment mapping used to read `DSH_HOME`.\n* @returns the normalized absolute harness home path.\n*/\nfunction resolveDshHome(configured, env = process.env) {\n\treturn resolveRoot(configured, env, DSH_HOME_ENV, defaultDshHome);\n}\n/**\n* Resolve the shared agent configuration root.\n*\n* Precedence, highest first: an explicit configured path, `$DSH_AGENTS_HOME`,\n* then `~/.agents`. The root holds configuration shared with other agent tools,\n* so it stays independent of the DeepSeek Harness home. An empty or\n* whitespace-only `$DSH_AGENTS_HOME` is treated as unset, so a blank override\n* never resolves the root to the current working directory.\n* @param configured - explicit shared-root override, which has highest precedence.\n* @param env - environment mapping used to read `DSH_AGENTS_HOME`.\n* @returns the normalized absolute shared agent configuration root.\n*/\nfunction resolveAgentsHome(configured, env = process.env) {\n\treturn resolveRoot(configured, env, AGENTS_HOME_ENV, defaultAgentsHome);\n}\n/**\n* Join path segments onto the resolved DeepSeek Harness home. It addresses the\n* existing top-level entries; a new path uses {@link dshPath} with its category.\n* @param segments - path segments appended to the Harness home; an empty list returns the home itself.\n* @returns the normalized absolute joined path.\n*/\nfunction dshHomePath(...segments) {\n\treturn join(resolveDshHome(), ...segments);\n}\n/**\n* Join path segments onto the resolved Harness home's `cache` directory without creating it; no arguments returns the directory itself.\n* @param optionsOrSegment - explicit home override, or the first path segment; omission uses the default home resolution.\n* @param segments - additional path segments after the first child, if any.\n* @returns the normalized absolute cache path.\n*/\nfunction dshCachePath(optionsOrSegment = {}, ...segments) {\n\tif (typeof optionsOrSegment === \"string\") return dshPath(\"cache\", optionsOrSegment, ...segments);\n\treturn dshPath({\n\t\tcategory: \"cache\",\n\t\tdshHome: optionsOrSegment.dshHome\n\t}, ...segments);\n}\n/**\n* Join path segments onto one category directory of the Harness home without\n* creating it. An owner passes its own directory name, normally its package\n* name without the `@deepseek-ai/dsh-` prefix, as the first segment.\n* @param location - category under the resolved home, or a category with an explicit home override.\n* @param segments - path segments appended to the category directory; an empty list returns the directory itself.\n* @returns the normalized absolute path.\n*/\nfunction dshPath(location, ...segments) {\n\tconst { category, dshHome } = typeof location === \"string\" ? {\n\t\tcategory: location,\n\t\tdshHome: void 0\n\t} : location;\n\treturn join(resolveDshHome(dshHome), category, ...segments);\n}\n/**\n* Describe a resolved harness home symbolically for user-facing display.\n*\n* It never returns an absolute machine path: the default home is labelled\n* `~/.dsh`, and any configured home is labelled `$DSH_HOME`.\n* @param resolvedHome - the absolute path returned by {@link resolveDshHome}.\n* @returns `~/.dsh` for the default home, otherwise `$DSH_HOME`.\n*/\nfunction dshHomeDisplay(resolvedHome) {\n\treturn rootDisplay(resolvedHome, defaultDshHome(), DEFAULT_DSH_HOME_DISPLAY, DSH_HOME_ENV);\n}\n/**\n* Describe a resolved shared agent configuration root symbolically for user-facing display.\n*\n* It never returns an absolute machine path: the default root is labelled\n* `~/.agents`, and any configured root is labelled `$DSH_AGENTS_HOME`.\n* @param resolvedHome - the absolute path returned by {@link resolveAgentsHome}.\n* @returns `~/.agents` for the default root, otherwise `$DSH_AGENTS_HOME`.\n*/\nfunction agentsHomeDisplay(resolvedHome) {\n\treturn rootDisplay(resolvedHome, defaultAgentsHome(), DEFAULT_AGENTS_HOME_DISPLAY, AGENTS_HOME_ENV);\n}\n//#endregion\nexport { AGENTS_HOME_DIR_NAME, AGENTS_HOME_ENV, DEFAULT_AGENTS_HOME_DISPLAY, DEFAULT_DSH_HOME_DISPLAY, DSH_HOME_DIR_NAME, DSH_HOME_ENV, agentsHomeDisplay, canonicalizeWatchPath, defaultAgentsHome, defaultDshHome, dshCachePath, dshHomeDisplay, dshHomePath, dshPath, expandHomePath, resolveAgentsHome, resolveDshHome };\n", "/**\n * This plugin's exact Fetch routes, carried by Connection's authenticated\n * `/api` transport below the shared channel.\n *\n * Configuration and credentials use DSH services. These four exact routes\n * serve the log, prompt preview, connectivity probe and sample judgement.\n * The physical /api carrier requires authentication; Connection's shared Fetch\n * handler checks that the admitted Peer is an owner before invoking any exact\n * route. The exact-route callback receives only Request, not the Peer.\n */\n\nimport type { ConnectionFetchRoute } from '@deepseek-ai/dsh-client-connection';\nimport { buildPreview, selectableRows } from './judge-prompt.ts';\nimport { LOG_PAGE_LIMIT } from './log-store.ts';\nimport { probeJudge } from './judge-client.ts';\nimport type { ResolvedConfig } from './config.ts';\nimport type { LogEntry } from './types.ts';\n\n/** Runtime log route path. */\nexport const LOG_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/log';\n\n/** Exact judge-prompt preview route path. */\nexport const PREVIEW_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/preview';\n\n/** Judge endpoint probe route path. */\nexport const PROBE_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/probe';\nexport const SAMPLE_ROUTE_PATH = '/api/dsh-subagent-judge-dispatch/sample';\n\nfunction sendJson(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json; charset=utf-8' },\n });\n}\n\n/** What one probe reports back to the page. */\nexport interface ProbeResult {\n ok: boolean;\n latencyMs: number;\n /** Which failure it was, when it failed. */\n reason?: string;\n}\n\n/** The Host-side face the routes read. */\nexport interface DispatchRouteFace {\n /** Current committed configuration. */\n config(): ResolvedConfig;\n /** Read the whole kept log, newest first; may resolve once the file has been read. */\n log(): LogEntry[] | Promise<LogEntry[]>;\n /** The judge key resolved from credentials, or '' when unset. */\n apiKey(): string;\n sample(task: string): Promise<unknown>;\n}\n\n/**\n * Build this plugin's Fetch routes.\n * @param face - the Host-side reads the routes serve.\n * @returns the routes to register on Connection.\n */\nexport function createFetchRoutes(face: DispatchRouteFace): ConnectionFetchRoute[] {\n const log: ConnectionFetchRoute = {\n path: LOG_ROUTE_PATH,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n // The page shows only the tail of the log; the file keeps the rest.\n return sendJson(200, { ok: true, entries: (await face.log()).slice(0, LOG_PAGE_LIMIT) });\n } catch (err) {\n return sendJson(500, { ok: false, error: describe(err) });\n }\n },\n };\n\n const preview: ConnectionFetchRoute = {\n path: PREVIEW_ROUTE_PATH,\n methods: ['GET'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n const config = face.config();\n // Built by the same function the real call uses, so what the page shows\n // cannot drift from what goes out.\n const text = buildPreview(selectableRows(config.rows), config.judgeModel.trim());\n return sendJson(200, { ok: true, preview: text });\n } catch (err) {\n return sendJson(500, { ok: false, error: describe(err) });\n }\n },\n };\n\n const probe: ConnectionFetchRoute = {\n path: PROBE_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async () => {\n try {\n const config = face.config();\n // \u53EA\u95EE\u300C\u8FD9\u4E2A\u5730\u5740\u4E0E\u6A21\u578B\u7B54\u4E0D\u7B54\u5F97\u4E0A\u6765\u300D\uFF0C\u6240\u4EE5\u4E0D\u95EE\u7C7B\u578B\u6E05\u5355\uFF1A\u6E05\u5355\u662F\u5224\u65AD\u65F6\u624D\n // \u9700\u8981\u7684\u8F93\u5165\uFF0C\u62FF\u5B83\u5F53\u4F5C\u80FD\u4E0D\u80FD\u6D4B\u7684\u524D\u63D0\uFF0C\u4F1A\u8BA9\u7A7A\u6E05\u5355\u7684\u8BFB\u8005\u4EE5\u4E3A\u670D\u52A1\u574F\u4E86\u3002\n const outcome = await probeJudge({\n url: config.endpointUrl,\n model: config.judgeModel,\n apiKey: face.apiKey(),\n });\n return sendJson(200, { ...outcome } satisfies ProbeResult);\n } catch (err) {\n return sendJson(500, { ok: false, error: describe(err) });\n }\n },\n };\n\n const sample: ConnectionFetchRoute = {\n path: SAMPLE_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request) => {\n try {\n const body: unknown = await request.json();\n const task = typeof body === 'object' && body !== null && 'task' in body ? body.task : undefined;\n if (typeof task !== 'string' || task.trim() === '' || task.length > 10000) return sendJson(400, { ok: false });\n return sendJson(200, await face.sample(task));\n } catch {\n return sendJson(500, { ok: false });\n }\n },\n };\n return [log, preview, probe, sample];\n}\n\n/** One-line error text for a route failure. */\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n", "import type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection';\nimport { SETTINGS_NAMESPACE } from './enablement.ts';\nimport {\n isJudgeUsable,\n readPluginConfig,\n type PluginConfigRefs,\n type ResolvedConfig,\n} from './server/config.ts';\nimport { JUDGE_API_KEY_REF, type CredentialsServiceLike } from './server/credentials.ts';\nimport { decideRewrite, outcomeReason } from './server/dispatch.ts';\nimport {\n hasRecordedRoute,\n isSubagent,\n readDelegatedTask,\n resolveRootSessionId,\n type SessionHeaderLike,\n type SessionLike,\n} from './server/identity.ts';\nimport { JudgeBudget } from './server/judge-budget.ts';\nimport { judgeTaskType } from './server/judge-client.ts';\nimport { composeJudgeSubject, selectableRows } from './server/judge-prompt.ts';\nimport { LogStore } from './server/log-store.ts';\nimport { createFetchRoutes } from './server/router.ts';\nimport type { FallbackReason, LogEntry } from './server/types.ts';\n\n/**\n * Stable Cordis loader name; the same literal as the `id` of this plugin's row\n * in `cordis.patch.yml` and as its settings namespace.\n */\nexport const name = SETTINGS_NAMESPACE;\n\n/**\n * Declared services. `credentials` is the DSH-owned secret surface the judge key\n * is read through. `sessions` finds the task the parent delegated. The Fetch\n * routes ride Connection's authenticated transport, which only a Web carrier composes, so they are taken\n * through `ctx.inject` and the plugin still loads without one.\n */\nexport const inject = ['credentials', 'sessions'];\n\nexport { Config } from './server/config.ts';\nexport { JUDGE_API_KEY_REF } from './server/credentials.ts';\n\n/** Minimal structural shape of this plugin's own `settings` usage. */\ninterface SettingsLike {\n configure(presentation: { auto?: boolean }, owner?: unknown): () => void;\n}\n\n/**\n * The Host context surface this plugin uses.\n *\n * Declared structurally rather than by extending `Context`: the fields read here\n * (`inject` with a narrower dependency list, `on` for one waterfall event) are a\n * subset with a deliberately looser signature, and widening `inject` to satisfy\n * the interface would hide the services this plugin actually declares through\n * the exported `inject` table.\n */\ninterface HostContext {\n credentials: CredentialsServiceLike;\n sessions: { get(id: string): unknown };\n settings: SettingsLike;\n fiber: unknown;\n get(name: 'sessionPersistence'): { stat(id: string): Promise<{ header: SessionHeaderLike } | undefined> } | undefined;\n get(name: 'subagentModelSelection'): { allowedRoutes(): readonly ModelRoute[] | undefined } | undefined;\n get(name: 'llm'): { resolveCallConfig(selection: RouteSelection, signal?: AbortSignal): Promise<unknown> } | undefined;\n on(event: string, listener: (...args: any[]) => unknown): () => void;\n effect(factory: () => void | (() => void | Promise<void>), label?: string): unknown;\n inject(names: string[] | string, callback: (ctx: HostContext) => void | (() => void)): void;\n}\n\n/** The route a child runs on; the three fields travel together. */\ninterface ModelRoute {\n provider: string;\n model: string;\n}\n\ninterface RouteSelection extends ModelRoute {\n reasoningEffort?: string;\n}\n\n/** The Agent model face this plugin uses: read the inherited route, select the judged one. */\ninterface AgentModelLike {\n current(): RouteSelection | undefined;\n select(selection: RouteSelection): void;\n}\n\n/** Which Agent fields this plugin reads when a child is created. */\ninterface RequestAgent {\n id: string;\n options: { subagentDepth?: number };\n session: SessionLike;\n model: AgentModelLike;\n}\n\n/** How many judged children to remember before forgetting the oldest. */\nconst JUDGED_LIMIT = 500;\n\n/**\n * The set of children already judged, bounded so a long-running instance cannot\n * grow without limit.\n *\n * Insertion order is eviction order: a `Set` iterates oldest-first, so the one\n * entry that goes is always the earliest judgement. Forgetting a very old child\n * costs at most one extra judgement should it somehow make another request,\n * which is strictly better than an unbounded map keyed by every subagent ever\n * delegated.\n */\nclass JudgedChildren {\n private readonly seen = new Set<string>();\n\n /** Record a child as judged, forgetting the oldest entry past the cap. */\n add(id: string): void {\n this.seen.add(id);\n if (this.seen.size <= JUDGED_LIMIT) return;\n const oldest = this.seen.values().next();\n if (!oldest.done) this.seen.delete(oldest.value);\n }\n\n /** Whether this child has already been judged. */\n has(id: string): boolean {\n return this.seen.has(id);\n }\n}\n\n/**\n * Mount the host half: judge every subagent once, write the route the judgement\n * chose, and keep the log the Plugins page reads.\n *\n * @param ctx - DSH Host context.\n * @param config - this plugin's runtime-resolved Config (every field a live ref).\n */\nexport function apply(ctx: HostContext, config: PluginConfigRefs): void {\n const log = new LogStore();\n const lifetime = new AbortController();\n /** Children already judged, so a ten-step child is asked about once. */\n const judged = new JudgedChildren();\n let apiKey = '';\n\n void log.init();\n\n const resolvedConfig = (): ResolvedConfig => readPluginConfig(config);\n\n /** Re-read the judge key; a key set outside the page takes effect at once. */\n const refreshKey = async (): Promise<void> => {\n try {\n apiKey = ((await ctx.credentials.resolve(JUDGE_API_KEY_REF))?.value ?? '').trim();\n } catch {\n apiKey = '';\n }\n };\n void refreshKey();\n ctx.on('credentials/reference-updated', () => {\n void refreshKey();\n });\n\n // Settings are read and written through the Plugins page's own card; DSH must\n // not also derive a generic settings form for the same entry.\n ctx.inject(['settings'], (child) => {\n child.effect(\n () => child.settings.configure({ auto: false }, child.fiber),\n 'dsh-subagent-judge-dispatch: settings page policy'\n );\n });\n\n /**\n * The delegation hook: one judgement per subagent, then the route it chose.\n *\n * Runs on `agent/created`, which the Host awaits before releasing the child's\n * queued work: the route selected here is the one the child's first step\n * prepares with.\n *\n * Never throws and never cancels: every failure path writes nothing, which is\n * what makes a judge outage cost latency and nothing else. The judgement is\n * awaited because the Host awaits this hook, so it can add up to the judge\n * budget to that one delegation.\n */\n ctx.on('agent/created', async ({ agent, source, signal }: {\n agent?: RequestAgent; source: string; signal?: AbortSignal;\n }) => {\n const cancellation = signal === undefined ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);\n if (agent === undefined || !isSubagent(agent) || judged.has(agent.id) || cancellation.aborted) return;\n if (source !== 'startup' && source !== 'resume') return;\n const resumed = source === 'resume';\n\n const budget = new JudgeBudget(cancellation);\n try {\n const lookup = (id: string) => ctx.sessions.get(id) as SessionLike | undefined;\n const parentId = agent.session.header.parentSession;\n const rootId = parentId ? await budget.run(() => resolveRootSessionId(parentId, async (id) => {\n budget.check();\n return lookup(id)?.header ?? (await ctx.get('sessionPersistence')?.stat(id))?.header;\n })) : undefined;\n const cfg = resolvedConfig();\n if (cancellation.aborted || !isJudgeUsable(cfg, rootId) || judged.has(agent.id)) return;\n const task = readDelegatedTask(agent, lookup, resumed);\n if (task === undefined || task.explicitRoute) return;\n judged.add(agent.id);\n\n const { label, text: taskText } = task;\n const inherited = agent.model.current() ?? { provider: '', model: '' };\n const outcome = await judgeTaskType(\n { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },\n selectableRows(cfg.rows),\n composeJudgeSubject(label, taskText),\n fetch,\n budget,\n );\n let decision = decideRewrite(outcome);\n let routeFailure: FallbackReason | undefined;\n if (decision.kind === 'rewrite') {\n const route = decision.rewrite;\n const llm = ctx.get('llm');\n const allowed = (): boolean => ctx.get('subagentModelSelection')?.allowedRoutes()?.some(\n (pair) => pair.provider === route.provider && pair.model === route.model,\n ) === true;\n try {\n if (llm === undefined || !allowed()) throw new Error('Unavailable child route');\n await budget.run((preflightSignal) => llm.resolveCallConfig(route, preflightSignal));\n if (!allowed()) throw new Error('Child route no longer allowed');\n if (cancellation.aborted || !isJudgeUsable(resolvedConfig(), rootId) || hasRecordedRoute(agent.session, resumed)) return;\n budget.check();\n agent.model.select(route);\n } catch {\n decision = { kind: 'none' };\n routeFailure = budget.expired() ? 'timeout' : 'unavailable-route';\n }\n }\n\n if (resolvedConfig().logEnabled && !cancellation.aborted) {\n log.append(buildEntry(inherited, decision, outcome, taskText, budget.elapsed(), routeFailure));\n }\n } catch {\n // A judge outage, an unreadable parent log or a Host rejection of the\n // selection costs this delegation latency and nothing else.\n } finally {\n budget.dispose();\n }\n });\n\n // The three reads only the Host can answer. Connection's /api transport is\n // composed by a Web carrier; without one the plugin loads and simply has no\n // HTTP surface.\n ctx.inject(['connection'], (connectionCtx) => {\n const routes = createFetchRoutes({\n config: resolvedConfig,\n log: () => log.readLatest(),\n apiKey: () => apiKey,\n sample: async (task) => {\n const cfg = resolvedConfig();\n const budget = new JudgeBudget(lifetime.signal);\n try {\n const outcome = await judgeTaskType(\n { url: cfg.endpointUrl, model: cfg.judgeModel, apiKey },\n selectableRows(cfg.rows), composeJudgeSubject('', task), fetch, budget,\n );\n const decision = decideRewrite(outcome);\n if (decision.kind !== 'rewrite') return { ok: false, reason: outcomeReason(outcome, decision) };\n const route = decision.rewrite;\n const llm = ctx.get('llm');\n const allowed = () => ctx.get('subagentModelSelection')?.allowedRoutes()?.some(\n (pair) => pair.provider === route.provider && pair.model === route.model,\n ) === true;\n try {\n if (llm === undefined || !allowed()) throw new Error('Unavailable child route');\n await budget.run((signal) => llm.resolveCallConfig(route, signal));\n if (!allowed()) throw new Error('Child route no longer allowed');\n budget.check();\n return { ok: true, typeId: outcome.kind === 'matched' ? outcome.row.id : null, route, valid: true };\n } catch {\n return { ok: false, typeId: outcome.kind === 'matched' ? outcome.row.id : null, route, valid: false,\n reason: budget.expired() ? 'timeout' : 'unavailable-route' };\n }\n } finally {\n budget.dispose();\n }\n },\n });\n const disposers = routes.map((route) =>\n (connectionCtx as HostContext & { connection: HostConnectionHandle }).connection.fetch.register(route)\n );\n return () => {\n for (const dispose of disposers) void Promise.resolve(dispose()).catch(() => {});\n };\n });\n\n // \u6BCF\u6B21\u8FFD\u52A0\u90FD\u7ACB\u523B\u5F00\u5199\uFF1B\u5378\u8F7D\u65F6\u518D\u7B49\u4E00\u6B21\u5728\u98DE\u7684\u5199\u843D\u5730\uFF0C\u5378\u8F7D\u4E0D\u4E22\u6700\u540E\u90A3\u6761\u3002\n ctx.effect(\n () => () => {\n lifetime.abort();\n return log.flush();\n },\n 'dsh-subagent-judge-dispatch: judgement log flush',\n );\n}\n\n/**\n * Build the log row for one judged delegation.\n *\n * A fallback row reports the route the child actually keeps \u2014 the main agent's\n * resolved provider, model and effort \u2014 rather than a blank, because the point\n * of the row is what the child ran on.\n */\nfunction buildEntry(\n resolved: RouteSelection,\n decision: ReturnType<typeof decideRewrite>,\n outcome: Awaited<ReturnType<typeof judgeTaskType>>,\n taskText: string,\n latencyMs: number,\n routeFailure: FallbackReason | undefined,\n): LogEntry {\n const matched = decision.kind === 'rewrite';\n const reason = routeFailure ?? outcomeReason(outcome, decision);\n return {\n typeId: matched && outcome.kind === 'matched' ? outcome.row.id : null,\n ...outcome.kind === 'matched' ? { typeDescription: outcome.row.description } : {},\n taskText,\n ...matched && outcome.kind === 'matched' && outcome.row.stableId ? { typeKey: outcome.row.stableId } : {},\n provider: matched ? decision.rewrite.provider : resolved.provider,\n model: matched ? decision.rewrite.model : resolved.model,\n effort: matched\n ? decision.rewrite.reasoningEffort\n : typeof resolved.reasoningEffort === 'string' ? resolved.reasoningEffort : '',\n ...reason === undefined ? {} : { reason },\n at: Date.now(),\n latencyMs,\n ...outcome.metrics === undefined ? {} : { metrics: outcome.metrics },\n };\n}\n"],
5
+ "mappings": ";AACO,IAAM,kBAAkB;AACxB,IAAM,qBAAqB;AAK3B,SAAS,WAAW,WAAoB,UAAmB,WAA6B;AAC7F,MAAI,cAAc,UAAa,cAAc,QAAQ,OAAO,cAAc,YACrE,CAAC,OAAO,OAAO,WAAW,SAAS,EAAG,QAAO;AAClD,QAAM,SAAU,UAA+B,SAAS;AACxD,SAAO,OAAO,WAAW,YAAY,SAAS;AAChD;;;ACKA,OAAO,OAAO;;;ACNd,IAAM,iBAAiB,CAAC,iBAAiB,YAAY;AAa9C,SAAS,mBAAmB,OAAwB;AACzD,QAAM,UAAU,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;AAC3D,QAAM,MAAM,IAAI,MAAM,OAA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AAS,kBAAkB;AAAA,IAC9E,GAAG,WAAW,SAAY,CAAC,IAAI,EAAE,OAAO;AAAA,IACxC,IAAI,KAAK,IAAI;AAAA,IACb;AAAA,IACA,GAAG,QAAQ,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;AAAA,EACrE;AACF;",
6
6
  "names": ["path", "text", "text", "resolve", "record", "dirname", "path", "count", "text"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lynn123411/dsh-subagent-judge-dispatch",
3
- "version": "0.6.10",
3
+ "version": "0.6.11",
4
4
  "description": "用一个判断模型从你写的任务类型清单里挑一个编号,据此改写子代理使用的模型与思考强度。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",