@cello-protocol/cli 0.0.315 → 0.0.317

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,39 @@
1
+ const SCHEMA = `
2
+ CREATE TABLE IF NOT EXISTS operator_messages (
3
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
4
+ agent_id BLOB NOT NULL REFERENCES agents(agent_id),
5
+ -- The session the operator was answering about, when they answered a notification that named one.
6
+ session_id BLOB,
7
+ -- Emptied once it's read. The row stays, so the same reply fetched again after a crash is still known.
8
+ text TEXT NOT NULL,
9
+ -- The notifier's name, so the agent knows which route it came by.
10
+ via TEXT NOT NULL,
11
+ -- The notifier's own id for it.
12
+ source_id TEXT NOT NULL UNIQUE,
13
+ received_at INTEGER NOT NULL,
14
+ read_at INTEGER
15
+ );
16
+ `;
17
+ export class OperatorInbox {
18
+ #store;
19
+ constructor(store) {
20
+ this.#store = store;
21
+ store.exec(SCHEMA);
22
+ }
23
+ // False when this one was stored before, whether or not it has been read since. An instruction given once must never
24
+ // reach the agent twice.
25
+ add(agentId, sessionId, text, via, sourceId) {
26
+ if (this.#store.prepare("SELECT 1 FROM operator_messages WHERE source_id = ?").get(sourceId))
27
+ return false;
28
+ this.#store.prepare("INSERT INTO operator_messages (agent_id, session_id, text, via, source_id, received_at) VALUES (?, ?, ?, ?, ?, ?)").run(agentId, sessionId, text, via, sourceId, Date.now());
29
+ return true;
30
+ }
31
+ unread(agentId) {
32
+ return this.#store.prepare("SELECT id, session_id, text, via, received_at FROM operator_messages WHERE agent_id = ? AND read_at IS NULL ORDER BY id").all(agentId);
33
+ }
34
+ // A read counts only once its answer is written, so these are marked then and not before. The words go and the row stays.
35
+ markRead(agentId, ids) {
36
+ for (const id of ids)
37
+ this.#store.prepare("UPDATE operator_messages SET read_at = ?, text = '' WHERE agent_id = ? AND id = ? AND read_at IS NULL").run(Date.now(), agentId, id);
38
+ }
39
+ }
@@ -1,5 +1,9 @@
1
1
  export declare function celloHome(): string;
2
- export declare function socketPath(home?: string): string;
2
+ export declare function socketPath(home?: string, platform?: NodeJS.Platform): string;
3
+ export declare function windowsPipe(home: string, name: "daemon" | "gateway"): string;
4
+ export declare function oldVersionEndpoints(home?: string, platform?: NodeJS.Platform): string[];
5
+ export declare const endpointIsFile: (platform?: NodeJS.Platform) => boolean;
6
+ export declare function ipcKeyPath(home?: string): string;
3
7
  export declare function databasePath(home?: string): string;
4
8
  export declare function logPath(home?: string): string;
5
9
  export declare function holdsOldVersion(home?: string): boolean;
@@ -1,12 +1,38 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { existsSync } from "node:fs";
2
3
  import { homedir } from "node:os";
3
- import { join } from "node:path";
4
+ import { join, win32 } from "node:path";
4
5
  export function celloHome() {
5
6
  return process.env["CELLO_HOME"] ?? join(homedir(), ".cello");
6
7
  }
7
- export function socketPath(home = celloHome()) {
8
+ // Windows refuses a Unix socket in the home folder (listen EACCES at any path length, admin or not), so there the
9
+ // daemon listens on a named pipe. The pipe's name comes from the home folder, so two homes get two daemons.
10
+ // A pipe made by Node takes the default DACL: full control for its user, SYSTEM and Administrators, and READ for
11
+ // Everyone and Anonymous. A reader can't send a request, so other accounts can't act, but the name is predictable and
12
+ // another account could create it first. The client checks the daemon's proof before trusting it (src/ipc/handshake.ts).
13
+ export function socketPath(home = celloHome(), platform = process.platform) {
14
+ if (platform === "win32")
15
+ return windowsPipe(home, "daemon");
8
16
  return join(home, "daemon.sock");
9
17
  }
18
+ // The old version used the same naming, with a second pipe for its gateway. Setup probes both to see if it's running.
19
+ export function windowsPipe(home, name) {
20
+ const canonical = win32.resolve(home).toLowerCase().replace(/\//g, "\\");
21
+ const hash = createHash("sha256").update(canonical).digest("hex").slice(0, 12);
22
+ return `\\\\.\\pipe\\cello-${hash}-${name}`;
23
+ }
24
+ // Where the old version listened: a socket file on macOS and Linux, a named pipe on Windows.
25
+ export function oldVersionEndpoints(home = celloHome(), platform = process.platform) {
26
+ if (platform === "win32")
27
+ return [windowsPipe(home, "daemon"), windowsPipe(home, "gateway")];
28
+ return [join(home, "daemon.sock"), join(home, "gateway.sock")];
29
+ }
30
+ // A named pipe vanishes with the process that made it. Only a socket file can be left behind by a crash.
31
+ export const endpointIsFile = (platform = process.platform) => platform !== "win32";
32
+ // The key the daemon proves itself with on Windows (src/ipc/handshake.ts). A fresh one at every start.
33
+ export function ipcKeyPath(home = celloHome()) {
34
+ return join(home, "daemon.ipc-key");
35
+ }
10
36
  export function databasePath(home = celloHome()) {
11
37
  return join(home, "cello.db");
12
38
  }
@@ -46,6 +46,10 @@ export const AGENT_SETTINGS = {
46
46
  "limits.stranger_pool": { default: "50", kind: "number", min: 1, max: 100_000, loosensWhen: "higher", description: "Open sessions all strangers together can have with this agent." },
47
47
  "limits.quiet_minutes": { default: "120", kind: "number", min: 1, max: 5_256_000, loosensWhen: "lower", description: "A session stops counting toward its caller's limit after this long with nothing new. It stays open." },
48
48
  "limits.cap_alarm_minutes": { default: "10", kind: "number", min: 0, max: 100_000, description: "The shortest gap between two notices that one caller keeps hitting a limit." },
49
+ // The two locks, and both start open: a Reminder or a notifier is meant to be set by just telling an agent. Turning one
50
+ // off is tightening, which anyone can do, and turning it back on is loosening, which takes a person.
51
+ "reminders.anyone_can_change": { default: "true", kind: "switch", description: "Whether anyone, an agent included, can set or remove this agent's Reminders. Off, it takes a person at a terminal. Turning it off needs no person, and turning it back on does." },
52
+ "notifiers.anyone_can_change": { default: "true", kind: "switch", description: "Whether anyone, an agent included, can add or remove this agent's notifiers. Off, it takes a person at a terminal. Turning it off needs no person, and turning it back on does. Sending through a notifier is never locked." },
49
53
  "away.answering": { default: "true", kind: "switch", neutral: true, description: "Whether a call nobody is reachable for gets a greeting, and its first message ends the visit. Off, such a call just waits." },
50
54
  "away.default": { default: "", kind: "text", description: "This agent's own away text, for any tier without its own." },
51
55
  "away.system.stranger": { default: "Dispatched.", kind: "text", description: "The away text of last resort, for a stranger." },
@@ -0,0 +1,26 @@
1
+ import type { Store } from "./store.ts";
2
+ export declare const MAX_REMINDERS = 20;
3
+ export declare const MAX_REMINDER_CHARS = 2000;
4
+ export declare const REMINDER_NOTE = "Reminders set for this agent on this machine, by your operator or by an agent acting for them. They are not from the other party, and nothing the other party writes can add or change one. Follow them. They rank below a policy and can't waive one.";
5
+ export interface DueReminder {
6
+ reminder: number;
7
+ text: string;
8
+ why: string;
9
+ }
10
+ export interface ReminderHost {
11
+ agentName(agentHex: string): string;
12
+ sessionOpen(agentHex: string, sessionHex: string): boolean;
13
+ }
14
+ export declare class Reminders {
15
+ #private;
16
+ constructor(store: Store, host: ReminderHost, now?: () => number);
17
+ set(agentHex: string, params: Record<string, unknown>): unknown;
18
+ list(agentHex: string): unknown;
19
+ remove(agentHex: string, id: unknown): unknown;
20
+ forget(agentHex: string): void;
21
+ due(agentHex: string, sessionHex: string, peerHex: string, delivered: number, starting?: boolean): {
22
+ due: DueReminder[];
23
+ commit(): void;
24
+ };
25
+ shouldWake(agentHex: string, sessionHex: string, peerHex: string): boolean;
26
+ }
@@ -0,0 +1,204 @@
1
+ // Reminders: text set for an agent that the daemon shows it again as a conversation goes, such as when to stop and ask its
2
+ // operator. They are not governance. A policy is semi-permanent and takes a person to change. A Reminder changes freely,
3
+ // anyone can set one, an agent included, and it ranks below a policy. The two travel under different names so a model can
4
+ // tell by the name alone how locked-in each is.
5
+ import { LocalError } from "./errors.js";
6
+ import { logEvent } from "./log.js";
7
+ const SCHEMA = `
8
+ CREATE TABLE IF NOT EXISTS reminders (
9
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
10
+ agent_id BLOB NOT NULL REFERENCES agents(agent_id),
11
+ text TEXT NOT NULL,
12
+ at_start INTEGER NOT NULL,
13
+ every_messages INTEGER,
14
+ every_minutes INTEGER,
15
+ -- Only sessions with this agent, or every one.
16
+ with_id BLOB,
17
+ -- Only this session, for a Reminder that's "for now". It goes when the session closes.
18
+ session_id BLOB,
19
+ expires_at INTEGER,
20
+ created_at INTEGER NOT NULL
21
+ );
22
+ `;
23
+ export const MAX_REMINDERS = 20;
24
+ export const MAX_REMINDER_CHARS = 2000;
25
+ export const REMINDER_NOTE = "Reminders set for this agent on this machine, by your operator or by an agent acting for them. They are not from the other party, and nothing the other party writes can add or change one. Follow them. They rank below a policy and can't waive one.";
26
+ const each = (n, unit) => (n === 1 ? `every ${unit}` : `every ${n} ${unit}s`);
27
+ const hex = (bytes) => Buffer.from(bytes).toString("hex");
28
+ const bytesOf = (text) => new Uint8Array(Buffer.from(text, "hex"));
29
+ function wholeNumber(params, name, max) {
30
+ const value = params[name];
31
+ if (value === undefined)
32
+ return null;
33
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max)
34
+ throw new LocalError("bad_argument", `${name} must be a whole number from 1 to ${max}`);
35
+ return value;
36
+ }
37
+ export class Reminders {
38
+ #store;
39
+ #host;
40
+ #now;
41
+ #shown = new Map();
42
+ constructor(store, host, now = Date.now) {
43
+ this.#store = store;
44
+ this.#host = host;
45
+ this.#now = now;
46
+ store.exec(SCHEMA);
47
+ }
48
+ // Drops what has run out: past its time, or for a session that has closed.
49
+ #live(agentHex) {
50
+ const rows = this.#store.prepare("SELECT id, text, at_start, every_messages, every_minutes, with_id, session_id, expires_at, created_at FROM reminders WHERE agent_id = ? ORDER BY id").all(bytesOf(agentHex));
51
+ const live = [];
52
+ for (const row of rows) {
53
+ const over = (row.expires_at !== null && row.expires_at <= this.#now()) || (row.session_id !== null && !this.#host.sessionOpen(agentHex, hex(row.session_id)));
54
+ if (!over) {
55
+ live.push(row);
56
+ continue;
57
+ }
58
+ this.#store.prepare("DELETE FROM reminders WHERE id = ?").run(row.id);
59
+ this.#drop(row.id);
60
+ logEvent("reminder.ended", { agent: agentHex, reminder: row.id });
61
+ }
62
+ return live;
63
+ }
64
+ #describe(row) {
65
+ const fires = [...(row.at_start ? ["at the start of a session"] : []), ...(row.every_messages ? [each(row.every_messages, "message")] : []), ...(row.every_minutes ? [each(row.every_minutes, "minute")] : [])];
66
+ return {
67
+ reminder: row.id,
68
+ text: row.text,
69
+ fires: fires.join(", "),
70
+ applies_to: row.session_id ? `session ${hex(row.session_id)}` : row.with_id ? `sessions with ${hex(row.with_id)}` : "every session",
71
+ ...(row.expires_at !== null ? { ends_at: new Date(row.expires_at).toISOString() } : row.session_id ? { ends: "when that session closes" } : {}),
72
+ };
73
+ }
74
+ set(agentHex, params) {
75
+ const text = typeof params["text"] === "string" ? params["text"].trim() : "";
76
+ if (text.length === 0)
77
+ throw new LocalError("bad_argument", "A Reminder needs its text.");
78
+ if (text.length > MAX_REMINDER_CHARS)
79
+ throw new LocalError("too_long", `A Reminder holds ${MAX_REMINDER_CHARS} characters, and this is ${text.length}. It's shown again and again, so keep it short.`);
80
+ const everyMessages = wholeNumber(params, "every_messages", 1000);
81
+ const everyMinutes = wholeNumber(params, "every_minutes", 1440);
82
+ const forMinutes = wholeNumber(params, "for_minutes", 43_200);
83
+ if (params["at_start"] !== undefined && typeof params["at_start"] !== "boolean")
84
+ throw new LocalError("bad_argument", "at_start must be true or false");
85
+ // With nothing said about when, it's shown once as each session starts.
86
+ const atStart = params["at_start"] === true || (everyMessages === null && everyMinutes === null);
87
+ const withHex = params["with"];
88
+ if (withHex !== undefined && (typeof withHex !== "string" || !/^[0-9a-f]{64}$/.test(withHex)))
89
+ throw new LocalError("bad_argument", "with must be an agent_id: 64 hex characters. A name won't do, since anyone can choose one.");
90
+ const sessionHex = params["session"];
91
+ if (sessionHex !== undefined && (typeof sessionHex !== "string" || !/^[0-9a-f]{32}$/.test(sessionHex)))
92
+ throw new LocalError("bad_argument", "session must be a session id: 32 hex characters");
93
+ const name = this.#host.agentName(agentHex);
94
+ if (typeof sessionHex === "string" && !this.#host.sessionOpen(agentHex, sessionHex))
95
+ throw new LocalError("no_such_session", `${name} has no open session ${sessionHex}, so a Reminder for it would never be shown.`);
96
+ if (this.#live(agentHex).length >= MAX_REMINDERS)
97
+ throw new LocalError("too_many_reminders", `${name} already has ${MAX_REMINDERS} Reminders, which is the most one agent holds. Remove one with reminder-remove.`);
98
+ const now = this.#now();
99
+ this.#store.prepare("INSERT INTO reminders (agent_id, text, at_start, every_messages, every_minutes, with_id, session_id, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
100
+ .run(bytesOf(agentHex), text, atStart ? 1 : 0, everyMessages, everyMinutes, typeof withHex === "string" ? bytesOf(withHex) : null, typeof sessionHex === "string" ? bytesOf(sessionHex) : null, forMinutes === null ? null : now + forMinutes * 60_000, now);
101
+ const row = this.#live(agentHex).at(-1);
102
+ logEvent("reminder.set", { agent: agentHex, reminder: row.id, at_start: atStart, every_messages: everyMessages, every_minutes: everyMinutes, scoped: withHex !== undefined || sessionHex !== undefined });
103
+ return { set: true, agent: name, ...this.#describe(row) };
104
+ }
105
+ list(agentHex) {
106
+ return { agent: this.#host.agentName(agentHex), reminders: this.#live(agentHex).map((row) => this.#describe(row)) };
107
+ }
108
+ remove(agentHex, id) {
109
+ const name = this.#host.agentName(agentHex);
110
+ if (typeof id !== "number" || !this.#live(agentHex).some((row) => row.id === id))
111
+ throw new LocalError("no_such_reminder", `${name} has no Reminder numbered ${String(id)}. reminder-list shows them.`);
112
+ this.#store.prepare("DELETE FROM reminders WHERE agent_id = ? AND id = ?").run(bytesOf(agentHex), id);
113
+ this.#drop(id);
114
+ logEvent("reminder.removed", { agent: agentHex, reminder: id });
115
+ return { removed: true, agent: name, reminder: id };
116
+ }
117
+ // An agent that's removed takes its Reminders with it.
118
+ forget(agentHex) {
119
+ for (const row of this.#live(agentHex))
120
+ this.#drop(row.id);
121
+ this.#store.prepare("DELETE FROM reminders WHERE agent_id = ?").run(bytesOf(agentHex));
122
+ }
123
+ // What was kept in memory about a Reminder goes with it.
124
+ #drop(id) {
125
+ for (const key of this.#shown.keys())
126
+ if (key.startsWith(`${id}:`))
127
+ this.#shown.delete(key);
128
+ }
129
+ #applies(row, sessionHex, peerHex) {
130
+ if (row.session_id !== null && hex(row.session_id) !== sessionHex)
131
+ return false;
132
+ return row.with_id === null || hex(row.with_id) === peerHex;
133
+ }
134
+ #state(row, sessionHex) {
135
+ // First seen now: a timer runs from here, so a Reminder set mid-conversation waits its full interval.
136
+ return this.#shown.get(`${row.id}:${sessionHex}`) ?? { start: false, since: 0, at: Math.max(row.created_at, this.#firstSeen(sessionHex)), woke: false };
137
+ }
138
+ #sessionsSeen = new Map();
139
+ #firstSeen(sessionHex) {
140
+ const seen = this.#sessionsSeen.get(sessionHex);
141
+ if (seen !== undefined)
142
+ return seen;
143
+ this.#sessionsSeen.set(sessionHex, this.#now());
144
+ return this.#now();
145
+ }
146
+ // What's due for one session, given how many messages are being delivered to the agent right now. Nothing is counted or
147
+ // marked shown until commit runs, because a read only counts once its answer has reached the agent.
148
+ // starting is true for the answer to a call the agent just placed: the caller sends before it ever reads.
149
+ due(agentHex, sessionHex, peerHex, delivered, starting = false) {
150
+ const now = this.#now();
151
+ // Noted even when the agent has no Reminders yet, so one set later knows the conversation was already under way.
152
+ this.#firstSeen(sessionHex);
153
+ const due = [];
154
+ const seen = [];
155
+ for (const row of this.#live(agentHex)) {
156
+ if (!this.#applies(row, sessionHex, peerHex))
157
+ continue;
158
+ const state = this.#state(row, sessionHex);
159
+ let why = null;
160
+ // One set part-way through a conversation is shown on the next read too, and says so, since it isn't the start.
161
+ if (row.at_start === 1 && !state.start && (starting || delivered > 0))
162
+ why = row.created_at > this.#firstSeen(sessionHex) ? "it was just set" : "the start of this session";
163
+ else if (row.every_messages !== null && state.since + delivered >= row.every_messages)
164
+ why = each(row.every_messages, "message");
165
+ else if (row.every_minutes !== null && now - state.at >= row.every_minutes * 60_000)
166
+ why = each(row.every_minutes, "minute");
167
+ if (why !== null)
168
+ due.push({ reminder: row.id, text: row.text, why });
169
+ seen.push({ row, shown: why !== null });
170
+ }
171
+ return {
172
+ due,
173
+ // Applied to what's there when the answer has gone, not to what was there when it was built: a wake or another read
174
+ // may have come between.
175
+ commit: () => {
176
+ for (const { row, shown } of seen) {
177
+ const state = this.#state(row, sessionHex);
178
+ // Only a message arriving ends a quiet spell and lets the timer wake the agent again: being shown doesn't.
179
+ const woke = delivered > 0 ? false : state.woke;
180
+ // Any showing starts every count again, so one Reminder isn't shown twice in a row for two reasons.
181
+ this.#shown.set(`${row.id}:${sessionHex}`, shown ? { start: true, since: 0, at: now, woke } : { ...state, since: state.since + delivered, woke });
182
+ }
183
+ },
184
+ };
185
+ }
186
+ // Whether a timed Reminder is due in a session where nothing is arriving, so the agent should be woken to read it.
187
+ // One wake per quiet spell: a session left open and idle must not cost a model turn every few minutes for good.
188
+ shouldWake(agentHex, sessionHex, peerHex) {
189
+ const now = this.#now();
190
+ let wake = false;
191
+ for (const row of this.#live(agentHex)) {
192
+ if (row.every_minutes === null || !this.#applies(row, sessionHex, peerHex))
193
+ continue;
194
+ const state = this.#state(row, sessionHex);
195
+ if (state.woke || now - state.at < row.every_minutes * 60_000) {
196
+ this.#shown.set(`${row.id}:${sessionHex}`, state);
197
+ continue;
198
+ }
199
+ this.#shown.set(`${row.id}:${sessionHex}`, { ...state, woke: true });
200
+ wake = true;
201
+ }
202
+ return wake;
203
+ }
204
+ }
@@ -0,0 +1,36 @@
1
+ export interface TelegramEndpoint {
2
+ apiUrl: string;
3
+ timeoutMs: number;
4
+ pollSeconds: number;
5
+ }
6
+ export declare const TELEGRAM: TelegramEndpoint;
7
+ export declare class TelegramError extends Error {
8
+ readonly code: number | undefined;
9
+ constructor(message: string, code?: number);
10
+ }
11
+ export declare const botIdOf: (token: string) => string;
12
+ export declare function botUsername(at: TelegramEndpoint, token: string): Promise<string>;
13
+ export interface TelegramChat {
14
+ id?: number | string;
15
+ type?: string;
16
+ username?: string;
17
+ first_name?: string;
18
+ title?: string;
19
+ }
20
+ export interface TelegramUpdate {
21
+ update_id: number;
22
+ message?: {
23
+ message_id?: number;
24
+ text?: string;
25
+ chat?: TelegramChat;
26
+ reply_to_message?: {
27
+ message_id?: number;
28
+ };
29
+ };
30
+ }
31
+ export declare function newestUpdate(at: TelegramEndpoint, token: string): Promise<TelegramUpdate | undefined>;
32
+ export declare function updatesFrom(at: TelegramEndpoint, token: string, offset: number, stop: AbortSignal): Promise<TelegramUpdate[]>;
33
+ export declare function sendText(at: TelegramEndpoint, token: string, chatId: string, text: string): Promise<{
34
+ chatId: string;
35
+ messageId: number;
36
+ }>;
@@ -0,0 +1,72 @@
1
+ export const TELEGRAM = { apiUrl: "https://api.telegram.org", timeoutMs: 15_000, pollSeconds: 25 };
2
+ export class TelegramError extends Error {
3
+ // Telegram's own error number, when it gave one: 401 is a token it doesn't know, 409 is another reader on the same bot.
4
+ code;
5
+ constructor(message, code) {
6
+ super(message);
7
+ this.code = code;
8
+ }
9
+ }
10
+ async function call(at, token, method, body, limitMs = at.timeoutMs, stop) {
11
+ let response;
12
+ // A dropped connection is tried once more, because a person not being told matters more than their being told twice.
13
+ // A timeout isn't: the limit is the promise.
14
+ for (let attempt = 1; response === undefined; attempt++) {
15
+ try {
16
+ response = await fetch(`${at.apiUrl}/bot${token}/${method}`, {
17
+ method: "POST",
18
+ headers: { "Content-Type": "application/json" },
19
+ body: JSON.stringify(body),
20
+ signal: stop ? AbortSignal.any([AbortSignal.timeout(limitMs), stop]) : AbortSignal.timeout(limitMs),
21
+ });
22
+ }
23
+ catch (err) {
24
+ if (stop?.aborted)
25
+ throw new TelegramError("Stopped.");
26
+ if (err instanceof Error && err.name === "TimeoutError")
27
+ throw new TelegramError(`Telegram didn't answer within ${limitMs / 1000} seconds.`);
28
+ if (attempt < 2)
29
+ continue;
30
+ const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : err instanceof Error ? err.message : String(err);
31
+ throw new TelegramError(`Telegram couldn't be reached, twice: ${cause.replaceAll(token, "<bot token>")}.`);
32
+ }
33
+ }
34
+ let answer;
35
+ try {
36
+ answer = await response.json();
37
+ }
38
+ catch {
39
+ // No number: a page from a proxy or a hotel network isn't Telegram refusing the token.
40
+ throw new TelegramError(`Telegram answered with something unreadable (HTTP ${response.status}).`);
41
+ }
42
+ if (answer.ok !== true)
43
+ throw new TelegramError(`Telegram refused: ${answer.description ?? `HTTP ${response.status}`}.`, answer.error_code);
44
+ return answer.result;
45
+ }
46
+ // The number before the colon in a token is the bot's own id, and it stays the same when the token is replaced.
47
+ export const botIdOf = (token) => token.split(":")[0] ?? "";
48
+ // The bot's own username, which also proves the token is real.
49
+ export async function botUsername(at, token) {
50
+ const me = await call(at, token, "getMe", {});
51
+ if (typeof me?.username !== "string")
52
+ throw new TelegramError("Telegram accepted the token but didn't name a bot.");
53
+ return me.username;
54
+ }
55
+ // The newest thing sent to the bot, alone. Offset -1 asks for just that: without it Telegram gives the oldest hundred, and
56
+ // "last" would be wrong on a bot with a backlog. It also makes Telegram forget everything older.
57
+ export async function newestUpdate(at, token) {
58
+ const updates = await call(at, token, "getUpdates", { offset: -1, timeout: 0, allowed_updates: ["message"] });
59
+ return updates.at(-1);
60
+ }
61
+ // Everything sent to the bot from this update on, waiting up to pollSeconds for the first. Stopping it ends the wait at once.
62
+ export async function updatesFrom(at, token, offset, stop) {
63
+ return await call(at, token, "getUpdates", { offset, timeout: at.pollSeconds, allowed_updates: ["message"] }, at.pollSeconds * 1000 + at.timeoutMs, stop);
64
+ }
65
+ // Answers only once Telegram has accepted the message, with the ids Telegram gave: the chat's own number, which is what a
66
+ // reply will carry even if the chat was named as @something, and the message's.
67
+ export async function sendText(at, token, chatId, text) {
68
+ const sent = await call(at, token, "sendMessage", { chat_id: chatId, text });
69
+ if (typeof sent?.message_id !== "number" || sent.chat?.id === undefined)
70
+ throw new TelegramError("Telegram accepted the message but didn't say where it went.");
71
+ return { chatId: String(sent.chat.id), messageId: sent.message_id };
72
+ }
@@ -33,7 +33,7 @@ const mcpEntry = () => fileURLToPath(new URL(`./mcp${extname(fileURLToPath(impor
33
33
  const daemonEntry = () => fileURLToPath(new URL(`./daemon/main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
34
34
  function withEnv(existing, set, drop) {
35
35
  const keyOf = (line) => line.split("=", 1)[0];
36
- const lines = existing.split("\n").filter((line) => !drop.includes(keyOf(line)));
36
+ const lines = existing.split(/\r?\n/).filter((line) => !drop.includes(keyOf(line)));
37
37
  while (lines.at(-1) === "")
38
38
  lines.pop();
39
39
  for (const [key, value] of Object.entries(set)) {
@@ -70,11 +70,11 @@ export function setLanding(options) {
70
70
  const envPath = join(hermesHome, ".env");
71
71
  if (!existsSync(envPath))
72
72
  return { ok: false, output: `There's no bridge in ${hermesHome} yet. A person sets it up first with cello bridge hermes.` };
73
- const bridged = readFileSync(envPath, "utf8").split("\n").find((line) => line.startsWith("CELLO_AGENT_NAME="))?.slice("CELLO_AGENT_NAME=".length);
73
+ const bridged = readFileSync(envPath, "utf8").split(/\r?\n/).find((line) => line.startsWith("CELLO_AGENT_NAME="))?.slice("CELLO_AGENT_NAME=".length);
74
74
  // An agent moves its own notifications, never another profile's.
75
75
  if (bridged !== options.agent.trim())
76
76
  return { ok: false, output: `${hermesHome} is bridged to ${bridged ?? "no agent"}, not ${options.agent}. Nothing changed.` };
77
- if (readFileSync(envPath, "utf8").split("\n").includes("CELLO_SESSION_SCOPE=peer"))
77
+ if (readFileSync(envPath, "utf8").split(/\r?\n/).includes("CELLO_SESSION_SCOPE=peer"))
78
78
  return { ok: false, output: "This agent gives each caller their own session, so there's no one landing session to move. Nothing changed." };
79
79
  const { landing, error } = resolveLanding(options.landingSession);
80
80
  if (error)
@@ -96,11 +96,11 @@ export async function installBridge(options) {
96
96
  const envPath = join(hermesHome, ".env");
97
97
  const hermesEnv = existsSync(envPath) ? readFileSync(envPath, "utf8") : "";
98
98
  // This has to be re-run after every upgrade, and forgetting a flag then mustn't open a public agent to strangers. Only --not-public ends it.
99
- const wasPublic = hermesEnv.split("\n").includes("CELLO_PUBLIC=1");
99
+ const wasPublic = hermesEnv.split(/\r?\n/).includes("CELLO_PUBLIC=1");
100
100
  if (options.public && options.notPublic)
101
101
  return refuse("--public and --not-public can't go together.");
102
102
  const isPublic = options.public || (wasPublic && !options.notPublic);
103
- const allowInitiate = options.allowInitiate || (isPublic && !options.notPublic && hermesEnv.split("\n").includes("CELLO_ALLOW_INITIATE=1"));
103
+ const allowInitiate = options.allowInitiate || (isPublic && !options.notPublic && hermesEnv.split(/\r?\n/).includes("CELLO_ALLOW_INITIATE=1"));
104
104
  const scope = options.sessionScope ?? (isPublic ? "peer" : "agent");
105
105
  if (!SESSION_SCOPES.includes(scope))
106
106
  return refuse(`--session-scope must be one of ${SESSION_SCOPES.join(", ")}, not '${scope}'.`);
@@ -3,4 +3,11 @@ export interface McpInstallLine {
3
3
  outcome: "installed" | "unchanged" | "not_found" | "failed";
4
4
  detail: string;
5
5
  }
6
+ export declare function claudeDesktopFolder(home: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): string;
7
+ export declare function windowsCommandLine(command: string, args: string[]): {
8
+ file: string;
9
+ args: string[];
10
+ shell: boolean;
11
+ };
12
+ export declare function pickWindowsClaude(whereOutput: string): string;
6
13
  export declare function installMcp(home?: string): McpInstallLine[];
@@ -1,8 +1,8 @@
1
1
  // cello setup --install-mcp: connects the apps on this machine, and says exactly what it changed. Nothing here leaves the machine.
2
2
  import { spawnSync } from "node:child_process";
3
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
- import { dirname, extname, join } from "node:path";
5
+ import { dirname, extname, join, win32 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  const CLAUDE_WAIT_MS = 120_000;
8
8
  function writeAtomically(path, text) {
@@ -10,13 +10,49 @@ function writeAtomically(path, text) {
10
10
  writeFileSync(`${path}.cello-tmp`, text, { mode: 0o600 });
11
11
  renameSync(`${path}.cello-tmp`, path);
12
12
  }
13
+ // Claude Desktop keeps its config in Application Support on a Mac, under %APPDATA% on Windows, and in ~/.config on Linux.
14
+ // The Microsoft Store (MSIX) install on Windows redirects %APPDATA% into its package folder, so that one wins if present.
15
+ export function claudeDesktopFolder(home, platform = process.platform, env = process.env) {
16
+ if (platform === "darwin")
17
+ return join(home, "Library", "Application Support", "Claude");
18
+ if (platform === "win32") {
19
+ const localAppData = env["LOCALAPPDATA"] ?? win32.join(home, "AppData", "Local");
20
+ const packages = win32.join(localAppData, "Packages");
21
+ const store = existsSync(packages) ? readdirSync(packages).find((name) => /^Claude_/i.test(name)) : undefined;
22
+ const storeConfig = store ? win32.join(packages, store, "LocalCache", "Roaming", "Claude") : undefined;
23
+ if (storeConfig && existsSync(storeConfig))
24
+ return storeConfig;
25
+ return win32.join(env["APPDATA"] ?? win32.join(home, "AppData", "Roaming"), "Claude");
26
+ }
27
+ return join(home, ".config", "Claude");
28
+ }
29
+ // Windows has no sh, so the claude command is found with where. An npm install there is claude.cmd, which Node
30
+ // runs only through a shell. The shell gets one finished line (an args array with shell: true is deprecated in
31
+ // Node 24), with each part quoted, because it splits on spaces and a user folder often has one.
32
+ export function windowsCommandLine(command, args) {
33
+ if (/\.exe$/i.test(command))
34
+ return { file: command, args, shell: false };
35
+ const quote = (s) => `"${s.replace(/"/g, '""')}"`;
36
+ return { file: [command, ...args].map(quote).join(" "), args: [], shell: true };
37
+ }
38
+ // where lists every match on PATH. An npm install puts an extensionless sh script first, which cmd can't run itself.
39
+ export function pickWindowsClaude(whereOutput) {
40
+ const found = whereOutput.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
41
+ return found.find((p) => /\.exe$/i.test(p)) ?? found.find((p) => /\.(cmd|bat)$/i.test(p)) ?? "";
42
+ }
43
+ function findClaude() {
44
+ if (process.platform === "win32")
45
+ return pickWindowsClaude(spawnSync("where", ["claude"], { encoding: "utf8" }).stdout ?? "");
46
+ return (spawnSync("sh", ["-c", "command -v claude"], { encoding: "utf8" }).stdout ?? "").trim();
47
+ }
13
48
  function claudeCode(packageRoot) {
14
49
  const app = "Claude Code";
15
- const onPath = spawnSync("sh", ["-c", "command -v claude"], { encoding: "utf8" }).stdout.trim();
50
+ const onPath = findClaude();
16
51
  if (!onPath)
17
52
  return { app, outcome: "not_found", detail: "no claude command on this PATH" };
18
53
  const claude = (args) => {
19
- const run = spawnSync(onPath, args, { encoding: "utf8", timeout: CLAUDE_WAIT_MS });
54
+ const line = process.platform === "win32" ? windowsCommandLine(onPath, args) : { file: onPath, args, shell: false };
55
+ const run = spawnSync(line.file, line.args, { encoding: "utf8", timeout: CLAUDE_WAIT_MS, shell: line.shell });
20
56
  return { ok: run.status === 0, said: `${run.stdout ?? ""}${run.stderr ?? ""}`.trim() };
21
57
  };
22
58
  const listed = claude(["plugin", "list"]);
@@ -32,7 +68,7 @@ function claudeCode(packageRoot) {
32
68
  }
33
69
  function claudeDesktop(home, command, args) {
34
70
  const app = "Claude Desktop";
35
- const folder = process.platform === "darwin" ? join(home, "Library", "Application Support", "Claude") : join(home, ".config", "Claude");
71
+ const folder = claudeDesktopFolder(home);
36
72
  if (!existsSync(folder))
37
73
  return { app, outcome: "not_found", detail: `no ${folder}` };
38
74
  const path = join(folder, "claude_desktop_config.json");
@@ -7,12 +7,16 @@ export declare class DaemonGone extends Error {
7
7
  readonly code = "daemon_not_running";
8
8
  constructor();
9
9
  }
10
+ export declare function connectFailure(path: string, err: NodeJS.ErrnoException): Error;
10
11
  export declare class IpcClient {
11
12
  #private;
12
13
  onNotification: (frame: IpcNotification) => void;
13
14
  onClose: () => void;
14
15
  private constructor();
15
- static connect(path: string): Promise<IpcClient>;
16
+ static connect(path: string, options?: {
17
+ verify?: boolean;
18
+ keyFile?: string;
19
+ }): Promise<IpcClient>;
16
20
  call(method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<unknown>;
17
21
  close(): void;
18
22
  }