@unieai/rabi-repeat-tool-reminder 0.2.1-rc.3 → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js 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 @unieai/rabi-llm/error
929
+ * @module @unieai/rabi-error
930
930
  */
931
931
  /**
932
932
  * Base class for all harness errors. Carries a `code` (stable, programmatic —
@@ -943,6 +943,76 @@ 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 `@unieai/rabi-error` and is re-exported here, so both
951
+ * import paths name the same class.
952
+ * @module @unieai/rabi-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
+ CONTENT_REFUSED: {},
967
+ CONTEXT_WINDOW_EXCEEDED: {},
968
+ DISCOVERY_FAILED: {},
969
+ DISCOVERY_UNSUPPORTED: {},
970
+ DUPLICATE_ADAPTER: {},
971
+ DUPLICATE_DIRECTORY: {},
972
+ DUPLICATE_DISCOVERY: {},
973
+ EMPTY_RESPONSE: { retryChoice: true },
974
+ FILES_API: {},
975
+ IMAGE_OFFLOAD_REQUIRED: {},
976
+ INVALID_ADAPTER: {},
977
+ INVALID_CATALOG: {},
978
+ INVALID_CONFIG: {},
979
+ INVALID_CREDENTIAL: {},
980
+ INVALID_DIRECTORY: {},
981
+ INVALID_DISCOVERY: {},
982
+ INVALID_MODEL_CONTEXT: {},
983
+ INVALID_MODEL_INFO: {},
984
+ INVALID_MODEL_MAX_TOKENS: {},
985
+ INVALID_MODEL_REASONING: {},
986
+ INVALID_PREPARED_CALL: {},
987
+ INVALID_REPLAY_STATE: {},
988
+ INVALID_REQUEST: {},
989
+ INVALID_RESPONSE: {},
990
+ MALFORMED_RESPONSE: { retryChoice: true },
991
+ MISSING_CREDENTIAL: {},
992
+ MODEL_SWITCH_COMPACTION_FAILED: {},
993
+ MODEL_UNSUPPORTED: {},
994
+ NO_ADAPTER: {},
995
+ NO_CREDENTIAL_STORE: {},
996
+ NO_DISCOVERY: {},
997
+ PI_AI_ERROR: {},
998
+ QUOTA: { retryChoice: true },
999
+ RATE_LIMIT: { retryChoice: true },
1000
+ REGISTRATION_DISPOSED: {},
1001
+ REQUEST_EXTENSION: {},
1002
+ REQUEST_HEADERS: {},
1003
+ SERVER: { retryChoice: true },
1004
+ STREAM_CLOSED: { retryChoice: true },
1005
+ TIMEOUT: { retryChoice: true },
1006
+ TRANSPORT: { retryChoice: true },
1007
+ UNKNOWN: {},
1008
+ UNKNOWN_MODEL: {},
1009
+ UNSTORABLE_PROVIDER_ID: {},
1010
+ UNSUPPORTED_CONTENT: {},
1011
+ UNSUPPORTED_OPTION: {},
1012
+ UNSUPPORTED_REASONING_EFFORT: {}
1013
+ };
1014
+ /** The {@link LLM_FAILURE_CODES} entries marked as retry-policy choices, in definition order. */
1015
+ const RETRY_CODE_CHOICES = Object.freeze(Object.keys(LLM_FAILURE_CODES).filter((code) => "retryChoice" in LLM_FAILURE_CODES[code]));
946
1016
  /**
947
1017
  * Canonical provider-neutral code for a response that completed normally but
948
1018
  * carried no content blocks at all. Providers occasionally emit a degenerate
@@ -978,14 +1048,14 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
978
1048
  "TRANSPORT"
979
1049
  ]);
980
1050
  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),
1051
+ initialDelayMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
1052
+ maxDelayMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
983
1053
  jitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
984
1054
  });
985
1055
  const normalPolicySchema = z.object({
986
1056
  mode: z.const("normal").required(),
987
1057
  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]),
1058
+ retryableCodes: z.array(z.union([...RETRY_CODE_CHOICES.map((code) => z.const(code)), z.string().min(1)])).min(1).default([...DEFAULT_RETRYABLE_CODES]),
989
1059
  backoff: backoffSchema
990
1060
  });
991
1061
  const alwaysPolicySchema = z.object({
@@ -1269,27 +1339,47 @@ function withoutDeveloperMessages(messages) {
1269
1339
  const retained = messages.filter((message) => message.role !== "developer");
1270
1340
  return retained.length === messages.length ? messages : retained;
1271
1341
  }
1272
- function toolDeclarations(tools, mode, history) {
1342
+ function toolDeclarations(history) {
1273
1343
  const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
1274
1344
  for (const update of history.updates) for (const tool of update.additions) if (!declarations.has(tool.name)) declarations.set(tool.name, {
1275
1345
  ...tool,
1276
1346
  deferLoading: true
1277
1347
  });
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;
1348
+ return declarations;
1349
+ }
1350
+ /** Rebuild declarations on removals or additions to an empty set, where the request prefix changes. */
1351
+ function rebaseAdditionOnlyHistory(history, messages) {
1352
+ const available = new Map(history.tools.map((tool) => [tool.name, tool]));
1353
+ let baseline = history.tools;
1354
+ let retainedFrom = 0;
1355
+ for (const [index, update] of history.updates.entries()) {
1356
+ const additions = new Map(update.additions.map((tool) => [tool.name, tool]));
1357
+ let reset = available.size === 0 && additions.size > 0;
1358
+ for (const block of messages.get(update.messageId)) if (block.type === "tool-addition") {
1359
+ const { deferLoading: _loading, ...tool } = additions.get(block.toolName);
1360
+ available.set(tool.name, tool);
1361
+ } else if (block.type === "tool-removal") {
1362
+ reset = true;
1363
+ available.delete(block.toolName);
1364
+ }
1365
+ if (reset) {
1366
+ baseline = [...available.values()];
1367
+ retainedFrom = index + 1;
1284
1368
  }
1285
- /* v8 ignore next 2 -- closed-union exhaustiveness guard */
1286
- default: return assertNever(mode);
1287
1369
  }
1370
+ return retainedFrom === 0 ? history : {
1371
+ tools: baseline,
1372
+ updates: history.updates.slice(retainedFrom)
1373
+ };
1288
1374
  }
