bitfab-py 0.78.3__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.3 → bitfab_py-0.78.5}/PKG-INFO +1 -1
  2. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/__init__.py +2 -0
  3. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/gmail_sandbox.py +328 -77
  4. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay.py +1 -0
  5. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/sandbox.py +40 -0
  6. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/pyproject.toml +1 -1
  7. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/README.md +0 -0
  8. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/agent_middleware.py +0 -0
  9. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/approval.py +0 -0
  10. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/assertion_categories.py +0 -0
  11. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/baml.py +0 -0
  12. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/baml_auto_trace.py +0 -0
  13. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/categories.py +0 -0
  14. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/claude_agent_sdk.py +0 -0
  15. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/client.py +0 -0
  16. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/client_patching.py +0 -0
  17. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/cloudReplay.py +0 -0
  18. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/cloud_replay_cli.py +0 -0
  19. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/commit_ref.py +0 -0
  20. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/compress.py +0 -0
  21. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/constants.py +0 -0
  22. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/datasets.py +0 -0
  23. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/db_snapshot.py +0 -0
  24. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/error_chain.py +0 -0
  25. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/experiment_id.py +0 -0
  26. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/experiments.py +0 -0
  27. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/finalizers.py +0 -0
  28. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/git_command.py +0 -0
  29. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/git_state.py +0 -0
  30. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/google_calls.py +0 -0
  31. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/graders.py +0 -0
  32. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/http.py +0 -0
  33. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/integration_fixture.py +0 -0
  34. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/jev.py +0 -0
  35. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/labels.py +0 -0
  36. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/langgraph.py +0 -0
  37. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/langgraph_integration.py +0 -0
  38. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/langgraph_runs.py +0 -0
  39. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/mock_matching.py +0 -0
  40. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/mock_override.py +0 -0
  41. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/openai_agent_sdk.py +0 -0
  42. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/openai_agents_usage.py +0 -0
  43. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/organization_members.py +0 -0
  44. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/otel.py +0 -0
  45. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/payload_budget.py +0 -0
  46. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/processor_payload.py +0 -0
  47. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/provider_calls.py +0 -0
  48. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_branch.py +0 -0
  49. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_cli.py +0 -0
  50. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_heartbeat.py +0 -0
  51. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_interrupt.py +0 -0
  52. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_invocation.py +0 -0
  53. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_memory.py +0 -0
  54. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_processes.py +0 -0
  55. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/replay_registry.py +0 -0
  56. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/seed_cli.py +0 -0
  57. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/selective_replay.py +0 -0
  58. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/serialize.py +0 -0
  59. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/service_calls.py +0 -0
  60. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/simulation_plan.py +0 -0
  61. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/span_meta.py +0 -0
  62. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/span_origin.py +0 -0
  63. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/spans.py +0 -0
  64. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/subtree.py +0 -0
  65. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/thread_propagation.py +0 -0
  66. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/timestamp.py +0 -0
  67. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/trace_completion.py +0 -0
  68. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/trace_metadata.py +0 -0
  69. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/trace_payload.py +0 -0
  70. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/traces.py +0 -0
  71. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/tracing.py +0 -0
  72. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/transport.py +0 -0
  73. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/transport_types.py +0 -0
  74. {bitfab_py-0.78.3 → bitfab_py-0.78.5}/bitfab/verdicts.py +0 -0
  75. {bitfab_py-0.78.3 → 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.3
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
@@ -155,6 +155,7 @@ from bitfab.sandbox import (
155
155
  Sandbox,
156
156
  SandboxStartCtx,
157
157
  sandbox_active,
158
+ sandbox_now,
158
159
  sandbox_state,
159
160
  without_sandbox,
160
161
  )
@@ -432,6 +433,7 @@ __all__ = [
432
433
  "report_replay_progress",
433
434
  "reseed_from_registry",
434
435
  "sandbox_active",
436
+ "sandbox_now",
435
437
  "sandbox_state",
436
438
  "seed_from_registry",
437
439
  "serialize_replay_result",
@@ -12,7 +12,12 @@ from typing import Any
12
12
 
13
13
  from bitfab.google_calls import CREDENTIAL_PARAM, HTTP_ERROR_KEY, request_credentials
14
14
  from bitfab.mock_override import MockOverrideCtx, SpanNodeMeta
15
- from bitfab.sandbox import Sandbox, SandboxStartCtx, sandbox_state
15
+ from bitfab.sandbox import (
16
+ Sandbox,
17
+ SandboxStartCtx,
18
+ sandbox_elapsed_ms,
19
+ sandbox_state,
20
+ )
16
21
  from bitfab.service_calls import ServiceCallHeldBackError
17
22
 
18
23
  GMAIL_SANDBOX_NAME = "Gmail"
@@ -50,6 +55,16 @@ _PLAIN_HEADERS = {
50
55
  }
51
56
  _TOKEN = re.compile(r'-?[A-Za-z_]+:"[^"]*"|-?[A-Za-z_]+:\S+|-?"[^"]*"|\S+')
52
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
+ }
53
68
  _RELATIVE = re.compile(r"^(\d+)([dmy])$")
54
69
 
55
70
 
@@ -245,6 +260,7 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
245
260
  "searches": [],
246
261
  "labels": {},
247
262
  "sendAs": None,
263
+ "historyId": None,
248
264
  },
