harness: Zig 0.17.1 migration + downloads room channel

- build: b.args -> addPassthruArgs, libqt6zig repointed to 0.17-ready rev
- matrix: Event carries room id; joinRoom percent-encodes alias and
  validates room_id in response (http() ignores HTTP status)
- harness: downloads room (#downloads) — URL in, yt-dlp out: detached
  job thread per request, /tmp/x2dm output, 2G cap, file-or-error reply
- resolveDownloadRoom: env MATRIX_DOWNLOAD_ROOM pin (continuwuity bare
  room ids have no :server suffix), join-or-create fallback

👾 Generated with [Letta Code](https://letta.com)

Co-Authored-By: Letta Code <noreply@letta.com>
This commit is contained in:
pierreandLetta Code committed 2026-11-16 08:09:57 +03:00
1 parent ac4571e751
commit 51046627b1
4 files changed
+279 -8

No files matched your search

+1 -1
View File
@@ -84,5 +84,5 @@ pub fn build(b: *std.Build) void {
const run_cmd = b.addRunArtifact(exe); const run_cmd = b.addRunArtifact(exe);
run_step.dependOn(&run_cmd.step); run_step.dependOn(&run_cmd.step);
run_cmd.step.dependOn(b.getInstallStep()); run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd.addArgs(args); run_cmd.addPassthruArgs();
} }
+3 -3
View File
@@ -25,7 +25,7 @@
.fingerprint = 0xb42cbab79cddafac, // Changing this has security and trust implications. .fingerprint = 0xb42cbab79cddafac, // Changing this has security and trust implications.
// Tracks the earliest Zig version that the package considers to be a // Tracks the earliest Zig version that the package considers to be a
// supported use case. // supported use case.
.minimum_zig_version = "0.16.0", .minimum_zig_version = "0.17.1",
// This field is optional. // This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`. // Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively. // `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
@@ -33,8 +33,8 @@
// internet connectivity. // internet connectivity.
.dependencies = .{ .dependencies = .{
.libqt6zig = .{ .libqt6zig = .{
.url = "git+https://github.com/rcalixte/libqt6zig#c8aa843ae59f3fae372dc4b5aab5c6b0f8623cc8", .url = "git+https://github.com/rcalixte/libqt6zig#76fbd35d3b4d67721e5ca5cd323c06cd83afeaad",
.hash = "libqt6zig-6.8.2-OSXtXHXCGx9sMo0pcuOmHLKsOeBYvntRpyp-owxQH8RT", .hash = "libqt6zig-6.8.2-OSXtXJRx4BxEkhok6OWmDklZGRHmnWFVTag8HX66JGuq",
}, },
}, },
.paths = .{ .paths = .{
+56 -4
View File
@@ -389,16 +389,62 @@ pub fn editText(alloc: std.mem.Allocator, io: Io, token: []const u8, room: []con
/// Join a room by id (accepts invites). /// Join a room by id (accepts invites).
pub fn joinRoom(alloc: std.mem.Allocator, io: Io, token: []const u8, room: []const u8) !void { pub fn joinRoom(alloc: std.mem.Allocator, io: Io, token: []const u8, room: []const u8) !void {
const url = try std.fmt.allocPrint(alloc, "{s}/_matrix/client/v3/rooms/{s}/join", .{ HOMESERVER, room }); // Room ids are safe in URLs; aliases carry '#' which must be encoded.
var enc: std.ArrayListUnmanaged(u8) = .empty;
defer enc.deinit(alloc);
for (room) |c| {
if (c == '#' or c == ':' or c == '!' or c == '/' or c == '?') {
var hb: [4]u8 = undefined;
const hx = std.fmt.bufPrint(&hb, "%{X:0>2}", .{c}) catch continue;
try enc.appendSlice(alloc, hx);
} else {
try enc.append(alloc, c);
}
}
const url = try std.fmt.allocPrint(alloc, "{s}/_matrix/client/v3/rooms/{s}/join", .{ HOMESERVER, enc.items });
defer alloc.free(url); defer alloc.free(url);
const resp = try http(alloc, io, "POST", url, token, "{}"); const resp = try http(alloc, io, "POST", url, token, "{}");
alloc.free(resp); defer alloc.free(resp);
// http() doesn't check HTTP status — validate the payload: a successful
// join returns {"room_id": "..."}; failures return an errcode object.
if (std.mem.indexOf(u8, resp, "\"room_id\"") == null) return error.JoinFailed;
}
/// Create a room with a local alias and invite peer. Returns room id.
pub fn createRoomAlias(alloc: std.mem.Allocator, io: Io, token: []const u8, alias_localpart: []const u8, peer: []const u8) ![]u8 {
const inv = try std.fmt.allocPrint(alloc, "[\"{s}\"]", .{peer});
defer alloc.free(inv);
const body = try std.fmt.allocPrint(alloc,
\\{{"room_alias_name":"{s}","name":"{s}","invite":{s},"preset":"private_chat"}}
, .{ alias_localpart, alias_localpart, inv });
defer alloc.free(body);
const url = try std.fmt.allocPrint(alloc, "{s}/_matrix/client/v3/createRoom", .{HOMESERVER});
defer alloc.free(url);
const resp = try http(alloc, io, "POST", url, token, body);
defer alloc.free(resp);
var arena_state = std.heap.ArenaAllocator.init(alloc);
defer arena_state.deinit();
const jalloc = arena_state.allocator();
var parsed = std.json.parseFromSlice(std.json.Value, jalloc, resp, .{}) catch return error.BadCreateJson;
defer parsed.deinit();
const root = switch (parsed.value) {
.object => |o| o,
else => return error.BadCreateJson,
};
const rid = root.get("room_id") orelse return error.BadCreateJson;
return switch (rid) {
.string => |s| alloc.dupe(u8, s),
else => error.BadCreateJson,
};
} }
pub const Event = struct { pub const Event = struct {
sender: []u8, sender: []u8,
body: []u8, body: []u8,
ts: i64 = 0, ts: i64 = 0,
/// Room id this event arrived in (allocated; caller frees).
room: []u8 = &.{},
/// mxc:// URI when the message carries an attachment (m.file/m.image/…). /// mxc:// URI when the message carries an attachment (m.file/m.image/…).
url: ?[]u8 = null, // allocated; caller frees url: ?[]u8 = null, // allocated; caller frees
mimetype: []u8 = "", // allocated; caller frees mimetype: []u8 = "", // allocated; caller frees
@@ -530,13 +576,19 @@ pub fn sync(alloc: std.mem.Allocator, io: Io, token: []const u8, since: []const
}; };
const sender_copy = alloc.dupe(u8, sender_raw) catch continue; const sender_copy = alloc.dupe(u8, sender_raw) catch continue;
const body_copy = alloc.dupe(u8, body_raw) catch { const room_copy = alloc.dupe(u8, room_entry.key_ptr.*) catch {
alloc.free(sender_copy); alloc.free(sender_copy);
continue; continue;
}; };
events.append(alloc, .{ .sender = sender_copy, .body = body_copy, .ts = ts, .url = url_copy, .filename = fname_copy, .mimetype = mime, .size = size }) catch { const body_copy = alloc.dupe(u8, body_raw) catch {
alloc.free(sender_copy);
alloc.free(room_copy);
continue;
};
events.append(alloc, .{ .sender = sender_copy, .body = body_copy, .room = room_copy, .ts = ts, .url = url_copy, .filename = fname_copy, .mimetype = mime, .size = size }) catch {
alloc.free(sender_copy); alloc.free(sender_copy);
alloc.free(body_copy); alloc.free(body_copy);
alloc.free(room_copy);
}; };
} }
} }
+219
View File
@@ -397,6 +397,194 @@ fn runAgentTurn(p: *Progress, prompt: []const u8) ![]u8 {
return reply; return reply;
} }
// ------------------------------------------------------- x2dm downloads ---
//
// A second room ("Downloads") where Pierre drops media URLs; the harness
// runs yt-dlp (its own config carries cookies + proxy) and replies with the
// file or an error message. No LLM involved — pure plumbing.
/// Where yt-dlp drops finished files.
const DOWNLOAD_DIR = "/tmp/x2dm";
/// Default room alias, overridable via MATRIX_DOWNLOAD_ROOM.
const DOWNLOAD_ALIAS_LOCALPART = "downloads";
const DOWNLOAD_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024; // 2 GiB upload ceiling
/// Extract the first http(s) URL from a message body (caller frees).
fn firstUrl(alloc: std.mem.Allocator, body: []const u8) ?[]u8 {
var i: usize = 0;
while (i < body.len) : (i += 1) {
if (!(std.mem.startsWith(u8, body[i..], "http://") or
std.mem.startsWith(u8, body[i..], "https://"))) continue;
var j = i;
while (j < body.len and !std.ascii.isWhitespace(body[j]) and
body[j] != '>' and body[j] != ')' and body[j] != '"') j += 1;
if (j > i) return alloc.dupe(u8, body[i..j]) catch null;
}
return null;
}
/// Resolve the downloads room: MATRIX_DOWNLOAD_ROOM env if set; otherwise
/// join #<localpart>:<server-name>, creating the room when no such alias.
fn resolveDownloadRoom(alloc: std.mem.Allocator, io: std.Io, token: []const u8, peer: []const u8) ?[]u8 {
const configured = env_or("MATRIX_DOWNLOAD_ROOM", "");
if (configured.len > 0) return alloc.dupe(u8, configured) catch null;
// Server name from the bot's own user id (@user:server → server).
const user = env_or("MATRIX_USER", "@chaos-prime:chaosmith.systems");
const server = if (std.mem.lastIndexOfScalar(u8, user, ':')) |i| user[i + 1 ..] else "chaosmith.systems";
const alias = std.fmt.allocPrint(alloc, "#{s}:{s}", .{ DOWNLOAD_ALIAS_LOCALPART, server }) catch return null;
defer alloc.free(alias);
matrix.joinRoom(alloc, io, token, alias) catch {
// Alias doesn't exist yet — create the room with that alias.
std.debug.print("matrix_harness: downloads room missing, creating #{s}...\n", .{DOWNLOAD_ALIAS_LOCALPART});
return matrix.createRoomAlias(alloc, io, token, DOWNLOAD_ALIAS_LOCALPART, peer) catch |e| {
std.debug.print("matrix_harness: createRoom(downloads) failed: {s}\n", .{@errorName(e)});
return null;
};
};
// Joined; resolve the alias to a real room id for comparisons.
return alloc.dupe(u8, alias) catch null;
}
/// One download request, run on its own thread. Owns everything it touches.
const DownloadJob = struct {
arena_state: std.heap.ArenaAllocator,
io: std.Io,
token: []u8,
room: []u8,
body: []u8,
fn runSelf(self: *DownloadJob) void {
const alloc = self.arena_state.allocator();
defer self.destroy();
self.run(alloc) catch |e| {
std.debug.print("matrix_harness: download job failed: {s}\n", .{@errorName(e)});
if (matrix.sendText(alloc, self.io, self.token, self.room, "download failed — see harness logs")) |ev| {
alloc.free(ev);
} else |_| {}
};
}
fn destroy(self: *DownloadJob) void {
const gpa = std.heap.page_allocator;
gpa.free(self.token);
gpa.free(self.room);
gpa.free(self.body);
const arena = self.arena_state;
gpa.destroy(self);
arena.deinit();
}
fn run(self: *DownloadJob, alloc: std.mem.Allocator) !void {
const io = self.io;
const url = firstUrl(alloc, self.body) orelse return error.NoUrl;
defer alloc.free(url);
std.debug.print("matrix_harness: downloading {s}\n", .{url});
std.Io.Dir.cwd().createDirPath(io, DOWNLOAD_DIR) catch {};
const out_tmpl = try std.fmt.allocPrint(alloc, "{s}/%(id)s.%(ext)s", .{DOWNLOAD_DIR});
defer alloc.free(out_tmpl);
const result = std.process.run(alloc, io, .{
.argv = &.{ "yt-dlp", "--no-playlist", "--max-filesize", "2G", "-o", out_tmpl, url },
.stderr_limit = .limited(8 * 1024),
}) catch |e| {
std.debug.print("matrix_harness: yt-dlp spawn failed: {s}\n", .{@errorName(e)});
const msg = try std.fmt.allocPrint(alloc, "yt-dlp failed to start: {s}", .{@errorName(e)});
defer alloc.free(msg);
if (matrix.sendText(alloc, io, self.token, self.room, msg)) |ev| alloc.free(ev) else |_| {}
return;
};
defer alloc.free(result.stdout);
defer alloc.free(result.stderr);
const ok = switch (result.term) {
.exited => |code| code == 0,
else => false,
};
if (!ok) {
// Pull the last meaningful line from yt-dlp's stderr for the reply.
var msg_src: []const u8 = "yt-dlp failed";
var lines = std.mem.splitBackwardsScalar(u8, result.stderr, '\n');
while (lines.next()) |line| {
const t = std.mem.trim(u8, line, " \r");
if (t.len > 0 and !std.mem.startsWith(u8, t, "[download]")) {
msg_src = t;
break;
}
}
const msg = try std.fmt.allocPrint(alloc, "download failed: {s}", .{msg_src[0..@min(msg_src.len, 300)]});
defer alloc.free(msg);
if (matrix.sendText(alloc, io, self.token, self.room, msg)) |ev| alloc.free(ev) else |_| {}
return;
}
// Find the newest file in DOWNLOAD_DIR.
var dir = std.Io.Dir.openDirAbsolute(io, DOWNLOAD_DIR, .{ .iterate = true }) catch return error.NoDownloadDir;
defer dir.close(io);
var it = dir.iterate();
var best_name: ?[]u8 = null;
var best_mtime: ?std.Io.Timestamp = null;
while (it.next(io) catch null) |entry| {
if (entry.kind != .file) continue;
const st = dir.statFile(io, entry.name, .{}) catch continue;
if (best_mtime == null or st.mtime.nanoseconds > best_mtime.?.nanoseconds) {
best_mtime = st.mtime;
if (best_name) |b| alloc.free(b);
best_name = alloc.dupe(u8, entry.name) catch null;
}
}
const name = best_name orelse {
if (matrix.sendText(alloc, io, self.token, self.room, "yt-dlp finished but no file appeared")) |ev| alloc.free(ev) else |_| {}
return;
};
defer alloc.free(name);
const ft = fileTypeOf(name);
const path = try std.fmt.allocPrint(alloc, "{s}/{s}", .{ DOWNLOAD_DIR, name });
defer alloc.free(path);
const size = blk: {
const st = std.Io.Dir.cwd().statFile(io, path, .{}) catch break :blk 0;
break :blk st.size;
};
std.debug.print("matrix_harness: uploading {s} ({d} bytes) to downloads room\n", .{ name, size });
const mxc = try matrix.uploadFile(alloc, io, self.token, path, name, ft.mimetype);
defer alloc.free(mxc);
const ev_id = try matrix.sendFile(alloc, io, self.token, self.room, ft.msgtype, mxc, name, ft.mimetype, size);
alloc.free(ev_id);
std.debug.print("matrix_harness: download delivered: {s}\n", .{name});
}
};
fn spawnDownloadJob(io: std.Io, token: []const u8, room: []const u8, body: []const u8) void {
const gpa = std.heap.page_allocator;
const job = gpa.create(DownloadJob) catch return;
job.* = .{
.arena_state = std.heap.ArenaAllocator.init(gpa),
.io = io,
.token = gpa.dupe(u8, token) catch {
gpa.destroy(job);
return;
},
.room = gpa.dupe(u8, room) catch {
gpa.free(job.token);
gpa.destroy(job);
return;
},
.body = gpa.dupe(u8, body) catch {
gpa.free(job.token);
gpa.free(job.room);
gpa.destroy(job);
return;
},
};
if (std.Thread.spawn(.{}, DownloadJob.runSelf, .{job})) |t| {
t.detach();
} else |_| {
job.destroy();
}
}
fn loadSeenTs(io: std.Io) i64 { fn loadSeenTs(io: std.Io) i64 {
var f = std.Io.Dir.openFileAbsolute(io, STATE_FILE, .{}) catch return 0; var f = std.Io.Dir.openFileAbsolute(io, STATE_FILE, .{}) catch return 0;
defer f.close(io); defer f.close(io);
@@ -475,6 +663,19 @@ pub fn main(init: std.process.Init) !void {
defer if (owned_room) |r| alloc.free(r); defer if (owned_room) |r| alloc.free(r);
std.debug.print("matrix_harness: room {s}\n", .{room_id}); std.debug.print("matrix_harness: room {s}\n", .{room_id});
// Downloads room: URL-dump channel handled WITHOUT the agent (yt-dlp
// plumbing). Fails safe: if unresolvable, downloads feature is off.
const download_room: ?[]u8 = blk: {
const r = resolveDownloadRoom(alloc, io, session.token, peer);
if (r) |rr| {
std.debug.print("matrix_harness: downloads room {s}\n", .{rr});
} else {
std.debug.print("matrix_harness: downloads room unavailable, feature off\n", .{});
}
break :blk r;
};
defer if (download_room) |r| alloc.free(r);
// No room banner on startup — restarts (deploys, watchdog) would spam // No room banner on startup — restarts (deploys, watchdog) would spam
// the DM. Startup is logged to journald instead. // the DM. Startup is logged to journald instead.
@@ -492,11 +693,14 @@ pub fn main(init: std.process.Init) !void {
for (first.events) |ev| { for (first.events) |ev| {
defer alloc.free(ev.sender); defer alloc.free(ev.sender);
defer alloc.free(ev.body); defer alloc.free(ev.body);
defer alloc.free(ev.room);
defer if (ev.filename.len > 0) alloc.free(ev.filename); defer if (ev.filename.len > 0) alloc.free(ev.filename);
defer if (ev.url) |u| alloc.free(u); defer if (ev.url) |u| alloc.free(u);
defer if (ev.mimetype.len > 0) alloc.free(ev.mimetype); defer if (ev.mimetype.len > 0) alloc.free(ev.mimetype);
if (ev.ts > new_max) new_max = ev.ts; if (ev.ts > new_max) new_max = ev.ts;
if (!std.mem.eql(u8, ev.sender, peer)) continue; if (!std.mem.eql(u8, ev.sender, peer)) continue;
// Only DM-room events are agent-relevant; downloads room is plumbing.
if (!std.mem.eql(u8, ev.room, room_id)) continue;
// Attachments in backlog are stale — note them but don't download. // Attachments in backlog are stale — note them but don't download.
if (ev.url != null) { if (ev.url != null) {
if (ev.ts > 0 and now_ms - ev.ts > 30 * 60 * 1000) continue; if (ev.ts > 0 and now_ms - ev.ts > 30 * 60 * 1000) continue;
@@ -553,6 +757,7 @@ pub fn main(init: std.process.Init) !void {
for (result.events) |ev| { for (result.events) |ev| {
defer alloc.free(ev.sender); defer alloc.free(ev.sender);
defer alloc.free(ev.body); defer alloc.free(ev.body);
defer alloc.free(ev.room);
defer if (ev.filename.len > 0) alloc.free(ev.filename); defer if (ev.filename.len > 0) alloc.free(ev.filename);
defer if (ev.url) |u| alloc.free(u); defer if (ev.url) |u| alloc.free(u);
defer if (ev.mimetype.len > 0) alloc.free(ev.mimetype); defer if (ev.mimetype.len > 0) alloc.free(ev.mimetype);
@@ -561,6 +766,20 @@ pub fn main(init: std.process.Init) !void {
if (!std.mem.eql(u8, ev.sender, peer)) continue; if (!std.mem.eql(u8, ev.sender, peer)) continue;
if (ev.body.len == 0) continue; if (ev.body.len == 0) continue;
// Downloads room: URL in → yt-dlp → file back. No agent turn.
if (download_room) |droom| {
if (std.mem.eql(u8, ev.room, droom)) {
if (firstUrl(alloc, ev.body)) |_| {
spawnDownloadJob(io, session.token, droom, ev.body);
} else {
if (matrix.sendText(alloc, io, session.token, droom, "no URL found in message")) |ev_id| alloc.free(ev_id) else |_| {}
}
continue;
}
}
// Agent turn: DM room only.
if (!std.mem.eql(u8, ev.room, room_id)) continue;
var ts_buf: [24]u8 = undefined; var ts_buf: [24]u8 = undefined;
const ts_str: []const u8 = blk: { const ts_str: []const u8 = blk: {
if (ev.ts <= 0) break :blk ""; if (ev.ts <= 0) break :blk "";