@terminal3/t3n-sdk 3.17.0 → 4.0.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
@@ -725,29 +725,6 @@ declare class UserUpsertError extends T3nError {
725
725
  */
726
726
  static fromWire(raw: string): UserUpsertError | null;
727
727
  }
728
- /** One contract-scoped grant for an agent. Wire form is snake_case
729
- * (`script_name` / `version_req` / `allowed_hosts`); `agentAuthUpdate`
730
- * performs the conversion. */
731
- interface AgentScriptGrant {
732
- scriptName: string;
733
- /** SemVer requirement (e.g. `"^1.0.0"`). Omit / null = any version. */
734
- versionReq?: string | null;
735
- /** Allowed function names. Omit / null = all functions. */
736
- functions?: string[] | null;
737
- /** Allowed outbound HTTP hosts. Omit = none. */
738
- allowedHosts?: string[];
739
- }
740
- /** Per-agent authorisation grant binding an agent DID to its script grants. */
741
- interface AgentGrantInput {
742
- agentDid: string;
743
- scripts: AgentScriptGrant[];
744
- }
745
- /** Input to {@link T3nClient.agentAuthUpdate}. The document IS the new state:
746
- * an empty `agents` list revokes all agent access. Mirrors the contract
747
- * `AgentAuthPolicy`. */
748
- interface AgentAuthUpdateInput {
749
- agents: AgentGrantInput[];
750
- }
751
728
 
752
729
  /**
753
730
  * Org-data wire types mirroring the org-data contract wire shapes.
@@ -1401,6 +1378,93 @@ declare class ContractResponseError extends T3nError {
1401
1378
  */
1402
1379
  declare function parseContractResponse<T = unknown>(raw: string, schema?: ContractResponseSchema<T>): T;
1403
1380
 
1381
+ /**
1382
+ * Agent-auth grants — the standing on-chain authority a user delegates to
1383
+ * an agent (envelope-free authorisation).
1384
+ *
1385
+ * `AGENT_AUTH_MAP` is keyed by the *user* DID — one policy document per
1386
+ * user, global across orgs, with at most one entry per agent DID. Reads
1387
+ * (`agent-auth-get`) and writes (`agent-auth-update`) on
1388
+ * `tee:user/contracts` are **SelfOnly**: only the user, authenticated as
1389
+ * themselves, may read or write their own grants. This is the user-approval
1390
+ * proof the per-call delegation credential's `user_sig` used to carry.
1391
+ *
1392
+ * The write shape gained `scopes` + a validity window: the
1393
+ * agent's delegated org-data scopes, and an optional `[valid_from_secs,
1394
+ * valid_until_secs]` window. The ≤ cap *length* check is enforced contract-
1395
+ * side at write time; the expiry gate is host-side at read time.
1396
+ *
1397
+ * The merge below is a script-level union (R59): writing a grant for one
1398
+ * `(agent_did, script_name)` preserves every other script row on that
1399
+ * agent's entry, and every other agent's entry, unchanged.
1400
+ */
1401
+ /** A single script grant in the camelCase write-request shape. */
1402
+ interface AgentAuthScriptGrant {
1403
+ /** Contract name, or `"*"`. */
1404
+ scriptName: string;
1405
+ /** Optional semver requirement; `null` to match any version. */
1406
+ versionReq?: string | null;
1407
+ /** Functions the agent may invoke on this contract. */
1408
+ functions: string[];
1409
+ /** Org-data scopes delegated to the agent for the contract functions to
1410
+ * read on its behalf. */
1411
+ scopes?: string[];
1412
+ /** Direct-read scopes the agent may enumerate itself, via whichever read
1413
+ * function the contract exposes for direct enumeration. A strict subset of
1414
+ * `scopes` (enforced contract-side). */
1415
+ readScopes?: string[];
1416
+ /** Optional validity-window start (unix seconds). */
1417
+ validFromSecs?: number | null;
1418
+ /** NEW: optional validity-window end (unix seconds). */
1419
+ validUntilSecs?: number | null;
1420
+ /** Egress hosts the agent may reach for this contract. */
1421
+ allowedHosts: string[];
1422
+ }
1423
+ /** One agent's entry in the write-request shape. */
1424
+ interface AgentAuthEntry {
1425
+ agentDid: string;
1426
+ scripts: AgentAuthScriptGrant[];
1427
+ }
1428
+ /** Extract the `agents` array from an `agent-auth-get` response. */
1429
+ declare function parseAgentAuthGet(response: unknown): AgentAuthEntry[];
1430
+ interface AgentAuthMergeResult {
1431
+ /** Full merged `agents` list, ready for `agent-auth-update`. */
1432
+ agents: AgentAuthEntry[];
1433
+ /** `"<agentDid> → <scriptName>"` rows preserved from the existing policy. */
1434
+ preservedRows: string[];
1435
+ }
1436
+ /** Input to the full-document write {@link T3nClient.agentAuthUpdate}. The
1437
+ * document IS the new state: an empty `agents` list revokes all agent
1438
+ * access. Mirrors the contract `AgentAuthPolicy`. */
1439
+ interface AgentAuthUpdateInput {
1440
+ agents: AgentAuthEntry[];
1441
+ }
1442
+ /**
1443
+ * Serialise a camelCase `agents` list to the contract's canonical
1444
+ * snake_case `agent-auth-update` wire (`agent_did` / `script_name` /
1445
+ * `version_req` / `read_scopes` / `valid_from_secs` / `valid_until_secs` /
1446
+ * `allowed_hosts`), so neither write path relies on the contract's
1447
+ * compatibility aliases. Absent optionals are omitted (never sent as
1448
+ * `null`); empty `scopes` / `read_scopes` are omitted (the contract
1449
+ * defaults both to empty). `functions` and `allowed_hosts` are always
1450
+ * emitted — the contract requires explicit functions (`["*"]` = all) and
1451
+ * reads an absent `allowed_hosts` as deny-all egress.
1452
+ */
1453
+ declare function toAgentAuthUpdateWire(agents: AgentAuthEntry[]): {
1454
+ agents: Array<{
1455
+ agent_did: string;
1456
+ scripts: Array<Record<string, unknown>>;
1457
+ }>;
1458
+ };
1459
+ /**
1460
+ * Merge new agent entries into the existing policy with script-level union
1461
+ * semantics: for an agent DID present on both sides, script rows whose
1462
+ * `scriptName` is not being written are preserved; rows with a matching
1463
+ * `scriptName` are replaced by the new grant. Entries for other agent DIDs
1464
+ * pass through unchanged.
1465
+ */
1466
+ declare function mergeAgentAuthEntries(existing: AgentAuthEntry[], newEntries: AgentAuthEntry[]): AgentAuthMergeResult;
1467
+
1404
1468
  /**
1405
1469
  * KYC types for the `tee:user/contracts::kyc-status` short-poll
1406
1470
  * function.
@@ -1747,6 +1811,41 @@ declare class T3nClient {
1747
1811
  * empty / too long)
1748
1812
  */
