@mentra/cloud-client 3.4.0-dev.999 → 3.5.0-dev.1238

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/node/index.ts CHANGED
@@ -52,5 +52,8 @@ export {
52
52
  AuthExpiredError,
53
53
  AuthUnavailableError,
54
54
  SessionRevocationError,
55
+ CoreRequestError,
56
+ CoreResponseError,
57
+ SessionChangedError,
55
58
  noopLogger,
56
59
  } from "@mentra/cloud-client";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentra/cloud-client",
3
- "version": "3.4.0-dev.999",
3
+ "version": "3.5.0-dev.1238",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "exports": {
@@ -12,10 +12,11 @@
12
12
  "test": "bun test"
13
13
  },
14
14
  "dependencies": {
15
- "@mentra/cloud-protocol": "3.4.0-dev.999",
15
+ "@mentra/cloud-protocol": "3.5.0-dev.1238",
16
16
  "tweetnacl": "^1.0.3"
17
17
  },
18
18
  "devDependencies": {
19
+ "@mentra/workspace-contract": "workspace:*",
19
20
  "ws": "^8.18.0",
20
21
  "@types/ws": "^8.5.12"
21
22
  },
package/src/client.ts CHANGED
@@ -267,7 +267,7 @@ export class CloudClient {
267
267
  })
268
268
 
269
269
  // Core is last: stateless REST on the core service, Bearer from auth.
270
- const core = coreHttp ? new Core({http: coreHttp}) : undefined
270
+ const core = coreHttp ? new Core({http: coreHttp, auth}) : undefined
271
271
 
272
272
  this.auth = auth
273
273
  this.runtime = runtime
package/src/index.ts CHANGED
@@ -58,6 +58,7 @@ export type {
58
58
  RuntimeAudioTransport,
59
59
  RuntimeSnapshot,
60
60
  RuntimeStatus,
61
+ RuntimeTtsFormat,
61
62
  RuntimeTtsSpeakOptions,
62
63
  RuntimeTtsSpeechSource,
63
64
  } from "./modules/runtime/runtime";
@@ -86,3 +87,18 @@ export type {
86
87
  SupportProfileUpdateResult,
87
88
  SupportStateInput,
88
89
  } from "./modules/core/core";
90
+
91
+ // Workspace, Fleet desired-state and registry calls (`cloud.core.workspaces`, `cloud.core.fleet.desiredState`,
92
+ // `cloud.core.registry`). The registry's request and answer types come from `@mentra/cloud-protocol`.
93
+ export {CoreRequestError, CoreResponseError, SessionChangedError} from "./modules/core/core";
94
+ export type {AccountCallOptions} from "./modules/core/core";
95
+ export type {
96
+ AcceptInvitationResult,
97
+ ClientWorkspaceRole,
98
+ DeclineInvitationResult,
99
+ InvitationPreview,
100
+ LeaveWorkspaceRequest,
101
+ MyWorkspace,
102
+ MyWorkspaceResponse,
103
+ PendingInvitationsResponse,
104
+ } from "./modules/core/workspace-types";
@@ -11,9 +11,10 @@
11
11
  * fetches the subject token on demand for subject tokens that themselves
12
12
  * expire. An `accessToken`/`refreshToken` variant skips straight to refresh.
13
13
  * - Near expiry (within a 60s margin) it refreshes at `/refresh` and rotates.
14
- * - Exchange, refresh, and each per-miniapp mint are single-flighted, so a
15
- * reconnect storm cannot fire a burst of competing requests (and a rotated
16
- * refresh token cannot be invalidated out from under a concurrent caller).
14
+ * - Exchange and refresh are single-flighted, so a reconnect storm cannot fire
15
+ * a burst of competing requests (and a rotated refresh token cannot be
16
+ * invalidated out from under a concurrent caller). Miniapp mints run one at
17
+ * a time per package and are shared as `getMiniappToken` describes.
17
18
  * - If Core definitively rejects the refresh token (see
18
19
  * `DEAD_REFRESH_TOKEN_ERRORS`) and the host can fetch a fresh subject token
19
20
  * on demand, we clear the dead refresh token and exchange once. If no fresh
