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,141 @@
1
+ /**
2
+ * Which files may be sent out of the machine from chat — `/file` as a
3
+ * download, `/telegraph <path>` as a public page.
4
+ *
5
+ * Both used to accept any path under WORKSPACE_DIR, which defaults to $HOME.
6
+ * On a shared bot that let any guest fetch `~/.claude/.credentials.json` or
7
+ * `~/.ssh/id_rsa`, and `/telegraph` would then publish it. Two rules now:
8
+ *
9
+ * - The scope guard's credential/bot-state denylist applies to everyone,
10
+ * admins included. An admin who wants their own SSH key has a shell; a chat
11
+ * command that sends one is only ever a mistake or someone else's request.
12
+ * - Guests are confined to the chat's project directory. Admins keep the
13
+ * whole workspace, since they already choose which project a chat is in.
14
+ *
15
+ * Containment is judged on the real path, so a symlink in the project that
16
+ * points at `~/.ssh` is followed before anything is decided. The denylist is
17
+ * checked on both the typed path and the real one.
18
+ */
19
+ import * as fs from 'fs';
20
+ import * as os from 'os';
21
+ import * as path from 'path';
22
+ import { isSensitivePath } from '../claude/scope-guard.js';
23
+ import { config } from '../config.js';
24
+ import { isAdmin } from '../utils/admins.js';
25
+ import { getWorkspaceRoot } from '../utils/workspace-guard.js';
26
+ import { EntityText } from '../telegram/entities.js';
27
+ import { replyFormatted } from '../telegram/send.js';
28
+ /** Expand `~`, then resolve against `cwd` unless already absolute. */
29
+ function toAbsolute(raw, cwd) {
30
+ let value = raw.trim();
31
+ if (value === '~')
32
+ value = os.homedir();
33
+ else if (value.startsWith('~/'))
34
+ value = path.join(os.homedir(), value.slice(2));
35
+ return path.isAbsolute(value) ? path.resolve(value) : path.resolve(cwd, value);
36
+ }
37
+ function within(root, target) {
38
+ return target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
39
+ }
40
+ /**
41
+ * Decide whether `raw` names a file that may leave the machine.
42
+ *
43
+ * Containment is checked before existence, so someone confined to a project
44
+ * can't use the answers to probe what exists outside it.
45
+ */
46
+ export function resolveShareablePath(raw, opts) {
47
+ const lexical = toAbsolute(raw, opts.cwd);
48
+ if (isSensitivePath(lexical))
49
+ return { ok: false, reason: 'sensitive' };
50
+ let real;
51
+ try {
52
+ real = fs.realpathSync(lexical);
53
+ }
54
+ catch {
55
+ real = undefined;
56
+ }
57
+ let realRoot;
58
+ try {
59
+ realRoot = fs.realpathSync(opts.root);
60
+ }
61
+ catch {
62
+ return { ok: false, reason: 'outside-root' };
63
+ }
64
+ if (!within(realRoot, real ?? lexical))
65
+ return { ok: false, reason: 'outside-root' };
66
+ if (real === undefined)
67
+ return { ok: false, reason: 'not-found' };
68
+ if (isSensitivePath(real))
69
+ return { ok: false, reason: 'sensitive' };
70
+ let stat;
71
+ try {
72
+ stat = fs.statSync(real);
73
+ }
74
+ catch {
75
+ return { ok: false, reason: 'not-found' };
76
+ }
77
+ if (stat.isDirectory())
78
+ return { ok: false, reason: 'directory' };
79
+ return { ok: true, path: real };
80
+ }
81
+ /**
82
+ * The root a user's paths are confined to: the whole workspace for an admin,
83
+ * the chat's project for anyone else.
84
+ */
85
+ export function shareRootFor(userId, projectDir) {
86
+ return isAdmin(userId) ? getWorkspaceRoot() : projectDir;
87
+ }
88
+ /**
89
+ * Resolve a path typed in chat against the session's project, reporting any
90
+ * refusal to the chat. Returns the real path to send, or null.
91
+ */
92
+ export async function resolveShareableFile(ctx, projectDir, raw) {
93
+ const root = shareRootFor(ctx.from?.id, projectDir);
94
+ const result = resolveShareablePath(raw, { cwd: projectDir, root });
95
+ if (result.ok)
96
+ return result.path;
97
+ const shown = raw.trim();
98
+ switch (result.reason) {
99
+ case 'sensitive':
100
+ console.log(`[file-access] REFUSED credential path for user:${ctx.from?.id ?? 'unknown'}`);
101
+ await replyFormatted(ctx, new EntityText()
102
+ .add('🔒 ').code(shown)
103
+ .add(' is a credential or bot-state path (SSH, cloud and Claude credentials, .env files and the like), and those are never sent from chat.')
104
+ .build());
105
+ break;
106
+ case 'outside-root':
107
+ await replyFormatted(ctx, isAdmin(ctx.from?.id)
108
+ ? new EntityText().add('❌ File path must be within workspace root: ').code(root).build()
109
+ : new EntityText().add("❌ You can only get files from this chat's project: ").code(root).build());
110
+ break;
111
+ case 'not-found':
112
+ await replyFormatted(ctx, new EntityText().add('❌ File not found: ').code(shown).build());
113
+ break;
114
+ case 'directory':
115
+ await replyFormatted(ctx, new EntityText().add("❌ That's a directory, not a file: ").code(shown).build());
116
+ break;
117
+ }
118
+ return null;
119
+ }
120
+ /**
121
+ * `/telegraph <path>` publishes a file as a public telegra.ph page, readable by
122
+ * anyone with the link and impossible to take down. That is an owner's call,
123
+ * so it is admin-only, and it needs TELEGRAPH_ENABLED like every other way of
124
+ * publishing. Replies to the chat and returns true when the publish is refused.
125
+ */
126
+ export async function refuseFilePublish(ctx) {
127
+ if (!isAdmin(ctx.from?.id)) {
128
+ console.log(`[file-access] DENIED /telegraph <path> for user:${ctx.from?.id ?? 'unknown'}`);
129
+ await ctx.reply('🔒 Publishing a file to Telegraph is admin-only — the page is public to anyone with the link. Use /file to get it as a download instead.');
130
+ return true;
131
+ }
132
+ if (!config.TELEGRAPH_ENABLED) {
133
+ await replyFormatted(ctx, new EntityText()
134
+ .add('📄 Telegraph is off. Set ').code('TELEGRAPH_ENABLED=true')
135
+ .add(' in .env to publish files as pages — they are public to anyone with the link. Use /file to get it as a download instead.')
136
+ .build());
137
+ return true;
138
+ }
139
+ return false;
140
+ }
141
+ //# sourceMappingURL=file-access.js.map
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Handing out access from chat: `/allow`, `/deny`, `/users`, `/members`.
3
+ *
4
+ * These exist because the alternative is editing `ALLOWED_USER_IDS` and
5
+ * restarting, and because the obvious shape — "just type their @username" —
6
+ * cannot work on its own. No Bot API method resolves a username to a user id.
7
+ * `getChatAdministrators` returns full user objects, but only for a group's
8
+ * admins; nothing lists ordinary members at all. A bot only ever learns a
9
+ * username by watching one go past.
10
+ *
11
+ * So they lean on the same two moves the bot already makes: it records everyone
12
+ * it sees in a shared group, and it posts a tap-to-approve card when a stranger
13
+ * turns up. Typing a username is the fallback, not the primary path — `/allow`
14
+ * as a reply to someone's message is exact, works for the many Telegram users
15
+ * who have no username at all, and cannot be aimed at the wrong person by a
16
+ * handle that changed hands.
17
+ *
18
+ * There are two access layers, and `/allow` means the nearer one:
19
+ *
20
+ * - In an allow-listed group it makes someone a *contributor there*. That is
21
+ * the least surprising reading of a command typed in a room — and the
22
+ * narrower grant, since it does not also hand out a private channel with
23
+ * the bot that nobody else in the group can see.
24
+ * - In a DM it admits them to the *global roster*, which is what makes them a
25
+ * contributor in every group at once.
26
+ *
27
+ * `/users` reads back the first, `/members` the second.
28
+ */
29
+ import { config } from '../../../config.js';
30
+ import { EntityText, joinMessages, plain } from '../../../telegram/entities.js';
31
+ import { markdownToEntities } from '../../../telegram/markdown.js';
32
+ import { replyFormatted } from '../../../telegram/send.js';
33
+ import { getAdminIds, getApproverIds, isApprover, isAdmin } from '../../../utils/admins.js';
34
+ import { admitUser, describeUser, envAllowedIds, listAdmitted, listPending, resolveUser, revokeUser, } from '../../../utils/user-roster.js';
35
+ import { grantAccess, groupDefaultIsContributor, listGroupAccess, resolveRole, revokeAccess, } from '../../access/group-access.js';
36
+ import { ACCESS_CALLBACK_PREFIX, clearAccessCooldown } from '../../../telegram/access-request.js';
37
+ import { sanitizeError } from '../../../utils/sanitize.js';
38
+ import { replyMd } from './shared.js';
39
+ /** The argument text after the command word, or '' when there is none. */
40
+ function argsOf(ctx) {
41
+ const text = ctx.message?.text ?? '';
42
+ return text.split(' ').slice(1).join(' ').trim();
43
+ }
44
+ /**
45
+ * The allow-listed group this update is in, or undefined for anywhere else.
46
+ *
47
+ * This is what decides whether `/allow` means "here" or "everywhere", so it is
48
+ * deliberately strict: an unlisted group is not a scope anyone has agreed to
49
+ * hand out access in.
50
+ */
51
+ function groupScope(ctx) {
52
+ const chatId = ctx.chat?.id;
53
+ const type = ctx.chat?.type;
54
+ if (chatId === undefined)
55
+ return undefined;
56
+ if (type !== 'group' && type !== 'supergroup')
57
+ return undefined;
58
+ return config.ALLOWED_GROUP_IDS.includes(chatId) ? chatId : undefined;
59
+ }
60
+ /**
61
+ * Who a command is aimed at: the author of the replied-to message, else the
62
+ * `@username` or numeric id in the arguments.
63
+ *
64
+ * The reply wins when both are present. It is the unambiguous one, and someone
65
+ * who replies *and* types a name has most likely typed the name of the person
66
+ * they are replying to.
67
+ */
68
+ function targetOf(ctx) {
69
+ const replied = ctx.message?.reply_to_message?.from;
70
+ if (replied && !replied.is_bot) {
71
+ const name = [replied.first_name, replied.last_name].filter(Boolean).join(' ');
72
+ return {
73
+ user: {
74
+ id: replied.id,
75
+ ...(replied.username ? { username: replied.username } : {}),
76
+ ...(name ? { name } : {}),
77
+ },
78
+ };
79
+ }
80
+ const query = argsOf(ctx);
81
+ if (!query)
82
+ return {};
83
+ return { user: resolveUser(query), query };
84
+ }
85
+ /** What to say when a handle names nobody the bot has ever seen. */
86
+ function unresolvedMessage(query) {
87
+ return new EntityText()
88
+ .add(`❌ I don't know ${query}.`)
89
+ .newline(2)
90
+ .add('Telegram gives bots no way to look up a username, so I can only match ' +
91
+ 'people I have already seen post here. Ask them to send a message in the ' +
92
+ 'group — then reply to it with ')
93
+ .code('/allow')
94
+ .add(', which is exact.')
95
+ .build();
96
+ }
97
+ /**
98
+ * A reply that opens with someone's name. The name is theirs to choose, so it
99
+ * goes in as text; `rest` (standard markdown, static) carries the formatting.
100
+ */
101
+ function aboutUser(prefix, user, rest) {
102
+ return new EntityText()
103
+ .add(`${prefix} ${describeUser(user)}`)
104
+ .append(inlineMarkdown(rest))
105
+ .build();
106
+ }
107
+ /**
108
+ * Static markdown rendered inline, keeping the leading space a paragraph would
109
+ * lose: `rest` in {@link aboutUser} continues a sentence.
110
+ */
111
+ function inlineMarkdown(markdown) {
112
+ const lead = markdown.match(/^ */)?.[0] ?? '';
113
+ return new EntityText().add(lead).append(markdownToEntities(markdown)).build();
114
+ }
115
+ export async function handleAllow(ctx) {
116
+ const { user, query } = targetOf(ctx);
117
+ if (!user) {
118
+ if (query) {
119
+ await replyFormatted(ctx, unresolvedMessage(query));
120
+ return;
121
+ }
122
+ await replyMd(ctx, 'Usage: reply to their message with `/allow`, or `/allow @username`.\n\n' +
123
+ 'Replying is exact and works for people with no username.');
124
+ return;
125
+ }
126
+ const by = ctx.from?.id;
127
+ if (by === undefined)
128
+ return;
129
+ const chatId = groupScope(ctx);
130
+ if (chatId !== undefined) {
131
+ try {
132
+ const previous = grantAccess(chatId, user.id, { username: user.username, grantedBy: by });
133
+ clearAccessCooldown(user.id);
134
+ console.log(`[access] ${by} made ${describeUser(user)} a contributor in ${chatId}`);
135
+ const already = previous === 'contributor'
136
+ ? ' They already could — now it survives a change of default.'
137
+ : '';
138
+ await replyFormatted(ctx, aboutUser('✅', user, ` can send prompts to the agent in this chat.${already}\n\n` +
139
+ '⚠️ That means running commands on this machine, in whichever project the ' +
140
+ 'session is pointed at.'));
141
+ }
142
+ catch (error) {
143
+ // The store rethrows a failed write precisely so this doesn't confirm a
144
+ // change that won't survive the next restart.
145
+ console.error('[access] grant failed:', sanitizeError(error));
146
+ await replyMd(ctx, '❌ Could not save that — nothing changed. Check the bot logs.');
147
+ }
148
+ return;
149
+ }
150
+ try {
151
+ const result = admitUser(user, by);
152
+ clearAccessCooldown(user.id);
153
+ if (result === 'already-allowed') {
154
+ await replyFormatted(ctx, aboutUser('✅', user, ' can already use this bot.'));
155
+ return;
156
+ }
157
+ console.log(`[access] ${by} admitted ${describeUser(user)}`);
158
+ await replyFormatted(ctx, aboutUser('✅', user, ' is in — as a **guest**, so their requests go ' +
159
+ 'through the charter judge and the permission gate.'));
160
+ }
161
+ catch (error) {
162
+ console.error('[access] admit failed:', sanitizeError(error));
163
+ await replyMd(ctx, '❌ Could not save the roster — they are **not** allowed in. Check the bot logs.');
164
+ }
165
+ }
166
+ export async function handleDeny(ctx) {
167
+ const { user, query } = targetOf(ctx);
168
+ if (!user) {
169
+ if (query) {
170
+ await replyFormatted(ctx, unresolvedMessage(query));
171
+ return;
172
+ }
173
+ await replyMd(ctx, 'Usage: reply to their message with `/deny`, or `/deny @username`.');
174
+ return;
175
+ }
176
+ if (isAdmin(user.id)) {
177
+ await replyFormatted(ctx, aboutUser('🔒', user, ' is an **admin**. Remove them from ' +
178
+ '`ADMIN_USER_IDS` and `ALLOWED_USER_IDS` in the bot\'s `.env`, then restart.'));
179
+ return;
180
+ }
181
+ const by = ctx.from?.id;
182
+ const chatId = groupScope(ctx);
183
+ if (chatId !== undefined) {
184
+ try {
185
+ revokeAccess(chatId, user.id, { username: user.username, grantedBy: by });
186
+ clearAccessCooldown(user.id);
187
+ console.log(`[access] ${by} made ${describeUser(user)} a spectator in ${chatId}`);
188
+ await replyFormatted(ctx, aboutUser('🚫', user, ' is a **spectator** here — they can read along and talk ' +
189
+ 'to everyone, but the bot will ignore anything they address to it.\n\n' +
190
+ 'This covers **this chat**. If they are on the bot\'s global roster, `/deny` them in ' +
191
+ 'a DM to take that away too.'));
192
+ }
193
+ catch (error) {
194
+ console.error('[access] revoke failed:', sanitizeError(error));
195
+ await replyMd(ctx, '❌ Could not save that — they **still** have access here. Check the bot logs.');
196
+ }
197
+ return;
198
+ }
199
+ try {
200
+ const result = revokeUser(user.id);
201
+ clearAccessCooldown(user.id);
202
+ if (result === 'env-configured') {
203
+ await replyFormatted(ctx, aboutUser('🔒', user, ' is allowed by the bot\'s `.env`, which I can\'t ' +
204
+ 'edit. Remove their id from `ALLOWED_USER_IDS`' +
205
+ (isApprover(user.id) ? ' **and** `APPROVER_USER_IDS`' : '') +
206
+ ' and restart.' +
207
+ (isApprover(user.id)
208
+ ? '\n\nBoth lines matter: an id left in `APPROVER_USER_IDS` that ' +
209
+ '`ALLOWED_USER_IDS` no longer carries stops the bot from starting.'
210
+ : '')));
211
+ return;
212
+ }
213
+ if (result === 'not-allowed') {
214
+ await replyFormatted(ctx, aboutUser('✅', user, ' already had no access.'));
215
+ return;
216
+ }
217
+ console.log(`[access] ${ctx.from?.id} revoked ${describeUser(user)}`);
218
+ await replyFormatted(ctx, aboutUser('🚫', user, ' is out.'));
219
+ }
220
+ catch (error) {
221
+ console.error('[access] revoke failed:', sanitizeError(error));
222
+ await replyMd(ctx, '❌ Could not save the roster — they **still** have access. Check the bot logs.');
223
+ }
224
+ }
225
+ /** One roster line: name, handle and the id that is the real identity. */
226
+ function userLine(b, user) {
227
+ const label = user.name ?? (user.username ? `@${user.username}` : `id ${user.id}`);
228
+ const handle = user.name && user.username ? ` @${user.username}` : '';
229
+ b.newline().add(`• ${label}${handle} — `).code(String(user.id));
230
+ }
231
+ /** A blank line, then a bold section heading with its count. */
232
+ function section(b, heading, count) {
233
+ return b.newline(2).bold(heading).add(` (${count})`);
234
+ }
235
+ /** A roster line for a bare id, marking the reader's own. */
236
+ function idLine(b, id, self) {
237
+ b.newline().add('• ').code(String(id)).add(id === self ? ' — you' : '');
238
+ }
239
+ export async function handleUsers(ctx) {
240
+ const admins = getAdminIds();
241
+ const approvers = getApproverIds();
242
+ const env = envAllowedIds().filter((id) => !admins.includes(id) && !approvers.includes(id));
243
+ const admitted = listAdmitted();
244
+ const pending = listPending();
245
+ const self = ctx.from?.id;
246
+ const b = new EntityText().bold('Who can use this bot');
247
+ section(b, 'Admins', admins.length);
248
+ for (const id of admins)
249
+ idLine(b, id, self);
250
+ if (approvers.length > 0) {
251
+ section(b, 'Approvers', approvers.length);
252
+ for (const id of approvers)
253
+ idLine(b, id, self);
254
+ b.newline().italic('Guests who can answer someone else’s approval prompt, but not their own.');
255
+ }
256
+ if (env.length > 0) {
257
+ b.newline(2).wrap('bold', (h) => h.add('Guests from ').code('.env')).add(` (${env.length})`);
258
+ for (const id of env)
259
+ idLine(b, id, undefined);
260
+ }
261
+ section(b, 'Guests admitted here', admitted.length);
262
+ if (admitted.length === 0) {
263
+ b.newline().italic('none yet');
264
+ }
265
+ else {
266
+ for (const user of admitted)
267
+ userLine(b, user);
268
+ }
269
+ if (pending.length > 0) {
270
+ const shown = pending.slice(0, 10);
271
+ section(b, 'Seen but not allowed', pending.length);
272
+ for (const user of shown)
273
+ userLine(b, user);
274
+ if (pending.length > shown.length) {
275
+ b.newline().italic(`…and ${pending.length - shown.length} more`);
276
+ }
277
+ b.newline(2).add('Reply to one of their messages with ').code('/allow').add(' to let them in.');
278
+ }
279
+ await replyFormatted(ctx, b.build());
280
+ }
281
+ /** Who may drive the agent in this one group. The per-group half of /users. */
282
+ export async function handleMembers(ctx) {
283
+ const chatId = groupScope(ctx);
284
+ if (chatId === undefined) {
285
+ await replyMd(ctx, '`/members` lists access for one group chat — run it in the group itself.\n\n' +
286
+ 'Use `/users` for who can reach the bot at all.');
287
+ return;
288
+ }
289
+ const { allow, deny } = listGroupAccess(chatId);
290
+ const label = (m) => m.username
291
+ ? new EntityText().add(`@${m.username} (`).code(String(m.userId)).add(')').build()
292
+ : new EntityText().code(String(m.userId)).build();
293
+ // Anyone on the global roster is a contributor here without an entry in the
294
+ // store, so /members has to add them back in or it under-reports who can
295
+ // prompt. An explicit /deny still removes them from this group.
296
+ const admins = getAdminIds();
297
+ const listed = new Set([...allow, ...deny].map((m) => m.userId));
298
+ const implicit = [...envAllowedIds(), ...listAdmitted().map((u) => u.id)]
299
+ .filter((id) => !admins.includes(id) && !listed.has(id) && resolveRole(chatId, id) === 'contributor')
300
+ .map((id) => new EntityText().code(String(id)).add(' (roster)').build());
301
+ const contributors = [...allow.map(label), ...implicit];
302
+ /** `items` comma-separated, or a dash for none. */
303
+ const list = (items) => items.length > 0 ? joinMessages(items, ', ') : plain('—');
304
+ const b = new EntityText()
305
+ .bold('Access in this chat')
306
+ .add(' (')
307
+ .code(String(chatId))
308
+ .add(')')
309
+ .newline(2)
310
+ .add('Default for anyone not listed: ')
311
+ .bold(groupDefaultIsContributor() ? 'contributor' : 'spectator')
312
+ .newline(2)
313
+ .bold('Admins:')
314
+ .add(' ')
315
+ .append(list(admins.map((id) => new EntityText().code(String(id)).build())))
316
+ .newline()
317
+ .bold('Contributors:')
318
+ .add(' ')
319
+ .append(list(contributors))
320
+ .newline()
321
+ .bold('Spectators (explicit):')
322
+ .add(' ')
323
+ .append(list(deny.map(label)));
324
+ if (!groupDefaultIsContributor() && allow.length === 0) {
325
+ b.newline(2)
326
+ .add('Nobody has been granted here yet. Reply to someone with ')
327
+ .code('/allow')
328
+ .add(' to let them prompt the agent.');
329
+ }
330
+ await replyFormatted(ctx, b.build());
331
+ }
332
+ /**
333
+ * The Allow / Ignore buttons on an access card.
334
+ *
335
+ * Registered behind `adminOnly`, which answers the callback itself for anyone
336
+ * else — so reaching here means an admin tapped it.
337
+ *
338
+ * The card is only ever posted in an allow-listed group, so "allow" here means
339
+ * the same as `/allow` typed in that group: a contributor in this chat, not a
340
+ * key to the bot everywhere.
341
+ */
342
+ export async function handleAccessCallback(ctx) {
343
+ const data = ctx.callbackQuery?.data;
344
+ if (!data?.startsWith(`${ACCESS_CALLBACK_PREFIX}:`))
345
+ return;
346
+ const [, rawId, verdict] = data.split(':');
347
+ const userId = parseInt(rawId, 10);
348
+ if (!Number.isFinite(userId)) {
349
+ await ctx.answerCallbackQuery({ text: 'Malformed button.' }).catch(() => { });
350
+ return;
351
+ }
352
+ const by = ctx.from?.id;
353
+ if (by === undefined)
354
+ return;
355
+ // The card carries only an id. Recover the name from the roster so the
356
+ // outcome line names a person rather than a number.
357
+ const known = resolveUser(String(userId)) ?? { id: userId };
358
+ if (verdict === 'y') {
359
+ const chatId = groupScope(ctx);
360
+ try {
361
+ if (chatId !== undefined) {
362
+ grantAccess(chatId, userId, { username: known.username, grantedBy: by });
363
+ clearAccessCooldown(userId);
364
+ await ctx
365
+ .answerCallbackQuery({ text: `${describeUser(known)} can prompt the agent here.` })
366
+ .catch(() => { });
367
+ await editCardOutcome(ctx, `✅ ${describeUser(known)} was allowed in, as a contributor here.`);
368
+ console.log(`[access] ${by} made ${describeUser(known)} a contributor in ${chatId} by card`);
369
+ return;
370
+ }
371
+ const result = admitUser(known, by);
372
+ clearAccessCooldown(userId);
373
+ const text = result === 'already-allowed'
374
+ ? `${describeUser(known)} could already use this bot.`
375
+ : `${describeUser(known)} is in, as a guest.`;
376
+ await ctx.answerCallbackQuery({ text }).catch(() => { });
377
+ await editCardOutcome(ctx, `✅ ${describeUser(known)} was allowed in.`);
378
+ console.log(`[access] ${by} admitted ${describeUser(known)} by card`);
379
+ }
380
+ catch (error) {
381
+ console.error('[access] admit failed:', sanitizeError(error));
382
+ await ctx
383
+ .answerCallbackQuery({ text: 'Could not save that — they are not in.', show_alert: true })
384
+ .catch(() => { });
385
+ }
386
+ return;
387
+ }
388
+ await ctx.answerCallbackQuery({ text: `${describeUser(known)} was not let in.` }).catch(() => { });
389
+ await editCardOutcome(ctx, `🚫 ${describeUser(known)} was not let in.`);
390
+ console.log(`[access] ${by} ignored ${describeUser(known)}`);
391
+ }
392
+ /** The role the sender holds here — used by /status to show it. */
393
+ export function describeRole(ctx) {
394
+ const chatId = groupScope(ctx);
395
+ const userId = ctx.from?.id;
396
+ if (chatId === undefined || userId === undefined)
397
+ return undefined;
398
+ return resolveRole(chatId, userId);
399
+ }
400
+ /**
401
+ * Replace the card with its outcome, so a group with several admins does not
402
+ * keep a live pair of buttons on a decision that has already been taken.
403
+ */
404
+ async function editCardOutcome(ctx, text) {
405
+ await ctx.editMessageText(text, { reply_markup: { inline_keyboard: [] } }).catch(() => { });
406
+ }
407
+ //# sourceMappingURL=access.js.map