Repository navigation
Expand file tree
/
Copy pathopencode_sublime.py
More file actions
1948 lines (1729 loc) · 86.9 KB
/
Copy pathopencode_sublime.py
File metadata and controls
1948 lines (1729 loc) · 86.9 KB
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import html
import difflib
import base64
import mimetypes
import os
from pathlib import Path
import re
import shutil
import subprocess
import time
import urllib.parse
import json
import threading
import urllib.error
import urllib.request
import uuid
from datetime import datetime
import sublime
import sublime_plugin
BASE_URL = "http://127.0.0.1:4096"
LAYOUT = {
"cols": [0.0, 0.70, 1.0],
"rows": [0.0, 1.0],
"cells": [
[0, 0, 1, 1],
[1, 0, 2, 1],
],
}
_states = {}
_server_lock = threading.Lock()
_server_process = None
_session_lock = threading.Lock()
class OpenCodeConnectionError(RuntimeError):
pass
def project_directory(window):
folders = window.folders()
active = window.active_view()
filename = active.file_name() if active and not active.settings().get("opencode_composer") else None
if filename:
filename = os.path.abspath(filename)
matches = []
for folder in folders:
try:
if os.path.commonpath([filename, os.path.abspath(folder)]) == os.path.abspath(folder):
matches.append(folder)
except ValueError:
pass
if matches:
return os.path.abspath(max(matches, key=len))
if folders:
return os.path.abspath(folders[0])
if filename:
return os.path.dirname(filename)
return None
def ensure_server(directory):
"""Reuse the existing server or start one, on a worker thread only."""
global _server_process
with _server_lock:
try:
health = request_json("GET", "/global/health", timeout=3)
if isinstance(health, dict) and health.get("healthy"):
return health
raise RuntimeError("OpenCode answered but is not healthy.")
except OpenCodeConnectionError:
pass
if not directory or not os.path.isdir(directory):
raise RuntimeError("Open a project folder in Sublime before starting OpenCode.")
settings = sublime.load_settings("OpenCodeSublime.sublime-settings")
executable = settings.get("opencode_executable") or shutil.which("opencode")
if not executable and sublime.platform() == "windows":
candidate = os.path.join(os.path.expanduser("~"), "scoop", "shims", "opencode.exe")
if os.path.isfile(candidate):
executable = candidate
if not executable:
raise RuntimeError("OpenCode executable not found. Set opencode_executable in the plugin settings.")
if _server_process is None or _server_process.poll() is not None:
log_dir = os.path.join(sublime.cache_path(), "OpenCodeSublime")
os.makedirs(log_dir, exist_ok=True)
log_path = os.path.join(log_dir, "server.log")
with open(log_path, "ab") as log:
_server_process = subprocess.Popen(
[executable, "serve", "--hostname", "127.0.0.1", "--port", "4096"],
cwd=directory,
stdin=subprocess.DEVNULL,
stdout=log,
stderr=subprocess.STDOUT,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0,
)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
health = request_json("GET", "/global/health", timeout=1)
if isinstance(health, dict) and health.get("healthy"):
return health
except OpenCodeConnectionError:
pass
if _server_process.poll() not in (None, 0):
break
time.sleep(0.25)
raise RuntimeError("OpenCode did not become ready. See OpenCodeSublime/server.log in Sublime's cache directory.")
def mention_at(view, point):
before = view.substr(sublime.Region(1, point))
match = re.search(r'(?<!\S)@([^\s@"<>]*)$', before)
if match:
return 1 + match.start(), point, match.group(1)
return None
def index_project_files(directory):
"""Use Git's ignore rules when available, with a bounded fallback scan."""
limit = 30000
if not directory:
return []
settings = sublime.load_settings("OpenCodeSublime.sublime-settings")
excluded = set(settings.get("context_excluded_folders") or [
".git", ".svn", ".hg", "node_modules", ".venv", "venv",
"__pycache__", "dist", "build", ".next", ".nuxt",
])
paths = None
if shutil.which("git"):
try:
result = subprocess.run(
["git", "-C", directory, "ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", "."],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=20,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0,
)
if result.returncode == 0:
paths = result.stdout.decode("utf-8", errors="replace").split("\0")
except (OSError, subprocess.TimeoutExpired):
pass
if paths is None:
paths = []
for base, dirs, files in os.walk(directory, followlinks=False):
dirs[:] = sorted(d for d in dirs if d not in excluded and not os.path.islink(os.path.join(base, d)))
paths.extend(os.path.relpath(os.path.join(base, f), directory) for f in files)
if len(paths) >= limit:
break
result = []
seen = set()
for relative in paths:
relative = relative.replace("\\", "/")
if not relative or any(part in excluded for part in relative.split("/")[:-1]):
continue
absolute = os.path.realpath(os.path.join(directory, relative))
try:
if os.path.commonpath([os.path.realpath(directory), absolute]) != os.path.realpath(directory):
continue
except ValueError:
continue
if absolute not in seen and os.path.isfile(absolute):
seen.add(absolute)
result.append({"relative": relative, "absolute": absolute})
if len(result) >= limit:
break
return sorted(result, key=lambda f: f["relative"].lower())
def refresh_files(window_id):
state = _states.get(window_id)
if not state or state.get("indexing"):
return
state["indexing"] = True
directory = state["directory"]
def worker():
try:
files = index_project_files(directory)
error = ""
except Exception as exc:
files, error = [], str(exc)
def finish():
if _states.get(window_id) is not state:
return
state["files"] = files
state["indexing"] = False
if error:
sublime.status_message("OpenCode file search: " + error)
view = state["composer"]
if view and view.is_valid() and view.sel() and mention_at(view, view.sel()[0].b):
view.run_command("auto_complete", {"disable_auto_insert": True, "next_completion_if_showing": False})
sublime.set_timeout(finish)
threading.Thread(target=worker, daemon=True).start()
def context_parts(state, prompt):
result, seen = [], set()
directory = state.get("directory")
if not directory:
return result
# Only actual files inside the current project become attachments.
for match in re.finditer(r'(?<!\S)@(?:"([^"\n]+)"|([^\s@<>]+))', prompt):
relative = match.group(1) or match.group(2)
absolute = os.path.realpath(os.path.join(directory, relative))
try:
if os.path.commonpath([os.path.realpath(directory), absolute]) != os.path.realpath(directory):
continue
except ValueError:
continue
if not os.path.isfile(absolute) or absolute in seen:
continue
seen.add(absolute)
mime = mimetypes.guess_type(absolute)[0] or "text/plain"
if not mime.startswith("image/") and mime != "application/pdf":
mime = "text/plain"
result.append({"type": "file", "mime": mime, "filename": relative, "url": Path(absolute).as_uri()})
return result
def request_json(method, path, body=None, timeout=120, directory=None):
if directory:
path += ("&" if "?" in path else "?") + urllib.parse.urlencode({"directory": directory})
data = None
headers = {"Accept": "application/json"}
password = os.environ.get("OPENCODE_SERVER_PASSWORD")
if password:
username = os.environ.get("OPENCODE_SERVER_USERNAME", "opencode")
encoded = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
headers["Authorization"] = "Basic " + encoded
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
BASE_URL + path,
data=data,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(req, timeout=timeout) as response:
raw = response.read()
return json.loads(raw.decode("utf-8")) if raw else None
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
raise RuntimeError("HTTP {} {}\n{}".format(error.code, error.reason, detail))
except urllib.error.URLError as error:
raise OpenCodeConnectionError("Could not connect to OpenCode: {}".format(error.reason))
def get_window(window_id):
for window in sublime.windows():
if window.id() == window_id:
return window
return None
def project_key(directory):
return os.path.normcase(os.path.realpath(os.path.abspath(directory))) if directory else None
def saved_project_session(directory):
key = project_key(directory)
with _session_lock:
records = sublime.load_settings("OpenCodeSublime.sublime-settings").get("project_sessions") or {}
record = records.get(key) if isinstance(records, dict) and key else None
return dict(record) if isinstance(record, dict) else {}
def remember_project_session(state):
key = project_key(state.get("directory"))
if not key:
return
composer = state.get("composer")
draft = draft_text(composer) if composer is not None and composer.is_valid() else state.get("saved_draft", "")
with _session_lock:
settings = sublime.load_settings("OpenCodeSublime.sublime-settings")
previous = settings.get("project_sessions") or {}
records = dict(previous) if isinstance(previous, dict) else {}
sid = state.get("session_id") or (state.get("restore_id") if state.get("restore_pending") else None)
records[key] = {"session_id": sid, "title": state.get("session_title") or "New chat", "draft": draft}
settings.set("project_sessions", records)
sublime.save_settings("OpenCodeSublime.sublime-settings")
def new_state(window):
settings = sublime.load_settings("OpenCodeSublime.sublime-settings")
color = settings.get("color_mode", "light")
agent = settings.get("last_agent")
agent = agent if isinstance(agent, str) and agent else None
saved_model = settings.get("last_model")
model = None
if isinstance(saved_model, dict) and all(
isinstance(saved_model.get(key), str) and saved_model[key]
for key in ("provider_id", "model_id")
):
model = {
"provider_id": saved_model["provider_id"],
"model_id": saved_model["model_id"],
"label": "{}/{}".format(saved_model["provider_id"], saved_model["model_id"]),
}
directory = project_directory(window)
remembered = saved_project_session(directory)
saved_id = remembered.get("session_id")
saved_id = saved_id if isinstance(saved_id, str) and saved_id.startswith("ses_") else None
return {
"window_id": window.id(),
"directory": directory,
"files": [],
"indexing": False,
"connecting": False,
"mention_request": 0,
"old_layout": window.layout(),
"phantoms": None,
"color_mode": color if color in ("light", "dark") else "light",
"composer": None,
"session_id": None,
"restore_id": saved_id,
"restore_pending": bool(saved_id),
"session_title": remembered.get("title") or "New chat",
"session_loading": False,
"session_request": 0,
"session_revision": 0,
"session_error": "",
"session_blocked": False,
"rename_inflight": False,
"diff_open": False,
"diff_loading": False,
"diff_error": "",
"diffs": [],
"diff_request": 0,
"saved_draft": remembered.get("draft") if isinstance(remembered.get("draft"), str) else "",
"turns": [],
"busy": False,
"active_turn": None,
"connected": False,
"version": "",
"error": "",
"agents": [],
"agent": agent or "build",
"preferred_agent": agent,
"models": [],
"selected_model": model,
"config_model": None,
"effective_model": None,
"generation": 0,
}
def save_preferences(state):
settings = sublime.load_settings("OpenCodeSublime.sublime-settings")
settings.set("color_mode", state["color_mode"])
settings.set("last_agent", state["agent"])
model = state["selected_model"]
settings.set("last_model", {
"provider_id": model["provider_id"],
"model_id": model["model_id"],
} if model else None)
sublime.save_settings("OpenCodeSublime.sublime-settings")
def message_time(timestamp):
if not timestamp:
return ""
try:
# Keep the local wall-clock time and offset captured on the computer.
return datetime.fromisoformat(timestamp).strftime("%H:%M")
except (ValueError, TypeError):
return ""
def state_for(window):
state = _states.get(window.id())
if state is None:
state = new_state(window)
_states[window.id()] = state
return state
def esc(value):
return html.escape(str(value or ""), quote=True)
def cmd_url(command, args=None):
# command_url already returns an HTML-embeddable URL. Escaping it again
# turns " into &quot; and breaks the JSON arguments on click.
return sublime.command_url(command, args or {})
def parse_agents(data):
agents = []
for item in data if isinstance(data, list) else []:
if not isinstance(item, dict) or not item.get("name"):
continue
if item.get("hidden") or item.get("disable"):
continue
if item.get("mode", "all") not in ("primary", "all", None):
continue
agents.append({
"name": item["name"],
"description": item.get("description") or "Primary agent",
"model": item.get("model"),
})
agents.sort(key=lambda x: (0 if x["name"] == "build" else 1, x["name"]))
return agents
def parse_models(data):
if not isinstance(data, dict):
return []
connected = data.get("connected")
connected = set(connected) if isinstance(connected, list) and connected else None
result = []
for provider in data.get("all") or []:
if not isinstance(provider, dict) or not provider.get("id"):
continue
provider_id = provider["id"]
if connected and provider_id not in connected:
continue
provider_name = provider.get("name") or provider_id
models = provider.get("models") or {}
entries = models.items() if isinstance(models, dict) else [
(m.get("id"), m) for m in models if isinstance(m, dict)
]
for fallback_id, model in entries:
if not isinstance(model, dict):
continue
model_id = model.get("id") or fallback_id
if not model_id:
continue
model_name = model.get("name") or model_id
result.append({
"provider_id": provider_id,
"provider_name": provider_name,
"model_id": model_id,
"model_name": model_name,
"label": "{} · {}".format(provider_name, model_name),
})
result.sort(key=lambda x: (x["provider_name"].lower(), x["model_name"].lower()))
return result
def resolve_model(state, provider_id, model_id):
for model in state["models"]:
if model["provider_id"] == provider_id and model["model_id"] == model_id:
return model["label"]
return "{}/{}".format(provider_id, model_id)
def label_from_ref(state, ref):
if isinstance(ref, dict):
return resolve_model(state, ref.get("providerID", ""), ref.get("modelID", ""))
if not ref or "/" not in ref:
return ref
provider_id, model_id = ref.split("/", 1)
return resolve_model(state, provider_id, model_id)
def current_model_label(state):
if state["selected_model"]:
return state["selected_model"]["label"]
if state["effective_model"]:
m = state["effective_model"]
return "Auto · " + resolve_model(state, m["provider_id"], m["model_id"])
for agent in state["agents"]:
if agent["name"] == state["agent"] and agent.get("model"):
return "Auto · " + label_from_ref(state, agent["model"])
if state["config_model"]:
return "Auto · " + label_from_ref(state, state["config_model"])
return "Auto · OpenCode default"
def markdown_segments(text):
segments, lines = [], []
fence, language = None, ""
for line in str(text or "").splitlines(keepends=True):
match = re.match(r"^ {0,3}(`{3,}|~{3,})([^\r\n]*)[\r\n]*$", line)
if fence is None and match and not (match.group(1)[0] == "`" and "`" in match.group(2)):
if lines:
segments.append({"type": "text", "text": "".join(lines)})
lines, fence, language = [], match.group(1), match.group(2).strip()
elif fence and match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence) and not match.group(2).strip():
segments.append({"type": "code", "text": "".join(lines), "language": language})
lines, fence, language = [], None, ""
else:
lines.append(line)
if lines or fence:
segments.append({"type": "code" if fence else "text", "text": "".join(lines), "language": language})
return segments
def message_html(text, code_context=None):
out, code_index = [], 0
for segment in markdown_segments(text):
if segment["type"] == "code":
caption = ""
if code_context is not None:
args = dict(code_context, block_index=code_index)
caption = '<div class="code-caption">{} <a href="{}">Copy code</a></div>'.format(
esc(segment.get("language") or "Code"), cmd_url("opencode_copy_response", args))
out.append('<div class="code">{}{}</div>'.format(caption, esc(segment["text"])))
code_index += 1
else:
out.append("<br>".join(esc(line) for line in segment["text"].splitlines()))
return "<br>".join(out)
def activity_html(activity):
status = activity.get("status", "completed")
icon = {"completed": "✓", "error": "!", "running": "●"}.get(status, "○")
cls = {"completed": "good", "error": "bad", "running": "accent"}.get(status, "muted")
return '<div class="activity"><span class="{}">{}</span> {}</div>'.format(
cls, icon, esc(activity.get("title") or activity.get("tool") or "Tool")
)
DARK_COLORS = {'#f7f8fa': '#1b202b', '#202632': '#e1e7f1', '#335cc5': '#8eafff', '#dfe3ea': '#354052', '#657184': '#a0aec2', '#dce1e9': '#3c485e', '#ffffff': '#252e3e', '#445166': '#c3cfdf', '#208450': '#72cf9b', '#bd3546': '#ff929f', '#eaf0fc': '#283956', '#263a5b': '#dce6ff', '#f0c9ce': '#68414e', '#fff1f3': '#3b2933', '#a92c3c': '#ffb0bb', '#eef1f5': '#242d3c', '#26364a': '#dae3f3'}
def duration_text(seconds):
seconds = max(0, int(seconds))
return "{}:{:02d}".format(seconds // 60, seconds % 60)
def thinking_html(state, turn, index):
reasoning = turn.get("reasoning") or ""
if not reasoning:
return ""
opened = turn.get("thinking_open", False)
label = "Thinking…" if turn.get("phase") == "thinking" else "Thinking"
link = cmd_url("opencode_toggle_thinking", {"window_id": state["window_id"], "turn_index": index})
text = '<div class="thinking-text">{}</div>'.format(message_html(reasoning)) if opened else ""
return '<div class="thinking"><a href="{}">{} {} · {}</a>{}</div>'.format(
link, "▾" if opened else "▸", label, "Hide" if opened else "Show", text,
)
def progress_html(state, turn):
phase = turn.get("phase")
if not phase:
return ""
now = turn["ended_at"] if turn.get("ended_at") is not None else time.monotonic()
elapsed = duration_text(now - turn.get("started_at", now))
labels = {
"preparing": "Preparing OpenCode", "sending": "Sending message",
"waiting": "Waiting for model", "thinking": "Thinking…",
"writing": "Writing response…", "tool": "Running tool",
"retry": "Provider retry", "permission": "Waiting for your permission",
"question": "Waiting for your answer", "reconnecting": "Connection lost · checking again",
"interrupted": "No active run",
"cancelling": "Cancelling…", "completed": "Completed",
"cancelled": "Cancelled", "error": "Error",
}
terminal = phase in ("completed", "cancelled", "error", "interrupted")
icon = {"completed": "✓", "cancelled": "■", "error": "!"}.get(phase, "●" if int(now) % 2 else "○")
label = labels.get(phase, "Agent working")
detail = turn.get("status_detail") or ""
if detail:
label += " · " + detail
meta = "Elapsed " + elapsed
if not terminal:
checked = turn.get("checked_at")
if checked:
meta += " · Last server check {} ago".format(duration_text(now - checked))
idle = now - turn.get("last_activity_at", turn.get("started_at", now))
if idle >= 45 and phase not in ("permission", "question", "cancelling"):
meta += "<br>No new activity for {}. {}".format(duration_text(idle),
"The server still reports a busy session; you can keep waiting or press Stop."
if turn.get("server_status") in ("busy", "retry") and phase != "reconnecting"
else "The current server state has not been confirmed; checking again.")
if turn.get("monitor_error"):
meta += "<br>" + esc(turn["monitor_error"])
return '<div class="working"><b>{} {}</b><div class="progress-meta">{}</div></div>'.format(icon, esc(label), meta)
def pending_html(state, turn):
out = []
wid = state["window_id"]
for item in turn.get("permissions", []):
links = ""
for reply, label in (("once", "Allow once"), ("reject", "Reject")):
links += '<a class="button" href="{}">{}</a> '.format(cmd_url(
"opencode_permission_reply", {"window_id": wid, "request_id": item["id"], "reply": reply}), label)
out.append('<div class="pending"><b>Permission required: {}</b><br>{}<div class="pending-actions">{}</div></div>'.format(
esc(item.get("permission", "Tool")), esc(" · ".join(item.get("patterns") or [])), links))
for item in turn.get("questions", []):
content = "<br>".join(esc(q.get("question", "")) for q in item.get("questions", []))
link = cmd_url("opencode_question_reply", {"window_id": wid, "request_id": item["id"]})
skip = cmd_url("opencode_question_reply", {"window_id": wid, "request_id": item["id"], "reject": True})
out.append('<div class="pending"><b>Agent needs an answer</b><br>{}<div class="pending-actions"><a class="button" href="{}">Answer</a> <a class="button" href="{}">Skip</a></div></div>'.format(content, link, skip))
if turn.get("action_error"):
out.append('<div class="error">{}</div>'.format(esc(turn["action_error"])))
return "".join(out)
def apply_color_mode(state):
composer = state.get("composer")
if composer is not None and composer.is_valid():
name = "OpenCode Prompt Dark" if state["color_mode"] == "dark" else "OpenCode Prompt"
composer.settings().set("color_scheme", "Packages/OpenCodeSublime/{}.sublime-color-scheme".format(name))
def reset_changes(state):
state["diff_request"] = state.get("diff_request", 0) + 1
state.update(diff_open=False, diff_loading=False, diff_error="", diffs=[])
def session_context_current(state, generation, session_id, serial):
return (_states.get(state["window_id"]) is state and state["generation"] == generation
and state.get("session_id") == session_id and state["session_revision"] == serial)
def normalize_session_diff(item):
if not isinstance(item, dict):
return None
filename = item.get("file") or item.get("path")
if not isinstance(filename, str) or not filename:
return None
patch = item.get("patch")
if not isinstance(patch, str) and isinstance(item.get("before"), str) and isinstance(item.get("after"), str):
before, after = item["before"], item["after"]
old_name = "/dev/null" if item.get("status") == "added" else "a/" + filename
new_name = "/dev/null" if item.get("status") == "deleted" else "b/" + filename
lines = difflib.unified_diff(before.splitlines(keepends=True), after.splitlines(keepends=True), fromfile=old_name, tofile=new_name)
patch = "".join(line if line.endswith("\n") else line + "\n\\ No newline at end of file\n" for line in lines)
def count(value):
return max(0, value) if isinstance(value, int) and not isinstance(value, bool) else 0
return {"file": filename, "patch": patch if isinstance(patch, str) else None,
"additions": count(item.get("additions")), "deletions": count(item.get("deletions")),
"status": item.get("status") if item.get("status") in ("added", "deleted", "modified") else "modified"}
def changes_html(state):
if not state.get("diff_open"):
return ""
wid = state["window_id"]
out = ['<div class="changes"><b>Recorded changes in this session</b>']
out.append(' <a href="{}">Refresh</a>'.format(cmd_url("opencode_show_changes", {"window_id": wid, "refresh": True})))
if state.get("diff_loading"):
out.append('<div class="muted">Loading changes…</div>')
if state.get("diff_error"):
out.append('<div class="error">{}</div>'.format(esc(state["diff_error"])))
if not state.get("diff_loading") and not state.get("diff_error") and not state.get("diffs"):
out.append('<div class="muted">No recorded file changes in this session.</div>')
if state.get("diffs"):
for index, item in enumerate(state["diffs"]):
args = {"window_id": wid, "diff_index": index, "request": state["diff_request"], "session_id": state["session_id"]}
out.append('<div class="change-file">{}<br><span class="muted">{} · +{} / −{}</span> <a href="{}">Diff</a> <a href="{}">Open</a></div>'.format(
esc(item["file"]), esc(item["status"]), item["additions"], item["deletions"],
cmd_url("opencode_view_change", args), cmd_url("opencode_view_change", dict(args, open_file=True))))
out.append('</div>')
return "".join(out)
def refresh_session_changes(state):
session_id = state.get("session_id")
if not session_id or state.get("session_loading"):
return
state["diff_request"] += 1
request, generation, serial = state["diff_request"], state["generation"], state["session_revision"]
state.update(diff_loading=True, diff_error="", diffs=[])
render(state["window_id"])
def worker():
error, diffs = "", []
try:
result = request_json("GET", "/session/{}/diff".format(urllib.parse.quote(session_id, safe="")), timeout=15, directory=state["directory"])
if not isinstance(result, list):
raise RuntimeError("OpenCode returned an invalid changes list.")
diffs = [diff for diff in (normalize_session_diff(item) for item in result) if diff is not None]
except Exception as failure:
error = "Could not load changes: " + str(failure)
def apply():
if not session_context_current(state, generation, session_id, serial) or state["diff_request"] != request:
return
state.update(diff_loading=False, diff_error=error, diffs=diffs)
render(state["window_id"])
sublime.set_timeout(apply)
threading.Thread(target=worker, daemon=True).start()
def safe_project_path(directory, filename):
if not directory or not filename:
raise RuntimeError("Open a project folder first.")
root = os.path.realpath(directory)
path = os.path.realpath(os.path.join(root, filename))
try:
inside = os.path.commonpath([os.path.normcase(root), os.path.normcase(path)]) == os.path.normcase(root)
except ValueError:
inside = False
if not inside:
raise RuntimeError("This file is outside the current project. Use Diff to inspect the recorded changes.")
return path
def build_html(state):
wid = state["window_id"]
status = (
'<span class="good">● Connected</span>'
if state["connected"]
else '<span class="bad">● Offline</span>'
)
selectors = '<span class="select-gap"> </span>'.join([
'<span class="control"><a class="select" href="{}">{} ▾</a></span>'.format(
cmd_url("opencode_choose_agent", {"window_id": wid}),
esc(state["agent"].upper()),
),
'<span class="control"><a class="select" href="{}" title="{}">{} ▾</a></span>'.format(
cmd_url("opencode_choose_model", {"window_id": wid}),
esc(current_model_label(state)),
esc(current_model_label(state) if len(current_model_label(state)) <= 24 else current_model_label(state)[:23] + "…"),
),
'<span class="control"><a class="select" href="{}">{} ▾</a></span>'.format(
cmd_url("opencode_choose_color", {"window_id": wid}),
"Dark" if state["color_mode"] == "dark" else "Light",
),
])
actions = "".join([
'<a class="button primary" href="{}">Send</a> '.format(
cmd_url("opencode_send_prompt", {"window_id": wid})
),
'<a class="button" href="{}">New</a> '.format(
cmd_url("opencode_new_session", {"window_id": wid})
),
(
'<a class="button danger" href="{}">Stop</a> '.format(
cmd_url("opencode_abort", {"window_id": wid})
)
if state["busy"] else ""
),
'<a class="button" href="{}">Close</a>'.format(
cmd_url("opencode_close_agent", {"window_id": wid})
),
])
session_label = "Loading session…" if state.get("session_loading") else state.get("session_title") or "New chat"
session_bar = '<div class="session-bar">Session: <a href="{}">{} ▾</a></div>'.format(
cmd_url("opencode_choose_session", {"window_id": wid}), esc(session_label))
if state.get("session_id"):
session_bar += '<div class="session-links"><a href="{}">Rename</a> <a href="{}">{} Changes</a></div>'.format(
cmd_url("opencode_rename_session", {"window_id": wid}),
cmd_url("opencode_show_changes", {"window_id": wid}), "▾" if state.get("diff_open") else "▸")
session_bar += changes_html(state)
if state.get("session_error"):
session_bar += '<div class="error">{}</div>'.format(esc(state["session_error"]))
body = []
if not state["turns"]:
body.append(
'<div class="welcome"><b>Agent ready</b><br>'
'<span class="muted">Write below and press Ctrl+Enter.</span></div>'
)
for turn_index, turn in enumerate(state["turns"]):
activities = "".join(activity_html(a) for a in turn.get("activities", []))
attached = turn.get("attachments") or []
context = '<div class="context-files">Context: {}</div>'.format(
esc(" · ".join(part["filename"] for part in attached))
) if attached else ""
response = thinking_html(state, turn, turn_index)
if turn.get("response"):
copy_args = {"window_id": wid, "turn_index": turn_index, "generation": state["generation"], "message_id": turn.get("message_id")}
response += '<div class="message-actions"><a href="{}">Copy response</a></div><div class="assistant">{}</div>'.format(
cmd_url("opencode_copy_response", copy_args), message_html(turn["response"], copy_args))
response += progress_html(state, turn)
response += pending_html(state, turn)
if turn.get("error"):
response += '<div class="error">{}</div>'.format(esc(turn["error"]))
body.append(
'<div class="turn">'
'<div class="caption">YOU <span class="timestamp">{}</span></div>'
'<div class="user">{}</div>'
'{}'
'<div class="assistant-title"><b>OPENCODE</b> '
'<span class="muted">{} · {}</span> <span class="timestamp">{}</span></div>'
'{}{}'
'</div>'.format(
esc(message_time(turn.get("sent_at"))),
message_html(turn["prompt"]),
context,
esc(turn["agent"].upper()),
esc(turn["model"]),
esc(message_time(turn.get("received_at"))),
activities,
response,
)
)
if state.get("connecting"):
status = '<span class="accent">● Connecting…</span>'
server = "OpenCode {}".format(esc(state["version"])) if state["version"] else esc(state["error"])
if state.get("directory"):
server += " · " + esc(os.path.basename(state["directory"]))
markup = """
<html><body id="opencode-agent"><style>
html {{ background-color: #f7f8fa; color: #202632; }}
body {{ margin: 18px; background-color: #f7f8fa; color: #202632; font-family: "Segoe UI", sans-serif; font-size: 14px; line-height: 1.5em; }}
a {{ text-decoration: none; color: #335cc5; }}
.header {{ padding-bottom: 16px; margin-bottom: 20px; border-bottom: 1px solid #dfe3ea; }}
.brand {{ font-size: 21px; font-weight: bold; color: #202632; }}
.meta {{ margin-top: 5px; font-size: 12px; color: #657184; }}
.toolbar {{ display: block; margin-top: 12px; padding-top: 8px; padding-bottom: 8px; line-height: 32px; }}
.control {{ display: inline-block; padding-right: 8px; }}
.select-gap {{ display: inline; font-size: 12px; }}
.toolbar-gap {{ display: block; padding-top: 6px; padding-bottom: 6px; font-size: 12px; line-height: 16px; }}
.actions {{ display: block; padding-top: 8px; padding-bottom: 8px; line-height: 32px; }}
.select,.button {{ display: inline-block; padding: 7px 10px; margin-right: 12px; margin-bottom: 6px; line-height: 20px; white-space: nowrap; border-radius: 6px; border: 1px solid #dce1e9; background-color: #ffffff; color: #445166; font-size: 12px; }}
.select {{ color: #335cc5; font-weight: bold; }}
.composer-label {{ margin-top: 24px; padding-top: 18px; padding-bottom: 10px; border-top: 1px solid #dfe3ea; color: #657184; font-size: 12px; }}
.primary {{ background-color: #335cc5; border-color: #335cc5; color: #ffffff; }}
.good {{ color: #208450; }}
.bad,.danger {{ color: #bd3546; }}
.accent {{ color: #335cc5; }}
.muted {{ color: #657184; }}
.welcome {{ margin-top: 26px; padding: 4px 0px; color: #202632; }}
.welcome b {{ font-size: 18px; }}
.turn {{ margin-bottom: 24px; }}
.caption,.assistant-title {{ margin-bottom: 8px; font-size: 11px; color: #657184; }}
.timestamp {{ padding-left: 8px; font-size: 11px; color: #657184; }}
.context-files {{ margin-top: 6px; font-size: 11px; color: #657184; }}
.assistant-title {{ margin-top: 18px; }}
.assistant-title b {{ color: #335cc5; }}
.user {{ padding: 12px 14px; border-radius: 8px; background-color: #eaf0fc; color: #263a5b; }}
.assistant {{ padding: 0px 2px; color: #202632; }}
.working {{ padding: 10px 0px; color: #335cc5; }}
.thinking {{ margin-top: 10px; margin-bottom: 12px; padding: 10px 12px; border: 1px solid #dfe3ea; border-radius: 6px; background-color: #eef1f5; }}
.thinking-text {{ padding-top: 10px; color: #445166; font-size: 12px; }}
.progress-meta {{ padding-top: 4px; font-size: 11px; color: #657184; }}
.pending {{ padding: 12px; margin-top: 10px; margin-bottom: 10px; border: 1px solid #dfe3ea; border-radius: 6px; background-color: #eaf0fc; }}
.pending-actions {{ padding-top: 8px; line-height: 32px; }}
.session-bar {{ padding-top: 14px; font-size: 12px; color: #657184; }}
.session-links {{ padding-top: 6px; line-height: 24px; }}
.message-actions {{ padding-bottom: 8px; font-size: 11px; }}
.code-caption {{ margin-bottom: 8px; white-space: normal; font-size: 11px; font-family: "Segoe UI", sans-serif; color: #657184; }}
.changes {{ margin-top: 12px; padding: 10px 12px; border: 1px solid #dfe3ea; border-radius: 6px; background-color: #eef1f5; }}
.change-file {{ padding-top: 8px; padding-bottom: 8px; border-bottom: 1px solid #dfe3ea; }}
.activity {{ padding: 6px 0px; margin-bottom: 3px; color: #445166; font-size: 12px; }}
.error {{ padding: 12px; border: 1px solid #f0c9ce; border-radius: 6px; background-color: #fff1f3; color: #a92c3c; }}
.code {{ padding: 12px; margin-top: 8px; margin-bottom: 8px; border: 1px solid #dfe3ea; border-radius: 6px; background-color: #eef1f5; color: #26364a; font-family: Consolas, monospace; white-space: pre-wrap; }}
</style>
<div class="header"><div class="brand">OpenCode Agent</div><div class="meta">{} {}</div><div class="toolbar">{}</div><div class="toolbar-gap"><br></div><div class="actions">{}</div>{}</div>
{}
<div class="composer-label"><b>Your message</b> · Ctrl+Enter to send</div>
</body></html>
""".format(status, server, selectors, actions, session_bar, "".join(body))
if state["color_mode"] == "dark":
# Replace tokens simultaneously so a new color cannot be replaced again.
import re
start, end = markup.index("<style>"), markup.index("</style>")
css = re.sub(r"#[0-9a-f]{6}", lambda m: DARK_COLORS.get(m.group(), m.group()), markup[start:end])
css = css.replace("color: #252e3e; }", "color: #17233c; }")
markup = markup[:start] + css + markup[end:]
return markup
def render(window_id):
state = _states.get(window_id)
if not state:
return
composer = state.get("composer")
phantoms = state.get("phantoms")
if composer is not None and composer.is_valid() and phantoms is not None:
apply_color_mode(state)
# The protected first newline anchors the HTML above the editable draft.
# Edits start at point 1, so the phantom never moves when the user types.
phantoms.update([
sublime.Phantom(sublime.Region(0, 0), build_html(state), sublime.LAYOUT_BLOCK)
])
def draft_text(view):
return view.substr(sublime.Region(1, view.size()))
def open_ui(window):
state = state_for(window)
composer = state["composer"]
if composer is not None and composer.is_valid():
window.focus_view(composer)
return state
state["old_layout"] = window.layout()
window.set_layout(LAYOUT)
window.focus_group(1)
composer = window.new_file()
composer.set_scratch(True)
composer.set_name("OpenCode Agent")
settings = composer.settings()
for key, value in {
"opencode_composer": True,
"word_wrap": True,
"line_numbers": False,
"gutter": False,
"spell_check": False,
"font_face": "Segoe UI",
"font_size": 11,
"draw_indent_guides": False,
"highlight_line": False,
"auto_complete": False,
"draw_centered": False,
"margin": 16,
"scroll_past_end": False,
}.items():
settings.set(key, value)
composer.assign_syntax("Packages/Text/Plain text.tmLanguage")
composer.set_status("opencode", "Ctrl+Enter to send · Enter for a new line")
window.set_view_index(composer, 1, 0)
state["composer"] = composer
composer.run_command("opencode_replace_text", {"text": state.get("saved_draft", "")})
state["phantoms"] = sublime.PhantomSet(composer, "opencode_agent")
apply_color_mode(state)
render(window.id())
window.focus_view(composer)
refresh_files(window.id())
return state
def load_metadata(window_id):
state = _states.get(window_id)
if not state:
return
directory = state["directory"]
expected_state = state
try:
health = ensure_server(directory)
agents = parse_agents(request_json("GET", "/agent", timeout=10, directory=directory))
models = parse_models(request_json("GET", "/provider", timeout=20, directory=directory))
config = request_json("GET", "/config", timeout=10, directory=directory) or {}
def apply():
state = _states.get(window_id)
if state is not expected_state:
return
state["connecting"] = False
state["connected"] = bool(health.get("healthy"))
state["version"] = health.get("version") or ""
state["error"] = ""
state["agents"] = agents
state["models"] = models
state["config_model"] = config.get("model")
default_agent = config.get("default_agent") or "build"
names = {a["name"] for a in agents}
if state["preferred_agent"] in names:
state["agent"] = state["preferred_agent"]
elif default_agent in names:
state["agent"] = default_agent
elif "build" in names:
state["agent"] = "build"
elif agents:
state["agent"] = agents[0]["name"]
selected = state["selected_model"]
if selected:
match = next((model for model in models if (
model["provider_id"], model["model_id"]
) == (selected["provider_id"], selected["model_id"])), None)
state["selected_model"] = match
if match is None:
sublime.status_message("OpenCode: saved model unavailable; using Auto.")
render(window_id)
if state.get("restore_pending") and not state.get("session_loading"):
load_session(state, state["restore_id"])
sublime.set_timeout(apply)
except Exception as error:
def fail(message=str(error)):
state = _states.get(window_id)
if state is expected_state:
state["connecting"] = False
state["connected"] = False
state["error"] = message
render(window_id)
sublime.set_timeout(fail)
def extract_text(result):
return "\n\n".join(
part.get("text", "")
for part in (result or {}).get("parts", [])
if part.get("type") == "text" and part.get("text")
)
def extract_activities(result):
activities = []