@vibedev-si/dsh-island 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,68 @@
1
+ const DAILY_FIELDS = {
2
+ todayTotal: 'today_tokens',
3
+ todayInput: 'today_input_tokens',
4
+ todayOutput: 'today_output_tokens',
5
+ todayRequests: 'today_requests',
6
+ todayCacheRead: 'today_cache_read_tokens',
7
+ todayCacheWrite: 'today_cache_creation_tokens',
8
+ }
9
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
10
+ const isCount = (value) => Number.isSafeInteger(value) && value >= 0
11
+
12
+ function balanceOf(input) {
13
+ if (!isRecord(input)) return undefined
14
+ const { amount, currency } = input
15
+ if (typeof amount !== 'string' || amount.length > 64 || !/^-?\d+(?:\.\d+)?$/.test(amount)) return undefined
16
+ if (typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency)) return undefined
17
+ return { amount, currency }
18
+ }
19
+
20
+ /** Validate a standalone snapshot and copy only the display fields to the native bridge. */
21
+ export function normalizeAccountUsage(input) {
22
+ if (!isRecord(input)) return undefined
23
+ const usage = {}
24
+ if (Object.hasOwn(input, 'balance')) {
25
+ const balance = balanceOf(input.balance)
26
+ if (balance === undefined) return undefined
27
+ usage.balance = balance
28
+ }
29
+ for (const key of Object.keys(DAILY_FIELDS)) {
30
+ if (!Object.hasOwn(input, key)) continue
31
+ const count = input[key]
32
+ if (!isCount(count)) return undefined
33
+ usage[key] = count === 0 ? 0 : count
34
+ }
35
+ if (Object.hasOwn(input, 'cacheHitRate')) {
36
+ const rate = input.cacheHitRate
37
+ if (!Number.isFinite(rate) || rate < 0 || rate > 1) return undefined
38
+ usage.cacheHitRate = rate === 0 ? 0 : rate
39
+ }
40
+ return Object.keys(usage).length > 0 ? usage : undefined
41
+ }
42
+
43
+ /** AccountView.user.id is the value for the VibeDev dashboard's expected-user header. */
44
+ export function usageUser(account) {
45
+ if (!['host', 'plugin', 'key'].includes(account?.source)) return undefined
46
+ const id = account.user?.id
47
+ return typeof id === 'string' && /^[!-~]{1,128}$/.test(id) ? id : undefined
48
+ }
49
+
50
+ /** Select the available balance and daily counters from AccountView.balance and dashboard stats.data. */
51
+ export function usageSnapshot(available, stats) {
52
+ const usage = {}
53
+ const balance = balanceOf(available)
54
+ if (balance !== undefined) usage.balance = balance
55
+ for (const [key, field] of Object.entries(DAILY_FIELDS)) {
56
+ const raw = stats?.[field]
57
+ const count = typeof raw === 'string' && /^\d+(?:\.0+)?$/.test(raw) ? Number(raw) : raw
58
+ if (isCount(count)) usage[key] = count === 0 ? 0 : count
59
+ }
60
+
61
+ // Account Center Charts uses read / (input + read + written). Native displays this fraction as a percentage.
62
+ const { todayInput, todayCacheRead, todayCacheWrite } = usage
63
+ if (todayInput !== undefined && todayCacheRead !== undefined && todayCacheWrite !== undefined) {
64
+ const incoming = todayInput + todayCacheRead + todayCacheWrite
65
+ if (incoming > 0) usage.cacheHitRate = todayCacheRead / incoming
66
+ }
67
+ return normalizeAccountUsage(usage)
68
+ }
@@ -0,0 +1,153 @@
1
+ /** Managed cards carry only complete, bounded details from the call that actually asked. */
2
+ import { posix, win32 } from 'node:path'
3
+ import { isDangerous, isFullAccess } from './approvals.js'
4
+
5
+ const MAX_CALLS = 128
6
+ const MAX_ARGUMENTS = 16_384
7
+ const MAX_OPERATION = 600
8
+ const SHELL_TOOLS = new Set(['bash', 'pwsh'])
9
+ const CONTROL_TEXT = /[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u
10
+ const SIMPLE_SHELL =
11
+ /^(?:(?:pnpm|npm) (?:test|check|run (?:test|check|lint|build))|node --test|cargo (?:test|check)|git (?:status|diff|log|show)|Get-ChildItem|Get-Location|Get-Content|Write-Output|echo|pwd|ls|dir)(?= |$)/i
12
+ const SHELL_CONTROL = /[;|&<>`$(){}]|--(?:prefix|ext-diff|textconv)(?= |=|$)/i
13
+ const SECRET_LIKE =
14
+ /(?:sk-|gh[pousr]_|github_pat_|npm_|AKIA|ASIA)[a-z0-9_-]{12,}|\b(?:api[_-]?key|token|authorization)\b/i
15
+
16
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
17
+ const text = (value, max) =>
18
+ typeof value === 'string' && value.length <= max && value.trim() !== '' && !CONTROL_TEXT.test(value)
19
+ const identity = (value) => text(value, 512) && value === value.trim()
20
+ const questionText = (value, max) =>
21
+ typeof value === 'string' && value.length <= max && text(value.replace(/[\n\r\t]/g, ''), max)
22
+
23
+ /** Resolve the shell's working directory and require it to remain inside the session directory. */
24
+ function scopedDirectory(root, requested) {
25
+ if (!text(root, 1024) || root !== root.trim()) return undefined
26
+ const windows = /^[a-z]:[\\/]/i.test(root)
27
+ const paths = windows ? win32 : posix
28
+ if (!paths.isAbsolute(root) || paths.resolve(root) === paths.parse(root).root) return undefined
29
+ if (requested === undefined) return paths.resolve(root)
30
+ if (!text(requested, 1024) || requested !== requested.trim()) return undefined
31
+ if (windows && (/^[\\/]/.test(requested) || /:/.test(requested.replace(/^[a-z]:[\\/]/i, '')))) return undefined
32
+ const cwd = paths.resolve(root, requested)
33
+ const relative = paths.relative(root, cwd)
34
+ if (relative === '..' || relative.startsWith(`..${paths.sep}`) || paths.isAbsolute(relative)) return undefined
35
+ return cwd
36
+ }
37
+
38
+ function shellArguments(operation) {
39
+ if (typeof operation !== 'string' || operation.length > MAX_ARGUMENTS) return undefined
40
+ let params
41
+ try {
42
+ params = JSON.parse(operation)
43
+ } catch {
44
+ return undefined
45
+ }
46
+ if (!record(params) || params.sandbox_permissions !== 'workspace-write' || !text(params.justification, MAX_OPERATION))
47
+ return undefined
48
+ const { command, workdir, justification } = params
49
+ if ((params.run_in_background !== undefined && params.run_in_background !== false) || !text(command, MAX_OPERATION))
50
+ return undefined
51
+ if (!SIMPLE_SHELL.test(command) || SHELL_CONTROL.test(command) || SECRET_LIKE.test(command)) return undefined
52
+ if (isDangerous({ reason: command }) || isFullAccess({ reason: command })) return undefined
53
+ return { command, workdir, justification }
54
+ }
55
+
56
+ /** Cache candidate calls by session and call id. Store no file payloads, results or history. */
57
+ export function createToolCallBook() {
58
+ const calls = new Map()
59
+ const keyFor = (sessionId, callId) => JSON.stringify([sessionId, callId])
60
+ const forget = (sessionId) => {
61
+ for (const [key, call] of calls) if (call.session.id === sessionId) calls.delete(key)
62
+ }
63
+ return {
64
+ observe(session, event) {
65
+ if (!identity(session?.id)) return
66
+ if (event?.type === 'turn/end') return forget(session.id)
67
+ if (event?.type === 'tool/result') return calls.delete(keyFor(session.id, event.data?.message?.toolCallId))
68
+ if (event?.type !== 'tool/call' || !identity(event.data?.callId)) return
69
+ const key = keyFor(session.id, event.data.callId)
70
+ calls.delete(key)
71
+ if (session.header?.origin === 'subagent' || !SHELL_TOOLS.has(event.data.name)) return
72
+ const args = shellArguments(event.data.arguments)
73
+ if (args === undefined) return
74
+ calls.set(key, { session, tool: event.data.name, ...args })
75
+ if (calls.size > MAX_CALLS) calls.delete(calls.keys().next().value)
76
+ },
77
+ details(event, workingDirectory) {
78
+ const sessionId = event?.agent?.id
79
+ if (!identity(sessionId) || !identity(event?.callId) || isDangerous(event) || isFullAccess(event))
80
+ return undefined
81
+ const recorded = calls.get(keyFor(sessionId, event.callId))
82
+ if (recorded === undefined || event.toolName !== recorded.tool) return undefined
83
+ if (event.agent.session !== undefined && event.agent.session !== recorded.session) return undefined
84
+ if (event.reason !== `escalate sandbox to workspace-write: ${recorded.justification}`) return undefined
85
+ const cwd = scopedDirectory(workingDirectory(recorded.session), recorded.workdir)
86
+ if (cwd === undefined || SECRET_LIKE.test(cwd) || isDangerous({ reason: cwd })) return undefined
87
+ return { tool: recorded.tool, operation: recorded.command, cwd }
88
+ },
89
+ forget,
90
+ clear: () => calls.clear(),
91
+ }
92
+ }
93
+
94
+ /** An approval, a plan review, or a timed question uses its own VibeDev answerer. */
95
+ export function structuredQuestions(event) {
96
+ if (!identity(event?.agent?.id) || event.wait?.timed === true || event.agent.session?.header?.origin === 'subagent')
97
+ return undefined
98
+ const input = event.questions
99
+ if (!Array.isArray(input) || input.length === 0 || input.length > 8) return undefined
100
+ const ids = new Set()
101
+ const questions = Array.of()
102
+ for (const question of input) {
103
+ if (!record(question) || question.intent !== undefined || !identity(question.id) || ids.has(question.id))
104
+ return undefined
105
+ if (
106
+ !questionText(question.question, 600) ||
107
+ (question.detail !== undefined && !questionText(question.detail, 1000))
108
+ )
109
+ return undefined
110
+ if (question.multiSelect !== undefined && typeof question.multiSelect !== 'boolean') return undefined
111
+ const { id, detail, multiSelect } = question
112
+ let options
113
+ if (question.options !== undefined) {
114
+ if (!Array.isArray(question.options) || question.options.length > 12) return undefined
115
+ const labels = new Set()
116
+ options = Array.of()
117
+ for (const option of question.options) {
118
+ if (!record(option) || !text(option.label, 160) || labels.has(option.label)) return undefined
119
+ if (option.description !== undefined && !text(option.description, 600)) return undefined
120
+ labels.add(option.label)
121
+ options.push({ label: option.label, description: option.description })
122
+ }
123
+ }
124
+ ids.add(id)
125
+ questions.push({ id, question: question.question, detail, multiSelect, options })
126
+ }
127
+ return questions
128
+ }
129
+
130
+ /** Validate the whole answer batch against the exact question IDs and option labels that were shown. */
131
+ export function validatedAnswers(questions, input) {
132
+ if (!Array.isArray(questions) || !Array.isArray(input) || input.length !== questions.length) return undefined
133
+ const byId = new Map()
134
+ for (const answer of input) {
135
+ if (!record(answer) || !identity(answer.id) || byId.has(answer.id) || !Array.isArray(answer.selected))
136
+ return undefined
137
+ byId.set(answer.id, answer)
138
+ }
139
+ const answers = Array.of()
140
+ for (const question of questions) {
141
+ const answer = byId.get(question.id)
142
+ if (answer === undefined) return undefined
143
+ const { id, selected, custom } = answer
144
+ const options = question.options ?? []
145
+ if (selected.length > options.length || new Set(selected).size !== selected.length) return undefined
146
+ if (selected.some((label) => !options.some((option) => option.label === label))) return undefined
147
+ if (custom !== undefined && !text(custom, 2000)) return undefined
148
+ if (selected.length === 0 && custom === undefined) return undefined
149
+ if (question.multiSelect !== true && selected.length + (custom === undefined ? 0 : 1) > 1) return undefined
150
+ answers.push({ id, selected: [...selected], ...(custom === undefined ? {} : { custom }) })
151
+ }
152
+ return { answers }
153
+ }
package/approvals.js CHANGED
@@ -68,12 +68,18 @@ export function isDangerous(event) {
68
68
  * `allow`、`deny`(在岛上决定了)、`open`(要回 VibeDev 处理)、`timeout`(没人管,交回)、
69
69
  * `cancelled`(请求在别处被取消了)。
70
70
  */
71
- export function createApprovalHolds({ setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
72
- /** id → `{ sessionId, finish }` */
71
+ export function createApprovalHolds({ setTimer = setTimeout, clearTimer = clearTimeout, onPendingChange } = {}) {
72
+ /** id → `{ sessionId, kind, finish }` */
73
73
  const pending = new Map()
74
74
 
75
+ const releaseWhere = (matches, decision) => {
76
+ const held = Array.from(pending.values()).filter(matches)
77
+ for (const item of held) item.finish(decision)
78
+ return held.length
79
+ }
80
+
75
81
  return {
76
- wait(id, { sessionId, signal, timeoutMs = HAND_BACK_MS } = {}) {
82
+ wait(id, { sessionId, kind, signal, timeoutMs = HAND_BACK_MS } = {}) {
77
83
  // 同一个 id 又来了一次(不该发生):旧的那次交回去,别让它一直挂着。
78
84
  pending.get(id)?.finish('timeout')
79
85
  return new Promise((resolve) => {
@@ -84,15 +90,17 @@ export function createApprovalHolds({ setTimer = setTimeout, clearTimer = clearT
84
90
  pending.delete(id)
85
91
  clearTimer(timer)
86
92
  signal?.removeEventListener?.('abort', onAbort)
93
+ onPendingChange?.(pending.size)
87
94
  resolve(decision)
88
95
  }
89
- pending.set(id, { sessionId, finish })
96
+ pending.set(id, { sessionId, kind, finish })
90
97
  if (signal?.aborted === true) {
91
98
  finish('cancelled')
92
99
  return
93
100
  }
94
101
  timer = setTimer(() => finish('timeout'), timeoutMs)
95
102
  signal?.addEventListener?.('abort', onAbort, { once: true })
103
+ onPendingChange?.(pending.size)
96
104
  })
97
105
  },
98
106
 
@@ -106,20 +114,48 @@ export function createApprovalHolds({ setTimer = setTimeout, clearTimer = clearT
106
114
 
107
115
  /** 这条会话在岛上等着的审批全部按 `decision` 了结,返回了结了几条。 */
108
116
  decideForSession(sessionId, decision) {
109
- const ids = Array.from(pending)
110
- .filter(([, held]) => held.sessionId === sessionId)
111
- .map(([id]) => id)
112
- for (const id of ids) pending.get(id)?.finish(decision)
113
- return ids.length
117
+ return releaseWhere((held) => held.sessionId === sessionId, decision)
114
118
  },
115
119
 
120
+ releaseWhere,
121
+
116
122
  has(id) {
117
123
  return pending.has(id)
118
124
  },
119
125
 
120
126
  /** 全部交回(岛屿退出、插件卸载)。 */
121
127
  releaseAll(decision = 'timeout') {
122
- for (const held of Array.from(pending.values())) held.finish(decision)
128
+ return releaseWhere(() => true, decision)
123
129
  },
124
130
  }
125
131
  }
132
+
133
+ export const FOREGROUND_RECHECK_MS = 500
134
+
135
+ /** Only sample while a managed request is held. Ignore replies from a previous set of holds. */
136
+ export function createForegroundRecheck({ setTimer, clearTimer, check, onUnsafe }) {
137
+ let timer
138
+ let generation = 0
139
+
140
+ const schedule = () => {
141
+ const current = generation
142
+ timer = setTimer(() => {
143
+ if (current !== generation) return
144
+ schedule()
145
+ const settled = (safe) => {
146
+ if (current === generation && !safe) onUnsafe()
147
+ }
148
+ void check().then(settled, () => settled(false))
149
+ }, FOREGROUND_RECHECK_MS)
150
+ }
151
+
152
+ return (count) => {
153
+ if (count === 0) {
154
+ generation += 1
155
+ clearTimer(timer)
156
+ timer = undefined
157
+ } else if (timer === undefined) {
158
+ schedule()
159
+ }
160
+ }
161
+ }
Binary file
Binary file