Skip to content

Commit 40502e3

Browse files
dfredriksenclaude
andcommitted
feat(session): native per-session goals with autonomous pursuit
Add a persisted, per-session "goal": a single objective with a status lifecycle (active / paused / completed), optional token budget, and running token/time usage. Closes anomalyco#27167. Closes anomalyco#29445. - Goal service + Drizzle schema + migration (core and opencode), exposed over the HTTP API as GET/POST/PATCH/DELETE /session/{sessionID}/goal and in the generated SDK as `client.session.goal.*`. - Inject the active goal as a <session-goal> block at the head of the system prompt every turn, and carry it into the compaction summary so it survives context overflow. No goal -> no block. - A model-callable `goal` tool (update / pause / resume / complete) lets the agent steer and terminate its own work; completing requires verification. - Setting or resuming a goal starts autonomous pursuit: SessionPrompt.pursue takes turns toward the goal and auto-continues after each natural stop until the model completes it, it is paused, the token budget is reached, or a hard step cap is hit. A default budget bounds runaway cost; pausing/completing cancels the in-flight turn so it stops promptly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 42f339c commit 40502e3

21 files changed

Lines changed: 2071 additions & 65 deletions

File tree

‎packages/core/src/database/migration.gen.ts‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { Effect } from "effect"
2+
import type { DatabaseMigration } from "../migration"
3+
4+
export default {
5+
id: "20260613180000_session_goals",
6+
up(tx) {
7+
return Effect.gen(function* () {
8+
// Create goal table for native per-session persisted goals (issue #27167).
9+
yield* tx.run(`
10+
CREATE TABLE \`goal\` (
11+
\`session_id\` text PRIMARY KEY,
12+
\`text\` text NOT NULL,
13+
\`status\` text NOT NULL,
14+
\`budget_tokens\` integer,
15+
\`tokens_used\` integer NOT NULL DEFAULT 0,
16+
\`time_ms\` integer NOT NULL DEFAULT 0,
17+
\`started_at\` integer NOT NULL,
18+
\`paused_at\` integer,
19+
\`completed_at\` integer,
20+
\`verification\` text,
21+
\`time_created\` integer NOT NULL,
22+
\`time_updated\` integer NOT NULL,
23+
CONSTRAINT \`fk_goal_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE
24+
);
25+
`)
26+
yield* tx.run(`CREATE INDEX \`goal_session_idx\` ON \`goal\` (\`session_id\`);`)
27+
})
28+
},
29+
} satisfies DatabaseMigration.Migration

‎packages/core/src/database/schema.gen.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,23 @@ export default {
239239
CONSTRAINT \`fk_session_share_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE
240240
);
241241
`)
242+
yield* tx.run(`
243+
CREATE TABLE \`goal\` (
244+
\`session_id\` text PRIMARY KEY,
245+
\`text\` text NOT NULL,
246+
\`status\` text NOT NULL,
247+
\`budget_tokens\` integer,
248+
\`tokens_used\` integer NOT NULL DEFAULT 0,
249+
\`time_ms\` integer NOT NULL DEFAULT 0,
250+
\`started_at\` integer NOT NULL,
251+
\`paused_at\` integer,
252+
\`completed_at\` integer,
253+
\`verification\` text,
254+
\`time_created\` integer NOT NULL,
255+
\`time_updated\` integer NOT NULL,
256+
CONSTRAINT \`fk_goal_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE
257+
);
258+
`)
242259
yield* tx.run(`CREATE UNIQUE INDEX \`event_aggregate_seq_idx\` ON \`event\` (\`aggregate_id\`,\`seq\`);`)
243260
yield* tx.run(`CREATE INDEX \`event_aggregate_type_seq_idx\` ON \`event\` (\`aggregate_id\`,\`type\`,\`seq\`);`)
244261
yield* tx.run(
@@ -272,6 +289,7 @@ export default {
272289
yield* tx.run(`CREATE INDEX \`session_workspace_idx\` ON \`session\` (\`workspace_id\`);`)
273290
yield* tx.run(`CREATE INDEX \`session_parent_idx\` ON \`session\` (\`parent_id\`);`)
274291
yield* tx.run(`CREATE INDEX \`todo_session_idx\` ON \`todo\` (\`session_id\`);`)
292+
yield* tx.run(`CREATE INDEX \`goal_session_idx\` ON \`goal\` (\`session_id\`);`)
275293
})
276294
},
277295
} satisfies Omit<DatabaseMigration.Migration, "id">

