An open-source, faster Devin alternative
TypeScript
Session roles: review fixes, one path each (work 112)
Igor Zalutski via Computer1ded1c5a417f
diff --git a/computer/README.md b/computer/README.mdindex e23ac4d9..945fa472 100644--- a/computer/README.md+++ b/computer/README.md@@ -213,13 +213,15 @@ the session once the value is set.| Scope | Gets it | Who can set it | Kept ||---|---|---|---|-| This session | this thread | anyone enabled | 30 days after the session was last active |+| This session | this thread | anyone who can drive it | 30 days after the session was last active || Just me (user) | every session the person owns | that person | until removed || Workspace | every session in the Slack workspace | admins | until removed |The narrowest scope wins on a name clash. `!secret` lists names (never values),`!secret rm NAME [session|me|workspace]` removes one, `!secret help` explains.-`!secret` is handled by the gateway and never reaches the session.+`!secret` is handled by the gateway and never reaches the session. In a+session's thread, `!secret`, `!var` and the secret form are for people who can+drive it (see below).**Where values live.** The gateway is the copy of record: AES-256-GCM, witheach row's scope, owner and name as associated data, so a row copied elsewhere@@ -279,7 +281,7 @@ in text and is never delivered:| `!access` | who drives now (`Change…` for the owner and admins) || `!access open` / `!access owner` | everyone in the thread / only the owner || `!access @a @b` | the owner and these people |-| `!access add @a` / `!access remove @a` | edit the list |+| `!access add @a` / `!access remove @a` | edit the list (not on an open session) || `!access default open` / `!access default owner` | what new sessions start with (admins) |The owner and admins (`"admin": true` in `SP_PEOPLE`) change it; only peoplediff --git a/computer/src/access.test.ts b/computer/src/access.test.tsindex dc35a519..d8cf5a7f 100644--- a/computer/src/access.test.ts+++ b/computer/src/access.test.ts@@ -180,11 +180,11 @@ describe('parseAccessCommand', () => {expect(accessCommandNeeds({ kind: 'remove', ids: ['U1'] })).toBe('grant');expect(accessCommandNeeds({ kind: 'default', value: 'owner' })).toBe('admin');});- it("edits the current list, '*' counting as empty", () => {- expect(editDrivers('*', { kind: 'add', ids: ['U1'] })).toEqual(['U1']);+ it("edits the current list, and refuses add and remove on an open session", () => {+ expect(editDrivers('*', { kind: 'add', ids: ['U1'] })).toBeUndefined();expect(editDrivers(['U2'], { kind: 'add', ids: ['U1'] })).toEqual(['U2', 'U1']);expect(editDrivers(['U1', 'U2'], { kind: 'remove', ids: ['U1'] })).toEqual(['U2']);- expect(editDrivers('*', { kind: 'remove', ids: ['U1'] })).toEqual([]);+ expect(editDrivers('*', { kind: 'remove', ids: ['U1'] })).toBeUndefined();expect(editDrivers(['U1'], { kind: 'set', drivers: '*' })).toBe('*');});});diff --git a/computer/src/access.ts b/computer/src/access.tsindex 3edb091a..ada86f1c 100644--- a/computer/src/access.ts+++ b/computer/src/access.ts@@ -204,11 +204,14 @@ export function accessCommandNeeds(c: AccessCommand): 'view' | 'grant' | 'admin'return c.kind === 'default' ? 'admin' : 'grant';}-/** The list a `set`, `add` or `remove` asks for, from the current one (`'*'` counts as empty for add and remove). Not normalized. */-export function editDrivers(current: Drivers, c: Extract<AccessCommand, { kind: 'set' | 'add' | 'remove' }>): Drivers {+/**+ * The list a `set`, `add` or `remove` asks for, from the current one. Not normalized. `undefined` when the session is+ * open and the edit is `add` or `remove`: there is no list to change, and making one would lock the thread by surprise.+ */+export function editDrivers(current: Drivers, c: Extract<AccessCommand, { kind: 'set' | 'add' | 'remove' }>): Drivers | undefined {if (c.kind === 'set') return c.drivers;- const list = current === '*' ? [] : current;- return c.kind === 'add' ? [...list, ...c.ids] : list.filter((id) => !c.ids.includes(id));+ if (current === '*') return undefined;+ return c.kind === 'add' ? [...current, ...c.ids] : current.filter((id) => !c.ids.includes(id));}/** The answer to any other form of `!access`. */diff --git a/computer/src/dev/gateway-check.ts b/computer/src/dev/gateway-check.tsindex af664ab8..d2b71db9 100644--- a/computer/src/dev/gateway-check.ts+++ b/computer/src/dev/gateway-check.ts@@ -213,7 +213,7 @@ check('ch → code channel session', cc?.session.key === 'C_CODE' && cc.session.await router.action(encodeActionId(`C1:${first.ts}`, 'pr7', 'allow'), owner.slackUserId, client, 'C1');const a = await host.next('action');check('action routed by session key', a?.sessionKey === `C1:${first.ts}` && a.promptId === 'pr7' && a.value === 'allow', a);-await router.stop({ channel: 'C1', thread_ts: first.ts }, 'Ev-stop');+await router.stop({ channel: 'C1', thread_ts: first.ts }, 'Ev-stop', client);const st = await host.next('stop');check('stop button → stop', st?.sessionKey === `C1:${first.ts}`, st);diff --git a/computer/src/dev/secrets-check.ts b/computer/src/dev/secrets-check.tsindex a8b2aa96..f9ce9b55 100644--- a/computer/src/dev/secrets-check.ts+++ b/computer/src/dev/secrets-check.ts@@ -279,7 +279,7 @@ const hub: Hub = new Hub({secretsFor: (spec) => (isSlackSpec(spec) ? vault.forSession(spec.key, spec.owner.slackUserId) : []),requestSecret: (from, req) => ui.request(from, req, client),});-const ui = createSecretsUi({ store, vault, hub });+const ui = createSecretsUi({ store, vault, hub, deliver: (spec, h, c) => router.deliver(spec, h, c) });const vars = createVariablesUi({ store, vault, hub });const router = createRouter({ store, hub, mode: 'bypassPermissions', models: () => ({}), secrets: ui, variables: vars });const server = createServer((_, res) => res.writeHead(404).end());@@ -468,6 +468,22 @@ check(called('chat.update')[0]?.args.ts === '500.1' && /GCP_SA/.test(told?.msg.text ?? '') && told?.secrets?.some((s) => s.name === 'GCP_SA' && s.file),{ update: called('chat.update'), told },);+check('request_secret: the session is told through the role gate, as the one who set it', told?.msg.role === 'owner', told?.msg);++// Session roles (work 112): in a session only its owner drives, ada cannot use `!secret` or submit its form.+store.access.writeDrivers(SK, []);+calls.length = 0;+await route({ thread_ts: '300.1', text: '!secret', user: ada.slackUserId });+const ok5 = ui.submit({ private_metadata: rview.private_metadata, state: { values: state('ADA_KEY', 'ada-value-456', 'session') } }, ada.slackUserId);+check(+ 'roles: a participant’s `!secret` and secret form are refused; nothing stored',+ /can drive this session can use `!secret`/.test(called('chat.postEphemeral')[0]?.args.text) &&+ 'errors' in ok5 &&+ /`!secret`/.test(ok5.errors.name) &&+ !vault.list([{ scope: 'session', owner: SK }]).some((s) => s.name === 'ADA_KEY'),+ { calls, ok5 },+);+store.access.writeDrivers(SK, '*');await checkVariables({ check, route, next, called, calls, button, vault, vars, owner, ada });diff --git a/computer/src/gateway/access-flow.test.ts b/computer/src/gateway/access-flow.test.tsindex da569dc0..2ab1a897 100644--- a/computer/src/gateway/access-flow.test.ts+++ b/computer/src/gateway/access-flow.test.ts@@ -10,6 +10,8 @@ import { encodeAccessId } from '../access-views.js';import type { Store } from './db.js';import type { Hub } from './hosts.js';import { type Ctx, createRouter, type Msg } from './routing.js';+import type { SecretsUi } from './secrets-ui.js';+import type { VariablesUi } from './variables-ui.js';import { BOT, fakeClient, fakeHub, fakeStore } from './test-fakes.js';const person = (id: string, admin = false) => ({ slackUserId: id, dir: id.toLowerCase(), gitName: id, gitEmail: `${id}@example.com`, ...(admin ? { admin } : {}) });@@ -21,6 +23,7 @@ let router: ReturnType<typeof createRouter>;let n = 0;let root: Msg;let key: string;+const deps = () => ({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'default' as const, models: () => ({ claude: { mode: 'profile' as const, profile: 'p', vars: {}, key: 'k' } }) });const msg = (over: Partial<Msg> = {}): Msg => ({ channel: 'C1', ts: `1.${++n}`, user: 'U1', text: `<@${BOT}> do it`, ...over });const ctx = (): Ctx => ({ client: client as unknown as WebClient, botUserId: BOT, teamId: 'T1', eventId: `ev-${++n}` });@@ -35,7 +38,7 @@ beforeEach(async () => {store = fakeStore(person('UBEA0002'), person('UCY00003'), person('UA', true));hub = fakeHub();client = fakeClient();- router = createRouter({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'default', models: () => ({ claude: { mode: 'profile', profile: 'p', vars: {}, key: 'k' } }) });+ router = createRouter(deps());root = msg();key = `C1:${root.ts}`;await router.route(root, ctx(), true);@@ -256,3 +259,97 @@ describe('new sessions', () => {expect(lock('reactions.add')).toEqual([{ channel: 'C1', timestamp: m.ts, name: 'lock' }]);});});++describe('one gate for everything that writes to a session', () => {+ it('a participant’s `!secret` and `!var` answer S8 and reach neither; a driver’s are handled, never delivered', async () => {+ const seen: string[] = [];+ const command = async (text: string) => (seen.push(text), true);+ router = createRouter({ ...deps(), secrets: { command } as unknown as SecretsUi, variables: { command } as unknown as VariablesUi });+ store.access.writeDrivers(key, ['UBEA0002']);+ await say('UCY00003', '!secret API_KEY');+ await say('UCY00003', '!var REGION=eu');+ await say('UBEA0002', '!secret API_KEY');+ expect(ephemerals('UCY00003')).toEqual([+ 'Only people who can drive this session can use `!secret`.',+ 'Only people who can drive this session can use `!var`.',+ ]);+ expect(seen).toEqual(['!secret API_KEY']);+ expect(hub.delivered).toHaveLength(0);+ expect(store.access.held(key)).toHaveLength(0);+ });++ it('an owner no longer in the people table can do nothing in their session', async () => {+ store.db.prepare('DELETE FROM people WHERE slack_user_id = ?').run('U1');+ await say('U1', 'go on');+ await say('U1', `<@${BOT}> go on`, true);+ await router.action(encodeActionId(key, 'p1', 'allow'), 'U1', wc(), 'C1');+ await router.stop({ channel: 'C1', thread_ts: root.ts, user: 'U1' }, 'ev-gone', wc());+ await router.access.click(encodeAccessId(key, 'open'), { user: { id: 'U1' }, trigger_id: 't', container: { channel_id: 'C1', thread_ts: root.ts } }, wc());+ expect([hub.delivered, hub.actions, hub.stops, client.of('views.open')].map((c) => c.length)).toEqual([0, 0, 0, 0]);+ expect(ephemerals('U1')).toEqual([expect.stringMatching(/not enabled/), expect.stringMatching(/not enabled/)]);+ });+});++describe('setDrivers refuses', () => {+ const access = (user: string, text: string) => say(user, `!access ${text}`);++ it('more than MAX_DRIVERS people, before asking who they are', async () => {+ await access('U1', Array.from({ length: 51 }, (_, i) => `<@UX${String(i).padStart(6, '0')}>`).join(' '));+ expect(ephemerals('U1')).toEqual(['At most 50 people can be named.']);+ expect(store.access.drivers(key)).toBe('*');+ });++ it('add or remove on an open session: the usage, and nothing changes', async () => {+ await access('U1', 'add <@UBEA0002>');+ expect(ephemerals('U1')[0]).toMatch(/^`!access`/);+ expect(store.access.drivers(key)).toBe('*');+ expect(posts()).toHaveLength(0);+ });++ it('Allow for a requester who is no longer a member: told to the clicker, the request stays open', async () => {+ store.access.writeDrivers(key, []);+ await say('UBEA0002', `<@${BOT}> fix the login`, true);+ store.db.prepare('DELETE FROM people WHERE slack_user_id = ?').run('UBEA0002');+ await router.access.click(encodeAccessId(key, 'allow', 'UBEA0002'), { user: { id: 'U1' }, channel: { id: 'C1' } }, wc());+ expect(ephemerals('U1')).toEqual(['<@UBEA0002> can’t be added: only full members of this workspace can drive.']);+ expect(store.access.drivers(key)).toEqual([]);+ expect(store.access.request(key, 'UBEA0002')?.state).toBe('open');+ expect(hub.delivered).toHaveLength(0);+ });+});++describe('the request row is the guard', () => {+ beforeEach(() => store.access.writeDrivers(key, []));++ it('two mentions at once post one request', async () => {+ await Promise.all([say('UBEA0002', `<@${BOT}> fix it`, true), say('UBEA0002', `<@${BOT}> please`, true)]);+ expect(posts()).toHaveLength(1);+ expect(store.access.held(key)).toHaveLength(2);+ });++ it('a request whose post failed is dropped, so the next mention asks again', async () => {+ const postMessage = client.chat.postMessage;+ client.chat.postMessage = async () => {+ throw new Error('slack down');+ };+ await say('UBEA0002', `<@${BOT}> fix it`, true);+ expect(store.access.request(key, 'UBEA0002')).toBeUndefined();+ expect(ephemerals('UBEA0002')).toHaveLength(0);+ client.chat.postMessage = postMessage;+ await say('UBEA0002', `<@${BOT}> please`, true);+ expect(posts()).toHaveLength(1);+ expect(store.access.request(key, 'UBEA0002')?.state).toBe('open');+ });+});++describe('context order', () => {+ it('a delivery that carried the newest 40 held messages deletes the older ones too', async () => {+ store.access.writeDrivers(key, []);+ for (let i = 0; i < 45; i++) await say('UBEA0002', `note ${i}`);+ expect(store.access.held(key)).toHaveLength(40);+ await say('U1', 'go');+ const context = hub.delivered[0].msg.linked!.at(-1)!;+ expect(context.ok && context.messages).toHaveLength(40);+ expect(store.db.prepare('SELECT COUNT(*) AS n FROM session_context').get()).toEqual({ n: 0 });+ });+});diff --git a/computer/src/gateway/access-flow.ts b/computer/src/gateway/access-flow.tsindex 7f1292a1..1d46ed5e 100644--- a/computer/src/gateway/access-flow.ts+++ b/computer/src/gateway/access-flow.ts@@ -2,7 +2,8 @@// does per role. A message in a session is delivered, refused or held as// context; a participant's mention asks the owner to let them drive; `Allow`// and `Not now` answer that; `setDrivers` is the one write of `drivers`; held-// context rides the next delivered message; a stop by someone else is named.+// context rides the next delivered message; a stop by someone else is named;+// a prompt's button is answered by whoever it may be.//// Who may do what is access.ts (`role`, `can`); the strings and Block Kit are// access.ts and access-views.ts; SQL is access-store.ts. This file holds the@@ -10,10 +11,14 @@// `forward`, given as `deliver`, as secrets-ui.ts is given the hub.//// Member and admin here: a row in the people table, and that row's `admin`.+// Only people in that table get this far (routing.ts and access-ui.ts turn+// anyone else away at each entry point), so the one acting is never an+// `outsider` here; a person named as a driver may still not be a member.import type { WebClient } from '@slack/web-api';import type { KnownBlock } from '@slack/types';import {+ ACCESS_USAGE,type Access,type AccessAction,type Actor,@@ -26,23 +31,28 @@ import {encodeDrivers,gained,grantedText,+ mention,normalize,notAskedText,+ notMemberText,onlyGrantorAnswersText,openedText,+ overLimit,ownerCommandText,ownerDecidesText,requestSentText,restricted,- type Role,role,sameDrivers,stoppedText,+ tooManyPeopleText,} from '../access.js';import { declinedPost, requestPost } from '../access-views.js';-import type { Delivery, SlackSessionSpec } from '../protocol.js';+import { type Delivery, NOT_ASKED, type SlackSessionSpec } from '../protocol.js';import type { Linked, LinkedMessage } from '../links.js';+import type { AccessRequest } from './access-store.js';import type { Store } from './db.js';+import type { Hub, Reply } from './hosts.js';import type { Msg } from './routing.js';import { errorText, log } from '../log.js';@@ -62,12 +72,26 @@ export interface HeldMessage {export interface AccessFlowDeps {store: Store;+ hub: Pick<Hub, 'stop' | 'action'>;/** Deliver as an ordinary message from `held.m.user` (routing.ts `forward`), with their role. */deliver(spec: SlackSessionSpec, held: HeldMessage, role: DeliveredRole, client: WebClient): Promise<void>;/** A person's name, for held context (links.ts's cached directory). */name(client: WebClient, id: string): Promise<string>;}+/**+ * What `setDrivers` did: the change is written (`after` settles once Slack has+ * been told), or why not: `usage` the edit does not apply to the current value+ * (add or remove on an open session), `limit` more than MAX_DRIVERS, `member`+ * a newly named id that is not a full member.+ */+export type DriversChange = { ok: true; after: Promise<void> } | { refused: 'usage' | 'limit' } | { refused: 'member'; id: string };++/** A refusal as words; `name`: how to show a `member` refusal's id (a mention, or a plain name in a modal). */+export function refusedText(r: Extract<DriversChange, { refused: string }>, name = r.refused === 'member' ? mention(r.id) : ''): string {+ return r.refused === 'usage' ? ACCESS_USAGE : r.refused === 'limit' ? tooManyPeopleText() : notMemberText(name);+}+/** Whoever acts, as this gateway knows them. */export function actor(store: Store, id: string): Actor {const p = store.person(id);@@ -83,7 +107,7 @@ export const changedBy = (spec: SlackSessionSpec, id: string): ChangedBy => ({ iconst inThread = (spec: SlackSessionSpec) => (spec.kind === 'thread' && spec.threadTs ? { thread_ts: spec.threadTs } : {});-export function createAccessFlow({ store, deliver, name }: AccessFlowDeps) {+export function createAccessFlow({ store, hub, deliver, name }: AccessFlowDeps) {// Held rows attached to a delivery the hub has not answered yet: the next message does not attach them again.const inFlight = new Set<number>();@@ -116,44 +140,43 @@ export function createAccessFlow({ store, deliver, name }: AccessFlowDeps) {}/**- * A message in an existing session ("Messages" steps 2 to 4). The role to- * deliver it with; `outsider` when it is dropped (routing.ts answers a- * mention); undefined when it was answered or held here.+ * A message in an existing session ("Messages" steps 2 to 4), from a person+ * in the people table: the role to deliver it with, or undefined when it was+ * refused or held here. Every command but `!access` passes here, gateway+ * commands (`!secret`, `!var`) too: they read as `instruct`.*/- async function message(spec: SlackSessionSpec, h: HeldMessage, client: WebClient): Promise<Role | undefined> {+ async function message(spec: SlackSessionSpec, h: HeldMessage, client: WebClient): Promise<DeliveredRole | undefined> {const a = accessOf(store, spec);const u = actor(store, h.m.user!);- const r = role(a, u);+ // Never `outsider`: the sender is in the people table (see the header).+ const r = role(a, u) as DeliveredRole;const needs = commandAction(h.text);if (needs !== undefined) {- // `!access` never gets here (routing.ts); commands never carry context.+ // Commands never carry context.if (can(a, u, needs as AccessAction)) return r;const word = commandWord(h.text) ?? '';- if (needs === 'settings') await ephemeral(client, spec, u.id, ownerCommandText(a.owner, word));- else if (needs === 'instruct') await ephemeral(client, spec, u.id, driversCommandText(word));+ await ephemeral(client, spec, u.id, needs === 'settings' ? ownerCommandText(a.owner, word) : driversCommandText(word));return undefined;}if (can(a, u, 'instruct')) return r;- if (r === 'outsider') return 'outsider';store.access.hold(spec.key, u.id, h.m.ts, h.text, (h.m.files ?? []).map((f) => f.name ?? f.id));// In a code channel every message is for the bot.- if (!(spec.kind === 'channel' || (h.mentioned && !h.inline))) return undefined;- if (store.access.request(spec.key, u.id)) return void (await ephemeral(client, spec, u.id, ownerDecidesText(a.owner)));- await requestToDrive(spec, a, h, client);+ if (spec.kind === 'channel' || (h.mentioned && !h.inline)) await requestToDrive(spec, a.owner, h, client);return undefined;}- /** "Request to drive": the visible request, its row, and S2 to the requester. */- async function requestToDrive(spec: SlackSessionSpec, a: Access, h: HeldMessage, client: WebClient) {+ /** "Request to drive": its row first (the guard against a second), then the visible request, then S2; S2b when there was one. */+ async function requestToDrive(spec: SlackSessionSpec, owner: string, h: HeldMessage, client: WebClient) {const requester = h.m.user!;- const p = requestPost(spec.key, a.owner, requester);+ if (!store.access.putRequest(spec.key, requester, JSON.stringify(h))) return ephemeral(client, spec, requester, ownerDecidesText(owner));+ const p = requestPost(spec.key, owner, requester);const posted = await post(client, spec, p.text, p.blocks);- if (!posted?.ts) return;- store.access.putRequest(spec.key, requester, posted.ts, JSON.stringify(h));- await ephemeral(client, spec, requester, requestSentText(a.owner));+ if (!posted?.ts) return store.access.dropRequest(spec.key, requester);+ store.access.requestPosted(spec.key, requester, posted.ts);+ await ephemeral(client, spec, requester, requestSentText(owner));}- /** `Allow` or `Not now` on a request, clicked by `clicker`. */+ /** `Allow` or `Not now` on a request, clicked by `clicker` (a person). */async function answer(key: string, verb: 'allow' | 'deny', requester: string, clicker: string, client: WebClient) {const spec = store.session(key)?.spec;if (!spec) return log.warn('access answer for unknown session', key);@@ -166,41 +189,58 @@ export function createAccessFlow({ store, deliver, name }: AccessFlowDeps) {const p = declinedPost(requester);return update(client, spec, q.messageTs, p.text, p.blocks);}- if (a.drivers !== '*') return setDrivers(spec, [...a.drivers, requester], changedBy(spec, clicker), client);+ const by = changedBy(spec, clicker);+ const r = setDrivers(spec, (d) => (d === '*' ? undefined : [...d, requester]), by, client);+ if (!('refused' in r)) return r.after;+ if (r.refused !== 'usage') return ephemeral(client, spec, clicker, refusedText(r));// Everyone already drives (it cannot normally happen): the request is answered, the held message stays context.store.access.closeRequest(key, requester);- await update(client, spec, q.messageTs, grantedText(changedBy(spec, clicker), [requester], a.owner), []);+ await update(client, spec, q.messageTs, grantedText(by, [requester], a.owner), []);}- /** "One transition": the only write of `drivers` after a session's first. */- async function setDrivers(spec: SlackSessionSpec, want: Drivers, by: ChangedBy, client: WebClient) {+ /**+ * "One transition": the only write of `drivers` after a session's first.+ * `edit` is applied to the value read here; reading, checking, writing and+ * closing the requests it answers happen with no await between them, so two+ * changes never interleave. Slack is told after, in `after`.+ */+ function setDrivers(spec: SlackSessionSpec, edit: (current: Drivers) => Drivers | undefined, by: ChangedBy, client: WebClient): DriversChange {const { owner, drivers: prev } = accessOf(store, spec);+ const want = edit(prev);+ if (want === undefined) return { refused: 'usage' };const next = normalize(owner, want);- if (sameDrivers(prev, next)) return;+ if (overLimit(next)) return { refused: 'limit' };+ const added = next === '*' ? [] : next.filter((id) => prev === '*' || !prev.includes(id));+ const stranger = added.find((id) => !actor(store, id).member);+ if (stranger) return { refused: 'member', id: stranger };+ if (sameDrivers(prev, next)) return { ok: true, after: Promise.resolve() };store.access.writeDrivers(spec.key, next);- if (restricted(prev) !== restricted(next)) await marker(spec, restricted(next), client);-const after: Access = { owner, drivers: next };- const handled: string[] = [];- const deliveries: Promise<void>[] = [];- for (const q of store.access.openRequests(spec.key)) {- if (role(after, actor(store, q.userId)) !== 'driver') continue;+ const granted = store.access.openRequests(spec.key).filter((q) => role(after, actor(store, q.userId)) === 'driver');+ for (const q of granted) {store.access.closeRequest(spec.key, q.userId);+ store.access.releaseTs(spec.key, (JSON.parse(q.held) as HeldMessage).m.ts);+ }+ log.info('access', spec.key, by.id, by.admin, encodeDrivers(prev), encodeDrivers(next));+ return { ok: true, after: tell(spec, prev, next, granted, by, client) };+ }++ /** What follows a change in Slack: the marker, the answered requests and their held messages, the announcement. */+ async function tell(spec: SlackSessionSpec, prev: Drivers, next: Drivers, granted: AccessRequest[], by: ChangedBy, client: WebClient) {+ const owner = spec.owner.slackUserId;+ if (restricted(prev) !== restricted(next)) await marker(spec, restricted(next), client);+ const deliveries: Promise<void>[] = [];+ for (const q of granted) {await update(client, spec, q.messageTs, grantedText(by, [q.userId], owner), []);- const held = JSON.parse(q.held) as HeldMessage;- store.access.releaseTs(spec.key, held.m.ts);- handled.push(q.userId);// Started in request order (forward keeps a session's order); not awaited before the announcement.- deliveries.push(deliver(spec, held, 'driver', client).catch((e) => log.warn(`deliver held ${spec.key}:`, errorText(e))));+ deliveries.push(deliver(spec, JSON.parse(q.held) as HeldMessage, 'driver', client).catch((e) => log.warn(`deliver held ${spec.key}:`, errorText(e))));}-const g = gained(prev, next);if (g === 'opened') await post(client, spec, openedText(by, owner));else {- const added = g.filter((id) => !handled.includes(id));+ const added = g.filter((id) => !granted.some((q) => q.userId === id));if (added.length) await post(client, spec, grantedText(by, added, owner));}- log.info('access', spec.key, by.id, by.admin, encodeDrivers(prev), encodeDrivers(next));await Promise.all(deliveries);}@@ -214,7 +254,8 @@ export function createAccessFlow({ store, deliver, name }: AccessFlowDeps) {/*** The session's held context as one `Linked`, for a message about to be* delivered; `settle` once the hub answers: accepted (delivered or queued)- * deletes the rows, anything else keeps them for the next message.+ * deletes every row up to the newest attached, those left out as skipped+ * too, so none arrives later out of order; anything else keeps them.*/async function context(spec: SlackSessionSpec, client: WebClient): Promise<{ linked?: Linked; settle(accepted: boolean): void }> {const rows = store.access.held(spec.key).filter((r) => !inFlight.has(r.seq));@@ -228,18 +269,30 @@ export function createAccessFlow({ store, deliver, name }: AccessFlowDeps) {linked: { url: '', ok: true, where: '', context: true, messages },settle(accepted) {for (const r of rows) inFlight.delete(r.seq);- if (accepted) store.access.release(rows.map((r) => r.seq));+ if (accepted) store.access.release(spec.key, rows[rows.length - 1].seq);},};}- /** A prompt button's clicker who may not answer it (S6), in the session's thread. */- const notAsked = (spec: SlackSessionSpec, user: string, client: WebClient) => ephemeral(client, spec, user, notAskedText(spec.owner.slackUserId));+ /** Slack's stop button, clicked by `user` (a person) or by nobody Slack names ("Stop"): stop, then S9 when it was not the owner. */+ async function stop(spec: SlackSessionSpec, user: string | undefined, client: WebClient) {+ const r = await hub.stop(spec.key);+ if (!r.ok) return log.warn(`stop ${spec.key}: ${r.error}`);+ if (user && user !== spec.owner.slackUserId) await post(client, spec, stoppedText(user));+ }- /** S9: someone other than the owner stopped the turn with the native button. */- const stopped = (spec: SlackSessionSpec, user: string, client: WebClient) => post(client, spec, stoppedText(user)).then(() => {});+ /** A prompt's button, clicked by `user` (a person): to the host with their role, or S6. The host's answer otherwise. */+ async function click(spec: SlackSessionSpec, promptId: string, value: string, user: string, client: WebClient): Promise<Reply | 'queued' | undefined> {+ const a = accessOf(store, spec);+ const u = actor(store, user);+ const notAsked = () => ephemeral(client, spec, user, notAskedText(a.owner));+ if (!can(a, u, 'answer')) return void (await notAsked());+ const r = await hub.action(spec.key, promptId, value, user, role(a, u) === 'owner' ? 'owner' : 'driver');+ if (r !== 'queued' && !r.ok && r.error === NOT_ASKED) return void (await notAsked());+ return r;+ }- return { message, answer, setDrivers, begin, context, notAsked, stopped };+ return { message, answer, setDrivers, begin, context, stop, click };}export type AccessFlow = ReturnType<typeof createAccessFlow>;diff --git a/computer/src/gateway/access-store.test.ts b/computer/src/gateway/access-store.test.tsindex deabdbdf..65b90082 100644--- a/computer/src/gateway/access-store.test.ts+++ b/computer/src/gateway/access-store.test.ts@@ -68,29 +68,41 @@ describe('held context', () => {expect(a.held('other', 0).map((r) => r.text)).toEqual(['old elsewhere']);});- it('release deletes by seq; releaseTs by the message’s ts', () => {+ it('release deletes every row up to a seq, also those left out; releaseTs by the message’s ts', () => {const a = fresh();- a.hold(spec.key, 'U2', '2.1', 'one');- a.hold(spec.key, 'U2', '2.2', 'two');- a.hold(spec.key, 'U2', '2.3', 'three');- a.release([a.held(spec.key)[0].seq]);- a.releaseTs(spec.key, '2.3');- expect(a.held(spec.key).map((r) => r.text)).toEqual(['two']);+ for (let i = 1; i <= CONTEXT_MAX_ROWS + 3; i++) a.hold(spec.key, 'U2', `2.${i}`, `m${i}`);+ a.hold('other', 'U2', '2.0', 'elsewhere');+ const read = a.held(spec.key);+ a.hold(spec.key, 'U2', '2.99', 'later');+ a.hold(spec.key, 'U2', '2.100', 'gone');+ a.release(spec.key, read.at(-1)!.seq);+ a.releaseTs(spec.key, '2.100');+ expect(a.held(spec.key).map((r) => r.text)).toEqual(['later']);+ expect(a.held('other')).toHaveLength(1);});});describe('requests', () => {it('one per person per session: a closed one stays and is never replaced', () => {const a = fresh();- a.putRequest(spec.key, 'U2', '3.1', '{"m":1}', 1);- a.putRequest(spec.key, 'U3', '3.2', '{"m":2}', 2);+ expect(a.putRequest(spec.key, 'U2', '{"m":1}', 1)).toBe(true);+ a.requestPosted(spec.key, 'U2', '3.1');+ expect(a.putRequest(spec.key, 'U3', '{"m":2}', 2)).toBe(true);expect(a.openRequests(spec.key).map((r) => r.userId)).toEqual(['U2', 'U3']);a.closeRequest(spec.key, 'U2');- a.putRequest(spec.key, 'U2', '3.3', '{"m":3}', 3);+ expect(a.putRequest(spec.key, 'U2', '{"m":3}', 3)).toBe(false);expect(a.request(spec.key, 'U2')).toEqual({ key: spec.key, userId: 'U2', state: 'closed', messageTs: '3.1', held: '{"m":1}', at: 1 });expect(a.openRequests(spec.key).map((r) => r.userId)).toEqual(['U3']);expect(a.request(spec.key, 'U9')).toBeUndefined();});++ it('a request whose message was not posted is dropped, so the person can ask again', () => {+ const a = fresh();+ a.putRequest(spec.key, 'U2', '{"m":1}');+ a.dropRequest(spec.key, 'U2');+ expect(a.request(spec.key, 'U2')).toBeUndefined();+ expect(a.putRequest(spec.key, 'U2', '{"m":2}')).toBe(true);+ });});describe('accessDefault', () => {diff --git a/computer/src/gateway/access-store.ts b/computer/src/gateway/access-store.tsindex 5ec3e2e1..69e721a2 100644--- a/computer/src/gateway/access-store.ts+++ b/computer/src/gateway/access-store.ts@@ -12,7 +12,9 @@// newest CONTEXT_MAX_ROWS of the session, oldest first, after that// session's rows older than CONTEXT_MAX_AGE_MS are deleted;// - one request per person per session, ever: a closed one stays, so a-// declined person is never asked about twice.+// declined person is never asked about twice. The row is inserted before+// its message is posted (`message_ts` empty until then), so it is the guard+// against two quick mentions; a post that fails deletes it.//// SQL only: who may do what is access.ts, what happens is access-flow.ts.@@ -110,10 +112,9 @@ export class AccessStore {return out;}- /** Held messages that went to the session, by seq. */- release(seqs: readonly number[]) {- const del = this.db.prepare('DELETE FROM session_context WHERE seq = ?');- for (const seq of seqs) del.run(seq);+ /** Held messages up to `seq` went to the session (or were left out as skipped): none of them is sent later, out of order. */+ release(key: string, seq: number) {+ this.db.prepare('DELETE FROM session_context WHERE key = ? AND seq <= ?').run(key, seq);}/** The held message with this ts (a request's, delivered on Allow). */@@ -133,10 +134,22 @@ export class AccessStore {return (this.db.prepare("SELECT * FROM access_requests WHERE key = ? AND state = 'open' ORDER BY at, rowid").all(key) as unknown as RequestRow[]).map(toRequest);}- putRequest(key: string, userId: string, messageTs: string, held: string, at = Date.now()) {- this.db- .prepare("INSERT OR IGNORE INTO access_requests (key, user_id, state, message_ts, held, at) VALUES (?, ?, 'open', ?, ?, ?)")- .run(key, userId, messageTs, held, at);+ /** A new open request, its message not posted yet; false when this person already has one (the row is the guard). */+ putRequest(key: string, userId: string, held: string, at = Date.now()): boolean {+ const r = this.db+ .prepare("INSERT OR IGNORE INTO access_requests (key, user_id, state, message_ts, held, at) VALUES (?, ?, 'open', '', ?, ?)")+ .run(key, userId, held, at);+ return r.changes > 0;+ }++ /** The request's message, once posted. */+ requestPosted(key: string, userId: string, messageTs: string) {+ this.db.prepare('UPDATE access_requests SET message_ts = ? WHERE key = ? AND user_id = ?').run(messageTs, key, userId);+ }++ /** A request whose message could not be posted: as if never asked. */+ dropRequest(key: string, userId: string) {+ this.db.prepare('DELETE FROM access_requests WHERE key = ? AND user_id = ?').run(key, userId);}closeRequest(key: string, userId: string) {diff --git a/computer/src/gateway/access-ui.test.ts b/computer/src/gateway/access-ui.test.tsindex 5ae4b588..8feaaf0a 100644--- a/computer/src/gateway/access-ui.test.ts+++ b/computer/src/gateway/access-ui.test.ts@@ -128,10 +128,10 @@ describe('the modal’s submission', () => {});});- it('a valid submission changes drivers only once acknowledged', async () => {+ it('a valid submission changes drivers at once; done() finishes the announcing', async () => {const r = await router.access.submit(submission('people', [B, 'U1']), ADMIN, wc());- expect(store.access.drivers(key)).toBe('*');- await (r as { done(c: WebClient): Promise<void> }).done(wc());+ expect(store.access.drivers(key)).toEqual([B]);+ await (r as { done(): Promise<void> }).done();expect(store.access.drivers(key)).toEqual([B]);expect(client.of('chat.postMessage')).toHaveLength(0); // '*' to a list: nobody gains});diff --git a/computer/src/gateway/access-ui.ts b/computer/src/gateway/access-ui.tsindex c72f9af0..39a66bc4 100644--- a/computer/src/gateway/access-ui.ts+++ b/computer/src/gateway/access-ui.ts@@ -5,11 +5,13 @@//// !access the state line; `Change…` for someone who can grant// !access open | owner | @a @b replace who drives, then the state line-// !access add @a | remove @a edit the list ('*' counts as empty)+// !access add @a | remove @a edit the list (not on an open session: the usage)// !access default open | owner the org default for new sessions (admins)//-// Views and strings are access-views.ts and access.ts; the steps that follow a-// change are access-flow.ts's setDrivers.+// Views and strings are access-views.ts and access.ts; access-flow.ts's+// setDrivers checks and makes a change, and this file only says its refusals.+// Someone not in the people table gets nothing from a button or the modal+// (routing.ts turns them away before `!access`).import type { WebClient } from '@slack/web-api';import type { KnownBlock, View } from '@slack/types';@@ -19,23 +21,18 @@ import {can,defaultChangedText,editDrivers,- mention,noSessionText,- normalize,- notMemberText,onlyAdminDefaultText,onlyGrantorChangesText,- overLimit,parseAccessCommand,stateText,- tooManyPeopleText,} from '../access.js';import { type AccessSubmission, accessView, decodeAccessId, readSubmission, statePost, submittedKey } from '../access-views.js';import type { SlackSessionSpec } from '../protocol.js';import type { Store } from './db.js';import type { Msg } from './routing.js';import type { ClickBody } from './secrets-ui.js';-import { type AccessFlow, accessOf, actor, changedBy } from './access-flow.js';+import { type AccessFlow, accessOf, actor, changedBy, refusedText } from './access-flow.js';import { errorText, log } from '../log.js';export interface AccessUiDeps {@@ -75,12 +72,9 @@ export function createAccessUi({ store, flow, name }: AccessUiDeps) {}if (c.kind === 'show' || c.kind === 'usage') return; // answered above; this narrows the typeif (!can(a, u, 'grant')) return say(onlyGrantorChangesText(a.owner));- const next = normalize(a.owner, editDrivers(a.drivers, c));- if (overLimit(next)) return say(tooManyPeopleText());- const named = c.kind === 'add' ? c.ids : c.kind === 'set' && c.drivers !== '*' ? c.drivers : [];- const stranger = named.find((id) => id !== a.owner && !actor(store, id).member);- if (stranger) return say(notMemberText(mention(stranger)));- await flow.setDrivers(spec, next, changedBy(spec, u.id), client);+ const r = flow.setDrivers(spec, (d) => editDrivers(d, c), changedBy(spec, u.id), client);+ if ('refused' in r) return say(refusedText(r));+ await r.after;return say(stateText(accessOf(store, spec)));}@@ -89,6 +83,7 @@ export function createAccessUi({ store, flow, name }: AccessUiDeps) {const id = decodeAccessId(actionId);const userId = body.user?.id;if (!id || !userId) return log.warn('unknown access action', actionId);+ if (!store.person(userId)) return;if (id.verb !== 'open') return flow.answer(id.sessionKey, id.verb, id.userId!, userId, client);const row = store.session(id.sessionKey);if (!row) {@@ -105,23 +100,24 @@ export function createAccessUi({ store, flow, name }: AccessUiDeps) {await client.views.open({ trigger_id: body.trigger_id ?? '', view: view as unknown as View }).catch((e) => log.warn('views.open', errorText(e)));}- /** The modal's submission: errors to show in it, or the change to make once it is acknowledged. */+ /** The modal's submission: errors to show in it, or the change, made, whose Slack follow-up `done` awaits after the ack. */async function submit(view: AccessSubmission,userId: string,client: WebClient,- ): Promise<{ errors: Record<string, string> } | { done(client: WebClient): Promise<void> } | undefined> {+ ): Promise<{ errors: Record<string, string> } | { done(): Promise<void> } | undefined> {const key = submittedKey(view);const spec = key ? store.session(key)?.spec : undefined;- if (!spec) return undefined;- const r = readSubmission(view, accessOf(store, spec), actor(store, userId));- if (!r.ok) return { errors: r.errors };- const stranger = r.ids.find((id) => !actor(store, id).member);- if (stranger) {- const wait = new Promise<string>((ok) => setTimeout(() => ok(stranger), NAME_WAIT_MS).unref());- return { errors: { people: notMemberText(await Promise.race([name(client, stranger), wait])) } };- }- return { done: (c) => flow.setDrivers(spec, r.drivers, changedBy(spec, userId), c) };+ if (!spec || !store.person(userId)) return undefined;+ const s = readSubmission(view, accessOf(store, spec), actor(store, userId));+ if (!s.ok) return { errors: s.errors };+ // Made now, so a refusal goes back in the ack; Slack hears of it after (`done`).+ const r = flow.setDrivers(spec, () => s.drivers, changedBy(spec, userId), client);+ if (!('refused' in r)) return { done: () => r.after };+ if (r.refused !== 'member') return { errors: { people: refusedText(r) } };+ const { id } = r;+ const wait = new Promise<string>((ok) => setTimeout(() => ok(id), NAME_WAIT_MS).unref());+ return { errors: { people: refusedText(r, await Promise.race([name(client, id), wait])) } };}return { command, click, submit };diff --git a/computer/src/gateway/main.ts b/computer/src/gateway/main.tsindex b514e9d6..553c65e5 100644--- a/computer/src/gateway/main.ts+++ b/computer/src/gateway/main.ts@@ -138,7 +138,15 @@ const hub = new Hub({secretsFor: (spec) => (isSlackSpec(spec) ? vault.forSession(spec.key, spec.owner.slackUserId) : []),requestSecret: (from, req) => secretsUi.request(from, req, new WebClient(get('SLACK_BOT_TOKEN'), slackClientOptions)),});-const secretsUi: SecretsUi = createSecretsUi({ store, vault, hub });+const secretsUi: SecretsUi = createSecretsUi({+ store,+ vault,+ hub,+ deliver: (spec, h, client) => {+ if (!slackRouter) throw new Error('Slack is not set up on the gateway');+ return slackRouter.deliver(spec, h, client);+ },+});const variablesUi = createVariablesUi({ store, vault, hub });/** The current Slack router (rebuilt with Bolt on reload); spawn requests from hosts go through it. */let slackRouter: Router | undefined;@@ -364,7 +372,7 @@ function boltHandler(): RequestListener {const r = await router.access.submit(view, body.user.id, client);if (r && 'errors' in r) return void (await ack({ response_action: 'errors', errors: r.errors }));await ack();- await r?.done(client).catch((e) => log.warn('access saved, follow-up failed:', errorText(e)));+ await r?.done().catch((e) => log.warn('access saved, follow-up failed:', errorText(e)));});app.view(SECRET_VIEW, async ({ ack, view, body, client }) => {diff --git a/computer/src/gateway/routing.test.ts b/computer/src/gateway/routing.test.tsindex c43461a2..fc0eafa6 100644--- a/computer/src/gateway/routing.test.ts+++ b/computer/src/gateway/routing.test.ts@@ -210,7 +210,7 @@ describe('replies in a session', () => {});it('the stop button interrupts the session', async () => {- await router.stop({ channel: 'C1', thread_ts: root.ts }, 'ev-stop');+ await router.stop({ channel: 'C1', thread_ts: root.ts }, 'ev-stop', client as unknown as WebClient);expect(hub.stops).toEqual([`C1:${root.ts}`]);});});diff --git a/computer/src/gateway/routing.ts b/computer/src/gateway/routing.tsindex 7bf4fd82..2d1d6ceb 100644--- a/computer/src/gateway/routing.ts+++ b/computer/src/gateway/routing.ts@@ -15,12 +15,14 @@// `!access …`, `ac:` buttons, the access modal → access-ui.ts (work 112)//// Only people in the people table get a session; anyone else gets an ephemeral-// "not enabled for you yet" and nothing else. In a session, who may instruct,-// answer and stop is access-flow.ts's (work 112): a message that may not-// instruct is refused, held as context or dropped.+// "not enabled for you yet" and nothing else, at each entry point here (route,+// action, stop) before any rule of a session. In a session, who may instruct,+// answer and stop is access-flow.ts's (work 112): every message but `!access`+// passes its gate before anything else, `!secret` and `!var` too, so a message+// that may not instruct is refused or held as context. This file dispatches.import type { WebClient } from '@slack/web-api';-import { decodeActionId, type Delivery, type HarnessName, NOT_ASKED, type PermissionMode, type SlackPerson, type SlackSessionSpec, type SpawnRequest, type SpawnResult } from '../protocol.js';+import { decodeActionId, type Delivery, type HarnessName, type PermissionMode, type SlackPerson, type SlackSessionSpec, type SpawnRequest, type SpawnResult } from '../protocol.js';import type { SlackFile } from '../protocol.js';import type { ModelRoutes } from '../protocol-model.js';import { addressed, decodeSlack } from '../slack-text.js';@@ -32,8 +34,8 @@ import type { Hub, Reply } from './hosts.js';import type { SecretsUi } from './secrets-ui.js';import type { VariablesUi } from './variables-ui.js';import { log } from '../log.js';-import { can, commandAction, initialDrivers, role } from '../access.js';-import { accessOf, actor, createAccessFlow, type DeliveredRole } from './access-flow.js';+import { commandAction, commandWord, initialDrivers } from '../access.js';+import { createAccessFlow, type DeliveredRole, type HeldMessage } from './access-flow.js';import { createAccessUi } from './access-ui.js';export interface Msg {@@ -65,6 +67,22 @@ export interface RouterDeps {variables?: VariablesUi;}+/** One message to a session's host (`forward`). */+interface Outgoing {+ spec: SlackSessionSpec;+ m: Msg;+ text: string;+ /** As HeldMessage has them; `mentioned` undefined: not typed by a person (a spawned thread's first message). */+ mentioned?: boolean;+ inline?: boolean;+ /** Mentioned mid-thread: the replies above go along. */+ midThread?: boolean;+ /** The session's first message: its agent session is renamed. */+ fresh?: boolean;+ /** The sender's (access-flow.ts), which also brings held context. */+ role?: DeliveredRole;+}+const APP_NAME = process.env.SLACK_APP_NAME ?? 'Computer';const NOT_ENABLED = `${APP_NAME} is not enabled for you yet. Ask the instance owner to add you.`;const OFFLINE = 'The agent host is offline; your message will be delivered when it reconnects.';@@ -96,7 +114,8 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: Rconst flow = createAccessFlow({store,- deliver: (spec, h, r, client) => forward(spec, h.m, h.text, client, h.mentioned, h.inline, false, false, r),+ hub,+ deliver: (spec, h, role, client) => forward({ spec, ...h, role }, client),name: resolveLinks.nameOf,});const access = createAccessUi({ store, flow, name: resolveLinks.nameOf });@@ -116,19 +135,13 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: Rconst existing = lookup(m.channel, m.thread_ts);if (!existing && !mentioned && m.channel_type !== 'im') return;const person = store.person(m.user);- if (!person && !existing) return notEnabled(m, client);- if (person && secrets && /^!secrets?(\s|$)/i.test(text)) return secrets.command(text, m, person, existing?.spec, client);- if (person && variables && (await variables.command(text, m, person, existing?.spec, client))) return;+ // Someone else talking in a session's thread is not asking for access.+ if (!person) return mentioned || !existing ? notEnabled(m, client) : undefined;+ // The one command outside the gate: it shows access (view) and changes it (grant) by its own rules.if (commandAction(text) === 'access') return access.command(text, m, existing?.spec, client);- if (existing) {- // In a DM or a code channel every message is for the bot.- const forBot = mentioned || m.channel_type === 'im' || existing.spec.kind === 'channel';- const r = await flow.message(existing.spec, { m, text, mentioned: forBot, inline: a.inline }, client);- // Someone else talking in a session's thread is not asking for access.- if (r === 'outsider') return mentioned ? notEnabled(m, client) : undefined;- return r ? forward(existing.spec, m, text, client, forBot, a.inline, false, false, r) : undefined;- }- if (!person) return;+ // In a DM or a code channel every message is for the bot.+ if (existing) return deliver(existing.spec, { m, text, mentioned: mentioned || m.channel_type === 'im' || existing.spec.kind === 'channel', inline: a.inline }, client);+ if (await gatewayCommand(text, m, undefined, client)) return;// `+codex` first; then `+smart ch <task>` and `ch +smart <task>` both work; the tier stays on the task for the session.const { harness, text: asked } = takeHarness(text);@@ -156,11 +169,30 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: Rlog.info(`new session ${spec.key} for ${person.dir}`);// Mentioned mid-thread: the session also gets the replies above (it only sees what reaches it from now on).const midThread = spec.kind === 'thread' && !!m.thread_ts && m.thread_ts !== m.ts;- return forward(spec, m, task, client, true, a.inline, midThread, spec.kind === 'thread', 'owner');+ return forward({ spec, m, text: task, mentioned: true, inline: a.inline, midThread, fresh: spec.kind === 'thread', role: 'owner' }, client);+ }++ /**+ * A message in an existing session from a person, typed or made for them (a+ * secret set from a request): the role gate first (access-flow.ts), then+ * the gateway's own commands, then the host.+ */+ async function deliver(spec: SlackSessionSpec, h: HeldMessage, client: WebClient) {+ const role = await flow.message(spec, h, client);+ if (!role || (await gatewayCommand(h.text, h.m, spec, client))) return;+ return forward({ spec, ...h, role }, client);+ }++ /** `!secret …` and `!var …`, answered here and never delivered; true when `text` was one. */+ async function gatewayCommand(text: string, m: Msg, spec: SlackSessionSpec | undefined, client: WebClient): Promise<boolean> {+ const person = store.person(m.user!);+ if (!person) return false;+ if (secrets && /^!secrets?(\s|$)/i.test(text)) return (await secrets.command(text, m, person, spec, client), true);+ return !!variables && (await variables.command(text, m, person, spec, client));}- /** Feedback first (< 1 s, no await), then hand to the host; `role`: the sender's (access-flow.ts), which also brings held context. */- async function forward(spec: SlackSessionSpec, m: Msg, text: string, client: WebClient, mentioned?: boolean, inline = false, midThread = false, fresh = false, role?: DeliveredRole) {+ /** Feedback first (< 1 s, no await), then hand to the host. */+ async function forward({ spec, m, text, mentioned, inline = false, midThread = false, fresh = false, role }: Outgoing, client: WebClient) {const msg: Delivery = {userId: m.user!,text,@@ -170,7 +202,7 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R...(mentioned && inline ? { mentionedInline: true } : {}),...(role ? { role } : {}),};- const command = text.startsWith('!') && !text.startsWith('!!');+ const command = commandWord(text) !== undefined;const online = hub.connected.length > 0;// A reply that @mentions other people and not the bot is most likely for// them: no "thinking…" flash; the agent decides whether to answer.@@ -294,31 +326,25 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R}}- /** Slack's native stop button on a processing agent session; `user`: who clicked, when Slack says. */- async function stop(ev: { channel: string; thread_ts?: string; user?: string }, eventId?: string, client?: WebClient) {+ /** Slack's native stop button on a processing agent session; `user`: who clicked, when Slack says (anyone not a person: ignored). */+ async function stop(ev: { channel: string; thread_ts?: string; user?: string }, eventId: string | undefined, client: WebClient) {if (!fresh(eventId)) return;const row = lookup(ev.channel, ev.thread_ts);log.info('stop button', ev.channel, ev.thread_ts, ev.user, !!row);- if (!row) return;- if (ev.user && !can(accessOf(store, row.spec), actor(store, ev.user), 'stop')) return log.info(`stop ${row.spec.key} by ${ev.user} ignored`);- const r = await hub.stop(row.spec.key);- if (!r.ok) return log.warn(`stop ${row.spec.key}: ${r.error}`);- if (ev.user && ev.user !== row.spec.owner.slackUserId && client) await flow.stopped(row.spec, ev.user, client);+ if (!row || (ev.user && !store.person(ev.user))) return;+ await flow.stop(row.spec, ev.user, client);}/** A prompt button: `p:<base64url(sessionKey)>:<promptId>:<value>`. */async function action(actionId: string, userId: string, client: WebClient, channel?: string) {const a = decodeActionId(actionId);if (!a) return log.warn('unknown action id', actionId);+ if (!store.person(userId)) return channel ? ephemeral(client, channel, userId, NOT_ENABLED) : undefined;const spec = store.session(a.sessionKey)?.spec;if (!spec) return log.warn('action for unknown session', a.sessionKey);- const acc = accessOf(store, spec);- const u = actor(store, userId);- if (!can(acc, u, 'answer')) return flow.notAsked(spec, userId, client);- const r = await hub.action(a.sessionKey, a.promptId, a.value, userId, role(acc, u) === 'owner' ? 'owner' : 'driver');+ const r = await flow.click(spec, a.promptId, a.value, userId, client);if (r === 'queued') return channel ? ephemeral(client, channel, userId, OFFLINE) : undefined;- if (!r.ok && r.error === NOT_ASKED) return flow.notAsked(spec, userId, client);- if (!r.ok) log.warn(`action for ${a.sessionKey}: ${r.error}`);+ if (r && !r.ok) log.warn(`action for ${a.sessionKey}: ${r.error}`);}/**@@ -367,13 +393,13 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R`Started by the session in thread ${from}${parentUrl ? ` (${parentUrl})` : ''}. ` +'Read the brief first; claim and report there.';// Not awaited: starting the runner can take longer than the parent should wait.- void forward(spec, { channel, ts: threadTs, thread_ts: threadTs, user: owner.slackUserId }, text, client, undefined, false, false, false, 'owner').catch((e) =>+ void forward({ spec, m: { channel, ts: threadTs, thread_ts: threadTs, user: owner.slackUserId }, text, role: 'owner' }, client).catch((e) =>log.warn(`deliver to spawned ${spec.key}:`, e?.message ?? e),);return { key: spec.key, url: await link(channel, threadTs) };}- return { route, stop, action, spawn, access, threads: threadAccess(store, resolveLinks) };+ return { route, deliver, stop, action, spawn, access, threads: threadAccess(store, resolveLinks) };}export type Router = ReturnType<typeof createRouter>;diff --git a/computer/src/gateway/secrets-ui.ts b/computer/src/gateway/secrets-ui.tsindex 64c2043f..3c23894d 100644--- a/computer/src/gateway/secrets-ui.ts+++ b/computer/src/gateway/secrets-ui.ts@@ -12,6 +12,11 @@// Scopes: this session (anyone enabled), just me (all sessions the person// owns), workspace (every session; admins only). Handled here, not by the runner:// the gateway holds the values and Slack modals need its interactivity.+//+// Session roles (work 112): in a session, `!secret` passes routing.ts's role+// gate like any message; a form opened from a session is submitted only by+// someone who can instruct it, and the "continue" it sends goes through that+// same gate (`deliver`), never to the hub directly.import type { WebClient } from '@slack/web-api';import type { KnownBlock, View } from '@slack/types';@@ -21,6 +26,8 @@ import type { Store } from './db.js';import type { Hub } from './hosts.js';import { MAX_VALUE, type Vault } from './vault.js';import type { Msg } from './routing.js';+import { can, driversCommandText } from '../access.js';+import { accessOf, actor, type HeldMessage } from './access-flow.js';import { errorText, log } from '../log.js';export const SECRET_VIEW = 'calvin_secret';@@ -87,10 +94,12 @@ export interface SubmittedView {export interface SecretsUiDeps {store: Store;vault: Vault;- hub: Hub;+ hub: Pick<Hub, 'pushSecrets'>;+ /** A message to a session as if its sender typed it (routing.ts `deliver`: the role gate, then the host). */+ deliver(spec: SlackSessionSpec, h: HeldMessage, client: WebClient): Promise<void>;}-export function createSecretsUi({ store, vault, hub }: SecretsUiDeps) {+export function createSecretsUi({ store, vault, hub, deliver }: SecretsUiDeps) {const thread = (spec?: SlackSessionSpec) => (spec?.kind === 'thread' ? spec.threadTs : undefined);async function ephemeral(client: WebClient, channel: string, user: string, text: string, threadTs?: string, blocks?: KnownBlock[]) {@@ -243,6 +252,7 @@ export function createSecretsUi({ store, vault, hub }: SecretsUiDeps) {if (!value.trim()) return { errors: { value: 'Enter a value.' } };if (Buffer.byteLength(value) > MAX_VALUE) return { errors: { value: 'Too large.' } };const spec = meta.k ? store.session(meta.k)?.spec : undefined;+ if (spec && !can(accessOf(store, spec), actor(store, userId), 'instruct')) return { errors: { name: driversCommandText('secret') } };if (scope === 'session' && !spec) return { errors: { scope: 'This session no longer exists; pick another scope.' } };if (scope === 'workspace' && !person.admin) return { errors: { scope: 'Only admins can set workspace secrets.' } };if (!scope) return { errors: { scope: 'Pick where it applies.' } };@@ -267,8 +277,8 @@ export function createSecretsUi({ store, vault, hub }: SecretsUiDeps) {const applies = spec && (scope !== 'user' || spec.owner.slackUserId === userId);if (meta.rq && spec && applies) {const text = `Secret $${name} is set (${where === 'just you' ? 'all my sessions' : where}). It is in the environment of your next Bash command${file ? ' as the path of a file holding it' : ''}. Continue.`;- const r = await hub.deliver(spec, { userId, text, ts: meta.rq, mentioned: true });- if (r !== 'queued' && !r.ok) log.warn(`secret set: deliver to ${spec.key} failed: ${r.error}`);+ const m = { channel: meta.ch ?? spec.channel, ts: meta.rq, user: userId, ...(meta.th ? { thread_ts: meta.th } : {}) };+ await deliver(spec, { m, text, mentioned: true, inline: false }, client);}if (pushed) log.info(`secrets pushed to ${pushed} live session(s)`);},diff --git a/computer/src/runner/model-access.test.ts b/computer/src/runner/model-access.test.tsindex a0d1df5d..53c7d48e 100644--- a/computer/src/runner/model-access.test.ts+++ b/computer/src/runner/model-access.test.ts@@ -201,4 +201,13 @@ describe('runnerModelAccess: the ceiling and a refused model', () => {expect(s.send).toHaveBeenCalledOnce();expect(a.idle()).toBe(false);});++ it('the retry keeps the turn’s driver (work 112)', async () => {+ const { a, s } = setup();+ Object.assign(s, { driver: 'UD' });+ a.apply(route({ tokenEnv: 'CLAUDE_CODE_OAUTH_TOKEN', downgradeOnModelRefusal: true }));+ await a.event(denied);+ a.idle();+ expect(s.send).toHaveBeenCalledWith(expect.any(String), 'UD', [], undefined, undefined, 'driver');+ });});diff --git a/computer/src/runner/model-access.ts b/computer/src/runner/model-access.tsindex af1ba7f0..1a5ab297 100644--- a/computer/src/runner/model-access.ts+++ b/computer/src/runner/model-access.ts@@ -155,7 +155,8 @@ export function runnerModelAccess({ env, cacheTtl, hooks: o }: RunnerModelAccessconst s = o.session();if (!retry || !s) return false;retry = false;- void s.send(RETRY_TEXT, s.info.userId);+ // The retried turn is still the driver's (work 112): their prompts keep waiting on them.+ void s.send(RETRY_TEXT, s.driver ?? s.info.userId, [], undefined, undefined, s.driver ? 'driver' : undefined);return true;},};diff --git a/services/managed-agents/src/computer/access-flow.ts b/services/managed-agents/src/computer/access-flow.tsindex db441c7e..f94b28df 100644--- a/services/managed-agents/src/computer/access-flow.ts+++ b/services/managed-agents/src/computer/access-flow.ts@@ -7,9 +7,11 @@// it gets as dependencies (like secrets-store.ts). The modal and `!access`// are access-ui.ts.//-// Member: a full member of the linked workspace (`isWorkspaceMember`). Admin:-// a Slack user linked to a dashboard member the dashboard last saw as an-// owner or admin (`apiAdmins`, sessions-api.ts). Both fail closed.+// Member: a full member of the linked workspace (`ThreadAccess.member`, the+// Durable Object's one cached lookup of a person). A failed lookup throws:+// a queued message is retried, a click or a modal answers "try again".+// Admin: a Slack user linked to a dashboard member the dashboard last saw as+// an owner or admin (`apiAdmins`, sessions-api.ts); fails closed.import {type Access,@@ -26,6 +28,9 @@ import {initialDrivers,normalize,notAskedText,+ notMemberText,+ noSessionText,+ overLimit,onlyGrantorAnswersText,onlyMembersText,openedText,@@ -36,12 +41,14 @@ import {role,sameDrivers,stoppedText,+ tooManyPeopleText,+ ACCESS_USAGE,} from "./access.js";import { declinedPost, requestPost } from "./access-views.js";-import type { AccessStore } from "./access-store.js";+import type { AccessRequest, AccessStore } from "./access-store.js";import { type CalvinSlackFile, type CalvinTraceContext, NOT_ASKED } from "./protocol.js";-import { type SlackMessageJob, type SlackResult, isWorkspaceMember } from "./slack.js";-import { type Linked, forwardedLinked } from "./threads.js";+import type { SlackMessageJob, SlackResult } from "./slack.js";+import { type Linked, LOOKUP_FAILED_TEXT } from "./threads.js";/** Pending prompt clicks remembered for a `not-asked` reply; the oldest go first past this. */const MAX_PENDING_ANSWERS = 200;@@ -73,11 +80,14 @@ export type MessageGate =| { deliver: true; role: "owner" | "driver" | "participant"; context: boolean }| { deliver: false; reason: "outsider" | "held" | "command_refused" };+/** Why `setDrivers` changed nothing: the caller only turns it into words (`refusalText`). */+export type DriversRefusal = { refused: "gone" | "usage" | "limit" } | { refused: "member"; id: string };+export interface AccessFlowDeps {store: AccessStore;slack(method: string, body: Record<string, unknown>): Promise<SlackResult>;- /** The linked Slack workspace. */- teamId(): string;+ /** Whether a person is a full member of the linked workspace (cached); throws when Slack could not be asked. */+ member(slackUserId: string): Promise<boolean>;/** A session with an owner, by runner key. */session(key: string): RoleSession | undefined;/** The dashboard member a Slack user linked to (`!link`), if any. */@@ -86,10 +96,11 @@ export interface AccessFlowDeps {isAdmin(member: string): boolean;/** A person's display name (cached), or their id. */name(slackUserId: string): Promise<string>;- /** Whether the organization may run a turn now (the credit gate); tells the thread when not. */- admit(channelId: string, threadTs: string): Promise<boolean>;- /** Queue a delivery for the host; resolves once it is accepted (sent, or kept for an offline host). */- deliver(dispatch: AccessDispatch): Promise<void>;+ /**+ * Put a message back on the Slack queue, synchronously: an allowed+ * request's message goes through the queue as its sender's, like any other.+ */+ requeue(job: SlackMessageJob): void;/** `access.changed`. */changed(key: string, by: ChangedBy, from: string, to: string): void;waitUntil(work: Promise<unknown>): void;@@ -101,6 +112,11 @@ export class AccessFlow {constructor(private readonly deps: AccessFlowDeps) {}+ /** The session a runner key names, with an owner. */+ session(key: string): RoleSession | undefined {+ return this.deps.session(key);+ }+access(key: string): Access | undefined {const s = this.deps.session(key);const drivers = s && this.deps.store.drivers(key);@@ -109,15 +125,32 @@ export class AccessFlow {/*** Who is acting. The owner's membership is not looked up: `role` puts the- * owner first, so it decides nothing for them.+ * owner first, so it decides nothing for them. Throws when Slack could not+ * be asked.*/async actor(userId: string, owner?: string): Promise<Actor> {const link = this.deps.linkOfSlack(userId);const admin = !!link && this.deps.isAdmin(link);- const member = userId === owner || (await isWorkspaceMember((method, body) => this.deps.slack(method, body), this.deps.teamId(), userId));+ const member = userId === owner || (await this.deps.member(userId));return { id: userId, member, admin };}+ /** `actor` for a click: when Slack could not be asked, the clicker is told to try again and it is undefined. */+ async clicker(s: { channelId: string; threadTs?: string }, userId: string, owner: string): Promise<Actor | undefined> {+ try {+ return await this.actor(userId, owner);+ } catch {+ await this.ephemeral(s, userId, LOOKUP_FAILED_TEXT);+ return undefined;+ }+ }++ /** Whether `userId` may write to or wake the session (`can(instruct)`); anyone, for a session without an owner. Throws as `actor`. */+ async instructs(key: string, userId: string): Promise<boolean> {+ const a = this.access(key);+ return !a || can(a, await this.actor(userId, a.owner), "instruct");+ }+/** `ChangedBy` for an actor: `admin` only when an admin who is not the owner made the change. */by(a: Access, u: Actor): ChangedBy {return { id: u.id, admin: u.admin && u.id !== a.owner };@@ -141,39 +174,84 @@ export class AccessFlow {// ---------------------------------------------------------------- one transition- /** The only write of `drivers` ("One transition", steps 1–6). */- async setDrivers(key: string, next: Drivers, by: ChangedBy): Promise<void> {- const s = this.deps.session(key);- const prev = s && this.deps.store.drivers(key);- if (!s || prev === undefined) return;- // 1–2.- next = normalize(s.ownerId, next);- if (sameDrivers(prev, next)) return;- this.deps.store.writeDrivers(key, next);- // 3. The marker, when restricted changed.- if (restricted(prev) !== restricted(next)) await this.marker(s, restricted(next));- // 4. Requests whose requester now drives: answered, and the message that asked runs.- const handled: string[] = [];- for (const r of this.deps.store.openRequests(key)) {- if (next !== "*" && !next.includes(r.userId)) continue;- if (!this.deps.store.closeRequest(key, r.userId)) continue;- handled.push(r.userId);- await this.call("chat.update", { channel: s.channelId, ts: r.messageTs, text: grantedText(by, [r.userId], s.ownerId), blocks: [] });- const job = JSON.parse(r.held) as SlackMessageJob;- this.deps.store.forgetMessage(key, job.messageTs);- try {- await this.deliverHeld(s, job);- } catch (error) {- warn("computer.access_held_failed", error);+ /**+ * The only write of `drivers` ("One transition"): `edit` turns the current+ * value into the next (undefined: it does not apply to it). The people it+ * adds are looked up first, together; then the current value is read,+ * edited, checked and written with nothing awaited in between, so an edit+ * made meanwhile is never lost. Undefined when done (also when nothing+ * changed); otherwise why not, for the caller to word.+ */+ async setDrivers(key: string, edit: (current: Drivers) => Drivers | undefined, by: ChangedBy): Promise<DriversRefusal | undefined> {+ const members = new Map<string, boolean>();+ for (;;) {+ // 1–2: read, edit, normalize, check.+ const s = this.deps.session(key);+ const prev = s && this.deps.store.drivers(key);+ if (!s || prev === undefined) return { refused: "gone" };+ const edited = edit(prev);+ if (edited === undefined) return { refused: "usage" };+ const next = normalize(s.ownerId, edited);+ if (overLimit(next)) return { refused: "limit" };+ // Only the people this names: someone already named stays until removed.+ const named = next === "*" ? [] : next.filter((id) => prev === "*" || !prev.includes(id));+ const unknown = named.filter((id) => !members.has(id));+ if (unknown.length) {+ // Looked up together; then read again, as the lookups let other edits in.+ const found = await Promise.all(unknown.map((id) => this.deps.member(id)));+ unknown.forEach((id, n) => members.set(id, found[n]!));+ continue;}+ const outsider = named.find((id) => !members.get(id));+ if (outsider) return { refused: "member", id: outsider };+ const granted = this.write(s, next);+ // 3. The marker, when restricted changed.+ if (restricted(prev) !== restricted(next)) await this.marker(s, restricted(next));+ for (const r of granted) await this.call("chat.update", { channel: s.channelId, ts: r.messageTs, text: grantedText(by, [r.userId], s.ownerId), blocks: [] });+ // 5. Announce when more people can drive than before.+ const more = gained(prev, next);+ const added = more === "opened" ? [] : more.filter((id) => !granted.some((r) => r.userId === id));+ if (more === "opened") await this.post(s, openedText(by, s.ownerId));+ else if (added.length) await this.post(s, grantedText(by, added, s.ownerId));+ // 6.+ if (!sameDrivers(prev, next)) this.deps.changed(key, by, encodeDrivers(prev), encodeDrivers(next));+ return undefined;+ }+ }++ /**+ * The write, and step 4 in the same synchronous block: requests whose+ * requester now may instruct are closed, and the message that asked goes+ * back on the queue as theirs, where `message` gates it again (a requester+ * was a member when they asked; the queue looks again). The closed requests.+ */+ private write(s: RoleSession, next: Drivers): AccessRequest[] {+ this.deps.store.writeDrivers(s.key, next);+ const a: Access = { owner: s.ownerId, drivers: next };+ const granted: AccessRequest[] = [];+ for (const r of this.deps.store.openRequests(s.key)) {+ if (!can(a, { id: r.userId, member: true, admin: false }, "instruct")) continue;+ if (!this.deps.store.closeRequest(s.key, r.userId)) continue;+ const job = JSON.parse(r.held) as SlackMessageJob;+ this.deps.store.forgetMessage(s.key, job.messageTs);+ this.deps.requeue(job);+ granted.push(r);+ }+ return granted;+ }++ /** A refusal from `setDrivers`, in words. */+ async refusalText(r: DriversRefusal): Promise<string> {+ switch (r.refused) {+ case "gone":+ return noSessionText();+ case "usage":+ return ACCESS_USAGE;+ case "limit":+ return tooManyPeopleText();+ case "member":+ return notMemberText(await this.deps.name(r.id));}- // 5. Announce when more people can drive than before.- const more = gained(prev, next);- const added = more === "opened" ? [] : more.filter((id) => !handled.includes(id));- if (more === "opened") await this.post(s, openedText(by, s.ownerId));- else if (added.length) await this.post(s, grantedText(by, added, s.ownerId));- // 6.- this.deps.changed(key, by, encodeDrivers(prev), encodeDrivers(next));}/** 🔒 on the thread's first message; `already_reacted` and `no_reaction` are success. Never throws. */@@ -189,10 +267,12 @@ export class AccessFlow {// ---------------------------------------------------------------- messages/**- * A message in an existing session ("Messages" steps 2–4), after the- * gateway's own commands and `!access`: whether it is delivered, and as- * whom. A participant's message is held as context, and a mention of the- * app at its start asks the owner to let them drive.+ * A message in an existing session ("Messages" steps 2–4), after `!access`+ * and before every other command, the gateway's own (`!secret`, `!var`, ...)+ * too: they read as `instruct`. Whether it is delivered (or, for a gateway+ * command, handled), and as whom. A participant's message is held as+ * context, and a mention of the app at its start asks the owner to let them+ * drive. Throws when Slack could not be asked who sent it: the queue retries.*/async message(job: SlackMessageJob, text: string, s: RoleSession): Promise<MessageGate> {const a: Access = { owner: s.ownerId, drivers: this.deps.store.drivers(s.key) ?? "*" };@@ -200,28 +280,27 @@ export class AccessFlow {const r = role(a, u);const command = commandAction(text);if (command !== undefined && command !== "access") {- if (can(a, u, command)) return { deliver: true, role: r === "outsider" ? "participant" : r, context: false };+ // An outsider can do nothing: `can` is false for them.+ if (can(a, u, command)) return { deliver: true, role: r as "owner" | "driver" | "participant", context: false };const word = commandWord(text) ?? "";if (command === "settings") await this.ephemeral(s, job.userId, ownerCommandText(s.ownerId, word));else if (command === "instruct") await this.ephemeral(s, job.userId, driversCommandText(word));return { deliver: false, reason: "command_refused" };}if (r === "owner" || r === "driver") return { deliver: true, role: r, context: true };- const mentioned = job.mentioned || job.channelType === "im";if (r === "outsider") {- if (mentioned) await this.ephemeral(s, job.userId, onlyMembersText());+ if (job.mentioned || job.channelType === "im") await this.ephemeral(s, job.userId, onlyMembersText());return { deliver: false, reason: "outsider" };}- this.deps.store.hold(s.key, {+ const held = this.deps.store.hold(s.key, {userId: job.userId,ts: job.messageTs,text: job.text,files: (job.files ?? []).map((f) => f.name ?? f.title ?? f.id),});- if (mentioned) {- if (this.deps.store.request(s.key, job.userId)) await this.ephemeral(s, job.userId, ownerDecidesText(s.ownerId));- else await this.requestToDrive(s, job);- }+ // The row is the guard: a message held already (a retried job) asks nothing again.+ // Only a mention of the app at the message's start asks, as self-hosted.+ if (held && ((job.mentioned && !job.mentionedInline) || job.channelType === "im")) await this.requestToDrive(s, job);return { deliver: false, reason: "held" };}@@ -247,35 +326,18 @@ export class AccessFlow {this.deps.store.forget(held.map((h) => h.seq));}- /** An allowed request's message, as its sender's own: through the credit gate, with the held context. */- private async deliverHeld(s: RoleSession, job: SlackMessageJob): Promise<void> {- if (!(await this.deps.admit(s.channelId, s.threadTs))) return;- const forwarded = forwardedLinked(job.forwarded);- await this.deliver(- s.key,- {- channelId: s.channelId,- threadTs: s.threadTs,- messageTs: job.messageTs,- userId: job.userId,- text: job.text,- ...(job.files?.length ? { files: job.files } : {}),- mentioned: job.mentioned || job.channelType === "im",- ...(forwarded.length ? { linked: forwarded } : {}),- role: "driver" as const,- },- (d) => this.deps.deliver(d),- );- }-// ---------------------------------------------------------------- request to drive- /** S1 with its buttons in the thread, the request row, and S2 to the requester. */+ /**+ * The request row first, the guard against a second (S2b when there was+ * one); then S1 with its buttons in the thread, whose ts the row gets, and+ * S2 to the requester. A post that fails takes the row with it.+ */private async requestToDrive(s: RoleSession, job: SlackMessageJob): Promise<void> {- const post = requestPost(s.key, s.ownerId, job.userId);- const posted = await this.call("chat.postMessage", { channel: s.channelId, thread_ts: s.threadTs, ...post });- if (!posted?.ok || !posted.ts) return;- this.deps.store.addRequest(s.key, job.userId, posted.ts, JSON.stringify(job));+ if (!this.deps.store.addRequest(s.key, job.userId, JSON.stringify(job))) return this.ephemeral(s, job.userId, ownerDecidesText(s.ownerId));+ const posted = await this.call("chat.postMessage", { channel: s.channelId, thread_ts: s.threadTs, ...requestPost(s.key, s.ownerId, job.userId) });+ if (!posted?.ok || !posted.ts) return this.deps.store.deleteRequest(s.key, job.userId);+ this.deps.store.postedRequest(s.key, job.userId, posted.ts);await this.ephemeral(s, job.userId, requestSentText(s.ownerId));}@@ -284,7 +346,8 @@ export class AccessFlow {const s = this.deps.session(key);const a = this.access(key);if (!s || !a) return;- const u = await this.actor(userId, a.owner);+ const u = await this.clicker(s, userId, a.owner);+ if (!u) return;if (!can(a, u, "grant")) return this.ephemeral(s, userId, onlyGrantorAnswersText(a.owner));const request = this.deps.store.request(key, requester);if (request?.state !== "open") return;@@ -293,14 +356,14 @@ export class AccessFlow {if (this.deps.store.closeRequest(key, requester)) await this.call("chat.update", { channel: s.channelId, ts: request.messageTs, ...declinedPost(requester) });return;}- // Everyone drives already: nothing to grant, only the request to answer.- if (a.drivers === "*") {- if (this.deps.store.closeRequest(key, requester)) {- await this.call("chat.update", { channel: s.channelId, ts: request.messageTs, text: grantedText(by, [requester], a.owner), blocks: [] });- }- return;+ // Under '*' the requester drives already: nothing is added, and `setDrivers` still answers the request.+ let refused: DriversRefusal | undefined;+ try {+ refused = await this.setDrivers(key, (d) => (d === "*" ? d : [...d, requester]), by);+ } catch {+ return this.ephemeral(s, userId, LOOKUP_FAILED_TEXT);}- await this.setDrivers(key, [...a.drivers, requester], by);+ if (refused) await this.ephemeral(s, userId, await this.refusalText(refused));}// ---------------------------------------------------------------- prompts@@ -318,7 +381,8 @@ export class AccessFlow {send();return;}- const u = await this.actor(userId, a.owner);+ const u = await this.clicker(s, userId, a.owner);+ if (!u) return;if (!can(a, u, "answer")) return this.ephemeral(s, userId, notAskedText(a.owner));const id = send(role(a, u) === "owner" ? "owner" : "driver");this.answers.set(id, { key, userId });@@ -342,7 +406,8 @@ export class AccessFlow {async stop(s: RoleSession, userId: string | undefined, send: () => boolean): Promise<boolean> {if (userId) {const a: Access = { owner: s.ownerId, drivers: this.deps.store.drivers(s.key) ?? "*" };- if (!can(a, await this.actor(userId, s.ownerId), "stop")) return false;+ const u = await this.clicker(s, userId, s.ownerId);+ if (!u || !can(a, u, "stop")) return false;}const delivered = send();if (delivered && userId && userId !== s.ownerId) await this.post(s, stoppedText(userId));diff --git a/services/managed-agents/src/computer/access-store.ts b/services/managed-agents/src/computer/access-store.tsindex 20cbf00f..1c6c7bd4 100644--- a/services/managed-agents/src/computer/access-store.ts+++ b/services/managed-agents/src/computer/access-store.ts@@ -50,6 +50,7 @@ export class AccessStore {key TEXT NOT NULL, user_id TEXT NOT NULL, ts TEXT NOT NULL,text TEXT NOT NULL, files TEXT, at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS session_context_key ON session_context (key, seq);+ CREATE UNIQUE INDEX IF NOT EXISTS session_context_ts ON session_context (key, ts);CREATE TABLE IF NOT EXISTS access_requests (key TEXT NOT NULL, user_id TEXT NOT NULL,state TEXT NOT NULL,@@ -87,16 +88,17 @@ export class AccessStore {// ---------------------------------------------------------------- context- hold(key: string, m: { userId: string; ts: string; text: string; files: string[] }, now = Date.now()): void {- this.sql.exec(- "INSERT INTO session_context (key, user_id, ts, text, files, at) VALUES (?, ?, ?, ?, ?, ?)",+ /** True when this call held it: a message already held (a retried job) is not held, or acted on, again. */+ hold(key: string, m: { userId: string; ts: string; text: string; files: string[] }, now = Date.now()): boolean {+ return this.sql.exec(+ "INSERT OR IGNORE INTO session_context (key, user_id, ts, text, files, at) VALUES (?, ?, ?, ?, ?, ?)",key,m.userId,m.ts,m.text.slice(0, CONTEXT_MAX_CHARS),m.files.length ? JSON.stringify(m.files) : null,now,- );+ ).rowsWritten > 0;}/** The newest CONTEXT_MAX_ROWS, oldest first, after this session's rows older than CONTEXT_MAX_AGE_MS are deleted. */@@ -141,8 +143,22 @@ export class AccessStore {)];}- addRequest(key: string, userId: string, messageTs: string, held: string, now = Date.now()): void {- this.sql.exec("INSERT OR IGNORE INTO access_requests (key, user_id, state, message_ts, held, at) VALUES (?, ?, 'open', ?, ?, ?)", key, userId, messageTs, held, now);+ /**+ * True when this call added it: the row is the guard against a second+ * request, so it is written before the request is posted (`messageTs` '').+ */+ addRequest(key: string, userId: string, held: string, now = Date.now()): boolean {+ return this.sql.exec("INSERT OR IGNORE INTO access_requests (key, user_id, state, message_ts, held, at) VALUES (?, ?, 'open', '', ?, ?)", key, userId, held, now).rowsWritten > 0;+ }++ /** The request's post, once Slack has it. */+ postedRequest(key: string, userId: string, messageTs: string): void {+ this.sql.exec("UPDATE access_requests SET message_ts = ? WHERE key = ? AND user_id = ?", messageTs, key, userId);+ }++ /** A request whose post failed: gone, so the next mention asks again. */+ deleteRequest(key: string, userId: string): void {+ this.sql.exec("DELETE FROM access_requests WHERE key = ? AND user_id = ?", key, userId);}/** True when this call closed it: one of two overlapping clicks acts. */diff --git a/services/managed-agents/src/computer/access-ui.ts b/services/managed-agents/src/computer/access-ui.tsindex 56ac9e8a..d6fc0b7d 100644--- a/services/managed-agents/src/computer/access-ui.ts+++ b/services/managed-agents/src/computer/access-ui.ts@@ -11,18 +11,15 @@ import {defaultChangedText,editDrivers,noSessionText,- normalize,- notMemberText,onlyAdminDefaultText,onlyGrantorChangesText,- overLimit,parseAccessCommand,- tooManyPeopleText,} from "./access.js";import { type AccessSubmission, accessView, decodeAccessId, readSubmission, statePost, submittedKey } from "./access-views.js";import type { AccessFlow } from "./access-flow.js";import type { AccessStore } from "./access-store.js";-import { type SlackResult, isWorkspaceMember } from "./slack.js";+import type { SlackResult } from "./slack.js";+import { LOOKUP_FAILED_TEXT } from "./threads.js";/** Where an answer goes: the person, and the channel and thread they acted in. */export interface AccessWhere {@@ -35,9 +32,6 @@ export interface AccessUiDeps {flow: AccessFlow;store: AccessStore;slack(method: string, body: Record<string, unknown>): Promise<SlackResult>;- teamId(): string;- /** A person's display name (cached), or their id. */- name(slackUserId: string): Promise<string>;}/** Follow-up work the Durable Object runs after it answered Slack (`waitUntil`). */@@ -63,23 +57,44 @@ export class AccessUi {await this.deps.flow.ephemeral(threadOf(where), where.userId, noSessionText());return {};}- const view = accessView(id.sessionKey, a, await this.deps.flow.actor(where.userId, a.owner));+ const u = await this.deps.flow.clicker(threadOf(where), where.userId, a.owner);+ const view = u && accessView(id.sessionKey, a, u);if (view && triggerId) await this.call("views.open", { trigger_id: triggerId, view });return {};}- /** The modal's `Save`: `errors` keep it open; `after` is the change. */+ /**+ * The modal's `Save`: `errors` keep it open; `after` is the change, whose+ * refusal (someone not a member, too many) is an ephemeral in the session's+ * thread: its lookups are `setDrivers`' and do not fit Slack's 3 s.+ */async submit(view: AccessSubmission, userId: string): Promise<{ errors?: Record<string, string>; after?: After }> {const key = submittedKey(view);const a = key ? this.deps.flow.access(key) : undefined;if (!key || !a) return { errors: { who: noSessionText() } };- const u = await this.deps.flow.actor(userId, a.owner);+ let u;+ try {+ u = await this.deps.flow.actor(userId, a.owner);+ } catch {+ return { errors: { who: LOOKUP_FAILED_TEXT } };+ }const read = readSubmission(view, a, u);if (!read.ok) return { errors: read.errors };- for (const id of read.ids) {- if (!(await this.member(id))) return { errors: { people: notMemberText(await this.deps.name(id)) } };- }- return { after: () => this.deps.flow.setDrivers(key, read.drivers, this.deps.flow.by(a, u)) };+ const by = this.deps.flow.by(a, u);+ return {+ after: async () => {+ const s = this.deps.flow.session(key);+ if (!s) return;+ let answer: string | undefined;+ try {+ const refused = await this.deps.flow.setDrivers(key, () => read.drivers, by);+ if (refused) answer = await this.deps.flow.refusalText(refused);+ } catch {+ answer = LOOKUP_FAILED_TEXT;+ }+ if (answer) await this.deps.flow.ephemeral(s, userId, answer);+ },+ };}/** `!access …`, never delivered. All answers are ephemerals to the typer, in the thread. */@@ -98,30 +113,21 @@ export class AccessUi {if (!key || !a) return say(noSessionText());const u = await this.deps.flow.actor(ctx.userId, a.owner);if (accessCommandNeeds(c) === "view") {- if (!can(a, u, "view")) return say(onlyGrantorChangesText(a.owner));+ // An outsider cannot view, and is not answered (as `!access` self-hosted).+ if (!can(a, u, "view")) return;if (c.kind === "usage") return say(ACCESS_USAGE);const post = statePost(key, a, can(a, u, "grant"));return say(post.text, post.blocks);}if (!can(a, u, "grant")) return say(onlyGrantorChangesText(a.owner));const edit = c as Extract<AccessCommand, { kind: "set" | "add" | "remove" }>;- const next = normalize(a.owner, editDrivers(a.drivers, edit));- if (overLimit(next)) return say(tooManyPeopleText());- // Only people this adds are checked: someone already named stays until removed.- const before = a.drivers === "*" ? [] : a.drivers;- for (const id of next === "*" ? [] : next.filter((id) => !before.includes(id))) {- if (!(await this.member(id))) return say(notMemberText(await this.deps.name(id)));- }- await this.deps.flow.setDrivers(key, next, this.deps.flow.by(a, u));+ const refused = await this.deps.flow.setDrivers(key, (current) => editDrivers(current, edit), this.deps.flow.by(a, u));+ if (refused) return say(await this.deps.flow.refusalText(refused));const after = this.deps.flow.access(key) ?? a;const post = statePost(key, after, true);return say(post.text, post.blocks);}- private member(userId: string): Promise<boolean> {- return isWorkspaceMember((method, body) => this.deps.slack(method, body), this.deps.teamId(), userId);- }-private async call(method: string, body: Record<string, unknown>): Promise<void> {try {const r = await this.deps.slack(method, body);diff --git a/services/managed-agents/src/computer/access.ts b/services/managed-agents/src/computer/access.tsindex 3edb091a..ada86f1c 100644--- a/services/managed-agents/src/computer/access.ts+++ b/services/managed-agents/src/computer/access.ts@@ -204,11 +204,14 @@ export function accessCommandNeeds(c: AccessCommand): 'view' | 'grant' | 'admin'return c.kind === 'default' ? 'admin' : 'grant';}-/** The list a `set`, `add` or `remove` asks for, from the current one (`'*'` counts as empty for add and remove). Not normalized. */-export function editDrivers(current: Drivers, c: Extract<AccessCommand, { kind: 'set' | 'add' | 'remove' }>): Drivers {+/**+ * The list a `set`, `add` or `remove` asks for, from the current one. Not normalized. `undefined` when the session is+ * open and the edit is `add` or `remove`: there is no list to change, and making one would lock the thread by surprise.+ */+export function editDrivers(current: Drivers, c: Extract<AccessCommand, { kind: 'set' | 'add' | 'remove' }>): Drivers | undefined {if (c.kind === 'set') return c.drivers;- const list = current === '*' ? [] : current;- return c.kind === 'add' ? [...list, ...c.ids] : list.filter((id) => !c.ids.includes(id));+ if (current === '*') return undefined;+ return c.kind === 'add' ? [...current, ...c.ids] : current.filter((id) => !c.ids.includes(id));}/** The answer to any other form of `!access`. */diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.tsindex 6deda710..b9626883 100644--- a/services/managed-agents/src/computer/durable-object.ts+++ b/services/managed-agents/src/computer/durable-object.ts@@ -94,7 +94,7 @@ import { sizeShape } from "./placement.js";import { DEFAULT_HARNESS, computerHarnesses, harnessOnProfile, helloProfiles, profileHarnesses, takeHarnessPrefix } from "./harnesses.js";import { type SealPurpose, seal, sha256Hex, unseal } from "./crypto.js";import { type DiskReport, diskDecision } from "./disk-growth.js";-import { type Linked, LINK_TIMEOUT_MS, ThreadAccess, findThreadLinks, forwardedLinked, threadRefFor } from "./threads.js";+import { type Linked, LINK_TIMEOUT_MS, LOOKUP_FAILED_TEXT, ThreadAccess, findThreadLinks, forwardedLinked, threadRefFor } from "./threads.js";import { type ComputerInstallation, type ComputerRepository, selectTokenTarget, workspaceDefinition } from "./github.js";import { hostToken } from "./host-token.js";import { failureNotice } from "./failure.js";@@ -150,7 +150,7 @@ import { AccessStore } from "./access-store.js";import { AccessFlow } from "./access-flow.js";import { AccessUi } from "./access-ui.js";import { ACCESS_VIEW, type AccessSubmission } from "./access-views.js";-import { commandAction } from "./access.js";+import { commandAction, driversCommandText } from "./access.js";import { CONNECTION_VIEW, ComputerConnections, type ConnectionRequest, type GrantableConnection } from "./connections.js";import {AGENT_ERRORS,@@ -553,7 +553,9 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {this.secrets = new SecretsStore({sql,encryptionKey: () => env.BLUE_CHANNEL_ENCRYPTION_KEY,- teamId: () => this.setting("slackTeamId") ?? "",+ member: (userId) => this.threads().member(userId),+ // Lazy: `this.roles` is built below.+ instructs: (key, userId) => this.roles.instructs(key, userId),slack: (method, body) => this.slack(method, body),session: (key) => this.runnerSession(key),push: (which) => this.pushSecrets(which),@@ -585,11 +587,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {poolProbe: (token, user) => (this.env.COMPUTERS && this.poolTarget() > 0 ? (this.poolObject().poolProbe(token, user) as Promise<PoolProbeResult>) : null),transaction: (fn) => this.ctx.storage.transactionSync(fn),waitUntil: (task) => ctx.waitUntil(task),- slackUserName: async (userId) => {- const r = await this.slack("users.info", { user: userId });- const u = r.ok ? r.user : undefined;- return u?.profile?.display_name || u?.real_name || u?.profile?.real_name || u?.name || undefined;- },+ slackUserName: (userId) => this.threads().name(userId),connectCodeIndex: {put: (hash, expiresAt) => this.computerObject(connectCodeIndexName(hash)).indexConnectCode(hash, this.accountId(), expiresAt),forget: (hash) => this.computerObject(connectCodeIndexName(hash)).forgetConnectCode(hash),@@ -683,14 +681,12 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {this.roles = new AccessFlow({store: roleStore,slack: (method, body) => this.slack(method, body),- teamId: () => this.setting("slackTeamId") ?? "",+ member: (slackUserId) => this.threads().member(slackUserId),session: (key) => this.runnerSession(key),linkOfSlack: (slackUserId) => this.access.agents.linkOfSlack(slackUserId),isAdmin: (member) => this.api.isAdmin(member),name: (slackUserId) => this.threads().name(slackUserId),- admit: (channelId, threadTs) => this.admit(channelId, threadTs),- // An allowed request's message, as `wakeSession` delivers: a trace of its own.- deliver: (d) => this.deliver({ ...d, trace: this.telemetry.trace({ teamId: this.setting("slackTeamId") ?? "", channelId: d.channelId, userId: d.userId, messageTs: d.messageTs, receivedAt: Date.now() }) }),+ requeue: (job) => this.requeueSlackJob(job),changed: (key, by, from, to) => this.telemetry.accessChanged(key, by, from, to),waitUntil: (work) => ctx.waitUntil(work),});@@ -698,8 +694,6 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {flow: this.roles,store: roleStore,slack: (method, body) => this.slack(method, body),- teamId: () => this.setting("slackTeamId") ?? "",- name: (slackUserId) => this.threads().name(slackUserId),});// A new instance holds no drain: every row an evicted one left `running` goes// back to the queue, synchronously (local SQL; a failure is logged, never thrown:@@ -2033,6 +2027,24 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {return { accepted: true };}+ /**+ * A message back on the queue (work 112: an allowed request's), queued as+ * `acceptSlackEvent` queues one: the row synchronously, in the caller's+ * block; the drain and the alarm off its path. Its working status was+ * withdrawn when it was held, so it has none.+ */+ private requeueSlackJob(job: SlackMessageJob): void {+ const { acked: _acked, ackIndicator: _indicator, ...rest } = job;+ const sql = this.ctx.storage.sql;+ sql.exec("INSERT INTO slack_queue (payload, available_at, thread_key) VALUES (?, ?, ?)", JSON.stringify(rest), Date.now(), `${job.channelId}:${job.threadTs}`);+ sql.exec(+ "INSERT INTO alarms (purpose, at) VALUES ('slack', ?) ON CONFLICT(purpose) DO UPDATE SET at = MIN(at, excluded.at)",+ Date.now() + SLACK_FALLBACK_MS,+ );+ this.ctx.waitUntil(this.drain().catch((error) => console.error(JSON.stringify({ level: "error", event: "computer.slack_drain_failed", message: errorText(error) }))));+ this.ctx.waitUntil(this.armAlarm());+ }+/*** Starts the working status for a message, off the caller's path; `ack.done`* goes on `t` when it settles. The queue row says so (`acked`) and, once@@ -2293,6 +2305,18 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {const text = commandText(job.text);const here = { userId: job.userId, channelId: job.channelId, ...(job.threadTs !== job.messageTs ? { threadTs: job.threadTs } : {}) };const inSession = session?.ownerId ? { session: { key, ownerId: session.ownerId } } : {};+ // `!access` (work 112): the gateway's, in a session or not; never delivered.+ if (commandAction(text) === "access") {+ return this.telemetry.command(t, "access", this.rolesUi.command(text, { ...here, ...(session?.ownerId ? { session: { key } } : {}) }));+ }+ // Work 112: who may instruct an existing session, before every other command, the+ // gateway's own too (they read as `instruct`). Not delivered: held as context, or dropped.+ const roleSession = this.runnerSession(key);+ const gate = roleSession ? await this.roles.message(job, text, roleSession) : undefined;+ if (gate && !gate.deliver) {+ await this.withdrawAcknowledgement(job, sequence);+ return t.emit("message.ignored", { data: { reason: gate.reason } });+ }// `!secret` and `!var` are the gateway's: they never reach the session or its history.const secretCommand = parseSecretCommand(text);if (secretCommand) {@@ -2321,17 +2345,6 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {if (variableCommand) {return this.telemetry.command(t, "variable", this.secrets.variableCommand(variableCommand, { ...here, ...inSession }, text));}- // `!access` (work 112): the gateway's too, in a session or not; never delivered.- if (commandAction(text) === "access") {- return this.telemetry.command(t, "access", this.rolesUi.command(text, { ...here, ...(session?.ownerId ? { session: { key } } : {}) }));- }- // Work 112: who may instruct an existing session. Not delivered: held as context, or dropped.- const roleSession = this.runnerSession(key);- const gate = roleSession ? await this.roles.message(job, text, roleSession) : undefined;- if (gate && !gate.deliver) {- await this.withdrawAcknowledgement(job, sequence);- return t.emit("message.ignored", { data: { reason: gate.reason } });- }// The credit gate, before anything is created or delivered (the working// status was usually started on accept; a refusal resets it).const ackKey = `${job.channelId}:${job.messageTs}`;@@ -2387,7 +2400,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {private threads(): ThreadAccess {const teamId = this.setting("slackTeamId") ?? "";if (this.threadAccess?.teamId !== teamId) {- this.threadAccess = { teamId, access: new ThreadAccess((method, body) => this.slack(method, body)) };+ this.threadAccess = { teamId, access: new ThreadAccess((method, body) => this.slack(method, body), teamId) };}return this.threadAccess.access;}@@ -2727,6 +2740,12 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {await respond("That session is gone; nothing was set.");return {};}+ // Work 112: `!var` in a session's thread is a write to it, from a click as from a message.+ const instructs = key ? await this.roles.instructs(key, userId).catch(() => undefined) : true;+ if (!instructs) {+ await respond(instructs === undefined ? LOOKUP_FAILED_TEXT : driversCommandText("var"));+ return {};+ }await this.secrets.confirmVariable(interaction.actions?.[0]?.value ?? "", {userId,...(channelId ? { channelId } : {}),@@ -2761,7 +2780,9 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {}/** A session that asked for something and is waiting: `text` from `userId` starts its next turn. */- private async wakeSession(session: { channelId: string; threadTs: string }, userId: string, text: string, ts: string): Promise<void> {+ private async wakeSession(session: { key: string; channelId: string; threadTs: string }, userId: string, text: string, ts: string): Promise<void> {+ // Work 112: waking a session is instructing it.+ if (!(await this.roles.instructs(session.key, userId))) return;if (!(await this.admit(session.channelId, session.threadTs))) return;const trace = this.telemetry.trace({ teamId: this.setting("slackTeamId") ?? "", channelId: session.channelId, userId, messageTs: ts, receivedAt: Date.now() });await this.deliver({ channelId: session.channelId, threadTs: session.threadTs, messageTs: ts, userId, text, mentioned: true, trace });@@ -3463,6 +3484,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {/** Slack says a person left, was deactivated or became a guest (work 077): their Claude subscription goes. */async slackMemberLeft(accountId: string, userId: string): Promise<void> {this.bind(accountId);+ this.threads().forget(userId);await this.access.models.memberRemoved(userId);}diff --git a/services/managed-agents/src/computer/secrets-store.ts b/services/managed-agents/src/computer/secrets-store.tsindex 3267c404..dceedad8 100644--- a/services/managed-agents/src/computer/secrets-store.ts+++ b/services/managed-agents/src/computer/secrets-store.ts@@ -34,7 +34,8 @@ import {secretNameProblem,setBlocks,} from "./secrets.js";-import { isWorkspaceMember } from "./slack.js";+import { driversCommandText } from "./access.js";+import { LOOKUP_FAILED_TEXT } from "./threads.js";import { type VariableCommand, VARIABLE_HELP, credentialHint, parseVariableCommand, showValue } from "./variables.js";import type { ApiCaller, ApiReply } from "./sessions-api.js";@@ -78,14 +79,6 @@ export interface SlackResult {ok: boolean;error?: string;ts?: string;- user?: {- team_id?: string;- deleted?: boolean;- is_bot?: boolean;- is_restricted?: boolean;- is_ultra_restricted?: boolean;- is_stranger?: boolean;- };}/** Where a command or click came from. */@@ -100,8 +93,15 @@ export interface SecretContext {export interface SecretsStoreDeps {sql: SqlStorage;encryptionKey: () => string | undefined;- /** The linked Slack workspace's id: organization secrets are for its own full members. */- teamId: () => string;+ /**+ * Whether a person is a full member of the linked Slack workspace: who may+ * set and remove organization secrets (2026-10-11: they are trusted). Not+ * guests, people from other organizations in shared channels, bots or+ * deactivated accounts. Throws when Slack could not be asked.+ */+ member(userId: string): Promise<boolean>;+ /** Whether a person may write to a session (work 112: `can(instruct)`). Throws when Slack could not be asked. */+ instructs(sessionKey: string, userId: string): Promise<boolean>;slack(method: string, body: Record<string, unknown>): Promise<SlackResult>;/** The session a runner key names, if this workspace has its conversation. */session(runnerKey: string): { key: string; ownerId: string; channelId: string; threadTs: string } | undefined;@@ -252,15 +252,6 @@ export class SecretsStore {// ---------------------------------------------------------------- Slack- /**- * Who may set and remove workspace secrets: full members of this Slack- * workspace (2026-10-11: they are trusted). Not guests, people from- * other organizations in shared channels, bots or deactivated accounts.- */- private isMember(userId: string): Promise<boolean> {- return isWorkspaceMember((method, body) => this.deps.slack(method, body), this.deps.teamId(), userId);- }-private async ephemeral(ctx: SecretContext, text: string, blocks?: unknown[]): Promise<void> {if (!ctx.channelId) return;await this.deps.slack("chat.postEphemeral", {@@ -309,7 +300,7 @@ export class SecretsStore {return `\`${name}\` is set in several scopes (${where}); say which: \`!secret rm ${name} <${where.replaceAll(", ", "|")}>\``;}const [scope, owner] = present[0]!;- if (scope === "workspace" && !(await this.isMember(ctx.userId))) return `\`${name}\` is an organization secret; only full members of this Slack workspace can remove it.`;+ if (scope === "workspace" && !(await this.deps.member(ctx.userId))) return `\`${name}\` is an organization secret; only full members of this Slack workspace can remove it.`;this.remove(scope, owner, name, { id: ctx.userId, surface: "slack" });console.log("secret_removed", { scope, name, by: ctx.userId });await this.deps.push(scope === "session" ? { key: owner } : scope === "user" ? { owner } : {});@@ -341,7 +332,14 @@ export class SecretsStore {async confirmVariable(text: string, ctx: SecretContext, respond: (text: string) => Promise<void>): Promise<void> {const cmd = parseVariableCommand(text);if (cmd?.kind !== "set") return;- await respond(await this.variableReply(cmd, ctx, true));+ let reply: string;+ try {+ reply = await this.variableReply(cmd, ctx, true);+ } catch {+ // A button has nobody to retry it but the person: the lookup failed, or the store did.+ reply = LOOKUP_FAILED_TEXT;+ }+ await respond(reply);}private async variableReply(cmd: VariableCommand, ctx: SecretContext, confirmed: true): Promise<string>;@@ -367,7 +365,7 @@ export class SecretsStore {}const scope: SecretScope = cmd.scope ?? (ctx.session ? "session" : "user");if (scope === "session" && !ctx.session) return "Not in a session: add `me` or `org`.";- if (scope === "workspace" && !(await this.isMember(ctx.userId))) return "Only full members of this Slack workspace can set or remove organization variables.";+ if (scope === "workspace" && !(await this.deps.member(ctx.userId))) return "Only full members of this Slack workspace can set or remove organization variables.";const owner = scope === "session" ? ctx.session!.key : scope === "user" ? ctx.userId : "*";const where = scopeLabel(scope, owner, ctx.userId);const existing = cmd.name ? this.meta([[scope, owner]]).find((m) => m.name === cmd.name) : undefined;@@ -402,6 +400,12 @@ export class SecretsStore {const d = decodeButtonId(actionId);if (!d) return;const session = d.k ? this.deps.session(d.k) : undefined;+ let member: boolean;+ try {+ member = await this.deps.member(ctx.userId);+ } catch {+ return this.ephemeral(ctx, LOOKUP_FAILED_TEXT);+ }const meta: ModalData = {...(session ? { k: session.key } : {}),...(ctx.channelId ? { ch: ctx.channelId } : {}),@@ -411,7 +415,7 @@ export class SecretsStore {const view = secretModal(d, meta, {session: !!session,...(session && session.ownerId !== ctx.userId ? { otherOwner: session.ownerId } : {}),- member: await this.isMember(ctx.userId),+ member,});const r = await this.deps.slack("views.open", { trigger_id: triggerId, view });if (!r.ok) console.error("secret_modal_failed", { error: r.error });@@ -427,7 +431,13 @@ export class SecretsStore {if ("errors" in s) return { errors: s.errors };const session = s.meta.k ? this.deps.session(s.meta.k) : undefined;if (s.scope === "session" && !session) return { errors: { scope: "This session no longer exists; pick another scope." } };- if (s.scope === "workspace" && !(await this.isMember(userId))) return { errors: { scope: "Only full members of this Slack workspace can set organization secrets." } };+ try {+ // A secret set from a session's thread is a write to that session (work 112), as `!secret` there is.+ if (session && !(await this.deps.instructs(session.key, userId))) return { errors: { scope: driversCommandText("secret") } };+ if (s.scope === "workspace" && !(await this.deps.member(userId))) return { errors: { scope: "Only full members of this Slack workspace can set organization secrets." } };+ } catch {+ return { errors: { scope: LOOKUP_FAILED_TEXT } };+ }const owner = s.scope === "session" ? session!.key : s.scope === "user" ? userId : "*";try {await this.put(s.scope, owner, s.name, s.value, s.file, { id: userId, surface: "slack" });diff --git a/services/managed-agents/src/computer/slack.ts b/services/managed-agents/src/computer/slack.tsindex dbbf1887..011d74ba 100644--- a/services/managed-agents/src/computer/slack.ts+++ b/services/managed-agents/src/computer/slack.ts@@ -19,6 +19,8 @@ export interface SlackMessageJob {/** Messages forwarded in this one: Slack sends them in `attachments`, not `text`. */forwarded?: ForwardedMessage[];mentioned: boolean;+ /** Mentioned only mid-message, not at its start (work 112: such a mention asks nothing of the app). */+ mentionedInline?: boolean;/** Raw text @mentions someone other than this app: most likely not addressed to it. */mentionsOthers?: boolean;channelType?: string;@@ -236,9 +238,12 @@ export function parseSlackEnvelope(payload: unknown, now = Date.now()): ParsedSlexport function normalizeJob(job: SlackMessageJob, botUserId: string): SlackMessageJob | null {const mention = `<@${botUserId}>`;const raw = botUserId ? job.text.replaceAll(mention, "") : job.text;+ const mentioned = job.mentioned || (botUserId !== "" && job.text.includes(mention));+ const leading = botUserId !== "" && job.text.trimStart().startsWith(mention);const normalized: SlackMessageJob = {...job,- mentioned: job.mentioned || (botUserId !== "" && job.text.includes(mention)),+ mentioned,+ ...(mentioned && !leading ? { mentionedInline: true } : {}),mentionsOthers: /<@[UW]/.test(raw),text: decodeSlack(raw).trim(),};@@ -303,27 +308,6 @@ export interface SlackResult {};}-/**- * A full member of the linked workspace (`teamId`): not deleted, a bot, a- * guest (`is_restricted`, `is_ultra_restricted`) or someone from another- * organization (`is_stranger`, another `team_id`). A failed lookup is false.- * Organization secrets (secrets-store.ts) and session roles (access-flow.ts).- */-export async function isWorkspaceMember(- slack: (method: string, body: Record<string, unknown>) => Promise<Pick<SlackResult, "ok" | "user">>,- teamId: string,- userId: string,-): Promise<boolean> {- try {- const r = await slack("users.info", { user: userId });- const u = r.ok ? r.user : undefined;- if (!u || u.deleted || u.is_bot || u.is_restricted || u.is_ultra_restricted || u.is_stranger) return false;- return !u.team_id || u.team_id === teamId;- } catch {- return false;- }-}-/** Errors that mean the bot token is dead for good: the app was uninstalled or the token revoked. */const DEAD_TOKEN_ERRORS = new Set(["token_revoked", "invalid_auth", "account_inactive", "token_expired"]);diff --git a/services/managed-agents/src/computer/threads.ts b/services/managed-agents/src/computer/threads.tsindex 1593b7c1..0c6812f0 100644--- a/services/managed-agents/src/computer/threads.ts+++ b/services/managed-agents/src/computer/threads.ts@@ -181,12 +181,17 @@ export function stripAttribution(text: string): string {class Refused extends Error {}+/** The answer to a click or a modal when `member` could not ask Slack: a click has nobody to retry it but the person. */+export const LOOKUP_FAILED_TEXT = "Slack could not be asked about the people involved just now; try again.";+interface User {at: number;name: string;- /** Deleted, or the lookup failed: never passes the check. */+ /** Deleted: never passes the check. */unknown: boolean;guest: boolean;+ /** A full member of this workspace (work 112): not deleted, a bot, a guest or from another organization. */+ member: boolean;}interface Channel {@@ -198,16 +203,20 @@ interface Channel {}/**- * One per Durable Object. Caches the workspace's own host and team- * (auth.test) and people (users.info, ten minutes); never a channel's- * state (a channel can go private, or lose the app, at any moment) and- * never message text.+ * One per Durable Object and linked workspace (`teamId`). Caches the+ * workspace's own host and team (auth.test) and people (users.info, ten+ * minutes): the one lookup of a person, for names, this check and+ * membership. Never a channel's state (a channel can go private, or lose+ * the app, at any moment) and never message text.*/export class ThreadAccess {private own?: { host: string; teamId: string };private readonly users = new Map<string, User>();- constructor(private readonly slack: Slack) {}+ constructor(+ private readonly slack: Slack,+ private readonly teamId: string,+ ) {}/** Every thread link in a message, read or refused. Never throws. */async resolve(text: string, audience: ThreadAudience): Promise<Linked[]> {@@ -267,6 +276,20 @@ export class ThreadAccess {}}+ /**+ * Whether a person is a full member of the linked workspace (work 112:+ * roles, organization secrets). Throws when Slack could not be asked: a+ * failed lookup is not an answer.+ */+ async member(id: string): Promise<boolean> {+ return (await this.user(id)).member;+ }++ /** Drop what is cached about a person: they left, or changed (Slack's team_leave, user_change). */+ forget(id: string): void {+ this.users.delete(id);+ }+/** D6, in order. Throws `Refused` (or Slack's error) unless the thread may be read here. */private async check(ref: ThreadRef, audience: ThreadAudience): Promise<{ url: string; channel: Channel }> {// 1. This workspace.@@ -280,8 +303,8 @@ export class ThreadAccess {// 3. The people it is for.let members: Set<string> | undefined;for (const id of new Set([audience.owner, audience.poster].filter((p): p is string => !!p))) {- const person = await this.user(id);- if (person.unknown) throw new Refused("could not confirm who asked can see that channel");+ const person = await this.user(id).catch(() => undefined);+ if (!person || person.unknown) throw new Refused("could not confirm who asked can see that channel");if (person.guest && !(members ??= await this.members(ref.channel, audience.deadline)).has(id)) throw new Refused("a guest who asked is not in that channel");}// 4. Not into a conversation shared with another organization.@@ -315,18 +338,20 @@ export class ThreadAccess {};}- /** users.info, cached. A failed lookup is not cached and counts as unknown: the check fails closed. */+ /** users.info, cached. A failed lookup throws and is not cached: each caller decides what failing means. */private async user(id: string): Promise<User> {const cached = this.users.get(id);if (cached && Date.now() - cached.at < USERS_TTL_MS) return cached;const r = await this.slack("users.info", { user: id });const u = r.ok ? r.user : undefined;- if (!u) return { at: Date.now(), name: id, unknown: true, guest: true };+ if (!u) throw new Error(`users.info failed: ${r.error ?? "no user"}`);+ const guest = !!(u.is_restricted || u.is_ultra_restricted || u.is_stranger);const user: User = {at: Date.now(),name: u.profile?.display_name || u.real_name || u.profile?.real_name || u.name || id,unknown: !!u.deleted,- guest: !!(u.is_restricted || u.is_ultra_restricted || u.is_stranger),+ guest,+ member: !u.deleted && !u.is_bot && !guest && (!u.team_id || u.team_id === this.teamId),};this.users.set(id, user);return user;diff --git a/services/managed-agents/test/computer-access-do.test.ts b/services/managed-agents/test/computer-access-do.test.tsindex 14ce3eb5..140fbee5 100644--- a/services/managed-agents/test/computer-access-do.test.ts+++ b/services/managed-agents/test/computer-access-do.test.ts@@ -1,7 +1,7 @@import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";-import { onlyMembersText, stateText, stoppedText } from "../src/computer/access.js";+import { driversCommandText, onlyMembersText, stateText, stoppedText } from "../src/computer/access.js";import type { ComputerDurableObject } from "../src/computer/durable-object.js";import { hostToken } from "../src/computer/host-token.js";import { SLACK_BOT_TOKEN } from "./fixtures/computer-fakes.mjs";@@ -132,6 +132,22 @@ describe("computer session roles (work 112)", () => {s.socket.close();});+ it("in a session's thread the gateway's own commands need someone who can drive it", async () => {+ const s = await withSession("org_roles_commands", "T0ROLES4");+ await s.say("UADA", "!access owner");+ await until(s.drivers, (d) => d === "[]", "restricted");+ const asked = [await s.say("UGRACE", "!var X=1"), await s.say("UGRACE", "!secret add TOKEN")];+ const refusals = await until(+ async () => (await s.calls()).filter((c) => c.method === "chat.postEphemeral" && c.body.user === "UGRACE").map((c) => c.body.text),+ (all) => all.length === 2,+ "two refusals",+ );+ expect(refusals).toEqual([driversCommandText("var"), driversCommandText("secret")]);+ expect((await s.calls()).filter((c) => c.method === "views.open")).toEqual([]);+ expect(s.frames.filter((f) => f.t === "deliver" && asked.includes(f.msg.ts))).toEqual([]);+ s.socket.close();+ });+it("a spawned session starts with its parent's drivers", async () => {const s = await withSession("org_roles_spawn", "T0ROLES3");// (The fake's ids are too short for `!access @U…`, which reads Slack's.)diff --git a/services/managed-agents/test/computer-access-flow.test.ts b/services/managed-agents/test/computer-access-flow.test.tsindex 93489d3a..ade7746e 100644--- a/services/managed-agents/test/computer-access-flow.test.ts+++ b/services/managed-agents/test/computer-access-flow.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {+ ACCESS_USAGE,driversCommandText,grantedText,notAskedText,@@ -12,9 +13,12 @@ import {requestSentText,requestText,stoppedText,+ type Drivers,} from "../src/computer/access.js";import { declinedPost, encodeAccessId } from "../src/computer/access-views.js";-import { A, ADMIN, B, GUEST, KEY, OWNER, SESSION, STRANGER, accessHarness, send } from "./fixtures/computer-access.js";+import { normalizeJob } from "../src/computer/slack.js";+import { LOOKUP_FAILED_TEXT } from "../src/computer/threads.js";+import { A, ADMIN, B, GUEST, KEY, OWNER, SESSION, STRANGER, accessHarness, drain, send } from "./fixtures/computer-access.js";const ctx = (h: ReturnType<typeof accessHarness>) => h.store.held(KEY);const owner = { id: OWNER, admin: false };@@ -56,12 +60,55 @@ describe("session roles: messages (work 112)", () => {expect(ctx(h).map((m) => m.text)).toEqual(["please fix it", "hello?"]);});- it("a request whose post failed is not recorded and answers nothing", async () => {+ it("a request whose post failed is not recorded and answers nothing; the next mention asks again", async () => {const h = accessHarness([]);h.answers.set("chat.postMessage", { ok: false, error: "not_in_channel" });await send(h, h.job(A, "please", { mentioned: true }));expect(h.store.request(KEY, A)).toBeUndefined();expect(h.ephemerals(A)).toEqual([]);+ h.answers.delete("chat.postMessage");+ await send(h, h.job(A, "please?", { mentioned: true }));+ expect(h.store.request(KEY, A)).toMatchObject({ state: "open", messageTs: expect.stringMatching(/\.1$/) });+ expect(h.ephemerals(A)).toEqual([requestSentText(OWNER)]);+ });++ it("the rows are guards: a retried message is held once and asks once", async () => {+ const h = accessHarness([]);+ const job = h.job(A, "please fix it", { mentioned: true, messageTs: "250.1" });+ await send(h, job);+ await send(h, job);+ expect(ctx(h)).toHaveLength(1);+ expect(h.of("chat.postMessage")).toHaveLength(1);+ expect(h.ephemerals(A)).toEqual([requestSentText(OWNER)]);+ });++ it("only a mention at the message's start asks to drive; one mid-message is context only", async () => {+ const h = accessHarness([]);+ const inline = normalizeJob(h.job(A, "ask <@UBOT> later", { mentioned: true }), "UBOT")!;+ expect(inline).toMatchObject({ mentioned: true, mentionedInline: true });+ expect(normalizeJob(h.job(A, " <@UBOT> now"), "UBOT")).toMatchObject({ mentioned: true });+ expect(normalizeJob(h.job(A, " <@UBOT> now"), "UBOT")!.mentionedInline).toBeUndefined();+ expect(await send(h, inline)).toEqual({ deliver: false, reason: "held" });+ expect(h.of("chat.postMessage")).toEqual([]);+ expect(h.ephemerals(A)).toEqual([]);+ await send(h, normalizeJob(h.job(A, "<@UBOT> now"), "UBOT")!);+ expect(h.posts()).toEqual([requestText(OWNER, A)]);+ });++ it("one lookup of a person, cached; a failed one throws on a message (the queue retries) and says try again on a click", async () => {+ const h = accessHarness([]);+ h.answers.set("users.info", { ok: false, error: "ratelimited" });+ await expect(send(h, h.job(A, "note"))).rejects.toThrow();+ expect(ctx(h)).toEqual([]);+ await h.flow.answer(KEY, A, () => "x");+ expect(h.ephemerals(A)).toEqual([LOOKUP_FAILED_TEXT]);+ expect(await h.flow.stop(SESSION, A, () => true)).toBe(false);+ h.answers.delete("users.info");+ await send(h, h.job(A, "note"));+ await send(h, h.job(A, "another"));+ expect(ctx(h)).toHaveLength(2);+ // Three failures, none kept; then one answer kept for both messages.+ expect(h.of("users.info")).toHaveLength(4);});it("held context rides the next driver message, oldest first with names, and is deleted after", async () => {@@ -125,6 +172,13 @@ describe("session roles: messages (work 112)", () => {expect(await send(h, h.job(GUEST, "!help"))).toEqual({ deliver: false, reason: "command_refused" });expect(h.ephemerals(GUEST)).toEqual([]);});++ it("the gateway's own commands read as instruct: S8 for a participant's `!secret`, through for a driver", async () => {+ const h = accessHarness([B]);+ expect(await send(h, h.job(A, "!secret set TOKEN"))).toEqual({ deliver: false, reason: "command_refused" });+ expect(h.ephemerals(A)).toEqual([driversCommandText("secret")]);+ expect(await h.flow.message(h.job(B, "!var X=1"), "!var X=1", SESSION)).toEqual({ deliver: true, role: "driver", context: false });+ });});describe("session roles: requests to drive (work 112)", () => {@@ -145,23 +199,50 @@ describe("session roles: requests to drive (work 112)", () => {expect(h.of("chat.update")).toEqual([]);});- it("Allow by the owner adds the driver, edits the request to S3 and delivers the held message once, not as context", async () => {+ it("Allow by the owner adds the driver, edits the request to S3 and puts the held message back on the queue, where it runs once as theirs", async () => {const h = await requested();await send(h, h.job(B, "unrelated note"));await h.flow.answerRequest(KEY, "allow", A, OWNER);expect(h.store.drivers(KEY)).toEqual([A]);expect(h.store.request(KEY, A)?.state).toBe("closed");expect(h.of("chat.update")).toEqual([{ channel: "C1", ts: "300.1", text: grantedText(owner, [A], OWNER), blocks: [] }]);+ expect(h.delivered).toEqual([]);+ expect(h.requeued).toMatchObject([{ userId: A, text: "please fix it", messageTs: "250.1", mentioned: true }]);+ // The request's own message is no longer context; the queue gates it again.+ expect(ctx(h).map((m) => m.text)).toEqual(["unrelated note"]);+ expect(await drain(h)).toEqual([{ deliver: true, role: "driver", context: true }]);expect(h.delivered).toHaveLength(1);- expect(h.delivered[0]).toMatchObject({ userId: A, text: "please fix it", messageTs: "250.1", role: "driver", mentioned: true });- // The other participant's note rides along; the request's own message does not.+ expect(h.delivered[0]).toMatchObject({ userId: A, text: "please fix it", messageTs: "250.1", role: "driver" });+ // The other participant's note rides along, once.expect(h.delivered[0]!.linked).toMatchObject([{ context: true, messages: [{ text: "unrelated note" }] }]);expect(ctx(h)).toEqual([]);// Step 4 handled A: no second S3 in the thread.expect(h.posts()).toEqual([requestText(OWNER, A)]);// A second click on the same request does nothing.await h.flow.answerRequest(KEY, "allow", A, OWNER);- expect(h.delivered).toHaveLength(1);+ expect(h.requeued).toEqual([]);+ });++ it("Allow when everyone drives already answers the request and runs its message, without a special case", async () => {+ const h = await requested();+ h.store.writeDrivers(KEY, "*");+ await h.flow.answerRequest(KEY, "allow", A, OWNER);+ expect(h.store.request(KEY, A)?.state).toBe("closed");+ expect(h.requeued).toHaveLength(1);+ expect(h.of("chat.update")).toHaveLength(1);+ expect(h.changes).toEqual([]);+ });++ it("Allow for someone who is no longer a member tells the clicker and leaves the request open", async () => {+ const h = accessHarness([]);+ // Held while a member (the lookup is cached ten minutes); a guest by the time of the click.+ await h.flow.message(h.job(GUEST, "x", { mentioned: true }), "x", SESSION);+ expect(h.posts()).toEqual([]);+ h.store.addRequest(KEY, GUEST, JSON.stringify(h.job(GUEST, "x")));+ await h.flow.answerRequest(KEY, "allow", GUEST, OWNER);+ expect(h.ephemerals(OWNER)).toEqual([`name-${GUEST} can’t be added: only full members of this workspace can drive.`]);+ expect(h.store.request(KEY, GUEST)?.state).toBe("open");+ expect(h.store.drivers(KEY)).toEqual([]);});it("Allow by an admin who is not the owner says so", async () => {@@ -185,32 +266,24 @@ describe("session roles: requests to drive (work 112)", () => {it("opening the session answers open requests and delivers their messages", async () => {const h = await requested();- await h.flow.setDrivers(KEY, "*", owner);+ await h.flow.setDrivers(KEY, () => "*", owner);expect(h.store.request(KEY, A)?.state).toBe("closed");- expect(h.delivered).toHaveLength(1);+ expect(h.requeued).toHaveLength(1);expect(h.posts()).toEqual([requestText(OWNER, A), openedText(owner, OWNER)]);});-- it("an allowed message waits for credits like any other", async () => {- const h = await requested();- h.admitted = false;- await h.flow.answerRequest(KEY, "allow", A, OWNER);- expect(h.store.drivers(KEY)).toEqual([A]);- expect(h.delivered).toEqual([]);- });});describe("session roles: setDrivers (work 112)", () => {it("the same value does nothing at all", async () => {const h = accessHarness([A]);- await h.flow.setDrivers(KEY, [A, OWNER, A], owner);+ await h.flow.setDrivers(KEY, () => [A, OWNER, A], owner);expect(h.calls).toEqual([]);expect(h.changes).toEqual([]);});it("restricting writes, adds the marker and posts nothing", async () => {const h = accessHarness("*");- await h.flow.setDrivers(KEY, [B, A, OWNER], owner);+ await h.flow.setDrivers(KEY, () => [B, A, OWNER], owner);expect(h.store.drivers(KEY)).toEqual([A, B]);expect(h.of("reactions.add")).toEqual([{ channel: "C1", timestamp: "100.1", name: "lock" }]);expect(h.posts()).toEqual([]);@@ -219,28 +292,51 @@ describe("session roles: setDrivers (work 112)", () => {it("opening a restricted session removes the marker and posts S3b", async () => {const h = accessHarness([]);- await h.flow.setDrivers(KEY, "*", owner);+ await h.flow.setDrivers(KEY, () => "*", owner);expect(h.of("reactions.remove")).toEqual([{ channel: "C1", timestamp: "100.1", name: "lock" }]);expect(h.posts()).toEqual([openedText(owner, OWNER)]);});it("adding people to a list posts S3 once naming them; removing posts nothing; the marker stays", async () => {const h = accessHarness([A]);- await h.flow.setDrivers(KEY, [A, B, ADMIN], owner);+ await h.flow.setDrivers(KEY, () => [A, B, ADMIN], owner);expect(h.posts()).toEqual([grantedText(owner, [ADMIN, B], OWNER)]);- await h.flow.setDrivers(KEY, [], owner);+ await h.flow.setDrivers(KEY, () => [], owner);expect(h.posts()).toHaveLength(1);expect(h.of("reactions.add")).toEqual([]);expect(h.of("reactions.remove")).toEqual([]);expect(h.changes.map((c) => c.to)).toEqual([JSON.stringify([A, ADMIN, B].sort()), "[]"]);});+ it("refusals come back for the caller to word: not a member, too many, a form that does not apply, no session", async () => {+ const h = accessHarness([A]);+ expect(await h.flow.setDrivers(KEY, (d) => (d === "*" ? d : [...d, GUEST]), owner)).toEqual({ refused: "member", id: GUEST });+ expect(await h.flow.setDrivers(KEY, () => [STRANGER], owner)).toEqual({ refused: "member", id: STRANGER });+ const many = Array.from({ length: 51 }, (_, i) => `U${String(i).padStart(7, "0")}`);+ expect(await h.flow.setDrivers(KEY, () => many, owner)).toEqual({ refused: "limit" });+ expect(await h.flow.setDrivers(KEY, () => undefined, owner)).toEqual({ refused: "usage" });+ expect(await h.flow.refusalText({ refused: "usage" })).toBe(ACCESS_USAGE);+ expect(await h.flow.setDrivers("T1:C9:1.1", () => "*", owner)).toEqual({ refused: "gone" });+ expect(h.store.drivers(KEY)).toEqual([A]);+ expect(h.changes).toEqual([]);+ // Too many is refused before anyone is looked up.+ expect(h.of("users.info").map((b) => b.user)).toEqual([GUEST, STRANGER]);+ });++ it("only people it adds are looked up, together, and an edit made meanwhile is not lost", async () => {+ const h = accessHarness([A]);+ const add = (id: string) => (d: Drivers) => (d === "*" ? undefined : [...d, id]);+ await Promise.all([h.flow.setDrivers(KEY, add(B), owner), h.flow.setDrivers(KEY, add(ADMIN), owner)]);+ expect(h.store.drivers(KEY)).toEqual([ADMIN, A, B].sort());+ expect(h.of("users.info").map((b) => b.user).sort()).toEqual([ADMIN, B].sort());+ });+it("a marker that is already there (or a refused one) does not fail the change", async () => {const h = accessHarness("*");h.answers.set("reactions.add", { ok: false, error: "already_reacted" });- await h.flow.setDrivers(KEY, [], owner);+ await h.flow.setDrivers(KEY, () => [], owner);h.answers.set("reactions.remove", { ok: false, error: "missing_scope" });- await h.flow.setDrivers(KEY, "*", owner);+ await h.flow.setDrivers(KEY, () => "*", owner);expect(h.store.drivers(KEY)).toBe("*");expect(h.changes).toHaveLength(2);});diff --git a/services/managed-agents/test/computer-access-store.test.ts b/services/managed-agents/test/computer-access-store.test.tsindex ca5a9849..26e7b843 100644--- a/services/managed-agents/test/computer-access-store.test.ts+++ b/services/managed-agents/test/computer-access-store.test.ts@@ -49,12 +49,25 @@ describe("session roles: the store (work 112)", () => {expect(s.held("k", now).map((m) => m.ts)).toEqual(["t0"]);});+ it("context: a message is held once, however often its job runs", () => {+ const { store: s } = store();+ const m = { userId: "U2", ts: "1.1", text: "hi", files: [] };+ expect(s.hold("k", m, 1)).toBe(true);+ expect(s.hold("k", m, 2)).toBe(false);+ expect(s.hold("k2", m, 2)).toBe(true);+ expect(s.held("k", 2)).toHaveLength(1);+ });+it("requests: one per person, closed once", () => {const { store: s } = store();- s.addRequest("k", "U2", "1.1", "{}", 1);- s.addRequest("k", "U2", "2.2", "{}", 2);- s.addRequest("k", "U3", "3.3", "{}", 3);- expect(s.openRequests("k").map((r) => [r.userId, r.messageTs])).toEqual([["U2", "1.1"], ["U3", "3.3"]]);+ expect(s.addRequest("k", "U2", "{}", 1)).toBe(true);+ expect(s.addRequest("k", "U2", "{}", 2)).toBe(false);+ expect(s.addRequest("k", "U3", "{}", 3)).toBe(true);+ s.postedRequest("k", "U2", "1.1");+ expect(s.openRequests("k").map((r) => [r.userId, r.messageTs])).toEqual([["U2", "1.1"], ["U3", ""]]);+ s.deleteRequest("k", "U3");+ expect(s.request("k", "U3")).toBeUndefined();+ expect(s.addRequest("k", "U3", "{}", 4)).toBe(true);expect(s.closeRequest("k", "U2")).toBe(true);expect(s.closeRequest("k", "U2")).toBe(false);expect(s.request("k", "U2")?.state).toBe("closed");diff --git a/services/managed-agents/test/computer-access-ui.test.ts b/services/managed-agents/test/computer-access-ui.test.tsindex ac023bf6..a7ae99b2 100644--- a/services/managed-agents/test/computer-access-ui.test.ts+++ b/services/managed-agents/test/computer-access-ui.test.ts@@ -12,6 +12,7 @@ import {tooManyPeopleText,} from "../src/computer/access.js";import { ACCESS_VIEW, encodeAccessId } from "../src/computer/access-views.js";+import { LOOKUP_FAILED_TEXT } from "../src/computer/threads.js";import { A, ADMIN, B, GUEST, KEY, OWNER, accessHarness } from "./fixtures/computer-access.js";const where = (userId: string) => ({ userId, channelId: "C1", threadTs: "100.1" });@@ -27,9 +28,10 @@ describe("session roles: !access (work 112)", () => {expect(participant).toMatchObject({ user: B, thread_ts: "100.1", text: stateText({ owner: OWNER, drivers: [A] }) });expect(blocksOf(participant).map((b) => b.type)).toEqual(["section"]);expect(blocksOf(own)[1]!.elements![0]!.action_id).toBe(encodeAccessId(KEY, "open"));- // An outsider cannot view.+ // An outsider cannot view, and gets no answer, as for any view command.await h.ui.command("!access", inSession(GUEST));- expect(h.ephemerals(GUEST)).toEqual([onlyGrantorChangesText(OWNER)]);+ expect(h.ephemerals(GUEST)).toEqual([]);+ expect(h.store.drivers(KEY)).toEqual([A]);});it("open, owner, a list, add and remove change drivers through setDrivers and answer S10", async () => {@@ -65,6 +67,13 @@ describe("session roles: !access (work 112)", () => {expect(h.store.drivers(KEY)).toEqual([A]);});+ it("add or remove when everyone drives answers the usage", async () => {+ const h = accessHarness("*");+ await h.ui.command(`!access add @${A}`, inSession(OWNER));+ expect(h.ephemerals(OWNER)).toEqual([ACCESS_USAGE]);+ expect(h.store.drivers(KEY)).toBe("*");+ });+it("more than 50 people are refused", async () => {const h = accessHarness([]);const many = Array.from({ length: 51 }, (_, i) => `@U${String(i).padStart(7, "0")}`).join(" ");@@ -127,12 +136,15 @@ describe("session roles: the modal (work 112)", () => {expect(h.ephemerals(B)).toHaveLength(1);});- it("Save re-checks grant, refuses nobody and non-members, then sets drivers", async () => {+ it("Save re-checks grant and refuses nobody in the modal; setDrivers refuses a non-member after it closes", async () => {const h = accessHarness("*");expect(await h.ui.submit(submission("owner"), A)).toEqual({ errors: { who: onlyGrantorChangesText(OWNER) } });expect(await h.ui.submit(submission("people", [OWNER]), OWNER)).toEqual({ errors: { people: pickSomeoneText() } });- expect(await h.ui.submit(submission("people", [A, GUEST]), OWNER)).toEqual({ errors: { people: notMemberText(`name-${GUEST}`) } });expect(await h.ui.submit(submission("people", [A], "T1:C1:9.9"), OWNER)).toEqual({ errors: { who: noSessionText() } });+ const guest = await h.ui.submit(submission("people", [A, GUEST]), OWNER);+ expect(guest.errors).toBeUndefined();+ await guest.after!();+ expect(h.ephemerals(OWNER)).toEqual([notMemberText(`name-${GUEST}`)]);expect(h.store.drivers(KEY)).toBe("*");const ok = await h.ui.submit(submission("people", [B, A, OWNER]), OWNER);expect(ok.errors).toBeUndefined();@@ -141,4 +153,11 @@ describe("session roles: the modal (work 112)", () => {// Nothing else is posted for a restriction.expect(h.posts()).toEqual([]);});++ it("a failed lookup of the person saving says try again and changes nothing", async () => {+ const h = accessHarness("*");+ h.answers.set("users.info", { ok: false, error: "ratelimited" });+ expect(await h.ui.submit(submission("owner"), ADMIN)).toEqual({ errors: { who: LOOKUP_FAILED_TEXT } });+ expect(h.store.drivers(KEY)).toBe("*");+ });});diff --git a/services/managed-agents/test/computer-secrets.test.ts b/services/managed-agents/test/computer-secrets.test.tsindex defcfc4d..c1489bab 100644--- a/services/managed-agents/test/computer-secrets.test.ts+++ b/services/managed-agents/test/computer-secrets.test.ts@@ -5,6 +5,8 @@ import { SecretsStore } from "../src/computer/secrets-store.js";import { credentialHint, parseVariableCommand } from "../src/computer/variables.js";import { secretNameProblem } from "../src/computer/secrets.js";import type { SlackResult } from "../src/computer/slack.js";+import { driversCommandText } from "../src/computer/access.js";+import { LOOKUP_FAILED_TEXT, ThreadAccess } from "../src/computer/threads.js";import { sqlStorage } from "./fixtures/computer-sql.js";const KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";@@ -15,25 +17,33 @@ let pushes: Array<{ key?: string; owner?: string }>;let woken: Array<{ key: string; userId: string; text: string }>;let guests: Set<string>;let s: SecretsStore;+/** Who may write to SESSION (work 112); undefined: everyone. */+let drivers: string[] | undefined;beforeEach(() => {calls = [];pushes = [];woken = [];+ drivers = undefined;guests = new Set(["U_GUEST", "U_EXTERNAL"]);+ const slack = async (method: string, body: Record<string, unknown>): Promise<SlackResult> => {+ calls.push({ method, body });+ if (method === "users.info") {+ const user = String(body.user);+ if (user === "U_DOWN") return { ok: false, error: "ratelimited" };+ if (user === "U_EXTERNAL") return { ok: true, user: { team_id: "T_OTHER" } };+ return { ok: true, user: { team_id: "T1", is_restricted: guests.has(user) } };+ }+ return { ok: true, ts: "200.1" };+ };+ // The Durable Object's one lookup of a person (threads.ts).+ const people = new ThreadAccess(slack, "T1");s = new SecretsStore({sql: sqlStorage(),encryptionKey: () => KEY,- teamId: () => "T1",- slack: async (method, body): Promise<SlackResult> => {- calls.push({ method, body });- if (method === "users.info") {- const user = String(body.user);- if (user === "U_EXTERNAL") return { ok: true, user: { team_id: "T_OTHER" } };- return { ok: true, user: { team_id: "T1", is_restricted: guests.has(user) } };- }- return { ok: true, ts: "200.1" };- },+ member: (userId) => people.member(userId),+ instructs: async (_key, userId) => !drivers || drivers.includes(userId),+ slack,session: (key) => (key === SESSION.key ? SESSION : undefined),push: async (which) => void pushes.push(which),wake: async (session, userId, text) => void woken.push({ key: session.key, userId, text }),@@ -135,6 +145,15 @@ describe("computer session secrets (ported from dash-cal)", () => {expect(woken).toEqual([{ key: SESSION.key, userId: "U_OWNER", text: expect.stringMatching(/^Secret \$GCP_SA is set/) }]);await expect(s.request(SESSION.key, { name: "PATH", reason: "x" })).rejects.toThrow(/reserved/);});++ it("from a session's thread the modal needs someone who can drive it; a failed lookup says try again (work 112)", async () => {+ drivers = ["U_OWNER"];+ expect(await s.submit(submission("TOKEN", "v", "user"), "U_MEMBER")).toEqual({ errors: { scope: driversCommandText("secret") } });+ expect((await s.submit(submission("TOKEN", "v", "user"), "U_OWNER")).errors).toBeUndefined();+ // Outside a session the person's own rules: a member sets an organization secret.+ expect((await s.submit(submission("ORG", "v", "workspace", { ch: "C1" }), "U_MEMBER")).errors).toBeUndefined();+ expect(await s.submit(submission("ORG", "v", "workspace", { ch: "C1" }), "U_DOWN")).toEqual({ errors: { scope: LOOKUP_FAILED_TEXT } });+ });});diff --git a/services/managed-agents/test/computer-units.test.ts b/services/managed-agents/test/computer-units.test.tsindex 0b47d013..91bba792 100644--- a/services/managed-agents/test/computer-units.test.ts+++ b/services/managed-agents/test/computer-units.test.ts@@ -633,7 +633,7 @@ describe("thread links (work 049 L3)", () => {}return { ok: false, error: "unexpected" };});- const access = new ThreadAccess(slack as never);+ const access = new ThreadAccess(slack as never, "T0ACME");const ref = { url: "u", host: "acme.slack.com", channel: "C0PUB", ts: "1700000001.000100" };const slow = await access.read(ref, { owner: "U1", destination: "C0PUB", deadline: Date.now() + 50 });expect(slow).toMatchObject({ ok: false, reason: "reading it took too long; ask again to retry" });@@ -654,7 +654,7 @@ describe("thread links (work 049 L3)", () => {}return { ok: false, error: "unexpected" };});- const access = new ThreadAccess(slack as never);+ const access = new ThreadAccess(slack as never, "T0ACME");const linked = await access.read({ url: "u", host: "acme.slack.com", channel: "C0PUB", ts: "1700000001.000205", threadTs: "1700000001.000100" },{ owner: "U1", destination: "C0PUB" },@@ -685,7 +685,7 @@ describe("thread links (work 049 L3)", () => {};return { ok: false, error: "unexpected" };});- const access = new ThreadAccess(slack as never);+ const access = new ThreadAccess(slack as never, "T0ACME");const ref = { url: "", channel: "C0PUB", ts: "1700000001.000300", threadTs: "1700000001.000100" };const linked = await access.read(ref, { owner: "U1", destination: "C0PUB" }, ref.ts);if (!linked.ok) throw new Error(linked.reason);diff --git a/services/managed-agents/test/fixtures/computer-access.ts b/services/managed-agents/test/fixtures/computer-access.tsindex 4a84235a..1ac74148 100644--- a/services/managed-agents/test/fixtures/computer-access.ts+++ b/services/managed-agents/test/fixtures/computer-access.ts@@ -3,6 +3,7 @@ import { AccessFlow, type AccessDispatch } from "../../src/computer/access-flow.import { AccessStore } from "../../src/computer/access-store.js";import { AccessUi } from "../../src/computer/access-ui.js";import type { SlackMessageJob, SlackResult } from "../../src/computer/slack.js";+import { ThreadAccess } from "../../src/computer/threads.js";import { sqlStorage } from "./computer-sql.js";/** People in the fake workspace: ids as Slack's (`!access` reads `@U…` with at least 7 characters). */@@ -16,7 +17,7 @@ export const ADMIN = "UADMIN01";export const KEY = "T1:C1:100.1";export const SESSION = { key: KEY, ownerId: OWNER, channelId: "C1", threadTs: "100.1" };-/** AccessFlow and AccessUi over node:sqlite, a fake Slack and a recording delivery. */+/** AccessFlow and AccessUi over node:sqlite, a fake Slack, the one lookup of people, and a recording queue and delivery. */export function accessHarness(drivers: Drivers = "*") {const sql = sqlStorage();sql.exec(`@@ -26,6 +27,8 @@ export function accessHarness(drivers: Drivers = "*") {const store = new AccessStore(sql);const calls: Array<{ method: string; body: Record<string, unknown> }> = [];const delivered: AccessDispatch[] = [];+ /** Messages `setDrivers` put back on the Slack queue. */+ const requeued: SlackMessageJob[] = [];const changes: Array<{ key: string; by: { id: string; admin: boolean }; from: string; to: string }> = [];const pending: Promise<unknown>[] = [];const h = {@@ -33,9 +36,9 @@ export function accessHarness(drivers: Drivers = "*") {store,calls,delivered,+ requeued,changes,failDelivery: false,- admitted: true,/** Slack answers for a method, instead of `{ ok: true, ts }`. */answers: new Map<string, SlackResult>(),flow: undefined as unknown as AccessFlow,@@ -72,10 +75,12 @@ export function accessHarness(drivers: Drivers = "*") {}return { ok: true, ts: `${ts++}.1` };};+ // The Durable Object's one lookup of a person (threads.ts).+ const people = new ThreadAccess(slack, "T1");h.flow = new AccessFlow({store,slack,- teamId: () => "T1",+ member: (id) => people.member(id),session: (key) => {const row = [...sql.exec<{ owner: string | null; channelId: string; threadTs: string }>("SELECT owner_id AS owner, channel_id AS channelId, thread_ts AS threadTs FROM sessions WHERE runner_key = ?",@@ -86,15 +91,11 @@ export function accessHarness(drivers: Drivers = "*") {linkOfSlack: (id) => (id === ADMIN ? "member-admin" : id === OWNER ? "member-owner" : undefined),isAdmin: (member) => member === "member-admin",name: async (id) => `name-${id}`,- admit: async () => h.admitted,- deliver: async (d) => {- if (h.failDelivery) throw new Error("hub down");- delivered.push(d);- },+ requeue: (job) => void requeued.push(job),changed: (key, by, from, to) => void changes.push({ key, by, from, to }),waitUntil: (p) => void pending.push(p),});- h.ui = new AccessUi({ flow: h.flow, store, slack, teamId: () => "T1", name: async (id) => `name-${id}` });+ h.ui = new AccessUi({ flow: h.flow, store, slack });h.addSession(KEY, OWNER, "100.1", drivers);return h;}@@ -114,3 +115,10 @@ export async function send(h: AccessHarness, job: SlackMessageJob, text = job.teelse await deliver(dispatch);return gate;}++/** The queue's turn: each requeued message through the gate, as `process` takes it. */+export async function drain(h: AccessHarness) {+ const gates = [];+ while (h.requeued.length) gates.push(await send(h, h.requeued.shift()!));+ return gates;+}