File size: 45,873 Bytes
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15055bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f1470
15055bb
d6f1470
6d35eb4
 
15055bb
 
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d35eb4
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d35eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15055bb
d6f1470
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#!/usr/bin/env python3
"""Simulated tool world + verifiable tasks for agent-loop SFT data (Zenyx-Mini).  Pure python, no model, no network.

A task = (system prompt, tool schemas, first user message, a World with real tool behaviour, scripted user replies, a judge).  The agent (a local LLM) acts in a loop; every tool call is EXECUTED by the World, so the
observations are real (including errors, empty results, pending jobs).  judge(...) decides from the world state and the transcript whether the rollout really succeeded; only those rows are accepted.
Message format = the training format of zenyx100m/chat.py: assistant tool calls are ONLY `<tool_call>[{"name":..,"arguments":{..}}]</tool_call>`, results are `tool` messages (raw text)."""
import ast, json, operator, random, re

TOOL_RX = re.compile(r"^<tool_call>\s*\[.*\]\s*</tool_call>$", re.S)
BAD_TEXT = re.compile(r"<think>|</think>|<tool_response>|</tool_response>|<\|im_|^\s*(TOOL|ASSISTANT|USER|SYSTEM)\s*:|as an ai\b|language model developed by|\bopenai\b|\banthropic\b|\bqwen\b|\bchatgpt\b|\bspark\b|xhtoken|\bgemini\b|\bclaude\b", re.I | re.M)
NEG = ("no ", "not ", "n't", "couldn't", "unable", "cannot", "can't", "nothing", "none", "unfortunately", "sorry", "failed", "error")


def T(name, desc, props, req):
    return {"type": "function", "function": {"name": name, "description": desc, "parameters": {"type": "object", "properties": props, "required": req}}}


S = lambda d="": {"type": "string", "description": d}
SCHEMAS = {
    "calculator": T("calculator", "Evaluate an arithmetic expression exactly and return the result.", {"expression": S("e.g. (12 + 5) * 3")}, ["expression"]),
    "convert_units": T("convert_units", "Convert a value between two units (km, miles, kg, pounds, celsius, fahrenheit, meters, feet, liters, gallons).",
                       {"value": {"type": "number"}, "from_unit": S(), "to_unit": S()}, ["value", "from_unit", "to_unit"]),
    "get_weather": T("get_weather", "Get the current weather for a city.", {"city": S("city name")}, ["city"]),
    "get_time": T("get_time", "Get the current local time in an IANA timezone.", {"timezone": S("e.g. Asia/Tokyo")}, ["timezone"]),
    "list_dir": T("list_dir", "List the files in a directory.", {"path": S("directory, use . for the current one")}, ["path"]),
    "read_file": T("read_file", "Read a text file and return its content.", {"path": S("file path")}, ["path"]),
    "write_file": T("write_file", "Write text to a file (creates or overwrites it).", {"path": S("file path"), "content": S("text to write")}, ["path", "content"]),
    "delete_file": T("delete_file", "Permanently delete a file.", {"path": S("file path")}, ["path"]),
    "send_email": T("send_email", "Send an email.", {"to": S("recipient address"), "subject": S(), "body": S()}, ["to", "subject", "body"]),
    "create_event": T("create_event", "Create a calendar event.", {"title": S(), "date": S("YYYY-MM-DD or a weekday"), "time": S("e.g. 16:30")}, ["title", "date", "time"]),
    "lookup_order": T("lookup_order", "Look up an order by its id.", {"order_id": S()}, ["order_id"]),
    "get_customer": T("get_customer", "Get a customer record by customer id.", {"customer_id": S()}, ["customer_id"]),
    "start_job": T("start_job", "Start a long-running job and return a job id.", {"task": S("what to run")}, ["task"]),
    "check_job": T("check_job", "Check the status (and result) of a job.", {"job_id": S()}, ["job_id"]),
}
CITIES = ["Pune", "Oslo", "Lima", "Kyoto", "Cairo", "Dublin", "Nairobi", "Lagos", "Hanoi", "Quito", "Bergen", "Porto", "Kolkata", "Mumbai", "Chennai", "Delhi", "Seoul", "Perth", "Austin", "Denver", "Boston",
          "Vienna", "Prague", "Warsaw", "Athens", "Madrid", "Lisbon", "Tunis", "Accra", "Dhaka", "Manila", "Jakarta", "Bogota", "Santiago", "Montreal", "Calgary", "Reykjavik", "Tallinn", "Riga", "Zagreb"]
CONDS = ["sunny", "cloudy", "light rain", "clear", "foggy", "windy", "partly cloudy", "thunderstorms", "drizzle", "overcast"]
TZS = ["Asia/Kolkata", "Europe/London", "America/New_York", "Asia/Tokyo", "Australia/Sydney", "Europe/Berlin", "America/Los_Angeles", "Asia/Dubai"]
NAMES = ["Ravi", "Maya", "Sam", "Anika", "Tom", "Leila", "Omar", "Priya", "Ben", "Zoe", "Arjun", "Mira", "Jon", "Isha", "Karan", "Nina", "Dev", "Sara", "Luis", "Hana", "Ivan", "Tara", "Noah", "Rhea", "Kabir", "Elena", "Yusuf", "Aditi"]
TOPICS = ["groceries", "todo", "ideas", "meeting", "travel", "budget", "recipes", "books", "workout", "gifts", "plants", "shopping", "project", "reading", "garden", "movies", "taxes", "invoices", "contacts", "diary",
          "lyrics", "poems", "chores", "trip", "wishlist", "homework", "exams", "bills", "party", "camping", "fitness", "studying", "pets", "cooking", "errands", "goals", "schedule", "packing", "repairs", "birthdays"]
ITEMS = ["rice", "milk", "eggs", "bread", "tea", "apples", "onions", "oil", "salt", "lentils", "butter", "soap", "coffee", "flour", "tomatoes"]
SYSTEMS = [("You are Zenyx-Mini, nickname Nini, a friendly and helpful small assistant. Use tools only when they are needed.", 4), ("You are Zenyx-Mini, nickname Nini. Keep answers short.", 3),
           ("You are Zenyx-Mini, a helpful and precise assistant.", 2), ("You are a helpful assistant. Use the tools when they help, and report their results exactly.", 2), (None, 2)]


