@cortexkit/aft-opencode 0.12.1 → 0.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config.d.ts.map +1 -1
- package/dist/index.js +53 -17
- package/dist/onnx-runtime.d.ts.map +1 -1
- package/package.json +9 -7
- package/src/shared/opencode-config-dir.ts +46 -0
- package/src/shared/rpc-client.ts +123 -0
- package/src/shared/rpc-server.ts +135 -0
- package/src/shared/rpc-utils.ts +21 -0
- package/src/shared/runtime.ts +26 -0
- package/src/shared/status.ts +206 -0
- package/src/shared/tui-config.ts +58 -0
- package/src/shared/url-fetch.ts +237 -0
- package/src/tui/index.tsx +209 -0
- package/src/tui/types/opencode-plugin-tui.d.ts +232 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
export interface AftStatusSnapshot {
|
|
2
|
+
version: string;
|
|
3
|
+
project_root: string | null;
|
|
4
|
+
features: {
|
|
5
|
+
format_on_edit: boolean;
|
|
6
|
+
validate_on_edit: string;
|
|
7
|
+
restrict_to_project_root: boolean;
|
|
8
|
+
experimental_search_index: boolean;
|
|
9
|
+
experimental_semantic_search: boolean;
|
|
10
|
+
};
|
|
11
|
+
search_index: {
|
|
12
|
+
status: string;
|
|
13
|
+
files: number | null;
|
|
14
|
+
trigrams: number | null;
|
|
15
|
+
};
|
|
16
|
+
semantic_index: {
|
|
17
|
+
status: string;
|
|
18
|
+
entries: number | null;
|
|
19
|
+
dimension: number | null;
|
|
20
|
+
};
|
|
21
|
+
disk: {
|
|
22
|
+
storage_dir: string | null;
|
|
23
|
+
trigram_disk_bytes: number;
|
|
24
|
+
semantic_disk_bytes: number;
|
|
25
|
+
};
|
|
26
|
+
lsp_servers: number;
|
|
27
|
+
symbol_cache: {
|
|
28
|
+
local_entries: number;
|
|
29
|
+
warm_entries: number;
|
|
30
|
+
};
|
|
31
|
+
storage_dir: string | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function asRecord(value: unknown): Record<string, unknown> {
|
|
35
|
+
return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readString(value: unknown, fallback = ""): string {
|
|
39
|
+
return typeof value === "string" ? value : fallback;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readNullableString(value: unknown): string | null {
|
|
43
|
+
return typeof value === "string" ? value : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function readBoolean(value: unknown, fallback = false): boolean {
|
|
47
|
+
return typeof value === "boolean" ? value : fallback;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readNumber(value: unknown, fallback = 0): number {
|
|
51
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readOptionalNumber(value: unknown): number | null {
|
|
55
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function formatFlag(enabled: boolean): string {
|
|
59
|
+
return enabled ? "enabled" : "disabled";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function formatCount(value: number | null): string {
|
|
63
|
+
return value == null ? "—" : value.toLocaleString("en-US");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function formatBytes(bytes: number): string {
|
|
67
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
|
|
68
|
+
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
69
|
+
let value = bytes;
|
|
70
|
+
let unitIndex = 0;
|
|
71
|
+
|
|
72
|
+
while (value >= 1024 && unitIndex < units.length - 1) {
|
|
73
|
+
value /= 1024;
|
|
74
|
+
unitIndex++;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const decimals = value >= 10 || unitIndex === 0 ? 0 : 1;
|
|
78
|
+
return `${value.toFixed(decimals)} ${units[unitIndex]}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function coerceAftStatus(response: Record<string, unknown>): AftStatusSnapshot {
|
|
82
|
+
const features = asRecord(response.features);
|
|
83
|
+
const searchIndex = asRecord(response.search_index);
|
|
84
|
+
const semanticIndex = asRecord(response.semantic_index);
|
|
85
|
+
const disk = asRecord(response.disk);
|
|
86
|
+
const symbolCache = asRecord(response.symbol_cache);
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
version: readString(response.version, "unknown"),
|
|
90
|
+
project_root: readNullableString(response.project_root),
|
|
91
|
+
features: {
|
|
92
|
+
format_on_edit: readBoolean(features.format_on_edit),
|
|
93
|
+
validate_on_edit: readString(features.validate_on_edit, "off"),
|
|
94
|
+
restrict_to_project_root: readBoolean(features.restrict_to_project_root),
|
|
95
|
+
experimental_search_index: readBoolean(features.experimental_search_index),
|
|
96
|
+
experimental_semantic_search: readBoolean(features.experimental_semantic_search),
|
|
97
|
+
},
|
|
98
|
+
search_index: {
|
|
99
|
+
status: readString(searchIndex.status, "unknown"),
|
|
100
|
+
files: readOptionalNumber(searchIndex.files),
|
|
101
|
+
trigrams: readOptionalNumber(searchIndex.trigrams),
|
|
102
|
+
},
|
|
103
|
+
semantic_index: {
|
|
104
|
+
status: readString(semanticIndex.status, "unknown"),
|
|
105
|
+
entries: readOptionalNumber(semanticIndex.entries),
|
|
106
|
+
dimension: readOptionalNumber(semanticIndex.dimension),
|
|
107
|
+
},
|
|
108
|
+
disk: {
|
|
109
|
+
storage_dir: readNullableString(disk.storage_dir),
|
|
110
|
+
trigram_disk_bytes: readNumber(disk.trigram_disk_bytes),
|
|
111
|
+
semantic_disk_bytes: readNumber(disk.semantic_disk_bytes),
|
|
112
|
+
},
|
|
113
|
+
lsp_servers: readNumber(response.lsp_servers),
|
|
114
|
+
symbol_cache: {
|
|
115
|
+
local_entries: readNumber(symbolCache.local_entries),
|
|
116
|
+
warm_entries: readNumber(symbolCache.warm_entries),
|
|
117
|
+
},
|
|
118
|
+
storage_dir: readNullableString(response.storage_dir),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function formatStatusDialogMessage(status: AftStatusSnapshot): string {
|
|
123
|
+
const lines = [
|
|
124
|
+
`AFT version: ${status.version}`,
|
|
125
|
+
`Project root: ${status.project_root ?? "(not configured)"}`,
|
|
126
|
+
"",
|
|
127
|
+
"Enabled features",
|
|
128
|
+
`- format_on_edit: ${formatFlag(status.features.format_on_edit)}`,
|
|
129
|
+
`- experimental_search_index: ${formatFlag(status.features.experimental_search_index)}`,
|
|
130
|
+
`- experimental_semantic_search: ${formatFlag(status.features.experimental_semantic_search)}`,
|
|
131
|
+
"",
|
|
132
|
+
"Search index",
|
|
133
|
+
`- status: ${status.search_index.status}`,
|
|
134
|
+
`- files: ${formatCount(status.search_index.files)}`,
|
|
135
|
+
`- trigrams: ${formatCount(status.search_index.trigrams)}`,
|
|
136
|
+
"",
|
|
137
|
+
"Semantic index",
|
|
138
|
+
`- status: ${status.semantic_index.status}`,
|
|
139
|
+
`- entries: ${formatCount(status.semantic_index.entries)}`,
|
|
140
|
+
];
|
|
141
|
+
|
|
142
|
+
if (status.semantic_index.dimension != null) {
|
|
143
|
+
lines.push(`- dimension: ${formatCount(status.semantic_index.dimension)}`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
lines.push(
|
|
147
|
+
"",
|
|
148
|
+
"Disk usage",
|
|
149
|
+
`- trigram index: ${formatBytes(status.disk.trigram_disk_bytes)}`,
|
|
150
|
+
`- semantic index: ${formatBytes(status.disk.semantic_disk_bytes)}`,
|
|
151
|
+
"",
|
|
152
|
+
"Runtime",
|
|
153
|
+
`- LSP servers: ${formatCount(status.lsp_servers)}`,
|
|
154
|
+
`- symbol cache: ${formatCount(status.symbol_cache.local_entries)} local / ${formatCount(status.symbol_cache.warm_entries)} warm`,
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
if (status.storage_dir ?? status.disk.storage_dir) {
|
|
158
|
+
lines.push(`- storage dir: ${status.storage_dir ?? status.disk.storage_dir}`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return lines.join("\n");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function formatStatusMarkdown(status: AftStatusSnapshot): string {
|
|
165
|
+
const lines = [
|
|
166
|
+
"## AFT Status",
|
|
167
|
+
"",
|
|
168
|
+
`- **Version:** \`${status.version}\``,
|
|
169
|
+
`- **Project root:** \`${status.project_root ?? "(not configured)"}\``,
|
|
170
|
+
"",
|
|
171
|
+
"### Enabled features",
|
|
172
|
+
`- \`format_on_edit\`: ${formatFlag(status.features.format_on_edit)}`,
|
|
173
|
+
`- \`experimental_search_index\`: ${formatFlag(status.features.experimental_search_index)}`,
|
|
174
|
+
`- \`experimental_semantic_search\`: ${formatFlag(status.features.experimental_semantic_search)}`,
|
|
175
|
+
"",
|
|
176
|
+
"### Search index",
|
|
177
|
+
`- **Status:** \`${status.search_index.status}\``,
|
|
178
|
+
`- **Files:** ${formatCount(status.search_index.files)}`,
|
|
179
|
+
`- **Trigrams:** ${formatCount(status.search_index.trigrams)}`,
|
|
180
|
+
"",
|
|
181
|
+
"### Semantic index",
|
|
182
|
+
`- **Status:** \`${status.semantic_index.status}\``,
|
|
183
|
+
`- **Entries:** ${formatCount(status.semantic_index.entries)}`,
|
|
184
|
+
];
|
|
185
|
+
|
|
186
|
+
if (status.semantic_index.dimension != null) {
|
|
187
|
+
lines.push(`- **Dimension:** ${formatCount(status.semantic_index.dimension)}`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
lines.push(
|
|
191
|
+
"",
|
|
192
|
+
"### Disk usage",
|
|
193
|
+
`- **Trigram index:** ${formatBytes(status.disk.trigram_disk_bytes)}`,
|
|
194
|
+
`- **Semantic index:** ${formatBytes(status.disk.semantic_disk_bytes)}`,
|
|
195
|
+
"",
|
|
196
|
+
"### Runtime",
|
|
197
|
+
`- **LSP servers:** ${formatCount(status.lsp_servers)}`,
|
|
198
|
+
`- **Symbol cache:** ${formatCount(status.symbol_cache.local_entries)} local / ${formatCount(status.symbol_cache.warm_entries)} warm`,
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
if (status.storage_dir ?? status.disk.storage_dir) {
|
|
202
|
+
lines.push(`- **Storage dir:** \`${status.storage_dir ?? status.disk.storage_dir}\``);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return lines.join("\n");
|
|
206
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { parse, stringify } from "comment-json";
|
|
4
|
+
import { log } from "../logger";
|
|
5
|
+
import { getOpenCodeConfigPaths } from "./opencode-config-dir";
|
|
6
|
+
|
|
7
|
+
const PLUGIN_NAME = "@cortexkit/aft-opencode";
|
|
8
|
+
const PLUGIN_ENTRY = `${PLUGIN_NAME}@latest`;
|
|
9
|
+
|
|
10
|
+
function resolveTuiConfigPath(): string {
|
|
11
|
+
const configDir = getOpenCodeConfigPaths({ binary: "opencode" }).configDir;
|
|
12
|
+
const jsoncPath = join(configDir, "tui.jsonc");
|
|
13
|
+
const jsonPath = join(configDir, "tui.json");
|
|
14
|
+
|
|
15
|
+
if (existsSync(jsoncPath)) return jsoncPath;
|
|
16
|
+
if (existsSync(jsonPath)) return jsonPath;
|
|
17
|
+
return jsonPath;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function ensureTuiPluginEntry(): boolean {
|
|
21
|
+
try {
|
|
22
|
+
const configPath = resolveTuiConfigPath();
|
|
23
|
+
|
|
24
|
+
let config: Record<string, unknown> = {};
|
|
25
|
+
if (existsSync(configPath)) {
|
|
26
|
+
config = (parse(readFileSync(configPath, "utf-8")) as Record<string, unknown>) ?? {};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const plugins = Array.isArray(config.plugin)
|
|
30
|
+
? config.plugin.filter((value): value is string => typeof value === "string")
|
|
31
|
+
: [];
|
|
32
|
+
|
|
33
|
+
if (
|
|
34
|
+
plugins.some(
|
|
35
|
+
(plugin) =>
|
|
36
|
+
plugin === PLUGIN_NAME ||
|
|
37
|
+
plugin.startsWith(`${PLUGIN_NAME}@`) ||
|
|
38
|
+
plugin.includes("opencode-plugin") ||
|
|
39
|
+
plugin.includes("aft-opencode"),
|
|
40
|
+
)
|
|
41
|
+
) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
plugins.push(PLUGIN_ENTRY);
|
|
46
|
+
config.plugin = plugins;
|
|
47
|
+
|
|
48
|
+
mkdirSync(dirname(configPath), { recursive: true });
|
|
49
|
+
writeFileSync(configPath, `${stringify(config, null, 2)}\n`);
|
|
50
|
+
log(`[aft-plugin] added TUI plugin entry to ${configPath}`);
|
|
51
|
+
return true;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
log(
|
|
54
|
+
`[aft-plugin] failed to update tui.json: ${error instanceof Error ? error.message : String(error)}`,
|
|
55
|
+
);
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
readdirSync,
|
|
6
|
+
readFileSync,
|
|
7
|
+
unlinkSync,
|
|
8
|
+
writeFileSync,
|
|
9
|
+
} from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { log, warn } from "../logger";
|
|
12
|
+
|
|
13
|
+
/** Max response body size (10 MB) */
|
|
14
|
+
const MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
|
|
15
|
+
/** Cache TTL: 1 day */
|
|
16
|
+
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
17
|
+
/** Fetch timeout: 30 seconds */
|
|
18
|
+
const FETCH_TIMEOUT_MS = 30_000;
|
|
19
|
+
|
|
20
|
+
interface CacheMeta {
|
|
21
|
+
url: string;
|
|
22
|
+
contentType: string;
|
|
23
|
+
extension: string;
|
|
24
|
+
fetchedAt: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function cacheDir(storageDir: string): string {
|
|
28
|
+
return join(storageDir, "url_cache");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function hashUrl(url: string): string {
|
|
32
|
+
return createHash("sha256").update(url).digest("hex").slice(0, 16);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function metaPath(storageDir: string, hash: string): string {
|
|
36
|
+
return join(cacheDir(storageDir), `${hash}.meta.json`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function contentPath(storageDir: string, hash: string, extension: string): string {
|
|
40
|
+
return join(cacheDir(storageDir), `${hash}${extension}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Map a Content-Type header to a file extension AFT can parse.
|
|
45
|
+
* Returns null for unsupported types.
|
|
46
|
+
*/
|
|
47
|
+
function resolveExtension(contentType: string): string | null {
|
|
48
|
+
// Normalize: strip parameters (after `;`) AND pick the first value if the server
|
|
49
|
+
// echoed back a comma-separated list (GitHub API does this for /readme endpoints).
|
|
50
|
+
const lower = contentType.toLowerCase().split(";")[0].split(",")[0].trim();
|
|
51
|
+
if (
|
|
52
|
+
lower === "text/html" ||
|
|
53
|
+
lower === "application/xhtml+xml" ||
|
|
54
|
+
lower === "application/vnd.github.html" ||
|
|
55
|
+
lower === "application/vnd.github+html"
|
|
56
|
+
) {
|
|
57
|
+
return ".html";
|
|
58
|
+
}
|
|
59
|
+
if (
|
|
60
|
+
lower === "text/markdown" ||
|
|
61
|
+
lower === "text/x-markdown" ||
|
|
62
|
+
lower === "application/markdown" ||
|
|
63
|
+
// GitHub API raw content type — returns raw markdown for README endpoints
|
|
64
|
+
lower === "application/vnd.github.raw" ||
|
|
65
|
+
lower === "application/vnd.github+raw" ||
|
|
66
|
+
lower === "application/vnd.github.v3.raw"
|
|
67
|
+
) {
|
|
68
|
+
return ".md";
|
|
69
|
+
}
|
|
70
|
+
if (lower === "text/plain") {
|
|
71
|
+
// treat plain text as markdown so aft_outline can show headings if present
|
|
72
|
+
return ".md";
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Fetch a URL to a cached temp file. Uses disk cache with 1-day TTL.
|
|
79
|
+
* Returns the cached file path the Rust outline/zoom command can read.
|
|
80
|
+
* Throws on errors (invalid URL, network failure, unsupported content type, oversized body).
|
|
81
|
+
*/
|
|
82
|
+
export async function fetchUrlToTempFile(url: string, storageDir: string): Promise<string> {
|
|
83
|
+
let parsed: URL;
|
|
84
|
+
try {
|
|
85
|
+
parsed = new URL(url);
|
|
86
|
+
} catch {
|
|
87
|
+
throw new Error(`Invalid URL: ${url}`);
|
|
88
|
+
}
|
|
89
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
90
|
+
throw new Error(`Only http:// and https:// URLs are supported, got: ${parsed.protocol}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const dir = cacheDir(storageDir);
|
|
94
|
+
mkdirSync(dir, { recursive: true });
|
|
95
|
+
|
|
96
|
+
const hash = hashUrl(url);
|
|
97
|
+
const metaFile = metaPath(storageDir, hash);
|
|
98
|
+
|
|
99
|
+
// Check cache
|
|
100
|
+
if (existsSync(metaFile)) {
|
|
101
|
+
try {
|
|
102
|
+
const meta = JSON.parse(readFileSync(metaFile, "utf8")) as CacheMeta;
|
|
103
|
+
const age = Date.now() - meta.fetchedAt;
|
|
104
|
+
const cached = contentPath(storageDir, hash, meta.extension);
|
|
105
|
+
if (age < CACHE_TTL_MS && existsSync(cached)) {
|
|
106
|
+
log(`URL cache hit: ${url} (${Math.round(age / 1000)}s old)`);
|
|
107
|
+
return cached;
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
// corrupted meta, re-fetch
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
log(`Fetching URL: ${url}`);
|
|
115
|
+
|
|
116
|
+
const controller = new AbortController();
|
|
117
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
118
|
+
let response: Response;
|
|
119
|
+
try {
|
|
120
|
+
response = await fetch(url, {
|
|
121
|
+
signal: controller.signal,
|
|
122
|
+
redirect: "follow",
|
|
123
|
+
headers: {
|
|
124
|
+
"user-agent": "aft-opencode-plugin",
|
|
125
|
+
// Prioritize markdown for content-negotiating servers (GitHub API, many docs sites).
|
|
126
|
+
// `application/vnd.github.raw` is GitHub's custom type — returns raw markdown from
|
|
127
|
+
// repo file and readme endpoints. Falls back to HTML if markdown is not available.
|
|
128
|
+
accept:
|
|
129
|
+
"application/vnd.github.raw, text/markdown, text/x-markdown, text/html;q=0.9, text/plain;q=0.5",
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
} catch (err) {
|
|
133
|
+
throw new Error(`Failed to fetch ${url}: ${(err as Error).message}`);
|
|
134
|
+
} finally {
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (!response.ok) {
|
|
139
|
+
throw new Error(`HTTP ${response.status} ${response.statusText} fetching ${url}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const contentType = response.headers.get("content-type") || "text/plain";
|
|
143
|
+
const extension = resolveExtension(contentType);
|
|
144
|
+
if (!extension) {
|
|
145
|
+
throw new Error(
|
|
146
|
+
`Unsupported content type '${contentType}' for ${url}. Supported: text/html, text/markdown, text/plain`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const lengthHeader = response.headers.get("content-length");
|
|
151
|
+
if (lengthHeader) {
|
|
152
|
+
const length = Number.parseInt(lengthHeader, 10);
|
|
153
|
+
if (Number.isFinite(length) && length > MAX_RESPONSE_BYTES) {
|
|
154
|
+
throw new Error(`Response too large: ${length} bytes (max ${MAX_RESPONSE_BYTES})`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Stream with size cap
|
|
159
|
+
const reader = response.body?.getReader();
|
|
160
|
+
if (!reader) {
|
|
161
|
+
throw new Error(`Failed to read response body for ${url}`);
|
|
162
|
+
}
|
|
163
|
+
const chunks: Uint8Array[] = [];
|
|
164
|
+
let total = 0;
|
|
165
|
+
while (true) {
|
|
166
|
+
const { done, value } = await reader.read();
|
|
167
|
+
if (done) break;
|
|
168
|
+
if (value) {
|
|
169
|
+
total += value.length;
|
|
170
|
+
if (total > MAX_RESPONSE_BYTES) {
|
|
171
|
+
reader.cancel().catch(() => {});
|
|
172
|
+
throw new Error(`Response exceeded ${MAX_RESPONSE_BYTES} bytes, aborted`);
|
|
173
|
+
}
|
|
174
|
+
chunks.push(value);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Write content and meta atomically
|
|
179
|
+
const body = Buffer.concat(chunks);
|
|
180
|
+
const contentFile = contentPath(storageDir, hash, extension);
|
|
181
|
+
const tmpContent = `${contentFile}.tmp-${process.pid}`;
|
|
182
|
+
writeFileSync(tmpContent, body);
|
|
183
|
+
const { renameSync } = await import("node:fs");
|
|
184
|
+
renameSync(tmpContent, contentFile);
|
|
185
|
+
|
|
186
|
+
const meta: CacheMeta = {
|
|
187
|
+
url,
|
|
188
|
+
contentType,
|
|
189
|
+
extension,
|
|
190
|
+
fetchedAt: Date.now(),
|
|
191
|
+
};
|
|
192
|
+
const tmpMeta = `${metaFile}.tmp-${process.pid}`;
|
|
193
|
+
writeFileSync(tmpMeta, JSON.stringify(meta));
|
|
194
|
+
renameSync(tmpMeta, metaFile);
|
|
195
|
+
|
|
196
|
+
log(`URL cached (${total} bytes): ${url}`);
|
|
197
|
+
return contentFile;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Remove cache entries older than TTL. Called periodically at plugin startup.
|
|
202
|
+
*/
|
|
203
|
+
export function cleanupUrlCache(storageDir: string): void {
|
|
204
|
+
const dir = cacheDir(storageDir);
|
|
205
|
+
if (!existsSync(dir)) return;
|
|
206
|
+
|
|
207
|
+
let removed = 0;
|
|
208
|
+
try {
|
|
209
|
+
for (const entry of readdirSync(dir)) {
|
|
210
|
+
if (!entry.endsWith(".meta.json")) continue;
|
|
211
|
+
const metaFile = join(dir, entry);
|
|
212
|
+
try {
|
|
213
|
+
const meta = JSON.parse(readFileSync(metaFile, "utf8")) as CacheMeta;
|
|
214
|
+
const age = Date.now() - meta.fetchedAt;
|
|
215
|
+
if (age > CACHE_TTL_MS) {
|
|
216
|
+
const hash = entry.slice(0, -".meta.json".length);
|
|
217
|
+
const content = contentPath(storageDir, hash, meta.extension);
|
|
218
|
+
if (existsSync(content)) unlinkSync(content);
|
|
219
|
+
unlinkSync(metaFile);
|
|
220
|
+
removed++;
|
|
221
|
+
}
|
|
222
|
+
} catch {
|
|
223
|
+
// corrupted meta, remove it too
|
|
224
|
+
try {
|
|
225
|
+
unlinkSync(metaFile);
|
|
226
|
+
removed++;
|
|
227
|
+
} catch {}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch (err) {
|
|
231
|
+
warn(`URL cache cleanup failed: ${(err as Error).message}`);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (removed > 0) {
|
|
235
|
+
log(`URL cache cleanup: removed ${removed} stale entries`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/solid */
|
|
2
|
+
// @ts-nocheck
|
|
3
|
+
|
|
4
|
+
import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui";
|
|
5
|
+
import { AftRpcClient } from "../shared/rpc-client";
|
|
6
|
+
import { coerceAftStatus, formatStatusDialogMessage } from "../shared/status";
|
|
7
|
+
|
|
8
|
+
const STATUS_COMMAND = "aft-status";
|
|
9
|
+
|
|
10
|
+
// RPC clients keyed by directory — one per project
|
|
11
|
+
const rpcClients = new Map<string, AftRpcClient>();
|
|
12
|
+
|
|
13
|
+
function getRpcClient(directory: string): AftRpcClient {
|
|
14
|
+
let client = rpcClients.get(directory);
|
|
15
|
+
if (client) return client;
|
|
16
|
+
|
|
17
|
+
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
18
|
+
const dataHome = process.env.XDG_DATA_HOME || `${home}/.local/share`;
|
|
19
|
+
const storageDir = `${dataHome}/opencode/storage/plugin/aft`;
|
|
20
|
+
|
|
21
|
+
client = new AftRpcClient(storageDir, directory);
|
|
22
|
+
rpcClients.set(directory, client);
|
|
23
|
+
return client;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function getSessionId(api: TuiPluginApi): string | null {
|
|
27
|
+
try {
|
|
28
|
+
const route = api.route.current;
|
|
29
|
+
if (route?.name === "session" && route.params?.sessionID) {
|
|
30
|
+
return route.params.sessionID;
|
|
31
|
+
}
|
|
32
|
+
} catch {
|
|
33
|
+
// ignore
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function showStatusDialog(api: TuiPluginApi): Promise<void> {
|
|
39
|
+
const sessionID = getSessionId(api);
|
|
40
|
+
if (!sessionID) {
|
|
41
|
+
api.ui.toast({ message: "No active session", variant: "warning", duration: 5000 });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const directory = api.state.path.directory ?? "";
|
|
46
|
+
if (!directory) {
|
|
47
|
+
api.ui.toast({ message: "No project directory", variant: "warning", duration: 5000 });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const client = getRpcClient(directory);
|
|
52
|
+
|
|
53
|
+
// Fetch status immediately and show the dialog
|
|
54
|
+
let currentMessage = "Connecting to AFT...";
|
|
55
|
+
try {
|
|
56
|
+
const response = await client.call("status", { sessionID });
|
|
57
|
+
if ((response as Record<string, unknown>).success !== false) {
|
|
58
|
+
const status = coerceAftStatus(response as Record<string, unknown>);
|
|
59
|
+
currentMessage = formatStatusDialogMessage(status);
|
|
60
|
+
}
|
|
61
|
+
} catch {
|
|
62
|
+
currentMessage = "AFT is starting up. Status will refresh automatically...";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Track whether dialog is still open for polling cleanup
|
|
66
|
+
let dialogOpen = true;
|
|
67
|
+
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
|
68
|
+
|
|
69
|
+
// Show dialog with initial data
|
|
70
|
+
api.ui.dialog.setSize("large");
|
|
71
|
+
api.ui.dialog.replace(
|
|
72
|
+
() => {
|
|
73
|
+
// Start polling after dialog renders
|
|
74
|
+
if (!pollTimer) {
|
|
75
|
+
pollTimer = setInterval(async () => {
|
|
76
|
+
if (!dialogOpen) {
|
|
77
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const response = await client.call("status", { sessionID });
|
|
82
|
+
if ((response as Record<string, unknown>).success !== false) {
|
|
83
|
+
const status = coerceAftStatus(response as Record<string, unknown>);
|
|
84
|
+
const newMessage = formatStatusDialogMessage(status);
|
|
85
|
+
if (newMessage !== currentMessage) {
|
|
86
|
+
currentMessage = newMessage;
|
|
87
|
+
// Re-render dialog with updated status
|
|
88
|
+
api.ui.dialog.replace(
|
|
89
|
+
() => (
|
|
90
|
+
<api.ui.DialogAlert
|
|
91
|
+
title="AFT Status"
|
|
92
|
+
message={currentMessage}
|
|
93
|
+
onConfirm={() => {
|
|
94
|
+
dialogOpen = false;
|
|
95
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
96
|
+
api.ui.dialog.setSize("medium");
|
|
97
|
+
}}
|
|
98
|
+
/>
|
|
99
|
+
),
|
|
100
|
+
() => {
|
|
101
|
+
dialogOpen = false;
|
|
102
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
103
|
+
api.ui.dialog.setSize("medium");
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
// Polling failure is non-fatal — just skip this tick
|
|
110
|
+
}
|
|
111
|
+
}, 1500);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return (
|
|
115
|
+
<api.ui.DialogAlert
|
|
116
|
+
title="AFT Status"
|
|
117
|
+
message={currentMessage}
|
|
118
|
+
onConfirm={() => {
|
|
119
|
+
dialogOpen = false;
|
|
120
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
121
|
+
api.ui.dialog.setSize("medium");
|
|
122
|
+
}}
|
|
123
|
+
/>
|
|
124
|
+
);
|
|
125
|
+
},
|
|
126
|
+
() => {
|
|
127
|
+
dialogOpen = false;
|
|
128
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
129
|
+
api.ui.dialog.setSize("medium");
|
|
130
|
+
},
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function showStartupNotifications(api: TuiPluginApi): Promise<void> {
|
|
135
|
+
const directory = api.state.path.directory ?? "";
|
|
136
|
+
if (!directory) return;
|
|
137
|
+
|
|
138
|
+
const client = getRpcClient(directory);
|
|
139
|
+
|
|
140
|
+
// Check for feature announcements
|
|
141
|
+
try {
|
|
142
|
+
const announcement = (await client.call("get-announcement", {})) as {
|
|
143
|
+
show?: boolean;
|
|
144
|
+
version?: string;
|
|
145
|
+
features?: string[];
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
if (announcement.show && announcement.version && announcement.features?.length) {
|
|
149
|
+
const featureText = announcement.features.map((f: string) => ` • ${f}`).join("\n");
|
|
150
|
+
|
|
151
|
+
api.ui.dialog.replace(
|
|
152
|
+
() => (
|
|
153
|
+
<api.ui.DialogAlert
|
|
154
|
+
title={`AFT v${announcement.version}`}
|
|
155
|
+
message={`What's new:\n\n${featureText}`}
|
|
156
|
+
onConfirm={() => {
|
|
157
|
+
// Mark as announced so it doesn't show again
|
|
158
|
+
void client.call("mark-announced", {});
|
|
159
|
+
}}
|
|
160
|
+
/>
|
|
161
|
+
),
|
|
162
|
+
() => {
|
|
163
|
+
void client.call("mark-announced", {});
|
|
164
|
+
},
|
|
165
|
+
);
|
|
166
|
+
return; // Show one dialog at a time
|
|
167
|
+
}
|
|
168
|
+
} catch {
|
|
169
|
+
// RPC server not ready yet — skip announcements
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Check for warnings
|
|
173
|
+
try {
|
|
174
|
+
const result = (await client.call("get-warnings", {})) as { warnings?: string[] };
|
|
175
|
+
if (result.warnings?.length) {
|
|
176
|
+
const warningText = result.warnings.join("\n\n");
|
|
177
|
+
api.ui.dialog.replace(
|
|
178
|
+
() => <api.ui.DialogAlert title="AFT Warning" message={warningText} onConfirm={() => {}} />,
|
|
179
|
+
() => {},
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
// RPC server not ready — skip warnings
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const tui: TuiPlugin = async (api) => {
|
|
188
|
+
api.command.register(() => [
|
|
189
|
+
{
|
|
190
|
+
title: "AFT: Status",
|
|
191
|
+
value: "aft.status",
|
|
192
|
+
category: "AFT",
|
|
193
|
+
slash: { name: STATUS_COMMAND },
|
|
194
|
+
onSelect() {
|
|
195
|
+
void showStatusDialog(api);
|
|
196
|
+
},
|
|
197
|
+
},
|
|
198
|
+
]);
|
|
199
|
+
|
|
200
|
+
// Show startup notifications — RPC server is already running by the time TUI loads
|
|
201
|
+
void showStartupNotifications(api);
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const id = "aft-opencode";
|
|
205
|
+
|
|
206
|
+
export default {
|
|
207
|
+
id,
|
|
208
|
+
tui,
|
|
209
|
+
};
|