@yasaswy.nagavolu/agents 0.26.9 → 0.26.11

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.
@@ -24,6 +24,15 @@
24
24
  "effort": "high",
25
25
  "roleEffort": {},
26
26
  "escalationSignal": "NEEDS_WORKER:",
27
+ "escalationPhrases": [
28
+ "^((this|the|that|my) (task|work|job|request|step) |this |it )?(needs|requires)[ _]+(a[ _]+|the[ _]+)?worker\\b",
29
+ "^needs?[ _]+worker\\b",
30
+ "^(i'?m |i am )?(hand(ing)?|pass(ing)?|send(ing)?)( this| it| the task)?( off| over| back)? to (the |a )?worker\\b",
31
+ "^(re-?dispatch|escalat(e|ing))( this| it| the task)? to (the |a )?worker\\b",
32
+ "^(this )?(task )?(is )?(out of|outside)( my| the)?( assistant)? (role|scope)\\b.*\\bworker\\b",
33
+ "^(a |the )?worker (is |will be )?(needed|required|should (do|take|handle))\\b"
34
+ ],
35
+ "escalationNegation": "\\b(not|n't|no longer)\\s+(be\\s+)?(needed|required|necessary)\\b|\\bno need\\b",
27
36
  "roleBrief": {
28
37
  "assistant": {
29
38
  "scope": ["research gathering", "file, log and code reading and triage", "running checks and reporting", "summaries and drafts", "classification and extraction", "git and GitLab chores", "browser and UI checks", "bulk edits that have an exact spec"],
@@ -52,6 +52,7 @@ The guard stays. It owns what the mod cannot do: name injection, `agent_dispatch
52
52
  | Routing logic and hook wiring (node, no network) | `node --test mods/model-routing/tests/*.test.mjs` (also runs in pytest: `proxy/tests/test_model_routing_mod.py`) |
53
53
  | Headless proof with a real subagent per case | `python mods/model-routing/tests/e2e/run_e2e.py [--guard]` |
54
54
  | Headless proof of effort, role brief, re-route, escalation, ledger and audit | `python mods/model-routing/tests/e2e/run_routing_e2e.py [--no-mod]` |
55
+ | Headless proof that a duplicate dispatch name is renamed `<name>-2` in the log, ledger and subagent | `python mods/model-routing/tests/e2e/run_routing_e2e.py --dup` |
55
56
  | Headless proof of the fork rule (`CLAUDE_CODE_FORK_SUBAGENT=1`; main-chat parent denied, assistant parent allowed) | `python mods/model-routing/tests/e2e/run_routing_e2e.py --fork` |
56
57
  | Guard-vs-mod role drift | `python -m pytest proxy/tests/test_routing_drift.py` |
57
58
  | Engine tests with stubbed Claude answers (needs claude 2.1.287+) | `claude plugin test mods/model-routing` (`tests/*.test.ts`; also run by `tools/tests/test_mod_plugin_tests.py`) |
@@ -6,6 +6,7 @@ Every sink (dispatch log, mod records, pending files, ledger) is redirected into
6
6
 
7
7
  python mods/model-routing/tests/e2e/run_routing_e2e.py full scenario
8
8
  python mods/model-routing/tests/e2e/run_routing_e2e.py --no-mod the mod is not loaded: proves the loud flag
9
+ python mods/model-routing/tests/e2e/run_routing_e2e.py --dup two dispatches with one name: the second is logged and addressed as <name>-2
9
10
  python mods/model-routing/tests/e2e/run_routing_e2e.py --fork a fork on a main-chat parent is denied, a fork on the assistant parent is not
10
11
  """
11
12
  import json
@@ -42,6 +43,11 @@ FORK_PROMPT = (
42
43
  "Make one Agent tool call: name f1, subagent_type fork, prompt 'Reply DONE.'. Then print its reply, or the error if the call was refused."
43
44
  )
44
45
 
46
+ DUP_PROMPT = (
47
+ "Make two Agent tool calls one after another, never in parallel, both with name dup1 and subagent_type general-purpose, "
48
+ "prompt 'Reply DONE.'. Then print the name each call reports."
49
+ )
50
+
45
51
  NO_MOD_PROMPT = (
46
52
  "Make one Agent tool call: name m1, subagent_type general-purpose, prompt 'Reply DONE.'. Then print its reply."
47
53
  )
@@ -200,6 +206,21 @@ def check_no_mod(sandbox: Path, result: dict) -> list:
200
206
  return problems
201
207
 
202
208
 
209
+ def check_dup(sandbox: Path, result: dict) -> list:
210
+ problems = []
211
+ names = [r["name"] for r in jsonl(sandbox / "agent_dispatch.jsonl") if not r.get("kind")]
212
+ if names != ["dup1", "dup1-2"]:
213
+ problems.append(f"dispatch log names are {names}, expected ['dup1', 'dup1-2']")
214
+ events = [r.get("agent_name") for r in ledger(sandbox) if r.get("record_type") == "routing"]
215
+ if events != ["dup1", "dup1-2"]:
216
+ problems.append(f"ledger routing events carry {events}, expected ['dup1', 'dup1-2']")
217
+ ids = [r.get("agent_id") for r in ledger(sandbox) if r.get("record_type") == "routing"]
218
+ probed = {r.get("agent_id") for r in jsonl(sandbox / "probe.jsonl")}
219
+ if len(set(ids)) != 2 or not set(ids) <= probed:
220
+ problems.append(f"the two dispatches are not two distinct stopped subagents: ledger ids {ids}, stopped {sorted(probed)}")
221
+ return problems
222
+
223
+
203
224
  def run_fork_scenarios() -> int:
204
225
  cfg = json.loads(CONFIG.read_text(encoding="utf-8"))
205
226
  failed = False
@@ -221,6 +242,15 @@ def run_fork_scenarios() -> int:
221
242
  def main(argv: list) -> int:
222
243
  if "--fork" in argv:
223
244
  return run_fork_scenarios()
245
+ if "--dup" in argv:
246
+ sandbox = Path(tempfile.mkdtemp(prefix="routing-e2e-dup-"))
247
+ result = run_claude(sandbox, DUP_PROMPT, True)
248
+ problems = check_dup(sandbox, result) if result.get("session_id") else ["claude run failed"]
249
+ print(json.dumps({"mode": "dup", "sandbox": str(sandbox), "answer": result.get("result", "")[:300]}, indent=1))
250
+ for p in problems:
251
+ print("FAIL", p)
252
+ print("PASS" if not problems else "FAILED")
253
+ return 1 if problems else 0
224
254
  with_mod = "--no-mod" not in argv
225
255
  sandbox = Path(tempfile.mkdtemp(prefix="routing-e2e-"))
226
256
  result = run_claude(sandbox, FULL_PROMPT if with_mod else NO_MOD_PROMPT, with_mod)
@@ -327,6 +327,66 @@ def _log_dispatch(session_id: str, name: str, subagent_type: str, model: str | N
327
327
  _record_dispatch_error(log_path, exc)
328
328
 
329
329
 
330
+ def _lock_path() -> str:
331
+ return _dispatch_log_path() + ".lock"
332
+
333
+
334
+ class _NameLock:
335
+ """Short exclusive lock around "pick a free name, then log it", so two concurrent hooks cannot both take the same name. Fails open after ~2 s."""
336
+
337
+ def __enter__(self):
338
+ self.path, self.held = _lock_path(), False
339
+ deadline = time.time() + 2.0
340
+ while time.time() < deadline:
341
+ try:
342
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
343
+ os.close(os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
344
+ self.held = True
345
+ break
346
+ except FileExistsError:
347
+ try:
348
+ if time.time() - os.path.getmtime(self.path) > 10:
349
+ os.remove(self.path)
350
+ except OSError:
351
+ pass
352
+ time.sleep(0.02)
353
+ except OSError:
354
+ break
355
+ return self
356
+
357
+ def __exit__(self, *exc):
358
+ if self.held:
359
+ try:
360
+ os.remove(self.path)
361
+ except OSError:
362
+ pass
363
+
364
+
365
+ def unique_session_name(session_id: str, name: str) -> str:
366
+ """`name`, or `<name>-<n>` (n from 2, the form Claude Code uses) when this session's dispatch log already holds `name`."""
367
+ if not session_id or not name:
368
+ return name
369
+ taken = set()
370
+ try:
371
+ with open(_dispatch_log_path(), "r", encoding="utf-8") as fh:
372
+ for line in fh:
373
+ try:
374
+ row = json.loads(line)
375
+ except ValueError:
376
+ continue
377
+ if isinstance(row, dict) and row.get("session_id") == session_id and isinstance(row.get("name"), str):
378
+ taken.add(row["name"])
379
+ except OSError:
380
+ return name
381
+ if name not in taken:
382
+ return name
383
+ base = name[: _NAME_MAX_LEN - 4].rstrip("-_") if len(name) > _NAME_MAX_LEN - 4 else name
384
+ n = 2
385
+ while f"{base}-{n}" in taken:
386
+ n += 1
387
+ return f"{base}-{n}"
388
+
389
+
330
390
  def _deny(reason: str) -> None:
331
391
  print(json.dumps({
332
392
  "hookSpecificOutput": {
@@ -511,17 +571,26 @@ def _safe_main() -> None:
511
571
  if unhandled and routing_log.mod_installed() and routing_log.warn_once(str(data.get("session_id") or "")):
512
572
  notes.append(routing_log.unhandled_warning(unhandled))
513
573
 
514
- _log_dispatch(str(data.get("session_id") or ""), corrected["name"], eff_type,
515
- (models_config.role_model(cfg, dispatch_role) if cfg and dispatch_role != "other" else None)
516
- or models_config.base_id(effective_model_final) or None, dispatch_role,
517
- extra={
518
- "tool_use_id": data.get("tool_use_id"),
519
- "requested_model": tool_input.get("model") or None,
520
- "effort": corrected.get("effort"),
521
- "header": header_applied,
522
- "reroute": reroute_reason,
523
- "registered": is_registered,
524
- })
574
+ session_for_log = str(data.get("session_id") or "")
575
+ with _NameLock():
576
+ chosen = unique_session_name(session_for_log, corrected["name"])
577
+ if chosen != corrected["name"]:
578
+ notes.append(
579
+ f"renamed duplicate name '{corrected['name']}' to '{chosen}' (the name is already used in this session) "
580
+ f"— address this subagent by '{chosen}'"
581
+ )
582
+ corrected["name"] = chosen
583
+ _log_dispatch(session_for_log, corrected["name"], eff_type,
584
+ (models_config.role_model(cfg, dispatch_role) if cfg and dispatch_role != "other" else None)
585
+ or models_config.base_id(effective_model_final) or None, dispatch_role,
586
+ extra={
587
+ "tool_use_id": data.get("tool_use_id"),
588
+ "requested_model": tool_input.get("model") or None,
589
+ "effort": corrected.get("effort"),
590
+ "header": header_applied,
591
+ "reroute": reroute_reason,
592
+ "registered": is_registered,
593
+ })
525
594
 
526
595
  # ------------------------------------------------------------------
527
596
  # FAIL-SAFE PHASE — denials, evaluated against the CORRECTED dispatch.
@@ -70,3 +70,16 @@ def out_of_scope_reason(cfg: dict | None, prompt: str) -> str | None:
70
70
  def escalation_signal(cfg: dict | None) -> str | None:
71
71
  signal = (cfg or {}).get("escalationSignal")
72
72
  return signal if isinstance(signal, str) and signal else None
73
+
74
+
75
+ def _compile(pattern) -> "re.Pattern | None":
76
+ try:
77
+ return re.compile(pattern, re.IGNORECASE) if isinstance(pattern, str) and pattern else None
78
+ except re.error:
79
+ return None
80
+
81
+
82
+ def escalation_matchers(cfg: dict | None) -> tuple[list, "re.Pattern | None"]:
83
+ """(informal first-line patterns, negation pattern) from models.json `escalationPhrases` / `escalationNegation`; bad entries are skipped."""
84
+ phrases = [c for c in (_compile(p) for p in ((cfg or {}).get("escalationPhrases") or [])) if c]
85
+ return phrases, _compile((cfg or {}).get("escalationNegation"))
@@ -30,14 +30,22 @@ import routing_brief
30
30
  import routing_log
31
31
 
32
32
 
33
- def escalation_reason(message: str, signal: str | None) -> str | None:
34
- """The reason when the first non-empty line of `message` starts with the signal, else None."""
35
- if not signal or not isinstance(message, str):
33
+ def escalation_reason(message: str, signal: str | None, phrases: list | None = None, negation=None) -> str | None:
34
+ """The reason when the first non-empty line of `message` starts with the strict signal, or reads as an informal
35
+ "needs a worker" hand-off (models.json `escalationPhrases`, unless it matches `escalationNegation`); else None."""
36
+ if not isinstance(message, str):
36
37
  return None
37
38
  for line in message.splitlines():
38
39
  line = line.strip()
39
- if line:
40
- return line[len(signal):].strip() or "(no reason given)" if line.startswith(signal) else None
40
+ if not line:
41
+ continue
42
+ if signal and line.startswith(signal):
43
+ return line[len(signal):].strip() or "(no reason given)"
44
+ if negation is not None and negation.search(line):
45
+ return None
46
+ if any(p.search(line) for p in phrases or []):
47
+ return line[:300]
48
+ return None
41
49
  return None
42
50
 
43
51
 
@@ -49,7 +57,8 @@ def _pending_path(session_id: str) -> str:
49
57
  def record_escalation(payload: dict) -> bool:
50
58
  cfg = models_config.load()
51
59
  signal = routing_brief.escalation_signal(cfg)
52
- reason = escalation_reason(payload.get("last_assistant_message"), signal)
60
+ phrases, negation = routing_brief.escalation_matchers(cfg)
61
+ reason = escalation_reason(payload.get("last_assistant_message"), signal, phrases, negation)
53
62
  if reason is None:
54
63
  return False
55
64
  session_id = payload.get("session_id") or ""
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yasaswy.nagavolu/agents",
3
- "version": "0.26.9",
3
+ "version": "0.26.11",
4
4
  "description": "CLI for installing the yasaswy.nagavolu agent/skill/hook bundle. `install` opens an interactive bundle menu in a TTY (or `--bundle <key> --yes` for non-interactive installs), with hash-tracked idempotent deploys, automatic hook wiring into settings.json, and masked secret prompting. `update` reconciles installed bundles against the current source (hash-tracked: silent overwrite, conflict diff+prompt, or --theirs/--keep-mine). `uninstall` removes a bundle's files and wiring. `secrets` re-runs secret prompting for already-installed bundles.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",