Spaces:
Running

File size: 33,297 Bytes
0776bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
"""Phase 8 subgraphs: COD confirmation, confirmation replies, timeouts, couriers, reconciliation.



**The confirmation wait is a state machine, not a held-open run.** A COD order is scored and

routed by band; a medium/high order gets a WhatsApp confirmation request and an

``ecom_cod_confirmations`` row (``pending``, ``deadline_at`` = now + tenant timeout), and the

run *completes*. Nothing waits in memory or in a checkpoint:



* the customer's reply arrives as a ``whatsapp.message`` event and starts a

  ``support_inbound`` run; its ``cod_check`` step (deterministic: button payload, then

  keyword rules, extractor only as a fallback with a closed enum) correlates it with the

  pending attempt (reply context, else the latest pending attempt for the sender's phone)

  and hands it to ``cod_reply``: CONFIRM -> book (high risk: human review), CANCEL -> cancel

  (auto, policy ``cancel_order_customer_rejected``), ADDRESS_CHANGE -> tainted address ->

  approval;

* the timeout is a durable timer: a tenant schedule (DBOS cron, Phase 5) emits

  ``ecommerce.cod_sweep`` events; the sweep marks attempts past their deadline

  ``no_answer`` and escalates them to the inbox as ONE batch cancellation approval

  (approve = cancel, reject = keep them for a phone follow-up).



Both halves survive restarts because their state lives in tables, and every side effect is

a gateway call with a stable step id (replays are idempotent).

"""

from __future__ import annotations

from typing import Any

from langgraph.graph import END, START

from core.agent.extractor import extract
from core.agent.state import Event, RunState, subgraph_builder
from core.agent.tools import action_record
from core.gateway.taint import Tainted
from core.i18n.locale import reply_language
from core.packs.loader import AgentDeps
from packs.ecommerce import i18n, inbound
from packs.ecommerce.cod_reply import AddressChangeFields, ConfirmationReply, classify
from packs.ecommerce.graphs import _err, _facts, _lookup, _ok, rs, stop_if_done
from packs.ecommerce.tools.cod import COD_TEMPLATES
from packs.ecommerce.views import normalize_order_number

STATUS_TEXT = {
    "out_for_delivery": "is out for delivery today",
    "delivered": "has been delivered",
    "failed_attempt": "could not be delivered (the rider could not reach you)",
}


def _data(out: Any) -> dict[str, Any]:
    return dict(out.result.data or {}) if out.result is not None else {}


def _cod(state: RunState) -> dict[str, Any]:
    return dict((state.get("facts") or {}).get("cod") or {})


def _stop_if_skip(state: RunState) -> str:
    if stop_if_done(state) == "stop" or _cod(state).get("skip"):
        return "stop"
    return "next"


def _join(*parts: str | None) -> str:
    return " ".join(p for p in parts if p)


# ------------------------------------------------------------------ COD confirmation


def _order_number_from(state: RunState, chained: bool) -> tuple[str | None, str | None]:
    """(order number, reason to skip)."""
    if chained:
        applied = [
            a
            for a in state.get("actions") or []
            if a.get("tool") == "ecommerce.apply_store_event" and a.get("data")
        ]
        if not applied:
            return None, "store event not applied"
        data = applied[-1]["data"]
        if data.get("action") != "created":
            return data.get("order"), "not a new order"
        return data.get("order"), None
    event = Event.model_validate(state["event"])
    raw = event.payload.get("order_number") or event.text
    number = normalize_order_number(str(raw) if raw else None)
    return number, None if number else "no order number"


