Module: PromptObjects::Server

Defined in:
lib/prompt_objects/server.rb,
lib/prompt_objects/server/app.rb,
lib/prompt_objects/server/api/routes.rb,
lib/prompt_objects/server/file_watcher.rb,
lib/prompt_objects/server/websocket_handler.rb

Defined Under Namespace

Modules: API Classes: App, FileWatcher, WebSocketHandler

Class Method Summary collapse

Class Method Details

.current_autonomous_config(runtime, po_name) ⇒ Object



253
254
255
256
257
258
259
# File 'lib/prompt_objects/server.rb', line 253

def self.current_autonomous_config(runtime, po_name)
  po = runtime.registry.get(po_name)
  return nil unless po.is_a?(PromptObject) && po.autonomous?

  config = po.autonomous_config
  config if config["start_on_boot"]
end

.handle_file_event(app, event, data, runtime: nil) ⇒ Object

Handle file change events and broadcast to connected clients.



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/prompt_objects/server.rb', line 312

def self.handle_file_event(app, event, data, runtime: nil)
  case event
  when :po_added
    po = data
    app.broadcast(
      type: "po_added",
      payload: {
        name: po.name,
        state: po.to_state_hash(registry: runtime&.registry)
      }
    )
    puts "Broadcast: PO added - #{po.name}"

  when :po_modified
    po = data
    app.broadcast(
      type: "po_modified",
      payload: {
        name: po.name,
        state: po.to_state_hash(registry: runtime&.registry)
      }
    )
    puts "Broadcast: PO modified - #{po.name}"

  when :po_removed
    app.broadcast(
      type: "po_removed",
      payload: { name: data[:name] }
    )
    puts "Broadcast: PO removed - #{data[:name]}"
  end
end

.read_server_file(env_path) ⇒ Hash?

Read a .server file to discover a running server. Returns nil if no server is running or the file is stale.

Parameters:

  • env_path (String)

    Path to the environment directory

Returns:

  • (Hash, nil)

    Server info with :host, :port, :pid



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/prompt_objects/server.rb', line 292

def self.read_server_file(env_path)
  server_file = File.join(env_path, ".server")
  return nil unless File.exist?(server_file)

  data = JSON.parse(File.read(server_file), symbolize_names: true)

  # Check if the process is still running
  begin
    Process.kill(0, data[:pid])
    data
  rescue Errno::ESRCH
    # Process is dead, clean up stale file
    File.delete(server_file)
    nil
  end
rescue StandardError
  nil
end

.remove_server_file(path) ⇒ Object

Remove the .server file on shutdown.

Parameters:

  • path (String)

    Path to the .server file



282
283
284
285
286
# File 'lib/prompt_objects/server.rb', line 282

def self.remove_server_file(path)
  File.delete(path) if path && File.exist?(path)
rescue StandardError
  # Ignore cleanup errors
end

.schedule_autonomous_pos(task, runtime, app) ⇒ Object

Schedule Async tasks for autonomous POs that think on their own interval. Uses runtime.inject_message — the same code path as human messages, service events, and webhooks.

Parameters:

  • task (Async::Task)

    The parent Async task

  • runtime (Runtime)

    The environment runtime

  • app (App)

    The server app (unused — broadcasting goes through runtime)



146
147
148
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
177
178
179
180
181
182
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
211
212
213
214
215
216
# File 'lib/prompt_objects/server.rb', line 146

def self.schedule_autonomous_pos(task, runtime, app)
  runtime.registry.prompt_objects.each do |po|
    next unless po.autonomous?

    auto_config = po.autonomous_config
    next unless auto_config["start_on_boot"]

    po_name = po.name

    task.async do |subtask|
      puts "Autonomous PO scheduled: #{po_name} (every #{auto_config['interval']}s, " \
           "initial delay #{auto_config['initial_delay']}s)"

      waiting_state = nil
      loop do
        current = current_autonomous_config(runtime, po_name)
        break unless current && current["wait_for_human"] && !runtime.human_message_received?(po_name)

        current_waiting_state = [current["interval"], current["initial_delay"]]
        if current_waiting_state != waiting_state
          runtime.update_autonomous_schedule(
            po_name,
            status: "waiting_for_human",
            interval: current["interval"],
            initial_delay: current["initial_delay"],
            wait_for_human: true,
            next_run_at: nil
          )
          waiting_state = current_waiting_state
        end
        subtask.sleep 0.1
      end

      next unless wait_for_live_autonomous_delay(
        subtask, runtime, po_name, duration_key: "initial_delay"
      )

      loop do
        current = current_autonomous_config(runtime, po_name)
        break unless current

        begin
          runtime.update_autonomous_schedule(
            po_name,
            status: "running",
            next_run_at: nil
          )
          # Autonomous work uses its own coalesced, summary-retention thread.
          execution = lambda do
            runtime.inject_message(
              target_po: po_name,
              content: current["message"].strip,
              from_source: "timer:#{po_name}"
            )
          end
          if app.respond_to?(:blocking_executor)
            app.blocking_executor.call(&execution)
          else
            execution.call
          end
        rescue => e
          warn "Autonomous PO #{po_name} error: #{e.class}: #{e.message}"
        end

        break unless wait_for_live_autonomous_delay(
          subtask, runtime, po_name, duration_key: "interval"
        )
      end
    end
  end
end

.schedule_service_ticks(task, runtime) ⇒ Object

Schedule Async tick tasks for services that have an interval. Runs inside the Async event loop so ticks cooperate with Falcon.

Parameters:

  • task (Async::Task)

    The parent Async task

  • runtime (Runtime)

    The environment runtime



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/prompt_objects/server.rb', line 124

