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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
|
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
)
// VarlinkCall represents a Varlink method call (request)
type VarlinkCall struct {
Method string `json:"method"`
Parameters map[string]any `json:"parameters,omitempty"`
More bool `json:"more,omitempty"`
}
// VarlinkReply represents a Varlink method reply (response)
type VarlinkReply struct {
Parameters map[string]any `json:"parameters,omitempty"`
Continues bool `json:"continues,omitempty"`
Error string `json:"error,omitempty"`
}
// Position represents a file location
type Position struct {
Path string
Line int
}
// ParameterSchema describes a parameter's type and purpose
type ParameterSchema struct {
Type string `json:"type"`
Description string `json:"description"`
}
// ActionSuggestion represents one way to invoke a method with specific parameters
type ActionSuggestion struct {
ID string `json:"id,omitempty"`
Description string `json:"description"`
Parameters map[string]any `json:"parameters"`
}
// Action represents a method with its parameter schema and suggested invocations (HATEOAS)
type Action struct {
Method string `json:"method"`
ParameterSchema map[string]ParameterSchema `json:"parameter_schema"`
Suggestions []ActionSuggestion `json:"suggestions"`
}
// AgentHookPayload represents the JSON from AI agent's post-edit hook
type AgentHookPayload struct {
ToolName string `json:"tool_name"`
ToolInput AgentToolInput `json:"tool_input"`
ToolResponse AgentToolResponse `json:"tool_response"`
}
// AgentToolInput contains the input parameters to the tool
type AgentToolInput struct {
FilePath string `json:"file_path"`
}
// AgentToolResponse contains the response from the tool
type AgentToolResponse struct {
StructuredPatch []StructuredPatchHunk `json:"structuredPatch"`
}
// StructuredPatchHunk represents a hunk in the structured patch
type StructuredPatchHunk struct {
NewStart int `json:"newStart"`
Lines []string `json:"lines"`
}
// HunkDelta represents the effect of a hunk on line numbers
type HunkDelta struct {
StartLine int // The line where the edit starts
Delta int // Net change in lines (positive = lines added, negative = lines removed)
}
// CalculateDelta computes the net change in line count for this hunk
func (h *StructuredPatchHunk) CalculateDelta() HunkDelta {
linesAdded := 0
linesRemoved := 0
for _, line := range h.Lines {
if len(line) > 0 {
switch line[0] {
case '+':
linesAdded++
case '-':
linesRemoved++
}
}
}
return HunkDelta{
StartLine: h.NewStart,
Delta: linesAdded - linesRemoved,
}
}
// PositionTracker manages the history of edited positions
type PositionTracker struct {
history []Position
mu sync.RWMutex
}
func NewPositionTracker() *PositionTracker {
return &PositionTracker{
history: make([]Position, 0),
}
}
// AddPosition adds a new position to the history
func (pt *PositionTracker) AddPosition(path string, line int) {
pt.mu.Lock()
defer pt.mu.Unlock()
pos := Position{Path: path, Line: line}
// Avoid adding duplicate consecutive positions
if len(pt.history) > 0 {
last := pt.history[len(pt.history)-1]
if last.Path == pos.Path && last.Line == pos.Line {
return
}
}
pt.history = append(pt.history, pos)
log.Printf("Position added to history: %s:%d (history size: %d)\n", path, line, len(pt.history))
}
// SetPosition updates the current position (for backward compatibility)
func (pt *PositionTracker) SetPosition(path string, line int) {
pt.AddPosition(path, line)
}
// GetPosition returns the most recent position (for backward compatibility)
func (pt *PositionTracker) GetPosition() Position {
pt.mu.RLock()
defer pt.mu.RUnlock()
if len(pt.history) == 0 {
return Position{Path: "", Line: 0}
}
return pt.history[len(pt.history)-1]
}
// GetPrevious returns the previous position relative to the given current position
// Returns (position, found) where found indicates if a previous position exists
func (pt *PositionTracker) GetPrevious(currentPath string, currentLine int) (Position, bool) {
pt.mu.RLock()
defer pt.mu.RUnlock()
// Find the current position in history
for i := len(pt.history) - 1; i >= 0; i-- {
if pt.history[i].Path == currentPath && pt.history[i].Line == currentLine {
// Found current position, return the previous one if it exists
if i > 0 {
log.Printf("GetPrevious: found at index %d, returning index %d\n", i, i-1)
return pt.history[i-1], true
}
// Current position is the first in history
log.Printf("GetPrevious: at beginning of history\n")
return Position{}, false
}
}
// Current position not found in history, return the last position
if len(pt.history) > 0 {
log.Printf("GetPrevious: current position not in history, returning last position\n")
return pt.history[len(pt.history)-1], true
}
log.Printf("GetPrevious: no history available\n")
return Position{}, false
}
// GetNext returns the next position relative to the given current position
// Returns (position, found) where found indicates if a next position exists
func (pt *PositionTracker) GetNext(currentPath string, currentLine int) (Position, bool) {
pt.mu.RLock()
defer pt.mu.RUnlock()
// Find the current position in history
for i := len(pt.history) - 1; i >= 0; i-- {
if pt.history[i].Path == currentPath && pt.history[i].Line == currentLine {
// Found current position, return the next one if it exists
if i < len(pt.history)-1 {
log.Printf("GetNext: found at index %d, returning index %d\n", i, i+1)
return pt.history[i+1], true
}
// Current position is the last in history
log.Printf("GetNext: at end of history\n")
return Position{}, false
}
}
// Current position not found in history
log.Printf("GetNext: current position not in history\n")
return Position{}, false
}
// AdjustHistoryPositions adjusts line numbers in history based on edit deltas
// This keeps historical positions valid after edits are made to a file
// Deltas should be sorted by StartLine in ascending order
func (pt *PositionTracker) AdjustHistoryPositions(filePath string, deltas []HunkDelta) {
pt.mu.Lock()
defer pt.mu.Unlock()
if len(deltas) == 0 {
return
}
// Process each historical position for this file
for i := range pt.history {
if pt.history[i].Path != filePath {
continue
}
oldLine := pt.history[i].Line
newLine := oldLine
// Apply each delta that affects this position
// Process in order since deltas are sorted by line number
for _, delta := range deltas {
// Only adjust if the historical position is after the edit
if oldLine > delta.StartLine {
newLine += delta.Delta
}
}
if newLine != oldLine {
log.Printf("Adjusted history position: %s:%d -> %s:%d (delta: %d)\n",
filePath, oldLine, filePath, newLine, newLine-oldLine)
pt.history[i].Line = newLine
}
}
}
// buildAvailableActions generates HATEOAS-style action suggestions based on current position
func (pt *PositionTracker) buildAvailableActions(currentPath string, currentLine int) []Action {
actions := []Action{}
// Don't show any actions when history is empty
if currentPath == "" {
return actions
}
// SetLastPosition action
actions = append(actions, Action{
Method: "de.profpatsch.AgentLastPosition.SetLastPosition",
ParameterSchema: map[string]ParameterSchema{
"path": {
Type: "string",
Description: "File path",
},
"line": {
Type: "int",
Description: "Line number",
},
},
Suggestions: []ActionSuggestion{
{
ID: "set_current",
Description: fmt.Sprintf("Set position to %s:%d", currentPath, currentLine),
Parameters: map[string]any{
"path": currentPath,
"line": currentLine,
},
},
},
})
// GetPrevious action (if available)
if _, hasPrev := pt.GetPrevious(currentPath, currentLine); hasPrev {
actions = append(actions, Action{
Method: "de.profpatsch.AgentLastPosition.GetPrevious",
ParameterSchema: map[string]ParameterSchema{
"path": {
Type: "string",
Description: "Current file path",
},
"line": {
Type: "int",
Description: "Current line number",
},
},
Suggestions: []ActionSuggestion{
{
ID: "goto_prev",
Description: "Navigate to previous position in history",
Parameters: map[string]any{
"path": currentPath,
"line": currentLine,
},
},
},
})
}
// GetNext action (if available)
if _, hasNext := pt.GetNext(currentPath, currentLine); hasNext {
actions = append(actions, Action{
Method: "de.profpatsch.AgentLastPosition.GetNext",
ParameterSchema: map[string]ParameterSchema{
"path": {
Type: "string",
Description: "Current file path",
},
"line": {
Type: "int",
Description: "Current line number",
},
},
Suggestions: []ActionSuggestion{
{
ID: "goto_next",
Description: "Navigate to next position in history",
Parameters: map[string]any{
"path": currentPath,
"line": currentLine,
},
},
},
})
}
return actions
}
// AddFromHookPayload parses AI agent hook JSON and adds positions to history
// For each hunk in the structuredPatch, a separate position entry is added
// Also adjusts existing history positions in the same file based on the edits
func (pt *PositionTracker) AddFromHookPayload(jsonData []byte) error {
var payload AgentHookPayload
if err := json.Unmarshal(jsonData, &payload); err != nil {
return fmt.Errorf("failed to parse hook payload: %w", err)
}
// Only process if we have a file path
if payload.ToolInput.FilePath == "" {
return fmt.Errorf("no file path in payload")
}
// If there are multiple hunks, calculate deltas and adjust history before adding new positions
if len(payload.ToolResponse.StructuredPatch) > 0 {
// Calculate deltas for all hunks (already sorted by line number from Claude)
var deltas []HunkDelta
for _, hunk := range payload.ToolResponse.StructuredPatch {
delta := hunk.CalculateDelta()
deltas = append(deltas, delta)
}
// Adjust existing history positions based on these edits
pt.AdjustHistoryPositions(payload.ToolInput.FilePath, deltas)
// Now add new positions for each hunk
for _, hunk := range payload.ToolResponse.StructuredPatch {
newStart := hunk.NewStart
// Find the first edit line (starts with + or -)
firstEditOffset := 0
for i, line := range hunk.Lines {
if len(line) > 0 && (line[0] == '+' || line[0] == '-') {
firstEditOffset = i
break
}
}
line := newStart + firstEditOffset
pt.AddPosition(payload.ToolInput.FilePath, line)
}
} else {
// No patch info (e.g., Write tool), default to line 1
pt.AddPosition(payload.ToolInput.FilePath, 1)
}
return nil
}
// VarlinkServer handles Varlink protocol
type VarlinkServer struct {
pt *PositionTracker
}
func NewVarlinkServer(pt *PositionTracker) *VarlinkServer {
return &VarlinkServer{pt: pt}
}
func (vs *VarlinkServer) handleConnection(conn net.Conn) {
defer conn.Close()
log.Println("Varlink client connected")
scanner := bufio.NewScanner(conn)
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Split on null byte
if i := strings.IndexByte(string(data), 0); i >= 0 {
return i + 1, data[0:i], nil
}
if atEOF && len(data) > 0 {
return len(data), data, nil
}
return 0, nil, nil
})
for scanner.Scan() {
msg := scanner.Bytes()
log.Printf("Received: %s\n", msg)
var request VarlinkCall
if err := json.Unmarshal(msg, &request); err != nil {
log.Printf("Failed to parse request: %v\n", err)
continue
}
response := vs.handleMethod(request)
responseBytes, _ := json.Marshal(response)
responseBytes = append(responseBytes, 0) // Add null terminator
if _, err := conn.Write(responseBytes); err != nil {
log.Printf("Failed to write response: %v\n", err)
return
}
}
if err := scanner.Err(); err != nil {
log.Printf("Scanner error: %v\n", err)
}
log.Println("Varlink client disconnected")
}
func (vs *VarlinkServer) handleMethod(request VarlinkCall) VarlinkReply {
switch request.Method {
case "org.varlink.service.GetInfo":
return VarlinkReply{
Parameters: map[string]any{
"vendor": "Profpatsch",
"product": "Agent Last Position Tracker",
"version": "0.1",
"url": "none",
"interfaces": []string{"de.profpatsch.AgentLastPosition"},
},
}
case "org.varlink.service.GetInterfaceDescription":
iface, _ := request.Parameters["interface"].(string)
// Strip method name if provided
if idx := strings.LastIndex(iface, "."); idx != -1 {
baseIface := iface[:idx]
if baseIface == "de.profpatsch.AgentLastPosition" {
iface = baseIface
}
}
if iface == "de.profpatsch.AgentLastPosition" {
return VarlinkReply{
Parameters: map[string]any{
"description": `# AI Agent edit position tracker
# Maintains a history of file positions edited by AI agents
interface de.profpatsch.AgentLastPosition
# Parameter schema describes a parameter's type and purpose
type ParameterSchema (
type: string,
description: string
)
# Action suggestion represents one way to invoke a method
type ActionSuggestion (
id: string,
description: string,
parameters: object
)
# Action represents a method with its schema and suggested invocations
type Action (
method: string,
parameter_schema: [string]ParameterSchema,
suggestions: []ActionSuggestion
)
# Set the last edited file position
method SetLastPosition(path: string, line: int) -> ()
# Get the most recent file position from edit history
# Includes HATEOAS-style available_actions for discovering next steps
method GetLastPosition() -> (path: string, line: int, available_actions: []Action)
`,
},
}
}
return VarlinkReply{Error: "UnknownInterface"}
case "de.profpatsch.AgentLastPosition.SetLastPosition":
path, pathOk := request.Parameters["path"].(string)
line, lineOk := request.Parameters["line"].(float64)
if !pathOk || !lineOk {
return VarlinkReply{Error: "InvalidParameter"}
}
log.Printf("SetLastPosition called: %s:%d\n", path, int(line))
vs.pt.SetPosition(path, int(line))
return VarlinkReply{Parameters: map[string]any{}}
case "de.profpatsch.AgentLastPosition.GetLastPosition":
pos := vs.pt.GetPosition()
actions := vs.pt.buildAvailableActions(pos.Path, pos.Line)
log.Printf("GetLastPosition called, returning: %s:%d with %d actions\n", pos.Path, pos.Line, len(actions))
return VarlinkReply{
Parameters: map[string]any{
"path": pos.Path,
"line": pos.Line,
"available_actions": actions,
},
}
case "de.profpatsch.AgentLastPosition.GetPrevious":
path, pathOk := request.Parameters["path"].(string)
line, lineOk := request.Parameters["line"].(float64)
if !pathOk || !lineOk {
return VarlinkReply{Error: "InvalidParameter"}
}
log.Printf("GetPrevious called with: %s:%d\n", path, int(line))
pos, found := vs.pt.GetPrevious(path, int(line))
actions := vs.pt.buildAvailableActions(pos.Path, pos.Line)
return VarlinkReply{
Parameters: map[string]any{
"path": pos.Path,
"line": pos.Line,
"found": found,
"available_actions": actions,
},
}
case "de.profpatsch.AgentLastPosition.GetNext":
path, pathOk := request.Parameters["path"].(string)
line, lineOk := request.Parameters["line"].(float64)
if !pathOk || !lineOk {
return VarlinkReply{Error: "InvalidParameter"}
}
log.Printf("GetNext called with: %s:%d\n", path, int(line))
pos, found := vs.pt.GetNext(path, int(line))
actions := vs.pt.buildAvailableActions(pos.Path, pos.Line)
return VarlinkReply{
Parameters: map[string]any{
"path": pos.Path,
"line": pos.Line,
"found": found,
"available_actions": actions,
},
}
default:
log.Printf("Unknown method: %s\n", request.Method)
return VarlinkReply{Error: "UnknownMethod"}
}
}
// Client functions
func getSocketPath() string {
return filepath.Join("/run/user", strconv.Itoa(os.Getuid()), "de.Profpatsch.AgentLastPosition")
}
// varlinkCall makes a Varlink call to the service
func varlinkCall(method string, params map[string]any) (VarlinkReply, error) {
socketPath := getSocketPath()
conn, err := net.Dial("unix", socketPath)
if err != nil {
return VarlinkReply{}, fmt.Errorf("failed to connect to service: %w", err)
}
defer conn.Close()
request := VarlinkCall{
Method: method,
Parameters: params,
}
requestBytes, err := json.Marshal(request)
if err != nil {
return VarlinkReply{}, fmt.Errorf("failed to marshal request: %w", err)
}
// Send with null terminator
requestBytes = append(requestBytes, 0)
if _, err := conn.Write(requestBytes); err != nil {
return VarlinkReply{}, fmt.Errorf("failed to write request: %w", err)
}
// Read response (null-terminated)
scanner := bufio.NewScanner(conn)
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if i := strings.IndexByte(string(data), 0); i >= 0 {
return i + 1, data[0:i], nil
}
if atEOF && len(data) > 0 {
return len(data), data, nil
}
return 0, nil, nil
})
if !scanner.Scan() {
return VarlinkReply{}, fmt.Errorf("failed to read response")
}
var response VarlinkReply
if err := json.Unmarshal(scanner.Bytes(), &response); err != nil {
return VarlinkReply{}, fmt.Errorf("failed to unmarshal response: %w", err)
}
if response.Error != "" {
return VarlinkReply{}, fmt.Errorf("varlink error: %s", response.Error)
}
return response, nil
}
func cmdSet(path string, line int) error {
params := map[string]any{
"path": path,
"line": line,
}
_, err := varlinkCall("de.profpatsch.AgentLastPosition.SetLastPosition", params)
return err
}
func cmdGet() (string, int, error) {
response, err := varlinkCall("de.profpatsch.AgentLastPosition.GetLastPosition", nil)
if err != nil {
return "", 0, err
}
path, ok := response.Parameters["path"].(string)
if !ok {
return "", 0, fmt.Errorf("invalid path in response")
}
line, ok := response.Parameters["line"].(float64)
if !ok {
return "", 0, fmt.Errorf("invalid line in response")
}
return path, int(line), nil
}
func cmdOpen() error {
path, line, err := cmdGet()
if err != nil {
return err
}
if path == "" {
return fmt.Errorf("no position recorded yet")
}
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
// Detect editor and use appropriate line-jump syntax
var cmd *exec.Cmd
switch {
case strings.Contains(editor, "vim") || strings.Contains(editor, "nvim"):
cmd = exec.Command(editor, fmt.Sprintf("+%d", line), path)
case strings.Contains(editor, "emacs"):
cmd = exec.Command(editor, fmt.Sprintf("+%d", line), path)
case strings.Contains(editor, "code"):
cmd = exec.Command(editor, "--goto", fmt.Sprintf("%s:%d", path, line))
default:
// Try generic +line syntax
cmd = exec.Command(editor, fmt.Sprintf("+%d", line), path)
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func cmdInfo() error {
response, err := varlinkCall("org.varlink.service.GetInfo", nil)
if err != nil {
return err
}
output, _ := json.MarshalIndent(response.Parameters, "", " ")
fmt.Println(string(output))
return nil
}
func cmdHook() error {
// Read JSON from stdin
jsonData, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("failed to read from stdin: %w", err)
}
// Parse the AI agent hook JSON
var payload AgentHookPayload
if err := json.Unmarshal(jsonData, &payload); err != nil {
return fmt.Errorf("failed to parse hook payload: %w", err)
}
// Extract file path
if payload.ToolInput.FilePath == "" {
return fmt.Errorf("no file path in payload")
}
// Determine the line number to record
line := 1 // default to line 1
if len(payload.ToolResponse.StructuredPatch) > 0 {
// Get the first hunk
firstHunk := payload.ToolResponse.StructuredPatch[0]
// Find the first edit line (starts with + or -)
firstEditOffset := 0
for i, l := range firstHunk.Lines {
if len(l) > 0 && (l[0] == '+' || l[0] == '-') {
firstEditOffset = i
break
}
}
line = firstHunk.NewStart + firstEditOffset
}
// Call SetLastPosition via varlink
return cmdSet(payload.ToolInput.FilePath, line)
}
func cmdPrev(path string, line int) error {
params := map[string]any{
"path": path,
"line": line,
}
response, err := varlinkCall("de.profpatsch.AgentLastPosition.GetPrevious", params)
if err != nil {
return err
}
found, ok := response.Parameters["found"].(bool)
if !ok || !found {
// Return non-zero exit code to indicate no previous position
os.Exit(1)
}
prevPath, _ := response.Parameters["path"].(string)
prevLine, _ := response.Parameters["line"].(float64)
fmt.Printf("%s:%d\n", prevPath, int(prevLine))
return nil
}
func cmdNext(path string, line int) error {
params := map[string]any{
"path": path,
"line": line,
}
response, err := varlinkCall("de.profpatsch.AgentLastPosition.GetNext", params)
if err != nil {
return err
}
found, ok := response.Parameters["found"].(bool)
if !ok || !found {
// Return non-zero exit code to indicate no next position
os.Exit(1)
}
nextPath, _ := response.Parameters["path"].(string)
nextLine, _ := response.Parameters["line"].(float64)
fmt.Printf("%s:%d\n", nextPath, int(nextLine))
return nil
}
func cmdServer() error {
socketPath := getSocketPath()
// Remove existing socket
os.Remove(socketPath)
// Create position tracker
pt := NewPositionTracker()
// Create Varlink server
server := NewVarlinkServer(pt)
// Listen on Unix socket
listener, err := net.Listen("unix", socketPath)
if err != nil {
log.Fatalf("Failed to listen on socket: %v\n", err)
}
defer listener.Close()
log.Printf("Listening on %s\n", socketPath)
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Accept error: %v\n", err)
continue
}
go server.handleConnection(conn)
}
}
func usage() {
progName := filepath.Base(os.Args[0])
fmt.Fprintf(os.Stderr, `Usage: %s <command> [args]
Commands:
server Start the Varlink service
set <path> <line> Set the last edited position
get Get the last edited position (JSON output)
open Open the last edited position in $EDITOR
info Get service information
hook Add position from AI agent hook JSON (reads from stdin)
prev <path> <line> Get the previous position in history
next <path> <line> Get the next position in history
Examples:
%s server
%s set /path/to/file.txt 42
%s get
%s open
echo '{"tool_input": {"file_path": "/tmp/test.txt"}, ...}' | %s hook
%s prev /tmp/test.txt 42
%s next /tmp/test.txt 42
`, progName, progName, progName, progName, progName, progName, progName, progName)
}
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(1)
}
command := os.Args[1]
switch command {
case "server":
if err := cmdServer(); err != nil {
log.Fatalf("Server error: %v\n", err)
}
case "set":
if len(os.Args) != 4 {
fmt.Fprintf(os.Stderr, "Usage: %s set <path> <line>\n", filepath.Base(os.Args[0]))
os.Exit(1)
}
path := os.Args[2]
line, err := strconv.Atoi(os.Args[3])
if err != nil {
log.Fatalf("Invalid line number: %v\n", err)
}
if err := cmdSet(path, line); err != nil {
log.Fatalf("Failed to set position: %v\n", err)
}
case "get":
path, line, err := cmdGet()
if err != nil {
log.Fatalf("Failed to get position: %v\n", err)
}
fmt.Printf("{\"path\": \"%s\", \"line\": %d}\n", path, line)
case "open":
if err := cmdOpen(); err != nil {
log.Fatalf("Failed to open position: %v\n", err)
}
case "info":
if err := cmdInfo(); err != nil {
log.Fatalf("Failed to get info: %v\n", err)
}
case "hook":
if err := cmdHook(); err != nil {
log.Fatalf("Failed to process hook: %v\n", err)
}
case "prev":
if len(os.Args) != 4 {
fmt.Fprintf(os.Stderr, "Usage: %s prev <path> <line>\n", filepath.Base(os.Args[0]))
os.Exit(1)
}
path := os.Args[2]
line, err := strconv.Atoi(os.Args[3])
if err != nil {
log.Fatalf("Invalid line number: %v\n", err)
}
if err := cmdPrev(path, line); err != nil {
log.Fatalf("Failed to get previous position: %v\n", err)
}
case "next":
if len(os.Args) != 4 {
fmt.Fprintf(os.Stderr, "Usage: %s next <path> <line>\n", filepath.Base(os.Args[0]))
os.Exit(1)
}
path := os.Args[2]
line, err := strconv.Atoi(os.Args[3])
if err != nil {
log.Fatalf("Invalid line number: %v\n", err)
}
if err := cmdNext(path, line); err != nil {
log.Fatalf("Failed to get next position: %v\n", err)
}
default:
fmt.Fprintf(os.Stderr, "Unknown command: %s\n", command)
usage()
os.Exit(1)
}
}
|