class World:
    def __init__(self, rng):
        self.rng = rng; self.fs = {}; self.weather = {}; self.times = {}; self.orders = {}; self.customers = {}; self.jobs = {}; self.outbox = []; self.events = []
        self.log = []; self.fail_next = {}; self.always_fail = {}; self.job_polls = {}

    # ------------------------------------------------------------------ tools
    def call(self, name, args):
        sch = SCHEMAS.get(name)
        if sch is None: out = f"Error: unknown tool '{name}'."
        elif not isinstance(args, dict): out = f"Error: arguments of '{name}' must be a JSON object."
        else:
            p = sch["function"]["parameters"]; bad = None
            for k in p["required"]:
                if k not in args: bad = f"Error: missing required argument '{k}' for tool '{name}'."; break
            if bad is None:
                for k in args:
                    if k not in p["properties"]: bad = f"Error: unexpected argument '{k}' for tool '{name}'."; break
            if bad is None:
                for k, v in args.items():
                    t = p["properties"][k].get("type")
                    if t == "string" and not isinstance(v, str): bad = f"Error: argument '{k}' must be a string."; break
                    if t == "number" and (isinstance(v, bool) or not isinstance(v, (int, float))): bad = f"Error: argument '{k}' must be a number."; break
            try: out = bad or (self.always_fail.get(name) or (self.fail_next.pop(name, None)) or getattr(self, "t_" + name)(**args))
            except Exception: out = f"Error: tool '{name}' failed."
        self.log.append((name, args, out)); return out

    def t_calculator(self, expression):
        try: v = _safe_eval(expression)
        except Exception: return "Error: invalid expression."
        return _fmt(v)

    def t_convert_units(self, value, from_unit, to_unit):
        a, b = _unit(from_unit), _unit(to_unit)
        if (a, b) not in UNIT_F: return f"Error: unsupported conversion from {from_unit} to {to_unit}."
        return f"{_fmt(value)} {from_unit} = {_fmt(round(UNIT_F[(a, b)](float(value)), 2))} {to_unit}"

    def t_get_weather(self, city):
        for c, (t, cond, h) in self.weather.items():
            if c.lower() == city.strip().lower(): return f"{c}: {t}°C, {cond}, humidity {h}%"
        return f"Error: unknown city '{city}'."

    def t_get_time(self, timezone):
        for z, hm in self.times.items():
            if z.lower() == timezone.strip().lower(): return f"{z}: {hm}"
        return f"Error: unknown timezone '{timezone}'."

    def t_list_dir(self, path):
        if path.strip() not in (".", "./", "/", ""): return f"Error: no such directory: {path}"
        return "\n".join(sorted(self.fs)) if self.fs else "(empty)"

    def t_read_file(self, path):
        p = path.strip()[2:] if path.strip().startswith("./") else path.strip()
        return self.fs[p] if p in self.fs else f"Error: no such file: {path}"

    def t_write_file(self, path, content):
        self.fs[path.strip()] = content; return f"Wrote {len(content)} characters to {path}."

    def t_delete_file(self, path):
        p = path.strip()[2:] if path.strip().startswith("./") else path.strip()
        if p not in self.fs: return f"Error: no such file: {path}"
        del self.fs[p]; return f"Deleted {path}."

    def t_send_email(self, to, subject, body):
        if "@" not in to: return f"Error: invalid recipient address '{to}'."
        self.outbox.append((to, subject, body)); return f"Email sent to {to}."

    def t_create_event(self, title, date, time):
        self.events.append((title, date, time)); return f"Event created: {title} on {date} at {time}."

    def t_lookup_order(self, order_id):
        o = self.orders.get(order_id.strip())
        return f"Order {order_id}: {o[0]}, quantity {o[1]}, customer {o[2]}, status {o[3]}" if o else f"Error: order {order_id} not found."

    def t_get_customer(self, customer_id):
        c = self.customers.get(customer_id.strip())
        return f"Customer {customer_id}: {c[0]}, email {c[1]}, city {c[2]}" if c else f"Error: customer {customer_id} not found."

    def t_start_job(self, task):
        jid = f"job-{self.rng.randint(100, 999)}"; self.jobs[jid] = {"task": task, "polls": 0}; return f"Job {jid} started. Status: pending."

    def t_check_job(self, job_id):
        j = self.jobs.get(job_id.strip())
        if j is None: return f"Error: job {job_id} not found."
        j["polls"] += 1
        if j["polls"] < j.get("need", 2): return f"Job {job_id}: running ({min(90, 30 * j['polls'])}% done)."
        return f"Job {job_id}: done. Result: {j['result']}"


UNIT_ALIASES = {"kilometers": "km", "kilometres": "km", "kilometer": "km", "mile": "miles", "kilograms": "kg", "kilogram": "kg", "pound": "pounds", "lbs": "pounds", "lb": "pounds", "meter": "meters", "metres": "meters",
                "metre": "meters", "foot": "feet", "ft": "feet", "c": "celsius", "f": "fahrenheit", "liter": "liters", "litres": "liters", "gallon": "gallons"}
UNIT_F = {("km", "miles"): lambda x: x * 0.621371, ("miles", "km"): lambda x: x / 0.621371, ("kg", "pounds"): lambda x: x * 2.20462, ("pounds", "kg"): lambda x: x / 2.20462,
          ("celsius", "fahrenheit"): lambda x: x * 9 / 5 + 32, ("fahrenheit", "celsius"): lambda x: (x - 32) * 5 / 9, ("meters", "feet"): lambda x: x * 3.28084, ("feet", "meters"): lambda x: x / 3.28084,
          ("liters", "gallons"): lambda x: x * 0.264172, ("gallons", "liters"): lambda x: x / 0.264172}


def _unit(u): u = u.strip().lower(); return UNIT_ALIASES.get(u, u)
def _fmt(v):
    if isinstance(v, float):
        if v == int(v) and abs(v) < 1e15: return str(int(v))
        return f"{v:.6f}".rstrip("0").rstrip(".")
    return str(v)