def confirmation_nodes(deps: AgentDeps, *, chained: bool) -> dict[str, Any]:
    """The three COD confirmation steps (context -> score -> route), shared by the

    ``ecommerce.cod_confirm`` intent and the ``orders/create`` chain."""

    async def context_node(state: RunState) -> dict[str, Any]:
        number, skip = _order_number_from(state, chained)
        if skip or not number:
            return {"facts": _facts(state, cod={"skip": skip or "no order"})}
        out = await deps.tools.call(
            state, "cod:context", "ecommerce.get_confirmation_context", {"order_number": number}
        )
        rec = action_record("cod:context", "ecommerce.get_confirmation_context", out)
        if not _ok(out):
            if chained:  # never fail an applied store event over the COD add-on
                return {"actions": [rec], "facts": _facts(state, cod={"skip": _err(out)})}
            return {"actions": [rec], "status": "failed", "error": _err(out)}
        c = _data(out)
        skip = None
        if c["payment_method"] != "COD":
            skip = f"{number} is prepaid"
        elif c["status"] != "pending":
            skip = f"{number} is {c['status']}"
        elif c["confirmation_status"] not in (None, "pending"):
            skip = f"{number} is already {c['confirmation_status']}"
        elif c.get("open_attempt"):
            skip = f"a confirmation for {number} is already pending"
        elif chained and not c.get("confirm_on_create"):
            skip = "COD confirmation on new orders is off (tenant setting cod.confirm_on_create)"
        update: dict[str, Any] = {"actions": [rec], "facts": _facts(state, cod={**c, "skip": skip})}
        if skip and not chained:
            update["output"] = f"Nothing to confirm: {skip}."
        return update

    async def score_node(state: RunState) -> dict[str, Any]:
        c = _cod(state)
        out = await deps.tools.call(
            state,
            "cod:score",
            "ecommerce.score_order_risk",
            {"order_number": c["order_number"], "stage": "created"},
        )
        rec = action_record("cod:score", "ecommerce.score_order_risk", out)
        if not _ok(out):
            return {"actions": [rec], "status": "failed", "error": _err(out)}
        risk = _data(out)
        line = f"{c['order_number']}: RTO risk {risk['score']:.0%} ({risk['band']}): " + "; ".join(
            risk["reasons"]
        )
        return {"actions": [rec], "facts": _facts(state, cod={**c, "risk": risk}), "log": [line]}

    async def route_node(state: RunState) -> dict[str, Any]:
        c = _cod(state)
        number, band = c["order_number"], c["risk"]["band"]
        prefix = f"{number} is {band} risk ({c['risk']['score']:.0%})."
        if band == "low":
            return await _auto_confirm(deps, state, number, prefix)
        return await _request_confirmation(deps, state, c, prefix)

    return {"cod_context": context_node, "cod_score": score_node, "cod_route": route_node}


async def _book(

    deps: AgentDeps, state: RunState, number: str, step: str

) -> tuple[Any, dict[str, Any]]:
    out = await deps.tools.call(state, step, "ecommerce.book_shipment", {"order_number": number})
    return out, action_record(step, "ecommerce.book_shipment", out)


async def _booking_followup(

    deps: AgentDeps, state: RunState, number: str, error: str, actions: list[dict[str, Any]]

) -> str:
    """A booking that failed (courier timeout, outage, bad address) must not leave a confirmed

    order silently unshipped: open a high-priority staff task to book it by hand. Returns a

    sentence for the run output. (evals/error_analysis.md #5)"""
    out = await deps.tools.call(
        state,
        "cod:book_followup",
        "ecommerce.create_task",
        {
            "title": f"Book shipment for {number} (automatic booking failed)",
            "description": f"Automatic courier booking failed: {error}. "
            "Retry the booking or book with another courier.",
            "priority": "high",
            "due_in_hours": 4,
            "order_number": number,
        },
    )
    actions.append(action_record("cod:book_followup", "ecommerce.create_task", out))
    if _ok(out):
        task = _data(out).get("number") or "a task"
        return f"Opened {task} for staff to book it."
    return f"Could not open a follow-up task either: {_err(out)}."


def _booked_text(out: Any) -> str:
    d = _data(out)
    return f"booked with {d.get('courier')} (tracking {d.get('tracking_number')})"


async def _auto_confirm(

    deps: AgentDeps, state: RunState, number: str, prefix: str

) -> dict[str, Any]:
    out = await deps.tools.call(
        state,
        "cod:auto_confirm",
        "ecommerce.resolve_confirmation",
        {"order_number": number, "outcome": "confirmed", "source": "auto"},
    )
    actions = [action_record("cod:auto_confirm", "ecommerce.resolve_confirmation", out)]
    if not _ok(out):
        return {"actions": actions, "status": "failed", "error": _err(out)}
    book, rec = await _book(deps, state, number, "cod:book")
    actions.append(rec)
    if _ok(book):
        return {
            "actions": actions,
            "output": _join(prefix, f"Auto-confirmed and {_booked_text(book)}."),
        }
    if book.status == "rejected":
        return {
            "actions": actions,
            "status": "rejected",
            "output": _join(prefix, "Auto-confirmed; the booking was not approved."),
        }
    followup = await _booking_followup(deps, state, number, _err(book), actions)
    return {
        "actions": actions,
        "output": _join(
            prefix, f"Auto-confirmed; booking needs attention: {_err(book)}. {followup}"
        ),
    }


