bitfab-py 0.78.1__tar.gz → 0.78.3__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.1 → bitfab_py-0.78.3}/PKG-INFO +1 -1
  2. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/client.py +52 -27
  3. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/gmail_sandbox.py +212 -39
  4. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/service_calls.py +19 -0
  5. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/pyproject.toml +1 -1
  6. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/README.md +0 -0
  7. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/__init__.py +0 -0
  8. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/agent_middleware.py +0 -0
  9. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/approval.py +0 -0
  10. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/assertion_categories.py +0 -0
  11. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/baml.py +0 -0
  12. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/baml_auto_trace.py +0 -0
  13. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/categories.py +0 -0
  14. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/claude_agent_sdk.py +0 -0
  15. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/client_patching.py +0 -0
  16. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/cloudReplay.py +0 -0
  17. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/cloud_replay_cli.py +0 -0
  18. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/commit_ref.py +0 -0
  19. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/compress.py +0 -0
  20. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/constants.py +0 -0
  21. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/datasets.py +0 -0
  22. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/db_snapshot.py +0 -0
  23. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/error_chain.py +0 -0
  24. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/experiment_id.py +0 -0
  25. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/experiments.py +0 -0
  26. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/finalizers.py +0 -0
  27. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/git_command.py +0 -0
  28. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/git_state.py +0 -0
  29. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/google_calls.py +0 -0
  30. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/graders.py +0 -0
  31. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/http.py +0 -0
  32. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/integration_fixture.py +0 -0
  33. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/jev.py +0 -0
  34. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/labels.py +0 -0
  35. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/langgraph.py +0 -0
  36. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/langgraph_integration.py +0 -0
  37. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/langgraph_runs.py +0 -0
  38. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/mock_matching.py +0 -0
  39. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/mock_override.py +0 -0
  40. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/openai_agent_sdk.py +0 -0
  41. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/openai_agents_usage.py +0 -0
  42. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/organization_members.py +0 -0
  43. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/otel.py +0 -0
  44. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/payload_budget.py +0 -0
  45. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/processor_payload.py +0 -0
  46. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/provider_calls.py +0 -0
  47. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay.py +0 -0
  48. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_branch.py +0 -0
  49. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_cli.py +0 -0
  50. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_heartbeat.py +0 -0
  51. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_interrupt.py +0 -0
  52. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_invocation.py +0 -0
  53. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_memory.py +0 -0
  54. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_processes.py +0 -0
  55. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/replay_registry.py +0 -0
  56. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/sandbox.py +0 -0
  57. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/seed_cli.py +0 -0
  58. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/selective_replay.py +0 -0
  59. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/serialize.py +0 -0
  60. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/simulation_plan.py +0 -0
  61. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/span_meta.py +0 -0
  62. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/span_origin.py +0 -0
  63. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/spans.py +0 -0
  64. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/subtree.py +0 -0
  65. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/thread_propagation.py +0 -0
  66. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/timestamp.py +0 -0
  67. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/trace_completion.py +0 -0
  68. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/trace_metadata.py +0 -0
  69. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/trace_payload.py +0 -0
  70. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/traces.py +0 -0
  71. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/tracing.py +0 -0
  72. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/transport.py +0 -0
  73. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/transport_types.py +0 -0
  74. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/bitfab/verdicts.py +0 -0
  75. {bitfab_py-0.78.1 → bitfab_py-0.78.3}/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.1
3
+ Version: 0.78.3
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
@@ -152,6 +152,7 @@ CAPTURE_ENABLED_ENV = "BITFAB_CAPTURE_ENABLED"
152
152
  MAX_CAPTURED_SUBTREE_SPANS_ENV = "BITFAB_MAX_CAPTURED_SUBTREE_SPANS"
153
153
 
154
154
  DISABLED_INTEGRATIONS_ENV = "BITFAB_DISABLED_INTEGRATIONS"
155
+ ENABLED_INTEGRATIONS_ENV = "BITFAB_ENABLED_INTEGRATIONS"
155
156
  CONTENT_WITHHELD_KEY = "content_withheld_while_integration_off"
