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
2 changes: 1 addition & 1 deletion GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ The device-wide wait after any turn starts, user or proactive, spoken or silent,
_Avoid_: quiet gap, pacer gap, global gap

**Chain cap**:
The most addressed turns one window answers in a row without a user turn in between; `addressed_chain_max` in configs/guardrails.json, overridable on the Together page. The next one is dropped with reason `addressed_cap`.
The most addressed turns one window answers in a row without a user turn in between; `addressed_chain_max` in configs/guardrails.json, overridable on the Together page. Each admitted addressed turn tells the backend how much of that budget it has used. The next one is dropped with reason `addressed_cap`.
_Avoid_: ping-pong cap, chain limit, addressed limit

**Tier**:
Expand Down
2 changes: 1 addition & 1 deletion docs/agent-guide/architecture/map.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 10 additions & 2 deletions docs/reference/client-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ Everything between the header line and the closing tag is a sequence of `key: va
9. `tool switches`
10. `previous turn`
11. `overheard`
12. One or more `trigger:`, `cue note`, `last together`, `waited`, or `signal` lines, depending on what fired.
12. One or more `trigger:`, `exchange`, `cue note`, `last together`, `waited`, or `signal` lines, depending on what fired.
13. The `guide:` block, when the turn carries one ([Guide](#guide-in-app-help-button)).

A line is omitted outright when its underlying field is absent. For example, there is no `screenshot source:` line when screen capture is off.
Expand Down Expand Up @@ -600,7 +600,15 @@ trigger: addressed by alice: "bob, you took my chair" (0min ago)

Another open character's reply called `address_character` and named this character. That reply's playback has ended. The headline names the speaker and quotes what she said, with the minutes since it was spoken.

The `ClientContext` field is `trigger.addressed?: { from, text, ts, user_message? }`. `from` is the speaker's preset name. `text` is the reply's spoken text. `ts` is the epoch-ms moment the reply was spoken.
The `ClientContext` field is `trigger.addressed?: { from, text, ts, user_message?, exchange? }`. `from` is the speaker's preset name. `text` is the reply's spoken text. `ts` is the epoch-ms moment the reply was spoken.

An admitted addressed turn also carries `exchange?: { used, max }`. `used` is how many addressed replies this character has given since the user last spoke, and `max` is the chain cap the user set. When both numbers are present, the block renders one line right after the headline, a handoff included:

```text
exchange: the character has answered other characters 3 times since the user last spoke, at most 10; a reply without address_character ends the exchange
```

Without the field the line is omitted, and a turn that only waited in a bundle carries no exchange line. The line states the fact; whether this character answers again is the backend's judgment.

When the cursor has not passed the exchange yet, the same lines also ride in the [`overheard`](#overheard) block. The client routes the turn. Whether this character answers is the backend's judgment. A `[SILENT]` reply ends the exchange.

Expand Down
4 changes: 3 additions & 1 deletion docs/reference/client-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Each row gives one tool's purpose, its arguments and result, the transports that
| `generate_express` | Places an expression cue (face, body motion, voice tone) on the speech around the call | Arguments `emotion_id`, `motion_id`, `emotion_text`, `caption`, each optional ([cue contract](client-context.md#tool-arguments)). Result: the string `ok` | Responses and Chat Completions as a declared tool. Push as cues inside `render` and `speech` segments | `createGenerateExpressTool` in `src/io/chat/tools/express.ts` | `runClientCall` in `src/io/chat/stream/client-tool-run.ts` |
| `body_action` | Moves the body: sit on a window's top edge, peek around its edge, move to a named spot, or stand up | Arguments `action` plus the field it needs: `app` for `sit_on_window`, `side` for `peek`, `spot` and an optional `monitor` for `move_to`; `stand` needs none. Result: `ok`, or one of the words `not_found`, `blocked`, `interrupted`, `busy`, `unsupported`, `timeout` after its 15 s wait, or `error: missing field <app\|side\|spot>` and `error: invalid field <app\|side\|spot>` for an absent or invalid argument | Responses, Chat Completions, and Push (`tool_call`/`tool_result`) | `createAvatarTools` in `src/io/chat/tools/avatar.ts` | `runClientCall` in `src/io/chat/stream/client-tool-run.ts`; on Push the consumer in `src/io/chat/push/tool-calls.ts` |
| `rate_relation` | Moves this character's relation toward the user or another open character by one small step, with the reason | Arguments `toward`, `delta` and `why`. Result: the band word after the change, `clamped: <band>` when the cap or the range held the value, or a refusal such as `error: unknown target` ([details](#rate-relation)) | Responses, Chat Completions, and Push (`tool_call`/`tool_result`) | `createRateRelationTool` in `src/io/chat/tools/relation.ts` | `runClientCall` in `src/io/chat/stream/client-tool-run.ts`; on Push the consumer in `src/io/chat/push/tool-calls.ts` |
| `address_character` | Names the character this reply is for, so that character receives a turn after the reply's playback | Arguments `to` (string: a name from the `open characters:` line) and optional boolean `handoff`, which passes the user's message to that character to answer. Result: `ok`, `ignored: already addressed <name>`, `error: unknown target` | Responses, Chat Completions, and Push (`tool_call`/`tool_result`) | `createAddressCharacterTool` in `src/io/chat/tools/address-character.ts` | `runClientCall` in `src/io/chat/stream/client-tool-run.ts`; on Push the consumer in `src/io/chat/push/tool-calls.ts` |
| `address_character` | Names the character this reply is for, so that character receives a turn after the reply's playback; a reply without this call ends the characters' exchange | Arguments `to` (string: a name from the `open characters:` line) and optional boolean `handoff`, which passes the user's message to that character to answer. Result: `ok`, `ignored: already addressed <name>`, `error: unknown target` | Responses, Chat Completions, and Push (`tool_call`/`tool_result`) | `createAddressCharacterTool` in `src/io/chat/tools/address-character.ts` | `runClientCall` in `src/io/chat/stream/client-tool-run.ts`; on Push the consumer in `src/io/chat/push/tool-calls.ts` |
| `yui_run` | Runs a backend script against the `yui` API: YUI's settings, state and info, and the namespaces the window has ([The yui API](#the-yui-api)) | Argument `code` (string: an async function body). Result: a JSON object with `status`, `result` or `error`, `logs`, and the optional `note`, `writes` and `images` ([details](#yui_run)); `error: timed out after 121 s` when the wait passes | Responses, Chat Completions, and Push (`tool_call`/`tool_result`) | `createYuiRunTool` in `src/io/chat/tools/run/yui-run-tool.ts` | `runClientCall` in `src/io/chat/stream/client-tool-run.ts`; on Push the consumer in `src/io/chat/push/tool-calls.ts` |

## Declaration per transport
Expand Down Expand Up @@ -291,6 +291,8 @@ The backend names, per reply, which other open character the reply speaks to. `t

