diff --git a/docs/bots.md b/docs/bots.md index 0d4ddeb40b..b1c937b025 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -710,6 +710,7 @@ Every bot has `secret_request` without asking, `secret_fetch` in its chat and it - **Pasting a key.** The desktop bot composer offers “Keep as secret” for recognized credential shapes, not for every possible secret. It recognizes provider-prefixed keys, labelled AWS secret access keys and AWS pairs across CSV, JSON, environment lines and prose, private-key blocks, credential URLs with long, varied token values (including OAuth fragments and signed S3/GCS links) and an Authorization Bearer line. Bare JWTs, arbitrary passwords, attached files (including dropped `.env` files), and text pastes of 32 KB or more that become attachments are not checked. Choose the private card's keep time (24 hours by default); the value goes to the local vault for the bot's home thread under a free, service-specific name. The composer replaces the matched span with “the secret NAME” for review; an AWS pair keeps the secret half and leaves the access key ID visible. Private drafts survive chat switches in window memory only, including text added by applets and memory quotes. A successful save says “Kept as NAME” even if it finished after an edit or while another chat was open. The notice clears on the next edit or Send; remembered copies expire with the keep time or clear on Send. A save that finishes after the window reloads cannot be announced there; the saved secret is still listed in Settings → Secrets. An AWS access key ID alone is public: paste its secret access key too. With temporary credentials (`ASIA…`), the session token stays in the message; it is useless without the secret access key. Send as text keeps unsaved text unchanged; ignoring the offer takes one extra Send. A refused save leaves the key private and explains the error. Phones are unchanged: secrets and this offer are desktop-only. +- **`/secform`.** The owner opens the form without waiting to be asked: `/secform` (one field), `/secform 3`, or `/secform for email, password and openrouterkey` (named fields, read in the composer by `parseSecform`; plain words such as email are shown as typed, the rest masked). The same command works in an agent thread. The form adds fields and sets when they expire (1 hour, 1 day, 7 days or never), who may use them (the thread, or a bot of this computer) and single use. Save securely sends the values once to the secret store of the computer that runs the thread (`secrets.share`; for a thread of another computer, over the encrypted link, routed with the values left out of the request ledger's match). The chat shows a chip, “Shared N secrets: NAMES · expires in …”, with Revoke; it reads expired or revoked once they end. The agent, or the bot, gets a quiet note with the names only, read with its next turn (`secretShareNote`). A single-use secret gets no readable file and is deleted after the first `secret_run` that names it. A bot of another computer is not offered the form yet. - **The card.** `secret_request` opens the same private card a thread shows (`SecretRequests`), filed under the bot's chat thread whichever of its turns asked (`botHomeOf`), and the bot's chat shows it above the composer (`BotSecretRequests`). The owner types the secret there, or picks a saved one, never in the chat; the bot gets only its name. A bot's turn answers no approvals, but this ask reaches its owner (`MousseTool.botAsksOwner`), so the call waits for the answer, up to the card's hour, as a thread's does. - **Bound to one service.** A bot may ask with `for: { service: "openai" }` (also anthropic, github, stripe, notion or huggingface), or `for: { origin: "https://api.example.com" }`. The private card names the service or host and says “read only”. - **Where the key goes.** Mousse keeps the value for requests to that origin, in one fixed header, with known services limited to listed API paths. Notion and Anthropic also have fixed version headers (`Notion-Version` and `anthropic-version`). diff --git a/src/main/mms/protocolEventBridge.ts b/src/main/mms/protocolEventBridge.ts index a47b36cef9..d983c8e284 100644 --- a/src/main/mms/protocolEventBridge.ts +++ b/src/main/mms/protocolEventBridge.ts @@ -275,6 +275,11 @@ export function bridgeProtocolEvent( if (threadId != null) broadcast('secrets:requestsChanged', { threadId }) return true } + case 'secrets.shares.changed': { + // Only the thread id: a window reads the thread's shared secrets (`/secform`) itself. + if (threadId != null) broadcast('secrets:sharesChanged', { threadId }) + return true + } case 'computerUse.setupRequest.changed': { // Only the thread id: a window reads the thread's setup card itself. if (threadId != null) broadcast('computerUse:setupRequestChanged', { threadId }) diff --git a/src/mms/MmsProfileServices.ts b/src/mms/MmsProfileServices.ts index 90387491cb..2c1f867c68 100644 --- a/src/mms/MmsProfileServices.ts +++ b/src/mms/MmsProfileServices.ts @@ -12,6 +12,7 @@ import { BugReportService } from './bugReports/BugReportService' import { WebPictures } from './webPictures/WebPictures' import { createGhFallbackRunner, execRunner } from './git/ghRunner' import { userAction } from './git/gitPolicy' +import { SecretShares } from './secrets/SecretShares' import { SecretRequests } from './secrets/SecretRequests' import { createSecretToolHost } from './secrets/secretToolHost' import { forgetWorktreeFolders, refreshWorktreeFolders, setWorktreeFolders } from './worktree/worktreeLayout' @@ -1608,9 +1609,23 @@ export class MmsProfileServices { // A subagent's thread is masked with its parents' secrets: their agents may hand it the value. ancestorsOf: (threadId) => threadAncestors(this.threads, threadId), threadBusy: (threadId) => secretThreadBusy(threadId, this.orchestrator, this.runEngine), - changed: () => this.secretsChanged.emit('changed') + changed: () => { + this.secretsChanged.emit('changed') + this.secretShares?.storeChanged() + }, + usedUp: (name, shareId) => this.secretShares?.usedUp(name, shareId) }) this.secretRequests = new SecretRequests(this.secretVault) + // Secrets a person shares with /secform (asks i121, i125): kept in the same store, for the thread or bot chosen. + this.secretShares = new SecretShares({ + profileRoot: homeDir, + vault: this.secretVault, + threadAlive: (threadId) => Boolean(this.threads.getThread(threadId)), + botHome: (botId) => { + if (!this.personalBots) throw new Error('Bots are not available.') + return this.personalBots.service.secretHome(botId) + } + }) const vault = this.secretVault // Bug reports (Settings → General → Error reports): the Report button's and report_bug's filing. const runner = createGhFallbackRunner(execRunner) @@ -2505,6 +2520,7 @@ export class MmsProfileServices { automationKeys!: { list(): string[]; set(name: string, value: string): void; has(name: string): boolean } /** Secrets agents asked for in threads, over the profile's secret store (#595). */ secretVault!: SecretVault + secretShares?: SecretShares secretRequests!: SecretRequests /** Emits `changed` when a secret is added, used, removed or expires (Settings → Secrets refreshes). */ readonly secretsChanged = new EventEmitter() diff --git a/src/mms/MousseMainService.ts b/src/mms/MousseMainService.ts index 6d32ef96c6..23958c260b 100644 --- a/src/mms/MousseMainService.ts +++ b/src/mms/MousseMainService.ts @@ -40,6 +40,7 @@ import { registerComputerUseMethods } from './computerUse/registerMethods' import { registerSourceControlMethods } from './sourceControl/registerMethods' import { GitHubAccount } from './git/GitHubAccount' import { registerSecretMethods } from './secrets/registerMethods' +import { secretShareNote } from './secrets/secretShareNote' import { registerBugReportMethods } from './bugReports/registerMethods' import { registerWorkflowDefinitionMethods } from './workflows/registerDefinitionMethods' import { registerWorkflowRunMethods } from './workflows/registerRunMethods' @@ -414,6 +415,26 @@ export class MousseMainService extends MmsProfileServices { if (!services.personalBots) throw new Error('Bots are not available.') return services.personalBots.service.secretHome(botId) } }, + shares: services.secretShares ? { + share: (input) => { + const { usableIn, ...share } = services.secretShares!.share(input) + const text = secretShareNote(share) + const bot = share.botId ? services.personalBots?.service : undefined + // A bot's chat keeps a quiet line the bot reads next turn, drawn as the chip there. + // The values are kept already: a line that could not be written must not read as a failed save (a retry would share twice). + if (share.botId && bot) { + try { bot.postSecretShare(share.botId, share.shareId, text) } + catch (error) { console.warn('the bot could not be told the names of shared secrets', { shareId: share.shareId, error: error instanceof Error ? error.message : String(error) }) } + } + // An agent thread shows the chip, and its agent (when it may use them) gets the names with its next turn. + if (share.threadId !== usableIn || !share.botId) { + services.orchestrator.recordSecretShare(share.threadId, share, share.botId ? undefined : { threadId: usableIn, text }) + } + return share + }, + list: (threadId) => services.secretShares!.list(threadId), + revoke: (threadId, shareId) => services.secretShares!.revoke(threadId, shareId) + } : undefined, list: () => services.secretVault.list(), delete: (name) => services.secretVault.delete(name) } diff --git a/src/mms/bots/chat/BotChatService.ts b/src/mms/bots/chat/BotChatService.ts index 9b1e141b6a..9747684887 100644 --- a/src/mms/bots/chat/BotChatService.ts +++ b/src/mms/bots/chat/BotChatService.ts @@ -46,6 +46,7 @@ import { pictureInfos, pictureThumbs, type PictureInfos } from '../../pictures/P import type { PictureThumbs } from '../../pictures/PictureThumbs' import { describedInOrder, localPictureFiles, withMessagePictures, type PictureFiles } from './messagePictures' import { turnTimingBegin, turnTimingBotMark, turnTimingForget } from '../../diagnostics/turnTiming' +import { SECFORM_LINE_PREFIX } from '../../../shared/secform' /** * The Bot UI's daemon side (Bot Phase 1 §5.3, §5.11): create a bot from a look and a sentence, @@ -499,6 +500,14 @@ export class BotChatService { * The local vault resolves its recipient here, never from a window's thread id. Every bot may be given secrets: one * with an approved grant may keep a pasted key. */ + /** + * `/secform` in the bot's chat: a quiet line from Mousse that names the secrets, which the bot reads with its next turn + * and the chat shows as the chip. It wakes nothing. + */ + postSecretShare(botId: string, shareId: string, text: string): void { + this.engine.chat.post({ id: `${SECFORM_LINE_PREFIX}${shareId}`, botId, author: 'bot', kind: 'notice', text, quiet: true, lane: 'chat' }) + } + secretHome(botId: string): { threadId: string; allowed: boolean } { this.engine.definitionOf(botId) const threadId = this.store.registry(botId)?.homeThreadId diff --git a/src/mms/bots/chat/projection.ts b/src/mms/bots/chat/projection.ts index 1b347783d7..fd8db7ce16 100644 --- a/src/mms/bots/chat/projection.ts +++ b/src/mms/bots/chat/projection.ts @@ -29,9 +29,10 @@ import { takeToolImages } from './toolImages' import { takeReplyCards } from './replyCards' import { readSilentReply, WAKE_LINE_PREFIX, wakeEventLabel } from '../../../shared/bots/personal/wakes' import { BOT_FOLD_LINE_PREFIX, BOT_FOLD_LINE_TITLE } from '../../../shared/bots/personal/memory' +import { SECFORM_LINE_PREFIX } from '../../../shared/secform' function isServiceLine(id: string): boolean { - return ['bm_asks_first_', 'bm_permission_', 'bm_schedule_ended_', 'bm_schedule_done_', WAKE_LINE_PREFIX, BOT_FOLD_LINE_PREFIX].some(prefix => id.startsWith(prefix)) + return ['bm_asks_first_', 'bm_permission_', 'bm_schedule_ended_', 'bm_schedule_done_', WAKE_LINE_PREFIX, BOT_FOLD_LINE_PREFIX, SECFORM_LINE_PREFIX].some(prefix => id.startsWith(prefix)) } import type { AppletReference } from '../../../shared/applets' import { BOT_USAGE_WINDOW_MS, botContextSummary, turnUsageSummary } from '../activation/turnUsage' @@ -448,6 +449,8 @@ export class BotChatProjection { ...(row.kind === 'notice' && isServiceLine(row.id) ? { systemLine: true as const } : {}), // A fold's line says what happened on hover (docs/plans/bot-context.md §14). ...(row.kind === 'notice' && row.id.startsWith(BOT_FOLD_LINE_PREFIX) ? { systemTitle: BOT_FOLD_LINE_TITLE } : {}), + // Secrets shared with /secform: the chat shows the form's chip instead of the words the bot reads. + ...(row.kind === 'notice' && row.id.startsWith(SECFORM_LINE_PREFIX) ? { secretShare: { shareId: row.id.slice(SECFORM_LINE_PREFIX.length) } } : {}), text: plain ? (said ? `${said}\n\n${plain}` : plain) : said, ...(plain ? { plainFrom: said.length } : {}), ...(cards.length ? { cards } : {}), diff --git a/src/mms/bridge/routed/OwnerRoutes.ts b/src/mms/bridge/routed/OwnerRoutes.ts index 9f28452d20..d13e074a01 100644 --- a/src/mms/bridge/routed/OwnerRoutes.ts +++ b/src/mms/bridge/routed/OwnerRoutes.ts @@ -8,6 +8,7 @@ import type { NodeCapability } from '../../../shared/net' import { ROUTED_AGENT_BOT_KEY, ROUTED_DISPLAY_ONLY_KEYS, + ROUTED_SECRET_KEYS, ROUTED_AGENT_CHAIN_KEY, ROUTED_AGENT_KEY, routedKeyForbidden, @@ -724,7 +725,10 @@ export class OwnerRoutes { } : {}), // A display-only key (a bot's name and face) is no part of what a retry is matched on (#2010). - ...(ROUTED_DISPLAY_ONLY_KEYS[method] ? { ledgerMatch: (params: unknown) => withoutKeys(params, ROUTED_DISPLAY_ONLY_KEYS[method]!) } : {}), + // Nor is a secret value (`/secform`): the ledger keeps no hash of one. + ...(ROUTED_DISPLAY_ONLY_KEYS[method] || ROUTED_SECRET_KEYS[method] + ? { ledgerMatch: (params: unknown) => withoutKeys(params, [...(ROUTED_DISPLAY_ONLY_KEYS[method] ?? []), ...(ROUTED_SECRET_KEYS[method] ?? [])]) } + : {}), handle: (params, context) => this.options.track(this.run(method, row, params as Record, context)) } diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index dc1c978f61..41911f3f05 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -6312,6 +6312,24 @@ export class OrchestratorService extends EventEmitter { } } + /** + * `/secform`: the person shared secrets in this thread. The chat gets the chip's row (`secretShare`); the agent that + * may use them (`usableIn`: this thread, or a thread a bot works in) gets `note`, quiet, with its next turn. Both name + * the secrets only: their values never pass through here. + */ + recordSecretShare(threadId: string, share: { shareId: string; names: string[] }, note: { threadId: string; text: string } | undefined): void { + this.sessionAls.run(this.getOrCreateSession(threadId), () => this.addSystemMessage(`Shared ${share.names.join(', ')} with /secform.`, undefined, undefined, undefined, share)) + if (!note) return + const payload: AgentNotePayload = { + kind: 'agent_note', senderThreadId: threadId, senderRunId: '', senderTitle: null, senderAccess: 'agent', from: 'relay', attention: 'none', text: note.text + } + try { + postNote(this.requireRunEngine(), `secform:${share.shareId}`, payload, note.threadId) + } catch (error) { + console.warn('the agent could not be told the names of shared secrets', { shareId: share.shareId, error: error instanceof Error ? error.message : String(error) }) + } + } + /** Tells a held message's sender what became of it, with a quiet note from Mousse it reads with its next turn. */ private tellHoldSender(hold: ChainHoldRecord, outcome: string): void { // A sender on another computer has no thread here to tell: it was told its message is held, and ended its turn. @@ -14309,12 +14327,13 @@ export class OrchestratorService extends EventEmitter { * `kind` `warning`: a line the thread shows, quiet, as Mousse's own (`ThreadNotice`). Others are not shown, the note * of a launched thread (`launchedThread`) among them. */ - private addSystemMessage(content: string, end?: { turnId?: string; turnEnd: TurnEnd }, kind?: 'warning', launchedThread?: ChatMessage['launchedThread']): void { + private addSystemMessage(content: string, end?: { turnId?: string; turnEnd: TurnEnd }, kind?: 'warning', launchedThread?: ChatMessage['launchedThread'], secretShare?: ChatMessage['secretShare']): void { const msg: ChatMessage = { id: uuidv4(), role: 'system', ...(kind ? { kind } : {}), ...(launchedThread ? { launchedThread } : {}), + ...(secretShare ? { secretShare: { shareId: secretShare.shareId, names: [...secretShare.names] } } : {}), content, timestamp: new Date().toISOString(), ...(end?.turnId ? { turnId: end.turnId } : {}), diff --git a/src/mms/protocol/server.ts b/src/mms/protocol/server.ts index b1e167724a..b5ca383f56 100644 --- a/src/mms/protocol/server.ts +++ b/src/mms/protocol/server.ts @@ -875,6 +875,13 @@ export class MmsProtocolServer { emitToSubscribers(this.ring.push('secrets.requests.changed', { threadId: payload.threadId }, payload.threadId)) }) } + // Secrets shared with /secform: only the thread id travels; a window reads the thread's chips itself. + const secretShares = services.secretShares + if (secretShares) { + onEmitter(secretShares, 'changed', (payload: { threadId: string }) => { + emitToSubscribers(this.ring.push('secrets.shares.changed', { threadId: payload.threadId }, payload.threadId)) + }) + } // Computer use setup cards: only the thread id travels; a window of this computer reads the card itself. Nothing // waits on one, so the thread's state stays as it is. const computerSetup = typeof services.orchestrator.computerUseSetup === 'function' ? services.orchestrator.computerUseSetup() : undefined diff --git a/src/mms/protocol/types.ts b/src/mms/protocol/types.ts index c00ed996ef..ace728c624 100644 --- a/src/mms/protocol/types.ts +++ b/src/mms/protocol/types.ts @@ -703,6 +703,7 @@ export type ProtocolEventType = | 'questions.pending' | 'questions.cleared' | 'secrets.requests.changed' + | 'secrets.shares.changed' | 'computerUse.setupRequest.changed' | 'secrets.changed' | 'pty.data' @@ -732,6 +733,7 @@ export type ProtocolEventType = | 'questions.pending' | 'questions.cleared' | 'secrets.requests.changed' + | 'secrets.shares.changed' | 'computerUse.setupRequest.changed' | 'secrets.changed' | 'pty.data' diff --git a/src/mms/run/mcp/appTools/secrets.ts b/src/mms/run/mcp/appTools/secrets.ts index d606b7b51e..a604682b86 100644 --- a/src/mms/run/mcp/appTools/secrets.ts +++ b/src/mms/run/mcp/appTools/secrets.ts @@ -57,7 +57,7 @@ const REQUEST_DEFINITION: Tool = { const RUN_DEFINITION: Tool = { name: 'secret_run', description: [ - 'Run one shell command in the thread\'s project folder with secrets the user gave this thread (through secret_request).', + 'Run one shell command in the thread\'s project folder with secrets the user gave this thread (through secret_request, or shared with /secform).', 'Each secret is the environment variable of its name (as: "env", the default), or a private file whose path is in NAME_FILE', '(as: "file"); the file is deleted when the command ends. Refer to the variable in the command (e.g. "$HF_TOKEN"), never the value.', 'The output comes back with every secret masked, and Authorization headers hidden.', @@ -247,7 +247,7 @@ export function secretTools(host: AppToolHost): MousseTool[] { approvalPrompt: 'Allow the agent to run this command with a secret you gave this thread?', // A personal bot's owner allowed "use secrets you give it" and "run commands": that is its answer, so nothing asks. botGrantAnswers: true, - botDescription: 'Run a command from your files folder with secrets your owner gave you (secret_request): each as an environment variable (default) or a private file, by name. Its output is masked. It runs without asking first, as your other commands do: from your files folder, with none of your owner\'s other settings or credentials, only the secrets you name. With your command sandbox on it runs there (only your folders, and the network as your owner set it); with it off, like your owner\'s own commands. Use it only for the work your owner asked for.', + botDescription: 'Run a command from your files folder with secrets your owner gave you (secret_request, or shared with /secform): each as an environment variable (default) or a private file, by name. Its output is masked. It runs without asking first, as your other commands do: from your files folder, with none of your owner\'s other settings or credentials, only the secrets you name. With your command sandbox on it runs there (only your folders, and the network as your owner set it); with it off, like your owner\'s own commands. Use it only for the work your owner asked for.', class: 'mutation', listed: () => Boolean(secrets()), available: (turn) => (secrets() ? runAvailable(turn) : 'secret_run is not available here.'), diff --git a/src/mms/secrets/SecretShares.ts b/src/mms/secrets/SecretShares.ts new file mode 100644 index 0000000000..9ac1433119 --- /dev/null +++ b/src/mms/secrets/SecretShares.ts @@ -0,0 +1,262 @@ +import { EventEmitter } from 'node:events' +import { randomUUID } from 'node:crypto' +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { isKeyName } from '../../shared/automationKeys' +import { secretValueProblem } from '../../shared/secretRequests' +import { + SECFORM_EXPIRIES, + SECFORM_MAX_FIELDS, + secformExpiresAt, + type SecformAudience, + type SecformExpiry, + type SecretShareState, + type SecretShareView +} from '../../shared/secform' +import { atomicWriteJsonSync } from '../data/AtomicFs' +import { ensurePrivateDirectory } from '../data/privateAcl' +import { SecretRequestError } from './SecretRequests' +import type { SecretVault } from './SecretVault' + +/** One form's record in `secrets/shares.json`: names and times, never a value. */ +interface ShareRecord { + /** The thread the form was opened in: its chat shows the chip. */ + threadId: string + /** The thread whose agents may use the secrets: the same thread, or a bot's chat. */ + usableIn: string + botId?: string + names: string[] + createdAt: string + expiresAt?: string + singleUse?: true + revokedAt?: string + /** Single-use names that were used, and so deleted. */ + usedUp?: string[] +} + +/** + * Names a command already uses: a secret under one would replace it inside every command it is given to (`secret_run` + * sets it as an environment variable). + */ +const RESERVED_NAMES = new Set(['PATH', 'HOME', 'SHELL', 'PWD', 'LANG', 'TERM', 'TMP', 'TEMP', 'TMPDIR', 'NODE_OPTIONS', 'NODE_PATH', 'PYTHONPATH', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'DYLD_INSERT_LIBRARIES', 'DYLD_LIBRARY_PATH', 'SYSTEMROOT', 'COMSPEC', 'PATHEXT', 'APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMDATA']) + +/** How long an ended form's record stays, so its chip still says what happened. */ +const ENDED_RECORD_KEEP_MS = 30 * 24 * 60 * 60 * 1000 + +export interface SecretSharesOptions { + profileRoot: string + vault: SecretVault + /** Whether a thread exists and is not archived. */ + threadAlive(threadId: string): boolean + /** A bot's chat thread, when the bot may keep secrets. */ + botHome?(botId: string): { threadId: string; allowed: boolean } + now?(): number +} + +/** + * The secrets a person shares with `/secform` (asks i121, i125). Each field's value goes once into the vault, the + * profile's secret store, kept as long as the form chose and usable by the thread or bot it chose; this service keeps + * which names one form gave and whether they are still kept, expired or revoked, for the chip the chat shows. The + * service sees values only inside `share`, which hands them straight to the vault. + */ +export class SecretShares extends EventEmitter { + private readonly path: string + private readonly now: () => number + + constructor(private readonly options: SecretSharesOptions) { + super() + this.path = join(options.profileRoot, 'secrets', 'shares.json') + this.now = options.now ?? Date.now + } + + /** Save securely: stores every field or none, and returns the chip's view with the names they are kept under. */ + share(input: { threadId: string; fields: unknown; expiry: unknown; singleUse: unknown; audience: unknown }): SecretShareView & { usableIn: string } { + const { threadId } = input + if (!this.options.threadAlive(threadId)) throw new SecretRequestError('not_found', 'This thread is gone.') + const fields = this.fieldsOf(input.fields) + if (typeof input.expiry !== 'string' || !(SECFORM_EXPIRIES as readonly string[]).includes(input.expiry)) throw new SecretRequestError('invalid', 'Choose when it expires.') + const expiry = input.expiry as SecformExpiry + const singleUse = input.singleUse === true + const audience = this.audienceOf(input.audience) + const usableIn = audience.kind === 'bot' ? this.botThread(audience.botId) : threadId + const now = this.now() + const expiresAt = secformExpiresAt(expiry, now) + const shareId = randomUUID() + const vault = this.options.vault + const names: string[] = [] + try { + for (const field of fields) { + const name = vault.freeName(field.name) + vault.store(name, field.value, { + keep: expiresAt ? 'day' : 'saved', + ...(expiresAt ? { expiresAt } : {}), + threadId: usableIn, + ...(field.label ? { label: field.label } : {}), + shareId, + singleUse + }) + names.push(name) + } + } catch (error) { + // All or nothing: a field that failed takes back the ones before it. + for (const name of names) vault.delete(name) + throw error + } + const record: ShareRecord = { + threadId, + usableIn, + ...(audience.kind === 'bot' ? { botId: audience.botId } : {}), + names, + createdAt: new Date(now).toISOString(), + ...(expiresAt ? { expiresAt } : {}), + ...(singleUse ? { singleUse: true as const } : {}) + } + this.write({ ...this.prune(this.read()), [shareId]: record }) + this.changed(record) + return { ...this.view(shareId, record), usableIn } + } + + /** The forms given in a thread, or for it (a bot's chat: forms whose secrets it may use), oldest first. */ + list(threadId: string): SecretShareView[] { + return Object.entries(this.read()) + .filter(([, record]) => record.threadId === threadId || record.usableIn === threadId) + .sort(([, a], [, b]) => a.createdAt.localeCompare(b.createdAt)) + .map(([shareId, record]) => this.view(shareId, record)) + } + + /** Revoke: every secret of the form still kept is deleted now. */ + revoke(threadId: string, shareId: string): SecretShareView { + const records = this.read() + const record = records[shareId] + if (!record || (record.threadId !== threadId && record.usableIn !== threadId)) throw new SecretRequestError('not_found', 'These secrets are no longer listed.') + for (const name of record.names) if (this.options.vault.shareOf(name) === shareId) this.options.vault.delete(name) + const next = record.revokedAt ? record : { ...record, revokedAt: new Date(this.now()).toISOString() } + this.write({ ...records, [shareId]: next }) + this.changed(next) + return this.view(shareId, next) + } + + /** A single-use secret was used: its form remembers it, so the chip reads expired rather than revoked. */ + usedUp(name: string, shareId: string | undefined): void { + if (!shareId) return + const records = this.read() + const record = records[shareId] + if (!record || record.usedUp?.includes(name)) return + this.write({ ...records, [shareId]: { ...record, usedUp: [...(record.usedUp ?? []), name] } }) + this.changed(record) + } + + /** The store changed (Settings removed one, a sweep expired one): every chip that may read differently is told. */ + storeChanged(): void { + const threads = new Set(Object.values(this.read()).filter((record) => !record.revokedAt).flatMap((record) => [record.threadId, record.usableIn])) + for (const threadId of threads) this.emit('changed', { threadId }) + } + + /** Both chats that show a form's chip are told: where it was filled in, and the bot chat that may use it. */ + private changed(record: ShareRecord): void { + this.emit('changed', { threadId: record.threadId }) + if (record.usableIn !== record.threadId) this.emit('changed', { threadId: record.usableIn }) + } + + private view(shareId: string, record: ShareRecord): SecretShareView { + return { + shareId, + threadId: record.threadId, + names: [...record.names], + createdAt: record.createdAt, + ...(record.expiresAt ? { expiresAt: record.expiresAt } : {}), + ...(record.singleUse ? { singleUse: true } : {}), + ...(record.botId ? { botId: record.botId } : {}), + state: this.stateOf(shareId, record) + } + } + + /** + * Revoked when taken back on the chip; expired when its time passed or every single-use secret was used; revoked as + * well when the secrets were deleted some other way (Settings → Secrets). + */ + private stateOf(shareId: string, record: ShareRecord): SecretShareState { + if (record.revokedAt) return 'revoked' + if (record.expiresAt && Date.parse(record.expiresAt) <= this.now()) return 'expired' + const kept = record.names.filter((name) => this.options.vault.shareOf(name) === shareId) + if (kept.length) return 'saved' + return record.usedUp?.length ? 'expired' : 'revoked' + } + + private fieldsOf(raw: unknown): Array<{ name: string; label?: string; value: string }> { + if (!Array.isArray(raw) || raw.length === 0) throw new SecretRequestError('invalid', 'Add a secret.') + if (raw.length > SECFORM_MAX_FIELDS) throw new SecretRequestError('invalid', `A form holds at most ${SECFORM_MAX_FIELDS} secrets.`) + const seen = new Set() + return raw.map((field, index) => { + const entry = (field && typeof field === 'object' ? field : {}) as Record + const where = raw.length > 1 ? ` (field ${index + 1})` : '' + if (!isKeyName(entry.name)) throw new SecretRequestError('invalid', `Name it with a word like GITHUB_TOKEN${where}.`) + if (seen.has(entry.name)) throw new SecretRequestError('invalid', `${entry.name} is named twice.`) + if (RESERVED_NAMES.has(entry.name)) throw new SecretRequestError('invalid', `Commands already use ${entry.name}; name it something else, like MY_${entry.name}.`) + seen.add(entry.name) + const problem = secretValueProblem(entry.value) + // The problem never repeats the value. + if (problem) throw new SecretRequestError('invalid', `${entry.name}: ${problem}`) + const label = typeof entry.label === 'string' && entry.label.trim() ? entry.label.trim().slice(0, 120) : undefined + return { name: entry.name, value: entry.value as string, ...(label ? { label } : {}) } + }) + } + + private audienceOf(raw: unknown): SecformAudience { + if (raw === undefined || raw === null) return { kind: 'thread' } + const entry = (typeof raw === 'object' ? raw : {}) as Record + if (entry.kind === 'thread') return { kind: 'thread' } + if (entry.kind === 'bot' && typeof entry.botId === 'string' && entry.botId && entry.botId.length <= 256) return { kind: 'bot', botId: entry.botId } + throw new SecretRequestError('invalid', 'Choose who can use it.') + } + + private botThread(botId: string): string { + const home = this.options.botHome?.(botId) + if (!home?.allowed) throw new SecretRequestError('invalid', "That bot is not set up yet, so it can't use secrets.") + return home.threadId + } + + /** Ended forms older than a month are forgotten. */ + private prune(records: Record): Record { + const now = this.now() + const out: Record = {} + for (const [shareId, record] of Object.entries(records)) { + const ended = this.stateOf(shareId, record) !== 'saved' + if (ended && now - Date.parse(record.createdAt) > ENDED_RECORD_KEEP_MS) continue + out[shareId] = record + } + return out + } + + private read(): Record { + if (!existsSync(this.path)) return {} + try { + const parsed = JSON.parse(readFileSync(this.path, 'utf8')) as unknown + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {} + const out: Record = {} + for (const [shareId, raw] of Object.entries(parsed as Record)) { + const entry = (raw && typeof raw === 'object' ? raw : {}) as Partial + if (typeof entry.threadId !== 'string' || typeof entry.usableIn !== 'string' || typeof entry.createdAt !== 'string' || !Array.isArray(entry.names)) continue + out[shareId] = { + threadId: entry.threadId, + usableIn: entry.usableIn, + ...(typeof entry.botId === 'string' ? { botId: entry.botId } : {}), + names: entry.names.filter(isKeyName), + createdAt: entry.createdAt, + ...(typeof entry.expiresAt === 'string' ? { expiresAt: entry.expiresAt } : {}), + ...(entry.singleUse === true ? { singleUse: true as const } : {}), + ...(typeof entry.revokedAt === 'string' ? { revokedAt: entry.revokedAt } : {}), + ...(Array.isArray(entry.usedUp) ? { usedUp: entry.usedUp.filter(isKeyName) } : {}) + } + } + return out + } catch { + return {} + } + } + + private write(records: Record): void { + ensurePrivateDirectory(join(this.options.profileRoot, 'secrets')) + atomicWriteJsonSync(this.path, records, { mode: 0o600 }) + } +} diff --git a/src/mms/secrets/SecretVault.ts b/src/mms/secrets/SecretVault.ts index b89fa8adf3..7b91d28f2c 100644 --- a/src/mms/secrets/SecretVault.ts +++ b/src/mms/secrets/SecretVault.ts @@ -21,6 +21,10 @@ interface SecretMeta { lastUsedAt?: string /** The threads whose agents may use it by name: the one that asked, and any thread the person gave it to later. */ threads: string[] + /** The `/secform` form that gave it (`SecretShares`). */ + shareId?: string + /** Deleted after its first use; never given as a file, so every use goes through Mousse and is counted. */ + singleUse?: true } type MetaFile = Record @@ -84,6 +88,8 @@ export interface SecretVaultOptions { removePath?(path: string): void /** The store changed (a secret added, used, deleted or expired). */ changed?(): void + /** A single-use secret was used and deleted. */ + usedUp?(name: string, shareId: string | undefined): void } /** @@ -189,7 +195,8 @@ export class SecretVault { isSaved(name: string, binding?: SecretBinding): boolean { if (!this.hasValue(name)) return false const meta = this.readMeta()[name] - return (!meta || meta.keep === 'saved') && sameSecretBinding(this.bindingFor(name), binding) + // A /secform secret kept with no end is for the thread or bot it was shared with, not offered to others. + return (!meta || (meta.keep === 'saved' && !meta.shareId)) && sameSecretBinding(this.bindingFor(name), binding) } /** `base`, or `base_2`, `base_3`… when the store already holds `base`. */ @@ -204,8 +211,11 @@ export class SecretVault { throw new Error('Too many secrets share this name.') } - /** Keeps a value the person typed, for the thread that asked. The name must be free (`freeName`). */ - store(name: string, value: string, input: { keep: SecretKeep; threadId: string; label?: string; binding?: SecretBinding }): void { + /** + * Keeps a value the person typed, for the thread that asked. The name must be free (`freeName`). A `/secform` + * secret comes with its own end (`expiresAt`, kept as `day`), its form and whether it is single use. + */ + store(name: string, value: string, input: { keep: SecretKeep; threadId: string; label?: string; binding?: SecretBinding; expiresAt?: string; shareId?: string; singleUse?: boolean }): void { if (!isKeyName(name)) throw new Error('A secret name is a word like GITHUB_TOKEN.') if (this.hasValue(name)) throw new Error(`A secret named ${name} already exists.`) const now = this.now() @@ -217,10 +227,12 @@ export class SecretVault { [name]: { ...(input.label ? { label: input.label.slice(0, 200) } : {}), keep: input.keep, - ...(input.keep === 'day' ? { expiresAt: new Date(now + SECRET_DAY_MS).toISOString() } : {}), + ...(input.keep === 'day' ? { expiresAt: input.expiresAt ?? new Date(now + SECRET_DAY_MS).toISOString() } : {}), threadId: input.threadId, createdAt: new Date(now).toISOString(), - threads: [input.threadId] + threads: [input.threadId], + ...(input.shareId ? { shareId: input.shareId } : {}), + ...(input.singleUse ? { singleUse: true as const } : {}) } }) this.didChange() @@ -287,7 +299,7 @@ export class SecretVault { /** The private file that holds the secret for the thread's agents to read; undefined when the thread may not use it. */ fileFor(name: string, threadId: string): string | undefined { - if (!isKeyName(name) || !FOLDER_ID.test(threadId) || !this.usableIn(name, threadId) || this.bindingFor(name)) return undefined + if (!isKeyName(name) || !FOLDER_ID.test(threadId) || !this.usableIn(name, threadId) || this.bindingFor(name) || this.readMeta()[name]?.singleUse) return undefined const path = join(this.filesRoot, threadId, name) return existsSync(path) ? path : undefined } @@ -301,13 +313,24 @@ export class SecretVault { return this.bindings.get(name) } + /** A command or a read used the secret. A single-use secret is deleted now: the use that called this has its value. */ markUsed(name: string): void { const meta = this.readMeta() if (!meta[name]) return + if (meta[name].singleUse) { + this.delete(name) + this.options.usedUp?.(name, meta[name].shareId) + return + } this.writeMeta({ ...meta, [name]: { ...meta[name], lastUsedAt: new Date(this.now()).toISOString() } }) this.options.changed?.() } + /** The `/secform` form a secret came from, while it is still kept. */ + shareOf(name: string): string | undefined { + return this.hasValue(name) ? this.readMeta()[name]?.shareId : undefined + } + /** * What masks a thread's text: every secret its agents may use, and its parents' when it is a subagent's, in * every form it can take; while a turn that had a removed or changed value settles, that value too. Undefined when @@ -402,6 +425,8 @@ export class SecretVault { ...(entry.threadId ? { threadId: entry.threadId } : {}), ...(entry.threads?.length ? { threads: [...entry.threads] } : {}), ...(title ? { threadTitle: title } : {}), + ...(entry.shareId ? { shareId: entry.shareId } : {}), + ...(entry.singleUse ? { singleUse: true } : {}), createdAt: entry.createdAt, ...(entry.lastUsedAt ? { lastUsedAt: entry.lastUsedAt } : {}) } @@ -411,7 +436,7 @@ export class SecretVault { /** The names a saved key list shows: secrets given in a thread for a while are not saved keys. */ savedKeyNames(): string[] { const meta = this.readMeta() - return listProfileKeyNames(this.options.profileRoot).filter((name) => !this.bindingFor(name) && (!meta[name] || meta[name].keep === 'saved')) + return listProfileKeyNames(this.options.profileRoot).filter((name) => !this.bindingFor(name) && (!meta[name] || (meta[name].keep === 'saved' && !meta[name].shareId))) } /** Removes a secret and its record; false when there was none. */ @@ -493,7 +518,7 @@ export class SecretVault { try { const wanted = new Map>() for (const [name, entry] of Object.entries(this.readMeta())) { - if (this.bindingFor(name)) continue + if (this.bindingFor(name) || entry.singleUse) continue const threads = entry.threads.filter((threadId) => FOLDER_ID.test(threadId) && this.copyThreads.has(threadId) && !this.holds.has(threadId) && this.options.threadAlive(threadId)) const value = threads.length ? this.value(name) : undefined if (!value) continue @@ -555,6 +580,8 @@ export class SecretVault { ...(typeof entry.threadId === 'string' ? { threadId: entry.threadId } : {}), createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : new Date(0).toISOString(), ...(typeof entry.lastUsedAt === 'string' ? { lastUsedAt: entry.lastUsedAt } : {}), + ...(typeof entry.shareId === 'string' ? { shareId: entry.shareId } : {}), + ...(entry.singleUse === true ? { singleUse: true as const } : {}), threads: Array.isArray(entry.threads) ? entry.threads.filter((id): id is string => typeof id === 'string') : [] } } diff --git a/src/mms/secrets/registerMethods.ts b/src/mms/secrets/registerMethods.ts index 4ac99ce388..e7aec12a8e 100644 --- a/src/mms/secrets/registerMethods.ts +++ b/src/mms/secrets/registerMethods.ts @@ -7,6 +7,7 @@ import type { SecretEntryView, SecretRequestView } from '../../shared/secretRequ import { DomainRpcError, domainObject, type DomainHandlerRegistry } from '../protocol/domainRegistry' import type { HandlerContext } from '../protocol/handlers' import { SecretRequestError } from './SecretRequests' +import type { SecretShareView } from '../../shared/secform' export const SECRETS_CAPABILITY = 'secrets.v1' @@ -19,6 +20,12 @@ export interface SecretsDomain { decline(threadId: string, requestId: string): void } pasted?: { vault: SecretVault; homeFor(botId: string): { threadId: string; allowed: boolean } } + /** `/secform`: the secrets a person shares in a thread or a bot's chat. */ + shares?: { + share(input: { threadId: string; fields: unknown; expiry: unknown; singleUse: unknown; audience: unknown }): SecretShareView + list(threadId: string): SecretShareView[] + revoke(threadId: string, shareId: string): SecretShareView + } list(): SecretEntryView[] delete(name: string): boolean } @@ -33,6 +40,16 @@ function fromWindow(context: HandlerContext): void { if (context.connection?.clientType !== 'gui') throw new DomainRpcError('forbidden', 'Answer it in a Mousse window on the computer that runs the thread.') } +/** + * `/secform` is filled in by a person at a Mousse window: on this computer, or on another of the user's computers for a + * thread this one runs (a routed call, sent over the encrypted link between them). Never an agent or a CLI. + */ +function fromPerson(context: HandlerContext): void { + const connection = context.connection + if (connection?.clientType === 'gui' || (connection?.clientType === 'bridge' && connection.bridgeCaller)) return + throw new DomainRpcError('forbidden', 'Share secrets from a Mousse window.') +} + /** A refusal in words that never repeat what was typed. */ function refusal(error: unknown): never { if (error instanceof DomainRpcError) throw error @@ -154,6 +171,67 @@ export function registerSecretMethods(domains: DomainHandlerRegistry, domainFor: } } }) + domains.register({ + method: 'secrets.share', + scope: 'profile', + capability: SECRETS_CAPABILITY, + validate: (params) => { + // Unknown fields are refused without naming them: even a malformed form may hold a value there. + if (!params || typeof params !== 'object' || Array.isArray(params) || Object.keys(params).some((key) => !['profileId', 'threadId', 'fields', 'values', 'expiry', 'singleUse', 'audience'].includes(key))) { + throw new DomainRpcError('invalid_params', 'Fill in the form again.') + } + const p = params as Record + id(p.threadId, 'A thread id') + if (!Array.isArray(p.fields) || !Array.isArray(p.values) || p.fields.length !== p.values.length) throw new DomainRpcError('invalid_params', 'Fill in the form again.') + return p + }, + async handle(context, params, binding) { + fromPerson(context) + const domain = await bound(binding) + if (!domain.shares) throw new DomainRpcError('not_found', 'Secrets cannot be shared here.') + // The values travel apart from the names (`values`), so a routed call's ledger never matches a retry on them. + const fields = (params.fields as unknown[]).map((field, index) => ({ ...(field && typeof field === 'object' ? field : {}), value: (params.values as unknown[])[index] })) + try { + return { share: domain.shares.share({ threadId: params.threadId as string, fields, expiry: params.expiry, singleUse: params.singleUse, audience: params.audience }) } + } catch (error) { + refusal(error) + } + } + }) + domains.register({ + method: 'secrets.shares.list', + scope: 'profile', + capability: SECRETS_CAPABILITY, + validate: (params) => { + const p = domainObject(params ?? {}, ['profileId', 'threadId']) + id(p.threadId, 'A thread id') + return p + }, + async handle(_context, params, binding) { + return { shares: (await bound(binding)).shares?.list(params.threadId as string) ?? [] } + } + }) + domains.register({ + method: 'secrets.shares.revoke', + scope: 'profile', + capability: SECRETS_CAPABILITY, + validate: (params) => { + const p = domainObject(params ?? {}, ['profileId', 'threadId', 'shareId']) + id(p.threadId, 'A thread id') + id(p.shareId, 'A share id') + return p + }, + async handle(context, params, binding) { + fromPerson(context) + const domain = await bound(binding) + if (!domain.shares) throw new DomainRpcError('not_found', 'These secrets are no longer listed.') + try { + return { share: domain.shares.revoke(params.threadId as string, params.shareId as string) } + } catch (error) { + refusal(error) + } + } + }) domains.register({ method: 'secrets.list', scope: 'profile', diff --git a/src/mms/secrets/secretShareNote.ts b/src/mms/secrets/secretShareNote.ts new file mode 100644 index 0000000000..e46359a919 --- /dev/null +++ b/src/mms/secrets/secretShareNote.ts @@ -0,0 +1,29 @@ +import type { SecretShareView } from '../../shared/secform' + +/** "2026-12-02 10:00 UTC": an end that still reads right when the note is read hours later. */ +function at(iso: string): string { + return `${new Date(iso).toISOString().slice(0, 16).replace('T', ' ')} UTC` +} + +/** + * What the agent (or bot) that may use secrets shared with `/secform` is told, quietly, with its next turn: their names, + * when they end and how to use them. Never a value. Agent-facing wording, reviewed by a council (three reviewers, + * December 2026); a change to it goes through that review again. + */ +export function secretShareNote(share: Pick): string { + const [first] = share.names + const many = share.names.length > 1 + const names = share.names.map((name) => `\`${name}\``).join(', ') + return [ + many ? `The user shared ${share.names.length} secrets with you. Names: ${names}.` : `The user shared a secret with you. Name: ${names}.`, + `Mousse keeps the ${many ? 'values' : 'value'} out of the chat; you have the ${many ? 'names' : 'name'} only.`, + share.expiresAt ? `${many ? 'They expire' : 'It expires'} at ${at(share.expiresAt)}.` : `No expiry: the user removes ${many ? 'them' : 'it'} when done.`, + `This note asks for nothing: use ${many ? 'them' : 'it'} only when a task the user asked for needs ${many ? 'them' : 'it'}.`, + `Pass secrets [{ "name": "${first}" }] to secret_run: that one command gets the value as the environment variable ${first}, and its output comes back masked.${many ? ' One command can name several.' : ''}`, + share.singleUse + ? `Single use: Mousse deletes ${many ? 'each one' : 'it'} after the first secret_run command that names it, even if that command fails, so do not test ${many ? 'them' : 'it'} first${many ? ', and name every one a command needs in that command' : ''}.` + : `In an MCP server's settings, \${secret:${first}} reads it.`, + `If ${many ? 'one is' : 'it is'} gone, ask the user to share it again with /secform; never ask them to paste a value in the chat.`, + 'Never print or echo a value in a reply, a message or command output.' + ].join(' ') +} diff --git a/src/mms/secrets/secretToolHost.ts b/src/mms/secrets/secretToolHost.ts index 46e445a891..69d0779226 100644 --- a/src/mms/secrets/secretToolHost.ts +++ b/src/mms/secrets/secretToolHost.ts @@ -26,12 +26,14 @@ export function createSecretToolHost(input: { vault: SecretVault; requests: Secr if (value === undefined) throw new Error(`The secret ${entry.name} is gone (it expired or was removed).`) return { ...entry, value } }) + // Built before the use is counted: a single-use secret is deleted then, and its output must still be masked. + const mask = vault.maskerFor(run.threadId) ?? ((text: string) => text) for (const entry of secrets) vault.markUsed(entry.name) return runWithSecrets({ command: run.command, cwd: run.cwd, secrets, - mask: vault.maskerFor(run.threadId) ?? ((text) => text), + mask, scratchRoot: input.scratchRoot, timeoutMs: run.timeoutMs, signal: run.signal, diff --git a/src/preload/index.ts b/src/preload/index.ts index f8d166b231..69e817f743 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -351,6 +351,12 @@ const api = { ipcRenderer.on('secrets:requestsChanged', handler) return () => ipcRenderer.removeListener('secrets:requestsChanged', handler) }, + /** A thread's secrets shared with `/secform` changed; read them with `secrets.shares.list`. Carries no value. */ + onSecretSharesChanged: (cb: (payload: { threadId: string }) => void): (() => void) => { + const handler = (_: Electron.IpcRendererEvent, payload: { threadId: string }) => cb(payload) + ipcRenderer.on('secrets:sharesChanged', handler) + return () => ipcRenderer.removeListener('secrets:sharesChanged', handler) + }, /** A thread's computer use setup card changed; read it with `computerUse.setupRequest.get`. */ onComputerUseSetupRequestChanged: (cb: (payload: { threadId: string }) => void): (() => void) => { const handler = (_: Electron.IpcRendererEvent, payload: { threadId: string }) => cb(payload) diff --git a/src/renderer/chat/adapters/mousseToUI.ts b/src/renderer/chat/adapters/mousseToUI.ts index 8d4c73302d..a2e0379d67 100644 --- a/src/renderer/chat/adapters/mousseToUI.ts +++ b/src/renderer/chat/adapters/mousseToUI.ts @@ -555,6 +555,16 @@ export function mousseToUIMessages(messages: ChatMessage[], senders?: TurnSender continue } + // Secrets the person shared with /secform: a chip of Mousse's own (names only), apart from the agent's answer. + if (msg.role === 'system' && msg.secretShare) { + base.metadata = { ...base.metadata as object, notice: true, secretShare: msg.secretShare } + base.parts = [{ type: 'text', text: msg.content } as unknown as UIMessage['parts'][number]] + base.role = 'assistant' + out.push(base) + lastAssistantText = null + continue + } + if (msg.kind === 'progress' || msg.kind === 'warning' || msg.kind === 'context_compaction' || msg.kind === 'context_cleared') { if (msg.kind === 'context_cleared') base.metadata = { ...base.metadata as object, contextCleared: true } if (msg.kind === 'context_compaction') base.metadata = { ...base.metadata as object, compaction: true, compacting: msg.streaming === true, diff --git a/src/renderer/chat/components/agent-elements/message-list.tsx b/src/renderer/chat/components/agent-elements/message-list.tsx index 22e1d387a9..6aeef8ba90 100644 --- a/src/renderer/chat/components/agent-elements/message-list.tsx +++ b/src/renderer/chat/components/agent-elements/message-list.tsx @@ -57,6 +57,7 @@ import { SubagentCardGroup } from "./tools/SubagentCard"; import { isCardRunning } from "./tools/subagent-card-logic"; import type { SubagentCardModel } from "../../adapters/subagentCards"; import { SecretRequestInline, isSecretRequestPart, isWaitingSecretRequest } from "../../../components/secrets/secretRequestPart"; +import { SecretShareChip } from "../../../components/secrets/SecretShareChip"; import { BackgroundNotice, SettleNotice, SubagentNotice } from "./tools/SubagentNotice"; import { SteerGroup } from "./steer-group"; import { isRunningSubagent } from "../../../../shared/subagents"; @@ -3620,7 +3621,11 @@ const AssistantParts = memo(function AssistantParts({ toolRenderers, ]); - if (isThreadNotice(msg)) return part.text).join('')} />; + if (isThreadNotice(msg)) { + const share = (msg.metadata as { secretShare?: { shareId: string; names: string[] } } | undefined)?.secretShare; + if (share) return ; + return part.text).join('')} />; + } const handoff = (msg.metadata as { contextHandoff?: HandoffMarker } | undefined)?.contextHandoff; if (handoff) return part.text).join('')} />; if ((msg.metadata as { contextCleared?: boolean } | undefined)?.contextCleared) diff --git a/src/renderer/components/ChatComposer.tsx b/src/renderer/components/ChatComposer.tsx index 17181ba205..6da752000a 100644 --- a/src/renderer/components/ChatComposer.tsx +++ b/src/renderer/components/ChatComposer.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { SECFORM_COMMAND } from '../../shared/secform' import type { ComponentProps, CSSProperties, ReactNode } from 'react' import { File as FileIcon, IconPhoto, MessageSquare, Mic, RefreshCw, Reply, X } from '../lib/icons' import type { @@ -1453,7 +1454,8 @@ export function ChatComposer({ const suggestion = item.command // An exact command that needs no text is already complete: execute it instead of // making users press Enter twice (first to re-apply the same suggestion). - if (e.key === 'Enter' && suggestion.argument !== 'required' && input.trim().toLowerCase() === `/${suggestion.name}`) { + // `/secform for email, password` too: its row stays while its fields are typed, and Enter opens the form. + if (e.key === 'Enter' && suggestion.argument !== 'required' && (input.trim().toLowerCase() === `/${suggestion.name}` || (suggestion.name === SECFORM_COMMAND && /^\/secform\s/i.test(input)))) { submit() } else { applySuggestion(suggestion) diff --git a/src/renderer/components/OrchestratorChat.tsx b/src/renderer/components/OrchestratorChat.tsx index a89cb92cc9..e14b48c4ae 100644 --- a/src/renderer/components/OrchestratorChat.tsx +++ b/src/renderer/components/OrchestratorChat.tsx @@ -151,6 +151,9 @@ import { SecretRequestActionsContext, useSecretRequestsElsewhere, withSecretRequ import { SecretRequestRow } from './secrets/SecretRequestRow' import { usePendingSecretRequests } from '../hooks/usePendingSecretRequests' import { createSecretsClient } from '../services/secretsClient' +import { SecformCard, type SecformAudienceOption } from './secrets/SecformCard' +import { SecretSharesContext, useSecretShares } from './secrets/SecretShareChip' +import type { SecformField } from '../../shared/secform' /** The chat's custom tool rows: drafts and run reports, and a secret request's row (#595). */ const THREAD_TOOL_RENDERERS = { ...CHAT_TOOL_RENDERERS, secret_request: SecretRequestRow } @@ -562,6 +565,15 @@ export function OrchestratorChat() { // The open thread's secret cards (#595): an agent asked for a secret; the value goes only to this computer's daemon. const secretsClient = useMemo(() => createSecretsClient(window.mousse?.platformRequest), []) const { requests: secretRequests, refresh: refreshSecretRequests } = usePendingSecretRequests(activeThreadId, secretsClient) + // `/secform`: the open form (its thread and the fields it opened with), and the chips of the forms given here. + const [secform, setSecform] = useState<{ threadId: string; fields: SecformField[] } | null>(null) + const secretShares = useSecretShares(activeThreadId, secretsClient) + const bots = useBotsStore((state) => state.bots) + // Who may use them: this thread, or a bot of this computer (a thread of another computer offers only itself). + const secformAudiences = useMemo(() => [ + { value: 'thread', label: 'This thread' }, + ...(activeThreadId && isQualifiedId(activeThreadId) ? [] : bots.filter((bot) => !bot.lives).map((bot) => ({ value: `bot:${bot.id}`, label: `${bot.name} only` }))) + ], [activeThreadId, bots]) const [connectionFailed, setConnectionFailed] = useState(false) const [sendFailure, setSendFailure] = useState(null) const sendError = sendFailure?.message ?? null @@ -1632,7 +1644,8 @@ export function OrchestratorChat() { rename: async (threadId, title) => { await window.mousse.threads.rename(threadId, title) }, // The sidebar cancels the event when it opened the thread's rename box. openRename: (threadId) => !window.dispatchEvent(new CustomEvent('mousse:rename-thread', { detail: { threadId }, cancelable: true })), - goal: (threadId, action, text) => window.mousse.platformRequest.request<{ text?: string }>('threads.goal', { threadId, action, ...(text !== undefined ? { text } : {}) }) + goal: (threadId, action, text) => window.mousse.platformRequest.request<{ text?: string }>('threads.goal', { threadId, action, ...(text !== undefined ? { text } : {}) }), + openSecform: (threadId, spec) => setSecform({ threadId, fields: spec.fields }) }) // A message sent from the warm start (WarmChat) while the window was connecting goes once, as an ordinary send of the @@ -2443,6 +2456,7 @@ export function OrchestratorChat() { entry.id === selectedProviderId)?.instanceId} snapshots={providerSnapshots} /> + + {/* /secform: the values go once to the computer that runs the thread, never into the composer or the chat. */} + {secform && secform.threadId === activeThreadId && ( +
+ setSecform(null)} + onSave={async (save) => { + const audience = save.audience.startsWith('bot:') ? { kind: 'bot' as const, botId: save.audience.slice(4) } : { kind: 'thread' as const } + await secretsClient.share({ threadId: secform.threadId, fields: save.fields, expiry: save.expiry, singleUse: save.singleUse, audience }) + secretShares.refresh() + setSecform(null) + }} + /> +
+ )} @@ -2659,6 +2691,7 @@ export function OrchestratorChat() { )} /> +
diff --git a/src/renderer/components/bots/BotChatView.tsx b/src/renderer/components/bots/BotChatView.tsx index 2b84a8213a..86b1df40c2 100644 --- a/src/renderer/components/bots/BotChatView.tsx +++ b/src/renderer/components/bots/BotChatView.tsx @@ -41,6 +41,11 @@ import { BotReminderReplies } from './BotReminderReplies' import { BotQuestionReplies } from './BotQuestionReplies' import { onBotMessageRequest, takeBotMessage } from '../../lib/botMessageLink' import { BotSecretRequests } from './BotSecretRequests' +import { SecformCard } from '../secrets/SecformCard' +import { SecretShareChip, SecretSharesContext, useSecretShares } from '../secrets/SecretShareChip' +import { createSecretsClient } from '../../services/secretsClient' +import { SECFORM_OPEN_EVENT } from './runBotCommand' +import type { SecformField } from '../../../shared/secform' import { ComputerUseSetupCard } from '../ComputerUseSetupCard' import { BotCards, galleryPaths } from './BotCards' import { BotActivitySticker, BotPresenceLine } from './BotPresence' @@ -980,6 +985,19 @@ export function BotChatView({ bot }: { bot: BotSummary }) { // About, Resume and the rest of its setup: always for this computer's bots; for a bot of another computer only with // Full bot access there while that computer is reached (`botSetupBlock`). const canSetup = !botSetupBlock(bot) + // `/secform` in this chat: the open form's fields, and the chips of what was shared with the bot. + const [secform, setSecform] = useState(null) + const secretsClient = useMemo(() => createSecretsClient(window.mousse?.platformRequest), []) + const secretShares = useSecretShares(remote ? undefined : bot.homeThreadId, secretsClient) + useEffect(() => { + setSecform(null) + const open = (event: Event): void => { + const detail = (event as CustomEvent<{ botId: string; fields: SecformField[] }>).detail + if (detail?.botId === bot.id) setSecform(detail.fields) + } + window.addEventListener(SECFORM_OPEN_EVENT, open) + return () => window.removeEventListener(SECFORM_OPEN_EVENT, open) + }, [bot.id]) const transcript = useRef(null) useReclampOpenTools(transcript) const messages = chat?.messages ?? EMPTY @@ -1324,7 +1342,7 @@ export function BotChatView({ bot }: { bot: BotSummary }) { const [voiceState, setVoiceState] = useState(null) const faceState: BotFaceState = voiceFaceState(voiceState) ?? botFaceState(bot, happy) - return + return {/* The chat pane: the conversation, and an applet beside it. The side panel docks outside it. */}
{/* The bot's colour tints the quotes of its messages. */} @@ -1398,7 +1416,8 @@ export function BotChatView({ bot }: { bot: BotSummary }) { {row.text} {row.expiredReviews.map(message => )} - : row.cut ? : } + : row.cut ? + : row.secretShare ? : } const message = row.message const key = replyKeys.keys.get(message.id) ?? message.id // Another bot's message, in its run's fold: the line sits on the first row of the run that is drawn, the @@ -1436,6 +1455,21 @@ export function BotChatView({ bot }: { bot: BotSummary }) { {unreachable && bot.lives &&