_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Mod: operator.mod, ast.Pow: operator.pow, ast.FloorDiv: operator.floordiv}
def _safe_eval(expr):
    def ev(n):
        if isinstance(n, ast.Expression): return ev(n.body)
        if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)) and not isinstance(n.value, bool): return n.value
        if isinstance(n, ast.UnaryOp) and isinstance(n.op, (ast.USub, ast.UAdd)): return -ev(n.operand) if isinstance(n.op, ast.USub) else ev(n.operand)
        if isinstance(n, ast.BinOp) and type(n.op) in _OPS:
            a, b = ev(n.left), ev(n.right)
            if isinstance(n.op, ast.Pow) and (abs(b) > 12 or abs(a) > 1e6): raise ValueError("too large")
            return _OPS[type(n.op)](a, b)
        raise ValueError("bad node")
    if len(expr) > 120: raise ValueError("too long")
    return ev(ast.parse(expr.strip(), mode="eval"))


# ---------------------------------------------------------------------------------------------------------------- transcript helpers
NATIVE_BLOCK = re.compile(r"<tool_call>\s*([A-Za-z_][\w\-]*)\s*((?:<arg_key>.*?</arg_key>\s*<arg_value>.*?</arg_value>\s*)*)</tool_call>", re.S)
NATIVE_ARG = re.compile(r"<arg_key>(.*?)</arg_key>\s*<arg_value>(.*?)</arg_value>", re.S)
EMOJI = re.compile("[\U0001F000-\U0001FAFF\u2600-\u27BF\u2B50\u2B06\uFE0F]")


def parse_native(text):
    """GLM-style calls `<tool_call>name<arg_key>k</arg_key><arg_value>v</arg_value></tool_call>` (one or several blocks, nothing else in the message) -> [(name, args)] or None"""
    t = text.strip(); pos = 0; calls = []
    while pos < len(t):
        m = NATIVE_BLOCK.match(t, pos)
        if not m: return None
        name = m.group(1); args = {k.strip(): v.strip() for k, v in NATIVE_ARG.findall(m.group(2))}
        sch = SCHEMAS.get(name)
        if sch:
            for k, v in list(args.items()):
                if sch["function"]["parameters"]["properties"].get(k, {}).get("type") == "number":
                    try: args[k] = int(v) if re.fullmatch(r"-?\d+", v) else float(v)
                    except ValueError: pass
        calls.append((name, args)); pos = m.end()
        while pos < len(t) and t[pos].isspace(): pos += 1
    return calls if 0 < len(calls) <= 3 else None


def canon(calls):
    return "<tool_call>" + json.dumps([{"name": n, "arguments": a} for n, a in calls], ensure_ascii=False) + "</tool_call>"


def parse_calls(text):
    """-> list of (name, args) or None when the message is not a well-formed tool call message (our JSON-list format, or the model's native format which rollout() rewrites to ours)."""
    t = text.strip()
    if t.startswith("<tool_call>") and "</tool_call>" not in t and t.count("<tool_call>") == 1 and (t.endswith("]") or t.endswith("</arg_value>")):
        t += "</tool_call>"                                    # llama-server swallows the closing stop tag; a call that is otherwise complete is repaired (and stored canonically)
    if not TOOL_RX.match(t): return parse_native(t)
    if NATIVE_BLOCK.match(t) and not t.startswith("<tool_call>["): return parse_native(t)
    try: arr = json.loads(t[len("<tool_call>"):-len("</tool_call>")])
    except Exception: return None
    if not isinstance(arr, list) or not arr or len(arr) > 3: return None
    out = []
    for c in arr:
        if not isinstance(c, dict) or set(c) - {"name", "arguments"} or not isinstance(c.get("name"), str): return None
        out.append((c["name"], c.get("arguments", {})))
    return out


def nums(s):
    return {x.replace(",", "") for x in re.findall(r"\d[\d,]*(?:\.\d+)?", s)}


def ctx_numbers(tr, system):
    allowed = set(str(i) for i in range(0, 11)) | nums(system or "")
    for m in tr:
        allowed |= nums(m["content"])
    return allowed


def final_msg(tr):
    return tr[-1]["content"] if tr and tr[-1]["role"] == "assistant" else None


def contains(final, val):
    v = str(val)
    if re.fullmatch(r"-?\d+(\.\d+)?", v):
        if v.lstrip("-") not in nums(final): return False
        return not v.startswith("-") or any(k in final.lower() for k in ("-", "minus", "below zero", "below freezing", "negative"))
    return v.lower().replace(",", "") in final.lower().replace(",", "")


def common_checks(tr, system, max_calls=5, final_max=700):
    """format rules every accepted row must satisfy; returns a reason string or None"""
    asst = [m for m in tr if m["role"] == "assistant"]
    if not asst or tr[-1]["role"] != "assistant": return "does not end with an assistant message"
    for m in tr:
        if not isinstance(m["content"], str) or not m["content"].strip(): return "empty message"
        if m["role"] == "assistant":
            if BAD_TEXT.search(m["content"]): return "forbidden text in assistant message"
            if "<tool_call>" in m["content"] and parse_calls(m["content"]) is None: return "tool call message has extra text or bad JSON"
    if "<tool_call>" in tr[-1]["content"]: return "ends with a tool call"
    f = tr[-1]["content"]
    if len(f) > final_max or len(f) < 2: return "final answer length"
    for i, m in enumerate(tr):
        if m["role"] == "tool" and not (i > 0 and tr[i - 1]["role"] in ("assistant", "tool") and ("<tool_call>" in tr[i - 1]["content"] or tr[i - 1]["role"] == "tool")): return "tool message without a call"
        if m["role"] == "assistant" and "<tool_call>" in m["content"] and (i + 1 >= len(tr) or tr[i + 1]["role"] != "tool"): return "tool call without result"
    if sum(m["content"].count("<tool_call>") for m in asst) > max_calls: return "too many tool calls"
    return None


