dsh-cohub 0.9.1 → 0.9.2

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.
Files changed (3) hide show
  1. package/README.md +3 -1
  2. package/lib/index.js +1292 -67
  3. package/package.json +2 -5
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import z from "@deepseek-ai/schemastery";
2
+ import z2 from "@deepseek-ai/schemastery";
3
3
  import { readFileSync as readFileSync4 } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { dshHomePath as dshHomePath4 } from "@deepseek-ai/dsh-home-paths";
@@ -359,6 +359,7 @@ co-explorer 搜索定位 → co-librarian 外部研究 → co-observer 多媒体
359
359
  T2/T3 汇总信息收集结果委派 co-planner 制定结构化方案,**要求其输出上限 8 行清单**(超出则合并同类项,或建议拆为多次交付)。收到后审核(需求覆盖度、委派对象合理性、并行策略可行性),修正后用 todo_write 创建任务列表。**方案末尾必须提供选项供用户选择(A. 立即执行 / B. 修改方案 / C. 取消)**,用 ask_user_question 发出,等用户回复后再进入调度执行。
360
360
 
361
361
  ## 4. 调度执行
362
+ **状态维护归父代理**:\`todo_write\` 建的表全程由你维护——派发前把本轮要做的对应项置 \`in_progress\`、未开始项保持 \`pending\`,禁止建一次就丢;状态只由你写回,子代理不碰面板。
362
363
  **按 planner 方案的并行分组执行**:planner 已标注每个子任务的 \`[可并行]\` / \`→ 依赖任务X\` 与批次号,直接按批次组织派发,不要重新分析依赖;下方检查清单用于验证分组是否合理(而非重建分组),确有写冲突或数据依赖错误时修正后执行。
363
364
  **执行前检查清单(每次派发前逐条确认)**:
364
365
  □ 列出本轮全部待委派 delegate(skill + 对象 + 作用文件)
@@ -369,6 +370,7 @@ T2/T3 汇总信息收集结果委派 co-planner 制定结构化方案,**要求
369
370
  □ 大批量同类任务 → 并行度克制,收益递减收敛分批(每批 2-3)
370
371
  □ 确认派发方式 → 单条消息同时发起所有无依赖且不冲突的 delegate tool_use 块;不同批次间串行(上批 tool_result 全部返回后再发下批),绝不逐个串行
371
372
  委派指令用中文。
373
+ **单项完成立即回写**:每个 todo 项验收通过后立刻调 \`todo_write\` 标 \`completed\`;同批多个子代理一起返回可合并成一次更新,但必须在该批结束、下一批派发之前写回,不得攒到整轮结束才更新(否则面板长期停在「进行中」)。
372
374
 
373
375
  ## 5. 验证(收敛验证,不默认全量复审)
374
376
  **T1/T2 固定为「co-fixer 自验(build + 相关测试)即完成验证」**,不追加 co-oracle 全量审查。仅以下情况追加:T3;或改动涉及「公共导出 / 配置 schema / preset 组合 / 权限与路径边界」时追加 co-oracle;**只有 UI 改动的 T1/T2 才需 co-designer**。同一事实不重复全量复审——上一轮已核实通过的结论不因新需求重跑。发现问题重新委派。多文件修改全部完成后一次性编译验证,不要每改一个文件跑一次。修改验证通过后立即委派 co-fixer 提交(git commit,精确 add 本次文件,隔离他人未提交改动);生成物若被 .gitignore 忽略则无需提交,只提交源文件。
@@ -376,6 +378,8 @@ T2/T3 汇总信息收集结果委派 co-planner 制定结构化方案,**要求
376
378
  **验证范围与扩大条件**:每轮验证范围由委派 prompt 明确——范围(修改文件/功能)、负责人(按第 5 步收敛验证:默认 co-fixer 自验;co-oracle / co-designer 仅在满足第 5 步追加条件时介入)、通过标准;多代理并行修改的 Wave 不自测,批量修改全部完成后统一验证。失败先集中归因(真实退出码/错误消息/日志位置),先定向修复最小范围,验证通过后再按影响面扩大;诊断/交互类问题(工具不可用、环境异常等)在报告中说明理由后可作例外,不绝对禁止扩大。
377
379
 
378
380
  **证据复用纪律**:仅复用成功完成的只读检查,且仍覆盖当前输入/源码与测试/配置/完整范围/环境及外部状态,证据不足就必要重验;失败不是通过证据,无新变更/目标时不机械重跑已知失败,先分析;不用 git diff 文件名未变判定同状态,不自动忽略 docs/config 影响;保留用户要求、TDD、竞态/稳定性计划性重复与相关变更后的复验;不设永远全量一次硬上限,不引入测试缓存/helper/强制模型保证。
381
+
382
+ **收尾对账(硬性)**:最终回复用户前必须再调一次 \`todo_write\` 对账——成功项标 \`completed\`、不再做的项删除、失败/阻塞项留 \`pending\` 并在回复里说明原因;**不得遗留任何 \`in_progress\`**,面板上残留「进行中」即视为本轮未完成。
379
383
  </工作流>
380
384
 
381
385
  ## 执行器环境契约(通用原则 + 探测式自适应)
@@ -1840,6 +1844,1221 @@ async function budgetResultWithSpill(ctx, raw, options) {
1840
1844
  };
1841
1845
  }
1842
1846
 
1847
+ // node_modules/@deepseek-ai/dsh-llm/lib/index.js
1848
+ import { createRequire as createRequire2 } from "node:module";
1849
+
1850
+ // node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
1851
+ import { Context, Service } from "@deepseek-ai/cordis";
1852
+ var RemoteError = class extends Error {
1853
+ code;
1854
+ details;
1855
+ isDSHRemoteError = true;
1856
+ constructor(code, message, details, options) {
1857
+ super(message, options);
1858
+ this.code = code;
1859
+ this.details = details;
1860
+ this.name = "RemoteError";
1861
+ }
1862
+ };
1863
+ var TYPERT_OWNED_VALUE = Symbol.for("dsh.typert.owned-value");
1864
+ var TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
1865
+ function isTypertRemoteSegment(value) {
1866
+ return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
1867
+ }
1868
+ var REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
1869
+ function bindTypertRemote(service, serviceKey, options = {}) {
1870
+ validateName("service key", serviceKey);
1871
+ const namespace = options.namespace ?? serviceKey;
1872
+ validateName("namespace", namespace);
1873
+ const ctx = Reflect.get(service, "ctx");
1874
+ if (ctx instanceof Context)
1875
+ provideInvocationAccessor(ctx);
1876
+ return Object.freeze({
1877
+ service,
1878
+ serviceKey,
1879
+ namespace
1880
+ });
1881
+ }
1882
+ var TypertRemoteService = class extends Service {
1883
+ typertRemote;
1884
+ constructor(ctx, serviceKey, options = {}) {
1885
+ super(ctx, serviceKey);
1886
+ this.typertRemote = bindTypertRemote(this, this.name, options);
1887
+ }
1888
+ };
1889
+ function provideInvocationAccessor(ctx) {
1890
+ if (Object.hasOwn(ctx.root.reflect.props, "invocation"))
1891
+ return;
1892
+ ctx.root.accessor("invocation", { get: () => {
1893
+ return;
1894
+ } });
1895
+ }
1896
+ function Remote(methodExportOrOptions, context) {
1897
+ if (typeof methodExportOrOptions === "string") {
1898
+ validateName("Remote export name", methodExportOrOptions);
1899
+ return remoteDecorator({ kind: "direct" }, undefined, methodExportOrOptions);
1900
+ }
1901
+ if (typeof methodExportOrOptions === "object") {
1902
+ if (remoteOptionMode(methodExportOrOptions) !== "stream" || Reflect.ownKeys(methodExportOrOptions).length !== 1)
1903
+ throw new TypeError('typert-protocol: Remote options must contain exactly mode: "stream"');
1904
+ return remoteDecorator({ kind: "direct" }, "stream");
1905
+ }
1906
+ if (context === undefined)
1907
+ throw new TypeError("typert-protocol: Remote decorator context is missing");
1908
+ addMarkerInitializer(context, { kind: "direct" });
1909
+ }
1910
+ function remoteOptionMode(options) {
1911
+ return Reflect.get(options, "mode");
1912
+ }
1913
+ function remoteDecorator(invocation, mode, exportName) {
1914
+ return function(_method, context) {
1915
+ addMarkerInitializer(context, invocation, mode, exportName);
1916
+ };
1917
+ }
1918
+ function readRemoteMethodDescriptor(prototype) {
1919
+ const property = Object.getOwnPropertyDescriptor(prototype, REMOTE_METHOD_DESCRIPTOR);
1920
+ if (property === undefined)
1921
+ return;
1922
+ const descriptor = property.value;
1923
+ if (descriptor === null || typeof descriptor !== "object")
1924
+ throw new TypeError("typert-protocol: Remote method descriptor must be an object");
1925
+ const version = Reflect.get(descriptor, "version");
1926
+ if (version !== 1)
1927
+ throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(version)}`);
1928
+ const methods = Reflect.get(descriptor, "methods");
1929
+ if (!Array.isArray(methods))
1930
+ throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
1931
+ return descriptor;
1932
+ }
1933
+ function addMarkerInitializer(context, invocation, mode, exportName) {
1934
+ if (context.private || context.static || typeof context.name !== "string")
1935
+ throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");
1936
+ const method = context.name;
1937
+ context.addInitializer(function() {
1938
+ const prototype = Object.getPrototypeOf(this);
1939
+ if (prototype === null)
1940
+ throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
1941
+ mark(prototype, method, invocation, mode, exportName);
1942
+ });
1943
+ }
1944
+ function mark(prototype, method, invocation, mode, exportName) {
1945
+ const descriptor = readRemoteMethodDescriptor(prototype);
1946
+ const marker = Object.freeze({
1947
+ method,
1948
+ ...exportName === undefined || exportName === method ? {} : { exportName },
1949
+ ...mode === undefined ? {} : { mode },
1950
+ invocation: Object.freeze(invocation)
1951
+ });
1952
+ const current = descriptor?.methods.find((candidate) => candidate.method === method);
1953
+ if (current !== undefined) {
1954
+ if (current.exportName === marker.exportName && current.mode === marker.mode && sameInvocation(current.invocation, invocation))
1955
+ return;
1956
+ throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
1957
+ }
1958
+ Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
1959
+ configurable: true,
1960
+ value: Object.freeze({
1961
+ version: 1,
1962
+ methods: Object.freeze([...descriptor?.methods ?? [], marker])
1963
+ })
1964
+ });
1965
+ }
1966
+ function sameInvocation(left, right) {
1967
+ if (left.kind === "direct")
1968
+ return right.kind === "direct";
1969
+ if (right.kind === "direct")
1970
+ return false;
1971
+ return left.context === right.context;
1972
+ }
1973
+ function validateName(subject, value) {
1974
+ if (!isTypertRemoteSegment(value))
1975
+ throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
1976
+ }
1977
+
1978
+ // node_modules/@deepseek-ai/dsh-util-values/lib/index.js
1979
+ function assertNever(value, context) {
1980
+ const rendered = JSON.stringify(value) ?? String(value);
1981
+ throw new Error(`unreachable variant${context ? ` in ${context}` : ""}: ${rendered}`);
1982
+ }
1983
+ function deepFreeze(value) {
1984
+ const seen = /* @__PURE__ */ new WeakSet;
1985
+ const pending = [{
1986
+ kind: "visit",
1987
+ node: value
1988
+ }];
1989
+ while (pending.length > 0) {
1990
+ const task = pending.pop();
1991
+ if (task === undefined)
1992
+ continue;
1993
+ if (task.kind === "property") {
1994
+ pending.push({
1995
+ kind: "visit",
1996
+ node: task.source[task.key]
1997
+ });
1998
+ continue;
1999
+ }
2000
+ const node = task.node;
2001
+ if (node === null || typeof node !== "object")
2002
+ continue;
2003
+ if (node instanceof AbortSignal)
2004
+ continue;
2005
+ if (seen.has(node))
2006
+ continue;
2007
+ seen.add(node);
2008
+ Object.freeze(node);
2009
+ const keys = Object.keys(node);
2010
+ for (let index = keys.length - 1;index >= 0; index--) {
2011
+ const key = keys[index];
2012
+ if (key === undefined)
2013
+ continue;
2014
+ pending.push({
2015
+ kind: "property",
2016
+ source: node,
2017
+ key
2018
+ });
2019
+ }
2020
+ }
2021
+ return value;
2022
+ }
2023
+
2024
+ // node_modules/@deepseek-ai/dsh-util-crypto/lib/index.js
2025
+ function randomUUID() {
2026
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
2027
+ const hex = Array.from(bytes, (byte, index) => {
2028
+ return (index === 6 ? byte & 15 | 64 : index === 8 ? byte & 63 | 128 : byte).toString(16).padStart(2, "0");
2029
+ }).join("");
2030
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2031
+ }
2032
+
2033
+ // node_modules/@deepseek-ai/dsh-brand/lib/index.js
2034
+ function brandString(value) {
2035
+ return value;
2036
+ }
2037
+
2038
+ // node_modules/@deepseek-ai/dsh-llm/lib/index.js
2039
+ import z from "@deepseek-ai/schemastery";
2040
+
2041
+ // node_modules/@deepseek-ai/dsh-timeout/lib/index.js
2042
+ var MAX_TIMER_DELAY_MS = 2147483647;
2043
+
2044
+ // node_modules/@deepseek-ai/dsh-llm/lib/index.js
2045
+ function freezeMessage(message) {
2046
+ return deepFreeze(structuredClone(message));
2047
+ }
2048
+ function createMessage(input) {
2049
+ return deepFreeze(structuredClone({
2050
+ ...input,
2051
+ id: brandString(randomUUID())
2052
+ }));
2053
+ }
2054
+ function createUserMessage(input) {
2055
+ return createMessage({
2056
+ ...input,
2057
+ role: "user"
2058
+ });
2059
+ }
2060
+ var HarnessError = class extends Error {
2061
+ code;
2062
+ constructor(message, code, options) {
2063
+ super(message, options);
2064
+ this.code = code;
2065
+ this.name = new.target.name;
2066
+ }
2067
+ };
2068
+ var EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
2069
+ var STRUCTURED_CONTEXT_OVERFLOW = new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` + String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`, "i");
2070
+ var TOO_LARGE_FOR_CONTEXT = new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?` + String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?` + String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`, "i");
2071
+ var EXCEEDS_MODEL_CONTEXT = new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}` + String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}` + String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`, "i");
2072
+ var DEFAULT_MAX_RETRIES = 5;
2073
+ var DEFAULT_INITIAL_DELAY_MS = 500;
2074
+ var DEFAULT_MAX_DELAY_MS = 1e4;
2075
+ var DEFAULT_JITTER_RATIO = 0.1;
2076
+ var DEFAULT_RETRYABLE_CODES = Object.freeze([
2077
+ EMPTY_RESPONSE_CODE,
2078
+ "RATE_LIMIT",
2079
+ "SERVER",
2080
+ "TIMEOUT",
2081
+ "TRANSPORT"
2082
+ ]);
2083
+ var backoffSchema = z.object({
2084
+ initialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
2085
+ maxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
2086
+ jitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
2087
+ });
2088
+ var normalPolicySchema = z.object({
2089
+ mode: z.const("normal").required(),
2090
+ maxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
2091
+ retryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),
2092
+ backoff: backoffSchema
2093
+ });
2094
+ var alwaysPolicySchema = z.object({
2095
+ mode: z.const("always").required(),
2096
+ backoff: backoffSchema
2097
+ });
2098
+ var RetryPolicySchema = z.union([normalPolicySchema, alwaysPolicySchema]);
2099
+ var NORMAL_POLICY_KEYS = new Set([
2100
+ "mode",
2101
+ "maxRetries",
2102
+ "retryableCodes",
2103
+ "backoff"
2104
+ ]);
2105
+ var ALWAYS_POLICY_KEYS = new Set([
2106
+ "mode",
2107
+ "maxRetries",
2108
+ "retryableCodes",
2109
+ "backoff"
2110
+ ]);
2111
+ var BACKOFF_KEYS = new Set([
2112
+ "initialDelayMs",
2113
+ "maxDelayMs",
2114
+ "jitterRatio"
2115
+ ]);
2116
+ function validateKeys(value, allowed, path) {
2117
+ for (const key of Object.keys(value))
2118
+ if (!allowed.has(key))
2119
+ throw new Error(`${path}: unknown key "${key}"`);
2120
+ }
2121
+ function resolveBackoff(config, path) {
2122
+ if (config !== undefined)
2123
+ validateKeys(config, BACKOFF_KEYS, path);
2124
+ const initialDelayMs = config?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
2125
+ const maxDelayMs = config?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
2126
+ const jitterRatio = config?.jitterRatio ?? DEFAULT_JITTER_RATIO;
2127
+ if (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > MAX_TIMER_DELAY_MS)
2128
+ throw new Error(`${path}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
2129
+ if (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > MAX_TIMER_DELAY_MS)
2130
+ throw new Error(`${path}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
2131
+ if (initialDelayMs > maxDelayMs)
2132
+ throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
2133
+ if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1)
2134
+ throw new Error(`${path}.jitterRatio must be between 0 and 1`);
2135
+ return Object.freeze({
2136
+ initialDelayMs,
2137
+ maxDelayMs,
2138
+ jitterRatio
2139
+ });
2140
+ }
2141
+ function resolveRetryPolicy(config, path) {
2142
+ if (config === undefined)
2143
+ return Object.freeze({
2144
+ mode: "normal",
2145
+ maxRetries: DEFAULT_MAX_RETRIES,
2146
+ retryableCodes: DEFAULT_RETRYABLE_CODES,
2147
+ ...resolveBackoff(undefined, `${path}.backoff`)
2148
+ });
2149
+ switch (config.mode) {
2150
+ case "normal": {
2151
+ validateKeys(config, NORMAL_POLICY_KEYS, path);
2152
+ const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
2153
+ const retryableCodes = config.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];
2154
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0)
2155
+ throw new Error(`${path}.maxRetries must be a non-negative safe integer`);
2156
+ if (retryableCodes.length === 0)
2157
+ throw new Error(`${path}.retryableCodes must not be empty`);
2158
+ if (retryableCodes.some((code) => typeof code !== "string" || code.length === 0))
2159
+ throw new Error(`${path}.retryableCodes must contain only non-empty strings`);
2160
+ if (new Set(retryableCodes).size !== retryableCodes.length)
2161
+ throw new Error(`${path}.retryableCodes must not contain duplicates`);
2162
+ return Object.freeze({
2163
+ mode: "normal",
2164
+ maxRetries,
2165
+ retryableCodes: Object.freeze([...retryableCodes]),
2166
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
2167
+ });
2168
+ }
2169
+ case "always":
2170
+ validateKeys(config, ALWAYS_POLICY_KEYS, path);
2171
+ return Object.freeze({
2172
+ mode: "always",
2173
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
2174
+ });
2175
+ default:
2176
+ throw new Error(`${path}.mode must be "normal" or "always"`);
2177
+ }
2178
+ }
2179
+ function callConfigEquals(a, b) {
2180
+ if (a.provider !== b.provider || a.model !== b.model || a.reasoningEffort !== b.reasoningEffort || a.temperature !== b.temperature || a.maxTokens !== b.maxTokens)
2181
+ return false;
2182
+ if (a.stop === undefined || b.stop === undefined)
2183
+ return a.stop === b.stop;
2184
+ return a.stop.length === b.stop.length && a.stop.every((s, i) => s === b.stop?.[i]);
2185
+ }
2186
+ function normalizeLlmFailure(value) {
2187
+ const error = value instanceof Error ? value : new HarnessError(thrownMessage(value), "UNKNOWN", { cause: value });
2188
+ const carried = ownFailureSnapshot(error);
2189
+ if (carried !== undefined && carried.code === ownErrorCode(error))
2190
+ return carried;
2191
+ return Object.freeze({
2192
+ message: errorMessage(error),
2193
+ code: harnessErrorCode(error)
2194
+ });
2195
+ }
2196
+ function thrownMessage(value) {
2197
+ try {
2198
+ const message = String(value);
2199
+ return message.length > 0 ? message : "LLM adapter failed";
2200
+ } catch (_hostileThrownValue) {
2201
+ return "LLM adapter failed";
2202
+ }
2203
+ }
2204
+ function ownErrorCode(error) {
2205
+ try {
2206
+ const descriptor = Object.getOwnPropertyDescriptor(error, "code");
2207
+ return descriptor !== undefined && "value" in descriptor ? descriptor.value : undefined;
2208
+ } catch (_sdkPropertyTrap) {
2209
+ return;
2210
+ }
2211
+ }
2212
+ function ownFailureSnapshot(error) {
2213
+ try {
2214
+ const descriptor = Object.getOwnPropertyDescriptor(error, "failure");
2215
+ return descriptor !== undefined && "value" in descriptor ? failureSnapshot(descriptor.value) : undefined;
2216
+ } catch (_sdkPropertyTrap) {
2217
+ return;
2218
+ }
2219
+ }
2220
+ function failureSnapshot(value) {
2221
+ if (typeof value !== "object" || value === null)
2222
+ return;
2223
+ try {
2224
+ const candidate = value;
2225
+ const message = candidate.message;
2226
+ const code = candidate.code;
2227
+ const status = candidate.status;
2228
+ const providerRetryAfterMs = candidate.providerRetryAfterMs;
2229
+ const requestId = candidate.requestId;
2230
+ const offloadImages = candidate.offloadImages;
2231
+ if (typeof message !== "string" || message.length === 0 || typeof code !== "string" || code.length === 0 || status !== undefined && (!Number.isInteger(status) || status < 100 || status > 599) || providerRetryAfterMs !== undefined && (!Number.isFinite(providerRetryAfterMs) || providerRetryAfterMs <= 0) || requestId !== undefined && (typeof requestId !== "string" || requestId.length === 0) || offloadImages !== undefined && (!Number.isSafeInteger(offloadImages) || offloadImages <= 0))
2232
+ return;
2233
+ return Object.freeze({
2234
+ message,
2235
+ code,
2236
+ ...status === undefined ? {} : { status },
2237
+ ...providerRetryAfterMs === undefined ? {} : { providerRetryAfterMs },
2238
+ ...requestId === undefined ? {} : { requestId },
2239
+ ...offloadImages === undefined ? {} : { offloadImages }
2240
+ });
2241
+ } catch (_sdkFailureGetter) {
2242
+ return;
2243
+ }
2244
+ }
2245
+ function errorMessage(error) {
2246
+ try {
2247
+ const message = error.message;
2248
+ if (typeof message === "string" && message.length > 0)
2249
+ return message;
2250
+ } catch (_sdkMessageGetter) {}
2251
+ return "LLM adapter failed";
2252
+ }
2253
+ function harnessErrorCode(error) {
2254
+ return error instanceof HarnessError ? error.code : "UNKNOWN";
2255
+ }
2256
+ function quoted(value) {
2257
+ return JSON.stringify(value);
2258
+ }
2259
+ function textOnlyImageText(ref) {
2260
+ return `[image omitted because this model accepts text only; attachment sha256:${String(ref.attachmentId).slice(7, 15)}]`;
2261
+ }
2262
+ function contentHasImage(content) {
2263
+ return content.some((block) => block.type === "image");
2264
+ }
2265
+ function contentHasFile(content) {
2266
+ for (const block of content)
2267
+ if (block.type === "file")
2268
+ return true;
2269
+ return false;
2270
+ }
2271
+ function fileHandleText(ref, readonlyPath) {
2272
+ const digest = String(ref.attachmentId).slice(7, 15);
2273
+ const identity = `File ${quoted(ref.name)} (${ref.bytes} bytes, sha256:${digest})`;
2274
+ if (readonlyPath === undefined)
2275
+ return `[${identity} was uploaded, but the current execution environment cannot access a readable path. Report that limitation if its contents are needed; do not claim to have read it.]`;
2276
+ return `[${identity}: verbatim read-only copy saved at ${quoted(readonlyPath)}. Read that path with your file tools when its contents are needed; copy it to a writable location before modifying it. When delegating file work, include this saved path in the delegation prompt; only subagents sharing this execution environment can read it.]`;
2277
+ }
2278
+ function replaceFilesWithHandles(blocks, resolvePath) {
2279
+ let next;
2280
+ for (const [index, block] of blocks.entries()) {
2281
+ if (block.type === "file") {
2282
+ next ??= blocks.slice(0, index);
2283
+ next.push({
2284
+ type: "text",
2285
+ text: fileHandleText(block.attachment, resolvePath(block.attachment))
2286
+ });
2287
+ continue;
2288
+ }
2289
+ next?.push(block);
2290
+ }
2291
+ return next ?? blocks;
2292
+ }
2293
+ function projectFilesToText(messages, resolvePath) {
2294
+ if (!messages.some((message) => contentHasFile(message.content)))
2295
+ return messages;
2296
+ return messages.map((message) => {
2297
+ const content = replaceFilesWithHandles(message.content, resolvePath);
2298
+ return content === message.content ? message : {
2299
+ ...message,
2300
+ content
2301
+ };
2302
+ });
2303
+ }
2304
+ function replaceImagesForTextModel(blocks) {
2305
+ let next;
2306
+ for (const [index, block] of blocks.entries()) {
2307
+ if (block.type === "image") {
2308
+ next ??= blocks.slice(0, index);
2309
+ next.push({
2310
+ type: "text",
2311
+ text: textOnlyImageText(block.attachment)
2312
+ });
2313
+ continue;
2314
+ }
2315
+ next?.push(block);
2316
+ }
2317
+ return next ?? blocks;
2318
+ }
2319
+ function projectImagesForTextModel(messages) {
2320
+ if (!messages.some((message) => contentHasImage(message.content)))
2321
+ return messages;
2322
+ return messages.map((message) => {
2323
+ const content = replaceImagesForTextModel(message.content);
2324
+ return content === message.content ? message : {
2325
+ ...message,
2326
+ content
2327
+ };
2328
+ });
2329
+ }
2330
+ function withoutDeveloperMessages(messages) {
2331
+ const retained = messages.filter((message) => message.role !== "developer");
2332
+ return retained.length === messages.length ? messages : retained;
2333
+ }
2334
+ function toolDeclarations(tools, mode, history) {
2335
+ const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
2336
+ for (const update of history.updates)
2337
+ for (const tool of update.additions)
2338
+ if (!declarations.has(tool.name))
2339
+ declarations.set(tool.name, {
2340
+ ...tool,
2341
+ deferLoading: true
2342
+ });
2343
+ switch (mode) {
2344
+ case "in-history":
2345
+ return declarations;
2346
+ case "addition-only": {
2347
+ const activeNames = new Set(tools?.map((tool) => tool.name));
2348
+ for (const name of declarations.keys())
2349
+ if (!activeNames.has(name))
2350
+ declarations.delete(name);
2351
+ return declarations;
2352
+ }
2353
+ default:
2354
+ return assertNever(mode);
2355
+ }
2356
+ }
2357
+ function projectToolUpdates(messages, tools, toolUpdate, history) {
2358
+ if (toolUpdate === undefined) {
2359
+ let immediateTools = tools;
2360
+ if (tools?.some((tool) => tool.deferLoading === true))
2361
+ immediateTools = tools.map(({ deferLoading: _loading, ...tool }) => tool);
2362
+ return {
2363
+ messages: withoutDeveloperMessages(messages),
2364
+ tools: immediateTools
2365
+ };
2366
+ }
2367
+ if (history === undefined)
2368
+ return {
2369
+ messages: withoutDeveloperMessages(messages),
2370
+ tools
2371
+ };
2372
+ const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
2373
+ if (history.updates.some((update) => !messageIds.has(update.messageId)))
2374
+ return {
2375
+ messages: withoutDeveloperMessages(messages),
2376
+ tools
2377
+ };
2378
+ const declarations = toolDeclarations(tools, toolUpdate, history);
2379
+ const updateIds = new Set(history.updates.map((update) => update.messageId));
2380
+ const offered = new Set(history.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
2381
+ const projectedMessages = [];
2382
+ for (const message of messages) {
2383
+ if (message.role !== "developer") {
2384
+ projectedMessages.push(message);
2385
+ continue;
2386
+ }
2387
+ if (!updateIds.has(message.id))
2388
+ continue;
2389
+ const content = message.content.filter((block) => {
2390
+ switch (block.type) {
2391
+ case "tool-addition":
2392
+ if (!declarations.has(block.toolName) || offered.has(block.toolName))
2393
+ return false;
2394
+ offered.add(block.toolName);
2395
+ return true;
2396
+ case "tool-removal":
2397
+ if (toolUpdate !== "in-history")
2398
+ return false;
2399
+ return offered.delete(block.toolName);
2400
+ default:
2401
+ return true;
2402
+ }
2403
+ });
2404
+ if (content.length === 0)
2405
+ continue;
2406
+ if (content.length === message.content.length)
2407
+ projectedMessages.push(message);
2408
+ else
2409
+ projectedMessages.push({
2410
+ ...message,
2411
+ content
2412
+ });
2413
+ }
2414
+ return {
2415
+ messages: projectedMessages.length === messages.length && projectedMessages.every((message, index) => message === messages[index]) ? messages : projectedMessages,
2416
+ tools: [...declarations.values()]
2417
+ };
2418
+ }
2419
+ var { version } = createRequire2(import.meta.url)("../package.json");
2420
+ var __runInitializers = function(thisArg, initializers, value) {
2421
+ var useValue = arguments.length > 2;
2422
+ for (var i = 0;i < initializers.length; i++)
2423
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
2424
+ return useValue ? value : undefined;
2425
+ };
2426
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2427
+ function accept(f) {
2428
+ if (f !== undefined && typeof f !== "function")
2429
+ throw new TypeError("Function expected");
2430
+ return f;
2431
+ }
2432
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
2433
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
2434
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
2435
+ var _, done = false;
2436
+ for (var i = decorators.length - 1;i >= 0; i--) {
2437
+ var context = {};
2438
+ for (var p in contextIn)
2439
+ context[p] = p === "access" ? {} : contextIn[p];
2440
+ for (var p in contextIn.access)
2441
+ context.access[p] = contextIn.access[p];
2442
+ context.addInitializer = function(f) {
2443
+ if (done)
2444
+ throw new TypeError("Cannot add initializers after decoration has completed");
2445
+ extraInitializers.push(accept(f || null));
2446
+ };
2447
+ var result = (0, decorators[i])(kind === "accessor" ? {
2448
+ get: descriptor.get,
2449
+ set: descriptor.set
2450
+ } : descriptor[key], context);
2451
+ if (kind === "accessor") {
2452
+ if (result === undefined)
2453
+ continue;
2454
+ if (result === null || typeof result !== "object")
2455
+ throw new TypeError("Object expected");
2456
+ if (_ = accept(result.get))
2457
+ descriptor.get = _;
2458
+ if (_ = accept(result.set))
2459
+ descriptor.set = _;
2460
+ if (_ = accept(result.init))
2461
+ initializers.unshift(_);
2462
+ } else if (_ = accept(result))
2463
+ if (kind === "field")
2464
+ initializers.unshift(_);
2465
+ else
2466
+ descriptor[key] = _;
2467
+ }
2468
+ if (target)
2469
+ Object.defineProperty(target, contextIn.name, descriptor);
2470
+ done = true;
2471
+ };
2472
+ var LlmError = class extends HarnessError {
2473
+ failure;
2474
+ constructor(message, code, options) {
2475
+ if (typeof message !== "string" || message.length === 0)
2476
+ throw new Error("LlmError message must be a non-empty string");
2477
+ if (typeof code !== "string" || code.length === 0)
2478
+ throw new Error("LlmError code must be a non-empty string");
2479
+ if (options?.status !== undefined && (!Number.isInteger(options.status) || options.status < 100 || options.status > 599))
2480
+ throw new Error("LlmError status must be an integer from 100 through 599");
2481
+ if (options?.providerRetryAfterMs !== undefined && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0))
2482
+ throw new Error("LlmError providerRetryAfterMs must be a positive finite number");
2483
+ if (options?.requestId !== undefined && (typeof options.requestId !== "string" || options.requestId.length === 0))
2484
+ throw new Error("LlmError requestId must be a non-empty string");
2485
+ super(message, code, options);
2486
+ this.name = "LlmError";
2487
+ this.failure = Object.freeze({
2488
+ message,
2489
+ code,
2490
+ ...options?.status === undefined ? {} : { status: options.status },
2491
+ ...options?.providerRetryAfterMs === undefined ? {} : { providerRetryAfterMs: options.providerRetryAfterMs },
2492
+ ...options?.requestId === undefined ? {} : { requestId: options.requestId },
2493
+ ...options?.offloadImages === undefined ? {} : { offloadImages: options.offloadImages }
2494
+ });
2495
+ }
2496
+ };
2497
+ var LlmRuntime = (() => {
2498
+ let _classSuper = TypertRemoteService;
2499
+ let _instanceExtraInitializers = [];
2500
+ let _listProviders_decorators;
2501
+ let _listConfigurableProviders_decorators;
2502
+ let _remoteDiscoverModels_decorators;
2503
+ return class LlmRuntime extends _classSuper {
2504
+ static {
2505
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : undefined;
2506
+ _listProviders_decorators = [Remote];
2507
+ _listConfigurableProviders_decorators = [Remote];
2508
+ _remoteDiscoverModels_decorators = [Remote("discoverModels")];
2509
+ __esDecorate(this, null, _listProviders_decorators, {
2510
+ kind: "method",
2511
+ name: "listProviders",
2512
+ static: false,
2513
+ private: false,
2514
+ access: {
2515
+ has: (obj) => ("listProviders" in obj),
2516
+ get: (obj) => obj.listProviders
2517
+ },
2518
+ metadata: _metadata
2519
+ }, null, _instanceExtraInitializers);
2520
+ __esDecorate(this, null, _listConfigurableProviders_decorators, {
2521
+ kind: "method",
2522
+ name: "listConfigurableProviders",
2523
+ static: false,
2524
+ private: false,
2525
+ access: {
2526
+ has: (obj) => ("listConfigurableProviders" in obj),
2527
+ get: (obj) => obj.listConfigurableProviders
2528
+ },
2529
+ metadata: _metadata
2530
+ }, null, _instanceExtraInitializers);
2531
+ __esDecorate(this, null, _remoteDiscoverModels_decorators, {
2532
+ kind: "method",
2533
+ name: "remoteDiscoverModels",
2534
+ static: false,
2535
+ private: false,
2536
+ access: {
2537
+ has: (obj) => ("remoteDiscoverModels" in obj),
2538
+ get: (obj) => obj.remoteDiscoverModels
2539
+ },
2540
+ metadata: _metadata
2541
+ }, null, _instanceExtraInitializers);
2542
+ if (_metadata)
2543
+ Object.defineProperty(this, Symbol.metadata, {
2544
+ enumerable: true,
2545
+ configurable: true,
2546
+ writable: true,
2547
+ value: _metadata
2548
+ });
2549
+ }
2550
+ adapters = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map);
2551
+ directory = /* @__PURE__ */ new Map;
2552
+ discoveries = /* @__PURE__ */ new Map;
2553
+ constructor(ctx) {
2554
+ super(ctx, "llm");
2555
+ }
2556
+ emitAdaptersUpdated() {
2557
+ let invariantFailure;
2558
+ for (const listener of this.ctx.events.dispatch("emit", ["llm/adapters-updated"]))
2559
+ try {
2560
+ const returned = listener();
2561
+ if (returned != null && typeof returned.then === "function")
2562
+ Promise.resolve(returned).then(undefined, (error) => {
2563
+ this.warnAdaptersListenerFailure(error);
2564
+ });
2565
+ } catch (error) {
2566
+ if (error?.code === "INVARIANT") {
2567
+ invariantFailure ??= error;
2568
+ continue;
2569
+ }
2570
+ this.warnAdaptersListenerFailure(error);
2571
+ }
2572
+ if (invariantFailure !== undefined)
2573
+ throw invariantFailure;
2574
+ }
2575
+ warnAdaptersListenerFailure(error) {
2576
+ this.ctx.logger.warn("llm: an llm/adapters-updated listener failed");
2577
+ this.ctx.logger.warn(error);
2578
+ }
2579
+ registerAdapter(providers, adapter) {
2580
+ const owned = /* @__PURE__ */ new Set;
2581
+ let released = false;
2582
+ const dispose = this.ctx.effect(function* () {
2583
+ if (providers.length === 0)
2584
+ throw new LlmError("an adapter must register at least one provider", "INVALID_ADAPTER");
2585
+ this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned));
2586
+ yield () => {
2587
+ released = true;
2588
+ for (const provider of owned)
2589
+ this.adapters.delete(provider);
2590
+ owned.clear();
2591
+ this.emitAdaptersUpdated();
2592
+ };
2593
+ }.bind(this), "llm.registerAdapter()");
2594
+ const handle = () => void dispose();
2595
+ handle.replace = (next) => {
2596
+ if (released)
2597
+ throw new LlmError("a disposed adapter registration cannot replace its routes", "REGISTRATION_DISPOSED");
2598
+ this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned));
2599
+ };
2600
+ return handle;
2601
+ }
2602
+ prepareRoutes(providers, adapter, owned) {
2603
+ const unique = /* @__PURE__ */ new Set;
2604
+ const registrations = [];
2605
+ for (const provider of providers) {
2606
+ if (provider.length === 0)
2607
+ throw new LlmError("adapter provider names must be non-empty", "INVALID_ADAPTER");
2608
+ if (unique.has(provider) || this.adapters.has(provider) && !owned.has(provider))
2609
+ throw new LlmError(`an adapter for provider "${provider}" is already registered`, "DUPLICATE_ADAPTER");
2610
+ const info = adapter.providerInfo(provider);
2611
+ if (typeof info.id !== "string" || info.id !== provider || typeof info.name !== "string" || info.name.length === 0)
2612
+ throw new LlmError(`adapter metadata for provider "${provider}" must preserve its id and have a non-empty name`, "INVALID_ADAPTER");
2613
+ unique.add(provider);
2614
+ const retryPolicy = adapter.providerRetryPolicy(provider) ?? resolveRetryPolicy(undefined, `llm: provider "${provider}" retryPolicy`);
2615
+ registrations.push({
2616
+ adapter,
2617
+ provider: {
2618
+ id: info.id,
2619
+ name: info.name
2620
+ },
2621
+ retryPolicy
2622
+ });
2623
+ }
2624
+ return registrations;
2625
+ }
2626
+ commitRoutes(owned, registrations) {
2627
+ for (const provider of owned)
2628
+ this.adapters.delete(provider);
2629
+ owned.clear();
2630
+ for (const registration of registrations) {
2631
+ this.adapters.set(registration.provider.id, registration);
2632
+ owned.add(registration.provider.id);
2633
+ }
2634
+ this.emitAdaptersUpdated();
2635
+ }
2636
+ listProviders() {
2637
+ return [...this.adapters.values()].map(({ provider }) => ({ ...provider }));
2638
+ }
2639
+ registerConfigurableProviders(entries) {
2640
+ let held = [];
2641
+ let disposed = false;
2642
+ const commit = (candidates) => {
2643
+ const detached = [];
2644
+ const own = new Set(held.map((entry) => entry.provider));
2645
+ for (const entry of candidates) {
2646
+ if (entry.provider.length === 0 || entry.displayName.length === 0 || entry.settingsNs.length === 0)
2647
+ throw new LlmError("configurable providers need a non-empty provider, displayName, and settingsNs", "INVALID_DIRECTORY");
2648
+ if (entry.settingsPath.some((segment) => segment.length === 0))
2649
+ throw new LlmError(`configurable provider "${entry.provider}" has an empty settingsPath segment`, "INVALID_DIRECTORY");
2650
+ if (this.directory.has(entry.provider) && !own.has(entry.provider) || detached.some((seen) => seen.provider === entry.provider))
2651
+ throw new LlmError(`configurable provider "${entry.provider}" is already declared`, "DUPLICATE_DIRECTORY");
2652
+ detached.push({
2653
+ ...entry,
2654
+ settingsPath: [...entry.settingsPath]
2655
+ });
2656
+ }
2657
+ for (const entry of held)
2658
+ this.directory.delete(entry.provider);
2659
+ for (const entry of detached)
2660
+ this.directory.set(entry.provider, entry);
2661
+ held = detached;
2662
+ this.emitAdaptersUpdated();
2663
+ };
2664
+ const dispose = this.ctx.effect(function* () {
2665
+ if (entries.length === 0)
2666
+ throw new LlmError("a configurable-provider registration must declare at least one provider", "INVALID_DIRECTORY");
2667
+ commit(entries);
2668
+ yield () => {
2669
+ disposed = true;
2670
+ for (const entry of held)
2671
+ this.directory.delete(entry.provider);
2672
+ held = [];
2673
+ this.emitAdaptersUpdated();
2674
+ };
2675
+ }.bind(this), "llm.registerConfigurableProviders()");
2676
+ const handle = () => void dispose();
2677
+ handle.replace = (next) => {
2678
+ if (disposed)
2679
+ throw new LlmError("this configurable-provider registration was disposed", "REGISTRATION_DISPOSED");
2680
+ commit(next);
2681
+ };
2682
+ return handle;
2683
+ }
2684
+ listConfigurableProviders() {
2685
+ return [...this.directory.values()].map((entry) => ({
2686
+ ...entry,
2687
+ settingsPath: [...entry.settingsPath]
2688
+ }));
2689
+ }
2690
+ registerModelDiscovery(settingsNs, discover) {
2691
+ const dispose = this.ctx.effect(function* () {
2692
+ if (settingsNs.length === 0)
2693
+ throw new LlmError("model discovery needs a non-empty settings namespace", "INVALID_DISCOVERY");
2694
+ if (this.discoveries.has(settingsNs))
2695
+ throw new LlmError(`model discovery for "${settingsNs}" is already registered`, "DUPLICATE_DISCOVERY");
2696
+ this.discoveries.set(settingsNs, discover);
2697
+ yield () => {
2698
+ this.discoveries.delete(settingsNs);
2699
+ };
2700
+ }.bind(this), "llm.registerModelDiscovery()");
2701
+ return () => void dispose();
2702
+ }
2703
+ async discoverModels(settingsNs, request, signal) {
2704
+ const discover = this.discoveries.get(settingsNs);
2705
+ if (discover === undefined)
2706
+ throw new LlmError(`no model discovery is registered for "${settingsNs}"`, "NO_DISCOVERY");
2707
+ if ((request.provider ?? "").length === 0 && (request.baseURL ?? "").length === 0)
2708
+ throw new LlmError("model discovery needs a provider route or a baseURL", "INVALID_DISCOVERY");
2709
+ const discovered = signal === undefined ? await discover(request) : await discover(request, signal);
2710
+ const seen = /* @__PURE__ */ new Set;
2711
+ const models = [];
2712
+ for (const model of discovered) {
2713
+ if (typeof model.id !== "string" || model.id.length === 0 || seen.has(model.id))
2714
+ continue;
2715
+ seen.add(model.id);
2716
+ models.push({
2717
+ id: model.id,
2718
+ ...model.name === undefined ? {} : { name: model.name },
2719
+ ...model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow },
2720
+ ...model.maxTokens === undefined ? {} : { maxTokens: model.maxTokens },
2721
+ ...model.inputModalities === undefined ? {} : { inputModalities: [...model.inputModalities] }
2722
+ });
2723
+ }
2724
+ return models;
2725
+ }
2726
+ async remoteDiscoverModels(settingsNs, request, signal) {
2727
+ try {
2728
+ return await this.discoverModels(settingsNs, request, signal);
2729
+ } catch (error) {
2730
+ throw new RemoteError("llm/model-discovery-rejected", error instanceof Error ? error.message : String(error), {
2731
+ settingsNs,
2732
+ ...request.baseURL === undefined ? {} : { baseURL: request.baseURL }
2733
+ }, { cause: error });
2734
+ }
2735
+ }
2736
+ providerRetryPolicy(provider) {
2737
+ return this.registration(provider).retryPolicy;
2738
+ }
2739
+ imageRequestPricing(provider, model) {
2740
+ return this.adapters.get(provider)?.adapter.imageRequestPricing(provider, model);
2741
+ }
2742
+ fileRequestText(ref) {
2743
+ return fileHandleText(ref, this.fileReadPath(ref));
2744
+ }
2745
+ detachedModalities(modalities) {
2746
+ return modalities === undefined ? undefined : [...modalities];
2747
+ }
2748
+ async listModels(provider) {
2749
+ const models = await this.registration(provider).adapter.listModels(provider);
2750
+ const seen = /* @__PURE__ */ new Set;
2751
+ return models.map((model) => {
2752
+ if (typeof model.provider !== "string" || model.provider !== provider || typeof model.id !== "string" || model.id.length === 0 || typeof model.name !== "string" || model.name.length === 0 || model.description !== undefined && typeof model.description !== "string" || seen.has(model.id))
2753
+ throw new LlmError(`adapter returned invalid or duplicate model metadata for provider "${provider}"`, "INVALID_CATALOG");
2754
+ seen.add(model.id);
2755
+ const inputModalities = this.detachedModalities(model.inputModalities);
2756
+ return {
2757
+ provider: model.provider,
2758
+ id: model.id,
2759
+ name: model.name,
2760
+ ...model.description === undefined ? {} : { description: model.description },
2761
+ ...inputModalities === undefined ? {} : { inputModalities }
2762
+ };
2763
+ });
2764
+ }
2765
+ async resolveModelInfo(provider, model, signal) {
2766
+ return this.resolveModelInfoFor(this.registration(provider), model, signal);
2767
+ }
2768
+ async resolveModelInfoFor(registration, model, signal) {
2769
+ const resolved = await registration.adapter.resolveModel(registration.provider.id, model, signal);
2770
+ return this.normalizeModelInfo(registration, model, resolved);
2771
+ }
2772
+ normalizeModelInfo(registration, model, resolved) {
2773
+ const provider = registration.provider.id;
2774
+ if (typeof resolved.provider !== "string" || resolved.provider !== provider || typeof resolved.id !== "string" || resolved.id !== model || typeof resolved.name !== "string" || resolved.name.length === 0 || resolved.description !== undefined && typeof resolved.description !== "string")
2775
+ throw new LlmError(`adapter returned invalid exact model metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_INFO");
2776
+ const context = resolved.context;
2777
+ if (context !== undefined && (!Number.isInteger(context.contextWindow) || context.contextWindow <= 0))
2778
+ throw new LlmError(`adapter returned invalid context metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_CONTEXT");
2779
+ const inputModalities = this.detachedModalities(resolved.inputModalities);
2780
+ const systemPromptUpdate = resolved.systemPromptUpdate;
2781
+ if (systemPromptUpdate !== undefined && systemPromptUpdate !== "in-history")
2782
+ throw new LlmError(`adapter returned invalid system prompt update mode for provider "${provider}" model "${model}"`, "INVALID_MODEL_INFO");
2783
+ const toolUpdate = resolved.toolUpdate;
2784
+ if (toolUpdate !== undefined && toolUpdate !== "in-history" && toolUpdate !== "addition-only")
2785
+ throw new LlmError(`adapter returned invalid tool update mode for provider "${provider}" model "${model}"`, "INVALID_MODEL_INFO");
2786
+ const defaultMaxTokens = resolved.defaultMaxTokens;
2787
+ if (defaultMaxTokens !== undefined && (!Number.isSafeInteger(defaultMaxTokens) || defaultMaxTokens <= 0))
2788
+ throw new LlmError(`adapter returned invalid default maxTokens for provider "${provider}" model "${model}"`, "INVALID_MODEL_MAX_TOKENS");
2789
+ const info = {
2790
+ provider,
2791
+ id: model,
2792
+ name: resolved.name,
2793
+ ...resolved.description === undefined ? {} : { description: resolved.description },
2794
+ ...inputModalities === undefined ? {} : { inputModalities },
2795
+ ...context === undefined ? {} : { context: { contextWindow: context.contextWindow } },
2796
+ ...defaultMaxTokens === undefined ? {} : { defaultMaxTokens },
2797
+ ...resolved.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: resolved.systemPromptUpdate },
2798
+ ...resolved.toolUpdate === undefined ? {} : { toolUpdate: resolved.toolUpdate }
2799
+ };
2800
+ const reasoning = resolved.reasoning;
2801
+ if (reasoning === undefined)
2802
+ return info;
2803
+ if (reasoning.efforts.length === 0)
2804
+ throw new LlmError(`adapter returned invalid reasoning metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
2805
+ const seen = /* @__PURE__ */ new Set;
2806
+ const efforts = reasoning.efforts.map((effort) => {
2807
+ if (typeof effort.id !== "string" || effort.id.length === 0 || typeof effort.name !== "string" || effort.name.length === 0 || effort.description !== undefined && typeof effort.description !== "string" || seen.has(effort.id))
2808
+ throw new LlmError(`adapter returned invalid or duplicate reasoning effort metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
2809
+ seen.add(effort.id);
2810
+ return {
2811
+ id: effort.id,
2812
+ name: effort.name,
2813
+ ...effort.description === undefined ? {} : { description: effort.description }
2814
+ };
2815
+ });
2816
+ if (reasoning.defaultEffort !== undefined && !seen.has(reasoning.defaultEffort))
2817
+ throw new LlmError(`adapter returned an unknown default reasoning effort for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
2818
+ return {
2819
+ ...info,
2820
+ reasoning: {
2821
+ efforts,
2822
+ ...reasoning.defaultEffort === undefined ? {} : { defaultEffort: reasoning.defaultEffort }
2823
+ }
2824
+ };
2825
+ }
2826
+ async resolveCallConfig(config, signal) {
2827
+ return (await this.resolveCallFor(this.registration(config.provider), config, signal)).config;
2828
+ }
2829
+ async resolveCallFor(registration, config, signal) {
2830
+ const info = await this.resolveModelInfoFor(registration, config.model, signal);
2831
+ return this.resolveCallWithInfo(config, info);
2832
+ }
2833
+ resolveCallWithInfo(config, info) {
2834
+ const defaulted = config.maxTokens === undefined && info.defaultMaxTokens !== undefined ? {
2835
+ ...config,
2836
+ maxTokens: info.defaultMaxTokens
2837
+ } : config;
2838
+ const reasoning = info.reasoning;
2839
+ const requested = defaulted.reasoningEffort;
2840
+ let resolvedConfig = defaulted;
2841
+ if (reasoning === undefined) {
2842
+ if (requested !== undefined)
2843
+ throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${requested}"`, "UNSUPPORTED_REASONING_EFFORT");
2844
+ } else {
2845
+ const effective = requested ?? reasoning.defaultEffort;
2846
+ if (effective !== undefined) {
2847
+ if (!reasoning.efforts.some((effort) => effort.id === effective))
2848
+ throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${effective}"`, "UNSUPPORTED_REASONING_EFFORT");
2849
+ if (requested !== effective)
2850
+ resolvedConfig = {
2851
+ ...defaulted,
2852
+ reasoningEffort: effective
2853
+ };
2854
+ }
2855
+ }
2856
+ return {
2857
+ config: resolvedConfig,
2858
+ ...info.context === undefined ? {} : { context: info.context },
2859
+ modelInfo: info
2860
+ };
2861
+ }
2862
+ async prepareCall(config, signal) {
2863
+ const registration = this.registration(config.provider);
2864
+ const adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal);
2865
+ const modelInfo = this.normalizeModelInfo(registration, config.model, adapterCall.model);
2866
+ const resolved = this.resolveCallWithInfo(config, modelInfo);
2867
+ const resolvedConfig = deepFreeze(structuredClone(resolved.config));
2868
+ const context = resolved.context === undefined ? undefined : deepFreeze(structuredClone(resolved.context));
2869
+ const adapterDefaults = deepFreeze({
2870
+ ...config.reasoningEffort === undefined && resolvedConfig.reasoningEffort !== undefined ? { reasoningEffort: true } : {},
2871
+ ...config.maxTokens === undefined && resolvedConfig.maxTokens !== undefined ? { maxTokens: true } : {}
2872
+ });
2873
+ let dispatched = false;
2874
+ return Object.freeze({
2875
+ config: resolvedConfig,
2876
+ retryPolicy: registration.retryPolicy,
2877
+ adapterDefaults,
2878
+ ...context === undefined ? {} : { context },
2879
+ ...modelInfo.inputModalities === undefined ? {} : { inputModalities: Object.freeze([...modelInfo.inputModalities]) },
2880
+ ...modelInfo.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: modelInfo.systemPromptUpdate },
2881
+ ...modelInfo.toolUpdate === undefined ? {} : { toolUpdate: modelInfo.toolUpdate },
2882
+ stream: (options) => {
2883
+ if (dispatched)
2884
+ throw new LlmError("a prepared LLM call can only be dispatched once", "INVALID_PREPARED_CALL");
2885
+ if (!callConfigEquals(options, resolvedConfig))
2886
+ throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
2887
+ dispatched = true;
2888
+ return this.streamWithRegistration(options, {
2889
+ registration,
2890
+ config: resolvedConfig,
2891
+ modelInfo,
2892
+ dispatch: (options) => adapterCall.stream(options)
2893
+ });
2894
+ }
2895
+ });
2896
+ }
2897
+ registration(provider) {
2898
+ const registration = this.adapters.get(provider);
2899
+ if (!registration)
2900
+ throw new LlmError(`no adapter registered for provider "${provider}"`, "NO_ADAPTER");
2901
+ return registration;
2902
+ }
2903
+ forAdapter(options, adapter) {
2904
+ const messages = options.messages.map((message) => {
2905
+ if (message.role !== "assistant")
2906
+ return message;
2907
+ const source = message.source;
2908
+ if (source.replayState === undefined)
2909
+ return message;
2910
+ if (this.adapters.get(source.provider)?.adapter === adapter)
2911
+ return message;
2912
+ return freezeMessage({
2913
+ ...message,
2914
+ source: {
2915
+ kind: "model",
2916
+ provider: source.provider,
2917
+ model: source.model
2918
+ }
2919
+ });
2920
+ });
2921
+ if (messages.every((message, index) => message === options.messages[index]))
2922
+ return options;
2923
+ const filtered = {
2924
+ ...options,
2925
+ messages
2926
+ };
2927
+ return Object.isFrozen(options) ? deepFreeze(filtered) : filtered;
2928
+ }
2929
+ fileReadPath(ref) {
2930
+ let hostPath;
2931
+ try {
2932
+ hostPath = this.ctx.get("attachments")?.fileHostPath(ref);
2933
+ } catch {
2934
+ return;
2935
+ }
2936
+ if (hostPath === undefined)
2937
+ return;
2938
+ return this.ctx.get("fs")?.processPathFromHostPath(hostPath);
2939
+ }
2940
+ async* adapterStream(options, prepared) {
2941
+ let iterator;
2942
+ try {
2943
+ const registration = prepared?.registration ?? this.registration(options.provider);
2944
+ const adapter = registration.adapter;
2945
+ let modelInfo;
2946
+ let resolvedConfig;
2947
+ let dispatch;
2948
+ if (prepared === undefined) {
2949
+ const adapterCall = await adapter.prepareCall(options.provider, options.model, options.signal);
2950
+ modelInfo = this.normalizeModelInfo(registration, options.model, adapterCall.model);
2951
+ resolvedConfig = this.resolveCallWithInfo(options, modelInfo).config;
2952
+ dispatch = (options) => adapterCall.stream(options);
2953
+ } else {
2954
+ modelInfo = prepared.modelInfo;
2955
+ resolvedConfig = prepared.config;
2956
+ dispatch = prepared.dispatch;
2957
+ }
2958
+ if (prepared !== undefined && !callConfigEquals(options, resolvedConfig))
2959
+ throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
2960
+ const resolvedOptions = callConfigEquals(options, resolvedConfig) ? options : Object.isFrozen(options) ? deepFreeze({
2961
+ ...options,
2962
+ ...resolvedConfig
2963
+ }) : {
2964
+ ...options,
2965
+ ...resolvedConfig
2966
+ };
2967
+ let projectedMessages = resolvedOptions.messages;
2968
+ if (projectedMessages.some((message) => contentHasFile(message.content)))
2969
+ projectedMessages = projectFilesToText(projectedMessages, (ref) => this.fileReadPath(ref));
2970
+ if (modelInfo.inputModalities !== undefined && !modelInfo.inputModalities.includes("image") && projectedMessages.some((message) => contentHasImage(message.content)))
2971
+ projectedMessages = projectImagesForTextModel(projectedMessages);
2972
+ const projectedTools = projectToolUpdates(projectedMessages, resolvedOptions.tools, modelInfo.toolUpdate, resolvedOptions.toolHistory);
2973
+ projectedMessages = projectedTools.messages;
2974
+ let projectedOptions = resolvedOptions;
2975
+ if (projectedMessages !== resolvedOptions.messages || projectedTools.tools !== resolvedOptions.tools) {
2976
+ projectedOptions = {
2977
+ ...resolvedOptions,
2978
+ messages: projectedMessages,
2979
+ ...projectedTools.tools === undefined ? {} : { tools: projectedTools.tools }
2980
+ };
2981
+ if (Object.isFrozen(resolvedOptions))
2982
+ deepFreeze(projectedOptions);
2983
+ }
2984
+ iterator = dispatch(this.forAdapter(projectedOptions, adapter))[Symbol.asyncIterator]();
2985
+ } catch (error) {
2986
+ yield adapterFailureChunk(error, options.signal);
2987
+ return;
2988
+ }
2989
+ let completed = false;
2990
+ try {
2991
+ while (true) {
2992
+ let item;
2993
+ try {
2994
+ const next = await iterator.next();
2995
+ item = next.done ? { done: true } : {
2996
+ done: false,
2997
+ value: next.value
2998
+ };
2999
+ } catch (error) {
3000
+ completed = true;
3001
+ yield adapterFailureChunk(error, options.signal);
3002
+ return;
3003
+ }
3004
+ if (item.done) {
3005
+ completed = true;
3006
+ return;
3007
+ }
3008
+ yield item.value;
3009
+ }
3010
+ } finally {
3011
+ if (!completed) {
3012
+ const close = iterator.return?.bind(iterator);
3013
+ if (close)
3014
+ await close();
3015
+ }
3016
+ }
3017
+ }
3018
+ stream(options) {
3019
+ return this.streamWithRegistration(options);
3020
+ }
3021
+ streamWithRegistration(options, prepared) {
3022
+ return this.ctx.waterfall(this, "llm/stream", options, () => this.adapterStream(options, prepared));
3023
+ }
3024
+ };
3025
+ })();
3026
+ function adapterFailureChunk(error, signal) {
3027
+ const failure = normalizeLlmFailure(error);
3028
+ return {
3029
+ type: "finish",
3030
+ reason: signal?.aborted || failure.code === "ABORTED" ? {
3031
+ kind: "aborted",
3032
+ failure
3033
+ } : {
3034
+ kind: "error",
3035
+ failure
3036
+ }
3037
+ };
3038
+ }
3039
+
3040
+ // src/todo-nudge.ts
3041
+ var NUDGE_TEXT = "委派结果已返回:立刻 todo_write 回写对应项状态(整表覆盖,保留未动项),再继续下一步。";
3042
+ var MAX_PER_SESSION = 2;
3043
+ var nudged = new WeakMap;
3044
+ function maybeDeferTodoNudge(exec) {
3045
+ try {
3046
+ if (typeof exec?.deferContext !== "function")
3047
+ return;
3048
+ const key = exec.agent ?? exec;
3049
+ if (key === null || typeof key !== "object")
3050
+ return;
3051
+ const used = nudged.get(key) ?? 0;
3052
+ if (used >= MAX_PER_SESSION)
3053
+ return;
3054
+ nudged.set(key, used + 1);
3055
+ exec.deferContext(createUserMessage({
3056
+ content: [{ type: "text", text: NUDGE_TEXT }],
3057
+ source: { kind: "cohub-todo-nudge" }
3058
+ }));
3059
+ } catch {}
3060
+ }
3061
+
1843
3062
  // src/delegate.ts
