Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ What good looks like:
```bash
iicp-node --help # shows query, serve, proxy, mcp-gateway, credits, ...
which iicp-node # points to your Python environment
iicp-node --version # prints iicp-node 0.7.108 or newer
iicp-node --version # prints iicp-node 0.7.109 or newer
```

The query command contacts the public directory, discovers a matching live node,
Expand Down Expand Up @@ -213,7 +213,7 @@ base URL. Full guide: <https://iicp.network/docs/proxy>

## Keep provider nodes current

The current public release line is **0.7.108**. Upgrade through your package
The current public release line is **0.7.109**. Upgrade through your package
manager before troubleshooting an older installation. Routing profiles can
refuse remote dispatch before a prompt leaves the client; use `sensitive` for
local-only work, `eu-restricted` for EU/EEA routing, or `strict-policy` when a
Expand Down Expand Up @@ -720,3 +720,16 @@ ruff check src tests # lint
---

Apache 2.0 · [iicp.network](https://iicp.network)

### Shell completion

Generate completion for your shell without reading node, operator, or network state:

```bash
iicp-node completion bash
iicp-node completion zsh
iicp-node completion fish
iicp-node completion powershell
```

Evaluate the output in your shell startup file or redirect it to the shell's normal completion directory.
26 changes: 26 additions & 0 deletions parity/cli-completion-v1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"schema": "iicp.cli-completion.v1",
"shells": ["bash", "zsh", "fish", "powershell"],
"aliases": {"pwsh": "powershell"},
"common_top_level": [
"completion", "credits", "doctor", "healthcheck", "help", "init", "list",
"mcp-gateway", "operator", "proxy", "query", "serve", "service", "update"
],
"cases": [
{"tokens": [], "contains": ["completion", "init", "query", "serve"]},
{"tokens": ["op"], "contains": ["operator"]},
{"tokens": ["operator", ""], "contains": ["decrypt", "dsr", "encrypt", "key", "rename"]},
{"tokens": ["operator", "dsr", ""], "contains": ["anonymize", "export", "restrict"]},
{"tokens": ["service", ""], "contains": ["install", "restart", "status", "uninstall"]},
{"tokens": ["query", "--routing-profile", ""], "contains": ["eu-restricted", "sensitive", "standard", "strict-policy"]},
{"tokens": ["serve", "--backend-type", ""], "contains": ["anthropic", "llamacpp", "meshllm", "openai_compat", "vllm"]},
{"tokens": ["query", "--rou"], "contains": ["--routing-profile"]}
],
"safety": {
"network_access": false,
"filesystem_mutation": false,
"shell_profile_mutation": false,
"operator_state_enumeration": false,
"secret_output": false
}
}
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "iicp-client"
version = "0.7.108"
version = "0.7.109"
description = "Use the open IICP AI mesh from Python without running a node"
readme = "README.md"
license = {text = "Apache-2.0"}
Expand Down
2 changes: 1 addition & 1 deletion src/iicp_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@
TaskResponse,
)

