Class: AI::App

Inherits:
Object
  • Object
show all
Defined in:
lib/app.rb

Overview

── App / REPL ───────────────────────────────────────────────────────

Constant Summary collapse

TITLE_PROMPT =
"Give a concise title (3-10 words) for this conversation. " \
"Respond with ONLY the title, nothing else."
DISCARD_USAGE =
"usage: /discard [* | N | A-B | A- | -B]"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key:, profile:, resume: false) ⇒ App

Returns a new instance of App.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/app.rb', line 11

def initialize(key:, profile:, resume: false)
  @key = key; @profile = profile
  @editor = LineEditor.new
  @editor.completer = ->(prefix) { complete(prefix) }
  @hl = Highlighter.new
  @fresh = true
  @attachments = []
  @title_thread = nil
  if resume && (st = Session.all.last) && (s = Session.load(st))
    @session = s; @fresh = false
  end
  @session ||= Session.new
end

Instance Attribute Details

#attachmentsObject (readonly)

Returns the value of attribute attachments.



9
10
11
# File 'lib/app.rb', line 9

def attachments
  @attachments
end

#sessionObject (readonly)

Returns the value of attribute session.



9
10
11
# File 'lib/app.rb', line 9

def session
  @session
end

Instance Method Details

#ask(text) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/app.rb', line 25

def ask(text)
  p = @profile
  attached_data = @attachments.map { |abs|
    { "path" => Paths.short(abs), "content" => safe_read(abs) }
  }
  user_msg = { "role" => "user", "content" => text }
  user_msg["attachments"] = attached_data unless attached_data.empty?
  pending = @session.messages.map { |m| AI.api_message(m) } << AI.api_message(user_msg)

  print_attachments(attached_data) if attached_data.any?
  puts "\n#{Ansi.fg(p.color)}#{p.icon} #{p.name}#{Ansi.reset}"
  reply, usage = begin
      AI.stream(pending, p.system, @key) { |chunk| print @hl.paint(chunk) }
    rescue Interrupt
      puts "\n#{Ansi.fg(220)}[interrupted — turn discarded]#{Ansi.reset}"
      return
    end
  puts
  @session.add_turn(text, reply, usage, attachments: attached_data)
  @attachments = []
  AI.print_usage(usage)
  @session.save(p)
  @fresh = false
  Stats.record(usage)
  kick_title_fetch if @session.title.nil? && @session.messages.length >= 2
end

#attach(arg) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/app.rb', line 116

def attach(arg)
  if arg.empty?
    notify "usage: /attach <file-or-directory-or-pattern>"
    return
  end
  matches = Dir.glob(arg).map { |p| File.expand_path(p) }
  if matches.empty?
    expanded = File.expand_path(arg)
    if File.exist?(expanded)
      matches = [expanded]
    else
      notify "no such path: #{arg}"
      return
    end
  end
  files = []
  matches.each do |p|
    if File.directory?(p)
      files.concat(Dir.children(p).map { |c| File.join(p, c) }.select { |cp| File.file?(cp) })
    elsif File.file?(p)
      files << p
    end
  end
  added = files.uniq - @attachments
  if added.empty?
    notify "(nothing new to attach)"
    return
  end
  @attachments.concat(added)
  shorts = added.map { |p| Paths.short(p) }
  notify "+ attached #{shorts.join(", ")}"
end

#clone_sessionObject



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/app.rb', line 100

def clone_session
  save_history
  src = @session
  dup = Session.new
  dup.messages = Marshal.load(Marshal.dump(src.messages))
  dup.usages = Marshal.load(Marshal.dump(src.usages))
  dup.title = src.title ? "#{src.title} (clone)" : "(clone)"
  dup.save(@profile)
  FileUtils.cp(src.history_file, dup.history_file) if File.exist?(src.history_file)
  @session = dup
  @fresh = false
  load_history
  redraw
  notify "cloned to new session"
end

#detach(arg) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/app.rb', line 149

