Fix session creation error handling and health endpoint status codes (#177) (#179)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-04-05 09:07:34 -04:00
1 parent 2f9c57a642
commit c32feae8ef
18 files changed
+257 -59

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.27",
"version": "0.0.28",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
+14
View File
@@ -100,6 +100,11 @@ KV entries are scoped to the current project and expire after 7 days. Use this f
Present plans with:
- **Objective**: What we're building and why
- **Phases**: Ordered implementation steps, each with specific files to create/modify, what changes to make, and acceptance criteria
- **Verification**: Concrete, runnable commands that prove the plan is complete. Every plan MUST include at least one verification step. Examples:
- Test commands: \`pnpm test\`, \`vitest run src/path/to/test.ts\`
- Type checking: \`pnpm tsc --noEmit\`, \`pnpm lint\`
- Runtime checks: curl commands, specific assertions about output
Plans without verification steps are incomplete. If no existing tests cover the changes, the plan MUST include a phase to write tests.
- **Decisions**: Architectural choices made during planning with rationale
- **Conventions**: Existing project conventions that must be followed
- **Key Context**: Relevant code patterns, file locations, integration points, and dependencies discovered during research
@@ -121,5 +126,14 @@ All execution modes require a **title** — a short descriptive label for the se
| Loop | memory-loop | false | Full self-contained plan |
"Full self-contained" means the plan must include every file path, implementation detail, code pattern, phase dependency, verification step, and gotcha. The receiving agent starts with zero context. Do NOT summarize, abbreviate, or include <promise> tags.
**IMPORTANT - Completion Signal:** When you have completed ALL phases of this plan successfully AND all verification steps pass, you MUST output the following tag exactly: <promise>DONE</promise>
Before outputting this tag, you MUST:
1. Run every verification command listed in the plan (tests, type checks, linting, build)
2. Confirm all verifications pass — if any fail, fix the issues first
3. Do NOT output the completion signal with known failing tests or type errors
The loop will continue until this signal is detected.
`,
}
+4
View File
@@ -57,6 +57,10 @@ Diffs alone are not enough. After getting the diff:
**Behavior Changes** — If a behavioral change is introduced, raise it (especially if possibly unintentional).
**Plan Compliance** — When reviewing loop iterations, check whether the implementation satisfies the plan's stated acceptance criteria and verification steps.
- If the task context includes verification commands (test, lint, type check), check whether they were run and passed
- If acceptance criteria from the plan are not met, report as a **warning** with the specific unmet criterion
## Before You Flag Something
Be certain. If you're going to call something a bug, you need to be confident it actually is one.
+9
View File
@@ -77,6 +77,15 @@ When you receive a message indicating that an architect agent has created a plan
You are the execution agent. Your job is to write code, not describe code.
**IMPORTANT - Completion Signal:** When you have completed ALL phases of this plan successfully AND all verification steps pass, you MUST output the following tag exactly: <promise>DONE</promise>
Before outputting this tag, you MUST:
1. Run every verification command listed in the plan (tests, type checks, linting, build)
2. Confirm all verifications pass — if any fail, fix the issues first
3. Do NOT output the completion signal with known failing tests or type errors
The loop will continue until this signal is detected.
## Project KV Store
You have access to a project-scoped key-value store with 7-day TTL for ephemeral state:
+34 -12
View File
@@ -29,26 +29,46 @@ export interface StatusArgs {
export async function run(argv: StatusArgs): Promise<void> {
const db = openDatabase(argv.dbPath)
function createStatusClient(serverUrl: string, directory: string) {
const url = new URL(serverUrl)
const password = url.password || process.env['OPENCODE_SERVER_PASSWORD']
const cleanUrl = new URL(url.toString())
cleanUrl.username = ''
cleanUrl.password = ''
const clientConfig: Parameters<typeof createOpencodeClient>[0] = { baseUrl: cleanUrl.toString(), directory }
if (password) {
clientConfig.headers = {
Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}`,
}
}
return createOpencodeClient(clientConfig)
}
async function tryFetchSessionOutput(serverUrl: string, sessionId: string, directory: string) {
try {
const url = new URL(serverUrl)
const password = url.password || process.env['OPENCODE_SERVER_PASSWORD']
const cleanUrl = new URL(url.toString())
cleanUrl.username = ''
cleanUrl.password = ''
const clientConfig: Parameters<typeof createOpencodeClient>[0] = { baseUrl: cleanUrl.toString(), directory }
if (password) {
clientConfig.headers = {
Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}`,
}
}
const client = createOpencodeClient(clientConfig)
const client = createStatusClient(serverUrl, directory)
return await fetchSessionOutput(client, sessionId, directory)
} catch {
return null
}
}
async function tryFetchSessionStatus(serverUrl: string, sessionId: string, directory: string): Promise<string> {
try {
const client = createStatusClient(serverUrl, directory)
const statusResult = await client.session.status({ directory })
const statuses = (statusResult.data ?? {}) as Record<string, { type: string; attempt?: number; message?: string; next?: number }>
const status = statuses[sessionId]
if (!status) return 'unknown'
if (status.type === 'retry') {
return `retry (attempt ${status.attempt}, next in ${Math.round(((status.next ?? 0) - Date.now()) / 1000)}s)`
}
return status.type
} catch {
return 'unavailable'
}
}
try {
if (argv.listWorktrees) {
const rows = db.prepare('SELECT key, data FROM project_kv WHERE key LIKE ? AND expires_at > ?').all('loop:%', Date.now()) as Array<{ key: string; data: string }>
@@ -201,6 +221,8 @@ export async function run(argv: StatusArgs): Promise<void> {
console.log(` Error Count: ${state.errorCount ?? 0}`)
console.log(` Audit Count: ${state.auditCount ?? 0}`)
console.log(` Started: ${new Date(startedAt).toISOString()}`)
const sessionStatus = await tryFetchSessionStatus(argv.server ?? 'http://localhost:5551', state.sessionId, state.worktreeDir!)
console.log(` Status: ${sessionStatus}`)
if (state.completionPromise) {
console.log(` Completion: ${state.completionPromise}`)
}
+1 -1
View File
@@ -115,7 +115,7 @@ export function createLoopEventHandler(
const sessionId = state.sessionId
try {
const statusResult = await v2Client.session.status()
const statusResult = await v2Client.session.status({ directory: state.worktreeDir })
const statuses = (statusResult.data ?? {}) as Record<string, { type: string }>
const status = statuses[sessionId]?.type
+31 -15
View File
@@ -1180,8 +1180,15 @@ Do NOT output text without also making this tool call.
let statuses: Record<string, { type: string; attempt?: number; message?: string; next?: number }> = {}
try {
const statusResult = await v2.session.status()
statuses = (statusResult.data ?? {}) as typeof statuses
const uniqueDirs = [...new Set(active.map((s) => s.worktreeDir).filter(Boolean))]
const results = await Promise.allSettled(
uniqueDirs.map((dir) => v2.session.status({ directory: dir })),
)
for (const result of results) {
if (result.status === 'fulfilled' && result.value.data) {
Object.assign(statuses, result.value.data)
}
}
} catch {
}
@@ -1192,7 +1199,7 @@ Do NOT output text without also making this tool call.
const seconds = elapsed % 60
const duration = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
const iterInfo = s.maxIterations && s.maxIterations > 0 ? `${s.iteration} / ${s.maxIterations}` : `${s.iteration} (unlimited)`
const sessionStatus = statuses[s.sessionId]?.type ?? 'unknown'
const sessionStatus = statuses[s.sessionId]?.type ?? 'unavailable'
const modeIndicator = !s.worktree ? ' (in-place)' : ''
const stallInfo = loopHandler.getStallInfo(s.worktreeName)
const stallCount = stallInfo?.consecutiveStalls ?? 0
@@ -1289,7 +1296,7 @@ Do NOT output text without also making this tool call.
let sessionStatus = 'unknown'
try {
const statusResult = await v2.session.status()
const statusResult = await v2.session.status({ directory: state.worktreeDir })
const statuses = statusResult.data as Record<string, { type: string; attempt?: number; message?: string; next?: number }> | undefined
const status = statuses?.[state.sessionId]
if (status) {
@@ -1334,7 +1341,27 @@ Do NOT output text without also making this tool call.
if (state.worktreeBranch) {
statusLines.push(`Branch: ${state.worktreeBranch}`)
}
let sessionOutput: LoopSessionOutput | null = null
if (state.worktreeDir) {
try {
sessionOutput = await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger)
} catch {
// Silently ignore fetch errors to avoid cluttering output
}
}
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
statusLines.push(...formatSessionOutput(sessionOutput))
}
if (state.lastAuditResult) {
statusLines.push(...formatAuditResult(state.lastAuditResult))
}
statusLines.push(
'',
`Completion promise: ${state.completionPromise ?? 'none'}`,
`Started: ${state.startedAt}`,
...(state.errorCount && state.errorCount > 0 ? [`Error count: ${state.errorCount} (retries before termination: ${MAX_RETRIES})`] : []),
@@ -1347,17 +1374,6 @@ Do NOT output text without also making this tool call.
`Prompt: ${promptPreview}`,
)
if (state.lastAuditResult) {
statusLines.push(...formatAuditResult(state.lastAuditResult))
}
const sessionOutput = state.worktreeDir ? await fetchSessionOutput(v2, state.sessionId, state.worktreeDir, logger) : null
if (sessionOutput) {
statusLines.push('')
statusLines.push('Session Output:')
statusLines.push(...formatSessionOutput(sessionOutput))
}
return statusLines.join('\n')
},
}),
+1 -1
View File
@@ -133,7 +133,7 @@ export function createLoopService(
let systemLine = `Loop iteration ${state.iteration ?? 0}`
if (state.completionPromise) {
systemLine += ` | To stop: output <promise>${state.completionPromise}</promise> (ONLY when all requirements are met)`
systemLine += ` | To stop: output <promise>${state.completionPromise}</promise> (ONLY after all verification steps pass)`
} else if ((state.maxIterations ?? 0) > 0) {
systemLine += ` / ${state.maxIterations}`
} else {
+10 -9
View File
@@ -7,6 +7,16 @@ export function formatTokens(n: number): string {
export function formatSessionOutput(sessionOutput: LoopSessionOutput): string[] {
const lines: string[] = []
if (sessionOutput.messages.length > 0) {
lines.push('Recent Activity:')
for (const msg of sessionOutput.messages) {
const preview = truncate(msg.text.replace(/\n/g, ' ').trim(), 1000)
lines.push(` [assistant] ${preview}`)
}
lines.push('')
}
const costStr = `$${sessionOutput.totalCost.toFixed(4)}`
const t = sessionOutput.totalTokens
const tokensStr = `${formatTokens(t.input)} in / ${formatTokens(t.output)} out / ${formatTokens(t.reasoning)} reasoning / ${formatTokens(t.cacheRead)} cache read / ${formatTokens(t.cacheWrite)} cache write`
@@ -17,15 +27,6 @@ export function formatSessionOutput(sessionOutput: LoopSessionOutput): string[]
lines.push(` Files changed: ${fc.files} (+${fc.additions}/-${fc.deletions} lines)`)
}
if (sessionOutput.messages.length > 0) {
lines.push('')
lines.push('Recent Activity:')
for (const msg of sessionOutput.messages) {
const preview = truncate(msg.text.replace(/\n/g, ' ').trim(), 200)
lines.push(` [assistant] ${preview}`)
}
}
return lines
}
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.27'
export const VERSION = '0.0.28'
+1 -1
View File
@@ -167,7 +167,7 @@ describe('formatSessionOutput', () => {
const lines = formatSessionOutput(sessionOutput)
const messageLine = lines.find((line) => line.includes('[assistant]'))
expect(messageLine).toBeDefined()
expect(messageLine!.length).toBeLessThanOrEqual(220)
expect(messageLine!.length).toBeLessThanOrEqual(1020)
})
test('handles multiline messages', () => {
+1 -1
View File
@@ -183,7 +183,7 @@ describe('LoopService', () => {
}
const prompt = loopService.buildContinuationPrompt(state)
expect(prompt).toContain('[Loop iteration 1 | To stop: output <promise>COMPLETE_TASK</promise> (ONLY when all requirements are met)]')
expect(prompt).toContain('[Loop iteration 1 | To stop: output <promise>COMPLETE_TASK</promise> (ONLY after all verification steps pass)]')
})
test('buildContinuationPrompt includes max iterations when no promise', () => {