@inetafrica/open-claudia 3.0.2 → 3.0.3

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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## v3.0.3 — the lock-holder stands its ground
4
+
5
+ - **A persistent 409 no longer restarts the bot.** v3.0.1 taught the poller to ride out short 409 conflicts but still `exit(1)` once a conflict outlived 2 minutes, on the theory that the survivor had to be a real second instance. In practice the rogue poller is lock-blind — a debugger-run dev checkout, a copy on another config dir, or another host on the same token — so the exit killed the *legitimate*, lock-holding service and launchd respawned it straight back into the same fight (five boot→409→exit cycles on 2026-07-12). The poller now never exits over a 409: it pauses 15s per retry, slows to 60s once the streak passes 2 minutes, sends the owner a throttled Telegram alert (max one per hour) naming the likely culprits, and posts an all-clear once the rogue goes away.
6
+ - **The single-instance lock is atomic.** Acquisition was read-check-then-write, so two processes booting together (a launchd respawn racing a manual start) could both judge the lock stale and both claim it — each believing it was the only copy. The lock is now claimed with an exclusive-create (`O_EXCL`) in a bounded retry loop: stale, corrupt, or own-pid locks are unlinked and re-claimed atomically, a live holder still turns the newcomer away, and a process that loses every claim attempt refuses to boot rather than assuming ownership.
7
+ - **Agent-space / OpenClaw:** no new deps, no new env, no schema change; Docker image builds identically. `test-telegram-409-grace.js` now proves the never-exit + owner-alert + all-clear path; `test-single-instance.js` passes unchanged against the atomic rewrite.
8
+
3
9
  ## v3.0.2 — honest context numbers, dream summaries that arrive
4
10
 
5
11
  - **The context warning counts the window again, not the bill.** The v3.0.0 provider rewrite computed the live context number from the provider's *cumulative* turn usage — every tool round-trip re-counted the cached prompt prefix, so a normal turn read as 347k+ "context" (crossing 1M on busy turns), spooked the usage alert, and could prematurely force-compact sessions whose real window was fine. The number now tracks the **peak single API call** in the turn (`peakContextTokens` over per-call usage events) — true window occupancy, the same semantics v2 reported (~160k on a heavy turn). Billing is untouched: ledger records keep the cumulative figure in `billedContextTokens`, and API-reported spend was never affected (v3 bills the same or less than v2 — the display was wrong, not the meter). The usage alert says "Context this turn" whenever the peak is available.
package/bot.js CHANGED
@@ -22,10 +22,10 @@ ensureRuntimeDirectories();
22
22
  const { acquireSingleInstanceLock } = require("./core/single-instance");
23
23
  const instanceLock = acquireSingleInstanceLock({ configDir: CONFIG_DIR });
24
24
  if (!instanceLock.acquired) {
25
- const h = instanceLock.holder;
25
+ const h = instanceLock.holder || {};
26
26
  console.error(
27
27
  `Another Open Claudia instance already owns ${CONFIG_DIR} ` +
28
- `(pid ${h.pid}, started ${h.startedAt || "?"}, ${h.entrypoint || "unknown entrypoint"}). Exiting. ` +
28
+ `(pid ${h.pid || "?"}, started ${h.startedAt || "?"}, ${h.entrypoint || "unknown entrypoint"}). Exiting. ` +
29
29
  "Stop it first (launchctl stop com.claude-telegram-bot), or give a dev run its own OPEN_CLAUDIA_CONFIG_DIR."
30
30
  );
31
31
  process.exit(1);
@@ -41,6 +41,8 @@ class TelegramAdapter {
41
41
  this._conflictSince = 0; // start of the current 409 streak
42
42
  this._conflictTimer = null; // pending paused retry after a 409
43
43
  this._conflictClearTimer = null; // quiet after a retry ⇒ streak over
44
+ this._conflictAlertAt = 0; // last owner alert about a rogue poller (throttle: 1/h)
45
+ this._conflictAlerted = false; // current streak already alerted ⇒ send the all-clear
44
46
  this._wireInbound();
45
47
  }
46
48
 
@@ -142,23 +144,31 @@ class TelegramAdapter {
142
144
  }, 30000);
143
145
  }
144
146
 
