Old Agent (Perl)

Tags:

Link: https://github.com/kristopolous/old-agent

8-color image

This is an LLM agent, written in pure Perl 5.006 with zero (non-core) dependencies. I guess the stated aim is good. You run this agent on a target machine that you want something done on. And since it uses Perl 5.006, and Perl has been fairly stable in the last 25 years, in the sense that code written for Perl 5.006 still compiles and runs today, you can call that agent onto basically any machine that has Perl available.

The alternative approach would likely be to give a random other LLM agent program ssh ( or telnet) credentials for that other machine, but this approach sounds more fun.

The program even brings an SSL terminating network proxy that you can run on another machine. That way, you don't need to worry to bring SSL certificates and SSL versions up to speed on the old machine, just to have the LLM agent run on it.

HTMX Patterns: Dynamic dropdown menu with Bootstrap 5

Tags:

After doing some more development with HTMX 4.0 , I find myself creating a list of patterns that I reuse, as somehow constructing them from first principles is more fiddly than I initially think, every time. I'm using HTMX 4.0 for the interactivity with Bootstrap 5.3 for the CSS styling. For the showcase, I'm using Perl and Mojolicious, but the approach obviously works elsewhere too.

Dynamic dropdown menu

From time to time, I want or need to provide the user with a more dynamic selection of items. In the below example, I use this technique to populate a list of labels that can be assigned to an item.

Doing so in HTMX (plus Bootstrap) can be done in a simplistic pattern. I put the HTML for the dropdown (or rather, drop-up in this case) into a separate template and URL. This HTML is then loaded when the button is clicked.

```perl

@@ main.html.ep
...
<a class="btn btn-secondary dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<%= $agent\_state->{session\_id} %%>

*   <a class="dropdown-item" href="#">&hellip;</a>

...

@@ available-sessions.html.ep
*   \+ New session
*

% for my $sess ($available\_sessions->@\*) {
<a href="">
    <%= $sess->{timestamp} // $sess->{last\_modified} %>
    % if( $sess->{name} ) {
        <%= $sess->{name} %> %
    % } else {
        <i>(unnamed)</i>
    % }
    <%= $sess->{id} %%>
</a>
% }

```

Serve available-sessions from /available-sessions.

no-JS fallback

I haven't actually implemented a no-JS fallback for this. This would need some bookkeeping for the application state, which URL I came from, and how I can restore the previous page after selecting from the dropdown, which I skipped on. In principle, it should be fairly easy to render the dropdown template inline, reloading the page on submit, or just have the complete dropdown have its own (no-JS) page.

Pattern: Progress / status poll

For progress updates or status polling, I really like the approach of having two templates, one that reloads itself until we arrive at the final stage, and a template that renders the final state.

@@ message-processing.html.ep
<div id="item"
     hx-get="/processing?request_id=123"
     hx-trigger="load delay:1s"
     hx-swap="outerHTML">
In progress
</div>

The other template is the final template. It has no more HTMX properties related to reloading the item, so the reloading simply stops.

@@ message-done.html.ep
<div id="item">
Item progressed
</div>

If you have multiple items in flight at the same time, it might be worthwhile to reload the complete list of items in one go instead of having each item issue its own separate request, especially as HTMX queues requests.

An alternative approach is to use Server-Sent Events, which HTMX also supports natively. That way, the client still polls, but the server can push multiple updates through a single URL and the client can signal after which update it wants to resume.

no-JS fallback

There is no good fallback without Javascript. You could work with a refreshing page:

<meta http-equiv="refresh" content="5; url=https://example.com/processing?request_id=123">

But that has the problem that the user might want to do other things on the page. Having a manual refresh link is likely the best approach.

Using Server-Sent Events does not update the page via Javascript either.

Using the <progress> element

HTMX does not replace attributes. The HTML <progress> element uses an attribute to fill the progress bar:

There is no convenient way to update just the value attribute from HTMX, so you have to replace the complete element:

@@progress.html.ep
    <progress value="99" max="100"
         hx-trigger="load delay:1s"
         hx-swap="outerHTML"
     >99 %</progress>

This potentially loses user interaction, but luckily, a <progress> element has no interaction.

<progress value="0" max="100">0 %</progress>

0 %

<progress value="35" max="100">35 %</progress>

0 %

<progress value="99" max="100">99 %</progress>

99 %

Thanksgiving release cleanout

Tags:

Twice a year, around Thanksgiving and Spring, I take stock of all the code that has amassed on my systems. I usually try to release it on CPAN, or at least publish it on GitHub, if not as a way of giving back to the community then at least as another off-site backup.

String::FuzzyMatch

I created the module when I wrote my third incarnation of fuzzy filtering strings, buggy in slightly different ways. It is already on CPAN.

AppTemplate-Perl-Mojolicious

This is my starter template for whenever I want a clanker to slop out some code. As LLMs usually copy the already existing style, I've found that having the crystals grow from the substrate laid out in these files reduces the amount of corrections I have to make with the LLM. Sometimes the LLM still puts documentation in one huge block, but at least I can then tell it to look at the pre-existing style and to copy it.

The repository consists of

  • scripts/app.pl -- Example application, to be customized
  • scripts/public -- Static public directory, contains CSS and vendored Javascript
  • Makefile.PL -- Part of the build process when distributing this Perl distribution
  • AGENTS.md -- Instructions for LLMs
  • t/ -- Directory for test files
  • xt/ -- Directory for author test files, only to be run before a release
  • skills/ -- Vendored skills

I usually transplant general findings into the master AGENTS.md, but I haven't tried out enough different models to know how well these findings translate across agents.

I mildly think about releasing this onto CPAN as well, but then again, you could do the same, better, with Module::Starter or some other templating tool.