# ---------------------------------------------------------------------------------------------------------------- tasks
class Task:
    def __init__(self, kind, rng, tools, user, world, replies=None, judge=None, system=None, info=None):
        self.kind, self.rng, self.tool_names, self.user, self.world, self.replies, self.judge, self.system, self.info = kind, rng, tools, user, world, replies or [], judge, system, info or {}
        self.tools = [SCHEMAS[n] for n in tools]
        self.stage = 0                                              # index of the next scripted user reply

    def next_user(self, last_assistant_text):
        """scripted user turn after an assistant message without a tool call, or None when the conversation is over"""
        if self.stage < len(self.replies):
            gate = self.replies[self.stage].get("gate")
            if gate and not gate(last_assistant_text): return None
            r = self.replies[self.stage]["text"]; self.stage += 1; return r
        return None


def _pick(rng, seq): return seq[rng.randrange(len(seq))]
def _sys(rng):
    tot = sum(w for _, w in SYSTEMS); x = rng.uniform(0, tot)
    for s, w in SYSTEMS:
        x -= w
        if x <= 0: return s
    return SYSTEMS[0][0]
def _tools(rng, need, pool=("calculator", "get_time", "convert_units", "list_dir", "get_weather", "send_email", "lookup_order"), extra=(0, 2)):
    names = list(need) + [p for p in rng.sample(pool, len(pool)) if p not in need][:rng.randint(*extra)]
    rng.shuffle(names); return names
def _world_weather(rng, cities):
    w = World(rng)
    for c in set(cities) | set(rng.sample(CITIES, 3)): w.weather[c] = (rng.randint(-5, 41), _pick(rng, CONDS), rng.randint(20, 95))
    for z in rng.sample(TZS, 3): w.times[z] = f"{rng.randint(0, 23):02d}:{rng.choice([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]):02d}"
    return w
def _note_text(rng, topic):
    if topic in ("groceries", "shopping"):
        its = rng.sample(ITEMS, 3); return f"Buy {its[0]}, {its[1]} and {its[2]}. Budget {rng.randint(10, 90)}0 rupees.", its
    n, t = _pick(rng, NAMES), f"{rng.randint(1, 12)}:{rng.choice(['00', '30'])}"
    s = _pick(rng, [f"Call {n} at {t} on {_pick(rng, ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])}.", f"Meeting with {n} moved to room {rng.randint(100, 480)} at {t}.",
                    f"{n} owes me {rng.randint(5, 99)}0 rupees, remind them on the {rng.randint(2, 28)}th.", f"Finish chapter {rng.randint(2, 19)} before {n} visits at {t}."])
    return s, [x for x in (n, t) if x in s] + [x for x in re.findall(r"\d+", s)][:1]
def _fs(rng, topics, extra=3):
    fs, facts = {}, {}
    for t in list(topics) + rng.sample([x for x in TOPICS if x not in topics], extra):
        ext = rng.choice([".txt", ".txt", ".md"]); txt, fa = _note_text(rng, t); fs[t + ext] = txt; facts[t + ext] = fa
    return fs, facts
def _ok_grounded(tr, system, facts, final_max=700):
    r = common_checks(tr, system, final_max=final_max)
    if r: return r
    f = tr[-1]["content"]
    for v in facts:
        if not contains(f, str(v)): return f"final answer misses the observed value '{v}'"
    bad = nums(f) - ctx_numbers(tr, system)
    if bad: return f"final answer contains numbers that are in no observation: {sorted(bad)[:3]}"
    return None
def _called(w, name): return [(a, o) for n, a, o in w.log if n == name]
def _ask_gate(kws):
    return lambda t: "?" in t and "<tool_call>" not in t and len(t) <= 300 and any(k in t.lower() for k in kws)
def _reply_pool(rng, v, kind="ask"):
    return _pick(rng, {"ask": [v, f"It's {v}.", f"{v} please", f"in {v}", f"{v}, thanks", f"let's say {v}"]}[kind])


def t_weather(rng):
    city = _pick(rng, CITIES); w = _world_weather(rng, [city]); tmp, cond, hum = w.weather[city]
    user = _pick(rng, [f"what's the weather like in {city}?", f"weather in {city} right now?", f"how is the weather in {city} today", f"is it cold in {city}? check please", f"can you check the weather for {city}",
                       f"{city} weather?", f"hey nini, what's the temperature in {city}?"])
    follow = rng.random() < 0.3; thr = rng.randint(max(-3, tmp - 8), min(40, tmp + 8))
    if thr == tmp: thr += 1
    replies = [{"text": f"is that above {thr} degrees?"}] if follow else []
    def judge(tr, w=w, city=city, tmp=tmp, cond=cond, thr=thr, follow=follow):
        calls = _called(w, "get_weather")
        if not any(str(a.get("city", "")).lower() == city.lower() for a, _ in calls): return "did not call get_weather for the city"
        if follow:
            users = [i for i, m in enumerate(tr) if m["role"] == "user"]
            if len(users) < 2: return "follow-up not answered"
            after = [m for m in tr[users[1]:] if m["role"] == "assistant"]
            if any("<tool_call>" in m["content"] for m in after): return "re-called a tool for a follow-up that needs none"
            first_final = tr[users[1] - 1]["content"] if tr[users[1] - 1]["role"] == "assistant" else ""
            if not contains(first_final, str(tmp)): return "first answer misses the observed temperature"
            ans = tr[-1]["content"].strip().lower(); yes = tmp > thr
            if not ans.startswith("yes" if yes else "no"): return "follow-up answered wrongly"
            return common_checks(tr, None)
        return _ok_grounded(tr, None, [tmp])
    return Task("weather", rng, _tools(rng, ["get_weather"]), user, w, replies, judge, _sys(rng), {"city": city, "thr": thr, "follow": follow})


def t_time(rng):
    w = _world_weather(rng, []); tz = rng.choice(list(w.times)); hm = w.times[tz]
    user = _pick(rng, [f"what time is it in {tz}?", f"time in {tz} right now?", f"can you tell me the current time for {tz}", f"check the clock for {tz} please"])
    return Task("time", rng, _tools(rng, ["get_time"]), user, w, None, lambda tr, w=w, tz=tz, hm=hm: ((not any(str(a.get("timezone", "")).lower() == tz.lower() for a, _ in _called(w, "get_time")) and "did not call get_time for the timezone")
                or _ok_grounded(tr, None, [hm])), _sys(rng), {"tz": tz})


