project-brain 0.44.0 → 0.46.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 +99 -15
- package/package.json +7 -7
- package/templates/claude-tui/activity-pane/hooks/feat-agents.tsx +179 -0
- package/templates/claude-tui/activity-pane/hooks/feat-blocked.tsx +232 -0
- package/templates/claude-tui/activity-pane/hooks/feat-ci.tsx +400 -0
- package/templates/claude-tui/activity-pane/hooks/feat-context.tsx +283 -0
- package/templates/claude-tui/activity-pane/hooks/feat-notify.tsx +145 -0
- package/templates/claude-tui/activity-pane/hooks/feat-progress.tsx +413 -0
- package/templates/claude-tui/activity-pane/hooks/feat-running.tsx +528 -0
- package/templates/claude-tui/activity-pane/hooks/feat-savings.tsx +533 -0
- package/templates/claude-tui/activity-pane/hooks/register.tsx +336 -177
- package/templates/claude-tui/activity-pane/types/index.d.ts +83 -0
- package/templates/claude-tui/context-gate/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/context-gate/hooks/hooks.json +1 -0
- package/templates/claude-tui/context-gate/hooks/register.tsx +355 -0
- package/templates/claude-tui/context-gate/types/index.d.ts +28 -0
- package/templates/claude-tui/skill-listing/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/skill-listing/hooks/hooks.json +1 -0
- package/templates/claude-tui/skill-listing/hooks/register.tsx +300 -0
- package/templates/claude-tui/skill-listing/types/index.d.ts +22 -0
- package/templates/model-routing.md +10 -0
|
@@ -113,6 +113,89 @@ declare module 'claude-code' {
|
|
|
113
113
|
history: Shaped<HistoryView>
|
|
114
114
|
accent: Shaped<string>
|
|
115
115
|
historyFiles: Shaped<Record<string, HistoryFiles>>
|
|
116
|
+
// feat:ci:start
|
|
117
|
+
ciStatus: Shaped<{
|
|
118
|
+
state: 'idle' | 'ready' | 'unavailable'
|
|
119
|
+
reason?: string
|
|
120
|
+
upstream?: string
|
|
121
|
+
ahead?: number
|
|
122
|
+
behind?: number
|
|
123
|
+
sha?: string
|
|
124
|
+
runs: {
|
|
125
|
+
id: number
|
|
126
|
+
workflow: string
|
|
127
|
+
title: string
|
|
128
|
+
status: string
|
|
129
|
+
conclusion: string
|
|
130
|
+
branch: string
|
|
131
|
+
createdAt: string
|
|
132
|
+
url: string
|
|
133
|
+
jobs?: { name: string; status: string; conclusion: string; failedStep?: string }[]
|
|
134
|
+
}[]
|
|
135
|
+
checkedAt: number
|
|
136
|
+
}>
|
|
137
|
+
// feat:ci:end
|
|
138
|
+
// feat:running:start
|
|
139
|
+
runningTasks: Shaped<{
|
|
140
|
+
id: string
|
|
141
|
+
kind: 'bash' | 'monitor' | 'agent' | 'workflow'
|
|
142
|
+
label: string
|
|
143
|
+
status: 'running' | 'completed' | 'failed' | 'killed'
|
|
144
|
+
startedAt: number
|
|
145
|
+
endedAt?: number
|
|
146
|
+
agentId?: string
|
|
147
|
+
agentLabel?: string
|
|
148
|
+
toolUseId?: string
|
|
149
|
+
outputFile?: string
|
|
150
|
+
lastLine?: string
|
|
151
|
+
exitCode?: number
|
|
152
|
+
deadline?: number
|
|
153
|
+
isInferred?: boolean
|
|
154
|
+
}[]>
|
|
155
|
+
runningTick: Shaped<number>
|
|
156
|
+
// feat:running:end
|
|
157
|
+
// feat:progress:start
|
|
158
|
+
progress: Shaped<{
|
|
159
|
+
path: string
|
|
160
|
+
mtimeMs: number
|
|
161
|
+
doc?: {
|
|
162
|
+
feature: string
|
|
163
|
+
path: string
|
|
164
|
+
title: string
|
|
165
|
+
objective?: string
|
|
166
|
+
tasks: { id: string; title: string; done: boolean; route?: string; commit?: string }[]
|
|
167
|
+
done: number
|
|
168
|
+
total: number
|
|
169
|
+
current?: { id: string; title: string; done: boolean; route?: string; commit?: string }
|
|
170
|
+
pending: string[]
|
|
171
|
+
}
|
|
172
|
+
}>
|
|
173
|
+
// feat:progress:end
|
|
174
|
+
// feat:agents:start
|
|
175
|
+
agentsExpanded: Shaped<boolean>
|
|
176
|
+
agentsReports: Shaped<Record<string, string>>
|
|
177
|
+
// feat:agents:end
|
|
178
|
+
// feat:context:start
|
|
179
|
+
contextBreakdown: Shaped<{ rows: { name: string; tokens: number; kind: 'used' | 'free' | 'buffer' }[]; window: number; total: number; autoCompactAt?: number; at: number }>
|
|
180
|
+
contextCompactions: Shaped<{ count: number; lastAt: number; before?: number; after?: number }>
|
|
181
|
+
contextLive: Shaped<{ tokens?: number; window: number; percent?: number }>
|
|
182
|
+
// feat:context:end
|
|
183
|
+
// feat:blocked:start
|
|
184
|
+
blockedList: Shaped<{ id: string; at: number; tool: string; summary: string; category: 'user' | 'classifier' | 'rule' | 'hook'; reason: string; label?: string; agentId?: string; agent?: string }[]>
|
|
185
|
+
blockedTurn: Shaped<number>
|
|
186
|
+
// feat:blocked:end
|
|
187
|
+
// feat:savings:start
|
|
188
|
+
savings: Shaped<{
|
|
189
|
+
at: number
|
|
190
|
+
gate?: { count: number; chars: number; last: { at: number; event: string; chars: number; score?: number; head: string }[] }
|
|
191
|
+
picks?: { prompts: { at: number; skills: string[] }[]; delegations: { agentId: string; description: string; skills: string[] }[] }
|
|
192
|
+
listing?: 'jev' | 'stats' | 'passthrough'
|
|
193
|
+
lane?: { state: 'up' | 'mismatch' | 'dead' | 'pending' | 'off'; reason?: string; at?: number }
|
|
194
|
+
}>
|
|
195
|
+
// feat:savings:end
|
|
196
|
+
// feat:notify:start
|
|
197
|
+
notify: Shaped<boolean>
|
|
198
|
+
// feat:notify:end
|
|
116
199
|
}
|
|
117
200
|
}
|
|
118
201
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "project-brain-context-gate",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Asks Jev whether the context other hooks inject is needed for the prompt at hand, leaves out what is not, and replays every answer on resume so the prompt cache holds.",
|
|
5
|
+
"author": { "name": "jcsoftdev" },
|
|
6
|
+
"types": "./types/index.d.ts"
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "modules": ["./register.tsx"] }
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import type { Hook, Register } from 'claude-code'
|
|
2
|
+
|
|
3
|
+
import type { DroppedEntry, Framed, GateConfig, Piece, Sent, SessionRecord, Verdict } from '../types'
|
|
4
|
+
|
|
5
|
+
type Api = Parameters<Hook<'prompt.attachment'>>[0]
|
|
6
|
+
type Attachment = Parameters<Hook<'prompt.attachment'>>[1]
|
|
7
|
+
|
|
8
|
+
const DAY_MS = 24 * 60 * 60_000
|
|
9
|
+
export const GATE_TIMEOUT_MS = 3_500
|
|
10
|
+
export const MIN_PIECE_CHARS = 300
|
|
11
|
+
export const MAX_GATE_FAILURES = 3
|
|
12
|
+
export const HEALTH_RETRY_MS = 10 * 60_000
|
|
13
|
+
export const SESSION_TTL_MS = 30 * DAY_MS
|
|
14
|
+
export const DROPPED_LOG_LIMIT = 100
|
|
15
|
+
const LOG_HEAD_CHARS = 160
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_ALLOW = [
|
|
18
|
+
'engram',
|
|
19
|
+
'mem_',
|
|
20
|
+
'project-brain',
|
|
21
|
+
'brain-',
|
|
22
|
+
'session-title',
|
|
23
|
+
'session-color',
|
|
24
|
+
'Model routing for delegated agents',
|
|
25
|
+
'Suggested skill',
|
|
26
|
+
'Suggested tool',
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
export const DEFAULT_CONFIG: GateConfig = { enabled: true, allow: DEFAULT_ALLOW }
|
|
30
|
+
|
|
31
|
+
export const FENCE_BEGIN = '<!-- project-brain:begin -->'
|
|
32
|
+
export const FENCE_END = '<!-- project-brain:end -->'
|
|
33
|
+
|
|
34
|
+
export const GATED_TYPES = new Set(['hook_additional_context', 'hook_success'])
|
|
35
|
+
export const GATED_HOOK_EVENTS = new Set(['SessionStart', 'UserPromptSubmit', 'PostToolUse'])
|
|
36
|
+
|
|
37
|
+
const HOOK_FRAME = /^[^\n]*? hook (?:additional context|success): /
|
|
38
|
+
const COMPACTIONS_THAT_STAND = new Set(['manual', 'auto', 'plugin'])
|
|
39
|
+
|
|
40
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
41
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
42
|
+
|
|
43
|
+
export function parseConfig(text: string): GateConfig {
|
|
44
|
+
try {
|
|
45
|
+
const raw: unknown = JSON.parse(text)
|
|
46
|
+
if (!isObject(raw)) return DEFAULT_CONFIG
|
|
47
|
+
const extra = Array.isArray(raw.contextAllow) ? raw.contextAllow.filter((s): s is string => typeof s === 'string' && s.trim() !== '') : []
|
|
48
|
+
return { enabled: raw.contextGate !== false, allow: [...DEFAULT_ALLOW, ...extra] }
|
|
49
|
+
} catch {
|
|
50
|
+
return DEFAULT_CONFIG
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const allowed = (text: string, allow: readonly string[]): boolean => {
|
|
55
|
+
const lower = text.toLowerCase()
|
|
56
|
+
return allow.some(signature => lower.includes(signature.toLowerCase()))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A stray or missing fence leaves no line provably outside project-brain's block, so the whole body is kept. */
|
|
60
|
+
const fencesBalanced = (body: string): boolean => {
|
|
61
|
+
let depth = 0
|
|
62
|
+
for (const line of body.split('\n')) {
|
|
63
|
+
const trimmed = line.trim()
|
|
64
|
+
if (trimmed === FENCE_BEGIN) depth++
|
|
65
|
+
if (trimmed === FENCE_END && --depth < 0) return false
|
|
66
|
+
}
|
|
67
|
+
return depth === 0
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function splitAttachment(type: string, text: string, allow: readonly string[]): Framed {
|
|
71
|
+
const frame = HOOK_FRAME.exec(text)?.[0] ?? ''
|
|
72
|
+
const body = text.slice(frame.length)
|
|
73
|
+
if (type === 'hook_success') return { frame, pieces: [{ text: body, allowed: allowed(body, allow) }] }
|
|
74
|
+
if (!fencesBalanced(body)) return { frame, pieces: [{ text: body, allowed: true }] }
|
|
75
|
+
const pieces: Piece[] = []
|
|
76
|
+
let depth = 0
|
|
77
|
+
for (const line of body.split('\n')) {
|
|
78
|
+
const trimmed = line.trim()
|
|
79
|
+
if (trimmed === FENCE_BEGIN) depth++
|
|
80
|
+
const lineAllowed = depth > 0 || allowed(line, allow)
|
|
81
|
+
if (trimmed === FENCE_END) depth = Math.max(0, depth - 1)
|
|
82
|
+
const last = pieces[pieces.length - 1]
|
|
83
|
+
if (last !== undefined && last.allowed === lineAllowed) last.text += `\n${line}`
|
|
84
|
+
else pieces.push({ text: line, allowed: lineAllowed })
|
|
85
|
+
}
|
|
86
|
+
return { frame, pieces }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export const askable = (piece: Piece): boolean => !piece.allowed && piece.text.trim().length >= MIN_PIECE_CHARS
|
|
90
|
+
|
|
91
|
+
export function assemble(framed: Framed, dropped: ReadonlySet<number>): string | null {
|
|
92
|
+
const kept = framed.pieces.filter((_, index) => !dropped.has(index))
|
|
93
|
+
if (kept.every(piece => piece.text.trim() === '')) return null
|
|
94
|
+
return framed.frame + kept.map(piece => piece.text).join('\n')
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function parseVerdict(stdout: string, count: number): Verdict | null {
|
|
98
|
+
const line = stdout.trim().split('\n').pop() ?? ''
|
|
99
|
+
try {
|
|
100
|
+
const raw: unknown = JSON.parse(line)
|
|
101
|
+
if (!isObject(raw) || !Array.isArray(raw.keep) || raw.keep.length !== count || !raw.keep.every(k => typeof k === 'boolean')) return null
|
|
102
|
+
const scores = Array.isArray(raw.scores) && raw.scores.length === count ? (raw.scores as Array<number | null>) : raw.keep.map(() => null)
|
|
103
|
+
return { keep: raw.keep as boolean[], scores }
|
|
104
|
+
} catch {
|
|
105
|
+
return null
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function gateHealthy(text: string, now: number): boolean {
|
|
110
|
+
try {
|
|
111
|
+
const raw: unknown = JSON.parse(text)
|
|
112
|
+
if (!isObject(raw) || typeof raw.failures !== 'number' || raw.failures < MAX_GATE_FAILURES) return true
|
|
113
|
+
return typeof raw.lastFailure === 'number' && now - raw.lastFailure >= HEALTH_RETRY_MS
|
|
114
|
+
} catch {
|
|
115
|
+
return true
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function tokenShaped(envToken: string | undefined, fileText: string): boolean {
|
|
120
|
+
const shaped = (value: unknown) => typeof value === 'string' && /^\S{8,}$/.test(value)
|
|
121
|
+
if (shaped(envToken)) return true
|
|
122
|
+
try {
|
|
123
|
+
const raw: unknown = JSON.parse(fileText)
|
|
124
|
+
return isObject(raw) && shaped(raw.token)
|
|
125
|
+
} catch {
|
|
126
|
+
return false
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function attachmentKey(epoch: number, e: { type: string; text: string; origin: { kind: string; event?: string } }): string {
|
|
131
|
+
const source = `${epoch}\u0000${e.type}\u0000${e.origin.kind}\u0000${e.origin.event ?? ''}\u0000${e.text}`
|
|
132
|
+
let h1 = 0xdeadbeef
|
|
133
|
+
let h2 = 0x41c6ce57
|
|
134
|
+
for (let i = 0; i < source.length; i++) {
|
|
135
|
+
const c = source.charCodeAt(i)
|
|
136
|
+
h1 = Math.imul(h1 ^ c, 2654435761)
|
|
137
|
+
h2 = Math.imul(h2 ^ c, 1597334677)
|
|
138
|
+
}
|
|
139
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
|
|
140
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
|
|
141
|
+
return `${(h2 >>> 0).toString(16).padStart(8, '0')}${(h1 >>> 0).toString(16).padStart(8, '0')}:${source.length}`
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export const replayed = (sent: Sent, original: string): string | null => (sent === true ? original : sent.text)
|
|
145
|
+
|
|
146
|
+
export function answerIn(record: SessionRecord, e: Parameters<typeof attachmentKey>[1]): Sent | undefined {
|
|
147
|
+
for (let epoch = record.epoch; epoch >= 0; epoch--) {
|
|
148
|
+
const sent = record.sent[attachmentKey(epoch, e)]
|
|
149
|
+
if (sent !== undefined) return sent
|
|
150
|
+
}
|
|
151
|
+
return undefined
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function readOr($: Api, path: string, fallback: string): Promise<string> {
|
|
155
|
+
try {
|
|
156
|
+
return await $.fs.read(path)
|
|
157
|
+
} catch {
|
|
158
|
+
return fallback
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const sessionKey = (sessionId: string) => `session:${sessionId}`
|
|
163
|
+
|
|
164
|
+
const STORE_UNREADABLE = Symbol('store unreadable')
|
|
165
|
+
|
|
166
|
+
async function readRecord($: Api, sessionId: string): Promise<SessionRecord | typeof STORE_UNREADABLE> {
|
|
167
|
+
let raw: unknown
|
|
168
|
+
try {
|
|
169
|
+
raw = await $.store.get(sessionKey(sessionId))
|
|
170
|
+
} catch {
|
|
171
|
+
return STORE_UNREADABLE
|
|
172
|
+
}
|
|
173
|
+
if (isObject(raw) && typeof raw.epoch === 'number' && isObject(raw.sent)) return raw as SessionRecord
|
|
174
|
+
return { epoch: 0, touched: 0, sent: {} }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function writeRecord($: Api, sessionId: string, record: SessionRecord): Promise<boolean> {
|
|
178
|
+
try {
|
|
179
|
+
await $.store.set(sessionKey(sessionId), { ...record, touched: await $.clock.now() })
|
|
180
|
+
return true
|
|
181
|
+
} catch {
|
|
182
|
+
return false
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function pruneSessions($: Api, keepSessionId: string): Promise<void> {
|
|
187
|
+
const cutoff = (await $.clock.now()) - SESSION_TTL_MS
|
|
188
|
+
for (const key of await $.store.keys()) {
|
|
189
|
+
if (!key.startsWith('session:') || key === sessionKey(keepSessionId)) continue
|
|
190
|
+
const raw = await $.store.get(key)
|
|
191
|
+
if (!isObject(raw) || typeof raw.touched !== 'number' || raw.touched < cutoff) await $.store.delete(key)
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function gateConfig($: Api, home: string): Promise<GateConfig> {
|
|
196
|
+
return parseConfig(await readOr($, `${home}/.project-brain/skills.json`, ''))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function gateReady($: Api, home: string, config: GateConfig): Promise<boolean> {
|
|
200
|
+
if (!config.enabled || (await $.env.get('BRAIN_CONTEXT_GATE')) === '0') return false
|
|
201
|
+
if (!tokenShaped(await $.env.get('TYPESAFE_API_KEY'), await readOr($, `${home}/.project-brain/reranker.json`, ''))) return false
|
|
202
|
+
return gateHealthy(await readOr($, `${home}/.project-brain/context-gate-health.json`, ''), await $.clock.now())
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function judge($: Api, prompt: string, segments: string[]): Promise<Verdict | null> {
|
|
206
|
+
const { exitCode, stdout } = await $.process.run(['project-brain', 'suggest', '--context', '--stdin'], {
|
|
207
|
+
stdin: JSON.stringify({ prompt, segments }),
|
|
208
|
+
timeoutMs: GATE_TIMEOUT_MS,
|
|
209
|
+
})
|
|
210
|
+
return exitCode === 0 ? parseVerdict(stdout, segments.length) : null
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function logDropped($: Api, home: string, entries: DroppedEntry[]): Promise<void> {
|
|
214
|
+
if (entries.length === 0) return
|
|
215
|
+
const path = `${home}/.project-brain/context-gate-log.json`
|
|
216
|
+
let earlier: DroppedEntry[] = []
|
|
217
|
+
try {
|
|
218
|
+
const raw: unknown = JSON.parse(await readOr($, path, '{}'))
|
|
219
|
+
if (isObject(raw) && Array.isArray(raw.dropped)) earlier = raw.dropped as DroppedEntry[]
|
|
220
|
+
} catch {
|
|
221
|
+
earlier = []
|
|
222
|
+
}
|
|
223
|
+
const dropped = [...earlier, ...entries].slice(-DROPPED_LOG_LIMIT)
|
|
224
|
+
await $.fs.write(path, `${JSON.stringify({ dropped }, null, 2)}\n`)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
type Gate = {
|
|
228
|
+
prompts: Map<string, string>
|
|
229
|
+
answers: Map<string, Sent>
|
|
230
|
+
replayOnly: boolean
|
|
231
|
+
submittedHere: boolean
|
|
232
|
+
queue: Promise<unknown>
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
type Decision = { text: string | null; dropped: DroppedEntry[] }
|
|
236
|
+
|
|
237
|
+
async function decide($: Api, gate: Gate, e: Attachment, sessionId: string, home: string): Promise<Decision> {
|
|
238
|
+
const unchanged: Decision = { text: e.text, dropped: [] }
|
|
239
|
+
if (gate.replayOnly) return unchanged
|
|
240
|
+
const prompt = gate.prompts.get(sessionId)
|
|
241
|
+
if (prompt === undefined) return unchanged
|
|
242
|
+
const config = await gateConfig($, home)
|
|
243
|
+
if (!(await gateReady($, home, config))) return unchanged
|
|
244
|
+
const framed = splitAttachment(e.type, e.text, config.allow)
|
|
245
|
+
const asked = framed.pieces.flatMap((piece, index) => (askable(piece) ? [index] : []))
|
|
246
|
+
if (asked.length === 0) return unchanged
|
|
247
|
+
const verdict = await judge($, prompt, asked.map(index => framed.pieces[index]!.text))
|
|
248
|
+
if (verdict === null) return unchanged
|
|
249
|
+
const droppedAt = asked.filter((_, n) => !verdict.keep[n])
|
|
250
|
+
if (droppedAt.length === 0) return unchanged
|
|
251
|
+
const now = await $.clock.now()
|
|
252
|
+
const origin = e.origin as { event?: string }
|
|
253
|
+
return {
|
|
254
|
+
text: assemble(framed, new Set(droppedAt)),
|
|
255
|
+
dropped: droppedAt.map(index => {
|
|
256
|
+
const piece = framed.pieces[index]!.text
|
|
257
|
+
return {
|
|
258
|
+
at: now,
|
|
259
|
+
session: sessionId,
|
|
260
|
+
type: e.type,
|
|
261
|
+
event: origin.event ?? '',
|
|
262
|
+
chars: piece.length,
|
|
263
|
+
score: verdict.scores[asked.indexOf(index)] ?? null,
|
|
264
|
+
head: piece.trim().slice(0, LOG_HEAD_CHARS),
|
|
265
|
+
}
|
|
266
|
+
}),
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function gated($: Api, gate: Gate, e: Attachment): Promise<string | null> {
|
|
271
|
+
const sessionId = await $.session.id()
|
|
272
|
+
const inProcess = `${sessionId}\u0000${attachmentKey(0, e)}`
|
|
273
|
+
const given = gate.answers.get(inProcess)
|
|
274
|
+
if (given !== undefined) return replayed(given, e.text)
|
|
275
|
+
const answer = (sent: Sent) => (gate.answers.set(inProcess, sent), replayed(sent, e.text))
|
|
276
|
+
|
|
277
|
+
const record = await readRecord($, sessionId)
|
|
278
|
+
if (record === STORE_UNREADABLE) return answer(true)
|
|
279
|
+
const earlier = answerIn(record, e)
|
|
280
|
+
if (earlier !== undefined) return answer(earlier)
|
|
281
|
+
|
|
282
|
+
const home = await $.env.get('HOME')
|
|
283
|
+
const decision = home ? await decide($, gate, e, sessionId, home).catch((): Decision => ({ text: e.text, dropped: [] })) : { text: e.text, dropped: [] }
|
|
284
|
+
const sent: Sent = decision.text === e.text ? true : { text: decision.text }
|
|
285
|
+
const persisted = await writeRecord($, sessionId, { ...record, sent: { ...record.sent, [attachmentKey(record.epoch, e)]: sent } })
|
|
286
|
+
if (!persisted) return answer(true)
|
|
287
|
+
if (home) await logDropped($, home, decision.dropped).catch(() => undefined)
|
|
288
|
+
return answer(sent)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export const gatedOrigin = (e: { type: string; origin: { kind: string; event?: string }; agentId?: string }): boolean => {
|
|
292
|
+
if (e.agentId !== undefined || !GATED_TYPES.has(e.type)) return false
|
|
293
|
+
if (e.origin.kind === 'plugin') return true
|
|
294
|
+
return e.origin.kind === 'hook' && GATED_HOOK_EVENTS.has(e.origin.event ?? '')
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function inTurn<T>(gate: Gate, work: () => Promise<T>): Promise<T> {
|
|
298
|
+
const run = gate.queue.then(work, work)
|
|
299
|
+
gate.queue = run.catch(() => undefined)
|
|
300
|
+
return run
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export function createGate(): Gate {
|
|
304
|
+
return { prompts: new Map(), answers: new Map(), replayOnly: false, submittedHere: false, queue: Promise.resolve() }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export const register: Register = on => {
|
|
308
|
+
const gate = createGate()
|
|
309
|
+
|
|
310
|
+
on('session.start', async ($, e, next) => {
|
|
311
|
+
try {
|
|
312
|
+
gate.replayOnly = (await $.session.turns()) > 0
|
|
313
|
+
void pruneSessions($ as unknown as Api, await $.session.id()).catch(() => undefined)
|
|
314
|
+
} catch {
|
|
315
|
+
gate.replayOnly = true
|
|
316
|
+
}
|
|
317
|
+
return next(e)
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
on('prompt.submit', async ($, e, next) => {
|
|
321
|
+
if (e.command === undefined && e.isMeta !== true) {
|
|
322
|
+
const sessionId = await $.session.id().catch(() => null)
|
|
323
|
+
if (sessionId !== null) gate.prompts.set(sessionId, e.text)
|
|
324
|
+
gate.submittedHere = true
|
|
325
|
+
}
|
|
326
|
+
return next(e)
|
|
327
|
+
})
|
|
328
|
+
|
|
329
|
+
on('turn.complete', async ($, e, next) => {
|
|
330
|
+
if (e.agentId === undefined && gate.submittedHere) gate.replayOnly = false
|
|
331
|
+
return next(e)
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
on('session.compact', async ($, e, next) => {
|
|
335
|
+
const result = await next(e)
|
|
336
|
+
if (e.agentId !== undefined || !COMPACTIONS_THAT_STAND.has(e.trigger) || result.skip !== undefined) return result
|
|
337
|
+
await inTurn(gate, async () => {
|
|
338
|
+
const sessionId = await $.session.id()
|
|
339
|
+
const record = await readRecord($ as unknown as Api, sessionId)
|
|
340
|
+
if (record !== STORE_UNREADABLE) await writeRecord($ as unknown as Api, sessionId, { ...record, epoch: record.epoch + 1 })
|
|
341
|
+
}).catch(() => undefined)
|
|
342
|
+
return result
|
|
343
|
+
})
|
|
344
|
+
|
|
345
|
+
on('prompt.attachment', async ($, e, next) => {
|
|
346
|
+
if (!gatedOrigin(e)) return next(e)
|
|
347
|
+
try {
|
|
348
|
+
const text = await inTurn(gate, () => gated($, gate, e))
|
|
349
|
+
if (text === null) return { text: null }
|
|
350
|
+
return text === e.text ? next(e) : next({ ...e, text })
|
|
351
|
+
} catch {
|
|
352
|
+
return next(e)
|
|
353
|
+
}
|
|
354
|
+
})
|
|
355
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export type GateConfig = {
|
|
2
|
+
enabled: boolean
|
|
3
|
+
allow: string[]
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export type Piece = { text: string; allowed: boolean }
|
|
7
|
+
|
|
8
|
+
export type Framed = { frame: string; pieces: Piece[] }
|
|
9
|
+
|
|
10
|
+
export type Sent = true | { text: string | null }
|
|
11
|
+
|
|
12
|
+
export type SessionRecord = {
|
|
13
|
+
epoch: number
|
|
14
|
+
touched: number
|
|
15
|
+
sent: Record<string, Sent>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type Verdict = { keep: boolean[]; scores: Array<number | null> }
|
|
19
|
+
|
|
20
|
+
export type DroppedEntry = {
|
|
21
|
+
at: number
|
|
22
|
+
session: string
|
|
23
|
+
type: string
|
|
24
|
+
event: string
|
|
25
|
+
chars: number
|
|
26
|
+
score: number | null
|
|
27
|
+
head: string
|
|
28
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "project-brain-skill-listing",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Lists most skills by name only in the session's skill listing; the Jev picker brings each prompt's skills in full, or, without it, the skills you use most keep their description.",
|
|
5
|
+
"author": { "name": "jcsoftdev" },
|
|
6
|
+
"types": "./types/index.d.ts"
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "modules": ["./register.tsx"] }
|