Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
perf(antigravity): stop re-inlining the standing prompt and bound the reply tail
2BAB0f5b8ca07c76
diff --git a/server/src/__tests__/agents-computer-engine-antigravity.test.ts b/server/src/__tests__/agents-computer-engine-antigravity.test.tsindex 76d2b99..561cac5 100644--- a/server/src/__tests__/agents-computer-engine-antigravity.test.ts+++ b/server/src/__tests__/agents-computer-engine-antigravity.test.ts@@ -20,6 +20,7 @@ const tempDirs: string[] = []afterEach(async () => {delete process.env.CUMORA_TRIAGE_MODEL+ delete process.env.CUMORA_AGY_POST_REPLY_GRACE_MSprocess.env.PATH = ORIGINAL_PATHawait Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))})@@ -41,6 +42,17 @@ rl.on('line', (line) => {const content = event?.message?.content || ''if (log) fs.appendFileSync(log, JSON.stringify({ type: 'prompt', event }) + '\\n')turn += 1+ // The post-reply summary hop: agy keeps working after the tool result and+ // never emits a terminal result event here, which is exactly the window the+ // daemon bounds once the reply has landed.+ if (process.env.FAKE_AGY_SCENARIO === 'stall') {+ out({ event: 'step_update', step_update: {+ conversation_id: 'agy-conversation-1', step_index: turn, state: 'DONE', step_type: 'agent_response',+ text_delta: 'partial summary',+ usage: { input_tokens: 100, output_tokens: 10, thinking_tokens: 4, cache_read_tokens: 40, total_tokens: 110 },+ } })+ return+ }if (process.env.FAKE_AGY_SCENARIO === 'error') {out({ event: 'result', result: {conversation_id: 'agy-conversation-1', status: 'ERROR', response: '', error: 'quota exhausted',@@ -130,6 +142,16 @@ async function fakeLog(f: Fixture): Promise<Array<Record<string, unknown>>> {return (await readFile(f.log, 'utf8')).split('\n').filter(Boolean).map((line) => JSON.parse(line))}+/** Wait for a condition the fixture satisfies asynchronously (child boot, the+ * init event that carries the conversation id). */+async function waitFor(predicate: () => boolean, timeoutMs = 4_000): Promise<void> {+ const started = Date.now()+ while (!predicate()) {+ if (Date.now() - started > timeoutMs) throw new Error('waitFor timed out')+ await new Promise((resolve) => setTimeout(resolve, 10))+ }+}+test('antigravity persistent session uses auto stream-json without inner --sandbox and bills per-turn deltas', { skip: IS_WIN }, async () => {const f = await fixture()const hops: EngineHopReport[] = []@@ -254,10 +276,8 @@ test('antigravity keeps its usage baseline across a result that reports no usageassert.deepEqual(hops.map((hop) => hop.usage), [first.usage, third.usage])})-test('antigravity skips default cold local triage while explicit classify uses plan mode', { skip: IS_WIN }, async () => {+test('antigravity classify runs in plan mode with --sandbox and honors CUMORA_TRIAGE_MODEL', { skip: IS_WIN }, async () => {const f = await fixture()- assert.equal(getAdapter('antigravity').skipLocalTriage, true)- assert.equal(getAdapter('claude').skipLocalTriage, undefined)process.env.CUMORA_TRIAGE_MODEL = 'Gemini 3.5 Flash (Low)'const result = await getAdapter('antigravity').classify({cwd: f.home,@@ -269,7 +289,7 @@ test('antigravity skips default cold local triage while explicit classify uses passert.equal(result.text, 'echo:classify this')const records = await fakeLog(f)const start = records.find((record) => record.type === 'start') as { argv: string[] }- assert.ok(start.argv.includes('--sandbox'))+ assert.ok(start.argv.includes('--sandbox'), 'triage keeps the read-only plan sandbox')assert.equal(start.argv[start.argv.indexOf('--mode') + 1], 'plan')assert.equal(start.argv[start.argv.indexOf('--model') + 1], 'Gemini 3.5 Flash (Low)')})@@ -310,3 +330,109 @@ test('antigravity is detected through the agy binary on PATH', { skip: IS_WIN },process.env.PATH = old}})++test('antigravity inlines the standing prompt once, then only the delta rides each wake', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const session = getAdapter('antigravity').startSession?.({+ home: f.home,+ env: f.env,+ onLog: () => {},+ })+ assert.ok(session)++ // A fresh process has nothing in its transcript yet, so the daemon must inline+ // the standing prompt (the biggest single source of per-wake context growth).+ assert.equal(session.carriesStandingPrompt, false)+ await session.send('turn 1')+ assert.equal(session.carriesStandingPrompt, true, 'after the inline turn the daemon sends only the per-turn delta')+ await session.send('turn 2')+ assert.equal(session.carriesStandingPrompt, true)+ await session.stop()+})++test('antigravity resumed conversation already carries the standing prompt', { skip: IS_WIN }, async () => {+ const f = await fixture('resume-history')+ const session = getAdapter('antigravity').startSession?.({+ home: f.home,+ env: f.env,+ resumeSessionId: 'agy-conversation-resumed',+ onLog: () => {},+ })+ assert.ok(session)+ assert.equal(session.carriesStandingPrompt, true, 'a resumed transcript holds the standing prompt from the prior process')+ await session.stop()+})++test('antigravity ends the post-reply summary hop after the grace and still bills the partial hop', { skip: IS_WIN }, async () => {+ const f = await fixture('stall')+ process.env.CUMORA_AGY_POST_REPLY_GRACE_MS = '20'+ const logs: string[] = []+ const session = getAdapter('antigravity').startSession?.({+ home: f.home,+ env: f.env,+ onLog: (line) => logs.push(line),+ })+ assert.ok(session)++ // The fake never emits `result` — agy is still in its summary hop. Once the+ // reply landed, that hop is pure dead time and must not hold the session.+ const turn = session.send('reply then stall')+ // A real reply lands long after agy's init event; wait for the conversation id+ // the session persists so the early end can hand it to the next wake.+ await waitFor(() => session.sessionId !== null)+ session.noteReplyDelivered?.()+ const result = await turn++ assert.equal(result.exitCode, 0, 'an early end is a completed turn, not a failure')+ assert.equal(result.error, undefined)+ assert.equal(result.sessionId, 'agy-conversation-1', 'the conversation id must survive so the next wake resumes it')+ assert.deepEqual(result.usage, { input_tokens: 60, output_tokens: 10, cache_read_input_tokens: 40 })+ assert.equal(session.alive, false, 'the stalled process is reaped instead of lingering')+ assert.ok(logs.some((line) => line.includes('reply already delivered')))+ await session.stop({ force: true })+})++test('antigravity answers a ping that lands after the reply by ending the tail immediately', { skip: IS_WIN }, async () => {+ const f = await fixture('stall')+ // Grace 0 disables the timer: only the steer path can finish this turn, which+ // is exactly the behaviour under test.+ process.env.CUMORA_AGY_POST_REPLY_GRACE_MS = '0'+ const session = getAdapter('antigravity').startSession?.({+ home: f.home,+ env: f.env,+ onLog: () => {},+ })+ assert.ok(session)++ const turn = session.send('reply then a teammate pings')+ await waitFor(() => session.sessionId !== null)+ session.noteReplyDelivered?.()+ session.steer('a teammate pinged you')+ const result = await turn++ assert.equal(result.exitCode, 0)+ assert.equal(result.sessionId, 'agy-conversation-1')+ assert.equal(session.alive, false, 'the rerun picks the ping up on a resumed conversation')+ await session.stop({ force: true })+})++test('antigravity keeps its tail when no reply landed (steer stays a logged no-op)', { skip: IS_WIN }, async () => {+ const f = await fixture()+ process.env.CUMORA_AGY_POST_REPLY_GRACE_MS = '20'+ const logs: string[] = []+ const session = getAdapter('antigravity').startSession?.({+ home: f.home,+ env: f.env,+ onLog: (line) => logs.push(line),+ })+ assert.ok(session)++ const turn = session.send('a turn with no reply tool call')+ session.steer('group noise')+ const result = await turn++ assert.equal(result.exitCode, 0)+ assert.equal(session.alive, true, 'nothing was delivered, so the running turn is left alone')+ assert.ok(logs.some((line) => line.includes('same-turn steer is not supported')))+ await session.stop()+})diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 44cd536..e63a8a4 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -140,9 +140,13 @@ const AVAIL_REASSERT_MS = 10 * 60_000// Pre-turn wake debounce. The FIRST wake from// an idle state arms this timer; wakes arriving within the window FOLD INTO it —// the turn snapshots ALL unread, so a burst of group messages becomes ONE big--// engine turn instead of N. Content-blind, no classification. Trades a small reply-// latency (a beat before the agent starts) for far fewer spawns in a busy room.-const WAKE_DEBOUNCE_MS = 2_500+// engine turn instead of N. Content-blind, no classification.+//+// 500ms, not 2.5s: this delay sits on the critical path of EVERY reply, and a live+// chat measurement showed the two waits (2.53s each) costing more perceived+// latency than the coalescing saved — a room's burst still folds in at 500ms+// because the timer only starts once the first wake lands.+const WAKE_DEBOUNCE_MS = 500// Same-turn group notice (default ON — set CUMORA_BYOA_STEER_GROUP=0// to disable). A DIRECT ping (DM / @me / human) is ALWAYS steered into the live// turn (see maybeSteer). With this on, plain GROUP activity arriving while busy@@ -2221,10 +2225,10 @@ export class AgentRunner {return { exitCode: 70, error: `HTTP ${res.status} ${body.slice(0, 200)}`.trim() }}const data = await res.json() as { text?: unknown; exitCode?: unknown }- return {- text: typeof data.text === 'string' ? data.text : '',- exitCode: typeof data.exitCode === 'number' ? data.exitCode : 0,- }+ const text = typeof data.text === 'string' ? data.text : ''+ const exitCode = typeof data.exitCode === 'number' ? data.exitCode : 0+ if (exitCode === 0) this.noteEngineReplyDelivered(argv, text)+ return { text, exitCode }} catch (err) {return { exitCode: 70, error: err instanceof Error ? err.message : String(err) }} finally {@@ -2233,6 +2237,18 @@ export class AgentRunner {}}+ /** Forward a LANDED reply to the live engine session. This is the turn's+ * user-visible effect: an engine with a post-tool summary hop (agy) can bound+ * how long it keeps the session locked after the message is already out.+ * A HELD response is NOT a delivery — the reply was withheld and the turn+ * still has real work (re-compose), so it must keep its normal tail. */+ private noteEngineReplyDelivered(argv: string[], text: string): void {+ const command = argv[0]+ if (command !== 'reply' && command !== 'send') return+ if (/NOT sent/i.test(text)) return+ try { this.engineSession?.noteReplyDelivered?.() } catch { /* observability only */ }+ }+/** Env handed to the engine subprocess. Secure mode preserves the operator's* original PATH so model-writable <home>/bin cannot shadow the engine binary;* compatibility mode alone exposes its legacy CLI shim there. No server URL@@ -2385,17 +2401,11 @@ export class AgentRunner {if (!payload) return nullif (payload.verdict) return payload.verdict // hard rule / empty inbox — no model neededif (!payload.instructions || !payload.input) return null- if (this.adapter.skipLocalTriage && !this.triageModelPin()) {- return {- actionable: true,- reason: `${this.adapter.id} skips cold local triage spawn; persistent main brain judges in-turn`,- promptNote:- 'No separate small-brain triage ran for this wake. Read the unread messages and recent context yourself: ' +- 'respond or act only if a human is involved/waiting, a teammate needs your specific answer or action, or your reply advances active claimed work; ' +- 'otherwise stay silent and do not post.',- source: 'support-model-local',- }- }+ // No per-engine "skip triage" escape hatch. It looked like a win (dodge one+ // cold CLI spawn per wake) but triage is NOT on the reply critical path:+ // triage-core answers human DMs/groups deterministically without a model,+ // and the small brain runs on the local cheap model. The escape hatch only+ // made one engine judge its own inbox instead of using the shared gate.// Triage concurrency gate + deterministic spawn pacer. Pacer is shared// with the big-brain path (same Anthropic/OpenAI account quota, same@@ -2687,6 +2697,16 @@ export class AgentRunner {// coordinates identically to the cloud pod-agent.GLANCE_YIELD_RULES + `\n\n` +postingMechanicsText(this.promptSurface()) ++ // Two cost rules discovered on live `agy` runs:+ // 1. The reply tool IS the deliverable. Anything the model writes after it+ // returns is a summary nobody reads, but the engine still spends a full+ // model hop on it while the session stays locked.+ // 2. agy's command-safety monitor flags shell-operator-shaped commands+ // (`unquoted_shell_operators`) and re-reviews every one of them with a+ // small model — ~1.5s per `cumora` call, on the critical path of a reply.+ `Once a \`cumora reply\` / \`send\` returns success the message is already delivered — ` ++ `end the turn there. Do NOT restate it, summarise it, or narrate what you just did. ` ++ `Keep each \`cumora\` call a SINGLE fully quoted command with no pipes, \`&&\`, or redirection. ` +`When you're answering a ` +`SPECIFIC message, add \`--quote <message_id>\` so your reply threads to its context. ` +`To address a teammate, @<their-id> (the short id in \`cumora messages\` / \`cumora participants\`), ` +diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 01e3cd8..f803e44 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -815,6 +815,13 @@ export interface EngineSession {* stream-json boundary so the agent answers a direct ping mid-task, then* continues. No-op if no turn is in flight. */steer(text: string): void+ /** The daemon just observed that this turn's user-visible reply actually+ * landed (a `cumora reply` / `send` returned success). Engines whose turn+ * keeps working after the tool result — agy spends one more model hop on a+ * summary the user never reads — use this to bound how long the session+ * stays locked after the message is already out. Optional: engines whose+ * turn ends with the reply simply ignore it. */+ noteReplyDelivered?(): void/** Process is up and stdin is writable. */readonly alive: boolean/** The latest session id seen (to `--resume` if the process must be respawned). */@@ -846,10 +853,6 @@ export interface EngineAdapter {startSession?(args: EngineSessionArgs): EngineSession | null/** Run a LOCAL small-brain triage completion, returning raw text. */classify(args: EngineClassifyArgs): Promise<EngineClassifyResult>- /** True when the engine has no lightweight small-brain alias and cold-spawning- * a separate triage CLI process per wake is slower and more expensive than- * waking the warm persistent session directly (unless a triage model is pinned). */- readonly skipLocalTriage?: boolean/** `doctor` liveness probe for one brain tier (big/small). Same one-shot spawn* as classify, with a trivial prompt — used to diagnose whether each brain is* reachable + authed on this machine. */@@ -5562,6 +5565,13 @@ class AntigravityTurnTracker {this.seenResponseSteps.clear()}+ /** Usage accrued so far this turn (the per-step `agent_response` sum). Needed+ * when a turn is completed early — BEFORE agy emits its terminal `result` —+ * so the ledger still bills the work that actually ran. */+ partialUsage(): EngineUsage | undefined {+ return antigravityUsage(this.turnStepUsage)+ }+/** Feed one event. True means the current turn reached its terminal result. */observe(event: AntigravityEvent): boolean {const id = event.conversation_id ?? event.init?.conversation_id ?? event.result?.conversation_id@@ -5621,6 +5631,33 @@ class AntigravityTurnTracker {}}+/** How long the session may stay locked in agy's post-tool summary hop AFTER the+ * reply already landed. That hop is invisible to the user (they already have+ * the message), yet it holds `pending`, so any ping arriving meanwhile waits.+ *+ * 60s, and that number is deliberate: ending a turn early is only possible by+ * reaping the process (agy has no cancel-turn), which costs a 2.4–4.8s cold+ * spawn on the NEXT wake and throws away the warm session this adapter exists+ * to keep. So this must sit far ABOVE any healthy hop2 — a live account+ * measured 8–15s on a thinking-tier model — and only catch runaway tails.+ * Using it as a normal-turn optimisation is a trap: at 8s every turn tripped it+ * and the warm session was never reused.+ *+ * 0 disables the early end entirely (pure protocol behaviour). */+function antigravityPostReplyGraceMs(): number {+ const raw = process.env.CUMORA_AGY_POST_REPLY_GRACE_MS+ if (raw == null || raw.trim() === '') return 60_000+ const n = Number(raw)+ return Number.isFinite(n) && n >= 0 ? n : 60_000+}++/** Re-inline the full standing prompt every N turns. `agy` exposes no+ * system-prompt file, so turn 1 carries it inline; keeping it out of turns+ * 2..N is what stops a persistent transcript from growing by a whole standing+ * prompt (~5k tokens) on every wake. The periodic refresh covers the engine's+ * native compaction dropping old turns. */+const ANTIGRAVITY_STANDING_REFRESH_TURNS = 8+class AntigravitySession implements EngineSession {private readonly child: ChildProcessprivate readonly tracker: AntigravityTurnTracker@@ -5632,7 +5669,13 @@ class AntigravitySession implements EngineSession {private stdoutTail: string[] = []private pending: { resolve: (result: EngineRunResult) => void } | null = nullprivate stopPromise: Promise<void> | null = null- readonly carriesStandingPrompt = false+ /** Whether this process's transcript already contains the standing prompt. */+ private standingDelivered: boolean+ /** Turns completed since the standing prompt was last inlined. */+ private standingTurns = 0+ /** A `cumora reply`/`send` this turn actually landed. */+ private replySent = false+ private replyGrace: NodeJS.Timeout | null = nullconstructor(command: string,@@ -5642,6 +5685,9 @@ class AntigravitySession implements EngineSession {pin: string | null,) {this.tracker = new AntigravityTurnTracker(pin, opts.onHopUsage, Boolean(opts.resumeSessionId))+ // A resumed conversation already carries the standing prompt from the prior+ // process; a fresh one gets it inline on its first turn.+ this.standingDelivered = Boolean(opts.resumeSessionId)this.child = spawnEngineChild(command, argv, {cwd: opts.home,env: opts.env,@@ -5660,6 +5706,10 @@ class AntigravitySession implements EngineSession {get alive(): boolean { return !this.exited && this.child.stdin?.writable === true }get sessionId(): string | null { return this.tracker.sessionId }get text(): string { return this.tracker.text }+ /** True once the transcript holds the standing prompt, so the daemon sends+ * only the per-turn delta. This is the whole reason a long-lived `agy`+ * session does not grow by a full standing prompt on every wake. */+ get carriesStandingPrompt(): boolean { return this.standingDelivered }send(prompt: string): Promise<EngineRunResult> {if (this.pending) return Promise.resolve({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.sessionId })@@ -5670,24 +5720,60 @@ class AntigravitySession implements EngineSession {sessionId: this.sessionId,})}+ // The prompt was assembled from carriesStandingPrompt a moment ago (see+ // daemon.turnPrompt), so an inlined standing prompt is about to enter the+ // transcript. Remember it on a SUCCESSFUL write only.+ const inlinedStanding = !this.standingDelivered+ this.replySent = false+ this.clearReplyGrace()this.tracker.beginTurn()return new Promise((resolve) => {this.pending = { resolve }const message = JSON.stringify({ event: 'user', message: { content: stripLoneSurrogates(prompt) } })if (!writeStdin(this.child, `${message}\n`)) {this.settle({ exitCode: 1, error: 'failed to write turn to antigravity', sessionId: this.sessionId })+ return+ }+ if (inlinedStanding) {+ this.standingDelivered = true+ this.standingTurns = 0}})}+ /** The daemon saw a `cumora reply`/`send` succeed this turn: the message is+ * out, so only agy's summary hop remains. Bound it instead of letting it hold+ * the session (and every queued ping) hostage. */+ noteReplyDelivered(): void {+ if (!this.pending || this.replySent) return+ this.replySent = true+ const grace = antigravityPostReplyGraceMs()+ if (grace <= 0) return+ this.replyGrace = setTimeout(() => {+ this.replyGrace = null+ if (!this.pending) return+ this.finishTurnEarly(`reply already delivered — ending agy's post-tool summary hop after ${grace}ms`)+ }, grace)+ this.replyGrace.unref?.()+ }+steer(_text: string): void {+ if (!this.pending) return+ // Once the reply is out there is nothing left to steer into: the only work+ // remaining is a summary hop the user never reads. End it now so the daemon's+ // coalesced rerun answers the ping immediately instead of waiting the tail out.+ if (this.replySent) {+ this.finishTurnEarly('a ping arrived after the reply landed — ending the tail so the rerun answers it now')+ return+ }// The documented protocol requires waiting for a result before the next// user event. Queueing mid-turn would be an undocumented race; the daemon's// normal coalesced wake delivers the ping after this turn instead.- if (this.pending) this.opts.onLog('[antigravity] same-turn steer is not supported; the ping rides the next wake')+ this.opts.onLog('[antigravity] same-turn steer is not supported; the ping rides the next wake')}stop(options: { force?: boolean } = {}): Promise<void> {+ this.clearReplyGrace()this.exited = truetry { this.child.stdin?.end() } catch { /* ignore */ }if (options.force) return terminateEngineTree(this.child, true)@@ -5700,6 +5786,33 @@ class AntigravitySession implements EngineSession {return this.stopPromise}+ /** Complete the turn WITHOUT agy's terminal `result`, then reap the process.+ * Only safe once the turn's user-visible effect already happened (the reply+ * landed), so the missing summary cannot lose work. The conversation id is+ * persisted by the daemon and the next wake resumes it via `--conversation`. */+ private finishTurnEarly(detail: string): void {+ if (!this.pending) return+ this.opts.onLog(`[antigravity] ${detail}`)+ const result: EngineRunResult = {+ exitCode: 0,+ sessionId: this.tracker.sessionId,+ usage: this.tracker.partialUsage(),+ model: this.tracker.model,+ }+ this.clearReplyGrace()+ // Flip `exited` BEFORE settling so the close handler's die() finds no pending+ // turn and stays silent — no spurious failure, no retry of a delivered reply.+ this.exited = true+ this.settle(result)+ void terminateEngineTree(this.child, true)+ }++ private clearReplyGrace(): void {+ if (!this.replyGrace) return+ clearTimeout(this.replyGrace)+ this.replyGrace = null+ }+private onStdout(buf: Buffer): void {this.outBuf += this.decoder.write(buf)let newline: number@@ -5759,6 +5872,16 @@ class AntigravitySession implements EngineSession {const pending = this.pendingif (!pending) returnthis.pending = null+ this.clearReplyGrace()+ if (this.standingDelivered) {+ this.standingTurns += 1+ if (this.standingTurns >= ANTIGRAVITY_STANDING_REFRESH_TURNS) {+ // Native compaction can drop old turns; re-inline soon so the mechanics+ // never silently disappear from a long-lived transcript.+ this.standingDelivered = false+ this.standingTurns = 0+ }+ }pending.resolve(result)}@@ -5781,7 +5904,6 @@ class AntigravitySession implements EngineSession {class AntigravityAdapter implements EngineAdapter {readonly id = 'antigravity' as constreadonly bin = 'agy'- readonly skipLocalTriage = trueprivate sessionArgs(args: EngineSessionArgs, mode: 'auto' | 'plan'): string[] {const model = args.model ? ['--model', args.model] : []