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
1 change: 1 addition & 0 deletions bun.lock

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

4 changes: 2 additions & 2 deletions packages/app-plan/src/turns.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AppAside, AppOutput, AppSession, Effort, HandoffBlock } from '@sand/accounts/contract'
import type { AppAside, AppAsk, AppOutput, AppSession, Effort, HandoffBlock } from '@sand/accounts/contract'
import type { ModelContent, StopReason, ToolResultBlock } from '@sand/chats/contract'

interface Wire {
Expand All @@ -9,7 +9,7 @@ interface Wire {
stop(): void
close(): Promise<void>
inject?(handoff: HandoffBlock): Promise<boolean>
aside?(prompt: string, signal?: AbortSignal): Promise<AppAside>
aside?(ask: AppAsk, signal?: AbortSignal): Promise<AppAside>
}

class Turns {
Expand Down
5 changes: 3 additions & 2 deletions plugins/core/accounts/src/apps/bridge.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
type AppAsk,
type AppPlan,
type AppSession,
type AppSetup,
Expand Down Expand Up @@ -64,7 +65,7 @@ const noUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }

const keyOf = (caller: string, thread: ThreadRef) => `${caller}:${thread.id}:${thread.generation}`

const askedOf = (request: Request) => textOf(request.messages.at(-1)?.content ?? [])
const askOf = ({ messages }: Request): AppAsk => ({ question: textOf(messages.at(-1)?.content ?? []), messages: messages.slice(0, -1) })

const callsOf = (message: Message) => message.content.flatMap(block => (block.type === 'tool_call' ? [block.id] : []))

Expand Down Expand Up @@ -224,7 +225,7 @@ export const createBridge = (plan: AppPlan, home: string, track: Track) => {
const entry = live.get(keyOf(caller, thread))
if (!entry?.done || !entry.session.aside) throw new Error(`${plan.app} can't answer beside this thread now`)
yield { type: 'start', model: request.model }
const { text, usage } = await entry.session.aside(askedOf(request), signal)
const { text, usage } = await entry.session.aside(askOf(request), signal)
yield { type: 'done', message: { role: 'assistant', content: text ? [{ type: 'text', text }] : [] }, stopReason: 'end_turn', usage: { ...noUsage, ...usage } }
}

Expand Down
9 changes: 7 additions & 2 deletions plugins/core/accounts/src/contract/plans.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ModelContent, StopReason, ToolResultBlock } from '@sand/chats/contract'
import type { Message, ModelContent, StopReason, ToolResultBlock } from '@sand/chats/contract'
import type { HandoffBlock, ProviderCapabilities, ToolSpec } from './llm'
import type { Effort, LimitWindow, ModelPrice } from './models'
import type { ContextReport, Usage } from './usage'
Expand Down Expand Up @@ -100,6 +100,11 @@ export interface AppOutput {
exit(error: Error): void
}

export interface AppAsk {
question: string
messages: Message[]
}