‎packages/core/src/location-layer.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import { ToolOutputStore } from "./tool-output-store"
4040
import { AppProcess } from "./process"
4141
import { SessionStore } from "./session/store"
4242
import { SessionTodo } from "./session/todo"
43+
import { SessionGoal } from "./session/goal"
4344
import { QuestionV2 } from "./question"
4445
import { LLMClient } from "@opencode-ai/llm"
4546
import { RequestExecutor } from "@opencode-ai/llm/route"
@@ -86,12 +87,14 @@ export class LocationServiceMap extends LayerMap.Service<LocationServiceMap>()("
8687
const skillGuidance = SkillGuidance.locationLayer.pipe(Layer.provide(services))
8788
const referenceGuidance = ReferenceGuidance.locationLayer.pipe(Layer.provide(services))
8889
const todos = SessionTodo.layer.pipe(Layer.provide(services))
90+
const goals = SessionGoal.layer.pipe(Layer.provide(services))
8991
const questions = QuestionV2.locationLayer.pipe(Layer.provide(services))
9092
const builtInTools = BuiltInTools.locationLayer.pipe(
9193
Layer.provide(services),
9294
Layer.provide(mutation),
9395
Layer.provide(resources),
9496
Layer.provide(todos),
97+
Layer.provide(goals),
9598
Layer.provide(questions),
9699
Layer.provide(image),
97100
)
@@ -114,6 +117,7 @@ export class LocationServiceMap extends LayerMap.Service<LocationServiceMap>()("
114117
mutation,
115118
resources,
116119
todos,
120+
goals,
117121
questions,
118122
model,
119123
runner,

‎packages/core/src/session/compaction.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
export * as SessionCompaction from "./compaction"
22

33
import { LLM, LLMError, LLMEvent, Message, type LLMRequest, type Model } from "@opencode-ai/llm"
4-
import { DateTime, Effect, Stream } from "effect"
4+
import { DateTime, Effect, Stream, Option } from "effect"
55
import type { Config } from "../config"
66
import type { EventV2 } from "../event"
77
import { SessionEvent } from "./event"
88
import { SessionMessage } from "./message"
99
import { SessionSchema } from "./schema"
1010
import { Token } from "../util/token"
11+
import { SessionGoal } from "./goal"
1112

1213
const DEFAULT_BUFFER = 20_000
1314
const DEFAULT_KEEP_TOKENS = 8_000
@@ -67,6 +68,9 @@ type Dependencies = {
6768
readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMError>
6869
}
6970
readonly config: readonly Config.Entry[]
71+
readonly goals?: {
72+
readonly get: (sessionID: SessionSchema.ID) => Effect.Effect<SessionGoal.Info | undefined>
73+
}
7074
}
7175

7276
type Input = {
@@ -181,10 +185,20 @@ export const make = (dependencies: Dependencies) => {
181185
const selected = select(input.entries, config.tokens)
182186
const previousSummary = input.entries.find((entry) => entry.message.type === "compaction")?.message
183187
if (!selected || (selected.head.length === 0 && previousSummary?.type !== "compaction")) return false
184-
const summaryPrompt = buildPrompt({
188+
const g = dependencies.goals
189+
? yield* dependencies.goals.get(input.sessionID).pipe(Effect.option)
190+
: Option.none()
191+
let summaryPrompt = buildPrompt({
185192
previousSummary: previousSummary?.type === "compaction" ? previousSummary.summary : undefined,
186193
context: [previousSummary?.type === "compaction" ? previousSummary.recent : "", selected.head].filter(Boolean),
187194
})
195+
if (Option.isSome(g) && g.value) {
196+
const goalLine = `- ${g.value.text} (status: ${g.value.status})`
197+
summaryPrompt = summaryPrompt.replace(
198+
"## Goal\n- [single-sentence task summary]",
199+
`## Goal\n${goalLine}`,
200+
)
201+
}
188202
const summaryOutput = Math.min(output || SUMMARY_OUTPUT_TOKENS, SUMMARY_OUTPUT_TOKENS)
189203
if (Token.estimate(summaryPrompt) > context - summaryOutput) return false
190204
const messageID = SessionMessage.ID.create()

‎packages/core/src/session/goal.ts‎

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
export * as SessionGoal from "./goal"
2+
3+
import { eq } from "drizzle-orm"
4+
import { Context, Effect, Layer, Schema } from "effect"
5+
import { Database } from "../database/database"
6+
import { EventV2 } from "../event"
7+
import { SessionSchema } from "./schema"
8+
import { GoalTable } from "./sql"
9+
10+
export const Status = Schema.Literals(["active", "paused", "completed"])
11+
export type Status = typeof Status.Type
12+
13+
export const Info = Schema.Struct({
14+
text: Schema.String.annotate({ description: "The active goal for this session" }),
15+
status: Status,
16+
budgetTokens: Schema.optional(Schema.Number).annotate({ description: "Optional token budget for the goal" }),
17+
tokensUsed: Schema.Number,
18+
timeMs: Schema.Number,
19+
startedAt: Schema.Number,
20+
pausedAt: Schema.optional(Schema.Number),
21+
completedAt: Schema.optional(Schema.Number),
22+
verification: Schema.optional(Schema.String),
23+
}).annotate({ identifier: "SessionGoal.Info" })
24+
export type Info = typeof Info.Type
25+
26+
export const Event = {
27+
Updated: EventV2.define({
28+
type: "goal.updated",
29+
schema: {
30+
sessionID: SessionSchema.ID,
31+
goal: Schema.NullOr(Info),
32+
},
33+
}),
34+
}
35+
36+
export interface Interface {
37+
readonly set: (input: {
38+
readonly sessionID: SessionSchema.ID
39+
readonly text: string
40+
readonly budgetTokens?: number
41+
}) => Effect.Effect<Info>
42+
readonly update: (input: {
43+
readonly sessionID: SessionSchema.ID
44+
readonly text?: string
45+
readonly status?: Status
46+
readonly budgetTokens?: number | null
47+
readonly verification?: string
48+
}) => Effect.Effect<Info | undefined>
49+
readonly pause: (sessionID: SessionSchema.ID) => Effect.Effect<Info | undefined>
50+
readonly resume: (sessionID: SessionSchema.ID) => Effect.Effect<Info | undefined>
51+
readonly clear: (sessionID: SessionSchema.ID) => Effect.Effect<void>
52+
readonly get: (sessionID: SessionSchema.ID) => Effect.Effect<Info | undefined>
53+
readonly recordUsage: (input: {
54+
readonly sessionID: SessionSchema.ID
55+
readonly tokens: number
56+
readonly durationMs: number
57+
}) => Effect.Effect<void>
58+
}
59+
60+
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/SessionGoal") {}
61+
62+
export const layer = Layer.effect(
63+
Service,
64+
Effect.gen(function* () {
65+
const { db } = yield* Database.Service
66+
const events = yield* EventV2.Service
67+
68+
const now = () => Date.now()
69+
70+
const read = (sessionID: SessionSchema.ID) =>
71+
db
72+
.select()
73+
.from(GoalTable)
74+
.where(eq(GoalTable.session_id, sessionID))
75+
.get()
76+
.pipe(Effect.orDie)
77+
78+
const publish = (sessionID: SessionSchema.ID, goal: Info | undefined) =>
79+
events.publish(Event.Updated, { sessionID, goal: goal ?? null })
80+
81+
const toInfo = (row: {
82+
text: string
83+
status: string
84+
budget_tokens: number | null
85+
tokens_used: number
86+
time_ms: number
87+
started_at: number
88+
paused_at: number | null
89+
completed_at: number | null
90+
verification: string | null
91+
}): Info => ({
92+
text: row.text,
93+
status: row.status as Status,
94+
budgetTokens: row.budget_tokens ?? undefined,
95+
tokensUsed: row.tokens_used,
96+
timeMs: row.time_ms,
97+
startedAt: row.started_at,
98+
pausedAt: row.paused_at ?? undefined,
99+
completedAt: row.completed_at ?? undefined,
100+
verification: row.verification ?? undefined,
101+
})
102+
103+
const set = Effect.fn("SessionGoal.set")(function* (input: {
104+
readonly sessionID: SessionSchema.ID
105+
readonly text: string
106+
readonly budgetTokens?: number
107+
}) {
108+
const ts = now()
109+
yield* db
110+
.insert(GoalTable)
111+
.values({
112+
session_id: input.sessionID,
113+
text: input.text,
114+
status: "active",
115+
budget_tokens: input.budgetTokens ?? null,
116+
tokens_used: 0,
117+
time_ms: 0,
118+
started_at: ts,
119+
paused_at: null,
120+
completed_at: null,
121+
verification: null,
122+
time_created: ts,
123+
time_updated: ts,
124+
})
125+
.onConflictDoUpdate({
126+
target: GoalTable.session_id,
127+
set: {
128+
text: input.text,
129+
status: "active",
130+
budget_tokens: input.budgetTokens ?? null,
131+
paused_at: null,
132+
completed_at: null,
133+
verification: null,
134+
time_updated: ts,
135+
},
136+
})
137+
.run()
138+
.pipe(Effect.orDie)
139+
const row = yield* read(input.sessionID)
140+
const info = row ? toInfo(row) : ({ text: input.text, status: "active", tokensUsed: 0, timeMs: 0, startedAt: ts } as Info)
141+
yield* publish(input.sessionID, info)
142+
return info
143+
})
144+
145+
const update = Effect.fn("SessionGoal.update")(function* (input: {
146+
readonly sessionID: SessionSchema.ID
147+
readonly text?: string
148+
readonly status?: Status
149+
readonly budgetTokens?: number | null
150+
readonly verification?: string
151+
}) {
152+
const current = yield* read(input.sessionID)
153+
if (!current) return undefined
154+
const ts = now()
155+
const status = input.status
156+
const next = {
157+
text: input.text ?? current.text,
158+
status: status ?? (current.status as Status),
159+
budget_tokens: input.budgetTokens === undefined ? current.budget_tokens : input.budgetTokens,
160+
tokens_used: current.tokens_used,
161+
time_ms: current.time_ms,
162+
started_at: current.started_at,
163+
paused_at: current.paused_at,
164+
completed_at: current.completed_at,
165+
verification: input.verification ?? current.verification,
166+
time_updated: ts,
167+
}
168+
if (status === "paused" && !next.paused_at) next.paused_at = ts
169+
if (status === "active" && next.paused_at) next.paused_at = null
170+
if (status === "completed" && !next.completed_at) next.completed_at = ts
171+
yield* db
172+
.update(GoalTable)
173+
.set(next)
174+
.where(eq(GoalTable.session_id, input.sessionID))
175+
.run()
176+
.pipe(Effect.orDie)
177+
const row = yield* read(input.sessionID)
178+
const info = row ? toInfo(row) : undefined
179+
yield* publish(input.sessionID, info)
180+
return info
181+
})
182+
183+
const pause = Effect.fn("SessionGoal.pause")(function* (sessionID: SessionSchema.ID) {
184+
return yield* update({ sessionID, status: "paused" })
185+
})
186+
187+
const resume = Effect.fn("SessionGoal.resume")(function* (sessionID: SessionSchema.ID) {
188+
return yield* update({ sessionID, status: "active" })
189+
})
190+
191+
const clear = Effect.fn("SessionGoal.clear")(function* (sessionID: SessionSchema.ID) {
192+
yield* db.delete(GoalTable).where(eq(GoalTable.session_id, sessionID)).run().pipe(Effect.orDie)
193+
yield* publish(sessionID, undefined)
194+
})
195+
196+
const get = Effect.fn("SessionGoal.get")(function* (sessionID: SessionSchema.ID) {
197+
const row = yield* read(sessionID)
198+
return row ? toInfo(row) : undefined
199+
})
200+
201+
const recordUsage = Effect.fn("SessionGoal.recordUsage")(function* (input: {
202+
readonly sessionID: SessionSchema.ID
203+
readonly tokens: number
204+
readonly durationMs: number
205+
}) {
206+
const current = yield* read(input.sessionID)
207+
if (!current || (current.status as Status) !== "active") return
208+
const ts = now()
209+
yield* db
210+
.update(GoalTable)
211+
.set({
212+
tokens_used: current.tokens_used + Math.max(0, Math.floor(input.tokens)),
213+
time_ms: current.time_ms + Math.max(0, Math.floor(input.durationMs)),
214+
time_updated: ts,
215+
})
216+
.where(eq(GoalTable.session_id, input.sessionID))
217+
.run()
218+
.pipe(Effect.orDie)
219+
const row = yield* read(input.sessionID)
220+
if (row) yield* publish(input.sessionID, toInfo(row))
221+
})
222+
223+
return Service.of({ set, update, pause, resume, clear, get, recordUsage })
224+
}),
225+
)
226+
227+
export const defaultLayer = layer.pipe(Layer.provide(EventV2.defaultLayer), Layer.provide(Database.defaultLayer))

0 commit comments

Comments
 (0)