bitfab-py 0.78.4__tar.gz → 0.78.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/PKG-INFO +1 -1
  2. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/gmail_sandbox.py +306 -71
  3. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/pyproject.toml +1 -1
  4. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/README.md +0 -0
  5. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/__init__.py +0 -0
  6. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/agent_middleware.py +0 -0
  7. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/approval.py +0 -0
  8. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/assertion_categories.py +0 -0
  9. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/baml.py +0 -0
  10. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/baml_auto_trace.py +0 -0
  11. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/categories.py +0 -0
  12. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/claude_agent_sdk.py +0 -0
  13. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/client.py +0 -0
  14. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/client_patching.py +0 -0
  15. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/cloudReplay.py +0 -0
  16. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/cloud_replay_cli.py +0 -0
  17. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/commit_ref.py +0 -0
  18. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/compress.py +0 -0
  19. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/constants.py +0 -0
  20. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/datasets.py +0 -0
  21. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/db_snapshot.py +0 -0
  22. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/error_chain.py +0 -0
  23. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/experiment_id.py +0 -0
  24. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/experiments.py +0 -0
  25. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/finalizers.py +0 -0
  26. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/git_command.py +0 -0
  27. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/git_state.py +0 -0
  28. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/google_calls.py +0 -0
  29. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/graders.py +0 -0
  30. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/http.py +0 -0
  31. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/integration_fixture.py +0 -0
  32. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/jev.py +0 -0
  33. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/labels.py +0 -0
  34. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/langgraph.py +0 -0
  35. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/langgraph_integration.py +0 -0
  36. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/langgraph_runs.py +0 -0
  37. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/mock_matching.py +0 -0
  38. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/mock_override.py +0 -0
  39. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/openai_agent_sdk.py +0 -0
  40. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/openai_agents_usage.py +0 -0
  41. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/organization_members.py +0 -0
  42. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/otel.py +0 -0
  43. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/payload_budget.py +0 -0
  44. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/processor_payload.py +0 -0
  45. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/provider_calls.py +0 -0
  46. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay.py +0 -0
  47. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_branch.py +0 -0
  48. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_cli.py +0 -0
  49. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_heartbeat.py +0 -0
  50. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_interrupt.py +0 -0
  51. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_invocation.py +0 -0
  52. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_memory.py +0 -0
  53. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_processes.py +0 -0
  54. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/replay_registry.py +0 -0
  55. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/sandbox.py +0 -0
  56. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/seed_cli.py +0 -0
  57. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/selective_replay.py +0 -0
  58. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/serialize.py +0 -0
  59. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/service_calls.py +0 -0
  60. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/simulation_plan.py +0 -0
  61. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/span_meta.py +0 -0
  62. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/span_origin.py +0 -0
  63. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/spans.py +0 -0
  64. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/subtree.py +0 -0
  65. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/thread_propagation.py +0 -0
  66. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/timestamp.py +0 -0
  67. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/trace_completion.py +0 -0
  68. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/trace_metadata.py +0 -0
  69. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/trace_payload.py +0 -0
  70. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/traces.py +0 -0
  71. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/tracing.py +0 -0
  72. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/transport.py +0 -0
  73. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/transport_types.py +0 -0
  74. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/verdicts.py +0 -0
  75. {bitfab_py-0.78.4 → bitfab_py-0.78.5}/bitfab/warn_once.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bitfab-py
3
- Version: 0.78.4
3
+ Version: 0.78.5
4
4
  Summary: Bitfab client for provider-based API calls with local BAML execution
5
5
  Author: Harvest Team
6
6
  Requires-Python: >=3.10
@@ -55,6 +55,16 @@ _PLAIN_HEADERS = {
55
55
  }
56
56
  _TOKEN = re.compile(r'-?[A-Za-z_]+:"[^"]*"|-?[A-Za-z_]+:\S+|-?"[^"]*"|\S+')
57
57
  _OPERATOR = re.compile(r"^[A-Za-z_]+:")
