Skip to content

Commit 2af04a6

Browse files
authored
Merge pull request #111 from ThinkOffApp/feat/choice-intents-clean
Choice intents: confirmations can offer N options; request_choice MCP tool
2 parents c6afc27 + 4c1a784 commit 2af04a6

3 files changed

Lines changed: 278 additions & 20 deletions

File tree

‎src/confirmations.mjs‎

Lines changed: 99 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ export function getIntent(id) {
180180
id,
181181
prompt: i.prompt,
182182
session: i.session,
183+
options: i.options || null,
183184
channels: i.channels,
184185
status: i.status,
185186
createdAt: i.createdAt,
@@ -191,12 +192,30 @@ export function getIntent(id) {
191192
// Decide an intent. Returns true if decided, false if id unknown or already
192193
// decided. Idempotent for same decision; rejects different decision after
193194
// settle.
194-
export function decideIntent(id, decision, { receiptsPath } = {}) {
195-
if (decision !== 'approve' && decision !== 'deny') {
196-
return { ok: false, error: 'decision must be "approve" or "deny"' };
197-
}
195+
export function decideIntent(id, rawDecision, { receiptsPath } = {}) {
196+
// Look the intent up BEFORE validating, because what counts as a legal
197+
// answer depends on the intent: a choice intent's legal answers are its own
198+
// declared options, and nothing else. Validating first against a fixed
199+
// approve/deny vocabulary is what made multi-option intents impossible.
198200
const i = intents.get(id);
199201
if (!i) return { ok: false, error: `unknown intent ${id}` };
202+
const options = Array.isArray(i.options) && i.options.length ? i.options : null;
203+
let decision = rawDecision;
204+
if (options) {
205+
// An option list is an allow-list, not a hint. `/choose <id> <anything>`
206+
// must never smuggle a value the requester did not offer, so match against
207+
// the declared options and store the DECLARED spelling - the requester
208+
// compares against the list it supplied, not against the phone's casing.
209+
const hit = options.find(
210+
(o) => String(o).toLowerCase() === String(rawDecision).trim().toLowerCase(),
211+
);
212+
if (!hit) {
213+
return { ok: false, error: `"${rawDecision}" is not an option for ${id}` };
214+
}
215+
decision = hit;
216+
} else if (decision !== 'approve' && decision !== 'deny') {
217+
return { ok: false, error: 'decision must be "approve" or "deny"' };
218+
}
200219
if (i.status !== 'pending') {
201220
if (i.decision === decision) return { ok: true, idempotent: true };
202221
return { ok: false, error: `intent ${id} already decided as ${i.decision}` };
@@ -213,7 +232,13 @@ export function decideIntent(id, decision, { receiptsPath } = {}) {
213232
try { r({ decision, id }); } catch {}
214233
}
215234
i.resolvers = [];
216-
const action = [...actions.values()].find((a) => a.intentId === id);
235+
// A choice answers a QUESTION; it does not authorise a typed executor. The
236+
// branch below treats everything that is not 'deny' as an approval and runs
237+
// the bound action, so letting a choice reach it would make picking an
238+
// option execute whatever action happened to be attached. The requester
239+
// acts on the resolved value instead - it is the one that knows what the
240+
// options meant.
241+
const action = options ? null : [...actions.values()].find((a) => a.intentId === id);
217242
if (action) {
218243
if (decision === 'deny') {
219244
settleAction(action, {
@@ -252,7 +277,10 @@ export function decideIntent(id, decision, { receiptsPath } = {}) {
252277
// Pure confirmation (no typed executor): the decision itself is terminal,
253278
// so mirror it directly. Typed actions instead mirror via runApprovedAction
254279
// (processing) and settleAction (completed/failed/denied/expired).
255-
pushStatus(id, decision === 'approve' ? 'approved' : 'denied', {
280+
// A settled choice is an affirmative outcome: the owner answered. The
281+
// status store enforces a monotonic rank, so a choice reports 'approved'
282+
// rather than inventing a state that could move a row backwards.
283+
pushStatus(id, (options || decision === 'approve') ? 'approved' : 'denied', {
256284
decision,
257285
approver: 'petrus',
258286
decided_at: new Date(i.decidedAt).toISOString(),
@@ -267,6 +295,9 @@ export function decideIntent(id, decision, { receiptsPath } = {}) {
267295
export async function createIntent({
268296
prompt,
269297
session,
298+
options, // optional string[]: turns this into a CHOICE intent whose legal
299+
// answers are exactly these labels, rendered as one button each
300+
// instead of Approve/Deny.
270301
channels = ['groupmind'],
271302
timeoutSec = 600,
272303
announce = async () => {},
@@ -275,9 +306,27 @@ export async function createIntent({
275306
// chat-author attribution; passed through to announcers.
276307
}) {
277308
const id = randomUUID().slice(0, 8);
309+
// ROUTE-DEPENDENT CAP, verified on GroupMind origin/main 159b16b. This
310+
// announcer posts to the GENERIC /api/v1/messages route, which carries
311+
// `actions` inside caller metadata and does NOT cap it. The per-room route
312+
// is different: it reads a TOP-LEVEL `actions` and silently does
313+
// `.slice(0, 6)`, so anything announcing a choice through that route loses
314+
// option 7 onwards with no error - a picker that renders fewer buttons than
315+
// it accepts answers. No cap is imposed here because it would be wrong for
316+
// the route actually in use; if you move the announcer to the room route,
317+
// cap it there and keep declared options equal to rendered ones.
318+
const cleanOptions = Array.isArray(options)
319+
// One line each, no blanks, no duplicates: a label is posted verbatim as
320+
// `/choose <id> <label>`, so a newline would split the command.
321+
? [...new Set(options.map((o) => String(o).replace(/[\r\n]+/g, ' ').trim()).filter(Boolean))]
322+
: null;
323+
if (cleanOptions && cleanOptions.length < 2) {
324+
throw new Error('a choice intent needs at least two distinct options');
325+
}
278326
const intent = {
279327
prompt,
280328
session,
329+
options: cleanOptions,
281330
channels,
282331
status: 'pending',
283332
createdAt: Date.now(),
@@ -289,12 +338,12 @@ export async function createIntent({
289338
intents.set(id, intent);
290339
persistIntent(id, intent);
291340
postReceipt(receiptsPath, {
292-
kind: 'intent.created', id, prompt, session, channels, createdAt: intent.createdAt,
341+
kind: 'intent.created', id, prompt, session, options: cleanOptions, channels, createdAt: intent.createdAt,
293342
});
294343
pushStatus(id, 'pending', { target_summary: prompt });
295344
// Side effects — never let an announce failure block the intent itself.
296345
try {
297-
await announce({ id, prompt, session, channels, fromHandle });
346+
await announce({ id, prompt, session, channels, fromHandle, options: cleanOptions });
298347
} catch (e) {
299348
postReceipt(receiptsPath, {
300349
kind: 'intent.announce_failed', id, error: e.message,
@@ -766,9 +815,19 @@ export function startConfirmationsServer({
766815
res.end(JSON.stringify({ ok: false, error: 'missing prompt' }));
767816
return;
768817
}
818+
// A malformed option list is the CALLER's error, so answer 400 rather
819+
// than letting createIntent throw into the 500 branch below - a 500
820+
// reads as "the daemon is broken" and sends someone looking in the
821+
// wrong place for a typo in their own request.
822+
if (payload.options !== undefined && !Array.isArray(payload.options)) {
823+
res.writeHead(400, { 'Content-Type': 'application/json' });
824+
res.end(JSON.stringify({ ok: false, error: 'options must be an array' }));
825+
return;
826+
}
769827
try {
770828
const id = await createIntent({
771829
prompt: payload.prompt,
830+
options: payload.options,
772831
session: payload.session || 'external',
773832
channels: Array.isArray(payload.channels) ? payload.channels : (announce ? ['groupmind'] : []),
774833
announce: announce || (async () => {}),
@@ -781,8 +840,12 @@ export function startConfirmationsServer({
781840
res.writeHead(201, { 'Content-Type': 'application/json' });
782841
res.end(JSON.stringify({ ok: true, id }));
783842
} catch (e) {
784-
res.writeHead(500, { 'Content-Type': 'application/json' });
785-
res.end(JSON.stringify({ ok: false, error: e.message || String(e) }));
843+
// createIntent rejects an option list that cannot be a choice
844+
// (fewer than two distinct labels). That is the caller's input, not
845+
// a daemon fault.
846+
const msg = e.message || String(e);
847+
res.writeHead(/at least two/.test(msg) ? 400 : 500, { 'Content-Type': 'application/json' });
848+
res.end(JSON.stringify({ ok: false, error: msg }));
786849
}
787850
});
788851
return;
@@ -1118,23 +1181,31 @@ export function makeGroupmindAnnouncer({ apiKey, room, callbackBase, apiKeys })
11181181
// the matching key from this map so the chat post is authored by the
11191182
// ORIGINATING agent rather than always by the daemon owner.
11201183
// Falls back to the default `apiKey` when no match is found.
1121-
return async ({ id, prompt, session, fromHandle }) => {
1184+
return async ({ id, prompt, session, fromHandle, options }) => {
11221185
if (!apiKey || !room) return;
11231186
// Per-agent key override.
11241187
const effectiveKey = (fromHandle && apiKeys && apiKeys[fromHandle]) || apiKey;
11251188
const uiLink = callbackBase ? `${callbackBase}/` : null;
1189+
const opts = Array.isArray(options) && options.length ? options : null;
1190+
// ALWAYS spell out the typed equivalent. The buttons need a client that
1191+
// renders them, and a phone that cannot (or an older build) must still be
1192+
// able to answer - otherwise a choice intent is unanswerable on exactly
1193+
// the surface it was built for.
1194+
const typed = opts
1195+
? opts.map((o) => `\`/choose ${id} ${o}\``).join(' · ')
1196+
: `\`/approve ${id}\` · \`/deny ${id}\``;
11261197
const body =
1127-
`[Confirmation needed] **${prompt}**\n` +
1198+
`[${opts ? 'Choice needed' : 'Confirmation needed'}] **${prompt}**\n` +
11281199
`Target session: \`${session || '(none)'}\`\n` +
11291200
(uiLink ? `Tap to decide: ${uiLink}\n` : '') +
1130-
`Or reply: \`/approve ${id}\` · \`/deny ${id}\``;
1201+
`Or reply: ${typed}`;
11311202
// Attach metadata so the GroupMind chat UI can render inline Approve/Deny
11321203
// buttons. Frontend reads `metadata.actions` + `metadata.intent_id` and
11331204
// POSTs `/approve <id>` (or `/deny <id>`) chat replies on tap, which the
11341205
// chat-reply poller in iak-mcp-daemon catches and routes to the local
11351206
// /intent/:id/decision endpoint. No new backend route needed.
11361207
const metadata = {
1137-
actions: ['Approve', 'Deny'],
1208+
actions: opts || ['Approve', 'Deny'],
11381209
intent_id: id,
11391210
intent_prompt: prompt,
11401211
intent_session: session || null,
@@ -1284,7 +1355,11 @@ export function startChatReplyPoller({ apiKey, room, intervalMs = 5000, log, own
12841355
seen.add(m.id);
12851356
if (!primed) continue; // ignore historical messages on first pass
12861357
const text = (m.body || '').trim();
1287-
const match = text.match(/^\/(approve|deny)\s+([a-f0-9]+)$/i);
1358+
// `/choose <id> <value>` carries a value, so its tail is greedy where
1359+
// approve/deny are anchored. Keep them one regex so a message can
1360+
// never match both readings.
1361+
const match = text.match(/^\/(approve|deny)\s+([a-f0-9]+)$/i)
1362+
|| text.match(/^\/(choose)\s+([a-f0-9]+)\s+(.+)$/i);
12881363
if (!match) continue;
12891364
// Only the human owner may settle intents. Fleet agents share the room
12901365
// and one (hermes) auto-replied "/approve <id>" to a confirmation card,
@@ -1331,7 +1406,9 @@ export function startChatReplyPoller({ apiKey, room, intervalMs = 5000, log, own
13311406
}
13321407
continue;
13331408
}
1334-
const decision = match[1].toLowerCase();
1409+
const verb = match[1].toLowerCase();
1410+
// For /choose the answer is the tail, not the verb.
1411+
const decision = verb === 'choose' ? match[3].trim() : verb;
13351412
const id = match[2];
13361413
const intent = getIntent(id);
13371414
if (!intent) {
@@ -1353,11 +1430,15 @@ export function startChatReplyPoller({ apiKey, room, intervalMs = 5000, log, own
13531430
// error: nothing happens, and the pending list still shows the
13541431
// truth. Restore a reply here only once a poller can tell "expired"
13551432
// apart from "belongs to another poller".
1356-
emit(`/${decision} ${id} from ${m.from}: unknown intent here, staying silent (another poller may own it)`);
1433+
emit(`/${verb} ${id} from ${m.from}: unknown intent here, staying silent (another poller may own it)`);
13571434
continue;
13581435
}
13591436
const r = decideIntent(id, decision);
1360-
emit(`/${decision} ${id} from ${m.from}: ${r.ok ? 'settled' : r.error}`);
1437+
// Keep the approve/deny line byte-identical - it is asserted by the
1438+
// suite and read by anyone grepping poller logs. Only /choose adds
1439+
// its value, because for a choice the verb alone says nothing.
1440+
const label = verb === 'choose' ? `/${verb} ${id} ${decision}` : `/${verb} ${id}`;
1441+
emit(`${label} from ${m.from}: ${r.ok ? 'settled' : r.error}`);
13611442
}
13621443
primed = true;
13631444
} catch (e) {

‎src/mcp-server.mjs‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,36 @@ export async function runMcpServer({ configPath } = {}) {
649649
required: ['prompt'],
650650
},
651651
},
652+
{
653+
name: 'request_choice',
654+
description:
655+
'Ask the user to PICK ONE of several options. Same lifecycle as request_confirmation ' +
656+
'(posts to the configured channels and BLOCKS until the user answers or the timeout ' +
657+
'expires) but renders one button per option instead of Approve/Deny, and returns ' +
658+
'{decision: "<the chosen option>"}. The option list is an allow-list: the user cannot ' +
659+
'answer with anything else. Use it for a model picker, a branch picker, any "which one?" ' +
660+
'question. Needs at least two distinct options; for a yes/no use request_confirmation.',
661+
inputSchema: {
662+
type: 'object',
663+
properties: {
664+
prompt: { type: 'string', description: 'The question. Keep it short — it fits in a watch notification.' },
665+
options: {
666+
type: 'array',
667+
items: { type: 'string' },
668+
description: 'The choices, one button each. At least two, each on one line. The label IS the answer, so label them with the value you want back.',
669+
},
670+
session: { type: 'string', description: 'tmux session that triggered the request, for context. Optional.' },
671+
channels: {
672+
type: 'array',
673+
items: { type: 'string', enum: ['groupmind', 'codewatch'] },
674+
description: 'Which channels to post to. Default: all configured channels.',
675+
},
676+
timeoutSec: { type: 'number', description: 'How long to wait before returning timeout. Default 600 (10 min).', default: 600 },
677+
fromHandle: { type: 'string', description: 'Originating agent handle for attribution, e.g. @CodexMB.' },
678+
},
679+
required: ['prompt', 'options'],
680+
},
681+
},
652682
{
653683
name: 'list_intents',
654684
description: 'List every confirmation intent the server knows about (pending, decided, recent).',
@@ -905,9 +935,19 @@ export async function runMcpServer({ configPath } = {}) {
905935
});
906936
return ok(JSON.stringify(posted, null, 2));
907937
}
938+
case 'request_choice':
908939
case 'request_confirmation': {
909-
if (!confirmEnabled && !daemonAvailable) return err('request_confirmation: confirmations not configured. Set mcp.confirmations.room (+ poller.api_key) and/or codewatch_gate_url.');
910-
if (!args.prompt) return err('request_confirmation: prompt is required');
940+
if (!confirmEnabled && !daemonAvailable) return err(`${name}: confirmations not configured. Set mcp.confirmations.room (+ poller.api_key) and/or codewatch_gate_url.`);
941+
if (!args.prompt) return err(`${name}: prompt is required`);
942+
// Validate HERE rather than letting the daemon or createIntent throw:
943+
// the caller is an agent composing a picker, and "needs at least two
944+
// distinct options" is only useful if it names which call was wrong.
945+
let options;
946+
if (name === 'request_choice') {
947+
if (!Array.isArray(args.options)) return err('request_choice: options must be an array of strings');
948+
options = [...new Set(args.options.map((o) => String(o).replace(/[\r\n]+/g, ' ').trim()).filter(Boolean))];
949+
if (options.length < 2) return err('request_choice: needs at least two distinct options; use request_confirmation for yes/no');
950+
}
911951
const timeoutSec = Math.max(1, Math.min(86400, args.timeoutSec || 600));
912952

913953
// Daemon mode: forward to the running iak-mcp-daemon so the intent
@@ -919,6 +959,7 @@ export async function runMcpServer({ configPath } = {}) {
919959
headers: { 'Content-Type': 'application/json', ...daemonAuthHeaders() },
920960
body: JSON.stringify({
921961
prompt: args.prompt,
962+
options,
922963
session: args.session,
923964
channels: Array.isArray(args.channels) ? args.channels : undefined,
924965
from_handle: confirmationFromHandle(args, config),
@@ -948,6 +989,7 @@ export async function runMcpServer({ configPath } = {}) {
948989
: Object.keys(announcerMap);
949990
const id = await createIntent({
950991
prompt: args.prompt,
992+
options,
951993
session: args.session,
952994
channels,
953995
timeoutSec,

0 commit comments

Comments
 (0)