Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Stop retrying restricted providers for companion memory (#625)

Deedee2f27085e4
diff --git a/cli/scripts/memory-native-opencode-inference-probe.mjs b/cli/scripts/memory-native-opencode-inference-probe.mjs
index d1f440645..8edb2b28a 100644
--- a/cli/scripts/memory-native-opencode-inference-probe.mjs
+++ b/cli/scripts/memory-native-opencode-inference-probe.mjs
@@ -22,6 +22,12 @@ const server = createServer(async (request, response) => {
tools: (body.tools ?? []).map(tool => tool.function?.name ?? tool.name ?? tool.type),
selectedCredential: request.headers.authorization === 'Bearer synthetic-memory-account',
})
+ if (current.mode === 'provider_restricted') {
+ response.writeHead(403, { 'content-type': 'application/json' }).end(JSON.stringify({ type: 'error', error: {
+ type: 'FreeTierError', message: "Error from provider (Console): OpenCode's free tier can only be used from within OpenCode",
+ } }))
+ return
+ }
const forced = current.mode !== 'text' && current.requests.length === 1
const tool = { index: 0, id: 'call_fixture', type: 'function', function: { name: current.mode,
arguments: JSON.stringify(current.mode === 'bash'
@@ -61,7 +67,7 @@ try {
models: { 'memory-model': { name: 'Memory fixture', limit: { context: 128_000, output: 4096 } } },
},
}
- for (const mode of ['text', 'bash', 'question']) {
+ for (const mode of ['text', 'bash', 'question', 'provider_restricted']) {
current = { mode, requests: [], snapshotReads: 0 }
runs.push(current)
try {
@@ -84,11 +90,14 @@ try {
if (mode === 'text') {
assert.deepEqual(current.result, { text: '{"proposals":[]}' })
assert.equal(current.snapshotReads, 3)
+ } else if (mode === 'provider_restricted') {
+ assert.equal(current.error, 'inference_provider_restricted')
+ assert.equal(current.requests.length, 1, 'The non-retryable refusal must not be retried by native OpenCode')
} else assert.equal(current.error, 'inference_tool_or_error')
}
console.log(JSON.stringify({ at: new Date().toISOString(), capability, runs,
limitations: ['Synthetic localhost responses; no personal conversations or real model inference.',
- 'Native transport only. Host account/config observation and companion wiring remain unimplemented.',
+ 'Native transport only. This probe does not exercise production account/config observation or companion wiring.',
'No claim about extraction quality, OAuth, automatic compaction or task benefit.'],
}, null, 2))
} finally {
diff --git a/cli/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.json b/cli/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.json
new file mode 100644
index 000000000..e942a7999
--- /dev/null
+++ b/cli/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.json
@@ -0,0 +1,12 @@
+{
+ "type": "error",
+ "error": {
+ "name": "APIError",
+ "data": {
+ "message": "Error from provider (Console): OpenCode's free tier can only be used from within OpenCode",
+ "statusCode": 403,
+ "isRetryable": false,
+ "responseBody": "{\"type\":\"error\",\"error\":{\"type\":\"FreeTierError\",\"message\":\"Error from provider (Console): OpenCode's free tier can only be used from within OpenCode\"}}"
+ }
+ }
+}
diff --git a/cli/src/memory/companion.spec.ts b/cli/src/memory/companion.spec.ts
index 0b3bde065..ec1bff0aa 100644
--- a/cli/src/memory/companion.spec.ts
+++ b/cli/src/memory/companion.spec.ts
@@ -1,5 +1,13 @@
import { expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { companionMemoryInference } from './companion.js'
+import { CompanionIntelligence, type CompanionRuntime } from '../pair/intelligence.js'
+import { CodingMemoryStore } from './store.js'
+import { MemoryLearner } from './learner.js'
+import { QUEUE_OPERATIONS, type MemoryPort, type Operation, type Arguments, type Result } from './operations.js'
+import { MemoryError } from './types.js'
it('waits for a certified selected Codex runtime and preserves foreground priority', async () => {
const intelligence = { extractionStatus: async () => ({ state: 'ready' as const, agentId: 'companion', engine: 'codex', contextKey: 'selected' }),
@@ -45,3 +53,53 @@ it('checks OpenCode native compatibility without probing a different engine', as
expect(await inference.target()).toEqual({ state: 'ready', key: 'native-binding', foregroundBusy: false })
expect(codex).not.toHaveBeenCalled(); expect(claude).not.toHaveBeenCalled()
})
+
+it('preserves queued evidence and stops calls and native probes after a refusal, then resumes on a new connection', async () => {
+ const directory = mkdtempSync(join(tmpdir(), 'memory-refusal-'))
+ let now = 10_000
+ const opened = CodingMemoryStore.open({ directory: join(directory, 'store'), profileId: 'owner', now: () => now })
+ if (!opened.ok) throw new Error(opened.reason)
+ const store = opened.store
+ try {
+ store.registerProject('project')
+ store.setControls({ learn: true, recall: true })
+ store.learning.capture({ streamId: 'stream', engine: 'codex', sessionId: 'coding-session', projectId: 'project',
+ episodeId: 'episode', from: null, to: '1', boundary: 'complete', events: [{
+ id: 'source', profileId: 'owner', projectId: 'project', engine: 'codex', sessionId: 'coding-session',
+ nativeEventId: 'source', role: 'user', eligibility: 'coding', observedAt: now, rootIds: ['source'],
+ text: 'Use SQLite for the synthetic offline project.',
+ }] })
+ const memory: MemoryPort = { async request<K extends Operation>(operation: K, args: Arguments<K>): Promise<Result<K>> {
+ const owner = (QUEUE_OPERATIONS as readonly string[]).includes(operation) ? store.learning : store
+ return (owner as unknown as Record<string, (...args: unknown[]) => unknown>)[operation].apply(owner, args) as Result<K>
+ } }
+ let runtime: CompanionRuntime = { agentId: 'companion', sessionId: 'companion-session', engine: 'opencode',
+ stopped: false, nativeProcessKey: 'process-a', accountKey: 'synthetic-owner', profile: null }
+ const run = vi.fn(async () => ({ text: '{"proposals":[]}' }))
+ run.mockRejectedValueOnce(new MemoryError('inference_provider_restricted'))
+ const intelligence = new CompanionIntelligence({ enabled: () => true, current: () => runtime,
+ directory: join(directory, 'work'), stateFile: join(directory, 'model.json'), runOpenCode: run,
+ openCodeSnapshot: () => ({ model: 'selected/model', auth: { type: 'api', key: 'synthetic-account' },
+ provider: { npm: '@ai-sdk/openai-compatible', models: { model: {} } } }),
+ })
+ const capability = vi.fn(async () => ({ supported: true, version: '1.18.34' }))
+ const inference = companionMemoryInference(intelligence, () => false, vi.fn(), vi.fn(), capability)
+ const learner = new MemoryLearner(memory, inference)
+ const refused = { state: 'waiting_for_model', reason: 'inference_provider_restricted' }
+ expect(await learner.tick()).toEqual(refused)
+ expect(capability).toHaveBeenCalledOnce()
+ for (const elapsed of [0, 60_001, 3_600_001]) {
+ now += elapsed
+ expect(await learner.tick()).toEqual(refused)
+ expect(run).toHaveBeenCalledOnce()
+ expect(capability).toHaveBeenCalledOnce()
+ expect(store.learning.status().jobs).toEqual({ waiting_for_model: 1 })
+ expect(store.source('source', { profileId: 'owner', projectIds: ['project'], includeProfile: false })?.text)
+ .toBe('Use SQLite for the synthetic offline project.')
+ }
+ runtime = { ...runtime, nativeProcessKey: 'process-b' }
+ expect(await learner.tick()).toEqual({ state: 'no_useful_memory', learned: 0 })
+ expect(run).toHaveBeenCalledTimes(2)
+ expect(store.learning.status().jobs).toEqual({ no_useful_memory: 1 })
+ } finally { store.close(); rmSync(directory, { recursive: true, force: true }) }
+})
diff --git a/cli/src/memory/companion.ts b/cli/src/memory/companion.ts
index 017e0bb2c..f8668bc31 100644
--- a/cli/src/memory/companion.ts
+++ b/cli/src/memory/companion.ts
@@ -13,7 +13,7 @@ export function companionMemoryInference(intelligence: Pick<CompanionIntelligenc
async target() {
const status = await intelligence.extractionStatus()
if (status.state === 'off') return { state: 'off' }
- if (status.state === 'unsupported') return { state: 'unsupported' }
+ if (status.state === 'unsupported') return { state: 'unsupported', ...(status.reason ? { reason: status.reason } : {}) }
if (status.state !== 'ready' || !status.contextKey || !status.agentId) return { state: 'waiting' }
if (status.engine === 'codex' && !(await codexCapability()).supported) return { state: 'unsupported' }
if (status.engine === 'claude' && !(await claudeCapability()).supported) return { state: 'unsupported' }
diff --git a/cli/src/memory/learner.spec.ts b/cli/src/memory/learner.spec.ts
index c5142ebf2..9e09ff314 100644
--- a/cli/src/memory/learner.spec.ts
+++ b/cli/src/memory/learner.spec.ts
@@ -264,6 +264,30 @@ it('keeps notebook quota failures pending and does not probe the selected accoun
expect(provider.run).toHaveBeenCalledOnce()
})
+it('keeps a refused notebook pending, respects pause, and resumes with a usable connection', async () => {
+ await seedNotebook()
+ const provider = inference('{"statements":[]}')
+ provider.run = vi.fn(async () => { throw new MemoryError('inference_provider_restricted') })
+ const learner = new MemoryLearner(memory, provider)
+ const refused = { state: 'waiting_for_model', reason: 'inference_provider_restricted' }
+ expect(await learner.tick()).toEqual(refused)
+ provider.target = vi.fn<MemoryInference['target']>(async () => ({ state: 'unsupported', reason: 'inference_provider_restricted' }))
+ expect(await learner.tick()).toEqual(refused)
+ now += 60_001
+ expect(await learner.tick()).toEqual(refused)
+ expect(provider.run).toHaveBeenCalledOnce()
+ expect(store.list(access)).toHaveLength(1)
+ store.setControls({ learn: false, recall: true })
+ vi.mocked(provider.target).mockClear()
+ expect(await learner.tick()).toEqual({ state: 'learning_off' })
+ expect(provider.target).not.toHaveBeenCalled()
+ store.setControls({ learn: true, recall: true })
+ provider.target = vi.fn<MemoryInference['target']>(async () => ({ state: 'ready', key: 'new-connection' }))
+ provider.run = vi.fn(async () => '{"statements":[]}')
+ expect(await learner.tick()).toEqual({ state: 'notebook_empty' })
+ expect(provider.run).toHaveBeenCalledOnce()
+})
+
it.each([null, 'not JSON', '{"statements":[],"decisions":[]}'])('distinguishes unavailable and malformed notebook output from empty synthesis: %s', async answer => {
await seedNotebook()
expect((await new MemoryLearner(memory, inference(answer)).tick()).state).toBe(answer === null ? 'waiting_for_model' : 'failed')
diff --git a/cli/src/memory/learner.ts b/cli/src/memory/learner.ts
index 633b0d9ba..4fc18c367 100644
--- a/cli/src/memory/learner.ts
+++ b/cli/src/memory/learner.ts
@@ -90,6 +90,7 @@ Supporting memory records: ${JSON.stringify(lease.input.records)}
export class MemoryLearner {
private active: Promise<LearningOutcome> | null = null
private controller: AbortController | null = null
+ private providerRestricted = false
constructor(private readonly memory: MemoryPort, private readonly inference: MemoryInference, private readonly timeoutMs = 90_000) {}
tick(): Promise<LearningOutcome> {
@@ -111,12 +112,25 @@ export class MemoryLearner {
const pending = await this.memory.request('pendingReview', [])
assertActive(controller.signal)
if (pending === 'learning_off') return { state: pending }
+ // Keep a non-retryable refusal visible even while the failed lease is deferred. The host's
+ // refusal status is cheap and suppresses native probes; only a changed connection can retry.
+ let target: InferenceTarget | undefined
+ if (this.providerRestricted) {
+ target = await this.inference.target()
+ assertActive(controller.signal)
+ if (target.state !== 'ready') return { state: 'waiting_for_model', ...(target.reason ? { reason: target.reason } : {}) }
+ this.providerRestricted = false
+ }
const notebook = await this.memory.request('notebookPending', [])
assertActive(controller.signal)
const buildNotebook = notebook.state === 'ready' && (pending !== 'ready' || notebook.prefer)
if (!buildNotebook && pending !== 'ready') return { state: notebook.state === 'idle' ? pending : notebook.state }
- const target = await this.inference.target()
+ target ??= await this.inference.target()
if (controller.signal.aborted) return { state: controller.signal.reason === 'foreground_activity' ? 'waiting_for_quiet' : 'cancelled' }
+ if (target.reason === 'inference_provider_restricted') {
+ this.providerRestricted = true
+ return { state: 'waiting_for_model', reason: target.reason }
+ }
const timeoutMs = Math.max(1, Math.min(this.timeoutMs, 90_000))
if (buildNotebook) {
const claim = await this.memory.request('notebookClaim', [target])
@@ -167,8 +181,9 @@ export class MemoryLearner {
const failure = error instanceof MemoryError ? error.code : 'inference_unavailable'
const code = failure === 'inference_cancelled' && controller.signal.reason === 'foreground_activity'
? 'inference_interrupted' : failure
+ if (code === 'inference_provider_restricted') this.providerRestricted = true
const state = code === 'inference_interrupted' ? 'queued' : code === 'inference_usage_limit' ? 'budget_deferred'
- : ['inference_cancelled', 'inference_context_changed', 'inference_unavailable', 'codex_version_uncertified', 'claude_version_uncertified'].includes(code) ? 'waiting_for_model'
+ : ['inference_cancelled', 'inference_context_changed', 'inference_unavailable', 'inference_provider_restricted', 'codex_version_uncertified', 'claude_version_uncertified'].includes(code) ? 'waiting_for_model'
: code === 'episode_context_too_large' ? 'source_incomplete' : 'failed'
if (lease) await this.memory.request('defer', [lease, state]).catch(() => {})
if (notebookLease) await this.memory.request('notebookDefer', [notebookLease, state === 'source_incomplete' ? 'failed' : state]).catch(() => {})
diff --git a/cli/src/memory/opencodeInference.spec.ts b/cli/src/memory/opencodeInference.spec.ts
index c7f1f41ea..bbfd345f9 100644
--- a/cli/src/memory/opencodeInference.spec.ts
+++ b/cli/src/memory/opencodeInference.spec.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { lstat } from 'node:fs/promises'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import providerRefusal from './__fixtures__/opencode-1.18.34-provider-refusal.json' with { type: 'json' }
import { openCodeSnapshotIdentity, opencodeMemoryCapability, runOpenCodeMemoryInference, type OpenCodeMemorySnapshot } from './opencodeInference.js'
vi.mock('node:fs/promises', async importOriginal => {
@@ -112,6 +113,22 @@ it('combines complete native text parts without duplicating repeated full snapsh
expect(await runOpenCodeMemoryInference(options())).toEqual({ text: '{"proposals":[]}' })
})
+it('identifies the recorded provider restriction without treating it as a transient outage', async () => {
+ program(emit([providerRefusal]))
+ await expect(runOpenCodeMemoryInference(options())).rejects.toThrow('inference_provider_restricted')
+ expect(readdirSync(directory)).toEqual(['opencode-fixture'])
+})
+
+it.each([
+ { ...providerRefusal.error.data, statusCode: 429 },
+ { ...providerRefusal.error.data, isRetryable: true },
+ { ...providerRefusal.error.data, responseBody: 'unrecognized provider response' },
+ { ...providerRefusal.error.data, responseBody: '{"error":{"type":"FreeTierError","message":"Another free tier error"}}' },
+])('does not turn other provider failures into a permanent restriction', async data => {
+ program(emit([{ type: 'error', error: { name: 'APIError', data } }]))
+ await expect(runOpenCodeMemoryInference(options())).rejects.toThrow('inference_unavailable')
+})
+
it('retains only native usage and cost, leaving the provider-resolved model unknown', async () => {
program(emit([start, text(), event('step_finish', { type: 'step-finish', reason: 'stop', cost: 0.02,
tokens: { input: 20, output: 10, cache: { read: 4, write: 5 }, private: 'ignored' } })]))
diff --git a/cli/src/memory/opencodeInference.ts b/cli/src/memory/opencodeInference.ts
index 35b62eeee..e72e3002e 100644
--- a/cli/src/memory/opencodeInference.ts
+++ b/cli/src/memory/opencodeInference.ts
@@ -135,8 +135,8 @@ function openCodeMemoryDecoder(): (event: Record<string, unknown>) => InferenceF
const text = new Map<string, string>()
return event => {
if (event.type === 'tool_use') return { error: 'inference_tool_or_error' }
- if (event.type === 'error') return { error: /rate.?limit|quota|usage limit/i.test(JSON.stringify(event.error))
- ? 'inference_usage_limit' : 'inference_unavailable' }
+ if (event.type === 'error') return { error: providerRestricted(event.error) ? 'inference_provider_restricted'
+ : /rate.?limit|quota|usage limit/i.test(JSON.stringify(event.error)) ? 'inference_usage_limit' : 'inference_unavailable' }
const part = event.part as Record<string, unknown> | undefined
if (!part || typeof part !== 'object' || !['step_start', 'text', 'step_finish'].includes(String(event.type))) return { error: 'inference_protocol_changed' }
if (event.type === 'step_start') {
@@ -162,3 +162,18 @@ function openCodeMemoryDecoder(): (event: Record<string, unknown>) => InferenceF
} }
}
}
+
+// Match the recorded non-retryable policy refusal only. An arbitrary 403, free-tier error,
+// or quoted message must not permanently disable learning for this connection.
+const restrictionSchema = z.object({ name: z.literal('APIError'), data: z.object({
+ statusCode: z.literal(403), isRetryable: z.literal(false), responseBody: z.string().max(64_000),
+}) })
+function providerRestricted(error: unknown): boolean {
+ const result = restrictionSchema.safeParse(error)
+ if (!result.success) return false
+ try {
+ const body = JSON.parse(result.data.data.responseBody)
+ return body?.type === 'error' && body?.error?.type === 'FreeTierError'
+ && body.error.message === "Error from provider (Console): OpenCode's free tier can only be used from within OpenCode"
+ } catch { return false }
+}
diff --git a/cli/src/memory/queue.ts b/cli/src/memory/queue.ts
index ae6d58493..7921da001 100644
--- a/cli/src/memory/queue.ts
+++ b/cli/src/memory/queue.ts
@@ -60,6 +60,8 @@ export interface InferenceTarget {
state: 'ready' | 'waiting' | 'off' | 'unsupported'
/** Opaque host-derived identity of the selected account, collection, model, and effort. */
key?: string
+ /** A recognized provider refusal, never raw provider output. */
+ reason?: 'inference_provider_restricted'
foregroundBusy?: boolean
}
export interface LearningLease {
diff --git a/cli/src/pair/intelligence.spec.ts b/cli/src/pair/intelligence.spec.ts
index 3dfc3137e..071284c4d 100644
--- a/cli/src/pair/intelligence.spec.ts
+++ b/cli/src/pair/intelligence.spec.ts
@@ -6,6 +6,7 @@ import { CompanionIntelligence, type CompanionRuntime } from './intelligence.js'
import { encodeRuntimeProfile } from '../lib/runtimeProfile.js'
import type { OneShotOptions } from '../lib/oneshot.js'
import { openCodeSnapshotIdentity, type OpenCodeMemorySnapshot, type OpenCodeMemoryInferenceOptions } from '../memory/opencodeInference.js'
+import { MemoryError } from '../memory/types.js'
let directory: string
beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'collection-model-')) })
@@ -194,6 +195,47 @@ describe('OpenCode companion request binding', () => {
expect(w.run).not.toHaveBeenCalled()
})
+ it.each(['model', 'account', 'process', 'owner'] as const)('holds a provider refusal until the selected %s changes', async change => {
+ const w = openCodeWorld(), contextKey = (await w.brain.extractionStatus()).contextKey!
+ const options = { contextKey, timeoutMs: 1000, signal: new AbortController().signal }
+ w.openCodeRun.mockRejectedValueOnce(new MemoryError('inference_provider_restricted'))
+ await expect(w.brain.extract('synthetic evidence', options)).rejects.toThrow('inference_provider_restricted')
+ expect(await w.brain.extractionStatus()).toMatchObject({ state: 'unsupported', reason: 'inference_provider_restricted', contextKey })
+ expect(await w.brain.extract('same queued evidence', options)).toBeNull()
+ expect(await w.brain.run('background triage', options)).toBeNull()
+ const savedSnapshot = w.snapshot()
+ w.setSnapshot(null)
+ expect(w.brain.status().state).toBe('waiting')
+ w.setSnapshot(structuredClone(savedSnapshot))
+ expect(w.brain.status().state).toBe('unsupported')
+ expect(w.openCodeRun).toHaveBeenCalledOnce()
+ expect(w.run).not.toHaveBeenCalled()
+ expect(readFileSync(w.deps.stateFile, 'utf8')).not.toContain('inference_provider_restricted')
+ if (change === 'model') w.setSnapshot({ ...w.snapshot(), model: 'selected/another',
+ provider: { ...w.snapshot().provider, models: { another: { name: 'Another', limit: { context: 10000, output: 1000 } } } } })
+ if (change === 'account') w.setSnapshot({ ...w.snapshot(), auth: { type: 'api', key: 'replacement' } })
+ if (change === 'process') w.set({ ...w.get(), nativeProcessKey: 'new-process' })
+ if (change === 'owner') w.set({ ...w.get(), accountKey: 'new-owner' })
+ const next = await w.brain.extractionStatus()
+ expect(next.state).toBe('ready')
+ expect(next.contextKey).not.toBe(contextKey)
+ expect(await w.brain.extract('synthetic evidence', { ...options, contextKey: next.contextKey! })).toBe('{"proposals":[]}')
+ expect(w.openCodeRun).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not apply a late refusal to a replacement connection', async () => {
+ const w = openCodeWorld(), contextKey = (await w.brain.extractionStatus()).contextKey!
+ let fail!: (error: Error) => void
+ w.openCodeRun.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject }))
+ const pending = w.brain.extract('synthetic evidence', { contextKey, timeoutMs: 1000, signal: new AbortController().signal })
+ const assertion = expect(pending).rejects.toThrow('inference_provider_restricted')
+ await vi.waitFor(() => expect(w.openCodeRun).toHaveBeenCalledOnce())
+ w.set({ ...w.get(), nativeProcessKey: 'replacement-process' })
+ fail(new MemoryError('inference_provider_restricted'))
+ await assertion
+ expect((await w.brain.extractionStatus()).state).toBe('ready')
+ })
+
it('rejects a queued extraction after the observed account changes', async () => {
const w = openCodeWorld(), contextKey = (await w.brain.extractionStatus()).contextKey!
w.setSnapshot({ ...w.snapshot(), auth: { type: 'api', key: 'replacement-account' } })
diff --git a/cli/src/pair/intelligence.ts b/cli/src/pair/intelligence.ts
index fc063f5d0..414dcbba1 100644
--- a/cli/src/pair/intelligence.ts
+++ b/cli/src/pair/intelligence.ts
@@ -36,6 +36,7 @@ export interface IntelligenceStatus {
model?: string
effort?: string
contextKey?: string
+ reason?: 'inference_provider_restricted'
}
interface IntelligenceDeps {
@@ -53,6 +54,8 @@ interface IntelligenceDeps {
export class CompanionIntelligence {
private saved: Record<string, { sessionId: string; profile: string }> | null = null
private readonly calls = new Set<AbortController>()
+ /** Volatile refusal for one observed connection. No credentials or policy failures are persisted. */
+ private restrictedContext: string | null = null
constructor(private readonly deps: IntelligenceDeps) {}
@@ -73,17 +76,19 @@ export class CompanionIntelligence {
opts.signal?.addEventListener('abort', abort, { once: true })
if (opts.signal?.aborted) controller.abort()
this.calls.add(controller)
+ let target: ReturnType<CompanionIntelligence['target']> | undefined
try {
const bound = extraction || this.deps.current()?.engine === 'opencode'
- const target = bound ? await this.extractionTarget() : this.target()
+ target = bound ? await this.extractionTarget() : this.target()
if (controller.signal.aborted || !target.profile || !target.runtime || target.status.state !== 'ready') return null
if (extraction && (!('contextKey' in opts) || opts.contextKey !== target.status.contextKey)) throw new MemoryError('inference_context_changed')
+ const selected = target
const { runtime, profile } = target
const engine = runtime.engine as 'claude' | 'codex' | 'opencode'
const assertAuthorized = (): void => {
if (controller.signal.aborted) throw new MemoryError('inference_cancelled')
if ('assertAuthorized' in opts) opts.assertAuthorized?.()
- if (this.target().status.contextKey !== target.runtimeContextKey) throw new MemoryError('inference_context_changed')
+ if (this.target().status.contextKey !== selected.runtimeContextKey) throw new MemoryError('inference_context_changed')
}
if (bound) assertAuthorized()
mkdirSync(this.deps.directory, { recursive: true, mode: 0o700 })
@@ -94,7 +99,7 @@ export class CompanionIntelligence {
timeoutMs: opts.timeoutMs, signal: controller.signal,
...(bound ? { assertAuthorized, beforeRun: async () => {
const current = await this.extractionTarget()
- if (current.status.state !== 'ready' || current.status.contextKey !== target.status.contextKey) throw new MemoryError('inference_context_changed')
+ if (current.status.state !== 'ready' || current.status.contextKey !== selected.status.contextKey) throw new MemoryError('inference_context_changed')
} } : {}),
}
const run = this.deps.run ?? ((engine, options) => engine === 'claude' ? extraction ? runClaudeMemoryInference(options) : runClaudeOneShot(options)
@@ -112,6 +117,13 @@ export class CompanionIntelligence {
(!runtime.sessionId && current.runtime?.startup?.processKey !== runtime.startup?.processKey) ||
current.runtime?.codexHome !== runtime.codexHome || current.status.contextKey !== target.status.contextKey) return null
return result.text
+ } catch (error) {
+ if (error instanceof MemoryError && error.code === 'inference_provider_restricted'
+ && !controller.signal.aborted && target?.runtime?.engine === 'opencode'
+ && target.runtimeContextKey && this.target().status.contextKey === target.runtimeContextKey) {
+ this.restrictedContext = target.runtimeContextKey
+ }
+ throw error
} finally {
opts.signal?.removeEventListener('abort', abort)
this.calls.delete(controller)
@@ -164,8 +176,11 @@ export class CompanionIntelligence {
const contextKey = createHash('sha256').update(JSON.stringify([runtime.agentId, runtime.sessionId,
runtime.sessionId ? null : runtime.startup?.processKey, runtime.engine, profile.id, runtime.codexHome ?? null, runtime.accountKey ?? null,
runtime.nativeProcessKey ?? null, openCodeSnapshot ? openCodeSnapshotIdentity(openCodeSnapshot) : null])).digest('hex')
+ if (this.restrictedContext !== contextKey) this.restrictedContext = null
return { runtime, profile, openCodeSnapshot, runtimeContextKey: contextKey,
- status: { ...status, state: 'ready', model: profile.model, effort: openCodeSnapshot?.variant ?? profile.effort, contextKey } }
+ status: { ...status, state: this.restrictedContext ? 'unsupported' : 'ready',
+ ...(this.restrictedContext ? { reason: 'inference_provider_restricted' as const } : {}),
+ model: profile.model, effort: openCodeSnapshot?.variant ?? profile.effort, contextKey } }
}
private load(): void {
diff --git a/desktop/integration_test/coding_memory_activity_native_test.dart b/desktop/integration_test/coding_memory_activity_native_test.dart
index ca10578ac..d0e22ff9e 100644
--- a/desktop/integration_test/coding_memory_activity_native_test.dart
+++ b/desktop/integration_test/coding_memory_activity_native_test.dart
@@ -147,6 +147,40 @@ void main() {
shot.dispose();
}
}
+ connection.runtime = {
+ 'state': 'ready',
+ 'learning': {
+ 'state': 'waiting_for_model',
+ 'reason': 'inference_provider_restricted',
+ },
+ };
+ await library.refresh();
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('provider declined background learning'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Choose another model'), findsOneWidget);
+ expect(connection.learn, isTrue);
+ expect(connection.recall, isTrue);
+ expect(
+ connection.calls.where((p) => p['action'] == 'apply'),
+ hasLength(1),
+ );
+ if (directory != null) {
+ final shot =
+ await (boundary.currentContext!.findRenderObject()
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 1);
+ try {
+ final bytes = await shot.toByteData(format: ui.ImageByteFormat.png);
+ await File(
+ '$directory/provider-refusal-native-${brightness.name}.png',
+ ).writeAsBytes(bytes!.buffer.asUint8List());
+ } finally {
+ shot.dispose();
+ }
+ }
expect(tester.takeException(), isNull);
},
);
diff --git a/desktop/lib/companions/coding_memory_view.dart b/desktop/lib/companions/coding_memory_view.dart
index cff24e99d..9b3738bd9 100644
--- a/desktop/lib/companions/coding_memory_view.dart
+++ b/desktop/lib/companions/coding_memory_view.dart
@@ -310,6 +310,9 @@ class _CodingMemoryViewState extends State<CodingMemoryView> {
: 'Some recent work could not be read for learning. Your existing memories are still available.';
final state = learning['state'];
final message = switch (state) {
+ 'waiting_for_model'
+ when learning['reason'] == 'inference_provider_restricted' =>
+ 'Your selected model’s provider declined background learning. Choose another model in the companion terminal to continue. Existing memories are still available.',
'waiting_for_model' => 'Waiting for your companion’s model. Check that its terminal beside this viewer is running with a model selected, and complete any setup shown there.',
'foreground_busy' =>
'Your companion is working. Learning waits until it is free.',
diff --git a/desktop/test/coding_memory_view_test.dart b/desktop/test/coding_memory_view_test.dart
index aebdd6235..1ac7b51f0 100644
--- a/desktop/test/coding_memory_view_test.dart
+++ b/desktop/test/coding_memory_view_test.dart
@@ -1112,6 +1112,52 @@ void main() {
]);
});
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'provider refusal explains recovery without changing settings at ${scale}x',
+ (tester) async {
+ transport.runtime = {
+ 'state': 'ready',
+ 'learning': {
+ 'state': 'waiting_for_model',
+ 'reason': 'inference_provider_restricted',
+ },
+ };
+ await mount(
+ tester,
+ scale: scale,
+ size: Size(scale == 1 ? 850 : 440, 900),
+ );
+ expect(find.text('Learning needs attention'), findsOneWidget);
+ expect(
+ find.textContaining('provider declined background learning'),
+ findsOneWidget,
+ );
+ await capture(tester, 'provider-refusal-${scale}x');
+ await tap(tester, 'Review learning');
+ expect(find.textContaining('Choose another model'), findsOneWidget);
+ expect(find.textContaining('complete any setup'), findsNothing);
+ expect(transport.learn, isTrue);
+ expect(transport.recall, isTrue);
+ expect(
+ transport.calls.every(
+ (p) => p['action'] != 'preview' && p['action'] != 'apply',
+ ),
+ isTrue,
+ );
+ expect(tester.takeException(), isNull);
+ transport.runtime = {
+ 'state': 'ready',
+ 'learning': {'state': 'learned', 'learned': 1},
+ };
+ await library.refresh();
+ await tester.pumpAndSettle();
+ expect(find.textContaining('provider declined'), findsNothing);
+ expect(find.textContaining('saved new memories'), findsOneWidget);
+ },
+ );
+ }
+
for (final state in [
('off', null, 'Resume it', true),
('unavailable', null, 'memory service', true),
diff --git a/docs/plans/2026-09-30-coding-memory-review-log.md b/docs/plans/2026-09-30-coding-memory-review-log.md
index 23a16ce7b..ab6969190 100644
--- a/docs/plans/2026-09-30-coding-memory-review-log.md
+++ b/docs/plans/2026-09-30-coding-memory-review-log.md
@@ -822,3 +822,34 @@ and shared correction/forgetting checks cover the new Claude version alongside C
No real account, model selection, conversation, installed application, or release was changed.
Print-mode transport is the measured boundary: production account/profile changes, interactive TUI
paths, semantic quality, and coding-task usefulness are not established by these mock observations.
+
+### Stop repeating a provider's non-retryable refusal — October 2
+
+A synthetic READY request through the saved OpenCode Muse free model received HTTP 403 with the
+provider's `FreeTierError`: this route was restricted to use within OpenCode. No extraction case
+completed. This is a provider refusal, not a memory-quality score. A similar custom-agent restriction
+is [reported upstream](https://github.com/anomalyco/opencode/issues/50627); that report does not prove
+the cause of this particular request. No private conversations or personal credentials were supplied.
+
+The production adapter previously turned this error into a generic model outage. Its selected
+connection remained ready, allowing another background call after the queue's one-minute defer.
+The adapter now recognizes the exact recorded, non-retryable refusal. Companion intelligence retains
+only an opaque connection fingerprint in memory, stops further background calls on that connection,
+and clears the refusal when the observed model, account, owner or native process changes. A routine
+refresh of the same snapshot does not reset it; a late error cannot block a replacement connection.
+Ordinary outages and quota failures retain their existing handling. No credential or refusal is added
+to the saved companion profile, and no alternative model is selected automatically.
+
+Learning keeps its sources queued under the existing retention and capacity limits, preserves the
+refusal during the deferred interval, and keeps notebook work pending as well. Memories explains
+that the selected provider declined background learning and points to the companion's existing model
+control. Reviewing that explanation does not change Learn or Recall. The foreground terminal remains
+available; saved memories remain subject to the existing Recall setting.
+
+The [recording](../research/2026-10-02-memory-provider-refusal.json) includes the real OpenCode 1.18.34
+binary receiving the same refusal from a localhost mock: exactly one request, no tools, no forbidden
+action, and disposable native storage removed. Synthetic integration checks exercise the production
+intelligence, learner and queue over more than an hour, then resume on a new connection without
+dropping source evidence. These checks establish refusal handling, not semantic extraction quality,
+live user learning, or improved coding outcomes. The selected external route was not retried or
+bypassed, and real-session quality evaluation remains incomplete.
diff --git a/docs/research/2026-10-02-memory-provider-refusal.json b/docs/research/2026-10-02-memory-provider-refusal.json
new file mode 100644
index 000000000..5ced845c8
--- /dev/null
+++ b/docs/research/2026-10-02-memory-provider-refusal.json
@@ -0,0 +1,108 @@
+{
+ "at": "2026-10-02T15:09:23.275Z",
+ "capability": {
+ "supported": true,
+ "version": "1.18.34"
+ },
+ "runs": [
+ {
+ "mode": "text",
+ "requests": [
+ {
+ "route": "/v1/chat/completions",
+ "model": "memory-model",
+ "tools": [],
+ "selectedCredential": true
+ }
+ ],
+ "snapshotReads": 3,
+ "result": {
+ "text": "{\"proposals\":[]}"
+ },
+ "forbiddenFileExists": false,
+ "privateStorageRemoved": true
+ },
+ {
+ "mode": "bash",
+ "requests": [
+ {
+ "route": "/v1/chat/completions",
+ "model": "memory-model",
+ "tools": [],
+ "selectedCredential": true
+ },
+ {
+ "route": "/v1/chat/completions",
+ "model": "memory-model",
+ "tools": [],
+ "selectedCredential": true
+ }
+ ],
+ "snapshotReads": 2,
+ "error": "inference_tool_or_error",
+ "forbiddenFileExists": false,
+ "privateStorageRemoved": true
+ },
+ {
+ "mode": "question",
+ "requests": [
+ {
+ "route": "/v1/chat/completions",
+ "model": "memory-model",
+ "tools": [],
+ "selectedCredential": true
+ },
+ {
+ "route": "/v1/chat/completions",
+ "model": "memory-model",
+ "tools": [],
+ "selectedCredential": true
+ }
+ ],
+ "snapshotReads": 2,
+ "error": "inference_tool_or_error",
+ "forbiddenFileExists": false,
+ "privateStorageRemoved": true
+ },
+ {
+ "mode": "provider_restricted",
+ "requests": [
+ {
+ "route": "/v1/chat/completions",
+ "model": "memory-model",
+ "tools": [],
+ "selectedCredential": true
+ }
+ ],
+ "snapshotReads": 2,
+ "error": "inference_provider_restricted",
+ "forbiddenFileExists": false,
+ "privateStorageRemoved": true
+ }
+ ],
+ "limitations": [
+ "Synthetic localhost responses; no personal conversations or real model inference.",
+ "Native transport only. This probe does not exercise production account/config observation or companion wiring.",
+ "No claim about extraction quality, OAuth, automatic compaction or task benefit."
+ ],
+ "provenance": {
+ "input": "Synthetic extraction and localhost responses only; no real accounts or conversations.",
+ "script": "cli/scripts/memory-native-opencode-inference-probe.mjs",
+ "scriptSha256": "efbfb7dac25818e04f1928301508e6a4b4149d7e84669c58d50eb03bf74ea9d9",
+ "adapterSha256": "e5fe3c6194718e9e388248ca907cf85f48a0a02904beea9879488618a28c7471",
+ "fixture": "cli/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.json",
+ "fixtureSource": "Native 1.18.34 error recorded on 2026-10-02 at 14:48 UTC during a synthetic READY request to the saved public free model. Headers, route and identifiers omitted.",
+ "qualityCredit": false
+ },
+ "observedExternalDiagnostic": {
+ "at": "2026-10-02T14:48:18Z",
+ "engine": "opencode",
+ "nativeVersion": "1.18.34",
+ "model": "opencode/muse-spark-1.3-contributor-free",
+ "input": "Synthetic READY request in disposable storage; public native credential only.",
+ "statusCode": 403,
+ "errorType": "FreeTierError",
+ "completedExtractionCases": 0,
+ "qualityCredit": false
+ }
+}