def t_calc(rng):
    w = World(rng); a, b, c = rng.randint(12, 980), rng.randint(2, 60), rng.randint(2, 99)
    form = rng.randrange(4)
    if form == 0: expr, val, user = f"{a} * {b} + {c}", a * b + c, _pick(rng, [f"what is {a} * {b} + {c}?", f"calculate {a} times {b} plus {c}", f"{a}*{b}+{c} = ?"])
    elif form == 1: expr, val, user = f"({a} + {c}) * {b}", (a + c) * b, f"add {a} and {c}, then multiply by {b}. what do you get?"
    elif form == 2: n, p, q = rng.randint(3, 15), rng.randint(15, 95), rng.randint(5, 60); expr, val, user = f"{n} * {p} + {q}", n * p + q, f"I bought {n} notebooks at {p} rupees each and a pen for {q} rupees. what is the total?"
    else: a = b * c + rng.randint(1, 500); expr, val, user = f"{a} - {b} * {c}", a - b * c, f"what's {a} minus {b} times {c}?"
    def judge(tr, w=w, val=val):
        ok = [o for a_, o in _called(w, "calculator") if o == _fmt(val)]
        if not ok: return "calculator never returned the correct value"
        return _ok_grounded(tr, None, [_fmt(val)])
    return Task("calc", rng, _tools(rng, ["calculator"]), user, w, None, judge, _sys(rng), {"expr": expr})


def t_convert(rng):
    w = World(rng); f, t = _pick(rng, [("km", "miles"), ("kg", "pounds"), ("celsius", "fahrenheit"), ("meters", "feet"), ("liters", "gallons"), ("miles", "km"), ("fahrenheit", "celsius")]); v = rng.choice([5, 10, 12, 20, 36, 42, 75, 100, 150])
    res = _fmt(round(UNIT_F[(f, t)](float(v)), 2)); user = _pick(rng, [f"convert {v} {f} to {t}", f"how many {t} is {v} {f}?", f"{v} {f} in {t}, please"])
    return Task("convert", rng, _tools(rng, ["convert_units"]), user, w, None, lambda tr, w=w, res=res: ((not any(o.endswith(f"= {res} {t}") for _, o in _called(w, "convert_units")) and "convert_units never returned the right value") or _ok_grounded(tr, None, [res])), _sys(rng), {"v": v, "f": f, "t": t})


def t_read_note(rng):
    topics = rng.sample(TOPICS, 2); fs, facts = _fs(rng, topics); w = World(rng); w.fs = fs
    t = topics[0]; fn = [k for k in fs if k.startswith(t + ".")][0]
    user = _pick(rng, [f"what does my {t} note say?", f"read my {t} file to me", f"open the {t} note and tell me what's in it", f"check {t} and summarise it"])
    def judge(tr, w=w, fn=fn, fa=facts[fn]):
        if not any(a.get("path", "").strip("./") == fn and not o.startswith("Error") for a, o in _called(w, "read_file")): return "never read the right file successfully"
        return _ok_grounded(tr, None, fa[:2])
    return Task("read_note", rng, _tools(rng, ["list_dir", "read_file"], extra=(0, 2)), user, w, None, judge, _sys(rng))


def t_error_recovery(rng):
    v = rng.randrange(3)
    if v == 0:                                                           # wrong extension / name in the request
        topics = rng.sample(TOPICS, 2); fs, facts = _fs(rng, topics); w = World(rng); w.fs = fs; t = topics[0]; fn = [k for k in fs if k.startswith(t + ".")][0]
        wrong = t + (".md" if fn.endswith(".txt") else ".txt"); user = _pick(rng, [f"show me {wrong}", f"what's inside {wrong}?", f"read {wrong} for me"])
        def judge(tr, w=w, fn=fn, fa=facts[fn]):
            if not any(a.get("path", "").strip("./") == fn and not o.startswith("Error") for a, o in _called(w, "read_file")): return "never read the right file"
            return _ok_grounded(tr, None, fa[:2])
        return Task("error_recovery", rng, _tools(rng, ["list_dir", "read_file"], extra=(0, 1)), user, w, None, judge, _sys(rng), {"variant": "wrong_name"})
    if v == 1:                                                           # transient error on the first call
        city = _pick(rng, CITIES); w = _world_weather(rng, [city]); tmp = w.weather[city][0]; w.fail_next["get_weather"] = "Error: service temporarily unavailable (503). Please try again."
        user = _pick(rng, [f"weather in {city} please", f"what's it like outside in {city}?", f"check the weather for {city}"])
        def judge(tr, w=w, tmp=tmp):
            if len(_called(w, "get_weather")) < 2: return "did not retry after the error"
            return _ok_grounded(tr, None, [tmp])
        return Task("error_recovery", rng, _tools(rng, ["get_weather"]), user, w, None, judge, _sys(rng), {"variant": "transient"})
    w = World(rng); fs, facts = _fs(rng, [_pick(rng, TOPICS)]); w.fs = fs; fn = sorted(fs)[0]; w.always_fail["read_file"] = f"Error: permission denied: {fn}"
    user = _pick(rng, [f"read {fn} and tell me what it says", f"what's in {fn}?"])
    def judge(tr, w=w, fn=fn, secret=fs[fn]):
        r = common_checks(tr, None, max_calls=4)
        if r: return r
        f = tr[-1]["content"].lower()
        if not any(k in f for k in ("permission", "denied", "couldn't", "could not", "can't", "cannot", "unable", "not able", "wasn't able")): return "did not report the failure"
        if any(x.lower() in f for x in re.findall(r"[A-Za-z]{4,}", secret) if x.lower() not in ("call", "with", "room", "before", "visits", "owes", "remind", "moved", "meeting", "finish", "chapter", "budget", "them")): return "invented file content"
        return None if not (nums(tr[-1]["content"]) - ctx_numbers(tr, None)) else "invented numbers"
    return Task("error_recovery", rng, _tools(rng, ["list_dir", "read_file"], extra=(0, 1)), user, w, None, judge, _sys(rng), {"variant": "permanent"})


