toolbase 0.7.0__tar.gz → 0.8.1__tar.gz

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.
Files changed (67) hide show
  1. {toolbase-0.7.0 → toolbase-0.8.1}/CHANGELOG.md +16 -0
  2. {toolbase-0.7.0 → toolbase-0.8.1}/PKG-INFO +12 -8
  3. {toolbase-0.7.0 → toolbase-0.8.1}/README.md +11 -7
  4. {toolbase-0.7.0 → toolbase-0.8.1}/pyproject.toml +1 -1
  5. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/cli.py +68 -16
  6. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/connect/__init__.py +3 -0
  7. toolbase-0.8.1/toolbase/connect/opencode.py +243 -0
  8. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/skills.py +45 -11
  9. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase.egg-info/SOURCES.txt +1 -0
  10. {toolbase-0.7.0 → toolbase-0.8.1}/LICENSE +0 -0
  11. {toolbase-0.7.0 → toolbase-0.8.1}/MANIFEST.in +0 -0
  12. {toolbase-0.7.0 → toolbase-0.8.1}/setup.cfg +0 -0
  13. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/__init__.py +0 -0
  14. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/_setup_host.py +0 -0
  15. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/_toolkit_host.py +0 -0
  16. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/astro.py +0 -0
  17. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/auth.py +0 -0
  18. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/config.py +0 -0
  19. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/connect/base.py +0 -0
  20. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/connect/claude_code.py +0 -0
  21. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/connect/codex.py +0 -0
  22. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/connect/orchestral.py +0 -0
  23. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/__init__.py +0 -0
  24. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/bundle_deps.py +0 -0
  25. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/cache.py +0 -0
  26. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/config.py +0 -0
  27. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/discovery.py +0 -0
  28. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/manifest.py +0 -0
  29. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/paths.py +0 -0
  30. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/envs/schema.py +0 -0
  31. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/hep.py +0 -0
  32. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/ingest.py +0 -0
  33. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/logging/__init__.py +0 -0
  34. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/logging/logger.py +0 -0
  35. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/naming.py +0 -0
  36. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/neutrino.py +0 -0
  37. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/quantum.py +0 -0
  38. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/serve/__init__.py +0 -0
  39. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/serve/bundles.py +0 -0
  40. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/serve/config.py +0 -0
  41. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/serve/orchestrator.py +0 -0
  42. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/serve/profile_scaffold.py +0 -0
  43. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/serve/profiles.py +0 -0
  44. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/serve/proxy_tool.py +0 -0
  45. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/__init__.py +0 -0
  46. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/_rpc.py +0 -0
  47. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/context.py +0 -0
  48. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/declarative.py +0 -0
  49. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/downloads.py +0 -0
  50. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/prompts.py +0 -0
  51. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/runner.py +0 -0
  52. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/schema.py +0 -0
  53. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/storage.py +0 -0
  54. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/setup/validate_cache.py +0 -0
  55. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/Dockerfile.template +0 -0
  56. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/README.md.template +0 -0
  57. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/__init__.py.template +0 -0
  58. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/mcp/__init__.py.template +0 -0
  59. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/mcp/server_stdio.py.template +0 -0
  60. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/requirements.txt.template +0 -0
  61. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/setup.py.template +0 -0
  62. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/skills/example_skill.md +0 -0
  63. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/tool_example.py +0 -0
  64. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/templates/toolkit.yaml.template +0 -0
  65. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/toolkit.py +0 -0
  66. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/validation.py +0 -0
  67. {toolbase-0.7.0 → toolbase-0.8.1}/toolbase/versioning.py +0 -0
