2026-09-02 08:26:45 +08:00
/**
* @fileoverview Zod validation for CLI registry entries.
*
* Every object here is `.strict()`: an unknown key is a hard validation error, not a
* silently-ignored one. That matters for a security-relevant schema — a typo in a field name
* must never degrade to "field absent, so the permissive default applies".
*
* The load-bearing rule enforced here is `SHELL_TOKEN`: it is what makes it impossible for a
* `clis.json` entry to smuggle shell metacharacters into the eventual `bash -c "..."` string
* (see argv.ts's file header for the full model).
*
* @module config/cli-registry/schema
*/
import { z } from 'zod' ;
2026-10-07 12:22:45 +02:00
import { compileVersionRegex , countCaptureGroups , TOKEN_PATTERNS } from './patterns.js' ;
2026-09-02 08:26:45 +08:00
import { isKnownLauncherProfile , isKnownSetenvProfile } from './profiles.js' ;
2026-10-11 07:10:41 +02:00
import type { AgentSkillDir , LaunchDefaultSettingKey , McpConfigFormat , ModelConfigResolverName } from './types.js' ;
/** `capabilities.agentSkillDir`: every value must stay a fixed, relative, `..`-free path. */
export const AGENT_SKILL_DIRS = [ '.claude/skills' , '.agents/skills' ] as const satisfies readonly AgentSkillDir [];
2026-09-02 08:26:45 +08:00
/** A bare CLI id: lowercase, starts with a letter, at most 24 chars. Also used as a CSS/URL token. */
const cliId = z
. string ()
. regex ( /^[a-z][a-z0-9-]{0,23}$/ , 'id must be lowercase, start with a letter, and be at most 24 chars' );
/** An env var name. */
const envName = z
. string ()
. regex ( /^[A-Z_][A-Z0-9_]*$/ , 'env var name must be UPPER_SNAKE_CASE' )
. max ( 64 );
2026-10-04 23:43:36 +02:00
/** A relative file path with no traversal or odd characters (MCP sync writes to it). */
const mcpRelativePath = z
. string ()
. min ( 1 )
. max ( 100 )
. regex ( /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/ )
. refine (( v ) => ! v . split ( '/' ). includes ( '..' ), 'must not contain ..' );
2026-09-02 08:26:45 +08:00
/**
* A shell-safe bare word: no space, quote, backtick, `$`, `;`, `&`, `|`, `<`, `>`, parens,
* braces, newline or backslash. Every LITERAL in the launch spec (base command, flag names,
* fixed values) must satisfy this — see argv.ts's file header.
*/
const shellToken = z
. string ()
. min ( 1 )
. max ( 256 )
. regex ( /^[A-Za-z0-9._:@=+/,-]+$/ , 'must be a plain word with no shell metacharacters' );
const flagToken = z . string (). regex ( /^--?[A-Za-z0-9][A-Za-z0-9-]*$/ , 'must look like -x or --long-flag' );
const quoteStyle = z . enum ([ 'auto' , 'bare' , 'double' , 'single' ]);
const condSchema : z.ZodType < import ( './types.js' ) .Cond > = z . lazy (() =>
z . union ([
z . object ({ param : z.string (), is : z . union ([ z . string (), z . boolean ()]) }). strict (),
z . object ({ param : z.string (), state : z.enum ([ 'set' , 'unset' ]) }). strict (),
z . object ({ allOf : z.array ( condSchema ). min ( 1 ). max ( 8 ) }). strict (),
z . object ({ anyOf : z.array ( condSchema ). min ( 1 ). max ( 8 ) }). strict (),
z . object ({ not : condSchema }). strict (),
z . object ({ capabilityGate : z.string () }). strict (),
])
);
const paramSpecSchema = z . union ([
z
. object ({ type : z . literal ( 'enum' ), values : z.array ( z . string ()). min ( 1 ). max ( 16 ), default : z . string (). optional () })
. strict (),
z . object ({ type : z . literal ( 'bool' ) }). strict (),
z . object ({ type : z . literal ( 'token' ), pattern : z.enum ( TOKEN_PATTERNS as [ string , ... string []]) }). strict (),
z
. object ({
type : z . literal ( 'engine' ),
source : z.enum ([
'sessionId' ,
'sessionName' ,
'muxName' ,
'effortLevel' ,
'effortSettingsJson' ,
'codemanPrefixedSessionId' ,
'launcherDefaultTarget' ,
]),
})
. strict (),
]);
const argSpecSchema = z . union ([
z . object ({ lit : shellToken , when : condSchema.optional () }). strict (),
z . object ({ flag : flagToken , when : condSchema.optional () }). strict (),
z . object ({ flag : flagToken , value : shellToken , quote : quoteStyle.optional (), when : condSchema.optional () }). strict (),
z
. object ({ flag : flagToken , valueFrom : z.string (), quote : quoteStyle.optional (), when : condSchema.optional () })
. strict (),
z . object ({ valueFrom : z.string (), quote : quoteStyle.optional (), when : condSchema.optional () }). strict (),
]);
const variantSchema = z
. object ({
id : z.string (). min ( 1 ). max ( 40 ),
when : condSchema.optional (),
// min(0): the `shell` entry declares a variant with no args — tmux-manager resolves the
// real login shell in code, since it varies per remote user's /etc/passwd entry.
args : z.array ( argSpecSchema ). max ( 32 ),
})
. strict ();
const launchSchema = z
. object ({
params : z.record ( z . string (), paramSpecSchema ),
chain : z.enum ([ 'first' , 'fallback' ]). optional (),
variants : z.array ( variantSchema ). min ( 1 ). max ( 4 ),
legacyConfigAliases : z.record ( z . string (), z . string ()). optional (),
legacyConfigField : z.string (). min ( 1 ). max ( 40 ). optional (),
resumeAppend : z
. union ([
z . object ({ style : z.literal ( 'flag' ), flag : flagToken }). strict (),
z . object ({ style : z.literal ( 'positional' ), token : shellToken }). strict (),
])
. optional (),
})
. strict ()
. superRefine (( launch , ctx ) => {
const paramNames = new Set ( Object . keys ( launch . params ));
const checkValueFrom = ( name : string , path : ( string | number )[]) => {
if ( ! paramNames . has ( name )) {
ctx . addIssue ({ code : 'custom' , message : `valueFrom " ${ name } " is not a declared param` , path });
}
};
launch . variants . forEach (( variant , vi ) => {
variant . args . forEach (( arg , ai ) => {
if ( 'valueFrom' in arg ) checkValueFrom ( arg . valueFrom , [ 'variants' , vi , 'args' , ai , 'valueFrom' ]);
});
});
if ( launch . chain === 'fallback' ) {
const last = launch . variants . at ( - 1 );
if ( last ? . when ) {
ctx . addIssue ({
code : 'custom' ,
message : 'the last variant of a fallback chain must have no `when` (it must be the guaranteed terminal case)' ,
path : [ 'variants' , launch . variants . length - 1 , 'when' ],
});
}
}
if ( launch . legacyConfigAliases ) {
for ( const paramName of Object . keys ( launch . legacyConfigAliases )) {
if ( ! paramNames . has ( paramName )) {
ctx . addIssue ({
code : 'custom' ,
message : `legacyConfigAliases key " ${ paramName } " is not a declared param` ,
path : [ 'legacyConfigAliases' , paramName ],
});
}
}
}
});
const versionProbeSchema = z
. object ({
arg : shellToken ,
regex : z.string (). max ( 200 ). optional (),
requireVersionMatch : z.boolean (). optional (),
retryOnTransientFailure : z.boolean (). optional (),
})
. strict ();
const identityProbeSchema = z
. object ({
arg : shellToken ,
// Same 200-char cap as version.regex, and compiled through the same compileVersionRegex()
// guard at use time. This is the second and last config-supplied regex in the registry.
regex : z.string (). min ( 1 ). max ( 200 ),
})
. strict ();
const discoverySchema = z
. object ({
// min(0): the `shell` entry has no binary of its own (it resolves the login shell in code).
binaries : z.array ( shellToken ). max ( 4 ),
searchDirs : z.array ( z . string (). max ( 300 )). max ( 16 ),
version : versionProbeSchema.optional (),
identity : identityProbeSchema.optional (),
launcherProfile : z.string (). max ( 40 ). optional (),
launcherTargetParam : z.string (). max ( 40 ). optional (),
install : z
. object ({
// z.record with an enum key type requires every enum member in Zod v4; the install
// command legitimately varies by platform and most entries only need one or two, so
// this is a plain object of optional platform keys instead.
command : z
. object ({
linux : z.string (). max ( 500 ). optional (),
darwin : z.string (). max ( 500 ). optional (),
wsl : z.string (). max ( 500 ). optional (),
win32 : z.string (). max ( 500 ). optional (),
})
. strict (),
npmPackage : z.string (). max ( 200 ). optional (),
docsUrl : z.url (). optional (),
2026-09-08 17:04:50 +08:00
// Requires a `reason` on purpose — see the field's own doc comment in types.ts. A
// dedicated agent-image layer with no stated reason is a silent id-keyed special case
// rebuilding itself inside the data this change moved it out of.
agentImageLayer : z
. object ({ kind : z.literal ( 'dedicated' ), reason : z.string (). min ( 1 ). max ( 300 ) })
. strict ()
. optional (),
2026-09-02 08:26:45 +08:00
})
. strict (),
})
. strict ();
const envExportSchema = z
. object ({
name : envName ,
value : z.union ([
shellToken ,
z
. object ({
engine : z.enum ([
'sessionId' ,
'sessionName' ,
'muxName' ,
'effortLevel' ,
'effortSettingsJson' ,
'codemanPrefixedSessionId' ,
'launcherDefaultTarget' ,
]),
})
. strict (),
]),
when : condSchema.optional (),
})
. strict ();
const envSchema = z
. object ({
exports : z.array ( envExportSchema ). max ( 16 ),
unset : z.array ( envName ). max ( 16 ),
tmuxSetenvKeys : z.array ( envName ). max ( 32 ),
dockerExecEnvNames : z.array ( envName ). max ( 32 ),
configSetenv : z
. array ( z . object ({ name : envName , fromParam : z.string (). min ( 1 ). max ( 40 ) }). strict ())
. max ( 8 )
. optional (),
allowedPrefixes : z
. array (
z
. string ()
. min ( 3 )
. max ( 32 )
. regex ( /^[A-Z][A-Z0-9_]*_$/ )
)
. max ( 8 ),
allowedKeys : z.array ( envName ). max ( 8 ),
configContentVar : envName.optional (),
setenvProfile : z.string (). max ( 40 ). optional (),
})
. strict ();
const echoSchema = z
. object ({
policy : z.enum ([ 'buffer' , 'predict' , 'off' ]),
anchor : z.union ([
z
. object ({ kind : z.literal ( 'glyph' ), glyph : z.string (). min ( 1 ). max ( 4 ), offset : z.number (). int (). min ( 0 ). max ( 16 ) })
. strict (),
z . object ({ kind : z.literal ( 'cursor' ) }). strict (),
z . object ({ kind : z.literal ( 'none' ) }). strict (),
]),
predictProfile : z.string (). max ( 40 ). optional (),
})
. strict ();
2026-09-14 23:45:42 +02:00
/**
* `capabilities.customModelInjection.launchModel`: the `model` launch-param value that
* selects the injected provider, with `{modelId}` standing for the chosen id. Bounded to
* the characters the `model`/`model-pi` token patterns accept plus the placeholder braces,
* so a template can never smuggle a token the argv engine would have to quote.
*/
const launchModelTemplate = z
. string ()
. min ( 1 )
. max ( 120 )
. regex ( /^[a-zA-Z0-9._\-/:{}]+$/ )
. optional ();
2026-11-01 21:34:37 +08:00
/** One entry name under a CLI's real home, for `linkFromRealHome`: single path segment,
* leading alphanumeric, no traversal or hidden-dot escape. */
const homeSegmentName = z
. string ()
. min ( 1 )
. max ( 40 )
. regex ( /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/ );
2026-09-02 08:26:45 +08:00
const capabilitiesSchema = z
. object ({
external : z.boolean (),
requiresMux : z.boolean (),
hooks : z.enum ([ 'none' , 'always' , 'supervised' ]),
transcript : z.enum ([ 'claude-jsonl' , 'codex-rollout' , 'deepseek-zstd' , 'omp-jsonl' , 'none' ]),
2026-10-08 14:55:02 +02:00
altScreen : z.enum ([ 'strip-full' , 'strip-mux-only' , 'strip-mux-and-mouse' , 'preserve' ]),
2026-09-02 08:26:45 +08:00
echo : echoSchema ,
wheelForward : z
2026-10-17 04:42:06 +08:00
. object ({ mode : z.enum ([ 'never' , 'version-gated' , 'always' ]), minVersion : z.string (). max ( 20 ). optional () })
2026-09-02 08:26:45 +08:00
. strict (),
2026-10-03 17:59:30 -04:00
// Whether a hollow pane's wheel/touch scroll may be turned into PageUp/PageDown for
// the CLI to page its own transcript. Distinct from wheelForward (SGR reports).
// Optional: absent means no paging, the safe default for an unmeasured CLI.
transcriptPageKeys : z.boolean (). optional (),
2026-10-24 19:26:36 -04:00
// Keep the PTY's rows while a phone keyboard is up (inline renderers only).
// Optional: absent means the keyboard resizes, the safe default.
keyboardHold : z.literal ( 'inline' ). optional (),
2026-09-02 08:26:45 +08:00
keyboardAccessory : z.enum ([ 'agent' , 'shell' ]),
privilegedCommandGate : z.boolean (),
startMode : z.enum ([ 'interactive' , 'shell' ]),
stripInkBloat : z.boolean (),
ralph : z.boolean (),
respawn : z.boolean (),
effort : z.boolean (),
agentSkillInjection : z.boolean (),
2026-10-11 07:10:41 +02:00
// A closed list on purpose: it decides where the server WRITES, and this file is
// user-editable, so it can never be a free path (`..`, absolute).
agentSkillDir : z.enum ( AGENT_SKILL_DIRS ). optional (),
2026-09-02 08:26:45 +08:00
statusLineTelemetry : z.boolean (),
2026-09-22 08:15:57 +02:00
// How many columns this CLI indents its transcript body by, so a copy can take
// that much off the clipboard. Bounded, because it is the whole strip: a copy
// never removes more than this, nor more than every selected line shares.
//
// ⚠ DECLARED, not measured off the pane, and two measured attempts are why.
// Asking whether the pane painted spaces across the unused part of each row
// separates a TUI from a shell perfectly where it fires and never
// over-stripped, but it is a function of pane WIDTH: that padding exists
// only while a rendered line stops short of the CLI's own layout width, and
// Claude Code's prose wraps to fill it — the share of padded rows on one
// live transcript ran 44%, 6%, 6%, 7% and 87% at 123, 160, 198, 235 and 298
// columns, so the strip did nothing at any ordinary size. Taking the
// narrowest indent on screen instead fires everywhere and over-strips, since
// a file listing inside the transcript can be the narrowest thing on it.
// A declared width cannot do either. Absent means no strip, so a CLI whose
// transcript layout nobody has measured is never touched.
transcriptGutter : z.number (). int (). min ( 1 ). max ( 8 ). optional (),
2026-10-08 15:00:29 +02:00
// Literal text matched by a `wait-output` long-poll, never compiled as a regex.
composerReadyMark : z.string (). min ( 1 ). max ( 64 ). optional (),
2026-09-06 17:41:01 +02:00
workDetect : z
. object ({
promptGlyph : z.string (). min ( 1 ). max ( 8 ),
2026-09-07 22:42:20 +02:00
// Config-supplied regex, so it goes through the same guard as `version.regex`:
// ~/.codeman/clis.json can set this, and the compiled pattern runs on the PTY
// hot path, where a nested quantifier would be a ReDoS against the event loop.
// A broken pattern must also fail at LOAD time rather than inside a data handler.
2026-09-06 17:41:01 +02:00
workingLine : z
. string ()
. min ( 1 )
2026-09-07 22:42:20 +02:00
. refine (
( src ) => compileVersionRegex ( src ) !== null ,
'workingLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
),
2026-09-21 18:00:30 +02:00
// Same guard, same reasons: this one runs over the foot of a pane capture every
// time a session settles, and ~/.codeman/clis.json can set it.
watchingLine : z
. string ()
. min ( 1 )
. refine (
( src ) => compileVersionRegex ( src ) !== null ,
'watchingLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
)
. optional (),
2026-09-22 08:58:52 +02:00
// Bounded hard: this is how far up the screen a config file may push the search,
// and every row it adds is one more row the agent itself may be able to write.
watchingLines : z.number (). int (). min ( 1 ). max ( 8 ). optional (),
2026-09-28 16:18:27 +02:00
// Same guard again: tested against a pane row every time a session settles.
awaitingLine : z
. string ()
. min ( 1 )
. refine (
( src ) => compileVersionRegex ( src ) !== null ,
'awaitingLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
)
. optional (),
2026-10-14 05:18:24 +02:00
// Same guard again: run over the foot of a pane capture every time a session
// settles and on a timer while a dialog is up, and ~/.codeman/clis.json can set it.
blockedLine : z
. string ()
. min ( 1 )
. refine (
( src ) => compileVersionRegex ( src ) !== null ,
'blockedLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
)
. optional (),
// Wider than `watchingLines` because a dialog's options wrap at narrow widths (codex
// needs 20 at 36 columns). That is safe only for a pattern that ends on the dialog's
// own footer: the rows above it, which the agent may write, can then supply a
// marker but never the footer. Still bounded, since it is also how much text the
// pattern runs over.
blockedLines : z.number (). int (). min ( 1 ). max ( 24 ). optional (),
2026-10-24 22:54:17 -04:00
// Same guard again: run over the rows under the composer each time guarded
// input reads the pane, and ~/.codeman/clis.json can set it.
composerFooterLine : z
. string ()
. min ( 1 )
. refine (
( src ) => compileVersionRegex ( src ) !== null ,
'composerFooterLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
)
. optional (),
2026-10-25 09:22:35 -04:00
// Same guard again: run over the rows just above the composer by the same reads.
composerPopupLine : z
. string ()
. min ( 1 )
. refine (
( src ) => compileVersionRegex ( src ) !== null ,
'composerPopupLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
)
. optional (),
// Single ASCII punctuation characters, never letters, digits or whitespace: each one
// refuses every message that starts (or whose last word starts) with it.
composerCommandPrefixes : z
. string ()
. regex ( /^[!-/:-@[-`{-~]{1,8}$/ , 'composerCommandPrefixes must be 1 to 8 ASCII punctuation characters' )
. optional (),
composerCompletionSigils : z
. string ()
. regex ( /^[!-/:-@[-`{-~]{1,8}$/ , 'composerCompletionSigils must be 1 to 8 ASCII punctuation characters' )
. optional (),
2026-09-06 17:41:01 +02:00
})
. strict ()
2026-09-22 17:11:33 +02:00
// A window with nothing to search is a typo, not a configuration. Refused at LOAD
// time for the same reason `privilegedParams[].param` is checked against the params
// the entry declares: the failure is otherwise silent and looks like a feature that
// simply never fires.
. refine (
( v ) => v . watchingLines === undefined || v . watchingLine !== undefined ,
'watchingLines has nothing to bound without a watchingLine'
)
2026-10-14 05:18:24 +02:00
. refine (
( v ) => v . blockedLines === undefined || v . blockedLine !== undefined ,
'blockedLines has nothing to bound without a blockedLine'
)
2026-09-06 17:41:01 +02:00
. optional (),
2026-09-02 08:26:45 +08:00
model : z
. object ({ source : z.enum ([ 'flag' , 'claude-settings-file' , 'none' ]), param : z.string (). optional () })
. strict (),
2026-10-07 12:22:45 +02:00
// Same guard as the workDetect patterns: ~/.codeman/clis.json can set it, and it runs
// over the foot of a pane capture every time a session settles. Exactly one capture
// group (the model), checked here so a pattern without one fails at LOAD time instead
// of silently never naming a model.
modelDetect : z
. object ({
screenLine : z
. string ()
. min ( 1 )
. refine (
( src ) => compileVersionRegex ( src ) !== null && countCaptureGroups ( src ) === 1 ,
'screenLine must be a regex compileVersionRegex() accepts (at most 200 characters, no nested quantifiers) with exactly one capture group'
2026-10-07 19:41:56 +02:00
)
. optional (),
2026-10-07 12:22:45 +02:00
// Bounded hard, like watchingLines: every row it adds is one more row the agent
2026-10-09 03:11:35 +02:00
// itself may be able to write. 8 is the reader's own cap (readScreenModel); a
// window taller than the CLI's footer needs a pattern only that CLI's chrome can
// satisfy at its position, as opencode's does by taking the LAST composer row.
screenLines : z.number (). int (). min ( 1 ). max ( 8 ). optional (),
2026-10-07 21:16:53 +02:00
// Single tokens, bounded: each is compared against one captured field.
rejectWords : z.array ( z . string (). min ( 1 ). max ( 40 ). regex ( /^\S+$/ )). max ( 32 ). optional (),
2026-10-07 19:41:56 +02:00
// A NAMED reader (src/model-config-resolvers.ts), never code in config.
configResolver : z.enum ([ 'deepseek-route' ] as const satisfies readonly ModelConfigResolverName []). optional (),
2026-10-07 12:22:45 +02:00
})
. strict ()
2026-10-07 19:41:56 +02:00
// Typos rather than configurations, refused at LOAD time like watchingLines.
. refine (
( v ) => v . screenLine !== undefined || v . configResolver !== undefined ,
'modelDetect declares nothing to read'
)
. refine (
( v ) => v . screenLines === undefined || v . screenLine !== undefined ,
'screenLines has nothing to bound without a screenLine'
)
2026-10-07 21:16:53 +02:00
. refine (
( v ) => v . rejectWords === undefined || v . screenLine !== undefined ,
'rejectWords has nothing to filter without a screenLine'
)
2026-10-07 12:22:45 +02:00
. optional (),
2026-10-09 09:35:56 +02:00
// Launch param -> synced App Settings key. The values are a closed enum, like
// configResolver: a clis.json override names one of the settings this build knows
// how to validate, never an arbitrary key. Params are checked against the declared
// ones in the superRefine below.
launchDefaults : z
. record (
z . string (),
z . enum ([ 'codexModel' , 'codexReasoningEffort' ] as const satisfies readonly LaunchDefaultSettingKey [])
)
. refine (( v ) => Object . keys ( v ). length >= 1 && Object . keys ( v ). length <= 8 , 'launchDefaults takes 1 to 8 params' )
. optional (),
2026-09-02 08:26:45 +08:00
privilegedParams : z
. array (
z
. object ({
param : z.string (),
clampTo : z.union ([ z . boolean (), z . string ()]),
materializeWhenAbsent : z.boolean (). optional (),
})
. strict ()
)
. max ( 8 ),
// Exact env var NAMES, not prefixes: this list is a targeted deny, and a prefix here
2026-10-16 01:48:37 +02:00
// would let one entry silently strip a whole namespace off every owner's overrides. The
// bound is generous because a longer list only takes more away from non-granted owners:
// copilot's COPILOT_ prefix covers dozens of variables that run code or redirect its token.
privilegedEnvKeys : z.array ( envName ). max ( 48 ),
2026-09-02 08:26:45 +08:00
gates : z.record ( z . string (), z . object ({ minVersion : z.string (). max ( 20 ), failClosed : z.boolean () }). strict ()),
maxFrameBytes : z.number (). int (). positive (). optional (),
2026-10-02 21:53:31 +08:00
newline : z.enum ([ 'line-feed' , 'esc-enter' ]). optional (),
2026-10-02 18:01:12 +08:00
mcpConfig : z
. object ({
// Home-relative, no traversal: sync writes to this path.
2026-10-04 23:43:36 +02:00
path : mcpRelativePath ,
2026-10-13 18:28:34 +02:00
// Home-relative fallback used when `path` is absent. Same no-traversal rule as `path`:
// sync reads it and, when it parses as plain JSON, writes to it.
2026-10-11 00:28:44 +08:00
altPath : mcpRelativePath.optional (),
2026-10-02 21:15:31 +08:00
// Every value must be a known McpConfigFormat (types.ts); mcp-sync.ts's dialect table is
// keyed by the same type, so an adapter-less format fails to compile there.
format : z.enum ([
'claude-json' ,
'gemini-json' ,
'codex-toml' ,
'opencode-json' ,
'antigravity-json' ,
2026-10-09 16:13:48 +08:00
'copilot-json' ,
2026-10-02 21:15:31 +08:00
] as const satisfies readonly McpConfigFormat []),
2026-10-04 23:43:36 +02:00
// The env var the CLI reads to move the file, and the path under it (same no-traversal
// rule: sync writes there too). Resolved from the server env at call time, never here.
relocation : z.object ({ envVar : envName , path : mcpRelativePath }). strict (). optional (),
2026-10-02 18:01:12 +08:00
})
. strict ()
. optional (),
2026-09-05 21:26:04 +08:00
customModelInjection : z.discriminatedUnion ( 'kind' , [
z
. object ({
kind : z.literal ( 'env' ),
baseUrlVar : envName ,
apiKeyVar : envName ,
// Empty is valid: deepseek's model routing is a profile-composition concern, not
// an env var, so it declares baseUrl/apiKey injection with no model var at all.
modelVars : z.array ( envName ). max ( 8 ),
2026-09-14 23:45:42 +02:00
launchModel : launchModelTemplate ,
2026-09-16 12:08:26 +08:00
// Optional: the env var to carry a discovered per-model context-window size
// (claude's CLAUDE_CODE_MAX_CONTEXT_TOKENS), and/or the env var that isolates
// this session's config/credential directory from the user's real one (claude's
// CLAUDE_CONFIG_DIR) so an injected API key never collides with a stored OAuth
// session. See the customModelInjection doc comment in cli-registry/types.ts.
contextLengthVar : envName.optional (),
configDirVar : envName.optional (),
2026-09-16 13:08:07 +08:00
// Relative path, WITHIN the isolated configDirVar directory, of a trust-dialog
// seed file the CLI itself owns the shape of — claude's `.claude.json`
// `customApiKeyResponses.approved` list, the same field an interactive "Detected
// a custom API key — use it?" prompt writes to on a real terminal. Only makes
// sense alongside configDirVar (an isolated, otherwise-empty directory has none
// of a real profile's prior approvals), and only implemented for the
// 'claude-api-key-responses' shape today — see custom-model-injection-apply.ts.
apiKeyTrustFile : z
. object ({ relPath : z.string (). min ( 1 ). max ( 80 ), shape : z.literal ( 'claude-api-key-responses' ) })
. strict ()
. optional (),
2026-09-17 09:21:36 +08:00
// An isolated config directory replays the CLI's whole first-run sequence (theme
// picker, security notes, per-project trust dialog, bypass-permissions warning)
// on every launch, same root cause as apiKeyTrustFile above — this reuses that
// same file to pre-seed the state a real, already-onboarded profile carries. See
// the customModelInjection doc comment in cli-registry/types.ts.
skipFirstRunPrompts : z.boolean (). optional (),
2026-09-17 13:41:19 +08:00
// DeepSeek-only, confirmed by reading its own bundled SDK source: it concatenates
// "/chat/completions" onto baseUrlVar's value with no "/v1" of its own, while
// llama-swap/llama.cpp only serves the "/v1/..." path — claude/gemini must NOT
// get this. See the customModelInjection doc comment in cli-registry/types.ts.
appendV1Suffix : z.boolean (). optional (),
2026-09-05 21:26:04 +08:00
})
. strict (),
z
. object ({
kind : z.literal ( 'configContentEnv' ),
envVar : envName ,
template : z.literal ( 'opencode-json' ),
2026-09-14 23:45:42 +02:00
launchModel : launchModelTemplate ,
2026-09-05 21:26:04 +08:00
})
. strict (),
z
. object ({
kind : z.literal ( 'configDir' ),
dirEnvVar : envName ,
fileName : z.string (). min ( 1 ). max ( 80 ),
2026-11-01 21:29:31 +08:00
template : z.enum ([ 'codex-toml' , 'pi-models-json' , 'omp-models-yml' , 'grok-toml' , 'deepseek-patch-json' ]),
2026-09-14 23:45:42 +02:00
launchModel : launchModelTemplate ,
2026-11-01 21:34:37 +08:00
// State that must survive the isolated-directory redirect, symlinked by name from
// the CLI's real home (deepseek: profiles/sessions/settings.yaml). Single path
// segments only — the consumer joins them, so a traversal here would escape the
// real home. See the field's comment in cli-registry/types.ts.
linkFromRealHome : z.array ( homeSegmentName ). max ( 8 ). optional (),
2026-11-02 14:06:56 +08:00
// Which of `linkFromRealHome` are directories (missing ones are created before
// linking; missing files are skipped). Same segment pattern, see types.ts.
linkFromRealHomeDirs : z.array ( homeSegmentName ). max ( 8 ). optional (),
// The real home's fallback location, relative to the user's home: ONE segment —
2026-11-02 15:50:45 +08:00
// a leading dot is legitimate (`.dsh` is what ships) but separators, `..` and
// bare `.` are not; the consumer joins it under the user's home, a traversal
// here escapes that home and `.` IS that home (linking THROUGH it unshielded).
2026-11-02 14:06:56 +08:00
realHomeFallback : z
. string ()
. min ( 1 )
. max ( 80 )
2026-11-02 15:50:45 +08:00
. regex ( /^(?!\.\.?$)[^/\\]+$/ )
2026-11-02 14:06:56 +08:00
. optional (),
2026-09-05 21:26:04 +08:00
})
2026-11-02 14:06:56 +08:00
. strict ()
. superRefine (( recipe , ctx ) => {
// Both rules were comments before; the schema is the security boundary, so
// enforce them at load time (see the header of this file).
if ( recipe . linkFromRealHome ? . length && ! recipe . realHomeFallback ) {
ctx . addIssue ({
code : 'custom' ,
message : 'realHomeFallback is required whenever linkFromRealHome is declared' ,
path : [ 'realHomeFallback' ],
});
}
for ( const name of recipe . linkFromRealHome ?? []) {
if ( name === recipe . fileName ) {
ctx . addIssue ({
code : 'custom' ,
message : `linkFromRealHome must never include fileName ( ${ JSON . stringify ( name ) } ): the generated file owns that name in the isolated directory, a link there would write THROUGH into the user's real file` ,
path : [ 'linkFromRealHome' ],
});
}
}
2026-11-02 15:50:45 +08:00
// types.ts documents the dirs list as "must be a subset of linkFromRealHome";
// a name absent from it names nothing (missing-file entries are skipped as
// files), so the recipe would silently stop creating a directory it declares.
const linkedNames = new Set ( recipe . linkFromRealHome ?? []);
for ( const dir of recipe . linkFromRealHomeDirs ?? []) {
if ( ! linkedNames . has ( dir )) {
ctx . addIssue ({
code : 'custom' ,
message : `linkFromRealHomeDirs must be a subset of linkFromRealHome: ${ JSON . stringify ( dir ) } is not linked, so the directory rule for it can never apply` ,
path : [ 'linkFromRealHomeDirs' ],
});
}
}
2026-11-02 14:06:56 +08:00
}),
2026-09-05 21:26:04 +08:00
z . object ({ kind : z.literal ( 'unsupported' ) }). strict (),
]),
2026-09-02 08:26:45 +08:00
})
. strict ();
const credStoreSchema = z
. object ({
rel : z.string (). min ( 1 ). max ( 100 ),
shareDirs : z.array ( z . string (). max ( 100 )). optional (),
shareFiles : z.array ( z . string (). max ( 100 )). optional (),
seedFiles : z.array ( z . string (). max ( 100 )). optional (),
seedWhole : z.boolean (). optional (),
})
. strict ();
/**
* A remote/docker default pane command: space-separated bare words from the SAME safe
* charset as `shellToken` (no shell metacharacters), so `claude --dangerously-skip-permissions`
* is expressible while still excluding `;`, `|`, `$`, backticks and quotes — this is not an
* escape hatch into arbitrary shell text, it is one bare command plus bare flags.
*/
const commandLine = z
. string ()
. min ( 1 )
. max ( 200 )
. regex (
/^[A-Za-z0-9._:@=+/,-]+( [A-Za-z0-9._:@=+/,-]+)*$/ ,
'must be space-separated bare words with no shell metacharacters'
);
const overlayTargetSchema = z . union ([
2026-09-05 16:21:51 +02:00
z . object ({ command : commandLine.optional (), rootCommand : commandLine.optional () }). strict (),
2026-09-02 08:26:45 +08:00
z . object ({ disabled : z.literal ( true ) }). strict (),
]);
const overlaysSchema = z
. object ({
remote : overlayTargetSchema.optional (),
docker : overlayTargetSchema.optional (),
credStore : credStoreSchema.optional (),
})
. strict ();
export const CliEntrySchema = z
. object ({
id : cliId ,
label : z.string (). min ( 1 ). max ( 60 ),
shortBadge : z.string (). min ( 1 ). max ( 6 ),
accent : z.string (). regex ( /^#[0-9a-fA-F]{6}$/ , 'accent must be a 6-digit hex colour' ),
enabled : z.boolean (),
stock : z.boolean (),
order : z.number (). int (),
kind : z.enum ([ 'agent' , 'shell' ]),
discovery : discoverySchema ,
launch : launchSchema ,
env : envSchema ,
capabilities : capabilitiesSchema ,
overlays : overlaysSchema ,
})
. strict ()
. superRefine (( entry , ctx ) => {
const gateNames = new Set ( Object . keys ( entry . capabilities . gates ));
const walkConds = ( cond : import ( './types.js' ). Cond | undefined ) => {
if ( ! cond ) return ;
if ( 'capabilityGate' in cond && ! gateNames . has ( cond . capabilityGate )) {
ctx . addIssue ({
code : 'custom' ,
message : `capabilityGate " ${ cond . capabilityGate } " is not declared in capabilities.gates` ,
});
}
if ( 'allOf' in cond ) cond . allOf . forEach ( walkConds );
if ( 'anyOf' in cond ) cond . anyOf . forEach ( walkConds );
if ( 'not' in cond ) walkConds ( cond . not );
};
for ( const variant of entry . launch . variants ) {
walkConds ( variant . when );
for ( const arg of variant . args ) walkConds ( arg . when );
}
// Reject a profile name this build does not implement, rather than letting it fail
// closed at use time. An unimplemented `launcherProfile` would make the CLI look
// permanently uninstalled, and an unimplemented `setenvProfile` would silently skip
// setup the CLI needs; both are far easier to diagnose as a load-time error naming the
// field. (`echo.predictProfile` is deliberately NOT checked here — see profiles.ts.)
const { launcherProfile } = entry . discovery ;
if ( launcherProfile !== undefined && ! isKnownLauncherProfile ( launcherProfile )) {
ctx . addIssue ({
code : 'custom' ,
message : `discovery.launcherProfile " ${ launcherProfile } " is not a profile this build implements` ,
path : [ 'discovery' , 'launcherProfile' ],
});
}
// An env var exported from a param that does not exist would silently export nothing,
// and for DSH_PERMISSION_MODE that means silently losing a permission clamp.
const declaredParams = new Set ( Object . keys ( entry . launch . params ));
entry . env . configSetenv ? . forEach (( mapping , i ) => {
if ( ! declaredParams . has ( mapping . fromParam )) {
ctx . addIssue ({
code : 'custom' ,
message : `configSetenv fromParam " ${ mapping . fromParam } " is not a declared launch param` ,
path : [ 'env' , 'configSetenv' , i , 'fromParam' ],
});
}
});
// Same class of silent failure on the OTHER privileged surface, and this one is a
// security control: `privilegedParams[].param` is the multi-user bypass clamp's only
// handle on a CLI's privilege switch, and a name that is not a declared param clamps
// NOTHING — no load error, no failing test, the clamp simply stops running. The clamp
// resolves the name through `legacyConfigAliases`, so this check is what keeps the two
// in ONE namespace rather than two that merely coincide today: they do not for codex
// (`bypassApprovals` vs `dangerouslyBypassApprovals`), and giving deepseek's
// `permissionMode` an alias later would otherwise have removed its clamp with nothing
// saying so.
entry . capabilities . privilegedParams . forEach (( clamp , i ) => {
if ( ! declaredParams . has ( clamp . param )) {
ctx . addIssue ({
code : 'custom' ,
message : `privilegedParams param " ${ clamp . param } " is not a declared launch param` ,
path : [ 'capabilities' , 'privilegedParams' , i , 'param' ],
});
}
});
2026-10-09 09:35:56 +02:00
// Same silent-no-op class again: a launch default for a param the entry never declared
// would be filled into the config object and then read by nothing. And without a
// `legacyConfigField` the entry's params are read off the request body itself, where a
// filled `model` would be a different field (claude's per-session one), so refuse it.
const { launchDefaults } = entry . capabilities ;
if ( launchDefaults !== undefined ) {
if ( entry . launch . legacyConfigField === undefined ) {
ctx . addIssue ({
code : 'custom' ,
message : 'launchDefaults needs launch.legacyConfigField to fill' ,
path : [ 'capabilities' , 'launchDefaults' ],
});
}
for ( const param of Object . keys ( launchDefaults )) {
if ( ! declaredParams . has ( param )) {
ctx . addIssue ({
code : 'custom' ,
message : `launchDefaults param " ${ param } " is not a declared launch param` ,
path : [ 'capabilities' , 'launchDefaults' , param ],
});
}
}
}
2026-09-02 08:26:45 +08:00
const { setenvProfile } = entry . env ;
if ( setenvProfile !== undefined && ! isKnownSetenvProfile ( setenvProfile )) {
ctx . addIssue ({
code : 'custom' ,
message : `env.setenvProfile " ${ setenvProfile } " is not a profile this build implements` ,
path : [ 'env' , 'setenvProfile' ],
});
}
});
export type ValidatedCliEntry = z . infer < typeof CliEntrySchema >;