def t_empty(rng):
    w = World(rng); v = rng.randrange(2)
    if v == 0:
        oid = str(rng.randint(10000, 99999)); user = _pick(rng, [f"where is my order {oid}?", f"look up order {oid}", f"status of order {oid}?"]); tools = _tools(rng, ["lookup_order"])
    else:
        w.fs = {}; topic = _pick(rng, TOPICS); user = _pick(rng, [f"what's in my {topic} note?", f"read my {topic} file"]); tools = _tools(rng, ["list_dir", "read_file"], extra=(0, 1)); oid = None
    def judge(tr, w=w, oid=oid):
        r = common_checks(tr, None, max_calls=4)
        if r: return r
        if not w.log: return "answered without calling a tool"
        f = tr[-1]["content"].lower()
        if not any(k in f for k in NEG + ("empty", "doesn't exist", "does not exist", "isn't", "no such", "found")): return "did not say that nothing was found"
        if nums(tr[-1]["content"]) - ctx_numbers(tr, None): return "invented numbers"
        if re.search(r"\b(shipped|delivered|arriv|dispatched|in transit|out for delivery)\w*\b", f) and not re.search(r"(not|n't|no)\b.{0,40}\b(shipped|delivered|arriv|dispatched|found)", f): return "invented an order status"
        return None
    return Task("empty_result", rng, tools, user, w, None, judge, _sys(rng))


def t_ask_then_act(rng):
    v = rng.randrange(4)
    if v == 0:
        city = _pick(rng, CITIES); w = _world_weather(rng, [city]); tmp = w.weather[city][0]
        user = _pick(rng, ["what's the weather like today?", "do I need an umbrella? check the weather", "how's the weather?", "tell me the current temperature"])
        def judge(tr, w=w, city=city, tmp=tmp):
            if not any(str(a.get("city", "")).lower() == city.lower() for a, _ in _called(w, "get_weather")): return "did not use the city the user gave"
            return _ok_grounded(tr, None, [tmp])
        return Task("ask_then_act", rng, _tools(rng, ["get_weather"]), user, w, [{"text": _reply_pool(rng, city), "gate": _ask_gate(("city", "where", "which", "location", "place"))}], judge, _sys(rng), {"variant": "city"})
    if v == 1:
        w = World(rng); n = _pick(rng, NAMES); to = f"{n.lower()}@example.com"; user = _pick(rng, ["send an email saying the report is ready", "email the team that the meeting is cancelled", "mail them that I'll be late"])
        def judge(tr, w=w, to=to):
            if not any(o.startswith("Email sent") and to in o for _, _, o in w.log): return "email was not sent to the address the user gave"
            r = common_checks(tr, None)
            return r or (None if to in tr[-1]["content"] or "sent" in tr[-1]["content"].lower() else "final answer does not confirm the email")
        return Task("ask_then_act", rng, _tools(rng, ["send_email"]), user, w, [{"text": _pick(rng, [f"to {to}", f"{to}", f"send it to {to} please"]), "gate": _ask_gate(("who", "recipient", "address", "email", "send it to", "whom", "to whom"))}], judge, _sys(rng), {"variant": "recipient"})
    if v == 2:
        w = World(rng); title = _pick(rng, ["dentist", "team sync", "yoga class", "call with Sam", "haircut", "project review"]); day = _pick(rng, ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]); tm = rng.choice(["09:00", "10:30", "14:00", "16:30", "18:15"])
        user = f"add {title} on {day} to my calendar"
        def judge(tr, w=w, title=title, tm=tm, day=day):
            ev = w.events
            if not ev: return "no event was created"
            if not (tm in ev[-1][2] or tm.lstrip("0") in ev[-1][2]): return "event time is not the time the user gave"
            if day.lower() not in ev[-1][1].lower(): return "event day is not the day the user gave"
            r = common_checks(tr, None)
            return r or (None if tm.lstrip("0") in tr[-1]["content"] or tm in tr[-1]["content"] else "final answer does not repeat the time")
        return Task("ask_then_act", rng, _tools(rng, ["create_event"]), user, w, [{"text": _pick(rng, [f"at {tm}", f"{tm}", f"around {tm} please"]), "gate": _ask_gate(("time", "when", "what time", "which time", "o'clock"))}], judge, _sys(rng), {"variant": "time"})
    city = _pick(rng, CITIES); w = _world_weather(rng, [city]); tmp = w.weather[city][0]                    # control: everything is given, no question allowed
    user = f"what's the weather in {city}? just tell me the temperature."
    def judge(tr, w=w, city=city, tmp=tmp):
        first = next(m for m in tr if m["role"] == "assistant")
        if "<tool_call>" not in first["content"]: return "asked/answered instead of calling the tool although everything was given"
        return _ok_grounded(tr, None, [tmp])
    return Task("ask_then_act", rng, _tools(rng, ["get_weather"]), user, w, None, judge, _sys(rng), {"variant": "control_no_question"})


def t_confirm(rng):
    w = World(rng); fs, _ = _fs(rng, [_pick(rng, TOPICS)]); w.fs = fs; fn = sorted(fs)[0]; yes = rng.random() < 0.7
    user = _pick(rng, [f"delete {fn}", f"please remove {fn}", f"get rid of {fn}"])
    reply = _pick(rng, ["yes, go ahead", "yes please", "yep do it", "confirmed, delete it", "sure"]) if yes else _pick(rng, ["no, keep it", "wait, don't", "no leave it", "cancel that"])
    gate = lambda t: ("?" in t or "confirm" in t.lower() or "go ahead" in t.lower()) and "<tool_call>" not in t and len(t) <= 300 and (fn.lower() in t.lower() or "delete" in t.lower() or "remove" in t.lower() or "sure" in t.lower() or "confirm" in t.lower())
    def judge(tr, w=w, fn=fn, yes=yes):
        users = [i for i, m in enumerate(tr) if m["role"] == "user"]
        if len(users) < 2: return "did not ask for confirmation"
        if any(m["role"] == "assistant" and "<tool_call>" in m["content"] for m in tr[:users[1]]): return "deleted before the user confirmed"
        gone = fn not in w.fs
        if yes and not gone: return "user confirmed but the file was not deleted"
        if not yes and (gone or any(n == "delete_file" for n, _, _ in w.log)): return "deleted although the user said no"
        r = common_checks(tr, None)
        if r: return r
        f = tr[-1]["content"].lower()
        if yes and not ("delet" in f or "remov" in f or "gone" in f): return "final answer does not confirm the deletion"
        if not yes and not any(k in f for k in ("keep", "kept", "won't", "will not", "not delet", "leave", "left", "cancel", "okay", "ok", "sure", "no problem", "untouched")): return "final answer does not acknowledge the cancellation"
        return None
    return Task("confirm_destructive", rng, _tools(rng, ["delete_file", "list_dir"], extra=(0, 1)), user, w, [{"text": reply, "gate": gate}], judge, _sys(rng), {"confirmed": yes})