def _confirm_text(c: dict[str, Any]) -> str:
    # Phase 13: localized when the confirmation context carries the customer's language.
    if localized := i18n.cod_confirm_text(c, str(c.get("language") or "en")):
        return localized
    return (
        f"Assalam o Alaikum {c['customer_first_name']}! Please confirm your order "
        f"{c['order_number']} ({rs(int(c['total']))}, cash on delivery). Reply HAAN to "
        "confirm or NAHI to cancel."
    )


async def _request_confirmation(

    deps: AgentDeps, state: RunState, c: dict[str, Any], prefix: str

) -> dict[str, Any]:
    number, band = c["order_number"], c["risk"]["band"]
    actions: list[dict[str, Any]] = []
    templates = set(c.get("templates") or [])
    can_whatsapp = bool(c.get("whatsapp_connected") and c.get("phone")) and (
        c.get("window_open") or "cod_confirm_v1" in templates
    )
    if not can_whatsapp:
        # No channel to ask on: a human confirms by phone and decides on the booking.
        book, rec = await _book(deps, state, number, "cod:review")
        actions.append(rec)
        if _ok(book):
            return {
                "actions": actions,
                "output": _join(prefix, f"Reviewed by a human and {_booked_text(book)}."),
            }
        if book.status == "rejected":
            return {
                "actions": actions,
                "status": "rejected",
                "output": _join(prefix, "A human declined the booking."),
            }
        followup = await _booking_followup(deps, state, number, _err(book), actions)
        return {
            "actions": actions,
            "status": "failed",
            "error": _err(book),
            "output": _join(prefix, f"Booking failed: {_err(book)}. {followup}"),
        }

    link = None
    advance = c.get("advance_payment") or {}
    if band == "high" and advance.get("enabled") and "cod_advance_payment_v1" in templates:
        out = await deps.tools.call(
            state,
            "cod:paylink",
            "ecommerce.create_payment_link",
            {"order_number": number, "provider": advance.get("provider") or "jazzcash"},
        )
        actions.append(action_record("cod:paylink", "ecommerce.create_payment_link", out))
        if _ok(out):
            link = _data(out)["link"]

    # Cost: a session message inside the customer's 24-hour window is free; otherwise the
    # utility template (paid per message) with quick-reply buttons.
    if c.get("window_open"):
        args: dict[str, Any] = {"to": c["phone"], "text": _confirm_text(c), "order_number": number}
    else:
        args = {
            "to": c["phone"],
            "template": "cod_confirm_v1",
            "template_params": [c["customer_first_name"], number, f"{int(c['total']):,}"],
            "buttons": [f"CONFIRM:{number}", f"CANCEL:{number}"],
            "order_number": number,
        }
    out = await deps.tools.call(state, "cod:send", "ecommerce.send_whatsapp", args)
    actions.append(action_record("cod:send", "ecommerce.send_whatsapp", out))
    if not _ok(out):
        book, rec = await _book(deps, state, number, "cod:review")
        actions.append(rec)
        if _ok(book):
            return {
                "actions": actions,
                "output": _join(
                    prefix, f"WhatsApp failed; reviewed by a human and {_booked_text(book)}."
                ),
            }
        status = "rejected" if book.status == "rejected" else "failed"
        return {
            "actions": actions,
            "status": status,
            "error": _err(out),
            "output": _join(prefix, f"Could not ask the customer: {_err(out)}."),
        }
    message_id = _data(out).get("message_id")

    if link:
        out = await deps.tools.call(
            state,
            "cod:send_advance",
            "ecommerce.send_whatsapp",
            {
                "to": c["phone"],
                "template": "cod_advance_payment_v1",
                "template_params": [
                    c["customer_first_name"],
                    number,
                    f"{int(link['amount']):,}",
                    link["url"],
                ],
                "order_number": number,
            },
        )
        actions.append(action_record("cod:send_advance", "ecommerce.send_whatsapp", out))

    out = await deps.tools.call(
        state,
        "cod:start",
        "ecommerce.start_confirmation",
        {
            "order_number": number,
            "channel": "whatsapp",
            "message_id": message_id,
            "band": band,
            "payment_link": link,
        },
    )
    actions.append(action_record("cod:start", "ecommerce.start_confirmation", out))
    if not _ok(out):
        return {"actions": actions, "status": "failed", "error": _err(out)}
    hours = c.get("timeout_hours", 24)
    extra = " A human reviews the booking if they confirm." if band == "high" else ""
    pay = f" Sent an advance-payment link ({rs(int(link['amount']))})." if link else ""
    return {
        "actions": actions,
        "output": _join(
            prefix,
            "Asked the customer to confirm on WhatsApp; waiting up to "
            f"{hours:g} hours.{pay}{extra}",
        ),
    }


