Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Preserve delegated Slack behavior and deliver approvals through the runtime (#1586)

Regan Bellab7866728098
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index f2bd12c59..2fc9101af 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -1,5 +1,6 @@
+import type { Run } from "../runs/run-store.ts";
import { userRuntimeConfigBody } from "./runtime-config.ts";
-import { isSubagentThreadRef } from "../sessions/session-syscalls.ts";
+import { isSubagentThreadRef, stopSessionTree } from "../sessions/session-syscalls.ts";
import type { Conversation, Principal, TurnRequest, TurnResult } from "../types.ts";
import { orgId as orgIdOf } from "../config.ts";
import { scopeId } from "../types.ts";
@@ -60,6 +61,7 @@ export function createTurnMethods(
| "subscribeRun"
| "syncRunStream"
| "activeRunForThread"
+ | "stopConversation"
| "withdrawRun"
| "editQueuedRun"
| "signalRun"
@@ -79,6 +81,18 @@ export function createTurnMethods(
replayOrphanedRunSignals,
} = h;
const { shouldRouteToSpine, markTriggerHandled, addressedWakeText } = ambient;
+ async function stopRunTree(run: Run): Promise<boolean> {
+ if (!deps.signals) return false;
+ const signals = deps.signals;
+ const stop = async () => {
+ const session = await deps.sessions.getByThread(run.sessionId);
+ if (session) return stopSessionTree({ sessions: deps.sessions, runs: deps.runs, signals }, session);
+ await signals.send(run.id, { kind: "abort" });
+ if (run.status === "pending") await deps.runs.withdraw(run.id);
+ return true;
+ };
+ return deps.advisoryLock ? deps.advisoryLock.withLock("session-tree-admission", stop) : stop();
+ }
return {
async turn(req: TurnRequest, replay?: { signalDedupKey: string }): Promise<TurnResult> {
const startedAt = performance.now();
@@ -462,7 +476,9 @@ export function createTurnMethods(
const steerTs = origin.kind === "human" ? (origin.messageTs ?? origin.entryTs) : origin.entryTs;
let redelivered = false;
const routedRunId = await withCurrentProjectRoster(async () => {
- if (route.kind === "steer")
+ if (route.kind === "steer" && route.signal === "abort") {
+ await stopRunTree(targetRun);
+ } else if (route.kind === "steer")
redelivered = !(await deps.signals!.send(targetRun.id, {
kind: route.signal,
...(route.text ? { text: route.text } : {}),
@@ -690,6 +706,15 @@ export function createTurnMethods(
};
},
+ async stopConversation(threadRef, viewer) {
+ const stop = async () => {
+ const session = await deps.sessions.getByThread(threadRef);
+ if (!session || !deps.signals || (viewer && !(await sessionForViewer(session.id, viewer)))) return false;
+ return stopSessionTree({ sessions: deps.sessions, runs: deps.runs, signals: deps.signals }, session);
+ };
+ return deps.advisoryLock ? deps.advisoryLock.withLock("session-tree-admission", stop) : stop();
+ },
+
async activeRunForThread(threadRef, viewer) {
const inFlight = await deps.runs.inFlightForThread(threadRef);
const visible: typeof inFlight = [];
@@ -740,6 +765,10 @@ export function createTurnMethods(
: undefined;
if (queuedKey && (await deps.signals.hasDedupeKey(queuedKey))) return { accepted: true };
if (isTerminal(run.status)) return { accepted: false, reason: "terminal" };
+ if (signal.kind === "abort") {
+ const accepted = await stopRunTree(run);
+ return accepted ? { accepted: true } : { accepted: false, reason: "terminal" };
+ }
if (signal.queuedRunId) {
const queued = await deps.runs.get(signal.queuedRunId);
if (!queued || (viewer && !(await viewerMayUseRun(queued, viewer))))
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 6d49876da..3331fd565 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -300,6 +300,7 @@ export interface App {
startedAt: number | null;
finishedAt: number | null;
} | null>;
+ stopConversation(threadRef: string, viewer?: string): Promise<boolean>;
activeRunForThread(
threadRef: string,
viewer?: string,
diff --git a/src/api/routes/pins.ts b/src/api/routes/pins.ts
index ee78d3ca4..f497a386d 100644
--- a/src/api/routes/pins.ts
+++ b/src/api/routes/pins.ts
@@ -1,8 +1,9 @@
+import { isSubagentThreadRef, sessionTreeRoot } from "../../sessions/session-syscalls.ts";
import { sendJson } from "../http.ts";
import { isObj } from "./shared.ts";
import { type ApiCtx, type Route } from "./route.ts";
-function conversationRef(ctx: ApiCtx): string | null {
+async function conversationRef(ctx: ApiCtx): Promise<string | null> {
const { res, capability } = ctx;
if (!capability) {
sendJson(res, 401, { error: "capability_required", message: "this endpoint is for the agent self-API" });
@@ -12,12 +13,24 @@ function conversationRef(ctx: ApiCtx): string | null {
sendJson(res, 400, { error: "no_conversation", message: "this token isn't bound to a conversation" });
return null;
}
- return capability.threadRef;
+ if (!isSubagentThreadRef(capability.threadRef)) return capability.threadRef;
+ const sessions = ctx.deps.sessions;
+ const session = await sessions?.getByThread(capability.threadRef);
+ const root = session && sessions ? await sessionTreeRoot(sessions, session) : null;
+ if (
+ !root ||
+ root.scopeId !== capability.scopeId ||
+ !(await sessions!.getForParticipant(root.id, capability.actorId))
+ ) {
+ sendJson(res, 403, { error: "forbidden", message: "the originating conversation is no longer accessible" });
+ return null;
+ }
+ return root.threadRef;
}
async function addPin(ctx: ApiCtx): Promise<void> {
const { res, app, body, capability } = ctx;
- const threadRef = conversationRef(ctx);
+ const threadRef = await conversationRef(ctx);
if (!threadRef) return;
const b = isObj(body) ? body : {};
const text = typeof b.text === "string" && b.text.trim() ? b.text.trim() : undefined;
@@ -50,7 +63,7 @@ async function addPin(ctx: ApiCtx): Promise<void> {
async function listPins(ctx: ApiCtx): Promise<void> {
const { res, app, capability } = ctx;
- const threadRef = conversationRef(ctx);
+ const threadRef = await conversationRef(ctx);
if (!threadRef) return;
const pins = await app.listConversationPins(threadRef, capability!.actorId);
if (pins === null) return sendJson(res, 404, { error: "not_found", message: "no such conversation" });
@@ -59,7 +72,7 @@ async function listPins(ctx: ApiCtx): Promise<void> {
async function removePin(ctx: ApiCtx): Promise<void> {
const { res, app } = ctx;
- const threadRef = conversationRef(ctx);
+ const threadRef = await conversationRef(ctx);
if (!threadRef) return;
const removed = await app.unpinConversationItem(threadRef, ctx.params.id!);
if (removed === null) return sendJson(res, 404, { error: "not_found", message: "no such conversation" });
diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.ts
index 0b9954ad3..5e7d19359 100644
--- a/src/api/slack-core-client.ts
+++ b/src/api/slack-core-client.ts
@@ -14,6 +14,7 @@ import type { ErrorLog } from "../admin/error-log.ts";
import { createNoopLeaderLease, type LeaderLease } from "../persistence/leader-lease.ts";
import type {
Delivery,
+ PendingApproval,
ScopeId,
SurfaceContextRequest,
SurfaceContextResult,
@@ -67,12 +68,9 @@ export interface SlackAgentRequestContext {
approvalRequestIds?: string[];
}
-interface StoredApprovalView {
- requestId: string;
- command: string;
+interface StoredApprovalView extends Omit<PendingApproval, "reason"> {
+ createdAt?: number;
reason?: string;
- purpose?: string;
- summary?: string;
request?: Record<string, unknown>;
}
@@ -113,6 +111,7 @@ export interface SlackCoreClient {
waitRun(runId: string, hooks?: SlackRunHooks): Promise<TurnResult | null>;
activeRunForThread(threadRef: string): Promise<string | undefined>;
signalRunAbort(runId: string): Promise<void>;
+ stopConversation(threadRef: string): Promise<boolean>;
ackRunDelivery(runId: string): Promise<void>;
reportTurnMetrics(runId: string, patch: { deliverMs?: number; slackInflightMs?: number }): Promise<void>;
reportRunEditRef(runId: string, editRef: string): Promise<void>;
@@ -419,6 +418,10 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien
return (await deps.app.activeRunForThread(threadRef))?.runId;
},
+ stopConversation(threadRef) {
+ return deps.app.stopConversation(threadRef);
+ },
+
async signalRunAbort(runId) {
const outcome = await deps.app.signalRun(runId, { kind: "abort" });
if (!outcome.accepted) throw new Error(`signal abort not accepted: ${outcome.reason ?? "unknown"}`);
@@ -442,10 +445,14 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien
if (!record) return null;
return {
requestId: record.requestId,
+ ...(record.createdAt !== undefined ? { createdAt: record.createdAt } : {}),
command: record.command,
...(record.reason !== undefined ? { reason: record.reason } : {}),
...(record.purpose !== undefined ? { purpose: record.purpose } : {}),
...(record.summary !== undefined ? { summary: record.summary } : {}),
+ ...(record.summaryDetail !== undefined ? { summaryDetail: record.summaryDetail } : {}),
+ ...(record.grantModes !== undefined ? { grantModes: record.grantModes } : {}),
+ ...(record.kind !== undefined ? { kind: record.kind } : {}),
...(record.request !== undefined ? { request: record.request as unknown as Record<string, unknown> } : {}),
};
},
diff --git a/src/core/approval-store.ts b/src/core/approval-store.ts
new file mode 100644
index 000000000..f446a0b13
--- /dev/null
+++ b/src/core/approval-store.ts
@@ -0,0 +1,34 @@
+import { swallowAs } from "../util/errors.ts";
+import type { PendingApprovalRecord } from "../types.ts";
+import type { DurableMap } from "../persistence/durable-map.ts";
+import type { DeliveryStore } from "../delivery/delivery-store.ts";
+import { principalDestination } from "../reach/reach.ts";
+
+export function approvalDeliveryKey(id: string, record: Pick<PendingApprovalRecord, "createdAt">): string {
+ return `command-approval:${id}:${record.createdAt ?? 0}`;
+}
+
+export function createApprovalStore(
+ backing: DurableMap<PendingApprovalRecord>,
+ deliveries: Pick<DeliveryStore, "enqueue">,
+) {
+ async function deliver(id: string, record: PendingApprovalRecord): Promise<void> {
+ if (record.request?.surface !== "slack") return;
+ const actorId = record.request.actor.externalId;
+ await deliveries.enqueue({
+ destination: { ...principalDestination(actorId, actorId), commandApprovalId: id },
+ text: `Approval needed: ${record.summary ?? record.command}`,
+ idempotencyKey: approvalDeliveryKey(id, record),
+ });
+ }
+ return {
+ ...backing,
+ async put(id: string, record: PendingApprovalRecord): Promise<void> {
+ await backing.put(id, record);
+ await deliver(id, record).catch(swallowAs("approvals: enqueue delivery", undefined));
+ },
+ async deliverPending(): Promise<void> {
+ for (const [id, record] of await backing.entries()) await deliver(id, record);
+ },
+ };
+}
diff --git a/src/sessions/session-syscalls.ts b/src/sessions/session-syscalls.ts
index b187bd19d..5099b1483 100644
--- a/src/sessions/session-syscalls.ts
+++ b/src/sessions/session-syscalls.ts
@@ -1,3 +1,6 @@
+import { principalDestination } from "../reach/reach.ts";
+import type { DeliveryStore } from "../delivery/delivery-store.ts";
+import { deliveryCandidatesFor } from "../core/orchestrator/turn-helpers.ts";
import type { SessionMailbox, SessionMessage } from "./session-mailbox.ts";
import { conversationScope } from "../resolution/resolution-service.ts";
import { sleep } from "../util/async.ts";
@@ -205,8 +208,8 @@ export interface SessionSyscallDeps {
| "visibleEntries"
| "getForParticipant"
>;
- runs: Pick<RunStore, "enqueue" | "inFlightForThread" | "latestForThread" | "getByDedupKey">;
- signals: Pick<RunSignalStore, "send">;
+ runs: Pick<RunStore, "enqueue" | "inFlightForThread" | "latestForThread" | "getByDedupKey" | "get" | "withdraw">;
+ signals: Pick<RunSignalStore, "send" | "pending">;
maxAttempts: number;
treeRunCap?: number;
advisoryLock?: AdvisoryLock;
@@ -291,10 +294,15 @@ function childRunRequest(child: Session, meta: SpawnMeta, text: string, displayT
...(meta.scopeVersion ? { scopeVersion: meta.scopeVersion } : {}),
...(meta.sessionParticipantIds ? { sessionParticipantIds: meta.sessionParticipantIds } : {}),
surface: meta.surface,
+ ...(meta.deliveryTarget ? { deliveryTarget: meta.deliveryTarget } : {}),
+ ...(meta.deliveryCandidates ? { deliveryCandidates: meta.deliveryCandidates } : {}),
actor: meta.actor,
conversation: { ...meta.conversation, threadRef: child.threadRef },
origin: {
kind: "automation",
+ ...(meta.origin?.kind === "automation" && meta.origin.destination
+ ? { destination: meta.origin.destination }
+ : {}),
...(meta.origin?.kind === "automation" && meta.origin.useOwnerKeychain ? { useOwnerKeychain: true } : {}),
screenData: text,
},
@@ -349,6 +357,44 @@ async function treeSessions(sessions: Pick<SessionStore, "childrenOf">, root: Se
return all;
}
+async function sessionRunCancelled(
+ runs: Pick<RunStore, "get">,
+ signals: Pick<RunSignalStore, "pending">,
+ runId: string | undefined,
+): Promise<boolean> {
+ const seen = new Set<string>();
+ while (runId) {
+ if (seen.has(runId)) return true;
+ seen.add(runId);
+ const run = await runs.get(runId);
+ if (!run) return true;
+ if (run.result?.stopped || (await signals.pending(runId)).some(({ signal }) => signal.kind === "abort"))
+ return true;
+ runId = run.request.delegatingRunId;
+ }
+ return false;
+}
+
+export async function stopSessionTree(
+ deps: {
+ sessions: Pick<SessionStore, "childrenOf">;
+ runs: Pick<RunStore, "inFlightForThread" | "withdraw" | "get">;
+ signals: Pick<RunSignalStore, "send">;
+ },
+ root: Session,
+): Promise<boolean> {
+ let stopped = false;
+ for (const session of await treeSessions(deps.sessions, root)) {
+ if (session.scopeId !== root.scopeId) continue;
+ for (const run of await deps.runs.inFlightForThread(session.threadRef)) {
+ await deps.signals.send(run.id, { kind: "abort" });
+ if (run.status === "pending") await deps.runs.withdraw(run.id);
+ stopped = true;
+ }
+ }
+ return stopped;
+}
+
export async function sessionTreeRunCount(
sessions: Pick<SessionStore, "childrenOf">,
runs: Pick<RunStore, "inFlightForThread">,
@@ -410,6 +456,9 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscalls
}
async function currentCaller(): Promise<OrchestratorInput> {
+ binding.request.cancel?.throwIfAborted();
+ if (await sessionRunCancelled(deps.runs, deps.signals, binding.request.runId))
+ throw new Error("this delegated task was stopped");
if (deps.enabled && !(await deps.enabled(binding.request.actor.id)))
throw new Error("persistent subagents are not enabled for this user");
const current = await deps.sessions.get(binding.session.id);
@@ -628,20 +677,15 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscalls
const request = deps.prepareRequest ? await deps.prepareRequest(prepared) : prepared;
assertAudienceCompatible(caller, request);
const title = target.title?.trim() || target.id;
- const inFlight = await deps.runs.inFlightForThread(target.threadRef);
- const running = inFlight.find((r) => r.status === "running");
if (input.interrupt) {
if (privateMessage)
return { ok: false, message: "ordinary sessions accept private messages, not interrupts" };
- if (caller.readOnly && !running?.request.readOnly)
- return { ok: false, message: "a read-only session cannot interrupt a writable turn" };
- if (!running)
- return {
- ok: false,
- message: `subagent "${title}" is not running — nothing to interrupt. Use followup_task to assign new work.`,
- };
- await deps.signals.send(running.id, { kind: "abort" });
- return { ok: true, sessionId: target.id, title, delivered: "interrupted" };
+ if (caller.readOnly && !target.spawnMeta?.readOnly)
+ return { ok: false, message: "a read-only session cannot interrupt a writable task" };
+ const stopped = await stopSessionTree(deps, target);
+ return stopped
+ ? { ok: true, sessionId: target.id, title, delivered: "interrupted" }
+ : { ok: false, message: `subagent "${title}" is not running — nothing to interrupt.` };
}
const text = input.text?.trim();
if (!text) return { ok: false, message: "write requires text (or interrupt: true)." };
@@ -766,6 +810,8 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscalls
}
export interface SubagentMailDeps {
+ signals?: Pick<RunSignalStore, "pending">;
+ deliveries?: Pick<DeliveryStore, "enqueue">;
delegationEnabled?: (actorId: string) => Promise<boolean>;
mailbox: SessionMailbox;
sessions: Pick<SessionStore, "get" | "getByThread" | "getEntries" | "latestEntrySeq" | "visibleEntries">;
@@ -777,6 +823,11 @@ export interface SubagentMailDeps {
export async function deliverSubagentMail(deps: SubagentMailDeps, run: Run): Promise<boolean> {
if (!isSubagentThreadRef(run.sessionId) || run.request.privateSessionMessage) return true;
+ if (
+ run.result?.stopped ||
+ (deps.signals && deps.runs.get && (await sessionRunCancelled({ get: deps.runs.get }, deps.signals, run.id)))
+ )
+ return true;
const child = await deps.sessions.getByThread(run.sessionId);
if (!child?.parentSessionId || !child.spawnMeta) return true;
const parent = await deps.sessions.get(child.parentSessionId);
@@ -810,7 +861,7 @@ export async function deliverSubagentMail(deps: SubagentMailDeps, run: Run): Pro
if (run.status === "failed" || result?.status === "failed") {
kind = "errored";
body = snippet(result?.reason ?? "the turn failed", MAIL_ERROR_CAP);
- } else if (result?.status === "pending_approval") {
+ } else if (result?.pendingApprovals?.length || result?.status === "pending_approval") {
kind = "awaiting_input";
body = snippet(
result.pendingApprovals?.map((a) => a.command).join("; ") ?? "a command needs human approval",
@@ -819,9 +870,9 @@ export async function deliverSubagentMail(deps: SubagentMailDeps, run: Run): Pro
} else if (result?.status === "refused") {
kind = "refused";
body = snippet(result.reason ?? "the turn was refused", MAIL_ERROR_CAP);
- } else if (result?.status === "ok" && result.reply?.trim()) {
+ } else if (result?.status === "ok" && (result.reply?.trim() || result.attachments?.length)) {
kind = "final_answer";
- body = result.reply.trim();
+ body = result.reply?.trim() || `Produced ${result.attachments!.map((file) => file.name).join(", ")}.`;
} else {
kind = "no_reply";
body = "completed without sending a reply.";
@@ -892,6 +943,28 @@ export async function deliverSubagentMail(deps: SubagentMailDeps, run: Run): Pro
throw new Error("the current parent audience cannot read this child result");
}
}
+ if (result?.attachments?.length && deps.deliveries) {
+ const delivery = deliveryCandidatesFor(meta.surface, meta.deliveryTarget, meta.deliveryCandidates, parent.scopeId);
+ const candidate = delivery.candidates.find((item) => item.key === delivery.defaultKey);
+ const destination =
+ candidate ??
+ (meta.origin?.kind === "automation" ? meta.origin.destination : undefined) ??
+ principalDestination(meta.actor.id, meta.actor.id);
+ await deps.deliveries.enqueue({
+ destination,
+ text: "",
+ attachments: result.attachments,
+ idempotencyKey: `subagent-files:${run.id}`,
+ provenance: {
+ trigger: "subagent",
+ surface: meta.surface ?? "unknown",
+ fireKey: `subagent-files:${run.id}`,
+ sourceScopeId: child.scopeId,
+ sourceThreadRef: child.threadRef,
+ sourceSessionId: child.id,
+ },
+ });
+ }
await deps.mailbox.send({
id: `subagent-mail-${run.id}`,
recipientId: parent.id,
diff --git a/src/slack/approvals.ts b/src/slack/approvals.ts
index 6eb58d755..64f0831b6 100644
--- a/src/slack/approvals.ts
+++ b/src/slack/approvals.ts
@@ -1,3 +1,4 @@
+import { isSubagentThreadRef } from "../sessions/session-syscalls.ts";
import { errMessage, swallow, swallowAs } from "../util/errors.ts";
import { slackFailureClause, slackFailureText } from "./turn-flow.ts";
import { randomUUID } from "node:crypto";
@@ -10,7 +11,6 @@ import {
type ApprovalActionId,
type StoredApproval,
agentRequestMessage,
- approvalCardDestination,
approvalMessage,
botIdentityArgs,
clip,
@@ -93,11 +93,6 @@ export interface Approvals {
approvals: NonNullable<TurnResult["pendingApprovals"]>,
ctx: Omit<SlackApprovalContext, "command" | "reason">,
): void;
- postApprovalButtons(
- client: any,
- ctx: Omit<SlackApprovalContext, "command" | "reason" | "approvalChannel">,
- approvals: NonNullable<TurnResult["pendingApprovals"]>,
- ): Promise<void>;
postAgentRequests(
client: any,
ctx: {
@@ -166,41 +161,6 @@ export function createApprovals(deps: {
}
}
- async function resolveApprovalCardChannel(
- client: any,
- ctx: { channel: string; requesterId: string | undefined; threadOnly: boolean },
- ): Promise<{ approvalChannel: string; toDm: boolean; channelPointer: string }> {
- const { toDm, channelPointer } = approvalCardDestination(ctx.threadOnly);
- if (!toDm) return { approvalChannel: ctx.channel, toDm: false, channelPointer };
- try {
- const opened = await client.conversations.open({ users: ctx.requesterId });
- const dm = String(opened?.channel?.id ?? "");
- if (dm) return { approvalChannel: dm, toDm: true, channelPointer };
- } catch (err) {
- console.error("[slack-plugin] couldn't open approval DM:", (err as Error).message);
- }
- return { approvalChannel: ctx.channel, toDm: false, channelPointer: "" };
- }
-
- async function postApprovalButtons(
- client: any,
- ctx: Omit<SlackApprovalContext, "command" | "reason" | "approvalChannel">,
- approvals: NonNullable<TurnResult["pendingApprovals"]>,
- ): Promise<void> {
- const { approvalChannel, toDm, channelPointer } = await resolveApprovalCardChannel(client, ctx);
- rememberSlackApprovals(approvals, { ...ctx, approvalChannel });
- const msg = approvalMessage(approvals);
- await client.chat.postMessage({
- ...slackReplyArgs(approvalChannel, msg.text, toDm ? undefined : ctx.replyThreadTs, { threadOnly: !toDm }),
- blocks: msg.blocks,
- });
- if (toDm && channelPointer) {
- await client.chat
- .postMessage(slackReplyArgs(ctx.channel, channelPointer, ctx.replyThreadTs, { threadOnly: true }))
- .catch(swallowAs("slack: post approval pointer", undefined));
- }
- }
-
type StoredApprovalFetch = { state: "found"; stored: StoredApproval } | { state: "gone" } | { state: "unavailable" };
async function fetchStoredApproval(requestId: string): Promise<StoredApprovalFetch> {
@@ -347,12 +307,13 @@ export function createApprovals(deps: {
turn,
agentRequest: linked,
});
- const msg = approvalMessage(approvals);
- if (opts.approvalMessageTs) {
- await updateSlackMessage(client, ctx.dmChannel, opts.approvalMessageTs, msg.text, msg.blocks);
- } else {
- await client.chat.postMessage({ ...slackReplyArgs(ctx.dmChannel, msg.text, undefined), blocks: msg.blocks });
- }
+ if (opts.approvalMessageTs)
+ await updateSlackMessage(
+ client,
+ ctx.dmChannel,
+ opts.approvalMessageTs,
+ "Approved. A new command needs approval; its card will arrive separately.",
+ );
await tryUpdateSlackMessage(
client,
ctx.originChannel,
@@ -605,9 +566,10 @@ export function createApprovals(deps: {
})
: null;
if (rebuilt && !ctx) {
- const handoff = await core
- .agentRequestForApproval(requestId)
- .catch(swallowAs("slack: agent-request recovery", null));
+ const handoffId = (rebuilt.turn.gatewayContext as CoreTurnBody["gatewayContext"])?.details?.agent_request_id;
+ const handoff = await (
+ typeof handoffId === "string" ? core.getAgentRequest(handoffId) : core.agentRequestForApproval(requestId)
+ ).catch(swallowAs("slack: agent-request recovery", null));
pendingSlackApprovals.remember(requestId, {
...rebuilt,
...(handoff ? { agentRequest: handoff } : {}),
@@ -686,12 +648,13 @@ export function createApprovals(deps: {
settled = true;
};
+ const delegated = isSubagentThreadRef(ctx.turn.conversation.threadRef);
const cardChannel = ctx.approvalChannel;
const cardIsRemote = cardChannel !== ctx.channel;
try {
const approver = await directory.classifyActor(client, clickerId);
const onQueued =
- messageTs && !cardIsRemote
+ messageTs && !cardIsRemote && !delegated
? (runId: string): void => {
void core
.reportRunEditRef(runId, messageTs)
@@ -699,7 +662,8 @@ export function createApprovals(deps: {
}
: undefined;
const sealedOut = async (result: TurnResult): Promise<boolean> => {
- if (result.status !== "pending_approval" || (result.pendingApprovals ?? []).length) return false;
+ const retained = result.pendingApprovals?.find((item) => item.requestId === requestId);
+ if (result.status !== "pending_approval" || (result.pendingApprovals?.length && !retained)) return false;
pendingSlackApprovals.remember(requestId, ctx);
const note = result.reason ?? "This conversation is waiting on a pending approval.";
const retry = approvalMessage([
@@ -711,6 +675,7 @@ export function createApprovals(deps: {
...(ctx.summary ? { summary: ctx.summary } : {}),
...(ctx.kind ? { kind: ctx.kind } : {}),
...(ctx.grantModes ? { grantModes: ctx.grantModes } : {}),
+ ...retained,
},
]);
await updateSlackMessage(
@@ -750,6 +715,18 @@ export function createApprovals(deps: {
if (await sealedOut(result)) return;
+ if (delegated) {
+ await updateSlackMessage(
+ client,
+ cardChannel,
+ messageTs,
+ result.status === "failed" || result.status === "refused"
+ ? `Approved; the delegated task could not continue: ${result.reason ?? "execution failed"}`
+ : `Approved ${inlineCode(ctx.command)}. Results will return to the original conversation.`,
+ );
+ return;
+ }
+
if (ctx.agentRequest) {
await handleAgentRequestResult(client, ctx.agentRequest, ctx.turn, result, {
approvalMessageTs: messageTs,
@@ -817,8 +794,12 @@ export function createApprovals(deps: {
...(ctx.slackIdsByPrincipal ? { slackIdsByPrincipal: ctx.slackIdsByPrincipal } : {}),
...(ctx.recovered ? { recovered: true } : {}),
});
- const msg = approvalMessage(approvals);
- await updateSlackMessage(client, cardChannel, messageTs, msg.text, msg.blocks);
+ await updateSlackMessage(
+ client,
+ cardChannel,
+ messageTs,
+ "Approved. A new command needs approval; its card will arrive separately.",
+ );
return;
}
@@ -943,9 +924,8 @@ export function createApprovals(deps: {
return;
}
if (!claimed) return;
- const ctx = claimed;
-
const decision = agentRequestAction(actionId);
+ const ctx = decision === "run" ? { ...claimed, requestId: randomUUID() } : claimed;
if (decision === "deny") {
await tryUpdateSlackMessage(
client,
@@ -987,6 +967,7 @@ export function createApprovals(deps: {
details: {
channel: ctx.dmChannel,
requested_by_channel: ctx.originChannel,
+ agent_request_id: ctx.requestId,
...(ctx.originThreadTs ? { requested_by_thread_ts: ctx.originThreadTs } : {}),
},
instructions:
@@ -995,6 +976,7 @@ export function createApprovals(deps: {
},
...(classified.timezone ? { timezone: classified.timezone } : {}),
};
+ await core.putAgentRequest(ctx.requestId, ctx);
const outcome = await runTurn(personalTurn);
await handleAgentRequestResult(client, ctx, personalTurn, outcome.result, {
handoffMessageTs: messageTs ?? ctx.dmMessageTs,
@@ -1011,5 +993,5 @@ export function createApprovals(deps: {
app.action(/^agent_request_/, handleAgentRequestAction);
}
- return { rememberSlackApprovals, postApprovalButtons, postAgentRequests, registerActions };
+ return { rememberSlackApprovals, postAgentRequests, registerActions };
}
diff --git a/src/slack/deliveries.ts b/src/slack/deliveries.ts
index 6383885ea..7e6926e0d 100644
--- a/src/slack/deliveries.ts
+++ b/src/slack/deliveries.ts
@@ -1,4 +1,7 @@
import { deployAccessMessage } from "./deploy-access.ts";
+import { approvalDeliveryKey } from "../core/approval-store.ts";
+import { samePerson } from "../directory/person.ts";
+import { approvalMessage } from "./approval-cards.ts";
import { keychainApprovalMessage, keychainApprovalOrigin } from "./keychain-approvals.ts";
import { errMessage, swallow, swallowAs } from "../util/errors.ts";
import { performance } from "node:perf_hooks";
@@ -230,7 +233,7 @@ export function createDeliveryPoller(deps: {
}
return undefined;
}
- const text = toSlackMrkdwn(runId ? cleanAgentReplyForSlack(d.text).text : stripSlackDirectives(d.text));
+ let text = toSlackMrkdwn(runId ? cleanAgentReplyForSlack(d.text).text : stripSlackDirectives(d.text));
const replayAttachments = async (root?: string): Promise<void> => {
if (!d.attachments?.length) return;
try {
@@ -247,6 +250,7 @@ export function createDeliveryPoller(deps: {
}
};
const messageFooter = deliveryFooter(d);
+ if (!text.trim() && !messageFooter.length && d.attachments?.length) text = "Files attached.";
const footer = [
...messageFooter,
...(d.destination.debugFooter ? [{ type: "mrkdwn", text: d.destination.debugFooter }] : []),
@@ -367,6 +371,18 @@ export function createDeliveryPoller(deps: {
d.destination.keychainAskId && core.keychainApprovals
? await core.keychainApprovals.get(d.destination.keychainAskId, d.destination.target)
: null;
+ const commandApproval = d.destination.commandApprovalId
+ ? await core.getApproval(d.destination.commandApprovalId)
+ : null;
+ const requester = commandApproval?.request?.actor as { externalId?: string } | undefined;
+ if (
+ d.destination.commandApprovalId &&
+ (!commandApproval ||
+ !requester?.externalId ||
+ !samePerson(requester.externalId, d.destination.target) ||
+ d.idempotencyKey !== approvalDeliveryKey(d.destination.commandApprovalId, commandApproval))
+ )
+ return undefined;
let card: { text: string; blocks: Array<Record<string, unknown>> } | null = null;
if (approval)
card = keychainApprovalMessage(
@@ -375,11 +391,14 @@ export function createDeliveryPoller(deps: {
);
else if (d.destination.deploymentAccess)
card = deployAccessMessage(d.destination.deploymentAccess, d.text);
- const text = card?.text ?? toSlackMrkdwn(stripReactionDirectives(d.text));
+ if (commandApproval)
+ card = approvalMessage([{ ...commandApproval, reason: commandApproval.reason ?? "Approval required" }]);
+ let text = card?.text ?? toSlackMrkdwn(stripReactionDirectives(d.text));
if (!text.trim() && !d.attachments?.length) return undefined;
const channel = await openConversationFor(client, [d.destination.target]);
const threadTs = d.destination.threadTs;
const footer = deliveryFooter(d);
+ if (!text.trim() && !footer.length && d.attachments?.length) text = "Files attached.";
const blocks =
card?.blocks ??
(footer.length
diff --git a/src/slack/message-gating.ts b/src/slack/message-gating.ts
index c33c9f5a2..3061684d2 100644
--- a/src/slack/message-gating.ts
+++ b/src/slack/message-gating.ts
@@ -201,8 +201,10 @@ export async function maybeInterceptStop(opts: {
threadRef: string;
getInFlightRun: (threadRef: string) => string | undefined | Promise<string | undefined>;
signalAbort: (runId: string) => Promise<void>;
+ stopConversation?: (threadRef: string) => Promise<boolean>;
}): Promise<boolean> {
if (!isBareStop(opts.text)) return false;
+ if (opts.stopConversation) return opts.stopConversation(opts.threadRef);
const runId = await opts.getInFlightRun(opts.threadRef);
if (!runId) return false;
await opts.signalAbort(runId);
diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.ts
index 1b76fd018..4b6e4e953 100644
--- a/src/slack/turn-handler.ts
+++ b/src/slack/turn-handler.ts
@@ -17,7 +17,6 @@ import {
type TaskListPresenter,
DEFAULT_ACK_REACTIONS,
REACTION_DETECT_GUIDANCE,
- approvalMessage,
botIdentityArgs,
buildReactionTurnText,
createAckPresenter,
@@ -363,6 +362,7 @@ export function createTurnHandler(deps: {
(await core.activeRunForThread(ref).catch(swallowAs("slack: active-run lookup", undefined))) ??
inFlightRunByThread.get(ref),
signalAbort: (runId) => core.signalRunAbort(runId),
+ stopConversation: (ref) => core.stopConversation(ref),
}).catch(swallowAs("slack: abort signal", true));
if (intercepted) return;
}
@@ -683,23 +683,6 @@ export function createTurnHandler(deps: {
actionableAgentRequests,
);
}
- if (result.pendingApprovals?.length) {
- await approvals.postApprovalButtons(
- client,
- {
- requesterId: inc.userId,
- channel: inc.channel,
- ...(replyThreadTs ? { replyThreadTs } : {}),
- triggerTs: inc.ts,
- threadOnly: inc.kind === "channel",
- turn,
- ...(allowedTs.size ? { allowedTs } : {}),
- ...(slackIdsByPrincipal ? { slackIdsByPrincipal } : {}),
- ...(ack?.postedAck() ? { ackedFirstBlock: ack.postedAck() } : {}),
- },
- result.pendingApprovals,
- );
- }
await settleAck();
await finishTaskAck();
};
@@ -746,28 +729,8 @@ export function createTurnHandler(deps: {
await finishTaskAck();
return;
}
- const baseCtx = {
- requesterId: inc.userId,
- channel: inc.channel,
- ...(replyThreadTs ? { replyThreadTs } : {}),
- triggerTs: inc.ts,
- threadOnly: inc.kind === "channel",
- turn,
- ...(allowedTs.size ? { allowedTs } : {}),
- ...(slackIdsByPrincipal ? { slackIdsByPrincipal } : {}),
- ...(ack?.postedAck() ? { ackedFirstBlock: ack.postedAck() } : {}),
- };
await settleAck();
- if (inc.kind === "channel") {
- await approvals.postApprovalButtons(client, baseCtx, pendingApprovals);
- } else {
- approvals.rememberSlackApprovals(pendingApprovals, { ...baseCtx, approvalChannel: inc.channel });
- const msg = approvalMessage(pendingApprovals);
- await client.chat.postMessage({
- ...slackReplyArgs(inc.channel, msg.text, replyThreadTs, { threadOnly: false }),
- blocks: msg.blocks,
- });
- }
+ await finishTaskAck();
} else {
await settleAck();
const delivery = refusalDelivery(result, inc.unprompted === true);
diff --git a/src/types.ts b/src/types.ts
index 371d44a26..0e98de5c8 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -201,6 +201,7 @@ export interface TriggerBase {
export interface Destination {
keychainAskId?: string;
deploymentAccess?: { deploymentId: string; requesterId: string };
+ commandApprovalId?: string;
type: string;
target: string;
audienceScopeId?: ScopeId;
diff --git a/src/wiring.ts b/src/wiring.ts
index b50887726..10c351880 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1,3 +1,4 @@
+import { createApprovalStore } from "./core/approval-store.ts";
import { createKeychainApprovals } from "./credentials/keychain-approval.ts";
import { flushErrorReporting, startTiming } from "../plugins/chassis/src/error-reporting.ts";
import type { TimingStatus } from "../plugins/chassis/src/timing.ts";
@@ -1630,7 +1631,6 @@ export function buildApp(
"[wiring] aws deploy: no data bucket resolved (AWS_DEPLOY_DATA_BUCKET unset, sandbox is not aws) — deployed apps have NO durable /data",
);
}
- const approvals = artifactMap<PendingApprovalRecord>("approvals");
const adminGrantPersist = config.databaseUrl
? createPostgresAdminGrantStore(config.databaseUrl)
: createMapAdminGrantPersistence(createMemoryMap<AdminGrant>());
@@ -1778,6 +1778,7 @@ export function buildApp(
`UPDATE webhooks SET json = jsonb_set(json, '{enabled}', 'false'::jsonb) WHERE (json ->> 'enabled')::boolean`,
],
});
+ const approvals = createApprovalStore(artifactMap<PendingApprovalRecord>("approvals"), deliveries);
let securityScreener = overrides.securityScreener;
if (!securityScreener && config.securityScreenBackend === "proxy") {
securityScreener = createSecurityScreenProxy({
@@ -2192,6 +2193,8 @@ export function buildApp(
mailbox: sessionMailbox,
prepareRequest: prepareSessionRequest,
delegationEnabled: (actorId) => featureFlags.enabled("responsive_spine", scopeId("personal", actorId)),
+ deliveries,
+ signals: runSignals,
},
run,
);
@@ -2210,6 +2213,14 @@ export function buildApp(
afterId = batch.at(-1)!.id;
}
};
+ const approvalDeliverySweeper = createSweeper(
+ () => advisoryLock.withLock("approval-deliveries", () => approvals.deliverPending()),
+ 30_000,
+ {
+ label: "approval-deliveries",
+ immediate: true,
+ },
+ );
const sessionReturnSweeper = createSweeper(
() =>
advisoryLock.tryWithLock
@@ -2570,6 +2581,7 @@ export function buildApp(
swarms?.start();
orphanedSignalSweeper.start();
sessionReturnSweeper.start();
+ approvalDeliverySweeper.start();
};
if (backgroundStopping)
void backgroundClaimsStopping.then(startPeriodic).catch(swallowAs("wiring: periodic resume failed", undefined));
@@ -2597,6 +2609,7 @@ export function buildApp(
swarms?.stop(),
orphanedSignalSweeper.stop(),
sessionReturnSweeper.stop(),
+ approvalDeliverySweeper.stop(),
...workers.map((worker) => worker.stopClaims()),
];
backgroundClaimsStopping = Promise.all(stopping).then(() => {});
diff --git a/test/approval-store.test.ts b/test/approval-store.test.ts
new file mode 100644
index 000000000..12f31356b
--- /dev/null
+++ b/test/approval-store.test.ts
@@ -0,0 +1,68 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createApprovalStore } from "../src/core/approval-store.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";
+import type { PendingApprovalRecord } from "../src/types.ts";
+
+function record(threadRef: string, createdAt = 1): PendingApprovalRecord {
+ return {
+ sessionId: threadRef,
+ command: "publish",
+ createdAt,
+ request: {
+ surface: "slack",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef },
+ text: "publish report",
+ },
+ kind: "input",
+ grantModes: { session: false, always: false },
+ };
+}
+
+for (const threadRef of ["dm:D1", "agent:main:subagent:child"]) {
+ test(`saving approval immediately delivers a native request for ${threadRef}`, async () => {
+ const backing = createMemoryMap<PendingApprovalRecord>();
+ const deliveries = createDeliveryStore();
+ const approvals = createApprovalStore(backing, deliveries);
+ await approvals.put("A1", record(threadRef));
+ const [delivery] = await deliveries.pending("principal");
+ assert.equal(delivery?.destination.commandApprovalId, "A1");
+ assert.equal(delivery?.destination.target, "U1");
+ assert.deepEqual((await backing.get("A1"))?.grantModes, { session: false, always: false });
+ await approvals.deliverPending();
+ assert.equal((await deliveries.pending("principal")).length, 1);
+ await deliveries.ack(delivery!.id, Date.now());
+ await approvals.take("A1");
+ await approvals.put("A1", record(threadRef, 2));
+ assert.equal((await deliveries.pending("principal")).length, 1);
+ assert.notEqual((await deliveries.pending("principal"))[0]!.id, delivery!.id);
+ });
+}
+
+test("persisted approvals recover after enqueue failure and restart without failing the turn", async () => {
+ const backing = createMemoryMap<PendingApprovalRecord>();
+ const failed = createApprovalStore(backing, {
+ enqueue: async () => {
+ throw new Error("delivery unavailable");
+ },
+ });
+ await failed.put("A1", record("agent:main:subagent:child"));
+ assert.ok(await backing.get("A1"));
+ const deliveries = createDeliveryStore();
+ const restarted = createApprovalStore(backing, deliveries);
+ await restarted.deliverPending();
+ await restarted.deliverPending();
+ assert.equal((await deliveries.pending("principal")).length, 1);
+});
+
+test("web approvals remain on their native surface", async () => {
+ const deliveries = createDeliveryStore();
+ const approvals = createApprovalStore(createMemoryMap<PendingApprovalRecord>(), deliveries);
+ const approval = record("web:U1");
+ approval.request!.surface = "web";
+ await approvals.put("A1", approval);
+ await approvals.deliverPending();
+ assert.equal((await deliveries.pending("principal")).length, 0);
+});
diff --git a/test/session-pins.test.ts b/test/session-pins.test.ts
index 81bf877ef..b6ddd3c32 100644
--- a/test/session-pins.test.ts
+++ b/test/session-pins.test.ts
@@ -47,7 +47,7 @@ describe("conversation pins self-API", async () => {
before(async () => {
built = buildApp(testConfig({ signingSecret: SECRET }));
- server = createServer(built.app, { signingSecret: SECRET });
+ server = createServer(built.app, { signingSecret: SECRET, sessions: built.sessions });
await new Promise<void>((resolve) => server.listen(0, resolve));
base = `http://localhost:${(server.address() as AddressInfo).port}`;
sessionId = (await built.app.turn(dm("U1", "remember the launch date is Sept 4", THREAD))).sessionId!;
@@ -100,6 +100,29 @@ describe("conversation pins self-API", async () => {
assert.equal(((await res.json()) as { error: string }).error, "entry_not_found");
});
+ it("nested children pin, list, and remove notes in the human conversation", async () => {
+ const child = await built.sessions.getOrCreateByThread(
+ "agent:main:subagent:pins-child",
+ "dm",
+ scopeId("personal", "U1"),
+ );
+ const nested = await built.sessions.getOrCreateByThread(
+ "agent:main:subagent:pins-nested",
+ "dm",
+ scopeId("personal", "U1"),
+ );
+ await built.sessions.setParentSession(child.id, sessionId);
+ await built.sessions.setParentSession(nested.id, child.id);
+ const token = await capFor("U1", nested.threadRef);
+ const added = await call("POST", "/v1/pins", { text: "delegated note" }, token);
+ assert.equal(added.status, 200);
+ const { pin } = (await added.json()) as { pin: { id: string } };
+ const listing = await call("GET", "/v1/pins", undefined, await capFor("U1", THREAD));
+ assert.ok(((await listing.json()) as { pins: { id: string }[] }).pins.some((p) => p.id === pin.id));
+ assert.equal((await call("GET", "/v1/pins", undefined, await capFor("U2", nested.threadRef))).status, 403);
+ assert.equal((await call("DELETE", `/v1/pins/${pin.id}`, undefined, token)).status, 200);
+ });
+
it("rejects an empty pin", async () => {
const token = await capFor("U1", THREAD);
const res = await call("POST", "/v1/pins", {}, token);
diff --git a/test/session-syscalls.test.ts b/test/session-syscalls.test.ts
index bd0f328ef..88c50253e 100644
--- a/test/session-syscalls.test.ts
+++ b/test/session-syscalls.test.ts
@@ -1,3 +1,6 @@
+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";
+import { createControlService } from "../src/api/control-service.ts";
+import { deliveryCandidatesFor } from "../src/core/orchestrator/turn-helpers.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
import { createSessionMailbox, type SessionMailbox, type SessionMessage } from "../src/sessions/session-mailbox.ts";
import { test } from "node:test";
@@ -14,6 +17,7 @@ import {
requiresDelegation,
sessionTreeRunCount,
delegatedAuthorizationOrigin,
+ stopSessionTree,
} from "../src/sessions/session-syscalls.ts";
import { scopeId, type Conversation, type Principal, type ScopeId, type Session } from "../src/types.ts";
import type { SessionStore } from "../src/sessions/session-store.ts";
@@ -90,7 +94,7 @@ test("open creates a child session with parent pointer, spawn meta, and a queued
assert.equal(inFlight.length, 1);
const request = inFlight[0]!.request;
assert.equal(request.conversation.threadRef, child.threadRef);
- assert.equal(request.deliveryTarget, undefined);
+ assert.equal(request.deliveryTarget, "D1");
assert.match(request.text, /subagent-task/);
assert.match(request.text, /build a personal website/);
assert.equal(out.liveRunsRemaining, SUBAGENT_TREE_RUN_CAP - 1);
@@ -146,7 +150,7 @@ test("write queues separately from a running child and interrupts explicitly", a
assert.ok(retask.ok);
assert.equal(retask.delivered, "queued_turn");
const rerun = await r.runs.inFlightForThread(child.threadRef);
- assert.equal(rerun.length, 2);
+ assert.equal(rerun.length, 1);
assert.ok(rerun.some((run) => /check it again/.test(run.request.text)));
});
@@ -1342,3 +1346,136 @@ for (const addressed of [true, false]) {
assert.equal(wake.request.envelopeWrapped, true);
});
}
+
+test("nested delegated work retains the reminder destination without exposing surface tools", async () => {
+ const r = await rig();
+ const first = await r.syscallsFor(r.room).open({ task: "analyze and remind me" });
+ assert.ok(first.ok);
+ const child = await freshSession(r.sessions, first.sessionId);
+ const run = (await r.runs.inFlightForThread(child.threadRef))[0]!;
+ const factory = createSessionSyscalls({ ...r, maxAttempts: 3 });
+ const second = await factory
+ .forTurn({ session: child, scopeId: scope, request: { ...run.request, runId: run.id } })
+ .open({ task: "schedule the result" });
+ assert.ok(second.ok);
+ const grandchild = await freshSession(r.sessions, second.sessionId);
+ const request = (await r.runs.inFlightForThread(grandchild.threadRef))[0]!.request;
+ assert.equal(request.surfaceTools, undefined);
+ const destinations = deliveryCandidatesFor(
+ request.surface,
+ request.deliveryTarget,
+ request.deliveryCandidates,
+ scope,
+ );
+ const control = createControlService({
+ createCron: async (input: unknown) => ({ id: "reminder", ...(input as object) }),
+ } as never);
+ const reminder = await control.createCron(
+ { schedule: { firstFireAt: Date.now() + 60_000 }, text: "the result" },
+ {
+ actorId: actor.id,
+ scopeId: scope,
+ exp: Date.now() + 60_000,
+ destinations: destinations.candidates,
+ defaultDestinationKey: destinations.defaultKey,
+ },
+ );
+ assert.ok(reminder.ok);
+ assert.equal(reminder.cron.destination?.target, "D1");
+});
+
+for (const status of ["ok", "pending_approval"] as const) {
+ test(`child ${status} forwards files once without creating approval deliveries`, async () => {
+ const r = await rig();
+ const deliveries = createDeliveryStore();
+ const out = await r.syscallsFor(r.room).open({ task: "prepare the report" });
+ assert.ok(out.ok);
+ const child = await freshSession(r.sessions, out.sessionId);
+ const run = (await r.runs.inFlightForThread(child.threadRef))[0]!;
+ const claimed = await r.runs.claimById(run.id, "worker", 60_000);
+ const attachment = { name: "report.pdf", blobId: "report", mimetype: "application/pdf", sizeBytes: 42 };
+ await r.runs.complete(run.id, claimed!.leaseToken!, {
+ status,
+ attachments: [attachment],
+ pendingApprovals: [{ requestId: "approve-report", command: "publish", reason: "needs consent" }],
+ });
+ const completed = (await r.runs.get(run.id))!;
+ const deps = { ...r, maxAttempts: 3, deliveries };
+ await deliverSubagentMail(deps, completed);
+ await deliverSubagentMail(deps, completed);
+ const files = await deliveries.pending("slack");
+ assert.equal(files.length, 1);
+ assert.deepEqual(files[0]!.attachments, [attachment]);
+ assert.equal(files[0]!.destination.target, "D1");
+ const approvals = await deliveries.pending("principal");
+ assert.equal(approvals.length, 0);
+ assert.match((await r.mailbox.pending(r.room.id))[0]!.text, /awaiting_input/);
+ });
+}
+
+test("file-only child completion is a result", async () => {
+ const r = await rig();
+ const deliveries = createDeliveryStore();
+ const out = await r.syscallsFor(r.room).open({ task: "make a chart" });
+ assert.ok(out.ok);
+ const child = await freshSession(r.sessions, out.sessionId);
+ const run = (await r.runs.inFlightForThread(child.threadRef))[0]!;
+ const claimed = await r.runs.claimById(run.id, "worker", 60_000);
+ await r.runs.complete(run.id, claimed!.leaseToken!, {
+ status: "ok",
+ attachments: [{ name: "chart.png", blobId: "chart", mimetype: "image/png", sizeBytes: 1 }],
+ });
+ await deliverSubagentMail({ ...r, maxAttempts: 3, deliveries }, (await r.runs.get(run.id))!);
+ assert.match((await r.mailbox.pending(r.room.id))[0]!.text, /Produced chart.png/);
+});
+
+test("stopping an idle coordinator cancels running and queued descendants and blocks new work", async () => {
+ const r = await rig();
+ const out = await r.syscallsFor(r.room).open({ task: "work" });
+ assert.ok(out.ok);
+ const child = await freshSession(r.sessions, out.sessionId);
+ const run = (await r.runs.inFlightForThread(child.threadRef))[0]!;
+ const claimed = await r.runs.claimById(run.id, "worker", 60_000);
+ const factory = createSessionSyscalls({ ...r, maxAttempts: 3 });
+ const childApi = factory.forTurn({ session: child, scopeId: scope, request: { ...run.request, runId: run.id } });
+ const grandchild = await childApi.open({ task: "more work" });
+ assert.ok(grandchild.ok);
+ assert.equal(await stopSessionTree(r, r.room), true);
+ assert.equal(
+ (await r.runs.inFlightForThread((await freshSession(r.sessions, grandchild.sessionId)).threadRef)).length,
+ 0,
+ );
+ assert.equal((await r.signals.pending(run.id))[0]!.signal.kind, "abort");
+ const late = await childApi.open({ task: "late spawn" });
+ assert.equal(late.ok, false);
+ const followup = await childApi.write({ target: grandchild.sessionId, followup: true, text: "late followup" });
+ assert.equal(followup.ok, false);
+ await r.runs.complete(run.id, claimed!.leaseToken!, { status: "ok", reply: "late result" });
+ assert.equal(
+ await deliverSubagentMail(
+ { ...r, maxAttempts: 3, delegationEnabled: async () => true },
+ (await r.runs.get(run.id))!,
+ ),
+ true,
+ );
+ assert.equal((await r.mailbox.pending(r.room.id)).length, 0);
+ assert.equal((await r.runs.inFlightForThread(r.room.threadRef)).length, 0);
+});
+
+test("stop still signals a queued child claimed during withdrawal", async () => {
+ const r = await rig();
+ const opened = await r.syscallsFor(r.room).open({ task: "race the claim" });
+ assert.ok(opened.ok);
+ const child = await freshSession(r.sessions, opened.sessionId);
+ const run = (await r.runs.inFlightForThread(child.threadRef))[0]!;
+ const runs = {
+ ...r.runs,
+ withdraw: async (id: string) => {
+ await r.runs.claimById(id, "racer", 60_000);
+ return false;
+ },
+ };
+ await stopSessionTree({ ...r, runs }, r.room);
+ assert.equal((await r.runs.get(run.id))!.status, "running");
+ assert.equal((await r.signals.pending(run.id))[0]!.signal.kind, "abort");
+});
diff --git a/test/slack-agent-requests.test.ts b/test/slack-agent-requests.test.ts
index f63f0a460..152cba771 100644
--- a/test/slack-agent-requests.test.ts
+++ b/test/slack-agent-requests.test.ts
@@ -324,7 +324,9 @@ test("a handoff command approval recovered on a fresh instance still reports bac
const { requestId, cardTs, statusTs } = await f.postRequest();
await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
- assert.deepEqual(f.store.get(requestId)?.approvalRequestIds, ["req-9"]);
+ const continuationId = f.submitted[0].gatewayContext.details.agent_request_id;
+ assert.notEqual(continuationId, requestId);
+ assert.deepEqual(f.store.get(continuationId)?.approvalRequestIds, ["req-9"]);
const waiting = f.updates.filter((u) => u.channel === "C1" && u.ts === statusTs);
assert.match(String(waiting.at(-1)?.text), /approve a command/);
@@ -379,3 +381,34 @@ test("the leftover strip is case-insensitive and safe on non-ASCII text", () =>
extractAgentRequests(("[[ask-agent:" + "x".repeat(88)).repeat(10000));
assert.ok(Number(process.hrtime.bigint() - start) / 1e6 < 100);
});
+
+test("an early approval has durable handoff context without making the original Run button reusable", async () => {
+ const f = durableFixture();
+ const { requestId, cardTs } = await f.postRequest();
+ let release!: () => void;
+ let started!: () => void;
+ const ready = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const pending = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ f.core.submitTurn = async (body) => {
+ f.submitted.push(body);
+ const continuationId = body.gatewayContext?.details?.agent_request_id;
+ assert.equal(typeof continuationId, "string");
+ assert.notEqual(continuationId, requestId);
+ assert.ok(f.store.has(String(continuationId)));
+ assert.equal(f.store.has(requestId), false);
+ started();
+ await pending;
+ return { status: "ok", reply: "done" };
+ };
+ const first = f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
+ await ready;
+ await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
+ assert.equal(f.submitted.length, 1);
+ release();
+ await first;
+ assert.equal(f.store.size, 0);
+});
diff --git a/test/slack-approval-repost.test.ts b/test/slack-approval-repost.test.ts
index e837d6004..0a378c30e 100644
--- a/test/slack-approval-repost.test.ts
+++ b/test/slack-approval-repost.test.ts
@@ -10,8 +10,9 @@ type ActionHandler = (args: any) => Promise<void>;
function fixture() {
const submitted: any[] = [];
+ const posts: any[] = [];
const state: {
- stored: { requesterId: string; text: string } | null;
+ stored: { requesterId: string; text: string; threadRef?: string } | null;
result: TurnResult;
hold: Promise<void> | null;
fetchFails: boolean;
@@ -39,7 +40,12 @@ function fixture() {
reason: "destructive",
request: {
actor: { externalId: state.stored.requesterId },
- conversation: { kind: "channel", threadRef: "ch:C1:1.0", channelRef: "C1", audience: [] },
+ conversation: {
+ kind: "channel",
+ threadRef: state.stored.threadRef ?? "ch:C1:1.0",
+ channelRef: "C1",
+ audience: [],
+ },
deliveryTarget: "C1:1.0",
text: state.stored.text,
},
@@ -64,7 +70,10 @@ function fixture() {
updates.push(body);
return { ok: true };
},
- postMessage: async () => ({ ok: true, ts: "9.9" }),
+ postMessage: async (body: any) => {
+ posts.push(body);
+ return { ok: true, ts: "9.9" };
+ },
postEphemeral: async (body: any) => {
ephemerals.push(body);
return { ok: true };
@@ -94,7 +103,7 @@ function fixture() {
},
});
};
- return { state, submitted, ephemerals, updates, click, rememberStale };
+ return { state, submitted, ephemerals, updates, posts, click, rememberStale };
}
test("a click resumes from the stored record, not from whatever the card registry last cached", async () => {
@@ -199,3 +208,35 @@ test("a sealed-out deny never claims the command was denied", async () => {
assert.equal(f.submitted.length, 2, "the restored card still denies once the conversation is unblocked");
assert.match(String(f.updates.at(-1)?.text ?? ""), /Denied/);
});
+
+test("cold delegated approval resumes the child without posting its reply a second time", async () => {
+ const f = fixture();
+ f.state.stored = { requesterId: "U2", text: "run delegated command", threadRef: "agent:main:subagent:child" };
+ f.state.result = { status: "ok", reply: "delegated result" };
+ await f.click("U2");
+ assert.equal(f.submitted.length, 1);
+ assert.equal(f.submitted[0].conversation.threadRef, "agent:main:subagent:child");
+ assert.equal(f.posts.length, 0);
+ assert.match(JSON.stringify(f.updates), /original conversation/);
+});
+
+test("a rejected grant scope preserves the same approval card instead of promising a replacement", async () => {
+ const f = fixture();
+ f.state.result = {
+ status: "pending_approval",
+ pendingApprovals: [
+ {
+ requestId: "req-1",
+ command: "publish",
+ reason: "only once allowed",
+ grantModes: { session: false, always: false },
+ },
+ ],
+ };
+ await f.click("U2", "hilo_allow_session");
+ const last = JSON.stringify(f.updates.at(-1));
+ assert.match(last, /hilo_allow_once/);
+ assert.doesNotMatch(last, /hilo_allow_session/);
+ assert.doesNotMatch(last, /new command needs approval/);
+ assert.equal(f.posts.length, 0);
+});
diff --git a/test/slack-deliveries.test.ts b/test/slack-deliveries.test.ts
index 74399364f..4394be7ae 100644
--- a/test/slack-deliveries.test.ts
+++ b/test/slack-deliveries.test.ts
@@ -17,10 +17,11 @@ async function deliver(
sourceThreadRef?: string,
webUiPublicUrl?: string,
text = "two screenshots and the notes",
- row: { createdAt?: number; history?: Record<string, unknown>[]; loseAck?: boolean } = {},
+ row: { createdAt?: number; history?: Record<string, unknown>[]; loseAck?: boolean; approval?: unknown } = {},
) {
const delivery = {
id: "D1",
+ idempotencyKey: destination.commandApprovalId ? `command-approval:${destination.commandApprovalId}:0` : "D1",
text,
...(sourceThreadRef
? { provenance: { trigger: "cron", sourceThreadRef, sourceTitle: "Weekly <project> & check-in" } }
@@ -44,6 +45,7 @@ async function deliver(
};
const core = {
holdDeliveryDispatch: (fn: (lost: Promise<void>) => Promise<unknown>) => fn(new Promise<void>(() => {})),
+ getApproval: async () => row.approval ?? null,
readBlob: async (id: string) => Buffer.from(id),
claimDeliveries: async (type: string) => queues.get(type)?.splice(0) ?? [],
ackDelivery: async (id: string) => {
@@ -287,3 +289,75 @@ test("principal delivery metadata renders an actionable deployment card", async
assert.equal(actions.elements!.length, 2);
assert.deepEqual(JSON.parse(actions.elements![0]!.value), request);
});
+test("delegated approvals recover native buttons from durable records", async () => {
+ const approval = {
+ requestId: "A1",
+ command: "publish",
+ reason: "approval",
+ grantModes: { session: false, always: false },
+ request: { actor: { externalId: "U1" } },
+ };
+ const history: Record<string, unknown>[] = [];
+ const destination = { type: "principal", target: "U1", commandApprovalId: "A1" };
+ const first = await deliver(destination, undefined, undefined, "Approval needed", {
+ approval,
+ history,
+ loseAck: true,
+ });
+ assert.equal(first.posts.length, 1);
+ const rendered = JSON.stringify(first.posts[0]!.blocks);
+ assert.match(rendered, /hilo_allow_once/);
+ assert.doesNotMatch(rendered, /hilo_allow_always/);
+ const second = await deliver(destination, undefined, undefined, "Approval needed", {
+ approval,
+ history,
+ createdAt: Date.now() - 60_000,
+ });
+ assert.equal(second.posts.length, 0);
+ assert.deepEqual(second.acknowledgements, ["D1"]);
+});
+
+for (const approval of [null, { requestId: "A1", command: "publish", request: { actor: { externalId: "U2" } } }]) {
+ test(`delegated approvals discard ${approval ? "mismatched" : "expired"} records`, async () => {
+ const out = await deliver(
+ { type: "principal", target: "U1", commandApprovalId: "A1" },
+ undefined,
+ undefined,
+ "Approval needed",
+ { approval },
+ );
+ assert.equal(out.posts.length, 0);
+ assert.deepEqual(out.acknowledgements, ["D1"]);
+ });
+}
+
+test("a stale queued approval cannot render a newer request for the same command", async () => {
+ const approval = { requestId: "A1", createdAt: 99, command: "publish", request: { actor: { externalId: "U1" } } };
+ const out = await deliver(
+ { type: "principal", target: "U1", commandApprovalId: "A1" },
+ undefined,
+ undefined,
+ "approval",
+ { approval },
+ );
+ assert.equal(out.posts.length, 0);
+ assert.deepEqual(out.acknowledgements, ["D1"]);
+});
+
+for (const type of ["slack", "group", "principal"]) {
+ test(`${type} file-only deliveries survive a restart after a lost acknowledgement`, async () => {
+ const history: Record<string, unknown>[] = [];
+ const first = await deliver({ type }, undefined, undefined, "", { history, loseAck: true });
+ assert.equal(first.posts.length, 1);
+ assert.equal(first.posts[0]!.text, "Files attached.");
+ assert.equal(first.uploads.length, 1);
+ assert.deepEqual(first.acknowledgements, []);
+ const recovered = await deliver({ type }, undefined, undefined, "", {
+ history,
+ createdAt: Date.now() - 60_000,
+ });
+ assert.equal(recovered.posts.length, 0);
+ assert.equal(recovered.uploads.length, 0);
+ assert.deepEqual(recovered.acknowledgements, ["D1"]);
+ });
+}
diff --git a/test/slack-index.integration.test.ts b/test/slack-index.integration.test.ts
index 525f5c90e..7f8489094 100644
--- a/test/slack-index.integration.test.ts
+++ b/test/slack-index.integration.test.ts
@@ -321,6 +321,11 @@ class FakeCore implements SlackCoreClient {
async activeRunForThread(): Promise<string | undefined> {
return this.activeRun;
}
+ async stopConversation(): Promise<boolean> {
+ if (!this.activeRun) return false;
+ await this.signalRunAbort(this.activeRun);
+ return true;
+ }
async signalRunAbort(runId: string): Promise<void> {
this.abortedRuns.push(runId);
}
diff --git a/test/slack-message-gating.test.ts b/test/slack-message-gating.test.ts
index 8f6e1512b..1ca6f514a 100644
--- a/test/slack-message-gating.test.ts
+++ b/test/slack-message-gating.test.ts
@@ -288,3 +288,19 @@ test("createInFlightThreadMap: clear is runId-guarded so a finished run can't un
runs.clear("dm:C1", "run-2");
assert.equal(runs.get("dm:C1"), undefined);
});
+
+test("stop checks the conversation tree even when the coordinator is idle", async () => {
+ const calls: string[] = [];
+ const stopped = await maybeInterceptStop({
+ text: "stop",
+ threadRef: "dm:D1",
+ getInFlightRun: () => undefined,
+ signalAbort: async () => assert.fail("must stop the tree"),
+ stopConversation: async (threadRef) => {
+ calls.push(threadRef);
+ return true;
+ },
+ });
+ assert.equal(stopped, true);
+ assert.deepEqual(calls, ["dm:D1"]);
+});
diff --git a/test/slack-stop-target.test.ts b/test/slack-stop-target.test.ts
index 2a757a454..9972af2f2 100644
--- a/test/slack-stop-target.test.ts
+++ b/test/slack-stop-target.test.ts
@@ -2,44 +2,28 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { createTurnHandler } from "../src/slack/turn-handler.ts";
-for (const active of ["running-before-account-switch", undefined]) {
- test(`Slack Stop prefers the durable active run over a queued follow-up (${active ?? "cache fallback"})`, async () => {
- const aborted: string[] = [];
- const lookedUp: string[] = [];
- const handler = createTurnHandler({
- core: {
- taskAcknowledgements: {},
- activeRunForThread: async (ref: string) => {
- lookedUp.push(ref);
- return active;
- },
- signalRunAbort: async (id: string) => {
- aborted.push(id);
- },
+test("Slack Stop cancels the durable conversation tree even when the coordinator is idle", async () => {
+ const stopped: string[] = [];
+ const handler = createTurnHandler({
+ core: {
+ taskAcknowledgements: {},
+ stopConversation: async (ref: string) => {
+ stopped.push(ref);
+ return true;
},
- flow: {
- inFlightRunByThread: new Map([["dm:D1", "queued-after-account-switch"]]),
- callCore: async () => {
- assert.fail("Stop must not submit another turn");
- },
- },
- directory: {},
- mirror: {},
- ids: { botUserId: "BOT" },
- } as unknown as Parameters<typeof createTurnHandler>[0]);
- await handler.handleIncoming(
- {
- kind: "dm",
- channel: "D1",
- userId: "U1",
- actor: { externalId: "U1" },
- rawText: "stop",
- files: [],
- ts: "10.0",
- },
- {},
- );
- assert.deepEqual(lookedUp, ["dm:D1"]);
- assert.deepEqual(aborted, [active ?? "queued-after-account-switch"]);
- });
-}
+ activeRunForThread: async () => assert.fail("Stop must not depend on a running coordinator"),
+ },
+ flow: {
+ inFlightRunByThread: new Map(),
+ callCore: async () => assert.fail("Stop must not submit another turn"),
+ },
+ directory: {},
+ mirror: {},
+ ids: { botUserId: "BOT" },
+ } as unknown as Parameters<typeof createTurnHandler>[0]);
+ await handler.handleIncoming(
+ { kind: "dm", channel: "D1", userId: "U1", actor: { externalId: "U1" }, rawText: "stop", files: [], ts: "10.0" },
+ {},
+ );
+ assert.deepEqual(stopped, ["dm:D1"]);
+});
diff --git a/test/wake-steering.test.ts b/test/wake-steering.test.ts
index 0ec1726c6..fa15520f3 100644
--- a/test/wake-steering.test.ts
+++ b/test/wake-steering.test.ts
@@ -165,6 +165,7 @@ test("spine ON: a bare 'stop' mid-turn routes through the ABORT interrupt (not a
const root = "200.2";
const first = await built.app.turn(mention("@bot do a long thing", channel, root));
const liveRunId = first.runId!;
+ assert.ok(await built.runs.claimById(liveRunId, "worker", 30_000));
const stop = await built.app.turn(mention("stop", channel, root));
assert.equal(stop.runId, liveRunId, "the stop attached to the live run");
@@ -329,6 +330,7 @@ test("an addressed bare 'stop' still ABORTS a live UNPROMPTED run", async () =>
const root = "1100.1";
const first = await built.app.turn(overheard("hm, interesting", channel, root));
const liveRunId = first.runId!;
+ assert.ok(await built.runs.claimById(liveRunId, "worker", 30_000));
const stop = await built.app.turn(mention("stop", channel, root));
assert.equal(stop.runId, liveRunId, "the stop attached to the live run");
@@ -385,6 +387,7 @@ test("an addressed bare 'stop' still ABORTS a live AUTOMATION run", async () =>
const root = "1400.1";
const first = await built.app.turn(automationRun(channel, root));
const liveRunId = first.runId!;
+ assert.ok(await built.runs.claimById(liveRunId, "worker", 30_000));
const stop = await built.app.turn(mention("stop", channel, root));
assert.equal(stop.runId, liveRunId, "the stop attached to the live automation run");
@@ -886,3 +889,12 @@ test("run snapshots expose authorized durable web input with safe attachment met
});
assert.equal((await built.app.getRun(explicit.run.id, run.request.actor.id))?.input?.text, "pending input");
});
+
+test("an addressed stop withdraws queued work before a worker can claim it", async () => {
+ const built = freshApp();
+ const first = await built.app.turn(mention("start the task", "C_STOP_QUEUED", "100.1"));
+ const stop = await built.app.turn(mention("stop", "C_STOP_QUEUED", "100.1"));
+ assert.equal(stop.runId, first.runId);
+ assert.equal(await built.runs.get(first.runId!), null);
+ assert.equal(await built.runs.claimById(first.runId!, "worker", 30_000), null);
+});