1289
1375
  /**
1290
1376
  * Construct provider declarations from session-folded history without changing logged active tools.
1291
1377
  * Unsupported routes and incomplete history use current declarations without developer updates.
1292
- * Explicitly deferred baseline tools become available only after their first retained addition.
1378
+ * Explicitly deferred declarations require an addition to activate them.
1379
+ * A rebuild makes previously activated declarations immediate; unactivated declarations stay deferred.
1380
+ * Addition-only routes rebuild when a tool is removed or tools are added to an empty set;
1381
+ * deferred declarations count as existing tools.
1382
+ * Later additions remain deferred and superseded tool blocks are omitted without dropping other content.
1293
1383
  * @param messages - complete request inputs, or the prefix selected for an auxiliary call.
1294
1384
  * @param tools - currently active tool schemas.
1295
1385
  * @param toolUpdate - the resolved route's update mode.
@@ -1309,14 +1399,16 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
1309
1399
  messages: withoutDeveloperMessages(messages),
1310
1400
  tools
1311
1401
  };
1312
- const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
1313
- if (history.updates.some((update) => !messageIds.has(update.messageId))) return {
1402
+ const updates = new Map(messages.flatMap((message) => message.role === "developer" ? [[message.id, message.content]] : []));
1403
+ if (history.updates.some((update) => !updates.has(update.messageId))) return {
1314
1404
  messages: withoutDeveloperMessages(messages),
1315
1405
  tools
1316
1406
  };
1317
- const declarations = toolDeclarations(tools, toolUpdate, history);
1407
+ const projectedHistory = toolUpdate === "addition-only" ? rebaseAdditionOnlyHistory(history, updates) : history;
1408
+ const declarations = toolDeclarations(projectedHistory);
1318
1409
  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));
1410
+ const retainedUpdateIds = new Set(projectedHistory.updates.map((update) => update.messageId));
1411
+ const offered = new Set(projectedHistory.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
1320
1412
  const projectedMessages = [];
1321
1413
  for (const message of messages) {
1322
1414
  if (message.role !== "developer") {
@@ -1327,6 +1419,7 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
1327
1419
  const content = message.content.filter((block) => {
1328
1420
  switch (block.type) {
1329
1421
  case "tool-addition":
1422
+ if (!retainedUpdateIds.has(message.id)) return false;
1330
1423
  if (!declarations.has(block.toolName) || offered.has(block.toolName)) return false;
1331
1424
  offered.add(block.toolName);
1332
1425
  return true;
@@ -1409,13 +1502,16 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
1409
1502
  /**
1410
1503
  * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
1411
1504
  * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
1505
+ * The constructor takes only a {@link BuiltinLlmFailureCode}; a failure from
1506
+ * another provider, whose code may be any string, is re-raised through
1507
+ * {@link LlmError.fromFailure}.
1412
1508
  */
1413
- var LlmError = class extends HarnessError {
1509
+ var LlmError = class LlmError extends HarnessError {
1414
1510
  /** Serializable facts retained beside this live Error. */
1415
1511
  failure;
1416
1512
  /**
1417
1513
  * @param message - non-empty human-readable failure summary.
1418
- * @param code - non-empty stable provider-neutral machine code.
1514
+ * @param code - built-in stable provider-neutral machine code.
1419
1515
  * @param options - optional cause and validated serializable provider facts.
1420
1516
  */
1421
1517
  constructor(message, code, options) {
@@ -1435,6 +1531,18 @@ var LlmError = class extends HarnessError {
1435
1531
  ...options?.offloadImages === void 0 ? {} : { offloadImages: options.offloadImages }
1436
1532
  });
1437
1533
  }
1534
+ /**
1535
+ * Raise an observed failure again with its own code, which any provider may have chosen.
1536
+ * @param failure - the serializable failure, typically from a stream's terminal chunk.
1537
+ * @param options - optional cause.
1538
+ * @returns an error carrying the failure's message, code, and provider facts.
1539
+ */
1540
+ static fromFailure(failure, options) {
1541
+ return new LlmError(failure.message, failure.code, {
1542
+ ...failure,
1543
+ ...options
1544
+ });
1545
+ }
1438
1546
  };