def cod_confirm_graph(deps: AgentDeps) -> Any:
    """Intent ``ecommerce.cod_confirm`` (payload ``{"order_number"}``)."""
    nodes = confirmation_nodes(deps, chained=False)
    g = subgraph_builder()
    for name, fn in nodes.items():
        g.add_node(name, fn)
    g.add_edge(START, "cod_context")
    g.add_conditional_edges("cod_context", _stop_if_skip, {"next": "cod_score", "stop": END})
    g.add_conditional_edges("cod_score", stop_if_done, {"next": "cod_route", "stop": END})
    g.add_edge("cod_route", END)
    return g.compile()


def order_created_graph(deps: AgentDeps) -> Any:
    """``ecommerce.order.created``: apply the store webhook (Phase 6), then, for a new COD

    order of a tenant with ``cod.confirm_on_create``, run the confirmation steps."""
    from packs.ecommerce.graphs import store_event_graph

    nodes = confirmation_nodes(deps, chained=True)
    g = subgraph_builder()
    g.add_node("apply", store_event_graph(deps, "ecommerce.order.created"))

    async def keep_output(state: RunState) -> dict[str, Any]:
        return {"facts": _facts(state, applied_output=state.get("output"))}

    async def merge_output(state: RunState) -> dict[str, Any]:
        first = (state.get("facts") or {}).get("applied_output")
        return {"output": _join(first and f"{first}.", state.get("output"))}

    g.add_node("keep", keep_output)
    for name, fn in nodes.items():
        g.add_node(name, fn)
    g.add_node("merge", merge_output)
    g.add_edge(START, "apply")
    g.add_conditional_edges("apply", stop_if_done, {"next": "keep", "stop": END})
    g.add_edge("keep", "cod_context")
    g.add_conditional_edges("cod_context", _stop_if_skip, {"next": "cod_score", "stop": "restore"})

    async def restore(state: RunState) -> dict[str, Any]:
        return {"output": (state.get("facts") or {}).get("applied_output")}

    g.add_node("restore", restore)
    g.add_edge("restore", END)
    g.add_conditional_edges("cod_score", stop_if_done, {"next": "cod_route", "stop": END})
    g.add_edge("cod_route", "merge")
    g.add_edge("merge", END)
    return g.compile()


# ------------------------------------------------------------------ replies (support_inbound)


async def cod_check_node(deps: AgentDeps, state: RunState) -> dict[str, Any]:
    """Is this inbound WhatsApp message an answer to a COD confirmation? Sets

    ``facts.cod_reply`` = {order_number, decision, source} or leaves it unset."""
    event = Event.model_validate(state["event"])
    if event.source != "whatsapp" or not event.payload.get("from"):
        return {}
    facts = state.get("facts") or {}
    reply_to = (facts.get("inbound") or {}).get("reply_to") or {}
    rule = classify(event.text, event.payload.get("button_payload"))
    number: str | None = rule.order_number
    source: str = rule.source
    actions: list[dict[str, Any]] = []
    if number is None:
        # Reply context names the order; a typed reply without context ("haan bhej do")
        # falls back to the latest pending confirmation for the sender's phone.
        lookup: dict[str, Any] = (
            {"order_number": reply_to["order_number"]}
            if reply_to.get("order_number")
            else {"phone": inbound.sender_of(event)}
        )
        out = await deps.tools.call(state, "cod:find", "ecommerce.find_open_confirmation", lookup)
        actions.append(action_record("cod:find", "ecommerce.find_open_confirmation", out))
        attempt = _data(out).get("attempt") if _ok(out) else None
        if attempt is None and reply_to.get("template") not in COD_TEMPLATES:
            return {"actions": actions}
        number = (attempt or {}).get("order_number") or reply_to.get("order_number")
    decision = rule.decision
    if decision == "UNCLEAR":
        try:
            fields, _ = await extract(
                deps.models.worker,
                ConfirmationReply,
                event.text or "",
                task="The customer was asked to confirm a cash-on-delivery order. Did they "
                "confirm it, cancel it, ask to change the delivery address, or is it unclear?",
            )
            decision, source = fields.decision, "extractor"
        except Exception:
            decision = "UNCLEAR"
    if decision == "UNCLEAR":
        return {"actions": actions, "log": ["reply to a COD confirmation is unclear"]}
    return {
        "actions": actions,
        "facts": _facts(
            state, cod_reply={"order_number": number, "decision": decision, "source": source}
        ),
        "log": [f"COD confirmation reply for {number}: {decision} ({source})"],
    }


