1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
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
217
218
219
220
221
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
|
-- OpenCode integration for micro editor
--
-- This plugin allows you to send messages to OpenCode sessions via the OpenCode HTTP server.
--
-- Setup:
-- 1. Start the OpenCode server:
-- opencode serve --port 4096
--
-- 2. (Optional) Set OPENCODE_PORT in your shell config if using a different port:
-- export OPENCODE_PORT=4096
--
-- Commands:
-- sendToAgent [message] - Send selected text or message to an OpenCode session
-- agentPrevPosition - Navigate to previous agent edit position
-- agentNextPosition - Navigate to next agent edit position
-- agentClearSession - Clear the remembered session (forces re-selection)
--
-- How it works:
-- The plugin lists all sessions from the server and lets you select one (using gum).
-- It remembers your last selected session, so you don't have to select it every time.
-- Use agentClearSession to switch to a different session.
--
local micro = import("micro")
local config = import("micro/config")
local filepath = import("filepath")
local shell = import("micro/shell")
local util = import("micro/util")
local os = import("os")
-- Store the last agent edit position we navigated to
-- Format: {path = "/path/to/file", line = 42}
local lastAgentPosition = nil
-- Store the last selected OpenCode session
-- Format: {id = "ses_...", title = "...", directory = "..."}
local lastOpencodeSession = nil
-- OpenCode server configuration
-- Can be overridden by setting OPENCODE_PORT environment variable
local function getEnvOrDefault(key, default)
local value = os.Getenv(key)
if not value or value == "" then
return default
end
return value
end
local OPENCODE_HOST = getEnvOrDefault("OPENCODE_HOST", "127.0.0.1")
local OPENCODE_PORT = getEnvOrDefault("OPENCODE_PORT", "4096")
-- HTTP request helper using curl
-- Returns: output string, error (nil on success)
local function httpRequest(method, endpoint, jsonBody)
local url = string.format("http://%s:%s%s", OPENCODE_HOST, OPENCODE_PORT, endpoint)
local cmd
if method == "GET" then
cmd = string.format("curl -s '%s' 2>&1", url)
elseif method == "POST" then
if jsonBody then
-- Escape single quotes in JSON body
local escapedBody = jsonBody:gsub("'", "'\\''")
cmd = string.format("curl -s -X POST -H 'Content-Type: application/json' -d '%s' '%s' 2>&1",
escapedBody, url)
else
cmd = string.format("curl -s -X POST '%s' 2>&1", url)
end
else
return nil, "Unsupported HTTP method: " .. method
end
local handle = io.popen(cmd)
if not handle then
return nil, "Failed to execute curl"
end
local output = handle:read("*a")
handle:close()
-- Check if output looks like an error (contains "curl:" or is empty)
if not output or output == "" or output:match("^curl:") then
return nil, output or "Empty response"
end
return output, nil
end
-- Escape a string for JSON
local function jsonEscape(str)
str = str:gsub("\\", "\\\\")
str = str:gsub('"', '\\"')
str = str:gsub("\n", "\\n")
str = str:gsub("\r", "\\r")
str = str:gsub("\t", "\\t")
return str
end
-- Format milliseconds since epoch to "X ago" string
local function formatTimeAgo(timestamp)
if not timestamp then return "unknown" end
local now = _G.os.time() * 1000 -- Convert to milliseconds
local diff = now - timestamp
local seconds = math.floor(diff / 1000)
if seconds < 60 then
return "just now"
elseif seconds < 3600 then
local mins = math.floor(seconds / 60)
return string.format("%dm ago", mins)
elseif seconds < 86400 then
local hours = math.floor(seconds / 3600)
return string.format("%dh ago", hours)
else
local days = math.floor(seconds / 86400)
return string.format("%dd ago", days)
end
end
-- Detect an uppercase PLAN marker at the start of the FIRST matching line
-- and strip only that occurrence. The marker can be a line on its own, or a
-- "PLAN <rest of prompt>" prefix. Returns: cleanedMessage, agent ("plan" or nil)
local function detectAgentMode(message)
local agent = nil
local lines = {}
for line in (message .. "\n"):gmatch("(.-)\n") do
if agent == nil and line:match("^%s*PLAN%s*$") then
-- First match, whole line is just the marker: drop the line entirely.
agent = "plan"
elseif agent == nil and line:match("^%s*PLAN%s+") then
-- First match, "PLAN <rest>": keep the rest of the line.
agent = "plan"
table.insert(lines, (line:match("^%s*PLAN%s+(.*)$")))
else
-- Not the first match (or no match): leave the line untouched.
table.insert(lines, line)
end
end
return table.concat(lines, "\n"), agent
end
-- Parse JSON array of sessions using jq
local function parseSessionList(jsonStr)
local sessions = {}
-- Use jq to extract session info in a parseable format
-- Output: id|title|directory|timeUpdated (one per line)
local jqCmd = string.format("echo '%s' | jq -r '.[] | \"\\(.id)|\\(.title)|\\(.directory)|\\(.time.updated)\"'",
jsonStr:gsub("'", "'\\''"))
local handle = io.popen(jqCmd)
if not handle then
return sessions
end
for line in handle:lines() do
local id, title, directory, timeUpdated = line:match("^([^|]+)|([^|]+)|([^|]+)|([^|]*)$")
if id then
table.insert(sessions, {
id = id,
title = title,
directory = directory,
timeUpdated = tonumber(timeUpdated)
})
end
end
handle:close()
return sessions
end
-- Check if OpenCode server is running
local function checkServer()
local output, err = httpRequest("GET", "/app")
if err then
local msg = string.format("OpenCode server not reachable at %s:%s\nSet OPENCODE_PORT env var if using a different port.\nError: %s",
OPENCODE_HOST, OPENCODE_PORT, err)
return false, msg
end
return true, nil
end
function agentPrevPosition(bp, args)
-- Use last tracked position if available, otherwise use current cursor position
local queryPath, queryLine
if lastAgentPosition then
queryPath = lastAgentPosition.path
queryLine = lastAgentPosition.line
else
queryPath = bp.Buf.Path
queryLine = bp.Cursor.Y + 1 -- Convert to 1-based
end
if not queryPath or queryPath == "" then
micro.InfoBar():Error("No file path - save the buffer first")
return
end
-- Call agent-last-position prev with the tracked position
local cmd = string.format("agent-last-position prev '%s' %d 2>&1", queryPath, queryLine)
local handle = io.popen(cmd)
if not handle then
micro.InfoBar():Error("Failed to run agent-last-position")
return
end
local output = handle:read("*a")
local success = handle:close()
-- If command failed (non-zero exit), we're at the beginning of history
if not success then
micro.InfoBar():Message("⏮️ At beginning of edit history")
return
end
-- Parse path:line format
local trimmed = output:match("^%s*(.-)%s*$")
-- Empty output means no history
if not trimmed or trimmed == "" then
micro.InfoBar():Message("⏮️ At beginning of edit history")
return
end
local path, line = trimmed:match("^(.+):(%d+)$")
if not path or not line then
micro.InfoBar():Error("Invalid response format: " .. output)
return
end
-- Update tracked position before navigating
lastAgentPosition = {path = path, line = tonumber(line)}
-- Navigate to the previous position
local newTab = OpenTabFromFile(bp, path, tonumber(line))
if newTab then
micro.InfoBar():Message(string.format("⏮️ Previous: %s:%d", filepath.Base(path), tonumber(line)))
else
micro.InfoBar():Error("Failed to open: " .. path)
end
end
function agentNextPosition(bp, args)
-- Use last tracked position if available, otherwise use current cursor position
local queryPath, queryLine
if lastAgentPosition then
queryPath = lastAgentPosition.path
queryLine = lastAgentPosition.line
else
queryPath = bp.Buf.Path
queryLine = bp.Cursor.Y + 1 -- Convert to 1-based
end
if not queryPath or queryPath == "" then
micro.InfoBar():Error("No file path - save the buffer first")
return
end
-- Call agent-last-position next with the tracked position
local cmd = string.format("agent-last-position next '%s' %d 2>&1", queryPath, queryLine)
local handle = io.popen(cmd)
if not handle then
micro.InfoBar():Error("Failed to run agent-last-position")
return
end
local output = handle:read("*a")
local success = handle:close()
-- If command failed (non-zero exit), we're at the end of history
if not success then
micro.InfoBar():Message("⏭️ At end of edit history")
return
end
-- Parse path:line format
local trimmed = output:match("^%s*(.-)%s*$")
-- Empty output means no history
if not trimmed or trimmed == "" then
micro.InfoBar():Message("⏭️ At end of edit history")
return
end
local path, line = trimmed:match("^(.+):(%d+)$")
if not path or not line then
micro.InfoBar():Error("Invalid response format: " .. output)
return
end
-- Update tracked position before navigating
lastAgentPosition = {path = path, line = tonumber(line)}
-- Navigate to the next position
local newTab = OpenTabFromFile(bp, path, tonumber(line))
if newTab then
micro.InfoBar():Message(string.format("⏭️ Next: %s:%d", filepath.Base(path), tonumber(line)))
else
micro.InfoBar():Error("Failed to open: " .. path)
end
end
function agentClearSession(bp, args)
if lastOpencodeSession then
local oldSession = lastOpencodeSession.title
lastOpencodeSession = nil
micro.InfoBar():Message("Cleared session selection: " .. oldSession)
else
micro.InfoBar():Message("No session was selected")
end
end
function sendToAgent(bp, args)
-- Check if server is running
local serverOk, serverErr = checkServer()
if not serverOk then
micro.InfoBar():Error(serverErr)
return
end
-- Get all sessions from OpenCode server
local sessionsJson, err = httpRequest("GET", "/session")
if err then
micro.InfoBar():Error("Failed to list sessions: " .. err)
return
end
local sessions = parseSessionList(sessionsJson)
if #sessions == 0 then
micro.InfoBar():Error("No OpenCode sessions found")
return
end
-- Select session
local selectedSession
-- If we have a last selected session and it's still in the list, use it
if lastOpencodeSession then
local found = false
for _, sess in ipairs(sessions) do
if sess.id == lastOpencodeSession.id then
found = true
selectedSession = sess
break
end
end
if found then
micro.InfoBar():Message("Using last OpenCode session: " .. selectedSession.title)
else
-- Session no longer exists, clear it and inform user
micro.InfoBar():Message("Session '" .. lastOpencodeSession.title .. "' no longer exists, selecting new session...")
lastOpencodeSession = nil
end
end
-- If we don't have a selection yet, prompt for one
if not selectedSession then
if #sessions == 1 then
selectedSession = sessions[1]
micro.InfoBar():Message("Using OpenCode session: " .. selectedSession.title)
else
-- Multiple sessions - use gum to select
-- Check if gum exists
local gumCheck = io.popen("command -v gum 2>/dev/null")
local gumPath = gumCheck:read("*l")
gumCheck:close()
if not gumPath or gumPath == "" then
micro.InfoBar():Error("Multiple OpenCode sessions found, but gum is not installed")
return
end
-- Build gum command with session info as arguments
-- Show title, directory, and time for context
local sessionChoices = {}
for _, sess in ipairs(sessions) do
local dirName = sess.directory:match("([^/]+)$") or sess.directory
local timeAgo = formatTimeAgo(sess.timeUpdated)
table.insert(sessionChoices, string.format("%s [%s] (%s)", sess.title, dirName, timeAgo))
end
-- Write choices to temp file for gum (safer than command line args)
local choicesFile = string.format("%s/micro-gum-choices-%d.txt", os.TempDir(), _G.os.time())
local f = io.open(choicesFile, "w")
if not f then
micro.InfoBar():Error("Failed to create temp file for session selection")
return
end
f:write(table.concat(sessionChoices, "\n"))
f:close()
local gumCmd = string.format("sh -c \"cat '%s' | gum choose --header 'Select OpenCode session:'\"", choicesFile)
-- Use RunInteractiveShell for gum
local output, gumErr = shell.RunInteractiveShell(gumCmd, false, true)
os.Remove(choicesFile)
if gumErr ~= nil then
micro.InfoBar():Error("Failed to run gum: " .. tostring(gumErr))
return
end
local selectedChoice = output:match("^%s*(.-)%s*$") -- trim whitespace
if not selectedChoice or selectedChoice == "" then
micro.InfoBar():Message("No session selected")
return
end
-- Find the session by matching the choice
for i, choice in ipairs(sessionChoices) do
if choice == selectedChoice then
selectedSession = sessions[i]
break
end
end
if not selectedSession then
micro.InfoBar():Error("Could not find selected session")
return
end
end
end
-- Remember the previously remembered session so we can restore it if the
-- user aborts (e.g. empties the message). We only commit the new selection
-- once we know the message will actually be sent.
local previousOpencodeSession = lastOpencodeSession
lastOpencodeSession = selectedSession
-- Build the initial message
local message
local cursor = bp.Cursor
local filePath = bp.Buf.Path
if cursor:HasSelection() then
-- Get selected text
local selectionBytes = cursor:GetSelection()
local selection = util.String(selectionBytes)
-- Get the line range of the selection
local startLine = cursor.CurSelection[1].Y + 1 -- Convert to 1-based
local endLine = cursor.CurSelection[2].Y + 1
local lineCount = endLine - startLine + 1
-- Build prompt with selection context
-- Only include text for short selections (< 10 lines)
if lineCount < 10 then
message = string.format("Look at %s lines %d–%d, I have the following comments:\n\n%s",
filePath, startLine, endLine, selection)
else
message = string.format("Look at %s lines %d–%d, I have the following comments:\n\n",
filePath, startLine, endLine)
end
else
-- No selection - use args if provided, otherwise error
if #args > 0 then
message = table.concat(args, " ")
else
micro.InfoBar():Error("No selection and no message provided")
return
end
end
-- Write message to temp file with unique name
-- Use _G.os.time() to access standard Lua os library (local 'os' is Micro's module)
local tmpfile = string.format("%s/micro-opencode-msg-%d.txt", os.TempDir(), _G.os.time())
local f = io.open(tmpfile, "w")
if not f then
micro.InfoBar():Error("Failed to create temp file")
lastOpencodeSession = previousOpencodeSession
return
end
-- Add two empty lines at the end for cursor positioning
local messageWithEmptyLines = message .. "\n\n"
f:write(messageWithEmptyLines)
f:close()
-- Count lines in message to position cursor at the last empty line
local lineCount = 1
for _ in message:gmatch("\n") do
lineCount = lineCount + 1
end
local cursorLine = lineCount + 2 -- Position at the second empty line we added
-- Spawn micro to edit the message with cursor at the end
micro.InfoBar():Message("Opening message in micro for editing...")
local editCmd = string.format("micro '%s:%d'", tmpfile, cursorLine)
local output, editErr = shell.RunInteractiveShell(editCmd, false, false)
if editErr ~= nil then
micro.InfoBar():Error("Failed to edit message: " .. tostring(editErr))
os.Remove(tmpfile)
lastOpencodeSession = previousOpencodeSession
return
end
-- Read the edited message back
local readFile = io.open(tmpfile, "r")
if not readFile then
micro.InfoBar():Error("Failed to read edited message")
os.Remove(tmpfile)
lastOpencodeSession = previousOpencodeSession
return
end
local editedMessage = readFile:read("*a")
readFile:close()
-- Trim whitespace and check if empty
local trimmedMessage = editedMessage and editedMessage:match("^%s*(.-)%s*$") or ""
if not trimmedMessage or trimmedMessage == "" then
micro.InfoBar():Message("Empty message, cancelled")
os.Remove(tmpfile)
lastOpencodeSession = previousOpencodeSession
return
end
-- Detect a leading PLAN marker to switch to the plan agent (read-only).
local agentMode
editedMessage, agentMode = detectAgentMode(editedMessage)
-- Send the message to OpenCode session via HTTP API in the background
-- The API expects a parts array with text content
local jsonBody
if agentMode then
jsonBody = string.format('{"agent":"%s","parts":[{"type":"text","text":"%s"}]}',
agentMode, jsonEscape(editedMessage))
else
jsonBody = string.format('{"parts":[{"type":"text","text":"%s"}]}', jsonEscape(editedMessage))
end
local endpoint = string.format("/session/%s/message", selectedSession.id)
-- Build curl command that runs in background
local url = string.format("http://%s:%s%s", OPENCODE_HOST, OPENCODE_PORT, endpoint)
local escapedBody = jsonBody:gsub("'", "'\\''")
local bgCmd = string.format("curl -s -X POST -H 'Content-Type: application/json' -d '%s' '%s' >/dev/null 2>&1 &",
escapedBody, url)
-- Execute in background via shell (fire and forget)
shell.ExecCommand("sh", "-c", bgCmd)
-- Clean up temp file
os.Remove(tmpfile)
-- Immediately show success message since we're not waiting for response
local modeLabel = agentMode and (" [" .. agentMode .. "]") or ""
micro.InfoBar():Message("✓ Sending to " .. selectedSession.title .. modeLabel .. "...")
end
|