249
265
  )
250
266
  if name == LIST_METHOD and not given.get("pageToken"):
@@ -260,6 +276,7 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
260
276
  )
261
277
  if name == PROFILE_METHOD:
262
278
  box["emailAddress"] = output.get("emailAddress") or box["emailAddress"]
279
+ box["historyId"] = output.get("historyId") or box["historyId"]
263
280
  if name == LABELS_LIST_METHOD:
264
281
  for label in output.get("labels") or []:
265
282
  _keep_user_label(box["labels"], label)
@@ -334,12 +351,26 @@ def as_mailboxes(ctx: SandboxStartCtx, started: Any) -> dict[str, Any]:
334
351
  searches=box.get("searches"),
335
352
  labels=box.get("labels"),
336
353
  send_as=box.get("sendAs"),
354
+ clock=box.get("clock"),
355
+ history_id=box.get("historyId"),
337
356
  )
338
357
  for index, box in enumerate(boxes or [{}])
339
358
  ]
340
359
  }
341
360
 
342
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
+
343
374
  def new_mailbox(
344
375
  ctx: SandboxStartCtx,
345
376
  index: int,
@@ -351,6 +382,8 @@ def new_mailbox(
351
382
  searches: list[dict[str, Any]] | None = None,
352
383
  labels: list[dict[str, Any] | str] | None = None,
353
384
  send_as: list[dict[str, Any]] | None = None,
385
+ clock: str | None = None,
386
+ history_id: Any = None,
354
387
  ) -> dict[str, Any]:
355
388
  normalized = [gmail_message(message) for message in messages or []]
356
389
  notes: list[str] = []
@@ -377,14 +410,15 @@ def new_mailbox(
377
410
  "emailAddress": email_address,
378
411
  "credential": credential,
379
412
  "details": dict(details or {}),
380
- "clock": ctx.trace_started_at,
381
- "historyId": 1000,
413
+ "clock": clock or ctx.trace_started_at,
414
+ "historyId": _starting_history_id([*(messages or []), *normalized], history_id),
382
415
  "nextId": index * 1_000_000 + 1,
383
416
  "messages": normalized,
384
417
  "drafts": started_drafts,
385
418
  "searches": list(searches or []),
386
419
  "labels": [_user_label(label) for label in labels or []],
387
420
  "sendAs": None if send_as is None else [dict(entry) for entry in send_as],
421
+ "history": [],
388
422
  "notes": notes,
389
423
  }
390
424
 
@@ -515,9 +549,16 @@ def _shaped(
515
549
 
516
550
 
517
551
  def _clock_millis(state: dict[str, Any]) -> int:
518
- return _millis(state.get("clock")) or int(
519
- datetime.datetime.now(datetime.timezone.utc).timestamp() * 1000
520
- )
552
+ started = _millis(state.get("clock"))
553
+ if started is None:
554
+ return int(datetime.datetime.now(datetime.timezone.utc).timestamp() * 1000)
555
+ return started + sandbox_elapsed_ms()
556
+
557
+
558
+ def _created_millis(state: dict[str, Any]) -> int:
559
+ created = max(_clock_millis(state), int(state.get("lastCreatedAt") or 0) + 1)
560
+ state["lastCreatedAt"] = created
561
+ return created
521
562
 
522
563
 
523
564
  def _date_bound(value: str) -> int | None:
@@ -623,6 +664,126 @@ def _term_matches(state: dict[str, Any], message: dict[str, Any], term: str) ->
623
664
  return _contains(text, term.strip('"'))
624
665
 
625
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
+
626
787
  def _is_free_text(term: str) -> bool:
627
788
  return bool(term) and not term.startswith("-") and not _OPERATOR.match(term)
628
789
 
@@ -630,14 +791,23 @@ def _is_free_text(term: str) -> bool:
630
791
  _DATE_OPERATORS = ("after:", "before:", "newer_than:", "older_than:")
631
792
 
632
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
+
633
808
  def search_key(query: str) -> str:
634
- return " ".join(
635
- sorted(
636
- t.lower()
637
- for t in _TOKEN.findall(query or "")
638
- if t != "AND" and not t.lower().startswith(_DATE_OPERATORS)
639
- )
640
- )
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))
641
811
 