def after_cod_check(state: RunState) -> str:
    return "cod_reply" if (state.get("facts") or {}).get("cod_reply") else "extract"


async def cod_reply_node(deps: AgentDeps, state: RunState) -> dict[str, Any]:
    event = Event.model_validate(state["event"])
    r = state["facts"]["cod_reply"]
    number, decision, source = r["order_number"], r["decision"], r["source"]
    order, rec = await _lookup(deps, state, number, "cod:lookup")
    actions = [rec]
    if order is None:
        return {"actions": actions, "output": f"Confirmation reply for unknown order {number}."}
    if inbound.sender_on_file(event, order) is False:
        return {
            "actions": actions,
            "output": f"Confirmation reply for {number} came from a number not on file; ignored.",
        }
    reply_id = ((state.get("facts") or {}).get("inbound") or {}).get("message_id")
    first = ((order.get("customer") or {}).get("name") or "Customer").split()[0]
    lang = reply_language(event)  # Phase 13: acknowledge in the customer's language

    async def resolve(outcome: str, src: str) -> tuple[bool, dict[str, Any]]:
        args: dict[str, Any] = {"order_number": number, "outcome": outcome, "source": src}
        if reply_id:
            args["reply_message_id"] = reply_id
        out = await deps.tools.call(state, "cod:resolve", "ecommerce.resolve_confirmation", args)
        actions.append(action_record("cod:resolve", "ecommerce.resolve_confirmation", out))
        return _ok(out), _data(out)

    async def ack(text: str) -> None:
        _, rec = await inbound.reply_whatsapp(deps, state, order, "cod:ack", text)
        actions.append(rec)

    async def confirm_and_book(src: str) -> dict[str, Any]:
        ok, data = await resolve("confirmed", src)
        if not ok:
            return {"actions": actions, "output": f"Nothing to confirm for {number}."}
        if data.get("already"):
            return {"actions": actions, "output": f"{number} was already confirmed."}
        out = await deps.tools.call(
            state,
            "cod:rescore",
            "ecommerce.score_order_risk",
            {"order_number": number, "stage": "confirmation"},
        )
        actions.append(action_record("cod:rescore", "ecommerce.score_order_risk", out))
        book, brec = await _book(deps, state, number, "cod:book")
        actions.append(brec)
        if _ok(book):
            d = _data(book)
            await ack(
                i18n.cod_confirmed_ack(
                    first, number, d.get("courier"), d.get("tracking_number"), lang
                )
                or f"Shukriya {first}! Your order {number} is confirmed and booked with "
                f"{d.get('courier')} (tracking {d.get('tracking_number')})."
            )
            return {
                "actions": actions,
                "output": f"Customer confirmed {number}; {_booked_text(book)}.",
            }
        if book.status == "rejected":
            return {
                "actions": actions,
                "status": "rejected",
                "output": f"Customer confirmed {number}; a human declined the booking.",
            }
        return {
            "actions": actions,
            "output": f"Customer confirmed {number}; booking needs attention: {_err(book)}.",
        }

    if decision == "CONFIRM":
        return await confirm_and_book(source)

    if decision == "CANCEL":
        ok, _ = await resolve("rejected", source)
        if not ok:
            return {"actions": actions, "output": f"Nothing to cancel for {number}."}
        out = await deps.tools.call(
            state,
            "cod:cancel",
            "ecommerce.cancel_order",
            {
                "order_numbers": [number],
                "reason": "customer_rejected",
                "note": "customer declined at COD confirmation",
            },
        )
        actions.append(action_record("cod:cancel", "ecommerce.cancel_order", out))
        if not _ok(out):
            status = "rejected" if out.status == "rejected" else "failed"
            return {"actions": actions, "status": status, "error": _err(out)}
        await ack(
            i18n.cod_cancelled_ack(first, number, lang)
            or f"Theek hai {first}, your order {number} has been cancelled as you asked."
        )
        return {"actions": actions, "output": f"Customer declined {number}; order cancelled."}

    # ADDRESS_CHANGE: the new address is untrusted text, so the update needs a human.
    address = city = None
    try:
        fields, _ = await extract(
            deps.models.worker,
            AddressChangeFields,
            event.text or "",
            task="The customer wants their order delivered to a different address. Extract "
            "the new address and city, if given.",
        )
        address, city = fields.new_address, fields.city
    except Exception:
        address = None
    address = (address or event.text or "").strip()[:400]
    if len(address) < 5:
        address = f"(customer asked to change the address: {(event.text or '')[:300]})"
    args: dict[str, Any] = {"order_number": number, "address": Tainted(address, source="whatsapp")}
    if city:
        args["city"] = Tainted(city, source="whatsapp")
    out = await deps.tools.call(state, "cod:address", "ecommerce.update_shipping_address", args)
    actions.append(action_record("cod:address", "ecommerce.update_shipping_address", out))
    if out.status == "rejected":
        return {
            "actions": actions,
            "status": "rejected",
            "output": f"Address change for {number} was not approved; the order stays "
            "pending confirmation.",
        }
    if not _ok(out):
        return {"actions": actions, "status": "failed", "error": _err(out)}
    return await confirm_and_book("address_change")


