Skip to content
Open
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 .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
registry=https://registry.npmjs.org/
1 change: 1 addition & 0 deletions packages/opencode/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
registry=https://registry.npmjs.org/
34 changes: 34 additions & 0 deletions packages/opencode/src/cli/cmd/tui/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { ToastProvider, useToast } from "./ui/toast"
import { ExitProvider, useExit } from "./context/exit"
import { Session as SessionApi } from "@/session"
import { TuiEvent } from "./event"
import { MessageID, PartID } from "@/session/schema"
import { KVProvider, useKV } from "./context/kv"
import { Provider } from "@/provider/provider"
import { ArgsProvider, useArgs, type Args } from "./context/args"
Expand Down Expand Up @@ -810,6 +811,39 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
})
})

event.on(TuiEvent.SessionNew.type, async (evt) => {
const model = local.model.current()
if (!model) return

// Abort the old session
await sdk.client.session.abort({ sessionID: evt.properties.sessionID }).catch(() => {})

// Create and navigate to the new session
const res = await sdk.client.session.create({})
if (res.error) return
const id = res.data.id

route.navigate({ type: "session", sessionID: id })

// Auto-send the initial message
sdk.client.session
.prompt({
sessionID: id,
...model,
messageID: MessageID.ascending(),
agent: local.agent.current().name,
model,
parts: [
{
id: PartID.ascending(),
type: "text" as const,
text: evt.properties.message,
},
],
})
.catch(() => {})
})

event.on("session.deleted", (evt) => {
if (route.data.type === "session" && route.data.sessionID === evt.properties.info.id) {
route.navigate({ type: "home" })
Expand Down
7 changes: 7 additions & 0 deletions packages/opencode/src/cli/cmd/tui/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,11 @@ export const TuiEvent = {
sessionID: SessionID.zod.describe("Session ID to navigate to"),
}),
),
SessionNew: BusEvent.define(
"tui.session.new",
z.object({
message: z.string().describe("Initial message to send in the new session"),
sessionID: SessionID.zod.describe("Session ID of the current session to abort"),
}),
),
}
40 changes: 40 additions & 0 deletions packages/opencode/src/tool/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import z from "zod"
import { Tool } from "./tool"
import type { Provider } from "../provider/provider"
import DESCRIPTION from "./context.txt"

export const ContextUsageTool = Tool.define("check_context_usage", {
description: DESCRIPTION,
parameters: z.object({}),
async execute(_params, ctx) {
const model = ctx.extra?.model as Provider.Model | undefined
const last = ctx.messages.filter((msg) => msg.info.role === "assistant" && msg.info.tokens.output > 0).at(-1)

if (!last || last.info.role !== "assistant") {
return {
title: "No usage data",
metadata: {},
output: "No context usage data available yet.",
}
}

const tokens = last.info.tokens
const total = tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write
const limit = model?.limit.context
const percentage = limit ? Math.round((total / limit) * 100) : null

return {
title: percentage !== null ? `${percentage}% used` : `${total.toLocaleString()} tokens`,
metadata: {
total,
limit,
percentage,
tokens,
},
output:
percentage !== null
? `Context usage: ${total.toLocaleString()} tokens (${percentage}% of ${limit?.toLocaleString()} context limit)`
: `Context usage: ${total.toLocaleString()} tokens (context limit unknown)`,
}
},
})
1 change: 1 addition & 0 deletions packages/opencode/src/tool/context.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Check your current context window usage. Returns the total token count, the percentage of the context window used, and the context limit. Use this to monitor how much of your context window remains before deciding whether to compact or adjust your approach.
24 changes: 24 additions & 0 deletions packages/opencode/src/tool/new-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import z from "zod"
import { Tool } from "./tool"
import { Bus } from "../bus"
import { TuiEvent } from "../cli/cmd/tui/event"
import DESCRIPTION from "./new-session.txt"

