Skip to content
3 changes: 3 additions & 0 deletions docs/concepts/actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ The actor is the authenticated session identity accountable for an action execut
- The trust boundary resolves the actor from primary session material, never from forwarded headers or app-supplied input ([access control](../architecture/access-control.md)).
- An automated dashboard message keeps its accountable actor separate from its source. With a guardian chain actor, the main agent, Concierge, and apps speak for the guardian: their messages use the guardian's avatar and viewer-relative side, with the source named below the bubble.
- Other sources, absent or anonymous chain actors, and visitor chains speak for themselves on the left with an Automated label. Each automated turn tells the receiving agent the guardian did not type it. Permissions and approvals stay unchanged.
- A live private Concierge turn may send one attributed input to a task owned by the same person and started in that Concierge chat. The host captures the source at tool-handler entry, before asynchronous setup, and binds the handoff to that turn, target chat, and exact input. It expires after 30 seconds and is consumed once. Stop, closure, a changed actor, chat or audience, or an archived chat refuse admission. A visitor stays a visitor. Group, unknown, forked, and autonomous sources grant no actor.
- The task message keeps Concierge as its source. Its admitted turn carries the verified actor through the usual action chain, without inheriting an approval. Model arguments, message text, and HTTP fields cannot grant an actor. Stopping the source before admission revokes its handoff. A follow-up from the same person in the same private chat, with the same audience, may supersede the source without revoking a pending handoff. It retains the captured actor, expiry and single-use limit. Any intervening identity or scope change revokes it permanently, even if a later input restores the original context. A callback with no eligible actor stays an ordinary automated send and never acquires an actor from a later turn. A refused handoff returns a delivery error even when its input was recorded. It does not run as unattributed work. The source actor stays unchanged for other tools. After admission the task has its own cancellation lifetime. Its [audience](../domains/participation.md#audience) is never more private than the source turn.
- A guardian handoff requires a private source audience. A shared guardian source grants no actor through this path.
- A guardian actor records the guardian seat, plus the bound cloud account id and email when known. A password-only seat has no email to record.
- Session-lifecycle audit telemetry stamps the same actor with the same absent-versus-anonymous semantics, so lifecycle changes are attributable from exported telemetry alone.

Expand Down
2 changes: 2 additions & 0 deletions docs/domains/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ The tools a session carries beyond the ones every session of its agent has, such

- A fork's session tools are its source's: the model is offered the same tools in the fork as in the source. The fork runs the ones it can run on its own, and refuses the others as unavailable in a forked turn. Until a session's tools are stored, the open session carries the tools its source last opened with. The rule is `forkSessionTools` in [`packages/core/src/agent/domain/session-tools.ts`](../../packages/core/src/agent/domain/session-tools.ts).

- Concierge's session tools may hand an attributed input to a private task through the host's turn-bound input path. The [actor contract](../concepts/actions.md#actor) defines its scope and cancellation. This path grants neither an action outside the receiving agent's catalog nor an approval.

## Turn middleware

What an installed app puts around producing a turn's reply. A middleware may rewrite the turn's prompt, answer the turn itself, or let the model answer. The model's reply is innermost and runs only when every middleware continues. Apps declare it as a `turn-middleware` hook, and an agent whose turns always come from one is code-backed.
Expand Down
87 changes: 84 additions & 3 deletions packages/core/src/agent/application/agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import {
forkSessionTools,
} from "../domain/session-tools.js";
import { type ForkOpening, type ForkRequest, keepsFork, openFork } from "../domain/fork.js";
import { type TurnFacts, type PushLevel, type TurnActor } from "../domain/turn-facts.js";
import { type TurnFacts, type PushLevel, type TurnActor, sameActor } from "../domain/turn-facts.js";
import { type Audience, turnAudience } from "../domain/turn-audience.js";
import {
NO_ROME_TOOLS,
Expand Down Expand Up @@ -825,6 +825,8 @@ interface TurnExecRefs {
bindTurnCtx: <T>(fn: () => T) => T;
/** Who the running turn acts for; its subagents' turns act for the same person. */
getActor: () => TurnActor | undefined;
isLive?: () => boolean;
captureTaskInputLiveness?: () => () => boolean;
/** Who can read the running turn; its subagents' turns are never more private. */
getAudience: () => Audience;
}
Expand Down Expand Up @@ -1435,6 +1437,8 @@ async function openSession(
attachSubagentCall: (toolUseId, call) => impl.addSubagentCall(toolUseId, call),
bindTurnCtx: inCurrentTurnCtx,
getActor: () => impl.currentTurnActorRef,
isLive: () => impl.currentTurnLiveRef,
captureTaskInputLiveness: () => impl.captureTaskInputLiveness(),
getAudience: () => impl.currentTurnAudienceRef,
};

Expand Down Expand Up @@ -1463,6 +1467,8 @@ async function openSession(
sharedContext: refs.getSharedContext,
pushLevel,
actor: refs.getActor,
live: () => refs.isLive?.() === true,
captureTaskInputLiveness: refs.captureTaskInputLiveness,
audience: refs.getAudience,
reportedTask,
inTurn: refs.bindTurnCtx,
Expand Down Expand Up @@ -2051,6 +2057,7 @@ interface TurnSink {
/** The guardian stopped the turn, not a `now` input superseding it. Its
* read inputs are then done with: the next turn hands none of them on. */
stoppedByGuardian: boolean;
taskInputContinues: boolean;
subagentCallsByToolUse: Map<string, { key: SubagentCallKey; call: SubagentCall }>;
pendingSubagentToolUses: Map<string, Extract<AgentEvent, { type: "tool_use" }>>;
emittedSubagentStarts: Set<string>;
Expand Down Expand Up @@ -2211,6 +2218,8 @@ class AgentSessionImpl implements AgentSession {
private sharedContext?: Record<string, unknown>;
private statusListeners = new Map<string, AgentSessionStatusListener>();
private currentSink: TurnSink | null = null;
private taskInputEpoch = 0;
private taskInputScope?: Pick<TurnSink, "actor" | "audience" | "threadContext">;
// Spans for the current turn. Both are opened in runOneTurn and closed in
// runEventsLoop when the terminal `result`/`error` message lands, so the
// trace contract is complete by the time the sink closes (i.e. before
Expand Down Expand Up @@ -2283,7 +2292,10 @@ class AgentSessionImpl implements AgentSession {
error: error instanceof Error ? error.message : String(error),
}),
(turnId) => {
if (this.currentSink?.turnId === turnId) this.currentSink.actor = undefined;
if (this.currentSink?.turnId === turnId) {
this.taskInputEpoch++;
this.currentSink.actor = undefined;
}
},
);
private keepAlive: boolean;
Expand Down Expand Up @@ -2387,6 +2399,50 @@ class AgentSessionImpl implements AgentSession {
return this.currentSink?.actor;
}

get currentTurnLiveRef(): boolean {
return (
!!this.currentSink &&
!this.currentSink.done &&
!this.currentSink.lifecycleInterrupted &&
!this.closing
);
}

captureTaskInputLiveness(): () => boolean {
const sink = this.currentSink;
const epoch = this.taskInputEpoch;
if (!sink || !this.currentTurnLiveRef) return () => false;
return () =>
this.taskInputEpoch === epoch &&
!this.closing &&
!sink.stoppedByGuardian &&
(sink.taskInputContinues || (!sink.done && !sink.lifecycleInterrupted));
}

private observeTaskInputScope(options?: SendTurnOptions): boolean {
const thread = options?.threadContext ?? this.threadContext;
const audience = turnAudience(thread, {
actor: options?.actor,
parent: options?.parentAudience,
place: this.placeAudience,
});
const previous = this.taskInputScope;
const same =
!!previous &&
sameActor(previous.actor, options?.actor) &&
previous.audience === audience &&
previous.threadContext?.channel === thread?.channel &&
previous.threadContext?.threadId === thread?.threadId &&
previous.threadContext?.threadType === thread?.threadType;
if (!same) this.taskInputEpoch++;
this.taskInputScope = {
actor: options?.actor ? { ...options.actor } : undefined,
audience,
threadContext: thread ? { ...thread } : undefined,
};
return same;
}

/** The running turn's audience; between turns, the session's place read alone. */
get currentTurnAudienceRef(): Audience {
return (
Expand Down Expand Up @@ -3521,6 +3577,17 @@ class AgentSessionImpl implements AgentSession {
submit(input: AgentTurnInput, options: SubmitOptions = {}): AgentInputReceipt {
if (this.status === "closed") throw new Error(`AgentSession ${this.sessionId} is closed`);
const { priority = "next", onInputStatus, ...turnOptions } = options;
// Observe before the queue synchronously stops a superseded turn. A changed
// scope revokes old callbacks even if another input restores it before delivery.
const sameScope = this.observeTaskInputScope(turnOptions);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] correctness — An automated input queued after a same-person supersede revokes a pending handoff before it runs

Every submit observes its scope, including after/next inputs that do not supersede the running turn. Here is the race: a backend task event is waiting behind T1's stream, and the guardian sends a now follow-up while chat_start is cold-opening. T1's stream then finishes, and the event's submit("after", actor: undefined) bumps the epoch. chat_start then fails permanently ("Do not start it again"), even though no other identity has run in the source session. The race is narrow. Optional fix: observe at submit only for now inputs. That is the case the comment's synchronous-stop argument needs. Leave runOneTurn and mixActors to catch other inputs once they actually run or are steered in.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed by the current submit/start path: an unattributed after input can revoke a pending handoff before that input runs. I am deferring this optional availability refinement, not treating it as an identity leak. The current contract conservatively revokes when a changed scope is accepted, and refuses visibly without retry or an anonymous fallback.

The suggested now-only observation is not sufficient on its own: startTurn also observes queued after work, and a next input can be steered into a running turn. mixActors covers identity changes, but not a same-actor thread/audience change on that steer. Deferring scope observation would need a reliable pre-steer scope boundary as well as the run-start boundary; simply removing the current observations loses that protection. I will keep that broader queue-policy refinement outside this focused repair. The owner-authorized same-person, unchanged-scope now case remains covered.

if (
priority === "now" &&
sameScope &&
this.currentSink &&
!this.currentSink.stoppedByGuardian
) {
this.currentSink.taskInputContinues = true;
}
if (!isQueueInput(priority)) {
const landed = afterLanding(this.turnMutex.isLocked());
const handle = this.startTurn(input, turnOptions);
Expand Down Expand Up @@ -3564,13 +3631,15 @@ class AgentSessionImpl implements AgentSession {
if (this.status === "closed") {
throw new Error(`AgentSession ${this.sessionId} is closed`);
}
this.observeTaskInputScope(options);
// turnId is allocated here, at the bottom of the agent
// stack, and threaded back to every consumer (route, tracing, IPC stream
// channel name). No upper layer ever invents one — eliminates duplicate
// / collision concerns by construction.
const turnId = uuidv7();
const { turn, writer } = createTurn(turnId, async (reason) => {
if (sink.done) return;
if (reason !== SUPERSEDED_INTERRUPT_REASON) this.taskInputEpoch++;
sink.lifecycleInterrupted = true;
if (this.currentSink === sink) await this.stopRunning(reason);
});
Expand Down Expand Up @@ -3603,6 +3672,7 @@ class AgentSessionImpl implements AgentSession {
lifecycleFinishDispatched: false,
lifecycleInterrupted: false,
stoppedByGuardian: false,
taskInputContinues: false,
subagentCallsByToolUse: new Map(),
pendingSubagentToolUses: new Map(),
emittedSubagentStarts: new Set(),
Expand Down Expand Up @@ -3717,6 +3787,11 @@ class AgentSessionImpl implements AgentSession {
span.end();
return;
}
this.observeTaskInputScope({
actor: sink.actor,
threadContext: sink.threadContext,
parentAudience: sink.audience,
});
this.currentSink = sink;
this.currentTurnId = turnId;
this.status = "running";
Expand Down Expand Up @@ -4128,6 +4203,8 @@ class AgentSessionImpl implements AgentSession {
}

async stop(reason?: string): Promise<void> {
// Stop also revokes a pending handoff between two superseded turns.
this.taskInputEpoch++;
await this.stopRunning(reason);
}

Expand All @@ -4136,7 +4213,10 @@ class AgentSessionImpl implements AgentSession {
const sink = this.currentSink;
if (!sink || sink.done || (expectedTurnId && sink.turnId !== expectedTurnId)) return;
sink.lifecycleInterrupted = true;
if (reason !== SUPERSEDED_INTERRUPT_REASON) sink.stoppedByGuardian = true;
if (reason !== SUPERSEDED_INTERRUPT_REASON) {
this.taskInputEpoch++;
sink.stoppedByGuardian = true;
}
// Cancel the provider before awaiting child cleanup. A slow child must
// not keep its parent generating after the user presses Stop.
await Promise.all([
Expand All @@ -4160,6 +4240,7 @@ class AgentSessionImpl implements AgentSession {
async close(reason: "idle" | "shutdown" | "error" | "user"): Promise<void> {
if (this.closingPromise) return await this.closingPromise;
if (this.status === "closed") return;
this.taskInputEpoch++;
this.inputs.close();
this.closingPromise = (async () => {
this.log.info("agent session closing", {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/agent/domain/turn-facts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ export interface TurnFacts {
widgets: WidgetDrawing;
/** The running turn's id, or undefined between turns. */
turnId(): string | undefined;
/** False once interrupted or closing. Absent facts cannot grant a task handoff. */
live?(): boolean;
/** Pins the live source before async task setup. Same-person supersession may
* continue it. Stop, close, or a changed person/chat/audience revokes it for good. */
captureTaskInputLiveness?(): () => boolean;
/** Where the running turn stands, else where the session does. */
threadContext(): ThreadContext | undefined;
sharedContext(): Record<string, unknown> | undefined;
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/agent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ export {
type SubmitOptions,
} from "./application/agent-input-queue.js";
export type { PushLevel, TurnActor, TurnFacts } from "./domain/turn-facts.js";
export { sameActor } from "./domain/turn-facts.js";
export {
type Audience,
messagingAudience,
Expand Down
Loading
Loading