1439
1547
  (() => {
1440
1548
  let _classSuper = TypertRemoteService;
@@ -1769,12 +1877,17 @@ var LlmError = class extends HarnessError {
1769
1877
  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 !== void 0 && typeof model.description !== "string" || seen.has(model.id)) throw new LlmError(`adapter returned invalid or duplicate model metadata for provider "${provider}"`, "INVALID_CATALOG");
1770
1878
  seen.add(model.id);
1771
1879
  const inputModalities = this.detachedModalities(model.inputModalities);
1880
+ const badge = model.badge;
1772
1881
  return {
1773
1882
  provider: model.provider,
1774
1883
  id: model.id,
1775
1884
  name: model.name,
1776
1885
  ...model.description === void 0 ? {} : { description: model.description },
1777
- ...inputModalities === void 0 ? {} : { inputModalities }
1886
+ ...inputModalities === void 0 ? {} : { inputModalities },
1887
+ ...badge === void 0 ? {} : { badge: {
1888
+ text: typeof badge.text === "string" ? badge.text : { ...badge.text },
1889
+ tone: badge.tone
1890
+ } }
1778
1891
  };
1779
1892
  });
1780
1893
  }
@@ -2248,11 +2361,6 @@ function apply(ctx, config) {
2248
2361
  const reminder = observe(exec);
2249
2362
  const downstream = await next();
2250
2363
  if (!reminder) return downstream;
2251
- if (downstream.kind === "block") return {
2252
- kind: "block",
2253
- feedback: downstream.feedback,
2254
- additionalContexts: prependContext(reminder, downstream.additionalContexts)
2255
- };
2256
2364
  return {
2257
2365
  ...downstream,
2258
2366
  additionalContexts: prependContext(reminder, downstream.additionalContexts)
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Erinnerung an Werkzeugaufruf wiederholen",
4
+ "description": "Fordern Sie die KI auf, ihren Ansatz anzupassen, wenn sie wiederholt dieselben Toolaufrufe ausführt."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Repetir recordatorio de llamada de herramienta",
4
+ "description": "Solicite a la IA que ajuste su enfoque cuando realice repetidamente las mismas llamadas a herramientas."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Répéter le rappel d'appel d'outil",
4
+ "description": "Inviter l’IA à ajuster son approche lorsqu’elle exécute à plusieurs reprises les mêmes appels d’outil."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "ツール呼び出しの繰り返し通知",
4
+ "description": "AI が同じツール呼び出しを繰り返した場合に、方法の調整を促します。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Repetir lembrete de chamada de ferramenta",
4
+ "description": "Solicite à IA que ajuste sua abordagem quando executar repetidamente as mesmas chamadas de ferramenta."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Напоминание о повторном вызове инструмента",
4
+ "description": "Попросите ИИ скорректировать свой подход, когда он неоднократно выполняет одни и те же вызовы инструментов."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-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.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -21,15 +21,18 @@
21
21
  "locale/*.json",
22
22
  "lib/index.js",
23
23
  "lib/types/**/*.d.ts",
24
+ "lib/types/**/*.d.ts.map",
25
+ "lib/**/*.js.map",
26
+ "src",
24
27
  "README.md"
25
28
  ],
26
29
  "license": "MIT",
27
30
  "dependencies": {
28
- "@unieai/schemastery": "3.18.5"
31
+ "@unieai/schemastery": "3.19.0"
29
32
  },
30
33
  "peerDependencies": {
31
- "@unieai/rabi-agent": "0.2.1-rc.3",
32
- "@unieai/rabi-tools": "0.2.1-rc.3",
33
- "@unieai/cordis": "4.0.5"
34
+ "@unieai/rabi-agent": "0.2.2-rc.5",
35
+ "@unieai/rabi-tools": "0.2.2-rc.5",
36
+ "@unieai/cordis": "4.1.0"
34
37
  }
35
38
  }
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 @unieai/rabi-repeat-tool-reminder
7
+ */
8
+
9
+ import type { Context } from '@unieai/cordis'
10
+ import z from '@unieai/schemastery'
11
+ import type { Agent, PreStepDecision } from '@unieai/rabi-agent'
12
+ import { createUserMessage } from '@unieai/rabi-llm'
13
+ import type { ContextFormed } from '@unieai/rabi-llm'
14
+ declare module '@unieai/rabi-llm' {
15
+ interface MessageSourceMap {
16
+ 'repeat-tool-reminder': { kind: 'repeat-tool-reminder' } & ContextFormed
17
+ }
18
+ }
19
+
20
+ import type { MessageSource } from '@unieai/rabi-llm'
21
+ import type { UserMessage } from '@unieai/rabi-session'
22
+ import type { PostToolDecision, ToolExecution } from '@unieai/rabi-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
+ }