@terminal3/t3n-sdk 4.29.0 → 4.32.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
@@ -933,290 +933,657 @@ declare class ContractResponseError extends T3nError {
933
933
  declare function parseContractResponse<T = unknown>(raw: string, schema?: ContractResponseSchema<T>): T;
934
934
 
935
935
  /**
936
- * Agent-auth grants — the standing on-chain authority a user delegates to
937
- * an agent (envelope-free authorisation).
936
+ * Org-data wire types mirroring the org-data contract wire shapes.
938
937
  *
939
- * `AGENT_AUTH_MAP` is keyed by the *user* DID — one policy document per
940
- * user, global across orgs, with at most one entry per agent DID. Reads
941
- * (`agent-auth-get`) and writes (`agent-auth-update`) on
942
- * `tee:authorisations/contracts` (the policy's owning contract) are
943
- * **SelfOnly**: only the user, authenticated as themselves, may read or
944
- * write their own grants. This is the user-approval
945
- * proof the per-call delegation credential's `user_sig` used to carry.
946
- *
947
- * The write shape gained `scopes` + a validity window: the
948
- * agent's delegated org-data scopes, and an optional `[valid_from_secs,
949
- * valid_until_secs]` window. The ≤ cap *length* check is enforced contract-
950
- * side at write time; the expiry gate is host-side at read time.
951
- *
952
- * The merge below is a script-level union (R59): writing a grant for one
953
- * `(agent_did, script_name)` preserves every other script row on that
954
- * agent's entry, and every other agent's entry, unchanged.
955
- */
956
- /** A single script grant in the camelCase write-request shape. */
957
- interface AgentAuthScriptGrant {
958
- /** Contract name, or `"*"`. */
959
- scriptName: string;
960
- /** Optional semver requirement; `null` to match any version. */
961
- versionReq?: string | null;
962
- /** Functions the agent may invoke on this contract. */
963
- functions: string[];
964
- /** Org-data scopes delegated to the agent for the contract functions to
965
- * read on its behalf. */
966
- scopes?: string[];
967
- /** Direct-read scopes the agent may enumerate itself, via whichever read
968
- * function the contract exposes for direct enumeration. A strict subset of
969
- * `scopes` (enforced contract-side). */
970
- readScopes?: string[];
971
- /** Optional validity-window start (unix seconds). */
972
- validFromSecs?: number | null;
973
- /** NEW: optional validity-window end (unix seconds). */
974
- validUntilSecs?: number | null;
975
- /** Egress hosts the agent may reach for this contract. */
976
- allowedHosts: string[];
977
- }
978
- /** One agent's entry in the write-request shape. */
979
- interface AgentAuthEntry {
980
- agentDid: string;
981
- scripts: AgentAuthScriptGrant[];
982
- }
983
- /**
984
- * The full agent-auth policy document in the camelCase write shape:
985
- * the per-agent grants plus the document-level discovery grants.
938
+ * Plain TypeScript interfaces (no zod) — the SDK does not use a
939
+ * validation library for domain types; see the existing `types/` files.
940
+ *
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.
986
947
  *
987
- * `discoverDids` (contract wire: `discover_dids`) is the
988
- * list of DIDs the user lets their registered agents *enumerate the
989
- * contracts of* via `listContracts`: an org DID grants org-mode discovery,
990
- * the user's own DID grants self-mode discovery. It lives at document
991
- * level — not on a script grant — because discovery must surface contracts
992
- * the agent cannot yet call. The node's discovery gate additionally
993
- * requires the calling agent to be named in `agents` (subject binding), so
994
- * an unregistered agent discovers nothing regardless of this list.
948
+ * Reference: the org-data wire contract.
995
949
  */
996
- interface AgentAuthPolicy {
997
- agents: AgentAuthEntry[];
998
- discoverDids: string[];
999
- }
1000
950
  /**
1001
- * Parse a full `agent-auth-get` response (the stored snake_case policy
1002
- * document) into the camelCase write shape, including the document-level
1003
- * `discover_dids`. A `null` / absent response is the empty policy.
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`).
1004
956
  */
1005
- declare function parseAgentAuthPolicy(response: unknown): AgentAuthPolicy;
1006
- /** Extract the `agents` array from an `agent-auth-get` response. */
1007
- declare function parseAgentAuthGet(response: unknown): AgentAuthEntry[];
1008
- interface AgentAuthMergeResult {
1009
- /** Full merged `agents` list, ready for `agent-auth-update`. */
1010
- agents: AgentAuthEntry[];
1011
- /** `"<agentDid> → <scriptName>"` rows preserved from the existing policy. */
1012
- preservedRows: string[];
957
+ interface Validity {
958
+ valid_from_secs?: number;
959
+ valid_until_secs?: number;
1013
960
  }
1014
- /** Input to the full-document write {@link T3nClient.agentAuthUpdate}. The
1015
- * document IS the new state: an empty `agents` list revokes all agent
1016
- * access, and an omitted / empty `discoverDids` persists an empty
1017
- * discovery-grant list (the contract has no per-field merge). Mirrors the
1018
- * contract `AgentAuthPolicy`. */
1019
- interface AgentAuthUpdateInput {
1020
- agents: AgentAuthEntry[];
1021
- /** Document-level discovery grants — see {@link AgentAuthPolicy}. */
1022
- discoverDids?: string[];
1023
- }
1024
- /**
1025
- * Serialise a camelCase policy document to the contract's canonical
1026
- * snake_case `agent-auth-update` wire (`agent_did` / `script_name` /
1027
- * `version_req` / `read_scopes` / `valid_from_secs` / `valid_until_secs` /
1028
- * `allowed_hosts` / `discover_dids`), so neither write path relies on the
1029
- * contract's compatibility aliases. Absent optionals are omitted (never
1030
- * sent as `null`); empty `scopes` / `read_scopes` are omitted (the
1031
- * contract defaults both to empty). `functions` and `allowed_hosts` are
1032
- * always emitted — the contract requires explicit functions (`["*"]` =
1033
- * all) and reads an absent `allowed_hosts` as deny-all egress. The
1034
- * document-level `discover_dids` (strictly snake_case — the contract
1035
- * defines no camelCase alias for it) is emitted only when non-empty; the
1036
- * contract defaults an absent list to empty.
1037
- */
1038
- declare function toAgentAuthUpdateWire(agents: AgentAuthEntry[], discoverDids?: string[]): {
1039
- agents: Array<{
1040
- agent_did: string;
1041
- scripts: Array<Record<string, unknown>>;
1042
- }>;
1043
- discover_dids?: string[];
1044
- };
1045
- /**
1046
- * Order-preserving deduplicating union of discovery-grant DID lists —
1047
- * the read-merge-write counterpart of {@link mergeAgentAuthEntries} for
1048
- * the document-level `discoverDids` (the contract rejects duplicate
1049
- * entries, so the union must dedupe).
1050
- */
1051
- declare function mergeDiscoverDids(existing: string[], additions: string[]): string[];
1052
- /**
1053
- * Merge new agent entries into the existing policy with script-level union
1054
- * semantics: for an agent DID present on both sides, script rows whose
1055
- * `scriptName` is not being written are preserved; rows with a matching
1056
- * `scriptName` are replaced by the new grant. Entries for other agent DIDs
1057
- * pass through unchanged.
1058
- */
1059
- declare function mergeAgentAuthEntries(existing: AgentAuthEntry[], newEntries: AgentAuthEntry[]): AgentAuthMergeResult;
1060
-
1061
961
  /**
1062
- * KYC types for the `tee:user/contracts::kyc-status` short-poll
1063
- * function.
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.
1064
966
  *
1065
- * The shape mirrors the `kyc-status` wire response.
1066
- * The bytes go straight from the contract
1067
- * through the JSON-RPC envelope into [[T3nClient.kycStatus]].
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.
1068
973
  */
1069
-
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
+ }
1070
996
  /**
1071
- * Terminal status for a Level 2 KYC verification, plus `pending`.
997
+ * Policy record for an organisation's data tier.
1072
998
  *
1073
- * - `pending` — provider has not delivered a verdict yet, or the
1074
- * webhook arrived but the post-action VC issuance hasn't completed.
1075
- * - `verified` — provider approved AND a VC has been issued. `vcIds`
1076
- * carries the issued credential ids.
1077
- * - `rejected` — provider declined / required resubmission /
1078
- * expired / the user abandoned the flow. `error` may carry a
1079
- * provider-supplied reason.
1080
- * - `orphan` — a Veriff webhook arrived with a `vendorData` that
1081
- * couldn't be matched to any user. Should not
1082
- * happen in the MetaMask flow but the contract surfaces it for
1083
- * completeness.
999
+ * Mirrors the org-data policy-meta wire shape.
1084
1000
  */
1085
- type KycStatusKind = "pending" | "verified" | "rejected" | "orphan";
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;
1086
1022
  /**
1087
- * Snapshot returned by `tee:user/contracts::kyc-status`.
1023
+ * Effective org policy view returned by `org-policy-view`.
1088
1024
  *
1089
- * Field names use camelCase on the SDK boundary even though the
1090
- * wire is snake_case — the wrapper rewrites keys at the client edge
1091
- * so callers don't see the JSON shape leaking through.
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.
1092
1030
  */
1093
- interface KycStatus {
1094
- /** Terminal status if reached, otherwise `pending`. */
1095
- status: KycStatusKind;
1096
- /**
1097
- * Provider being polled. Echoed back so callers that didn't
1098
- * supply one see the contract's default (`"veriff"` in phase one).
1099
- */
1100
- provider: string;
1101
- /**
1102
- * Unix-millis of the latest contract-visible event:
1103
- * VC issuance time, attestation arrival time, session-row
1104
- * `started_at_ms`, or orphan-record arrival time. Best-effort —
1105
- * `undefined` when no source carries a usable timestamp.
1106
- */
1107
- updatedAt?: number;
1108
- /**
1109
- * VC ids appended for this provider, in append order. Empty for
1110
- * `pending` / `rejected` / `orphan`.
1111
- */
1112
- vcIds: string[];
1031
+ interface OrgPolicyView {
1113
1032
  /**
1114
- * Provider-supplied reason for `rejected`, when available.
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
1037
  */
1116
- error?: string;
1038
+ effective_validity_secs: number;
1117
1039
  }
1040
+ /** Shallow runtime guard for {@link OrgPolicyView}. */
1041
+ declare function isOrgPolicyView(value: unknown): value is OrgPolicyView;
1118
1042
  /**
1119
- * Polling cadence for [[T3nClient.kycStatusPoll]]. Defaults:
1120
- * poll fast for the first 30 seconds, then back
1121
- * off, and bail after 5 minutes.
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.
1122
1049
  */
1123
- interface KycPollCadence {
1124
- /** Poll interval in ms while `elapsed < switchAtMs`. Default: 2000. */
1125
- fastMs: number;
1126
- /** Poll interval in ms once `elapsed >= switchAtMs`. Default: 5000. */
1127
- slowMs: number;
1128
- /** Elapsed-ms threshold to switch from fast to slow cadence. Default: 30_000. */
1129
- switchAtMs: number;
1130
- /**
1131
- * Maximum total time to spend polling before rejecting with
1132
- * [[KycStatusTimeoutError]]. Default: 300_000 (5 minutes).
1133
- */
1134
- timeoutMs: number;
1050
+ interface OrgAdminStatus {
1051
+ /** Whether the calling session is an admin of the queried org. */
1052
+ is_admin: boolean;
1135
1053
  }
1054
+ /** Shallow runtime guard for {@link OrgAdminStatus}. */
1055
+ declare function isOrgAdminStatus(value: unknown): value is OrgAdminStatus;
1136
1056
  /**
1137
- * Optional knobs for [[T3nClient.kycStatusPoll]]. Most callers won't
1138
- * touch any of these — the cadence defaults are baked in.
1057
+ * Standard response returned by all policy write and data mutation operations.
1058
+ *
1059
+ * Mirrors the org-data `MutationResponse` wire shape.
1139
1060
  */
1140
- interface KycPollOptions {
1141
- /**
1142
- * Cancellation signal. When aborted, the helper rejects with
1143
- * `signal.reason` (or a generic `AbortError` if the consumer
1144
- * didn't supply a reason). The currently-in-flight `kycStatus()`
1145
- * call also receives the signal so it can short-circuit.
1146
- */
1147
- signal?: AbortSignal;
1148
- /**
1149
- * Called with every snapshot the helper receives, including
1150
- * non-terminal `pending` ones. Useful for surfacing intermediate
1151
- * UI states (e.g. "still waiting on provider…"). Errors thrown
1152
- * from this callback are caught and ignored — they must not
1153
- * sink the poll loop.
1154
- */
1155
- onUpdate?: (status: KycStatus) => void;
1156
- /**
1157
- * Override one or more cadence fields. Anything not specified
1158
- * uses the defaults from [[DEFAULT_KYC_POLL_CADENCE]].
1159
- */
1160
- cadence?: Partial<KycPollCadence>;
1061
+ interface MutationResponse {
1161
1062
  /**
1162
- * Provider id to poll. Defaults to the contract default
1163
- * (`"veriff"` in phase one). Mirrored on the wire as
1164
- * `input.provider_id`.
1063
+ * `"created"`, `"updated"`, `"deleted"`, or — for the agent-card mutations —
1064
+ * `"published"` / `"unpublished"`.
1165
1065
  */
1166
- providerId?: string;
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;
1167
1074
  }
1168
1075
  /**
1169
- * Default cadence used by [[T3nClient.kycStatusPoll]] when the caller
1170
- * doesn't override `cadence.*`.
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.
1171
1082
  */
1172
- declare const DEFAULT_KYC_POLL_CADENCE: KycPollCadence;
1083
+ declare function isMutationResponse(value: unknown): value is MutationResponse;
1173
1084
  /**
1174
- * Subset of [[KycStatusKind]] that ends a poll. `pending` is the
1175
- * only non-terminal value.
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>`.
1176
1089
  */
1177
- declare const TERMINAL_KYC_STATUSES: ReadonlySet<KycStatusKind>;
1090
+ interface OrgWriters {
1091
+ writers: string[];
1092
+ }
1093
+ /** Shallow runtime guard for {@link OrgWriters}. */
1094
+ declare function isOrgWriters(value: unknown): value is OrgWriters;
1178
1095
  /**
1179
- * Thrown by [[T3nClient.kycStatusPoll]] when the cadence's
1180
- * `timeoutMs` elapses without a terminal status arriving. The
1181
- * `lastStatus` field is the most recent (necessarily `pending`)
1182
- * snapshot the helper saw, useful for surfacing "we tried for N
1183
- * minutes but Veriff is still working" UX.
1096
+ * Response type alias for org-grants-get.
1097
+ *
1098
+ * The wire body echoes the `contract_id` alongside the grant list.
1184
1099
  */
1185
- declare class KycStatusTimeoutError extends T3nError {
1186
- /** The timeout (ms) the helper exhausted before a terminal status arrived. */
1187
- readonly timeoutMs: number;
1188
- /** The last `pending` snapshot before timeout, if any. */
1189
- readonly lastStatus?: KycStatus | undefined;
1190
- constructor(
1191
- /** The timeout (ms) the helper exhausted before a terminal status arrived. */
1192
- timeoutMs: number,
1193
- /** The last `pending` snapshot before timeout, if any. */
1194
- lastStatus?: KycStatus | undefined);
1100
+ interface OrgContractGrants {
1101
+ contract_id: string;
1102
+ grants: BoundGrant[];
1195
1103
  }
1196
-
1197
1104
  /**
1198
- * Wire types for the explicit `otp-request` /
1199
- * `otp-verify` / slim `user-upsert` exports on `tee:user/contracts`
1200
- * (`tee:user@2.0.0`).
1201
- *
1202
- * Pre-2.0.0 the user contract dispatched OTP request and OTP verify
1203
- * implicitly from the input shape of a single `user-upsert` call.
1204
- * 2.0.0 splits that surface into three explicit functions; the
1205
- * shapes here mirror the OTP / user-upsert wire contract.
1105
+ * Shallow runtime guard for {@link OrgContractGrants}.
1206
1106
  *
1207
- * Bytes flow directly from the contract
1208
- * through the JSON-RPC envelope into the SDK wrappers
1209
- * (`T3nClient.otpRequest`, `T3nClient.otpVerify`,
1210
- * `T3nClient.submitUserInput`).
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.
1211
1111
  */
1212
-
1112
+ declare function isOrgContractGrants(value: unknown): value is OrgContractGrants;
1213
1113
  /**
1214
- * OTP delivery channel. Matches the `OtpContactChannel` Rust enum
1215
- * with `serde(rename_all = "snake_case")`.
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.
1216
1117
  */
1217
- type OtpChannel = "email" | "sms";
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
+ }
1218
1126
  /**
1219
- * Discriminated OTP contact target. Mirrors the Rust `OtpRequest` enum
1127
+ * A role: a named bundle of grants and/or composed sub-roles.
1128
+ * Mirrors the org-data `RoleDefinition` wire shape.
1129
+ */
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
+ }
1140
+ /**
1141
+ * The roles assigned to one grantee within one org.
1142
+ * Mirrors the org-data `RoleAssignments` wire shape.
1143
+ */
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;
1151
+ }
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[];
1160
+ }
1161
+ /** Shallow runtime guard for {@link RoleAssignmentsResponse}. */
1162
+ declare function isRoleAssignmentsResponse(value: unknown): value is RoleAssignmentsResponse;
1163
+ /**
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.
1167
+ */
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;
1174
+ }
1175
+ /**
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.
1181
+ */
1182
+ interface AgentSummary {
1183
+ /** The agent's DID (`did:t3n:<40-hex>`). */
1184
+ 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;
1196
+ }
1197
+ /** A human member's org role. The closed wire domain of {@link HumanMember}. */
1198
+ type MemberRole = "admin" | "member";
1199
+ /**
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.
1203
+ */
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;
1210
+ }
1211
+ /**
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.
1215
+ */
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;
1254
+ }
1255
+ /**
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.
1259
+ */
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;
1271
+ /**
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.
1275
+ */
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;
1310
+ }
1311
+ /** Shallow runtime guard for {@link DataGetResponse}. */
1312
+ declare function isDataGetResponse(value: unknown): value is DataGetResponse;
1313
+ /**
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.
1318
+ */
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;
1327
+ /**
1328
+ * Legacy direct-route org-data envelope shape retained for compatibility.
1329
+ *
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.
1334
+ */
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;
1344
+ }
1345
+
1346
+ /**
1347
+ * Agent-auth grants — the standing on-chain authority a user delegates to
1348
+ * an agent (envelope-free authorisation).
1349
+ *
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).
1371
+ */
1372
+
1373
+ /**
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[];
1411
+ }
1412
+ /**
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.
1418
+ */
1419
+ declare function mergeGrants(existing: BoundGrant[], additions: BoundGrant[]): GrantsMergeResult;
1420
+ /**
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).
1425
+ */
1426
+ declare function mergeDiscoverDids(existing: string[], additions: string[]): string[];
1427
+
1428
+ /**
1429
+ * KYC types for the `tee:user/contracts::kyc-status` short-poll
1430
+ * function.
1431
+ *
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]].
1435
+ */
1436
+
1437
+ /**
1438
+ * Terminal status for a Level 2 KYC verification, plus `pending`.
1439
+ *
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.
1451
+ */
1452
+ type KycStatusKind = "pending" | "verified" | "rejected" | "orphan";
1453
+ /**
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.
1459
+ */
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;
1484
+ }
1485
+ /**
1486
+ * Polling cadence for [[T3nClient.kycStatusPoll]]. Defaults:
1487
+ * poll fast for the first 30 seconds, then back
1488
+ * off, and bail after 5 minutes.
1489
+ */
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;
1497
+ /**
1498
+ * Maximum total time to spend polling before rejecting with
1499
+ * [[KycStatusTimeoutError]]. Default: 300_000 (5 minutes).
1500
+ */
1501
+ timeoutMs: number;
1502
+ }
1503
+ /**
1504
+ * Optional knobs for [[T3nClient.kycStatusPoll]]. Most callers won't
1505
+ * touch any of these — the cadence defaults are baked in.
1506
+ */
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;
1534
+ }
1535
+ /**
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.
1551
+ */
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);
1562
+ }
1563
+
1564
+ /**
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`).
1568
+ *
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.
1573
+ *
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`).
1578
+ */
1579
+
1580
+ /**
1581
+ * OTP delivery channel. Matches the `OtpContactChannel` Rust enum
1582
+ * with `serde(rename_all = "snake_case")`.
1583
+ */
1584
+ type OtpChannel = "email" | "sms";
1585
+ /**
1586
+ * Discriminated OTP contact target. Mirrors the Rust `OtpRequest` enum
1220
1587
  * (`email_channel` / `sms_channel` on the wire). Exactly one branch is
1221
1588
  * set — no parallel optional email + phone with a separate channel tag.
1222
1589
  *
@@ -1784,7 +2151,7 @@ interface ListContractsResult {
1784
2151
  next_offset: number | null;
1785
2152
  }
1786
2153
  /** Which standing grant a satisfied/missing entry refers to. */
