@deepseek-ai/dsh-repeat-tool-reminder 0.2.2-rc.1 → 0.2.2-rc.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.
package/README.i18n.yaml CHANGED
@@ -36,8 +36,8 @@
36
36
  en: b76a432aad14aa90
37
37
  zh: b0cd916f7897fb42
38
38
  /deepseek-ai-dsh-repeat-tool-reminder/understand-the-implementation/reminder-delivery:
39
- en: a3edc5c0f98b0d1e
40
- zh: 173f6166ce3af779
39
+ en: e11bb31ae82954cd
40
+ zh: 14f9c32ca93e7096
41
41
  /deepseek-ai-dsh-repeat-tool-reminder/understand-the-implementation/source-map:
42
42
  en: ba2eb423e165510d
43
43
  zh: db5155503a8504cb
package/README.md CHANGED
@@ -88,7 +88,7 @@ Each agent's chain is keyed by `(tool name, canonical arguments)` — two calls
88
88
 
89
89
  ### Reminder delivery
90
90
 
91
- Reminders ride the post-execute decision's `additionalContexts` (source `{kind: 'repeat-tool-reminder', form: 'notice', summary: '<tool> × <count>'}`), never a `content` replacement: the `tool/result` event stays the tool's own output for audit. The loop buffers the context and appends it as an injected `user/message` after the step's tool results, which the session renders as a plain synthetic user message — model-visible, source-attributed, and reconstructable from the session log with no new session event. The guard always delegates via `next()` and prepends its reminder to the downstream decision's context array, so both decision variants (a blocked call included) still get the nudge while every entry retains its own source and metadata.
91
+ Reminders ride the post-execute decision's `additionalContexts` (source `{kind: 'repeat-tool-reminder', form: 'notice', summary: '<tool> × <count>'}`), never a `content` replacement: the `tool/result` event stays the tool's own output for audit. The loop buffers the context and appends it as an injected `user/message` after the step's tool results, which the session renders as a plain synthetic user message — model-visible, source-attributed, and reconstructable from the session log with no new session event. The guard always delegates via `next()` and prepends its reminder to the downstream decision's context array, so both decision variants (a blocked call included) still get the nudge while every entry retains its own source and metadata and a downstream block keeps its feedback and structured error identity.
92
92
 
93
93
  ### Source map
94
94
 
package/README.zh.md CHANGED
@@ -88,7 +88,7 @@ guard 建立在四项承诺之上:
88
88
 
89
89
  ### 提醒传递
90
90
 
91
- 提醒随 post-execute 决策的 `additionalContexts`(来源为 `{kind: 'repeat-tool-reminder', form: 'notice', summary: '<tool> × <count>'}`)传递,绝不替换 `content`:用于审计的 `tool/result` 事件仍保留工具自己的输出。循环会缓冲这段上下文,并在该步骤的工具结果之后作为注入的 `user/message` 追加,会话将其渲染为普通的合成用户消息——模型可见、带有来源归属,且无需新会话事件即可从会话日志重建。guard 始终通过 `next()` 委派,并把提醒放在下游决策的上下文数组之前,因此两种决策变体(包括被阻止的调用)都会收到提醒,同时每个条目保留自己的来源与元数据。
91
+ 提醒随 post-execute 决策的 `additionalContexts`(来源为 `{kind: 'repeat-tool-reminder', form: 'notice', summary: '<tool> × <count>'}`)传递,绝不替换 `content`:用于审计的 `tool/result` 事件仍保留工具自己的输出。循环会缓冲这段上下文,并在该步骤的工具结果之后作为注入的 `user/message` 追加,会话将其渲染为普通的合成用户消息——模型可见、带有来源归属,且无需新会话事件即可从会话日志重建。guard 始终通过 `next()` 委派,并把提醒放在下游决策的上下文数组之前,因此两种决策变体(包括被阻止的调用)都会收到提醒,同时每个条目保留自己的来源与元数据,下游阻止也保留其反馈与结构化错误标识。
92
92
 
93
93
  ### 源码地图
