Multiplayer agent harness for work.
Preserve human origins through delegated session turns (#2375)
Regan Bell03e9146ee0b4
diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex 5d7dfcf02..67f04191e 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -9,7 +9,7 @@ import { scopeId } from "../types.ts";import { rosterAdmits } from "../resolution/scope-membership.ts";import { isHalt, routeWake, type Wake } from "../wake/wake.ts";import type { OrchestratorInput } from "../core/orchestrator.ts";-import { isPersonAuthored, resolveTurnOrigin } from "../core/turn-origin.ts";+import { isPersonAuthored, isSessionTurn, resolveTurnOrigin } from "../core/turn-origin.ts";import { conversationScope } from "../resolution/resolution-service.ts";import { isTerminal, leaseLapsed } from "../runs/run-store.ts";import type { SessionStateEvent } from "../runs/session-state-bus.ts";@@ -201,9 +201,12 @@ export function createTurnMethods(let privateRequest = req.privateSessionMessage ? req : undefined;if (approvedRequest?.privateSessionMessage) privateRequest = approvedRequest;const origin = resolveTurnOrigin(privateRequest ?? req);+ const sessionTurn =+ (req.spawned && isSessionTurn(req)) ||+ (sameApprovedMessage && approvedRequest && isSessionTurn(approvedRequest));const modelAccount =- !req.externalSlack && deps.userModelCredentials && origin.kind === "human"+ !req.externalSlack && deps.userModelCredentials && origin.kind === "human" && !sessionTurn? await deps.config.getModelAccountDurable(actor.id): "company";const individualAuth = modelAccount !== "company";@@ -374,9 +377,14 @@ export function createTurnMethods(surface: req.surface,...(req.slackSource ? { slackSource: req.slackSource } : {}),...(req.externalSlack ? { externalSlack: req.externalSlack } : {}),+ ...(req.spawned && req.sessionSenderId ? { sessionSenderId: req.sessionSenderId } : {}),+ ...(req.spawned && req.delegatingRunId ? { delegatingRunId: req.delegatingRunId } : {}),...(sameApprovedMessage && approvedRequest?.sessionSenderId? { sessionSenderId: approvedRequest.sessionSenderId }: {}),+ ...(sameApprovedMessage && approvedRequest?.delegatingRunId+ ? { delegatingRunId: approvedRequest.delegatingRunId }+ : {}),...(req.deliveryTarget ? { deliveryTarget: req.deliveryTarget } : {}),...(req.deliveryCandidates?.length ? { deliveryCandidates: req.deliveryCandidates } : {}),actor,@@ -479,7 +487,7 @@ export function createTurnMethods(if (replay) dedupKey = replay.signalDedupKey;- if (origin.kind === "human" && !req.approval) deps.reaperPoke?.();+ if (origin.kind === "human" && !isSessionTurn(input) && !req.approval) deps.reaperPoke?.();if (req.surface !== "web" &&diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.tsindex 60382770d..48a7c1f0e 100644--- a/src/api/slack-core-client.ts+++ b/src/api/slack-core-client.ts@@ -1,3 +1,4 @@+import { isSessionTurn } from "../core/turn-origin.ts";import { replayableRequest } from "../core/orchestrator/turn-helpers.ts";import {createSlackSessionStatus,@@ -285,7 +286,12 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClienasync privateContinuationSource(runId) {const run = await deps.runs.get(runId);- if (!run?.request.externalSlack || run.request.origin.kind !== "human" || run.request.actor.type !== "internal")+ if (+ !run?.request.externalSlack ||+ run.request.origin.kind !== "human" ||+ isSessionTurn(run.request) ||+ run.request.actor.type !== "internal"+ )return null;return replayableRequest(run.request);},diff --git a/src/api/start-session.ts b/src/api/start-session.tsindex 24dcd0dd7..149562aa1 100644--- a/src/api/start-session.ts+++ b/src/api/start-session.ts@@ -1,12 +1,21 @@+import { sessionTurnOrigin } from "../core/turn-origin.ts";import type { App } from "./app-types.ts";import type { SessionStore } from "../sessions/session-store.ts";-import { parseScopeId, type ScopeId, type Session } from "../types.ts";+import { parseScopeId, type ScopeId, type Session, type TurnOrigin } from "../types.ts";export async function startSession(app: Pick<App, "turn" | "forkSession" | "spawnSession" | "discardSession">,sessions: Pick<SessionStore, "get" | "updateTitle">,actorId: string,- input: { scopeId: ScopeId; forkOf?: string; text?: string; title?: string },+ input: {+ scopeId: ScopeId;+ forkOf?: string;+ text?: string;+ title?: string;+ origin?: TurnOrigin;+ sessionSenderId?: string;+ delegatingRunId?: string;+ },): Promise<{ session: Session; refused?: string } | { error: string }> {const out = input.forkOf? await app.forkSession(input.forkOf, actorId)@@ -26,6 +35,9 @@ export async function startSession(...(out.session.channelName ? { channelName: out.session.channelName } : {}),},text: input.text,+ ...(input.origin ? { origin: sessionTurnOrigin(input.origin, input.text) } : {}),+ ...(input.sessionSenderId ? { sessionSenderId: input.sessionSenderId } : {}),+ ...(input.delegatingRunId ? { delegatingRunId: input.delegatingRunId } : {}),spawned: true,async: true,});diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 76307a057..0580c9078 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -35,7 +35,7 @@ import type {PendingApprovalRecord,} from "../types.ts";import { scopeId as toScopeId, personalScope } from "../types.ts";-import { turnOriginRequestFields } from "./turn-origin.ts";+import { isSessionTurn, turnOriginRequestFields } from "./turn-origin.ts";import { resolveTurnFastMode, turnRuntimePurpose } from "./turn-options.ts";import { orgId } from "../config.ts";import { renderGatewayContext } from "./gateway-context.ts";@@ -541,6 +541,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const automatedTurn = input.origin.kind === "automation";const ambientTurn = input.origin.kind === "ambient";const humanTurn = input.origin.kind === "human";+ const sessionTurn = isSessionTurn(input);+ const humanInput = humanTurn && !sessionTurn;const allInternal =deps.identity.audienceIsAllInternal(conversation.audience) &&(conversation.kind === "dm" ||@@ -553,12 +555,17 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {!external && deps.runs? await delegatedAuthorizationOrigin(input, { runs: deps.runs, sessions: deps.sessions }): undefined;- const liveTurn = (humanTurn || delegatedOrigin?.kind === "human") && allInternal && !external;+ const authorizationOrigin = sessionTurn ? (delegatedOrigin ?? { kind: "automation" as const }) : input.origin;+ const liveTurn = authorizationOrigin.kind === "human" && allInternal && !external;const liveAuthorTurn =- !external && (humanTurn || authoredDetection || delegatedOrigin !== undefined) && allInternal;- const messageTs = input.origin.kind === "human" ? input.origin.messageTs : undefined;+ !external &&+ ((!sessionTurn && (humanTurn || authoredDetection)) || delegatedOrigin !== undefined) &&+ allInternal;+ const messageTs = humanInput && input.origin.kind === "human" ? input.origin.messageTs : undefined;const entryTs =- input.origin.kind === "human" || input.origin.kind === "ambient" ? input.origin.entryTs : undefined;+ !sessionTurn && (input.origin.kind === "human" || input.origin.kind === "ambient")+ ? input.origin.entryTs+ : undefined;const coreReceivedAt = Date.now();let detectMs: number | undefined;let compactMs: number | undefined;@@ -819,7 +826,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const sessionSender = input.sessionSenderId ? await deps.sessions.get(input.sessionSenderId) : null;const verifiedSessionMessage = Boolean(sessionSender &&- automatedTurn &&sessionSender.scopeId === scopeId &&(await deps.sessions.getForParticipant(sessionSender.id, actor.id)),);@@ -827,6 +833,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {? securityScreenPayload({...input,...turnOriginRequestFields(input.origin),+ ...(sessionTurn ? { triggered: true, securityScreenData: input.text } : {}),overheard: [],externalPromptData,verifiedSwarm: Boolean(input.swarm && swarmBinding),@@ -1010,7 +1017,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {actor,audience: conversation.audience,acl: deps.acl,- origin: delegatedOrigin ?? input.origin,+ origin: authorizationOrigin,trustedLiveHuman: liveAuthorTurn,targetScope: scopeId,config: deps.config,@@ -1040,7 +1047,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const botHandle = rawHandle && rawHandle.toLowerCase() !== botName.toLowerCase() ? rawHandle : undefined;let modeName = "mode-fallback";if (input.surfaceTools) modeName = "mode-autonomous";- else if (!automatedTurn && (conversation.kind === "dm" || isWeb)) modeName = "mode-conversation";+ else if (!automatedTurn && !(sessionTurn && input.envelopeWrapped) && (conversation.kind === "dm" || isWeb))+ modeName = "mode-conversation";let frameMd = MODE_FALLBACK_MD;if (modeName === "mode-autonomous") frameMd = MODE_AUTONOMOUS_MD;else if (modeName === "mode-conversation") frameMd = MODE_CONVERSATION_MD;@@ -1263,9 +1271,10 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (!input.sessionParticipantIds?.length && !automatedTurn)await deps.sessions.addParticipant(session.id, actor.id);- const delegatedTask =- automatedTurn && !!input.sessionSenderId && session.parentSessionId === input.sessionSenderId;- const syntheticInput = (input.proactiveOpener && !input.text.trim()) || (automatedTurn && !delegatedTask);+ const delegatedTask = !!input.sessionSenderId && session.parentSessionId === input.sessionSenderId;+ const syntheticInput =+ (input.proactiveOpener && !input.text.trim()) ||+ ((automatedTurn || (sessionTurn && input.envelopeWrapped)) && !delegatedTask);const titleText = input.displayText?.trim() || input.text;let fallbackTitleWrite: Promise<void> | undefined;const assignSessionTitle = () => {@@ -2342,6 +2351,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (ambientTurn &&+ !sessionTurn &&deps.harness.models.shouldRespond &&!(isRetry &&@@ -2541,13 +2551,21 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {});const earlyTaskAck =input.surface === "slack" &&- input.origin.kind === "human" &&+ humanInput &&conversation.kind === "dm" &&!input.approval &&!input.botActor &&!input.swarm;const publishFirstAck = (deliberatePost: boolean) => {- if (!input.runId || !input.addressed || isPollFire || !spineFirstBlockOpen || resume || approvalReplay)+ if (+ !input.runId ||+ !input.addressed ||+ sessionTurn ||+ isPollFire ||+ !spineFirstBlockOpen ||+ resume ||+ approvalReplay+ )return;spineFirstBlockOpen = false;const ack = spineFirstBlock.trim();@@ -2695,7 +2713,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}: {}),...(deps.webhookPublicUrl ? { webhookPublicUrl: deps.webhookPublicUrl } : {}),- ...(humanTurn && !external ? { humanTurn: true } : {}),+ ...(humanInput && !external ? { humanTurn: true } : {}),...(surfaceToolDeps ? { surface: surfaceToolDeps } : {}),...(sessionSyscalls? {@@ -2807,7 +2825,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}const importedOverheard: OverheardEntryPayload[] = [];- if (!memoryHistoryReset && (!input.envelopeWrapped || humanTurn) && input.overheard?.length) {+ if (!memoryHistoryReset && (!input.envelopeWrapped || humanInput) && input.overheard?.length) {const toImport = await transcripts.forRender(session.id).then((read) => selectOverheardToImport(input.overheard!, recordedMessageTimestamps(read.entries)))@@ -2936,7 +2954,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {session.threadRef,visibleHistory.findLast((e) => e.type === "user" && !isOverheardEntry(e))?.createdAt,);- const sender = !automatedTurn && input.text.trim() ? senderNote(actor.displayName) : "";+ const sender = !automatedTurn && !sessionTurn && input.text.trim() ? senderNote(actor.displayName) : "";const unscreenedNote =inputUnscreened || (enforceScreen && inbound.unscreened.length) || documentsUnscreened? unscreenedNotice("inbound content")@@ -3045,7 +3063,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {!syntheticPrompt && input.text.trim()? {text: input.text,- ...(humanTurn ? { speakerId: actor.id } : {}),+ ...(humanInput ? { speakerId: actor.id } : {}),...((messageTs ?? entryTs) ? { ts: messageTs ?? entryTs } : {}),...(actor.displayName?.trim() ? { name: actor.displayName.trim() } : {}),...(input.displayText?.trim() ? { display: input.displayText } : {}),@@ -3063,9 +3081,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const wantsOrgFastMode =typeof input.fastMode !== "boolean" &&!purposeDefault &&- humanTurn &&+ humanInput &&(await deps.config?.getInteractiveFastModeDurable());- const effectiveFastMode = resolveTurnFastMode(input.fastMode, humanTurn, wantsOrgFastMode === true);+ const effectiveFastMode = resolveTurnFastMode(input.fastMode, humanInput, wantsOrgFastMode === true);const loadRuntimeAuth = async (runtime: Partial<RuntimeChoice>) => {let userProviderKeys: ProviderKeys | undefined;let userModelOverride: string | undefined;@@ -3075,7 +3093,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const account = external? "company": (input.modelAccount ?? (await deps.config?.getModelAccountDurable(actor.id)) ?? "company");- if (userCredStore && humanTurn && account !== "company") {+ if (userCredStore && humanInput && account !== "company") {const [anthCred, oaiCred] = await Promise.all([account === "openai" ? null : userCredStore.get(actor.id, "anthropic"),account === "anthropic" ? null : userCredStore.get(actor.id, "openai"),@@ -3247,7 +3265,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {Object.assign(payload, swarmEntryProvenance);if (input.runId) payload.runId = input.runId;delete payload.speakerId;- if (humanTurn && !syntheticPrompt && !continuation && !payload.steered && !payload.overheard)+ if (humanInput && !syntheticPrompt && !continuation && !payload.steered && !payload.overheard)payload.speakerId = actor.id;if (actor.displayName?.trim() && typeof payload.name !== "string")payload.name = actor.displayName.trim();@@ -3411,7 +3429,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {signal?: AbortSignal,) =>deps.runtime!(- runtimeClaims,+ sessionTurn && request.lifetime === "scope"+ ? { ...runtimeClaims, liveActor: false, liveAuthor: false }+ : runtimeClaims,active,request,checkRuntimeAuth,diff --git a/src/core/orchestrator/surface-tools.ts b/src/core/orchestrator/surface-tools.tsindex 4f4a58143..b0c234d68 100644--- a/src/core/orchestrator/surface-tools.ts+++ b/src/core/orchestrator/surface-tools.ts@@ -1,3 +1,4 @@+import { isSessionTurn } from "../turn-origin.ts";import type {Conversation,DeliveryProvenance,@@ -100,7 +101,10 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDepsconst deliveries = deps.deliveries;const currentDestination = defaultDestination;const rateLimitRecipient =- input.origin?.kind === "human" && currentDestination.type === "slack" && currentDestination.target+ input.origin?.kind === "human" &&+ !isSessionTurn(input) &&+ currentDestination.type === "slack" &&+ currentDestination.target? { rateLimitRecipient: { target: currentDestination.target, user: actor.id } }: {};let editRefConsumed = false;diff --git a/src/core/orchestrator/turn-helpers.ts b/src/core/orchestrator/turn-helpers.tsindex a7de00bb1..99b7662d2 100644--- a/src/core/orchestrator/turn-helpers.ts+++ b/src/core/orchestrator/turn-helpers.ts@@ -183,6 +183,7 @@ export function replayableRequest(input: OrchestratorInput): TurnRequest {...(input.slackSource ? { slackSource: input.slackSource } : {}),...(input.externalSlack ? { externalSlack: input.externalSlack } : {}),...(input.sessionSenderId ? { sessionSenderId: input.sessionSenderId } : {}),+ ...(input.delegatingRunId ? { delegatingRunId: input.delegatingRunId } : {}),...(input.scopeVersion ? { scopeVersion: input.scopeVersion } : {}),...(input.deliveryTarget ? { deliveryTarget: input.deliveryTarget } : {}),...(input.deliveryCandidates?.length ? { deliveryCandidates: input.deliveryCandidates } : {}),diff --git a/src/core/turn-origin.ts b/src/core/turn-origin.tsindex 26ee2394b..479e662e0 100644--- a/src/core/turn-origin.ts+++ b/src/core/turn-origin.ts@@ -106,3 +106,14 @@ export function turnOriginRequestFields(origin: TurnOrigin): Partial<LegacyTurnOexport function isPersonAuthored(kind: TurnOrigin["kind"]): boolean {return kind === "human" || kind === "direct";}++export function isSessionTurn(input: Pick<TurnRequest, "sessionSenderId" | "delegatingRunId">): boolean {+ return !!input.sessionSenderId || !!input.delegatingRunId;+}++export function sessionTurnOrigin(origin: TurnOrigin | undefined, text: string): TurnOrigin {+ if (!origin || origin.kind === "automation") return { ...origin, kind: "automation", screenData: text };+ if (origin.kind === "human") return { kind: "human" };+ if (origin.kind === "ambient") return { kind: "ambient", ...(origin.live ? { live: true } : {}) };+ return origin;+}diff --git a/src/delivery/run-result-delivery.ts b/src/delivery/run-result-delivery.tsindex 98abe0eba..d99ab09f7 100644--- a/src/delivery/run-result-delivery.ts+++ b/src/delivery/run-result-delivery.ts@@ -2,7 +2,7 @@ import { isSubagentThreadRef } from "../sessions/session-syscalls.ts";import type { DeliveryProvenance, Destination, OutgoingAttachment } from "../types.ts";import type { Run, RunStore } from "../runs/run-store.ts";import { turnDeliveryProvenance, type DeliveryStore } from "./delivery-store.ts";-import { resolveTurnOrigin } from "../core/turn-origin.ts";+import { isSessionTurn, resolveTurnOrigin } from "../core/turn-origin.ts";import type { TurnFailurePayload } from "../core/turn-error.ts";import { standaloneFailureText, userFacingFailureClause } from "../core/failure-copy.ts";import { conversationScope } from "../resolution/resolution-service.ts";@@ -72,7 +72,7 @@ export function runResultDelivery(run: Run, adminUrlFor?: AdminUrlFor): RunResul}if (run.request.surfaceTools && run.result?.status !== "failed" && !run.result?.attachments?.length) return null;if (failed) {- if (origin.kind === "ambient") return null;+ if (origin.kind === "ambient" && !isSessionTurn(run.request)) return null;const clause = userFacingFailureClause(run.result ?? { status: "failed" });const adminUrl = run.result?.sessionId ? adminUrlFor?.(run.result.sessionId) : undefined;const detail = adminUrl ? ` — full error: ${adminUrl}` : "";diff --git a/src/sessions/session-syscalls.ts b/src/sessions/session-syscalls.tsindex 4ba40951c..274b458c9 100644--- a/src/sessions/session-syscalls.ts+++ b/src/sessions/session-syscalls.ts@@ -1,3 +1,4 @@+import { isSessionTurn, sessionTurnOrigin } from "../core/turn-origin.ts";import { memoryContextPayload, type MemoryContextSnapshot } from "../memory/context-boundary.ts";import { TURN_STOPPED_KIND } from "../harness/replay.ts";import { principalDestination } from "../reach/reach.ts";@@ -47,7 +48,7 @@ export async function delegatedAuthorizationOrigin(let current = request;for (let depth = 0; depth < 32; depth++) {if (- current.origin.kind !== "automation" ||+ current.origin.kind === "automation" ||current.readOnly ||current.privateSessionMessage ||current.swarm ||@@ -66,11 +67,15 @@ export async function delegatedAuthorizationOrigin(child.parentSessionId === sender.id &&source.sessionId === sender.threadRef;const continued =- requiresDelegation(current, true) &&isSubagentThreadRef(sender.threadRef) &&sender.parentSessionId === child.id &&source.sessionId === child.threadRef;- if (!delegated && !continued) return;+ const started =+ current.surface === "web" &&+ !child.parentSessionId &&+ !isSubagentThreadRef(child.threadRef) &&+ source.sessionId === sender.threadRef;+ if (!delegated && !continued && !started) return;const parent = source.request;const audience = new Set([parent.actor.id, ...parent.conversation.audience.map((person) => person.id)]);if (@@ -91,6 +96,7 @@ export async function delegatedAuthorizationOrigin((!!parent.conversation.publishMembers?.length &&parent.conversation.publishMembers.every((person) => person.type === "internal")));if (+ !isSessionTurn(parent) &&internal &&(parent.origin.kind === "human" ||(parent.origin.kind === "ambient" && parent.origin.live === true && parent.conversation.kind !== "dm"))@@ -255,7 +261,15 @@ export interface SessionSyscallDeps {list(actorId: string): Promise<Session[]>;start(actorId: string,- input: { scopeId: ScopeId; forkOf?: string; text?: string; title?: string },+ input: {+ scopeId: ScopeId;+ forkOf?: string;+ text?: string;+ title?: string;+ origin?: OrchestratorInput["origin"];+ sessionSenderId?: string;+ delegatingRunId?: string;+ },): Promise<{ session: Session; refused?: string } | { error: string }>;};}@@ -350,14 +364,7 @@ function childRunRequest(child: Session, meta: SpawnMeta, text: string, displayT...(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,- },+ origin: sessionTurnOrigin(meta.origin, text),...(meta.unattendedGrants ? { unattendedGrants: [...meta.unattendedGrants] } : {}),text,displayText,@@ -582,7 +589,7 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscallsthrow new Error("the sender no longer has access to this session");const request: OrchestratorInput = {...binding.request,- origin: binding.request.origin?.kind === "automation" ? binding.request.origin : { kind: "automation" },+ origin: binding.request.origin ?? { kind: "automation" },text: "",};return deps.prepareRequest ? deps.prepareRequest(request) : request;@@ -691,15 +698,7 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscalls);const title = existing ? visibleTitle(existing) : input.name?.trim() || autoTitle(task);const meta: SpawnMeta = {- ...(caller.origin.kind === "automation"- ? {- origin: {- kind: "automation" as const,- ...(caller.origin.useOwnerKeychain ? { useOwnerKeychain: true } : {}),- ...(caller.origin.destination ? { destination: caller.origin.destination } : {}),- },- }- : {}),+ origin: caller.origin,...(binding.request.surfaceTools ? { surfaceTools: true } : {}),...(binding.request.deliveryCandidates? { deliveryCandidates: binding.request.deliveryCandidates }@@ -868,10 +867,7 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscallsreturn { ok: true, sessionId: target.id, title, delivered: "queued_turn" };}}- request.origin = {- ...(request.origin.kind === "automation" ? request.origin : { kind: "automation" as const }),- screenData: stamped,- };+ request.origin = sessionTurnOrigin(request.origin, stamped);request.sessionSenderId = binding.session.id;request.delegatingRunId = binding.request.runId;if (@@ -1038,6 +1034,9 @@ export function createSessionSyscalls(deps: SessionSyscallDeps): SessionSyscallsconst out = await conversations.start(binding.request.actor.id, {scopeId: binding.scopeId,+ origin: binding.request.origin,+ sessionSenderId: binding.session.id,+ ...(binding.request.runId ? { delegatingRunId: binding.request.runId } : {}),...(input.fork ? { forkOf: binding.session.id } : {}),...(text ? { text } : {}),...(input.title?.trim() ? { title: input.title.trim() } : {}),@@ -1144,10 +1143,7 @@ export async function deliverSubagentMail(deps: SubagentMailDeps, run: Run): Pro: {}),threadRef: parent.threadRef,},- origin: {- ...(meta.origin?.kind === "automation" ? meta.origin : { kind: "automation" as const }),- screenData: text,- },+ origin: sessionTurnOrigin(meta.origin, text),text,displayText: `[subagent ${title}: ${kind.replace("_", " ")}]`,envelopeWrapped: true,@@ -1246,7 +1242,7 @@ export async function deliverSubagentMail(deps: SubagentMailDeps, run: Run): Pro...prepared,...(surfaceTools ? { surfaceTools } : {}),...(originalParent && initiatingRun ? { delegatingRunId: initiatingRun.id } : {}),- origin: { ...prepared.origin, kind: "automation", screenData: wake },+ origin: sessionTurnOrigin(prepared.origin, wake),text: wake,displayText: "Delegated task completed",},diff --git a/src/types.ts b/src/types.tsindex b21a4805b..fc98079b4 100644--- a/src/types.ts+++ b/src/types.ts@@ -664,6 +664,7 @@ export interface TurnRequest {serviceCredentials: string[];};sessionSenderId?: string;+ delegatingRunId?: string;privateSessionMessage?: true;sessionMessageDepth?: number;surface: string;diff --git a/src/util/product-analytics.ts b/src/util/product-analytics.tsindex 6e7453616..bdb20e04e 100644--- a/src/util/product-analytics.ts+++ b/src/util/product-analytics.ts@@ -1,4 +1,4 @@-import { resolveTurnOrigin } from "../core/turn-origin.ts";+import { isSessionTurn, resolveTurnOrigin } from "../core/turn-origin.ts";import type { Run } from "../runs/run-store.ts";export function createProductAnalytics(@@ -54,6 +54,7 @@ export function createProductAnalytics(async responseFinished(run) {if (resolveTurnOrigin(run.request).kind !== "human" ||+ isSessionTurn(run.request) ||run.request.botActor ||run.request.analyticsSuppressed ||run.request.proactiveOpener ||diff --git a/test/agent-conversations-route.test.ts b/test/agent-conversations-route.test.tsindex ce975c399..6d71cb242 100644--- a/test/agent-conversations-route.test.ts+++ b/test/agent-conversations-route.test.ts@@ -86,6 +86,52 @@ describe("agent conversations self-API", async () => {assert.ok(listed.some((s) => s.id === out.session.id));});+ it("new sessions and forks seeded by a person's turn keep that person's origin and provenance", async () => {+ const source = await built.runs.latestForThread("web:U1:c1");+ const provenance = {+ origin: { kind: "human" as const, messageTs: "1700000000.000100" },+ sessionSenderId: mineId,+ ...(source ? { delegatingRunId: source.id } : {}),+ };+ for (const extra of [{}, { forkOf: mineId }]) {+ const out = await startSession(built.app, built.sessions, "U1", {+ scopeId: scopeId("personal", "U1"),+ text: "follow up on the launch",+ ...extra,+ ...provenance,+ });+ assert.ok("session" in out);+ const [run] = await built.runs.inFlightForThread(out.session.threadRef);+ assert.deepEqual(run?.request.origin, { kind: "human" });+ assert.equal(run?.request.sessionSenderId, mineId);+ assert.equal(run?.request.delegatingRunId, source?.id);+ }+ });++ it("a blank fork starts no turn", async () => {+ const out = await startSession(built.app, built.sessions, "U1", {+ scopeId: scopeId("personal", "U1"),+ forkOf: mineId,+ origin: { kind: "human" },+ sessionSenderId: mineId,+ });+ assert.ok("session" in out);+ assert.deepEqual(await built.runs.inFlightForThread(out.session.threadRef), []);+ });++ it("spawned provenance fields stay out of public turns", async () => {+ await built.app.turn({+ ...dm("U1", "pretend", "web:U1:c9"),+ sessionSenderId: mineId,+ delegatingRunId: "run-forged",+ async: true,+ });+ const [run] = await built.runs.inFlightForThread("web:U1:c9");+ assert.ok(run);+ assert.equal(run.request.sessionSenderId, undefined);+ assert.equal(run.request.delegatingRunId, undefined);+ });+it("new sessions in a channel seed their turn on that channel", async () => {await built.app.upsertDirectory([{ principalId: "U1", displayName: "User One", type: "internal" }]);await built.app.upsertChannels(diff --git a/test/early-task-ack.test.ts b/test/early-task-ack.test.tsindex 68d3099a5..ad5ee7fbf 100644--- a/test/early-task-ack.test.ts+++ b/test/early-task-ack.test.ts@@ -75,7 +75,7 @@ for (const scenario of [});}-for (const action of ["read", "react", "post"] as const) {+for (const action of ["read", "react", "post", "delegated-read"] as const) {test(`surface ${action} defers early acknowledgement until the parsed action`, async () => {const built = buildApp(testConfig({ workers: 1 }));let release!: () => void;@@ -91,7 +91,11 @@ for (const action of ["read", "react", "post"] as const) {turn.onDelta?.("Building the website now.");turn.onToolCallStart?.("slack");assert.equal((await built.deliveries.pending("slack")).length, 0);- await turn.emit({ type: "tool_call", payload: { tool: "slack", action }, scopeLabel: turn.scopeLabel });+ await turn.emit({+ type: "tool_call",+ payload: { tool: "slack", action: action === "delegated-read" ? "read" : action },+ scopeLabel: turn.scopeLabel,+ });started();await block;};@@ -103,6 +107,7 @@ for (const action of ["read", "react", "post"] as const) {actor: { externalId: "U1" },conversation: { kind: "dm", threadRef: `surface-${action}` },text: "Build a website",+ ...(action === "delegated-read" ? { spawned: true, sessionSenderId: "child", delegatingRunId: "parent" } : {}),surfaceTools: true,addressed: true,deliveryTarget: "D1",@@ -112,7 +117,7 @@ for (const action of ["read", "react", "post"] as const) {const deliveries = await built.deliveries.pending("slack");assert.deepEqual(deliveries.map((delivery) => delivery.text),- action === "post" ? [] : ["Building the website now."],+ action === "post" || action === "delegated-read" ? [] : ["Building the website now."],);release();await built.runs.waitFor(queued.runId!, 5000);diff --git a/test/external-slack-policy.test.ts b/test/external-slack-policy.test.tsindex 1bca19e00..698028c83 100644--- a/test/external-slack-policy.test.ts+++ b/test/external-slack-policy.test.ts@@ -1,3 +1,5 @@+import { createMemoryRunStore } from "../src/runs/memory-run-store.ts";+import { createSlackCoreClient, type SlackCoreClientDeps } from "../src/api/slack-core-client.ts";import assert from "node:assert/strict";import { test } from "node:test";import {@@ -389,3 +391,25 @@ test("external account poller neither claims default identity nor releases pre-passert.deepEqual(acks, hasDefault ? ["legacy"] : []);}});++test("delegated human-origin runs cannot restart themselves as a person's private continuation", async () => {+ const { runs } = createMemoryRunStore();+ const client = createSlackCoreClient({ runs } as SlackCoreClientDeps);+ const request = {+ surface: "slack",+ actor: { id: "employee", type: "internal" as const },+ conversation: { kind: "dm" as const, threadRef: "external:dm", audience: [] },+ origin: { kind: "human" as const },+ externalSlack: { accountId: "partner", teamId: "TPARTNER", userId: "UEMPLOYEE", ...policy },+ text: "continue privately",+ };+ const direct = await runs.enqueue({ sessionId: request.conversation.threadRef, request });+ assert.ok(await client.privateContinuationSource!(direct.run.id));+ for (const provenance of [{ sessionSenderId: "child" }, { delegatingRunId: direct.run.id }]) {+ const delegated = await runs.enqueue({+ sessionId: request.conversation.threadRef,+ request: { ...request, ...provenance },+ });+ assert.equal(await client.privateContinuationSource!(delegated.run.id), null);+ }+});diff --git a/test/product-analytics.test.ts b/test/product-analytics.test.tsindex 1ae630004..6072a3d3f 100644--- a/test/product-analytics.test.ts+++ b/test/product-analytics.test.ts@@ -93,6 +93,8 @@ test("non-human, stopped and non-completion results do not produce response outcawait analytics.responseFinished({ ...run, request: { ...run.request, origin: { kind } } });}await analytics.responseFinished({ ...run, request: { ...run.request, botActor: true } });+ for (const provenance of [{ sessionSenderId: "sender" }, { delegatingRunId: "parent-run" }])+ await analytics.responseFinished({ ...run, request: { ...run.request, ...provenance } });for (const flag of ["analyticsSuppressed", "proactiveOpener"] as const) {for (const status of ["ok", "failed"] as const) {await analytics.responseFinished({ ...run, request: { ...run.request, [flag]: true }, result: { status } });diff --git a/test/run-result-delivery.test.ts b/test/run-result-delivery.test.tsindex 1d36af5a1..8cab48d3c 100644--- a/test/run-result-delivery.test.ts+++ b/test/run-result-delivery.test.ts@@ -197,6 +197,7 @@ test("runResultDelivery keeps unprompted failures quiet, like the live path", ()const failed = run({ status: "failed", result: { status: "failed", reason: "boom" } });failed.request = { ...failed.request, origin: { kind: "ambient" } };assert.equal(runResultDelivery(failed), null, "no failure note where nobody addressed the agent");+ assert.ok(runResultDelivery({ ...failed, request: { ...failed.request, sessionSenderId: "child" } }));const ok = run({});ok.request = { ...ok.request, origin: { kind: "ambient" } };assert.equal(runResultDelivery(ok)?.text, "the reply", "an unprompted reply the agent chose to send still recovers");diff --git a/test/session-syscalls.test.ts b/test/session-syscalls.test.tsindex 9753eaf82..ba9abbce0 100644--- a/test/session-syscalls.test.ts+++ b/test/session-syscalls.test.ts@@ -1178,9 +1178,9 @@ async function delegatedHumanRig(context: Partial<OrchestratorInput> = {}) {return { ...r, parent: parent.run, child, run, api };}-test("delegated live authority follows immutable provenance without changing automation origin", async () => {+test("delegated human origin retains live authority boundaries", async () => {const r = await delegatedHumanRig();- assert.equal(r.run.request.origin.kind, "automation");+ assert.equal(r.run.request.origin.kind, "human");assert.equal((await delegatedAuthorizationOrigin(r.run.request, r))?.kind, "human");for (const patch of [{ actor: { ...actor, id: "other" } },@@ -1279,39 +1279,41 @@ test("a later participant cannot change a completion's actor, rollout, destinatiassert.equal(wake.request.actor.id, actor.id);assert.equal(wake.request.deliveryTarget, "slack:C1:task");assert.equal(wake.request.unattendedGrants, undefined);- assert.deepEqual(wake.request.origin, { kind: "automation", screenData: wake.request.text });+ assert.deepEqual(wake.request.origin, { kind: "human" });});-test("completion wakes preserve live authorization for subsequent delegated steps", async () => {- const r = await delegatedHumanRig();- const claimed = await r.runs.claimById(r.run.id, "w1", 60000);- await r.runs.complete(r.run.id, claimed!.leaseToken!, { status: "ok", reply: "step one" });- for (const pending of await r.runs.inFlightForThread(r.room.threadRef)) {- const parentTurn = await r.runs.claimById(pending.id, "parent", 60_000);- assert.ok(parentTurn);- await r.runs.complete(pending.id, parentTurn.leaseToken!, { status: "silent" });- }- await deliverSubagentMail(- { ...r, maxAttempts: 3, delegationEnabled: async () => true },- (await r.runs.get(r.run.id))!,- );- const wake = (await r.runs.getByDedupKey(`subagent-return:${r.run.id}`))!;- assert.ok(wake);- assert.equal(wake.request.origin.kind, "automation");- assert.equal(wake.request.addressed, true);- assert.equal((await delegatedAuthorizationOrigin(wake.request, r))?.kind, "human");- const api = createSessionSyscalls({ ...r, maxAttempts: 3 }).forTurn({- session: r.room,- scopeId: scope,- request: { ...wake.request, runId: wake.id },+for (const surface of ["slack", "web"] as const) {+ test(`${surface} completion wakes preserve live authorization for subsequent delegated steps`, async () => {+ const r = await delegatedHumanRig({ surface });+ const claimed = await r.runs.claimById(r.run.id, "w1", 60000);+ await r.runs.complete(r.run.id, claimed!.leaseToken!, { status: "ok", reply: "step one" });+ for (const pending of await r.runs.inFlightForThread(r.room.threadRef)) {+ const parentTurn = await r.runs.claimById(pending.id, "parent", 60_000);+ assert.ok(parentTurn);+ await r.runs.complete(pending.id, parentTurn.leaseToken!, { status: "silent" });+ }+ await deliverSubagentMail(+ { ...r, maxAttempts: 3, delegationEnabled: async () => true },+ (await r.runs.get(r.run.id))!,+ );+ const wake = (await r.runs.getByDedupKey(`subagent-return:${r.run.id}`))!;+ assert.ok(wake);+ assert.equal(wake.request.origin.kind, "human");+ assert.equal(wake.request.addressed, true);+ assert.equal((await delegatedAuthorizationOrigin(wake.request, r))?.kind, "human");+ const api = createSessionSyscalls({ ...r, maxAttempts: 3 }).forTurn({+ session: r.room,+ scopeId: scope,+ request: { ...wake.request, runId: wake.id },+ });+ assert.ok((await api.write({ target: r.child.id, text: "step two", followup: true })).ok);+ const next = (await r.runs.inFlightForThread(r.child.threadRef))[0]!;+ assert.equal((await delegatedAuthorizationOrigin(next.request, r))?.kind, "human");+ await r.sessions.setParentSession(r.child.id, null);+ assert.equal(await delegatedAuthorizationOrigin(wake.request, r), undefined);+ assert.equal(await delegatedAuthorizationOrigin(next.request, r), undefined);});- assert.ok((await api.write({ target: r.child.id, text: "step two", followup: true })).ok);- const next = (await r.runs.inFlightForThread(r.child.threadRef))[0]!;- assert.equal((await delegatedAuthorizationOrigin(next.request, r))?.kind, "human");- await r.sessions.setParentSession(r.child.id, null);- assert.equal(await delegatedAuthorizationOrigin(wake.request, r), undefined);- assert.equal(await delegatedAuthorizationOrigin(next.request, r), undefined);-});+}test("completed children do not fill a working parent's run slots and consumed returns settle", async () => {const r = await rig();@@ -1493,7 +1495,7 @@ for (const addressed of [true, false]) {assert.equal(wake.request.surfaceTools, true);assert.equal(wake.request.delegatingRunId, r.parent.id);assert.equal(wake.request.sessionSenderId, r.child.id);- assert.equal(wake.request.origin.kind, "automation");+ assert.equal(wake.request.origin.kind, "human");assert.match(wake.request.text, /delegated task finished/i);assert.equal(wake.request.displayText, "Delegated task completed");assert.equal(wake.request.envelopeWrapped, true);@@ -1830,8 +1832,8 @@ test("sessions list shows only sidebar sessions the whole audience can see and cassert.equal((await live.start!({ fork: false, text: "hello", title: "fresh" })).ok, true);assert.equal((await live.start!({ fork: true })).ok, true);assert.deepEqual(started, [- { scopeId: scope, text: "hello", title: "fresh" },- { scopeId: scope, forkOf: room.id },+ { scopeId: scope, origin: { kind: "human" }, sessionSenderId: room.id, text: "hello", title: "fresh" },+ { scopeId: scope, origin: { kind: "human" }, sessionSenderId: room.id, forkOf: room.id },]);const child = await sessions.getOrCreateByThread("agent:main:subagent:w", "dm", scope, undefined, "web");await sessions.updateTitle(child.id, "worker");@@ -1936,3 +1938,47 @@ test("stopping a session tree tells every stopped run who stopped it", async ()],);});++for (const origin of [+ { kind: "human", messageTs: "1", entryTs: "2" },+ { kind: "ambient", live: true, entryTs: "2" },+ { kind: "automation" },+] as const) {+ test(`nested tasks and followups inherit ${origin.kind} origin`, async () => {+ const r = await delegatedHumanRig({ origin });+ const childApi = createSessionSyscalls({ ...r, maxAttempts: 3 }).forTurn({+ session: r.child,+ scopeId: scope,+ request: { ...r.run.request, runId: r.run.id },+ });+ const opened = await childApi.open({ task: "inspect nested" });+ assert.ok(opened.ok);+ const child = (await r.sessions.get(opened.sessionId))!;+ const nested = (await r.runs.latestForThread(child.threadRef))!;+ assert.equal(nested.request.origin.kind, origin.kind);+ assert.equal("messageTs" in nested.request.origin, false);+ assert.equal("entryTs" in nested.request.origin, false);+ assert.equal(nested.request.delegatingRunId, r.run.id);+ assert.equal(nested.request.sessionSenderId, r.child.id);+ assert.ok((await childApi.write({ target: child.id, followup: true, text: "inspect again" })).ok);+ const followup = (await r.runs.latestForThread(child.threadRef))!;+ assert.equal(followup.request.origin.kind, origin.kind);+ assert.equal(followup.request.delegatingRunId, r.run.id);+ });+}++test("detaching an ancestor revokes a descendant's delegated live authority", async () => {+ const r = await delegatedHumanRig();+ const api = createSessionSyscalls({ ...r, maxAttempts: 3 }).forTurn({+ session: r.child,+ scopeId: scope,+ request: { ...r.run.request, runId: r.run.id },+ });+ const opened = await api.open({ task: "inspect nested" });+ assert.ok(opened.ok);+ const nested = (await r.sessions.get(opened.sessionId))!;+ const run = (await r.runs.latestForThread(nested.threadRef))!;+ assert.equal((await delegatedAuthorizationOrigin(run.request, r))?.kind, "human");+ await r.sessions.setParentSession(r.child.id, null);+ assert.equal(await delegatedAuthorizationOrigin(run.request, r), undefined);+});diff --git a/test/sharing-context-e2e.test.ts b/test/sharing-context-e2e.test.tsindex 666d61926..0cce67e13 100644--- a/test/sharing-context-e2e.test.ts+++ b/test/sharing-context-e2e.test.ts@@ -167,7 +167,7 @@ test("sharing e2e: a delegated turn shares its live parent's access under currenrequest: {...parent.request,conversation: { ...parent.request.conversation, threadRef: child.threadRef },- origin: { kind: "automation", screenData: text },+ origin: parent.request.origin,delegatingRunId: parent.id,sessionSenderId: parentSession.id,text,@@ -192,7 +192,24 @@ test("sharing e2e: a delegated turn shares its live parent's access under currenconst delegatedClaims = await verifyCapabilityToken(token, TEST_CAPABILITY_SECRET);assert.equal(delegatedClaims?.liveAuthor, true);assert.equal(delegatedClaims?.liveActor, true);- assert.equal(delegatedClaims?.triggered, true);+ assert.equal(delegatedClaims?.triggered, undefined);+ const credential = await b.keychain!.save({+ ownerId: "U1",+ service: "delegated-test",+ secret: "fixture-secret",+ envKey: "DELEGATED_TEST_TOKEN",+ });+ assert.equal(+ await childTurn(+ `!execute ${JSON.stringify({+ command: 'test -n "$DELEGATED_TEST_TOKEN" && printf available',+ ownerAuth: true,+ credentials: [credentialHandle(credential)],+ })}`,+ ),+ "available",+ );+ assert.deepEqual(await b.keychain!.grantsForScope("channel:C1"), []);await b.config.setSharingPosture("personal:U1", "isolated");assert.match(await childTurn(read), /no file/);await b.config.clearSharingPosture("personal:U1");diff --git a/test/subagent-parity.test.ts b/test/subagent-parity.test.tsindex 389d0a7b5..8031a1fd2 100644--- a/test/subagent-parity.test.ts+++ b/test/subagent-parity.test.ts@@ -1,3 +1,6 @@+import { createRuntimeService } from "../src/harness/runtime-control.ts";+import type { RuntimeChoice } from "../src/harness/harness.ts";+import type { RuntimeControl } from "../src/harness/runtime-types.ts";import { test } from "node:test";import assert from "node:assert/strict";import { mkdtempSync } from "node:fs";@@ -36,6 +39,8 @@ import type { Run } from "../src/runs/run-store.ts";type Call = { tool: string; args: Record<string, unknown> };type Turn = {ref: Parameters<typeof createAgentTools>[0];+ runtime?: RuntimeControl;+ requestedRuntime?: Partial<RuntimeChoice>;options: AgentToolsOptions;tools: string[];results: Array<{ isError?: unknown }>;@@ -101,7 +106,15 @@ async function world(flags: FeatureName[], next: (turn: Turn, subagent: boolean)};const options = harnessToolOptions({}, turn);const tools = createAgentTools(ref, options);- const record: Turn = { ref, options, tools: tools.map((t) => t.name).sort(), results, started: sidebar };+ const record: Turn = {+ ref,+ runtime: turn.runtimeControl,+ requestedRuntime: turn.runtime,+ options,+ tools: tools.map((t) => t.name).sort(),+ results,+ started: sidebar,+ };turns.set(turn.session.threadRef, record);for (let call = next(record, !!turn.session.parentSessionId);@@ -121,9 +134,18 @@ async function world(flags: FeatureName[], next: (turn: Turn, subagent: boolean)const acl = createAclStore();const auditLog = createAuditLog();const workspace = createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "subagent-parity-")));+ const config = createMemoryConfigStore("org");+ config.setApprovedHarnesses(["pi", "claude"]);+ config.setInteractiveFastMode(true);+ await config.flushScope("org:org");const orchestrator = createOrchestrator({+ config,+ runtime: createRuntimeService(+ { config, harnessId: "pi", baseModelDefault: "claude-opus-5" },+ { authorizesCapabilityScope: async () => true },+ ),identity: createIdentityService(),- resolution: createResolutionService("org", createMemoryConfigStore("org"), acl),+ resolution: createResolutionService("org", config, acl),sessions,runs,workspace,@@ -199,6 +221,10 @@ for (const [surface, flags] of [const omit = (options: AgentToolsOptions) =>Object.fromEntries(Object.entries(options).filter(([key]) => !(key in SUBAGENT_EXCEPTIONS)));assert.deepEqual(omit(child.options), omit(parent.options));+ assert.equal(parent.ref.current?.humanTurn, true);+ assert.equal(child.ref.current?.humanTurn, undefined);+ assert.equal(parent.requestedRuntime?.fastMode, true);+ assert.equal(child.requestedRuntime?.fastMode, undefined);const asParent = { ...child.options, ...Object.fromEntries(exceptions.map((key) => [key, parent.options[key]])) };assert.deepEqual(createAgentTools(child.ref, asParent)@@ -213,3 +239,27 @@ for (const [surface, flags] of [);});}++test("human-descended tasks cannot finish silently without surface tools", async () => {+ const w = await world(["persistent_subagents"], (turn, child) => {+ if (turn.results.length) return;+ return child+ ? { tool: "finish_silently", args: {} }+ : { tool: "subagents", args: { action: "open", task: "report the result" } };+ });+ const { child } = await w.parentTurn("web", "web:U1:silence");+ assert.equal(child.results[0]?.isError, true);+});++test("human-descended tasks can change their runtime but not scope defaults", async () => {+ const w = await world(["persistent_subagents"], script);+ const { parent, child } = await w.parentTurn("web", "web:U1:runtime");+ const active = { harnessId: "pi" as const, modelId: "claude-opus-5", effortLevel: "high", fastMode: false };+ assert.ok(child.runtime);+ assert.equal((await child.runtime(active, { action: "set", model: "Astra", lifetime: "task" })).ok, true);+ assert.deepEqual(await child.runtime(active, { action: "set", model: "Astra", lifetime: "scope" }), {+ ok: false,+ error: "live_actor_required",+ });+ assert.equal((await parent.runtime!(active, { action: "set", model: "Astra", lifetime: "scope" })).ok, true);+});diff --git a/test/subagent-task-visibility.test.ts b/test/subagent-task-visibility.test.tsindex a9a279520..f8527ca68 100644--- a/test/subagent-task-visibility.test.ts+++ b/test/subagent-task-visibility.test.ts@@ -23,9 +23,11 @@ test("a subagent shows its delegated tasks while the parent's completion wake stactor: { externalId: "U1" },conversation: { kind: "dm", threadRef },text: "hello",+ origin: { kind: "human" },});const parentRun = (await built.runs.latestForThread(threadRef))!;const parentSession = (await built.sessions.getByThread(threadRef))!;+ await built.config.setPersonalModelAuth("U1", true, "openai");await built.featureFlags.setEnabled("responsive_spine", parentSession.scopeId, true, "U1");const syscalls = createSessionSyscalls({sessions: built.sessions,@@ -33,7 +35,11 @@ test("a subagent shows its delegated tasks while the parent's completion wake stsignals: built.signals,mailbox: createSessionMailbox(createMemoryMap<SessionMessage>()),maxAttempts: 1,- }).forTurn({ session: parentSession, scopeId: parentSession.scopeId, request: parentRun.request });+ }).forTurn({+ session: parentSession,+ scopeId: parentSession.scopeId,+ request: { ...parentRun.request, runId: parentRun.id },+ });const finished = async (lookup: () => Promise<Run | null | undefined>) => {let run: Run | null | undefined;await settle(async () => ["done", "failed"].includes((run = await lookup())?.status ?? ""));@@ -44,7 +50,8 @@ test("a subagent shows its delegated tasks while the parent's completion wake stconst session = (await built.sessions.getByThread(run.sessionId))!;const entries = await built.sessions.getEntries(session.id);const { payload } = entries.find((entry) => entry.type === "user" && entry.seq === run.turnUserSeq)!;- const { hidden, display } = payload as { hidden?: boolean; display?: string };+ const { hidden, display, speakerId } = payload as { hidden?: boolean; display?: string; speakerId?: string };+ assert.equal(speakerId, undefined, "delegated input is not a new human message");return { hidden: hidden === true, display };};@@ -53,11 +60,106 @@ test("a subagent shows its delegated tasks while the parent's completion wake stconst child = (await built.sessions.get(opened.sessionId))!;built.runtime.startBackground();const first = await finished(() => built.runs.latestForThread(child.threadRef));+ assert.equal(first.request.origin.kind, "human");assert.deepEqual(await userEntry(first), { hidden: false, display: "Summarize the repo" });const wake = await finished(() => built.runs.getByDedupKey(`subagent-return:${first.id}`));assert.equal((await userEntry(wake)).hidden, true);+ assert.equal(wake.request.origin.kind, "human");assert.ok((await syscalls.write({ followup: true, target: child.id, text: "Check the tests too" })).ok);const second = await finished(() => built.runs.latestForThread(child.threadRef));assert.deepEqual(await userEntry(second), { hidden: false, display: "Check the tests too" });});++test("human-origin delegated input is screened before model execution", async (t) => {+ const screened: string[] = [];+ const built = buildApp(testConfig({ memoryCapture: "off", securityPosture: "strict" }), {+ securityScreener: {+ provider: "test-screen",+ async classify(input) {+ screened.push(input.payload);+ return {+ score: 1,+ threshold: 0.5,+ verdict: input.payload.includes("UNTRUSTED_TASK")+ ? { decision: "strict", reason: "test block" }+ : { decision: "auto" },+ };+ },+ },+ });+ t.after(async () => {+ built.scheduler.stop();+ built.deploymentLayerRefresh.stop();+ await built.runtime.stop();+ });+ const threadRef = "dm:U1:screen-delegation";+ await built.app.turn({+ surface: "test",+ actor: { externalId: "U1" },+ conversation: { kind: "dm", threadRef },+ origin: { kind: "human" },+ text: "inspect a task",+ });+ const parent = (await built.runs.latestForThread(threadRef))!;+ const session = (await built.sessions.getByThread(threadRef))!;+ const syscalls = createSessionSyscalls({+ sessions: built.sessions,+ runs: built.runs,+ signals: built.signals,+ mailbox: createSessionMailbox(createMemoryMap<SessionMessage>()),+ maxAttempts: 1,+ }).forTurn({ session, scopeId: session.scopeId, request: { ...parent.request, runId: parent.id } });+ const opened = await syscalls.open({ task: "UNTRUSTED_TASK" });+ assert.ok(opened.ok);+ const child = (await built.sessions.get(opened.sessionId))!;+ const run = (await built.runs.latestForThread(child.threadRef))!;+ assert.equal(run.request.origin.kind, "human");+ built.runtime.startBackground();+ await settle(async () => ["done", "failed"].includes((await built.runs.get(run.id))!.status));+ assert.equal((await built.runs.get(run.id))!.result?.status, "pending_approval");+ assert.ok(screened.some((payload) => payload.includes("session-delegation") && payload.includes("UNTRUSTED_TASK")));+});++for (const fork of [false, true]) {+ test(`a human-initiated ${fork ? "fork" : "new session"} shows its seed without claiming human authorship`, async (t) => {+ const { startSession } = await import("../src/api/start-session.ts");+ const built = buildApp(testConfig({ memoryCapture: "off" }));+ t.after(async () => {+ built.scheduler.stop();+ built.deploymentLayerRefresh.stop();+ await built.runtime.stop();+ });+ const threadRef = `web:U1:seed-${fork}`;+ await built.app.turn({+ surface: "web",+ actor: { externalId: "U1" },+ conversation: { kind: "dm", threadRef },+ origin: { kind: "human" },+ text: "start another task",+ });+ const parent = (await built.runs.latestForThread(threadRef))!;+ const session = (await built.sessions.getByThread(threadRef))!;+ await built.config.setPersonalModelAuth("U1", true, "openai");+ const out = await startSession(built.app, built.sessions, "U1", {+ scopeId: session.scopeId,+ ...(fork ? { forkOf: session.id } : {}),+ text: "work on the seed",+ origin: parent.request.origin,+ sessionSenderId: session.id,+ delegatingRunId: parent.id,+ });+ assert.ok("session" in out);+ const queued = (await built.runs.latestForThread(out.session.threadRef))!;+ assert.equal(queued.request.modelAccount, "company");+ built.runtime.startBackground();+ await settle(async () => (await built.runs.get(queued.id))!.status === "done");+ const run = (await built.runs.get(queued.id))!;+ assert.equal(run.result?.status, "ok");+ const entry = (await built.sessions.getEntries(out.session.id)).find((entry) => entry.seq === run.turnUserSeq)!;+ const payload = entry.payload as { hidden?: boolean; speakerId?: string; text?: string };+ assert.equal(payload.hidden === true, false);+ assert.equal(payload.speakerId, undefined);+ assert.equal(payload.text, "work on the seed");+ });+}