@witbitz/sdk 4.3.0 → 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/README.md +2 -2
- package/a2aCore.js +26 -5
- package/accountErase.js +6 -1
- package/accountRecord.js +2 -2
- package/agentDoorTools.js +28 -0
- package/chatLock.js +16 -0
- package/cloudDevicePins.js +2 -2
- package/codeAttachments.js +100 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +0 -2
- package/codeComputers.js +1 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeModes.js +2 -0
- package/codeProgress.js +54 -0
- package/codeSent.js +68 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +22 -0
- package/connections.js +17 -18
- package/deviceAttest.js +9 -3
- package/idb.js +19 -3
- package/jobAgents.js +2 -2
- package/keptMerge.js +9 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +93 -30
- package/laneAssociation.js +68 -0
- package/laneConfig.js +4 -3
- package/manifest.json +80 -61
- package/memberChange.js +4 -2
- package/mirrorBatch.js +47 -0
- package/opRouting.js +10 -0
- package/package.json +21 -2
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/protectedLocal.js +18 -2
- package/removedMessage.js +1 -1
- package/roomEmbed.js +111 -0
- package/roomName.js +1 -1
- package/roomRoster.js +21 -5
- package/rosterCount.js +6 -3
- package/sdkA2A.js +160 -40
- package/sdkAccount.js +17 -4
- package/sdkAccountDoc.js +11 -3
- package/sdkAccountSections.js +117 -8
- package/sdkBackup.js +35 -8
- package/sdkCloudDevice.js +8 -2
- package/sdkComputers.js +582 -53
- package/sdkDictation.js +114 -24
- package/sdkErase.js +9 -4
- package/sdkExports.js +4 -2
- package/sdkLaneLink.js +3 -3
- package/sdkPlan.js +4 -2
- package/sdkRekey.js +50 -17
- package/sdkReport.js +1 -1
- package/sdkSafeMedia.js +1 -1
- package/sdkSpeech.js +19 -2
- package/sdkTemporaryRooms.js +123 -0
- package/sdkVault.js +66 -10
- package/sentinelRelease.js +1 -0
- package/sharedViews.js +17 -3
- package/siri.js +114 -7
- package/spaceClient.js +16 -5
- package/spaceEmailGate.js +2 -2
- package/spaceTemplates.js +99 -0
- package/speechOut.js +4 -2
- package/store.js +83 -14
- package/sw-notif-core.js +9 -7
- package/turnVerdict.js +1 -0
- package/vault-core.js +480 -112
- package/vault-kit.mjs +2 -2
- package/vault-screens.js +5 -7
- package/vaultAtRest.js +35 -4
- package/vaultKeep.js +9 -3
- package/vaultWorkerHost.js +23 -4
- package/witbitz-admin.mjs +12 -11
- package/witbitz-sdk.d.ts +115 -24
- package/witbitz-sdk.js +572 -149
package/README.md
CHANGED
|
@@ -16,6 +16,6 @@ The guide: https://witbitz.chat/docs/sdk
|
|
|
16
16
|
|
|
17
17
|
## The same bytes as the hosted release
|
|
18
18
|
|
|
19
|
-
Version 4.
|
|
20
|
-
`
|
|
19
|
+
Version 4.4.0 of this package is the release folder https://witbitz.chat/sdk/4.4.0/ unchanged (from commit
|
|
20
|
+
`ab2472bedd442be2662fdf540a3175fd54ed1ad0`), plus this README, `package.json` and `LICENSE`. Its `manifest.json` lists the sha384 of every file; each file in the
|
|
21
21
|
package matches it.
|
package/a2aCore.js
CHANGED
|
@@ -11,6 +11,7 @@ export const MAX_LANES = 32, MAX_PEERS = 32
|
|
|
11
11
|
// THE SENTINEL TAKES 16 (infra/cloud-computer/sentinel/a2a.mjs LANES_MAX): a 17th lane made here could never be pushed — the whole
|
|
12
12
|
// record was refused, every lane with it. MAX_LANES stays what a stored copy may hold; a NEW lane stops at this one (2026-11-23).
|
|
13
13
|
export const SENTINEL_LANES_MAX = 16
|
|
14
|
+
const validConnectionId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value)
|
|
14
15
|
const laneErr = (code, m) => Object.assign(new Error(m), { code })
|
|
15
16
|
const ROOM = /^[A-Za-z0-9_:.-]{4,120}$/, HANDLE = /^[A-Za-z0-9_-]{16,43}$/, COORD = /^[A-Za-z0-9_-]{43}$/
|
|
16
17
|
const b64u = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
@@ -54,7 +55,7 @@ export function normA2A (o) {
|
|
|
54
55
|
if (!pub || !COORD.test(String(pub.x)) || !COORD.test(String(pub.y)) || (!held && (!priv || !COORD.test(String(priv.d))))) continue
|
|
55
56
|
const removed = marks(l.removed, (id) => PEER_ID.test(id))
|
|
56
57
|
const peers = (Array.isArray(l.peers) ? l.peers : []).filter((p) => p && PEER_ID.test(String(p.id)) && !removed[String(p.id)] && /^[A-Za-z0-9+/]{43}=$/.test(String(p.tokenHash))).slice(0, MAX_PEERS)
|
|
57
|
-
.map((p) => ({ id: String(p.id), name: String(p.name || '').slice(0, 80), tokenHash: String(p.tokenHash), reply: p.reply === 'auto' ? 'auto' : 'ask', created: Number(p.created) || 0, ...(p.job === true ? { job: true } : {}), ...(p.own === true ? { own: true } : {}) }))
|
|
58
|
+
.map((p) => ({ id: String(p.id), name: String(p.name || '').slice(0, 80), tokenHash: String(p.tokenHash), reply: p.reply === 'auto' ? 'auto' : 'ask', ...(Number(p.replyAt) > 0 ? { replyAt: Number(p.replyAt) } : {}), created: Number(p.created) || 0, ...(p.job === true ? { job: true, ...(validConnectionId(p.connectionId) ? { connectionId: p.connectionId } : {}) } : {}), ...(p.own === true ? { own: true } : {}) }))
|
|
58
59
|
lanes[room] = { handle: String(l.handle), name: String(l.name || '').slice(0, 80), description: String(l.description || '').slice(0, 280), pub: { x: pub.x, y: pub.y }, ...(held ? { held: 1 } : { priv: { kty: 'EC', crv: 'P-256', x: pub.x, y: pub.y, d: priv.d } }), peers, ...(Object.keys(removed).length ? { removed } : {}), ...(Number(l.at) > 0 ? { at: Number(l.at) } : {}) }
|
|
59
60
|
}
|
|
60
61
|
return { lanes, ...(Object.keys(gone).length ? { gone } : {}) }
|
|
@@ -103,20 +104,23 @@ export const newPeerToken = () => 'a2a_' + rnd(32)
|
|
|
103
104
|
const TOKEN_HASH = /^[A-Za-z0-9+/]{43}=$/
|
|
104
105
|
/** Let one outside agent in → { id, token } — the token exists only here; only its hash is kept. With `tokenHash` (a token minted
|
|
105
106
|
* ELSEWHERE — the hosted app's vault, which shows it on its own screen) no token is made here: → { id, token: '' }. */
|
|
106
|
-
export async function addPeerIn (s, room, name, { reply = 'ask', job = false, own = false, tokenHash = '' } = {}, err) {
|
|
107
|
+
export async function addPeerIn (s, room, name, { reply = 'ask', job = false, own = false, connectionId, tokenHash = '' } = {}, err) {
|
|
107
108
|
const l = s.lanes[room]
|
|
108
109
|
if (!l) throw err('not_enabled', 'let outside agents reach this lane first')
|
|
109
110
|
const n = String(name || '').trim(); if (!n) throw err('name_required', 'name the agent you are letting in')
|
|
110
111
|
if (l.peers.length >= MAX_PEERS) throw err('too_many', `at most ${MAX_PEERS} agents per lane`)
|
|
111
112
|
if (tokenHash && !TOKEN_HASH.test(String(tokenHash))) throw err('bad_token', 'the agent\'s key could not be made')
|
|
113
|
+
if (connectionId !== undefined && (!job || !validConnectionId(connectionId))) throw err('invalid_argument', 'Choose a valid connection ID for a job peer.')
|
|
112
114
|
const token = tokenHash ? '' : newPeerToken(), id = 'p_' + rnd(9)
|
|
113
|
-
l.peers.push({ id, name: n.slice(0, 80), ...(tokenHash ? { tokenHash } : { tokenHash: await a2aTokenHash(token) }), reply: reply === 'auto' ? 'auto' : 'ask', created: Date.now(), ...(job === true ? { job: true } : {}), ...(own === true ? { own: true } : {}) })
|
|
115
|
+
l.peers.push({ id, name: n.slice(0, 80), ...(tokenHash ? { tokenHash } : { tokenHash: await a2aTokenHash(token) }), reply: reply === 'auto' ? 'auto' : 'ask', created: Date.now(), ...(job === true ? { job: true, ...(connectionId ? { connectionId } : {}) } : {}), ...(own === true ? { own: true } : {}) })
|
|
114
116
|
return { id, token }
|
|
115
117
|
}
|
|
116
118
|
export function setPeerReplyIn (s, room, id, reply, err) {
|
|
117
119
|
const p = s.lanes[room] && s.lanes[room].peers.find((x) => x.id === id)
|
|
118
120
|
if (!p) throw err('unknown_peer', 'no such agent on this lane')
|
|
119
|
-
|
|
121
|
+
const next = reply === 'auto' ? 'auto' : 'ask'
|
|
122
|
+
if (p.reply !== next) { p.reply = next; p.replyAt = Math.max(Date.now(), (p.replyAt || 0) + 1) }
|
|
123
|
+
return p.reply
|
|
120
124
|
}
|
|
121
125
|
export function removePeerIn (s, room, id) {
|
|
122
126
|
if (!s.lanes[room]) return false
|
|
@@ -139,7 +143,7 @@ export const peersOf = (s, room) => (s.lanes[room] ? s.lanes[room].peers.map(({
|
|
|
139
143
|
|
|
140
144
|
// ── the Sentinel ──
|
|
141
145
|
/** What the Sentinel takes (a2a.mjs grant): PUBLIC halves and token hashes only. */
|
|
142
|
-
export const recordFor = (s, account) => ({ account, lanes: Object.entries(s.lanes).map(([room, l]) => ({ handle: l.handle, room, name: l.name, description: l.description, inboxPub: { x: l.pub.x, y: l.pub.y }, peers: l.peers.map(({ own, ...p }) => p) })) }) // `own` stays the account's: the Sentinel needs none of it
|
|
146
|
+
export const recordFor = (s, account) => ({ account, lanes: Object.entries(s.lanes).map(([room, l]) => ({ handle: l.handle, room, name: l.name, description: l.description, inboxPub: { x: l.pub.x, y: l.pub.y }, peers: l.peers.map(({ own, connectionId, replyAt, ...p }) => p) })) }) // `own` stays the account's: the Sentinel needs none of it
|
|
143
147
|
/** sealed(mode, obj): attest the standing Sentinel, seal `obj` to it. plain(mode, extra): the unsealed ops. `err(kind, message, r)`
|
|
144
148
|
* — kind 'refused' | 'unreachable' — lets each side keep its own codes. */
|
|
145
149
|
export function sentinelCalls ({ post, auth = {}, attest, seal, err }) {
|
|
@@ -198,3 +202,20 @@ export const A2A_COLLECT_WINDOW_MS = 45_000
|
|
|
198
202
|
|
|
199
203
|
/** A reply to a task the peer already finished: "done", not a failure — ONE test for the app (a2aLane.js) and the SDK (sdkA2A.js). */
|
|
200
204
|
export const finishedTask = (e) => /already finished|task is finished/i.test(String((e && (e.message || e.error)) || e))
|
|
205
|
+
|
|
206
|
+
export function applyRemovals(record, removals) {
|
|
207
|
+
let changed = false
|
|
208
|
+
for (const [room, handle, id] of removals) {
|
|
209
|
+
if (record.lanes[room]?.handle !== handle) continue
|
|
210
|
+
changed = (id ? removePeerIn(record, room, id) : disableLaneIn(record, room)) || changed
|
|
211
|
+
}
|
|
212
|
+
return changed
|
|
213
|
+
}
|
|
214
|
+
export function removalIntents(base, candidate) {
|
|
215
|
+
const intents = []
|
|
216
|
+
for (const [room, lane] of Object.entries(base.lanes)) {
|
|
217
|
+
if (candidate.gone?.[lane.handle]) intents.push([room, lane.handle, ''])
|
|
218
|
+
else for (const peer of lane.peers) if (candidate.lanes[room]?.removed?.[peer.id]) intents.push([room, lane.handle, peer.id])
|
|
219
|
+
}
|
|
220
|
+
return intents
|
|
221
|
+
}
|
package/accountErase.js
CHANGED
|
@@ -218,6 +218,11 @@ export async function eraseAccount (d) {
|
|
|
218
218
|
if (queuedOnly(r)) await confirmQueued(d, [d.indexRoom], rep, say) // the index holds the account key: confirmed before the wipe (9·S#1)
|
|
219
219
|
else if (deletionConfirmed(r)) rep.deleted.push(d.indexRoom); else if (r.status === 404) rep.lapsing.push(d.indexRoom); else rep.failed.push({ room: d.indexRoom, why: 'delete ' + (r.status || 'unreachable') })
|
|
220
220
|
}
|
|
221
|
-
if (!rep.failed.length) {
|
|
221
|
+
if (!rep.failed.length) {
|
|
222
|
+
try {
|
|
223
|
+
if (await d.wipe() === false) throw new Error('Device cleanup is pending. Close other Spaces windows to finish.')
|
|
224
|
+
say('Done.')
|
|
225
|
+
} catch (error) { rep.failed.push({ what: 'device cleanup', why: String(error.message || error) }) }
|
|
226
|
+
}
|
|
222
227
|
return rep
|
|
223
228
|
}
|
package/accountRecord.js
CHANGED
|
@@ -54,7 +54,7 @@ export function recordFromRooms ({ rooms = [], tomb, email, inviteKey, indexRoom
|
|
|
54
54
|
for (const r of rooms) {
|
|
55
55
|
if (!r || !r.room || !r.link) continue
|
|
56
56
|
recents.push({ room: r.room, title: r.label || '', ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), at: r.at || 0, ...roomPin(r), link: r.link, kind: r.kind === 'lane' ? 'lane' : 'space',
|
|
57
|
-
...(r.shared ? { shared: r.shared } : {}), ...(r.archived ? { archived: true } : {}) })
|
|
57
|
+
...(r.shared ? { shared: r.shared } : {}), ...(r.mintedFor ? { mintedFor: r.mintedFor } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), ...(r.archived ? { archived: true } : {}) })
|
|
58
58
|
const mk = keyInLink(r.link) || r.mk // the link's own key first: a separate copy of a plain room's key may be stale
|
|
59
59
|
if (mk) keys[r.room] = { mk }
|
|
60
60
|
}
|
|
@@ -72,7 +72,7 @@ export function roomsOfRecord (doc) {
|
|
|
72
72
|
if (!Array.isArray(doc.recents)) return []
|
|
73
73
|
const keys = doc.keys && typeof doc.keys === 'object' ? doc.keys : {}
|
|
74
74
|
return doc.recents.filter((r) => r && r.room && r.link).map((r) => ({
|
|
75
|
-
room: r.room, ...roomPin(r), ...(r.at ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), link: r.link,
|
|
75
|
+
room: r.room, ...roomPin(r), ...(r.mintedFor ? { mintedFor: r.mintedFor } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), ...(r.at ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), link: r.link,
|
|
76
76
|
kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.title ? { label: r.title } : {}), ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), ...(r.shared ? { shared: r.shared } : {}),
|
|
77
77
|
...(keys[r.room] && keys[r.room].mk && !keyInLink(r.link) ? { mk: keys[r.room].mk } : {}),
|
|
78
78
|
}))
|
|
@@ -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/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
|
+
}
|
package/cloudDevicePins.js
CHANGED
|
@@ -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).
|
|
33
|
-
export const CLOUD_DEVICE_PCR0 = Object.freeze(['8784c47385209fdf983161c3a2927a455c224000deab3395aad501e6cfd8858e6621ded7ded84193eb1f25ab5838ba84'
|
|
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,100 @@
|
|
|
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
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The note that replaces the files in the message. `entries`: {name, size, path, copy?, inline?, noCopy?} — `copy` is the
|
|
52
|
+
* text copy's path, `inline` means the file also rides the message (an image a model can see), `noCopy` why there is none.
|
|
53
|
+
*/
|
|
54
|
+
export function attachmentNote(entries) {
|
|
55
|
+
const lines = [NOTE_HEAD]
|
|
56
|
+
for (const e of entries) {
|
|
57
|
+
lines.push(`• ${shown(e.name)} — ${formatSize(e.size)} — ${e.path}`)
|
|
58
|
+
if (e.copy) lines.push(` Its text — open THIS with the read tool, not the original: ${e.copy}`)
|
|
59
|
+
else if (e.inline) lines.push(' Shown to you with this message.')
|
|
60
|
+
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.`)
|
|
61
|
+
}
|
|
62
|
+
return lines.join('\n')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The note back → [{name, size, session, file, copy, inline}], or null when the text is not a note. */
|
|
66
|
+
export function parseAttachmentNote(text) {
|
|
67
|
+
const lines = String(text || '').split('\n')
|
|
68
|
+
if (lines[0] !== NOTE_HEAD) return null
|
|
69
|
+
const out = []
|
|
70
|
+
for (const line of lines.slice(1)) {
|
|
71
|
+
const m = /^• (.+?) — (\d+(?:\.\d)? (?:B|KB|MB)) — (\/.+)$/.exec(line)
|
|
72
|
+
if (m) {
|
|
73
|
+
const parts = m[3].split('/')
|
|
74
|
+
out.push({ name: m[1], size: m[2], session: parts[parts.length - 2] || '', file: parts[parts.length - 1] || '', copy: '', inline: false })
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
const last = out[out.length - 1]
|
|
78
|
+
if (!last) continue
|
|
79
|
+
const c = /^ {2}Its text — .*: (\/.+)$/.exec(line)
|
|
80
|
+
if (c) last.copy = c[1].split('/').pop()
|
|
81
|
+
else if (/^ {2}Shown to you with this message\.$/.test(line)) last.inline = true
|
|
82
|
+
}
|
|
83
|
+
return out.length ? out : null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A page's request for a staged file names a session and a staged file name — never a path. */
|
|
87
|
+
export function validAttachmentRef(session, file) {
|
|
88
|
+
return /^[A-Za-z0-9_-]{1,128}$/.test(String(session || '')) &&
|
|
89
|
+
/^[0-9a-f]{8}-(?!\.)[A-Za-z0-9._ ()-]{1,110}$/.test(String(file || '')) && !String(file).includes('..')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const MIME = { pdf: 'application/pdf', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', heic: 'image/heic',
|
|
93
|
+
md: 'text/markdown', txt: 'text/plain', csv: 'text/csv', json: 'application/json',
|
|
94
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xls: 'application/vnd.ms-excel',
|
|
95
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', doc: 'application/msword',
|
|
96
|
+
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }
|
|
97
|
+
export const mimeForFile = (file) => MIME[extOf(file)] || 'application/octet-stream'
|
|
98
|
+
|
|
99
|
+
/** The connector-owned route a page asks for a staged file on (never forwarded to OpenCode). */
|
|
100
|
+
export const ATTACHMENT_ROUTE = '/witbitz/attachment'
|
package/codeCache.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
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
|
+
|
|
18
|
+
const SESS = (cid, sid) => `code:sess:${cid}:${sid}`
|
|
19
|
+
const LIST = (cid) => `code:list:${cid}`
|
|
20
|
+
export const codeSessKey = SESS
|
|
21
|
+
export const codeListKey = LIST
|
|
22
|
+
|
|
23
|
+
export const MAX_MSGS = 150 // a long turn is a few dozen messages; 150 covers a working day of one session
|
|
24
|
+
export const MAX_BYTES = 1_200_000 // ~1.2 MB of JSON per session: enough for real transcripts, small enough to write often
|
|
25
|
+
export const MAX_SESSIONS = 20 // per computer, by last use — the history sheet shows far fewer than this
|
|
26
|
+
export const MAX_OUTPUT = 24_000 // per tool output / patch kept on the device
|
|
27
|
+
|
|
28
|
+
// A step's output and its patch are the heavy part, by a wide margin: codeHistory.js measured ONE real session at
|
|
29
|
+
// 9.7 MB over 136 messages, with a single message carrying 2.5 MB of tool output. Keeping the head of each is what
|
|
30
|
+
// makes a whole transcript fit — you can still read what ran and how it started, and the live copy has the rest
|
|
31
|
+
// whenever the computer is there. The cut is marked so the step sheet can say so rather than imply the output ended.
|
|
32
|
+
const clip = (s) => (typeof s === 'string' && s.length > MAX_OUTPUT ? s.slice(0, MAX_OUTPUT) : s)
|
|
33
|
+
export function trimMessage(m) {
|
|
34
|
+
if (!m || typeof m !== 'object' || !Array.isArray(m.parts)) return m
|
|
35
|
+
let touched = false
|
|
36
|
+
const parts = m.parts.map((p) => {
|
|
37
|
+
const st = p && p.state
|
|
38
|
+
const md = st && st.metadata
|
|
39
|
+
const big = (v) => typeof v === 'string' && v.length > MAX_OUTPUT
|
|
40
|
+
if (!st || !(big(st.output) || (md && (big(md.output) || big(md.diff) || (md.filediff && big(md.filediff.patch)))))) return p
|
|
41
|
+
touched = true
|
|
42
|
+
const next = { ...p, state: { ...st } }
|
|
43
|
+
if (big(st.output)) next.state.output = clip(st.output)
|
|
44
|
+
if (md) {
|
|
45
|
+
next.state.metadata = { ...md, wbClipped: true }
|
|
46
|
+
if (big(md.output)) next.state.metadata.output = clip(md.output)
|
|
47
|
+
if (big(md.diff)) next.state.metadata.diff = clip(md.diff)
|
|
48
|
+
if (md.filediff && big(md.filediff.patch)) next.state.metadata.filediff = { ...md.filediff, patch: clip(md.filediff.patch) }
|
|
49
|
+
} else next.state.metadata = { wbClipped: true }
|
|
50
|
+
return next
|
|
51
|
+
})
|
|
52
|
+
return touched ? { ...m, parts } : m
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Clip each message's heavy parts, then drop messages from the FRONT until the whole thing fits: the newest are the
|
|
56
|
+
* ones worth keeping. */
|
|
57
|
+
export function trimMessages(msgs, { maxMsgs = MAX_MSGS, maxBytes = MAX_BYTES } = {}) {
|
|
58
|
+
let out = (Array.isArray(msgs) ? msgs.slice(-maxMsgs) : []).map(trimMessage)
|
|
59
|
+
while (out.length > 1) {
|
|
60
|
+
let size = 0
|
|
61
|
+
try { size = JSON.stringify(out).length } catch { return out.slice(-10) } // circular/exotic → keep a token tail
|
|
62
|
+
if (size <= maxBytes) break
|
|
63
|
+
out = out.slice(Math.max(1, Math.ceil(out.length * 0.15))) // 15% off the front per pass, so a huge tail converges fast
|
|
64
|
+
}
|
|
65
|
+
return out
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Remember one session's transcript. `msgs` is the page's own message array; meta rides along for the list row. */
|
|
69
|
+
export async function saveSession(cid, sid, msgs, meta = {}, store = idb) {
|
|
70
|
+
if (!cid || !sid) return
|
|
71
|
+
const kept = trimMessages(msgs)
|
|
72
|
+
if (!kept.length) return
|
|
73
|
+
await store.set(SESS(cid, sid), { msgs: kept, at: Date.now(), trimmed: Array.isArray(msgs) && kept.length < msgs.length, ...meta })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** → { msgs, at, trimmed, … } or null. */
|
|
77
|
+
export async function clearSession(cid, sid, store = idb, strict = false) {
|
|
78
|
+
if (strict && cid && sid && store.delStrict) { await store.delStrict(SESS(cid, sid)); return }
|
|
79
|
+
if (cid && sid) await store.del(SESS(cid, sid))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function removeCachedSession(cid, sid, store = idb, local) {
|
|
83
|
+
await clearSession(cid, sid, store, true)
|
|
84
|
+
const saved = await loadList(cid, store)
|
|
85
|
+
if (saved?.list.some(row => row.id === sid)) {
|
|
86
|
+
await saveList(cid, saved.list.filter(row => row.id !== sid), store, { allowEmpty: true })
|
|
87
|
+
if ((await loadList(cid, store))?.list.some(row => row.id === sid)) throw new Error('The cached session directory could not be updated')
|
|
88
|
+
}
|
|
89
|
+
const raw = local?.getItem('oc.list')
|
|
90
|
+
if (!raw) return
|
|
91
|
+
const directory = JSON.parse(raw)
|
|
92
|
+
const entry = directory?.entries?.find(e => e.key === cid)
|
|
93
|
+
if (entry?.sessions?.some(row => row.id === sid)) {
|
|
94
|
+
entry.sessions = entry.sessions.filter(row => row.id !== sid)
|
|
95
|
+
local.setItem('oc.list', JSON.stringify(directory))
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function loadSession(cid, sid, store = idb) {
|
|
100
|
+
if (!cid || !sid) return null
|
|
101
|
+
const c = await store.get(SESS(cid, sid))
|
|
102
|
+
return c && Array.isArray(c.msgs) && c.msgs.length ? c : null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The session LIST as the computer last gave it, so the history sheet has something to show when it is away. */
|
|
106
|
+
export async function saveList(cid, list, store = idb, { allowEmpty = false } = {}) {
|
|
107
|
+
if (!cid || !Array.isArray(list) || (!list.length && !allowEmpty)) return // never write an empty list over a good one
|
|
108
|
+
await store.set(LIST(cid), { list: list.slice(0, 200), at: Date.now() })
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function loadList(cid, store = idb) {
|
|
112
|
+
if (!cid) return null
|
|
113
|
+
const c = await store.get(LIST(cid))
|
|
114
|
+
return c && Array.isArray(c.list) ? c : null
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Which sessions this device is holding for a computer, newest first: [{ id, at, msgs, title, dir }]. Enough to draw a
|
|
118
|
+
* drawer row from, so the list survives even when the list itself was never saved. */
|
|
119
|
+
export async function cachedSessions(cid, store = idb) {
|
|
120
|
+
if (!cid) return []
|
|
121
|
+
const pfx = `code:sess:${cid}:`
|
|
122
|
+
const rows = await store.entries(pfx)
|
|
123
|
+
return rows
|
|
124
|
+
.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) || '' }))
|
|
125
|
+
.sort((a, b) => b.at - a.at)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Keep the newest MAX_SESSIONS per computer. Called after a save — cheap, and it bounds a year of use. */
|
|
129
|
+
export async function prune(cid, keep = MAX_SESSIONS, store = idb) {
|
|
130
|
+
const all = await cachedSessions(cid, store)
|
|
131
|
+
for (const s of all.slice(keep)) await store.del(SESS(cid, s.id))
|
|
132
|
+
return all.length - Math.min(all.length, keep)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Forget one computer entirely (unpaired / removed) — its transcripts have no other home to belong to. */
|
|
136
|
+
export async function forgetComputer(cid) {
|
|
137
|
+
if (!cid) return
|
|
138
|
+
await idb.delPrefix(`code:sess:${cid}:`)
|
|
139
|
+
await idb.del(LIST(cid))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function slimSession(x) {
|
|
143
|
+
const o = { id: x.id }
|
|
144
|
+
for (const f of ['title', 'slug', 'directory', 'path', 'parentID', 'agent', 'projectID']) if (typeof x[f] === 'string') o[f] = x[f]
|
|
145
|
+
const t = x.time || {}
|
|
146
|
+
o.time = {}
|
|
147
|
+
for (const f of ['created', 'updated', 'archived']) if (typeof t[f] === 'number') o.time[f] = t[f]
|
|
148
|
+
return o
|
|
149
|
+
}
|
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/*'
|
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}$/
|
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 }
|