94
94
 
package/lib/index.js CHANGED
@@ -922,11 +922,11 @@ function createUserMessage(input) {
922
922
  /** Largest delay Node schedules without clamping it to one millisecond. */
923
923
  const MAX_TIMER_DELAY_MS = 2147483647;
924
924
  //#endregion
925
- //#region ../../llm/llm/src/error.ts
925
+ //#region ../../util/error/src/index.ts
926
926
  /**
927
927
  * Harness error base with a stable machine-routable code and chained cause.
928
928
  * Package errors extend it so tool results and replay can retain failure class.
929
- * @module @deepseek-ai/dsh-llm/error
929
+ * @module @deepseek-ai/dsh-error
930
930
  */
931
931
  /**
932
932
  * Base class for all harness errors. Carries a `code` (stable, programmatic —
@@ -943,6 +943,75 @@ var HarnessError = class extends Error {
943
943
  this.name = new.target.name;
944
944
  }
945
945
  };
946
+ //#endregion
947
+ //#region ../../llm/llm/src/error.ts
948
+ /**
949
+ * LLM failure codes and helpers over the shared Harness error base. The base
950
+ * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
951
+ * import paths name the same class.
952
+ * @module @deepseek-ai/dsh-llm/error
953
+ */
954
+ /**
955
+ * Every failure code the built-in providers and the LLM runtime raise. An entry
956
+ * marked `retryChoice` is offered as a choice for a provider retry policy's
957
+ * `retryableCodes`; being a choice does not make a code retried by default.
958
+ */
959
+ const LLM_FAILURE_CODES = {
960
+ ABORTED: {},
961
+ ACCOUNT_QUOTA: {},
962
+ ACCOUNT_SIGN_IN_REQUIRED: {},
963
+ ACCOUNT_TOKEN_INVALID: {},
964
+ AUTH: {},
965
+ CLIENT_UPGRADE_REQUIRED: {},
966
+ CONTEXT_WINDOW_EXCEEDED: {},
967
+ DISCOVERY_FAILED: {},
968
+ DISCOVERY_UNSUPPORTED: {},
969
+ DUPLICATE_ADAPTER: {},
970
+ DUPLICATE_DIRECTORY: {},
971
+ DUPLICATE_DISCOVERY: {},
972
+ EMPTY_RESPONSE: { retryChoice: true },
973
+ FILES_API: {},
974
+ IMAGE_OFFLOAD_REQUIRED: {},
975
+ INVALID_ADAPTER: {},
976
+ INVALID_CATALOG: {},
977
+ INVALID_CONFIG: {},
978
+ INVALID_CREDENTIAL: {},
979
+ INVALID_DIRECTORY: {},
980
+ INVALID_DISCOVERY: {},
981
+ INVALID_MODEL_CONTEXT: {},
982
+ INVALID_MODEL_INFO: {},
983
+ INVALID_MODEL_MAX_TOKENS: {},
984
+ INVALID_MODEL_REASONING: {},
985
+ INVALID_PREPARED_CALL: {},
986
+ INVALID_REPLAY_STATE: {},
987
+ INVALID_REQUEST: {},
988
+ INVALID_RESPONSE: {},
989
+ MALFORMED_RESPONSE: { retryChoice: true },
990
+ MISSING_CREDENTIAL: {},
991
+ MODEL_SWITCH_COMPACTION_FAILED: {},
992
+ MODEL_UNSUPPORTED: {},
993
+ NO_ADAPTER: {},
994
+ NO_CREDENTIAL_STORE: {},
995
+ NO_DISCOVERY: {},
996
+ PI_AI_ERROR: {},
997
+ QUOTA: { retryChoice: true },
998
+ RATE_LIMIT: { retryChoice: true },
999
+ REGISTRATION_DISPOSED: {},
1000
+ REQUEST_EXTENSION: {},
1001
+ REQUEST_HEADERS: {},
1002
+ SERVER: { retryChoice: true },
1003
+ STREAM_CLOSED: { retryChoice: true },
1004
+ TIMEOUT: { retryChoice: true },
1005
+ TRANSPORT: { retryChoice: true },
1006
+ UNKNOWN: {},
1007
+ UNKNOWN_MODEL: {},
1008
+ UNSTORABLE_PROVIDER_ID: {},
1009
+ UNSUPPORTED_CONTENT: {},
1010
+ UNSUPPORTED_OPTION: {},
1011
+ UNSUPPORTED_REASONING_EFFORT: {}
1012
+ };
1013
+ /** The {@link LLM_FAILURE_CODES} entries marked as retry-policy choices, in definition order. */
1014
+ const RETRY_CODE_CHOICES = Object.freeze(Object.keys(LLM_FAILURE_CODES).filter((code) => "retryChoice" in LLM_FAILURE_CODES[code]));
946
1015
  /**
947
1016
  * Canonical provider-neutral code for a response that completed normally but
948
1017
  * carried no content blocks at all. Providers occasionally emit a degenerate
@@ -978,14 +1047,14 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
978
1047
  "TRANSPORT"
979
1048
  ]);
980
1049
  const backoffSchema = z.object({
981
- initialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
982
- maxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
1050
+ initialDelayMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
1051
+ maxDelayMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
983
1052
  jitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
984
1053
  });
985
1054
  const normalPolicySchema = z.object({
986
1055
  mode: z.const("normal").required(),
987
1056
  maxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
988
- retryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),
1057
+ retryableCodes: z.array(z.union([...RETRY_CODE_CHOICES.map((code) => z.const(code)), z.string().min(1)])).min(1).default([...DEFAULT_RETRYABLE_CODES]),
989
1058
  backoff: backoffSchema
990
1059
  });
991
1060
  const alwaysPolicySchema = z.object({
@@ -1269,27 +1338,47 @@ function withoutDeveloperMessages(messages) {
1269
1338
  const retained = messages.filter((message) => message.role !== "developer");
1270
1339
  return retained.length === messages.length ? messages : retained;
1271
1340
  }
1272
- function toolDeclarations(tools, mode, history) {
1341
+ function toolDeclarations(history) {
1273
1342
  const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
1274
1343
  for (const update of history.updates) for (const tool of update.additions) if (!declarations.has(tool.name)) declarations.set(tool.name, {
1275
1344
  ...tool,
1276
1345
  deferLoading: true
1277
1346
  });
1278
- switch (mode) {
1279
- case "in-history": return declarations;
1280
- case "addition-only": {
1281
- const activeNames = new Set(tools?.map((tool) => tool.name));
1282
- for (const name of declarations.keys()) if (!activeNames.has(name)) declarations.delete(name);
1283
- return declarations;
1347
+ return declarations;
1348
+ }
1349
+ /** Rebuild declarations on removals or additions to an empty set, where the request prefix changes. */
1350
+ function rebaseAdditionOnlyHistory(history, messages) {
1351
+ const available = new Map(history.tools.map((tool) => [tool.name, tool]));
1352
+ let baseline = history.tools;
1353
+ let retainedFrom = 0;
1354
+ for (const [index, update] of history.updates.entries()) {
1355
+ const additions = new Map(update.additions.map((tool) => [tool.name, tool]));
1356
+ let reset = available.size === 0 && additions.size > 0;
1357
+ for (const block of messages.get(update.messageId)) if (block.type === "tool-addition") {
1358
+ const { deferLoading: _loading, ...tool } = additions.get(block.toolName);
1359
+ available.set(tool.name, tool);
1360
+ } else if (block.type === "tool-removal") {
1361
+ reset = true;
1362
+ available.delete(block.toolName);
1363
+ }
1364
+ if (reset) {
1365
+ baseline = [...available.values()];
1366
+ retainedFrom = index + 1;
1284
1367
  }
1285
- /* v8 ignore next 2 -- closed-union exhaustiveness guard */
1286
- default: return assertNever(mode);
1287
1368
  }
1369
+ return retainedFrom === 0 ? history : {
1370
+ tools: baseline,
1371
+ updates: history.updates.slice(retainedFrom)
1372
+ };
1288
1373
  }
1289
1374
  /**
1290
1375
  * Construct provider declarations from session-folded history without changing logged active tools.
1291
1376
  * Unsupported routes and incomplete history use current declarations without developer updates.
1292
- * Explicitly deferred baseline tools become available only after their first retained addition.
1377
+ * Explicitly deferred declarations require an addition to activate them.
1378
+ * A rebuild makes previously activated declarations immediate; unactivated declarations stay deferred.
1379
+ * Addition-only routes rebuild when a tool is removed or tools are added to an empty set;
1380
+ * deferred declarations count as existing tools.
1381
+ * Later additions remain deferred and superseded tool blocks are omitted without dropping other content.
1293
1382
  * @param messages - complete request inputs, or the prefix selected for an auxiliary call.
1294
1383
  * @param tools - currently active tool schemas.
1295
1384
  * @param toolUpdate - the resolved route's update mode.
@@ -1309,14 +1398,16 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
1309
1398
  messages: withoutDeveloperMessages(messages),
1310
1399
  tools
1311
1400
  };
1312
- const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
1313
- if (history.updates.some((update) => !messageIds.has(update.messageId))) return {
1401
+ const updates = new Map(messages.flatMap((message) => message.role === "developer" ? [[message.id, message.content]] : []));
1402
+ if (history.updates.some((update) => !updates.has(update.messageId))) return {
1314
1403
  messages: withoutDeveloperMessages(messages),
1315
1404
  tools
1316
1405
  };
1317
- const declarations = toolDeclarations(tools, toolUpdate, history);
1406
+ const projectedHistory = toolUpdate === "addition-only" ? rebaseAdditionOnlyHistory(history, updates) : history;
1407
+ const declarations = toolDeclarations(projectedHistory);
1318
1408
  const updateIds = new Set(history.updates.map((update) => update.messageId));
1319
- const offered = new Set(history.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
1409
+ const retainedUpdateIds = new Set(projectedHistory.updates.map((update) => update.messageId));
1410
+ const offered = new Set(projectedHistory.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
1320
1411
  const projectedMessages = [];
1321
1412
  for (const message of messages) {
1322
1413
  if (message.role !== "developer") {
@@ -1327,6 +1418,7 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
1327
1418
  const content = message.content.filter((block) => {
1328
1419
  switch (block.type) {
1329
1420
  case "tool-addition":
1421
+ if (!retainedUpdateIds.has(message.id)) return false;
1330
1422
  if (!declarations.has(block.toolName) || offered.has(block.toolName)) return false;
1331
1423
  offered.add(block.toolName);
1332
1424
  return true;
@@ -1409,13 +1501,16 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
1409
1501
  /**
1410
1502
  * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
1411
1503
  * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
1504
+ * The constructor takes only a {@link BuiltinLlmFailureCode}; a failure from
1505
+ * another provider, whose code may be any string, is re-raised through
1506
+ * {@link LlmError.fromFailure}.
1412
1507
  */
1413
- var LlmError = class extends HarnessError {
1508
+ var LlmError = class LlmError extends HarnessError {
1414
1509
  /** Serializable facts retained beside this live Error. */
1415
1510
  failure;
1416
1511
  /**
1417
1512
  * @param message - non-empty human-readable failure summary.
1418
- * @param code - non-empty stable provider-neutral machine code.
1513
+ * @param code - built-in stable provider-neutral machine code.
1419
1514
  * @param options - optional cause and validated serializable provider facts.
1420
1515
  */
1421
1516
  constructor(message, code, options) {
@@ -1435,6 +1530,18 @@ var LlmError = class extends HarnessError {
1435
1530
  ...options?.offloadImages === void 0 ? {} : { offloadImages: options.offloadImages }
1436
1531
  });
1437
1532
  }
1533
+ /**
1534
+ * Raise an observed failure again with its own code, which any provider may have chosen.
1535
+ * @param failure - the serializable failure, typically from a stream's terminal chunk.
1536
+ * @param options - optional cause.
1537
+ * @returns an error carrying the failure's message, code, and provider facts.
1538
+ */
1539
+ static fromFailure(failure, options) {
1540
+ return new LlmError(failure.message, failure.code, {
1541
+ ...failure,
1542
+ ...options
1543
+ });
1544
+ }
1438
1545
  };
1439
1546
  (() => {
1440
1547
  let _classSuper = TypertRemoteService;
@@ -2253,11 +2360,6 @@ function apply(ctx, config) {
2253
2360
  const reminder = observe(exec);
2254
2361
  const downstream = await next();
2255
2362
  if (!reminder) return downstream;
2256
- if (downstream.kind === "block") return {
2257
- kind: "block",
2258
- feedback: downstream.feedback,
2259
- additionalContexts: prependContext(reminder, downstream.additionalContexts)
2260
- };
2261
2363
  return {
2262
2364
  ...downstream,
2263
2365
  additionalContexts: prependContext(reminder, downstream.additionalContexts)
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAGxC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AACzD,OAAO,QAAQ,sBAAsB,CAAC;IACpC,UAAU,gBAAgB;QACxB,sBAAsB,EAAE;YAAE,IAAI,EAAE,sBAAsB,CAAA;SAAE,GAAG,aAAa,CAAA;KACzE;CACF;AAMD,eAAO,MAAM,IAAI,yBAAyB,CAAA;AAE1C;;;;;;;;GAQG;AACH,MAAM,WAAW,MAAM;IACrB,+EAA+E;IAC/E,UAAU,CAAC,EAAE,MAAM,EAAE,CAAA;IACrB,sEAAsE;IACtE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB,6EAA6E;IAC7E,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB;;;;;;OAMG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAA;CAC/B;AAED,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAK3B,CAAA;AA2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E;QAC/E,IAAI,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC;YAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;QAClF,OAAO,IAAI,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/dsh-repeat-tool-reminder",
3
3
  "description": "Repeat-tool-call guard plugin: advisory reminders when an agent loops on identical tool calls",
4
- "version": "0.2.2-rc.1",
4
+ "version": "0.2.2-rc.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -25,26 +25,29 @@
25
25
  "files": [
26
26
  "locale/*.json",
27
27
  "lib/index.js",
28
- "lib/types/**/*.d.ts"
28
+ "lib/types/**/*.d.ts",
29
+ "lib/types/**/*.d.ts.map",
30
+ "lib/**/*.js.map",
31
+ "src"
29
32
  ],
30
33
  "license": "MIT",
31
34
  "dependencies": {
32
35
  "@deepseek-ai/schemastery": "~3.19.0"
33
36
  },
34
37
  "peerDependencies": {
35
- "@deepseek-ai/dsh-agent": "0.2.2-rc.1",
36
- "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
38
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
39
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
37
40
  "@deepseek-ai/cordis": "~4.1.0"
38
41
  },
39
42
  "devDependencies": {
40
- "@deepseek-ai/dsh-agent": "0.2.2-rc.1",
41
- "@deepseek-ai/dsh-agent-loop": "0.2.2-rc.1",
42
- "@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.1",
43
- "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
44
- "@deepseek-ai/dsh-session": "0.2.2-rc.1",
45
- "@deepseek-ai/dsh-tool-testkit": "0.2.2-rc.1",
46
- "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
43
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
44
+ "@deepseek-ai/dsh-agent-loop": "0.2.2-rc.2",
45
+ "@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.2",
46
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.2",
47
+ "@deepseek-ai/dsh-session": "0.2.2-rc.2",
48
+ "@deepseek-ai/dsh-tool-testkit": "0.2.2-rc.2",
49
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
47
50
  "@deepseek-ai/cordis": "~4.1.0",
48
- "@deepseek-ai/dsh-session-projection": "0.2.2-rc.1"
51
+ "@deepseek-ai/dsh-session-projection": "0.2.2-rc.2"
49
52
  }
50
53
  }
package/src/index.ts ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Advisory per-agent repeat-call detector. It enriches post-execute decisions
3
+ * with logged model context without vetoing or rewriting calls. Configuration
4
+ * and chain semantics live in the package README; rationale lives in the
5
+ * repeat-tool-reminder Agent Note.
6
+ * @module @deepseek-ai/dsh-repeat-tool-reminder
7
+ */
8
+
9
+ import type { Context } from '@deepseek-ai/cordis'
10
+ import z from '@deepseek-ai/schemastery'
11
+ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
12
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
13
+ import type { ContextFormed } from '@deepseek-ai/dsh-llm'
14
+ declare module '@deepseek-ai/dsh-llm' {
15
+ interface MessageSourceMap {
16
+ 'repeat-tool-reminder': { kind: 'repeat-tool-reminder' } & ContextFormed
17
+ }
18
+ }
19
+
20
+ import type { MessageSource } from '@deepseek-ai/dsh-llm'
21
+ import type { UserMessage } from '@deepseek-ai/dsh-session'
22
+ import type { PostToolDecision, ToolExecution } from '@deepseek-ai/dsh-tools'
23
+
24
+ export const name = 'repeat-tool-reminder'
25
+
26
+ /**
27
+ * Plugin config, validated by the same-named schemastery schema plus the
28
+ * load-time checks in `apply` (misconfiguration fails loud: an empty
29
+ * `thresholds` list, a non-integer, a value below 2, or a duplicate throws at
30
+ * plugin load, never a silent fall-back). `include`/`exclude` entries are
31
+ * `*`-wildcard predicates over tool names at call time, not references to
32
+ * registry entries — a pattern matching no currently registered tool is valid
33
+ * (`exclude: [mcp_*]` must stay legal in a deployment that loads no MCP tools).
34
+ */
35
+ export interface Config {
36
+ /** Consecutive-repeat counts that trigger a reminder (default `[3, 5, 8]`). */
37
+ thresholds?: number[]
38
+ /** Tool-name patterns to track; empty means every tool is tracked. */
39
+ include?: string[]
40
+ /** Tool-name patterns transparent to the chain (neither count nor reset). */
41
+ exclude?: string[]
42
+ /**
43
+ * Maximum characters of canonical arguments quoted in the DETAILED reminder
44
+ * (default 500). Large payloads (a `write` body, a long command) would
45
+ * otherwise ride into the next request unbounded — precisely in a loop
46
+ * scenario; the cap bounds the reminder, never the detection (the chain key
47
+ * always compares the FULL canonical string).
48
+ */
49
+ argumentsPreviewChars?: number
50
+ }
51
+
52
+ export const Config: z<Config> = z.object({
53
+ thresholds: z.array(z.number()).default([3, 5, 8]),
54
+ include: z.array(z.string()).default([]),
55
+ exclude: z.array(z.string()).default([]),
56
+ argumentsPreviewChars: z.number().default(500),
57
+ })
58
+
59
+ /**
60
+ * The `{kind:'repeat-tool-reminder'}` producer source stamped on every reminder
61
+ * this guard injects — the label is load-bearing (an unlabeled context would
62
+ * render as a user prompt in derived history).
63
+ */
64
+ const REMINDER_SOURCE: MessageSource = { kind: 'repeat-tool-reminder' }
65
+
66
+ /**
67
+ * The gentle first-threshold reminder. Keyed to `thresholds[0]`, not a literal
68
+ * count, so a custom first threshold keeps the gentle-then-detailed escalation.
69
+ */
70
+ const GENTLE_REMINDER =
71
+ 'You are repeating the exact same tool call with identical arguments. '
72
+ + 'Carefully analyze the previous result before calling again: if the task is '
73
+ + 'not complete, try a different approach or different arguments instead of '
74
+ + 'repeating the call.'
75
+
76
+ /** The detailed later-threshold reminder naming the tool, the run length, and the canonical arguments. */
77
+ function detailedReminder(toolName: string, count: number, canonicalArguments: string): string {
78
+ return 'Repeated tool call detected:\n'
79
+ + `- tool: ${toolName}\n`
80
+ + `- consecutive_calls: ${count}\n`
81
+ + `- arguments: ${canonicalArguments}\n`
82
+ + 'The repeated calls are not making progress. Do not call this tool with '
83
+ + 'these exact arguments again. Inspect the latest result and choose a '
84
+ + 'different action, different arguments, or finish the task if enough '
85
+ + 'evidence has been gathered.'
86
+ }
87
+
88
+ /**
89
+ * Deep key-sort of a parsed-JSON value so two argument objects that differ
90
+ * only in property order canonicalize identically. Arguments reach the guard
91
+ * as the loop's `JSON.parse` output (or its raw-string fallback for malformed
92
+ * argument JSON), so JSON's value domain is the whole input domain — no
93
+ * bigint, cycle, or `undefined` handling exists because no input path can
94
+ * produce them.
95
+ */
96
+ function sortJsonValue(value: unknown): unknown {
97
+ if (Array.isArray(value)) return value.map(sortJsonValue)
98
+ if (value !== null && typeof value === 'object') {
99
+ const record = value as Record<string, unknown>
100
+ const sorted: Record<string, unknown> = {}
101
+ for (const key of Object.keys(record).sort()) {
102
+ sorted[key] = sortJsonValue(record[key])
103
+ }
104
+ return sorted
105
+ }
106
+ return value
107
+ }
108
+
109
+ /** Canonical string form of a call's arguments: deep key-sort, then stringify. */
110
+ function canonicalize(argumentsValue: unknown): string {
111
+ return JSON.stringify(sortJsonValue(argumentsValue))
112
+ }
113
+
114
+ /** Compile one `*`-wildcard pattern to an anchored RegExp (every other regex metacharacter is matched literally). */
115
+ function wildcardToRegExp(pattern: string): RegExp {
116
+ const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, String.raw`\$&`)
117
+ return new RegExp(`^${escaped.replaceAll('*', '.*')}$`)
118
+ }
119
+
120
+ /**
121
+ * Head-truncate the canonical arguments for quoting in the detailed reminder,
122
+ * marking how much was omitted. Bounds only the model-visible text — the
123
+ * chain key always uses the full canonical string.
124
+ */
125
+ function previewArguments(canonical: string, cap: number): string {
126
+ if (canonical.length <= cap) return canonical
127
+ return `${canonical.slice(0, cap)}… (+${canonical.length - cap} more chars)`
128
+ }
129
+
130
+ /**
131
+ * Validate `thresholds` per the fail-loud contract and return them sorted
132
+ * ascending (the escalation rule reads `thresholds[0]` as the gentle tier, so
133
+ * order is normalized here, once).
134
+ */
135
+ function validateThresholds(values: number[]): number[] {
136
+ if (values.length === 0) {
137
+ throw new Error('repeat-tool-reminder: `thresholds` must not be empty')
138
+ }
139
+ for (const value of values) {
140
+ if (!Number.isInteger(value) || value < 2) {
141
+ throw new Error(`repeat-tool-reminder: invalid threshold ${value} — every threshold must be an integer >= 2`)
142
+ }
143
+ }
144
+ if (new Set(values).size !== values.length) {
145
+ throw new Error('repeat-tool-reminder: `thresholds` must not contain duplicates')
146
+ }
147
+ return [...values].sort((a, b) => a - b)
148
+ }
149
+
150
+ /**
151
+ * Prepend the guard's reminder while preserving every downstream context's
152
+ * source and metadata.
153
+ */
154
+ function prependContext(ours: UserMessage, theirs: UserMessage[] | undefined): UserMessage[] {
155
+ return [ours, ...theirs ?? []]
156
+ }
157
+
158
+ /** One agent's consecutive-repeat chain: the last tracked call's identity key and its run length. */
159
+ interface Chain {
160
+ key: string
161
+ count: number
162
+ }
163
+
164
+ /**
165
+ * Install the guard's listeners.
166
+ * @param ctx - plugin context; listeners are scoped to it and disposed with it.
167
+ * @param config - validated {@link Config}; `thresholds` is re-checked fail-loud here.
168
+ */
169
+ export function apply(ctx: Context, config: Config): void {
170
+ // schemastery's .default() guarantees the fields are set after validation.
171
+ const thresholds = validateThresholds(config.thresholds as number[])
172
+ const thresholdSet = new Set(thresholds)
173
+ const includePatterns = (config.include as string[]).map(wildcardToRegExp)
174
+ const excludePatterns = (config.exclude as string[]).map(wildcardToRegExp)
175
+ const argumentsPreviewChars = config.argumentsPreviewChars as number
176
+ if (!Number.isInteger(argumentsPreviewChars) || argumentsPreviewChars < 1) {
177
+ throw new Error(`repeat-tool-reminder: invalid argumentsPreviewChars ${argumentsPreviewChars} — must be an integer >= 1`)
178
+ }
179
+
180
+ const chains = new WeakMap<Agent, Chain>()
181
+
182
+ /** Whether a tool participates in the chain (untracked calls are transparent: they neither count nor reset). */
183
+ function tracked(toolName: string): boolean {
184
+ if (includePatterns.length > 0 && !includePatterns.some(pattern => pattern.test(toolName))) return false
185
+ return !excludePatterns.some(pattern => pattern.test(toolName))
186
+ }
187
+
188
+ /**
189
+ * Advance the calling agent's chain for one attempt and return the reminder
190
+ * to deliver, if this attempt's run length hits a configured threshold.
191
+ * Counting happens here — in post-execute — because denied calls also flow
192
+ * through this waterfall (`ToolRuntime.execute` routes a deny through the
193
+ * same pipeline), and a model hammering a denied call is exactly the loop
194
+ * worth breaking.
195
+ */
196
+ function observe(exec: ToolExecution): UserMessage | undefined {
197
+ // A direct `ctx.tools.execute()` caller has no model to remind and no id
198
+ // to key on; only agent-loop calls participate.
199
+ if (!exec.agent) return undefined
200
+ if (!tracked(exec.name)) return undefined
201
+ const canonical = canonicalize(exec.arguments)
202
+ const key = JSON.stringify([exec.name, canonical])
203
+ const chain = chains.get(exec.agent)
204
+ const count = chain !== undefined && chain.key === key ? chain.count + 1 : 1
205
+ chains.set(exec.agent, { key, count })
206
+ if (!thresholdSet.has(count)) return undefined
207
+ const text = count === thresholds[0]
208
+ ? GENTLE_REMINDER
209
+ : detailedReminder(exec.name, count, previewArguments(canonical, argumentsPreviewChars))
210
+ return createUserMessage({
211
+ content: [{ type: 'text', text }],
212
+ source: { ...REMINDER_SOURCE, form: 'notice', summary: `${exec.name} × ${count}` },
213
+ })
214
+ }
215
+
216
+ // Observe-and-enrich, never veto: count first (state advances regardless of
217
+ // the downstream outcome), DELEGATE so a later listener can still block or
218
+ // replace, then fold the reminder onto whatever came back — additionalContexts
219
+ // rides both decision variants, so a blocked call still gets the nudge.
220
+ ctx.on('tools/post-execute', async (exec, _result, next): Promise<PostToolDecision> => {
221
+ const reminder = observe(exec)
222
+ const downstream = await next()
223
+ if (!reminder) return downstream
224
+ return { ...downstream, additionalContexts: prependContext(reminder, downstream.additionalContexts) }
225
+ })
226
+
227
+ // A user interjection changes the context; repetition across it is not a
228
+ // loop. Pure reset hook: always delegates (attaching nothing, vetoing
229
+ // nothing).
230
+ ctx.on('agent/pre-step', ({ agent, messages }, next): Promise<PreStepDecision> => {
231
+ if (messages.some(message => message.source.kind === 'user')) chains.delete(agent)
232
+ return next()
233
+ })
234
+ }