switchroom 0.19.1 → 0.19.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-scheduler/index.js +31 -1
- package/dist/auth-broker/index.js +565 -48
- package/dist/cli/autoaccept-poll.js +31 -1
- package/dist/cli/drive-write-pretool.mjs +32 -2
- package/dist/cli/ms-365-write-pretool.mjs +32 -2
- package/dist/cli/switchroom.js +1148 -274
- package/dist/host-control/main.js +3 -3
- package/dist/vault/approvals/kernel-server.js +2 -2
- package/dist/vault/broker/server.js +2 -2
- package/package.json +3 -2
- package/profiles/_base/start.sh.hbs +1 -0
- package/profiles/default/CLAUDE.md.hbs +8 -0
- package/skills/mental-model-curator/SKILL.md +68 -2
- package/skills/switchroom-cli/SKILL.md +25 -0
- package/telegram-plugin/auth-snapshot-format.ts +143 -12
- package/telegram-plugin/dist/bridge/bridge.js +8 -2
- package/telegram-plugin/dist/gateway/gateway.js +1427 -689
- package/telegram-plugin/dist/server.js +8 -2
- package/telegram-plugin/external-spend.ts +135 -0
- package/telegram-plugin/flushed-turn-supersede.ts +117 -13
- package/telegram-plugin/gateway/auth-add-flow.ts +215 -6
- package/telegram-plugin/gateway/auth-command.ts +138 -5
- package/telegram-plugin/gateway/gateway.ts +141 -158
- package/telegram-plugin/gateway/inbound-interceptors.ts +13 -3
- package/telegram-plugin/gateway/model-command.ts +309 -1
- package/telegram-plugin/gateway/narrative-lane.ts +23 -9
- package/telegram-plugin/gateway/outbound-send-path.ts +68 -15
- package/telegram-plugin/gateway/session-model-source.ts +90 -10
- package/telegram-plugin/gateway/status-pin-store.ts +64 -4
- package/telegram-plugin/gateway/stream-render.ts +22 -5
- package/telegram-plugin/gateway/usage-mask.ts +29 -0
- package/telegram-plugin/hooks/subagent-tracker-pretool.mjs +19 -2
- package/telegram-plugin/quota-bar-format.ts +78 -12
- package/telegram-plugin/quota-check.ts +17 -2
- package/telegram-plugin/reply-owner-resolve.ts +76 -11
- package/telegram-plugin/session-tail.ts +27 -3
- package/telegram-plugin/tests/activity-card-wiring.test.ts +47 -0
- package/telegram-plugin/tests/auth-add-flow.test.ts +367 -5
- package/telegram-plugin/tests/auth-snapshot-format.test.ts +41 -0
- package/telegram-plugin/tests/external-spend.test.ts +168 -0
- package/telegram-plugin/tests/flushed-turn-supersede.test.ts +117 -0
- package/telegram-plugin/tests/gateway-session-model-relaunch.test.ts +219 -29
- package/telegram-plugin/tests/model-command.test.ts +220 -0
- package/telegram-plugin/tests/quota-bar-format.test.ts +43 -0
- package/telegram-plugin/tests/quota-check.test.ts +57 -0
- package/telegram-plugin/tests/reply-owner-resolve.test.ts +257 -13
- package/telegram-plugin/tests/send-reply-golden.test.ts +154 -0
- package/telegram-plugin/tests/session-model-source.test.ts +142 -0
- package/telegram-plugin/tests/session-tail-first-attach.test.ts +115 -2
- package/telegram-plugin/tests/status-pin-store.test.ts +198 -0
- package/telegram-plugin/tests/subagent-tracker-hooks.test.ts +50 -0
- package/telegram-plugin/tests/usage-footer-freshness.test.ts +141 -0
- package/telegram-plugin/tests/usage-mask.test.ts +35 -0
- package/telegram-plugin/tests/worker-feed-dispatch.test.ts +27 -0
- package/telegram-plugin/tests/worker-feed-pin-persistence.test.ts +131 -1
- package/vendor/hindsight-memory/CHANGELOG.md +102 -0
- package/vendor/hindsight-memory/README.md +2 -1
- package/vendor/hindsight-memory/hooks/hooks.json +12 -0
- package/vendor/hindsight-memory/scripts/directive_verify.py +100 -3
- package/vendor/hindsight-memory/scripts/lib/config.py +150 -1
- package/vendor/hindsight-memory/scripts/lib/content.py +55 -5
- package/vendor/hindsight-memory/scripts/lib/directives.py +152 -15
- package/vendor/hindsight-memory/scripts/lib/parallel_recall.py +142 -0
- package/vendor/hindsight-memory/scripts/lib/state.py +31 -0
- package/vendor/hindsight-memory/scripts/recall.py +789 -143
- package/vendor/hindsight-memory/scripts/reconcile_tail.py +22 -1
- package/vendor/hindsight-memory/scripts/retain.py +71 -2
- package/vendor/hindsight-memory/scripts/subagent_retain.py +501 -0
- package/vendor/hindsight-memory/scripts/tests/test_directive_verify.py +169 -0
- package/vendor/hindsight-memory/scripts/tests/test_directives.py +177 -0
- package/vendor/hindsight-memory/scripts/tests/test_lesson_tagging.py +200 -0
- package/vendor/hindsight-memory/scripts/tests/test_recall_context_turns_default.py +200 -0
- package/vendor/hindsight-memory/scripts/tests/test_recall_envelope_strip_telemetry.py +477 -0
- package/vendor/hindsight-memory/scripts/tests/test_recall_integration.py +51 -0
- package/vendor/hindsight-memory/scripts/tests/test_recall_parallel_deadline.py +409 -0
- package/vendor/hindsight-memory/scripts/tests/test_recall_tag_weights.py +96 -0
- package/vendor/hindsight-memory/scripts/tests/test_recall_transcript_fallback.py +413 -0
- package/vendor/hindsight-memory/scripts/tests/test_reconcile_durability.py +49 -0
- package/vendor/hindsight-memory/scripts/tests/test_subagent_retain.py +439 -0
- package/vendor/hindsight-memory/settings.json +3 -1
|
@@ -67,10 +67,15 @@ import {
|
|
|
67
67
|
parseSetupTokenUrl,
|
|
68
68
|
readTokenFromCredentialsFile,
|
|
69
69
|
} from '../../src/auth/manager.js'
|
|
70
|
+
import { PRE_PASTE_RULES } from '../../src/auth/via-claude.js'
|
|
70
71
|
import type {
|
|
71
72
|
AddAccountCredentials,
|
|
72
73
|
AnthropicAddAccountCredentials,
|
|
73
74
|
} from '../../src/auth/broker/client.js'
|
|
75
|
+
import { isAuthAdmin, runReaddPrecheck } from './auth-command.js'
|
|
76
|
+
import type { ParsedAuthCommand } from './auth-command.js'
|
|
77
|
+
import { getAuthBrokerClient } from './auth-broker-client.js'
|
|
78
|
+
import { chatKey } from './chat-key.js'
|
|
74
79
|
|
|
75
80
|
/* ── Injectable tmux ops (mirrors makeTmuxRunner in src/agents/inject.ts) ─── */
|
|
76
81
|
|
|
@@ -103,6 +108,19 @@ export interface AuthAddTmuxOps {
|
|
|
103
108
|
* the session has ended.
|
|
104
109
|
*/
|
|
105
110
|
send(socket: string, session: string, text: string): void
|
|
111
|
+
/**
|
|
112
|
+
* `tmux -L <socket> send-keys -t <session> <key>` — a SINGLE key-name
|
|
113
|
+
* dispatch (e.g. `Enter`), with NO `-l` literal prefix and NO pane
|
|
114
|
+
* capture. Used for:
|
|
115
|
+
* - pre-paste picker choreography (theme / login-method Enters) during
|
|
116
|
+
* the URL-poll phase, before any secret is on the pane; and
|
|
117
|
+
* - blind post-paste Enter dispatches to advance past Enter-gated
|
|
118
|
+
* "Logged in / Security notes" screens in the via-claude picker flow.
|
|
119
|
+
* It reads nothing from the pane, so it can never leak the echoed code —
|
|
120
|
+
* this is the deterministic replacement for via-claude's capture-driven
|
|
121
|
+
* post-paste dispatch (see prb-safety.md).
|
|
122
|
+
*/
|
|
123
|
+
sendKey(socket: string, session: string, key: string): void
|
|
106
124
|
/** `tmux -L <socket> has-session -t <session>` — returns true if alive. */
|
|
107
125
|
hasSession(socket: string, session: string): boolean
|
|
108
126
|
/** `tmux -L <socket> kill-session -t <session>` — best-effort. */
|
|
@@ -151,6 +169,12 @@ export function makeAuthAddTmuxOps(tmuxBin = 'tmux'): AuthAddTmuxOps {
|
|
|
151
169
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
152
170
|
})
|
|
153
171
|
},
|
|
172
|
+
sendKey(socket, session, key) {
|
|
173
|
+
// Single key-name dispatch, no -l literal prefix, no capture.
|
|
174
|
+
execFileSync(tmuxBin, ['-L', socket, 'send-keys', '-t', session, key], {
|
|
175
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
176
|
+
})
|
|
177
|
+
},
|
|
154
178
|
hasSession(socket, session) {
|
|
155
179
|
try {
|
|
156
180
|
execFileSync(tmuxBin, ['-L', socket, 'has-session', '-t', session], {
|
|
@@ -184,6 +208,20 @@ export function makeAuthAddTmuxOps(tmuxBin = 'tmux'): AuthAddTmuxOps {
|
|
|
184
208
|
* TTL matches `REAUTH_INTERCEPT_TTL_MS` (10 minutes); the reaper sweep
|
|
185
209
|
* in gateway.ts walks both maps each minute.
|
|
186
210
|
*/
|
|
211
|
+
/**
|
|
212
|
+
* Which credential minter drives the flow.
|
|
213
|
+
*
|
|
214
|
+
* - `'via-claude'` (DEFAULT): spawn the bare `claude` login picker, which
|
|
215
|
+
* mints the broad scope set (`org:create_api_key user:profile
|
|
216
|
+
* user:inference user:sessions:claude_code user:mcp_servers
|
|
217
|
+
* user:file_upload`) that `server:` mode agents require at boot. This is
|
|
218
|
+
* the default because `claude setup-token` tokens carry only
|
|
219
|
+
* `user:inference` and are REFUSED by server: agents (via-claude.ts:9-17).
|
|
220
|
+
* - `'setup-token'`: spawn `claude setup-token` (narrow `user:inference`).
|
|
221
|
+
* Kept for completeness / legacy narrow-scope adds.
|
|
222
|
+
*/
|
|
223
|
+
export type AuthAddMode = 'via-claude' | 'setup-token'
|
|
224
|
+
|
|
187
225
|
export interface PendingAuthAddFlow {
|
|
188
226
|
label: string
|
|
189
227
|
scratchDir: string
|
|
@@ -192,6 +230,21 @@ export interface PendingAuthAddFlow {
|
|
|
192
230
|
/** tmux session name (`auth-add-<label>-<hex>`). */
|
|
193
231
|
tmuxSession: string
|
|
194
232
|
startedAt: number
|
|
233
|
+
/**
|
|
234
|
+
* True when this flow re-authenticates an EXISTING account label in place
|
|
235
|
+
* (`/auth readd`) — threaded to `addAccountViaBroker(..., { replace: true })`
|
|
236
|
+
* so the broker overwrites the stored credentials instead of rejecting the
|
|
237
|
+
* duplicate. Absent/false is a fresh add. Set by the gateway dispatch.
|
|
238
|
+
*/
|
|
239
|
+
replace?: boolean
|
|
240
|
+
/**
|
|
241
|
+
* Minter mode this flow was started in. `submitAccountAuthCode` reads it to
|
|
242
|
+
* decide whether to dispatch blind post-paste Enter key-presses (via-claude
|
|
243
|
+
* picker screens) — setup-token exits after the code so needs none.
|
|
244
|
+
* Optional for back-compat with callers/tests that construct flows directly;
|
|
245
|
+
* absent is treated as `'via-claude'` (the default minter).
|
|
246
|
+
*/
|
|
247
|
+
mode?: AuthAddMode
|
|
195
248
|
}
|
|
196
249
|
export const pendingAuthAddFlows = new Map<string, PendingAuthAddFlow>()
|
|
197
250
|
|
|
@@ -299,6 +352,8 @@ export interface StartAccountAuthSessionResult {
|
|
|
299
352
|
scratchDir: string
|
|
300
353
|
tmuxSocket: string
|
|
301
354
|
tmuxSession: string
|
|
355
|
+
/** The minter mode the session was started in. */
|
|
356
|
+
mode: AuthAddMode
|
|
302
357
|
}
|
|
303
358
|
|
|
304
359
|
/**
|
|
@@ -343,6 +398,11 @@ export async function startAccountAuthSession(
|
|
|
343
398
|
agentName?: string
|
|
344
399
|
/** Override the claude binary name (tests). */
|
|
345
400
|
claudeBinary?: string
|
|
401
|
+
/**
|
|
402
|
+
* Credential minter. Defaults to `'via-claude'` (broad scope) — see
|
|
403
|
+
* {@link AuthAddMode}. Pass `'setup-token'` for the narrow-scope minter.
|
|
404
|
+
*/
|
|
405
|
+
mode?: AuthAddMode
|
|
346
406
|
} = {},
|
|
347
407
|
): Promise<StartAccountAuthSessionResult> {
|
|
348
408
|
if (process.env.SWITCHROOM_TMUX_SUPERVISOR !== '1' && !opts.tmuxOps) {
|
|
@@ -353,10 +413,14 @@ export async function startAccountAuthSession(
|
|
|
353
413
|
}
|
|
354
414
|
|
|
355
415
|
const home = opts.home ?? homedir()
|
|
356
|
-
|
|
416
|
+
// 30s (was 12s): the via-claude login picker adds keystroke-choreography
|
|
417
|
+
// latency (theme + login-method Enters) before the URL renders, and an
|
|
418
|
+
// unloaded VM can be slow. via-claude's own default is 20s; 30s is generous.
|
|
419
|
+
const urlTimeoutMs = opts.urlTimeoutMs ?? 30_000
|
|
357
420
|
const agentName = opts.agentName ?? process.env.SWITCHROOM_AGENT_NAME ?? 'gateway'
|
|
358
421
|
const tmux = opts.tmuxOps ?? makeAuthAddTmuxOps(opts.tmuxBin)
|
|
359
422
|
const binary = opts.claudeBinary ?? 'claude'
|
|
423
|
+
const mode: AuthAddMode = opts.mode ?? 'via-claude'
|
|
360
424
|
|
|
361
425
|
const scratchDir = pickScratchDir(label, home)
|
|
362
426
|
mkdirSync(scratchDir, { recursive: true, mode: 0o700 })
|
|
@@ -391,20 +455,31 @@ export async function startAccountAuthSession(
|
|
|
391
455
|
if (process.env.CLAUDE_CONFIG_DIR) sessionEnv['CLAUDE_CONFIG_DIR'] = scratchDir // always override
|
|
392
456
|
if (process.env.XDG_CONFIG_HOME) sessionEnv['XDG_CONFIG_HOME'] = process.env.XDG_CONFIG_HOME
|
|
393
457
|
|
|
458
|
+
// Command: bare `claude` for the broad-scope login picker (via-claude), or
|
|
459
|
+
// `claude setup-token` for the narrow-scope minter.
|
|
460
|
+
const sessionCmd = mode === 'via-claude' ? binary : binary + ' setup-token'
|
|
461
|
+
const minterLabel = mode === 'via-claude' ? 'claude login' : 'claude setup-token'
|
|
394
462
|
try {
|
|
395
|
-
tmux.newSession(tmuxSocket, tmuxSession, sessionEnv,
|
|
463
|
+
tmux.newSession(tmuxSocket, tmuxSession, sessionEnv, sessionCmd)
|
|
396
464
|
} catch (err) {
|
|
397
465
|
cleanScratchDir(scratchDir)
|
|
398
|
-
throw new Error(`Failed to start tmux session for
|
|
466
|
+
throw new Error(`Failed to start tmux session for ${minterLabel}: ${(err as Error).message}`)
|
|
399
467
|
}
|
|
400
468
|
|
|
401
469
|
// Poll capture-pane every 500ms up to the URL timeout.
|
|
470
|
+
//
|
|
471
|
+
// In via-claude mode we ALSO dispatch the pre-paste picker choreography
|
|
472
|
+
// (theme picker → Enter, login-method picker → Enter) each tick, at most
|
|
473
|
+
// once per rule. This runs BEFORE any secret is on the pane, so capturing
|
|
474
|
+
// here is safe. parseSetupTokenUrl matches both the claude.ai/oauth and
|
|
475
|
+
// claude.com/cai/oauth shapes, which is exactly the URL the picker renders.
|
|
476
|
+
const preFired = new Set<string>()
|
|
402
477
|
const loginUrl = await new Promise<string>((resolve, reject) => {
|
|
403
478
|
const deadline = setTimeout(() => {
|
|
404
479
|
clearInterval(ticker)
|
|
405
480
|
tmux.killSession(tmuxSocket, tmuxSession)
|
|
406
481
|
cleanScratchDir(scratchDir)
|
|
407
|
-
reject(new Error(
|
|
482
|
+
reject(new Error(`${minterLabel} did not print an OAuth URL within ${urlTimeoutMs}ms`))
|
|
408
483
|
}, urlTimeoutMs)
|
|
409
484
|
|
|
410
485
|
const ticker = setInterval(() => {
|
|
@@ -414,9 +489,20 @@ export async function startAccountAuthSession(
|
|
|
414
489
|
clearTimeout(deadline)
|
|
415
490
|
clearInterval(ticker)
|
|
416
491
|
cleanScratchDir(scratchDir)
|
|
417
|
-
reject(new Error(
|
|
492
|
+
reject(new Error(`${minterLabel} exited before printing OAuth URL`))
|
|
418
493
|
return
|
|
419
494
|
}
|
|
495
|
+
if (mode === 'via-claude') {
|
|
496
|
+
for (const rule of PRE_PASTE_RULES) {
|
|
497
|
+
if (preFired.has(rule.name)) continue
|
|
498
|
+
if (rule.match.test(pane)) {
|
|
499
|
+
preFired.add(rule.name)
|
|
500
|
+
// The pre-paste rules dispatch bare key-names (Enter); use the
|
|
501
|
+
// single-key primitive, not the literal-code `send`.
|
|
502
|
+
for (const key of rule.keys) tmux.sendKey(tmuxSocket, tmuxSession, key)
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
420
506
|
const url = parseSetupTokenUrl(pane)
|
|
421
507
|
if (url) {
|
|
422
508
|
clearTimeout(deadline)
|
|
@@ -427,7 +513,7 @@ export async function startAccountAuthSession(
|
|
|
427
513
|
}, 500)
|
|
428
514
|
})
|
|
429
515
|
|
|
430
|
-
return { loginUrl, scratchDir, tmuxSocket, tmuxSession }
|
|
516
|
+
return { loginUrl, scratchDir, tmuxSocket, tmuxSession, mode }
|
|
431
517
|
}
|
|
432
518
|
|
|
433
519
|
/**
|
|
@@ -456,11 +542,24 @@ export async function submitAccountAuthCode(
|
|
|
456
542
|
pollIntervalMs?: number
|
|
457
543
|
pollTimeoutMs?: number
|
|
458
544
|
tmuxOps?: AuthAddTmuxOps
|
|
545
|
+
/**
|
|
546
|
+
* Blind post-paste Enter schedule (ms after the code paste) for the
|
|
547
|
+
* via-claude picker flow: advances past the Enter-gated "Logged in /
|
|
548
|
+
* Security notes" screens WITHOUT ever capturing the pane (the echoed
|
|
549
|
+
* code is a secret — see prb-safety.md). Defaults derive from
|
|
550
|
+
* `flow.mode`: via-claude → `[1500, 3000, 5000]`, setup-token → `[]`
|
|
551
|
+
* (setup-token exits after the code, so no screens to dismiss). Pass an
|
|
552
|
+
* explicit array to override (tests use tight schedules).
|
|
553
|
+
*/
|
|
554
|
+
blindEnterDelaysMs?: number[]
|
|
459
555
|
} = {},
|
|
460
556
|
): Promise<AddAccountCredentials> {
|
|
461
557
|
const pollIntervalMs = opts.pollIntervalMs ?? 250
|
|
462
558
|
const pollTimeoutMs = opts.pollTimeoutMs ?? 300_000
|
|
463
559
|
const tmux = opts.tmuxOps ?? makeAuthAddTmuxOps()
|
|
560
|
+
const mode: AuthAddMode = flow.mode ?? 'via-claude'
|
|
561
|
+
const blindEnterDelaysMs =
|
|
562
|
+
opts.blindEnterDelaysMs ?? (mode === 'via-claude' ? [1500, 3000, 5000] : [])
|
|
464
563
|
|
|
465
564
|
const credentialsPath = join(flow.scratchDir, '.credentials.json')
|
|
466
565
|
|
|
@@ -475,11 +574,29 @@ export async function submitAccountAuthCode(
|
|
|
475
574
|
)
|
|
476
575
|
}
|
|
477
576
|
|
|
577
|
+
// Blind post-paste Enter schedule (via-claude picker). Absolute deadlines;
|
|
578
|
+
// each fires at most once. NEVER reads the pane — sendKey only writes.
|
|
579
|
+
const pasteAt = Date.now()
|
|
580
|
+
const blindEnters = blindEnterDelaysMs.map((d) => ({ at: pasteAt + d, fired: false }))
|
|
581
|
+
|
|
478
582
|
// Poll filesystem + session liveness only — no capture-pane.
|
|
479
583
|
const deadline = Date.now() + pollTimeoutMs
|
|
480
584
|
while (Date.now() < deadline) {
|
|
481
585
|
await new Promise((r) => setTimeout(r, pollIntervalMs))
|
|
482
586
|
|
|
587
|
+
// Dispatch any due blind Enters (best-effort; a dead session just throws
|
|
588
|
+
// and we swallow it — the fs poll below is the real success signal).
|
|
589
|
+
for (const be of blindEnters) {
|
|
590
|
+
if (!be.fired && Date.now() >= be.at) {
|
|
591
|
+
be.fired = true
|
|
592
|
+
try {
|
|
593
|
+
tmux.sendKey(flow.tmuxSocket, flow.tmuxSession, 'Enter')
|
|
594
|
+
} catch {
|
|
595
|
+
// best-effort — session may have already exited on success
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
483
600
|
if (existsSync(credentialsPath)) {
|
|
484
601
|
const token = readTokenFromCredentialsFile(credentialsPath)
|
|
485
602
|
if (token) {
|
|
@@ -529,3 +646,95 @@ export function cancelAccountAuthSession(
|
|
|
529
646
|
tmux.killSession(flow.tmuxSocket, flow.tmuxSession)
|
|
530
647
|
cleanScratchDir(flow.scratchDir)
|
|
531
648
|
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* `/auth add`, `/auth readd`, `/auth add --replace`, and `/auth cancel`
|
|
652
|
+
* dispatch. Extracted verbatim from gateway.ts (switchroom#2996 ratchet) —
|
|
653
|
+
* behavior identical. Gateway-routed because it drives a scratch-dir-backed
|
|
654
|
+
* `claude setup-token` tmux/OAuth lifecycle the broker client can't model.
|
|
655
|
+
*
|
|
656
|
+
* `reply` sends an HTML message to the originating chat; `escapeHtml` is the
|
|
657
|
+
* gateway's Telegram-HTML escaper. Admin authority is passed through as
|
|
658
|
+
* `isAdmin` (the gateway sources it from the agent's own `admin`/`root` flag).
|
|
659
|
+
*/
|
|
660
|
+
export async function handleAuthAddOrCancel(opts: {
|
|
661
|
+
parsed: Extract<ParsedAuthCommand, { kind: 'add' | 'cancel' }>
|
|
662
|
+
isAdmin: boolean
|
|
663
|
+
currentAgent: string
|
|
664
|
+
chatId: string
|
|
665
|
+
threadId: number | null
|
|
666
|
+
reply: (text: string) => Promise<unknown>
|
|
667
|
+
escapeHtml: (text: string) => string
|
|
668
|
+
}): Promise<void> {
|
|
669
|
+
const { parsed, isAdmin, currentAgent, chatId, threadId, reply, escapeHtml } = opts
|
|
670
|
+
if (!isAuthAdmin({ isAdmin })) {
|
|
671
|
+
await reply(
|
|
672
|
+
`**Not authorized.** \`/auth ${parsed.kind}\` is admin-only.\n` +
|
|
673
|
+
`Set \`admin: true\` on this agent in switchroom.yaml to unlock ` +
|
|
674
|
+
`(the same flag that gates \`/agents\`, \`/restart\`, ` +
|
|
675
|
+
`\`/update\` etc.).`,
|
|
676
|
+
)
|
|
677
|
+
return
|
|
678
|
+
}
|
|
679
|
+
// PR3 supergroup-mode: key auth-add flows by (chat, thread) so
|
|
680
|
+
// separate flows in two topics of one supergroup can't collide.
|
|
681
|
+
// In DM chats message_thread_id is undefined → key collapses to
|
|
682
|
+
// `chatId:_`, identical to today's behavior.
|
|
683
|
+
const authAddKey = chatKey(chatId, threadId) as string
|
|
684
|
+
if (parsed.kind === 'cancel') {
|
|
685
|
+
const existing = pendingAuthAddFlows.get(authAddKey)
|
|
686
|
+
if (!existing) {
|
|
687
|
+
await reply("_No pending \`/auth add\` flow in this chat._")
|
|
688
|
+
return
|
|
689
|
+
}
|
|
690
|
+
cancelAccountAuthSession(existing)
|
|
691
|
+
pendingAuthAddFlows.delete(authAddKey)
|
|
692
|
+
await reply("Cancelled.")
|
|
693
|
+
return
|
|
694
|
+
}
|
|
695
|
+
// parsed.kind === 'add'
|
|
696
|
+
if (pendingAuthAddFlows.has(authAddKey)) {
|
|
697
|
+
await reply(
|
|
698
|
+
"_An \`/auth add\` flow is already in progress for this chat. " +
|
|
699
|
+
"Finish the paste, or send \`/auth cancel\` to abort._",
|
|
700
|
+
)
|
|
701
|
+
return
|
|
702
|
+
}
|
|
703
|
+
// Precheck against broker state (readd requires the label to exist; a
|
|
704
|
+
// fresh add requires it NOT to): fail fast before spinning up a tmux/OAuth
|
|
705
|
+
// flow. Best-effort — a broker-unreachable case returns null and
|
|
706
|
+
// addAccountViaBroker enforces.
|
|
707
|
+
const precheckErr = await runReaddPrecheck(
|
|
708
|
+
() => getAuthBrokerClient(currentAgent),
|
|
709
|
+
parsed.label,
|
|
710
|
+
parsed.replace,
|
|
711
|
+
)
|
|
712
|
+
if (precheckErr) {
|
|
713
|
+
await reply(precheckErr)
|
|
714
|
+
return
|
|
715
|
+
}
|
|
716
|
+
try {
|
|
717
|
+
const { loginUrl, scratchDir, tmuxSocket, tmuxSession, mode } = await startAccountAuthSession(parsed.label)
|
|
718
|
+
pendingAuthAddFlows.set(authAddKey, {
|
|
719
|
+
label: parsed.label,
|
|
720
|
+
scratchDir,
|
|
721
|
+
tmuxSocket,
|
|
722
|
+
tmuxSession,
|
|
723
|
+
startedAt: Date.now(),
|
|
724
|
+
replace: parsed.replace,
|
|
725
|
+
mode,
|
|
726
|
+
})
|
|
727
|
+
const verbNoun = parsed.replace ? 'Re-authenticating account' : 'Adding account'
|
|
728
|
+
await reply(
|
|
729
|
+
`**${verbNoun}** \`${parsed.label}\`\n\n` +
|
|
730
|
+
`1. Open this URL on your phone:\n${loginUrl}\n\n` +
|
|
731
|
+
`2. Log into Anthropic, copy the code Claude shows.\n` +
|
|
732
|
+
`3. Paste it back here.\n\n` +
|
|
733
|
+
`Send \`/auth cancel\` to abort.`,
|
|
734
|
+
)
|
|
735
|
+
} catch (err) {
|
|
736
|
+
await reply(
|
|
737
|
+
`**/auth ${parsed.replace ? 'readd' : 'add'} failed:** ${escapeHtml((err as Error)?.message ?? String(err))}`,
|
|
738
|
+
)
|
|
739
|
+
}
|
|
740
|
+
}
|
|
@@ -44,7 +44,19 @@ export type ParsedAuthCommand =
|
|
|
44
44
|
| { kind: 'list' }
|
|
45
45
|
| { kind: 'use'; label: string }
|
|
46
46
|
| { kind: 'rotate' }
|
|
47
|
-
| {
|
|
47
|
+
| {
|
|
48
|
+
kind: 'add'
|
|
49
|
+
label: string
|
|
50
|
+
/**
|
|
51
|
+
* Re-auth an EXISTING account label in place (broker `addAccount(...,
|
|
52
|
+
* replace=true)`). Set by the `/auth readd <label>` verb (and
|
|
53
|
+
* `/auth add <label> --replace`). Plain `/auth add` leaves it false —
|
|
54
|
+
* the broker rejects a duplicate label, which is the desired guard for
|
|
55
|
+
* a fresh add. `/auth readd` is the path to widen scope on the 3 pooled
|
|
56
|
+
* accounts without renaming them.
|
|
57
|
+
*/
|
|
58
|
+
replace: boolean
|
|
59
|
+
}
|
|
48
60
|
| { kind: 'cancel' }
|
|
49
61
|
| {
|
|
50
62
|
kind: 'provider-add'
|
|
@@ -149,12 +161,25 @@ export function parseAuthCommand(text: string): ParsedAuthCommand | null {
|
|
|
149
161
|
if (!label) return { kind: 'help', reason: 'Usage: /auth use <label>' }
|
|
150
162
|
return { kind: 'use', label }
|
|
151
163
|
}
|
|
152
|
-
case 'add':
|
|
153
|
-
|
|
154
|
-
|
|
164
|
+
case 'add':
|
|
165
|
+
case 'readd': {
|
|
166
|
+
// `readd` is `add` with replace=true; `add --replace` is the same.
|
|
167
|
+
const positional = parts.slice(1).filter((t) => !t.startsWith('--'))
|
|
168
|
+
const flags = new Set(
|
|
169
|
+
parts.slice(1).filter((t) => t.startsWith('--')).map((t) => t.toLowerCase()),
|
|
170
|
+
)
|
|
171
|
+
const label = positional[0]
|
|
172
|
+
const usage = verb === 'readd' ? 'Usage: /auth readd <label>' : 'Usage: /auth add <label>'
|
|
173
|
+
if (!label) return { kind: 'help', reason: usage }
|
|
155
174
|
const err = validateAuthAddLabel(label)
|
|
156
175
|
if (err) return { kind: 'help', reason: err }
|
|
157
|
-
|
|
176
|
+
for (const f of flags) {
|
|
177
|
+
if (f !== '--replace') {
|
|
178
|
+
return { kind: 'help', reason: `Unknown flag \`${codeSpanSafe(f)}\` for \`/auth ${verb}\`.` }
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const replace = verb === 'readd' || flags.has('--replace')
|
|
182
|
+
return { kind: 'add', label, replace }
|
|
158
183
|
}
|
|
159
184
|
case 'cancel':
|
|
160
185
|
return { kind: 'cancel' }
|
|
@@ -451,6 +476,7 @@ export async function handleAuthCommand(
|
|
|
451
476
|
` \`/auth use <label>\` — admin: swap the fleet to <label>\n` +
|
|
452
477
|
` \`/auth rotate\` — admin: cycle to next non-exhausted fallback\n` +
|
|
453
478
|
` \`/auth add <label>\` — admin: OAuth-add a new Anthropic account from chat\n` +
|
|
479
|
+
` \`/auth readd <label>\` — admin: re-auth an EXISTING account in place (widen scope)\n` +
|
|
454
480
|
` \`/auth google add <email>\` — admin: Telegram-native Google account add/re-auth\n` +
|
|
455
481
|
` \`/auth microsoft add <email>\` — admin: Telegram-native Microsoft account add/re-auth\n` +
|
|
456
482
|
` \`/auth cancel\` — abort an \`/auth add\` or provider add in progress\n` +
|
|
@@ -819,6 +845,113 @@ function isAdmin(ctx: AuthCommandContext): boolean {
|
|
|
819
845
|
return ctx.isAdmin === true
|
|
820
846
|
}
|
|
821
847
|
|
|
848
|
+
/**
|
|
849
|
+
* The scope every `server:` mode agent needs from a pooled account for
|
|
850
|
+
* fable/Claude 7-day usage reporting. Absence is the whole reason
|
|
851
|
+
* `/auth readd` exists (setup-token tokens can't carry it).
|
|
852
|
+
*/
|
|
853
|
+
export const REQUIRED_USAGE_SCOPE = 'user:profile'
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Precheck for the gateway `/auth add`/`readd` dispatch. Returns a
|
|
857
|
+
* user-facing error string when the request is incoherent against current
|
|
858
|
+
* broker state, else null.
|
|
859
|
+
*
|
|
860
|
+
* - `readd` (replace=true) of a label that does NOT exist → error (there's
|
|
861
|
+
* nothing to re-auth; the operator wants `/auth add`).
|
|
862
|
+
* - plain `add` (replace=false) of a label that ALREADY exists → error
|
|
863
|
+
* (the broker would reject the duplicate anyway; fail fast with a clear
|
|
864
|
+
* message pointing at `/auth readd`).
|
|
865
|
+
*
|
|
866
|
+
* Kept pure so it's unit-testable without a live broker.
|
|
867
|
+
*/
|
|
868
|
+
export function readdPrecheckError(
|
|
869
|
+
label: string,
|
|
870
|
+
replace: boolean,
|
|
871
|
+
labelExists: boolean,
|
|
872
|
+
): string | null {
|
|
873
|
+
if (replace && !labelExists) {
|
|
874
|
+
return (
|
|
875
|
+
`**/auth readd:** no account named \`${codeSpanSafe(label)}\` to re-auth. ` +
|
|
876
|
+
`Run \`/auth show\` for the current list, or \`/auth add ${codeSpanSafe(label)}\` to add it fresh.`
|
|
877
|
+
)
|
|
878
|
+
}
|
|
879
|
+
if (!replace && labelExists) {
|
|
880
|
+
return (
|
|
881
|
+
`**/auth add:** \`${codeSpanSafe(label)}\` already exists. ` +
|
|
882
|
+
`Use \`/auth readd ${codeSpanSafe(label)}\` to re-authenticate it in place (e.g. to widen scope).`
|
|
883
|
+
)
|
|
884
|
+
}
|
|
885
|
+
return null
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/**
|
|
889
|
+
* Broker-backed precheck for the `/auth add` / `/auth readd` chat verb.
|
|
890
|
+
* Resolves a broker client (via the caller-supplied getter), queries live
|
|
891
|
+
* account state, and returns the {@link readdPrecheckError} message (or null
|
|
892
|
+
* when the request is valid) so the gateway can fail fast before spinning up
|
|
893
|
+
* a tmux/OAuth flow.
|
|
894
|
+
*
|
|
895
|
+
* Best-effort by design: if the broker is unreachable (getter returns null or
|
|
896
|
+
* `listState` throws) this returns null and lets `addAccountViaBroker` enforce
|
|
897
|
+
* existence at add time. Kept here — beside `readdPrecheckError` — so the
|
|
898
|
+
* gateway carries only a thin call site (switchroom#2996 line-ratchet: no new
|
|
899
|
+
* inline bodies in gateway.ts).
|
|
900
|
+
*/
|
|
901
|
+
export async function runReaddPrecheck(
|
|
902
|
+
getClient: () => Promise<AuthBrokerClient | null>,
|
|
903
|
+
label: string,
|
|
904
|
+
replace: boolean,
|
|
905
|
+
): Promise<string | null> {
|
|
906
|
+
try {
|
|
907
|
+
const client = await getClient()
|
|
908
|
+
if (!client) return null
|
|
909
|
+
const state = await client.listState()
|
|
910
|
+
const exists = state.accounts.some((a) => a.label === label)
|
|
911
|
+
return readdPrecheckError(label, replace, exists)
|
|
912
|
+
} catch {
|
|
913
|
+
// broker unreachable — skip precheck; addAccountViaBroker enforces.
|
|
914
|
+
return null
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* Render the "granted scopes" tail for a successful `/auth add`/`readd`.
|
|
920
|
+
* Reads the scopes STRUCTURALLY from `credentials.claudeAiOauth.scopes`
|
|
921
|
+
* (never scraped from the pane). Returns the text plus a `warn` flag set
|
|
922
|
+
* when {@link REQUIRED_USAGE_SCOPE} is absent, so the caller can surface a
|
|
923
|
+
* loud warning at add time instead of a silent `/usage` failure later.
|
|
924
|
+
*/
|
|
925
|
+
export function formatGrantedScopesReply(scopes: string[] | undefined): {
|
|
926
|
+
text: string
|
|
927
|
+
hasUsageScope: boolean
|
|
928
|
+
} {
|
|
929
|
+
const list = Array.isArray(scopes) ? scopes.filter((s) => typeof s === 'string') : []
|
|
930
|
+
const hasUsageScope = list.includes(REQUIRED_USAGE_SCOPE)
|
|
931
|
+
if (list.length === 0) {
|
|
932
|
+
return {
|
|
933
|
+
text:
|
|
934
|
+
`\n⚠️ **No scopes reported** on the new token — could not confirm \`${REQUIRED_USAGE_SCOPE}\`. ` +
|
|
935
|
+
`7-day usage reporting may not work. Re-run \`/auth readd\` if usage is missing.`,
|
|
936
|
+
hasUsageScope: false,
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
const rendered = list.map((s) => `\`${codeSpanSafe(s)}\``).join(', ')
|
|
940
|
+
if (hasUsageScope) {
|
|
941
|
+
return {
|
|
942
|
+
text: `\nGranted scopes: ${rendered}\n✓ \`${REQUIRED_USAGE_SCOPE}\` present — 7-day usage reporting is unlocked.`,
|
|
943
|
+
hasUsageScope: true,
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
return {
|
|
947
|
+
text:
|
|
948
|
+
`\nGranted scopes: ${rendered}\n` +
|
|
949
|
+
`⚠️ **\`${REQUIRED_USAGE_SCOPE}\` is MISSING** — 7-day usage reporting will not work for this account. ` +
|
|
950
|
+
`This usually means the narrow \`setup-token\` minter was used. Re-run \`/auth readd <label>\` with the broad login to fix.`,
|
|
951
|
+
hasUsageScope: false,
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
|
|
822
955
|
/**
|
|
823
956
|
* Choose the next account `auth rotate` should set active. Walks
|
|
824
957
|
* `fallback_order` starting *after* the currently-active label,
|