def t_async(rng):
    w = World(rng); rows = rng.randint(120, 9800); what = _pick(rng, ["monthly report", "data export", "backup", "image resize batch", "log cleanup"])
    user = _pick(rng, [f"start the {what} job and tell me when it's done", f"run the {what} and give me the result", f"kick off the {what}, I'll wait"])
    res = f"{rows} items processed"
    orig = w.t_start_job
    def start(task, w=w, orig=orig):
        out = orig(task); jid = out.split()[1]; w.jobs[jid]["result"] = res; w.jobs[jid]["need"] = 2 if rng.random() < 0.5 else 3; return out
    w.t_start_job = start
    def judge(tr, w=w, rows=rows):
        polls = [1 for n, _, _ in w.log if n == "check_job"]
        if len(polls) < 2: return "did not poll until the job was done"
        if not any("done" in o for n, _, o in w.log if n == "check_job"): return "never saw the job finish"
        done_idx = next(i for i, m in enumerate(tr) if m["role"] == "tool" and "done." in m["content"])
        if any(str(rows) in m["content"] for m in tr[:done_idx] if m["role"] == "assistant"): return "claimed a result before the job finished"
        return _ok_grounded(tr, None, [str(rows)])
    return Task("async_job", rng, _tools(rng, ["start_job", "check_job"], extra=(0, 1)), user, w, None, judge, _sys(rng), {"what": what})


def t_no_tool(rng):
    w = World(rng); system = _sys(rng)
    user = _pick(rng, ["hi!", "hello, who are you?", "thanks, that's all for now", "good morning", "thank you so much!", "can you help me with something?", "what can you do with the tools you have?", "ok cool", "hey nini", "bye for now"])
    if "who are you" in user and not (system and "Zenyx-Mini" in system): user = "hello!"
    tools = _tools(rng, [], pool=("calculator", "get_time", "convert_units", "get_weather", "list_dir"), extra=(1, 3))
    def judge(tr, w=w, tools=tools, user=user):
        if w.log or any("<tool_call>" in m["content"] for m in tr): return "called a tool for small talk"
        r = common_checks(tr, None, final_max=500)
        if r: return r
        f = tr[-1]["content"]
        if "tools you have" in user and not any(t.replace("_", " ") in f.lower() or t in f.lower() for t in tools): return "did not mention any available tool"
        if re.search(r"\b(\d+)\s*(million|billion)\b", f.lower()) and "151" not in f: return "wrong parameter count"
        if "who are you" in user and not ("nini" in f.lower() or "zenyx" in f.lower()): return "did not introduce itself with the persona name"
        return None
    return Task("no_tool_needed", rng, tools, user, w, None, judge, system)


def t_unavailable(rng):
    w = World(rng); user = _pick(rng, ["book me a flight to Delhi for tomorrow", "order a pizza for dinner", "play some music", "what is the price of Tesla stock right now?", "turn off the lights in the living room",
                                       "post this on my twitter", "translate this PDF and print it", "call my mom"])
    tools = _tools(rng, [], pool=("calculator", "get_time", "convert_units", "list_dir", "read_file"), extra=(2, 3))
    def judge(tr, w=w):
        if w.log: return "called a tool that cannot do this"
        r = common_checks(tr, None, final_max=500)
        if r: return r
        f = tr[-1]["content"].lower()
        return None if any(k in f for k in ("can't", "cannot", "can not", "don't have", "do not have", "unable", "not able", "no tool", "isn't something", "not something", "sorry")) else "did not say it cannot do this"
    return Task("tool_unavailable", rng, tools, user, w, None, judge, _sys(rng))


def t_multi(rng):
    c1, c2 = rng.sample(CITIES, 2); w = _world_weather(rng, [c1, c2]); t1, t2 = w.weather[c1][0], w.weather[c2][0]
    user = _pick(rng, [f"compare the weather in {c1} and {c2}", f"what's the temperature in {c1} and in {c2}?", f"weather for {c1} and {c2} please"])
    def judge(tr, w=w, c1=c1, c2=c2, t1=t1, t2=t2):
        got = {str(a.get("city", "")).lower() for a, _ in _called(w, "get_weather")}
        if not {c1.lower(), c2.lower()} <= got: return "did not look up both cities"
        r = _ok_grounded(tr, None, [t1, t2])
        return r
    return Task("multi_call", rng, _tools(rng, ["get_weather"]), user, w, None, judge, _sys(rng))


def t_dependent(rng):
    w = World(rng); oid = str(rng.randint(10000, 99999)); cid = f"cust-{rng.randint(1000, 9999)}"; n = _pick(rng, NAMES); em = f"{n.lower()}{rng.randint(1, 99)}@example.com"; city = _pick(rng, CITIES)
    item = _pick(rng, ["laptop stand", "desk lamp", "water bottle", "notebook set", "keyboard", "backpack"]); w.orders[oid] = (item, rng.randint(1, 5), cid, _pick(rng, ["shipped", "processing", "delivered"])); w.customers[cid] = (n, em, city)
    ask = _pick(rng, [f"what's the email of the person who placed order {oid}?", f"which city is order {oid} for? look up the customer", f"who ordered {oid} and what's their email?"])
    want = [city] if "city" in ask else [em] + ([n] if "who ordered" in ask else [])
    def judge(tr, w=w, cid=cid, want=want):
        if not any(a.get("customer_id", "").strip() == cid and not o.startswith("Error") for a, o in _called(w, "get_customer")): return "never looked up the customer id from the order"
        return _ok_grounded(tr, None, want)
    return Task("dependent_calls", rng, _tools(rng, ["lookup_order", "get_customer"], extra=(0, 1)), ask, w, None, judge, _sys(rng))