# ------------------------------------------------------------------ timeout sweep


def cod_sweep_graph(deps: AgentDeps) -> Any:
    """``ecommerce.cod_sweep`` (tenant schedule): expire unanswered confirmations, then

    escalate them to the inbox as one batch cancellation approval."""

    async def node(state: RunState) -> dict[str, Any]:
        event = Event.model_validate(state["event"])
        args: dict[str, Any] = {}
        if event.payload.get("as_of"):
            args["as_of"] = event.payload["as_of"]
        out = await deps.tools.call(state, "sweep:expire", "ecommerce.expire_confirmations", args)
        actions = [action_record("sweep:expire", "ecommerce.expire_confirmations", out)]
        if not _ok(out):
            return {"actions": actions, "status": "failed", "error": _err(out)}
        expired = _data(out)["expired"]
        if not expired:
            return {"actions": actions, "output": "No COD confirmations have timed out."}
        numbers = [e["order_number"] for e in expired]
        out = await deps.tools.call(
            state,
            "sweep:escalate",
            "ecommerce.cancel_order",
            {
                "order_numbers": numbers,
                "reason": "no_answer",
                "note": "no answer to the COD confirmation before the deadline",
            },
        )
        actions.append(action_record("sweep:escalate", "ecommerce.cancel_order", out))
        listed = ", ".join(numbers)
        if _ok(out):
            return {
                "actions": actions,
                "output": f"{len(numbers)} COD orders did not answer ({listed}); a human "
                "approved cancelling them.",
            }
        if out.status == "rejected":
            return {
                "actions": actions,
                "status": "rejected",
                "output": f"{len(numbers)} COD orders did not answer ({listed}); kept for "
                "a phone follow-up." + (f" Note: {out.note}" if out.note else ""),
            }
        return {"actions": actions, "status": "failed", "error": _err(out)}

    g = subgraph_builder()
    g.add_node("sweep", node)
    g.add_edge(START, "sweep")
    g.add_edge("sweep", END)
    return g.compile()


# ------------------------------------------------------------------ couriers


async def _notify_status(

    deps: AgentDeps, state: RunState, change: dict[str, Any], step: str

) -> dict[str, Any] | None:
    """Tell the customer on file about out-for-delivery / delivered / failed attempts with

    the ``order_update`` utility template. Best effort: a missing template is not a failure."""
    number = change.get("order_number")
    if not number or not change.get("notify"):
        return None
    order, rec = await _lookup(deps, state, number, f"{step}:lookup")
    phone = ((order or {}).get("customer") or {}).get("phone") or (order or {}).get("ship_phone")
    if order is None or not phone:
        return rec
    first = ((order.get("customer") or {}).get("name") or "Customer").split()[0]
    out = await deps.tools.call(
        state,
        step,
        "ecommerce.send_whatsapp",
        {
            "to": phone,
            "template": "order_update",
            "template_params": [first, number, STATUS_TEXT.get(change["status"], change["status"])],
            "order_number": number,
        },
    )
    return action_record(step, "ecommerce.send_whatsapp", out)