1844
3063
  var PARALLEL_TOOL_DISCIPLINE = "【并行工具纪律】① 同一条消息内一次性发起全部独立只读查询,不要发一个等一个。" + "② 真并发的只读工具:read、read_image、web_search、web_fetch、subagent。" + "注意 glob、grep 虽然只读但不可并发(会被串行执行),别指望它们并行。" + "③ 可并发调用必须连续相邻,中间不要插 bash、edit、write、grep 等串行调用," + "否则其后调用另起一组、并发度归零([read, bash, read] 并发度=1,[read, read, read, bash] 并发度=3)。" + "④ 不要依赖平台真并发:需要 N 个互不依赖的子任务时,优先用 delegate_batch" + "(内部 Promise.allSettled,不依赖 agent loop 调度;该工具可用时)。";
1845
3064
  var DELEGATE_PERSONA = "你是被委派的专职代理:严格遵循任务消息中的角色定义、关键约束、输出格式与工具指令,并完成末尾的具体任务。" + "你的首条用户消息(下方任务书)已含 `--- 你的具体任务 ---` 分隔符,即身份判据成立:不要调用 skill 工具加载 co-orchestrator 技能——技能指令已由 brief 注入。" + PARALLEL_TOOL_DISCIPLINE;
@@ -2951,6 +4170,7 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
2951
4170
  }