1787
- type DelegationGrantKind = "agent_auth" | "user_grant";
2154
+ type DelegationGrantKind = "agent_auth" | "org_grant";
1788
2155
  /** Params for `delegation.check` (the generic capability read). */
1789
2156
  interface GrantCheckParams {
1790
2157
  /** The target contract whose requirements are checked. */
@@ -1805,7 +2172,7 @@ interface DelegationGrantRef {
1805
2172
  scopes: string[];
1806
2173
  }
1807
2174
  /**
1808
- * Response for `delegation.check`: the `agent_auth ∩ UserGrant` verdict.
2175
+ * Response for `delegation.check`: the `agent_auth ∩ org_grant` verdict.
1809
2176
  *
1810
2177
  * `disclosed` is `true` only when the agent is registered under `pii_did`, so
1811
2178
  * org-side status was safe to disclose; `false` yields the uniform,
@@ -1835,8 +2202,8 @@ declare class T3nClient {
1835
2202
  /**
1836
2203
  * Resolved node base URL. Snapshotted in the constructor so the
1837
2204
  * typed contract wrappers (`kycStatus`, `getSelfEthAddress`, …)
1838
- * can call `getScriptVersion()` against the same host the
1839
- * transport talks to. Used only by the `script_version: "latest"`
2205
+ * can call `getContractVersion()` against the same host the
2206
+ * transport talks to. Used only by the `contract_version: "latest"`
1840
2207
  * resolution path in {@link executeUserContract}.
1841
2208
  */
1842
2209
  private readonly effectiveBaseUrl;
@@ -2035,7 +2402,7 @@ declare class T3nClient {
2035
2402
  * Generic capability check (`delegation.check`) — the
2036
2403
  * node-backed source for the MCP `checkDelegation` funnel tool.
2037
2404
  *
2038
- * Returns the `agent_auth ∩ UserGrant` verdict for `(agent, contract,
2405
+ * Returns the `agent_auth ∩ org_grant` verdict for `(agent, contract,
2039
2406
  * pii_did)`: whether the acting agent (resolved from the session) holds the
2040
2407
  * standing grants that `contract`'s `functions` / `scopes` need for member
2041
2408
  * `pii_did`. The org half is vacuous for no-org (Individual-owned) targets,
@@ -2274,10 +2641,10 @@ declare class T3nClient {
2274
2641
  * (org-admin gated; idempotent on an already-absent membership). The host
2275
2642
  * membership gate makes the detach effective immediately.
2276
2643
  * 2. `org-remove-member-grants` — sweep the member from the org's
2277
- * per-contract `UserGrant` lists, so the capability does not silently
2644
+ * per-contract `BoundGrant` lists, so the capability does not silently
2278
2645
  * reactivate if the member later rejoins.
2279
2646
  *
2280
- * The member's `agent_auth` delegations are self-scoped (`AGENT_AUTH_MAP` is a
2647
+ * The member's `agent_auth` delegations are self-scoped (the agent-auth edge in `ROLE_ASSIGNMENTS_MAP` is a
2281
2648
  * per-user document an admin cannot reach), so this cannot sweep them; the host
2282
2649
  * membership gate denies them regardless, and the member's own session can run
2283
2650
  * {@link revokeAgentAuthForOrg} for full cleanup.
@@ -2308,7 +2675,7 @@ declare class T3nClient {
2308
2675
  * Revoke the caller's own agent delegations scoped to one org
2309
2676
  * (detach-cascade `agent_auth` half). Dispatches
2310
2677
  * `agent-auth-revoke-org` on `tee:user/contracts` (**SelfOnly**): every
2311
- * `ScriptGrant` targeting a `z:<orgTid>:*` contract is removed from the
2678
+ * agent-edge grant targeting a `z:<orgTid>:*` contract is removed from the
2312
2679
  * caller's own agent-auth document.
2313
2680
  *
2314
2681
  * @param orgTid - the org's z-space tenant id (`did:t3n:<hex>` or bare
@@ -2320,25 +2687,27 @@ declare class T3nClient {
2320
2687
  * grants delegated to agents. Dispatches `agent-auth-get` on
2321
2688
  * `tee:authorisations/contracts` (the policy's owning contract), which is
2322
2689
  * **SelfOnly**, so this always returns the caller's own
2323
- * `AGENT_AUTH_MAP[self]` document.
2690
+ * agent-auth edge in `ROLE_ASSIGNMENTS_MAP`.
2324
2691
  *
2325
- * @returns the full policy document (normalised to the camelCase write
2326
- * shape): the per-agent `agents` entries plus the document-level
2327
- * `discoverDids` discovery grants
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
2328
2695
  * @throws if the session is not authenticated, or the contract refuses
2329
2696
  */
2330
- getAgentAuth(): Promise<AgentAuthPolicy>;
2697
+ getAgentAuth(): Promise<AgentAuthDoc>;
2331
2698
  /**
2332
2699
  * Authorise an agent for one contract on the caller's own behalf
2333
2700
  * (envelope-free authorisation). Read-merge-writes the
2334
- * caller's `AGENT_AUTH_MAP[self]` document via `agent-auth-update`
2335
- * (**SelfOnly**) with script-level union semantics, so other contracts'
2336
- * grants for this or any agent survive untouched.
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.
2337
2704
  *
2338
- * Carries the new `scopes` + validity fields: the delegated
2339
- * org-data scopes and an optional `[validFromSecs, validUntilSecs]`
2340
- * window. The ≤ cap *length* check is enforced contract-side at write
2341
- * time; the expiry gate is host-side at read time.
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.
2342
2711
  *
2343
2712
  * This is the write surface `getDelegationInstructions` produces the
2344
2713
  * parameters for. The caller MUST be the delegating user, authenticated as
@@ -2350,38 +2719,38 @@ declare class T3nClient {
2350
2719
  * standing discovery), and any `options.discoverDids` are unioned in
2351
2720
  * (order-preserving, deduplicated).
2352
2721
  *
2353
- * @param agentDid - the agent DID being authorised
2354
- * @param grant - the single script grant to set (contract, functions,
2355
- * scopes, validity, egress hosts)
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)
2356
2725
  * @param options - optional `discoverDids` to union into the document's
2357
2726
  * discovery grants (org DIDs for org-mode `listContracts`, the caller's
2358
2727
  * own DID for self mode)
2359
- * @returns the script rows preserved from the existing policy (audit aid)
2728
+ * @returns the grant rows preserved from the existing policy (audit aid)
2360
2729
  * @throws if the session is not authenticated, or the contract refuses
2361
2730
  */
2362
- updateAgentAuth(agentDid: string, grant: AgentAuthScriptGrant, options?: {
2731
+ updateAgentAuth(grant: BoundGrant, options?: {
2363
2732
  discoverDids?: string[];
2364
2733
  }): Promise<{
2365
2734
  preservedRows: string[];
2366
2735
  }>;
2367
2736
  /**
2368
2737
  * Build the canonical `ExecuteActionRequest` shape the server
2369
- * expects (`script_name`, `script_version`, `function_name`, `input`,
2738
+ * expects (`contract_id`, `contract_version`, `function_name`, `input`,
2370
2739
  * optional `pii_did`) and dispatch it through {@link execute}.
2371
2740
  *
2372
2741
  * Two pieces of glue live here that every typed user-contract
2373
2742
  * wrapper would otherwise duplicate:
2374
2743
  *
2375
2744
  * 1. **Field naming.** The server deserialises strictly into
2376
- * `script_name` / `script_version` / `function_name` —
2745
+ * `contract_id` / `contract_version` / `function_name` —
2377
2746
  * sending `contract` / `version` / `function` produces
2378
2747
  * `Invalid action request: missing field …` 400s. Centralising
2379
2748
  * the names here means every wrapper agrees with the server.
2380
- * 2. **`"latest"` resolution.** `script_version` is `SemVer` on
2749
+ * 2. **`"latest"` resolution.** `contract_version` is `SemVer` on
2381
2750
  * the server, so a literal `"latest"` cannot be parsed. We
2382
2751
  * fetch the registered current version via
2383
2752
  * `GET /api/contracts/current?name=…` (cached per script name
2384
- * in `getScriptVersion`) and forward the resolved
2753
+ * in `getContractVersion`) and forward the resolved
2385
2754
  * `MAJOR.MINOR.PATCH` string.
2386
2755
  *
2387
2756
  * Wrappers that need PII delegation can extend this helper
@@ -2646,25 +3015,24 @@ declare class T3nClient {
2646
3015
  */
2647
3016
  submitUserInput(input: SubmitUserInputArgs): Promise<SubmitUserInputResult>;
2648
3017
  /**
2649
- * Replace this user's agent-authorisation policy (`tee:user/contracts` →
2650
- * `agent-auth-update`). The supplied document IS the new state: an empty
2651
- * `agents` array revokes all agent access, and an omitted `discoverDids`
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`
2652
3021
  * persists an empty discovery-grant list. This is the full-document
2653
3022
  * write — use {@link T3nClient.updateAgentAuth} for the single-grant
2654
3023
  * read-merge-write that preserves other contracts' grants and the
2655
3024
  * standing discovery grants.
2656
3025
  *
2657
- * Typed wrapper over the raw contract call: callers pass camelCase input;
2658
- * the SDK emits the canonical snake_case wire via
2659
- * {@link toAgentAuthUpdateWire} (carrying `scopes` / `read_scopes` /
2660
- * validity alongside `functions` / `allowed_hosts`, plus the
2661
- * document-level `discover_dids`), so it does not rely on the contract's
2662
- * compatibility aliases.
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.
2663
3031
  *
2664
3032
  * @throws {RpcError} if the contract rejects the policy (validation failure,
2665
3033
  * too many agents/grants).
2666
3034
  */
2667
- agentAuthUpdate(input: AgentAuthUpdateInput): Promise<void>;
3035
+ agentAuthUpdate(input: AgentAuthDoc): Promise<void>;
2668
3036
  /**
2669
3037
  * Convenience helper: run the explicit OTP roundtrip and submit
2670
3038
  * the slim user-upsert in one call.
@@ -2859,572 +3227,238 @@ declare class T3nClient {
2859
3227
  /**
2860
3228
  * Get the finalized session blob (for `session.encrypt` calls).
2861
3229
  * Populated by `tryFinalize` once the handshake state machine
2862
- * reaches its terminal phase.
2863
- */
2864
- private getSessionState;
2865
- }
2866
-
2867
- /**
2868
- * Guest-to-Host Request Handlers
2869
- *
2870
- * These handle requests from WASM that need the host environment to perform side effects.
2871
- * Examples: signing challenges, providing public keys, generating random bytes.
2872
- */
2873
-
2874
- /**
2875
- * Account — MetaMask handler accepts either a plain address string or an
2876
- * object with an `address` field (for compatibility with various wallet
2877
- * libraries).
2878
- */
2879
- type EthAccount = string | {
2880
- address: string;
2881
- };
2882
- /**
2883
- * Create an EthSign handler using MetaMask (window.ethereum)
2884
- * @param account - MetaMask account (string address or object with address property)
2885
- * @param logger - Optional logger instance. Defaults to a logger using the global log level (LogLevel.ERROR).
2886
- * Pass a custom logger to override logging behavior for this handler.
2887
- * @param privateKey - Optional private key for signing (if provided, MetaMask is not used)
2888
- */
2889
- declare function metamask_sign(account: EthAccount, logger?: Logger, privateKey?: string | undefined): GuestToHostHandler;
2890
- /**
2891
- * Get the current MetaMask address
2892
- * @returns Ethereum address (lowercase, 0x prefixed)
2893
- */
2894
- declare function metamask_get_address(): Promise<string>;
2895
- /**
2896
- * Get the address for a given private key
2897
- * @param privateKey - Ethereum private key (0x prefixed hex string)
2898
- * @returns Ethereum address (lowercase, 0x prefixed)
2899
- */
2900
- declare function eth_get_address(privateKey: string): string;
2901
- /**
2902
- * Create an MlKemPublicKey handler that lazily fetches the root public key
2903
- * from `${baseUrl}/status` on first invocation, verifies it against the
2904
- * DKG attestation trust anchor (SP-003), and caches the encoded response
2905
- * for subsequent calls.
2906
- *
2907
- * @param baseUrl - **Required**. The node URL whose `/status` endpoint should
2908
- * serve the ML-KEM public key. Must be the same URL the
2909
- * T3nClient is constructed with — otherwise the handshake
2910
- * encrypts to one node and sends ciphertext to another.
2911
- *
2912
- * Was optional in 0.3.x, where omitting it caused the lazy
2913
- * fetch to silently fall back to `NODE_URLS[currentEnv]` and
2914
- * hit the wrong node. Three downstream consumers (demo.ts,
2915
- * t3-apps dev wallet hooks, t3n-mcp session manager) all
2916
- * hit this trap before we tightened the type.
2917
- * @param trustAnchor - **Required**. Client-pinned expected peer IDs +
2918
- * RTMR3 allowlist the DKG bundle is verified against, or
2919
- * `{ unsafe_trust_server: true }` to skip verification.
2920
- * The key is only cached/returned once verification passes.
2921
- */
2922
- declare function createMlKemPublicKeyHandler(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandler;
2923
- /**
2924
- * Create Random handler backed by crypto.getRandomValues
2925
- * Note: The Rust Vec<u8> type serializes as an array of bytes, not a base64 string
2926
- */
2927
- declare function createRandomHandler(): GuestToHostHandler;
2928
- /**
2929
- * Create the default handler set required by the T3n handshake.
2930
- *
2931
- * @param baseUrl - **Required**. Forwarded to `createMlKemPublicKeyHandler`
2932
- * so the lazy /status fetch hits the right node.
2933
- * @param trustAnchor - **Required**. Forwarded to the ML-KEM handler so the
2934
- * fetched key is verified against the DKG attestation
2935
- * (SP-003) before the handshake trusts it.
2936
- */
2937
- declare function createDefaultHandlers(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandlers;
2938
-
2939
- /**
2940
- * Stateless `api_key` agent auth.
2941
- *
2942
- * `invoke` posts once to `POST /api/invoke` — an HTTPS-only
2943
- * endpoint (see the HTTPS-guard note below) that authenticates an org agent
2944
- * by an opaque API key (`X-T3N-Api-Key: t3n_key_<...>`) and executes a
2945
- * `z:` contract as that agent in the SAME request. Unlike
2946
- * {@link T3nClient.execute}, there is **no** ML-KEM handshake, **no**
2947
- * `Session-Id`, and **no** session state: the node derives the acting agent
2948
- * DID from the relayed key per-call (`resolve_stateless_credential`
2949
- * driving the session contract's `api_key` action), then runs the same
2950
- * execute pipeline `action.execute` runs after `check_authentication`
2951
- * (`ActionService::execute_as_did`), and returns the contract's decoded
2952
- * result as a plain `Json(result)` body — NOT a JSON-RPC envelope.
2953
- *
2954
- * Because the response is the bare decoded value (no `{jsonrpc,result,id}`
2955
- * wrapper to unwrap), decoding reuses {@link parseContractResponse} — the
2956
- * exact same JSON.parse + optional-schema path {@link T3nClient.executeAndDecode}
2957
- * uses for the session `execute` RPC — so callers get identical typed /
2958
- * schema-validated decoding on either path.
2959
- *
2960
- * This module intentionally does NOT import {@link T3nClient}, the WASM
2961
- * component loader, or any handshake/session machinery — `invoke` is
2962
- * a single fetch, nothing else.
2963
- *
2964
- * ### HTTPS guard (CodeRabbit T2)
2965
- * The API key is a long-lived bearer credential relayed in a plain header,
2966
- * so `invoke` refuses to send it over an insecure transport: `baseUrl`
2967
- * must be `https:`, unless the host is a local-dev loopback
2968
- * (`localhost` / `127.0.0.1` / `[::1]`), in which case plain `http:` is
2969
- * allowed. The check runs before any network activity — an insecure
2970
- * `baseUrl` never gets as far as a `fetch` call.
2971
- *
2972
- * ### Error hygiene (CodeRabbit T3/T4/T5)
2973
- * Every error `invoke` throws is a fixed, generic
2974
- * {@link InvokeError} message — the response body text, the
2975
- * underlying network error's message, and the api key are never
2976
- * interpolated into it. This is defense in depth against a server (or a
2977
- * malicious intermediary) that echoes the key or other secrets back in an
2978
- * error body: whatever comes back over the wire on a non-2xx response is
2979
- * discarded, not surfaced. The timeout timer also stays armed until the
2980
- * response body has been fully read (or has itself timed out) — see
2981
- * {@link invoke}'s implementation — so a connection that delivers
2982
- * headers and then stalls on the body still respects `timeoutMs`.
2983
- */
2984
-
2985
- /**
2986
- * Wire body for `POST /api/invoke` — mirrors the server's
2987
- * server-side `ExecuteActionRequest`, the same shape
2988
- * `T3nClient`'s `execute*` wrappers build for the session `action.execute`
2989
- * RPC. Field names are load-bearing: the server deserialises strictly into
2990
- * `script_name` / `script_version` / `function_name` (see
2991
- * `T3nClient.executeSystemContract`'s doc comment) — `contract` / `version`
2992
- * / `function` produce a 400.
2993
- */
2994
- interface InvokeRequest {
2995
- script_name: string;
2996
- script_version: string;
2997
- function_name: string;
2998
- /** Delegated-call target member; omitted for a self (non-delegated) call. */
2999
- pii_did?: string;
3000
- input?: unknown;
3001
- }
3002
- /** Options for {@link invoke}. */
3003
- interface InvokeOptions {
3004
- /**
3005
- * RPC base URL of the T3n node, e.g. `https://node.example.com`. Must be
3006
- * `https:` unless the host is a local-dev loopback (`localhost` /
3007
- * `127.0.0.1` / `[::1]`) — see the module doc comment's HTTPS-guard note.
3008
- */
3009
- baseUrl: string;
3010
- /**
3011
- * The agent's opaque API key (`t3n_key_<...>`), relayed verbatim in the
3012
- * `X-T3N-Api-Key` header. Never logged and never interpolated into any
3013
- * error this module throws — see the module doc comment and
3014
- * {@link InvokeError}.
3015
- */
3016
- apiKey: string;
3017
- /** The wire request to execute, built to the {@link InvokeRequest} shape. */
3018
- request: InvokeRequest;
3019
- /** Fetch timeout in ms. Defaults to 30s, matching {@link HttpTransport}. */
3020
- timeoutMs?: number;
3021
- }
3022
- /**
3023
- * Thrown when `POST /api/invoke` fails at the transport or HTTP
3024
- * layer (network failure, timeout, non-2xx status). Contract-level errors
3025
- * the node returns as a 2xx JSON error value are NOT wrapped here — they
3026
- * flow through {@link parseContractResponse}'s normal return, same as the
3027
- * session `execute` path.
3028
- *
3029
- * The message is always one of a small set of fixed, generic strings — it
3030
- * NEVER contains the raw api key, the response body text, or the
3031
- * underlying network error's message (CodeRabbit T4/T5): a server (or a
3032
- * misbehaving intermediary) that echoes the key or other secrets back in
3033
- * an error body must not be able to leak them through this error's
3034
- * message.
3035
- */
3036
- declare class InvokeError extends T3nError {
3037
- readonly status?: number | undefined;
3038
- constructor(message: string, status?: number | undefined);
3039
- }
3040
- /**
3041
- * Execute a `z:` contract as an org agent, authenticating with an opaque
3042
- * API key — one request, no handshake, no session.
3043
- *
3044
- * @param opts - baseUrl, apiKey, and the wire request to execute
3045
- * @param schema - optional validator applied to the decoded result (e.g. a
3046
- * zod schema); anything exposing `.parse(value)` is accepted, same as
3047
- * {@link T3nClient.executeAndDecode}
3048
- * @returns the contract's decoded result, typed as `T`
3049
- * @throws {InvokeError} if `baseUrl` is insecure, on a network
3050
- * failure/timeout, or on a non-2xx response
3051
- * @throws {ContractResponseError} if the node returns a 2xx with a body
3052
- * that is not valid JSON
3053
- */
3054
- declare function invoke<T = unknown>(opts: InvokeOptions, schema?: ContractResponseSchema<T>): Promise<T>;
3230
+ * reaches its terminal phase.
3231
+ */
3232
+ private getSessionState;
3233
+ }
3055
3234
 
3056
3235
  /**
3057
- * Token fixed-point units (USDT-style 6 decimals).
3058
- *
3059
- * As of `tee:*` metering v2, every token amount on the wire —
3060
- * {@link BalanceRow}'s `available`/`reserved`, {@link UsageEntry.amount},
3061
- * and `total_supply` — is denominated in **base units**, where
3062
- * `1 T3N token = `{@link BASE_UNITS_PER_TOKEN}` base units`. The node
3063
- * meters the *actual* fractional cost of each operation (pro-rata by
3064
- * bytes / byte-seconds / fuel) down to `1e-6` token, so amounts are
3065
- * raw integers in base units, NOT whole tokens.
3066
- *
3067
- * The wire fields are left as raw base units (no silent rescaling — that
3068
- * would lose precision for large balances and surprise callers doing
3069
- * arithmetic). Use {@link formatTokens} to render a human "tokens"
3070
- * string and {@link toBaseUnits} to convert a token figure back.
3236
+ * Guest-to-Host Request Handlers
3071
3237
  *
3072
- * ⚠️ Breaking vs. the pre-decimals SDK: a balance that used to read `5`
3073
- * (whole tokens) now reads `5_000_000` (base units). Multiply existing
3074
- * display code through {@link formatTokens}.
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.
3075
3240
  */
3076
- /** Decimal places in a T3N token (fixed; mirrors the node constant). */
3077
- declare const TOKEN_DECIMALS = 6;
3078
- /** Base units per whole T3N token — `10 ** TOKEN_DECIMALS`. */
3079
- declare const BASE_UNITS_PER_TOKEN = 1000000;
3241
+
3080
3242
  /**
3081
- * Render a base-unit amount as a human-readable token string, e.g.
3082
- * `25_920_000 → "25.92"`, `1_000_000 → "1"`, `4768 → "0.004768"`.
3083
- *
3084
- * Trailing-zero fraction digits are trimmed; an integer amount renders
3085
- * with no decimal point. Accepts `number` or `bigint`; for balances
3086
- * above `Number.MAX_SAFE_INTEGER` prefer passing a `bigint`.
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).
3087
3246
  */
3088
- declare function formatTokens(baseUnits: number | bigint): string;
3247
+ type EthAccount = string | {
3248
+ address: string;
3249
+ };
3089
3250
  /**
3090
- * Convert a whole-or-fractional token figure to base units (rounded to
3091
- * the nearest base unit). E.g. `25.92 → 25_920_000`, `1 → 1_000_000`.
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)
3092
3256
  */
3093
- declare function toBaseUnits(tokens: number): number;
3094
-
3257
+ declare function metamask_sign(account: EthAccount, logger?: Logger, privateKey?: string | undefined): GuestToHostHandler;
3095
3258
  /**
3096
- * Org-data wire types mirroring the org-data contract wire shapes.
3097
- *
3098
- * Plain TypeScript interfaces (no zod) — the SDK does not use a
3099
- * validation library for domain types; see the existing `types/` files.
3100
- *
3101
- * Each response type below is paired with a shallow runtime predicate
3102
- * (`isMutationResponse`, `isOrgPolicyMeta`, etc.) so the org-data client
3103
- * can `assertShape` the decoded payload before returning to callers.
3104
- * Predicates check the top-level structure only; nested elements
3105
- * (e.g. each `UserGrant` inside `OrgContractGrants.grants`) are not
3106
- * deeply validated — see `utils/shape.ts` for the rationale.
3107
- *
3108
- * Reference: the org-data wire contract.
3259
+ * Get the current MetaMask address
3260
+ * @returns Ethereum address (lowercase, 0x prefixed)
3109
3261
  */
3262
+ declare function metamask_get_address(): Promise<string>;
3110
3263
  /**
3111
- * Capability grant stored under `ORG_CONTRACT_GRANTS_MAP`.
3112
- *
3113
- * Mirrors the org-data `UserGrant` wire shape.
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)
3114
3267
  */
3115
- interface UserGrant {
3116
- /** The user this grant applies to (`did:t3n:<40-hex>`). */
3117
- user_did: string;
3118
- /** WIT function names the user may invoke (e.g. `"set-records"`). */
3119
- functions: string[];
3120
- /** Data scope paths the user may access (e.g. `"example/records"`). */
3121
- scopes: string[];
3122
- }
3268
+ declare function eth_get_address(privateKey: string): string;
3123
3269
  /**
3124
- * Policy record for an organisation's data tier.
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.
3125
3274
  *
3126
- * Mirrors the org-data policy-meta wire shape.
3127
- */
3128
- interface OrgPolicyMeta {
3129
- /** DIDs (`did:t3n:<40-hex>`) of users authorised to manage policy and read data. */
3130
- admins: string[];
3131
- /** Maximum number of admins allowed for this org. */
3132
- max_admins: number;
3133
- /** Unix timestamp (secs) when the policy was first created. */
3134
- created_at_secs: number;
3135
- /** Unix timestamp (secs) of the most recent policy update. */
3136
- updated_at_secs: number;
3137
- /**
3138
- * Per-org ceiling on delegation-credential validity (seconds).
3139
- *
3140
- * Absent when no org-level cap is set — the contract omits the field
3141
- * (never serialises null) and the cluster-wide
3142
- * `delegation.max_credential_validity_secs` governs instead. When set,
3143
- * the effective cap is `min(max_credential_validity_secs, cluster_ceiling)`.
3144
- */
3145
- max_credential_validity_secs?: number;
3146
- }
3147
- /** Shallow runtime guard for {@link OrgPolicyMeta}. */
3148
- declare function isOrgPolicyMeta(value: unknown): value is OrgPolicyMeta;
3149
- /**
3150
- * Effective org policy view returned by `org-policy-view`.
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.
3151
3279
  *
3152
- * Readable by any authenticated session (non-sensitive metadata).
3153
- * Returns the **effective** credential validity cap:
3154
- * `min(org.max_credential_validity_secs, cluster_ceiling)`, equal to the
3155
- * cluster ceiling when the org has not set a per-org cap. The contract
3156
- * always returns a value (or errors) — the field is never null.
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.
3157
3289
  */
3158
- interface OrgPolicyView {
3159
- /**
3160
- * Effective delegation-credential validity cap in seconds:
3161
- * `min(org value, cluster ceiling)`, equal to the cluster ceiling when the
3162
- * org has not set a per-org cap. Always present — mirrors the contract's
3163
- * `PolicyViewResponse.effective_validity_secs` (org-data `org-policy-view`).
3164
- */
3165
- effective_validity_secs: number;
3166
- }
3167
- /** Shallow runtime guard for {@link OrgPolicyView}. */
3168
- declare function isOrgPolicyView(value: unknown): value is OrgPolicyView;
3290
+ declare function createMlKemPublicKeyHandler(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandler;
3169
3291
  /**
3170
- * Caller-scoped admin status returned by `org-am-i-admin`.
3171
- *
3172
- * Reports only whether the **calling** session's DID is in the org's admin
3173
- * list — never the roster itself (contrast {@link OrgPolicyMeta}, returned by
3174
- * the admin-gated `org-policy-get`). Readable by any authenticated session.
3175
- * Mirrors the org-data `AmIAdminResponse` wire shape.
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
3176
3294
  */
3177
- interface OrgAdminStatus {
3178
- /** Whether the calling session is an admin of the queried org. */
3179
- is_admin: boolean;
3180
- }
3181
- /** Shallow runtime guard for {@link OrgAdminStatus}. */
3182
- declare function isOrgAdminStatus(value: unknown): value is OrgAdminStatus;
3295
+ declare function createRandomHandler(): GuestToHostHandler;
3183
3296
  /**
3184
- * Standard response returned by all policy write and data mutation operations.
3297
+ * Create the default handler set required by the T3n handshake.
3185
3298
  *
3186
- * Mirrors the org-data `MutationResponse` wire shape.
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.
3187
3304
  */
3188
- interface MutationResponse {
3189
- /**
3190
- * `"created"`, `"updated"`, `"deleted"`, or — for the agent-card mutations —
3191
- * `"published"` / `"unpublished"`.
3192
- */
3193
- status: string;
3194
- /** Hex-encoded entry ID; present on data write/delete operations. */
3195
- entry_id?: string;
3196
- /** Whether the target key existed before deletion; present on single-entry deletes. */
3197
- deleted?: boolean;
3198
- /** Number of entries removed; present on `org-data-delete-scope`. */
3199
- deleted_entries?: number;
3200
- tx_hash: string | null;
3201
- }
3305
+ declare function createDefaultHandlers(baseUrl: string, trustAnchor: TrustAnchorOrUnsafe): GuestToHostHandlers;
3306
+
3202
3307
  /**
3203
- * Shallow runtime guard for {@link MutationResponse}.
3308
+ * Stateless `api_key` agent auth.
3204
3309
  *
3205
- * Only the always-present fields are checked — `status` is mandatory on
3206
- * every mutation; `tx_hash` is non-optional but nullable. The optional
3207
- * fields (`entry_id`, `deleted`, `deleted_entries`) are not validated
3208
- * because their presence depends on which mutation ran.
3209
- */
3210
- declare function isMutationResponse(value: unknown): value is MutationResponse;
3211
- /**
3212
- * Response type alias for org-writers-get.
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.
3213
3321
  *
3214
- * The wire body is `{ writers: string[] }` where each entry is
3215
- * `did:t3n:<40-hex>`.
3216
- */
3217
- interface OrgWriters {
3218
- writers: string[];
3219
- }
3220
- /** Shallow runtime guard for {@link OrgWriters}. */
3221
- declare function isOrgWriters(value: unknown): value is OrgWriters;
3222
- /**
3223
- * Response type alias for org-grants-get.
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.
3224
3327
  *
3225
- * The wire body echoes the `contract_id` alongside the grant list.
3226
- */
3227
- interface OrgContractGrants {
3228
- contract_id: string;
3229
- grants: UserGrant[];
3230
- }
3231
- /**
3232
- * Shallow runtime guard for {@link OrgContractGrants}.
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.
3233
3331
  *
3234
- * Validates the immediate envelope (`contract_id: string`, `grants:
3235
- * array`) without recursing into each `UserGrant`. The Rust contract
3236
- * is the source of truth for grant element shape; widening the predicate
3237
- * here would create maintenance churn against benign field additions.
3238
- */
3239
- declare function isOrgContractGrants(value: unknown): value is OrgContractGrants;
3240
- /**
3241
- * One grant inside a role: a {@link UserGrant} body (without the
3242
- * grantee, which is bound at assignment time) plus the target contract.
3243
- * Mirrors the org-data `RoleGrant` wire shape.
3244
- */
3245
- interface RoleGrant {
3246
- /** Target contract (canonical name, e.g. `"tee:z-payroll/contracts"`). */
3247
- contract_id: string;
3248
- /** WIT function names this grant confers. */
3249
- functions: string[];
3250
- /** Data scope paths this grant confers (canonicalised lowercase). */
3251
- scopes: string[];
3252
- }
3253
- /**
3254
- * A role: a named bundle of grants and/or composed sub-roles.
3255
- * Mirrors the org-data `RoleDefinition` wire shape.
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`.
3256
3351
  */
3257
- interface RoleDefinition {
3258
- /** Org-unique role identifier (slug; function-name grammar). */
3259
- role_id: string;
3260
- /** Human-facing label. */
3261
- label: string;
3262
- /** Composite: other role ids in the same org whose grants this role confers. */
3263
- includes: string[];
3264
- /** Grants this role confers directly. */
3265
- grants: RoleGrant[];
3266
- }
3352
+
3267
3353
  /**
3268
- * The roles assigned to one grantee within one org.
3269
- * Mirrors the org-data `RoleAssignments` wire shape.
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.
3270
3361
  */
3271
- interface RoleAssignments {
3272
- /** Assigned role ids. */
3273
- roles: string[];
3274
- }
3275
- /** Response for `org-role-get`; `role` is `null` when the id is unknown. */
3276
- interface RoleGetResponse {
3277
- role: RoleDefinition | null;
3278
- }
3279
- /** Shallow runtime guard for {@link RoleGetResponse}. */
3280
- declare function isRoleGetResponse(value: unknown): value is RoleGetResponse;
3281
- /** Response for `org-role-assignments-get`. */
3282
- interface RoleAssignmentsResponse {
3283
- /** Echoed back so callers don't need to track which request this answers. */
3284
- grantee_did: string;
3285
- /** The grantee's assigned role ids (empty when none). */
3286
- roles: string[];
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;
3287
3369
  }
3288
- /** Shallow runtime guard for {@link RoleAssignmentsResponse}. */
3289
- declare function isRoleAssignmentsResponse(value: unknown): value is RoleAssignmentsResponse;
3290
- /** The (org) key for `listAgents` — mirrors the contract's `OrgOnlyInput`. */
3291
- interface ListAgentsInput {
3292
- orgDid: string;
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;
3293
3389
  }
3294
3390
  /**
3295
- * One org-owned agent in a {@link ListAgentsResponse}: the agent's DID, its
3296
- * display name, and the number of distinct contracts it can access via a direct
3297
- * grant. Mirrors the org-data `AgentSummary` wire shape. The name comes from the
3298
- * agent's private card (falling back to the DID), so the FE no longer needs to
3299
- * fetch each `public:agent_cards` entry to render the roster.
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.
3300
3403
  */
3301
- interface AgentSummary {
3302
- /** The agent's DID (`did:t3n:<40-hex>`). */
3303
- did: string;
3304
- /** The agent's display name, from its private card (DID when unavailable). */
3305
- name: string;
3306
- /** Count of distinct contracts the agent holds a direct grant on. */
3307
- contract_count: number;
3308
- }
3309
- /** Response for `org-data-list-agents`. */
3310
- interface ListAgentsResponse {
3311
- /** The org's org-owned agents, sorted by DID. */
3312
- agents: AgentSummary[];
3313
- }
3314
- /** Shallow runtime guard for {@link ListAgentsResponse}. */
3315
- declare function isListAgentsResponse(value: unknown): value is ListAgentsResponse;
3316
- /** Response for `org-data-list`. */
3317
- interface DataListResponse {
3318
- /** Hex-encoded entry IDs for this page. */
3319
- entry_ids: string[];
3320
- /** Offset to pass for the next page. `null` when this is the last page. */
3321
- next_offset: number | null;
3322
- /** Total number of entries in the scope (across all pages). */
3323
- total: number;
3324
- }
3325
- /** Shallow runtime guard for {@link DataListResponse}. */
3326
- declare function isDataListResponse(value: unknown): value is DataListResponse;
3327
- /** Secret shape discriminator (mirrors the contract `SecretKind`). */
3328
- type SecretKind = "single_value" | "json";
3329
- /** Metadata common to every {@link SecretView} entry. */
3330
- interface SecretViewBase {
3331
- /** Secret name (the `(org, name)` key tail). */
3332
- name: string;
3333
- /** Monotonic version, bumped on each value rotation and ACL edit. */
3334
- version: number;
3335
- /** Unix seconds of the most recent write. */
3336
- updated_at_secs: number;
3404
+ declare class InvokeError extends T3nError {
3405
+ readonly status?: number | undefined;
3406
+ constructor(message: string, status?: number | undefined);
3337
3407
  }
3338
3408
  /**
3339
- * The redacted per-secret summary `org-secret-list` returns — a discriminated
3340
- * union on `kind`. The value is NEVER present: a single-value exposes only its
3341
- * last four characters and a json secret only its sorted top-level field names.
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
3342
3421
  */
3343
- type SecretView = (SecretViewBase & {
3344
- kind: "single_value";
3345
- /** Last four characters of the value (whole value when ≤ 4 chars). */
3346
- last4: string;
3347
- }) | (SecretViewBase & {
3348
- kind: "json";
3349
- /** Sorted top-level object field names (keys only, no values). */
3350
- field_names: string[];
3351
- });
3352
- /** Shallow runtime guard for {@link SecretView}. */
3353
- declare function isSecretView(value: unknown): value is SecretView;
3422
+ declare function invoke<T = unknown>(opts: InvokeOptions, schema?: ContractResponseSchema<T>): Promise<T>;
3423
+
3354
3424
  /**
3355
- * Full secret record returned by `org-secret-get` — the value IS included
3356
- * (the deliberate read-back path the READ axis exists for), along with all
3357
- * three ACLs.
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}.
3358
3443
  */
3359
- interface SecretRecord {
3360
- name: string;
3361
- kind: SecretKind;
3362
- /** The value as text: the scalar for a single-value, canonical JSON object for a json secret. */
3363
- value: string;
3364
- version: number;
3365
- /** READ axis — DIDs allowed to read the value back. */
3366
- reader_dids: string[];
3367
- /** READ axis — role ids allowed to read the value back. */
3368
- reader_roles: string[];
3369
- /** MANAGE axis — DIDs allowed to rotate the value. */
3370
- manager_dids: string[];
3371
- /** MANAGE axis — role ids allowed to rotate the value. */
3372
- manager_roles: string[];
3373
- /** USE axis — canonical contract ids allowed to have the value injected. */
3374
- contract_allowlist: string[];
3375
- created_at_secs: number;
3376
- updated_at_secs: number;
3377
- /** DID of the caller who last wrote the record. */
3378
- updated_by: string;
3379
- }
3380
- /** Shallow runtime guard for {@link SecretRecord}. */
3381
- declare function isSecretRecord(value: unknown): value is SecretRecord;
3382
- /** Response for `org-secret-list`: redacted per-kind views, no values. */
3383
- interface SecretListResponse {
3384
- secrets: SecretView[];
3385
- }
3386
- /** Shallow runtime guard for {@link SecretListResponse}. */
3387
- declare function isSecretListResponse(value: unknown): value is SecretListResponse;
3388
- /** Response for `org-data-get`. */
3389
- interface DataGetResponse {
3390
- entry_id: string;
3391
- /** Hex-encoded raw payload bytes. */
3392
- payload_hex: string;
3393
- }
3394
- /** Shallow runtime guard for {@link DataGetResponse}. */
3395
- declare function isDataGetResponse(value: unknown): value is DataGetResponse;
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;
3396
3448
  /**
3397
- * Return shape of `agentCardGet` — composed client-side from the generic
3398
- * `org-data-get` read of the card's entry (there is no card-specific read
3399
- * operation on the contract). To check whether a public copy exists, probe
3400
- * the anonymous `GET /api/agent-card/{did}` endpoint.
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`.
3401
3455
  */
3402
- interface AgentCardResponse {
3403
- /** The agent whose card this is (`did:t3n:<40-hex>`). */
3404
- agent_did: string;
3405
- /** The stored card JSON body, verbatim. */
3406
- card: string;
3407
- }
3408
- /** Shallow runtime guard for {@link AgentCardResponse}. */
3409
- declare function isAgentCardResponse(value: unknown): value is AgentCardResponse;
3456
+ declare function formatTokens(baseUnits: number | bigint): string;
3410
3457
  /**
3411
- * Legacy direct-route org-data envelope shape retained for compatibility.
3412
- *
3413
- * This mirrors the removed `/api/user-contract/execute` body format from
3414
- * the transitional transport. New callers should use `OrgDataClient`,
3415
- * which now dispatches through authenticated `/api/rpc` +
3416
- * `action.execute` instead.
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`.
3417
3460
  */
3418
- interface OrgDataActionWire {
3419
- nonce: string;
3420
- user_did: string;
3421
- authenticator_id: string;
3422
- contract_id: string;
3423
- function: string;
3424
- args_hash: string;
3425
- expires_at_secs: number;
3426
- signature: string;
3427
- }
3461
+ declare function toBaseUnits(tokens: number): number;
3428
3462
 
3429
3463
  /**
3430
3464
  * OrgDataClient — typed wrapper over the existing authenticated
@@ -3497,10 +3531,17 @@ interface SetWritersInput {
3497
3531
  scope: string;
3498
3532
  writers: string[];
3499
3533
  }
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">;
3500
3541
  interface SetGrantsInput {
3501
3542
  orgDid: string;
3502
3543
  contractId: string;
3503
- grants: UserGrant[];
3544
+ grants: SetGrantInput[];
3504
3545
  }
3505
3546
  interface DeleteGrantsInput {
3506
3547
  orgDid: string;
@@ -3762,7 +3803,7 @@ declare class OrgDataClient {
3762
3803
  /** Delete a secret entirely (org-admin only). */
3763
3804
  secretDelete(input: SecretNameInput): Promise<MutationResponse>;
3764
3805
  /**
3765
- * Full replacement of the user-grant list for a contract.
3806
+ * Full replacement of the org's grant list for a contract.
3766
3807
  *
3767
3808
  * Passing an empty list removes the entry.
3768
3809
  */
@@ -3787,11 +3828,15 @@ declare class OrgDataClient {
3787
3828
  /** Read a grantee's assigned role ids (org-admin only). */
3788
3829
  getRoleAssignments(input: GranteeInput): Promise<RoleAssignmentsResponse>;
3789
3830
  /**
3790
- * List the org's org-owned agents, each with its display name and the number
3791
- * of distinct contracts it can access via a direct grant (org-admin only).
3831
+ * List ONE PAGE of the org's org-owned agents, each with its display name and
3832
+ * the number of distinct contracts it can access via a direct grant
3833
+ * (org-admin only).
3792
3834
  *
3793
- * The name comes from the agent's private card (falling back to the DID), so
3794
- * the caller renders the roster without fetching each agent's card.
3835
+ * The response carries at most `limit` agents plus an optional `next_cursor`;
3836
+ * to enumerate every agent, pass the returned `next_cursor` back as `cursor`
3837
+ * until it is absent. The name comes from the agent's private card (falling
3838
+ * back to the DID), so the caller renders the roster without fetching each
3839
+ * agent's card.
3795
3840
  *
3796
3841
  * Rides the generic contract-execute funnel (`this.call` →
3797
3842
  * `executeOrgDataAction` → `client.executeAndDecode`) like every other
@@ -3799,6 +3844,17 @@ declare class OrgDataClient {
3799
3844
  * access is not counted.
3800
3845
  */
3801
3846
  listAgents(input: ListAgentsInput): Promise<ListAgentsResponse>;
3847
+ /**
3848
+ * List ONE PAGE of the org's direct HUMAN members, each with its org role
3849
+ * (`admin`|`member`) (org-admin only). A human is a member absent from the
3850
+ * agent registry — the exact complement of {@link listAgents}.
3851
+ *
3852
+ * No profile PII (name/email) is returned; the roster is DID + role only
3853
+ * (AI-175). The response carries at most `limit` members plus an optional
3854
+ * `next_cursor`; to enumerate every member, pass the returned `next_cursor`
3855
+ * back as `cursor` until it is absent.
3856
+ */
3857
+ listHumanMembers(input: ListHumanMembersInput): Promise<ListHumanMembersResponse>;
3802
3858
  /**
3803
3859
  * Write a data entry to the org's scope.
3804
3860
  *
@@ -3826,7 +3882,7 @@ declare class OrgDataClient {
3826
3882
  purgeOrg(input: PurgeOrgInput): Promise<MutationResponse>;
3827
3883
  /**
3828
3884
  * Detach-cascade grant sweep: drop `memberDid` from every
3829
- * one of the org's per-contract `UserGrant` lists. Authorised for an
3885
+ * one of the org's per-contract `BoundGrant` lists. Authorised for an
3830
3886
  * org-admin of the subject, or the member removing their own grants.
3831
3887
  * `deleted_entries` reports how many contract grant lists were rewritten.
3832
3888
  */
@@ -3973,6 +4029,8 @@ declare class SessionOrgDataClient {
3973
4029
  getRoleAssignments(input: GranteeInput): Promise<RoleAssignmentsResponse>;
3974
4030
  /** Mirrors {@link OrgDataClient.listAgents}. */
3975
4031
  listAgents(input: ListAgentsInput): Promise<ListAgentsResponse>;
4032
+ /** Mirrors {@link OrgDataClient.listHumanMembers}. */
4033
+ listHumanMembers(input: ListHumanMembersInput): Promise<ListHumanMembersResponse>;
3976
4034
  /** Mirrors {@link OrgDataClient.writeData}. */
3977
4035
  writeData(input: WriteDataInput): Promise<MutationResponse>;
3978
4036
  /** Mirrors {@link OrgDataClient.deleteData}. */
@@ -4022,7 +4080,7 @@ declare function createOrgDataClientFromSession(t3n: T3nClient, baseUrl: string)
4022
4080
  *
4023
4081
  * Envelope-free authorisation removed the per-call delegation
4024
4082
  * credential and envelope entirely: authority is now the standing on-chain
4025
- * `agent_auth` ∩ `UserGrant` intersection the host re-reads every call, and
4083
+ * `agent_auth` ∩ `org_grant` intersection the host re-reads every call, and
4026
4084
  * every payroll call emits the plain Direct wire variant (`{ request }`).
4027
4085
  * What remains here is the request body shape, its canonical defaults, and
4028
4086
  * the base64url / DID helpers callers still need.
@@ -4241,7 +4299,7 @@ declare function stringToBytes(str: string): Uint8Array;
4241
4299
  */
4242
4300
  declare function bytesToString(bytes: Uint8Array): string;
4243
4301
 
4244
- declare function getScriptVersion(rpcUrl: string, scriptName: string): Promise<string>;
4302
+ declare function getContractVersion(rpcUrl: string, contractId: string): Promise<string>;
4245
4303
 
4246
4304
  /**
4247
4305
  * Secret redaction utilities for T3n SDK
@@ -4283,7 +4341,7 @@ declare function redactSecretsFromJson(jsonString: string): string;
4283
4341
  *
4284
4342
  * Predicates are intentionally shallow — they validate the immediate
4285
4343
  * top-level structure (object kind, presence/type of leading fields)
4286
- * but do not deeply validate nested elements (e.g. each `UserGrant`
4344
+ * but do not deeply validate nested elements (e.g. each `BoundGrant`
4287
4345
  * inside `OrgContractGrants.grants`). Deep validation would be brittle
4288
4346
  * against benign contract additions; shallow guards catch the failure
4289
4347
  * modes that actually surface as runtime crashes (null/string/missing
@@ -4564,7 +4622,7 @@ interface TenantBaseClient {
4564
4622
  }
4565
4623
  interface TenantClientConfig {
4566
4624
  environment?: TenantSdkEnvironment;
4567
- /** Node URL for `getScriptVersion` during business contract execution. Falls back to `baseUrl`. */
4625
+ /** Node URL for `getContractVersion` during business contract execution. Falls back to `baseUrl`. */
4568
4626
  endpoint?: string;
4569
4627
  /**
4570
4628
  * Authenticated base client the TenantClient dispatches RPCs through.
@@ -4581,7 +4639,7 @@ interface TenantClientConfig {
4581
4639
  t3n?: TenantBaseClient;
4582
4640
  baseUrl?: string;
4583
4641
  tenantDid?: string;
4584
- tenantScriptName?: string;
4642
+ tenantContractId?: string;
4585
4643
  }
4586
4644
  type TenantStatus = "pending" | "active" | "suspended";
4587
4645
  interface TenantMeResponse {
@@ -5031,5 +5089,5 @@ declare function tenantDidHex(tenantDid: string): string;
5031
5089
  declare function validateTail(tail: string): string;
5032
5090
  declare function canonicalTenantName(tenantDid: string, tail: string): string;
5033
5091
 
5034
- 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, 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 };
5035
- 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, InvokeOptions, InvokeRequest, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, ListAgentsInput, ListAgentsResponse, ListContractsParams, ListContractsResult, ListContractsScope, ListedContract, Logger, MapCreateInput, MapLifecycleStatus, MapResponse, MapUpdateInput, MapVisibility, 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, UserGrant, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult, WireBlock, WorkloadAuthInput, WriteDataInput, WriterSet, WritersGetInput };
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 };