58
+ _QUERY_TOKEN = re.compile(
59
+ r'-?[A-Za-z_]+:\(|-?[A-Za-z_]+:"[^"]*"|-?[A-Za-z_]+:[^\s(){}]+|-?"[^"]*"'
60
+ r'|-?[({]|[)}]|-?[^\s(){}"]+'
61
+ )
62
+ _HISTORY_TYPES = {
63
+ "messageAdded": "messagesAdded",
64
+ "messageDeleted": "messagesDeleted",
65
+ "labelAdded": "labelsAdded",
66
+ "labelRemoved": "labelsRemoved",
67
+ }
58
68
  _RELATIVE = re.compile(r"^(\d+)([dmy])$")
59
69
 
60
70
 
@@ -250,6 +260,7 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
250
260
  "searches": [],
251
261
  "labels": {},
252
262
  "sendAs": None,
263
+ "historyId": None,
253
264
  },
254
265
  )
255
266
  if name == LIST_METHOD and not given.get("pageToken"):
@@ -265,6 +276,7 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
265
276
  )
266
277
  if name == PROFILE_METHOD:
267
278
  box["emailAddress"] = output.get("emailAddress") or box["emailAddress"]
279
+ box["historyId"] = output.get("historyId") or box["historyId"]
268
280
  if name == LABELS_LIST_METHOD:
269
281
  for label in output.get("labels") or []:
270
282
  _keep_user_label(box["labels"], label)
@@ -340,12 +352,25 @@ def as_mailboxes(ctx: SandboxStartCtx, started: Any) -> dict[str, Any]:
340
352
  labels=box.get("labels"),
341
353
  send_as=box.get("sendAs"),
342
354
  clock=box.get("clock"),
355
+ history_id=box.get("historyId"),
343
356
  )
344
357
  for index, box in enumerate(boxes or [{}])
345
358
  ]
346
359
  }
347
360
 
348
361
 
