# Superb SDK

Use context-aware definitions, inspect source passages, compare readings and submit
linguistic judgments through one API. Deterministic inference needs no wallet,
account or external model. The source workspace package is `@superb/sdk`; it has
not been published to the npm registry.

```js
import { Superb } from '@superb/sdk';
const superb = new Superb({ baseUrl: 'https://your-superb-host.example' });
const result = await superb.resolve({ text: 'The bank approved the loan.', target: 'bank' });
if (result.sense) console.log(result.sense.gloss);
else console.log('Keep the alternatives open.', result.alternatives);
```

Use your actual deployment URL. Local development defaults to
`http://localhost:4173`. Errors are `SuperbError` values with HTTP `status`.
Requests accept `{signal}` and have a 15-second default timeout; increase
`timeoutMs` for provider requests.

## Inference

`resolve({text,target,mode?})` accepts up to 12,000 characters and a 100-character
word or phrase present in the passage. `mode` is `deterministic` (default), `jev`
or `laya`. Deterministic scores combine lexical overlap and released reviewed
anchors. They are not probabilities. Small margins abstain.

Jev uses TypeSafe's Choice API with the complete bounded sense inventory and an
explicit unclear option. Returned choices and probability distributions are
validated. `confidence` and `selectedProbability` are different provider fields.
Superb has not calibrated them on its corpus. Model agreement is not proof of truth.
Provider-backed requests require a signed-in account or a Bearer key entitled to
`sense-inference`, and server-side `TYPESAFE_API_KEY` configuration.

## Protocol consensus and contextual sense choice

```js
const consensus = await superb.predictConsensus({ contrastId: 'a'.repeat(64) });
if (consensus.kind === 'observed') console.log(consensus.result);
else console.log('Provisional distribution', consensus.resultDistribution);

const sense = await superb.predictSense({ text: 'The bank approved the loan.', target: 'bank' });
```

`predictConsensus()` reads a program-owned consensus account at Solana
`finalized` commitment and checks its registered rule/evaluator count result.
`kind: 'observed'` means protocol finalization also occurred. It reports
`verification.replay: false` until the committed artifact is supplied to
`verifyConsensus({contrastId,artifact})`. `predictSense()` is deterministic
contextual ranking; JEV/LAYA remain behind `predict_async()` and cannot
create protocol consensus. The older `predict()` reads a reward-epoch release
anchor and is a legacy corpus lookup, not a semantic consensus record.

`getConsensus(contrastId)` returns the compact account state.
`getReleaseCommitment(releaseId)` reads on-chain release lineage.
`verifyRelease({releaseId,artifact})` replays the release root and every member
consensus. `verifyReleaseArtifact(id)` retains the older local manifest and
artifact hash check without claiming on-chain lineage.

`compare({a,b,target,mode?})` returns both resolutions and a candidate relation;
`sameSenseProbability` remains null. `illuminate({text,targets,mode?})` accepts
1–12 explicit targets and returns UTF-16 offsets. `word(word)` returns definitions.

## Evidence, practice and contributions

| SDK method | HTTP route |
| --- | --- |
| `capabilities()` / `corpus()` | GET `/v1` / `/v1/corpus` |
| `contexts(target)` | GET `/v1/contexts?target=...` |
| `practice(target)` | GET `/v1/practice?target=...` |
| `releases()` / `release(id)` | GET `/v1/releases` / `/v1/releases/{id}` |
| `getConsensus(contrastId)` | GET `/v1/contrasts/{id}/consensus` |
| `predictConsensus(input)` / `predictSense(input)` | POST `/v1/predict/consensus` / `/v1/predict/sense` |
| `verifyConsensus(input)` / `verifyRelease(input)` | POST `/v1/verify/consensus` / `/v1/verify/release` |
| `epoch(id)` | GET `/v1/epochs/{id}` |
| `nextTask()` | GET `/v1/tasks/next` |
| `answer(id,'yes'|'no'|'unsure')` | POST `/v1/tasks/{id}/answer` |
| `me()` | GET `/v1/me` |
| `walletChallenge(wallet)` | POST `/v1/me/wallet/challenge` |
| `bindWallet({wallet,nonce,signature})` | POST `/v1/me/wallet/bind` |
| `reviewArgument(input)` | POST `/api/argument/review` |
| `importMedia(url)` | POST `/api/argument/import` |