145
- // Telegram 409s a getUpdates call while ANOTHER one holds the token. Two
146
- // causes: a ghost long-poll left by an uncleanly-killed predecessor (clears
147
- // within its ≤30s poll timeout), or a genuinely running second instance.
148
- // Exiting on the first 409 turned the ghost case into a KeepAlive respawn
149
- // storm (7 boot→409→die cycles on 2026-07-12). So: pause, retry inside a
150
- // grace window, and exit only if the conflict outlives it that really is
151
- // a second instance, and the supervisor's throttled respawns pace the rest.
147
+ // Telegram 409s a getUpdates call while ANOTHER one holds the token: a
148
+ // ghost long-poll left by an uncleanly-killed predecessor (clears within
149
+ // its ≤30s poll timeout), or a genuinely running second poller. We hold
150
+ // the single-instance lock, so WE are the legitimate copy the rogue is
151
+ // lock-blind (a pre-lock process, a checkout on another CONFIG_DIR, or
152
+ // another host on the same token). Exiting here just handed launchd a
153
+ // respawn into the same fight (the 5-boot storm of 2026-07-12), so we
154
+ // never exit: pause, retry, and once the streak outlives the ghost window
155
+ // slow to 60s retries and alert the owner (max 1/hour) until it clears.
152
156
  _on409Conflict() {
153
157
  const now = Date.now();
154
158
  if (!this._conflictSince) this._conflictSince = now;
155
159
  if (this._conflictClearTimer) { clearTimeout(this._conflictClearTimer); this._conflictClearTimer = null; }
156
- if (now - this._conflictSince > 120000) {
157
- console.error("Another instance is polling (409 persisted >2min). Exiting.");
158
- process.exit(1);
160
+ const persisted = now - this._conflictSince > 120000;
161
+ if (persisted && this.ownerChatId && now - this._conflictAlertAt > 3600000) {
162
+ this._conflictAlertAt = now;
163
+ this._conflictAlerted = true;
164
+ Promise.resolve(this.bot.sendMessage(
165
+ this.ownerChatId,
166
+ "⚠️ Another poller has held my Telegram token for over 2 minutes — likely a dev checkout, a debugger run, or another host using this token. I hold the instance lock, so I'm staying up and retrying every 60s; messages may lag until it stops.",
167
+ )).catch(() => {});
159
168
  }
160
169
  if (this._conflictTimer) return; // a paused retry is already queued
161
- console.error("409 Conflict: another poller holds this token — pausing 15s (ghost polls clear in <1min; exiting only if this persists >2min).");
170
+ const pauseMs = persisted ? 60000 : 15000;
171
+ console.error(`409 Conflict: another poller holds this token — pausing ${Math.round(pauseMs / 1000)}s, then retrying (we hold the instance lock; never exiting).`);
162
172
  // Stop hammering now; the timer below dials back in.
163
173
  Promise.resolve(this.bot.stopPolling({ cancel: true, reason: "409 conflict backoff" })).catch(() => {});
164
174
  this._conflictTimer = setTimeout(async () => {
@@ -168,8 +178,14 @@ class TelegramAdapter {
168
178
  this._conflictClearTimer = setTimeout(() => {
169
179
  this._conflictClearTimer = null;
170
180
  this._conflictSince = 0;
181
+ if (this._conflictAlerted) {
182
+ this._conflictAlerted = false;
183
+ if (this.ownerChatId) {
184
+ Promise.resolve(this.bot.sendMessage(this.ownerChatId, "✅ The competing Telegram poller is gone — normal polling resumed.")).catch(() => {});
185
+ }
186
+ }
171
187
  }, 45000);
172
- }, 15000);
188
+ }, pauseMs);
173
189
  }
174
190
 
