Metadata-Version: 2.5
Name: jejoo-cli
Version: 0.1.0
Summary: Privacy-preserving Jejoo local analysis client.
Project-URL: Homepage, https://scaillabs.ai
Project-URL: Repository, https://github.com/dongyujung/jejoo
Keywords: agents,analysis,cli,observability,optimization
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.11
Requires-Dist: certifi>=2024.2.2
Requires-Dist: duckdb<2,>=1.1
Requires-Dist: numpy<3,>=2
Requires-Dist: polars<2,>=1.0
Requires-Dist: pyarrow<30,>=15
Requires-Dist: pydantic<3,>=2.7
Provides-Extra: langfuse
Requires-Dist: langfuse<6,>=5.0.4; extra == 'langfuse'
Provides-Extra: langsmith
Requires-Dist: langsmith<1,>=0.10.15; extra == 'langsmith'
Description-Content-Type: text/markdown

# Jejoo CLI

Jejoo CLI analyzes agent execution traces while keeping raw traces and canonical
execution facts on the user's machine. The Jejoo service supplies a bounded
normalization specification and investigation requests; the CLI returns only redacted
samples and bounded aggregate evidence.

For a task-oriented walkthrough, command reference, output files, and recovery
examples, see the [CLI user guide](https://github.com/dongyujung/jejoo/blob/main/docs/cli-user-guide.md).

The public package is now `jejoo-cli`, and the primary command is `jejoo`.
The previous `optimaize` and `optimaize-analyze` commands remain compatibility
aliases. Use `JEJOO_*` configuration variables; the corresponding `OPTIMAIZE_*`
names remain accepted. If both are set, the `JEJOO_*` value wins, including an empty
value. Default credentials are stored under `~/.config/jejoo`; valid credentials
from `~/.config/optimaize` are copied privately when first used and retained there
for rollback. Explicit config directories do not read or migrate another directory.

## Requirements

- Python 3.11 or newer
- A Jejoo API URL (no account or API key required for anonymous use)
- Optional workflow source files in UTF-8 text (any extension), or canonical workflow JSON
- A trace source: a local JSON/JSONL/CSV/Parquet file, LangSmith, or Langfuse

## Install

```bash
python -m pip install jejoo-cli
```

The CLI automatically loads a trusted public certificate bundle through `certifi`,
in addition to your platform's default certificate authorities. No certificate export
is needed for standard HTTPS connections, including Python installations without a
configured CA file. Certificate and hostname verification remain enabled.

For a custom or corporate trust configuration, set `SSL_CERT_FILE` or `SSL_CERT_DIR`.
When either is set, the CLI uses Python's configured trust settings without adding
the bundled public roots.

## Analyze

Choose the source that holds your traces. Each option runs the same analysis;
LangSmith and Langfuse users can connect directly without preparing a JSON export.

| Source | Getting started |
| --- | --- |
| Local JSON or another file | Pass the export path to `jejoo analyze` (JSON, JSONL, CSV, or Parquet). |
| [LangSmith](#fetch-from-langsmith) | Install `jejoo-cli[langsmith]`, configure credentials, and use `--source langsmith`. |
| [Langfuse](#fetch-from-langfuse) | Install `jejoo-cli[langfuse]`, configure credentials, and use `--source langfuse`. |

On first use the CLI obtains an installation token and project automatically. It
stores credentials outside your repository, under `~/.config/jejoo`, with
owner-only permissions. Set `JEJOO_CONFIG_DIR` to choose another location.
No account, manually supplied API key, or project ID is required.

Anonymous usage allows three analyses per installation per rolling 24 hours, one
active analysis per installation, and ten active anonymous analyses across the
service. Waiting for local evidence holds a concurrency slot. Shared source-address
and service-wide allowances also apply. Each JSON request is limited to 1 MiB;
trace artifacts stay local. Each job allows up to eight evidence queries of at
most 100 rows each.

Normalization allows six requests per installation per rolling 24 hours, with
bounded output and conservative model-cost reservations of $2 per installation,
$3 per source address, and $20 service-wide per rolling 24 hours. These are
server spending ceilings estimated using the configured model rate card, not a
charge to the user. Provider-reported usage settles each model call and releases unused allowance.
Timeouts and calls without usable usage retain their reservations as unknown.
Unknown-price models are unavailable to anonymous clients. SDK retries are disabled
for anonymous model calls; explicit repair calls reserve budget separately.

The CLI stores each job's separate access token privately. Installation tokens
cannot read job status/results, and a job token cannot read another job or submit
new analyses. Losing the local job credential means losing access to that job.
Installation credentials last one year and are replaced automatically on next use
after expiry; job credentials last until job expiry
(24 hours for anonymous jobs).

API keys remain optional for provisioned projects: set `JEJOO_API_KEY` and
`JEJOO_PROJECT_ID` (or pass the matching `--project-id`) to use that mode.
Keys are scoped to their provisioned projects and use authenticated submission
limits, rather than the anonymous installation allowance. Existing per-job
evidence limits and redaction still apply. Keep keys outside your repository and
shell history. If your operator supplies a private environment file, load it with
`source /path/to/private/testing.env` before running the usual analyze command.

For the local-file option, run trace-only analysis with an optional workflow input:

```bash
jejoo analyze traces.jsonl \
  --api-base-url https://app.scaillabs.ai \
  --output-dir .jejoo/trace-only-001
```

With no `--workflow`, the CLI derives an observed planning workflow locally from
normalized facts using the same helper as the web UI. Observed chronological
adjacency is not asserted to be declared control flow or causality. Declared-route
checks are disabled. Trace normalization and default LLM analysis still run, under
the existing usage limits; no workflow-normalization job is requested. Raw traces
and canonical facts remain local. The 100-operation web limit also applies.

To supply workflow context, run:

```bash
jejoo analyze traces.jsonl \
  --workflow workflow.json \
  --redaction-policy-id company-policy-v1 \
  --api-base-url https://api.example.com \
  --output-dir .jejoo/analysis
```

Remove sensitive fields from representative samples before they leave the machine:

```bash
jejoo analyze traces.jsonl \
  --workflow workflow.json \
  --redaction-policy-id company-policy-v1 \
  --remove-key prompt \
  --remove-key response \
  --api-base-url https://api.example.com \
  --output-dir .jejoo/analysis
```

Workflow sources use server-side LLM normalization by default. Repeat `--workflow`
to include orchestration and called modules, such as `--workflow agent.py --workflow tools.py`.
Any UTF-8 text extension is accepted (Python, JSON, YAML, TypeScript, Markdown, etc.),
with at most 10 files and 200000 source bytes combined. Binary files and archives
are not supported. Sources are read as text and never executed.

Workflow file contents and relative filenames are sent to the Jejoo server and
its normalization and analysis models. Trace sample redaction does not apply to workflow sources.
The supplied files also remain available to this analysis through bounded source
lookups, so retry predicates, backoff and fallback behavior can be checked against
the trace. Include the helpers implementing those policies, not only the entry
point. This requires a matching server and updated CLI; source files follow the
analysis submission's access and retention lifecycle. Source reads are never executed.
The normalized workflow and normalization spec are saved as `declared-workflow.json`
and `workflow-normalization.json`. Use `--workflow-normalization canonical` to read
one canonical `DeclaredWorkflow` JSON file directly, without workflow LLM normalization.
The resulting declared workflow is still sent with the analysis submission.

The final findings are written to `analysis-result.json`. Canonical facts remain in
`local/facts/execution_facts.parquet` beneath the selected output directory. The CLI does
not upload that Parquet file or its local path.

Run `jejoo analyze --help` for evidence, storage, sampling, and redaction limits.

## Fetch from LangSmith

Install the optional connector and configure LangSmith credentials locally:

```bash
python -m pip install 'jejoo-cli[langsmith]'
export LANGSMITH_API_KEY="your-langsmith-key"
# For regional or self-hosted deployments, also set LANGSMITH_ENDPOINT.
```

Select executions by their root runs, then fetch every internal run for local
normalization:

```bash
jejoo analyze \
  --source langsmith \
  --source-project research-agent \
  --since 7d \
  --max-traces 100 \
  --tag production \
  --workflow workflow.json \
  --redaction-policy-id company-policy-v1 \
  --api-base-url https://api.example.com \
  --output-dir .jejoo/langsmith-analysis
```

The LangSmith project name is separate from the Jejoo `--project-id`.
`--since` defaults to `7d`; it also accepts a timezone-aware ISO timestamp.
`--until` sets the exclusive upper bound (default: now). These bounds apply only
to root start times. Children are fetched without time or operation filters.

Use `--name` for an exact root name, repeat `--tag` to require all tags, or repeat
`--trace-id` to restrict the selection to specific trace UUIDs. Trace IDs still
obey the root time window and other selection criteria. `--source-filter` accepts
an advanced root filter, such as `eq(status, "error")`. `--tree-filter` selects
executions containing a matching internal operation, without discarding other steps.

The connector writes `langsmith-runs.jsonl` and `source-selection.json` locally.
The selection manifest records resolved timestamps, filters, selected root/trace IDs,
counts, the export hash, and whether the retrieval cap was reached. The cap follows
API result order; it is not representative sampling. A fresh output directory is
required for each export. Exceeding `--max-source-bytes` fails the export rather than
truncating execution trees. Live traces contain the steps available at retrieval time;
choose completed executions for stable analysis.

The connector requires `langsmith>=0.10.15` and uses the
[SmithDB SDK trace methods](https://docs.langchain.com/langsmith/smithdb-sdk-migration-traces).
Self-hosted LangSmith requires version 0.16 or later. It uses the existing local
normalization, redaction, and bounded evidence flow after retrieval.

## Fetch from Langfuse

Langfuse follows the shared normalization flow: the adapter retrieves native
observations, the server generates and validates a normalization program, and
the client executes the hash-verified program locally. Langfuse schema handling,
repair and native fallback remain on the server. Workflow files are optional.

Install the optional connector and configure project-scoped credentials locally:

```bash
python -m pip install 'jejoo-cli[langfuse]'
export LANGFUSE_PUBLIC_KEY="your-project-public-key"
export LANGFUSE_SECRET_KEY="your-project-secret-key"
export LANGFUSE_BASE_URL="https://cloud.langfuse.com"
```

Use your region's base URL or self-hosted URL. The connector uses Langfuse SDK v5
and Observations API v2, available on Langfuse Cloud and self-hosted Langfuse v4.
For a checkout of the full distribution, install `'.[langfuse]'` instead.

```bash
jejoo analyze \
  --source langfuse \
  --source-project research-agent \
  --since 7d \
  --max-traces 100 \
  --tag production \
  --workflow workflow.json \
  --redaction-policy-id company-policy-v1 \
  --api-base-url https://api.example.com \
  --output-dir .jejoo/langfuse-analysis
```

Credentials select the Langfuse project. `--source-project` is optional and verifies
the project name; `--project-id` identifies the separate Jejoo project.
The adapter selects logical root observations, then fetches every page of
observations belonging to each selected trace, including spans, tools, generations,
and events. Traces without an exported logical root in this project are not selected.

`--since` defaults to `7d`, and `--until` defaults to now. The inclusive lower and
exclusive upper bounds apply to root start times. `--name` matches the root
observation name; repeated `--tag` values require all tags. Repeated `--trace-id`
values restrict the selection to those IDs, while still respecting the root filters
and time window. IDs need not be UUIDs. Results follow newest-root order, or the
requested trace-ID order when IDs are supplied. The retrieval cap is not a
representative sampling strategy.

`--source-filter` accepts a Langfuse JSON array of conditions, combined with the
root/time/name/tag criteria. For example, select roots marked as errors:

```bash
--source-filter '[{"type":"stringOptions","column":"level","operator":"any of","value":["ERROR"]}]'
```

`--tree-filter` currently supports LangSmith only. Langfuse child retrieval has no
root filters or time bounds. The local export is `langfuse-observations.jsonl`, with
SDK field names such as `trace_id` and `parent_observation_id`. Inputs and outputs
remain the raw strings returned by v2. Field groups include I/O, model, usage, cost,
metadata, timing, and trace context. Langfuse may truncate metadata values; the
selection manifest records this limitation. It also records filters, selected
roots, project, counts, the export hash, and the retrieval cap.

As with LangSmith, exports require a fresh output directory and fail on the byte
limit rather than truncating execution trees. Retrieval reflects data visible at
fetch time; ingestion delays or running executions can leave later steps unavailable.
After retrieval, the existing local normalization and redaction flow applies.
See the [Langfuse SDK query documentation](https://langfuse.com/docs/api-and-data-platform/features/query-via-sdk).

The server-issued program preserves native and custom metadata locally and
projects diagnostic fields into a source-neutral form. It includes reasoning and
cache token subcategories in canonical counts and supplies a separate source-only
conservation check. The client executes these programs and applies generic
validation; it does not rewrite provider mappings. Diagnostics can detect empty,
reasoning-only attempts that consumed the configured output budget without
inventing a provider finish reason or retry index. Raw diagnostic content is
excluded from outbound evidence. Include entry-point and retry-helper files with
`--workflow` when the analysis should verify the configured retry policy; these
source files are sent to the server. Workflow files remain optional.

### Background normalization

Workflow and trace normalization run as private background jobs. The CLI submits
quickly and polls until the result is ready, so model calls may take longer than
the gateway's request limit. No additional flags are needed. A temporary polling
failure is retried without resubmitting model work.

Pending receipts, job credentials, and completed normalization results are cached
in the owner-only CLI credential directory for up to 24 hours. Rerun the same
command and output directory after a network interruption to resume normalization.
Once a job receipt is saved, the same command resumes that existing job even after
local canonicalization. The CLI verifies the local facts, trace and workflow identity;
changed inputs require a fresh output directory. Transient read requests are retried
within a bounded timeout. Analysis submissions are not automatically repeated.

The updated CLI requires a server that exposes the background normalization routes.

### Normalization usage

The CLI prints a per-stage usage summary and writes `normalization-usage.json` in
the output directory, including when normalization fails after a model response.
The printed summary shows model attempts, input and cached-input tokens, output and
reasoning tokens, and unresolved attempt counts. Dollar amounts are not printed.
The JSON artifact also records reported-usage cost estimates, released allowance,
and installation allowance left.
Reasoning tokens are included in output counts and are not charged a second time.
Costs use the rate-card snapshot saved with the attempt and are estimates, not invoices.

Successful cached normalizations are labelled as previous usage and do not represent
new model calls or a current allowance balance. Unknown attempts are shown separately;
their full unresolved reservation is recorded in the JSON artifact. Usage records contain identifiers, counts,
and pricing metadata; they do not contain prompts, trace samples, API keys, or raw
model responses. Historical calls that predate tracking cannot be priced retrospectively
from the application logs and keep their existing reservations.

Output diagnostics are computed locally. The client can return bounded finish reasons,
reasoning/output token counts, configured limits, empty-output flags, and ordered
attempt metadata. Prompts, generated text, and input fingerprints remain local.
Equivalent-input groups use existing opaque operation IDs. Missing diagnostic
metadata remains unknown, and older servers/clients keep their existing flow.
