tr-ai-intercom-helper 0.0.0-stage → 1.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.
@@ -0,0 +1,165 @@
1
+ import { chmod, lstat, mkdir, unlink } from 'node:fs/promises';
2
+ import net from 'node:net';
3
+ import path from 'node:path';
4
+ /**
5
+ * The notification listener: a local (Unix domain) socket of the helper's
6
+ * own, on which every program that connects is sent each notification as one
7
+ * line of JSON. It is the opposite of the local-socket delivery method, where
8
+ * the helper connects out to a socket somebody else listens on.
9
+ *
10
+ * Unless a path is given, the socket is
11
+ * /tmp/tr-ai-intercom-helper.<uid>/<port>.sock, with <port> the local port
12
+ * the helper listens on, so that a client finds it from the port alone.
13
+ */
14
+ /** The longest socket path every supported system accepts. */
15
+ const MAX_PATH_BYTES = 103;
16
+ /** The user's own directory for listener sockets. Undefined where there are no user ids. */
17
+ export function listenerDirectory() {
18
+ const uid = process.getuid?.();
19
+ return uid === undefined ? undefined : `/tmp/tr-ai-intercom-helper.${uid}`;
20
+ }
21
+ /** The default socket path of the helper that listens on `port`. */
22
+ export function defaultListenerPath(port) {
23
+ const dir = listenerDirectory();
24
+ if (!dir) {
25
+ throw new Error('This system has no default place for the notification listener. Give the socket path explicitly.');
26
+ }
27
+ return path.join(dir, `${port}.sock`);
28
+ }
29
+ /**
30
+ * Make sure a directory in /tmp is really the user's own. /tmp is shared, so
31
+ * somebody else may have created a directory of that name first, to read or
32
+ * to fake what goes through it.
33
+ */
34
+ export async function checkOwnDirectory(dir) {
35
+ const info = await lstat(dir);
36
+ const problem = !info.isDirectory()
37
+ ? 'is not a directory'
38
+ : info.uid !== process.getuid?.()
39
+ ? 'belongs to another user'
40
+ : (info.mode & 0o077) !== 0
41
+ ? 'is open to other users'
42
+ : undefined;
43
+ if (problem) {
44
+ throw new Error(`${dir} ${problem}, so it cannot be trusted. Remove it, or use a socket path of your own instead.`);
45
+ }
46
+ }
47
+ function assertUsablePath(socketPath) {
48
+ if (Buffer.byteLength(socketPath) > MAX_PATH_BYTES) {
49
+ throw new Error(`The socket path ${socketPath} is longer than ${MAX_PATH_BYTES} bytes, which a local socket cannot have.`);
50
+ }
51
+ }
52
+ /** True when something accepts connections on the socket. */
53
+ function answers(socketPath) {
54
+ return new Promise((resolve) => {
55
+ const probe = net.createConnection(socketPath);
56
+ const finish = (alive) => {
57
+ probe.destroy();
58
+ resolve(alive);
59
+ };
60
+ probe.setTimeout(1000, () => finish(false));
61
+ probe.on('connect', () => finish(true));
62
+ probe.on('error', () => finish(false));
63
+ });
64
+ }
65
+ /** A client that reads nothing gets this much buffered before it is dropped. */
66
+ const MAX_BUFFERED_BYTES = 1024 * 1024;
67
+ /**
68
+ * The delivery method behind --notification-listener. Each connected client
69
+ * gets every notification as one line of compact JSON. While nobody is
70
+ * connected the latest notification is kept and handed to the next client
71
+ * that connects, so that a program which reads one notification, acts, and
72
+ * connects again does not lose what came in between.
73
+ */
74
+ export function listenerSink(logger, configuredPath) {
75
+ const clients = new Set();
76
+ let server;
77
+ let socketPath;
78
+ /** The latest notification that no client received. */
79
+ let kept;
80
+ const send = (client, line) => {
81
+ if (client.writableLength > MAX_BUFFERED_BYTES) {
82
+ logger.warn('a notification listener client stopped reading and was dropped');
83
+ client.destroy();
84
+ return;
85
+ }
86
+ client.write(line);
87
+ };
88
+ return {
89
+ name: 'listener',
90
+ path: () => socketPath,
91
+ clientCount: () => clients.size,
92
+ async start({ port }) {
93
+ let target;
94
+ if (configuredPath) {
95
+ target = path.resolve(configuredPath);
96
+ }
97
+ else {
98
+ target = defaultListenerPath(port);
99
+ const dir = path.dirname(target);
100
+ await mkdir(dir, { mode: 0o700 }).catch((err) => {
101
+ if (err.code !== 'EEXIST')
102
+ throw err;
103
+ });
104
+ await checkOwnDirectory(dir);
105
+ }
106
+ assertUsablePath(target);
107
+ // A socket file left behind by a helper that did not stop cleanly.
108
+ const existing = await lstat(target).catch(() => undefined);
109
+ if (existing) {
110
+ if (!existing.isSocket()) {
111
+ throw new Error(`${target} exists and is not a socket. Remove it or use another path.`);
112
+ }
113
+ if (await answers(target)) {
114
+ throw new Error(`Another program is already listening on ${target}.`);
115
+ }
116
+ await unlink(target);
117
+ }
118
+ const created = net.createServer((client) => {
119
+ clients.add(client);
120
+ // Clients only listen; whatever they send is discarded.
121
+ client.resume();
122
+ client.on('error', () => undefined);
123
+ client.on('close', () => clients.delete(client));
124
+ if (kept !== undefined) {
125
+ send(client, kept);
126
+ kept = undefined;
127
+ }
128
+ });
129
+ await new Promise((resolve, reject) => {
130
+ created.once('error', reject);
131
+ created.listen(target, () => {
132
+ created.off('error', reject);
133
+ resolve();
134
+ });
135
+ });
136
+ await chmod(target, 0o600);
137
+ server = created;
138
+ socketPath = target;
139
+ },
140
+ async deliver(_notification, json) {
141
+ const line = `${json}\n`;
142
+ if (clients.size === 0) {
143
+ kept = line;
144
+ return;
145
+ }
146
+ for (const client of clients)
147
+ send(client, line);
148
+ },
149
+ stop() {
150
+ for (const client of clients)
151
+ client.destroy();
152
+ clients.clear();
153
+ server?.close();
154
+ server = undefined;
155
+ // Node removes the socket file on close; this covers the case where it did not.
156
+ if (socketPath)
157
+ void unlink(socketPath).catch(() => undefined);
158
+ },
159
+ };
160
+ }
161
+ /** The command line that connects to a listener, for the log and the documentation. */
162
+ export function notifyCommand(opts) {
163
+ const where = opts.path ? `--socket-path '${opts.path}'` : `--helper-port ${opts.port}`;
164
+ return `npx -y -p tr-ai-intercom-helper tr-ai-intercom-notify --monitor ${where}`;
165
+ }
@@ -0,0 +1,15 @@
1
+ declare const LEVELS: readonly ["debug", "info", "warn", "error", "silent"];
2
+ export type Level = (typeof LEVELS)[number];
3
+ export interface Logger {
4
+ debug(message: string, details?: Record<string, unknown>): void;
5
+ info(message: string, details?: Record<string, unknown>): void;
6
+ warn(message: string, details?: Record<string, unknown>): void;
7
+ error(message: string, details?: Record<string, unknown>): void;
8
+ }
9
+ /**
10
+ * A logger that writes JSON lines to standard error, so that standard output
11
+ * stays free. The agent's token never reaches it: nothing here logs headers.
12
+ */
13
+ export declare function createLogger(level: string, write?: (line: string) => void): Logger;
14
+ export declare const silentLogger: Logger;
15
+ export {};
package/dist/logger.js ADDED
@@ -0,0 +1,23 @@
1
+ const LEVELS = ['debug', 'info', 'warn', 'error', 'silent'];
2
+ function plain(value) {
3
+ if (value instanceof Error) {
4
+ const code = value.code;
5
+ return code === undefined ? value.message : `${value.message} (${String(code)})`;
6
+ }
7
+ return value;
8
+ }
9
+ /**
10
+ * A logger that writes JSON lines to standard error, so that standard output
11
+ * stays free. The agent's token never reaches it: nothing here logs headers.
12
+ */
13
+ export function createLogger(level, write = (line) => process.stderr.write(line)) {
14
+ const threshold = Math.max(0, LEVELS.indexOf(level));
15
+ const at = (name) => (message, details = {}) => {
16
+ if (LEVELS.indexOf(name) < threshold)
17
+ return;
18
+ const extra = Object.fromEntries(Object.entries(details).map(([k, v]) => [k, plain(v)]));
19
+ write(`${JSON.stringify({ time: new Date().toISOString(), level: name, msg: message, ...extra })}\n`);
20
+ };
21
+ return { debug: at('debug'), info: at('info'), warn: at('warn'), error: at('error') };
22
+ }
23
+ export const silentLogger = createLogger('silent');
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The client of the helper's notification listener: connects to the socket
3
+ * and prints each notification, one line of JSON, as it arrives. An agent
4
+ * runs it in the background to be woken by its output.
5
+ */
6
+ export interface NotifierOptions {
7
+ /** The socket to connect to. */
8
+ socketPath: string;
9
+ /** 'monitor' prints everything until stopped; 'oneshot' prints one line and ends. */
10
+ mode: 'monitor' | 'oneshot';
11
+ /** Monitor only: connect again, after a pause, whenever there is no connection. */
12
+ reconnect?: boolean;
13
+ /** The pause before connecting again. */
14
+ cooloffMs?: number;
15
+ /**
16
+ * Print a notification of the notifier's own, `local-idle-notification`, whenever nothing has
17
+ * been printed for this long. Undefined: never.
18
+ */
19
+ idleIntervalMs?: number | undefined;
20
+ /** Receives each complete line, newline included. */
21
+ out(line: string): void;
22
+ /** Receives remarks about the connection. */
23
+ err(message: string): void;
24
+ /** Ends the run; it then resolves with 0. */
25
+ signal?: AbortSignal;
26
+ }
27
+ export declare const DEFAULT_COOLOFF_MS = 5000;
28
+ /** The socket a notifier is pointed at: an explicit path, or the default for a helper's port. */
29
+ export declare function resolveSocketPath(where: {
30
+ port?: number | undefined;
31
+ path?: string | undefined;
32
+ }): Promise<string>;
33
+ /**
34
+ * Run the notifier. Resolves with the exit status: 0 when it ended as asked
35
+ * (one line printed in oneshot mode, or stopped), 1 when the connection could
36
+ * not be made or was lost and reconnecting was not asked for.
37
+ */
38
+ export declare function runNotifier(opts: NotifierOptions): Promise<number>;
@@ -0,0 +1,148 @@
1
+ import net from 'node:net';
2
+ import path from 'node:path';
3
+ import { checkOwnDirectory, defaultListenerPath, listenerDirectory } from './listener.js';
4
+ export const DEFAULT_COOLOFF_MS = 5000;
5
+ /** The socket a notifier is pointed at: an explicit path, or the default for a helper's port. */
6
+ export async function resolveSocketPath(where) {
7
+ if (where.path)
8
+ return path.resolve(where.path);
9
+ if (where.port === undefined)
10
+ throw new Error('Neither a port nor a socket path was given.');
11
+ const target = defaultListenerPath(where.port);
12
+ // Somebody else's directory under our name must not be listened to.
13
+ const dir = listenerDirectory();
14
+ if (dir) {
15
+ await checkOwnDirectory(dir).catch((err) => {
16
+ if (err.code !== 'ENOENT')
17
+ throw err;
18
+ });
19
+ }
20
+ return target;
21
+ }
22
+ /**
23
+ * Run the notifier. Resolves with the exit status: 0 when it ended as asked
24
+ * (one line printed in oneshot mode, or stopped), 1 when the connection could
25
+ * not be made or was lost and reconnecting was not asked for.
26
+ */
27
+ export function runNotifier(opts) {
28
+ const cooloff = opts.cooloffMs ?? DEFAULT_COOLOFF_MS;
29
+ const reconnect = opts.mode === 'monitor' && opts.reconnect === true;
30
+ return new Promise((resolve) => {
31
+ let socket;
32
+ let timer;
33
+ let idleTimer;
34
+ let done = false;
35
+ let complained = false;
36
+ /** The highest sequence number printed so far. */
37
+ let highest = 0;
38
+ /** When the last notification from the helper was printed; the start until then. */
39
+ let lastReal = Date.now();
40
+ const finish = (status) => {
41
+ if (done)
42
+ return;
43
+ done = true;
44
+ clearTimeout(timer);
45
+ clearTimeout(idleTimer);
46
+ opts.signal?.removeEventListener('abort', onAbort);
47
+ socket?.destroy();
48
+ resolve(status);
49
+ };
50
+ const onAbort = () => finish(0);
51
+ if (opts.signal?.aborted) {
52
+ resolve(0);
53
+ return;
54
+ }
55
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
56
+ /** Print a line; in oneshot mode that ends the run. Returns false when it did. */
57
+ const print = (line) => {
58
+ opts.out(line);
59
+ if (opts.mode === 'oneshot') {
60
+ finish(0);
61
+ return false;
62
+ }
63
+ armIdle();
64
+ return true;
65
+ };
66
+ /** Count the idle time from now: from the start, or from the line just printed. */
67
+ const armIdle = () => {
68
+ clearTimeout(idleTimer);
69
+ const interval = opts.idleIntervalMs;
70
+ if (interval === undefined || done)
71
+ return;
72
+ idleTimer = setTimeout(() => {
73
+ if (done)
74
+ return;
75
+ // Made here, not by the intercom: the time is this machine's, and the
76
+ // number is the latest one seen.
77
+ const idle = {
78
+ message: 'local-idle-notification',
79
+ seq: highest,
80
+ time: new Date().toISOString(),
81
+ // Whole seconds since the last notification from the helper, or
82
+ // since the notifier started when there has been none.
83
+ data: { idle: Math.round((Date.now() - lastReal) / 1000) },
84
+ };
85
+ print(`${JSON.stringify(idle)}\n`);
86
+ }, interval);
87
+ };
88
+ armIdle();
89
+ const connect = () => {
90
+ if (done)
91
+ return;
92
+ let pending = '';
93
+ let connected = false;
94
+ const current = net.createConnection(opts.socketPath);
95
+ socket = current;
96
+ current.setEncoding('utf8');
97
+ current.on('connect', () => {
98
+ connected = true;
99
+ if (complained)
100
+ opts.err(`Connected to ${opts.socketPath}.`);
101
+ complained = false;
102
+ });
103
+ current.on('data', (chunk) => {
104
+ pending += chunk;
105
+ for (;;) {
106
+ const at = pending.indexOf('\n');
107
+ if (at < 0)
108
+ break;
109
+ const line = pending.slice(0, at + 1);
110
+ pending = pending.slice(at + 1);
111
+ if (done)
112
+ return;
113
+ try {
114
+ const seq = JSON.parse(line).seq;
115
+ if (typeof seq === 'number' && seq > highest)
116
+ highest = seq;
117
+ }
118
+ catch {
119
+ // Not ours to judge: the line is printed as it came.
120
+ }
121
+ lastReal = Date.now();
122
+ if (!print(line))
123
+ return;
124
+ }
125
+ });
126
+ current.on('error', () => undefined);
127
+ current.on('close', () => {
128
+ if (done || socket !== current)
129
+ return;
130
+ const what = connected
131
+ ? `The connection to ${opts.socketPath} was closed: the helper stopped.`
132
+ : `Could not connect to ${opts.socketPath}: no helper is listening there. Start tr-ai-intercom-helper with --notification-listener.`;
133
+ if (!reconnect) {
134
+ opts.err(what);
135
+ finish(1);
136
+ return;
137
+ }
138
+ // Say it once per outage, not at every attempt.
139
+ if (!complained) {
140
+ opts.err(`${what} Trying again every ${Math.round(cooloff / 1000)} s.`);
141
+ complained = true;
142
+ }
143
+ timer = setTimeout(connect, cooloff);
144
+ });
145
+ };
146
+ connect();
147
+ });
148
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ import Optist from 'optist';
3
+ import { resolveSocketPath, runNotifier } from './notifier.js';
4
+ import { NOTIFY_OPTIONS } from './notify-options.js';
5
+ // tr-ai-intercom-notify: prints the notifications of a running
6
+ // tr-ai-intercom-helper to standard output, one line of JSON each.
7
+ const HELP_TAIL = 'Give exactly one of --monitor and --oneshot, and exactly one of --helper-port and --socket-path. Each line printed is one notification as compact JSON; it says that something happened on the intercom, never what. The helper must run with --notification-listener.';
8
+ async function main() {
9
+ const parser = new Optist()
10
+ .opts(NOTIFY_OPTIONS)
11
+ .additional(0, 0)
12
+ .help('tr-ai-intercom-notify')
13
+ .helpMessageTail(HELP_TAIL);
14
+ const opt = parser.parse();
15
+ const fail = (message) => {
16
+ parser.showErrorMessageHelpAndExitIfHelpEnabled(message, 1);
17
+ throw new Error(message);
18
+ };
19
+ const monitor = opt.value('monitor');
20
+ const oneshot = opt.value('oneshot');
21
+ if (!monitor && !oneshot)
22
+ fail('Give --monitor or --oneshot.');
23
+ const port = opt.value('helper-port');
24
+ const path = opt.value('socket-path');
25
+ if (port === undefined && !path)
26
+ fail('Give --helper-port or --socket-path.');
27
+ const idle = opt.value('idle-notification-interval');
28
+ const stop = new AbortController();
29
+ process.on('SIGINT', () => stop.abort());
30
+ process.on('SIGTERM', () => stop.abort());
31
+ // Whoever read our output went away: nothing left to do.
32
+ process.stdout.on('error', () => process.exit(0));
33
+ const socketPath = await resolveSocketPath({ port, path });
34
+ const status = await runNotifier({
35
+ socketPath,
36
+ mode: monitor ? 'monitor' : 'oneshot',
37
+ reconnect: opt.value('reconnect'),
38
+ idleIntervalMs: idle === undefined ? undefined : idle * 1000,
39
+ out: (line) => process.stdout.write(line),
40
+ err: (message) => process.stderr.write(`tr-ai-intercom-notify: ${message}\n`),
41
+ signal: stop.signal,
42
+ });
43
+ // Let the last line reach a pipe before the process ends.
44
+ process.stdout.write('', () => process.exit(status));
45
+ }
46
+ main().catch((err) => {
47
+ process.stderr.write(`tr-ai-intercom-notify: ${err.message}\n`);
48
+ process.exit(1);
49
+ });
@@ -0,0 +1,9 @@
1
+ import type { OptDef } from 'optist';
2
+ /**
3
+ * The options of tr-ai-intercom-notify.
4
+ *
5
+ * Every option names its environment variable in its own definition,
6
+ * INTERCOM_NOTIFY_OPT_ followed by the option name in upper case with dashes
7
+ * as underscores.
8
+ */
9
+ export declare const NOTIFY_OPTIONS: OptDef[];
@@ -0,0 +1,55 @@
1
+ import ou from 'optist/util.js';
2
+ import { parseTimespec } from './options.js';
3
+ /**
4
+ * The options of tr-ai-intercom-notify.
5
+ *
6
+ * Every option names its environment variable in its own definition,
7
+ * INTERCOM_NOTIFY_OPT_ followed by the option name in upper case with dashes
8
+ * as underscores.
9
+ */
10
+ export const NOTIFY_OPTIONS = [
11
+ {
12
+ longName: 'monitor',
13
+ environment: 'INTERCOM_NOTIFY_OPT_MONITOR',
14
+ description: 'Print every notification as it arrives, until stopped.',
15
+ conflictsWith: 'oneshot',
16
+ },
17
+ {
18
+ longName: 'oneshot',
19
+ environment: 'INTERCOM_NOTIFY_OPT_ONESHOT',
20
+ description: 'Print the first notification and end.',
21
+ conflictsWith: ['monitor', 'reconnect'],
22
+ },
23
+ {
24
+ longName: 'reconnect',
25
+ environment: 'INTERCOM_NOTIFY_OPT_RECONNECT',
26
+ description: 'With --monitor: when the helper cannot be reached or goes away, keep trying every few seconds instead of ending.',
27
+ requiresAlso: 'monitor',
28
+ },
29
+ {
30
+ longName: 'helper-port',
31
+ environment: 'INTERCOM_NOTIFY_OPT_HELPER_PORT',
32
+ description: 'The local port the helper listens on (its --listen-port). The socket is found from it: /tmp/tr-ai-intercom-helper.<uid>/<port>.sock.',
33
+ hasArg: true,
34
+ conflictsWith: 'socket-path',
35
+ optArgCb: ou.integerWithLimitsCbFactory(1, 65535),
36
+ },
37
+ {
38
+ longName: 'socket-path',
39
+ environment: 'INTERCOM_NOTIFY_OPT_SOCKET_PATH',
40
+ description: 'The socket of the helper, when it was started with --notification-listener-path.',
41
+ hasArg: true,
42
+ conflictsWith: 'helper-port',
43
+ optArgCb: ou.nonEmptyCb,
44
+ },
45
+ {
46
+ longName: 'idle-notification-interval',
47
+ environment: 'INTERCOM_NOTIFY_OPT_IDLE_NOTIFICATION_INTERVAL',
48
+ description: 'Print a notification of its own, with the message "local-idle-notification", whenever nothing has been printed for this long, and again each time that long passes. Its data.idle is the number of seconds since the last notification from the helper. In seconds, or with a unit: 90, 15m, 2h, 1d. Without it nothing is printed while nothing happens.',
49
+ hasArg: true,
50
+ optArgCb: (s) => {
51
+ const seconds = parseTimespec(s);
52
+ return seconds !== undefined && seconds > 0 ? seconds : undefined;
53
+ },
54
+ },
55
+ ];
@@ -0,0 +1,47 @@
1
+ import type { OptDef } from 'optist';
2
+ /**
3
+ * A time span in seconds: a number, optionally followed by s, m, h or d.
4
+ * "90", "90s", "15m", "2h" and "1d" are all fine. Fractions are allowed.
5
+ */
6
+ export declare function parseTimespec(text: string): number | undefined;
7
+ /** One header line, "Name: value". */
8
+ export declare function parseHeaderLine(line: string): {
9
+ name: string;
10
+ value: string;
11
+ } | undefined;
12
+ export declare const OPTIONS: OptDef[];
13
+ export interface Config {
14
+ /** Root URL of the intercom. */
15
+ upstreamUrl: string;
16
+ host: string;
17
+ port: number;
18
+ logLevel: string;
19
+ /** Close the idle wake-up socket after this many seconds; undefined = never. */
20
+ socketTimeout: number | undefined;
21
+ file: string | undefined;
22
+ dir: string | undefined;
23
+ tmpDir: string | undefined;
24
+ url: string | undefined;
25
+ urlHeader: {
26
+ name: string;
27
+ value: string;
28
+ } | undefined;
29
+ localSocket: string | undefined;
30
+ command: string | undefined;
31
+ /** Serve notifications on a local socket of the helper's own. */
32
+ listener: boolean;
33
+ /** Its path, when not the default one. */
34
+ listenerPath: string | undefined;
35
+ }
36
+ export declare class ConfigError extends Error {
37
+ }
38
+ /**
39
+ * The configuration, from the command line and the environment.
40
+ *
41
+ * `argv` holds the arguments only (default: those of the process). With
42
+ * `exitOnError` (the default) a mistake prints the error and the usage text
43
+ * and ends the process; without it a ConfigError is thrown instead.
44
+ */
45
+ export declare function loadConfig(argv?: string[], opts?: {
46
+ exitOnError?: boolean;
47
+ }): Config;