@@ -8,6 +8,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.8.1] — 2026-07-27
12
+
13
+ ### Fixed
14
+
15
+ - **`tb connect --abspath` no longer silently falls back to a bare command.** It resolved the binary with `shutil.which("toolbase")`, which returns `None` exactly when toolbase isn't on PATH at connect time (a venv/conda install, or toolbase invoked by absolute path) — the very case `--abspath` exists for — so it quietly wrote a bare `toolbase` that the harness then couldn't launch. It now resolves the toolbase beside the running interpreter first (`sys.executable`'s dir), falling back to `which` then bare.
16
+
17
+ ### Changed
18
+
19
+ - **`tb connect` command default is now scope-aware.** User-scope connects (`-g`, a machine-local config that is never committed) default to the **absolute** toolbase path so the harness always finds it — important because a harness process (e.g. a GUI app, or a shell without your env activated) often doesn't have a venv/conda `bin` on PATH. Project-scope connects (git-committed, shared) stay **bare** `toolbase` for portability, and now print a note when toolbase is env-installed that a bare command may not resolve for the harness (suggesting `--abspath`, `-g`, or a login-PATH install). New `--portable` flag forces the bare command in any scope; `--abspath` still forces the absolute path.
20
+
21
+ ## [0.8.0] — 2026-07-27
22
+
23
+ ### Added
24
+
25
+ - **`tb connect opencode` — OpenCode is now a supported harness.** A new `OpenCodeAdapter` wires toolbase into OpenCode's `mcp` block (`opencode.json` / `opencode.jsonc`, user `~/.config/opencode/` honoring `$XDG_CONFIG_HOME`, or project root), writing a local stdio server in OpenCode's single-`command`-array form (`{"type":"local","command":["toolbase","serve"],"enabled":true}`) with a non-destructive, atomic merge that preserves `$schema` and other servers. An existing comment-free `.jsonc` is edited in place; a `.jsonc` that actually carries comments is refused with guidance rather than clobbered. Registering the adapter also lights up `tb disconnect opencode`, `--harnesses`, and `--list`. OpenCode skills surface as `~/.config/opencode/command/<toolkit>__<skill>.md` slash-command prompts (via the existing `SkillTarget` flat layout), keeping only the `description` frontmatter OpenCode shows in its TUI — enabled by a new `SkillTarget.frontmatter_keys` that narrows the emitted block to named keys.
26
+
11
27
  ## [0.7.0] — 2026-07-26
12
28
 
13
29
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: toolbase
3
- Version: 0.7.0
3
+ Version: 0.8.1
4
4
  Summary: The community registry and CLI for AI agent toolkits - discover, share, and serve tools to AI agents over MCP
5
5
  Author-email: Alex Roman <toolbase.dev@gmail.com>
6
6
  License: MIT
@@ -86,12 +86,13 @@ the activation is scoped: `tb activate` writes to the current
86
86
  directory's `.toolbase/` by default, `-g` writes to the user-wide
87
87
  profile instead.
88
88
 
89
- **`tb connect` writes the MCP config for you.** Claude Code, Codex, and
90
- Orchestral are all supported (`tb connect --harnesses` lists them);
91
- Claude Code and Codex are MCP clients (`tb connect` edits their config
92
- file), while Orchestral gets a runnable agent script you launch
93
- yourself. It also surfaces the activated toolkits' **skills** into the
94
- harness — see [Skills](#skills-guides-that-travel-with-the-toolkit).
89
+ **`tb connect` writes the MCP config for you.** Claude Code, Codex,
90
+ OpenCode, and Orchestral are all supported (`tb connect --harnesses`
91
+ lists them); Claude Code, Codex, and OpenCode are MCP clients (`tb
92
+ connect` edits their config file), while Orchestral gets a runnable agent
93
+ script you launch yourself. It also surfaces the activated toolkits'
94
+ **skills** into the harness — see
95
+ [Skills](#skills-guides-that-travel-with-the-toolkit).
95
96
 
96
97
  ## Inspect
97
98
 
@@ -140,6 +141,9 @@ format:
140
141
  to the model *and* available as a `/<toolkit>__<skill>` slash command.
141
142
  - **Codex** → `~/.codex/prompts/<toolkit>__<skill>.md` — a
142
143
  `/<toolkit>__<skill>` slash-command prompt.
144
+ - **OpenCode** → `~/.config/opencode/command/<toolkit>__<skill>.md` — a
145
+ `/<toolkit>__<skill>` slash-command prompt (its `description` shows in
146
+ the TUI).
143
147
 
144
148
  Skills follow the same curation as tools: a guide is surfaced only when
145
149
  its toolkit is active, and you toggle a single one with the activation
@@ -224,7 +228,7 @@ Full reference with all flags: <https://toolbase-ai.com/docs/reference/commands>
224
228
  | `tb list` | Installed toolkits (`-v` for a per-tool view) |
225
229
  | `tb activate ITEM` | Expose a toolkit / `toolkit/bundle` / `toolkit__tool` / `toolkit__skill` (project-local; `-g` for user-wide) |
226
230
  | `tb deactivate ITEM` | Hide a toolkit / bundle / tool / skill |
227
- | `tb connect HARNESS` | Wire toolbase into Claude Code, Codex, or scaffold an Orchestral agent script (also surfaces skills; `--no-skills` to skip) |
231
+ | `tb connect HARNESS` | Wire toolbase into Claude Code, Codex, OpenCode, or scaffold an Orchestral agent script (also surfaces skills; `--no-skills` to skip) |
228
232
  | `tb disconnect HARNESS` | Remove toolbase from a harness (and its surfaced skills) |
229
233
  | `tb logs` | Tail the serve log, live |
230
234
  | `tb profile …` | Manage named profiles: `list \| show \| create \| edit \| delete \| set-default \| path \| tools` |
@@ -45,12 +45,13 @@ the activation is scoped: `tb activate` writes to the current
45
45
  directory's `.toolbase/` by default, `-g` writes to the user-wide
46
46
  profile instead.
47
47
 
48
- **`tb connect` writes the MCP config for you.** Claude Code, Codex, and
49
- Orchestral are all supported (`tb connect --harnesses` lists them);
50
- Claude Code and Codex are MCP clients (`tb connect` edits their config
51
- file), while Orchestral gets a runnable agent script you launch
52
- yourself. It also surfaces the activated toolkits' **skills** into the
53
- harness — see [Skills](#skills-guides-that-travel-with-the-toolkit).
48
+ **`tb connect` writes the MCP config for you.** Claude Code, Codex,
49
+ OpenCode, and Orchestral are all supported (`tb connect --harnesses`
50
+ lists them); Claude Code, Codex, and OpenCode are MCP clients (`tb
51
+ connect` edits their config file), while Orchestral gets a runnable agent
52
+ script you launch yourself. It also surfaces the activated toolkits'
53
+ **skills** into the harness — see
54
+ [Skills](#skills-guides-that-travel-with-the-toolkit).
54
55
 
55
56
  ## Inspect
56
57
 
@@ -99,6 +100,9 @@ format:
99
100
  to the model *and* available as a `/<toolkit>__<skill>` slash command.
100
101
  - **Codex** → `~/.codex/prompts/<toolkit>__<skill>.md` — a
101
102
  `/<toolkit>__<skill>` slash-command prompt.
103
+ - **OpenCode** → `~/.config/opencode/command/<toolkit>__<skill>.md` — a
104
+ `/<toolkit>__<skill>` slash-command prompt (its `description` shows in
105
+ the TUI).
102
106
 
103
107
  Skills follow the same curation as tools: a guide is surfaced only when
104
108
  its toolkit is active, and you toggle a single one with the activation
@@ -183,7 +187,7 @@ Full reference with all flags: <https://toolbase-ai.com/docs/reference/commands>
183
187
  | `tb list` | Installed toolkits (`-v` for a per-tool view) |
184
188
  | `tb activate ITEM` | Expose a toolkit / `toolkit/bundle` / `toolkit__tool` / `toolkit__skill` (project-local; `-g` for user-wide) |
185
189
  | `tb deactivate ITEM` | Hide a toolkit / bundle / tool / skill |
186
- | `tb connect HARNESS` | Wire toolbase into Claude Code, Codex, or scaffold an Orchestral agent script (also surfaces skills; `--no-skills` to skip) |
190
+ | `tb connect HARNESS` | Wire toolbase into Claude Code, Codex, OpenCode, or scaffold an Orchestral agent script (also surfaces skills; `--no-skills` to skip) |
187
191
  | `tb disconnect HARNESS` | Remove toolbase from a harness (and its surfaced skills) |
188
192
  | `tb logs` | Tail the serve log, live |
189
193
  | `tb profile …` | Manage named profiles: `list \| show \| create \| edit \| delete \| set-default \| path \| tools` |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "toolbase"
7
- version = "0.7.0"
7
+ version = "0.8.1"
8
8
  description = "The community registry and CLI for AI agent toolkits - discover, share, and serve tools to AI agents over MCP"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -4123,7 +4123,7 @@ def _note_skills_available(name: str, slot: Path, no_skills: bool = False) -> No
4123
4123
  if not no_skills:
4124
4124
  console.print(
4125
4125
  "[dim]Surface them with [/dim][cyan]tb connect <harness>[/cyan]"
4126
- "[dim] (claude-code, codex); toggle one with [/dim]"
4126
+ "[dim] (claude-code, codex, opencode); toggle one with [/dim]"
4127
4127
  "[cyan]tb deactivate <toolkit>__<skill>[/cyan][dim].[/dim]"
4128
4128
  )
4129
4129
 
@@ -6830,18 +6830,66 @@ def _resolve_connect_scope(global_scope: bool, local_scope: bool):
6830
6830
  return "project", root
6831
6831
 
6832
6832
 
6833
- def _toolbase_command(abspath: bool) -> str:
6834
- """The command string to write into the harness's config.
6833
+ def _toolbase_abspath() -> str:
6834
+ """Absolute path of the *running* toolbase binary.
6835
6835
 
6836
- Default is the bare ``toolbase`` (PATH-resolved, portable across
6837
- machines — important for team-shared project configs). ``--abspath``
6838
- writes the resolved absolute path of the current binary.
6836
+ A harness launches the MCP server by exec'ing this command against its
6837
+ own process PATH — which for a venv/conda install often does not include
6838
+ the env's ``bin``, so a bare ``toolbase`` fails to launch. The absolute
6839
+ path is PATH-independent.
6840
+
6841
+ Resolution prefers the ``toolbase`` beside the running interpreter
6842
+ (``sys.executable``'s ``bin/`` — where a console-script entry point
6843
+ lives, i.e. *this* toolbase), because ``shutil.which`` returns ``None``
6844
+ when toolbase isn't on the PATH at connect time (exactly the case that
6845
+ needs an absolute path). Falls back to ``which`` then bare.
6839
6846
  """
6840
- if not abspath:
6841
- return "toolbase"
6842
6847
  import shutil
6843
- resolved = shutil.which("toolbase")
6844
- return resolved or "toolbase"
6848
+ bindir = Path(sys.executable).parent
6849
+ for cand in (bindir / "toolbase", bindir / "toolbase.exe"):
6850
+ if cand.exists():
6851
+ return str(cand)
6852
+ return shutil.which("toolbase") or "toolbase"
6853
+
6854
+
6855
+ def _toolbase_is_env_installed() -> bool:
6856
+ """True when toolbase runs from an isolated env whose ``bin`` a harness
6857
+ process likely won't have on PATH — a venv/virtualenv, or a *named*
6858
+ (non-base) conda env. Used to warn before writing a bare command that
6859
+ may not resolve for the harness."""
6860
+ if sys.prefix != getattr(sys, "base_prefix", sys.prefix):
6861
+ return True # venv / virtualenv
6862
+ conda_env = os.environ.get("CONDA_DEFAULT_ENV")
6863
+ return bool(conda_env) and conda_env != "base" # named conda env
6864
+
6865
+
6866
+ def _resolve_connect_command(*, abspath: bool, portable: bool, scope: str) -> str:
6867
+ """The command string to write into the harness's config, scope-aware.
6868
+
6869
+ Default optimizes for the config's shareability: ``user`` scope (``-g``,
6870
+ a machine-local config that is never committed) writes the absolute path
6871
+ so the harness always finds it; ``project`` scope (git-committed, shared)
6872
+ stays bare ``toolbase`` for portability across machines. ``--abspath``
6873
+ forces the absolute path in any scope; ``--portable`` forces bare. On a
6874
+ project-scope bare write from an isolated env, warn that the harness may
6875
+ not resolve a bare command."""
6876
+ if abspath and portable:
6877
+ raise click.UsageError("--abspath and --portable are mutually exclusive.")
6878
+ use_abspath = abspath or (not portable and scope == "user")
6879
+ if use_abspath:
6880
+ return _toolbase_abspath()
6881
+ if scope != "user" and _toolbase_is_env_installed():
6882
+ console.print(
6883
+ "[yellow]Note:[/yellow] wrote a bare [cyan]toolbase[/cyan] (portable). "
6884
+ "The harness resolves it against its own PATH, and toolbase lives in "
6885
+ "an isolated env — so a harness launched outside that env (a desktop "
6886
+ "app, or a terminal without the env active) won't find it and the MCP "
6887
+ "server will show as failed. Fixes: reconnect with [cyan]--abspath[/cyan] "
6888
+ "(machine-specific path), use [cyan]-g[/cyan] (user scope uses the "
6889
+ "absolute path by default), or put toolbase on your login PATH "
6890
+ "(e.g. [cyan]pipx install toolbase[/cyan]) to keep it bare and portable."
6891
+ )
6892
+ return "toolbase"
6845
6893
 
6846
6894
 
6847
6895
  def _activated_toolkit_dirs() -> "dict[str, Path]":
@@ -6956,7 +7004,11 @@ def _unsurface_skills_for_connect(adapter) -> None:
6956
7004
  @click.option('--dry-run', 'dry_run', is_flag=True, default=False,
6957
7005
  help='Print the intended write without changing anything.')
6958
7006
  @click.option('--abspath', 'abspath', is_flag=True, default=False,
6959
- help='Write the absolute toolbase binary path instead of relying on PATH.')
7007
+ help='Force the absolute toolbase binary path (PATH-independent). '
7008
+ 'Default for user scope (-g); project scope stays bare.')
7009
+ @click.option('--portable', 'portable', is_flag=True, default=False,
7010
+ help='Force the bare `toolbase` command (portable across machines) '
7011
+ 'even for user scope.')
6960
7012
  @click.option('--list', 'do_list', is_flag=True, default=False,
6961
7013
  help='Show where toolbase is wired across harnesses, then exit.')
6962
7014
  @click.option('--harnesses', 'do_harnesses', is_flag=True, default=False,
@@ -6970,13 +7022,13 @@ def _unsurface_skills_for_connect(adapter) -> None:
6970
7022
  help="Don't surface the activated toolkits' skills into the "
6971
7023
  "harness (wire the MCP server only).")
6972
7024
  def connect(harness, global_scope, local_scope, profile_name, remove, dry_run,
6973
- abspath, do_list, do_harnesses, out_path, force, no_skills):
7025
+ abspath, portable, do_list, do_harnesses, out_path, force, no_skills):
6974
7026
  """Wire toolbase into an agent harness.
6975
7027
 
6976
7028
  \b
6977
- Claude Code and Codex are MCP clients: this writes a server entry into the
6978
- harness's config. Orchestral is a Python library, not a config-file harness,
6979
- so it writes a runnable agent script you launch yourself.
7029
+ Claude Code, Codex, and OpenCode are MCP clients: this writes a server entry
7030
+ into the harness's config. Orchestral is a Python library, not a config-file
7031
+ harness, so it writes a runnable agent script you launch yourself.
6980
7032
 
6981
7033
  \b
6982
7034
  Examples:
@@ -7063,7 +7115,7 @@ def connect(harness, global_scope, local_scope, profile_name, remove, dry_run,
7063
7115
  _unsurface_skills_for_connect(adapter)
7064
7116
  return
7065
7117
 
7066
- command = _toolbase_command(abspath)
7118
+ command = _resolve_connect_command(abspath=abspath, portable=portable, scope=scope)
7067
7119
  try:
7068
7120
  path = adapter.install(
7069
7121
  scope=scope, project_root=project_root, server_name="toolbase",
@@ -20,6 +20,7 @@ from typing import Dict, List
20
20
  from .base import HarnessAdapter, RegistrationEntry, AvailabilityStatus
21
21
  from .claude_code import ClaudeCodeAdapter
22
22
  from .codex import CodexAdapter
23
+ from .opencode import OpenCodeAdapter
23
24
 
24
25
 
25
26
  # Registry of config-file harness adapters, keyed by the name the user types
@@ -27,6 +28,7 @@ from .codex import CodexAdapter
27
28
  _ADAPTERS: Dict[str, HarnessAdapter] = {
28
29
  "claude-code": ClaudeCodeAdapter(),
29
30
  "codex": CodexAdapter(),
31
+ "opencode": OpenCodeAdapter(),
30
32
  }
31
33
 
32
34
 
@@ -49,6 +51,7 @@ __all__ = [
49
51
  "AvailabilityStatus",
50
52
  "ClaudeCodeAdapter",
51
53
  "CodexAdapter",
54
+ "OpenCodeAdapter",
52
55
  "get_adapter",
53
56
  "available_adapter_names",
54
57
  "all_adapters",
@@ -0,0 +1,243 @@
1
+ """OpenCode adapter for ``tb connect``.
2
+
3
+ Scopes (toolbase -> OpenCode):
4
+ - ``user`` -> ``~/.config/opencode/opencode.json`` (honors ``$XDG_CONFIG_HOME``)
5
+ - ``project`` -> ``<root>/opencode.json``
6
+
7
+ OpenCode merges the project config over the global one key-by-key, so both
8
+ scopes are real. The MCP entry lives under the top-level ``mcp`` key as a
9
+ *local* (stdio) server, and — unlike Claude Code / Codex — the command and its
10
+ arguments are a single ``command`` array::
11
+
12
+ {
13
+ "$schema": "https://opencode.ai/config.json",
14
+ "mcp": {
15
+ "toolbase": {
16
+ "type": "local",
17
+ "command": ["toolbase", "serve"],
18
+ "enabled": true
19
+ }
20
+ }
21
+ }
22
+
23
+ Config files may be ``.json`` or ``.jsonc``. We edit an existing ``.jsonc`` in
24
+ place when that is what the user has (so we don't create a competing
25
+ ``.json``), and refuse to overwrite a ``.jsonc`` that actually carries comments
26
+ rather than silently dropping them — the same "refuse rather than clobber"
27
+ discipline the Claude Code adapter applies to malformed JSON.
28
+
29
+ Writes are a non-destructive merge (only the toolbase entry under ``mcp`` is
30
+ touched; every other server, top-level key, and ``$schema`` is preserved) and
31
+ atomic (tmp file + rename).
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import os
38
+ from pathlib import Path
39
+ from typing import Dict, List, Optional
40
+
41
+ from .base import (
42
+ AvailabilityStatus, HarnessAdapter, HarnessConfigError, RegistrationEntry,
43
+ )
44
+
45
+ _SCHEMA_URL = "https://opencode.ai/config.json"
46
+
47
+
48
+ class OpenCodeConfigError(HarnessConfigError):
49
+ """Existing OpenCode config is unreadable / malformed."""
50
+
51
+
52
+ def _config_home() -> Path:
53
+ """``$XDG_CONFIG_HOME`` (when set and non-empty) or ``~/.config``."""
54
+ xdg = os.environ.get("XDG_CONFIG_HOME")
55
+ return Path(xdg) if xdg else Path.home() / ".config"
56
+
57
+
58
+ class OpenCodeAdapter(HarnessAdapter):
59
+ name = "opencode"
60
+
61
+ def project_scope_note(self) -> str:
62
+ return (
63
+ "OpenCode merges a project's opencode.json over your global config "
64
+ "automatically — no extra trust step is required."
65
+ )
66
+
67
+ # ── detection ────────────────────────────────────────────────────
68
+
69
+ def is_available(self) -> AvailabilityStatus:
70
+ import shutil
71
+ if shutil.which("opencode"):
72
+ return AvailabilityStatus(True, "opencode CLI found on PATH")
73
+ if (_config_home() / "opencode").exists():
74
+ return AvailabilityStatus(True, "found ~/.config/opencode")
75
+ return AvailabilityStatus(
76
+ False, "no `opencode` CLI on PATH and no ~/.config/opencode"
77
+ )
78
+
79
+ def supported_scopes(self) -> Dict[str, str]:
80
+ return {"user": "global", "project": "project"}
81
+
82
+ def skill_target(self):
83
+ # ~/.config/opencode/command/<toolkit>__<skill>.md — one flat file per
84
+ # skill, each a `/<toolkit>__<skill>` slash-command prompt. OpenCode
85
+ # honors a `description` frontmatter field (shown in its TUI), so we
86
+ # keep just that key and drop toolbase's `name`/`bundle`.
87
+ from ..skills import SkillTarget
88
+ return SkillTarget(
89
+ harness=self.name, root=_config_home() / "opencode" / "command",
90
+ layout="flat", keep_frontmatter=False, frontmatter_keys=["description"],
91
+ )
92
+
93
+ # ── paths ────────────────────────────────────────────────────────
94
+
95
+ def config_path(self, scope: str, project_root: Optional[Path]) -> Path:
96
+ if scope == "user":
97
+ return self._resolve_variant(_config_home() / "opencode" / "opencode.json")
98
+ if scope == "project":
99
+ if project_root is None:
100
+ raise ValueError("project scope requires a project_root")
101
+ return self._resolve_variant(project_root / "opencode.json")
102
+ raise ValueError(f"unknown scope {scope!r}")
103
+
104
+ @staticmethod
105
+ def _resolve_variant(json_path: Path) -> Path:
106
+ """Prefer an existing config file. OpenCode reads either ``.json`` or
107
+ ``.jsonc``; if the user already has a ``.jsonc`` we edit that rather
108
+ than create a second file OpenCode may ignore. Absent both, default to
109
+ ``.json``."""
110
+ if json_path.exists():
111
+ return json_path
112
+ jsonc = json_path.with_suffix(".jsonc")
113
+ if jsonc.exists():
114
+ return jsonc
115
+ return json_path
116
+
117
+ # ── read / write ─────────────────────────────────────────────────
118
+
119
+ @staticmethod
120
+ def _read(path: Path) -> dict:
121
+ if not path.exists():
122
+ return {}
123
+ text = path.read_text(encoding="utf-8")
124
+ try:
125
+ data = json.loads(text)
126
+ except json.JSONDecodeError as e:
127
+ hint = ""
128
+ if "//" in text or "/*" in text:
129
+ hint = (
130
+ " It looks like JSONC with comments, which toolbase can't "
131
+ "safely rewrite — add the toolbase MCP server under `mcp` "
132
+ "by hand, or remove the comments and re-run."
133
+ )
134
+ raise OpenCodeConfigError(
135
+ f"{path} is not valid JSON ({e}); refusing to overwrite.{hint}"
136
+ ) from e
137
+ if not isinstance(data, dict):
138
+ raise OpenCodeConfigError(
139
+ f"{path} must be a JSON object at the top level."
140
+ )
141
+ return data
142
+
143
+ @staticmethod
144
+ def _write_atomic(path: Path, data: dict) -> None:
145
+ path.parent.mkdir(parents=True, exist_ok=True)
146
+ tmp = path.with_suffix(path.suffix + ".tmp")
147
+ with open(tmp, "w", encoding="utf-8") as f:
148
+ json.dump(data, f, indent=2, sort_keys=False)
149
+ f.write("\n")
150
+ f.flush()
151
+ os.fsync(f.fileno())
152
+ os.replace(tmp, path)
153
+
154
+ @staticmethod
155
+ def _entry(command: str, args: List[str], env: Optional[Dict[str, str]]) -> dict:
156
+ # OpenCode wants command + args as one array; env is `environment`.
157
+ entry: dict = {
158
+ "type": "local",
159
+ "command": [command, *args],
160
+ "enabled": True,
161
+ }
162
+ if env:
163
+ entry["environment"] = dict(env)
164
+ return entry
165
+
166
+ # ── install / uninstall ──────────────────────────────────────────
167
+
168
+ def install(
169
+ self,
170
+ *,
171
+ scope: str,
172
+ project_root: Optional[Path],
173
+ server_name: str,
174
+ command: str,
175
+ args: List[str],
176
+ env: Optional[Dict[str, str]] = None,
177
+ dry_run: bool = False,
178
+ ) -> Path:
179
+ path = self.config_path(scope, project_root)
180
+ data = self._read(path)
181
+ data.setdefault("$schema", _SCHEMA_URL)
182
+ servers = data.get("mcp")
183
+ if servers is None:
184
+ servers = {}
185
+ elif not isinstance(servers, dict):
186
+ raise OpenCodeConfigError(f"{path}: 'mcp' must be a JSON object.")
187
+ servers[server_name] = self._entry(command, args, env)
188
+ data["mcp"] = servers
189
+ if not dry_run:
190
+ self._write_atomic(path, data)
191
+ return path
192
+
193
+ def uninstall(
194
+ self,
195
+ *,
196
+ scope: str,
197
+ project_root: Optional[Path],
198
+ server_name: str,
199
+ ) -> bool:
200
+ path = self.config_path(scope, project_root)
201
+ if not path.exists():
202
+ return False
203
+ data = self._read(path)
204
+ servers = data.get("mcp")
205
+ if not isinstance(servers, dict) or server_name not in servers:
206
+ return False
207
+ del servers[server_name]
208
+ # Leave an empty mcp object rather than reshaping the file.
209
+ data["mcp"] = servers
210
+ self._write_atomic(path, data)
211
+ return True
212
+
213
+ # ── status ───────────────────────────────────────────────────────
214
+
215
+ def status(self, project_root: Optional[Path]) -> List[RegistrationEntry]:
216
+ out: List[RegistrationEntry] = []
217
+ scopes = [("user", None)]
218
+ if project_root is not None:
219
+ scopes.append(("project", project_root))
220
+ for scope, root in scopes:
221
+ path = self.config_path(scope, root)
222
+ present = False
223
+ command = ""
224
+ args: Optional[List[str]] = None
225
+ if path.exists():
226
+ try:
227
+ data = self._read(path)
228
+ except OpenCodeConfigError:
229
+ data = {}
230
+ servers = data.get("mcp")
231
+ if isinstance(servers, dict) and "toolbase" in servers:
232
+ entry = servers["toolbase"]
233
+ if isinstance(entry, dict):
234
+ present = True
235
+ cmd = entry.get("command")
236
+ if isinstance(cmd, list) and cmd:
237
+ command = str(cmd[0])
238
+ args = [str(a) for a in cmd[1:]]
239
+ out.append(RegistrationEntry(
240
+ harness=self.name, scope=scope, path=path,
241
+ present=present, command=command, args=args,
242
+ ))
243
+ return out
@@ -103,14 +103,24 @@ class SkillTarget:
103
103
  ``~/.codex/prompts/<name>.md`` as a ``/<name>`` slash-command prompt
104
104
  (user-invoked only; Codex has no model-facing skill concept), so
105
105
  frontmatter is stripped to the body — Codex would otherwise render the
106
- YAML block as prose. A flat file has no dir to mark, so ownership is
106
+ YAML block as prose. OpenCode reads ``~/.config/opencode/command/<name>.md``
107
+ the same way but *does* honor a ``description`` frontmatter field (it
108
+ shows in the TUI), so its target keeps only that key via
109
+ ``frontmatter_keys``. A flat file has no dir to mark, so ownership is
107
110
  tracked by a JSON manifest at ``<root>/<MANIFEST_NAME>``.
111
+
112
+ ``frontmatter_keys`` (flat layout only) narrows the emitted frontmatter to
113
+ the listed keys when ``keep_frontmatter`` is False: ``None`` strips the
114
+ block entirely (Codex), a list rewrites it to just those keys pulled from
115
+ the source (OpenCode → ``["description"]``). Ignored when
116
+ ``keep_frontmatter`` is True.
108
117
  """
109
118
 
110
119
  harness: str
111
120
  root: Path
112
121
  layout: str # "dir" | "flat"
113
122
  keep_frontmatter: bool
123
+ frontmatter_keys: Optional[List[str]] = None
114
124
 
115
125
 
116
126
  def _read_manifest(root: Path) -> Dict[str, str]:
@@ -257,6 +267,7 @@ def surface_skills(
257
267
  _surface_flat(
258
268
  target.root, slug, text, body, fm,
259
269
  keep_frontmatter=target.keep_frontmatter,
270
+ frontmatter_keys=target.frontmatter_keys,
260
271
  manifest=manifest, toolkit_name=toolkit_name,
261
272
  )
262
273
  surfaced.append(slug)
@@ -316,22 +327,45 @@ def _surface_dir(
316
327
  def _surface_flat(
317
328
  root: Path, slug: str, text: str, body: str,
318
329
  fm: Optional[SkillFrontmatter], *, keep_frontmatter: bool,
330
+ frontmatter_keys: Optional[List[str]] = None,
319
331
  manifest: Dict[str, str], toolkit_name: str,
320
332
  ) -> None:
321
- """Write one skill as ``<root>/<slug>.md`` (Codex prompt layout).
322
-
323
- Codex has no model-facing skill concept and no frontmatter support, so
324
- by default we strip the YAML block and write only the guide body — it
325
- becomes the text of a ``/<slug>`` slash-command prompt. We always
326
- (re)write a copy (never symlink): the on-disk content differs from the
327
- source once frontmatter is stripped, and Codex reads it once at
328
- invocation rather than watching for edits.
333
+ """Write one skill as ``<root>/<slug>.md`` (flat prompt/command layout).
334
+
335
+ The file becomes the text of a ``/<slug>`` slash-command prompt. What we
336
+ keep of the source frontmatter depends on the harness:
337
+
338
+ - ``keep_frontmatter`` True — keep the block verbatim.
339
+ - ``frontmatter_keys`` set — rewrite the block to just those keys pulled
340
+ from the source (OpenCode honors ``description`` in its command files).
341
+ - otherwise — strip the block, writing only the body (Codex renders a
342
+ YAML block as prose).
343
+
344
+ We always (re)write a copy (never symlink): the on-disk content differs
345
+ from the source once frontmatter is transformed, and the harness reads it
346
+ at invocation rather than watching for edits.
329
347
  """
330
- dest = root / f"{slug}.md"
331
- content = text if keep_frontmatter else body
348
+ if keep_frontmatter:
349
+ content = text
350
+ elif frontmatter_keys and fm is not None:
351
+ kept = {
352
+ k: fm.raw[k] for k in frontmatter_keys
353
+ if fm.raw.get(k) is not None
354
+ }
355
+ if kept:
356
+ fm_block = yaml.safe_dump(
357
+ kept, default_flow_style=False, allow_unicode=True,
358
+ sort_keys=False,
359
+ )
360
+ content = f"---\n{fm_block}---\n\n" + body.lstrip("\n")
361
+ else:
362
+ content = body
363
+ else:
364
+ content = body
332
365
  content = content.lstrip("\n")
333
366
  if not content.endswith("\n"):
334
367
  content += "\n"
368
+ dest = root / f"{slug}.md"
335
369
  dest.write_text(content, encoding="utf-8")
336
370
  manifest[dest.name] = toolkit_name
337
371
 
@@ -23,6 +23,7 @@ toolbase/connect/__init__.py
23
23
  toolbase/connect/base.py
24
24
  toolbase/connect/claude_code.py
25
25
  toolbase/connect/codex.py
26
+ toolbase/connect/opencode.py
26
27
  toolbase/connect/orchestral.py
27
28
  toolbase/envs/__init__.py
28
29
  toolbase/envs/bundle_deps.py
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes