repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by admin
nushell/modules/pi_reader.nu
Raw# Read-only session snapshot and RAM-only native terminal reader.
use markdown_render.nu [format-blocks]
def is-string [value: any] { ($value | describe) == string }
def is-record [value: any] { ($value | describe) | str starts-with record }
def key [anchor: record] { [$anchor.message_id $anchor.block_id $anchor.line] | to json --raw }
export def load [file: path] {
let path = $file | path expand
let snapshot = try {
let size = ls --all $path | first | get size | into int
open --raw $path | into binary | bytes at ..<$size | decode utf-8
} catch { error make {msg: 'Cannot read selected session file'} }
mut malformed = 0
mut invalid = 0
mut header: any = null
mut entries = []
for line in ($snapshot | split row (char nl)) {
if ($line | str trim | is-empty) { continue }
let e = try { $line | from json --strict } catch { null }
if not (is-record $e) { $malformed += 1; continue }
if $e.type? == session {
if $header == null and (is-string $e.id?) { $header = $e }
} else if (is-string $e.type?) and (is-string $e.id?) and $e.id != '' and ('parentId' in $e) and ($e.parentId == null or (is-string $e.parentId)) {
$entries = ($entries | append $e)
} else { $invalid += 1 }
}
if $header == null { error make {msg: 'Selected file has no valid session header'} }
mut by_id = {}
for e in $entries { $by_id = ($by_id | upsert $e.id $e) }
mut current = $entries | last 1 | get -o 0
let leaf = $current.id? | default $header.id
mut seen = {}
mut branch = []
mut missing = 0
mut cycles = 0
while $current != null {
if ($seen | get -o $current.id | default false) { $cycles += 1; break }
$seen = ($seen | upsert $current.id true)
$branch = ($branch | append $current)
if $current.parentId == null { break }
let parent = $by_id | get -o $current.parentId
if $parent == null { $missing += 1; break }
$current = $parent
}
let messages = $branch | reverse | each {|e|
if $e.type != message or not (is-record $e.message?) { return null }
let role = $e.message.role?
if $role not-in [user assistant] { return null }
let content = $e.message.content?
let blocks = if (is-string $content) { [{kind: raw_text text: $content}] } else if (($content | describe) =~ '^(list|table)') {
$content | each {|block|
if not (is-record $block) { return null }
if $block.type? == text and (is-string $block.text?) { {kind: raw_text text: $block.text} } else if $block.type? == image {
{kind: image mime_type: ($block.mimeType? | default '') data: (if (is-string $block.data?) { $block.data } else { '' })}
}
} | compact
} else { [] }
{id: $e.id role: $role blocks: $blocks raw_message: $e.message}
} | compact
{path: $path cwd: (if (is-string $header.cwd?) { $header.cwd } else { '' }) id: $header.id messages: $messages metadata: {
selected_leaf_id: $leaf
aggregate: {parsed_entries: ($entries | length) branch_entries: ($branch | length) malformed_lines: $malformed structurally_invalid_entries: $invalid missing_parent_links: $missing cyclic_parent_links: $cycles}
}}
}
export def prepare [loaded: record --width: int = 80] {
mut sources = []
mut messages = []
# Per-reader random namespace, within Kitty's unsigned 32-bit image ID range.
mut image_id = random int 100000..2000000000
mut owned = []
for message in $loaded.messages {
mut blocks = []
for entry in ($message.blocks | enumerate) {
let b = $entry.item
let prefix = [$message.id $entry.index] | to json --raw
let converted = if $b.kind == raw_text {
$sources = ($sources | append {message_id: $message.id content_index: $entry.index block_id: $prefix text: $b.text})
[{id: $prefix kind: raw_text text: $b.text}]
} else if $b.kind == image and $b.mime_type == image/png and ($b.data | str length) > 0 and ($b.data | str length) <= 2097152 and ($b.data =~ '^[A-Za-z0-9+/]*={0,2}$') {
$image_id += 1
$owned = ($owned | append $image_id)
let image = {id: ($prefix + ':image') kind: image image_id: $image_id data: $b.data}
[($image | reject data | insert transmission (transmit $image))]
} else {
# Do not interpolate untrusted MIME strings into terminal output.
[{id: ($prefix + ':unsupported-image') kind: text text: '[image unavailable: PNG ≤2 MiB base64 only]'}]
}
$blocks = ($blocks | append $converted)
}
$messages = ($messages | append ($message | update blocks $blocks))
}
let initial = $loaded | update messages $messages | upsert raw_sources $sources | upsert reader_anchor {} | upsert latest_page true | upsert owned_image_ids $owned
let state = reflow $initial $width
let anchor = if ($state.history.lines | is-empty) { {} } else { $state.history.lines | last | select message_id block_id line }
$state | update reader_anchor $anchor
}
# Only one width's layout is retained; logical blocks and complete sources stay in RAM.
export def reflow [state: record width: int] {
let width = [1 $width] | math max
if $state.layout_width? == $width { return $state }
let history = $state.messages | each {|message|
let visible = $message.blocks | any {|block| $block.kind == image or ($block.text? | default '' | str trim | is-not-empty) }
if not $visible { return [] }
let boundary = {message_id: $message.id block_id: 'role' line: 0 text: (if $message.role == user { '● you' } else { '◆ pi' }) image: null}
let blocks = $message.blocks | each {|block|
if $block.kind == raw_text { format-blocks $block.text $block.id --width $width } else { [$block] }
} | flatten
let lines = $blocks | each {|block|
if $block.kind == text {
[{message_id: $message.id block_id: $block.id line: ($block.line? | default 0) text: $block.text image: null}]
} else {
[0 1 2] | each {|line| {message_id: $message.id block_id: $block.id line: $line text: '' image: $block} }
}
} | flatten
$lines | prepend $boundary
} | flatten
let indexes = $history | enumerate | each {|entry| [(key $entry.item) $entry.index] } | into record
$state | upsert history {lines: $history indexes: $indexes} | upsert layout_width $width
}
def current-index [state: record] {
if ($state.reader_anchor | is-empty) { return 0 }
let exact = $state.history.indexes | get -o (key $state.reader_anchor)
if $exact != null { return $exact }
# Anchor offsets are positions within the same logical source line, not chunks.
$state.history.lines | enumerate | where {|entry|
$entry.item.message_id == $state.reader_anchor.message_id and $entry.item.block_id == $state.reader_anchor.block_id and $entry.item.line <= $state.reader_anchor.line
} | last 1 | get -o 0.index | default 0
}
def page-start [state: record height: int] {
if $state.latest_page? == true { [0 (($state.history.lines | length) - $height)] | math max } else { current-index $state }
}
def at-index [state: record index: int] {
if ($state.history.lines | is-empty) { return $state | upsert latest_page false }
let bounded = [0 ([($index) (($state.history.lines | length) - 1)] | math min)] | math max
$state | update reader_anchor ($state.history.lines | get $bounded | select message_id block_id line) | upsert latest_page false
}
export def scroll [state: record delta: int] {
at-index $state ((current-index $state) + $delta)
}
# Physical Kitty placements, chunked in multiples of four base64 characters.
def transmit [image: record] {
let chunks = $image.data | parse --regex '(?<chunk>.{1,4096})' | get chunk
let last = ($chunks | length) - 1
$chunks | enumerate | each {|chunk|
let more = if $chunk.index == $last { 0 } else { 1 }
let options = if $chunk.index == 0 { $'a=T,f=100,i=($image.image_id),p=1,c=8,r=3,q=2,m=($more)' } else { $'m=($more)' }
$'(ansi escape)_G($options);($chunk.item)(ansi escape)\'
} | str join
}
def delete-placements [placements: list] {
$placements | each {|p| $'(ansi escape)_Ga=d,d=I,i=($p.image_id),q=2(ansi escape)\' } | str join
}
export def render [state: record dims: record] {
let columns = [1 $dims.columns] | math max
let rows = [1 $dims.rows] | math max
let state = reflow $state $columns
let height = [0 ($rows - 1)] | math max
let start = page-start $state $height
mut frame = $'(ansi escape)[H(ansi escape)[2J'
mut placements = []
if $columns < 48 or $rows < 4 {
$frame += ('Resize: 48 columns minimum' | str substring 0..<$columns)
} else {
for entry in ($state.history.lines | skip $start | take $height | enumerate) {
let row = $entry.index + 1
let line = $entry.item
$frame += $'(ansi escape)[($row);1H'
if $line.image == null { $frame += ($line.text + (ansi reset)) } else if $line.line == 0 {
if ($entry.index + 3) <= $height {
$frame += $line.image.transmission
$placements = ($placements | append {image_id: $line.image.image_id placement_id: 1 row: $row column: 1 columns: 8 rows: 3})
} else { $frame += '[image]' }
} else if $entry.index == 0 { $frame += '[image ↑]' }
}
}
let counts = $state.metadata.aggregate
let issues = $counts.malformed_lines + $counts.structurally_invalid_entries + $counts.missing_parent_links + $counts.cyclic_parent_links
let footer = (if $issues > 0 { $'⚠ ($issues) history issues Enter resume q back' } else { '↑↓ scroll g/G ends Enter resume q back' }) | str substring 0..<$columns
$frame += $'(ansi escape)[($rows);1H(ansi d)($footer)(ansi reset)'
{frame: $frame placements: $placements state: $state}
}
# Catch only the documented ordinary timeout; unexpected input failures propagate.
def listen [] {
try { input listen --timeout 5ms } catch {|e|
if $e.msg == 'Timed out while waiting for user input' { null } else { error make {msg: 'Reader input failed'} }
}
}
# `run` is a Nu parser keyword; module main supplies `pi_reader run <file>`.
export def main [action: string file: path] {
if $action != run { error make {msg: 'Expected: pi_reader run <file>'} }
let path = $file | path expand
let owner = job id
let tag = random int 1..2000000000
mut worker: any = null
mut state: any = null
mut placements = []
mut action = 'back'
mut dirty = true
mut dims = {columns: 80 rows: 24}
let failed = try {
$dims = (term size)
let initial_width = $dims.columns
$worker = (job spawn {
let result = try { {state: (prepare (load $path) --width $initial_width)} } catch { {failed: true} }
$result | job send $owner --tag $tag
})
print --no-newline $'(ansi escape)[?1049h(ansi escape)[?25l'
loop {
if $state == null {
let result = try { job recv --tag $tag --timeout 0sec } catch {|e|
if $e.msg == 'No message was received in the requested time interval' { null } else { error make {msg: 'Reader worker failed'} }
}
if $result != null {
if $result.failed? == true { error make {msg: 'Cannot load selected session'} }
$state = $result.state
$dirty = true
}
}
if $dirty {
print --no-newline (delete-placements $placements)
$placements = []
if $state == null {
print --no-newline $'(ansi escape)[H(ansi escape)[2JLoading session… q back'
} else {
$state = (reflow $state $dims.columns)
let view = render $state $dims
$placements = $view.placements
print --no-newline $view.frame
if $state.latest_page {
$state = (at-index $state (page-start $state ([0 ($dims.rows - 1)] | math max)))
}
}
$dirty = false
}
let event = listen
if $event == null { continue }
if $event.type == resize {
$dims = {columns: $event.col rows: $event.row}
$dirty = true
} else if $event.type == key {
let code = $event.code
if $code in [esc escape q] or ($code == c and control in $event.modifiers) { break }
if $code == enter and $state != null { $action = 'resume'; break }
if $state == null { continue }
let page = [1 ($dims.rows - 2)] | math max
match $code {
j | down => { $state = (scroll $state 1) }
k | up => { $state = (scroll $state -1) }
g | home => { $state = (at-index $state 0) }
G | end => { $state = ($state | upsert latest_page true) }
page_up | pageup => { $state = (scroll $state (0 - $page)) }
page_down | pagedown => { $state = (scroll $state $page) }
_ => { continue }
}
$dirty = true
}
}
false
} catch { true }
# Cleanup always precedes resume delegation in the caller.
try { job kill $worker } catch { null } | ignore
# Discard any late result from this invocation's private mailbox tag.
try { job recv --tag $tag --timeout 0sec | ignore } catch { null } | ignore
print --no-newline ((delete-placements $placements) + $'(ansi reset)(ansi escape)[?25h(ansi escape)[?1049l')
if $failed { error make {msg: 'Reader failed for selected session file'} }
{action: $action path: $path cwd: ($state.cwd? | default '')}
}