lkeab's picture
Add files using upload-large-folder tool
d45a493 verified
Raw
History Blame Contribute Delete
28.1 kB
"""
Reward Script: X2 — Won deal to invoice to notification
Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_x2.py
Variant: eval
Mocks: hubspot_mock,quickbooks_mock,gmail_mock
"""
import copy
import re
import sys
import requests
try:
with open('/tmp/task_web_sid', encoding='utf-8') as f:
sid = f.read().strip()
if not sid:
raise ValueError('sid is empty')
except Exception as e:
print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
print('REWARD: 0.0')
sys.exit(0)
APP_URLS = {'hubspot': 'http://28.7.184.198:8150', 'quickbooks': 'http://28.7.184.198:8172', 'gmail': 'http://28.7.184.198:8138'}
_GO_CACHE = {}
def clamp01(x):
return max(0.0, min(1.0, float(x)))
def frac(num, den):
return 0.0 if den == 0 else num / den
def f1(true_set, pred_set):
if not true_set and not pred_set:
return 1.0
tp = len(true_set & pred_set)
if tp == 0:
return 0.0
prec = tp / len(pred_set)
rec = tp / len(true_set)
return 2 * prec * rec / (prec + rec)
def by_id(items, key='id'):
return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
def has_text(haystack, *needles):
s = (haystack or '').lower()
return any(n.lower() in s for n in needles)
def norm(s):
return (str(s) if s is not None else '').strip().lower()
def _deal_amount(deal):
if not isinstance(deal, dict):
return 0.0
line_items = deal.get('lineItems') or []
if isinstance(line_items, list) and line_items:
total = 0.0
for item in line_items:
if isinstance(item, dict):
try:
total += float(item.get('amount', 0) or 0)
except (TypeError, ValueError):
continue
return total
try:
return float(deal.get('amount', 0) or 0)
except (TypeError, ValueError):
return 0.0
def _invoice_customer_name(iv):
if not isinstance(iv, dict):
return ''
customer = iv.get('customer')
if isinstance(customer, dict):
return customer.get('name') or customer.get('displayName') or customer.get('customerName') or customer.get('fullName') or ''
if isinstance(customer, list):
for c in customer:
if isinstance(c, dict):
name = c.get('name') or c.get('displayName') or c.get('customerName') or c.get('fullName')
if name:
return name
elif c:
return str(c)
return customer or iv.get('customerName') or iv.get('name') or iv.get('displayName') or iv.get('customerDisplayName') or ''
def _invoice_total(iv):
if not isinstance(iv, dict):
return 0.0
for key in ('total', 'amount', 'invoiceTotal', 'balance', 'totalAmount', 'amountDue', 'amount_total'):
value = iv.get(key)
if isinstance(value, dict):
value = value.get('amount') or value.get('value')
try:
return float(value or 0)
except (TypeError, ValueError):
continue
line_items = iv.get('lineItems') or iv.get('items') or iv.get('lines')
if isinstance(line_items, list) and line_items:
total = 0.0
for item in line_items:
if not isinstance(item, dict):
continue
raw = item.get('amount')
if raw is None:
qty = item.get('quantity', 1)
unit = item.get('unitPrice') or item.get('rate') or item.get('price')
try:
raw = float(qty or 0) * float(unit or 0)
except (TypeError, ValueError):
raw = 0
try:
total += float(raw or 0)
except (TypeError, ValueError):
continue
return total
return 0.0
def _notes_text(deal):
if not isinstance(deal, dict):
return ''
chunks = []
notes = deal.get('notes', [])
if isinstance(notes, list):
for x in notes:
if isinstance(x, dict):
chunks.append(str(x.get('body') or x.get('content') or x.get('text') or x.get('note') or x))
else:
chunks.append(str(x))
elif notes:
chunks.append(str(notes))
for key in ('activity', 'activities', 'timeline', 'comments'):
value = deal.get(key)
if isinstance(value, list):
for v in value:
if isinstance(v, dict):
chunks.append(str(v.get('body') or v.get('content') or v.get('text') or v.get('note') or v))
else:
chunks.append(str(v))
elif value:
chunks.append(str(value))
return ' '.join(chunks)
def _email_text(email):
if not isinstance(email, dict):
return str(email)
to = email.get('to', '')
if isinstance(to, list):
to = ' '.join(
(x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x)
for x in to
)
elif isinstance(to, dict):
to = to.get('name') or to.get('email') or str(to)
to_recips = email.get('toRecipients', [])
if isinstance(to_recips, list):
to_recips = ' '.join(
(x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x)
for x in to_recips
)
else:
to_recips = ''
return f"{to} {to_recips} {email.get('subject', '')} {email.get('body', '')}"
def _gmail_sent_emails(gmail_state):
out = []
if not isinstance(gmail_state, dict):
return out
for e in gmail_state.get('emails', []):
if not isinstance(e, dict):
continue
folder = norm(e.get('folder'))
if folder in ('sent', 'sentitems', 'sent items'):
out.append(e)
continue
if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'):
out.append(e)
if out:
return out
for key in ('sent', 'sentEmails', 'outbox'):
items = gmail_state.get(key, [])
if isinstance(items, list):
out.extend(x for x in items if isinstance(x, dict))
return out
def _normalize_app_name(app):
app = (app or '').strip().lower()
return app[:-5] if app.endswith('_mock') else app
def _parse_cell_id(cell_id):
if not isinstance(cell_id, str) or not cell_id:
return None
idx = 0
while idx < len(cell_id) and cell_id[idx].isalpha():
idx += 1
if idx == 0 or idx >= len(cell_id):
return None
col = 0
for ch in cell_id[:idx].upper():
col = col * 26 + (ord(ch) - ord('A') + 1)
try:
row = int(cell_id[idx:])
except ValueError:
return None
return row, col - 1
def _extract_rows_from_workbook(state):
if not isinstance(state, dict):
return None
sheets = state.get('sheets')
if not isinstance(sheets, list):
return None
adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
out = {}
for sh in sheets:
if not isinstance(sh, dict):
continue
name = sh.get('name') or sh.get('id') or 'Sheet1'
data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
headers = headers_by_sheet.get(name)
if not headers:
cols = []
for cid, cell in data.items():
rc = _parse_cell_id(cid)
if not rc:
continue
row_idx, col_idx = rc
if row_idx != 1:
continue
value = ''
if isinstance(cell, dict):
value = cell.get('value', '')
elif cell is not None:
value = str(cell)
if value is not None and str(value) != '':
cols.append((col_idx, str(value)))
headers = [v for _, v in sorted(cols)]
if not headers:
continue
by_row = {}
for cid, cell in data.items():
rc = _parse_cell_id(cid)
if not rc:
continue
row_idx, col_idx = rc
if row_idx <= 1 or col_idx >= len(headers):
continue
if isinstance(cell, dict):
value = cell.get('value', '')
else:
value = cell
by_row.setdefault(row_idx, {})[headers[col_idx]] = value
rows = []
for row_idx in sorted(by_row.keys()):
row = by_row[row_idx]
if not any(str(row.get(h, '')).strip() for h in headers):
continue
rows.append({h: row.get(h, '') for h in headers})
out[name] = {'headers': headers, 'rows': rows}
if not out:
return None
return {'sheets': out}
def _materialize_google_sheets(payload):
for key in ('initial_state', 'current_state'):
state = payload.get(key)
if not isinstance(state, dict):
continue
maybe_rows = _extract_rows_from_workbook(state)
if maybe_rows is not None:
state['_ui_workbook'] = {
'sheets': copy.deepcopy(state.get('sheets', [])),
'title': state.get('title'),
}
state['sheets'] = maybe_rows['sheets']
def _materialize_slack(payload):
for key in ('initial_state', 'current_state'):
state = payload.get(key)
if not isinstance(state, dict):
continue
channels = state.get('channels') if isinstance(state.get('channels'), list) else []
messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
for ch in channels:
if not isinstance(ch, dict):
continue
cid = ch.get('channelId') or ch.get('id')
if not cid:
continue
msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
merged = {
(m.get('messageId') or m.get('id')): dict(m)
for m in channel_msgs
if isinstance(m, dict)
}
for m in msg_list:
if not isinstance(m, dict):
continue
mid = m.get('messageId') or m.get('id')
text = m.get('text') if m.get('text') is not None else m.get('content', '')
merged[mid] = {
'id': mid,
'messageId': mid,
'text': text,
'content': m.get('content', text),
'senderId': m.get('senderId'),
'timestamp': m.get('timestamp'),
'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
}
ch['messages'] = list(merged.values())
def _owner_name_map(state):
out = {}
users = state.get('users') if isinstance(state.get('users'), list) else []
for u in users:
if not isinstance(u, dict):
continue
uid = u.get('userId')
if not uid:
continue
name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
out[uid] = name
return out
def _materialize_salesforce(payload):
for key in ('initial_state', 'current_state'):
state = payload.get(key)
if not isinstance(state, dict):
continue
adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
owner_names = _owner_name_map(state)
task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
if task_leads and isinstance(state.get('leads'), list):
restored = []
for lead in state['leads']:
if not isinstance(lead, dict):
continue
lid = str(lead.get('leadId') or lead.get('id') or '')
meta = task_leads.get(lid, {})
restored.append({
'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
'company': lead.get('company', meta.get('company', '')),
'status': lead.get('status', 'New'),
'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
})
state['leads'] = restored
task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
if task_accounts and isinstance(state.get('accounts'), list):
current_by_id = {}
for acc in state['accounts']:
if isinstance(acc, dict):
current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
restored_accounts = []
for aid, meta in task_accounts.items():
cur = current_by_id.get(str(aid), {})
restored_accounts.append({
'id': meta.get('id') or aid,
'name': meta.get('name') or cur.get('name', ''),
'contact': meta.get('contact'),
'wonWithin7d': bool(meta.get('wonWithin7d', False)),
'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
})
state['accounts'] = restored_accounts
def _materialize_google_docs(payload):
for key in ('initial_state', 'current_state'):
state = payload.get(key)
if not isinstance(state, dict):
continue
adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
if not task_docs:
continue
docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
restored = []
for did, meta in task_docs.items():
cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
restored.append({
'id': meta.get('id') or did,
'title': cur.get('title', meta.get('title')),
'vendor': meta.get('vendor'),
'folder': meta.get('folder'),
'content': cur.get('content', meta.get('content', '')),
})
state['documents'] = restored
def _adapt_payload_for_reward(app, payload):
app_name = _normalize_app_name(app)
if app_name == 'google_sheets':
_materialize_google_sheets(payload)
elif app_name == 'slack':
_materialize_slack(payload)
elif app_name == 'salesforce':
_materialize_salesforce(payload)
elif app_name == 'google_docs':
_materialize_google_docs(payload)
return payload
def go(app_name):
if app_name in _GO_CACHE:
return _GO_CACHE[app_name]
base = APP_URLS.get(app_name)
if not base:
print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
print('REWARD: 0.0')
sys.exit(0)
try:
resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
resp.raise_for_status()
payload = resp.json()
except Exception as e:
print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
print('REWARD: 0.0')
sys.exit(0)
payload = _adapt_payload_for_reward(app_name, payload)
_GO_CACHE[app_name] = payload
return payload
# === Task-specific reward (rewritten for new schema, per-deal weighted) ===
#
# Scoring model (B-mixed, decided 2026-06-15):
# - Each April-Closed-Won deal contributes up to 1.0 to its own score.
# - 6 sub-checks per deal, weights sum to 1.0:
# A1 customer 0.15 invoice exists for this deal's company
# A2 line item 0.20 exactly 1 item with the right product/qty/rate/amount
# (must also match customer name; A2 is self-contained
# and re-checks customer to prevent cross-deal mix-up)
# A3 header 0.15 same invoice has terms/date/dueDate/tax/status correct
# (must also match customer name; self-contained)
# B1 recipient 0.10 a sent gmail email addressed to the right contact
# B2 email body 0.15 email's subject + body match the template anchors,
# with subject/body invoice number self-consistent.
# Independent of A* (does NOT require a real invoice).
# C description 0.25 deal.description contains "Invoiced INV-<digits>.".
# Independent of A* (does NOT require a real invoice).
# - total_score = sum(deal_score(d) for d in won) / n
# - n is the count of April-Closed-Won deals in the initial state.
#
# Dependency chain (B-mixed):
# A1 -> A2 (re-checks customer) and A3 (re-checks customer): A group is integrated.
# B1 -> B2 (re-checks recipient): B group is internally chained.
# C is fully standalone (matches the literal pattern in description).
# A and B and C are independent of each other.
import datetime as _dt
import re as _re
_INV_NUMBER_RE = _re.compile(r'Invoiced\s+INV-(\d+)\.', _re.IGNORECASE)
def _april_won_deals(deals_initial):
out = []
for d in deals_initial or []:
if not isinstance(d, dict):
continue
if norm(d.get('stage')) != 'closedwon':
continue
close_date = (d.get('closeDate') or '').strip()
if close_date.startswith('2026-04-'):
out.append(d)
return out
def _company_name_for_deal(deal, hubspot_initial):
company_id = deal.get('companyId')
for c in hubspot_initial.get('companies', []) or []:
if isinstance(c, dict) and c.get('id') == company_id:
return (c.get('name') or '').strip()
return (deal.get('customer') or '').strip()
def _primary_contact_for_deal(deal, hubspot_initial):
contact_ids = deal.get('contactIds') or []
if not contact_ids:
return None
cid0 = contact_ids[0]
for c in hubspot_initial.get('contacts', []) or []:
if isinstance(c, dict) and c.get('id') == cid0:
return c
return None
def _qb_customer_name_by_id(qb_state):
return {
c.get('id'): (c.get('name') or '').strip()
for c in (qb_state.get('customers') or [])
if isinstance(c, dict) and c.get('id')
}
def _qb_product_by_id(qb_state):
return {
p.get('id'): p
for p in (qb_state.get('products') or [])
if isinstance(p, dict) and p.get('id')
}
def _add_days(date_str, days):
try:
d = _dt.datetime.strptime(date_str, '%Y-%m-%d').date()
except (TypeError, ValueError):
return ''
return (d + _dt.timedelta(days=days)).isoformat()
def _invoice_items(iv):
items = iv.get('items')
if isinstance(items, list):
return items
items = iv.get('lineItems')
if isinstance(items, list):
return items
return []
def _check_a1_customer(deal, hubspot_initial, invoices, qb_cust_by_id):
target_name = norm(_company_name_for_deal(deal, hubspot_initial))
if not target_name:
return None
for iv in invoices or []:
if not isinstance(iv, dict):
continue
cust_name = norm(qb_cust_by_id.get(iv.get('customerId'), ''))
if not cust_name:
cust_name = norm(_invoice_customer_name(iv))
if cust_name and cust_name == target_name:
return iv
return None
def _check_a2_line_item(deal, hubspot_initial, invoices, qb_cust_by_id, qb_prod_by_id):
"""Self-contained: find ANY invoice for the deal's company that has the right
single line item. Independent of A1's pick (but typically returns same one)."""
target_name = norm(_company_name_for_deal(deal, hubspot_initial))
if not target_name:
return False
deal_name = deal.get('name') or ''
if ' - ' not in deal_name:
return False
expected_product = deal_name.split(' - ', 1)[1].strip()
deal_amt = _deal_amount(deal)
for invoice in invoices or []:
if not isinstance(invoice, dict):
continue
cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), ''))
if not cust_name:
cust_name = norm(_invoice_customer_name(invoice))
if cust_name != target_name:
continue
items = _invoice_items(invoice)
if len(items) != 1:
continue
item = items[0]
if not isinstance(item, dict):
continue
product = qb_prod_by_id.get(item.get('productId')) or {}
if norm(product.get('name', '')) != norm(expected_product):
continue
try:
qty = float(item.get('qty', 0) or 0)
except (TypeError, ValueError):
qty = 0
if abs(qty - 1.0) > 1e-6:
continue
try:
rate = float(item.get('rate', 0) or 0)
amt = float(item.get('amount', 0) or 0)
except (TypeError, ValueError):
continue
if abs(rate - deal_amt) > 0.5 or abs(amt - deal_amt) > 0.5:
continue
return True
return False
def _check_a3_header(deal, hubspot_initial, invoices, qb_cust_by_id):
"""Self-contained: find ANY invoice for the deal's company with correct header."""
target_name = norm(_company_name_for_deal(deal, hubspot_initial))
if not target_name:
return False
close_date = (deal.get('closeDate') or '').strip()
expected_due = _add_days(close_date, 30)
for invoice in invoices or []:
if not isinstance(invoice, dict):
continue
cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), ''))
if not cust_name:
cust_name = norm(_invoice_customer_name(invoice))
if cust_name != target_name:
continue
if norm(invoice.get('terms')) != 'net 30':
continue
if (invoice.get('date') or '').strip() != close_date:
continue
if (invoice.get('dueDate') or '').strip() != expected_due:
continue
try:
tax = float(invoice.get('tax', 0) or 0)
except (TypeError, ValueError):
tax = 0
if abs(tax) > 0.01:
continue
if norm(invoice.get('status')) != 'sent':
continue
return True
return False
def _check_b1_recipient(deal, hubspot_initial, sent_emails):
contact = _primary_contact_for_deal(deal, hubspot_initial)
if not contact:
return None
target_email = norm(contact.get('email'))
if not target_email:
return None
for e in sent_emails or []:
if not isinstance(e, dict):
continue
if target_email in norm(_email_text(e)):
return e
return None
def _check_b2_email_body(deal, hubspot_initial, sent_emails):
"""Self-contained: find ANY sent email to the deal's primary contact whose
subject contains 'Invoice #<n>', body contains 'INVOICE #<n>' (same <n>),
'Total: $<deal.amount>', and 'Status: Sent'. Independent of any QB invoice."""
contact = _primary_contact_for_deal(deal, hubspot_initial)
if not contact:
return False
target_email = norm(contact.get('email'))
if not target_email:
return False
deal_amt = _deal_amount(deal)
amt_int = 'total: ${}'.format(int(round(deal_amt)))
amt_dec = 'total: ${:.2f}'.format(deal_amt)
subject_re = _re.compile(r'invoice\s*#\s*(\d+)')
for e in sent_emails or []:
if not isinstance(e, dict):
continue
if target_email not in norm(_email_text(e)):
continue
subject = norm(e.get('subject') or '')
body = e.get('body') or ''
body_text = _re.sub(r'<[^>]+>', ' ', body)
nb = norm(body_text)
m_sub = subject_re.search(subject)
if not m_sub:
continue
n = m_sub.group(1)
# Body must reference the SAME number (self-consistent).
if 'invoice #{}'.format(n) not in nb:
continue
if amt_int not in nb and amt_dec not in nb:
continue
if 'status: sent' not in nb:
continue
return True
return False
def _check_c_description(deal_current):
"""Self-contained: deal.description contains 'Invoiced INV-<digits>.'.
Independent of any QB invoice. (Falls back to deal.notes for legacy agents.)"""
if not deal_current:
return False
desc = deal_current.get('description') or ''
if _INV_NUMBER_RE.search(desc):
return True
notes_text = _notes_text(deal_current)
if _INV_NUMBER_RE.search(notes_text):
return True
return False
WEIGHTS = {
'A1_customer': 0.15,
'A2_line_item': 0.20,
'A3_header': 0.15,
'B1_recipient': 0.10,
'B2_email': 0.15,
'C_description': 0.25,
}
def reward(go):
hubspot_i = go('hubspot').get('initial_state', {}) or {}
hubspot_c = go('hubspot').get('current_state', {}) or {}
qb_c = go('quickbooks').get('current_state', {}) or {}
gmail_c = go('gmail').get('current_state', {}) or {}
deals_i = hubspot_i.get('deals', []) or []
deals_c_by_id = {
d.get('id'): d
for d in (hubspot_c.get('deals', []) or [])
if isinstance(d, dict)
}
invoices = qb_c.get('invoices', []) or []
qb_cust_by_id = _qb_customer_name_by_id(qb_c)
qb_prod_by_id = _qb_product_by_id(qb_c)
sent_emails = _gmail_sent_emails(gmail_c)
won = _april_won_deals(deals_i)
n = len(won)
if n == 0:
print('DEBUG_054e615f n=0 -> vacuous REWARD=1.0')
return 1.0
per_deal_lines = []
pass_counts = {k: 0 for k in WEIGHTS}
total = 0.0
for d in won:
deal_id = d.get('id')
deal_current = deals_c_by_id.get(deal_id, {})
# A1 picks an invoice for debug logging; A2/A3 are self-contained
# but conceptually still belong to the same A group.
invoice = _check_a1_customer(d, hubspot_i, invoices, qb_cust_by_id)
checks = {
'A1_customer': invoice is not None,
'A2_line_item': _check_a2_line_item(d, hubspot_i, invoices, qb_cust_by_id, qb_prod_by_id),
'A3_header': _check_a3_header(d, hubspot_i, invoices, qb_cust_by_id),
'B1_recipient': _check_b1_recipient(d, hubspot_i, sent_emails) is not None,
'B2_email': _check_b2_email_body(d, hubspot_i, sent_emails),
'C_description': _check_c_description(deal_current),
}
deal_score = 0.0
for k, ok in checks.items():
if ok:
deal_score += WEIGHTS[k]
pass_counts[k] += 1
total += deal_score
flags = ' '.join(
'{}={}'.format(k.split('_', 1)[0], 'Y' if v else 'N')
for k, v in checks.items()
)
company = _company_name_for_deal(d, hubspot_i) or '?'
per_deal_lines.append(
' {} {:<12s}: score={:.3f} {}'.format(deal_id, company, deal_score, flags)
)
score = total / n
print('DEBUG_054e615f n={}'.format(n))
for line in per_deal_lines:
print(line)
rates = ' '.join('{}={}/{}'.format(k.split('_', 1)[0], pass_counts[k], n) for k in WEIGHTS)
print('sub-check pass rates: {}'.format(rates))
print('total = sum / n = {:.4f} / {} = {:.4f}'.format(total, n, score))
return clamp01(score)
try:
score = float(reward(go))
except Exception as exc:
print(f'ERROR: reward() raised {exc!r}')
score = 0.0
score = clamp01(score)
print(f'\nREWARD: {round(score, 4)}')