feat(extensions): add Roast Room, bring Codex to parity, fix audit findings
Roast Room is installed as a managed Git clone under ~/.my-ai-configuration/roast-room, shared by Claude and Codex. A personal launcher skill runs it from any folder, starts its live room when needed, and only runs when invoked by name (/roast-room, $roast-room). Codex now gets what was Claude-only before: the Caveman skill with a SessionStart hook that keeps it on, PreCompact and session-pointer hooks, execpolicy deny rules mirroring Claude's permissions.deny, and Impeccable's custom agents registered in ~/.codex/agents. The command-safety hook checks both shell dialects for Codex on Windows, where PowerShell text arrives as Bash, in both the PowerShell and Bash packages. Audit fixes: - command-safety blocks git checkout -- / restore / push --force / stash clear and find -delete, and treats heredoc bodies as text - removing a clone clears read-only Git files, git errors no longer abort the extension sync, and a lock left by a dead process is replaced - with-credential passes child flags such as -k or -d through unchanged and resolves commands from PATH - uninstall strips only owned hooks from settings.json and config.toml and keeps the selection while another client is installed; update keeps CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY; Bash merges write the same bytes as PowerShell - qmd no longer trusts a stale daemon.json after a lost start race and prunes collections of deleted repositories - Bash scripts avoid GNU-only find -printf Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
63a36d90e0
commit
b35e2254b3
48 files changed
+1059
-98
No files matched your search
@@ -9,7 +9,7 @@ from personal_instructions import CLIENT_FILES, render
|
||||
|
||||
|
||||
# Hook scripts this configuration installs; merges replace these and keep any foreign hooks.
|
||||
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook|search-?reminder)\.(?:ps1|sh)'
|
||||
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-?state-?pointer|caveman-?mode|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook|search-?reminder)\.(?:ps1|sh)'
|
||||
|
||||
|
||||
def is_flashbang(hook):
|
||||
@@ -109,17 +109,35 @@ def filter_flashbang(path):
|
||||
return filter_options(path, flashbang_enabled=False)
|
||||
|
||||
|
||||
def without_owned_hooks(groups):
|
||||
retained = []
|
||||
for group in groups:
|
||||
if not isinstance(group, dict) or not isinstance(group.get('hooks'), list):
|
||||
retained.append(group)
|
||||
continue
|
||||
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
|
||||
OWNED_HOOK_PATTERN,
|
||||
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
||||
if foreign:
|
||||
retained.append(dict(group, hooks=foreign))
|
||||
return retained
|
||||
|
||||
|
||||
def without_qmd_exclusion(settings):
|
||||
sandbox = settings.get('sandbox')
|
||||
if isinstance(sandbox, dict) and isinstance(sandbox.get('excludedCommands'), list):
|
||||
# The QMD exclusion is owned; managed settings re-add it only while semantic retrieval is enabled.
|
||||
excluded = [command for command in sandbox['excludedCommands'] if 'qmd-search.mjs' not in str(command)]
|
||||
settings['sandbox'] = dict(sandbox, excludedCommands=excluded) if excluded else {k: v for k, v in sandbox.items() if k != 'excludedCommands'}
|
||||
|
||||
|
||||
def merge_json(current, managed):
|
||||
if not isinstance(current, dict) or not isinstance(managed, dict):
|
||||
return managed
|
||||
result = dict(current)
|
||||
if 'statusLine' not in managed:
|
||||
result.pop('statusLine', None)
|
||||
sandbox = result.get('sandbox')
|
||||
if isinstance(sandbox, dict) and isinstance(sandbox.get('excludedCommands'), list):
|
||||
# The QMD exclusion is owned; managed settings re-add it only while semantic retrieval is enabled.
|
||||
excluded = [command for command in sandbox['excludedCommands'] if 'qmd-search.mjs' not in str(command)]
|
||||
result['sandbox'] = dict(sandbox, excludedCommands=excluded) if excluded else {k: v for k, v in sandbox.items() if k != 'excludedCommands'}
|
||||
without_qmd_exclusion(result)
|
||||
for key, value in managed.items():
|
||||
if key == 'hooks' and isinstance(value, dict) and isinstance(result.get(key), dict):
|
||||
hooks = dict(result[key])
|
||||
@@ -127,16 +145,7 @@ def merge_json(current, managed):
|
||||
groups = value.get(event, [])
|
||||
old_groups = hooks.get(event, [])
|
||||
if isinstance(groups, list) and isinstance(old_groups, list):
|
||||
retained = []
|
||||
for group in old_groups:
|
||||
if not isinstance(group, dict) or not isinstance(group.get('hooks'), list):
|
||||
retained.append(group)
|
||||
continue
|
||||
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
|
||||
OWNED_HOOK_PATTERN,
|
||||
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
||||
if foreign:
|
||||
retained.append(dict(group, hooks=foreign))
|
||||
retained = without_owned_hooks(old_groups)
|
||||
merged = groups + [group for group in retained if group not in groups]
|
||||
if merged:
|
||||
hooks[event] = merged
|
||||
@@ -236,9 +245,46 @@ def merge_toml(current_text, managed_text, statusline_enabled=True):
|
||||
return result
|
||||
|
||||
|
||||
def strip_json(current):
|
||||
"""Remove only what this setup owns (hooks, status line, QMD exclusion); keep everything else."""
|
||||
if not isinstance(current, dict):
|
||||
return current
|
||||
result = dict(current)
|
||||
status = result.get('statusLine')
|
||||
if isinstance(status, dict) and re.search(OWNED_HOOK_PATTERN, str(status.get('command', '')), re.I):
|
||||
del result['statusLine']
|
||||
without_qmd_exclusion(result)
|
||||
if isinstance(result.get('hooks'), dict):
|
||||
hooks = {}
|
||||
for event, groups in result['hooks'].items():
|
||||
remaining = without_owned_hooks(groups) if isinstance(groups, list) else groups
|
||||
if remaining:
|
||||
hooks[event] = remaining
|
||||
if hooks:
|
||||
result['hooks'] = hooks
|
||||
else:
|
||||
del result['hooks']
|
||||
return result
|
||||
|
||||
|
||||
def strip_toml(current_text):
|
||||
# Merging with an empty managed file drops owned hook tables and keeps every other line.
|
||||
result = merge_toml(current_text, '').lstrip('\r\n')
|
||||
return result if result.strip() else ''
|
||||
|
||||
|
||||
def strip_file(path):
|
||||
"""Return path's content without owned entries, or '' when nothing else remains."""
|
||||
content = path.read_text(encoding='utf-8-sig')
|
||||
if path.name == 'config.toml':
|
||||
return strip_toml(content)
|
||||
result = strip_json(json.loads(content))
|
||||
return json.dumps(result, indent=2, ensure_ascii=False) + '\n' if result else ''
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('filter', 'filter-instructions', 'merge-json', 'merge-toml'))
|
||||
parser.add_argument('action', choices=('filter', 'filter-instructions', 'merge-json', 'merge-toml', 'strip'))
|
||||
parser.add_argument('--path', type=Path)
|
||||
parser.add_argument('--current', type=Path)
|
||||
parser.add_argument('--flashbang', choices=('true', 'false'))
|
||||
@@ -256,6 +302,8 @@ if __name__ == '__main__':
|
||||
if args.destination and args.path.name in CLIENT_FILES.values():
|
||||
client = next(client for client, name in CLIENT_FILES.items() if name == args.path.name)
|
||||
result = render(result, args.destination.parent, client)
|
||||
elif args.action == 'strip':
|
||||
result = strip_file(args.current)
|
||||
else:
|
||||
managed = args.managed.read_text(encoding='utf-8-sig') if args.managed else sys.stdin.buffer.read().decode('utf-8-sig')
|
||||
current = args.current.read_text(encoding='utf-8-sig')
|
||||
|
||||
@@ -193,7 +193,7 @@ class Manager:
|
||||
raise ValueError('Invalid extension ownership ledger.')
|
||||
identities = set()
|
||||
for resource in self.state['resources']:
|
||||
if not isinstance(resource, dict) or resource.get('client') not in ('codex', 'claude', 'shared') or resource.get('kind') not in ('plugin', 'skill', 'qmd', 'cli', 'mcp'):
|
||||
if not isinstance(resource, dict) or resource.get('client') not in ('codex', 'claude', 'shared') or resource.get('kind') not in ('plugin', 'skill', 'qmd', 'cli', 'mcp', 'clone'):
|
||||
raise ValueError('Invalid extension ownership record.')
|
||||
if not isinstance(resource.get('name'), str) or not resource['name']:
|
||||
raise ValueError('Invalid extension ownership name.')
|
||||
@@ -220,6 +220,13 @@ class Manager:
|
||||
if not relative.startswith(directory + '/') or not re.fullmatch(r'[a-f0-9]{64}', value):
|
||||
raise ValueError('Invalid owned skill file record.')
|
||||
safe_path(self.home, relative)
|
||||
for relative, value in resource.get('agents', {}).items():
|
||||
if resource['client'] != 'codex' or not re.fullmatch(r'\.codex/agents/[A-Za-z0-9_-]+\.toml', relative) or not re.fullmatch(r'[a-f0-9]{64}', value):
|
||||
raise ValueError('Invalid owned skill agent record.')
|
||||
elif resource['kind'] == 'clone':
|
||||
if resource['client'] != 'shared' or not re.fullmatch(r'\.my-ai-configuration/[A-Za-z0-9_-]+', resource.get('directory', '')):
|
||||
raise ValueError('Invalid owned clone record.')
|
||||
safe_path(self.home, resource['directory'])
|
||||
elif resource['kind'] == 'qmd' and (resource.get('package') != '@tobilu/qmd' or resource['client'] not in ('codex', 'shared')):
|
||||
raise ValueError('Invalid owned QMD record.')
|
||||
elif resource['kind'] == 'cli' and not re.fullmatch(r'[a-z0-9@/_.-]+', resource.get('package', '')):
|
||||
@@ -297,6 +304,14 @@ class Manager:
|
||||
self.command(arguments)
|
||||
self.cache[client].pop(selector, None)
|
||||
elif record['kind'] == 'skill':
|
||||
for relative, expected in list(record.get('agents', {}).items()):
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (not path.is_file() or digest(path) != expected):
|
||||
print(f'WARN Preserving modified agent file: {relative}')
|
||||
continue
|
||||
path.unlink(missing_ok=True)
|
||||
del record['agents'][relative]
|
||||
self.save()
|
||||
empty_candidates = set()
|
||||
for relative, expected in list(record['files'].items()):
|
||||
path = safe_path(self.home, relative)
|
||||
@@ -326,6 +341,22 @@ class Manager:
|
||||
pass
|
||||
if record['files']:
|
||||
return
|
||||
elif record['kind'] == 'clone':
|
||||
directory = safe_path(self.home, record['directory'])
|
||||
if directory.exists():
|
||||
# Saved sessions, .env files, and local edits live in the clone; never delete them.
|
||||
try:
|
||||
status = run_command(['git', '-C', str(directory), 'status', '--porcelain', '--ignored', '--untracked-files=all'], True, self.home)
|
||||
except ValueError as error:
|
||||
print(f'WARN Preserving {record["directory"]}: cannot read its Git status ({str(error).splitlines()[0]}).')
|
||||
return
|
||||
local = [line for line in status.splitlines() if not line[3:].startswith('node_modules/')]
|
||||
if local:
|
||||
print(f'WARN Preserving {record["directory"]}: it holds local files ({len(local)}); delete it yourself if they are not needed.')
|
||||
return
|
||||
# Git marks pack files read-only, which Windows refuses to delete.
|
||||
retry = lambda _, path, __: (os.chmod(path, stat.S_IWRITE), os.unlink(path))
|
||||
shutil.rmtree(directory, **({'onexc': retry} if sys.version_info >= (3, 12) else {'onerror': retry}))
|
||||
elif record['kind'] == 'mcp':
|
||||
self.command(['mcporter', '--config', str(self.home / '.mcporter/mcporter.json'), 'config', 'remove', record['server']])
|
||||
else:
|
||||
@@ -338,6 +369,9 @@ class Manager:
|
||||
if entry['codex_method'] == 'cli':
|
||||
self.ensure_cli(client, entry)
|
||||
return
|
||||
if entry['codex_method'] == 'clone':
|
||||
self.ensure_clone(client, entry)
|
||||
return
|
||||
# A Claude row without a plugin ('-') reuses the skill payload from codex_source.
|
||||
skill = entry['codex_method'] == 'skill' and (client == 'codex' or entry['claude_plugin'] == '-')
|
||||
kind = 'skill' if skill else 'plugin'
|
||||
@@ -429,6 +463,42 @@ class Manager:
|
||||
self.state['resources'].append(dict(client='shared', name=entry['name'], kind='cli', package=package, clients=[client]))
|
||||
self.save()
|
||||
|
||||
def ensure_clone(self, client, entry):
|
||||
"""Keep a project repository (skills, agents, app) cloned under ~/.my-ai-configuration, shared by both clients."""
|
||||
source, folder = entry['codex_source'], entry['codex_skill']
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', source) or not re.fullmatch(r'[A-Za-z0-9_-]+', folder):
|
||||
raise ValueError('Invalid clone source or folder.')
|
||||
directory = '.my-ai-configuration/' + folder
|
||||
target = safe_path(self.home, directory)
|
||||
record = next((r for r in self.state['resources'] if r['client'] == 'shared' and r['name'] == entry['name']), None)
|
||||
if record is None and target.exists():
|
||||
if not self.summary:
|
||||
print(f'PASS Preserving pre-existing folder: {directory}')
|
||||
return
|
||||
if self.dry_run:
|
||||
if not self.summary:
|
||||
print(f'DRYRUN ensure {client} clone: {entry["name"]}')
|
||||
return
|
||||
if record is not None and client not in record['clients']:
|
||||
record['clients'] = sorted(set(record['clients']) | {client})
|
||||
self.save()
|
||||
if not target.exists():
|
||||
self.command(['git', 'clone', '--depth', '1', f'https://github.com/{source}.git', str(target)])
|
||||
elif self.update and entry['name'] not in self.updated_packages:
|
||||
# Both clients share the folder; check and pull it once per run. A broken clone must not stop the other extensions.
|
||||
self.updated_packages.add(entry['name'])
|
||||
try:
|
||||
changed = run_command(['git', '-C', str(target), 'status', '--porcelain', '--untracked-files=no'], True, self.home)
|
||||
if changed.strip():
|
||||
print(f'WARN Not updating {directory}: tracked files were changed locally.')
|
||||
else:
|
||||
self.command(['git', '-C', str(target), 'pull', '--ff-only', '--quiet'])
|
||||
except ValueError as error:
|
||||
print(f'WARN Not updating {directory}: {str(error).splitlines()[0]}')
|
||||
if record is None:
|
||||
self.state['resources'].append(dict(client='shared', name=entry['name'], kind='clone', directory=directory, source=source, clients=[client]))
|
||||
self.save()
|
||||
|
||||
def ensure_ponytail_mode(self):
|
||||
# Same lookup as Ponytail's hooks/ponytail-config.js; PONYTAIL_DEFAULT_MODE still wins over this file.
|
||||
if os.environ.get('XDG_CONFIG_HOME'):
|
||||
@@ -552,9 +622,33 @@ class Manager:
|
||||
path.unlink(missing_ok=True)
|
||||
del record['files'][relative]
|
||||
self.save()
|
||||
if client == 'codex':
|
||||
self.sync_skill_agents(record, files)
|
||||
record['complete'] = True
|
||||
self.save()
|
||||
|
||||
def sync_skill_agents(self, record, files):
|
||||
"""Codex loads custom agents only from ~/.codex/agents, so register the skill's agents/*.toml there."""
|
||||
agents = {'.codex/agents/' + name.split('/', 1)[1]: content for name, (content, _) in files.items()
|
||||
if re.fullmatch(r'agents/[A-Za-z0-9_-]+\.toml', name)}
|
||||
owned = record.setdefault('agents', {})
|
||||
for relative, content in agents.items():
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (relative not in owned or not path.is_file() or digest(path) != owned[relative]):
|
||||
print(f'WARN Preserving modified or foreign agent file: {relative}')
|
||||
continue
|
||||
atomic_write(path, content)
|
||||
owned[relative] = hashlib.sha256(content).hexdigest()
|
||||
self.save()
|
||||
for relative in [name for name in owned if name not in agents]:
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (not path.is_file() or digest(path) != owned[relative]):
|
||||
print(f'WARN Preserving modified stale agent file: {relative}')
|
||||
continue
|
||||
path.unlink(missing_ok=True)
|
||||
del owned[relative]
|
||||
self.save()
|
||||
|
||||
def sync(self, entries, clients, selected, action='sync'):
|
||||
self.normalize_global_records()
|
||||
desired = {entry['name']: entry for entry in entries if entry['name'] in selected}
|
||||
@@ -590,6 +684,47 @@ class Manager:
|
||||
print('EXTENSIONS: reconciliation complete' + (' (dry run)' if self.dry_run else ''))
|
||||
|
||||
|
||||
def process_alive(pid):
|
||||
if os.name == 'nt':
|
||||
import ctypes
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
||||
if not handle:
|
||||
return False
|
||||
code = ctypes.c_ulong()
|
||||
try:
|
||||
return bool(kernel32.GetExitCodeProcess(handle, ctypes.byref(code))) and code.value == 259 # STILL_ACTIVE
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def acquire_lock(lock):
|
||||
"""Create the lock with this PID; replace a lock whose process is gone (closed terminal, kill)."""
|
||||
for _ in range(2):
|
||||
try:
|
||||
descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||
except FileExistsError:
|
||||
try:
|
||||
pid = int(lock.read_text(encoding='utf-8').strip() or 0)
|
||||
except (OSError, ValueError):
|
||||
pid = 0
|
||||
if pid and process_alive(pid):
|
||||
raise ValueError(f'Another install or update is running (PID {pid}). If it is not, delete {lock}.')
|
||||
lock.unlink(missing_ok=True)
|
||||
continue
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as stream:
|
||||
stream.write(str(os.getpid()))
|
||||
return
|
||||
raise ValueError(f'Cannot acquire {lock}.')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('sync', 'install', 'remove'))
|
||||
@@ -616,9 +751,8 @@ def main():
|
||||
return
|
||||
lock = safe_path(manager.home, '.my-ai-configuration/extensions.lock')
|
||||
lock.parent.mkdir(parents=True, exist_ok=True)
|
||||
descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||
acquire_lock(lock)
|
||||
try:
|
||||
os.close(descriptor)
|
||||
manager = Manager(args.home, args.dry_run, args.update, args.summary)
|
||||
manager.sync(entries, clients, selected, args.action)
|
||||
finally:
|
||||
|
||||
@@ -268,14 +268,23 @@ function Invoke-ManagedSync {
|
||||
if (-not (Test-Path -LiteralPath $target)) { continue }
|
||||
# A stale file changed locally is backed up but kept; only an unmodified one is removed.
|
||||
$action = if ((Get-Sha256Hash $target) -eq $oldManifest[$relative]) { 'REMOVE' } else { 'KEEP' }
|
||||
$null = $plan.Add([pscustomobject]@{ Relative = $relative; Target = $target; Action = $action; Bytes = $null; Hash = $null })
|
||||
$bytes = $null
|
||||
$hash = $null
|
||||
if ($action -eq 'KEEP' -and $relative -in @('settings.json', 'config.toml')) {
|
||||
# Client plugin commands edit these after install; drop only the entries this setup owns.
|
||||
$stripped = Invoke-InstallOptions -Arguments @('strip', '--current', $target) -ErrorMessage "Could not remove managed entries from $relative."
|
||||
$action = if ($stripped) { 'STRIP' } else { 'REMOVE' }
|
||||
$bytes = (New-Object System.Text.UTF8Encoding($false)).GetBytes($stripped)
|
||||
$hash = Get-Sha256HashOfBytes $bytes
|
||||
}
|
||||
$null = $plan.Add([pscustomobject]@{ Relative = $relative; Target = $target; Action = $action; Bytes = $bytes; Hash = $hash })
|
||||
}
|
||||
|
||||
if (-not $DryRun) {
|
||||
$journalEntries = @(foreach ($item in $plan) {
|
||||
switch ($item.Action) {
|
||||
'CREATE' { [ordered]@{ path = $item.Relative; action = 'create'; sha256 = $item.Hash } }
|
||||
'UPDATE' { [ordered]@{ path = $item.Relative; action = 'update'; backup = "$Stamp/$($item.Relative)"; sha256 = $item.Hash } }
|
||||
{ $_ -in @('UPDATE', 'STRIP') } { [ordered]@{ path = $item.Relative; action = 'update'; backup = "$Stamp/$($item.Relative)"; sha256 = $item.Hash } }
|
||||
'REMOVE' { [ordered]@{ path = $item.Relative; action = 'remove'; backup = "$Stamp/$($item.Relative)" } }
|
||||
}
|
||||
})
|
||||
|
||||
+34
-13
@@ -119,6 +119,16 @@ acquire_managed_lock() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# run_install_options <arguments...>: print install-options.py output byte-exact.
|
||||
# Python writes a file, because a captured stdout gets CRLF on Windows and differs from PowerShell's bytes.
|
||||
run_install_options() {
|
||||
local output status=0
|
||||
output=$(mktemp) || return 1
|
||||
{ run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" "$@" --output "$output" && cat -- "$output"; } || status=$?
|
||||
rm -f -- "$output"
|
||||
return "$status"
|
||||
}
|
||||
|
||||
# sync_managed_destination: same arguments as run_managed_sync; holds the destination lock unless dry-running.
|
||||
sync_managed_destination() {
|
||||
[ "$7" != true ] || { run_managed_sync "$@"; return; }
|
||||
@@ -214,12 +224,12 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
content=${content%$'\034'}
|
||||
needs_sub=false
|
||||
if { [ "$flashbang_enabled" = false ] || [ "$statusline_enabled" = false ] || [ "$semantic_retrieval_enabled" = false ]; } && [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
|
||||
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||
content=$(run_install_options filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
fi
|
||||
if [[ "$relative" = CLAUDE.md || "$relative" = AGENTS.md ]] || { [ "$semantic_retrieval_enabled" = false ] && [ "$relative" = rules/general.md ]; }; then
|
||||
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||
content=$(run_install_options filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
fi
|
||||
@@ -236,13 +246,14 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
else
|
||||
new_hash=$(sha256_of_file "$source_file")
|
||||
fi
|
||||
if [ "$relative" = config.toml ] && [ -f "$target" ]; then
|
||||
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-toml --current "$target" --statusline "$statusline_enabled") || return
|
||||
needs_sub=true
|
||||
new_hash=$(sha256_of_string "$content")
|
||||
fi
|
||||
if [ "$relative" = settings.json ] && [ -f "$target" ]; then
|
||||
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return
|
||||
if [[ "$relative" = config.toml || "$relative" = settings.json ]] && [ -f "$target" ]; then
|
||||
local managed_file merge_action=merge-json
|
||||
[ "$relative" = settings.json ] || merge_action=merge-toml
|
||||
managed_file=$(mktemp) || return 1
|
||||
printf '%s' "$content" > "$managed_file" || { rm -f -- "$managed_file"; return 1; }
|
||||
content=$(run_install_options "$merge_action" --current "$target" --managed "$managed_file" --statusline "$statusline_enabled" && printf '\034') || { rm -f -- "$managed_file"; return 1; }
|
||||
rm -f -- "$managed_file"
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
new_hash=$(sha256_of_string "$content")
|
||||
fi
|
||||
@@ -265,10 +276,20 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
target=$(managed_target "$destination" "$relative") || return 1
|
||||
[ -f "$target" ] || continue
|
||||
# A stale file changed locally is backed up but kept; only an unmodified one is removed.
|
||||
local stripped='' stripped_hash=''
|
||||
action=KEEP
|
||||
[ "$(sha256_of_file "$target")" != "${old_manifest[$relative]}" ] || action=REMOVE
|
||||
plan_relative+=("$relative"); plan_target+=("$target"); plan_action+=("$action"); plan_hash+=('')
|
||||
plan_source+=(''); plan_sub+=(false); plan_content+=('')
|
||||
if [ "$(sha256_of_file "$target")" = "${old_manifest[$relative]}" ]; then
|
||||
action=REMOVE
|
||||
elif [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
|
||||
# Client plugin commands edit these after install; drop only the entries this setup owns.
|
||||
stripped=$(run_install_options strip --current "$target" && printf '\034') || return 1
|
||||
stripped=${stripped%$'\034'}
|
||||
action=STRIP
|
||||
[ -n "$stripped" ] || action=REMOVE
|
||||
stripped_hash=$(sha256_of_string "$stripped")
|
||||
fi
|
||||
plan_relative+=("$relative"); plan_target+=("$target"); plan_action+=("$action"); plan_hash+=("$stripped_hash")
|
||||
plan_source+=(''); plan_sub+=(true); plan_content+=("$stripped")
|
||||
done
|
||||
|
||||
local index entry journal_content first_entry=true
|
||||
@@ -279,7 +300,7 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
for index in "${!plan_action[@]}"; do
|
||||
case "${plan_action[$index]}" in
|
||||
CREATE) entry=$(printf '{"path": %s, "action": "create", "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
UPDATE) entry=$(printf '{"path": %s, "action": "update", "backup": %s, "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
UPDATE|STRIP) entry=$(printf '{"path": %s, "action": "update", "backup": %s, "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
REMOVE) entry=$(printf '{"path": %s, "action": "remove", "backup": %s}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")") ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
|
||||
@@ -134,6 +134,7 @@ function Select-ConfiguredPlugins {
|
||||
$checked = @($toggleable | ForEach-Object {
|
||||
if ($Mode -eq 'Install') { $true; return }
|
||||
if ($_.codex_method -eq 'cli') { return Test-CliCommand -Name $_.codex_source }
|
||||
if ($_.codex_method -eq 'clone') { return Test-Path -LiteralPath (Join-Path $HomePath ('.my-ai-configuration/' + $_.codex_skill)) }
|
||||
$entry = $_
|
||||
$found = if ($entry.mcporter_name -and $entry.mcporter_url) {
|
||||
Test-InstalledMCPServer -HomePath $HomePath -Name $entry.mcporter_name -Url $entry.mcporter_url
|
||||
|
||||
@@ -171,6 +171,10 @@ select_configured_plugins() {
|
||||
if cli_installed "$(plugin_field "$root" "$name" codex_source)"; then checked+=(true); else checked+=(false); fi
|
||||
continue
|
||||
fi
|
||||
if [ "$(plugin_field "$root" "$name" codex_method)" = clone ]; then
|
||||
if [ -d "${home_path:-$HOME}/.my-ai-configuration/$(plugin_field "$root" "$name" codex_skill)" ]; then checked+=(true); else checked+=(false); fi
|
||||
continue
|
||||
fi
|
||||
found=false
|
||||
local mcporter_name mcporter_url status
|
||||
mcporter_name=$(plugin_field "$root" "$name" mcporter_name)
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet('Codex', 'Claude')][string]$Client,
|
||||
[string]$Key,
|
||||
[Parameter(Position = 2)][string]$FilePath,
|
||||
[Parameter(Position = 3, ValueFromRemainingArguments = $true)][string[]]$ArgumentList
|
||||
)
|
||||
# Usage: with-credential.ps1 -Client <Codex|Claude> -Key <NAME> -FilePath <command> [child arguments...]
|
||||
# No param() block: PowerShell would bind abbreviated child flags such as -k or -d to -Key or -Debug.
|
||||
# Only the exact names below are read; everything after the command goes to the child unchanged.
|
||||
# Own variable names: scripts that dot-source this file keep their own $Client and $Key.
|
||||
$credentialClient = $null
|
||||
$credentialKey = $null
|
||||
$childPath = $null
|
||||
$childArguments = @()
|
||||
for ($index = 0; $index -lt $args.Count; $index++) {
|
||||
$token = [string]$args[$index]
|
||||
if ($null -ne $childPath) { $childArguments = @($args[$index..($args.Count - 1)] | ForEach-Object { [string]$_ }); break }
|
||||
if ($token -eq '-Client' -and $index + 1 -lt $args.Count) { $credentialClient = [string]$args[++$index] }
|
||||
elseif ($token -eq '-Key' -and $index + 1 -lt $args.Count) { $credentialKey = [string]$args[++$index] }
|
||||
elseif ($token -eq '-FilePath' -and $index + 1 -lt $args.Count) { $childPath = [string]$args[++$index] }
|
||||
else { $childPath = $token }
|
||||
}
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
@@ -106,7 +115,10 @@ function Remove-ManagedCredential {
|
||||
function Invoke-WithManagedCredential {
|
||||
param([ValidateSet('Codex', 'Claude')][string]$Client, [string]$Key, [string]$FilePath, [string[]]$ArgumentList)
|
||||
Assert-CredentialKey $Key
|
||||
if (-not (Test-Path -LiteralPath $FilePath -PathType Leaf)) { throw 'Child command was not found.' }
|
||||
# Accept a full path or a command name on PATH (gh, curl.exe).
|
||||
$command = Get-Command -Name $FilePath -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if (-not $command) { throw 'Child command was not found.' }
|
||||
$FilePath = $command.Source
|
||||
$prior = [Environment]::GetEnvironmentVariable($Key, 'Process')
|
||||
$value = Get-ManagedCredential $Client $Key
|
||||
try {
|
||||
@@ -119,8 +131,8 @@ function Invoke-WithManagedCredential {
|
||||
}
|
||||
}
|
||||
|
||||
if ($FilePath) {
|
||||
if (-not $Client -or -not $Key) { throw 'Client and key are required.' }
|
||||
Invoke-WithManagedCredential $Client $Key $FilePath $ArgumentList
|
||||
if ($childPath) {
|
||||
if (-not $credentialClient -or -not $credentialKey) { throw 'Client and key are required.' }
|
||||
Invoke-WithManagedCredential $credentialClient $credentialKey $childPath $childArguments
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
Reference in new issue
Block a user