156
157
  OFF_BY_DEFAULT_INTEGRATIONS = frozenset({"gmail"})
157
158
  KNOWN_INTEGRATIONS = provider_calls.INTEGRATION_NAMES | OFF_BY_DEFAULT_INTEGRATIONS
@@ -170,9 +171,23 @@ def read_positive_int_env(name: str) -> int | None:
170
171
  return value if value > 0 else None
171
172
 
172
173
 
173
- def resolve_disabled_integrations(
174
+ def _integration_names_from_env(name: str, known: frozenset[str]) -> set[str]:
175
+ raw = os.environ.get(name, "")
176
+ names = {part.strip().lower() for part in raw.split(",") if part.strip()}
177
+ unknown = sorted(names - known)
178
+ if unknown:
179
+ warn_once(
180
+ f"unknown-integrations:{name}:{','.join(unknown)}",
181
+ f"{name} names {', '.join(unknown)}, "
182
+ f"which the SDK does not know; ignoring it. Known integrations are "
183
+ f"{', '.join(sorted(known))}.",
184
+ )
185
+ return names & known
186
+
187
+
188
+ def resolve_integrations(
174
189
  integrations: Mapping[str, bool] | None,
175
- ) -> frozenset[str]:
190
+ ) -> tuple[frozenset[str], frozenset[str]]:
176
191
  known = KNOWN_INTEGRATIONS
177
192
  in_code = dict(integrations or {})
178
193
  unknown = sorted(set(in_code) - known)
@@ -181,25 +196,26 @@ def resolve_disabled_integrations(
181
196
  f"Bitfab(integrations=...) got {', '.join(unknown)}; "
182
197
  f"known integrations are {', '.join(sorted(known))}."
183
198
  )
184
- raw = os.environ.get(DISABLED_INTEGRATIONS_ENV, "")
185
- from_env = {name.strip().lower() for name in raw.split(",") if name.strip()}
186
- unknown_in_env = sorted(from_env - known)
187
- if unknown_in_env:
188
- warn_once(
189
- f"unknown-disabled-integrations:{','.join(unknown_in_env)}",
190
- f"{DISABLED_INTEGRATIONS_ENV} names {', '.join(unknown_in_env)}, "
191
- f"which the SDK does not know; ignoring it. Known integrations are "
192
- f"{', '.join(sorted(known))}.",
193
- )
194
- return frozenset(
195
- name
196
- for name in known
197
- if (
198
- not in_code[name]
199
- if name in in_code
200
- else name in from_env or name in OFF_BY_DEFAULT_INTEGRATIONS
201
- )
202
- )
199
+ turned_off = _integration_names_from_env(DISABLED_INTEGRATIONS_ENV, known)
200
+ turned_on = _integration_names_from_env(ENABLED_INTEGRATIONS_ENV, known)
201
+ disabled: set[str] = set()
202
+ off_by_default: set[str] = set()
203
+ for name in known:
204
+ if name in in_code:
205
+ if not in_code[name]:
206
+ disabled.add(name)
207
+ elif name in turned_off:
208
+ disabled.add(name)
209
+ elif name in OFF_BY_DEFAULT_INTEGRATIONS and name not in turned_on:
210
+ disabled.add(name)
211
+ off_by_default.add(name)
212
+ return frozenset(disabled), frozenset(off_by_default)
213
+
214
+
215
+ def resolve_disabled_integrations(
216
+ integrations: Mapping[str, bool] | None,
217
+ ) -> frozenset[str]:
218
+ return resolve_integrations(integrations)[0]
203
219
 
204
220
 
205
221
  def read_boolean_env(name: str) -> bool | None:
@@ -1457,13 +1473,19 @@ class Bitfab:
1457
1473
  span, and replay cannot mock them, and a model client no
1458
1474
  Bitfab client has on is never patched. ``gmail`` (Google's
1459
1475
  Python client) is off by default because mail is sensitive;
