@hopetherenojs/contextya 0.0.0-stage → 0.1.4
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/.claude-plugin/plugin.json +18 -0
- package/LICENSE +23 -0
- package/README.md +81 -2
- package/bin/realontext.js +52 -0
- package/hooks/hint-grep.md +3 -0
- package/hooks/hint.js +5 -0
- package/hooks/hint.md +3 -0
- package/hooks/hooks.json +16 -0
- package/lib/agents.js +268 -0
- package/lib/binary.js +83 -0
- package/lib/distribution.json +9 -0
- package/lib/hook.js +55 -0
- package/lib/mcp.js +95 -0
- package/lib/rules.md +3 -0
- package/lib/setup.js +100 -0
- package/lib/tui.mjs +177 -0
- package/lib/update.js +141 -0
- package/package.json +42 -4
- package/pi/realontext.js +83 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "contextya",
|
|
3
|
+
"version": "0.1.4",
|
|
4
|
+
"description": "Code search. Install @hopetherenojs/contextya globally first.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "FlowerRealm",
|
|
7
|
+
"email": "flower_realm@outlook.com"
|
|
8
|
+
},
|
|
9
|
+
"mcpServers": {
|
|
10
|
+
"contextya": {
|
|
11
|
+
"command": "contextya",
|
|
12
|
+
"args": [
|
|
13
|
+
"mcp"
|
|
14
|
+
]
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://contextya.emrank.tech/docs"
|
|
18
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
realontext — 专有软件许可
|
|
2
|
+
|
|
3
|
+
Copyright (C) 2026 FlowerRealm. All rights reserved.
|
|
4
|
+
|
|
5
|
+
本软件及其源代码、文档、构建产物为 FlowerRealm 的专有财产,受著作权法保护。
|
|
6
|
+
|
|
7
|
+
未经 FlowerRealm 事先书面许可,任何人不得复制、修改、合并、发布、分发、再许可、
|
|
8
|
+
出售本软件的副本,不得对本软件进行反向工程、反编译或反汇编,不得移除或更改本
|
|
9
|
+
许可声明。
|
|
10
|
+
|
|
11
|
+
通过 npm 分发的二进制包,授予终端用户一项非独占、不可转让、可撤销的使用许可,
|
|
12
|
+
范围仅限于在用户自己的设备上运行本软件以索引和检索用户自己的代码。该许可不包
|
|
13
|
+
含对源代码的任何权利。
|
|
14
|
+
|
|
15
|
+
本软件按「现状」提供,不含任何明示或默示的担保,包括但不限于适销性、特定用途
|
|
16
|
+
适用性和非侵权的担保。在任何情况下,作者或版权持有人均不对任何索赔、损害或其
|
|
17
|
+
他责任负责。
|
|
18
|
+
|
|
19
|
+
第三方依赖各自适用其自身的许可证,见 client/vcpkg.json 所列各项目。其中 libgit2 为
|
|
20
|
+
GPL-2.0,附带 linking exception,链接不构成传染,因此不限制本许可的选择。其余
|
|
21
|
+
依赖为 MIT、Apache-2.0、CC0、curl 许可或公有领域,均允许在专有软件中使用。
|
|
22
|
+
|
|
23
|
+
商务联系:flower_realm@outlook.com
|
package/README.md
CHANGED
|
@@ -1,3 +1,82 @@
|
|
|
1
|
-
#
|
|
1
|
+
# contextya
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Code search for coding agents, over the directory you are in: whole functions
|
|
4
|
+
and classes, ranked on the machine and, when you are logged in, by a model
|
|
5
|
+
through the contextya Relay.
|
|
6
|
+
|
|
7
|
+
## Installing
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install -g @hopetherenojs/contextya
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## The menu
|
|
14
|
+
|
|
15
|
+
Run `contextya` with no command, in the repository's root: connect agents,
|
|
16
|
+
log in, and see your plan, credits left and last queries.
|
|
17
|
+
|
|
18
|
+
## Connecting an agent
|
|
19
|
+
|
|
20
|
+
In the repository root (including Claude Code):
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
contextya setup # pick the agents in the menu
|
|
24
|
+
contextya setup codex gemini # or name them: codex, gemini, cursor, vscode, opencode
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
It runs the agent's own `mcp add` (Codex, Gemini CLI) or writes the entry into
|
|
28
|
+
the repository's config (`.cursor/mcp.json`, `.vscode/mcp.json`,
|
|
29
|
+
`opencode.json`), replacing any earlier contextya entry. For any other MCP
|
|
30
|
+
client:
|
|
31
|
+
|
|
32
|
+
```jsonc
|
|
33
|
+
{ "contextya": { "command": "contextya", "args": ["mcp"] } }
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Logging in
|
|
37
|
+
|
|
38
|
+
Log in once; the Token is kept in `~/.config/contextya/config.toml`
|
|
39
|
+
(`%USERPROFILE%\.config\contextya\config.toml` on Windows) and every
|
|
40
|
+
repository uses it:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
contextya login # in the browser
|
|
44
|
+
contextya login --paste # when the browser is on another machine
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
With a Token, a described query is ranked at the Relay, which is sent the
|
|
48
|
+
query, file paths and function names, and the code of the candidate functions.
|
|
49
|
+
Without a Token nothing leaves the machine: the results are ranked locally,
|
|
50
|
+
with a notice saying so. `CONTEXTYA_TOKEN` overrides the saved Token; set to
|
|
51
|
+
an empty string, it keeps that process local.
|
|
52
|
+
|
|
53
|
+
## Updates
|
|
54
|
+
|
|
55
|
+
The binary keeps itself at the version the Relay names. In the background, at
|
|
56
|
+
most once an hour, `contextya` asks the Relay for it; a newer one is
|
|
57
|
+
downloaded from the npm registry (`npm_config_registry` if set), checked
|
|
58
|
+
against the registry's integrity, and kept in `~/.local/share/contextya`
|
|
59
|
+
(`%LOCALAPPDATA%\contextya` on Windows). The next start runs it. An agent's
|
|
60
|
+
`contextya mcp` asks before every query and, when there is a newer binary,
|
|
61
|
+
runs the query on it, without the agent seeing the switch. A newer
|
|
62
|
+
`npm install -g @hopetherenojs/contextya` runs in its place. `CONTEXTYA_NO_AUTO_UPDATE=1`
|
|
63
|
+
turns this off.
|
|
64
|
+
|
|
65
|
+
## From the shell
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
contextya query -i --pattern 'yaml|load' # the current directory
|
|
69
|
+
contextya query --pattern 'yaml|load' --query "why does loading yaml crash" # described: the Relay ranks
|
|
70
|
+
contextya query --pattern 'yaml|load' --path src --path lib -g '*.rs' # paths, and rg's options
|
|
71
|
+
git log --oneline | contextya query --pattern fix # stdin, line by line
|
|
72
|
+
cat loader.rs | contextya query --label loader.rs --pattern yaml # stdin, named for its grammar
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The regex is `--pattern`, the description `--query`, each place to search
|
|
76
|
+
`--path`; every other word goes to ripgrep as one of its options. Code comes back as
|
|
77
|
+
whole functions and classes, any other file line by line. With `--query`, a
|
|
78
|
+
description of the code, the Relay ranks the results; without it, the
|
|
79
|
+
pattern's words do. As with grep: text on stdout (`--json` for programs), exit
|
|
80
|
+
status 0 with results, 1 without, 2 on error.
|
|
81
|
+
|
|
82
|
+
Builds: macOS on Apple Silicon (13 and later), x64 Linux and x64 Windows.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The `realontext` command npm installs: runs the binary of this platform with
|
|
3
|
+
// this process's arguments, stdio and exit status. What is written here
|
|
4
|
+
// instead is what Node does better: `setup` edits agents' configs,
|
|
5
|
+
// `hook` answers the hooks it wrote, and with no command, in a
|
|
6
|
+
// terminal, a menu of everything. Each start may update the binary in
|
|
7
|
+
// the background; `mcp` passes the session through and switches to a
|
|
8
|
+
// newer binary in its middle.
|
|
9
|
+
"use strict";
|
|
10
|
+
|
|
11
|
+
const { spawnSync } = require("child_process");
|
|
12
|
+
|
|
13
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
14
|
+
const terminal = process.stdin.isTTY && process.stdout.isTTY;
|
|
15
|
+
|
|
16
|
+
if (command !== "mcp" && command !== "hook") require("../lib/update.js").start();
|
|
17
|
+
|
|
18
|
+
function exit(status) {
|
|
19
|
+
if (typeof status !== "string") process.exit(status);
|
|
20
|
+
process.kill(process.pid, status);
|
|
21
|
+
// Still here: a signal Node ignores, SIGPIPE. The status a shell gives it.
|
|
22
|
+
process.exit(128 + require("os").constants.signals[status]);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (terminal && (command === undefined || (command === "setup" && rest.length === 0))) {
|
|
26
|
+
import("../lib/tui.mjs")
|
|
27
|
+
.then((tui) => tui.default(command === "setup" ? "setup" : "home"))
|
|
28
|
+
.then((status) => process.exit(status));
|
|
29
|
+
} else if (command === "setup") {
|
|
30
|
+
process.exit(require("../lib/setup.js").setup(rest));
|
|
31
|
+
} else if (command === "hook") {
|
|
32
|
+
require("../lib/hook.js")(rest[0]);
|
|
33
|
+
} else {
|
|
34
|
+
const binary = require("../lib/binary.js");
|
|
35
|
+
let path;
|
|
36
|
+
try {
|
|
37
|
+
path = binary();
|
|
38
|
+
} catch (e) {
|
|
39
|
+
console.error(`contextya: ${e.message}`);
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
if (command === "mcp") {
|
|
43
|
+
require("../lib/mcp.js")(path, rest).then(exit);
|
|
44
|
+
} else {
|
|
45
|
+
const run = spawnSync(path, process.argv.slice(2), { stdio: "inherit" });
|
|
46
|
+
if (run.error) {
|
|
47
|
+
console.error(`contextya: ${run.error.message}`);
|
|
48
|
+
process.exit(1);
|
|
49
|
+
}
|
|
50
|
+
exit(run.signal ?? run.status);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
<contextya>
|
|
2
|
+
That was grep. Code search goes through codebase-retrieval, not grep: call it now for the code you were looking for - it returns whole functions, ranked by what you asked, with line numbers. If it is not loaded yet, load it once with `search_tools` (query "codebase-retrieval") and call it. `pattern` is the regex you would grep for; give `query`, an English description of the code, on every call - leave it out only when the pattern is one exact name you know; with it, a model on the contextya Relay ranks the results. Text outside code (docs, configs, logs, a command's output) is `contextya query --pattern RE [--path PATH]...` in the shell.
|
|
3
|
+
</contextya>
|
package/hooks/hint.js
ADDED
package/hooks/hint.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
<contextya>
|
|
2
|
+
To search source code, call codebase-retrieval yourself instead of grep or rg: it returns whole functions ranked by what you asked, with line numbers. Search yourself, at every step of the task: do not hand a code search to a subagent, which may not have this tool and greps instead. If your client defers tools and lists it by name only, load it once with your tool search before the first call. `pattern` is the regex you would grep for; give `query`, an English description of the code, on every call - leave it out only when the pattern is one exact name you know; with it, a model on the contextya Relay ranks the results. For docs, configs, logs and a command's output, use `contextya query --pattern RE [--path PATH]...` in the shell, or pipe into it: `git log | contextya query --pattern fix`. Do not run grep or rg at all.
|
|
3
|
+
</contextya>
|
package/hooks/hooks.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"description": "Reminds the agent of codebase-retrieval, once a session",
|
|
3
|
+
"hooks": {
|
|
4
|
+
"PreToolUse": [
|
|
5
|
+
{
|
|
6
|
+
"matcher": "Bash|Grep",
|
|
7
|
+
"hooks": [
|
|
8
|
+
{
|
|
9
|
+
"type": "command",
|
|
10
|
+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/hint.js\""
|
|
11
|
+
}
|
|
12
|
+
]
|
|
13
|
+
}
|
|
14
|
+
]
|
|
15
|
+
}
|
|
16
|
+
}
|
package/lib/agents.js
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// How contextya is connected to each agent, the data `setup.js` acts
|
|
2
|
+
// on and `hook.js` answers from. An agent is a list of steps, each one of:
|
|
3
|
+
//
|
|
4
|
+
// run a command of the agent's own CLI; `clear` first, quietly, when
|
|
5
|
+
// its `add` refuses a name it already has
|
|
6
|
+
// json `value` set at the key path `at` of a JSON file
|
|
7
|
+
// list `value` put in the array at `at` of a JSON file, in place of the
|
|
8
|
+
// entries an earlier setup put there
|
|
9
|
+
// block `text` as a marked block at the end of a text file (TOML, YAML,
|
|
10
|
+
// Markdown), in place of the block an earlier setup put there
|
|
11
|
+
// file `text` as the whole of a file of contextya's own
|
|
12
|
+
//
|
|
13
|
+
// A path starting with `~/` is under the home directory, a relative one under
|
|
14
|
+
// the directory `setup` runs in. Three things go in: the MCP server, everywhere;
|
|
15
|
+
// the once-a-session reminder, where the agent has a hook that adds
|
|
16
|
+
// context the model sees; the usage rules, where the agent is known not to
|
|
17
|
+
// pass the server's instructions to the model, or its model was seen not to
|
|
18
|
+
// use the tool without them. `hook` names the event or events the
|
|
19
|
+
// reminder answers, with `flat` that the answer is not wrapped in
|
|
20
|
+
// `hookSpecificOutput`, and with `hint` that another file in `hooks/` carries
|
|
21
|
+
// the text. An entry on a tool call answers the first time that tool runs.
|
|
22
|
+
"use strict";
|
|
23
|
+
|
|
24
|
+
const fs = require("fs");
|
|
25
|
+
const os = require("os");
|
|
26
|
+
const path = require("path");
|
|
27
|
+
|
|
28
|
+
const SERVER = { command: "contextya", args: ["mcp"] };
|
|
29
|
+
const RULES = fs.readFileSync(path.join(__dirname, "rules.md"), "utf8");
|
|
30
|
+
// Absolute: dsh reads the hooks file's path from YAML as it is.
|
|
31
|
+
const DSH = process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
|
|
32
|
+
|
|
33
|
+
const hook = (agent) => `contextya hook ${agent}`;
|
|
34
|
+
// The Claude Code shape, that Gemini CLI, Qwen Code, Codex and dsh read too.
|
|
35
|
+
const nested = (agent, matcher) => ({ ...(matcher && { matcher }), hooks: [{ type: "command", command: hook(agent) }] });
|
|
36
|
+
// The Copilot shape: no matcher, no nesting.
|
|
37
|
+
const flat = (agent) => ({ type: "command", command: hook(agent) });
|
|
38
|
+
|
|
39
|
+
const agents = {
|
|
40
|
+
claude: {
|
|
41
|
+
name: "Claude Code",
|
|
42
|
+
steps: [
|
|
43
|
+
{ clear: "claude mcp remove contextya -s local", run: "claude mcp add contextya -- contextya mcp" },
|
|
44
|
+
{ list: ".claude/settings.local.json", at: ["hooks", "PreToolUse"], value: nested("claude", "Bash|Grep") },
|
|
45
|
+
],
|
|
46
|
+
hook: { event: "PreToolUse" },
|
|
47
|
+
},
|
|
48
|
+
codex: {
|
|
49
|
+
name: "Codex",
|
|
50
|
+
steps: [
|
|
51
|
+
{ run: "codex mcp add contextya -- contextya mcp" },
|
|
52
|
+
// Codex drops what a PreToolUse hook adds; SessionStart's reaches the model.
|
|
53
|
+
{ list: "~/.codex/hooks.json", at: ["hooks", "SessionStart"], value: nested("codex") },
|
|
54
|
+
],
|
|
55
|
+
hook: { event: "SessionStart" },
|
|
56
|
+
},
|
|
57
|
+
gemini: {
|
|
58
|
+
name: "Gemini CLI",
|
|
59
|
+
steps: [
|
|
60
|
+
// Trusted: in headless runs (`gemini -p`) Gemini CLI hides tools that need approval.
|
|
61
|
+
{ run: "gemini mcp add --trust contextya contextya mcp" },
|
|
62
|
+
// Gemini CLI drops what a BeforeTool hook adds; AfterTool's goes after the tool's result.
|
|
63
|
+
{
|
|
64
|
+
list: ".gemini/settings.json",
|
|
65
|
+
at: ["hooks", "AfterTool"],
|
|
66
|
+
value: nested("gemini", "run_shell_command|grep_search|search_file_content"),
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
hook: { event: "AfterTool" },
|
|
70
|
+
note: "Gemini CLI starts MCP servers and hooks only in trusted folders: trust this one when it asks.",
|
|
71
|
+
},
|
|
72
|
+
qwen: {
|
|
73
|
+
name: "Qwen Code",
|
|
74
|
+
steps: [
|
|
75
|
+
{ run: "qwen mcp add -s project contextya contextya mcp" },
|
|
76
|
+
// Qwen Code holds a project's new server until it is approved.
|
|
77
|
+
{ run: "qwen mcp approve contextya" },
|
|
78
|
+
// Qwen Code drops what a PreToolUse hook adds; PostToolUse's goes after the tool's result.
|
|
79
|
+
{ list: ".qwen/settings.json", at: ["hooks", "PostToolUse"], value: nested("qwen", "run_shell_command|grep_search") },
|
|
80
|
+
],
|
|
81
|
+
hook: { event: "PostToolUse" },
|
|
82
|
+
},
|
|
83
|
+
kimi: {
|
|
84
|
+
name: "Kimi Code",
|
|
85
|
+
steps: [
|
|
86
|
+
{ json: "~/.kimi-code/mcp.json", at: ["mcpServers", "contextya"], value: SERVER },
|
|
87
|
+
{
|
|
88
|
+
block: "~/.kimi-code/config.toml",
|
|
89
|
+
text: `[[hooks]]\nevent = "PostToolUse"\nmatcher = "Shell|Bash|Grep"\ncommand = "${hook("kimi")}"\n`,
|
|
90
|
+
},
|
|
91
|
+
],
|
|
92
|
+
hook: { event: "PostToolUse" },
|
|
93
|
+
},
|
|
94
|
+
codebuddy: {
|
|
95
|
+
name: "CodeBuddy Code",
|
|
96
|
+
steps: [
|
|
97
|
+
// `alwaysLoad`: CodeBuddy defers MCP tools and ignores the tool's own `_meta`.
|
|
98
|
+
{ run: `codebuddy mcp add-json contextya ${JSON.stringify(JSON.stringify({ ...SERVER, alwaysLoad: true }))}` },
|
|
99
|
+
// CodeBuddy drops what a PreToolUse hook adds; SessionStart's reaches the model.
|
|
100
|
+
{ list: ".codebuddy/settings.local.json", at: ["hooks", "SessionStart"], value: nested("codebuddy") },
|
|
101
|
+
// It does not pass the server's instructions to the model.
|
|
102
|
+
{ file: ".codebuddy/rules/contextya.md", text: `---\nalwaysApply: true\n---\n\n${RULES}` },
|
|
103
|
+
],
|
|
104
|
+
hook: { event: "SessionStart" },
|
|
105
|
+
},
|
|
106
|
+
copilot: {
|
|
107
|
+
name: "GitHub Copilot CLI",
|
|
108
|
+
steps: [
|
|
109
|
+
{ clear: "copilot mcp remove contextya", run: "copilot mcp add contextya -- contextya mcp" },
|
|
110
|
+
{ list: "~/.copilot/hooks/contextya.json", at: ["hooks", "sessionStart"], value: flat("copilot") },
|
|
111
|
+
],
|
|
112
|
+
hook: { event: "sessionStart", flat: true },
|
|
113
|
+
},
|
|
114
|
+
vscode: {
|
|
115
|
+
name: "VS Code (GitHub Copilot)",
|
|
116
|
+
steps: [
|
|
117
|
+
{ json: ".vscode/mcp.json", at: ["servers", "contextya"], value: { type: "stdio", ...SERVER } },
|
|
118
|
+
// VS Code ignores matchers: the reminder comes before the session's first tool call.
|
|
119
|
+
{ list: ".github/hooks/contextya.json", at: ["hooks", "PreToolUse"], value: flat("vscode") },
|
|
120
|
+
{ block: ".github/copilot-instructions.md", text: RULES },
|
|
121
|
+
],
|
|
122
|
+
hook: { event: "PreToolUse" },
|
|
123
|
+
},
|
|
124
|
+
jetbrains: {
|
|
125
|
+
name: "JetBrains (GitHub Copilot)",
|
|
126
|
+
steps: [
|
|
127
|
+
{ json: "~/.config/github-copilot/intellij/mcp.json", at: ["servers", "contextya"], value: SERVER },
|
|
128
|
+
// The hooks file VS Code reads, the same wire format.
|
|
129
|
+
{ list: ".github/hooks/contextya.json", at: ["hooks", "PreToolUse"], value: flat("vscode") },
|
|
130
|
+
{ block: ".github/copilot-instructions.md", text: RULES },
|
|
131
|
+
],
|
|
132
|
+
},
|
|
133
|
+
cursor: {
|
|
134
|
+
name: "Cursor",
|
|
135
|
+
steps: [
|
|
136
|
+
{ json: ".cursor/mcp.json", at: ["mcpServers", "contextya"], value: SERVER },
|
|
137
|
+
// Cursor does not show the model what its hooks add: the rules carry it.
|
|
138
|
+
{ file: ".cursor/rules/contextya.mdc", text: `---\ndescription: Code search with contextya\nalwaysApply: true\n---\n\n${RULES}` },
|
|
139
|
+
],
|
|
140
|
+
note: "Approve the server once: in the editor when it asks, or `cursor-agent mcp enable contextya`.",
|
|
141
|
+
},
|
|
142
|
+
opencode: {
|
|
143
|
+
name: "opencode",
|
|
144
|
+
steps: [{ json: "opencode.json", at: ["mcp", "contextya"], value: { type: "local", command: ["contextya", "mcp"] } }],
|
|
145
|
+
},
|
|
146
|
+
kilo: {
|
|
147
|
+
name: "Kilo Code",
|
|
148
|
+
steps: [{ json: "kilo.json", at: ["mcp", "contextya"], value: { type: "local", command: ["contextya", "mcp"] } }],
|
|
149
|
+
},
|
|
150
|
+
kiro: {
|
|
151
|
+
name: "Kiro",
|
|
152
|
+
steps: [
|
|
153
|
+
{ json: ".kiro/settings/mcp.json", at: ["mcpServers", "contextya"], value: SERVER },
|
|
154
|
+
{ file: ".kiro/steering/contextya.md", text: `---\ninclusion: always\n---\n\n${RULES}` },
|
|
155
|
+
],
|
|
156
|
+
},
|
|
157
|
+
antigravity: {
|
|
158
|
+
name: "Antigravity",
|
|
159
|
+
steps: [
|
|
160
|
+
// Antigravity 2.x reads the global MCP file the CLI writes, not the old `antigravity/` one.
|
|
161
|
+
{ json: "~/.gemini/config/mcp_config.json", at: ["mcpServers", "contextya"], value: SERVER },
|
|
162
|
+
// The same agent as Antigravity CLI: MCP tools only through `call_mcp_tool`.
|
|
163
|
+
{ block: "AGENTS.md", text: RULES },
|
|
164
|
+
],
|
|
165
|
+
},
|
|
166
|
+
agy: {
|
|
167
|
+
name: "Antigravity CLI",
|
|
168
|
+
steps: [
|
|
169
|
+
{ run: "agy mcp add contextya contextya mcp" },
|
|
170
|
+
// Antigravity CLI shows MCP tools only through a generic `call_mcp_tool`: the rules name it.
|
|
171
|
+
{ block: "AGENTS.md", text: RULES },
|
|
172
|
+
],
|
|
173
|
+
},
|
|
174
|
+
zed: {
|
|
175
|
+
name: "Zed",
|
|
176
|
+
steps: [{ json: ".zed/settings.json", at: ["context_servers", "contextya"], value: SERVER }],
|
|
177
|
+
note: "Zed starts a project's context servers only once the folder is trusted: trust it when Zed asks.",
|
|
178
|
+
},
|
|
179
|
+
openclaw: {
|
|
180
|
+
name: "OpenClaw",
|
|
181
|
+
steps: [
|
|
182
|
+
{ json: "~/.openclaw/openclaw.json", at: ["mcp", "servers", "contextya"], value: SERVER },
|
|
183
|
+
// OpenClaw passes no server instructions and keeps MCP tools behind its Tool Search;
|
|
184
|
+
// a skill is what its prompt lists, by name and description.
|
|
185
|
+
{
|
|
186
|
+
file: "~/.openclaw/skills/contextya/SKILL.md",
|
|
187
|
+
text: `---\nname: contextya\ndescription: Read this before searching source code. Code is searched with the contextya__codebase-retrieval tool, not with grep, rg or find through exec: every time you need to find where something is in the code (a behavior, a definition, its callers).\n---\n\n${RULES}\nIn OpenClaw the tool is \`contextya__codebase-retrieval\`; when it is not in your tool list, find it with \`tool_search\` and call it with \`tool_call\`.\n`,
|
|
188
|
+
},
|
|
189
|
+
],
|
|
190
|
+
},
|
|
191
|
+
cline: {
|
|
192
|
+
name: "Cline",
|
|
193
|
+
steps: [
|
|
194
|
+
{ clear: "cline mcp remove contextya", run: "cline mcp add --yes contextya -- contextya mcp" },
|
|
195
|
+
// Cline has a search tool of its own and reaches for it first, unless the rules name it.
|
|
196
|
+
{
|
|
197
|
+
file: ".clinerules/contextya.md",
|
|
198
|
+
text: `${RULES}\nIn Cline the tool is \`contextya__codebase-retrieval\`, and it takes the place of \`search_codebase\`: search source code with it, not with \`search_codebase\` or \`run_commands\`.\n`,
|
|
199
|
+
},
|
|
200
|
+
],
|
|
201
|
+
},
|
|
202
|
+
pi: {
|
|
203
|
+
name: "Pi",
|
|
204
|
+
// Pi has no MCP: the package's own extension (`pi/contextya.js`) is the bridge.
|
|
205
|
+
steps: [{ run: `pi install "${path.dirname(__dirname)}"` }],
|
|
206
|
+
},
|
|
207
|
+
omp: {
|
|
208
|
+
name: "Oh My Pi",
|
|
209
|
+
steps: [
|
|
210
|
+
{ json: "~/.omp/agent/mcp.json", at: ["mcpServers", "contextya"], value: SERVER },
|
|
211
|
+
// Oh My Pi gives MCP servers 250 ms to list their tools before the first turn; a
|
|
212
|
+
// server that misses it is left out of that turn's prompt. 0 waits for it.
|
|
213
|
+
{ run: "omp config set mcp.startupTimeoutMs 0" },
|
|
214
|
+
// Its own `find` and `grep` win otherwise.
|
|
215
|
+
{
|
|
216
|
+
file: ".omp/rules/contextya.md",
|
|
217
|
+
text: `---\ndescription: Code search with contextya\nalwaysApply: true\n---\n\n${RULES}\nIn Oh My Pi the tool is \`mcp__contextya_codebase_retrieval\` (or the device \`xd://mcp__contextya_codebase_retrieval\`), and it takes the place of \`find\` and \`grep\`: search source code with it, not with them.\n`,
|
|
218
|
+
},
|
|
219
|
+
],
|
|
220
|
+
},
|
|
221
|
+
dsh: {
|
|
222
|
+
name: "DeepSeek Harness",
|
|
223
|
+
steps: [
|
|
224
|
+
{
|
|
225
|
+
block: path.join(DSH, "cordis.patch.yml"),
|
|
226
|
+
text: [
|
|
227
|
+
"- insert:",
|
|
228
|
+
" - id: contextya",
|
|
229
|
+
" name: '@deepseek-ai/dsh-mcp-client'",
|
|
230
|
+
" config:",
|
|
231
|
+
" serverName: contextya",
|
|
232
|
+
" transport: stdio",
|
|
233
|
+
" command: contextya",
|
|
234
|
+
" args: [mcp]",
|
|
235
|
+
" cwd: !!js process.cwd()",
|
|
236
|
+
" - id: contextya-hooks",
|
|
237
|
+
" name: '@deepseek-ai/dsh-hooks-claude-code'",
|
|
238
|
+
" config:",
|
|
239
|
+
` configPath: '${path.join(DSH, "contextya-hooks.json")}'`,
|
|
240
|
+
"",
|
|
241
|
+
].join("\n"),
|
|
242
|
+
},
|
|
243
|
+
// dsh's Claude Code bridge adds no context from PreToolUse; SessionStart's reaches the model.
|
|
244
|
+
{ list: path.join(DSH, "contextya-hooks.json"), at: ["hooks", "SessionStart"], value: nested("dsh") },
|
|
245
|
+
],
|
|
246
|
+
hook: { event: "SessionStart" },
|
|
247
|
+
},
|
|
248
|
+
commandcode: {
|
|
249
|
+
name: "Command Code",
|
|
250
|
+
steps: [
|
|
251
|
+
// Global, like Codex's: nothing of ours lands in the repository. An
|
|
252
|
+
// earlier entry at another scope would win over this one, so clear first.
|
|
253
|
+
{ clear: "cmd mcp remove contextya", run: "cmd mcp add --scope user contextya -- contextya mcp" },
|
|
254
|
+
{ list: "~/.commandcode/settings.json", at: ["hooks", "SessionStart"], value: nested("commandcode") },
|
|
255
|
+
// Its hooks match the tool's display name, and the Grep tool's is SEARCH:
|
|
256
|
+
// the reminder rides the first grep result itself, where the model reads
|
|
257
|
+
// it, not the session's first turn. Anchored: SEARCH also sits inside
|
|
258
|
+
// SEARCH_TOOLS and WEB_SEARCH.
|
|
259
|
+
{ list: "~/.commandcode/settings.json", at: ["hooks", "PreToolUse"], value: nested("commandcode", "^SEARCH$") },
|
|
260
|
+
],
|
|
261
|
+
hook: [
|
|
262
|
+
{ event: "SessionStart" },
|
|
263
|
+
{ event: "PreToolUse", hint: "grep" },
|
|
264
|
+
],
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
module.exports = agents;
|
package/lib/binary.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// The binary this machine runs: the one the platform package npm picked
|
|
2
|
+
// through optionalDependencies, or the newer one the updater put in
|
|
3
|
+
// versions/. Throws when there is neither.
|
|
4
|
+
"use strict";
|
|
5
|
+
|
|
6
|
+
const fs = require("fs");
|
|
7
|
+
const os = require("os");
|
|
8
|
+
const path = require("path");
|
|
9
|
+
const { version } = require("../package.json");
|
|
10
|
+
|
|
11
|
+
const distribution = require('./distribution.json');
|
|
12
|
+
const packages = Object.fromEntries(Object.entries(distribution.packages).map(([platform, name]) => [platform.replace('-', ' '), name]));
|
|
13
|
+
|
|
14
|
+
const exe = process.platform === "win32" ? "realontext.exe" : "realontext";
|
|
15
|
+
|
|
16
|
+
function packageName() {
|
|
17
|
+
return packages[`${process.platform} ${process.arch}`];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Where the updater keeps versions/<version>/ and `current`, the version that runs.
|
|
21
|
+
function home() {
|
|
22
|
+
if (process.platform === "win32") {
|
|
23
|
+
return path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"), "contextya");
|
|
24
|
+
}
|
|
25
|
+
return path.join(os.homedir(), ".local", "share", "contextya");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function parse(v) {
|
|
29
|
+
const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(v || "");
|
|
30
|
+
return m && m.slice(1).map(Number);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Whether version `a` is later than `b`; false when either is not a version.
|
|
34
|
+
function newer(a, b) {
|
|
35
|
+
const x = parse(a);
|
|
36
|
+
const y = parse(b);
|
|
37
|
+
if (!x || !y) return false;
|
|
38
|
+
const i = x.findIndex((n, k) => n !== y[k]);
|
|
39
|
+
return i >= 0 && x[i] > y[i];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The updater's version, when it is newer than npm's: {version, path}.
|
|
43
|
+
function installed() {
|
|
44
|
+
if (distribution.local) return null;
|
|
45
|
+
try {
|
|
46
|
+
const v = fs.readFileSync(path.join(home(), "current"), "utf8").trim();
|
|
47
|
+
const p = path.join(home(), "versions", v, exe);
|
|
48
|
+
return newer(v, version) && fs.existsSync(p) ? { version: v, path: p } : null;
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function binary() {
|
|
55
|
+
if (distribution.local) {
|
|
56
|
+
if (process.platform !== 'linux' || process.arch !== 'x64') {
|
|
57
|
+
throw new Error('this local package is for Linux x64 (including WSL Ubuntu)');
|
|
58
|
+
}
|
|
59
|
+
return path.join(__dirname, '../native', exe);
|
|
60
|
+
}
|
|
61
|
+
const ours = installed();
|
|
62
|
+
if (ours) return ours.path;
|
|
63
|
+
const name = packageName();
|
|
64
|
+
if (!name) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`no build for ${process.platform}-${process.arch}; ` +
|
|
67
|
+
`there are builds for ${Object.keys(packages).map((k) => k.replace(" ", "-")).join(", ")}`
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
return require.resolve(`${name}/bin/${exe}`);
|
|
72
|
+
} catch {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`${name} is not installed. It is an optional dependency of contextya; ` +
|
|
75
|
+
`reinstall without --no-optional / --omit=optional.`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// The version `binary()` runs.
|
|
81
|
+
binary.version = () => installed()?.version ?? version;
|
|
82
|
+
|
|
83
|
+
module.exports = Object.assign(binary, { packageName, home, exe, newer });
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"relay": "https://contextya.emrank.tech",
|
|
3
|
+
"console": "https://contextya.emrank.tech",
|
|
4
|
+
"packages": {
|
|
5
|
+
"darwin-arm64": "@hopetherenojs/contextya-darwin-arm64",
|
|
6
|
+
"linux-x64": "@hopetherenojs/contextya-linux-x64",
|
|
7
|
+
"win32-x64": "@hopetherenojs/contextya-win32-x64"
|
|
8
|
+
}
|
|
9
|
+
}
|
package/lib/hook.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// `contextya hook <agent>`: the first time a session fires each hook
|
|
2
|
+
// `setup` wrote, the model is reminded that codebase-retrieval searches source
|
|
3
|
+
// code. Once a session per event, and only context: the agent goes on as it
|
|
4
|
+
// would, and any failure here is silent. Which events it answers, and in what
|
|
5
|
+
// shape, is the agent's `hook` in `agents.js` - one event or a list of them; an
|
|
6
|
+
// entry naming a `hint` reads `hooks/hint-<hint>.md` in place of `hooks/hint.md`.
|
|
7
|
+
// An entry with no `hint` whose event fired for a grep tool reads `hint-grep.md`
|
|
8
|
+
// instead: the reminder rides the grep itself, which is where the model reaches
|
|
9
|
+
// for it, not the session's first turn.
|
|
10
|
+
"use strict";
|
|
11
|
+
|
|
12
|
+
const fs = require("fs");
|
|
13
|
+
const os = require("os");
|
|
14
|
+
const path = require("path");
|
|
15
|
+
|
|
16
|
+
// True the first time it is asked for one session, event and text, false after:
|
|
17
|
+
// a marker file per session, made atomically, since every hook call is its own
|
|
18
|
+
// process.
|
|
19
|
+
function firstTime(marker) {
|
|
20
|
+
const id = marker.replace(/[^\w-]/g, "");
|
|
21
|
+
try {
|
|
22
|
+
fs.closeSync(fs.openSync(path.join(os.tmpdir(), `contextya-hint-${id}`), "wx"));
|
|
23
|
+
return true;
|
|
24
|
+
} catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
module.exports = function hook(key) {
|
|
30
|
+
let raw = "";
|
|
31
|
+
process.stdin.on("data", (d) => (raw += d));
|
|
32
|
+
process.stdin.on("end", () => {
|
|
33
|
+
try {
|
|
34
|
+
const events = [].concat(require("./agents.js")[key].hook);
|
|
35
|
+
const input = JSON.parse(raw);
|
|
36
|
+
// The event that fired, as the agent names it; the first entry answers
|
|
37
|
+
// when the payload does not name one.
|
|
38
|
+
const fired = typeof input.hook_event_name === "string" ? input.hook_event_name : "";
|
|
39
|
+
const { event, flat, hint } = events.find((e) => e.event === fired) ?? events[0];
|
|
40
|
+
const session = String((input.session_id ?? input.sessionId ?? input.conversation_id) || process.ppid);
|
|
41
|
+
// The tool the event is about, as the agent names it: a grep tool gets the
|
|
42
|
+
// sharp reminder, anything else the plain one. Command Code's grep is
|
|
43
|
+
// SEARCH, which no `/grep/i` catches: its own entry says `hint: "grep"`.
|
|
44
|
+
const tool = String(input.tool_name ?? input.toolName ?? input.tool ?? "");
|
|
45
|
+
const which = hint ?? (/grep/i.test(tool) ? "grep" : "");
|
|
46
|
+
if (!firstTime(`${key}-${event}-${which || "hint"}-${session}`)) return;
|
|
47
|
+
const file = which ? `hint-${which}.md` : "hint.md";
|
|
48
|
+
const text = fs.readFileSync(path.join(__dirname, "..", "hooks", file), "utf8").trimEnd();
|
|
49
|
+
const out = flat ? { additionalContext: text } : { hookSpecificOutput: { hookEventName: event, additionalContext: text } };
|
|
50
|
+
process.stdout.write(JSON.stringify(out));
|
|
51
|
+
} catch {
|
|
52
|
+
// A reminder that cannot be given is not worth stopping the agent for.
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
};
|
package/lib/mcp.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// `realontext mcp` through the wrapper: the agent's JSON-RPC lines go to
|
|
2
|
+
// the binary in order and its lines come back. Before each tools/call the
|
|
3
|
+
// version is asked for; when that gives a newer binary, it is started,
|
|
4
|
+
// the session's initialize is replayed to it and its answer dropped, and the
|
|
5
|
+
// call goes to it. The old binary's stdin is closed: it answers what it was
|
|
6
|
+
// sent and exits.
|
|
7
|
+
"use strict";
|
|
8
|
+
|
|
9
|
+
const readline = require("readline");
|
|
10
|
+
const { spawn } = require("child_process");
|
|
11
|
+
const binary = require("./binary.js");
|
|
12
|
+
const update = require("./update.js");
|
|
13
|
+
|
|
14
|
+
const replay = "realontext-switch"; // the id of the replayed initialize
|
|
15
|
+
|
|
16
|
+
function parse(line) {
|
|
17
|
+
try {
|
|
18
|
+
const m = JSON.parse(line);
|
|
19
|
+
return m && typeof m === "object" ? m : null;
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Resolves to the exit status, or the signal, once the binary has exited.
|
|
26
|
+
module.exports = function mcp(path, args) {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
let child;
|
|
29
|
+
let initialize = null;
|
|
30
|
+
let busy = false;
|
|
31
|
+
let closed = false;
|
|
32
|
+
let status = null; // the current binary's, once it has exited
|
|
33
|
+
const alive = new Set(); // binaries not exited, the old ones answering what they were sent
|
|
34
|
+
const held = []; // the agent's lines not sent yet
|
|
35
|
+
|
|
36
|
+
function start() {
|
|
37
|
+
const c = spawn(path, ["mcp", ...args], {
|
|
38
|
+
stdio: ["pipe", "pipe", "inherit"],
|
|
39
|
+
windowsHide: true,
|
|
40
|
+
});
|
|
41
|
+
child = c;
|
|
42
|
+
c.stdin.on("error", () => {});
|
|
43
|
+
readline.createInterface({ input: c.stdout, crlfDelay: Infinity }).on("line", (line) => {
|
|
44
|
+
if (parse(line)?.id !== replay) process.stdout.write(line + "\n");
|
|
45
|
+
});
|
|
46
|
+
c.on("error", (e) => {
|
|
47
|
+
if (c !== child) return;
|
|
48
|
+
console.error(`contextya: ${e.message}`);
|
|
49
|
+
resolve(1);
|
|
50
|
+
});
|
|
51
|
+
alive.add(c);
|
|
52
|
+
c.on("exit", (code, signal) => {
|
|
53
|
+
alive.delete(c);
|
|
54
|
+
if (c === child) status = signal ?? code ?? 1;
|
|
55
|
+
// The status goes back once every binary has answered and every answer is out.
|
|
56
|
+
if (status !== null && !alive.size) process.stdout.write("", () => resolve(status));
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function pump() {
|
|
61
|
+
if (busy) return;
|
|
62
|
+
busy = true;
|
|
63
|
+
while (held.length) {
|
|
64
|
+
const line = held.shift();
|
|
65
|
+
const m = parse(line);
|
|
66
|
+
if (m?.method === "tools/call") {
|
|
67
|
+
const newer = await update.latest();
|
|
68
|
+
if (newer && newer !== path) {
|
|
69
|
+
const old = child;
|
|
70
|
+
path = newer;
|
|
71
|
+
start();
|
|
72
|
+
if (initialize) child.stdin.write(JSON.stringify({ ...parse(initialize), id: replay }) + "\n");
|
|
73
|
+
old.stdin.end();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (m?.method === "initialize") initialize = line;
|
|
77
|
+
child.stdin.write(line + "\n");
|
|
78
|
+
}
|
|
79
|
+
busy = false;
|
|
80
|
+
if (closed) child.stdin.end();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
start();
|
|
84
|
+
readline
|
|
85
|
+
.createInterface({ input: process.stdin, crlfDelay: Infinity })
|
|
86
|
+
.on("line", (line) => {
|
|
87
|
+
held.push(line);
|
|
88
|
+
pump();
|
|
89
|
+
})
|
|
90
|
+
.on("close", () => {
|
|
91
|
+
closed = true;
|
|
92
|
+
pump();
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
};
|
package/lib/rules.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
## Code search
|
|
2
|
+
|
|
3
|
+
This repository is searched with contextya, which replaces grep. Its MCP tool `codebase-retrieval` searches the code: every time you need to know where something is in the source (where or how something is done, where a name you know is defined, what calls it, where it is used, which line of a file it is on), call `codebase-retrieval` yourself, at every step of the task (if your tools are deferred, load it first). For text in docs, configs and logs, and for a command's output, run `contextya query --pattern RE [--path PATH]...` in the shell, or pipe into it: `git log | contextya query --pattern fix`. Do not run grep, rg, git grep or any other text search, as a tool or in the shell, alone or inside a longer command. Listing files by name stays with your own tools. Every call needs a `pattern`: the grep you would have run, in ripgrep's syntax: a name exactly (`truncate_name\(` for every call of it), or for a description the keywords the code must contain, broad and case-insensitive (`(?i)retry|backoff`); only code with a matching line is searched. Give a `query` on every call, an English description of the behavior with words likely to appear in the code: the Relay then orders the results. Leave it out only when the pattern is one exact name you already know and you want just its own line: the pattern's words answer at once. If nothing comes back, loosen the pattern; if 20 results are not enough, narrow it.
|
package/lib/setup.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// `contextya setup [agent...]`: connects agents to `contextya mcp`, run from
|
|
2
|
+
// the repository root. What each agent gets is in `agents.js`;
|
|
3
|
+
// this file carries the steps out. With no agent named, the menu in `tui.mjs`
|
|
4
|
+
// asks which. Running it again replaces what an earlier run wrote, such as an
|
|
5
|
+
// older `npx` entry, and leaves everything else in the files as it was.
|
|
6
|
+
"use strict";
|
|
7
|
+
|
|
8
|
+
const fs = require("fs");
|
|
9
|
+
const os = require("os");
|
|
10
|
+
const path = require("path");
|
|
11
|
+
const { spawnSync } = require("child_process");
|
|
12
|
+
const agents = require("./agents.js");
|
|
13
|
+
|
|
14
|
+
const MINE = "contextya hook"; // in every hook entry setup writes
|
|
15
|
+
|
|
16
|
+
// Through a shell, so that npm's `.cmd` wrappers run on Windows too.
|
|
17
|
+
function sh(command, quiet) {
|
|
18
|
+
const run = spawnSync(command, { shell: true, stdio: quiet ? "ignore" : "inherit" });
|
|
19
|
+
if (run.error) throw run.error;
|
|
20
|
+
return run.status ?? 1;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function where(file) {
|
|
24
|
+
return file.startsWith("~/") ? path.join(os.homedir(), file.slice(2)) : file;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function save(file, text) {
|
|
28
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
29
|
+
fs.writeFileSync(file, text);
|
|
30
|
+
console.error(`contextya: wrote ${file}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The JSON at `file` with `change` made to the value at the key path `at`.
|
|
34
|
+
function edit(file, at, change) {
|
|
35
|
+
let config = {};
|
|
36
|
+
if (fs.existsSync(file)) {
|
|
37
|
+
try {
|
|
38
|
+
config = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
39
|
+
} catch (e) {
|
|
40
|
+
throw new Error(`${file} is not plain JSON (${e.message}); add this at ${at.join(" > ")} by hand:\n` + JSON.stringify(change(undefined), null, 2));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const parent = at.slice(0, -1).reduce((o, k) => (o[k] = o[k] ?? {}), config);
|
|
44
|
+
const key = at[at.length - 1];
|
|
45
|
+
parent[key] = change(parent[key]);
|
|
46
|
+
save(file, JSON.stringify(config, null, 2) + "\n");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// `text` between two marker lines at the end of `file`, in place of the ones there.
|
|
50
|
+
function block(file, text) {
|
|
51
|
+
const [open, close] = file.endsWith(".md")
|
|
52
|
+
? ["<!-- >>> contextya -->", "<!-- <<< contextya -->"]
|
|
53
|
+
: ["# >>> contextya", "# <<< contextya"];
|
|
54
|
+
const old = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
|
|
55
|
+
const start = old.indexOf(open);
|
|
56
|
+
const end = old.indexOf(close, start);
|
|
57
|
+
const rest = start < 0 || end < 0 ? old : old.slice(0, start) + old.slice(end + close.length).replace(/^\r?\n/, "");
|
|
58
|
+
const head = rest.trimEnd();
|
|
59
|
+
save(file, `${head}${head ? "\n\n" : ""}${open}\n${text.trimEnd()}\n${close}\n`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function step(s) {
|
|
63
|
+
if (s.run) {
|
|
64
|
+
if (s.clear) sh(s.clear, true);
|
|
65
|
+
const status = sh(s.run, false);
|
|
66
|
+
if (status !== 0) throw new Error(`\`${s.run}\` exited with ${status}`);
|
|
67
|
+
} else if (s.json) {
|
|
68
|
+
edit(where(s.json), s.at, () => s.value);
|
|
69
|
+
} else if (s.list) {
|
|
70
|
+
const ours = (e) => JSON.stringify(e).includes(MINE);
|
|
71
|
+
edit(where(s.list), s.at, (list) => [...(Array.isArray(list) ? list.filter((e) => !ours(e)) : []), s.value]);
|
|
72
|
+
} else if (s.block) {
|
|
73
|
+
block(where(s.block), s.text);
|
|
74
|
+
} else {
|
|
75
|
+
save(where(s.file), s.text);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The steps run in order; the first that fails stops this agent.
|
|
80
|
+
function connect(agent) {
|
|
81
|
+
try {
|
|
82
|
+
agent.steps.forEach(step);
|
|
83
|
+
} catch (e) {
|
|
84
|
+
console.error(`contextya: ${agent.name}: ${e.message}`);
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
if (agent.note) console.error(agent.note);
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Every agent named gets its turn; one failing does not stop the rest.
|
|
92
|
+
function setup(keys) {
|
|
93
|
+
if (!keys.length || keys.some((k) => !agents[k])) {
|
|
94
|
+
console.error(`usage: contextya setup [agent...], in the repository's root\nagents: ${Object.keys(agents).join(", ")}`);
|
|
95
|
+
return 2;
|
|
96
|
+
}
|
|
97
|
+
return keys.map((k) => connect(agents[k])).some((status) => status !== 0) ? 1 : 0;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = { agents, setup };
|
package/lib/tui.mjs
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// What `contextya` opens with no command, in a terminal: the account
|
|
2
|
+
// behind the Token, connecting agents, logging in. The Relay is asked through
|
|
3
|
+
// the binary (`usage`, `login`), agents are connected through `setup.js`.
|
|
4
|
+
//
|
|
5
|
+
// A screen that needs the terminal to itself (login waits on the browser or
|
|
6
|
+
// reads a pasted Token; an agent's own `mcp add` prints) closes the menu, runs,
|
|
7
|
+
// and the menu opens again below what it printed.
|
|
8
|
+
import { execFile, spawnSync } from "node:child_process";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import React, { useEffect, useState } from "react";
|
|
11
|
+
import { Box, Text, render, useApp, useInput } from "ink";
|
|
12
|
+
|
|
13
|
+
const require = createRequire(import.meta.url);
|
|
14
|
+
const { agents, setup } = require("./setup.js");
|
|
15
|
+
const binary = require("./binary.js");
|
|
16
|
+
const h = React.createElement;
|
|
17
|
+
|
|
18
|
+
// `contextya usage`: {account, queries}, or {error} with what went wrong.
|
|
19
|
+
function usage() {
|
|
20
|
+
return new Promise((resolve) => {
|
|
21
|
+
execFile(binary(), ["usage"], (err, stdout, stderr) =>
|
|
22
|
+
resolve(err ? { error: stderr.trim().replace(/^contextya: /, "") || err.message } : JSON.parse(stdout))
|
|
23
|
+
);
|
|
24
|
+
}).catch((e) => ({ error: e.message }));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function run(args) {
|
|
28
|
+
try {
|
|
29
|
+
spawnSync(binary(), args, { stdio: "inherit" });
|
|
30
|
+
} catch (e) {
|
|
31
|
+
console.error(`contextya: ${e.message}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Up and down move, enter picks, esc or q goes back. With `multiple`, space
|
|
36
|
+
// ticks, and enter picks the ticked items, or the one under the cursor when
|
|
37
|
+
// none is ticked. `onPick` gets the indices picked.
|
|
38
|
+
function List({ items, multiple, onPick, onBack }) {
|
|
39
|
+
const [at, setAt] = useState(0);
|
|
40
|
+
const [ticked, setTicked] = useState(() => new Set());
|
|
41
|
+
useInput((input, key) => {
|
|
42
|
+
if (key.upArrow || input === "k") setAt((at + items.length - 1) % items.length);
|
|
43
|
+
else if (key.downArrow || input === "j") setAt((at + 1) % items.length);
|
|
44
|
+
else if (input === " " && multiple) {
|
|
45
|
+
const next = new Set(ticked);
|
|
46
|
+
next.has(at) ? next.delete(at) : next.add(at);
|
|
47
|
+
setTicked(next);
|
|
48
|
+
} else if (key.return) onPick(ticked.size ? [...ticked].sort() : [at]);
|
|
49
|
+
else if (key.escape || input === "q") onBack();
|
|
50
|
+
});
|
|
51
|
+
return h(
|
|
52
|
+
Box,
|
|
53
|
+
{ flexDirection: "column" },
|
|
54
|
+
items.map((label, i) =>
|
|
55
|
+
h(
|
|
56
|
+
Text,
|
|
57
|
+
{ key: label, color: i === at ? "cyan" : undefined, bold: i === at },
|
|
58
|
+
`${i === at ? ">" : " "} ${multiple ? (ticked.has(i) ? "[x] " : "[ ] ") : ""}${label}`
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function Account({ account }) {
|
|
65
|
+
if (!account) return h(Text, { dimColor: true }, "Checking the account...");
|
|
66
|
+
if (account.error) return h(Text, { color: "yellow" }, account.error);
|
|
67
|
+
const { email, plan, end_at, credit } = account.account;
|
|
68
|
+
const term = plan ? `${plan} plan${end_at ? ` until ${end_at.slice(0, 10)}` : ""}` : "no plan";
|
|
69
|
+
return h(Text, null, `${email} · ${term} · ${credit} credits left`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// A screen, or a thing to run once the menu has closed; neither is quitting.
|
|
73
|
+
const HOME = [
|
|
74
|
+
{ label: "Connect agents in this directory", screen: "setup" },
|
|
75
|
+
{ label: "Usage", screen: "usage" },
|
|
76
|
+
{ label: "Log in in the browser", then: () => run(["login"]) },
|
|
77
|
+
{ label: "Log in with a pasted Token", then: () => run(["login", "--paste"]) },
|
|
78
|
+
{ label: "Quit" },
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
function Home({ go, done }) {
|
|
82
|
+
return h(List, {
|
|
83
|
+
items: HOME.map((item) => item.label),
|
|
84
|
+
onPick: ([i]) => (HOME[i].screen ? go(HOME[i].screen) : done(HOME[i].then)),
|
|
85
|
+
onBack: () => done(),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function Setup({ go, done }) {
|
|
90
|
+
const keys = Object.keys(agents);
|
|
91
|
+
return h(
|
|
92
|
+
Box,
|
|
93
|
+
{ flexDirection: "column" },
|
|
94
|
+
h(Text, { dimColor: true }, "space ticks, enter connects, esc goes back"),
|
|
95
|
+
h(List, {
|
|
96
|
+
items: keys.map((k) => agents[k].name),
|
|
97
|
+
multiple: true,
|
|
98
|
+
onPick: (picked) => done(() => setup(picked.map((i) => keys[i]))),
|
|
99
|
+
onBack: () => go("home"),
|
|
100
|
+
})
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function Usage({ account, go }) {
|
|
105
|
+
useInput((input, key) => {
|
|
106
|
+
if (key.escape || key.return || input === "q") go("home");
|
|
107
|
+
});
|
|
108
|
+
const back = h(Text, { dimColor: true }, "esc goes back");
|
|
109
|
+
if (!account || account.error) return back;
|
|
110
|
+
const { plan, end_at, credit } = account.account;
|
|
111
|
+
const queries = account.queries.items;
|
|
112
|
+
return h(
|
|
113
|
+
Box,
|
|
114
|
+
{ flexDirection: "column" },
|
|
115
|
+
h(Text, null, `Plan ${plan ?? "none"}${end_at ? `, until ${end_at} UTC` : ""}`),
|
|
116
|
+
h(Text, null, `Credits ${credit} left`),
|
|
117
|
+
h(Text, { bold: true }, `\n${"Last queries charged".padEnd(25)}seconds status`),
|
|
118
|
+
queries.length
|
|
119
|
+
? queries.map((q) =>
|
|
120
|
+
h(Text, { key: q.id }, `${q.time} UTC ${(q.duration_ms / 1000).toFixed(1).padStart(7)} ${q.status}`)
|
|
121
|
+
)
|
|
122
|
+
: h(Text, { dimColor: true }, "none yet"),
|
|
123
|
+
back
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const SCREENS = { home: Home, setup: Setup, usage: Usage };
|
|
128
|
+
|
|
129
|
+
function App({ start, onDone }) {
|
|
130
|
+
const { exit } = useApp();
|
|
131
|
+
const [screen, go] = useState(start);
|
|
132
|
+
const [account, setAccount] = useState(null);
|
|
133
|
+
useEffect(() => {
|
|
134
|
+
usage().then(setAccount);
|
|
135
|
+
}, []);
|
|
136
|
+
const done = (then) => {
|
|
137
|
+
onDone(then);
|
|
138
|
+
exit();
|
|
139
|
+
};
|
|
140
|
+
return h(
|
|
141
|
+
Box,
|
|
142
|
+
{ flexDirection: "column", gap: 1 },
|
|
143
|
+
h(
|
|
144
|
+
Box,
|
|
145
|
+
{ flexDirection: "column" },
|
|
146
|
+
h(Text, { bold: true }, `contextya ${binary.version()} `, h(Text, { dimColor: true }, process.cwd())),
|
|
147
|
+
h(Account, { account })
|
|
148
|
+
),
|
|
149
|
+
h(SCREENS[screen], { account, go, done })
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Resolves to what to run once the menu has closed, or nothing to quit. The
|
|
154
|
+
// menu is wiped first: what runs prints where it was.
|
|
155
|
+
async function show(start) {
|
|
156
|
+
let then;
|
|
157
|
+
const app = render(
|
|
158
|
+
h(App, {
|
|
159
|
+
start,
|
|
160
|
+
onDone: (f) => {
|
|
161
|
+
then = f;
|
|
162
|
+
app.clear();
|
|
163
|
+
},
|
|
164
|
+
})
|
|
165
|
+
);
|
|
166
|
+
await app.waitUntilExit();
|
|
167
|
+
return then;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export default async function tui(start) {
|
|
171
|
+
for (let screen = start; ; screen = "home") {
|
|
172
|
+
const then = await show(screen);
|
|
173
|
+
if (!then) return 0;
|
|
174
|
+
then();
|
|
175
|
+
console.log();
|
|
176
|
+
}
|
|
177
|
+
}
|
package/lib/update.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Keeps the binary at the version the Relay names. The Relay's GET
|
|
2
|
+
// /v1/client names the version; when it is newer than npm's, that version's
|
|
3
|
+
// platform package comes from the registry, checked against the registry's
|
|
4
|
+
// integrity, into versions/<version>/, and `current` names it. A version no
|
|
5
|
+
// newer than npm's lets npm's run. Nothing is printed; the last failure is
|
|
6
|
+
// left in update.log.
|
|
7
|
+
//
|
|
8
|
+
// `start()` runs this file as a detached process, at most once an hour: the
|
|
9
|
+
// command it was started for does not wait, the next start runs the new
|
|
10
|
+
// version. `latest()` does the same in this process, for `mcp` before each
|
|
11
|
+
// call, which switches to what it returns.
|
|
12
|
+
"use strict";
|
|
13
|
+
|
|
14
|
+
const crypto = require("crypto");
|
|
15
|
+
const fs = require("fs");
|
|
16
|
+
const path = require("path");
|
|
17
|
+
const zlib = require("zlib");
|
|
18
|
+
const { spawn } = require("child_process");
|
|
19
|
+
const binary = require("./binary.js");
|
|
20
|
+
const { version } = require("../package.json");
|
|
21
|
+
|
|
22
|
+
const { relay } = require("./distribution.json");
|
|
23
|
+
const registry = (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
|
|
24
|
+
const hour = 60 * 60 * 1000;
|
|
25
|
+
|
|
26
|
+
const off = () => Boolean(process.env.CONTEXTYA_NO_AUTO_UPDATE) || !binary.packageName();
|
|
27
|
+
|
|
28
|
+
function start() {
|
|
29
|
+
if (off()) return;
|
|
30
|
+
const checked = path.join(binary.home(), "checked");
|
|
31
|
+
try {
|
|
32
|
+
if (Date.now() - fs.statSync(checked).mtimeMs < hour) return;
|
|
33
|
+
} catch {}
|
|
34
|
+
try {
|
|
35
|
+
fs.mkdirSync(binary.home(), { recursive: true });
|
|
36
|
+
fs.writeFileSync(checked, "");
|
|
37
|
+
spawn(process.execPath, [__filename], { detached: true, stdio: "ignore", windowsHide: true }).unref();
|
|
38
|
+
} catch {}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function get(url, ms = 60000) {
|
|
42
|
+
const res = await fetch(url, {
|
|
43
|
+
headers: { "User-Agent": `Contextya/${version}` },
|
|
44
|
+
signal: AbortSignal.timeout(ms),
|
|
45
|
+
});
|
|
46
|
+
if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
|
|
47
|
+
return res;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The file `want` in a tar archive.
|
|
51
|
+
function untar(tar, want) {
|
|
52
|
+
for (let at = 0; at + 512 <= tar.length && tar[at] !== 0; ) {
|
|
53
|
+
const field = (from, to) => tar.toString("utf8", at + from, at + to).replace(/\0[\s\S]*$/, "");
|
|
54
|
+
const prefix = field(345, 500);
|
|
55
|
+
const name = (prefix ? prefix + "/" : "") + field(0, 100);
|
|
56
|
+
const size = parseInt(field(124, 136).trim(), 8);
|
|
57
|
+
if (name === want) return tar.subarray(at + 512, at + 512 + size);
|
|
58
|
+
at += 512 + Math.ceil(size / 512) * 512;
|
|
59
|
+
}
|
|
60
|
+
throw new Error(`${want} is not in the package`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Puts `v`'s binary in versions/<v>/.
|
|
64
|
+
async function install(v) {
|
|
65
|
+
const dir = path.join(binary.home(), "versions", v);
|
|
66
|
+
if (fs.existsSync(path.join(dir, binary.exe))) return;
|
|
67
|
+
const name = binary.packageName();
|
|
68
|
+
const meta = await (await get(`${registry}/${name.replace("/", "%2f")}/${v}`)).json();
|
|
69
|
+
const tgz = Buffer.from(await (await get(meta.dist.tarball)).arrayBuffer());
|
|
70
|
+
const [algorithm, digest] = meta.dist.integrity.split(/-(.*)/s);
|
|
71
|
+
if (crypto.createHash(algorithm).update(tgz).digest("base64") !== digest) {
|
|
72
|
+
throw new Error(`${name}@${v}: the download does not match the registry's integrity`);
|
|
73
|
+
}
|
|
74
|
+
const tar = zlib.gunzipSync(tgz);
|
|
75
|
+
const file = untar(tar, `package/bin/${binary.exe}`);
|
|
76
|
+
// Written beside, then renamed: a start never finds half a binary.
|
|
77
|
+
const tmp = `${dir}.${process.pid}`;
|
|
78
|
+
fs.mkdirSync(tmp, { recursive: true });
|
|
79
|
+
fs.writeFileSync(path.join(tmp, binary.exe), file, { mode: 0o755 });
|
|
80
|
+
try {
|
|
81
|
+
fs.renameSync(tmp, dir);
|
|
82
|
+
} catch (e) {
|
|
83
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
84
|
+
if (!fs.existsSync(path.join(dir, binary.exe))) throw e;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Points `current` at `v`, or at nothing; versions/ keeps it and the one before.
|
|
89
|
+
function choose(v) {
|
|
90
|
+
const current = path.join(binary.home(), "current");
|
|
91
|
+
let was = null;
|
|
92
|
+
try {
|
|
93
|
+
was = fs.readFileSync(current, "utf8").trim();
|
|
94
|
+
} catch {}
|
|
95
|
+
if (v) {
|
|
96
|
+
fs.writeFileSync(`${current}.${process.pid}`, v);
|
|
97
|
+
fs.renameSync(`${current}.${process.pid}`, current);
|
|
98
|
+
} else {
|
|
99
|
+
fs.rmSync(current, { force: true });
|
|
100
|
+
}
|
|
101
|
+
const versions = path.join(binary.home(), "versions");
|
|
102
|
+
for (const d of fs.existsSync(versions) ? fs.readdirSync(versions) : []) {
|
|
103
|
+
if (d === v || d === was) continue;
|
|
104
|
+
// A version still running on Windows cannot go: it goes next time.
|
|
105
|
+
try {
|
|
106
|
+
fs.rmSync(path.join(versions, d), { recursive: true, force: true });
|
|
107
|
+
} catch {}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function run() {
|
|
112
|
+
// `mcp` asks before every call: an unreachable Relay costs it 2 s at most.
|
|
113
|
+
const want = (await (await get(`${relay}/v1/client`, 2000)).json()).version;
|
|
114
|
+
if (!want) return;
|
|
115
|
+
if (!binary.newer(want, version)) return choose(null);
|
|
116
|
+
await install(want);
|
|
117
|
+
choose(want);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function log(e) {
|
|
121
|
+
try {
|
|
122
|
+
fs.mkdirSync(binary.home(), { recursive: true });
|
|
123
|
+
fs.writeFileSync(path.join(binary.home(), "update.log"), `${new Date().toISOString()} ${e.message}\n`);
|
|
124
|
+
} catch {}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The binary to run once versions/ is where the Relay says; null when updates
|
|
128
|
+
// are off or there is no binary.
|
|
129
|
+
async function latest() {
|
|
130
|
+
if (off()) return null;
|
|
131
|
+
await run().catch(log);
|
|
132
|
+
try {
|
|
133
|
+
return binary();
|
|
134
|
+
} catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (require.main === module) run().catch(log);
|
|
140
|
+
|
|
141
|
+
module.exports = { start, latest };
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hopetherenojs/contextya",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.4",
|
|
4
|
+
"description": "Code search for coding agents, over the directory you are in. CLI and MCP server.",
|
|
5
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/un4gt/realontext.git",
|
|
9
|
+
"directory": "client/npm/realontext"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"pi-package"
|
|
13
|
+
],
|
|
14
|
+
"bin": {
|
|
15
|
+
"contextya": "bin/realontext.js"
|
|
16
|
+
},
|
|
17
|
+
"pi": {
|
|
18
|
+
"extensions": [
|
|
19
|
+
"./pi/realontext.js"
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
".claude-plugin/",
|
|
24
|
+
"bin/realontext.js",
|
|
25
|
+
"hooks/",
|
|
26
|
+
"lib/",
|
|
27
|
+
"pi/"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=18"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"ink": "^5.2.1",
|
|
34
|
+
"react": "^18.3.1"
|
|
35
|
+
},
|
|
36
|
+
"optionalDependencies": {
|
|
37
|
+
"@hopetherenojs/contextya-darwin-arm64": "0.1.4",
|
|
38
|
+
"@hopetherenojs/contextya-linux-x64": "0.1.4",
|
|
39
|
+
"@hopetherenojs/contextya-win32-x64": "0.1.4"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/pi/realontext.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// The Pi extension. Pi has no MCP client, so this is one, for
|
|
2
|
+
// `realontext mcp` alone: it starts the server with this package's own
|
|
3
|
+
// command, registers the tools the server lists, with their names,
|
|
4
|
+
// descriptions and schemas as they are, and appends the server's
|
|
5
|
+
// instructions to the system prompt. A tool call is a `tools/call`; what the
|
|
6
|
+
// server answers goes back to the model.
|
|
7
|
+
"use strict";
|
|
8
|
+
|
|
9
|
+
const path = require("path");
|
|
10
|
+
const readline = require("readline");
|
|
11
|
+
const { spawn } = require("child_process");
|
|
12
|
+
const { Type } = require("typebox");
|
|
13
|
+
|
|
14
|
+
const BIN = path.join(__dirname, "..", "bin", "realontext.js");
|
|
15
|
+
|
|
16
|
+
// A JSON-RPC session over the server's stdio: `ask` sends a request and
|
|
17
|
+
// resolves to its result, or rejects with its error.
|
|
18
|
+
function connect() {
|
|
19
|
+
const child = spawn(process.execPath, [BIN, "mcp"], { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
|
|
20
|
+
const waiting = new Map();
|
|
21
|
+
let next = 1;
|
|
22
|
+
const fail = (e) => {
|
|
23
|
+
for (const { reject } of waiting.values()) reject(e);
|
|
24
|
+
waiting.clear();
|
|
25
|
+
};
|
|
26
|
+
child.on("error", fail);
|
|
27
|
+
child.on("exit", () => fail(new Error("realontext mcp exited")));
|
|
28
|
+
child.stdin.on("error", () => {});
|
|
29
|
+
readline.createInterface({ input: child.stdout, crlfDelay: Infinity }).on("line", (line) => {
|
|
30
|
+
let m;
|
|
31
|
+
try {
|
|
32
|
+
m = JSON.parse(line);
|
|
33
|
+
} catch {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const w = waiting.get(m.id);
|
|
37
|
+
if (!w) return;
|
|
38
|
+
waiting.delete(m.id);
|
|
39
|
+
m.error ? w.reject(new Error(m.error.message)) : w.resolve(m.result);
|
|
40
|
+
});
|
|
41
|
+
const send = (m) => child.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...m }) + "\n");
|
|
42
|
+
return {
|
|
43
|
+
ask: (method, params) =>
|
|
44
|
+
new Promise((resolve, reject) => {
|
|
45
|
+
const id = next++;
|
|
46
|
+
waiting.set(id, { resolve, reject });
|
|
47
|
+
send({ id, method, params });
|
|
48
|
+
}),
|
|
49
|
+
tell: (method, params) => send({ method, params }),
|
|
50
|
+
close: () => child.stdin.end(),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
module.exports = async function (pi) {
|
|
55
|
+
const server = connect();
|
|
56
|
+
const init = await server.ask("initialize", {
|
|
57
|
+
protocolVersion: "2025-06-18",
|
|
58
|
+
capabilities: {},
|
|
59
|
+
clientInfo: { name: "pi", version: "0" },
|
|
60
|
+
});
|
|
61
|
+
server.tell("notifications/initialized");
|
|
62
|
+
const { tools } = await server.ask("tools/list", {});
|
|
63
|
+
|
|
64
|
+
for (const tool of tools) {
|
|
65
|
+
pi.registerTool({
|
|
66
|
+
name: tool.name,
|
|
67
|
+
label: tool.title || tool.name,
|
|
68
|
+
description: tool.description,
|
|
69
|
+
parameters: Type.Unsafe(tool.inputSchema),
|
|
70
|
+
async execute(_id, params) {
|
|
71
|
+
const result = await server.ask("tools/call", { name: tool.name, arguments: params });
|
|
72
|
+
const content = result.content.filter((c) => c.type === "text");
|
|
73
|
+
if (result.isError) throw new Error(content.map((c) => c.text).join("\n"));
|
|
74
|
+
return { content, details: {} };
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (init.instructions) {
|
|
80
|
+
pi.on("before_agent_start", (event) => ({ systemPrompt: `${event.systemPrompt}\n\n${init.instructions}` }));
|
|
81
|
+
}
|
|
82
|
+
pi.on("session_shutdown", () => server.close());
|
|
83
|
+
};
|