# DeAlgo: connect an agent

DeAlgo is financial authority middleware: restricted identities, bounded proposals, exact human review, and linked evidence. Use it when an agent should request financial authority without broad payment credentials. General proposals never execute payments. The separate refund pilot executes only eligible Stripe test refunds. DeAlgo does not hold funds or provide payment accounts.

## 1. Owner creates the connection

The owner signs in at https://dealgo-portal.vercel.app/commerce/control?view=agents and creates a restricted commerce connection. Store the one-time key in the agent host's secret settings. Do not put it in chat, source control, a URL, or evidence. The owner must confirm the intended workspace and agent. A refund-only key cannot be used for commerce.

Install the pinned archive (Node.js 20 or later):

```sh
npm install --global https://dealgo-portal.vercel.app/downloads/dealgo-middleware-0.5.0.tgz
```

The checksum is at https://dealgo-portal.vercel.app/downloads/dealgo-middleware-0.5.0.sha256. To verify before installation, download the archive, compare its SHA-256 with the published checksum, then install that local file. The checksum detects corruption; it is not an independent signature.

Set DEALGO_URL to https://dealgo-portal.vercel.app and DEALGO_API_KEY to the restricted key in the host's secret environment. For self-hosted tests use the authorized server origin; plain HTTP is permitted only on localhost. Never substitute an untrusted server URL with your key. Supply the key through your secret manager rather than typing it into saved shell history.

## 2. Agent checks its connection

```sh
dealgo-middleware doctor-commerce
dealgo-middleware config-commerce
```

The doctor command makes a read-only authenticated capabilities check. Confirm workspaceId and agentId with the owner. It reports intakePaused, activeMandates, allowed evidence tools/origins, and nextSteps. These are a snapshot, not permission to execute. Active mandate count does not mean a particular request fits its limits or has available budget.

The config command prints a local stdio MCP configuration. Merge its entry into your MCP host without replacing other servers. The printed key is a placeholder, never the environment secret. Fill it using the host's secret settings. Restart the host. There is no hosted MCP URL. Legacy `config` and `mcp` select the separate test-refund tools; use the commerce commands for this guide.

MCP tools: dealgo_connection_status, dealgo_prepare_policy, dealgo_request_policy, dealgo_policy_request_status, dealgo_list_mandates, dealgo_propose_deal, dealgo_proposal_status, dealgo_report_tool_evidence. No tool can create credentials, activate policies, approve requests, change billing, or execute general payments.

## 3. Agent prepares; owner grants

Call `dealgo_request_policy` (SDK: `requestPolicy`) with the bound agentId, name, currency, explicit actions and counterparty IDs, maxSingleMinor, budgetMinor, expiresAt, and a persisted requestKey. Expiration must be in the future and no more than 90 days away. Limits are positive integer minor units, with maxSingleMinor no greater than budgetMinor.

```js
const identity = await dealgo.capabilities();
// Persist the entire payload before submission. Do not recompute expiresAt on retry.
const terms = {
  agentId: identity.agentId,
  name: "Approved suppliers",
  currency: "usd",
  actions: ["purchase"],
  counterparties: ["vendor_acme"],
  maxSingleMinor: 2500,
  budgetMinor: 10000,
  expiresAt: savedPolicyExpiry,
  requestKey: "supplier-policy-001",
};
const request = await dealgo.requestPolicy(terms);
console.log(request.reviewUrl, request.workspaceId);
// Owner independently reviews and activates in the same workspace.
const result = await dealgo.getPolicyRequest(request.id);
// Only an ACTIVATED result has a mandateId. Read current mandate limits before proposing.
```

The owner opens reviewUrl, signs in, selects the indicated workspace, and reviews the stored terms. A checkbox confirms that review before activation. The server compares the exact digest and rechecks the original connection. The agent must not impersonate the owner, click approval for them, or bypass the gate. The owner separately opens proposal intake in Settings when ready.

Requests expire after 24 hours or at the policy expiry, whichever comes first. At most 25 unexpired requests can be pending per agent. Identical retries with the same connection and requestKey return the same request; changed terms or a different credential with that key are refused. After an ambiguous submission, inspect the pending request list (`GET /api/v1/commerce/policy-requests`) and use the same key and exact payload if retrying. Keep returned IDs for future reads. GET by ID also reads reviewed or expired requests. Collection reads show the oldest 50 unexpired pending requests, scoped to the agent.

An expired or rejected request never grants authority. After owner review, ACTIVATED returns a mandateId for **proposals only**. Revoking the submitting connection blocks pending activation. Revoking a policy after activation is separate; always read its current status. The request's ACTIVATED history is not a continuing permission check.