1460
- True records each Gmail API call as a span named for its
1461
- method. Whatever this says, a Gmail call made during a replay
1476
+ True, or ``BITFAB_ENABLED_INTEGRATIONS=gmail``, records each
1477
+ Gmail API call as a span named for its method, which the Gmail
1478
+ sandbox builds its starting mailbox from on replay. While it is
1479
+ off only by default, the first Gmail call inside a trace warns
1480
+ once with how to turn it on; turning it off by name silences
1481
+ that. Whatever this says, a Gmail call made during a replay
1462
1482
  never reaches Google: the Gmail sandbox answers it. None
1463
1483
  (default) or a name left out: off when
1464
- ``BITFAB_DISABLED_INTEGRATIONS`` lists it (comma separated);
1465
- a name given here wins over that variable. Raises ValueError
1466
- for a name the SDK does not know.
1484
+ ``BITFAB_DISABLED_INTEGRATIONS`` lists it, on when
1485
+ ``BITFAB_ENABLED_INTEGRATIONS`` lists it (both comma
1486
+ separated; off wins when both do); a name given here wins
1487
+ over both variables. Raises ValueError for a name the SDK
1488
+ does not know.
1467
1489
  enabled: Deprecated alias for ``capture_enabled``. Warns once.
1468
1490
  """
1469
1491
  if enabled is not None:
@@ -1484,7 +1506,10 @@ class Bitfab:
1484
1506
  self._capture_enabled_in_code = capture_enabled
1485
1507
  self._capture_enabled_from_env: bool | None = None
1486
1508
  self._strict = strict
1487
- self._disabled_integrations = resolve_disabled_integrations(integrations)
1509
+ (
1510
+ self._disabled_integrations,
1511
+ self._integrations_off_by_default,
1512
+ ) = resolve_integrations(integrations)
1488
1513
  self._patched_integrations = (
1489
1514
  provider_calls.INTEGRATION_NAMES - self._disabled_integrations
1490
1515
  )
@@ -22,6 +22,9 @@ PROFILE_METHOD = "gmail.users.getProfile"
22
22
  LABELS_LIST_METHOD = "gmail.users.labels.list"
23
23
  LABEL_GET_METHOD = "gmail.users.labels.get"
24
24
  SEND_AS_LIST_METHOD = "gmail.users.settings.sendAs.list"
25
+ DRAFT_GET_METHOD = "gmail.users.drafts.get"
26
+ DRAFT_LIST_METHOD = "gmail.users.drafts.list"
27
+ DRAFT_CREATE_METHOD = "gmail.users.drafts.create"
25
28
  SYSTEM_LABELS = (
26
29
  "INBOX",
27
30
  "SENT",
@@ -167,6 +170,26 @@ def gmail_message(fields: dict[str, Any]) -> dict[str, Any]:
167
170
  return message
168
171
 
169
172
 
173
+ def _fields_from_raw(raw: str | None) -> dict[str, Any]:
174
+ parsed = email.message_from_string(
175
+ _unb64(raw) if raw else "", policy=email.policy.default
176
+ )
177
+ body_part = (
178
+ parsed.get_body(preferencelist=("plain", "html"))
179
+ if parsed.is_multipart()
180
+ else parsed
181
+ )
182
+ body = body_part.get_content() if body_part is not None else ""
183
+ return {
184
+ **{
185
+ key: str(parsed.get(header))
186
+ for key, header in _PLAIN_HEADERS.items()
187
+ if parsed.get(header)
188
+ },
189
+ "body": str(body),
190
+ }
191
+
192
+
170
193
  def _richer(
171
194
  existing: dict[str, Any] | None, candidate: dict[str, Any]
172
195
  ) -> dict[str, Any]:
@@ -182,11 +205,19 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
182
205
 
183
206
  Uses the state recorded with ``record_sandbox_state("Gmail", ...)`` when
184
207
  there is one. Otherwise takes every message the original run read
185
- (``gmail.users.messages.get`` replies) and each account's address from
186
- ``gmail.users.getProfile``, one mailbox per credential the calls used.
208
+ (``gmail.users.messages.get`` replies), each account's address from
209
+ ``gmail.users.getProfile``, and the drafts the run found
210
+ (``gmail.users.drafts.list`` and ``gmail.users.drafts.get`` replies, the
211
+ first read of each draft), one mailbox per credential the calls used.
212
+ Drafts the original run created are left out.
187
213
  """