1749
1813
  createOrganisation(name: string): Promise<Did>;
1814
+ /**
1815
+ * Read the authenticated user's own agent-auth policy — the standing
1816
+ * grants delegated to agents. Dispatches `agent-auth-get` on
1817
+ * `tee:user/contracts`, which is **SelfOnly**, so this always returns the
1818
+ * caller's own `AGENT_AUTH_MAP[self]` document.
1819
+ *
1820
+ * @returns the `agents` entries (normalised to the camelCase write shape)
1821
+ * @throws if the session is not authenticated, or the contract refuses
1822
+ */
1823
+ getAgentAuth(): Promise<AgentAuthEntry[]>;
1824
+ /**
1825
+ * Authorise an agent for one contract on the caller's own behalf
1826
+ * (envelope-free authorisation). Read-merge-writes the
1827
+ * caller's `AGENT_AUTH_MAP[self]` document via `agent-auth-update`
1828
+ * (**SelfOnly**) with script-level union semantics, so other contracts'
1829
+ * grants for this or any agent survive untouched.
1830
+ *
1831
+ * Carries the new `scopes` + validity fields: the delegated
1832
+ * org-data scopes and an optional `[validFromSecs, validUntilSecs]`
1833
+ * window. The ≤ cap *length* check is enforced contract-side at write
1834
+ * time; the expiry gate is host-side at read time.
1835
+ *
1836
+ * This is the write surface `getDelegationInstructions` produces the
1837
+ * parameters for. The caller MUST be the delegating user, authenticated as
1838
+ * themselves — only they may create their own grant.
1839
+ *
1840
+ * @param agentDid - the agent DID being authorised
1841
+ * @param grant - the single script grant to set (contract, functions,
1842
+ * scopes, validity, egress hosts)
1843
+ * @returns the script rows preserved from the existing policy (audit aid)
1844
+ * @throws if the session is not authenticated, or the contract refuses
1845
+ */
1846
+ updateAgentAuth(agentDid: string, grant: AgentAuthScriptGrant): Promise<{
1847
+ preservedRows: string[];
1848
+ }>;
1750
1849
  /**
1751
1850
  * Build the canonical `ExecuteActionRequest` shape the server
1752
1851
  * expects (`script_name`, `script_version`, `function_name`, `input`,
@@ -1996,12 +2095,15 @@ declare class T3nClient {
1996
2095
  /**
1997
2096
  * Replace this user's agent-authorisation policy (`tee:user/contracts` →
1998
2097
  * `agent-auth-update`). The supplied document IS the new state: an empty
1999
- * `agents` array revokes all agent access.
2098
+ * `agents` array revokes all agent access. This is the full-document
2099
+ * write — use {@link T3nClient.updateAgentAuth} for the single-grant
2100
+ * read-merge-write that preserves other contracts' grants.
2000
2101
  *
2001
- * Typed wrapper over the raw contract call: callers pass
2002
- * camelCase input; the SDK emits the canonical snake_case wire
2003
- * (`agent_did` / `script_name` / `version_req` / `allowed_hosts`), so it no
2004
- * longer relies on the contract's compatibility aliases.
2102
+ * Typed wrapper over the raw contract call: callers pass camelCase input;
2103
+ * the SDK emits the canonical snake_case wire via
2104
+ * {@link toAgentAuthUpdateWire} (carrying `scopes` / `read_scopes` /
2105
+ * validity alongside `functions` / `allowed_hosts`), so it does not rely
2106
+ * on the contract's compatibility aliases.
2005
2107
  *
2006
2108
  * @throws {RpcError} if the contract rejects the policy (validation failure,
2007
2109
  * too many agents/grants).
@@ -2269,44 +2371,26 @@ declare function createRandomHandler(): GuestToHostHandler;
2269
2371
  declare function createDefaultHandlers(baseUrl: string): GuestToHostHandlers;
2270
2372
 
2271
2373
  /**
2272
- * User-to-Agent Delegation.
2273
- *
2274
- * TypeScript reference implementation of the delegation credential and
2275
- * envelope shapes defined by the delegation wire contract.
2276
- *
2277
- * The wire shape is byte-for-byte identical to the Rust source — pinned
2278
- * by the KAT fixtures under `tests/kat/`. Specifically:
2279
- *
2280
- * - `not_before_secs` / `not_after_secs` / `batch_cap_cents` are
2281
- * emitted as **JSON strings** (e.g. `"1700086400"`) so JS Number
2282
- * precision never enters the canonicalisation surface.
2283
- * - `nonce` (16 B), `vc_id` (16 B), `request_hash` (32 B),
2284
- * `agent_pubkey` (33 B compressed secp256k1), `user_sig`,
2285
- * `agent_sig` are emitted as **base64url-no-pad** strings.
2286
- * - `org_did` / `user_did` are emitted as `did:t3n:<40-hex>` (the
2287
- * `CompactDid` `Display` form).
2288
- *
2289
- * Canonicalisation uses the npm `canonicalize` package (RFC 8785 JCS).
2290
- * Cryptography uses `@noble/curves` (secp256k1) and `@noble/hashes`
2291
- * (sha256, keccak_256).
2292
- */
2293
- /** Domain tag carried in `DelegationCredential.v`. */
2294
- declare const DELEGATION_CREDENTIAL_DOMAIN: "ot3.delegation/1";
2295
- /** Domain tag prepended to the agent-side pre-image. */
2296
- declare const DELEGATION_INVOCATION_DOMAIN: "ot3.invocation/1";
2297
- declare const VC_ID_LEN = 16;
2298
- declare const NONCE_LEN = 16;
2299
- declare const REQUEST_HASH_LEN = 32;
2300
- declare const AGENT_PUBKEY_LEN = 33;
2301
- declare const ETH_SIG_LEN = 65;
2302
- declare const MAX_FUNCTIONS_PER_CREDENTIAL = 16;
2374
+ * Payroll request shapes + shared encoding utilities.
2375
+ *
2376
+ * Envelope-free authorisation removed the per-call delegation
2377
+ * credential and envelope entirely: authority is now the standing on-chain
2378
+ * `agent_auth` ∩ `UserGrant` intersection the host re-reads every call, and
2379
+ * every payroll call emits the plain Direct wire variant (`{ request }`).
2380
+ * What remains here is the request body shape, its canonical defaults, and
2381
+ * the base64url / DID helpers callers still need.
2382
+ *
2383
+ * Wire conventions retained from the contract:
2384
+ * - `batch_cap_cents` is emitted as a **JSON string** so JS Number
2385
+ * precision never enters the wire surface.
2386
+ * - binary fields are base64url-no-pad strings.
2387
+ * - `org_id` is `did:t3n:<40-hex>` (the `CompactDid` `Display` form).
2388
+ */
2303
2389
  /**
2304
2390
  * Canonical sorted run-pipeline function surface for the z-payroll contract
2305
- * (`z:<org-tid>:payroll`). Sorted ascending as required by the credential
2306
- * validator. Mirrors `Z_PAYROLL_RUN_FUNCTIONS` in the Trinity harness.
2307
- *
2308
- * Pass this (or a sorted subset) as `functions` to
2309
- * {@link buildDelegationCredential} for z-payroll credentials.
2391
+ * (`z:<org-tid>:payroll`). Sorted ascending. Mirrors `Z_PAYROLL_RUN_FUNCTIONS`
2392
+ * in the Trinity harness; used as the `functions` set for agent-auth grants
2393
+ * and `check-delegation` queries.
2310
2394
  */
