@witbitz/sdk 4.8.0 → 4.9.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/witbitz-sdk.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { isSealedAppRoom } from './sealedRoomWire.js'
1
2
  // witbitz-sdk.js — the small, stable Witbitz application SDK.
2
3
  //
3
4
  // Witbitz is a runtime: a shared room with humans, an AI agent, sealed persistent state, identity and authority. This
@@ -15,6 +16,7 @@
15
16
  // cross-origin import of this one URL pulls the transitive crypto from this origin automatically. The room key never
16
17
  // reaches the server — only its commitment — and reads are content-blind (the client opens the sealed ledger locally).
17
18
  // `space.sealedProof()` returns the exact opaque bytes the server stores, so an app can PROVE that at rest.
19
+ import { makeAccountRoomAccess } from './roomPass.js'
18
20
  import { mirrorBatches } from './mirrorBatch.js'
19
21
  import { makeSpaceClient } from './spaceClient.js'
20
22
  import { ownAdmissionEntries } from './emptySpaces.js'
@@ -102,7 +104,7 @@ const withTurnOk = (r) => { const k = turnVerdict(r).kind; return withUsage({ ..
102
104
  /** The server's usage record → { tokensIn, tokensOut, tokensCached, costMicros, costUsd, calls, models, source } (sdkTurn turnUsage). */
103
105
  const withUsage = (r) => { if (r && r.usage) { const u = turnUsage(r.usage); if (u) r.usage = u; else delete r.usage } return r }
104
106
  import { renameRefusalText } from './renameRefusal.js' // why a rename was refused — the app's words
105
- import { isTitleEntry, latestTitle, titleFromDoc, sendRename as sendRoomRename, cleanTitle, isDirect, directPeer, isLaneCopy as laneCopy } from './roomName.js' // a room's NAME — the same rule the Spaces app reads it by
107
+ import { isTitleEntry, latestTitle, titleFromDoc, sendRename as sendRoomRename, cleanTitle, isDirect, directPeer, taggedDirectPeer, isLaneCopy as laneCopy } from './roomName.js' // a room's NAME — the same rule the Spaces app reads it by
106
108
  import { pollVerdict } from './pollVerdict.js' // one verdict on a poll answer, shared with the Spaces app
107
109
  import { hide, redacted, REDACTED } from './sdkRedact.js'
108
110
  import { WitbitzAdmin } from './witbitz-admin.js'
@@ -201,7 +203,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
201
203
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
202
204
  export { isLaneCopy } from './roomName.js' // is this message a lane's copy of its shared room's line? (the app's own test, sdk-agents.md#lanes)
203
205
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
204
- export const SDK_VERSION = '4.8.0'
206
+ export const SDK_VERSION = '4.9.0'
205
207
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
206
208
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
207
209
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -433,6 +435,7 @@ export class Witbitz {
433
435
  delCommit: (room) => (this.erasure ? this.erasure._commitFor(room) : null), // only this account can later delete a room it created (sdkErase.js)
434
436
  // INTERNAL — a builder's VAULT (vault-core.js) only: the room pass of its account on the Witbitz account service (roomPass.js,
435
437
  // docs/device-gate-design.md) on this client's verified-Space requests. Not an option for pages.
438
+ accountRoomAccess: makeAccountRoomAccess({ issueRoom: (room, pub, kind) => this.backup._v2.accountRoomPassFor(this.backup, room, pub, kind) }),
436
439
  ...(_roomPass && typeof _roomPass.fieldsFor === 'function' ? { roomPass: _roomPass } : {}),
437
440
  ...(typeof _renewSignIn === 'function' ? { renewSignIn: _renewSignIn } : {}), // INTERNAL (the vault): renew the session once on `pass: app_unnamed`
438
441
  auth: async () => {
@@ -1218,6 +1221,7 @@ export class Witbitz {
1218
1221
  /** @private one call to the builder's app-half function → { status, ...answer }. Same-origin by design: the function
1219
1222
  * answers its own origin only. */
1220
1223
  async _appShareCall(body) {
1224
+ if (isSealedAppRoom(body?.room)) return { status: 426, error: 'sealed_transport_required' }
1221
1225
  let r
1222
1226
  try { r = await this._fetch(this._appShareUrl, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }) } catch { return { status: 0, error: 'appshare_unreachable' } }
1223
1227
  const j = await r.json().catch(() => ({}))
@@ -1340,6 +1344,7 @@ export class Witbitz {
1340
1344
  // combine must match the room's commitment before it is used (§6.4).
1341
1345
  const room = roomFromLink(s), userShare = fragParam(s, 'us'), want = fragParam(s, 'spc')
1342
1346
  if (!room || !userShare) throw sdkError('witbitz: that link is not a Space link (or its key is incomplete)', 'invalid_link')
1347
+ if (isSealedAppRoom(room)) throw sdkError('This Space needs a sealed share transport', 'sealed_transport_required')
1343
1348
  const kept = this.backup.keyFor(room)
1344
1349
  // ⚑ A SPLIT ENCLAVE SPACE (the hosted app makes them: a backend create, then the enclave seal — the owner, 2026-11-25: "Keep this
1345
1350
  // Space always on" on a hosted Enclave Space ended "could not read this Space's gate"). The app half is the standard tier's to serve,
@@ -1863,6 +1868,9 @@ export class Space {
1863
1868
  r = await doTurn()
1864
1869
  }
1865
1870
  if (turnVerdict(r).kind === 'pending') return { ...r, pending: true, ok: true }
1871
+ // sync sweep 2026-12-04 N3: a quiet turn whose append failed answers 200 with `memberStored: false` — the app keeps that
1872
+ // message unconfirmed (space.js), and send() said ok: true for a message the room did not keep
1873
+ if (r && r.status === 200 && r.memberStored === false && !r.error) return withUsage({ ...r, ok: false, error: 'not_stored', retryable: true, detail: 'the room did not store the message — send it again' })
1866
1874
  return withTurnOk(r)
1867
1875
  }
1868
1876
 
@@ -2252,11 +2260,23 @@ export class Space {
2252
2260
  * `{ email }` (or `{ username }` for an older room), or null when this is not a direct chat you are in. Call the chat by
2253
2261
  * them, as the Spaces app does; nobody renames a direct chat (`rename()` → `direct_chat`). Needs a signed-in session. */
2254
2262
  async directPeer() {
2263
+ // sync sweep 2026-12-04 O26: a chat of two @username TAGS names nobody on its list — the app finds the other person through the
2264
+ // verified roster (roomName.taggedDirectPeer); so does the SDK now. In a vault its own Space answers (it holds the sign-in).
2265
+ if (this._wb?.vault?._c?.roomAccount) {
2266
+ try { return await this._wb.vault._c.roomAccount(this.room, 'roster', 'directPeer') } catch (err) { if (err?.code !== 'vault_refused') throw err }
2267
+ }
2255
2268
  const sess = this._wb && this._wb._session
2256
2269
  let cfg
2257
2270
  try { cfg = await this._gateConfig() } catch (e) { if (e && e.code === 'sign_in_required') throw e; return null }
2258
2271
  const me = this._wb && this._wb.vault ? ((await this._wb.vault.whoami()) || {}).email : sess && sess.email // in a vault, its signed-in member
2259
- return isDirect(cfg) && cfg.admission === 'email' ? directPeer(cfg, me) : null
2272
+ if (!isDirect(cfg) || cfg.admission !== 'email') return null
2273
+ const peer = directPeer(cfg, me)
2274
+ if (peer || !me) return peer
2275
+ return taggedDirectPeer(cfg, this.room, {
2276
+ myTags: () => signedInRoomTags(this._client, this.room, sess?.idToken),
2277
+ roster: async () => { const b = await this._client.state(this.room, this._mk, ROSTER_DOC); return b?.status === 200 ? b.seen : null },
2278
+ userTag: (name, room) => this._client.userTag(name, room),
2279
+ }).catch(() => null)
2260
2280
  }
2261
2281
 
2262
2282
  _invitationMatches(cfg, seen) {
@@ -2746,15 +2766,15 @@ export class Space {
2746
2766
  * → { how: 'none'|'in_place'|'fork'|'new_room'|'refused', history: 'kept'|'carried'|'not_carried'|null, call, steps,
2747
2767
  * reason?, code? } */
2748
2768
  async plan(change = {}) {
2749
- let cfg = null, gatedUnread = false
2750
- if (change && change.admission !== undefined && !this._sharedRoom) { this._gateCfg = null; try { cfg = await this._gateConfig() } catch (e) { if (e && e.code === 'sign_in_required') gatedUnread = true; else if (e && e.code !== 'config_unavailable') throw e } } // signed out in a gated room: a refusal, not a throw (sdk-assistant.md#changing-the-assistant)
2769
+ let cfg = null, gatedUnread = false, cfgUnread = false
2770
+ if (change && change.admission !== undefined && !this._sharedRoom) { this._gateCfg = null; try { cfg = await this._gateConfig({ plainMark: true }) } catch (e) { if (e && e.code === 'sign_in_required') gatedUnread = true; else if (e && e.code === 'config_unavailable') cfgUnread = true; else throw e } } // plainMark + cfgUnread: an open room reads { plain: true }, so a FAILED read is told apart (sync sweep 12-04 O27) // signed out in a gated room: a refusal, not a throw (sdk-assistant.md#changing-the-assistant)
2751
2771
  else if (change && (change.agent || change.data !== undefined || change.platformTools !== undefined || change.framing !== undefined || change.dataWrites !== undefined || change.safeMedia !== undefined || change.lanes !== undefined) && typeof this._client.getConfig === 'function') { try { const c = await this._client.getConfig(this.room, this._mk); gatedUnread = !!(c && c.gated === true && !c.allow); cfg = c && typeof c === 'object' && !gatedUnread ? c : null } catch { cfg = null } } // the in-place rules need the room's admins (sdkPlan.js)
2752
2772
  const sess = this._wb && this._wb._session
2753
2773
  const me = this._wb && this._wb.vault ? String(((await this._wb.vault.whoami()) || {}).email || '') // in a vault, its signed-in member (sync sweep 10-15 #2)
2754
2774
  : sess && (!sess.exp || sess.exp > Date.now()) ? String(sess.email || '') : ''
2755
2775
  const roles = rolesOf(cfg), tagged = !!(roles.ownerTags.length || roles.adminTags.length)
2756
2776
  const role = tagged && me ? (this._wb?.vault ? await this._wb.vault._c.roomAccount(this.room, 'roster', 'sessionRole') : await sessionRole(this, cfg, me)) : undefined
2757
- const out = planChange(change, { cfg, me, role, lane: !!(this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)), activeLane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, signIn: signInHow(this._wb) })
2777
+ const out = planChange(change, { cfg, me, role, lane: !!(this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)), activeLane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, cfgUnread, signIn: signInHow(this._wb) })
2758
2778
  if (out.how === 'in_place' && change.agent && change.agent.model && this._wb) { try { await this._wb._checkModel(change.agent.model) } catch (e) { return { how: 'refused', history: null, call: null, steps: out.steps, reason: String(e.message || e), code: e.code || 'invalid_model' } } }
2759
2779
  return out
2760
2780
  }
@@ -3136,9 +3156,9 @@ export class Space {
3136
3156
  * until a human calls approve() (posts the crossing / runs your handler on this device) or deny().
3137
3157
  * • `resolved` ({ id, approved, action, result? }) — after a decision. */
3138
3158
  export class Lane extends Space {
3139
- constructor(client, { room, mk, link, viewer, sharedRoom, sharedMk, actions, resume, wb = null, shared = null, mirror = false, split = false, poll, handlers, live, crossTier = false }) {
3159
+ constructor(client, { room, mk, link, viewer, sharedRoom, sharedMk, actions, resume, wb = null, shared = null, mirror = false, split = false, poll, handlers, live, crossTier = false, gated = false }) {
3140
3160
  if (typeof resume?.room === 'string' && resume.room !== room) resume = null
3141
- super(client, { room, mk, link, viewer, resume, wb, split, poll, handlers, ...(live !== undefined ? { live } : {}) }) // `live`: as a Space's (a vault's own handle opens no stream) // `resume`: a prior snapshot() — see Space; was dropped here for a Lane (2026-09-25)
3161
+ super(client, { room, mk, link, viewer, resume, wb, split, poll, handlers, gated, ...(live !== undefined ? { live } : {}) }) // `live`: as a Space's (a vault's own handle opens no stream) // `resume`: a prior snapshot() — see Space; was dropped here for a Lane (2026-09-25)
3142
3162
  this._sharedRoom = sharedRoom
3143
3163
  if (this._wb && sharedRoom) (this._wb._openLanes ||= new Set()).add(this)
3144
3164
  this._sharedMk = sharedMk
@@ -3252,11 +3272,14 @@ export class Lane extends Space {
3252
3272
 
3253
3273
  async linkKept(space, opts = {}) {
3254
3274
  if (!(space instanceof Space) || space._sharedRoom) throw sdkError('witbitz: linkKept needs an always-on Space', 'invalid_argument')
3275
+ // sync sweep 2026-12-04 N7: in a vault only the room id crosses — a kept Space from ANOTHER client acted on this vault's room of that id (sdkKeptAgent checked() refuses it directly)
3276
+ if (this._wb && this._wb.vault && space._wb !== this._wb) throw sdkError('witbitz: link a private lane and a kept Space from the same client', 'invalid_argument')
3255
3277
  if (this._wb && this._wb.vault) return this._wb.vault._c.roomAccount(this.room, 'keptAgent', 'link', space.room, opts)
3256
3278
  return linkKeptAgent(this, space, opts)
3257
3279
  }
3258
3280
  async unlinkKept(space, link) {
3259
3281
  if (!(space instanceof Space) || space._sharedRoom) throw sdkError('witbitz: unlinkKept needs its kept Space', 'invalid_argument')
3282
+ if (this._wb && this._wb.vault && space._wb !== this._wb) throw sdkError('witbitz: unlink a private lane and a kept Space from the same client', 'invalid_argument') // 12-04 N7, as linkKept
3260
3283
  if (this._wb && this._wb.vault) return this._wb.vault._c.roomAccount(this.room, 'keptAgent', 'unlink', space.room, link)
3261
3284
  return unlinkKeptAgent(this, space, link)
3262
3285
  }
@@ -3339,6 +3362,7 @@ export class Lane extends Space {
3339
3362
  sourceRoom: from.room,
3340
3363
  id: 'sh:' + (e.id || ('t' + e.ts)), // the entry id alone, no room prefix — stable across a fork (the app's rule)
3341
3364
  from: e.name || e.from || 'party', ...(e.self === true ? { self: true } : {}), ...(e.md === true ? { md: true } : {}),
3365
+ ...(e.gdata === true ? { gdata: true } : {}), // an answer built from Google Calendar keeps its mark in the lane, so the lane's turns stay under the floor (the app's mirrorLoop.js; sync sweep 12-04 O16)
3342
3366
  ...(typeof e.fr === 'string' ? { fr: e.fr, frRoom: from.room } : {}), // the Space's franking record + which Space: a report of the copy names the ORIGINAL (the app's mirrorLoop.js; sync sweep 11-19 P1)
3343
3367
  ...(e.self && Array.isArray(e.sources) ? { sources: e.sources.slice(0, 12) } : {}),
3344
3368
  ...mirrorBy(from.room, e), // WHO WROTE IT, as the Space verified them — Block collapses their copy in the lane too (the app's mirrorLoop.js byOf; sync sweep 11-08)
@@ -3987,7 +4011,7 @@ export class VaultSession {
3987
4011
  // the Space opened here is the lane's own: lane.close() closes it too — it was left polling (sync sweep 2026-11-03 #5)
3988
4012
  try { const lane = await this._openLane(room, { space, resume }); lane._ownsSharedSpace = true; return lane } catch (e) { space.close(); throw e }
3989
4013
  }
3990
- const sp = new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, resume, wb, lanes: it.lanes === true })
4014
+ const sp = new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, resume, wb, lanes: it.lanes === true, gated: it.gated === true }) // gated: sync sweep 2026-12-04 O24 — an incomplete settings read is no open room
3991
4015
  if (it.tier === 'enclave') wb._enc.rooms.set(room, true)
3992
4016
  if (it.detachedLane) sp._detachedLane = true
3993
4017
  return refuseSpaceInVault(sp)
@@ -3997,6 +4021,8 @@ export class VaultSession {
3997
4021
  async _openLane(room, { space, actions, resume, tier, mirror }) {
3998
4022
  const wb = this._wb
3999
4023
  if (!(space instanceof Space) || !space.room) throw sdkError('witbitz: openLane needs `space`, the shared Space the lane belongs to', 'invalid_argument')
4024
+ // sync sweep 2026-12-04 N7: a Space from ANOTHER client with the same room id bound this lane's mirror to that handle — the direct check (Witbitz.openLane)
4025
+ if (space._wb !== wb) throw sdkError('Open this private room with its recorded parent Space.', 'lane_space_mismatch')
4000
4026
  if (typeof room !== 'string' || /[:#/]/.test(room)) throw sdkError('witbitz: in a vault, openLane takes the lane\'s room id from wb.vault.rooms() — the vault opens links', 'vault_opens_links')
4001
4027
  const held = await this._c.rooms(), it = held.find((r) => r.room === room)
4002
4028
  if (!it) throw sdkError('witbitz: this vault holds no Space ' + room.slice(0, 40), 'not_in_vault')
@@ -4009,7 +4035,7 @@ export class VaultSession {
4009
4035
  // a lane of the OTHER tier (the app links one): mirrored by this device, no bridge — as outside a vault (Witbitz.openLane)
4010
4036
  const crossTier = (it.tier === 'enclave') !== ((held.find((r) => r.room === space.room) || {}).tier === 'enclave')
4011
4037
  if (it.tier === 'enclave') wb._enc.rooms.set(room, true)
4012
- return refuseSpaceInVault(new Lane(wb._client, { room, mk: null, link: null, viewer: wb._viewer, sharedRoom: space.room, sharedMk: null, actions, resume, wb, shared: space, mirror: crossTier ? (mirror || true) : mirror, crossTier }))
4038
+ return refuseSpaceInVault(new Lane(wb._client, { room, mk: null, link: null, viewer: wb._viewer, sharedRoom: space.room, sharedMk: null, actions, resume, wb, shared: space, mirror: crossTier ? (mirror || true) : mirror, crossTier, gated: it.gated === true })) // gated: 12-04 O24
4013
4039
  }
4014
4040
  /** Show the Siri Shortcut's key in the VAULT's own screen (it posts words into the person's Spaces, so it never comes
4015
4041
  * to this page). Rejects `no_key` until a Space has Siri enabled. */
@@ -4084,6 +4110,9 @@ export class VaultSession {
4084
4110
  const me = who && who.signedIn ? String(who.email || '').trim().toLowerCase() : ''
4085
4111
  if (me && admission.emails.map((e) => String(e).trim().toLowerCase()).includes(me)) admission = { ...admission, owners: [me] }
4086
4112
  }
4113
+ // sync sweep 2026-12-04 O36: an open or explicit-owner create bound no account, so a sign-in change during the model lookup
4114
+ // below made the Space in the replacement account — every create names the account it started in (the vault refuses a change)
4115
+ if (!creator) await readCreator()
4087
4116
  await wb._checkModel(model || (agent && agent.model))
4088
4117
  const gate = normAdmission(admission)
4089
4118
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
@@ -4457,6 +4486,9 @@ class SiriAccount {
4457
4486
  const stagedRemovals = new Set()
4458
4487
  for (let i = 0; i < 4; i++) {
4459
4488
  const account = await this._wb._account(), base = this._wb._siri
4489
+ // sync sweep 2026-12-04 O38: ALSO on the first attempt — a restore (another device's Siri, through the vault's keep) that landed
4490
+ // during this first account lookup was taken as this edit's starting point, and a Stop or a default change overwrote it
4491
+ if (!i && guard && guarded(base) !== began) throw sdkError('Another device changed this Siri setting first — check it and try again.', 'siri_conflict')
4460
4492
  const conflict = !!(i && guard && guarded(base) !== began) // pushed as it now stands (the Sentinel took this edit's copy), then said
4461
4493
  const next = siriStateOf(JSON.parse(JSON.stringify(base)))
4462
4494
  // A restore can carry this attempt's local retry marker along with the newer room.