@witbitz/sdk 0.0.0-stage → 4.4.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/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/agentDoorTools.js +28 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +113 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/sdkKeptAgent.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { linkOwnAgent, unlinkOwnAgent } from './ownAgentLink.js'
|
|
2
|
+
import { enableLaneIn, addPeerIn, removePeerIn, peersOf, mcpUrlOf } from './a2aCore.js'
|
|
3
|
+
import { A2A_PEERS_DOC } from './a2aShared.js'
|
|
4
|
+
import { sealDoc } from './accountSeal.js'
|
|
5
|
+
|
|
6
|
+
const fail = (code, text) => Object.assign(new Error('witbitz: ' + text), { code })
|
|
7
|
+
const ID = /^[A-Za-z0-9_-]{1,128}$/
|
|
8
|
+
const validLink = (link, lane, space) => link && link.lane === lane.room && link.space === space.room && ['connId', 'lPeer', 'sPeer'].every((k) => typeof link[k] === 'string' && ID.test(link[k]))
|
|
9
|
+
const queue = (w, fn) => { const out = (w._keptAgentRun || Promise.resolve()).catch(() => {}).then(fn); w._keptAgentRun = out.catch(() => {}); return out }
|
|
10
|
+
const DOC = 'xkept-agent-links' // private account doc: the framed page has no raw account-document API
|
|
11
|
+
const publicLink = (l) => ({ lane: l.lane, space: l.space, connId: l.connId, lPeer: l.lPeer, sPeer: l.sPeer })
|
|
12
|
+
async function readLinks(w, guard) {
|
|
13
|
+
guard()
|
|
14
|
+
if (!w.account.enabled) throw fail('not_enabled', 'enable the account before linking kept assistants')
|
|
15
|
+
const loc = await w.account._where(); guard()
|
|
16
|
+
const got = await w.account._read(loc, DOC, loc.app); guard()
|
|
17
|
+
if (!got.ok) throw fail('unreadable', 'the account’s kept-assistant links could not be read')
|
|
18
|
+
const links = (got.doc && got.doc.links) || {}
|
|
19
|
+
if (got.doc && (got.doc.v !== 1 || typeof links !== 'object' || Array.isArray(links))) throw fail('unopenable', 'the kept-assistant link document is malformed')
|
|
20
|
+
for (const [id, l] of Object.entries(links)) if (!l || id !== l.connId || !['lane', 'space', 'connId', 'lPeer', 'sPeer'].every((k) => typeof l[k] === 'string' && ID.test(l[k]))) throw fail('unopenable', 'a kept-assistant link is malformed')
|
|
21
|
+
return { loc, got, links }
|
|
22
|
+
}
|
|
23
|
+
async function saveLink(w, link, guard) {
|
|
24
|
+
for (let i = 0; i < 5; i++) {
|
|
25
|
+
const { loc, got, links } = await readLinks(w, guard)
|
|
26
|
+
const next = { v: 1, links: { ...links, [link.connId]: { ...link, at: Math.max(Date.now(), (Number(links[link.connId] && links[link.connId].at) || 0) + 1) } } }
|
|
27
|
+
const sealed = await sealDoc(loc.app, next); guard()
|
|
28
|
+
const r = await w.account._client().state(loc.room, loc.mk, DOC, sealed, 'kept assistant links', 'device', got.v); guard()
|
|
29
|
+
if (r && r.status === 409) continue
|
|
30
|
+
if (!r || r.status !== 200) throw fail('save_failed', 'the kept-assistant link could not be saved')
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
throw fail('version_conflict', 'the kept-assistant links kept changing')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Runs the app's complete link/rollback workflow where the credentials live: directly, or INSIDE the vault. */
|
|
37
|
+
function deps(w, lane, space, guard) {
|
|
38
|
+
const a = w.a2a, made = {}, held = new Map(), byRoom = new Map([[lane.room, lane], [space.room, space]])
|
|
39
|
+
const call = async (fn) => { guard(); const r = await fn(); guard(); return r }
|
|
40
|
+
const url = (room) => { const c = a._s.lanes[room]; return c ? mcpUrlOf(a.endpoint, c.handle) : null }
|
|
41
|
+
return {
|
|
42
|
+
unavailable: () => '', hosted: () => false,
|
|
43
|
+
hasLane: (room) => !!a._s.lanes[room],
|
|
44
|
+
enableLane: (room, name) => call(() => a._change((s) => enableLaneIn(s, room, { name }))),
|
|
45
|
+
addPeer: (room, name, opts) => call(async () => { const r = await a._change((s) => addPeerIn(s, room, name, opts, fail)); made[room] = r.id; return r }),
|
|
46
|
+
removePeer: (room, id) => call(async () => { if (peersOf(a._s, room).some((p) => p.id === id)) await a._change((s) => removePeerIn(s, room, id)) }),
|
|
47
|
+
push: async () => {}, // _change already pushes and commits each change only after acknowledgement
|
|
48
|
+
peersOf: (room) => peersOf(a._s, room), mcpUrl: url,
|
|
49
|
+
syncSpaceAgents: (room) => call(async () => {
|
|
50
|
+
const sp = byRoom.get(room)
|
|
51
|
+
for (let i = 0; i < 5; i++) {
|
|
52
|
+
const d = await sp._client.state(room, sp._mk, A2A_PEERS_DOC); guard()
|
|
53
|
+
if (!d || d.status !== 200 || !Number.isInteger(d.v)) throw fail('unreadable', 'the kept assistant’s peer list could not be read')
|
|
54
|
+
const peers = peersOf(a._s, room)
|
|
55
|
+
const r = await sp._client.state(room, sp._mk, A2A_PEERS_DOC, { peers }, `${peers.length} outside agents may write here`, sp._who(), d.v)
|
|
56
|
+
guard()
|
|
57
|
+
if (r && r.status === 409) continue
|
|
58
|
+
if (!r || r.status !== 200) throw fail('save_failed', 'the kept assistant’s peer list could not be saved')
|
|
59
|
+
return
|
|
60
|
+
}
|
|
61
|
+
throw fail('version_conflict', 'the kept assistant’s peer list kept changing')
|
|
62
|
+
}),
|
|
63
|
+
report: (room, peerId, target) => call(async () => { try { return await w.cloudDevice._ask('report', { room, peerId, ...(target ? { url: target.url, token: target.token, name: target.name || '' } : { off: true }) }) } catch (e) { if (target || (e.code !== 'not_enrolled' && e.code !== 'not_kept')) throw e } }), // 11·O#4: off where the device holds no such Space = done
|
|
64
|
+
connect: (spec, input) => call(async () => {
|
|
65
|
+
const conn = await w.connections.attachMcp({ url: spec.url, label: spec.label, token: input.token }); guard()
|
|
66
|
+
const link = { lane: lane.room, space: space.room, lPeer: made[lane.room], sPeer: made[space.room], connId: conn.id, pending: true }
|
|
67
|
+
try {
|
|
68
|
+
await saveLink(w, link, guard)
|
|
69
|
+
if (w._keepAgentConnection) await w._keepAgentConnection(conn, link)
|
|
70
|
+
w._keptAgentConnections = w._keptAgentConnections || new Map()
|
|
71
|
+
w._keptAgentConnections.set(conn.id, { ...conn, ownLink: link }); held.set(conn.id, conn)
|
|
72
|
+
} catch (e) { await w.connections.detach(conn.id).catch(() => {}); throw e }
|
|
73
|
+
return conn
|
|
74
|
+
}),
|
|
75
|
+
disconnect: (id) => call(() => w.connections.detach(id, { spaces: [lane] })),
|
|
76
|
+
useIn: (_room, id) => call(() => lane.connections.grant(held.get(id), { reads: 'auto' })),
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function checked(lane, space) {
|
|
81
|
+
const w = lane._wb
|
|
82
|
+
if (!w || !lane._sharedRoom || !space || space._sharedRoom || space._wb !== w || space.room === lane.room) throw fail('invalid_argument', 'link a private lane and a kept Space from the same client')
|
|
83
|
+
const session = w._session, state = w.backup._s
|
|
84
|
+
const guard = () => { if (w._session !== session || w.backup._s !== state) throw fail('account_changed', 'the account changed during assistant linking') }
|
|
85
|
+
return { w, guard }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function linkKeptAgent(lane, space, { spaceName = space && space.title, laneName = lane.title } = {}) {
|
|
89
|
+
const { w, guard } = checked(lane, space)
|
|
90
|
+
return queue(w, async () => {
|
|
91
|
+
guard()
|
|
92
|
+
if (!(await space.alwaysOn.status()).on) throw fail('not_always_on', 'keep this Space on the cloud device before linking it')
|
|
93
|
+
guard()
|
|
94
|
+
const { links } = await readLinks(w, guard)
|
|
95
|
+
const existing = Object.values(links).find((l) => l && !l.gone && l.lane === lane.room && l.space === space.room)
|
|
96
|
+
guard()
|
|
97
|
+
if (existing && !existing.pending) {
|
|
98
|
+
if (!w.a2a._s.lanes[lane.room] || !w.a2a._s.lanes[space.room]) throw fail('a2a_state_required', 'restore this account’s A2A state before reopening its kept-assistant link')
|
|
99
|
+
const cfg = await lane._gateConfig({ fresh: true }); guard()
|
|
100
|
+
if (!cfg || cfg.gated && !cfg.allow) throw fail('unreadable', 'the private assistant’s connections could not be read')
|
|
101
|
+
const connections = Array.isArray(cfg?.connections) ? cfg.connections : []
|
|
102
|
+
if (connections.some((c) => c.id === existing.connId)) return publicLink(existing)
|
|
103
|
+
}
|
|
104
|
+
if (existing) await unlinkKnown(w, lane, space, existing, guard)
|
|
105
|
+
const d = deps(w, lane, space, guard)
|
|
106
|
+
const result = await linkOwnAgent({ lane: lane.room, space: space.room, spaceName: String(spaceName || 'Kept assistant').slice(0, 80), laneName: String(laneName || 'Private assistant').slice(0, 80) }, d)
|
|
107
|
+
guard()
|
|
108
|
+
const link = { lane: lane.room, space: space.room, ...result }
|
|
109
|
+
await saveLink(w, link, guard)
|
|
110
|
+
return link
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function unlinkKeptAgent(lane, space, link) {
|
|
115
|
+
const { w, guard } = checked(lane, space)
|
|
116
|
+
if (!validLink(link, lane, space)) throw fail('invalid_argument', 'use the link returned by lane.linkKept for these rooms')
|
|
117
|
+
return queue(w, async () => {
|
|
118
|
+
guard()
|
|
119
|
+
const { links } = await readLinks(w, guard), known = links[link.connId]
|
|
120
|
+
if (!known) throw fail('not_in_account', 'that kept-assistant link is not in this account')
|
|
121
|
+
if (known.gone) return { disconnected: true }
|
|
122
|
+
if (!validLink(known, lane, space) || known.lPeer !== link.lPeer || known.sPeer !== link.sPeer) throw fail('not_in_account', 'that kept-assistant link does not belong to these rooms')
|
|
123
|
+
await unlinkKnown(w, lane, space, known, guard)
|
|
124
|
+
return { disconnected: true }
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function unlinkKnown(w, lane, space, link, guard) {
|
|
129
|
+
if (!w._agentRoom && (!w.a2a._s.lanes[lane.room] || !w.a2a._s.lanes[space.room])) throw fail('a2a_state_required', 'restore this account’s A2A state before unlinking its kept assistant')
|
|
130
|
+
const missing = [[lane.room, link.lPeer], [space.room, link.sPeer]]
|
|
131
|
+
.filter(([room, id]) => !peersOf(w.a2a._s, room).some((p) => p.id === id))
|
|
132
|
+
if (missing.length) {
|
|
133
|
+
const remote = await w.a2a.status()
|
|
134
|
+
guard()
|
|
135
|
+
if (remote?.ok !== true || !Array.isArray(remote.lanes)) throw fail('unreadable', 'the active outside-agent peers could not be checked')
|
|
136
|
+
for (const [room, id] of missing) {
|
|
137
|
+
const active = remote.lanes.find((l) => l.room === room)
|
|
138
|
+
if (active && (!Array.isArray(active.peers) || active.peers.some((p) => p.id === id))) throw fail('a2a_state_required', 'restore this account’s current A2A state before unlinking its kept assistant')
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
await unlinkOwnAgent({ lane: lane.room, space: space.room, lPeer: link.lPeer, sPeer: link.sPeer, connId: link.connId }, deps(w, lane, space, guard))
|
|
142
|
+
guard()
|
|
143
|
+
await saveLink(w, { ...publicLink(link), gone: true }, guard)
|
|
144
|
+
if (w._forgetAgentConnection) await w._forgetAgentConnection(link.connId)
|
|
145
|
+
if (w._keptAgentConnections) w._keptAgentConnections.delete(link.connId)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function keptAgentSpaceIds(w) {
|
|
149
|
+
const legacy = Object.keys(w.a2a?._s?.lanes || {})
|
|
150
|
+
.filter((room) => peersOf(w.a2a._s, room).some((p) => p.own === true))
|
|
151
|
+
if (!w.account?.enabled || typeof w.account._read !== 'function') return legacy
|
|
152
|
+
const session = w._session, state = w.backup._s
|
|
153
|
+
const guard = () => { if (w._session !== session || w.backup._s !== state) throw fail('account_changed', 'the account changed while reading kept links') }
|
|
154
|
+
const { links } = await readLinks(w, guard)
|
|
155
|
+
return [...new Set([...legacy, ...Object.values(links).filter((l) => !l.gone).map((l) => l.space)])]
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Stop every link to a Space, including links created on another device. Uses the private account doc, not page-supplied ids. */
|
|
159
|
+
export function disconnectKeptSpace(space) {
|
|
160
|
+
const w = space._wb, session = w._session, state = w.backup._s
|
|
161
|
+
const guard = () => { if (w._session !== session || w.backup._s !== state) throw fail('account_changed', 'the account changed while stopping kept assistants') }
|
|
162
|
+
return queue(w, async () => {
|
|
163
|
+
guard()
|
|
164
|
+
const { links } = w.account?.enabled ? await readLinks(w, guard) : { links: {} }
|
|
165
|
+
const errors = []
|
|
166
|
+
for (const link of Object.values(links).filter((l) => l && !l.gone && l.space === space.room)) {
|
|
167
|
+
let lane, close = false
|
|
168
|
+
try {
|
|
169
|
+
if (w._agentRoom) lane = w._agentRoom(link.lane)
|
|
170
|
+
else {
|
|
171
|
+
const rec = w.backup.rooms.find((r) => r.room === link.lane)
|
|
172
|
+
if (!rec) throw fail('not_in_account', 'the private assistant must be restored before unlinking it')
|
|
173
|
+
lane = await w.openSpace(rec.link, { live: false }); close = true
|
|
174
|
+
}
|
|
175
|
+
guard()
|
|
176
|
+
await unlinkKnown(w, lane, space, link, guard)
|
|
177
|
+
} catch (e) { errors.push(e) }
|
|
178
|
+
finally { if (lane && (close || w._agentRoom)) lane.close() }
|
|
179
|
+
}
|
|
180
|
+
if (w.a2a) {
|
|
181
|
+
const d = deps(w, space, space, guard)
|
|
182
|
+
for (const p of d.peersOf(space.room).filter((p) => p.own === true)) {
|
|
183
|
+
try { await unlinkOwnAgent({ space: space.room, sPeer: p.id }, d) } catch (e) { errors.push(e) }
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (errors.length) throw errors[0]
|
|
187
|
+
})
|
|
188
|
+
}
|
package/sdkLaneLink.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// spaces/public/sdkLaneLink.js — `lane.link(other)`: one member's two private assistants ask each other (2026-10-03,
|
|
2
|
+
// the owner: "Build the lane links"). The SDK twin of the app's linked lanes (https://witbitz.chat/docs/sdk-agents.md#lane-links; laneLink.js),
|
|
3
|
+
// on the SAME pure core (laneLinkCore.js: the frame, the hop counter, which answer goes back), so the two cannot drift.
|
|
4
|
+
//
|
|
5
|
+
// ENTIRELY ON THE DEVICE, as the design decided: the device holds both lanes' keys, so it is the only thing that can
|
|
6
|
+
// bridge them, and the server never joins two rooms. Two legs, one primitive (post into a lane + wake its assistant):
|
|
7
|
+
// • OUT — the asking assistant calls `tell_lane` (an `await` action: this device answers it within the turn). The
|
|
8
|
+
// device frames the question, posts it into the other lane and wakes that lane's assistant, then answers the tool
|
|
9
|
+
// AT ONCE: the exchange is asynchronous, never a blocking wait (Decision 2).
|
|
10
|
+
// • BACK — the device watches the lane that was asked; when its assistant answers, planForward() picks the answer and
|
|
11
|
+
// the device carries it back framed as a reply and wakes the asking assistant, which relays it to the member.
|
|
12
|
+
// The hop cap bounds BOTH legs (Decision 4): an ask continues the chain of the message that triggered it, so a loop of
|
|
13
|
+
// assistants asking each other stops at the cap. Default 3; `cap: 0` = no lane-to-lane traffic.
|
|
14
|
+
// ⚑ It runs while both lanes are OPEN on this device (the app's driver is "app-open only" too). `link.state` carries the
|
|
15
|
+
// cursors; pass it back as `resume` to pick up an exchange that was in flight when the page closed.
|
|
16
|
+
import { buildFramed, parseFramed, newCorr, askHopFrom, canForward, planForward, DEFAULT_LANE_LINK_CAP } from './laneLinkCore.js'
|
|
17
|
+
|
|
18
|
+
const GUIDANCE =
|
|
19
|
+
'You can ask the member\'s OTHER linked assistants a question with tell_lane. It is ASYNCHRONOUS: tell_lane posts ' +
|
|
20
|
+
'your question and returns immediately — the other assistant\'s answer arrives here later as a new message, and you ' +
|
|
21
|
+
'will be asked to relay it to the member then. So do NOT wait for the answer inside this turn and never invent one; ' +
|
|
22
|
+
'just send the question and tell the member you have asked. Keep the question self-contained — the other assistant ' +
|
|
23
|
+
'cannot see this conversation, only what you put in `message`.'
|
|
24
|
+
const DEFAULT_LABEL = 'linked assistant'
|
|
25
|
+
// How long a post into the other lane may take. A turn returns only AFTER its reply (the send IS the turn), so 10 s read
|
|
26
|
+
// every slower reply as "not delivered" — tell_lane told the model "busy" and a pass forwarded the same reply again (sync
|
|
27
|
+
// sweep, 2026-10-10). Now just past the server's turn budget (240 s), as the app waits for the turn's answer itself.
|
|
28
|
+
const WAKE_WAIT_MS = 280_000
|
|
29
|
+
const ASK_WAIT_MS = 6_000 // tell_lane: a refusal or a busy answer comes back at once; past this the question is in
|
|
30
|
+
|
|
31
|
+
const fail = (code, msg) => Object.assign(new Error('witbitz: ' + msg), { code })
|
|
32
|
+
const isAgent = (e) => !!(e && e.self === true)
|
|
33
|
+
|
|
34
|
+
/** The peers of `lane`, labelled the way its model sees them: [{ label, link, peer }]. Twins are suffixed ("… (2)"), and
|
|
35
|
+
* the tool's enum and its executor both read THIS list, so the name the model picks can never resolve to another lane
|
|
36
|
+
* (the app's linkedLaneChoices rule). */
|
|
37
|
+
export function peersOf(lane) {
|
|
38
|
+
const seen = new Map(), out = []
|
|
39
|
+
for (const link of (lane._laneLinks || [])) {
|
|
40
|
+
if (link._dead) continue
|
|
41
|
+
const side = link._sideOf(lane)
|
|
42
|
+
const base = side.to || DEFAULT_LABEL
|
|
43
|
+
const n = (seen.get(base) || 0) + 1
|
|
44
|
+
seen.set(base, n)
|
|
45
|
+
out.push({ label: n === 1 ? base : `${base} (${n})`, link, peer: side.other })
|
|
46
|
+
}
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The `tell_lane` def + guidance this lane's turns carry, or null when it has no live link. */
|
|
51
|
+
export function laneLinkTool(lane) {
|
|
52
|
+
const peers = peersOf(lane)
|
|
53
|
+
if (!peers.length) return null
|
|
54
|
+
return {
|
|
55
|
+
def: {
|
|
56
|
+
name: 'tell_lane',
|
|
57
|
+
mode: 'await',
|
|
58
|
+
description:
|
|
59
|
+
'Ask one of the member\'s OTHER linked assistants a question, on their behalf. `lane` is which assistant to ask; ' +
|
|
60
|
+
'`message` is the full question (the other assistant sees ONLY this — include everything it needs). ' +
|
|
61
|
+
'ASYNCHRONOUS: this returns immediately; the answer arrives later as a new message, and you relay it to the ' +
|
|
62
|
+
'member then. Never wait for it or make one up.',
|
|
63
|
+
inputSchema: { type: 'object', properties: { lane: { type: 'string', enum: peers.map((p) => p.label), description: 'Which linked assistant to ask.' }, message: { type: 'string', description: 'The complete question to ask it.' } }, required: ['lane', 'message'] },
|
|
64
|
+
},
|
|
65
|
+
guidance: GUIDANCE,
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Post a framed message into `lane` and wake its assistant ('always', whatever the lane's reply mode). True once the
|
|
70
|
+
// lane ACCEPTED it; a lane still busy past WAKE_WAIT_MS reads as not delivered, and the caller retries / reports it.
|
|
71
|
+
// `ask: true` = tell_lane's post, answered within the SERVER's device-call limit (25 s, spaceRoom.mjs): it waits ASK_WAIT_MS
|
|
72
|
+
// for a quick refusal, then counts the question as sent and lets the turn run on — the answer comes back through the
|
|
73
|
+
// link's pass, as the tool says (sync sweep, 2026-10-10: waiting for the whole reply ran past the limit).
|
|
74
|
+
async function postAndWake(lane, text, from, { ask = false } = {}) {
|
|
75
|
+
// Given up = given up (sync sweep, 2026-10-10): a pass's send still held for "busy" is not resent after the wait (the
|
|
76
|
+
// pass retries it, and a second copy would forward twice); and `from` is the LINK's label, never the member's name.
|
|
77
|
+
let timedOut = false, timer
|
|
78
|
+
try {
|
|
79
|
+
const sent = lane.send(text, { from, mode: 'always', ...(ask ? { _noHold: true } : { _aborted: () => timedOut }), _linkPost: true })
|
|
80
|
+
const r = await Promise.race([sent, new Promise((res) => { timer = setTimeout(() => { timedOut = true; res(null) }, ask ? ASK_WAIT_MS : WAKE_WAIT_MS) })])
|
|
81
|
+
if (r === null && ask) { sent.catch(() => {}); return true } // still running: the question is in, the turn is answering it
|
|
82
|
+
return !!(r && r.status === 200 && !r.busy && r.ok !== false)
|
|
83
|
+
} catch { return false } finally { clearTimeout(timer) }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class LaneLink {
|
|
87
|
+
constructor(a, b, { to, as, cap, resume } = {}) {
|
|
88
|
+
this.a = a; this.b = b
|
|
89
|
+
// `to`: what A's assistant calls B; `as`: what B's assistant calls A.
|
|
90
|
+
this._labels = { a: String(to || DEFAULT_LABEL).slice(0, 60), b: String(as || DEFAULT_LABEL).slice(0, 60) }
|
|
91
|
+
this.cap = Number.isFinite(Number(cap)) && Number(cap) >= 0 ? Math.floor(Number(cap)) : DEFAULT_LANE_LINK_CAP
|
|
92
|
+
const r = resume && typeof resume === 'object' ? resume : {}
|
|
93
|
+
// Cursor per side: how many of that lane's messages the link has already judged. null = not seen yet → set to the
|
|
94
|
+
// lane's length at first sight, so linking never forwards history (the app's no-backfill rule).
|
|
95
|
+
this._cur = { a: Number.isFinite(r.cursorA) ? r.cursorA : null, b: Number.isFinite(r.cursorB) ? r.cursorB : null }
|
|
96
|
+
this._sent = { a: Array.isArray(r.sentA) ? r.sentA.slice(-200) : [], b: Array.isArray(r.sentB) ? r.sentB.slice(-200) : [] }
|
|
97
|
+
this._dead = false
|
|
98
|
+
this._busy = false
|
|
99
|
+
this._again = false
|
|
100
|
+
this._t = null
|
|
101
|
+
this._subA = () => this._schedule()
|
|
102
|
+
this._subB = () => this._schedule()
|
|
103
|
+
a.on('message', this._subA); b.on('message', this._subB)
|
|
104
|
+
for (const l of [a, b]) {
|
|
105
|
+
l._laneLinks = [...(l._laneLinks || []), this]
|
|
106
|
+
l._reads.tell_lane = (args) => tellLane(l, args)
|
|
107
|
+
}
|
|
108
|
+
Promise.all([a.ready, b.ready].map((p) => Promise.resolve(p).catch(() => {}))).then(() => this._schedule())
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The progress to persist (JSON-safe) — hand it back as `link(other, { resume })` after a reload. */
|
|
112
|
+
get state() { return { cursorA: this._cur.a, cursorB: this._cur.b, sentA: this._sent.a.slice(), sentB: this._sent.b.slice() } }
|
|
113
|
+
|
|
114
|
+
/** End the link: neither assistant is offered the other any more. */
|
|
115
|
+
unlink() { this._stop(); if (this._onUnlink) { try { this._onUnlink() } catch { /* the account record */ } } }
|
|
116
|
+
|
|
117
|
+
// Stop on THIS device without ending the link in the account (a lane closing).
|
|
118
|
+
_stop() {
|
|
119
|
+
if (this._dead) return
|
|
120
|
+
this._dead = true
|
|
121
|
+
clearTimeout(this._t)
|
|
122
|
+
for (const [l, sub] of [[this.a, this._subA], [this.b, this._subB]]) {
|
|
123
|
+
const subs = l._subs && l._subs.message
|
|
124
|
+
if (subs) { const i = subs.indexOf(sub); if (i >= 0) subs.splice(i, 1) }
|
|
125
|
+
l._laneLinks = (l._laneLinks || []).filter((x) => x !== this)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Run one pass now (it also runs on its own whenever either lane gets a message). */
|
|
130
|
+
async run() { return this._pass() }
|
|
131
|
+
|
|
132
|
+
_sideOf(lane) { return lane === this.a ? { key: 'a', other: this.b, to: this._labels.a, as: this._labels.b } : { key: 'b', other: this.a, to: this._labels.b, as: this._labels.a } }
|
|
133
|
+
_schedule() { if (this._dead) return; clearTimeout(this._t); this._t = setTimeout(() => { this._pass().catch(() => {}) }, 120) }
|
|
134
|
+
|
|
135
|
+
// BACK LEG, both directions: for each lane, the answers its assistant gave to questions it was asked go to the asker.
|
|
136
|
+
async _pass() {
|
|
137
|
+
if (this._dead) return { forwarded: 0 }
|
|
138
|
+
if (this._busy) { this._again = true; return { forwarded: 0 } }
|
|
139
|
+
this._busy = true
|
|
140
|
+
let forwarded = 0
|
|
141
|
+
try {
|
|
142
|
+
for (const lane of [this.a, this.b]) {
|
|
143
|
+
const side = this._sideOf(lane)
|
|
144
|
+
if (lane._more || !(lane._historyRead || lane._hostDriven)) continue // the lane's 'message' events re-run the pass as its history arrives — no timer here (a history that never completes spun one every 120 ms; sync sweep, 2026-10-10) // not yet the WHOLE history (a page still to come, or one that failed — `_more` alone stops being true then; sync sweep, 2026-10-10) // still reading its pages: a cursor set (or a plan made) on part of the history would forward old asks again (sync sweep, 2026-10-10)
|
|
145
|
+
const entries = lane.messages || []
|
|
146
|
+
if (this._cur[side.key] == null) { this._cur[side.key] = entries.length; continue } // first sight: no backfill
|
|
147
|
+
const { forwards, cursor } = planForward(entries, this._cur[side.key], this._sent[side.key], this.cap, isAgent)
|
|
148
|
+
let allOk = true
|
|
149
|
+
for (const f of forwards) {
|
|
150
|
+
if (f.toRoom !== side.other.room) { this._sent[side.key].push(f.corr); continue } // asked by a lane this link does not hold
|
|
151
|
+
// The reply is labelled with how the ASKER knows this lane.
|
|
152
|
+
// Already there (state machines pass 7, L#8): a post that LANDED but whose answer was lost (a 5xx, a timeout) kept
|
|
153
|
+
// the corr out of `sent`, and another device with this link open keeps its own `sent` — both carried the same
|
|
154
|
+
// answer back again. The asking lane is the record: a framed reply with this corr in it is a forward done.
|
|
155
|
+
if ((side.other.messages || []).some((e) => { const p = parseFramed(e && e.text); return p && p.kind === 'reply' && p.corr === f.corr })) { this._sent[side.key].push(f.corr); continue }
|
|
156
|
+
const framed = buildFramed({ from: side.as, fromRoom: lane.room, corr: f.corr, hop: f.hop, cap: this.cap, kind: 'reply', body: f.text })
|
|
157
|
+
if (await postAndWake(side.other, framed, side.as)) { this._sent[side.key].push(f.corr); forwarded++ } else allOk = false
|
|
158
|
+
}
|
|
159
|
+
this._sent[side.key] = this._sent[side.key].slice(-200)
|
|
160
|
+
if (allOk) this._cur[side.key] = cursor // a failed forward holds the cursor, and `sent` keeps the rest from repeating
|
|
161
|
+
}
|
|
162
|
+
} finally {
|
|
163
|
+
this._busy = false
|
|
164
|
+
if (this._again && !this._dead) { this._again = false; this._schedule() }
|
|
165
|
+
}
|
|
166
|
+
return { forwarded }
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** OUT LEG: the `tell_lane` handler on `lane` — the device answers the turn at once with what happened. */
|
|
171
|
+
async function tellLane(lane, args) {
|
|
172
|
+
const want = String((args && args.lane) || '').trim()
|
|
173
|
+
const hit = peersOf(lane).find((p) => p.label === want)
|
|
174
|
+
if (!hit) return { ok: false, error: 'No linked assistant by that name.' }
|
|
175
|
+
const { link, peer } = hit
|
|
176
|
+
const side = link._sideOf(lane)
|
|
177
|
+
// The ask continues the chain of the message that triggered this turn (a framed peer message → hop+1, else hop 1).
|
|
178
|
+
// the LAST message decides the hop: on part of the history it is a guess that could reset the cap — the app refuses too (sync sweep, 2026-10-11)
|
|
179
|
+
if (lane._more || !(lane._historyRead || lane._hostDriven)) return { ok: false, error: 'Couldn’t read this conversation just now — try again in a moment.' }
|
|
180
|
+
const hop = askHopFrom(lane.messages || [])
|
|
181
|
+
if (!canForward(hop, link.cap)) return { ok: false, error: `This request has crossed too many lanes already (limit ${link.cap}) — answering here instead of asking on.` }
|
|
182
|
+
const corr = newCorr()
|
|
183
|
+
const framed = buildFramed({ from: side.as, fromRoom: lane.room, corr, hop, cap: link.cap, kind: 'ask', body: String((args && args.message) || '') })
|
|
184
|
+
if (link._cur[link._sideOf(peer).key] == null) {
|
|
185
|
+
// the cursor pins at the end of the peer's WHOLE history — on part of it, the pass after the ask would forward older
|
|
186
|
+
// messages as if they answered it (the app reads every page first; sync sweep 10-12)
|
|
187
|
+
if (peer._more || !(peer._historyRead || peer._hostDriven)) return { ok: false, error: `Couldn’t read ${hit.label}’s conversation just now — try again in a moment.` }
|
|
188
|
+
link._cur[link._sideOf(peer).key] = (peer.messages || []).length // the question lands after this point
|
|
189
|
+
}
|
|
190
|
+
const ok = await postAndWake(peer, framed, side.as, { ask: true })
|
|
191
|
+
return ok
|
|
192
|
+
? { ok: true, corr, message: `Sent to ${hit.label}. Its answer will arrive here shortly.` }
|
|
193
|
+
: { ok: false, error: `${hit.label} is busy right now — try again in a moment.` }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** `a.link(b, opts)` — checks, then the link. Lanes of ANY kind (the owner, 2026-10-11): this client copies the words
|
|
197
|
+
* between them itself; no room's key is handed to the other's tier. */
|
|
198
|
+
export function linkLanes(a, b, opts = {}, { tierMismatch } = {}) {
|
|
199
|
+
if (!b || typeof b.send !== 'function' || !b.room) throw fail('not_a_lane', 'link takes another Lane (from privateLane or openLane)')
|
|
200
|
+
if (b === a || b.room === a.room) throw fail('self_link', 'a lane cannot be linked to itself')
|
|
201
|
+
if ((a._laneLinks || []).some((l) => !l._dead && (l.a === b || l.b === b))) throw fail('already_linked', 'these two lanes are already linked')
|
|
202
|
+
return new LaneLink(a, b, opts)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export { parseFramed }
|
package/sdkPlan.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// sdkPlan.js — say what a change to a room requires BEFORE making it (https://witbitz.chat/docs/sdk-roadmap.md, "Later": space.plan).
|
|
2
|
+
//
|
|
3
|
+
// A Space's settings live in three places, and a builder could not tell which from the outside:
|
|
4
|
+
// · IN PLACE — the assistant's name, instructions and model, and the store's collections: `space.configure()`, for
|
|
5
|
+
// every member, the history untouched;
|
|
6
|
+
// · THE MEMBERS — a new member list (the email gate, admins, owners): since 2.3.0 IN PLACE too, `space.changeMembers()` — the
|
|
7
|
+
// same room and history, a new key for the members on the list (sdkRekey.js). Only an email-gated room, by an owner or
|
|
8
|
+
// admin; in a room with owners the owners must stay (emailFork.planGovernance). a Space no longer moves (`fork()` is retired);
|
|
9
|
+
// · CREATE-TIME — the tier, a split key, the tools the assistant may use and which run without approval: a new room
|
|
10
|
+
// (`wb.createSpace`), and the SDK carries no history into it.
|
|
11
|
+
// planChange() applies exactly those rules (the same functions configure() and fork() call) and changes nothing.
|
|
12
|
+
import { planGovernance, normAdmission, forkConfig, checkAdminCollections } from './emailFork.js'
|
|
13
|
+
|
|
14
|
+
const IN_PLACE_AGENT = ['name', 'instructions', 'model']
|
|
15
|
+
const CREATE_TIME = ['tier', 'key', 'tools', 'immediateTools']
|
|
16
|
+
const IN_PLACE_ROOM = ['platformTools', 'framing', 'dataWrites', 'safeMedia', 'lanes'] // safeMedia: Safe media on/off (sync sweep 2026-10-28) // configure()'s room settings — in place, admin-ruled (spaceService MUTABLE; sync sweep, 2026-10-10)
|
|
17
|
+
const RANK = { none: 0, in_place: 1, fork: 2, new_room: 3 }
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param change { agent?: { name?, instructions?, model? }, data?, platformTools?, framing?, dataWrites?, admission?, tier?, key?, tools?, immediateTools? }
|
|
21
|
+
* @param room { cfg (the room's sealed config, or null), me (the signed-in email, or ''), lane (bool), checkData?(data) }
|
|
22
|
+
* → { how: 'none'|'in_place'|'new_room'|'refused', history: 'kept'|'not_carried'|null, call, steps, reason? }
|
|
23
|
+
*/
|
|
24
|
+
export function planChange (change = {}, { cfg = null, me = '', lane = false, activeLane = lane, checkData = null, gatedUnread = false, signIn = 'wb.signIn' } = {}) { // signIn: the call that signs in here ('wb.vault.signIn' in a vault) // gatedUnread: a gated room answered only its stub (not signed in)
|
|
25
|
+
const steps = []
|
|
26
|
+
let members = false // the change includes a member list (in place: space.changeMembers)
|
|
27
|
+
let how = 'none', refusal = null
|
|
28
|
+
const need = (h) => { if (RANK[h] > RANK[how]) how = h }
|
|
29
|
+
const refuse = (code, reason) => { if (!refusal) refusal = { code, reason } }
|
|
30
|
+
// a private lane follows its Space's Safe media — refused as configure() refuses it (sync sweep 2026-11-02 #2), and FIRST, as
|
|
31
|
+
// configure() checks it first: after the admin/sign-in checks a lane read signed out planned sign_in_required (2026-11-03 #6)
|
|
32
|
+
if (change.lanes !== undefined && typeof change.lanes !== 'boolean') refuse('invalid_argument', 'lanes takes true or false')
|
|
33
|
+
if (lane && change.lanes !== undefined) refuse('lane', 'a private lane has no private assistants of its own')
|
|
34
|
+
if (activeLane && change.safeMedia !== undefined) refuse('lane_follows_space', 'a private lane follows its Space’s Safe media — set it on the Space')
|
|
35
|
+
|
|
36
|
+
const agent = change.agent && typeof change.agent === 'object' ? change.agent : {}
|
|
37
|
+
for (const k of Object.keys(agent)) {
|
|
38
|
+
if (IN_PLACE_AGENT.includes(k)) { need('in_place'); steps.push(`agent.${k}: changed in place for every member (a system line says so)`) }
|
|
39
|
+
else if (k === 'tools') { need('new_room'); steps.push('agent.tools: chosen at creation — a new room') }
|
|
40
|
+
else refuse('unknown_field', `agent.${k} is not a setting of the assistant`)
|
|
41
|
+
}
|
|
42
|
+
for (const k of IN_PLACE_ROOM) if (change[k] !== undefined) { need('in_place'); steps.push(`${k}: changed in place for every member`) }
|
|
43
|
+
if (change.data !== undefined) {
|
|
44
|
+
need('in_place'); steps.push('data: the store\'s collections are declared or changed in place')
|
|
45
|
+
if (typeof checkData === 'function') { try { checkData(change.data) } catch (e) { refuse(e.code || 'invalid_data', String(e.message || e)) } }
|
|
46
|
+
}
|
|
47
|
+
// THE SERVER'S IN-PLACE RULES (op 'config'; sync sweep, 2026-10-10 — the plan said "in place" for changes it refuses):
|
|
48
|
+
// an owner-governed room changes by fork; a room with admins or owners takes a change from them only; an admins-only
|
|
49
|
+
// collection needs admins or owners. Judged only when the room's config could be read.
|
|
50
|
+
// only the IN-PLACE keys: `agent.tools` alone is a new room, not a change the room's admins must make
|
|
51
|
+
if (Object.keys(agent).some((k) => IN_PLACE_AGENT.includes(k)) || change.data !== undefined || IN_PLACE_ROOM.some((k) => change[k] !== undefined)) {
|
|
52
|
+
if (gatedUnread && !cfg) refuse('sign_in_required', 'an email-gated room takes a change only from a signed-in member (' + signIn + ')')
|
|
53
|
+
else if (cfg && cfg.ownerPolicy && !(cfg.ownerPolicy.policy && cfg.ownerPolicy.policy.app === 'chat.witbitz')) refuse('governed_room', 'an owner-governed room changes by fork-and-replay') // the sealed field is ownerPolicy (it read cfg.policy, which no config carries — sync sweep 2026-11-09); a room under Witbitz's own rule changes in place, as the server allows (spaceService op config)
|
|
54
|
+
else if (cfg) {
|
|
55
|
+
const gov = [...lower(cfg.admins), ...lower(cfg.owners)], email = String(me || '').toLowerCase()
|
|
56
|
+
if (gov.length && !gov.includes(email)) refuse(email ? 'not_admin' : 'sign_in_required', email ? "only this room's admins can change the assistant" : 'a room with admins takes a change only from a signed-in admin (' + signIn + ')')
|
|
57
|
+
else if (change.data !== undefined) { try { checkAdminCollections(change.data, cfg) } catch (e) { refuse(e.code || 'admins_required', String(e.message || e).replace(/^witbitz: /, '')) } }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
for (const k of CREATE_TIME) if (change[k] !== undefined) { need('new_room'); steps.push(`${k}: chosen at creation — a new room, and the history does not come along`) }
|
|
61
|
+
|
|
62
|
+
if (change.admission !== undefined) {
|
|
63
|
+
if (lane) refuse('lane', "a lane is one member's own room — change its Space's members instead")
|
|
64
|
+
else if (gatedUnread && !cfg) { need('in_place'); refuse('sign_in_required', 'a member change needs a signed-in member (' + signIn + ')') } // a gated room read signed out: it IS gated, its gate unread
|
|
65
|
+
else if (!cfg || cfg.admission !== 'email') { need('new_room'); steps.push("admission: an open room's link IS its membership — gate a new room (createSpace({ admission })); the history does not come along") }
|
|
66
|
+
else {
|
|
67
|
+
// A gate fork() would refuse is a refusal here, never a throw (sync sweep, 2026-10-12: normAdmission throws).
|
|
68
|
+
let gate = null, bad = null
|
|
69
|
+
try { gate = normAdmission(change.admission) } catch (e) { bad = e }
|
|
70
|
+
if (bad) refuse(bad.code || 'invalid_admission', String(bad.message || bad).replace(/^witbitz: /, ''))
|
|
71
|
+
else if (!gate) refuse('invalid_admission', 'admission needs at least one address or domain')
|
|
72
|
+
else {
|
|
73
|
+
// ONLY IN PLACE (2.3.0; the owner, 2026-10-23: "only in place"): the same room and history, a new key for the members on
|
|
74
|
+
// the list (sdkRekey.js, sdk-people.md#members). A Space no longer moves, so a change that names a `history` is refused by name.
|
|
75
|
+
if (change.history !== undefined) refuse('use_change_members', 'a Space no longer moves to a new room — its members change in place, history and all (space.changeMembers)')
|
|
76
|
+
need('in_place'); members = true; steps.push('admission: changed in place — the same room and history, a new key that only the members on the list receive (space.changeMembers)')
|
|
77
|
+
const admins = lower(cfg.admins), owners = lower(cfg.owners), email = String(me || '').toLowerCase()
|
|
78
|
+
if (!email) refuse('sign_in_required', 'a member change needs a signed-in member (' + signIn + ')')
|
|
79
|
+
else if (!admins.length && !owners.length) refuse('not_admin', 'this Space has no owners or admins — only the Spaces app can change it (its creator)')
|
|
80
|
+
else if ((admins.length || owners.length) && !admins.includes(email) && !owners.includes(email)) refuse('not_admin', "only this room's owners and admins change its members")
|
|
81
|
+
else {
|
|
82
|
+
// the same two checks space.fork() makes, in its order: governance, then an admins-only collection the
|
|
83
|
+
// new room would keep with no admin or owner (emailFork.checkAdminCollections; sync sweep, 2026-10-10)
|
|
84
|
+
try { planGovernance(cfg, gate, email, change.admission.admins !== undefined); const next = forkConfig(cfg, gate, ''); checkAdminCollections(next.dataSchema, next) } catch (e) { refuse(e.code || 'refused', String(e.message || e).replace(/^witbitz: /, '')) } }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (refusal) return { how: 'refused', history: null, call: null, steps, reason: refusal.reason, code: refusal.code }
|
|
90
|
+
const history = how === 'new_room' ? 'not_carried' : how === 'in_place' ? 'kept' : null
|
|
91
|
+
const configures = steps.some((x) => !/^admission:/.test(x))
|
|
92
|
+
const call = how === 'in_place' ? (members ? (configures ? 'space.configure(…) and space.changeMembers(admission)' : 'space.changeMembers(admission)') : 'space.configure(…)') : how === 'new_room' ? 'wb.createSpace(…)' : null
|
|
93
|
+
return { how, history, call, steps }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const lower = (g) => (g && Array.isArray(g.emails) ? g.emails.map((x) => String(x).toLowerCase()) : [])
|