telecoder 0.0.0-stage → 1.2.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.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Who may use this bot, beyond the ids written into `.env`.
3
+ *
4
+ * `ALLOWED_USER_IDS` is read once at startup, so every new person costs an edit
5
+ * and a restart — which is the wrong shape for a bot shared with friends, where
6
+ * the natural moment to grant access is the moment someone turns up in the
7
+ * group. This module is the mutable half of the allow-list: an admin admits
8
+ * someone, it persists, and it takes effect immediately.
9
+ *
10
+ * The two halves are deliberately asymmetric. Ids from `.env` are the operator's
11
+ * standing decision and cannot be revoked from chat — a `/deny` that appeared to
12
+ * work and then un-did itself on the next restart is worse than one that says
13
+ * where the id actually lives. Ids admitted here can be revoked here.
14
+ *
15
+ * ## Why a "seen" list exists
16
+ *
17
+ * There is no Bot API call that turns a `@username` into a user id.
18
+ * `getChatAdministrators` returns full user objects but only for a group's
19
+ * admins; nothing enumerates ordinary members. So the only usernames this bot
20
+ * can ever resolve are the ones it has watched go by — a message sent, or a
21
+ * `new_chat_members` service update — and `/allow @someone` is a lookup into
22
+ * that history rather than a query to Telegram.
23
+ *
24
+ * Ids are the identity everywhere; usernames are a convenience for typing.
25
+ * Telegram usernames can be dropped and re-claimed by someone else, so a
26
+ * username is re-resolved on every use and never stored as the thing being
27
+ * allowed.
28
+ *
29
+ * ## Why each bot has its own
30
+ *
31
+ * `/allow` answers who can use this bot. Bots on one machine can differ in who
32
+ * their `.env` lets in and in the workspace they open, and a first guest is what
33
+ * switches on a bot's guardrails, so a guest let into one must not reach the
34
+ * others. Each bot is also its own process, and sharing a file meant each one
35
+ * rewrote it from the copy it loaded at startup: a `/deny` on one bot was undone
36
+ * by the next save on another.
37
+ */
38
+ import * as path from 'path';
39
+ import { z } from 'zod';
40
+ import { BOT_ID, config } from '../config.js';
41
+ import { ensureStateDir, getStateDir, readSeededJsonFile, writeJsonFile } from './json-store.js';
42
+ /**
43
+ * How many observed-but-not-admitted people to remember. Enough that a name
44
+ * mentioned in yesterday's conversation still resolves, small enough that the
45
+ * file stays a file; the oldest sighting is dropped first.
46
+ */
47
+ const MAX_SEEN = 200;
48
+ const admittedSchema = z.object({
49
+ id: z.number(),
50
+ username: z.string().optional(),
51
+ name: z.string().optional(),
52
+ admittedAt: z.string(),
53
+ admittedBy: z.number(),
54
+ });
55
+ const seenSchema = z.object({
56
+ id: z.number(),
57
+ username: z.string().optional(),
58
+ name: z.string().optional(),
59
+ chatId: z.number().optional(),
60
+ seenAt: z.string(),
61
+ });
62
+ const rosterSchema = z.object({
63
+ admitted: z.array(admittedSchema).default([]),
64
+ seen: z.array(seenSchema).default([]),
65
+ });
66
+ const LABEL = 'UserRoster';
67
+ /**
68
+ * Resolved on use rather than at import. The state directory hangs off the home
69
+ * directory, and binding that into a module-level constant makes the first
70
+ * `import` of this file a filesystem decision — which is both untestable and a
71
+ * side effect nothing asked for.
72
+ */
73
+ function rosterFile() {
74
+ return path.join(getStateDir(), `user-roster-${BOT_ID}.json`);
75
+ }
76
+ /** The single file every bot shared before rosters were per-bot. */
77
+ function sharedRosterFile() {
78
+ return path.join(getStateDir(), 'user-roster.json');
79
+ }
80
+ let admitted = [];
81
+ let seen = [];
82
+ let loaded = false;
83
+ function load() {
84
+ if (loaded)
85
+ return;
86
+ ensureStateDir(getStateDir(), LABEL);
87
+ const data = readSeededJsonFile(rosterFile(), sharedRosterFile(), rosterSchema, LABEL);
88
+ admitted = data?.admitted ?? [];
89
+ seen = data?.seen ?? [];
90
+ loaded = true;
91
+ }
92
+ function save(opts) {
93
+ writeJsonFile(rosterFile(), { admitted, seen }, LABEL, opts);
94
+ }
95
+ /** Normalise a username for comparison: no leading `@`, case-insensitive. */
96
+ function normaliseUsername(value) {
97
+ return value.replace(/^@/, '').toLowerCase();
98
+ }
99
+ /** A human label for a user, preferring the display name over the handle. */
100
+ /**
101
+ * The fields the roster keeps, taken off a Telegram user.
102
+ *
103
+ * Lives here rather than in the middleware that first needed it because two
104
+ * gates now build identities — the door and the group role check — and a
105
+ * second copy would be one drift away from two different ideas of a name.
106
+ */
107
+ export function identifyUser(user) {
108
+ const name = [user.first_name, user.last_name].filter(Boolean).join(' ');
109
+ return {
110
+ id: user.id,
111
+ ...(user.username ? { username: user.username } : {}),
112
+ ...(name ? { name } : {}),
113
+ };
114
+ }
115
+ export function describeUser(user) {
116
+ if (user.name && user.username)
117
+ return `${user.name} (@${user.username})`;
118
+ if (user.name)
119
+ return user.name;
120
+ if (user.username)
121
+ return `@${user.username}`;
122
+ return `id ${user.id}`;
123
+ }
124
+ /** Ids allowed by `.env`. Separated out because they are not revocable here. */
125
+ export function envAllowedIds() {
126
+ return [...config.ALLOWED_USER_IDS];
127
+ }
128
+ /** Every id that may use this bot: the `.env` list plus everyone admitted since. */
129
+ export function allAllowedUserIds() {
130
+ load();
131
+ const ids = new Set(config.ALLOWED_USER_IDS);
132
+ for (const user of admitted)
133
+ ids.add(user.id);
134
+ return [...ids];
135
+ }
136
+ /**
137
+ * The allow-list check the auth middleware runs. Replaces a direct
138
+ * `config.ALLOWED_USER_IDS.includes()` so an admitted user is let through
139
+ * without a restart.
140
+ */
141
+ export function isAllowedUser(userId) {
142
+ if (userId === undefined)
143
+ return false;
144
+ if (config.ALLOWED_USER_IDS.includes(userId))
145
+ return true;
146
+ load();
147
+ return admitted.some((user) => user.id === userId);
148
+ }
149
+ /**
150
+ * Everyone admitted from chat, most recent first.
151
+ *
152
+ * Array order is the ordering, not the timestamp: entries are appended as they
153
+ * are added, and two things that happen in the same millisecond carry identical
154
+ * ISO strings, which would leave a comparator to fall back on stable order
155
+ * anyway — and get it backwards.
156
+ */
157
+ export function listAdmitted() {
158
+ load();
159
+ return [...admitted].reverse();
160
+ }
161
+ /** Everyone observed but not currently allowed, most recently seen first. */
162
+ export function listPending() {
163
+ load();
164
+ return [...seen].reverse().filter((user) => !isAllowedUser(user.id));
165
+ }
166
+ /**
167
+ * Record that a user was observed, so `/allow @them` can resolve later. Called
168
+ * for allowed and unknown users alike — the allowed ones are how an admin looks
169
+ * up someone already in, and it keeps display names fresh.
170
+ */
171
+ export function noteSeenUser(user, chatId) {
172
+ load();
173
+ const entry = {
174
+ id: user.id,
175
+ ...(user.username ? { username: user.username } : {}),
176
+ ...(user.name ? { name: user.name } : {}),
177
+ ...(chatId !== undefined ? { chatId } : {}),
178
+ seenAt: new Date().toISOString(),
179
+ };
180
+ const existing = seen.findIndex((s) => s.id === user.id);
181
+ const unchanged = existing !== -1 &&
182
+ seen[existing].username === entry.username &&
183
+ seen[existing].name === entry.name &&
184
+ seen[existing].chatId === entry.chatId;
185
+ // Every message from an allowed user would otherwise be a disk write. Only
186
+ // the first sighting and a genuine change to the identifying fields are
187
+ // worth persisting; a refreshed timestamp on its own is not.
188
+ if (unchanged)
189
+ return;
190
+ if (existing !== -1)
191
+ seen.splice(existing, 1);
192
+ seen.push(entry);
193
+ if (seen.length > MAX_SEEN)
194
+ seen = seen.slice(seen.length - MAX_SEEN);
195
+ save();
196
+ }
197
+ /**
198
+ * Resolve `@username`, a bare username, or a numeric id against what the bot
199
+ * has seen. A numeric id resolves even for someone never observed — an admin
200
+ * who already knows the id should not have to wait for a message first.
201
+ */
202
+ export function resolveUser(query) {
203
+ load();
204
+ const trimmed = query.trim();
205
+ if (!trimmed)
206
+ return undefined;
207
+ if (/^-?\d+$/.test(trimmed)) {
208
+ const id = parseInt(trimmed, 10);
209
+ const known = seen.find((user) => user.id === id) ?? admitted.find((user) => user.id === id);
210
+ return known ? { id, username: known.username, name: known.name } : { id };
211
+ }
212
+ const wanted = normaliseUsername(trimmed);
213
+ if (!wanted)
214
+ return undefined;
215
+ // Newest sighting wins: a username that has changed hands should resolve to
216
+ // whoever is carrying it now, not whoever carried it first. `seen` is append
217
+ // ordered — noteSeenUser re-pushes on every change — so the last match is the
218
+ // most recent one, without depending on timestamps being distinct.
219
+ for (let i = seen.length - 1; i >= 0; i--) {
220
+ const candidate = seen[i];
221
+ if (candidate.username && normaliseUsername(candidate.username) === wanted) {
222
+ return { id: candidate.id, username: candidate.username, name: candidate.name };
223
+ }
224
+ }
225
+ const fromRoster = admitted.find((user) => user.username && normaliseUsername(user.username) === wanted);
226
+ return fromRoster ? { id: fromRoster.id, username: fromRoster.username, name: fromRoster.name } : undefined;
227
+ }
228
+ /**
229
+ * Add a user to the roster. Reports `already-allowed` for someone who could
230
+ * already use the bot, whether from `.env` or from an earlier `/allow`, so the
231
+ * caller can say so rather than claiming to have changed something.
232
+ *
233
+ * Write failures propagate: this is reported to an admin as "they're in", and
234
+ * saying that when nothing reached disk would strand a guest at the next restart.
235
+ */
236
+ export function admitUser(user, admittedBy) {
237
+ load();
238
+ if (isAllowedUser(user.id))
239
+ return 'already-allowed';
240
+ admitted.push({
241
+ id: user.id,
242
+ ...(user.username ? { username: user.username } : {}),
243
+ ...(user.name ? { name: user.name } : {}),
244
+ admittedAt: new Date().toISOString(),
245
+ admittedBy,
246
+ });
247
+ save({ rethrow: true });
248
+ return 'admitted';
249
+ }
250
+ /**
251
+ * Remove a user from the roster.
252
+ *
253
+ * `env-configured` means the id is in `ALLOWED_USER_IDS`, where this module
254
+ * cannot reach it. Reporting that beats deleting a roster entry that was never
255
+ * what was granting access, which would look like it worked until the user
256
+ * carried on using the bot.
257
+ */
258
+ export function revokeUser(userId) {
259
+ load();
260
+ if (config.ALLOWED_USER_IDS.includes(userId))
261
+ return 'env-configured';
262
+ const index = admitted.findIndex((user) => user.id === userId);
263
+ if (index === -1)
264
+ return 'not-allowed';
265
+ admitted.splice(index, 1);
266
+ save({ rethrow: true });
267
+ return 'revoked';
268
+ }
269
+ /** Test seam — production loads once and keeps the roster for the process. */
270
+ export function resetRosterCache() {
271
+ admitted = [];
272
+ seen = [];
273
+ loaded = false;
274
+ }
275
+ //# sourceMappingURL=user-roster.js.map
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Verbosity tier system.
3
+ *
4
+ * Maps a single `quiet | normal | verbose | debug` level (per-chat or env
5
+ * default) onto a set of individual rendering flags. Explicit env vars win
6
+ * over the tier; the per-chat preference wins over the env default.
7
+ */
8
+ import { config, explicitFlags } from '../config.js';
9
+ import { userPreferences } from '../providers/user-preferences.js';
10
+ export const VERBOSITY_LEVELS = ['quiet', 'normal', 'verbose', 'debug'];
11
+ export function isValidVerbosityLevel(level) {
12
+ return VERBOSITY_LEVELS.includes(level);
13
+ }
14
+ export const VERBOSITY_INFO = [
15
+ {
16
+ id: 'quiet',
17
+ label: '🔇 Quiet',
18
+ description: 'Answer only. Suppresses completion pings and the usage footer; keeps compaction warnings.',
19
+ },
20
+ {
21
+ id: 'normal',
22
+ label: '💬 Normal',
23
+ description: 'Default. Tool status, task list, background tasks, completion ping.',
24
+ },
25
+ {
26
+ id: 'verbose',
27
+ label: '🔊 Verbose',
28
+ description: 'Adds the per-turn usage footer, untruncated tool inputs, and a consolidated action log that streams tool results and diffs live, then collapses to a Telegraph link at the end of each turn.',
29
+ },
30
+ {
31
+ id: 'debug',
32
+ label: '🐛 Debug',
33
+ description: 'Verbose mode with extended limits: longer tool result previews (40 lines) and diffs (50 lines) in the consolidated action log. Same end-of-turn collapse to a Telegraph link. Reserved for upcoming thinking blocks, hook events, and SDK internals.',
34
+ },
35
+ ];
36
+ function defaultsForLevel(level) {
37
+ switch (level) {
38
+ case 'quiet':
39
+ return {
40
+ showUsageFooter: false,
41
+ notifyCompaction: true,
42
+ terminalUiVerbose: false,
43
+ sendCompletionPing: false,
44
+ showToolResults: false,
45
+ toolResultMaxLines: 0,
46
+ toolResultMaxChars: 0,
47
+ showDiffs: false,
48
+ diffMaxLines: 0,
49
+ useActionLog: false,
50
+ };
51
+ case 'normal':
52
+ return {
53
+ showUsageFooter: false,
54
+ notifyCompaction: true,
55
+ terminalUiVerbose: false,
56
+ sendCompletionPing: true,
57
+ showToolResults: false,
58
+ toolResultMaxLines: 0,
59
+ toolResultMaxChars: 0,
60
+ showDiffs: false,
61
+ diffMaxLines: 0,
62
+ useActionLog: false,
63
+ };
64
+ case 'verbose':
65
+ return {
66
+ showUsageFooter: true,
67
+ notifyCompaction: true,
68
+ terminalUiVerbose: true,
69
+ sendCompletionPing: true,
70
+ showToolResults: true,
71
+ toolResultMaxLines: 20,
72
+ toolResultMaxChars: 2000,
73
+ showDiffs: true,
74
+ diffMaxLines: 25,
75
+ useActionLog: true,
76
+ };
77
+ case 'debug':
78
+ return {
79
+ showUsageFooter: true,
80
+ notifyCompaction: true,
81
+ terminalUiVerbose: true,
82
+ sendCompletionPing: true,
83
+ showToolResults: true,
84
+ toolResultMaxLines: 40,
85
+ toolResultMaxChars: 4000,
86
+ showDiffs: true,
87
+ diffMaxLines: 50,
88
+ useActionLog: true,
89
+ };
90
+ }
91
+ }
92
+ /**
93
+ * Resolve the active verbosity level for a chat. Per-chat preference wins
94
+ * over the env-level VERBOSITY_DEFAULT.
95
+ */
96
+ export function getVerbosityLevel(chatId) {
97
+ return userPreferences.getVerbosity(chatId) ?? config.VERBOSITY_DEFAULT;
98
+ }
99
+ /**
100
+ * Resolve effective rendering flags for a chat. An explicit env override
101
+ * wins over the tier default; an unset env var defers to the tier.
102
+ */
103
+ export function resolveVerbosityFlags(chatId) {
104
+ const tier = defaultsForLevel(getVerbosityLevel(chatId));
105
+ return {
106
+ showUsageFooter: explicitFlags.CONTEXT_SHOW_USAGE ? config.CONTEXT_SHOW_USAGE : tier.showUsageFooter,
107
+ notifyCompaction: explicitFlags.CONTEXT_NOTIFY_COMPACTION ? config.CONTEXT_NOTIFY_COMPACTION : tier.notifyCompaction,
108
+ terminalUiVerbose: explicitFlags.TERMINAL_UI_VERBOSE ? config.TERMINAL_UI_VERBOSE : tier.terminalUiVerbose,
109
+ sendCompletionPing: tier.sendCompletionPing,
110
+ showToolResults: tier.showToolResults,
111
+ toolResultMaxLines: tier.toolResultMaxLines,
112
+ toolResultMaxChars: tier.toolResultMaxChars,
113
+ showDiffs: tier.showDiffs,
114
+ diffMaxLines: tier.diffMaxLines,
115
+ useActionLog: tier.useActionLog,
116
+ };
117
+ }
118
+ //# sourceMappingURL=verbosity.js.map
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Whether the build this process loaded is the latest one, for /version.
3
+ *
4
+ * Same code or not comes from comparing hashes (scripts/source-hash.mjs), never
5
+ * from commits. Git only describes a difference once there is one, and says how
6
+ * this checkout stands against the branch it tracks.
7
+ *
8
+ * Any of it can fail to run: no git, no source beside the build, no network.
9
+ * Those are results of their own, so a check that never happened can't pass for
10
+ * a clean one.
11
+ */
12
+ import { execFile } from 'child_process';
13
+ const LOCAL_TIMEOUT_MS = 5_000;
14
+ /** ssh to GitHub takes about 1.5s, and past this nobody is still waiting on the reply. */
15
+ const REMOTE_TIMEOUT_MS = 8_000;
16
+ /** What git answers, or null when it fails, for whatever reason. */
17
+ function git(root, args, { timeout = LOCAL_TIMEOUT_MS, env } = {}) {
18
+ return new Promise((resolve) => {
19
+ execFile('git', args, { cwd: root, timeout, env }, (error, stdout) => {
20
+ if (error) {
21
+ // Not the message: git's stderr can carry a remote's URL, credentials included.
22
+ console.debug(`[Version] git ${args[0]} failed (${error.code ?? error.signal})`);
23
+ resolve(null);
24
+ return;
25
+ }
26
+ resolve(stdout.trim());
27
+ });
28
+ });
29
+ }
30
+ /** The module that holds the hash. Found at run time because dist/ may have no scripts/ beside it. */
31
+ async function loadSourceHash() {
32
+ try {
33
+ return await import(new URL('../../scripts/source-hash.mjs', import.meta.url).href);
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ /** How many commits since `build` touch `paths`, or null when that count wouldn't mean anything. */
40
+ async function commitsSince(root, build, paths) {
41
+ // A build with uncommitted changes in it already holds some of what came next.
42
+ if (!build.commit || build.dirty)
43
+ return null;
44
+ // Rewritten history or another branch: everything since the fork would count as new.
45
+ if (await git(root, ['merge-base', '--is-ancestor', build.commit, 'HEAD']) === null)
46
+ return null;
47
+ const count = await git(root, ['rev-list', '--count', `${build.commit}..HEAD`, '--', ...paths]);
48
+ return count === null ? null : Number(count);
49
+ }
50
+ /** Compare `running`, the build this process loaded, with the code in `root`. `latest` is the last build on disk. */
51
+ export async function checkCode(running, latest, root) {
52
+ if (!running)
53
+ return { kind: 'unstamped' };
54
+ const source = await loadSourceHash();
55
+ if (!source || !running.sourceHash)
56
+ return { kind: 'unknown' };
57
+ let current;
58
+ try {
59
+ current = source.hashSource(root);
60
+ }
61
+ catch {
62
+ return { kind: 'unknown' };
63
+ }
64
+ if (running.sourceHash === current)
65
+ return { kind: 'current' };
66
+ if (latest?.sourceHash === current)
67
+ return { kind: 'not-loaded' };
68
+ const [commits, changes] = await Promise.all([
69
+ commitsSince(root, running, source.SOURCE_PATHS),
70
+ git(root, ['--no-optional-locks', 'status', '--porcelain', '--', ...source.SOURCE_PATHS]),
71
+ ]);
72
+ return { kind: 'changed', commits, uncommitted: Boolean(changes) };
73
+ }
74
+ /** The current branch's upstream, or null on a detached HEAD or with none configured. */
75
+ async function trackedBranch(root) {
76
+ const branch = await git(root, ['symbolic-ref', '-q', 'HEAD']);
77
+ if (!branch)
78
+ return null;
79
+ const upstream = await git(root, [
80
+ 'for-each-ref', '--format=%(upstream:remotename) %(upstream:remoteref) %(upstream:short)', branch,
81
+ ]);
82
+ const [remote, remoteRef, ref] = upstream?.split(' ') ?? [];
83
+ return remote && remoteRef && ref ? { remote, remoteRef, ref } : null;
84
+ }
85
+ /** An environment where asking for a passphrase or a host key fails instead of waiting for an answer. */
86
+ async function promptFreeEnv(root) {
87
+ const ssh = process.env.GIT_SSH_COMMAND || await git(root, ['config', '--get', 'core.sshCommand']) || 'ssh';
88
+ return {
89
+ ...process.env,
90
+ GIT_TERMINAL_PROMPT: '0',
91
+ GIT_SSH_COMMAND: `${ssh} -o BatchMode=yes -o ConnectTimeout=5`,
92
+ };
93
+ }
94
+ /**
95
+ * How the checkout in `root` stands against the branch it tracks.
96
+ *
97
+ * ls-remote and not fetch: this writes nothing to a checkout that sessions may
98
+ * be working in. So the remote's latest commit may be one this checkout has
99
+ * never seen, which is enough to say it's behind but not by how much.
100
+ */
101
+ export async function checkRemote(root, timeout = REMOTE_TIMEOUT_MS) {
102
+ const tracked = await trackedBranch(root);
103
+ if (!tracked)
104
+ return { kind: 'untracked' };
105
+ const { remote, remoteRef, ref } = tracked;
106
+ const env = await promptFreeEnv(root);
107
+ const listing = await git(root, ['ls-remote', '--', remote, remoteRef], { timeout, env });
108
+ if (listing === null)
109
+ return { kind: 'unreachable', remote, ref };
110
+ const tip = listing.split('\n').map((line) => line.split('\t')).find(([, name]) => name === remoteRef)?.[0];
111
+ if (!tip)
112
+ return { kind: 'untracked' };
113
+ const head = await git(root, ['rev-parse', 'HEAD']);
114
+ if (tip === head)
115
+ return { kind: 'same', ref };
116
+ if (await git(root, ['cat-file', '-e', `${tip}^{commit}`]) === null)
117
+ return { kind: 'behind', ref };
118
+ const base = await git(root, ['merge-base', tip, 'HEAD']);
119
+ if (base === head)
120
+ return { kind: 'behind', ref };
121
+ if (base !== tip)
122
+ return { kind: 'diverged', ref };
123
+ return { kind: 'ahead', ref, commits: Number(await git(root, ['rev-list', '--count', `${tip}..HEAD`])) };
124
+ }
125
+ const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
126
+ export function describeCodeCheck(check) {
127
+ switch (check.kind) {
128
+ case 'unstamped':
129
+ return "❓ No build stamp, so there's nothing to compare: this is running from source, or from a build that skipped it.";
130
+ case 'unknown':
131
+ return "❓ Couldn't compare this build with the code here, so it may or may not be the latest.";
132
+ case 'current':
133
+ return '✅ This is the current code.';
134
+ case 'not-loaded':
135
+ return '⚠️ A newer build is on disk but not loaded. /restartbot picks it up.';
136
+ case 'changed': {
137
+ const { commits, uncommitted } = check;
138
+ const parts = [
139
+ ...(commits ? [plural(commits, 'newer commit')] : []),
140
+ ...(uncommitted ? ['uncommitted changes'] : []),
141
+ ];
142
+ if (parts.length === 0)
143
+ return '⚠️ The code here has changed since this build. /rebuildbot picks it up.';
144
+ const them = commits === 1 && !uncommitted ? 'it' : 'them';
145
+ return `⚠️ The code here has ${parts.join(' and ')}. /rebuildbot picks ${them} up.`;
146
+ }
147
+ }
148
+ }
149
+ /** Null when there's nothing to say: a checkout that tracks nothing can't be behind anything. */
150
+ export function describeRemoteCheck(check) {
151
+ switch (check.kind) {
152
+ case 'untracked':
153
+ return null;
154
+ case 'unreachable':
155
+ return `❓ Couldn't reach ${check.remote}, so ${check.ref} wasn't checked.`;
156
+ case 'same':
157
+ return `✅ ${check.ref} has nothing newer.`;
158
+ case 'ahead':
159
+ return `⬆️ This checkout is ${plural(check.commits, 'commit')} ahead of ${check.ref}.`;
160
+ case 'behind':
161
+ return `⚠️ ${check.ref} has commits this checkout doesn't. git pull, then /rebuildbot.`;
162
+ case 'diverged':
163
+ return `⚠️ This checkout and ${check.ref} have diverged.`;
164
+ }
165
+ }
166
+ //# sourceMappingURL=version-check.js.map
@@ -0,0 +1,44 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { config } from '../config.js';
4
+ export function getWorkspaceRoot() {
5
+ const root = config.WORKSPACE_DIR || process.env.HOME || process.cwd();
6
+ return path.resolve(root);
7
+ }
8
+ /**
9
+ * Check if target path is within root directory.
10
+ * Uses realpathSync to resolve symlinks and prevent symlink-based traversal.
11
+ */
12
+ export function isPathWithinRoot(root, target) {
13
+ try {
14
+ // Resolve symlinks to get actual paths
15
+ const resolvedRoot = fs.realpathSync(root);
16
+ let resolvedTarget;
17
+ try {
18
+ resolvedTarget = fs.realpathSync(target);
19
+ }
20
+ catch {
21
+ // Target doesn't exist — just normalize the path
22
+ resolvedTarget = path.resolve(target);
23
+ }
24
+ return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);
25
+ }
26
+ catch {
27
+ // Root doesn't exist — reject all paths
28
+ return false;
29
+ }
30
+ }
31
+ export function resolvePathWithinRoot(root, target) {
32
+ let resolved;
33
+ try {
34
+ resolved = fs.realpathSync(target);
35
+ }
36
+ catch {
37
+ resolved = path.resolve(target);
38
+ }
39
+ if (!isPathWithinRoot(root, resolved)) {
40
+ return null;
41
+ }
42
+ return resolved;
43
+ }
44
+ //# sourceMappingURL=workspace-guard.js.map