def self.schedule_service_ticks(task, runtime)
  runtime.services.each do |service|
    next unless service.interval

    task.async do |subtask|
      puts "Service tick loop started: #{service.name} (every #{service.interval}s)"
      loop do
        subtask.sleep service.interval
        service.tick
      rescue => e
        warn "Service #{service.name} tick error: #{e.class}: #{e.message}"
      end
    end
  end
end

.start(runtime:, host: "localhost", port: 3000, env_path: nil) ⇒ Object

Start the server for a given runtime.

Parameters:

  • runtime (Runtime)

    The runtime/environment to serve

  • host (String) (defaults to: "localhost")

    Host to bind to

  • port (Integer) (defaults to: 3000)

    Port to listen on

  • env_path (String) (defaults to: nil)

    Path to the environment directory



15
16
17
18
19
20
21
22
23
24
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
51
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/prompt_objects/server.rb', line 15

def self.start(runtime:, host: "localhost", port: 3000, env_path: nil)
  require "async"
  require "async/http/endpoint"
  require "falcon"

  app = App.new(runtime)
  url = "http://#{host}:#{port}"

  puts "PromptObjects Server"
  puts "===================="
  puts "Environment: #{runtime.name}"
  puts "URL: #{url}"
  puts ""
  puts "Prompt Objects:"
  runtime.registry.prompt_objects.each do |po|
    auto = po.autonomous? ? " (autonomous: #{po.autonomous_config['interval']}s)" : ""
    puts "  - #{po.name}: #{po.description}#{auto}"
  end
  puts ""
  if runtime.services.any?
    puts "Services:"
    runtime.services.each do |s|
      puts "  - #{s.name}: #{s.description || '(no description)'}"
    end
    puts ""
  end
  puts "Press Ctrl+C to stop"
  puts ""

  # Register callback for immediate PO registration notifications
  # This fires when create_capability creates a new PO programmatically
  runtime.on_po_registered = ->(po) {
    app.broadcast(
      type: "po_added",
      payload: {
        name: po.name,
        state: po.to_state_hash(registry: runtime.registry)
      }
    )
    puts "Broadcast: PO registered - #{po.name}"
  }

  # Register callback for PO modification notifications
  # This fires when capabilities are added/removed programmatically
  runtime.on_po_modified = ->(po) {
    app.broadcast(
      type: "po_modified",
      payload: {
        name: po.name,
        state: po.to_state_hash(registry: runtime.registry)
      }
    )
    puts "Broadcast: PO modified (programmatic) - #{po.name}"
  }

  # Register broadcast callback for services to push WebSocket messages
  runtime.on_broadcast = ->(message) { app.broadcast(message) }

  # Start file watcher for live updates (manual file edits)
  file_watcher = nil
  if env_path
    file_watcher = FileWatcher.new(runtime: runtime, env_path: env_path)
    file_watcher.subscribe do |event, data|
      handle_file_event(app, event, data, runtime: runtime)
    end
    file_watcher.start
  end

  # Start environment services (calls service.start, no scheduling yet)
  runtime.start_services if runtime.services.any?

  # Start environment connectors (Discord/Slack/webhook bridges)
  runtime.start_connectors if runtime.connectors.any?

  # Write .server file for CLI discovery
  server_file = write_server_file(env_path, host: host, port: port) if env_path

  Async do |task|
    endpoint = Async::HTTP::Endpoint.parse(url)

    server = Falcon::Server.new(
      Falcon::Server.middleware(app),
      endpoint
    )

    # Schedule service tick loops as Async tasks.
    # These cooperate with Falcon's event loop instead of fighting it.
    schedule_service_ticks(task, runtime)

    # Schedule autonomous PO execution as Async tasks.
    schedule_autonomous_pos(task, runtime, app)

    task.async do
      server.run
    end
  ensure
    runtime.stop_connectors if runtime.connectors.any?
    runtime.stop_services if runtime.services.any?
    runtime.shutdown_execution(wait: false)
    file_watcher&.stop
    app.close
    remove_server_file(server_file) if server_file
  end
end

.wait_for_live_autonomous_delay(subtask, runtime, po_name, duration_key:) ⇒ Object

Sleep until the PO's current autonomous deadline while re-reading its frontmatter. In-app and external source edits can therefore change the message used by the next tick and move an interval deadline without a server restart.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/prompt_objects/server.rb', line 222

def self.wait_for_live_autonomous_delay(subtask, runtime, po_name, duration_key:)
  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  published_deadline = nil

  loop do
    config = current_autonomous_config(runtime, po_name)
    return false unless config

    duration = [config[duration_key].to_f, 0].max
    elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at
    remaining = duration - elapsed
    return true if remaining <= 0

    deadline = Time.now.utc + remaining
    deadline_key = [duration, config["interval"], config["initial_delay"], config["wait_for_human"]]
    if deadline_key != published_deadline
      runtime.update_autonomous_schedule(
        po_name,
        status: "scheduled",
        interval: config["interval"],
        initial_delay: config["initial_delay"],
        wait_for_human: config["wait_for_human"],
        next_run_at: deadline.iso8601(6)
      )
      published_deadline = deadline_key
    end

    subtask.sleep([remaining, 0.1].min)
  end
end

.write_server_file(env_path, host:, port:) ⇒ String

Write a .server file so CLI clients can discover the running server.

Parameters:

  • env_path (String)

    Path to the environment directory

  • host (String)

    Server host

  • port (Integer)

    Server port

Returns:

  • (String)

    Path to the .server file



266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/prompt_objects/server.rb', line 266

def self.write_server_file(env_path, host:, port:)
  return nil unless env_path

  server_file = File.join(env_path, ".server")
  data = {
    pid: Process.pid,
    host: host,
    port: port,
    started_at: Time.now.iso8601
  }
  File.write(server_file, JSON.generate(data))
  server_file
end