`dealgo_prepare_policy` / `preparePolicy` remains available for validation without saving anything. It returns activated:false. Use requestPolicy when an owner handoff is needed.

## 4. Agent proposes exact terms

Install the archive into an application (omit --global) to use JavaScript:

```js
import { DeAlgo } from "@dealgo/middleware";
const dealgo = new DeAlgo({
  url: process.env.DEALGO_URL,
  apiKey: process.env.DEALGO_API_KEY,
});
const identity = await dealgo.capabilities();
const { mandates } = await dealgo.listMandates();
const mandate = mandates.find((m) => m.id === process.env.DEALGO_MANDATE_ID);
if (!mandate || identity.intakePaused) throw new Error("Owner setup required");
const result = await dealgo.propose({
  mandateId: mandate.id,
  action: "purchase",
  counterpartyId: "vendor_acme",
  amountMinor: 2500,
  currency: "usd",
  description: "Supplies for PO-1042",
  requestKey: "purchase-order-1042",
});
console.log(result.proposal.id, result.approvalUrl);
const status = await dealgo.getProposal(result.proposal.id);
// APPROVED is permission only. executionEnabled remains false.
```

Use a counterparty explicitly approved by the owner. Persist requestKey alongside the business request before submission. Reuse it with identical terms after a timeout; never invent a new key to retry the same action. A changed payload with the same key is refused. If the outcome is unclear, read the stored proposal or listProposals and escalate. The SDK never retries mutations automatically.

The review URL opens the queue; include the proposal ID so the owner can locate it. Collection reads return the latest 100 records for this agent; retain proposal IDs for subsequent reads. Searchable workspace-wide Activity is administrator-only.

## 5. Report authorized external tool metadata

The owner enables named tools and allowed evidence origins in Integrations. This permits reporting only; it does not authorize running the external tool or spending money. Call reportToolEvidence / dealgo_report_tool_evidence with eventKey, owned proposalId, tool, outcome (succeeded or failed), startedAt, finishedAt, inputSha256, outputSha256, and optional evidenceUrl and parentEventId.

Hash canonical, redacted inputs and outputs locally using SHA-256 (64 lowercase hex characters). Never submit raw arguments, outputs, credentials, or personal data. Do not send low-entropy sensitive data even as a hash. Evidence URLs must use an allowed HTTPS origin without credentials, query or fragment. Use a protected evidence resource, not a secret bearer URL. DeAlgo stores the reference and does not fetch the page. Parent events must belong to this same proposal and agent.

Preserve eventKey and the exact payload on retries. Identical reports deduplicate; changes return evidence_key_conflict. Reports are AGENT_REPORTED and are not independently verified, signed, or proof of payment. If the tool outcome is unknown, do not invent succeeded or failed: retain the uncertainty in your system and ask the owner to investigate. This version does not accept an unknown report outcome.

## Errors and handoff

- 401: invalid or missing connection; ask the owner for a valid restricted key, never their password.
- 403: wrong scope/agent, forbidden administrator action, or reporting not authorized. Do not expand privileges automatically.
- 409: conflicting terms or state; inspect error.code and ask the owner as needed.
- 429: respect the rate limit; do not issue parallel retry storms.
- Transport error or 5xx after submission: the result may be unknown. Preserve identifiers and exact terms; read before any same-key retry.

Read error.code; HTTP status alone does not authorize a fallback. HTTP reference: https://dealgo-portal.vercel.app/openapi.json. Complete behavior: https://dealgo-portal.vercel.app/downloads/dealgo-commerce-guide.md.

## What an internal pilot proves

An isolated agent pilot checks discovery, setup, identity, proposals, replay safety, evidence and forbidden operations. Test operator fixtures substitute for human review in that test environment only. They are not customer adoption, live settlement validation, security certification, or regulatory clearance. Keep live money disabled until business, provider, operational and legal requirements are resolved.

## Connect an approved request to a test refund

SDK 0.5.0 can include `refundTarget: { decisionId, paymentIntentId, reason }` on a refund proposal. Its counterparty must be `stripe:test:<paymentIntentId>`, and the original recorded decision must belong to the same agent and workspace. After owner approval, call `stageTestRefund(proposalId, digest)` or MCP `dealgo_stage_test_refund`. Give the returned review URL to the owner for final submission. `getTestRefund(proposalId)` / `dealgo_test_refund_status` reads the existing outcome. These tools cannot submit money or approve themselves.

Exact examples, eligibility, cancellation boundary and recovery: https://dealgo-portal.vercel.app/downloads/dealgo-commerce-guide.md#connected-test-refunds-050