642
812
 
643
813
  def _text_key(query: str) -> str:
@@ -674,55 +844,41 @@ def _known_results(state: dict[str, Any], key: str) -> set[str] | None:
674
844
  return {i for ids in found for i in ids}
675
845
 
676
846
 
677
- def _matches_every_term(
678
- state: dict[str, Any], message: dict[str, Any], terms: list[str]
679
- ) -> bool:
680
- return all(
681
- (not _term_matches(state, message, t[1:]))
682
- if t.startswith("-") and len(t) > 1
683
- else _term_matches(state, message, t)
684
- for t in terms
685
- if t
686
- )
687
-
688
-
689
847
  def _search(
690
848
  state: dict[str, Any], query: str, include_spam_trash: bool
691
849
  ) -> list[dict[str, Any]]:
692
- terms = [t for t in _TOKEN.findall(query or "") if t not in {"(", ")", "AND"}]
693
- if "OR" in terms or any(t.startswith("{") or t.startswith("(") for t in terms):
694
- _note(
695
- state, "OR and grouped searches are matched as if every word were required"
696
- )
697
- terms = [t.strip("(){}") for t in terms if t != "OR"]
850
+ parsed = parse_query(query)
698
851
  same = _same_search(state, query)
699
852
  if same is not None:
700
853
  by_id = {m.get("id"): m for m in state["messages"]}
701
854
  created = [
702
855
  m
703
856
  for m in state["messages"]
704
- if m.get("bitfabCreated") and _matches_every_term(state, m, terms)
857
+ if m.get("bitfabCreated") and _matches(state, m, parsed)
705
858
  ]
706
- 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)]
707
860
  recorded = [
708
861
  by_id[i]
709
862
  for i in same
710
- 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)
711
864
  ]
712
865
  newest_first = sorted(
713
866
  created, key=lambda m: int(m.get("internalDate") or 0), reverse=True
714
867
  )
715
868
  return newest_first + recorded
716
- 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", [])
717
872
  if known is not None:
718
- free = [t for t in terms if _is_free_text(t)]
719
- 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
+ )
720
879
  found = []
721
880
  for message in state["messages"]:
722
881
  labels = set(message.get("labelIds") or [])
