> ## Documentation Index
> Fetch the complete documentation index at: https://docs.argalabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Gmail and Stripe tracing in TypeScript

> Capture selected agent evidence with customer-side filtering and identity aliases

Use Node.js SDK v0.2.0+ to wrap your existing Stripe and Gmail clients. Selection, text filtering and identity aliases run in your process. Arga receives a typed evidence projection for [Training](https://docs.argalabs.com/sdks/typescript/training.md).

## Create an upload key

Run this in a trusted setup process with a full Arga credential:

```typescript theme={null}
import { Arga } from 'arga-sdk';

const client = new Arga({ apiKey: process.env.ARGA_API_KEY! });
const credential = await client.training.createUploadKey({ source: 'support-agent' });
const uploadSecret = credential.key.getSecretValue();
// Store uploadSecret in your secret manager as ARGA_TRACE_KEY. Do not print it.
```

Use only `ARGA_TRACE_KEY` in the agent. It can upload evidence for that exact source, but cannot read collections, generate tasks, approve them or provision environments. The key expires after 30 days. Renew it in your trusted setup process. Legacy account-key rotation or session revocation invalidates it; v1 has no individual upload-key revocation endpoint.

## Wrap the provider clients

Provider libraries retain their own Node requirements. CI covers Gmail 18/Stripe 22 on the supported Node matrix and Gmail 22/Stripe 23 on Node 22.

The following code belongs alongside your existing `stripeClient`, `gmailClient` and `runAgent` application objects. A Gmail client from `googleapis` or `@googleapis/gmail` is supported. Arga does not create provider clients or read their credentials.

```typescript theme={null}
import { Tracing, CapturePolicy } from 'arga-sdk/tracing';

const tracing = new Tracing({
  source: 'support-agent',
  policy: new CapturePolicy({
    textFields: ['goal', 'policy'],
    transformText: filterTrainingText,
    revision: 'support-1',
  }),
});
const tracedStripe = tracing.wrapStripe(stripeClient);
const tracedGmail = tracing.wrapGmail(gmailClient);

const tracedAgent = tracing.agent(runAgent, {
  goal: (request) => request.task,
  policies: ['Customer confirmations require owner review before sending.'],
});
// Configure runAgent to use tracedStripe and tracedGmail, then invoke tracedAgent.
```

`filterTrainingText` is your synchronous local function. It must return a string and must not send raw text to Arga. Use it to remove names, proprietary facts and other information your organization excludes. Increase `revision` when its behavior changes. Built-in credential masking and email/Stripe-ID aliases supplement your filter; they do not guarantee removal of all personal information.

No free text leaves by default. Select `gmail.subject` and `gmail.body` explicitly only when those fields are needed and your local filter handles them. Supported text selectors are `goal`, `policy`, `gmail.subject` and `gmail.body`. A failed filter marks incomplete coverage and does not fall back to exporting the original text.

## Use an explicit episode

For a direct async workflow:

```typescript theme={null}
await tracing.episode({
  goal: 'Resolve the duplicate payment while preserving the original.',
  policies: ['Customer confirmations require owner review before sending.'],
}, async () => {
  // Await calls through tracedStripe and tracedGmail here.
});
await tracing.flush(10000);
console.log(tracing.diagnostics());
console.log(tracing.recentUploads());
await tracing.close();
```

Await every provider call before the episode ends. Context follows asynchronous calls through Node's `AsyncLocalStorage`; simultaneous agent invocations remain isolated. Synchronous functions and Gmail callbacks are also supported. Keep the episode open until callbacks finish. Consume generators inside an explicit episode.

After `close()`, a function wrapped by `agent()` continues to run without collection. Explicit `episode()` calls on a closed tracer raise an error.

There are no global monkey patches or additional provider calls. Original provider results and errors reach your application. Use manual page iteration with supported list calls when you need complete evidence. Stripe's automatic pagination helpers are delegated but create a coverage gap because subsequent internal requests are not individually observed.

## Preview and delivery

```typescript theme={null}
const preview = new Tracing({
  source: 'support-agent', upload: false,
  policy: new CapturePolicy({ textFields: ['goal'], transformText: filterTrainingText }),
});
const previewStripe = preview.wrapStripe(stripeClient);
await preview.episode({ goal: 'Inspect a selected customer' }, async () => {
  await previewStripe.customers.retrieve('YOUR_CUSTOMER_ID');
});
// Inspect preview.lastEpisode locally before enabling uploads.
```

The export queue contains validated, projected JSON only. It defaults to 32 episodes and makes at most three delivery attempts. `flush()` reports queue drainage; check `uploaded`, `failed` and `dropped` counters to verify delivery. Recent receipts contain only collection IDs and relative Training paths. There is no durable disk spool, so flush before process shutdown.

## Coverage and limits

* Stripe projection supports `customers`, `payment_intents`, `charges` and `refunds`; Gmail supports `messages`, `drafts` and `profile`.
* Gmail `messages.insert` and `messages.import` normalize to the evidence contract's `messages.create`; raw MIME arguments remain excluded.
* Only executed calls through the wrapped clients are observed. Unknown operations detected through those wrappers create coverage gaps. Calls using other clients are not automatically captured.
* Source code, provider credentials, arbitrary metadata, system prompts, model reasoning, raw MIME, attachments, HTML and Gmail snippets are excluded.
* Identity aliases are consistent within an episode and differ across episodes. Amounts, dates, resource relationships, provenance and selected operating policy remain available.
* Lists describe result pages, not the entire account. Missing fields mean unknown. Parallel reads are accepted; overlapping mutations, including overlapping reads and writes, create an ordering gap.
* Each episode is limited to 100,000 bytes, 100 events, 50 records per event, 4,000 characters per selected text and 10 policy strings. Exceeding a limit records a coverage issue rather than claiming completeness.

Arga stores one immutable private Training collection per accepted episode. Exact duplicate evidence is deduplicated per owner. There is no continuous collection grouping or automatic expiry in v1. Requested generation sends the selected evidence to Arga's configured model provider. Incomplete evidence remains inspectable and blocks task generation when required facts are missing.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.