@witbitz/sdk 0.0.0-stage → 4.3.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.
Files changed (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
@@ -0,0 +1,112 @@
1
+ // codeCloudKeys.js — A CLOUD COMPUTER'S MODEL KEYS FROM THE SPACES ACCOUNT, as a paired laptop's are (docs/code-account-keys.md;
2
+ // the owner, 2026-10-12, on the New cloud computer sheet: "Why do we need the key?" → "Account keys, count it"). Laptops
3
+ // have taken their keys from the account since 10-08; cloud computers were left asking for the person's own. Now the page
4
+ // does what a laptop's connector does (tools/code-keys-client.mjs): two key pairs — P-256, which the keys are SEALED to;
5
+ // Ed25519, which signs later calls — then POST /v1/spaces/code-keys with the account's sign-in. The answer is opened HERE,
6
+ // and the keys go where a pasted key went: the account's sealed cloud doc, handed only to the host's Credential Sentinel.
7
+ // The same caps ($50 TrustedRouter + $5 Tinfoil a month) and the same limit (3 computers per account). Removing the
8
+ // computer cancels them (drawer.js revokeCodeKeys). Cloud computers made before keep their pasted keys (owner's choice).
9
+ //
10
+ // `codeKey` = { keyId, tenantId, userId, kid, sealPriv, signPriv } (both private keys as JWK) rides the cloud entry, so a
11
+ // later open can call status (signed): that is what renews the Tinfoil key's cap each month, or mints one that failed.
12
+
13
+ export const CODE_KEYS_API = 'https://api.witbitz.chat/v1/spaces/code-keys'
14
+ const enc = new TextEncoder(), dec = new TextDecoder()
15
+ const b64u = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
16
+ const ub64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((String(s).length + 3) % 4)), (c) => c.charCodeAt(0))
17
+ export const codeAad = (tenantId, userId, kid, provider) => `wbkey-v1|${tenantId}|${userId}|code:${kid}:${provider}` // = codeKeys.mjs codeAad
18
+ export const signedMessage = (op, keyId, ts) => `wbcode-v1|${op}|${keyId}|${ts}` // = codeKeys.mjs signedMessage
19
+
20
+ // What the person reads when the account will not give this computer keys — the server's codes, said as the laptop says them.
21
+ const REFUSALS = {
22
+ not_invited: 'Coding on Witbitz is by invitation for now, and this account is not on the list.',
23
+ code_keys_off: 'Coding on Witbitz is paused for now.',
24
+ revoked: 'Billing for this account has been turned off.',
25
+ signin_stale: 'Your sign-in on this device is about to end — open Settings, sign in again, then try once more.',
26
+ not_signed_in: 'This device’s sign-in was not accepted — sign in again with your email, then try once more.',
27
+ signin_invalid: 'This device’s sign-in was not accepted — sign in again, then try once more.',
28
+ }
29
+
30
+ /** The mkseal envelope (enclaveKeySeal.mjs) → the secret, or null (wrong key, tamper, wrong AAD). */
31
+ export async function openSealed(blob, sealPrivJwk, aad) {
32
+ try {
33
+ if (!blob || !blob.epk || !blob.iv || !blob.ct) return null
34
+ const priv = await crypto.subtle.importKey('jwk', sealPrivJwk, { name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'])
35
+ const epkBytes = ub64u(blob.epk)
36
+ const epk = await crypto.subtle.importKey('raw', epkBytes, { name: 'ECDH', namedCurve: 'P-256' }, false, [])
37
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: epk }, priv, 256))
38
+ const ikm = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey'])
39
+ const key = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: new Uint8Array([...enc.encode('mkseal-v1'), ...epkBytes]) }, ikm, { name: 'AES-GCM', length: 256 }, false, ['decrypt'])
40
+ return dec.decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ub64u(blob.iv), additionalData: enc.encode(aad) }, key, ub64u(blob.ct)))
41
+ } catch { return null }
42
+ }
43
+
44
+ /** The computer's two key pairs, private halves as JWK (kept in the sealed cloud doc). */
45
+ export async function newIdentity() {
46
+ const seal = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits'])
47
+ const sign = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])
48
+ const sp = await crypto.subtle.exportKey('jwk', seal.publicKey)
49
+ return {
50
+ sealPriv: await crypto.subtle.exportKey('jwk', seal.privateKey),
51
+ signPriv: await crypto.subtle.exportKey('jwk', sign.privateKey),
52
+ sealPub: { kty: 'EC', crv: 'P-256', x: sp.x, y: sp.y },
53
+ signPub: b64u(new Uint8Array(await crypto.subtle.exportKey('raw', sign.publicKey))),
54
+ }
55
+ }
56
+
57
+ /** → { ok:true, tr, tinfoil, venice, codeKey } | { ok:false, reason } — the keys for computer `computerId`, from the account.
58
+ * `venice`: the zero-retention models' key (docs/code-venice-fallback.md) — '' when none came. */
59
+ export async function mintCloudKeys({ computerId, name, idToken, fetchImpl = fetch, api = CODE_KEYS_API } = {}) {
60
+ if (!idToken) return { ok: false, reason: 'Sign in with your email in Spaces first — the computer’s keys come from your account.' }
61
+ let id
62
+ try { id = await newIdentity() } catch { return { ok: false, reason: 'This browser cannot make the computer’s keys (it lacks Ed25519) — update it, or use another device.' } }
63
+ let r = null, j = null
64
+ try {
65
+ r = await fetchImpl(api, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ idToken, computerId, name, sealPub: id.sealPub, signPub: id.signPub }) })
66
+ j = await r.json().catch(() => null)
67
+ } catch { return { ok: false, reason: 'Couldn’t reach Witbitz for the computer’s keys — check your connection and try again.' } }
68
+ const err = (j && j.error) || {}, d = (j && j.data) || {}
69
+ if (!r.ok || !d.sealed) {
70
+ const code = String(err.code || '')
71
+ return { ok: false, code, reason: (code === 'too_many_computers' && err.message ? err.message[0].toUpperCase() + err.message.slice(1) + '.' : '') || REFUSALS[code] || 'Witbitz did not give this computer its keys — try again in a minute.' }
72
+ }
73
+ j = d
74
+ const tr = await openSealed(j.sealed.trustedrouter, id.sealPriv, codeAad(j.tenantId, j.userId, j.kid, 'trustedrouter'))
75
+ if (!tr) return { ok: false, reason: 'The computer’s keys arrived but would not open — try again.' }
76
+ const tinfoil = j.sealed.tinfoil ? (await openSealed(j.sealed.tinfoil, id.sealPriv, codeAad(j.tenantId, j.userId, j.kid, 'tinfoil'))) || '' : ''
77
+ const venice = j.sealed.venice ? (await openSealed(j.sealed.venice, id.sealPriv, codeAad(j.tenantId, j.userId, j.kid, 'venice'))) || '' : ''
78
+ const codeKey = takeCodeKey({ keyId: j.keyId, tenantId: j.tenantId, userId: j.userId, kid: j.kid, sealPriv: id.sealPriv, signPriv: id.signPriv })
79
+ if (!codeKey) return { ok: false, reason: 'Witbitz answered with keys this page could not keep — try again.' }
80
+ return { ok: true, tr, tinfoil, venice, codeKey }
81
+ }
82
+
83
+ /** At an opening: a SIGNED status — renews the Tinfoil cap at a month change, mints a Tinfoil key that failed at creation.
84
+ * And the Venice key, sent at every status (the server keeps resending it: a page before cloud computers took it threw it away).
85
+ * → { live, tinfoil?, venice? } (each only when one came back) | null (unknown: never blocks the opening). */
86
+ export async function cloudKeyStatus(codeKey, { fetchImpl = fetch, api = CODE_KEYS_API, nowS = () => Math.floor(Date.now() / 1000), timeoutMs = 5000 } = {}) {
87
+ try {
88
+ if (!codeKey || !codeKey.keyId || !codeKey.signPriv) return null
89
+ const ts = nowS()
90
+ const k = await crypto.subtle.importKey('jwk', codeKey.signPriv, { name: 'Ed25519' }, false, ['sign'])
91
+ const sig = b64u(new Uint8Array(await crypto.subtle.sign({ name: 'Ed25519' }, k, enc.encode(signedMessage('status', codeKey.keyId, ts)))))
92
+ const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), timeoutMs)
93
+ let j = null
94
+ try { const r = await fetchImpl(api + '/status', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ keyId: codeKey.keyId, ts, sig }), signal: ctrl.signal }); j = ((await r.json().catch(() => null)) || {}).data || null } finally { clearTimeout(t) }
95
+ if (!j || typeof j.live !== 'boolean') return null
96
+ const tinfoil = j.sealed && j.sealed.tinfoil ? await openSealed(j.sealed.tinfoil, codeKey.sealPriv, codeAad(codeKey.tenantId, codeKey.userId, codeKey.kid, 'tinfoil')) : null
97
+ const venice = j.sealed && j.sealed.venice ? await openSealed(j.sealed.venice, codeKey.sealPriv, codeAad(codeKey.tenantId, codeKey.userId, codeKey.kid, 'venice')) : null
98
+ return { live: j.live, ...(j.why ? { why: j.why } : {}), ...(tinfoil ? { tinfoil } : {}), ...(venice ? { venice } : {}) }
99
+ } catch { return null }
100
+ }
101
+
102
+ const JWK_EC = (v) => v && typeof v === 'object' && v.kty === 'EC' && v.crv === 'P-256' && typeof v.d === 'string' && typeof v.x === 'string' && typeof v.y === 'string'
103
+ const JWK_ED = (v) => v && typeof v === 'object' && v.kty === 'OKP' && v.crv === 'Ed25519' && typeof v.d === 'string' && typeof v.x === 'string'
104
+ const ID = /^[A-Za-z0-9_-]{1,80}$/
105
+ /** codeComputers.js CLOUD_FIELDS validator: the shape above, or undefined (dropped). */
106
+ export function takeCodeKey(v) {
107
+ if (!v || typeof v !== 'object') return undefined
108
+ const keyId = String(v.keyId || ''), tenantId = String(v.tenantId || ''), userId = String(v.userId || ''), kid = String(v.kid || '')
109
+ if (!/^[A-Za-z0-9_-]{1,80}\.[A-Za-z0-9_-]{1,80}$/.test(keyId) || !ID.test(tenantId) || !ID.test(userId) || !ID.test(kid) || !JWK_EC(v.sealPriv) || !JWK_ED(v.signPriv)) return undefined
110
+ const ec = ({ kty, crv, x, y, d }) => ({ kty, crv, x, y, d }), ed = ({ kty, crv, x, d }) => ({ kty, crv, x, d })
111
+ return { keyId, tenantId, userId, kid, sealPriv: ec(v.sealPriv), signPriv: ed(v.signPriv) }
112
+ }
@@ -0,0 +1,167 @@
1
+ // spaces/public/codeCommands.js — OpenCode's "/" commands and skills in the Code section.
2
+ //
3
+ // ★ NEVER POST /session/:id/command. Measured on opencode 1.18.30 (2026-09-13): that route substitutes the typed arguments
4
+ // into the template and THEN runs every !`…` in the result through a shell — with no permission prompt, even in a session
5
+ // whose rules deny bash (a probe `touch`ed a file that way, both for a command and for a skill). So a command's arguments
6
+ // are a shell, and the relay must not carry them. An ordinary message with the same text runs nothing.
7
+ //
8
+ // Instead the page reads the list (GET /command — name, description, source, template, agent, model), fills the
9
+ // template in itself with OpenCode's OWN substitution rules (the regexes below are copied from its source), and sends an
10
+ // ordinary message: what you typed ("/review main") as the visible part, the expansion as a `synthetic` part — measured:
11
+ // the model reads it, the stored message keeps the flag, and the transcript hides it. A template that itself contains
12
+ // !`…` needs the computer: it is listed, marked, and refused here.
13
+ // Not reproduced from OpenCode's route: its @file expansion inside a template, and running `subtask` commands as a
14
+ // sub-agent. The agent reads files itself, and the turn runs in the open session.
15
+
16
+ const SHELL_RE = /!`([^`]+)`/ // OpenCode: /!`([^`]+)`/g
17
+ const ARG_RE = /(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi // OpenCode's argument splitter
18
+ const QUOTE_RE = /^["']|["']$/g
19
+ const POS_RE = /\$(\d+)/g
20
+
21
+ const str = (v) => (v == null ? '' : String(v))
22
+
23
+ /** GET /command → the entries that can be offered, sorted by name. `needsComputer` = the template runs a shell. */
24
+ export function normCommands(list) {
25
+ return (Array.isArray(list) ? list : [])
26
+ .filter((c) => c && typeof c === 'object' && str(c.name).trim() && typeof c.template === 'string')
27
+ .map((c) => ({
28
+ name: str(c.name).trim(),
29
+ description: str(c.description),
30
+ source: ['command', 'skill', 'mcp'].includes(c.source) ? c.source : 'command',
31
+ template: c.template,
32
+ agent: str(c.agent),
33
+ model: str(c.model),
34
+ needsComputer: SHELL_RE.test(c.template),
35
+ }))
36
+ .sort((a, b) => a.name.localeCompare(b.name))
37
+ }
38
+
39
+ /** OpenCode's substitution, minus the shell: $1…$n positional (the highest takes the rest), $ARGUMENTS verbatim, and
40
+ * with no placeholder at all the arguments are appended after a blank line. */
41
+ export function expandTemplate(template, args) {
42
+ const a = str(args)
43
+ const words = (a.match(ARG_RE) || []).map((w) => w.replace(QUOTE_RE, ''))
44
+ const placeholders = template.match(POS_RE) || []
45
+ let last = 0
46
+ for (const p of placeholders) last = Math.max(last, Number(p.slice(1)))
47
+ let out = template.replace(POS_RE, (_, n) => {
48
+ const i = Number(n) - 1
49
+ if (i < 0 || i >= words.length) return ''
50
+ return Number(n) === last ? words.slice(i).join(' ') : words[i]
51
+ })
52
+ const hasAll = template.includes('$ARGUMENTS')
53
+ out = out.split('$ARGUMENTS').join(a)
54
+ if (!placeholders.length && !hasAll && a.trim()) out = `${out}\n\n${a}`
55
+ return out.trim()
56
+ }
57
+
58
+ /** "/name args" at the very start of the message → {name, args}; anything else is a normal message. */
59
+ export function parseSlash(text) {
60
+ const m = /^\/([^\s/][^\s]*)(?:\s+([\s\S]*))?$/.exec(str(text))
61
+ return m ? { name: m[1], args: str(m[2]).trim() } : null
62
+ }
63
+
64
+ /** The turn a "/…" message becomes, or null when it is not a known command (then it is sent as typed). */
65
+ export function commandTurn(text, commands) {
66
+ const s = parseSlash(str(text).trim())
67
+ if (!s || !Array.isArray(commands)) return null
68
+ const cmd = commands.find((c) => c.name === s.name)
69
+ if (!cmd) return null
70
+ return {
71
+ name: cmd.name, source: cmd.source, agent: cmd.agent, model: cmd.model,
72
+ visible: `/${cmd.name}${s.args ? ' ' + s.args : ''}`,
73
+ expanded: expandTemplate(cmd.template, s.args),
74
+ blocked: cmd.needsComputer,
75
+ }
76
+ }
77
+
78
+ /** Names starting with the query first, then names or descriptions containing it. */
79
+ export function filterCommands(commands, query) {
80
+ const q = str(query).toLowerCase()
81
+ const list = Array.isArray(commands) ? commands : []
82
+ if (!q) return list.slice()
83
+ const starts = list.filter((c) => c.name.toLowerCase().startsWith(q))
84
+ const rest = list.filter((c) => !starts.includes(c) && (c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q)))
85
+ return [...starts, ...rest]
86
+ }
87
+
88
+ /**
89
+ * The menu over the composer. It opens while the message is a lone "/word" being typed, filters as you type, and picks
90
+ * with a tap, Enter or Tab (↑↓ to move, Escape to close). Options fire on mousedown so the keyboard stays up.
91
+ * @param input the composer <textarea>
92
+ * @param anchor the element the menu sits above (the composer pill)
93
+ * @param commands () => { list } | { loading: true } | { error: 'why' } — asked on every open; may start a load
94
+ * @param onChange () => void — after a pick rewrites the input (autosize, direction)
95
+ */
96
+ export function slashMenu({ input, anchor, commands, onChange = () => {} }) {
97
+ let menu = null, items = [], index = 0
98
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
99
+ const query = () => {
100
+ const caret = input.selectionStart == null ? input.value.length : input.selectionStart
101
+ const m = /^\/(\S*)$/.exec(input.value.slice(0, caret))
102
+ return m && !/\S/.test(input.value.slice(caret, caret + 1)) ? m[1] : null
103
+ }
104
+ const close = () => { if (menu) { menu.remove(); menu = null } }
105
+ const pick = (c) => {
106
+ const rest = input.value.replace(/^\/\S*\s?/, '')
107
+ input.value = `/${c.name} ${rest}`
108
+ const end = c.name.length + 2
109
+ try { input.setSelectionRange(end, end) } catch { /* not focused */ }
110
+ close()
111
+ onChange()
112
+ }
113
+ const render = () => {
114
+ const q = query()
115
+ if (q == null) return close()
116
+ const state = commands() || {}
117
+ if (!menu) {
118
+ menu = el('div', 'slash-menu')
119
+ menu.setAttribute('role', 'listbox')
120
+ menu.addEventListener('mousedown', (e) => e.preventDefault()) // never take focus from the composer
121
+ document.body.appendChild(menu)
122
+ }
123
+ menu.textContent = ''
124
+ items = state.list ? filterCommands(state.list, q) : []
125
+ if (index >= items.length) index = 0
126
+ if (state.error) menu.append(el('div', 'slash-note', state.error))
127
+ else if (state.loading) menu.append(el('div', 'slash-note', 'Loading commands…'))
128
+ else if (!items.length) menu.append(el('div', 'slash-note', q ? `No command or skill matches "${q}"` : 'No commands or skills on this computer'))
129
+ items.forEach((c, i) => {
130
+ const row = el('button', 'slash-opt')
131
+ row.type = 'button'
132
+ row.setAttribute('role', 'option')
133
+ row.setAttribute('aria-selected', String(i === index))
134
+ const top = el('span', 'slash-top')
135
+ top.append(el('span', 'slash-name', '/' + c.name), el('span', 'slash-src', c.source))
136
+ row.append(top)
137
+ if (c.description) row.append(el('span', 'slash-desc', c.description))
138
+ if (c.needsComputer) row.append(el('span', 'slash-warn', 'Runs commands on your computer — start it there, not from here'))
139
+ row.addEventListener('mousedown', (e) => { e.preventDefault(); pick(c) })
140
+ menu.append(row)
141
+ })
142
+ const r = anchor.getBoundingClientRect()
143
+ menu.style.left = `${Math.max(8, r.left)}px`
144
+ menu.style.width = `${Math.min(r.width, window.innerWidth - 16)}px`
145
+ menu.style.bottom = `${Math.max(8, window.innerHeight - r.top + 8)}px`
146
+ const sel = menu.querySelector('[aria-selected="true"]')
147
+ if (sel && sel.scrollIntoView) sel.scrollIntoView({ block: 'nearest' })
148
+ }
149
+ input.addEventListener('input', () => { index = 0; render() })
150
+ input.addEventListener('click', render)
151
+ input.addEventListener('blur', () => setTimeout(() => { if (document.activeElement !== input) close() }, 150))
152
+ // Capture, so a pick with Enter/Tab never reaches the composer's own keys (a newline, or send on ⌘/Ctrl-Enter).
153
+ input.addEventListener('keydown', (e) => {
154
+ if (!menu) return
155
+ if (e.key === 'Escape') { e.preventDefault(); e.stopImmediatePropagation(); close(); return }
156
+ if (!items.length) return
157
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
158
+ e.preventDefault(); e.stopImmediatePropagation()
159
+ index = (index + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length
160
+ render()
161
+ } else if ((e.key === 'Enter' && !e.metaKey && !e.ctrlKey) || e.key === 'Tab') {
162
+ e.preventDefault(); e.stopImmediatePropagation()
163
+ pick(items[index])
164
+ }
165
+ }, true)
166
+ return { refresh: render, close, isOpen: () => !!menu }
167
+ }