open-notes-mcp 0.1.0
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/LICENSE +202 -0
- package/README.md +69 -0
- package/bin/open-notes-mcp.js +15 -0
- package/lib/installer.js +811 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# open-notes-mcp
|
|
2
|
+
|
|
3
|
+
[](LICENSE)
|
|
4
|
+
[](https://www.npmjs.com/package/open-notes-mcp)
|
|
5
|
+
[](https://github.com/openai/codex)
|
|
6
|
+
|
|
7
|
+
**Model agnostic notes memory solution for Codex/ChatGPT.**
|
|
8
|
+
|
|
9
|
+
## The problem
|
|
10
|
+
|
|
11
|
+
With `features.token_budget` on, Codex hard-cuts to a fresh context window
|
|
12
|
+
without summarising. Nothing survives unless the agent wrote it down — and
|
|
13
|
+
upstream's notes (`ext/history-notes`) sit behind three gates:
|
|
14
|
+
|
|
15
|
+
```rust
|
|
16
|
+
config.token_budget.use_history_notes_extension
|
|
17
|
+
&& config.model_provider.is_openai() // ← provider
|
|
18
|
+
&& auth_manager.current_auth_uses_codex_backend() // ← ApiKey => false, always
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
| you are… | native notes? |
|
|
22
|
+
|---|---|
|
|
23
|
+
| signed in with a **ChatGPT subscription** | ✅ |
|
|
24
|
+
| **API key**, OpenAI model | ⛔ |
|
|
25
|
+
| API key, **any other model provider** | ⛔ |
|
|
26
|
+
|
|
27
|
+
**Notes are a subscription feature.** This server answers the bridge Codex still
|
|
28
|
+
calls when native notes are off (`notes` / `thread_hint`), which checks
|
|
29
|
+
**neither** gate. Same cut, same injection point, no membership test.
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npx -y open-notes-mcp init # idempotent; asks before enabling token_budget
|
|
35
|
+
open-notes-mcp doctor # what is installed, active, or broken
|
|
36
|
+
open-notes-mcp uninstall # undoes its own changes — never your notes
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`init` proves itself with a real `codex exec` and a fresh `.last-hint` stamp,
|
|
40
|
+
not `codex mcp list`. Exit codes: **`0` live · `2` installed but inactive ·
|
|
41
|
+
`1` failed** — "installed" and "working" are different claims.
|
|
42
|
+
|
|
43
|
+
## The INDEX contract
|
|
44
|
+
|
|
45
|
+
With the server installed and documented, agents wrote **zero** notes. Writing
|
|
46
|
+
is behavioural, so the installer ships a contract, not just a tool:
|
|
47
|
+
|
|
48
|
+
> `INDEX.md` is a **table of contents, not a notebook** — one line per topic,
|
|
49
|
+
> detail in its own file, updated at task boundaries, under ~3,500 bytes.
|
|
50
|
+
|
|
51
|
+
The size rule matters: the hint is capped at 4,000 bytes, and what gets cut is
|
|
52
|
+
whatever was written most recently.
|
|
53
|
+
|
|
54
|
+
## Status
|
|
55
|
+
|
|
56
|
+
Pre-1.0, verified against Codex `0.148` → `0.154.0-alpha`. Our own deployment,
|
|
57
|
+
30 production agents over two days, counted as stated:
|
|
58
|
+
|
|
59
|
+
| observed | counted by |
|
|
60
|
+
|---|---|
|
|
61
|
+
| **0 → 25/30** agents writing notes | a non-hidden file in the notes dir — not tool-call counts |
|
|
62
|
+
| **25/30** had notes injected after a cut | `.last-hint` byte count `> 0` |
|
|
63
|
+
| **7/30** hit the 4,000-byte cap | `INDEX.md` grown to 4–7 KB — found and fixed |
|
|
64
|
+
|
|
65
|
+
Upstream calls the bridge *legacy*; it may vanish silently. Notes are plain files
|
|
66
|
+
an agent can re-read, so that would cost the auto-injection, not the notes.
|
|
67
|
+
Whether your agent writes *useful* notes is up to your agent.
|
|
68
|
+
|
|
69
|
+
Full contract: [docs/SPEC.md](docs/SPEC.md) · Security: [SECURITY.md](SECURITY.md) · [Apache-2.0](LICENSE)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
const { run } = require("../lib/installer");
|
|
6
|
+
|
|
7
|
+
run(process.argv.slice(2)).then(
|
|
8
|
+
(code) => {
|
|
9
|
+
process.exitCode = code;
|
|
10
|
+
},
|
|
11
|
+
(error) => {
|
|
12
|
+
process.stderr.write(`open-notes-mcp: ${error.message}\n`);
|
|
13
|
+
process.exitCode = 1;
|
|
14
|
+
},
|
|
15
|
+
);
|
package/lib/installer.js
ADDED
|
@@ -0,0 +1,811 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const childProcess = require("child_process");
|
|
4
|
+
const crypto = require("crypto");
|
|
5
|
+
const fs = require("fs");
|
|
6
|
+
const os = require("os");
|
|
7
|
+
const path = require("path");
|
|
8
|
+
|
|
9
|
+
const MCP_BEGIN = "# open-notes-mcp:mcp:begin";
|
|
10
|
+
const MCP_END = "# open-notes-mcp:mcp:end";
|
|
11
|
+
const AGENTS_BEGIN = "<!-- open-notes-mcp:begin -->";
|
|
12
|
+
const AGENTS_END = "<!-- open-notes-mcp:end -->";
|
|
13
|
+
const TOKEN_ADDED_KEY = "# open-notes-mcp:token-budget:added-key";
|
|
14
|
+
const TOKEN_ADDED_TABLE = "# open-notes-mcp:token-budget:added-table";
|
|
15
|
+
const TOKEN_CHANGED = "# open-notes-mcp:token-budget:changed:";
|
|
16
|
+
const INSTALL_STATE = "open-notes-mcp.install.json";
|
|
17
|
+
const MIN_CODEX_VERSION = Object.freeze([0, 148, 0]);
|
|
18
|
+
|
|
19
|
+
const AGENTS_BLOCK = `${AGENTS_BEGIN}
|
|
20
|
+
## Cross-window notes
|
|
21
|
+
|
|
22
|
+
Maintain cross-window memory in \`$AGENT_NOTES_DIR\` when it is set, otherwise in \`~/.agent-notes\`.
|
|
23
|
+
|
|
24
|
+
- Update \`INDEX.md\` at task boundaries: conclusions, direction changes, and completed steps. Note-taking is part of the workflow, not an escape hatch for a full context window.
|
|
25
|
+
- Keep \`INDEX.md\` as a table of contents, not a notebook. For each topic, record a filename, a one-line summary, and a pointer. Put all detail in partition files.
|
|
26
|
+
- Keep \`INDEX.md\` under about 3,500 bytes so it survives the 4,000-byte context-window hint limit.
|
|
27
|
+
- Read partition files with the notes tools when their detail is needed.
|
|
28
|
+
${AGENTS_END}`;
|
|
29
|
+
|
|
30
|
+
const PLATFORM_PACKAGES = new Map([
|
|
31
|
+
["darwin-arm64", "@open-notes-mcp/darwin-arm64"],
|
|
32
|
+
["darwin-x64", "@open-notes-mcp/darwin-x64"],
|
|
33
|
+
["linux-arm64", "@open-notes-mcp/linux-arm64"],
|
|
34
|
+
["linux-x64", "@open-notes-mcp/linux-x64"],
|
|
35
|
+
["win32-arm64", "@open-notes-mcp/win32-arm64"],
|
|
36
|
+
["win32-x64", "@open-notes-mcp/win32-x64"],
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
function usage() {
|
|
40
|
+
return `Usage: open-notes-mcp <command> [options]
|
|
41
|
+
|
|
42
|
+
Commands:
|
|
43
|
+
init [--enable-token-budget | --without-token-budget]
|
|
44
|
+
doctor
|
|
45
|
+
uninstall
|
|
46
|
+
|
|
47
|
+
init asks before enabling features.token_budget. The two flags provide an
|
|
48
|
+
explicit non-interactive answer.`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function locations(env = process.env, platform = process.platform) {
|
|
52
|
+
const home = env.HOME || env.USERPROFILE || os.homedir();
|
|
53
|
+
const codexHome = env.CODEX_HOME || path.join(home, ".codex");
|
|
54
|
+
let dataHome;
|
|
55
|
+
if (platform === "win32") {
|
|
56
|
+
dataHome = env.LOCALAPPDATA || path.join(home, "AppData", "Local");
|
|
57
|
+
} else {
|
|
58
|
+
dataHome = env.XDG_DATA_HOME || path.join(home, ".local", "share");
|
|
59
|
+
}
|
|
60
|
+
const installRoot = path.join(dataHome, "open-notes-mcp");
|
|
61
|
+
return {
|
|
62
|
+
home,
|
|
63
|
+
codexHome,
|
|
64
|
+
configPath: path.join(codexHome, "config.toml"),
|
|
65
|
+
statePath: path.join(codexHome, INSTALL_STATE),
|
|
66
|
+
agentsPath: path.join(codexHome, "AGENTS.md"),
|
|
67
|
+
agentsOverridePath: path.join(codexHome, "AGENTS.override.md"),
|
|
68
|
+
notesRoot: env.AGENT_NOTES_DIR || path.join(home, ".agent-notes"),
|
|
69
|
+
installRoot,
|
|
70
|
+
binaryPath: path.join(installRoot, "bin", platform === "win32" ? "notes-mcp.exe" : "notes-mcp"),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function countOccurrences(text, marker) {
|
|
75
|
+
let count = 0;
|
|
76
|
+
let offset = 0;
|
|
77
|
+
while ((offset = text.indexOf(marker, offset)) !== -1) {
|
|
78
|
+
count += 1;
|
|
79
|
+
offset += marker.length;
|
|
80
|
+
}
|
|
81
|
+
return count;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function managedBlockRange(text, begin, end, label) {
|
|
85
|
+
const beginCount = countOccurrences(text, begin);
|
|
86
|
+
const endCount = countOccurrences(text, end);
|
|
87
|
+
if (beginCount === 0 && endCount === 0) return null;
|
|
88
|
+
if (beginCount !== 1 || endCount !== 1) {
|
|
89
|
+
throw new Error(`${label} has duplicate or unmatched managed sentinels`);
|
|
90
|
+
}
|
|
91
|
+
const start = text.indexOf(begin);
|
|
92
|
+
const endStart = text.indexOf(end);
|
|
93
|
+
if (endStart < start) throw new Error(`${label} managed sentinels are out of order`);
|
|
94
|
+
let finish = endStart + end.length;
|
|
95
|
+
if (text.slice(finish, finish + 2) === "\r\n") finish += 2;
|
|
96
|
+
else if (text[finish] === "\n") finish += 1;
|
|
97
|
+
return { start, finish };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function appendBlock(text, block) {
|
|
101
|
+
const newline = text.includes("\r\n") ? "\r\n" : "\n";
|
|
102
|
+
const normalizedBlock = newline === "\r\n" ? block.replace(/\n/g, "\r\n") : block;
|
|
103
|
+
if (text.length === 0) return `${normalizedBlock}${newline}`;
|
|
104
|
+
if (text.endsWith(`${newline}${newline}`)) return `${text}${normalizedBlock}${newline}`;
|
|
105
|
+
if (text.endsWith(newline)) return `${text}${newline}${normalizedBlock}${newline}`;
|
|
106
|
+
return `${text}${newline}${newline}${normalizedBlock}${newline}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function upsertManagedBlock(text, begin, end, block, label) {
|
|
110
|
+
const range = managedBlockRange(text, begin, end, label);
|
|
111
|
+
if (!range) return appendBlock(text, block);
|
|
112
|
+
const newline = text.includes("\r\n") ? "\r\n" : "\n";
|
|
113
|
+
const normalizedBlock = newline === "\r\n" ? block.replace(/\n/g, "\r\n") : block;
|
|
114
|
+
return `${text.slice(0, range.start)}${normalizedBlock}${newline}${text.slice(range.finish)}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function removeManagedBlock(text, begin, end, label) {
|
|
118
|
+
const range = managedBlockRange(text, begin, end, label);
|
|
119
|
+
if (!range) return text;
|
|
120
|
+
let start = range.start;
|
|
121
|
+
if (start >= 4 && text.slice(start - 4, start) === "\r\n\r\n") start -= 2;
|
|
122
|
+
else if (start >= 2 && text.slice(start - 2, start) === "\n\n") start -= 1;
|
|
123
|
+
return `${text.slice(0, start)}${text.slice(range.finish)}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function tomlString(value) {
|
|
127
|
+
return JSON.stringify(value);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function mcpBlock(binaryPath) {
|
|
131
|
+
return `${MCP_BEGIN}\n[mcp_servers.notes]\ncommand = ${tomlString(binaryPath)}\n${MCP_END}`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function mcpServerEntry(config) {
|
|
135
|
+
const { lines } = splitLines(config);
|
|
136
|
+
let start = -1;
|
|
137
|
+
let end = lines.length;
|
|
138
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
139
|
+
if (/^\s*\[\s*mcp_servers\s*\.\s*(?:notes|"notes"|'notes')\s*\]\s*(?:#.*)?$/.test(lines[index])) {
|
|
140
|
+
if (start !== -1) throw new Error("Codex config defines mcp_servers.notes more than once");
|
|
141
|
+
start = index;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (start !== -1 && /^\s*\[/.test(lines[index])) {
|
|
145
|
+
end = index;
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (start === -1) return null;
|
|
150
|
+
let command = null;
|
|
151
|
+
for (const line of lines.slice(start + 1, end)) {
|
|
152
|
+
const match = line.match(/^\s*command\s*=\s*("(?:\\.|[^"\\])*")\s*(?:#.*)?$/);
|
|
153
|
+
if (match) {
|
|
154
|
+
try {
|
|
155
|
+
command = JSON.parse(match[1]);
|
|
156
|
+
} catch {
|
|
157
|
+
command = null;
|
|
158
|
+
}
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return { start, end, command };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function hasUnmanagedNotesServer(config) {
|
|
166
|
+
const withoutManaged = removeManagedBlock(config, MCP_BEGIN, MCP_END, "Codex config");
|
|
167
|
+
return mcpServerEntry(withoutManaged) !== null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function splitLines(text) {
|
|
171
|
+
const newline = text.includes("\r\n") ? "\r\n" : "\n";
|
|
172
|
+
return { lines: text.replace(/\r\n/g, "\n").split("\n"), newline };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function tokenBudgetEntry(config) {
|
|
176
|
+
const { lines } = splitLines(config);
|
|
177
|
+
let table = "";
|
|
178
|
+
const entries = [];
|
|
179
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
180
|
+
const line = lines[index];
|
|
181
|
+
const tableMatch = line.match(/^\s*\[\s*([^\]]+?)\s*\]\s*(?:#.*)?$/);
|
|
182
|
+
if (tableMatch) {
|
|
183
|
+
table = tableMatch[1].trim().replace(/^["']|["']$/g, "");
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
let match;
|
|
187
|
+
let installedLine;
|
|
188
|
+
if (table === "features") {
|
|
189
|
+
match = line.match(/^(\s*)token_budget\s*=\s*(true|false)\s*(?:#.*)?$/);
|
|
190
|
+
if (match) installedLine = `${match[1]}token_budget = true`;
|
|
191
|
+
} else if (table === "") {
|
|
192
|
+
match = line.match(/^(\s*)features\s*\.\s*token_budget\s*=\s*(true|false)\s*(?:#.*)?$/);
|
|
193
|
+
if (match) installedLine = `${match[1]}features.token_budget = true`;
|
|
194
|
+
}
|
|
195
|
+
if (match) entries.push({
|
|
196
|
+
index,
|
|
197
|
+
value: match[2] === "true",
|
|
198
|
+
line,
|
|
199
|
+
installedLine,
|
|
200
|
+
kind: table === "features" ? "table" : "dotted",
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
if (entries.length > 1) throw new Error("Codex config defines features.token_budget more than once");
|
|
204
|
+
return entries[0] || null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function enableTokenBudget(config) {
|
|
208
|
+
const current = tokenBudgetEntry(config);
|
|
209
|
+
if (current?.value) return config;
|
|
210
|
+
const { lines, newline } = splitLines(config);
|
|
211
|
+
if (current) {
|
|
212
|
+
const encoded = Buffer.from(current.line, "utf8").toString("base64url");
|
|
213
|
+
lines.splice(current.index, 1, `${TOKEN_CHANGED}${encoded}`, current.installedLine);
|
|
214
|
+
return lines.join(newline);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const featuresIndex = lines.findIndex((line) => /^\s*\[\s*["']?features["']?\s*\]\s*(?:#.*)?$/.test(line));
|
|
218
|
+
if (featuresIndex !== -1) {
|
|
219
|
+
lines.splice(featuresIndex + 1, 0, TOKEN_ADDED_KEY, "token_budget = true");
|
|
220
|
+
return lines.join(newline);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let result = config;
|
|
224
|
+
const block = `[features]\n${TOKEN_ADDED_TABLE}\ntoken_budget = true`;
|
|
225
|
+
result = appendBlock(result, block);
|
|
226
|
+
return result;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function removeManagedTokenBudget(config) {
|
|
230
|
+
const { lines, newline } = splitLines(config);
|
|
231
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
232
|
+
const line = lines[index];
|
|
233
|
+
if (line === TOKEN_ADDED_KEY) {
|
|
234
|
+
if (lines[index + 1] === "token_budget = true") {
|
|
235
|
+
lines.splice(index, 2);
|
|
236
|
+
} else {
|
|
237
|
+
lines.splice(index, 1);
|
|
238
|
+
}
|
|
239
|
+
return lines.join(newline);
|
|
240
|
+
}
|
|
241
|
+
if (line === TOKEN_ADDED_TABLE) {
|
|
242
|
+
const headerIndex = index - 1;
|
|
243
|
+
const expectedHeader = /^\s*\[\s*["']?features["']?\s*\]\s*(?:#.*)?$/.test(lines[headerIndex] || "");
|
|
244
|
+
const expectedValue = lines[index + 1] === "token_budget = true";
|
|
245
|
+
let nextTable = index + 2;
|
|
246
|
+
while (nextTable < lines.length && !/^\s*\[/.test(lines[nextTable])) nextTable += 1;
|
|
247
|
+
const extra = lines.slice(index + 2, nextTable).some((candidate) => candidate.trim() && !candidate.trim().startsWith("#"));
|
|
248
|
+
if (expectedHeader && expectedValue && !extra) {
|
|
249
|
+
let removeCount = 3;
|
|
250
|
+
if (lines[index + 2] === "") removeCount += 1;
|
|
251
|
+
lines.splice(headerIndex, removeCount);
|
|
252
|
+
} else {
|
|
253
|
+
lines.splice(index, expectedValue ? 2 : 1);
|
|
254
|
+
}
|
|
255
|
+
return lines.join(newline);
|
|
256
|
+
}
|
|
257
|
+
if (line.startsWith(TOKEN_CHANGED)) {
|
|
258
|
+
const encoded = line.slice(TOKEN_CHANGED.length);
|
|
259
|
+
let original;
|
|
260
|
+
try {
|
|
261
|
+
original = Buffer.from(encoded, "base64url").toString("utf8");
|
|
262
|
+
} catch {
|
|
263
|
+
original = "";
|
|
264
|
+
}
|
|
265
|
+
if (!original) throw new Error("Codex config has an invalid token-budget ownership marker");
|
|
266
|
+
const tableMatch = original.match(/^(\s*)token_budget\s*=\s*false\s*(?:#.*)?$/);
|
|
267
|
+
const dottedMatch = original.match(/^(\s*)features\s*\.\s*token_budget\s*=\s*false\s*(?:#.*)?$/);
|
|
268
|
+
if (!tableMatch && !dottedMatch) throw new Error("Codex config has an invalid token-budget ownership marker");
|
|
269
|
+
const installedLine = tableMatch
|
|
270
|
+
? `${tableMatch[1]}token_budget = true`
|
|
271
|
+
: `${dottedMatch[1]}features.token_budget = true`;
|
|
272
|
+
if (lines[index + 1] === installedLine) {
|
|
273
|
+
lines.splice(index, 2, original);
|
|
274
|
+
} else {
|
|
275
|
+
lines.splice(index, 1);
|
|
276
|
+
}
|
|
277
|
+
return lines.join(newline);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return config;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function readFileOrEmpty(file) {
|
|
284
|
+
try {
|
|
285
|
+
return fs.readFileSync(file, "utf8");
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (error.code === "ENOENT") return "";
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function readInstallState(file) {
|
|
293
|
+
try {
|
|
294
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
295
|
+
if (!parsed || parsed.version !== 1 || !parsed.tokenBudget || typeof parsed.mcpCommand !== "string") {
|
|
296
|
+
throw new Error("invalid install state");
|
|
297
|
+
}
|
|
298
|
+
return parsed;
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.code === "ENOENT") return null;
|
|
301
|
+
if (error instanceof SyntaxError || error.message === "invalid install state") {
|
|
302
|
+
throw new Error(`invalid ${INSTALL_STATE}: ${error.message}`);
|
|
303
|
+
}
|
|
304
|
+
throw error;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function writeInstallState(file, state) {
|
|
309
|
+
atomicWrite(file, `${JSON.stringify(state, null, 2)}\n`, 0o600);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function removeFileIfPresent(file) {
|
|
313
|
+
try {
|
|
314
|
+
fs.unlinkSync(file);
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (error.code !== "ENOENT") throw error;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function atomicWrite(file, content, newMode) {
|
|
321
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
322
|
+
let mode = newMode;
|
|
323
|
+
try {
|
|
324
|
+
mode = fs.statSync(file).mode & 0o777;
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (error.code !== "ENOENT") throw error;
|
|
327
|
+
}
|
|
328
|
+
const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
329
|
+
try {
|
|
330
|
+
fs.writeFileSync(temp, content, { mode, flag: "wx" });
|
|
331
|
+
fs.renameSync(temp, file);
|
|
332
|
+
} finally {
|
|
333
|
+
try {
|
|
334
|
+
fs.unlinkSync(temp);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (error.code !== "ENOENT") throw error;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function copyBinary(source, destination) {
|
|
342
|
+
const bytes = fs.readFileSync(source);
|
|
343
|
+
let unchanged = false;
|
|
344
|
+
try {
|
|
345
|
+
const current = fs.readFileSync(destination);
|
|
346
|
+
unchanged = current.equals(bytes);
|
|
347
|
+
} catch (error) {
|
|
348
|
+
if (error.code !== "ENOENT") throw error;
|
|
349
|
+
}
|
|
350
|
+
if (!unchanged) atomicWrite(destination, bytes, 0o755);
|
|
351
|
+
fs.chmodSync(destination, 0o755);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function resolveNativeBinary(env = process.env, platform = process.platform, arch = process.arch) {
|
|
355
|
+
if (env.OPEN_NOTES_MCP_BINARY) return path.resolve(env.OPEN_NOTES_MCP_BINARY);
|
|
356
|
+
const key = `${platform}-${arch}`;
|
|
357
|
+
const packageName = PLATFORM_PACKAGES.get(key);
|
|
358
|
+
if (!packageName) throw new Error(`unsupported platform ${key}`);
|
|
359
|
+
let manifest;
|
|
360
|
+
try {
|
|
361
|
+
manifest = require.resolve(`${packageName}/package.json`, { paths: [__dirname] });
|
|
362
|
+
} catch {
|
|
363
|
+
throw new Error(`native package ${packageName} is missing; reinstall open-notes-mcp with optional dependencies enabled`);
|
|
364
|
+
}
|
|
365
|
+
return path.join(path.dirname(manifest), "bin", platform === "win32" ? "notes-mcp.exe" : "notes-mcp");
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function codexCommand(env = process.env) {
|
|
369
|
+
return env.OPEN_NOTES_MCP_CODEX_BIN || "codex";
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function codexVersion(env = process.env) {
|
|
373
|
+
const result = childProcess.spawnSync(codexCommand(env), ["--version"], {
|
|
374
|
+
env,
|
|
375
|
+
encoding: "utf8",
|
|
376
|
+
timeout: 5000,
|
|
377
|
+
});
|
|
378
|
+
if (result.error?.code === "ENOENT") return { ok: false, missing: true, supported: false, detail: "Codex CLI not found on PATH" };
|
|
379
|
+
if (result.error) return { ok: false, missing: false, supported: false, detail: result.error.message };
|
|
380
|
+
if (result.status !== 0) return { ok: false, missing: false, supported: false, detail: (result.stderr || result.stdout || `exit ${result.status}`).trim() };
|
|
381
|
+
const detail = [result.stdout, result.stderr].filter(Boolean).join(" ").trim();
|
|
382
|
+
const match = detail.match(/\b(\d+)\.(\d+)(?:\.(\d+))?/);
|
|
383
|
+
if (!match) return { ok: false, missing: false, supported: false, detail: `unable to parse Codex version from: ${detail || "(empty output)"}` };
|
|
384
|
+
const version = [Number(match[1]), Number(match[2]), Number(match[3] || 0)];
|
|
385
|
+
const supported = version[0] > MIN_CODEX_VERSION[0]
|
|
386
|
+
|| (version[0] === MIN_CODEX_VERSION[0] && (version[1] > MIN_CODEX_VERSION[1]
|
|
387
|
+
|| (version[1] === MIN_CODEX_VERSION[1] && version[2] >= MIN_CODEX_VERSION[2])));
|
|
388
|
+
return {
|
|
389
|
+
ok: supported,
|
|
390
|
+
missing: false,
|
|
391
|
+
supported,
|
|
392
|
+
version,
|
|
393
|
+
detail: supported ? detail : `Codex ${detail} is too old; requires >= 0.148.0`,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function readConsent() {
|
|
398
|
+
process.stderr.write("Enable features.token_budget? This opts Codex into hard context-window cuts and activates automatic notes hints. [y/N] ");
|
|
399
|
+
const buffer = Buffer.alloc(1);
|
|
400
|
+
let answer = "";
|
|
401
|
+
try {
|
|
402
|
+
while (fs.readSync(0, buffer, 0, 1, null) === 1) {
|
|
403
|
+
const character = buffer.toString("utf8");
|
|
404
|
+
if (character === "\n" || character === "\r") break;
|
|
405
|
+
answer += character;
|
|
406
|
+
}
|
|
407
|
+
} catch (error) {
|
|
408
|
+
if (error.code !== "EAGAIN") throw error;
|
|
409
|
+
}
|
|
410
|
+
return /^(?:y|yes)$/i.test(answer.trim());
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function parseInitOptions(args) {
|
|
414
|
+
let tokenChoice = null;
|
|
415
|
+
for (const arg of args) {
|
|
416
|
+
if (arg === "--enable-token-budget") {
|
|
417
|
+
if (tokenChoice === false) throw new Error("token-budget options are mutually exclusive");
|
|
418
|
+
tokenChoice = true;
|
|
419
|
+
} else if (arg === "--without-token-budget") {
|
|
420
|
+
if (tokenChoice === true) throw new Error("token-budget options are mutually exclusive");
|
|
421
|
+
tokenChoice = false;
|
|
422
|
+
} else {
|
|
423
|
+
throw new Error(`unknown init option: ${arg}`);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return tokenChoice;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function runCodex(args, env = process.env) {
|
|
430
|
+
return childProcess.spawnSync(codexCommand(env), args, {
|
|
431
|
+
env,
|
|
432
|
+
encoding: "utf8",
|
|
433
|
+
timeout: 10000,
|
|
434
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function codexMcpAdd(binaryPath, env = process.env) {
|
|
439
|
+
const result = runCodex(["mcp", "add", "notes", "--", binaryPath], env);
|
|
440
|
+
if (result.error || result.status !== 0) {
|
|
441
|
+
throw new Error(`Codex MCP registration failed: ${result.error?.message || (result.stderr || result.stdout || `exit ${result.status}`).trim()}`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function codexMcpRemove(env = process.env) {
|
|
446
|
+
const result = runCodex(["mcp", "remove", "notes"], env);
|
|
447
|
+
if (result.error || result.status !== 0) {
|
|
448
|
+
throw new Error(`Codex MCP removal failed: ${result.error?.message || (result.stderr || result.stdout || `exit ${result.status}`).trim()}`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function restoreFile(file, existed, content) {
|
|
453
|
+
if (existed) atomicWrite(file, content, 0o600);
|
|
454
|
+
else removeFileIfPresent(file);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function prepareInit(loc, binaryPath, tokenChoice, state) {
|
|
458
|
+
const config = readFileOrEmpty(loc.configPath);
|
|
459
|
+
const agentsFiles = [loc.agentsPath, loc.agentsOverridePath].map((file) => ({
|
|
460
|
+
file,
|
|
461
|
+
content: readFileOrEmpty(file),
|
|
462
|
+
}));
|
|
463
|
+
const existingMcp = mcpServerEntry(config);
|
|
464
|
+
if (existingMcp && (!state || existingMcp.command !== state.mcpCommand)) {
|
|
465
|
+
throw new Error("Codex config already has an unmanaged [mcp_servers.notes] table; remove or rename it before init");
|
|
466
|
+
}
|
|
467
|
+
for (const entry of agentsFiles) {
|
|
468
|
+
managedBlockRange(entry.content, AGENTS_BEGIN, AGENTS_END, path.basename(entry.file));
|
|
469
|
+
}
|
|
470
|
+
const activeAgentsPath = agentsFiles[1].content.trim() ? loc.agentsOverridePath : loc.agentsPath;
|
|
471
|
+
|
|
472
|
+
const currentToken = tokenBudgetEntry(config);
|
|
473
|
+
let enableToken = currentToken?.value === true;
|
|
474
|
+
if (!enableToken) enableToken = tokenChoice === null ? readConsent() : tokenChoice;
|
|
475
|
+
|
|
476
|
+
let nextConfig = config;
|
|
477
|
+
if (enableToken && !currentToken?.value) nextConfig = enableTokenBudget(nextConfig);
|
|
478
|
+
const agentsUpdates = agentsFiles.map((entry) => ({
|
|
479
|
+
...entry,
|
|
480
|
+
next: entry.file === activeAgentsPath
|
|
481
|
+
? upsertManagedBlock(entry.content, AGENTS_BEGIN, AGENTS_END, AGENTS_BLOCK, path.basename(entry.file))
|
|
482
|
+
: removeManagedBlock(entry.content, AGENTS_BEGIN, AGENTS_END, path.basename(entry.file)),
|
|
483
|
+
}));
|
|
484
|
+
const originalToken = state?.tokenBudget || {
|
|
485
|
+
present: Boolean(currentToken),
|
|
486
|
+
value: currentToken ? currentToken.value : null,
|
|
487
|
+
kind: currentToken?.kind || null,
|
|
488
|
+
line: currentToken?.line || null,
|
|
489
|
+
};
|
|
490
|
+
return {
|
|
491
|
+
config,
|
|
492
|
+
nextConfig,
|
|
493
|
+
agentsUpdates,
|
|
494
|
+
activeAgentsPath,
|
|
495
|
+
tokenEnabled: enableToken,
|
|
496
|
+
existingMcp,
|
|
497
|
+
originalToken,
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function init(args, io = console, env = process.env) {
|
|
502
|
+
const tokenChoice = parseInitOptions(args);
|
|
503
|
+
const loc = locations(env);
|
|
504
|
+
const version = codexVersion(env);
|
|
505
|
+
if (!version.ok) throw new Error(version.detail);
|
|
506
|
+
const nativeBinary = resolveNativeBinary(env);
|
|
507
|
+
const state = readInstallState(loc.statePath);
|
|
508
|
+
const prepared = prepareInit(loc, loc.binaryPath, tokenChoice, state);
|
|
509
|
+
const codexHomeExisted = fs.existsSync(loc.codexHome);
|
|
510
|
+
const configExisted = fs.existsSync(loc.configPath);
|
|
511
|
+
const stateExisted = fs.existsSync(loc.statePath);
|
|
512
|
+
const originalAgents = prepared.agentsUpdates.map((entry) => ({ file: entry.file, existed: fs.existsSync(entry.file), content: entry.content }));
|
|
513
|
+
|
|
514
|
+
fs.mkdirSync(loc.codexHome, { recursive: true, mode: 0o700 });
|
|
515
|
+
copyBinary(nativeBinary, loc.binaryPath);
|
|
516
|
+
try {
|
|
517
|
+
if (prepared.nextConfig !== prepared.config) atomicWrite(loc.configPath, prepared.nextConfig, 0o600);
|
|
518
|
+
if (!prepared.existingMcp) {
|
|
519
|
+
codexMcpAdd(loc.binaryPath, env);
|
|
520
|
+
const registered = mcpServerEntry(readFileOrEmpty(loc.configPath));
|
|
521
|
+
if (!registered || registered.command !== loc.binaryPath) {
|
|
522
|
+
throw new Error("Codex MCP registration did not produce the expected notes server entry");
|
|
523
|
+
}
|
|
524
|
+
} else if (prepared.existingMcp.command !== loc.binaryPath) {
|
|
525
|
+
throw new Error("existing notes MCP entry points at a different binary");
|
|
526
|
+
}
|
|
527
|
+
for (const entry of prepared.agentsUpdates) {
|
|
528
|
+
if (entry.next !== entry.content) atomicWrite(entry.file, entry.next, 0o644);
|
|
529
|
+
}
|
|
530
|
+
writeInstallState(loc.statePath, {
|
|
531
|
+
version: 1,
|
|
532
|
+
mcpCommand: loc.binaryPath,
|
|
533
|
+
binaryPath: loc.binaryPath,
|
|
534
|
+
agentsPath: prepared.activeAgentsPath,
|
|
535
|
+
tokenBudget: prepared.originalToken,
|
|
536
|
+
activated: prepared.tokenEnabled,
|
|
537
|
+
});
|
|
538
|
+
} catch (error) {
|
|
539
|
+
restoreFile(loc.configPath, configExisted, prepared.config);
|
|
540
|
+
for (const entry of originalAgents) restoreFile(entry.file, entry.existed, entry.content);
|
|
541
|
+
if (!stateExisted) removeFileIfPresent(loc.statePath);
|
|
542
|
+
removeFileIfPresent(loc.binaryPath);
|
|
543
|
+
for (const directory of [path.dirname(loc.binaryPath), loc.installRoot, !codexHomeExisted ? loc.codexHome : null]) {
|
|
544
|
+
if (!directory) continue;
|
|
545
|
+
try {
|
|
546
|
+
fs.rmdirSync(directory);
|
|
547
|
+
} catch (cleanupError) {
|
|
548
|
+
if (!['ENOENT', 'ENOTEMPTY'].includes(cleanupError.code)) throw cleanupError;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
throw error;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
io.log(`installed notes MCP binary: ${loc.binaryPath}`);
|
|
555
|
+
io.log(`configured Codex via codex mcp add: ${loc.configPath}`);
|
|
556
|
+
io.log(`installed notes workflow block: ${prepared.activeAgentsPath}`);
|
|
557
|
+
if (!prepared.tokenEnabled) {
|
|
558
|
+
io.log("features.token_budget: disabled by your choice; automatic hints will not be injected");
|
|
559
|
+
io.log("To enable later: npx open-notes-mcp init --enable-token-budget");
|
|
560
|
+
return 2;
|
|
561
|
+
}
|
|
562
|
+
io.log("features.token_budget: enabled");
|
|
563
|
+
const live = livenessProbe(loc, env);
|
|
564
|
+
if (!live.ok) {
|
|
565
|
+
io.error?.(`FAIL liveness: ${live.detail}`);
|
|
566
|
+
return 1;
|
|
567
|
+
}
|
|
568
|
+
io.log(`PASS liveness: ${live.detail}`);
|
|
569
|
+
return 0;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function binaryHandshake(binaryPath, notesRoot, env = process.env) {
|
|
573
|
+
const started = process.hrtime.bigint();
|
|
574
|
+
const input = `${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })}\n`;
|
|
575
|
+
const result = childProcess.spawnSync(binaryPath, [], {
|
|
576
|
+
input,
|
|
577
|
+
env: { ...env, AGENT_NOTES_DIR: notesRoot },
|
|
578
|
+
encoding: "utf8",
|
|
579
|
+
timeout: 2000,
|
|
580
|
+
maxBuffer: 1024 * 1024,
|
|
581
|
+
});
|
|
582
|
+
const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;
|
|
583
|
+
if (result.error) return { ok: false, detail: result.error.message, elapsedMs };
|
|
584
|
+
if (result.status !== 0) return { ok: false, detail: (result.stderr || `exit ${result.status}`).trim(), elapsedMs };
|
|
585
|
+
try {
|
|
586
|
+
const response = JSON.parse(result.stdout.trim());
|
|
587
|
+
const ok = response?.result?.serverInfo?.name === "notes" && elapsedMs < 200;
|
|
588
|
+
return { ok, detail: ok ? `${elapsedMs.toFixed(1)}ms` : `unexpected initialize response (${elapsedMs.toFixed(1)}ms)`, elapsedMs };
|
|
589
|
+
} catch (error) {
|
|
590
|
+
return { ok: false, detail: `invalid initialize response: ${error.message}`, elapsedMs };
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function livenessProbe(loc, env = process.env) {
|
|
595
|
+
const stampPath = path.join(loc.notesRoot, ".last-hint");
|
|
596
|
+
let before = null;
|
|
597
|
+
try {
|
|
598
|
+
before = fs.readFileSync(stampPath, "utf8");
|
|
599
|
+
} catch (error) {
|
|
600
|
+
if (error.code !== "ENOENT") return { ok: false, detail: error.message };
|
|
601
|
+
}
|
|
602
|
+
const started = Date.now();
|
|
603
|
+
const provider = "open_notes_mcp_doctor";
|
|
604
|
+
const args = [
|
|
605
|
+
"exec",
|
|
606
|
+
"--skip-git-repo-check",
|
|
607
|
+
"--ephemeral",
|
|
608
|
+
"--color", "never",
|
|
609
|
+
"-c", `model_provider=${tomlString(provider)}`,
|
|
610
|
+
"-c", `model_providers.${provider}.name=${tomlString("open-notes-mcp doctor")}`,
|
|
611
|
+
"-c", `model_providers.${provider}.base_url=${tomlString("http://127.0.0.1:9/v1")}`,
|
|
612
|
+
"-c", `model_providers.${provider}.env_key=${tomlString("OPENAI_API_KEY")}`,
|
|
613
|
+
"-c", `model_providers.${provider}.wire_api=${tomlString("responses")}`,
|
|
614
|
+
"-c", `model_providers.${provider}.request_max_retries=0`,
|
|
615
|
+
"-c", `model_providers.${provider}.stream_max_retries=0`,
|
|
616
|
+
"Reply with OK.",
|
|
617
|
+
];
|
|
618
|
+
childProcess.spawnSync(codexCommand(env), args, {
|
|
619
|
+
cwd: os.tmpdir(),
|
|
620
|
+
env: { ...env, OPENAI_API_KEY: "open-notes-mcp-doctor-placeholder" },
|
|
621
|
+
encoding: "utf8",
|
|
622
|
+
timeout: 8000,
|
|
623
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
try {
|
|
627
|
+
const after = fs.readFileSync(stampPath, "utf8");
|
|
628
|
+
const stat = fs.statSync(stampPath);
|
|
629
|
+
const valid = /^last_thread_hint=\S+ thread_id=[0-9a-f-]+ bytes=\d+\n?$/.test(after);
|
|
630
|
+
const fresh = after !== before && stat.mtimeMs >= started - 1000;
|
|
631
|
+
return { ok: valid && fresh, detail: valid && fresh ? `fresh stamp at ${stampPath}` : "codex exec did not produce a fresh valid .last-hint" };
|
|
632
|
+
} catch (error) {
|
|
633
|
+
return { ok: false, detail: `codex exec did not create ${stampPath}: ${error.message}` };
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function doctor(_args, io = console, env = process.env) {
|
|
638
|
+
const loc = locations(env);
|
|
639
|
+
let failed = false;
|
|
640
|
+
let inactive = false;
|
|
641
|
+
const report = (kind, label, detail) => {
|
|
642
|
+
io.log(`${kind} ${label}: ${detail}`);
|
|
643
|
+
if (kind === "FAIL") failed = true;
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
const version = codexVersion(env);
|
|
647
|
+
if (version.ok) report("PASS", "codex", version.detail);
|
|
648
|
+
else report("FAIL", "codex", version.detail);
|
|
649
|
+
|
|
650
|
+
const config = readFileOrEmpty(loc.configPath);
|
|
651
|
+
const state = (() => {
|
|
652
|
+
try {
|
|
653
|
+
return readInstallState(loc.statePath);
|
|
654
|
+
} catch (error) {
|
|
655
|
+
report("FAIL", "install state", error.message);
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
658
|
+
})();
|
|
659
|
+
try {
|
|
660
|
+
const entry = mcpServerEntry(config);
|
|
661
|
+
const matches = Boolean(state && entry && entry.command === state.mcpCommand && entry.command === loc.binaryPath);
|
|
662
|
+
report(matches ? "PASS" : "FAIL", "config", matches ? "notes server registered by codex mcp add" : entry ? "notes server entry differs from this installation" : "notes server entry is missing");
|
|
663
|
+
} catch (error) {
|
|
664
|
+
report("FAIL", "config", error.message);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const agentsFiles = [loc.agentsPath, loc.agentsOverridePath].map((file) => ({
|
|
668
|
+
file,
|
|
669
|
+
content: readFileOrEmpty(file),
|
|
670
|
+
}));
|
|
671
|
+
try {
|
|
672
|
+
const ranges = agentsFiles.map((entry) => managedBlockRange(entry.content, AGENTS_BEGIN, AGENTS_END, path.basename(entry.file)));
|
|
673
|
+
const activeIndex = agentsFiles[1].content.trim() ? 1 : 0;
|
|
674
|
+
const range = ranges[activeIndex];
|
|
675
|
+
const matches = ranges.filter(Boolean).length === 1
|
|
676
|
+
&& range
|
|
677
|
+
&& agentsFiles[activeIndex].content.slice(range.start, range.finish).replace(/\r\n/g, "\n").trimEnd() === AGENTS_BLOCK;
|
|
678
|
+
report(matches ? "PASS" : "FAIL", "AGENTS.md", matches ? `managed workflow block in ${path.basename(agentsFiles[activeIndex].file)}` : "managed block is missing, duplicated, inactive, or differs from this release");
|
|
679
|
+
} catch (error) {
|
|
680
|
+
report("FAIL", "AGENTS.md", error.message);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
try {
|
|
684
|
+
const token = tokenBudgetEntry(config);
|
|
685
|
+
if (token?.value) report("PASS", "token budget", "enabled");
|
|
686
|
+
else {
|
|
687
|
+
inactive = true;
|
|
688
|
+
report("WARN", "token budget", "installed but inactive; automatic hints will not be injected");
|
|
689
|
+
io.log("To enable later: npx open-notes-mcp init --enable-token-budget");
|
|
690
|
+
}
|
|
691
|
+
} catch (error) {
|
|
692
|
+
report("FAIL", "token budget", error.message);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const handshake = binaryHandshake(loc.binaryPath, loc.notesRoot, env);
|
|
696
|
+
report(handshake.ok ? "PASS" : "FAIL", "binary initialize", handshake.detail);
|
|
697
|
+
|
|
698
|
+
if (!version.ok) {
|
|
699
|
+
io.log(`SKIP liveness: ${version.detail}`);
|
|
700
|
+
failed = true;
|
|
701
|
+
} else if (inactive) {
|
|
702
|
+
io.log("SKIP liveness: token_budget is disabled by user choice");
|
|
703
|
+
} else if (!handshake.ok) {
|
|
704
|
+
io.log("SKIP liveness: installed binary failed initialize");
|
|
705
|
+
failed = true;
|
|
706
|
+
} else {
|
|
707
|
+
const live = livenessProbe(loc, env);
|
|
708
|
+
report(live.ok ? "PASS" : "FAIL", "liveness", live.detail);
|
|
709
|
+
}
|
|
710
|
+
return failed ? 1 : inactive ? 2 : 0;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function removeMcpServerTable(config) {
|
|
714
|
+
const entry = mcpServerEntry(config);
|
|
715
|
+
if (!entry) return config;
|
|
716
|
+
const { lines, newline } = splitLines(config);
|
|
717
|
+
let start = entry.start;
|
|
718
|
+
let end = entry.end;
|
|
719
|
+
if (start > 0 && lines[start - 1] === "") start -= 1;
|
|
720
|
+
if (end < lines.length && lines[end] === "") end += 1;
|
|
721
|
+
lines.splice(start, end - start);
|
|
722
|
+
return lines.join(newline);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function uninstall(args, io = console, env = process.env) {
|
|
726
|
+
if (args.length) throw new Error(`unknown uninstall option: ${args[0]}`);
|
|
727
|
+
const loc = locations(env);
|
|
728
|
+
const state = readInstallState(loc.statePath);
|
|
729
|
+
const config = readFileOrEmpty(loc.configPath);
|
|
730
|
+
const agentsFiles = [loc.agentsPath, loc.agentsOverridePath].map((file) => ({
|
|
731
|
+
file,
|
|
732
|
+
content: readFileOrEmpty(file),
|
|
733
|
+
}));
|
|
734
|
+
let nextConfig = config;
|
|
735
|
+
if (state) {
|
|
736
|
+
const entry = mcpServerEntry(config);
|
|
737
|
+
if (entry && entry.command !== state.mcpCommand) {
|
|
738
|
+
throw new Error("notes MCP entry points at a different binary; refusing to remove user configuration");
|
|
739
|
+
}
|
|
740
|
+
if (entry) {
|
|
741
|
+
try {
|
|
742
|
+
codexMcpRemove(env);
|
|
743
|
+
nextConfig = readFileOrEmpty(loc.configPath);
|
|
744
|
+
} catch (error) {
|
|
745
|
+
nextConfig = removeMcpServerTable(config);
|
|
746
|
+
if (nextConfig === config) throw error;
|
|
747
|
+
atomicWrite(loc.configPath, nextConfig, 0o600);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (state.tokenBudget.value === false || state.tokenBudget.value === null) {
|
|
751
|
+
nextConfig = removeManagedTokenBudget(nextConfig);
|
|
752
|
+
}
|
|
753
|
+
} else {
|
|
754
|
+
io.log(`install state missing; unable to determine original token_budget, keeping current value`);
|
|
755
|
+
}
|
|
756
|
+
if (nextConfig !== config) atomicWrite(loc.configPath, nextConfig, 0o600);
|
|
757
|
+
for (const entry of agentsFiles) {
|
|
758
|
+
const next = removeManagedBlock(entry.content, AGENTS_BEGIN, AGENTS_END, path.basename(entry.file));
|
|
759
|
+
if (next !== entry.content) atomicWrite(entry.file, next, 0o644);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
try {
|
|
763
|
+
fs.unlinkSync(loc.binaryPath);
|
|
764
|
+
} catch (error) {
|
|
765
|
+
if (error.code !== "ENOENT") throw error;
|
|
766
|
+
}
|
|
767
|
+
for (const directory of [path.dirname(loc.binaryPath), loc.installRoot]) {
|
|
768
|
+
try {
|
|
769
|
+
fs.rmdirSync(directory);
|
|
770
|
+
} catch (error) {
|
|
771
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTEMPTY") throw error;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
if (state) removeFileIfPresent(loc.statePath);
|
|
775
|
+
io.log("removed open-notes-mcp managed configuration and binary");
|
|
776
|
+
io.log(`preserved notes data: ${loc.notesRoot}`);
|
|
777
|
+
return 0;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
async function run(args, io = console, env = process.env) {
|
|
781
|
+
const [command, ...rest] = args;
|
|
782
|
+
if (!command || command === "--help" || command === "-h" || command === "help") {
|
|
783
|
+
io.log(usage());
|
|
784
|
+
return command ? 0 : 1;
|
|
785
|
+
}
|
|
786
|
+
if (command === "init") return init(rest, io, env);
|
|
787
|
+
if (command === "doctor") {
|
|
788
|
+
if (rest.length) throw new Error(`unknown doctor option: ${rest[0]}`);
|
|
789
|
+
return doctor(rest, io, env);
|
|
790
|
+
}
|
|
791
|
+
if (command === "uninstall") return uninstall(rest, io, env);
|
|
792
|
+
throw new Error(`unknown command: ${command}\n\n${usage()}`);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
module.exports = {
|
|
796
|
+
AGENTS_BEGIN,
|
|
797
|
+
AGENTS_BLOCK,
|
|
798
|
+
AGENTS_END,
|
|
799
|
+
MCP_BEGIN,
|
|
800
|
+
MCP_END,
|
|
801
|
+
codexVersion,
|
|
802
|
+
enableTokenBudget,
|
|
803
|
+
locations,
|
|
804
|
+
mcpServerEntry,
|
|
805
|
+
mcpBlock,
|
|
806
|
+
removeManagedBlock,
|
|
807
|
+
removeManagedTokenBudget,
|
|
808
|
+
run,
|
|
809
|
+
tokenBudgetEntry,
|
|
810
|
+
upsertManagedBlock,
|
|
811
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "open-notes-mcp",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Cross-window file-backed notes for Codex CLI",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/oreasono/open-notes-mcp.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/oreasono/open-notes-mcp#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/oreasono/open-notes-mcp/issues"
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"open-notes-mcp": "bin/open-notes-mcp.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin",
|
|
19
|
+
"lib",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"optionalDependencies": {
|
|
27
|
+
"@open-notes-mcp/darwin-arm64": "0.1.0",
|
|
28
|
+
"@open-notes-mcp/darwin-x64": "0.1.0",
|
|
29
|
+
"@open-notes-mcp/linux-arm64": "0.1.0",
|
|
30
|
+
"@open-notes-mcp/linux-x64": "0.1.0",
|
|
31
|
+
"@open-notes-mcp/win32-arm64": "0.1.0",
|
|
32
|
+
"@open-notes-mcp/win32-x64": "0.1.0"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build:native": "sh scripts/build-native.sh",
|
|
36
|
+
"prepack": "npm run build:native",
|
|
37
|
+
"test": "node --test test/*.test.js",
|
|
38
|
+
"probe": "sh scripts/probe.sh",
|
|
39
|
+
"probe:installer": "node scripts/installer-probe.js"
|
|
40
|
+
}
|
|
41
|
+
}
|