diff --git a/data/.codex/.codex/.tmp/plugins/plugins/amplitude/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/amplitude/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..ad275566fdb326dc1f76b1442267ebe079961fe2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/amplitude/.codex-plugin/plugin.json @@ -0,0 +1,26 @@ +{ + "name": "amplitude", + "version": "1.0.2", + "description": "Product analytics and funnels", + "author": { + "name": "Amplitude" + }, + "repository": "https://github.com/openai/plugins", + "license": "MIT", + "keywords": [], + "apps": "./.app.json", + "interface": { + "displayName": "Amplitude", + "shortDescription": "Product analytics and funnels", + "longDescription": "Product analytics and funnels", + "developerName": "Amplitude", + "category": "Data & Analytics", + "capabilities": [], + "defaultPrompt": [ + "Show the signup funnel trend in Amplitude" + ], + "screenshots": [], + "composerIcon": "./assets/app-icon.png", + "logo": "./assets/app-icon.png" + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/brex/.codex-plugin/plugin.json b/data/.codex/.codex/.tmp/plugins/plugins/brex/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..bc01ac4b98c4aaad4a8716f5c29870ae07971279 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/brex/.codex-plugin/plugin.json @@ -0,0 +1,32 @@ +{ + "name": "brex", + "version": "1.0.3", + "description": "Connect Brex to Codex and review your company finances through natural conversation \u2014 at Codex speed.", + "author": { + "name": "Brex Inc.", + "url": "https://brex.com" + }, + "homepage": "https://brex.com", + "repository": "https://github.com/openai/plugins", + "license": "MIT", + "keywords": [], + "apps": "./.app.json", + "interface": { + "displayName": "Brex", + "shortDescription": "Connect Brex to Codex and review your company finances through natural conversation \u2014 at Codex speed.", + "longDescription": "Connect Brex to Codex and review your company finances through natural conversation \u2014 at Codex speed.\n\nFor finance teams: Analyze spend, detect anomalies, and run custom queries and reports instantly to accelerate decisions and do more with less.\n\nFor employees: See how much you can spend, ask policy questions, check reimbursement status, manage travel, and more right in Codex.\n\nAccess is role-aware by default: employees see only what applies to them, while admins retain full visibility and control.", + "developerName": "Brex Inc.", + "category": "Finance", + "capabilities": [], + "websiteURL": "https://brex.com", + "privacyPolicyURL": "https://www.brex.com/legal/privacy", + "termsOfServiceURL": "https://www.brex.com/legal/platform-agreement", + "defaultPrompt": [ + "How much did I spend on Delta last year" + ], + "screenshots": [], + "composerIcon": "./assets/logo.png", + "logo": "./assets/logo.png", + "logoDark": "./assets/logo-dark.png" + } +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ee56259aa5dcaf360322f562a0dba9cd3ae49863 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/SKILL.md @@ -0,0 +1,99 @@ +--- +name: chronograph-cashflow-forecast +description: Forecast private capital cashflows for existing portfolios using Chronograph MCP data and a Takahashi-Alexander style model. Use when Codex needs to analyze or forecast LP-level contributions, distributions, NAV, unfunded exposure, net cashflows, or Excel-style cashflow forecast outputs from existing Chronograph funds, commitments, groups, or portfolios. +--- + +# Chronograph Cashflow Forecast + +**Requirements:** The Existing Portfolio Forecast mode requires a connected Chronograph MCP server — these workflows are designed for permissioned Chronograph users to connect to their private investment data. The Future Commitment Pacing Overlay mode runs from user-provided assumptions and works without a connection. + +## Overview + +Use the Chronograph MCP server as the source of truth for private capital commitment data, then forecast fund and portfolio cashflows with a Takahashi-Alexander style model. Prefer concise analysis in chat unless the user asks for a workbook, export, or model artifact. + +Do not hard-code tool names — read the Chronograph MCP server's live tool descriptions to pick the appropriate tool for each data need. + +## Workflow + +1. Clarify scope only when needed: portfolio, group, fund IDs, commitment IDs, currency, as-of date, forecast horizon, and units. V1 is existing-portfolio-only; do not model future commitments or pacing schedules. +2. Resolve entities. The Chronograph MCP server exposes a tool for resolving fund, group, GP, or company names to IDs. Use it to turn user-provided names into IDs before pulling any metrics. +3. Pull fund metadata. The Chronograph MCP server exposes a generic query tool for retrieving core entity attributes — use it to get fund name, fund type, vintage year, reporting currency, geographic focus, general partner, and final reporting date where useful. +4. Pull net LP commitment values: NAV, called, distributed, unfunded, commitment amount, net IRR, net MOIC, DPI, and RVPI. The Chronograph MCP server exposes a dedicated tool for net LP-level performance that covers all of these. Treat the values as net and surface the as-of date, currency, and that the values are net (not gross) in user-facing results. +5. Map fund types to forecast assumptions. Use the default assumptions in `references/model-methodology.md` unless the user provides custom assumptions. +6. Build yearly or quarterly forecast periods from the as-of date through the requested horizon. Default to annual periods for executive analysis and quarterly periods for Excel-style output. +7. Forecast contributions, distributions, NAV, unfunded, and net cashflow by fund, then aggregate to portfolio, group, vintage, fund type, or GP as requested. +8. Present assumptions, source context, and checks. Always state currency, units, as-of date, forecast horizon, and that future commitments are excluded in V1. +9. If the user requests Excel, create a workbook with Inputs, Fund Forecast, Portfolio Summary, and Checks. + +## Planning Mode + +Use one of these modes, or combine them when the user asks for a liquidity plan: + +- **Existing Portfolio Forecast.** Use Chronograph actuals for current commitments, NAV, unfunded, called, distributed, and net performance, then forecast runoff for existing commitments only. +- **Future Commitment Pacing Overlay.** Use user-provided planned commitments and strategy assumptions to estimate future calls, distributions, NAV, unfunded, exposure, and net cashflow. These values are planning assumptions, not Chronograph actuals. +- **Combined Liquidity Plan.** Add the existing portfolio forecast and pacing overlay to show total expected calls, distributions, net cashflow, NAV, unfunded, and exposure. + +## Chronograph MCP Usage + +The skill needs three categories of data from the Chronograph MCP server: entity identifiers (fund and group IDs), fund metadata (name, type, vintage, reporting currency, geographic focus, GP, final reporting date), and net LP-level cashflow values (NAV, called, distributed, unfunded, commitment amount, net IRR, net MOIC, DPI, RVPI). Inspect the server's live tool descriptions and pick the appropriate tool for each category. Do not hard-code tool names. + +**Net vs gross — confirm with the user when ambiguous.** This skill forecasts *net* LP cashflows. The Chronograph MCP server exposes separate tools for net LP-level performance and gross fund-level returns. User requests like "show me MOIC for these funds" are ambiguous — confirm net or gross before picking a tool. Gross returns (gross IRR, gross MOIC, cost, realized, unrealized) are not used in this forecast and live in a different tool. + +**Currency.** Do not default currency to USD. For specific funds, resolve reporting currency from fund metadata before pulling cashflow values. If reporting currencies conflict across a multi-fund portfolio, ask the user. + +**Custom investment-level metrics.** If a tool requires a discovery / help / schema-introspection call first (common pattern on the Chronograph MCP server), make that call to see which metric types are available, then query each line item. + +See `references/chronograph-mcp-map.md` for data-need to tool mapping guidance. + +## Error Handling + +- **MCP not connected.** Depends on mode. For an Existing Portfolio Forecast, stop — the connection is required, because forecasting runoff of a real portfolio needs its actual NAV, unfunded, called, and distributed baseline; do not invent those values or forecast a real portfolio from assumptions alone. For a Future Commitment Pacing Overlay (or a from-scratch pacing request with no existing portfolio), proceed from user-provided commitment amounts, vintages, and strategy assumptions, and label every value as a planning assumption rather than a Chronograph actual. If the user wants a Combined Liquidity Plan but Chronograph is unavailable, produce the pacing overlay only and list the existing-portfolio baseline as a missing input. +- **Entity not found.** Ask the user to confirm the fund / group / GP name. Do not silently substitute a near-match. +- **Currency cannot be resolved.** Ask the user which currency to use rather than defaulting to USD. +- **Future commitments / pacing overlay.** Chronograph is still the source of truth for the existing portfolio baseline. Future commitments are user-provided planning assumptions. Do not imply that planned commitments, future calls, future distributions, future NAV, or wind-down schedules are sourced from Chronograph if they are guided by the user in conversation. +- **Net-vs-gross ambiguity.** Confirm with the user before proceeding. +- **Pacing details incomplete.** If the user gives a high-level plan such as "deploy $500mm for a couple years, then wind down," make a conservative explicit schedule and label it as an assumption. Ask when the missing detail materially changes the decision, such as currency, annual versus total commitment budget, or strategy mix. + +## Forecast Method + +Use `references/model-methodology.md` for the distilled forecast methodology. Load it when doing actual forecast math, explaining assumptions, building an Excel output, or debugging differences versus a reference workbook. + +Core outputs: + +- Contributions: forecast capital calls. +- Distributions: forecast realizations/income. +- NAV: forecast residual value. +- Unfunded: forecast remaining callable commitment. +- Net cashflow: distributions minus contributions. +- Total exposure: NAV plus unfunded. + +## Output Standards + +- Include a compact assumption table whenever forecast values are shown. +- For planning-mode outputs, include a baseline section, an assumed commitment schedule, an overlay cashflow table, a combined liquidity view when available, and caveats / missing inputs. +- Separate actuals from forecasts. Label actual periods with `A` and forecast periods with `E` when producing Excel-style tables. +- Show totals and key years first, then detail by fund or fund type. +- Include basic checks: beginning NAV plus contributions less distributions plus growth should reconcile to ending NAV; prior unfunded less contributions should reconcile to ending unfunded; net cashflow should equal distributions less contributions. +- Avoid overstating precision. Forecasts are model estimates driven by assumptions, not Chronograph-reported future values. + +## Guardrails + +- Treat the output as draft analyst work product for liquidity and pacing planning. +- Do not provide investment, legal, tax, audit, or valuation advice. A forecast or liquidity plan is a scenario estimate, not a recommendation to commit, call, distribute, or sell. +- Do not present a pacing figure or commitment range as advice to act. Frame it as what the model implies under the stated assumptions, and surface the assumptions that drive it. +- Forecasts are scenario estimates under explicit assumptions, not predictions. Disclose the assumption set and that actual outcomes will differ. +- Do not imply that planned commitments, future calls, future distributions, or future NAV are sourced from Chronograph when they are user-provided planning inputs. + +## Excel Outputs + +When asked for Excel, use the spreadsheet skill and build a clean workbook rather than recreating the original workbook cell-by-cell. A good workbook shape is: + +- `Inputs`: scope, as-of date, currency, units, horizon, assumptions by fund type. +- `Fund Forecast`: one row per fund/period with actuals and forecast values. +- `Portfolio Summary`: annual totals, net cashflow, NAV, unfunded, exposure, charts when useful. +- `Checks`: reconciliation checks and source context. + +## Reference Files + +- `references/model-methodology.md`: forecast formulas and default assumptions based on the Excel model. +- `references/chronograph-mcp-map.md`: Chronograph MCP data-need to tool mapping guidance for this workflow. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ec7068a11a93eba9e8196ba26b2756c4b93d7d3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Chronograph Cashflow Forecast" + short_description: "Forecast private capital cashflows with Chronograph" + default_prompt: "Use $chronograph-cashflow-forecast to forecast private capital contributions, distributions, NAV, and unfunded exposure from Chronograph data." + +dependencies: + tools: + - type: "mcp" + value: "chronograph-lp" + description: "Chronograph MCP server for fund, commitment, and investment data." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/references/chronograph-mcp-map.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/references/chronograph-mcp-map.md new file mode 100644 index 0000000000000000000000000000000000000000..48384eb231c2ddfaa83b8640eac84be026b4a141 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/references/chronograph-mcp-map.md @@ -0,0 +1,36 @@ +# Chronograph MCP Data Map + +Use this map to translate cashflow forecast data needs into Chronograph MCP tool selection. Do not hard-code tool names — read the Chronograph MCP server's live tool descriptions to stay current. + +## Primary data needs + +The skill needs four categories of data from the Chronograph MCP server: + +- **Entity identifiers.** Fund IDs, group IDs, GP IDs, commitment IDs. Chronograph exposes a dedicated tool for resolving names to IDs. Use it before pulling any metric data. +- **Fund metadata.** Fund name, fund type, vintage year, reporting currency, geographic focus, final reporting date, general partner. Chronograph exposes a generic query tool covering core entity attributes — use it for all metadata reads. +- **Net LP commitment values.** NAV, called, distributed, unfunded, commitment amount, net IRR, net MOIC, DPI, RVPI. Chronograph exposes a dedicated tool for net LP-level performance that covers all of these in a single call. +- **Custom investment-level metrics (rare for cashflow forecasting).** Only needed if the user asks for non-standard metrics like Revenue or EBITDA. Chronograph exposes a metrics tool for these; it requires a discovery call first to enumerate available metric types. + +## Net vs gross + +This skill uses *net* LP cashflow values, not gross fund returns. If the user request is ambiguous ("show me MOIC for these funds"), confirm net or gross before pulling data. Gross returns (gross IRR, gross MOIC, cost, realized, unrealized) live in a separate Chronograph tool and are not used in this forecast. + +## Currency + +Do not default to USD. Resolve reporting currency from fund metadata before pulling cashflow values. If reporting currencies conflict across a multi-fund portfolio, ask the user. + +## Fund type mapping + +Map Chronograph fund-type values to general forecast buckets per the table in `model-methodology.md`. Do not duplicate that table here. + +## Presentation requirements + +Always surface in user-facing output: + +- as-of date +- currency +- that the values are net (not gross) +- number of funds or commitments included +- any funds excluded because data was missing + +When forecast assumptions are applied, separate Chronograph-reported actuals from model-generated forecasts. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/references/model-methodology.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/references/model-methodology.md new file mode 100644 index 0000000000000000000000000000000000000000..74128c8e4fd24911322315ef5fa382c3591fbb46 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-cashflow-forecast/references/model-methodology.md @@ -0,0 +1,141 @@ +# Model Methodology + +This reference distills a Takahashi-Alexander style cashflow model pattern. Use it to forecast private capital cashflows from Chronograph actuals. Treat future commitments and pacing overlays as user-provided assumptions and model estimates. + +## Model Modes + +- Existing portfolio forecast: forecast runoff from current Chronograph commitments. +- Future commitment pacing overlay: model planned new commitments as assumptions. +- Combined liquidity view: add existing portfolio forecast and future pacing overlay. + +## Example Planning Assumptions + +Use these as illustrative starting points when the user has not provided custom assumptions. Do not treat them as client-specific defaults. + +| General fund type | Initial contribution rate | Contribution rate | Bow | Life | Yield | Growth | +|---|---:|---:|---:|---:|---:|---:| +| Buyout / Private Equity | 25% | 50% | 2.5 | 12 | 0% | 13% | +| Venture / Growth | 25% | 50% | 3.0 | 15 | 0% | 10% | +| Real Assets | 40% | 40% | 5.0 | 12 | 5% | 8% | +| Energy / Natural Resources | 30% | 50% | 1.0 | 15 | 15% | 8% | +| Other / Mixed | 30% | 45% | 2.0 | 12 | 8% | 8% | + +Ask for user assumptions when strategy mix materially affects the answer. If unavailable, use a clearly labeled illustrative assumption set. + +## Assumption Selection + +Use assumptions in this order: + +1. User-provided assumptions. +2. User-provided strategy mix mapped to the example assumption sets. +3. A clearly labeled illustrative assumption set. +4. Chronograph fund type metadata. + +## Input Data + +For each fund or commitment, collect: + +- Fund ID and fund name. +- Commitment ID if working at commitment level. +- Vintage year. +- Fund type or a mapped general fund type. +- Commitment amount. +- Actual called, distributed, NAV, and unfunded as of the current reporting date. +- Historical called and distributed if the output needs actual annual cashflows. + +## Periods + +Use annual forecast periods by default. If the as-of date is not a year end, the first forecast year should be prorated for remaining quarters in the year. For a quarterly model, apply the same formulas at quarter granularity. + +Let: + +- `age = forecast_year - vintage_year` +- `remaining_unfunded_prior = prior period unfunded` +- `nav_prior = prior period NAV` +- `initial_call_rate = assumption for years 1-2` +- `call_rate = assumption for years 3+` +- `bow`, `life`, `yield`, and `growth` from the assumption table + +## Forecast Contributions + +The workbook calls capital from prior unfunded. For annual periods: + +```text +rate = initial_call_rate if age <= 2 else call_rate +forecast_contribution = max(rate * remaining_unfunded_prior, 0) +``` + +For a stub first forecast year, prorate by remaining quarters: + +```text +stub_factor = remaining_quarters_in_year / 4 +forecast_contribution = stub_factor * rate * remaining_unfunded_prior +``` + +Cap contributions so they do not exceed prior unfunded unless the user explicitly wants a looser model. + +## Forecast Distribution Rate + +The workbook uses a Takahashi-Alexander style bow curve: + +```text +life_progress = age / life +distribution_rate = 1 if life_progress >= 1 else max(yield, life_progress ^ bow) +``` + +Clamp negative ages to zero. If vintage year is missing, ask for a vintage or use a conservative assumption only if the user approves. + +## Forecast Distributions + +The workbook applies the distribution rate to prior NAV after growth, with a special first forecast period that avoids a drop below prior actual distributions within the same year. + +Simple annual implementation: + +```text +forecast_distribution = distribution_rate * nav_prior * (1 + growth) +``` + +For income-oriented strategies, `yield` creates a floor through the distribution rate formula. Distributions should not exceed a sensible total value unless the user asks for unconstrained output. + +## Forecast NAV + +Roll NAV forward: + +```text +forecast_nav = max(nav_prior * (1 + growth) + forecast_contribution - forecast_distribution, 0) +``` + +For quarterly periods: + +```text +quarterly_growth = (1 + annual_growth) ^ 0.25 - 1 +forecast_nav = max(nav_prior * (1 + quarterly_growth) + contribution - distribution, 0) +``` + +## Forecast Unfunded + +Roll unfunded forward: + +```text +forecast_unfunded = max(remaining_unfunded_prior - forecast_contribution, 0) +``` + +## Net Cashflow and Exposure + +```text +net_cashflow = distributions - contributions +exposure = nav + unfunded +``` + +Use net cashflow from the LP perspective: contributions are cash outflows, distributions are inflows. + +## Checks + +Include these checks in analysis or Excel outputs: + +- Contributions do not exceed beginning unfunded. +- Ending unfunded equals beginning unfunded less contributions. +- Ending NAV equals beginning NAV grown plus contributions less distributions. +- Net cashflow equals distributions less contributions. +- Planned commitments are not counted as contributions until called. +- Combined totals equal existing portfolio plus pacing overlay. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..c63e23f0bf560a4649eb62f8e1fdbce611a2e614 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/SKILL.md @@ -0,0 +1,88 @@ +--- +name: chronograph-gp-meeting-prep +description: > + Prepare an LP to meet with their fund manager (GP): review the fund's latest + reporting, surface what changed since last period, and draft the questions + worth raising. Use when someone is getting ready for a manager call, quarterly + check-in, annual meeting, LPAC meeting, or a re-up decision — for example "I + have my quarterly call with this manager next week, help me prep," "what + changed in this fund this quarter," "what should I ask them about these marks," + or "what are the red flags in this reporting package." Draws on Chronograph + fund and portfolio data when connected — captured reporting such as fund + performance, schedules of investments, and portfolio company KPI profiles — + and asks the LP to provide anything else it needs, such as a capital account + statement, investor letter, or AGM or board deck. +--- + +# Chronograph GP Meeting Prep + +**Requirements:** A connected Chronograph MCP server. These workflows are designed for permissioned Chronograph users to connect to their private investment data. + +## Overview + +Prepare an LP for a meeting with a GP by reviewing fund reporting, surfacing what changed, identifying diligence questions, and producing a concise meeting brief. The brief exists to sharpen a forward decision — a re-up, a secondary sale, or an LPAC vote — so prioritize what bears on those. Use Chronograph as the source of truth where connected and permissioned; otherwise work from user-provided reporting materials. + +Default to a chat brief. Create a document, workbook, or deck only when the user asks for an artifact. + +## Workflow + +1. Clarify scope only when needed: GP, fund, reporting period, meeting type, as-of date, currency, units, output format, and whether the user wants a quick brief or a formal prep document. +2. Resolve the relevant fund, manager, commitment, reporting period, and LP perspective from Chronograph where available. If Chronograph is unavailable, ask for the GP reporting package or a pasted/uploaded summary. +3. Gather the fund baseline, anchoring first on the figures the GP reported this period and citing the source document where available: gross performance, cost, realized and unrealized value, current valuation, portfolio holdings, prior-period values, and fund attributes. Carry net performance — NAV, calls, distributions, TVPI/DPI/RVPI, and net IRR — as the LP's headline return, clearly labeled gross versus net and dated. +4. Review document-backed reporting content. When Chronograph document semantic search is available, use it as a primary step to find the story behind the numbers: what drove calls and distributions, how the GP describes its marks, and the commentary on portfolio company KPIs. +5. If a document the meeting needs isn't in the connected context, ask the LP to provide it. Do not infer narrative, management explanations, or meeting context from structured data alone. +6. Compare current period to prior period: performance movement, cashflow activity, NAV and unfunded movement, valuation changes, portfolio company adds/exits, concentration changes, and KPI movements. +7. Separate facts from interpretation. Use reporting data for facts, cite document support when available, and label inferred questions as analyst prompts rather than confirmed issues. +8. Produce a prioritized meeting brief with key changes, watch items, suggested GP questions, and follow-up requests. + +## Chronograph Data Use + +When the Chronograph MCP is available, use it to retrieve the relevant portfolio, fund, commitment, performance, exposure, and report-derived document context where permissioned. Keep public-facing explanations at the workflow level; do not expose internal schemas, private tool names, field mappings, or retrieval recipes. + +Source discipline: + +- Cite Chronograph, document, page, period, or user-provided source for quantitative claims whenever available. +- State currency, units, as-of date, and whether values are GP-reported, Chronograph-derived, user-provided, or estimated. +- Do not fabricate NAVs, KPIs, performance metrics, holdings, explanations, or manager commentary. +- If sources disagree, present the discrepancy and ask the GP-facing question that follows from it. + +## Review Priorities + +Use `references/report-review-checklist.md` for a fuller checklist when reviewing a package. Anchor the review on the figures the GP reported this period, citing the source document where available, and present net performance as the LP's headline return clearly labeled gross versus net. Prioritize: + +- Performance: lead with the GP-reported figures — gross IRR and MOIC, cost, and realized and unrealized value — and their movement versus prior period, citing sources where available. Carry net performance (TVPI, DPI, RVPI, net IRR) as the LP's bottom-line return, labeled gross versus net, and watch the trend from unrealized value toward realized distributions. +- Cashflows: calls, distributions, recallable amounts, unfunded exposure, and unusual activity. Distinguish realized-cash distributions from those financed by NAV or subscription-line facilities. +- Valuation: write-ups, write-downs, stale marks, methodology changes (including any shift toward a cost basis), the GP's written valuation policy, and valuation concentration. +- Portfolio: new investments, exits, major company KPI changes, top holdings, sector/geography exposure, and single-name concentration. +- Reporting quality: missing explanations, inconsistent values, stale dates, changed definitions, or unexplained metric movement. +- Meeting readiness: three to eight prioritized questions, required follow-up materials, and open items to track. + +## Output + +For a quick answer, use this shape: + +- Executive snapshot +- What changed this period +- Items to ask the GP +- Follow-up requests +- Source notes and assumptions + +For a formal memo or document, use `references/meeting-brief-template.md`. + +Use `references/question-bank.md` when the user wants more complete question coverage by topic or when the review surfaces a broad set of issues. + +## Fallback Behavior + +If Chronograph is unavailable, or the meeting needs a document outside the connected context: + +- Ask the LP for the relevant GP reporting package or materials — for example the quarterly report, schedule of investments, capital account statement, or prior meeting notes. +- If only partial data is available, produce a partial brief and list the missing inputs needed for a complete meeting prep. +- If the user provides PDFs, workbooks, or pasted text, extract only what is supported by the material and cite the source artifact. + +## Guardrails + +- Treat the output as draft analyst work product for LP meeting preparation. +- Do not provide investment, legal, tax, audit, or valuation advice. +- Do not imply that a missing GP explanation is misconduct; frame gaps as questions or follow-up requests. +- Do not infer manager intent or portfolio company facts from metric movement alone. +- Avoid overprecision. Round appropriately and disclose incomplete source coverage. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f1669581a4969bb942a96e259d978f12d1eec92 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Chronograph GP Meeting Prep" + short_description: "Prepare LP meeting briefs from GP reporting" + default_prompt: "Use $chronograph-gp-meeting-prep to review GP reporting and prepare an LP meeting brief." + +dependencies: + tools: + - type: "mcp" + value: "chronograph-lp" + description: "Chronograph MCP server for private capital fund, commitment, performance, exposure, and report-derived document context." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/meeting-brief-template.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/meeting-brief-template.md new file mode 100644 index 0000000000000000000000000000000000000000..da985b826b2cc43754842b51f3de0583042286fa --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/meeting-brief-template.md @@ -0,0 +1,106 @@ +# Meeting Brief Template + +Use this template when the user asks for a formal memo, document, or full GP meeting prep brief. Keep it concise; expand only where the source materials support it. + +## Header + +- GP: +- Fund: +- Reporting period: +- Meeting type: +- LP perspective: +- Currency and units: +- Sources reviewed: +- Prepared date: + +## 1. Executive Snapshot + +Summarize the fund's current status in 3-5 bullets: + +- Current valuation and performance position +- Period-over-period change +- Major cashflow activity +- Most important portfolio or KPI movement +- Highest-priority meeting topic + +## 2. What Changed This Period + +Use a compact table when possible: + +List the GP-reported figures first, citing a source for each where available, then the net figures; label each as gross or net. + +| Area | Current period | Prior period | Change | Source | +|---|---:|---:|---:|---| +| Gross MOIC / IRR | | | | | +| Cost | | | | | +| Realized value | | | | | +| Unrealized value (marks) | | | | | +| NAV | | | | | +| Unfunded | | | | | +| Contributions | | | | | +| Distributions | | | | | +| TVPI / DPI / RVPI / net IRR | | | | | + +Where the source materials support it, decompose the NAV change into a simple bridge — beginning NAV, plus calls, less distributions, plus or minus value change — and note any portion the materials do not separate, such as fee or financing effects. Request a GP-provided NAV bridge for the precise decomposition. + +Add short commentary only when supported by source material. + +## 3. Portfolio Review + +Cover the facts that matter for the meeting: + +- Top holdings and concentration +- New investments and exits +- Write-ups and write-downs +- Portfolio company KPI movements +- Sector, geography, or single-name exposure changes +- Items with stale or missing support + +## 4. Reporting Quality Notes + +Flag items that affect confidence in the review: + +- Missing explanations for material changes +- Inconsistent metric definitions +- Changed reporting format or valuation methodology +- Stale reported values +- Values that do not reconcile across materials + +Phrase these as review observations, not accusations. + +## 5. Recommended GP Questions + +Group questions by priority: + +### Priority 1 + +Questions that should be asked in the meeting because they affect valuation, liquidity, risk, re-up decisioning, or LP reporting. + +### Priority 2 + +Questions that can be handled as follow-up if meeting time is limited. + +### Optional + +Lower-priority questions, housekeeping items, and clarifications. + +## 6. Follow-Up Requests + +List materials or data to request from the GP: + +- Updated schedule of investments +- Support for valuation changes +- Portfolio company KPI detail +- Bridge from prior period to current period +- Explanation of cashflow activity +- Additional disclosure on watchlist companies + +## 7. Source Notes and Assumptions + +State: + +- Source artifacts used +- Documents not available +- Chronograph data coverage limitations +- User-provided assumptions +- Any estimated, incomplete, or unreconciled values diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/question-bank.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/question-bank.md new file mode 100644 index 0000000000000000000000000000000000000000..38e0591564494e135c108c28e1a67dd43fee8740 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/question-bank.md @@ -0,0 +1,75 @@ +# GP Meeting Question Bank + +Use this reference when a user asks for a fuller question list or when the reporting review surfaces issues across multiple areas. Select the questions that fit the facts; do not include a generic laundry list. + +## Performance + +- What were the main drivers of TVPI, DPI, RVPI, or IRR movement this period? +- How much of the performance movement came from realized activity versus unrealized marks? +- Which holdings contributed most to the change in value? +- Are any reported performance metrics preliminary or subject to revision? +- How should we interpret performance relative to the fund's age, strategy, and original underwriting? + +## Cashflows and Liquidity + +- What drove the period's capital calls? +- How much of the call activity related to new investments, follow-ons, fees, expenses, reserves, or recycling? +- What drove distributions this period? +- Were any distributions funded by realized exits, or by a NAV facility or subscription line rather than realized cash? +- How does the fund use fund-level leverage or subscription lines, and how is that usage capped? +- Are there expected near-term calls or distributions that LPs should plan around? +- Has the GP's view of reserve needs changed? + +## Valuation + +- What were the largest write-ups and write-downs this period? +- Were there any changes to valuation methodology, comparable sets, discount rates, or company forecasts? +- Has the basis for any marks shifted, for example from public-market comparables toward cost, and what prompted the change? +- Can the GP share its written valuation policy: committee composition, valuation frequency, third-party involvement, and write-down triggers? +- Which holdings have stale marks or limited recent operating support? +- Which marks are most sensitive to public market multiples, financing conditions, or company plan revisions? +- Are any valuations based on recent transactions, financing rounds, or third-party indications? + +## Portfolio Companies and KPIs + +- Which portfolio companies are most ahead of or behind plan? +- For companies with KPI deterioration, what actions is management taking? +- For companies with strong KPI improvement, how durable is the trend? +- Are margin, leverage, retention, bookings, or other operating metrics moving differently from revenue? +- Which companies may need additional capital? + +## Concentration and Risk + +- How concentrated is remaining value in the top holdings? +- Are any exposures materially affected by sector, geography, customer, supplier, or financing-market risk? +- Which companies are on the GP's internal watchlist? +- What are the main downside cases for the largest remaining holdings? +- Are there any covenant, liquidity, or refinancing risks? + +## Exits and Realizations + +- Which companies are expected to be exit candidates over the next 12-24 months? +- What exit paths are most likely: strategic sale, sponsor sale, IPO, dividend recap, or continuation vehicle? +- How has the GP's exit timing changed since the prior period? +- Are there market conditions delaying realizations? +- What portion of remaining value is expected to be realized in the near term? +- How is the GP pacing the conversion of unrealized value into realized distributions, and how does it weigh secondaries or continuation vehicles in that plan? + +## Reporting and Follow-Up + +- Can the GP provide a bridge from prior-period NAV to current-period NAV? +- Can the GP provide supporting detail for the largest valuation changes? +- Can the GP provide company-level KPI detail for top holdings or watchlist names? +- Are any metrics reported on a different basis than prior periods? +- Can the GP explain any values that do not reconcile across the reporting package? + +## Re-Up Context + +- How has the strategy changed from prior funds? +- How does the current portfolio support or challenge the case for re-up? +- What team, sourcing, underwriting, or portfolio construction changes should LPs understand? +- How much overlap should LPs expect between the existing portfolio and the next fund's strategy? +- What lessons from the current fund are being applied to the next fund? +- What is the firm's succession and key-person framework, and how concentrated is decision-making authority beneath the founders? +- How deep is the team below the senior partners, and what has changed in firm governance since the prior fund? +- How is carried interest crystallized, and does any carry pay out on unrealized gains before the performance picture is fully realized? diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/report-review-checklist.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/report-review-checklist.md new file mode 100644 index 0000000000000000000000000000000000000000..3366db48b2f8471b91adbc2611af9d4daabb95e8 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-gp-meeting-prep/references/report-review-checklist.md @@ -0,0 +1,56 @@ +# Report Review Checklist + +Use this checklist when reviewing a GP reporting package or Chronograph report-derived context for LP meeting prep. + +## Source Coverage + +- Identify which materials are available, whether from Chronograph or provided by the LP. +- When Chronograph document search is available, use it to review the captured reporting package, including the narrative and commentary it contains, not just the summary tables. +- Ask the LP to provide any document the meeting needs that isn't in the connected context. + +## Fund-Level Review + +- Confirm reporting period, as-of date, currency, and units. +- Lead with the GP-reported figures and cite their source document where available: gross IRR and MOIC, cost, realized value, and unrealized value, plus their movement versus the prior period. +- Review NAV, unfunded, contributions, distributions, and total exposure versus the prior period, and check TVPI, DPI, RVPI, and net IRR movement as the LP's bottom-line return. +- Distinguish gross from net throughout, and look for changes in recallable amounts and other cost or value items. +- Flag values that do not reconcile or appear to use different dates or definitions. + +## Cashflow Review + +- Identify large calls, distributions, or recallable distributions. +- Ask whether calls were for new investments, follow-ons, fees, expenses, or reserves if not explained. +- Ask what drove distributions: exits, partial sales, dividends, recapitalizations, or other activity. +- Distinguish distributions funded by realized exits from those financed by a NAV facility or subscription line. +- Compare cashflow timing to the fund's age, strategy, and prior deployment pace. + +## Valuation Review + +- Identify material write-ups and write-downs. +- Look for stale marks, large unchanged values, and methodology changes. +- Flag any shift in valuation basis, such as a move from market comparables toward cost, and ask what prompted it. +- Where marks drive the discussion, ask whether a written valuation policy with defined write-down triggers supports them. +- Check whether valuation changes are concentrated in a few holdings. +- Ask for support where valuation movement lacks KPI or transaction context. + +## Portfolio Review + +- Identify top holdings and concentration by company, sector, geography, and fund exposure where available. +- Review new investments, exits, partial realizations, and follow-on investments. +- Review company KPI profile changes: revenue, EBITDA, leverage, customer metrics, or other reported operating KPIs. +- Flag portfolio companies with worsening KPIs but unchanged or increasing marks. +- Flag positive KPI movement that is not reflected in valuation or manager commentary. + +## Reporting Quality Review + +- Note missing explanations for material performance, valuation, or cashflow movement. +- Note inconsistent metric names, definitions, periods, currency, or scale. +- Note changed reporting format or missing tables compared with prior periods. +- Note where the GP report gives conclusions without supporting detail. + +## Meeting Output + +- Lead with the highest-priority issues, not a full data dump. +- Convert gaps into specific GP questions. +- Separate urgent meeting questions from follow-up document requests. +- Include source notes so the LP can trace every quantitative point. diff --git a/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-portfolio-company-one-pager/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-portfolio-company-one-pager/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..f3c4ca10b8d2b8f5ebeafb6553923e596770d5b3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/chronograph-lp/skills/chronograph-portfolio-company-one-pager/SKILL.md @@ -0,0 +1,487 @@ +--- +name: chronograph-portfolio-company-one-pager +description: > + GP platform one-pager and investor report generator for private equity portfolio companies. + Use this skill whenever a user asks to generate a company tearsheet, one-pager, investor + report, portfolio overview, or company deep-dive — especially when they name a company or + ask to "build a report", "create a one-pager", or "show me a tearsheet". Also trigger when + the user asks to include commentary, quarterly updates, investment narratives, or any + Investment Overview in the report output. This skill handles live data fetching via a + connected MCP data source OR from an uploaded Excel model, metric formatting, AI-generated + or model-sourced commentary, and rendering a fully styled HTML one-pager. Also trigger for + LP quarterly updates, valuation summaries, and portco performance pages — any output that + combines financials, valuation, and return data for a single portfolio company. +--- + +# GP Report Builder + +Generates a fully styled, self-contained HTML investor report for a named portfolio company. +Supports two data source modes, two report types, and automatic brand detection from uploaded +templates. **Read this skill fully before writing a single line of HTML.** + +**Requirements:** A connected Chronograph MCP server. These workflows are designed for permissioned Chronograph users to connect to their private investment data, or an uploaded Excel model for Model mode. + +--- + +## Step 0 — Resolve Branding + +Brand tokens are resolved automatically — the user never fills in a config file manually. +Execute the following decision tree before any other step. + +### 0A — Check for an Uploaded Brand Template + +Look for any of the following in the current conversation: + +| File type | What to extract | +|---|---| +| **HTML / CSS file** | Parse all `color`, `background`, `font-family`, and `border` declarations. Identify the dominant background, primary accent, heading font, and body font. Extract any `--variable` tokens if a design system is present. | +| **PDF report or one-pager** | Visually analyse the document. Identify background color(s), the dominant accent/highlight color, heading and body typefaces, logo presence, and footer text. | +| **Image (PNG / JPG / SVG)** | Extract the 3–5 most visually prominent colors using the image content. Identify any visible text to infer font style (serif vs sans-serif, bold vs light). Note logo or wordmark if present. | +| **PowerPoint / PPTX** | Read slide backgrounds, title font, body font, accent colors from shapes and highlights. | +| **CSS / design token file** | Map token names to the brand token schema below directly. | + +Once extracted, map findings to the Brand Token Schema in **0C**. + +If the user has dropped **multiple** files, treat the most recent one as authoritative for +branding, unless the user specifies otherwise. + +### 0B — No Template Provided → Apply Chronograph Defaults + +If no brand template is present in the conversation, apply the following defaults silently — +do not ask the user to provide branding. + +``` +firm_name: Chronograph +website: www.chronograph.pe +confidentiality_label: CONFIDENTIAL + +colors: + bg_primary: #101C1D ← Near Black 1 (page background) + bg_secondary: #1A2627 ← Near Black 2 (card / panel background) + bg_header: #1B4147 ← Deep Teal (header strip) + accent_primary: #57E5EE ← Bright Teal (headlines, KPI values, eyebrows) + accent_secondary: #11A8B2 ← Regular Teal (bars, borders, left-rule accents) + accent_negative: #F95532 ← Accent Red (EBITDA bars, negative deltas) + accent_positive: #4ecb8a ← Green (positive deltas) + text_primary: #FFFFFF ← White (body text) + text_muted: #D9E8E8 ← Light teal tint (footnotes, commentary) + table_header_bg: #1B4147 ← Deep Teal (table header row) + +fonts: + heading: Ubuntu + heading_weight: 700 + body: Open Sans + body_weight: 300 + google_fonts_url: https://fonts.googleapis.com/css2?family=Ubuntu:wght@700&family=Open+Sans:wght@300;300i&display=swap + +logo: + url: (none — render firm name as text) + position: top-left + +theme: dark +``` + +### 0C — Brand Token Schema + +Whether tokens are extracted from a template (0A) or defaults are applied (0B), resolve all +of the following before proceeding. Every downstream panel references these names. + +| Token | Role | Fallback if undetectable | +|---|---|---| +| `firm_name` | Firm name in header and footer | Infer from logo text or filename; else `"Your Firm"` | +| `website` | Footer URL | `""` (omit from footer) | +| `confidentiality_label` | Footer suffix | `"CONFIDENTIAL"` | +| `bg_primary` | Page / root background | Chronograph default | +| `bg_secondary` | Card / panel background | Darken `bg_primary` by 5% | +| `bg_header` | Header strip background | Darken `bg_primary` by 15% | +| `accent_primary` | Headlines, KPI values, eyebrow labels | Dominant bright color from template | +| `accent_secondary` | Bars, borders, left-rule accents | Mute `accent_primary` by 30% | +| `accent_negative` | Negative values, downward deltas | `#F95532` | +| `accent_positive` | Positive deltas | `#4ecb8a` | +| `text_primary` | Main body text | `#FFFFFF` on dark; `#1A1A1A` on light | +| `text_muted` | Footnotes, commentary | Tint `text_primary` toward `bg_primary` by 20% | +| `table_header_bg` | Table header row | `bg_header` | +| `font_heading` | Heading / KPI / eyebrow font | Detected from template; else `Ubuntu` | +| `font_heading_weight` | Heading weight | `700` | +| `font_body` | Body / table / footnote font | Detected from template; else `Open Sans` | +| `font_body_weight` | Body weight | `300` | +| `google_fonts_url` | Font load URL | Build from detected font names | +| `logo_url` | Logo image src | `""` — fall back to firm name as text | +| `logo_position` | Header logo placement | `top-left` | +| `theme` | `dark` or `light` | `dark` if `bg_primary` luminance < 0.2; else `light` | + +### 0D — Theme Handling + +**Dark theme** (luminance of `bg_primary` < 0.2): +Use the token values as resolved. Default contrast pairings apply (white text on dark +backgrounds). Minimum contrast ratio: 4.5:1 for body text, 3:1 for large text (≥ 18px bold). + +**Light theme** (luminance of `bg_primary` ≥ 0.2): +- Swap `text_primary` to a near-black (e.g. `#1A1A1A`) if not already dark +- Ensure `accent_primary` provides ≥ 3:1 contrast against `bg_primary` +- Table header: use the firm's dark brand color (e.g. deep navy / dark green) rather than + a light value + +### 0E — Confirm with the User (optional, brief) + +After resolving tokens, output a **single short line** — not a table, not a list — before +generating the report: + +> *"Using [firm_name] branding — [accent_primary] accent on [bg_primary] background, +> [font_heading] / [font_body] fonts."* + +If brand detection produced low-confidence results (e.g. only a logo image was provided with +no color context), ask one focused question: + +> *"I've picked up [X] and [Y] from your file — is that the right color scheme, +> or would you like to adjust anything?"* + +Do not ask if defaults were applied — just proceed. + +--- + +## Step 1 — Determine Report Mode + +**Data source mode:** + +| Signal | Mode | +|---|---| +| User uploads an Excel model (.xlsx) or references an uploaded file | **Model mode** — read data from the file | +| No file uploaded; company exists in the connected data platform | **MCP mode** — fetch live from the platform | +| Both available | Prefer the model for financials and commentary; use MCP to supplement metadata and returns | + +**Report type:** + +| User asks for… | Report type | +|---|---| +| One-pager, tearsheet, company report, GP report | **GP One-Pager** | +| LP update, quarterly update, LP quarterly report | **LP Quarterly Update** | + +If unclear, default to **GP One-Pager**. + +--- + +## Step 2 — Resolve the Company & Fetch Data + +### MCP Mode + +All data is fetched from the user's connected **Chronograph MCP server**. The agent must have the Chronograph MCP connected before running the skill in MCP mode; if it isn't connected, prompt the user to connect it, or fall back to Model mode if a file is available. + +Inspect the connected Chronograph MCP's tool list at runtime and pick the appropriate tool for each step below based on the tool descriptions the server provides. Do not hard-code tool names — read the live descriptions to stay current. + +### Fetch sequence + +Work through these steps in order. At each step, identify the right Chronograph tool from its description, call it to fetch what the report needs, and hold the result for the rendering steps that follow. The skill does not need a fixed schema — only the values listed below in plain language. + +**1. Resolve the company.** Find the tool that searches for companies, funds, and other portfolio entities by name. Use it to turn the user's input into a canonical company. If multiple candidates come back, prefer the closest name match; ask the user only if genuinely ambiguous. + +**2. Get the company's basic facts.** Use the tool that retrieves core portfolio entity records. Fetch what the **Header Strip** (Step 4) needs: company name, sector, industry, geography, HQ, and the company's reporting currency. Request only what the header renders — the tool's description will list what's available. + +**3. Get the company's investments.** Using the same core-entity retrieval tool, fetch the list of investments associated with the company. The **Investment Returns Table** (Step 4) needs one row per investment: investment name, the fund it belongs to, entry date, exit date if applicable, and whether it has exited. + +**4. Get the company's financial line items.** Find the tool for company-level financial metrics. Make a discovery / help call first, passing the company ID, to see what's available. + +**Metric selection rule.** Always query by the platform's metric type when one is available for the line item — even if the company's display label differs. Use a company-specific mapped metric definition only when no metric type covers the line item or the request is inherently tenant-specific (bespoke KPIs, commentary fields, operating metrics, custom valuation inputs). + +Priority: + +1. Platform metric type +2. Company-specific mapped metric definition (only if no metric type exists) +3. Name-based metric search (only if neither of the above resolves) + +Do not pick a company-specific metric because its label is a closer word match than an available metric type. Metric types drive querying; display labels drive presentation. + +What the report needs (query via the metric type whenever available): + +- **Financial Performance Table:** Revenue, Gross Profit, EBITDA, the company's adjusted EBITDA series, and Net Debt. Pull the last 4–5 trailing-twelve-month periods plus the most recent quarter. +- **Valuation Summary Table:** Enterprise Value, valuation multiple, Total Debt, Cash, Net Debt, Equity Value — current quarter and prior quarter. +- **KPI Strip:** the latest values for LTM Revenue, LTM Adj. EBITDA, Enterprise Value, and Net Debt. + +Use LTM for income-statement items, As-of for balance items. The discovery response will tell you which period types are supported per metric. + +**5. Get per-investment returns.** Find the tool for investment-level performance. It uses gross performance figures (not net — net lives elsewhere on the platform and is the wrong tool for the GP one-pager). The **Investment Returns Table** needs, per investment: invested capital, realized proceeds, unrealized value, MOIC, and IRR. Sum across investments to populate the MOIC card in the **KPI Strip**. + +**6. Resolve any non-standard metrics by name.** If the user asks the report to include a tenant-specific KPI that isn't part of the platform's standard metric set — e.g. a custom operating metric — use the metric-name search tool to resolve it to an ID before querying the company-metrics tool. + +### Currency + +Use the company's reporting currency as returned in step 2. **Do not default to USD.** If the user explicitly asks for a different currency, pass that through to each tool call. + +### If something is missing + +- Company not found → ask the user to confirm spelling; try the legal name. +- A metric returns no value → display `—`. Never fabricate. +- A tool returns a schema or help error → comply with the introspection call it asks for and retry. +- Chronograph MCP not connected → prompt the user to connect it, or fall back to Model mode. + +### Model Mode + +Read the uploaded Excel file using pandas (`data_only=True`). Extract from: + +| Tab | Data to extract | +|---|---| +| `Overview` | Company name, HQ, fiscal year end, fund name(s), investment names, entry dates, ownership % | +| `Performance` | Revenue, Gross Profit, EBITDA, Adj. EBITDA (Reported and Valuation basis), Net Debt — last 4–5 LTM periods | +| `Valuation` | EV, valuation multiple, equity value, net debt — current and prior quarter; commentary text (Business Update, Rationale for Conclusion, Rationale for Discount); per-investment cost, realized, unrealized, MOIC | + +**Currency and scale:** Check the `Figures In` field on the Overview tab. If `1000` +(thousands), divide all financial values by 1,000 before displaying in millions. Note the +`Local Currency` field and include it in the report header. + +**If commentary is present in the model**, use it verbatim (lightly edited for grammar only). + +--- + +## Step 3 — Layout Structure + +Both report types share the same structural template. The Financial Performance table must +always be **directly above** the Valuation Summary table in the same column. + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ HEADER — Logo · Company · Fund · Sector · HQ · Report date │ +│ Tag pills: sector, geography, fund, status │ +├─────────────────────────────────────────────────────────────────┤ +│ KPI STRIP (5 cards, full width) │ +│ LTM Revenue | LTM EBITDA | Enterprise Value | Net Debt | MOIC │ +├───────────────────────────┬─────────────────────────────────────┤ +│ LEFT COLUMN │ RIGHT COLUMN │ +│ │ │ +│ Financial Performance │ Revenue & EBITDA Bar Chart │ +│ Table │ (last 4 LTM periods, SVG inline) │ +│ │ │ +│ Valuation Summary │ Investment Returns Table │ +│ Table ← must stay here │ │ +│ │ │ +├───────────────────────────┴─────────────────────────────────────┤ +│ COMMENTARY (full width, up to 3 columns) │ +│ Business Update | Valuation Rationale | Discount Rationale │ +├─────────────────────────────────────────────────────────────────┤ +│ FOOTER — © {firm_name} | {website} | {confidentiality_label} │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Step 4 — Panel Specifications + +### Header Strip + +- Background: `bg_header` → `bg_primary` gradient, 135° +- **Logo:** if `logo_url` is set, render `` at `logo_position`; + maintain clearspace equal to the cap-height of the firm name on all sides +- **Logo fallback:** if `logo_url` is blank, render firm name in `font_heading`, + `font_heading_weight`, 24px, `text_primary` +- Company name: `font_heading`, 28px, `accent_primary` +- Subtitle (fund · sector · HQ · date): `font_body`, 12px, `text_muted` +- Tag pills: `bg_secondary` fill, `accent_secondary` border, `font_body` 10px + +### KPI Strip (5 cards) + +| Card | Value | +|---|---| +| LTM Revenue | Current period revenue | +| LTM Adj. EBITDA | Valuation basis if available, else Reported | +| Enterprise Value | Current quarter EV | +| Net Debt | Current quarter net debt | +| Gross MOIC | Blended or primary investment MOIC | + +- Card: `bg_secondary` background, 6px border-radius, `box-shadow: 0 2px 8px rgba(0,0,0,0.4)` +- Value: `font_heading`, 28px, `accent_primary` +- Label: `font_body`, 9px, uppercase, letter-spacing 0.05em, `text_primary` +- Delta: `▲ +X%` in `accent_positive` · `▼ -X%` in `accent_negative` + +### Financial Performance Table (LEFT column, top) + +Rows (LTM, 3 prior periods + current quarter, vs. PY column): + +| Row | Notes | +|---|---| +| Revenue | | +| Gross Profit | | +| Gross Margin % | | +| EBITDA | | +| EBITDA Margin % | | +| **Adj. EBITDA (Valuation)** | Highlight row — `font_heading`, `accent_primary` value | +| **Adj. EBITDA Margin %** | Highlight row | +| Net Debt | | + +- Header row: `table_header_bg`, `font_body` 9px uppercase, `text_primary` +- Alternating rows: `bg_secondary` / `bg_primary` +- Highlight rows: `rgba({accent_primary}, 0.06)` background +- Numeric columns right-aligned; label column left-aligned + +### Valuation Summary Table (LEFT column, directly below Financial Performance) + +| Row | Notes | +|---|---| +| Valuation Multiple | `X.Xx` | +| Adj. EBITDA (LTM) | currency | +| **Enterprise Value** | Highlight row | +| Total Debt | | +| Cash | | +| Net Debt | | +| **Total Equity Value** | Highlight row | + +Prior Quarter vs Current Quarter, plus a delta column (`accent_positive` / `accent_negative`). + +### Revenue & EBITDA Bar Chart (RIGHT column, top) + +- **Inline SVG only** — no external JS or D3 +- Side-by-side bars: Revenue in `accent_secondary`, Adj. EBITDA in `accent_negative` +- Current quarter Revenue bar: `accent_primary` +- 4 LTM periods on x-axis; `$Xm` labels above each bar +- Current quarter label: `font_heading`, `accent_primary`; prior: `font_body`, `text_muted` +- Y-axis gridlines: dashed, `rgba({accent_primary}, 0.08)` +- Legend: colour swatches + labels, `font_body` 9px +- Auto-scale: y-axis max = largest revenue × 1.2; bar heights proportional + +### Investment Returns Table (RIGHT column, bottom) + +| Column | Format | +|---|---| +| Investment name | Left-aligned | +| Entry date | `Mon YYYY` | +| Ownership % | `X.X%` | +| Cost (Gross) | `$Xm` | +| Realized | `$Xm` | +| Unrealized | `$Xm` | +| MOIC (Gross) | `X.XXx` — `font_heading`, `accent_primary` | + +- Sort: largest cost first +- **Total / Blended** row at bottom in `font_heading` +- Add IRR column if available; omit column if all values null +- Unavailable values: `—` +- One-sentence QoQ note below table: `font_body` 9.5px, `text_muted` + +### Commentary Section (full width, up to 3 columns) + +1. **Business Update** — verbatim from model if present; AI-generated in MCP mode +2. **Rationale for Valuation Conclusion** — verbatim from model if present +3. **Rationale for Discount to Comps** — verbatim from model if present + +- Eyebrow label: `accent_primary`, 9px, uppercase, letter-spacing 0.08em, + 1px bottom border in `accent_primary` +- Body: `font_body`, 11px, `text_muted`, line-height 1.6 +- Collapse empty columns — never show a blank block + +--- + +## Step 5 — LP Quarterly Update Additions + +When report type is **LP Quarterly Update**: + +1. Header eyebrow → `LP QUARTERLY UPDATE · Q[N] YYYY` +2. Commentary must come from model verbatim — never AI-generate for LP reports +3. Add an optional **valuation bridge note** below the Valuation Summary table: + *"EV increase driven by multiple expansion from X.Xx to Y.Yx; EBITDA contribution +$Zm"* + +--- + +## Step 6 — CSS Variables & Font Loading + +Populate these from the resolved brand tokens (Step 0). Set once in ` +``` + +--- + +## Step 7 — Formatting Rules + +| Type | Format | +|---|---| +| Currency (millions) | `$43.5m` | +| Negative / net cash | `($3.4m)` in `var(--accent-negative)` | +| Multiples | `1.41x` | +| Percentages | `15.7%` | +| Basis point changes | `+70bps` | +| Dates | `Q4 2024` or `31 Dec 2024` | +| MOIC | `4.97x` — heading font, `var(--accent-primary)` | +| Positive delta | `▲ +X%` — `var(--accent-positive)` | +| Negative delta | `▼ -X%` — `var(--accent-negative)` | +| Unavailable | `—` (em dash) — never fabricate | + +--- + +## Step 8 — Output + +- **File name:** `[company_name_lowercase_underscored]_[report_type]_[quarter].html` + - Examples: `ashworth_health_gp_report.html` · `ashworth_health_lp_update_q4_2024.html` +- **Single self-contained HTML file** — all CSS in ` + + +
+
+
+
+
+ +
Earnings Call
Transcripts Summary
+
Companies covered
+
+
+
+ Date: + Companies: + Type: Earnings Call Summary +
+
+
+
+
+
+
+
+
+
+
+
Contents
+ +
+
+
+
Section 1. Executive Summary
+
+
+
+
+
Section 2. Overall Credit Consideration
+
+
+
+
+
+
+
+
Section 3. Revenue YOY Trend
+ + + +
Company NameYOY ChangeCommentary
+
+
+
+
Section 4. Volumes YOY Trend
+ + + +
Company NameYOY ChangeCommentary
+
+
+
+
Section 5. Selling Price Trend
+ + + +
Company NameYOY ChangeCommentary
+
+
+
+
Section 6. Qualitative / Broad Industry Commentary on Revenue, Volumes & Pricing
+
+
+
+
+
Section 7. End Market Conditions
+
+
+
+
+
Section 8. Supply Chain Conditions
+
+
+
+
+
Section 9. Business Conditions by Geography
+
+
+
+
+
Section 10. Next Quarter & Full Year Business Outlook / Guidance
+
+
+
+
+
Section 11. Earnings Revisions for Applicable Companies
+
+
+
+
+
Section 12. Corporate Events (M&A, Restructurings, Plant Closures, Force Majeures, etc.)
+
+
+
+
+
Citations
+
+
+
+ +
+ + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-earnings-brief/evals/evals.json b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-earnings-brief/evals/evals.json new file mode 100644 index 0000000000000000000000000000000000000000..2c087deca594d2511417aa8cbc57c8aba7715c14 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-earnings-brief/evals/evals.json @@ -0,0 +1,62 @@ +{ + "skill_name": "earnings-brief", + "evals": [ + { + "id": 1, + "prompt": "Generate an earnings call summary for Apple, Microsoft, and Alphabet", + "expected_output": "eval-1", + "assertions": [ + "Output is a complete standalone HTML document (doctype + )", + "Report uses the skill's template scaffold (ecs-* element IDs present)", + "All 20 core template placeholders populated with non-empty content", + "Company chips count matches expected (3)", + "ecs-tbody-ratings has 3 rows (one per company)", + "ecs-tbody-revenue has 3 rows (one per company)", + "ecs-tbody-volumes has 3 rows (one per company)", + "ecs-tbody-prices has 3 rows (one per company)", + "Credit sentiment badge has a positive/negative/neutral modifier class", + "Report uses subheaders (>=12 across sections)", + "Citations block contains >= 3 source-item entries (canonical markup per skills/shared/citations/SKILL.md)" + ], + "files": [] + }, + { + "id": 2, + "prompt": "Summarize the latest earnings calls for Ford and General Motors", + "expected_output": "eval-2", + "assertions": [ + "Output is a complete standalone HTML document (doctype + )", + "Report uses the skill's template scaffold (ecs-* element IDs present)", + "All 20 core template placeholders populated with non-empty content", + "Company chips count matches expected (2)", + "ecs-tbody-ratings has 2 rows (one per company)", + "ecs-tbody-revenue has 2 rows (one per company)", + "ecs-tbody-volumes has 2 rows (one per company)", + "ecs-tbody-prices has 2 rows (one per company)", + "Credit sentiment badge has a positive/negative/neutral modifier class", + "Report uses subheaders (>=12 across sections)", + "Citations block contains >= 3 source-item entries (canonical markup per skills/shared/citations/SKILL.md)" + ], + "files": [] + }, + { + "id": 3, + "prompt": "Create an earnings call report covering JPMorgan Chase, Bank of America, and Wells Fargo", + "expected_output": "eval-3", + "assertions": [ + "Output is a complete standalone HTML document (doctype + )", + "Report uses the skill's template scaffold (ecs-* element IDs present)", + "All 20 core template placeholders populated with non-empty content", + "Company chips count matches expected (3)", + "ecs-tbody-ratings has 3 rows (one per company)", + "ecs-tbody-revenue has 3 rows (one per company)", + "ecs-tbody-volumes has 3 rows (one per company)", + "ecs-tbody-prices has 3 rows (one per company)", + "Credit sentiment badge has a positive/negative/neutral modifier class", + "Report uses subheaders (>=12 across sections)", + "Citations block contains >= 3 source-item entries (canonical markup per skills/shared/citations/SKILL.md)" + ], + "files": [] + } + ] +} \ No newline at end of file diff --git a/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-explore-mcp/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-explore-mcp/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..a28d653f8405c5ea511d6b98266e671bb1c429a2 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-explore-mcp/SKILL.md @@ -0,0 +1,80 @@ +--- +name: moody-s-explore-mcp +description: Discover and safely explore Moody's MCP tools. Use when the user wants to see what Moody's data is available, verify MCP connectivity, look up an entity, or run a lightweight ratings/research probe before deeper analysis. +--- + + + +# Explore Moody's MCP + +Use this skill to discover Moody's MCP capabilities and run a minimal, read-only probe before deeper credit and financial analysis workflows. + +## When to Use + +- User asks "what can Moody's do?", "list Moody's tools", or "is Moody's connected?" +- User wants a quick entity lookup or ratings snapshot without a full credit memo +- You need to verify which Moody's tools are available in the current session + +## Prerequisites + +- Moody's plugin installed with the enterprise store MCP linked via `.app.json` +- OAuth completed on first use - auth errors mean the user should reconnect the Moody's integration + +## Workflow + +### Step 1: Verify MCP Availability + +Confirm Moody's MCP tools appear in the session. If tools are missing or calls fail with auth errors, stop and ask the user to install or re-authenticate the Moody's plugin. + +### Step 2: Discover Tools + +List available Moody's MCP tools. **Read each tool's schema before calling** - tool names and parameters may differ from the reference list below. + +If tools appear as deferred, batch-load schemas in a single discovery pass rather than calling tools blindly. + +### Step 3: Smoke Test - Entity Lookup + +Run `findEntity` (or the equivalent entity-search tool) with a company name or identifier the user provides. If no company was given, ask for one before proceeding. + +Present matches clearly and confirm which entity to use. **Never invent entity IDs** - always resolve through entity search first. + +### Step 4: Light Probe (Optional) + +After confirming an entity, call one read-only tool to demonstrate connectivity: + +- `getEntityRatings` - current rating, outlook, and recent history +- `searchEntityDocuments` - recent research documents for the entity +- `getEntityPeers` - comparable entities for context + +Pick the tool that best matches the user's question. Read the schema, call once, and summarize results. + +### Step 5: Summarize + +Report: + +1. Which tools are available in this session +2. The entity resolved (name + ID) +3. What data was retrieved in the probe +4. Suggested next steps (e.g. full ratings history, peer comparison, document deep-dive) + +## Known Tools (Reference - Verify Live Schemas) + +| Tool | Purpose | +| ------------------------ | ------------------------------------------------ | +| `findEntity` | Search entities by name, identifier, or metadata | +| `getEntityRatings` | Current ratings, outlooks, and rating history | +| `getEntityPeers` | Comparable peer entities | +| `searchEntityDocuments` | Search Moody's research document library | +| `getEntityScorecard` | Rating scorecard metrics and methodology inputs | +| `getEntityRatingDrivers` | Upgrade and downgrade factor analysis | +| `getEntityEsg` | ESG factors affecting credit quality | + +Tool names above are reference only. Always confirm against live MCP tool descriptors before calling. + +## Guardrails + +- Read tool schemas before every call +- Do not invent entity IDs - always resolve via entity search first +- Cite Moody's as the data source +- This skill provides research context, not investment advice +- On empty or error responses, report clearly and stop - do not retry blindly or fabricate data diff --git a/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-explore-mcp/agents/openai.yaml b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-explore-mcp/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..195abadbc2c323e452aca85308bf25299bbfccc3 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-explore-mcp/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Moody's MCP Explorer" + short_description: "Discover Moody's MCP tools and run safe read-only entity probes" + default_prompt: "Use Moody's MCP Explorer to verify available tools, resolve an entity, and run a lightweight cited Moody's data probe." diff --git a/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-issuer-brief/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-issuer-brief/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..2e37ad8b608525fd9418b9b227d3ae26b22ee57d --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-issuer-brief/SKILL.md @@ -0,0 +1,673 @@ +--- +name: moody-s-issuer-brief +description: > + Produce a comprehensive Issuer Brief HTML report for a company using Moody's + GenAI MCP tools. Use this skill whenever the user asks to create an Issuer Brief, + company profile report, credit memo, investment book, or comprehensive company analysis. Also + trigger when they ask for a report combining company overview, financials, peer comparison, + industry overview, strategic developments, management, credit profile, risks, and ESG into a + single document. Trigger even if they just name a company and say "Issuer Brief", "info book", "company + book", "credit book", or "full company report". +--- + +# Issuer Brief Skill + +Generates a professional HTML report (styled like a Moody's Issuer Brief) for a +target company. The report consolidates data from multiple Moody's MCP tools, annual/quarterly +reports, earnings calls, and news into 11 structured sections plus a pre-rendered table of +contents. Section 4 is titled "Company Metrics" (formerly "Share Price Performance and Valuation"). + +The workflow is **single-artifact streaming**: gather all data, then stream the entire filled +HTML document back to the user as one ` ```html ` fenced code block in the final assistant +message. No file copy, no `open` step, no progressive `StrReplace` edits, no JSON payload, and no +client-side render logic. The fenced code block is the deliverable. + +> ## ⚠️ CRITICAL — NON-NEGOTIABLE OUTPUT CONTRACT +> +> **The LLM MUST stream the final report back as a single HTML artifact inside the assistant +> response.** This is the only acceptable form of delivery for this skill. Specifically: +> +> - The final assistant message **MUST** contain exactly one ` ```html ` fenced code block +> holding the **complete, standalone HTML document** (`` → ``), with +> every section from the streaming protocol populated inline. +> - The LLM **MUST NOT** write the report to a file on disk (no `Write`, no `cp` of the +> template, no `StrReplace` into a working artifact, no `open` command). +> - The LLM **MUST NOT** split the report across multiple code blocks, multiple messages, +> partial snippets, or summaries. +> - The LLM **MUST NOT** substitute prose, Markdown, JSON, attachments, or links for the +> fenced HTML artifact. The artifact itself is the answer. +> - If data gathering fails partially, still emit the single ` ```html ` artifact with +> the best-available content and `"--"` placeholders for missing cells — never skip the +> artifact. +> +> Treat any other output shape as a hard failure of the skill. + +> ## ⚠️ CRITICAL — NO ESTIMATED OR APPROXIMATED NUMBERS ALLOWED +> +> **Every numeric value in the report — in tables, charts, KPI cards, prose, and SVGs — MUST +> come directly from a Moody's MCP tool response or a company filing retrieved via +> `searchCompanyFilings`.** Estimation, approximation, interpolation, and inference from +> indirect sources are strictly forbidden. Specifically: +> +> - **NEVER** write `~`, `approx.`, `estimated`, or any similar qualifier next to a number. +> If the exact figure is unavailable from the data gathered, use `"--"` instead. +> - **NEVER** derive a number by splitting, distributing, or back-calculating from an aggregate +> (e.g. do not allocate total debt across maturity buckets by assumption). +> - **NEVER** invent segment revenue, EPS, FCF, ROE, debt maturity amounts, or any other +> metric that was not explicitly returned by a tool call. +> - **Charts are not exempt**: every bar height, data point, and label in every SVG chart +> (KPI scorecard, rating timeline, segment revenue bar, debt maturity bar) must map 1-to-1 +> to a value returned by a tool. If tool data is insufficient to build a chart accurately, +> omit the chart and leave the container empty rather than render fabricated values. +> - **Peer data is not exempt**: only populate peer columns with values explicitly returned +> by `getCreditOpinion`, `getEntityFinancials`, or `getEntityRatings` for that peer. +> +> Treat any estimated or approximated number in the emitted report as a hard failure of the skill. + +## Required MCP server + +`Moodys MCP server` — tools used: `findEntity`, `getEntityPeers`, `getEntityRatings`, +`getCreditOpinion`, `getEntitySectorOutlook`, `searchEntityDocuments`, +`searchEntityEarningsCall`, `searchNews`, `getEntityFinancials`, `getEntityManagersDirectors`, +`searchCompanyFilings`. + +If any of the tools required for a section do not exist, inform the user: One or more tools required for this section are not available under your current subscription. Unlock more of the expert insights, data, and analytics you trust. Get Link:https://www.moodys.com/web/en/us/capabilities/gen-ai/ai-ready-data.html with us to learn more. + +> ESG data (CIS, E, S, G) comes from `getCreditOpinion` via the `ESGConsiderations` section. + +## Bundled files + +- `assets/template.html` — self-contained static report shell: CSS, layout, a hardcoded 11-entry + table of contents, pre-shaped tables (financial / 5 valuation / key-indicators / ESG-score) + with cell-level IDs, and empty targets (containers, ``, `
    `, `
    `) for variable + content. Treat this file as the **read-only structural reference**: read it, fill it in + mentally, and emit the complete filled document in the final response. + +## Template (shared) + +Before emitting the HTML report, **read both**: +1. [`skills/shared/template/SKILL.md`](../shared/template/SKILL.md) — authoring rules (which + classes / snippets are owned by the shared layer, allowed per-skill overrides, outlook-badge + usage). +2. [`skills/shared/template/assets/template.html`](../shared/template/assets/template.html) — + canonical CSS (inside ` + + +
    +
    +
    + +
    Issuer Brief
    +
    +
    + Company: + Date: + Type: Issuer Brief +
    +
    + +
    + +
    +
    1. Company Overview
    +
    +
    +
    + +
    +
    2. Business Segments and Operations
    +
    +
    +
      +
      +
      +
      +
      + +
      +
      3. Historical Financials
      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Financial Items (in millions)
      Revenues (net sales)
      Gross profit
      SG&A
      Operating expenses
      Net income
      EBITDA
      FCF
      CAPEX
      Share repurchased
      Dividends
      Cash Flow from operations
      Taxes paid
      Cash & Equivalents
      Total debt
      Net debt
      Total Debt/EBITDA
      Net Debt/EBITDA
      ROE
      EPS
      +Financial Summary +
      +Recent Earnings Call Highlights +
      +Historical Financial Analysis +
      +
      +
      +
      + +
      +
      4. Share Price Performance and Valuation
      +
      +Monthly Share Price +
      +
      +Peer Share Price Comparison +
      +
      +Valuation Analysis + +Market & Price Data + + + + + + + + +
      Line item
      Market Capitalization / Sales
      Market Capitalization / EBITDA
      Debt / Market Capitalization
      Market Capitalization / Book Value
      +
      + +Profitability Metrics + + + + + + + + + + + + +
      Line item
      Revenue
      EBITDA
      EBITDA Margin
      EBIT Margin
      Net Income
      ROE
      ROA
      Operating Margin
      +
      + +Leverage & Coverage + + + + + + + + +
      Line item
      Debt / EBITDA
      Total Debt
      Interest Coverage
      FCF / Debt
      +
      + +Cash Flow & Efficiency + + + + + + +
      Line item
      Free Cash Flow
      CAPEX / Revenue
      +
      + +Earnings & Shareholder Returns + + + + + + + +
      Line item
      Basic EPS
      Diluted EPS
      Dividends as % of NPATBUI
      +
      +
      +
      +
      + +
      +
      5. Peer Comparison and Competitive Landscape
      +
      +
      +Peers + + +
      NameDescription
      +Peers Rating + + +
      CompanyRatingOutlook
      +Quantitative Comparison (Key Indicators) + + + + + + + + + + + + +
      Account Name
      Revenue
      EBITDA
      EBITDA Margin
      Debt / EBITDA
      Interest Coverage
      Total Debt
      Net Debt
      Free Cash Flow
      +Conclusion +
      +
      +
      +
      + +
      +
      6. Industry Overview and Trends
      +
      +
      +
      + +
      +
      7. Strategic Developments
      +
      +
        +
        +
        +
        + +
        +
        8. Management and Governance
        +
        +
        +
        + +
        +
        9. Credit Profile
        +
        +
        +
        + + +
        Rating ClassAssigned RatingAssigned OutlookRating Action Date
        +
        +
        +
        + +
        +
        10. Risks and Challenges
        +
        +
        + + +
        Risk CategoryDescriptionPotential ImpactMitigation Strategy
        +
        +
        +
        + +
        +
        11. ESG Profile
        +
        +
        +ESG Performance Summary + + + + + + + +
        CategoryKey Focus AreasMoody's ESG Score
        Environmental
        Social
        Governance
        +
        +
        +
        + +
        +
        Citations
        +
        +
        +
        + +
        + + diff --git a/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-issuer-brief/evals/evals.json b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-issuer-brief/evals/evals.json new file mode 100644 index 0000000000000000000000000000000000000000..7870f2795468401bde924ace5076348db63e556a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-issuer-brief/evals/evals.json @@ -0,0 +1,71 @@ +{ + "skill_name": "issuer-brief", + "evals": [ + { + "id": 1, + "prompt": "Create an Issuer Brief for Apple Inc.", + "expected_output": "Single fenced ```html code block containing a complete standalone HTML document built from the Issuer Brief template. Target = Apple Inc. with 3 credit peers from getEntityPeers, all 27 pib-* placeholders populated, 19x8 financial table mostly filled (with '--' allowed), 5 valuation tables, peers/rating/KI tables, strategy and segments lists, risk + rating + ESG tables, monthly price and debt-maturity SVG charts, and a populated sources list.", + "files": [], + "assertions": [ + "Output is a complete standalone HTML document (doctype + )", + "Report uses the skill's template scaffold (core pib-* table IDs present)", + "All 27 core pib-* placeholders defined in the document", + "6 narrative sections (overview, industry, mgmt, credit, risks, esg) all populated", + "Financial table >= 100/152 cells populated (19 rows x 8 year cols, allowing '--' placeholders)", + "Peers comparison table has >= 3 rows", + "Peers rating table has >= 3 rows", + "Rating history table has >= 1 row", + "Risk table has >= 3 rows", + "Strategy list (#pib-strategy-list) has >= 3
      • entries", + "Segments list (#pib-segments-list) has >= 2
      • entries", + "Share price monthly chart and credit chart both contain ", + "ESG table (E/S/G) all 3 rows populated (focus + score)", + "Sources section contains >= 5 entries" + ] + }, + { + "id": 2, + "prompt": "I need a full company report for Tesla Inc. \u2014 an Issuer Brief covering everything from financials to ESG", + "expected_output": "Single fenced ```html code block with the full Issuer Brief HTML for Tesla + 3 peers. Same structural requirements as eval-1 (all 27 pib-* placeholders, 5 valuation tables, peers/rating/KI tables, monthly + credit SVGs, E/S/G scores, and >= 5 sources), tested via a natural-language phrasing.", + "files": [], + "assertions": [ + "Output is a complete standalone HTML document (doctype + )", + "Report uses the skill's template scaffold (core pib-* table IDs present)", + "All 27 core pib-* placeholders defined in the document", + "6 narrative sections (overview, industry, mgmt, credit, risks, esg) all populated", + "Financial table >= 100/152 cells populated (19 rows x 8 year cols, allowing '--' placeholders)", + "Peers comparison table has >= 3
        rows", + "Peers rating table has >= 3
        rows", + "Rating history table has >= 1
        row", + "Risk table has >= 3
        rows", + "Strategy list (#pib-strategy-list) has >= 3
      • entries", + "Segments list (#pib-segments-list) has >= 2
      • entries", + "Share price monthly chart and credit chart both contain ", + "ESG table (E/S/G) all 3 rows populated (focus + score)", + "Sources section contains >= 5 entries" + ] + }, + { + "id": 3, + "prompt": "Generate an Issuer Brief for The Walt Disney Company in USD", + "expected_output": "Single fenced ```html code block with the full Issuer Brief HTML for Disney + 3 peers in USD. Tests currency parameter handling plus structural compliance (all 27 pib-* placeholders, financials, peers, credit, ESG, sources).", + "files": [], + "assertions": [ + "Output is a complete standalone HTML document (doctype + )", + "Report uses the skill's template scaffold (core pib-* table IDs present)", + "All 27 core pib-* placeholders defined in the document", + "6 narrative sections (overview, industry, mgmt, credit, risks, esg) all populated", + "Financial table >= 100/152 cells populated (19 rows x 8 year cols, allowing '--' placeholders)", + "Peers comparison table has >= 3
        rows", + "Peers rating table has >= 3
        rows", + "Rating history table has >= 1
        row", + "Risk table has >= 3
        rows", + "Strategy list (#pib-strategy-list) has >= 3
      • entries", + "Segments list (#pib-segments-list) has >= 2
      • entries", + "Share price monthly chart and credit chart both contain ", + "ESG table (E/S/G) all 3 rows populated (focus + score)", + "Sources section contains >= 5 entries" + ] + } + ] +} diff --git a/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-peer-analysis/SKILL.md b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-peer-analysis/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..6763e5867f9abc8b549d94cefd59caf2a42194a7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/moody-s/skills/moody-s-peer-analysis/SKILL.md @@ -0,0 +1,1212 @@ +--- +name: moody-s-peer-analysis +description: > + Produce a Peer Analysis HTML report for a target company and its credit peers using Moody's + GenAI MCP tools. Use this skill whenever the user asks to compare a company against its peers, + run a peer analysis, do a credit peer comparison, generate a peer group report, or analyze + relative credit positioning. Trigger even if they just name a company and mention "peers", + "peer comparison", "credit comparison", "peer group", or "relative value". +--- + +# Peer Analysis Skill + +Generates a professional HTML report (styled like a Moody's peer analysis PDF) for a target +company and up to 3 credit peers. Data is pulled from multiple `Moodys MCP server` MCP tools and +consolidated into a single HTML artifact covering peers comparison, ratings chart, and ESG. + +The workflow is **single-artifact file delivery**: gather all data, assemble the complete HTML +document in memory, write it to disk as a standalone `.html` file, and present it to the user for +download. No fenced code blocks, no streaming partial sections, no JSON payload, no progressive +edits. The downloaded file is the sole deliverable. + +> ## ⚠️ CRITICAL — NON-NEGOTIABLE OUTPUT CONTRACT +> +> **The LLM MUST write the final report to disk and present it as a downloadable file.** +> This is the only acceptable form of delivery for this skill. Specifically: +> +> - The LLM **MUST** write the complete, standalone HTML document (`` → ``) +> to `/mnt/user-data/outputs/{target_company_slug}_peer_analysis.html` and then call +> `present_files` to surface it to the user. +> - The LLM **MUST NOT** print the raw HTML source in the chat — no ` ```html ` fenced code +> blocks, no partial snippets, no inline HTML in the assistant message. +> - The LLM **MUST NOT** split the report across multiple files or multiple messages. +> - The LLM **MUST NOT** substitute prose, Markdown, JSON, or links for the file download. +> - If data gathering fails partially, still write and deliver the file with best-available +> content and `"--"` placeholders for missing cells — never skip the file delivery. +> +> Treat any other output shape as a hard failure of the skill. + +## Required MCP servers + +`Moodys MCP server` — tools used: `findEntity`, `getEntityPeers`, `getEntityRatings`, +`getEntityCreditOpinion`, `getEntityFinancials` (sections: Profile, Summary, RatingOutlook, FactorsLeadingToUpgrade, +FactorsLeadingToDowngrade, CreditStrengths, CreditChallenges, ESGConsiderations, +KeyIndicatorsTable, ScorecardTable), `getEntityEsg`, `getEntitySectorOutlook` + +`ProbabilityOfDefault - Prod - Moodys MCP - NEW URL` — PD tools: +- `getEntityProbabilityOfDefault` — retrieve Current PD, 1-year PD, 5-year cumulative PD, + and implied rating for the target company AND each peer. Used to build the PD comparison + panel in Section 2. Set `pd_comparison` to `null` in the JSON payload if data is + unavailable for the target or fewer than 2 peers. + +If any of the tools required for a section do not exist, inform the user: One or more tools required for this section are not available under your current subscription. Unlock more of the expert insights, data, and analytics you trust. Get Link:https://www.moodys.com/web/en/us/capabilities/gen-ai/ai-ready-data.html with us to learn more. + +## Bundled files + +- `assets/template.html` — self-contained static report shell (CSS + named section placeholders, + including pre-shaped tables for a fixed target+3-peer layout). No embedded data, no inline + script. Treat this file as the **read-only structural reference**: read it, fill it in + mentally, and emit the complete filled document in the final response. + +## Template (shared) + +Before emitting the HTML report, **read both**: +1. [`skills/shared/template/SKILL.md`](../shared/template/SKILL.md) — authoring rules (which + classes / snippets are owned by the shared layer, allowed per-skill overrides, outlook-badge + usage). +2. [`skills/shared/template/assets/template.html`](../shared/template/assets/template.html) — + canonical CSS (inside ``, section order, table skeletons (including all pre-shaped 4-company columns/rows), +row labels, and element IDs — as the scaffold for the final artifact. Do **not** copy it to the +workspace and do **not** open it. + +--- + +## Step 4 — Gather all data in parallel + +For every company in the set (target + up to 3 peers), fire **all of the following in a single +parallel batch** (one message, many tool calls): + +### Credit Opinion data (per company) + +Call `getEntityCreditOpinion`,`getEntityFinancials` requesting these sections, about the key Indicators table this should be populated with most recent fiscal year available (e.g. 2025 FY) on `getEntityFinancials`. Not LTM allowed: + +> **CRITICAL — `getEntityFinancials` is the authoritative source for all quantitative data.** +> Always call `getEntityFinancials` (with `excludeInterimData: true`) for every entity in the +> peer set to obtain the most recent **fiscal year-end** figures. Do NOT rely solely on the +> Key Indicators or Scorecard exhibits embedded in `getEntityCreditOpinion` — those may +> reference an older period. After fetching financials, identify each entity's latest year +> with a non-null Revenue value and use that year exclusively for Key Indicators charts, +> Scorecard "Current" column, and the Revenue bar chart. LTM figures are **not permitted**. + +| Section parameter | Purpose | +|---|---| +| `Profile` | Company description for the Peers Table | +| `FactorsLeadingToUpgrade` | Upgrade factors for Credit Drivers | +| `FactorsLeadingToDowngrade` | Downgrade factors for Credit Drivers | +| `CreditStrengths` | Credit strengths for Credit Drivers | +| `CreditChallenges` | Credit challenges for Credit Drivers | +| `KeyIndicatorsTable` | Financial metrics for Key Indicators table | +| `ScorecardTable` | Scorecard data | + +### Ratings (per company) + +Call `getEntityRatings` — retrieve the current long-term rating, rating class, rating date, +outlook, and historical ratings (need at least the last 5 rating actions for the Ratings Chart). + +### ESG (per company) + +Call `getEntityEsg` — overall CIS classification plus E, S, G sub-scores. + +### Sector outlook (once per sector) + +Call `getEntitySectorOutlook` for the target company's sector. Reuse for peers in the same +sector. + +### Probability of Default (target + all peers) + +Call `getEntityProbabilityOfDefault` for the target company AND every resolved peer in a +single parallel batch. Retrieve: +- 1-year PD (%) +- 5-year cumulative PD (%) +- PD-implied rating + +Compute the **peer average** for 1-year PD and 5-year cumulative PD (exclude the target). +Determine `pd_signal`: +- `"red"` — target 1-year PD is >2× peer average +- `"amber"` — target 1-year PD is 1.25–2× peer average +- `"green"` — target 1-year PD is ≤1.25× peer average + +Build `pd_gap_1yr` label (e.g. `"+0.079pp above peer avg (3.5×)"`). + +Set `pd_comparison` to `null` if the PD tool is unavailable or data is missing for the target +or fewer than 2 peers — the panel is suppressed automatically. + +Hold all results in context for Step 5 synthesis. + +--- + +## Step 5 — Synthesize + emit the complete artifact + +After data is gathered, assemble the complete filled HTML document and write it to disk, then +present it to the user for download (see Step 7 for the file-naming and delivery contract). + +The assembled document **must**: + +- Be a complete, standalone HTML document (doctype → ``) that renders without + external dependencies. +- Preserve the template's `` (CSS, fonts), section order, table skeletons, row labels, and + element IDs exactly. Only the empty targets defined below are populated. + +Write in professional financial/credit analysis language. Always reference specific companies by +name. The target company is **always the first column / first row** in every table. Render order +of content inside the code block follows the page top-to-bottom so the artifact is human-readable +as well as browser-renderable: cover/header fields first, then Peers Comparison sub-sections +(1–6), Ratings Chart, ESG, and citations/sources last. + +Attribute substantive claims with numbered citation references. The exact inline markup, the +URL-less fallback, and the rule that `n` matches the row position of the source inside +`#pa-sources` are defined in [skills/shared/citations/SKILL.md](../shared/citations/SKILL.md). + +### Cover / header fields (write first) + +- `#pa-report-date` — e.g. `April 20, 2026` (plain text) +- `#pa-footer-date` — same value (plain text) +- `#pa-target-company` — canonical name of the target (plain text) +- `#pa-peer-count` — integer count of peers resolved in Step 2 (plain text) +- `#pa-company-chips` — `Target` followed by one + `Peer` per peer (space-separated; target first) +- `#pa-cover-img-right`, `#pa-cover-img-bottom` — optional. If you have image URLs or data URIs + to use, set the `src` attributes **and** add the `has-cover-image` class to the corresponding + container (`
        ` and/or `
        `). + If you do not have images, leave the template as-is — the empty image strips will collapse + automatically and the cover will render as a clean navy block with the accent bar. + +### Section 1 — Peers Comparison Table & Analysis + +**1) Peers Table** → `` + +Write one `` per company. Two columns: company name + a substantive description paragraph +sourced from the Credit Opinion `Profile` section (headquarters, business overview, key +brands/segments, approximate TTM revenue). Description paragraphs may carry inline citations. + +**2) Peers Rating** → `` + +Write one `` per company. Three columns: company name, rating (formatted as +`{rating} ({rating class} / {date})`), and `Outlook`. +Use class rules below. + +**3) Credit Drivers** — 5 rows × 4 company columns, pre-shaped `` with per-cell IDs + +Write the 4 company header cells first: +- `#pa-cd-col-1` — target name (plain text) +- `#pa-cd-col-2`, `#pa-cd-col-3`, `#pa-cd-col-4` — peer names in order (leave empty if fewer + than 3 peers were resolved) + +Then write the 16 body cells (`#pa-cd-r{1..4}-c{1..4}`). Each cell is a substantive paragraph +with specific quantitative thresholds where available. Cells may carry inline citations: + +- Row 1 (`Upgrade factors`) — from `FactorsLeadingToUpgrade` +- Row 2 (`Downgrade factors`) — from `FactorsLeadingToDowngrade` +- Row 3 (`Credit strengths (qualitative)`) — from `CreditStrengths` +- Row 4 (`Credit challenges (qualitative)`) — from `CreditChallenges` + +> **Row 5 ("Quantitative support") has been removed.** Do NOT emit a 5th row in the Credit +> Drivers table. The pre-shaped table in `assets/template.html` has 5 row slots — leave +> `#pa-cd-r5-c{1..4}` blank and suppress the row label for Row 5 by setting its `
        ` to +> an empty string or by omitting it entirely if the template allows. Quantitative metrics +> are covered by the Key Indicators bar charts immediately below. + +If a Credit Opinion section is missing for a company, write `Not available` in the corresponding +cell rather than leaving it blank. + +**4) Key Indicators — Peer Bar Charts** → `#pa-ki-charts` + +Replace the static Key Indicators table with a set of **horizontal peer bar charts** matching +the visual style from the sector-drift report. Emit a `
        ` block +containing **five** `peer-bar-chart-outer` panels, one per metric: + +| Chart | Metric | Unit | Source | Note on "lower is better" | +|-------|--------|------|--------|--------------------------| +| 1 | FCF Margin % | `%` | (OCF − \|Capex\|) / Revenue | Higher = better | +| 2 | Debt / EBITDA | `x` | Moody's pre-computed Key Indicators | Lower = better | +| 3 | EBITDA Margin % | `%` | EBITDA / Revenue | Higher = better | +| 4 | EBITA / Interest | `x` | Moody's pre-computed Key Indicators | Higher = better | +| 5 | RCF / Net Debt | `%` | Moody's pre-computed Key Indicators | Higher = better | + +For each chart: +- Show one bar per company (target first, then peers sorted by descending value, then AVERAGE last) +- The target bar uses `background:#0066cc` (blue); AVERAGE bar uses `background:#2e7d32` (green) +- Peers use `background:#7ca8d8` (steel blue) for positive values, `background:#e0a0a0` for negative +- Draw an orange median line (`background: #e87722`) at the peer median position +- **Show the fiscal year for each company's bar** by appending the FY label in parentheses to + the `pbc-name` element (e.g. `Target Co (FY2025)`, `Peer A (FY2024)`). This is required + because different entities may have different most-recent fiscal years. Use the same FY + year identified via `getEntityFinancials` for each entity. +- Display the fiscal year reference at the top of the block (e.g. `FY2025, % of revenue | Orange line = peer median | Green bar = peer average`); if entities have mixed FYs, write `Most recent FY` instead of a single year +- Include a note line at the bottom with: peer median, peer avg (n=X), company value, gap + +**Compute peer average and peer median** across all resolved peers (exclude the target). + +**FY period header**: show the most recent common FY year at the top of `#pa-ki-charts` in +a `
        ` (e.g. `KEY INDICATORS — FY2025 | Company vs. Peers`). + +**Reference snippet** for one chart panel (emit five of these inside `#pa-ki-charts`): + +```html +
        +
        KEY INDICATORS — FY2025 | Company vs. Peers
        + +
        +
        FCF MARGIN — COMPANY VS. PEERS
        +
        FY2025, % of revenue | Orange line = peer median | Green bar = peer average
        +
        + +
        +
        Target Co
        +
        +
        Median 8.4%
        +
        +
        +
        -2.1%
        +
        + +
        +
        Peer A
        +
        +
        +
        +
        +
        12.3%
        +
        + +
        +
        AVERAGE
        +
        +
        +
        +
        8.7%
        +
        +
        +
        Peer median 8.42% | Peer avg 8.70% (n=6, Moody's). Company: -2.10%. Gap vs. median: -10.52pp.
        +
        + + +
        +``` + +**Bar width calculation** — for charts with only positive values: +- Find `maxAbs` = max of all absolute values across company + peers +- `fillW` = `(value / maxAbs * 88).toFixed(1) + '%'` + +For charts that could include negative values (FCF Margin): +- Use a zero-anchored track: `zeroPct = 44`, positive bars grow right, negative bars grow left +- `fillW = (|value| / maxAbs * 44).toFixed(1) + '%'` +- `fillL` for negative: `(zeroPct - |value|/maxAbs*44).toFixed(1) + '%'` + +**Median line position**: `medPct = (medV / maxAbs * 88).toFixed(1) + '%'` (positive-only charts) + +Source all values from `getEntityFinancials` (most recent FY — same period used in scorecards). +If a value is missing, omit the bar row for that company. + +**5) Scorecards** — 7 rows × 8 sub-columns (4 companies × Current/Forward), pre-shaped `` + +Write the 4 top-level company headers first: +- `#pa-sc-col-1` — target name +- `#pa-sc-col-2`, `#pa-sc-col-3`, `#pa-sc-col-4` — peer names + +Write the 8 sub-header labels: +- `#pa-sc-col-{1..4}-curr` — current-period label that **must exactly match the most-recent + FY period used for that entity in the Key Indicators bar charts** (e.g. if Apple's KI data + is from FY2025, write `FY2025`; if Microsoft's is from FY2024, write `FY2024`). Each + entity's label is set independently — do not force a single common year across all columns. +- `#pa-sc-col-{1..4}-fwd` — forward-period label (e.g. `Forward`) + +> **FY LABEL SYNCHRONY — STRICTLY ENFORCED (Sections 4 and 5):** +> The fiscal year label shown in Section 4 (Key Indicators bar charts) for each entity +> **MUST be identical** to the label shown in the `#pa-sc-col-{n}-curr` sub-header for that +> same entity in Section 5 (Scorecards). This is a hard consistency requirement: +> +> - Determine the most-recent non-null full fiscal year-end for each entity from +> `getEntityFinancials` (with `excludeInterimData: true`). Label it as `FY{YYYY}` +> (e.g. `FY2025`, `FY2024`). **Never use "LTM", "TTM", "Current", or any period +> label other than the specific `FY{YYYY}` form.** +> - Write that exact `FY{YYYY}` string in: +> 1. The `pbc-name` element of each company's row inside every Section 4 bar chart +> (appended in parentheses, e.g. `Apple Inc. (FY2025)`), AND in the +> `
        ` block label. +> 2. The `#pa-sc-col-{n}-curr` sub-header cell for that entity in Section 5. +> 3. The data values themselves — all numbers in Section 4 and Section 5 Current cells +> must be sourced from the same `FY{YYYY}` period. +> - If two entities have different most-recent FYs, each gets its own correct label +> independently. The header `
        ` should then read +> `KEY INDICATORS — Most Recent FY | Company vs. Peers`. +> - This synchrony check is mandatory before emitting the final HTML. Mismatched labels +> between Section 4 and Section 5 are a hard failure of the skill. + +> **`~` (tilde) prefix rule — STRICT:** The `~` prefix (e.g. `~2.5x`, `~15%`) means +> *approximately estimated / forecast* and must **only** appear in **Forward** (`-fwd`) cells. +> It must **never** appear in **Current** (`-curr`) cells. Current-period cells contain actual +> reported or Moody's-adjusted figures sourced from `getEntityFinancials`; use the precise +> value as-is (e.g. `2.3x`, `14.8%`). If the exact current figure is unavailable, write `N/A` +> — do not substitute a tilde-prefixed estimate. + +Then write the 56 body cells (`#pa-sc-r{1..7}-c{1..4}-curr` and `-fwd`) for the 7 rows: +- Row 1 — Scale: Revenue/Sales (USD bn) +- Row 2 — Profitability: EBIT(A) margin +- Row 3 — Leverage: Debt/EBITDA +- Row 4 — Cash flow: RCF/Net debt +- Row 5 — Coverage: EBIT(A)/Interest +- Row 6 — Scorecard-indicated outcome +- Row 7 — Actual rating + +Source from `ScorecardTable` in the Credit Opinion and `getEntityFinancials` + +**6) Conclusion** → `#pa-conclusion` + +Three `

        ` paragraphs focused on **differentiation** of the target among its peers. Paragraphs +may carry inline citations: + +- Paragraph 1: How the target differentiates positively vs. weaker peers on quantitative metrics + (leverage, coverage, cash flow). Cite specific ratios. +- Paragraph 2: Business risk profile comparison — where the target is more concentrated or less + diversified vs. stable peers. Reference upgrade/downgrade triggers. +- Paragraph 3: Practical positioning — frame the target's "path to stand out" by linking back + to the upgrade/downgrade framework and key risk factors. + +### Section 2 — Ratings Chart (± Probability of Default) + +> **SECTION 2 TITLE RULE — STRICTLY ENFORCED:** +> The heading for Section 2 (in both the TOC `

      • ` and the `
        `) +> must be set **conditionally** at emit time: +> +> - If PD data is available (i.e. `pd_comparison` is NOT `null`) → +> use **"Section 2. Ratings Chart & Probability of Default"** +> - If PD data is unavailable (i.e. `pd_comparison` is `null`, the MCP server is unreachable, +> or data is missing for the target or fewer than 2 peers) → +> use **"Section 2. Ratings Chart"** +> +> The template ships with the longer title as a placeholder; overwrite it in both locations +> (`#sec2 .section-heading` and the matching `
      • ` in `
          `) whenever +> PD data is absent. Never show "& Probability of Default" in the title if there is no PD panel. + +**Chart** → `#pa-ratings-chart` + +Emit a single inline `` block authored by the agent (see SVG template below). The chart +plots the last 5 rating actions for each company as a line chart. X-axis uses sequential labels +(`Rating 1` … `Rating 5`, most recent first); Y-axis maps Moody's rating symbols to a numeric +scale. + +**PD Panel** → `#pa-pd-panel` + +Immediately after the ratings chart, emit the Probability of Default panel as a **horizontal +bar chart** using the same `.peer-bar-chart-outer` style as the Key Indicators charts in +Section 1. If PD data is unavailable, leave `#pa-pd-panel` empty (the element collapses). + +Emit one `peer-bar-chart-outer` block showing the **1-year PD (%)** for each company. Use the +same CSS classes and bar-width formula as the KI charts (`pbc-fill`, `pbc-track`, `pbc-rows`, +etc.). Include a note row at the bottom with peer median, peer average, and the gap signal. + +Signal colouring for the target bar: +- `pbc-fill subj-neg` (red) — target 1-year PD > 2× peer average (`pd_signal: "red"`) +- `pbc-fill subj-pos` (blue) — all other cases + +**Reference snippet** (emit this block directly into `#pa-pd-panel`): + +```html +
          +
          PROBABILITY OF DEFAULT — 1-YEAR PD (%)
          +
          Moody's PD model | Orange line = peer median | Green bar = peer average
          +
          + +
          +
          Target Co
          +
          +
          Median 0.032%
          +
          +
          +
          0.111%
          +
          + +
          +
          Peer A
          +
          +
          +
          +
          +
          0.060%
          +
          + +
          +
          AVERAGE
          +
          +
          +
          +
          0.032%
          +
          +
          +
          Peer median 0.032% | Peer avg 0.032% (n=3). Target: 0.111%. Gap: +0.079pp above peer avg (3.5×). PD-implied rating: A1.
          +
          One-sentence PD narrative goes here.
          +
          +``` + +**Bar width calculation:** `fillW = (pd_1yr / maxPD * 88).toFixed(1) + '%'` where `maxPD` is +the maximum 1-year PD across all companies including the target. + +**Median line position:** `medPct = (medianPD / maxPD * 88).toFixed(1) + '%'` + +**Analysis** → `#pa-ratings-analysis` + +One `

          ` paragraph on rating trajectories — which companies show improvement, deterioration, +or stability, and what that implies for relative credit positioning. May carry inline citations. + +### Section 3 — ESG Table & Analysis + +**ESG Table** → `

      • ` + +Write one `` per company. Five columns: company name, Overall (CIS-*), Environmental (E-*), +Social (S-*), Governance (G-*). + +**Analysis** → `#pa-esg-analysis` + +Two `

        ` paragraphs. Paragraphs may carry inline citations: + +- Paragraph 1: Compare ESG profiles across the peer set. Identify which companies share similar + profiles and what drives the overall classification. +- Paragraph 2: Highlight the key differentiator (typically Governance) and explain which company + stands out as weaker/stronger and why. + +### Citations & sources (write last) + +- `#pa-cite-peers` — optional `

        …
        ` recap for the + peers-comparison section. Use the markup defined in + [skills/shared/citations/SKILL.md](../shared/citations/SKILL.md). Omit if empty. +- `#pa-cite-ratings` — optional recap for the ratings-chart section. Same markup. +- `#pa-cite-esg` — optional recap for the ESG section. Same markup. +- `#pa-sources` — end-of-document Citations rows. One `
        ` per source, + in `[1], [2], …` order, using the canonical row markup from the shared citations skill. + Internal MCP tool names are NEVER rendered in `.source-meta`. + +--- + +## Streaming protocol (element → content mapping) + +| Element ID | Content type | +|------------------------------------------------------|------------------------------------------------------------------------| +| `#pa-report-date` | Plain text date | +| `#pa-footer-date` | Plain text date (same value) | +| `#pa-target-company` | Plain text (canonical target name) | +| `#pa-peer-count` | Plain text integer | +| `#pa-company-chips` | `` + ``s | +| `#pa-cover-img-right`, `#pa-cover-img-bottom` | `` element — set `src` attribute | +| `
        ` | `` rows (company name + description) with inline citations | +| `` | `` rows with `` | +| `#pa-cd-col-1` … `#pa-cd-col-4` | Plain text (company names) | +| `#pa-cd-r{1..4}-c{1..4}` | Prose cell content (short `

        ` or plain text) with inline citations | +| `#pa-ki-charts` | Five `.peer-bar-chart-outer` panels (FCF Margin, Debt/EBITDA, EBITDA Margin, EBITA/Interest, RCF/Net Debt) | +| `#pa-sc-col-1` … `#pa-sc-col-4` | Plain text (company names, span 2 sub-columns) | +| `#pa-sc-col-{1..4}-curr`, `#pa-sc-col-{1..4}-fwd` | Plain text sub-header labels (Current / Forward period) | +| `#pa-sc-r{1..7}-c{1..4}-curr`, `…-fwd` | Plain text scorecard cell values | +| `#pa-conclusion` | Three `

        ` paragraphs with inline citations | +| `#pa-ratings-chart` | Single `

        ………
        ` block | +| `#pa-pd-panel` | PD comparison panel — horizontal bar chart using `peer-bar-chart-outer` style | +| `#pa-ratings-analysis` | One `

        ` paragraph with inline citations | +| `

        ` | `` rows (company + overall + E + S + G) | +| `#pa-esg-analysis` | Two `

        ` paragraphs with inline citations | +| `#pa-cite-peers`, `#pa-cite-ratings`, `#pa-cite-esg` | `

        …
        ` (optional, see shared citations skill) | +| `#pa-sources` | `
        ` rows (see shared citations skill) | + +If fewer than 3 peers are returned, leave unused column/row IDs empty. Do not collapse or remove +cells — the pre-shaped table simply keeps those cells blank. + +### Reference HTML snippets + +**Peers table row** (`
        `): + +```html + + + + +``` + +**Peers rating row** (``): + +```html + + + + + +``` + +**Company chips** (`#pa-company-chips`): + +```html +Target Co +Peer One +Peer Two +Peer Three +``` + +**ESG table row** (``): + +```html + + + + + + + +``` + +**Credit Drivers — per-cell write** (repeat for each of the 20 body cells): + +```html +Leverage sustained below 2.5x Debt/EBITDA, EBITA margin above 7%, and sustained positive free cash flow after dividends [1]. +``` + +**Conclusion paragraph** (inside `#pa-conclusion`, same inline-citation pattern applies to +`#pa-ratings-analysis` and `#pa-esg-analysis`): + +```html +

        On pure quantitative credit metrics, Target Co stands out decisively: Debt/EBITDA of 0.7x and EBITA/Interest of 27x are in line with the strongest-scoring peers, while its scale advantage (LTM revenue of $294B vs. $61B and $23B for the peer set) and FCF/Debt of 41% add a differentiation layer the others cannot match [1][2].

        +``` + +**Key Indicators — single row** (emit the full `` for each company inside the +`#pa-key-indicators` table, keeping the per-cell `id` attributes intact): + +```html + + + + + + + + + + + + + +``` + +**Scorecard — per-cell write** (Current or Forward): + +```html +2.7x +``` + +**Section citations recap** (`#pa-cite-peers`, `#pa-cite-ratings`, `#pa-cite-esg`) and +**sources rows** (`#pa-sources`): see +[skills/shared/citations/SKILL.md](../shared/citations/SKILL.md) for the canonical markup. +Reuse the same `[n]` numbering across inline references, optional recap blocks, and the +end-of-document Citations block. Never include MCP tool names in `.source-meta`. + +--- + +## Ratings Chart SVG template + +Emit the entire chart as a single HTML string into `#pa-ratings-chart`. The agent authors the +SVG directly — there is no runtime script. + +### Hardcoded constants + +- Dimensions: `W = 700`, `H = 350` +- Padding: `PAD_L = 70`, `PAD_R = 30`, `PAD_T = 30`, `PAD_B = 50` +- Plot area: width `= W - PAD_L - PAD_R = 600`, height `= H - PAD_T - PAD_B = 270` +- Number of x-axis points: `maxPts` = the largest number of ratings any company has, capped at 5 +- Palette (first = target): `#0066cc`, `#e6550d`, `#1a7a4a`, `#8b5cf6`, `#d63384` + +### Moody's rating → numeric value map + +| Rating | Value | Rating | Value | +|--------|-------|--------|-------| +| Aaa | 21 | Ba1 | 11 | +| Aa1 | 20 | Ba2 | 10 | +| Aa2 | 19 | Ba3 | 9 | +| Aa3 | 18 | B1 | 8 | +| A1 | 17 | B2 | 7 | +| A2 | 16 | B3 | 6 | +| A3 | 15 | Caa1 | 5 | +| Baa1 | 14 | Caa2 | 4 | +| Baa2 | 13 | Caa3 | 3 | +| Baa3 | 12 | Ca | 2 | +| | | C | 1 | + +`RATING_LABELS` (index 0..20 → symbol): `["C", "Ca", "Caa3", "Caa2", "Caa1", "B3", "B2", "B1", "Ba3", "Ba2", "Ba1", "Baa3", "Baa2", "Baa1", "A3", "A2", "A1", "Aa3", "Aa2", "Aa1", "Aaa"]`. + +### Coordinate formulae + +Compute once per chart: + +- Collect every rating value across all companies' last-5 series → `values[]`. +- `minV = clamp(min(values) - 1, 1, 21)` +- `maxV = clamp(max(values) + 1, 1, 21)` (ensure `maxV > minV`; if equal, set `maxV = minV + 1`) + +Per point `(i, v)` where `i` is the x-index (0-based) and `v` is the rating value: + +- `xPos(i) = PAD_L + (i / (maxPts - 1)) * 600` = `70 + (i / (maxPts - 1)) * 600` +- `yPos(v) = PAD_T + 270 - ((v - minV) / (maxV - minV)) * 270` = `30 + 270 - ((v - minV) / (maxV - minV)) * 270` + +### Reference SVG block + +```html +
        +
        Last 5 Ratings for Target and Peers
        + + + + Baa1 + + Baa2 + + Baa3 + + Ba1 + + Ba2 + + Ba3 + + + + Rating 1 + Rating 2 + Rating 3 + Rating 4 + Rating 5 + + + + + + + + + + + +
        +
        Target Co
        +
        Peer One
        +
        Peer Two
        +
        Peer Three
        +
        +
        +``` + +### Class-selection rules + +**`.outlook-badge`** modifier (inside peers-rating rows): + +- `stable` — outlook is "Stable" +- `positive` — outlook is "Positive" +- `negative` — outlook is "Negative" +- `review` — outlook contains "Review" (e.g., "Rating Under Review") +- `na` — outlook is missing or unknown + +**`.company-chip.target`** applies only to the target (first) chip. Remaining chips use plain +`.company-chip`. + +### Conventions + +- Use `

        ` for paragraphs, `

        • ` for bullets, `…` + for bold subheaders inside prose containers. +- Emit inline citations per [skills/shared/citations/SKILL.md](../shared/citations/SKILL.md). + Inline citations are the primary attribution mechanism — the optional per-section blocks + (`#pa-cite-peers`, `#pa-cite-ratings`, `#pa-cite-esg`) remain available as supplementary + summary boxes. +- Do NOT include overall section titles — the template already has those. +- `rating` values: use Moody's rating symbol (e.g. `Aaa`, `Aa1`, `Baa2`, `Ba1`). If not found, + use `N/A`. +- `outlook` values: `Stable`, `Positive`, `Negative`, `Rating Under Review`, or `N/A`. + +--- + + + + + + + + +--- + +## Tips + +- Run ALL data-gathering tool calls in a single parallel batch (one message, many tool calls). +- Write the final HTML to disk as a single `.html` file and deliver it via `present_files` — do not print the HTML source in the chat, do not split across multiple files. +- The target company always appears as the first column / first row in every table and + comparison. +- The conclusion must orient around the target company — how it differentiates from its peers. +- If fewer than 3 peers are returned, leave the unused column/row IDs empty. The pre-shaped + tables keep those cells blank — do not attempt to collapse or restructure the table. +- If `getEntityCreditOpinion` does not return a particular section, write `Not available` in the + corresponding cell rather than leaving it blank. +- `getEntitySectorOutlook` typically applies to all companies in the same sector — call once + and reuse. +- Emit the ratings-chart SVG directly into `#pa-ratings-chart` — the template no longer builds + the chart at render time. Pick the `.outlook-badge` class yourself using the rules above. +- For companies with fewer than 5 historical ratings, either repeat the oldest available rating + value to fill the trailing points, or reduce `maxPts` in the chart formula to the largest + available count (and drop the corresponding `Rating k` x-axis labels). +- Inline citations follow the shared citations skill — read + [skills/shared/citations/SKILL.md](../shared/citations/SKILL.md) before authoring any `[n]` + reference or the Citations block. +- **PD panel**: write the fully rendered HTML directly into `#pa-pd-panel` using the CSS classes + already in the template (`.pd-panel`, `.pd-stats`, `.pbc-rows`, etc.). The template's `'; + +// ========== Helper Functions ========== + +function isFullDocument(html) { + const trimmed = html.trimStart().toLowerCase(); + return trimmed.startsWith('', content); +} + +function getNewestScreen() { + const files = fs.readdirSync(CONTENT_DIR) + .filter(f => f.endsWith('.html')) + .map(f => { + const fp = path.join(CONTENT_DIR, f); + return { path: fp, mtime: fs.statSync(fp).mtime.getTime() }; + }) + .sort((a, b) => b.mtime - a.mtime); + return files.length > 0 ? files[0].path : null; +} + +// ========== HTTP Request Handler ========== + +function handleRequest(req, res) { + touchActivity(); + if (req.method === 'GET' && req.url === '/') { + const screenFile = getNewestScreen(); + let html = screenFile + ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8')) + : WAITING_PAGE; + + if (html.includes('')) { + html = html.replace('', helperInjection + '\n'); + } else { + html += helperInjection; + } + + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + res.end(html); + } else if (req.method === 'GET' && req.url.startsWith('/files/')) { + const fileName = req.url.slice(7); + const filePath = path.join(CONTENT_DIR, path.basename(fileName)); + if (!fs.existsSync(filePath)) { + res.writeHead(404); + res.end('Not found'); + return; + } + const ext = path.extname(filePath).toLowerCase(); + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; + res.writeHead(200, { 'Content-Type': contentType }); + res.end(fs.readFileSync(filePath)); + } else { + res.writeHead(404); + res.end('Not found'); + } +} + +// ========== WebSocket Connection Handling ========== + +const clients = new Set(); + +function handleUpgrade(req, socket) { + const key = req.headers['sec-websocket-key']; + if (!key) { socket.destroy(); return; } + + const accept = computeAcceptKey(key); + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n' + ); + + let buffer = Buffer.alloc(0); + clients.add(socket); + + socket.on('data', (chunk) => { + buffer = Buffer.concat([buffer, chunk]); + while (buffer.length > 0) { + let result; + try { + result = decodeFrame(buffer); + } catch (e) { + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); + clients.delete(socket); + return; + } + if (!result) break; + buffer = buffer.slice(result.bytesConsumed); + + switch (result.opcode) { + case OPCODES.TEXT: + handleMessage(result.payload.toString()); + break; + case OPCODES.CLOSE: + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); + clients.delete(socket); + return; + case OPCODES.PING: + socket.write(encodeFrame(OPCODES.PONG, result.payload)); + break; + case OPCODES.PONG: + break; + default: { + const closeBuf = Buffer.alloc(2); + closeBuf.writeUInt16BE(1003); + socket.end(encodeFrame(OPCODES.CLOSE, closeBuf)); + clients.delete(socket); + return; + } + } + } + }); + + socket.on('close', () => clients.delete(socket)); + socket.on('error', () => clients.delete(socket)); +} + +function handleMessage(text) { + let event; + try { + event = JSON.parse(text); + } catch (e) { + console.error('Failed to parse WebSocket message:', e.message); + return; + } + touchActivity(); + console.log(JSON.stringify({ source: 'user-event', ...event })); + if (event.choice) { + const eventsFile = path.join(STATE_DIR, 'events'); + fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n'); + } +} + +function broadcast(msg) { + const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg))); + for (const socket of clients) { + try { socket.write(frame); } catch (e) { clients.delete(socket); } + } +} + +// ========== Activity Tracking ========== + +const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes +let lastActivity = Date.now(); + +function touchActivity() { + lastActivity = Date.now(); +} + +// ========== File Watching ========== + +const debounceTimers = new Map(); + +// ========== Server Startup ========== + +function startServer() { + if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true }); + if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true }); + + // Track known files to distinguish new screens from updates. + // macOS fs.watch reports 'rename' for both new files and overwrites, + // so we can't rely on eventType alone. + const knownFiles = new Set( + fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html')) + ); + + const server = http.createServer(handleRequest); + server.on('upgrade', handleUpgrade); + + const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => { + if (!filename || !filename.endsWith('.html')) return; + + if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename)); + debounceTimers.set(filename, setTimeout(() => { + debounceTimers.delete(filename); + const filePath = path.join(CONTENT_DIR, filename); + + if (!fs.existsSync(filePath)) return; // file was deleted + touchActivity(); + + if (!knownFiles.has(filename)) { + knownFiles.add(filename); + const eventsFile = path.join(STATE_DIR, 'events'); + if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile); + console.log(JSON.stringify({ type: 'screen-added', file: filePath })); + } else { + console.log(JSON.stringify({ type: 'screen-updated', file: filePath })); + } + + broadcast({ type: 'reload' }); + }, 100)); + }); + watcher.on('error', (err) => console.error('fs.watch error:', err.message)); + + function shutdown(reason) { + console.log(JSON.stringify({ type: 'server-stopped', reason })); + const infoFile = path.join(STATE_DIR, 'server-info'); + if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile); + fs.writeFileSync( + path.join(STATE_DIR, 'server-stopped'), + JSON.stringify({ reason, timestamp: Date.now() }) + '\n' + ); + watcher.close(); + clearInterval(lifecycleCheck); + server.close(() => process.exit(0)); + } + + function ownerAlive() { + if (!ownerPid) return true; + try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; } + } + + // Check every 60s: exit if owner process died or idle for 30 minutes + const lifecycleCheck = setInterval(() => { + if (!ownerAlive()) shutdown('owner process exited'); + else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout'); + }, 60 * 1000); + lifecycleCheck.unref(); + + // Validate owner PID at startup. If it's already dead, the PID resolution + // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios). + // Disable monitoring and rely on the idle timeout instead. + if (ownerPid) { + try { process.kill(ownerPid, 0); } + catch (e) { + if (e.code !== 'EPERM') { + console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' })); + ownerPid = null; + } + } + } + + server.listen(PORT, HOST, () => { + const info = JSON.stringify({ + type: 'server-started', port: Number(PORT), host: HOST, + url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT, + screen_dir: CONTENT_DIR, state_dir: STATE_DIR + }); + console.log(info); + fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n'); + }); +} + +if (require.main === module) { + startServer(); +} + +module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES }; diff --git a/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/scripts/start-server.sh b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/scripts/start-server.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ef6dcb991547a28e2b555d6fd08e97b8ea27400 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/scripts/start-server.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Start the brainstorm server and output connection info +# Usage: start-server.sh [--project-dir ] [--host ] [--url-host ] [--foreground] [--background] +# +# Starts server on a random high port, outputs JSON with URL. +# Each session gets its own directory to avoid conflicts. +# +# Options: +# --project-dir Store session files under /.superpowers/brainstorm/ +# instead of /tmp. Files persist after server stops. +# --host Host/interface to bind (default: 127.0.0.1). +# Use 0.0.0.0 in remote/containerized environments. +# --url-host Hostname shown in returned URL JSON. +# --foreground Run server in the current terminal (no backgrounding). +# --background Force background mode (overrides Codex auto-foreground). + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# Parse arguments +PROJECT_DIR="" +FOREGROUND="false" +FORCE_BACKGROUND="false" +BIND_HOST="127.0.0.1" +URL_HOST="" +while [[ $# -gt 0 ]]; do + case "$1" in + --project-dir) + PROJECT_DIR="$2" + shift 2 + ;; + --host) + BIND_HOST="$2" + shift 2 + ;; + --url-host) + URL_HOST="$2" + shift 2 + ;; + --foreground|--no-daemon) + FOREGROUND="true" + shift + ;; + --background|--daemon) + FORCE_BACKGROUND="true" + shift + ;; + *) + echo "{\"error\": \"Unknown argument: $1\"}" + exit 1 + ;; + esac +done + +if [[ -z "$URL_HOST" ]]; then + if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then + URL_HOST="localhost" + else + URL_HOST="$BIND_HOST" + fi +fi + +# Some environments reap detached/background processes. Auto-foreground when detected. +if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then + FOREGROUND="true" +fi + +# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected. +if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then + case "${OSTYPE:-}" in + msys*|cygwin*|mingw*) FOREGROUND="true" ;; + esac + if [[ -n "${MSYSTEM:-}" ]]; then + FOREGROUND="true" + fi +fi + +# Generate unique session directory +SESSION_ID="$$-$(date +%s)" + +if [[ -n "$PROJECT_DIR" ]]; then + SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}" +else + SESSION_DIR="/tmp/brainstorm-${SESSION_ID}" +fi + +STATE_DIR="${SESSION_DIR}/state" +PID_FILE="${STATE_DIR}/server.pid" +LOG_FILE="${STATE_DIR}/server.log" + +# Create fresh session directory with content and state peers +mkdir -p "${SESSION_DIR}/content" "$STATE_DIR" + +# Kill any existing server +if [[ -f "$PID_FILE" ]]; then + old_pid=$(cat "$PID_FILE") + kill "$old_pid" 2>/dev/null + rm -f "$PID_FILE" +fi + +cd "$SCRIPT_DIR" + +# Resolve the harness PID (grandparent of this script). +# $PPID is the ephemeral shell the harness spawned to run us — it dies +# when this script exits. The harness itself is $PPID's parent. +OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')" +if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then + OWNER_PID="$PPID" +fi + +# Foreground mode for environments that reap detached/background processes. +if [[ "$FOREGROUND" == "true" ]]; then + echo "$$" > "$PID_FILE" + env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs + exit $? +fi + +# Start server, capturing output to log file +# Use nohup to survive shell exit; disown to remove from job table +nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs > "$LOG_FILE" 2>&1 & +SERVER_PID=$! +disown "$SERVER_PID" 2>/dev/null +echo "$SERVER_PID" > "$PID_FILE" + +# Wait for server-started message (check log file) +for i in {1..50}; do + if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then + # Verify server is still alive after a short window (catches process reapers) + alive="true" + for _ in {1..20}; do + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + alive="false" + break + fi + sleep 0.1 + done + if [[ "$alive" != "true" ]]; then + echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}" + exit 1 + fi + grep "server-started" "$LOG_FILE" | head -1 + exit 0 + fi + sleep 0.1 +done + +# Timeout - server didn't start +echo '{"error": "Server failed to start within 5 seconds"}' +exit 1 diff --git a/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/scripts/stop-server.sh b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/scripts/stop-server.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6b94e6532b7006c7cb05898475e9f71c53c173e --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/scripts/stop-server.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Stop the brainstorm server and clean up +# Usage: stop-server.sh +# +# Kills the server process. Only deletes session directory if it's +# under /tmp (ephemeral). Persistent directories (.superpowers/) are +# kept so mockups can be reviewed later. + +SESSION_DIR="$1" + +if [[ -z "$SESSION_DIR" ]]; then + echo '{"error": "Usage: stop-server.sh "}' + exit 1 +fi + +STATE_DIR="${SESSION_DIR}/state" +PID_FILE="${STATE_DIR}/server.pid" + +if [[ -f "$PID_FILE" ]]; then + pid=$(cat "$PID_FILE") + + # Try to stop gracefully, fallback to force if still alive + kill "$pid" 2>/dev/null || true + + # Wait for graceful shutdown (up to ~2s) + for i in {1..20}; do + if ! kill -0 "$pid" 2>/dev/null; then + break + fi + sleep 0.1 + done + + # If still running, escalate to SIGKILL + if kill -0 "$pid" 2>/dev/null; then + kill -9 "$pid" 2>/dev/null || true + + # Give SIGKILL a moment to take effect + sleep 0.1 + fi + + if kill -0 "$pid" 2>/dev/null; then + echo '{"status": "failed", "error": "process still running"}' + exit 1 + fi + + rm -f "$PID_FILE" "${STATE_DIR}/server.log" + + # Only delete ephemeral /tmp directories + if [[ "$SESSION_DIR" == /tmp/* ]]; then + rm -rf "$SESSION_DIR" + fi + + echo '{"status": "stopped"}' +else + echo '{"status": "not_running"}' +fi diff --git a/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/spec-document-reviewer-prompt.md b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/spec-document-reviewer-prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..35acbb611c054f59f8cba0e551e7f04d3ce489e7 --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/spec-document-reviewer-prompt.md @@ -0,0 +1,49 @@ +# Spec Document Reviewer Prompt Template + +Use this template when dispatching a spec document reviewer subagent. + +**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning. + +**Dispatch after:** Spec document is written to docs/superpowers/specs/ + +``` +Task tool (general-purpose): + description: "Review spec document" + prompt: | + You are a spec document reviewer. Verify this spec is complete and ready for planning. + + **Spec to review:** [SPEC_FILE_PATH] + + ## What to Check + + | Category | What to Look For | + |----------|------------------| + | Completeness | TODOs, placeholders, "TBD", incomplete sections | + | Consistency | Internal contradictions, conflicting requirements | + | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing | + | Scope | Focused enough for a single plan — not covering multiple independent subsystems | + | YAGNI | Unrequested features, over-engineering | + + ## Calibration + + **Only flag issues that would cause real problems during implementation planning.** + A missing section, a contradiction, or a requirement so ambiguous it could be + interpreted two different ways — those are issues. Minor wording improvements, + stylistic preferences, and "sections less detailed than others" are not. + + Approve unless there are serious gaps that would lead to a flawed plan. + + ## Output Format + + ## Spec Review + + **Status:** Approved | Issues Found + + **Issues (if any):** + - [Section X]: [specific issue] - [why it matters for planning] + + **Recommendations (advisory, do not block approval):** + - [suggestions for improvement] +``` + +**Reviewer returns:** Status, Issues (if any), Recommendations diff --git a/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/visual-companion.md b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/visual-companion.md new file mode 100644 index 0000000000000000000000000000000000000000..2113863d1e3d48dca1efb42f31aa70ec9613290a --- /dev/null +++ b/data/.codex/.codex/.tmp/plugins/plugins/superpowers/skills/brainstorming/visual-companion.md @@ -0,0 +1,287 @@ +# Visual Companion Guide + +Browser-based visual brainstorming companion for showing mockups, diagrams, and options. + +## When to Use + +Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?** + +**Use the browser** when the content itself is visual: + +- **UI mockups** — wireframes, layouts, navigation structures, component designs +- **Architecture diagrams** — system components, data flow, relationship maps +- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions +- **Design polish** — when the question is about look and feel, spacing, visual hierarchy +- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams + +**Use the terminal** when the content is text or tabular: + +- **Requirements and scope questions** — "what does X mean?", "which features are in scope?" +- **Conceptual A/B/C choices** — picking between approaches described in words +- **Tradeoff lists** — pros/cons, comparison tables +- **Technical decisions** — API design, data modeling, architectural approach selection +- **Clarifying questions** — anything where the answer is words, not a visual preference + +A question *about* a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser. + +## How It Works + +The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn. + +**Content fragments vs full documents:** If your HTML file starts with `/.superpowers/brainstorm/` for the session directory. + +**Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there. + +**Launching the server by platform:** + +**Claude Code (macOS / Linux):** +```bash +# Default mode works — the script backgrounds the server itself +scripts/start-server.sh --project-dir /path/to/project +``` + +**Claude Code (Windows):** +```bash +# Windows auto-detects and uses foreground mode, which blocks the tool call. +# Use run_in_background: true on the Bash tool call so the server survives +# across conversation turns. +scripts/start-server.sh --project-dir /path/to/project +``` +When calling this via the Bash tool, set `run_in_background: true`. Then read `$STATE_DIR/server-info` on the next turn to get the URL and port. + +**Codex:** +```bash +# Codex reaps background processes. The script auto-detects CODEX_CI and +# switches to foreground mode. Run it normally — no extra flags needed. +scripts/start-server.sh --project-dir /path/to/project +``` + +**Gemini CLI:** +```bash +# Use --foreground and set is_background: true on your shell tool call +# so the process survives across turns +scripts/start-server.sh --project-dir /path/to/project --foreground +``` + +**Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism. + +If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host: + +```bash +scripts/start-server.sh \ + --project-dir /path/to/project \ + --host 0.0.0.0 \ + --url-host localhost +``` + +Use `--url-host` to control what hostname is printed in the returned URL JSON. + +## The Loop + +1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`: + - Before each write, check that `$STATE_DIR/server-info` exists. If it doesn't (or `$STATE_DIR/server-stopped` exists), the server has shut down — restart it with `start-server.sh` before continuing. The server auto-exits after 30 minutes of inactivity. + - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html` + - **Never reuse filenames** — each screen gets a fresh file + - Use Write tool — **never use cat/heredoc** (dumps noise into terminal) + - Server automatically serves the newest file + +2. **Tell user what to expect and end your turn:** + - Remind them of the URL (every step, not just first) + - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage") + - Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like." + +3. **On your next turn** — after the user responds in the terminal: + - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines + - Merge with the user's terminal text to get the full picture + - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data + +4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated. + +5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content: + + ```html + +
          +

          Continuing in terminal...

          +
          + ``` + + This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual. + +6. Repeat until done. + +## Writing Content Fragments + +Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure). + +**Minimal example:** + +```html +

          Which layout works better?

          +

          Consider readability and visual hierarchy

          + +
          +
          +
          A
          +
          +

          Single Column

          +

          Clean, focused reading experience

          +
          +
          +
          +
          B
          +
          +

          Two Column

          +

          Sidebar navigation with main content

          +
          +
          +
          +``` + +That's it. No ``, no CSS, no `\n" + '\n' + ) + SPOTLIGHT_ERROR_PAGE_SNIPPET = ( + '\n' + '\n' + ) + CHARSET_PREFIX = "charset=" + BODY_TAG_NAME = "body" + BODY_CLOSE_TAG_POSSIBILITIES = tuple( + "".format("".join(chars)) + for chars in product(*zip(BODY_TAG_NAME.upper(), BODY_TAG_NAME.lower())) + ) + + class SpotlightMiddleware(MiddlewareMixin): # type: ignore[misc] + _spotlight_script: "Optional[str]" = None + _spotlight_url: "Optional[str]" = None + + def __init__(self: "Self", get_response: "Callable[..., HttpResponse]") -> None: + super().__init__(get_response) + + import sentry_sdk.api + + self.sentry_sdk = sentry_sdk.api + + spotlight_client = self.sentry_sdk.get_client().spotlight + if spotlight_client is None: + sentry_logger.warning( + "Cannot find Spotlight client from SpotlightMiddleware, disabling the middleware." + ) + return None + # Spotlight URL has a trailing `/stream` part at the end so split it off + self._spotlight_url = urllib.parse.urljoin(spotlight_client.url, "../") + + @property + def spotlight_script(self: "Self") -> "Optional[str]": + if self._spotlight_url is not None and self._spotlight_script is None: + try: + spotlight_js_url = urllib.parse.urljoin( + self._spotlight_url, SPOTLIGHT_JS_ENTRY_PATH + ) + req = urllib.request.Request( + spotlight_js_url, + method="HEAD", + ) + urllib.request.urlopen(req) + self._spotlight_script = SPOTLIGHT_JS_SNIPPET_PATTERN.format( + spotlight_url=self._spotlight_url, + spotlight_js_url=spotlight_js_url, + ) + except urllib.error.URLError as err: + sentry_logger.debug( + "Cannot get Spotlight JS to inject at %s. SpotlightMiddleware will not be very useful.", + spotlight_js_url, + exc_info=err, + ) + + return self._spotlight_script + + def process_response( + self: "Self", _request: "HttpRequest", response: "HttpResponse" + ) -> "Optional[HttpResponse]": + content_type_header = tuple( + p.strip() + for p in response.headers.get("Content-Type", "").lower().split(";") + ) + content_type = content_type_header[0] + if len(content_type_header) > 1 and content_type_header[1].startswith( + CHARSET_PREFIX + ): + encoding = content_type_header[1][len(CHARSET_PREFIX) :] + else: + encoding = "utf-8" + + if ( + self.spotlight_script is not None + and not response.streaming + and content_type == "text/html" + ): + content_length = len(response.content) + injection = self.spotlight_script.encode(encoding) + injection_site = next( + ( + idx + for idx in ( + response.content.rfind(body_variant.encode(encoding)) + for body_variant in BODY_CLOSE_TAG_POSSIBILITIES + ) + if idx > -1 + ), + content_length, + ) + + # This approach works even when we don't have a `` tag + response.content = ( + response.content[:injection_site] + + injection + + response.content[injection_site:] + ) + + if response.has_header("Content-Length"): + response.headers["Content-Length"] = content_length + len(injection) + + return response + + def process_exception( + self: "Self", _request: "HttpRequest", exception: Exception + ) -> "Optional[HttpResponseServerError]": + if not settings.DEBUG or not self._spotlight_url: + return None + + try: + spotlight = ( + urllib.request.urlopen(self._spotlight_url).read().decode("utf-8") + ) + except urllib.error.URLError: + return None + else: + event_id = self.sentry_sdk.capture_exception(exception) + return HttpResponseServerError( + spotlight.replace( + "", + SPOTLIGHT_ERROR_PAGE_SNIPPET.format( + spotlight_url=self._spotlight_url, event_id=event_id + ), + ) + ) + +except ImportError: + settings = None + + +def _resolve_spotlight_url( + spotlight_config: "Any", sentry_logger: "Any" +) -> "Optional[str]": + """ + Resolve the Spotlight URL based on config and environment variable. + + Implements precedence rules per the SDK spec: + https://develop.sentry.dev/sdk/expected-features/spotlight/ + + Returns the resolved URL string, or None if Spotlight should be disabled. + """ + spotlight_env_value = os.environ.get("SENTRY_SPOTLIGHT") + + # Parse env var to determine if it's a boolean or URL + spotlight_from_env: "Optional[bool]" = None + spotlight_env_url: "Optional[str]" = None + if spotlight_env_value: + parsed = env_to_bool(spotlight_env_value, strict=True) + if parsed is None: + # It's a URL string + spotlight_from_env = True + spotlight_env_url = spotlight_env_value + else: + spotlight_from_env = parsed + + # Apply precedence rules per spec: + # https://develop.sentry.dev/sdk/expected-features/spotlight/#precedence-rules + if spotlight_config is False: + # Config explicitly disables spotlight - warn if env var was set + if spotlight_from_env: + sentry_logger.warning( + "Spotlight is disabled via spotlight=False config option, " + "ignoring SENTRY_SPOTLIGHT environment variable." + ) + return None + elif spotlight_config is True: + # Config enables spotlight with boolean true + # If env var has URL, use env var URL per spec + if spotlight_env_url: + return spotlight_env_url + else: + return DEFAULT_SPOTLIGHT_URL + elif isinstance(spotlight_config, str): + # Config has URL string - use config URL, warn if env var differs + if spotlight_env_value and spotlight_env_value != spotlight_config: + sentry_logger.warning( + "Spotlight URL from config (%s) takes precedence over " + "SENTRY_SPOTLIGHT environment variable (%s).", + spotlight_config, + spotlight_env_value, + ) + return spotlight_config + elif spotlight_config is None: + # No config - use env var + if spotlight_env_url: + return spotlight_env_url + elif spotlight_from_env: + return DEFAULT_SPOTLIGHT_URL + # else: stays None (disabled) + + return None + + +def setup_spotlight(options: "Dict[str, Any]") -> "Optional[SpotlightClient]": + url = _resolve_spotlight_url(options.get("spotlight"), sentry_logger) + + if url is None: + return None + + # Only set up logging handler when spotlight is actually enabled + _handler = logging.StreamHandler(sys.stderr) + _handler.setFormatter(logging.Formatter(" [spotlight] %(levelname)s: %(message)s")) + logger.addHandler(_handler) + logger.setLevel(logging.INFO) + + # Update options with resolved URL for consistency + options["spotlight"] = url + + with capture_internal_exceptions(): + if ( + settings is not None + and settings.DEBUG + and env_to_bool(os.environ.get("SENTRY_SPOTLIGHT_ON_ERROR", "1")) + and env_to_bool(os.environ.get("SENTRY_SPOTLIGHT_MIDDLEWARE", "1")) + ): + middleware = settings.MIDDLEWARE + if DJANGO_SPOTLIGHT_MIDDLEWARE_PATH not in middleware: + settings.MIDDLEWARE = type(middleware)( + chain(middleware, (DJANGO_SPOTLIGHT_MIDDLEWARE_PATH,)) + ) + logger.info("Enabled Spotlight integration for Django") + + client = SpotlightClient(url) + logger.info("Enabled Spotlight using sidecar at %s", url) + + return client diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/traces.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/traces.py new file mode 100644 index 0000000000000000000000000000000000000000..f49760f03b02451322ea1800b2f3e76da02a2bc8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/traces.py @@ -0,0 +1,810 @@ +""" +EXPERIMENTAL. Do not use in production. + +The API in this file is only meant to be used in span streaming mode. + +You can enable span streaming mode via +sentry_sdk.init(_experiments={"trace_lifecycle": "stream"}). +""" + +import sys +import uuid +import warnings +from datetime import datetime, timedelta, timezone +from enum import Enum +from typing import TYPE_CHECKING + +import sentry_sdk +from sentry_sdk.consts import SPANDATA +from sentry_sdk.profiler.continuous_profiler import ( + get_profiler_id, + try_autostart_continuous_profiler, + try_profile_lifecycle_trace_start, +) +from sentry_sdk.tracing_utils import Baggage +from sentry_sdk.utils import ( + capture_internal_exceptions, + format_attribute, + get_current_thread_meta, + logger, + nanosecond_time, + should_be_treated_as_error, +) + +if TYPE_CHECKING: + from typing import ( + Any, + Callable, + Iterator, + Optional, + overload, + ParamSpec, + TypeVar, + Union, + ) + + from sentry_sdk._types import Attributes, AttributeValue + from sentry_sdk.profiler.continuous_profiler import ContinuousProfile + + P = ParamSpec("P") + R = TypeVar("R") + + +BAGGAGE_HEADER_NAME = "baggage" +SENTRY_TRACE_HEADER_NAME = "sentry-trace" + + +class SpanStatus(str, Enum): + OK = "ok" + ERROR = "error" + + def __str__(self) -> str: + return self.value + + +_VALID_SPAN_STATUSES = frozenset(e.value for e in SpanStatus) + + +# Segment source, see +# https://getsentry.github.io/sentry-conventions/generated/attributes/sentry.html#sentryspansource +class SegmentSource(str, Enum): + COMPONENT = "component" + CUSTOM = "custom" + ROUTE = "route" + TASK = "task" + URL = "url" + VIEW = "view" + + def __str__(self) -> str: + return self.value + + +# These are typically high cardinality and the server hates them +LOW_QUALITY_SEGMENT_SOURCES = [ + SegmentSource.URL, +] + + +SOURCE_FOR_STYLE = { + "endpoint": SegmentSource.COMPONENT, + "function_name": SegmentSource.COMPONENT, + "handler_name": SegmentSource.COMPONENT, + "method_and_path_pattern": SegmentSource.ROUTE, + "path": SegmentSource.URL, + "route_name": SegmentSource.COMPONENT, + "route_pattern": SegmentSource.ROUTE, + "uri_template": SegmentSource.ROUTE, + "url": SegmentSource.ROUTE, +} + + +# Sentinel value for an unset parent_span to be able to distinguish it from +# a None set by the user +_DEFAULT_PARENT_SPAN = object() + + +def start_span( + name: str, + attributes: "Optional[Attributes]" = None, + parent_span: "Optional[StreamedSpan]" = _DEFAULT_PARENT_SPAN, # type: ignore[assignment] + active: bool = True, +) -> "StreamedSpan": + """ + Start a span. + + EXPERIMENTAL. Use sentry_sdk.start_transaction() and sentry_sdk.start_span() + instead. + + The span's parent, unless provided explicitly via the `parent_span` argument, + will be the current active span, if any. If there is none, this span will + become the root of a new span tree. If you explicitly want this span to be + top-level without a parent, set `parent_span=None`. + + `start_span()` can either be used as context manager or you can use the span + object it returns and explicitly end it via `span.end()`. The following is + equivalent: + + ```python + import sentry_sdk + + with sentry_sdk.traces.start_span(name="My Span"): + # do something + + # The span automatically finishes once the `with` block is exited + ``` + + ```python + import sentry_sdk + + span = sentry_sdk.traces.start_span(name="My Span") + # do something + span.end() + ``` + + To continue a trace from another service, call + `sentry_sdk.traces.continue_trace()` prior to creating a top-level span. + + :param name: The name to identify this span by. + :type name: str + + :param attributes: Key-value attributes to set on the span from the start. + These will also be accessible in the traces sampler. + :type attributes: "Optional[Attributes]" + + :param parent_span: A span instance that the new span should consider its + parent. If not provided, the parent will be set to the currently active + span, if any. If set to `None`, this span will become a new root-level + span. + :type parent_span: "Optional[StreamedSpan]" + + :param active: Controls whether spans started while this span is running + will automatically become its children. That's the default behavior. If + you want to create a span that shouldn't have any children (unless + provided explicitly via the `parent_span` argument), set this to `False`. + :type active: bool + + :return: The span that has been started. + :rtype: StreamedSpan + """ + from sentry_sdk.tracing_utils import has_span_streaming_enabled + + if not has_span_streaming_enabled(sentry_sdk.get_client().options): + warnings.warn( + "Using span streaming API in non-span-streaming mode. Use " + "sentry_sdk.start_transaction() and sentry_sdk.start_span() " + "instead.", + stacklevel=2, + ) + return NoOpStreamedSpan() + + return sentry_sdk.get_current_scope().start_streamed_span( + name, attributes, parent_span, active + ) + + +def continue_trace(incoming: "dict[str, Any]") -> None: + """ + Continue a trace from headers or environment variables. + + EXPERIMENTAL. Use sentry_sdk.continue_trace() instead. + + This function sets the propagation context on the scope. Any span started + in the updated scope will belong under the trace extracted from the + provided propagation headers or environment variables. + + continue_trace() doesn't start any spans on its own. Use the start_span() + API for that. + """ + # This is set both on the isolation and the current scope for compatibility + # reasons. Conceptually, it belongs on the isolation scope, and it also + # used to be set there in non-span-first mode. But in span first mode, we + # start spans on the current scope, regardless of type, like JS does, so we + # need to set the propagation context there. + sentry_sdk.get_isolation_scope().generate_propagation_context( + incoming, + ) + sentry_sdk.get_current_scope().generate_propagation_context( + incoming, + ) + + +def new_trace() -> None: + """ + Resets the propagation context, forcing a new trace. + + EXPERIMENTAL. + + This function sets the propagation context on the scope. Any span started + in the updated scope will start its own trace. + + new_trace() doesn't start any spans on its own. Use the start_span() API + for that. + """ + sentry_sdk.get_isolation_scope().set_new_propagation_context() + sentry_sdk.get_current_scope().set_new_propagation_context() + + +class StreamedSpan: + """ + A span holds timing information of a block of code. + + Spans can have multiple child spans, thus forming a span tree. + + This is the Span First span implementation that streams spans. The original + transaction-based span implementation lives in tracing.Span. + """ + + __slots__ = ( + "_name", + "_attributes", + "_active", + "_span_id", + "_trace_id", + "_parent_span_id", + "_segment", + "_parent_sampled", + "_start_timestamp", + "_start_timestamp_monotonic_ns", + "_end_timestamp", + "_status", + "_scope", + "_previous_span_on_scope", + "_baggage", + "_sample_rand", + "_sample_rate", + "_continuous_profile", + ) + + def __init__( + self, + *, + name: str, + attributes: "Optional[Attributes]" = None, + active: bool = True, + scope: "sentry_sdk.Scope", + segment: "Optional[StreamedSpan]" = None, + trace_id: "Optional[str]" = None, + parent_span_id: "Optional[str]" = None, + parent_sampled: "Optional[bool]" = None, + baggage: "Optional[Baggage]" = None, + sample_rate: "Optional[float]" = None, + sample_rand: "Optional[float]" = None, + ): + self._name: str = name + self._active: bool = active + self._attributes: "Attributes" = { + "sentry.origin": "manual", + } + + if attributes: + for attribute, value in attributes.items(): + self.set_attribute(attribute, value) + + self._scope = scope + + self._segment = segment or self + + self._trace_id: "Optional[str]" = trace_id + self._parent_span_id = parent_span_id + self._parent_sampled = parent_sampled + self._baggage = baggage + self._sample_rand = sample_rand + self._sample_rate = sample_rate + + self._start_timestamp = datetime.now(timezone.utc) + self._end_timestamp: "Optional[datetime]" = None + + # profiling depends on this value and requires that + # it is measured in nanoseconds + self._start_timestamp_monotonic_ns = nanosecond_time() + + self._span_id: "Optional[str]" = None + + self._status = SpanStatus.OK.value + + self._update_active_thread() + + self._continuous_profile: "Optional[ContinuousProfile]" = None + self._start_profile() + self._set_profile_id(get_profiler_id()) + + self._set_segment_attributes() + + self._start() + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__}(" + f"name={self._name}, " + f"trace_id={self.trace_id}, " + f"span_id={self.span_id}, " + f"parent_span_id={self._parent_span_id}, " + f"active={self._active})>" + ) + + def __enter__(self) -> "StreamedSpan": + return self + + def __exit__( + self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]" + ) -> None: + if self._end_timestamp is not None: + # This span is already finished, ignore + return + + if value is not None and should_be_treated_as_error(ty, value): + self.status = SpanStatus.ERROR.value + + self._end() + + def end(self, end_timestamp: "Optional[Union[float, datetime]]" = None) -> None: + """ + Finish this span and queue it for sending. + + :param end_timestamp: End timestamp to use instead of current time. + :type end_timestamp: "Optional[Union[float, datetime]]" + """ + self._end(end_timestamp) + + def finish(self, end_timestamp: "Optional[Union[float, datetime]]" = None) -> None: + warnings.warn( + "span.finish() is deprecated. Use span.end() instead.", + stacklevel=2, + category=DeprecationWarning, + ) + + self.end(end_timestamp) + + def _start(self) -> None: + if self._active: + old_span = self._scope.streamed_span + self._scope.streamed_span = self + self._previous_span_on_scope = old_span + + def _end(self, end_timestamp: "Optional[Union[float, datetime]]" = None) -> None: + if self._end_timestamp is not None: + # This span is already finished, ignore. + return + + # Stop the profiler + if self._is_segment() and self._continuous_profile is not None: + with capture_internal_exceptions(): + self._continuous_profile.stop() + + # Detach from scope + if self._active: + with capture_internal_exceptions(): + old_span = self._previous_span_on_scope + del self._previous_span_on_scope + self._scope.streamed_span = old_span + + # Set attributes from the segment. These are set on span end on purpose + # so that we have the best chance to capture the segment's final name + # (since it might change during its lifetime) + self.set_attribute("sentry.segment.id", self._segment.span_id) + self.set_attribute("sentry.segment.name", self._segment.name) + + # Set the end timestamp + if end_timestamp is not None: + if isinstance(end_timestamp, (float, int)): + try: + end_timestamp = datetime.fromtimestamp(end_timestamp, timezone.utc) + except Exception: + pass + + if isinstance(end_timestamp, datetime): + self._end_timestamp = end_timestamp + else: + logger.debug( + "[Tracing] Failed to set end_timestamp. Using current time instead." + ) + + if self._end_timestamp is None: + elapsed = nanosecond_time() - self._start_timestamp_monotonic_ns + self._end_timestamp = self._start_timestamp + timedelta( + microseconds=elapsed / 1000 + ) + + client = sentry_sdk.get_client() + if not client.is_active(): + return + + # Finally, queue the span for sending to Sentry + self._scope._capture_span(self) + + def get_attributes(self) -> "Attributes": + return self._attributes + + def set_attribute(self, key: str, value: "AttributeValue") -> None: + self._attributes[key] = format_attribute(value) + + def set_attributes(self, attributes: "Attributes") -> None: + for key, value in attributes.items(): + self.set_attribute(key, value) + + def remove_attribute(self, key: str) -> None: + try: + del self._attributes[key] + except KeyError: + pass + + @property + def status(self) -> "str": + return self._status + + @status.setter + def status(self, status: "Union[SpanStatus, str]") -> None: + if isinstance(status, Enum): + status = status.value + + if status not in _VALID_SPAN_STATUSES: + logger.debug( + f'[Tracing] Unsupported span status {status}. Expected one of: "ok", "error"' + ) + return + + self._status = status + + @property + def name(self) -> str: + return self._name + + @name.setter + def name(self, name: str) -> None: + self._name = name + + @property + def active(self) -> bool: + return self._active + + @property + def span_id(self) -> str: + if not self._span_id: + self._span_id = uuid.uuid4().hex[16:] + + return self._span_id + + @property + def trace_id(self) -> str: + if not self._trace_id: + self._trace_id = uuid.uuid4().hex + + return self._trace_id + + @property + def sampled(self) -> "Optional[bool]": + return True + + @property + def start_timestamp(self) -> "Optional[datetime]": + return self._start_timestamp + + @property + def end_timestamp(self) -> "Optional[datetime]": + return self._end_timestamp + + def _is_segment(self) -> bool: + return self._segment is self + + def _update_active_thread(self) -> None: + thread_id, thread_name = get_current_thread_meta() + + if thread_id is not None: + self.set_attribute(SPANDATA.THREAD_ID, str(thread_id)) + + if thread_name is not None: + self.set_attribute(SPANDATA.THREAD_NAME, thread_name) + + def _dynamic_sampling_context(self) -> "dict[str, str]": + return self._segment._get_baggage().dynamic_sampling_context() + + def _to_traceparent(self) -> str: + if self.sampled is True: + sampled = "1" + elif self.sampled is False: + sampled = "0" + else: + sampled = None + + traceparent = "%s-%s" % (self.trace_id, self.span_id) + if sampled is not None: + traceparent += "-%s" % (sampled,) + + return traceparent + + def _to_baggage(self) -> "Optional[Baggage]": + if self._segment: + return self._segment._get_baggage() + return None + + def _get_baggage(self) -> "Baggage": + """ + Return the :py:class:`~sentry_sdk.tracing_utils.Baggage` associated with + the segment. + + The first time a new baggage with Sentry items is made, it will be frozen. + """ + if not self._baggage or self._baggage.mutable: + self._baggage = Baggage.populate_from_segment(self) + + return self._baggage + + def _iter_headers(self) -> "Iterator[tuple[str, str]]": + if not self._segment: + return + + yield SENTRY_TRACE_HEADER_NAME, self._to_traceparent() + + baggage = self._segment._get_baggage().serialize() + if baggage: + yield BAGGAGE_HEADER_NAME, baggage + + def _get_trace_context(self) -> "dict[str, Any]": + # Even if spans themselves are not event-based anymore, we need this + # to populate trace context on events + context: "dict[str, Any]" = { + "trace_id": self.trace_id, + "span_id": self.span_id, + "parent_span_id": self._parent_span_id, + "dynamic_sampling_context": self._dynamic_sampling_context(), + } + + if "sentry.op" in self._attributes: + context["op"] = self._attributes["sentry.op"] + if "sentry.origin" in self._attributes: + context["origin"] = self._attributes["sentry.origin"] + + return context + + def _set_profile_id(self, profiler_id: "Optional[str]") -> None: + if profiler_id is not None: + self.set_attribute("sentry.profiler_id", profiler_id) + + def _start_profile(self) -> None: + if not self._is_segment(): + return + + try_autostart_continuous_profiler() + + self._continuous_profile = try_profile_lifecycle_trace_start() + + def _set_segment_attributes(self) -> None: + if not self._is_segment(): + return + + self.set_attribute("process.command_args", sys.argv) + + +class NoOpStreamedSpan(StreamedSpan): + __slots__ = ( + "_finished", + "_unsampled_reason", + ) + + def __init__( + self, + unsampled_reason: "Optional[str]" = None, + scope: "Optional[sentry_sdk.Scope]" = None, + ) -> None: + self._scope = scope # type: ignore[assignment] + self._unsampled_reason = unsampled_reason + + self._finished = False + + self._start() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}(sampled={self.sampled})>" + + def __enter__(self) -> "NoOpStreamedSpan": + return self + + def __exit__( + self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]" + ) -> None: + self._end() + + def _start(self) -> None: + if self._scope is None: + return + + old_span = self._scope.streamed_span + self._scope.streamed_span = self + self._previous_span_on_scope = old_span + + def _end(self, end_timestamp: "Optional[Union[float, datetime]]" = None) -> None: + if self._finished: + return + + if self._unsampled_reason is not None: + client = sentry_sdk.get_client() + if client.is_active() and client.transport: + logger.debug( + f"[Tracing] Discarding span because sampled=False (reason: {self._unsampled_reason})" + ) + client.transport.record_lost_event( + reason=self._unsampled_reason, + data_category="span", + quantity=1, + ) + + if self._scope and hasattr(self, "_previous_span_on_scope"): + with capture_internal_exceptions(): + old_span = self._previous_span_on_scope + del self._previous_span_on_scope + self._scope.streamed_span = old_span + + self._finished = True + + def end(self, end_timestamp: "Optional[Union[float, datetime]]" = None) -> None: + self._end() + + def finish(self, end_timestamp: "Optional[Union[float, datetime]]" = None) -> None: + warnings.warn( + "span.finish() is deprecated. Use span.end() instead.", + stacklevel=2, + category=DeprecationWarning, + ) + + self._end() + + def get_attributes(self) -> "Attributes": + return {} + + def set_attribute(self, key: str, value: "AttributeValue") -> None: + pass + + def set_attributes(self, attributes: "Attributes") -> None: + pass + + def remove_attribute(self, key: str) -> None: + pass + + def _is_segment(self) -> bool: + return self._scope is not None + + @property + def status(self) -> "str": + return SpanStatus.OK.value + + @status.setter + def status(self, status: "Union[SpanStatus, str]") -> None: + pass + + @property + def name(self) -> str: + return "" + + @name.setter + def name(self, value: str) -> None: + pass + + @property + def active(self) -> bool: + return True + + @property + def span_id(self) -> str: + return "0000000000000000" + + @property + def trace_id(self) -> str: + return "00000000000000000000000000000000" + + @property + def sampled(self) -> "Optional[bool]": + return False + + @property + def start_timestamp(self) -> "Optional[datetime]": + return None + + @property + def end_timestamp(self) -> "Optional[datetime]": + return None + + +if TYPE_CHECKING: + + @overload + def trace( + func: "Callable[P, R]", + ) -> "Callable[P, R]": ... + + @overload + def trace( + func: None = None, + *, + name: "Optional[str]" = None, + attributes: "Optional[dict[str, Any]]" = None, + active: bool = True, + ) -> "Callable[[Callable[P, R]], Callable[P, R]]": ... + + +def trace( + func: "Optional[Callable[P, R]]" = None, + *, + name: "Optional[str]" = None, + attributes: "Optional[dict[str, Any]]" = None, + active: bool = True, +) -> "Union[Callable[P, R], Callable[[Callable[P, R]], Callable[P, R]]]": + """ + Decorator to start a span around a function call. + + EXPERIMENTAL. Use @sentry_sdk.trace instead. + + This decorator automatically creates a new span when the decorated function + is called, and finishes the span when the function returns or raises an exception. + + :param func: The function to trace. When used as a decorator without parentheses, + this is the function being decorated. When used with parameters (e.g., + ``@trace(op="custom")``, this should be None. + :type func: Callable or None + + :param name: The human-readable name/description for the span. If not provided, + defaults to the function name. This provides more specific details about + what the span represents (e.g., "GET /api/users", "process_user_data"). + :type name: str or None + + :param attributes: A dictionary of key-value pairs to add as attributes to the span. + Attribute values must be strings, integers, floats, or booleans. These + attributes provide additional context about the span's execution. + :type attributes: dict[str, Any] or None + + :param active: Controls whether spans started while this span is running + will automatically become its children. That's the default behavior. If + you want to create a span that shouldn't have any children (unless + provided explicitly via the `parent_span` argument), set this to False. + :type active: bool + + :returns: When used as ``@trace``, returns the decorated function. When used as + ``@trace(...)`` with parameters, returns a decorator function. + :rtype: Callable or decorator function + + Example:: + + import sentry_sdk + + # Simple usage with default values + @sentry_sdk.trace + def process_data(): + # Function implementation + pass + + # With custom parameters + @sentry_sdk.trace( + name="Get user data", + attributes={"postgres": True} + ) + def make_db_query(sql): + # Function implementation + pass + """ + from sentry_sdk.tracing_utils import ( + create_streaming_span_decorator, + ) + + decorator = create_streaming_span_decorator( + name=name, + attributes=attributes, + active=active, + ) + + if func: + return decorator(func) + else: + return decorator + + +def _get_current_streamed_span( + scope: "Optional[sentry_sdk.Scope]" = None, +) -> "Optional[StreamedSpan]": + """ + Returns the currently active span on the scope if the span is a `StreamedSpan`, otherwise `None`. + + This function will only return a non-`None` value when the streaming trace lifecycle is enabled. + To enable the lifecycle, pass `_experiments={"trace_lifecycle": "stream"}` to `sentry.init()`. + """ + scope = scope or sentry_sdk.get_current_scope() + current_span = scope.streamed_span + return current_span diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/tracing.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf2527fe3cccc3250e7b7778b22369046eb73a2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/tracing.py @@ -0,0 +1,1475 @@ +import uuid +import warnings +from datetime import datetime, timedelta, timezone +from enum import Enum +from typing import TYPE_CHECKING + +import sentry_sdk +from sentry_sdk.consts import INSTRUMENTER, SPANDATA, SPANSTATUS, SPANTEMPLATE +from sentry_sdk.profiler.continuous_profiler import get_profiler_id +from sentry_sdk.utils import ( + capture_internal_exceptions, + get_current_thread_meta, + is_valid_sample_rate, + logger, + nanosecond_time, + should_be_treated_as_error, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping, MutableMapping + from typing import ( + Any, + Dict, + Iterator, + List, + Optional, + ParamSpec, + Tuple, + TypeVar, + Union, + overload, + ) + + from typing_extensions import TypedDict, Unpack + + P = ParamSpec("P") + R = TypeVar("R") + + from sentry_sdk._types import ( + Event, + MeasurementUnit, + MeasurementValue, + SamplingContext, + ) + from sentry_sdk.profiler.continuous_profiler import ContinuousProfile + from sentry_sdk.profiler.transaction_profiler import Profile + + class SpanKwargs(TypedDict, total=False): + trace_id: str + """ + The trace ID of the root span. If this new span is to be the root span, + omit this parameter, and a new trace ID will be generated. + """ + + span_id: str + """The span ID of this span. If omitted, a new span ID will be generated.""" + + parent_span_id: str + """The span ID of the parent span, if applicable.""" + + same_process_as_parent: bool + """Whether this span is in the same process as the parent span.""" + + sampled: bool + """ + Whether the span should be sampled. Overrides the default sampling decision + for this span when provided. + """ + + op: str + """ + The span's operation. A list of recommended values is available here: + https://develop.sentry.dev/sdk/performance/span-operations/ + """ + + description: str + """A description of what operation is being performed within the span. This argument is DEPRECATED. Please use the `name` parameter, instead.""" + + hub: "Optional[sentry_sdk.Hub]" + """The hub to use for this span. This argument is DEPRECATED. Please use the `scope` parameter, instead.""" + + status: str + """The span's status. Possible values are listed at https://develop.sentry.dev/sdk/event-payloads/span/""" + + containing_transaction: "Optional[Transaction]" + """The transaction that this span belongs to.""" + + start_timestamp: "Optional[Union[datetime, float]]" + """ + The timestamp when the span started. If omitted, the current time + will be used. + """ + + scope: "sentry_sdk.Scope" + """The scope to use for this span. If not provided, we use the current scope.""" + + origin: str + """ + The origin of the span. + See https://develop.sentry.dev/sdk/performance/trace-origin/ + Default "manual". + """ + + name: str + """A string describing what operation is being performed within the span/transaction.""" + + class TransactionKwargs(SpanKwargs, total=False): + source: str + """ + A string describing the source of the transaction name. This will be used to determine the transaction's type. + See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations for more information. + Default "custom". + """ + + parent_sampled: bool + """Whether the parent transaction was sampled. If True this transaction will be kept, if False it will be discarded.""" + + baggage: "Baggage" + """The W3C baggage header value. (see https://www.w3.org/TR/baggage/)""" + + ProfileContext = TypedDict( + "ProfileContext", + { + "profiler_id": str, + }, + ) + +BAGGAGE_HEADER_NAME = "baggage" +SENTRY_TRACE_HEADER_NAME = "sentry-trace" + + +# Transaction source +# see https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations +class TransactionSource(str, Enum): + COMPONENT = "component" + CUSTOM = "custom" + ROUTE = "route" + TASK = "task" + URL = "url" + VIEW = "view" + + def __str__(self) -> str: + return self.value + + +# These are typically high cardinality and the server hates them +LOW_QUALITY_TRANSACTION_SOURCES = [ + TransactionSource.URL, +] + +SOURCE_FOR_STYLE = { + "endpoint": TransactionSource.COMPONENT, + "function_name": TransactionSource.COMPONENT, + "handler_name": TransactionSource.COMPONENT, + "method_and_path_pattern": TransactionSource.ROUTE, + "path": TransactionSource.URL, + "route_name": TransactionSource.COMPONENT, + "route_pattern": TransactionSource.ROUTE, + "uri_template": TransactionSource.ROUTE, + "url": TransactionSource.ROUTE, +} + + +def get_span_status_from_http_code(http_status_code: int) -> str: + """ + Returns the Sentry status corresponding to the given HTTP status code. + + See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context + """ + if http_status_code < 400: + return SPANSTATUS.OK + + elif 400 <= http_status_code < 500: + if http_status_code == 403: + return SPANSTATUS.PERMISSION_DENIED + elif http_status_code == 404: + return SPANSTATUS.NOT_FOUND + elif http_status_code == 429: + return SPANSTATUS.RESOURCE_EXHAUSTED + elif http_status_code == 413: + return SPANSTATUS.FAILED_PRECONDITION + elif http_status_code == 401: + return SPANSTATUS.UNAUTHENTICATED + elif http_status_code == 409: + return SPANSTATUS.ALREADY_EXISTS + else: + return SPANSTATUS.INVALID_ARGUMENT + + elif 500 <= http_status_code < 600: + if http_status_code == 504: + return SPANSTATUS.DEADLINE_EXCEEDED + elif http_status_code == 501: + return SPANSTATUS.UNIMPLEMENTED + elif http_status_code == 503: + return SPANSTATUS.UNAVAILABLE + else: + return SPANSTATUS.INTERNAL_ERROR + + return SPANSTATUS.UNKNOWN_ERROR + + +class _SpanRecorder: + """Limits the number of spans recorded in a transaction.""" + + __slots__ = ("maxlen", "spans", "dropped_spans") + + def __init__(self, maxlen: int) -> None: + # FIXME: this is `maxlen - 1` only to preserve historical behavior + # enforced by tests. + # Either this should be changed to `maxlen` or the JS SDK implementation + # should be changed to match a consistent interpretation of what maxlen + # limits: either transaction+spans or only child spans. + self.maxlen = maxlen - 1 + self.spans: "List[Span]" = [] + self.dropped_spans: int = 0 + + def add(self, span: "Span") -> None: + if len(self.spans) > self.maxlen: + span._span_recorder = None + self.dropped_spans += 1 + else: + self.spans.append(span) + + +class Span: + """A span holds timing information of a block of code. + Spans can have multiple child spans thus forming a span tree. + + :param trace_id: The trace ID of the root span. If this new span is to be the root span, + omit this parameter, and a new trace ID will be generated. + :param span_id: The span ID of this span. If omitted, a new span ID will be generated. + :param parent_span_id: The span ID of the parent span, if applicable. + :param same_process_as_parent: Whether this span is in the same process as the parent span. + :param sampled: Whether the span should be sampled. Overrides the default sampling decision + for this span when provided. + :param op: The span's operation. A list of recommended values is available here: + https://develop.sentry.dev/sdk/performance/span-operations/ + :param description: A description of what operation is being performed within the span. + + .. deprecated:: 2.15.0 + Please use the `name` parameter, instead. + :param name: A string describing what operation is being performed within the span. + :param hub: The hub to use for this span. + + .. deprecated:: 2.0.0 + Please use the `scope` parameter, instead. + :param status: The span's status. Possible values are listed at + https://develop.sentry.dev/sdk/event-payloads/span/ + :param containing_transaction: The transaction that this span belongs to. + :param start_timestamp: The timestamp when the span started. If omitted, the current time + will be used. + :param scope: The scope to use for this span. If not provided, we use the current scope. + """ + + __slots__ = ( + "_trace_id", + "_span_id", + "parent_span_id", + "same_process_as_parent", + "sampled", + "op", + "description", + "_measurements", + "start_timestamp", + "_start_timestamp_monotonic_ns", + "status", + "timestamp", + "_tags", + "_data", + "_span_recorder", + "hub", + "_context_manager_state", + "_containing_transaction", + "scope", + "origin", + "name", + "_flags", + "_flags_capacity", + ) + + def __init__( + self, + trace_id: "Optional[str]" = None, + span_id: "Optional[str]" = None, + parent_span_id: "Optional[str]" = None, + same_process_as_parent: bool = True, + sampled: "Optional[bool]" = None, + op: "Optional[str]" = None, + description: "Optional[str]" = None, + hub: "Optional[sentry_sdk.Hub]" = None, # deprecated + status: "Optional[str]" = None, + containing_transaction: "Optional[Transaction]" = None, + start_timestamp: "Optional[Union[datetime, float]]" = None, + scope: "Optional[sentry_sdk.Scope]" = None, + origin: str = "manual", + name: "Optional[str]" = None, + ) -> None: + self._trace_id = trace_id + self._span_id = span_id + self.parent_span_id = parent_span_id + self.same_process_as_parent = same_process_as_parent + self.sampled = sampled + self.op = op + self.description = name or description + self.status = status + self.hub = hub # backwards compatibility + self.scope = scope + self.origin = origin + self._measurements: "Dict[str, MeasurementValue]" = {} + self._tags: "MutableMapping[str, str]" = {} + self._data: "Dict[str, Any]" = {} + self._containing_transaction = containing_transaction + self._flags: "Dict[str, bool]" = {} + self._flags_capacity = 10 + + if hub is not None: + warnings.warn( + "The `hub` parameter is deprecated. Please use `scope` instead.", + DeprecationWarning, + stacklevel=2, + ) + + self.scope = self.scope or hub.scope + + if start_timestamp is None: + start_timestamp = datetime.now(timezone.utc) + elif isinstance(start_timestamp, float): + start_timestamp = datetime.fromtimestamp(start_timestamp, timezone.utc) + self.start_timestamp = start_timestamp + try: + # profiling depends on this value and requires that + # it is measured in nanoseconds + self._start_timestamp_monotonic_ns = nanosecond_time() + except AttributeError: + pass + + #: End timestamp of span + self.timestamp: "Optional[datetime]" = None + + self._span_recorder: "Optional[_SpanRecorder]" = None + + self.update_active_thread() + self.set_profiler_id(get_profiler_id()) + + # TODO this should really live on the Transaction class rather than the Span + # class + def init_span_recorder(self, maxlen: int) -> None: + if self._span_recorder is None: + self._span_recorder = _SpanRecorder(maxlen) + + @property + def trace_id(self) -> str: + if not self._trace_id: + self._trace_id = uuid.uuid4().hex + + return self._trace_id + + @trace_id.setter + def trace_id(self, value: str) -> None: + self._trace_id = value + + @property + def span_id(self) -> str: + if not self._span_id: + self._span_id = uuid.uuid4().hex[16:] + + return self._span_id + + @span_id.setter + def span_id(self, value: str) -> None: + self._span_id = value + + def __repr__(self) -> str: + return ( + "<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, origin=%r)>" + % ( + self.__class__.__name__, + self.op, + self.description, + self.trace_id, + self.span_id, + self.parent_span_id, + self.sampled, + self.origin, + ) + ) + + def __enter__(self) -> "Span": + scope = self.scope or sentry_sdk.get_current_scope() + old_span = scope.span + scope.span = self + self._context_manager_state = (scope, old_span) + return self + + def __exit__( + self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]" + ) -> None: + if value is not None and should_be_treated_as_error(ty, value): + self.set_status(SPANSTATUS.INTERNAL_ERROR) + + with capture_internal_exceptions(): + scope, old_span = self._context_manager_state + del self._context_manager_state + self.finish(scope) + scope.span = old_span + + @property + def containing_transaction(self) -> "Optional[Transaction]": + """The ``Transaction`` that this span belongs to. + The ``Transaction`` is the root of the span tree, + so one could also think of this ``Transaction`` as the "root span".""" + + # this is a getter rather than a regular attribute so that transactions + # can return `self` here instead (as a way to prevent them circularly + # referencing themselves) + return self._containing_transaction + + def start_child( + self, instrumenter: str = INSTRUMENTER.SENTRY, **kwargs: "Any" + ) -> "Span": + """ + Start a sub-span from the current span or transaction. + + Takes the same arguments as the initializer of :py:class:`Span`. The + trace id, sampling decision, transaction pointer, and span recorder are + inherited from the current span/transaction. + + The instrumenter parameter is deprecated for user code, and it will + be removed in the next major version. Going forward, it should only + be used by the SDK itself. + """ + if kwargs.get("description") is not None: + warnings.warn( + "The `description` parameter is deprecated. Please use `name` instead.", + DeprecationWarning, + stacklevel=2, + ) + + configuration_instrumenter = sentry_sdk.get_client().options["instrumenter"] + + if instrumenter != configuration_instrumenter: + return NoOpSpan() + + kwargs.setdefault("sampled", self.sampled) + + child = Span( + trace_id=self.trace_id, + parent_span_id=self.span_id, + containing_transaction=self.containing_transaction, + **kwargs, + ) + + span_recorder = ( + self.containing_transaction and self.containing_transaction._span_recorder + ) + if span_recorder: + span_recorder.add(child) + + return child + + @classmethod + def continue_from_environ( + cls, + environ: "Mapping[str, str]", + **kwargs: "Any", + ) -> "Transaction": + """ + DEPRECATED: Use :py:meth:`sentry_sdk.continue_trace`. + + Create a Transaction with the given params, then add in data pulled from + the ``sentry-trace`` and ``baggage`` headers from the environ (if any) + before returning the Transaction. + + This is different from :py:meth:`~sentry_sdk.tracing.Span.continue_from_headers` + in that it assumes header names in the form ``HTTP_HEADER_NAME`` - + such as you would get from a WSGI/ASGI environ - + rather than the form ``header-name``. + + :param environ: The ASGI/WSGI environ to pull information from. + """ + return Transaction.continue_from_headers(EnvironHeaders(environ), **kwargs) + + @classmethod + def continue_from_headers( + cls, + headers: "Mapping[str, str]", + *, + _sample_rand: "Optional[str]" = None, + **kwargs: "Any", + ) -> "Transaction": + """ + DEPRECATED: Use :py:meth:`sentry_sdk.continue_trace`. + + Create a transaction with the given params (including any data pulled from + the ``sentry-trace`` and ``baggage`` headers). + + :param headers: The dictionary with the HTTP headers to pull information from. + :param _sample_rand: If provided, we override the sample_rand value from the + incoming headers with this value. (internal use only) + """ + logger.warning("Deprecated: use sentry_sdk.continue_trace instead.") + + # TODO-neel move away from this kwargs stuff, it's confusing and opaque + # make more explicit + baggage = Baggage.from_incoming_header( + headers.get(BAGGAGE_HEADER_NAME), _sample_rand=_sample_rand + ) + kwargs.update({BAGGAGE_HEADER_NAME: baggage}) + + sentrytrace_kwargs = extract_sentrytrace_data( + headers.get(SENTRY_TRACE_HEADER_NAME) + ) + + if sentrytrace_kwargs is not None: + kwargs.update(sentrytrace_kwargs) + + # If there's an incoming sentry-trace but no incoming baggage header, + # for instance in traces coming from older SDKs, + # baggage will be empty and immutable and won't be populated as head SDK. + baggage.freeze() + + transaction = Transaction(**kwargs) + transaction.same_process_as_parent = False + + return transaction + + def iter_headers(self) -> "Iterator[Tuple[str, str]]": + """ + Creates a generator which returns the span's ``sentry-trace`` and ``baggage`` headers. + If the span's containing transaction doesn't yet have a ``baggage`` value, + this will cause one to be generated and stored. + """ + if not self.containing_transaction: + # Do not propagate headers if there is no containing transaction. Otherwise, this + # span ends up being the root span of a new trace, and since it does not get sent + # to Sentry, the trace will be missing a root transaction. The dynamic sampling + # context will also be missing, breaking dynamic sampling & traces. + return + + yield SENTRY_TRACE_HEADER_NAME, self.to_traceparent() + + baggage = self.containing_transaction.get_baggage().serialize() + if baggage: + yield BAGGAGE_HEADER_NAME, baggage + + @classmethod + def from_traceparent( + cls, + traceparent: "Optional[str]", + **kwargs: "Any", + ) -> "Optional[Transaction]": + """ + DEPRECATED: Use :py:meth:`sentry_sdk.continue_trace`. + + Create a ``Transaction`` with the given params, then add in data pulled from + the given ``sentry-trace`` header value before returning the ``Transaction``. + """ + if not traceparent: + return None + + return cls.continue_from_headers( + {SENTRY_TRACE_HEADER_NAME: traceparent}, **kwargs + ) + + def to_traceparent(self) -> str: + if self.sampled is True: + sampled = "1" + elif self.sampled is False: + sampled = "0" + else: + sampled = None + + traceparent = "%s-%s" % (self.trace_id, self.span_id) + if sampled is not None: + traceparent += "-%s" % (sampled,) + + return traceparent + + def to_baggage(self) -> "Optional[Baggage]": + """Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage` + associated with this ``Span``, if any. (Taken from the root of the span tree.) + """ + if self.containing_transaction: + return self.containing_transaction.get_baggage() + return None + + def set_tag(self, key: str, value: "Any") -> None: + self._tags[key] = value + + def set_data(self, key: str, value: "Any") -> None: + self._data[key] = value + + def update_data(self, data: "Dict[str, Any]") -> None: + self._data.update(data) + + def set_flag(self, flag: str, result: bool) -> None: + if len(self._flags) < self._flags_capacity: + self._flags[flag] = result + + def set_status(self, value: str) -> None: + self.status = value + + def set_measurement( + self, name: str, value: float, unit: "MeasurementUnit" = "" + ) -> None: + """ + .. deprecated:: 2.28.0 + This function is deprecated and will be removed in the next major release. + """ + + warnings.warn( + "`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.", + DeprecationWarning, + stacklevel=2, + ) + self._measurements[name] = {"value": value, "unit": unit} + + def set_thread( + self, thread_id: "Optional[int]", thread_name: "Optional[str]" + ) -> None: + if thread_id is not None: + self.set_data(SPANDATA.THREAD_ID, str(thread_id)) + + if thread_name is not None: + self.set_data(SPANDATA.THREAD_NAME, thread_name) + + def set_profiler_id(self, profiler_id: "Optional[str]") -> None: + if profiler_id is not None: + self.set_data(SPANDATA.PROFILER_ID, profiler_id) + + def set_http_status(self, http_status: int) -> None: + self.set_tag( + "http.status_code", str(http_status) + ) # TODO-neel remove in major, we keep this for backwards compatibility + self.set_data(SPANDATA.HTTP_STATUS_CODE, http_status) + self.set_status(get_span_status_from_http_code(http_status)) + + def is_success(self) -> bool: + return self.status == "ok" + + def finish( + self, + scope: "Optional[sentry_sdk.Scope]" = None, + end_timestamp: "Optional[Union[float, datetime]]" = None, + ) -> "Optional[str]": + """ + Sets the end timestamp of the span. + + Additionally it also creates a breadcrumb from the span, + if the span represents a database or HTTP request. + + :param scope: The scope to use for this transaction. + If not provided, the current scope will be used. + :param end_timestamp: Optional timestamp that should + be used as timestamp instead of the current time. + + :return: Always ``None``. The type is ``Optional[str]`` to match + the return value of :py:meth:`sentry_sdk.tracing.Transaction.finish`. + """ + if self.timestamp is not None: + # This span is already finished, ignore. + return None + + try: + if end_timestamp: + if isinstance(end_timestamp, float): + end_timestamp = datetime.fromtimestamp(end_timestamp, timezone.utc) + self.timestamp = end_timestamp + else: + elapsed = nanosecond_time() - self._start_timestamp_monotonic_ns + self.timestamp = self.start_timestamp + timedelta( + microseconds=elapsed / 1000 + ) + except AttributeError: + self.timestamp = datetime.now(timezone.utc) + + scope = scope or sentry_sdk.get_current_scope() + + # Copy conversation_id from scope to span data if this is an AI span + conversation_id = scope.get_conversation_id() + if conversation_id: + has_ai_op = SPANDATA.GEN_AI_OPERATION_NAME in self._data + is_ai_span_op = self.op is not None and ( + self.op.startswith("ai.") or self.op.startswith("gen_ai.") + ) + if has_ai_op or is_ai_span_op: + self.set_data("gen_ai.conversation.id", conversation_id) + + maybe_create_breadcrumbs_from_span(scope, self) + + return None + + def to_json(self) -> "Dict[str, Any]": + """Returns a JSON-compatible representation of the span.""" + + rv: "Dict[str, Any]" = { + "trace_id": self.trace_id, + "span_id": self.span_id, + "parent_span_id": self.parent_span_id, + "same_process_as_parent": self.same_process_as_parent, + "op": self.op, + "description": self.description, + "start_timestamp": self.start_timestamp, + "timestamp": self.timestamp, + "origin": self.origin, + } + + if self.status: + rv["status"] = self.status + # TODO-neel remove redundant tag in major + self._tags["status"] = self.status + + if len(self._measurements) > 0: + rv["measurements"] = self._measurements + + tags = self._tags + if tags: + rv["tags"] = tags + + data = {} + data.update(self._flags) + data.update(self._data) + if data: + rv["data"] = data + + return rv + + def get_trace_context(self) -> "Any": + rv: "Dict[str, Any]" = { + "trace_id": self.trace_id, + "span_id": self.span_id, + "parent_span_id": self.parent_span_id, + "op": self.op, + "description": self.description, + "origin": self.origin, + } + if self.status: + rv["status"] = self.status + + if self.containing_transaction: + rv["dynamic_sampling_context"] = ( + self.containing_transaction.get_baggage().dynamic_sampling_context() + ) + + data = {} + + thread_id = self._data.get(SPANDATA.THREAD_ID) + if thread_id is not None: + data["thread.id"] = thread_id + + thread_name = self._data.get(SPANDATA.THREAD_NAME) + if thread_name is not None: + data["thread.name"] = thread_name + + if data: + rv["data"] = data + + return rv + + def get_profile_context(self) -> "Optional[ProfileContext]": + profiler_id = self._data.get(SPANDATA.PROFILER_ID) + if profiler_id is None: + return None + + return { + "profiler_id": profiler_id, + } + + def update_active_thread(self) -> None: + thread_id, thread_name = get_current_thread_meta() + self.set_thread(thread_id, thread_name) + + # Private aliases matching StreamedSpan's private API + _to_traceparent = to_traceparent + _to_baggage = to_baggage + _iter_headers = iter_headers + _get_trace_context = get_trace_context + + +class Transaction(Span): + """The Transaction is the root element that holds all the spans + for Sentry performance instrumentation. + + :param name: Identifier of the transaction. + Will show up in the Sentry UI. + :param parent_sampled: Whether the parent transaction was sampled. + If True this transaction will be kept, if False it will be discarded. + :param baggage: The W3C baggage header value. + (see https://www.w3.org/TR/baggage/) + :param source: A string describing the source of the transaction name. + This will be used to determine the transaction's type. + See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations + for more information. Default "custom". + :param kwargs: Additional arguments to be passed to the Span constructor. + See :py:class:`sentry_sdk.tracing.Span` for available arguments. + """ + + __slots__ = ( + "name", + "source", + "parent_sampled", + # used to create baggage value for head SDKs in dynamic sampling + "sample_rate", + "_measurements", + "_contexts", + "_profile", + "_continuous_profile", + "_baggage", + "_sample_rand", + ) + + def __init__( # type: ignore[misc] + self, + name: str = "", + parent_sampled: "Optional[bool]" = None, + baggage: "Optional[Baggage]" = None, + source: str = TransactionSource.CUSTOM, + **kwargs: "Unpack[SpanKwargs]", + ) -> None: + super().__init__(**kwargs) + + self.name = name + self.source = source + self.sample_rate: "Optional[float]" = None + self.parent_sampled = parent_sampled + self._measurements: "Dict[str, MeasurementValue]" = {} + self._contexts: "Dict[str, Any]" = {} + self._profile: "Optional[Profile]" = None + self._continuous_profile: "Optional[ContinuousProfile]" = None + self._baggage = baggage + + baggage_sample_rand = ( + None if self._baggage is None else self._baggage._sample_rand() + ) + if baggage_sample_rand is not None: + self._sample_rand = baggage_sample_rand + else: + self._sample_rand = _generate_sample_rand(self.trace_id) + + def __repr__(self) -> str: + return ( + "<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, source=%r, origin=%r)>" + % ( + self.__class__.__name__, + self.name, + self.op, + self.trace_id, + self.span_id, + self.parent_span_id, + self.sampled, + self.source, + self.origin, + ) + ) + + def _possibly_started(self) -> bool: + """Returns whether the transaction might have been started. + + If this returns False, we know that the transaction was not started + with sentry_sdk.start_transaction, and therefore the transaction will + be discarded. + """ + + # We must explicitly check self.sampled is False since self.sampled can be None + return self._span_recorder is not None or self.sampled is False + + def __enter__(self) -> "Transaction": + if not self._possibly_started(): + logger.debug( + "Transaction was entered without being started with sentry_sdk.start_transaction." + "The transaction will not be sent to Sentry. To fix, start the transaction by" + "passing it to sentry_sdk.start_transaction." + ) + + super().__enter__() + + if self._profile is not None: + self._profile.__enter__() + + return self + + def __exit__( + self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]" + ) -> None: + if self._profile is not None: + self._profile.__exit__(ty, value, tb) + + if self._continuous_profile is not None: + self._continuous_profile.stop() + + super().__exit__(ty, value, tb) + + @property + def containing_transaction(self) -> "Transaction": + """The root element of the span tree. + In the case of a transaction it is the transaction itself. + """ + + # Transactions (as spans) belong to themselves (as transactions). This + # is a getter rather than a regular attribute to avoid having a circular + # reference. + return self + + def _get_scope_from_finish_args( + self, + scope_arg: "Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]", + hub_arg: "Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]", + ) -> "Optional[sentry_sdk.Scope]": + """ + Logic to get the scope from the arguments passed to finish. This + function exists for backwards compatibility with the old finish. + + TODO: Remove this function in the next major version. + """ + scope_or_hub = scope_arg + if hub_arg is not None: + warnings.warn( + "The `hub` parameter is deprecated. Please use the `scope` parameter, instead.", + DeprecationWarning, + stacklevel=3, + ) + + scope_or_hub = hub_arg + + if isinstance(scope_or_hub, sentry_sdk.Hub): + warnings.warn( + "Passing a Hub to finish is deprecated. Please pass a Scope, instead.", + DeprecationWarning, + stacklevel=3, + ) + + return scope_or_hub.scope + + return scope_or_hub + + def _get_log_representation(self) -> str: + return "{op}transaction <{name}>".format( + op=("<" + self.op + "> " if self.op else ""), name=self.name + ) + + def finish( + self, + scope: "Optional[sentry_sdk.Scope]" = None, + end_timestamp: "Optional[Union[float, datetime]]" = None, + *, + hub: "Optional[sentry_sdk.Hub]" = None, + ) -> "Optional[str]": + """Finishes the transaction and sends it to Sentry. + All finished spans in the transaction will also be sent to Sentry. + + :param scope: The Scope to use for this transaction. + If not provided, the current Scope will be used. + :param end_timestamp: Optional timestamp that should + be used as timestamp instead of the current time. + :param hub: The hub to use for this transaction. + This argument is DEPRECATED. Please use the `scope` + parameter, instead. + + :return: The event ID if the transaction was sent to Sentry, + otherwise None. + """ + if self.timestamp is not None: + # This transaction is already finished, ignore. + return None + + # For backwards compatibility, we must handle the case where `scope` + # or `hub` could both either be a `Scope` or a `Hub`. + scope = self._get_scope_from_finish_args(scope, hub) + + scope = scope or self.scope or sentry_sdk.get_current_scope() + client = sentry_sdk.get_client() + + if not client.is_active(): + # We have no active client and therefore nowhere to send this transaction. + return None + + if self._span_recorder is None: + # Explicit check against False needed because self.sampled might be None + if self.sampled is False: + logger.debug("Discarding transaction because sampled = False") + else: + logger.debug( + "Discarding transaction because it was not started with sentry_sdk.start_transaction" + ) + + # This is not entirely accurate because discards here are not + # exclusively based on sample rate but also traces sampler, but + # we handle this the same here. + if client.transport and has_tracing_enabled(client.options): + if client.monitor and client.monitor.downsample_factor > 0: + reason = "backpressure" + else: + reason = "sample_rate" + + client.transport.record_lost_event(reason, data_category="transaction") + + # Only one span (the transaction itself) is discarded, since we did not record any spans here. + client.transport.record_lost_event(reason, data_category="span") + return None + + if not self.name: + logger.warning( + "Transaction has no name, falling back to ``." + ) + self.name = "" + + super().finish(scope, end_timestamp) + + status_code = self._data.get(SPANDATA.HTTP_STATUS_CODE) + if ( + status_code is not None + and status_code in client.options["trace_ignore_status_codes"] + ): + logger.debug( + "[Tracing] Discarding {transaction_description} because the HTTP status code {status_code} is matched by trace_ignore_status_codes: {trace_ignore_status_codes}".format( + transaction_description=self._get_log_representation(), + status_code=self._data[SPANDATA.HTTP_STATUS_CODE], + trace_ignore_status_codes=client.options[ + "trace_ignore_status_codes" + ], + ) + ) + if client.transport: + client.transport.record_lost_event( + "event_processor", data_category="transaction" + ) + + num_spans = len(self._span_recorder.spans) + 1 + client.transport.record_lost_event( + "event_processor", data_category="span", quantity=num_spans + ) + + self.sampled = False + + if not self.sampled: + # At this point a `sampled = None` should have already been resolved + # to a concrete decision. + if self.sampled is None: + logger.warning("Discarding transaction without sampling decision.") + + return None + + finished_spans = [] + has_gen_ai_span = False + if client.options.get("stream_gen_ai_spans", False): + for span in self._span_recorder.spans: + if span.timestamp is None: + continue + + if isinstance(span.op, str) and span.op.startswith("gen_ai."): + has_gen_ai_span = True + + finished_spans.append(span.to_json()) + else: + finished_spans = [ + span.to_json() + for span in self._span_recorder.spans + if span.timestamp is not None + ] + + len_diff = len(self._span_recorder.spans) - len(finished_spans) + dropped_spans = len_diff + self._span_recorder.dropped_spans + + # we do this to break the circular reference of transaction -> span + # recorder -> span -> containing transaction (which is where we started) + # before either the spans or the transaction goes out of scope and has + # to be garbage collected + self._span_recorder = None + + contexts = {} + contexts.update(self._contexts) + contexts.update({"trace": self.get_trace_context()}) + profile_context = self.get_profile_context() + if profile_context is not None: + contexts.update({"profile": profile_context}) + + event: "Event" = { + "type": "transaction", + "transaction": self.name, + "transaction_info": {"source": self.source}, + "contexts": contexts, + "tags": self._tags, + "timestamp": self.timestamp, + "start_timestamp": self.start_timestamp, + "spans": finished_spans, + } + + if dropped_spans > 0: + event["_dropped_spans"] = dropped_spans + + if has_gen_ai_span: + event["_has_gen_ai_span"] = True + + if self._profile is not None and self._profile.valid(): + event["profile"] = self._profile + self._profile = None + + event["measurements"] = self._measurements + + return scope.capture_event(event) + + def set_measurement( + self, name: str, value: float, unit: "MeasurementUnit" = "" + ) -> None: + """ + .. deprecated:: 2.28.0 + This function is deprecated and will be removed in the next major release. + """ + + warnings.warn( + "`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.", + DeprecationWarning, + stacklevel=2, + ) + self._measurements[name] = {"value": value, "unit": unit} + + def set_context(self, key: str, value: "dict[str, Any]") -> None: + """Sets a context. Transactions can have multiple contexts + and they should follow the format described in the "Contexts Interface" + documentation. + + :param key: The name of the context. + :param value: The information about the context. + """ + self._contexts[key] = value + + def set_http_status(self, http_status: int) -> None: + """Sets the status of the Transaction according to the given HTTP status. + + :param http_status: The HTTP status code.""" + super().set_http_status(http_status) + self.set_context("response", {"status_code": http_status}) + + def to_json(self) -> "Dict[str, Any]": + """Returns a JSON-compatible representation of the transaction.""" + rv = super().to_json() + + rv["name"] = self.name + rv["source"] = self.source + rv["sampled"] = self.sampled + + return rv + + def get_trace_context(self) -> "Any": + trace_context = super().get_trace_context() + + if self._data: + trace_context["data"] = self._data + + return trace_context + + def get_baggage(self) -> "Baggage": + """Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage` + associated with the Transaction. + + The first time a new baggage with Sentry items is made, + it will be frozen.""" + if not self._baggage or self._baggage.mutable: + self._baggage = Baggage.populate_from_transaction(self) + + return self._baggage + + def _set_initial_sampling_decision( + self, sampling_context: "SamplingContext" + ) -> None: + """ + Sets the transaction's sampling decision, according to the following + precedence rules: + + 1. If a sampling decision is passed to `start_transaction` + (`start_transaction(name: "my transaction", sampled: True)`), that + decision will be used, regardless of anything else + + 2. If `traces_sampler` is defined, its decision will be used. It can + choose to keep or ignore any parent sampling decision, or use the + sampling context data to make its own decision or to choose a sample + rate for the transaction. + + 3. If `traces_sampler` is not defined, but there's a parent sampling + decision, the parent sampling decision will be used. + + 4. If `traces_sampler` is not defined and there's no parent sampling + decision, `traces_sample_rate` will be used. + """ + client = sentry_sdk.get_client() + + transaction_description = self._get_log_representation() + + # nothing to do if tracing is disabled + if not has_tracing_enabled(client.options): + self.sampled = False + return + + # if the user has forced a sampling decision by passing a `sampled` + # value when starting the transaction, go with that + if self.sampled is not None: + self.sample_rate = float(self.sampled) + return + + # we would have bailed already if neither `traces_sampler` nor + # `traces_sample_rate` were defined, so one of these should work; prefer + # the hook if so + sample_rate = ( + client.options["traces_sampler"](sampling_context) + if callable(client.options.get("traces_sampler")) + # default inheritance behavior + else ( + sampling_context["parent_sampled"] + if sampling_context["parent_sampled"] is not None + else client.options["traces_sample_rate"] + ) + ) + + # Since this is coming from the user (or from a function provided by the + # user), who knows what we might get. (The only valid values are + # booleans or numbers between 0 and 1.) + if not is_valid_sample_rate(sample_rate, source="Tracing"): + logger.warning( + "[Tracing] Discarding {transaction_description} because of invalid sample rate.".format( + transaction_description=transaction_description, + ) + ) + self.sampled = False + return + + self.sample_rate = float(sample_rate) + + if client.monitor: + self.sample_rate /= 2**client.monitor.downsample_factor + + # if the function returned 0 (or false), or if `traces_sample_rate` is + # 0, it's a sign the transaction should be dropped + if not self.sample_rate: + logger.debug( + "[Tracing] Discarding {transaction_description} because {reason}".format( + transaction_description=transaction_description, + reason=( + "traces_sampler returned 0 or False" + if callable(client.options.get("traces_sampler")) + else "traces_sample_rate is set to 0" + ), + ) + ) + self.sampled = False + return + + # Now we roll the dice. + self.sampled = self._sample_rand < self.sample_rate + + if self.sampled: + logger.debug( + "[Tracing] Starting {transaction_description}".format( + transaction_description=transaction_description, + ) + ) + else: + logger.debug( + "[Tracing] Discarding {transaction_description} because it's not included in the random sample (sampling rate = {sample_rate})".format( + transaction_description=transaction_description, + sample_rate=self.sample_rate, + ) + ) + + # Private aliases matching StreamedSpan's private API + _get_baggage = get_baggage + _get_trace_context = get_trace_context + + +class NoOpSpan(Span): + def __repr__(self) -> str: + return "<%s>" % self.__class__.__name__ + + @property + def containing_transaction(self) -> "Optional[Transaction]": + return None + + def start_child( + self, instrumenter: str = INSTRUMENTER.SENTRY, **kwargs: "Any" + ) -> "NoOpSpan": + return NoOpSpan() + + def to_traceparent(self) -> str: + return "" + + def to_baggage(self) -> "Optional[Baggage]": + return None + + def get_baggage(self) -> "Optional[Baggage]": + return None + + def iter_headers(self) -> "Iterator[Tuple[str, str]]": + return iter(()) + + def set_tag(self, key: str, value: "Any") -> None: + pass + + def set_data(self, key: str, value: "Any") -> None: + pass + + def update_data(self, data: "Dict[str, Any]") -> None: + pass + + def set_status(self, value: str) -> None: + pass + + def set_http_status(self, http_status: int) -> None: + pass + + def is_success(self) -> bool: + return True + + def to_json(self) -> "Dict[str, Any]": + return {} + + def get_trace_context(self) -> "Any": + return {} + + def get_profile_context(self) -> "Any": + return {} + + def finish( + self, + scope: "Optional[sentry_sdk.Scope]" = None, + end_timestamp: "Optional[Union[float, datetime]]" = None, + *, + hub: "Optional[sentry_sdk.Hub]" = None, + ) -> "Optional[str]": + """ + The `hub` parameter is deprecated. Please use the `scope` parameter, instead. + """ + pass + + def set_measurement( + self, name: str, value: float, unit: "MeasurementUnit" = "" + ) -> None: + pass + + def set_context(self, key: str, value: "dict[str, Any]") -> None: + pass + + def init_span_recorder(self, maxlen: int) -> None: + pass + + def _set_initial_sampling_decision( + self, sampling_context: "SamplingContext" + ) -> None: + pass + + # Private aliases matching StreamedSpan's private API + _to_traceparent = to_traceparent + _to_baggage = to_baggage + _get_baggage = get_baggage + _iter_headers = iter_headers + _get_trace_context = get_trace_context + + +if TYPE_CHECKING: + + @overload + def trace( + func: None = None, + *, + op: "Optional[str]" = None, + name: "Optional[str]" = None, + attributes: "Optional[dict[str, Any]]" = None, + template: "SPANTEMPLATE" = SPANTEMPLATE.DEFAULT, + ) -> "Callable[[Callable[P, R]], Callable[P, R]]": + # Handles: @trace() and @trace(op="custom") + pass + + @overload + def trace(func: "Callable[P, R]") -> "Callable[P, R]": + # Handles: @trace + pass + + +def trace( + func: "Optional[Callable[P, R]]" = None, + *, + op: "Optional[str]" = None, + name: "Optional[str]" = None, + attributes: "Optional[dict[str, Any]]" = None, + template: "SPANTEMPLATE" = SPANTEMPLATE.DEFAULT, +) -> "Union[Callable[P, R], Callable[[Callable[P, R]], Callable[P, R]]]": + """ + Decorator to start a child span around a function call. + + This decorator automatically creates a new span when the decorated function + is called, and finishes the span when the function returns or raises an exception. + + :param func: The function to trace. When used as a decorator without parentheses, + this is the function being decorated. When used with parameters (e.g., + ``@trace(op="custom")``, this should be None. + :type func: Callable or None + + :param op: The operation name for the span. This is a high-level description + of what the span represents (e.g., "http.client", "db.query"). + You can use predefined constants from :py:class:`sentry_sdk.consts.OP` + or provide your own string. If not provided, a default operation will + be assigned based on the template. + :type op: str or None + + :param name: The human-readable name/description for the span. If not provided, + defaults to the function name. This provides more specific details about + what the span represents (e.g., "GET /api/users", "process_user_data"). + :type name: str or None + + :param attributes: A dictionary of key-value pairs to add as attributes to the span. + Attribute values must be strings, integers, floats, or booleans. These + attributes provide additional context about the span's execution. + :type attributes: dict[str, Any] or None + + :param template: The type of span to create. This determines what kind of + span instrumentation and data collection will be applied. Use predefined + constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`. + The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most + use cases. + :type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE` + + :returns: When used as ``@trace``, returns the decorated function. When used as + ``@trace(...)`` with parameters, returns a decorator function. + :rtype: Callable or decorator function + + Example:: + + import sentry_sdk + from sentry_sdk.consts import OP, SPANTEMPLATE + + # Simple usage with default values + @sentry_sdk.trace + def process_data(): + # Function implementation + pass + + # With custom parameters + @sentry_sdk.trace( + op=OP.DB_QUERY, + name="Get user data", + attributes={"postgres": True} + ) + def make_db_query(sql): + # Function implementation + pass + + # With a custom template + @sentry_sdk.trace(template=SPANTEMPLATE.AI_TOOL) + def calculate_interest_rate(amount, rate, years): + # Function implementation + pass + """ + from sentry_sdk.tracing_utils import create_span_decorator + + decorator = create_span_decorator( + op=op, + name=name, + attributes=attributes, + template=template, + ) + + if func: + return decorator(func) + else: + return decorator + + +# Circular imports + +from sentry_sdk.tracing_utils import ( + Baggage, + EnvironHeaders, + _generate_sample_rand, + extract_sentrytrace_data, + has_tracing_enabled, + maybe_create_breadcrumbs_from_span, +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/tracing_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/tracing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8986759885003dfc7134fc8b4fbf8ddeffb3f0dd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/tracing_utils.py @@ -0,0 +1,1734 @@ +import contextlib +import functools +import inspect +import os +import re +import sys +import warnings +from collections.abc import Mapping, MutableMapping +from datetime import datetime, timedelta, timezone +from random import Random +from urllib.parse import quote, unquote +import uuid + +try: + from re import Pattern +except ImportError: + # 3.6 + from typing import Pattern + +import sentry_sdk +from sentry_sdk.consts import OP, SPANDATA, SPANSTATUS, SPANTEMPLATE +from sentry_sdk.utils import ( + capture_internal_exceptions, + filename_for_module, + logger, + match_regex_list, + qualname_from_function, + safe_repr, + to_string, + try_convert, + is_sentry_url, + is_valid_sample_rate, + _is_external_source, + _is_in_project_root, + _module_in_list, +) +from sentry_sdk.tracing import Span as LegacySpan + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Any + from typing import Dict + from typing import Generator + from typing import Optional + from typing import Union + from typing import Iterator + from typing import Tuple + + from types import FrameType + + from sentry_sdk._types import Attributes + + +SENTRY_TRACE_REGEX = re.compile( + "^[ \t]*" # whitespace + "([0-9a-f]{32})?" # trace_id + "-?([0-9a-f]{16})?" # span_id + "-?([01])?" # sampled + "[ \t]*$" # whitespace +) + + +# This is a normal base64 regex, modified to reflect that fact that we strip the +# trailing = or == off +base64_stripped = ( + # any of the characters in the base64 "alphabet", in multiples of 4 + "([a-zA-Z0-9+/]{4})*" + # either nothing or 2 or 3 base64-alphabet characters (see + # https://en.wikipedia.org/wiki/Base64#Decoding_Base64_without_padding for + # why there's never only 1 extra character) + "([a-zA-Z0-9+/]{2,3})?" +) + + +class EnvironHeaders(Mapping): # type: ignore + def __init__( + self, + environ: "Mapping[str, str]", + prefix: str = "HTTP_", + ) -> None: + self.environ = environ + self.prefix = prefix + + def __getitem__(self, key: str) -> "Optional[Any]": + return self.environ[self.prefix + key.replace("-", "_").upper()] + + def __len__(self) -> int: + return sum(1 for _ in iter(self)) + + def __iter__(self) -> "Generator[str, None, None]": + for k in self.environ: + if not isinstance(k, str): + continue + + k = k.replace("-", "_").upper() + if not k.startswith(self.prefix): + continue + + yield k[len(self.prefix) :] + + +def has_tracing_enabled(options: "Optional[Dict[str, Any]]") -> bool: + """ + Returns True if either traces_sample_rate or traces_sampler is + defined and enable_tracing is set and not false. + """ + if options is None: + return False + + return bool( + options.get("enable_tracing") is not False + and ( + options.get("traces_sample_rate") is not None + or options.get("traces_sampler") is not None + ) + ) + + +def has_span_streaming_enabled(options: "Optional[dict[str, Any]]") -> bool: + if options is None: + return False + + return (options.get("_experiments") or {}).get("trace_lifecycle") == "stream" + + +@contextlib.contextmanager +def record_sql_queries( + cursor: "Any", + query: "Any", + params_list: "Any", + paramstyle: "Optional[str]", + executemany: bool, + record_cursor_repr: bool = False, + span_origin: str = "manual", +) -> "Generator[sentry_sdk.tracing.Span, None, None]": + # TODO: Bring back capturing of params by default + if sentry_sdk.get_client().options["_experiments"].get("record_sql_params", False): + if not params_list or params_list == [None]: + params_list = None + + if paramstyle == "pyformat": + paramstyle = "format" + else: + params_list = None + paramstyle = None + + query = _format_sql(cursor, query) + + data = {} + if params_list is not None: + data["db.params"] = params_list + if paramstyle is not None: + data["db.paramstyle"] = paramstyle + if executemany: + data["db.executemany"] = True + if record_cursor_repr and cursor is not None: + data["db.cursor"] = cursor + + with capture_internal_exceptions(): + sentry_sdk.add_breadcrumb(message=query, category="query", data=data) + + with sentry_sdk.start_span( + op=OP.DB, + name=query, + origin=span_origin, + ) as span: + for k, v in data.items(): + span.set_data(k, v) + yield span + + +# Mirrors record_sql_queries() temporarily so the Django and asyncpg integrations don't crash with span streaming enabled. +# Once both are ported, remove record_sql_queries() and rename record_sql_queries_supporting_streaming() to record_sql_queries(). +@contextlib.contextmanager +def record_sql_queries_supporting_streaming( + cursor: "Any", + query: "Any", + params_list: "Any", + paramstyle: "Optional[str]", + executemany: bool, + record_cursor_repr: bool = False, + span_origin: str = "manual", +) -> "Generator[Union[sentry_sdk.tracing.Span, sentry_sdk.traces.StreamedSpan], None, None]": + # TODO: Bring back capturing of params by default + client = sentry_sdk.get_client() + if client.options["_experiments"].get("record_sql_params", False): + if not params_list or params_list == [None]: + params_list = None + + if paramstyle == "pyformat": + paramstyle = "format" + else: + params_list = None + paramstyle = None + + query = _format_sql(cursor, query) + + data = {} + if params_list is not None: + data["db.params"] = params_list + if paramstyle is not None: + data["db.paramstyle"] = paramstyle + if executemany: + data["db.executemany"] = True + if record_cursor_repr and cursor is not None: + data["db.cursor"] = cursor + + with capture_internal_exceptions(): + sentry_sdk.add_breadcrumb(message=query, category="query", data=data) + + if has_span_streaming_enabled(client.options): + with sentry_sdk.traces.start_span( + name="" if query is None else query, + attributes={ + "sentry.origin": span_origin, + "sentry.op": OP.DB, + }, + ) as span: + yield span + else: + with sentry_sdk.start_span( + op=OP.DB, + name=query, + origin=span_origin, + ) as span: + for k, v in data.items(): + span.set_data(k, v) + yield span + + +def maybe_create_breadcrumbs_from_span( + scope: "sentry_sdk.Scope", span: "sentry_sdk.tracing.Span" +) -> None: + if span.op == OP.DB_REDIS: + scope.add_breadcrumb( + message=span.description, type="redis", category="redis", data=span._tags + ) + + elif span.op == OP.HTTP_CLIENT: + level = None + status_code = span._data.get(SPANDATA.HTTP_STATUS_CODE) + if status_code: + if 500 <= status_code <= 599: + level = "error" + elif 400 <= status_code <= 499: + level = "warning" + + if level: + scope.add_breadcrumb( + type="http", category="httplib", data=span._data, level=level + ) + else: + scope.add_breadcrumb(type="http", category="httplib", data=span._data) + + elif span.op == "subprocess": + scope.add_breadcrumb( + type="subprocess", + category="subprocess", + message=span.description, + data=span._data, + ) + + +def _get_frame_module_abs_path(frame: "FrameType") -> "Optional[str]": + try: + return frame.f_code.co_filename + except Exception: + return None + + +def _should_be_included( + is_sentry_sdk_frame: bool, + namespace: "Optional[str]", + in_app_include: "Optional[list[str]]", + in_app_exclude: "Optional[list[str]]", + abs_path: "Optional[str]", + project_root: "Optional[str]", +) -> bool: + # in_app_include takes precedence over in_app_exclude + should_be_included = _module_in_list(namespace, in_app_include) + should_be_excluded = _is_external_source(abs_path) or _module_in_list( + namespace, in_app_exclude + ) + return not is_sentry_sdk_frame and ( + should_be_included + or (_is_in_project_root(abs_path, project_root) and not should_be_excluded) + ) + + +def add_source( + span: "Union[sentry_sdk.tracing.Span, sentry_sdk.traces.StreamedSpan]", + project_root: "Optional[str]", + in_app_include: "Optional[list[str]]", + in_app_exclude: "Optional[list[str]]", +) -> None: + """ + Adds OTel compatible source code information to the span + """ + # Find the correct frame + frame: "Union[FrameType, None]" = sys._getframe() + while frame is not None: + abs_path = _get_frame_module_abs_path(frame) + + try: + namespace: "Optional[str]" = frame.f_globals.get("__name__") + except Exception: + namespace = None + + is_sentry_sdk_frame = namespace is not None and namespace.startswith( + "sentry_sdk." + ) + + should_be_included = _should_be_included( + is_sentry_sdk_frame=is_sentry_sdk_frame, + namespace=namespace, + in_app_include=in_app_include, + in_app_exclude=in_app_exclude, + abs_path=abs_path, + project_root=project_root, + ) + if should_be_included: + break + + frame = frame.f_back + else: + frame = None + + # Set the data + if frame is not None: + try: + lineno = frame.f_lineno + except Exception: + lineno = None + if lineno is not None: + if isinstance(span, LegacySpan): + span.set_data(SPANDATA.CODE_LINENO, lineno) + else: + span.set_attribute("code.line.number", lineno) + + try: + namespace = frame.f_globals.get("__name__") + except Exception: + namespace = None + if namespace is not None: + if isinstance(span, LegacySpan): + span.set_data(SPANDATA.CODE_NAMESPACE, namespace) + else: + span.set_attribute(SPANDATA.CODE_NAMESPACE, namespace) + + filepath = _get_frame_module_abs_path(frame) + if filepath is not None: + if namespace is not None: + in_app_path = filename_for_module(namespace, filepath) + elif project_root is not None and filepath.startswith(project_root): + in_app_path = filepath.replace(project_root, "").lstrip(os.sep) + else: + in_app_path = filepath + + if isinstance(span, LegacySpan): + span.set_data(SPANDATA.CODE_FILEPATH, in_app_path) + else: + if in_app_path is not None: + span.set_attribute("code.file.path", in_app_path) + + try: + code_function = frame.f_code.co_name + except Exception: + code_function = None + + if code_function is not None: + if isinstance(span, LegacySpan): + span.set_data(SPANDATA.CODE_FUNCTION, frame.f_code.co_name) + else: + span.set_attribute(SPANDATA.CODE_FUNCTION, frame.f_code.co_name) + + +def add_query_source( + span: "Union[sentry_sdk.tracing.Span, sentry_sdk.traces.StreamedSpan]", +) -> None: + """ + Adds OTel compatible source code information to a database query span + """ + client = sentry_sdk.get_client() + if not client.is_active(): + return + + if isinstance(span, LegacySpan): + # In the StreamedSpan case, we need to add the extra span information before + # the span finishes, so it's expected that this will be None. In the LegacySpan case, + # it should already be finished. + if span.timestamp is None: + return + + if span.start_timestamp is None: + return + + should_add_query_source = client.options.get("enable_db_query_source", True) + if not should_add_query_source: + return + + if isinstance(span, StreamedSpan): + end_timestamp = span.end_timestamp + else: + end_timestamp = span.timestamp + + end_timestamp = end_timestamp or datetime.now(timezone.utc) + + duration = end_timestamp - span.start_timestamp + threshold = client.options.get("db_query_source_threshold_ms", 0) + slow_query = duration / timedelta(milliseconds=1) > threshold + + if not slow_query: + return + + add_source( + span=span, + project_root=client.options["project_root"], + in_app_include=client.options.get("in_app_include"), + in_app_exclude=client.options.get("in_app_exclude"), + ) + + +def add_http_request_source( + span: "Union[sentry_sdk.tracing.Span, sentry_sdk.traces.StreamedSpan]", +) -> None: + """ + Adds OTel compatible source code information to a span for an outgoing HTTP request + """ + client = sentry_sdk.get_client() + if not client.is_active(): + return + + if isinstance(span, LegacySpan): + # In the StreamedSpan case, we need to add the extra span information before + # the span finishes, so it's expected that this will be None. In the LegacySpan case, + # it should already be finished. + if span.timestamp is None: + return + + if span.start_timestamp is None: + return + + should_add_request_source = client.options.get("enable_http_request_source", True) + if not should_add_request_source: + return + + if isinstance(span, StreamedSpan): + end_timestamp = span.end_timestamp + else: + end_timestamp = span.timestamp + + end_timestamp = end_timestamp or datetime.now(timezone.utc) + + duration = end_timestamp - span.start_timestamp + threshold = client.options.get("http_request_source_threshold_ms", 0) + slow_query = duration / timedelta(milliseconds=1) > threshold + + if not slow_query: + return + + add_source( + span=span, + project_root=client.options["project_root"], + in_app_include=client.options.get("in_app_include"), + in_app_exclude=client.options.get("in_app_exclude"), + ) + + +def extract_sentrytrace_data( + header: "Optional[str]", +) -> "Optional[Dict[str, Union[str, bool, None]]]": + """ + Given a `sentry-trace` header string, return a dictionary of data. + """ + if not header: + return None + + if header.startswith("00-") and header.endswith("-00"): + header = header[3:-3] + + match = SENTRY_TRACE_REGEX.match(header) + if not match: + return None + + trace_id, parent_span_id, sampled_str = match.groups() + parent_sampled = None + + if trace_id: + trace_id = "{:032x}".format(int(trace_id, 16)) + if parent_span_id: + parent_span_id = "{:016x}".format(int(parent_span_id, 16)) + if sampled_str: + parent_sampled = sampled_str != "0" + + return { + "trace_id": trace_id, + "parent_span_id": parent_span_id, + "parent_sampled": parent_sampled, + } + + +def _format_sql(cursor: "Any", sql: str) -> "Optional[str]": + real_sql = None + + # If we're using psycopg2, it could be that we're + # looking at a query that uses Composed objects. Use psycopg2's mogrify + # function to format the query. We lose per-parameter trimming but gain + # accuracy in formatting. + try: + if hasattr(cursor, "mogrify"): + real_sql = cursor.mogrify(sql) + if isinstance(real_sql, bytes): + real_sql = real_sql.decode(cursor.connection.encoding) + except Exception: + real_sql = None + + return real_sql or to_string(sql) + + +class PropagationContext: + """ + The PropagationContext represents the data of a trace in Sentry. + """ + + __slots__ = ( + "_trace_id", + "_span_id", + "parent_span_id", + "parent_sampled", + "baggage", + "custom_sampling_context", + ) + + def __init__( + self, + trace_id: "Optional[str]" = None, + span_id: "Optional[str]" = None, + parent_span_id: "Optional[str]" = None, + parent_sampled: "Optional[bool]" = None, + dynamic_sampling_context: "Optional[Dict[str, str]]" = None, + baggage: "Optional[Baggage]" = None, + ) -> None: + self._trace_id = trace_id + """The trace id of the Sentry trace.""" + + self._span_id = span_id + """The span id of the currently executing span.""" + + self.parent_span_id = parent_span_id + """The id of the parent span that started this span. + The parent span could also be a span in an upstream service.""" + + self.parent_sampled = parent_sampled + """Boolean indicator if the parent span was sampled. + Important when the parent span originated in an upstream service, + because we want to sample the whole trace, or nothing from the trace.""" + + self.baggage = baggage + """Parsed baggage header that is used for dynamic sampling decisions.""" + + """DEPRECATED this only exists for backwards compat of constructor.""" + if baggage is None and dynamic_sampling_context is not None: + self.baggage = Baggage(dynamic_sampling_context) + + self.custom_sampling_context: "Optional[dict[str, Any]]" = None + + @classmethod + def from_incoming_data( + cls, incoming_data: "Dict[str, Any]" + ) -> "PropagationContext": + propagation_context = PropagationContext() + normalized_data = normalize_incoming_data(incoming_data) + + sentry_trace_header = normalized_data.get(SENTRY_TRACE_HEADER_NAME) + sentrytrace_data = extract_sentrytrace_data(sentry_trace_header) + + # nothing to propagate if no sentry-trace + if sentrytrace_data is None: + return propagation_context + + baggage_header = normalized_data.get(BAGGAGE_HEADER_NAME) + baggage = ( + Baggage.from_incoming_header(baggage_header) if baggage_header else None + ) + + if not _should_continue_trace(baggage): + return propagation_context + + propagation_context.update(sentrytrace_data) + if baggage: + propagation_context.baggage = baggage + + propagation_context._fill_sample_rand() + + return propagation_context + + @property + def trace_id(self) -> str: + """The trace id of the Sentry trace.""" + if not self._trace_id: + # New trace, don't fill in sample_rand + self._trace_id = uuid.uuid4().hex + + return self._trace_id + + @trace_id.setter + def trace_id(self, value: str) -> None: + self._trace_id = value + + @property + def span_id(self) -> str: + """The span id of the currently executed span.""" + if not self._span_id: + self._span_id = uuid.uuid4().hex[16:] + + return self._span_id + + @span_id.setter + def span_id(self, value: str) -> None: + self._span_id = value + + @property + def dynamic_sampling_context(self) -> "Optional[Dict[str, Any]]": + return self.get_baggage().dynamic_sampling_context() + + def to_traceparent(self) -> str: + return f"{self.trace_id}-{self.span_id}" + + def get_baggage(self) -> "Baggage": + if self.baggage is None: + self.baggage = Baggage.populate_from_propagation_context(self) + return self.baggage + + def iter_headers(self) -> "Iterator[Tuple[str, str]]": + """ + Creates a generator which returns the propagation_context's ``sentry-trace`` and ``baggage`` headers. + """ + yield SENTRY_TRACE_HEADER_NAME, self.to_traceparent() + + baggage = self.get_baggage().serialize() + if baggage: + yield BAGGAGE_HEADER_NAME, baggage + + def update(self, other_dict: "Dict[str, Any]") -> None: + """ + Updates the PropagationContext with data from the given dictionary. + """ + for key, value in other_dict.items(): + try: + setattr(self, key, value) + except AttributeError: + pass + + def _set_custom_sampling_context( + self, custom_sampling_context: "dict[str, Any]" + ) -> None: + self.custom_sampling_context = custom_sampling_context + + def __repr__(self) -> str: + return "".format( + self._trace_id, + self._span_id, + self.parent_span_id, + self.parent_sampled, + self.baggage, + ) + + def _fill_sample_rand(self) -> None: + """ + Ensure that there is a valid sample_rand value in the baggage. + + If there is a valid sample_rand value in the baggage, we keep it. + Otherwise, we generate a sample_rand value according to the following: + + - If we have a parent_sampled value and a sample_rate in the DSC, we compute + a sample_rand value randomly in the range: + - [0, sample_rate) if parent_sampled is True, + - or, in the range [sample_rate, 1) if parent_sampled is False. + + - If either parent_sampled or sample_rate is missing, we generate a random + value in the range [0, 1). + + The sample_rand is deterministically generated from the trace_id, if present. + + This function does nothing if there is no baggage. + """ + if self.baggage is None: + return + + sample_rand = try_convert(float, self.baggage.sentry_items.get("sample_rand")) + if sample_rand is not None and 0 <= sample_rand < 1: + # sample_rand is present and valid, so don't overwrite it + return + + # Get the sample rate and compute the transformation that will map the random value + # to the desired range: [0, 1), [0, sample_rate), or [sample_rate, 1). + sample_rate = try_convert(float, self.baggage.sentry_items.get("sample_rate")) + lower, upper = _sample_rand_range(self.parent_sampled, sample_rate) + + try: + sample_rand = _generate_sample_rand(self.trace_id, interval=(lower, upper)) + except ValueError: + # ValueError is raised if the interval is invalid, i.e. lower >= upper. + # lower >= upper might happen if the incoming trace's sampled flag + # and sample_rate are inconsistent, e.g. sample_rate=0.0 but sampled=True. + # We cannot generate a sensible sample_rand value in this case. + logger.debug( + f"Could not backfill sample_rand, since parent_sampled={self.parent_sampled} " + f"and sample_rate={sample_rate}." + ) + return + + self.baggage.sentry_items["sample_rand"] = f"{sample_rand:.6f}" # noqa: E231 + + def _sample_rand(self) -> "Optional[str]": + """Convenience method to get the sample_rand value from the baggage.""" + if self.baggage is None: + return None + + return self.baggage.sentry_items.get("sample_rand") + + +class Baggage: + """ + The W3C Baggage header information (see https://www.w3.org/TR/baggage/). + + Before mutating a `Baggage` object, calling code must check that `mutable` is `True`. + Mutating a `Baggage` object that has `mutable` set to `False` is not allowed, but + it is the caller's responsibility to enforce this restriction. + """ + + __slots__ = ("sentry_items", "third_party_items", "mutable") + + SENTRY_PREFIX = "sentry-" + SENTRY_PREFIX_REGEX = re.compile("^sentry-") + + def __init__( + self, + sentry_items: "Dict[str, str]", + third_party_items: str = "", + mutable: bool = True, + ): + self.sentry_items = sentry_items + self.third_party_items = third_party_items + self.mutable = mutable + + @classmethod + def from_incoming_header( + cls, + header: "Optional[str]", + *, + _sample_rand: "Optional[str]" = None, + ) -> "Baggage": + """ + freeze if incoming header already has sentry baggage + """ + sentry_items = {} + third_party_items = "" + mutable = True + + if header: + for item in header.split(","): + if "=" not in item: + continue + + with capture_internal_exceptions(): + item = item.strip() + key, val = item.split("=") + if Baggage.SENTRY_PREFIX_REGEX.match(key): + baggage_key = unquote(key.split("-")[1]) + sentry_items[baggage_key] = unquote(val) + mutable = False + else: + third_party_items += ("," if third_party_items else "") + item + + if _sample_rand is not None: + sentry_items["sample_rand"] = str(_sample_rand) + mutable = False + + return Baggage(sentry_items, third_party_items, mutable) + + @classmethod + def from_options(cls, scope: "sentry_sdk.scope.Scope") -> "Optional[Baggage]": + """ + Deprecated: use populate_from_propagation_context + """ + if scope._propagation_context is None: + return Baggage({}) + + return Baggage.populate_from_propagation_context(scope._propagation_context) + + @classmethod + def populate_from_propagation_context( + cls, propagation_context: "PropagationContext" + ) -> "Baggage": + sentry_items: "Dict[str, str]" = {} + third_party_items = "" + mutable = False + + client = sentry_sdk.get_client() + + if not client.is_active(): + return Baggage(sentry_items) + + options = client.options + + sentry_items["trace_id"] = propagation_context.trace_id + + if options.get("environment"): + sentry_items["environment"] = options["environment"] + + if options.get("release"): + sentry_items["release"] = options["release"] + + if client.parsed_dsn: + sentry_items["public_key"] = client.parsed_dsn.public_key + if client.parsed_dsn.org_id: + sentry_items["org_id"] = client.parsed_dsn.org_id + + if options.get("traces_sample_rate"): + sentry_items["sample_rate"] = str(options["traces_sample_rate"]) + + return Baggage(sentry_items, third_party_items, mutable) + + @classmethod + def populate_from_transaction( + cls, transaction: "sentry_sdk.tracing.Transaction" + ) -> "Baggage": + """ + Populate fresh baggage entry with sentry_items and make it immutable + if this is the head SDK which originates traces. + """ + client = sentry_sdk.get_client() + sentry_items: "Dict[str, str]" = {} + + if not client.is_active(): + return Baggage(sentry_items) + + options = client.options or {} + + sentry_items["trace_id"] = transaction.trace_id + sentry_items["sample_rand"] = f"{transaction._sample_rand:.6f}" # noqa: E231 + + if options.get("environment"): + sentry_items["environment"] = options["environment"] + + if options.get("release"): + sentry_items["release"] = options["release"] + + if client.parsed_dsn: + sentry_items["public_key"] = client.parsed_dsn.public_key + if client.parsed_dsn.org_id: + sentry_items["org_id"] = client.parsed_dsn.org_id + + if ( + transaction.name + and transaction.source not in LOW_QUALITY_TRANSACTION_SOURCES + ): + sentry_items["transaction"] = transaction.name + + if transaction.sample_rate is not None: + sentry_items["sample_rate"] = str(transaction.sample_rate) + + if transaction.sampled is not None: + sentry_items["sampled"] = "true" if transaction.sampled else "false" + + # there's an existing baggage but it was mutable, + # which is why we are creating this new baggage. + # However, if by chance the user put some sentry items in there, give them precedence. + if transaction._baggage and transaction._baggage.sentry_items: + sentry_items.update(transaction._baggage.sentry_items) + + return Baggage(sentry_items, mutable=False) + + @classmethod + def populate_from_segment(cls, segment: "StreamedSpan") -> "Baggage": + """ + Populate fresh baggage entry with sentry_items and make it immutable + if this is the head SDK which originates traces. + """ + client = sentry_sdk.get_client() + sentry_items: "Dict[str, str]" = {} + + if not client.is_active(): + return Baggage(sentry_items) + + options = client.options or {} + + sentry_items["trace_id"] = segment.trace_id + sentry_items["sample_rand"] = f"{segment._sample_rand:.6f}" # noqa: E231 + + if options.get("environment"): + sentry_items["environment"] = options["environment"] + + if options.get("release"): + sentry_items["release"] = options["release"] + + if client.parsed_dsn: + sentry_items["public_key"] = client.parsed_dsn.public_key + if client.parsed_dsn.org_id: + sentry_items["org_id"] = client.parsed_dsn.org_id + + if ( + segment.get_attributes().get("sentry.span.source") + not in LOW_QUALITY_SEGMENT_SOURCES + ) and segment._name: + sentry_items["transaction"] = segment._name + + if segment._sample_rate is not None: + sentry_items["sample_rate"] = str(segment._sample_rate) + + if segment.sampled is not None: + sentry_items["sampled"] = "true" if segment.sampled else "false" + + # There's an existing baggage but it was mutable, which is why we are + # creating this new baggage. + # However, if by chance the user put some sentry items in there, give + # them precedence. + if segment._baggage and segment._baggage.sentry_items: + sentry_items.update(segment._baggage.sentry_items) + + return Baggage(sentry_items, mutable=False) + + def freeze(self) -> None: + self.mutable = False + + def dynamic_sampling_context(self) -> "Dict[str, str]": + header = {} + + for key, item in self.sentry_items.items(): + header[key] = item + + return header + + def serialize(self, include_third_party: bool = False) -> str: + items = [] + + for key, val in self.sentry_items.items(): + with capture_internal_exceptions(): + item = Baggage.SENTRY_PREFIX + quote(key) + "=" + quote(str(val)) + items.append(item) + + if include_third_party: + items.append(self.third_party_items) + + return ",".join(items) + + @staticmethod + def strip_sentry_baggage(header: str) -> str: + """Remove Sentry baggage from the given header. + + Given a Baggage header, return a new Baggage header with all Sentry baggage items removed. + """ + return ",".join( + ( + item + for item in header.split(",") + if not Baggage.SENTRY_PREFIX_REGEX.match(item.strip()) + ) + ) + + def _sample_rand(self) -> "Optional[float]": + """Convenience method to get the sample_rand value from the sentry_items. + + We validate the value and parse it as a float before returning it. The value is considered + valid if it is a float in the range [0, 1). + """ + sample_rand = try_convert(float, self.sentry_items.get("sample_rand")) + + if sample_rand is not None and 0.0 <= sample_rand < 1.0: + return sample_rand + + return None + + def __repr__(self) -> str: + return f'' + + +def should_propagate_trace(client: "sentry_sdk.client.BaseClient", url: str) -> bool: + """ + Returns True if url matches trace_propagation_targets configured in the given client. Otherwise, returns False. + """ + trace_propagation_targets = client.options["trace_propagation_targets"] + + if is_sentry_url(client, url): + return False + + return match_regex_list(url, trace_propagation_targets, substring_matching=True) + + +def normalize_incoming_data(incoming_data: "Dict[str, Any]") -> "Dict[str, Any]": + """ + Normalizes incoming data so the keys are all lowercase with dashes instead of underscores and stripped from known prefixes. + """ + data = {} + for key, value in incoming_data.items(): + if key.startswith("HTTP_"): + key = key[5:] + + key = key.replace("_", "-").lower() + data[key] = value + + return data + + +def create_span_decorator( + op: "Optional[Union[str, OP]]" = None, + name: "Optional[str]" = None, + attributes: "Optional[dict[str, Any]]" = None, + template: "SPANTEMPLATE" = SPANTEMPLATE.DEFAULT, +) -> "Any": + """ + Create a span decorator that can wrap both sync and async functions. + + :param op: The operation type for the span. + :type op: str or :py:class:`sentry_sdk.consts.OP` or None + :param name: The name of the span. + :type name: str or None + :param attributes: Additional attributes to set on the span. + :type attributes: dict or None + :param template: The type of span to create. This determines what kind of + span instrumentation and data collection will be applied. Use predefined + constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`. + The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most + use cases. + :type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE` + """ + from sentry_sdk.scope import should_send_default_pii + + def span_decorator(f: "Any") -> "Any": + """ + Decorator to create a span for the given function. + """ + + @functools.wraps(f) + async def async_wrapper(*args: "Any", **kwargs: "Any") -> "Any": + current_span = get_current_span() + + if current_span is None: + logger.debug( + "Cannot create a child span for %s. " + "Please start a Sentry transaction before calling this function.", + qualname_from_function(f), + ) + return await f(*args, **kwargs) + + if isinstance(current_span, StreamedSpan): + warnings.warn( + "Use the @sentry_sdk.traces.trace decorator in span streaming mode.", + DeprecationWarning, + stacklevel=2, + ) + return await f(*args, **kwargs) + + span_op = op or _get_span_op(template) + function_name = name or qualname_from_function(f) or "" + span_name = _get_span_name(template, function_name, kwargs) + send_pii = should_send_default_pii() + + with current_span.start_child( + op=span_op, + name=span_name, + ) as span: + span.update_data(attributes or {}) + _set_input_attributes( + span, template, send_pii, function_name, f, args, kwargs + ) + + result = await f(*args, **kwargs) + + _set_output_attributes(span, template, send_pii, result) + + return result + + try: + async_wrapper.__signature__ = inspect.signature(f) # type: ignore[attr-defined] + except Exception: + pass + + @functools.wraps(f) + def sync_wrapper(*args: "Any", **kwargs: "Any") -> "Any": + current_span = get_current_span() + + if current_span is None: + logger.debug( + "Cannot create a child span for %s. " + "Please start a Sentry transaction before calling this function.", + qualname_from_function(f), + ) + return f(*args, **kwargs) + + if isinstance(current_span, StreamedSpan): + warnings.warn( + "Use the @sentry_sdk.traces.trace decorator in span streaming mode.", + DeprecationWarning, + stacklevel=2, + ) + return f(*args, **kwargs) + + span_op = op or _get_span_op(template) + function_name = name or qualname_from_function(f) or "" + span_name = _get_span_name(template, function_name, kwargs) + send_pii = should_send_default_pii() + + with current_span.start_child( + op=span_op, + name=span_name, + ) as span: + span.update_data(attributes or {}) + _set_input_attributes( + span, template, send_pii, function_name, f, args, kwargs + ) + + result = f(*args, **kwargs) + + _set_output_attributes(span, template, send_pii, result) + + return result + + try: + sync_wrapper.__signature__ = inspect.signature(f) # type: ignore[attr-defined] + except Exception: + pass + + if inspect.iscoroutinefunction(f): + return async_wrapper + else: + return sync_wrapper + + return span_decorator + + +def create_streaming_span_decorator( + name: "Optional[str]" = None, + attributes: "Optional[dict[str, Any]]" = None, + active: bool = True, +) -> "Any": + """ + Create a span creating decorator that can wrap both sync and async functions. + """ + + def span_decorator(f: "Any") -> "Any": + """ + Decorator to create a span for the given function. + """ + + @functools.wraps(f) + async def async_wrapper(*args: "Any", **kwargs: "Any") -> "Any": + client = sentry_sdk.get_client() + if not has_span_streaming_enabled(client.options): + warnings.warn( + "Using span streaming API in non-span-streaming mode. Use " + "@sentry_sdk.trace instead.", + stacklevel=2, + ) + + span_name = name or qualname_from_function(f) or "" + + with start_streaming_span( + name=span_name, attributes=attributes, active=active + ): + result = await f(*args, **kwargs) + return result + + try: + async_wrapper.__signature__ = inspect.signature(f) # type: ignore[attr-defined] + except Exception: + pass + + @functools.wraps(f) + def sync_wrapper(*args: "Any", **kwargs: "Any") -> "Any": + client = sentry_sdk.get_client() + if not has_span_streaming_enabled(client.options): + warnings.warn( + "Using span streaming API in non-span-streaming mode. Use " + "@sentry_sdk.trace instead.", + stacklevel=2, + ) + + span_name = name or qualname_from_function(f) or "" + + with start_streaming_span( + name=span_name, attributes=attributes, active=active + ): + return f(*args, **kwargs) + + try: + sync_wrapper.__signature__ = inspect.signature(f) # type: ignore[attr-defined] + except Exception: + pass + + if inspect.iscoroutinefunction(f): + return async_wrapper + else: + return sync_wrapper + + return span_decorator + + +def get_current_span( + scope: "Optional[sentry_sdk.Scope]" = None, +) -> "Optional[Span]": + """ + Returns the currently active span if there is one running, otherwise `None` + """ + scope = scope or sentry_sdk.get_current_scope() + current_span = scope.span + return current_span + + +def set_span_errored(span: "Optional[Union[Span, StreamedSpan]]" = None) -> None: + """ + Set the status of the current or given span to INTERNAL_ERROR. + Also sets the status of the transaction (root span) to INTERNAL_ERROR. + """ + from sentry_sdk.traces import StreamedSpan, SpanStatus, _get_current_streamed_span + + client = sentry_sdk.get_client() + + if not span: + span = ( + _get_current_streamed_span() + if has_span_streaming_enabled(client.options) + else sentry_sdk.get_current_span() + ) + + if span is not None: + if isinstance(span, Span): + span.set_status(SPANSTATUS.INTERNAL_ERROR) + if span.containing_transaction is not None: + span.containing_transaction.set_status(SPANSTATUS.INTERNAL_ERROR) + elif isinstance(span, StreamedSpan): + span.status = SpanStatus.ERROR + if span._segment is not None: + span._segment.status = SpanStatus.ERROR + + +def _generate_sample_rand( + trace_id: "Optional[str]", + *, + interval: "tuple[float, float]" = (0.0, 1.0), +) -> float: + """Generate a sample_rand value from a trace ID. + + The generated value will be pseudorandomly chosen from the provided + interval. Specifically, given (lower, upper) = interval, the generated + value will be in the range [lower, upper). The value has 6-digit precision, + so when printing with .6f, the value will never be rounded up. + + The pseudorandom number generator is seeded with the trace ID. + """ + lower, upper = interval + if not lower < upper: # using `if lower >= upper` would handle NaNs incorrectly + raise ValueError("Invalid interval: lower must be less than upper") + + rng = Random(trace_id) + lower_scaled = int(lower * 1_000_000) + upper_scaled = int(upper * 1_000_000) + try: + sample_rand_scaled = rng.randrange(lower_scaled, upper_scaled) + except ValueError: + # In some corner cases it might happen that the range is too small + # In that case, just take the lower bound + sample_rand_scaled = lower_scaled + + return sample_rand_scaled / 1_000_000 + + +def _sample_rand_range( + parent_sampled: "Optional[bool]", sample_rate: "Optional[float]" +) -> "tuple[float, float]": + """ + Compute the lower (inclusive) and upper (exclusive) bounds of the range of values + that a generated sample_rand value must fall into, given the parent_sampled and + sample_rate values. + """ + if parent_sampled is None or sample_rate is None: + return 0.0, 1.0 + elif parent_sampled is True: + return 0.0, sample_rate + else: # parent_sampled is False + return sample_rate, 1.0 + + +def _get_value(source: "Any", key: str) -> "Optional[Any]": + """ + Gets a value from a source object. The source can be a dict or an object. + It is checked for dictionary keys and object attributes. + """ + value = None + if isinstance(source, dict): + value = source.get(key) + else: + if hasattr(source, key): + try: + value = getattr(source, key) + except Exception: + value = None + return value + + +def _get_span_name( + template: "Union[str, SPANTEMPLATE]", + name: str, + kwargs: "Optional[dict[str, Any]]" = None, +) -> str: + """ + Get the name of the span based on the template and the name. + """ + span_name = name + + if template == SPANTEMPLATE.AI_CHAT: + model = None + if kwargs: + for key in ("model", "model_name"): + if kwargs.get(key) and isinstance(kwargs[key], str): + model = kwargs[key] + break + + span_name = f"chat {model}" if model else "chat" + + elif template == SPANTEMPLATE.AI_AGENT: + span_name = f"invoke_agent {name}" + + elif template == SPANTEMPLATE.AI_TOOL: + span_name = f"execute_tool {name}" + + return span_name + + +def _get_span_op(template: "Union[str, SPANTEMPLATE]") -> str: + """ + Get the operation of the span based on the template. + """ + mapping: "dict[Union[str, SPANTEMPLATE], Union[str, OP]]" = { + SPANTEMPLATE.AI_CHAT: OP.GEN_AI_CHAT, + SPANTEMPLATE.AI_AGENT: OP.GEN_AI_INVOKE_AGENT, + SPANTEMPLATE.AI_TOOL: OP.GEN_AI_EXECUTE_TOOL, + } + op = mapping.get(template, OP.FUNCTION) + + return str(op) + + +def _get_input_attributes( + template: "Union[str, SPANTEMPLATE]", + send_pii: bool, + args: "tuple[Any, ...]", + kwargs: "dict[str, Any]", +) -> "dict[str, Any]": + """ + Get input attributes for the given span template. + """ + attributes: "dict[str, Any]" = {} + + if template in [SPANTEMPLATE.AI_AGENT, SPANTEMPLATE.AI_TOOL, SPANTEMPLATE.AI_CHAT]: + mapping = { + "model": (SPANDATA.GEN_AI_REQUEST_MODEL, str), + "model_name": (SPANDATA.GEN_AI_REQUEST_MODEL, str), + "agent": (SPANDATA.GEN_AI_AGENT_NAME, str), + "agent_name": (SPANDATA.GEN_AI_AGENT_NAME, str), + "max_tokens": (SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, int), + "frequency_penalty": (SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, float), + "presence_penalty": (SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, float), + "temperature": (SPANDATA.GEN_AI_REQUEST_TEMPERATURE, float), + "top_p": (SPANDATA.GEN_AI_REQUEST_TOP_P, float), + "top_k": (SPANDATA.GEN_AI_REQUEST_TOP_K, int), + } + + def _set_from_key(key: str, value: "Any") -> None: + if key in mapping: + (attribute, data_type) = mapping[key] + if value is not None and isinstance(value, data_type): + attributes[attribute] = value + + for key, value in list(kwargs.items()): + if key == "prompt" and isinstance(value, str): + attributes.setdefault(SPANDATA.GEN_AI_REQUEST_MESSAGES, []).append( + {"role": "user", "content": value} + ) + continue + + if key == "system_prompt" and isinstance(value, str): + attributes.setdefault(SPANDATA.GEN_AI_REQUEST_MESSAGES, []).append( + {"role": "system", "content": value} + ) + continue + + _set_from_key(key, value) + + if template == SPANTEMPLATE.AI_TOOL and send_pii: + attributes[SPANDATA.GEN_AI_TOOL_INPUT] = safe_repr( + {"args": args, "kwargs": kwargs} + ) + + # Coerce to string + if SPANDATA.GEN_AI_REQUEST_MESSAGES in attributes: + attributes[SPANDATA.GEN_AI_REQUEST_MESSAGES] = safe_repr( + attributes[SPANDATA.GEN_AI_REQUEST_MESSAGES] + ) + + return attributes + + +def _get_usage_attributes(usage: "Any") -> "dict[str, Any]": + """ + Get usage attributes. + """ + attributes = {} + + def _set_from_keys(attribute: str, keys: "tuple[str, ...]") -> None: + for key in keys: + value = _get_value(usage, key) + if value is not None and isinstance(value, int): + attributes[attribute] = value + + _set_from_keys( + SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, + ("prompt_tokens", "input_tokens"), + ) + _set_from_keys( + SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, + ("completion_tokens", "output_tokens"), + ) + _set_from_keys( + SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, + ("total_tokens",), + ) + + return attributes + + +def _get_output_attributes( + template: "Union[str, SPANTEMPLATE]", send_pii: bool, result: "Any" +) -> "dict[str, Any]": + """ + Get output attributes for the given span template. + """ + attributes: "dict[str, Any]" = {} + + if template in [SPANTEMPLATE.AI_AGENT, SPANTEMPLATE.AI_TOOL, SPANTEMPLATE.AI_CHAT]: + with capture_internal_exceptions(): + # Usage from result, result.usage, and result.metadata.usage + usage_candidates = [result] + + usage = _get_value(result, "usage") + usage_candidates.append(usage) + + meta = _get_value(result, "metadata") + usage = _get_value(meta, "usage") + usage_candidates.append(usage) + + for usage_candidate in usage_candidates: + if usage_candidate is not None: + attributes.update(_get_usage_attributes(usage_candidate)) + + # Response model + model_name = _get_value(result, "model") + if model_name is not None and isinstance(model_name, str): + attributes[SPANDATA.GEN_AI_RESPONSE_MODEL] = model_name + + model_name = _get_value(result, "model_name") + if model_name is not None and isinstance(model_name, str): + attributes[SPANDATA.GEN_AI_RESPONSE_MODEL] = model_name + + # Tool output + if template == SPANTEMPLATE.AI_TOOL and send_pii: + attributes[SPANDATA.GEN_AI_TOOL_OUTPUT] = safe_repr(result) + + return attributes + + +def _set_input_attributes( + span: "Span", + template: "Union[str, SPANTEMPLATE]", + send_pii: bool, + name: str, + f: "Any", + args: "tuple[Any, ...]", + kwargs: "dict[str, Any]", +) -> None: + """ + Set span input attributes based on the given span template. + + :param span: The span to set attributes on. + :param template: The template to use to set attributes on the span. + :param send_pii: Whether to send PII data. + :param f: The wrapped function. + :param args: The arguments to the wrapped function. + :param kwargs: The keyword arguments to the wrapped function. + """ + attributes: "dict[str, Any]" = {} + + if template == SPANTEMPLATE.AI_AGENT: + attributes = { + SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent", + SPANDATA.GEN_AI_AGENT_NAME: name, + } + elif template == SPANTEMPLATE.AI_CHAT: + attributes = { + SPANDATA.GEN_AI_OPERATION_NAME: "chat", + } + elif template == SPANTEMPLATE.AI_TOOL: + attributes = { + SPANDATA.GEN_AI_OPERATION_NAME: "execute_tool", + SPANDATA.GEN_AI_TOOL_NAME: name, + } + + docstring = f.__doc__ + if docstring is not None: + attributes[SPANDATA.GEN_AI_TOOL_DESCRIPTION] = docstring + + attributes.update(_get_input_attributes(template, send_pii, args, kwargs)) + span.update_data(attributes or {}) + + +def _set_output_attributes( + span: "Span", template: "Union[str, SPANTEMPLATE]", send_pii: bool, result: "Any" +) -> None: + """ + Set span output attributes based on the given span template. + + :param span: The span to set attributes on. + :param template: The template to use to set attributes on the span. + :param send_pii: Whether to send PII data. + :param result: The result of the wrapped function. + """ + span.update_data(_get_output_attributes(template, send_pii, result) or {}) + + +def _should_continue_trace(baggage: "Optional[Baggage]") -> bool: + """ + Check if we should continue the incoming trace according to the strict_trace_continuation spec. + https://develop.sentry.dev/sdk/telemetry/traces/#stricttracecontinuation + """ + + client = sentry_sdk.get_client() + parsed_dsn = client.parsed_dsn + client_org_id = parsed_dsn.org_id if parsed_dsn else None + baggage_org_id = baggage.sentry_items.get("org_id") if baggage else None + + if ( + client_org_id is not None + and baggage_org_id is not None + and client_org_id != baggage_org_id + ): + logger.debug( + f"Starting a new trace because org IDs don't match (incoming baggage org_id: {baggage_org_id}, SDK org_id: {client_org_id})" + ) + return False + + strict_trace_continuation: bool = client.options.get( + "strict_trace_continuation", False + ) + if strict_trace_continuation: + if (baggage_org_id is not None and client_org_id is None) or ( + baggage_org_id is None and client_org_id is not None + ): + logger.debug( + f"Starting a new trace because strict trace continuation is enabled and one org ID is missing (incoming baggage org_id: {baggage_org_id}, SDK org_id: {client_org_id})" + ) + return False + + return True + + +def add_sentry_baggage_to_headers( + headers: "MutableMapping[str, str]", sentry_baggage: str +) -> None: + """Add the Sentry baggage to the headers. + + This function directly mutates the provided headers. The provided sentry_baggage + is appended to the existing baggage. If the baggage already contains Sentry items, + they are stripped out first. + """ + existing_baggage = headers.get(BAGGAGE_HEADER_NAME, "") + stripped_existing_baggage = Baggage.strip_sentry_baggage(existing_baggage) + + separator = "," if len(stripped_existing_baggage) > 0 else "" + + headers[BAGGAGE_HEADER_NAME] = ( + stripped_existing_baggage + separator + sentry_baggage + ) + + +def _make_sampling_decision( + name: str, + attributes: "Optional[Attributes]", + scope: "sentry_sdk.Scope", +) -> "tuple[bool, Optional[float], Optional[float], Optional[str]]": + """ + Decide whether a span should be sampled. + + Returns a tuple with: + 1. the sampling decision + 2. the effective sample rate + 3. the sample rand + 4. the reason for not sampling the span, if unsampled + """ + client = sentry_sdk.get_client() + + if not has_tracing_enabled(client.options): + return False, None, None, None + + propagation_context = scope.get_active_propagation_context() + + sample_rand = None + if propagation_context.baggage is not None: + sample_rand = propagation_context.baggage._sample_rand() + if sample_rand is None: + sample_rand = _generate_sample_rand(propagation_context.trace_id) + + # If there's a traces_sampler, use that; otherwise use traces_sample_rate + traces_sampler_defined = callable(client.options.get("traces_sampler")) + if traces_sampler_defined: + sampling_context = { + "span_context": { + "name": name, + "trace_id": propagation_context.trace_id, + "parent_span_id": propagation_context.parent_span_id, + "parent_sampled": propagation_context.parent_sampled, + "attributes": dict(attributes) if attributes else {}, + }, + } + + if propagation_context.custom_sampling_context: + sampling_context.update(propagation_context.custom_sampling_context) + + sample_rate = client.options["traces_sampler"](sampling_context) + else: + if propagation_context.parent_sampled is not None: + sample_rate = propagation_context.parent_sampled + else: + sample_rate = client.options["traces_sample_rate"] + + # Validate whether the sample_rate we got is actually valid. Since + # traces_sampler is user-provided, it could return anything. + if not is_valid_sample_rate(sample_rate, source="Tracing"): + logger.warning(f"[Tracing] Discarding {name} because of invalid sample rate.") + return False, None, None, "sample_rate" + + sample_rate = float(sample_rate) + if not sample_rate: + if traces_sampler_defined: + reason = "traces_sampler returned 0 or False" + else: + reason = "traces_sample_rate is set to 0" + + logger.debug(f"[Tracing] Discarding {name} because {reason}") + return False, 0.0, None, "sample_rate" + + # Adjust sample rate if we're under backpressure + if client.monitor: + sample_rate /= 2**client.monitor.downsample_factor + + if not sample_rate: + logger.debug(f"[Tracing] Discarding {name} because backpressure") + return False, 0.0, None, "backpressure" + + sampled = sample_rand < sample_rate + + if sampled: + logger.debug(f"[Tracing] Starting {name}") + outcome = None + else: + logger.debug( + f"[Tracing] Discarding {name} because it's not included in the random sample (sampling rate = {sample_rate})" + ) + outcome = "sample_rate" + + return sampled, sample_rate, sample_rand, outcome + + +def is_ignored_span(name: str, attributes: "Optional[Attributes]") -> bool: + """Determine if a span fits one of the rules in ignore_spans.""" + client = sentry_sdk.get_client() + ignore_spans = (client.options.get("_experiments") or {}).get("ignore_spans") + + if not ignore_spans: + return False + + def _matches(rule: "Any", value: "Any") -> bool: + if isinstance(rule, Pattern): + if isinstance(value, str): + return bool(rule.fullmatch(value)) + else: + return False + + return rule == value + + for rule in ignore_spans: + if isinstance(rule, (str, Pattern)): + if _matches(rule, name): + return True + + elif isinstance(rule, dict) and ("name" in rule or "attributes" in rule): + name_matches = True + attributes_match = True + + attributes = attributes or {} + + if "name" in rule: + name_matches = _matches(rule["name"], name) + + if "attributes" in rule: + for attribute, value in rule["attributes"].items(): + if attribute not in attributes or not _matches( + value, attributes[attribute] + ): + attributes_match = False + break + + if name_matches and attributes_match: + return True + + return False + + +# Circular imports +from sentry_sdk.tracing import ( + BAGGAGE_HEADER_NAME, + LOW_QUALITY_TRANSACTION_SOURCES, + SENTRY_TRACE_HEADER_NAME, + Span, +) +from sentry_sdk.traces import ( + LOW_QUALITY_SEGMENT_SOURCES, + StreamedSpan, + start_span as start_streaming_span, +) + +if TYPE_CHECKING: + from sentry_sdk.tracing import Span diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/transport.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/transport.py new file mode 100644 index 0000000000000000000000000000000000000000..2b71fee429162ac93009a5aee7488e74e54304d7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/transport.py @@ -0,0 +1,1255 @@ +import asyncio +import gzip +import io +import json +import logging +import os +import socket +import ssl +import time +import warnings +from abc import ABC, abstractmethod +from collections import defaultdict +from datetime import datetime, timedelta, timezone +from urllib.request import getproxies + +try: + import brotli # type: ignore +except ImportError: + brotli = None + +try: + import httpcore +except ImportError: + httpcore = None # type: ignore[assignment,unused-ignore] + +try: + import h2 # noqa: F401 + + HTTP2_ENABLED = httpcore is not None +except ImportError: + HTTP2_ENABLED = False + +try: + import anyio # noqa: F401 + + ASYNC_TRANSPORT_AVAILABLE = httpcore is not None +except ImportError: + ASYNC_TRANSPORT_AVAILABLE = False + +from typing import TYPE_CHECKING, Dict, List, cast + +import certifi +import urllib3 + +import sentry_sdk +from sentry_sdk.consts import EndpointType +from sentry_sdk.envelope import Envelope, Item, PayloadRef +from sentry_sdk.utils import ( + Dsn, + capture_internal_exceptions, + logger, + mark_sentry_task_internal, +) +from sentry_sdk.worker import AsyncWorker, BackgroundWorker, Worker + +if TYPE_CHECKING: + from typing import ( + Any, + Callable, + DefaultDict, + Iterable, + Mapping, + Optional, + Self, + Tuple, + Type, + Union, + ) + + from urllib3.poolmanager import PoolManager, ProxyManager + + from sentry_sdk._types import Event, EventDataCategory + +KEEP_ALIVE_SOCKET_OPTIONS = [] +for option in [ + (socket.SOL_SOCKET, lambda: getattr(socket, "SO_KEEPALIVE"), 1), # noqa: B009 + (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPIDLE"), 45), # noqa: B009 + (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPINTVL"), 10), # noqa: B009 + (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPCNT"), 6), # noqa: B009 +]: + try: + KEEP_ALIVE_SOCKET_OPTIONS.append((option[0], option[1](), option[2])) + except AttributeError: + # a specific option might not be available on specific systems, + # e.g. TCP_KEEPIDLE doesn't exist on macOS + pass + + +def _get_httpcore_header_value(response: "Any", header: str) -> "Optional[str]": + """Case-insensitive header lookup for httpcore-style responses.""" + header_lower = header.lower() + return next( + ( + val.decode("ascii") + for key, val in response.headers + if key.decode("ascii").lower() == header_lower + ), + None, + ) + + +class Transport(ABC): + """Baseclass for all transports. + + A transport is used to send an event to sentry. + """ + + parsed_dsn: "Optional[Dsn]" = None + + def __init__(self: "Self", options: "Optional[Dict[str, Any]]" = None) -> None: + self.options = options + if options and options["dsn"]: + self.parsed_dsn = Dsn(options["dsn"], options.get("org_id")) + else: + self.parsed_dsn = None + + def capture_event(self: "Self", event: "Event") -> None: + """ + DEPRECATED: Please use capture_envelope instead. + + This gets invoked with the event dictionary when an event should + be sent to sentry. + """ + + warnings.warn( + "capture_event is deprecated, please use capture_envelope instead!", + DeprecationWarning, + stacklevel=2, + ) + + envelope = Envelope() + envelope.add_event(event) + self.capture_envelope(envelope) + + @abstractmethod + def capture_envelope(self: "Self", envelope: "Envelope") -> None: + """ + Send an envelope to Sentry. + + Envelopes are a data container format that can hold any type of data + submitted to Sentry. We use it to send all event data (including errors, + transactions, crons check-ins, etc.) to Sentry. + """ + pass + + def flush( + self: "Self", + timeout: float, + callback: "Optional[Any]" = None, + ) -> None: + """ + Wait `timeout` seconds for the current events to be sent out. + + The default implementation is a no-op, since this method may only be relevant to some transports. + Subclasses should override this method if necessary. + """ + return None + + def kill(self: "Self") -> None: + """ + Forcefully kills the transport. + + The default implementation is a no-op, since this method may only be relevant to some transports. + Subclasses should override this method if necessary. + """ + return None + + def record_lost_event( + self, + reason: str, + data_category: "Optional[EventDataCategory]" = None, + item: "Optional[Item]" = None, + *, + quantity: int = 1, + ) -> None: + """This increments a counter for event loss by reason and + data category by the given positive-int quantity (default 1). + + If an item is provided, the data category and quantity are + extracted from the item, and the values passed for + data_category and quantity are ignored. + + When recording a lost transaction via data_category="transaction", + the calling code should also record the lost spans via this method. + When recording lost spans, `quantity` should be set to the number + of contained spans, plus one for the transaction itself. When + passing an Item containing a transaction via the `item` parameter, + this method automatically records the lost spans. + """ + return None + + def is_healthy(self: "Self") -> bool: + return True + + +def _parse_rate_limits( + header: str, now: "Optional[datetime]" = None +) -> "Iterable[Tuple[Optional[EventDataCategory], datetime]]": + if now is None: + now = datetime.now(timezone.utc) + + for limit in header.split(","): + try: + parameters = limit.strip().split(":") + retry_after_val, categories = parameters[:2] + + retry_after = now + timedelta(seconds=int(retry_after_val)) + for category in categories and categories.split(";") or (None,): + yield category, retry_after # type: ignore + except (LookupError, ValueError): + continue + + +class HttpTransportCore(Transport): + """Shared base class for sync and async transports.""" + + TIMEOUT = 30 # seconds + + def __init__(self: "Self", options: "Dict[str, Any]") -> None: + from sentry_sdk.consts import VERSION + + Transport.__init__(self, options) + assert self.parsed_dsn is not None + self.options: "Dict[str, Any]" = options + self._worker = self._create_worker(options) + self._auth = self.parsed_dsn.to_auth("sentry.python/%s" % VERSION) + self._disabled_until: "Dict[Optional[EventDataCategory], datetime]" = {} + # We only use this Retry() class for the `get_retry_after` method it exposes + self._retry = urllib3.util.Retry() + self._discarded_events: "DefaultDict[Tuple[EventDataCategory, str], int]" = ( + defaultdict(int) + ) + self._last_client_report_sent = time.time() + + self._pool = self._make_pool() + + # Backwards compatibility for deprecated `self.hub_class` attribute + self._hub_cls = sentry_sdk.Hub + + experiments = options.get("_experiments", {}) + compression_level = experiments.get( + "transport_compression_level", + experiments.get("transport_zlib_compression_level"), + ) + compression_algo = experiments.get( + "transport_compression_algo", + ( + "gzip" + # if only compression level is set, assume gzip for backwards compatibility + # if we don't have brotli available, fallback to gzip + if compression_level is not None or brotli is None + else "br" + ), + ) + + if compression_algo == "br" and brotli is None: + logger.warning( + "You asked for brotli compression without the Brotli module, falling back to gzip -9" + ) + compression_algo = "gzip" + compression_level = None + + if compression_algo not in ("br", "gzip"): + logger.warning( + "Unknown compression algo %s, disabling compression", compression_algo + ) + self._compression_level = 0 + self._compression_algo = None + else: + self._compression_algo = compression_algo + + if compression_level is not None: + self._compression_level = compression_level + elif self._compression_algo == "gzip": + self._compression_level = 9 + elif self._compression_algo == "br": + self._compression_level = 4 + + def _create_worker(self: "Self", options: "Dict[str, Any]") -> "Worker": + raise NotImplementedError() + + def record_lost_event( + self, + reason: str, + data_category: "Optional[EventDataCategory]" = None, + item: "Optional[Item]" = None, + *, + quantity: int = 1, + ) -> None: + if not self.options["send_client_reports"]: + return + + if item is not None: + data_category = item.data_category + quantity = 1 # If an item is provided, we always count it as 1 (except for attachments, handled below). + + if data_category == "transaction": + # Also record the lost spans + event = item.get_transaction_event() or {} + + # +1 for the transaction itself + span_count = ( + len(cast(List[Dict[str, object]], event.get("spans") or [])) + 1 + ) + self.record_lost_event(reason, "span", quantity=span_count) + + elif data_category == "log_item" and item: + # Also record size of lost logs in bytes + bytes_size = len(item.get_bytes()) + self.record_lost_event(reason, "log_byte", quantity=bytes_size) + + elif data_category == "attachment": + # quantity of 0 is actually 1 as we do not want to count + # empty attachments as actually empty. + quantity = len(item.get_bytes()) or 1 + + elif data_category is None: + raise TypeError("data category not provided") + + self._discarded_events[data_category, reason] += quantity + + def _get_header_value( + self: "Self", response: "Any", header: str + ) -> "Optional[str]": + return response.headers.get(header) + + def _update_rate_limits( + self: "Self", response: "Union[urllib3.BaseHTTPResponse, httpcore.Response]" + ) -> None: + # new sentries with more rate limit insights. We honor this header + # no matter of the status code to update our internal rate limits. + header = self._get_header_value(response, "x-sentry-rate-limits") + if header: + logger.warning("Rate-limited via x-sentry-rate-limits") + self._disabled_until.update(_parse_rate_limits(header)) + + # old sentries only communicate global rate limit hits via the + # retry-after header on 429. This header can also be emitted on new + # sentries if a proxy in front wants to globally slow things down. + elif response.status == 429: + logger.warning("Rate-limited via 429") + retry_after_value = self._get_header_value(response, "Retry-After") + retry_after = ( + self._retry.parse_retry_after(retry_after_value) + if retry_after_value is not None + else None + ) or 60 + self._disabled_until[None] = datetime.now(timezone.utc) + timedelta( + seconds=retry_after + ) + + def _handle_request_error( + self: "Self", + envelope: "Optional[Envelope]", + loss_reason: str = "network", + record_reason: str = "network_error", + ) -> None: + def record_loss(reason: str) -> None: + if envelope is None: + self.record_lost_event(reason, data_category="error") + else: + for item in envelope.items: + self.record_lost_event(reason, item=item) + + self.on_dropped_event(loss_reason) + record_loss(record_reason) + + def _handle_response( + self: "Self", + response: "Union[urllib3.BaseHTTPResponse, httpcore.Response]", + envelope: "Optional[Envelope]", + ) -> None: + self._update_rate_limits(response) + + if response.status == 413: + size_exceeded_message = ( + "HTTP 413: Event dropped due to exceeded envelope size limit" + ) + response_message = getattr( + response, "data", getattr(response, "content", None) + ) + if response_message is not None: + size_exceeded_message += f" (body: {response_message})" + + logger.error(size_exceeded_message) + self._handle_request_error( + envelope=envelope, loss_reason="status_413", record_reason="send_error" + ) + + elif response.status == 429: + # if we hit a 429. Something was rate limited but we already + # acted on this in `self._update_rate_limits`. Note that we + # do not want to record event loss here as we will have recorded + # an outcome in relay already. + self.on_dropped_event("status_429") + pass + + elif response.status >= 300 or response.status < 200: + logger.error( + "Unexpected status code: %s (body: %s)", + response.status, + getattr(response, "data", getattr(response, "content", None)), + ) + self._handle_request_error( + envelope=envelope, loss_reason="status_{}".format(response.status) + ) + + def _update_headers( + self: "Self", + headers: "Dict[str, str]", + ) -> None: + headers.update( + { + "User-Agent": str(self._auth.client), + "X-Sentry-Auth": str(self._auth.to_header()), + } + ) + + def on_dropped_event(self: "Self", _reason: str) -> None: + return None + + def _fetch_pending_client_report( + self: "Self", force: bool = False, interval: int = 60 + ) -> "Optional[Item]": + if not self.options["send_client_reports"]: + return None + + if not (force or self._last_client_report_sent < time.time() - interval): + return None + + discarded_events = self._discarded_events + self._discarded_events = defaultdict(int) + self._last_client_report_sent = time.time() + + if not discarded_events: + return None + + return Item( + PayloadRef( + json={ + "timestamp": time.time(), + "discarded_events": [ + {"reason": reason, "category": category, "quantity": quantity} + for ( + (category, reason), + quantity, + ) in discarded_events.items() + ], + } + ), + type="client_report", + ) + + def _check_disabled(self, category: str) -> bool: + def _disabled(bucket: "Any") -> bool: + ts = self._disabled_until.get(bucket) + return ts is not None and ts > datetime.now(timezone.utc) + + return _disabled(category) or _disabled(None) + + def _is_rate_limited(self: "Self") -> bool: + return any( + ts > datetime.now(timezone.utc) for ts in self._disabled_until.values() + ) + + def _is_worker_full(self: "Self") -> bool: + return self._worker.full() + + def is_healthy(self: "Self") -> bool: + return not (self._is_worker_full() or self._is_rate_limited()) + + def _prepare_envelope( + self: "Self", envelope: "Envelope" + ) -> "Optional[Tuple[Envelope, io.BytesIO, Dict[str, str]]]": + # remove all items from the envelope which are over quota + new_items = [] + for item in envelope.items: + if self._check_disabled(item.data_category): + if item.data_category in ("transaction", "error", "default", "statsd"): + self.on_dropped_event("self_rate_limits") + self.record_lost_event("ratelimit_backoff", item=item) + else: + new_items.append(item) + + # Since we're modifying the envelope here make a copy so that others + # that hold references do not see their envelope modified. + envelope = Envelope(headers=envelope.headers, items=new_items) + + if not envelope.items: + return None + + # since we're already in the business of sending out an envelope here + # check if we have one pending for the stats session envelopes so we + # can attach it to this enveloped scheduled for sending. This will + # currently typically attach the client report to the most recent + # session update. + client_report_item = self._fetch_pending_client_report(interval=30) + if client_report_item is not None: + envelope.items.append(client_report_item) + + content_encoding, body = self._serialize_envelope(envelope) + + assert self.parsed_dsn is not None + logger.debug( + "Sending envelope [%s] project:%s host:%s", + envelope.description, + self.parsed_dsn.project_id, + self.parsed_dsn.host, + ) + + headers: "Dict[str, str]" = { + "Content-Type": "application/x-sentry-envelope", + } + if content_encoding: + headers["Content-Encoding"] = content_encoding + + return envelope, body, headers + + def _serialize_envelope( + self: "Self", envelope: "Envelope" + ) -> "tuple[Optional[str], io.BytesIO]": + content_encoding = None + body = io.BytesIO() + if self._compression_level == 0 or self._compression_algo is None: + envelope.serialize_into(body) + else: + content_encoding = self._compression_algo + if self._compression_algo == "br" and brotli is not None: + body.write( + brotli.compress( + envelope.serialize(), quality=self._compression_level + ) + ) + else: # assume gzip as we sanitize the algo value in init + with gzip.GzipFile( + fileobj=body, mode="w", compresslevel=self._compression_level + ) as f: + envelope.serialize_into(f) + + return content_encoding, body + + def _get_httpcore_pool_options( + self: "Self", http2: bool = False + ) -> "Dict[str, Any]": + """Shared pool options for httpcore-based transports (Http2 and Async).""" + options: "Dict[str, Any]" = { + "http2": http2, + "retries": 3, + } + + socket_options: "Optional[List[Tuple[int, int, int | bytes]]]" = None + + if self.options["socket_options"] is not None: + socket_options = self.options["socket_options"] + + if socket_options is None: + socket_options = [] + + used_options = {(o[0], o[1]) for o in socket_options} + for default_option in KEEP_ALIVE_SOCKET_OPTIONS: + if (default_option[0], default_option[1]) not in used_options: + socket_options.append(default_option) + + if socket_options is not None: + options["socket_options"] = socket_options + + ssl_context = ssl.create_default_context() + ssl_context.load_verify_locations( + self.options["ca_certs"] + or os.environ.get("SSL_CERT_FILE") + or os.environ.get("REQUESTS_CA_BUNDLE") + or certifi.where() + ) + cert_file = self.options["cert_file"] or os.environ.get("CLIENT_CERT_FILE") + key_file = self.options["key_file"] or os.environ.get("CLIENT_KEY_FILE") + if cert_file is not None: + ssl_context.load_cert_chain(cert_file, key_file) + + options["ssl_context"] = ssl_context + return options + + def _resolve_proxy(self: "Self") -> "Optional[str]": + """Resolve proxy URL from options and environment. Returns proxy URL or None.""" + if self.parsed_dsn is None: + return None + + no_proxy = self._in_no_proxy(self.parsed_dsn) + proxy = None + + # try HTTPS first + https_proxy = self.options["https_proxy"] + if self.parsed_dsn.scheme == "https" and (https_proxy != ""): + proxy = https_proxy or (not no_proxy and getproxies().get("https")) + + # maybe fallback to HTTP proxy + http_proxy = self.options["http_proxy"] + if not proxy and (http_proxy != ""): + proxy = http_proxy or (not no_proxy and getproxies().get("http")) + + return proxy or None + + @property + def _timeout_extensions(self: "Self") -> "Dict[str, Any]": + return { + "timeout": { + "pool": self.TIMEOUT, + "connect": self.TIMEOUT, + "write": self.TIMEOUT, + "read": self.TIMEOUT, + } + } + + def _get_pool_options(self: "Self") -> "Dict[str, Any]": + raise NotImplementedError() + + def _in_no_proxy(self: "Self", parsed_dsn: "Dsn") -> bool: + no_proxy = getproxies().get("no") + if not no_proxy: + return False + for host in no_proxy.split(","): + host = host.strip() + if parsed_dsn.host.endswith(host) or parsed_dsn.netloc.endswith(host): + return True + return False + + def _make_pool( + self: "Self", + ) -> "Union[PoolManager, ProxyManager, httpcore.SOCKSProxy, httpcore.HTTPProxy, httpcore.ConnectionPool, httpcore.AsyncSOCKSProxy, httpcore.AsyncHTTPProxy, httpcore.AsyncConnectionPool]": + raise NotImplementedError() + + def _request( + self: "Self", + method: str, + endpoint_type: "EndpointType", + body: "Any", + headers: "Mapping[str, str]", + ) -> "Union[urllib3.BaseHTTPResponse, httpcore.Response]": + raise NotImplementedError() + + def kill(self: "Self") -> None: + logger.debug("Killing HTTP transport") + self._worker.kill() + + +# Keep BaseHttpTransport as an alias for backwards compatibility +# and for the sync transport implementation +class BaseHttpTransport(HttpTransportCore): + """The base HTTP transport (synchronous).""" + + def _send_envelope(self: "Self", envelope: "Envelope") -> None: + _prepared_envelope = self._prepare_envelope(envelope) + if _prepared_envelope is not None: + envelope, body, headers = _prepared_envelope + self._send_request( + body.getvalue(), + headers=headers, + endpoint_type=EndpointType.ENVELOPE, + envelope=envelope, + ) + return None + + def _send_request( + self: "Self", + body: bytes, + headers: "Dict[str, str]", + endpoint_type: "EndpointType", + envelope: "Optional[Envelope]" = None, + ) -> None: + self._update_headers(headers) + try: + response = self._request( + "POST", + endpoint_type, + body, + headers, + ) + except Exception: + self._handle_request_error(envelope=envelope, loss_reason="network") + raise + try: + self._handle_response(response=response, envelope=envelope) + finally: + response.close() + + def _create_worker(self: "Self", options: "Dict[str, Any]") -> "Worker": + return BackgroundWorker(queue_size=options["transport_queue_size"]) + + def _flush_client_reports(self: "Self", force: bool = False) -> None: + client_report = self._fetch_pending_client_report(force=force, interval=60) + if client_report is not None: + self.capture_envelope(Envelope(items=[client_report])) + + def capture_envelope( + self, + envelope: "Envelope", + ) -> None: + def send_envelope_wrapper() -> None: + with capture_internal_exceptions(): + self._send_envelope(envelope) + self._flush_client_reports() + + if not self._worker.submit(send_envelope_wrapper): + self.on_dropped_event("full_queue") + for item in envelope.items: + self.record_lost_event("queue_overflow", item=item) + + def flush( + self: "Self", + timeout: float, + callback: "Optional[Callable[[int, float], None]]" = None, + ) -> None: + logger.debug("Flushing HTTP transport") + + if timeout > 0: + self._worker.submit(lambda: self._flush_client_reports(force=True)) + self._worker.flush(timeout, callback) + + @staticmethod + def _warn_hub_cls() -> None: + """Convenience method to warn users about the deprecation of the `hub_cls` attribute.""" + warnings.warn( + "The `hub_cls` attribute is deprecated and will be removed in a future release.", + DeprecationWarning, + stacklevel=3, + ) + + @property + def hub_cls(self: "Self") -> "type[sentry_sdk.Hub]": + """DEPRECATED: This attribute is deprecated and will be removed in a future release.""" + HttpTransport._warn_hub_cls() + return self._hub_cls + + @hub_cls.setter + def hub_cls(self: "Self", value: "type[sentry_sdk.Hub]") -> None: + """DEPRECATED: This attribute is deprecated and will be removed in a future release.""" + HttpTransport._warn_hub_cls() + self._hub_cls = value + + +class HttpTransport(BaseHttpTransport): + if TYPE_CHECKING: + _pool: "Union[PoolManager, ProxyManager]" + + def _get_pool_options(self: "Self") -> "Dict[str, Any]": + num_pools = self.options.get("_experiments", {}).get("transport_num_pools") + options = { + "num_pools": 2 if num_pools is None else int(num_pools), + "cert_reqs": "CERT_REQUIRED", + "timeout": urllib3.Timeout(total=self.TIMEOUT), + } + + socket_options: "Optional[List[Tuple[int, int, int | bytes]]]" = None + + if self.options["socket_options"] is not None: + socket_options = self.options["socket_options"] + + if self.options["keep_alive"]: + if socket_options is None: + socket_options = [] + + used_options = {(o[0], o[1]) for o in socket_options} + for default_option in KEEP_ALIVE_SOCKET_OPTIONS: + if (default_option[0], default_option[1]) not in used_options: + socket_options.append(default_option) + + if socket_options is not None: + options["socket_options"] = socket_options + + options["ca_certs"] = ( + self.options["ca_certs"] # User-provided bundle from the SDK init + or os.environ.get("SSL_CERT_FILE") + or os.environ.get("REQUESTS_CA_BUNDLE") + or certifi.where() + ) + + options["cert_file"] = self.options["cert_file"] or os.environ.get( + "CLIENT_CERT_FILE" + ) + options["key_file"] = self.options["key_file"] or os.environ.get( + "CLIENT_KEY_FILE" + ) + + return options + + def _make_pool(self: "Self") -> "Union[PoolManager, ProxyManager]": + if self.parsed_dsn is None: + raise ValueError("Cannot create HTTP-based transport without valid DSN") + + proxy = None + no_proxy = self._in_no_proxy(self.parsed_dsn) + + # try HTTPS first + https_proxy = self.options["https_proxy"] + if self.parsed_dsn.scheme == "https" and (https_proxy != ""): + proxy = https_proxy or (not no_proxy and getproxies().get("https")) + + # maybe fallback to HTTP proxy + http_proxy = self.options["http_proxy"] + if not proxy and (http_proxy != ""): + proxy = http_proxy or (not no_proxy and getproxies().get("http")) + + opts = self._get_pool_options() + + if proxy: + proxy_headers = self.options["proxy_headers"] + if proxy_headers: + opts["proxy_headers"] = proxy_headers + + if proxy.startswith("socks"): + use_socks_proxy = True + try: + # Check if PySocks dependency is available + from urllib3.contrib.socks import SOCKSProxyManager + except ImportError: + use_socks_proxy = False + logger.warning( + "You have configured a SOCKS proxy (%s) but support for SOCKS proxies is not installed. Disabling proxy support. Please add `PySocks` (or `urllib3` with the `[socks]` extra) to your dependencies.", + proxy, + ) + + if use_socks_proxy: + return SOCKSProxyManager(proxy, **opts) + else: + return urllib3.PoolManager(**opts) + else: + return urllib3.ProxyManager(proxy, **opts) + else: + return urllib3.PoolManager(**opts) + + def _request( + self: "Self", + method: str, + endpoint_type: "EndpointType", + body: "Any", + headers: "Mapping[str, str]", + ) -> "urllib3.BaseHTTPResponse": + return self._pool.request( + method, + self._auth.get_api_url(endpoint_type), + body=body, + headers=headers, + ) + + +class AsyncHttpTransport(HttpTransportCore): + def __init__(self: "Self", options: "Dict[str, Any]") -> None: + if not ASYNC_TRANSPORT_AVAILABLE: + raise RuntimeError( + "AsyncHttpTransport requires httpcore[asyncio]. " + "Install it with: pip install sentry-sdk[asyncio]" + ) + super().__init__(options) + # Requires event loop at init time + self.loop = asyncio.get_running_loop() + + def _create_worker(self: "Self", options: "Dict[str, Any]") -> "Worker": + return AsyncWorker(queue_size=options["transport_queue_size"]) + + def _get_header_value( + self: "Self", response: "Any", header: str + ) -> "Optional[str]": + return _get_httpcore_header_value(response, header) + + async def _send_envelope(self: "Self", envelope: "Envelope") -> None: + _prepared_envelope = self._prepare_envelope(envelope) + if _prepared_envelope is not None: + envelope, body, headers = _prepared_envelope + await self._send_request( + body.getvalue(), + headers=headers, + endpoint_type=EndpointType.ENVELOPE, + envelope=envelope, + ) + return None + + async def _send_request( + self: "Self", + body: bytes, + headers: "Dict[str, str]", + endpoint_type: "EndpointType", + envelope: "Optional[Envelope]" = None, + ) -> None: + self._update_headers(headers) + try: + response = await self._request( + "POST", + endpoint_type, + body, + headers, + ) + except Exception: + self._handle_request_error(envelope=envelope, loss_reason="network") + raise + try: + self._handle_response(response=response, envelope=envelope) + finally: + await response.aclose() + + async def _request( # type: ignore[override] + self: "Self", + method: str, + endpoint_type: "EndpointType", + body: "Any", + headers: "Mapping[str, str]", + ) -> "httpcore.Response": + return await self._pool.request( # type: ignore[misc,unused-ignore] + method, + self._auth.get_api_url(endpoint_type), + content=body, + headers=headers, # type: ignore[arg-type,unused-ignore] + extensions=self._timeout_extensions, + ) + + async def _flush_client_reports(self: "Self", force: bool = False) -> None: + client_report = self._fetch_pending_client_report(force=force, interval=60) + if client_report is not None: + self.capture_envelope(Envelope(items=[client_report])) + + def _capture_envelope(self: "Self", envelope: "Envelope") -> None: + async def send_envelope_wrapper() -> None: + with capture_internal_exceptions(): + await self._send_envelope(envelope) + await self._flush_client_reports() + + if not self._worker.submit(send_envelope_wrapper): + self.on_dropped_event("full_queue") + for item in envelope.items: + self.record_lost_event("queue_overflow", item=item) + + def capture_envelope(self: "Self", envelope: "Envelope") -> None: + # Synchronous entry point + if self.loop and self.loop.is_running(): + self.loop.call_soon_threadsafe(self._capture_envelope, envelope) + else: + # The event loop is no longer running + logger.warning("Async Transport is not running in an event loop.") + self.on_dropped_event("internal_sdk_error") + for item in envelope.items: + self.record_lost_event("internal_sdk_error", item=item) + + def flush( # type: ignore[override] + self: "Self", + timeout: float, + callback: "Optional[Callable[[int, float], None]]" = None, + ) -> "Optional[asyncio.Task[None]]": + logger.debug("Flushing HTTP transport") + + if timeout > 0: + self._worker.submit(lambda: self._flush_client_reports(force=True)) + return self._worker.flush(timeout, callback) # type: ignore[func-returns-value] + return None + + def _get_pool_options(self: "Self") -> "Dict[str, Any]": + return self._get_httpcore_pool_options( + http2=HTTP2_ENABLED + and self.parsed_dsn is not None + and self.parsed_dsn.scheme == "https" + ) + + def _make_pool( + self: "Self", + ) -> "Union[httpcore.AsyncSOCKSProxy, httpcore.AsyncHTTPProxy, httpcore.AsyncConnectionPool]": + if self.parsed_dsn is None: + raise ValueError("Cannot create HTTP-based transport without valid DSN") + + proxy = self._resolve_proxy() + opts = self._get_pool_options() + + if proxy: + proxy_headers = self.options["proxy_headers"] + if proxy_headers: + opts["proxy_headers"] = proxy_headers + + if proxy.startswith("socks"): + try: + socks_opts = opts.copy() + if "socket_options" in socks_opts: + socket_options = socks_opts.pop("socket_options") + if socket_options: + logger.warning( + "You have defined socket_options but using a SOCKS proxy which doesn't support these. We'll ignore socket_options." + ) + return httpcore.AsyncSOCKSProxy(proxy_url=proxy, **socks_opts) + except RuntimeError: + logger.warning( + "You have configured a SOCKS proxy (%s) but support for SOCKS proxies is not installed. Disabling proxy support.", + proxy, + ) + else: + return httpcore.AsyncHTTPProxy(proxy_url=proxy, **opts) + + return httpcore.AsyncConnectionPool(**opts) + + def kill(self: "Self") -> "Optional[asyncio.Task[None]]": # type: ignore[override] + logger.debug("Killing HTTP transport") + self._worker.kill() + try: + # Return the pool cleanup task so caller can await it if needed + with mark_sentry_task_internal(): + return self.loop.create_task(self._pool.aclose()) # type: ignore[union-attr,unused-ignore] + except RuntimeError: + logger.warning("Event loop not running, aborting kill.") + return None + + +if not HTTP2_ENABLED: + # Sorry, no Http2Transport for you + class Http2Transport(HttpTransport): + def __init__(self: "Self", options: "Dict[str, Any]") -> None: + super().__init__(options) + logger.warning( + "You tried to use HTTP2Transport but don't have httpcore[http2] installed. Falling back to HTTPTransport." + ) + +else: + + class Http2Transport(BaseHttpTransport): # type: ignore + """The HTTP2 transport based on httpcore.""" + + TIMEOUT = 15 + + if TYPE_CHECKING: + _pool: """Union[ + httpcore.SOCKSProxy, httpcore.HTTPProxy, httpcore.ConnectionPool + ]""" + + def _get_header_value( + self: "Self", response: "httpcore.Response", header: str + ) -> "Optional[str]": + return _get_httpcore_header_value(response, header) + + def _request( + self: "Self", + method: str, + endpoint_type: "EndpointType", + body: "Any", + headers: "Mapping[str, str]", + ) -> "httpcore.Response": + response = self._pool.request( + method, + self._auth.get_api_url(endpoint_type), + content=body, + headers=headers, # type: ignore[arg-type,unused-ignore] + extensions=self._timeout_extensions, + ) + return response + + def _get_pool_options(self: "Self") -> "Dict[str, Any]": + return self._get_httpcore_pool_options( + http2=self.parsed_dsn is not None and self.parsed_dsn.scheme == "https" + ) + + def _make_pool( + self: "Self", + ) -> "Union[httpcore.SOCKSProxy, httpcore.HTTPProxy, httpcore.ConnectionPool]": + if self.parsed_dsn is None: + raise ValueError("Cannot create HTTP-based transport without valid DSN") + + proxy = self._resolve_proxy() + opts = self._get_pool_options() + + if proxy: + proxy_headers = self.options["proxy_headers"] + if proxy_headers: + opts["proxy_headers"] = proxy_headers + + if proxy.startswith("socks"): + try: + if "socket_options" in opts: + socket_options = opts.pop("socket_options") + if socket_options: + logger.warning( + "You have defined socket_options but using a SOCKS proxy which doesn't support these. We'll ignore socket_options." + ) + return httpcore.SOCKSProxy(proxy_url=proxy, **opts) + except RuntimeError: + logger.warning( + "You have configured a SOCKS proxy (%s) but support for SOCKS proxies is not installed. Disabling proxy support.", + proxy, + ) + else: + return httpcore.HTTPProxy(proxy_url=proxy, **opts) + + return httpcore.ConnectionPool(**opts) + + +class _EnvelopePrinterTransport(Transport): + """Wraps another transport, printing envelope contents to the SDK debug logger before sending.""" + + def __init__(self, transport: "Transport") -> None: + Transport.__init__(self, options=transport.options) + self._inner = transport + self.parsed_dsn = transport.parsed_dsn + + self.envelope_logger = logging.getLogger("sentry_sdk.envelopes") + self.envelope_logger.setLevel(logging.INFO) + self.envelope_logger.propagate = False + if not self.envelope_logger.handlers: + handler = logging.StreamHandler() + handler.setLevel(logging.INFO) + handler.setFormatter(logging.Formatter("%(message)s")) + self.envelope_logger.addHandler(handler) + + @property # type: ignore[misc] + def __class__(self) -> type: + return self._inner.__class__ + + def capture_envelope(self, envelope: "Envelope") -> None: + try: + self.envelope_logger.info("--- Sentry Envelope ---") + self.envelope_logger.info( + "Headers: %s", json.dumps(envelope.headers, indent=2, default=str) + ) + for item in envelope.items: + self.envelope_logger.info(" Item type: %s", item.type) + self.envelope_logger.info( + " Item headers: %s", + json.dumps(item.headers, indent=2, default=str), + ) + try: + payload = json.loads(item.get_bytes()) + self.envelope_logger.info( + " Payload:\n%s", + json.dumps(payload, indent=2, default=str), + ) + except (ValueError, TypeError): + self.envelope_logger.info( + " Payload: ", + len(item.get_bytes()), + ) + self.envelope_logger.info("--- End Envelope ---") + except Exception: + pass + + self._inner.capture_envelope(envelope) + + def flush( + self, + timeout: float, + callback: "Optional[Any]" = None, + ) -> "Any": + return self._inner.flush(timeout, callback) + + def kill(self) -> "Any": + return self._inner.kill() + + def record_lost_event( + self, + reason: str, + data_category: "Optional[EventDataCategory]" = None, + item: "Optional[Item]" = None, + *, + quantity: int = 1, + ) -> None: + self._inner.record_lost_event(reason, data_category, item, quantity=quantity) + + def is_healthy(self) -> bool: + return self._inner.is_healthy() + + def __getattr__(self, name: str) -> "Any": + return getattr(self._inner, name) + + +class _FunctionTransport(Transport): + """ + DEPRECATED: Users wishing to provide a custom transport should subclass + the Transport class, rather than providing a function. + """ + + def __init__( + self, + func: "Callable[[Event], None]", + ) -> None: + Transport.__init__(self) + self._func = func + + def capture_event( + self, + event: "Event", + ) -> None: + self._func(event) + return None + + def capture_envelope(self, envelope: "Envelope") -> None: + # Since function transports expect to be called with an event, we need + # to iterate over the envelope and call the function for each event, via + # the deprecated capture_event method. + event = envelope.get_event() + if event is not None: + self.capture_event(event) + + +def make_transport(options: "Dict[str, Any]") -> "Optional[Transport]": + ref_transport = options["transport"] + + use_http2_transport = options.get("_experiments", {}).get("transport_http2", False) + use_async_transport = options.get("_experiments", {}).get("transport_async", False) + async_integration = any( + integration.__class__.__name__ == "AsyncioIntegration" + for integration in options.get("integrations") or [] + ) + + # By default, we use the http transport class + transport_cls: "Type[Transport]" = ( + Http2Transport if use_http2_transport else HttpTransport + ) + + if use_async_transport and ASYNC_TRANSPORT_AVAILABLE: + try: + asyncio.get_running_loop() + if async_integration: + if use_http2_transport: + logger.warning( + "HTTP/2 transport is not supported with async transport. " + "Ignoring transport_http2 experiment." + ) + transport_cls = AsyncHttpTransport + else: + logger.warning( + "You tried to use AsyncHttpTransport but the AsyncioIntegration is not enabled. Falling back to sync transport." + ) + except RuntimeError: + # No event loop running, fall back to sync transport + logger.warning("No event loop running, falling back to sync transport.") + elif use_async_transport: + logger.warning( + "You tried to use AsyncHttpTransport but don't have httpcore[asyncio] installed. Falling back to sync transport." + ) + + transport: "Optional[Transport]" = None + + if isinstance(ref_transport, Transport): + transport = ref_transport + elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport): + transport_cls = ref_transport + elif callable(ref_transport): + warnings.warn( + "Function transports are deprecated and will be removed in a future release." + "Please provide a Transport instance or subclass, instead.", + DeprecationWarning, + stacklevel=2, + ) + transport = _FunctionTransport(ref_transport) + + # if a transport class is given only instantiate it if the dsn is not + # empty or None + if transport is None and options["dsn"]: + transport = transport_cls(options) + + if transport is not None and os.environ.get( + "SENTRY_PRINT_ENVELOPES", "" + ).lower() in ("1", "true", "yes"): + transport = _EnvelopePrinterTransport(transport) + + return transport diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/types.py new file mode 100644 index 0000000000000000000000000000000000000000..8b28166462ba34052438c3ecc2efd977efa8f8c8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/types.py @@ -0,0 +1,52 @@ +""" +This module contains type definitions for the Sentry SDK's public API. +The types are re-exported from the internal module `sentry_sdk._types`. + +Disclaimer: Since types are a form of documentation, type definitions +may change in minor releases. Removing a type would be considered a +breaking change, and so we will only remove type definitions in major +releases. +""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # Re-export types to make them available in the public API + from sentry_sdk._types import ( + Breadcrumb, + BreadcrumbHint, + Event, + EventDataCategory, + Hint, + Log, + MonitorConfig, + SamplingContext, + Metric, + ) +else: + from typing import Any + + # The lines below allow the types to be imported from outside `if TYPE_CHECKING` + # guards. The types in this module are only intended to be used for type hints. + Breadcrumb = Any + BreadcrumbHint = Any + Event = Any + EventDataCategory = Any + Hint = Any + Log = Any + MonitorConfig = Any + SamplingContext = Any + Metric = Any + + +__all__ = ( + "Breadcrumb", + "BreadcrumbHint", + "Event", + "EventDataCategory", + "Hint", + "Log", + "MonitorConfig", + "SamplingContext", + "Metric", +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5051a3d9d2c6f73f8bde69b2ad0a5e0b1a01ed5d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/utils.py @@ -0,0 +1,2164 @@ +import base64 +import contextvars +import copy +import json +import linecache +import logging +import math +import os +import random +import re +import subprocess +import sys +import threading +import time +from collections import namedtuple +from contextlib import contextmanager +from datetime import datetime, timezone +from decimal import Decimal +from functools import partial, partialmethod, wraps +from numbers import Real +from urllib.parse import parse_qs, unquote, urlencode, urlsplit, urlunsplit + +try: + # Python 3.11 + from builtins import BaseExceptionGroup +except ImportError: + # Python 3.10 and below + BaseExceptionGroup = None # type: ignore + +try: + from aiohttp.web_exceptions import HTTPException as AIOHttpHttpException +except ImportError: + AIOHttpHttpException = None + +from typing import TYPE_CHECKING + +import sentry_sdk +from sentry_sdk._compat import PY37 +from sentry_sdk._types import SENSITIVE_DATA_SUBSTITUTE, Annotated, AnnotatedValue +from sentry_sdk.consts import ( + DEFAULT_ADD_FULL_STACK, + DEFAULT_MAX_STACK_FRAMES, + DEFAULT_MAX_VALUE_LENGTH, + EndpointType, +) + +if TYPE_CHECKING: + from types import FrameType, TracebackType + from typing import ( + Any, + Callable, + ContextManager, + Dict, + Generator, + Iterator, + List, + NoReturn, + Optional, + ParamSpec, + Set, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, + ) + + from gevent.hub import Hub + + from sentry_sdk._types import ( + AttributeValue, + Event, + ExcInfo, + Hint, + Log, + Metric, + SerializedAttributeValue, + ) + + P = ParamSpec("P") + R = TypeVar("R") + + +epoch = datetime(1970, 1, 1) + +# The logger is created here but initialized in the debug support module +logger = logging.getLogger("sentry_sdk.errors") + +_installed_modules = None + +_is_sentry_internal_task = contextvars.ContextVar( + "is_sentry_internal_task", default=False +) + + +def is_internal_task() -> bool: + return _is_sentry_internal_task.get() + + +@contextmanager +def mark_sentry_task_internal() -> "Generator[None, None, None]": + """Context manager to mark a task as Sentry internal.""" + token = _is_sentry_internal_task.set(True) + try: + yield + finally: + _is_sentry_internal_task.reset(token) + + +BASE64_ALPHABET = re.compile(r"^[a-zA-Z0-9/+=]*$") + +FALSY_ENV_VALUES = frozenset(("false", "f", "n", "no", "off", "0")) +TRUTHY_ENV_VALUES = frozenset(("true", "t", "y", "yes", "on", "1")) + +MAX_STACK_FRAMES = 2000 +"""Maximum number of stack frames to send to Sentry. + +If we have more than this number of stack frames, we will stop processing +the stacktrace to avoid getting stuck in a long-lasting loop. This value +exceeds the default sys.getrecursionlimit() of 1000, so users will only +be affected by this limit if they have a custom recursion limit. +""" + + +def env_to_bool(value: "Any", *, strict: "Optional[bool]" = False) -> "bool | None": + """Casts an ENV variable value to boolean using the constants defined above. + In strict mode, it may return None if the value doesn't match any of the predefined values. + """ + normalized = str(value).lower() if value is not None else None + + if normalized in FALSY_ENV_VALUES: + return False + + if normalized in TRUTHY_ENV_VALUES: + return True + + return None if strict else bool(value) + + +def json_dumps(data: "Any") -> bytes: + """Serialize data into a compact JSON representation encoded as UTF-8.""" + return json.dumps(data, allow_nan=False, separators=(",", ":")).encode("utf-8") + + +def get_git_revision() -> "Optional[str]": + try: + with open(os.path.devnull, "w+") as null: + # prevent command prompt windows from popping up on windows + startupinfo = None + if sys.platform == "win32" or sys.platform == "cygwin": + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + + revision = ( + subprocess.Popen( + ["git", "rev-parse", "HEAD"], + startupinfo=startupinfo, + stdout=subprocess.PIPE, + stderr=null, + stdin=null, + ) + .communicate()[0] + .strip() + .decode("utf-8") + ) + except (OSError, IOError, FileNotFoundError): + return None + + return revision + + +def get_default_release() -> "Optional[str]": + """Try to guess a default release.""" + release = os.environ.get("SENTRY_RELEASE") + if release: + return release + + release = get_git_revision() + if release: + return release + + for var in ( + "HEROKU_BUILD_COMMIT", + "HEROKU_SLUG_COMMIT", # deprecated by Heroku, kept for backward compatibility + "SOURCE_VERSION", + "CODEBUILD_RESOLVED_SOURCE_VERSION", + "CIRCLE_SHA1", + "GAE_DEPLOYMENT_ID", + "K_REVISION", + ): + release = os.environ.get(var) + if release: + return release + return None + + +def get_sdk_name(installed_integrations: "List[str]") -> str: + """Return the SDK name including the name of the used web framework.""" + + # Note: I can not use for example sentry_sdk.integrations.django.DjangoIntegration.identifier + # here because if django is not installed the integration is not accessible. + framework_integrations = [ + "django", + "flask", + "fastapi", + "bottle", + "falcon", + "quart", + "sanic", + "starlette", + "litestar", + "starlite", + "chalice", + "serverless", + "pyramid", + "tornado", + "aiohttp", + "aws_lambda", + "gcp", + "beam", + "asgi", + "wsgi", + ] + + for integration in framework_integrations: + if integration in installed_integrations: + return "sentry.python.{}".format(integration) + + return "sentry.python" + + +class CaptureInternalException: + __slots__ = () + + def __enter__(self) -> "ContextManager[Any]": + return self + + def __exit__( + self, + ty: "Optional[Type[BaseException]]", + value: "Optional[BaseException]", + tb: "Optional[TracebackType]", + ) -> bool: + if ty is not None and value is not None: + capture_internal_exception((ty, value, tb)) + + return True + + +_CAPTURE_INTERNAL_EXCEPTION = CaptureInternalException() + + +def capture_internal_exceptions() -> "ContextManager[Any]": + return _CAPTURE_INTERNAL_EXCEPTION + + +def capture_internal_exception(exc_info: "ExcInfo") -> None: + """ + Capture an exception that is likely caused by a bug in the SDK + itself. + + These exceptions do not end up in Sentry and are just logged instead. + """ + if sentry_sdk.get_client().is_active(): + logger.error("Internal error in sentry_sdk", exc_info=exc_info) + + +def to_timestamp(value: "datetime") -> float: + return (value - epoch).total_seconds() + + +def format_timestamp(value: "datetime") -> str: + """Formats a timestamp in RFC 3339 format. + + Any datetime objects with a non-UTC timezone are converted to UTC, so that all timestamps are formatted in UTC. + """ + utctime = value.astimezone(timezone.utc) + + # We use this custom formatting rather than isoformat for backwards compatibility (we have used this format for + # several years now), and isoformat is slightly different. + return utctime.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +ISO_TZ_SEPARATORS = frozenset(("+", "-")) + + +def datetime_from_isoformat(value: str) -> "datetime": + try: + result = datetime.fromisoformat(value) + except (AttributeError, ValueError): + # py 3.6 + timestamp_format = ( + "%Y-%m-%dT%H:%M:%S.%f" if "." in value else "%Y-%m-%dT%H:%M:%S" + ) + if value.endswith("Z"): + value = value[:-1] + "+0000" + + if value[-6] in ISO_TZ_SEPARATORS: + timestamp_format += "%z" + value = value[:-3] + value[-2:] + elif value[-5] in ISO_TZ_SEPARATORS: + timestamp_format += "%z" + + result = datetime.strptime(value, timestamp_format) + return result.astimezone(timezone.utc) + + +def event_hint_with_exc_info( + exc_info: "Optional[ExcInfo]" = None, +) -> "Dict[str, Optional[ExcInfo]]": + """Creates a hint with the exc info filled in.""" + if exc_info is None: + exc_info = sys.exc_info() + else: + exc_info = exc_info_from_error(exc_info) + if exc_info[0] is None: + exc_info = None + return {"exc_info": exc_info} + + +class BadDsn(ValueError): + """Raised on invalid DSNs.""" + + +class Dsn: + """Represents a DSN.""" + + ORG_ID_REGEX = re.compile(r"^o(\d+)\.") + + def __init__( + self, value: "Union[Dsn, str]", org_id: "Optional[str]" = None + ) -> None: + if isinstance(value, Dsn): + self.__dict__ = dict(value.__dict__) + return + parts = urlsplit(str(value)) + + if parts.scheme not in ("http", "https"): + raise BadDsn("Unsupported scheme %r" % parts.scheme) + self.scheme = parts.scheme + + if parts.hostname is None: + raise BadDsn("Missing hostname") + + self.host = parts.hostname + + if org_id is not None: + self.org_id: "Optional[str]" = org_id + else: + org_id_match = Dsn.ORG_ID_REGEX.match(self.host) + self.org_id = org_id_match.group(1) if org_id_match else None + + if parts.port is None: + self.port: int = self.scheme == "https" and 443 or 80 + else: + self.port = parts.port + + if not parts.username: + raise BadDsn("Missing public key") + + self.public_key = parts.username + self.secret_key = parts.password + + path = parts.path.rsplit("/", 1) + + try: + self.project_id = str(int(path.pop())) + except (ValueError, TypeError): + raise BadDsn("Invalid project in DSN (%r)" % (parts.path or "")[1:]) + + self.path = "/".join(path) + "/" + + @property + def netloc(self) -> str: + """The netloc part of a DSN.""" + rv = self.host + if (self.scheme, self.port) not in (("http", 80), ("https", 443)): + rv = "%s:%s" % (rv, self.port) + return rv + + def to_auth(self, client: "Optional[Any]" = None) -> "Auth": + """Returns the auth info object for this dsn.""" + return Auth( + scheme=self.scheme, + host=self.netloc, + path=self.path, + project_id=self.project_id, + public_key=self.public_key, + secret_key=self.secret_key, + client=client, + ) + + def __str__(self) -> str: + return "%s://%s%s@%s%s%s" % ( + self.scheme, + self.public_key, + self.secret_key and "@" + self.secret_key or "", + self.netloc, + self.path, + self.project_id, + ) + + +class Auth: + """Helper object that represents the auth info.""" + + def __init__( + self, + scheme: str, + host: str, + project_id: str, + public_key: str, + secret_key: "Optional[str]" = None, + version: int = 7, + client: "Optional[Any]" = None, + path: str = "/", + ) -> None: + self.scheme = scheme + self.host = host + self.path = path + self.project_id = project_id + self.public_key = public_key + self.secret_key = secret_key + self.version = version + self.client = client + + def get_api_url( + self, + type: "EndpointType" = EndpointType.ENVELOPE, + ) -> str: + """Returns the API url for storing events.""" + return "%s://%s%sapi/%s/%s/" % ( + self.scheme, + self.host, + self.path, + self.project_id, + type.value, + ) + + def to_header(self) -> str: + """Returns the auth header a string.""" + rv = [("sentry_key", self.public_key), ("sentry_version", self.version)] + if self.client is not None: + rv.append(("sentry_client", self.client)) + if self.secret_key is not None: + rv.append(("sentry_secret", self.secret_key)) + return "Sentry " + ", ".join("%s=%s" % (key, value) for key, value in rv) + + +def get_type_name(cls: "Optional[type]") -> "Optional[str]": + return getattr(cls, "__qualname__", None) or getattr(cls, "__name__", None) + + +def get_type_module(cls: "Optional[type]") -> "Optional[str]": + mod = getattr(cls, "__module__", None) + if mod not in (None, "builtins", "__builtins__"): + return mod + return None + + +def should_hide_frame(frame: "FrameType") -> bool: + try: + mod = frame.f_globals["__name__"] + if mod.startswith("sentry_sdk."): + return True + except (AttributeError, KeyError): + pass + + for flag_name in "__traceback_hide__", "__tracebackhide__": + try: + if frame.f_locals[flag_name]: + return True + except Exception: + pass + + return False + + +def iter_stacks(tb: "Optional[TracebackType]") -> "Iterator[TracebackType]": + tb_: "Optional[TracebackType]" = tb + while tb_ is not None: + if not should_hide_frame(tb_.tb_frame): + yield tb_ + tb_ = tb_.tb_next + + +def get_lines_from_file( + filename: str, + lineno: int, + max_length: "Optional[int]" = None, + loader: "Optional[Any]" = None, + module: "Optional[str]" = None, +) -> "Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]": + context_lines = 5 + source = None + if loader is not None and hasattr(loader, "get_source"): + try: + source_str: "Optional[str]" = loader.get_source(module) + except (ImportError, IOError): + source_str = None + if source_str is not None: + source = source_str.splitlines() + + if source is None: + try: + source = linecache.getlines(filename) + except (OSError, IOError): + return [], None, [] + + if not source: + return [], None, [] + + lower_bound = max(0, lineno - context_lines) + upper_bound = min(lineno + 1 + context_lines, len(source)) + + try: + pre_context = [ + strip_string(line.strip("\r\n"), max_length=max_length) + for line in source[lower_bound:lineno] + ] + context_line = strip_string(source[lineno].strip("\r\n"), max_length=max_length) + post_context = [ + strip_string(line.strip("\r\n"), max_length=max_length) + for line in source[(lineno + 1) : upper_bound] + ] + return pre_context, context_line, post_context + except IndexError: + # the file may have changed since it was loaded into memory + return [], None, [] + + +def get_source_context( + frame: "FrameType", + tb_lineno: "Optional[int]", + max_value_length: "Optional[int]" = None, +) -> "Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]": + try: + abs_path: "Optional[str]" = frame.f_code.co_filename + except Exception: + abs_path = None + try: + module = frame.f_globals["__name__"] + except Exception: + return [], None, [] + try: + loader = frame.f_globals["__loader__"] + except Exception: + loader = None + + if tb_lineno is not None and abs_path: + lineno = tb_lineno - 1 + return get_lines_from_file( + abs_path, lineno, max_value_length, loader=loader, module=module + ) + + return [], None, [] + + +def safe_str(value: "Any") -> str: + try: + return str(value) + except Exception: + return safe_repr(value) + + +def safe_repr(value: "Any") -> str: + try: + return repr(value) + except Exception: + return "" + + +def filename_for_module( + module: "Optional[str]", abs_path: "Optional[str]" +) -> "Optional[str]": + if not abs_path or not module: + return abs_path + + try: + if abs_path.endswith(".pyc"): + abs_path = abs_path[:-1] + + base_module = module.split(".", 1)[0] + if base_module == module: + return os.path.basename(abs_path) + + base_module_path = sys.modules[base_module].__file__ + if not base_module_path: + return abs_path + + return abs_path.split(base_module_path.rsplit(os.sep, 2)[0], 1)[-1].lstrip( + os.sep + ) + except Exception: + return abs_path + + +def serialize_frame( + frame: "FrameType", + tb_lineno: "Optional[int]" = None, + include_local_variables: bool = True, + include_source_context: bool = True, + max_value_length: "Optional[int]" = None, + custom_repr: "Optional[Callable[..., Optional[str]]]" = None, +) -> "Dict[str, Any]": + f_code = getattr(frame, "f_code", None) + if not f_code: + abs_path = None + function = None + else: + abs_path = frame.f_code.co_filename + function = frame.f_code.co_name + try: + module = frame.f_globals["__name__"] + except Exception: + module = None + + if tb_lineno is None: + tb_lineno = frame.f_lineno + + try: + os_abs_path = os.path.abspath(abs_path) if abs_path else None + except Exception: + os_abs_path = None + + rv: "Dict[str, Any]" = { + "filename": filename_for_module(module, abs_path) or None, + "abs_path": os_abs_path, + "function": function or "", + "module": module, + "lineno": tb_lineno, + } + + if include_source_context: + rv["pre_context"], rv["context_line"], rv["post_context"] = get_source_context( + frame, tb_lineno, max_value_length + ) + + if include_local_variables: + from sentry_sdk.serializer import serialize + + rv["vars"] = serialize( + dict(frame.f_locals), is_vars=True, custom_repr=custom_repr + ) + + return rv + + +def current_stacktrace( + include_local_variables: bool = True, + include_source_context: bool = True, + max_value_length: "Optional[int]" = None, +) -> "Dict[str, Any]": + __tracebackhide__ = True + frames = [] + + f: "Optional[FrameType]" = sys._getframe() + while f is not None: + if not should_hide_frame(f): + frames.append( + serialize_frame( + f, + include_local_variables=include_local_variables, + include_source_context=include_source_context, + max_value_length=max_value_length, + ) + ) + f = f.f_back + + frames.reverse() + + return {"frames": frames} + + +def get_errno(exc_value: BaseException) -> "Optional[Any]": + return getattr(exc_value, "errno", None) + + +def get_error_message(exc_value: "Optional[BaseException]") -> str: + message: str = safe_str( + getattr(exc_value, "message", "") + or getattr(exc_value, "detail", "") + or safe_str(exc_value) + ) + + # __notes__ should be a list of strings when notes are added + # via add_note, but can be anything else if __notes__ is set + # directly. We only support strings in __notes__, since that + # is the correct use. + notes: object = getattr(exc_value, "__notes__", None) + if isinstance(notes, list) and len(notes) > 0: + message += "\n" + "\n".join(note for note in notes if isinstance(note, str)) + + return message + + +def single_exception_from_error_tuple( + exc_type: "Optional[type]", + exc_value: "Optional[BaseException]", + tb: "Optional[TracebackType]", + client_options: "Optional[Dict[str, Any]]" = None, + mechanism: "Optional[Dict[str, Any]]" = None, + exception_id: "Optional[int]" = None, + parent_id: "Optional[int]" = None, + source: "Optional[str]" = None, + full_stack: "Optional[list[dict[str, Any]]]" = None, +) -> "Dict[str, Any]": + """ + Creates a dict that goes into the events `exception.values` list and is ingestible by Sentry. + + See the Exception Interface documentation for more details: + https://develop.sentry.dev/sdk/event-payloads/exception/ + """ + exception_value: "Dict[str, Any]" = {} + exception_value["mechanism"] = ( + mechanism.copy() if mechanism else {"type": "generic", "handled": True} + ) + if exception_id is not None: + exception_value["mechanism"]["exception_id"] = exception_id + + if exc_value is not None: + errno = get_errno(exc_value) + else: + errno = None + + if errno is not None: + exception_value["mechanism"].setdefault("meta", {}).setdefault( + "errno", {} + ).setdefault("number", errno) + + if source is not None: + exception_value["mechanism"]["source"] = source + + is_root_exception = exception_id == 0 + if not is_root_exception and parent_id is not None: + exception_value["mechanism"]["parent_id"] = parent_id + exception_value["mechanism"]["type"] = "chained" + + if is_root_exception and "type" not in exception_value["mechanism"]: + exception_value["mechanism"]["type"] = "generic" + + is_exception_group = BaseExceptionGroup is not None and isinstance( + exc_value, BaseExceptionGroup + ) + if is_exception_group: + exception_value["mechanism"]["is_exception_group"] = True + + exception_value["module"] = get_type_module(exc_type) + exception_value["type"] = get_type_name(exc_type) + exception_value["value"] = get_error_message(exc_value) + + if client_options is None: + include_local_variables = True + include_source_context = True + max_value_length = DEFAULT_MAX_VALUE_LENGTH # fallback + custom_repr = None + else: + include_local_variables = client_options["include_local_variables"] + include_source_context = client_options["include_source_context"] + max_value_length = client_options["max_value_length"] + custom_repr = client_options.get("custom_repr") + + frames: "List[Dict[str, Any]]" = [ + serialize_frame( + tb.tb_frame, + tb_lineno=tb.tb_lineno, + include_local_variables=include_local_variables, + include_source_context=include_source_context, + max_value_length=max_value_length, + custom_repr=custom_repr, + ) + # Process at most MAX_STACK_FRAMES + 1 frames, to avoid hanging on + # processing a super-long stacktrace. + for tb, _ in zip(iter_stacks(tb), range(MAX_STACK_FRAMES + 1)) + ] + + if len(frames) > MAX_STACK_FRAMES: + # If we have more frames than the limit, we remove the stacktrace completely. + # We don't trim the stacktrace here because we have not processed the whole + # thing (see above, we stop at MAX_STACK_FRAMES + 1). Normally, Relay would + # intelligently trim by removing frames in the middle of the stacktrace, but + # since we don't have the whole stacktrace, we can't do that. Instead, we + # drop the entire stacktrace. + exception_value["stacktrace"] = AnnotatedValue.removed_because_over_size_limit( + value=None + ) + + elif frames: + if not full_stack: + new_frames = frames + else: + new_frames = merge_stack_frames(frames, full_stack, client_options) + + exception_value["stacktrace"] = {"frames": new_frames} + + return exception_value + + +HAS_CHAINED_EXCEPTIONS = hasattr(Exception, "__suppress_context__") + +if HAS_CHAINED_EXCEPTIONS: + + def walk_exception_chain(exc_info: "ExcInfo") -> "Iterator[ExcInfo]": + exc_type, exc_value, tb = exc_info + + seen_exceptions = [] + seen_exception_ids: "Set[int]" = set() + + while ( + exc_type is not None + and exc_value is not None + and id(exc_value) not in seen_exception_ids + ): + yield exc_type, exc_value, tb + + # Avoid hashing random types we don't know anything + # about. Use the list to keep a ref so that the `id` is + # not used for another object. + seen_exceptions.append(exc_value) + seen_exception_ids.add(id(exc_value)) + + if exc_value.__suppress_context__: + cause = exc_value.__cause__ + else: + cause = exc_value.__context__ + if cause is None: + break + exc_type = type(cause) + exc_value = cause + tb = getattr(cause, "__traceback__", None) + +else: + + def walk_exception_chain(exc_info: "ExcInfo") -> "Iterator[ExcInfo]": + yield exc_info + + +def exceptions_from_error( + exc_type: "Optional[type]", + exc_value: "Optional[BaseException]", + tb: "Optional[TracebackType]", + client_options: "Optional[Dict[str, Any]]" = None, + mechanism: "Optional[Dict[str, Any]]" = None, + exception_id: int = 0, + parent_id: int = 0, + source: "Optional[str]" = None, + full_stack: "Optional[list[dict[str, Any]]]" = None, + seen_exceptions: "Optional[list[BaseException]]" = None, + seen_exception_ids: "Optional[Set[int]]" = None, +) -> "Tuple[int, List[Dict[str, Any]]]": + """ + Creates the list of exceptions. + This can include chained exceptions and exceptions from an ExceptionGroup. + + See the Exception Interface documentation for more details: + https://develop.sentry.dev/sdk/event-payloads/exception/ + + Args: + exception_id (int): + + Sequential counter for assigning ``mechanism.exception_id`` + to each processed exception. Is NOT the result of calling `id()` on the exception itself. + + parent_id (int): + + The ``mechanism.exception_id`` of the parent exception. + + Written into ``mechanism.parent_id`` in the event payload so Sentry can + reconstruct the exception tree. + + Not to be confused with ``seen_exception_ids``, which tracks Python ``id()`` + values for cycle detection. + """ + + if seen_exception_ids is None: + seen_exception_ids = set() + + if seen_exceptions is None: + seen_exceptions = [] + + if exc_value is not None and id(exc_value) in seen_exception_ids: + return (exception_id, []) + + if exc_value is not None: + seen_exceptions.append(exc_value) + seen_exception_ids.add(id(exc_value)) + + parent = single_exception_from_error_tuple( + exc_type=exc_type, + exc_value=exc_value, + tb=tb, + client_options=client_options, + mechanism=mechanism, + exception_id=exception_id, + parent_id=parent_id, + source=source, + full_stack=full_stack, + ) + exceptions = [parent] + + parent_id = exception_id + exception_id += 1 + + should_supress_context = ( + hasattr(exc_value, "__suppress_context__") and exc_value.__suppress_context__ # type: ignore + ) + if should_supress_context: + # Add direct cause. + # The field `__cause__` is set when raised with the exception (using the `from` keyword). + exception_has_cause = ( + exc_value + and hasattr(exc_value, "__cause__") + and exc_value.__cause__ is not None + ) + if exception_has_cause: + cause = exc_value.__cause__ # type: ignore + (exception_id, child_exceptions) = exceptions_from_error( + exc_type=type(cause), + exc_value=cause, + tb=getattr(cause, "__traceback__", None), + client_options=client_options, + mechanism=mechanism, + exception_id=exception_id, + source="__cause__", + full_stack=full_stack, + seen_exceptions=seen_exceptions, + seen_exception_ids=seen_exception_ids, + ) + exceptions.extend(child_exceptions) + + else: + # Add indirect cause. + # The field `__context__` is assigned if another exception occurs while handling the exception. + exception_has_content = ( + exc_value + and hasattr(exc_value, "__context__") + and exc_value.__context__ is not None + ) + if exception_has_content: + context = exc_value.__context__ # type: ignore + (exception_id, child_exceptions) = exceptions_from_error( + exc_type=type(context), + exc_value=context, + tb=getattr(context, "__traceback__", None), + client_options=client_options, + mechanism=mechanism, + exception_id=exception_id, + source="__context__", + full_stack=full_stack, + seen_exceptions=seen_exceptions, + seen_exception_ids=seen_exception_ids, + ) + exceptions.extend(child_exceptions) + + # Add exceptions from an ExceptionGroup. + is_exception_group = exc_value and hasattr(exc_value, "exceptions") + if is_exception_group: + for idx, e in enumerate(exc_value.exceptions): # type: ignore + (exception_id, child_exceptions) = exceptions_from_error( + exc_type=type(e), + exc_value=e, + tb=getattr(e, "__traceback__", None), + client_options=client_options, + mechanism=mechanism, + exception_id=exception_id, + parent_id=parent_id, + source="exceptions[%s]" % idx, + full_stack=full_stack, + seen_exceptions=seen_exceptions, + seen_exception_ids=seen_exception_ids, + ) + exceptions.extend(child_exceptions) + + return (exception_id, exceptions) + + +def exceptions_from_error_tuple( + exc_info: "ExcInfo", + client_options: "Optional[Dict[str, Any]]" = None, + mechanism: "Optional[Dict[str, Any]]" = None, + full_stack: "Optional[list[dict[str, Any]]]" = None, +) -> "List[Dict[str, Any]]": + exc_type, exc_value, tb = exc_info + + is_exception_group = BaseExceptionGroup is not None and isinstance( + exc_value, BaseExceptionGroup + ) + + if is_exception_group: + (_, exceptions) = exceptions_from_error( + exc_type=exc_type, + exc_value=exc_value, + tb=tb, + client_options=client_options, + mechanism=mechanism, + exception_id=0, + parent_id=0, + full_stack=full_stack, + ) + + else: + exceptions = [] + for exc_type, exc_value, tb in walk_exception_chain(exc_info): + exceptions.append( + single_exception_from_error_tuple( + exc_type=exc_type, + exc_value=exc_value, + tb=tb, + client_options=client_options, + mechanism=mechanism, + full_stack=full_stack, + ) + ) + + exceptions.reverse() + + return exceptions + + +def to_string(value: str) -> str: + try: + return str(value) + except UnicodeDecodeError: + return repr(value)[1:-1] + + +def iter_event_stacktraces(event: "Event") -> "Iterator[Annotated[Dict[str, Any]]]": + if "stacktrace" in event: + yield event["stacktrace"] + if "threads" in event: + for thread in event["threads"].get("values") or (): + if "stacktrace" in thread: + yield thread["stacktrace"] + if "exception" in event: + for exception in event["exception"].get("values") or (): + if isinstance(exception, dict) and "stacktrace" in exception: + yield exception["stacktrace"] + + +def iter_event_frames(event: "Event") -> "Iterator[Dict[str, Any]]": + for stacktrace in iter_event_stacktraces(event): + if isinstance(stacktrace, AnnotatedValue): + stacktrace = stacktrace.value or {} + + for frame in stacktrace.get("frames") or (): + yield frame + + +def handle_in_app( + event: "Event", + in_app_exclude: "Optional[List[str]]" = None, + in_app_include: "Optional[List[str]]" = None, + project_root: "Optional[str]" = None, +) -> "Event": + for stacktrace in iter_event_stacktraces(event): + if isinstance(stacktrace, AnnotatedValue): + stacktrace = stacktrace.value or {} + + set_in_app_in_frames( + stacktrace.get("frames"), + in_app_exclude=in_app_exclude, + in_app_include=in_app_include, + project_root=project_root, + ) + + return event + + +def set_in_app_in_frames( + frames: "Any", + in_app_exclude: "Optional[List[str]]", + in_app_include: "Optional[List[str]]", + project_root: "Optional[str]" = None, +) -> "Optional[Any]": + if not frames: + return None + + for frame in frames: + # if frame has already been marked as in_app, skip it + current_in_app = frame.get("in_app") + if current_in_app is not None: + continue + + module = frame.get("module") + + # check if module in frame is in the list of modules to include + if _module_in_list(module, in_app_include): + frame["in_app"] = True + continue + + # check if module in frame is in the list of modules to exclude + if _module_in_list(module, in_app_exclude): + frame["in_app"] = False + continue + + # if frame has no abs_path, skip further checks + abs_path = frame.get("abs_path") + if abs_path is None: + continue + + if _is_external_source(abs_path): + frame["in_app"] = False + continue + + if _is_in_project_root(abs_path, project_root): + frame["in_app"] = True + continue + + return frames + + +def exc_info_from_error(error: "Union[BaseException, ExcInfo]") -> "ExcInfo": + if isinstance(error, tuple) and len(error) == 3: + exc_type, exc_value, tb = error + elif isinstance(error, BaseException): + tb = getattr(error, "__traceback__", None) + if tb is not None: + exc_type = type(error) + exc_value = error + else: + exc_type, exc_value, tb = sys.exc_info() + if exc_value is not error: + tb = None + exc_value = error + exc_type = type(error) + + else: + raise ValueError("Expected Exception object to report, got %s!" % type(error)) + + exc_info = (exc_type, exc_value, tb) + + if TYPE_CHECKING: + # This cast is safe because exc_type and exc_value are either both + # None or both not None. + exc_info = cast(ExcInfo, exc_info) + + return exc_info + + +def merge_stack_frames( + frames: "List[Dict[str, Any]]", + full_stack: "List[Dict[str, Any]]", + client_options: "Optional[Dict[str, Any]]", +) -> "List[Dict[str, Any]]": + """ + Add the missing frames from full_stack to frames and return the merged list. + """ + frame_ids = { + ( + frame["abs_path"], + frame["context_line"], + frame["lineno"], + frame["function"], + ) + for frame in frames + } + + new_frames = [ + stackframe + for stackframe in full_stack + if ( + stackframe["abs_path"], + stackframe["context_line"], + stackframe["lineno"], + stackframe["function"], + ) + not in frame_ids + ] + new_frames.extend(frames) + + # Limit the number of frames + max_stack_frames = ( + client_options.get("max_stack_frames", DEFAULT_MAX_STACK_FRAMES) + if client_options + else None + ) + if max_stack_frames is not None: + new_frames = new_frames[len(new_frames) - max_stack_frames :] + + return new_frames + + +def event_from_exception( + exc_info: "Union[BaseException, ExcInfo]", + client_options: "Optional[Dict[str, Any]]" = None, + mechanism: "Optional[Dict[str, Any]]" = None, +) -> "Tuple[Event, Dict[str, Any]]": + exc_info = exc_info_from_error(exc_info) + hint = event_hint_with_exc_info(exc_info) + + if client_options and client_options.get("add_full_stack", DEFAULT_ADD_FULL_STACK): + full_stack = current_stacktrace( + include_local_variables=client_options["include_local_variables"], + max_value_length=client_options["max_value_length"], + )["frames"] + else: + full_stack = None + + return ( + { + "level": "error", + "exception": { + "values": exceptions_from_error_tuple( + exc_info, client_options, mechanism, full_stack + ) + }, + }, + hint, + ) + + +def _module_in_list(name: "Optional[str]", items: "Optional[List[str]]") -> bool: + if name is None: + return False + + if not items: + return False + + for item in items: + if item == name or name.startswith(item + "."): + return True + + return False + + +def _is_external_source(abs_path: "Optional[str]") -> bool: + # check if frame is in 'site-packages' or 'dist-packages' + if abs_path is None: + return False + + external_source = ( + re.search(r"[\\/](?:dist|site)-packages[\\/]", abs_path) is not None + ) + return external_source + + +def _is_in_project_root( + abs_path: "Optional[str]", project_root: "Optional[str]" +) -> bool: + if abs_path is None or project_root is None: + return False + + # check if path is in the project root + if abs_path.startswith(project_root): + return True + + return False + + +def _truncate_by_bytes(string: str, max_bytes: int) -> str: + """ + Truncate a UTF-8-encodable string to the last full codepoint so that it fits in max_bytes. + """ + truncated = string.encode("utf-8")[: max_bytes - 3].decode("utf-8", errors="ignore") + + return truncated + "..." + + +def _get_size_in_bytes(value: str) -> "Optional[int]": + try: + return len(value.encode("utf-8")) + except (UnicodeEncodeError, UnicodeDecodeError): + return None + + +def strip_string( + value: str, max_length: "Optional[int]" = None +) -> "Union[AnnotatedValue, str]": + if not value: + return value + + if max_length is None: + max_length = DEFAULT_MAX_VALUE_LENGTH + + byte_size = _get_size_in_bytes(value) + text_size = len(value) + + if byte_size is not None and byte_size > max_length: + # truncate to max_length bytes, preserving code points + truncated_value = _truncate_by_bytes(value, max_length) + elif text_size is not None and text_size > max_length: + # fallback to truncating by string length + truncated_value = value[: max_length - 3] + "..." + else: + return value + + return AnnotatedValue( + value=truncated_value, + metadata={ + "len": byte_size or text_size, + "rem": [["!limit", "x", max_length - 3, max_length]], + }, + ) + + +def parse_version(version: str) -> "Optional[Tuple[int, ...]]": + """ + Parses a version string into a tuple of integers. + This uses the parsing loging from PEP 440: + https://peps.python.org/pep-0440/#appendix-b-parsing-version-strings-with-regular-expressions + """ + VERSION_PATTERN = r""" # noqa: N806 + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                                    # pre-release
          +                [-_\.]?
          +                (?P(a|b|c|rc|alpha|beta|pre|preview))
          +                [-_\.]?
          +                (?P[0-9]+)?
          +            )?
          +            (?P                                         # post release
          +                (?:-(?P[0-9]+))
          +                |
          +                (?:
          +                    [-_\.]?
          +                    (?Ppost|rev|r)
          +                    [-_\.]?
          +                    (?P[0-9]+)?
          +                )
          +            )?
          +            (?P                                          # dev release
          +                [-_\.]?
          +                (?Pdev)
          +                [-_\.]?
          +                (?P[0-9]+)?
          +            )?
          +        )
          +        (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
          +    """
          +
          +    pattern = re.compile(
          +        r"^\s*" + VERSION_PATTERN + r"\s*$",
          +        re.VERBOSE | re.IGNORECASE,
          +    )
          +
          +    try:
          +        release = pattern.match(version).groupdict()["release"]  # type: ignore
          +        release_tuple: "Tuple[int, ...]" = tuple(map(int, release.split(".")[:3]))
          +    except (TypeError, ValueError, AttributeError):
          +        return None
          +
          +    return release_tuple
          +
          +
          +def _is_contextvars_broken() -> bool:
          +    """
          +    Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars.
          +    """
          +    try:
          +        import gevent
          +        from gevent.monkey import is_object_patched
          +
          +        # Get the MAJOR and MINOR version numbers of Gevent
          +        version_tuple = tuple(
          +            [int(part) for part in re.split(r"a|b|rc|\.", gevent.__version__)[:2]]
          +        )
          +        if is_object_patched("threading", "local"):
          +            # Gevent 20.9.0 depends on Greenlet 0.4.17 which natively handles switching
          +            # context vars when greenlets are switched, so, Gevent 20.9.0+ is all fine.
          +            # Ref: https://github.com/gevent/gevent/blob/83c9e2ae5b0834b8f84233760aabe82c3ba065b4/src/gevent/monkey.py#L604-L609
          +            # Gevent 20.5, that doesn't depend on Greenlet 0.4.17 with native support
          +            # for contextvars, is able to patch both thread locals and contextvars, in
          +            # that case, check if contextvars are effectively patched.
          +            if (
          +                # Gevent 20.9.0+
          +                (sys.version_info >= (3, 7) and version_tuple >= (20, 9))
          +                # Gevent 20.5.0+ or Python < 3.7
          +                or (is_object_patched("contextvars", "ContextVar"))
          +            ):
          +                return False
          +
          +            return True
          +    except ImportError:
          +        pass
          +
          +    try:
          +        import greenlet
          +        from eventlet.patcher import is_monkey_patched  # type: ignore
          +
          +        greenlet_version = parse_version(greenlet.__version__)
          +
          +        if greenlet_version is None:
          +            logger.error(
          +                "Internal error in Sentry SDK: Could not parse Greenlet version from greenlet.__version__."
          +            )
          +            return False
          +
          +        if is_monkey_patched("thread") and greenlet_version < (0, 5):
          +            return True
          +    except ImportError:
          +        pass
          +
          +    return False
          +
          +
          +def _make_threadlocal_contextvars(local: type) -> type:
          +    class ContextVar:
          +        # Super-limited impl of ContextVar
          +
          +        def __init__(self, name: str, default: "Any" = None) -> None:
          +            self._name = name
          +            self._default = default
          +            self._local = local()
          +            self._original_local = local()
          +
          +        def get(self, default: "Any" = None) -> "Any":
          +            return getattr(self._local, "value", default or self._default)
          +
          +        def set(self, value: "Any") -> "Any":
          +            token = str(random.getrandbits(64))
          +            original_value = self.get()
          +            setattr(self._original_local, token, original_value)
          +            self._local.value = value
          +            return token
          +
          +        def reset(self, token: "Any") -> None:
          +            self._local.value = getattr(self._original_local, token)
          +            # delete the original value (this way it works in Python 3.6+)
          +            del self._original_local.__dict__[token]
          +
          +    return ContextVar
          +
          +
          +def _get_contextvars() -> "Tuple[bool, type]":
          +    """
          +    Figure out the "right" contextvars installation to use. Returns a
          +    `contextvars.ContextVar`-like class with a limited API.
          +
          +    See https://docs.sentry.io/platforms/python/contextvars/ for more information.
          +    """
          +    if not _is_contextvars_broken():
          +        # aiocontextvars is a PyPI package that ensures that the contextvars
          +        # backport (also a PyPI package) works with asyncio under Python 3.6
          +        #
          +        # Import it if available.
          +        if sys.version_info < (3, 7):
          +            # `aiocontextvars` is absolutely required for functional
          +            # contextvars on Python 3.6.
          +            try:
          +                from aiocontextvars import ContextVar
          +
          +                return True, ContextVar
          +            except ImportError:
          +                pass
          +        else:
          +            # On Python 3.7 contextvars are functional.
          +            try:
          +                from contextvars import ContextVar
          +
          +                return True, ContextVar
          +            except ImportError:
          +                pass
          +
          +    # Fall back to basic thread-local usage.
          +
          +    from threading import local
          +
          +    return False, _make_threadlocal_contextvars(local)
          +
          +
          +HAS_REAL_CONTEXTVARS, ContextVar = _get_contextvars()
          +
          +CONTEXTVARS_ERROR_MESSAGE = """
          +
          +With asyncio/ASGI applications, the Sentry SDK requires a functional
          +installation of `contextvars` to avoid leaking scope/context data across
          +requests.
          +
          +Please refer to https://docs.sentry.io/platforms/python/contextvars/ for more information.
          +"""
          +
          +
          +def qualname_from_function(func: "Callable[..., Any]") -> "Optional[str]":
          +    """Return the qualified name of func. Works with regular function, lambda, partial and partialmethod."""
          +    func_qualname: "Optional[str]" = None
          +
          +    prefix, suffix = "", ""
          +
          +    if isinstance(func, partial) and hasattr(func.func, "__name__"):
          +        prefix, suffix = "partial()"
          +        func = func.func
          +    else:
          +        # The _partialmethod attribute of methods wrapped with partialmethod() was renamed to __partialmethod__ in CPython 3.13:
          +        # https://github.com/python/cpython/pull/16600
          +        partial_method = getattr(func, "_partialmethod", None) or getattr(
          +            func, "__partialmethod__", None
          +        )
          +        if isinstance(partial_method, partialmethod):
          +            prefix, suffix = "partialmethod()"
          +            func = partial_method.func
          +
          +    if hasattr(func, "__qualname__"):
          +        func_qualname = func.__qualname__
          +    elif hasattr(func, "__name__"):
          +        func_qualname = func.__name__
          +
          +    if func_qualname is not None:
          +        if hasattr(func, "__module__") and isinstance(func.__module__, str):
          +            func_qualname = func.__module__ + "." + func_qualname
          +        func_qualname = prefix + func_qualname + suffix
          +
          +    return func_qualname
          +
          +
          +def transaction_from_function(func: "Callable[..., Any]") -> "Optional[str]":
          +    return qualname_from_function(func)
          +
          +
          +disable_capture_event = ContextVar("disable_capture_event")
          +
          +
          +class ServerlessTimeoutWarning(Exception):  # noqa: N818
          +    """Raised when a serverless method is about to reach its timeout."""
          +
          +    pass
          +
          +
          +class TimeoutThread(threading.Thread):
          +    """Creates a Thread which runs (sleeps) for a time duration equal to
          +    waiting_time and raises a custom ServerlessTimeout exception.
          +    """
          +
          +    def __init__(
          +        self,
          +        waiting_time: float,
          +        configured_timeout: int,
          +        isolation_scope: "Optional[sentry_sdk.Scope]" = None,
          +        current_scope: "Optional[sentry_sdk.Scope]" = None,
          +    ) -> None:
          +        threading.Thread.__init__(self)
          +        self.waiting_time = waiting_time
          +        self.configured_timeout = configured_timeout
          +
          +        self.isolation_scope = isolation_scope
          +        self.current_scope = current_scope
          +
          +        self._stop_event = threading.Event()
          +
          +    def stop(self) -> None:
          +        self._stop_event.set()
          +
          +    def _capture_exception(self) -> "ExcInfo":
          +        exc_info = sys.exc_info()
          +
          +        client = sentry_sdk.get_client()
          +        event, hint = event_from_exception(
          +            exc_info,
          +            client_options=client.options,
          +            mechanism={"type": "threading", "handled": False},
          +        )
          +        sentry_sdk.capture_event(event, hint=hint)
          +
          +        return exc_info
          +
          +    def run(self) -> None:
          +        self._stop_event.wait(self.waiting_time)
          +
          +        if self._stop_event.is_set():
          +            return
          +
          +        integer_configured_timeout = int(self.configured_timeout)
          +
          +        # Setting up the exact integer value of configured time(in seconds)
          +        if integer_configured_timeout < self.configured_timeout:
          +            integer_configured_timeout = integer_configured_timeout + 1
          +
          +        # Raising Exception after timeout duration is reached
          +        if self.isolation_scope is not None and self.current_scope is not None:
          +            with sentry_sdk.scope.use_isolation_scope(self.isolation_scope):
          +                with sentry_sdk.scope.use_scope(self.current_scope):
          +                    try:
          +                        raise ServerlessTimeoutWarning(
          +                            "WARNING : Function is expected to get timed out. Configured timeout duration = {} seconds.".format(
          +                                integer_configured_timeout
          +                            )
          +                        )
          +                    except Exception:
          +                        reraise(*self._capture_exception())
          +
          +        raise ServerlessTimeoutWarning(
          +            "WARNING : Function is expected to get timed out. Configured timeout duration = {} seconds.".format(
          +                integer_configured_timeout
          +            )
          +        )
          +
          +
          +def to_base64(original: str) -> "Optional[str]":
          +    """
          +    Convert a string to base64, via UTF-8. Returns None on invalid input.
          +    """
          +    base64_string = None
          +
          +    try:
          +        utf8_bytes = original.encode("UTF-8")
          +        base64_bytes = base64.b64encode(utf8_bytes)
          +        base64_string = base64_bytes.decode("UTF-8")
          +    except Exception as err:
          +        logger.warning("Unable to encode {orig} to base64:".format(orig=original), err)
          +
          +    return base64_string
          +
          +
          +def from_base64(base64_string: str) -> "Optional[str]":
          +    """
          +    Convert a string from base64, via UTF-8. Returns None on invalid input.
          +    """
          +    utf8_string = None
          +
          +    try:
          +        only_valid_chars = BASE64_ALPHABET.match(base64_string)
          +        assert only_valid_chars
          +
          +        base64_bytes = base64_string.encode("UTF-8")
          +        utf8_bytes = base64.b64decode(base64_bytes)
          +        utf8_string = utf8_bytes.decode("UTF-8")
          +    except Exception as err:
          +        logger.warning(
          +            "Unable to decode {b64} from base64:".format(b64=base64_string), err
          +        )
          +
          +    return utf8_string
          +
          +
          +Components = namedtuple("Components", ["scheme", "netloc", "path", "query", "fragment"])
          +
          +
          +def sanitize_url(
          +    url: str,
          +    remove_authority: bool = True,
          +    remove_query_values: bool = True,
          +    split: bool = False,
          +) -> "Union[str, Components]":
          +    """
          +    Removes the authority and query parameter values from a given URL.
          +    """
          +    parsed_url = urlsplit(url)
          +    query_params = parse_qs(parsed_url.query, keep_blank_values=True)
          +
          +    # strip username:password (netloc can be usr:pwd@example.com)
          +    if remove_authority:
          +        netloc_parts = parsed_url.netloc.split("@")
          +        if len(netloc_parts) > 1:
          +            netloc = "%s:%s@%s" % (
          +                SENSITIVE_DATA_SUBSTITUTE,
          +                SENSITIVE_DATA_SUBSTITUTE,
          +                netloc_parts[-1],
          +            )
          +        else:
          +            netloc = parsed_url.netloc
          +    else:
          +        netloc = parsed_url.netloc
          +
          +    # strip values from query string
          +    if remove_query_values:
          +        query_string = unquote(
          +            urlencode({key: SENSITIVE_DATA_SUBSTITUTE for key in query_params})
          +        )
          +    else:
          +        query_string = parsed_url.query
          +
          +    components = Components(
          +        scheme=parsed_url.scheme,
          +        netloc=netloc,
          +        query=query_string,
          +        path=parsed_url.path,
          +        fragment=parsed_url.fragment,
          +    )
          +
          +    if split:
          +        return components
          +    else:
          +        return urlunsplit(components)
          +
          +
          +ParsedUrl = namedtuple("ParsedUrl", ["url", "query", "fragment"])
          +
          +
          +def parse_url(url: str, sanitize: bool = True) -> "ParsedUrl":
          +    """
          +    Splits a URL into a url (including path), query and fragment. If sanitize is True, the query
          +    parameters will be sanitized to remove sensitive data. The autority (username and password)
          +    in the URL will always be removed.
          +    """
          +    parsed_url = sanitize_url(
          +        url, remove_authority=True, remove_query_values=sanitize, split=True
          +    )
          +
          +    base_url = urlunsplit(
          +        Components(
          +            scheme=parsed_url.scheme,  # type: ignore
          +            netloc=parsed_url.netloc,  # type: ignore
          +            query="",
          +            path=parsed_url.path,  # type: ignore
          +            fragment="",
          +        )
          +    )
          +
          +    return ParsedUrl(
          +        url=base_url,
          +        query=parsed_url.query,  # type: ignore
          +        fragment=parsed_url.fragment,  # type: ignore
          +    )
          +
          +
          +def is_valid_sample_rate(rate: "Any", source: str) -> bool:
          +    """
          +    Checks the given sample rate to make sure it is valid type and value (a
          +    boolean or a number between 0 and 1, inclusive).
          +    """
          +
          +    # both booleans and NaN are instances of Real, so a) checking for Real
          +    # checks for the possibility of a boolean also, and b) we have to check
          +    # separately for NaN and Decimal does not derive from Real so need to check that too
          +    if not isinstance(rate, (Real, Decimal)) or math.isnan(rate):
          +        logger.warning(
          +            "{source} Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got {rate} of type {type}.".format(
          +                source=source, rate=rate, type=type(rate)
          +            )
          +        )
          +        return False
          +
          +    # in case rate is a boolean, it will get cast to 1 if it's True and 0 if it's False
          +    rate = float(rate)
          +    if rate < 0 or rate > 1:
          +        logger.warning(
          +            "{source} Given sample rate is invalid. Sample rate must be between 0 and 1. Got {rate}.".format(
          +                source=source, rate=rate
          +            )
          +        )
          +        return False
          +
          +    return True
          +
          +
          +def match_regex_list(
          +    item: str,
          +    regex_list: "Optional[List[str]]" = None,
          +    substring_matching: bool = False,
          +) -> bool:
          +    if regex_list is None:
          +        return False
          +
          +    for item_matcher in regex_list:
          +        if not substring_matching and item_matcher[-1] != "$":
          +            item_matcher += "$"
          +
          +        matched = re.search(item_matcher, item)
          +        if matched:
          +            return True
          +
          +    return False
          +
          +
          +def is_sentry_url(client: "sentry_sdk.client.BaseClient", url: str) -> bool:
          +    """
          +    Determines whether the given URL matches the Sentry DSN.
          +    """
          +    return (
          +        client is not None
          +        and client.transport is not None
          +        and client.transport.parsed_dsn is not None
          +        and client.transport.parsed_dsn.netloc in url
          +    )
          +
          +
          +def _generate_installed_modules() -> "Iterator[Tuple[str, str]]":
          +    try:
          +        from importlib import metadata
          +
          +        yielded = set()
          +        for dist in metadata.distributions():
          +            name = dist.metadata.get("Name", None)  # type: ignore[attr-defined]
          +            # `metadata` values may be `None`, see:
          +            # https://github.com/python/cpython/issues/91216
          +            # and
          +            # https://github.com/python/importlib_metadata/issues/371
          +            if name is not None:
          +                normalized_name = _normalize_module_name(name)
          +                if dist.version is not None and normalized_name not in yielded:
          +                    yield normalized_name, dist.version
          +                    yielded.add(normalized_name)
          +
          +    except ImportError:
          +        # < py3.8
          +        try:
          +            import pkg_resources
          +        except ImportError:
          +            return
          +
          +        for info in pkg_resources.working_set:
          +            yield _normalize_module_name(info.key), info.version
          +
          +
          +def _normalize_module_name(name: str) -> str:
          +    return name.lower()
          +
          +
          +def _replace_hyphens_dots_and_underscores_with_dashes(name: str) -> str:
          +    # https://peps.python.org/pep-0503/#normalized-names
          +    return re.sub(r"[-_.]+", "-", name)
          +
          +
          +def _get_installed_modules() -> "Dict[str, str]":
          +    global _installed_modules
          +    if _installed_modules is None:
          +        _installed_modules = dict(_generate_installed_modules())
          +    return _installed_modules
          +
          +
          +def package_version(package: str) -> "Optional[Tuple[int, ...]]":
          +    normalized_package = _normalize_module_name(
          +        _replace_hyphens_dots_and_underscores_with_dashes(package)
          +    )
          +
          +    installed_packages = {
          +        _replace_hyphens_dots_and_underscores_with_dashes(module): v
          +        for module, v in _get_installed_modules().items()
          +    }
          +    version = installed_packages.get(normalized_package)
          +    if version is None:
          +        return None
          +
          +    return parse_version(version)
          +
          +
          +def reraise(
          +    tp: "Optional[Type[BaseException]]",
          +    value: "Optional[BaseException]",
          +    tb: "Optional[Any]" = None,
          +) -> "NoReturn":
          +    assert value is not None
          +    if value.__traceback__ is not tb:
          +        raise value.with_traceback(tb)
          +    raise value
          +
          +
          +def _no_op(*_a: "Any", **_k: "Any") -> None:
          +    """No-op function for ensure_integration_enabled."""
          +    pass
          +
          +
          +if TYPE_CHECKING:
          +
          +    @overload
          +    def ensure_integration_enabled(
          +        integration: "type[sentry_sdk.integrations.Integration]",
          +        original_function: "Callable[P, R]",
          +    ) -> "Callable[[Callable[P, R]], Callable[P, R]]": ...
          +
          +    @overload
          +    def ensure_integration_enabled(
          +        integration: "type[sentry_sdk.integrations.Integration]",
          +    ) -> "Callable[[Callable[P, None]], Callable[P, None]]": ...
          +
          +
          +def ensure_integration_enabled(
          +    integration: "type[sentry_sdk.integrations.Integration]",
          +    original_function: "Union[Callable[P, R], Callable[P, None]]" = _no_op,
          +) -> "Callable[[Callable[P, R]], Callable[P, R]]":
          +    """
          +    Ensures a given integration is enabled prior to calling a Sentry-patched function.
          +
          +    The function takes as its parameters the integration that must be enabled and the original
          +    function that the SDK is patching. The function returns a function that takes the
          +    decorated (Sentry-patched) function as its parameter, and returns a function that, when
          +    called, checks whether the given integration is enabled. If the integration is enabled, the
          +    function calls the decorated, Sentry-patched function. If the integration is not enabled,
          +    the original function is called.
          +
          +    The function also takes care of preserving the original function's signature and docstring.
          +
          +    Example usage:
          +
          +    ```python
          +    @ensure_integration_enabled(MyIntegration, my_function)
          +    def patch_my_function():
          +        with sentry_sdk.start_transaction(...):
          +            return my_function()
          +    ```
          +    """
          +    if TYPE_CHECKING:
          +        # Type hint to ensure the default function has the right typing. The overloads
          +        # ensure the default _no_op function is only used when R is None.
          +        original_function = cast(Callable[P, R], original_function)
          +
          +    def patcher(sentry_patched_function: "Callable[P, R]") -> "Callable[P, R]":
          +        def runner(*args: "P.args", **kwargs: "P.kwargs") -> "R":
          +            if sentry_sdk.get_client().get_integration(integration) is None:
          +                return original_function(*args, **kwargs)
          +
          +            return sentry_patched_function(*args, **kwargs)
          +
          +        if original_function is _no_op:
          +            return wraps(sentry_patched_function)(runner)
          +
          +        return wraps(original_function)(runner)
          +
          +    return patcher
          +
          +
          +if PY37:
          +
          +    def nanosecond_time() -> int:
          +        return time.perf_counter_ns()
          +
          +else:
          +
          +    def nanosecond_time() -> int:
          +        return int(time.perf_counter() * 1e9)
          +
          +
          +def now() -> float:
          +    return time.perf_counter()
          +
          +
          +try:
          +    from gevent import get_hub as get_gevent_hub
          +    from gevent.monkey import is_module_patched
          +except ImportError:
          +    # it's not great that the signatures are different, get_hub can't return None
          +    # consider adding an if TYPE_CHECKING to change the signature to Optional[Hub]
          +    def get_gevent_hub() -> "Optional[Hub]":  # type: ignore[misc]
          +        return None
          +
          +    def is_module_patched(mod_name: str) -> bool:
          +        # unable to import from gevent means no modules have been patched
          +        return False
          +
          +
          +def is_gevent() -> bool:
          +    return is_module_patched("threading") or is_module_patched("_thread")
          +
          +
          +def get_current_thread_meta(
          +    thread: "Optional[threading.Thread]" = None,
          +) -> "Tuple[Optional[int], Optional[str]]":
          +    """
          +    Try to get the id of the current thread, with various fall backs.
          +    """
          +
          +    # if a thread is specified, that takes priority
          +    if thread is not None:
          +        try:
          +            thread_id = thread.ident
          +            thread_name = thread.name
          +            if thread_id is not None:
          +                return thread_id, thread_name
          +        except AttributeError:
          +            pass
          +
          +    # if the app is using gevent, we should look at the gevent hub first
          +    # as the id there differs from what the threading module reports
          +    if is_gevent():
          +        gevent_hub = get_gevent_hub()
          +        if gevent_hub is not None:
          +            try:
          +                # this is undocumented, so wrap it in try except to be safe
          +                return gevent_hub.thread_ident, None
          +            except AttributeError:
          +                pass
          +
          +    # use the current thread's id if possible
          +    try:
          +        thread = threading.current_thread()
          +        thread_id = thread.ident
          +        thread_name = thread.name
          +        if thread_id is not None:
          +            return thread_id, thread_name
          +    except AttributeError:
          +        pass
          +
          +    # if we can't get the current thread id, fall back to the main thread id
          +    try:
          +        thread = threading.main_thread()
          +        thread_id = thread.ident
          +        thread_name = thread.name
          +        if thread_id is not None:
          +            return thread_id, thread_name
          +    except AttributeError:
          +        pass
          +
          +    # we've tried everything, time to give up
          +    return None, None
          +
          +
          +def should_be_treated_as_error(ty: "Any", value: "Any") -> bool:
          +    if ty == SystemExit and hasattr(value, "code") and value.code in (0, None):
          +        # https://docs.python.org/3/library/exceptions.html#SystemExit
          +        return False
          +
          +    # In the aiohttp integration, all of their HTTP responses are Exceptions.
          +    # Because they have to be raised and handled by the framework, we need this check so
          +    # that we don't accidentally overwrite a status of "ok" with "error" here.
          +    if AIOHttpHttpException and isinstance(value, AIOHttpHttpException):
          +        return False
          +
          +    return True
          +
          +
          +if TYPE_CHECKING:
          +    T = TypeVar("T")
          +
          +
          +def try_convert(convert_func: "Callable[[Any], T]", value: "Any") -> "Optional[T]":
          +    """
          +    Attempt to convert from an unknown type to a specific type, using the
          +    given function. Return None if the conversion fails, i.e. if the function
          +    raises an exception.
          +    """
          +    try:
          +        if isinstance(value, convert_func):  # type: ignore
          +            return value
          +    except TypeError:
          +        pass
          +
          +    try:
          +        return convert_func(value)
          +    except Exception:
          +        return None
          +
          +
          +def safe_serialize(data: "Any") -> str:
          +    """Safely serialize to a readable string."""
          +
          +    def serialize_item(
          +        item: "Any",
          +    ) -> "Union[str, dict[Any, Any], list[Any], tuple[Any, ...]]":
          +        if callable(item):
          +            try:
          +                module = getattr(item, "__module__", None)
          +                qualname = getattr(item, "__qualname__", None)
          +                name = getattr(item, "__name__", "anonymous")
          +
          +                if module and qualname:
          +                    full_path = f"{module}.{qualname}"
          +                elif module and name:
          +                    full_path = f"{module}.{name}"
          +                else:
          +                    full_path = name
          +
          +                return f""
          +            except Exception:
          +                return f""
          +        elif isinstance(item, dict):
          +            return {k: serialize_item(v) for k, v in item.items()}
          +        elif isinstance(item, (list, tuple)):
          +            return [serialize_item(x) for x in item]
          +        elif hasattr(item, "__dict__"):
          +            try:
          +                attrs = {
          +                    k: serialize_item(v)
          +                    for k, v in vars(item).items()
          +                    if not k.startswith("_")
          +                }
          +                return f"<{type(item).__name__} {attrs}>"
          +            except Exception:
          +                return repr(item)
          +        else:
          +            return item
          +
          +    try:
          +        serialized = serialize_item(data)
          +        return (
          +            json.dumps(serialized, default=str)
          +            if not isinstance(serialized, str)
          +            else serialized
          +        )
          +    except Exception:
          +        return str(data)
          +
          +
          +def has_logs_enabled(options: "Optional[dict[str, Any]]") -> bool:
          +    if options is None:
          +        return False
          +
          +    return bool(
          +        options.get("enable_logs", False)
          +        or options["_experiments"].get("enable_logs", False)
          +    )
          +
          +
          +def get_before_send_log(
          +    options: "Optional[dict[str, Any]]",
          +) -> "Optional[Callable[[Log, Hint], Optional[Log]]]":
          +    if options is None:
          +        return None
          +
          +    return options.get("before_send_log") or options["_experiments"].get(
          +        "before_send_log"
          +    )
          +
          +
          +def has_metrics_enabled(options: "Optional[dict[str, Any]]") -> bool:
          +    if options is None:
          +        return False
          +
          +    return bool(options.get("enable_metrics", True))
          +
          +
          +def get_before_send_metric(
          +    options: "Optional[dict[str, Any]]",
          +) -> "Optional[Callable[[Metric, Hint], Optional[Metric]]]":
          +    if options is None:
          +        return None
          +
          +    return options.get("before_send_metric") or options["_experiments"].get(
          +        "before_send_metric"
          +    )
          +
          +
          +def format_attribute(val: "Any") -> "AttributeValue":
          +    """
          +    Turn unsupported attribute value types into an AttributeValue.
          +
          +    We do this as soon as a user-provided attribute is set, to prevent spans,
          +    logs, metrics and similar from having live references to various objects.
          +
          +    Note: This is not the final attribute value format. Before they're sent,
          +    they're serialized further into the actual format the protocol expects:
          +    https://develop.sentry.dev/sdk/telemetry/attributes/
          +    """
          +    if isinstance(val, (bool, int, float, str)):
          +        return val
          +
          +    if isinstance(val, (list, tuple)) and not val:
          +        return []
          +    elif isinstance(val, list):
          +        ty = type(val[0])
          +        if ty in (str, int, float, bool) and all(type(v) is ty for v in val):
          +            return copy.deepcopy(val)
          +    elif isinstance(val, tuple):
          +        ty = type(val[0])
          +        if ty in (str, int, float, bool) and all(type(v) is ty for v in val):
          +            return list(val)
          +
          +    return safe_repr(val)
          +
          +
          +def serialize_attribute(val: "AttributeValue") -> "SerializedAttributeValue":
          +    """Serialize attribute value to the transport format."""
          +    if isinstance(val, bool):
          +        return {"value": val, "type": "boolean"}
          +    if isinstance(val, int):
          +        return {"value": val, "type": "integer"}
          +    if isinstance(val, float):
          +        return {"value": val, "type": "double"}
          +    if isinstance(val, str):
          +        return {"value": val, "type": "string"}
          +
          +    if isinstance(val, list):
          +        if not val:
          +            return {"value": [], "type": "array"}
          +
          +        # Only lists of elements of a single type are supported
          +        ty = type(val[0])
          +        if ty in (int, str, bool, float) and all(type(v) is ty for v in val):
          +            return {"value": val, "type": "array"}
          +
          +    # Coerce to string if we don't know what to do with the value. This should
          +    # never happen as we pre-format early in format_attribute, but let's be safe.
          +    return {"value": safe_repr(val), "type": "string"}
          diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/worker.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/worker.py
          new file mode 100644
          index 0000000000000000000000000000000000000000..7931f9c027f9b0a60ce36b97c8d72baf4498be49
          --- /dev/null
          +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sentry_sdk/worker.py
          @@ -0,0 +1,311 @@
          +from abc import ABC, abstractmethod
          +import asyncio
          +import os
          +import threading
          +
          +from time import sleep, time
          +from sentry_sdk._queue import Queue, FullError
          +from sentry_sdk.utils import logger, mark_sentry_task_internal
          +from sentry_sdk.consts import DEFAULT_QUEUE_SIZE
          +
          +from typing import TYPE_CHECKING
          +
          +if TYPE_CHECKING:
          +    from typing import Any
          +    from typing import Optional
          +    from typing import Callable
          +
          +
          +_TERMINATOR = object()
          +
          +
          +class Worker(ABC):
          +    """Base class for all workers."""
          +
          +    @property
          +    @abstractmethod
          +    def is_alive(self) -> bool:
          +        """Whether the worker is alive and running."""
          +        pass
          +
          +    @abstractmethod
          +    def kill(self) -> None:
          +        """Kill the worker. It will not process any more events."""
          +        pass
          +
          +    def flush(
          +        self, timeout: float, callback: "Optional[Callable[[int, float], Any]]" = None
          +    ) -> None:
          +        """Flush the worker, blocking until done or timeout is reached."""
          +        return None
          +
          +    @abstractmethod
          +    def full(self) -> bool:
          +        """Whether the worker's queue is full."""
          +        pass
          +
          +    @abstractmethod
          +    def submit(self, callback: "Callable[[], Any]") -> bool:
          +        """Schedule a callback. Returns True if queued, False if full."""
          +        pass
          +
          +
          +class BackgroundWorker(Worker):
          +    def __init__(self, queue_size: int = DEFAULT_QUEUE_SIZE) -> None:
          +        self._queue: "Queue" = Queue(queue_size)
          +        self._lock = threading.Lock()
          +        self._thread: "Optional[threading.Thread]" = None
          +        self._thread_for_pid: "Optional[int]" = None
          +
          +    @property
          +    def is_alive(self) -> bool:
          +        if self._thread_for_pid != os.getpid():
          +            return False
          +        if not self._thread:
          +            return False
          +        return self._thread.is_alive()
          +
          +    def _ensure_thread(self) -> None:
          +        if not self.is_alive:
          +            self.start()
          +
          +    def _timed_queue_join(self, timeout: float) -> bool:
          +        deadline = time() + timeout
          +        queue = self._queue
          +
          +        queue.all_tasks_done.acquire()
          +
          +        try:
          +            while queue.unfinished_tasks:
          +                delay = deadline - time()
          +                if delay <= 0:
          +                    return False
          +                queue.all_tasks_done.wait(timeout=delay)
          +
          +            return True
          +        finally:
          +            queue.all_tasks_done.release()
          +
          +    def start(self) -> None:
          +        with self._lock:
          +            if not self.is_alive:
          +                self._thread = threading.Thread(
          +                    target=self._target, name="sentry-sdk.BackgroundWorker"
          +                )
          +                self._thread.daemon = True
          +                try:
          +                    self._thread.start()
          +                    self._thread_for_pid = os.getpid()
          +                except RuntimeError:
          +                    # At this point we can no longer start because the interpreter
          +                    # is already shutting down.  Sadly at this point we can no longer
          +                    # send out events.
          +                    self._thread = None
          +
          +    def kill(self) -> None:
          +        """
          +        Kill worker thread. Returns immediately. Not useful for
          +        waiting on shutdown for events, use `flush` for that.
          +        """
          +        logger.debug("background worker got kill request")
          +        with self._lock:
          +            if self._thread:
          +                try:
          +                    self._queue.put_nowait(_TERMINATOR)
          +                except FullError:
          +                    logger.debug("background worker queue full, kill failed")
          +
          +                self._thread = None
          +                self._thread_for_pid = None
          +
          +    def flush(self, timeout: float, callback: "Optional[Any]" = None) -> None:
          +        logger.debug("background worker got flush request")
          +        with self._lock:
          +            if self.is_alive and timeout > 0.0:
          +                self._wait_flush(timeout, callback)
          +        logger.debug("background worker flushed")
          +
          +    def full(self) -> bool:
          +        return self._queue.full()
          +
          +    def _wait_flush(self, timeout: float, callback: "Optional[Any]") -> None:
          +        initial_timeout = min(0.1, timeout)
          +        if not self._timed_queue_join(initial_timeout):
          +            pending = self._queue.qsize() + 1
          +            logger.debug("%d event(s) pending on flush", pending)
          +            if callback is not None:
          +                callback(pending, timeout)
          +
          +            if not self._timed_queue_join(timeout - initial_timeout):
          +                pending = self._queue.qsize() + 1
          +                logger.error("flush timed out, dropped %s events", pending)
          +
          +    def submit(self, callback: "Callable[[], Any]") -> bool:
          +        self._ensure_thread()
          +        try:
          +            self._queue.put_nowait(callback)
          +            return True
          +        except FullError:
          +            return False
          +
          +    def _target(self) -> None:
          +        while True:
          +            callback = self._queue.get()
          +            try:
          +                if callback is _TERMINATOR:
          +                    break
          +                try:
          +                    callback()
          +                except Exception:
          +                    logger.error("Failed processing job", exc_info=True)
          +            finally:
          +                self._queue.task_done()
          +            sleep(0)
          +
          +
          +class AsyncWorker(Worker):
          +    def __init__(self, queue_size: int = DEFAULT_QUEUE_SIZE) -> None:
          +        self._queue: "Optional[asyncio.Queue[Any]]" = None
          +        self._queue_size = queue_size
          +        self._task: "Optional[asyncio.Task[None]]" = None
          +        # Event loop needs to remain in the same process
          +        self._task_for_pid: "Optional[int]" = None
          +        self._loop: "Optional[asyncio.AbstractEventLoop]" = None
          +        # Track active callback tasks so they have a strong reference and can be cancelled on kill
          +        self._active_tasks: "set[asyncio.Task[None]]" = set()
          +
          +    @property
          +    def is_alive(self) -> bool:
          +        if self._task_for_pid != os.getpid():
          +            return False
          +        if not self._task or not self._loop:
          +            return False
          +        return self._loop.is_running() and not self._task.done()
          +
          +    def kill(self) -> None:
          +        if self._task:
          +            # Cancel the main consumer task to prevent duplicate consumers
          +            self._task.cancel()
          +            # Also cancel any active callback tasks
          +            # Avoid modifying the set while cancelling tasks
          +            tasks_to_cancel = set(self._active_tasks)
          +            for task in tasks_to_cancel:
          +                task.cancel()
          +            self._active_tasks.clear()
          +            self._loop = None
          +            self._task = None
          +            self._task_for_pid = None
          +
          +    def start(self) -> None:
          +        if not self.is_alive:
          +            try:
          +                self._loop = asyncio.get_running_loop()
          +                # Always create a fresh queue on start to avoid stale items
          +                self._queue = asyncio.Queue(maxsize=self._queue_size)
          +                with mark_sentry_task_internal():
          +                    self._task = self._loop.create_task(self._target())
          +                self._task_for_pid = os.getpid()
          +            except RuntimeError:
          +                # There is no event loop running
          +                logger.warning("No event loop running, async worker not started")
          +                self._loop = None
          +                self._task = None
          +                self._task_for_pid = None
          +
          +    def full(self) -> bool:
          +        if self._queue is None:
          +            return True
          +        return self._queue.full()
          +
          +    def _ensure_task(self) -> None:
          +        if not self.is_alive:
          +            self.start()
          +
          +    async def _wait_flush(
          +        self, timeout: float, callback: "Optional[Any]" = None
          +    ) -> None:
          +        if not self._loop or not self._loop.is_running() or self._queue is None:
          +            return
          +
          +        initial_timeout = min(0.1, timeout)
          +
          +        # Timeout on the join
          +        try:
          +            await asyncio.wait_for(self._queue.join(), timeout=initial_timeout)
          +        except asyncio.TimeoutError:
          +            pending = self._queue.qsize() + len(self._active_tasks)
          +            logger.debug("%d event(s) pending on flush", pending)
          +            if callback is not None:
          +                callback(pending, timeout)
          +
          +            try:
          +                remaining_timeout = timeout - initial_timeout
          +                await asyncio.wait_for(self._queue.join(), timeout=remaining_timeout)
          +            except asyncio.TimeoutError:
          +                pending = self._queue.qsize() + len(self._active_tasks)
          +                logger.error("flush timed out, dropped %s events", pending)
          +
          +    def flush(  # type: ignore[override]
          +        self, timeout: float, callback: "Optional[Any]" = None
          +    ) -> "Optional[asyncio.Task[None]]":
          +        if self.is_alive and timeout > 0.0 and self._loop and self._loop.is_running():
          +            with mark_sentry_task_internal():
          +                return self._loop.create_task(self._wait_flush(timeout, callback))
          +        return None
          +
          +    def submit(self, callback: "Callable[[], Any]") -> bool:
          +        self._ensure_task()
          +        if self._queue is None:
          +            return False
          +        try:
          +            self._queue.put_nowait(callback)
          +            return True
          +        except asyncio.QueueFull:
          +            return False
          +
          +    async def _target(self) -> None:
          +        if self._queue is None:
          +            return
          +        try:
          +            while True:
          +                callback = await self._queue.get()
          +                if callback is _TERMINATOR:
          +                    self._queue.task_done()
          +                    break
          +                # Firing tasks instead of awaiting them allows for concurrent requests
          +                with mark_sentry_task_internal():
          +                    task = asyncio.create_task(self._process_callback(callback))
          +                # Create a strong reference to the task so it can be cancelled on kill
          +                # and does not get garbage collected while running
          +                self._active_tasks.add(task)
          +                # Capture queue ref at dispatch time so done callbacks use the
          +                # correct queue even if kill()/start() replace self._queue.
          +                queue_ref = self._queue
          +                task.add_done_callback(lambda t: self._on_task_complete(t, queue_ref))
          +                # Yield to let the event loop run other tasks
          +                await asyncio.sleep(0)
          +        except asyncio.CancelledError:
          +            pass  # Expected during kill()
          +
          +    async def _process_callback(self, callback: "Callable[[], Any]") -> None:
          +        # Callback is an async coroutine, need to await it
          +        await callback()
          +
          +    def _on_task_complete(
          +        self,
          +        task: "asyncio.Task[None]",
          +        queue: "Optional[asyncio.Queue[Any]]" = None,
          +    ) -> None:
          +        try:
          +            task.result()
          +        except asyncio.CancelledError:
          +            pass  # Task was cancelled, expected during shutdown
          +        except Exception:
          +            logger.error("Failed processing job", exc_info=True)
          +        finally:
          +            # Mark the task as done and remove it from the active tasks set
          +            # Use the queue reference captured at dispatch time, not self._queue,
          +            # to avoid calling task_done() on a different queue after kill()/start().
          +            if queue is not None:
          +                queue.task_done()
          +            self._active_tasks.discard(task)
          diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sqlitedict.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sqlitedict.py
          new file mode 100644
          index 0000000000000000000000000000000000000000..3e65724a2f1d32c8105f7ccae7eafe54f6c2ba5d
          --- /dev/null
          +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sqlitedict.py
          @@ -0,0 +1,697 @@
          +#!/usr/bin/env python
          +# -*- coding: utf-8 -*-
          +#
          +# This code is distributed under the terms and conditions
          +# from the Apache License, Version 2.0
          +#
          +# http://opensource.org/licenses/apache2.0.php
          +#
          +# This code was inspired by:
          +#  * http://code.activestate.com/recipes/576638-draft-for-an-sqlite3-based-dbm/
          +#  * http://code.activestate.com/recipes/526618/
          +
          +"""
          +A lightweight wrapper around Python's sqlite3 database, with a dict-like interface
          +and multi-thread access support::
          +
          +>>> mydict = SqliteDict('some.db', autocommit=True) # the mapping will be persisted to file `some.db`
          +>>> mydict['some_key'] = any_picklable_object
          +>>> print mydict['some_key']
          +>>> print len(mydict) # etc... all dict functions work
          +
          +Pickle is used internally to serialize the values. Keys are strings.
          +
          +If you don't use autocommit (default is no autocommit for performance), then
          +don't forget to call `mydict.commit()` when done with a transaction.
          +
          +"""
          +
          +import sqlite3
          +import os
          +import sys
          +import tempfile
          +import threading
          +import logging
          +import traceback
          +from base64 import b64decode, b64encode
          +import weakref
          +
          +__version__ = '2.1.0'
          +
          +
          +def reraise(tp, value, tb=None):
          +    if value is None:
          +        value = tp()
          +    if value.__traceback__ is not tb:
          +        raise value.with_traceback(tb)
          +    raise value
          +
          +
          +try:
          +    from cPickle import dumps, loads, HIGHEST_PROTOCOL as PICKLE_PROTOCOL
          +except ImportError:
          +    from pickle import dumps, loads, HIGHEST_PROTOCOL as PICKLE_PROTOCOL
          +
          +# some Python 3 vs 2 imports
          +try:
          +    from collections import UserDict as DictClass
          +except ImportError:
          +    from UserDict import DictMixin as DictClass
          +
          +try:
          +    from queue import Queue
          +except ImportError:
          +    from Queue import Queue
          +
          +
          +logger = logging.getLogger(__name__)
          +
          +#
          +# There's a thread that holds the actual SQL connection (SqliteMultithread).
          +# We communicate with this thread via queues (request and responses).
          +# The requests can either be SQL commands or one of the "special" commands
          +# below:
          +#
          +# _REQUEST_CLOSE: request that the SQL connection be closed
          +# _REQUEST_COMMIT: request that any changes be committed to the DB
          +#
          +# Responses are either SQL records (e.g. results of a SELECT) or the magic
          +# _RESPONSE_NO_MORE command, which indicates nothing else will ever be written
          +# to the response queue.
          +#
          +_REQUEST_CLOSE = '--close--'
          +_REQUEST_COMMIT = '--commit--'
          +_RESPONSE_NO_MORE = '--no more--'
          +
          +#
          +# We work with weak references for better memory efficiency.
          +# Dereferencing, checking the referent queue still exists, and putting to it
          +# is boring and repetitive, so we have a _put function to handle it for us.
          +#
          +_PUT_OK, _PUT_REFERENT_DESTROYED, _PUT_NOOP = 0, 1, 2
          +
          +
          +def _put(queue_reference, item):
          +    if queue_reference is not None:
          +        queue = queue_reference()
          +        if queue is None:
          +            #
          +            # We got a reference to a queue, but that queue no longer exists
          +            #
          +            retval = _PUT_REFERENT_DESTROYED
          +        else:
          +            queue.put(item)
          +            retval = _PUT_OK
          +
          +        del queue
          +        return retval
          +
          +    #
          +    # We didn't get a reference to a queue, so do nothing (no-op).
          +    #
          +    return _PUT_NOOP
          +
          +
          +def open(*args, **kwargs):
          +    """See documentation of the SqliteDict class."""
          +    return SqliteDict(*args, **kwargs)
          +
          +
          +def encode(obj):
          +    """Serialize an object using pickle to a binary format accepted by SQLite."""
          +    return sqlite3.Binary(dumps(obj, protocol=PICKLE_PROTOCOL))
          +
          +
          +def decode(obj):
          +    """Deserialize objects retrieved from SQLite."""
          +    return loads(bytes(obj))
          +
          +
          +def encode_key(key):
          +    """Serialize a key using pickle + base64 encoding to text accepted by SQLite."""
          +    return b64encode(dumps(key, protocol=PICKLE_PROTOCOL)).decode("ascii")
          +
          +
          +def decode_key(key):
          +    """Deserialize a key retrieved from SQLite."""
          +    return loads(b64decode(key.encode("ascii")))
          +
          +
          +def identity(obj):
          +    """Identity f(x) = x function for encoding/decoding."""
          +    return obj
          +
          +
          +class SqliteDict(DictClass):
          +    VALID_FLAGS = ['c', 'r', 'w', 'n']
          +
          +    def __init__(self, filename=None, tablename='unnamed', flag='c',
          +                 autocommit=False, journal_mode="DELETE", encode=encode,
          +                 decode=decode, encode_key=identity, decode_key=identity,
          +                 timeout=5, outer_stack=True):
          +        """
          +        Initialize a thread-safe sqlite-backed dictionary. The dictionary will
          +        be a table `tablename` in database file `filename`. A single file (=database)
          +        may contain multiple tables.
          +
          +        If no `filename` is given, a random file in temp will be used (and deleted
          +        from temp once the dict is closed/deleted).
          +
          +        If you enable `autocommit`, changes will be committed after each operation
          +        (more inefficient but safer). Otherwise, changes are committed on `self.commit()`,
          +        `self.clear()` and `self.close()`.
          +
          +        Set `journal_mode` to 'OFF' if you're experiencing sqlite I/O problems
          +        or if you need performance and don't care about crash-consistency.
          +
          +        Set `outer_stack` to False to disable the output of the outer exception
          +        to the error logs.  This may improve the efficiency of sqlitedict
          +        operation at the expense of a detailed exception trace.
          +
          +        The `flag` parameter. Exactly one of:
          +          'c': default mode, open for read/write, creating the db/table if necessary.
          +          'w': open for r/w, but drop `tablename` contents first (start with empty table)
          +          'r': open as read-only
          +          'n': create a new database (erasing any existing tables, not just `tablename`!).
          +
          +        The `encode` and `decode` parameters are used to customize how the values
          +        are serialized and deserialized.
          +        The `encode` parameter must be a function that takes a single Python
          +        object and returns a serialized representation.
          +        The `decode` function must be a function that takes the serialized
          +        representation produced by `encode` and returns a deserialized Python
          +        object.
          +        The default is to use pickle.
          +
          +        The `timeout` defines the maximum time (in seconds) to wait for initial Thread startup.
          +
          +        """
          +        self.in_temp = filename is None
          +        if self.in_temp:
          +            fd, filename = tempfile.mkstemp(prefix='sqldict')
          +            os.close(fd)
          +
          +        if flag not in SqliteDict.VALID_FLAGS:
          +            raise RuntimeError("Unrecognized flag: %s" % flag)
          +        self.flag = flag
          +
          +        if flag == 'n':
          +            if os.path.exists(filename):
          +                os.remove(filename)
          +
          +        dirname = os.path.dirname(filename)
          +        if dirname:
          +            if not os.path.exists(dirname):
          +                raise RuntimeError('Error! The directory does not exist, %s' % dirname)
          +
          +        self.filename = filename
          +
          +        # Use standard SQL escaping of double quote characters in identifiers, by doubling them.
          +        # See https://github.com/RaRe-Technologies/sqlitedict/pull/113
          +        self.tablename = tablename.replace('"', '""')
          +
          +        self.autocommit = autocommit
          +        self.journal_mode = journal_mode
          +        self.encode = encode
          +        self.decode = decode
          +        self.encode_key = encode_key
          +        self.decode_key = decode_key
          +        self._outer_stack = outer_stack
          +
          +        logger.debug("opening Sqlite table %r in %r" % (tablename, filename))
          +        self.conn = self._new_conn()
          +        if self.flag == 'r':
          +            if self.tablename not in SqliteDict.get_tablenames(self.filename):
          +                msg = 'Refusing to create a new table "%s" in read-only DB mode' % tablename
          +                raise RuntimeError(msg)
          +        else:
          +            MAKE_TABLE = 'CREATE TABLE IF NOT EXISTS "%s" (key TEXT PRIMARY KEY, value BLOB)' % self.tablename
          +            self.conn.execute(MAKE_TABLE)
          +            self.conn.commit()
          +        if flag == 'w':
          +            self.clear()
          +
          +    def _new_conn(self):
          +        return SqliteMultithread(
          +            self.filename,
          +            autocommit=self.autocommit,
          +            journal_mode=self.journal_mode,
          +            outer_stack=self._outer_stack,
          +        )
          +
          +    def __enter__(self):
          +        if not hasattr(self, 'conn') or self.conn is None:
          +            self.conn = self._new_conn()
          +        return self
          +
          +    def __exit__(self, *exc_info):
          +        self.close()
          +
          +    def __str__(self):
          +        return "SqliteDict(%s)" % (self.filename)
          +
          +    def __repr__(self):
          +        return str(self)  # no need of something complex
          +
          +    def __len__(self):
          +        # `select count (*)` is super slow in sqlite (does a linear scan!!)
          +        # As a result, len() is very slow too once the table size grows beyond trivial.
          +        # We could keep the total count of rows ourselves, by means of triggers,
          +        # but that seems too complicated and would slow down normal operation
          +        # (insert/delete etc).
          +        GET_LEN = 'SELECT COUNT(*) FROM "%s"' % self.tablename
          +        rows = self.conn.select_one(GET_LEN)[0]
          +        return rows if rows is not None else 0
          +
          +    def __bool__(self):
          +        # No elements is False, otherwise True
          +        GET_MAX = 'SELECT MAX(ROWID) FROM "%s"' % self.tablename
          +        m = self.conn.select_one(GET_MAX)[0]
          +        # Explicit better than implicit and bla bla
          +        return True if m is not None else False
          +
          +    def iterkeys(self):
          +        GET_KEYS = 'SELECT key FROM "%s" ORDER BY rowid' % self.tablename
          +        for key in self.conn.select(GET_KEYS):
          +            yield self.decode_key(key[0])
          +
          +    def itervalues(self):
          +        GET_VALUES = 'SELECT value FROM "%s" ORDER BY rowid' % self.tablename
          +        for value in self.conn.select(GET_VALUES):
          +            yield self.decode(value[0])
          +
          +    def iteritems(self):
          +        GET_ITEMS = 'SELECT key, value FROM "%s" ORDER BY rowid' % self.tablename
          +        for key, value in self.conn.select(GET_ITEMS):
          +            yield self.decode_key(key), self.decode(value)
          +
          +    def keys(self):
          +        return self.iterkeys()
          +
          +    def values(self):
          +        return self.itervalues()
          +
          +    def items(self):
          +        return self.iteritems()
          +
          +    def __contains__(self, key):
          +        HAS_ITEM = 'SELECT 1 FROM "%s" WHERE key = ?' % self.tablename
          +        return self.conn.select_one(HAS_ITEM, (self.encode_key(key),)) is not None
          +
          +    def __getitem__(self, key):
          +        GET_ITEM = 'SELECT value FROM "%s" WHERE key = ?' % self.tablename
          +        item = self.conn.select_one(GET_ITEM, (self.encode_key(key),))
          +        if item is None:
          +            raise KeyError(key)
          +        return self.decode(item[0])
          +
          +    def __setitem__(self, key, value):
          +        if self.flag == 'r':
          +            raise RuntimeError('Refusing to write to read-only SqliteDict')
          +
          +        ADD_ITEM = 'REPLACE INTO "%s" (key, value) VALUES (?,?)' % self.tablename
          +        self.conn.execute(ADD_ITEM, (self.encode_key(key), self.encode(value)))
          +        if self.autocommit:
          +            self.commit()
          +
          +    def __delitem__(self, key):
          +        if self.flag == 'r':
          +            raise RuntimeError('Refusing to delete from read-only SqliteDict')
          +
          +        if key not in self:
          +            raise KeyError(key)
          +        DEL_ITEM = 'DELETE FROM "%s" WHERE key = ?' % self.tablename
          +        self.conn.execute(DEL_ITEM, (self.encode_key(key),))
          +        if self.autocommit:
          +            self.commit()
          +
          +    def update(self, items=(), **kwds):
          +        if self.flag == 'r':
          +            raise RuntimeError('Refusing to update read-only SqliteDict')
          +
          +        try:
          +            items = items.items()
          +        except AttributeError:
          +            pass
          +        items = [(self.encode_key(k), self.encode(v)) for k, v in items]
          +
          +        UPDATE_ITEMS = 'REPLACE INTO "%s" (key, value) VALUES (?, ?)' % self.tablename
          +        self.conn.executemany(UPDATE_ITEMS, items)
          +        if kwds:
          +            self.update(kwds)
          +        if self.autocommit:
          +            self.commit()
          +
          +    def __iter__(self):
          +        return self.iterkeys()
          +
          +    def clear(self):
          +        if self.flag == 'r':
          +            raise RuntimeError('Refusing to clear read-only SqliteDict')
          +
          +        # avoid VACUUM, as it gives "OperationalError: database schema has changed"
          +        CLEAR_ALL = 'DELETE FROM "%s";' % self.tablename
          +        self.conn.commit()
          +        self.conn.execute(CLEAR_ALL)
          +        self.conn.commit()
          +
          +    @staticmethod
          +    def get_tablenames(filename):
          +        """get the names of the tables in an sqlite db as a list"""
          +        if not os.path.isfile(filename):
          +            raise IOError('file %s does not exist' % (filename))
          +        GET_TABLENAMES = 'SELECT name FROM sqlite_master WHERE type="table"'
          +        with sqlite3.connect(filename) as conn:
          +            cursor = conn.execute(GET_TABLENAMES)
          +            res = cursor.fetchall()
          +
          +        return [name[0] for name in res]
          +
          +    def commit(self, blocking=True):
          +        """
          +        Persist all data to disk.
          +
          +        When `blocking` is False, the commit command is queued, but the data is
          +        not guaranteed persisted (default implication when autocommit=True).
          +        """
          +        if self.conn is not None:
          +            self.conn.commit(blocking)
          +    sync = commit
          +
          +    def close(self, do_log=True, force=False):
          +        if do_log:
          +            logger.debug("closing %s" % self)
          +        if hasattr(self, 'conn') and self.conn is not None:
          +            if self.conn.autocommit and not force:
          +                # typically calls to commit are non-blocking when autocommit is
          +                # used.  However, we need to block on close() to ensure any
          +                # awaiting exceptions are handled and that all data is
          +                # persisted to disk before returning.
          +                self.conn.commit(blocking=True)
          +            self.conn.close(force=force)
          +            self.conn = None
          +        if self.in_temp:
          +            try:
          +                os.remove(self.filename)
          +            except Exception:
          +                pass
          +
          +    def terminate(self):
          +        """Delete the underlying database file. Use with care."""
          +        if self.flag == 'r':
          +            raise RuntimeError('Refusing to terminate read-only SqliteDict')
          +
          +        self.close()
          +
          +        if self.filename == ':memory:':
          +            return
          +
          +        logger.info("deleting %s" % self.filename)
          +        try:
          +            if os.path.isfile(self.filename):
          +                os.remove(self.filename)
          +        except (OSError, IOError):
          +            logger.exception("failed to delete %s" % (self.filename))
          +
          +    def __del__(self):
          +        # like close(), but assume globals are gone by now (do not log!)
          +        try:
          +            self.close(do_log=False, force=True)
          +        except Exception:
          +            # prevent error log flood in case of multiple SqliteDicts
          +            # closed after connection lost (exceptions are always ignored
          +            # in __del__ method.
          +            pass
          +
          +
          +class SqliteMultithread(threading.Thread):
          +    """
          +    Wrap sqlite connection in a way that allows concurrent requests from multiple threads.
          +
          +    This is done by internally queueing the requests and processing them sequentially
          +    in a separate thread (in the same order they arrived).
          +
          +    """
          +    def __init__(self, filename, autocommit, journal_mode, outer_stack=True):
          +        super(SqliteMultithread, self).__init__()
          +        self.filename = filename
          +        self.autocommit = autocommit
          +        self.journal_mode = journal_mode
          +        # use request queue of unlimited size
          +        self.reqs = Queue()
          +        self.daemon = True
          +        self._outer_stack = outer_stack
          +        self.log = logging.getLogger('sqlitedict.SqliteMultithread')
          +
          +        #
          +        # Parts of this object's state get accessed from different threads, so
          +        # we use synchronization to avoid race conditions.  For example,
          +        # .exception gets set inside the new daemon thread that we spawned, but
          +        # gets read from the main thread.  This is particularly important
          +        # during initialization: the Thread needs some time to actually start
          +        # working, and until this happens, any calls to e.g.
          +        # check_raise_error() will prematurely return None, meaning all is
          +        # well.  If the that connection happens to fail, we'll never know about
          +        # it, and instead wait for a result that never arrives (effectively,
          +        # deadlocking).  Locking solves this problem by eliminating the race
          +        # condition.
          +        #
          +        self._lock = threading.Lock()
          +        self._lock.acquire()
          +        self.exception = None
          +
          +        self.start()
          +
          +    def _connect(self):
          +        """Connect to the underlying database.
          +
          +        Raises an exception on failure.  Returns the connection and cursor on success.
          +        """
          +        try:
          +            if self.autocommit:
          +                conn = sqlite3.connect(self.filename, isolation_level=None, check_same_thread=False)
          +            else:
          +                conn = sqlite3.connect(self.filename, check_same_thread=False)
          +        except Exception:
          +            self.log.exception("Failed to initialize connection for filename: %s" % self.filename)
          +            self.exception = sys.exc_info()
          +            raise
          +
          +        try:
          +            conn.execute('PRAGMA journal_mode = %s' % self.journal_mode)
          +            conn.text_factory = str
          +            cursor = conn.cursor()
          +            conn.commit()
          +            cursor.execute('PRAGMA synchronous=OFF')
          +        except Exception:
          +            self.log.exception("Failed to execute PRAGMA statements.")
          +            self.exception = sys.exc_info()
          +            raise
          +
          +        return conn, cursor
          +
          +    def run(self):
          +        #
          +        # Nb. this is what actually runs inside the new daemon thread.
          +        # self._lock is locked at this stage - see the initializer function.
          +        #
          +        try:
          +            conn, cursor = self._connect()
          +        finally:
          +            self._lock.release()
          +
          +        res_ref = None
          +        while True:
          +            #
          +            # req: an SQL command or one of the --magic-- commands we use internally
          +            # arg: arguments for the command
          +            # res_ref: a weak reference to the queue into which responses must be placed
          +            # outer_stack: the outer stack, for producing more informative traces in case of error
          +            #
          +            req, arg, res_ref, outer_stack = self.reqs.get()
          +
          +            if req == _REQUEST_CLOSE:
          +                assert res_ref, ('--close-- without return queue', res_ref)
          +                break
          +            elif req == _REQUEST_COMMIT:
          +                conn.commit()
          +                _put(res_ref, _RESPONSE_NO_MORE)
          +            else:
          +                try:
          +                    cursor.execute(req, arg)
          +                except Exception:
          +                    with self._lock:
          +                        self.exception = (e_type, e_value, e_tb) = sys.exc_info()
          +
          +                    inner_stack = traceback.extract_stack()
          +
          +                    # An exception occurred in our thread, but we may not
          +                    # immediately able to throw it in our calling thread, if it has
          +                    # no return `res` queue: log as level ERROR both the inner and
          +                    # outer exception immediately.
          +                    #
          +                    # Any iteration of res.get() or any next call will detect the
          +                    # inner exception and re-raise it in the calling Thread; though
          +                    # it may be confusing to see an exception for an unrelated
          +                    # statement, an ERROR log statement from the 'sqlitedict.*'
          +                    # namespace contains the original outer stack location.
          +                    self.log.error('Inner exception:')
          +                    for item in traceback.format_list(inner_stack):
          +                        self.log.error(item)
          +                    self.log.error('')  # deliniate traceback & exception w/blank line
          +                    for item in traceback.format_exception_only(e_type, e_value):
          +                        self.log.error(item)
          +
          +                    self.log.error('')  # exception & outer stack w/blank line
          +
          +                    if self._outer_stack:
          +                        self.log.error('Outer stack:')
          +                        for item in traceback.format_list(outer_stack):
          +                            self.log.error(item)
          +                        self.log.error('Exception will be re-raised at next call.')
          +                    else:
          +                        self.log.error(
          +                            'Unable to show the outer stack. Pass '
          +                            'outer_stack=True when initializing the '
          +                            'SqliteDict instance to show the outer stack.'
          +                        )
          +
          +                if res_ref:
          +                    for rec in cursor:
          +                        if _put(res_ref, rec) == _PUT_REFERENT_DESTROYED:
          +                            #
          +                            # The queue we are sending responses to got garbage
          +                            # collected.  Nobody is listening anymore, so we
          +                            # stop sending responses.
          +                            #
          +                            break
          +
          +                    _put(res_ref, _RESPONSE_NO_MORE)
          +
          +                if self.autocommit:
          +                    conn.commit()
          +
          +        self.log.debug('received: %s, send: --no more--', req)
          +        conn.close()
          +
          +        _put(res_ref, _RESPONSE_NO_MORE)
          +
          +    def check_raise_error(self):
          +        """
          +        Check for and raise exception for any previous sqlite query.
          +
          +        For the `execute*` family of method calls, such calls are non-blocking and any
          +        exception raised in the thread cannot be handled by the calling Thread (usually
          +        MainThread).  This method is called on `close`, and prior to any subsequent
          +        calls to the `execute*` methods to check for and raise an exception in a
          +        previous call to the MainThread.
          +        """
          +        with self._lock:
          +            if self.exception:
          +                e_type, e_value, e_tb = self.exception
          +
          +                # clear self.exception, if the caller decides to handle such
          +                # exception, we should not repeatedly re-raise it.
          +                self.exception = None
          +
          +                self.log.error('An exception occurred from a previous statement, view '
          +                               'the logging namespace "sqlitedict" for outer stack.')
          +
          +                # The third argument to raise is the traceback object, and it is
          +                # substituted instead of the current location as the place where
          +                # the exception occurred, this is so that when using debuggers such
          +                # as `pdb', or simply evaluating the naturally raised traceback, we
          +                # retain the original (inner) location of where the exception
          +                # occurred.
          +                reraise(e_type, e_value, e_tb)
          +
          +    def execute(self, req, arg=None, res=None):
          +        """
          +        `execute` calls are non-blocking: just queue up the request and return immediately.
          +
          +        :param req: The request (an SQL command)
          +        :param arg: Arguments to the SQL command
          +        :param res: A queue in which to place responses as they become available
          +        """
          +        self.check_raise_error()
          +        stack = None
          +
          +        if self._outer_stack:
          +            # NOTE: This might be a lot of information to pump into an input
          +            # queue, affecting performance.  I've also seen earlier versions of
          +            # jython take a severe performance impact for throwing exceptions
          +            # so often.
          +            stack = traceback.extract_stack()[:-1]
          +
          +        #
          +        # We pass a weak reference to the response queue instead of a regular
          +        # reference, because we want the queues to be garbage-collected
          +        # more aggressively.
          +        #
          +        res_ref = None
          +        if res:
          +            res_ref = weakref.ref(res)
          +
          +        self.reqs.put((req, arg or tuple(), res_ref, stack))
          +
          +    def executemany(self, req, items):
          +        for item in items:
          +            self.execute(req, item)
          +        self.check_raise_error()
          +
          +    def select(self, req, arg=None):
          +        """
          +        Unlike sqlite's native select, this select doesn't handle iteration efficiently.
          +
          +        The result of `select` starts filling up with values as soon as the
          +        request is dequeued, and although you can iterate over the result normally
          +        (`for res in self.select(): ...`), the entire result will be in memory.
          +        """
          +        res = Queue()  # results of the select will appear as items in this queue
          +        self.execute(req, arg, res)
          +        while True:
          +            rec = res.get()
          +            self.check_raise_error()
          +            if rec == _RESPONSE_NO_MORE:
          +                break
          +            yield rec
          +
          +    def select_one(self, req, arg=None):
          +        """Return only the first row of the SELECT, or None if there are no matching rows."""
          +        try:
          +            return next(iter(self.select(req, arg)))
          +        except StopIteration:
          +            return None
          +
          +    def commit(self, blocking=True):
          +        if blocking:
          +            # by default, we await completion of commit() unless
          +            # blocking=False.  This ensures any available exceptions for any
          +            # previous statement are thrown before returning, and that the
          +            # data has actually persisted to disk!
          +            self.select_one(_REQUEST_COMMIT)
          +        else:
          +            # otherwise, we fire and forget as usual.
          +            self.execute(_REQUEST_COMMIT)
          +
          +    def close(self, force=False):
          +        if force:
          +            # If a SqliteDict is being killed or garbage-collected, then select_one()
          +            # could hang forever because run() might already have exited and therefore
          +            # can't process the request. Instead, push the close command to the requests
          +            # queue directly. If run() is still alive, it will exit gracefully. If not,
          +            # then there's nothing we can do anyway.
          +            self.reqs.put((_REQUEST_CLOSE, None, weakref.ref(Queue()), None))
          +        else:
          +            # we abuse 'select' to "iter" over a "--close--" statement so that we
          +            # can confirm the completion of close before joining the thread and
          +            # returning (by semaphore '--no more--'
          +            self.select_one(_REQUEST_CLOSE)
          +            self.join()
          +
          +
          +#
          +# This is here for .github/workflows/release.yml
          +#
          +if __name__ == '__main__':
          +    print(__version__)
          diff --git a/data/tefig/envs/olmes-eval/pyvenv.cfg b/data/tefig/envs/olmes-eval/pyvenv.cfg
          new file mode 100644
          index 0000000000000000000000000000000000000000..88047e47ba03384d05f56771c46e2b721eee3b62
          --- /dev/null
          +++ b/data/tefig/envs/olmes-eval/pyvenv.cfg
          @@ -0,0 +1,3 @@
          +home = /zfspool/zangyihe/conda_envs/lg/bin
          +include-system-site-packages = true
          +version = 3.10.19
          
        Target CoHeadquartered in Dearborn, Michigan, Target Co is a global automaker with TTM revenue of approximately $180B [1], anchored by its F-Series, SUV, and Pro commercial businesses [2].
        Target CoBaa3 (Senior Unsecured - Dom Curr / 2024-05-09)Stable
        Target CoCIS-3E-4S-3G-2
        Target CoLTM (30 Sep 2025)180.2B155.6B7.8B4.33%13.1B11.88x3.62x136.0B18.5%