175
191
  _wireInbound() {
@@ -17,30 +17,46 @@ function pidAlive(pid) {
17
17
 
18
18
  function acquireSingleInstanceLock({ configDir, name = "bot" }) {
19
19
  const lockPath = path.join(configDir, `${name}.lock`);
20
- try {
21
- const prev = JSON.parse(fs.readFileSync(lockPath, "utf8"));
22
- if (prev && prev.pid && prev.pid !== process.pid && pidAlive(prev.pid)) {
23
- return { acquired: false, holder: prev, lockPath };
24
- }
25
- // Missing, corrupt, own-pid, or dead-pid (stale after SIGKILL): claim it.
26
- } catch (e) {}
27
- fs.writeFileSync(lockPath, JSON.stringify({
20
+ const payload = JSON.stringify({
28
21
  pid: process.pid,
29
22
  startedAt: new Date().toISOString(),
30
23
  entrypoint: process.argv[1] || "",
31
- }));
32
- let released = false;
33
- const release = () => {
34
- if (released) return;
35
- released = true;
24
+ });
25
+ // O_EXCL creation is the only atomic claim the filesystem offers. The old
26
+ // read-check-then-write had a TOCTOU hole: two processes booting together
27
+ // (launchd respawn racing a manual start) could both read "stale" and both
28
+ // write, each believing it held the lock. Now a stale/corrupt lock is
29
+ // unlinked and the claim retried; only a wx-create that succeeds counts.
30
+ for (let attempt = 0; attempt < 5; attempt++) {
36
31
  try {
37
- const cur = JSON.parse(fs.readFileSync(lockPath, "utf8"));
38
- // Never delete a lock a successor already owns.
39
- if (cur && cur.pid === process.pid) fs.unlinkSync(lockPath);
40
- } catch (e) {}
41
- };
42
- process.on("exit", release);
43
- return { acquired: true, lockPath, release };
32
+ fs.writeFileSync(lockPath, payload, { flag: "wx" });
33
+ let released = false;
34
+ const release = () => {
35
+ if (released) return;
36
+ released = true;
37
+ try {
38
+ const cur = JSON.parse(fs.readFileSync(lockPath, "utf8"));
39
+ // Never delete a lock a successor already owns.
40
+ if (cur && cur.pid === process.pid) fs.unlinkSync(lockPath);
41
+ } catch (e) {}
42
+ };
43
+ process.on("exit", release);
44
+ return { acquired: true, lockPath, release };
45
+ } catch (e) {
46
+ if (e.code !== "EEXIST") throw e;
47
+ }
48
+ let prev = null;
49
+ try { prev = JSON.parse(fs.readFileSync(lockPath, "utf8")); } catch (e) {}
50
+ if (prev && prev.pid && prev.pid !== process.pid && pidAlive(prev.pid)) {
51
+ return { acquired: false, holder: prev, lockPath };
52
+ }
53
+ // Corrupt, own-pid, or dead-pid (stale after SIGKILL): clear and retry.
54
+ try { fs.unlinkSync(lockPath); } catch (e) {}
55
+ }
56
+ // Five claim attempts lost to contenders — treat it as someone else's lock.
57
+ let holder = null;
58
+ try { holder = JSON.parse(fs.readFileSync(lockPath, "utf8")); } catch (e) {}
59
+ return { acquired: false, holder, lockPath };
44
60
  }
45
61
 
46
62
  module.exports = { acquireSingleInstanceLock, pidAlive };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inetafrica/open-claudia",
3
- "version": "3.0.2",
3
+ "version": "3.0.3",
4
4
  "description": "An always-on, provider-agnostic coding-agent harness for Claude Code and OpenAI Codex via chat",
5
5
  "main": "bot.js",
6
6
  "bin": {
@@ -32,10 +32,10 @@ assert.doesNotMatch(setup, /Your Claude Code bot is connected|Description=Claude
32
32
 
33
33
  const pkg = JSON.parse(read("package.json"));
34
34
  assert.match(pkg.description, /provider-agnostic coding-agent harness/i);
35
- // 3.0.2 approved by Sumeet 2026-07-12 ("Yeh do it and push it out" — peak
36
- // context metric restored, Telegram long-message chunking so dream summaries
37
- // deliver; CHANGELOG documents it as v3.0.2).
38
- assert.strictEqual(pkg.version, "3.0.2", "release version must remain unchanged without explicit approval");
35
+ // 3.0.3 approved by Sumeet 2026-07-12 ("Yes please" to patching the double-
36
+ // poller bug as v3.0.3 — atomic single-instance lock, 409 handler never exits
37
+ // while holding the lock, throttled owner alert; CHANGELOG documents it).
38
+ assert.strictEqual(pkg.version, "3.0.3", "release version must remain unchanged without explicit approval");
39
39
  for (const keyword of ["claude", "codex", "coding-agent", "provider-agnostic"]) {
40
40
  assert.ok(pkg.keywords.includes(keyword), `package keyword missing: ${keyword}`);
41
41
  }