188
214
  if ctx.recorded_state is not None:
189
215
  return as_mailboxes(ctx, ctx.recorded_state)
216
+ created = {
217
+ str(span.output.get("id"))
218
+ for span in ctx.recorded_spans(DRAFT_CREATE_METHOD)
219
+ if isinstance(span.output, dict) and span.output.get("id")
220
+ }
190
221
  by_credential: dict[str | None, dict[str, Any]] = {}
191
222
  for name in (
192
223
  GET_METHOD,
@@ -195,6 +226,8 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
195
226
  LABELS_LIST_METHOD,
196
227
  LABEL_GET_METHOD,
197
228
  SEND_AS_LIST_METHOD,
229
+ DRAFT_GET_METHOD,
230
+ DRAFT_LIST_METHOD,
198
231
  ):
199
232
  for span in ctx.recorded_spans(name):
200
233
  output = span.output
@@ -208,6 +241,7 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
208
241
  "credential": credential,
209
242
  "emailAddress": None,
210
243
  "messages": {},
244
+ "drafts": {},
211
245
  "searches": [],
212
246
  "labels": {},
213
247
  "sendAs": None,
@@ -233,11 +267,23 @@ def mailbox_from_recorded_calls(ctx: SandboxStartCtx) -> dict[str, Any]:
233
267
  _keep_user_label(box["labels"], output)
234
268
  if name == SEND_AS_LIST_METHOD and isinstance(output.get("sendAs"), list):
235
269
  box["sendAs"] = output["sendAs"]
270
+ drafts = (
271
+ [output]
272
+ if name == DRAFT_GET_METHOD
273
+ else output.get("drafts") or []
274
+ if name == DRAFT_LIST_METHOD
275
+ else []
276
+ )
277
+ for draft in drafts:
278
+ draft_id = str(draft.get("id") or "")
279
+ if draft_id and draft_id not in created:
280
+ box["drafts"].setdefault(draft_id, draft)
236
281
  boxes = [
237
282
  {
238
283
  **box,
239
284
  "messages": list(box["messages"].values()),
240
285
  "labels": list(box["labels"].values()),
286
+ "drafts": list(box["drafts"].values()),
241
287
  }
242
288
  for box in by_credential.values()
243
289
  ]
@@ -307,6 +353,12 @@ def new_mailbox(
307
353
  send_as: list[dict[str, Any]] | None = None,
308
354
  ) -> dict[str, Any]:
309
355
  normalized = [gmail_message(message) for message in messages or []]
356
+ notes: list[str] = []
357
+ started_drafts = [
358
+ _start_draft(draft, position, normalized, notes)
359
+ for position, draft in enumerate(drafts or [])
360
+ if isinstance(draft, dict)
361
+ ]
310
362
  for message in normalized:
311
363
  if (
312
364
  message.get("payload")
@@ -329,11 +381,11 @@ def new_mailbox(
329
381
  "historyId": 1000,
330
382
  "nextId": index * 1_000_000 + 1,
331
383
  "messages": normalized,
332
- "drafts": list(drafts or []),
384
+ "drafts": started_drafts,
333
385
  "searches": list(searches or []),
334
386
  "labels": [_user_label(label) for label in labels or []],
335
387
  "sendAs": None if send_as is None else [dict(entry) for entry in send_as],
336
- "notes": [],
388
+ "notes": notes,
337
389
  }
338
390
 
339
391
 
@@ -350,6 +402,60 @@ def _user_label(label: dict[str, Any] | str) -> dict[str, Any]:
350
402
  }
351
403
 
352
404
 