Context pagination uses the returned `next` value as the next `after` query.
Only contribution passages cleared for display are public. Practice returns only
reviewed anchors in an accepted release; an empty set is a valid result. Task
answers need a current assignment and same-origin account session. Retries are
idempotent; changing an existing answer returns 409. Calibration answers and
private evaluation labels are never returned by task APIs.

Sign the exact wallet challenge message with your Solana wallet. Encode its
64-byte signature as base58. The nonce expires after five minutes and is single
use. Wallet binding permits no transfers. `/v1/me` returns allocations and proofs,
not a promise that an allocation is already claimed on chain. Use the settlement
client or a wallet transaction to claim and inspect the on-chain receipt.

## Media review

Supply `text`, optional `context` and `reply`, and up to four
`sources: [{id,label,text,url?}]`. Local review checks wording and semantic
candidates; it does not score truth or a person's intelligence. Cloud review needs
explicit consent and an `argument-review` key. `importMedia` explicitly fetches
public text through Superb, requires sign-in, and returns a transcript/extraction
for review. It does not assess video images. Upload transcription remains
`POST /api/argument/transcribe` with separate provider consent.

## Verify a release

```js
import { releaseHash } from '@superb/sdk';
const release = await superb.release('1.0.0');
if (await releaseHash(release.manifest) !== release.hash) throw new Error('Invalid release');
```

GET `/v1/releases/{id}/artifact` returns the committed reviewed artifact. Check its
SHA-256 against `manifest.artifactHash` using the same canonical encoding before
using it offline. Withdrawn artifacts return 410. Unconfigured capabilities return
503; missing records return 404. See `/data/openapi.json` for the machine-readable
contract and the repository's `examples/` for runnable scripts.

TypeSafe references: [Choice](https://docs.typesafe.ai/primitives/choice) and
[confidence](https://docs.typesafe.ai/confidence).

## Argument and agent primitives

`analyzeArgument({messages:[{id,text,author?,replyTo?}],maxClaims?,mode?,consent?,store?})`
returns candidate claims with exact UTF-16 spans, types, relations, verification
needs, contextual mismatch candidates, release provenance and an analysis ID.
Default extraction is sentence-based and does not decide truth. Jev mode classifies
claims and compares bounded candidate pairs. `focusMessageId` must name a supplied
message. Limits: 20 messages, 40,000 total characters, at most 40 extracted claims.

`compareClaims({a,b,mode?,consent?})` compares propositions. Deterministic output
recognizes exact text identity and isolated scope/strength substitutions. General
entailment, contradiction and referents require model assessment and may abstain.
`evaluateEvidence({claim,evidence:[{id,excerpt,title?,publisher?,url?}],mode?,consent?})`
assesses supplied text; deterministic overlap never becomes support or contradiction.
Jev reports can say supports, contradicts, mixed, insufficient or irrelevant, with
exact excerpt citations. A supplied publisher label is not independently verified.

These model calls require `argument-analysis` scope or same-origin sign-in,
`mode:'jev'` and `consent:true`. Pass a server-side `apiKey` to the SDK constructor.
Confidence is explicitly null where no calibrated or model value exists. Every v1
HTTP response carries `x-request-id`; errors expose it as `SuperbError.requestId`.
`store:true` retains argument/evidence analysis for the authenticated contributor;
otherwise requests are not retained. Stored analyses can link an observation.

`submitObservation({source,observedText,targets,rights,analysisId?,textHash?,residuals?})`
submits private observations for independent validation. Required rights include
`analysis:true`, separate display/redistribute/training booleans and a permission
basis. Observation duplicates are idempotent for their original contributor.
Agents never count as human voters. Source clearance, human review, released
utility and measured validation improvement precede discovery rewards.

Supply `span:[start,end]` to resolve one occurrence of a repeated expression. A
span can supply the target when `target` is omitted. Ambiguous target occurrences
abstain. `release` pins a version, hash, or published epoch; withdrawn releases
return 410. `verifyReleaseArtifact(id)` verifies both local manifest and artifact
hashes. It does not establish a finalized semantic release on Solana.
Wallet routes are `/v1/me/wallet/challenge` and `/v1/me/wallet/bind`;
DELETE `/v1/me/wallet` unbinds future rewards without changing existing allocations.

## Editorial reference inventory

`resolve({ text, target, inventory: "reference" })` uses the current public Reference inventory, including clarified glosses and sourced slang. This is an editorial view, not an accepted consensus release. The returned source includes the inventory integrity digest. Omit `inventory` to retain the accepted-release behavior, and use `release` to pin that behavior. `inventory: "reference"` cannot be combined with `release`. Source links and usage rights remain attached to the alternatives.
