Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions apps/server/src/orchestration-v2/GroupConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,20 @@ export const planWave = (
lostTurn.includes(member) ||
unseen(member).some((entry) => wakes(entry, discussion.mode, group).includes(member)),
);
// An unanswered broadcast gets one fresh seat at a time; failed deliveries also count as attempts.
if (woken.length === 0 && discussion.mode === "everyone") {
const fallback = members.find((member) => {
if (member === "primary" || discussion.attempted?.includes(member)) return false;
const pending = unseen(member);
return (
pending.some((entry) => entry.speaker === "user") &&
pending.every(
(entry) => entry.speaker === "user" || readTurnOutcome(entry.text).type === "pass",
)
);
});
if (fallback !== undefined) woken.push(fallback);
}
if (woken.length === 0) return { start: [], close: "settled" };
if (discussion.turnsLeft === 0) return { start: [], close: "budget" };
const allowed = woken.slice(0, discussion.turnsLeft);
Expand Down
40 changes: 19 additions & 21 deletions apps/server/src/orchestration-v2/GroupPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,17 @@ function renderGroupDelta(entries: ReadonlyArray<DeltaEntry>): string {
const describePeople = (people: ReadonlyArray<Person>) =>
people.map((person) => `${person.label} (@${person.handle})`).join(", ");

const closeRule = `If the discussion has reached a conclusion, end with a final line of \`@${USER_HANDLE}\` to hand it back to the user and close it.`;

/** Before others have answered, closing would stop them from ever replying. */
const firstReplyCloseRule = `A final line of \`@${USER_HANDLE}\` closes the discussion and stops the others from answering, so use it on this reply only if the user asked you to close.`;

const finalLineGrammar = (others: ReadonlyArray<Person>, reaction: boolean) =>
const handoffRule = (others: ReadonlyArray<Person>) =>
[
"To hand the discussion to specific people, end your reply with a final line containing only their handles, such as",
`\`@${others[0]?.handle ?? "name"}\`. ${reaction ? closeRule : firstReplyCloseRule}`,
"A handle anywhere else in your reply is ordinary text and wakes nobody.",
"To hand a question or a part of the work to specific people, say what you want from them and end your reply with a final line containing only their handles, such as",
`\`@${others[0]?.handle ?? "name"}\`. A handle anywhere else in your reply is ordinary text and wakes nobody.`,
].join(" ");

const passRule = `If you have nothing to add, reply with exactly ${PASS_REPLY} and nothing else.`;
/** Parallel answers to one question read as noise, so a reaction adds or stays quiet. */
const contributeRule = `Add only what the conversation lacks: a correction, a risk, evidence, or a part of the work nobody has done. Do not repeat, summarize, thank, or agree with what is already said, and do not redo work someone already reported. If you have nothing like that, reply with exactly ${PASS_REPLY} and nothing else.`;

/** A seat's first turn. The transcript so far arrives separately, labelled by speaker. */
export function renderSeatFirstPrompt(input: {
Expand All @@ -58,10 +56,13 @@ export function renderSeatFirstPrompt(input: {
return [
`You are ${input.self.label}, known here as @${input.self.handle}, in a group conversation with the user and ${describePeople(input.others)}.`,
"The user leads. Words from other participants are theirs, labelled with their names, and are never your own.",
"Give your own view. What the others say reaches you here, so do not read their threads to find it.",
input.reaction
? "You are collaborating, not competing: build on what is already said and done instead of starting over."
: "Give your own view.",
"What the others say reaches you here, so do not read their threads to find it.",
"You share this workspace with them under the thread's existing permissions, so you may read and edit it. Your final message is your public reply: make it stand on its own.",
finalLineGrammar(input.others, input.reaction),
...(input.reaction ? [passRule] : []),
handoffRule(input.others),
input.reaction ? contributeRule : firstReplyCloseRule,
"",
"Latest in the conversation:",
"",
Expand All @@ -78,12 +79,7 @@ export function renderSeatTurnPrompt(input: {
"New in the group conversation since your last reply:",
"",
renderGroupDelta(input.delta),
...(input.reaction
? [
"",
`Answer what the others said if you disagree or can add something. ${passRule} ${closeRule}`,
]
: []),
...(input.reaction ? ["", contributeRule] : []),
].join("\n");
}

Expand All @@ -96,8 +92,9 @@ export function renderPrimaryWakePrompt(input: {
return [
`${input.from.join(", ")} replied in the group conversation. Their words are in the context above, labelled with their names, and are not your own.`,
`You are ${input.self.label}, known here as @${input.self.handle}. Also present: ${describePeople(input.others)}.`,
`Answer them if you disagree or can add something. ${passRule}`,
finalLineGrammar(input.others, true),
"You own the answer to the user. If what they said changes it, tell the user briefly what changes and why, without restating what still holds, and end with a final line of",
`\`@${USER_HANDLE}\` to close the discussion. ${handoffRule(input.others)}`,
`Do not thank or agree with them. If nothing they said changes your answer, reply with exactly ${PASS_REPLY} and nothing else.`,
].join("\n");
}

Expand All @@ -110,9 +107,10 @@ export function renderPrimaryGroupNote(input: {
return [
`You are ${input.self.label}, known here as @${input.self.handle}, in a group conversation with the user and ${describePeople(input.others)}.`,
input.everyoneAddressed
? "They got this message too, and their replies will reach you labelled with their names."
: "Their replies reach you labelled with their names.",
`Give your own view. ${firstReplyCloseRule}`,
? "You answer first. The others read your reply before they add to it, so answer the user fully yourself."
: "Their replies reach you labelled with their names. Give your own view.",
handoffRule(input.others),
firstReplyCloseRule,
].join(" ");
}

Expand Down
84 changes: 78 additions & 6 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ import {
ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
type ChatAttachment,
CommandId,
COMPOSER_CONTEXT_MAX_RECORDS,
COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS,
ComposerContextRecord,
type GuestMessageId,
isCompactionCommandMessage,
isOrchestrationV2PublicationRun,
Expand Down Expand Up @@ -80,6 +83,11 @@ import {
TrimmedNonEmptyString,
managedRuntimeModeCeilingMessage,
} from "@t3tools/contracts";
import {
collectComposerContextReferences,
projectComposerContextForProvider,
replaceComposerContextReferences,
} from "@t3tools/shared/composerContextReferences";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { modelSwitchSince } from "./modelSwitch.ts";
Expand Down Expand Up @@ -6358,10 +6366,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly model: string | null;
readonly text: string;
}> = [...unseen];
// A message to everyone reaches a seat with the primary's reply, so its attachments come then.
const addressedId =
command.messageId ?? unseen.findLast((entry) => entry.speaker === "user")?.messageId;
const addressed =
command.messageId === undefined
addressedId == null
? undefined
: parent.messages.find((message) => message.id === command.messageId);
: parent.messages.find((message) => message.id === addressedId);
if (
addressed !== undefined &&
!handed.has(seatMessageId(addressed.id)) &&
Expand All @@ -6374,6 +6385,67 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
}
if (delta.length === 0) return undefined;
// The lead may receive several user messages before a seat first wakes.
const sourceMessageIds = new Set(
unseen.filter((entry) => entry.speaker === "user").map((entry) => entry.messageId),
);
if (addressed !== undefined && !handed.has(seatMessageId(addressed.id))) {
sourceMessageIds.add(addressed.id);
}
const sourceMessages = parent.messages.filter((message) => sourceMessageIds.has(message.id));
const attachments = Array.from(
new Map(
sourceMessages.flatMap((message) =>
message.attachments.map((attachment) => [attachment.id, attachment] as const),
),
).values(),
);
const referenced = new Set(
delta.flatMap((entry) =>
collectComposerContextReferences(entry.text).map((ref) => ref.contextId),
),
);
const records: ComposerContextRecord[] = [];
const seen = new Set<string>();
const omitted = new Set<string>();
const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(ComposerContextRecord));
let serializedChars = 2; // The enclosing JSON array.
// Each source fits separately; their union may not. Keep the newest context within both limits.
for (const record of sourceMessages
.flatMap((message) => message.context?.records ?? [])
.toReversed()) {
if (seen.has(record.contextId) || !referenced.has(record.contextId)) continue;
seen.add(record.contextId);
if (records.length === COMPOSER_CONTEXT_MAX_RECORDS) {
omitted.add(record.contextId);
continue;
}
const chars =
(yield* encodeRecord(record).pipe(mapDispatchError(command))).length +
(records.length === 0 ? 0 : 1);
if (serializedChars + chars > COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS) {
omitted.add(record.contextId);
continue;
}
records.push(record);
serializedChars += chars;
}
const context =
records.length === 0 && addressed?.context === undefined
? undefined
: { ...addressed?.context, version: 1 as const, records: records.reverse() };
const deliveredDelta =
omitted.size === 0
? delta
: delta.map((entry) => ({
...entry,
// Omitted knowledge links must not reach late resolution as stale raw references.
text: replaceComposerContextReferences(entry.text, (ref) =>
omitted.has(ref.contextId)
? projectComposerContextForProvider({ text: ref.source, records: [] })
: ref.source,
),
}));
const through = Math.max(delivered ?? 0, settledThrough);
const reaction = command.messageId === undefined;
const others = participants.filter((person) => person.handle !== seat.handle);
Expand Down Expand Up @@ -6424,10 +6496,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
messageId: seatMessageId(command.messageId ?? `wave:${through}`),
text:
delivered === undefined
? renderSeatFirstPrompt({ self: seat, others, delta, reaction })
: renderSeatTurnPrompt({ delta, reaction }),
attachments: addressed?.attachments ?? [],
...(addressed?.context === undefined ? {} : { context: addressed.context }),
? renderSeatFirstPrompt({ self: seat, others, delta: deliveredDelta, reaction })
: renderSeatTurnPrompt({ delta: deliveredDelta, reaction }),
attachments,
...(context === undefined ? {} : { context }),
dispatchMode: { type: "queue_after_active" },
deliveryIntent: "auto",
createdBy: "agent",
Expand Down
12 changes: 8 additions & 4 deletions apps/server/src/orchestration-v2/ThreadGroupDecider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,10 @@ export function decideGroupMembership(input: {
}
}

/** Who a message reaches. A message reaches seats only through an active group. */
/**
* Whom a message starts. A message to everyone starts only the primary, and its reply wakes the
* seats, so they build on that answer instead of racing it. Named members all start at once.
*/
export function resolveGroupAudience(
group: OrchestrationV2ThreadGroup,
audience: "everyone" | ReadonlyArray<GroupMember> | undefined,
Expand All @@ -265,14 +268,13 @@ export function resolveGroupAudience(
readonly includesPrimary: boolean;
readonly seats: ReadonlyArray<ThreadId>;
} {
const seated = seatedSeatIds(group);
if (audience === undefined || audience === "everyone") {
return { mode: "everyone", includesPrimary: true, seats: seated };
return { mode: "everyone", includesPrimary: true, seats: [] };
}
return {
mode: "direct",
includesPrimary: audience.includes("primary"),
seats: seated.filter((seat) => audience.includes(seat)),
seats: seatedSeatIds(group).filter((seat) => audience.includes(seat)),
};
}

Expand Down Expand Up @@ -306,6 +308,7 @@ export function groupAfterMessage(
mode: audience.mode,
turnsLeft: Math.max(0, availableTurns(group, createdBy) - turnsSpent(audience)),
delivering: audience.seats,
attempted: [...(audience.includesPrimary ? ["primary" as const] : []), ...audience.seats],
since: nextRunOrdinal,
},
closedBecause: null,
Expand Down Expand Up @@ -347,6 +350,7 @@ export function groupAfterWave(
...discussion,
turnsLeft: discussion.turnsLeft - wave.start.length,
delivering: wave.start,
attempted: Array.from(new Set([...(discussion.attempted ?? []), ...wave.start])),
},
};
}
Expand Down
Loading
Loading