405
+ def _draft_label(labels: Any) -> list[str]:
406
+ kept = [label for label in labels or [] if label != "DRAFT"]
407
+ return ["DRAFT", *kept]
408
+
409
+
410
+ def _draft_ref(message: dict[str, Any]) -> dict[str, Any]:
411
+ return {
412
+ "id": message["id"],
413
+ "threadId": message.get("threadId"),
414
+ "labelIds": message.get("labelIds"),
415
+ }
416
+
417
+
418
+ def _start_draft(
419
+ draft: dict[str, Any],
420
+ position: int,
421
+ messages: list[dict[str, Any]],
422
+ notes: list[str],
423
+ ) -> dict[str, Any]:
424
+ draft_id = str(draft.get("id") or f"r-start{position}")
425
+ given = dict(draft.get("message") or {})
426
+ message_id = str(given.get("id") or f"m-{draft_id}")
427
+ if given.get("raw") and "payload" not in given:
428
+ given = {**given, **_fields_from_raw(given.pop("raw"))}
429
+ existing = next((m for m in messages if m.get("id") == message_id), None)
430
+ carries_content = bool(set(given) - {"id", "threadId", "labelIds", "historyId"})
431
+ if carries_content:
432
+ built = gmail_message({"labelIds": ["DRAFT"], **given, "id": message_id})
433
+ message = _richer(existing, built) if existing else built
434
+ elif existing is not None:
435
+ message = existing
436
+ else:
437
+ message = gmail_message(
438
+ {
439
+ "id": message_id,
440
+ "threadId": given.get("threadId"),
441
+ "labelIds": ["DRAFT"],
442
+ "body": "",
443
+ }
444
+ )
445
+ message["labelIds"] = _draft_label(
446
+ message.get("labelIds") if given.get("labelIds") is None else given["labelIds"]
447
+ )
448
+ if not _body_text(message.get("payload") or {}) and not message.get("snippet"):
449
+ notes.append(
450
+ f"draft {draft_id} was never read in full in the original run, so its message is empty"
451
+ )
452
+ if existing is None:
453
+ messages.append(message)
454
+ elif message is not existing:
455
+ messages[messages.index(existing)] = message
456
+ return {"id": draft_id, "message": _draft_ref(message)}
457
+
458
+
353
459
  def _note(state: dict[str, Any], text: str) -> None:
354
460
  notes = state.setdefault("notes", [])
355
461
  if text not in notes:
@@ -685,27 +791,12 @@ def _bump_history(state: dict[str, Any]) -> str:
685
791
  def _from_raw(
686
792
  state: dict[str, Any], raw: str | None, thread_id: str | None, labels: list[str]
687
793
  ) -> dict[str, Any]:
688
- parsed = email.message_from_string(
689
- _unb64(raw) if raw else "", policy=email.policy.default
690
- )
691
- body_part = (
692
- parsed.get_body(preferencelist=("plain", "html"))
693
- if parsed.is_multipart()
694
- else parsed
695
- )
696
- body = body_part.get_content() if body_part is not None else ""
697
- fields = {
698
- key: parsed.get(header)
699
- for key, header in _PLAIN_HEADERS.items()
700
- if parsed.get(header)
701
- }
702
794
  message_id = _next_id(state, "sandbox")
