@xortex/xcode 3.1.1 → 3.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ import memoize from 'lodash-es/memoize.js'
2
+ import { basename } from 'path'
3
+ import type { OutputStyleConfig } from '../constants/outputStyles.js'
4
+ import { logForDebugging } from '../utils/debug.js'
5
+ import { coerceDescriptionToString } from '../utils/frontmatterParser.js'
6
+ import { logError } from '../utils/log.js'
7
+ import {
8
+ extractDescriptionFromMarkdown,
9
+ loadMarkdownFilesForSubdir,
10
+ } from '../utils/markdownConfigLoader.js'
11
+ import { clearPluginOutputStyleCache } from '../utils/plugins/loadPluginOutputStyles.js'
12
+
13
+ /**
14
+ * Loads markdown files from .claude/output-styles directories throughout the project
15
+ * and from ~/.claude/output-styles directory and converts them to output styles.
16
+ *
17
+ * Each filename becomes a style name, and the file content becomes the style prompt.
18
+ * The frontmatter provides name and description.
19
+ *
20
+ * Structure:
21
+ * - Project .claude/output-styles/*.md -> project styles
22
+ * - User ~/.claude/output-styles/*.md -> user styles (overridden by project styles)
23
+ *
24
+ * @param cwd Current working directory for project directory traversal
25
+ */
26
+ export const getOutputStyleDirStyles = memoize(
27
+ async (cwd: string): Promise<OutputStyleConfig[]> => {
28
+ try {
29
+ const markdownFiles = await loadMarkdownFilesForSubdir(
30
+ 'output-styles',
31
+ cwd,
32
+ )
33
+
34
+ const styles = markdownFiles
35
+ .map(({ filePath, frontmatter, content, source }) => {
36
+ try {
37
+ const fileName = basename(filePath)
38
+ const styleName = fileName.replace(/\.md$/, '')
39
+
40
+ // Get style configuration from frontmatter
41
+ const name = (frontmatter['name'] || styleName) as string
42
+ const description =
43
+ coerceDescriptionToString(
44
+ frontmatter['description'],
45
+ styleName,
46
+ ) ??
47
+ extractDescriptionFromMarkdown(
48
+ content,
49
+ `Custom ${styleName} output style`,
50
+ )
51
+
52
+ // Parse keep-coding-instructions flag (supports both boolean and string values)
53
+ const keepCodingInstructionsRaw =
54
+ frontmatter['keep-coding-instructions']
55
+ const keepCodingInstructions =
56
+ keepCodingInstructionsRaw === true ||
57
+ keepCodingInstructionsRaw === 'true'
58
+ ? true
59
+ : keepCodingInstructionsRaw === false ||
60
+ keepCodingInstructionsRaw === 'false'
61
+ ? false
62
+ : undefined
63
+
64
+ // Warn if force-for-plugin is set on non-plugin output style
65
+ if (frontmatter['force-for-plugin'] !== undefined) {
66
+ logForDebugging(
67
+ `Output style "${name}" has force-for-plugin set, but this option only applies to plugin output styles. Ignoring.`,
68
+ { level: 'warn' },
69
+ )
70
+ }
71
+
72
+ return {
73
+ name,
74
+ description,
75
+ prompt: content.trim(),
76
+ source,
77
+ keepCodingInstructions,
78
+ }
79
+ } catch (error) {
80
+ logError(error)
81
+ return null
82
+ }
83
+ })
84
+ .filter(style => style !== null)
85
+
86
+ return styles
87
+ } catch (error) {
88
+ logError(error)
89
+ return []
90
+ }
91
+ },
92
+ )
93
+
94
+ export function clearOutputStyleCaches(): void {
95
+ getOutputStyleDirStyles.cache?.clear?.()
96
+ loadMarkdownFilesForSubdir.cache?.clear?.()
97
+ clearPluginOutputStyleCache()
98
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xortex/xcode",
3
- "version": "3.1.1",
3
+ "version": "3.1.3",
4
4
  "description": "XCode - AI-powered coding assistant with XMem long-term memory. Supports Claude, Gemini, Kimi, DeepSeek via OpenRouter.",
5
5
  "main": "main.tsx",
6
6
  "bin": {
@@ -37,17 +37,28 @@
37
37
  "types/",
38
38
  "upstreamproxy/",
39
39
  "utils/",
40
+ "vim/",
40
41
  "voice/",
42
+ "plugins/",
43
+ "public/",
44
+ "server/",
45
+ "outputStyles/",
46
+ "moreright/",
47
+ "native-ts/",
41
48
  "bun-bundle-hook.js",
42
49
  "bun-bundle-shim.ts",
43
50
  "tsconfig.json",
44
51
  "macro.ts",
45
52
  "main.tsx",
53
+ "ink.ts",
46
54
  "commands.ts",
47
55
  "context.ts",
48
56
  "cost-tracker.ts",
57
+ "costHook.ts",
49
58
  "history.ts",
50
59
  "interactiveHelpers.tsx",
60
+ "replLauncher.tsx",
61
+ "dialogLaunchers.tsx",
51
62
  "QueryEngine.ts",
52
63
  "query.ts",
53
64
  "setup.ts",
@@ -55,7 +66,7 @@
55
66
  "Task.ts",
56
67
  "Tool.ts",
57
68
  "tools.ts",
58
- "ink.ts",
69
+ "projectOnboardingState.ts",
59
70
  "README.md",
60
71
  "LICENSE"
61
72
  ],
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Built-in Plugin Registry
3
+ *
4
+ * Manages built-in plugins that ship with the CLI and can be enabled/disabled
5
+ * by users via the /plugin UI.
6
+ *
7
+ * Built-in plugins differ from bundled skills (src/skills/bundled/) in that:
8
+ * - They appear in the /plugin UI under a "Built-in" section
9
+ * - Users can enable/disable them (persisted to user settings)
10
+ * - They can provide multiple components (skills, hooks, MCP servers)
11
+ *
12
+ * Plugin IDs use the format `{name}@builtin` to distinguish them from
13
+ * marketplace plugins (`{name}@{marketplace}`).
14
+ */
15
+
16
+ import type { Command } from '../commands.js'
17
+ import type { BundledSkillDefinition } from '../skills/bundledSkills.js'
18
+ import type { BuiltinPluginDefinition, LoadedPlugin } from '../types/plugin.js'
19
+ import { getSettings_DEPRECATED } from '../utils/settings/settings.js'
20
+
21
+ const BUILTIN_PLUGINS: Map<string, BuiltinPluginDefinition> = new Map()
22
+
23
+ export const BUILTIN_MARKETPLACE_NAME = 'builtin'
24
+
25
+ /**
26
+ * Register a built-in plugin. Call this from initBuiltinPlugins() at startup.
27
+ */
28
+ export function registerBuiltinPlugin(
29
+ definition: BuiltinPluginDefinition,
30
+ ): void {
31
+ BUILTIN_PLUGINS.set(definition.name, definition)
32
+ }
33
+
34
+ /**
35
+ * Check if a plugin ID represents a built-in plugin (ends with @builtin).
36
+ */
37
+ export function isBuiltinPluginId(pluginId: string): boolean {
38
+ return pluginId.endsWith(`@${BUILTIN_MARKETPLACE_NAME}`)
39
+ }
40
+
41
+ /**
42
+ * Get a specific built-in plugin definition by name.
43
+ * Useful for the /plugin UI to show the skills/hooks/MCP list without
44
+ * a marketplace lookup.
45
+ */
46
+ export function getBuiltinPluginDefinition(
47
+ name: string,
48
+ ): BuiltinPluginDefinition | undefined {
49
+ return BUILTIN_PLUGINS.get(name)
50
+ }
51
+
52
+ /**
53
+ * Get all registered built-in plugins as LoadedPlugin objects, split into
54
+ * enabled/disabled based on user settings (with defaultEnabled as fallback).
55
+ * Plugins whose isAvailable() returns false are omitted entirely.
56
+ */
57
+ export function getBuiltinPlugins(): {
58
+ enabled: LoadedPlugin[]
59
+ disabled: LoadedPlugin[]
60
+ } {
61
+ const settings = getSettings_DEPRECATED()
62
+ const enabled: LoadedPlugin[] = []
63
+ const disabled: LoadedPlugin[] = []
64
+
65
+ for (const [name, definition] of BUILTIN_PLUGINS) {
66
+ if (definition.isAvailable && !definition.isAvailable()) {
67
+ continue
68
+ }
69
+
70
+ const pluginId = `${name}@${BUILTIN_MARKETPLACE_NAME}`
71
+ const userSetting = settings?.enabledPlugins?.[pluginId]
72
+ // Enabled state: user preference > plugin default > true
73
+ const isEnabled =
74
+ userSetting !== undefined
75
+ ? userSetting === true
76
+ : (definition.defaultEnabled ?? true)
77
+
78
+ const plugin: LoadedPlugin = {
79
+ name,
80
+ manifest: {
81
+ name,
82
+ description: definition.description,
83
+ version: definition.version,
84
+ },
85
+ path: BUILTIN_MARKETPLACE_NAME, // sentinel — no filesystem path
86
+ source: pluginId,
87
+ repository: pluginId,
88
+ enabled: isEnabled,
89
+ isBuiltin: true,
90
+ hooksConfig: definition.hooks,
91
+ mcpServers: definition.mcpServers,
92
+ }
93
+
94
+ if (isEnabled) {
95
+ enabled.push(plugin)
96
+ } else {
97
+ disabled.push(plugin)
98
+ }
99
+ }
100
+
101
+ return { enabled, disabled }
102
+ }
103
+
104
+ /**
105
+ * Get skills from enabled built-in plugins as Command objects.
106
+ * Skills from disabled plugins are not returned.
107
+ */
108
+ export function getBuiltinPluginSkillCommands(): Command[] {
109
+ const { enabled } = getBuiltinPlugins()
110
+ const commands: Command[] = []
111
+
112
+ for (const plugin of enabled) {
113
+ const definition = BUILTIN_PLUGINS.get(plugin.name)
114
+ if (!definition?.skills) continue
115
+ for (const skill of definition.skills) {
116
+ commands.push(skillDefinitionToCommand(skill))
117
+ }
118
+ }
119
+
120
+ return commands
121
+ }
122
+
123
+ /**
124
+ * Clear built-in plugins registry (for testing).
125
+ */
126
+ export function clearBuiltinPlugins(): void {
127
+ BUILTIN_PLUGINS.clear()
128
+ }
129
+
130
+ // --
131
+
132
+ function skillDefinitionToCommand(definition: BundledSkillDefinition): Command {
133
+ return {
134
+ type: 'prompt',
135
+ name: definition.name,
136
+ description: definition.description,
137
+ hasUserSpecifiedDescription: true,
138
+ allowedTools: definition.allowedTools ?? [],
139
+ argumentHint: definition.argumentHint,
140
+ whenToUse: definition.whenToUse,
141
+ model: definition.model,
142
+ disableModelInvocation: definition.disableModelInvocation ?? false,
143
+ userInvocable: definition.userInvocable ?? true,
144
+ contentLength: 0,
145
+ // 'bundled' not 'builtin' — 'builtin' in Command.source means hardcoded
146
+ // slash commands (/help, /clear). Using 'bundled' keeps these skills in
147
+ // the Skill tool's listing, analytics name logging, and prompt-truncation
148
+ // exemption. The user-toggleable aspect is tracked on LoadedPlugin.isBuiltin.
149
+ source: 'bundled',
150
+ loadedFrom: 'bundled',
151
+ hooks: definition.hooks,
152
+ context: definition.context,
153
+ agent: definition.agent,
154
+ isEnabled: definition.isEnabled ?? (() => true),
155
+ isHidden: !(definition.userInvocable ?? true),
156
+ progressMessage: 'running',
157
+ getPromptForCommand: definition.getPromptForCommand,
158
+ }
159
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Built-in Plugin Initialization
3
+ *
4
+ * Initializes built-in plugins that ship with the CLI and appear in the
5
+ * /plugin UI for users to enable/disable.
6
+ *
7
+ * Not all bundled features should be built-in plugins — use this for
8
+ * features that users should be able to explicitly enable/disable. For
9
+ * features with complex setup or automatic-enabling logic (e.g.
10
+ * claude-in-chrome), use src/skills/bundled/ instead.
11
+ *
12
+ * To add a new built-in plugin:
13
+ * 1. Import registerBuiltinPlugin from '../builtinPlugins.js'
14
+ * 2. Call registerBuiltinPlugin() with the plugin definition here
15
+ */
16
+
17
+ /**
18
+ * Initialize built-in plugins. Called during CLI startup.
19
+ */
20
+ export function initBuiltinPlugins(): void {
21
+ // No built-in plugins registered yet — this is the scaffolding for
22
+ // migrating bundled skills that should be user-toggleable.
23
+ }
@@ -0,0 +1,83 @@
1
+ import memoize from 'lodash-es/memoize.js'
2
+ import { join } from 'path'
3
+ import {
4
+ getCurrentProjectConfig,
5
+ saveCurrentProjectConfig,
6
+ } from './utils/config.js'
7
+ import { getCwd } from './utils/cwd.js'
8
+ import { isDirEmpty } from './utils/file.js'
9
+ import { getFsImplementation } from './utils/fsOperations.js'
10
+
11
+ export type Step = {
12
+ key: string
13
+ text: string
14
+ isComplete: boolean
15
+ isCompletable: boolean
16
+ isEnabled: boolean
17
+ }
18
+
19
+ export function getSteps(): Step[] {
20
+ const hasClaudeMd = getFsImplementation().existsSync(
21
+ join(getCwd(), 'CLAUDE.md'),
22
+ )
23
+ const isWorkspaceDirEmpty = isDirEmpty(getCwd())
24
+
25
+ return [
26
+ {
27
+ key: 'workspace',
28
+ text: 'Ask Claude to create a new app or clone a repository',
29
+ isComplete: false,
30
+ isCompletable: true,
31
+ isEnabled: isWorkspaceDirEmpty,
32
+ },
33
+ {
34
+ key: 'claudemd',
35
+ text: 'Run /init to create a CLAUDE.md file with instructions for Claude',
36
+ isComplete: hasClaudeMd,
37
+ isCompletable: true,
38
+ isEnabled: !isWorkspaceDirEmpty,
39
+ },
40
+ ]
41
+ }
42
+
43
+ export function isProjectOnboardingComplete(): boolean {
44
+ return getSteps()
45
+ .filter(({ isCompletable, isEnabled }) => isCompletable && isEnabled)
46
+ .every(({ isComplete }) => isComplete)
47
+ }
48
+
49
+ export function maybeMarkProjectOnboardingComplete(): void {
50
+ // Short-circuit on cached config — isProjectOnboardingComplete() hits
51
+ // the filesystem, and REPL.tsx calls this on every prompt submit.
52
+ if (getCurrentProjectConfig().hasCompletedProjectOnboarding) {
53
+ return
54
+ }
55
+ if (isProjectOnboardingComplete()) {
56
+ saveCurrentProjectConfig(current => ({
57
+ ...current,
58
+ hasCompletedProjectOnboarding: true,
59
+ }))
60
+ }
61
+ }
62
+
63
+ export const shouldShowProjectOnboarding = memoize((): boolean => {
64
+ const projectConfig = getCurrentProjectConfig()
65
+ // Short-circuit on cached config before isProjectOnboardingComplete()
66
+ // hits the filesystem — this runs during first render.
67
+ if (
68
+ projectConfig.hasCompletedProjectOnboarding ||
69
+ projectConfig.projectOnboardingSeenCount >= 4 ||
70
+ process.env.IS_DEMO
71
+ ) {
72
+ return false
73
+ }
74
+
75
+ return !isProjectOnboardingComplete()
76
+ })
77
+
78
+ export function incrementProjectOnboardingSeenCount(): void {
79
+ saveCurrentProjectConfig(current => ({
80
+ ...current,
81
+ projectOnboardingSeenCount: current.projectOnboardingSeenCount + 1,
82
+ }))
83
+ }
Binary file
Binary file
@@ -0,0 +1,27 @@
1
+ import React from "react";
2
+ import type { StatsStore } from "./context/stats.js";
3
+ import type { Root } from "./ink.js";
4
+ import type { Props as REPLProps } from "./screens/REPL.js";
5
+ import type { AppState } from "./state/AppStateStore.js";
6
+ import type { FpsMetrics } from "./utils/fpsTracker.js";
7
+ type AppWrapperProps = {
8
+ getFpsMetrics: () => FpsMetrics | undefined;
9
+ stats?: StatsStore;
10
+ initialState: AppState;
11
+ };
12
+ export async function launchRepl(
13
+ root: Root,
14
+ appProps: AppWrapperProps,
15
+ replProps: REPLProps,
16
+ renderAndRun: (root: Root, element: React.ReactNode) => Promise<void>,
17
+ ): Promise<void> {
18
+ const { App } = await import("./components/App.js");
19
+ const { REPL } = await import("./screens/REPL.js");
20
+ await renderAndRun(
21
+ root,
22
+ <App {...appProps}>
23
+ <REPL {...replProps} />
24
+ </App>,
25
+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VYsU0FBUyxFQUNwQlcsWUFBWSxFQUFFLENBQUNILElBQUksRUFBRVYsSUFBSSxFQUFFYyxPQUFPLEVBQUVoQixLQUFLLENBQUNpQixTQUFTLEVBQUUsR0FBR0MsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUN0RSxFQUFFQSxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7RUFDZixNQUFNO0lBQUVDO0VBQUksQ0FBQyxHQUFHLE1BQU0sTUFBTSxDQUFDLHFCQUFxQixDQUFDO0VBQ25ELE1BQU07SUFBRUM7RUFBSyxDQUFDLEdBQUcsTUFBTSxNQUFNLENBQUMsbUJBQW1CLENBQUM7RUFDbEQsTUFBTUwsWUFBWSxDQUNoQkgsSUFBSSxFQUNKLENBQUMsR0FBRyxDQUFDLElBQUlDLFFBQVEsQ0FBQztBQUN0QixNQUFNLENBQUMsSUFBSSxDQUFDLElBQUlDLFNBQVMsQ0FBQztBQUMxQixJQUFJLEVBQUUsR0FBRyxDQUNQLENBQUM7QUFDSCIsImlnbm9yZUxpc3QiOltdfQ==
@@ -0,0 +1,88 @@
1
+ /* eslint-disable eslint-plugin-n/no-unsupported-features/node-builtins */
2
+
3
+ import { errorMessage } from '../utils/errors.js'
4
+ import { jsonStringify } from '../utils/slowOperations.js'
5
+ import type { DirectConnectConfig } from './directConnectManager.js'
6
+ import { connectResponseSchema } from './types.js'
7
+
8
+ /**
9
+ * Errors thrown by createDirectConnectSession when the connection fails.
10
+ */
11
+ export class DirectConnectError extends Error {
12
+ constructor(message: string) {
13
+ super(message)
14
+ this.name = 'DirectConnectError'
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Create a session on a direct-connect server.
20
+ *
21
+ * Posts to `${serverUrl}/sessions`, validates the response, and returns
22
+ * a DirectConnectConfig ready for use by the REPL or headless runner.
23
+ *
24
+ * Throws DirectConnectError on network, HTTP, or response-parsing failures.
25
+ */
26
+ export async function createDirectConnectSession({
27
+ serverUrl,
28
+ authToken,
29
+ cwd,
30
+ dangerouslySkipPermissions,
31
+ }: {
32
+ serverUrl: string
33
+ authToken?: string
34
+ cwd: string
35
+ dangerouslySkipPermissions?: boolean
36
+ }): Promise<{
37
+ config: DirectConnectConfig
38
+ workDir?: string
39
+ }> {
40
+ const headers: Record<string, string> = {
41
+ 'content-type': 'application/json',
42
+ }
43
+ if (authToken) {
44
+ headers['authorization'] = `Bearer ${authToken}`
45
+ }
46
+
47
+ let resp: Response
48
+ try {
49
+ resp = await fetch(`${serverUrl}/sessions`, {
50
+ method: 'POST',
51
+ headers,
52
+ body: jsonStringify({
53
+ cwd,
54
+ ...(dangerouslySkipPermissions && {
55
+ dangerously_skip_permissions: true,
56
+ }),
57
+ }),
58
+ })
59
+ } catch (err) {
60
+ throw new DirectConnectError(
61
+ `Failed to connect to server at ${serverUrl}: ${errorMessage(err)}`,
62
+ )
63
+ }
64
+
65
+ if (!resp.ok) {
66
+ throw new DirectConnectError(
67
+ `Failed to create session: ${resp.status} ${resp.statusText}`,
68
+ )
69
+ }
70
+
71
+ const result = connectResponseSchema().safeParse(await resp.json())
72
+ if (!result.success) {
73
+ throw new DirectConnectError(
74
+ `Invalid session response: ${result.error.message}`,
75
+ )
76
+ }
77
+
78
+ const data = result.data
79
+ return {
80
+ config: {
81
+ serverUrl,
82
+ sessionId: data.session_id,
83
+ wsUrl: data.ws_url,
84
+ authToken,
85
+ },
86
+ workDir: data.work_dir,
87
+ }
88
+ }