dsh-submodel 0.3.0 → 0.4.1
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/README.en.md +94 -96
- package/README.md +87 -79
- package/client.js +474 -0
- package/docs/plugin-detail.md +5 -0
- package/lib/config.js +164 -0
- package/lib/delegation.js +49 -51
- package/lib/index.js +42 -131
- package/lib/policy.js +110 -43
- package/lib/setup.js +95 -184
- package/lib/watchdog.js +577 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +19 -4
package/lib/watchdog.js
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { readLive, readModelGroups, readWatchdog, CONFIG_ENTRY } from './config.js';
|
|
3
|
+
import { HOST_SELECTION_ENTRY_ID, routeKey } from './policy.js';
|
|
4
|
+
|
|
5
|
+
const LIMITS = Object.freeze({ pending: 60_000, release: 30_000, attempt: 30 * 60_000 });
|
|
6
|
+
const RETRY_CODES = new Set(['RATE_LIMIT', 'TIMEOUT', 'TRANSPORT', 'SERVER']);
|
|
7
|
+
const MIN_HOST_RETRIES = 5;
|
|
8
|
+
const USAGE_KEYS = ['uncachedInputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens'];
|
|
9
|
+
const NAME = /^[a-z][a-z0-9-]{0,31}$/u;
|
|
10
|
+
const REMINDER = '请尽快收尾,优先交回已有结论、证据和待核实项。';
|
|
11
|
+
const NOTICE_SOURCE = 'dsh-submodel-watchdog';
|
|
12
|
+
const samePair = (left, right) => typeof left?.provider === 'string' && left.provider !== '' &&
|
|
13
|
+
typeof left.model === 'string' && left.model !== '' && routeKey(left) === routeKey(right);
|
|
14
|
+
const endKey = ({ id, runId }) => JSON.stringify([id, runId]);
|
|
15
|
+
const shortId = () => randomUUID().slice(0, 12).replaceAll('-', '');
|
|
16
|
+
|
|
17
|
+
export function sumUsage(value) {
|
|
18
|
+
if (!value) return undefined;
|
|
19
|
+
let total = 0;
|
|
20
|
+
for (const key of USAGE_KEYS) {
|
|
21
|
+
const part = value[key];
|
|
22
|
+
if (!Number.isSafeInteger(part) || part < 0) return undefined;
|
|
23
|
+
total += part;
|
|
24
|
+
}
|
|
25
|
+
return Number.isSafeInteger(total) ? total : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function includesContent(blocks) {
|
|
29
|
+
return Array.isArray(blocks) && blocks.some(block => block?.type !== 'text' || Boolean(block.text?.trim()));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function observeAssistant(attempt, event) {
|
|
33
|
+
const { usage, stream, message, turn } = event.data;
|
|
34
|
+
if (turn !== attempt.turn) {
|
|
35
|
+
attempt.incomplete = true;
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (message?.source?.kind === 'model' && !samePair(attempt.route, message.source)) attempt.routeChanged = true;
|
|
39
|
+
if (includesContent(message?.content)) attempt.hasOutput = true;
|
|
40
|
+
let streamedUsage;
|
|
41
|
+
let finish;
|
|
42
|
+
for (const record of Array.isArray(stream) ? stream : []) {
|
|
43
|
+
if (record.type === 'chunk' && record.chunk?.type === 'finish') finish = record.chunk.reason?.kind;
|
|
44
|
+
if (record.type === 'chunk' && record.chunk?.type === 'usage') streamedUsage = record.chunk.usage;
|
|
45
|
+
if ((record.type === 'text-chunks' && record.texts?.some(text => text.trim())) ||
|
|
46
|
+
record.type === 'tool-call-chunks' ||
|
|
47
|
+
(record.type === 'reasoning-chunks' && record.texts?.some(text => text.trim())) ||
|
|
48
|
+
(record.type === 'chunk' && (
|
|
49
|
+
(['text-delta', 'reasoning-delta'].includes(record.chunk?.type) && record.chunk.text?.trim()) ||
|
|
50
|
+
record.chunk?.type === 'tool-call-delta' ||
|
|
51
|
+
(record.chunk?.type === 'block-start' && record.chunk.blockType === 'tool-call') ||
|
|
52
|
+
(record.chunk?.type === 'block-end' && record.chunk.block && includesContent([record.chunk.block]))
|
|
53
|
+
))) attempt.hasOutput = true;
|
|
54
|
+
}
|
|
55
|
+
// A final reply can be durable while its turn still reports running. Inserting
|
|
56
|
+
// input there would extend the turn and start another model request.
|
|
57
|
+
attempt.waitForProgress = event.type !== 'assistant/message' || event.data.interrupted === true ||
|
|
58
|
+
finish === 'max-tokens' || !message?.content?.some(block => block.type === 'tool-call');
|
|
59
|
+
const reported = usage ?? streamedUsage;
|
|
60
|
+
const total = reported == null ? undefined : sumUsage({
|
|
61
|
+
uncachedInputTokens: reported.inputTokens,
|
|
62
|
+
outputTokens: reported.outputTokens,
|
|
63
|
+
cacheReadTokens: reported.cacheReadTokens === undefined ? 0 : reported.cacheReadTokens,
|
|
64
|
+
cacheWriteTokens: reported.cacheWriteTokens === undefined ? 0 : reported.cacheWriteTokens,
|
|
65
|
+
});
|
|
66
|
+
// DSH rc.5 can emit the same all-zero chunk for a missing provider sample.
|
|
67
|
+
// A previous step's usage cannot make the current failed attempt eligible.
|
|
68
|
+
attempt.reportedUsage = total > 0 ? total : undefined;
|
|
69
|
+
attempt.lastRequest = { step: event.data.step, seq: event.seq, usage: attempt.reportedUsage };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function notice(agent, text, id = randomUUID()) {
|
|
73
|
+
agent.inject({
|
|
74
|
+
id, role: 'user', content: [{ type: 'text', text }],
|
|
75
|
+
source: { kind: NOTICE_SOURCE, form: 'notice', summary: text.slice(0, 120) },
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function laterModels(groups, tier, route) {
|
|
80
|
+
const rows = tier === 'expert' ? groups.experts : groups.executors;
|
|
81
|
+
const position = rows.findIndex(row => samePair(route, row));
|
|
82
|
+
return position < 0 ? [] : rows.slice(position + 1).map(({ provider, model }) => ({ provider, model }));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 改派目标在所属组里的配置档位;未配置返回 undefined(交给模型默认)。 */
|
|
86
|
+
function candidateRowEffort(groups, tier, route) {
|
|
87
|
+
const rows = tier === 'expert' ? groups.experts : groups.executors;
|
|
88
|
+
const row = rows.find(item => samePair(item, route));
|
|
89
|
+
return typeof row?.reasoningEffort === 'string' && row.reasoningEffort !== '' ? row.reasoningEffort : undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function sameGroupOrder(frozen, current, tier) {
|
|
93
|
+
const field = tier === 'expert' ? 'experts' : 'executors';
|
|
94
|
+
const before = frozen[field];
|
|
95
|
+
const after = current?.[field];
|
|
96
|
+
return before.length === after?.length && before.every((row, index) => samePair(row, after[index]));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Pair the host's scheduled and started records in one run and one step. */
|
|
100
|
+
function observeRetry(attempt, event) {
|
|
101
|
+
const data = event.data;
|
|
102
|
+
const state = attempt.hostRetry ??= { started: 0 };
|
|
103
|
+
if (state.invalid) return;
|
|
104
|
+
if (data.turn !== attempt.turn || data.step !== attempt.step || data.retry !== state.started + 1 ||
|
|
105
|
+
typeof data.retryId !== 'string' || data.retryId === '') {
|
|
106
|
+
state.invalid = true;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (event.type === 'llm/retry') {
|
|
110
|
+
const sample = attempt.lastRequest;
|
|
111
|
+
// A missing sample leaves cumulative usage unknown, even if later retries report usage.
|
|
112
|
+
if (state.pending || data.provider !== attempt.route.provider || data.mode !== 'normal' ||
|
|
113
|
+
!Number.isSafeInteger(data.maxRetries) || data.maxRetries < MIN_HOST_RETRIES || data.retry > data.maxRetries ||
|
|
114
|
+
typeof data.policyKey !== 'string' || data.policyKey === '' ||
|
|
115
|
+
(state.started > 0 && (state.id !== data.retryId || state.policyKey !== data.policyKey || state.limit !== data.maxRetries)) ||
|
|
116
|
+
!sample || sample.step !== data.step || sample.seq <= (state.lastStart ?? -1) || sample.usage === undefined) {
|
|
117
|
+
state.invalid = true;
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
state.id = data.retryId;
|
|
121
|
+
state.policyKey = data.policyKey;
|
|
122
|
+
state.limit = data.maxRetries;
|
|
123
|
+
state.pending = true;
|
|
124
|
+
} else if (state.pending && state.id === data.retryId) {
|
|
125
|
+
state.pending = false;
|
|
126
|
+
state.started = data.retry;
|
|
127
|
+
state.lastStart = event.seq;
|
|
128
|
+
} else {
|
|
129
|
+
state.invalid = true;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function hostRetriesExhausted(attempt) {
|
|
134
|
+
const { hostRetry, lastRequest, failure, step } = attempt;
|
|
135
|
+
return !!hostRetry && !hostRetry.invalid && !hostRetry.pending && hostRetry.started >= MIN_HOST_RETRIES &&
|
|
136
|
+
hostRetry.started === hostRetry.limit && failure.retryLimit === hostRetry.limit &&
|
|
137
|
+
lastRequest?.step === step && lastRequest.seq > hostRetry.lastStart && lastRequest.usage !== undefined;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function matchesEnd(attempt) {
|
|
141
|
+
return attempt.turn !== undefined && attempt.failure !== undefined &&
|
|
142
|
+
attempt.terminal?.stopReason === 'error' && attempt.terminal.turn === attempt.turn &&
|
|
143
|
+
attempt.failure.turn === attempt.turn && attempt.failure.step === attempt.step &&
|
|
144
|
+
attempt.failure.code === attempt.terminal.code && RETRY_CODES.has(attempt.failure.code) &&
|
|
145
|
+
!attempt.incomplete && !attempt.hasOutput && !attempt.routeChanged && !attempt.cancelled &&
|
|
146
|
+
attempt.initialId !== undefined && attempt.usage !== undefined &&
|
|
147
|
+
(!attempt.job.grouped || hostRetriesExhausted(attempt));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** One observer per eligible parent. Child observation uses the plugin context, not the parent scope. */
|
|
151
|
+
export function installWatchdog({ ctx, parent, config, nativeDefinition, modelGroups, logger = ctx.logger, clock = globalThis }) {
|
|
152
|
+
const projections = ctx.get('sessionProjections');
|
|
153
|
+
const agents = ctx.get('agents');
|
|
154
|
+
const subagents = ctx.get('subagents');
|
|
155
|
+
if (!projections?.snapshot || !projections?.onChanged || !agents?.get || !subagents?.namesOf) return undefined;
|
|
156
|
+
const jobs = new Set();
|
|
157
|
+
const pending = new Map();
|
|
158
|
+
const runs = new Map();
|
|
159
|
+
const children = new WeakMap();
|
|
160
|
+
const sessions = new WeakMap();
|
|
161
|
+
const released = new Map();
|
|
162
|
+
const listeners = [];
|
|
163
|
+
let closed = false;
|
|
164
|
+
let parentSignal;
|
|
165
|
+
let stopListeningParent;
|
|
166
|
+
|
|
167
|
+
function onAbort(signal, callback) {
|
|
168
|
+
if (!signal) return () => {};
|
|
169
|
+
if (signal.aborted) callback();
|
|
170
|
+
else signal.addEventListener('abort', callback, { once: true });
|
|
171
|
+
return () => signal.removeEventListener('abort', callback);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function liveParent() {
|
|
175
|
+
if (closed || agents.get(parent.id) !== parent || parent.ctx?.fiber?.uid === null) return false;
|
|
176
|
+
try { parent.ctx?.fiber?.assertActive?.(); }
|
|
177
|
+
catch { return false; }
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function valid(job) {
|
|
182
|
+
return jobs.has(job) && !job.controller.signal.aborted && !parentSignal?.aborted &&
|
|
183
|
+
liveParent() && readWatchdog(config).mode !== 'off';
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function stopTimer(record, key) {
|
|
187
|
+
if (record[key] !== undefined) clock.clearTimeout(record[key]);
|
|
188
|
+
record[key] = undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function report(text) {
|
|
192
|
+
if (!liveParent()) return;
|
|
193
|
+
try { notice(parent, text); }
|
|
194
|
+
catch { logger?.warn?.('dsh-submodel: could not deliver a monitoring notice'); }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function dropChild(attempt) {
|
|
198
|
+
if (attempt.child) {
|
|
199
|
+
children.delete(attempt.child);
|
|
200
|
+
sessions.delete(attempt.child.session);
|
|
201
|
+
}
|
|
202
|
+
attempt.child = undefined;
|
|
203
|
+
attempt.stopListeningChild?.();
|
|
204
|
+
attempt.stopListeningChild = undefined;
|
|
205
|
+
attempt.signal = undefined;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function unpend(attempt) {
|
|
209
|
+
const siblings = pending.get(attempt.name);
|
|
210
|
+
siblings?.delete(attempt);
|
|
211
|
+
if (siblings?.size === 0) pending.delete(attempt.name);
|
|
212
|
+
stopTimer(attempt, 'pendingTimer');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function dropAttempt(attempt) {
|
|
216
|
+
unpend(attempt);
|
|
217
|
+
if (attempt.key !== undefined) runs.delete(attempt.key);
|
|
218
|
+
if (released.get(attempt.id) === attempt) released.delete(attempt.id);
|
|
219
|
+
dropChild(attempt);
|
|
220
|
+
attempt.args = undefined;
|
|
221
|
+
stopTimer(attempt, 'attemptTimer');
|
|
222
|
+
stopTimer(attempt, 'releaseTimer');
|
|
223
|
+
stopTimer(attempt, 'graceTimer');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function clear(job) {
|
|
227
|
+
if (!jobs.delete(job)) return;
|
|
228
|
+
job.stopListeningCaller?.();
|
|
229
|
+
dropAttempt(job.attempt);
|
|
230
|
+
if (job.previous && job.previous !== job.attempt) dropAttempt(job.previous);
|
|
231
|
+
job.previous = undefined;
|
|
232
|
+
job.args = undefined;
|
|
233
|
+
job.controller.abort();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function scheduleAttempt(job, args, route, name) {
|
|
237
|
+
const attempt = { job, route, name, args: { ...args, name }, parentSeq: parent.session.seq, status: 'pending' };
|
|
238
|
+
job.attempt = attempt;
|
|
239
|
+
const siblings = pending.get(name) ?? new Set();
|
|
240
|
+
if (siblings.size > 0) {
|
|
241
|
+
// Keep reservations until their native receipts arrive or the deadline passes.
|
|
242
|
+
for (const previous of siblings) previous.ambiguous = true;
|
|
243
|
+
attempt.ambiguous = true;
|
|
244
|
+
}
|
|
245
|
+
siblings.add(attempt);
|
|
246
|
+
pending.set(name, siblings);
|
|
247
|
+
attempt.pendingTimer = clock.setTimeout(() => clear(job), LIMITS.pending);
|
|
248
|
+
attempt.attemptTimer = clock.setTimeout(() => {
|
|
249
|
+
if (valid(job)) report(`「${name}」的用量观察已到时限。请在子代理面板查看进度。`);
|
|
250
|
+
clear(job);
|
|
251
|
+
}, LIMITS.attempt);
|
|
252
|
+
return attempt;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function begin(args, route, tier, exec) {
|
|
256
|
+
const policy = readWatchdog(config);
|
|
257
|
+
if (!liveParent() || !tier || !samePair(route, route) || policy.mode === 'off' ||
|
|
258
|
+
!policy.tiers.includes(tier) || exec.signal?.aborted) return undefined;
|
|
259
|
+
const initial = { provider: route.provider, model: route.model };
|
|
260
|
+
const candidates = modelGroups ? laterModels(modelGroups, tier, initial)
|
|
261
|
+
: (readLive(config, 'fallbacks') ?? []).find(row => samePair(initial, row.primary))?.alternatives ?? [];
|
|
262
|
+
const job = {
|
|
263
|
+
id: shortId(), tier, policy: structuredClone(policy), initial, grouped: modelGroups !== undefined,
|
|
264
|
+
candidates: structuredClone(candidates), used: 0, total: 0,
|
|
265
|
+
args: structuredClone(args), controller: new AbortController(), budgetReached: false,
|
|
266
|
+
};
|
|
267
|
+
const name = typeof args.name === 'string' && NAME.test(args.name) && args.name !== 'lead' ? args.name : `sm-${job.id}`;
|
|
268
|
+
jobs.add(job);
|
|
269
|
+
const ticket = scheduleAttempt(job, args, initial, name);
|
|
270
|
+
job.stopListeningCaller = onAbort(exec.signal, () => clear(job));
|
|
271
|
+
return ticket;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function beginObservation(info) {
|
|
275
|
+
if (!info.local || info.provider !== 'spawn' || info.parentSessionId !== parent.id) return;
|
|
276
|
+
const previous = released.get(info.id);
|
|
277
|
+
if (previous?.runId !== info.runId && previous) clear(previous.job);
|
|
278
|
+
if (runs.has(endKey(info))) return;
|
|
279
|
+
const child = agents.get(info.id);
|
|
280
|
+
if (!child?.session || child.session.header?.parentSession !== parent.id) return;
|
|
281
|
+
let name;
|
|
282
|
+
try { name = subagents.namesOf(child).self; }
|
|
283
|
+
catch { return; }
|
|
284
|
+
const siblings = pending.get(name);
|
|
285
|
+
if (siblings?.size !== 1) return;
|
|
286
|
+
const [attempt] = siblings;
|
|
287
|
+
if (attempt.ambiguous || attempt.child || !valid(attempt.job)) return;
|
|
288
|
+
attempt.id = info.id;
|
|
289
|
+
attempt.runId = info.runId;
|
|
290
|
+
attempt.key = endKey(info);
|
|
291
|
+
attempt.child = child;
|
|
292
|
+
attempt.fromSeq = child.session.seq;
|
|
293
|
+
runs.set(attempt.key, attempt);
|
|
294
|
+
children.set(child, attempt);
|
|
295
|
+
sessions.set(child.session, attempt);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function stillWorking(attempt) {
|
|
299
|
+
return !attempt.waitForProgress && !attempt.cancelled && !attempt.incomplete && !attempt.routeChanged && !attempt.terminal &&
|
|
300
|
+
!!attempt.child && agents.get(attempt.id) === attempt.child && attempt.child.status === 'running' &&
|
|
301
|
+
attempt.signal && !attempt.signal.aborted && attempt.initialId && valid(attempt.job);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function sample(attempt) {
|
|
305
|
+
if (!attempt.child) return;
|
|
306
|
+
if (attempt.reportedUsage === undefined) {
|
|
307
|
+
attempt.usage = undefined;
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
let observed;
|
|
311
|
+
try { observed = sumUsage(projections.snapshot(attempt.child.session, ['tokenUsage']).values.tokenUsage); }
|
|
312
|
+
catch { /* Unavailable or invalid observations cannot authorize an action. */ }
|
|
313
|
+
if (observed === undefined || observed < attempt.reportedUsage) {
|
|
314
|
+
attempt.usage = undefined;
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
attempt.peak = Math.max(attempt.peak ?? 0, observed);
|
|
318
|
+
attempt.usage = attempt.peak;
|
|
319
|
+
const job = attempt.job;
|
|
320
|
+
const total = job.total + attempt.usage;
|
|
321
|
+
if (!Number.isSafeInteger(total)) {
|
|
322
|
+
attempt.usage = undefined;
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (!attempt.accepted || attempt.nudged || total < job.policy.warnTokens || !valid(job)) return;
|
|
326
|
+
job.budgetReached = true;
|
|
327
|
+
if (!stillWorking(attempt)) return;
|
|
328
|
+
attempt.nudged = true;
|
|
329
|
+
const signal = attempt.signal;
|
|
330
|
+
const turn = attempt.turn;
|
|
331
|
+
queueMicrotask(() => {
|
|
332
|
+
if (!stillWorking(attempt) || attempt.signal !== signal || attempt.turn !== turn) return;
|
|
333
|
+
attempt.noticeId = randomUUID();
|
|
334
|
+
try { notice(attempt.child, REMINDER, attempt.noticeId); }
|
|
335
|
+
catch {
|
|
336
|
+
if (valid(job)) report(`请在子代理面板提醒「${attempt.name}」收尾。`);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
attempt.status = 'nudged';
|
|
340
|
+
if (job.policy.mode !== 'stop' || !stillWorking(attempt)) return;
|
|
341
|
+
attempt.graceTimer = clock.setTimeout(() => {
|
|
342
|
+
attempt.graceTimer = undefined;
|
|
343
|
+
if (!stillWorking(attempt) || readWatchdog(config).mode !== 'stop') return;
|
|
344
|
+
report(`「${attempt.name}」在宽限期后仍在进行。请在子代理面板停止。`);
|
|
345
|
+
}, job.policy.graceMs);
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function finish(attempt, receipt) {
|
|
350
|
+
if (!attempt || !jobs.has(attempt.job)) return;
|
|
351
|
+
unpend(attempt);
|
|
352
|
+
if (!valid(attempt.job) || attempt.ambiguous || !attempt.key || !attempt.catalogSeen ||
|
|
353
|
+
receipt?.kind !== 'activation' || receipt.name !== attempt.name) {
|
|
354
|
+
clear(attempt.job);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
attempt.accepted = true;
|
|
358
|
+
attempt.status = 'running';
|
|
359
|
+
sample(attempt);
|
|
360
|
+
if (attempt.ended) settle(attempt);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function routeRecorded(route) {
|
|
364
|
+
try {
|
|
365
|
+
const state = projections.stateOf?.(parent.session, 'subagentModelSelectionPolicy');
|
|
366
|
+
return Array.isArray(state) && state.some(row => samePair(row, route));
|
|
367
|
+
} catch { return false; }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function validRetry(job, candidate) {
|
|
371
|
+
if (!valid(job) || job.budgetReached) return false;
|
|
372
|
+
const active = readWatchdog(config);
|
|
373
|
+
if (active.mode !== 'retry' || !active.tiers.includes(job.tier) || job.used > active.maxRetries ||
|
|
374
|
+
job.total >= active.warnTokens) return false;
|
|
375
|
+
const currentGroups = readModelGroups(config);
|
|
376
|
+
if (job.grouped) {
|
|
377
|
+
if (!sameGroupOrder(modelGroups, currentGroups, job.tier)) return false;
|
|
378
|
+
} else {
|
|
379
|
+
const currentChain = (readLive(config, 'fallbacks') ?? []).find(row => samePair(row.primary, job.initial))?.alternatives;
|
|
380
|
+
if (currentGroups || candidate.provider !== job.initial.provider || !samePair(currentChain?.[job.used - 1], candidate)) return false;
|
|
381
|
+
}
|
|
382
|
+
if (ctx.tools.executable?.('subagent', parent) !== nativeDefinition || !routeRecorded(candidate)) return false;
|
|
383
|
+
try {
|
|
384
|
+
const host = ctx.get('settings')?.describe().find(row => row.ns === HOST_SELECTION_ENTRY_ID)?.value;
|
|
385
|
+
return host?.enabled === true && host.allowedModels.some(row => samePair(row, candidate));
|
|
386
|
+
} catch { return false; }
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function retry(job, previous, candidate) {
|
|
390
|
+
const nextName = `sm-${job.id}-r${job.used}`;
|
|
391
|
+
const failed = `「${previous.name}」失败。`;
|
|
392
|
+
const manual = () => { if (valid(job)) report(`${failed}请在子代理面板确认是否重新派活。`); };
|
|
393
|
+
try {
|
|
394
|
+
if (!validRetry(job, candidate)) return manual();
|
|
395
|
+
const models = await ctx.get('llm')?.listModels(candidate.provider, job.controller.signal);
|
|
396
|
+
if (!models?.some(model => model.id === candidate.model) || !validRetry(job, candidate) ||
|
|
397
|
+
agents.get(previous.id) !== undefined) return manual();
|
|
398
|
+
const { reasoning_effort, ...original } = job.args;
|
|
399
|
+
void reasoning_effort;
|
|
400
|
+
// 改派不继承原档位;目标模型配置了默认档位时使用它,否则交给模型默认。
|
|
401
|
+
const candidateArgs = { ...original, ...candidate };
|
|
402
|
+
const configured = modelGroups ? candidateRowEffort(modelGroups, job.tier, candidate) : undefined;
|
|
403
|
+
if (configured !== undefined) candidateArgs.reasoning_effort = configured;
|
|
404
|
+
const attempt = scheduleAttempt(job, candidateArgs, candidate, nextName);
|
|
405
|
+
const startup = new AbortController();
|
|
406
|
+
const stopForwarding = onAbort(job.controller.signal, () => startup.abort());
|
|
407
|
+
const id = randomUUID();
|
|
408
|
+
let receipt;
|
|
409
|
+
try {
|
|
410
|
+
const batch = await ctx.tools.execute({ agent: parent, signal: startup.signal,
|
|
411
|
+
calls: [{ id, name: 'subagent', arguments: JSON.stringify(attempt.args) }],
|
|
412
|
+
});
|
|
413
|
+
// Once the tool has returned, withdrawing monitoring must leave accepted work to the host.
|
|
414
|
+
stopForwarding();
|
|
415
|
+
const result = batch.results.find(entry => entry.callId === id)?.result;
|
|
416
|
+
if (result && !result.isError) receipt = result.value;
|
|
417
|
+
if (valid(job)) {
|
|
418
|
+
if (receipt?.kind === 'activation' && receipt.name === nextName) report(`${failed}已接受改派「${nextName}」。`);
|
|
419
|
+
else manual();
|
|
420
|
+
}
|
|
421
|
+
} catch {
|
|
422
|
+
if (valid(job)) report(`${failed}未收到改派确认。请先在子代理面板查看新任务是否已经启动。`);
|
|
423
|
+
} finally {
|
|
424
|
+
stopForwarding();
|
|
425
|
+
finish(attempt, receipt);
|
|
426
|
+
}
|
|
427
|
+
} catch {
|
|
428
|
+
manual();
|
|
429
|
+
} finally {
|
|
430
|
+
if (job.attempt === previous) clear(job);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function settle(attempt) {
|
|
435
|
+
if (!attempt.accepted || !attempt.ended || attempt.status === 'terminal') return;
|
|
436
|
+
attempt.status = 'terminal';
|
|
437
|
+
const job = attempt.job;
|
|
438
|
+
const candidate = job.candidates[job.used];
|
|
439
|
+
if (!valid(job) || !matchesEnd(attempt) || job.policy.mode !== 'retry' || job.budgetReached ||
|
|
440
|
+
job.used >= job.policy.maxRetries || !candidate) {
|
|
441
|
+
clear(job);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
job.total += attempt.usage;
|
|
445
|
+
if (!Number.isSafeInteger(job.total) || job.total >= job.policy.warnTokens) {
|
|
446
|
+
clear(job);
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
job.used++;
|
|
450
|
+
dropAttempt(attempt);
|
|
451
|
+
// Keep only the prior generation id during the async decision.
|
|
452
|
+
job.previous = attempt;
|
|
453
|
+
released.set(attempt.id, attempt);
|
|
454
|
+
attempt.releaseTimer = clock.setTimeout(() => clear(job), LIMITS.release);
|
|
455
|
+
void retry(job, attempt, candidate).finally(() => {
|
|
456
|
+
if (job.previous === attempt) job.previous = undefined;
|
|
457
|
+
dropAttempt(attempt);
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function finishObservation(info) {
|
|
462
|
+
const attempt = runs.get(endKey(info));
|
|
463
|
+
if (!attempt || attempt.ended || info.parentSessionId !== parent.id) return;
|
|
464
|
+
if (attempt.child !== undefined) attempt.incomplete = true;
|
|
465
|
+
attempt.ended = true;
|
|
466
|
+
stopTimer(attempt, 'graceTimer');
|
|
467
|
+
attempt.terminal = { ...attempt.terminal, stopReason: info.stopReason };
|
|
468
|
+
if (includesContent(info.lastAssistantMessage)) attempt.hasOutput = true;
|
|
469
|
+
settle(attempt);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function onSessionEvent(session, event) {
|
|
473
|
+
if (session === parent.session && event.type === 'subagent/catalog') {
|
|
474
|
+
for (const attempt of pending.get(event.data.name) ?? []) {
|
|
475
|
+
if (attempt.id === event.data.childId && event.seq >= attempt.parentSeq) attempt.catalogSeen = true;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
const attempt = sessions.get(session);
|
|
479
|
+
if (!attempt || event.seq < attempt.fromSeq) return;
|
|
480
|
+
if (attempt.job.grouped && (event.type === 'llm/retry' || event.type === 'llm/retry-started')) {
|
|
481
|
+
observeRetry(attempt, event);
|
|
482
|
+
}
|
|
483
|
+
if (event.type === 'step/start' || event.type === 'llm/retry-started') {
|
|
484
|
+
attempt.waitForProgress = false;
|
|
485
|
+
sample(attempt);
|
|
486
|
+
}
|
|
487
|
+
if (event.type === 'tool/call') attempt.hasOutput = true;
|
|
488
|
+
if (event.type === 'request/header' && !samePair(attempt.route, event.data.header?.config)) attempt.routeChanged = true;
|
|
489
|
+
if (event.type === 'request/context' && !samePair(attempt.route, event.data)) attempt.routeChanged = true;
|
|
490
|
+
if (event.type === 'assistant/message' || event.type === 'assistant/attempt') {
|
|
491
|
+
observeAssistant(attempt, event);
|
|
492
|
+
sample(attempt);
|
|
493
|
+
}
|
|
494
|
+
if (event.type === 'turn/end') {
|
|
495
|
+
const { turn, reason } = event.data;
|
|
496
|
+
stopTimer(attempt, 'graceTimer');
|
|
497
|
+
attempt.terminal = { turn, code: reason.kind === 'error' ? reason.error?.code : undefined };
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function onDispose({ agent }) {
|
|
502
|
+
if (agent === parent) { dispose(); return; }
|
|
503
|
+
const attempt = children.get(agent);
|
|
504
|
+
if (!attempt) return;
|
|
505
|
+
sample(attempt);
|
|
506
|
+
if (attempt.signal?.aborted || !attempt.terminal) attempt.cancelled = true;
|
|
507
|
+
stopTimer(attempt, 'graceTimer');
|
|
508
|
+
dropChild(attempt);
|
|
509
|
+
released.set(agent.id, attempt);
|
|
510
|
+
attempt.releaseTimer = clock.setTimeout(() => clear(attempt.job), LIMITS.release);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function dispose() {
|
|
514
|
+
if (closed) return;
|
|
515
|
+
closed = true;
|
|
516
|
+
for (const job of jobs) clear(job);
|
|
517
|
+
stopListeningParent?.();
|
|
518
|
+
parentSignal = undefined;
|
|
519
|
+
for (const disposeListener of listeners.splice(0).reverse()) disposeListener?.();
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function listen(context, event, callback, options) {
|
|
523
|
+
listeners.push(context.on(event, callback, options));
|
|
524
|
+
}
|
|
525
|
+
listen(parent.ctx, 'subagent/start', beginObservation);
|
|
526
|
+
listen(parent.ctx, 'subagent/end', finishObservation);
|
|
527
|
+
listen(ctx, 'session/event', onSessionEvent, { global: true });
|
|
528
|
+
listen(ctx, 'agent/disposed', onDispose, { global: true });
|
|
529
|
+
listen(ctx, 'settings/document-updated', ns => {
|
|
530
|
+
if (ns === CONFIG_ENTRY && readWatchdog(config).mode === 'off') for (const job of jobs) clear(job);
|
|
531
|
+
});
|
|
532
|
+
listen(ctx, 'agent/inbox/inserted', ({ agent, message }) => {
|
|
533
|
+
const attempt = children.get(agent);
|
|
534
|
+
if (!attempt || message.id === attempt.noticeId) return;
|
|
535
|
+
if (attempt.initialId === undefined && message.source?.kind === 'user' && !message.source.rpcId) attempt.initialId = message.id;
|
|
536
|
+
else clear(attempt.job);
|
|
537
|
+
}, { global: true });
|
|
538
|
+
listen(ctx, 'agent/pre-step', ({ agent, turn, step, signal, modelSelection }, next) => {
|
|
539
|
+
if (agent === parent && parentSignal !== signal) {
|
|
540
|
+
stopListeningParent?.();
|
|
541
|
+
parentSignal = signal;
|
|
542
|
+
stopListeningParent = onAbort(signal, () => { for (const job of jobs) clear(job); });
|
|
543
|
+
}
|
|
544
|
+
const attempt = children.get(agent);
|
|
545
|
+
if (attempt) {
|
|
546
|
+
if (attempt.turn !== undefined && attempt.turn !== turn) clear(attempt.job);
|
|
547
|
+
else {
|
|
548
|
+
attempt.turn = turn;
|
|
549
|
+
if (attempt.step !== step) attempt.hostRetry = undefined;
|
|
550
|
+
attempt.step = step;
|
|
551
|
+
if (!samePair(attempt.route, modelSelection)) attempt.routeChanged = true;
|
|
552
|
+
if (attempt.signal !== signal) {
|
|
553
|
+
attempt.stopListeningChild?.();
|
|
554
|
+
attempt.signal = signal;
|
|
555
|
+
attempt.stopListeningChild = onAbort(signal, () => clear(attempt.job));
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return next();
|
|
560
|
+
}, { global: true });
|
|
561
|
+
listen(ctx, 'agent/request-error', ({ agent, turn, step, provider, failure, retryPolicy }, next) => {
|
|
562
|
+
const attempt = children.get(agent);
|
|
563
|
+
if (attempt) {
|
|
564
|
+
if (provider !== attempt.route.provider) attempt.routeChanged = true;
|
|
565
|
+
const retryLimit = retryPolicy?.mode === 'normal' && retryPolicy.retryableCodes?.includes(failure?.code)
|
|
566
|
+
? retryPolicy.maxRetries : undefined;
|
|
567
|
+
attempt.failure = { turn, step, code: failure?.code, retryLimit };
|
|
568
|
+
}
|
|
569
|
+
return next();
|
|
570
|
+
}, { global: true });
|
|
571
|
+
listeners.push(projections.onChanged((session, key) => {
|
|
572
|
+
const attempt = sessions.get(session);
|
|
573
|
+
if (key === 'tokenUsage' && attempt) sample(attempt);
|
|
574
|
+
}));
|
|
575
|
+
|
|
576
|
+
return { begin, finish, dispose };
|
|
577
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Subagent model settings",
|
|
4
|
+
"description": "Order cost-effective and expert models, add purpose notes, and choose when to remind or switch models. Manage permissions separately in Subagent settings.",
|
|
5
|
+
"detail": "docs/plugin-detail.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-submodel",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "官方 subagent
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "Two-way cross-model delegation for the official DSH subagent: routine execution on a cheap model, hard problems on a strong one. 官方 subagent 的双向跨模型派活策略:常规执行走便宜模型、难题升级强模型,token 花在刀刃上。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./lib/index.js",
|
|
9
|
+
"./client": "./client.js",
|
|
10
|
+
"./locale/*.json": "./locale/*.json",
|
|
9
11
|
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
10
12
|
"./package.json": "./package.json"
|
|
11
13
|
},
|
|
@@ -22,10 +24,15 @@
|
|
|
22
24
|
"dsh": {
|
|
23
25
|
"bundle": {
|
|
24
26
|
"patch": "./cordis.patch.yml"
|
|
27
|
+
},
|
|
28
|
+
"client": {
|
|
29
|
+
"platform": "web",
|
|
30
|
+
"immediately": true,
|
|
31
|
+
"inject": ["@deepseek-ai/dsh-client-ui-plugin-manager"]
|
|
25
32
|
}
|
|
26
33
|
},
|
|
27
34
|
"engines": {
|
|
28
|
-
"dsh": ">=0.2.2-rc.
|
|
35
|
+
"dsh": ">=0.2.2-rc.5"
|
|
29
36
|
},
|
|
30
37
|
"peerDependencies": {
|
|
31
38
|
"@deepseek-ai/schemastery": ">=3.18.4 <4.0.0"
|
|
@@ -35,6 +42,9 @@
|
|
|
35
42
|
},
|
|
36
43
|
"files": [
|
|
37
44
|
"lib",
|
|
45
|
+
"client.js",
|
|
46
|
+
"locale/*.json",
|
|
47
|
+
"docs/plugin-detail.md",
|
|
38
48
|
"cordis.patch.yml",
|
|
39
49
|
"README.md",
|
|
40
50
|
"README.en.md",
|
|
@@ -47,6 +57,11 @@
|
|
|
47
57
|
"subagent",
|
|
48
58
|
"delegation",
|
|
49
59
|
"policy",
|
|
50
|
-
"model-routing"
|
|
60
|
+
"model-routing",
|
|
61
|
+
"token-optimization",
|
|
62
|
+
"cost-optimization",
|
|
63
|
+
"routing",
|
|
64
|
+
"agent-teams",
|
|
65
|
+
"flash"
|
|
51
66
|
]
|
|
52
67
|
}
|