export const NewSessionTool = Tool.define("new_session", {
description: DESCRIPTION,
parameters: z.object({
initial_message: z.string().describe("The message to send as the first user message in the new session"),
}),
async execute(args, ctx) {
await Bus.publish(TuiEvent.SessionNew, {
message: args.initial_message,
sessionID: ctx.sessionID,
})

return {
title: "Starting new session",
metadata: {},
output: `New session requested with message: "${args.initial_message}". Current session will be terminated.`,
}
},
})
5 changes: 5 additions & 0 deletions packages/opencode/src/tool/new-session.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Stop the current session and start a new one with the given initial message. Use this when you need to start fresh in a new session, for example after completing a large task and the user wants to move on to something unrelated, or when context is getting too large and you want to continue work in a clean session.

The current session will be aborted immediately and a new session will be created with the initial_message sent as the first user message. The new session will begin processing automatically.

IMPORTANT: After calling this tool, do not call any other tools or generate further output - the current session is being terminated.
7 changes: 7 additions & 0 deletions packages/opencode/src/tool/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ import { AppFileSystem } from "../filesystem"
import { Agent } from "../agent/agent"
import { Skill } from "../skill"
import { Permission } from "@/permission"
import { ContextUsageTool } from "./context"
import { NewSessionTool } from "./new-session"

export namespace ToolRegistry {
const log = Log.create({ service: "tool.registry" })
Expand Down Expand Up @@ -172,6 +174,7 @@ export namespace ToolRegistry {
const cfg = yield* config.get()
const questionEnabled =
["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT) || Flag.OPENCODE_ENABLE_QUESTION_TOOL
const tui = ["app", "cli", "desktop"].includes(Flag.OPENCODE_CLIENT)

const tool = yield* Effect.all({
invalid: Tool.init(InvalidTool),
Expand All @@ -191,6 +194,8 @@ export namespace ToolRegistry {
question: Tool.init(question),
lsp: Tool.init(lsptool),
plan: Tool.init(plan),
context: Tool.init(ContextUsageTool),
session: Tool.init(NewSessionTool),
})

return {
Expand All @@ -207,6 +212,8 @@ export namespace ToolRegistry {
tool.task,
tool.fetch,
tool.todo,
tool.context,
...(tui ? [tool.session] : []),
tool.search,
tool.code,
tool.skill,
Expand Down
8 changes: 7 additions & 1 deletion packages/sdk/js/src/v2/gen/sdk.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type {
EventSubscribeResponses,
EventTuiCommandExecute,
EventTuiPromptAppend,
EventTuiSessionNew,
EventTuiSessionSelect,
EventTuiToastShow,
ExperimentalConsoleGetResponses,
Expand Down Expand Up @@ -3824,7 +3825,12 @@ export class Tui extends HeyApiClient {
parameters?: {
directory?: string
workspace?: string
body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventTuiSessionSelect
body?:
| EventTuiPromptAppend
| EventTuiCommandExecute
| EventTuiToastShow
| EventTuiSessionSelect
| EventTuiSessionNew
},
options?: Options<never, ThrowOnError>,
) {
Expand Down
17 changes: 16 additions & 1 deletion packages/sdk/js/src/v2/gen/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,20 @@ export type EventMessagePartRemoved = {
}
}

export type EventTuiSessionNew = {
type: "tui.session.new"
properties: {
/**
* Initial message to send in the new session
*/
message: string
/**
* Session ID of the current session to abort
*/
sessionID: string
}
}

export type PermissionAction = "allow" | "deny" | "ask"

export type PermissionRule = {
Expand Down Expand Up @@ -992,6 +1006,7 @@ export type Event =
| EventTuiCommandExecute
| EventTuiToastShow
| EventTuiSessionSelect
| EventTuiSessionNew
| EventMcpToolsChanged
| EventMcpBrowserOpenFailed
| EventCommandExecuted
Expand Down Expand Up @@ -4971,7 +4986,7 @@ export type TuiShowToastResponses = {
export type TuiShowToastResponse = TuiShowToastResponses[keyof TuiShowToastResponses]

export type TuiPublishData = {
body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventTuiSessionSelect
body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventTuiSessionSelect | EventTuiSessionNew
path?: never
query?: {
directory?: string
Expand Down
Loading