@suifei/dsh-ai-team 0.4.94 → 0.4.96

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.
@@ -1,155 +1,157 @@
1
- /**
2
- * LLM failure classification and the deterministic retry/fallback decision.
3
- *
4
- * The listener on `agent/request-error` owns the retry for transient
5
- * server/network failures and re-dispatches the same request immediately
6
- * (DSH's agent loop supports that via `{ kind: 'retry' }`). There are no
7
- * timers: a fallback patch only rewrites the member's persisted config, so it
8
- * takes effect on the next wake — the current turn ends (`fail`). Rate limits
9
- * also end the turn: hammering the same route at once burns the retry budget
10
- * without a backoff clock. Auth/billing/policy failures are fail-closed and
11
- * require a Human or the Project owner to change the environment.
12
- */
13
-
14
- export const FAILURE_CATEGORY = Object.freeze({
15
- AUTH: 'auth',
16
- BILLING: 'billing',
17
- RATE_LIMIT: 'rate_limit',
18
- NETWORK: 'network',
19
- SERVER: 'server',
20
- MODEL_UNAVAILABLE: 'model_unavailable',
21
- CONTEXT_OVERFLOW: 'context_overflow',
22
- POLICY: 'policy',
23
- UNKNOWN: 'unknown',
24
- });
25
-
26
- const NETWORK_CODES = new Set([
27
- 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN', 'EPIPE', 'UND_ERR_CONNECT_TIMEOUT',
28
- ]);
29
-
30
- function statusOf(error) {
31
- const value = error?.status ?? error?.statusCode ?? error?.response?.status ?? error?.details?.status;
32
- return Number.isSafeInteger(value) ? value : null;
33
- }
34
-
35
- function codeOf(error) {
36
- return String(error?.code ?? error?.details?.code ?? '').toUpperCase();
37
- }
38
-
39
- function textOf(error) {
40
- return String(error?.message ?? error?.details?.message ?? '').toLowerCase();
41
- }
42
-
43
- /** Map a provider/network error to one stable category + policy. */
44
- export function classifyLlmFailure(error) {
45
- const status = statusOf(error);
46
- const code = codeOf(error);
47
- const text = textOf(error);
48
- const base = { status, code: code || null, message: error?.message ?? '' };
49
-
50
- if (status === 401 || status === 403 || code.includes('INVALID_API_KEY') || code.includes('UNAUTHORIZED')) {
51
- return { ...base, category: FAILURE_CATEGORY.AUTH, retryable: false, humanRequired: true, action: 'stop' };
52
- }
53
- // 429 必须先判:限流响应常带 "quota"/"insufficient" 字样,若先走 billing
54
- // 分支就会被当成致命计费错误,永远不重试也不换路。
55
- if (status === 429 || code.includes('RATE_LIMIT') || /rate limit/.test(text)) {
56
- return { ...base, category: FAILURE_CATEGORY.RATE_LIMIT, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
57
- }
58
- if (
59
- status === 402 ||
60
- /insufficient|balance|quota|billing|payment|credit/.test(code) ||
61
- /insufficient|balance|quota|billing|payment|credit/.test(text)
62
- ) {
63
- return { ...base, category: FAILURE_CATEGORY.BILLING, retryable: false, humanRequired: true, action: 'stop' };
64
- }
65
- if (status !== null && status >= 500) {
66
- return { ...base, category: FAILURE_CATEGORY.SERVER, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
67
- }
68
- if (NETWORK_CODES.has(code) || /network|timeout|timed out|socket|connection reset|dns/.test(text)) {
69
- return { ...base, category: FAILURE_CATEGORY.NETWORK, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
70
- }
71
- if (status === 404 || /model.*(not found|unavailable)|unknown model/.test(text)) {
72
- return { ...base, category: FAILURE_CATEGORY.MODEL_UNAVAILABLE, retryable: false, humanRequired: false, action: 'fallback' };
73
- }
74
- if (/context.*(length|window|overflow)|too many tokens|maximum context/.test(text)) {
75
- return { ...base, category: FAILURE_CATEGORY.CONTEXT_OVERFLOW, retryable: false, humanRequired: false, action: 'compact_or_fallback' };
76
- }
77
- if (status === 400 && /content|policy|refus|safety/.test(text)) {
78
- return { ...base, category: FAILURE_CATEGORY.POLICY, retryable: false, humanRequired: true, action: 'stop' };
79
- }
80
- return { ...base, category: FAILURE_CATEGORY.UNKNOWN, retryable: false, humanRequired: true, action: 'stop' };
81
- }
82
-
83
- function fallbackAt(config, index) {
84
- const list = Array.isArray(config?.fallback) ? config.fallback : [];
85
- return list[index] ?? null;
86
- }
87
-
88
- /**
89
- * Decide what the request-error listener does next. `retry` re-dispatches the
90
- * same request immediately; `fallback` writes the config patch and ends the
91
- * turn (it can only take effect on the next wake, because a step's route is
92
- * captured before dispatch); `fail` ends the turn unchanged.
93
- */
94
- /**
95
- * 本次请求的连续失败次数。
96
- *
97
- * 此前调用方把 `member.attempts`(成员**生命周期**里的失败计数)当成本次尝试数传进来,
98
- * 于是换路索引被跳过、重试预算被历史失败提前耗尽。这里按会话维护一个窗口内的计数:
99
- * 窗口过期即视为新请求(成员被唤醒重试时应当拿到完整预算)。
100
- */
101
- export function nextRequestAttempt(store, sessionId, now = Date.now(), windowMs = 10 * 60_000) {
102
- const key = typeof sessionId === 'string' && sessionId !== '' ? sessionId : '(unknown)';
103
- const prior = store?.get?.(key);
104
- const attempt = prior !== undefined && typeof prior.at === 'number' && now - prior.at < windowMs
105
- ? prior.count + 1
106
- : 1;
107
- store?.set?.(key, { count: attempt, at: now });
108
- return attempt;
109
- }
110
-
111
- export function retryDecision(failure, config = {}, attempt = 1) {
112
- const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
113
- ? Math.max(1, Math.min(config.retry.maxAttempts, 5))
114
- : 3;
115
- // 换路(fallback)能否执行取决于“路由可变”,与“同路由立刻重试”不同:
116
- // model_unavailable / context_overflow 明确声明了 fallback 语义且 retryable=false,
117
- // 若这里按 retryable 一刀切返回 fail,它们的 fallback 声明就永远不可达。
118
- const fallbackCapable = failure?.retryable === true
119
- || failure?.action === 'fallback'
120
- || failure?.action === 'compact_or_fallback';
121
- if (!fallbackCapable) return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} has no recoverable action` };
122
- const nextFallbackIndex = attempt - 1;
123
- const fallback = fallbackAt(config, nextFallbackIndex);
124
- if (fallback !== null) {
125
- // 换路优先于预算:fallback 不是同路由重试,预算钳制它会让 maxAttempts=1
126
- // 的配置永远走不到备用路由。
127
- return {
128
- action: 'fallback',
129
- attempt,
130
- fallbackIndex: nextFallbackIndex,
131
- patch: {
132
- provider: fallback.provider ?? config.provider,
133
- model: fallback.model ?? config.model,
134
- ...(fallback.reasoningEffort === undefined ? {} : { reasoningEffort: fallback.reasoningEffort }),
135
- ...(fallback.maxTokens === undefined ? {} : { maxTokens: fallback.maxTokens }),
136
- },
137
- reason: `fallback to ${fallback.provider ?? config.provider}/${fallback.model ?? config.model}`,
138
- };
139
- }
140
- if (failure?.retryable !== true) {
141
- return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} is not retryable and has no fallback route` };
142
- }
143
- if (attempt >= maxAttempts) return { action: 'fail', attempt, reason: `retry budget exhausted (${maxAttempts})` };
144
- // No fallback route configured: a rate limit would hit again at once
145
- // without a backoff clock — end the turn and let the next event/startup
146
- // try fresh instead of burning the budget on a throttled route.
147
- if (failure.category === FAILURE_CATEGORY.RATE_LIMIT) {
148
- return { action: 'fail', attempt, reason: 'rate limited; left to the next wake' };
149
- }
150
- return { action: 'retry', attempt, reason: 'same route, immediate retry' };
151
- }
152
-
153
- export function describeFailure(failure) {
154
- return `${failure.category}${failure.status ? ` HTTP ${failure.status}` : ''}${failure.code ? ` ${failure.code}` : ''}`;
155
- }
1
+ /**
2
+ * LLM failure classification and the deterministic retry/fallback decision.
3
+ *
4
+ * The listener on `agent/request-error` owns the retry for transient
5
+ * server/network failures and re-dispatches the same request immediately
6
+ * (DSH's agent loop supports that via `{ kind: 'retry' }`). There are no
7
+ * timers: a fallback patch only rewrites the member's persisted config, so it
8
+ * takes effect on the next wake — the current turn ends (`fail`). Rate limits
9
+ * also end the turn: hammering the same route at once burns the retry budget
10
+ * without a backoff clock. Auth/billing/policy failures are fail-closed and
11
+ * require a Human or the Project owner to change the environment.
12
+ */
13
+
14
+ export const FAILURE_CATEGORY = Object.freeze({
15
+ AUTH: 'auth',
16
+ BILLING: 'billing',
17
+ RATE_LIMIT: 'rate_limit',
18
+ NETWORK: 'network',
19
+ SERVER: 'server',
20
+ MODEL_UNAVAILABLE: 'model_unavailable',
21
+ CONTEXT_OVERFLOW: 'context_overflow',
22
+ POLICY: 'policy',
23
+ // 成员会话不可续接且已用掉自动重建额度(见 activation-budget.js autoReseatAllowed)。
24
+ SESSION: 'session',
25
+ UNKNOWN: 'unknown',
26
+ });
27
+
28
+ const NETWORK_CODES = new Set([
29
+ 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN', 'EPIPE', 'UND_ERR_CONNECT_TIMEOUT',
30
+ ]);
31
+
32
+ function statusOf(error) {
33
+ const value = error?.status ?? error?.statusCode ?? error?.response?.status ?? error?.details?.status;
34
+ return Number.isSafeInteger(value) ? value : null;
35
+ }
36
+
37
+ function codeOf(error) {
38
+ return String(error?.code ?? error?.details?.code ?? '').toUpperCase();
39
+ }
40
+
41
+ function textOf(error) {
42
+ return String(error?.message ?? error?.details?.message ?? '').toLowerCase();
43
+ }
44
+
45
+ /** Map a provider/network error to one stable category + policy. */
46
+ export function classifyLlmFailure(error) {
47
+ const status = statusOf(error);
48
+ const code = codeOf(error);
49
+ const text = textOf(error);
50
+ const base = { status, code: code || null, message: error?.message ?? '' };
51
+
52
+ if (status === 401 || status === 403 || code.includes('INVALID_API_KEY') || code.includes('UNAUTHORIZED')) {
53
+ return { ...base, category: FAILURE_CATEGORY.AUTH, retryable: false, humanRequired: true, action: 'stop' };
54
+ }
55
+ // 429 必须先判:限流响应常带 "quota"/"insufficient" 字样,若先走 billing
56
+ // 分支就会被当成致命计费错误,永远不重试也不换路。
57
+ if (status === 429 || code.includes('RATE_LIMIT') || /rate limit/.test(text)) {
58
+ return { ...base, category: FAILURE_CATEGORY.RATE_LIMIT, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
59
+ }
60
+ if (
61
+ status === 402 ||
62
+ /insufficient|balance|quota|billing|payment|credit/.test(code) ||
63
+ /insufficient|balance|quota|billing|payment|credit/.test(text)
64
+ ) {
65
+ return { ...base, category: FAILURE_CATEGORY.BILLING, retryable: false, humanRequired: true, action: 'stop' };
66
+ }
67
+ if (status !== null && status >= 500) {
68
+ return { ...base, category: FAILURE_CATEGORY.SERVER, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
69
+ }
70
+ if (NETWORK_CODES.has(code) || /network|timeout|timed out|socket|connection reset|dns/.test(text)) {
71
+ return { ...base, category: FAILURE_CATEGORY.NETWORK, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
72
+ }
73
+ if (status === 404 || /model.*(not found|unavailable)|unknown model/.test(text)) {
74
+ return { ...base, category: FAILURE_CATEGORY.MODEL_UNAVAILABLE, retryable: false, humanRequired: false, action: 'fallback' };
75
+ }
76
+ if (/context.*(length|window|overflow)|too many tokens|maximum context/.test(text)) {
77
+ return { ...base, category: FAILURE_CATEGORY.CONTEXT_OVERFLOW, retryable: false, humanRequired: false, action: 'compact_or_fallback' };
78
+ }
79
+ if (status === 400 && /content|policy|refus|safety/.test(text)) {
80
+ return { ...base, category: FAILURE_CATEGORY.POLICY, retryable: false, humanRequired: true, action: 'stop' };
81
+ }
82
+ return { ...base, category: FAILURE_CATEGORY.UNKNOWN, retryable: false, humanRequired: true, action: 'stop' };
83
+ }
84
+
85
+ function fallbackAt(config, index) {
86
+ const list = Array.isArray(config?.fallback) ? config.fallback : [];
87
+ return list[index] ?? null;
88
+ }
89
+
90
+ /**
91
+ * Decide what the request-error listener does next. `retry` re-dispatches the
92
+ * same request immediately; `fallback` writes the config patch and ends the
93
+ * turn (it can only take effect on the next wake, because a step's route is
94
+ * captured before dispatch); `fail` ends the turn unchanged.
95
+ */
96
+ /**
97
+ * 本次请求的连续失败次数。
98
+ *
99
+ * 此前调用方把 `member.attempts`(成员**生命周期**里的失败计数)当成本次尝试数传进来,
100
+ * 于是换路索引被跳过、重试预算被历史失败提前耗尽。这里按会话维护一个窗口内的计数:
101
+ * 窗口过期即视为新请求(成员被唤醒重试时应当拿到完整预算)。
102
+ */
103
+ export function nextRequestAttempt(store, sessionId, now = Date.now(), windowMs = 10 * 60_000) {
104
+ const key = typeof sessionId === 'string' && sessionId !== '' ? sessionId : '(unknown)';
105
+ const prior = store?.get?.(key);
106
+ const attempt = prior !== undefined && typeof prior.at === 'number' && now - prior.at < windowMs
107
+ ? prior.count + 1
108
+ : 1;
109
+ store?.set?.(key, { count: attempt, at: now });
110
+ return attempt;
111
+ }
112
+
113
+ export function retryDecision(failure, config = {}, attempt = 1) {
114
+ const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
115
+ ? Math.max(1, Math.min(config.retry.maxAttempts, 5))
116
+ : 3;
117
+ // 换路(fallback)能否执行取决于“路由可变”,与“同路由立刻重试”不同:
118
+ // model_unavailable / context_overflow 明确声明了 fallback 语义且 retryable=false,
119
+ // 若这里按 retryable 一刀切返回 fail,它们的 fallback 声明就永远不可达。
120
+ const fallbackCapable = failure?.retryable === true
121
+ || failure?.action === 'fallback'
122
+ || failure?.action === 'compact_or_fallback';
123
+ if (!fallbackCapable) return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} has no recoverable action` };
124
+ const nextFallbackIndex = attempt - 1;
125
+ const fallback = fallbackAt(config, nextFallbackIndex);
126
+ if (fallback !== null) {
127
+ // 换路优先于预算:fallback 不是同路由重试,预算钳制它会让 maxAttempts=1
128
+ // 的配置永远走不到备用路由。
129
+ return {
130
+ action: 'fallback',
131
+ attempt,
132
+ fallbackIndex: nextFallbackIndex,
133
+ patch: {
134
+ provider: fallback.provider ?? config.provider,
135
+ model: fallback.model ?? config.model,
136
+ ...(fallback.reasoningEffort === undefined ? {} : { reasoningEffort: fallback.reasoningEffort }),
137
+ ...(fallback.maxTokens === undefined ? {} : { maxTokens: fallback.maxTokens }),
138
+ },
139
+ reason: `fallback to ${fallback.provider ?? config.provider}/${fallback.model ?? config.model}`,
140
+ };
141
+ }
142
+ if (failure?.retryable !== true) {
143
+ return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} is not retryable and has no fallback route` };
144
+ }
145
+ if (attempt >= maxAttempts) return { action: 'fail', attempt, reason: `retry budget exhausted (${maxAttempts})` };
146
+ // No fallback route configured: a rate limit would hit again at once
147
+ // without a backoff clock — end the turn and let the next event/startup
148
+ // try fresh instead of burning the budget on a throttled route.
149
+ if (failure.category === FAILURE_CATEGORY.RATE_LIMIT) {
150
+ return { action: 'fail', attempt, reason: 'rate limited; left to the next wake' };
151
+ }
152
+ return { action: 'retry', attempt, reason: 'same route, immediate retry' };
153
+ }
154
+
155
+ export function describeFailure(failure) {
156
+ return `${failure.category}${failure.status ? ` HTTP ${failure.status}` : ''}${failure.code ? ` ${failure.code}` : ''}`;
157
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 停止即停:项目停止后,团队会话(PMO + 成员)不得再唤醒或派生智能体。
3
+ *
4
+ * 实机(il2c,11-14 20:14):Human 停止 → 插件中断全部成员(生效,成员回合以
5
+ * aborted:user 结束)→ 宿主给父会话(PMO)递送「Background subagent … was stopped
6
+ * before it finished」→ PMO 开新回合,用宿主内置的 `send_message` 发「续跑唤醒」→
7
+ * 成员接着干了 25 分钟。插件自己的唤醒有 runState 闸,但 `send_message` 是宿主
8
+ * 内置工具,完全绕过它。这里在 `tools.guard` 上补这道闸:停止期间团队会话调用
9
+ * 唤醒 / 派生类工具一律拒绝,拒绝理由回给模型,让它结束本回合等 Human。
10
+ */
11
+
12
+ /** 宿主内置的、会唤醒已有智能体或派生新智能体的工具(tool-subagent-control / tool-subagent / ralph)。 */
13
+ export const AGENT_WAKE_TOOLS = new Set(['send_message', 'subagent', 'subagent_fork', 'subagent_oar', 'ralph']);
14
+
15
+ /**
16
+ * @param {object} execution 宿主 ToolExecution(name / agent.id)
17
+ * @param {(sessionId: string) => ({ stopped: boolean, projectId: string, projectName?: string } | null)} projectOf
18
+ * @returns {{ projectId: string, reason: string } | null} 需要拒绝时返回理由
19
+ */
20
+ export function stoppedTeamDenial(execution, projectOf) {
21
+ const name = String(execution?.name ?? '');
22
+ if (!AGENT_WAKE_TOOLS.has(name)) return null;
23
+ const sessionId = execution?.agent?.id;
24
+ if (typeof sessionId !== 'string' || sessionId === '') return null;
25
+ const project = projectOf(sessionId);
26
+ if (project === null || project === undefined || project.stopped !== true) return null;
27
+ const label = project.projectName ? `项目「${project.projectName}」` : '项目';
28
+ return {
29
+ projectId: project.projectId,
30
+ reason: `已阻止:${label}已被 Human 停止,停止期间不得唤醒或派生成员(${name})。成员被停是 Human 的决定,不是异常中断,不要续跑。结束本回合,等 Human 重新启动项目。`,
31
+ };
32
+ }
33
+
34
+ /**
35
+ * @param {object} options
36
+ * @param {object} options.tools `ctx.tools`
37
+ * @param {(sessionId: string) => object | null} options.projectOf
38
+ * @param {{ append?: (row: object) => void }} [options.diag]
39
+ * @returns {() => void} disposer
40
+ */
41
+ export function registerStopGuard({ tools, projectOf, diag }) {
42
+ if (tools === undefined || tools === null || typeof tools.guard !== 'function') return () => {};
43
+ return tools.guard((execution) => {
44
+ try {
45
+ const denial = stoppedTeamDenial(execution, projectOf);
46
+ if (denial === null) return undefined;
47
+ diag?.append?.({ ev: 'team.stopped.blocked', projectId: denial.projectId, sessionId: execution?.agent?.id ?? null, tool: String(execution?.name ?? '') });
48
+ return denial.reason;
49
+ } catch {
50
+ // 守卫自身出错绝不能阻断工具调用。
51
+ return undefined;
52
+ }
53
+ });
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.94",
3
+ "version": "0.4.96",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",