chat-recall 0.7.25 → 0.7.29

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,157 @@
1
+ import { recallTarget } from '@chat-recall/engine/core/remote-target.js';
2
+ import { formatDelivery } from '@chat-recall/engine/core/session-messages.js';
3
+ import { ancestorPids, channelDecision } from './channel-detect.js';
4
+ import { clearChannelAlive, markChannelAlive, sessionIdFromPids } from './channel-state.js';
5
+ import { fetchWithTimeout } from './http.js';
6
+ /** One long-poll; the server holds it for at most 25 s. */
7
+ const WAIT_SECS = 25;
8
+ /** How long a session with no id yet keeps asking the hook for one. */
9
+ const SESSION_ID_WAIT_MS = 90_000;
10
+ /** How often the marker is refreshed; a waiter treats an older one as gone. */
11
+ const MARK_EVERY_MS = 30_000;
12
+ /**
13
+ * Declare the capability the client looks for.
14
+ *
15
+ * It must be registered BEFORE the transport connects: the client reads
16
+ * `capabilities` from the initialize result and decides once, at connect, that
17
+ * this server may push messages into the session. Registering later is silent —
18
+ * the client has already made up its mind.
19
+ */
20
+ export function declareChannel(server) {
21
+ server.registerCapabilities({ experimental: { 'claude/channel': {} } });
22
+ }
23
+ /**
24
+ * Prepare a session for channel delivery: declare the capability, and return the
25
+ * function that starts delivering, or null when this session did not ask.
26
+ *
27
+ * The two halves are separate because of when the client decides: it reads the
28
+ * capability once, from the initialize result, and never looks again. So the
29
+ * capability goes in before `connect()`, and the loop starts after — polling a
30
+ * server that is not connected yet would deliver into nothing.
31
+ */
32
+ export function beginChannel(server, debug) {
33
+ const decision = channelDecision();
34
+ const log = debug ?? ((reason) => {
35
+ if (process.env.CHAT_RECALL_MESSAGE_HOOK_DEBUG === '1')
36
+ process.stderr.write(`chat-recall channel: ${reason}\n`);
37
+ });
38
+ if (!decision.enabled)
39
+ return null;
40
+ const target = recallTarget();
41
+ if (!target) {
42
+ log('asked for, but this machine has no login');
43
+ return null;
44
+ }
45
+ declareChannel(server);
46
+ const pids = ancestorPids();
47
+ return () => {
48
+ void runChannel({ server, target, sessionId: () => sessionIdFromPids(pids), debug: log })
49
+ .catch((e) => log(`stopped: ${e instanceof Error ? e.message : String(e)}`));
50
+ };
51
+ }
52
+ function headers(target) {
53
+ const h = { 'content-type': 'application/json' };
54
+ if (target.token)
55
+ h.authorization = `Bearer ${target.token}`;
56
+ return h;
57
+ }
58
+ async function postJson(target, path, body, ms) {
59
+ const res = await fetchWithTimeout(`${target.base}${path}`, {
60
+ method: 'POST', headers: headers(target), body: JSON.stringify(body),
61
+ }, ms);
62
+ return { status: res.status, body: res.ok ? await res.json() : null };
63
+ }
64
+ /**
65
+ * Deliver messages until the session ends.
66
+ *
67
+ * The loop mirrors the waiter's, on purpose: same endpoint, same lease, same
68
+ * acknowledgement rule (ack only after the message has left this process), and
69
+ * the same give-up rules, so a server without this route costs a few retries
70
+ * rather than a spin.
71
+ */
72
+ export async function runChannel(deps) {
73
+ const debug = deps.debug ?? (() => { });
74
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => { setTimeout(r, ms); }));
75
+ const post = deps.post ?? postJson;
76
+ let sessionId = deps.sessionId();
77
+ const giveUpAt = Date.now() + SESSION_ID_WAIT_MS;
78
+ while (!sessionId) {
79
+ if (Date.now() > giveUpAt) {
80
+ debug('channel: the hook never recorded this session');
81
+ return;
82
+ }
83
+ await sleep(500);
84
+ sessionId = deps.sessionId();
85
+ }
86
+ debug(`channel: delivering for ${sessionId}`);
87
+ markChannelAlive(sessionId);
88
+ let markedAt = Date.now();
89
+ let failures = 0;
90
+ let notFound = 0;
91
+ try {
92
+ for (;;) {
93
+ if (Date.now() - markedAt >= MARK_EVERY_MS) {
94
+ markChannelAlive(sessionId);
95
+ markedAt = Date.now();
96
+ }
97
+ let r;
98
+ try {
99
+ r = await post(deps.target, '/api/live-sessions/wait', { sessionId, timeoutSecs: WAIT_SECS }, (WAIT_SECS + 15) * 1000);
100
+ }
101
+ catch (e) {
102
+ r = { status: 0, body: null };
103
+ debug(`channel: request failed: ${e instanceof Error ? e.message : String(e)}`);
104
+ }
105
+ if (r.status === 401 || r.status === 402 || r.status === 403) {
106
+ debug(`channel: HTTP ${r.status}`);
107
+ return;
108
+ }
109
+ const body = r.body;
110
+ if (!body) {
111
+ // The same numbers as the waiter: a 404 at the start is the
112
+ // SessionStart report still on its way, and a network that keeps
113
+ // failing is not worth an hour of retries from a process the session
114
+ // cannot see.
115
+ failures += 1;
116
+ notFound = r.status === 404 ? notFound + 1 : 0;
117
+ if (notFound >= 5 || failures > 120) {
118
+ debug('channel: giving up on the server');
119
+ return;
120
+ }
121
+ await sleep(Math.min(30_000, 1000 * 2 ** Math.min(failures, 5)));
122
+ continue;
123
+ }
124
+ failures = 0;
125
+ notFound = 0;
126
+ if (body.ended) {
127
+ debug('channel: the session ended');
128
+ return;
129
+ }
130
+ const messages = body.messages ?? [];
131
+ if (!messages.length)
132
+ continue;
133
+ const content = formatDelivery(sessionId, messages, {
134
+ now: (deps.now ?? Date.now)(),
135
+ labels: new Map(Object.entries(body.labels ?? {})),
136
+ });
137
+ try {
138
+ await deps.server.notification({
139
+ method: 'notifications/claude/channel',
140
+ params: { content, meta: { from: 'chat-recall', session: sessionId } },
141
+ });
142
+ }
143
+ catch (e) {
144
+ // A message the client never got must not be acknowledged: the lease
145
+ // ends and the waiter, or the next turn, offers it again.
146
+ debug(`channel: could not emit: ${e instanceof Error ? e.message : String(e)}`);
147
+ return;
148
+ }
149
+ await post(deps.target, '/api/live-sessions/ack', { sessionId, ids: messages.map((m) => m.id) }, 3000)
150
+ .catch(() => { });
151
+ }
152
+ }
153
+ finally {
154
+ clearChannelAlive(sessionId);
155
+ }
156
+ }
157
+ //# sourceMappingURL=channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.js","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,YAAY,EAAE,MAAM,2CAA2C,CAAC;AACzE,OAAO,EAAE,cAAc,EAAoB,MAAM,8CAA8C,C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