@terminal3/t3n-sdk 4.32.0 → 4.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -644,6 +644,24 @@ interface TrustAnchor {
644
644
  * image measurements both verify.
645
645
  */
646
646
  rtmr3_allowlist: string[];
647
+ /**
648
+ * Optional provenance of the pinned values, for diagnostics only —
649
+ * never passed to the verifier and never part of any security
650
+ * decision. `fetchTrustedManifest` fills it in so a failed handshake
651
+ * can name *which* manifest disagreed with the cluster instead of
652
+ * leaving an operator to guess. The usual answer is a manifest
653
+ * published before the cluster rolled to a new image.
654
+ */
655
+ source?: TrustAnchorSource;
656
+ }
657
+ /** Where a {@link TrustAnchor}'s pinned values came from. Diagnostics only. */
658
+ interface TrustAnchorSource {
659
+ /** Monotonic version of the manifest the anchor was projected from. */
660
+ manifest_version: number;
661
+ /** RFC 3339 timestamp the manifest was signed. */
662
+ signed_at: string;
663
+ /** URL the manifest was fetched from. */
664
+ url: string;
647
665
  }
648
666
  /**
649
667
  * Escape hatch for local dev / tests against a node whose attestation
@@ -933,1294 +951,927 @@ declare class ContractResponseError extends T3nError {
933
951
  declare function parseContractResponse<T = unknown>(raw: string, schema?: ContractResponseSchema<T>): T;
934
952
 
935
953
  /**
936
- * Org-data wire types mirroring the org-data contract wire shapes.
937
- *
938
- * Plain TypeScript interfaces (no zod) — the SDK does not use a
939
- * validation library for domain types; see the existing `types/` files.
954
+ * Agent-auth grants — the standing on-chain authority a user delegates to
955
+ * an agent (envelope-free authorisation).
940
956
  *
941
- * Each response type below is paired with a shallow runtime predicate
942
- * (`isMutationResponse`, `isOrgPolicyMeta`, etc.) so the org-data client
943
- * can `assertShape` the decoded payload before returning to callers.
944
- * Predicates check the top-level structure only; nested elements
945
- * (e.g. each `BoundGrant` inside `OrgContractGrants.grants`) are not
946
- * deeply validated — see `utils/shape.ts` for the rationale.
957
+ * `AGENT_AUTH_MAP` is keyed by the *user* DID — one policy document per
958
+ * user, global across orgs, with at most one entry per agent DID. Reads
959
+ * (`agent-auth-get`) and writes (`agent-auth-update`) on
960
+ * `tee:authorisations/contracts` (the policy's owning contract) are
961
+ * **SelfOnly**: only the user, authenticated as themselves, may read or
962
+ * write their own grants. This is the user-approval
963
+ * proof the per-call delegation credential's `user_sig` used to carry.
964
+ *
965
+ * The write shape gained `scopes` + a validity window: the
966
+ * agent's delegated org-data scopes, and an optional `[valid_from_secs,
967
+ * valid_until_secs]` window. The ≤ cap *length* check is enforced contract-
968
+ * side at write time; the expiry gate is host-side at read time.
969
+ *
970
+ * The merge below is a script-level union (R59): writing a grant for one
971
+ * `(agent_did, script_name)` preserves every other script row on that
972
+ * agent's entry, and every other agent's entry, unchanged.
973
+ */
974
+ /** A single script grant in the camelCase write-request shape. */
975
+ interface AgentAuthScriptGrant {
976
+ /** Contract name, or `"*"`. */
977
+ scriptName: string;
978
+ /** Optional semver requirement; `null` to match any version. */
979
+ versionReq?: string | null;
980
+ /** Functions the agent may invoke on this contract. */
981
+ functions: string[];
982
+ /** Org-data scopes delegated to the agent for the contract functions to
983
+ * read on its behalf. */
984
+ scopes?: string[];
985
+ /** Direct-read scopes the agent may enumerate itself, via whichever read
986
+ * function the contract exposes for direct enumeration. A strict subset of
987
+ * `scopes` (enforced contract-side). */
988
+ readScopes?: string[];
989
+ /** Optional validity-window start (unix seconds). */
990
+ validFromSecs?: number | null;
991
+ /** NEW: optional validity-window end (unix seconds). */
992
+ validUntilSecs?: number | null;
993
+ /** Egress hosts the agent may reach for this contract. */
994
+ allowedHosts: string[];
995
+ }
996
+ /** One agent's entry in the write-request shape. */
997
+ interface AgentAuthEntry {
998
+ agentDid: string;
999
+ scripts: AgentAuthScriptGrant[];
1000
+ }
1001
+ /**
1002
+ * The full agent-auth policy document in the camelCase write shape:
1003
+ * the per-agent grants plus the document-level discovery grants.
947
1004
  *
948
- * Reference: the org-data wire contract.
1005
+ * `discoverDids` (contract wire: `discover_dids`) is the
1006
+ * list of DIDs the user lets their registered agents *enumerate the
1007
+ * contracts of* via `listContracts`: an org DID grants org-mode discovery,
1008
+ * the user's own DID grants self-mode discovery. It lives at document
1009
+ * level — not on a script grant — because discovery must surface contracts
1010
+ * the agent cannot yet call. The node's discovery gate additionally
1011
+ * requires the calling agent to be named in `agents` (subject binding), so
1012
+ * an unregistered agent discovers nothing regardless of this list.
949
1013
  */
1014
+ interface AgentAuthPolicy {
1015
+ agents: AgentAuthEntry[];
1016
+ discoverDids: string[];
1017
+ }
950
1018
  /**
951
- * Validity time-box on an agent-edge grant — serialised under the JSON key
952
- * `window`. Both bounds are optional unix-seconds; an omitted bound is
953
- * defaulted contract-side (`valid_from_secs` → now, `valid_until_secs` → now +
954
- * operator cap). Mirrors the org-data `Validity` wire shape. Absent bounds
955
- * are omitted from the wire (never sent as `null`).
1019
+ * Parse a full `agent-auth-get` response (the stored snake_case policy
1020
+ * document) into the camelCase write shape, including the document-level
1021
+ * `discover_dids`. A `null` / absent response is the empty policy.
956
1022
  */
