mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
chore(lint): replace ESLint with Oxlint and clear anti-slop findings
This commit is contained in:
1 parent
c6c13335e5
commit
b625acfc0c
1083 files changed
+67089
-80136
No files matched your search
@@ -8,7 +8,6 @@ try {
|
||||
const { config } = await import('dotenv')
|
||||
config({ path: path.resolve(process.cwd(), '.env') })
|
||||
} catch {
|
||||
// dotenv not available (e.g., in production Docker), env vars already set
|
||||
}
|
||||
|
||||
const getEnvString = (key: string, defaultValue: string): string => {
|
||||
@@ -170,13 +169,14 @@ export const getOpenCodeConfigFilePath = () => path.join(ENV.WORKSPACE.BASE_PATH
|
||||
export const getAgentsMdPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR, 'AGENTS.md')
|
||||
export const getDatabasePath = () => ENV.DATABASE.PATH
|
||||
|
||||
export const getTrustedOrigins = (): string[] =>
|
||||
ENV.AUTH.TRUSTED_ORIGINS
|
||||
export const parseTrustedOrigins = (configured: string): string[] =>
|
||||
configured
|
||||
.split(',')
|
||||
.map((origin) => origin.trim())
|
||||
.filter((origin) => origin.length > 0)
|
||||
|
||||
/** Reports whether a request Origin is one of the configured trusted origins. */
|
||||
export const getTrustedOrigins = (): string[] => parseTrustedOrigins(ENV.AUTH.TRUSTED_ORIGINS)
|
||||
|
||||
export const isTrustedOrigin = (
|
||||
origin: string | undefined,
|
||||
options: { requireOrigin?: boolean } = {},
|
||||
|
||||
@@ -2,8 +2,10 @@ import { OPENCODE_CONFIG_SOURCE_NAMES, type OpenCodeConfigSourceName } from './d
|
||||
|
||||
export const DEFAULT_OPENCODE_CONFIG_SOURCE_NAME: OpenCodeConfigSourceName = 'opencode.jsonc'
|
||||
|
||||
const OPENCODE_CONFIG_SOURCE_NAME_SET: ReadonlySet<string> = new Set(OPENCODE_CONFIG_SOURCE_NAMES)
|
||||
|
||||
export function isOpenCodeConfigSourceName(value: string): value is OpenCodeConfigSourceName {
|
||||
return (OPENCODE_CONFIG_SOURCE_NAMES as readonly string[]).includes(value)
|
||||
return OPENCODE_CONFIG_SOURCE_NAME_SET.has(value)
|
||||
}
|
||||
|
||||
export function selectPreferredOpenCodeConfigSourceName(
|
||||
|
||||
@@ -1,58 +1,53 @@
|
||||
import { z } from 'zod'
|
||||
import type { GoalState, GoalStatus } from '../opencode/goal'
|
||||
import type { MultiRunEntryStatus } from '../schemas/multi-runs'
|
||||
import type { JsonObject, JsonValue } from '../utils/json'
|
||||
import { JsonObjectSchema } from '../utils/json'
|
||||
|
||||
const MULTI_RUN_ENTRY_STATUS_LABELS: Record<MultiRunEntryStatus, string> = {
|
||||
const MULTI_RUN_ENTRY_STATUS_LABELS = {
|
||||
starting: 'Starting',
|
||||
started: 'Started',
|
||||
failed: 'Failed',
|
||||
discarded: 'Discarded',
|
||||
}
|
||||
} satisfies Record<MultiRunEntryStatus, string>
|
||||
|
||||
export function getMultiRunEntryStatusLabel(status: MultiRunEntryStatus): string {
|
||||
return MULTI_RUN_ENTRY_STATUS_LABELS[status]
|
||||
}
|
||||
|
||||
const GOAL_STATUS_TITLES: Record<GoalStatus, string> = {
|
||||
const GOAL_STATUS_TITLES = {
|
||||
active: 'Goal active',
|
||||
paused: 'Goal paused',
|
||||
complete: 'Goal completed',
|
||||
}
|
||||
} satisfies Record<GoalStatus, string>
|
||||
|
||||
/** Titles a notification for the current state of an OpenCode goal. */
|
||||
export function getGoalStatusTitle(status: GoalStatus): string {
|
||||
return GOAL_STATUS_TITLES[status]
|
||||
}
|
||||
|
||||
/** Labels the continuation progress of an OpenCode goal. */
|
||||
export function getGoalRoundsLabel(goal: Pick<GoalState, 'rounds' | 'maxRounds'>): string {
|
||||
return `Round ${goal.rounds}/${goal.maxRounds}`
|
||||
}
|
||||
|
||||
const PERMISSION_LABELS: Record<string, string> = {
|
||||
read: 'Read File',
|
||||
edit: 'Edit File',
|
||||
glob: 'Search Files',
|
||||
grep: 'Search Content',
|
||||
shell: 'Run Command',
|
||||
subagent: 'Run Subagent',
|
||||
external_directory: 'External Access',
|
||||
question: 'Ask Question',
|
||||
webfetch: 'Fetch URL',
|
||||
websearch: 'Web Search',
|
||||
skill: 'Use Skill',
|
||||
}
|
||||
const PERMISSION_LABELS = new Map<string, string>([
|
||||
['read', 'Read File'],
|
||||
['edit', 'Edit File'],
|
||||
['glob', 'Search Files'],
|
||||
['grep', 'Search Content'],
|
||||
['shell', 'Run Command'],
|
||||
['subagent', 'Run Subagent'],
|
||||
['external_directory', 'External Access'],
|
||||
['question', 'Ask Question'],
|
||||
['webfetch', 'Fetch URL'],
|
||||
['websearch', 'Web Search'],
|
||||
['skill', 'Use Skill'],
|
||||
])
|
||||
|
||||
export function getPermissionLabel(permission: string): string {
|
||||
if (!permission) return 'Approval'
|
||||
return PERMISSION_LABELS[permission] ?? permission.charAt(0).toUpperCase() + permission.slice(1)
|
||||
return PERMISSION_LABELS.get(permission) ?? permission.charAt(0).toUpperCase() + permission.slice(1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a permission action as a lowercase mid-sentence phrase, preserving acronyms.
|
||||
*
|
||||
* Use inside sentences such as `Allow ${getPermissionPhrase(action)}?` so the human
|
||||
* label reads naturally instead of lowercasing the whole label.
|
||||
*/
|
||||
export function getPermissionPhrase(action: string): string {
|
||||
return getPermissionLabel(action)
|
||||
.split(' ')
|
||||
@@ -60,11 +55,11 @@ export function getPermissionPhrase(action: string): string {
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
interface PermissionLike {
|
||||
action?: unknown
|
||||
metadata?: unknown
|
||||
resources?: unknown
|
||||
save?: unknown
|
||||
export interface PermissionLike {
|
||||
action?: string
|
||||
metadata?: Record<string, JsonValue>
|
||||
resources?: string[]
|
||||
save?: string[]
|
||||
}
|
||||
|
||||
export interface PermissionDetail {
|
||||
@@ -73,50 +68,70 @@ export interface PermissionDetail {
|
||||
label?: string
|
||||
}
|
||||
|
||||
const PERMISSION_RESOURCE_LABELS: Record<string, { one: string; many: string }> = {
|
||||
shell: { one: 'Command', many: 'Commands' },
|
||||
glob: { one: 'Pattern', many: 'Patterns' },
|
||||
grep: { one: 'Pattern', many: 'Patterns' },
|
||||
read: { one: 'Path', many: 'Paths' },
|
||||
list: { one: 'Path', many: 'Paths' },
|
||||
edit: { one: 'File', many: 'Files' },
|
||||
external_directory: { one: 'Path', many: 'Paths' },
|
||||
webfetch: { one: 'URL', many: 'URLs' },
|
||||
interface PermissionResourceLabels {
|
||||
one: string
|
||||
many: string
|
||||
}
|
||||
|
||||
const PERMISSION_RESOURCE_LABELS = new Map<string, PermissionResourceLabels>([
|
||||
['shell', { one: 'Command', many: 'Commands' }],
|
||||
['glob', { one: 'Pattern', many: 'Patterns' }],
|
||||
['grep', { one: 'Pattern', many: 'Patterns' }],
|
||||
['read', { one: 'Path', many: 'Paths' }],
|
||||
['list', { one: 'Path', many: 'Paths' }],
|
||||
['edit', { one: 'File', many: 'Files' }],
|
||||
['external_directory', { one: 'Path', many: 'Paths' }],
|
||||
['webfetch', { one: 'URL', many: 'URLs' }],
|
||||
])
|
||||
|
||||
const DEFAULT_PERMISSION_RESOURCE_LABELS: PermissionResourceLabels = { one: 'Resource', many: 'Resources' }
|
||||
|
||||
function getPermissionResourceLabel(action: string, count: number): string {
|
||||
const labels = PERMISSION_RESOURCE_LABELS[action] ?? { one: 'Resource', many: 'Resources' }
|
||||
const labels = PERMISSION_RESOURCE_LABELS.get(action) ?? DEFAULT_PERMISSION_RESOURCE_LABELS
|
||||
return count > 1 ? labels.many : labels.one
|
||||
}
|
||||
|
||||
export function getPermissionDetail(input: PermissionLike): PermissionDetail {
|
||||
const action = typeof input.action === 'string' ? input.action : ''
|
||||
const metadata = (input.metadata && typeof input.metadata === 'object' ? input.metadata : {}) as Record<string, unknown>
|
||||
const resources = Array.isArray(input.resources) ? input.resources.filter((resource): resource is string => typeof resource === 'string') : []
|
||||
const str = (v: unknown): string | undefined => (typeof v === 'string' && v.length > 0 ? v : undefined)
|
||||
const PermissionFileSchema = z.object({
|
||||
file: z.string().optional(),
|
||||
patch: z.string().optional(),
|
||||
})
|
||||
|
||||
switch (action) {
|
||||
case 'edit': {
|
||||
const files = Array.isArray(metadata.files) ? metadata.files : []
|
||||
const first = (files[0] && typeof files[0] === 'object' ? files[0] : {}) as Record<string, unknown>
|
||||
const filePath = str(first.file) ?? str(metadata.filepath)
|
||||
if (filePath) {
|
||||
const diff = str(first.patch) ?? str(metadata.diff)
|
||||
return {
|
||||
primary: filePath,
|
||||
secondary: diff ? diff.slice(0, 500) + (diff.length > 500 ? '\n...' : '') : undefined,
|
||||
label: getPermissionResourceLabel('edit', 1),
|
||||
}
|
||||
const PermissionFileListSchema = z.array(PermissionFileSchema)
|
||||
|
||||
function readNonEmptyString(value: JsonValue | undefined): string | undefined {
|
||||
const text = z.string().safeParse(value)
|
||||
return text.success && text.data.length > 0 ? text.data : undefined
|
||||
}
|
||||
|
||||
function readJsonObject(value: JsonValue | undefined): JsonObject {
|
||||
const object = JsonObjectSchema.safeParse(value)
|
||||
return object.success ? object.data : {}
|
||||
}
|
||||
|
||||
export function getPermissionDetail(input: PermissionLike): PermissionDetail {
|
||||
const action = input.action ?? ''
|
||||
const metadata = readJsonObject(input.metadata)
|
||||
const resources = input.resources ?? []
|
||||
|
||||
if (action === 'edit') {
|
||||
const files = PermissionFileListSchema.safeParse(metadata['files'])
|
||||
const firstFile = readJsonObject(files.success ? files.data[0] : undefined)
|
||||
const filePath = readNonEmptyString(firstFile['file']) ?? readNonEmptyString(metadata['filepath'])
|
||||
if (filePath) {
|
||||
const diff = readNonEmptyString(firstFile['patch']) ?? readNonEmptyString(metadata['diff'])
|
||||
return {
|
||||
primary: filePath,
|
||||
secondary: diff ? diff.slice(0, 500) + (diff.length > 500 ? '\n...' : '') : undefined,
|
||||
label: getPermissionResourceLabel('edit', 1),
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'webfetch': {
|
||||
const url = str(metadata.url)
|
||||
if (url) return { primary: url, label: getPermissionResourceLabel('webfetch', 1) }
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (action === 'webfetch') {
|
||||
const url = readNonEmptyString(metadata['url'])
|
||||
if (url) return { primary: url, label: getPermissionResourceLabel('webfetch', 1) }
|
||||
}
|
||||
|
||||
return { primary: resources.join('\n'), label: getPermissionResourceLabel(action, resources.length) }
|
||||
}
|
||||
|
||||
@@ -126,19 +141,21 @@ export interface PermissionAlwaysScope {
|
||||
}
|
||||
|
||||
export function getPermissionAlwaysScope(input: PermissionLike): PermissionAlwaysScope | null {
|
||||
const action = typeof input.action === 'string' ? input.action : ''
|
||||
const save = Array.isArray(input.save) ? input.save.filter((item): item is string => typeof item === 'string') : []
|
||||
if (save.length === 0) return null
|
||||
if (save.length === 1 && save[0] === '*') {
|
||||
const action = input.action ?? ''
|
||||
const save = z.array(z.string()).safeParse(input.save)
|
||||
if (!save.success || save.data.length === 0) return null
|
||||
if (save.data.length === 1 && save.data[0] === '*') {
|
||||
return { summary: `This will always allow ${getPermissionPhrase(action)} for this project.`, patterns: [] }
|
||||
}
|
||||
return { summary: 'This will always allow the following patterns for this project.', patterns: save }
|
||||
return { summary: 'This will always allow the following patterns for this project.', patterns: save.data }
|
||||
}
|
||||
|
||||
interface FormLike {
|
||||
export interface FormLike {
|
||||
title?: unknown
|
||||
}
|
||||
|
||||
export function getFormText(form: FormLike | null | undefined): string {
|
||||
return form && typeof form.title === 'string' && form.title.length > 0 ? form.title : ''
|
||||
if (!form) return ''
|
||||
const title = z.string().safeParse(form.title)
|
||||
return title.success && title.data.length > 0 ? title.data : ''
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Info } from '@opencode/schema/config'
|
||||
import { Schema } from 'effect'
|
||||
import { z } from 'zod'
|
||||
import type { OpenCodeConfigValidationIssue } from '../types'
|
||||
import { isRecord } from '../utils/record'
|
||||
import { JsonObjectSchema, type JsonValue } from '../utils/json'
|
||||
|
||||
export type OpenCodeConfigValidationResult =
|
||||
| { success: true }
|
||||
@@ -14,31 +15,25 @@ const standardSchema = Schema.toStandardSchemaV1(Info, {
|
||||
const LEGACY_SKILLS_MESSAGE =
|
||||
'skills must be a list of skill paths. Replace the legacy `skills: { paths: [...] }` object with `skills: [...]`.'
|
||||
|
||||
/**
|
||||
* Renders a schema issue path as a dotted string, unwrapping the standard-schema key objects and
|
||||
* falling back to `root` for empty or missing paths.
|
||||
*/
|
||||
const IssuePathObjectSchema = z.object({ key: z.union([z.string(), z.number(), z.symbol()]) })
|
||||
|
||||
function toIssuePath(path: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined): string {
|
||||
if (!path || path.length === 0) return 'root'
|
||||
return path
|
||||
.map((segment) => String(typeof segment === 'object' ? segment.key : segment))
|
||||
.map((segment) => {
|
||||
const nested = IssuePathObjectSchema.safeParse(segment)
|
||||
return String(nested.success ? nested.data.key : segment)
|
||||
})
|
||||
.join('.')
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects the v1 `skills: { paths: [...] }` object form, which the v2 schema rejects and which
|
||||
* `validateOpenCodeConfig` rewrites with an actionable message.
|
||||
*/
|
||||
function hasLegacySkillsObject(value: unknown): boolean {
|
||||
return isRecord(value) && isRecord(value.skills)
|
||||
function hasLegacySkillsObject(value: JsonValue | undefined): boolean {
|
||||
const root = JsonObjectSchema.safeParse(value)
|
||||
if (!root.success) return false
|
||||
return JsonObjectSchema.safeParse(root.data.skills).success
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a parsed OpenCode config document against the v2 `Config.Info` schema, ignoring
|
||||
* unknown keys so v1-only fields in existing files stay loadable. A legacy v1 `skills` object
|
||||
* is reported with an actionable message naming the v2 list form.
|
||||
*/
|
||||
export function validateOpenCodeConfig(value: unknown): OpenCodeConfigValidationResult {
|
||||
export function validateOpenCodeConfig(value: JsonValue | undefined): OpenCodeConfigValidationResult {
|
||||
const result = standardSchema['~standard'].validate(value)
|
||||
if (result instanceof Promise) {
|
||||
throw new Error('OpenCode config validation must be synchronous')
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { ConfigEntry } from '@opencode/client'
|
||||
import { z } from 'zod'
|
||||
import { JsonObjectSchema, JsonValueSchema } from '../utils/json'
|
||||
|
||||
export type OpenCodeConfigInfo = Extract<ConfigEntry, { type: 'document' }>['info']
|
||||
|
||||
@@ -11,3 +13,212 @@ export type OpenCodeProviderConfig = NonNullable<OpenCodeConfigInfo['providers']
|
||||
export type OpenCodeProviderModelConfig = NonNullable<OpenCodeProviderConfig['models']>[string]
|
||||
|
||||
export type OpenCodePermissionRule = NonNullable<OpenCodeConfigInfo['permissions']>[number]
|
||||
|
||||
type ProviderSettings = NonNullable<OpenCodeProviderConfig['settings']>
|
||||
|
||||
type ProviderModelSettings = NonNullable<OpenCodeProviderModelConfig['settings']>
|
||||
|
||||
type ProviderModelCompatibility = NonNullable<OpenCodeProviderModelConfig['compatibility']>
|
||||
|
||||
type ProviderCompatibility = NonNullable<OpenCodeProviderConfig['compatibility']>
|
||||
|
||||
type ProviderModelCapabilities = NonNullable<OpenCodeProviderModelConfig['capabilities']>
|
||||
|
||||
type ProviderModelCost = NonNullable<OpenCodeProviderModelConfig['cost']>
|
||||
|
||||
type ProviderModelLimit = NonNullable<OpenCodeProviderModelConfig['limit']>
|
||||
|
||||
type ProviderModelVariant = NonNullable<OpenCodeProviderModelConfig['variants']>[number]
|
||||
|
||||
type ProviderModelVariantSettings = NonNullable<ProviderModelVariant['settings']>
|
||||
|
||||
const JsonValueOrNullSchema = z.union([JsonValueSchema, z.null()])
|
||||
|
||||
const modelRefSchema = z.object({
|
||||
providerID: z.string(),
|
||||
model: z.string(),
|
||||
variant: z.string().optional(),
|
||||
})
|
||||
|
||||
const modelRefOrStringSchema = z.union([z.string(), modelRefSchema])
|
||||
|
||||
const timeoutSchema = z.union([z.number(), z.literal(false)])
|
||||
|
||||
const providerCompactionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('summary') }),
|
||||
z.object({ type: z.literal('native') }),
|
||||
])
|
||||
|
||||
const providerCacheSchema = z.object({
|
||||
ttl: z.templateLiteral([z.number(), z.enum(['ms', 's', 'm', 'h', 'd'])]).optional(),
|
||||
})
|
||||
|
||||
const providerEncodingSchema = z.enum(['zstd', 'gzip', 'none'])
|
||||
|
||||
const providerSettingsSchema: z.ZodType<ProviderSettings> = z
|
||||
.object({
|
||||
timeout: timeoutSchema.optional(),
|
||||
headerTimeout: timeoutSchema.optional(),
|
||||
chunkTimeout: timeoutSchema.optional(),
|
||||
compaction: providerCompactionSchema.optional(),
|
||||
cache: providerCacheSchema.optional(),
|
||||
transport: z.enum(['http', 'websocket']).optional(),
|
||||
encoding: providerEncodingSchema.optional(),
|
||||
})
|
||||
.catchall(JsonValueOrNullSchema)
|
||||
|
||||
const providerModelSettingsSchema: z.ZodType<ProviderModelSettings> = z
|
||||
.object({
|
||||
compaction: providerCompactionSchema.optional(),
|
||||
cache: providerCacheSchema.optional(),
|
||||
encoding: providerEncodingSchema.optional(),
|
||||
})
|
||||
.catchall(JsonValueOrNullSchema)
|
||||
|
||||
const providerModelVariantSettingsSchema: z.ZodType<ProviderModelVariantSettings> = z
|
||||
.object({
|
||||
compaction: providerCompactionSchema.optional(),
|
||||
encoding: providerEncodingSchema.optional(),
|
||||
})
|
||||
.catchall(JsonValueOrNullSchema)
|
||||
|
||||
const providerCompatibilityFields = {
|
||||
reasoningField: z.string().optional(),
|
||||
requireReasoning: z.boolean().optional(),
|
||||
maxTokensField: z.enum(['max_completion_tokens', 'max_tokens']).optional(),
|
||||
requireFinishReason: z.boolean().optional(),
|
||||
requireAssistantAfterTool: z.boolean().optional(),
|
||||
supportsPromptCacheKey: z.boolean().optional(),
|
||||
streamUsage: z.boolean().optional(),
|
||||
cacheFormat: z.enum(['anthropic', 'alibaba']).optional(),
|
||||
mediaInput: z.enum(['assets', 'state', 'root']).optional(),
|
||||
}
|
||||
|
||||
const providerCompatibilitySchema: z.ZodType<ProviderCompatibility> = z.object(providerCompatibilityFields).catchall(JsonValueSchema)
|
||||
|
||||
const providerModelCompatibilitySchema: z.ZodType<ProviderModelCompatibility> = z.object({
|
||||
...providerCompatibilityFields,
|
||||
supportsThinkingBlockBinding: z.boolean().optional(),
|
||||
supportsEffortUpdates: z.boolean().optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
const modelBudgetSchema = z.object({
|
||||
min: z.number().optional(),
|
||||
max: z.number().optional(),
|
||||
})
|
||||
|
||||
const providerModelReasoningSchema: z.ZodType<ProviderModelCapabilities['reasoning']> = z.union([
|
||||
z.object({ supported: z.literal(false) }).catchall(JsonValueSchema),
|
||||
z.object({
|
||||
supported: z.literal(true),
|
||||
toggle: z.boolean().optional(),
|
||||
effort: z.array(z.string()).optional(),
|
||||
budget: modelBudgetSchema.optional(),
|
||||
}).catchall(JsonValueSchema),
|
||||
])
|
||||
|
||||
const providerModelCapabilitiesSchema: z.ZodType<ProviderModelCapabilities> = z.object({
|
||||
tools: z.boolean().optional(),
|
||||
input: z.array(z.string()).optional(),
|
||||
output: z.array(z.string()).optional(),
|
||||
temperature: z.boolean().optional(),
|
||||
reasoning: providerModelReasoningSchema.optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
const providerModelCostEntrySchema = z.object({
|
||||
tier: z.object({ type: z.literal('context'), size: z.number() }).optional(),
|
||||
input: z.number(),
|
||||
output: z.number(),
|
||||
cache: z.object({
|
||||
read: z.number().optional(),
|
||||
write: z.number().optional(),
|
||||
}).optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
const providerModelCostSchema: z.ZodType<ProviderModelCost> = z.union([
|
||||
providerModelCostEntrySchema,
|
||||
z.array(providerModelCostEntrySchema),
|
||||
])
|
||||
|
||||
const providerModelLimitSchema: z.ZodType<ProviderModelLimit> = z.object({
|
||||
context: z.number().optional(),
|
||||
input: z.number().optional(),
|
||||
output: z.number().optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
const providerModelVariantSchema: z.ZodType<ProviderModelVariant> = z.object({
|
||||
id: z.string(),
|
||||
settings: providerModelVariantSettingsSchema.optional(),
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
body: JsonObjectSchema.optional(),
|
||||
})
|
||||
|
||||
export const OpenCodeProviderModelConfigSchema: z.ZodType<OpenCodeProviderModelConfig> = z.object({
|
||||
modelID: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
family: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
releaseDate: z.string().optional(),
|
||||
compatibility: providerModelCompatibilitySchema.optional(),
|
||||
package: z.string().optional(),
|
||||
settings: providerModelSettingsSchema.optional(),
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
body: JsonObjectSchema.optional(),
|
||||
capabilities: providerModelCapabilitiesSchema.optional(),
|
||||
variants: z.array(providerModelVariantSchema).optional(),
|
||||
cost: providerModelCostSchema.optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
limit: providerModelLimitSchema.optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
export const OpenCodeProviderConfigSchema: z.ZodType<OpenCodeProviderConfig> = z.object({
|
||||
canonical: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
env: z.array(z.string()).optional(),
|
||||
package: z.string().optional(),
|
||||
compatibility: providerCompatibilitySchema.optional(),
|
||||
settings: providerSettingsSchema.optional(),
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
body: JsonObjectSchema.optional(),
|
||||
models: z.record(z.string(), OpenCodeProviderModelConfigSchema).optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
export const OpenCodeCommandConfigSchema: z.ZodType<OpenCodeCommandConfig> = z.object({
|
||||
template: z.string(),
|
||||
description: z.string().optional(),
|
||||
agent: z.string().optional(),
|
||||
model: modelRefOrStringSchema.optional(),
|
||||
subagent: z.boolean().optional(),
|
||||
subtask: z.boolean().optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
export const OpenCodePermissionRuleSchema: z.ZodType<OpenCodePermissionRule> = z.object({
|
||||
action: z.string(),
|
||||
resource: z.string(),
|
||||
effect: z.enum(['allow', 'deny', 'ask']),
|
||||
})
|
||||
|
||||
export const OpenCodeAgentConfigSchema: z.ZodType<OpenCodeAgentConfig> = z.object({
|
||||
model: modelRefOrStringSchema.optional(),
|
||||
request: z.object({
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
body: JsonObjectSchema.optional(),
|
||||
}).catchall(JsonValueSchema).optional(),
|
||||
system: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
mode: z.enum(['subagent', 'primary', 'all']).optional(),
|
||||
hidden: z.boolean().optional(),
|
||||
color: z.string().optional(),
|
||||
steps: z.number().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
permissions: z.array(OpenCodePermissionRuleSchema).optional(),
|
||||
}).catchall(JsonValueSchema)
|
||||
|
||||
export const OpenCodeManagedConfigSectionsSchema = z.object({
|
||||
agents: z.record(z.string(), OpenCodeAgentConfigSchema).optional(),
|
||||
commands: z.record(z.string(), OpenCodeCommandConfigSchema).optional(),
|
||||
providers: z.record(z.string(), OpenCodeProviderConfigSchema).optional(),
|
||||
mcp: JsonValueSchema.optional(),
|
||||
})
|
||||
|
||||
export type OpenCodeManagedConfigSections = z.infer<typeof OpenCodeManagedConfigSectionsSchema>
|
||||
@@ -1,12 +1,13 @@
|
||||
import type { SessionMessageAssistant, ToolContent } from '@opencode/client'
|
||||
import { z } from 'zod'
|
||||
|
||||
const THINK_BLOCK_PATTERN = /<think>[\s\S]*?<\/think>\s*/g
|
||||
|
||||
const SessionEventDataSchema = z.object({ sessionID: z.string() })
|
||||
|
||||
export function sessionIDFromEvent(event: { data: unknown }): string | undefined {
|
||||
const data = event.data
|
||||
if (typeof data !== 'object' || data === null) return undefined
|
||||
if (!('sessionID' in data) || typeof data.sessionID !== 'string') return undefined
|
||||
return data.sessionID
|
||||
const data = SessionEventDataSchema.safeParse(event.data)
|
||||
return data.success ? data.data.sessionID : undefined
|
||||
}
|
||||
|
||||
export interface AssistantTextOptions {
|
||||
|
||||
+31
-38
@@ -1,92 +1,85 @@
|
||||
import { isRpcError } from '@opencode/client'
|
||||
import type { Goal } from '@opencode/schema/goal'
|
||||
import { z } from 'zod'
|
||||
import type { OpenCodeApi } from './index'
|
||||
|
||||
/** The OpenCode goal as the server reports it. */
|
||||
export type GoalState = Goal.State
|
||||
|
||||
/** The lifecycle status of an OpenCode goal. */
|
||||
export type GoalStatus = Goal.State['status']
|
||||
|
||||
/** The RPC the `/goal` plugin exposes on the OpenCode server. */
|
||||
export const GOAL_RPC_ID = 'opencode.goal'
|
||||
|
||||
/** The event the `/goal` plugin publishes in a session's location on every goal write. */
|
||||
export const GOAL_CHANGED_EVENT_TYPE = 'rpc.opencode.goal.changed'
|
||||
|
||||
/** The slash command that controls a session goal. */
|
||||
export const GOAL_COMMAND_NAME = 'goal'
|
||||
|
||||
/** Pause reasons that mean the user stopped the goal rather than the goal finishing its work. */
|
||||
export const GOAL_USER_PAUSE_REASONS = ['Paused by the user', 'Stopped by the user'] as const
|
||||
|
||||
const GOAL_USER_PAUSE_REASON_SET: ReadonlySet<string> = new Set(GOAL_USER_PAUSE_REASONS)
|
||||
|
||||
const GOAL_STATUSES = ['active', 'paused', 'complete'] as const satisfies readonly GoalStatus[]
|
||||
|
||||
/** Reports whether a value from a remote server has the shape of a reported goal. */
|
||||
function isGoalState(value: unknown): value is GoalState {
|
||||
if (typeof value !== 'object' || value === null) return false
|
||||
const goal = value as { id?: unknown; objective?: unknown; status?: unknown; rounds?: unknown; maxRounds?: unknown }
|
||||
return (
|
||||
typeof goal.id === 'string' &&
|
||||
typeof goal.objective === 'string' &&
|
||||
(GOAL_STATUSES as readonly unknown[]).includes(goal.status) &&
|
||||
typeof goal.rounds === 'number' &&
|
||||
typeof goal.maxRounds === 'number'
|
||||
)
|
||||
}
|
||||
const GoalStateSchema = z.object({
|
||||
id: z.string(),
|
||||
objective: z.string(),
|
||||
status: z.enum(GOAL_STATUSES),
|
||||
reason: z.string().optional(),
|
||||
rounds: z.number(),
|
||||
maxRounds: z.number(),
|
||||
stalls: z.number().optional(),
|
||||
boot: z.string(),
|
||||
updatedAt: z.number(),
|
||||
})
|
||||
|
||||
const GoalChangedEventSchema = z.object({
|
||||
sessionID: z.string(),
|
||||
goal: GoalStateSchema.nullable(),
|
||||
})
|
||||
|
||||
/** The result of reading a session goal, distinguishing an older server without the goal RPC. */
|
||||
export type SessionGoalRead = { supported: true; goal: GoalState | null } | { supported: false }
|
||||
|
||||
/** Reads a session goal, reporting an unsupported server instead of throwing. */
|
||||
export type SessionGoalRpc = { rpc: Pick<OpenCodeApi['rpc'], 'call'> }
|
||||
|
||||
export async function readSessionGoal(
|
||||
api: OpenCodeApi,
|
||||
api: SessionGoalRpc,
|
||||
input: { sessionID: string; directory?: string },
|
||||
): Promise<SessionGoalRead> {
|
||||
try {
|
||||
const location = input.directory ? { location: { directory: input.directory } } : undefined
|
||||
const result = await api.rpc.call({
|
||||
rpcID: GOAL_RPC_ID,
|
||||
method: 'get',
|
||||
input: { sessionID: input.sessionID },
|
||||
...(input.directory ? { location: { directory: input.directory } } : {}),
|
||||
...location,
|
||||
})
|
||||
const output: unknown = result.output ?? null
|
||||
if (output === null) return { supported: true, goal: null }
|
||||
if (!isGoalState(output)) return { supported: false }
|
||||
return { supported: true, goal: output }
|
||||
const goal = GoalStateSchema.safeParse(output)
|
||||
if (!goal.success) return { supported: false }
|
||||
return { supported: true, goal: goal.data }
|
||||
} catch (error) {
|
||||
if (isRpcError(error) && error.type === 'rpc.unavailable') return { supported: false }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** Extracts a session goal change from an OpenCode event, ignoring unrelated and malformed events. */
|
||||
export function goalChangeFromEvent(
|
||||
event: { type: string; data: unknown },
|
||||
): { sessionID: string; goal: GoalState | null } | null {
|
||||
if (event.type !== GOAL_CHANGED_EVENT_TYPE) return null
|
||||
|
||||
const data = event.data
|
||||
if (typeof data !== 'object' || data === null) return null
|
||||
const change = GoalChangedEventSchema.safeParse(event.data)
|
||||
if (!change.success) return null
|
||||
|
||||
const sessionID = (data as { sessionID?: unknown }).sessionID
|
||||
if (typeof sessionID !== 'string') return null
|
||||
|
||||
const goal = (data as { goal?: unknown }).goal
|
||||
if (goal === null) return { sessionID, goal: null }
|
||||
if (!isGoalState(goal)) return null
|
||||
|
||||
return { sessionID, goal }
|
||||
return { sessionID: change.data.sessionID, goal: change.data.goal }
|
||||
}
|
||||
|
||||
/** Reports whether the goal is still being worked on, whether running or paused. */
|
||||
export function isGoalOpen(goal: GoalState | null | undefined): boolean {
|
||||
return goal?.status === 'active' || goal?.status === 'paused'
|
||||
}
|
||||
|
||||
/** Reports whether the goal reached an outcome, meaning it completed or the reviewer paused it. */
|
||||
export function isGoalOutcome(goal: GoalState): boolean {
|
||||
if (goal.status === 'complete') return true
|
||||
if (goal.status !== 'paused') return false
|
||||
return !(GOAL_USER_PAUSE_REASONS as readonly string[]).includes(goal.reason ?? '')
|
||||
return !GOAL_USER_PAUSE_REASON_SET.has(goal.reason ?? '')
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { OpenCode } from '@opencode/client'
|
||||
import { z } from 'zod'
|
||||
import { OPENCODE_SERVER_USERNAME } from '../schemas/opencode-servers'
|
||||
|
||||
export { OPENCODE_SERVER_USERNAME }
|
||||
@@ -56,11 +57,21 @@ export type {
|
||||
OpenCodeAgentConfig,
|
||||
OpenCodeCommandConfig,
|
||||
OpenCodeConfigInfo,
|
||||
OpenCodeManagedConfigSections,
|
||||
OpenCodePermissionRule,
|
||||
OpenCodeProviderConfig,
|
||||
OpenCodeProviderModelConfig,
|
||||
} from './config'
|
||||
|
||||
export {
|
||||
OpenCodeAgentConfigSchema,
|
||||
OpenCodeCommandConfigSchema,
|
||||
OpenCodeManagedConfigSectionsSchema,
|
||||
OpenCodePermissionRuleSchema,
|
||||
OpenCodeProviderConfigSchema,
|
||||
OpenCodeProviderModelConfigSchema,
|
||||
} from './config'
|
||||
|
||||
export {
|
||||
GOAL_CHANGED_EVENT_TYPE,
|
||||
GOAL_COMMAND_NAME,
|
||||
@@ -72,7 +83,7 @@ export {
|
||||
readSessionGoal,
|
||||
} from './goal'
|
||||
|
||||
export type { GoalState, GoalStatus, SessionGoalRead } from './goal'
|
||||
export type { GoalState, GoalStatus, SessionGoalRead, SessionGoalRpc } from './goal'
|
||||
|
||||
export { configModelRef, formatOpenCodeModelRef, parseOpenCodeModelRef, selectConfiguredModelRef } from './modelRef'
|
||||
|
||||
@@ -211,10 +222,9 @@ export function createOpenCodeApi(options: OpenCodeApiOptions): OpenCodeApi {
|
||||
return OpenCode.make({
|
||||
baseUrl: options.baseUrl,
|
||||
fetch: options.fetch,
|
||||
headers: {
|
||||
...options.headers,
|
||||
...(options.password ? { Authorization: buildOpenCodeBasicAuth(options.password) } : {}),
|
||||
},
|
||||
headers: options.password
|
||||
? { ...options.headers, Authorization: buildOpenCodeBasicAuth(options.password) }
|
||||
: options.headers,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -226,7 +236,11 @@ export function openCodeLocation(directory: string | undefined): OpenCodeLocatio
|
||||
return directory ? { location: { directory } } : undefined
|
||||
}
|
||||
|
||||
const OPENCODE_ERROR_STATUS_BY_TAG: Record<string, number> = {
|
||||
interface OpenCodeErrorStatusByTag {
|
||||
[tag: string]: number
|
||||
}
|
||||
|
||||
const OPENCODE_ERROR_STATUS_BY_TAG: OpenCodeErrorStatusByTag = {
|
||||
InvalidRequestError: 400,
|
||||
RpcError: 400,
|
||||
InvalidCursorError: 400,
|
||||
@@ -259,16 +273,19 @@ const OPENCODE_ERROR_STATUS_BY_TAG: Record<string, number> = {
|
||||
ServiceUnavailableError: 503,
|
||||
}
|
||||
|
||||
export function openCodeErrorStatus(error: unknown): number | undefined {
|
||||
if (error === null || typeof error !== 'object') return undefined
|
||||
const OpenCodeErrorIdentitySchema = z.object({
|
||||
_tag: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
})
|
||||
|
||||
const tag = (error as { _tag?: unknown })._tag
|
||||
if (typeof tag === 'string' && OPENCODE_ERROR_STATUS_BY_TAG[tag] !== undefined) {
|
||||
return OPENCODE_ERROR_STATUS_BY_TAG[tag]
|
||||
export function openCodeErrorStatus(cause: unknown): number | undefined {
|
||||
const identity = OpenCodeErrorIdentitySchema.safeParse(cause)
|
||||
if (!identity.success) return undefined
|
||||
|
||||
const { _tag, name } = identity.data
|
||||
if (_tag !== undefined && OPENCODE_ERROR_STATUS_BY_TAG[_tag] !== undefined) {
|
||||
return OPENCODE_ERROR_STATUS_BY_TAG[_tag]
|
||||
}
|
||||
|
||||
const name = (error as { name?: unknown }).name
|
||||
if (typeof name === 'string') return OPENCODE_ERROR_STATUS_BY_TAG[name]
|
||||
|
||||
if (name !== undefined) return OPENCODE_ERROR_STATUS_BY_TAG[name]
|
||||
return undefined
|
||||
}
|
||||
+35
-25
@@ -1,6 +1,7 @@
|
||||
import type { McpServer } from '@opencode/client'
|
||||
import { z } from 'zod'
|
||||
import type { OpenCodeConfigInfo } from './config'
|
||||
import { isRecord } from '../utils/record'
|
||||
import { JsonValueSchema, type JsonValue } from '../utils/json'
|
||||
|
||||
export const MCP_OAUTH_CALLBACK_PATH = '/api/mcp-oauth-proxy/callback'
|
||||
|
||||
@@ -14,17 +15,34 @@ export type McpStatus = McpServer['status'] & Pick<McpServer, 'integrationID'>
|
||||
|
||||
export type McpStatusMap = Record<string, McpStatus>
|
||||
|
||||
const McpServerConfigSchema = z.union([
|
||||
z.looseObject({
|
||||
type: z.literal('local'),
|
||||
command: z.array(z.string()),
|
||||
}),
|
||||
z.looseObject({
|
||||
type: z.literal('remote'),
|
||||
url: z.string(),
|
||||
}),
|
||||
])
|
||||
|
||||
const McpConfigDocumentSchema = z.looseObject({
|
||||
servers: z.record(z.string(), JsonValueSchema).optional(),
|
||||
})
|
||||
|
||||
export function mcpOAuthRedirectUri(origin: string): string {
|
||||
return new URL(MCP_OAUTH_CALLBACK_PATH, origin).toString()
|
||||
}
|
||||
|
||||
function isMcpServerConfig(value: unknown): value is McpServerConfig {
|
||||
return isRecord(value) && (value.type === 'local' || value.type === 'remote')
|
||||
}
|
||||
|
||||
export function mcpServersFromConfig(mcp: unknown): Record<string, McpServerConfig> {
|
||||
if (!isRecord(mcp) || !isRecord(mcp.servers)) return {}
|
||||
return Object.fromEntries(Object.entries(mcp.servers).filter((entry): entry is [string, McpServerConfig] => isMcpServerConfig(entry[1])))
|
||||
export function mcpServersFromConfig(mcp: JsonValue | undefined): Record<string, McpServerConfig> {
|
||||
const document = McpConfigDocumentSchema.safeParse(mcp)
|
||||
if (!document.success || document.data.servers === undefined) return {}
|
||||
return Object.fromEntries(
|
||||
Object.entries(document.data.servers).flatMap(([name, entry]) => {
|
||||
const config = McpServerConfigSchema.safeParse(entry)
|
||||
return config.success ? [[name, config.data] as const] : []
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export interface McpServerView {
|
||||
@@ -35,20 +53,14 @@ export interface McpServerView {
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a config server to its UI-facing view, exposing `command` for local servers and `url` for
|
||||
* remote ones so the view never carries both. `enabled` reflects the absence of `disabled: true`.
|
||||
*/
|
||||
function toMcpServerView(name: string, config: McpServerConfig, enabled: boolean): McpServerView {
|
||||
return {
|
||||
name,
|
||||
type: config.type,
|
||||
...(config.type === 'local' ? { command: config.command } : { url: config.url }),
|
||||
enabled,
|
||||
if (config.type === 'local') {
|
||||
return { name, type: config.type, command: config.command, enabled }
|
||||
}
|
||||
return { name, type: config.type, url: config.url, enabled }
|
||||
}
|
||||
|
||||
export function mcpServerViewsFromConfig(mcp: unknown): McpServerView[] {
|
||||
export function mcpServerViewsFromConfig(mcp: JsonValue | undefined): McpServerView[] {
|
||||
return Object.entries(mcpServersFromConfig(mcp))
|
||||
.map(([name, config]) => toMcpServerView(name, config, config.disabled !== true))
|
||||
.sort((left, right) => left.name.localeCompare(right.name))
|
||||
@@ -56,12 +68,10 @@ export function mcpServerViewsFromConfig(mcp: unknown): McpServerView[] {
|
||||
|
||||
export function mcpStatusByName(servers: McpServer[]): McpStatusMap {
|
||||
return Object.fromEntries(
|
||||
servers.map((server) => [
|
||||
server.name,
|
||||
{
|
||||
...server.status,
|
||||
...(server.integrationID ? { integrationID: server.integrationID } : {}),
|
||||
},
|
||||
]),
|
||||
servers.map((server) => {
|
||||
const status: McpStatus = { ...server.status }
|
||||
if (server.integrationID) status.integrationID = server.integrationID
|
||||
return [server.name, status]
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ModelInfo, ModelRef } from '@opencode/client'
|
||||
import { isRecord } from '../utils/record'
|
||||
import { z } from 'zod'
|
||||
import { JsonObjectSchema, JsonValueSchema, type JsonObject, type JsonValue } from '../utils/json'
|
||||
|
||||
export type ModelPreferenceModel = {
|
||||
providerID: string
|
||||
@@ -12,24 +13,30 @@ export type ModelPreference = {
|
||||
variant: Record<string, string | undefined>
|
||||
}
|
||||
|
||||
export type ModelPreferenceDocument = Record<string, unknown> & ModelPreference
|
||||
export type ModelPreferenceDocument = ModelPreference &
|
||||
Record<string, JsonValue | undefined | ModelPreference['variant']>
|
||||
|
||||
function models(value: unknown): ModelPreferenceModel[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value.flatMap((item): ModelPreferenceModel[] => {
|
||||
if (!isRecord(item)) return []
|
||||
if (typeof item.providerID !== 'string' || item.providerID.length === 0) return []
|
||||
if (typeof item.modelID !== 'string' || item.modelID.length === 0) return []
|
||||
return [{ providerID: item.providerID, modelID: item.modelID }]
|
||||
const ModelPreferenceModelSchema = z.object({
|
||||
providerID: z.string().min(1),
|
||||
modelID: z.string().min(1),
|
||||
})
|
||||
|
||||
function models(value: JsonValue | undefined): ModelPreferenceModel[] {
|
||||
const entries = z.array(JsonValueSchema).safeParse(value)
|
||||
if (!entries.success) return []
|
||||
return entries.data.flatMap((item): ModelPreferenceModel[] => {
|
||||
const model = ModelPreferenceModelSchema.safeParse(item)
|
||||
return model.success ? [model.data] : []
|
||||
})
|
||||
}
|
||||
|
||||
function variants(value: unknown): Record<string, string | undefined> {
|
||||
if (!isRecord(value)) return {}
|
||||
function variants(value: JsonValue | undefined): Record<string, string | undefined> {
|
||||
const entries = JsonObjectSchema.safeParse(value)
|
||||
if (!entries.success) return {}
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).flatMap(([key, item]) => {
|
||||
if (key.length === 0 || typeof item !== 'string' || item.length === 0) return []
|
||||
return [[key, item]] as const
|
||||
Object.entries(entries.data).flatMap(([key, item]) => {
|
||||
const variant = z.string().min(1).safeParse(item)
|
||||
return key.length > 0 && variant.success ? [[key, variant.data] as const] : []
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -115,8 +122,9 @@ export function cycleModelVariant(current: string | undefined, variants: string[
|
||||
return named[index + 1]
|
||||
}
|
||||
|
||||
export function decodeModelPreference(value: unknown): ModelPreferenceDocument {
|
||||
const root = isRecord(value) ? value : {}
|
||||
export function decodeModelPreference(value: JsonValue | undefined): ModelPreferenceDocument {
|
||||
const parsed = JsonObjectSchema.safeParse(value)
|
||||
const root: JsonObject = parsed.success ? parsed.data : {}
|
||||
return {
|
||||
...root,
|
||||
recent: models(root.recent),
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import type { ConfigEntry, ModelRef } from '@opencode/client'
|
||||
import { z } from 'zod'
|
||||
import type { OpenCodeConfigInfo } from './config'
|
||||
|
||||
type ConfigDocumentModel = OpenCodeConfigInfo['model']
|
||||
|
||||
const ConfigModelRefSchema = z.object({
|
||||
providerID: z.string(),
|
||||
model: z.string(),
|
||||
variant: z.string().optional(),
|
||||
})
|
||||
|
||||
export function parseOpenCodeModelRef(model: string): ModelRef | undefined {
|
||||
const providerEnd = model.indexOf('/')
|
||||
if (providerEnd <= 0) return undefined
|
||||
@@ -16,7 +23,9 @@ export function parseOpenCodeModelRef(model: string): ModelRef | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return { providerID, id, ...(variant ? { variant } : {}) }
|
||||
const ref: ModelRef = { providerID, id }
|
||||
if (variant) ref.variant = variant
|
||||
return ref
|
||||
}
|
||||
|
||||
export function formatOpenCodeModelRef(ref: ModelRef): string {
|
||||
@@ -27,13 +36,15 @@ export function configModelRef(
|
||||
model: string | { providerID: string; model: string; variant?: string } | undefined | null,
|
||||
): ModelRef | undefined {
|
||||
if (!model) return undefined
|
||||
if (typeof model === 'string') return parseOpenCodeModelRef(model)
|
||||
const text = z.string().safeParse(model)
|
||||
if (text.success) return parseOpenCodeModelRef(text.data)
|
||||
|
||||
return {
|
||||
providerID: model.providerID,
|
||||
id: model.model,
|
||||
...(model.variant ? { variant: model.variant } : {}),
|
||||
}
|
||||
const configured = ConfigModelRefSchema.safeParse(model)
|
||||
if (!configured.success) return undefined
|
||||
|
||||
const ref: ModelRef = { providerID: configured.data.providerID, id: configured.data.model }
|
||||
if (configured.data.variant) ref.variant = configured.data.variant
|
||||
return ref
|
||||
}
|
||||
|
||||
export function selectConfiguredModelRef(entries: ConfigEntry[]): ModelRef | undefined {
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { z } from 'zod'
|
||||
import { JsonValueSchema, type JsonValue } from '../utils/json'
|
||||
|
||||
const PAIRING_PROTOCOL = 'ocm-pair-v2'
|
||||
const PAIRING_PROOF_PREFIX = `${PAIRING_PROTOCOL}:`
|
||||
const PAIRING_KEY_INFO = `${PAIRING_PROTOCOL} credentials`
|
||||
@@ -10,11 +13,16 @@ const textDecoder = new TextDecoder()
|
||||
|
||||
type WebCryptoKey = Awaited<ReturnType<typeof globalThis.crypto.subtle.importKey>>
|
||||
|
||||
export interface OpenCodePairingCredentials {
|
||||
export type OpenCodePairingCredentials = {
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
const OpenCodePairingCredentialsSchema = z.object({
|
||||
username: z.string().min(1),
|
||||
password: z.string(),
|
||||
})
|
||||
|
||||
export interface OpenCodePairingEncryptedCredentials {
|
||||
iv: string
|
||||
ciphertext: string
|
||||
@@ -30,33 +38,27 @@ export interface OpenCodePairingDecryptOptions extends OpenCodePairingKeyOptions
|
||||
ciphertext: string
|
||||
}
|
||||
|
||||
/** Generates a fresh 32-byte pairing nonce encoded as base64url. */
|
||||
export function createOpenCodePairingNonce(): string {
|
||||
return base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(PAIRING_NONCE_BYTES)))
|
||||
}
|
||||
|
||||
/** Reports whether a value is a base64url-encoded 32-byte pairing nonce. */
|
||||
export function isOpenCodePairingNonce(value: unknown): value is string {
|
||||
if (typeof value !== 'string') return false
|
||||
const bytes = base64UrlDecode(value)
|
||||
export function isOpenCodePairingNonce(value: string): boolean {
|
||||
const nonce = z.string().safeParse(value)
|
||||
if (!nonce.success) return false
|
||||
const bytes = base64UrlDecode(nonce.data)
|
||||
return bytes !== null && bytes.length === PAIRING_NONCE_BYTES
|
||||
}
|
||||
|
||||
/** Reports whether a value carries non-empty string credentials. */
|
||||
export function isOpenCodePairingCredentials(value: unknown): value is OpenCodePairingCredentials {
|
||||
if (typeof value !== 'object' || value === null) return false
|
||||
const { username, password } = value as { username?: unknown; password?: unknown }
|
||||
return typeof username === 'string' && username.length > 0 && typeof password === 'string'
|
||||
export function isOpenCodePairingCredentials(value: JsonValue | undefined): value is OpenCodePairingCredentials {
|
||||
return OpenCodePairingCredentialsSchema.safeParse(value).success
|
||||
}
|
||||
|
||||
/** Computes the base64url HMAC-SHA256 proof that binds a pairing code to a nonce. */
|
||||
export async function createOpenCodePairingProof(code: string, nonce: string): Promise<string> {
|
||||
const key = await importHmacKey(code)
|
||||
const signature = await globalThis.crypto.subtle.sign('HMAC', key, pairingProofMessage(nonce))
|
||||
return base64UrlEncode(new Uint8Array(signature))
|
||||
}
|
||||
|
||||
/** Verifies a pairing proof in constant time through the Web Crypto HMAC verifier. */
|
||||
export async function verifyOpenCodePairingProof(code: string, nonce: string, proof: string): Promise<boolean> {
|
||||
const signature = base64UrlDecode(proof)
|
||||
if (signature === null) return false
|
||||
@@ -68,7 +70,6 @@ export async function verifyOpenCodePairingProof(code: string, nonce: string, pr
|
||||
}
|
||||
}
|
||||
|
||||
/** Encrypts pairing credentials with AES-256-GCM under a key derived from the code and nonce. */
|
||||
export async function encryptOpenCodePairingCredentials(
|
||||
options: OpenCodePairingKeyOptions & { credentials: OpenCodePairingCredentials },
|
||||
): Promise<OpenCodePairingEncryptedCredentials> {
|
||||
@@ -89,7 +90,6 @@ export async function encryptOpenCodePairingCredentials(
|
||||
}
|
||||
}
|
||||
|
||||
/** Decrypts pairing credentials, throwing when the payload is tampered with or malformed. */
|
||||
export async function decryptOpenCodePairingCredentials(
|
||||
options: OpenCodePairingDecryptOptions,
|
||||
): Promise<OpenCodePairingCredentials> {
|
||||
@@ -104,9 +104,9 @@ export async function decryptOpenCodePairingCredentials(
|
||||
key,
|
||||
ciphertext,
|
||||
)
|
||||
const parsed: unknown = JSON.parse(textDecoder.decode(plaintext))
|
||||
if (!isOpenCodePairingCredentials(parsed)) throw new Error('Invalid pairing payload')
|
||||
return parsed
|
||||
const parsed = JsonValueSchema.safeParse(JSON.parse(textDecoder.decode(plaintext)))
|
||||
if (!parsed.success || !isOpenCodePairingCredentials(parsed.data)) throw new Error('Invalid pairing payload')
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
function encodeText(value: string): Uint8Array<ArrayBuffer> {
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
import { compareParsedSemver, compareSemver, normalizeSemver, parseSemver, type Semver } from '../utils/semver'
|
||||
|
||||
/** The OpenCode release Manager is built against and bundles; matches the `@opencode/*` pnpm catalog entries. */
|
||||
export const OPENCODE_PINNED_VERSION = '2.2.5'
|
||||
|
||||
/** The oldest OpenCode release Manager supports; any later release of the same major is accepted. */
|
||||
export const OPENCODE_MIN_VERSION = '2.2.5'
|
||||
|
||||
const OPENCODE_RELEASE_BASE_URL = 'https://opencode.ai/files/bin'
|
||||
|
||||
const OPENCODE_ARCH_ALIASES: Record<string, string> = {
|
||||
x64: 'x64',
|
||||
amd64: 'x64',
|
||||
x86_64: 'x64',
|
||||
arm64: 'arm64',
|
||||
aarch64: 'arm64',
|
||||
}
|
||||
const OPENCODE_ARCH_ALIASES = new Map<string, string>([
|
||||
['x64', 'x64'],
|
||||
['amd64', 'x64'],
|
||||
['x86_64', 'x64'],
|
||||
['arm64', 'arm64'],
|
||||
['aarch64', 'arm64'],
|
||||
])
|
||||
|
||||
const OPENCODE_PLATFORM_ARCHIVES: Partial<Record<NodeJS.Platform, 'tar.gz' | 'zip'>> = {
|
||||
linux: 'tar.gz',
|
||||
darwin: 'zip',
|
||||
}
|
||||
const OPENCODE_PLATFORM_ARCHIVES = new Map<NodeJS.Platform, 'tar.gz' | 'zip'>([
|
||||
['linux', 'tar.gz'],
|
||||
['darwin', 'zip'],
|
||||
])
|
||||
|
||||
export type OpenCodeVersion = Semver
|
||||
|
||||
@@ -67,7 +65,6 @@ export function isSupportedOpenCodeVersion(version: string): boolean {
|
||||
return parsed.major === OPENCODE_MIN.major && compareParsedSemver(parsed, OPENCODE_MIN) >= 0
|
||||
}
|
||||
|
||||
/** Reports whether a server version shares Manager's OpenCode major, so the V2 client can still talk to it. */
|
||||
export function isSameOpenCodeMajor(version: string): boolean {
|
||||
return parseOpenCodeVersion(version)?.major === OPENCODE_MIN.major
|
||||
}
|
||||
@@ -76,14 +73,19 @@ export function describeUnsupportedOpenCodeVersion(version: string): string {
|
||||
return `OpenCode ${version} is not supported; OpenCode Manager requires OpenCode ${OPENCODE_SUPPORTED_VERSION_RANGE}`
|
||||
}
|
||||
|
||||
export interface OpenCodeReleaseAsset {
|
||||
url: string
|
||||
archive: 'tar.gz' | 'zip'
|
||||
}
|
||||
|
||||
export function buildOpenCodeReleaseAsset(
|
||||
version: string,
|
||||
target: { platform: NodeJS.Platform; arch: string; musl: boolean },
|
||||
): { url: string; archive: 'tar.gz' | 'zip' } {
|
||||
const archive = OPENCODE_PLATFORM_ARCHIVES[target.platform]
|
||||
): OpenCodeReleaseAsset {
|
||||
const archive = OPENCODE_PLATFORM_ARCHIVES.get(target.platform)
|
||||
if (!archive) throw new Error(`Unsupported OpenCode platform: ${target.platform}`)
|
||||
|
||||
const arch = OPENCODE_ARCH_ALIASES[target.arch]
|
||||
const arch = OPENCODE_ARCH_ALIASES.get(target.arch)
|
||||
if (!arch) throw new Error(`Unsupported OpenCode architecture: ${target.arch}`)
|
||||
|
||||
const muslSuffix = target.musl ? '-musl' : ''
|
||||
|
||||
@@ -2,18 +2,11 @@ import type { SessionMessageInfo, SessionStatus } from '@opencode/client'
|
||||
|
||||
import { assistantText } from './content'
|
||||
|
||||
/** Key under which the voice conversation instructions are stored on a session. */
|
||||
export const VOICE_MODE_INSTRUCTION_KEY = 'voice-mode'
|
||||
|
||||
/** Session instructions that make every assistant reply suitable for reading aloud. */
|
||||
export const VOICE_MODE_INSTRUCTIONS =
|
||||
'Every reply will be read aloud in full by text-to-speech. Write plain, conversational spoken sentences. Never include file paths, filenames, line numbers, URLs, code, commands, markdown, lists, tables or symbols; describe code by what it does instead. Say numbers naturally. Lead with the outcome and keep it to a few sentences unless asked for detail. End with a direct question when you need input. This changes only how replies are written, not how thoroughly you work or use tools, and it takes precedence over other formatting guidance while active.'
|
||||
|
||||
/**
|
||||
* The stage a hands-free voice conversation is currently in. `recording`
|
||||
* captures a message that is added to the session queue while the agent keeps
|
||||
* working, so it is separate from the `listening` stage that opens a new turn.
|
||||
*/
|
||||
export type VoicePhase =
|
||||
| 'off'
|
||||
| 'listening'
|
||||
@@ -23,40 +16,21 @@ export type VoicePhase =
|
||||
| 'recording'
|
||||
| 'paused'
|
||||
|
||||
/** Why a paused voice conversation stopped listening. */
|
||||
export type VoicePauseReason = 'user' | 'background' | 'no-speech' | 'error'
|
||||
|
||||
/**
|
||||
* Where a failure came from, which decides what the user must fix before a
|
||||
* retry can succeed. A failed capture usually means the microphone, while a
|
||||
* failed send or reading can succeed on a plain retry.
|
||||
*/
|
||||
export type VoiceFailureSource = 'capture' | 'send' | 'playback'
|
||||
|
||||
/** The reported status of a session, as a session transcript carries it. */
|
||||
export type VoiceSessionStatus = SessionStatus['type']
|
||||
|
||||
/** Everything needed to resume or label a hands-free voice conversation. */
|
||||
export interface VoiceConversationState {
|
||||
/** Current stage of the conversation loop. */
|
||||
phase: VoicePhase
|
||||
/** Why the conversation is paused, or null when it is not paused. */
|
||||
pauseReason: VoicePauseReason | null
|
||||
/** Message shown to the user after a failure, or null when there is none. */
|
||||
error: string | null
|
||||
/** Where the failure came from, or null when there is no failure. */
|
||||
failureSource: VoiceFailureSource | null
|
||||
/**
|
||||
* Id of the transcript message whose successors the conversation reads
|
||||
* aloud, or null when the whole transcript is in scope. Replies after it are
|
||||
* read one by one, including replies to messages queued during the turn.
|
||||
*/
|
||||
baselineId: string | null
|
||||
/** Whether the session has reported being busy since the current turn was sent. */
|
||||
sawBusy: boolean
|
||||
}
|
||||
|
||||
/** State of a voice conversation that is not running. */
|
||||
export const INITIAL_VOICE_CONVERSATION_STATE: VoiceConversationState = {
|
||||
phase: 'off',
|
||||
pauseReason: null,
|
||||
@@ -66,7 +40,6 @@ export const INITIAL_VOICE_CONVERSATION_STATE: VoiceConversationState = {
|
||||
sawBusy: false,
|
||||
}
|
||||
|
||||
/** A signal from the voice conversation controller or the session. */
|
||||
export type VoiceConversationEvent =
|
||||
| { type: 'start'; busy: boolean; baselineId: string | null }
|
||||
| { type: 'transcript'; text: string }
|
||||
@@ -87,59 +60,31 @@ export type VoiceConversationEvent =
|
||||
| { type: 'error'; message: string; source: VoiceFailureSource }
|
||||
| { type: 'exit' }
|
||||
|
||||
/** An assistant message the conversation reads aloud. */
|
||||
export interface VoiceSpokenMessage {
|
||||
/** Id of the assistant message. */
|
||||
id: string
|
||||
/** Trimmed spoken text of the message, which is never empty. */
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Session data used to decide whether the current turn is finished. */
|
||||
export interface VoiceTurnCompletionInput {
|
||||
/** Reported session status for the active session. */
|
||||
status: VoiceSessionStatus
|
||||
/** Whether the session has reported being busy since the current turn started. */
|
||||
sawBusy: boolean
|
||||
/** Whether a message of the current turn was read aloud. */
|
||||
spoke: boolean
|
||||
/** Whether the session still holds prompts queued by the user. */
|
||||
hasPendingPrompts: boolean
|
||||
/** Whether an assistant message after the baseline is still streaming. */
|
||||
hasIncomplete: boolean
|
||||
}
|
||||
|
||||
/** Inputs that determine the text shown for the voice conversation. */
|
||||
export interface VoiceConversationLabelInput {
|
||||
/** Current stage of the conversation loop. */
|
||||
phase: VoicePhase
|
||||
/** Why the conversation is paused, or null when it is not paused. */
|
||||
pauseReason: VoicePauseReason | null
|
||||
/** Whether the session is waiting for the user to approve a tool. */
|
||||
pendingApproval: boolean
|
||||
/** Whether the current recording has stopped and is being finalized. */
|
||||
isEndpointing: boolean
|
||||
/** Whether a reading is held mid-reply after a pause. */
|
||||
isPlaybackPaused: boolean
|
||||
/** Whether the session is still working on the current turn. */
|
||||
sessionBusy: boolean
|
||||
/** Message shown to the user after a failure, or null when there is none. */
|
||||
error?: string | null
|
||||
/** Where the failure came from, which decides how the user can recover. */
|
||||
failureSource?: VoiceFailureSource | null
|
||||
/** Whether the microphone was asked to start but has not begun capturing yet. */
|
||||
isStartingCapture?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one voice conversation event to the loop state. Events that do not
|
||||
* apply to the current phase are ignored, and the previous state object is
|
||||
* returned unchanged so callers can skip re-rendering on no-ops.
|
||||
*
|
||||
* @param state The current conversation state.
|
||||
* @param event The event to apply.
|
||||
* @returns The next state, or the same state object when the event does not apply.
|
||||
*/
|
||||
export function reduceVoiceConversation(
|
||||
state: VoiceConversationState,
|
||||
event: VoiceConversationEvent,
|
||||
@@ -258,15 +203,6 @@ export function reduceVoiceConversation(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index of the first message the conversation may read. Messages at
|
||||
* or before the baseline are excluded; a null or unknown baseline leaves the
|
||||
* whole transcript in scope.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @returns The index of the first message in scope.
|
||||
*/
|
||||
function spokenWindowStart(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
@@ -276,17 +212,6 @@ function spokenWindowStart(
|
||||
return baselineIndex === -1 ? 0 : baselineIndex + 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists every completed assistant message with text that the conversation has
|
||||
* not read yet, oldest first. Messages are read in the order they arrive, so a
|
||||
* user message inside the window does not end the scan: replies to prompts
|
||||
* queued during the turn are read as well.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @param spokenIds Ids of the messages already read aloud.
|
||||
* @returns The unread messages, oldest first.
|
||||
*/
|
||||
export function listUnspokenMessages(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
@@ -305,15 +230,6 @@ export function listUnspokenMessages(
|
||||
return unspoken
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the message the conversation reads next: the oldest unread message that
|
||||
* has already completed.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @param spokenIds Ids of the messages already read aloud.
|
||||
* @returns The next message to read, or null when there is nothing to read.
|
||||
*/
|
||||
export function findNextUnspokenMessage(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
@@ -322,15 +238,6 @@ export function findNextUnspokenMessage(
|
||||
return listUnspokenMessages(messages, baselineId, spokenIds)[0] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether any message of the current turn has been read aloud, which
|
||||
* lets a turn that produced a reply finish without ever reporting itself busy.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @param spokenIds Ids of the messages already read aloud.
|
||||
* @returns Whether a message after the baseline has been read.
|
||||
*/
|
||||
export function hasSpokenMessage(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
@@ -341,14 +248,6 @@ export function hasSpokenMessage(
|
||||
.some((message) => spokenIds.has(message.id))
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the turn still produces an assistant message, which keeps the
|
||||
* turn open so the rest of a just-finished reply can still be read.
|
||||
*
|
||||
* @param messages The session transcript, oldest first.
|
||||
* @param baselineId Id of the message the turn starts after.
|
||||
* @returns Whether an assistant message after the baseline is still streaming.
|
||||
*/
|
||||
export function hasIncompleteAssistant(
|
||||
messages: readonly SessionMessageInfo[],
|
||||
baselineId: string | null,
|
||||
@@ -358,17 +257,6 @@ export function hasIncompleteAssistant(
|
||||
.some((message) => message.type === 'assistant' && message.time.completed === undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether the session has finished the current turn. The turn is over
|
||||
* only when the session is idle, holds no prompt the user queued during it, and
|
||||
* has no reply still streaming, and when the turn showed activity — a busy
|
||||
* report or a message that was read aloud. Callers only ask once every eligible
|
||||
* message has been read, so an unread message keeps the turn open by
|
||||
* construction.
|
||||
*
|
||||
* @param input The session status and the turn's queued, streaming and spoken state.
|
||||
* @returns Whether the turn is over.
|
||||
*/
|
||||
export function isVoiceTurnComplete(input: VoiceTurnCompletionInput): boolean {
|
||||
return (
|
||||
input.status === 'idle' &&
|
||||
@@ -378,14 +266,6 @@ export function isVoiceTurnComplete(input: VoiceTurnCompletionInput): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces the short status text shown on the status line while a voice
|
||||
* conversation is active. The text never names the next action, so a single
|
||||
* line describes the phase without growing or shifting the bar.
|
||||
*
|
||||
* @param input The current phase, pause reason and session signals.
|
||||
* @returns The status to display, or an empty string when voice mode is off.
|
||||
*/
|
||||
export function voiceConversationLabel(input: VoiceConversationLabelInput): string {
|
||||
const { phase, pauseReason, pendingApproval, error, isStartingCapture } = input
|
||||
|
||||
@@ -411,13 +291,6 @@ export function voiceConversationLabel(input: VoiceConversationLabelInput): stri
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces the action hint shown directly under the conversation orb, which
|
||||
* names what a tap does in the current phase and state.
|
||||
*
|
||||
* @param input The current phase, pause reason and session signals.
|
||||
* @returns The hint to display, or an empty string when the orb has no action.
|
||||
*/
|
||||
export function voiceConversationHint(input: VoiceConversationLabelInput): string {
|
||||
const {
|
||||
phase,
|
||||
|
||||
@@ -1,65 +1,26 @@
|
||||
/** Storage key under which a device persists the pause-before-sending duration. */
|
||||
export const VOICE_PAUSE_STORAGE_KEY = 'voice.pauseBeforeSendingMs'
|
||||
|
||||
/**
|
||||
* Pause durations, in milliseconds, offered by the pause-before-sending picker.
|
||||
* A stored or requested value outside this list is treated as absent.
|
||||
*/
|
||||
export const VOICE_PAUSE_OPTIONS_MS = [800, 1200, 1600, 2000, 3000] as const
|
||||
|
||||
/**
|
||||
* Pause duration applied before the first stored value is hydrated, and the
|
||||
* value persisted when storage holds nothing usable.
|
||||
*/
|
||||
export const DEFAULT_VOICE_PAUSE_MS = 1200
|
||||
|
||||
/**
|
||||
* Fixed silence timeout, in milliseconds, that ends a hands-free voice turn.
|
||||
* Not user-adjustable and therefore independent of the pause preference.
|
||||
*/
|
||||
export const VOICE_NO_SPEECH_TIMEOUT_MS = 10_000
|
||||
|
||||
/**
|
||||
* Reports whether `value` is one of the selectable pause durations.
|
||||
*
|
||||
* @param value Candidate pause duration in milliseconds.
|
||||
* @returns Whether the value is offered by the pause-before-sending picker.
|
||||
*/
|
||||
const VOICE_PAUSE_OPTION_SET: ReadonlySet<number> = new Set(VOICE_PAUSE_OPTIONS_MS)
|
||||
|
||||
export function isVoicePauseOption(value: number): boolean {
|
||||
return (VOICE_PAUSE_OPTIONS_MS as readonly number[]).includes(value)
|
||||
return VOICE_PAUSE_OPTION_SET.has(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a stored pause duration. A value that is not one of
|
||||
* {@link VOICE_PAUSE_OPTIONS_MS} is treated as absent, so the caller keeps
|
||||
* {@link DEFAULT_VOICE_PAUSE_MS}.
|
||||
*
|
||||
* @param raw The stored string.
|
||||
* @returns The pause duration in milliseconds, or undefined when it is unusable.
|
||||
*/
|
||||
export function parseVoicePauseMs(raw: string): number | undefined {
|
||||
const ms = Number(raw)
|
||||
return isVoicePauseOption(ms) ? ms : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a requested pause duration. A value that is not one of
|
||||
* {@link VOICE_PAUSE_OPTIONS_MS} is rejected instead of being clamped.
|
||||
*
|
||||
* @param ms Requested pause duration in milliseconds.
|
||||
* @returns The pause duration in milliseconds, or undefined when it is unusable.
|
||||
*/
|
||||
export function normalizeVoicePauseMs(ms: number): number | undefined {
|
||||
return isVoicePauseOption(ms) ? ms : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a pause duration as the one-decimal seconds label used by the
|
||||
* pause-before-sending picker and the settings row.
|
||||
*
|
||||
* @param ms Pause duration in milliseconds.
|
||||
* @returns The label, for example `"1.2 s"` for 1200 milliseconds.
|
||||
*/
|
||||
export function formatVoicePauseMs(ms: number): string {
|
||||
return `${(ms / 1000).toFixed(1)} s`
|
||||
}
|
||||
@@ -28,11 +28,6 @@ function gitRemoteParts(host: string, name: string): string | undefined {
|
||||
return `${host.toLowerCase()}/${pathname}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a git remote URL into OpenCode's `host/path` identity form, or
|
||||
* returns undefined for unsupported remotes (e.g. `file:` URLs). Mirrors the
|
||||
* normalization in OpenCode's `ProjectV2.resolve`.
|
||||
*/
|
||||
export function normalizeGitRemote(input: string): string | undefined {
|
||||
const value = input.trim()
|
||||
if (!value) return undefined
|
||||
@@ -48,22 +43,12 @@ export function normalizeGitRemote(input: string): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the OpenCode remote-backed project ID for a git origin URL, or
|
||||
* undefined when the remote cannot be normalized.
|
||||
*/
|
||||
export function gitRemoteProjectId(originUrl: string): string | undefined {
|
||||
const normalized = normalizeGitRemote(originUrl)
|
||||
if (!normalized) return undefined
|
||||
return createHash('sha1').update(`git-remote:${normalized}`).digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the OpenCode project ID for a git working directory using the same
|
||||
* precedence OpenCode applies: normalized origin remote hash, then the cached
|
||||
* `<git-common-dir>/opencode` id, then the sorted first root commit. Returns
|
||||
* null when the directory is not a git repository or no id can be derived.
|
||||
*/
|
||||
export async function resolveOpenCodeProjectId(repoDir: string): Promise<string | null> {
|
||||
const worktree = await git(repoDir, ['rev-parse', '--show-toplevel'])
|
||||
if (!worktree) return null
|
||||
@@ -80,7 +65,6 @@ export async function resolveOpenCodeProjectId(repoDir: string): Promise<string
|
||||
const cached = (await readFile(path.join(commonDir, 'opencode'), 'utf-8')).trim()
|
||||
if (cached) return cached
|
||||
} catch {
|
||||
// cache file absent or unreadable
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,8 @@ export const OAUTH_ERROR_CODES = [
|
||||
|
||||
export type OAuthErrorCode = (typeof OAUTH_ERROR_CODES)[number];
|
||||
|
||||
const OAUTH_ERROR_CODE_SET: ReadonlySet<string> = new Set(OAUTH_ERROR_CODES);
|
||||
|
||||
export function isOAuthErrorCode(code: string): code is OAuthErrorCode {
|
||||
return (OAUTH_ERROR_CODES as readonly string[]).includes(code);
|
||||
return OAUTH_ERROR_CODE_SET.has(code);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { gitRefSchema } from './git'
|
||||
import { JsonValueSchema } from '../utils/json'
|
||||
|
||||
export const WALKTHROUGH_DIFF_MAX_CHARS = 60000;
|
||||
export const WALKTHROUGH_HUNK_MAX_CHARS = 8000;
|
||||
@@ -98,7 +99,11 @@ export function parseWalkthroughSourceKey(key: string): WalkthroughSource | null
|
||||
return null
|
||||
}
|
||||
|
||||
function parseWalkthroughSourceCandidate(candidate: unknown): WalkthroughSource | null {
|
||||
function parseWalkthroughSourceCandidate(candidate: {
|
||||
kind: WalkthroughSource['kind']
|
||||
base?: string
|
||||
number?: number
|
||||
}): WalkthroughSource | null {
|
||||
const parsed = WalkthroughSourceSchema.safeParse(candidate)
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
@@ -126,7 +131,7 @@ export type WalkthroughOmittedFile = z.infer<typeof WalkthroughOmittedFileSchema
|
||||
export const WalkthroughGenerationErrorSchema = z.object({
|
||||
message: z.string(),
|
||||
code: z.string().optional(),
|
||||
details: z.unknown().optional(),
|
||||
details: JsonValueSchema.optional(),
|
||||
});
|
||||
|
||||
export type WalkthroughGenerationError = z.infer<typeof WalkthroughGenerationErrorSchema>;
|
||||
|
||||
@@ -39,7 +39,6 @@ const BLOCKED_REMOTE_ACCESS_HEADER_NAMES = new Set([
|
||||
"cf-connecting-ip",
|
||||
]);
|
||||
|
||||
/** Reports whether a header name is reserved by the transport or uses the proxy- prefix. */
|
||||
export function isBlockedRemoteAccessHeaderName(name: string): boolean {
|
||||
const normalized = name.trim().toLowerCase();
|
||||
return BLOCKED_REMOTE_ACCESS_HEADER_NAMES.has(normalized) || normalized.startsWith("proxy-");
|
||||
@@ -80,7 +79,6 @@ export const RemoteAccessHeaderListSchema = z
|
||||
`Remote access headers are too long to fit in a QR code (limit ${REMOTE_ACCESS_HEADERS_MAX_ENCODED_LENGTH} encoded characters)`,
|
||||
);
|
||||
|
||||
/** Serializes a remote-access header into the `Name:Value` form carried by the link `h` parameter. */
|
||||
export function formatRemoteAccessHeaderParam(header: RemoteAccessHeader): string {
|
||||
return `${header.name}:${header.value}`;
|
||||
}
|
||||
@@ -190,19 +188,16 @@ export type PairedDevicesResponse = z.infer<typeof PairedDevicesResponseSchema>;
|
||||
export type DevicePairingErrorCode =
|
||||
(typeof DEVICE_PAIRING_ERROR_CODES)[keyof typeof DEVICE_PAIRING_ERROR_CODES];
|
||||
|
||||
/** Builds the browser pairing link whose code stays in the URL fragment. */
|
||||
export function buildManagerBrowserPairingLink(origin: string, code: string): string {
|
||||
return `${trimUrlTrailingSlashes(origin)}${DEVICE_PAIRING_PATH}#c=${encodeURIComponent(code)}`;
|
||||
}
|
||||
|
||||
/** Reads a pairing code from a URL fragment, or null when the fragment holds no valid code. */
|
||||
export function readPairingCodeFromHash(hash: string): string | null {
|
||||
const code = new URLSearchParams(hash.replace(/^#/, "")).get("c");
|
||||
const parsed = DevicePairingCodeSchema.safeParse(code);
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
/** Parses a browser pairing link into its origin and code, or null when the text is not one. */
|
||||
export function parseManagerBrowserPairingLink(text: string): { origin: string; code: string } | null {
|
||||
const url = parseHttpUrl(text.trim());
|
||||
if (!url) return null;
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const FileInfoSchema: z.ZodType<{
|
||||
name: string
|
||||
path: string
|
||||
isDirectory: boolean
|
||||
size: number
|
||||
mimeType?: string
|
||||
content?: string
|
||||
children?: Array<any>
|
||||
lastModified: Date
|
||||
totalLines?: number
|
||||
}> = z.object({
|
||||
export const FileInfoSchema = z.object({
|
||||
name: z.string(),
|
||||
path: z.string(),
|
||||
isDirectory: z.boolean(),
|
||||
size: z.number(),
|
||||
mimeType: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
children: z.lazy(() => z.array(FileInfoSchema)).optional(),
|
||||
lastModified: z.date(),
|
||||
get children() {
|
||||
return z.array(FileInfoSchema).optional()
|
||||
},
|
||||
lastModified: z.coerce.date(),
|
||||
workspaceRoot: z.string().optional(),
|
||||
totalLines: z.number().optional(),
|
||||
})
|
||||
|
||||
@@ -49,7 +42,7 @@ export const ChunkedFileInfoSchema = z.object({
|
||||
startLine: z.number(),
|
||||
endLine: z.number(),
|
||||
hasMore: z.boolean(),
|
||||
lastModified: z.date(),
|
||||
lastModified: z.coerce.date(),
|
||||
})
|
||||
|
||||
export const FileRangeRequestSchema = z.object({
|
||||
@@ -68,4 +61,3 @@ export const FilePatchRequestSchema = z.object({
|
||||
patches: z.array(PatchOperationSchema),
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { z } from 'zod'
|
||||
import { OPENCODE_LIFECYCLE_STATES, OPENCODE_RECOVERY_ACTIONS } from '../opencode/lifecycle'
|
||||
|
||||
const openCodeLifecycleStatusSchema = z.object({
|
||||
state: z.enum(OPENCODE_LIFECYCLE_STATES),
|
||||
healthy: z.boolean(),
|
||||
port: z.number(),
|
||||
version: z.string().nullable(),
|
||||
minVersion: z.string(),
|
||||
versionSupported: z.boolean(),
|
||||
lastError: z.string().nullable(),
|
||||
activeRecoveryAction: z.enum(OPENCODE_RECOVERY_ACTIONS).nullable(),
|
||||
attemptedRecoveryActions: z.array(z.enum(OPENCODE_RECOVERY_ACTIONS)),
|
||||
nextRecoveryAction: z.enum(OPENCODE_RECOVERY_ACTIONS).nullable(),
|
||||
failureCount: z.number(),
|
||||
watching: z.boolean(),
|
||||
updatedAt: z.string(),
|
||||
})
|
||||
|
||||
const healthSandboxStatusSchema = z.object({
|
||||
available: z.boolean(),
|
||||
enabled: z.boolean(),
|
||||
enforced: z.boolean(),
|
||||
reason: z.string().optional(),
|
||||
msbVersion: z.string().optional(),
|
||||
})
|
||||
|
||||
export const healthResponseSchema = z.object({
|
||||
status: z.enum(['healthy', 'degraded', 'unhealthy']),
|
||||
timestamp: z.string(),
|
||||
database: z.enum(['connected', 'disconnected']),
|
||||
opencode: z.enum(['healthy', 'unhealthy']),
|
||||
opencodePort: z.number(),
|
||||
opencodeVersion: z.string().nullable(),
|
||||
opencodeMinVersion: z.string(),
|
||||
opencodeVersionSupported: z.boolean(),
|
||||
opencodeManagerVersion: z.string().nullable(),
|
||||
opencodeRestartPending: z.boolean().optional(),
|
||||
opencodeLifecycle: openCodeLifecycleStatusSchema.optional(),
|
||||
sandbox: healthSandboxStatusSchema.optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
|
||||
export type HealthResponse = z.infer<typeof healthResponseSchema>
|
||||
@@ -24,3 +24,4 @@ export * from './change-walkthroughs'
|
||||
export * from './opencode-servers'
|
||||
export * from './secrets'
|
||||
export * from './device-pairing'
|
||||
export * from './health'
|
||||
@@ -83,10 +83,6 @@ export const AssistantNotificationResponseSchema = z.object({
|
||||
noSubscriptions: z.boolean(),
|
||||
})
|
||||
|
||||
// NOTE: These are defined as plain z.object (not .pick() from the full schemas)
|
||||
// so that .default() values from the source schemas are NOT inherited. A patch
|
||||
// like { voice: 'nova' } must produce only { voice: 'nova' } in the parsed output,
|
||||
// not { voice: 'nova', provider: 'external', autoPlay: false }.
|
||||
export const AssistantTTSPatchSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
provider: z.enum(['external', 'builtin']),
|
||||
|
||||
@@ -100,7 +100,6 @@ export type OpenCodeServerStatus = z.infer<typeof OpenCodeServerStatusSchema>;
|
||||
export type OpenCodeServerLink = z.infer<typeof OpenCodeServerLinkSchema>;
|
||||
export type ManagerAppLink = z.infer<typeof ManagerAppLinkSchema>;
|
||||
|
||||
/** Builds the `ocm://link` URL encoded into a pairing QR code. */
|
||||
export function buildOpenCodeServerLink(link: OpenCodeServerLink): string {
|
||||
const params = buildLinkParams(link);
|
||||
params.set("pair", link.pairing.pairUrl);
|
||||
@@ -108,14 +107,12 @@ export function buildOpenCodeServerLink(link: OpenCodeServerLink): string {
|
||||
return buildLinkUrl(params);
|
||||
}
|
||||
|
||||
/** Parses an `ocm://link` URL from a QR code or pasted text; returns null when it is not a valid link. */
|
||||
export function parseOpenCodeServerLink(text: string): OpenCodeServerLink | null {
|
||||
return readLink(OpenCodeServerLinkSchema, text, (url) => ({
|
||||
pairing: { pairUrl: url.searchParams.get("pair"), code: url.searchParams.get("code") },
|
||||
}));
|
||||
}
|
||||
|
||||
/** Builds the `ocm://link` URL for a manager app pairing QR code, including remote-access headers. */
|
||||
export function buildManagerAppLink(link: ManagerAppLink): string {
|
||||
const params = buildLinkParams(link);
|
||||
params.set("code", link.code);
|
||||
@@ -123,7 +120,6 @@ export function buildManagerAppLink(link: ManagerAppLink): string {
|
||||
return buildLinkUrl(params);
|
||||
}
|
||||
|
||||
/** Parses an `ocm://link` manager app link; returns null when it is not a valid manager link. */
|
||||
export function parseManagerAppLink(text: string): ManagerAppLink | null {
|
||||
return readLink(ManagerAppLinkSchema, text, (url) => {
|
||||
const headers: Array<{ name: string; value: string }> = [];
|
||||
@@ -136,7 +132,6 @@ export function parseManagerAppLink(text: string): ManagerAppLink | null {
|
||||
});
|
||||
}
|
||||
|
||||
/** Reads the `v` parameter of an `ocm://link` URL, or null when the text is not an `ocm://link` URL. */
|
||||
export function readOpenCodeServerLinkVersion(text: string): string | null {
|
||||
return parseOpenCodeServerLinkUrl(text)?.searchParams.get("v") ?? null;
|
||||
}
|
||||
@@ -186,10 +181,10 @@ function readLinkQueryFields(text: string): { url: URL; fields: LinkQueryFields
|
||||
};
|
||||
}
|
||||
|
||||
function readLink<T>(
|
||||
function readLink<T, Details extends object>(
|
||||
schema: z.ZodType<T>,
|
||||
text: string,
|
||||
readDetails: (url: URL) => Record<string, unknown> | null,
|
||||
readDetails: (url: URL) => Details | null,
|
||||
): T | null {
|
||||
const link = readLinkQueryFields(text);
|
||||
if (!link) return null;
|
||||
@@ -201,12 +196,10 @@ function readLink<T>(
|
||||
|
||||
const REMOTE_DIRECTORY_KEY_PATTERN = /^(srv_[A-Za-z0-9_-]+)\|(.+)$/s;
|
||||
|
||||
/** Builds the event-stream subscription key for a directory; local directories stay unchanged. */
|
||||
export function buildServerDirectoryKey(serverId: string, directory: string): string {
|
||||
return serverId === LOCAL_OPENCODE_SERVER_ID ? directory : `${serverId}|${directory}`;
|
||||
}
|
||||
|
||||
/** Splits an event-stream subscription key into its server id and directory. */
|
||||
export function parseServerDirectoryKey(key: string): { serverId: string; directory: string } {
|
||||
const match = REMOTE_DIRECTORY_KEY_PATTERN.exec(key);
|
||||
return match?.[1] && match[2] ? { serverId: match[1], directory: match[2] } : { serverId: LOCAL_OPENCODE_SERVER_ID, directory: key };
|
||||
|
||||
@@ -36,11 +36,13 @@ export const REPO_PROJECT_ENV_MAX_ENTRIES = 100
|
||||
|
||||
const REPO_PROJECT_ENV_RESERVED_NAMES = ['GH_TOKEN'] as const
|
||||
|
||||
const REPO_PROJECT_ENV_RESERVED_NAME_SET: ReadonlySet<string> = new Set(REPO_PROJECT_ENV_RESERVED_NAMES)
|
||||
|
||||
const REPO_PROJECT_ENV_RESERVED_PREFIXES = ['GITHUB_', 'GIT_'] as const
|
||||
|
||||
function isRepoProjectEnvGitReserved(name: string): boolean {
|
||||
const normalized = name.toUpperCase()
|
||||
if ((REPO_PROJECT_ENV_RESERVED_NAMES as readonly string[]).includes(normalized)) return true
|
||||
if (REPO_PROJECT_ENV_RESERVED_NAME_SET.has(normalized)) return true
|
||||
return REPO_PROJECT_ENV_RESERVED_PREFIXES.some((prefix) => normalized.startsWith(prefix))
|
||||
}
|
||||
|
||||
|
||||
@@ -10,28 +10,12 @@ export type ScheduleRunStatus = z.infer<typeof ScheduleRunStatusSchema>
|
||||
export const ScheduleModeSchema = z.enum(['interval', 'cron'])
|
||||
export type ScheduleMode = z.infer<typeof ScheduleModeSchema>
|
||||
|
||||
/**
|
||||
* Where a scheduled run executes. `worktree` gives every run a fresh worktree that is
|
||||
* removed when the run ends, `kept-worktree` keeps each run's worktree afterwards, and
|
||||
* `shared-worktree` reuses one worktree and branch for every run of the schedule.
|
||||
* `in-place` runs directly in the target directory and is the only mode available for a
|
||||
* project on a linked remote OpenCode server, which has no local checkout to branch from.
|
||||
*/
|
||||
export const ScheduleWorkspaceModeSchema = z.enum(['worktree', 'kept-worktree', 'shared-worktree', 'in-place'])
|
||||
export type ScheduleWorkspaceMode = z.infer<typeof ScheduleWorkspaceModeSchema>
|
||||
|
||||
/**
|
||||
* What clearing run history does with the run worktrees that still exist on disk.
|
||||
* `commit` commits their pending changes to their branches and keeps those branches;
|
||||
* `discard` force-removes the worktrees and deletes their branches.
|
||||
*/
|
||||
export const ScheduleRunWorktreesModeSchema = z.enum(['commit', 'discard']).default('commit')
|
||||
export type ScheduleRunWorktreesMode = z.infer<typeof ScheduleRunWorktreesModeSchema>
|
||||
|
||||
/**
|
||||
* A schedule worktree that still exists on disk. `runId` is null for the schedule's
|
||||
* shared worktree, and `inUse` is true while a running run is working in it.
|
||||
*/
|
||||
export const ScheduleWorktreeSchema = z.object({
|
||||
worktreePath: z.string(),
|
||||
branch: z.string(),
|
||||
@@ -91,11 +75,6 @@ export const ScheduleMcpServerConfigSchema = z.discriminatedUnion('type', [
|
||||
])
|
||||
export type ScheduleMcpServerConfig = z.infer<typeof ScheduleMcpServerConfigSchema>
|
||||
|
||||
/**
|
||||
* An MCP server attached to a schedule. Without `config` it names a server from
|
||||
* the OpenCode configuration, which is connected for the run even when disabled.
|
||||
* With `config` it is a schedule-only server added to the run's location.
|
||||
*/
|
||||
export const ScheduleMcpServerSchema = z.object({
|
||||
name: z.string().trim().min(1).max(100),
|
||||
config: ScheduleMcpServerConfigSchema.optional(),
|
||||
@@ -107,13 +86,6 @@ export const ScheduleMcpServersSchema = z.array(ScheduleMcpServerSchema).max(50)
|
||||
{ message: 'MCP server names must be unique' },
|
||||
)
|
||||
|
||||
/**
|
||||
* Bash commands whose blast radius escapes the throwaway worktree: host-level
|
||||
* commands that damage the machine regardless of cwd, plus force-pushes that can
|
||||
* overwrite remote branches. File-mutating commands (`rm -rf`, `git reset --hard`,
|
||||
* etc.) are intentionally omitted — they only affect the disposable worktree, which
|
||||
* is never auto-pushed and is the real safety boundary.
|
||||
*/
|
||||
export const DEFAULT_DESTRUCTIVE_BASH_PATTERNS = [
|
||||
'git push --force*', 'git push -f *',
|
||||
'sudo *', 'dd *', 'mkfs*',
|
||||
@@ -129,10 +101,6 @@ export const SchedulePermissionConfigSchema = z.object({
|
||||
})
|
||||
export type SchedulePermissionConfig = z.infer<typeof SchedulePermissionConfigSchema>
|
||||
|
||||
/**
|
||||
* Sandbox settings for a scheduled run's session. `resources` overrides the
|
||||
* default CPU and memory limits; null keeps the server defaults.
|
||||
*/
|
||||
export const ScheduleSandboxConfigSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
resources: SessionSandboxResourcesSchema.nullable(),
|
||||
@@ -141,11 +109,6 @@ export type ScheduleSandboxConfig = z.infer<typeof ScheduleSandboxConfigSchema>
|
||||
|
||||
export type SchedulePermissionEffect = 'allow' | 'deny' | 'ask'
|
||||
|
||||
/**
|
||||
* A single OpenCode 2 session permission rule. `action` is the tool or permission
|
||||
* action (e.g. `shell`, `external_directory`, or `*` for all), `resource` is the
|
||||
* glob matched against the tool argument, and `effect` is the resulting decision.
|
||||
*/
|
||||
export interface SchedulePermissionRule {
|
||||
action: string
|
||||
resource: string
|
||||
@@ -154,17 +117,6 @@ export interface SchedulePermissionRule {
|
||||
|
||||
export type SchedulePermissionRuleset = SchedulePermissionRule[]
|
||||
|
||||
/**
|
||||
* Builds the OpenCode session permission ruleset for an unattended scheduled run.
|
||||
*
|
||||
* OpenCode's `POST /session` `permissions` field expects an ordered array of
|
||||
* `{ action, resource, effect }` rules (`Permission.Ruleset`), evaluated with
|
||||
* last-match-wins semantics (see https://opencode.ai/docs/permissions).
|
||||
* A leading `*`/`*` allow rule sets the allow-all baseline; the trailing
|
||||
* `external_directory`, `question` and `shell` deny rules then override it for
|
||||
* external directory access, agent questions that would block an unattended run
|
||||
* with nobody to answer them, and matching destructive command patterns.
|
||||
*/
|
||||
export function buildSchedulePermissionRuleset(
|
||||
config: SchedulePermissionConfig | null | undefined,
|
||||
): SchedulePermissionRuleset {
|
||||
@@ -190,11 +142,6 @@ export const ScheduleJobSchema = z.object({
|
||||
name: z.string(),
|
||||
description: z.string().nullable(),
|
||||
enabled: z.boolean(),
|
||||
/**
|
||||
* Whether finished runs of this schedule appear in the inbox. `false` stores successful
|
||||
* runs as already viewed and skips their completion push, while failed runs are still
|
||||
* announced.
|
||||
*/
|
||||
showInInbox: z.boolean(),
|
||||
scheduleMode: ScheduleModeSchema,
|
||||
intervalMinutes: z.number().int().min(5).max(10080).nullable(),
|
||||
@@ -242,11 +189,6 @@ const ScheduleJobBaseRequestSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
description: z.string().max(500).optional(),
|
||||
enabled: z.boolean().default(true),
|
||||
/**
|
||||
* Whether finished runs of this schedule appear in the inbox. `false` stores successful
|
||||
* runs as already viewed and skips their completion push, while failed runs are still
|
||||
* announced.
|
||||
*/
|
||||
showInInbox: z.boolean().default(true),
|
||||
agentSlug: z.string().min(1).max(100).optional(),
|
||||
prompt: z.string().min(1).max(20000),
|
||||
@@ -277,11 +219,6 @@ export const UpdateScheduleJobRequestSchema = z.object({
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(500).nullable().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
/**
|
||||
* Whether finished runs of this schedule appear in the inbox. `false` stores successful
|
||||
* runs as already viewed and skips their completion push, while failed runs are still
|
||||
* announced.
|
||||
*/
|
||||
showInInbox: z.boolean().optional(),
|
||||
scheduleMode: ScheduleModeSchema.optional(),
|
||||
intervalMinutes: z.number().int().min(5).max(10080).nullable().optional(),
|
||||
|
||||
@@ -11,21 +11,18 @@ export const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
|
||||
|
||||
const RESERVED_ENV_PREFIXES = ['OCM_', 'OPENCODE_', 'GIT_CONFIG_', 'MSB_', 'LD_'] as const
|
||||
|
||||
/**
|
||||
* Prefixes the sandbox owns: a plan-provided or forwarded variable using one of
|
||||
* them could replace the sandbox control variables, so they never cross into a
|
||||
* microVM from a plan.
|
||||
*/
|
||||
export const SANDBOX_CONTROL_ENV_PREFIXES = ['OCM_', 'MSB_'] as const satisfies readonly (typeof RESERVED_ENV_PREFIXES)[number][]
|
||||
|
||||
const RESERVED_ENV_NAMES = ['PATH', 'HOME', 'NODE_OPTIONS'] as const
|
||||
|
||||
const RESERVED_ENV_NAME_SET: ReadonlySet<string> = new Set(RESERVED_ENV_NAMES)
|
||||
|
||||
const BLOCKED_ENV_NAMES = new Set<string>(BLOCKED_SERVER_ENV_KEYS)
|
||||
|
||||
export function isReservedEnvName(name: string): boolean {
|
||||
const normalized = name.toUpperCase()
|
||||
if (BLOCKED_ENV_NAMES.has(normalized)) return true
|
||||
if ((RESERVED_ENV_NAMES as readonly string[]).includes(normalized)) return true
|
||||
if (RESERVED_ENV_NAME_SET.has(normalized)) return true
|
||||
return RESERVED_ENV_PREFIXES.some((prefix) => normalized.startsWith(prefix))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const SessionSandboxCpusSchema = z.number().int().min(1).max(64);
|
||||
|
||||
export const SessionSandboxMemoryMibSchema = z.number().int().min(1024).max(1048576);
|
||||
|
||||
export const SessionSandboxResourcesSchema = z.object({
|
||||
cpus: z.number().int().min(1).max(64),
|
||||
memoryMib: z.number().int().min(1024).max(1048576),
|
||||
cpus: SessionSandboxCpusSchema,
|
||||
memoryMib: SessionSandboxMemoryMibSchema,
|
||||
});
|
||||
|
||||
export type SessionSandboxResources = z.infer<typeof SessionSandboxResourcesSchema>;
|
||||
|
||||
@@ -3,7 +3,8 @@ import { NotificationPreferencesSchema, DEFAULT_NOTIFICATION_PREFERENCES } from
|
||||
import { OPENCODE_CONFIG_SOURCE_NAMES } from "../config/defaults";
|
||||
import { ColorThemeIdSchema, MANAGER_COLOR_THEME_ID } from "../themes";
|
||||
import { SessionPermissionModeSchema } from "./session-permissions";
|
||||
import { SessionSandboxResourcesSchema } from "./session-sandbox";
|
||||
import { SessionSandboxCpusSchema, SessionSandboxMemoryMibSchema } from "./session-sandbox";
|
||||
import { JsonObjectSchema, type JsonValue } from "../utils/json";
|
||||
|
||||
export const CustomCommandSchema = z.object({
|
||||
name: z.string(),
|
||||
@@ -73,7 +74,7 @@ export type ActivityWindowMinutes = z.infer<typeof ActivityWindowMinutesSchema>;
|
||||
|
||||
export const DEFAULT_ACTIVITY_WINDOW_MINUTES: ActivityWindowMinutes = 30;
|
||||
|
||||
export function isActivityWindowMinutes(value: unknown): value is ActivityWindowMinutes {
|
||||
export function isActivityWindowMinutes(value: JsonValue | undefined): value is ActivityWindowMinutes {
|
||||
return ActivityWindowMinutesSchema.safeParse(value).success;
|
||||
}
|
||||
|
||||
@@ -148,8 +149,6 @@ export const ServerEnvVarSchema = z.object({
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
type ServerEnvVar = z.infer<typeof ServerEnvVarSchema>
|
||||
|
||||
export const BLOCKED_SERVER_ENV_KEYS = [
|
||||
'OPENCODE_PASSWORD',
|
||||
'OPENCODE_SERVER_PASSWORD',
|
||||
@@ -174,8 +173,8 @@ export const SandboxPreferencesSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
gitCredentials: z.boolean().optional(),
|
||||
defaultForNewSessions: z.boolean().optional(),
|
||||
cpus: SessionSandboxResourcesSchema.shape.cpus.optional(),
|
||||
memoryMib: SessionSandboxResourcesSchema.shape.memoryMib.optional(),
|
||||
cpus: SessionSandboxCpusSchema.optional(),
|
||||
memoryMib: SessionSandboxMemoryMibSchema.optional(),
|
||||
idleStopMinutes: z.number().int().min(1).max(1440).optional(),
|
||||
maxRunningVms: z.number().int().min(1).max(32).optional(),
|
||||
});
|
||||
@@ -278,17 +277,17 @@ export const DEFAULT_USER_PREFERENCES = {
|
||||
groupToolCalls: true,
|
||||
showReasoning: false,
|
||||
simpleChatMode: false,
|
||||
keyboardShortcuts: {} as Record<string, string>,
|
||||
keyboardShortcuts: {},
|
||||
customCommands: [],
|
||||
customAgents: [],
|
||||
gitCredentials: [] as GitCredential[],
|
||||
defaultGitCredentialId: undefined as string | undefined,
|
||||
gitCredentials: [],
|
||||
defaultGitCredentialId: undefined,
|
||||
gitIdentity: DEFAULT_GIT_IDENTITY,
|
||||
tts: DEFAULT_TTS_CONFIG,
|
||||
stt: DEFAULT_STT_CONFIG,
|
||||
notifications: DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
repoSortMode: 'recent' as const,
|
||||
serverEnvVars: [] as ServerEnvVar[],
|
||||
serverEnvVars: [],
|
||||
sandbox: DEFAULT_SANDBOX_PREFERENCES,
|
||||
sessionDefaults: DEFAULT_SESSION_DEFAULTS,
|
||||
};
|
||||
@@ -313,7 +312,7 @@ export const OpenCodeConfigSourceFileSchema = z.object({
|
||||
name: OpenCodeConfigSourceNameSchema,
|
||||
path: z.string(),
|
||||
rawContent: z.string(),
|
||||
content: z.record(z.string(), z.unknown()),
|
||||
content: JsonObjectSchema,
|
||||
isValid: z.boolean(),
|
||||
validationIssues: z.array(OpenCodeConfigValidationIssueSchema).optional(),
|
||||
updatedAt: z.number(),
|
||||
@@ -321,7 +320,7 @@ export const OpenCodeConfigSourceFileSchema = z.object({
|
||||
|
||||
export const OpenCodeConfigFileSchema = z.object({
|
||||
path: z.string(),
|
||||
content: z.record(z.string(), z.unknown()),
|
||||
content: JsonObjectSchema,
|
||||
rawContent: z.string(),
|
||||
isValid: z.boolean(),
|
||||
validationIssues: z.array(OpenCodeConfigValidationIssueSchema).optional(),
|
||||
@@ -331,13 +330,13 @@ export const OpenCodeConfigFileSchema = z.object({
|
||||
});
|
||||
|
||||
export const UpdateOpenCodeConfigRequestSchema = z.object({
|
||||
content: z.union([z.record(z.string(), z.unknown()), z.string()]),
|
||||
content: z.union([JsonObjectSchema, z.string()]),
|
||||
source: OpenCodeConfigSourceNameSchema.optional(),
|
||||
expectedRevision: z.string().optional(),
|
||||
});
|
||||
|
||||
export const UpdateOpenCodeConfigPatchRequestSchema = z.object({
|
||||
patch: z.record(z.string(), z.unknown()),
|
||||
patch: JsonObjectSchema,
|
||||
source: OpenCodeConfigSourceNameSchema.optional(),
|
||||
expectedRevision: z.string().optional(),
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from 'zod'
|
||||
import { OPENCODE_THEMES } from './opencode-palettes'
|
||||
import type { JsonValue } from '../utils/json'
|
||||
import type { OpenCodeThemeDefinition } from './types'
|
||||
|
||||
export type { HexColor } from './types'
|
||||
@@ -10,8 +11,13 @@ export const MANAGER_COLOR_THEME_ID = 'manager' as const
|
||||
type OpenCodeThemeId = (typeof OPENCODE_THEMES)[number]['id']
|
||||
export type ColorThemeId = typeof MANAGER_COLOR_THEME_ID | OpenCodeThemeId
|
||||
|
||||
export function isColorThemeId(value: unknown): value is ColorThemeId {
|
||||
return value === MANAGER_COLOR_THEME_ID || OPENCODE_THEMES.some((theme) => theme.id === value)
|
||||
const COLOR_THEME_ID_LIST = [MANAGER_COLOR_THEME_ID, ...OPENCODE_THEMES.map((theme) => theme.id)] as const
|
||||
|
||||
const COLOR_THEME_IDS: ReadonlySet<string> = new Set<string>(COLOR_THEME_ID_LIST)
|
||||
|
||||
export function isColorThemeId(value: JsonValue | undefined): value is ColorThemeId {
|
||||
const id = z.string().safeParse(value)
|
||||
return id.success && COLOR_THEME_IDS.has(id.data)
|
||||
}
|
||||
|
||||
export function getOpenCodeTheme(id: ColorThemeId): OpenCodeThemeDefinition | undefined {
|
||||
@@ -19,6 +25,4 @@ export function getOpenCodeTheme(id: ColorThemeId): OpenCodeThemeDefinition | un
|
||||
return OPENCODE_THEMES.find((theme) => theme.id === id)
|
||||
}
|
||||
|
||||
export const ColorThemeIdSchema: z.ZodType<ColorThemeId> = z.custom<ColorThemeId>(isColorThemeId, {
|
||||
message: 'Unknown color theme',
|
||||
})
|
||||
export const ColorThemeIdSchema = z.enum(COLOR_THEME_ID_LIST)
|
||||
@@ -16,8 +16,9 @@ const ENV_EXPRESSION_PATTERN = /\$\{\{([\s\S]*?)\}\}/g
|
||||
const ENV_EXPRESSION_REFERENCE_PATTERN = /^\s*(secrets|vars)\.(\S+)\s*$/i
|
||||
|
||||
function toReference(match: RegExpExecArray): EnvExpressionReference {
|
||||
const context = (match[1] ?? '').toLowerCase()
|
||||
return {
|
||||
context: (match[1] ?? '').toLowerCase() as EnvExpressionContext,
|
||||
context: context === 'vars' ? 'vars' : 'secrets',
|
||||
name: (match[2] ?? '').toUpperCase(),
|
||||
}
|
||||
}
|
||||
@@ -28,11 +29,6 @@ function matchReference(inner: string): EnvExpressionReference | null {
|
||||
return toReference(match)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses every `${{ ... }}` occurrence in a value, accepting only
|
||||
* `secrets.<NAME>` and `vars.<NAME>` references. The context is
|
||||
* case-insensitive and the name is normalized to upper case.
|
||||
*/
|
||||
export function parseEnvExpressionReferences(value: string): ParseEnvExpressionReferencesResult {
|
||||
const references: EnvExpressionReference[] = []
|
||||
|
||||
@@ -50,16 +46,10 @@ export function parseEnvExpressionReferences(value: string): ParseEnvExpressionR
|
||||
return { ok: true, references }
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces every `${{ secrets.<NAME> }}` / `${{ vars.<NAME> }}` occurrence with
|
||||
* the value returned by `lookup`. A reference that resolves to `undefined`
|
||||
* becomes an empty string, matching GitHub Actions. Unsupported expressions and
|
||||
* expressions with an invalid name are left untouched.
|
||||
*/
|
||||
export function interpolateEnvExpressions(
|
||||
value: string,
|
||||
lookup: (reference: EnvExpressionReference) => string | undefined,
|
||||
): { value: string } {
|
||||
) {
|
||||
const interpolated = value.replace(ENV_EXPRESSION_PATTERN, (expression, inner: string) => {
|
||||
const reference = matchReference(inner)
|
||||
if (!reference) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export * from './env-expressions'
|
||||
export * from './json'
|
||||
export * from './jsonc'
|
||||
export * from './record'
|
||||
export * from './repo'
|
||||
export * from './sandbox-command'
|
||||
export * from './semver'
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject
|
||||
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue
|
||||
}
|
||||
|
||||
export interface JsonContainer {
|
||||
[key: string]: JsonValue | undefined
|
||||
}
|
||||
|
||||
export const JsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
|
||||
z.union([
|
||||
z.null(),
|
||||
z.boolean(),
|
||||
z.number(),
|
||||
z.string(),
|
||||
z.array(JsonValueSchema),
|
||||
JsonObjectSchema,
|
||||
]),
|
||||
)
|
||||
|
||||
export const JsonObjectSchema: z.ZodType<JsonObject> = z.record(z.string(), JsonValueSchema)
|
||||
|
||||
export const JsonContainerSchema: z.ZodType<JsonContainer> = z.record(
|
||||
z.string(),
|
||||
z.union([JsonValueSchema, z.undefined()]),
|
||||
)
|
||||
|
||||
export function isJsonContainer(value: JsonValue | JsonContainer | undefined): value is JsonContainer {
|
||||
return JsonContainerSchema.safeParse(value).success
|
||||
}
|
||||
|
||||
export function parseJsonObject(value: JsonValue | undefined): JsonObject | null {
|
||||
const parsed = JsonObjectSchema.safeParse(value)
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
|
||||
export function parseJsonString(value: JsonValue | undefined): string | null {
|
||||
const parsed = z.string().safeParse(value)
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
|
||||
export function parseJsonText(text: string): JsonValue | null {
|
||||
try {
|
||||
const parsed = JsonValueSchema.safeParse(JSON.parse(text))
|
||||
return parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
+19
-18
@@ -1,6 +1,7 @@
|
||||
import { parse as parseJsoncLib, parseTree, findNodeAtLocation, type ParseError, type JSONPath } from 'jsonc-parser/lib/esm/main.js'
|
||||
import { JsonValueSchema, type JsonValue } from './json'
|
||||
|
||||
export function parseJsonc<T = unknown>(content: string): T {
|
||||
export function parseJsonc(content: string): JsonValue {
|
||||
const errors: ParseError[] = []
|
||||
const result = parseJsoncLib(content, errors, {
|
||||
allowTrailingComma: true,
|
||||
@@ -13,7 +14,7 @@ export function parseJsonc<T = unknown>(content: string): T {
|
||||
throw new SyntaxError(message)
|
||||
}
|
||||
|
||||
return result as T
|
||||
return JsonValueSchema.parse(result)
|
||||
}
|
||||
|
||||
export function getParseErrorMessage(error: number, content: string, offset: number | undefined): string {
|
||||
@@ -28,25 +29,25 @@ export function getParseErrorMessage(error: number, content: string, offset: num
|
||||
return `${message} at line ${line}, column ${col}`
|
||||
}
|
||||
|
||||
function getErrorMessageByCode(error: number): string {
|
||||
const errorMessages: Record<number, string> = {
|
||||
1: 'Invalid symbol',
|
||||
2: 'Invalid number format',
|
||||
3: 'Property name expected',
|
||||
4: 'Value expected',
|
||||
5: 'Colon expected',
|
||||
6: 'Comma expected',
|
||||
7: 'Trailing comma not allowed',
|
||||
8: 'Unexpected end of input',
|
||||
9: 'Invalid comment',
|
||||
}
|
||||
const JSONC_ERROR_MESSAGES = new Map<number, string>([
|
||||
[1, 'Invalid symbol'],
|
||||
[2, 'Invalid number format'],
|
||||
[3, 'Property name expected'],
|
||||
[4, 'Value expected'],
|
||||
[5, 'Colon expected'],
|
||||
[6, 'Comma expected'],
|
||||
[7, 'Trailing comma not allowed'],
|
||||
[8, 'Unexpected end of input'],
|
||||
[9, 'Invalid comment'],
|
||||
])
|
||||
|
||||
return errorMessages[error] || 'Invalid JSONC'
|
||||
function getErrorMessageByCode(error: number): string {
|
||||
return JSONC_ERROR_MESSAGES.get(error) || 'Invalid JSONC'
|
||||
}
|
||||
|
||||
export function parseJsoncErrorLine(error: unknown): number | null {
|
||||
if (!(error instanceof SyntaxError)) return null
|
||||
const match = error.message.match(/at line (\d+)/)
|
||||
export function parseJsoncErrorLine(cause: unknown): number | null {
|
||||
if (!(cause instanceof SyntaxError)) return null
|
||||
const match = cause.message.match(/at line (\d+)/)
|
||||
return match ? Number(match[1]) : null
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
@@ -93,15 +93,8 @@ export function getBranchNameError(name: string): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Who owns a repo worktree: OpenCode, a schedule, or nobody (a plain git worktree).
|
||||
*/
|
||||
export type RepoWorktreeSource = 'opencode' | 'schedule' | 'git'
|
||||
|
||||
/**
|
||||
* The schedule a worktree belongs to. `runId` is null for the schedule's shared worktree,
|
||||
* `inUse` is true while a running run works in it, and `name` is the schedule's display name.
|
||||
*/
|
||||
export interface RepoWorktreeSchedule {
|
||||
repoId: number
|
||||
jobId: number
|
||||
@@ -110,10 +103,6 @@ export interface RepoWorktreeSchedule {
|
||||
name: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A repository visible from another repository in the same project: the repo itself, a plain
|
||||
* git or OpenCode worktree, or a schedule worktree.
|
||||
*/
|
||||
export type RepoSibling = Repo & {
|
||||
currentBranch?: string
|
||||
worktreeSource?: RepoWorktreeSource
|
||||
|
||||
+26
-10
@@ -1,3 +1,5 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export type SemverPrereleaseIdentifier = number | string
|
||||
|
||||
export interface Semver {
|
||||
@@ -27,26 +29,40 @@ export function parseSemver(version: string): Semver | null {
|
||||
}
|
||||
}
|
||||
|
||||
type PrereleaseIdentifierKind =
|
||||
| { kind: 'numeric'; value: number }
|
||||
| { kind: 'text'; value: string }
|
||||
|
||||
function classifyPrereleaseIdentifier(identifier: SemverPrereleaseIdentifier): PrereleaseIdentifierKind {
|
||||
const numeric = z.number().safeParse(identifier)
|
||||
return numeric.success ? { kind: 'numeric', value: numeric.data } : { kind: 'text', value: String(identifier) }
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifiers(
|
||||
left: SemverPrereleaseIdentifier[],
|
||||
right: SemverPrereleaseIdentifier[],
|
||||
): number {
|
||||
if (left.length === 0 || right.length === 0) return right.length - left.length
|
||||
|
||||
for (let index = 0; index < Math.max(left.length, right.length); index++) {
|
||||
const leftIdentifier = left[index]
|
||||
const rightIdentifier = right[index]
|
||||
const leftIdentifiers = left.map(classifyPrereleaseIdentifier)
|
||||
const rightIdentifiers = right.map(classifyPrereleaseIdentifier)
|
||||
|
||||
for (let index = 0; index < Math.max(leftIdentifiers.length, rightIdentifiers.length); index++) {
|
||||
const leftIdentifier = leftIdentifiers[index]
|
||||
const rightIdentifier = rightIdentifiers[index]
|
||||
|
||||
if (leftIdentifier === undefined) return -1
|
||||
if (rightIdentifier === undefined) return 1
|
||||
if (leftIdentifier === rightIdentifier) continue
|
||||
|
||||
const leftNumeric = typeof leftIdentifier === 'number'
|
||||
const rightNumeric = typeof rightIdentifier === 'number'
|
||||
if (leftNumeric && rightNumeric) return leftIdentifier > rightIdentifier ? 1 : -1
|
||||
if (leftNumeric) return -1
|
||||
if (rightNumeric) return 1
|
||||
return leftIdentifier > rightIdentifier ? 1 : -1
|
||||
if (leftIdentifier.kind === 'numeric' && rightIdentifier.kind === 'numeric') {
|
||||
if (leftIdentifier.value !== rightIdentifier.value) return leftIdentifier.value > rightIdentifier.value ? 1 : -1
|
||||
continue
|
||||
}
|
||||
if (leftIdentifier.kind === 'text' && rightIdentifier.kind === 'text') {
|
||||
if (leftIdentifier.value !== rightIdentifier.value) return leftIdentifier.value > rightIdentifier.value ? 1 : -1
|
||||
continue
|
||||
}
|
||||
return leftIdentifier.kind === 'numeric' ? -1 : 1
|
||||
}
|
||||
|
||||
return 0
|
||||
|
||||
@@ -92,7 +92,12 @@ export function parseDiffLines(diff: string): DiffLine[] {
|
||||
return result;
|
||||
}
|
||||
|
||||
export function countDiffLineChanges(text: string): { added: number; removed: number } {
|
||||
export interface DiffLineChangeCount {
|
||||
added: number
|
||||
removed: number
|
||||
}
|
||||
|
||||
export function countDiffLineChanges(text: string): DiffLineChangeCount {
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
for (const line of parseDiffLines(text)) {
|
||||
@@ -181,17 +186,17 @@ function stripDiffPathPrefix(path: string, prefix: string): string {
|
||||
return path.startsWith(prefix) ? path.slice(prefix.length) : path;
|
||||
}
|
||||
|
||||
const GIT_C_ESCAPES: Record<string, number> = {
|
||||
a: 0x07,
|
||||
b: 0x08,
|
||||
f: 0x0c,
|
||||
n: 0x0a,
|
||||
r: 0x0d,
|
||||
t: 0x09,
|
||||
v: 0x0b,
|
||||
"\\": 0x5c,
|
||||
'"': 0x22,
|
||||
};
|
||||
const GIT_C_ESCAPES = new Map<string, number>([
|
||||
["a", 0x07],
|
||||
["b", 0x08],
|
||||
["f", 0x0c],
|
||||
["n", 0x0a],
|
||||
["r", 0x0d],
|
||||
["t", 0x09],
|
||||
["v", 0x0b],
|
||||
["\\", 0x5c],
|
||||
['"', 0x22],
|
||||
])
|
||||
|
||||
function parseDiffPathToken(raw: string, prefix: string): string {
|
||||
const token = raw.startsWith('"') ? decodeGitQuotedPath(raw) : raw.split("\t")[0]!;
|
||||
@@ -219,7 +224,7 @@ function decodeGitQuotedPath(raw: string): string {
|
||||
if (next === undefined) {
|
||||
break;
|
||||
}
|
||||
const escaped = GIT_C_ESCAPES[next];
|
||||
const escaped = GIT_C_ESCAPES.get(next);
|
||||
bytes.push(...(escaped === undefined ? encoder.encode(next) : [escaped]));
|
||||
index += 2;
|
||||
continue;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
/** Trims a URL and removes its trailing slashes. */
|
||||
export function trimUrlTrailingSlashes(url: string): string {
|
||||
return url.trim().replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
/** Parses a value into a URL, or returns null when it is not an absolute http(s) URL. */
|
||||
export function parseHttpUrl(value: string): URL | null {
|
||||
let url: URL
|
||||
try {
|
||||
@@ -15,13 +13,11 @@ export function parseHttpUrl(value: string): URL | null {
|
||||
return url
|
||||
}
|
||||
|
||||
/** Reports whether two URLs share the same origin; false when either URL is invalid. */
|
||||
export function haveSameUrlOrigin(first: string, second: string): boolean {
|
||||
const origin = readUrlOrigin(first)
|
||||
return origin !== null && origin === readUrlOrigin(second)
|
||||
}
|
||||
|
||||
/** Reports whether a hostname refers to the local machine. */
|
||||
export function isLoopbackHost(hostname: string): boolean {
|
||||
const host = normalizeHostname(hostname)
|
||||
if (host === 'localhost' || host === '::1') return true
|
||||
@@ -29,7 +25,6 @@ export function isLoopbackHost(hostname: string): boolean {
|
||||
return octets !== null && octets[0] === 127
|
||||
}
|
||||
|
||||
/** Reports whether a hostname is an RFC 1918, link-local, or CGNAT address. */
|
||||
export function isPrivateNetworkHost(hostname: string): boolean {
|
||||
const host = normalizeHostname(hostname)
|
||||
const octets = parseIpv4Octets(host)
|
||||
@@ -48,7 +43,6 @@ export function isPrivateNetworkHost(hostname: string): boolean {
|
||||
return firstHextet >= 0xfc00 && firstHextet <= 0xfdff
|
||||
}
|
||||
|
||||
/** Reports whether a URL uses plain HTTP on a host other than loopback or a private network. */
|
||||
export function isPublicPlainHttpUrl(url: URL): boolean {
|
||||
return (
|
||||
url.protocol === 'http:' &&
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
const UNKNOWN_DEVICE = 'Unknown device'
|
||||
const RAW_USER_AGENT_MAX_LENGTH = 80
|
||||
|
||||
/** Describes a user agent as "browser on platform", falling back to the raw string. */
|
||||
export function describeUserAgent(userAgent: string | null | undefined): string {
|
||||
const value = userAgent?.trim()
|
||||
if (!value) return UNKNOWN_DEVICE
|
||||
|
||||
Reference in new issue
Block a user