2952
4171
  }
2953
4172
  const foregroundText = await runAttempts(exec.signal);
4173
+ maybeDeferTodoNudge(exec);
2954
4174
  if (args.background === true && bgFallbackReason !== undefined) {
2955
4175
  return foregroundText + `
2956
4176
 
@@ -3451,6 +4671,7 @@ ${r.result}
3451
4671
  }).text;
3452
4672
  ctx?.logger?.warn?.("[cohub budget] batch:total:拼装结果 " + fullChars + " 字符 ≈ " + approxTokens(fullChars) + " tokens 超过总预算 " + budget.batchTotalMaxChars + " 字符,已裁剪;各任务全文见各自的 locator。仅告警,不阻断。");
3453
4673
  }
4674
+ maybeDeferTodoNudge(exec);
3454
4675
  return statsLine + output;
3455
4676
  }
3456
4677
  });
@@ -4866,92 +6087,96 @@ function registerReviewCommand(ctx) {
4866
6087
  }
4867
6088
 
4868
6089
  // src/index.ts
4869
- var Councillor = z.object({
4870
- name: z.string(),
4871
- provider: z.string(),
4872
- model: z.string(),
4873
- prompt: z.string()
6090
+ function volatileSchema(schema) {
6091
+ const fn = schema.volatile;
6092
+ return typeof fn === "function" ? fn.call(schema) : schema;
6093
+ }
6094
+ var Councillor = z2.object({
6095
+ name: z2.string(),
6096
+ provider: z2.string(),
6097
+ model: z2.string(),
6098
+ prompt: z2.string()
4874
6099
  });
4875
- var SkillRoute = z.object({
4876
- name: z.string(),
4877
- provider: z.string(),
4878
- model: z.string(),
4879
- maxTokens: z.number(),
4880
- reasoningEffort: z.string().description("推理强度(如 low/medium/high;留空则按模型默认档/继承规则)")
6100
+ var SkillRoute = z2.object({
6101
+ name: z2.string(),
6102
+ provider: z2.string(),
6103
+ model: z2.string(),
6104
+ maxTokens: z2.number(),
6105
+ reasoningEffort: z2.string().description("推理强度(如 low/medium/high;留空则按模型默认档/继承规则)")
4881
6106
  });
4882
- var EnvContractConfig = z.object({
4883
- enabled: z.boolean().default(true),
4884
- text: z.string()
6107
+ var EnvContractConfig = z2.object({
6108
+ enabled: z2.boolean().default(true),
6109
+ text: z2.string()
4885
6110
  }).default({});
4886
- var StallDetector = z.object({
4887
- enabled: z.boolean().default(false),
4888
- consecutiveErrors: z.number().default(3),
4889
- idleMs: z.number().default(180000),
4890
- reasoningWithoutAction: z.number().default(50),
4891
- loopCount: z.number().default(3),
4892
- graceMs: z.number().default(30000),
4893
- recoverable: z.boolean().default(true)
6111
+ var StallDetector = z2.object({
6112
+ enabled: z2.boolean().default(false),
6113
+ consecutiveErrors: z2.number().default(3),
6114
+ idleMs: z2.number().default(180000),
6115
+ reasoningWithoutAction: z2.number().default(50),
6116
+ loopCount: z2.number().default(3),
6117
+ graceMs: z2.number().default(30000),
6118
+ recoverable: z2.boolean().default(true)
4894
6119
  }).default({});
4895
- var DelegateRetry = z.object({
4896
- maxRetries: z.number().default(0),
4897
- retryDelayMs: z.number().default(1000),
4898
- retryableReasons: z.array(z.string()).default(["aborted"]),
6120
+ var DelegateRetry = z2.object({
6121
+ maxRetries: z2.number().default(0),
6122
+ retryDelayMs: z2.number().default(1000),
6123
+ retryableReasons: z2.array(z2.string()).default(["aborted"]),
4899
6124
  stall: StallDetector
4900
6125
  }).default({});
4901
- var EnvContractFacts = z.object({
4902
- moduleLoading: z.string().default("unknown"),
4903
- topLevelAwait: z.boolean().default(true),
4904
- wallClockLimitMs: z.number().default(600000),
4905
- hasJobTracking: z.boolean().default(false)
6126
+ var EnvContractFacts = z2.object({
6127
+ moduleLoading: z2.string().default("unknown"),
6128
+ topLevelAwait: z2.boolean().default(true),
6129
+ wallClockLimitMs: z2.number().default(600000),
6130
+ hasJobTracking: z2.boolean().default(false)
4906
6131
  });
4907
- var EnvSignatures = z.object({
4908
- use: z.union(["auto", "off", "manual"]).default("auto"),
4909
- ttlMs: z.number().default(604800000),
4910
- confirmCount: z.number().default(2),
6132
+ var EnvSignatures = z2.object({
6133
+ use: z2.union(["auto", "off", "manual"]).default("auto"),
6134
+ ttlMs: z2.number().default(604800000),
6135
+ confirmCount: z2.number().default(2),
4911
6136
  contract: EnvContractFacts,
4912
- errorCategories: z.array(z.string()).default(DEFAULT_ERROR_CATEGORIES)
6137
+ errorCategories: z2.array(z2.string()).default(DEFAULT_ERROR_CATEGORIES)
4913
6138
  }).default({});
4914
- var ScheduleConfig = z.object({
4915
- maxParallelBatch: z.number().default(3),
4916
- wallClockBudgetMs: z.number().default(WALL_CLOCK_BUDGET_MS)
6139
+ var ScheduleConfig = z2.object({
6140
+ maxParallelBatch: z2.number().default(3),
6141
+ wallClockBudgetMs: z2.number().default(WALL_CLOCK_BUDGET_MS)
4917
6142
  }).default({});
4918
- var ResultBudgetConfig = z.object({
4919
- enabled: z.boolean().default(true),
4920
- maxChars: z.number().default(DEFAULT_DELEGATE_RESULT_CHARS),
4921
- partialMaxChars: z.number().default(DEFAULT_PARTIAL_BUDGET_CHARS),
4922
- batchTaskMaxChars: z.number().default(DEFAULT_BATCH_TASK_CHARS),
4923
- batchTotalMaxChars: z.number().default(DEFAULT_BATCH_TOTAL_CHARS),
4924
- warnMessageTokens: z.number().default(DEFAULT_CONTEXT_WARN_TOKENS)
6143
+ var ResultBudgetConfig = z2.object({
6144
+ enabled: z2.boolean().default(true),
6145
+ maxChars: z2.number().default(DEFAULT_DELEGATE_RESULT_CHARS),
6146
+ partialMaxChars: z2.number().default(DEFAULT_PARTIAL_BUDGET_CHARS),
6147
+ batchTaskMaxChars: z2.number().default(DEFAULT_BATCH_TASK_CHARS),
6148
+ batchTotalMaxChars: z2.number().default(DEFAULT_BATCH_TOTAL_CHARS),
6149
+ warnMessageTokens: z2.number().default(DEFAULT_CONTEXT_WARN_TOKENS)
4925
6150
  }).default({});
4926
- var DelegateBackgroundConfig = z.object({
4927
- enabled: z.boolean().default(false),
4928
- defaultFor: z.array(z.string()).default([])
6151
+ var DelegateBackgroundConfig = z2.object({
6152
+ enabled: z2.boolean().default(false),
6153
+ defaultFor: z2.array(z2.string()).default([])
4929
6154
  }).default({});
4930
- var ToolFilterConfig = z.object({
4931
- enabled: z.boolean().default(true)
6155
+ var ToolFilterConfig = z2.object({
6156
+ enabled: z2.boolean().default(true)
4932
6157
  }).default({});
4933
- var DelegateSubagentPresetConfig = z.object({
4934
- enabled: z.boolean().default(true)
6158
+ var DelegateSubagentPresetConfig = z2.object({
6159
+ enabled: z2.boolean().default(true)
4935
6160
  }).default({});
4936
6161
  var name = "cohub";
4937
6162
  var inject = ["systemPrompt", "skills", "tools", "sessionProjections", "llm", "subagents"];
4938
- var Config = z.object({
4939
- councillors: z.array(Councillor).default([]),
4940
- councilTimeoutMs: z.number().default(COUNCIL_TIMEOUT_MS),
4941
- councilProvider: z.string().default("spawn"),
4942
- skills: z.array(SkillRoute).default([]).volatile(),
6163
+ var Config = z2.object({
6164
+ councillors: z2.array(Councillor).default([]),
6165
+ councilTimeoutMs: z2.number().default(COUNCIL_TIMEOUT_MS),
6166
+ councilProvider: z2.string().default("spawn"),
6167
+ skills: volatileSchema(z2.array(SkillRoute).default([])),
4943
6168
  delegateEnvContract: EnvContractConfig,
4944
- delegateRetry: DelegateRetry.volatile(),
6169
+ delegateRetry: volatileSchema(DelegateRetry),
4945
6170
  envSignatures: EnvSignatures,
4946
- schedule: ScheduleConfig.volatile(),
4947
- resultBudget: ResultBudgetConfig.volatile(),
4948
- delegateBackground: DelegateBackgroundConfig.volatile(),
6171
+ schedule: volatileSchema(ScheduleConfig),
6172
+ resultBudget: volatileSchema(ResultBudgetConfig),
6173
+ delegateBackground: volatileSchema(DelegateBackgroundConfig),
4949
6174
  toolFilter: ToolFilterConfig,
4950
- delegateSubagentPreset: DelegateSubagentPresetConfig.volatile(),
4951
- installPresets: z.boolean().default(true)
6175
+ delegateSubagentPreset: volatileSchema(DelegateSubagentPresetConfig),
6176
+ installPresets: z2.boolean().default(true)
4952
6177
  });
4953
- var CohubSettingsSchema = z.object({
4954
- skills: z.array(SkillRoute).default([]),
6178
+ var CohubSettingsSchema = z2.object({
6179
+ skills: z2.array(SkillRoute).default([]),
4955
6180
  schedule: ScheduleConfig,
4956
6181
  delegateRetry: DelegateRetry,
4957
6182
  resultBudget: ResultBudgetConfig,