__version__ = "0.7.108"
__version__ = "0.7.109"
__all__ = [
"IicpClient",
"IicpError",
Expand Down
14 changes: 13 additions & 1 deletion src/iicp_client/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ def _build_parser() -> argparse.ArgumentParser:
"help",
help="Print this top-level usage and exit.",
)
completion = sub.add_parser("completion", help="Print a shell completion script.")
completion.add_argument("shell", choices=["bash", "zsh", "fish", "powershell", "pwsh"])
sub.add_parser(
"init",
help="Interactive wizard — set up operator identity + first node config.",
Expand Down Expand Up @@ -3245,12 +3247,22 @@ def run_actions() -> None:


def main(argv: list[str] | None = None) -> int:
parser = _build_parser()
raw_argv = sys.argv[1:] if argv is None else argv
if raw_argv[:1] == ["__complete"]:
from iicp_client.completion import candidates

sys.stdout.write("".join(f"{item}\n" for item in candidates(raw_argv[1:])))
return 0
parser = _build_parser()
args = parser.parse_args(argv)
if args.cmd == "help":
parser.print_help()
return 0
if args.cmd == "completion":
from iicp_client.completion import script

sys.stdout.write(script(args.shell))
return 0
if args.cmd == "serve":
# Record whether the operator explicitly toggled the NAT flag on the CLI
# so saved-config restore can honour an explicit --no-auto-detect-nat
Expand Down
53 changes: 53 additions & 0 deletions src/iicp_client/completion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Side-effect-free shell completion for the ``iicp-node`` CLI."""

from __future__ import annotations

COMMANDS = ("completion", "credits", "doctor", "healthcheck", "help", "init", "list", "mcp-gateway", "operator", "proxy", "query", "serve", "service", "update")
SUBCOMMANDS = {
("operator",): ("decrypt", "dsr", "encrypt", "key", "rename"),
("operator", "dsr"): ("anonymize", "export", "restrict"),
("operator", "key"): ("export", "generate", "import", "list", "revoke", "rotate"),
("service",): ("install", "restart", "status", "uninstall"),
}
OPTIONS = {
(): ("--help", "--version"),
("query",): ("--directory", "--intent", "--json", "--node", "--routing-profile"),
("serve",): ("--backend-type", "--directory", "--host", "--node", "--port", "--routing-profile"),
}
VALUES = {
("query", "--routing-profile"): ("eu-restricted", "sensitive", "standard", "strict-policy"),
("serve", "--backend-type"): ("anthropic", "llamacpp", "meshllm", "openai_compat", "vllm"),
}


def candidates(tokens: list[str]) -> list[str]:
"""Return static candidates without reading operator or network state."""
if not tokens:
return list(COMMANDS)
partial = tokens[-1]
prior = tokens[:-1]
command = prior[0] if prior else ""
for (owner, option), values in VALUES.items():
if command == owner and prior and prior[-1] == option:
return [value for value in values if value.startswith(partial)]
path = tuple(item for item in prior if not item.startswith("-") and item not in ("",))
choices = list(SUBCOMMANDS.get(path, ()))
if not prior:
choices.extend(COMMANDS)
context = (command,) if command else ()
if partial.startswith("-"):
choices = list(OPTIONS.get(context, ())) + list(OPTIONS[()])
return sorted({choice for choice in choices if choice.startswith(partial)})


def script(shell: str) -> str:
shell = "powershell" if shell == "pwsh" else shell
scripts = {
"bash": '''_iicp_node_complete() {\n COMPREPLY=()\n local -a args=("${COMP_WORDS[@]:1:$COMP_CWORD}")\n while IFS= read -r candidate; do COMPREPLY+=("$candidate"); done < <(command iicp-node __complete "${args[@]}")\n}\ncomplete -F _iicp_node_complete iicp-node\n''',
"zsh": '''_iicp_node_complete() {\n local -a args candidates\n args=("${words[@]:1}")\n candidates=("${(@f)$(command iicp-node __complete "${args[@]}")}")\n compadd -- $candidates\n}\ncompdef _iicp_node_complete iicp-node\n''',
"fish": '''function __iicp_node_complete\n set -l tokens (commandline -opc)\n set -e tokens[1]\n set -a tokens (commandline -ct)\n command iicp-node __complete $tokens\nend\ncomplete -c iicp-node -f -a '(__iicp_node_complete)'\n''',
"powershell": '''Register-ArgumentCompleter -Native -CommandName iicp-node -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n $tokens = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.Extent.Text })\n if ($tokens.Count -eq 0 -or $commandAst.Extent.Text.EndsWith(' ')) { $tokens += '' }\n iicp-node __complete @tokens | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }\n}\n''',
}
if shell not in scripts:
raise ValueError(f"unsupported shell: {shell}")
return scripts[shell]
32 changes: 32 additions & 0 deletions tests/test_cli_completion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import json
from pathlib import Path

import pytest

from iicp_client.cli import main
from iicp_client.completion import candidates, script

FIXTURE = json.loads((Path(__file__).parents[1] / "parity/cli-completion-v1.json").read_text())


@pytest.mark.parametrize("case", FIXTURE["cases"])
def test_completion_parity(case):
result = candidates(case["tokens"])
assert set(case["contains"]) <= set(result)


@pytest.mark.parametrize("shell", FIXTURE["shells"] + ["pwsh"])
def test_scripts_are_static(shell):
rendered = script(shell)
assert "iicp-node __complete" in rendered
assert "IICP_DIRECTORY" not in rendered


def test_hidden_completion_stdout(capsys):
assert main(["__complete", "op"]) == 0
assert capsys.readouterr().out == "operator\n"


def test_public_completion(capsys):
assert main(["completion", "bash"]) == 0
assert "complete -F" in capsys.readouterr().out
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading