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
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@
*.mjs diff
*.json diff=json
.gitattributes diff
# VERBOO-BRAND: classifier prompts are reviewable policy, not binary blobs.
*.txt diff
17 changes: 17 additions & 0 deletions UPSTREAM_SYNC.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,23 @@ em volta. Use `git grep "VERBOO-BRAND"` para localizar todos os pontos editados.
- `src/commands/provider/` — arquivos **NÃO foram deletados** (upstream
continua mexendo neles; deletar gera conflitos "deleted file modified upstream").

#### Auto mode (comportamento próximo ao do Claude Code)
- `src/utils/messages.ts` — instrução do auto mode reescrita (não pedir
licença para o que foi pedido; pergunta encerra a vez).
- `src/utils/permissions/yoloClassifier.ts` — modelo do papel `classifier` do
roteador (`VERBOO_AUTO_MODE_MODEL` para diagnóstico); `classifierSideQuery`
com prazo e uma nova tentativa; resposta fora do formato = `unavailable`;
regras do usuário somam às padrão.
- `src/utils/permissions/permissions.ts` — classificador indisponível pergunta
ao usuário na sessão interativa (headless continua negando).
- `src/services/api/openaiShim.ts` — tool call forçado com `finish_reason:
stop` é aceito.
- `src/utils/settings/settings.ts` — `localSettings` não conta para o opt-in
nem para regras do classificador.
- `src/services/analytics/growthbook.ts` e `scripts/no-telemetry-plugin.ts` —
`jsonlTranscript: true`; overrides de objeto mesclam; arquivo em
`~/.verboo/feature-flags.json`.

#### Mensagens reescritas
- `src/utils/providerValidation.ts` (3 ocorrências)
- `src/services/api/withRetry.ts`
Expand Down
18 changes: 17 additions & 1 deletion scripts/no-telemetry-growthbook-stub.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,20 @@ describe('growthbook stub — local feature flag overrides', () => {
writeFileSync(flagsFile, JSON.stringify({ tengu_disable_bypass_permissions_mode: true }))
expect(await stub.checkSecurityRestrictionGate('tengu_disable_bypass_permissions_mode')).toBe(false)
})
})

// VERBOO-BRAND: an object override is merged over the open-build default, so
// tuning one auto mode key does not silently turn auto mode off.
test('object overrides merge over the open-build auto mode default', () => {
expect(
stub.getFeatureValue_CACHED_MAY_BE_STALE('tengu_auto_mode_config', {}),
).toEqual({ enabled: 'enabled', jsonlTranscript: true })
writeFileSync(
flagsFile,
JSON.stringify({ tengu_auto_mode_config: { model: 'some/model' } }),
)
stub.resetGrowthBook()
expect(
stub.getFeatureValue_CACHED_MAY_BE_STALE('tengu_auto_mode_config', {}),
).toEqual({ enabled: 'enabled', jsonlTranscript: true, model: 'some/model' })
})
})
19 changes: 13 additions & 6 deletions scripts/no-telemetry-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,16 @@ let _flags = undefined;
// features. Only keys that DIFFER from upstream belong here — the
// catalog below is pure documentation and does NOT affect resolution.
//
// Priority: ~/.claude/feature-flags.json > _openBuildDefaults > defaultValue
// Priority: ~/.verboo/feature-flags.json > _openBuildDefaults > defaultValue
//
// To override at runtime, create ~/.claude/feature-flags.json:
// To override at runtime, create ~/.verboo/feature-flags.json:
// { "tengu_some_flag": true }
const _openBuildDefaults = {
'tengu_sedge_lantern': true, // AWAY_SUMMARY — "while you were away" recap (upstream: false)
'tengu_hive_evidence': true, // VERIFICATION_AGENT — read-only test/verification agent (upstream: false)
'tengu_passport_quail': true, // EXTRACT_MEMORIES — enable memory extraction (upstream: false)
'tengu_coral_fern': true, // EXTRACT_MEMORIES — enable memory search in past context (upstream: false)
'tengu_auto_mode_config': { enabled: 'enabled' }, // AUTO MODE — expose the permission classifier in the Shift+Tab carousel (upstream default: 'disabled' when unset)
'tengu_auto_mode_config': { enabled: 'enabled', jsonlTranscript: true }, // AUTO MODE — expose the classifier in the Shift+Tab carousel; JSONL transcript so tool output cannot forge a "User:" line
};

/* ── Known runtime feature keys (reference only) ───────────────────────
Expand All @@ -65,7 +65,7 @@ const _openBuildDefaults = {
* Some keys have different defaults at different call sites — this is
* intentional upstream (the server unifies the value at runtime).
*
* To activate any of these, add them to ~/.claude/feature-flags.json
* To activate any of these, add them to ~/.verboo/feature-flags.json
* or to _openBuildDefaults above.
*
* ── Reasoning & thinking ──────────────────────────────────────────────
Expand Down Expand Up @@ -188,8 +188,9 @@ const _openBuildDefaults = {
function _loadFlags() {
if (_flags !== undefined) return;
try {
// VERBOO-BRAND: the overrides file lives in the Verboo config dir.
const flagsPath = process.env.CLAUDE_FEATURE_FLAGS_FILE
|| _path.join(_os.homedir(), '.claude', 'feature-flags.json');
|| _path.join(process.env.VERBOO_CONFIG_DIR || _path.join(_os.homedir(), '.verboo'), 'feature-flags.json');
const parsed = JSON.parse(_fs.readFileSync(flagsPath, 'utf-8'));
_flags = (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : null;
} catch {
Expand All @@ -199,7 +200,13 @@ function _loadFlags() {

function _getFlagValue(key, defaultValue) {
_loadFlags();
if (_flags != null && Object.hasOwn(_flags, key)) return _flags[key];
if (_flags != null && Object.hasOwn(_flags, key)) {
const value = _flags[key];
const base = _openBuildDefaults[key];
// VERBOO-BRAND: object overrides merge over the open-build default.
const isObj = v => typeof v === 'object' && v !== null && !Array.isArray(v);
return isObj(base) && isObj(value) ? { ...base, ...value } : value;
}
if (Object.hasOwn(_openBuildDefaults, key)) return _openBuildDefaults[key];
return defaultValue;
}
Expand Down
28 changes: 11 additions & 17 deletions src/cli/handlers/autoMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,24 @@ export function autoModeDefaultsHandler(): void {
}

/**
* Dump the effective auto mode config: user settings where provided, external
* defaults otherwise. Per-section REPLACE semantics — matches how
* buildYoloSystemPrompt resolves the external template (a non-empty user
* section replaces that section's defaults entirely; an empty/absent section
* falls through to defaults).
* Dump the effective auto mode config: the external defaults plus the user's
* rules. VERBOO-BRAND: additive, matching how buildYoloSystemPrompt resolves
* the template, so custom rules never drop a default protection.
*/
export function autoModeConfigHandler(): void {
const config = getAutoModeConfig()
const defaults = getDefaultExternalAutoModeRules()
writeRules({
allow: config?.allow?.length ? config.allow : defaults.allow,
soft_deny: config?.soft_deny?.length
? config.soft_deny
: defaults.soft_deny,
environment: config?.environment?.length
? config.environment
: defaults.environment,
allow: [...defaults.allow, ...(config?.allow ?? [])],
soft_deny: [...defaults.soft_deny, ...(config?.soft_deny ?? [])],
environment: [...defaults.environment, ...(config?.environment ?? [])],
})
}

const CRITIQUE_SYSTEM_PROMPT =
'You are an expert reviewer of auto mode classifier rules for Claude Code.\n' +
'You are an expert reviewer of auto mode classifier rules for Verboo Code.\n' +
'\n' +
'Claude Code has an "auto mode" that uses an AI classifier to decide whether ' +
'Verboo Code has an "auto mode" that uses an AI classifier to decide whether ' +
'tool calls should be auto-approved or require user confirmation. Users can ' +
'write custom rules in three categories:\n' +
'\n' +
Expand Down Expand Up @@ -125,7 +119,7 @@ export async function autoModeCritiqueHandler(options: {
'<classifier_system_prompt>\n' +
classifierPrompt +
'\n</classifier_system_prompt>\n\n' +
"Here are the user's custom rules that REPLACE the corresponding default sections:\n\n" +
"Here are the user's custom rules, which are ADDED to the corresponding default sections:\n\n" +
userRulesSummary +
'\nPlease critique these custom rules.',
},
Expand Down Expand Up @@ -158,11 +152,11 @@ function formatRulesForCritique(
return (
'## ' +
section +
' (custom rules replacing defaults)\n' +
' (custom rules added to the defaults)\n' +
'Custom:\n' +
customLines +
'\n\n' +
'Defaults being replaced:\n' +
'Defaults that stay in effect:\n' +
defaultLines +
'\n\n'
)
Expand Down
4 changes: 3 additions & 1 deletion src/components/Settings/Config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,9 @@ export function Config({
onChange(mode: string) {
const parsedMode = permissionModeFromString(mode);
// Internal modes (e.g. auto) are stored directly
const validatedMode = isExternalPermissionMode(parsedMode) ? toExternalPermissionMode(parsedMode) : parsedMode;
// VERBOO-BRAND: isExternalPermissionMode() is always true outside ant
// builds, so "auto" was converted to "default" and the choice was lost.
const validatedMode = parsedMode === 'auto' ? parsedMode : isExternalPermissionMode(parsedMode) ? toExternalPermissionMode(parsedMode) : parsedMode;
const result = updateSettingsForSource('userSettings', {
permissions: {
...settingsData?.permissions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { BULLET_OPERATOR } from '../../../constants/figures.js';
import { Text } from '../../../ink.js';
import { filterToolProgressMessages, type Tool, type Tools } from '../../../Tool.js';
import type { ProgressMessage } from '../../../types/message.js';
import { INTERRUPT_MESSAGE_FOR_TOOL_USE, isClassifierDenial, PLAN_REJECTION_PREFIX, REJECT_MESSAGE_WITH_REASON_PREFIX } from '../../../utils/messages.js';
import { INTERRUPT_MESSAGE_FOR_TOOL_USE, getClassifierDenialReason, isClassifierDenial, PLAN_REJECTION_PREFIX, REJECT_MESSAGE_WITH_REASON_PREFIX } from '../../../utils/messages.js';
import { FallbackToolUseErrorMessage } from '../../FallbackToolUseErrorMessage.js';
import { InterruptedByUser } from '../../InterruptedByUser.js';
import { MessageResponse } from '../../MessageResponse.js';
Expand Down Expand Up @@ -71,14 +71,8 @@ export function UserToolErrorMessage(t0) {
return t1;
}
if (feature("TRANSCRIPT_CLASSIFIER") && typeof param.content === "string" && isClassifierDenial(param.content)) {
let t1;
if ($[6] === Symbol.for("react.memo_cache_sentinel")) {
t1 = <MessageResponse height={1}><Text dimColor={true}>Denied by auto mode classifier {BULLET_OPERATOR} open an issue if incorrect</Text></MessageResponse>;
$[6] = t1;
} else {
t1 = $[6];
}
return t1;
// VERBOO-BRAND: the person sees why it was blocked, not only that it was.
return <MessageResponse><Text dimColor={true}>Denied by auto mode classifier: {getClassifierDenialReason(param.content)} {BULLET_OPERATOR} open an issue if incorrect</Text></MessageResponse>;
}
let t1;
if ($[7] !== isTranscriptMode || $[8] !== param.content || $[9] !== progressMessagesForMessage || $[10] !== tool || $[11] !== tools || $[12] !== verbose) {
Expand Down
29 changes: 23 additions & 6 deletions src/services/analytics/growthbook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
*
* OpenClaude does not phone home. This module replaces the original
* analytics-driven GrowthBook client with a local-only implementation that
* reads feature flags from ~/.claude/feature-flags.json for developer overrides.
* reads feature flags from ~/.verboo/feature-flags.json for developer overrides.
*
* Priority: CLAUDE_FEATURE_FLAGS_FILE env > ~/.claude/feature-flags.json > defaultValue
* Priority: CLAUDE_FEATURE_FLAGS_FILE env > ~/.verboo/feature-flags.json > defaultValue
*/

import { existsSync, readFileSync } from 'node:fs'
Expand All @@ -25,17 +25,20 @@ const _openBuildDefaults: Record<string, unknown> = {
// kill switch that defaults to 'disabled' when the config is absent, which
// made auto mode unreachable in this build. 'enabled' exposes it in the
// carousel; the opt-in dialog is still shown on first entry.
tengu_auto_mode_config: { enabled: 'enabled' },
// jsonlTranscript: the classifier sees tool calls as JSON lines, so a command
// or file content cannot forge a "User:" line and fake the user's approval.
tengu_auto_mode_config: { enabled: 'enabled', jsonlTranscript: true },
}

let _flags: Record<string, unknown> | null | undefined = undefined

function _loadFlags(): void {
if (_flags !== undefined) return
try {
// VERBOO-BRAND: the overrides file lives in the Verboo config dir.
const flagsPath =
process.env.CLAUDE_FEATURE_FLAGS_FILE ||
join(homedir(), '.claude', 'feature-flags.json')
join(process.env.VERBOO_CONFIG_DIR || join(homedir(), '.verboo'), 'feature-flags.json')
const parsed = JSON.parse(readFileSync(flagsPath, 'utf-8'))
_flags =
parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null
Expand All @@ -44,10 +47,22 @@ function _loadFlags(): void {
}
}

function _isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}

function _getFlagValue<T>(key: string, defaultValue: T): T {
_loadFlags()
if (_flags != null && Object.hasOwn(_flags as object, key))
return (_flags as Record<string, unknown>)[key] as T
if (_flags != null && Object.hasOwn(_flags as object, key)) {
const value = (_flags as Record<string, unknown>)[key]
// VERBOO-BRAND: an object override is merged over the open-build default,
// so {"tengu_auto_mode_config":{"model":"x"}} keeps auto mode enabled.
const base = _openBuildDefaults[key]
if (_isPlainObject(base) && _isPlainObject(value)) {
return { ...base, ...value } as T
}
return value as T
}
if (Object.hasOwn(_openBuildDefaults, key))
return _openBuildDefaults[key] as T
return defaultValue
Expand Down Expand Up @@ -127,6 +142,8 @@ export function getFeatureValue_CACHED_MAY_BE_STALE<T>(
export function getFeatureValue_CACHED_WITH_REFRESH<T>(
_featureName: string,
defaultValue: T,
// Upstream callers pass a refresh interval; nothing refreshes in this build.
_refreshMs?: number,
): T {
return _getFlagValue(_featureName, defaultValue)
}
Expand Down
54 changes: 54 additions & 0 deletions src/services/api/openaiShim.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9082,3 +9082,57 @@ test.each([

expect(events.filter((e) => e.type === 'message_stop')).toHaveLength(0)
})

// VERBOO-BRAND: OpenAI-compatible servers often finish a forced function call
// with finish_reason "stop". The auto mode classifier forces one tool; its
// answer must be committed, not discarded as an unfinished call.
test.each([
{ forced: true, callName: 'classify_result', committed: true },
{ forced: false, callName: 'classify_result', committed: false },
{ forced: true, callName: 'other_tool', committed: false },
])('forced tool call finished with "stop" (forced=$forced, call=$callName)', async ({ forced, callName, committed }) => {
process.env.CLAUDE_CODE_USE_OPENAI = '1'
process.env.OPENAI_BASE_URL = 'http://forced-tool.test/v1'
process.env.OPENAI_API_KEY = 'test-key'
globalThis.fetch = (async () =>
new Response(JSON.stringify({
id: 'chatcmpl-forced',
model: 'some-model',
choices: [{
message: {
role: 'assistant',
content: null,
tool_calls: [{
id: 'call_1',
type: 'function',
function: { name: callName, arguments: '{"shouldBlock":false,"reason":"ok"}' },
}],
},
finish_reason: 'stop',
}],
}), { headers: { 'Content-Type': 'application/json' } })) as unknown as FetchType

const client = createOpenAIShimClient({}) as OpenAIShimClient
const tool = (name: string) => ({
name,
description: `${name} tool`,
input_schema: { type: 'object', properties: { shouldBlock: { type: 'boolean' }, reason: { type: 'string' } } },
})
const result = await client.beta.messages.create({
model: 'some-model',
messages: [{ role: 'user', content: 'classify' }],
max_tokens: 64,
stream: false,
tools: [tool('classify_result'), tool('other_tool')],
...(forced ? { tool_choice: { type: 'tool', name: 'classify_result' } } : {}),
}) as { content: Array<{ type: string; name?: string }>; stop_reason: string }

const toolUses = result.content.filter(block => block.type === 'tool_use')
if (committed) {
expect(toolUses.map(block => block.name)).toEqual(['classify_result'])
expect(result.stop_reason).toBe('tool_use')
} else {
expect(toolUses).toEqual([])
expect(result.stop_reason).toBe('end_turn')
}
})
Loading
Loading