def courier_status_graph(deps: AgentDeps) -> Any:
    """``ecommerce.courier_status`` (alias ``courier.status``, a generic signed webhook with

    ``{"courier", "tracking_number", "status", ...}`` or the courier's own body)."""

    async def node(state: RunState) -> dict[str, Any]:
        event = Event.model_validate(state["event"])
        body = event.payload.get("body") or event.payload
        courier = str(event.payload.get("courier") or body.get("courier") or "")
        out = await deps.tools.call(
            state, "apply", "ecommerce.apply_courier_status", {"courier": courier, "payload": body}
        )
        actions = [action_record("apply", "ecommerce.apply_courier_status", out)]
        if not _ok(out):
            return {"actions": actions, "status": "failed", "error": _err(out)}
        d = _data(out)
        if not d["changed"]:
            return {
                "actions": actions,
                "output": f"{d['tracking_number']}: no change ({d['status']}).",
            }
        rec = await _notify_status(deps, state, d, "notify")
        if rec:
            actions.append(rec)
        return {
            "actions": actions,
            "output": f"{d['order_number']} ({d['courier']} {d['tracking_number']}): "
            f"{d['status_before']} -> {d['status']}.",
        }

    g = subgraph_builder()
    g.add_node("status", node)
    g.add_edge(START, "status")
    g.add_edge("status", END)
    return g.compile()


def courier_poll_graph(deps: AgentDeps) -> Any:
    """``ecommerce.courier_poll`` (tenant schedule): the polling fallback for couriers

    without webhooks."""

    async def node(state: RunState) -> dict[str, Any]:
        out = await deps.tools.call(state, "poll", "ecommerce.poll_courier_updates", {})
        actions = [action_record("poll", "ecommerce.poll_courier_updates", out)]
        if not _ok(out):
            return {"actions": actions, "status": "failed", "error": _err(out)}
        d = _data(out)
        for ch in d["changes"][:20]:
            rec = await _notify_status(deps, state, ch, f"notify:{ch['tracking_number']}")
            if rec:
                actions.append(rec)
        return {
            "actions": actions,
            "output": f"Checked {d['checked']} shipments: {len(d['changes'])} changed, "
            f"{d['skipped']} skipped.",
        }

    g = subgraph_builder()
    g.add_node("poll", node)
    g.add_edge(START, "poll")
    g.add_edge("poll", END)
    return g.compile()


def cod_reconcile_graph(deps: AgentDeps) -> Any:
    """``ecommerce.cod_reconcile`` (schedule or operator chat): fetch settlements from courier

    APIs (payload ``couriers``), then reconcile and report."""

    async def node(state: RunState) -> dict[str, Any]:
        event = Event.model_validate(state["event"])
        actions = []
        for key in event.payload.get("couriers") or []:
            out = await deps.tools.call(
                state, f"fetch:{key}", "ecommerce.fetch_remittance", {"courier": key}
            )
            actions.append(action_record(f"fetch:{key}", "ecommerce.fetch_remittance", out))
        args: dict[str, Any] = {}
        if event.payload.get("as_of"):
            args["as_of"] = event.payload["as_of"]
        out = await deps.tools.call(state, "reconcile", "ecommerce.reconcile_cod", args)
        actions.append(action_record("reconcile", "ecommerce.reconcile_cod", out))
        if not _ok(out):
            return {"actions": actions, "status": "failed", "error": _err(out)}
        d = _data(out)
        kinds = ", ".join(f"{n} {k.replace('_', ' ')}" for k, n in d["by_kind"].items())
        return {
            "actions": actions,
            "output": f"COD reconciliation: {d['open_issues']} open issues"
            + (f" ({kinds})." if kinds else "."),
        }

    g = subgraph_builder()
    g.add_node("reconcile", node)
    g.add_edge(START, "reconcile")
    g.add_edge("reconcile", END)
    return g.compile()