@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/idbSeal.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// idbSeal.js — DEVICE STORAGE PROTECTION for the page's IndexedDB CONTENT (docs/device-storage-protection.md, slice 3):
|
|
2
|
+
// the chat cache (`chat:<room>`: every message this device has shown), widget state (`wstate:<room>:<widget>`: itineraries,
|
|
3
|
+
// lists, places), cached attachments (`blob:<room>:<ref>`) and the Code section's offline transcripts (`code:…`). With the
|
|
4
|
+
// switch on they are ciphertext at rest under the device key, like the keys in slice 1 and the secrets in slice 2.
|
|
5
|
+
//
|
|
6
|
+
// Pure decisions, no storage of its own: idb.js asks `wrapForStore` before a put and `unwrapFromStore` after a get, so no
|
|
7
|
+
// cache module changes. States: INACTIVE (switch off, or a framed app that does not own the lock) → pass-through;
|
|
8
|
+
// ACTIVE + key (unlocked) → seal on write, open on read; ACTIVE, no key (locked) → a protected key reads as ABSENT (no
|
|
9
|
+
// cache → the room loads from the network after the unlock) and a write is DROPPED (never a clear write over a protected
|
|
10
|
+
// store; the cache refills on the next save). `zoom:` (a call's meeting link, its passcode included) is sealed since
|
|
11
|
+
// 2026-10-10 — a call tap on a protected device opens the app, not the meeting. Keys the service worker needs while locked (the
|
|
12
|
+
// notification mirror, the push prefetch — which holds the server's sealed boxes, unreadable without the room key anyway)
|
|
13
|
+
// are not protected, on purpose.
|
|
14
|
+
import { sealIf, openIf, isSealed, importRaw, seal, open } from './deviceSeal.js'
|
|
15
|
+
import { makeNamer, isOpaqueName } from './sealedNames.js'
|
|
16
|
+
|
|
17
|
+
// §NAMES (docs/desktop-protection.md, phase 2): on a protected device EVERY key in this store is kept under an opaque name
|
|
18
|
+
// (sealedNames.js) with its value sealed — `chat:<room>`, the worker's `mk:<room>`, `cnt:`, `viewing`, all of it — so a disk
|
|
19
|
+
// copy lists no room. The page (here) and the key worker (l1-worker.js §PROTECT) each set it from the device key; without
|
|
20
|
+
// the key (locked, memory-only) idb.js answers absent and drops writes. Only the names the SERVICE WORKERS share with the
|
|
21
|
+
// page keep their real name, since they hold no key: the tap record, the preview setting, the protection flag, the worker
|
|
22
|
+
// trail, the Code reminder key (codeRemind.js: at rest only while previews are opted in) — and `nk:` while previews are opted in.
|
|
23
|
+
// `devkey:v1` (devices.js) keeps its name and is never sealed either: it holds a NON-EXTRACTABLE CryptoKey, which no page
|
|
24
|
+
// or disk copy can turn into bytes, so sealing protects nothing — and sealing is JSON, which turned the key into `{}` (every
|
|
25
|
+
// protected device lost its device key at switch-on; account recovery v2's staging test, 2026-11-14).
|
|
26
|
+
export const IDB_SHARED_NAMES = Object.freeze(['notifTap', 'notifPreview', 'protectedNames', 'swTrail', 'codeRemindKey', 'devkey:v1', 'blocks:sw', 'chatlocked:sw'])
|
|
27
|
+
const naming = { on: false, key: null, namer: null }
|
|
28
|
+
/** { on, key (CryptoKey for values), namer (sealedNames.makeNamer) } — on without a namer = locked. */
|
|
29
|
+
export function setIdbNaming ({ on = false, key = null, namer = null } = {}) { naming.on = !!on; naming.key = key; naming.namer = namer }
|
|
30
|
+
export const idbNamingState = () => naming
|
|
31
|
+
/** Key worker: the device key's raw bytes → this realm's naming (null = locked; off = unprotected). */
|
|
32
|
+
export async function armIdbNaming (rawKey) { setIdbNaming({ on: true, key: await importRaw(rawKey), namer: await makeNamer(rawKey) }) }
|
|
33
|
+
|
|
34
|
+
export const IDB_PROTECTED_PREFIXES = Object.freeze(['chat:', 'wstate:', 'blob:', 'code:', 'vchat:', 'vblob:', 'vblobidx', 'hidx:', 'zoom:', 'mailpend:']) // vchat: = the vault's durable seed of the framed app's chat (slice 4); hidx: = Help search's full-history copy (helpIndex.js); mailpend: = a mail's attachment parts waiting for their mail (mailShare.js)
|
|
35
|
+
export const isProtectedIdbKey = (k) => { const s = String(k); return IDB_PROTECTED_PREFIXES.some((p) => s.startsWith(p)) }
|
|
36
|
+
|
|
37
|
+
const st = { active: false, key: null }
|
|
38
|
+
/** The lock hooks drive this: { active, key } — key is a CryptoKey from deviceSeal.importRaw, or null while locked. */
|
|
39
|
+
export function setIdbProtection ({ active = st.active, key = st.key } = {}) { st.active = !!active; st.key = key || null; if (!st.active) setIdbNaming({ on: false }); else if (!st.key) setIdbNaming({ on: true }) } // locked: names on, no namer
|
|
40
|
+
export const idbProtection = () => ({ active: st.active, unlocked: !!st.key })
|
|
41
|
+
|
|
42
|
+
/** What to put under `k` for value `v`: the value (inactive or not a protected key), a sealed blob (unlocked), or
|
|
43
|
+
* `undefined` = DROP the write (locked: never a clear write over a protected store). */
|
|
44
|
+
export async function wrapForStore (k, v) {
|
|
45
|
+
if (!st.active || !isProtectedIdbKey(k)) return v
|
|
46
|
+
if (!st.key) return undefined
|
|
47
|
+
return sealIf(st.key, v)
|
|
48
|
+
}
|
|
49
|
+
/** What a get returns for stored `v`: the value, the opened value, or null for a sealed value with no key (locked) or
|
|
50
|
+
* a key that cannot open it (never a throw up into a cache reader — it treats null as "no cache"). */
|
|
51
|
+
export async function unwrapFromStore (k, v) {
|
|
52
|
+
if (!isProtectedIdbKey(k) || !isSealed(v)) return v // the worker's own sealed `mk:`/`us:`/`nk:` entries pass through untouched — it parks and opens them itself
|
|
53
|
+
if (!st.key) return null
|
|
54
|
+
try { return await openIf(st.key, v) } catch { return null }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The protected keys under every prefix, WITHOUT their values (keysRaw where the store has it; else the keys of entriesRaw). */
|
|
58
|
+
const protectedKeys = async (idb) => { const out = []; for (const pfx of IDB_PROTECTED_PREFIXES) { if (typeof idb.keysRaw === 'function') out.push(...await idb.keysRaw(pfx)); else for (const [k] of await idb.entriesRaw(pfx)) out.push(k) } return out }
|
|
59
|
+
|
|
60
|
+
/** UNLOCK: hold the key, no scan. A clear legacy entry still reads (unwrapFromStore passes it through) and is sealed by its
|
|
61
|
+
* next write; the full migration runs ONCE, at switch-on. Scanning the whole content store on every unlock loaded every
|
|
62
|
+
* cached room into memory at once and killed the page on an iPhone ("A problem repeatedly occurred", 2026-10-06). */
|
|
63
|
+
export async function armIdbProtection (rawKey) { const key = await importRaw(rawKey); setIdbProtection({ active: true, key }); setIdbNaming({ on: true, key, namer: await makeNamer(rawKey) }) }
|
|
64
|
+
/** §NAMES: move every entry still under its real name under its opaque name, ONE at a time (keys first — never the whole
|
|
65
|
+
* store in memory). Phase-1 content sealed in place is opened first; the key worker's own sealed keys move as they are.
|
|
66
|
+
* An entry already present under its opaque name (written since) wins — the old one is only deleted. Cheap once done. */
|
|
67
|
+
export async function moveToOpaqueNames (idb) {
|
|
68
|
+
const { key, namer } = naming; if (!key || !namer) return 0
|
|
69
|
+
try { await idb.setRaw('protectedNames', true) } catch { /* the service workers' cue: no prefetch on this device */ }
|
|
70
|
+
let n = 0
|
|
71
|
+
for (const k of await idb.keysRaw('')) {
|
|
72
|
+
if (isOpaqueName(k) || IDB_SHARED_NAMES.includes(k) || k.startsWith('nk:')) continue
|
|
73
|
+
let v = await idb.getRaw(k); if (v === undefined || v === null) continue
|
|
74
|
+
if (isProtectedIdbKey(k) && isSealed(v)) { try { v = await openIf(st.key || key, v) } catch { continue } }
|
|
75
|
+
const o = await namer.opaque(k)
|
|
76
|
+
if ((await idb.getRaw(o)) == null) await idb.setRaw(o, await seal(key, v))
|
|
77
|
+
await idb.delRaw(k); n++
|
|
78
|
+
}
|
|
79
|
+
return n
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Switch on: seal every clear protected entry in place (migration) — ONE entry at a time, keys first, never the whole store. */
|
|
83
|
+
export async function migrateIdbProtection (idb, rawKey) {
|
|
84
|
+
await armIdbProtection(rawKey)
|
|
85
|
+
return moveToOpaqueNames(idb)
|
|
86
|
+
}
|
|
87
|
+
/** Switch off: open every sealed protected entry and write it back in the clear, one at a time; then pass-through. */
|
|
88
|
+
export async function unprotectIdb (idb, rawKey) {
|
|
89
|
+
const key = await importRaw(rawKey), namer = await makeNamer(rawKey)
|
|
90
|
+
for (const o of await idb.keysRaw('p:')) { const name = await namer.real(o); const v = await idb.getRaw(o); if (name != null && v != null) { try { await idb.setRaw(name, await open(key, v)) } catch { /* junk */ } } await idb.delRaw(o) } // back under real names (the key worker opens its own keys after)
|
|
91
|
+
for (const k of await protectedKeys(idb)) { const v = await idb.getRaw(k); if (isSealed(v)) { try { await idb.setRaw(k, await openIf(key, v)) } catch { await idb.delRaw(k) } } } // an entry the key cannot open is junk: drop it
|
|
92
|
+
try { await idb.delRaw('protectedNames') } catch { /* */ }
|
|
93
|
+
setIdbProtection({ active: false, key: null })
|
|
94
|
+
}
|
|
95
|
+
/** A FRAMED app whose framer no longer protects the device: the sealed content cannot be opened — drop it (it is a cache)
|
|
96
|
+
* and pass through. */
|
|
97
|
+
export async function dropSealedIdb (idb) {
|
|
98
|
+
for (const k of await protectedKeys(idb)) { const v = await idb.getRaw(k); if (isSealed(v)) { try { await idb.delRaw(k) } catch { /* */ } } }
|
|
99
|
+
for (const o of await idb.keysRaw('p:')) { try { await idb.delRaw(o) } catch { /* */ } }
|
|
100
|
+
try { await idb.delRaw('protectedNames') } catch { /* */ }
|
|
101
|
+
setIdbProtection({ active: false, key: null })
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// SELF-INIT from the lock's stored config, like protectedLocal.js: a protected standalone app starts ACTIVE and LOCKED
|
|
105
|
+
// (reads answer null) until the unlock supplies the key. A worker realm has no window: inactive there (the worker seals
|
|
106
|
+
// its own store itself, l1-worker.js §PROTECT).
|
|
107
|
+
try {
|
|
108
|
+
if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
|
|
109
|
+
const rawGet0 = (k) => { try { return typeof Storage !== 'undefined' ? Storage.prototype.getItem.call(localStorage, k) : localStorage.getItem(k) } catch { return null } }
|
|
110
|
+
const cfgOn = (k) => { try { const c = JSON.parse(rawGet0(k) || 'null'); return !!(c && c.on && c.protect && c.protect.on) } catch { return false } }
|
|
111
|
+
// a TOP-LEVEL page reads its own lock config (the standalone app's, or the vault's); a FRAMED app reads the marker its
|
|
112
|
+
// framing vault left (protectedLocal.js FRAMED_MARK) — the key arrives from the vault after boot
|
|
113
|
+
// a same-origin frame of the app (the Code section, codeView.js) shares its localStorage AND its idb: read the app's own
|
|
114
|
+
// lock config there too — its parent hands the key down ({ch:'codeProtect'}); a cross-origin frame reads the marker
|
|
115
|
+
let sameOriginFramed = false; try { sameOriginFramed = window.top !== window && window.parent.location.origin === location.origin } catch { sameOriginFramed = false }
|
|
116
|
+
const on = (window.top === window || sameOriginFramed) ? (cfgOn('space:lock') || cfgOn('vault:lock') || rawGet0('space:protected') === '1' || (window.top === window && rawGet0('vault:atrest') === '1') || rawGet0('space:atrest') === '1') : rawGet0('space:protected') === '1'
|
|
117
|
+
if (on) setIdbProtection({ active: true, key: null })
|
|
118
|
+
}
|
|
119
|
+
} catch { /* no storage here */ }
|
package/indexGone.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// indexGone.js — ONE RULE for "this account was deleted while the device was offline" (the app: devices.js indexGoneVerdict; the SDK:
|
|
2
|
+
// sdkAccount.js — sync sweep 2026-11-18 #11: the SDK read any non-200 as "unreadable" for ever). The account's index answers 410
|
|
3
|
+
// once Delete my account deleted it (only that deletes an account index). Believed only when seen twice at least a minute apart —
|
|
4
|
+
// one odd answer never wipes a device — and a good read clears the note. Pure: the caller keeps `first`.
|
|
5
|
+
export const INDEX_GONE_AFTER_MS = 60_000
|
|
6
|
+
/** → { first, erased }: `first` is what to keep (0 = clear it); `erased` = sign this device out as erased now. */
|
|
7
|
+
export function indexGoneStep (first, status, now = Date.now()) {
|
|
8
|
+
if (status !== 410) return { first: status === 200 ? 0 : (Number(first) || 0), erased: false }
|
|
9
|
+
const f = Number(first) || 0
|
|
10
|
+
if (!f) return { first: now, erased: false }
|
|
11
|
+
return { first: f, erased: now - f >= INDEX_GONE_AFTER_MS }
|
|
12
|
+
}
|
package/invite.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// 2-of-2 async handshake — seal one share under the couple's shared CODE (docs: the async code-sealed exchange).
|
|
2
|
+
// The creator seals shareA under a key derived from a short code (PBKDF2) and registers the ciphertext ("invite") with
|
|
3
|
+
// the room. The partner, holding their OWN share-link + the code (both out of band), fetches the invite, unseals shareA,
|
|
4
|
+
// and combines → mk. Neither factor alone opens the room: a leaked link is one bare share; the code alone unseals only
|
|
5
|
+
// shareA (still needs the other share). The server only ever holds ciphertext under a code it doesn't have.
|
|
6
|
+
const enc = new TextEncoder()
|
|
7
|
+
const dec = new TextDecoder()
|
|
8
|
+
|
|
9
|
+
// A short, human-shareable code — 4 groups so it reads like "7K2P-9QF3-…". Ambiguous chars dropped.
|
|
10
|
+
export function newCode() {
|
|
11
|
+
const A = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' // no I/O/0/1
|
|
12
|
+
const r = crypto.getRandomValues(new Uint8Array(12))
|
|
13
|
+
const s = [].slice.call(r).map((x) => A[x % A.length]).join('')
|
|
14
|
+
return s.slice(0, 4) + '-' + s.slice(4, 8) + '-' + s.slice(8, 12)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const normCode = (code) => String(code || '').toUpperCase().replace(/[^A-Z0-9]/g, '') // forgiving: case + dashes/spaces
|
|
18
|
+
|
|
19
|
+
async function keyFromCode(code, salt) {
|
|
20
|
+
const base = await crypto.subtle.importKey('raw', enc.encode(normCode(code)), 'PBKDF2', false, ['deriveKey'])
|
|
21
|
+
return crypto.subtle.deriveKey(
|
|
22
|
+
{ name: 'PBKDF2', salt, iterations: 210000, hash: 'SHA-256' }, // slow: the code is low-entropy, so make guessing costly
|
|
23
|
+
base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'],
|
|
24
|
+
)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const b64 = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
28
|
+
const ub64 = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const a = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) a[i] = b.charCodeAt(i); return a }
|
|
29
|
+
|
|
30
|
+
/** Seal a short string under the code → an opaque base64 blob ( salt16 ‖ iv12 ‖ ciphertext ). */
|
|
31
|
+
export async function sealUnderCode(plaintext, code) {
|
|
32
|
+
const salt = crypto.getRandomValues(new Uint8Array(16))
|
|
33
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
34
|
+
const key = await keyFromCode(code, salt)
|
|
35
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, enc.encode(String(plaintext))))
|
|
36
|
+
const out = new Uint8Array(16 + 12 + ct.length)
|
|
37
|
+
out.set(salt); out.set(iv, 16); out.set(ct, 28)
|
|
38
|
+
return b64(out)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Open a code-sealed blob → the string, or null on a wrong code / tamper (never throws). */
|
|
42
|
+
export async function openUnderCode(blob, code) {
|
|
43
|
+
try {
|
|
44
|
+
const raw = ub64(blob)
|
|
45
|
+
const key = await keyFromCode(code, raw.slice(0, 16))
|
|
46
|
+
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: raw.slice(16, 28) }, key, raw.slice(28))
|
|
47
|
+
return dec.decode(pt)
|
|
48
|
+
} catch {
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
}
|
package/inviteEnroll.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Tier-2 email-invite ENROLL (docs/spaces-email-invite.md). Runs once after email sign-in: mint (or reuse) a per-user
|
|
2
|
+
// invite identity — an ECDH "box" keypair + a random inbox id — derive THIS user's directory handle via the BLINDED
|
|
3
|
+
// OPRF (the email never leaves the device), and publish { boxPub, inbox } to the directory, authenticated by the login
|
|
4
|
+
// idToken (the server checks OPRF(email)==handle, so a slot can't be squatted). The box PRIVATE key is what opens
|
|
5
|
+
// invites sent to you; it is persisted AND backed up, so every device of yours shares ONE invite identity (restored via
|
|
6
|
+
// the recovery vault → an invite sealed to your boxPub opens on any of them, and they all poll the same inbox).
|
|
7
|
+
import { blind, finalize } from './oprf.js'
|
|
8
|
+
|
|
9
|
+
const b64u = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
10
|
+
const randInbox = () => b64u(crypto.getRandomValues(new Uint8Array(18))) // 24-char base64url mailbox id (high-entropy)
|
|
11
|
+
|
|
12
|
+
// Resolve an email → its directory handle via the blinded OPRF round-trip. The email is blinded locally; the server
|
|
13
|
+
// only ever sees a uniform random point. Throws on a bad DLEQ or an unavailable service (caller treats as "can't
|
|
14
|
+
// resolve" — never fall back to an unverified handle).
|
|
15
|
+
// A tenant/app SCOPE (per-tenant account isolation). Default '' = the GLOBAL directory (standalone regular Spaces —
|
|
16
|
+
// byte-identical). A tenant vault/app sets a STABLE, origin-INDEPENDENT scope, so the SAME email is a DIFFERENT account
|
|
17
|
+
// per app: the handle derives from (scope · email), never colliding with — or resolving — the global one. The scope
|
|
18
|
+
// must be applied to BOTH blind() and finalize() (the DLEQ verify re-hashes the same input), so they stay consistent.
|
|
19
|
+
let _dirScope = ''
|
|
20
|
+
// `spaces` and `spaces.<kind>` are slot NAMES with their own writers (the regular app's slot, attestedBox.js boxApp) — never a
|
|
21
|
+
// scope: the username slot is written under the scope's name, so a link's `?dirscope=spaces.emulated` would put the regular
|
|
22
|
+
// invite box into the attested slot (sync sweep 2026-10-20 #3).
|
|
23
|
+
export const reservedScope = (s) => /^spaces(\.|$)/.test(String(s || ''))
|
|
24
|
+
export function setDirScope(scope) { _dirScope = reservedScope(scope) ? '' : String(scope || '') }
|
|
25
|
+
export const getDirScope = () => _dirScope // the same namespace for the email-discovery switch (usernameSettings.js)
|
|
26
|
+
|
|
27
|
+
export async function resolveHandle(email, client, scope = _dirScope) {
|
|
28
|
+
const e = scope ? scope + '\x1f' + email : email
|
|
29
|
+
const { b, r } = blind(e)
|
|
30
|
+
const ev = await client.oprf(b)
|
|
31
|
+
if (!ev || ev.status !== 200 || !ev.z || !ev.proof || !ev.kpub) throw new Error('oprf_unavailable')
|
|
32
|
+
return finalize(e, ev.z, r, ev.proof, ev.kpub) // verifies the DLEQ, unblinds, hashes → the handle
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// THE USERNAME DOOR OF A SCOPED APP (the owner, 2026-10-19: an invite sent in the hosted app by @username landed in the
|
|
36
|
+
// invitee's REGULAR app). A username names the GLOBAL handle, and a scoped app's own slot lives under its scoped one, so
|
|
37
|
+
// the lookup could only answer the regular app's inbox. A scoped app therefore ALSO keeps its slot under the global handle,
|
|
38
|
+
// named after its scope (agent/spaceHandler.mjs dirSlot — one row, one slot per app), and asks for that slot by name
|
|
39
|
+
// (inviteSend.js). The same "find me by email" switch covers it. Only first-party apps can write under the global handle
|
|
40
|
+
// (the server refuses a sign-in made on another website). → { ok } | { skip } | { ok:false, reason }.
|
|
41
|
+
export const usernameSlotApp = () => _dirScope || null
|
|
42
|
+
export async function enrollUsernameSlot({ email, idToken, client, id }) {
|
|
43
|
+
if (!_dirScope) return { skip: true }
|
|
44
|
+
if (!email || !idToken || !client || !id || !id.boxPub || !id.inbox) return { ok: false, reason: 'bad_args' }
|
|
45
|
+
const handle = await resolveHandle(email, client, '') // the GLOBAL handle — what a username names
|
|
46
|
+
const r = await client.dirPut(handle, { boxPub: id.boxPub, inbox: id.inbox }, idToken, '', _dirScope)
|
|
47
|
+
return r && r.status === 200 ? { ok: true } : { ok: false, reason: 'dir_put_failed:' + (r ? r.status : 'net') }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Publish (or refresh) this user's invite slot. Idempotent by design: REUSES an existing invite identity when present
|
|
51
|
+
// (so all your devices — and a restored one — share one boxPub/inbox), otherwise mints a fresh keypair. `load`/`save`
|
|
52
|
+
// persist the identity; `save` is also where the caller queues a backup so boxPriv survives device loss.
|
|
53
|
+
// `scope`: the directory namespace (default: the one this page set) — the SDK passes its app's own, 'app:<origin>'.
|
|
54
|
+
export async function enroll({ email, idToken, client, genRecipientKey, load, save, scope = _dirScope }) {
|
|
55
|
+
if (!email || !idToken || !client || !genRecipientKey) return null
|
|
56
|
+
let id = (load && load()) || null
|
|
57
|
+
if (!id || !id.boxPub || !id.boxPriv || !id.inbox) {
|
|
58
|
+
const kp = await genRecipientKey() // { publicJwk, privateJwk } — ECDH P-256 (e2ee.js)
|
|
59
|
+
id = { boxPub: kp.publicJwk, boxPriv: kp.privateJwk, inbox: randInbox() }
|
|
60
|
+
}
|
|
61
|
+
const handle = await resolveHandle(email, client, scope)
|
|
62
|
+
const r = await client.dirPut(handle, { boxPub: id.boxPub, inbox: id.inbox }, idToken, scope) // send the scope so the server re-derives OPRF(scope·email)==handle (a scoped account's put would otherwise 403 handle_mismatch)
|
|
63
|
+
if (!r || r.status !== 200) throw new Error('dir_put_failed:' + (r ? r.status : 'net'))
|
|
64
|
+
const next = { ...id, handle }
|
|
65
|
+
if (save) save(next)
|
|
66
|
+
return next
|
|
67
|
+
}
|
package/inviteSend.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Tier-2 invite — SEND (docs/spaces-email-invite.md; by username: docs/spaces-usernames.md §5). Resolve the invitee's
|
|
2
|
+
// ADDRESS — an email (via the blinded OPRF, so the email never leaves the device) or a public "@username" (via the
|
|
3
|
+
// registry, which answers the account's handle) — to the SAME directory slot, wrap THIS room's key to the recipient's
|
|
4
|
+
// boxPub (an anonymous sealed box), and drop it in their inbox. The server only ever sees a blinded lookup or a public
|
|
5
|
+
// name, and an anonymous ciphertext landing in some inbox — never the email, the room, or the key.
|
|
6
|
+
import { resolveHandle, usernameSlotApp } from './inviteEnroll.js' // ⛔ THIS address: the vault sets the hosted app's directory scope on it (setDirScope); its build leaves a plain './inviteEnroll.js' plain = a second, unscoped copy, and every invitee was looked up in the regular app's directory (2026-11-17; vaultModuleOneAddress.test.mjs)
|
|
7
|
+
import { validUsername } from './address.js'
|
|
8
|
+
import { sealTo } from './e2ee.js'
|
|
9
|
+
|
|
10
|
+
/** The invitee's directory handle for `{ email } | { username }`. Returns `{ handle }` or `{ reason }`:
|
|
11
|
+
* `no_user` = no such username (distinct from an enrolled-or-not email — a name is either claimed or it is not).
|
|
12
|
+
* Throws only if the OPRF/DLEQ round-trip fails. */
|
|
13
|
+
export async function resolveInvitee({ email, username, app, scope }, client) {
|
|
14
|
+
if (username !== undefined && username !== null && username !== '') {
|
|
15
|
+
const u = validUsername(username)
|
|
16
|
+
if (!u) return { reason: 'bad_args' }
|
|
17
|
+
// the slot of THIS app: an attested kind's box, else — in a scoped app (the hosted app) — its own slot under the global
|
|
18
|
+
// handle (inviteEnroll.js enrollUsernameSlot), never the regular app's default one
|
|
19
|
+
const slot = app || (scope === undefined ? usernameSlotApp() : scope) || undefined
|
|
20
|
+
const r = await client.userResolve(u, slot)
|
|
21
|
+
if (!r || r.status === 404) return { reason: 'no_user' }
|
|
22
|
+
if (r.status !== 200) return { reason: 'resolve_failed:' + (r ? r.status : 'net') }
|
|
23
|
+
const entry = r.entry && r.entry.boxPub && r.entry.inbox ? r.entry : null
|
|
24
|
+
if (!entry && slot) return { reason: 'not_enrolled' } // no slot for this app: they have not opened it — never another app's inbox
|
|
25
|
+
const handle = typeof r.handle === 'string' && r.handle ? r.handle : null // §12: absent for a member who closed the email door
|
|
26
|
+
if (!entry && !handle) return { reason: 'not_enrolled' }
|
|
27
|
+
return { ...(handle ? { handle } : {}), ...(entry ? { entry } : {}) } // the resolve carries the invite slot itself (docs/spaces-usernames.md §10)
|
|
28
|
+
}
|
|
29
|
+
if (!email) return { reason: 'bad_args' }
|
|
30
|
+
return { handle: await (scope === undefined ? resolveHandle(email, client) : resolveHandle(email, client, scope)) } // blinded — the email never leaves the device
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The invitee's invite slot — the lookup alone, nothing sent. → { ok: true, entry } | { ok: false, reason }: `not_enrolled` (never
|
|
34
|
+
* signed in to Spaces — no slot), `no_user` (no such username), `no_entry` / `resolve_failed:…` (could not tell). New Space uses it
|
|
35
|
+
* to refuse people who are not on Spaces (the owner, 2026-11-21: "You cannot create a room for a person that is not registered"). */
|
|
36
|
+
export async function findInvitee({ email, username, app, scope }, client) {
|
|
37
|
+
if ((!email && !username) || !client) return { ok: false, reason: 'bad_args' }
|
|
38
|
+
const who = await resolveInvitee({ email, username, app, scope }, client)
|
|
39
|
+
if (!who.handle && !who.entry) return { ok: false, reason: who.reason }
|
|
40
|
+
// By @username the slot came with the resolve — the EMAIL lookup is never asked, so a member who closed that door is
|
|
41
|
+
// still reachable by the name they chose to be public. By email: the lookup, which answers 404 for a closed door too.
|
|
42
|
+
const g = who.entry ? { status: 200, entry: who.entry } : await client.dirGet(who.handle, app ? { app } : undefined)
|
|
43
|
+
if (!g || g.status === 404) return { ok: false, reason: 'not_enrolled' }
|
|
44
|
+
if (g.status !== 200 || !g.entry || !g.entry.boxPub || !g.entry.inbox) return { ok: false, reason: 'no_entry' }
|
|
45
|
+
return { ok: true, entry: g.entry }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Returns { ok:true } or { ok:false, reason }. `not_enrolled` = the recipient has never opened Spaces, so there is no
|
|
49
|
+
// slot to seal to (the UI should say "ask them to open Spaces once"); `no_user` = that username does not exist.
|
|
50
|
+
export async function sendInvite({ email, username, room, mk, title, from, gate, link, client, direct, app, scope, kind, us = null, spc = '' }) { // app/kind: an ATTESTED room's invite goes to the invitee's box for that kind (attestedBox.js), never with a link
|
|
51
|
+
// A SPLIT room has NO mk to deliver — the self-contained `link` carries the userShare (#us=) instead, so accept when
|
|
52
|
+
// EITHER an mk or a link is present. (`mk` is still delivered for a plain room, and as a v1 fallback field below.)
|
|
53
|
+
// AN ATTESTED SPLIT ROOM (the hosted app's — 2026-11-24, every attested invite there failed bad_args): no mk and no link, the user
|
|
54
|
+
// share and its commitment instead — only into an attested kind's box (an ordinary split room's invite is its link)
|
|
55
|
+
if (us && !kind) return { ok: false, reason: 'bad_args' }
|
|
56
|
+
if ((!email && !username) || !room || (!mk && !link && !us) || !client) return { ok: false, reason: 'bad_args' }
|
|
57
|
+
const f = await findInvitee({ email, username, app, scope }, client)
|
|
58
|
+
if (!f.ok) return f
|
|
59
|
+
const g = { entry: f.entry }
|
|
60
|
+
// Seal the self-contained LINK (room+mk+gate+lanes in ONE grammar) as the source of truth the recipient reverse-parses,
|
|
61
|
+
// so no field is ever hand-dropped again (that was the "synced, can't open" bug — the gate marker went missing). room/mk
|
|
62
|
+
// /gate are ALSO carried for now so a not-yet-updated recipient (a v1 reader) still works during rollout.
|
|
63
|
+
const box = await sealTo(JSON.stringify({ v: 2, ...(link ? { link } : {}), room, ...(mk ? { mk } : {}), ...(us ? { us: String(us), ...(spc ? { spc: String(spc) } : {}) } : {}), ...(gate ? { gate } : {}), title: title || '', from: from || '', ...(kind ? { kind } : {}), ...(direct ? { direct: String(direct).slice(0, 254) } : {}), at: Date.now() }), g.entry.boxPub)
|
|
64
|
+
const r = await client.drop(g.entry.inbox, box)
|
|
65
|
+
if (r && r.status === 200) return { ok: true }
|
|
66
|
+
if (r && r.status === 507) return { ok: false, reason: 'inbox_full' }
|
|
67
|
+
return { ok: false, reason: 'drop_failed:' + (r ? r.status : 'net') }
|
|
68
|
+
}
|
package/jobAgents.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// jobAgents.js — AGENTS THAT TAKE JOBS, as data (the owner, 2026-10-21: "Can we make it general so adding another agent this
|
|
2
|
+
// way is just a ui change" → "Let's do Claude code and leave codex out"; docs/job-agents.md). An agent of this kind:
|
|
3
|
+
// • is started by ONE https address you POST a job to, with a key the Sentinel keeps (a bearer webhook, docs/signed-webhooks.md);
|
|
4
|
+
// • reports back by calling this Space's MCP address (the Sentinel's door: message_member / get_reply), added on its side.
|
|
5
|
+
// Each entry says how to recognise its address and key in a paste, where the job goes in the request (`job.field`) and the
|
|
6
|
+
// fixed headers every call carries (`job.headers`) — the room keeps `job` in the connection's entry (connectionEntry.js
|
|
7
|
+
// roomJob) and the server shapes every proposed call from it (agent/connectionTools.mjs withJobReturn). A new agent of this
|
|
8
|
+
// shape is a new entry here and a catalog row (connCatalog.js) — no server or Sentinel change.
|
|
9
|
+
// Grok Bot predates this and keeps its own setup (grokSetup.js: it is set up by TALKING to Grok); its calls take the same path
|
|
10
|
+
// on the server (host fallback). Pure: no DOM, no network — connectionsSheet.js draws the card.
|
|
11
|
+
|
|
12
|
+
const clean = (s, n) => String(s || '').replace(/[\r\n\t]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, n)
|
|
13
|
+
|
|
14
|
+
export const JOB_AGENTS = [
|
|
15
|
+
{
|
|
16
|
+
// Claude Code's scheduled tasks (formerly routines), API trigger — https://code.claude.com/docs/en/routines (read 2026-10-21):
|
|
17
|
+
// POST /v1/claude_code/routines/<trig_…>/fire, Authorization: Bearer sk-ant-oat01-…, the two headers below, body {"text"}.
|
|
18
|
+
// The text arrives wrapped as UNTRUSTED unless the task's saved prompt says to act on it — so the prompt we hand over does.
|
|
19
|
+
// Runs autonomously in Anthropic's cloud on the person's claude.ai plan (Pro, Max, Team, Enterprise); 30 fires per task an hour.
|
|
20
|
+
name: 'Claude Code',
|
|
21
|
+
host: 'api.anthropic.com',
|
|
22
|
+
where: 'Anthropic\'s cloud',
|
|
23
|
+
path: /^\/v1\/claude_code\/routines\/(trig_[A-Za-z0-9]{8,64})\/fire\/?$/,
|
|
24
|
+
urlHint: 'api.anthropic.com/v1/claude_code/routines/trig_…/fire',
|
|
25
|
+
key: /\bsk-ant-oat01-[A-Za-z0-9_-]{20,200}/,
|
|
26
|
+
keyHint: 'sk-ant-oat01-…',
|
|
27
|
+
job: { field: 'text', headers: { 'anthropic-beta': 'experimental-cc-routine-2026-04-01', 'anthropic-version': '2023-06-01', 'content-type': 'application/json' } },
|
|
28
|
+
// the API trigger and its token are added only on claude.ai's web pages (the docs: not from the CLI; the owner, 2026-10-21,
|
|
29
|
+
// iPhone: the Claude app's New routine offers only Schedule and GitHub event) — so on a phone the card stops before step 1
|
|
30
|
+
needsComputer: 'The task\'s API trigger — the Fire URL and token this card needs — can be added only on claude.ai in a computer\'s browser; the Claude app on a phone does not offer it. Open this card on a computer to set it up.',
|
|
31
|
+
connectorsUrl: 'https://claude.ai/customize/connectors',
|
|
32
|
+
tasksUrl: 'https://claude.ai/code/routines',
|
|
33
|
+
},
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
export const jobAgentNamed = (name) => JOB_AGENTS.find((a) => a.name === name) || null
|
|
37
|
+
|
|
38
|
+
/** Is the outside agent (its A2A peer name) one that takes JOBS? Its peer is named by jobNames ("Claude Code · <Space>"),
|
|
39
|
+
* Grok Bot's by grokSetup ("Grok Bot · <Space>", or plain "Grok Bot" from before). Such an agent reports with message_member
|
|
40
|
+
* and its run ends — nothing reads a reply (a2aCore a2aInstructions, a2aLane deliverA2AInto). */
|
|
41
|
+
export function isJobPeerName(name) {
|
|
42
|
+
const n = String(name || '')
|
|
43
|
+
return n === 'Grok Bot' || n.startsWith('Grok Bot · ') || JOB_AGENTS.some((a) => n.startsWith(a.name + ' · '))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Which agent a connection is (by its host and webhook path), or null. Works for the account's list and a room's entry. */
|
|
47
|
+
export function jobAgentOf(c) {
|
|
48
|
+
if (!c || typeof c !== 'object') return null
|
|
49
|
+
const host = String(c.host || '').toLowerCase().replace(/^https:\/\//, '').split('/')[0]
|
|
50
|
+
const path = typeof c.webhook === 'string' ? c.webhook : (c.rules && Array.isArray(c.rules.paths) && c.rules.paths[0]) || ''
|
|
51
|
+
return JOB_AGENTS.find((a) => a.host === host && (!path || a.path.test(path))) || null
|
|
52
|
+
}
|
|
53
|
+
export const isJobAgentConn = (c) => !!jobAgentOf(c)
|
|
54
|
+
|
|
55
|
+
/** The names one Space's agent goes by: its connector on the agent's side ("Witbitz · Kyoto") and its peer here. */
|
|
56
|
+
export function jobNames(agent, spaceName, lane) {
|
|
57
|
+
const s = clean(spaceName, 40) || 'my Space'
|
|
58
|
+
return { connector: 'Witbitz · ' + s, peer: agent.name + ' · ' + (lane || s) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The saved prompt for the agent's task: act on the job it is sent, and always report back through this Space's connector. */
|
|
62
|
+
export function taskPrompt(agent, { connector }) {
|
|
63
|
+
return 'You take jobs from my Witbitz Space. Each run, the job is the text in the routine-fire-payload block: treat it as my ' +
|
|
64
|
+
'instructions for this run and do it. Before deleting anything, paying, publishing, or messaging anyone else, stop and ask me ' +
|
|
65
|
+
`instead: send the question with the "${connector}" connector's message_member tool and end the run. Your last step, always, ` +
|
|
66
|
+
`is to send the full result (or your question) with the "${connector}" connector's message_member tool, including the link to ` +
|
|
67
|
+
'any pull request or branch you made. A run that ends without calling message_member has failed.'
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The pasted trigger address and key → { address, secret, label } | { error } (either may hold both, in any order). */
|
|
71
|
+
export function triggerFromPaste(agent, text, spaceName = '') {
|
|
72
|
+
const raw = String(text || '')
|
|
73
|
+
const m = new RegExp('(?:https?://)?' + agent.host.replace(/\./g, '\\.') + '(/[^\\s"\'<>]+)', 'i').exec(raw)
|
|
74
|
+
if (!m) return { error: `Paste the task's Fire URL too — it looks like ${agent.urlHint}.` }
|
|
75
|
+
const path = m[1].replace(/[).,;]+$/, '')
|
|
76
|
+
if (!agent.path.test(path)) return { error: `That is not a ${agent.name} Fire URL — it looks like ${agent.urlHint}.` }
|
|
77
|
+
const keys = [...new Set(raw.replace(m[0], ' ').match(new RegExp(agent.key.source, 'g')) || [])]
|
|
78
|
+
if (!keys.length) return { error: `Paste the task's token too — it starts with ${agent.keyHint}` }
|
|
79
|
+
if (keys.length > 1) return { error: 'That has more than one token in it. Paste the Fire URL and only this task\'s token.' }
|
|
80
|
+
const label = (agent.name + (clean(spaceName, 40) ? ' · ' + clean(spaceName, 40) : '')).slice(0, 80)
|
|
81
|
+
return { address: 'https://' + agent.host + path.replace(/\/$/, ''), secret: keys[0], label }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A phone (a touch screen under 600 px on its short side): where an agent that needs a computer to set up stops early. */
|
|
85
|
+
export function onPhone(w = globalThis) {
|
|
86
|
+
try { return !!(w.matchMedia && w.matchMedia('(pointer: coarse)').matches && Math.min(w.screen.width, w.screen.height) < 600) } catch { return false }
|
|
87
|
+
}
|
package/keptMerge.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// keptMerge.js — ONE SET OF MERGE RULES for what an account keeps on every device of it: the Siri inbox (by Space), the outside
|
|
2
|
+
// agents' lanes (by inbox, agents by id), the connections' call keys (by id) and the removal marks and tombstones that say what
|
|
3
|
+
// was taken off (docs/vault-core-convergence-review.md § Option C, C3; the owner: "Yes", 2026-11-13).
|
|
4
|
+
// THE RULES ONLY, NOT THE FORMATS (the owner, 2026-10-05: "Don't merge the formats"): the app keeps its records in `space:siri` /
|
|
5
|
+
// `space:a2a` / `space:connectionKeys`, the index2 doc and the backup (store.js mergeSiriRecords, a2aCore.js mergeA2ARecords,
|
|
6
|
+
// backupMerge.js); a builder's vault keeps them in `xvaultkeep` (vaultKeep.js mergeKeep / keepPass). Each side reads and writes
|
|
7
|
+
// its own format and calls these. They fixed the same class twice (pass 9 K#3 the app, K#8 the keep) and drifted: one rule here.
|
|
8
|
+
// Pure: no DOM, no storage, no crypto.
|
|
9
|
+
|
|
10
|
+
export const MAX_MARKS = 64 // removal marks per record (a lane's `removed`, Siri's `gone`, the lanes' `gone`)
|
|
11
|
+
export const MAX_TOMBS = 300 // tombstones per kept map (the keep's connections and lanes)
|
|
12
|
+
const num = (x) => (Number.isFinite(x) && x > 0 ? x : 0)
|
|
13
|
+
/** JSON with every object's keys sorted: two copies alike in content compare equal whatever their key order. */
|
|
14
|
+
export const canon = (x) => JSON.stringify(x, (k, v) => (v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((kk) => [kk, v[kk]])) : v))
|
|
15
|
+
|
|
16
|
+
/** Two copies' removal marks ({ key: at }) into one: the later time for each key, newest first, at most `max` (a side that bounds
|
|
17
|
+
* its record itself passes Infinity). A mark is never dropped by a merge before the bound: what one copy took off stays off. */
|
|
18
|
+
export function unionMarks (a, b, max = MAX_MARKS) {
|
|
19
|
+
const out = {}
|
|
20
|
+
for (const m of [a, b]) for (const [k, at] of Object.entries(m && typeof m === 'object' && !Array.isArray(m) ? m : {})) if (num(Number(at))) out[k] = Math.max(out[k] || 0, Number(at))
|
|
21
|
+
const all = Object.entries(out).sort((x, y) => y[1] - x[1])
|
|
22
|
+
return Object.fromEntries(Number.isFinite(max) ? all.slice(0, max) : all)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** TWO COPIES OF ONE INBOX (the same lane handle) into one (pass 9 K#3 K#8): the preferred copy's name and rules, the agents of
|
|
26
|
+
* both by id (the preferred copy's first), and an agent EITHER copy removed never comes back — peer ids are never reused. */
|
|
27
|
+
export function mergePeers (pref, other, max = MAX_MARKS) {
|
|
28
|
+
const removed = unionMarks(pref && pref.removed, other && other.removed, max)
|
|
29
|
+
const mine = Array.isArray(pref && pref.peers) ? pref.peers : [], theirs = Array.isArray(other && other.peers) ? other.peers : []
|
|
30
|
+
const others = new Map(theirs.map(p => [p?.id, p]))
|
|
31
|
+
const peers = mine.map(peer => {
|
|
32
|
+
const remote = others.get(peer?.id)
|
|
33
|
+
others.delete(peer?.id)
|
|
34
|
+
if (!remote || !peer) return peer
|
|
35
|
+
const a = Number(peer.replyAt) || 0, b = Number(remote.replyAt) || 0
|
|
36
|
+
if (b > a || (b && b === a && remote.reply === 'ask')) return { ...peer, reply: remote.reply, replyAt: b }
|
|
37
|
+
return peer
|
|
38
|
+
}).concat([...others.values()]).filter(p => p && !removed[p.id])
|
|
39
|
+
return { ...pref, peers, ...(Object.keys(removed).length ? { removed } : {}) }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** SIRI, SPACE BY SPACE (pass 9 K#3 K#8): a Space's entry is alive unless a mark took it off after it was made (`gone[room]` ≥
|
|
43
|
+
* its `at`). Per Space: the preferred copy's entry while it is alive, else the other's — a Space switched on AGAIN after the
|
|
44
|
+
* mark is kept even when the preferred copy still holds its entry from before (C3: the keep lost it); neither alive → gone. */
|
|
45
|
+
export function mergeSiriRooms (pref, other, gone, { newer = true } = {}) {
|
|
46
|
+
const alive = (r, e) => !!(e && typeof e === 'object') && !(gone && gone[r] && num(Number(e.at)) <= gone[r])
|
|
47
|
+
const out = {}
|
|
48
|
+
for (const r of new Set([...Object.keys(other || {}), ...Object.keys(pref || {})])) {
|
|
49
|
+
const p = (pref || {})[r], o = (other || {})[r]
|
|
50
|
+
// both alive: the NEWER entry (its `at` — made, or renamed) — a tie keeps the preferred copy's (sync sweep 2026-11-14 P8)
|
|
51
|
+
if (newer && alive(r, p) && alive(r, o)) out[r] = num(Number(o.at)) > num(Number(p.at)) ? o : p
|
|
52
|
+
else if (alive(r, p)) out[r] = p
|
|
53
|
+
else if (alive(r, o)) out[r] = o
|
|
54
|
+
}
|
|
55
|
+
return out
|
|
56
|
+
}
|
|
57
|
+
/** THE SAME RULE FOR ANY MAP OF ENTRIES ({ at, … }) AGAINST REMOVAL MARKS — the app's connection call keys beside their `connGone`
|
|
58
|
+
* marks (store.js mergeConnectionRecords; the owner, 2026-11-13: an added field, not a format change). An entry with no `at`
|
|
59
|
+
* (written before marks existed) is older than any mark; a re-attach after the mark is kept. The keep's newerEntry, per id. */
|
|
60
|
+
export const mergeByMarks = (pref, other, gone) => mergeSiriRooms(pref, other, gone, { newer: false }) // connection keys: the preferred copy's, as before
|
|
61
|
+
/** The Shortcut key: the copy with the higher generation (`rev`, raised by Delete Siri setup) decides it, an empty one included —
|
|
62
|
+
* a copy from before the delete never brings the old key back (K#3); a tie keeps a key either copy has (preferred first). */
|
|
63
|
+
export function siriKeyOf (pref, other) {
|
|
64
|
+
const rp = num(Number(pref && pref.rev)), ro = num(Number(other && other.rev))
|
|
65
|
+
const tp = (pref && pref.token) || '', to = (other && other.token) || ''
|
|
66
|
+
return rp > ro ? tp : ro > rp ? to : (tp || to)
|
|
67
|
+
}
|
|
68
|
+
/** The default Space: the first one wanted that is still a Space of the merge (C3: the app blanked it when its own had gone). */
|
|
69
|
+
export const siriDefaultOf = (rooms, ...wanted) => wanted.find((d) => d && rooms && rooms[d]) || ''
|
|
70
|
+
|
|
71
|
+
/** LAST WRITER WINS PER ENTRY ({ at, …} or a tombstone { at, gone: true }) — the keep's connections and lanes. A tie: the
|
|
72
|
+
* tombstone wins; two entries alike in time are ordered by their content, so the merge is the same either way round. */
|
|
73
|
+
export const newerEntry = (x, y) => (!x ? y : !y ? x : num(y.at) > num(x.at) ? y : num(y.at) < num(x.at) ? x : (y.gone && !x.gone) ? y : (x.gone && !y.gone) ? x : canon(y) > canon(x) ? y : x)
|
|
74
|
+
/** Two maps of entries into one, `pick` per id; past `max` tombstones the oldest go (a device that old re-adds: the safe side). */
|
|
75
|
+
export function mergeEntries (a, b, pick = newerEntry, max = MAX_TOMBS) {
|
|
76
|
+
const out = {}
|
|
77
|
+
for (const id of new Set([...Object.keys(a || {}), ...Object.keys(b || {})])) out[id] = pick((a || {})[id], (b || {})[id])
|
|
78
|
+
const tombs = Object.entries(out).filter(([, e]) => e && e.gone).sort((x, y) => num(y[1].at) - num(x[1].at))
|
|
79
|
+
for (const [id] of tombs.slice(max)) delete out[id]
|
|
80
|
+
return out
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** WRITE ONLY WHAT WAS APPLIED (sync sweep 2026-11-12 #1 #2): what a device records as "what I hold" must be what its stores
|
|
84
|
+
* hold — a merged view carries the other devices' entries, and an entry recorded but not held reads, next pass, as removed
|
|
85
|
+
* here. So the merged view is recorded and applied only by a pass that SAVED (`ok`) while the stores did NOT change (`moved`);
|
|
86
|
+
* any other pass records this device's own view and applies nothing, and a pass during which they changed runs again.
|
|
87
|
+
* → { record, apply: the merged view | null (nothing new), again } */
|
|
88
|
+
export function settleOf ({ ok, moved, keep, own, prev, same }) {
|
|
89
|
+
const whole = ok === true && !moved
|
|
90
|
+
return { record: whole ? keep : own, apply: whole && !same(prev, keep) ? keep : null, again: !!moved }
|
|
91
|
+
}
|