cdpm-mcp 0.0.0-stage → 0.1.0
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/CHANGELOG.md +33 -0
- package/LICENSE +21 -0
- package/README.ko.md +245 -0
- package/README.md +167 -2
- package/dist/agent-setup.js +134 -0
- package/dist/auto-setup.js +110 -0
- package/dist/cdp/client.js +127 -0
- package/dist/cdp/downloads.js +69 -0
- package/dist/cdp/network.js +118 -0
- package/dist/cdp/sessions.js +519 -0
- package/dist/cdp/targets.js +43 -0
- package/dist/chrome/finder.js +87 -0
- package/dist/chrome/launcher.js +52 -0
- package/dist/chrome/proxy.js +109 -0
- package/dist/claude-md-setup.js +68 -0
- package/dist/cli.js +230 -0
- package/dist/errors.js +3 -0
- package/dist/index.js +26 -0
- package/dist/install.js +34 -0
- package/dist/page/actions.js +1101 -0
- package/dist/page/keys.js +115 -0
- package/dist/page/snapshot.js +283 -0
- package/dist/paths.js +43 -0
- package/dist/pause.js +74 -0
- package/dist/proxy-forwarder.js +191 -0
- package/dist/registry/lock.js +93 -0
- package/dist/registry/messages.js +106 -0
- package/dist/registry/store.js +27 -0
- package/dist/service.js +340 -0
- package/dist/slots.js +72 -0
- package/dist/statusline-setup.js +142 -0
- package/dist/statusline.js +82 -0
- package/dist/taskbar/dock.js +94 -0
- package/dist/taskbar/icon-gdi.js +191 -0
- package/dist/taskbar/icon.js +300 -0
- package/dist/taskbar/watcher.js +65 -0
- package/dist/taskbar/win32.js +135 -0
- package/dist/tools/format.js +48 -0
- package/dist/tools/read.js +81 -0
- package/dist/tools/register.js +907 -0
- package/dist/util.js +111 -0
- package/dist/version.js +3 -0
- package/package.json +62 -4
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// 슬롯 하나 전용 프록시 중계 프로그램 (src/chrome/proxy.ts가 띄운다).
|
|
2
|
+
// Chrome은 아이디·비밀번호가 있는 프록시를 플래그로 받지 못하므로, Chrome은 인증 없이 여기(127.0.0.1)로 보내고
|
|
3
|
+
// 여기서 원래 프록시(http/https/socks5)에 인증을 붙여 넘긴다. 그 슬롯 Chrome이 꺼지면 스스로 끝난다.
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import tls from 'node:tls';
|
|
7
|
+
const up = JSON.parse(process.env.CDPM_PROXY_UPSTREAM ?? '{}');
|
|
8
|
+
const cdpPort = Number(process.env.CDPM_PROXY_CDP_PORT);
|
|
9
|
+
const basic = up.user !== undefined ? 'Basic ' + Buffer.from(`${up.user}:${up.pass ?? ''}`).toString('base64') : undefined;
|
|
10
|
+
function connectUpstream() {
|
|
11
|
+
const host = up.host.replace(/^\[|\]$/g, ''); // IPv6는 [::1]처럼 대괄호로 온다
|
|
12
|
+
return up.scheme === 'https'
|
|
13
|
+
? tls.connect({ host, port: up.port, servername: net.isIP(host) ? undefined : host })
|
|
14
|
+
: net.connect({ host, port: up.port });
|
|
15
|
+
}
|
|
16
|
+
/** 원래 프록시를 거쳐 host:port로 가는 연결(터널)을 만든다. */
|
|
17
|
+
function tunnel(host, port) {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
const s = connectUpstream();
|
|
20
|
+
const fail = (e) => { s.destroy(); reject(e); };
|
|
21
|
+
s.once('error', fail);
|
|
22
|
+
s.setTimeout(20_000, () => fail(new Error('프록시 응답 없음')));
|
|
23
|
+
const ready = () => { s.setTimeout(0); s.removeListener('error', fail); resolve(s); };
|
|
24
|
+
s.once(up.scheme === 'https' ? 'secureConnect' : 'connect', () => {
|
|
25
|
+
if (up.scheme === 'socks5')
|
|
26
|
+
return socks5(s, host, port).then(ready, fail);
|
|
27
|
+
s.write(`CONNECT ${host}:${port} HTTP/1.1\r\nHost: ${host}:${port}\r\n${basic ? `Proxy-Authorization: ${basic}\r\n` : ''}\r\n`);
|
|
28
|
+
let buf = Buffer.alloc(0);
|
|
29
|
+
const onData = (d) => {
|
|
30
|
+
buf = Buffer.concat([buf, d]);
|
|
31
|
+
const end = buf.indexOf('\r\n\r\n');
|
|
32
|
+
if (end < 0)
|
|
33
|
+
return;
|
|
34
|
+
s.removeListener('data', onData);
|
|
35
|
+
s.pause(); // 다 읽은 뒤 멈춰 둬야, 이어서 온 데이터가 읽는 쪽이 붙기 전에 버려지지 않는다
|
|
36
|
+
const status = /^HTTP\/1\.[01] (\d{3})/.exec(buf.toString('latin1'))?.[1];
|
|
37
|
+
if (status !== '200')
|
|
38
|
+
return fail(new Error(`프록시가 연결을 거절했어요 (HTTP ${status ?? '?'})`));
|
|
39
|
+
const rest = buf.subarray(end + 4);
|
|
40
|
+
if (rest.length)
|
|
41
|
+
s.unshift(rest);
|
|
42
|
+
ready();
|
|
43
|
+
};
|
|
44
|
+
s.on('data', onData);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function readBytes(s, n) {
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
let buf = Buffer.alloc(0);
|
|
51
|
+
const onData = (d) => {
|
|
52
|
+
buf = Buffer.concat([buf, d]);
|
|
53
|
+
if (buf.length < n)
|
|
54
|
+
return;
|
|
55
|
+
s.removeListener('data', onData);
|
|
56
|
+
s.removeListener('close', onClose);
|
|
57
|
+
s.pause();
|
|
58
|
+
if (buf.length > n)
|
|
59
|
+
s.unshift(buf.subarray(n));
|
|
60
|
+
resolve(buf.subarray(0, n));
|
|
61
|
+
};
|
|
62
|
+
const onClose = () => reject(new Error('프록시가 연결을 끊었어요'));
|
|
63
|
+
s.on('data', onData);
|
|
64
|
+
s.once('close', onClose);
|
|
65
|
+
s.resume(); // 앞에서 멈춰 둔 소켓은 data 리스너만으로는 다시 흐르지 않는다
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
async function socks5(s, host, port) {
|
|
69
|
+
s.write(Buffer.from(basic ? [5, 2, 0, 2] : [5, 1, 0]));
|
|
70
|
+
const [, method] = await readBytes(s, 2);
|
|
71
|
+
if (method === 2) {
|
|
72
|
+
const u = Buffer.from(up.user ?? ''), p = Buffer.from(up.pass ?? '');
|
|
73
|
+
s.write(Buffer.concat([Buffer.from([1, u.length]), u, Buffer.from([p.length]), p]));
|
|
74
|
+
const [, ok] = await readBytes(s, 2);
|
|
75
|
+
if (ok !== 0)
|
|
76
|
+
throw new Error('socks5 프록시가 아이디·비밀번호를 거절했어요');
|
|
77
|
+
}
|
|
78
|
+
else if (method !== 0)
|
|
79
|
+
throw new Error('socks5 프록시가 인증 방식을 받지 않았어요');
|
|
80
|
+
// 주소 이름을 그대로 넘겨 DNS도 프록시 쪽에서 풀게 한다 (이 PC의 DNS로 새지 않게)
|
|
81
|
+
const h = host.replace(/^\[|\]$/g, '');
|
|
82
|
+
const ipType = net.isIP(h);
|
|
83
|
+
const addr = ipType === 4 ? Buffer.from([1, ...h.split('.').map(Number)])
|
|
84
|
+
: ipType === 6 ? Buffer.concat([Buffer.from([4]), ipv6Bytes(h)])
|
|
85
|
+
: Buffer.concat([Buffer.from([3, Buffer.byteLength(h)]), Buffer.from(h)]);
|
|
86
|
+
s.write(Buffer.concat([Buffer.from([5, 1, 0]), addr, Buffer.from([port >> 8, port & 255])]));
|
|
87
|
+
const head = await readBytes(s, 4);
|
|
88
|
+
if (head[1] !== 0)
|
|
89
|
+
throw new Error(`socks5 프록시가 연결을 거절했어요 (코드 ${head[1]})`);
|
|
90
|
+
const len = head[3] === 1 ? 4 : head[3] === 4 ? 16 : (await readBytes(s, 1))[0];
|
|
91
|
+
await readBytes(s, len + 2);
|
|
92
|
+
}
|
|
93
|
+
function ipv6Bytes(ip) {
|
|
94
|
+
const [a, b = ''] = ip.split('::');
|
|
95
|
+
const hs = (x) => (x ? x.split(':') : []);
|
|
96
|
+
const left = hs(a), right = hs(b);
|
|
97
|
+
const all = [...left, ...Array(8 - left.length - right.length).fill('0'), ...right];
|
|
98
|
+
return Buffer.from(all.flatMap((g) => { const n = parseInt(g, 16); return [n >> 8, n & 255]; }));
|
|
99
|
+
}
|
|
100
|
+
function splitHostPort(v, def) {
|
|
101
|
+
const m = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(v);
|
|
102
|
+
return m ? [m[1], Number(m[2] ?? def)] : [v, def];
|
|
103
|
+
}
|
|
104
|
+
const server = http.createServer((req, res) => {
|
|
105
|
+
// https가 아닌 일반 http 요청 (Chrome은 전체 주소를 보낸다)
|
|
106
|
+
let target;
|
|
107
|
+
try {
|
|
108
|
+
target = new URL(req.url ?? '');
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
res.writeHead(400).end();
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const headers = { ...req.headers };
|
|
115
|
+
delete headers['proxy-connection'];
|
|
116
|
+
const done = (e) => { if (!res.headersSent)
|
|
117
|
+
res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }); res.end(`CDPM 프록시 중계 오류: ${e.message}`); };
|
|
118
|
+
if (up.scheme === 'socks5') {
|
|
119
|
+
const port = Number(target.port || 80);
|
|
120
|
+
tunnel(target.hostname, port).then((sock) => {
|
|
121
|
+
sock.resume(); // 터널을 만들며 멈춰 둔 소켓 (http 요청은 스스로 다시 켜지 않는다)
|
|
122
|
+
const r = http.request({ method: req.method, path: target.pathname + target.search, headers, createConnection: () => sock });
|
|
123
|
+
r.on('response', (pr) => { res.writeHead(pr.statusCode ?? 502, pr.headers); pr.pipe(res); });
|
|
124
|
+
r.on('error', done);
|
|
125
|
+
req.pipe(r);
|
|
126
|
+
}, done);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const out = http.request({
|
|
130
|
+
method: req.method, path: req.url, headers: { ...headers, ...(basic ? { 'proxy-authorization': basic } : {}) },
|
|
131
|
+
createConnection: () => connectUpstream(), // 원래 프록시로 (https 프록시면 TLS, IPv6 대괄호 처리 포함)
|
|
132
|
+
});
|
|
133
|
+
out.on('response', (pr) => { res.writeHead(pr.statusCode ?? 502, pr.headers); pr.pipe(res); });
|
|
134
|
+
out.on('error', done);
|
|
135
|
+
req.pipe(out);
|
|
136
|
+
});
|
|
137
|
+
server.on('connect', (req, client, head) => {
|
|
138
|
+
const [host, port] = splitHostPort(req.url ?? '', 443);
|
|
139
|
+
client.on('error', () => undefined);
|
|
140
|
+
tunnel(host, port).then((remote) => {
|
|
141
|
+
client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
142
|
+
if (head?.length)
|
|
143
|
+
remote.write(head);
|
|
144
|
+
remote.on('error', () => client.destroy());
|
|
145
|
+
client.on('close', () => remote.destroy());
|
|
146
|
+
remote.on('close', () => client.destroy());
|
|
147
|
+
remote.pipe(client);
|
|
148
|
+
client.pipe(remote);
|
|
149
|
+
}, (e) => {
|
|
150
|
+
client.end(`HTTP/1.1 502 Bad Gateway\r\ncontent-type: text/plain; charset=utf-8\r\n\r\nCDPM 프록시 중계 오류: ${e.message}`);
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
/** 그 슬롯 포트에 떠 있는 Chrome의 고유 주소 (Chrome마다 다름). 응답이 없으면 undefined. */
|
|
154
|
+
function chromeId() {
|
|
155
|
+
return new Promise((resolve) => {
|
|
156
|
+
const r = http.get({ host: '127.0.0.1', port: cdpPort, path: '/json/version', timeout: 2000 }, (res) => {
|
|
157
|
+
let b = '';
|
|
158
|
+
res.on('data', (d) => (b += d));
|
|
159
|
+
res.on('end', () => { try {
|
|
160
|
+
resolve(JSON.parse(b).webSocketDebuggerUrl);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
resolve(undefined);
|
|
164
|
+
} });
|
|
165
|
+
});
|
|
166
|
+
r.on('error', () => resolve(undefined));
|
|
167
|
+
r.on('timeout', () => { r.destroy(); resolve(undefined); });
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
server.listen(0, '127.0.0.1', () => {
|
|
171
|
+
const addr = server.address();
|
|
172
|
+
process.stdout.write(`LISTEN ${addr.port}\n`);
|
|
173
|
+
// Chrome이 뜨기를 1분까지 기다린다. 뜬 뒤에는 그 Chrome이 꺼지거나(두 번 연속 응답 없음)
|
|
174
|
+
// 같은 포트에 다른 Chrome이 뜨면(슬롯을 끄고 다시 켬) 끝난다.
|
|
175
|
+
const started = Date.now();
|
|
176
|
+
let mine, misses = 0;
|
|
177
|
+
const check = async () => {
|
|
178
|
+
const id = await chromeId();
|
|
179
|
+
if (id && !mine)
|
|
180
|
+
mine = id;
|
|
181
|
+
if (id && mine && id !== mine)
|
|
182
|
+
process.exit(0);
|
|
183
|
+
if (!id && (mine ? ++misses >= 2 : Date.now() - started > 60_000))
|
|
184
|
+
process.exit(0);
|
|
185
|
+
if (id)
|
|
186
|
+
misses = 0;
|
|
187
|
+
// 내 Chrome을 알아보기 전에는 자주 본다 (금방 꺼지는 Chrome도 놓치지 않게)
|
|
188
|
+
setTimeout(check, mine ? 2000 : 300);
|
|
189
|
+
};
|
|
190
|
+
setTimeout(check, 300);
|
|
191
|
+
});
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { paths } from '../paths.js';
|
|
4
|
+
import { pidAlive, sleep } from '../util.js';
|
|
5
|
+
const RETRY_MS = 30;
|
|
6
|
+
/** 잠금 파일을 만든 직후 PID를 쓰기 전의 아주 짧은 순간만 봐주는 시간 (PID 확인이 불가능할 때만 쓰임) */
|
|
7
|
+
const UNREADABLE_GRACE_MS = 5000;
|
|
8
|
+
export class LockTimeoutError extends Error {
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* 프로세스 간 잠금. 잠금 파일을 'wx'로 만들 수 있으면 잡은 것. 파일에는 잡은 프로세스의 PID를 적는다.
|
|
12
|
+
* 잠금이 남아 있어도 시간으로 판단하지 않고, 그 PID의 프로세스가 실제로 죽었을 때만 풀어 준다
|
|
13
|
+
* (느린 프로세스의 잠금을 뺏어 기록이 깨지는 일이 없게).
|
|
14
|
+
*/
|
|
15
|
+
export async function withLock(fn, timeoutMs = 10_000) {
|
|
16
|
+
return withFileLock(paths.lock(), fn, timeoutMs, '저장소 잠금을 얻지 못했어요 (다른 프로세스가 오래 쓰는 중).');
|
|
17
|
+
}
|
|
18
|
+
/** 같은 방식의 잠금을 원하는 파일로 (예: 탭 하나를 여러 Claude 세션이 동시에 조작하지 않게). */
|
|
19
|
+
export async function withFileLock(lockPath, fn, timeoutMs, timeoutMessage) {
|
|
20
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
21
|
+
const deadline = Date.now() + timeoutMs;
|
|
22
|
+
for (;;) {
|
|
23
|
+
try {
|
|
24
|
+
const fd = fs.openSync(lockPath, 'wx');
|
|
25
|
+
fs.writeSync(fd, String(process.pid));
|
|
26
|
+
fs.closeSync(fd);
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
// Windows는 다른 프로세스가 잠금 파일을 지우는 중이면 EEXIST 대신 EPERM/EACCES/EBUSY를 낸다.
|
|
31
|
+
const code = e.code;
|
|
32
|
+
if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY')
|
|
33
|
+
throw e;
|
|
34
|
+
removeIfOwnerDead(lockPath);
|
|
35
|
+
if (Date.now() > deadline)
|
|
36
|
+
throw new LockTimeoutError(timeoutMessage);
|
|
37
|
+
await sleep(RETRY_MS + Math.random() * RETRY_MS);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
return await fn();
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
try {
|
|
45
|
+
// 내 잠금일 때만 지운다
|
|
46
|
+
if (fs.readFileSync(lockPath, 'utf8') === String(process.pid))
|
|
47
|
+
fs.unlinkSync(lockPath);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// 이미 정리됨
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function removeIfOwnerDead(lockPath) {
|
|
55
|
+
try {
|
|
56
|
+
const owner = Number(fs.readFileSync(lockPath, 'utf8'));
|
|
57
|
+
if (owner > 0) {
|
|
58
|
+
if (!pidAlive(owner))
|
|
59
|
+
fs.unlinkSync(lockPath);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
// PID를 아직 못 읽음 (방금 만들어진 파일이거나 깨진 파일): 깨진 파일만 오래되면 정리
|
|
63
|
+
if (Date.now() - fs.statSync(lockPath).mtimeMs > UNREADABLE_GRACE_MS)
|
|
64
|
+
fs.unlinkSync(lockPath);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// 그 사이 풀렸으면 무시
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** 임시 파일에 쓰고 rename으로 교체. Windows에서 다른 프로세스가 읽는 중이면 잠깐 실패할 수 있어 재시도한다. */
|
|
71
|
+
export function writeFileAtomic(file, data) {
|
|
72
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
73
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
74
|
+
fs.writeFileSync(tmp, data);
|
|
75
|
+
for (let i = 0;; i++) {
|
|
76
|
+
try {
|
|
77
|
+
fs.renameSync(tmp, file);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
const code = e.code;
|
|
82
|
+
if (i >= 50 || (code !== 'EPERM' && code !== 'EBUSY' && code !== 'EACCES')) {
|
|
83
|
+
try {
|
|
84
|
+
fs.unlinkSync(tmp);
|
|
85
|
+
}
|
|
86
|
+
catch { /* 무시 */ }
|
|
87
|
+
throw e;
|
|
88
|
+
}
|
|
89
|
+
const until = Date.now() + 10;
|
|
90
|
+
while (Date.now() < until) { /* 짧게 대기 */ }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { paths } from '../paths.js';
|
|
4
|
+
import { nowIso, sleep } from '../util.js';
|
|
5
|
+
import { withLock, writeFileAtomic } from './lock.js';
|
|
6
|
+
const MAX_LINES = 1000;
|
|
7
|
+
const KEEP_LINES = 500;
|
|
8
|
+
const FIRST_VISIT_BACKLOG = 20;
|
|
9
|
+
function readAll(slot) {
|
|
10
|
+
let raw;
|
|
11
|
+
try {
|
|
12
|
+
raw = fs.readFileSync(paths.messages(slot), 'utf8');
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return [];
|
|
16
|
+
}
|
|
17
|
+
const out = [];
|
|
18
|
+
for (const line of raw.split('\n')) {
|
|
19
|
+
if (!line.trim())
|
|
20
|
+
continue;
|
|
21
|
+
try {
|
|
22
|
+
out.push(JSON.parse(line));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// 깨진 줄은 건너뜀
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
function readCursors(slot) {
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(fs.readFileSync(paths.cursors(slot), 'utf8'));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return {};
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export async function sendMessage(slot, from, text, to) {
|
|
39
|
+
return withLock(() => {
|
|
40
|
+
const all = readAll(slot);
|
|
41
|
+
const msg = { seq: (all.at(-1)?.seq ?? 0) + 1, at: nowIso(), from, to, text };
|
|
42
|
+
const file = paths.messages(slot);
|
|
43
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
44
|
+
if (all.length + 1 > MAX_LINES) {
|
|
45
|
+
const kept = [...all.slice(-(KEEP_LINES - 1)), msg];
|
|
46
|
+
writeFileAtomic(file, kept.map((m) => JSON.stringify(m)).join('\n') + '\n');
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
fs.appendFileSync(file, JSON.stringify(msg) + '\n');
|
|
50
|
+
}
|
|
51
|
+
return msg;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function visibleTo(agent, m) {
|
|
55
|
+
return m.from !== agent && (m.to === null || m.to === agent);
|
|
56
|
+
}
|
|
57
|
+
/** 안 읽은 메시지를 가져오고 읽음 처리한다. */
|
|
58
|
+
export async function takeUnread(slot, agent) {
|
|
59
|
+
const all = readAll(slot);
|
|
60
|
+
const cursors = readCursors(slot);
|
|
61
|
+
const lastSeq = all.at(-1)?.seq ?? 0;
|
|
62
|
+
const cursor = cursors[agent];
|
|
63
|
+
let unread;
|
|
64
|
+
if (cursor === undefined) {
|
|
65
|
+
unread = all.filter((m) => visibleTo(agent, m)).slice(-FIRST_VISIT_BACKLOG);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
unread = all.filter((m) => m.seq > cursor && visibleTo(agent, m));
|
|
69
|
+
}
|
|
70
|
+
if (cursor !== lastSeq) {
|
|
71
|
+
await withLock(() => {
|
|
72
|
+
const c = readCursors(slot);
|
|
73
|
+
c[agent] = Math.max(c[agent] ?? 0, lastSeq);
|
|
74
|
+
// 에이전트 이름이 계속 늘어나도 파일이 커지지 않게, 가장 오래 안 읽은 이름부터 지운다.
|
|
75
|
+
const names = Object.keys(c);
|
|
76
|
+
if (names.length > 200)
|
|
77
|
+
names.sort((a, b) => c[a] - c[b]).slice(0, names.length - 200).forEach((n) => delete c[n]);
|
|
78
|
+
writeFileAtomic(paths.cursors(slot), JSON.stringify(c, null, 2));
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return unread;
|
|
82
|
+
}
|
|
83
|
+
/** 읽음 처리하지 않고, 이 에이전트에게 새 메시지가 왔는지만 본다 (기다리는 도중 바로 멈추기 위해). */
|
|
84
|
+
export function hasUnread(slot, agent) {
|
|
85
|
+
const cursor = readCursors(slot)[agent];
|
|
86
|
+
const since = Date.now() - 60_000;
|
|
87
|
+
return readAll(slot).some((m) => visibleTo(agent, m) && (cursor === undefined ? Date.parse(m.at) >= since : m.seq > cursor));
|
|
88
|
+
}
|
|
89
|
+
/** 안 읽은 메시지가 생길 때까지 최대 waitSec초 기다린다. */
|
|
90
|
+
export async function waitUnread(slot, agent, waitSec) {
|
|
91
|
+
const deadline = Date.now() + waitSec * 1000;
|
|
92
|
+
for (;;) {
|
|
93
|
+
const got = await takeUnread(slot, agent);
|
|
94
|
+
if (got.length || Date.now() >= deadline)
|
|
95
|
+
return got;
|
|
96
|
+
await sleep(100); // 메시지가 오면 0.1초 안에 알아챈다
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** 이미 읽음 처리된(머리말로 전달된) 최근 메시지. inbox에 새 메시지가 없을 때 참고로 보여준다. */
|
|
100
|
+
export function recentDelivered(slot, agent, max = 5, withinSec = 600) {
|
|
101
|
+
const cursor = readCursors(slot)[agent] ?? 0;
|
|
102
|
+
const since = Date.now() - withinSec * 1000;
|
|
103
|
+
return readAll(slot)
|
|
104
|
+
.filter((m) => m.seq <= cursor && visibleTo(agent, m) && Date.parse(m.at) >= since)
|
|
105
|
+
.slice(-max);
|
|
106
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { paths } from '../paths.js';
|
|
3
|
+
import { withLock, writeFileAtomic } from './lock.js';
|
|
4
|
+
const empty = () => ({ version: 1, slots: {} });
|
|
5
|
+
export function readRegistry() {
|
|
6
|
+
try {
|
|
7
|
+
const r = JSON.parse(fs.readFileSync(paths.registry(), 'utf8'));
|
|
8
|
+
if (r && r.version === 1 && r.slots)
|
|
9
|
+
return r;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
// 없거나 깨졌으면 빈 저장소
|
|
13
|
+
}
|
|
14
|
+
return empty();
|
|
15
|
+
}
|
|
16
|
+
/** 잠금을 잡고 읽고-고치고-쓴다. mutator의 반환값을 돌려준다. */
|
|
17
|
+
export async function updateRegistry(mutator) {
|
|
18
|
+
return withLock(() => {
|
|
19
|
+
const r = readRegistry();
|
|
20
|
+
const result = mutator(r);
|
|
21
|
+
writeFileAtomic(paths.registry(), JSON.stringify(r, null, 2));
|
|
22
|
+
return result;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export function newSlotRecord(launchedBy, at, pid) {
|
|
26
|
+
return { pid, launchedBy, launchedAt: at, nextTabSeq: 1, tabs: {} };
|
|
27
|
+
}
|