@@ -63,10 +64,14 @@ export interface AuthModule {
63
64
  getRuntimeToken(opts?: {forceRefresh?: boolean}): Promise<string>
64
65
  // current Core token, refreshing as needed (Core-backed mode only).
65
66
  getCoreToken(opts?: {forceRefresh?: boolean}): Promise<string>
66
- // a miniapp-scoped token, cached per packageName and re-minted before expiry
67
+ // a miniapp-scoped token, cached per packageName and re-minted before expiry.
68
+ // Pass `{ fresh: true }` to skip the cache and mint now, for the moments the
69
+ // token's claims must be current (a miniapp opening). Pass
70
+ // `{ localBuild: true }` for a local or development build: Core marks its
71
+ // token as one, and it is cached apart from the installed miniapp's.
67
72
  getMiniappToken(
68
73
  packageName: string,
69
- opts?: {minTtlMs?: number},
74
+ opts?: {minTtlMs?: number; fresh?: boolean; localBuild?: boolean},
70
75
  ): Promise<{token: string; expiresAt: number}>
71
76
  // Core-owned user/oem identity, read from the Core access token.
72
77
  // Runtime-only deployments do not expose this surface.
@@ -135,6 +140,16 @@ interface MiniappTokenEntry {
135
140
  expiresAt: number
136
141
  }
137
142
 
143
+ /**
144
+ * One miniapp mint. `requestSent()` turns true just before the request to Core
145
+ * leaves. Until then a caller who needs a token minted from now on can still
146
+ * share it, because Core has not yet read anything on its behalf.
147
+ */
148
+ interface MiniappMint {
149
+ promise: Promise<MiniappTokenEntry>
150
+ requestSent: () => boolean
151
+ }
152
+
138
153
  interface RuntimeTokenResponse {
139
154
  access_token: string
140
155
  token_type: string
@@ -146,6 +161,15 @@ interface RuntimeTokenEntry {
146
161
  expiresAt: number
147
162
  }
148
163
 
164
+ /**
165
+ * The cache key of a package's miniapp token: an installed miniapp's and a local
166
+ * build's are different tokens. The variant comes first and holds no `:`, so no
167
+ * package name makes one key look like another.
168
+ */
169
+ function miniappTokenKey(packageName: string, localBuild: boolean): string {
170
+ return `${localBuild ? "local" : "installed"}:${packageName}`
171
+ }
172
+
149
173
  /**
150
174
  * A revoke is worth retrying only when Core gave no definite answer: the
151
175
  * transport failed (`status` 0) or the server errored (5xx). A 4xx means Core
@@ -257,8 +281,10 @@ export class Auth implements AuthModule {
257
281
  private readonly httpTransport: HttpTransport
258
282
  private readonly timers: CloudClientTimers
259
283
 
260
- /** Miniapp tokens cached per packageName until near expiry. */
284
+ /** Miniapp tokens cached per packageName and local-build flag (`miniappTokenKey`) until near expiry. */
261
285
  private readonly miniappCache = new Map<string, MiniappTokenEntry>()
286
+ /** The newest mint per package, flag and session, until it settles. See `mintMiniappToken`. */
287
+ private readonly miniappMints = new Map<string, MiniappMint>()
262
288
  /** Core-brokered runtime token cache. */
263
289
  private runtimeToken: RuntimeTokenEntry | null = null
264
290
 
@@ -346,44 +372,93 @@ export class Auth implements AuthModule {
346
372
  /**
347
373
  * Mint (or return a cached) miniapp-scoped token for `packageName`.
348
374
  *
349
- * Cached per packageName and re-minted only when near expiry, so a steady
350
- * miniapp does not hit the cloud on every call. The mint is single-flighted
351
- * per packageName so two near-simultaneous launches of the same miniapp share
352
- * one request. The access token is the Bearer here and is never exposed to the
353
- * miniapp; only the returned miniapp-scoped token is.
375
+ * By default the token is cached per packageName and re-minted only when near
376
+ * expiry, so a steady miniapp does not hit the cloud on every call.
377
+ *
378
+ * `localBuild: true` asks for a local or development build's token, which Core
379
+ * marks as one (and never names a workspace in). It is a different token from
380
+ * the installed miniapp's, so the two are cached and minted apart, and a call
381
+ * never gets the other's.
382
+ *
383
+ * `fresh: true` skips the cache and reaches Core, because what Core puts in a
384
+ * token (the features the user holds, today) can change within its hour. It
385
+ * can share a mint only if that mint's request has not left yet; a mint whose
386
+ * request is already out may have read the user's features before the change,
387
+ * so the caller gets a new mint, which starts once the earlier one settles.
388
+ * Callers waiting on that follow-up share it. `minTtlMs` has no use with
389
+ * `fresh`: the token it returns was minted for this call.
390
+ *
391
+ * Mints for one package never overlap, and a default call that finds one in
392
+ * flight takes it rather than starting another. The access token is the
393
+ * Bearer here and is never exposed to the miniapp; only the returned
394
+ * miniapp-scoped token is.
354
395
  */
355
396
  async getMiniappToken(
356
397
  packageName: string,
357
- opts?: {minTtlMs?: number},
398
+ opts?: {minTtlMs?: number; fresh?: boolean; localBuild?: boolean},
358
399
  ): Promise<{token: string; expiresAt: number}> {
359
400
  this.assertSessionActive()
360
401
  const generation = this.sessionGeneration
361
- const marginSeconds = this.tokenMarginSeconds(opts?.minTtlMs)
362
- const cached = this.miniappCache.get(packageName)
363
- if (cached && !this.isExpiring(cached.expiresAt, marginSeconds)) {
364
- return {token: cached.token, expiresAt: cached.expiresAt}
402
+ const fresh = opts?.fresh === true
403
+ const localBuild = opts?.localBuild === true
404
+ if (!fresh) {
405
+ const marginSeconds = this.tokenMarginSeconds(opts?.minTtlMs)
406
+ const cached = this.miniappCache.get(miniappTokenKey(packageName, localBuild))
407
+ if (cached && !this.isExpiring(cached.expiresAt, marginSeconds)) {
408
+ return {token: cached.token, expiresAt: cached.expiresAt}
409
+ }
365
410
  }
366
411
 
367
- return this.store.singleFlight(`${MINIAPP_FLIGHT_PREFIX}${packageName}:${generation}`, async () => {
368
- // Re-check the cache inside the flight: a concurrent mint that resolved
369
- // while we were queued may have already filled it.
370
- const fresh = this.miniappCache.get(packageName)
371
- if (fresh && !this.isExpiring(fresh.expiresAt, marginSeconds)) {
372
- return {token: fresh.token, expiresAt: fresh.expiresAt}
373
- }
412
+ const entry = await this.mintMiniappToken(packageName, localBuild, generation, fresh)
413
+ return {token: entry.token, expiresAt: entry.expiresAt}
414
+ }
374
415
 
416
+ /**
417
+ * The mint a caller should wait on. Mints for a package (and local-build flag)
418
+ * form a chain, one at a time; `miniappMints` holds the newest link.
419
+ *
420
+ * - A default caller takes the newest mint, whatever its state.
421
+ * - A fresh caller takes it only while its request is unsent. Otherwise it
422
+ * appends a mint that starts when the newest one settles, win or lose, and
423
+ * becomes the newest, so later fresh callers share it until it too sends.
424
+ */
425
+ private mintMiniappToken(
426
+ packageName: string,
427
+ localBuild: boolean,
428
+ generation: number,
429
+ fresh: boolean,
430
+ ): Promise<MiniappTokenEntry> {
431
+ const cacheKey = miniappTokenKey(packageName, localBuild)
432
+ const key = `${MINIAPP_FLIGHT_PREFIX}${generation}:${cacheKey}`
433
+ const newest = this.miniappMints.get(key)
434
+ if (newest && (!fresh || !newest.requestSent())) return newest.promise
435
+
436
+ let requestSent = false
437
+ const promise = (async () => {
438
+ if (newest) await newest.promise.catch(() => undefined)
375
439
  const accessToken = await this.getCoreToken()
376
440
  const http = this.requireCoreHttp()
377
- // A dev build of a package is that package: the request names it and
378
- // nothing else. The phone has already applied the installed signer rule.
379
- const res = await http.post<MiniappTokenEntry>(MINIAPP_TOKEN_PATH, {packageName}, {bearer: accessToken})
441
+ requestSent = true
442
+ // The request names the package, and says when it is a local build so
443
+ // Core marks the token. An installed miniapp's request names only the
444
+ // package, as it always has.
445
+ const body = localBuild ? {packageName, localBuild: true} : {packageName}
446
+ const res = await http.post<MiniappTokenEntry>(MINIAPP_TOKEN_PATH, body, {bearer: accessToken})
380
447
 
381
448
  this.assertSessionActive(generation)
382
449
  const entry: MiniappTokenEntry = {token: res.token, expiresAt: res.expiresAt}
383
- this.miniappCache.set(packageName, entry)
384
- this.logger.debug("minted miniapp token", {packageName})
385
- return {token: entry.token, expiresAt: entry.expiresAt}
386
- })
450
+ this.miniappCache.set(cacheKey, entry)
451
+ this.logger.debug("minted miniapp token", {packageName, localBuild})
452
+ return entry
453
+ })()
454
+ const mint: MiniappMint = {promise, requestSent: () => requestSent}
455
+ this.miniappMints.set(key, mint)
456
+ // A later mint that replaced this one as the newest stays registered.
457
+ const release = () => {
458
+ if (this.miniappMints.get(key) === mint) this.miniappMints.delete(key)
459
+ }
460
+ void promise.then(release, release)
461
+ return promise
387
462
  }
388
463
 
389
464
  /**
@@ -0,0 +1,203 @@
1
+ /**
2
+ * @fileoverview Core calls made as one account.
3
+ *
4
+ * A call here belongs to the account whose Core token it was sent with, and to no other. The runner:
5
+ *
6
+ * - gets the token and reads whose it is (`sub`), then sends that exact token as the request's bearer, so the
7
+ * request never reads the token source again and cannot pick up another account's token;
8
+ * - refuses to send when the caller named the account it expects and the token is someone else's;
9
+ * - after the answer (a good one or a failure), asks the token source whose session it holds now. When that is not
10
+ * the account the request was sent for, the answer is discarded as `SessionChangedError`: a switch or sign-out
11
+ * during the request must not hand A's data to a screen that now speaks for B;
12
+ * - on a 401, refreshes the token once, and sends again only when the refreshed token is still the same account's.
13
+ * A second 401 is an error.
14
+ *
15
+ * Every failure of a Core answer is a `CoreRequestError` that keeps the HTTP status and Core's error code. Its message
16
+ * is fixed text built from the status; Core's own wording (`error_description`) never reaches it, because a screen
17
+ * may show the message and the app has its own words for each code.
18
+ */
19
+ import {AuthExpiredError, CloudClientError, HttpError} from "../../errors"
20
+ import {decodeClaims} from "../auth/jwt"
21
+
22
+ /** Core's error codes are short snake_case words; anything else is not safe to surface or branch on. */
23
+ const ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
24
+
25
+ /** The part of `cloud.auth` the runner needs. */
26
+ export interface CoreTokenSource {
27
+ getCoreToken(opts?: {forceRefresh?: boolean}): Promise<string>
28
+ }
29
+
30
+ /** Per-call options. */
31
+ export interface AccountCallOptions {
32
+ signal?: AbortSignal
33
+ /**
34
+ * The Mentra user ID the caller is acting for. When the client holds another account's token the call is refused
35
+ * with `SessionChangedError` before anything is sent.
36
+ */
37
+ expectedAccount?: string
38
+ }
39
+
40
+ /** A Core answer that was not a success. `status` is 0 when nothing answered. */
41
+ export class CoreRequestError extends CloudClientError {
42
+ readonly status: number
43
+ /** Core's error code when it gave a well-formed one; `network_error` when nothing answered. */
44
+ readonly code?: string
45
+ readonly retryAfterSeconds?: number
46
+
47
+ constructor(status: number, code?: string, retryAfterSeconds?: number) {
48
+ super(status === 0 ? "Core request failed: no answer" : `Core request failed (HTTP ${status})`)
49
+ this.name = "CoreRequestError"
50
+ this.status = status
51
+ this.code = code
52
+ this.retryAfterSeconds = retryAfterSeconds
53
+ Object.setPrototypeOf(this, new.target.prototype)
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Core answered 2xx, but not with what this client can use: no body, a body of another shape, or (for desired state)
59
+ * a status this client does not know. Never read as an empty or `unmanaged` answer.
60
+ */
61
+ export class CoreResponseError extends CloudClientError {
62
+ readonly reason: "invalid_shape" | "unknown_status"
63
+
64
+ constructor(reason: "invalid_shape" | "unknown_status") {
65
+ super(`Core's answer was not usable (${reason})`)
66
+ this.name = "CoreResponseError"
67
+ this.reason = reason
68
+ Object.setPrototypeOf(this, new.target.prototype)
69
+ }
70
+ }
71
+
72
+ /**
73
+ * The client no longer holds the session the call was made for (another account signed in, or the session ended),
74
+ * so nothing was sent or the answer was dropped. The caller discards it and follows the new session.
75
+ */
76
+ export class SessionChangedError extends CloudClientError {
77
+ readonly reason: "other_account" | "signed_out" | "unreadable_token"
78
+
79
+ constructor(reason: "other_account" | "signed_out" | "unreadable_token") {
80
+ super(`The signed-in account changed during the request (${reason})`)
81
+ this.name = "SessionChangedError"
82
+ this.reason = reason
83
+ Object.setPrototypeOf(this, new.target.prototype)
84
+ }
85
+ }
86
+
87
+ function isAbortError(error: unknown): boolean {
88
+ return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError"
89
+ }
90
+
91
+ function abortReason(signal: AbortSignal): unknown {
92
+ if (signal.reason !== undefined) return signal.reason
93
+ const error = new Error("The request was aborted")
94
+ error.name = "AbortError"
95
+ return error
96
+ }
97
+
98
+ /** The account a Core token belongs to (its `sub`), or null when the token is not readable. */
99
+ function accountOf(token: string): string | null {
100
+ try {
101
+ const sub = decodeClaims(token).sub
102
+ return typeof sub === "string" && sub ? sub : null
103
+ } catch {
104
+ return null
105
+ }
106
+ }
107
+
108
+ function toRequestError(error: HttpError): CoreRequestError {
109
+ const code =
110
+ error.status === 0
111
+ ? "network_error"
112
+ : typeof error.code === "string" && ERROR_CODE_PATTERN.test(error.code)
113
+ ? error.code
114
+ : undefined
115
+ return new CoreRequestError(error.status, code, error.retryAfterSeconds)
116
+ }
117
+
118
+ /** Runs requests as one account. See the file comment. */
119
+ export class AccountCaller {
120
+ constructor(private readonly auth: CoreTokenSource | undefined) {}
121
+
122
+ /**
123
+ * Sends one request with the current account's token. `send` receives the bearer to use and must use exactly it.
124
+ * Rejects with `CoreRequestError` for a Core answer that is not a success, `SessionChangedError` when the account
125
+ * changed, the auth errors from the token source (`AuthExpiredError`, `AuthUnavailableError`) as they are, and the
126
+ * caller's abort reason when `opts.signal` is aborted.
127
+ */
128
+ async run<T>(send: (bearer: string) => Promise<T>, opts: AccountCallOptions = {}): Promise<T> {
129
+ const auth = this.auth
130
+ if (!auth) throw new CloudClientError("This client has no Core sign-in; workspace and Fleet calls need one")
131
+ const {signal} = opts
132
+
133
+ const first = await this.tokenFor(auth, false, signal)
134
+ const account = first.account
135
+ if (opts.expectedAccount !== undefined && opts.expectedAccount !== account) {
136
+ throw new SessionChangedError("other_account")
137
+ }
138
+
139
+ let token = first.token
140
+ for (let attempt = 0; ; attempt++) {
141
+ let result: T
142
+ try {
143
+ result = await send(token)
144
+ } catch (error) {
145
+ if (signal?.aborted) throw abortReason(signal)
146
+ if (isAbortError(error)) throw error
147
+ if (!(error instanceof HttpError)) {
148
+ // Not a Core answer: a 2xx body that is not JSON, or a connection that dropped while the body was read.
149
+ await this.assertStill(auth, account, signal)
150
+ if (error instanceof CloudClientError) throw error
151
+ throw error instanceof SyntaxError
152
+ ? new CoreResponseError("invalid_shape")
153
+ : new CoreRequestError(0, "network_error")
154
+ }
155
+ // Whatever Core answered, it answered A: if the session is not A's any more, nobody here wants the answer,
156
+ // and a 401 must not trigger a refresh of someone else's session.
157
+ await this.assertStill(auth, account, signal)
158
+ if (error.status === 401 && attempt === 0) {
159
+ const refreshed = await this.tokenFor(auth, true, signal)
160
+ if (refreshed.account !== account) throw new SessionChangedError("other_account")
161
+ token = refreshed.token
162
+ continue
163
+ }
164
+ throw toRequestError(error)
165
+ }
166
+ if (signal?.aborted) throw abortReason(signal)
167
+ await this.assertStill(auth, account, signal)
168
+ return result
169
+ }
170
+ }
171
+
172
+ private async tokenFor(
173
+ auth: CoreTokenSource,
174
+ forceRefresh: boolean,
175
+ signal?: AbortSignal,
176
+ ): Promise<{token: string; account: string}> {
177
+ if (signal?.aborted) throw abortReason(signal)
178
+ let token: string
179
+ try {
180
+ token = await auth.getCoreToken(forceRefresh ? {forceRefresh: true} : undefined)
181
+ } catch (error) {
182
+ if (signal?.aborted) throw abortReason(signal)
183
+ throw error
184
+ }
185
+ if (signal?.aborted) throw abortReason(signal)
186
+ const account = accountOf(token)
187
+ if (!account) throw new SessionChangedError("unreadable_token")
188
+ return {token, account}
189
+ }
190
+
191
+ /** Throws `SessionChangedError` unless the client holds `account`'s session right now. */
192
+ private async assertStill(auth: CoreTokenSource, account: string, signal?: AbortSignal): Promise<void> {
193
+ let current: string
194
+ try {
195
+ current = (await this.tokenFor(auth, false, signal)).account
196
+ } catch (error) {
197
+ // A session that ended mid-request is a change; any other trouble reading it is reported as it is.
198
+ if (error instanceof AuthExpiredError) throw new SessionChangedError("signed_out")
199
+ throw error
200
+ }
201
+ if (current !== account) throw new SessionChangedError("other_account")
202
+ }
203
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @fileoverview `cloud.core.account`: what the phone keeps on the signed-in person's Core account, over Core's
3
+ * `/api/account` router.
4
+ *
5
+ * GET /declared-age the age the person declared and when, both null until they answer
6
+ * PUT /declared-age {age} keep a new answer, dated now
7
+ *
8
+ * The engine asks a person's age once, when a miniapp rated above the host app's own App Store rating first installs
9
+ * or opens, and keeps it here (`declared-age.ts` in `@mentra/cloud-protocol`). It is never sent to a miniapp.
10
+ *
11
+ * Each call is made as the account whose Core token it carries (see `account-call.ts`): an answer that comes back after
12
+ * the account changed is discarded as `SessionChangedError`, and a 401 refreshes the token once. A failure keeps
13
+ * Core's status and error code on a `CoreRequestError` (`invalid_request`, `rate_limited`, `network_error`); an answer
14
+ * of another shape is a `CoreResponseError`.
15
+ */
16
+ import {DeclaredAgeSchema, type DeclaredAge} from "@mentra/cloud-protocol"
17
+ import type {HttpClient} from "../../http"
18
+ import {AccountCaller, CoreResponseError, type AccountCallOptions, type CoreTokenSource} from "./account-call"
19
+
20
+ const DECLARED_AGE_PATH = "/api/account/declared-age"
21
+
22
+ export class Account {
23
+ private readonly caller: AccountCaller
24
+
25
+ constructor(
26
+ private readonly http: HttpClient,
27
+ auth?: CoreTokenSource,
28
+ ) {
29
+ this.caller = new AccountCaller(auth)
30
+ }
31
+
32
+ /** The age the signed-in person declared, and when; both null until they answer. */
33
+ async declaredAge(opts?: AccountCallOptions): Promise<DeclaredAge> {
34
+ const body = await this.caller.run(
35
+ (bearer) =>
36
+ this.http.get<unknown>(DECLARED_AGE_PATH, {
37
+ bearer,
38
+ // A read: safe to retry.
39
+ idempotent: true,
40
+ ...(opts?.signal ? {signal: opts.signal} : {}),
41
+ }),
42
+ opts,
43
+ )
44
+ return readDeclaredAge(body)
45
+ }
46
+
47
+ /** Keep `age` as the signed-in person's declared age, dated now. Resolves with what Core kept. */
48
+ async setDeclaredAge(age: number, opts?: AccountCallOptions): Promise<DeclaredAge> {
49
+ const body = await this.caller.run(
50
+ (bearer) =>
51
+ this.http.put<unknown>(
52
+ DECLARED_AGE_PATH,
53
+ {age},
54
+ {
55
+ bearer,
56
+ // Sending the same answer again keeps the same age.
57
+ idempotent: true,
58
+ ...(opts?.signal ? {signal: opts.signal} : {}),
59
+ },
60
+ ),
61
+ opts,
62
+ )
63
+ const kept = readDeclaredAge(body)
64
+ if (kept.declaredAge !== age) throw new CoreResponseError("invalid_shape")
65
+ return kept
66
+ }
67
+ }
68
+
69
+ function readDeclaredAge(body: unknown): DeclaredAge {
70
+ const parsed = DeclaredAgeSchema.safeParse(body)
71
+ if (!parsed.success) throw new CoreResponseError("invalid_shape")
72
+ return {declaredAge: parsed.data.declaredAge, declaredAgeAt: parsed.data.declaredAgeAt}
73
+ }
@@ -7,7 +7,8 @@
7
7
  * core never touches credentials itself.
8
8
  *
9
9
  * Today it exposes the unified report submission surface, the support
10
- * profile update and the Fleet report.
10
+ * profile update, the Fleet report, the workspace calls, the miniapp
11
+ * registry calls and the person's declared age.
11
12
  *
12
13
  * Guardrail: this is device-facing only. It deliberately carries none of the
13
14
  * Dev Console / OEM Portal / store web UI surface; those are separate clients.
@@ -16,8 +17,27 @@
16
17
  * ("src/modules/core/core.ts").
17
18
  */
18
19
  import type { HttpClient } from "../../http";
19
- import type { FleetReport } from "@mentra/cloud-protocol";
20
+ import type {
21
+ DeclaredAge,
22
+ FleetDesiredState,
23
+ FleetReport,
24
+ RegistryRegisterRequest,
25
+ RegistryRegisterResponse,
26
+ RegistryStatusRequest,
27
+ RegistryStatusResponse,
28
+ } from "@mentra/cloud-protocol";
29
+ import type {
30
+ AcceptInvitationResult,
31
+ DeclineInvitationResult,
32
+ LeaveWorkspaceRequest,
33
+ MyWorkspaceResponse,
34
+ PendingInvitationsResponse,
35
+ } from "./workspace-types";
36
+ import type { AccountCallOptions, CoreTokenSource } from "./account-call";
37
+ import { Account } from "./account";
20
38
  import { Fleet, type FleetReportOutcome } from "./fleet";
39
+ import { Registry } from "./registry";
40
+ import { Workspaces } from "./workspaces";
21
41
  import {
22
42
  Reports,
23
43
  type AddReportArtifactsResult,
@@ -56,6 +76,13 @@ export type {
56
76
  SubmitReportResult,
57
77
  } from "./reports";
58
78
  export type { FleetAck, FleetAckResult, FleetReportOutcome } from "./fleet";
79
+ export {
80
+ CoreRequestError,
81
+ CoreResponseError,
82
+ SessionChangedError,
83
+ type AccountCallOptions,
84
+ type CoreTokenSource,
85
+ } from "./account-call";
59
86
  export type {
60
87
  SupportConnectionState,
61
88
  SupportProfileUpdateResult,
@@ -65,6 +92,11 @@ export type {
65
92
  /** The dependencies `cloud.core` is wired with. */
66
93
  export interface CoreDeps {
67
94
  http: HttpClient;
95
+ /**
96
+ * Where workspace, desired-state, registry and account calls get the signed-in account's Core token (`cloud.auth`).
97
+ * Without it those calls reject, because they must be made as one account.
98
+ */
99
+ auth?: CoreTokenSource;
68
100
  }
69
101
 
70
102
  /**
@@ -112,13 +144,48 @@ export class Core {
112
144
  * that Core token instead of the token source's.
113
145
  */
114
146
  report(batch: FleetReport, opts?: { signal?: AbortSignal; bearer?: string }): Promise<FleetReportOutcome>;
147
+ /**
148
+ * `GET /api/client/fleet/desired-state`, validated. Resolves only with a complete `managed` or `unmanaged` answer;
149
+ * every failure rejects (`CoreRequestError`, `CoreResponseError`, `SessionChangedError`, auth errors, abort), so
150
+ * none can be read as an empty set.
151
+ */
152
+ desiredState(opts?: AccountCallOptions): Promise<FleetDesiredState>;
153
+ };
154
+ readonly workspaces: {
155
+ /** `GET /api/client/workspaces/mine`. */
156
+ mine(opts?: AccountCallOptions): Promise<MyWorkspaceResponse>;
157
+ /** `GET /api/client/workspaces/invitations/mine`. */
158
+ pendingInvitations(opts?: AccountCallOptions): Promise<PendingInvitationsResponse>;
159
+ /** `POST /api/client/workspaces/invitations/:invitationId/accept`. */
160
+ acceptInvitation(invitationId: string, opts?: AccountCallOptions): Promise<AcceptInvitationResult>;
161
+ /** `POST /api/client/workspaces/invitations/:invitationId/decline`. */
162
+ declineInvitation(invitationId: string, opts?: AccountCallOptions): Promise<DeclineInvitationResult>;
163
+ /** `POST /api/client/workspaces/leave`, naming `opts.workspaceId` when given. */
164
+ leave(opts?: AccountCallOptions & LeaveWorkspaceRequest): Promise<void>;
165
+ };
166
+ /** The miniapp registry (`registry.ts`). Each call is made as one account. */
167
+ readonly registry: {
168
+ /** `POST /api/client/registry/register`, at each install of a miniapp URL. */
169
+ registerMiniappUrl(request: RegistryRegisterRequest, opts?: AccountCallOptions): Promise<RegistryRegisterResponse>;
170
+ /** `POST /api/client/registry/status`: one batch of installed URLs. */
171
+ registryStatus(request: RegistryStatusRequest, opts?: AccountCallOptions): Promise<RegistryStatusResponse>;
172
+ };
173
+ /** What the phone keeps on the signed-in person's account (`account.ts`). Each call is made as one account. */
174
+ readonly account: {
175
+ /** `GET /api/account/declared-age`: the age the person declared and when, both null until they answer. */
176
+ declaredAge(opts?: AccountCallOptions): Promise<DeclaredAge>;
177
+ /** `PUT /api/account/declared-age`: keep `age` as the person's declared age, dated now. */
178
+ setDeclaredAge(age: number, opts?: AccountCallOptions): Promise<DeclaredAge>;
115
179
  };
116
180
 
117
181
  constructor(deps: CoreDeps) {
118
- const { http } = deps;
182
+ const { http, auth } = deps;
119
183
  const reports = new Reports({ http });
120
184
  const supportProfiles = new SupportProfiles(http);
121
- const fleet = new Fleet(http);
185
+ const fleet = new Fleet(http, auth);
186
+ const workspaces = new Workspaces(http, auth);
187
+ const registry = new Registry(http, auth);
188
+ const account = new Account(http, auth);
122
189
 
123
190
  this.reports = {
124
191
  submit: reports.submit.bind(reports),
@@ -134,6 +201,22 @@ export class Core {
134
201
  };
135
202
  this.fleet = {
136
203
  report: fleet.report.bind(fleet),
204
+ desiredState: fleet.desiredState.bind(fleet),
205
+ };
206
+ this.workspaces = {
207
+ mine: workspaces.mine.bind(workspaces),
208
+ pendingInvitations: workspaces.pendingInvitations.bind(workspaces),
209
+ acceptInvitation: workspaces.acceptInvitation.bind(workspaces),
210
+ declineInvitation: workspaces.declineInvitation.bind(workspaces),
211
+ leave: workspaces.leave.bind(workspaces),
212
+ };
213
+ this.registry = {
214
+ registerMiniappUrl: registry.registerMiniappUrl.bind(registry),
215
+ registryStatus: registry.registryStatus.bind(registry),
216
+ };
217
+ this.account = {
218
+ declaredAge: account.declaredAge.bind(account),
219
+ setDeclaredAge: account.setDeclaredAge.bind(account),
137
220
  };
138
221
  }
139
222
  }
@@ -1,8 +1,16 @@
1
- import {FLEET_NOT_INSTALLED, FLEET_SCHEMA_VERSION, type FleetReport} from "@mentra/cloud-protocol"
1
+ import {
2
+ FLEET_NOT_INSTALLED,
3
+ FLEET_SCHEMA_VERSION,
4
+ FleetDesiredStateSchema,
5
+ type FleetDesiredState,
6
+ type FleetReport,
7
+ } from "@mentra/cloud-protocol"
2
8
  import {AuthExpiredError, HttpError} from "../../errors"
3
9
  import type {HttpClient} from "../../http"
10
+ import {AccountCaller, CoreResponseError, type AccountCallOptions, type CoreTokenSource} from "./account-call"
4
11
 
5
12
  const FLEET_REPORT_PATH = "/api/client/fleet/report"
13
+ const FLEET_DESIRED_STATE_PATH = "/api/client/fleet/desired-state"
6
14
 
7
15
  /** Core's whole-response error codes are short snake_case words; anything else is not safe to surface. */
8
16
  const ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
@@ -27,6 +35,8 @@ export interface FleetAckResult {
27
35
  export interface FleetAck {
28
36
  schemaVersion: typeof FLEET_SCHEMA_VERSION
29
37
  results: FleetAckResult[]
38
+ /** The account's desired-state revision at the time of the answer (Phase 11). Absent from an older Fleet. */
39
+ revision?: number
30
40
  }
31
41
 
32
42
  /**
@@ -96,7 +106,45 @@ function outcomeForHttpError(error: HttpError): FleetReportOutcome {
96
106
  }
97
107
 
98
108
  export class Fleet {
99
- constructor(private readonly http: HttpClient) {}
109
+ private readonly caller: AccountCaller
110
+
111
+ constructor(
112
+ private readonly http: HttpClient,
113
+ auth?: CoreTokenSource,
114
+ ) {
115
+ this.caller = new AccountCaller(auth)
116
+ }
117
+
118
+ /**
119
+ * Fetches the account's desired state (`GET /api/client/fleet/desired-state`), validated against
120
+ * `FleetDesiredStateSchema`.
121
+ *
122
+ * Resolves only with a complete, valid `managed` or `unmanaged` answer. Everything else rejects, so a failure can
123
+ * never be read as "nothing assigned" or "unmanaged" and make the phone drop what it holds:
124
+ * - `CoreRequestError`: any non-success answer (the status and Core's code are kept: 503 `fleet_unavailable`,
125
+ * 404 `fleet_not_installed`, 403, 429, ...) and a network failure (`status` 0, code `network_error`).
126
+ * - `CoreResponseError`: Core answered 2xx but the body is not desired state: no body, a missing field (an entry
127
+ * without `url`, a managed answer without `workspace`), an unknown key, or a `status` this client does not know
128
+ * (`reason: "unknown_status"`, for example a later `paused`).
129
+ * - `SessionChangedError`: the account changed while the request was out; the answer is dropped.
130
+ * - `AuthExpiredError` / `AuthUnavailableError` from the token source, and the abort reason on abort.
131
+ *
132
+ * A 401 refreshes the Core token once and sends again. `opts.expectedAccount` refuses the call when the client
133
+ * holds another account's token.
134
+ */
135
+ async desiredState(opts?: AccountCallOptions): Promise<FleetDesiredState> {
136
+ const body = await this.caller.run(
137
+ bearer =>
138
+ this.http.get<unknown>(FLEET_DESIRED_STATE_PATH, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
139
+ opts,
140
+ )
141
+ const parsed = FleetDesiredStateSchema.safeParse(body)
142
+ if (parsed.success) return parsed.data
143
+ const status = typeof body === "object" && body !== null && "status" in body ? body.status : undefined
144
+ throw new CoreResponseError(
145
+ typeof status === "string" && status !== "managed" && status !== "unmanaged" ? "unknown_status" : "invalid_shape",
146
+ )
147
+ }
100
148
 
101
149
  /**
102
150
  * Reports one batch of Fleet records to the phone's own Core.
@@ -171,5 +219,8 @@ function readAck(body: unknown): FleetAck | null {
171
219
  if (isWholeNumber(raw.retryAfterSeconds)) result.retryAfterSeconds = raw.retryAfterSeconds
172
220
  results.push(result)
173
221
  }
174
- return {schemaVersion: FLEET_SCHEMA_VERSION, results}
222
+ const ack: FleetAck = {schemaVersion: FLEET_SCHEMA_VERSION, results}
223
+ // A newer Fleet's revision tells the phone to fetch desired state. Anything but a whole number of 1 or more is not one.
224
+ if (typeof body.revision === "number" && Number.isSafeInteger(body.revision) && body.revision >= 1) ack.revision = body.revision
225
+ return ack
175
226
  }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @fileoverview `cloud.core.registry`: the Mentra App's registry calls, over Core's `/api/client/registry` router.
3
+ *
4
+ * POST /register at each install of a miniapp URL; Core verifies the URL and answers
5
+ * `accepted` (with Core's verified `miniapp.json`), `accepted_unverified`, `not_a_miniapp` or
6
+ * `archived`
7
+ * POST /status one batch of installed URLs and versions; Core answers `active`, `archived` or `unknown` for
8
+ * each, and how long the answer stays valid
9
+ *
10
+ * Each call is made as the account whose Core token it carries (see `account-call.ts`): an answer that comes back
11
+ * after the account changed is discarded as `SessionChangedError`, and a 401 refreshes the token once. A failure keeps
12
+ * Core's status and error code on a `CoreRequestError`: `email_unverified` (403), `rate_limited` (429, with
13
+ * `retryAfterSeconds`), `invalid_request` (400), `unavailable` (503), `network_error` (no answer). An answer of
14
+ * another shape, or a `result` this client doesn't know, is a `CoreResponseError`, never a guess.
15
+ */
16
+ import {
17
+ RegistryRegisterResponseSchema,
18
+ RegistryStatusResponseSchema,
19
+ type RegistryRegisterRequest,
20
+ type RegistryRegisterResponse,
21
+ type RegistryStatusRequest,
22
+ type RegistryStatusResponse,
23
+ } from "@mentra/cloud-protocol"
24
+ import type {HttpClient} from "../../http"
25
+ import {AccountCaller, CoreResponseError, type AccountCallOptions, type CoreTokenSource} from "./account-call"
26
+
27
+ const REGISTER_PATH = "/api/client/registry/register"
28
+ const STATUS_PATH = "/api/client/registry/status"
29
+ const KNOWN_RESULTS = new Set(["accepted", "accepted_unverified", "not_a_miniapp", "archived"])
30
+
31
+ export class Registry {
32
+ private readonly caller: AccountCaller
33
+
34
+ constructor(
35
+ private readonly http: HttpClient,
36
+ auth?: CoreTokenSource,
37
+ ) {
38
+ this.caller = new AccountCaller(auth)
39
+ }
40
+
41
+ /**
42
+ * Registers a miniapp URL at install. `reported` is what the phone read from `<url>/miniapp.json`; Core keeps it
43
+ * only when it can't read the URL itself. Resolves with Core's verdict; rejects for every failure (see the file
44
+ * comment), so a caller can tell "Core said no" from "Core didn't answer".
45
+ */
46
+ async registerMiniappUrl(request: RegistryRegisterRequest, opts?: AccountCallOptions): Promise<RegistryRegisterResponse> {
47
+ const body = await this.caller.run(
48
+ (bearer) =>
49
+ this.http.post<unknown>(REGISTER_PATH, request, {
50
+ bearer,
51
+ // Registering a URL twice gives the same answer, so a transient network failure may be retried.
52
+ idempotent: true,
53
+ ...(opts?.signal ? {signal: opts.signal} : {}),
54
+ }),
55
+ opts,
56
+ )
57
+ const parsed = RegistryRegisterResponseSchema.safeParse(body)
58
+ if (parsed.success) return parsed.data
59
+ const result = typeof body === "object" && body !== null && "result" in body ? body.result : undefined
60
+ throw new CoreResponseError(
61
+ typeof result === "string" && !KNOWN_RESULTS.has(result) ? "unknown_status" : "invalid_shape",
62
+ )
63
+ }
64
+
65
+ /** The registry status of each installed URL, in the order sent, with how long the answer stays valid. */
66
+ async registryStatus(request: RegistryStatusRequest, opts?: AccountCallOptions): Promise<RegistryStatusResponse> {
67
+ const body = await this.caller.run(
68
+ (bearer) =>
69
+ this.http.post<unknown>(STATUS_PATH, request, {
70
+ bearer,
71
+ // A read: safe to retry.
72
+ idempotent: true,
73
+ ...(opts?.signal ? {signal: opts.signal} : {}),
74
+ }),
75
+ opts,
76
+ )
77
+ const parsed = RegistryStatusResponseSchema.safeParse(body)
78
+ if (!parsed.success || parsed.data.statuses.length !== request.entries.length) {
79
+ throw new CoreResponseError("invalid_shape")
80
+ }
81
+ return parsed.data
82
+ }
83
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @fileoverview The wire shapes of Core's `/api/client/workspaces` router, as the Mentra App reads them.
3
+ *
4
+ * `@mentra/workspace-contract` defines them for Core, but it is a private package and this one is published, so a
5
+ * consumer of `@mentra/cloud-client` could not resolve an import of it. They are restated here instead;
6
+ * `workspace-types.test.ts` holds each one equal to the contract's, so the two cannot drift apart.
7
+ */
8
+
9
+ /** A role in a workspace (`WorkspaceRole` in the contract). */
10
+ export type ClientWorkspaceRole = "member" | "developer" | "admin" | "owner";
11
+
12
+ /** An invitation as the invitee sees it before accepting. It never carries the token or its hash. */
13
+ export interface InvitationPreview {
14
+ invitationId: string;
15
+ workspaceId: string;
16
+ workspaceName: string;
17
+ /** The invited address. */
18
+ email: string;
19
+ role: ClientWorkspaceRole;
20
+ /** Who sent it, by email address; null when the system did, or the address is no longer known. */
21
+ invitedByEmail: string | null;
22
+ expiresAt: string;
23
+ }
24
+
25
+ /** The workspace the signed-in phone's person belongs to (`GET /api/client/workspaces/mine`). */
26
+ export interface MyWorkspace {
27
+ workspaceId: string;
28
+ name: string;
29
+ role: ClientWorkspaceRole;
30
+ membershipId: string;
31
+ }
32
+
33
+ /** `GET /api/client/workspaces/mine`. */
34
+ export interface MyWorkspaceResponse {
35
+ workspace: MyWorkspace | null;
36
+ }
37
+
38
+ /** `GET /api/client/workspaces/invitations/mine`: the invitations addressed to the signed-in person. */
39
+ export interface PendingInvitationsResponse {
40
+ invitations: InvitationPreview[];
41
+ }
42
+
43
+ /** `POST /api/client/workspaces/invitations/:invitationId/accept`. */
44
+ export interface AcceptInvitationResult {
45
+ workspace: MyWorkspace;
46
+ }
47
+
48
+ /** `POST /api/client/workspaces/invitations/:invitationId/decline`. Declining twice is idempotent. */
49
+ export interface DeclineInvitationResult {
50
+ invitationId: string;
51
+ declined: true;
52
+ }
53
+
54
+ /**
55
+ * `POST /api/client/workspaces/leave`. With `workspaceId`, Core leaves that workspace only while the person is in
56
+ * it, and answers `membership_changed` (409) otherwise; without one, the person's workspace.
57
+ */
58
+ export interface LeaveWorkspaceRequest {
59
+ workspaceId?: string;
60
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * @fileoverview `cloud.core.workspaces`: the Mentra App's own view of the workspace the signed-in person belongs to,
3
+ * over Core's `/api/client/workspaces` router.
4
+ *
5
+ * GET /mine the person's workspace, or `{workspace: null}`
6
+ * GET /invitations/mine invitations addressed to their verified email
7
+ * POST /invitations/:invitationId/accept join the workspace the invitation is for
8
+ * POST /invitations/:invitationId/decline turn it down (idempotent)
9
+ * POST /leave leave the workspace (204; the only Owner cannot)
10
+ *
11
+ * Each call is made as the account whose Core token it carries (see `account-call.ts`): an answer that comes back after
12
+ * the account changed is discarded as `SessionChangedError`, and a 401 refreshes the token once. A failure keeps
13
+ * Core's status and error code on a `CoreRequestError` (`already_in_workspace`, `last_owner`, `invitation_expired`,
14
+ * `invitation_not_found`, `email_unverified`, `membership_changed`, ...) and never carries Core's wording.
15
+ */
16
+ import type {
17
+ AcceptInvitationResult,
18
+ DeclineInvitationResult,
19
+ InvitationPreview,
20
+ LeaveWorkspaceRequest,
21
+ MyWorkspace,
22
+ MyWorkspaceResponse,
23
+ PendingInvitationsResponse,
24
+ } from "./workspace-types"
25
+ import type {HttpClient} from "../../http"
26
+ import {AccountCaller, CoreResponseError, type AccountCallOptions, type CoreTokenSource} from "./account-call"
27
+
28
+ const BASE = "/api/client/workspaces"
29
+
30
+ function isObject(value: unknown): value is Record<string, unknown> {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value)
32
+ }
33
+
34
+ function isText(value: unknown): value is string {
35
+ return typeof value === "string" && value.length > 0
36
+ }
37
+
38
+ function readWorkspace(value: unknown): MyWorkspace {
39
+ if (
40
+ !isObject(value) ||
41
+ !isText(value.workspaceId) ||
42
+ typeof value.name !== "string" ||
43
+ !isText(value.role) ||
44
+ !isText(value.membershipId)
45
+ ) {
46
+ throw new CoreResponseError("invalid_shape")
47
+ }
48
+ return {
49
+ workspaceId: value.workspaceId,
50
+ name: value.name,
51
+ role: value.role as MyWorkspace["role"],
52
+ membershipId: value.membershipId,
53
+ }
54
+ }
55
+
56
+ function readInvitation(value: unknown): InvitationPreview {
57
+ if (
58
+ !isObject(value) ||
59
+ !isText(value.invitationId) ||
60
+ !isText(value.workspaceId) ||
61
+ typeof value.workspaceName !== "string" ||
62
+ typeof value.email !== "string" ||
63
+ !isText(value.role) ||
64
+ (value.invitedByEmail !== null && typeof value.invitedByEmail !== "string") ||
65
+ !isText(value.expiresAt)
66
+ ) {
67
+ throw new CoreResponseError("invalid_shape")
68
+ }
69
+ return {
70
+ invitationId: value.invitationId,
71
+ workspaceId: value.workspaceId,
72
+ workspaceName: value.workspaceName,
73
+ email: value.email,
74
+ role: value.role as InvitationPreview["role"],
75
+ invitedByEmail: value.invitedByEmail,
76
+ expiresAt: value.expiresAt,
77
+ }
78
+ }
79
+
80
+ export class Workspaces {
81
+ private readonly caller: AccountCaller
82
+
83
+ constructor(
84
+ private readonly http: HttpClient,
85
+ auth?: CoreTokenSource,
86
+ ) {
87
+ this.caller = new AccountCaller(auth)
88
+ }
89
+
90
+ /** The workspace the signed-in person belongs to, or `{workspace: null}`. */
91
+ async mine(opts?: AccountCallOptions): Promise<MyWorkspaceResponse> {
92
+ const body = await this.caller.run(
93
+ bearer => this.http.get<unknown>(`${BASE}/mine`, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
94
+ opts,
95
+ )
96
+ if (!isObject(body) || !("workspace" in body)) throw new CoreResponseError("invalid_shape")
97
+ return {workspace: body.workspace === null ? null : readWorkspace(body.workspace)}
98
+ }
99
+
100
+ /** The invitations addressed to the signed-in person's verified email that they can still accept. */
101
+ async pendingInvitations(opts?: AccountCallOptions): Promise<PendingInvitationsResponse> {
102
+ const body = await this.caller.run(
103
+ bearer =>
104
+ this.http.get<unknown>(`${BASE}/invitations/mine`, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
105
+ opts,
106
+ )
107
+ if (!isObject(body) || !Array.isArray(body.invitations)) throw new CoreResponseError("invalid_shape")
108
+ return {invitations: body.invitations.map(readInvitation)}
109
+ }
110
+
111
+ /** Joins the workspace the invitation is for. `already_in_workspace` (409) means leave the current one first. */
112
+ async acceptInvitation(invitationId: string, opts?: AccountCallOptions): Promise<AcceptInvitationResult> {
113
+ const body = await this.caller.run(
114
+ bearer =>
115
+ this.http.post<unknown>(`${BASE}/invitations/${encodeURIComponent(invitationId)}/accept`, undefined, {
116
+ bearer,
117
+ ...(opts?.signal ? {signal: opts.signal} : {}),
118
+ }),
119
+ opts,
120
+ )
121
+ if (!isObject(body)) throw new CoreResponseError("invalid_shape")
122
+ return {workspace: readWorkspace(body.workspace)}
123
+ }
124
+
125
+ /** Turns the invitation down. Declining twice is fine; no membership changes. */
126
+ async declineInvitation(invitationId: string, opts?: AccountCallOptions): Promise<DeclineInvitationResult> {
127
+ const body = await this.caller.run(
128
+ bearer =>
129
+ this.http.post<unknown>(`${BASE}/invitations/${encodeURIComponent(invitationId)}/decline`, undefined, {
130
+ bearer,
131
+ // Idempotent on Core, so a transient network failure may be retried.
132
+ idempotent: true,
133
+ ...(opts?.signal ? {signal: opts.signal} : {}),
134
+ }),
135
+ opts,
136
+ )
137
+ if (!isObject(body) || !isText(body.invitationId) || body.declined !== true) {
138
+ throw new CoreResponseError("invalid_shape")
139
+ }
140
+ return {invitationId: body.invitationId, declined: true}
141
+ }
142
+
143
+ /**
144
+ * Leaves the workspace: `opts.workspaceId` when given, which Core refuses with `membership_changed` (409) once the
145
+ * person is no longer in it. `last_owner` (409) means the only Owner cannot leave; `not_found` that there is none.
146
+ */
147
+ async leave(opts?: AccountCallOptions & LeaveWorkspaceRequest): Promise<void> {
148
+ const body: LeaveWorkspaceRequest | undefined = opts?.workspaceId ? {workspaceId: opts.workspaceId} : undefined
149
+ await this.caller.run(
150
+ bearer => this.http.post<unknown>(`${BASE}/leave`, body, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
151
+ opts,
152
+ )
153
+ }
154
+ }
@@ -70,7 +70,7 @@ export type {
70
70
  RouteAvoidances,
71
71
  ReverseGeocodeResult,
72
72
  } from "./maps";
73
- export type { RuntimeTtsSpeakOptions, RuntimeTtsSpeechSource } from "./tts";
73
+ export type { RuntimeTtsFormat, RuntimeTtsSpeakOptions, RuntimeTtsSpeechSource } from "./tts";
74
74
  export type { RuntimeAudioTransport } from "./audio-udp";
75
75
  export type { RuntimeStatus, RuntimeSnapshot } from "./status";
76
76
 
@@ -10,7 +10,24 @@ import type { HttpClient } from "../../http";
10
10
 
11
11
  const TTS_PATH = "/api/tts/speak";
12
12
 
13
+ /**
14
+ * Audio encoding of the returned source. `mp3` (default) plays in a media
15
+ * player. `pcm_24000` is raw signed 16-bit little-endian mono PCM at 24 kHz,
16
+ * for hosts that stream it into a PCM player as it downloads.
17
+ */
18
+ export type RuntimeTtsFormat = "mp3" | "pcm_24000";
19
+
20
+ /** Content-type prefix the runtime must return for each format. */
21
+ const FORMAT_CONTENT_TYPE: Record<RuntimeTtsFormat, string> = {
22
+ mp3: "audio/",
23
+ pcm_24000: "audio/pcm",
24
+ };
25
+
13
26
  export interface RuntimeTtsSpeakOptions {
27
+ /** Reuse a successful runtime readiness check for 30 seconds. */
28
+ reusePreflight?: boolean;
29
+ /** Audio encoding to request. Default `mp3`. */
30
+ format?: RuntimeTtsFormat;
14
31
  voiceId?: string;
15
32
  voice_id?: string;
16
33
  modelId?: string;
@@ -31,6 +48,7 @@ export interface TtsDeps {
31
48
 
32
49
  export class Tts {
33
50
  private readonly http: HttpClient;
51
+ private ready?: { endpoint: string; format: RuntimeTtsFormat; contentType: string; expiresAt: number };
34
52
 
35
53
  constructor(deps: TtsDeps) {
36
54
  this.http = deps.http;
@@ -49,11 +67,31 @@ export class Tts {
49
67
  throw new Error("runtime.tts.speak requires text");
50
68
  }
51
69
 
70
+ const format = options.format ?? "mp3";
52
71
  const path = this.buildTtsPath(text, options);
53
- const res = await this.http.head(path, { idempotent: true });
54
- const contentType = res.headers.get("content-type") ?? "";
55
- if (!contentType.toLowerCase().startsWith("audio/")) {
56
- throw new Error(`Runtime TTS returned non-audio content-type: ${contentType || "missing"}`);
72
+ const endpoint = this.http.url(TTS_PATH);
73
+ let contentType: string;
74
+ const ready = this.ready;
75
+ if (
76
+ options.reusePreflight &&
77
+ ready?.endpoint === endpoint &&
78
+ ready.format === format &&
79
+ ready.expiresAt > Date.now()
80
+ ) {
81
+ contentType = ready.contentType;
82
+ } else {
83
+ const res = await this.http.head(path, { idempotent: true });
84
+ contentType = res.headers.get("content-type") ?? "";
85
+ const normalized = contentType.toLowerCase();
86
+ if (!normalized.startsWith("audio/")) {
87
+ throw new Error(`Runtime TTS returned non-audio content-type: ${contentType || "missing"}`);
88
+ }
89
+ // A runtime that predates `format` ignores it and answers MP3. Playing
90
+ // those bytes as PCM would be noise, so refuse before playback.
91
+ if (!normalized.startsWith(FORMAT_CONTENT_TYPE[format])) {
92
+ throw new Error(`Runtime TTS does not support format ${format} (returned ${contentType})`);
93
+ }
94
+ if (options.reusePreflight) this.ready = { endpoint, format, contentType, expiresAt: Date.now() + 30_000 };
57
95
  }
58
96
 
59
97
  return {
@@ -76,6 +114,9 @@ export class Tts {
76
114
  const voiceSettings = options.voiceSettings ?? options.voice_settings;
77
115
  if (voiceSettings) query.set("voice_settings", JSON.stringify(voiceSettings));
78
116
 
117
+ // MP3 is the runtime default; leave its URL unchanged for older runtimes.
118
+ if (options.format && options.format !== "mp3") query.set("format", options.format);
119
+
79
120
  return `${TTS_PATH}?${query.toString()}`;
80
121
  }
81
122
  }