export interface AppAside {
text: string
usage: Partial<Usage>
Expand All @@ -112,7 +117,7 @@ export interface AppSession {
steer?(content: ModelContent[]): void
answer(id: string, result: ToolResultBlock): void
inject?(handoff: HandoffBlock): Promise<boolean>
aside?(prompt: string, signal?: AbortSignal): Promise<AppAside>
aside?(ask: AppAsk, signal?: AbortSignal): Promise<AppAside>
interrupt(): Promise<void>
close(): Promise<void>
}
Expand Down
1 change: 1 addition & 0 deletions plugins/core/agy/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@sand/accounts": "workspace:*",
"@sand/app-plan": "workspace:*",
"@sand/chats": "workspace:*",
"@sand/config": "workspace:*",
"@sand/media": "workspace:*",
"@sand/util": "workspace:*",
"drydock": "github:vaakx-dev/drydock#v0.2.0-alpha.1"
Expand Down
5 changes: 3 additions & 2 deletions plugins/core/agy/src/acp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { acpArgs, agy } from './binary'

interface AcpOptions {
folder?: string
agent?: string
cwd?: string
onNotify?(method: string, params: Json): void
onRequest?(method: string, params: Json): Promise<unknown>
Expand All @@ -17,9 +18,9 @@ const refused = async (method: string) => {
throw new Error(`sand doesn't handle ${method}`)
}

async function startAcp({ folder, cwd, onNotify, onRequest, onExit }: AcpOptions) {
async function startAcp({ folder, agent, cwd, onNotify, onRequest, onExit }: AcpOptions) {
const client = startRpc({
command: [await agy.require(), ...acpArgs(folder)],
command: [await agy.require(), ...acpArgs({ folder, agent })],
app: agy.app,
cwd,
onNotify: onNotify ?? (() => {}),
Expand Down
40 changes: 40 additions & 0 deletions plugins/core/agy/src/aside.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { AppAsk, AppSetup } from '@sand/accounts/contract'
import { textOf, type Message } from '@sand/chats/contract'
import { join } from 'node:path'

const AGENT = 'sand-aside'

const AGENT_FILE = `---
name: ${AGENT}
description: Answers one question about the end of a chat in a single short reply
excludeDefaultComponents: true
tools: []
---
You see the end of a chat between a user and an AI assistant, then one question about it. Answer the question in one short reply, using only what the chat shows.
`

const EFFORT = 'low'

const RECENT_CHARS = 8_000

const SPEAKERS: Record<Message['role'], string> = { user: 'User', assistant: 'Assistant' }

function said(message: Message): string[] {
const text = textOf(message.content).trim()
return text ? [`${SPEAKERS[message.role]}: ${text}`] : []
}

function recentChat(messages: Message[]): string {
return messages.flatMap(said).join('\n\n').slice(-RECENT_CHARS)
}

function asidePrompt({ question, messages }: AppAsk): string {
return `<chat>\n${recentChat(messages)}\n</chat>\n\n${question}`
}

async function asideSetup({ model }: AppSetup, workspace: string): Promise<AppSetup> {
await Bun.write(join(workspace, '.agents', 'agents', `${AGENT}.md`), AGENT_FILE)
return { model, effort: EFFORT, system: '', tools: [], cwd: workspace, persist: false }
}

export { AGENT, asidePrompt, asideSetup }
4 changes: 3 additions & 1 deletion plugins/core/agy/src/binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ const folderArgs = (folder?: string) => (folder ? ['--gemini_dir', folder] : [])

const agy = appBinary({ command: 'agy', app: 'Antigravity', install: 'https://antigravity.google/docs/getting-started', installed: [installed()] })

const acpArgs = (folder?: string) => ['acp', '--disable-telemetry', '--include-default-customizations=false', ...folderArgs(folder)]
const agentArgs = (agent?: string) => (agent ? ['--agent', agent] : [])

const acpArgs = ({ folder, agent }: { folder?: string; agent?: string }) => ['acp', '--disable-telemetry', '--include-default-customizations=false', ...folderArgs(folder), ...agentArgs(agent)]

const loginArgs = (folder?: string) => ['acp', '--login', ...folderArgs(folder)]

Expand Down
11 changes: 7 additions & 4 deletions plugins/core/agy/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { llmPlans, type ProviderCapabilities } from '@sand/accounts/contract'
import { appPlan, type Provider } from '@sand/app-plan'
import { cli } from '@sand/config/contract'
import { media, type Media } from '@sand/media/contract'
import { definePlugin } from 'drydock'
import { join } from 'node:path'
import { listModels, readStatus, signIn, signOut } from './account'
import { agy } from './binary'
import { agyHistory } from './history'
Expand All @@ -18,7 +20,7 @@ const CAPS: ProviderCapabilities = {
cacheTtlMs: 60 * 60_000,
}

function antigravity(media: Media): Provider {
function antigravity(media: Media, asides: string): Provider {
return {
id: 'agy',
label: 'Antigravity',
Expand All @@ -35,7 +37,7 @@ function antigravity(media: Media): Provider {
models: () => listModels(folder),
usage: () => readLimits(folder),
history: agyHistory(folder),
open: (setup, output, resume) => openSession(setup, output, { media, folder, report }, resume),
open: (setup, output, resume) => openSession(setup, output, { media, folder, asides, report }, resume),
}
},
}
Expand All @@ -44,8 +46,9 @@ function antigravity(media: Media): Provider {
export default definePlugin({
name: 'agy',
description: 'Adds Antigravity (agy) to Settings → Accounts so sand can run Gemini models with sand’s own tools and prompt',
inject: { media },
inject: { cli, media },
apply(ctx) {
ctx.watch(llmPlans, plans => plans?.register(appPlan(antigravity(ctx.media), plans)))
const asides = join(ctx.cli.home, 'apps', 'agy')
ctx.watch(llmPlans, plans => plans?.register(appPlan(antigravity(ctx.media, asides), plans)))
},
})
14 changes: 12 additions & 2 deletions plugins/core/agy/src/session.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { type AppOutput, type AppSession, type AppSetup, type Effort, type PlanLimits, UsageLimited } from '@sand/accounts/contract'
import { fieldsOf, type Json, mcpBlock, mcpBridge, parts, resetOf, SERVER_NAME, Turns } from '@sand/app-plan'
import { type AppAsk, type AppOutput, type AppSession, type AppSetup, type Effort, type PlanLimits, UsageLimited } from '@sand/accounts/contract'
import { fieldsOf, forkedAside, type Json, mcpBlock, mcpBridge, parts, resetOf, SERVER_NAME, Turns } from '@sand/app-plan'
import type { ModelContent, StopReason } from '@sand/chats/contract'
import type { Media } from '@sand/media/contract'
import { errorMessage } from '@sand/util'
import { configOptions, effortOption, modelOption } from './account'
import { type AcpClient, startAcp } from './acp'
import { AGENT, asidePrompt, asideSetup } from './aside'
import { readLimits } from './limits'

interface SessionNeeds {
media: Media
folder?: string
asides: string
agent?: string
report(limits: PlanLimits): void
}

Expand Down Expand Up @@ -123,6 +126,7 @@ async function openSession(setup: AppSetup, output: AppOutput, needs: SessionNee

const client = await startAcp({
folder: needs.folder,
agent: needs.agent,
cwd: setup.cwd,
onNotify,
onRequest,
Expand Down Expand Up @@ -169,9 +173,15 @@ async function openSession(setup: AppSetup, output: AppOutput, needs: SessionNee
}
}

const aside = async (ask: AppAsk, signal?: AbortSignal) => {
const asking = await asideSetup(setup, needs.asides)
return forkedAside(output => openSession(asking, output, { ...needs, agent: AGENT }), asidePrompt(ask), signal)
}

return turns.session({
id: sessionId,
pid: client.pid,
aside,
prompt: (content, wanted) => void runTurn(content, wanted),
stop: () => client.notify('session/cancel', { sessionId }),
async close() {
Expand Down
49 changes: 49 additions & 0 deletions plugins/core/agy/test/aside.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { AppAsk } from '@sand/accounts/contract'
import { afterEach, beforeEach, expect, test } from 'bun:test'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { ASIDE_REPLY, type Call, fakeAgy } from './fake-agy'

let folder: string

beforeEach(async () => {
folder = await mkdtemp(join(tmpdir(), 'sand-agy-'))
})

afterEach(() => rm(folder, { recursive: true, force: true }))

const chatThenAside = async (said: string, ask: AppAsk) => {
const child = Bun.spawn([process.execPath, join(import.meta.dir, 'chat.ts'), folder, said, JSON.stringify(ask)], {
env: { ...process.env, PATH: `${folder}${delimiter}${process.env.PATH}` },
stderr: 'inherit',
})
const [printed, code] = await Promise.all([new Response(child.stdout).text(), child.exited])
expect(code).toBe(0)
return JSON.parse(printed)
}

const byProcess = (calls: Call[]) => [...Map.groupBy(calls, call => call.pid).values()]

test('an aside asks a separate tool-less agy agent about the recent chat and leaves the chat’s own session alone', async () => {
const agy = await fakeAgy(folder)
const reply = await chatThenAside('Fix the login bug', {
question: 'What will the user most likely say next?',
messages: [
{ role: 'user', content: [{ type: 'text', text: 'Fix the login bug' }] },
{ role: 'assistant', content: [{ type: 'text', text: 'Fixed it, and the auth tests pass.' }] },
],
})
expect(reply).toEqual({ text: ASIDE_REPLY, usage: { input: 600, output: 4, cacheRead: 0, cacheWrite: 0 } })

const [chat, aside] = byProcess(await agy.calls())
expect(chat!.filter(call => call.method === 'session/prompt')).toHaveLength(1)
expect(chat!.filter(call => call.method === 'session/new')).toHaveLength(1)

const prompt = JSON.stringify(aside!.find(call => call.method === 'session/prompt')!.params.prompt)
expect(prompt).toContain('Fixed it, and the auth tests pass.')
expect(prompt).toContain('What will the user most likely say next?')
expect(aside!.find(call => call.method === 'session/new')!.params.mcpServers).toEqual([])
expect(aside!.filter(call => call.method === 'session/set_config_option').map(call => call.params.value)).toEqual(['gemini-test', 'low'])
expect(aside!.at(-1)!.method).toBe('session/close')
})
38 changes: 38 additions & 0 deletions plugins/core/agy/test/chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { AppAsk, AppOutput } from '@sand/accounts/contract'
import type { Media } from '@sand/media/contract'
import { join } from 'node:path'
import { openSession } from '../src/session'

const media: Media = { put: () => ({ hash: '', size: 0, mediaType: '' }), path: () => '', data: () => undefined, exclude: () => {}, include: () => {}, inUse: () => () => {} }

const turnOutput = () => {
const finished = Promise.withResolvers<void>()
const output: AppOutput = {
text() {},
thinking() {},
call() {},
usage() {},
context() {},
pause() {},
finish: () => finished.resolve(),
fail: error => finished.reject(error),
exit() {},
}
return { output, finished: finished.promise }
}

const chatThenAside = async (folder: string, said: string, ask: AppAsk) => {
const { output, finished } = turnOutput()
const setup = { model: 'gemini-test', system: 'Be brief.', tools: [], cwd: folder, persist: true }
const session = await openSession(setup, output, { media, asides: join(folder, 'asides'), report() {} })
session.send([{ type: 'text', text: said }])
await finished
const reply = await session.aside!(ask)
await session.close()
return reply
}

if (import.meta.main) {
const [folder, said, ask] = process.argv.slice(2) as [string, string, string]
console.log(JSON.stringify(await chatThenAside(folder, said, JSON.parse(ask))))
}
Loading
Loading