2311
2395
  declare const Z_PAYROLL_RUN_FUNCTIONS: readonly ["compute-payroll", "execute-disbursement", "finalize-audit", "submit-escalations", "validate-credentials"];
2312
2396
  /**
@@ -2315,48 +2399,7 @@ declare const Z_PAYROLL_RUN_FUNCTIONS: readonly ["compute-payroll", "execute-dis
2315
2399
  * `get-audit-entry`.
2316
2400
  */
2317
2401
  declare const Z_PAYROLL_AUDIT_READ_FUNCTIONS: readonly ["get-audit-entry", "list-audit-cycles"];
2318
- /** User-to-agent delegation credential body. */
2319
- interface DelegationCredential {
2320
- /** Domain tag, must equal {@link DELEGATION_CREDENTIAL_DOMAIN}. */
2321
- v: string;
2322
- /** `did:t3n:<40-hex>` user DID. */
2323
- user_did: string;
2324
- /** 33-byte compressed secp256k1 public key the agent uses per call. */
2325
- agent_pubkey: Uint8Array;
2326
- /** `did:t3n:<40-hex>` org DID. */
2327
- org_did: string;
2328
- /** Contract id, e.g. `"tee:z-payroll"`. */
2329
- contract: string;
2330
- /**
2331
- * Functions this credential authorises. Sorted ascending, deduped,
2332
- * each entry non-empty lowercase ASCII, 1..=16 entries.
2333
- */
2334
- functions: string[];
2335
- /** Org-data scopes the contract may read on this user's behalf. */
2336
- scopes: string[];
2337
- /** Flat key-value labels checked against the org grant. */
2338
- metadata: Record<string, string>;
2339
- /** Inclusive lower bound of the validity window (unix seconds). */
2340
- not_before_secs: bigint;
2341
- /** Inclusive upper bound of the validity window (unix seconds). */
2342
- not_after_secs: bigint;
2343
- /** Random 16-byte credential id. */
2344
- vc_id: Uint8Array;
2345
- }
2346
- /** Envelope wrapping a contract-specific request body. */
2347
- interface DelegationEnvelope {
2348
- /** RFC 8785 JCS bytes of the credential, exactly as signed. */
2349
- credential_jcs: Uint8Array;
2350
- /** 65-byte EIP-191 signature over `credential_jcs`. */
2351
- user_sig: Uint8Array;
2352
- /** Per-call agent signature over the invocation pre-image. */
2353
- agent_sig: Uint8Array;
2354
- /** 16-byte agent-generated per-call nonce. */
2355
- nonce: Uint8Array;
2356
- /** SHA-256 of the canonical request body. */
2357
- request_hash: Uint8Array;
2358
- }
2359
- /** Payroll-specific request body wrapped by a delegation envelope. */
2402
+ /** Payroll-specific request body — the Direct wire variant carries `{ request }`. */
2360
2403
  interface PayrollRunRequest {
2361
2404
  /** `did:t3n:<40-hex>` org id. */
2362
2405
  org_id: string;
@@ -2368,55 +2411,18 @@ interface PayrollRunRequest {
2368
2411
  /** `employee_id` → previous-cycle baseline net disbursement, cents (decimal string). */
2369
2412
  historical_baselines: Record<string, string>;
2370
2413
  /**
2371
- * Per-employee disbursement flag threshold, in cents. Mirrors the
2372
- * payroll request's individual-disbursement threshold field.
2373
- * When absent the contract applies its own default (SGD 15,000). When
2374
- * present, the value is included in the wire shape and participates in
2375
- * the request hash.
2414
+ * Per-employee disbursement flag threshold, in cents. When absent the
2415
+ * contract applies its own default (SGD 15,000); when present it is included
2416
+ * in the wire shape.
2376
2417
  */
2377
2418
  individual_disbursement_threshold_cents?: bigint;
2378
2419
  }
2379
2420
  /** Default for `individual_disbursement_threshold_cents` — SGD 15,000. */
2380
2421
  declare const DEFAULT_INDIVIDUAL_THRESHOLD_CENTS = 1500000n;
2381
- /** Delegated invocation: the agent acts on behalf of a user. */
2382
- interface PayrollInvocationDelegated {
2383
- envelope: DelegationEnvelope;
2384
- request: PayrollRunRequest;
2385
- }
2386
- /**
2387
- * Direct invocation: the agent acts on its own behalf. No delegation
2388
- * envelope is included. The principal DID is resolved by the service layer
2389
- * from `DynamicContext.authenticated_did`; authorisation falls through to
2390
- * `OrgContractGrants[org || "tee:z-payroll"]` for the agent's own DID.
2391
- *
2392
- * Wire shape is `{ request }` — no `envelope` field and no
2393
- * `authenticated_did` field. The contract's entry-point handler injects
2394
- * `authenticated_did` from `GenericInput.context` before calling `verify`.
2395
- */
2396
- interface PayrollInvocationDirect {
2397
- request: PayrollRunRequest;
2398
- }
2399
- /**
2400
- * Union of the two invocation variants. The serde-untagged enum on the
2401
- * contract side disambiguates by presence of `envelope` — delegated calls
2402
- * carry `{ envelope, request }`, direct calls carry `{ request }` only.
2403
- */
2404
- type PayrollInvocation = PayrollInvocationDelegated | PayrollInvocationDirect;
2405
- /** Response from `tee:delegation.sign`. */
2406
- interface SignDelegationResponse {
2407
- credential_jcs: Uint8Array;
2408
- user_sig: Uint8Array;
2409
- }
2410
2422
  declare function b64uEncode(input: Uint8Array): string;
2411
2423
  /**
2412
- * Encode raw bytes to base64url-no-pad (RFC 4648 §5 with padding
2413
- * dropped). The same encoding the wire-shape uses for binary
2414
- * fields (`agent_pubkey`, `vc_id`, `nonce`, `agent_sig`, `user_sig`,
2415
- * `request_hash`, `credential_jcs`).
2416
- *
2417
- * Public API since v2.2: callers building `PayrollInvocation` JSON
2418
- * for the wire (e.g. the t3n-mcp `runPayroll` handler) need this
2419
- * encoder to match the contract's deserializer.
2424
+ * Encode raw bytes to base64url-no-pad (RFC 4648 §5 with padding dropped).
2425
+ * The encoding the wire uses for binary fields.
2420
2426
  */
2421
2427
  declare function b64uEncodeBytes(input: Uint8Array): string;
2422
2428
  /**
@@ -2429,241 +2435,6 @@ declare function b64uDecodeStrict(input: string): Uint8Array;
2429
2435
  declare const _b64uEncode: typeof b64uEncode;
2430
2436
  /** Build a `did:t3n:<40-hex>` from raw 20 bytes. */
2431
2437
  declare function compactDidFromBytes(bytes: Uint8Array): string;
2432
- /**
2433
- * Canonicalise a {@link DelegationCredential} to RFC 8785 JCS bytes.
2434
- *
2435
- * Output is byte-identical to the Rust `canonicalise_credential` in
2436
- * `delegation-types` (pinned by `tests/kat/credential.json`).
2437
- */
2438
- declare function canonicaliseCredential(credential: DelegationCredential): Uint8Array;
2439
- /** Canonicalise an arbitrary {@link PayrollRunRequest} to JCS bytes. */
2440
- declare function canonicaliseRequest(request: PayrollRunRequest): Uint8Array;
2441
- /** SHA-256 of the canonicalised request body. */
2442
- declare function requestHash(request: PayrollRunRequest): Uint8Array;
2443
- /**
2444
- * Build the agent-side pre-image bytes:
2445
- * `utf8(DELEGATION_INVOCATION_DOMAIN) || vc_id || nonce || request_hash`.
2446
- *
2447
- * SHA-256 of these bytes is what the agent's secp256k1 signature is
2448
- * verified against.
2449
- */
2450
- declare function buildInvocationPreimage(vcId: Uint8Array, nonce: Uint8Array, reqHash: Uint8Array): Uint8Array;
2451
- /** Options for {@link buildDelegationCredential}. */
2452
- interface BuildDelegationCredentialOpts {
2453
- user_did: string;
2454
- agent_pubkey: Uint8Array;
2455
- org_did: string;
2456
- contract: string;
2457
- /**
2458
- * Functions this credential authorises. Must be non-empty, sorted
2459
- * ascending, deduped — the same invariants enforced by
2460
- * {@link validateCredentialBody}.
2461
- */
2462
- functions: string[];
2463
- scopes?: string[];
2464
- metadata?: Record<string, string>;
2465
- not_before_secs: bigint | number;
2466
- not_after_secs: bigint | number;
2467
- vc_id: Uint8Array;
2468
- }
2469
- /**
2470
- * Construct a {@link DelegationCredential} and validate body-level
2471
- * invariants (domain, lengths, validity window). Throws on the same
2472
- * conditions the Rust `validate_credential_body` rejects.
2473
- */
2474
- declare function buildDelegationCredential(opts: BuildDelegationCredentialOpts): DelegationCredential;
2475
- /**
2476
- * Body-level validation matching the delegation credential-body validation,
2477
- * minus the `now`/`max_validity_secs` checks (which are caller-supplied).
2478
- * Throws with a message identifying the offending invariant.
2479
- */
2480
- declare function validateCredentialBody(c: DelegationCredential): void;
2481
- /** Compute the EIP-191 "personal_sign" digest of a message. */
2482
- declare function eip191Digest(msg: Uint8Array): Uint8Array;
2483
- /**
2484
- * EIP-191 sign `jcs` under `secret`, returning a 65-byte signature
2485
- * (`r || s || v`, with `v` in 27/28 — Ethereum convention) and the
2486
- * recovered 20-byte ETH address.
2487
- */
2488
- declare function signCredential(jcs: Uint8Array, secret: Uint8Array): {
2489
- sig: Uint8Array;
2490
- addr: Uint8Array;
2491
- };
2492
- /**
2493
- * Recover the 20-byte ETH address that signed `msg` under EIP-191.
2494
- * Mirrors the delegation contract's EIP-191 address recovery.
2495
- *
2496
- * **Signature malleability — accepted by design.** This routine does
2497
- * not enforce low-s. EIP-2 mandates low-s for *transaction* signatures,
2498
- * but EIP-191 / `personal_sign` has no such requirement, and ethers.js
2499
- * / MetaMask / web3.js produce both shapes. Two distinct `(r, s)` and
2500
- * `(r, n − s)` pairs verify under the same recovered address — replay
2501
- * protection comes from the envelope's `request_hash` + `nonce`, not
2502
- * from byte-uniqueness of the signature.
2503
- */
2504
- declare function ethRecoverEip191(msg: Uint8Array, sig: Uint8Array): Uint8Array;
2505
- /**
2506
- * Sign the agent-side invocation pre-image. The signature is raw
2507
- * compact ECDSA (64 bytes) over `sha256(preimage)` — the 64-byte form
2508
- * the delegation contract accepts.
2509
- */
2510
- declare function signAgentInvocation(preimage: Uint8Array, secret: Uint8Array): Uint8Array;
2511
- /**
2512
- * Options for {@link DelegationCustodialClient}.
2513
- */
2514
- interface DelegationCustodialClientOpts {
2515
- /**
2516
- * Explicit semver string for the delegation contract (e.g. `"1.0.0"`).
2517
- * When omitted the client resolves `"latest"` via
2518
- * `GET /api/contracts/current?name=tee:delegation/contracts` (one
2519
- * request per client instance, cached in `getScriptVersion`).
2520
- */
2521
- scriptVersion?: string;
2522
- }
2523
- /**
2524
- * Result returned by {@link DelegationCustodialClient.signCustodial}.
2525
- */
2526
- interface SignCustodialResult {
2527
- /** RFC 8785 JCS bytes of the credential, exactly as signed by the node. */
2528
- credentialJcs: Uint8Array;
2529
- /** 65-byte EIP-191 signature over `credentialJcs` produced by the TEE. */
2530
- userSig: Uint8Array;
2531
- }
2532
- /**
2533
- * Wraps the `tee:delegation/contracts::sign` function for OIDC users
2534
- * (or any user whose private key is held by the TEE rather than the
2535
- * browser).
2536
- *
2537
- * ETH-EOA users who hold their own key should call
2538
- * {@link signCredential} directly — no network round-trip required.
2539
- *
2540
- * The client must be constructed with an authenticated {@link T3nClient}
2541
- * instance and the node's base URL; `signCustodial` sends the credential
2542
- * body to the TEE and returns the signed bytes.
2543
- */
2544
- declare class DelegationCustodialClient {
2545
- private readonly t3n;
2546
- private readonly baseUrl;
2547
- private readonly opts;
2548
- constructor(t3n: T3nClient, baseUrl: string, opts?: DelegationCustodialClientOpts);
2549
- /**
2550
- * Request the TEE to sign a delegation credential on behalf of the
2551
- * authenticated user.
2552
- *
2553
- * The `body` is sent as-is as the `input.body` field of the
2554
- * `tee:delegation/contracts::sign` action. Use
2555
- * {@link buildDelegationCredential} + the wire-shape projection to
2556
- * produce the correct representation — binary fields (`agent_pubkey`,
2557
- * `vc_id`) must be base64url-no-pad strings, and `not_before_secs` /
2558
- * `not_after_secs` must be decimal strings.
2559
- *
2560
- * Returns `{ credentialJcs, userSig }` — both as `Uint8Array` — ready
2561
- * to be passed into {@link buildPayrollInvocation}.
2562
- */
2563
- signCustodial(body: Record<string, unknown>): Promise<SignCustodialResult>;
2564
- }
2565
- /** Options for {@link revokeDelegation}. */
2566
- interface RevokeDelegationOpts {
2567
- /** Credential body to revoke. Already-encoded base64url-no-pad JCS bytes. */
2568
- credentialJcsB64u: string;
2569
- /**
2570
- * Omit (or pass `undefined`) to revoke the whole credential. Pass an
2571
- * array of function names to revoke a subset; the array must obey the
2572
- * same sort + dedupe invariants the credential's `functions` field
2573
- * enforces, and each entry must already appear in the credential's
2574
- * `functions` list (a revocation can only narrow the set, never grow
2575
- * it).
2576
- *
2577
- * Ignored when routing to a z-space contract (`revoke-credential` drops
2578
- * per-function granularity — whole-credential only).
2579
- */
2580
- revokedFunctions?: string[];
2581
- /** Authenticated {@link T3nClient} for the credential's `user_did`. */
2582
- client: T3nClient;
2583
- /**
2584
- * Override the resolved delegation contract version. Defaults to
2585
- * whatever `GET /api/contracts/current?name=tee:delegation/contracts`
2586
- * returns at call time.
2587
- *
2588
- * For z-space credentials this field is REQUIRED — `GET /api/contracts/current`
2589
- * 404s for z: names, so there is no dynamic resolution path.
2590
- */
2591
- scriptVersion?: string;
2592
- /** Override the node base URL used for `"latest"` resolution. */
2593
- baseUrl?: string;
2594
- }
2595
- /** Result of a successful {@link revokeDelegation} call. */
2596
- interface RevokeDelegationResult {
2597
- /** Credential id (base64url-no-pad, no padding). */
2598
- vcId: string;
2599
- /**
2600
- * Mirrors the persisted revocation state after merging: `null` means
2601
- * whole-credential, a sorted array means per-function. The contract
2602
- * may return a larger set than `opts.revokedFunctions` when an
2603
- * earlier per-function revocation existed for the same credential.
2604
- *
2605
- * Always `null` for z-space credentials (whole-credential granularity only).
2606
- */
2607
- revokedFunctions: string[] | null;
2608
- }
2609
- /**
2610
- * Revoke a delegation credential, routing automatically to the correct
2611
- * revocation endpoint based on the credential's `contract` field:
2612
- *
2613
- * - **`tee:` credentials** — calls `tee:delegation/contracts::revoke`.
2614
- * Only the credential's `user_did` may call this; the contract reads the
2615
- * authenticated DID from session context and rejects other callers with
2616
- * `NotCredentialHolder`. Per-function granularity via `revokedFunctions`
2617
- * is supported. Merge semantics are handled server-side.
2618
- *
2619
- * - **`z:` credentials** — routes to `<z-contract>::revoke-credential`.
2620
- * The tenant owns its own revocation list; the global
2621
- * `tee:delegation.revoke` rejects z-space credential names with a typed
2622
- * `TenantScopedCredential` error. `revokedFunctions` is ignored (z-payroll
2623
- * revokes whole credentials only). `scriptVersion` is REQUIRED for z:
2624
- * contracts — `GET /api/contracts/current` 404s for them.
2625
- */
2626
- declare function revokeDelegation(opts: RevokeDelegationOpts): Promise<RevokeDelegationResult>;
2627
- /** Options for {@link buildPayrollInvocation}. */
2628
- interface BuildPayrollInvocationOpts {
2629
- credentialJcs: Uint8Array;
2630
- userSig: Uint8Array;
2631
- /** Credential's `vc_id` — needed for the agent pre-image. */
2632
- vcId: Uint8Array;
2633
- nonce: Uint8Array;
2634
- request: PayrollRunRequest;
2635
- agentSecret: Uint8Array;
2636
- }
2637
- /**
2638
- * Assemble a delegated {@link PayrollInvocationDelegated} (envelope +
2639
- * request) given a user-signed credential and a per-call agent secret.
2640
- * Computes `request_hash` from the canonical request bytes and produces an
2641
- * `agent_sig` over `sha256(invocation_preimage)`.
2642
- *
2643
- * When `request.individual_disbursement_threshold_cents` is undefined this
2644
- * function fills in {@link DEFAULT_INDIVIDUAL_THRESHOLD_CENTS} before
2645
- * hashing so the SDK's hash matches the Rust contract's hash (the contract
2646
- * applies the same default via `#[serde(default)]`).
2647
- */
2648
- declare function buildPayrollInvocation(opts: BuildPayrollInvocationOpts): PayrollInvocationDelegated;
2649
- /** Options for {@link buildPayrollDirectInvocation}. */
2650
- interface BuildPayrollDirectInvocationOpts {
2651
- request: PayrollRunRequest;
2652
- }
2653
- /**
2654
- * Assemble a direct {@link PayrollInvocationDirect} — no delegation
2655
- * envelope. The caller supplies only the request body; the contract
2656
- * entry-point resolves the principal DID from
2657
- * `DynamicContext.authenticated_did` at runtime.
2658
- *
2659
- * Callers in direct mode must hold a grant in
2660
- * `OrgContractGrants[org || "tee:z-payroll"]` under their own DID.
2661
- *
2662
- * When `request.individual_disbursement_threshold_cents` is undefined this
2663
- * function fills in {@link DEFAULT_INDIVIDUAL_THRESHOLD_CENTS} so the wire
2664
- * shape matches the Rust contract's `#[serde(default)]` canonicalisation.
2665
- */
2666
- declare function buildPayrollDirectInvocation(opts: BuildPayrollDirectInvocationOpts): PayrollInvocationDirect;
2667
2438
 
2668
2439
  /**
2669
2440
  * OrgDataClient — typed wrapper over the existing authenticated
@@ -3609,5 +3380,5 @@ declare function tenantDidHex(tenantDid: string): string;
3609
3380
  declare function validateTail(tail: string): string;
3610
3381
  declare function canonicalTenantName(tenantDid: string, tail: string): string;
3611
3382
 
3612
- export { AGENT_PUBKEY_LEN, AuthMethod, AuthenticationError, BASE_UNITS_PER_TOKEN, ContractResponseError, DEFAULT_ENVIRONMENT, DEFAULT_INDIVIDUAL_THRESHOLD_CENTS, DEFAULT_KYC_POLL_CADENCE, DELEGATION_CREDENTIAL_DOMAIN, DELEGATION_INVOCATION_DOMAIN, DelegationCustodialClient, ETH_SIG_LEN, HandshakeError, HttpTransport, KycStatusTimeoutError, LogLevel, MAX_FUNCTIONS_PER_CREDENTIAL, MockTransport, NODE_URLS, NONCE_LEN, OrgDataClient, OtpRateLimitedError, REQUEST_HASH_LEN, RpcError, SessionExpiredError, SessionOrgDataClient, SessionStateError, SessionStatus, T3nClient, T3nError, TERMINAL_KYC_STATUSES, TOKEN_DECIMALS, TenantClient, TenantContractsNamespace, TenantMapsNamespace, TenantNamespace, TenantSdkValidationError, TenantTokenNamespace, UnsupportedTenantSdkOperationError, UserUpsertError, VC_ID_LEN, WasmError, Z_PAYROLL_AUDIT_READ_FUNCTIONS, Z_PAYROLL_RUN_FUNCTIONS, _b64uEncode, assertShape, b64uDecodeStrict, b64uEncodeBytes, buildDelegationCredential, buildInvocationPreimage, buildPayrollDirectInvocation, buildPayrollInvocation, bytesToString, canonicalTenantName, canonicaliseCredential, canonicaliseRequest, clearKeyCache, compactDidFromBytes, createDefaultHandlers, createEmailOtpAuthInput, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createOrgDataClientFromSession, createRandomHandler, decodeWasmErrorMessage, eip191Digest, ethRecoverEip191, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, formatTokens, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, isDataGetResponse, isDataListResponse, isMutationResponse, isObject, isOrgContractGrants, isOrgPolicyMeta, isOrgPolicyView, isOrgWriters, loadConfig, loadWasmComponent, maskKeyMaterial, metamask_get_address, metamask_sign, parseContractResponse, redactSecrets, redactSecretsFromJson, requestHash, revokeDelegation, setEnvironment, setGlobalLogLevel, setNodeUrl, signAgentInvocation, signCredential, stringToBytes, tenantDidHex, toBaseUnits, validateConfig, validateCredentialBody, validateTail, verifyDkgAttestation, verifyTdxQuote };
3613
- export type { AdmitForOrgOptions, AgentAuthUpdateInput, AgentGrantInput, AgentScriptGrant, AuthInput, BalanceRow, BuildDelegationCredentialOpts, BuildPayrollDirectInvocationOpts, BuildPayrollInvocationOpts, ChargeReason, ClientAuth, ClientHandshake, ConfigValidationResult, ContractExecuteInput, ContractPublishInput, ContractRegisterResult, ContractResponseSchema, CreatePolicyInput, DataGetInput, DataGetResponse, DataListInput, DataListResponse, DelegationCredential, DelegationCustodialClientOpts, DelegationEnvelope, DeleteDataInput, DeleteGrantsInput, DeleteScopeInput, Did, Direction, DkgAttestation, DkgVerifyResult, EmailOtpAuthInput, EmailOtpCredentials, Environment, EthAuthInput, ExecuteBusinessContractOptions, ExecuteOrgDataActionOptions, GetUsageOptions, GrantsGetInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, Logger, MapCreateInput, MapResponse, MapUpdateInput, MapVisibility, MutationResponse, OidcAuthInput, OidcCredentials, OrgContractGrants, OrgDataActionWire, OrgDataClientOptions, OrgPolicyMeta, OrgPolicyView, OrgWriters, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollInvocation, PayrollInvocationDelegated, PayrollInvocationDirect, PayrollRunRequest, PeerQuoteResult, PolicyGetInput, QuoteVerifyResult, ReaderSet, RevokeDelegationOpts, RevokeDelegationResult, SdkConfig, SessionCrypto, SessionId, SetGrantsInput, SetWritersInput, SignCustodialResult, SignDelegationResponse, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, TenantAdmitProjection, TenantAdmitStatus, TenantBaseClient, TenantClientConfig, TenantContractExecuteInput, TenantContractPublishInput, TenantExecutionSession, TenantMapCreateInput, TenantMapUpdatePatch, TenantMeResponse, TenantSdkEnvironment, TenantSelfAdmitResult, TenantStatus, TenantTargetOptions, TokenTxKind, Transport, UpdateMetaInput, UsageEntry, UsagePage, UserGrant, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult, WriteDataInput, WriterSet, WritersGetInput };
3383
+ export { AuthMethod, AuthenticationError, BASE_UNITS_PER_TOKEN, ContractResponseError, DEFAULT_ENVIRONMENT, DEFAULT_INDIVIDUAL_THRESHOLD_CENTS, DEFAULT_KYC_POLL_CADENCE, HandshakeError, HttpTransport, KycStatusTimeoutError, LogLevel, MockTransport, NODE_URLS, OrgDataClient, OtpRateLimitedError, RpcError, SessionExpiredError, SessionOrgDataClient, SessionStateError, SessionStatus, T3nClient, T3nError, TERMINAL_KYC_STATUSES, TOKEN_DECIMALS, TenantClient, TenantContractsNamespace, TenantMapsNamespace, TenantNamespace, TenantSdkValidationError, TenantTokenNamespace, UnsupportedTenantSdkOperationError, UserUpsertError, WasmError, Z_PAYROLL_AUDIT_READ_FUNCTIONS, Z_PAYROLL_RUN_FUNCTIONS, _b64uEncode, assertShape, b64uDecodeStrict, b64uEncodeBytes, bytesToString, canonicalTenantName, clearKeyCache, compactDidFromBytes, createDefaultHandlers, createEmailOtpAuthInput, createEthAuthInput, createLogger, createMlKemPublicKeyHandler, createOidcAuthInput, createOrgDataClientFromSession, createRandomHandler, decodeWasmErrorMessage, eth_get_address, extractWasmError, fetchDkgAttestation, fetchMlKemPublicKey, formatTokens, generateRandomString, generateUUID, getEnvironment, getEnvironmentName, getGlobalLogLevel, getLogger, getNodeUrl, getScriptVersion, isDataGetResponse, isDataListResponse, isMutationResponse, isObject, isOrgContractGrants, isOrgPolicyMeta, isOrgPolicyView, isOrgWriters, loadConfig, loadWasmComponent, maskKeyMaterial, mergeAgentAuthEntries, metamask_get_address, metamask_sign, parseAgentAuthGet, parseContractResponse, redactSecrets, redactSecretsFromJson, setEnvironment, setGlobalLogLevel, setNodeUrl, stringToBytes, tenantDidHex, toAgentAuthUpdateWire, toBaseUnits, validateConfig, validateTail, verifyDkgAttestation, verifyTdxQuote };
3384
+ export type { AdmitForOrgOptions, AgentAuthEntry, AgentAuthMergeResult, AgentAuthScriptGrant, AgentAuthUpdateInput, AuthInput, BalanceRow, ChargeReason, ClientAuth, ClientHandshake, ConfigValidationResult, ContractExecuteInput, ContractPublishInput, ContractRegisterResult, ContractResponseSchema, CreatePolicyInput, DataGetInput, DataGetResponse, DataListInput, DataListResponse, DeleteDataInput, DeleteGrantsInput, DeleteScopeInput, Did, Direction, DkgAttestation, DkgVerifyResult, EmailOtpAuthInput, EmailOtpCredentials, Environment, EthAuthInput, ExecuteBusinessContractOptions, ExecuteOrgDataActionOptions, GetUsageOptions, GrantsGetInput, GuestToHostHandler, GuestToHostHandlers, HandshakeResult, JsonRpcRequest, JsonRpcResponse, KycPollCadence, KycPollOptions, KycStatus, KycStatusKind, Logger, MapCreateInput, MapResponse, MapUpdateInput, MapVisibility, MutationResponse, OidcAuthInput, OidcCredentials, OrgContractGrants, OrgDataActionWire, OrgDataClientOptions, OrgPolicyMeta, OrgPolicyView, OrgWriters, OtpChannel, OtpMergeSuggestion, OtpRequestInput, OtpRequestResult, OtpVerifyInput, OtpVerifyResult, PayrollRunRequest, PeerQuoteResult, PolicyGetInput, QuoteVerifyResult, ReaderSet, SdkConfig, SessionCrypto, SessionId, SetGrantsInput, SetWritersInput, SubmitUserInputArgs, SubmitUserInputResult, T3nClientConfig, TenantAdmitProjection, TenantAdmitStatus, TenantBaseClient, TenantClientConfig, TenantContractExecuteInput, TenantContractPublishInput, TenantExecutionSession, TenantMapCreateInput, TenantMapUpdatePatch, TenantMeResponse, TenantSdkEnvironment, TenantSelfAdmitResult, TenantStatus, TenantTargetOptions, TokenTxKind, Transport, UpdateMetaInput, UsageEntry, UsagePage, UserGrant, UserInputProfile, UserUpsertErrorKind, WasmComponent, WasmNextResult, WriteDataInput, WriterSet, WritersGetInput };