@selesai/code 0.6.1 → 0.6.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.
- package/CHANGELOG.md +15 -0
- package/dist/config.d.ts +16 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +106 -5
- package/dist/config.js.map +1 -1
- package/dist/defaults/settings.json +4 -5
- package/dist/extensions/pi-subagents/src/tui/render.ts +19 -15
- package/dist/extensions/pi-subagents/test/integration/render-fork-badge.test.ts +227 -0
- package/dist/skills/pi-subagents/SKILL.md +43 -0
- package/dist/skills/pi-subagents/references/constraints-and-recipes.md +257 -0
- package/dist/skills/pi-subagents/references/execution-controls.md +431 -0
- package/dist/skills/pi-subagents/references/management-authoring-rpc.md +144 -0
- package/dist/skills/pi-subagents/references/prompting-and-roles.md +281 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,21 @@ All notable changes to `@selesai/code` will be documented in this file.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.6.3] - 2026-08-05
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- **Repair package install by pinning Readability to the available 0.6.0.** The 0.6.2 release declared `@mozilla/readability` `^0.6.1` in the root and bundled `pi-web-agent` manifests, but the npm registry offers no 0.6.1 (latest published is 0.6.0), so fresh installs failed with `ETARGET`. Both manifests now declare the published `^0.6.0` and the root lockfile re-resolves the available 0.6.0 release, restoring clean `npm ci` and fresh installs.
|
|
11
|
+
|
|
12
|
+
## [0.6.2] - 2026-08-05
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
- **Top-level `pi-subagents` skill.** The delegation guidance skill now also ships as a bundled top-level skill under `skills/pi-subagents/` (with its four reference documents), loaded from the package at boot alongside the other bundled skills and seeded into the agent dir on first run — so parent-orchestration guidance is available without relying on the extension's internal copy.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
- **Reference-first foreground output.** The terminal renderer for delegated results no longer re-reads or re-inlines saved child output files: settled file-only results show the saved-output reference (path/size/lines) instead of replayed child prose, legacy/foreign results carrying only `savedOutputPath` get a synthesized path-only reference (the file is never read), and explicit `outputMode: "inline"` results keep their full text.
|
|
19
|
+
- **Safe bundled skill and settings seeding.** First-run bootstrap now adds a missing top-level `subagents` key to an existing user `settings.json` via byte-preserving textual insertion (user formatting, unknown keys, and unrelated settings survive verbatim), leaves any user-configured `subagents` untouched, and installs newly added bundled skills (like `pi-subagents`) while never overwriting user-edited skill files. The bundled subagent defaults now map each builtin agent to an explicit model.
|
|
20
|
+
- **Web-agent Readability range alignment.** The bundled `pi-web-agent` extension manifest now declares `@mozilla/readability` `^0.6.1`, matching the version resolved in the root package.
|
|
21
|
+
|
|
7
22
|
## [0.6.1] - 2026-08-05
|
|
8
23
|
|
|
9
24
|
### Added
|
package/dist/config.d.ts
CHANGED
|
@@ -138,6 +138,14 @@ export declare function ensureAgentDir(agentDir?: string): void;
|
|
|
138
138
|
* bundled source is missing.
|
|
139
139
|
*/
|
|
140
140
|
export declare function seedDefaultConfigFile(destPath: string, bundledName: string, bundledDefaultsDir?: string): string | undefined;
|
|
141
|
+
/**
|
|
142
|
+
* Add bundled subagent defaults to an existing user settings file when that
|
|
143
|
+
* top-level setting is absent. The file is modified with a minimal textual
|
|
144
|
+
* insertion, so unrelated settings (including their formatting and unknown
|
|
145
|
+
* keys) are preserved byte-for-byte. Invalid or non-object JSON, or a user
|
|
146
|
+
* file that already configures `subagents`, is left untouched.
|
|
147
|
+
*/
|
|
148
|
+
export declare function seedMissingSubagentSettings(destPath: string, bundledDefaultsDir?: string): boolean;
|
|
141
149
|
/**
|
|
142
150
|
* Bundled extensions load directly from the installed package. Do not copy them
|
|
143
151
|
* into the user's agent dir, otherwise startup discovers both copies and tool
|
|
@@ -148,7 +156,11 @@ export declare function seedDefaultConfigFile(destPath: string, bundledName: str
|
|
|
148
156
|
export declare function seedDefaultExtensions(agentDir: string, bundledExtensionsDir?: string): string[];
|
|
149
157
|
/**
|
|
150
158
|
* Seed bundled built-in skills into the user's agent dir/skills.
|
|
151
|
-
*
|
|
159
|
+
* Ownership rule: bundled files are installed only when missing, so a new
|
|
160
|
+
* release can supply new bundled skills, but existing user files are never
|
|
161
|
+
* overwritten — user-authored edits survive. User-only skills stay. The
|
|
162
|
+
* authoritative bundled copy still loads directly from the package at boot
|
|
163
|
+
* (additionalSkillPaths), so a stale user copy never loses functionality.
|
|
152
164
|
* Returns the list of destination paths that were written.
|
|
153
165
|
*/
|
|
154
166
|
export declare function seedDefaultSkills(agentDir: string, bundledSkillsDir?: string): string[];
|
|
@@ -159,8 +171,9 @@ export declare function seedDefaultSkills(agentDir: string, bundledSkillsDir?: s
|
|
|
159
171
|
*/
|
|
160
172
|
export declare function seedDefaultThemes(agentDir: string, bundledThemesDir?: string): string[];
|
|
161
173
|
/**
|
|
162
|
-
* Run
|
|
163
|
-
* settings.json
|
|
174
|
+
* Run bootstrap for the agent dir: ensure directories, seed a missing
|
|
175
|
+
* settings.json, and add missing bundled subagent defaults. Idempotent — safe
|
|
176
|
+
* on every startup.
|
|
164
177
|
* Bundled models load package-locally; copying them would expose internal
|
|
165
178
|
* providers as user config. Bundled extensions also stay package-local.
|
|
166
179
|
*/
|
package/dist/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"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","sourcesContent":["import {\n\taccessSync,\n\tchmodSync,\n\tconstants,\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trealpathSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"fs\";\nimport { homedir } from \"os\";\nimport { basename, dirname, join, resolve, sep, win32 } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { spawnProcessSync } from \"./utils/child-process.ts\";\nimport { normalizePath } from \"./utils/paths.ts\";\n\n// =============================================================================\n// Package Detection\n// =============================================================================\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Detect if we're running as a Bun compiled binary.\n * Bun binaries have import.meta.url containing \"$bunfs\", \"~BUN\", or \"%7EBUN\" (Bun's virtual filesystem path)\n */\nexport const isBunBinary =\n\timport.meta.url.includes(\"$bunfs\") || import.meta.url.includes(\"~BUN\") || import.meta.url.includes(\"%7EBUN\");\n\n/** Detect if Bun is the runtime (compiled binary or bun run) */\nexport const isBunRuntime = !!process.versions.bun;\n\n// =============================================================================\n// Install Method Detection\n// =============================================================================\n\nexport type InstallMethod = \"bun-binary\" | \"source\" | \"npm\" | \"pnpm\" | \"yarn\" | \"bun\" | \"unknown\";\n\ninterface SelfUpdateCommandStep {\n\tcommand: string;\n\targs: string[];\n\tdisplay: string;\n}\n\nexport interface SelfUpdateCommand extends SelfUpdateCommandStep {\n\tsteps?: SelfUpdateCommandStep[];\n}\n\nexport type SelfUpdatePackageTarget = string | { packageName: string; installSpec?: string };\n\nfunction normalizeSelfUpdatePackageTarget(target: SelfUpdatePackageTarget): {\n\tpackageName: string;\n\tinstallSpec: string;\n} {\n\tif (typeof target === \"string\") {\n\t\treturn { packageName: target, installSpec: target };\n\t}\n\treturn { packageName: target.packageName, installSpec: target.installSpec ?? target.packageName };\n}\n\nfunction makeSelfUpdateCommand(\n\tinstallStep: SelfUpdateCommandStep,\n\tuninstallStep?: SelfUpdateCommandStep,\n): SelfUpdateCommand {\n\tif (!uninstallStep) return installStep;\n\treturn {\n\t\t...installStep,\n\t\tdisplay: `${uninstallStep.display} && ${installStep.display}`,\n\t\tsteps: [uninstallStep, installStep],\n\t};\n}\n\nfunction makeSelfUpdateCommandStep(command: string, args: string[]): SelfUpdateCommandStep {\n\treturn {\n\t\tcommand,\n\t\targs,\n\t\tdisplay: [command, ...args].map((arg) => (/\\s/.test(arg) ? `\"${arg}\"` : arg)).join(\" \"),\n\t};\n}\n\nexport function detectInstallMethod(): InstallMethod {\n\tif (isBunBinary) {\n\t\treturn \"bun-binary\";\n\t}\n\n\tif (existsSync(join(getPackageDir(), \".git\"))) {\n\t\treturn \"source\";\n\t}\n\n\tconst resolvedPath = `${__dirname}\\0${process.execPath || \"\"}`.toLowerCase().replace(/\\\\/g, \"/\");\n\n\tif (resolvedPath.includes(\"/pnpm/\") || resolvedPath.includes(\"/.pnpm/\")) {\n\t\treturn \"pnpm\";\n\t}\n\tif (resolvedPath.includes(\"/yarn/\") || resolvedPath.includes(\"/.yarn/\")) {\n\t\treturn \"yarn\";\n\t}\n\tif (isBunRuntime || resolvedPath.includes(\"/install/global/node_modules/\")) {\n\t\treturn \"bun\";\n\t}\n\tif (resolvedPath.includes(\"/npm/\") || resolvedPath.includes(\"/node_modules/\")) {\n\t\treturn \"npm\";\n\t}\n\n\treturn \"unknown\";\n}\n\nfunction getInferredNpmInstall(): { root: string; prefix: string } | undefined {\n\tconst packageDir = getPackageDir();\n\tconst path = process.platform === \"win32\" || packageDir.includes(\"\\\\\") ? win32 : { basename, dirname };\n\tconst parent = path.dirname(packageDir);\n\tlet root: string | undefined;\n\tif (path.basename(parent).startsWith(\"@\") && path.basename(path.dirname(parent)) === \"node_modules\") {\n\t\troot = path.dirname(parent);\n\t} else if (path.basename(parent) === \"node_modules\") {\n\t\troot = parent;\n\t}\n\tif (!root) return undefined;\n\tconst rootParent = path.dirname(root);\n\tif (path.basename(rootParent) === \"lib\") return { root, prefix: path.dirname(rootParent) };\n\t// Windows global npm prefixes use `<prefix>\\\\node_modules`, which is\n\t// indistinguishable from local project installs by path shape alone. Do not\n\t// infer unsupported Windows custom prefixes without `npm root -g` evidence.\n\treturn undefined;\n}\n\nfunction getSelfUpdateCommandForMethod(\n\tmethod: InstallMethod,\n\tinstalledPackageName: string,\n\tupdatePackageTarget: SelfUpdatePackageTarget = installedPackageName,\n\tnpmCommand?: string[],\n): SelfUpdateCommand | undefined {\n\tconst target = normalizeSelfUpdatePackageTarget(updatePackageTarget);\n\tswitch (method) {\n\t\tcase \"bun-binary\":\n\t\t\treturn undefined;\n\t\tcase \"source\": {\n\t\t\tif (target.packageName !== installedPackageName) return undefined;\n\t\t\tconst packageDir = getPackageDir();\n\t\t\tconst steps = [\n\t\t\t\tmakeSelfUpdateCommandStep(\"git\", [\"-C\", packageDir, \"pull\", \"--ff-only\"]),\n\t\t\t\tmakeSelfUpdateCommandStep(\"npm\", [\"--prefix\", packageDir, \"install\"]),\n\t\t\t\tmakeSelfUpdateCommandStep(\"npm\", [\"--prefix\", packageDir, \"run\", \"build\"]),\n\t\t\t];\n\t\t\treturn { ...steps[0], display: steps.map((step) => step.display).join(\" && \"), steps };\n\t\t}\n\t\tcase \"pnpm\": {\n\t\t\tconst match = readCommandOutput(\"pnpm\", [\"root\", \"-g\"])\n\t\t\t\t? undefined\n\t\t\t\t: /^(.*[\\\\/]global[\\\\/][^\\\\/]+)[\\\\/]\\.pnpm[\\\\/]/.exec(getPackageDir());\n\t\t\tconst binDirArgs = match\n\t\t\t\t? [`--config.global-bin-dir=${process.env.PNPM_HOME || dirname(dirname(match[1]))}`]\n\t\t\t\t: [];\n\t\t\treturn makeSelfUpdateCommand(\n\t\t\t\tmakeSelfUpdateCommandStep(\"pnpm\", [\n\t\t\t\t\t\"install\",\n\t\t\t\t\t\"-g\",\n\t\t\t\t\t\"--ignore-scripts\",\n\t\t\t\t\t\"--config.minimumReleaseAge=0\",\n\t\t\t\t\t...binDirArgs,\n\t\t\t\t\ttarget.installSpec,\n\t\t\t\t]),\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(\"pnpm\", [\"remove\", \"-g\", ...binDirArgs, installedPackageName]),\n\t\t\t);\n\t\t}\n\t\tcase \"yarn\":\n\t\t\treturn makeSelfUpdateCommand(\n\t\t\t\tmakeSelfUpdateCommandStep(\"yarn\", [\"global\", \"add\", \"--ignore-scripts\", target.installSpec]),\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(\"yarn\", [\"global\", \"remove\", installedPackageName]),\n\t\t\t);\n\t\tcase \"bun\":\n\t\t\treturn makeSelfUpdateCommand(\n\t\t\t\tmakeSelfUpdateCommandStep(\"bun\", [\n\t\t\t\t\t\"install\",\n\t\t\t\t\t\"-g\",\n\t\t\t\t\t\"--ignore-scripts\",\n\t\t\t\t\t\"--minimum-release-age=0\",\n\t\t\t\t\ttarget.installSpec,\n\t\t\t\t]),\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(\"bun\", [\"uninstall\", \"-g\", installedPackageName]),\n\t\t\t);\n\t\tcase \"npm\": {\n\t\t\tconst [command = \"npm\", ...npmArgs] = npmCommand ?? [];\n\t\t\tconst inferred = npmCommand?.length ? undefined : getInferredNpmInstall();\n\t\t\tconst prefixArgs = [...npmArgs, ...(inferred ? [\"--prefix\", inferred.prefix] : [])];\n\t\t\tconst installStep = makeSelfUpdateCommandStep(command, [\n\t\t\t\t...prefixArgs,\n\t\t\t\t\"install\",\n\t\t\t\t\"-g\",\n\t\t\t\t\"--ignore-scripts\",\n\t\t\t\t\"--min-release-age=0\",\n\t\t\t\ttarget.installSpec,\n\t\t\t]);\n\t\t\tconst uninstallStep =\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(command, [...prefixArgs, \"uninstall\", \"-g\", installedPackageName]);\n\t\t\treturn makeSelfUpdateCommand(installStep, uninstallStep);\n\t\t}\n\t\tcase \"unknown\":\n\t\t\treturn undefined;\n\t}\n}\n\nfunction readCommandOutput(\n\tcommand: string,\n\targs: string[],\n\toptions: { requireSuccess?: boolean } = {},\n): string | undefined {\n\tconst result = spawnProcessSync(command, args, {\n\t\tencoding: \"utf-8\",\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t});\n\tif (result.status === 0) return result.stdout.trim() || undefined;\n\tif (options.requireSuccess) {\n\t\tconst reason = result.error?.message || result.stderr.trim() || `exit code ${result.status ?? \"unknown\"}`;\n\t\tthrow new Error(`Failed to run ${[command, ...args].join(\" \")}: ${reason}`);\n\t}\n\treturn undefined;\n}\n\nfunction getGlobalPackageRoots(method: InstallMethod, _packageName: string, npmCommand?: string[]): string[] {\n\tswitch (method) {\n\t\tcase \"npm\": {\n\t\t\tconst configured = !!npmCommand?.length;\n\t\t\tconst [command = \"npm\", ...npmArgs] = npmCommand ?? [];\n\t\t\tif (configured && command === \"bun\") {\n\t\t\t\tconst bunBin = readCommandOutput(command, [...npmArgs, \"pm\", \"bin\", \"-g\"], {\n\t\t\t\t\trequireSuccess: true,\n\t\t\t\t});\n\t\t\t\tconst roots = [join(homedir(), \".bun\", \"install\", \"global\", \"node_modules\")];\n\t\t\t\tif (bunBin) {\n\t\t\t\t\troots.push(join(dirname(bunBin), \"install\", \"global\", \"node_modules\"));\n\t\t\t\t}\n\t\t\t\treturn roots;\n\t\t\t}\n\t\t\tconst root = readCommandOutput(command, [...npmArgs, \"root\", \"-g\"], {\n\t\t\t\trequireSuccess: configured,\n\t\t\t});\n\t\t\tconst inferred = configured ? undefined : getInferredNpmInstall();\n\t\t\treturn [root, inferred?.root].filter((x): x is string => !!x);\n\t\t}\n\t\tcase \"pnpm\": {\n\t\t\tconst root = readCommandOutput(\"pnpm\", [\"root\", \"-g\"]);\n\t\t\tif (root) return [root, dirname(root)];\n\t\t\tconst match = /^(.*[\\\\/]global[\\\\/][^\\\\/]+)[\\\\/]\\.pnpm[\\\\/]/.exec(getPackageDir());\n\t\t\treturn match ? [match[1]] : [];\n\t\t}\n\t\tcase \"yarn\": {\n\t\t\tconst dir = readCommandOutput(\"yarn\", [\"global\", \"dir\"]);\n\t\t\treturn dir ? [dir, join(dir, \"node_modules\")] : [];\n\t\t}\n\t\tcase \"bun\": {\n\t\t\tconst bunBin = readCommandOutput(\"bun\", [\"pm\", \"bin\", \"-g\"]);\n\t\t\tconst roots = [join(homedir(), \".bun\", \"install\", \"global\", \"node_modules\")];\n\t\t\tif (bunBin) {\n\t\t\t\troots.push(join(dirname(bunBin), \"install\", \"global\", \"node_modules\"));\n\t\t\t}\n\t\t\treturn roots;\n\t\t}\n\t\tcase \"bun-binary\":\n\t\tcase \"source\":\n\t\tcase \"unknown\":\n\t\t\treturn [];\n\t}\n}\n\nfunction normalizeExistingPathForComparison(path: string, resolveSymlinks: boolean): string | undefined {\n\tconst resolvedPath = resolve(path);\n\tif (!existsSync(resolvedPath)) {\n\t\treturn undefined;\n\t}\n\tlet normalizedPath = resolvedPath;\n\tif (resolveSymlinks) {\n\t\ttry {\n\t\t\tnormalizedPath = realpathSync(resolvedPath);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (process.platform === \"win32\") {\n\t\tnormalizedPath = normalizedPath.toLowerCase();\n\t}\n\treturn normalizedPath;\n}\n\nfunction getPathComparisonCandidates(path: string): string[] {\n\treturn Array.from(\n\t\tnew Set(\n\t\t\t[normalizeExistingPathForComparison(path, false), normalizeExistingPathForComparison(path, true)].filter(\n\t\t\t\t(candidate): candidate is string => !!candidate,\n\t\t\t),\n\t\t),\n\t);\n}\n\nfunction getEntrypointPackageDir(): string | undefined {\n\tconst entrypoint = process.argv[1];\n\tif (!entrypoint) return undefined;\n\tlet dir = dirname(entrypoint);\n\twhile (dir !== dirname(dir)) {\n\t\tif (existsSync(join(dir, \"package.json\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tdir = dirname(dir);\n\t}\n\treturn undefined;\n}\n\nfunction isSelfUpdatePathWritable(): boolean {\n\tconst packageDir = getPackageDir();\n\ttry {\n\t\taccessSync(packageDir, constants.W_OK);\n\t\taccessSync(dirname(packageDir), constants.W_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction isManagedByGlobalPackageManager(method: InstallMethod, packageName: string, npmCommand?: string[]): boolean {\n\tconst packageDirs = [getPackageDir(), getEntrypointPackageDir()].filter((dir): dir is string => !!dir);\n\tconst packageDirCandidates = packageDirs.flatMap((dir) => getPathComparisonCandidates(dir));\n\treturn getGlobalPackageRoots(method, packageName, npmCommand).some((root) => {\n\t\treturn getPathComparisonCandidates(root).some((normalizedRoot) => {\n\t\t\tconst rootPrefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\t\treturn packageDirCandidates.some((packageDir) => packageDir.startsWith(rootPrefix));\n\t\t});\n\t});\n}\n\nexport function getSelfUpdateCommand(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdatePackageTarget: SelfUpdatePackageTarget = packageName,\n): SelfUpdateCommand | undefined {\n\tconst method = detectInstallMethod();\n\tconst command = getSelfUpdateCommandForMethod(method, packageName, updatePackageTarget, npmCommand);\n\tif (!command || !isSelfUpdatePathWritable()) {\n\t\treturn undefined;\n\t}\n\tif (method !== \"source\" && !isManagedByGlobalPackageManager(method, packageName, npmCommand)) {\n\t\treturn undefined;\n\t}\n\treturn command;\n}\n\nexport function getSelfUpdateUnavailableInstruction(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdatePackageTarget: SelfUpdatePackageTarget = packageName,\n): string {\n\tconst method = detectInstallMethod();\n\tconst target = normalizeSelfUpdatePackageTarget(updatePackageTarget);\n\tif (method === \"bun-binary\") {\n\t\treturn `Download from: https://github.com/earendil-works/pi-mono/releases/latest`;\n\t}\n\tconst command = getSelfUpdateCommandForMethod(method, packageName, target, npmCommand);\n\tif (command) {\n\t\tif (method === \"source\") {\n\t\t\treturn isSelfUpdatePathWritable()\n\t\t\t\t? `Update the source checkout yourself with: ${command.display}`\n\t\t\t\t: `This source checkout is not writable. Update it yourself with: ${command.display}`;\n\t\t}\n\t\tif (isManagedByGlobalPackageManager(method, packageName, npmCommand) && !isSelfUpdatePathWritable()) {\n\t\t\treturn `This installation is managed by a global ${method} install, but the install path is not writable. Update it yourself with: ${command.display}`;\n\t\t}\n\t\treturn `This installation is not managed by a global ${method} install. Update it with the package manager, wrapper, or source checkout that provides it.`;\n\t}\n\treturn `Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`;\n}\n\nexport function getUpdateInstruction(packageName: string): string {\n\tconst method = detectInstallMethod();\n\tconst command = getSelfUpdateCommandForMethod(method, packageName);\n\tif (command) {\n\t\treturn `Run: ${command.display}`;\n\t}\n\treturn getSelfUpdateUnavailableInstruction(packageName);\n}\n\n// =============================================================================\n// Package Asset Paths (shipped with executable)\n// =============================================================================\n\n/**\n * Get the base directory for resolving package assets (themes, package.json, README.md, CHANGELOG.md).\n * - For Bun binary: returns the directory containing the executable\n * - For Node.js (dist/): returns __dirname (the dist/ directory)\n * - For tsx (src/): returns parent directory (the package root)\n */\nexport function getPackageDir(): string {\n\t// Allow override via environment variable (useful for Nix/Guix where store paths tokenize poorly)\n\tconst envDir = process.env.PI_PACKAGE_DIR;\n\tif (envDir) {\n\t\treturn normalizePath(envDir);\n\t}\n\n\tif (isBunBinary) {\n\t\t// Bun binary: process.execPath points to the compiled executable\n\t\treturn dirname(process.execPath);\n\t}\n\t// Node.js: walk up from __dirname until we find package.json\n\tlet dir = __dirname;\n\twhile (dir !== dirname(dir)) {\n\t\tif (existsSync(join(dir, \"package.json\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tdir = dirname(dir);\n\t}\n\t// Fallback (shouldn't happen)\n\treturn __dirname;\n}\n\n/**\n * Get path to built-in themes directory (shipped with package)\n * - For Bun binary: theme/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/theme/\n * - For tsx (src/): src/modes/interactive/theme/\n */\nexport function getThemesDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"theme\");\n\t}\n\t// Theme is in modes/interactive/theme/ relative to src/ or dist/\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, \"modes\", \"interactive\", \"theme\");\n}\n\n/**\n * Get path to HTML export template directory (shipped with package)\n * - For Bun binary: export-html/ next to executable\n * - For Node.js (dist/): dist/core/export-html/\n * - For tsx (src/): src/core/export-html/\n */\nexport function getExportTemplateDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"export-html\");\n\t}\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, \"core\", \"export-html\");\n}\n\n/** Get path to package.json */\nexport function getPackageJsonPath(): string {\n\treturn join(getPackageDir(), \"package.json\");\n}\n\n/** Get path to README.md */\nexport function getReadmePath(): string {\n\treturn resolve(join(getPackageDir(), \"README.md\"));\n}\n\n/** Get path to docs directory */\nexport function getDocsPath(): string {\n\treturn resolve(join(getPackageDir(), \"docs\"));\n}\n\n/** Get path to examples directory */\nexport function getExamplesPath(): string {\n\treturn resolve(join(getPackageDir(), \"examples\"));\n}\n\n/** Get path to CHANGELOG.md */\nexport function getChangelogPath(): string {\n\treturn resolve(join(getPackageDir(), \"CHANGELOG.md\"));\n}\n\n/**\n * Get path to built-in interactive assets directory.\n * - For Bun binary: assets/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/assets/\n * - For tsx (src/): src/modes/interactive/assets/\n */\nexport function getInteractiveAssetsDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"assets\");\n\t}\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, \"modes\", \"interactive\", \"assets\");\n}\n\n/**\n * Resolve a bundled subdirectory shipped with the package (defaults/extensions/themes).\n * - For Bun binary: <dir>/ next to executable\n * - For Node.js (dist/): dist/<dir>/\n * - For tsx (src/): src/<dir>/\n */\nfunction getBundledSubdir(name: string): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), name);\n\t}\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, name);\n}\n\n/**\n * Get path to bundled default config directory (shipped with package).\n * Holds bundled defaults. settings.json is copied on first run; models.json is loaded directly.\n */\nexport function getBundledDefaultsDir(): string {\n\treturn getBundledSubdir(\"defaults\");\n}\n\n/**\n * Get path to bundled built-in extensions directory (shipped with package).\n * Loaded directly via additionalExtensionPaths at boot (not copied into the\n * user agent dir) — same hook as CLI --extension. .ts ships as-is (jiti loads it).\n * - For Bun binary: extensions/ next to executable\n * - For Node.js (dist/): dist/extensions/\n * - For tsx (src/): src/extensions/\n */\nexport function getBundledExtensionsDir(): string {\n\treturn getBundledSubdir(\"extensions\");\n}\n\n/**\n * Get path to bundled built-in themes directory (shipped with package).\n * Loaded directly via additionalThemePaths at boot.\n */\nexport function getBundledThemesDir(): string {\n\treturn getBundledSubdir(\"themes\");\n}\n\n/**\n * Get path to bundled built-in skills directory (shipped with package).\n * Loaded directly via additionalSkillPaths at boot.\n */\nexport function getBundledSkillsDir(): string {\n\treturn getBundledSubdir(\"skills\");\n}\n\n/** Get path to a bundled interactive asset */\nexport function getBundledInteractiveAssetPath(name: string): string {\n\treturn join(getInteractiveAssetsDir(), name);\n}\n\n// =============================================================================\n// App Config (from package.json piConfig)\n// =============================================================================\n\ninterface PackageJson {\n\tname?: string;\n\tversion?: string;\n\tpiConfig?: {\n\t\tname?: string;\n\t\tconfigDir?: string;\n\t};\n}\n\nlet pkg: PackageJson = {};\ntry {\n\tpkg = JSON.parse(readFileSync(getPackageJsonPath(), \"utf-8\")) as PackageJson;\n} catch (e: unknown) {\n\tconst err = e as NodeJS.ErrnoException;\n\tif (err.code !== \"ENOENT\") throw e;\n}\n\nconst piConfigName: string | undefined = pkg.piConfig?.name;\nexport const PACKAGE_NAME: string = pkg.name || \"@earendil-works/pi-coding-agent\";\nexport const APP_NAME: string = piConfigName || \"pi\";\nexport const APP_TITLE: string = piConfigName ? APP_NAME : \"π\";\nexport const CONFIG_DIR_NAME: string = pkg.piConfig?.configDir || \".pi\";\nexport const VERSION: string = pkg.version || \"0.0.0\";\n\n// e.g., PI_CODING_AGENT_DIR or TAU_CODING_AGENT_DIR\nexport const ENV_AGENT_DIR = `${APP_NAME.toUpperCase()}_CODING_AGENT_DIR`;\nexport const ENV_SESSION_DIR = `${APP_NAME.toUpperCase()}_CODING_AGENT_SESSION_DIR`;\n\nexport function expandTildePath(path: string): string {\n\treturn normalizePath(path);\n}\n\nconst DEFAULT_SHARE_VIEWER_URL = \"https://pi.dev/session/\";\n\n/** Get the share viewer URL for a gist ID */\nexport function getShareViewerUrl(gistId: string): string {\n\tconst baseUrl = process.env.PI_SHARE_VIEWER_URL || DEFAULT_SHARE_VIEWER_URL;\n\treturn `${baseUrl}#${gistId}`;\n}\n\n// =============================================================================\n// User Config Paths (~/<configured-dir>/agent/*)\n// =============================================================================\n\n/** Get the agent config directory (e.g., ~/.selesai/agent/) */\nexport function getAgentDir(): string {\n\tconst envDir = process.env[ENV_AGENT_DIR];\n\tif (envDir) {\n\t\treturn expandTildePath(envDir);\n\t}\n\treturn join(homedir(), CONFIG_DIR_NAME, \"agent\");\n}\n\n/** Get path to user's custom themes directory */\nexport function getCustomThemesDir(): string {\n\treturn join(getAgentDir(), \"themes\");\n}\n\n/** Get path to models.json */\nexport function getModelsPath(): string {\n\treturn join(getAgentDir(), \"models.json\");\n}\n\n/** Get path to auth.json */\nexport function getAuthPath(): string {\n\treturn join(getAgentDir(), \"auth.json\");\n}\n\n/** Get path to settings.json */\nexport function getSettingsPath(): string {\n\treturn join(getAgentDir(), \"settings.json\");\n}\n\n/** Get path to tools directory */\nexport function getToolsDir(): string {\n\treturn join(getAgentDir(), \"tools\");\n}\n\n/** Get path to managed binaries directory (fd, rg) */\nexport function getBinDir(): string {\n\treturn join(getAgentDir(), \"bin\");\n}\n\n/** Get path to prompt templates directory */\nexport function getPromptsDir(): string {\n\treturn join(getAgentDir(), \"prompts\");\n}\n\n/** Get path to sessions directory */\nexport function getSessionsDir(): string {\n\treturn join(getAgentDir(), \"sessions\");\n}\n\n/** Get path to debug log file */\nexport function getDebugLogPath(): string {\n\treturn join(getAgentDir(), `${APP_NAME}-debug.log`);\n}\n\n/**\n * Marker file written once first-time onboarding completes. Decouples the\n * first-run dialog gate from settings.json existence so that bootstrapping a\n * bundled default settings.json does not suppress the dialog.\n */\nexport function getFirstRunMarkerPath(agentDir: string = getAgentDir()): string {\n\treturn join(agentDir, \".firstRunComplete\");\n}\n\n/**\n * Mark first-run onboarding as complete. Safe to call repeatedly.\n */\nexport function markFirstRunComplete(agentDir: string = getAgentDir()): void {\n\tmkdirSync(agentDir, { recursive: true, mode: 0o700 });\n\twriteFileSync(getFirstRunMarkerPath(agentDir), \"1\", { mode: 0o600 });\n}\n\n// =============================================================================\n// Agent Dir Bootstrap (first-run seeding)\n// =============================================================================\n\n/** Subdirectories created under the agent dir on first run. */\nconst AGENT_SUBDIRS = [\n\t\"themes\",\n\t\"tools\",\n\t\"bin\",\n\t\"prompts\",\n\t\"sessions\",\n\t\"extensions\",\n\t\"skills\",\n] as const;\n\n/**\n * Ensure the agent dir and standard subdirs exist (mode 0o700 for privacy).\n * Safe to call on every startup; no-op when dirs already exist.\n */\nexport function ensureAgentDir(agentDir: string = getAgentDir()): void {\n\tmkdirSync(agentDir, { recursive: true, mode: 0o700 });\n\tfor (const sub of AGENT_SUBDIRS) {\n\t\tmkdirSync(join(agentDir, sub), { recursive: true, mode: 0o700 });\n\t}\n}\n\n/**\n * Seed a default config file from the bundled defaults dir if it does not yet\n * exist. Never overwrites an existing user file. Returns the destination path\n * when a seed was written, undefined when the file already existed or the\n * bundled source is missing.\n */\nexport function seedDefaultConfigFile(\n\tdestPath: string,\n\tbundledName: string,\n\tbundledDefaultsDir: string = getBundledDefaultsDir(),\n): string | undefined {\n\tif (existsSync(destPath)) return undefined;\n\tconst source = join(bundledDefaultsDir, bundledName);\n\tif (!existsSync(source)) return undefined;\n\tmkdirSync(dirname(destPath), { recursive: true, mode: 0o700 });\n\tcopyFileSync(source, destPath);\n\ttry {\n\t\tchmodSync(destPath, 0o600);\n\t} catch {\n\t\t// chmod is best-effort (no-op on platforms that don't support it).\n\t}\n\treturn destPath;\n}\n\n/**\n * Recursively copy a bundled directory tree into the user's agent dir, skipping\n * any file that already exists (user edits survive). Never overwrites. Used to\n * seed bundled skills/themes so the user can inspect and edit them.\n * Returns the list of destination paths that were written.\n */\nfunction seedBundledDir(\n\tdestDir: string,\n\tbundledDir: string,\n): string[] {\n\tif (!existsSync(bundledDir)) return [];\n\tmkdirSync(destDir, { recursive: true, mode: 0o700 });\n\tconst written: string[] = [];\n\tconst stack: Array<{ src: string; dst: string }> = [{ src: bundledDir, dst: destDir }];\n\twhile (stack.length > 0) {\n\t\tconst { src, dst } = stack.pop()!;\n\t\tmkdirSync(dst, { recursive: true, mode: 0o700 });\n\t\tfor (const entry of readdirSync(src, { withFileTypes: true })) {\n\t\t\tif (entry.name === \".DS_Store\" || entry.name === \"node_modules\") continue;\n\t\t\tconst srcPath = join(src, entry.name);\n\t\t\tconst dstPath = join(dst, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tif (!existsSync(dstPath)) mkdirSync(dstPath, { recursive: true, mode: 0o700 });\n\t\t\t\tstack.push({ src: srcPath, dst: dstPath });\n\t\t\t} else if (entry.isFile() || entry.isSymbolicLink()) {\n\t\t\t\tif (existsSync(dstPath)) continue;\n\t\t\t\tcopyFileSync(srcPath, dstPath);\n\t\t\t\ttry {\n\t\t\t\t\tchmodSync(dstPath, 0o600);\n\t\t\t\t} catch {\n\t\t\t\t\t// best-effort\n\t\t\t\t}\n\t\t\t\twritten.push(dstPath);\n\t\t\t}\n\t\t}\n\t}\n\treturn written;\n}\n\nfunction removeIdenticalBundledFiles(destDir: string, bundledDir: string): string[] {\n\tif (!existsSync(destDir) || !existsSync(bundledDir)) return [];\n\tconst removed: string[] = [];\n\tconst stack: Array<{ src: string; dst: string }> = [{ src: bundledDir, dst: destDir }];\n\twhile (stack.length > 0) {\n\t\tconst { src, dst } = stack.pop()!;\n\t\tif (!existsSync(dst)) continue;\n\t\tfor (const entry of readdirSync(src, { withFileTypes: true })) {\n\t\t\tif (entry.name === \".DS_Store\" || entry.name === \"node_modules\") continue;\n\t\t\tconst srcPath = join(src, entry.name);\n\t\t\tconst dstPath = join(dst, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push({ src: srcPath, dst: dstPath });\n\t\t\t} else if (existsSync(dstPath) && readFileSync(srcPath).equals(readFileSync(dstPath))) {\n\t\t\t\tunlinkSync(dstPath);\n\t\t\t\tremoved.push(dstPath);\n\t\t\t}\n\t\t}\n\t}\n\treturn removed;\n}\n\n/**\n * Bundled extensions load directly from the installed package. Do not copy them\n * into the user's agent dir, otherwise startup discovers both copies and tool\n * registration conflicts with itself.\n * Remove files copied by older releases only when they are byte-identical to\n * bundled files, so user-edited extensions survive.\n */\nexport function seedDefaultExtensions(\n\tagentDir: string,\n\tbundledExtensionsDir: string = getBundledExtensionsDir(),\n): string[] {\n\tremoveIdenticalBundledFiles(join(agentDir, \"extensions\"), bundledExtensionsDir);\n\treturn [];\n}\n\n/**\n * Seed bundled built-in skills into the user's agent dir/skills.\n * Skips existing files (user edits survive). Never overwrites.\n * Returns the list of destination paths that were written.\n */\nexport function seedDefaultSkills(\n\tagentDir: string,\n\tbundledSkillsDir: string = getBundledSkillsDir(),\n): string[] {\n\treturn seedBundledDir(join(agentDir, \"skills\"), bundledSkillsDir);\n}\n\n/**\n * Seed bundled built-in themes into the user's agent dir/themes.\n * Skips existing files (user edits survive). Never overwrites.\n * Returns the list of destination paths that were written.\n */\nexport function seedDefaultThemes(\n\tagentDir: string,\n\tbundledThemesDir: string = getBundledThemesDir(),\n): string[] {\n\treturn seedBundledDir(join(agentDir, \"themes\"), bundledThemesDir);\n}\n\n/**\n * Run full first-run bootstrap for the agent dir: ensure directories and seed\n * settings.json from bundled defaults. Idempotent — safe on every startup.\n * Bundled models load package-locally; copying them would expose internal\n * providers as user config. Bundled extensions also stay package-local.\n */\nexport function bootstrapAgentDir(agentDir: string = getAgentDir()): void {\n\tensureAgentDir(agentDir);\n\tseedDefaultConfigFile(join(agentDir, \"settings.json\"), \"settings.json\");\n\tseedDefaultExtensions(agentDir);\n\tseedDefaultSkills(agentDir);\n\tseedDefaultThemes(agentDir);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"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","sourcesContent":["import {\n\taccessSync,\n\tchmodSync,\n\tconstants,\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trealpathSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"fs\";\nimport { homedir } from \"os\";\nimport { basename, dirname, join, resolve, sep, win32 } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { spawnProcessSync } from \"./utils/child-process.ts\";\nimport { normalizePath } from \"./utils/paths.ts\";\n\n// =============================================================================\n// Package Detection\n// =============================================================================\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Detect if we're running as a Bun compiled binary.\n * Bun binaries have import.meta.url containing \"$bunfs\", \"~BUN\", or \"%7EBUN\" (Bun's virtual filesystem path)\n */\nexport const isBunBinary =\n\timport.meta.url.includes(\"$bunfs\") || import.meta.url.includes(\"~BUN\") || import.meta.url.includes(\"%7EBUN\");\n\n/** Detect if Bun is the runtime (compiled binary or bun run) */\nexport const isBunRuntime = !!process.versions.bun;\n\n// =============================================================================\n// Install Method Detection\n// =============================================================================\n\nexport type InstallMethod = \"bun-binary\" | \"source\" | \"npm\" | \"pnpm\" | \"yarn\" | \"bun\" | \"unknown\";\n\ninterface SelfUpdateCommandStep {\n\tcommand: string;\n\targs: string[];\n\tdisplay: string;\n}\n\nexport interface SelfUpdateCommand extends SelfUpdateCommandStep {\n\tsteps?: SelfUpdateCommandStep[];\n}\n\nexport type SelfUpdatePackageTarget = string | { packageName: string; installSpec?: string };\n\nfunction normalizeSelfUpdatePackageTarget(target: SelfUpdatePackageTarget): {\n\tpackageName: string;\n\tinstallSpec: string;\n} {\n\tif (typeof target === \"string\") {\n\t\treturn { packageName: target, installSpec: target };\n\t}\n\treturn { packageName: target.packageName, installSpec: target.installSpec ?? target.packageName };\n}\n\nfunction makeSelfUpdateCommand(\n\tinstallStep: SelfUpdateCommandStep,\n\tuninstallStep?: SelfUpdateCommandStep,\n): SelfUpdateCommand {\n\tif (!uninstallStep) return installStep;\n\treturn {\n\t\t...installStep,\n\t\tdisplay: `${uninstallStep.display} && ${installStep.display}`,\n\t\tsteps: [uninstallStep, installStep],\n\t};\n}\n\nfunction makeSelfUpdateCommandStep(command: string, args: string[]): SelfUpdateCommandStep {\n\treturn {\n\t\tcommand,\n\t\targs,\n\t\tdisplay: [command, ...args].map((arg) => (/\\s/.test(arg) ? `\"${arg}\"` : arg)).join(\" \"),\n\t};\n}\n\nexport function detectInstallMethod(): InstallMethod {\n\tif (isBunBinary) {\n\t\treturn \"bun-binary\";\n\t}\n\n\tif (existsSync(join(getPackageDir(), \".git\"))) {\n\t\treturn \"source\";\n\t}\n\n\tconst resolvedPath = `${__dirname}\\0${process.execPath || \"\"}`.toLowerCase().replace(/\\\\/g, \"/\");\n\n\tif (resolvedPath.includes(\"/pnpm/\") || resolvedPath.includes(\"/.pnpm/\")) {\n\t\treturn \"pnpm\";\n\t}\n\tif (resolvedPath.includes(\"/yarn/\") || resolvedPath.includes(\"/.yarn/\")) {\n\t\treturn \"yarn\";\n\t}\n\tif (isBunRuntime || resolvedPath.includes(\"/install/global/node_modules/\")) {\n\t\treturn \"bun\";\n\t}\n\tif (resolvedPath.includes(\"/npm/\") || resolvedPath.includes(\"/node_modules/\")) {\n\t\treturn \"npm\";\n\t}\n\n\treturn \"unknown\";\n}\n\nfunction getInferredNpmInstall(): { root: string; prefix: string } | undefined {\n\tconst packageDir = getPackageDir();\n\tconst path = process.platform === \"win32\" || packageDir.includes(\"\\\\\") ? win32 : { basename, dirname };\n\tconst parent = path.dirname(packageDir);\n\tlet root: string | undefined;\n\tif (path.basename(parent).startsWith(\"@\") && path.basename(path.dirname(parent)) === \"node_modules\") {\n\t\troot = path.dirname(parent);\n\t} else if (path.basename(parent) === \"node_modules\") {\n\t\troot = parent;\n\t}\n\tif (!root) return undefined;\n\tconst rootParent = path.dirname(root);\n\tif (path.basename(rootParent) === \"lib\") return { root, prefix: path.dirname(rootParent) };\n\t// Windows global npm prefixes use `<prefix>\\\\node_modules`, which is\n\t// indistinguishable from local project installs by path shape alone. Do not\n\t// infer unsupported Windows custom prefixes without `npm root -g` evidence.\n\treturn undefined;\n}\n\nfunction getSelfUpdateCommandForMethod(\n\tmethod: InstallMethod,\n\tinstalledPackageName: string,\n\tupdatePackageTarget: SelfUpdatePackageTarget = installedPackageName,\n\tnpmCommand?: string[],\n): SelfUpdateCommand | undefined {\n\tconst target = normalizeSelfUpdatePackageTarget(updatePackageTarget);\n\tswitch (method) {\n\t\tcase \"bun-binary\":\n\t\t\treturn undefined;\n\t\tcase \"source\": {\n\t\t\tif (target.packageName !== installedPackageName) return undefined;\n\t\t\tconst packageDir = getPackageDir();\n\t\t\tconst steps = [\n\t\t\t\tmakeSelfUpdateCommandStep(\"git\", [\"-C\", packageDir, \"pull\", \"--ff-only\"]),\n\t\t\t\tmakeSelfUpdateCommandStep(\"npm\", [\"--prefix\", packageDir, \"install\"]),\n\t\t\t\tmakeSelfUpdateCommandStep(\"npm\", [\"--prefix\", packageDir, \"run\", \"build\"]),\n\t\t\t];\n\t\t\treturn { ...steps[0], display: steps.map((step) => step.display).join(\" && \"), steps };\n\t\t}\n\t\tcase \"pnpm\": {\n\t\t\tconst match = readCommandOutput(\"pnpm\", [\"root\", \"-g\"])\n\t\t\t\t? undefined\n\t\t\t\t: /^(.*[\\\\/]global[\\\\/][^\\\\/]+)[\\\\/]\\.pnpm[\\\\/]/.exec(getPackageDir());\n\t\t\tconst binDirArgs = match\n\t\t\t\t? [`--config.global-bin-dir=${process.env.PNPM_HOME || dirname(dirname(match[1]))}`]\n\t\t\t\t: [];\n\t\t\treturn makeSelfUpdateCommand(\n\t\t\t\tmakeSelfUpdateCommandStep(\"pnpm\", [\n\t\t\t\t\t\"install\",\n\t\t\t\t\t\"-g\",\n\t\t\t\t\t\"--ignore-scripts\",\n\t\t\t\t\t\"--config.minimumReleaseAge=0\",\n\t\t\t\t\t...binDirArgs,\n\t\t\t\t\ttarget.installSpec,\n\t\t\t\t]),\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(\"pnpm\", [\"remove\", \"-g\", ...binDirArgs, installedPackageName]),\n\t\t\t);\n\t\t}\n\t\tcase \"yarn\":\n\t\t\treturn makeSelfUpdateCommand(\n\t\t\t\tmakeSelfUpdateCommandStep(\"yarn\", [\"global\", \"add\", \"--ignore-scripts\", target.installSpec]),\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(\"yarn\", [\"global\", \"remove\", installedPackageName]),\n\t\t\t);\n\t\tcase \"bun\":\n\t\t\treturn makeSelfUpdateCommand(\n\t\t\t\tmakeSelfUpdateCommandStep(\"bun\", [\n\t\t\t\t\t\"install\",\n\t\t\t\t\t\"-g\",\n\t\t\t\t\t\"--ignore-scripts\",\n\t\t\t\t\t\"--minimum-release-age=0\",\n\t\t\t\t\ttarget.installSpec,\n\t\t\t\t]),\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(\"bun\", [\"uninstall\", \"-g\", installedPackageName]),\n\t\t\t);\n\t\tcase \"npm\": {\n\t\t\tconst [command = \"npm\", ...npmArgs] = npmCommand ?? [];\n\t\t\tconst inferred = npmCommand?.length ? undefined : getInferredNpmInstall();\n\t\t\tconst prefixArgs = [...npmArgs, ...(inferred ? [\"--prefix\", inferred.prefix] : [])];\n\t\t\tconst installStep = makeSelfUpdateCommandStep(command, [\n\t\t\t\t...prefixArgs,\n\t\t\t\t\"install\",\n\t\t\t\t\"-g\",\n\t\t\t\t\"--ignore-scripts\",\n\t\t\t\t\"--min-release-age=0\",\n\t\t\t\ttarget.installSpec,\n\t\t\t]);\n\t\t\tconst uninstallStep =\n\t\t\t\ttarget.packageName === installedPackageName\n\t\t\t\t\t? undefined\n\t\t\t\t\t: makeSelfUpdateCommandStep(command, [...prefixArgs, \"uninstall\", \"-g\", installedPackageName]);\n\t\t\treturn makeSelfUpdateCommand(installStep, uninstallStep);\n\t\t}\n\t\tcase \"unknown\":\n\t\t\treturn undefined;\n\t}\n}\n\nfunction readCommandOutput(\n\tcommand: string,\n\targs: string[],\n\toptions: { requireSuccess?: boolean } = {},\n): string | undefined {\n\tconst result = spawnProcessSync(command, args, {\n\t\tencoding: \"utf-8\",\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t});\n\tif (result.status === 0) return result.stdout.trim() || undefined;\n\tif (options.requireSuccess) {\n\t\tconst reason = result.error?.message || result.stderr.trim() || `exit code ${result.status ?? \"unknown\"}`;\n\t\tthrow new Error(`Failed to run ${[command, ...args].join(\" \")}: ${reason}`);\n\t}\n\treturn undefined;\n}\n\nfunction getGlobalPackageRoots(method: InstallMethod, _packageName: string, npmCommand?: string[]): string[] {\n\tswitch (method) {\n\t\tcase \"npm\": {\n\t\t\tconst configured = !!npmCommand?.length;\n\t\t\tconst [command = \"npm\", ...npmArgs] = npmCommand ?? [];\n\t\t\tif (configured && command === \"bun\") {\n\t\t\t\tconst bunBin = readCommandOutput(command, [...npmArgs, \"pm\", \"bin\", \"-g\"], {\n\t\t\t\t\trequireSuccess: true,\n\t\t\t\t});\n\t\t\t\tconst roots = [join(homedir(), \".bun\", \"install\", \"global\", \"node_modules\")];\n\t\t\t\tif (bunBin) {\n\t\t\t\t\troots.push(join(dirname(bunBin), \"install\", \"global\", \"node_modules\"));\n\t\t\t\t}\n\t\t\t\treturn roots;\n\t\t\t}\n\t\t\tconst root = readCommandOutput(command, [...npmArgs, \"root\", \"-g\"], {\n\t\t\t\trequireSuccess: configured,\n\t\t\t});\n\t\t\tconst inferred = configured ? undefined : getInferredNpmInstall();\n\t\t\treturn [root, inferred?.root].filter((x): x is string => !!x);\n\t\t}\n\t\tcase \"pnpm\": {\n\t\t\tconst root = readCommandOutput(\"pnpm\", [\"root\", \"-g\"]);\n\t\t\tif (root) return [root, dirname(root)];\n\t\t\tconst match = /^(.*[\\\\/]global[\\\\/][^\\\\/]+)[\\\\/]\\.pnpm[\\\\/]/.exec(getPackageDir());\n\t\t\treturn match ? [match[1]] : [];\n\t\t}\n\t\tcase \"yarn\": {\n\t\t\tconst dir = readCommandOutput(\"yarn\", [\"global\", \"dir\"]);\n\t\t\treturn dir ? [dir, join(dir, \"node_modules\")] : [];\n\t\t}\n\t\tcase \"bun\": {\n\t\t\tconst bunBin = readCommandOutput(\"bun\", [\"pm\", \"bin\", \"-g\"]);\n\t\t\tconst roots = [join(homedir(), \".bun\", \"install\", \"global\", \"node_modules\")];\n\t\t\tif (bunBin) {\n\t\t\t\troots.push(join(dirname(bunBin), \"install\", \"global\", \"node_modules\"));\n\t\t\t}\n\t\t\treturn roots;\n\t\t}\n\t\tcase \"bun-binary\":\n\t\tcase \"source\":\n\t\tcase \"unknown\":\n\t\t\treturn [];\n\t}\n}\n\nfunction normalizeExistingPathForComparison(path: string, resolveSymlinks: boolean): string | undefined {\n\tconst resolvedPath = resolve(path);\n\tif (!existsSync(resolvedPath)) {\n\t\treturn undefined;\n\t}\n\tlet normalizedPath = resolvedPath;\n\tif (resolveSymlinks) {\n\t\ttry {\n\t\t\tnormalizedPath = realpathSync(resolvedPath);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\tif (process.platform === \"win32\") {\n\t\tnormalizedPath = normalizedPath.toLowerCase();\n\t}\n\treturn normalizedPath;\n}\n\nfunction getPathComparisonCandidates(path: string): string[] {\n\treturn Array.from(\n\t\tnew Set(\n\t\t\t[normalizeExistingPathForComparison(path, false), normalizeExistingPathForComparison(path, true)].filter(\n\t\t\t\t(candidate): candidate is string => !!candidate,\n\t\t\t),\n\t\t),\n\t);\n}\n\nfunction getEntrypointPackageDir(): string | undefined {\n\tconst entrypoint = process.argv[1];\n\tif (!entrypoint) return undefined;\n\tlet dir = dirname(entrypoint);\n\twhile (dir !== dirname(dir)) {\n\t\tif (existsSync(join(dir, \"package.json\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tdir = dirname(dir);\n\t}\n\treturn undefined;\n}\n\nfunction isSelfUpdatePathWritable(): boolean {\n\tconst packageDir = getPackageDir();\n\ttry {\n\t\taccessSync(packageDir, constants.W_OK);\n\t\taccessSync(dirname(packageDir), constants.W_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction isManagedByGlobalPackageManager(method: InstallMethod, packageName: string, npmCommand?: string[]): boolean {\n\tconst packageDirs = [getPackageDir(), getEntrypointPackageDir()].filter((dir): dir is string => !!dir);\n\tconst packageDirCandidates = packageDirs.flatMap((dir) => getPathComparisonCandidates(dir));\n\treturn getGlobalPackageRoots(method, packageName, npmCommand).some((root) => {\n\t\treturn getPathComparisonCandidates(root).some((normalizedRoot) => {\n\t\t\tconst rootPrefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\t\treturn packageDirCandidates.some((packageDir) => packageDir.startsWith(rootPrefix));\n\t\t});\n\t});\n}\n\nexport function getSelfUpdateCommand(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdatePackageTarget: SelfUpdatePackageTarget = packageName,\n): SelfUpdateCommand | undefined {\n\tconst method = detectInstallMethod();\n\tconst command = getSelfUpdateCommandForMethod(method, packageName, updatePackageTarget, npmCommand);\n\tif (!command || !isSelfUpdatePathWritable()) {\n\t\treturn undefined;\n\t}\n\tif (method !== \"source\" && !isManagedByGlobalPackageManager(method, packageName, npmCommand)) {\n\t\treturn undefined;\n\t}\n\treturn command;\n}\n\nexport function getSelfUpdateUnavailableInstruction(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdatePackageTarget: SelfUpdatePackageTarget = packageName,\n): string {\n\tconst method = detectInstallMethod();\n\tconst target = normalizeSelfUpdatePackageTarget(updatePackageTarget);\n\tif (method === \"bun-binary\") {\n\t\treturn `Download from: https://github.com/earendil-works/pi-mono/releases/latest`;\n\t}\n\tconst command = getSelfUpdateCommandForMethod(method, packageName, target, npmCommand);\n\tif (command) {\n\t\tif (method === \"source\") {\n\t\t\treturn isSelfUpdatePathWritable()\n\t\t\t\t? `Update the source checkout yourself with: ${command.display}`\n\t\t\t\t: `This source checkout is not writable. Update it yourself with: ${command.display}`;\n\t\t}\n\t\tif (isManagedByGlobalPackageManager(method, packageName, npmCommand) && !isSelfUpdatePathWritable()) {\n\t\t\treturn `This installation is managed by a global ${method} install, but the install path is not writable. Update it yourself with: ${command.display}`;\n\t\t}\n\t\treturn `This installation is not managed by a global ${method} install. Update it with the package manager, wrapper, or source checkout that provides it.`;\n\t}\n\treturn `Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`;\n}\n\nexport function getUpdateInstruction(packageName: string): string {\n\tconst method = detectInstallMethod();\n\tconst command = getSelfUpdateCommandForMethod(method, packageName);\n\tif (command) {\n\t\treturn `Run: ${command.display}`;\n\t}\n\treturn getSelfUpdateUnavailableInstruction(packageName);\n}\n\n// =============================================================================\n// Package Asset Paths (shipped with executable)\n// =============================================================================\n\n/**\n * Get the base directory for resolving package assets (themes, package.json, README.md, CHANGELOG.md).\n * - For Bun binary: returns the directory containing the executable\n * - For Node.js (dist/): returns __dirname (the dist/ directory)\n * - For tsx (src/): returns parent directory (the package root)\n */\nexport function getPackageDir(): string {\n\t// Allow override via environment variable (useful for Nix/Guix where store paths tokenize poorly)\n\tconst envDir = process.env.PI_PACKAGE_DIR;\n\tif (envDir) {\n\t\treturn normalizePath(envDir);\n\t}\n\n\tif (isBunBinary) {\n\t\t// Bun binary: process.execPath points to the compiled executable\n\t\treturn dirname(process.execPath);\n\t}\n\t// Node.js: walk up from __dirname until we find package.json\n\tlet dir = __dirname;\n\twhile (dir !== dirname(dir)) {\n\t\tif (existsSync(join(dir, \"package.json\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tdir = dirname(dir);\n\t}\n\t// Fallback (shouldn't happen)\n\treturn __dirname;\n}\n\n/**\n * Get path to built-in themes directory (shipped with package)\n * - For Bun binary: theme/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/theme/\n * - For tsx (src/): src/modes/interactive/theme/\n */\nexport function getThemesDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"theme\");\n\t}\n\t// Theme is in modes/interactive/theme/ relative to src/ or dist/\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, \"modes\", \"interactive\", \"theme\");\n}\n\n/**\n * Get path to HTML export template directory (shipped with package)\n * - For Bun binary: export-html/ next to executable\n * - For Node.js (dist/): dist/core/export-html/\n * - For tsx (src/): src/core/export-html/\n */\nexport function getExportTemplateDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"export-html\");\n\t}\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, \"core\", \"export-html\");\n}\n\n/** Get path to package.json */\nexport function getPackageJsonPath(): string {\n\treturn join(getPackageDir(), \"package.json\");\n}\n\n/** Get path to README.md */\nexport function getReadmePath(): string {\n\treturn resolve(join(getPackageDir(), \"README.md\"));\n}\n\n/** Get path to docs directory */\nexport function getDocsPath(): string {\n\treturn resolve(join(getPackageDir(), \"docs\"));\n}\n\n/** Get path to examples directory */\nexport function getExamplesPath(): string {\n\treturn resolve(join(getPackageDir(), \"examples\"));\n}\n\n/** Get path to CHANGELOG.md */\nexport function getChangelogPath(): string {\n\treturn resolve(join(getPackageDir(), \"CHANGELOG.md\"));\n}\n\n/**\n * Get path to built-in interactive assets directory.\n * - For Bun binary: assets/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/assets/\n * - For tsx (src/): src/modes/interactive/assets/\n */\nexport function getInteractiveAssetsDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"assets\");\n\t}\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, \"modes\", \"interactive\", \"assets\");\n}\n\n/**\n * Resolve a bundled subdirectory shipped with the package (defaults/extensions/themes).\n * - For Bun binary: <dir>/ next to executable\n * - For Node.js (dist/): dist/<dir>/\n * - For tsx (src/): src/<dir>/\n */\nfunction getBundledSubdir(name: string): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), name);\n\t}\n\tconst packageDir = getPackageDir();\n\tconst srcOrDist = existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\";\n\treturn join(packageDir, srcOrDist, name);\n}\n\n/**\n * Get path to bundled default config directory (shipped with package).\n * Holds bundled defaults. settings.json is copied on first run; models.json is loaded directly.\n */\nexport function getBundledDefaultsDir(): string {\n\treturn getBundledSubdir(\"defaults\");\n}\n\n/**\n * Get path to bundled built-in extensions directory (shipped with package).\n * Loaded directly via additionalExtensionPaths at boot (not copied into the\n * user agent dir) — same hook as CLI --extension. .ts ships as-is (jiti loads it).\n * - For Bun binary: extensions/ next to executable\n * - For Node.js (dist/): dist/extensions/\n * - For tsx (src/): src/extensions/\n */\nexport function getBundledExtensionsDir(): string {\n\treturn getBundledSubdir(\"extensions\");\n}\n\n/**\n * Get path to bundled built-in themes directory (shipped with package).\n * Loaded directly via additionalThemePaths at boot.\n */\nexport function getBundledThemesDir(): string {\n\treturn getBundledSubdir(\"themes\");\n}\n\n/**\n * Get path to bundled built-in skills directory (shipped with package).\n * Loaded directly via additionalSkillPaths at boot.\n */\nexport function getBundledSkillsDir(): string {\n\treturn getBundledSubdir(\"skills\");\n}\n\n/** Get path to a bundled interactive asset */\nexport function getBundledInteractiveAssetPath(name: string): string {\n\treturn join(getInteractiveAssetsDir(), name);\n}\n\n// =============================================================================\n// App Config (from package.json piConfig)\n// =============================================================================\n\ninterface PackageJson {\n\tname?: string;\n\tversion?: string;\n\tpiConfig?: {\n\t\tname?: string;\n\t\tconfigDir?: string;\n\t};\n}\n\nlet pkg: PackageJson = {};\ntry {\n\tpkg = JSON.parse(readFileSync(getPackageJsonPath(), \"utf-8\")) as PackageJson;\n} catch (e: unknown) {\n\tconst err = e as NodeJS.ErrnoException;\n\tif (err.code !== \"ENOENT\") throw e;\n}\n\nconst piConfigName: string | undefined = pkg.piConfig?.name;\nexport const PACKAGE_NAME: string = pkg.name || \"@earendil-works/pi-coding-agent\";\nexport const APP_NAME: string = piConfigName || \"pi\";\nexport const APP_TITLE: string = piConfigName ? APP_NAME : \"π\";\nexport const CONFIG_DIR_NAME: string = pkg.piConfig?.configDir || \".pi\";\nexport const VERSION: string = pkg.version || \"0.0.0\";\n\n// e.g., PI_CODING_AGENT_DIR or TAU_CODING_AGENT_DIR\nexport const ENV_AGENT_DIR = `${APP_NAME.toUpperCase()}_CODING_AGENT_DIR`;\nexport const ENV_SESSION_DIR = `${APP_NAME.toUpperCase()}_CODING_AGENT_SESSION_DIR`;\n\nexport function expandTildePath(path: string): string {\n\treturn normalizePath(path);\n}\n\nconst DEFAULT_SHARE_VIEWER_URL = \"https://pi.dev/session/\";\n\n/** Get the share viewer URL for a gist ID */\nexport function getShareViewerUrl(gistId: string): string {\n\tconst baseUrl = process.env.PI_SHARE_VIEWER_URL || DEFAULT_SHARE_VIEWER_URL;\n\treturn `${baseUrl}#${gistId}`;\n}\n\n// =============================================================================\n// User Config Paths (~/<configured-dir>/agent/*)\n// =============================================================================\n\n/** Get the agent config directory (e.g., ~/.selesai/agent/) */\nexport function getAgentDir(): string {\n\tconst envDir = process.env[ENV_AGENT_DIR];\n\tif (envDir) {\n\t\treturn expandTildePath(envDir);\n\t}\n\treturn join(homedir(), CONFIG_DIR_NAME, \"agent\");\n}\n\n/** Get path to user's custom themes directory */\nexport function getCustomThemesDir(): string {\n\treturn join(getAgentDir(), \"themes\");\n}\n\n/** Get path to models.json */\nexport function getModelsPath(): string {\n\treturn join(getAgentDir(), \"models.json\");\n}\n\n/** Get path to auth.json */\nexport function getAuthPath(): string {\n\treturn join(getAgentDir(), \"auth.json\");\n}\n\n/** Get path to settings.json */\nexport function getSettingsPath(): string {\n\treturn join(getAgentDir(), \"settings.json\");\n}\n\n/** Get path to tools directory */\nexport function getToolsDir(): string {\n\treturn join(getAgentDir(), \"tools\");\n}\n\n/** Get path to managed binaries directory (fd, rg) */\nexport function getBinDir(): string {\n\treturn join(getAgentDir(), \"bin\");\n}\n\n/** Get path to prompt templates directory */\nexport function getPromptsDir(): string {\n\treturn join(getAgentDir(), \"prompts\");\n}\n\n/** Get path to sessions directory */\nexport function getSessionsDir(): string {\n\treturn join(getAgentDir(), \"sessions\");\n}\n\n/** Get path to debug log file */\nexport function getDebugLogPath(): string {\n\treturn join(getAgentDir(), `${APP_NAME}-debug.log`);\n}\n\n/**\n * Marker file written once first-time onboarding completes. Decouples the\n * first-run dialog gate from settings.json existence so that bootstrapping a\n * bundled default settings.json does not suppress the dialog.\n */\nexport function getFirstRunMarkerPath(agentDir: string = getAgentDir()): string {\n\treturn join(agentDir, \".firstRunComplete\");\n}\n\n/**\n * Mark first-run onboarding as complete. Safe to call repeatedly.\n */\nexport function markFirstRunComplete(agentDir: string = getAgentDir()): void {\n\tmkdirSync(agentDir, { recursive: true, mode: 0o700 });\n\twriteFileSync(getFirstRunMarkerPath(agentDir), \"1\", { mode: 0o600 });\n}\n\n// =============================================================================\n// Agent Dir Bootstrap (first-run seeding and settings migration)\n// =============================================================================\n\n/** Subdirectories created under the agent dir on first run. */\nconst AGENT_SUBDIRS = [\n\t\"themes\",\n\t\"tools\",\n\t\"bin\",\n\t\"prompts\",\n\t\"sessions\",\n\t\"extensions\",\n\t\"skills\",\n] as const;\n\n/**\n * Ensure the agent dir and standard subdirs exist (mode 0o700 for privacy).\n * Safe to call on every startup; no-op when dirs already exist.\n */\nexport function ensureAgentDir(agentDir: string = getAgentDir()): void {\n\tmkdirSync(agentDir, { recursive: true, mode: 0o700 });\n\tfor (const sub of AGENT_SUBDIRS) {\n\t\tmkdirSync(join(agentDir, sub), { recursive: true, mode: 0o700 });\n\t}\n}\n\n/**\n * Seed a default config file from the bundled defaults dir if it does not yet\n * exist. Never overwrites an existing user file. Returns the destination path\n * when a seed was written, undefined when the file already existed or the\n * bundled source is missing.\n */\nexport function seedDefaultConfigFile(\n\tdestPath: string,\n\tbundledName: string,\n\tbundledDefaultsDir: string = getBundledDefaultsDir(),\n): string | undefined {\n\tif (existsSync(destPath)) return undefined;\n\tconst source = join(bundledDefaultsDir, bundledName);\n\tif (!existsSync(source)) return undefined;\n\tmkdirSync(dirname(destPath), { recursive: true, mode: 0o700 });\n\tcopyFileSync(source, destPath);\n\ttry {\n\t\tchmodSync(destPath, 0o600);\n\t} catch {\n\t\t// chmod is best-effort (no-op on platforms that don't support it).\n\t}\n\treturn destPath;\n}\n\n/**\n * Insert a top-level key into the root object of a JSON document without\n * touching any other bytes: the user's formatting, unknown keys, and trailing\n * whitespace survive verbatim. Returns the new document text, or undefined\n * when the root value is not a JSON object.\n */\nfunction injectRootObjectKey(raw: string, key: string, value: unknown): string | undefined {\n\tlet inString = false;\n\tlet escaped = false;\n\tlet depth = 0;\n\tlet rootOpen = -1;\n\tlet rootClose = -1;\n\tfor (let i = 0; i < raw.length; i++) {\n\t\tconst ch = raw[i]!;\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (ch === \"\\\\\") escaped = true;\n\t\t\telse if (ch === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"{\" || ch === \"[\") {\n\t\t\tif (depth === 0) rootOpen = i;\n\t\t\tdepth++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"}\" || ch === \"]\") {\n\t\t\tdepth--;\n\t\t\tif (depth < 0) return undefined;\n\t\t\tif (depth === 0 && ch === \"}\") {\n\t\t\t\trootClose = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (rootOpen === -1 || rootClose === -1 || raw[rootOpen] !== \"{\") return undefined;\n\n\tconst keyJson = `${JSON.stringify(key)}: ${JSON.stringify(value)}`;\n\tlet lastContentIndex = -1;\n\tfor (let i = rootClose - 1; i > rootOpen; i--) {\n\t\tif (!/\\s/.test(raw[i]!)) {\n\t\t\tlastContentIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (lastContentIndex === -1) {\n\t\t// Empty root object: inject right after the opening brace.\n\t\treturn `${raw.slice(0, rootOpen + 1)}${keyJson}${raw.slice(rootOpen + 1)}`;\n\t}\n\t// Append after the last content token, before the original whitespace run.\n\treturn `${raw.slice(0, lastContentIndex + 1)}, ${keyJson}${raw.slice(lastContentIndex + 1)}`;\n}\n\n/**\n * Add bundled subagent defaults to an existing user settings file when that\n * top-level setting is absent. The file is modified with a minimal textual\n * insertion, so unrelated settings (including their formatting and unknown\n * keys) are preserved byte-for-byte. Invalid or non-object JSON, or a user\n * file that already configures `subagents`, is left untouched.\n */\nexport function seedMissingSubagentSettings(\n\tdestPath: string,\n\tbundledDefaultsDir: string = getBundledDefaultsDir(),\n): boolean {\n\tif (!existsSync(destPath)) return false;\n\n\ttry {\n\t\tconst raw = readFileSync(destPath, \"utf-8\");\n\t\tconst settings = JSON.parse(raw) as unknown;\n\t\tconst defaults = JSON.parse(readFileSync(join(bundledDefaultsDir, \"settings.json\"), \"utf-8\")) as unknown;\n\t\tif (\n\t\t\ttypeof settings !== \"object\" ||\n\t\t\tsettings === null ||\n\t\t\tArray.isArray(settings) ||\n\t\t\tObject.hasOwn(settings, \"subagents\") ||\n\t\t\ttypeof defaults !== \"object\" ||\n\t\t\tdefaults === null ||\n\t\t\tArray.isArray(defaults) ||\n\t\t\t!Object.hasOwn(defaults, \"subagents\")\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst injected = injectRootObjectKey(raw, \"subagents\", (defaults as Record<string, unknown>).subagents);\n\t\tif (injected === undefined) return false;\n\t\twriteFileSync(destPath, injected);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Recursively copy a bundled directory tree into the user's agent dir, skipping\n * any file that already exists (user edits survive). Never overwrites. Used to\n * seed bundled skills/themes so the user can inspect and edit them.\n * Returns the list of destination paths that were written.\n */\nfunction seedBundledDir(\n\tdestDir: string,\n\tbundledDir: string,\n): string[] {\n\tif (!existsSync(bundledDir)) return [];\n\tmkdirSync(destDir, { recursive: true, mode: 0o700 });\n\tconst written: string[] = [];\n\tconst stack: Array<{ src: string; dst: string }> = [{ src: bundledDir, dst: destDir }];\n\twhile (stack.length > 0) {\n\t\tconst { src, dst } = stack.pop()!;\n\t\tmkdirSync(dst, { recursive: true, mode: 0o700 });\n\t\tfor (const entry of readdirSync(src, { withFileTypes: true })) {\n\t\t\tif (entry.name === \".DS_Store\" || entry.name === \"node_modules\") continue;\n\t\t\tconst srcPath = join(src, entry.name);\n\t\t\tconst dstPath = join(dst, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tif (!existsSync(dstPath)) mkdirSync(dstPath, { recursive: true, mode: 0o700 });\n\t\t\t\tstack.push({ src: srcPath, dst: dstPath });\n\t\t\t} else if (entry.isFile() || entry.isSymbolicLink()) {\n\t\t\t\tif (existsSync(dstPath)) continue;\n\t\t\t\tcopyFileSync(srcPath, dstPath);\n\t\t\t\ttry {\n\t\t\t\t\tchmodSync(dstPath, 0o600);\n\t\t\t\t} catch {\n\t\t\t\t\t// best-effort\n\t\t\t\t}\n\t\t\t\twritten.push(dstPath);\n\t\t\t}\n\t\t}\n\t}\n\treturn written;\n}\n\nfunction removeIdenticalBundledFiles(destDir: string, bundledDir: string): string[] {\n\tif (!existsSync(destDir) || !existsSync(bundledDir)) return [];\n\tconst removed: string[] = [];\n\tconst stack: Array<{ src: string; dst: string }> = [{ src: bundledDir, dst: destDir }];\n\twhile (stack.length > 0) {\n\t\tconst { src, dst } = stack.pop()!;\n\t\tif (!existsSync(dst)) continue;\n\t\tfor (const entry of readdirSync(src, { withFileTypes: true })) {\n\t\t\tif (entry.name === \".DS_Store\" || entry.name === \"node_modules\") continue;\n\t\t\tconst srcPath = join(src, entry.name);\n\t\t\tconst dstPath = join(dst, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push({ src: srcPath, dst: dstPath });\n\t\t\t} else if (existsSync(dstPath) && readFileSync(srcPath).equals(readFileSync(dstPath))) {\n\t\t\t\tunlinkSync(dstPath);\n\t\t\t\tremoved.push(dstPath);\n\t\t\t}\n\t\t}\n\t}\n\treturn removed;\n}\n\n/**\n * Bundled extensions load directly from the installed package. Do not copy them\n * into the user's agent dir, otherwise startup discovers both copies and tool\n * registration conflicts with itself.\n * Remove files copied by older releases only when they are byte-identical to\n * bundled files, so user-edited extensions survive.\n */\nexport function seedDefaultExtensions(\n\tagentDir: string,\n\tbundledExtensionsDir: string = getBundledExtensionsDir(),\n): string[] {\n\tremoveIdenticalBundledFiles(join(agentDir, \"extensions\"), bundledExtensionsDir);\n\treturn [];\n}\n\n/**\n * Seed bundled built-in skills into the user's agent dir/skills.\n * Ownership rule: bundled files are installed only when missing, so a new\n * release can supply new bundled skills, but existing user files are never\n * overwritten — user-authored edits survive. User-only skills stay. The\n * authoritative bundled copy still loads directly from the package at boot\n * (additionalSkillPaths), so a stale user copy never loses functionality.\n * Returns the list of destination paths that were written.\n */\nexport function seedDefaultSkills(\n\tagentDir: string,\n\tbundledSkillsDir: string = getBundledSkillsDir(),\n): string[] {\n\treturn seedBundledDir(join(agentDir, \"skills\"), bundledSkillsDir);\n}\n\n/**\n * Seed bundled built-in themes into the user's agent dir/themes.\n * Skips existing files (user edits survive). Never overwrites.\n * Returns the list of destination paths that were written.\n */\nexport function seedDefaultThemes(\n\tagentDir: string,\n\tbundledThemesDir: string = getBundledThemesDir(),\n): string[] {\n\treturn seedBundledDir(join(agentDir, \"themes\"), bundledThemesDir);\n}\n\n/**\n * Run bootstrap for the agent dir: ensure directories, seed a missing\n * settings.json, and add missing bundled subagent defaults. Idempotent — safe\n * on every startup.\n * Bundled models load package-locally; copying them would expose internal\n * providers as user config. Bundled extensions also stay package-local.\n */\nexport function bootstrapAgentDir(agentDir: string = getAgentDir()): void {\n\tensureAgentDir(agentDir);\n\tconst settingsPath = join(agentDir, \"settings.json\");\n\tseedDefaultConfigFile(settingsPath, \"settings.json\");\n\tseedMissingSubagentSettings(settingsPath);\n\tseedDefaultExtensions(agentDir);\n\tseedDefaultSkills(agentDir);\n\tseedDefaultThemes(agentDir);\n}\n"]}
|
package/dist/config.js
CHANGED
|
@@ -537,7 +537,7 @@ export function markFirstRunComplete(agentDir = getAgentDir()) {
|
|
|
537
537
|
writeFileSync(getFirstRunMarkerPath(agentDir), "1", { mode: 0o600 });
|
|
538
538
|
}
|
|
539
539
|
// =============================================================================
|
|
540
|
-
// Agent Dir Bootstrap (first-run seeding)
|
|
540
|
+
// Agent Dir Bootstrap (first-run seeding and settings migration)
|
|
541
541
|
// =============================================================================
|
|
542
542
|
/** Subdirectories created under the agent dir on first run. */
|
|
543
543
|
const AGENT_SUBDIRS = [
|
|
@@ -581,6 +581,100 @@ export function seedDefaultConfigFile(destPath, bundledName, bundledDefaultsDir
|
|
|
581
581
|
}
|
|
582
582
|
return destPath;
|
|
583
583
|
}
|
|
584
|
+
/**
|
|
585
|
+
* Insert a top-level key into the root object of a JSON document without
|
|
586
|
+
* touching any other bytes: the user's formatting, unknown keys, and trailing
|
|
587
|
+
* whitespace survive verbatim. Returns the new document text, or undefined
|
|
588
|
+
* when the root value is not a JSON object.
|
|
589
|
+
*/
|
|
590
|
+
function injectRootObjectKey(raw, key, value) {
|
|
591
|
+
let inString = false;
|
|
592
|
+
let escaped = false;
|
|
593
|
+
let depth = 0;
|
|
594
|
+
let rootOpen = -1;
|
|
595
|
+
let rootClose = -1;
|
|
596
|
+
for (let i = 0; i < raw.length; i++) {
|
|
597
|
+
const ch = raw[i];
|
|
598
|
+
if (inString) {
|
|
599
|
+
if (escaped)
|
|
600
|
+
escaped = false;
|
|
601
|
+
else if (ch === "\\")
|
|
602
|
+
escaped = true;
|
|
603
|
+
else if (ch === '"')
|
|
604
|
+
inString = false;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
if (ch === '"') {
|
|
608
|
+
inString = true;
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
if (ch === "{" || ch === "[") {
|
|
612
|
+
if (depth === 0)
|
|
613
|
+
rootOpen = i;
|
|
614
|
+
depth++;
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (ch === "}" || ch === "]") {
|
|
618
|
+
depth--;
|
|
619
|
+
if (depth < 0)
|
|
620
|
+
return undefined;
|
|
621
|
+
if (depth === 0 && ch === "}") {
|
|
622
|
+
rootClose = i;
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
if (rootOpen === -1 || rootClose === -1 || raw[rootOpen] !== "{")
|
|
628
|
+
return undefined;
|
|
629
|
+
const keyJson = `${JSON.stringify(key)}: ${JSON.stringify(value)}`;
|
|
630
|
+
let lastContentIndex = -1;
|
|
631
|
+
for (let i = rootClose - 1; i > rootOpen; i--) {
|
|
632
|
+
if (!/\s/.test(raw[i])) {
|
|
633
|
+
lastContentIndex = i;
|
|
634
|
+
break;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (lastContentIndex === -1) {
|
|
638
|
+
// Empty root object: inject right after the opening brace.
|
|
639
|
+
return `${raw.slice(0, rootOpen + 1)}${keyJson}${raw.slice(rootOpen + 1)}`;
|
|
640
|
+
}
|
|
641
|
+
// Append after the last content token, before the original whitespace run.
|
|
642
|
+
return `${raw.slice(0, lastContentIndex + 1)}, ${keyJson}${raw.slice(lastContentIndex + 1)}`;
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Add bundled subagent defaults to an existing user settings file when that
|
|
646
|
+
* top-level setting is absent. The file is modified with a minimal textual
|
|
647
|
+
* insertion, so unrelated settings (including their formatting and unknown
|
|
648
|
+
* keys) are preserved byte-for-byte. Invalid or non-object JSON, or a user
|
|
649
|
+
* file that already configures `subagents`, is left untouched.
|
|
650
|
+
*/
|
|
651
|
+
export function seedMissingSubagentSettings(destPath, bundledDefaultsDir = getBundledDefaultsDir()) {
|
|
652
|
+
if (!existsSync(destPath))
|
|
653
|
+
return false;
|
|
654
|
+
try {
|
|
655
|
+
const raw = readFileSync(destPath, "utf-8");
|
|
656
|
+
const settings = JSON.parse(raw);
|
|
657
|
+
const defaults = JSON.parse(readFileSync(join(bundledDefaultsDir, "settings.json"), "utf-8"));
|
|
658
|
+
if (typeof settings !== "object" ||
|
|
659
|
+
settings === null ||
|
|
660
|
+
Array.isArray(settings) ||
|
|
661
|
+
Object.hasOwn(settings, "subagents") ||
|
|
662
|
+
typeof defaults !== "object" ||
|
|
663
|
+
defaults === null ||
|
|
664
|
+
Array.isArray(defaults) ||
|
|
665
|
+
!Object.hasOwn(defaults, "subagents")) {
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
const injected = injectRootObjectKey(raw, "subagents", defaults.subagents);
|
|
669
|
+
if (injected === undefined)
|
|
670
|
+
return false;
|
|
671
|
+
writeFileSync(destPath, injected);
|
|
672
|
+
return true;
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
584
678
|
/**
|
|
585
679
|
* Recursively copy a bundled directory tree into the user's agent dir, skipping
|
|
586
680
|
* any file that already exists (user edits survive). Never overwrites. Used to
|
|
@@ -660,7 +754,11 @@ export function seedDefaultExtensions(agentDir, bundledExtensionsDir = getBundle
|
|
|
660
754
|
}
|
|
661
755
|
/**
|
|
662
756
|
* Seed bundled built-in skills into the user's agent dir/skills.
|
|
663
|
-
*
|
|
757
|
+
* Ownership rule: bundled files are installed only when missing, so a new
|
|
758
|
+
* release can supply new bundled skills, but existing user files are never
|
|
759
|
+
* overwritten — user-authored edits survive. User-only skills stay. The
|
|
760
|
+
* authoritative bundled copy still loads directly from the package at boot
|
|
761
|
+
* (additionalSkillPaths), so a stale user copy never loses functionality.
|
|
664
762
|
* Returns the list of destination paths that were written.
|
|
665
763
|
*/
|
|
666
764
|
export function seedDefaultSkills(agentDir, bundledSkillsDir = getBundledSkillsDir()) {
|
|
@@ -675,14 +773,17 @@ export function seedDefaultThemes(agentDir, bundledThemesDir = getBundledThemesD
|
|
|
675
773
|
return seedBundledDir(join(agentDir, "themes"), bundledThemesDir);
|
|
676
774
|
}
|
|
677
775
|
/**
|
|
678
|
-
* Run
|
|
679
|
-
* settings.json
|
|
776
|
+
* Run bootstrap for the agent dir: ensure directories, seed a missing
|
|
777
|
+
* settings.json, and add missing bundled subagent defaults. Idempotent — safe
|
|
778
|
+
* on every startup.
|
|
680
779
|
* Bundled models load package-locally; copying them would expose internal
|
|
681
780
|
* providers as user config. Bundled extensions also stay package-local.
|
|
682
781
|
*/
|
|
683
782
|
export function bootstrapAgentDir(agentDir = getAgentDir()) {
|
|
684
783
|
ensureAgentDir(agentDir);
|
|
685
|
-
|
|
784
|
+
const settingsPath = join(agentDir, "settings.json");
|
|
785
|
+
seedDefaultConfigFile(settingsPath, "settings.json");
|
|
786
|
+
seedMissingSubagentSettings(settingsPath);
|
|
686
787
|
seedDefaultExtensions(agentDir);
|
|
687
788
|
seedDefaultSkills(agentDir);
|
|
688
789
|
seedDefaultThemes(agentDir);
|