{bot.lives.name} is offline

} {/* A secret the bot asked for: typed into its private card, never into the chat. */} {!remote && } + {/* /secform: the values go once to this computer's secret store for the bot, never into the chat. */} + {!remote && secform && bot.homeThreadId && ( +
+ setSecform(null)} + onSave={async (save) => { + await secretsClient.share({ threadId: bot.homeThreadId!, fields: save.fields, expiry: save.expiry, singleUse: save.singleUse, audience: { kind: 'bot', botId: bot.id } }) + secretShares.refresh() + setSecform(null) + }} + /> +
+ )} {/* Computer use one of the bot's turns asked to set up: whatever is chosen applies from its next turn. */} {!remote && } {!remote && pasted.offer} @@ -1496,5 +1530,5 @@ export function BotChatView({ bot }: { bot: BotSummary }) { {/* A bot of another computer: its Agent settings alone; its browser and files folder stay on its computer. */} {memoryOpen && } - + } diff --git a/src/renderer/components/bots/botChatShape.ts b/src/renderer/components/bots/botChatShape.ts index 88225f563c..9181fd0068 100644 --- a/src/renderer/components/bots/botChatShape.ts +++ b/src/renderer/components/bots/botChatShape.ts @@ -50,7 +50,7 @@ export function workSignalsOf(message: BotChatMessage): { titles: string[]; queu */ export type BotChatRow = | { kind: 'message'; message: BotChatMessage } - | { kind: 'system'; id: string; at: string; text: string; title?: string; of?: string; note?: 'info' | 'error'; cut?: true; expiredReviews?: BotChatMessage[]; actionHistory?: BotChatMessage[] } + | { kind: 'system'; id: string; at: string; text: string; title?: string; of?: string; note?: 'info' | 'error'; cut?: true; expiredReviews?: BotChatMessage[]; actionHistory?: BotChatMessage[]; secretShare?: string } /** A row of this window only: a `/` command's line, or (`cut`) the words of a reply its turn stopped before finishing. */ export interface BotWindowLine { id: string; at: string; text: string; error?: true; cut?: true; expiredReviews?: BotChatMessage[]; actionHistory?: BotChatMessage[] } @@ -232,7 +232,7 @@ export function chatRows(messages: readonly BotChatMessage[], botName: string, a // The same quiet line twice in a row ("Older messages summarised" from two folds with nothing between) shows once. const previous = rows.at(-1) if (previous?.kind === 'system' && previous.text === message.text && previous.title === message.systemTitle && message.systemTitle) continue - rows.push({ kind: 'system', id: message.id, at: message.at, text: message.text, of: message.id, ...(message.systemTitle ? { title: message.systemTitle } : {}) }) + rows.push({ kind: 'system', id: message.id, at: message.at, text: message.text, of: message.id, ...(message.systemTitle ? { title: message.systemTitle } : {}), ...(message.secretShare ? { secretShare: message.secretShare.shareId } : {}) }) continue } const signals = workSignalsOf(message) diff --git a/src/renderer/components/bots/botCommands.ts b/src/renderer/components/bots/botCommands.ts index 8c3a526837..92d2d185e0 100644 --- a/src/renderer/components/bots/botCommands.ts +++ b/src/renderer/components/bots/botCommands.ts @@ -1,5 +1,7 @@ import { BOT_CUSTOM_SLOT_NAME, MAX_BOT_CUSTOM_SLOT_DESCRIPTION, type BotModelPick } from '../../../shared/bots/personal/definition' import type { LlmProviderOption } from '../../../shared/settings' +import { parseSecform, type SecformField } from '../../../shared/secform' +import { secformSuggestion } from '../../../shared/composerCommands' /** * The owner's `/` commands in a bot's chat. Mousse runs them itself: they never reach the bot, so they cost no tokens. @@ -13,6 +15,8 @@ export const BOT_BASE_SLOTS: readonly BotBaseSlot[] = ['talk', 'work', 'light', export type BotCommand = | { kind: 'clear' | 'stop' | 'status' | 'pause' | 'resume' | 'memory' | 'reset' | 'model-list' } + /** `/secform`: the form of secrets for the bot, with the fields read from what was typed. */ + | { kind: 'secform'; fields: SecformField[] } | { kind: 'forget'; history: boolean } /** `slot`: lower case; a base slot or a custom one. `description`: everything after the model, for a custom slot. */ | { kind: 'model-set'; slot: string; model: string; description?: string } @@ -33,7 +37,8 @@ const COMMANDS: readonly CommandRow[] = [ { usage: '/forget', action: 'Wipe saved memory', fill: '/forget', complete: true, setup: true }, { usage: '/forget history', action: 'Wipe chat and run notes, keep memory', fill: '/forget history', complete: true, setup: true }, { usage: '/reset', action: 'Start fresh: chat, memory, schedules', fill: '/reset', complete: true, setup: true }, - { usage: '/model', action: 'List models, or set one', fill: '/model ', complete: true, setup: true } + { usage: '/model', action: 'List models, or set one', fill: '/model ', complete: true, setup: true }, + { usage: '/secform [n]', action: 'Share secrets securely', fill: '/secform', complete: true } ] /** @@ -42,7 +47,7 @@ const COMMANDS: readonly CommandRow[] = [ * entry there still needs Full); a wrong command is answered here. */ export function isSetupCommand(command: BotCommand): boolean { - return command.kind !== 'stop' && command.kind !== 'status' && command.kind !== 'memory' && command.kind !== 'invalid' + return command.kind !== 'stop' && command.kind !== 'status' && command.kind !== 'memory' && command.kind !== 'secform' && command.kind !== 'invalid' } const NO_ARGS = new Set(['clear', 'stop', 'status', 'pause', 'resume', 'memory', 'reset']) @@ -59,7 +64,7 @@ export function baseSlotOf(word: string): BotBaseSlot | undefined { /** * What a message asks for, or null when it is an ordinary message for the bot: it does not start with a command's - * word. A `/word` that is no command (`/secform`, a path) goes to the bot as typed; a command written the wrong way + * word. A `/word` that is no command (a path) goes to the bot as typed; a command written the wrong way * is `invalid` and never sent. */ export function parseBotCommand(text: string): BotCommand | null { @@ -74,6 +79,7 @@ export function parseBotCommand(text: string): BotCommand | null { return rest.toLowerCase() === 'history' ? { kind: 'forget', history: true } : { kind: 'invalid', text: 'Use /forget or /forget history.' } } if (name === 'model') return parseModel(rest) + if (name === 'secform') return { kind: 'secform', fields: parseSecform(trimmed)?.fields ?? [] } return null } @@ -153,6 +159,9 @@ export const MAX_MODEL_SUGGESTIONS = 40 export function botCommandSuggestions(input: string, context: BotCommandContext = {}): BotCommandSuggestion[] { if (!input.startsWith('/') || input.includes('\n')) return [] const typed = input.toLowerCase().replace(/\s+/g, ' ') + // `/secform` keeps its row while its fields are typed after it, saying what the form opens with. + const secform = secformSuggestion(input) + if (secform) return [{ key: '/secform', label: '/secform [n]', description: secform.description, fill: input, complete: true }] const blocked = context.setupBlocked if (blocked && typed.startsWith('/model ')) return [] if (blocked) diff --git a/src/renderer/components/bots/runBotCommand.ts b/src/renderer/components/bots/runBotCommand.ts index e8ba415842..bb3f835f5a 100644 --- a/src/renderer/components/bots/runBotCommand.ts +++ b/src/renderer/components/bots/runBotCommand.ts @@ -7,6 +7,9 @@ import { noteBotStopAsked } from '../../stores/botLiveReplies' import { errorText } from '../../services/personalBotsClient' import { baseSlotOf, isSetupCommand, parseBotCommand, resolveModelWord, type BotCommand } from './botCommands' import { botSetupBlock } from './botSetup' + +/** Opens `/secform`'s form in a bot's chat: `detail` is `{ botId, fields }`. */ +export const SECFORM_OPEN_EVENT = 'mousse:bot-secform' import type { VoiceSendOptions } from '../../voice/voiceTarget' /** @@ -46,6 +49,11 @@ export async function runBotCommand(botId: string, command: BotCommand): Promise try { switch (command.kind) { case 'invalid': return fail(botId, command.text) + case 'secform': { + if (bot?.lives) return fail(botId, `Share secrets with this bot in its chat on ${bot.lives.name} for now.`) + window.dispatchEvent(new CustomEvent(SECFORM_OPEN_EVENT, { detail: { botId, fields: command.fields } })) + return + } case 'memory': return store().openMemory(botId) case 'forget': return confirm(botId, command.history ? 'forget-history' : 'forget') case 'reset': return confirm(botId, 'reset') diff --git a/src/renderer/components/secrets/SecformCard.tsx b/src/renderer/components/secrets/SecformCard.tsx new file mode 100644 index 0000000000..76eb20ebb0 --- /dev/null +++ b/src/renderer/components/secrets/SecformCard.tsx @@ -0,0 +1,256 @@ +import { useEffect, useId, useRef, useState } from 'react' +import { Eye, EyeOff, Laptop, Lock, Plus, X } from '../../lib/icons' +import { keyNameOf, isKeyName } from '../../../shared/automationKeys' +import { secretValueProblem } from '../../../shared/secretRequests' +import { + DEFAULT_SECFORM_EXPIRY, + SECFORM_EXPIRIES, + SECFORM_MAX_FIELDS, + secformExpiryLabel, + type SecformExpiry, + type SecformField, + type SecformValue +} from '../../../shared/secform' +import { Select } from '../ui/Select' +import { Switch } from '../settings/SettingsRow' +import { errorMessage } from '../../lib/errorText' + +/** Who may use the secrets, as the form offers it: `thread`, or `bot:`. */ +export interface SecformAudienceOption { + value: string + label: string +} + +export interface SecformSave { + fields: SecformValue[] + expiry: SecformExpiry + singleUse: boolean + /** The chosen audience option's value. */ + audience: string +} + +export interface SecformCardProps { + /** The fields `/secform` opened with (`parseSecform`). */ + fields: SecformField[] + audiences: readonly SecformAudienceOption[] + /** The computer that keeps the secrets, when it is not this one. */ + storedOn?: string + /** Save securely. Rejects with a message to show; the typed values are cleared once it resolves. */ + onSave(save: SecformSave): Promise + onCancel(): void +} + +interface Row extends SecformField { + key: number + value: string + shown: boolean +} + +/** A name as typed, made a key name (`openrouter key` → `OPENROUTER_KEY`); empty while there is none. */ +function cleanName(typed: string): string { + const trimmed = typed.trim() + if (!trimmed) return '' + const keyed: boolean = isKeyName(trimmed) + return keyed ? trimmed : keyNameOf(trimmed.replace(/[^A-Za-z0-9 _.-]+/g, ' ')) ?? trimmed.toUpperCase() +} + +/** What a field's value box says while empty: a plain field names what to type, a masked one asks for the secret. */ +function valuePlaceholder(row: Pick): string { + return row.masked ? 'Paste or type the secret' : `Type the ${row.label ? row.label.toLowerCase() : 'value'}` +} + +/** + * The form `/secform` opens (asks i121, i125): named secret fields, when they expire, who may use them and whether + * each is used once. Values live only in this card's state (gone when it closes) and are sent once, to the computer that keeps them; they + * never go into the composer, the chat or a model. + */ +export function SecformCard({ fields, audiences, storedOn, onSave, onCancel }: SecformCardProps) { + const nextKey = useRef(0) + const makeRow = (field: SecformField): Row => ({ ...field, key: nextKey.current++, value: '', shown: false }) + const [rows, setRows] = useState(() => (fields.length ? fields : [{ label: '', name: '', masked: true }]).map(makeRow)) + const [expiry, setExpiry] = useState(DEFAULT_SECFORM_EXPIRY) + const [audience, setAudience] = useState(audiences[0]?.value ?? 'thread') + const [singleUse, setSingleUse] = useState(false) + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const firstEmpty = useRef(null) + const ids = useId() + const titleId = `${ids}-title` + + // The first box to fill takes the focus when the form opens. + useEffect(() => { + firstEmpty.current?.focus({ preventScroll: true }) + }, []) + + const update = (key: number, change: Partial): void => setRows((current) => current.map((row) => (row.key === key ? { ...row, ...change } : row))) + const remove = (key: number): void => setRows((current) => (current.length > 1 ? current.filter((row) => row.key !== key) : current)) + const add = (): void => setRows((current) => (current.length >= SECFORM_MAX_FIELDS ? current : [...current, makeRow({ label: '', name: '', masked: true })])) + + const complete = rows.length > 0 && rows.every((row) => cleanName(row.name) && row.value) + + const save = async (): Promise => { + const names = rows.map((row) => cleanName(row.name)) + const bad = names.findIndex((name) => !isKeyName(name)) + if (bad >= 0) return setError('Name each secret with a word like GITHUB_TOKEN.') + const twice = names.find((name, index) => names.indexOf(name) !== index) + if (twice) return setError(`${twice} is named twice.`) + for (const [index, row] of rows.entries()) { + const problem = secretValueProblem(row.value) + if (problem) return setError(rows.length > 1 ? `${names[index]}: ${problem}` : problem) + } + setBusy(true) + setError(null) + try { + await onSave({ + fields: rows.map((row, index) => ({ name: names[index]!, ...(row.label ? { label: row.label } : {}), value: row.value })), + expiry, + singleUse, + audience + }) + setRows((current) => current.map((row) => ({ ...row, value: '' }))) + } catch (failure) { + setError(errorMessage(failure) || 'That did not work. Try again.') + } finally { + setBusy(false) + } + } + + const named = rows.some((row) => row.label) + let focusTaken = false + return ( +
+
+

+

+
+
{ + event.preventDefault() + if (complete && !busy) void save() + }} + > + {rows.map((row) => { + const takeFocus = !focusTaken && (!row.name || !row.value) + if (takeFocus) focusTaken = true + const nameId = `${ids}-name-${row.key}` + return ( +
+ {named && row.label && } +
+ update(row.key, { name: event.target.value })} + onBlur={() => update(row.key, { name: cleanName(row.name) })} + aria-label="Name" + placeholder="NAME" + autoComplete="off" + autoCorrect="off" + autoCapitalize="characters" + spellCheck={false} + disabled={busy} + /> +
+ update(row.key, { value: event.target.value })} + aria-label={row.label || cleanName(row.name) || 'Secret'} + placeholder={valuePlaceholder(row)} + autoComplete="off" + autoCorrect="off" + autoCapitalize="off" + spellCheck={false} + data-private="true" + disabled={busy} + /> + {row.masked && ( + + )} +
+ {rows.length > 1 && ( + + )} +
+
+ ) + })} + {rows.length < SECFORM_MAX_FIELDS && ( + + )} +
+ + Expires + + variant="menu" + size="small" + ariaLabelledBy={`${ids}-expires`} + value={expiry} + onChange={setExpiry} + options={SECFORM_EXPIRIES.map((value) => ({ value, label: secformExpiryLabel(value) }))} + disabled={busy} + /> + + {audiences.length > 0 && ( + + Who can use it +