@inetafrica/open-claudia 2.2.20 → 2.2.22

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/.env.example CHANGED
@@ -17,7 +17,7 @@ KAZEE_DEBUG_EVENTS=
17
17
  WORKSPACE=/path/to/your/workspace
18
18
  CLAUDE_PATH=/path/to/claude
19
19
  # Default Claude Code model when users haven't selected one with /model.
20
- CLAUDE_MODEL=claude-opus-4-8
20
+ CLAUDE_MODEL=claude-fable-5
21
21
  CURSOR_PATH=
22
22
  CODEX_PATH=
23
23
  AUTO_COMPACT_TOKENS=280000
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## v2.2.22
4
+ - **Token economy: stable prompt-cache prefix (R1).** The per-turn churning lines — `Vault: unlocked/locked`, `Session: resuming/new`, and the full pending-tasks tree — moved out of the `--append-system-prompt` block into a "Runtime state (current turn)" header prepended to each user prompt (`promptWithDynamicContext`). The appended system prompt precedes the entire conversation in every API request, so any byte that changed between turns invalidated Anthropic's prompt-cache prefix and re-billed the whole history at 1.25x write price instead of 0.1x read price; on long sessions this churn was the dominant bot cost. `buildSystemPrompt()` is now byte-stable within a session (remaining interpolations — project path, channel, voice, team/speaker — only change on rare events), and the dynamic state rides at the end of the request where it is always uncached anyway. Transcripts still log the bare prompt; Cursor/Codex paths unchanged.
5
+ - Compaction is much less lossy. Three changes to `compactActiveSession`:
6
+ - **Two-tier brief**: every compaction brief is now archived verbatim to `~/.open-claudia/briefs/<project-prefix>-<timestamp>.md` before seeding the fresh session, and the seed prompt tells the new session where the archive lives. Repeated compactions previously re-summarized prior summaries, blurring older facts each round — now the new session can reread earlier briefs at full fidelity instead of guessing. The summary prompt also drops length pressure ("length is NOT a constraint") since the brief is archived anyway. The summarizer additionally emits a `=== CONDENSED SEED ===` section (300-500 words: goal, next step, gated actions, load-bearing paths); when present and the full brief made it to disk, only the condensed section is seeded into the live context — cutting the per-turn context cost of the carried summary — while the detailed brief stays on disk for on-demand reads. Missing marker or failed archive falls back to seeding the full text exactly as before.
7
+ - **Machine-generated repo state**: the seed prompt now includes a git-generated block (branch, dirty files, ahead/behind upstream, last commit) for the session cwd — or its direct child repos (capped at 10) when the cwd itself isn't a git repo. Repo state was exactly the class of fact summarizers hallucinated or dropped; this block is produced by `git`, not model recall, and the seed says to trust it over the summary on conflict.
8
+ - **Verbatim recency tail**: the last 6 user/assistant turns (1,500 chars each, compact-summary/seed entries filtered out) are carried into the seed raw from the project transcript. Users most often reference the exchange immediately before compaction ("as I said", "do that thing you showed"), which summaries flatten; now those turns survive as exact quotes. Captured before the summarizer runs so the tail reflects real conversation.
9
+ - All three collectors are fail-soft: any error (missing transcript, unreadable repo, git timeout) degrades to the previous behaviour rather than blocking compaction.
10
+
11
+ ## v2.2.21
12
+ - Add Claude Fable 5 (`claude-fable-5`) to the Claude model picker and make it the default Claude Code model used when no per-user model override is selected. The default can still be overridden with `CLAUDE_MODEL`.
13
+
3
14
  ## v2.2.19
4
15
  - Add Claude Opus 4.8 (`claude-opus-4-8`) to the Claude model picker and make it the default Claude Code model used when no per-user model override is selected. The default can still be overridden with `CLAUDE_MODEL`, now documented in `.env.example`.
5
16
 
package/bot-agent.js CHANGED
@@ -78,7 +78,7 @@ const CHAT_ID = CHAT_IDS[0]; // Primary owner chat for crons/notifications
78
78
  const WORKSPACE = config.WORKSPACE;
79
79
  const CLAUDE_PATH = config.CLAUDE_PATH;
80
80
  const CURSOR_PATH = config.CURSOR_PATH || null;
