Skip to content

An open-source, faster Devin alternative

TypeScript

managed-agents: session roles in the production gateway

Igor Zalutski via Computerb989c13da5e6
diff --git a/services/managed-agents/src/computer/access-flow.ts b/services/managed-agents/src/computer/access-flow.ts
new file mode 100644
index 00000000..db441c7e
--- /dev/null
+++ b/services/managed-agents/src/computer/access-flow.ts
@@ -0,0 +1,378 @@
+// Session roles in the computer's gateway (work 112, "One transition",
+// "Messages", "Request to drive", "Prompts", "Stop"): who is acting, the one
+// write of `drivers`, the context held from people who cannot instruct a
+// session and its attachment to the next message that is delivered, requests
+// to drive, prompt clicks and the stop line. The rules are access.ts's; this
+// applies them with the store, Slack and the Durable Object's delivery, which
+// 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.
+
+import {
+ type Access,
+ type Actor,
+ type ChangedBy,
+ type Drivers,
+ can,
+ commandAction,
+ commandWord,
+ driversCommandText,
+ encodeDrivers,
+ gained,
+ grantedText,
+ initialDrivers,
+ normalize,
+ notAskedText,
+ onlyGrantorAnswersText,
+ onlyMembersText,
+ openedText,
+ ownerCommandText,
+ ownerDecidesText,
+ requestSentText,
+ restricted,
+ role,
+ sameDrivers,
+ stoppedText,
+} from "./access.js";
+import { declinedPost, requestPost } from "./access-views.js";
+import type { 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";
+
+/** Pending prompt clicks remembered for a `not-asked` reply; the oldest go first past this. */
+const MAX_PENDING_ANSWERS = 200;
+
+/** The session an event is about: its runner key, owner and thread. */
+export interface RoleSession {
+ key: string;
+ ownerId: string;
+ channelId: string;
+ threadTs: string;
+}
+
+/** A delivery as the Durable Object queues it (its `Dispatch`), as far as roles need it. */
+export interface AccessDispatch {
+ channelId: string;
+ threadTs: string;
+ messageTs: string;
+ userId: string;
+ text: string;
+ files?: CalvinSlackFile[];
+ mentioned?: boolean;
+ trace?: CalvinTraceContext;
+ linked?: Linked[];
+ role?: "owner" | "driver" | "participant";
+}
+
+/** What `message` decided: deliver with `role` (and the held context unless it is a command), or not at all. */
+export type MessageGate =
+ | { deliver: true; role: "owner" | "driver" | "participant"; context: boolean }
+ | { deliver: false; reason: "outsider" | "held" | "command_refused" };
+
+export interface AccessFlowDeps {
+ store: AccessStore;
+ slack(method: string, body: Record<string, unknown>): Promise<SlackResult>;
+ /** The linked Slack workspace. */
+ teamId(): string;
+ /** A session with an owner, by runner key. */
+ session(key: string): RoleSession | undefined;
+ /** The dashboard member a Slack user linked to (`!link`), if any. */
+ linkOfSlack(slackUserId: string): string | undefined;
+ /** Whether a dashboard member is an owner or admin of the organization. */
+ 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>;
+ /** `access.changed`. */
+ changed(key: string, by: ChangedBy, from: string, to: string): void;
+ waitUntil(work: Promise<unknown>): void;
+}
+
+export class AccessFlow {
+ /** Prompt clicks sent to the host with a `role`, by frame id: whom to tell when the runner answers `not-asked`. */
+ private readonly answers = new Map<string, { key: string; userId: string }>();
+
+ constructor(private readonly deps: AccessFlowDeps) {}
+
+ access(key: string): Access | undefined {
+ const s = this.deps.session(key);
+ const drivers = s && this.deps.store.drivers(key);
+ return s && drivers !== undefined ? { owner: s.ownerId, drivers } : undefined;
+ }
+
+ /**
+ * Who is acting. The owner's membership is not looked up: `role` puts the
+ * owner first, so it decides nothing for them.
+ */
+ 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));
+ return { id: userId, member, admin };
+ }
+
+ /** `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 };
+ }
+
+ // ---------------------------------------------------------------- new sessions
+
+ /**
+ * A new session's `drivers`: its parent's for a spawned one (`from`), else
+ * the organization's default. A restricted one gets the marker, off the
+ * caller's path (session creation is synchronous).
+ */
+ start(key: string, from?: string): void {
+ const s = this.deps.session(key);
+ if (!s) return;
+ const parent = from ? this.deps.store.drivers(from) : undefined;
+ const drivers = normalize(s.ownerId, parent ?? initialDrivers(this.deps.store.accessDefault()));
+ this.deps.store.writeDrivers(key, drivers);
+ if (restricted(drivers)) this.deps.waitUntil(this.marker(s, true));
+ }
+
+ // ---------------------------------------------------------------- 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);
+ }
+ }
+ // 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. */
+ private async marker(s: RoleSession, on: boolean): Promise<void> {
+ try {
+ const r = await this.deps.slack(on ? "reactions.add" : "reactions.remove", { channel: s.channelId, timestamp: s.threadTs, name: "lock" });
+ if (!r.ok && r.error !== "already_reacted" && r.error !== "no_reaction") warn("computer.access_marker_failed", r.error);
+ } catch (error) {
+ warn("computer.access_marker_failed", error);
+ }
+ }
+
+ // ---------------------------------------------------------------- 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.
+ */
+ async message(job: SlackMessageJob, text: string, s: RoleSession): Promise<MessageGate> {
+ const a: Access = { owner: s.ownerId, drivers: this.deps.store.drivers(s.key) ?? "*" };
+ const u = await this.actor(job.userId, s.ownerId);
+ 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 };
+ 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());
+ return { deliver: false, reason: "outsider" };
+ }
+ 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);
+ }
+ return { deliver: false, reason: "held" };
+ }
+
+ /**
+ * "Messages" step 5: `dispatch` with the session's held context attached,
+ * through `send` (the queue's own delivery by default). The attached rows go
+ * once it is accepted; a failure keeps them for the next message.
+ */
+ async deliver<D extends AccessDispatch>(key: string, dispatch: D, send: (d: D) => Promise<void>): Promise<void> {
+ const held = this.deps.store.held(key);
+ if (!held.length) return send(dispatch);
+ const messages = await Promise.all(
+ held.map(async (h) => ({
+ name: await this.deps.name(h.userId),
+ ts: h.ts,
+ text: h.text,
+ ...(h.files.length ? { files: h.files } : {}),
+ ...(h.skipped ? { skipped: h.skipped } : {}),
+ })),
+ );
+ const context: Linked = { url: "", ok: true, where: "", context: true, messages };
+ await send({ ...dispatch, linked: [...(dispatch.linked ?? []), context] });
+ 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. */
+ 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));
+ await this.ephemeral(s, job.userId, requestSentText(s.ownerId));
+ }
+
+ /** `Allow` or `Not now` on a request (`ac:<k>:allow|deny:<requester>`), clicked by `userId`. */
+ async answerRequest(key: string, verb: "allow" | "deny", requester: string, userId: string): Promise<void> {
+ const s = this.deps.session(key);
+ const a = this.access(key);
+ if (!s || !a) return;
+ const u = await this.actor(userId, a.owner);
+ 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;
+ const by = this.by(a, u);
+ if (verb === "deny") {
+ 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;
+ }
+ await this.setDrivers(key, [...a.drivers, requester], by);
+ }
+
+ // ---------------------------------------------------------------- prompts
+
+ /**
+ * A click on a prompt's button. Without `can(answer)` the clicker is told
+ * S6 and nothing is sent; otherwise `send` sends the `action` frame with
+ * their role and returns its id, remembered for a `not-asked` reply. A
+ * session with no owner sends as before, without a role.
+ */
+ async answer(key: string, userId: string, send: (role?: "owner" | "driver") => string): Promise<void> {
+ const s = this.deps.session(key);
+ const a = this.access(key);
+ if (!s || !a) {
+ send();
+ return;
+ }
+ const u = await this.actor(userId, a.owner);
+ 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 });
+ if (this.answers.size > MAX_PENDING_ANSWERS) this.answers.delete(this.answers.keys().next().value!);
+ }
+
+ /** The host's reply to an `action` frame: a `not-asked` error is S6 to whoever clicked. */
+ async answered(id: string, error: string | undefined): Promise<void> {
+ const pending = this.answers.get(id);
+ this.answers.delete(id);
+ const s = pending && error === NOT_ASKED ? this.deps.session(pending.key) : undefined;
+ if (s && pending) await this.ephemeral(s, pending.userId, notAskedText(s.ownerId));
+ }
+
+ // ---------------------------------------------------------------- stop
+
+ /**
+ * Slack's stop button. An outsider's is ignored; without a user it stops as
+ * before. Once the hub took it, someone other than the owner is named (S9).
+ */
+ 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 delivered = send();
+ if (delivered && userId && userId !== s.ownerId) await this.post(s, stoppedText(userId));
+ return delivered;
+ }
+
+ // ---------------------------------------------------------------- Slack
+
+ /** An ephemeral to `userId` in the thread (at the top level without one). Never throws. */
+ async ephemeral(s: { channelId: string; threadTs?: string }, userId: string, text: string, blocks?: unknown[]): Promise<void> {
+ await this.call("chat.postEphemeral", { channel: s.channelId, user: userId, ...(s.threadTs ? { thread_ts: s.threadTs } : {}), text, ...(blocks ? { blocks } : {}) });
+ }
+
+ private async post(s: RoleSession, text: string): Promise<void> {
+ await this.call("chat.postMessage", { channel: s.channelId, thread_ts: s.threadTs, text });
+ }
+
+ /** A Slack call whose failure is logged, never thrown: each is a courtesy or is retried by the person. */
+ private async call(method: string, body: Record<string, unknown>): Promise<SlackResult | undefined> {
+ try {
+ const r = await this.deps.slack(method, body);
+ if (!r.ok) warn("computer.access_slack_failed", `${method}: ${r.error ?? "unknown_error"}`);
+ return r;
+ } catch (error) {
+ warn("computer.access_slack_failed", error);
+ return undefined;
+ }
+ }
+}
+
+function warn(event: string, error: unknown): void {
+ console.warn(JSON.stringify({ level: "warn", event, message: error instanceof Error ? error.message : String(error ?? "") }));
+}
diff --git a/services/managed-agents/src/computer/access-store.ts b/services/managed-agents/src/computer/access-store.ts
new file mode 100644
index 00000000..20cbf00f
--- /dev/null
+++ b/services/managed-agents/src/computer/access-store.ts
@@ -0,0 +1,161 @@
+// Session roles (work 112): what the computer's Durable Object stores about
+// who may drive a Slack session. `sessions.drivers`, the context held from
+// people who cannot instruct a session (`session_context`), requests to drive
+// (`access_requests`), and the organization's default for new sessions
+// (`accessDefault` in `settings`). SQL only; access-flow.ts decides.
+
+import {
+ ACCESS_DEFAULT_SETTING,
+ type AccessDefault,
+ CONTEXT_MAX_AGE_MS,
+ CONTEXT_MAX_CHARS,
+ CONTEXT_MAX_ROWS,
+ type Drivers,
+ decodeDrivers,
+ encodeDrivers,
+ readAccessDefault,
+} from "./access.js";
+
+/** One message held as context, oldest first; `skipped` on the first when older rows were left out. */
+export interface HeldMessage {
+ seq: number;
+ userId: string;
+ ts: string;
+ text: string;
+ files: string[];
+ skipped?: number;
+}
+
+/** A request to drive. `held`: the message that asked, as the gateway received it (JSON). */
+export type AccessRequest = {
+ key: string;
+ userId: string;
+ state: "open" | "closed";
+ messageTs: string;
+ held: string;
+ at: number;
+};
+
+export class AccessStore {
+ constructor(private readonly sql: SqlStorage) {
+ // The `sessions` table is the Durable Object's; sessions from before work 112 read '*'.
+ try {
+ sql.exec("ALTER TABLE sessions ADD COLUMN drivers TEXT NOT NULL DEFAULT '*'");
+ } catch {
+ // Already there.
+ }
+ sql.exec(`
+ CREATE TABLE IF NOT EXISTS session_context (
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
+ 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 TABLE IF NOT EXISTS access_requests (
+ key TEXT NOT NULL, user_id TEXT NOT NULL,
+ state TEXT NOT NULL,
+ message_ts TEXT NOT NULL,
+ held TEXT NOT NULL,
+ at INTEGER NOT NULL,
+ PRIMARY KEY (key, user_id));
+ `);
+ }
+
+ // ---------------------------------------------------------------- drivers
+
+ /** A session's `drivers`; undefined when there is no such session. */
+ drivers(key: string): Drivers | undefined {
+ const row = [...this.sql.exec<{ drivers: string | null }>("SELECT drivers FROM sessions WHERE runner_key = ?", key)][0];
+ return row ? decodeDrivers(row.drivers) : undefined;
+ }
+
+ /** Only `AccessFlow.setDrivers` and session creation write this. */
+ writeDrivers(key: string, drivers: Drivers): void {
+ this.sql.exec("UPDATE sessions SET drivers = ? WHERE runner_key = ?", encodeDrivers(drivers), key);
+ }
+
+ accessDefault(): AccessDefault {
+ return readAccessDefault([...this.sql.exec<{ value: string }>("SELECT value FROM settings WHERE key = ?", ACCESS_DEFAULT_SETTING)][0]?.value);
+ }
+
+ setAccessDefault(value: AccessDefault): void {
+ this.sql.exec(
+ "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ ACCESS_DEFAULT_SETTING,
+ value,
+ );
+ }
+
+ // ---------------------------------------------------------------- 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 (?, ?, ?, ?, ?, ?)",
+ key,
+ m.userId,
+ m.ts,
+ m.text.slice(0, CONTEXT_MAX_CHARS),
+ m.files.length ? JSON.stringify(m.files) : null,
+ now,
+ );
+ }
+
+ /** The newest CONTEXT_MAX_ROWS, oldest first, after this session's rows older than CONTEXT_MAX_AGE_MS are deleted. */
+ held(key: string, now = Date.now()): HeldMessage[] {
+ this.sql.exec("DELETE FROM session_context WHERE key = ? AND at < ?", key, now - CONTEXT_MAX_AGE_MS);
+ const total = [...this.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM session_context WHERE key = ?", key)][0]?.n ?? 0;
+ const rows = [...this.sql.exec<{ seq: number; userId: string; ts: string; text: string; files: string | null }>(
+ "SELECT seq, user_id AS userId, ts, text, files FROM session_context WHERE key = ? ORDER BY seq DESC LIMIT ?",
+ key,
+ CONTEXT_MAX_ROWS,
+ )].reverse();
+ const messages = rows.map((r): HeldMessage => ({ seq: r.seq, userId: r.userId, ts: r.ts, text: r.text, files: decodeFiles(r.files) }));
+ const skipped = total - messages.length;
+ if (skipped > 0 && messages[0]) messages[0] = { ...messages[0], skipped };
+ return messages;
+ }
+
+ /** Rows delivered with a message. */
+ forget(seqs: readonly number[]): void {
+ for (const seq of seqs) this.sql.exec("DELETE FROM session_context WHERE seq = ?", seq);
+ }
+
+ /** A held message that is delivered as itself (an allowed request). */
+ forgetMessage(key: string, ts: string): void {
+ this.sql.exec("DELETE FROM session_context WHERE key = ? AND ts = ?", key, ts);
+ }
+
+ // ---------------------------------------------------------------- requests
+
+ request(key: string, userId: string): AccessRequest | undefined {
+ return [...this.sql.exec<AccessRequest>(
+ "SELECT key, user_id AS userId, state, message_ts AS messageTs, held, at FROM access_requests WHERE key = ? AND user_id = ?",
+ key,
+ userId,
+ )][0];
+ }
+
+ openRequests(key: string): AccessRequest[] {
+ return [...this.sql.exec<AccessRequest>(
+ "SELECT key, user_id AS userId, state, message_ts AS messageTs, held, at FROM access_requests WHERE key = ? AND state = 'open' ORDER BY at, rowid",
+ key,
+ )];
+ }
+
+ 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 closed it: one of two overlapping clicks acts. */
+ closeRequest(key: string, userId: string): boolean {
+ return this.sql.exec("UPDATE access_requests SET state = 'closed' WHERE key = ? AND user_id = ? AND state = 'open'", key, userId).rowsWritten > 0;
+ }
+}
+
+function decodeFiles(text: string | null): string[] {
+ try {
+ const v: unknown = JSON.parse(text ?? "[]");
+ return Array.isArray(v) ? v.filter((f): f is string => typeof f === "string") : [];
+ } catch {
+ return [];
+ }
+}
diff --git a/services/managed-agents/src/computer/access-ui.ts b/services/managed-agents/src/computer/access-ui.ts
new file mode 100644
index 00000000..56ac9e8a
--- /dev/null
+++ b/services/managed-agents/src/computer/access-ui.ts
@@ -0,0 +1,138 @@
+// Session roles' controls in the computer's gateway (work 112, "Controls"):
+// the `Access` button's modal and its submission, the request buttons, and
+// `!access`. Views and strings are access-views.ts and access.ts; every
+// change of `drivers` goes through `AccessFlow.setDrivers`.
+
+import {
+ type AccessCommand,
+ ACCESS_USAGE,
+ accessCommandNeeds,
+ can,
+ 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";
+
+/** Where an answer goes: the person, and the channel and thread they acted in. */
+export interface AccessWhere {
+ userId: string;
+ channelId: string;
+ threadTs?: string;
+}
+
+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`). */
+export type After = () => Promise<void>;
+
+export class AccessUi {
+ constructor(private readonly deps: AccessUiDeps) {}
+
+ /**
+ * A click on an `ac:` button: `open` shows the modal now (its `trigger_id`
+ * lasts 3 s); `allow` and `deny` are returned as `after`, for Slack's 3 s ack.
+ */
+ async action(actionId: string, triggerId: string | undefined, where: AccessWhere): Promise<{ after?: After }> {
+ const id = decodeAccessId(actionId);
+ if (!id) return {};
+ if (id.verb !== "open") {
+ const verb = id.verb;
+ const requester = id.userId ?? "";
+ return { after: () => this.deps.flow.answerRequest(id.sessionKey, verb, requester, where.userId) };
+ }
+ const a = this.deps.flow.access(id.sessionKey);
+ if (!a) {
+ 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));
+ 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. */
+ 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);
+ 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)) };
+ }
+
+ /** `!access …`, never delivered. All answers are ephemerals to the typer, in the thread. */
+ async command(text: string, ctx: AccessWhere & { session?: { key: string } }): Promise<void> {
+ const c = parseAccessCommand(text);
+ const where = threadOf(ctx);
+ const say = (answer: string, blocks?: unknown[]) => this.deps.flow.ephemeral(where, ctx.userId, answer, blocks);
+ if (c.kind === "default") {
+ const u = await this.deps.flow.actor(ctx.userId);
+ if (!u.admin || !u.member) return say(onlyAdminDefaultText());
+ this.deps.store.setAccessDefault(c.value);
+ return say(defaultChangedText(c.value));
+ }
+ const key = ctx.session?.key;
+ const a = key ? this.deps.flow.access(key) : undefined;
+ 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));
+ 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 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);
+ if (!r.ok) console.warn(JSON.stringify({ level: "warn", event: "computer.access_slack_failed", message: `${method}: ${r.error ?? "unknown_error"}` }));
+ } catch (error) {
+ console.warn(JSON.stringify({ level: "warn", event: "computer.access_slack_failed", message: error instanceof Error ? error.message : String(error) }));
+ }
+ }
+}
+
+/** An ephemeral's place: the thread, or the channel's top level when there is none. */
+function threadOf(where: AccessWhere): { channelId: string; threadTs?: string } {
+ return { channelId: where.channelId, ...(where.threadTs ? { threadTs: where.threadTs } : {}) };
+}
diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.ts
index 5ca46f30..6deda710 100644
--- a/services/managed-agents/src/computer/durable-object.ts
+++ b/services/managed-agents/src/computer/durable-object.ts
@@ -146,6 +146,11 @@ import {
import { type SubmittedView, parseSecretCommand } from "./secrets.js";
import { parseVariableCommand } from "./variables.js";
import { type SecretsApiOp, SecretsStore } from "./secrets-store.js";
+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 { CONNECTION_VIEW, ComputerConnections, type ConnectionRequest, type GrantableConnection } from "./connections.js";
import {
AGENT_ERRORS,
@@ -285,6 +290,8 @@ interface Dispatch {
trace?: CalvinTraceContext;
/** Threads linked in the message (work 049 L3): dropped from the row once the host has answered. */
linked?: Linked[];
+ /** Work 112: the sender's role in the session (access-flow.ts); absent for a message that starts one. */
+ role?: "owner" | "driver" | "participant";
}
type SessionRow = {
@@ -400,6 +407,9 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
*/
private readonly access: ModelAccess;
private readonly connections: ComputerConnections;
+ /** Work 112: who may drive each Slack session (access-flow.ts), its modal and `!access` (access-ui.ts). */
+ private readonly roles: AccessFlow;
+ private readonly rolesUi: AccessUi;
private readonly billing: ComputerRuntimeBilling;
/** Work 054: the gateway's telemetry events (telemetry/computer.ts); sends nothing unless configured. */
private readonly telemetry: ComputerTelemetry;
@@ -668,6 +678,29 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
remove: (key) => this.remove(key),
telemetry: this.apiTelemetry,
});
+ // Work 112: session roles. After the sessions table and `this.api` (who is an admin).
+ const roleStore = new AccessStore(sql);
+ this.roles = new AccessFlow({
+ store: roleStore,
+ slack: (method, body) => this.slack(method, body),
+ teamId: () => this.setting("slackTeamId") ?? "",
+ 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() }) }),
+ changed: (key, by, from, to) => this.telemetry.accessChanged(key, by, from, to),
+ waitUntil: (work) => ctx.waitUntil(work),
+ });
+ this.rolesUi = new AccessUi({
+ 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:
// a throw here would reset the object on every instantiation). The alarm for
@@ -2288,6 +2321,17 @@ 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}`;
@@ -2323,7 +2367,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
// A mention partway through a thread starts the session: it also gets the replies above (it sees only what comes after).
const above = !addressed && job.channelType !== "im" && job.threadTs !== job.messageTs;
const linked = await this.linkedThreads(t, job, session.ownerId ?? job.userId, above);
- await this.deliver({
+ const dispatch: Dispatch = {
channelId: job.channelId,
threadTs: job.threadTs,
messageTs: job.messageTs,
@@ -2333,7 +2377,11 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
mentioned,
...(job.trace ? { trace: job.trace } : {}),
...(linked.length ? { linked } : {}),
- }, t);
+ ...(gate?.deliver ? { role: gate.role } : {}),
+ };
+ // With the context held for the session, except on a command.
+ if (gate?.deliver && gate.context) await this.roles.deliver(key, dispatch, (d) => this.deliver(d, t));
+ else await this.deliver(dispatch, t);
}
private threads(): ThreadAccess {
@@ -2534,7 +2582,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
console.log(JSON.stringify({ level: "info", event: "computer.thread_harness", harness, via }));
}
- private createSession(input: { channelId: string; threadTs: string; ownerId: string; title: string; mode?: CalvinMode; model?: string }): SessionRow {
+ /** `from`: the session that spawned this one, whose `drivers` it starts with (work 112). */
+ private createSession(input: { channelId: string; threadTs: string; ownerId: string; title: string; mode?: CalvinMode; model?: string; from?: string }): SessionRow {
const teamId = this.setting("slackTeamId")!;
const key = sessionKey(teamId, input.channelId, input.threadTs);
const now = Date.now();
@@ -2552,6 +2601,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
now,
now,
);
+ // Work 112: who may drive it, from the organization's default or the parent; 🔒 when restricted.
+ this.roles.start(key, input.from);
// Analytics: one row per created session in the managed-agent session
// index, like every serverless agent session, with source `computer`
// so @OpenComputer sessions stay distinct from api, schedule, webhook,
@@ -2574,14 +2625,16 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
return { indicator: "reaction", ok: reacted.ok, callMs: Date.now() - started };
}
- /** Slack's stop button on a thread. */
- async slackStop(accountId: string, channelId: string, threadTs?: string): Promise<{ delivered: boolean }> {
+ /** Slack's stop button on a thread. `userId`: who pressed it (work 112: an outsider's is ignored, anyone else's is named). */
+ async slackStop(accountId: string, channelId: string, threadTs?: string, userId?: string): Promise<{ delivered: boolean }> {
this.bind(accountId);
const teamId = this.setting("slackTeamId");
if (!teamId || !threadTs) return { delivered: false };
const key = sessionKey(teamId, channelId, threadTs);
if (!this.session(key)) return { delivered: false };
- return { delivered: this.send({ t: "stop", id: crypto.randomUUID(), sessionKey: key }) };
+ const stop = () => this.send({ t: "stop", id: crypto.randomUUID(), sessionKey: key });
+ const roleSession = this.runnerSession(key);
+ return { delivered: roleSession ? await this.roles.stop(roleSession, userId, stop) : stop() };
}
/** Interactivity: the secret modal's submission, its button, and prompts the runner posted. */
@@ -2609,6 +2662,12 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
if (after) this.ctx.waitUntil(after().catch((error) => console.error("computer.connection_followup_failed", errorText(error))));
return errors ? { errors } : {};
}
+ // Work 112: the session access modal.
+ if (interaction.type === "view_submission" && interaction.view?.callback_id === ACCESS_VIEW) {
+ const { errors, after } = await this.rolesUi.submit(interaction.view as AccessSubmission, userId);
+ if (after) this.ctx.waitUntil(after().catch((error) => console.error(JSON.stringify({ level: "error", event: "computer.access_followup_failed", message: errorText(error) }))));
+ return errors ? { errors } : {};
+ }
if (interaction.type === "view_submission" && interaction.view) {
const { errors, after } = await this.secrets.submit(interaction.view as SubmittedView, userId);
if (after) this.ctx.waitUntil(after().catch((error) => console.error("computer.secret_followup_failed", errorText(error))));
@@ -2676,9 +2735,27 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
}, respond);
return {};
}
+ // Work 112: `Access`, and a request's `Allow` / `Not now`.
+ if (actionId.startsWith("ac:")) {
+ const container = interaction.container;
+ const channelId = interaction.channel?.id ?? container?.channel_id;
+ if (!channelId) return {};
+ const { after } = await this.rolesUi.action(actionId, interaction.trigger_id, {
+ userId,
+ channelId,
+ ...(container?.thread_ts ? { threadTs: container.thread_ts } : {}),
+ });
+ if (after) this.ctx.waitUntil(after().catch((error) => console.error(JSON.stringify({ level: "error", event: "computer.access_followup_failed", message: errorText(error) }))));
+ return {};
+ }
const action = decodeCalvinActionId(actionId);
if (action) {
- this.send({ t: "action", id: crypto.randomUUID(), sessionKey: action.sessionKey, promptId: action.promptId, value: action.value, userId });
+ // Work 112: only someone who may answer the session's prompts; the frame carries their role.
+ await this.roles.answer(action.sessionKey, userId, (role) => {
+ const id = crypto.randomUUID();
+ this.send({ t: "action", id, sessionKey: action.sessionKey, promptId: action.promptId, value: action.value, userId, ...(role ? { role } : {}) });
+ return id;
+ });
}
return {};
}
@@ -2953,6 +3030,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
...(dispatch.files?.length ? { files: dispatch.files } : {}),
...(dispatch.mentioned !== undefined ? { mentioned: dispatch.mentioned } : {}),
...(dispatch.linked?.length ? { linked: dispatch.linked } : {}),
+ ...(dispatch.role ? { role: dispatch.role } : {}),
},
credentials,
secrets,
@@ -3009,6 +3087,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
);
this.ctx.storage.sql.exec("DELETE FROM dispatches WHERE state IN ('complete', 'failed') AND updated_at < ?", Date.now() - DEDUP_TTL_MS);
if (!event.ok) await this.deliveryFailed(event.id, event.error ?? "unknown error");
+ // Work 112: a prompt click the runner refused (`not-asked`) is told to whoever clicked.
+ await this.roles.answered(event.id, event.ok ? undefined : event.error);
// Other threads' text is not kept past delivery (the row stays for dedup).
this.ctx.storage.sql.exec(
"UPDATE dispatches SET payload = json_remove(payload, '$.linked') WHERE id = ? AND json_extract(payload, '$.linked') IS NOT NULL",
@@ -3328,6 +3408,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
threadTs,
ownerId,
title: task,
+ from,
...(parent.mode ? { mode: parent.mode } : {}),
// A tier picks its own model in the runner; without one the parent's carries over.
...(!req.tier && parent.model ? { model: parent.model } : {}),
diff --git a/services/managed-agents/src/computer/routes.ts b/services/managed-agents/src/computer/routes.ts
index d2308660..40edb365 100644
--- a/services/managed-agents/src/computer/routes.ts
+++ b/services/managed-agents/src/computer/routes.ts
@@ -573,7 +573,7 @@ async function slackEvents(request: Request, env: ComputerEdgeEnv, context: Exec
}
if (parsed.kind === "stop") {
const interacted = interactionSpan(env, request, context, { teamId, channelId: parsed.channelId, accountId });
- await interacted("stop", computer.slackStop(accountId, parsed.channelId, parsed.threadTs));
+ await interacted("stop", computer.slackStop(accountId, parsed.channelId, parsed.threadTs, parsed.userId));
} else {
const accepted = await computer.acceptSlackEvent(accountId, received ? { ...parsed.job, trace: received.trace } : parsed.job);
// The organization is not linked to this workspace (any more): a cached link was stale.
diff --git a/services/managed-agents/src/computer/secrets-store.ts b/services/managed-agents/src/computer/secrets-store.ts
index 7e934378..3267c404 100644
--- a/services/managed-agents/src/computer/secrets-store.ts
+++ b/services/managed-agents/src/computer/secrets-store.ts
@@ -34,6 +34,7 @@ import {
secretNameProblem,
setBlocks,
} from "./secrets.js";
+import { isWorkspaceMember } from "./slack.js";
import { type VariableCommand, VARIABLE_HELP, credentialHint, parseVariableCommand, showValue } from "./variables.js";
import type { ApiCaller, ApiReply } from "./sessions-api.js";
@@ -256,11 +257,8 @@ export class SecretsStore {
* workspace (2026-10-11: they are trusted). Not guests, people from
* other organizations in shared channels, bots or deactivated accounts.
*/
- private async isMember(userId: string): Promise<boolean> {
- const r = await this.deps.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 === this.deps.teamId();
+ 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> {
diff --git a/services/managed-agents/src/computer/sessions-api.ts b/services/managed-agents/src/computer/sessions-api.ts
index e54bfcd7..aaa480ab 100644
--- a/services/managed-agents/src/computer/sessions-api.ts
+++ b/services/managed-agents/src/computer/sessions-api.ts
@@ -1139,6 +1139,11 @@ export class ComputerSessionsApi {
return this.adminsCache;
}
+ /** Whether organization member `member` (`usr_…`) is an admin, as last seen on the dashboard (work 112: session roles). */
+ isAdmin(member: string): boolean {
+ return this.admins().includes(member);
+ }
+
/** Records whether `member` is an admin; on a change, every access list goes to the host again. */
private noteAdmin(member: string, admin: boolean): void {
const admins = this.admins();
diff --git a/services/managed-agents/src/computer/slack.ts b/services/managed-agents/src/computer/slack.ts
index 77283f85..dbbf1887 100644
--- a/services/managed-agents/src/computer/slack.ts
+++ b/services/managed-agents/src/computer/slack.ts
@@ -143,7 +143,8 @@ function fileMetadata(files: CalvinSlackFile[] | undefined): CalvinSlackFile[] |
export type ParsedSlackEvent =
| { kind: "challenge"; challenge: string }
| { kind: "message"; job: SlackMessageJob }
- | { kind: "stop"; teamId: string; channelId: string; threadTs?: string; eventId: string }
+ /** `userId`: who pressed stop, when Slack says (work 112: an outsider's stop is ignored). */
+ | { kind: "stop"; teamId: string; channelId: string; threadTs?: string; userId?: string; eventId: string }
/** The app was uninstalled from the workspace, or its bot token revoked. */
| { kind: "revoked"; teamId: string }
/** Work 077: a person left the workspace, was deactivated or became a guest (`team_leave`, `user_change`). */
@@ -169,6 +170,7 @@ export function parseSlackEnvelope(payload: unknown, now = Date.now()): ParsedSl
teamId: envelope.team_id,
channelId: event.channel,
...(event.thread_ts ? { threadTs: event.thread_ts } : {}),
+ ...(typeof event.user === "string" && event.user ? { userId: event.user } : {}),
eventId: envelope.event_id,
};
}
@@ -301,6 +303,27 @@ 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/telemetry/catalog.ts b/services/managed-agents/src/computer/telemetry/catalog.ts
index 4860cd36..2cc4c1f7 100644
--- a/services/managed-agents/src/computer/telemetry/catalog.ts
+++ b/services/managed-agents/src/computer/telemetry/catalog.ts
@@ -3,7 +3,7 @@
// message.received's cached, cache_layer and colo, queue.started's inline and parallel,
// dispatch.sent's wait_ms (work 068)
// (bluecode perf/gateway-ack; add them to calvin's copy), and the subscription.* events
-// (work 082 P2, blue#272; add them to calvin's copy), the work 084 instrumentation entries
+// (work 082 P2, blue#272; add them to calvin's copy), access.changed (work 112; add it to calvin's copy), the work 084 instrumentation entries
// (calvin's mirror.*, api.*, wire.*, cli.* and turn.started's keys verbatim, catalog v2; blue's
// and the edge's own, below, per /tmp/build084/instrumentation-catalog.md); keep identical until work 050 P3
// shares the protocol package.
@@ -69,6 +69,9 @@ export const CATALOG = {
'credentials.resolved': gateway('source'),
// The organization's repositories re-read: account object (installations, token mints) and GitHub (listing) timed apart.
'definition.refreshed': gateway('account_ms', 'github_ms', 'repos', 'changed', 'timed_out'),
+ // Work 112: who can drive a Slack session changed (`session_key`, `person_id`: who changed it). `by_admin`: an
+ // admin who is not the owner; `from`/`to`: `*` (everyone in the thread) or a JSON array of Slack user ids.
+ 'access.changed': gateway('by_admin', 'from', 'to'),
// Model subscriptions held by the computer (work 077 Claude, 082 ChatGPT for Codex); the envelope's
// `provider` (anthropic|chatgpt) says whose. Never a token, an account id or a fingerprint.
// `via` slack|dashboard|connect_code; `plan` from the token's claims (chatgpt).
diff --git a/services/managed-agents/src/computer/telemetry/computer.ts b/services/managed-agents/src/computer/telemetry/computer.ts
index 78d2211e..a8db6d5d 100644
--- a/services/managed-agents/src/computer/telemetry/computer.ts
+++ b/services/managed-agents/src/computer/telemetry/computer.ts
@@ -10,6 +10,7 @@
// host socket host.connected / .disconnected; the telemetry credential in `welcome`
// subscriptions subscription.* (work 082), from ModelSubscriptions through `subscription`
// billing billing.vm_terminated (work 086), from the idle check
+// roles access.changed (work 112), from AccessFlow.setDrivers
//
// Invariants: no hook throws or awaits anything a turn waits for; batches
// leave through `waitUntil`. With telemetry off (gateway.ts) every hook still
@@ -194,6 +195,15 @@ export class ComputerTelemetry {
this.send(t);
}
+ // ---------------------------------------------------------------- session roles
+
+ /** `access.changed` (work 112): who can drive a session changed, in its own batch. */
+ accessChanged(key: string, by: { id: string; admin: boolean }, from: string, to: string): void {
+ const t = this.invocation();
+ t.emit("access.changed", { session_key: key, person_id: by.id, data: { by_admin: by.admin, from, to } });
+ this.send(t);
+ }
+
// ---------------------------------------------------------------- dispatches
/** The trace to send with a delivery: stamped with this send's time (the stored payload keeps the original). */
diff --git a/services/managed-agents/src/computer/threads.ts b/services/managed-agents/src/computer/threads.ts
index 68b03cdd..1593b7c1 100644
--- a/services/managed-agents/src/computer/threads.ts
+++ b/services/managed-agents/src/computer/threads.ts
@@ -258,6 +258,15 @@ export class ThreadAccess {
return { ts: posted.ts, url: `https://${host}/archives/${ref.channel}/p${posted.ts.replace(".", "")}?thread_ts=${root}&cid=${ref.channel}` };
}
+ /** A person's display name from the cached lookup, or their id when Slack does not say (work 112: held context). */
+ async name(id: string): Promise<string> {
+ try {
+ return (await this.user(id)).name;
+ } catch {
+ return 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.
diff --git a/services/managed-agents/test/computer-access-do.test.ts b/services/managed-agents/test/computer-access-do.test.ts
new file mode 100644
index 00000000..14ce3eb5
--- /dev/null
+++ b/services/managed-agents/test/computer-access-do.test.ts
@@ -0,0 +1,149 @@
+import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";
+import { describe, expect, it } from "vitest";
+
+import { 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";
+
+/**
+ * Session roles at the computer's seams (work 112): `process` gates a message
+ * in an existing session, `!access` is the gateway's, `slackStop` takes the
+ * user, spawn copies `drivers`. The rules themselves are
+ * computer-access-flow.test.ts's. The fake Slack's people (computer-fakes.mjs)
+ * are full members of this test's workspace except UGUEST, a guest.
+ */
+
+const ORIGIN = "https://managedagents.test";
+const SIGNING_SECRET = "computer-signing-secret";
+const HOST_KEY = "test-computer-host-token-key";
+const TS = "1700000000.000100";
+
+type Namespace = DurableObjectNamespace<ComputerDurableObject>;
+const computers = () => (env as unknown as { COMPUTERS: Namespace }).COMPUTERS;
+
+async function until<T>(read: () => T | Promise<T>, done: (value: T) => boolean, what: string): Promise<T> {
+ for (let i = 0; i < 150; i += 1) {
+ const value = await read();
+ if (done(value)) return value;
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ throw new Error(`never: ${what}`);
+}
+
+async function signed(path: string, body: string) {
+ const timestamp = String(Math.floor(Date.now() / 1000));
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(SIGNING_SECRET), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`v0:${timestamp}:${body}`)));
+ const signature = `v0=${[...mac].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
+ return SELF.fetch(`${ORIGIN}${path}`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-slack-request-timestamp": timestamp, "x-slack-signature": signature },
+ body,
+ });
+}
+
+/** A linked organization with a connected host and one session UADA started in C1; this object's Slack calls recorded. */
+async function withSession(org: string, team: string) {
+ const computer = computers().getByName(org);
+ // The outbound fake's call log is shared with files running in parallel: observe this object's own calls.
+ // Its people are of workspace T0ACME; here they are of this test's.
+ await runInDurableObject(computer, ((instance: any) => {
+ instance.accessTestCalls = [];
+ const slack = instance.slack.bind(instance);
+ instance.slack = async (method: string, body: Record<string, unknown>) => {
+ instance.accessTestCalls.push({ method, body });
+ const result = await slack(method, body);
+ return method === "users.info" && result.user ? { ...result, user: { ...result.user, team_id: team } } : result;
+ };
+ }) as never);
+ const calls = () => runInDurableObject(computer, ((instance: any) => instance.accessTestCalls) as never) as Promise<Array<{ method: string; body: Record<string, any> }>>;
+ await computers().getByName(`computer-slack-team:${team}`).claimTeam(team, org);
+ await computer.linkSlack(org, { teamId: team, teamName: "Roles", botUserId: "UBOT", botToken: SLACK_BOT_TOKEN });
+ const upgraded = await SELF.fetch(`${ORIGIN}/v1/computer/host?organizationId=${org}`, {
+ headers: { upgrade: "websocket", authorization: `Bearer ${await hostToken(HOST_KEY, org)}` },
+ });
+ const socket = upgraded.webSocket!;
+ socket.accept();
+ const frames: any[] = [];
+ socket.addEventListener("message", (event: MessageEvent) => void frames.push(JSON.parse(String(event.data))));
+ socket.send(JSON.stringify({ t: "hello", protocol: 1, hostId: org, version: "host-1", sessions: [] }));
+ await until(() => frames, (all) => all.some((frame) => frame.t === "welcome"), "welcome");
+
+ let n = 0;
+ /** A message event, and the queue run that follows it. */
+ const post = async (user: string, text: string, o: { mention?: boolean; threadTs?: string } = {}) => {
+ const ts = o.threadTs === undefined ? TS : `1700000000.${String(200 + n).padStart(6, "0")}`;
+ const event = {
+ type: "event_callback",
+ event_id: `Ev-${org}-${n++}`,
+ team_id: team,
+ event: { type: o.mention ? "app_mention" : "message", channel: "C1", user, text: o.mention ? `<@UBOT> ${text}` : text, ts, ...(o.threadTs ? { thread_ts: o.threadTs } : {}) },
+ };
+ expect((await signed("/v1/webhooks/computer/slack/events", JSON.stringify(event))).status).toBe(200);
+ await runInDurableObject(computer, (_instance, state: DurableObjectState) => state.storage.sql.exec("UPDATE alarms SET at = 0 WHERE purpose = 'slack'"));
+ await runDurableObjectAlarm(computer);
+ return ts;
+ };
+ const delivered = (ts: string) => until(() => frames.find((frame) => frame.t === "deliver" && frame.msg.ts === ts), (found) => !!found, `the delivery of ${ts}`);
+ const say = (user: string, text: string, o: { mention?: boolean } = {}) => post(user, text, { ...o, threadTs: TS });
+ const key = `${team}:C1:${TS}`;
+ const first = await delivered(await post("UADA", "plan the work", { mention: true }));
+ const drivers = () =>
+ runInDurableObject(computer, (_instance, state: DurableObjectState) => [...state.storage.sql.exec<{ d: string }>("SELECT drivers AS d FROM sessions WHERE runner_key = ?", key)][0]?.d);
+ return { computer, socket, frames, calls, key, first, say, delivered, drivers };
+}
+
+describe("computer session roles (work 112)", () => {
+ it("gates messages in an existing session: drivers with a role, participants held, outsiders dropped", async () => {
+ const s = await withSession("org_roles_gate", "T0ROLES1");
+ // The message that starts a session is unchanged: no role.
+ expect(s.first.msg.role).toBeUndefined();
+ expect(await s.drivers()).toBe("*");
+ expect((await s.delivered(await s.say("UGRACE", "and the tests"))).msg.role).toBe("driver");
+
+ // `!access owner`: the gateway's, never delivered; 🔒 on the thread, the state to the owner.
+ const restricted = await s.say("UADA", "!access owner");
+ await until(s.drivers, (d) => d === "[]", "restricted");
+ await until(s.calls, (all) => all.some((c) => c.method === "chat.postEphemeral" && c.body.text === stateText({ owner: "UADA", drivers: [] })), "the state");
+ expect((await s.calls()).filter((c) => c.method === "reactions.add" && c.body.name === "lock")).toEqual([
+ { method: "reactions.add", body: { channel: "C1", timestamp: TS, name: "lock" } },
+ ]);
+
+ const held = await s.say("UGRACE", "the logs say 503");
+ const dropped = await s.say("UGUEST", "ship it", { mention: true });
+ const next = await s.delivered(await s.say("UADA", "go on"));
+ expect(next.msg.role).toBe("owner");
+ expect(next.msg.linked).toMatchObject([{ context: true, messages: [{ ts: held, text: "the logs say 503" }] }]);
+ expect(s.frames.filter((f) => f.t === "deliver" && [restricted, held, dropped].includes(f.msg.ts))).toEqual([]);
+ expect((await s.calls()).filter((c) => c.method === "chat.postEphemeral" && c.body.user === "UGUEST").map((c) => c.body.text)).toEqual([onlyMembersText()]);
+ s.socket.close();
+ });
+
+ it("stop: an outsider's is ignored, a participant's stops and names them", async () => {
+ const s = await withSession("org_roles_stop", "T0ROLES2");
+ await s.say("UADA", "!access owner");
+ await until(s.drivers, (d) => d === "[]", "restricted");
+ expect(await s.computer.slackStop("org_roles_stop", "C1", TS, "UGUEST")).toEqual({ delivered: false });
+ expect(s.frames.filter((f) => f.t === "stop")).toEqual([]);
+ expect(await s.computer.slackStop("org_roles_stop", "C1", TS, "UGRACE")).toEqual({ delivered: true });
+ expect(s.frames.filter((f) => f.t === "stop")).toHaveLength(1);
+ expect((await s.calls()).filter((c) => c.method === "chat.postMessage" && c.body.text === stoppedText("UGRACE"))).toHaveLength(1);
+ 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.)
+ await s.say("UADA", "!access owner");
+ await until(s.drivers, (d) => d === "[]", "restricted");
+ const id = crypto.randomUUID();
+ s.socket.send(JSON.stringify({ t: "spawn", id, from: s.key, req: { task: "Port it", brief: "b.md" } }));
+ const spawned = await until(() => s.frames.find((f) => f.t === "spawned" && f.id === id), (found) => !!found, "spawned");
+ const child = await runInDurableObject(s.computer, (_instance, state: DurableObjectState) =>
+ [...state.storage.sql.exec<{ d: string }>("SELECT drivers AS d FROM sessions WHERE runner_key = ?", spawned.result.key)][0]?.d,
+ );
+ expect(child).toBe("[]");
+ s.socket.close();
+ });
+});
diff --git a/services/managed-agents/test/computer-access-flow.test.ts b/services/managed-agents/test/computer-access-flow.test.ts
new file mode 100644
index 00000000..93489d3a
--- /dev/null
+++ b/services/managed-agents/test/computer-access-flow.test.ts
@@ -0,0 +1,318 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ driversCommandText,
+ grantedText,
+ notAskedText,
+ onlyGrantorAnswersText,
+ onlyMembersText,
+ openedText,
+ ownerCommandText,
+ ownerDecidesText,
+ requestSentText,
+ requestText,
+ stoppedText,
+} 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";
+
+const ctx = (h: ReturnType<typeof accessHarness>) => h.store.held(KEY);
+const owner = { id: OWNER, admin: false };
+
+describe("session roles: messages (work 112)", () => {
+ it("a participant's message is held as context and not delivered", async () => {
+ const h = accessHarness([]);
+ const gate = await send(h, h.job(A, "the logs say 503", { files: [{ id: "F1", name: "log.txt" }] }));
+ expect(gate).toEqual({ deliver: false, reason: "held" });
+ expect(h.delivered).toEqual([]);
+ expect(ctx(h)).toMatchObject([{ userId: A, text: "the logs say 503", files: ["log.txt"] }]);
+ // Not a mention: nothing is posted.
+ expect(h.calls.filter((c) => c.method !== "users.info")).toEqual([]);
+ });
+
+ it("an outsider's message is dropped and never reaches context; a mention answers S14", async () => {
+ const h = accessHarness("*");
+ expect(await send(h, h.job(GUEST, "hi"))).toEqual({ deliver: false, reason: "outsider" });
+ expect(await send(h, h.job(STRANGER, "do it", { mentioned: true }))).toEqual({ deliver: false, reason: "outsider" });
+ expect(ctx(h)).toEqual([]);
+ expect(h.delivered).toEqual([]);
+ expect(h.ephemerals(GUEST)).toEqual([]);
+ expect(h.ephemerals(STRANGER)).toEqual([onlyMembersText()]);
+ });
+
+ it("a participant's first mention posts S1 once with its buttons and answers S2; a second answers S2b and posts nothing", async () => {
+ const h = accessHarness([]);
+ await send(h, h.job(A, "please fix it", { mentioned: true }));
+ const [post] = h.of("chat.postMessage");
+ expect(post).toMatchObject({ channel: "C1", thread_ts: "100.1", text: requestText(OWNER, A) });
+ const buttons = (post!.blocks as Array<{ elements?: Array<{ action_id: string }> }>)[1]!.elements!.map((e) => e.action_id);
+ expect(buttons).toEqual([encodeAccessId(KEY, "allow", A), encodeAccessId(KEY, "deny", A)]);
+ expect(h.ephemerals(A)).toEqual([requestSentText(OWNER)]);
+ expect(h.store.request(KEY, A)).toMatchObject({ state: "open", messageTs: "300.1" });
+ await send(h, h.job(A, "hello?", { mentioned: true }));
+ expect(h.of("chat.postMessage")).toHaveLength(1);
+ expect(h.ephemerals(A)).toEqual([requestSentText(OWNER), ownerDecidesText(OWNER)]);
+ // Both are context.
+ 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 () => {
+ 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([]);
+ });
+
+ it("held context rides the next driver message, oldest first with names, and is deleted after", async () => {
+ const h = accessHarness([]);
+ await send(h, h.job(A, "first"));
+ await send(h, h.job(B, "second"));
+ await send(h, h.job(OWNER, "go"));
+ expect(h.delivered).toHaveLength(1);
+ expect(h.delivered[0]).toMatchObject({ userId: OWNER, role: "owner" });
+ expect(h.delivered[0]!.linked).toEqual([
+ {
+ url: "",
+ ok: true,
+ where: "",
+ context: true,
+ messages: [
+ { name: `name-${A}`, ts: expect.any(String), text: "first" },
+ { name: `name-${B}`, ts: expect.any(String), text: "second" },
+ ],
+ },
+ ]);
+ expect(ctx(h)).toEqual([]);
+ await send(h, h.job(OWNER, "again"));
+ expect(h.delivered[1]!.linked).toBeUndefined();
+ });
+
+ it("a failed delivery keeps the context for the next message", async () => {
+ const h = accessHarness([]);
+ await send(h, h.job(A, "note"));
+ h.failDelivery = true;
+ await expect(send(h, h.job(OWNER, "go"))).rejects.toThrow("hub down");
+ expect(ctx(h).map((m) => m.text)).toEqual(["note"]);
+ h.failDelivery = false;
+ await send(h, h.job(OWNER, "go"));
+ expect(h.delivered[0]!.linked).toHaveLength(1);
+ expect(ctx(h)).toEqual([]);
+ });
+
+ it("a driver in an open session delivers with role driver", async () => {
+ const h = accessHarness("*");
+ expect(await send(h, h.job(A, "do it"))).toEqual({ deliver: true, role: "driver", context: true });
+ expect(h.delivered[0]).toMatchObject({ userId: A, role: "driver" });
+ });
+
+ it("`!mode` from a driver answers S7 and is not delivered", async () => {
+ const h = accessHarness("*");
+ expect(await send(h, h.job(A, "!mode plan"))).toEqual({ deliver: false, reason: "command_refused" });
+ expect(h.ephemerals(A)).toEqual([ownerCommandText(OWNER, "mode")]);
+ expect(h.delivered).toEqual([]);
+ });
+
+ it("other commands: S8 for a participant's `!diff`; `!stop` from a participant is delivered without context; nothing for an outsider's `!help`", async () => {
+ const h = accessHarness([]);
+ await send(h, h.job(B, "held"));
+ expect(await send(h, h.job(A, "!diff"))).toEqual({ deliver: false, reason: "command_refused" });
+ expect(h.ephemerals(A)).toEqual([driversCommandText("diff")]);
+ expect(await send(h, h.job(A, "!stop"))).toEqual({ deliver: true, role: "participant", context: false });
+ expect(h.delivered[0]).toMatchObject({ text: "!stop", role: "participant" });
+ expect(h.delivered[0]!.linked).toBeUndefined();
+ expect(ctx(h)).toHaveLength(1);
+ expect(await send(h, h.job(GUEST, "!help"))).toEqual({ deliver: false, reason: "command_refused" });
+ expect(h.ephemerals(GUEST)).toEqual([]);
+ });
+});
+
+describe("session roles: requests to drive (work 112)", () => {
+ async function requested() {
+ const h = accessHarness([]);
+ await send(h, h.job(A, "please fix it", { mentioned: true, messageTs: "250.1" }));
+ return h;
+ }
+
+ it("Allow by anyone who cannot grant answers S5 and changes nothing, the requester included", async () => {
+ const h = await requested();
+ await h.flow.answerRequest(KEY, "allow", A, A);
+ await h.flow.answerRequest(KEY, "allow", A, B);
+ expect(h.ephemerals(A).at(-1)).toBe(onlyGrantorAnswersText(OWNER));
+ expect(h.ephemerals(B)).toEqual([onlyGrantorAnswersText(OWNER)]);
+ expect(h.store.drivers(KEY)).toEqual([]);
+ expect(h.store.request(KEY, A)?.state).toBe("open");
+ 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 () => {
+ 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).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]!.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);
+ });
+
+ it("Allow by an admin who is not the owner says so", async () => {
+ const h = await requested();
+ await h.flow.answerRequest(KEY, "allow", A, ADMIN);
+ expect(h.of("chat.update")[0]!.text).toBe(grantedText({ id: ADMIN, admin: true }, [A], OWNER));
+ expect(h.changes).toEqual([{ key: KEY, by: { id: ADMIN, admin: true }, from: "[]", to: `["${A}"]` }]);
+ });
+
+ it("Not now closes the request, edits it to S4, keeps the message as context; a later mention answers S2b", async () => {
+ const h = await requested();
+ await h.flow.answerRequest(KEY, "deny", A, OWNER);
+ expect(h.store.request(KEY, A)?.state).toBe("closed");
+ expect(h.of("chat.update")).toEqual([{ channel: "C1", ts: "300.1", ...declinedPost(A) }]);
+ expect(ctx(h).map((m) => m.text)).toEqual(["please fix it"]);
+ await send(h, h.job(A, "again", { mentioned: true }));
+ expect(h.ephemerals(A).at(-1)).toBe(ownerDecidesText(OWNER));
+ expect(h.of("chat.postMessage")).toHaveLength(1);
+ expect(h.store.drivers(KEY)).toEqual([]);
+ });
+
+ it("opening the session answers open requests and delivers their messages", async () => {
+ const h = await requested();
+ await h.flow.setDrivers(KEY, "*", owner);
+ expect(h.store.request(KEY, A)?.state).toBe("closed");
+ expect(h.delivered).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);
+ 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);
+ 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([]);
+ expect(h.changes).toEqual([{ key: KEY, by: owner, from: "*", to: JSON.stringify([A, B]) }]);
+ });
+
+ it("opening a restricted session removes the marker and posts S3b", async () => {
+ const h = accessHarness([]);
+ 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);
+ expect(h.posts()).toEqual([grantedText(owner, [ADMIN, B], 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("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);
+ h.answers.set("reactions.remove", { ok: false, error: "missing_scope" });
+ await h.flow.setDrivers(KEY, "*", owner);
+ expect(h.store.drivers(KEY)).toBe("*");
+ expect(h.changes).toHaveLength(2);
+ });
+});
+
+describe("session roles: new sessions (work 112)", () => {
+ it("a new session under accessDefault = owner is [] with a marker; under the default it is open with none", async () => {
+ const h = accessHarness();
+ h.store.setAccessDefault("owner");
+ h.addSession("T1:C1:500.1", OWNER, "500.1");
+ h.flow.start("T1:C1:500.1");
+ await h.settle();
+ expect(h.store.drivers("T1:C1:500.1")).toEqual([]);
+ expect(h.of("reactions.add")).toEqual([{ channel: "C1", timestamp: "500.1", name: "lock" }]);
+ h.store.setAccessDefault("open");
+ h.addSession("T1:C1:600.1", OWNER, "600.1");
+ h.flow.start("T1:C1:600.1");
+ await h.settle();
+ expect(h.store.drivers("T1:C1:600.1")).toBe("*");
+ expect(h.of("reactions.add")).toHaveLength(1);
+ });
+
+ it("a spawned session copies its parent's drivers, not the default", async () => {
+ const h = accessHarness([A]);
+ h.addSession("T1:C1:700.1", OWNER, "700.1");
+ h.flow.start("T1:C1:700.1", KEY);
+ await h.settle();
+ expect(h.store.drivers("T1:C1:700.1")).toEqual([A]);
+ expect(h.of("reactions.add")).toEqual([{ channel: "C1", timestamp: "700.1", name: "lock" }]);
+ });
+});
+
+describe("session roles: stop and prompts (work 112)", () => {
+ it("stop by an outsider is ignored; by a participant it stops and posts S9; by the owner or without a user it posts nothing", async () => {
+ const h = accessHarness([]);
+ const stops: string[] = [];
+ const stop = (who: string) => () => (stops.push(who), true);
+ expect(await h.flow.stop(SESSION, GUEST, stop(GUEST))).toBe(false);
+ expect(await h.flow.stop(SESSION, A, stop(A))).toBe(true);
+ expect(await h.flow.stop(SESSION, OWNER, stop(OWNER))).toBe(true);
+ expect(await h.flow.stop(SESSION, undefined, stop("nobody"))).toBe(true);
+ expect(stops).toEqual([A, OWNER, "nobody"]);
+ expect(h.posts()).toEqual([stoppedText(A)]);
+ });
+
+ it("a stop the hub did not take posts nothing", async () => {
+ const h = accessHarness([]);
+ expect(await h.flow.stop(SESSION, A, () => false)).toBe(false);
+ expect(h.posts()).toEqual([]);
+ });
+
+ it("a prompt click needs answer: a participant gets S6 and nothing is sent; a driver's frame carries their role", async () => {
+ const h = accessHarness([B]);
+ const sent: Array<string | undefined> = [];
+ const frame = (role?: string) => (sent.push(role), `id-${sent.length}`);
+ await h.flow.answer(KEY, A, frame);
+ expect(sent).toEqual([]);
+ expect(h.ephemerals(A)).toEqual([notAskedText(OWNER)]);
+ await h.flow.answer(KEY, B, frame);
+ await h.flow.answer(KEY, OWNER, frame);
+ expect(sent).toEqual(["driver", "owner"]);
+ // The runner refused B's click: S6 to B; the owner's passed.
+ await h.flow.answered("id-1", "not-asked");
+ await h.flow.answered("id-2", undefined);
+ expect(h.ephemerals(B)).toEqual([notAskedText(OWNER)]);
+ expect(h.ephemerals(OWNER)).toEqual([]);
+ });
+
+ it("a prompt in a session with no owner is sent as before, without a role", async () => {
+ const h = accessHarness();
+ const sent: Array<string | undefined> = [];
+ await h.flow.answer("T1:C9:1.1", A, (role) => (sent.push(role), "x"));
+ expect(sent).toEqual([undefined]);
+ });
+});
diff --git a/services/managed-agents/test/computer-access-store.test.ts b/services/managed-agents/test/computer-access-store.test.ts
new file mode 100644
index 00000000..ca5a9849
--- /dev/null
+++ b/services/managed-agents/test/computer-access-store.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+
+import { CONTEXT_MAX_AGE_MS, CONTEXT_MAX_CHARS, CONTEXT_MAX_ROWS } from "../src/computer/access.js";
+import { AccessStore } from "../src/computer/access-store.js";
+import { sqlStorage } from "./fixtures/computer-sql.js";
+
+function store() {
+ const sql = sqlStorage();
+ sql.exec(`
+ CREATE TABLE sessions (runner_key TEXT PRIMARY KEY, owner_id TEXT);
+ CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ `);
+ // A session from before work 112.
+ sql.exec("INSERT INTO sessions (runner_key, owner_id) VALUES ('k', 'U1')");
+ return { sql, store: new AccessStore(sql) };
+}
+
+describe("session roles: the store (work 112)", () => {
+ it("adds the column once: older sessions read '*', a second instance changes nothing", () => {
+ const { sql, store: s } = store();
+ expect(s.drivers("k")).toBe("*");
+ expect(s.drivers("missing")).toBeUndefined();
+ s.writeDrivers("k", ["U2"]);
+ new AccessStore(sql);
+ expect(s.drivers("k")).toEqual(["U2"]);
+ });
+
+ it("the default is open until set", () => {
+ const { store: s } = store();
+ expect(s.accessDefault()).toBe("open");
+ s.setAccessDefault("owner");
+ expect(s.accessDefault()).toBe("owner");
+ });
+
+ it("context: text cut, the newest rows oldest first with how many were skipped, old rows deleted", () => {
+ const { store: s } = store();
+ const now = 10 * CONTEXT_MAX_AGE_MS;
+ s.hold("k", { userId: "U2", ts: "old", text: "stale", files: [] }, now - CONTEXT_MAX_AGE_MS - 1);
+ s.hold("k", { userId: "U2", ts: "big", text: "x".repeat(CONTEXT_MAX_CHARS + 10), files: ["a.png"] }, now);
+ for (let i = 0; i < CONTEXT_MAX_ROWS + 1; i++) s.hold("k", { userId: "U3", ts: `t${i}`, text: `m${i}`, files: [] }, now);
+ const held = s.held("k", now);
+ expect(held).toHaveLength(CONTEXT_MAX_ROWS);
+ expect(held[0]).toMatchObject({ ts: "t1", skipped: 2 });
+ expect(held.at(-1)).toMatchObject({ ts: `t${CONTEXT_MAX_ROWS}` });
+ expect(held.filter((m) => m.skipped)).toHaveLength(1);
+ s.forget(held.map((m) => m.seq));
+ expect(s.held("k", now)).toMatchObject([{ ts: "big", files: ["a.png"], text: "x".repeat(CONTEXT_MAX_CHARS) }, { ts: "t0", files: [] }]);
+ s.forgetMessage("k", "big");
+ expect(s.held("k", now).map((m) => m.ts)).toEqual(["t0"]);
+ });
+
+ 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.closeRequest("k", "U2")).toBe(true);
+ expect(s.closeRequest("k", "U2")).toBe(false);
+ expect(s.request("k", "U2")?.state).toBe("closed");
+ expect(s.openRequests("k").map((r) => r.userId)).toEqual(["U3"]);
+ });
+});
diff --git a/services/managed-agents/test/computer-access-ui.test.ts b/services/managed-agents/test/computer-access-ui.test.ts
new file mode 100644
index 00000000..ac023bf6
--- /dev/null
+++ b/services/managed-agents/test/computer-access-ui.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ ACCESS_USAGE,
+ defaultChangedText,
+ noSessionText,
+ notMemberText,
+ onlyAdminDefaultText,
+ onlyGrantorChangesText,
+ pickSomeoneText,
+ stateText,
+ tooManyPeopleText,
+} from "../src/computer/access.js";
+import { ACCESS_VIEW, encodeAccessId } from "../src/computer/access-views.js";
+import { A, ADMIN, B, GUEST, KEY, OWNER, accessHarness } from "./fixtures/computer-access.js";
+
+const where = (userId: string) => ({ userId, channelId: "C1", threadTs: "100.1" });
+const inSession = (userId: string) => ({ ...where(userId), session: { key: KEY } });
+const blocksOf = (body: Record<string, unknown> | undefined) => (body?.blocks ?? []) as Array<{ type: string; elements?: Array<{ action_id: string }> }>;
+
+describe("session roles: !access (work 112)", () => {
+ it("shows the state to anyone who can view, with Change… only for someone who can grant", async () => {
+ const h = accessHarness([A]);
+ await h.ui.command("!access", inSession(B));
+ await h.ui.command("!access", inSession(OWNER));
+ const [participant, own] = h.of("chat.postEphemeral");
+ 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.
+ await h.ui.command("!access", inSession(GUEST));
+ expect(h.ephemerals(GUEST)).toEqual([onlyGrantorChangesText(OWNER)]);
+ });
+
+ it("open, owner, a list, add and remove change drivers through setDrivers and answer S10", async () => {
+ const h = accessHarness("*");
+ await h.ui.command(`!access @${A} @${B}`, inSession(OWNER));
+ expect(h.store.drivers(KEY)).toEqual([A, B]);
+ await h.ui.command(`!access remove @${A}`, inSession(OWNER));
+ expect(h.store.drivers(KEY)).toEqual([B]);
+ await h.ui.command(`!access add @${A}`, inSession(OWNER));
+ expect(h.store.drivers(KEY)).toEqual([A, B]);
+ await h.ui.command("!access owner", inSession(OWNER));
+ expect(h.store.drivers(KEY)).toEqual([]);
+ await h.ui.command("!access open", inSession(OWNER));
+ expect(h.store.drivers(KEY)).toBe("*");
+ expect(h.ephemerals(OWNER).at(-1)).toBe(stateText({ owner: OWNER, drivers: "*" }));
+ expect(h.changes).toHaveLength(5);
+ });
+
+ it("without grant: S11 and nothing changes; an admin may", async () => {
+ const h = accessHarness([A]);
+ await h.ui.command("!access open", inSession(A));
+ expect(h.ephemerals(A)).toEqual([onlyGrantorChangesText(OWNER)]);
+ expect(h.store.drivers(KEY)).toEqual([A]);
+ await h.ui.command("!access open", inSession(ADMIN));
+ expect(h.store.drivers(KEY)).toBe("*");
+ expect(h.changes[0]!.by).toEqual({ id: ADMIN, admin: true });
+ });
+
+ it("a named person who is not a member answers the member error and changes nothing", async () => {
+ const h = accessHarness([A]);
+ await h.ui.command(`!access add @${GUEST}`, inSession(OWNER));
+ expect(h.ephemerals(OWNER)).toEqual([notMemberText(`name-${GUEST}`)]);
+ expect(h.store.drivers(KEY)).toEqual([A]);
+ });
+
+ 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(" ");
+ await h.ui.command(`!access ${many}`, inSession(OWNER));
+ expect(h.ephemerals(OWNER)).toEqual([tooManyPeopleText()]);
+ expect(h.store.drivers(KEY)).toEqual([]);
+ });
+
+ it("any other form answers the usage", async () => {
+ const h = accessHarness();
+ await h.ui.command("!access everyone please", inSession(A));
+ expect(h.ephemerals(A)).toEqual([ACCESS_USAGE]);
+ });
+
+ it("outside a session: S12; the default needs an admin who is a member, and works anywhere", async () => {
+ const h = accessHarness();
+ await h.ui.command("!access", where(A));
+ expect(h.ephemerals(A)).toEqual([noSessionText()]);
+ await h.ui.command("!access default owner", where(OWNER));
+ expect(h.ephemerals(OWNER)).toEqual([onlyAdminDefaultText()]);
+ expect(h.store.accessDefault()).toBe("open");
+ await h.ui.command("!access default owner", { userId: ADMIN, channelId: "C2" });
+ expect(h.store.accessDefault()).toBe("owner");
+ const answer = h.of("chat.postEphemeral").at(-1);
+ expect(answer).toEqual({ channel: "C2", user: ADMIN, text: defaultChangedText("owner") });
+ });
+});
+
+describe("session roles: the modal (work 112)", () => {
+ const submission = (who: string, people: string[] = [], key = KEY) => ({
+ callback_id: ACCESS_VIEW,
+ private_metadata: JSON.stringify({ key }),
+ state: { values: { who: { v: { selected_option: { value: who } } }, people: { v: { selected_users: people } } } },
+ });
+
+ it("Access opens the grantor view for the owner, the read-only one for a participant, nothing for an outsider", async () => {
+ const h = accessHarness([A]);
+ const open = encodeAccessId(KEY, "open");
+ await h.ui.action(open, "trig", where(OWNER));
+ await h.ui.action(open, "trig", where(B));
+ await h.ui.action(open, "trig", where(GUEST));
+ const views = h.of("views.open") as Array<{ trigger_id: string; view: { callback_id: string; submit?: unknown } }>;
+ expect(views).toHaveLength(2);
+ expect(views[0]).toMatchObject({ trigger_id: "trig", view: { callback_id: ACCESS_VIEW, submit: { text: "Save" } } });
+ expect(views[1]!.view.submit).toBeUndefined();
+ });
+
+ it("Access for a session that is gone answers S12", async () => {
+ const h = accessHarness();
+ await h.ui.action(encodeAccessId("T1:C1:9.9", "open"), "trig", where(A));
+ expect(h.ephemerals(A)).toEqual([noSessionText()]);
+ });
+
+ it("a request's buttons come back as work for after the ack", async () => {
+ const h = accessHarness([]);
+ const r = await h.ui.action(encodeAccessId(KEY, "allow", A), "trig", where(B));
+ expect(h.calls).toEqual([]);
+ await r.after!();
+ // No request is open: B cannot grant, so S5.
+ expect(h.ephemerals(B)).toHaveLength(1);
+ });
+
+ it("Save re-checks grant, refuses nobody and non-members, then sets drivers", 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() } });
+ expect(h.store.drivers(KEY)).toBe("*");
+ const ok = await h.ui.submit(submission("people", [B, A, OWNER]), OWNER);
+ expect(ok.errors).toBeUndefined();
+ await ok.after!();
+ expect(h.store.drivers(KEY)).toEqual([A, B]);
+ // Nothing else is posted for a restriction.
+ expect(h.posts()).toEqual([]);
+ });
+});
diff --git a/services/managed-agents/test/computer-routes.test.ts b/services/managed-agents/test/computer-routes.test.ts
index 6b7974be..46684195 100644
--- a/services/managed-agents/test/computer-routes.test.ts
+++ b/services/managed-agents/test/computer-routes.test.ts
@@ -1003,7 +1003,8 @@ describe("computer routes", () => {
expect(off.welcome).not.toHaveProperty("wire");
expect(off.recorded).toBe(3);
expect(off.listed).toMatchObject({ status: 409, error: { code: "feature_unavailable", feature: "sessions" } });
- expect(off.deliver).toEqual(v3.deliver);
+ // (The baseline's message started the thread's session; this one is its owner's in it: work 112's `role`.)
+ expect(off.deliver).toEqual({ ...v3.deliver, msg: { ...v3.deliver.msg, role: "owner" } });
expect(off.deliver.session).not.toHaveProperty("sessionId");
expect(off.access).toEqual([]);
@@ -1015,7 +1016,7 @@ describe("computer routes", () => {
expect(on.deliver.session).toMatchObject({ key: v3.deliver.session.key, sessionId: expect.stringMatching(/^cs_/), origin: { type: "slack" } });
const { epoch, lastSeq, ...onRest } = on.deliver;
expect({ epoch, lastSeq }).toEqual({ epoch: 1, lastSeq: 0 });
- expect({ ...onRest, session: v3.deliver.session }).toEqual(v3.deliver);
+ expect({ ...onRest, session: off.deliver.session }).toEqual(off.deliver);
expect(off.deliver).not.toHaveProperty("epoch");
// Flipped back off: v3 again at the next hello, the API refuses again.
diff --git a/services/managed-agents/test/computer-threads.test.ts b/services/managed-agents/test/computer-threads.test.ts
index 336eaeae..dcdcccaa 100644
--- a/services/managed-agents/test/computer-threads.test.ts
+++ b/services/managed-agents/test/computer-threads.test.ts
@@ -183,9 +183,14 @@ describe("computer thread access", () => {
it("reads for a guest only when they are in the channel, and fails closed on an unknown person", async () => {
const s = await withSession("org_threads_guest", "T0TH5");
- expect((await s.say(`<${PUBLIC}>`, { user: "UGUEST" })).msg.linked[0]).toEqual({ url: PUBLIC, ok: false, reason: "a guest who asked is not in that channel" });
- expect((await s.say(`<${PUBLIC}>`, { user: "UGUESTIN" })).msg.linked[0]).toMatchObject({ ok: true });
- expect((await s.say(`<${PUBLIC}>`, { user: "UNOBODY" })).msg.linked[0]).toMatchObject({ ok: false, reason: "could not confirm who asked can see that channel" });
+ // Work 112: only full members drive someone else's session, so each starts a session of their own.
+ const own = async (user: string, ts: string) => {
+ await slackEvent(s.org, s.team, s.channel, { type: "app_mention", user, text: `<@UBOT> <${PUBLIC}>`, ts });
+ return until(() => s.frames.find((frame) => frame.t === "deliver" && frame.msg.ts === ts), (found) => !!found, `the delivery of ${ts}`);
+ };
+ expect((await own("UGUEST", "1700000101.000100")).msg.linked[0]).toEqual({ url: PUBLIC, ok: false, reason: "a guest who asked is not in that channel" });
+ expect((await own("UGUESTIN", "1700000102.000100")).msg.linked[0]).toMatchObject({ ok: true });
+ expect((await own("UNOBODY", "1700000103.000100")).msg.linked[0]).toMatchObject({ ok: false, reason: "could not confirm who asked can see that channel" });
s.socket.close();
});
diff --git a/services/managed-agents/test/computer-units.test.ts b/services/managed-agents/test/computer-units.test.ts
index 03f01455..0b47d013 100644
--- a/services/managed-agents/test/computer-units.test.ts
+++ b/services/managed-agents/test/computer-units.test.ts
@@ -342,6 +342,15 @@ describe("Slack", () => {
threadTs: "1.1",
eventId: "E",
});
+ // Work 112: who pressed stop.
+ expect(parseSlackEnvelope({ type: "event_callback", event_id: "E", team_id: "T", event: { type: "agent_session_stopped", channel: "C", thread_ts: "1.1", user: "U1" } })).toEqual({
+ kind: "stop",
+ teamId: "T",
+ channelId: "C",
+ threadTs: "1.1",
+ userId: "U1",
+ eventId: "E",
+ });
});
it("normalizes text: strips this app's mention, decodes, notices other mentions", () => {
diff --git a/services/managed-agents/test/fixtures/computer-access.ts b/services/managed-agents/test/fixtures/computer-access.ts
new file mode 100644
index 00000000..4a84235a
--- /dev/null
+++ b/services/managed-agents/test/fixtures/computer-access.ts
@@ -0,0 +1,116 @@
+import type { Drivers } from "../../src/computer/access.js";
+import { AccessFlow, type AccessDispatch } from "../../src/computer/access-flow.js";
+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 { sqlStorage } from "./computer-sql.js";
+
+/** People in the fake workspace: ids as Slack's (`!access` reads `@U…` with at least 7 characters). */
+export const OWNER = "UOWNER01";
+export const A = "UAAAAAA1";
+export const B = "UBBBBBB1";
+export const GUEST = "UGUEST01";
+export const STRANGER = "UEXTERN1";
+/** A full member linked to a dashboard admin. */
+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. */
+export function accessHarness(drivers: Drivers = "*") {
+ const sql = sqlStorage();
+ sql.exec(`
+ CREATE TABLE sessions (runner_key TEXT PRIMARY KEY, owner_id TEXT, channel_id TEXT NOT NULL, thread_ts TEXT NOT NULL);
+ CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ `);
+ const store = new AccessStore(sql);
+ const calls: Array<{ method: string; body: Record<string, unknown> }> = [];
+ const delivered: AccessDispatch[] = [];
+ const changes: Array<{ key: string; by: { id: string; admin: boolean }; from: string; to: string }> = [];
+ const pending: Promise<unknown>[] = [];
+ const h = {
+ sql,
+ store,
+ calls,
+ delivered,
+ 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,
+ ui: undefined as unknown as AccessUi,
+ addSession(key: string, owner: string, threadTs: string, d?: Drivers) {
+ sql.exec("INSERT INTO sessions (runner_key, owner_id, channel_id, thread_ts) VALUES (?, ?, 'C1', ?)", key, owner, threadTs);
+ if (d !== undefined) store.writeDrivers(key, d);
+ },
+ of(method: string) {
+ return calls.filter((c) => c.method === method).map((c) => c.body);
+ },
+ ephemerals(user: string) {
+ return calls.filter((c) => c.method === "chat.postEphemeral" && c.body.user === user).map((c) => c.body.text);
+ },
+ posts() {
+ return calls.filter((c) => c.method === "chat.postMessage").map((c) => c.body.text);
+ },
+ async settle() {
+ while (pending.length) await pending.shift();
+ },
+ job(userId: string, text: string, o: Partial<SlackMessageJob> = {}): SlackMessageJob {
+ return { eventId: `E${text}`, teamId: "T1", channelId: "C1", threadTs: "100.1", messageTs: `${200 + calls.length}.1`, userId, text, mentioned: false, receivedAt: 0, ...o };
+ },
+ };
+ let ts = 300;
+ const slack = async (method: string, body: Record<string, unknown>): Promise<SlackResult> => {
+ calls.push({ method, body });
+ const answer = h.answers.get(method);
+ if (answer) return answer;
+ if (method === "users.info") {
+ const user = String(body.user);
+ if (user === STRANGER) return { ok: true, user: { team_id: "T_OTHER" } };
+ return { ok: true, user: { team_id: "T1", is_restricted: user === GUEST } };
+ }
+ return { ok: true, ts: `${ts++}.1` };
+ };
+ h.flow = new AccessFlow({
+ store,
+ slack,
+ teamId: () => "T1",
+ 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 = ?",
+ key,
+ )][0];
+ return row?.owner ? { key, ownerId: row.owner, channelId: row.channelId, threadTs: row.threadTs } : undefined;
+ },
+ 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);
+ },
+ 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.addSession(KEY, OWNER, "100.1", drivers);
+ return h;
+}
+
+export type AccessHarness = ReturnType<typeof accessHarness>;
+
+/** A message through the gate and, when it passes, the delivery `process` makes. */
+export async function send(h: AccessHarness, job: SlackMessageJob, text = job.text) {
+ const gate = await h.flow.message(job, text, SESSION);
+ if (!gate.deliver) return gate;
+ const dispatch: AccessDispatch = { channelId: job.channelId, threadTs: job.threadTs, messageTs: job.messageTs, userId: job.userId, text: job.text, mentioned: job.mentioned, role: gate.role };
+ const deliver = async (d: AccessDispatch) => {
+ if (h.failDelivery) throw new Error("hub down");
+ h.delivered.push(d);
+ };
+ if (gate.context) await h.flow.deliver(KEY, dispatch, deliver);
+ else await deliver(dispatch);
+ return gate;
+}
diff --git a/services/managed-agents/vitest.config.ts b/services/managed-agents/vitest.config.ts
index 71ca8b8d..7c407047 100644
--- a/services/managed-agents/vitest.config.ts
+++ b/services/managed-agents/vitest.config.ts
@@ -269,7 +269,7 @@ export default defineConfig({
],
test: {
name: "computer",
- include: ["test/computer-routes.test.ts", "test/computer-operator.test.ts", "test/computer-pool-probe-do.test.ts", "test/computer-agent-routes.test.ts", "test/computer-size.test.ts", "test/computer-self-managed.test.ts", "test/computer-spawn.test.ts", "test/computer-threads.test.ts", "test/computer-queue.test.ts", "test/computer-disk.test.ts", "test/computer-model-access-do.test.ts", "test/computer-model-profiles-do.test.ts", "test/computer-hosted-do.test.ts"],
+ include: ["test/computer-routes.test.ts", "test/computer-operator.test.ts", "test/computer-pool-probe-do.test.ts", "test/computer-agent-routes.test.ts", "test/computer-size.test.ts", "test/computer-self-managed.test.ts", "test/computer-spawn.test.ts", "test/computer-threads.test.ts", "test/computer-queue.test.ts", "test/computer-disk.test.ts", "test/computer-model-access-do.test.ts", "test/computer-model-profiles-do.test.ts", "test/computer-hosted-do.test.ts", "test/computer-access-do.test.ts"],
},
},
{
@@ -502,6 +502,7 @@ export default defineConfig({
"test/computer-connect-codes.test.ts",
"test/computer-units.test.ts",
"test/computer-access.test.ts",
+ "test/computer-access-store.test.ts", "test/computer-access-flow.test.ts", "test/computer-access-ui.test.ts",
"test/session-fold.test.ts",
"test/computer-calvin-contract.test.ts",
"test/computer-telemetry.test.ts",