The schema carries no enum, so the declared set is identical whatever is open and provider prompt caches keep matching. The name is checked when the call runs against the presets open at that moment. The entry maps to the preset id; an entry outside the list answers `error: unknown target`. The user is never a target.

A reply that names no character ends the exchange between the characters. The tool's description tells the backend to name one only when it has something new to tell them.

### Handoff

Optional boolean `handoff` passes the user's message on this turn to the named character, who takes it and answers the user. The tool's description tells the model to set it only when the user asks to pass their message to that character, and to say only briefly in its own reply that it passed it on.
Expand Down
9 changes: 8 additions & 1 deletion src/contract/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,14 @@ export interface TriggerMeta {
/** proactive only: Math.round(gap_ms / 60000). */
idle_elapsed_min?: number;
/** addressed.* — another open character's reply named this character through address_character. */
addressed?: { from: string; text: string; ts: number; user_message?: string };
addressed?: {
from: string;
text: string;
ts: number;
user_message?: string;
/** The chain numbers the admission stamped: used since the user last spoke, the max it admitted under. */
exchange?: { used: number; max: number };
};
/** signals.batch / signals.catchup / signals.urgent / signals.urgent_catchup — grouped opaque items forwarded from the /signals ingress. */
signals?: SignalGroup[];
/** proactive.screen_* — a frontmost-app transition fired this turn. */
Expand Down
27 changes: 27 additions & 0 deletions src/dispatcher/backend/client-context-text.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1222,6 +1222,33 @@ describe("renderClientContext — exhaustiveness", () => {
],
];

it("renders the exchange line right after an addressed headline, and omits it without the field", () => {
const addressed = {
kind: "addressed" as const,
addressed: {
from: "perlica",
text: "natsume, you took my chair",
ts: NOW,
exchange: { used: 3, max: 10 },
},
};
const text = renderClientContext(baseContext(addressed), NOW);
expect(text).toContain(
'trigger: addressed by perlica: "natsume, you took my chair" (0min ago)\n' +
"exchange: the character has answered other characters 3 times since the user last spoke, at most 10; " +
"a reply without address_character ends the exchange",
);

const without = renderClientContext(
baseContext({
kind: "addressed",
addressed: { from: "perlica", text: "natsume, you took my chair", ts: NOW },
}),
NOW,
);
expect(without).not.toContain("exchange:");
});

it.each(
CASES,
)("%s trigger kind renders its distinctive fields, not just any trigger: line", (_name, trigger, expectedSubstrings) => {
Expand Down
6 changes: 6 additions & 0 deletions src/dispatcher/backend/client-context-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,11 @@ function addressedBody(a: NonNullable<TriggerMeta["addressed"]>): string {
: `addressed by ${oneLine(a.from)}: "${oneLine(a.text)}"`;
}

/** The exchange fact an addressed turn carries: the used budget, the max, and that silence ends it. */
function exchangeLine(e: { used: number; max: number }): string {
return `exchange: the character has answered other characters ${e.used} time${e.used === 1 ? "" : "s"} since the user last spoke, at most ${e.max}; a reply without address_character ends the exchange`;
}

/** The reply as the subject of a past-event line. */
function addressedPastBody(a: NonNullable<TriggerMeta["addressed"]>): string {
return a.user_message !== undefined
Expand Down Expand Up @@ -287,6 +292,7 @@ function renderTrigger(trigger: TriggerMeta, nowMs: number): string[] {
lines.push(
`trigger: ${addressedBody(trigger.addressed)} (${minutesSince(trigger.addressed.ts, nowMs)}min ago)`,
);
if (trigger.addressed.exchange) lines.push(exchangeLine(trigger.addressed.exchange));
} else if (trigger.kind === "user") {
const addressed =
trigger.mention === "everyone"
Expand Down
30 changes: 30 additions & 0 deletions src/dispatcher/backend/context-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,36 @@ describe("buildClientContext — addressed forwarding", () => {
expect(client.trigger.kind).toBe("addressed");
expect("addressed" in client.trigger).toBe(false);
});

it("projects the stamped exchange when both numbers are present and the max is positive, and omits it at max 0", () => {
const client = buildClientContext(
CTX,
addressedEnv({
from: "perlica",
name: "Perlica",
line: "natsume, you took my chair",
exchange: { used: 3, max: 10 },
}),
);

expect(client.trigger.addressed).toEqual({
from: "Perlica",
text: "natsume, you took my chair",
ts: 1_717_000_000_000,
exchange: { used: 3, max: 10 },
});

const capped = buildClientContext(
CTX,
addressedEnv({ from: "perlica", name: "Perlica", line: "hi", exchange: { used: 1, max: 0 } }),
);

expect(capped.trigger.addressed).toEqual({
from: "Perlica",
text: "hi",
ts: 1_717_000_000_000,
});
});
});

describe("buildClientContext — mention forwarding", () => {
Expand Down
10 changes: 10 additions & 0 deletions src/dispatcher/backend/context-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,16 +137,26 @@ export function signalsOf(env: BusEnvelope): TriggerMeta["signals"] | undefined
function addressedOf(env: BusEnvelope): TriggerMeta["addressed"] | undefined {
if (env.event_name !== ADDRESSED_EVENT) return undefined;
const { name, line, user_message } = env.payload ?? {};
const exchange = exchangeOf(env);
return typeof name === "string" && typeof line === "string"
? {
from: name,
text: line,
ts: env.ts,
...(typeof user_message === "string" ? { user_message } : {}),
...(exchange ? { exchange } : {}),
}
: undefined;
}

/** The exchange numbers release and the gate grant stamped, present only on an admitted addressed turn. */
function exchangeOf(env: BusEnvelope): NonNullable<TriggerMeta["addressed"]>["exchange"] {
const raw = env.payload?.exchange;
if (raw === null || typeof raw !== "object") return undefined;
const { used, max } = raw as { used?: unknown; max?: unknown };
return typeof used === "number" && typeof max === "number" && max > 0 ? { used, max } : undefined;
}

function screenOf(env: BusEnvelope): TriggerMeta["screen"] | undefined {
if (!env.event_name.startsWith("proactive.screen_")) return undefined;
const payload = env.payload;
Expand Down
13 changes: 13 additions & 0 deletions src/dispatcher/core/addressed-chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ export interface AddressedChain {
canAdmit(pending?: number): boolean;
/** Counts `n` admitted addressed turns, one by default. */
count(n?: number): void;
/** The count after the last charge; the exchange line's used. */
taken(): number;
/** The cap the last admission read; the exchange line's max. */
max(): number;
reset(): void;
}

Expand All @@ -14,8 +18,17 @@ export function createAddressedChain(max: () => number): AddressedChain {
count(n = 1) {
taken += n;
},
taken: () => taken,
max,
reset() {
taken = 0;
},
};
}

/** Stamps the used count beside the max release stamped, before the context awaits. */
export function stampExchangeUsed(env: { payload?: Record<string, unknown> }, used: number): void {
const exchange = env.payload?.exchange as { max?: unknown } | undefined;
if (!exchange || typeof exchange.max !== "number") return;
env.payload = { ...env.payload, exchange: { max: exchange.max, used } };
}
4 changes: 4 additions & 0 deletions src/dispatcher/core/waiting-release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export interface ReleaseInput {
admissible: (env: BusEnvelope) => boolean;
/** The addressed chain's room, with `pending` addressed entries already taken. */
canAdmit: (pending: number) => boolean;
/** The cap the admission reads, stamped on each admitted addressed envelope. */
exchangeMax: () => number;
/** Drained groups may join waiting entries: do-not-disturb is off. */
groupsJoin: boolean;
/** Drained groups may go out alone: the edge into a free slot. */
Expand All @@ -81,6 +83,8 @@ export function planRelease(input: ReleaseInput): {
if (!isAddressedEvent(w.env)) return true;
if (!input.canAdmit(addressed)) return false;
addressed += 1;
// Stamp the max the admission used, for the context's exchange line.
w.env.payload = { ...w.env.payload, exchange: { max: input.exchangeMax() } };
return true;
});
const overCap = input.list.take((w) => isAddressedEvent(w.env) && !input.canAdmit(addressed));
Expand Down
4 changes: 3 additions & 1 deletion src/dispatcher/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import type {
TurnOutcome,
} from "./backend/backend-caller";
import { userTextOf } from "./backend/context-builder";
import type { AddressedChain } from "./core/addressed-chain";
import { type AddressedChain, stampExchangeUsed } from "./core/addressed-chain";
import { createAdmission } from "./core/admission";
import {
classify,
Expand Down Expand Up @@ -433,6 +433,7 @@ export function createDispatcher(deps: DispatcherDeps): Dispatcher {
if (admission.heldByDndAny(env, members)) return "dnd";
guardrails.spend(env);
deps.addressedChain.count(addressedIn(env, members));
stampExchangeUsed(env, deps.addressedChain.taken());
return backendCaller.call(turn, abort.signal, (detail) => {
errorDetail = detail;
});
Expand Down Expand Up @@ -498,6 +499,7 @@ export function createDispatcher(deps: DispatcherDeps): Dispatcher {
list,
admissible: admission.admissible,
canAdmit: deps.addressedChain.canAdmit,
exchangeMax: deps.addressedChain.max,
groupsJoin: deps.isDndOn?.() !== true,
catchupEdge: catchupFree && !wasFree,
drain: () => deps.drainSignals?.() ?? [],
Expand Down
Loading
Loading