703
795
  message = gmail_message(
704
796
  {
705
- **fields,
797
+ **_fields_from_raw(raw),
706
798
  "id": message_id,
707
799
  "threadId": thread_id or message_id,
708
- "body": str(body),
709
800
  "labelIds": labels,
710
801
  "internalDate": _clock_millis(state),
711
802
  }
@@ -726,31 +817,87 @@ def _send(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
726
817
  }
727
818
 
728
819
 
820
+ def _bad_request(text: str) -> dict[str, Any]:
821
+ return {
822
+ HTTP_ERROR_KEY: {
823
+ "code": 400,
824
+ "message": text,
825
+ "status": "INVALID_ARGUMENT",
826
+ "errors": [
827
+ {"message": text, "domain": "global", "reason": "invalidArgument"}
828
+ ],
829
+ }
830
+ }
831
+
832
+
833
+ def _find_draft(state: dict[str, Any], draft_id: Any) -> dict[str, Any] | None:
834
+ return next((d for d in state["drafts"] if d.get("id") == draft_id), None)
835
+
836
+
837
+ def _new_draft_message(
838
+ state: dict[str, Any], inner: dict[str, Any], thread_id: str | None
839
+ ) -> dict[str, Any]:
840
+ message = _from_raw(
841
+ state, inner.get("raw"), inner.get("threadId") or thread_id, ["DRAFT"]
842
+ )
843
+ state["messages"].append(message)
844
+ return message
845
+
846
+
729
847
  def _draft_create(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
730
848
  inner = (params.get("body") or {}).get("message") or {}
731
- message = _from_raw(state, inner.get("raw"), inner.get("threadId"), ["DRAFT"])
732
- state["messages"].append(message)
733
- draft = {
734
- "id": _next_id(state, "r-sandbox"),
735
- "message": {
736
- "id": message["id"],
737
- "threadId": message["threadId"],
738
- "labelIds": ["DRAFT"],
739
- },
740
- }
849
+ message = _new_draft_message(state, inner, None)
850
+ draft = {"id": _next_id(state, "r-sandbox"), "message": _draft_ref(message)}
741
851
  state["drafts"].append(draft)
742
- return draft
852
+ return copy.deepcopy(draft)
743
853
 
744
854
 
745
- def _draft_send(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
746
- draft_id = (params.get("body") or {}).get("id")
747
- draft = next((d for d in state["drafts"] if d.get("id") == draft_id), None)
855
+ def _draft_get(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
856
+ draft = _find_draft(state, params.get("id"))
748
857
  if draft is None:
749
- return _not_found(f"draft {draft_id}")
750
- state["drafts"].remove(draft)
858
+ return _not_found(f"draft {params.get('id')}")
751
859
  message = _find(state, draft["message"]["id"])
752
860
  if message is None:
753
861
  return _not_found(f"message {draft['message']['id']}")
862
+ fmt = str(params.get("format") or "full").lower()
863
+ return {"id": draft["id"], "message": _shaped(message, fmt, None)}
864
+
865
+
866
+ def _replace_draft_message(
867
+ state: dict[str, Any], draft: dict[str, Any], inner: dict[str, Any]
868
+ ) -> None:
869
+ old = _find(state, draft["message"]["id"])
870
+ if old is not None:
871
+ state["messages"].remove(old)
872
+ message = _new_draft_message(
873
+ state, inner, (old or draft["message"]).get("threadId")
874
+ )
875
+ draft["message"] = _draft_ref(message)
876
+
877
+
878
+ def _draft_update(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
879
+ draft = _find_draft(state, params.get("id"))
880
+ if draft is None:
881
+ return _not_found(f"draft {params.get('id')}")
882
+ inner = (params.get("body") or {}).get("message") or {}
883
+ if not inner.get("raw"):
884
+ return _bad_request("Missing draft message")
885
+ _replace_draft_message(state, draft, inner)
886
+ return copy.deepcopy(draft)
887
+
888
+
889
+ def _draft_delete(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
890
+ draft = _find_draft(state, params.get("id"))
891
+ if draft is None:
892
+ return _not_found(f"draft {params.get('id')}")
893
+ state["drafts"].remove(draft)
894
+ message = _find(state, draft["message"]["id"])
895
+ if message is not None:
896
+ state["messages"].remove(message)
897
+ return {}
898
+
899
+
900
+ def _mark_sent(state: dict[str, Any], message: dict[str, Any]) -> dict[str, Any]:
754
901
  message["labelIds"] = [
755
902
  label for label in message.get("labelIds") or [] if label != "DRAFT"
756
903
  ] + ["SENT"]
@@ -762,6 +909,26 @@ def _draft_send(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]
762
909
  }
763
910
 
764
911
 
912
+ def _draft_send(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
913
+ body = params.get("body") or {}
914
+ inner = body.get("message") or {}
915
+ draft_id = body.get("id")
916
+ if draft_id is None:
917
+ if not inner.get("raw"):
918
+ return _bad_request("Missing draft id or message")
919
+ return _mark_sent(state, _new_draft_message(state, inner, None))
920
+ draft = _find_draft(state, draft_id)
921
+ if draft is None:
922
+ return _not_found(f"draft {draft_id}")
923
+ if inner.get("raw"):
924
+ _replace_draft_message(state, draft, inner)
925
+ state["drafts"].remove(draft)
926
+ message = _find(state, draft["message"]["id"])
927
+ if message is None:
928
+ return _not_found(f"message {draft['message']['id']}")
929
+ return _mark_sent(state, message)
930
+
931
+
765
932
  def _modify(state: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
766
933
  message = _find(state, str(params.get("id")))
767
934
  if message is None:
@@ -967,9 +1134,12 @@ HANDLERS: dict[str, Callable[[dict[str, Any], dict[str, Any]], dict[str, Any]]]
967
1134
  "gmail.users.messages.send": _send,
968
1135
  "gmail.users.messages.modify": _modify,
969
1136
  "gmail.users.messages.attachments.get": _attachment,
970
- "gmail.users.drafts.create": _draft_create,
1137
+ DRAFT_CREATE_METHOD: _draft_create,
1138
+ DRAFT_GET_METHOD: _draft_get,
1139
+ "gmail.users.drafts.update": _draft_update,
1140
+ "gmail.users.drafts.delete": _draft_delete,
971
1141
  "gmail.users.drafts.send": _draft_send,
972
- "gmail.users.drafts.list": _drafts_list,
1142
+ DRAFT_LIST_METHOD: _drafts_list,
973
1143
  "gmail.users.threads.get": _thread,
974
1144
  "gmail.users.history.list": _history,
975
1145
  LABELS_LIST_METHOD: _labels,
@@ -1095,7 +1265,10 @@ def gmail_sandbox(
1095
1265
  signature.
1096
1266
  Each message is a Gmail API message or plain fields as
1097
1267
  ``gmail_message`` takes them; a plain ``account`` field puts the
1098
- message in that account's mailbox. For several accounts, return
1268
+ message in that account's mailbox. Each draft is
1269
+ ``{"id": ..., "message": ...}``, where the message is a Gmail API
1270
+ message (as ``drafts.get`` returns it, ``raw`` included), plain
1271
+ fields, or only the ``id`` of a message in ``messages``. For several accounts, return
1099
1272
  ``{"mailboxes": [{"emailAddress": ..., "messages": [...]}]}``.
1100
1273
  ``None`` uses ``mailbox_from_recorded_calls``.
1101
1274
  account: With several mailboxes, names the account a call is for
@@ -11,6 +11,7 @@ from typing import Any
11
11
 
12
12
  from bitfab.constants import _replay_context, replay_item_is_running
13
13
  from bitfab.sandbox import SANDBOX_SESSION_KEY
14
+ from bitfab.warn_once import warn_once
14
15
 
15
16
 
16
17
  @dataclass(frozen=True)
@@ -53,6 +54,22 @@ def _records(client: Any, integration: str) -> bool:
53
54
  return integration not in getattr(client, "_disabled_integrations", ())
54
55
 
55
56
 
57
+ def _warn_recording_off_by_default(integration: str) -> None:
58
+ newest = next(iter(_alive_clients()), None)
59
+ if integration not in getattr(newest, "_integrations_off_by_default", ()):
60
+ return
61
+ warn_once(
62
+ f"integration-off-by-default:{integration}",
63
+ f"a {integration} call ran inside a trace and was not recorded, because "
64
+ f"Bitfab records {integration} calls only once you turn them on (they "
65
+ f"carry your users' data). Without them, replays of this trace start "
66
+ f"the {integration} sandbox with nothing the original run read. Turn "
67
+ f'recording on with Bitfab(integrations={{"{integration}": True}}) or '
68
+ f"BITFAB_ENABLED_INTEGRATIONS={integration}; turn it off by name "
69
+ f'(integrations={{"{integration}": False}}) to stop this warning.',
70
+ )
71
+
72
+
56
73
  def current_call() -> ServiceCall | None:
57
74
  return _current.get()
58
75
 
@@ -117,6 +134,8 @@ def run(call: ServiceCall) -> Any:
117
134
  (c for c in _alive_clients() if _records(c, call.integration)), None
118
135
  )
119
136
  if client is None or not _inside_trace():
137
+ if client is None and _inside_trace():
138
+ _warn_recording_off_by_default(call.integration)
120
139
  return call.send()
121
140
  tokens = (
122
141
  _current.set(call),
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "bitfab-py"
3
- version = "0.78.1"
3
+ version = "0.78.3"
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