723
- searching_everywhere = any(
724
- t.lower() in {"in:anywhere", "in:spam", "in:trash"} for t in terms
725
- )
726
882
  if (
727
883
  not include_spam_trash
728
884
  and not searching_everywhere
@@ -732,10 +888,10 @@ def _search(
732
888
  if known is not None and (
733
889
  message.get("id") not in known
734
890
  if not message.get("bitfabCreated")
735
- else not all(_term_matches(state, message, t) for t in free)
891
+ else not _matches(state, message, free)
736
892
  ):
737
893
  continue
738
- if _matches_every_term(state, message, terms):
894
+ if _matches(state, message, rest):
739
895
  found.append(message)
740
896
  return sorted(found, key=lambda m: int(m.get("internalDate") or 0), reverse=True)
741
897
 
@@ -788,6 +944,47 @@ def _bump_history(state: dict[str, Any]) -> str:
788
944
  return str(state["historyId"])
789
945
 
790
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
+
791
988
  def _from_raw(
792
989
  state: dict[str, Any], raw: str | None, thread_id: str | None, labels: list[str]
793
990
  ) -> dict[str, Any]:
@@ -798,18 +995,18 @@ def _from_raw(
798
995
  "id": message_id,
799
996
  "threadId": thread_id or message_id,
800
997
  "labelIds": labels,
801
- "internalDate": _clock_millis(state),
998
+ "internalDate": _created_millis(state),
802
999
  }
803
1000
  )
804
- message["historyId"] = _bump_history(state)
805
1001
  message["bitfabCreated"] = True
1002
+ state["messages"].append(message)
1003
+ _record_change(state, message, {"messagesAdded": True})
806
1004
  return message
807
1005
 
808
1006
 
809
1007
  def _send(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
810
1008
  body = params.get("body") or {}
811
1009
  message = _from_raw(state, body.get("raw"), body.get("threadId"), ["SENT"])
812
- state["messages"].append(message)
813
1010
  return {
814
1011
  "id": message["id"],
815
1012
  "threadId": message["threadId"],
@@ -840,7 +1037,6 @@ def _new_draft_message(
840
1037
  message = _from_raw(
841
1038
  state, inner.get("raw"), inner.get("threadId") or thread_id, ["DRAFT"]
842
1039
  )
843
- state["messages"].append(message)
844
1040
  return message
845
1041
 
846
1042
 
@@ -868,7 +1064,7 @@ def _replace_draft_message(
868
1064
  ) -> None:
869
1065
  old = _find(state, draft["message"]["id"])
870
1066
  if old is not None:
871
- state["messages"].remove(old)
1067
+ _remove_message(state, old)
872
1068
  message = _new_draft_message(
873
1069
  state, inner, (old or draft["message"]).get("threadId")
874
1070
  )
@@ -893,15 +1089,12 @@ def _draft_delete(state: dict[str, Any], params: dict[str, Any]) -> dict[str, An
893
1089
  state["drafts"].remove(draft)
894
1090
  message = _find(state, draft["message"]["id"])
895
1091
  if message is not None:
896
- state["messages"].remove(message)
1092
+ _remove_message(state, message)
897
1093
  return {}
898
1094
 
899
1095
 
900
1096
  def _mark_sent(state: dict[str, Any], message: dict[str, Any]) -> dict[str, Any]:
901
- message["labelIds"] = [
902
- label for label in message.get("labelIds") or [] if label != "DRAFT"
903
- ] + ["SENT"]
904
- message["historyId"] = _bump_history(state)
1097
+ _relabel(state, message, ["SENT"], ["DRAFT"])
905
1098
  return {
906
1099
  "id": message["id"],
907
1100
  "threadId": message["threadId"],
@@ -934,17 +1127,47 @@ def _modify(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
934
1127
  if message is None:
935
1128
  return _not_found(f"message {params.get('id')}")
936
1129
  body = params.get("body") or {}
937
- labels = [
938
- label
939
- for label in message.get("labelIds") or []
940
- if label not in set(body.get("removeLabelIds") or [])
941
- ]
942
- labels += [label for label in body.get("addLabelIds") or [] if label not in labels]
943
- message["labelIds"] = labels
944
- message["historyId"] = _bump_history(state)
1130
+ _relabel(
1131
+ state,
1132
+ message,
1133
+ list(body.get("addLabelIds") or []),
1134
+ list(body.get("removeLabelIds") or []),
1135
+ )
945
1136
  return _shaped(message, "minimal", None)
946
1137
 
947
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"], [])
1144
+ return _shaped(message, "minimal", None)
1145
+
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
+
948
1171
  def _thread(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
949
1172
  thread_id = str(params.get("id"))
950
1173
  messages = [m for m in state["messages"] if m.get("threadId") == thread_id]
@@ -958,26 +1181,48 @@ def _thread(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
958
1181
  }
959
1182
 
960
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
+
961
1200
  def _history(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
962
1201
  start = int(params.get("startHistoryId") or 0)
963
- 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)
964
1220
  reply: dict[str, Any] = {"historyId": str(state.get("historyId") or 1000)}
965
- if added:
966
- reply["history"] = [
967
- {
968
- "id": m["historyId"],
969
- "messagesAdded": [
970
- {
971
- "message": {
972
- "id": m["id"],
973
- "threadId": m.get("threadId"),
974
- "labelIds": m.get("labelIds"),
975
- }
976
- }
977
- ],
978
- }
979
- for m in added
980
- ]
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)
981
1226
  return reply
982
1227
 
983
1228
 
@@ -1133,6 +1378,9 @@ HANDLERS: dict[str, Callable[[dict[str, Any], dict[str, Any]], dict[str, Any]]]
1133
1378
  GET_METHOD: _get,
1134
1379
  "gmail.users.messages.send": _send,
1135
1380
  "gmail.users.messages.modify": _modify,
1381
+ "gmail.users.messages.trash": _trash,
1382
+ "gmail.users.messages.untrash": _untrash,
1383
+ "gmail.users.messages.delete": _delete,
1136
1384
  "gmail.users.messages.attachments.get": _attachment,
1137
1385
  DRAFT_CREATE_METHOD: _draft_create,
1138
1386
  DRAFT_GET_METHOD: _draft_get,
@@ -1219,6 +1467,7 @@ def _empty_mailbox_for(boxes: list[dict[str, Any]], address: str) -> dict[str, A
1219
1467
  "searches": [],
1220
1468
  "labels": [],
1221
1469
  "sendAs": None,
1470
+ "history": [],
1222
1471
  "notes": [f"{address} had no mailbox in the original run, so it starts empty"],
1223
1472
  }
1224
1473
 
@@ -1263,6 +1512,8 @@ def gmail_sandbox(
1263
1512
  send-as entries (``sendAsEmail``, ``displayName``, ``signature``,
1264
1513
  ...). Without ``sendAs``, the account's address is listed with no
1265
1514
  signature.
1515
+ ``clock`` (ISO 8601) is where the mailbox's time starts, in place
1516
+ of the original trace's start time.
1266
1517
  Each message is a Gmail API message or plain fields as
1267
1518
  ``gmail_message`` takes them; a plain ``account`` field puts the
1268
1519
  message in that account's mailbox. Each draft is
@@ -2962,6 +2962,7 @@ def _sandbox_session(
2962
2962
  sandboxes=sandboxes,
2963
2963
  client=client,
2964
2964
  make_start_ctx=make_start_ctx,
2965
+ trace_started_at=trace_started_at,
2965
2966
  )
2966
2967
 
2967
2968
 
@@ -1,9 +1,11 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import copy
4
+ import datetime
4
5
  import json
5
6
  import sys
6
7
  import threading
8
+ import time
7
9
  from collections.abc import Callable, Sequence
8
10
  from dataclasses import dataclass, field
9
11
  from typing import Any
@@ -122,10 +124,15 @@ class SandboxSession:
122
124
  sandboxes: Sequence[Sandbox]
123
125
  client: Any
124
126
  make_start_ctx: Callable[[Sandbox], SandboxStartCtx]
127
+ trace_started_at: str | None = None
128
+ started: float = field(default_factory=time.monotonic)
125
129
  _states: dict[str, Any] = field(default_factory=dict)
126
130
  _reports: dict[str, dict[str, Any]] = field(default_factory=dict)
127
131
  _lock: threading.RLock = field(default_factory=threading.RLock)
128
132
 
133
+ def elapsed_ms(self) -> int:
134
+ return int((time.monotonic() - self.started) * 1000)
135
+
129
136
  def find(self, node: SpanNodeMeta) -> Sandbox | None:
130
137
  return next(
131
138
  (sandbox for sandbox in self.sandboxes if sandbox.match(node)), None
@@ -256,3 +263,36 @@ def sandbox_state(name: str) -> Any:
256
263
  if session is None or sandbox is None:
257
264
  return None
258
265
  return session.state_of(sandbox, _attach_to_replay_root)
266
+
267
+
268
+ def sandbox_elapsed_ms() -> int:
269
+ session = current_session()
270
+ return session.elapsed_ms() if session is not None else 0
271
+
272
+
273
+ def parse_timestamp(value: str | None) -> datetime.datetime | None:
274
+ if not value:
275
+ return None
276
+ try:
277
+ parsed = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
278
+ except ValueError:
279
+ return None
280
+ if parsed.tzinfo is None:
281
+ return parsed.replace(tzinfo=datetime.timezone.utc)
282
+ return parsed
283
+
284
+
285
+ def sandbox_now() -> datetime.datetime | None:
286
+ """The time sandboxes use in the current replay item.
287
+
288
+ It starts at the moment the original trace started and moves forward as
289
+ the replay item runs, so a sandbox answers as if the run were happening
290
+ again at its original time. Use it in a sandbox's ``handle`` to date what
291
+ the call writes. Returns ``None`` outside a replay item, or when the
292
+ original start time is not known. ``datetime.now()`` is not changed.
293
+ """
294
+ session = current_session()
295
+ started_at = parse_timestamp(session.trace_started_at) if session else None
296
+ if session is None or started_at is None:
297
+ return None
298
+ return started_at + datetime.timedelta(milliseconds=session.elapsed_ms())
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "bitfab-py"
3
- version = "0.78.3"
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