Linux-ARPTable

Born out of the intention of waking up machines via WOL. It is quite Linux specific, as it reads /net/arp to get the information about the IP addresses. I thought I could get away without any pinging or IP functionality, but it turns out even the topology of my home network needs sufficient network traffic to fill the ARP cache. So it's unlikely that I'll release this specific module, but there is a Mojolicious wrapper gestating in it, that makes sure that one or more machines are awake and reachable over IP.

App-CaptureAgenda

I've already blogged about it, and it's on GitHub already. It contains a module that could evolve into some kind of prompt runner, but as most prompt runners are little more than curl or HTTP::Tiny and a JSON parser, I'm not sure releasing it makes sense.

Protocol::Samsung::MDC

I wrote this to update what my Samsung EM32DX screen displays. It works quite well, and I also blogged about it at the time.

Perl Module: String::FuzzyMatch

Tags:

I often find myself writing some small tool where I need to select a file or other string. I could do so from the command line, adding some mechanism to add command line completion, but most of the time, I reach for fzf. The program takes a list of strings from STDIN. It displays them as a list and allows me to select an item with the cursor keys, and to filter the list by typing any sequence of characters. The searching is fuzzy. It filters the list by any string that contains the typed characters in sequence.For the example below, I'm listing files in a directory. There is a file named with an umlaut, hätte.test.

list of files

When filtering the list, fzf will ignore any diacritics in the filename, so typing ha filters the list down to Changes and hätte.test.

filtered to hätte.test and Changes

Typing an actual umlaut there respects the diacritics and thus filters the list immediately down to hätte.test.

filtered to hätte.test

In other situations, I can't readily shell out to fzf. Maybe because it is in a web context or somewhere where I don't want to install fzf. For that situation, I wrote (and now released) String::FuzzyMatch. The module provides a class where you can do such fuzzy filtering and highlighting on your strings.

my $filter = String::FuzzyFind->new(
    highlight_start => '[',
    highlight_end => ']',
);

$filter->filter( 'ab', ['aab','abc','acb','cba','aaa', 'abab'] );
# ['aab','abc','acb','abab' ]

# HTML highlighting
my $html = String::FuzzyFind->new(
    highlight_cb => sub( $match ) {
        return join '',
            '<highlight>',
            html_escape($match),
            '</highlight>',
    };
);
$html->highlight( 'ab', 'Now Playing: äbändön' );
# 'Now Playing: <highlight>äb</highlight>'

$html->highlight( 'r&d', 'Welcome to R & D' );
# 'Welcome to <highlight>R</highlight> <highlight>&amp;</highlight> <highlight>D</highlight>'

This approach is quite convenient, because it allows me to have both, a clicky menu when I'm working on a touch-enabled device, and some quick-access text entry box where I can type in a short code that matches whatever rare letters there are in the menu to select an option.

Writing the code was a fun exercise. The nice people at Perlmonks pointed me towards the appropirate Unicode properties to match or remove respectively. Then came a quick reminder about NFD, NFC and how I need consistency in my test suite and my code about when I'm returning what. In the end, I settled on accepting any encoding but converting and returning the original code while filtering a list and returning NFD when highlighting a string.

Using the Perl 'class' feature

Tags:

I'm not really deep into class design, Metaobject protocols and object-oriented programming, but one feature I've come to like with Perl is using roles to mix-in methods that are convenient to have but tedious to reimplement ad-hoc. Roles can be implemented via multiple inheritance, but they (try to) avoid problems by being designed more around adding self-contained features and not overriding methods in the descendant class.

For example MooX::Role::DBIConnection gives a class a lazy ->dbh accessor and a nice way to supply database credentials in the constructor. I'm not claiming that this is the best way to approach this, but it makes managing the credentials and constructing the database handle very convenient.

{ package My::Example;
  use Moo 2;
  with 'MooX::Role::DBIConnection';
};
# Lazily connect using the parameters
my $writer = My::Example->new(
    dbh => {
        dsn  => '...',
        user => '...',
        password => '...',
        options => '...',
    },
);

my $count = $writer->dbh->selectall_arrayref("select count(*) from mytable")->[0]->[0];

The other thing that roles, or at least Moo::Role brings to the table is checking that the target class the role is applied to provides some methods, using the requires keyword. This checks the contract at compile time instead of needing to exercise the code in the test suite.

I spent some hours revisiting Protocol::Samsung::MDC to talk to my Samsung EM32DX, and I reimplemented it using the "new" class feature, using a Perl-built-in object model. The class feature is still experimental and the finer points are still being worked on, but for my use-case it worked quite well.

One thing I was missing was a convenient way to emit events from an object. Emitting events makes for a (IMO) nicer code structure than hooking up callbacks, as I don't have to set up all callbacks in the constructor, and have a centralized dispatch mechanism for all events within an object.

package main;
my $foo = My::Thing->new();
$foo->on( myevent => sub( $ev ) {
    say "I receivend an event";
});

The basic code is well-tested, originally in Mojo::EventEmitter, and also available outside of Mojolicious as Role::EventEmitter and my almost identical MooX::Role::EventEmitter.

The class feature has no provision yet on how to interact with bless-based classes, so reusing these modules did not work. But copying the code into a class-based module did work, with the one thing missing - no implicit checking of methods and fields in the target class:

use experimental 'class';
class My::Thing :isa(PerlX::Role::EventEmitter);
use 5.020;
use experimental 'signatures';

sub event_received( $self, $ev ) {
    $self->emit( myevent => $ev );
}
...

Maybe one could implement the check for the required members and functions in the ADJUST phase of the role, but as some day the class feature might gain native support for roles (or acquire a sibling role keyword), I'm happy to let my test suite suss out missing methods.