957
- interface Validity {
958
- valid_from_secs?: number;
959
- valid_until_secs?: number;
1023
+ declare function parseAgentAuthPolicy(response: unknown): AgentAuthPolicy;
1024
+ /** Extract the `agents` array from an `agent-auth-get` response. */
1025
+ declare function parseAgentAuthGet(response: unknown): AgentAuthEntry[];
1026
+ interface AgentAuthMergeResult {
1027
+ /** Full merged `agents` list, ready for `agent-auth-update`. */
1028
+ agents: AgentAuthEntry[];
1029
+ /** `"<agentDid> → <scriptName>"` rows preserved from the existing policy. */
1030
+ preservedRows: string[];
960
1031
  }
1032
+ /** Input to the full-document write {@link T3nClient.agentAuthUpdate}. The
1033
+ * document IS the new state: an empty `agents` list revokes all agent
1034
+ * access, and an omitted / empty `discoverDids` persists an empty
1035
+ * discovery-grant list (the contract has no per-field merge). Mirrors the
1036
+ * contract `AgentAuthPolicy`. */
1037
+ interface AgentAuthUpdateInput {
1038
+ agents: AgentAuthEntry[];
1039
+ /** Document-level discovery grants — see {@link AgentAuthPolicy}. */
1040
+ discoverDids?: string[];
1041
+ }
1042
+ /**
1043
+ * Serialise a camelCase policy document to the contract's canonical
1044
+ * snake_case `agent-auth-update` wire (`agent_did` / `script_name` /
1045
+ * `version_req` / `read_scopes` / `valid_from_secs` / `valid_until_secs` /
1046
+ * `allowed_hosts` / `discover_dids`), so neither write path relies on the
1047
+ * contract's compatibility aliases. Absent optionals are omitted (never
1048
+ * sent as `null`); empty `scopes` / `read_scopes` are omitted (the
1049
+ * contract defaults both to empty). `functions` and `allowed_hosts` are
1050
+ * always emitted — the contract requires explicit functions (`["*"]` =
1051
+ * all) and reads an absent `allowed_hosts` as deny-all egress. The
1052
+ * document-level `discover_dids` (strictly snake_case — the contract
1053
+ * defines no camelCase alias for it) is emitted only when non-empty; the
1054
+ * contract defaults an absent list to empty.
1055
+ */
1056
+ declare function toAgentAuthUpdateWire(agents: AgentAuthEntry[], discoverDids?: string[]): {
1057
+ agents: Array<{
1058
+ agent_did: string;
1059
+ scripts: Array<Record<string, unknown>>;
1060
+ }>;
1061
+ discover_dids?: string[];
1062
+ };
1063
+ /**
1064
+ * Order-preserving deduplicating union of discovery-grant DID lists —
1065
+ * the read-merge-write counterpart of {@link mergeAgentAuthEntries} for
1066
+ * the document-level `discoverDids` (the contract rejects duplicate
1067
+ * entries, so the union must dedupe).
1068
+ */
1069
+ declare function mergeDiscoverDids(existing: string[], additions: string[]): string[];
1070
+ /**
1071
+ * Merge new agent entries into the existing policy with script-level union
1072
+ * semantics: for an agent DID present on both sides, script rows whose
1073
+ * `scriptName` is not being written are preserved; rows with a matching
1074
+ * `scriptName` are replaced by the new grant. Entries for other agent DIDs
1075
+ * pass through unchanged.
1076
+ */
1077
+ declare function mergeAgentAuthEntries(existing: AgentAuthEntry[], newEntries: AgentAuthEntry[]): AgentAuthMergeResult;
1078
+
961
1079
  /**
962
- * A grantee-bound capability grant — the element of BOTH grant-management
963
- * surfaces: the org edge (`org-policy-set-grants` input / `org-grants-get`
964
- * output) and the flat agent edge (`agent-auth-get` output / `agent-auth-update`
965
- * input). Stored inline on the unified `ROLE_ASSIGNMENTS_MAP` edge record.
1080
+ * KYC types for the `tee:user/contracts::kyc-status` short-poll
1081
+ * function.
966
1082
  *
967
- * Mirrors the org-data `BoundGrant` wire shape verbatim (snake_case, no casing
968
- * transform): `grantee` followed by the flattened capability body. The org edge
969
- * populates only `functions` + `scopes`; the agent edge additionally carries the
970
- * qualifiers `version_req` / `read_scopes` / `allowed_hosts` and the validity
971
- * `window`. All qualifier fields are optional and omitted from the wire when
972
- * absent (never sent as `null`), so an org grant simply leaves them unset.
1083
+ * The shape mirrors the `kyc-status` wire response.
1084
+ * The bytes go straight from the contract
1085
+ * through the JSON-RPC envelope into [[T3nClient.kycStatus]].
973
1086
  */
974
- interface BoundGrant {
975
- /** The principal (`did:t3n:<40-hex>`) this grant applies to — a user or an
976
- * agent DID. */
977
- grantee: string;
978
- /** Target contract id (canonical name, e.g. `"tee:z-payroll/contracts"`), or
979
- * `"*"`. On a read this echoes the queried contract. */
980
- contract_id: string;
981
- /** WIT function names the grantee may invoke (e.g. `"set-records"`; `["*"]`
982
- * matches all). */
983
- functions: string[];
984
- /** Data scope paths the grantee may access (e.g. `"example/records"`). */
985
- scopes: string[];
986
- /** Agent edge only: optional semver requirement; omitted matches any version. */
987
- version_req?: string;
988
- /** Agent edge only: direct-read scopes the grantee may enumerate itself — a
989
- * subset of `scopes` (enforced contract-side). */
990
- read_scopes?: string[];
991
- /** Agent edge only: egress hosts the grantee may reach for this contract. */
992
- allowed_hosts?: string[];
993
- /** Agent edge only: optional validity time-box. */
994
- window?: Validity;
995
- }
1087
+
996
1088
  /**
997
- * Policy record for an organisation's data tier.
1089
+ * Terminal status for a Level 2 KYC verification, plus `pending`.
998
1090
  *
999
- * Mirrors the org-data policy-meta wire shape.
1091
+ * - `pending` — provider has not delivered a verdict yet, or the
1092
+ * webhook arrived but the post-action VC issuance hasn't completed.
1093
+ * - `verified` — provider approved AND a VC has been issued. `vcIds`
1094
+ * carries the issued credential ids.
1095
+ * - `rejected` — provider declined / required resubmission /
1096
+ * expired / the user abandoned the flow. `error` may carry a
1097
+ * provider-supplied reason.
1098
+ * - `orphan` — a Veriff webhook arrived with a `vendorData` that
1099
+ * couldn't be matched to any user. Should not
1100
+ * happen in the MetaMask flow but the contract surfaces it for
1101
+ * completeness.
1000
1102
  */
1001
- interface OrgPolicyMeta {
1002
- /** DIDs (`did:t3n:<40-hex>`) of users authorised to manage policy and read data. */
1003
- admins: string[];
1004
- /** Maximum number of admins allowed for this org. */
1005
- max_admins: number;
1006
- /** Unix timestamp (secs) when the policy was first created. */
1007
- created_at_secs: number;
1008
- /** Unix timestamp (secs) of the most recent policy update. */
1009
- updated_at_secs: number;
1010
- /**
1011
- * Per-org ceiling on delegation-credential validity (seconds).
1012
- *
1013
- * Absent when no org-level cap is set — the contract omits the field
1014
- * (never serialises null) and the cluster-wide
1015
- * `delegation.max_credential_validity_secs` governs instead. When set,
1016
- * the effective cap is `min(max_credential_validity_secs, cluster_ceiling)`.
1017
- */
1018
- max_credential_validity_secs?: number;
1019
- }
1020
- /** Shallow runtime guard for {@link OrgPolicyMeta}. */
1021
- declare function isOrgPolicyMeta(value: unknown): value is OrgPolicyMeta;
1103
+ type KycStatusKind = "pending" | "verified" | "rejected" | "orphan";
1022
1104
  /**
1023
- * Effective org policy view returned by `org-policy-view`.
1105
+ * Snapshot returned by `tee:user/contracts::kyc-status`.
1024
1106
  *
1025
- * Readable by any authenticated session (non-sensitive metadata).
1026
- * Returns the **effective** credential validity cap:
1027
- * `min(org.max_credential_validity_secs, cluster_ceiling)`, equal to the
1028
- * cluster ceiling when the org has not set a per-org cap. The contract
1029
- * always returns a value (or errors) — the field is never null.
1107
+ * Field names use camelCase on the SDK boundary even though the
1108
+ * wire is snake_case — the wrapper rewrites keys at the client edge
1109
+ * so callers don't see the JSON shape leaking through.
1030
1110
  */
1031
- interface OrgPolicyView {
1111
+ interface KycStatus {
1112
+ /** Terminal status if reached, otherwise `pending`. */
1113
+ status: KycStatusKind;
1032
1114
  /**
1033
- * Effective delegation-credential validity cap in seconds:
1034
- * `min(org value, cluster ceiling)`, equal to the cluster ceiling when the
1035
- * org has not set a per-org cap. Always present — mirrors the contract's
1036
- * `PolicyViewResponse.effective_validity_secs` (org-data `org-policy-view`).
1115
+ * Provider being polled. Echoed back so callers that didn't
1116
+ * supply one see the contract's default (`"veriff"` in phase one).
1037
1117
  */
1038
- effective_validity_secs: number;
1118
+ provider: string;
1119
+ /**
1120
+ * Unix-millis of the latest contract-visible event:
1121
+ * VC issuance time, attestation arrival time, session-row
1122
+ * `started_at_ms`, or orphan-record arrival time. Best-effort —
1123
+ * `undefined` when no source carries a usable timestamp.
1124
+ */
1125
+ updatedAt?: number;
1126
+ /**
1127
+ * VC ids appended for this provider, in append order. Empty for
1128
+ * `pending` / `rejected` / `orphan`.
1129
+ */
1130
+ vcIds: string[];
1131
+ /**
1132
+ * Provider-supplied reason for `rejected`, when available.
1133
+ */
1134
+ error?: string;
1039
1135
  }
1040
- /** Shallow runtime guard for {@link OrgPolicyView}. */
1041
- declare function isOrgPolicyView(value: unknown): value is OrgPolicyView;
1042
1136
  /**
1043
- * Caller-scoped admin status returned by `org-am-i-admin`.
1044
- *
1045
- * Reports only whether the **calling** session's DID is in the org's admin
1046
- * list — never the roster itself (contrast {@link OrgPolicyMeta}, returned by
1047
- * the admin-gated `org-policy-get`). Readable by any authenticated session.
1048
- * Mirrors the org-data `AmIAdminResponse` wire shape.
1137
+ * Polling cadence for [[T3nClient.kycStatusPoll]]. Defaults:
1138
+ * poll fast for the first 30 seconds, then back
1139
+ * off, and bail after 5 minutes.
1049
1140
  */
1050
- interface OrgAdminStatus {
1051
- /** Whether the calling session is an admin of the queried org. */
1052
- is_admin: boolean;
1141
+ interface KycPollCadence {
1142
+ /** Poll interval in ms while `elapsed < switchAtMs`. Default: 2000. */
1143
+ fastMs: number;
1144
+ /** Poll interval in ms once `elapsed >= switchAtMs`. Default: 5000. */
1145
+ slowMs: number;
1146
+ /** Elapsed-ms threshold to switch from fast to slow cadence. Default: 30_000. */
1147
+ switchAtMs: number;
1148
+ /**
1149
+ * Maximum total time to spend polling before rejecting with
1150
+ * [[KycStatusTimeoutError]]. Default: 300_000 (5 minutes).
1151
+ */
1152
+ timeoutMs: number;
1053
1153
  }
1054
- /** Shallow runtime guard for {@link OrgAdminStatus}. */
1055
- declare function isOrgAdminStatus(value: unknown): value is OrgAdminStatus;
1056
1154
  /**
1057
- * Standard response returned by all policy write and data mutation operations.
1058
- *
1059
- * Mirrors the org-data `MutationResponse` wire shape.
1155
+ * Optional knobs for [[T3nClient.kycStatusPoll]]. Most callers won't
1156
+ * touch any of these — the cadence defaults are baked in.
1060
1157
  */
1061
- interface MutationResponse {
1158
+ interface KycPollOptions {
1062
1159
  /**
1063
- * `"created"`, `"updated"`, `"deleted"`, or — for the agent-card mutations —
1064
- * `"published"` / `"unpublished"`.
1160
+ * Cancellation signal. When aborted, the helper rejects with
1161
+ * `signal.reason` (or a generic `AbortError` if the consumer
1162
+ * didn't supply a reason). The currently-in-flight `kycStatus()`
1163
+ * call also receives the signal so it can short-circuit.
1065
1164
  */
1066
- status: string;
1067
- /** Hex-encoded entry ID; present on data write/delete operations. */
1068
- entry_id?: string;
1069
- /** Whether the target key existed before deletion; present on single-entry deletes. */
1070
- deleted?: boolean;
1071
- /** Number of entries removed; present on `org-data-delete-scope`. */
1072
- deleted_entries?: number;
1073
- tx_hash: string | null;
1165
+ signal?: AbortSignal;
1166
+ /**
1167
+ * Called with every snapshot the helper receives, including
1168
+ * non-terminal `pending` ones. Useful for surfacing intermediate
1169
+ * UI states (e.g. "still waiting on provider…"). Errors thrown
1170
+ * from this callback are caught and ignored — they must not
1171
+ * sink the poll loop.
1172
+ */
1173
+ onUpdate?: (status: KycStatus) => void;
1174
+ /**
1175
+ * Override one or more cadence fields. Anything not specified
1176
+ * uses the defaults from [[DEFAULT_KYC_POLL_CADENCE]].
1177
+ */
1178
+ cadence?: Partial<KycPollCadence>;
1179
+ /**
1180
+ * Provider id to poll. Defaults to the contract default
1181
+ * (`"veriff"` in phase one). Mirrored on the wire as
1182
+ * `input.provider_id`.
1183
+ */
1184
+ providerId?: string;
1074
1185
  }
1075
1186
  /**
1076
- * Shallow runtime guard for {@link MutationResponse}.
1077
- *
1078
- * Only the always-present fields are checked — `status` is mandatory on
1079
- * every mutation; `tx_hash` is non-optional but nullable. The optional
1080
- * fields (`entry_id`, `deleted`, `deleted_entries`) are not validated
1081
- * because their presence depends on which mutation ran.
1187
+ * Default cadence used by [[T3nClient.kycStatusPoll]] when the caller
1188
+ * doesn't override `cadence.*`.
1082
1189
  */
1083
- declare function isMutationResponse(value: unknown): value is MutationResponse;
1190
+ declare const DEFAULT_KYC_POLL_CADENCE: KycPollCadence;
1084
1191
  /**
1085
- * Response type alias for org-writers-get.
1086
- *
1087
- * The wire body is `{ writers: string[] }` where each entry is
1088
- * `did:t3n:<40-hex>`.
1192
+ * Subset of [[KycStatusKind]] that ends a poll. `pending` is the
1193
+ * only non-terminal value.
1089
1194
  */
1090
- interface OrgWriters {
1091
- writers: string[];
1092
- }
1093
- /** Shallow runtime guard for {@link OrgWriters}. */
1094
- declare function isOrgWriters(value: unknown): value is OrgWriters;
1195
+ declare const TERMINAL_KYC_STATUSES: ReadonlySet<KycStatusKind>;
1095
1196
  /**
1096
- * Response type alias for org-grants-get.
1097
- *
1098
- * The wire body echoes the `contract_id` alongside the grant list.
1197
+ * Thrown by [[T3nClient.kycStatusPoll]] when the cadence's
1198
+ * `timeoutMs` elapses without a terminal status arriving. The
1199
+ * `lastStatus` field is the most recent (necessarily `pending`)
1200
+ * snapshot the helper saw, useful for surfacing "we tried for N
1201
+ * minutes but Veriff is still working" UX.
1099
1202
  */
1100
- interface OrgContractGrants {
1101
- contract_id: string;
1102
- grants: BoundGrant[];
1203
+ declare class KycStatusTimeoutError extends T3nError {
1204
+ /** The timeout (ms) the helper exhausted before a terminal status arrived. */
1205
+ readonly timeoutMs: number;
1206
+ /** The last `pending` snapshot before timeout, if any. */
1207
+ readonly lastStatus?: KycStatus | undefined;
1208
+ constructor(
1209
+ /** The timeout (ms) the helper exhausted before a terminal status arrived. */
1210
+ timeoutMs: number,
1211
+ /** The last `pending` snapshot before timeout, if any. */
1212
+ lastStatus?: KycStatus | undefined);
1103
1213
  }
1214
+
1104
1215
  /**
1105
- * Shallow runtime guard for {@link OrgContractGrants}.
1216
+ * Wire types for the explicit `otp-request` /
1217
+ * `otp-verify` / slim `user-upsert` exports on `tee:user/contracts`
1218
+ * (`tee:user@2.0.0`).
1106
1219
  *
1107
- * Validates the immediate envelope (`contract_id: string`, `grants:
1108
- * array`) without recursing into each `BoundGrant`. The Rust contract
1109
- * is the source of truth for grant element shape; widening the predicate
1110
- * here would create maintenance churn against benign field additions.
1220
+ * Pre-2.0.0 the user contract dispatched OTP request and OTP verify
1221
+ * implicitly from the input shape of a single `user-upsert` call.
1222
+ * 2.0.0 splits that surface into three explicit functions; the
1223
+ * shapes here mirror the OTP / user-upsert wire contract.
1224
+ *
1225
+ * Bytes flow directly from the contract
1226
+ * through the JSON-RPC envelope into the SDK wrappers
1227
+ * (`T3nClient.otpRequest`, `T3nClient.otpVerify`,
1228
+ * `T3nClient.submitUserInput`).
1111
1229
  */
1112
- declare function isOrgContractGrants(value: unknown): value is OrgContractGrants;
1230
+
1113
1231
  /**
1114
- * One grant inside a role: a capability body (functions + scopes, without the
1115
- * grantee, which is bound at assignment time) plus the target contract.
1116
- * Mirrors the org-data `RoleGrant` wire shape.
1232
+ * OTP delivery channel. Matches the `OtpContactChannel` Rust enum
1233
+ * with `serde(rename_all = "snake_case")`.
1117
1234
  */
1118
- interface RoleGrant {
1119
- /** Target contract (canonical name, e.g. `"tee:z-payroll/contracts"`). */
1120
- contract_id: string;
1121
- /** WIT function names this grant confers. */
1122
- functions: string[];
1123
- /** Data scope paths this grant confers (canonicalised lowercase). */
1124
- scopes: string[];
1125
- }
1235
+ type OtpChannel = "email" | "sms";
1126
1236
  /**
1127
- * A role: a named bundle of grants and/or composed sub-roles.
1128
- * Mirrors the org-data `RoleDefinition` wire shape.
1237
+ * Discriminated OTP contact target. Mirrors the Rust `OtpRequest` enum
1238
+ * (`email_channel` / `sms_channel` on the wire). Exactly one branch is
1239
+ * set — no parallel optional email + phone with a separate channel tag.
1240
+ *
1241
+ * The legacy `keys.generic_api.otp_channel` body shadow was removed
1242
+ * in 2.0.0 — the contract rejects calls carrying it with a
1243
+ * `legacy_field` error.
1129
1244
  */
1130
- interface RoleDefinition {
1131
- /** Org-unique role identifier (slug; function-name grammar). */
1132
- role_id: string;
1133
- /** Human-facing label. */
1134
- label: string;
1135
- /** Composite: other role ids in the same org whose grants this role confers. */
1136
- includes: string[];
1137
- /** Grants this role confers directly. */
1138
- grants: RoleGrant[];
1139
- }
1245
+ type OtpRequestInput = {
1246
+ emailChannel: {
1247
+ emailAddress: string;
1248
+ };
1249
+ } | {
1250
+ smsChannel: {
1251
+ phoneNumber: string;
1252
+ };
1253
+ };
1140
1254
  /**
1141
- * The roles assigned to one grantee within one org.
1142
- * Mirrors the org-data `RoleAssignments` wire shape.
1255
+ * Response returned by `otp-request`. Mirrors the OTP wire response.
1256
+ *
1257
+ * - `contact` echoes the OTP destination so clients that race
1258
+ * multiple channels can correlate replies.
1259
+ * - `expiresAtSec` is the Unix-second TTL the host minted for the
1260
+ * pending OTP. Absent in `skip_otp` test environments.
1261
+ * - `status` is `"otp_pending"` on the happy path. `"otp_failed"`
1262
+ * only appears on retry without a fresh request — usually you
1263
+ * shouldn't see it on `otp-request`.
1264
+ * - `txHash` is the host-enriched ledger ref for the OTP-pending
1265
+ * write (the contract leaves it `null`; the host injects).
1266
+ * - `isNewProfile` is `true` on a fresh DID's first OTP request —
1267
+ * read this to detect "did the user just register".
1143
1268
  */
1144
- interface RoleAssignments {
1145
- /** Assigned role ids. */
1146
- roles: string[];
1147
- }
1148
- /** Response for `org-role-get`; `role` is `null` when the id is unknown. */
1149
- interface RoleGetResponse {
1150
- role: RoleDefinition | null;
1269
+ interface OtpRequestResult {
1270
+ contact: string;
1271
+ channel: OtpChannel;
1272
+ expiresAtSec?: number;
1273
+ status?: string;
1274
+ txHash?: string;
1275
+ isNewProfile?: boolean;
1151
1276
  }
1152
- /** Shallow runtime guard for {@link RoleGetResponse}. */
1153
- declare function isRoleGetResponse(value: unknown): value is RoleGetResponse;
1154
- /** Response for `org-role-assignments-get`. */
1155
- interface RoleAssignmentsResponse {
1156
- /** Echoed back so callers don't need to track which request this answers. */
1157
- grantee_did: string;
1158
- /** The grantee's assigned role ids (empty when none). */
1159
- roles: string[];
1277
+ /**
1278
+ * Input to `T3nClient.otpVerify`. `otpCode` is mandatory; `request`
1279
+ * repeats the same discriminated contact shape as {@link OtpRequestInput}.
1280
+ */
1281
+ interface OtpVerifyInput {
1282
+ otpCode: string;
1283
+ request: OtpRequestInput;
1160
1284
  }
1161
- /** Shallow runtime guard for {@link RoleAssignmentsResponse}. */
1162
- declare function isRoleAssignmentsResponse(value: unknown): value is RoleAssignmentsResponse;
1163
1285
  /**
1164
- * Input for `listAgents` — the org plus optional pagination. Omit both `cursor`
1165
- * and `limit` for the first page at the default limit; pass a previous
1166
- * response's `next_cursor` back as `cursor` to fetch the following page.
1286
+ * Suggestion surfaced when the bind-target contact already belongs
1287
+ * to another DID. The contract refuses to silently steal the
1288
+ * authenticator; the caller must resolve the merge (typically via
1289
+ * `merge-profiles`) before re-attempting verify.
1167
1290
  */
1168
- interface ListAgentsInput {
1169
- orgDid: string;
1170
- /** Opaque cursor from a previous response's `next_cursor`. */
1171
- cursor?: string;
1172
- /** Maximum agents to return in this page. */
1173
- limit?: number;
1291
+ interface OtpMergeSuggestion {
1292
+ existingDid: string;
1293
+ currentDid: string;
1294
+ email?: string;
1295
+ phone?: string;
1296
+ channel: OtpChannel;
1174
1297
  }
1175
1298
  /**
1176
- * One org-owned agent in a {@link ListAgentsResponse}: the agent's DID, its
1177
- * display name, and the number of distinct contracts it can access via a direct
1178
- * grant. Mirrors the org-data `AgentSummary` wire shape. The name comes from the
1179
- * agent's private card (falling back to the DID), so the FE no longer needs to
1180
- * fetch each `public:agent_cards` entry to render the roster.
1299
+ * Response returned by `otp-verify`. Mirrors the OTP-verify wire response.
1300
+ *
1301
+ * - `email` is populated on `channel = "email"` success;
1302
+ * `phone` on `channel = "sms"` success. Mutually exclusive on
1303
+ * the happy path.
1304
+ * - `status` carries `"otp_failed"` / `"otp_expired"` on retry; the
1305
+ * happy path leaves it `undefined`.
1306
+ * - `mergeSuggestion` is set when the contact-to-bind is already
1307
+ * owned by another DID. Wire it into your merge UX.
1181
1308
  */
1182
- interface AgentSummary {
1183
- /** The agent's DID (`did:t3n:<40-hex>`). */
1309
+ interface OtpVerifyResult {
1310
+ txHash?: string;
1184
1311
  did: string;
1185
- /** The agent's display name, from its private card (DID when unavailable). */
1186
- name: string;
1187
- /** Count of distinct contracts the agent holds a direct grant on. */
1188
- contract_count: number;
1189
- }
1190
- /** Response for `org-data-list-agents`. */
1191
- interface ListAgentsResponse {
1192
- /** One PAGE of the org's org-owned agents, sorted by DID. */
1193
- agents: AgentSummary[];
1194
- /** Opaque cursor for the next page; absent on the last page. */
1195
- next_cursor?: string;
1312
+ channel: OtpChannel;
1313
+ email?: string;
1314
+ phone?: string;
1315
+ status?: string;
1316
+ mergeSuggestion?: OtpMergeSuggestion;
1317
+ isNewProfile?: boolean;
1196
1318
  }
1197
- /** A human member's org role. The closed wire domain of {@link HumanMember}. */
1198
- type MemberRole = "admin" | "member";
1199
1319
  /**
1200
- * Input for `listHumanMembers` — the org plus optional pagination. Omit both
1201
- * `cursor` and `limit` for the first page at the default limit; pass a previous
1202
- * response's `next_cursor` back as `cursor` to fetch the following page.
1320
+ * Level-1 user-input fields accepted by the slim `user-upsert`. Field names
1321
+ * are the on-the-wire names — `submitUserInput` sends this object verbatim,
1322
+ * so keys must match the contract exactly (snake_case). The canonical Level-1
1323
+ * set is the six fields below; the shape is intentionally open so callers can
1324
+ * add provider-specific fields the contract knows how to merge.
1325
+ *
1326
+ * `email_address` / `phone_number` are normally bound via the OTP roundtrip
1327
+ * before `submitUserInput`, but the contract accepts them directly here too.
1203
1328
  */
1204
- interface ListHumanMembersInput {
1205
- orgDid: string;
1206
- /** Opaque cursor from a previous response's `next_cursor`. */
1207
- cursor?: string;
1208
- /** Maximum members to return in this page. */
1209
- limit?: number;
1329
+ interface UserInputProfile {
1330
+ first_name?: string;
1331
+ last_name?: string;
1332
+ country_of_residence?: string;
1333
+ document_issuance_country?: string;
1334
+ ssn?: string;
1335
+ address?: string;
1336
+ email_address?: string;
1337
+ phone_number?: string;
1338
+ campaign_code?: string;
1339
+ role?: string;
1340
+ [key: string]: unknown;
1210
1341
  }
1211
1342
  /**
1212
- * One direct human member: DID plus org role. No profile PII (name/email are
1213
- * out of scope and owned by `tee:user`). Mirrors the org-data `HumanMember`
1214
- * wire shape.
1343
+ * Input to `T3nClient.submitUserInput`. Maps onto the slim
1344
+ * `user-upsert` request shape: `{ profile, organisation_did?,
1345
+ * attestations?, keys? }`.
1215
1346
  */
1216
- interface HumanMember {
1217
- /** The member's DID (`did:t3n:<40-hex>`). */
1218
- did: string;
1219
- /** The member's org role. */
1220
- role: MemberRole;
1221
- }
1222
- /** Response for `org-data-list-human-members`. */
1223
- interface ListHumanMembersResponse {
1224
- /** One PAGE of the org's direct human members, sorted by DID. */
1225
- members: HumanMember[];
1226
- /** Opaque cursor for the next page; absent on the last page. */
1227
- next_cursor?: string;
1228
- }
1229
- /** Shallow runtime guard for {@link ListHumanMembersResponse}. */
1230
- declare function isListHumanMembersResponse(value: unknown): value is ListHumanMembersResponse;
1231
- /** Shallow runtime guard for {@link ListAgentsResponse}. */
1232
- declare function isListAgentsResponse(value: unknown): value is ListAgentsResponse;
1233
- /** Response for `org-data-list`. */
1234
- interface DataListResponse {
1235
- /** Hex-encoded entry IDs for this page. */
1236
- entry_ids: string[];
1237
- /** Offset to pass for the next page. `null` when this is the last page. */
1238
- next_offset: number | null;
1239
- /** Total number of entries in the scope (across all pages). */
1240
- total: number;
1241
- }
1242
- /** Shallow runtime guard for {@link DataListResponse}. */
1243
- declare function isDataListResponse(value: unknown): value is DataListResponse;
1244
- /** Secret shape discriminator (mirrors the contract `SecretKind`). */
1245
- type SecretKind = "single_value" | "json";
1246
- /** Metadata common to every {@link SecretView} entry. */
1247
- interface SecretViewBase {
1248
- /** Secret name (the `(org, name)` key tail). */
1249
- name: string;
1250
- /** Monotonic version, bumped on each value rotation and ACL edit. */
1251
- version: number;
1252
- /** Unix seconds of the most recent write. */
1253
- updated_at_secs: number;
1347
+ interface SubmitUserInputArgs {
1348
+ profile: UserInputProfile;
1349
+ organisationDid?: string;
1350
+ attestations?: unknown;
1351
+ keys?: Record<string, unknown>;
1352
+ /**
1353
+ * KYC webhook orphan-attestation flow. When set, the contract
1354
+ * skips the email-not-verified gate and only records the
1355
+ * attestation if the DID has no profile yet.
1356
+ * Most callers should leave this `undefined`.
1357
+ */
1358
+ requireExistingUser?: boolean;
1359
+ /**
1360
+ * Testnet self-admit. When `true`, the contract additionally
1361
+ * runs the self-admit side-effect after the profile commit: writes
1362
+ * the caller's DID into `idx:_tenants` + `idx:_tenant_quotas` and
1363
+ * mints any operator-configured welcome credits. Inspect the
1364
+ * `tenantAdmit` field on the response for the outcome.
1365
+ *
1366
+ * Testnet-only. Production clusters return
1367
+ * `tenantAdmit.status = "refused"` with
1368
+ * `reason = "not_testnet" | "self_admit_disabled" | "not_eth_derived"`.
1369
+ * The profile commit always succeeds regardless of the inner outcome.
1370
+ *
1371
+ * Most callers should leave this `undefined`.
1372
+ */
1373
+ becomeDevTenant?: boolean;
1254
1374
  }
1255
1375
  /**
1256
- * The redacted per-secret summary `org-secret-list` returns — a discriminated
1257
- * union on `kind`. The value is NEVER present: a single-value exposes only its
1258
- * last four characters and a json secret only its sorted top-level field names.
1376
+ * Testnet self-admit projection from `user-upsert`. Present only
1377
+ * when the caller set `becomeDevTenant: true` on the request.
1378
+ *
1379
+ * - `status: "admitted"` — first call for this DID; tenant record
1380
+ * committed and (if configured) welcome credits minted into
1381
+ * `grantedCredits`.
1382
+ * - `status: "already-admitted"` — replay; idempotent no-op.
1383
+ * - `status: "refused"` — the cluster declined the self-admit;
1384
+ * `reason` is the machine-readable cause (`not_testnet`,
1385
+ * `self_admit_disabled`, `not_eth_derived`), `detail` is a
1386
+ * human-readable string.
1259
1387
  */
1260
- type SecretView = (SecretViewBase & {
1261
- kind: "single_value";
1262
- /** Last four characters of the value (whole value when ≤ 4 chars). */
1263
- last4: string;
1264
- }) | (SecretViewBase & {
1265
- kind: "json";
1266
- /** Sorted top-level object field names (keys only, no values). */
1267
- field_names: string[];
1268
- });
1269
- /** Shallow runtime guard for {@link SecretView}. */
1270
- declare function isSecretView(value: unknown): value is SecretView;
1388
+ type TenantAdmitStatus = "admitted" | "already-admitted" | "refused";
1389
+ interface TenantAdmitProjection {
1390
+ status: TenantAdmitStatus;
1391
+ grantedCredits?: string;
1392
+ reason?: string;
1393
+ detail?: string;
1394
+ }
1271
1395
  /**
1272
- * Full secret record returned by `org-secret-get` — the value IS included
1273
- * (the deliberate read-back path the READ axis exists for), along with all
1274
- * three ACLs.
1396
+ * Response shape returned by the slim `user-upsert`. Carries the
1397
+ * post-merge tx hash plus the Level-1 merge diagnostics
1398
+ * (`refusedFields`, `mergeSuggestion`) the pre-2.0.0 omnibus
1399
+ * `UpsertResponse` already surfaced.
1275
1400
  */
1276
- interface SecretRecord {
1277
- name: string;
1278
- kind: SecretKind;
1279
- /** The value as text: the scalar for a single-value, canonical JSON object for a json secret. */
1280
- value: string;
1281
- version: number;
1282
- /** READ axis — DIDs allowed to read the value back. */
1283
- reader_dids: string[];
1284
- /** READ axis — role ids allowed to read the value back. */
1285
- reader_roles: string[];
1286
- /** MANAGE axis — DIDs allowed to rotate the value. */
1287
- manager_dids: string[];
1288
- /** MANAGE axis — role ids allowed to rotate the value. */
1289
- manager_roles: string[];
1290
- /** USE axis — canonical contract ids allowed to have the value injected. */
1291
- contract_allowlist: string[];
1292
- created_at_secs: number;
1293
- updated_at_secs: number;
1294
- /** DID of the caller who last wrote the record. */
1295
- updated_by: string;
1296
- }
1297
- /** Shallow runtime guard for {@link SecretRecord}. */
1298
- declare function isSecretRecord(value: unknown): value is SecretRecord;
1299
- /** Response for `org-secret-list`: redacted per-kind views, no values. */
1300
- interface SecretListResponse {
1301
- secrets: SecretView[];
1302
- }
1303
- /** Shallow runtime guard for {@link SecretListResponse}. */
1304
- declare function isSecretListResponse(value: unknown): value is SecretListResponse;
1305
- /** Response for `org-data-get`. */
1306
- interface DataGetResponse {
1307
- entry_id: string;
1308
- /** Hex-encoded raw payload bytes. */
1309
- payload_hex: string;
1401
+ interface SubmitUserInputResult {
1402
+ txHash?: string;
1403
+ refusedFields?: string[];
1404
+ mergeSuggestion?: OtpMergeSuggestion;
1405
+ userFound?: boolean;
1406
+ /**
1407
+ * Testnet self-admit projection. Present only when the caller
1408
+ * set `becomeDevTenant: true` on the request.
1409
+ */
1410
+ tenantAdmit?: TenantAdmitProjection;
1310
1411
  }
1311
- /** Shallow runtime guard for {@link DataGetResponse}. */
1312
- declare function isDataGetResponse(value: unknown): value is DataGetResponse;
1313
1412
  /**
1314
- * Return shape of `agentCardGet` — composed client-side from the generic
1315
- * `org-data-get` read of the card's entry (there is no card-specific read
1316
- * operation on the contract). To check whether a public copy exists, probe
1317
- * the anonymous `GET /api/agent-card/{did}` endpoint.
1413
+ * Discriminator for {@link UserUpsertError}. Mirrors the
1414
+ * `UserUpsertError` wire enum and its `<code>:<detail>` wire
1415
+ * format. Branch with a `switch` over `kind`.
1416
+ *
1417
+ * - `EmailNotVerified` — the slim `user-upsert` was called against
1418
+ * a DID that has no verified email and no proving authenticator.
1419
+ * Run `otpRequest` + `otpVerify` first (or accept an
1420
+ * OIDC/Email-authed session).
1421
+ * - `LegacyField` — caller passed a pre-2.0.0 dispatch field
1422
+ * (`otp_code` to a non-verify export, or
1423
+ * `keys.generic_api.otp_channel` anywhere). Migrate the call
1424
+ * site to the new explicit functions.
1425
+ * - `UserNotFound` — `requireExistingUser` was set but no profile
1426
+ * exists for the DID. The attestation is recorded for audit;
1427
+ * no profile created.
1318
1428
  */
1319
- interface AgentCardResponse {
1320
- /** The agent whose card this is (`did:t3n:<40-hex>`). */
1321
- agent_did: string;
1322
- /** The stored card JSON body, verbatim. */
1323
- card: string;
1324
- }
1325
- /** Shallow runtime guard for {@link AgentCardResponse}. */
1326
- declare function isAgentCardResponse(value: unknown): value is AgentCardResponse;
1429
+ type UserUpsertErrorKind = "EmailNotVerified" | "LegacyField" | "UserNotFound";
1327
1430
  /**
1328
- * Legacy direct-route org-data envelope shape retained for compatibility.
1431
+ * Typed wrapper for the `<code>:<detail>` errors the slim
1432
+ * `user-upsert` and the OTP entry points emit. `kind` is the
1433
+ * structured discriminator the SDK derives from the error code
1434
+ * prefix; `code` and `detail` retain the wire components for
1435
+ * fall-through logging.
1329
1436
  *
1330
- * This mirrors the removed `/api/user-contract/execute` body format from
1331
- * the transitional transport. New callers should use `OrgDataClient`,
1332
- * which now dispatches through authenticated `/api/rpc` +
1333
- * `action.execute` instead.
1437
+ * Throw site: `T3nClient.submitUserInput` (and friends) when the
1438
+ * contract returns a string error matching the
1439
+ * `<code>:<detail>` shape.
1334
1440
  */
1335
- interface OrgDataActionWire {
1336
- nonce: string;
1337
- user_did: string;
1338
- authenticator_id: string;
1339
- contract_id: string;
1340
- function: string;
1341
- args_hash: string;
1342
- expires_at_secs: number;
1343
- signature: string;
1441
+ declare class UserUpsertError extends T3nError {
1442
+ readonly kind: UserUpsertErrorKind | "Unknown";
1443
+ readonly detail: string;
1444
+ constructor(code: string, detail: string);
1445
+ /**
1446
+ * Try to parse a contract error string into a `UserUpsertError`.
1447
+ * Returns `null` if `raw` doesn't match the `<code>:<detail>`
1448
+ * shape — caller falls back to a generic error.
1449
+ */
1450
+ static fromWire(raw: string): UserUpsertError | null;
1344
1451
  }
1345
1452
 
1346
1453
  /**
1347
- * Agent-auth grants — the standing on-chain authority a user delegates to
1348
- * an agent (envelope-free authorisation).
1454
+ * Token-metering wire shapes.
1349
1455
  *
1350
- * The document is one flat list of {@link BoundGrant} rows plus the
1351
- * document-level discovery grants: `{ grants, discover_dids }`. Each grant's
1352
- * `grantee` is the agent DID it authorises, so there is no per-agent grouping —
1353
- * a user's whole delegation surface is the single `grants` array. Reads
1354
- * (`agent-auth-get`) and writes (`agent-auth-update`) on
1355
- * `tee:authorisations/contracts` (the policy's owning contract) are
1356
- * **SelfOnly**: only the user, authenticated as themselves, may read or write
1357
- * their own grants. This is the user-approval proof the per-call delegation
1358
- * credential's `user_sig` used to carry.
1359
- *
1360
- * A grant carries `functions`, the agent's delegated org-data `scopes`, the
1361
- * direct-enumerable `read_scopes`, egress `allowed_hosts`, an optional semver
1362
- * `version_req`, and an optional validity `window`. The ≤ cap *length* check is
1363
- * enforced contract-side at write time; the expiry gate is host-side at read
1364
- * time.
1365
- *
1366
- * The SDK is a literal snake_case mirror of the wire: {@link BoundGrant} IS the
1367
- * wire grant shape, so reads and writes pass through untouched — there is no
1368
- * casing transform. The only glue here is the read-merge-write helper
1369
- * ({@link mergeGrants}) that lets a single-grant write preserve every other row
1370
- * (the contract has no per-field merge; the document IS the new state).
1456
+ * Mirrors the token-metering wire contract. `u128` fields land on the
1457
+ * wire as JSON numbers (same convention as the existing
1458
+ * `token.get-balance` response) — JS clients with histories that
1459
+ * exceed 2⁵³ tokens should switch to a streaming JSON parser; the
1460
+ * common case fits in `number` losslessly.
1371
1461
  */
1372
-
1373
1462
  /**
1374
- * The full agent-auth policy document — the shape of BOTH the `agent-auth-get`
1375
- * output and the `agent-auth-update` input (they are identical). A flat list of
1376
- * grant rows plus the document-level discovery grants; mirrors the contract
1377
- * `AgentAuthDoc` wire shape verbatim (snake_case).
1378
- *
1379
- * `discover_dids` is the list of DIDs the user lets their registered agents
1380
- * *enumerate the contracts of* via `listContracts`: an org DID grants org-mode
1381
- * discovery, the user's own DID grants self-mode discovery. It lives at document
1382
- * level — not on a grant — because discovery must surface contracts the agent
1383
- * cannot yet call. The node's discovery gate additionally requires the calling
1384
- * agent to be the `grantee` of at least one grant (subject binding), so an
1385
- * unregistered agent discovers nothing regardless of this list.
1386
- *
1387
- * The document IS the new state on a write: an empty `grants` list revokes all
1388
- * agent access, and an empty `discover_dids` persists an empty discovery-grant
1389
- * list (there is no per-field merge). Use {@link mergeGrants} /
1390
- * {@link mergeDiscoverDids} to read-merge-write a single grant without dropping
1391
- * the rest.
1392
- */
1393
- interface AgentAuthDoc {
1394
- /** Every standing agent-edge grant, each keyed by its `grantee` agent DID. */
1395
- grants: BoundGrant[];
1396
- /** Document-level discovery grants (`did:t3n:<40-hex>` entries). */
1397
- discover_dids: string[];
1398
- }
1399
- /**
1400
- * Decode an `agent-auth-get` response into an {@link AgentAuthDoc}. The wire is
1401
- * already snake_case, so grant rows pass through unchanged — this only defaults
1402
- * a `null` / absent response (the empty policy) and a missing field to an empty
1403
- * list. NOT a casing transform.
1404
- */
1405
- declare function parseAgentAuthDoc(response: unknown): AgentAuthDoc;
1406
- interface GrantsMergeResult {
1407
- /** Full merged grant list, ready for `agent-auth-update`. */
1408
- grants: BoundGrant[];
1409
- /** `"<grantee> → <contract_id>"` rows preserved from the existing policy. */
1410
- preservedRows: string[];
1463
+ * The token `BalanceRow` wire shape — caller's credit row.
1464
+ *
1465
+ * `available` and `reserved` are `u128` on the server; the wire
1466
+ * format is a JSON number. Callers should not assume bigint until
1467
+ * the SDK migrates to a streaming parser (tracked separately).
1468
+ *
1469
+ * ⚠️ Amounts are in **base units** (`1 token = `
1470
+ * {@link BASE_UNITS_PER_TOKEN}), not whole tokens. Use
1471
+ * {@link formatTokens} to display them.
1472
+ */
1473
+ interface BalanceRow {
1474
+ /** Spendable balance, in base units (see {@link formatTokens}). */
1475
+ available: number;
1476
+ /** Reserved balance, in base units. */
1477
+ reserved: number;
1478
+ last_settled_seq_no: number;
1479
+ version: number;
1480
+ credit_exhausted: boolean;
1411
1481
  }
1412
1482
  /**
1413
- * Merge new grant rows into the existing flat list with `(grantee, contract_id)`
1414
- * union semantics: an existing row whose `(grantee, contract_id)` matches a new
1415
- * row is replaced; every other existing row is preserved (and reported in
1416
- * `preservedRows` as an audit aid). New rows for a `(grantee, contract_id)` not
1417
- * already present are appended.
1483
+ * The token-tx-kind wire alphabet (snake_case). Every
1484
+ * value listed here is accepted by the server-side
1485
+ * `token.get-usage` `kinds` filter.
1486
+ */
1487
+ type TokenTxKind = "mint" | "burn" | "charge" | "transfer" | "bridge_mint_attest" | "bridge_burn_attest";
1488
+ /**
1489
+ * Per-caller view direction. `"in"` = caller's balance went up;
1490
+ * `"out"` = caller's balance went down. Derived host-side from
1491
+ * `(caller_did, tx.src, tx.dst)`; the same `seq_no` appears in both
1492
+ * parties' usage feeds with opposite directions on a transfer.
1418
1493
  */
1419
- declare function mergeGrants(existing: BoundGrant[], additions: BoundGrant[]): GrantsMergeResult;
1494
+ type Direction = "in" | "out";
1420
1495
  /**
1421
- * Order-preserving deduplicating union of discovery-grant DID lists — the
1422
- * read-merge-write counterpart of {@link mergeGrants} for the document-level
1423
- * `discover_dids` (the contract rejects duplicate entries, so the union must
1424
- * dedupe).
1496
+ * Discriminated union mirroring the charge-reason wire union.
1497
+ * Present only when the row's `kind === "charge"`.
1425
1498
  */
1426
- declare function mergeDiscoverDids(existing: string[], additions: string[]): string[];
1427
-
1499
+ type ChargeReason = {
1500
+ kind: "contract_register";
1501
+ script_name: string;
1502
+ version: string;
1503
+ } | {
1504
+ kind: "invocation";
1505
+ script_name: string;
1506
+ function: string;
1507
+ fuel_consumed: number;
1508
+ fuel_tokens: number;
1509
+ host_call_count: number;
1510
+ host_call_tokens: number;
1511
+ } | {
1512
+ kind: "kv_bytes";
1513
+ map: string;
1514
+ } | {
1515
+ kind: "cas_bytes";
1516
+ backend: string;
1517
+ } | {
1518
+ kind: "outbox_egress";
1519
+ upstream: string;
1520
+ };
1428
1521
  /**
1429
- * KYC types for the `tee:user/contracts::kyc-status` short-poll
1430
- * function.
1522
+ * One row in the caller's usage feed — a per-caller projection of
1523
+ * the underlying `TokenTx`. `counterparty` is the other party from
1524
+ * the caller's perspective: `tx.dst` on outbound entries, `tx.src`
1525
+ * on inbound. `null` when the underlying tx has no counterparty
1526
+ * (mints have no `src`; burns and charges have no `dst`).
1527
+ */
1528
+ interface UsageEntry {
1529
+ seq_no: number;
1530
+ kind: TokenTxKind;
1531
+ /** Amount moved, in base units (`1 token = `{@link BASE_UNITS_PER_TOKEN}); see {@link formatTokens}. */
1532
+ amount: number;
1533
+ timestamp_ms: number;
1534
+ direction: Direction;
1535
+ counterparty?: string | null;
1536
+ reason?: ChargeReason | null;
1537
+ note?: string | null;
1538
+ }
1539
+ /**
1540
+ * Response shape of `token.get-usage` — caller's balance plus a
1541
+ * paginated slice of their most-recent `token:tx_log` entries.
1431
1542
  *
1432
- * The shape mirrors the `kyc-status` wire response.
1433
- * The bytes go straight from the contract
1434
- * through the JSON-RPC envelope into [[T3nClient.kycStatus]].
1543
+ * `next_cursor` is the inclusive upper-bound `seq_no` to pass back
1544
+ * as `after_seq` to fetch the next page. `null` (or absent) means
1545
+ * the caller's history is fully drained.
1546
+ */
1547
+ interface UsagePage {
1548
+ balance: BalanceRow;
1549
+ entries: UsageEntry[];
1550
+ next_cursor?: number | null;
1551
+ }
1552
+ /**
1553
+ * Request shape — all fields optional. `limit` clamps to
1554
+ * `1..=200` server-side; out-of-range values snap silently to the
1555
+ * bounds. `kinds: []` is treated as "no filter".
1435
1556
  */
1557
+ interface GetUsageOptions {
1558
+ limit?: number;
1559
+ after_seq?: number;
1560
+ kinds?: TokenTxKind[];
1561
+ }
1436
1562
 
1437
1563
  /**
1438
- * Terminal status for a Level 2 KYC verification, plus `pending`.
1564
+ * Tenant audit-event wire shapes.
1439
1565
  *
1440
- * - `pending` — provider has not delivered a verdict yet, or the
1441
- * webhook arrived but the post-action VC issuance hasn't completed.
1442
- * - `verified` — provider approved AND a VC has been issued. `vcIds`
1443
- * carries the issued credential ids.
1444
- * - `rejected` — provider declined / required resubmission /
1445
- * expired / the user abandoned the flow. `error` may carry a
1446
- * provider-supplied reason.
1447
- * - `orphan` — a Veriff webhook arrived with a `vendorData` that
1448
- * couldn't be matched to any user. Should not
1449
- * happen in the MetaMask flow but the contract surfaces it for
1450
- * completeness.
1566
+ * Mirrors `tenant_types::AuditEvent` and the `audit.get-mine` response
1567
+ * (`service::tenant_logs::{AuditBatch, AuditPage}`). A tenant contract
1568
+ * emits an audit event via the `logging::audit` host call; the host
1569
+ * stamps the identity fields (`subject` / `actor` / `vc_id`) from the
1570
+ * verified dispatch context, so a contract can never forge who acted or
1571
+ * on whom. Events are permanent (encrypted, append-only) and scoped to a
1572
+ * user — distinct from the evicting debug ring read via `getContractLogs`.
1451
1573
  */
1452
- type KycStatusKind = "pending" | "verified" | "rejected" | "orphan";
1453
1574
  /**
1454
- * Snapshot returned by `tee:user/contracts::kyc-status`.
1455
- *
1456
- * Field names use camelCase on the SDK boundary even though the
1457
- * wire is snake_case — the wrapper rewrites keys at the client edge
1458
- * so callers don't see the JSON shape leaking through.
1575
+ * One host-stamped audit event. `subject` / `actor` are canonical DID
1576
+ * strings. On a self-call `actor === subject` and `vc_id` is `null`; on a
1577
+ * delegated call `actor` is the agent and `vc_id` is the delegation
1578
+ * credential. The remaining fields are supplied verbatim by the contract.
1459
1579
  */
1460
- interface KycStatus {
1461
- /** Terminal status if reached, otherwise `pending`. */
1462
- status: KycStatusKind;
1463
- /**
1464
- * Provider being polled. Echoed back so callers that didn't
1465
- * supply one see the contract's default (`"veriff"` in phase one).
1466
- */
1467
- provider: string;
1468
- /**
1469
- * Unix-millis of the latest contract-visible event:
1470
- * VC issuance time, attestation arrival time, session-row
1471
- * `started_at_ms`, or orphan-record arrival time. Best-effort —
1472
- * `undefined` when no source carries a usable timestamp.
1473
- */
1474
- updatedAt?: number;
1475
- /**
1476
- * VC ids appended for this provider, in append order. Empty for
1477
- * `pending` / `rejected` / `orphan`.
1478
- */
1479
- vcIds: string[];
1480
- /**
1481
- * Provider-supplied reason for `rejected`, when available.
1482
- */
1483
- error?: string;
1580
+ interface AuditEvent {
1581
+ /** Cluster-deterministic flush timestamp (ms). */
1582
+ ts_ms: number;
1583
+ /** The user whose data the call touched (host-stamped `pii_did`). */
1584
+ subject: string;
1585
+ /** The agent (delegated) or user (self-call) who acted (host-stamped). */
1586
+ actor: string;
1587
+ /** Delegation credential id on a delegated call; `null` on a self-call. */
1588
+ vc_id?: string | null;
1589
+ /** Contract-supplied: what happened, e.g. `"kyc.approve"`. */
1590
+ action: string;
1591
+ /** Contract-supplied: what it acted on, e.g. `"user-profile"`. */
1592
+ target: string;
1593
+ /** Contract-supplied: the result, e.g. `"success"` / `"denied"`. */
1594
+ outcome: string;
1595
+ /** Contract-supplied: optional free-text / JSON detail. */
1596
+ details?: string | null;
1484
1597
  }
1485
1598
  /**
1486
- * Polling cadence for [[T3nClient.kycStatusPoll]]. Defaults:
1487
- * poll fast for the first 30 seconds, then back
1488
- * off, and bail after 5 minutes.
1599
+ * One archived batch — the events committed in a single tenant dispatch.
1600
+ * Every event in a batch shares the same `subject` / `actor` / `vc_id`.
1489
1601
  */
1490
- interface KycPollCadence {
1491
- /** Poll interval in ms while `elapsed < switchAtMs`. Default: 2000. */
1492
- fastMs: number;
1493
- /** Poll interval in ms once `elapsed >= switchAtMs`. Default: 5000. */
1494
- slowMs: number;
1495
- /** Elapsed-ms threshold to switch from fast to slow cadence. Default: 30_000. */
1496
- switchAtMs: number;
1602
+ interface AuditBatch {
1603
+ /** Hex of the archive key — usable directly as `cursor` for the next page. */
1604
+ key: string;
1497
1605
  /**
1498
- * Maximum total time to spend polling before rejecting with
1499
- * [[KycStatusTimeoutError]]. Default: 300_000 (5 minutes).
1606
+ * Host-stamped: did the emitting dispatch's contract transaction
1607
+ * commit? `false` means the call rolled back or trapped, so an event's
1608
+ * `outcome: "success"` in this batch is the contract's *claim*, not a
1609
+ * committed fact — filter on this when you need only durable events.
1500
1610
  */
1501
- timeoutMs: number;
1611
+ committed: boolean;
1612
+ events: AuditEvent[];
1502
1613
  }
1503
1614
  /**
1504
- * Optional knobs for [[T3nClient.kycStatusPoll]]. Most callers won't
1505
- * touch any of these — the cadence defaults are baked in.
1615
+ * `audit.get-mine` response — a page of audit batches, newest scan order.
1616
+ * `next_cursor` is present (a key hex) when more batches remain; `null`
1617
+ * once the scan reaches the end.
1506
1618
  */
1507
- interface KycPollOptions {
1508
- /**
1509
- * Cancellation signal. When aborted, the helper rejects with
1510
- * `signal.reason` (or a generic `AbortError` if the consumer
1511
- * didn't supply a reason). The currently-in-flight `kycStatus()`
1512
- * call also receives the signal so it can short-circuit.
1513
- */
1514
- signal?: AbortSignal;
1515
- /**
1516
- * Called with every snapshot the helper receives, including
1517
- * non-terminal `pending` ones. Useful for surfacing intermediate
1518
- * UI states (e.g. "still waiting on provider…"). Errors thrown
1519
- * from this callback are caught and ignored — they must not
1520
- * sink the poll loop.
1521
- */
1522
- onUpdate?: (status: KycStatus) => void;
1523
- /**
1524
- * Override one or more cadence fields. Anything not specified
1525
- * uses the defaults from [[DEFAULT_KYC_POLL_CADENCE]].
1526
- */
1527
- cadence?: Partial<KycPollCadence>;
1528
- /**
1529
- * Provider id to poll. Defaults to the contract default
1530
- * (`"veriff"` in phase one). Mirrored on the wire as
1531
- * `input.provider_id`.
1532
- */
1533
- providerId?: string;
1619
+ interface AuditPage {
1620
+ batches: AuditBatch[];
1621
+ next_cursor?: string | null;
1534
1622
  }
1535
1623
  /**
1536
- * Default cadence used by [[T3nClient.kycStatusPoll]] when the caller
1537
- * doesn't override `cadence.*`.
1538
- */
1539
- declare const DEFAULT_KYC_POLL_CADENCE: KycPollCadence;
1540
- /**
1541
- * Subset of [[KycStatusKind]] that ends a poll. `pending` is the
1542
- * only non-terminal value.
1543
- */
1544
- declare const TERMINAL_KYC_STATUSES: ReadonlySet<KycStatusKind>;
1545
- /**
1546
- * Thrown by [[T3nClient.kycStatusPoll]] when the cadence's
1547
- * `timeoutMs` elapses without a terminal status arriving. The
1548
- * `lastStatus` field is the most recent (necessarily `pending`)
1549
- * snapshot the helper saw, useful for surfacing "we tried for N
1550
- * minutes but Veriff is still working" UX.
1624
+ * Request shape for {@link T3nClient.getAuditEvents} — all fields
1625
+ * optional. Omit `pii_did` to read your own trail (all actors); set it to
1626
+ * another user's DID to read, as a delegated agent, the events you
1627
+ * performed for them — admitted only while that user's agent-auth grant
1628
+ * to you is live. `cursor` is the `next_cursor` from a prior page.
1551
1629
  */
1552
- declare class KycStatusTimeoutError extends T3nError {
1553
- /** The timeout (ms) the helper exhausted before a terminal status arrived. */
1554
- readonly timeoutMs: number;
1555
- /** The last `pending` snapshot before timeout, if any. */
1556
- readonly lastStatus?: KycStatus | undefined;
1557
- constructor(
1558
- /** The timeout (ms) the helper exhausted before a terminal status arrived. */
1559
- timeoutMs: number,
1560
- /** The last `pending` snapshot before timeout, if any. */
1561
- lastStatus?: KycStatus | undefined);
1630
+ interface GetAuditEventsOptions {
1631
+ pii_did?: string;
1632
+ limit?: number;
1633
+ cursor?: string;
1562
1634
  }
1563
1635
 
1564
1636
  /**
1565
- * Wire types for the explicit `otp-request` /
1566
- * `otp-verify` / slim `user-upsert` exports on `tee:user/contracts`
1567
- * (`tee:user@2.0.0`).
1637
+ * Agent-activity audit-log wire shapes (the node's `auditlog` RPC).
1568
1638
  *
1569
- * Pre-2.0.0 the user contract dispatched OTP request and OTP verify
1570
- * implicitly from the input shape of a single `user-upsert` call.
1571
- * 2.0.0 splits that surface into three explicit functions; the
1572
- * shapes here mirror the OTP / user-upsert wire contract.
1639
+ * Mirrors `service::activity_audit::{ActivityReport, ReportEntry}` and
1640
+ * `primitives::audit_log::AuditLogEntry`. One entry per audited contract
1641
+ * dispatch — who called, for whom, which contract + function, and how it
1642
+ * ended. Entries are reconstructed from the append-only ledger on read, so
1643
+ * `seq_no` (the ledger index) and `hash` are derived server-side rather than
1644
+ * stored with the record.
1573
1645
  *
1574
- * Bytes flow directly from the contract
1575
- * through the JSON-RPC envelope into the SDK wrappers
1576
- * (`T3nClient.otpRequest`, `T3nClient.otpVerify`,
1577
- * `T3nClient.submitUserInput`).
1646
+ * Scope is the caller's **own organisation**, resolved node-side from the
1647
+ * session DID: there is no scope parameter, and a page carries **every
1648
+ * member's** activity in that org, not just the caller's own. Metadata only —
1649
+ * DIDs, never display names, call arguments, or payloads.
1578
1650
  */
1579
-
1580
1651
  /**
1581
- * OTP delivery channel. Matches the `OtpContactChannel` Rust enum
1582
- * with `serde(rename_all = "snake_case")`.
1652
+ * Whether the actor is a registered agent or a human / self principal.
1653
+ * Decided node-side by an existence check on the actor DID in the agent
1654
+ * registry — never inferred from the DID's shape.
1583
1655
  */
1584
- type OtpChannel = "email" | "sms";
1656
+ type ActivityCallerType = "agent" | "human";
1585
1657
  /**
1586
- * Discriminated OTP contact target. Mirrors the Rust `OtpRequest` enum
1587
- * (`email_channel` / `sms_channel` on the wire). Exactly one branch is
1588
- * set — no parallel optional email + phone with a separate channel tag.
1658
+ * Host-stamped outcome of an audited dispatch.
1589
1659
  *
1590
- * The legacy `keys.generic_api.otp_channel` body shadow was removed
1591
- * in 2.0.0 — the contract rejects calls carrying it with a
1592
- * `legacy_field` error.
1660
+ * - `success` — the business transaction committed.
1661
+ * - `denied` — authorisation refused the call.
1662
+ * - `error` — the call was allowed but failed / rolled back.
1593
1663
  */
1594
- type OtpRequestInput = {
1595
- emailChannel: {
1596
- emailAddress: string;
1597
- };
1598
- } | {
1599
- smsChannel: {
1600
- phoneNumber: string;
1601
- };
1602
- };
1664
+ type ActivityOutcome = "success" | "denied" | "error";
1665
+ /** One audited call. */
1666
+ interface ActivityEntry {
1667
+ /**
1668
+ * Ledger index of the entry — its unique, ordered id. Use it as the row key
1669
+ * and as the ordering key: it is monotonic, whereas {@link timestamp_ms} is
1670
+ * per-node wall clock.
1671
+ */
1672
+ seq_no: number;
1673
+ /** Hex SHA-256 of the stored entry (64 chars) — read-time tamper evidence. */
1674
+ hash: string;
1675
+ /**
1676
+ * Call time in Unix ms, stamped on the node that took the request. NOT a
1677
+ * cluster-assigned time, so entries from different nodes can be skewed by
1678
+ * their clock offset — order by {@link seq_no}, not by this.
1679
+ */
1680
+ timestamp_ms: number;
1681
+ /** Agent vs human, from the agent-registry check on {@link actor}. */
1682
+ caller_type: ActivityCallerType;
1683
+ /** DID that actually invoked the contract. */
1684
+ actor: string;
1685
+ /**
1686
+ * DID of the owner the caller acted for. Equals {@link actor} on a self /
1687
+ * own-authority call — never null.
1688
+ */
1689
+ on_behalf_of: string;
1690
+ /**
1691
+ * Organisation the acting principal belongs to — the report's scope key, so
1692
+ * it is identical on every row of a page. Falls back to `on_behalf_of` when
1693
+ * that principal is in no organisation.
1694
+ */
1695
+ org: string;
1696
+ /** Contract that ran, e.g. `tee:user/contracts`. */
1697
+ contract: string;
1698
+ /** Contract function invoked, e.g. `user-upsert`. */
1699
+ function: string;
1700
+ /** success / denied / error — host-stamped from the dispatch result. */
1701
+ outcome: ActivityOutcome;
1702
+ /**
1703
+ * Role ids the acting authority carried at call time: the actor's role in
1704
+ * the organisation on a self-call, the roles the owner granted the agent on
1705
+ * a delegated call. Omitted when the authority carried no role (direct
1706
+ * grants, an individual, or an entry recorded before roles were captured).
1707
+ * On a `denied` entry this is the caller's *claimed* authority, not a
1708
+ * validated one.
1709
+ */
1710
+ roles?: string[];
1711
+ }
1603
1712
  /**
1604
- * Response returned by `otp-request`. Mirrors the OTP wire response.
1605
- *
1606
- * - `contact` echoes the OTP destination so clients that race
1607
- * multiple channels can correlate replies.
1608
- * - `expiresAtSec` is the Unix-second TTL the host minted for the
1609
- * pending OTP. Absent in `skip_otp` test environments.
1610
- * - `status` is `"otp_pending"` on the happy path. `"otp_failed"`
1611
- * only appears on retry without a fresh request — usually you
1612
- * shouldn't see it on `otp-request`.
1613
- * - `txHash` is the host-enriched ledger ref for the OTP-pending
1614
- * write (the contract leaves it `null`; the host injects).
1615
- * - `isNewProfile` is `true` on a fresh DID's first OTP request —
1616
- * read this to detect "did the user just register".
1713
+ * One page of the organisation's activity report — **newest first**, i.e.
1714
+ * descending `seq_no`.
1617
1715
  */
1618
- interface OtpRequestResult {
1619
- contact: string;
1620
- channel: OtpChannel;
1621
- expiresAtSec?: number;
1622
- status?: string;
1623
- txHash?: string;
1624
- isNewProfile?: boolean;
1716
+ interface ActivityReport {
1717
+ entries: ActivityEntry[];
1718
+ /**
1719
+ * Cursor to resume from — pass it back as
1720
+ * {@link GetActivityLogOptions.before_seq}. `null` once the requested window
1721
+ * is exhausted.
1722
+ *
1723
+ * A live cursor with **fewer rows than `limit`, or none at all**, is normal:
1724
+ * the node also caps how much ledger one call decrypts, and that cap can trip
1725
+ * before the window ends. Page until this is `null`, never on a short or
1726
+ * empty page.
1727
+ */
1728
+ next_seq: number | null;
1625
1729
  }
1626
- /**
1627
- * Input to `T3nClient.otpVerify`. `otpCode` is mandatory; `request`
1628
- * repeats the same discriminated contact shape as {@link OtpRequestInput}.
1629
- */
1630
- interface OtpVerifyInput {
1631
- otpCode: string;
1632
- request: OtpRequestInput;
1730
+ /** Params for one activity-report page. All optional; `{}` is valid. */
1731
+ interface GetActivityLogOptions {
1732
+ /** Window start, Unix ms, inclusive. Defaults to 0 (no lower bound). */
1733
+ from_ms?: number;
1734
+ /** Window end, Unix ms, inclusive. Defaults to unbounded. */
1735
+ to_ms?: number;
1736
+ /**
1737
+ * Cursor, inclusive — the highest `seq_no` this page may return. Omitted ⇒
1738
+ * start at the newest entry in the window. Pages walk downwards, so this is
1739
+ * the previous page's {@link ActivityReport.next_seq}.
1740
+ */
1741
+ before_seq?: number;
1742
+ /**
1743
+ * Rows returned this page. Clamped server-side to 1–1000 (default 200).
1744
+ *
1745
+ * A page can still be shorter than this (or empty) with a live `next_seq` —
1746
+ * the node's own scan cap can trip first. See {@link ActivityReport.next_seq}.
1747
+ */
1748
+ limit?: number;
1633
1749
  }
1750
+
1634
1751
  /**
1635
- * Suggestion surfaced when the bind-target contact already belongs
1636
- * to another DID. The contract refuses to silently steal the
1637
- * authenticator; the caller must resolve the merge (typically via
1638
- * `merge-profiles`) before re-attempting verify.
1752
+ * Contract-discovery wire shapes.
1753
+ *
1754
+ * Field-for-field mirrors of the node's `contracts.list` and `delegation.check`
1755
+ * JSON-RPC responses (`service::contract_discovery::{ListedContract,
1756
+ * ListContractsResponse}` and `service::grant_check::{GrantRef,
1757
+ * GrantCheckResponse}`). Both methods are session-authenticated plaintext reads
1758
+ * dispatched over `/api/rpc` — the same posture as `token.get-usage` — so the
1759
+ * SDK wrappers return the parsed `result` object directly.
1639
1760
  */
1640
- interface OtpMergeSuggestion {
1641
- existingDid: string;
1642
- currentDid: string;
1643
- email?: string;
1644
- phone?: string;
1645
- channel: OtpChannel;
1761
+ /** The navigable starting points of the discovery funnel. */
1762
+ type ListContractsScope = "core" | "org" | "self";
1763
+ /** Params for `contracts.list` (every field optional; `{}` lists core). */
1764
+ interface ListContractsParams {
1765
+ /** `"core"` (default) | `"org"` | `"self"`. */
1766
+ scope?: ListContractsScope;
1767
+ /** Target org DID (required for scope `"org"`). */
1768
+ org_did?: string;
1769
+ /** The member the agent acts for (required for scope `"org"` / `"self"`). */
1770
+ pii_did?: string;
1771
+ /** Page offset (defaults to 0 server-side). */
1772
+ offset?: number;
1773
+ /** Page size (defaults + clamped server-side). */
1774
+ limit?: number;
1775
+ }
1776
+ /** Contract kind — `"core"` platform system contract, `"tenant"` z-space. */
1777
+ type ContractKind = "core" | "tenant";
1778
+ /** One contract as presented by `contracts.list`. */
1779
+ interface ListedContract {
1780
+ /** Canonical name: `tee:<name>` for core, `z:<tid>:<tail>` for tenant. */
1781
+ name: string;
1782
+ kind: ContractKind;
1783
+ /** Current registered version; `null` when the contract is not registered. */
1784
+ version: string | null;
1785
+ /** Descriptor summary, or empty when no descriptor is published. */
1786
+ summary: string;
1787
+ /** Descriptor tags, or empty. */
1788
+ tags: string[];
1789
+ /** Owning DID: the org DID (org mode) or the member's own DID (self mode). */
1790
+ owner_org_did?: string;
1791
+ /**
1792
+ * Human-facing short name: the trailing segment of `name` (`payroll` from
1793
+ * `z:<tid>:payroll`, `user` from `tee:user`). Present this to people instead
1794
+ * of the full canonical `name`, which remains the dispatch key.
1795
+ */
1796
+ short_name: string;
1797
+ }
1798
+ /** Response body for `contracts.list`. */
1799
+ interface ListContractsResult {
1800
+ scope: string;
1801
+ contracts: ListedContract[];
1802
+ next_offset: number | null;
1803
+ }
1804
+ /** Which standing grant a satisfied/missing entry refers to. */
1805
+ type DelegationGrantKind = "agent_auth" | "user_grant";
1806
+ /** Params for `delegation.check` (the generic capability read). */
1807
+ interface GrantCheckParams {
1808
+ /** The target contract whose requirements are checked. */
1809
+ contract: string;
1810
+ /** The member the agent wants to act for (the subject). */
1811
+ pii_did: string;
1812
+ /** Functions the intended action needs. */
1813
+ functions: string[];
1814
+ /** Org-data scopes the intended action needs. */
1815
+ scopes: string[];
1816
+ }
1817
+ /** One grant requirement — satisfied or missing. */
1818
+ interface DelegationGrantRef {
1819
+ grant: DelegationGrantKind;
1820
+ /** The target contract's canonical name. */
1821
+ contract: string;
1822
+ functions: string[];
1823
+ scopes: string[];
1646
1824
  }
1647
1825
  /**
1648
- * Response returned by `otp-verify`. Mirrors the OTP-verify wire response.
1826
+ * Response for `delegation.check`: the `agent_auth ∩ UserGrant` verdict.
1649
1827
  *
1650
- * - `email` is populated on `channel = "email"` success;
1651
- * `phone` on `channel = "sms"` success. Mutually exclusive on
1652
- * the happy path.
1653
- * - `status` carries `"otp_failed"` / `"otp_expired"` on retry; the
1654
- * happy path leaves it `undefined`.
1655
- * - `mergeSuggestion` is set when the contact-to-bind is already
1656
- * owned by another DID. Wire it into your merge UX.
1828
+ * `disclosed` is `true` only when the agent is registered under `pii_did`, so
1829
+ * org-side status was safe to disclose; `false` yields the uniform,
1830
+ * non-disclosive verdict (`authorised:false, satisfied:[], missing:[]`) that is
1831
+ * byte-invariant to the requested capability (R5 anti-enumeration).
1657
1832
  */
1658
- interface OtpVerifyResult {
1659
- txHash?: string;
1660
- did: string;
1661
- channel: OtpChannel;
1662
- email?: string;
1663
- phone?: string;
1664
- status?: string;
1665
- mergeSuggestion?: OtpMergeSuggestion;
1666
- isNewProfile?: boolean;
1833
+ interface GrantCheckResult {
1834
+ authorised: boolean;
1835
+ disclosed: boolean;
1836
+ satisfied: DelegationGrantRef[];
1837
+ missing: DelegationGrantRef[];
1667
1838
  }
1839
+
1668
1840
  /**
1669
- * Level-1 user-input fields accepted by the slim `user-upsert`. Field names
1670
- * are the on-the-wire names — `submitUserInput` sends this object verbatim,
1671
- * so keys must match the contract exactly (snake_case). The canonical Level-1
1672
- * set is the six fields below; the shape is intentionally open so callers can
1673
- * add provider-specific fields the contract knows how to merge.
1841
+ * T3n Client - Main SDK class
1674
1842
  *
1675
- * `email_address` / `phone_number` are normally bound via the OTP roundtrip
1676
- * before `submitUserInput`, but the contract accepts them directly here too.
1843
+ * Provides a simple interface for establishing secure sessions with T3n nodes.
1844
+ * All cryptographic complexity is handled in WASM components.
1677
1845
  */
1678
- interface UserInputProfile {
1679
- first_name?: string;
1680
- last_name?: string;
1681
- country_of_residence?: string;
1682
- document_issuance_country?: string;
1683
- ssn?: string;
1684
- address?: string;
1685
- email_address?: string;
1686
- phone_number?: string;
1687
- campaign_code?: string;
1688
- role?: string;
1689
- [key: string]: unknown;
1690
- }
1846
+
1691
1847
  /**
1692
- * Input to `T3nClient.submitUserInput`. Maps onto the slim
1693
- * `user-upsert` request shape: `{ profile, organisation_did?,
1694
- * attestations?, keys? }`.
1848
+ * Main T3n SDK Client
1695
1849
  */
1696
- interface SubmitUserInputArgs {
1697
- profile: UserInputProfile;
1698
- organisationDid?: string;
1699
- attestations?: unknown;
1700
- keys?: Record<string, unknown>;
1850
+ declare class T3nClient {
1851
+ private readonly config;
1852
+ private readonly transport;
1701
1853
  /**
1702
- * KYC webhook orphan-attestation flow. When set, the contract
1703
- * skips the email-not-verified gate and only records the
1704
- * attestation if the DID has no profile yet.
1705
- * Most callers should leave this `undefined`.
1854
+ * Resolved node base URL. Snapshotted in the constructor so the
1855
+ * typed contract wrappers (`kycStatus`, `getSelfEthAddress`, …)
1856
+ * can call `getScriptVersion()` against the same host the
1857
+ * transport talks to. Used only by the `script_version: "latest"`
1858
+ * resolution path in {@link executeUserContract}.
1706
1859
  */
1707
- requireExistingUser?: boolean;
1860
+ private readonly effectiveBaseUrl;
1708
1861
  /**
1709
- * Testnet self-admit. When `true`, the contract additionally
1710
- * runs the self-admit side-effect after the profile commit: writes
1711
- * the caller's DID into `idx:_tenants` + `idx:_tenant_quotas` and
1712
- * mints any operator-configured welcome credits. Inspect the
1713
- * `tenantAdmit` field on the response for the outcome.
1714
- *
1715
- * Testnet-only. Production clusters return
1716
- * `tenantAdmit.status = "refused"` with
1717
- * `reason = "not_testnet" | "self_admit_disabled" | "not_eth_derived"`.
1718
- * The profile commit always succeeds regardless of the inner outcome.
1719
- *
1720
- * Most callers should leave this `undefined`.
1862
+ * Server-minted session ID, set by {@link handshake} from the
1863
+ * `Session-Id` response header. `null`
1864
+ * until the handshake completes. Client code cannot set it — a
1865
+ * client-supplied session id is rejected, closing the
1866
+ * session-fixation vector.
1721
1867
  */
1722
- becomeDevTenant?: boolean;
1723
- }
1724
- /**
1725
- * Testnet self-admit projection from `user-upsert`. Present only
1726
- * when the caller set `becomeDevTenant: true` on the request.
1727
- *
1728
- * - `status: "admitted"` — first call for this DID; tenant record
1729
- * committed and (if configured) welcome credits minted into
1730
- * `grantedCredits`.
1731
- * - `status: "already-admitted"` — replay; idempotent no-op.
1732
- * - `status: "refused"` — the cluster declined the self-admit;
1733
- * `reason` is the machine-readable cause (`not_testnet`,
1734
- * `self_admit_disabled`, `not_eth_derived`), `detail` is a
1735
- * human-readable string.
1736
- */
1737
- type TenantAdmitStatus = "admitted" | "already-admitted" | "refused";
1738
- interface TenantAdmitProjection {
1739
- status: TenantAdmitStatus;
1740
- grantedCredits?: string;
1741
- reason?: string;
1742
- detail?: string;
1743
- }
1744
- /**
1745
- * Response shape returned by the slim `user-upsert`. Carries the
1746
- * post-merge tx hash plus the Level-1 merge diagnostics
1747
- * (`refusedFields`, `mergeSuggestion`) the pre-2.0.0 omnibus
1748
- * `UpsertResponse` already surfaced.
1749
- */
1750
- interface SubmitUserInputResult {
1751
- txHash?: string;
1752
- refusedFields?: string[];
1753
- mergeSuggestion?: OtpMergeSuggestion;
1754
- userFound?: boolean;
1868
+ private sessionId;
1755
1869
  /**
1756
- * Testnet self-admit projection. Present only when the caller
1757
- * set `becomeDevTenant: true` on the request.
1758
- */
1759
- tenantAdmit?: TenantAdmitProjection;
1760
- }
1761
- /**
1762
- * Discriminator for {@link UserUpsertError}. Mirrors the
1763
- * `UserUpsertError` wire enum and its `<code>:<detail>` wire
1764
- * format. Branch with a `switch` over `kind`.
1765
- *
1766
- * - `EmailNotVerified` — the slim `user-upsert` was called against
1767
- * a DID that has no verified email and no proving authenticator.
1768
- * Run `otpRequest` + `otpVerify` first (or accept an
1769
- * OIDC/Email-authed session).
1770
- * - `LegacyField` — caller passed a pre-2.0.0 dispatch field
1771
- * (`otp_code` to a non-verify export, or
1772
- * `keys.generic_api.otp_channel` anywhere). Migrate the call
1773
- * site to the new explicit functions.
1774
- * - `UserNotFound` — `requireExistingUser` was set but no profile
1775
- * exists for the DID. The attestation is recorded for audit;
1776
- * no profile created.
1777
- */
1778
- type UserUpsertErrorKind = "EmailNotVerified" | "LegacyField" | "UserNotFound";
1779
- /**
1780
- * Typed wrapper for the `<code>:<detail>` errors the slim
1781
- * `user-upsert` and the OTP entry points emit. `kind` is the
1782
- * structured discriminator the SDK derives from the error code
1783
- * prefix; `code` and `detail` retain the wire components for
1784
- * fall-through logging.
1785
- *
1786
- * Throw site: `T3nClient.submitUserInput` (and friends) when the
1787
- * contract returns a string error matching the
1788
- * `<code>:<detail>` shape.
1789
- */
1790
- declare class UserUpsertError extends T3nError {
1791
- readonly kind: UserUpsertErrorKind | "Unknown";
1792
- readonly detail: string;
1793
- constructor(code: string, detail: string);
1794
- /**
1795
- * Try to parse a contract error string into a `UserUpsertError`.
1796
- * Returns `null` if `raw` doesn't match the `<code>:<detail>`
1797
- * shape — caller falls back to a generic error.
1798
- */
1799
- static fromWire(raw: string): UserUpsertError | null;
1800
- }
1801
-
1802
- /**
1803
- * Token-metering wire shapes.
1804
- *
1805
- * Mirrors the token-metering wire contract. `u128` fields land on the
1806
- * wire as JSON numbers (same convention as the existing
1807
- * `token.get-balance` response) — JS clients with histories that
1808
- * exceed 2⁵³ tokens should switch to a streaming JSON parser; the
1809
- * common case fits in `number` losslessly.
1810
- */
1811
- /**
1812
- * The token `BalanceRow` wire shape — caller's credit row.
1813
- *
1814
- * `available` and `reserved` are `u128` on the server; the wire
1815
- * format is a JSON number. Callers should not assume bigint until
1816
- * the SDK migrates to a streaming parser (tracked separately).
1817
- *
1818
- * ⚠️ Amounts are in **base units** (`1 token = `
1819
- * {@link BASE_UNITS_PER_TOKEN}), not whole tokens. Use
1820
- * {@link formatTokens} to display them.
1821
- */
1822
- interface BalanceRow {
1823
- /** Spendable balance, in base units (see {@link formatTokens}). */
1824
- available: number;
1825
- /** Reserved balance, in base units. */
1826
- reserved: number;
1827
- last_settled_seq_no: number;
1828
- version: number;
1829
- credit_exhausted: boolean;
1830
- }
1831
- /**
1832
- * The token-tx-kind wire alphabet (snake_case). Every
1833
- * value listed here is accepted by the server-side
1834
- * `token.get-usage` `kinds` filter.
1835
- */
1836
- type TokenTxKind = "mint" | "burn" | "charge" | "transfer" | "bridge_mint_attest" | "bridge_burn_attest";
1837
- /**
1838
- * Per-caller view direction. `"in"` = caller's balance went up;
1839
- * `"out"` = caller's balance went down. Derived host-side from
1840
- * `(caller_did, tx.src, tx.dst)`; the same `seq_no` appears in both
1841
- * parties' usage feeds with opposite directions on a transfer.
1842
- */
1843
- type Direction = "in" | "out";
1844
- /**
1845
- * Discriminated union mirroring the charge-reason wire union.
1846
- * Present only when the row's `kind === "charge"`.
1847
- */
1848
- type ChargeReason = {
1849
- kind: "contract_register";
1850
- script_name: string;
1851
- version: string;
1852
- } | {
1853
- kind: "invocation";
1854
- script_name: string;
1855
- function: string;
1856
- fuel_consumed: number;
1857
- fuel_tokens: number;
1858
- host_call_count: number;
1859
- host_call_tokens: number;
1860
- } | {
1861
- kind: "kv_bytes";
1862
- map: string;
1863
- } | {
1864
- kind: "cas_bytes";
1865
- backend: string;
1866
- } | {
1867
- kind: "outbox_egress";
1868
- upstream: string;
1869
- };
1870
- /**
1871
- * One row in the caller's usage feed — a per-caller projection of
1872
- * the underlying `TokenTx`. `counterparty` is the other party from
1873
- * the caller's perspective: `tx.dst` on outbound entries, `tx.src`
1874
- * on inbound. `null` when the underlying tx has no counterparty
1875
- * (mints have no `src`; burns and charges have no `dst`).
1876
- */
1877
- interface UsageEntry {
1878
- seq_no: number;
1879
- kind: TokenTxKind;
1880
- /** Amount moved, in base units (`1 token = `{@link BASE_UNITS_PER_TOKEN}); see {@link formatTokens}. */
1881
- amount: number;
1882
- timestamp_ms: number;
1883
- direction: Direction;
1884
- counterparty?: string | null;
1885
- reason?: ChargeReason | null;
1886
- note?: string | null;
1887
- }
1888
- /**
1889
- * Response shape of `token.get-usage` — caller's balance plus a
1890
- * paginated slice of their most-recent `token:tx_log` entries.
1891
- *
1892
- * `next_cursor` is the inclusive upper-bound `seq_no` to pass back
1893
- * as `after_seq` to fetch the next page. `null` (or absent) means
1894
- * the caller's history is fully drained.
1895
- */
1896
- interface UsagePage {
1897
- balance: BalanceRow;
1898
- entries: UsageEntry[];
1899
- next_cursor?: number | null;
1900
- }
1901
- /**
1902
- * Request shape — all fields optional. `limit` clamps to
1903
- * `1..=200` server-side; out-of-range values snap silently to the
1904
- * bounds. `kinds: []` is treated as "no filter".
1905
- */
1906
- interface GetUsageOptions {
1907
- limit?: number;
1908
- after_seq?: number;
1909
- kinds?: TokenTxKind[];
1910
- }
1911
-
1912
- /**
1913
- * Tenant audit-event wire shapes.
1914
- *
1915
- * Mirrors `tenant_types::AuditEvent` and the `audit.get-mine` response
1916
- * (`service::tenant_logs::{AuditBatch, AuditPage}`). A tenant contract
1917
- * emits an audit event via the `logging::audit` host call; the host
1918
- * stamps the identity fields (`subject` / `actor` / `vc_id`) from the
1919
- * verified dispatch context, so a contract can never forge who acted or
1920
- * on whom. Events are permanent (encrypted, append-only) and scoped to a
1921
- * user — distinct from the evicting debug ring read via `getContractLogs`.
1922
- */
1923
- /**
1924
- * One host-stamped audit event. `subject` / `actor` are canonical DID
1925
- * strings. On a self-call `actor === subject` and `vc_id` is `null`; on a
1926
- * delegated call `actor` is the agent and `vc_id` is the delegation
1927
- * credential. The remaining fields are supplied verbatim by the contract.
1928
- */
1929
- interface AuditEvent {
1930
- /** Cluster-deterministic flush timestamp (ms). */
1931
- ts_ms: number;
1932
- /** The user whose data the call touched (host-stamped `pii_did`). */
1933
- subject: string;
1934
- /** The agent (delegated) or user (self-call) who acted (host-stamped). */
1935
- actor: string;
1936
- /** Delegation credential id on a delegated call; `null` on a self-call. */
1937
- vc_id?: string | null;
1938
- /** Contract-supplied: what happened, e.g. `"kyc.approve"`. */
1939
- action: string;
1940
- /** Contract-supplied: what it acted on, e.g. `"user-profile"`. */
1941
- target: string;
1942
- /** Contract-supplied: the result, e.g. `"success"` / `"denied"`. */
1943
- outcome: string;
1944
- /** Contract-supplied: optional free-text / JSON detail. */
1945
- details?: string | null;
1946
- }
1947
- /**
1948
- * One archived batch — the events committed in a single tenant dispatch.
1949
- * Every event in a batch shares the same `subject` / `actor` / `vc_id`.
1950
- */
1951
- interface AuditBatch {
1952
- /** Hex of the archive key — usable directly as `cursor` for the next page. */
1953
- key: string;
1954
- /**
1955
- * Host-stamped: did the emitting dispatch's contract transaction
1956
- * commit? `false` means the call rolled back or trapped, so an event's
1957
- * `outcome: "success"` in this batch is the contract's *claim*, not a
1958
- * committed fact — filter on this when you need only durable events.
1959
- */
1960
- committed: boolean;
1961
- events: AuditEvent[];
1962
- }
1963
- /**
1964
- * `audit.get-mine` response — a page of audit batches, newest scan order.
1965
- * `next_cursor` is present (a key hex) when more batches remain; `null`
1966
- * once the scan reaches the end.
1967
- */
1968
- interface AuditPage {
1969
- batches: AuditBatch[];
1970
- next_cursor?: string | null;
1971
- }
1972
- /**
1973
- * Request shape for {@link T3nClient.getAuditEvents} — all fields
1974
- * optional. Omit `pii_did` to read your own trail (all actors); set it to
1975
- * another user's DID to read, as a delegated agent, the events you
1976
- * performed for them — admitted only while that user's agent-auth grant
1977
- * to you is live. `cursor` is the `next_cursor` from a prior page.
1978
- */
1979
- interface GetAuditEventsOptions {
1980
- pii_did?: string;
1981
- limit?: number;
1982
- cursor?: string;
1983
- }
1984
-
1985
- /**
1986
- * Agent-activity audit-log wire shapes (the node's `auditlog` RPC).
1987
- *
1988
- * Mirrors `service::activity_audit::{ActivityReport, ReportEntry}` and
1989
- * `primitives::audit_log::AuditLogEntry`. One entry per audited contract
1990
- * dispatch — who called, for whom, which contract + function, and how it
1991
- * ended. Entries are reconstructed from the append-only ledger on read, so
1992
- * `seq_no` (the ledger index) and `hash` are derived server-side rather than
1993
- * stored with the record.
1994
- *
1995
- * Scope is the caller's **own organisation**, resolved node-side from the
1996
- * session DID: there is no scope parameter, and a page carries **every
1997
- * member's** activity in that org, not just the caller's own. Metadata only —
1998
- * DIDs, never display names, call arguments, or payloads.
1999
- */
2000
- /**
2001
- * Whether the actor is a registered agent or a human / self principal.
2002
- * Decided node-side by an existence check on the actor DID in the agent
2003
- * registry — never inferred from the DID's shape.
2004
- */
2005
- type ActivityCallerType = "agent" | "human";
2006
- /**
2007
- * Host-stamped outcome of an audited dispatch.
2008
- *
2009
- * - `success` — the business transaction committed.
2010
- * - `denied` — authorisation refused the call.
2011
- * - `error` — the call was allowed but failed / rolled back.
2012
- */
2013
- type ActivityOutcome = "success" | "denied" | "error";
2014
- /** One audited call. */
2015
- interface ActivityEntry {
2016
- /**
2017
- * Ledger index of the entry — its unique, ordered id. Use it as the row key
2018
- * and as the ordering key: it is monotonic, whereas {@link timestamp_ms} is
2019
- * per-node wall clock.
2020
- */
2021
- seq_no: number;
2022
- /** Hex SHA-256 of the stored entry (64 chars) — read-time tamper evidence. */
2023
- hash: string;
2024
- /**
2025
- * Call time in Unix ms, stamped on the node that took the request. NOT a
2026
- * cluster-assigned time, so entries from different nodes can be skewed by
2027
- * their clock offset — order by {@link seq_no}, not by this.
2028
- */
2029
- timestamp_ms: number;
2030
- /** Agent vs human, from the agent-registry check on {@link actor}. */
2031
- caller_type: ActivityCallerType;
2032
- /** DID that actually invoked the contract. */
2033
- actor: string;
2034
- /**
2035
- * DID of the owner the caller acted for. Equals {@link actor} on a self /
2036
- * own-authority call — never null.
2037
- */
2038
- on_behalf_of: string;
2039
- /**
2040
- * Organisation the acting principal belongs to — the report's scope key, so
2041
- * it is identical on every row of a page. Falls back to `on_behalf_of` when
2042
- * that principal is in no organisation.
2043
- */
2044
- org: string;
2045
- /** Contract that ran, e.g. `tee:user/contracts`. */
2046
- contract: string;
2047
- /** Contract function invoked, e.g. `user-upsert`. */
2048
- function: string;
2049
- /** success / denied / error — host-stamped from the dispatch result. */
2050
- outcome: ActivityOutcome;
2051
- /**
2052
- * Role ids the acting authority carried at call time: the actor's role in
2053
- * the organisation on a self-call, the roles the owner granted the agent on
2054
- * a delegated call. Omitted when the authority carried no role (direct
2055
- * grants, an individual, or an entry recorded before roles were captured).
2056
- * On a `denied` entry this is the caller's *claimed* authority, not a
2057
- * validated one.
2058
- */
2059
- roles?: string[];
2060
- }
2061
- /**
2062
- * One page of the organisation's activity report — **newest first**, i.e.
2063
- * descending `seq_no`.
2064
- */
2065
- interface ActivityReport {
2066
- entries: ActivityEntry[];
2067
- /**
2068
- * Cursor to resume from — pass it back as
2069
- * {@link GetActivityLogOptions.before_seq}. `null` once the requested window
2070
- * is exhausted.
2071
- *
2072
- * A live cursor with **fewer rows than `limit`, or none at all**, is normal:
2073
- * the node also caps how much ledger one call decrypts, and that cap can trip
2074
- * before the window ends. Page until this is `null`, never on a short or
2075
- * empty page.
2076
- */
2077
- next_seq: number | null;
2078
- }
2079
- /** Params for one activity-report page. All optional; `{}` is valid. */
2080
- interface GetActivityLogOptions {
2081
- /** Window start, Unix ms, inclusive. Defaults to 0 (no lower bound). */
2082
- from_ms?: number;
2083
- /** Window end, Unix ms, inclusive. Defaults to unbounded. */
2084
- to_ms?: number;
2085
- /**
2086
- * Cursor, inclusive — the highest `seq_no` this page may return. Omitted ⇒
2087
- * start at the newest entry in the window. Pages walk downwards, so this is
2088
- * the previous page's {@link ActivityReport.next_seq}.
2089
- */
2090
- before_seq?: number;
2091
- /**
2092
- * Rows returned this page. Clamped server-side to 1–1000 (default 200).
2093
- *
2094
- * A page can still be shorter than this (or empty) with a live `next_seq` —
2095
- * the node's own scan cap can trip first. See {@link ActivityReport.next_seq}.
2096
- */
2097
- limit?: number;
2098
- }
2099
-
2100
- /**
2101
- * Contract-discovery wire shapes.
2102
- *
2103
- * Field-for-field mirrors of the node's `contracts.list` and `delegation.check`
2104
- * JSON-RPC responses (`service::contract_discovery::{ListedContract,
2105
- * ListContractsResponse}` and `service::grant_check::{GrantRef,
2106
- * GrantCheckResponse}`). Both methods are session-authenticated plaintext reads
2107
- * dispatched over `/api/rpc` — the same posture as `token.get-usage` — so the
2108
- * SDK wrappers return the parsed `result` object directly.
2109
- */
2110
- /** The navigable starting points of the discovery funnel. */
2111
- type ListContractsScope = "core" | "org" | "self";
2112
- /** Params for `contracts.list` (every field optional; `{}` lists core). */
2113
- interface ListContractsParams {
2114
- /** `"core"` (default) | `"org"` | `"self"`. */
2115
- scope?: ListContractsScope;
2116
- /** Target org DID (required for scope `"org"`). */
2117
- org_did?: string;
2118
- /** The member the agent acts for (required for scope `"org"` / `"self"`). */
2119
- pii_did?: string;
2120
- /** Page offset (defaults to 0 server-side). */
2121
- offset?: number;
2122
- /** Page size (defaults + clamped server-side). */
2123
- limit?: number;
2124
- }
2125
- /** Contract kind — `"core"` platform system contract, `"tenant"` z-space. */
2126
- type ContractKind = "core" | "tenant";
2127
- /** One contract as presented by `contracts.list`. */
2128
- interface ListedContract {
2129
- /** Canonical name: `tee:<name>` for core, `z:<tid>:<tail>` for tenant. */
2130
- name: string;
2131
- kind: ContractKind;
2132
- /** Current registered version; `null` when the contract is not registered. */
2133
- version: string | null;
2134
- /** Descriptor summary, or empty when no descriptor is published. */
2135
- summary: string;
2136
- /** Descriptor tags, or empty. */
2137
- tags: string[];
2138
- /** Owning DID: the org DID (org mode) or the member's own DID (self mode). */
2139
- owner_org_did?: string;
2140
- /**
2141
- * Human-facing short name: the trailing segment of `name` (`payroll` from
2142
- * `z:<tid>:payroll`, `user` from `tee:user`). Present this to people instead
2143
- * of the full canonical `name`, which remains the dispatch key.
2144
- */
2145
- short_name: string;
2146
- }
2147
- /** Response body for `contracts.list`. */
2148
- interface ListContractsResult {
2149
- scope: string;
2150
- contracts: ListedContract[];
2151
- next_offset: number | null;
2152
- }
2153
- /** Which standing grant a satisfied/missing entry refers to. */
2154
- type DelegationGrantKind = "agent_auth" | "org_grant";
2155
- /** Params for `delegation.check` (the generic capability read). */
2156
- interface GrantCheckParams {
2157
- /** The target contract whose requirements are checked. */
2158
- contract: string;
2159
- /** The member the agent wants to act for (the subject). */
2160
- pii_did: string;
2161
- /** Functions the intended action needs. */
2162
- functions: string[];
2163
- /** Org-data scopes the intended action needs. */
2164
- scopes: string[];
2165
- }
2166
- /** One grant requirement — satisfied or missing. */
2167
- interface DelegationGrantRef {
2168
- grant: DelegationGrantKind;
2169
- /** The target contract's canonical name. */
2170
- contract: string;
2171
- functions: string[];
2172
- scopes: string[];
2173
- }
2174
- /**
2175
- * Response for `delegation.check`: the `agent_auth ∩ org_grant` verdict.
2176
- *
2177
- * `disclosed` is `true` only when the agent is registered under `pii_did`, so
2178
- * org-side status was safe to disclose; `false` yields the uniform,
2179
- * non-disclosive verdict (`authorised:false, satisfied:[], missing:[]`) that is
2180
- * byte-invariant to the requested capability (R5 anti-enumeration).
2181
- */
2182
- interface GrantCheckResult {
2183
- authorised: boolean;
2184
- disclosed: boolean;
2185
- satisfied: DelegationGrantRef[];
2186
- missing: DelegationGrantRef[];
2187
- }
2188
-
2189
- /**
2190
- * T3n Client - Main SDK class
2191
- *
2192
- * Provides a simple interface for establishing secure sessions with T3n nodes.
2193
- * All cryptographic complexity is handled in WASM components.
2194
- */
2195
-
2196
- /**
2197
- * Main T3n SDK Client
2198
- */
2199
- declare class T3nClient {
2200
- private readonly config;
2201
- private readonly transport;
2202
- /**
2203
- * Resolved node base URL. Snapshotted in the constructor so the
2204
- * typed contract wrappers (`kycStatus`, `getSelfEthAddress`, …)
2205
- * can call `getContractVersion()` against the same host the
2206
- * transport talks to. Used only by the `contract_version: "latest"`
2207
- * resolution path in {@link executeUserContract}.
2208
- */
2209
- private readonly effectiveBaseUrl;
2210
- /**
2211
- * Server-minted session ID, set by {@link handshake} from the
2212
- * `Session-Id` response header. `null`
2213
- * until the handshake completes. Client code cannot set it — a
2214
- * client-supplied session id is rejected, closing the
2215
- * session-fixation vector.
2216
- */
2217
- private sessionId;
2218
- /**
2219
- * Set by {@link sendRpcRequest} when an `auth.handshake` RPC is
2220
- * actually issued. Decouples the "flow completed without talking
2221
- * to a server" case (unit-test mocks that only exercise handler
2222
- * delegation) from the real "server must mint the id" invariant:
2223
- * we only enforce the mint requirement when a round-trip happened.
1870
+ * Set by {@link sendRpcRequest} when an `auth.handshake` RPC is
1871
+ * actually issued. Decouples the "flow completed without talking
1872
+ * to a server" case (unit-test mocks that only exercise handler
1873
+ * delegation) from the real "server must mint the id" invariant:
1874
+ * we only enforce the mint requirement when a round-trip happened.
2224
1875
  */
2225
1876
  private handshakeSentRpc;
2226
1877
  private readonly logger;
@@ -2402,7 +2053,7 @@ declare class T3nClient {
2402
2053
  * Generic capability check (`delegation.check`) — the
2403
2054
  * node-backed source for the MCP `checkDelegation` funnel tool.
2404
2055
  *
2405
- * Returns the `agent_auth ∩ org_grant` verdict for `(agent, contract,
2056
+ * Returns the `agent_auth ∩ UserGrant` verdict for `(agent, contract,
2406
2057
  * pii_did)`: whether the acting agent (resolved from the session) holds the
2407
2058
  * standing grants that `contract`'s `functions` / `scopes` need for member
2408
2059
  * `pii_did`. The org half is vacuous for no-org (Individual-owned) targets,
@@ -2641,10 +2292,10 @@ declare class T3nClient {
2641
2292
  * (org-admin gated; idempotent on an already-absent membership). The host
2642
2293
  * membership gate makes the detach effective immediately.
2643
2294
  * 2. `org-remove-member-grants` — sweep the member from the org's
2644
- * per-contract `BoundGrant` lists, so the capability does not silently
2295
+ * per-contract `UserGrant` lists, so the capability does not silently
2645
2296
  * reactivate if the member later rejoins.
2646
2297
  *
2647
- * The member's `agent_auth` delegations are self-scoped (the agent-auth edge in `ROLE_ASSIGNMENTS_MAP` is a
2298
+ * The member's `agent_auth` delegations are self-scoped (`AGENT_AUTH_MAP` is a
2648
2299
  * per-user document an admin cannot reach), so this cannot sweep them; the host
2649
2300
  * membership gate denies them regardless, and the member's own session can run
2650
2301
  * {@link revokeAgentAuthForOrg} for full cleanup.
@@ -2675,7 +2326,7 @@ declare class T3nClient {
2675
2326
  * Revoke the caller's own agent delegations scoped to one org
2676
2327
  * (detach-cascade `agent_auth` half). Dispatches
2677
2328
  * `agent-auth-revoke-org` on `tee:user/contracts` (**SelfOnly**): every
2678
- * agent-edge grant targeting a `z:<orgTid>:*` contract is removed from the
2329
+ * `ScriptGrant` targeting a `z:<orgTid>:*` contract is removed from the
2679
2330
  * caller's own agent-auth document.
2680
2331
  *
2681
2332
  * @param orgTid - the org's z-space tenant id (`did:t3n:<hex>` or bare
@@ -2687,27 +2338,25 @@ declare class T3nClient {
2687
2338
  * grants delegated to agents. Dispatches `agent-auth-get` on
2688
2339
  * `tee:authorisations/contracts` (the policy's owning contract), which is
2689
2340
  * **SelfOnly**, so this always returns the caller's own
2690
- * agent-auth edge in `ROLE_ASSIGNMENTS_MAP`.
2341
+ * `AGENT_AUTH_MAP[self]` document.
2691
2342
  *
2692
- * @returns the full policy document as the flat snake_case wire shape: the
2693
- * `grants` list (each row's `grantee` is the authorised agent DID) plus the
2694
- * document-level `discover_dids` discovery grants
2343
+ * @returns the full policy document (normalised to the camelCase write
2344
+ * shape): the per-agent `agents` entries plus the document-level
2345
+ * `discoverDids` discovery grants
2695
2346
  * @throws if the session is not authenticated, or the contract refuses
2696
2347
  */
2697
- getAgentAuth(): Promise<AgentAuthDoc>;
2348
+ getAgentAuth(): Promise<AgentAuthPolicy>;
2698
2349
  /**
2699
2350
  * Authorise an agent for one contract on the caller's own behalf
2700
2351
  * (envelope-free authorisation). Read-merge-writes the
2701
- * caller's agent-auth edge in `ROLE_ASSIGNMENTS_MAP` via `agent-auth-update`
2702
- * (**SelfOnly**) with `(grantee, contract_id)` union semantics, so other
2703
- * contracts' grants for this or any agent survive untouched.
2352
+ * caller's `AGENT_AUTH_MAP[self]` document via `agent-auth-update`
2353
+ * (**SelfOnly**) with script-level union semantics, so other contracts'
2354
+ * grants for this or any agent survive untouched.
2704
2355
  *
2705
- * The grant is the flat wire {@link BoundGrant}: its `grantee` is the agent
2706
- * DID being authorised, and it carries `functions`, the delegated org-data
2707
- * `scopes`, direct-read `read_scopes`, egress `allowed_hosts`, an optional
2708
- * semver `version_req`, and an optional validity `window`. The ≤ cap *length*
2709
- * check is enforced contract-side at write time; the expiry gate is host-side
2710
- * at read time.
2356
+ * Carries the new `scopes` + validity fields: the delegated
2357
+ * org-data scopes and an optional `[validFromSecs, validUntilSecs]`
2358
+ * window. The ≤ cap *length* check is enforced contract-side at write
2359
+ * time; the expiry gate is host-side at read time.
2711
2360
  *
2712
2361
  * This is the write surface `getDelegationInstructions` produces the
2713
2362
  * parameters for. The caller MUST be the delegating user, authenticated as
@@ -2719,38 +2368,38 @@ declare class T3nClient {
2719
2368
  * standing discovery), and any `options.discoverDids` are unioned in
2720
2369
  * (order-preserving, deduplicated).
2721
2370
  *
2722
- * @param grant - the single grant to set — a {@link BoundGrant} whose
2723
- * `grantee` is the agent DID being authorised (contract_id, functions,
2724
- * scopes, window, egress hosts)
2371
+ * @param agentDid - the agent DID being authorised
2372
+ * @param grant - the single script grant to set (contract, functions,
2373
+ * scopes, validity, egress hosts)
2725
2374
  * @param options - optional `discoverDids` to union into the document's
2726
2375
  * discovery grants (org DIDs for org-mode `listContracts`, the caller's
2727
2376
  * own DID for self mode)
2728
- * @returns the grant rows preserved from the existing policy (audit aid)
2377
+ * @returns the script rows preserved from the existing policy (audit aid)
2729
2378
  * @throws if the session is not authenticated, or the contract refuses
2730
2379
  */
2731
- updateAgentAuth(grant: BoundGrant, options?: {
2380
+ updateAgentAuth(agentDid: string, grant: AgentAuthScriptGrant, options?: {
2732
2381
  discoverDids?: string[];
2733
2382
  }): Promise<{
2734
2383
  preservedRows: string[];
2735
2384
  }>;
2736
2385
  /**
2737
2386
  * Build the canonical `ExecuteActionRequest` shape the server
2738
- * expects (`contract_id`, `contract_version`, `function_name`, `input`,
2387
+ * expects (`script_name`, `script_version`, `function_name`, `input`,
2739
2388
  * optional `pii_did`) and dispatch it through {@link execute}.
2740
2389
  *
2741
2390
  * Two pieces of glue live here that every typed user-contract
2742
2391
  * wrapper would otherwise duplicate:
2743
2392
  *
2744
2393
  * 1. **Field naming.** The server deserialises strictly into
2745
- * `contract_id` / `contract_version` / `function_name` —
2394
+ * `script_name` / `script_version` / `function_name` —
2746
2395
  * sending `contract` / `version` / `function` produces
2747
2396
  * `Invalid action request: missing field …` 400s. Centralising
2748
2397
  * the names here means every wrapper agrees with the server.
2749
- * 2. **`"latest"` resolution.** `contract_version` is `SemVer` on
2398
+ * 2. **`"latest"` resolution.** `script_version` is `SemVer` on
2750
2399
  * the server, so a literal `"latest"` cannot be parsed. We
2751
2400
  * fetch the registered current version via
2752
2401
  * `GET /api/contracts/current?name=…` (cached per script name
2753
- * in `getContractVersion`) and forward the resolved
2402
+ * in `getScriptVersion`) and forward the resolved
2754
2403
  * `MAJOR.MINOR.PATCH` string.
2755
2404
  *
2756
2405
  * Wrappers that need PII delegation can extend this helper
@@ -3015,24 +2664,25 @@ declare class T3nClient {
3015
2664
  */
3016
2665
  submitUserInput(input: SubmitUserInputArgs): Promise<SubmitUserInputResult>;
3017
2666
  /**
3018
- * Replace this user's agent-authorisation policy (`tee:authorisations/contracts`
3019
- * → `agent-auth-update`). The supplied document IS the new state: an empty
3020
- * `grants` array revokes all agent access, and an empty `discover_dids`
2667
+ * Replace this user's agent-authorisation policy (`tee:user/contracts` →
2668
+ * `agent-auth-update`). The supplied document IS the new state: an empty
2669
+ * `agents` array revokes all agent access, and an omitted `discoverDids`
3021
2670
  * persists an empty discovery-grant list. This is the full-document
3022
2671
  * write — use {@link T3nClient.updateAgentAuth} for the single-grant
3023
2672
  * read-merge-write that preserves other contracts' grants and the
3024
2673
  * standing discovery grants.
3025
2674
  *
3026
- * The {@link AgentAuthDoc} IS the snake_case wire shape — grant rows are
3027
- * {@link BoundGrant} verbatim — so the document passes straight through with
3028
- * no casing transform. Absent per-grant qualifiers (`version_req` /
3029
- * `read_scopes` / `allowed_hosts` / `window`) are simply unset on the object
3030
- * and so omitted from the JSON.
2675
+ * Typed wrapper over the raw contract call: callers pass camelCase input;
2676
+ * the SDK emits the canonical snake_case wire via
2677
+ * {@link toAgentAuthUpdateWire} (carrying `scopes` / `read_scopes` /
2678
+ * validity alongside `functions` / `allowed_hosts`, plus the
2679
+ * document-level `discover_dids`), so it does not rely on the contract's
2680
+ * compatibility aliases.
3031
2681
  *
3032
2682
  * @throws {RpcError} if the contract rejects the policy (validation failure,
3033
2683
  * too many agents/grants).
3034
2684
  */
3035
- agentAuthUpdate(input: AgentAuthDoc): Promise<void>;
2685
+ agentAuthUpdate(input: AgentAuthUpdateInput): Promise<void>;
3036
2686
  /**
3037
2687
  * Convenience helper: run the explicit OTP roundtrip and submit
3038
2688
  * the slim user-upsert in one call.
@@ -3182,283 +2832,661 @@ declare class T3nClient {
3182
2832
  */
3183
2833
  private sendUnencryptedSessionRpc;
3184
2834
  /**
3185
- * Send a session-authenticated JSON-RPC request whose params/result
3186
- * are sealed with the same {@link SessionEncryption} layer
3187
- * `action.execute` uses — for read endpoints that return PII
3188
- * (`audit.get-mine`) and therefore must not travel plaintext over
3189
- * TLS. Unlike {@link sendRpcRequest}, this is not tied to the WASM
3190
- * client `Method` state machine: it takes the raw RPC method string
3191
- * and only does encrypt → send → decrypt.
3192
- *
3193
- * Requires an established (>= Encrypted) session; returns the
3194
- * decrypted plaintext response string for the caller to `JSON.parse`.
2835
+ * Send a session-authenticated JSON-RPC request whose params/result
2836
+ * are sealed with the same {@link SessionEncryption} layer
2837
+ * `action.execute` uses — for read endpoints that return PII
2838
+ * (`audit.get-mine`) and therefore must not travel plaintext over
2839
+ * TLS. Unlike {@link sendRpcRequest}, this is not tied to the WASM
2840
+ * client `Method` state machine: it takes the raw RPC method string
2841
+ * and only does encrypt → send → decrypt.
2842
+ *
2843
+ * Requires an established (>= Encrypted) session; returns the
2844
+ * decrypted plaintext response string for the caller to `JSON.parse`.
2845
+ */
2846
+ private sendEncryptedSessionRpc;
2847
+ /**
2848
+ * Inspect a JSON-RPC response for an `error` field and throw the
2849
+ * appropriate typed exception. No-op when `response.error` is
2850
+ * absent. Shared by every RPC path so wire-shape changes in the
2851
+ * server's error envelope (typed-error subclasses, request-id
2852
+ * placement, detail formatting) only need to land in one place.
2853
+ *
2854
+ * JSON-RPC `error.message` is the generic category string
2855
+ * ("Invalid params", "Internal error", …). The node attaches the
2856
+ * actionable text and per-request correlation id in `error.data`.
2857
+ * Extract both so callers (and toasts that only render `.message`)
2858
+ * get the real reason plus an id an operator can grep in the logs.
2859
+ *
2860
+ * Chargepoint denials surface as a typed
2861
+ * `InsufficientCreditError` so frontends can branch on
2862
+ * `instanceof` to render an "out of credit" UI without
2863
+ * prefix-matching the message themselves. The wire format is stable.
2864
+ */
2865
+ private throwIfRpcError;
2866
+ private sendMultipartRpcRequest;
2867
+ /**
2868
+ * Capture the server-minted `Session-Id` from the last handshake
2869
+ * response headers. Validates shape so a
2870
+ * broken or MITM'd response fails loudly instead of leaving a
2871
+ * garbage value in the client. Idempotent: only the first valid
2872
+ * mint per session is honoured — subsequent handshake RPC legs
2873
+ * (none exist today, but the state-machine loop can iterate) do
2874
+ * not overwrite an already-set value.
2875
+ */
2876
+ private captureMintedSessionId;
2877
+ /**
2878
+ * Get the finalized session blob (for `session.encrypt` calls).
2879
+ * Populated by `tryFinalize` once the handshake state machine
2880
+ * reaches its terminal phase.
2881
+ */
2882
+ private getSessionState;
2883
+ }
2884
+
2885
+ /**
2886
+ * Guest-to-Host Request Handlers
2887
+ *
2888
+ * These handle requests from WASM that need the host environment to perform side effects.
2889
+ * Examples: signing challenges, providing public keys, generating random bytes.
2890
+ */
2891
+
2892
+ /**
2893
+ * Account — MetaMask handler accepts either a plain address string or an
2894
+ * object with an `address` field (for compatibility with various wallet
2895
+ * libraries).
2896
+ */
2897
+ type EthAccount = string | {
2898
+ address: string;
2899
+ };
2900
+ /**
2901
+ * Create an EthSign handler using MetaMask (window.ethereum)
2902
+ * @param account - MetaMask account (string address or object with address property)
2903
+ * @param logger - Optional logger instance. Defaults to a logger using the global log level (LogLevel.ERROR).
2904
+ * Pass a custom logger to override logging behavior for this handler.
2905
+ * @param privateKey - Optional private key for signing (if provided, MetaMask is not used)
2906
+ */
2907
+ declare function metamask_sign(account: EthAccount, logger?: Logger, privateKey?: string | undefined): GuestToHostHandler;
2908
+ /**
2909
+ * Get the current MetaMask address
2910
+ * @returns Ethereum address (lowercase, 0x prefixed)
2911
+ */
2912
+ declare function metamask_get_address(): Promise<string>;
2913
+ /**
2914
+ * Get the address for a given private key
2915
+ * @param privateKey - Ethereum private key (0x prefixed hex string)
2916
+ * @returns Ethereum address (lowercase, 0x prefixed)
2917
+ */
2918
+ declare function eth_get_address(privateKey: string): string;
2919
+ /**
2920
+ * Create an MlKemPublicKey handler that lazily fetches the root public key
2921
+ * from `${baseUrl}/status` on first invocation, verifies it against the
2922
+ * DKG attestation trust anchor (SP-003), and caches the encoded response
2923
+ * for subsequent calls.
2924
+ *
2925
+ * @param baseUrl - **Required**. The node URL whose `/status` endpoint should
2926
+ * serve the ML-KEM public key. Must be the same URL the
2927
+ * T3nClient is constructed with — otherwise the handshake
2928
+ * encrypts to one node and sends ciphertext to another.
2929
+ *
2930
+ * Was optional in 0.3.x, where omitting it caused the lazy
2931
+ * fetch to silently fall back to `NODE_URLS[currentEnv]` and
2932
+ * hit the wrong node. Three downstream consumers (demo.ts,
2933
+ * t3-apps dev wallet hooks, t3n-mcp session manager) all
2934
+ * hit this trap before we tightened the type.
2935
+ * @param trustAnchor - **Required**. Client-pinned expected peer IDs +
2936
+ * RTMR3 allowlist the DKG bundle is verified against, or
2937
+ * `{ unsafe_trust_server: true }` to skip verification.
2938
+ * The key is only cached/returned once verification passes.
2939
+ */
2940
+ declare function createMlKemPublicKeyHandler(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandler;
2941
+ /**
2942
+ * Create Random handler backed by crypto.getRandomValues
2943
+ * Note: The Rust Vec<u8> type serializes as an array of bytes, not a base64 string
2944
+ */
2945
+ declare function createRandomHandler(): GuestToHostHandler;
2946
+ /**
2947
+ * Create the default handler set required by the T3n handshake.
2948
+ *
2949
+ * @param baseUrl - **Required**. Forwarded to `createMlKemPublicKeyHandler`
2950
+ * so the lazy /status fetch hits the right node.
2951
+ * @param trustAnchor - **Required**. Forwarded to the ML-KEM handler so the
2952
+ * fetched key is verified against the DKG attestation
2953
+ * (SP-003) before the handshake trusts it.
2954
+ */
2955
+ declare function createDefaultHandlers(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandlers;
2956
+
2957
+ /**
2958
+ * Stateless `api_key` agent auth.
2959
+ *
2960
+ * `invoke` posts once to `POST /api/invoke` — an HTTPS-only
2961
+ * endpoint (see the HTTPS-guard note below) that authenticates an org agent
2962
+ * by an opaque API key (`X-T3N-Api-Key: t3n_key_<...>`) and executes a
2963
+ * `z:` contract as that agent in the SAME request. Unlike
2964
+ * {@link T3nClient.execute}, there is **no** ML-KEM handshake, **no**
2965
+ * `Session-Id`, and **no** session state: the node derives the acting agent
2966
+ * DID from the relayed key per-call (`resolve_stateless_credential`
2967
+ * driving the session contract's `api_key` action), then runs the same
2968
+ * execute pipeline `action.execute` runs after `check_authentication`
2969
+ * (`ActionService::execute_as_did`), and returns the contract's decoded
2970
+ * result as a plain `Json(result)` body — NOT a JSON-RPC envelope.
2971
+ *
2972
+ * Because the response is the bare decoded value (no `{jsonrpc,result,id}`
2973
+ * wrapper to unwrap), decoding reuses {@link parseContractResponse} — the
2974
+ * exact same JSON.parse + optional-schema path {@link T3nClient.executeAndDecode}
2975
+ * uses for the session `execute` RPC — so callers get identical typed /
2976
+ * schema-validated decoding on either path.
2977
+ *
2978
+ * This module intentionally does NOT import {@link T3nClient}, the WASM
2979
+ * component loader, or any handshake/session machinery — `invoke` is
2980
+ * a single fetch, nothing else.
2981
+ *
2982
+ * ### HTTPS guard (CodeRabbit T2)
2983
+ * The API key is a long-lived bearer credential relayed in a plain header,
2984
+ * so `invoke` refuses to send it over an insecure transport: `baseUrl`
2985
+ * must be `https:`, unless the host is a local-dev loopback
2986
+ * (`localhost` / `127.0.0.1` / `[::1]`), in which case plain `http:` is
2987
+ * allowed. The check runs before any network activity — an insecure
2988
+ * `baseUrl` never gets as far as a `fetch` call.
2989
+ *
2990
+ * ### Error hygiene (CodeRabbit T3/T4/T5)
2991
+ * Every error `invoke` throws is a fixed, generic
2992
+ * {@link InvokeError} message — the response body text, the
2993
+ * underlying network error's message, and the api key are never
2994
+ * interpolated into it. This is defense in depth against a server (or a
2995
+ * malicious intermediary) that echoes the key or other secrets back in an
2996
+ * error body: whatever comes back over the wire on a non-2xx response is
2997
+ * discarded, not surfaced. The timeout timer also stays armed until the
2998
+ * response body has been fully read (or has itself timed out) — see
2999
+ * {@link invoke}'s implementation — so a connection that delivers
3000
+ * headers and then stalls on the body still respects `timeoutMs`.
3001
+ */
3002
+
3003
+ /**
3004
+ * Wire body for `POST /api/invoke` — mirrors the server's
3005
+ * server-side `ExecuteActionRequest`, the same shape
3006
+ * `T3nClient`'s `execute*` wrappers build for the session `action.execute`
3007
+ * RPC. Field names are load-bearing: the server deserialises strictly into
3008
+ * `script_name` / `script_version` / `function_name` (see
3009
+ * `T3nClient.executeSystemContract`'s doc comment) — `contract` / `version`
3010
+ * / `function` produce a 400.
3011
+ */
3012
+ interface InvokeRequest {
3013
+ script_name: string;
3014
+ script_version: string;
3015
+ function_name: string;
3016
+ /** Delegated-call target member; omitted for a self (non-delegated) call. */
3017
+ pii_did?: string;
3018
+ input?: unknown;
3019
+ }
3020
+ /** Options for {@link invoke}. */
3021
+ interface InvokeOptions {
3022
+ /**
3023
+ * RPC base URL of the T3n node, e.g. `https://node.example.com`. Must be
3024
+ * `https:` unless the host is a local-dev loopback (`localhost` /
3025
+ * `127.0.0.1` / `[::1]`) — see the module doc comment's HTTPS-guard note.
3195
3026
  */
3196
- private sendEncryptedSessionRpc;
3027
+ baseUrl: string;
3197
3028
  /**
3198
- * Inspect a JSON-RPC response for an `error` field and throw the
3199
- * appropriate typed exception. No-op when `response.error` is
3200
- * absent. Shared by every RPC path so wire-shape changes in the
3201
- * server's error envelope (typed-error subclasses, request-id
3202
- * placement, detail formatting) only need to land in one place.
3203
- *
3204
- * JSON-RPC `error.message` is the generic category string
3205
- * ("Invalid params", "Internal error", …). The node attaches the
3206
- * actionable text and per-request correlation id in `error.data`.
3207
- * Extract both so callers (and toasts that only render `.message`)
3208
- * get the real reason plus an id an operator can grep in the logs.
3209
- *
3210
- * Chargepoint denials surface as a typed
3211
- * `InsufficientCreditError` so frontends can branch on
3212
- * `instanceof` to render an "out of credit" UI without
3213
- * prefix-matching the message themselves. The wire format is stable.
3029
+ * The agent's opaque API key (`t3n_key_<...>`), relayed verbatim in the
3030
+ * `X-T3N-Api-Key` header. Never logged and never interpolated into any
3031
+ * error this module throws — see the module doc comment and
3032
+ * {@link InvokeError}.
3214
3033
  */
3215
- private throwIfRpcError;
3216
- private sendMultipartRpcRequest;
3034
+ apiKey: string;
3035
+ /** The wire request to execute, built to the {@link InvokeRequest} shape. */
3036
+ request: InvokeRequest;
3037
+ /** Fetch timeout in ms. Defaults to 30s, matching {@link HttpTransport}. */
3038
+ timeoutMs?: number;
3039
+ }
3040
+ /**
3041
+ * Thrown when `POST /api/invoke` fails at the transport or HTTP
3042
+ * layer (network failure, timeout, non-2xx status). Contract-level errors
3043
+ * the node returns as a 2xx JSON error value are NOT wrapped here — they
3044
+ * flow through {@link parseContractResponse}'s normal return, same as the
3045
+ * session `execute` path.
3046
+ *
3047
+ * The message is always one of a small set of fixed, generic strings — it
3048
+ * NEVER contains the raw api key, the response body text, or the
3049
+ * underlying network error's message (CodeRabbit T4/T5): a server (or a
3050
+ * misbehaving intermediary) that echoes the key or other secrets back in
3051
+ * an error body must not be able to leak them through this error's
3052
+ * message.
3053
+ */
3054
+ declare class InvokeError extends T3nError {
3055
+ readonly status?: number | undefined;
3056
+ constructor(message: string, status?: number | undefined);
3057
+ }
3058
+ /**
3059
+ * Execute a `z:` contract as an org agent, authenticating with an opaque
3060
+ * API key — one request, no handshake, no session.
3061
+ *
3062
+ * @param opts - baseUrl, apiKey, and the wire request to execute
3063
+ * @param schema - optional validator applied to the decoded result (e.g. a
3064
+ * zod schema); anything exposing `.parse(value)` is accepted, same as
3065
+ * {@link T3nClient.executeAndDecode}
3066
+ * @returns the contract's decoded result, typed as `T`
3067
+ * @throws {InvokeError} if `baseUrl` is insecure, on a network
3068
+ * failure/timeout, or on a non-2xx response
3069
+ * @throws {ContractResponseError} if the node returns a 2xx with a body
3070
+ * that is not valid JSON
3071
+ */
3072
+ declare function invoke<T = unknown>(opts: InvokeOptions, schema?: ContractResponseSchema<T>): Promise<T>;
3073
+
3074
+ /**
3075
+ * Token fixed-point units (USDT-style 6 decimals).
3076
+ *
3077
+ * As of `tee:*` metering v2, every token amount on the wire —
3078
+ * {@link BalanceRow}'s `available`/`reserved`, {@link UsageEntry.amount},
3079
+ * and `total_supply` — is denominated in **base units**, where
3080
+ * `1 T3N token = `{@link BASE_UNITS_PER_TOKEN}` base units`. The node
3081
+ * meters the *actual* fractional cost of each operation (pro-rata by
3082
+ * bytes / byte-seconds / fuel) down to `1e-6` token, so amounts are
3083
+ * raw integers in base units, NOT whole tokens.
3084
+ *
3085
+ * The wire fields are left as raw base units (no silent rescaling — that
3086
+ * would lose precision for large balances and surprise callers doing
3087
+ * arithmetic). Use {@link formatTokens} to render a human "tokens"
3088
+ * string and {@link toBaseUnits} to convert a token figure back.
3089
+ *
3090
+ * ⚠️ Breaking vs. the pre-decimals SDK: a balance that used to read `5`
3091
+ * (whole tokens) now reads `5_000_000` (base units). Multiply existing
3092
+ * display code through {@link formatTokens}.
3093
+ */
3094
+ /** Decimal places in a T3N token (fixed; mirrors the node constant). */
3095
+ declare const TOKEN_DECIMALS = 6;
3096
+ /** Base units per whole T3N token — `10 ** TOKEN_DECIMALS`. */
3097
+ declare const BASE_UNITS_PER_TOKEN = 1000000;
3098
+ /**
3099
+ * Render a base-unit amount as a human-readable token string, e.g.
3100
+ * `25_920_000 → "25.92"`, `1_000_000 → "1"`, `4768 → "0.004768"`.
3101
+ *
3102
+ * Trailing-zero fraction digits are trimmed; an integer amount renders
3103
+ * with no decimal point. Accepts `number` or `bigint`; for balances
3104
+ * above `Number.MAX_SAFE_INTEGER` prefer passing a `bigint`.
3105
+ */
3106
+ declare function formatTokens(baseUnits: number | bigint): string;
3107
+ /**
3108
+ * Convert a whole-or-fractional token figure to base units (rounded to
3109
+ * the nearest base unit). E.g. `25.92 → 25_920_000`, `1 → 1_000_000`.
3110
+ */
3111
+ declare function toBaseUnits(tokens: number): number;
3112
+
3113
+ /**
3114
+ * Org-data wire types mirroring the org-data contract wire shapes.
3115
+ *
3116
+ * Plain TypeScript interfaces (no zod) — the SDK does not use a
3117
+ * validation library for domain types; see the existing `types/` files.
3118
+ *
3119
+ * Each response type below is paired with a shallow runtime predicate
3120
+ * (`isMutationResponse`, `isOrgPolicyMeta`, etc.) so the org-data client
3121
+ * can `assertShape` the decoded payload before returning to callers.
3122
+ * Predicates check the top-level structure only; nested elements
3123
+ * (e.g. each `UserGrant` inside `OrgContractGrants.grants`) are not
3124
+ * deeply validated — see `utils/shape.ts` for the rationale.
3125
+ *
3126
+ * Reference: the org-data wire contract.
3127
+ */
3128
+ /**
3129
+ * Capability grant stored under `ORG_CONTRACT_GRANTS_MAP`.
3130
+ *
3131
+ * Mirrors the org-data `UserGrant` wire shape.
3132
+ */
3133
+ interface UserGrant {
3134
+ /** The user this grant applies to (`did:t3n:<40-hex>`). */
3135
+ user_did: string;
3136
+ /** WIT function names the user may invoke (e.g. `"set-records"`). */
3137
+ functions: string[];
3138
+ /** Data scope paths the user may access (e.g. `"example/records"`). */
3139
+ scopes: string[];
3140
+ }
3141
+ /**
3142
+ * Policy record for an organisation's data tier.
3143
+ *
3144
+ * Mirrors the org-data policy-meta wire shape.
3145
+ */
3146
+ interface OrgPolicyMeta {
3147
+ /** DIDs (`did:t3n:<40-hex>`) of users authorised to manage policy and read data. */
3148
+ admins: string[];
3149
+ /** Maximum number of admins allowed for this org. */
3150
+ max_admins: number;
3151
+ /** Unix timestamp (secs) when the policy was first created. */
3152
+ created_at_secs: number;
3153
+ /** Unix timestamp (secs) of the most recent policy update. */
3154
+ updated_at_secs: number;
3217
3155
  /**
3218
- * Capture the server-minted `Session-Id` from the last handshake
3219
- * response headers. Validates shape so a
3220
- * broken or MITM'd response fails loudly instead of leaving a
3221
- * garbage value in the client. Idempotent: only the first valid
3222
- * mint per session is honoured — subsequent handshake RPC legs
3223
- * (none exist today, but the state-machine loop can iterate) do
3224
- * not overwrite an already-set value.
3156
+ * Per-org ceiling on delegation-credential validity (seconds).
3157
+ *
3158
+ * Absent when no org-level cap is set — the contract omits the field
3159
+ * (never serialises null) and the cluster-wide
3160
+ * `delegation.max_credential_validity_secs` governs instead. When set,
3161
+ * the effective cap is `min(max_credential_validity_secs, cluster_ceiling)`.
3225
3162
  */
3226
- private captureMintedSessionId;
3163
+ max_credential_validity_secs?: number;
3164
+ }
3165
+ /** Shallow runtime guard for {@link OrgPolicyMeta}. */
3166
+ declare function isOrgPolicyMeta(value: unknown): value is OrgPolicyMeta;
3167
+ /**
3168
+ * Effective org policy view returned by `org-policy-view`.
3169
+ *
3170
+ * Readable by any authenticated session (non-sensitive metadata).
3171
+ * Returns the **effective** credential validity cap:
3172
+ * `min(org.max_credential_validity_secs, cluster_ceiling)`, equal to the
3173
+ * cluster ceiling when the org has not set a per-org cap. The contract
3174
+ * always returns a value (or errors) — the field is never null.
3175
+ */
3176
+ interface OrgPolicyView {
3227
3177
  /**
3228
- * Get the finalized session blob (for `session.encrypt` calls).
3229
- * Populated by `tryFinalize` once the handshake state machine
3230
- * reaches its terminal phase.
3178
+ * Effective delegation-credential validity cap in seconds:
3179
+ * `min(org value, cluster ceiling)`, equal to the cluster ceiling when the
3180
+ * org has not set a per-org cap. Always present — mirrors the contract's
3181
+ * `PolicyViewResponse.effective_validity_secs` (org-data `org-policy-view`).
3231
3182
  */
3232
- private getSessionState;
3183
+ effective_validity_secs: number;
3233
3184
  }
3234
-
3185
+ /** Shallow runtime guard for {@link OrgPolicyView}. */
3186
+ declare function isOrgPolicyView(value: unknown): value is OrgPolicyView;
3235
3187
  /**
3236
- * Guest-to-Host Request Handlers
3188
+ * Caller-scoped admin status returned by `org-am-i-admin`.
3237
3189
  *
3238
- * These handle requests from WASM that need the host environment to perform side effects.
3239
- * Examples: signing challenges, providing public keys, generating random bytes.
3190
+ * Reports only whether the **calling** session's DID is in the org's admin
3191
+ * list — never the roster itself (contrast {@link OrgPolicyMeta}, returned by
3192
+ * the admin-gated `org-policy-get`). Readable by any authenticated session.
3193
+ * Mirrors the org-data `AmIAdminResponse` wire shape.
3240
3194
  */
3241
-
3195
+ interface OrgAdminStatus {
3196
+ /** Whether the calling session is an admin of the queried org. */
3197
+ is_admin: boolean;
3198
+ }
3199
+ /** Shallow runtime guard for {@link OrgAdminStatus}. */
3200
+ declare function isOrgAdminStatus(value: unknown): value is OrgAdminStatus;
3242
3201
  /**
3243
- * Account — MetaMask handler accepts either a plain address string or an
3244
- * object with an `address` field (for compatibility with various wallet
3245
- * libraries).
3202
+ * Standard response returned by all policy write and data mutation operations.
3203
+ *
3204
+ * Mirrors the org-data `MutationResponse` wire shape.
3246
3205
  */
3247
- type EthAccount = string | {
3248
- address: string;
3249
- };
3206
+ interface MutationResponse {
3207
+ /**
3208
+ * `"created"`, `"updated"`, `"deleted"`, or — for the agent-card mutations —
3209
+ * `"published"` / `"unpublished"`.
3210
+ */
3211
+ status: string;
3212
+ /** Hex-encoded entry ID; present on data write/delete operations. */
3213
+ entry_id?: string;
3214
+ /** Whether the target key existed before deletion; present on single-entry deletes. */
3215
+ deleted?: boolean;
3216
+ /** Number of entries removed; present on `org-data-delete-scope`. */
3217
+ deleted_entries?: number;
3218
+ tx_hash: string | null;
3219
+ }
3250
3220
  /**
3251
- * Create an EthSign handler using MetaMask (window.ethereum)
3252
- * @param account - MetaMask account (string address or object with address property)
3253
- * @param logger - Optional logger instance. Defaults to a logger using the global log level (LogLevel.ERROR).
3254
- * Pass a custom logger to override logging behavior for this handler.
3255
- * @param privateKey - Optional private key for signing (if provided, MetaMask is not used)
3221
+ * Shallow runtime guard for {@link MutationResponse}.
3222
+ *
3223
+ * Only the always-present fields are checked — `status` is mandatory on
3224
+ * every mutation; `tx_hash` is non-optional but nullable. The optional
3225
+ * fields (`entry_id`, `deleted`, `deleted_entries`) are not validated
3226
+ * because their presence depends on which mutation ran.
3256
3227
  */
3257
- declare function metamask_sign(account: EthAccount, logger?: Logger, privateKey?: string | undefined): GuestToHostHandler;
3228
+ declare function isMutationResponse(value: unknown): value is MutationResponse;
3258
3229
  /**
3259
- * Get the current MetaMask address
3260
- * @returns Ethereum address (lowercase, 0x prefixed)
3230
+ * Response type alias for org-writers-get.
3231
+ *
3232
+ * The wire body is `{ writers: string[] }` where each entry is
3233
+ * `did:t3n:<40-hex>`.
3261
3234
  */
3262
- declare function metamask_get_address(): Promise<string>;
3235
+ interface OrgWriters {
3236
+ writers: string[];
3237
+ }
3238
+ /** Shallow runtime guard for {@link OrgWriters}. */
3239
+ declare function isOrgWriters(value: unknown): value is OrgWriters;
3263
3240
  /**
3264
- * Get the address for a given private key
3265
- * @param privateKey - Ethereum private key (0x prefixed hex string)
3266
- * @returns Ethereum address (lowercase, 0x prefixed)
3241
+ * Response type alias for org-grants-get.
3242
+ *
3243
+ * The wire body echoes the `contract_id` alongside the grant list.
3267
3244
  */
3268
- declare function eth_get_address(privateKey: string): string;
3245
+ interface OrgContractGrants {
3246
+ contract_id: string;
3247
+ grants: UserGrant[];
3248
+ }
3269
3249
  /**
3270
- * Create an MlKemPublicKey handler that lazily fetches the root public key
3271
- * from `${baseUrl}/status` on first invocation, verifies it against the
3272
- * DKG attestation trust anchor (SP-003), and caches the encoded response
3273
- * for subsequent calls.
3274
- *
3275
- * @param baseUrl - **Required**. The node URL whose `/status` endpoint should
3276
- * serve the ML-KEM public key. Must be the same URL the
3277
- * T3nClient is constructed with — otherwise the handshake
3278
- * encrypts to one node and sends ciphertext to another.
3250
+ * Shallow runtime guard for {@link OrgContractGrants}.
3279
3251
  *
3280
- * Was optional in 0.3.x, where omitting it caused the lazy
3281
- * fetch to silently fall back to `NODE_URLS[currentEnv]` and
3282
- * hit the wrong node. Three downstream consumers (demo.ts,
3283
- * t3-apps dev wallet hooks, t3n-mcp session manager) all
3284
- * hit this trap before we tightened the type.
3285
- * @param trustAnchor - **Required**. Client-pinned expected peer IDs +
3286
- * RTMR3 allowlist the DKG bundle is verified against, or
3287
- * `{ unsafe_trust_server: true }` to skip verification.
3288
- * The key is only cached/returned once verification passes.
3252
+ * Validates the immediate envelope (`contract_id: string`, `grants:
3253
+ * array`) without recursing into each `UserGrant`. The Rust contract
3254
+ * is the source of truth for grant element shape; widening the predicate
3255
+ * here would create maintenance churn against benign field additions.
3289
3256
  */
3290
- declare function createMlKemPublicKeyHandler(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandler;
3257
+ declare function isOrgContractGrants(value: unknown): value is OrgContractGrants;
3291
3258
  /**
3292
- * Create Random handler backed by crypto.getRandomValues
3293
- * Note: The Rust Vec<u8> type serializes as an array of bytes, not a base64 string
3259
+ * One grant inside a role: a {@link UserGrant} body (without the
3260
+ * grantee, which is bound at assignment time) plus the target contract.
3261
+ * Mirrors the org-data `RoleGrant` wire shape.
3294
3262
  */
3295
- declare function createRandomHandler(): GuestToHostHandler;
3263
+ interface RoleGrant {
3264
+ /** Target contract (canonical name, e.g. `"tee:z-payroll/contracts"`). */
3265
+ contract_id: string;
3266
+ /** WIT function names this grant confers. */
3267
+ functions: string[];
3268
+ /** Data scope paths this grant confers (canonicalised lowercase). */
3269
+ scopes: string[];
3270
+ }
3296
3271
  /**
3297
- * Create the default handler set required by the T3n handshake.
3298
- *
3299
- * @param baseUrl - **Required**. Forwarded to `createMlKemPublicKeyHandler`
3300
- * so the lazy /status fetch hits the right node.
3301
- * @param trustAnchor - **Required**. Forwarded to the ML-KEM handler so the
3302
- * fetched key is verified against the DKG attestation
3303
- * (SP-003) before the handshake trusts it.
3272
+ * A role: a named bundle of grants and/or composed sub-roles.
3273
+ * Mirrors the org-data `RoleDefinition` wire shape.
3304
3274
  */
3305
- declare function createDefaultHandlers(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandlers;
3306
-
3275
+ interface RoleDefinition {
3276
+ /** Org-unique role identifier (slug; function-name grammar). */
3277
+ role_id: string;
3278
+ /** Human-facing label. */
3279
+ label: string;
3280
+ /** Composite: other role ids in the same org whose grants this role confers. */
3281
+ includes: string[];
3282
+ /** Grants this role confers directly. */
3283
+ grants: RoleGrant[];
3284
+ }
3307
3285
  /**
3308
- * Stateless `api_key` agent auth.
3309
- *
3310
- * `invoke` posts once to `POST /api/invoke` — an HTTPS-only
3311
- * endpoint (see the HTTPS-guard note below) that authenticates an org agent
3312
- * by an opaque API key (`X-T3N-Api-Key: t3n_key_<...>`) and executes a
3313
- * `z:` contract as that agent in the SAME request. Unlike
3314
- * {@link T3nClient.execute}, there is **no** ML-KEM handshake, **no**
3315
- * `Session-Id`, and **no** session state: the node derives the acting agent
3316
- * DID from the relayed key per-call (`resolve_stateless_credential`
3317
- * driving the session contract's `api_key` action), then runs the same
3318
- * execute pipeline `action.execute` runs after `check_authentication`
3319
- * (`ActionService::execute_as_did`), and returns the contract's decoded
3320
- * result as a plain `Json(result)` body — NOT a JSON-RPC envelope.
3321
- *
3322
- * Because the response is the bare decoded value (no `{jsonrpc,result,id}`
3323
- * wrapper to unwrap), decoding reuses {@link parseContractResponse} — the
3324
- * exact same JSON.parse + optional-schema path {@link T3nClient.executeAndDecode}
3325
- * uses for the session `execute` RPC — so callers get identical typed /
3326
- * schema-validated decoding on either path.
3327
- *
3328
- * This module intentionally does NOT import {@link T3nClient}, the WASM
3329
- * component loader, or any handshake/session machinery — `invoke` is
3330
- * a single fetch, nothing else.
3331
- *
3332
- * ### HTTPS guard (CodeRabbit T2)
3333
- * The API key is a long-lived bearer credential relayed in a plain header,
3334
- * so `invoke` refuses to send it over an insecure transport: `baseUrl`
3335
- * must be `https:`, unless the host is a local-dev loopback
3336
- * (`localhost` / `127.0.0.1` / `[::1]`), in which case plain `http:` is
3337
- * allowed. The check runs before any network activity — an insecure
3338
- * `baseUrl` never gets as far as a `fetch` call.
3339
- *
3340
- * ### Error hygiene (CodeRabbit T3/T4/T5)
3341
- * Every error `invoke` throws is a fixed, generic
3342
- * {@link InvokeError} message — the response body text, the
3343
- * underlying network error's message, and the api key are never
3344
- * interpolated into it. This is defense in depth against a server (or a
3345
- * malicious intermediary) that echoes the key or other secrets back in an
3346
- * error body: whatever comes back over the wire on a non-2xx response is
3347
- * discarded, not surfaced. The timeout timer also stays armed until the
3348
- * response body has been fully read (or has itself timed out) — see
3349
- * {@link invoke}'s implementation — so a connection that delivers
3350
- * headers and then stalls on the body still respects `timeoutMs`.
3286
+ * The roles assigned to one grantee within one org.
3287
+ * Mirrors the org-data `RoleAssignments` wire shape.
3351
3288
  */
3352
-
3289
+ interface RoleAssignments {
3290
+ /** Assigned role ids. */
3291
+ roles: string[];
3292
+ }
3293
+ /** Response for `org-role-get`; `role` is `null` when the id is unknown. */
3294
+ interface RoleGetResponse {
3295
+ role: RoleDefinition | null;
3296
+ }
3297
+ /** Shallow runtime guard for {@link RoleGetResponse}. */
3298
+ declare function isRoleGetResponse(value: unknown): value is RoleGetResponse;
3299
+ /** Response for `org-role-assignments-get`. */
3300
+ interface RoleAssignmentsResponse {
3301
+ /** Echoed back so callers don't need to track which request this answers. */
3302
+ grantee_did: string;
3303
+ /** The grantee's assigned role ids (empty when none). */
3304
+ roles: string[];
3305
+ }
3306
+ /** Shallow runtime guard for {@link RoleAssignmentsResponse}. */
3307
+ declare function isRoleAssignmentsResponse(value: unknown): value is RoleAssignmentsResponse;
3308
+ /**
3309
+ * Input for `listAgents` — the org plus optional pagination. Omit both `cursor`
3310
+ * and `limit` for the first page at the default limit; pass a previous
3311
+ * response's `next_cursor` back as `cursor` to fetch the following page.
3312
+ */
3313
+ interface ListAgentsInput {
3314
+ orgDid: string;
3315
+ /** Opaque cursor from a previous response's `next_cursor`. */
3316
+ cursor?: string;
3317
+ /** Maximum agents to return in this page. */
3318
+ limit?: number;
3319
+ }
3353
3320
  /**
3354
- * Wire body for `POST /api/invoke` — mirrors the server's
3355
- * server-side `ExecuteActionRequest`, the same shape
3356
- * `T3nClient`'s `execute*` wrappers build for the session `action.execute`
3357
- * RPC. Field names are load-bearing: the server deserialises strictly into
3358
- * `contract_id` / `contract_version` / `function_name` (see
3359
- * `T3nClient.executeSystemContract`'s doc comment) — `contract` / `version`
3360
- * / `function` produce a 400.
3321
+ * One org-owned agent in a {@link ListAgentsResponse}: the agent's DID, its
3322
+ * display name, and the number of distinct contracts it can access via a direct
3323
+ * grant. Mirrors the org-data `AgentSummary` wire shape. The name comes from the
3324
+ * agent's private card (falling back to the DID), so the FE no longer needs to
3325
+ * fetch each `public:agent_cards` entry to render the roster.
3361
3326
  */
3362
- interface InvokeRequest {
3363
- contract_id: string;
3364
- contract_version: string;
3365
- function_name: string;
3366
- /** Delegated-call target member; omitted for a self (non-delegated) call. */
3367
- pii_did?: string;
3368
- input?: unknown;
3327
+ interface AgentSummary {
3328
+ /** The agent's DID (`did:t3n:<40-hex>`). */
3329
+ did: string;
3330
+ /** The agent's display name, from its private card (DID when unavailable). */
3331
+ name: string;
3332
+ /** Count of distinct contracts the agent holds a direct grant on. */
3333
+ contract_count: number;
3369
3334
  }
3370
- /** Options for {@link invoke}. */
3371
- interface InvokeOptions {
3372
- /**
3373
- * RPC base URL of the T3n node, e.g. `https://node.example.com`. Must be
3374
- * `https:` unless the host is a local-dev loopback (`localhost` /
3375
- * `127.0.0.1` / `[::1]`) — see the module doc comment's HTTPS-guard note.
3376
- */
3377
- baseUrl: string;
3378
- /**
3379
- * The agent's opaque API key (`t3n_key_<...>`), relayed verbatim in the
3380
- * `X-T3N-Api-Key` header. Never logged and never interpolated into any
3381
- * error this module throws — see the module doc comment and
3382
- * {@link InvokeError}.
3383
- */
3384
- apiKey: string;
3385
- /** The wire request to execute, built to the {@link InvokeRequest} shape. */
3386
- request: InvokeRequest;
3387
- /** Fetch timeout in ms. Defaults to 30s, matching {@link HttpTransport}. */
3388
- timeoutMs?: number;
3335
+ /** Response for `org-data-list-agents`. */
3336
+ interface ListAgentsResponse {
3337
+ /** One PAGE of the org's org-owned agents, sorted by DID. */
3338
+ agents: AgentSummary[];
3339
+ /** Opaque cursor for the next page; absent on the last page. */
3340
+ next_cursor?: string;
3389
3341
  }
3342
+ /** A human member's org role. The closed wire domain of {@link HumanMember}. */
3343
+ type MemberRole = "admin" | "member";
3390
3344
  /**
3391
- * Thrown when `POST /api/invoke` fails at the transport or HTTP
3392
- * layer (network failure, timeout, non-2xx status). Contract-level errors
3393
- * the node returns as a 2xx JSON error value are NOT wrapped here — they
3394
- * flow through {@link parseContractResponse}'s normal return, same as the
3395
- * session `execute` path.
3396
- *
3397
- * The message is always one of a small set of fixed, generic strings — it
3398
- * NEVER contains the raw api key, the response body text, or the
3399
- * underlying network error's message (CodeRabbit T4/T5): a server (or a
3400
- * misbehaving intermediary) that echoes the key or other secrets back in
3401
- * an error body must not be able to leak them through this error's
3402
- * message.
3345
+ * Input for `listHumanMembers` — the org plus optional pagination. Omit both
3346
+ * `cursor` and `limit` for the first page at the default limit; pass a previous
3347
+ * response's `next_cursor` back as `cursor` to fetch the following page.
3403
3348
  */
3404
- declare class InvokeError extends T3nError {
3405
- readonly status?: number | undefined;
3406
- constructor(message: string, status?: number | undefined);
3349
+ interface ListHumanMembersInput {
3350
+ orgDid: string;
3351
+ /** Opaque cursor from a previous response's `next_cursor`. */
3352
+ cursor?: string;
3353
+ /** Maximum members to return in this page. */
3354
+ limit?: number;
3407
3355
  }
3408
3356
  /**
3409
- * Execute a `z:` contract as an org agent, authenticating with an opaque
3410
- * API key — one request, no handshake, no session.
3411
- *
3412
- * @param opts - baseUrl, apiKey, and the wire request to execute
3413
- * @param schema - optional validator applied to the decoded result (e.g. a
3414
- * zod schema); anything exposing `.parse(value)` is accepted, same as
3415
- * {@link T3nClient.executeAndDecode}
3416
- * @returns the contract's decoded result, typed as `T`
3417
- * @throws {InvokeError} if `baseUrl` is insecure, on a network
3418
- * failure/timeout, or on a non-2xx response
3419
- * @throws {ContractResponseError} if the node returns a 2xx with a body
3420
- * that is not valid JSON
3357
+ * One direct human member: DID plus org role. No profile PII (name/email are
3358
+ * out of scope and owned by `tee:user`). Mirrors the org-data `HumanMember`
3359
+ * wire shape.
3421
3360
  */
3422
- declare function invoke<T = unknown>(opts: InvokeOptions, schema?: ContractResponseSchema<T>): Promise<T>;
3423
-
3361
+ interface HumanMember {
3362
+ /** The member's DID (`did:t3n:<40-hex>`). */
3363
+ did: string;
3364
+ /** The member's org role. */
3365
+ role: MemberRole;
3366
+ }
3367
+ /** Response for `org-data-list-human-members`. */
3368
+ interface ListHumanMembersResponse {
3369
+ /** One PAGE of the org's direct human members, sorted by DID. */
3370
+ members: HumanMember[];
3371
+ /** Opaque cursor for the next page; absent on the last page. */
3372
+ next_cursor?: string;
3373
+ }
3374
+ /** Shallow runtime guard for {@link ListHumanMembersResponse}. */
3375
+ declare function isListHumanMembersResponse(value: unknown): value is ListHumanMembersResponse;
3376
+ /** Shallow runtime guard for {@link ListAgentsResponse}. */
3377
+ declare function isListAgentsResponse(value: unknown): value is ListAgentsResponse;
3378
+ /** Response for `org-data-list`. */
3379
+ interface DataListResponse {
3380
+ /** Hex-encoded entry IDs for this page. */
3381
+ entry_ids: string[];
3382
+ /** Offset to pass for the next page. `null` when this is the last page. */
3383
+ next_offset: number | null;
3384
+ /** Total number of entries in the scope (across all pages). */
3385
+ total: number;
3386
+ }
3387
+ /** Shallow runtime guard for {@link DataListResponse}. */
3388
+ declare function isDataListResponse(value: unknown): value is DataListResponse;
3389
+ /** Secret shape discriminator (mirrors the contract `SecretKind`). */
3390
+ type SecretKind = "single_value" | "json";
3391
+ /** Metadata common to every {@link SecretView} entry. */
3392
+ interface SecretViewBase {
3393
+ /** Secret name (the `(org, name)` key tail). */
3394
+ name: string;
3395
+ /** Monotonic version, bumped on each value rotation and ACL edit. */
3396
+ version: number;
3397
+ /** Unix seconds of the most recent write. */
3398
+ updated_at_secs: number;
3399
+ }
3424
3400
  /**
3425
- * Token fixed-point units (USDT-style 6 decimals).
3426
- *
3427
- * As of `tee:*` metering v2, every token amount on the wire —
3428
- * {@link BalanceRow}'s `available`/`reserved`, {@link UsageEntry.amount},
3429
- * and `total_supply` — is denominated in **base units**, where
3430
- * `1 T3N token = `{@link BASE_UNITS_PER_TOKEN}` base units`. The node
3431
- * meters the *actual* fractional cost of each operation (pro-rata by
3432
- * bytes / byte-seconds / fuel) down to `1e-6` token, so amounts are
3433
- * raw integers in base units, NOT whole tokens.
3434
- *
3435
- * The wire fields are left as raw base units (no silent rescaling — that
3436
- * would lose precision for large balances and surprise callers doing
3437
- * arithmetic). Use {@link formatTokens} to render a human "tokens"
3438
- * string and {@link toBaseUnits} to convert a token figure back.
3439
- *
3440
- * ⚠️ Breaking vs. the pre-decimals SDK: a balance that used to read `5`
3441
- * (whole tokens) now reads `5_000_000` (base units). Multiply existing
3442
- * display code through {@link formatTokens}.
3401
+ * The redacted per-secret summary `org-secret-list` returns — a discriminated
3402
+ * union on `kind`. The value is NEVER present: a single-value exposes only its
3403
+ * last four characters and a json secret only its sorted top-level field names.
3443
3404
  */
3444
- /** Decimal places in a T3N token (fixed; mirrors the node constant). */
3445
- declare const TOKEN_DECIMALS = 6;
3446
- /** Base units per whole T3N token — `10 ** TOKEN_DECIMALS`. */
3447
- declare const BASE_UNITS_PER_TOKEN = 1000000;
3405
+ type SecretView = (SecretViewBase & {
3406
+ kind: "single_value";
3407
+ /** Last four characters of the value (whole value when ≤ 4 chars). */
3408
+ last4: string;
3409
+ }) | (SecretViewBase & {
3410
+ kind: "json";
3411
+ /** Sorted top-level object field names (keys only, no values). */
3412
+ field_names: string[];
3413
+ });
3414
+ /** Shallow runtime guard for {@link SecretView}. */
3415
+ declare function isSecretView(value: unknown): value is SecretView;
3448
3416
  /**
3449
- * Render a base-unit amount as a human-readable token string, e.g.
3450
- * `25_920_000 → "25.92"`, `1_000_000 → "1"`, `4768 → "0.004768"`.
3451
- *
3452
- * Trailing-zero fraction digits are trimmed; an integer amount renders
3453
- * with no decimal point. Accepts `number` or `bigint`; for balances
3454
- * above `Number.MAX_SAFE_INTEGER` prefer passing a `bigint`.
3417
+ * Full secret record returned by `org-secret-get` — the value IS included
3418
+ * (the deliberate read-back path the READ axis exists for), along with all
3419
+ * three ACLs.
3455
3420
  */
3456
- declare function formatTokens(baseUnits: number | bigint): string;
3421
+ interface SecretRecord {
3422
+ name: string;
3423
+ kind: SecretKind;
3424
+ /** The value as text: the scalar for a single-value, canonical JSON object for a json secret. */
3425
+ value: string;
3426
+ version: number;
3427
+ /** READ axis — DIDs allowed to read the value back. */
3428
+ reader_dids: string[];
3429
+ /** READ axis — role ids allowed to read the value back. */
3430
+ reader_roles: string[];
3431
+ /** MANAGE axis — DIDs allowed to rotate the value. */
3432
+ manager_dids: string[];
3433
+ /** MANAGE axis — role ids allowed to rotate the value. */
3434
+ manager_roles: string[];
3435
+ /** USE axis — canonical contract ids allowed to have the value injected. */
3436
+ contract_allowlist: string[];
3437
+ created_at_secs: number;
3438
+ updated_at_secs: number;
3439
+ /** DID of the caller who last wrote the record. */
3440
+ updated_by: string;
3441
+ }
3442
+ /** Shallow runtime guard for {@link SecretRecord}. */
3443
+ declare function isSecretRecord(value: unknown): value is SecretRecord;
3444
+ /** Response for `org-secret-list`: redacted per-kind views, no values. */
3445
+ interface SecretListResponse {
3446
+ secrets: SecretView[];
3447
+ }
3448
+ /** Shallow runtime guard for {@link SecretListResponse}. */
3449
+ declare function isSecretListResponse(value: unknown): value is SecretListResponse;
3450
+ /** Response for `org-data-get`. */
3451
+ interface DataGetResponse {
3452
+ entry_id: string;
3453
+ /** Hex-encoded raw payload bytes. */
3454
+ payload_hex: string;
3455
+ }
3456
+ /** Shallow runtime guard for {@link DataGetResponse}. */
3457
+ declare function isDataGetResponse(value: unknown): value is DataGetResponse;
3457
3458
  /**
3458
- * Convert a whole-or-fractional token figure to base units (rounded to
3459
- * the nearest base unit). E.g. `25.92 → 25_920_000`, `1 → 1_000_000`.
3459
+ * Return shape of `agentCardGet` — composed client-side from the generic
3460
+ * `org-data-get` read of the card's entry (there is no card-specific read
3461
+ * operation on the contract). To check whether a public copy exists, probe
3462
+ * the anonymous `GET /api/agent-card/{did}` endpoint.
3460
3463
  */
3461
- declare function toBaseUnits(tokens: number): number;
3464
+ interface AgentCardResponse {
3465
+ /** The agent whose card this is (`did:t3n:<40-hex>`). */
3466
+ agent_did: string;
3467
+ /** The stored card JSON body, verbatim. */
3468
+ card: string;
3469
+ }
3470
+ /** Shallow runtime guard for {@link AgentCardResponse}. */
3471
+ declare function isAgentCardResponse(value: unknown): value is AgentCardResponse;
3472
+ /**
3473
+ * Legacy direct-route org-data envelope shape retained for compatibility.
3474
+ *
3475
+ * This mirrors the removed `/api/user-contract/execute` body format from
3476
+ * the transitional transport. New callers should use `OrgDataClient`,
3477
+ * which now dispatches through authenticated `/api/rpc` +
3478
+ * `action.execute` instead.
3479
+ */
3480
+ interface OrgDataActionWire {
3481
+ nonce: string;
3482
+ user_did: string;
3483
+ authenticator_id: string;
3484
+ contract_id: string;
3485
+ function: string;
3486
+ args_hash: string;
3487
+ expires_at_secs: number;
3488
+ signature: string;
3489
+ }
3462
3490
 
3463
3491
  /**
3464
3492
  * OrgDataClient — typed wrapper over the existing authenticated
@@ -3531,17 +3559,10 @@ interface SetWritersInput {
3531
3559
  scope: string;
3532
3560
  writers: string[];
3533
3561
  }
3534
- /**
3535
- * A grant to set via {@link OrgDataClient.setGrants}. The per-grant
3536
- * `contract_id` is injected by the SDK from the request `contractId` (the
3537
- * contract sets it server-side regardless), so callers omit it — a read-back
3538
- * {@link BoundGrant}, which carries `contract_id`, is still assignable.
3539
- */
3540
- type SetGrantInput = Omit<BoundGrant, "contract_id">;
3541
3562
  interface SetGrantsInput {
3542
3563
  orgDid: string;
3543
3564
  contractId: string;
3544
- grants: SetGrantInput[];
3565
+ grants: UserGrant[];
3545
3566
  }
3546
3567
  interface DeleteGrantsInput {
3547
3568
  orgDid: string;
@@ -3803,7 +3824,7 @@ declare class OrgDataClient {
3803
3824
  /** Delete a secret entirely (org-admin only). */
3804
3825
  secretDelete(input: SecretNameInput): Promise<MutationResponse>;
3805
3826
  /**
3806
- * Full replacement of the org's grant list for a contract.
3827
+ * Full replacement of the user-grant list for a contract.
3807
3828
  *
3808
3829
  * Passing an empty list removes the entry.
3809
3830
  */
@@ -3882,7 +3903,7 @@ declare class OrgDataClient {
3882
3903
  purgeOrg(input: PurgeOrgInput): Promise<MutationResponse>;
3883
3904
  /**
3884
3905
  * Detach-cascade grant sweep: drop `memberDid` from every
3885
- * one of the org's per-contract `BoundGrant` lists. Authorised for an
3906
+ * one of the org's per-contract `UserGrant` lists. Authorised for an
3886
3907
  * org-admin of the subject, or the member removing their own grants.
3887
3908
  * `deleted_entries` reports how many contract grant lists were rewritten.
3888
3909
  */
@@ -4080,7 +4101,7 @@ declare function createOrgDataClientFromSession(t3n: T3nClient, baseUrl: string)
4080
4101
  *
4081
4102
  * Envelope-free authorisation removed the per-call delegation
4082
4103
  * credential and envelope entirely: authority is now the standing on-chain
4083
- * `agent_auth` ∩ `org_grant` intersection the host re-reads every call, and
4104
+ * `agent_auth` ∩ `UserGrant` intersection the host re-reads every call, and
4084
4105
  * every payroll call emits the plain Direct wire variant (`{ request }`).
4085
4106
  * What remains here is the request body shape, its canonical defaults, and
4086
4107
  * the base64url / DID helpers callers still need.
@@ -4299,7 +4320,7 @@ declare function stringToBytes(str: string): Uint8Array;
4299
4320
  */
4300
4321
  declare function bytesToString(bytes: Uint8Array): string;
4301
4322
 
4302
- declare function getContractVersion(rpcUrl: string, contractId: string): Promise<string>;
4323
+ declare function getScriptVersion(rpcUrl: string, scriptName: string): Promise<string>;
4303
4324
 
4304
4325
  /**
4305
4326
  * Secret redaction utilities for T3n SDK
@@ -4341,7 +4362,7 @@ declare function redactSecretsFromJson(jsonString: string): string;
4341
4362
  *
4342
4363
  * Predicates are intentionally shallow — they validate the immediate
4343
4364
  * top-level structure (object kind, presence/type of leading fields)
4344
- * but do not deeply validate nested elements (e.g. each `BoundGrant`
4365
+ * but do not deeply validate nested elements (e.g. each `UserGrant`
4345
4366
  * inside `OrgContractGrants.grants`). Deep validation would be brittle
4346
4367
  * against benign contract additions; shallow guards catch the failure
4347
4368
  * modes that actually surface as runtime crashes (null/string/missing
@@ -4445,8 +4466,14 @@ type TrustManifestPayload = Omit<SignedTrustManifest, "signature">;
4445
4466
  * malformed inputs (non-hex key/signature) return `false`.
4446
4467
  */
4447
4468
  declare function verifyManifestSignature(manifest: SignedTrustManifest, operatorPublicKeyHex: string): boolean;
4448
- /** Project a verified manifest onto the `TrustAnchor` the client pins. */
4449
- declare function manifestToTrustAnchor(manifest: SignedTrustManifest): TrustAnchor;
4469
+ /**
4470
+ * Project a verified manifest onto the `TrustAnchor` the client pins.
4471
+ *
4472
+ * `url` is recorded on the anchor's `source` for diagnostics only — it
4473
+ * carries no security weight, and is omitted when the caller doesn't
4474
+ * have one (a hand-built manifest in a test).
4475
+ */
4476
+ declare function manifestToTrustAnchor(manifest: SignedTrustManifest, url?: string): TrustAnchor;
4450
4477
  /** Options for {@link fetchTrustedManifest}. */
4451
4478
  interface FetchTrustedManifestOptions {
4452
4479
  /**
@@ -4622,7 +4649,7 @@ interface TenantBaseClient {
4622
4649
  }
4623
4650
  interface TenantClientConfig {
4624
4651
  environment?: TenantSdkEnvironment;
4625
- /** Node URL for `getContractVersion` during business contract execution. Falls back to `baseUrl`. */
4652
+ /** Node URL for `getScriptVersion` during business contract execution. Falls back to `baseUrl`. */
4626
4653
  endpoint?: string;
4627
4654
  /**
4628
4655
  * Authenticated base client the TenantClient dispatches RPCs through.
@@ -4639,7 +4666,7 @@ interface TenantClientConfig {
4639
4666
  t3n?: TenantBaseClient;
4640
4667
  baseUrl?: string;
4641
4668
  tenantDid?: string;
4642
- tenantContractId?: string;
4669
+ tenantScriptName?: string;
4643
4670
  }
4644
4671
  type TenantStatus = "pending" | "active" | "suspended";
4645
4672
  interface TenantMeResponse {
@@ -5089,5 +5116,5 @@ declare function tenantDidHex(tenantDid: string): string;
5089
5116
  declare function validateTail(tail: string): string;
5090
5117
  declare function canonicalTenantName(tenantDid: string, tail: string): string;
5091
5118
 
5092
- export { AGENT_CARDS_SCOPE, AuthMethod, AuthenticationError, BASE_UNITS_PER_TOKEN, ContractResponseError, DEFAULT_ENVIRONMENT, DEFAULT_INDIVIDUAL_THRESHOLD_CENTS, DEFAULT_KYC_POLL_CADENCE, HandshakeError, HttpTransport, InvokeError, KycStatusTimeoutError, LogLevel, MockTransport, NODE_URLS, OrgDataClient, OtpRateLimitedError, RpcError, SessionExpiredError, SessionOrgDataClient, SessionStateError, SessionStatus, SessionUsageReportClient, T3nClient, T3nError, TERMINAL_KYC_STATUSES, TOKEN_DECIMALS, TenantClient, TenantContractsNamespace, TenantMapsNamespace, TenantNamespace, TenantSdkValidationError, TenantTokenNamespace, UnsupportedTenantSdkOperationError, UserUpsertError, WasmError, WireEncodingError, Z_PAYROLL_AUDIT_READ_FUNCTIONS, Z_PAYROLL_RUN_FUNCTIONS, _b64uEncode, assertShape, b64uDecodeStrict, b64uEncodeBytes, buildSecretWriteArgs, bytesToString, canonicalTenantName, clearKeyCache, clearManifestVersionFloor, compactDidFromBytes, createDefaultHandlers, createEmailOtpAuthInput, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createOrgDataClientFromSession, createRandomHandler, createUsageReportClientFromSession, createWorkloadAuthInput, decodeWasmErrorMessage, deriveAgentCardEntryId, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, fetchTrustedManifest, formatTokens, generateRandomString, generateUUID, getContractVersion, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, invoke, isAgentCardResponse, isDataGetResponse, isDataListResponse, isListAgentsResponse, isListHumanMembersResponse, isMutationResponse, isObject, isOrgAdminStatus, isOrgContractGrants, isOrgPolicyMeta, isOrgPolicyView, isOrgUsageReport, isOrgWriters, isRoleAssignmentsResponse, isRoleGetResponse, isSecretListResponse, isSecretRecord, isSecretView, isUnsafeTrustServer, loadConfig, loadWasmComponent, manifestToTrustAnchor, maskKeyMaterial, mergeDiscoverDids, mergeGrants, metamask_get_address, metamask_sign, parseAgentAuthDoc, parseContractResponse, redactSecrets, redactSecretsFromJson, requestToWire, setEnvironment, setGlobalLogLevel, setNodeUrl, stringToBytes, tenantDidHex, toBaseUnits, validateConfig, validateTail, verifyDkgAttestation, verifyManifestSignature, verifyTdxQuote };
5093
- export type { ActivityCallerType, ActivityEntry, ActivityOutcome, ActivityReport, AdmitForOrgOptions, AgentAuthDoc, AgentCardRefInput, AgentCardResponse, AgentCardSetInput, AgentSummary, AssignRolesInput, AuthInput, BalanceRow, BoundGrant, ChargeReason, ClientAuth, ClientHandshake, ConfigValidationResult, ContractDescriptorFacets, ContractExecuteInput, ContractKind, ContractLifecycleStatus, ContractListDetailedOptions, ContractListDetailedPage, ContractPublishInput, ContractRegisterResult, ContractResponseSchema, ContractSetDescriptorInput, CreatePolicyInput, DataGetInput, DataGetResponse, DataListInput, DataListResponse, DelegationGrantKind, DelegationGrantRef, DeleteDataInput, DeleteGrantsInput, DeleteScopeInput, DetailedContract, Did, Direction, DkgAttestation, DkgVerifyResult, EmailOtpAuthInput, EmailOtpCredentials, Environment, EthAuthInput, ExecuteBusinessContractOptions, ExecuteOrgDataActionOptions, FetchTrustedManifestOptions, GetActivityLogOptions, GetUsageOptions, GrantCheckParams, GrantCheckResult, GranteeInput, GrantsGetInput, GrantsMergeResult, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, HumanMember, InvokeOptions, InvokeRequest, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, ListAgentsInput, ListAgentsResponse, ListContractsParams, ListContractsResult, ListContractsScope, ListHumanMembersInput, ListHumanMembersResponse, ListedContract, Logger, MapCreateInput, MapLifecycleStatus, MapResponse, MapUpdateInput, MapVisibility, MemberRole, MutationResponse, OidcAuthInput, OidcCredentials, OrgAdminStatus, OrgContractGrants, OrgDataActionWire, OrgDataClientOptions, OrgPolicyMeta, OrgPolicyView, OrgUsageReport, OrgUsageReportInput, OrgWriters, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollRunRequest, PeerQuoteResult, PolicyGetInput, PurgeOrgInput, QuoteVerifyResult, ReaderSet, RemoveMemberGrantsInput, RoleAssignments, RoleAssignmentsResponse, RoleDefinition, RoleGetResponse, RoleGrant, RoleIdInput, SdkConfig, SecretKind, SecretListInput, SecretListResponse, SecretNameInput, SecretRecord, SecretSetValueInput, SecretView, SecretWriteInput, SessionCrypto, SessionId, SetGrantsInput, SetRoleInput, SetWritersInput, SignedTrustManifest, StringEncoding, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, TenantAdmitProjection, TenantAdmitStatus, TenantBaseClient, TenantClientConfig, TenantContractExecuteInput, TenantContractPublishInput, TenantContractSetDescriptorInput, TenantExecutionSession, TenantMapCreateInput, TenantMapUpdatePatch, TenantMeResponse, TenantSdkEnvironment, TenantSelfAdmitResult, TenantStatus, TenantTargetOptions, TokenTxKind, Transport, TrustAnchor, TrustAnchorOrUnsafe, TrustManifestPayload, UnassignRolesInput, UnsafeTrustServer, UpdateMetaInput, UsageEntry, UsagePage, UsageReportSignature, UserInputProfile, UserUpsertErrorKind, Validity, WasmComponent, WasmNextResult, WireBlock, WorkloadAuthInput, WriteDataInput, WriterSet, WritersGetInput };
5119
+ export { AGENT_CARDS_SCOPE, AuthMethod, AuthenticationError, BASE_UNITS_PER_TOKEN, ContractResponseError, DEFAULT_ENVIRONMENT, DEFAULT_INDIVIDUAL_THRESHOLD_CENTS, DEFAULT_KYC_POLL_CADENCE, HandshakeError, HttpTransport, InvokeError, KycStatusTimeoutError, LogLevel, MockTransport, NODE_URLS, OrgDataClient, OtpRateLimitedError, RpcError, SessionExpiredError, SessionOrgDataClient, SessionStateError, SessionStatus, SessionUsageReportClient, T3nClient, T3nError, TERMINAL_KYC_STATUSES, TOKEN_DECIMALS, TenantClient, TenantContractsNamespace, TenantMapsNamespace, TenantNamespace, TenantSdkValidationError, TenantTokenNamespace, UnsupportedTenantSdkOperationError, UserUpsertError, WasmError, WireEncodingError, Z_PAYROLL_AUDIT_READ_FUNCTIONS, Z_PAYROLL_RUN_FUNCTIONS, _b64uEncode, assertShape, b64uDecodeStrict, b64uEncodeBytes, buildSecretWriteArgs, bytesToString, canonicalTenantName, clearKeyCache, clearManifestVersionFloor, compactDidFromBytes, createDefaultHandlers, createEmailOtpAuthInput, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createOrgDataClientFromSession, createRandomHandler, createUsageReportClientFromSession, createWorkloadAuthInput, decodeWasmErrorMessage, deriveAgentCardEntryId, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, fetchTrustedManifest, formatTokens, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, invoke, isAgentCardResponse, isDataGetResponse, isDataListResponse, isListAgentsResponse, isListHumanMembersResponse, isMutationResponse, isObject, isOrgAdminStatus, isOrgContractGrants, isOrgPolicyMeta, isOrgPolicyView, isOrgUsageReport, isOrgWriters, isRoleAssignmentsResponse, isRoleGetResponse, isSecretListResponse, isSecretRecord, isSecretView, isUnsafeTrustServer, loadConfig, loadWasmComponent, manifestToTrustAnchor, maskKeyMaterial, mergeAgentAuthEntries, mergeDiscoverDids, metamask_get_address, metamask_sign, parseAgentAuthGet, parseAgentAuthPolicy, parseContractResponse, redactSecrets, redactSecretsFromJson, requestToWire, setEnvironment, setGlobalLogLevel, setNodeUrl, stringToBytes, tenantDidHex, toAgentAuthUpdateWire, toBaseUnits, validateConfig, validateTail, verifyDkgAttestation, verifyManifestSignature, verifyTdxQuote };
5120
+ export type { ActivityCallerType, ActivityEntry, ActivityOutcome, ActivityReport, AdmitForOrgOptions, AgentAuthEntry, AgentAuthMergeResult, AgentAuthPolicy, AgentAuthScriptGrant, AgentAuthUpdateInput, AgentCardRefInput, AgentCardResponse, AgentCardSetInput, AgentSummary, AssignRolesInput, AuthInput, BalanceRow, ChargeReason, ClientAuth, ClientHandshake, ConfigValidationResult, ContractDescriptorFacets, ContractExecuteInput, ContractKind, ContractLifecycleStatus, ContractListDetailedOptions, ContractListDetailedPage, ContractPublishInput, ContractRegisterResult, ContractResponseSchema, ContractSetDescriptorInput, CreatePolicyInput, DataGetInput, DataGetResponse, DataListInput, DataListResponse, DelegationGrantKind, DelegationGrantRef, DeleteDataInput, DeleteGrantsInput, DeleteScopeInput, DetailedContract, Did, Direction, DkgAttestation, DkgVerifyResult, EmailOtpAuthInput, EmailOtpCredentials, Environment, EthAuthInput, ExecuteBusinessContractOptions, ExecuteOrgDataActionOptions, FetchTrustedManifestOptions, GetActivityLogOptions, GetUsageOptions, GrantCheckParams, GrantCheckResult, GranteeInput, GrantsGetInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, HumanMember, InvokeOptions, InvokeRequest, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, ListAgentsInput, ListAgentsResponse, ListContractsParams, ListContractsResult, ListContractsScope, ListHumanMembersInput, ListHumanMembersResponse, ListedContract, Logger, MapCreateInput, MapLifecycleStatus, MapResponse, MapUpdateInput, MapVisibility, MemberRole, MutationResponse, OidcAuthInput, OidcCredentials, OrgAdminStatus, OrgContractGrants, OrgDataActionWire, OrgDataClientOptions, OrgPolicyMeta, OrgPolicyView, OrgUsageReport, OrgUsageReportInput, OrgWriters, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollRunRequest, PeerQuoteResult, PolicyGetInput, PurgeOrgInput, QuoteVerifyResult, ReaderSet, RemoveMemberGrantsInput, RoleAssignments, RoleAssignmentsResponse, RoleDefinition, RoleGetResponse, RoleGrant, RoleIdInput, SdkConfig, SecretKind, SecretListInput, SecretListResponse, SecretNameInput, SecretRecord, SecretSetValueInput, SecretView, SecretWriteInput, SessionCrypto, SessionId, SetGrantsInput, SetRoleInput, SetWritersInput, SignedTrustManifest, StringEncoding, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, TenantAdmitProjection, TenantAdmitStatus, TenantBaseClient, TenantClientConfig, TenantContractExecuteInput, TenantContractPublishInput, TenantContractSetDescriptorInput, TenantExecutionSession, TenantMapCreateInput, TenantMapUpdatePatch, TenantMeResponse, TenantSdkEnvironment, TenantSelfAdmitResult, TenantStatus, TenantTargetOptions, TokenTxKind, Transport, TrustAnchor, TrustAnchorOrUnsafe, TrustAnchorSource, TrustManifestPayload, UnassignRolesInput, UnsafeTrustServer, UpdateMetaInput, UsageEntry, UsagePage, UsageReportSignature, UserGrant, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult, WireBlock, WorkloadAuthInput, WriteDataInput, WriterSet, WritersGetInput };