@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.
- package/LICENSE +21 -0
- package/README.md +144 -2
- package/SECURITY.md +81 -0
- package/avron.cjs +2985 -0
- package/bin/avron-antigravity-hook.cjs +332 -0
- package/bin/avron-antigravity-statusline.cjs +593 -0
- package/bin/avron-claude-plugin.cjs +418 -0
- package/bin/avron-codex-hook.cjs +555 -0
- package/bin/avron-copilot-hook.cjs +294 -0
- package/bin/avron-copilot-statusline.cjs +510 -0
- package/bin/avron-cursor-hook.cjs +319 -0
- package/bin/avron-daemon.cjs +1846 -0
- package/bin/avron-hook.cjs +541 -0
- package/bin/avron-opencode-core.mjs +467 -0
- package/bin/avron-opencode.tsx +77 -0
- package/bin/avron-statusline.cjs +583 -0
- package/claude-plugin/.claude-plugin/marketplace.json +14 -0
- package/claude-plugin/avron/.claude-plugin/plugin.json +10 -0
- package/claude-plugin/avron/LICENSE +21 -0
- package/claude-plugin/avron/hooks/hooks.json +1 -0
- package/claude-plugin/avron/hooks/register.tsx +254 -0
- package/claude-plugin/avron/types/index.d.ts +23 -0
- package/package.json +28 -4
|
@@ -0,0 +1,1846 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// packages/core/src/daemon-main.ts
|
|
4
|
+
var import_node_fs10 = require("node:fs");
|
|
5
|
+
var import_promises2 = require("node:fs/promises");
|
|
6
|
+
var import_node_os3 = require("node:os");
|
|
7
|
+
var import_node_path11 = require("node:path");
|
|
8
|
+
|
|
9
|
+
// packages/protocol/src/art.ts
|
|
10
|
+
var ART_LIMITS = { rows: 6, cols: 60 };
|
|
11
|
+
var ART_CHAR = /^[⠀-⣿▀-▟ ]*$/;
|
|
12
|
+
var COLOR = /^#[0-9a-f]{6}$/i;
|
|
13
|
+
function cleanArt(raw) {
|
|
14
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
15
|
+
const r = raw;
|
|
16
|
+
if (!Array.isArray(r.rows) || r.rows.length === 0 || r.rows.length > ART_LIMITS.rows) return null;
|
|
17
|
+
const rows = [];
|
|
18
|
+
for (const row of r.rows) {
|
|
19
|
+
if (typeof row !== "string" || !ART_CHAR.test(row) || [...row].length > ART_LIMITS.cols) return null;
|
|
20
|
+
rows.push(row.replace(/ +$/, ""));
|
|
21
|
+
}
|
|
22
|
+
while (rows.length && !rows[0]) rows.shift();
|
|
23
|
+
while (rows.length && !rows[rows.length - 1]) rows.pop();
|
|
24
|
+
if (!rows.length) return null;
|
|
25
|
+
const color = typeof r.color === "string" && COLOR.test(r.color) ? r.color.toLowerCase() : void 0;
|
|
26
|
+
return { rows, ...color ? { color } : {} };
|
|
27
|
+
}
|
|
28
|
+
var BLANK = String.fromCodePoint(10240);
|
|
29
|
+
var MOTIONS = ["reveal", "wipe"];
|
|
30
|
+
|
|
31
|
+
// packages/protocol/src/constants.ts
|
|
32
|
+
var PROTOCOL_VERSION = "2.0.0";
|
|
33
|
+
var ADAPTER_TIMEOUT_MS = 15;
|
|
34
|
+
var VALID_IMPRESSION_MS = 5e3;
|
|
35
|
+
var GRACE_PERIOD_MS = 1500;
|
|
36
|
+
var MAX_TTL_MS = 6e4;
|
|
37
|
+
var MANIFEST_SYNC_INTERVAL_MS = 30 * 6e4;
|
|
38
|
+
var BATCH_FLUSH_INTERVAL_MS = 60 * 6e4;
|
|
39
|
+
var DAEMON_IDLE_EXIT_MS = 3 * 60 * 6e4;
|
|
40
|
+
var OFFLINE_QUEUE_MAX_BYTES = 5 * 1024 * 1024;
|
|
41
|
+
var MICRO_TAG_MAX_CHARS = 15;
|
|
42
|
+
var MAX_LINE_BYTES = 8 * 1024;
|
|
43
|
+
var ALLOWED_LINK_PREFIX = "https://avron.dev/go/";
|
|
44
|
+
var FORMATS = ["line", "card", "image", "banner", "motion", "toast"];
|
|
45
|
+
function largerFormat(a, b) {
|
|
46
|
+
if (!a) return b;
|
|
47
|
+
if (!b) return a;
|
|
48
|
+
return FORMATS.indexOf(b) > FORMATS.indexOf(a) ? b : a;
|
|
49
|
+
}
|
|
50
|
+
var AD_TIER_RANK = { line: 0, card: 1, spot: 2 };
|
|
51
|
+
function isAdTier(v) {
|
|
52
|
+
return v === "line" || v === "card" || v === "spot";
|
|
53
|
+
}
|
|
54
|
+
var SPONSOR_LABEL = "Sponsored";
|
|
55
|
+
var SPONSOR_LABELS = {
|
|
56
|
+
ko: "\uAD11\uACE0",
|
|
57
|
+
ja: "\u5E83\u544A",
|
|
58
|
+
"zh-CN": "\u5E7F\u544A",
|
|
59
|
+
"zh-TW": "\u5EE3\u544A",
|
|
60
|
+
es: "Patrocinado",
|
|
61
|
+
pt: "Patrocinado",
|
|
62
|
+
de: "Anzeige",
|
|
63
|
+
fr: "Sponsoris\xE9"
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// packages/protocol/src/validate.ts
|
|
67
|
+
var TIERS = ["cli", "harness", "ide"];
|
|
68
|
+
var SLOTS = ["spinner", "statusline", "ide_statusbar", "collapsible"];
|
|
69
|
+
var REASONS = ["completed", "aborted", "error"];
|
|
70
|
+
var ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
71
|
+
var AGENT_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
72
|
+
var MAX_PLACES = 16;
|
|
73
|
+
var isHash = (v) => typeof v === "string" && /^[0-9a-f]{16}$/.test(v);
|
|
74
|
+
function isObject(v) {
|
|
75
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
76
|
+
}
|
|
77
|
+
function parseAdapterMessage(line) {
|
|
78
|
+
if (line.length === 0 || Buffer.byteLength(line, "utf8") > MAX_LINE_BYTES) return null;
|
|
79
|
+
let raw;
|
|
80
|
+
try {
|
|
81
|
+
raw = JSON.parse(line);
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
if (!isObject(raw)) return null;
|
|
86
|
+
const { protocolVersion, eventType, agentName, agentTier, sessionId, turnId, timestamp } = raw;
|
|
87
|
+
if (typeof protocolVersion !== "string" || protocolVersion.split(".")[0] !== PROTOCOL_VERSION.split(".")[0]) {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
if (typeof agentName !== "string" || !AGENT_RE.test(agentName)) return null;
|
|
91
|
+
if (typeof agentTier !== "string" || !TIERS.includes(agentTier)) return null;
|
|
92
|
+
if (typeof sessionId !== "string" || !ID_RE.test(sessionId)) return null;
|
|
93
|
+
if (turnId !== void 0 && (typeof turnId !== "string" || !ID_RE.test(turnId))) return null;
|
|
94
|
+
if (typeof timestamp !== "number" || !Number.isFinite(timestamp) || timestamp < 0) return null;
|
|
95
|
+
const env = {
|
|
96
|
+
protocolVersion,
|
|
97
|
+
agentName,
|
|
98
|
+
agentTier,
|
|
99
|
+
sessionId,
|
|
100
|
+
timestamp,
|
|
101
|
+
...turnId !== void 0 ? { turnId } : {}
|
|
102
|
+
};
|
|
103
|
+
const payload = isObject(raw.payload) ? raw.payload : void 0;
|
|
104
|
+
switch (eventType) {
|
|
105
|
+
case "AGENT_BUSY": {
|
|
106
|
+
const slots = Array.isArray(payload?.declaredSlots) ? payload.declaredSlots.filter((s) => SLOTS.includes(s)) : void 0;
|
|
107
|
+
const hostPane = isHash(payload?.hostPane) ? payload.hostPane : void 0;
|
|
108
|
+
const place = isHash(payload?.place) ? payload.place : void 0;
|
|
109
|
+
return {
|
|
110
|
+
...env,
|
|
111
|
+
eventType,
|
|
112
|
+
payload: {
|
|
113
|
+
...slots ? { declaredSlots: slots } : {},
|
|
114
|
+
...hostPane ? { hostPane } : {},
|
|
115
|
+
...place ? { place } : {}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
case "AGENT_IDLE": {
|
|
120
|
+
const r = payload?.terminationReason;
|
|
121
|
+
const reason = typeof r === "string" && REASONS.includes(r) ? r : void 0;
|
|
122
|
+
const at = payload?.observedAt;
|
|
123
|
+
const observedAt = typeof at === "number" && Number.isFinite(at) && at > 0 ? at : void 0;
|
|
124
|
+
return {
|
|
125
|
+
...env,
|
|
126
|
+
eventType,
|
|
127
|
+
payload: {
|
|
128
|
+
...reason ? { terminationReason: reason } : {},
|
|
129
|
+
...observedAt !== void 0 && env.turnId === void 0 ? { observedAt } : {}
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
case "PAYLOAD_REQUEST": {
|
|
134
|
+
const slot = payload?.slot;
|
|
135
|
+
if (typeof slot !== "string" || !SLOTS.includes(slot)) return null;
|
|
136
|
+
const max = payload?.maxLength;
|
|
137
|
+
const maxLength = typeof max === "number" && Number.isInteger(max) && max > 0 && max <= 1e3 ? max : void 0;
|
|
138
|
+
const list = payload?.places;
|
|
139
|
+
const places = Array.isArray(list) && list.length > 0 && list.length <= MAX_PLACES && list.every(isHash) ? list : void 0;
|
|
140
|
+
if (list !== void 0 && !places) return null;
|
|
141
|
+
const drawn = FORMATS.includes(payload?.drawn) ? payload?.drawn : void 0;
|
|
142
|
+
return {
|
|
143
|
+
...env,
|
|
144
|
+
eventType,
|
|
145
|
+
payload: {
|
|
146
|
+
slot,
|
|
147
|
+
...maxLength ? { maxLength } : {},
|
|
148
|
+
...places ? { places } : {},
|
|
149
|
+
...drawn ? { drawn } : {},
|
|
150
|
+
...payload?.poster === true ? { poster: true } : {}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
default:
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function serialize(msg) {
|
|
159
|
+
return `${JSON.stringify(msg)}
|
|
160
|
+
`;
|
|
161
|
+
}
|
|
162
|
+
function inactiveResponse(sessionId, turnId, now) {
|
|
163
|
+
return {
|
|
164
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
165
|
+
eventType: "PAYLOAD_RESPONSE",
|
|
166
|
+
ok: true,
|
|
167
|
+
sessionId,
|
|
168
|
+
...turnId !== void 0 ? { turnId } : {},
|
|
169
|
+
timestamp: now,
|
|
170
|
+
payload: { active: false, headline: "" }
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// packages/protocol/src/endpoint.ts
|
|
175
|
+
var import_node_crypto = require("node:crypto");
|
|
176
|
+
var import_node_os = require("node:os");
|
|
177
|
+
var import_node_path = require("node:path");
|
|
178
|
+
function avronHome(env = process.env) {
|
|
179
|
+
return env.AVRON_HOME && env.AVRON_HOME.length > 0 ? env.AVRON_HOME : (0, import_node_path.join)((0, import_node_os.homedir)(), ".avron");
|
|
180
|
+
}
|
|
181
|
+
function avronPaths(env = process.env) {
|
|
182
|
+
const home = avronHome(env);
|
|
183
|
+
return {
|
|
184
|
+
home,
|
|
185
|
+
runDir: (0, import_node_path.join)(home, "run"),
|
|
186
|
+
logDir: (0, import_node_path.join)(home, "logs"),
|
|
187
|
+
dataDir: (0, import_node_path.join)(home, "data"),
|
|
188
|
+
cacheDir: (0, import_node_path.join)(home, "cache"),
|
|
189
|
+
keyDir: (0, import_node_path.join)(home, "keys"),
|
|
190
|
+
daemonLog: (0, import_node_path.join)(home, "logs", "daemon.log"),
|
|
191
|
+
impressionsLog: (0, import_node_path.join)(home, "logs", "impressions.ndjson"),
|
|
192
|
+
ledgerSnapshot: (0, import_node_path.join)(home, "data", "ledger.json"),
|
|
193
|
+
manifestCache: (0, import_node_path.join)(home, "cache", "manifest.json"),
|
|
194
|
+
eventQueue: (0, import_node_path.join)(home, "data", "queue.ndjson")
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
var UDS_MAX = 100;
|
|
198
|
+
function ipcEndpoint(env = process.env, platform = process.platform) {
|
|
199
|
+
const home = avronHome(env);
|
|
200
|
+
const tag = (0, import_node_crypto.createHash)("sha256").update(home).digest("hex").slice(0, 12);
|
|
201
|
+
if (platform === "win32") return `\\\\.\\pipe\\avron-uasp-${tag}.sock`;
|
|
202
|
+
const preferred = (0, import_node_path.join)(home, "run", "avron-uasp.sock");
|
|
203
|
+
if (Buffer.byteLength(preferred) <= UDS_MAX) return preferred;
|
|
204
|
+
return (0, import_node_path.join)((0, import_node_os.tmpdir)(), `avron-uasp-${tag}.sock`);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// packages/protocol/src/client.ts
|
|
208
|
+
var import_node_net = require("node:net");
|
|
209
|
+
|
|
210
|
+
// packages/protocol/src/quiet.ts
|
|
211
|
+
function quietHere(env = process.env) {
|
|
212
|
+
if (env.AVRON_ALLOW_CI === "1") return false;
|
|
213
|
+
const ci = (env.CI ?? "").trim().toLowerCase();
|
|
214
|
+
return ci !== "" && ci !== "0" && ci !== "false";
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// packages/protocol/src/client.ts
|
|
218
|
+
var DAEMON_STOP_LINE = '{"eventType":"DAEMON_CONTROL","action":"stop"}';
|
|
219
|
+
var DAEMON_STOP_ACK = '{"ok":true,"stopping":true}';
|
|
220
|
+
function send(msg, opts = {}) {
|
|
221
|
+
if (quietHere()) return Promise.resolve(false);
|
|
222
|
+
const endpoint = opts.endpoint ?? ipcEndpoint();
|
|
223
|
+
const timeoutMs = opts.timeoutMs ?? ADAPTER_TIMEOUT_MS;
|
|
224
|
+
return new Promise((resolve2) => {
|
|
225
|
+
let done = false;
|
|
226
|
+
const finish = (ok) => {
|
|
227
|
+
if (done) return;
|
|
228
|
+
done = true;
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
if (!ok) socket.destroy();
|
|
231
|
+
resolve2(ok);
|
|
232
|
+
};
|
|
233
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
234
|
+
const socket = (0, import_node_net.connect)(endpoint);
|
|
235
|
+
socket.on("connect", () => {
|
|
236
|
+
socket.end(serialize(msg), () => finish(true));
|
|
237
|
+
});
|
|
238
|
+
socket.on("error", () => finish(false));
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// packages/protocol/src/spawn.ts
|
|
243
|
+
var FIRST_MESSAGE_ENV = "AVRON_FIRST_MESSAGE";
|
|
244
|
+
|
|
245
|
+
// packages/core/src/config.ts
|
|
246
|
+
var import_node_fs = require("node:fs");
|
|
247
|
+
var import_node_path2 = require("node:path");
|
|
248
|
+
var DEFAULT_FORMATS = {
|
|
249
|
+
card: true,
|
|
250
|
+
codeLines: 3,
|
|
251
|
+
banner: false,
|
|
252
|
+
motion: false,
|
|
253
|
+
poster: false,
|
|
254
|
+
image: true,
|
|
255
|
+
toast: true
|
|
256
|
+
};
|
|
257
|
+
var DEFAULT_CONFIG = {
|
|
258
|
+
mode: "pill-statusline",
|
|
259
|
+
paused: false,
|
|
260
|
+
formats: { ...DEFAULT_FORMATS }
|
|
261
|
+
};
|
|
262
|
+
function readFormats(raw) {
|
|
263
|
+
const f = typeof raw === "object" && raw !== null ? raw : {};
|
|
264
|
+
const flag = (k) => typeof f[k] === "boolean" ? f[k] : DEFAULT_FORMATS[k];
|
|
265
|
+
const lines = f.codeLines;
|
|
266
|
+
return {
|
|
267
|
+
card: flag("card"),
|
|
268
|
+
codeLines: lines === 1 || lines === 2 || lines === 3 ? lines : DEFAULT_FORMATS.codeLines,
|
|
269
|
+
banner: flag("banner"),
|
|
270
|
+
motion: flag("motion"),
|
|
271
|
+
poster: flag("poster"),
|
|
272
|
+
image: flag("image"),
|
|
273
|
+
toast: flag("toast")
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
function configPath(env = process.env) {
|
|
277
|
+
return (0, import_node_path2.join)(avronHome(env), "config.json");
|
|
278
|
+
}
|
|
279
|
+
function readConfig(env = process.env) {
|
|
280
|
+
try {
|
|
281
|
+
const raw = JSON.parse((0, import_node_fs.readFileSync)(configPath(env), "utf8"));
|
|
282
|
+
return {
|
|
283
|
+
mode: raw.mode === "pill-statusline" ? raw.mode : DEFAULT_CONFIG.mode,
|
|
284
|
+
paused: raw.paused === true,
|
|
285
|
+
formats: readFormats(raw.formats)
|
|
286
|
+
};
|
|
287
|
+
} catch {
|
|
288
|
+
return { ...DEFAULT_CONFIG, formats: { ...DEFAULT_FORMATS } };
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function liveConfig(env = process.env) {
|
|
292
|
+
let cached = readConfig(env);
|
|
293
|
+
let stamp = -1;
|
|
294
|
+
let checkedAt = 0;
|
|
295
|
+
return () => {
|
|
296
|
+
const now = Date.now();
|
|
297
|
+
if (now - checkedAt < 1e3) return cached;
|
|
298
|
+
checkedAt = now;
|
|
299
|
+
try {
|
|
300
|
+
const m = (0, import_node_fs.statSync)(configPath(env)).mtimeMs;
|
|
301
|
+
if (m !== stamp) {
|
|
302
|
+
stamp = m;
|
|
303
|
+
cached = readConfig(env);
|
|
304
|
+
}
|
|
305
|
+
} catch {
|
|
306
|
+
cached = { ...DEFAULT_CONFIG, formats: { ...DEFAULT_FORMATS } };
|
|
307
|
+
stamp = -1;
|
|
308
|
+
}
|
|
309
|
+
return cached;
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// packages/core/src/daemon.ts
|
|
314
|
+
var import_node_fs3 = require("node:fs");
|
|
315
|
+
var import_node_path4 = require("node:path");
|
|
316
|
+
|
|
317
|
+
// packages/core/src/engine.ts
|
|
318
|
+
var import_node_crypto2 = require("node:crypto");
|
|
319
|
+
var systemClock = {
|
|
320
|
+
now: () => Date.now(),
|
|
321
|
+
setTimeout: (fn, ms) => {
|
|
322
|
+
const t = setTimeout(fn, ms);
|
|
323
|
+
t.unref();
|
|
324
|
+
return t;
|
|
325
|
+
},
|
|
326
|
+
clearTimeout: (h) => clearTimeout(h)
|
|
327
|
+
};
|
|
328
|
+
function drawableTier(agentName, noLine, f, surface = false) {
|
|
329
|
+
if (noLine) return f.toast || surface && f.card ? "card" : "line";
|
|
330
|
+
if (agentName === "claude-code" && f.banner) return "spot";
|
|
331
|
+
if (agentName === "opencode") return "line";
|
|
332
|
+
return f.card ? "card" : "line";
|
|
333
|
+
}
|
|
334
|
+
var DISPLAY_CAP_DEFAULT_MS = 15e3;
|
|
335
|
+
var DISPLAY_CAP_MIN_MS = 8e3;
|
|
336
|
+
var DISPLAY_CAP_RECOVERY_TURNS = 5;
|
|
337
|
+
var TOAST_AFTER_MS = 6e3;
|
|
338
|
+
var MAX_SESSIONS = 512;
|
|
339
|
+
var LEGACY_KEY_AGENT = "claude-code";
|
|
340
|
+
var MAX_CREDITED_KEYS = 4096;
|
|
341
|
+
var SESSION_STALE_MS = 6 * 60 * 6e4;
|
|
342
|
+
var Engine = class {
|
|
343
|
+
constructor(opts) {
|
|
344
|
+
this.opts = opts;
|
|
345
|
+
this.clock = opts.clock ?? systemClock;
|
|
346
|
+
this.baseCapMs = Math.min(opts.displayCapMs ?? DISPLAY_CAP_DEFAULT_MS, MAX_TTL_MS);
|
|
347
|
+
}
|
|
348
|
+
clock;
|
|
349
|
+
sessions = /* @__PURE__ */ new Map();
|
|
350
|
+
credited = /* @__PURE__ */ new Set();
|
|
351
|
+
baseCapMs;
|
|
352
|
+
/** Handle one adapter message. Returns a response for PAYLOAD_REQUEST, null for one-way events. */
|
|
353
|
+
handle(msg) {
|
|
354
|
+
switch (msg.eventType) {
|
|
355
|
+
case "AGENT_BUSY":
|
|
356
|
+
this.onBusy(msg);
|
|
357
|
+
return null;
|
|
358
|
+
case "AGENT_IDLE":
|
|
359
|
+
this.onIdle(msg);
|
|
360
|
+
return null;
|
|
361
|
+
case "PAYLOAD_REQUEST":
|
|
362
|
+
return this.onRequest(msg);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/** Number of sessions with a turn that is currently eligible to show a line. For diagnostics. */
|
|
366
|
+
activeTurns() {
|
|
367
|
+
let n = 0;
|
|
368
|
+
for (const s of this.sessions.values()) if (s.turn && !s.turn.expired) n++;
|
|
369
|
+
return n;
|
|
370
|
+
}
|
|
371
|
+
/** Drop every timer. Call on daemon shutdown. */
|
|
372
|
+
dispose() {
|
|
373
|
+
for (const s of this.sessions.values()) {
|
|
374
|
+
if (!s.turn) continue;
|
|
375
|
+
this.clock.clearTimeout(s.turn.ttl);
|
|
376
|
+
this.clock.clearTimeout(s.turn.toast);
|
|
377
|
+
}
|
|
378
|
+
this.sessions.clear();
|
|
379
|
+
}
|
|
380
|
+
enabled() {
|
|
381
|
+
return this.opts.enabled ? this.opts.enabled() : true;
|
|
382
|
+
}
|
|
383
|
+
mode() {
|
|
384
|
+
return this.opts.mode ? this.opts.mode() : "pill-statusline";
|
|
385
|
+
}
|
|
386
|
+
session(id, now) {
|
|
387
|
+
let s = this.sessions.get(id);
|
|
388
|
+
if (!s) {
|
|
389
|
+
if (this.sessions.size >= MAX_SESSIONS) this.evict(now);
|
|
390
|
+
s = { lastSeen: now, capMs: this.baseCapMs, cleanStreak: 0 };
|
|
391
|
+
this.sessions.set(id, s);
|
|
392
|
+
}
|
|
393
|
+
s.lastSeen = now;
|
|
394
|
+
return s;
|
|
395
|
+
}
|
|
396
|
+
evict(now) {
|
|
397
|
+
for (const [id, s] of this.sessions) {
|
|
398
|
+
if (!s.turn && now - s.lastSeen > SESSION_STALE_MS) this.sessions.delete(id);
|
|
399
|
+
}
|
|
400
|
+
if (this.sessions.size < MAX_SESSIONS) return;
|
|
401
|
+
let oldest;
|
|
402
|
+
let oldestSeen = Number.POSITIVE_INFINITY;
|
|
403
|
+
for (const [id, s] of this.sessions) {
|
|
404
|
+
if (s.lastSeen < oldestSeen) {
|
|
405
|
+
oldestSeen = s.lastSeen;
|
|
406
|
+
oldest = id;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (oldest !== void 0) {
|
|
410
|
+
const s = this.sessions.get(oldest);
|
|
411
|
+
if (s?.turn) {
|
|
412
|
+
this.clock.clearTimeout(s.turn.ttl);
|
|
413
|
+
this.clock.clearTimeout(s.turn.toast);
|
|
414
|
+
}
|
|
415
|
+
this.sessions.delete(oldest);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
onBusy(msg) {
|
|
419
|
+
const now = this.clock.now();
|
|
420
|
+
const s = this.session(sessionKey(msg), now);
|
|
421
|
+
if (s.turn && msg.turnId !== void 0 && msg.turnId === s.turn.turnId) return;
|
|
422
|
+
if (s.turn) {
|
|
423
|
+
this.clock.clearTimeout(s.turn.ttl);
|
|
424
|
+
this.clock.clearTimeout(s.turn.toast);
|
|
425
|
+
s.capMs = Math.min(s.capMs, DISPLAY_CAP_MIN_MS);
|
|
426
|
+
s.cleanStreak = 0;
|
|
427
|
+
}
|
|
428
|
+
const slots = msg.eventType === "AGENT_BUSY" ? msg.payload?.declaredSlots : void 0;
|
|
429
|
+
const noLine = Array.isArray(slots) && slots.length > 0 && !slots.includes("statusline");
|
|
430
|
+
const named = msg.eventType === "AGENT_BUSY" ? msg.payload?.place : void 0;
|
|
431
|
+
const turn = {
|
|
432
|
+
// Without a turn id every BUSY is a new turn. A random id (not a counter) so a restarted
|
|
433
|
+
// daemon can never reuse the key of a turn that was already credited.
|
|
434
|
+
turnId: msg.turnId ?? `auto-${(0, import_node_crypto2.randomUUID)()}`,
|
|
435
|
+
agentName: msg.agentName,
|
|
436
|
+
agentTier: msg.agentTier,
|
|
437
|
+
...msg.eventType === "AGENT_BUSY" && msg.payload?.hostPane ? { hostPane: msg.payload.hostPane } : {},
|
|
438
|
+
...msg.eventType === "AGENT_BUSY" && msg.payload?.place ? { place: msg.payload.place } : {},
|
|
439
|
+
...noLine ? { noLine: true } : {},
|
|
440
|
+
t0: now,
|
|
441
|
+
creative: this.enabled() ? this.opts.campaigns.pick({
|
|
442
|
+
agentName: msg.agentName,
|
|
443
|
+
...this.opts.formats ? {
|
|
444
|
+
drawable: drawableTier(msg.agentName, noLine, this.opts.formats(), Boolean(named))
|
|
445
|
+
} : {}
|
|
446
|
+
}) : null,
|
|
447
|
+
expired: false,
|
|
448
|
+
ttl: void 0
|
|
449
|
+
};
|
|
450
|
+
turn.ttl = this.clock.setTimeout(() => {
|
|
451
|
+
turn.expired = true;
|
|
452
|
+
}, MAX_TTL_MS);
|
|
453
|
+
if (this.opts.onToast) turn.toast = this.clock.setTimeout(() => this.maybeToast(s, turn), TOAST_AFTER_MS);
|
|
454
|
+
s.turn = turn;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* A long turn whose line is on screen (or from an app with no status line of its own, such as the
|
|
458
|
+
* Claude and Codex desktop apps) may raise an OS notification (formats.toast), once. The daemon
|
|
459
|
+
* decides whether one is shown (its daily limit) and says so; for a turn with no other surface,
|
|
460
|
+
* showing the notification counts as serving the turn.
|
|
461
|
+
*/
|
|
462
|
+
maybeToast(s, turn) {
|
|
463
|
+
if (s.turn !== turn || turn.expired || !turn.creative) return;
|
|
464
|
+
if (turn.firstServedAt === void 0 && !turn.noLine) return;
|
|
465
|
+
if (!this.enabled() || this.mode() !== "pill-statusline" || this.shadowed(turn)) return;
|
|
466
|
+
if (this.opts.formats && !this.opts.formats().toast) return;
|
|
467
|
+
try {
|
|
468
|
+
if (this.opts.onToast?.(turn.creative)) {
|
|
469
|
+
turn.drawn = largerFormat(turn.drawn, "toast");
|
|
470
|
+
if (turn.firstServedAt === void 0) {
|
|
471
|
+
turn.firstServedAt = this.clock.now();
|
|
472
|
+
this.opts.campaigns.served?.(turn.creative.campaignId);
|
|
473
|
+
this.opts.onServe?.(turn.creative);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
} catch {
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
onRequest(msg) {
|
|
480
|
+
const now = this.clock.now();
|
|
481
|
+
const off = inactiveResponse(msg.sessionId, msg.turnId, now);
|
|
482
|
+
if (msg.eventType === "PAYLOAD_REQUEST" && msg.payload.poster) return this.onPoster(msg, now);
|
|
483
|
+
if (msg.eventType === "PAYLOAD_REQUEST" && msg.payload.places)
|
|
484
|
+
return this.onPlaces(msg, msg.payload.places);
|
|
485
|
+
const s = this.sessions.get(sessionKey(msg));
|
|
486
|
+
if (!s) return off;
|
|
487
|
+
s.lastSeen = now;
|
|
488
|
+
const turn = s.turn;
|
|
489
|
+
if (!turn) return off;
|
|
490
|
+
if (msg.turnId !== void 0 && msg.turnId !== turn.turnId) return off;
|
|
491
|
+
turn.ownLine = true;
|
|
492
|
+
return this.serve(msg, s, turn, now);
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* An editor window asks for whatever turn is thinking in its places (its folders, its window).
|
|
496
|
+
* Only turns that named a place answer, so an agent with its own line (Claude Code) is never
|
|
497
|
+
* shown twice. Of several, the oldest one that can show a line now is served.
|
|
498
|
+
*/
|
|
499
|
+
onPlaces(msg, places) {
|
|
500
|
+
const now = this.clock.now();
|
|
501
|
+
const found = [];
|
|
502
|
+
for (const s of this.sessions.values()) {
|
|
503
|
+
const turn = s.turn;
|
|
504
|
+
if (turn?.place && !turn.ownLine && !turn.expired && places.includes(turn.place))
|
|
505
|
+
found.push({ s, turn });
|
|
506
|
+
}
|
|
507
|
+
found.sort((a, b) => a.turn.t0 - b.turn.t0);
|
|
508
|
+
for (const { s, turn } of found) {
|
|
509
|
+
const res = this.serve(msg, s, turn, now);
|
|
510
|
+
if (res.payload.active) return res;
|
|
511
|
+
}
|
|
512
|
+
return inactiveResponse(msg.sessionId, void 0, now);
|
|
513
|
+
}
|
|
514
|
+
/** The line of `turn` right now, or an inactive response. The first line served is counted. */
|
|
515
|
+
serve(msg, s, turn, now) {
|
|
516
|
+
const off = inactiveResponse(msg.sessionId, msg.turnId, now);
|
|
517
|
+
if (turn.expired || !turn.creative) return off;
|
|
518
|
+
if (!this.enabled() || this.mode() !== "pill-statusline") return off;
|
|
519
|
+
if (this.shadowed(turn)) return off;
|
|
520
|
+
const elapsed = now - turn.t0;
|
|
521
|
+
if (elapsed < GRACE_PERIOD_MS)
|
|
522
|
+
return { ...off, payload: { ...off.payload, retryInMs: Math.ceil(GRACE_PERIOD_MS - elapsed) } };
|
|
523
|
+
if (elapsed >= s.capMs) return off;
|
|
524
|
+
const c = turn.creative;
|
|
525
|
+
if (msg.eventType === "PAYLOAD_REQUEST" && msg.payload.drawn)
|
|
526
|
+
turn.drawn = largerFormat(turn.drawn, msg.payload.drawn);
|
|
527
|
+
if (turn.firstServedAt === void 0) {
|
|
528
|
+
turn.firstServedAt = now;
|
|
529
|
+
try {
|
|
530
|
+
this.opts.campaigns.served?.(c.campaignId);
|
|
531
|
+
this.opts.onServe?.(c);
|
|
532
|
+
} catch {
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return {
|
|
536
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
537
|
+
eventType: "PAYLOAD_RESPONSE",
|
|
538
|
+
ok: true,
|
|
539
|
+
sessionId: msg.sessionId,
|
|
540
|
+
turnId: turn.turnId,
|
|
541
|
+
timestamp: now,
|
|
542
|
+
payload: {
|
|
543
|
+
...this.creativePayload(c, false),
|
|
544
|
+
...this.animated(c) ? { motionMs: now - (turn.firstServedAt ?? now) } : {}
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* A sponsor's fields as a response payload, without what the person switched off. The card off:
|
|
550
|
+
* no code row, promo code, description or logo. The banner off: no dot art (a poster always
|
|
551
|
+
* carries its art, since the poster switch decides that one).
|
|
552
|
+
*/
|
|
553
|
+
creativePayload(c, poster) {
|
|
554
|
+
const f = this.opts.formats?.();
|
|
555
|
+
const card = f ? f.card : true;
|
|
556
|
+
const snippet = card && c.snippet !== void 0 ? firstLines(c.snippet, f?.codeLines ?? 3) : void 0;
|
|
557
|
+
const art = poster || (f ? f.banner : true);
|
|
558
|
+
return {
|
|
559
|
+
active: true,
|
|
560
|
+
campaignId: c.campaignId,
|
|
561
|
+
...c.label !== void 0 ? { label: c.label } : {},
|
|
562
|
+
sponsorName: c.sponsorName,
|
|
563
|
+
headline: c.headline,
|
|
564
|
+
...c.ctaText !== void 0 ? { ctaText: c.ctaText } : {},
|
|
565
|
+
...card && c.promoCode !== void 0 ? { promoCode: c.promoCode } : {},
|
|
566
|
+
...snippet !== void 0 ? { snippet } : {},
|
|
567
|
+
...card && c.body !== void 0 ? { body: c.body } : {},
|
|
568
|
+
...card && c.logoUrl !== void 0 ? { logoUrl: c.logoUrl } : {},
|
|
569
|
+
...(f ? f.image : true) && c.imageUrl !== void 0 ? { imageUrl: c.imageUrl } : {},
|
|
570
|
+
...art && c.art ? { art: c.art } : {},
|
|
571
|
+
...!poster && art && this.animated(c) ? { motion: c.motion } : {},
|
|
572
|
+
...c.displayUrl !== void 0 ? { displayUrl: c.displayUrl } : {},
|
|
573
|
+
...c.actionUrl !== void 0 ? { actionUrl: c.actionUrl } : {},
|
|
574
|
+
renderMode: "ansi"
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
/** The sponsor's banner is animated for this person (banner and animation both switched on). */
|
|
578
|
+
animated(c) {
|
|
579
|
+
const f = this.opts.formats?.();
|
|
580
|
+
return c.art !== void 0 && c.motion !== void 0 && (f ? f.banner && f.motion : true);
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* The start poster: one sponsor and today's count, for a session that just began (protocol
|
|
584
|
+
* PAYLOAD_REQUEST `poster`). Not a thinking turn, so it is never an impression; it uses up the
|
|
585
|
+
* sponsor's daily cap like a shown line and is counted apart (`onPoster`).
|
|
586
|
+
*/
|
|
587
|
+
onPoster(msg, now) {
|
|
588
|
+
const off = inactiveResponse(msg.sessionId, msg.turnId, now);
|
|
589
|
+
if (!this.enabled() || this.mode() !== "pill-statusline") return off;
|
|
590
|
+
if (this.opts.formats && !this.opts.formats().poster) return off;
|
|
591
|
+
const c = this.opts.campaigns.pick({ agentName: msg.agentName });
|
|
592
|
+
if (!c) return off;
|
|
593
|
+
try {
|
|
594
|
+
this.opts.campaigns.served?.(c.campaignId);
|
|
595
|
+
this.opts.onPoster?.(c);
|
|
596
|
+
} catch {
|
|
597
|
+
}
|
|
598
|
+
const today = this.opts.todayTurns?.();
|
|
599
|
+
return {
|
|
600
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
601
|
+
eventType: "PAYLOAD_RESPONSE",
|
|
602
|
+
ok: true,
|
|
603
|
+
sessionId: msg.sessionId,
|
|
604
|
+
timestamp: now,
|
|
605
|
+
payload: { ...this.creativePayload(c, true), ...today !== void 0 ? { todayTurns: today } : {} }
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* One thinking turn is shown in one place. A host app's turn (an Orca pane, tier `harness`) stays
|
|
610
|
+
* empty while an agent with its own surface (Claude Code's status line) runs a turn in the same
|
|
611
|
+
* pane. It is never served, so it is never credited either.
|
|
612
|
+
*/
|
|
613
|
+
shadowed(turn) {
|
|
614
|
+
if (turn.agentTier !== "harness" || !turn.hostPane) return false;
|
|
615
|
+
for (const s of this.sessions.values()) {
|
|
616
|
+
const other = s.turn;
|
|
617
|
+
if (other && other !== turn && !other.expired && other.agentTier !== "harness" && other.hostPane === turn.hostPane)
|
|
618
|
+
return true;
|
|
619
|
+
}
|
|
620
|
+
return false;
|
|
621
|
+
}
|
|
622
|
+
onIdle(msg) {
|
|
623
|
+
const now = this.clock.now();
|
|
624
|
+
const s = this.sessions.get(sessionKey(msg));
|
|
625
|
+
if (!s) return;
|
|
626
|
+
s.lastSeen = now;
|
|
627
|
+
const turn = s.turn;
|
|
628
|
+
if (!turn) return;
|
|
629
|
+
if (msg.turnId !== void 0 && msg.turnId !== turn.turnId) return;
|
|
630
|
+
const observedAt = msg.eventType === "AGENT_IDLE" ? msg.payload?.observedAt : void 0;
|
|
631
|
+
if (observedAt !== void 0 && observedAt < turn.t0) return;
|
|
632
|
+
this.clock.clearTimeout(turn.ttl);
|
|
633
|
+
this.clock.clearTimeout(turn.toast);
|
|
634
|
+
s.turn = void 0;
|
|
635
|
+
if (++s.cleanStreak >= DISPLAY_CAP_RECOVERY_TURNS) s.capMs = this.baseCapMs;
|
|
636
|
+
if (!this.enabled()) return;
|
|
637
|
+
const thinkingMs = now - turn.t0;
|
|
638
|
+
if (thinkingMs < VALID_IMPRESSION_MS) return;
|
|
639
|
+
const mode = this.mode();
|
|
640
|
+
if (mode === "pill-statusline" && turn.firstServedAt === void 0) return;
|
|
641
|
+
const turnKey = turnKeyOf(turn.agentName, msg.sessionId, turn.turnId);
|
|
642
|
+
if (this.credited.has(turnKey)) return;
|
|
643
|
+
if (turn.firstServedAt === void 0 && turn.creative) {
|
|
644
|
+
try {
|
|
645
|
+
this.opts.campaigns.served?.(turn.creative.campaignId);
|
|
646
|
+
} catch {
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if (this.credited.size >= MAX_CREDITED_KEYS) {
|
|
650
|
+
const first = this.credited.values().next().value;
|
|
651
|
+
if (first !== void 0) this.credited.delete(first);
|
|
652
|
+
}
|
|
653
|
+
this.credited.add(turnKey);
|
|
654
|
+
this.opts.sink.record({
|
|
655
|
+
timestamp: now,
|
|
656
|
+
turnKey,
|
|
657
|
+
campaignId: turn.creative?.campaignId ?? null,
|
|
658
|
+
agentName: turn.agentName,
|
|
659
|
+
agentTier: turn.agentTier,
|
|
660
|
+
exposureDurationSec: round1(thinkingMs / 1e3),
|
|
661
|
+
displayedDurationSec: turn.firstServedAt === void 0 ? 0 : round1((now - turn.firstServedAt) / 1e3),
|
|
662
|
+
mode,
|
|
663
|
+
format: turn.drawn ?? "line",
|
|
664
|
+
earnedCredits: 1
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
function sessionKey(msg) {
|
|
669
|
+
return `${msg.agentName}:${msg.sessionId}`;
|
|
670
|
+
}
|
|
671
|
+
function turnKeyOf(agentName, sessionId, turnId) {
|
|
672
|
+
const input = agentName === LEGACY_KEY_AGENT ? `${sessionId}:${turnId}` : `${agentName}:${sessionId}:${turnId}`;
|
|
673
|
+
return (0, import_node_crypto2.createHash)("sha256").update(input).digest("hex").slice(0, 24);
|
|
674
|
+
}
|
|
675
|
+
function round1(n) {
|
|
676
|
+
return Math.round(n * 10) / 10;
|
|
677
|
+
}
|
|
678
|
+
function firstLines(text, n) {
|
|
679
|
+
const nl = String.fromCharCode(10);
|
|
680
|
+
return text.split(nl).slice(0, n).join(nl);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// packages/core/src/logger.ts
|
|
684
|
+
var import_node_fs2 = require("node:fs");
|
|
685
|
+
var import_node_path3 = require("node:path");
|
|
686
|
+
var MAX_LOG_BYTES = 1024 * 1024;
|
|
687
|
+
function fileLogger(file) {
|
|
688
|
+
const write = (level, msg) => {
|
|
689
|
+
try {
|
|
690
|
+
(0, import_node_fs2.mkdirSync)((0, import_node_path3.dirname)(file), { recursive: true });
|
|
691
|
+
try {
|
|
692
|
+
if ((0, import_node_fs2.statSync)(file).size > MAX_LOG_BYTES) (0, import_node_fs2.renameSync)(file, `${file}.1`);
|
|
693
|
+
} catch {
|
|
694
|
+
}
|
|
695
|
+
(0, import_node_fs2.appendFileSync)(file, `${(/* @__PURE__ */ new Date()).toISOString()} ${level} ${msg}
|
|
696
|
+
`);
|
|
697
|
+
} catch {
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
return {
|
|
701
|
+
info: (msg) => write("INFO", msg),
|
|
702
|
+
error: (msg, err) => write("ERROR", err === void 0 ? msg : `${msg}: ${describe(err)}`)
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
function describe(err) {
|
|
706
|
+
if (err instanceof Error) return `${err.name}: ${err.message}`;
|
|
707
|
+
return String(err);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// packages/core/src/server.ts
|
|
711
|
+
var import_node_net2 = require("node:net");
|
|
712
|
+
function listen(endpoint, engine, log, onActivity, onStop) {
|
|
713
|
+
return new Promise((resolve2) => {
|
|
714
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
715
|
+
const server = (0, import_node_net2.createServer)((socket) => {
|
|
716
|
+
sockets.add(socket);
|
|
717
|
+
socket.setEncoding("utf8");
|
|
718
|
+
let buf = "";
|
|
719
|
+
socket.on("data", (chunk) => {
|
|
720
|
+
buf += chunk;
|
|
721
|
+
if (buf.length > MAX_LINE_BYTES * 2) {
|
|
722
|
+
socket.destroy();
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
let nl = buf.indexOf("\n");
|
|
726
|
+
while (nl >= 0) {
|
|
727
|
+
const line = buf.slice(0, nl);
|
|
728
|
+
buf = buf.slice(nl + 1);
|
|
729
|
+
handleLine(line, socket);
|
|
730
|
+
nl = buf.indexOf("\n");
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
socket.on("error", () => socket.destroy());
|
|
734
|
+
socket.on("close", () => sockets.delete(socket));
|
|
735
|
+
});
|
|
736
|
+
const handleLine = (line, socket) => {
|
|
737
|
+
if (onStop && line.trim() === DAEMON_STOP_LINE) {
|
|
738
|
+
void onStop().catch((err) => log.error("stop failed", err)).finally(() => socket.end(`${DAEMON_STOP_ACK}
|
|
739
|
+
`));
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
try {
|
|
743
|
+
const msg = parseAdapterMessage(line);
|
|
744
|
+
if (!msg) {
|
|
745
|
+
socket.destroy();
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
const poll = msg.eventType === "PAYLOAD_REQUEST" && msg.payload.places !== void 0;
|
|
749
|
+
if (!poll) onActivity();
|
|
750
|
+
const res = engine.handle(msg);
|
|
751
|
+
if (poll && res?.payload.active) onActivity();
|
|
752
|
+
if (res) socket.end(serialize(res));
|
|
753
|
+
} catch (err) {
|
|
754
|
+
log.error("message handling failed", err);
|
|
755
|
+
socket.destroy();
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
server.once("error", (err) => {
|
|
759
|
+
resolve2({ ok: false, reason: err.code === "EADDRINUSE" ? "in-use" : "error", error: err });
|
|
760
|
+
});
|
|
761
|
+
server.listen(endpoint, () => {
|
|
762
|
+
server.on("error", (err) => log.error("server error", err));
|
|
763
|
+
resolve2({
|
|
764
|
+
ok: true,
|
|
765
|
+
server: {
|
|
766
|
+
close: () => new Promise((done) => {
|
|
767
|
+
for (const s of sockets) s.destroy();
|
|
768
|
+
server.close(() => done());
|
|
769
|
+
})
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
});
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
function isAlive(endpoint, timeoutMs = 300) {
|
|
776
|
+
return new Promise((resolve2) => {
|
|
777
|
+
const socket = (0, import_node_net2.connect)(endpoint);
|
|
778
|
+
const done = (alive) => {
|
|
779
|
+
clearTimeout(timer);
|
|
780
|
+
socket.destroy();
|
|
781
|
+
resolve2(alive);
|
|
782
|
+
};
|
|
783
|
+
const timer = setTimeout(() => done(false), timeoutMs);
|
|
784
|
+
socket.once("connect", () => done(true));
|
|
785
|
+
socket.once("error", () => done(false));
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// packages/core/src/daemon.ts
|
|
790
|
+
async function startDaemon(opts) {
|
|
791
|
+
const env = opts.env ?? process.env;
|
|
792
|
+
const paths = avronPaths(env);
|
|
793
|
+
const endpoint = ipcEndpoint(env);
|
|
794
|
+
const log = opts.logger ?? fileLogger(paths.daemonLog);
|
|
795
|
+
const clock = opts.clock ?? systemClock;
|
|
796
|
+
try {
|
|
797
|
+
for (const dir of [paths.home, paths.runDir, paths.logDir, paths.dataDir, paths.cacheDir]) {
|
|
798
|
+
(0, import_node_fs3.mkdirSync)(dir, { recursive: true });
|
|
799
|
+
}
|
|
800
|
+
if (process.platform !== "win32") {
|
|
801
|
+
(0, import_node_fs3.chmodSync)(paths.home, 448);
|
|
802
|
+
(0, import_node_fs3.mkdirSync)((0, import_node_path4.dirname)(endpoint), { recursive: true });
|
|
803
|
+
}
|
|
804
|
+
} catch (err) {
|
|
805
|
+
log.error("cannot prepare avron home", err);
|
|
806
|
+
return { started: false, reason: "error" };
|
|
807
|
+
}
|
|
808
|
+
const engine = new Engine({
|
|
809
|
+
clock,
|
|
810
|
+
campaigns: opts.campaigns,
|
|
811
|
+
sink: opts.sink,
|
|
812
|
+
mode: opts.mode,
|
|
813
|
+
enabled: opts.enabled,
|
|
814
|
+
formats: opts.formats,
|
|
815
|
+
todayTurns: opts.todayTurns,
|
|
816
|
+
onPoster: opts.onPoster,
|
|
817
|
+
onToast: opts.onToast,
|
|
818
|
+
displayCapMs: opts.displayCapMs,
|
|
819
|
+
onServe: opts.onServe
|
|
820
|
+
});
|
|
821
|
+
let lastActivity = clock.now();
|
|
822
|
+
const touch = () => {
|
|
823
|
+
lastActivity = clock.now();
|
|
824
|
+
};
|
|
825
|
+
const onStop = async () => {
|
|
826
|
+
log.info("stop requested");
|
|
827
|
+
await opts.flush?.();
|
|
828
|
+
setTimeout(() => void close().then(() => opts.onExit?.("stop")), 50);
|
|
829
|
+
};
|
|
830
|
+
let res = await listen(endpoint, engine, log, touch, onStop);
|
|
831
|
+
if (!res.ok && res.reason === "in-use") {
|
|
832
|
+
if (await isAlive(endpoint)) {
|
|
833
|
+
engine.dispose();
|
|
834
|
+
return { started: false, reason: "already-running" };
|
|
835
|
+
}
|
|
836
|
+
if (process.platform !== "win32") {
|
|
837
|
+
try {
|
|
838
|
+
(0, import_node_fs3.unlinkSync)(endpoint);
|
|
839
|
+
} catch {
|
|
840
|
+
}
|
|
841
|
+
res = await listen(endpoint, engine, log, touch, onStop);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
if (!res.ok) {
|
|
845
|
+
engine.dispose();
|
|
846
|
+
if (res.reason === "in-use") return { started: false, reason: "already-running" };
|
|
847
|
+
log.error("cannot bind ipc endpoint", res.error);
|
|
848
|
+
return { started: false, reason: "error" };
|
|
849
|
+
}
|
|
850
|
+
const server = res.server;
|
|
851
|
+
if (process.platform !== "win32") {
|
|
852
|
+
try {
|
|
853
|
+
(0, import_node_fs3.chmodSync)(endpoint, 384);
|
|
854
|
+
} catch {
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
const idleExitMs = opts.idleExitMs ?? DAEMON_IDLE_EXIT_MS;
|
|
858
|
+
let closed = false;
|
|
859
|
+
const close = async () => {
|
|
860
|
+
if (closed) return;
|
|
861
|
+
closed = true;
|
|
862
|
+
clearInterval(idleTimer);
|
|
863
|
+
engine.dispose();
|
|
864
|
+
await server.close();
|
|
865
|
+
if (process.platform !== "win32") {
|
|
866
|
+
try {
|
|
867
|
+
(0, import_node_fs3.unlinkSync)(endpoint);
|
|
868
|
+
} catch {
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
const idleTimer = setInterval(
|
|
873
|
+
() => {
|
|
874
|
+
if (clock.now() - lastActivity < idleExitMs) return;
|
|
875
|
+
log.info("no adapter request for the idle limit, shutting down");
|
|
876
|
+
void close().then(() => opts.onExit?.("idle"));
|
|
877
|
+
},
|
|
878
|
+
Math.min(6e4, Math.max(50, Math.floor(idleExitMs / 4)))
|
|
879
|
+
);
|
|
880
|
+
idleTimer.unref();
|
|
881
|
+
log.info(`daemon started pid=${process.pid}`);
|
|
882
|
+
return { started: true, daemon: { endpoint, engine, close } };
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// packages/core/src/identity.ts
|
|
886
|
+
var import_node_crypto3 = require("node:crypto");
|
|
887
|
+
var import_node_fs4 = require("node:fs");
|
|
888
|
+
var import_node_path5 = require("node:path");
|
|
889
|
+
var files = (paths) => ({
|
|
890
|
+
priv: (0, import_node_path5.join)(paths.keyDir, "private.key"),
|
|
891
|
+
pub: (0, import_node_path5.join)(paths.keyDir, "public.key")
|
|
892
|
+
});
|
|
893
|
+
function describe2(publicKeyPem) {
|
|
894
|
+
const der = (0, import_node_crypto3.createPublicKey)(publicKeyPem).export({ type: "spki", format: "der" });
|
|
895
|
+
const installId = (0, import_node_crypto3.createHash)("sha256").update(der).digest("hex");
|
|
896
|
+
return { installId, ref: installId.slice(0, 6), publicKeyPem };
|
|
897
|
+
}
|
|
898
|
+
function loadIdentity(paths) {
|
|
899
|
+
try {
|
|
900
|
+
return describe2((0, import_node_fs4.readFileSync)(files(paths).pub, "utf8"));
|
|
901
|
+
} catch {
|
|
902
|
+
return null;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
function signPayload(paths, payload) {
|
|
906
|
+
try {
|
|
907
|
+
const key = (0, import_node_crypto3.createPrivateKey)((0, import_node_fs4.readFileSync)(files(paths).priv, "utf8"));
|
|
908
|
+
return (0, import_node_crypto3.sign)(null, Buffer.from(payload, "utf8"), key).toString("base64");
|
|
909
|
+
} catch {
|
|
910
|
+
return null;
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
// packages/core/src/ledger.ts
|
|
915
|
+
var import_node_fs5 = require("node:fs");
|
|
916
|
+
var import_promises = require("node:fs/promises");
|
|
917
|
+
var import_node_path6 = require("node:path");
|
|
918
|
+
function dayOf(ts) {
|
|
919
|
+
return new Date(ts).toISOString().slice(0, 10);
|
|
920
|
+
}
|
|
921
|
+
var Ledger = class {
|
|
922
|
+
constructor(paths, log) {
|
|
923
|
+
this.paths = paths;
|
|
924
|
+
this.log = log;
|
|
925
|
+
this.snapshot = {
|
|
926
|
+
validTurns: 0,
|
|
927
|
+
credits: 0,
|
|
928
|
+
byAgent: {},
|
|
929
|
+
today: { date: dayOf(Date.now()), validTurns: 0 },
|
|
930
|
+
updatedAt: 0
|
|
931
|
+
};
|
|
932
|
+
try {
|
|
933
|
+
(0, import_node_fs5.mkdirSync)((0, import_node_path6.dirname)(paths.impressionsLog), { recursive: true });
|
|
934
|
+
(0, import_node_fs5.mkdirSync)((0, import_node_path6.dirname)(paths.ledgerSnapshot), { recursive: true });
|
|
935
|
+
for (const line of (0, import_node_fs5.readFileSync)(paths.impressionsLog, "utf8").split("\n")) {
|
|
936
|
+
if (!line) continue;
|
|
937
|
+
try {
|
|
938
|
+
this.tally(JSON.parse(line));
|
|
939
|
+
} catch {
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
} catch {
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
queue = Promise.resolve();
|
|
946
|
+
snapshot;
|
|
947
|
+
seen = /* @__PURE__ */ new Set();
|
|
948
|
+
tally(e) {
|
|
949
|
+
if (typeof e.turnKey !== "string" || this.seen.has(e.turnKey)) return;
|
|
950
|
+
this.seen.add(e.turnKey);
|
|
951
|
+
const s = this.snapshot;
|
|
952
|
+
s.validTurns += 1;
|
|
953
|
+
s.credits += typeof e.earnedCredits === "number" ? e.earnedCredits : 0;
|
|
954
|
+
s.byAgent[e.agentName] = (s.byAgent[e.agentName] ?? 0) + 1;
|
|
955
|
+
const day = dayOf(e.timestamp);
|
|
956
|
+
if (day !== s.today.date) {
|
|
957
|
+
if (day < s.today.date) return;
|
|
958
|
+
s.today = { date: day, validTurns: 0 };
|
|
959
|
+
}
|
|
960
|
+
s.today.validTurns += 1;
|
|
961
|
+
}
|
|
962
|
+
record(rec) {
|
|
963
|
+
if (this.seen.has(rec.turnKey)) return;
|
|
964
|
+
const entry = { ...rec, syncStatus: "pending" };
|
|
965
|
+
this.tally(entry);
|
|
966
|
+
this.snapshot.updatedAt = rec.timestamp;
|
|
967
|
+
const snapshot = JSON.stringify(this.snapshot);
|
|
968
|
+
this.queue = this.queue.then(() => (0, import_promises.appendFile)(this.paths.impressionsLog, `${JSON.stringify(entry)}
|
|
969
|
+
`)).then(async () => {
|
|
970
|
+
const tmp = `${this.paths.ledgerSnapshot}.tmp`;
|
|
971
|
+
await (0, import_promises.writeFile)(tmp, snapshot);
|
|
972
|
+
await (0, import_promises.rename)(tmp, this.paths.ledgerSnapshot);
|
|
973
|
+
}).catch((err) => this.log.error("ledger write failed", err));
|
|
974
|
+
}
|
|
975
|
+
totals() {
|
|
976
|
+
return this.snapshot;
|
|
977
|
+
}
|
|
978
|
+
/** Wait until every queued write reached the disk. */
|
|
979
|
+
flush() {
|
|
980
|
+
return this.queue;
|
|
981
|
+
}
|
|
982
|
+
};
|
|
983
|
+
|
|
984
|
+
// packages/core/src/manifest.ts
|
|
985
|
+
var import_node_fs6 = require("node:fs");
|
|
986
|
+
var import_node_path7 = require("node:path");
|
|
987
|
+
|
|
988
|
+
// packages/core/src/default-manifest.json
|
|
989
|
+
var default_manifest_default = {
|
|
990
|
+
version: "2.0.0",
|
|
991
|
+
enabled: true,
|
|
992
|
+
ttlSeconds: 1800,
|
|
993
|
+
defaultLocale: "en",
|
|
994
|
+
campaigns: [
|
|
995
|
+
{
|
|
996
|
+
id: "house-how-it-works",
|
|
997
|
+
sponsorName: "Avron",
|
|
998
|
+
weight: 3,
|
|
999
|
+
creatives: {
|
|
1000
|
+
pillStatusline: {
|
|
1001
|
+
badge: "AVRON",
|
|
1002
|
+
copy: "This line shows only while your agent thinks",
|
|
1003
|
+
ctaButton: "How it works",
|
|
1004
|
+
actionUrl: "https://avron.dev/go/how"
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
},
|
|
1008
|
+
{
|
|
1009
|
+
id: "house-privacy",
|
|
1010
|
+
sponsorName: "Avron",
|
|
1011
|
+
weight: 2,
|
|
1012
|
+
creatives: {
|
|
1013
|
+
pillStatusline: {
|
|
1014
|
+
badge: "AVRON",
|
|
1015
|
+
copy: "Reads no prompts, code or file paths",
|
|
1016
|
+
ctaButton: "Verify it",
|
|
1017
|
+
actionUrl: "https://avron.dev/go/audit"
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
},
|
|
1021
|
+
{
|
|
1022
|
+
id: "house-sponsor",
|
|
1023
|
+
sponsorName: "Avron",
|
|
1024
|
+
weight: 2,
|
|
1025
|
+
creatives: {
|
|
1026
|
+
pillStatusline: {
|
|
1027
|
+
badge: "AVRON",
|
|
1028
|
+
copy: "Dev-tool team? Put one line here",
|
|
1029
|
+
ctaButton: "Sponsor",
|
|
1030
|
+
actionUrl: "https://avron.dev/go/sponsor"
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
},
|
|
1034
|
+
{
|
|
1035
|
+
id: "house-uninstall",
|
|
1036
|
+
sponsorName: "Avron",
|
|
1037
|
+
weight: 1,
|
|
1038
|
+
creatives: {
|
|
1039
|
+
pillStatusline: {
|
|
1040
|
+
badge: "AVRON",
|
|
1041
|
+
copy: "Remove anytime with: npx @wbcode/avron uninstall"
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
]
|
|
1046
|
+
};
|
|
1047
|
+
|
|
1048
|
+
// packages/core/src/manifest.ts
|
|
1049
|
+
var LOGO_PREFIX = "https://avron.dev/";
|
|
1050
|
+
var DEFAULT_DAILY_CAP = 60;
|
|
1051
|
+
function str(v, max) {
|
|
1052
|
+
return typeof v === "string" && v.length > 0 && v.length <= max ? v : void 0;
|
|
1053
|
+
}
|
|
1054
|
+
function isObject2(v) {
|
|
1055
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1056
|
+
}
|
|
1057
|
+
function parseCard(raw) {
|
|
1058
|
+
if (!isObject2(raw)) return void 0;
|
|
1059
|
+
const snippet = codeLines(raw.snippet);
|
|
1060
|
+
const body = str(raw.body, 160);
|
|
1061
|
+
const logo = str(raw.logoUrl, 300);
|
|
1062
|
+
const logoUrl = logo?.startsWith(LOGO_PREFIX) && /^[A-Za-z0-9._~\-/:%]+$/.test(logo) ? logo : void 0;
|
|
1063
|
+
const image = str(raw.imageUrl, 300);
|
|
1064
|
+
const imageUrl = image?.startsWith(LOGO_PREFIX) && /^[A-Za-z0-9._~\-/:%]+\.(png|webp)$/.test(image) ? image : void 0;
|
|
1065
|
+
if (!snippet && !body && !logoUrl && !imageUrl) return void 0;
|
|
1066
|
+
return {
|
|
1067
|
+
...snippet ? { snippet } : {},
|
|
1068
|
+
...body ? { body } : {},
|
|
1069
|
+
...logoUrl ? { logoUrl } : {},
|
|
1070
|
+
...imageUrl ? { imageUrl } : {}
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
function codeLines(raw) {
|
|
1074
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > 200) return void 0;
|
|
1075
|
+
const lines = raw.split(String.fromCharCode(10));
|
|
1076
|
+
if (lines.length > 3 || lines.some((l) => l.length === 0 || l.length > 64)) return void 0;
|
|
1077
|
+
return raw;
|
|
1078
|
+
}
|
|
1079
|
+
function idList(raw, re) {
|
|
1080
|
+
if (!Array.isArray(raw)) return void 0;
|
|
1081
|
+
const out = raw.filter((v) => typeof v === "string" && re.test(v)).slice(0, 20);
|
|
1082
|
+
return out.length ? out : void 0;
|
|
1083
|
+
}
|
|
1084
|
+
function parseTargets(raw) {
|
|
1085
|
+
if (!isObject2(raw)) return void 0;
|
|
1086
|
+
const agents = idList(raw.agents, /^[a-z0-9-]{1,32}$/);
|
|
1087
|
+
const locales = idList(raw.locales, /^[a-z]{2}(-[A-Za-z]{2,4})?$/);
|
|
1088
|
+
if (!agents && !locales) return void 0;
|
|
1089
|
+
return { ...agents ? { agents } : {}, ...locales ? { locales } : {} };
|
|
1090
|
+
}
|
|
1091
|
+
function parseManifest(raw) {
|
|
1092
|
+
if (!isObject2(raw) || !Array.isArray(raw.campaigns)) return null;
|
|
1093
|
+
const campaigns = [];
|
|
1094
|
+
for (const c of raw.campaigns) {
|
|
1095
|
+
if (!isObject2(c) || !isObject2(c.creatives)) continue;
|
|
1096
|
+
const id = str(c.id, 64);
|
|
1097
|
+
const sponsorName = str(c.sponsorName, 40);
|
|
1098
|
+
const pill = c.creatives.pillStatusline;
|
|
1099
|
+
if (!id || !/^[A-Za-z0-9._-]+$/.test(id) || !sponsorName || !isObject2(pill)) continue;
|
|
1100
|
+
const copy = str(pill.copy, 120);
|
|
1101
|
+
if (!copy) continue;
|
|
1102
|
+
const actionUrl = str(pill.actionUrl, 300);
|
|
1103
|
+
const locales = {};
|
|
1104
|
+
if (isObject2(c.creatives.locales)) {
|
|
1105
|
+
for (const [lang, v] of Object.entries(c.creatives.locales)) {
|
|
1106
|
+
if (!isObject2(v) || !/^[a-z]{2}(-[A-Z]{2})?$/.test(lang)) continue;
|
|
1107
|
+
locales[lang] = { copy: str(v.copy, 120), ctaButton: str(v.ctaButton, 28) };
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
const microTag = str(c.creatives.microTag, 40);
|
|
1111
|
+
const card = parseCard(c.creatives.card);
|
|
1112
|
+
const art = cleanArt(c.creatives.art);
|
|
1113
|
+
const motion = MOTIONS.includes(c.creatives.motion) ? c.creatives.motion : void 0;
|
|
1114
|
+
const targets = parseTargets(c.targets);
|
|
1115
|
+
campaigns.push({
|
|
1116
|
+
id,
|
|
1117
|
+
sponsorName,
|
|
1118
|
+
weight: typeof c.weight === "number" && c.weight > 0 ? Math.min(c.weight, 1e3) : 1,
|
|
1119
|
+
dailyCap: typeof c.dailyCap === "number" && c.dailyCap > 0 ? Math.floor(c.dailyCap) : DEFAULT_DAILY_CAP,
|
|
1120
|
+
promoCode: str(c.promoCode, 40),
|
|
1121
|
+
...microTag && [...microTag].length <= MICRO_TAG_MAX_CHARS ? { microTag } : {},
|
|
1122
|
+
pill: {
|
|
1123
|
+
badge: str(pill.badge, 24) ?? sponsorName,
|
|
1124
|
+
copy,
|
|
1125
|
+
ctaButton: str(pill.ctaButton, 28),
|
|
1126
|
+
// Anything that is not an avron.dev/go link is dropped here and again at render time.
|
|
1127
|
+
...actionUrl?.startsWith(ALLOWED_LINK_PREFIX) ? { actionUrl } : {}
|
|
1128
|
+
},
|
|
1129
|
+
locales,
|
|
1130
|
+
...card ? { card } : {},
|
|
1131
|
+
...art ? { art } : {},
|
|
1132
|
+
...art && motion ? { motion } : {},
|
|
1133
|
+
...targets ? { targets } : {},
|
|
1134
|
+
...isAdTier(c.tier) && c.tier !== "line" ? { tier: c.tier } : {}
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
return {
|
|
1138
|
+
version: str(raw.version, 20) ?? "0",
|
|
1139
|
+
enabled: raw.enabled !== false,
|
|
1140
|
+
serverNonce: str(raw.serverNonce, 300),
|
|
1141
|
+
ttlSeconds: typeof raw.ttlSeconds === "number" && raw.ttlSeconds > 0 ? raw.ttlSeconds : 1800,
|
|
1142
|
+
campaigns
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
function readJson(file) {
|
|
1146
|
+
try {
|
|
1147
|
+
return JSON.parse((0, import_node_fs6.readFileSync)(file, "utf8"));
|
|
1148
|
+
} catch {
|
|
1149
|
+
return null;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
var ManifestStore = class {
|
|
1153
|
+
constructor(env, log) {
|
|
1154
|
+
this.env = env;
|
|
1155
|
+
this.log = log;
|
|
1156
|
+
this.manifest = parseManifest(default_manifest_default) ?? {
|
|
1157
|
+
version: "0",
|
|
1158
|
+
enabled: true,
|
|
1159
|
+
ttlSeconds: 1800,
|
|
1160
|
+
campaigns: []
|
|
1161
|
+
};
|
|
1162
|
+
this.reload();
|
|
1163
|
+
}
|
|
1164
|
+
manifest;
|
|
1165
|
+
current() {
|
|
1166
|
+
return this.manifest;
|
|
1167
|
+
}
|
|
1168
|
+
/** Re-read from disk. Keeps the previous manifest if nothing valid is found. */
|
|
1169
|
+
reload() {
|
|
1170
|
+
const paths = avronPaths(this.env);
|
|
1171
|
+
const dropIn = (0, import_node_path7.join)(paths.home, "manifest.override.json");
|
|
1172
|
+
const override = this.env.AVRON_MANIFEST_FILE || ((0, import_node_fs6.existsSync)(dropIn) ? dropIn : void 0);
|
|
1173
|
+
const sources = override ? [override] : [paths.manifestCache];
|
|
1174
|
+
for (const file of sources) {
|
|
1175
|
+
const parsed = parseManifest(readJson(file));
|
|
1176
|
+
if (parsed) {
|
|
1177
|
+
this.manifest = parsed;
|
|
1178
|
+
return;
|
|
1179
|
+
}
|
|
1180
|
+
if (override) this.log.error(`manifest override is not usable: ${file}`);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
function localDay(now) {
|
|
1185
|
+
const d = new Date(now);
|
|
1186
|
+
return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
|
|
1187
|
+
}
|
|
1188
|
+
function systemLocale() {
|
|
1189
|
+
try {
|
|
1190
|
+
return Intl.DateTimeFormat().resolvedOptions().locale;
|
|
1191
|
+
} catch {
|
|
1192
|
+
return "";
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
function localeCandidates(env, osLocale = systemLocale()) {
|
|
1196
|
+
const posix = [env.AVRON_LOCALE, env.LC_ALL, env.LC_MESSAGES, env.LANG].find(
|
|
1197
|
+
(v) => v && !/^(C|POSIX)([._@]|$)/i.test(v)
|
|
1198
|
+
);
|
|
1199
|
+
const raw = (posix || osLocale || "").split(/[.@]/)[0].replace(/_/g, "-");
|
|
1200
|
+
const parts = raw.split("-").filter(Boolean);
|
|
1201
|
+
const lang = parts[0]?.toLowerCase() ?? "";
|
|
1202
|
+
if (!/^[a-z]{2,3}$/.test(lang)) return [];
|
|
1203
|
+
const script = parts.find((p) => /^[A-Za-z]{4}$/.test(p))?.toLowerCase();
|
|
1204
|
+
const region = parts.slice(1).find((p) => /^([A-Za-z]{2}|\d{3})$/.test(p))?.toUpperCase();
|
|
1205
|
+
const out = [];
|
|
1206
|
+
if (lang === "zh") {
|
|
1207
|
+
const traditional = script === "hant" || !script && ["TW", "HK", "MO"].includes(region ?? "");
|
|
1208
|
+
if (region) out.push(`zh-${region}`);
|
|
1209
|
+
out.push(traditional ? "zh-TW" : "zh-CN");
|
|
1210
|
+
} else if (region) {
|
|
1211
|
+
out.push(`${lang}-${region}`);
|
|
1212
|
+
}
|
|
1213
|
+
out.push(lang);
|
|
1214
|
+
return [...new Set(out)];
|
|
1215
|
+
}
|
|
1216
|
+
function localized(locales, candidates) {
|
|
1217
|
+
const keys = new Map(Object.keys(locales).map((k) => [k.toLowerCase(), k]));
|
|
1218
|
+
for (const c of candidates) {
|
|
1219
|
+
const key = keys.get(c.toLowerCase());
|
|
1220
|
+
if (key !== void 0) return { key, value: locales[key] };
|
|
1221
|
+
}
|
|
1222
|
+
return void 0;
|
|
1223
|
+
}
|
|
1224
|
+
function sponsorLabel(localeKey) {
|
|
1225
|
+
if (!localeKey) return SPONSOR_LABEL;
|
|
1226
|
+
const [lang = ""] = localeKey.split("-");
|
|
1227
|
+
return SPONSOR_LABELS[localeKey] ?? SPONSOR_LABELS[lang] ?? SPONSOR_LABEL;
|
|
1228
|
+
}
|
|
1229
|
+
var Rotation = class {
|
|
1230
|
+
constructor(manifest, opts = {}) {
|
|
1231
|
+
this.manifest = manifest;
|
|
1232
|
+
this.opts = opts;
|
|
1233
|
+
this.load();
|
|
1234
|
+
}
|
|
1235
|
+
last = null;
|
|
1236
|
+
day = "";
|
|
1237
|
+
shown = /* @__PURE__ */ new Map();
|
|
1238
|
+
candidates = null;
|
|
1239
|
+
/** Worked out once: the machine's language does not change while the daemon runs. */
|
|
1240
|
+
locale() {
|
|
1241
|
+
this.candidates ??= localeCandidates(this.opts.env ?? process.env, this.opts.osLocale);
|
|
1242
|
+
return this.candidates;
|
|
1243
|
+
}
|
|
1244
|
+
today() {
|
|
1245
|
+
const today = localDay(this.opts.now ? this.opts.now() : Date.now());
|
|
1246
|
+
if (today !== this.day) {
|
|
1247
|
+
this.day = today;
|
|
1248
|
+
this.shown.clear();
|
|
1249
|
+
}
|
|
1250
|
+
return today;
|
|
1251
|
+
}
|
|
1252
|
+
load() {
|
|
1253
|
+
const path = this.opts.statePath;
|
|
1254
|
+
if (!path) return;
|
|
1255
|
+
try {
|
|
1256
|
+
const raw = JSON.parse((0, import_node_fs6.readFileSync)(path, "utf8"));
|
|
1257
|
+
if (typeof raw.day !== "string" || raw.day !== this.today()) return;
|
|
1258
|
+
if (typeof raw.last === "string") this.last = raw.last;
|
|
1259
|
+
if (raw.shown && typeof raw.shown === "object") {
|
|
1260
|
+
for (const [id, n] of Object.entries(raw.shown)) {
|
|
1261
|
+
if (typeof n === "number" && Number.isInteger(n) && n > 0) this.shown.set(id, n);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
} catch {
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
saveTimer = null;
|
|
1268
|
+
/**
|
|
1269
|
+
* Write today's counts now. Called by the daemon on shutdown and by tests; during normal work
|
|
1270
|
+
* `served` schedules this about a second later, so the disk write never sits on the path of a
|
|
1271
|
+
* status line request (15 ms budget).
|
|
1272
|
+
*/
|
|
1273
|
+
flush() {
|
|
1274
|
+
if (this.saveTimer) {
|
|
1275
|
+
clearTimeout(this.saveTimer);
|
|
1276
|
+
this.saveTimer = null;
|
|
1277
|
+
}
|
|
1278
|
+
const path = this.opts.statePath;
|
|
1279
|
+
if (!path) return;
|
|
1280
|
+
try {
|
|
1281
|
+
(0, import_node_fs6.mkdirSync)((0, import_node_path7.dirname)(path), { recursive: true });
|
|
1282
|
+
const tmp = `${path}.tmp`;
|
|
1283
|
+
(0, import_node_fs6.writeFileSync)(
|
|
1284
|
+
tmp,
|
|
1285
|
+
JSON.stringify({ day: this.day, last: this.last, shown: Object.fromEntries(this.shown) })
|
|
1286
|
+
);
|
|
1287
|
+
(0, import_node_fs6.renameSync)(tmp, path);
|
|
1288
|
+
} catch {
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
served(campaignId) {
|
|
1292
|
+
this.today();
|
|
1293
|
+
this.last = campaignId;
|
|
1294
|
+
this.shown.set(campaignId, (this.shown.get(campaignId) ?? 0) + 1);
|
|
1295
|
+
if (this.opts.statePath && !this.saveTimer) {
|
|
1296
|
+
this.saveTimer = setTimeout(() => this.flush(), 1e3);
|
|
1297
|
+
this.saveTimer.unref?.();
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
/** A campaign aimed at some tools or languages is left out everywhere else. */
|
|
1301
|
+
aimedHere(c, ctx) {
|
|
1302
|
+
if (ctx.drawable && AD_TIER_RANK[c.tier ?? "line"] > AD_TIER_RANK[ctx.drawable]) return false;
|
|
1303
|
+
const t = c.targets;
|
|
1304
|
+
if (!t) return true;
|
|
1305
|
+
if (t.agents && !(ctx.agentName && t.agents.includes(ctx.agentName))) return false;
|
|
1306
|
+
if (t.locales) {
|
|
1307
|
+
const mine = this.locale().map((l) => l.toLowerCase());
|
|
1308
|
+
const hit = t.locales.some((want) => {
|
|
1309
|
+
const w = want.toLowerCase();
|
|
1310
|
+
return mine.some((l) => l === w || l.startsWith(`${w}-`));
|
|
1311
|
+
});
|
|
1312
|
+
if (!hit) return false;
|
|
1313
|
+
}
|
|
1314
|
+
return true;
|
|
1315
|
+
}
|
|
1316
|
+
pick(ctx = {}) {
|
|
1317
|
+
const m = this.manifest();
|
|
1318
|
+
if (!m.enabled) return null;
|
|
1319
|
+
this.today();
|
|
1320
|
+
let pool = m.campaigns.filter((c) => (this.shown.get(c.id) ?? 0) < c.dailyCap && this.aimedHere(c, ctx));
|
|
1321
|
+
if (pool.length === 0) return null;
|
|
1322
|
+
if (pool.length > 1) pool = pool.filter((c) => c.id !== this.last);
|
|
1323
|
+
const total = pool.reduce((sum, c) => sum + c.weight, 0);
|
|
1324
|
+
let roll = (this.opts.random ? this.opts.random() : Math.random()) * total;
|
|
1325
|
+
let chosen = pool[pool.length - 1];
|
|
1326
|
+
for (const c of pool) {
|
|
1327
|
+
roll -= c.weight;
|
|
1328
|
+
if (roll < 0) {
|
|
1329
|
+
chosen = c;
|
|
1330
|
+
break;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
const match = localized(chosen.locales, this.locale());
|
|
1334
|
+
const local = match?.value.copy ? match.value : void 0;
|
|
1335
|
+
const label = sponsorLabel(local ? match?.key : void 0);
|
|
1336
|
+
const ref = this.opts.installRef?.();
|
|
1337
|
+
const url = chosen.pill.actionUrl;
|
|
1338
|
+
return {
|
|
1339
|
+
campaignId: chosen.id,
|
|
1340
|
+
label,
|
|
1341
|
+
sponsorName: chosen.pill.badge,
|
|
1342
|
+
headline: local?.copy ?? chosen.pill.copy,
|
|
1343
|
+
ctaText: local?.ctaButton ?? chosen.pill.ctaButton,
|
|
1344
|
+
promoCode: chosen.promoCode,
|
|
1345
|
+
...chosen.card?.snippet ? { snippet: chosen.card.snippet } : {},
|
|
1346
|
+
...chosen.card?.body ? { body: chosen.card.body } : {},
|
|
1347
|
+
...chosen.card?.logoUrl ? { logoUrl: chosen.card.logoUrl } : {},
|
|
1348
|
+
...chosen.card?.imageUrl ? { imageUrl: chosen.card.imageUrl } : {},
|
|
1349
|
+
...chosen.art ? { art: chosen.art } : {},
|
|
1350
|
+
...chosen.motion ? { motion: chosen.motion } : {},
|
|
1351
|
+
...url ? {
|
|
1352
|
+
actionUrl: ref ? `${url}${url.includes("?") ? "&" : "?"}r=${ref}` : url,
|
|
1353
|
+
displayUrl: url.replace(/^https:\/\//, "")
|
|
1354
|
+
} : {}
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
};
|
|
1358
|
+
|
|
1359
|
+
// packages/core/src/relaunch.ts
|
|
1360
|
+
var import_node_child_process = require("node:child_process");
|
|
1361
|
+
var import_node_fs7 = require("node:fs");
|
|
1362
|
+
var import_node_os2 = require("node:os");
|
|
1363
|
+
var import_node_path8 = require("node:path");
|
|
1364
|
+
var CLEAN_FLAG = "--clean";
|
|
1365
|
+
function relaunchWithoutInheritedHandles(entry, env = process.env, timeoutMs = 1e4) {
|
|
1366
|
+
return new Promise((resolve2) => {
|
|
1367
|
+
let settled = false;
|
|
1368
|
+
const finish = (ok) => {
|
|
1369
|
+
if (settled) return;
|
|
1370
|
+
settled = true;
|
|
1371
|
+
clearTimeout(timer);
|
|
1372
|
+
resolve2(ok);
|
|
1373
|
+
};
|
|
1374
|
+
const powershell = (0, import_node_path8.join)(
|
|
1375
|
+
env.SystemRoot || env.windir || "C:\\Windows",
|
|
1376
|
+
"System32",
|
|
1377
|
+
"WindowsPowerShell",
|
|
1378
|
+
"v1.0",
|
|
1379
|
+
"powershell.exe"
|
|
1380
|
+
);
|
|
1381
|
+
const timer = setTimeout(() => {
|
|
1382
|
+
try {
|
|
1383
|
+
child?.kill();
|
|
1384
|
+
} catch {
|
|
1385
|
+
}
|
|
1386
|
+
finish(false);
|
|
1387
|
+
}, timeoutMs);
|
|
1388
|
+
let child;
|
|
1389
|
+
if (!(0, import_node_fs7.existsSync)(powershell)) {
|
|
1390
|
+
finish(false);
|
|
1391
|
+
return;
|
|
1392
|
+
}
|
|
1393
|
+
const command = [
|
|
1394
|
+
"Start-Process -WindowStyle Hidden",
|
|
1395
|
+
"-WorkingDirectory $env:AVRON_RELAUNCH_CWD",
|
|
1396
|
+
"-FilePath $env:AVRON_RELAUNCH_NODE",
|
|
1397
|
+
`-ArgumentList ([char]34 + $env:AVRON_RELAUNCH_ENTRY + [char]34), '${CLEAN_FLAG}'`
|
|
1398
|
+
].join(" ");
|
|
1399
|
+
try {
|
|
1400
|
+
child = (0, import_node_child_process.spawn)(powershell, ["-NoProfile", "-NonInteractive", "-Command", command], {
|
|
1401
|
+
// Not detached: PowerShell does not start without a console of its own.
|
|
1402
|
+
stdio: "ignore",
|
|
1403
|
+
windowsHide: true,
|
|
1404
|
+
env: {
|
|
1405
|
+
...env,
|
|
1406
|
+
AVRON_RELAUNCH_NODE: process.execPath,
|
|
1407
|
+
AVRON_RELAUNCH_ENTRY: entry,
|
|
1408
|
+
AVRON_RELAUNCH_CWD: (0, import_node_os2.homedir)()
|
|
1409
|
+
}
|
|
1410
|
+
});
|
|
1411
|
+
child.on("error", () => finish(false));
|
|
1412
|
+
child.on("exit", (code) => finish(code === 0));
|
|
1413
|
+
} catch {
|
|
1414
|
+
finish(false);
|
|
1415
|
+
}
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// packages/core/src/sync.ts
|
|
1420
|
+
var import_node_crypto4 = require("node:crypto");
|
|
1421
|
+
var import_node_fs8 = require("node:fs");
|
|
1422
|
+
var import_node_path9 = require("node:path");
|
|
1423
|
+
var DEFAULT_API_BASE = "https://avron.dev";
|
|
1424
|
+
var MAX_EVENTS_PER_BATCH = 500;
|
|
1425
|
+
var HTTP_TIMEOUT_MS = 8e3;
|
|
1426
|
+
function apiBase(env) {
|
|
1427
|
+
const v = env.AVRON_API_BASE;
|
|
1428
|
+
return v && /^https?:\/\//.test(v) ? v.replace(/\/+$/, "") : DEFAULT_API_BASE;
|
|
1429
|
+
}
|
|
1430
|
+
async function http(fetchImpl, url, timeoutMs, init) {
|
|
1431
|
+
const ctl = new AbortController();
|
|
1432
|
+
const timer = setTimeout(() => ctl.abort(), timeoutMs);
|
|
1433
|
+
try {
|
|
1434
|
+
return await fetchImpl(url, { ...init, signal: ctl.signal });
|
|
1435
|
+
} finally {
|
|
1436
|
+
clearTimeout(timer);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
async function syncManifest(env, paths, store, log, fetchImpl = fetch) {
|
|
1440
|
+
try {
|
|
1441
|
+
const res = await http(fetchImpl, `${apiBase(env)}/v1/manifest.json`, HTTP_TIMEOUT_MS);
|
|
1442
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
1443
|
+
const text = await res.text();
|
|
1444
|
+
if (!parseManifest(JSON.parse(text))) throw new Error("manifest failed validation");
|
|
1445
|
+
(0, import_node_fs8.mkdirSync)((0, import_node_path9.dirname)(paths.manifestCache), { recursive: true });
|
|
1446
|
+
const tmp = `${paths.manifestCache}.tmp`;
|
|
1447
|
+
(0, import_node_fs8.writeFileSync)(tmp, text);
|
|
1448
|
+
(0, import_node_fs8.renameSync)(tmp, paths.manifestCache);
|
|
1449
|
+
store.reload();
|
|
1450
|
+
return true;
|
|
1451
|
+
} catch (err) {
|
|
1452
|
+
log.error("manifest sync failed (cached manifest stays in use)", err);
|
|
1453
|
+
return false;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
var statePath = (paths) => (0, import_node_path9.join)(paths.dataDir, "sync-state.json");
|
|
1457
|
+
var count = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
|
|
1458
|
+
function readState(paths) {
|
|
1459
|
+
try {
|
|
1460
|
+
const s = JSON.parse((0, import_node_fs8.readFileSync)(statePath(paths), "utf8"));
|
|
1461
|
+
const accepted = count(s.accepted);
|
|
1462
|
+
const acceptedAt = count(s.acceptedAt);
|
|
1463
|
+
return {
|
|
1464
|
+
offset: count(s.offset) ?? 0,
|
|
1465
|
+
...accepted !== void 0 ? { accepted } : {},
|
|
1466
|
+
...acceptedAt !== void 0 ? { acceptedAt } : {}
|
|
1467
|
+
};
|
|
1468
|
+
} catch {
|
|
1469
|
+
return { offset: 0 };
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
function updateState(paths, patch) {
|
|
1473
|
+
(0, import_node_fs8.mkdirSync)(paths.dataDir, { recursive: true });
|
|
1474
|
+
const tmp = `${statePath(paths)}.tmp`;
|
|
1475
|
+
(0, import_node_fs8.writeFileSync)(tmp, JSON.stringify({ ...readState(paths), ...patch }));
|
|
1476
|
+
(0, import_node_fs8.renameSync)(tmp, statePath(paths));
|
|
1477
|
+
}
|
|
1478
|
+
function readPending(paths) {
|
|
1479
|
+
let size = 0;
|
|
1480
|
+
try {
|
|
1481
|
+
size = (0, import_node_fs8.statSync)(paths.impressionsLog).size;
|
|
1482
|
+
} catch {
|
|
1483
|
+
return { events: [], nextOffset: 0, size: 0 };
|
|
1484
|
+
}
|
|
1485
|
+
let offset = Math.min(readState(paths).offset, size);
|
|
1486
|
+
const fd = (0, import_node_fs8.openSync)(paths.impressionsLog, "r");
|
|
1487
|
+
try {
|
|
1488
|
+
if (size - offset > OFFLINE_QUEUE_MAX_BYTES) {
|
|
1489
|
+
offset = size - OFFLINE_QUEUE_MAX_BYTES;
|
|
1490
|
+
const probe = Buffer.alloc(4096);
|
|
1491
|
+
const n = (0, import_node_fs8.readSync)(fd, probe, 0, probe.length, offset);
|
|
1492
|
+
const nl = probe.subarray(0, n).indexOf(10);
|
|
1493
|
+
offset += nl >= 0 ? nl + 1 : n;
|
|
1494
|
+
}
|
|
1495
|
+
const want = Math.min(size - offset, 512 * 1024);
|
|
1496
|
+
const buf = Buffer.alloc(want);
|
|
1497
|
+
const got = (0, import_node_fs8.readSync)(fd, buf, 0, want, offset);
|
|
1498
|
+
const chunk = buf.subarray(0, got);
|
|
1499
|
+
const events = [];
|
|
1500
|
+
let consumed = 0;
|
|
1501
|
+
while (events.length < MAX_EVENTS_PER_BATCH) {
|
|
1502
|
+
const nl = chunk.indexOf(10, consumed);
|
|
1503
|
+
if (nl < 0) break;
|
|
1504
|
+
const line = chunk.subarray(consumed, nl).toString("utf8");
|
|
1505
|
+
consumed = nl + 1;
|
|
1506
|
+
try {
|
|
1507
|
+
const e = JSON.parse(line);
|
|
1508
|
+
if (e.mode !== "pill-statusline") continue;
|
|
1509
|
+
events.push({
|
|
1510
|
+
turnKey: e.turnKey,
|
|
1511
|
+
timestamp: e.timestamp,
|
|
1512
|
+
campaignId: e.campaignId,
|
|
1513
|
+
agentName: e.agentName,
|
|
1514
|
+
agentTier: e.agentTier,
|
|
1515
|
+
exposureDurationSec: e.exposureDurationSec,
|
|
1516
|
+
displayedDurationSec: e.displayedDurationSec,
|
|
1517
|
+
mode: e.mode,
|
|
1518
|
+
format: e.format ?? "line"
|
|
1519
|
+
});
|
|
1520
|
+
} catch {
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
return { events, nextOffset: offset + consumed, size };
|
|
1524
|
+
} finally {
|
|
1525
|
+
(0, import_node_fs8.closeSync)(fd);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
function signBatch(paths, pending, nonce, now) {
|
|
1529
|
+
if (pending.events.length === 0) return null;
|
|
1530
|
+
const identity = loadIdentity(paths);
|
|
1531
|
+
if (!identity) return null;
|
|
1532
|
+
const payload = JSON.stringify({
|
|
1533
|
+
v: 1,
|
|
1534
|
+
installId: identity.installId,
|
|
1535
|
+
nonce: nonce ?? null,
|
|
1536
|
+
sentAt: now,
|
|
1537
|
+
events: pending.events
|
|
1538
|
+
});
|
|
1539
|
+
const signature = signPayload(paths, payload);
|
|
1540
|
+
if (!signature) return null;
|
|
1541
|
+
const publicKey = (0, import_node_crypto4.createPublicKey)(identity.publicKeyPem).export({ type: "spki", format: "der" }).toString("base64");
|
|
1542
|
+
return {
|
|
1543
|
+
envelope: { payload, publicKey, signature },
|
|
1544
|
+
events: pending.events,
|
|
1545
|
+
nextOffset: pending.nextOffset
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
async function flushBatches(env, paths, store, log, fetchImpl = fetch, now = Date.now) {
|
|
1549
|
+
let delivered = 0;
|
|
1550
|
+
try {
|
|
1551
|
+
for (let i = 0; i < 20; i++) {
|
|
1552
|
+
const nonce = store.current().serverNonce;
|
|
1553
|
+
if (!nonce) return delivered;
|
|
1554
|
+
const before = readState(paths).offset;
|
|
1555
|
+
const pending = readPending(paths);
|
|
1556
|
+
if (pending.events.length === 0) {
|
|
1557
|
+
if (pending.nextOffset > before) {
|
|
1558
|
+
updateState(paths, { offset: pending.nextOffset });
|
|
1559
|
+
continue;
|
|
1560
|
+
}
|
|
1561
|
+
return delivered;
|
|
1562
|
+
}
|
|
1563
|
+
const batch = signBatch(paths, pending, nonce, now());
|
|
1564
|
+
if (!batch) return delivered;
|
|
1565
|
+
const res = await http(fetchImpl, `${apiBase(env)}/v1/events/batch`, HTTP_TIMEOUT_MS, {
|
|
1566
|
+
method: "POST",
|
|
1567
|
+
headers: { "content-type": "application/json" },
|
|
1568
|
+
body: JSON.stringify(batch.envelope)
|
|
1569
|
+
});
|
|
1570
|
+
if (res.status !== 202) throw new Error(`HTTP ${res.status}`);
|
|
1571
|
+
let accepted = 0;
|
|
1572
|
+
try {
|
|
1573
|
+
accepted = count(JSON.parse(await res.text()).accepted) ?? 0;
|
|
1574
|
+
} catch {
|
|
1575
|
+
}
|
|
1576
|
+
updateState(paths, {
|
|
1577
|
+
offset: batch.nextOffset,
|
|
1578
|
+
accepted: (readState(paths).accepted ?? 0) + accepted,
|
|
1579
|
+
acceptedAt: now()
|
|
1580
|
+
});
|
|
1581
|
+
delivered += batch.events.length;
|
|
1582
|
+
}
|
|
1583
|
+
} catch (err) {
|
|
1584
|
+
log.error("batch flush failed (events stay queued on disk)", err);
|
|
1585
|
+
}
|
|
1586
|
+
return delivered;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
// packages/core/src/toast.ts
|
|
1590
|
+
var import_node_child_process2 = require("node:child_process");
|
|
1591
|
+
var import_node_crypto5 = require("node:crypto");
|
|
1592
|
+
var import_node_fs9 = require("node:fs");
|
|
1593
|
+
var import_node_path10 = require("node:path");
|
|
1594
|
+
var WINDOWS_APP_ID = "Avron.Notifier";
|
|
1595
|
+
var WINDOWS_APP_KEY = `HKCU:\\Software\\Classes\\AppUserModelId\\${WINDOWS_APP_ID}`;
|
|
1596
|
+
var WINDOWS_SCRIPT = [
|
|
1597
|
+
'$ErrorActionPreference = "Stop"',
|
|
1598
|
+
"[void][Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]",
|
|
1599
|
+
"[void][Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]",
|
|
1600
|
+
`$k = '${WINDOWS_APP_KEY}'`,
|
|
1601
|
+
'if (-not (Test-Path $k)) { [void](New-Item $k -Force); [void](New-ItemProperty $k -Name DisplayName -Value "Avron" -PropertyType String -Force) }',
|
|
1602
|
+
"$t = New-Object Windows.Data.Xml.Dom.XmlDocument",
|
|
1603
|
+
`$t.LoadXml('<toast duration="long"><visual><binding template="ToastGeneric"><text/><text/><text/></binding></visual></toast>')`,
|
|
1604
|
+
'$b = $t.GetElementsByTagName("binding").Item(0)',
|
|
1605
|
+
'$n = $t.GetElementsByTagName("text")',
|
|
1606
|
+
"[void]$n.Item(0).AppendChild($t.CreateTextNode($env:AVRON_TOAST_TITLE))",
|
|
1607
|
+
"[void]$n.Item(1).AppendChild($t.CreateTextNode($env:AVRON_TOAST_BODY))",
|
|
1608
|
+
"[void]$n.Item(2).AppendChild($t.CreateTextNode($env:AVRON_TOAST_EXTRA))",
|
|
1609
|
+
'if ($env:AVRON_TOAST_HERO) { $i = $t.CreateElement("image"); $i.SetAttribute("placement", "hero"); $i.SetAttribute("src", $env:AVRON_TOAST_HERO); [void]$b.InsertBefore($i, $b.FirstChild) }',
|
|
1610
|
+
'if ($env:AVRON_TOAST_IMAGE) { $i = $t.CreateElement("image"); $i.SetAttribute("placement", "appLogoOverride"); $i.SetAttribute("src", $env:AVRON_TOAST_IMAGE); [void]$b.InsertBefore($i, $b.FirstChild) }',
|
|
1611
|
+
'if ($env:AVRON_TOAST_URL) { $t.DocumentElement.SetAttribute("activationType", "protocol"); $t.DocumentElement.SetAttribute("launch", $env:AVRON_TOAST_URL) }',
|
|
1612
|
+
"$toast = [Windows.UI.Notifications.ToastNotification]::new($t)",
|
|
1613
|
+
"$toast.ExpirationTime = [DateTimeOffset]::Now.AddSeconds(30)",
|
|
1614
|
+
'$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("Avron.Notifier")',
|
|
1615
|
+
// Windows reports success even when the user (or a policy) has switched this app's notifications
|
|
1616
|
+
// off, so ask first: a notification nobody can see must not count as shown (exit code 3).
|
|
1617
|
+
'if ($notifier.Setting.ToString() -ne "Enabled") { exit 3 }',
|
|
1618
|
+
"$notifier.Show($toast)"
|
|
1619
|
+
].join("; ");
|
|
1620
|
+
function toastCommand(toast, platform = process.platform) {
|
|
1621
|
+
const env = {
|
|
1622
|
+
AVRON_TOAST_TITLE: toast.title,
|
|
1623
|
+
AVRON_TOAST_BODY: toast.body,
|
|
1624
|
+
AVRON_TOAST_EXTRA: toast.extra ?? "",
|
|
1625
|
+
AVRON_TOAST_URL: toast.url ?? "",
|
|
1626
|
+
AVRON_TOAST_IMAGE: toast.image ?? "",
|
|
1627
|
+
AVRON_TOAST_HERO: toast.hero ?? ""
|
|
1628
|
+
};
|
|
1629
|
+
if (platform === "win32")
|
|
1630
|
+
return {
|
|
1631
|
+
cmd: "powershell.exe",
|
|
1632
|
+
args: ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_SCRIPT],
|
|
1633
|
+
env
|
|
1634
|
+
};
|
|
1635
|
+
if (platform === "darwin")
|
|
1636
|
+
return {
|
|
1637
|
+
cmd: "osascript",
|
|
1638
|
+
args: [
|
|
1639
|
+
"-e",
|
|
1640
|
+
'display notification ((system attribute "AVRON_TOAST_BODY") & return & (system attribute "AVRON_TOAST_EXTRA")) with title (system attribute "AVRON_TOAST_TITLE")'
|
|
1641
|
+
],
|
|
1642
|
+
env
|
|
1643
|
+
};
|
|
1644
|
+
if (platform === "linux")
|
|
1645
|
+
return {
|
|
1646
|
+
cmd: "notify-send",
|
|
1647
|
+
args: [
|
|
1648
|
+
"--expire-time=15000",
|
|
1649
|
+
toast.title,
|
|
1650
|
+
[toast.body, toast.extra].filter(Boolean).join(String.fromCharCode(10))
|
|
1651
|
+
],
|
|
1652
|
+
env
|
|
1653
|
+
};
|
|
1654
|
+
return null;
|
|
1655
|
+
}
|
|
1656
|
+
function showToast(toast) {
|
|
1657
|
+
const c = toastCommand(toast);
|
|
1658
|
+
if (!c) return Promise.resolve(false);
|
|
1659
|
+
return new Promise((resolve2) => {
|
|
1660
|
+
try {
|
|
1661
|
+
const child = (0, import_node_child_process2.spawn)(c.cmd, c.args, {
|
|
1662
|
+
env: { ...process.env, ...c.env },
|
|
1663
|
+
stdio: "ignore",
|
|
1664
|
+
windowsHide: true
|
|
1665
|
+
});
|
|
1666
|
+
const timer = setTimeout(() => {
|
|
1667
|
+
child.kill();
|
|
1668
|
+
resolve2(false);
|
|
1669
|
+
}, 1e4);
|
|
1670
|
+
child.on("error", () => {
|
|
1671
|
+
clearTimeout(timer);
|
|
1672
|
+
resolve2(false);
|
|
1673
|
+
});
|
|
1674
|
+
child.on("exit", (code) => {
|
|
1675
|
+
clearTimeout(timer);
|
|
1676
|
+
resolve2(code === 0);
|
|
1677
|
+
});
|
|
1678
|
+
} catch {
|
|
1679
|
+
resolve2(false);
|
|
1680
|
+
}
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
function toastFor(c) {
|
|
1684
|
+
const code = c.snippet?.split(String.fromCharCode(10))[0]?.trim() ?? "";
|
|
1685
|
+
const extra = [code, c.promoCode ? `code ${c.promoCode}` : ""].filter(Boolean).join(" \xB7 ");
|
|
1686
|
+
return {
|
|
1687
|
+
title: `${c.label ?? "Sponsored"} \xB7 ${c.sponsorName}`,
|
|
1688
|
+
body: c.headline,
|
|
1689
|
+
extra,
|
|
1690
|
+
...c.actionUrl?.startsWith("https://avron.dev/") ? { url: c.actionUrl } : {}
|
|
1691
|
+
};
|
|
1692
|
+
}
|
|
1693
|
+
var PICTURE_MAX_BYTES = 2e5;
|
|
1694
|
+
var PICTURES_KEPT = 20;
|
|
1695
|
+
var PNG_MAGIC = [137, 80, 78, 71];
|
|
1696
|
+
async function cachePicture(url, dir, fetchFn = fetch) {
|
|
1697
|
+
if (!url?.startsWith("https://avron.dev/") || !url.endsWith(".png")) return "";
|
|
1698
|
+
const file = (0, import_node_path10.join)(dir, `${(0, import_node_crypto5.createHash)("sha256").update(url).digest("hex").slice(0, 16)}.png`);
|
|
1699
|
+
try {
|
|
1700
|
+
if ((0, import_node_fs9.statSync)(file).size > 0) return file;
|
|
1701
|
+
} catch {
|
|
1702
|
+
}
|
|
1703
|
+
try {
|
|
1704
|
+
const res = await fetchFn(url, { signal: AbortSignal.timeout(4e3), redirect: "error" });
|
|
1705
|
+
if (!res.ok) return "";
|
|
1706
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
1707
|
+
if (bytes.length === 0 || bytes.length > PICTURE_MAX_BYTES) return "";
|
|
1708
|
+
if (!PNG_MAGIC.every((b, i) => bytes[i] === b)) return "";
|
|
1709
|
+
(0, import_node_fs9.mkdirSync)(dir, { recursive: true });
|
|
1710
|
+
(0, import_node_fs9.writeFileSync)(file, bytes);
|
|
1711
|
+
const old = (0, import_node_fs9.readdirSync)(dir).map((f) => ({ f, t: (0, import_node_fs9.statSync)((0, import_node_path10.join)(dir, f)).mtimeMs })).sort((a, b) => b.t - a.t).slice(PICTURES_KEPT);
|
|
1712
|
+
for (const o of old) (0, import_node_fs9.rmSync)((0, import_node_path10.join)(dir, o.f), { force: true });
|
|
1713
|
+
return file;
|
|
1714
|
+
} catch {
|
|
1715
|
+
return "";
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
// packages/core/src/daemon-main.ts
|
|
1720
|
+
async function main() {
|
|
1721
|
+
const env = process.env;
|
|
1722
|
+
const paths = avronPaths(env);
|
|
1723
|
+
const log = fileLogger(paths.daemonLog);
|
|
1724
|
+
process.on("uncaughtException", (err) => log.error("uncaught exception", err));
|
|
1725
|
+
process.on("unhandledRejection", (err) => log.error("unhandled rejection", err));
|
|
1726
|
+
try {
|
|
1727
|
+
process.chdir((0, import_node_os3.homedir)());
|
|
1728
|
+
} catch {
|
|
1729
|
+
}
|
|
1730
|
+
const entry = process.argv[1];
|
|
1731
|
+
if (process.platform === "win32" && entry && !process.argv.includes(CLEAN_FLAG)) {
|
|
1732
|
+
if (await isAlive(ipcEndpoint(env))) process.exit(0);
|
|
1733
|
+
if (await relaunchWithoutInheritedHandles(entry, env)) process.exit(0);
|
|
1734
|
+
log.error("could not restart without inherited handles; running in this process instead");
|
|
1735
|
+
}
|
|
1736
|
+
const store = new ManifestStore(env, log);
|
|
1737
|
+
const ledger = new Ledger(paths, log);
|
|
1738
|
+
const config = liveConfig(env);
|
|
1739
|
+
const identity = loadIdentity(paths);
|
|
1740
|
+
const pidFile = (0, import_node_path11.join)(paths.runDir, "daemon.pid");
|
|
1741
|
+
const lastShown = (0, import_node_path11.join)(paths.runDir, "last-shown.json");
|
|
1742
|
+
const posterViews = (0, import_node_path11.join)((0, import_node_path11.dirname)(paths.ledgerSnapshot), "poster-views.json");
|
|
1743
|
+
let toasts = { day: "", shown: 0, last: 0 };
|
|
1744
|
+
let posters = readPosters(posterViews);
|
|
1745
|
+
const rotation = new Rotation(() => store.current(), {
|
|
1746
|
+
env,
|
|
1747
|
+
installRef: () => identity?.ref ?? null,
|
|
1748
|
+
statePath: (0, import_node_path11.join)((0, import_node_path11.dirname)(paths.ledgerSnapshot), "rotation.json")
|
|
1749
|
+
});
|
|
1750
|
+
const res = await startDaemon({
|
|
1751
|
+
env,
|
|
1752
|
+
logger: log,
|
|
1753
|
+
campaigns: rotation,
|
|
1754
|
+
sink: ledger,
|
|
1755
|
+
mode: () => config().mode,
|
|
1756
|
+
enabled: () => store.current().enabled && !config().paused,
|
|
1757
|
+
formats: () => config().formats,
|
|
1758
|
+
todayTurns: () => {
|
|
1759
|
+
const t = ledger.totals().today;
|
|
1760
|
+
return t.date === (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) ? t.validTurns : 0;
|
|
1761
|
+
},
|
|
1762
|
+
onToast: (c) => {
|
|
1763
|
+
if (env.AVRON_NO_TOAST === "1") return false;
|
|
1764
|
+
const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1765
|
+
if (toasts.day !== day) toasts = { day, shown: 0, last: 0 };
|
|
1766
|
+
const now = Date.now();
|
|
1767
|
+
if (toasts.shown >= TOASTS_PER_DAY || now - toasts.last < TOAST_GAP_MS) return false;
|
|
1768
|
+
toasts.shown += 1;
|
|
1769
|
+
toasts.last = now;
|
|
1770
|
+
const dir = (0, import_node_path11.join)(paths.runDir, "toast-pictures");
|
|
1771
|
+
void Promise.all([cachePicture(c.logoUrl, dir), cachePicture(c.imageUrl, dir)]).then(
|
|
1772
|
+
([image, hero]) => showToast({ ...toastFor(c), ...image ? { image } : {}, ...hero ? { hero } : {} })
|
|
1773
|
+
).then((ok) => {
|
|
1774
|
+
if (!ok) log.error("could not show a notification");
|
|
1775
|
+
});
|
|
1776
|
+
return true;
|
|
1777
|
+
},
|
|
1778
|
+
onPoster: (c) => {
|
|
1779
|
+
const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1780
|
+
if (posters.day !== day) posters = { day, byCampaign: {} };
|
|
1781
|
+
posters.byCampaign[c.campaignId] = (posters.byCampaign[c.campaignId] ?? 0) + 1;
|
|
1782
|
+
void (0, import_promises2.writeFile)(posterViews, JSON.stringify(posters)).catch(
|
|
1783
|
+
(err) => log.error("cannot write poster-views.json", err)
|
|
1784
|
+
);
|
|
1785
|
+
},
|
|
1786
|
+
onServe: (c) => {
|
|
1787
|
+
void (0, import_promises2.writeFile)(
|
|
1788
|
+
lastShown,
|
|
1789
|
+
JSON.stringify({
|
|
1790
|
+
campaignId: c.campaignId,
|
|
1791
|
+
sponsorName: c.sponsorName,
|
|
1792
|
+
actionUrl: c.actionUrl,
|
|
1793
|
+
promoCode: c.promoCode
|
|
1794
|
+
})
|
|
1795
|
+
).catch((err) => log.error("cannot write last-shown.json", err));
|
|
1796
|
+
},
|
|
1797
|
+
flush: () => {
|
|
1798
|
+
rotation.flush();
|
|
1799
|
+
return ledger.flush();
|
|
1800
|
+
},
|
|
1801
|
+
onExit: () => {
|
|
1802
|
+
rotation.flush();
|
|
1803
|
+
(0, import_node_fs10.rmSync)(pidFile, { force: true });
|
|
1804
|
+
void ledger.flush().finally(() => process.exit(0));
|
|
1805
|
+
}
|
|
1806
|
+
});
|
|
1807
|
+
if (!res.started) {
|
|
1808
|
+
process.exit(0);
|
|
1809
|
+
}
|
|
1810
|
+
try {
|
|
1811
|
+
(0, import_node_fs10.writeFileSync)(pidFile, String(process.pid));
|
|
1812
|
+
} catch (err) {
|
|
1813
|
+
log.error("cannot write pid file", err);
|
|
1814
|
+
}
|
|
1815
|
+
const first = env[FIRST_MESSAGE_ENV];
|
|
1816
|
+
delete env[FIRST_MESSAGE_ENV];
|
|
1817
|
+
const firstMsg = first ? parseAdapterMessage(first) : null;
|
|
1818
|
+
if (firstMsg) void send(firstMsg, { endpoint: ipcEndpoint(env) });
|
|
1819
|
+
if (env.AVRON_OFFLINE !== "1") {
|
|
1820
|
+
const sync = () => void syncManifest(env, paths, store, log);
|
|
1821
|
+
const flush = () => void ledger.flush().then(() => flushBatches(env, paths, store, log));
|
|
1822
|
+
setTimeout(sync, 3e3 + Math.random() * 7e3).unref();
|
|
1823
|
+
setInterval(sync, MANIFEST_SYNC_INTERVAL_MS).unref();
|
|
1824
|
+
setTimeout(flush, 5 * 6e4).unref();
|
|
1825
|
+
setInterval(flush, BATCH_FLUSH_INTERVAL_MS).unref();
|
|
1826
|
+
}
|
|
1827
|
+
const stop = () => {
|
|
1828
|
+
rotation.flush();
|
|
1829
|
+
(0, import_node_fs10.rmSync)(pidFile, { force: true });
|
|
1830
|
+
void res.daemon.close().then(() => ledger.flush()).finally(() => process.exit(0));
|
|
1831
|
+
};
|
|
1832
|
+
process.on("SIGTERM", stop);
|
|
1833
|
+
process.on("SIGINT", stop);
|
|
1834
|
+
}
|
|
1835
|
+
void main();
|
|
1836
|
+
var TOASTS_PER_DAY = 8;
|
|
1837
|
+
var TOAST_GAP_MS = 20 * 6e4;
|
|
1838
|
+
function readPosters(file) {
|
|
1839
|
+
try {
|
|
1840
|
+
const v = JSON.parse((0, import_node_fs10.readFileSync)(file, "utf8"));
|
|
1841
|
+
if (typeof v.day === "string" && typeof v.byCampaign === "object" && v.byCampaign !== null)
|
|
1842
|
+
return { day: v.day, byCampaign: v.byCampaign };
|
|
1843
|
+
} catch {
|
|
1844
|
+
}
|
|
1845
|
+
return { day: "", byCampaign: {} };
|
|
1846
|
+
}
|