@wbcode/avron 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,418 @@
1
+ "use strict";
2
+
3
+ // packages/protocol/src/art.ts
4
+ var ART_LIMITS = { rows: 6, cols: 60 };
5
+ var ART_CHAR = /^[⠀-⣿▀-▟ ]*$/;
6
+ var COLOR = /^#[0-9a-f]{6}$/i;
7
+ function cleanArt(raw) {
8
+ if (typeof raw !== "object" || raw === null) return null;
9
+ const r = raw;
10
+ if (!Array.isArray(r.rows) || r.rows.length === 0 || r.rows.length > ART_LIMITS.rows) return null;
11
+ const rows = [];
12
+ for (const row of r.rows) {
13
+ if (typeof row !== "string" || !ART_CHAR.test(row) || [...row].length > ART_LIMITS.cols) return null;
14
+ rows.push(row.replace(/ +$/, ""));
15
+ }
16
+ while (rows.length && !rows[0]) rows.shift();
17
+ while (rows.length && !rows[rows.length - 1]) rows.pop();
18
+ if (!rows.length) return null;
19
+ const color = typeof r.color === "string" && COLOR.test(r.color) ? r.color.toLowerCase() : void 0;
20
+ return { rows, ...color ? { color } : {} };
21
+ }
22
+ var BLANK = String.fromCodePoint(10240);
23
+
24
+ // packages/protocol/src/constants.ts
25
+ var PROTOCOL_VERSION = "2.0.0";
26
+ var ADAPTER_TIMEOUT_MS = 15;
27
+ var MANIFEST_SYNC_INTERVAL_MS = 30 * 6e4;
28
+ var BATCH_FLUSH_INTERVAL_MS = 60 * 6e4;
29
+ var DAEMON_IDLE_EXIT_MS = 3 * 60 * 6e4;
30
+ var OFFLINE_QUEUE_MAX_BYTES = 5 * 1024 * 1024;
31
+ var MAX_LINE_BYTES = 8 * 1024;
32
+ var ALLOWED_LINK_PREFIX = "https://avron.dev/go/";
33
+ var SPONSOR_LABEL = "Sponsored";
34
+ var SPONSOR_LABELS = {
35
+ ko: "\uAD11\uACE0",
36
+ ja: "\u5E83\u544A",
37
+ "zh-CN": "\u5E7F\u544A",
38
+ "zh-TW": "\u5EE3\u544A",
39
+ es: "Patrocinado",
40
+ pt: "Patrocinado",
41
+ de: "Anzeige",
42
+ fr: "Sponsoris\xE9"
43
+ };
44
+
45
+ // packages/protocol/src/validate.ts
46
+ function isObject(v) {
47
+ return typeof v === "object" && v !== null && !Array.isArray(v);
48
+ }
49
+ function parsePayloadResponse(line) {
50
+ if (line.length === 0 || Buffer.byteLength(line, "utf8") > MAX_LINE_BYTES) return null;
51
+ let raw;
52
+ try {
53
+ raw = JSON.parse(line);
54
+ } catch {
55
+ return null;
56
+ }
57
+ if (!isObject(raw) || raw.eventType !== "PAYLOAD_RESPONSE") return null;
58
+ if (!isObject(raw.payload) || typeof raw.payload.active !== "boolean") return null;
59
+ if (typeof raw.sessionId !== "string") return null;
60
+ return raw;
61
+ }
62
+ function serialize(msg) {
63
+ return `${JSON.stringify(msg)}
64
+ `;
65
+ }
66
+
67
+ // packages/protocol/src/endpoint.ts
68
+ var import_node_crypto = require("node:crypto");
69
+ var import_node_os = require("node:os");
70
+ var import_node_path = require("node:path");
71
+ function placeOf(key) {
72
+ return (0, import_node_crypto.createHash)("sha256").update(`avron-place:${key}`).digest("hex").slice(0, 16);
73
+ }
74
+ var placeOfSession = (sessionId) => placeOf(`session:${sessionId}`);
75
+ function avronHome(env = process.env) {
76
+ return env.AVRON_HOME && env.AVRON_HOME.length > 0 ? env.AVRON_HOME : (0, import_node_path.join)((0, import_node_os.homedir)(), ".avron");
77
+ }
78
+ var UDS_MAX = 100;
79
+ function ipcEndpoint(env = process.env, platform = process.platform) {
80
+ const home = avronHome(env);
81
+ const tag = (0, import_node_crypto.createHash)("sha256").update(home).digest("hex").slice(0, 12);
82
+ if (platform === "win32") return `\\\\.\\pipe\\avron-uasp-${tag}.sock`;
83
+ const preferred = (0, import_node_path.join)(home, "run", "avron-uasp.sock");
84
+ if (Buffer.byteLength(preferred) <= UDS_MAX) return preferred;
85
+ return (0, import_node_path.join)((0, import_node_os.tmpdir)(), `avron-uasp-${tag}.sock`);
86
+ }
87
+
88
+ // packages/protocol/src/client.ts
89
+ var import_node_net = require("node:net");
90
+
91
+ // packages/protocol/src/quiet.ts
92
+ function quietHere(env = process.env) {
93
+ if (env.AVRON_ALLOW_CI === "1") return false;
94
+ const ci = (env.CI ?? "").trim().toLowerCase();
95
+ return ci !== "" && ci !== "0" && ci !== "false";
96
+ }
97
+
98
+ // packages/protocol/src/client.ts
99
+ function request(msg, opts = {}) {
100
+ if (quietHere()) return Promise.resolve(null);
101
+ const endpoint = opts.endpoint ?? ipcEndpoint();
102
+ const timeoutMs = opts.timeoutMs ?? ADAPTER_TIMEOUT_MS;
103
+ return new Promise((resolve3) => {
104
+ let done = false;
105
+ let buf = "";
106
+ const finish = (value) => {
107
+ if (done) return;
108
+ done = true;
109
+ clearTimeout(timer);
110
+ socket.destroy();
111
+ resolve3(value);
112
+ };
113
+ const timer = setTimeout(() => finish(null), timeoutMs);
114
+ const socket = (0, import_node_net.connect)(endpoint);
115
+ socket.setEncoding("utf8");
116
+ socket.on("connect", () => {
117
+ socket.write(serialize(msg));
118
+ });
119
+ socket.on("data", (chunk) => {
120
+ buf += chunk;
121
+ const nl = buf.indexOf("\n");
122
+ if (nl >= 0) finish(parsePayloadResponse(buf.slice(0, nl)));
123
+ else if (buf.length > MAX_LINE_BYTES) finish(null);
124
+ });
125
+ socket.on("error", () => finish(null));
126
+ socket.on("close", () => finish(null));
127
+ });
128
+ }
129
+ function send(msg, opts = {}) {
130
+ if (quietHere()) return Promise.resolve(false);
131
+ const endpoint = opts.endpoint ?? ipcEndpoint();
132
+ const timeoutMs = opts.timeoutMs ?? ADAPTER_TIMEOUT_MS;
133
+ return new Promise((resolve3) => {
134
+ let done = false;
135
+ const finish = (ok) => {
136
+ if (done) return;
137
+ done = true;
138
+ clearTimeout(timer);
139
+ if (!ok) socket.destroy();
140
+ resolve3(ok);
141
+ };
142
+ const timer = setTimeout(() => finish(false), timeoutMs);
143
+ const socket = (0, import_node_net.connect)(endpoint);
144
+ socket.on("connect", () => {
145
+ socket.end(serialize(msg), () => finish(true));
146
+ });
147
+ socket.on("error", () => finish(false));
148
+ });
149
+ }
150
+
151
+ // packages/adapter-kit/src/render.ts
152
+ var ESC = "\x1B";
153
+ var RESET = `${ESC}[0m`;
154
+ function sanitizeText(input, maxChars = 120) {
155
+ if (typeof input !== "string") return "";
156
+ let out = "";
157
+ for (const ch of input) {
158
+ const cp = ch.codePointAt(0);
159
+ if (cp < 32 || cp >= 127 && cp <= 159) {
160
+ out += " ";
161
+ continue;
162
+ }
163
+ if (cp >= 8203 && cp <= 8207 || cp >= 8234 && cp <= 8238 || cp >= 8294 && cp <= 8297)
164
+ continue;
165
+ if (cp === 65279 || cp === 8232 || cp === 8233) continue;
166
+ out += ch;
167
+ }
168
+ out = out.replace(/\s+/g, " ").trim();
169
+ return [...out].slice(0, maxChars).join("");
170
+ }
171
+ function snippetLines(input, max = 3) {
172
+ if (typeof input !== "string") return [];
173
+ return input.split(String.fromCharCode(10)).map((l) => sanitizeText(l, 65)).filter((l) => l.length > 0 && [...l].length <= 64).slice(0, max);
174
+ }
175
+ function safeLink(url) {
176
+ if (typeof url !== "string" || !url.startsWith(ALLOWED_LINK_PREFIX)) return null;
177
+ if (!/^https:\/\/avron\.dev\/go\/[A-Za-z0-9._~\-/?=&%]*$/.test(url)) return null;
178
+ return url;
179
+ }
180
+ function isWide(cp) {
181
+ return cp >= 4352 && cp <= 4447 || // Hangul Jamo
182
+ cp >= 11904 && cp <= 42191 || // CJK radicals .. Yi
183
+ cp >= 44032 && cp <= 55203 || // Hangul syllables
184
+ cp >= 63744 && cp <= 64255 || // CJK compatibility ideographs
185
+ cp >= 65072 && cp <= 65103 || // CJK compatibility forms
186
+ cp >= 65280 && cp <= 65376 || // Fullwidth forms
187
+ cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || // pictographs
188
+ cp >= 131072 && cp <= 262141;
189
+ }
190
+ function isZeroWidth(cp) {
191
+ return cp >= 768 && cp <= 879 || cp >= 65024 && cp <= 65039 || cp === 8205;
192
+ }
193
+ function displayWidth(text) {
194
+ let w = 0;
195
+ for (const ch of stripAnsi(text)) {
196
+ const cp = ch.codePointAt(0);
197
+ if (isZeroWidth(cp)) continue;
198
+ w += isWide(cp) ? 2 : 1;
199
+ }
200
+ return w;
201
+ }
202
+ var ANSI_RE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-9;?]*[ -/]*[@-~]/g;
203
+ function stripAnsi(text) {
204
+ return text.replace(ANSI_RE, "");
205
+ }
206
+ function truncate(text, columns) {
207
+ if (displayWidth(text) <= columns) return text;
208
+ if (columns <= 1) return "";
209
+ let out = "";
210
+ let w = 0;
211
+ for (const ch of text) {
212
+ const cw = displayWidth(ch);
213
+ if (w + cw > columns - 1) break;
214
+ out += ch;
215
+ w += cw;
216
+ }
217
+ return `${out.trimEnd()}\u2026`;
218
+ }
219
+ var SEP = "\u2502";
220
+ var KNOWN_LABELS = /* @__PURE__ */ new Set([SPONSOR_LABEL, ...Object.values(SPONSOR_LABELS)]);
221
+ function layout(c, width) {
222
+ const label = KNOWN_LABELS.has(c.label ?? "") ? c.label : SPONSOR_LABEL;
223
+ const badge = sanitizeText(c.sponsorName, 24).toUpperCase();
224
+ const copyFull = sanitizeText(c.headline, 80);
225
+ const ctaRaw = sanitizeText(c.ctaText, 28);
226
+ const cta = ctaRaw ? `${ctaRaw.replace(/\s*↗$/, "")} \u2197` : "";
227
+ if (!badge) return null;
228
+ const fits = (p) => displayWidth(plain(p)) <= width;
229
+ const wide = { label, badge, copy: copyFull, cta };
230
+ if (copyFull && fits(wide)) return wide;
231
+ if (copyFull) {
232
+ const fixed = displayWidth(plain({ label, badge, copy: "", cta })) + 3;
233
+ const room = width - fixed;
234
+ if (room >= 16) {
235
+ const standard = { label, badge, copy: truncate(copyFull, room), cta };
236
+ if (fits(standard)) return standard;
237
+ }
238
+ }
239
+ const compact = { label, badge, copy: "", cta };
240
+ if (cta && fits(compact)) return compact;
241
+ return null;
242
+ }
243
+ function plainLine(content, maxLength) {
244
+ const p = layout(content, maxLength);
245
+ return p ? plain(p) : "";
246
+ }
247
+ function plain(p) {
248
+ const left = `${p.label} ${p.badge} `;
249
+ if (p.copy && p.cta) return `${left}${SEP} ${p.copy} \xB7 ${p.cta}`;
250
+ if (p.copy) return `${left}${SEP} ${p.copy}`;
251
+ if (p.cta) return `${left}\xB7 ${p.cta}`;
252
+ return left;
253
+ }
254
+ var style = {
255
+ truecolor: {
256
+ badge: `${ESC}[48;2;39;39;42m${ESC}[38;2;244;244;245m`,
257
+ dim: `${ESC}[38;2;113;113;122m`,
258
+ copy: `${ESC}[38;2;161;161;170m`,
259
+ cta: `${ESC}[38;2;52;211;153m`
260
+ },
261
+ basic: { badge: `${ESC}[7m`, dim: `${ESC}[2m`, copy: `${ESC}[2m`, cta: `${ESC}[32m` }
262
+ };
263
+ var LOGO_RE = /^https:\/\/avron\.dev\/[A-Za-z0-9._~\-/%]+\.(png|webp)$/;
264
+ function cardOf(c) {
265
+ const art = cleanArt(c.art);
266
+ const imageUrl = typeof c.imageUrl === "string" && LOGO_RE.test(c.imageUrl) ? c.imageUrl : "";
267
+ const body = sanitizeText(c.body, 160);
268
+ const snippet = snippetLines(c.snippet).join(String.fromCharCode(10));
269
+ const promoCode = safePromo(c.promoCode);
270
+ const logoUrl = typeof c.logoUrl === "string" && LOGO_RE.test(c.logoUrl) ? c.logoUrl : "";
271
+ if (!body && !snippet && !promoCode && !logoUrl && !art && !imageUrl) return null;
272
+ const sponsorName = sanitizeText(c.sponsorName, 24);
273
+ const headline = sanitizeText(c.headline, 80);
274
+ if (!sponsorName || !headline) return null;
275
+ return {
276
+ label: KNOWN_LABELS.has(c.label ?? "") ? c.label : SPONSOR_LABEL,
277
+ sponsorName,
278
+ headline,
279
+ body,
280
+ snippet,
281
+ promoCode,
282
+ logoUrl,
283
+ art,
284
+ imageUrl
285
+ };
286
+ }
287
+ function safePromo(code) {
288
+ return typeof code === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(code) ? code : "";
289
+ }
290
+
291
+ // packages/adapter-kit/src/turn.ts
292
+ function placesMessage(agent, surfaceId, places, slot, maxLength, drawn) {
293
+ return {
294
+ protocolVersion: PROTOCOL_VERSION,
295
+ agentName: agent.name,
296
+ agentTier: agent.tier,
297
+ sessionId: surfaceId,
298
+ timestamp: Date.now(),
299
+ eventType: "PAYLOAD_REQUEST",
300
+ payload: { slot, ...maxLength !== void 0 ? { maxLength } : {}, places, ...drawn ? { drawn } : {} }
301
+ };
302
+ }
303
+ var askPlaces = (agent, surfaceId, places, slot, maxLength, endpoint, drawn) => request(placesMessage(agent, surfaceId, places, slot, maxLength, drawn), { endpoint });
304
+
305
+ // packages/adapter-kit/src/reversible.ts
306
+ var import_node_path2 = require("node:path");
307
+ var PROTECTED_DIRS = [
308
+ ".claude",
309
+ ".cursor",
310
+ ".codex",
311
+ ".copilot",
312
+ ".kiro",
313
+ ".codeium",
314
+ ".gemini",
315
+ ".orca",
316
+ (0, import_node_path2.join)(".config", "opencode"),
317
+ (0, import_node_path2.join)("AppData", "Roaming", "orca"),
318
+ (0, import_node_path2.join)("Library", "Application Support", "orca")
319
+ ];
320
+
321
+ // packages/adapter-claude-code/src/plugin-surface.ts
322
+ var PLUGIN_AGENT = { name: "claude-plugin", tier: "ide" };
323
+ var MAX_LENGTH = 80;
324
+ var POLL_MS = 1e3;
325
+ function drawableCard(card) {
326
+ if (!card || !(card.body || card.snippet || card.promoCode)) return null;
327
+ return { ...card, logoUrl: "", imageUrl: "", art: null };
328
+ }
329
+ function startPluginSurface(sessionId, onChange, opts = {}) {
330
+ const endpoint = ipcEndpoint(opts.env ?? process.env);
331
+ const place = placeOfSession(sessionId);
332
+ const surfaceId = `cp-${place}`;
333
+ let shown = null;
334
+ let busy = false;
335
+ let drawn;
336
+ const set = (line) => {
337
+ if (line?.text === shown?.text && line?.url === shown?.url && JSON.stringify(line?.card ?? null) === JSON.stringify(shown?.card ?? null))
338
+ return;
339
+ shown = line;
340
+ drawn = line?.card ? "card" : void 0;
341
+ onChange(line);
342
+ };
343
+ async function tick() {
344
+ if (busy) return;
345
+ busy = true;
346
+ try {
347
+ const res = await askPlaces(
348
+ PLUGIN_AGENT,
349
+ surfaceId,
350
+ [place],
351
+ "ide_statusbar",
352
+ MAX_LENGTH,
353
+ endpoint,
354
+ drawn
355
+ );
356
+ const p = res?.payload;
357
+ const text = p?.active && p.sponsorName && p.headline ? plainLine({ ...p, sponsorName: p.sponsorName, headline: p.headline }, MAX_LENGTH) : "";
358
+ const card = text && p?.sponsorName && p.headline ? drawableCard(cardOf({ ...p, sponsorName: p.sponsorName, headline: p.headline })) : null;
359
+ set(text ? { text, sponsorName: p?.sponsorName ?? "", url: safeLink(p?.actionUrl), card } : null);
360
+ } catch {
361
+ set(null);
362
+ } finally {
363
+ busy = false;
364
+ }
365
+ }
366
+ const timer = setInterval(() => void tick(), opts.pollMs ?? POLL_MS);
367
+ timer.unref?.();
368
+ void tick();
369
+ return {
370
+ tick,
371
+ current: () => shown,
372
+ dispose() {
373
+ clearInterval(timer);
374
+ set(null);
375
+ }
376
+ };
377
+ }
378
+
379
+ // packages/adapter-claude-code/src/plugin-bin.ts
380
+ var ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
381
+ var MAX_LIFETIME_MS = 10 * 60 * 1e3;
382
+ var REASONS = ["completed", "aborted", "error"];
383
+ async function watch(sessionId) {
384
+ const surface = startPluginSurface(sessionId, (line) => {
385
+ process.stdout.write(`${JSON.stringify({ shown: line })}
386
+ `);
387
+ });
388
+ await new Promise((resolve3) => {
389
+ const stop = setTimeout(resolve3, MAX_LIFETIME_MS);
390
+ process.once("SIGTERM", () => {
391
+ clearTimeout(stop);
392
+ resolve3();
393
+ });
394
+ });
395
+ surface.dispose();
396
+ }
397
+ async function idle(sessionId, reason) {
398
+ const terminationReason = REASONS.find((r) => r === reason) ?? "aborted";
399
+ const msg = {
400
+ protocolVersion: PROTOCOL_VERSION,
401
+ agentName: "claude-code",
402
+ agentTier: "cli",
403
+ sessionId,
404
+ timestamp: Date.now(),
405
+ // No turn id: whatever turn is open in this session ends (the same as SessionEnd).
406
+ eventType: "AGENT_IDLE",
407
+ payload: { terminationReason }
408
+ };
409
+ await send(msg);
410
+ }
411
+ async function main() {
412
+ const [command, sessionId, reason] = process.argv.slice(2);
413
+ if (!sessionId || !ID_RE.test(sessionId)) return;
414
+ if (command === "watch") await watch(sessionId);
415
+ else if (command === "idle") await idle(sessionId, reason);
416
+ }
417
+ main().catch(() => {
418
+ }).finally(() => process.exit(0));