81
- const DEFAULT_CLAUDE_MODEL = config.CLAUDE_MODEL || process.env.CLAUDE_MODEL || "claude-opus-4-8";
81
+ const DEFAULT_CLAUDE_MODEL = config.CLAUDE_MODEL || process.env.CLAUDE_MODEL || "claude-fable-5";
82
82
 
83
83
  // Resolve Cursor Agent CLI (optional)
84
84
  let resolvedCursorPath = CURSOR_PATH;
@@ -1661,9 +1661,9 @@ bot.onText(/\/model$/, (msg) => {
1661
1661
  [{ text: "GPT-5.4", callback_data: "m:gpt-5.4-medium" }, { text: "GPT-5.4 High", callback_data: "m:gpt-5.4-high" }],
1662
1662
  [{ text: "Auto", callback_data: "m:auto" }, { text: "Default", callback_data: "m:default" }],
1663
1663
  ] : [
1664
- [{ text: "Opus 4.8", callback_data: "m:claude-opus-4-8" }, { text: "Opus 4.7", callback_data: "m:claude-opus-4-7" }],
1665
- [{ text: "Sonnet", callback_data: "m:sonnet" }, { text: "Haiku", callback_data: "m:haiku" }],
1666
- [{ text: "Default", callback_data: "m:default" }],
1664
+ [{ text: "Fable 5", callback_data: "m:claude-fable-5" }, { text: "Opus 4.8", callback_data: "m:claude-opus-4-8" }],
1665
+ [{ text: "Opus 4.7", callback_data: "m:claude-opus-4-7" }, { text: "Sonnet", callback_data: "m:sonnet" }],
1666
+ [{ text: "Haiku", callback_data: "m:haiku" }, { text: "Default", callback_data: "m:default" }],
1667
1667
  ];
1668
1668
  const label = settings.backend === "cursor" ? "Cursor Agent" : "Claude Code";
1669
1669
  send(`${label} model: ${settings.model || "default"}\n\nOr type /model <name> for any model.`, { keyboard: { inline_keyboard: keyboard } });
package/core/config.js CHANGED
@@ -47,7 +47,7 @@ const WORKSPACE = config.WORKSPACE;
47
47
  const CLAUDE_PATH = config.CLAUDE_PATH;
48
48
  const CURSOR_PATH = config.CURSOR_PATH || null;
49
49
  const CODEX_PATH = config.CODEX_PATH || null;
50
- const DEFAULT_CLAUDE_MODEL = config.CLAUDE_MODEL || process.env.CLAUDE_MODEL || "claude-opus-4-8";
50
+ const DEFAULT_CLAUDE_MODEL = config.CLAUDE_MODEL || process.env.CLAUDE_MODEL || "claude-fable-5";
51
51
  const AUTO_COMPACT_TOKENS = parseInt(config.AUTO_COMPACT_TOKENS || process.env.AUTO_COMPACT_TOKENS || "380000", 10);
52
52
  const MIN_COMPACT_INTERVAL_MS = parseInt(config.MIN_COMPACT_INTERVAL_MS || process.env.MIN_COMPACT_INTERVAL_MS || "1800000", 10);
53
53
  const PROJECT_TRANSCRIPTS = configTruthy(config.PROJECT_TRANSCRIPTS || process.env.PROJECT_TRANSCRIPTS, true);
package/core/handlers.js CHANGED
@@ -535,7 +535,10 @@ register({
535
535
  const rows = [];
536
536
  rows.push([{ text: "── Claude ──", callback_data: "noop" }]);
537
537
  rows.push([
538
+ { text: "Fable 5", callback_data: "mb:claude:claude-fable-5" },
538
539
  { text: "Opus 4.8", callback_data: "mb:claude:claude-opus-4-8" },
540
+ ]);
541
+ rows.push([
539
542
  { text: "Opus 4.7", callback_data: "mb:claude:claude-opus-4-7" },
540
543
  { text: "Opus 4.6", callback_data: "mb:claude:claude-opus-4-6" },
541
544
  ]);
package/core/runner.js CHANGED
@@ -3,14 +3,17 @@
3
3
  // progress UI. All IO routes through core/io.js so the same runner
4
4
  // works on every channel.
5
5
 
6
- const { spawn } = require("child_process");
6
+ const fs = require("fs");
7
+ const path = require("path");
8
+ const { spawn, execFileSync } = require("child_process");
7
9
  const {
8
10
  CLAUDE_PATH, DEFAULT_CLAUDE_MODEL, resolvedCursorPath, resolvedCodexPath,
9
11
  AUTO_COMPACT_TOKENS, MIN_COMPACT_INTERVAL_MS, MAX_PROCESS_TIMEOUT, COMPACT_SUMMARY_TIMEOUT, botSubprocessEnv,
12
+ CONFIG_DIR,
10
13
  } = require("./config");
11
14
  const { currentState, saveState, recordSession, userOwnsClaudeSession } = require("./state");
12
15
  const { chatContext, currentChannelId, currentAdapter } = require("./context");
13
- const { buildSystemPrompt } = require("./system-prompt");
16
+ const { buildSystemPrompt, promptWithDynamicContext } = require("./system-prompt");
14
17
  const { redactSensitive } = require("./redact");
15
18
  const { send, editMessage, sendVoice, splitMessage } = require("./io");
16
19
  const { textToVoice, TTS_CMD } = require("./media");
@@ -130,7 +133,9 @@ function buildClaudeArgs(prompt, opts = {}) {
130
133
  if (settings.permissionMode) args.push("--permission-mode", settings.permissionMode);
131
134
  else args.push("--dangerously-skip-permissions");
132
135
  if (settings.worktree) args.push("--worktree");
133
- args.push(prompt);
136
+ // Dynamic state rides in the user prompt so the appended system prompt
137
+ // stays byte-stable across turns and the prompt-cache prefix survives.
138
+ args.push(promptWithDynamicContext(prompt));
134
139
  return args;
135
140
  }
136
141
 
@@ -237,29 +242,177 @@ function compactSummaryPrompt() {
237
242
  "",
238
243
  "Do not include: secrets, raw tokens, full file dumps, or chat pleasantries.",
239
244
  "Be concrete. Names of files, commands, flags, tags, and commits beat paraphrase. If a fact was load-bearing in this session, write it down verbatim.",
245
+ "Length is NOT a constraint for the brief — it is archived verbatim to disk and reread later. When in doubt, include the fact rather than dropping it for brevity.",
246
+ "",
247
+ "After the brief, output a final section that begins with a line containing exactly:",
248
+ "=== CONDENSED SEED ===",
249
+ "Below that marker write a tight condensed version, 300-500 words max: current goal, exact next step, hard constraints and gated actions (pushes, deploys, anything awaiting user approval), unresolved questions, and the load-bearing paths/IDs. The condensed section lives in the active context every single turn, so optimize it for token economy; the full brief above is read from disk only when needed, so optimize it for completeness.",
240
250
  ].join("\n");
241
251
  }
242
252
 
243
- function compactSeedPrompt(summary) {
244
- return [
253
+ const CONDENSED_MARKER_RE = /^[=#*\s]*CONDENSED SEED[=#*\s]*$/i;
254
+
255
+ function splitCompactionBrief(summary) {
256
+ const text = String(summary || "");
257
+ const lines = text.split("\n");
258
+ let markerIdx = -1;
259
+ for (let i = lines.length - 1; i >= 0; i--) {
260
+ if (lines[i].length <= 60 && CONDENSED_MARKER_RE.test(lines[i])) { markerIdx = i; break; }
261
+ }
262
+ if (markerIdx === -1) return { fullBrief: text, condensed: null };
263
+ const condensed = lines.slice(markerIdx + 1).join("\n").trim();
264
+ const fullBrief = lines.slice(0, markerIdx).join("\n").trim();
265
+ if (condensed.length < 80 || !fullBrief) return { fullBrief: text, condensed: null };
266
+ return { fullBrief, condensed };
267
+ }
268
+
269
+ function compactSeedPrompt(summary, extras = {}) {
270
+ const parts = [
245
271
  "This is a compacted continuation of a previous Open Claudia session.",
246
272
  "Treat the following summary as the prior conversation context. Do not repeat it back unless asked.",
247
273
  "Continue from this state in future turns.",
248
274
  "",
249
275
  "Before telling the user you lack context on something they reference:",
250
276
  "1. Check the summary below.",
251
- "2. Search the project transcript with `open-claudia transcript-window <pattern>`.",
277
+ "2. Read the full archived brief on disk (path given below, when present) — it is the detailed version of this summary.",
278
+ "3. Search the project transcript with `open-claudia transcript-window <pattern>`.",
252
279
  " It returns each hit with surrounding turns of context, capped per turn so it stays bounded.",
253
280
  " Useful flags: --before N / --after N (default 2), --max-turns K (default 10), --regex.",
254
281
  " Fall back to `grep -n -C 5 <pattern> <transcript-path>` (path in your system prompt under",
255
282
  " 'Project Transcript Memory') only if the helper does not fit your search.",
256
- "Only ask the user if both turn up nothing.",
283
+ "Only ask the user if all of these turn up nothing.",
257
284
  "",
258
285
  "If a fact in the summary contradicts current repo state (a file path, a command, a flag, a version), trust what you observe now and proceed without flagging it unless the user asks.",
259
286
  "",
260
- "Compacted summary:",
287
+ extras.condensed
288
+ ? "Compacted summary (condensed — the full detailed brief is archived on disk at the path below):"
289
+ : "Compacted summary:",
261
290
  summary,
262
- ].join("\n");
291
+ ];
292
+ if (extras.briefPath) {
293
+ parts.push(
294
+ "",
295
+ `Full detailed brief for this compaction: ${extras.briefPath}`,
296
+ `Read it before re-deriving or re-asking anything the summary covers only thinly. Older compaction briefs for this project live in the same directory (${path.dirname(extras.briefPath)}, same filename prefix) — repeated compaction blurs older facts, so consult them for older work before falling back to transcript search.`
297
+ );
298
+ }
299
+ if (extras.repoFacts) {
300
+ parts.push(
301
+ "",
302
+ "Machine-generated repo state at compaction time (produced by git, not model recall — trust it over the summary if they disagree):",
303
+ extras.repoFacts
304
+ );
305
+ }
306
+ if (extras.recentTurns) {
307
+ parts.push(
308
+ "",
309
+ "Verbatim final turns before compaction (raw, most recent last). The user is most likely to reference these; treat them as exact quotes, unlike the summary above:",
310
+ extras.recentTurns
311
+ );
312
+ }
313
+ return parts.join("\n");
314
+ }
315
+
316
+ const BRIEFS_DIR = path.join(CONFIG_DIR, "briefs");
317
+
318
+ function briefArchivePrefix(state = currentState()) {
319
+ const tinfo = transcriptProjectInfo(state);
320
+ if (tinfo && tinfo.transcriptPath) return path.basename(tinfo.transcriptPath, ".jsonl");
321
+ const channel = String(currentChannelId() || "unknown").replace(/[^a-zA-Z0-9_-]/g, "_");
322
+ return `channel-${channel}`;
323
+ }
324
+
325
+ function archiveCompactionBrief(summary, state = currentState()) {
326
+ try {
327
+ fs.mkdirSync(BRIEFS_DIR, { recursive: true, mode: 0o700 });
328
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
329
+ const filePath = path.join(BRIEFS_DIR, `${briefArchivePrefix(state)}-${stamp}.md`);
330
+ const header = [
331
+ `# Compaction brief — ${new Date().toISOString()}`,
332
+ state.currentSession ? `Project: ${state.currentSession.name} (${state.currentSession.dir})` : null,
333
+ "",
334
+ "",
335
+ ].filter((line) => line !== null).join("\n");
336
+ fs.writeFileSync(filePath, header + summary + "\n", { mode: 0o600 });
337
+ return filePath;
338
+ } catch (e) {
339
+ console.warn(`[compact] brief archive failed: ${redactSensitive(e.message)}`);
340
+ return null;
341
+ }
342
+ }
343
+
344
+ function gitFactsForRepo(repoDir) {
345
+ const run = (args) => execFileSync("git", ["-C", repoDir, ...args], {
346
+ timeout: 4000, stdio: ["ignore", "pipe", "ignore"],
347
+ }).toString().trim();
348
+ const branch = run(["rev-parse", "--abbrev-ref", "HEAD"]);
349
+ const dirty = run(["status", "--porcelain"]).split("\n").filter(Boolean);
350
+ const lastCommit = run(["log", "-1", "--format=%h %s"]);
351
+ let upstream;
352
+ try {
353
+ const [behind, ahead] = run(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"]).split(/\s+/);
354
+ upstream = (ahead === "0" && behind === "0") ? "in sync with upstream" : `${ahead} ahead / ${behind} behind upstream`;
355
+ } catch (e) {
356
+ upstream = "no upstream";
357
+ }
358
+ const dirtyNote = dirty.length
359
+ ? `${dirty.length} uncommitted: ${dirty.slice(0, 8).map((l) => l.trim().replace(/^\S+\s+/, "")).join(", ")}${dirty.length > 8 ? ", …" : ""}`
360
+ : "clean";
361
+ return `${repoDir} — branch ${branch}, ${dirtyNote}, ${upstream}, last commit: ${lastCommit}`;
362
+ }
363
+
364
+ function collectRepoStateFacts(cwd) {
365
+ try {
366
+ let repos = [];
367
+ if (fs.existsSync(path.join(cwd, ".git"))) {
368
+ repos = [cwd];
369
+ } else {
370
+ repos = fs.readdirSync(cwd, { withFileTypes: true })
371
+ .filter((d) => d.isDirectory() && fs.existsSync(path.join(cwd, d.name, ".git")))
372
+ .slice(0, 10)
373
+ .map((d) => path.join(cwd, d.name));
374
+ }
375
+ const lines = [];
376
+ for (const repo of repos) {
377
+ try { lines.push(`- ${gitFactsForRepo(repo)}`); } catch (e) { /* unreadable repo — skip */ }
378
+ }
379
+ return lines.length ? lines.join("\n") : null;
380
+ } catch (e) {
381
+ return null;
382
+ }
383
+ }
384
+
385
+ function collectRecentTurns(state = currentState(), maxTurns = 6, maxCharsPerTurn = 1500) {
386
+ try {
387
+ const tinfo = transcriptProjectInfo(state);
388
+ if (!tinfo || !tinfo.transcriptPath || !fs.existsSync(tinfo.transcriptPath)) return null;
389
+ const stat = fs.statSync(tinfo.transcriptPath);
390
+ const readBytes = Math.min(stat.size, 256 * 1024);
391
+ if (!readBytes) return null;
392
+ const fd = fs.openSync(tinfo.transcriptPath, "r");
393
+ const buf = Buffer.alloc(readBytes);
394
+ try {
395
+ fs.readSync(fd, buf, 0, readBytes, stat.size - readBytes);
396
+ } finally {
397
+ fs.closeSync(fd);
398
+ }
399
+ const lines = buf.toString("utf8").split("\n").filter((l) => l.trim());
400
+ const turns = [];
401
+ for (let i = lines.length - 1; i >= 0 && turns.length < maxTurns; i--) {
402
+ let entry;
403
+ try { entry = JSON.parse(lines[i]); } catch (e) { continue; /* partial first line of the byte window */ }
404
+ if (entry.role !== "user" && entry.role !== "assistant") continue;
405
+ const label = entry.metadata && entry.metadata.label;
406
+ if (label === "compact-summary" || label === "compact-seed") continue;
407
+ const text = String(entry.text || "").trim();
408
+ if (!text) continue;
409
+ const clipped = text.length > maxCharsPerTurn ? `${text.slice(0, maxCharsPerTurn)} …[truncated]` : text;
410
+ turns.push(`[${entry.role} @ ${entry.timestamp || "?"}]\n${clipped}`);
411
+ }
412
+ return turns.length ? turns.reverse().join("\n\n") : null;
413
+ } catch (e) {
414
+ return null;
415
+ }
263
416
  }
264
417
 
265
418
  function formatProgress(text, tools, currentTool, elapsed, toolDetail) {
@@ -380,6 +533,7 @@ async function compactActiveSession(cwd, opts = {}) {
380
533
 
381
534
  state.isCompacting = true;
382
535
  let summary;
536
+ const recentTurns = collectRecentTurns(state);
383
537
  try {
384
538
  if (opts.notify) await send(opts.message || "Context is getting large, compacting first so this stays fast…");
385
539
  const summaryRun = await runClaudeCapture(compactSummaryPrompt(), cwd, { resumeSessionId: oldSessionId, skipAutoCompact: true, label: "compact-summary", timeoutMs: COMPACT_SUMMARY_TIMEOUT });
@@ -393,7 +547,12 @@ async function compactActiveSession(cwd, opts = {}) {
393
547
  saveState();
394
548
  }
395
549
 
396
- const seedRun = await runClaudeCapture(compactSeedPrompt(summary), cwd, { fresh: true, skipAutoCompact: true, label: "compact-seed" });
550
+ const { fullBrief, condensed } = splitCompactionBrief(summary);
551
+ const briefPath = archiveCompactionBrief(fullBrief, state);
552
+ // Only seed with the condensed version when the full text actually made it to disk.
553
+ const seedSummary = (condensed && briefPath) ? condensed : (condensed ? `${fullBrief}\n\n${condensed}` : fullBrief);
554
+ const repoFacts = collectRepoStateFacts(cwd);
555
+ const seedRun = await runClaudeCapture(compactSeedPrompt(seedSummary, { briefPath, condensed: !!(condensed && briefPath), repoFacts, recentTurns }), cwd, { fresh: true, skipAutoCompact: true, label: "compact-seed" });
397
556
  const newSessionId = seedRun.sessionId || state[sessionKey];
398
557
  if (newSessionId) state[sessionKey] = newSessionId;
399
558
  state.isFirstMessage = false;
@@ -739,7 +898,7 @@ async function runClaudeSilent(prompt, cwd, label) {
739
898
  return new Promise((resolve) => {
740
899
  const args = ["-p", "--output-format", "text", "--verbose",
741
900
  "--append-system-prompt", buildSystemPrompt(),
742
- "--dangerously-skip-permissions", prompt];
901
+ "--dangerously-skip-permissions", promptWithDynamicContext(prompt)];
743
902
  const proc = spawn(CLAUDE_PATH, args, {
744
903
  cwd, env: claudeSubprocessEnv(),
745
904
  stdio: ["ignore", "pipe", "pipe"],
@@ -766,6 +925,11 @@ module.exports = {
766
925
  getActiveSessionKey,
767
926
  shouldAutoCompact,
768
927
  effectiveCompactThreshold,
928
+ compactSeedPrompt,
929
+ splitCompactionBrief,
930
+ archiveCompactionBrief,
931
+ collectRepoStateFacts,
932
+ collectRecentTurns,
769
933
  formatProgress,
770
934
  preflightClaudeAuthMessage,
771
935
  claudeEmptyFailureMessage,
@@ -28,17 +28,6 @@ function buildSystemPrompt() {
28
28
  ? (adapter.type === "kazee" ? "Kazee Chat" : adapter.type === "telegram" ? "Telegram" : adapter.type)
29
29
  : "Telegram";
30
30
 
31
- let pendingTasksBlock = "";
32
- if (adapter && channelId) {
33
- try {
34
- const pending = tasksStore.pendingSummary(adapter.id, channelId);
35
- if (pending.length > 0) {
36
- const tree = tasksStore.formatTree(adapter.id, channelId, { showIds: true });
37
- pendingTasksBlock = `\n## Pending tasks\nYou may be resuming prior work. Before starting anything new, review these and decide whether to continue, update, or abandon them. Mark a subtask in_progress when you actually start it and completed when it's done.\n\n${tree}\n`;
38
- }
39
- } catch (e) {}
40
- }
41
-
42
31
  let teamBlock = "";
43
32
  let currentSpeakerBlock = "";
44
33
  try {
@@ -115,8 +104,7 @@ ${soul}
115
104
  - Interface: ${channelLabel} chat through Open Claudia.
116
105
  - Active project path: ${state.currentSession ? state.currentSession.dir : "none"}
117
106
  - Voice notes: ${hasVoice ? "enabled" : "disabled"}
118
- - Vault: ${vault.isUnlocked() ? "unlocked" : "locked"}
119
- - Session: ${state.lastSessionId ? "resuming existing conversation" : "new conversation"}
107
+ - Vault status, session state, and any pending tasks arrive in a "Runtime state" block at the top of each user message, not here.
120
108
 
121
109
  ## Stable Local Paths
122
110
  - Bot code: ${path.join(BOT_DIR, "bot.js")}
@@ -127,7 +115,7 @@ ${soul}
127
115
  - Received user files directory: ${FILES_DIR}
128
116
 
129
117
  ${transcriptPointerNote(state)}
130
- ${currentSpeakerBlock}${teamBlock}${pendingTasksBlock}${slashCommandsBlock}${channelFormattingBlock}
118
+ ${currentSpeakerBlock}${teamBlock}${slashCommandsBlock}${channelFormattingBlock}
131
119
  ## Delivery
132
120
  Reply normally in your final answer. To send a file, image, or voice clip back to the current chat, run the bot CLI from inside this task — channel context is already in the env:
133
121
  - \`open-claudia send-file <path> [caption]\` — any document/binary
@@ -150,7 +138,7 @@ Persistent todo list with plans + subtasks (per channel; survives compaction and
150
138
 
151
139
  Note: any \`<system-reminder>\` you see about "task tools" / TaskCreate / TaskUpdate is from the underlying Claude Code harness — that's a different, ephemeral todo system. Open Claudia work belongs in \`open-claudia task\` (the persistent, channel-scoped one). Don't double-track.
152
140
 
153
- Use a plan when work is likely to outlive a single turn — i.e. it may hit a compaction, a restart, or a scheduled wakeup before completing, or its progress is something the user will want to see between turns. The plan is a parent task whose children are the steps. As you work, mark each subtask in_progress when you begin and completed when done — this is how a resumed turn sees where you left off. If pending tasks already exist when you start a turn they will be shown under "## Pending tasks" above; check them first.
141
+ Use a plan when work is likely to outlive a single turn — i.e. it may hit a compaction, a restart, or a scheduled wakeup before completing, or its progress is something the user will want to see between turns. The plan is a parent task whose children are the steps. As you work, mark each subtask in_progress when you begin and completed when done — this is how a resumed turn sees where you left off. If pending tasks already exist when you start a turn they will be shown under "## Pending tasks" inside the Runtime state block at the top of the user message; check them first.
154
142
 
155
143
  Skip the plan for work that visibly completes within the current turn (e.g. running a few CLI commands in sequence and replying). A plan there is overhead the user has to read past.
156
144
 
@@ -214,4 +202,39 @@ If you tell the user "I'll check back in N minutes" or "I'll run this every morn
214
202
  `.trim();
215
203
  }
216
204
 
217
- module.exports = { loadSoul, buildSystemPrompt };
205
+ // Per-turn churning state. Lives in the user prompt, NOT the appended
206
+ // system prompt: the system prompt precedes the whole conversation in
207
+ // every API request, so any byte that changes between turns invalidates
208
+ // the prompt-cache prefix and re-bills the full history at write price
209
+ // instead of 0.1x read price. Keep buildSystemPrompt() byte-stable
210
+ // within a session; put anything that flips between turns here.
211
+ function buildDynamicContextBlock() {
212
+ const state = currentState();
213
+ const adapter = currentAdapter();
214
+ const channelId = currentChannelId();
215
+ const lines = [
216
+ "## Runtime state (current turn)",
217
+ `- Vault: ${vault.isUnlocked() ? "unlocked" : "locked"}`,
218
+ `- Session: ${state.lastSessionId ? "resuming existing conversation" : "new conversation"}`,
219
+ ];
220
+ if (adapter && channelId) {
221
+ try {
222
+ const pending = tasksStore.pendingSummary(adapter.id, channelId);
223
+ if (pending.length > 0) {
224
+ const tree = tasksStore.formatTree(adapter.id, channelId, { showIds: true });
225
+ lines.push("", "## Pending tasks", "You may be resuming prior work. Before starting anything new, review these and decide whether to continue, update, or abandon them. Mark a subtask in_progress when you actually start it and completed when it's done.", "", tree);
226
+ }
227
+ } catch (e) {}
228
+ }
229
+ return lines.join("\n");
230
+ }
231
+
232
+ function promptWithDynamicContext(prompt) {
233
+ try {
234
+ return `${buildDynamicContextBlock()}\n\nCurrent user request:\n${prompt}`;
235
+ } catch (e) {
236
+ return prompt;
237
+ }
238
+ }
239
+
240
+ module.exports = { loadSoul, buildSystemPrompt, buildDynamicContextBlock, promptWithDynamicContext };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inetafrica/open-claudia",
3
- "version": "2.2.20",
3
+ "version": "2.2.22",
4
4
  "description": "Your always-on AI coding assistant — Claude Code, Cursor Agent, and OpenAI Codex via Telegram or Kazee Chat",
5
5
  "main": "bot.js",
6
6
  "bin": {