def detach(arg)
  if arg.empty?
    notify "usage: /detach <path|pattern|directory>"
    return
  end
  expanded = File.expand_path(arg)
  targets = if File.directory?(expanded)
      @attachments.select { |p| File.dirname(p) == expanded }
    else
      exact = @attachments.find { |p| Paths.short(p) == arg }
      if exact
        [exact]
      else
        @attachments.select { |p|
          File.fnmatch(arg, File.basename(p)) ||
          File.fnmatch(arg, Paths.short(p)) ||
          File.fnmatch(arg, p)
        }
      end
    end
  if targets.empty?
    notify "no matching attachments: #{arg}"
    return
  end
  targets.each { |t| @attachments.delete(t) }
  shorts = targets.map { |p| Paths.short(p) }
  notify "\u2212 detached #{shorts.join(", ")}"
end

#discard(arg) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/app.rb', line 52

def discard(arg)
  arg = arg.to_s.strip
  return discard_session if arg == "*"

  total = @session.turns
  range = if arg.empty?
      [total, total]
    else
      parsed = parse_discard_arg(arg, total)
      return notify(DISCARD_USAGE) unless parsed
      parsed
    end

  first, last = range
  first = first.clamp(1, total)
  last = last.clamp(1, total)
  if last < first
    notify "no turns in that range"; return
  end

  removed = @session.remove_turns(first, last)
  if @session.empty?
    @session.delete_files
    @fresh = true
    redraw
    notify "\u2212 discarded #{removed} turn#{removed == 1 ? "" : "s"} · session is now empty"
  else
    @session.save(@profile)
    redraw
    notify "\u2212 discarded #{removed} turn#{removed == 1 ? "" : "s"}"
  end
end

#discard_sessionObject



85
86
87
# File 'lib/app.rb', line 85

def discard_session
  delete_session(announce: "discarded session #{@session.stamp}")
end

#format_attachment_summaryObject



214
215
216
217
218
219
220
221
222
223
# File 'lib/app.rb', line 214

def format_attachment_summary
  return nil if @attachments.empty?
  counts = @attachments.group_by { |p| File.extname(p).delete_prefix(".") }
  parts = counts.sort_by { |ext, _| ext }.map do |ext, fs|
    ext_display = ext.empty? ? "(no ext)" : ext
    "#{fs.length} #{ext_display}"
  end
  suffix = counts.length == 1 ? " file included" : " file(s) included"
  "\e[2;38;5;75m#{parts.join(", ")}#{suffix}\e[0m"
end

#list_filesObject



178
179
180
181
# File 'lib/app.rb', line 178

def list_files
  shorts = @attachments.map { |p| Paths.short(p) }
  notify "#{@attachments.length} file(s) attached:\n#{shorts.join("\n")}"
end

#notify(msg) ⇒ Object



212
# File 'lib/app.rb', line 212

def notify(msg) = puts("#{CMT_STYLE}#{msg}#{Ansi.reset}\n\n")

#replObject



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/app.rb', line 183

def repl
  load_history
  redraw if @session.messages.any?
  loop do
    puts format_attachment_summary if @attachments.any?
    result = begin; @editor.readline(build_prompt);           rescue Interrupt; break; end
    case result
    when nil then break
    when :sess_next then switch_session(+1)
    when :sess_prev then switch_session(-1)
    when :redraw then redraw
    when :del_session then delete_session
    when String
      t = result.strip
      next if t.empty?
      break if %w[exit quit bye :q].include?(t)
      if Commands.slash?(t)
        handle_command(t)
      else
        @hl = Highlighter.new
        ask(t); puts
      end
    end
  end
  flush_title_fetch
  save_history
  footer
end

#set_title(text) ⇒ Object



89
90
91
92
93
94
95
96
97
98
# File 'lib/app.rb', line 89

def set_title(text)
  if text.empty?
    notify "usage: /title <new title>"
    return
  end
  @session.title = text
  @session.save(@profile)
  redraw
  notify "title set"
end