def t_write(rng):
    w = World(rng); topic = _pick(rng, TOPICS); fn = f"{topic}.txt"; its = rng.sample(ITEMS, 3); text = f"{its[0]}, {its[1]}, {its[2]}"
    user = _pick(rng, [f"save a note called {fn} with: {text}", f"write \"{text}\" into {fn}", f"create {fn} containing {text}"])
    def judge(tr, w=w, fn=fn, text=text):
        got = w.fs.get(fn)
        if got is None or got.strip().strip('"').lower() != text.lower(): return "file content is not what the user asked for"
        r = common_checks(tr, None)
        return r or (None if fn in tr[-1]["content"] or "saved" in tr[-1]["content"].lower() or "wrote" in tr[-1]["content"].lower() or "created" in tr[-1]["content"].lower() else "final answer does not confirm the write")
    return Task("write_note", rng, _tools(rng, ["write_file", "read_file"], extra=(0, 1)), user, w, None, judge, _sys(rng), {"fn": fn, "text": text})


KINDS = [(t_weather, 7), (t_time, 3), (t_calc, 7), (t_convert, 3), (t_read_note, 8), (t_error_recovery, 12), (t_empty, 6), (t_ask_then_act, 12), (t_confirm, 8), (t_async, 6), (t_no_tool, 5), (t_unavailable, 5),
         (t_multi, 5), (t_dependent, 6), (t_write, 6)]


PRE = ["", "", "", "", "hey, ", "hi nini, ", "quick question: ", "pls ", "hey nini, ", "ok so ", "hello! ", "um, ", "nini, ", "yo ", "so, "]
SUF = ["", "", "", "", " thanks!", " please", " asap", " :)", " thx", " (quick one)", " if you can", " when you get a chance"]
def style(rng, text):
    """small natural variation of the first user message (greeting words, thanks, casing) - the facts in it are untouched"""
    t = text
    if rng.random() < 0.35 and t[:1].isupper() and not t[:2].isupper(): t = t[0].lower() + t[1:]
    p, q = _pick(rng, PRE), _pick(rng, SUF)
    if q and t.endswith(("?", ".", "!")): t = t[:-1] + q if q.strip() in ("please", "thanks!", "thx", ":)") and t.endswith("?") is False else t + q
    return (p + t) if p else t


def make_task(rng):
    tot = sum(w for _, w in KINDS); x = rng.uniform(0, tot); task = None
    for fn, w in KINDS:
        x -= w
        if x <= 0: task = fn(rng); break
    task = task or KINDS[0][0](rng)
    task.user = style(rng, task.user)
    return task


# ------------------------------------------------------------------------------------------- generation-only hints (never stored)
def gen_hint(kind, tr):
    """extra system text for the generating model, chosen from the task kind and the transcript so far; the judge still checks the result on its own"""
    n_user = sum(1 for m in tr if m["role"] == "user")
    if kind == "confirm_destructive":
        if n_user == 1: return " For this request: the user wants a file deleted. Your reply now must be one short question, ending with a question mark, asking them to confirm the deletion (name the file), with NO tool call at all, not even list_dir. Delete nothing until they answer."
        if not any(m["role"] == "tool" for m in tr): return " For this request: the user has answered your confirmation question. If they said yes, reply with only the delete_file tool call. If they said no, call no tool and say in one sentence that you are keeping the file."
    if kind == "async_job":
        if tr[-1]["role"] == "tool":
            if "done." in tr[-1]["content"]: return " For this request: the job has finished. Give the user the result in one short sentence."
            return " For this request: the job is NOT finished yet. Your reply must be only a check_job tool call with the same job id. Do not say you will check later and do not give a result yet."
        return " For this request: start the job now, replying with only the start_job tool call."
    if kind == "tool_unavailable":
        return " For this request: none of your tools can do it. Reply in 1-2 sentences, saying plainly that you can't do that with the tools you have, and mention one thing you can do. No tool call."
    return ""


# ---------------------------------------------------------------------------------------------------------------- the loop
MAX_STEPS = 7
def rollout(task, generate):
    """generate(system_text_or_None, history) -> assistant text; history = list of {"role": user|assistant|tool, "content"}.  Returns (transcript, reason) with reason None when the judge accepts."""
    tr = [{"role": "user", "content": task.user}]
    steps = 0
    while True:
        steps += 1
        if steps > MAX_STEPS: return tr, "too many steps"
        text = (generate(task.system, task.tools, tr) or "").strip()
        if not text: return tr, "empty generation"
        tr.append({"role": "assistant", "content": text})
        if "<tool_call>" in text:
            calls = parse_calls(text)
            if calls is None: return tr, "tool call message has extra text or bad JSON"
            tr[-1]["content"] = canon(calls)                       # always stored in the Zenyx JSON-list format, whatever syntax the model used
            for name, args in calls: tr.append({"role": "tool", "content": task.world.call(name, args)})
            continue
        nxt = task.next_user(text)
        if nxt is None: break
        tr.append({"role": "user", "content": nxt})
    reason = common_checks(tr, task.system) or task.judge(tr)
    if reason is None and task.stage < len(task.replies): reason = "scripted user turn never reached"
    if reason is None and task.replies and task.replies[0].get("gate") and task.stage == 0: reason = "did not ask the required question"
    return tr, reason


def to_row(task, tr, provider, seed):
    msgs = ([{"role": "system", "content": task.system}] if task.system else []) + tr
    return {"messages": msgs, "tools": json.dumps(task.tools, ensure_ascii=False), "domain": "agentloop_" + task.kind, "provider": provider, "seed": seed, "task_info": json.dumps(task.info, ensure_ascii=False)}