362
+ def _history_number(value: Any) -> int:
363
+ text = str(value or "").strip()
364
+ return int(text) if text.isdigit() else 0
365
+
366
+
367
+ def _starting_history_id(messages: list[dict[str, Any]], recorded: Any) -> int:
368
+ return max(
369
+ [1000, _history_number(recorded)]
370
+ + [_history_number(m.get("historyId")) for m in messages]
371
+ )
372
+
373
+
349
374
  def new_mailbox(
350
375
  ctx: SandboxStartCtx,
351
376
  index: int,
@@ -358,6 +383,7 @@ def new_mailbox(
358
383
  labels: list[dict[str, Any] | str] | None = None,
359
384
  send_as: list[dict[str, Any]] | None = None,
360
385
  clock: str | None = None,
386
+ history_id: Any = None,
361
387
  ) -> dict[str, Any]:
362
388
  normalized = [gmail_message(message) for message in messages or []]
363
389
  notes: list[str] = []
@@ -385,13 +411,14 @@ def new_mailbox(
385
411
  "credential": credential,
386
412
  "details": dict(details or {}),
387
413
  "clock": clock or ctx.trace_started_at,
388
- "historyId": 1000,
414
+ "historyId": _starting_history_id([*(messages or []), *normalized], history_id),
389
415
  "nextId": index * 1_000_000 + 1,
390
416
  "messages": normalized,
391
417
  "drafts": started_drafts,
392
418
  "searches": list(searches or []),
393
419
  "labels": [_user_label(label) for label in labels or []],
394
420
  "sendAs": None if send_as is None else [dict(entry) for entry in send_as],
421
+ "history": [],
395
422
  "notes": notes,
396
423
  }
397
424
 
@@ -637,6 +664,126 @@ def _term_matches(state: dict[str, Any], message: dict[str, Any], term: str) ->
637
664
  return _contains(text, term.strip('"'))
638
665
 
639
666
 
667
+ Query = tuple[str, Any]
668
+
669
+
670
+ def _negated(negate: bool, query: Query) -> Query:
671
+ return ("not", query) if negate else query
672
+
673
+
674
+ def _leaf(token: str, field: str | None) -> Query:
675
+ negate = token.startswith("-") and len(token) > 1
676
+ text = token[1:] if negate else token
677
+ if field and not _OPERATOR.match(text):
678
+ text = f"{field}:{text}"
679
+ return _negated(negate, ("term", text))
680
+
681
+
682
+ class _QueryParser:
683
+ def __init__(self, query: str) -> None:
684
+ self.tokens = _QUERY_TOKEN.findall(query or "")
685
+ self.at = 0
686
+
687
+ def peek(self) -> str | None:
688
+ return self.tokens[self.at] if self.at < len(self.tokens) else None
689
+
690
+ def take(self) -> str:
691
+ token = self.tokens[self.at]
692
+ self.at += 1
693
+ return token
694
+
695
+ def conjunction(self, closer: str | None, field: str | None) -> Query:
696
+ items: list[Query] = []
697
+ while (token := self.peek()) is not None and token != closer:
698
+ if token in {"AND", ")", "}"}:
699
+ self.take()
700
+ continue
701
+ items.append(self.disjunction(closer, field))
702
+ if self.peek() == closer and closer is not None:
703
+ self.take()
704
+ return items[0] if len(items) == 1 else ("and", items)
705
+
706
+ def disjunction(self, closer: str | None, field: str | None) -> Query:
707
+ items = [self.unary(field)]
708
+ while self.peek() == "OR":
709
+ self.take()
710
+ if self.peek() in {None, closer, "OR"}:
711
+ continue
712
+ items.append(self.unary(field))
713
+ return items[0] if len(items) == 1 else ("or", items)
714
+
715
+ def unary(self, field: str | None) -> Query:
716
+ token = self.take()
717
+ negate = token.startswith("-") and len(token) > 1
718
+ bare = token[1:] if negate else token
719
+ if bare == "(":
720
+ return _negated(negate, self.conjunction(")", field))
721
+ if bare == "{":
722
+ return _negated(negate, self.braced(field))
723
+ if bare.endswith(":("):
724
+ return _negated(negate, self.conjunction(")", bare[:-2]))
725
+ return _leaf(token, field)
726
+
727
+ def braced(self, field: str | None) -> Query:
728
+ items: list[Query] = []
729
+ while (token := self.peek()) is not None and token != "}":
730
+ if token in {"AND", "OR", ")"}:
731
+ self.take()
732
+ continue
733
+ items.append(self.unary(field))
734
+ if self.peek() == "}":
735
+ self.take()
736
+ return items[0] if len(items) == 1 else ("or", items)
737
+
738
+
739
+ def _flattened(query: Query) -> Query:
740
+ kind, value = query
741
+ if kind == "term":
742
+ return query
743
+ if kind == "not":
744
+ return ("not", _flattened(value))
745
+ items: list[Query] = []
746
+ for child in (_flattened(q) for q in value):
747
+ items.extend(child[1] if child[0] == kind else [child])
748
+ return items[0] if len(items) == 1 else (kind, items)
749
+
750
+
751
+ def parse_query(query: str) -> Query:
752
+ return _flattened(_QueryParser(query).conjunction(None, None))
753
+
754
+
755
+ def _matches(state: dict[str, Any], message: dict[str, Any], query: Query) -> bool:
756
+ kind, value = query
757
+ if kind == "term":
758
+ return _term_matches(state, message, value)
759
+ if kind == "not":
760
+ return not _matches(state, message, value)
761
+ if kind == "or":
762
+ return any(_matches(state, message, q) for q in value)
763
+ return all(_matches(state, message, q) for q in value)
764
+
765
+
766
+ def _leaves(query: Query) -> list[str]:
767
+ kind, value = query
768
+ if kind == "term":
769
+ return [value]
770
+ if kind == "not":
771
+ return []
772
+ return [leaf for q in value for leaf in _leaves(q)]
773
+
774
+
775
+ def _required(query: Query) -> list[Query]:
776
+ kind, value = query
777
+ return list(value) if kind == "and" else [query]
778
+
779
+
780
+ def _is_plain(query: Query) -> bool:
781
+ return all(
782
+ q[0] == "term" or (q[0] == "not" and q[1][0] == "term")
783
+ for q in _required(query)
784
+ )
785
+
786
+
640
787
  def _is_free_text(term: str) -> bool:
641
788
  return bool(term) and not term.startswith("-") and not _OPERATOR.match(term)
642
789
 
@@ -644,14 +791,23 @@ def _is_free_text(term: str) -> bool:
644
791
  _DATE_OPERATORS = ("after:", "before:", "newer_than:", "older_than:")
645
792
 
646
793
 
794
+ def _canonical(query: Query) -> str:
795
+ kind, value = query
796
+ if kind == "term":
797
+ return str(value).lower()
798
+ if kind == "not":
799
+ return "-" + _canonical(value)
800
+ joined = f" {kind.upper()} ".join(sorted(_canonical(q) for q in value))
801
+ return f"({joined})"
802
+
803
+
804
+ def _is_date_bound(query: Query) -> bool:
805
+ return query[0] == "term" and query[1].lower().startswith(_DATE_OPERATORS)
806
+
807
+
647
808
  def search_key(query: str) -> str:
648
- return " ".join(
649
- sorted(
650
- t.lower()
651
- for t in _TOKEN.findall(query or "")
652
- if t != "AND" and not t.lower().startswith(_DATE_OPERATORS)
653
- )
654
- )
809
+ kept = [q for q in _required(parse_query(query)) if not _is_date_bound(q)]
810
+ return " ".join(sorted(_canonical(q) for q in kept))
655
811
 
656
812
 
657
813
  def _text_key(query: str) -> str:
@@ -688,55 +844,41 @@ def _known_results(state: dict[str, Any], key: str) -> set[str] | None:
688
844
  return {i for ids in found for i in ids}
689
845
 
690
846
 
691
- def _matches_every_term(
692
- state: dict[str, Any], message: dict[str, Any], terms: list[str]
693
- ) -> bool:
694
- return all(
695
- (not _term_matches(state, message, t[1:]))
696
- if t.startswith("-") and len(t) > 1
697
- else _term_matches(state, message, t)
698
- for t in terms
699
- if t
700
- )
701
-
702
-
703
847
  def _search(
704
848
  state: dict[str, Any], query: str, include_spam_trash: bool
705
849
  ) -> list[dict[str, Any]]:
706
- terms = [t for t in _TOKEN.findall(query or "") if t not in {"(", ")", "AND"}]
707
- if "OR" in terms or any(t.startswith("{") or t.startswith("(") for t in terms):
708
- _note(
709
- state, "OR and grouped searches are matched as if every word were required"
710
- )
711
- terms = [t.strip("(){}") for t in terms if t != "OR"]
850
+ parsed = parse_query(query)
712
851
  same = _same_search(state, query)
713
852
  if same is not None:
714
853
  by_id = {m.get("id"): m for m in state["messages"]}
715
854
  created = [
716
855
  m
717
856
  for m in state["messages"]
718
- if m.get("bitfabCreated") and _matches_every_term(state, m, terms)
857
+ if m.get("bitfabCreated") and _matches(state, m, parsed)
719
858
  ]
720
- dates = [t for t in terms if t.lower().startswith(_DATE_OPERATORS)]
859
+ dates = [q for q in _required(parsed) if _is_date_bound(q)]
721
860
  recorded = [
722
861
  by_id[i]
723
862
  for i in same
724
- if i in by_id and all(_term_matches(state, by_id[i], t) for t in dates)
863
+ if i in by_id and all(_matches(state, by_id[i], q) for q in dates)
725
864
  ]
726
865
  newest_first = sorted(
727
866
  created, key=lambda m: int(m.get("internalDate") or 0), reverse=True
728
867
  )
729
868
  return newest_first + recorded
730
- known = _known_results(state, _text_key(query))
869
+ known = _known_results(state, _text_key(query)) if _is_plain(parsed) else None
870
+ rest = parsed
871
+ free: Query = ("and", [])
731
872
  if known is not None:
732
- free = [t for t in terms if _is_free_text(t)]
733
- terms = [t for t in terms if not _is_free_text(t)]
873
+ required = _required(parsed)
874
+ free = ("and", [q for q in required if q[0] == "term" and _is_free_text(q[1])])
875
+ rest = ("and", [q for q in required if q not in free[1]])
876
+ searching_everywhere = any(
877
+ t.lower() in {"in:anywhere", "in:spam", "in:trash"} for t in _leaves(parsed)
878
+ )
734
879
  found = []
735
880
  for message in state["messages"]:
736
881
  labels = set(message.get("labelIds") or [])
737
- searching_everywhere = any(
738
- t.lower() in {"in:anywhere", "in:spam", "in:trash"} for t in terms
739
- )
740
882
  if (
741
883
  not include_spam_trash
742
884
  and not searching_everywhere
@@ -746,10 +888,10 @@ def _search(
746
888
  if known is not None and (
747
889
  message.get("id") not in known
748
890
  if not message.get("bitfabCreated")
749
- else not all(_term_matches(state, message, t) for t in free)
891
+ else not _matches(state, message, free)
750
892
  ):
751
893
  continue
752
- if _matches_every_term(state, message, terms):
894
+ if _matches(state, message, rest):
753
895
  found.append(message)
754
896
  return sorted(found, key=lambda m: int(m.get("internalDate") or 0), reverse=True)
755
897
 
@@ -802,6 +944,47 @@ def _bump_history(state: dict[str, Any]) -> str:
802
944
  return str(state["historyId"])
803
945
 
804
946
 
947
+ def _message_ref(message: dict[str, Any]) -> dict[str, Any]:
948
+ return {
949
+ "id": message["id"],
950
+ "threadId": message.get("threadId"),
951
+ "labelIds": list(message.get("labelIds") or []),
952
+ }
953
+
954
+
955
+ def _record_change(
956
+ state: dict[str, Any], message: dict[str, Any], changes: dict[str, Any]
957
+ ) -> None:
958
+ history_id = _bump_history(state)
959
+ message["historyId"] = history_id
960
+ ref = _message_ref(message)
961
+ entry: dict[str, Any] = {
962
+ "id": history_id,
963
+ "messages": [{"id": ref["id"], "threadId": ref["threadId"]}],
964
+ }
965
+ for key, labels in changes.items():
966
+ if key in {"messagesAdded", "messagesDeleted"}:
967
+ entry[key] = [{"message": ref}]
968
+ elif labels:
969
+ entry[key] = [{"message": ref, "labelIds": list(labels)}]
970
+ state.setdefault("history", []).append(entry)
971
+
972
+
973
+ def _relabel(
974
+ state: dict[str, Any],
975
+ message: dict[str, Any],
976
+ add: list[str],
977
+ remove: list[str],
978
+ ) -> None:
979
+ before = list(message.get("labelIds") or [])
980
+ removed = [label for label in before if label in set(remove)]
981
+ kept = [label for label in before if label not in set(remove)]
982
+ added = list(dict.fromkeys(label for label in add if label not in kept))
983
+ message["labelIds"] = kept + added
984
+ if added or removed:
985
+ _record_change(state, message, {"labelsAdded": added, "labelsRemoved": removed})
986
+
987
+
805
988
  def _from_raw(
806
989
  state: dict[str, Any], raw: str | None, thread_id: str | None, labels: list[str]
807
990
  ) -> dict[str, Any]:
@@ -815,15 +998,15 @@ def _from_raw(
815
998
  "internalDate": _created_millis(state),
816
999
  }
817
1000
  )
818
- message["historyId"] = _bump_history(state)
819
1001
  message["bitfabCreated"] = True
1002
+ state["messages"].append(message)
1003
+ _record_change(state, message, {"messagesAdded": True})
820
1004
  return message
821
1005
 
822
1006
 
823
1007
  def _send(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
824
1008
  body = params.get("body") or {}
825
1009
  message = _from_raw(state, body.get("raw"), body.get("threadId"), ["SENT"])
826
- state["messages"].append(message)
827
1010
  return {
828
1011
  "id": message["id"],
829
1012
  "threadId": message["threadId"],
@@ -854,7 +1037,6 @@ def _new_draft_message(
854
1037
  message = _from_raw(
855
1038
  state, inner.get("raw"), inner.get("threadId") or thread_id, ["DRAFT"]
856
1039
  )
857
- state["messages"].append(message)
858
1040
  return message
859
1041
 
860
1042
 
@@ -882,7 +1064,7 @@ def _replace_draft_message(
882
1064
  ) -> None:
883
1065
  old = _find(state, draft["message"]["id"])
884
1066
  if old is not None:
885
- state["messages"].remove(old)
1067
+ _remove_message(state, old)
886
1068
  message = _new_draft_message(
887
1069
  state, inner, (old or draft["message"]).get("threadId")
888
1070
  )
@@ -907,15 +1089,12 @@ def _draft_delete(state: dict[str, Any], params: dict[str, Any]) -> dict[str, An
907
1089
  state["drafts"].remove(draft)
908
1090
  message = _find(state, draft["message"]["id"])
909
1091
  if message is not None:
910
- state["messages"].remove(message)
1092
+ _remove_message(state, message)
911
1093
  return {}
912
1094
 
913
1095
 
914
1096
  def _mark_sent(state: dict[str, Any], message: dict[str, Any]) -> dict[str, Any]:
915
- message["labelIds"] = [
916
- label for label in message.get("labelIds") or [] if label != "DRAFT"
917
- ] + ["SENT"]
918
- message["historyId"] = _bump_history(state)
1097
+ _relabel(state, message, ["SENT"], ["DRAFT"])
919
1098
  return {
920
1099
  "id": message["id"],
921
1100
  "threadId": message["threadId"],
@@ -948,17 +1127,47 @@ def _modify(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
948
1127
  if message is None:
949
1128
  return _not_found(f"message {params.get('id')}")
950
1129
  body = params.get("body") or {}
951
- labels = [
952
- label
953
- for label in message.get("labelIds") or []
954
- if label not in set(body.get("removeLabelIds") or [])
955
- ]
956
- labels += [label for label in body.get("addLabelIds") or [] if label not in labels]
957
- message["labelIds"] = labels
958
- message["historyId"] = _bump_history(state)
1130
+ _relabel(
1131
+ state,
1132
+ message,
1133
+ list(body.get("addLabelIds") or []),
1134
+ list(body.get("removeLabelIds") or []),
1135
+ )
1136
+ return _shaped(message, "minimal", None)
1137
+
1138
+
1139
+ def _trash(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
1140
+ message = _find(state, str(params.get("id")))
1141
+ if message is None:
1142
+ return _not_found(f"message {params.get('id')}")
1143
+ _relabel(state, message, ["TRASH"], [])
959
1144
  return _shaped(message, "minimal", None)
960
1145
 
961
1146
 
1147
+ def _untrash(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
1148
+ message = _find(state, str(params.get("id")))
1149
+ if message is None:
1150
+ return _not_found(f"message {params.get('id')}")
1151
+ _relabel(state, message, [], ["TRASH"])
1152
+ return _shaped(message, "minimal", None)
1153
+
1154
+
1155
+ def _remove_message(state: dict[str, Any], message: dict[str, Any]) -> None:
1156
+ state["messages"].remove(message)
1157
+ _record_change(state, message, {"messagesDeleted": True})
1158
+
1159
+
1160
+ def _delete(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
1161
+ message = _find(state, str(params.get("id")))
1162
+ if message is None:
1163
+ return _not_found(f"message {params.get('id')}")
1164
+ state["drafts"] = [
1165
+ d for d in state["drafts"] if d.get("message", {}).get("id") != message["id"]
1166
+ ]
1167
+ _remove_message(state, message)
1168
+ return {}
1169
+
1170
+
962
1171
  def _thread(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
963
1172
  thread_id = str(params.get("id"))
964
1173
  messages = [m for m in state["messages"] if m.get("threadId") == thread_id]
@@ -972,26 +1181,48 @@ def _thread(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
972
1181
  }
973
1182
 
974
1183
 
1184
+ def _wanted_types(params: dict[str, Any]) -> set[str]:
1185
+ given = params.get("historyTypes") or []
1186
+ names = [given] if isinstance(given, str) else list(given)
1187
+ chosen = {_HISTORY_TYPES[n] for n in names if n in _HISTORY_TYPES}
1188
+ return chosen or set(_HISTORY_TYPES.values())
1189
+
1190
+
1191
+ def _touches_label(entry: dict[str, Any], label: str) -> bool:
1192
+ return any(
1193
+ label in (change["message"].get("labelIds") or [])
1194
+ or label in (change.get("labelIds") or [])
1195
+ for key in _HISTORY_TYPES.values()
1196
+ for change in entry.get(key) or []
1197
+ )
1198
+
1199
+
975
1200
  def _history(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
976
1201
  start = int(params.get("startHistoryId") or 0)
977
- added = [m for m in state["messages"] if int(m.get("historyId") or 0) > start]
1202
+ wanted = _wanted_types(params)
1203
+ label = params.get("labelId")
1204
+ entries = []
1205
+ for entry in state.get("history") or []:
1206
+ if int(entry["id"]) <= start:
1207
+ continue
1208
+ kept = {
1209
+ key: copy.deepcopy(value)
1210
+ for key, value in entry.items()
1211
+ if key in {"id", "messages"} or key in wanted
1212
+ }
1213
+ if len(kept) == 2:
1214
+ continue
1215
+ if label and not _touches_label(kept, str(label)):
1216
+ continue
1217
+ entries.append(kept)
1218
+ size = min(int(params.get("maxResults") or 100), 500)
1219
+ offset = int(params.get("pageToken") or 0)
978
1220
  reply: dict[str, Any] = {"historyId": str(state.get("historyId") or 1000)}
979
- if added:
980
- reply["history"] = [
981
- {
982
- "id": m["historyId"],
983
- "messagesAdded": [
984
- {
985
- "message": {
986
- "id": m["id"],
987
- "threadId": m.get("threadId"),
988
- "labelIds": m.get("labelIds"),
989
- }
990
- }
991
- ],
992
- }
993
- for m in added
994
- ]
1221
+ page = entries[offset : offset + size]
1222
+ if page:
1223
+ reply["history"] = page
1224
+ if offset + size < len(entries):
1225
+ reply["nextPageToken"] = str(offset + size)
995
1226
  return reply
996
1227
 
997
1228
 
@@ -1147,6 +1378,9 @@ HANDLERS: dict[str, Callable[[dict[str, Any], dict[str, Any]], dict[str, Any]]]
1147
1378
  GET_METHOD: _get,
1148
1379
  "gmail.users.messages.send": _send,
1149
1380
  "gmail.users.messages.modify": _modify,
1381
+ "gmail.users.messages.trash": _trash,
1382
+ "gmail.users.messages.untrash": _untrash,
1383
+ "gmail.users.messages.delete": _delete,
1150
1384
  "gmail.users.messages.attachments.get": _attachment,
1151
1385
  DRAFT_CREATE_METHOD: _draft_create,
1152
1386
  DRAFT_GET_METHOD: _draft_get,
@@ -1233,6 +1467,7 @@ def _empty_mailbox_for(boxes: list[dict[str, Any]], address: str) -> dict[str, A
1233
1467
  "searches": [],
1234
1468
  "labels": [],
1235
1469
  "sendAs": None,
1470
+ "history": [],
1236
1471
  "notes": [f"{address} had no mailbox in the original run, so it starts empty"],
1237
1472
  }
1238
1473
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "bitfab-py"
3
- version = "0.78.4"
3
+ version = "0.78.5"
4
4
  description = "Bitfab client for provider-based API calls with local BAML execution"
5
5
  authors = ["Harvest Team"]
6
6
  readme = "README.md"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes