@witbitz/sdk 4.3.0 → 4.5.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 (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
package/acctV2UiCore.js CHANGED
@@ -54,6 +54,7 @@ const MESSAGES = {
54
54
  keys_mismatch: 'The service answered with keys this device didn’t register. Nothing was changed.',
55
55
  session_ended: 'That took too long or something changed meanwhile. Nothing changed — start again.',
56
56
  pending_not_kept: 'This device couldn’t save the new recovery code, so it wasn’t activated. Your current code still works — free some space or try again.',
57
+ attested_prev_not_saved: 'The new recovery code wasn’t made: the service didn’t answer while your Spaces that need the Witbitz app were being linked to it. Your current code still works — try again in a moment.', // side sweep round 5: the record of the earlier keys comes before the new code
57
58
  address_taken: 'That email address already has an account on the new service. Restore it on this device instead (“Restore my account from the new service”).',
58
59
  bad_address: 'That doesn’t look like an email address.',
59
60
  state_changed: 'Something changed on your account meanwhile. Nothing changed — start again.',
@@ -259,7 +260,7 @@ export const emailCode = (address, kind = 'account') => withChoice(address, asyn
259
260
  })
260
261
 
261
262
  /** Append the section to the devices box; `rerender` redraws the panel after a change. */
262
- export function renderAcctV2Section(box, rerender) {
263
+ export function renderAcctV2Section(box, rerender, { devicesBox = null } = {}) { // devicesBox: the devices and "Sign out all" go there (the vault's Your devices view)
263
264
  const a = acctV2()
264
265
  if (!a.enabled()) { renderMoveOnly(box, rerender); return } // an account on the OLD service: only the move, where it is open
265
266
  const s = a.state()
@@ -301,7 +302,10 @@ export function renderAcctV2Section(box, rerender) {
301
302
  b.onclick = () => startFresh(a, address, rerender)
302
303
  sec.append(t, d, b); box.append(sec); return
303
304
  }
304
- sec.append(t, d, serviceDevicesBlock(a, address, rerender), b, nc)
305
+ // ON THEIR OWN CARD, WHERE ASKED (the owner, 2026-11-27, of the vault's Back up & recovery: "too many logouts … It should be on a
306
+ // different card"): the devices and "Sign out all other devices now" go to the caller's box; the recovery code stays here
307
+ if (devicesBox) { b.style.marginTop = '10px'; devicesBox.replaceChildren(serviceDevicesBlock(a, address, rerender), b); sec.append(t, d, nc) }
308
+ else sec.append(t, d, serviceDevicesBlock(a, address, rerender), b, nc)
305
309
  const mw = moveWarningBlock(rerender) // § 11.5, 3a: a move of this account's address under way — above everything else
306
310
  if (mw) sec.prepend(mw)
307
311
  box.append(sec)
@@ -487,6 +491,7 @@ export function moveOpen(svc, fetchImpl = (...x) => fetch(...x)) {
487
491
  try {
488
492
  const r = await fetchImpl(String(svc).replace(/\/+$/, '') + '/v2/account/legacy/intent', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
489
493
  const on = r.status !== 501 && r.status !== 404 && r.status < 500
494
+ if (r.status >= 500 && r.status !== 501) return false // an outage is not an answer: asked again next time (side sweep 2026-11-28: a 503 hid the move until reload)
490
495
  _moveKnown.set(svc, on)
491
496
  return on
492
497
  } catch { return false } finally { _moveProbe.delete(svc) }
@@ -526,12 +531,12 @@ export async function offerAutoMove(rerender = () => {}) {
526
531
  if (!oldAccountHere()) return false
527
532
  return moveAccount(rerender, { auto: true })
528
533
  }
529
- const AUTO_MOVE_TEXT = (address) => `Your account needs a one-time move to Witbitz’s new account service.\n\nWe’ll send a code to ${address} — type it in the next step. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).\n\nYou can also do it later: Settings → Back up & recovery.`
534
+ const AUTO_MOVE_TEXT = (address) => `Your account needs a one-time move to Witbitz’s new account service.\n\nWe’ll send a code to ${address} — type it in the next step. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).\n\nIts old backup has no account key, so it moves with your email only: Advanced Backup isn’t available for it afterwards, and the original backup is kept as it was for a year.\n\nYou can also do it later: Settings → Back up & recovery.`
530
535
  /** The move itself. The device is switched onto the service for it, and back if the account did not move. → whether it moved. */
531
536
  async function moveAccount(rerender, { auto = false } = {}) {
532
537
  const address = accountAddress()
533
538
  if (!address) { if (!auto) await notice('Sign in with your email on this device first.'); return false }
534
- if (!(await confirmSheet(auto ? { message: AUTO_MOVE_TEXT(address), confirmLabel: 'Move now', cancelLabel: 'Not now', destructive: false } : { message: `Move this account to the new account service?\n\nWe’ll send a code to ${address}. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).`, confirmLabel: 'Move', destructive: false }))) return false
539
+ if (!(await confirmSheet(auto ? { message: AUTO_MOVE_TEXT(address), confirmLabel: 'Move now', cancelLabel: 'Not now', destructive: false } : { message: `Move this account to the new account service?\n\nWe’ll send a code to ${address}. Your Spaces and your recovery code stay as they are.\n\nWhen the move is done, your OTHER devices are signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).\n\nIf its old backup has no account key, it moves with your email only: Advanced Backup isn’t available for it afterwards, and the original backup is kept as it was for a year.`, confirmLabel: 'Move', destructive: false }))) return false
535
540
  let a = acctV2(), undo = () => {}
536
541
  if (!a.enabled()) {
537
542
  const svc = moveSvc()
@@ -558,12 +563,16 @@ async function moveAccount(rerender, { auto = false } = {}) {
558
563
  }
559
564
  }
560
565
  // MOVED. Only now are the other devices signed out (a move that failed signed out nobody).
566
+ // a SILENT move resumed here (its answer was lost): the other devices join it by themselves — never signed out (side sweep 2026-11-28)
561
567
  let others = null
562
- try { others = dep().afterMove ? await dep().afterMove({ trust: r.legacy_trust }) : null } catch { others = null }
568
+ if (r.silent) others = []
569
+ else { try { others = dep().afterMove ? await dep().afterMove({ trust: r.legacy_trust }) : null } catch { others = null } }
563
570
  const emailOnly = r.legacy_trust === 'email_only'
564
571
  await notice('Done. This account now uses the new account service, with the same recovery code.'
565
572
  + (emailOnly ? '\n\nIt was moved with your email only (its old backup had no account key), so it stays in a lower-trust state: Advanced Backup isn’t available for it, and the original backup is kept as it was for a year.' : '')
566
- + (Array.isArray(others) && !others.length ? '' : '\n\nYour other devices are being signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).'))
573
+ + (others && others.unconfirmed ? '\n\nThis device could not confirm that your other devices were told to sign out. If one still shows your Spaces, sign it out from Settings → Your devices on this device.'
574
+ : r.silent ? '\n\nYour other devices join it by themselves the next time they open.'
575
+ : Array.isArray(others) && !others.length ? '' : '\n\nYour other devices are being signed out: each clears itself the next time it’s online and says why. To use one again, restore your Spaces on it with your recovery code, or add it from this device (Add a device).'))
567
576
  rerender()
568
577
  return true
569
578
  }
@@ -605,6 +614,17 @@ export async function approveNewDevice({ newSpk, label }) {
605
614
  }
606
615
  }
607
616
 
617
+ /** § 8.6's undo, on the APPROVING device (both apps' givers): the new device declined the account, or never collected it, after
618
+ * approveNewDevice registered it — take the registration back, so it is not left among the account's devices. Best effort and
619
+ * silent: an older service (404/501), a refusal (the device already used the account, the window passed) or no network leaves
620
+ * it as before — Your devices → Sign out. → true when the service removed it. */
621
+ export async function cancelNewDevice(newSpk) {
622
+ try { const a = acctV2(); const r = await a.cancelEnrolment(newSpk); return !!(r && r.cancelled) } catch (e) {
623
+ console.warn('[link] the new device’s registration stays: ' + ((e && (e.code || e.message)) || e))
624
+ return false
625
+ }
626
+ }
627
+
608
628
  /** § 8.6 on the NEW device: the approving device registered it and sent { acct, base, address } with the account's keys.
609
629
  * This device is switched on for that service (only the service this app may use — acctV2Switch.baseOf) and reads the
610
630
  * backup through it with its own key. → { ok: true, rooms } | { ok: false, reason }; nothing kept on failure. */
@@ -797,7 +817,7 @@ export function renderAdvanced(sec, a, address, rerender, { confirm = confirmShe
797
817
  * restore goes on), { done, rooms, address } = restored, { message } = stop and show it. */
798
818
  export async function restoreFromCode(code, { service = null, signIn = null } = {}) {
799
819
  let a = acctV2()
800
- if (a.enabled() && a.state()) return null // this device already has an account on the new service
820
+ if (a.enabled() && a.state() && !(a.halfMade && a.halfMade())) return null // this device already has an account on the new service (not an older app's half-made restore — side sweep: interrupted-restore-retry)
801
821
  // A DEVICE NOT YET ON THE NEW SERVICE (a new phone, a fresh browser): once new accounts start there (the release switch,
802
822
  // acctV2Switch.newAccountService — the same rule, so every account it makes can be restored), the normal Restore asks it
803
823
  // too, switching this device on for the try and back if the code is not an account there. Without this, an account made
@@ -0,0 +1,28 @@
1
+ // agentDoorTools.js — the two tools of a Witbitz member's door (agents.witbitz.chat/mcp/<handle>), as the Sentinel lists them
2
+ // (infra/cloud-computer/sentinel/mcpDoor.mjs TOOLS, held equal by spaces/test/agentDoorTools.test.mjs). A connection whose key only
3
+ // the vault holds cannot be listed by the Sentinel ("opens only with its key now"); its tools are these, known in advance.
4
+ export const AGENT_DOOR_HOST = 'agents.witbitz.chat'
5
+ export const AGENT_DOOR_TOOLS = Object.freeze([
6
+ {
7
+ name: 'message_member',
8
+ title: 'Message the member',
9
+ description: 'Send a message to the member who gave you this connection — a question, an update, or the result of a task they gave you. It lands in their private assistant, sealed so that only their own devices can read it. This call waits up to about 45 seconds for the answer and returns it when it comes in time — an assistant that answers on its own (one kept always on) usually does. Otherwise it returns a task_id and the state; then call get_reply with that task_id later (a person may take hours). To continue the same conversation, pass the task_id you got before.',
10
+ inputSchema: { type: 'object', properties: { text: { type: 'string', description: 'What to send (plain text, up to 8,000 characters).' }, task_id: { type: 'string', description: 'Optional: an earlier task_id, to continue that conversation.' } }, required: ['text'], additionalProperties: false },
11
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
12
+ },
13
+ {
14
+ name: 'get_reply',
15
+ title: 'Get the member’s reply',
16
+ description: 'The state of a message you sent with message_member, and the member’s reply once there is one. States: waiting (not read yet), read (the member has it), question (the member asked you something back — answer with message_member and the same task_id), answered, declined, expired.',
17
+ inputSchema: { type: 'object', properties: { task_id: { type: 'string' } }, required: ['task_id'], additionalProperties: false },
18
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
19
+ },
20
+ ])
21
+
22
+ /** The member's agent advertises these two tools even before the Sentinel can read a cached list. */
23
+ export async function listGrantTools(host, list) {
24
+ try { return await list() } catch (error) {
25
+ if (host !== AGENT_DOOR_HOST || !/opens only with its key/.test(String(error?.message || error))) throw error
26
+ return { tools: AGENT_DOOR_TOOLS.map(t => ({ ...t, readOnly: t.annotations?.readOnlyHint === true })) }
27
+ }
28
+ }
package/awsKey.js CHANGED
@@ -88,7 +88,9 @@ export function awsUsageRow (st) {
88
88
  if (!Number.isFinite(usd) || !(cap > 0)) return null
89
89
  let when = ''
90
90
  try { when = st.resetsAt ? 'starts again on ' + new Date(st.resetsAt).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', timeZone: 'UTC' }) : '' } catch { when = '' }
91
- const note = [st.tier === 'free' ? 'the free allowance' : '', usd >= cap ? 'used up' : '', when].filter(Boolean).join(' · ')
91
+ // held: what a running computer may still spend — admission counts it against the cap (side sweep cloud-allowance-display-omits-active-reservations)
92
+ const held = Number(m.heldUsd) > 0 ? Number(m.heldUsd) : 0
93
+ const note = [st.tier === 'free' ? 'the free allowance' : '', held ? `${creditsText(creditsOf(held))} held by a running computer` : '', usd + held >= cap ? 'used up' : '', when].filter(Boolean).join(' · ')
92
94
  return { label: 'Cloud computers', value: `${creditsNumber(creditsOf(usd))} of ${creditsText(creditsOf(cap))}`, note } // credits (100 = $1); the key keeps dollars
93
95
  }
94
96
 
package/backupRecord.js CHANGED
@@ -30,6 +30,9 @@ export function orphanRows (recents, storageKeys, { mk, us }) {
30
30
  let rm = null
31
31
  if (k && k.indexOf(mk) === 0) rm = k.slice(mk.length)
32
32
  else if (k && k.indexOf(us) === 0) rm = k.slice(us.length)
33
+ // a TEMPORARY room (`tmp-`, roomState.isTempRoom) is never durable: a share an earlier acceptance left in storage must not
34
+ // reach the backup (side sweep: temporary-split-invite-share-enters-backup)
35
+ if (rm && rm.startsWith('tmp-')) continue
33
36
  if (rm && !listed.has(rm)) { orphans.push({ room: rm, title: '', at: 0 }); listed.add(rm) }
34
37
  }
35
38
  return orphans
package/chatLock.js CHANGED
@@ -147,3 +147,19 @@ export function wrongTryIn (doc, dev, now = Date.now()) {
147
147
  return { ...d, tries: { ...(d.tries || {}), [dev]: { fails: mine.fails + 1, at: mine.fails ? mine.at : now, next: w ? now + w : 0 } } }
148
148
  }
149
149
 
150
+
151
+ /** Act only on the listed locks. A target is complete once its removal and the lock update both succeed. */
152
+ export async function deleteLockedTargets(targets, { stillLocked, removeTarget, removeLock }) {
153
+ const outcomes = []
154
+ for (const { lockId, kind, target } of targets) {
155
+ let deleted = false
156
+ try {
157
+ if (await stillLocked(lockId, kind, target) && await removeTarget(kind, target)) {
158
+ await removeLock(lockId, kind, target)
159
+ deleted = true
160
+ }
161
+ } catch { /* record the failure and keep the other targets independent */ }
162
+ outcomes.push({ lockId, kind, target, deleted })
163
+ }
164
+ return outcomes
165
+ }
@@ -29,5 +29,5 @@
29
29
  // Rollover: cd16 first, cd15 until the switch; narrow at the next release.
30
30
  // cd17 (2026-11-25, 28779188 — PASS Rekor 4111966802): the device's trail reaches the `logs` op. cd18 (2026-11-25, 234eed2e — PASS on a
31
31
  // fresh build-enclave boot, Rekor 4112152120): a hosted sign-in acts on the hosted app's own Sentinel account (an own agent's report
32
- // came back). cd18 runs; KMS {cd18, cd17}. Devices on an older release follow cd18 by its record (followImage FOLLOW_WINDOW).
33
- export const CLOUD_DEVICE_PCR0 = Object.freeze(['8784c47385209fdf983161c3a2927a455c224000deab3395aad501e6cfd8858e6621ded7ded84193eb1f25ab5838ba84', '4e7a102e95899ac3db979f85176bed3d3fd4f8a6263e3ad474a5a49a3654fa197393de1be5acd1c30bc201c797ace849']) // cd19 and cd18 during the rollout
32
+ // came back). cd19 runs and KMS opens for cd19. Devices on an older release follow it by its record (followImage FOLLOW_WINDOW).
33
+ export const CLOUD_DEVICE_PCR0 = Object.freeze(['8784c47385209fdf983161c3a2927a455c224000deab3395aad501e6cfd8858e6621ded7ded84193eb1f25ab5838ba84']) // cd19
@@ -0,0 +1,101 @@
1
+ // spaces/public/codeAttachments.js — attachments in the Code section, the Claude Code way (docs/code-attachments.md).
2
+ //
3
+ // The connector saves every file a message carries on the computer and puts a NOTE in the message in its place; the agent
4
+ // opens the file (or its Tinfoil text copy) with its read tool when it needs it. This module is the note's one definition:
5
+ // the connector writes it, the page reads it back into chips, and the Python twin matches it through the tests.
6
+ //
7
+ // Measured on opencode 1.18.30 (2026-09-13): OpenCode refuses an Excel or Word file part for every model ("'file part media
8
+ // type …spreadsheetml.sheet' functionality not supported"); a staged text copy named in a synthetic line was read by Kimi K3
9
+ // unprompted, while DeepSeek V4 Flash first reached for the shell on the original — so the note says WHICH file to open.
10
+ // Pure: no DOM, no fs — the same module runs in the page and in Node.
11
+
12
+ const NOTE_HEAD = 'The user attached files. They are saved on this computer — open them with the read tool.'
13
+ const MAX_NAME = 100
14
+
15
+ /** A name that is safe as the last part of a path: no folders, no dot-file, only plain characters, at most 100 long. */
16
+ export function safeName(name) {
17
+ let s = String(name || '').split(/[\\/]/).pop().trim()
18
+ s = s.replace(/[^A-Za-z0-9._ ()-]+/g, '_').replace(/_+/g, '_').replace(/^\./, '_')
19
+ if (!s.replace(/[._ ]/g, '')) s = 'file' // nothing readable left (an empty or all-foreign name)
20
+ if (s.length > MAX_NAME) {
21
+ const ext = (s.match(/\.[A-Za-z0-9]{1,10}$/) || [''])[0]
22
+ s = s.slice(0, MAX_NAME - ext.length) + ext
23
+ }
24
+ return s
25
+ }
26
+
27
+ /** On disk: the first 8 hex of the content's SHA-256, then the safe name — the same bytes land on the same file. */
28
+ export const stagedFileName = (hashHex, name) => `${String(hashHex).slice(0, 8)}-${safeName(name)}`
29
+
30
+ const extOf = (name) => (String(name || '').toLowerCase().match(/\.([a-z0-9]+)$/) || [])[1] || ''
31
+ const TEXT_EXT = new Set(['txt', 'md', 'markdown', 'csv', 'tsv', 'json', 'log', 'xml', 'yaml', 'yml', 'html', 'htm', 'js', 'mjs', 'ts', 'py', 'sh', 'sql', 'ini', 'toml'])
32
+
33
+ /** A document the read tool cannot show a model (PDF, Word, Excel, slides…) gets a text copy; images and text do not. */
34
+ export function needsTextCopy(mime, name) {
35
+ const m = String(mime || '').toLowerCase()
36
+ if (m.startsWith('image/') || m.startsWith('text/') || m === 'application/json') return false
37
+ return !TEXT_EXT.has(extOf(name))
38
+ }
39
+
40
+ export function formatSize(bytes) {
41
+ const n = Number(bytes) || 0
42
+ if (n < 1024) return `${n} B`
43
+ if (n < 1024 * 1023.95) return `${(n / 1024).toFixed(1)} KB` // never "1024.0 KB"
44
+ return `${(n / 1024 / 1024).toFixed(1)} MB`
45
+ }
46
+
47
+ const SHOWN_MAX = 200 // a file name is prompt text the model reads — keep it a name, not a paragraph (review finding)
48
+ const shown = (name) => String(name || 'file').replace(/[\r\n]+/g, ' ').replace(/ — /g, ' - ').slice(0, SHOWN_MAX)
49
+ export const shownName = shown // the form a name takes in the note (codeSent.js compares a sent file's name with the note's in this form)
50
+
51
+ /**
52
+ * The note that replaces the files in the message. `entries`: {name, size, path, copy?, inline?, noCopy?} — `copy` is the
53
+ * text copy's path, `inline` means the file also rides the message (an image a model can see), `noCopy` why there is none.
54
+ */
55
+ export function attachmentNote(entries) {
56
+ const lines = [NOTE_HEAD]
57
+ for (const e of entries) {
58
+ lines.push(`• ${shown(e.name)} — ${formatSize(e.size)} — ${e.path}`)
59
+ if (e.copy) lines.push(` Its text — open THIS with the read tool, not the original: ${e.copy}`)
60
+ else if (e.inline) lines.push(' Shown to you with this message.')
61
+ else if (e.noCopy) lines.push(` No text copy (${e.noCopy}) — open it with the read tool if you can; otherwise ask the user before converting it.`)
62
+ }
63
+ return lines.join('\n')
64
+ }
65
+
66
+ /** The note back → [{name, size, session, file, copy, inline}], or null when the text is not a note. */
67
+ export function parseAttachmentNote(text) {
68
+ const lines = String(text || '').split('\n')
69
+ if (lines[0] !== NOTE_HEAD) return null
70
+ const out = []
71
+ for (const line of lines.slice(1)) {
72
+ const m = /^• (.+?) — (\d+(?:\.\d)? (?:B|KB|MB)) — (\/.+)$/.exec(line)
73
+ if (m) {
74
+ const parts = m[3].split('/')
75
+ out.push({ name: m[1], size: m[2], session: parts[parts.length - 2] || '', file: parts[parts.length - 1] || '', copy: '', inline: false })
76
+ continue
77
+ }
78
+ const last = out[out.length - 1]
79
+ if (!last) continue
80
+ const c = /^ {2}Its text — .*: (\/.+)$/.exec(line)
81
+ if (c) last.copy = c[1].split('/').pop()
82
+ else if (/^ {2}Shown to you with this message\.$/.test(line)) last.inline = true
83
+ }
84
+ return out.length ? out : null
85
+ }
86
+
87
+ /** A page's request for a staged file names a session and a staged file name — never a path. */
88
+ export function validAttachmentRef(session, file) {
89
+ return /^[A-Za-z0-9_-]{1,128}$/.test(String(session || '')) &&
90
+ /^[0-9a-f]{8}-(?!\.)[A-Za-z0-9._ ()-]{1,110}$/.test(String(file || '')) && !String(file).includes('..')
91
+ }
92
+
93
+ const MIME = { pdf: 'application/pdf', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', heic: 'image/heic',
94
+ md: 'text/markdown', txt: 'text/plain', csv: 'text/csv', json: 'application/json',
95
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xls: 'application/vnd.ms-excel',
96
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', doc: 'application/msword',
97
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }
98
+ export const mimeForFile = (file) => MIME[extOf(file)] || 'application/octet-stream'
99
+
100
+ /** The connector-owned route a page asks for a staged file on (never forwarded to OpenCode). */
101
+ export const ATTACHMENT_ROUTE = '/witbitz/attachment'
package/codeCache.js ADDED
@@ -0,0 +1,173 @@
1
+ // spaces/public/codeCache.js — the Code section's OFFLINE CACHE: the sessions you have opened, kept device-local so the
2
+ // page can show them when the computer is asleep, unpaired, or you have no network at all. The owner, 2026-09-17, after
3
+ // the Spaces airplane-mode work: "Can we make the code sessions also cache".
4
+ //
5
+ // The Code section was entirely LIVE until now — every session list and every message came off the sealed relay, so a
6
+ // computer that was not answering left the page with nothing to draw. Rooms have had this since the beginning
7
+ // (chatCache.js); this is the same idea with one difference that matters: a code transcript is far bigger than a chat.
8
+ // A single session can carry megabytes of tool output and diffs, so what is kept is capped three ways — messages per
9
+ // session, bytes per session (oldest trimmed first), and sessions per computer — and the cache is written from what the
10
+ // page ALREADY holds in memory, never by asking the computer for more.
11
+ //
12
+ // What is stored is what the page was already showing: the connector withholds secret-looking files and oversized
13
+ // patches before they ever reach the phone (codeRelay.js projectResponse), so nothing new crosses that line by being
14
+ // remembered. It is plaintext at rest on YOUR device, the same trust boundary as the room chat cache, and it is dropped
15
+ // with the rest of the app's storage on sign-out.
16
+ import { idb } from './idb.js'
17
+ import { cursorBefore } from './codeHistory.js'
18
+
19
+ const SESS = (cid, sid) => `code:sess:${cid}:${sid}`
20
+ const LIST = (cid) => `code:list:${cid}`
21
+ export const codeSessKey = SESS
22
+ export const codeListKey = LIST
23
+
24
+ export const MAX_MSGS = 150 // a long turn is a few dozen messages; 150 covers a working day of one session
25
+ export const MAX_BYTES = 1_200_000 // ~1.2 MB of JSON per session: enough for real transcripts, small enough to write often
26
+ export const MAX_SESSIONS = 20 // per computer, by last use — the history sheet shows far fewer than this
27
+ export const MAX_OUTPUT = 24_000 // per tool output / patch kept on the device
28
+
29
+ // A step's output and its patch are the heavy part, by a wide margin: codeHistory.js measured ONE real session at
30
+ // 9.7 MB over 136 messages, with a single message carrying 2.5 MB of tool output. Keeping the head of each is what
31
+ // makes a whole transcript fit — you can still read what ran and how it started, and the live copy has the rest
32
+ // whenever the computer is there. The cut is marked so the step sheet can say so rather than imply the output ended.
33
+ const clip = (s) => (typeof s === 'string' && s.length > MAX_OUTPUT ? s.slice(0, MAX_OUTPUT) : s)
34
+ export function trimMessage(m) {
35
+ if (!m || typeof m !== 'object' || !Array.isArray(m.parts)) return m
36
+ let touched = false
37
+ const parts = m.parts.map((p) => {
38
+ const st = p && p.state
39
+ const md = st && st.metadata
40
+ const big = (v) => typeof v === 'string' && v.length > MAX_OUTPUT
41
+ if (!st || !(big(st.output) || (md && (big(md.output) || big(md.diff) || (md.filediff && big(md.filediff.patch)))))) return p
42
+ touched = true
43
+ const next = { ...p, state: { ...st } }
44
+ if (big(st.output)) next.state.output = clip(st.output)
45
+ if (md) {
46
+ next.state.metadata = { ...md, wbClipped: true }
47
+ if (big(md.output)) next.state.metadata.output = clip(md.output)
48
+ if (big(md.diff)) next.state.metadata.diff = clip(md.diff)
49
+ if (md.filediff && big(md.filediff.patch)) next.state.metadata.filediff = { ...md.filediff, patch: clip(md.filediff.patch) }
50
+ } else next.state.metadata = { wbClipped: true }
51
+ return next
52
+ })
53
+ return touched ? { ...m, parts } : m
54
+ }
55
+
56
+ /** Clip each message's heavy parts, then drop messages from the FRONT until the whole thing fits: the newest are the
57
+ * ones worth keeping. */
58
+ export function trimMessages(msgs, { maxMsgs = MAX_MSGS, maxBytes = MAX_BYTES } = {}) {
59
+ let out = (Array.isArray(msgs) ? msgs.slice(-maxMsgs) : []).map(trimMessage)
60
+ while (out.length > 1) {
61
+ let size = 0
62
+ try { size = JSON.stringify(out).length } catch { return out.slice(-10) } // circular/exotic → keep a token tail
63
+ if (size <= maxBytes) break
64
+ out = out.slice(Math.max(1, Math.ceil(out.length * 0.15))) // 15% off the front per pass, so a huge tail converges fast
65
+ }
66
+ return out
67
+ }
68
+
69
+ /** Remember one session's transcript. `msgs` is the page's own message array; meta rides along for the list row. */
70
+ export async function saveSession(cid, sid, msgs, meta = {}, store = idb) {
71
+ if (!cid || !sid) return
72
+ const kept = trimMessages(msgs)
73
+ if (!kept.length) return
74
+ const trimmed = Array.isArray(msgs) && kept.length < msgs.length
75
+ // A trimmed copy pages back from its OWN oldest message: the page's cursor points before messages it no longer keeps, or is ''
76
+ // at the start, and an offline open then skipped the dropped block or could not page at all (side sweep 2026-11-28)
77
+ if (removed.has(SESS(cid, sid))) return // deleted: a save queued before the delete does not bring it back (side sweep round 2)
78
+ await store.set(SESS(cid, sid), { msgs: kept, at: Date.now(), trimmed, ...meta, ...(trimmed ? { cursor: cursorBefore(kept[0]) } : {}) })
79
+ if (removed.has(SESS(cid, sid))) await store.del(SESS(cid, sid)) // deleted while this write was on its way
80
+ }
81
+ // The sessions deleted while this page lives. A session id is never reused, so the set only grows by what was deleted here.
82
+ const removed = new Set()
83
+
84
+ /** A renamed session's saved copy takes its new title — nothing else changes (its sync time, its "trimmed"). Help reads titles
85
+ * from these copies, and kept the old name until the transcript was saved again (side sweep 2026-11-28). */
86
+ export async function retitleSession(cid, sid, title, store = idb) {
87
+ if (!cid || !sid || typeof title !== 'string') return
88
+ const c = await store.get(SESS(cid, sid))
89
+ if (c && typeof c === 'object' && Array.isArray(c.msgs)) await store.set(SESS(cid, sid), { ...c, title })
90
+ }
91
+
92
+ /** → { msgs, at, trimmed, … } or null. */
93
+ export async function clearSession(cid, sid, store = idb, strict = false) {
94
+ if (strict && cid && sid && store.delStrict) { await store.delStrict(SESS(cid, sid)); return }
95
+ if (cid && sid) await store.del(SESS(cid, sid))
96
+ }
97
+
98
+ export async function removeCachedSession(cid, sid, store = idb, local) {
99
+ if (cid && sid) removed.add(SESS(cid, sid))
100
+ await clearSession(cid, sid, store, true)
101
+ const saved = await loadList(cid, store)
102
+ if (saved?.list.some(row => row.id === sid)) {
103
+ await saveList(cid, saved.list.filter(row => row.id !== sid), store, { allowEmpty: true })
104
+ if ((await loadList(cid, store))?.list.some(row => row.id === sid)) throw new Error('The cached session directory could not be updated')
105
+ }
106
+ const raw = local?.getItem('oc.list')
107
+ if (!raw) return
108
+ const directory = JSON.parse(raw)
109
+ const entry = directory?.entries?.find(e => e.key === cid)
110
+ if (entry?.sessions?.some(row => row.id === sid)) {
111
+ entry.sessions = entry.sessions.filter(row => row.id !== sid)
112
+ local.setItem('oc.list', JSON.stringify(directory))
113
+ }
114
+ }
115
+
116
+ export async function loadSession(cid, sid, store = idb) {
117
+ if (!cid || !sid) return null
118
+ const c = await store.get(SESS(cid, sid))
119
+ if (!(c && Array.isArray(c.msgs) && c.msgs.length)) return null
120
+ // a TRIMMED copy pages back from its own oldest message — a copy saved before saveSession wrote that cursor kept the page's own
121
+ // (pointing before messages it dropped, or '' — no paging at all) (side sweep: code-trimmed-cache-stale-cursor)
122
+ return c.trimmed ? { ...c, cursor: cursorBefore(c.msgs[0]) } : c
123
+ }
124
+
125
+ /** The session LIST as the computer last gave it, so the history sheet has something to show when it is away. */
126
+ export async function saveList(cid, list, store = idb, { allowEmpty = false } = {}) {
127
+ if (!cid || !Array.isArray(list) || (!list.length && !allowEmpty)) return // never write an empty list over a good one
128
+ await store.set(LIST(cid), { list: list.slice(0, 200), at: Date.now() })
129
+ }
130
+
131
+ export async function loadList(cid, store = idb) {
132
+ if (!cid) return null
133
+ const c = await store.get(LIST(cid))
134
+ return c && Array.isArray(c.list) ? c : null
135
+ }
136
+
137
+ /** Which sessions this device is holding for a computer, newest first: [{ id, at, msgs, title, dir }]. Enough to draw a
138
+ * drawer row from, so the list survives even when the list itself was never saved. */
139
+ export async function cachedSessions(cid, store = idb) {
140
+ if (!cid) return []
141
+ const pfx = `code:sess:${cid}:`
142
+ const rows = await store.entries(pfx)
143
+ return rows
144
+ // `revert`: the session's undo point, kept with its copy — a row rebuilt from the copies alone drew an undone turn as current (side sweep: code-offline-copy-loses-undo-point)
145
+ .map(([k, v]) => ({ id: k.slice(pfx.length), at: (v && v.at) || 0, msgs: (v && Array.isArray(v.msgs) && v.msgs.length) || 0, title: (v && v.title) || '', dir: (v && v.dir) || '', ...(v && v.revert && typeof v.revert === 'object' ? { revert: v.revert } : {}) }))
146
+ .sort((a, b) => b.at - a.at)
147
+ }
148
+
149
+ /** Keep the newest MAX_SESSIONS per computer. Called after a save — cheap, and it bounds a year of use. */
150
+ export async function prune(cid, keep = MAX_SESSIONS, store = idb) {
151
+ const all = await cachedSessions(cid, store)
152
+ for (const s of all.slice(keep)) await store.del(SESS(cid, s.id))
153
+ return all.length - Math.min(all.length, keep)
154
+ }
155
+
156
+ /** Forget one computer entirely (unpaired / removed) — its transcripts have no other home to belong to. */
157
+ export async function forgetComputer(cid) {
158
+ if (!cid) return
159
+ await idb.delPrefix(`code:sess:${cid}:`)
160
+ await idb.del(LIST(cid))
161
+ }
162
+
163
+ export function slimSession(x) {
164
+ const o = { id: x.id }
165
+ for (const f of ['title', 'slug', 'directory', 'path', 'parentID', 'agent', 'projectID']) if (typeof x[f] === 'string') o[f] = x[f]
166
+ const t = x.time || {}
167
+ o.time = {}
168
+ for (const f of ['created', 'updated', 'archived']) if (typeof t[f] === 'number') o.time[f] = t[f]
169
+ // its undo point: without it an offline reopen drew an undone turn as current (side sweep 2026-11-28; read by opencodeWire normRevert)
170
+ const r = x.revert
171
+ if (r && typeof r === 'object' && typeof r.messageID === 'string' && r.messageID) o.revert = { messageID: r.messageID, ...(typeof r.partID === 'string' && r.partID ? { partID: r.partID } : {}), snapshot: !!r.snapshot }
172
+ return o
173
+ }
package/codeCloud.js CHANGED
@@ -50,7 +50,6 @@ export const CLOUD_API = 'https://api.witbitz.chat/v1/cloud-computer'
50
50
  // stop condition on its own; the check that holds is the file-by-file tarball diff.
51
51
  export const CLOUD_PCR0 = [
52
52
  '66c77a098b36a21fa4a7612ecad202ef2c8e46e34f14e9ab56a3a2a9f3108190f6d2bac14c526f501b1e0109d9605a72', // p3i, reproduced twice from c6ca1e6b
53
- '9b76ca93221300bce9ced817ea8e4a4f21edc6db1953d50deefe4360ec40247c5a6683c62be34a96cb7a5c602e236238', // p3h, currently armed on both hosts
54
53
  ]
55
54
  // The published Credential Sentinel image.
56
55
  // ★ A NEW KERNEL MOVES THIS ONE TOO, with an untouched sentinel userland: PCR0 measures kernel and ramdisk together
@@ -90,7 +89,6 @@ export const CLOUD_PCR0 = [
90
89
  // that caught the esbuild-cwd leak, and which caught nothing for four cycles because the number always moved.
91
90
  export const SENTINEL_PCR0 = [
92
91
  'aaeb3d3f64efa4f072372a7f257eaa89fd969614139ca08a8ce817ec46cd0d32cf2b4e6103b984a2b7f9d7ce3354c248', // p3i, reproduced twice from c6ca1e6b
93
- 'b6a8a6425aa579008cfa8aa91d6875912c6422b52433a55b77db22c434d04c58a02e8fddd2c8187c9e2730232dbe5c14', // p3h, currently armed on both hosts
94
92
  ]
95
93
  export const GRANT_TTL_MS = 24 * 3600_000
96
94
  export const PUSH_PATTERN = 'witbitz/*'
@@ -499,6 +497,8 @@ export async function openCloud(computer, { token, aws = null, onStep = () => {}
499
497
  if (granted.github) { try { onGitHub(granted.github) } catch { /* */ } }
500
498
  assigned = await call({ action: 'op', workspace: c.workspace, cid: opened.cid, req: { op: 'assign', sealed } })
501
499
  }
500
+ // the enclave refused the assign (host.py answers 200 { error } and throws that enclave away): not opened
501
+ if (assigned.error) throw new CloudError(`the cloud computer could not be set up (${assigned.error})`, { code: 'assign' })
502
502
  onStep('connecting')
503
503
  // ★ THE SESSION HANDLE GOES OUT THROUGH A CALLBACK, NOT THE RETURN VALUE. What openCloud RETURNS is merged into the
504
504
  // account's sealed entry, and `normCloudEntry` is an allowlist — a new field there is either dropped silently or
package/codeComputers.js CHANGED
@@ -17,6 +17,7 @@ import { normEgress } from './codeEgress.js' // what this computer may reach —
17
17
  import { gunzipB64 } from './compress.js' // a plain doc the computer wrote large arrives gzipped ({ z }) — confirmScannedComputer reads it
18
18
 
19
19
  export const COMPUTERS_KEY = 'space:computers'
20
+ export const CLOUD_PICKS_MAX_BYTES = 800_000
20
21
  export const COMPUTERS_DOC = 'computers'
21
22
 
22
23
  const ID = /^[A-Za-z0-9_-]{8,64}$/
@@ -379,6 +380,14 @@ export async function moveCloudCallKeys ({ hold, load = loadCloud, save = saveCl
379
380
  }
380
381
  export function loadCloud() { try { return normCloud(JSON.parse(localStorage.getItem(CLOUD_KEY) || 'null')) } catch { return normCloud(null) } }
381
382
  export function saveCloud(reg) { try { localStorage.setItem(CLOUD_KEY, JSON.stringify(normCloud(reg))) } catch { /* private mode */ } }
383
+ /** THE ACCOUNT'S cloud computers, for "Delete my account" (side sweep: account-erase-skips-unsynced-cloud-workspace): this device's
384
+ * list merged with the account's synced one (`readRemote()` → its state, null = none) — a workspace made on another device and not
385
+ * synced here yet got no destroy request. → { reg, unread }: `unread` when the account's list could not be read (the step is not
386
+ * done; the ones known here still go); a device with no account (`no_account`) has only its own list. */
387
+ export async function cloudForErase(readRemote) {
388
+ try { return { reg: mergeCloud(loadCloud(), await readRemote()), unread: false } }
389
+ catch (e) { return { reg: loadCloud(), unread: !(e && e.code === 'no_account') } }
390
+ }
382
391
  export function adoptCloud(remote) {
383
392
  const cur = loadCloud()
384
393
  const next = mergeCloud(cur, remote)
package/codeFolders.js ADDED
@@ -0,0 +1,116 @@
1
+ // spaces/public/codeFolders.js — "allow this folder": ONE card for a folder outside the project, for the whole conversation.
2
+ //
3
+ // The owner, with a session refused twice reading ~/witbitz-code-pub: "It should ask for permission once for the whole new
4
+ // project like the parent directory which should be enough". OpenCode asks `external_directory` for the folder of EACH file
5
+ // it reaches (`<dirname>/*`) and for each folder a command touches, so every new subfolder asked again — and Auto answered
6
+ // only "once", judging each one. Now the card names the folder the ask belongs to (its git root, or the top folder under
7
+ // home), and allowing it adds `external_directory <folder>/* allow` to the session (the connector: tools/code-folders.mjs,
8
+ // witbitz_code/folders.py). Session rules are last-match-wins and `*` crosses "/" (measured, OpenCode 1.18.30), so
9
+ // everything inside is allowed from then on — for this conversation and the subagents it starts.
10
+ //
11
+ // Pure, shared by the page, the connector and Auto (tools/code-auto.mjs); the Python twin answers the same
12
+ // (tools/code-folders.vectors.json).
13
+ export const FOLDER_ROUTE = '/witbitz/folder'
14
+
15
+ const SYSTEM = ['/bin', '/boot', '/dev', '/etc', '/lib', '/lib32', '/lib64', '/libx32', '/proc', '/root', '/run', '/sbin', '/sys', '/usr', '/var']
16
+ const SECRET_PARTS = new Set(['.ssh', '.aws', '.gnupg', '.kube', '.docker', '.git'])
17
+ const GLOB = /[*?[\]{}]/
18
+
19
+ /** posix.normalize for absolute paths, without node:path (this module also runs in the browser). '' when not absolute. */
20
+ export function normAbs(p) {
21
+ if (typeof p !== 'string' || !p.startsWith('/') || p.includes('\0')) return ''
22
+ const out = []
23
+ for (const part of p.split('/')) {
24
+ if (!part || part === '.') continue
25
+ if (part === '..') out.pop(); else out.push(part)
26
+ }
27
+ return '/' + out.join('/')
28
+ }
29
+ const under = (p, root) => root === '/' ? p.startsWith('/') : p === root || p.startsWith(root + '/')
30
+
31
+ /**
32
+ * The folder an outside path belongs to — what "allow this folder" allows. null when it must not be widened: the home
33
+ * folder itself, "/", a system folder, a secret store, or a hidden folder right under home (~/.config, ~/.local…).
34
+ * dir the directory OpenCode asked for (a pattern's `<dir>` of `<dir>/*`)
35
+ * home this computer's home directory
36
+ * hasGit (path) => whether `path/.git` exists — the nearest one below home (or anywhere, outside home) is the root
37
+ */
38
+ export function folderRoot(dir, { home = '', hasGit = () => false } = {}) {
39
+ const d = normAbs(dir)
40
+ const h = normAbs(home) === '/' ? '' : normAbs(home) // a home of "/" is no home to go by
41
+ if (!d || d === '/' || (h && d === h) || GLOB.test(d)) return null
42
+ if (d.split('/').some((part) => SECRET_PARTS.has(part))) return null
43
+ if (SYSTEM.some((s) => under(d, s))) return null
44
+ if (h && under(h, d)) return null // an ancestor of home holds home
45
+ const inHome = !!h && under(d, h)
46
+ if (inHome && d.slice(h.length + 1).startsWith('.')) return null
47
+ // the nearest git root — never home or /tmp themselves, or above them (a stray /tmp/.git must not swallow every temp folder)
48
+ for (let p = d; p !== '/' && !(h && p === h) && p !== '/tmp'; p = p.slice(0, p.lastIndexOf('/')) || '/') {
49
+ if (inHome && !under(p, h)) break
50
+ let git = false
51
+ try { git = !!hasGit(p) } catch { git = false }
52
+ if (git) return p
53
+ }
54
+ if (inHome) return h + '/' + d.slice(h.length + 1).split('/')[0]
55
+ if (under(d, '/tmp')) return d === '/tmp' ? '/tmp' : '/tmp/' + d.slice(5).split('/')[0]
56
+ return d
57
+ }
58
+
59
+ /** The directories an external_directory ask names: its patterns' `<dir>` of `<dir>/*`. null when any is not that shape. */
60
+ export function askDirs(ask) {
61
+ const pats = ask && Array.isArray(ask.patterns) ? ask.patterns : []
62
+ if (!pats.length) return null
63
+ const dirs = []
64
+ for (const p of pats) {
65
+ if (typeof p !== 'string' || !p.endsWith('/*')) return null
66
+ const d = normAbs(p.slice(0, -2))
67
+ if (!d || GLOB.test(p.slice(0, -2))) return null
68
+ dirs.push(d)
69
+ }
70
+ return dirs
71
+ }
72
+
73
+ /** The folders to allow for an ask — one per distinct root, in order; null when any of its directories cannot be widened. */
74
+ export function foldersForAsk(ask, opts) {
75
+ if (!ask || ask.permission !== 'external_directory') return null
76
+ const dirs = askDirs(ask)
77
+ if (!dirs) return null
78
+ const roots = []
79
+ for (const d of dirs) {
80
+ const r = folderRoot(d, opts)
81
+ if (!r) return null
82
+ if (!roots.includes(r)) roots.push(r)
83
+ }
84
+ return roots
85
+ }
86
+
87
+ /** The rule that allows a folder. */
88
+ export const folderRule = (root) => ({ permission: 'external_directory', pattern: root + '/*', action: 'allow' })
89
+
90
+ /** The folders a session's rules allow outside its project: every `external_directory <abs>/*` whose LAST matching rule of
91
+ * that exact pattern allows (OpenCode's last-match-wins). */
92
+ export function allowedFolders(rules) {
93
+ const last = new Map()
94
+ for (const r of Array.isArray(rules) ? rules : []) {
95
+ if (!r || r.permission !== 'external_directory' || typeof r.pattern !== 'string' || !r.pattern.endsWith('/*')) continue
96
+ last.set(r.pattern, r.action)
97
+ }
98
+ const out = []
99
+ for (const [pattern, action] of last) {
100
+ const d = normAbs(pattern.slice(0, -2))
101
+ if (action === 'allow' && d && d !== '/' && !GLOB.test(pattern.slice(0, -2)) && !out.includes(d)) out.push(d)
102
+ }
103
+ return out
104
+ }
105
+
106
+ /** Is the absolute path inside one of the folders? */
107
+ export const insideFolders = (abs, folders) => { const a = normAbs(abs); return !!a && (Array.isArray(folders) ? folders : []).some((f) => { const r = normAbs(f); return !!r && r !== '/' && under(a, r) }) }
108
+
109
+ /** Does an external_directory ask fall entirely inside allowed folders? */
110
+ export function foldersCover(ask, folders) {
111
+ const dirs = askDirs(ask)
112
+ return !!dirs && dirs.every((d) => insideFolders(d, folders))
113
+ }
114
+
115
+ /** "~/witbitz-code-pub" for the card. */
116
+ export const displayPath = (p, home) => { const h = normAbs(home); return h && h !== '/' && under(p, h) ? '~' + p.slice(h.length) : p }