@eocrm/cli 0.0.1-bootstrap.0 → 0.4.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 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 CHANGED
@@ -1,3 +1,142 @@
1
- # @eocrm/cli
1
+ # eocrm plugins for Claude Code and Codex
2
2
 
3
- Placeholder that reserves the name. Install the latest release with `npx @eocrm/cli@latest init`.
3
+ Two plugins in one catalogue, for Claude Code and for Codex:
4
+
5
+ - **`eocrm-mcp`**: eocrm tools only. Claude can read and change tasks, contacts, deals, appointments and records in your workspaces through the eocrm MCP server. No hooks and no tracking.
6
+ - **`eocrm`**: agent work. It reports Claude Code and Codex runs, plan steps, commits, test runs, PRs and review findings to your eocrm workspace. In Claude Code it installs `eocrm-mcp` too; in Codex, add `eocrm-mcp` yourself.
7
+
8
+ ## Install (Claude Code)
9
+
10
+ ```
11
+ /plugin marketplace add eocrm/agent-plugin
12
+ /plugin install eocrm-mcp@eocrm # tools only
13
+ /plugin install eocrm@eocrm # agent work (includes the tools)
14
+ ```
15
+
16
+ For the tools, run `/mcp`, select `plugin:eocrm-mcp:eocrm` and sign in through the browser. For agent work, also run `/eocrm:login`. If you added the eocrm MCP server by hand before, remove it (`claude mcp remove eocrm`) so the tools aren't listed twice.
17
+
18
+ Then turn on updates: `/plugin` → Marketplaces → `eocrm` → Enable auto-update. Claude Code leaves it off for third-party catalogues, and you only receive a release when its `version` changes.
19
+
20
+ ## Install (Codex)
21
+
22
+ ```
23
+ codex plugin marketplace add eocrm/agent-plugin
24
+ codex plugin add eocrm@eocrm # agent work
25
+ codex plugin add eocrm-mcp@eocrm # tools
26
+ ```
27
+
28
+ Then open `/hooks` in Codex and trust the eocrm hooks, listed under `eocrm: …` names (Codex runs none until you do, and asks again after an update changes them; `status` says so while no hook has run in the repo), and sign in with the `login` skill. Node 20+ must be on the PATH of the Codex desktop app too. Codex uses its own skill texts (`codex-skills/`), which find the plugin's data and session without Claude Code's variables.
29
+
30
+ Prerequisites for `eocrm` (agent work): Node 20+ on PATH, `git`, optionally `gh`. Without a GitHub SSH key, set `CLAUDE_CODE_PLUGIN_PREFER_HTTPS=1` so installs and updates clone over HTTPS.
31
+
32
+ ## Use
33
+
34
+ - `/eocrm:login` (a skill; in Codex, ask for the `login` skill) signs in through the browser (sign-in starts in the EU and eocrm resolves your home region; `--region ru` signs in to an RU workspace) and stores tokens in the OS keychain, or a 0600 file when no keychain is usable.
35
+ - `/eocrm:use` maps the current repo to a workspace. The mapping is stored per repo, and `.claude/eocrm.json` (workspace slug and region only) can be committed to share it; each user confirms it once. With a single workspace the plugin picks it automatically.
36
+ - Reminders: on session start, resume or `/clear`, on a new branch, or when work moves to another task, the plugin reminds Claude of the linked task. The Conventions **Task switch check** sets how often it checks for a task switch: Every prompt, After a pause (the default), or Signals only.
37
+ - Four skills: `pick-type`, `link-run`, `record-judgement`, `file-human-work`.
38
+ - `/eocrm:status` (Codex: the `status` skill) shows sign-in, workspace and pairing.
39
+
40
+ ## Use with any agent (CLI)
41
+
42
+ For agents without the plugin, the `@eocrm/cli` package reports their runs and commits through git hooks. Node 20+ and `git` are required; `gh` is optional (the branch's pull request).
43
+
44
+ ```
45
+ npx @eocrm/cli init # in the repo
46
+ npx @eocrm/cli init --agent cursor # also set the repo's default agent
47
+ ```
48
+
49
+ `--agent` is one of `claude_code`, `cursor`, `codex`, `cline`, `roo`, `opencode`, `aider`, or `none` to clear it. `init` signs in if needed, maps the repo to a workspace (`eocrm init <workspace>` names one), copies the CLI to `<data>/bin/<version>` with a launcher at `<data>/bin/eocrm.mjs` (so hooks survive npx clearing its cache), and adds one line to the repo's `post-commit`, `pre-push` and `post-checkout` hooks. Data lives in `$XDG_DATA_HOME/eocrm`, `~/.local/share/eocrm`, or `%APPDATA%\eocrm`; only `--data <dir>` overrides it. The CLI keeps its own sign-in and never touches the plugin's.
50
+
51
+ ### Per tool
52
+
53
+ A commit counts for an agent when it carries that agent's signal; with none, it counts for the repo's `--agent`; with neither it is a person's commit and starts no run.
54
+
55
+ | Tool | Detected automatically | Needs `--agent` |
56
+ |---|---|---|
57
+ | Cline (VS Code) | commits from its terminal (`CLINE_ACTIVE`) | commits made through other means |
58
+ | Roo Code (VS Code) | commits from its terminal (`ROO_ACTIVE`) | commits made through other means |
59
+ | Cursor | the Cursor agent's terminal (`CURSOR_AGENT`, or the agent terminal role) | a person's terminal in Cursor looks the same as any editor terminal: set `--agent cursor` only if all commits there are the agent's |
60
+ | opencode | its shell (`OPENCODE=1`) | no |
61
+ | Aider | the ` (aider)` author or committer suffix, or a `Co-authored-by: aider` trailer (aider's defaults) | if you turned attribution off |
62
+ | Claude Code, Codex | their shell variables | prefer the plugin; with the plugin live in the worktree the CLI hooks stay quiet |
63
+
64
+ Attribution is display only, not a trust boundary.
65
+
66
+ ### Sign in
67
+
68
+ `eocrm login [workspace]` opens the browser; `eocrm login --device [workspace]` prints a code to approve on another device (SSH, containers). `--region ru` signs in to an RU workspace. `eocrm logout` signs out. Tokens go to the OS keychain, or a 0600 file when none is usable. Login, `init` and `status` print `Signed in at <sign-in host> — reporting to <workspace>`; check the workspace there, since anyone who sees a `--device` code can answer it first (the server gives the CLI no account name).
69
+
70
+ ### Commands
71
+
72
+ | Command | Does |
73
+ |---|---|
74
+ | `eocrm init [workspace] [--agent X] [--shared-hooks]` | sign in if needed, map the repo, install the hooks |
75
+ | `eocrm status` | sign-in, workspace, agent, hooks and live runs |
76
+ | `eocrm sync` | send queued events, import plans, check the branch's PR |
77
+ | `eocrm run start [--agent X]` / `run stop` | start or end a run by hand (a started run carries its agent to commits without a signal) |
78
+ | `eocrm link <KEY\|none>` | link this worktree to a task |
79
+ | `eocrm link <change> <KEY\|none>` | link an OpenSpec change to a task |
80
+ | `eocrm openspec import --space KEY` | create tasks for unlinked OpenSpec changes |
81
+ | `eocrm uninstall` | remove exactly the lines `init` added |
82
+
83
+ ### Hooks
84
+
85
+ Hooks only queue an event and return; a detached process sends it. They never fail or noticeably slow `git commit` or `git push`, and always exit 0. `init` inserts its line into an existing husky, lefthook or `core.hooksPath` hook (or a hand-written sh hook) and keeps the rest byte for byte; `uninstall` restores it. Husky regenerates its hooks on install, which drops the line: re-run `eocrm init` afterwards. If `core.hooksPath` comes from your global or system git config, the hooks directory is shared by other repositories, so `init` refuses unless you pass `--shared-hooks`; the line stays quiet in repos where `init` never ran. Hooks that are not shell scripts are skipped and reported.
86
+
87
+ ### OpenSpec
88
+
89
+ With `openspec/changes/<id>/tasks.md` in the repo, each open change becomes a plan on a task. `eocrm openspec import --space KEY` creates a task per unlinked change (title from `proposal.md`, the Why section as description) and records the mapping per repo; without `--space` it lists your spaces. To link a change to an existing task use `eocrm link <change> <KEY>`, or put `<!-- eocrm: KEY -->` in its `proposal.md`. Checked-off items in `tasks.md` mark plan items done; lines inside code fences are ignored.
90
+
91
+ ### Upgrading
92
+
93
+ ```
94
+ npx @eocrm/cli@latest init
95
+ ```
96
+
97
+ This copies the new version and repoints the hooks; `status` warns when the hooks' copy is missing or the CLI is below eocrm's minimum.
98
+
99
+ ### Privacy
100
+
101
+ The CLI sends the same metadata as the plugin (see "What is sent"): branch, repo, task key, plan items, commit sha and subject, PR links, run boundaries; never prompts, replies or file contents, scrubbed for secrets. OpenSpec import sends titles, the Why text and plan items; OpenSpec import identifies the repo by a hash; run and PR events carry the repository's owner/name, never its remote URL.
102
+
103
+ ## Pair with your tools connection
104
+
105
+ The plugin's sign-in can only report and read runs; it can't change tasks. If your tools (`eocrm-mcp`) are already signed in, the plugin's sign-in sends a pairing request: in eocrm open Account → Agents and select **Approve**, so both show as one agent. If you signed in the tools afterwards, select **Merge into…** on the new connection there instead. Claude Code pairs with Claude Code, Codex with Codex; a request expires after 15 minutes. Someone who uses both signs in twice and sees two agents.
106
+
107
+ Agent work must be on in the workspace (Settings → Modules); it needs Tasks and AI assistants. What runs show, the conventions and alerts: [Agent work help](https://docs.eocrm.io/help/agent-work/).
108
+
109
+ ## Messages from eocrm
110
+
111
+ eocrm can answer tracking calls with short messages, and the plugin shows each one once, at your next prompt, Bash or task tool call, or stop. Lines meant for you (someone commented on the linked task, conventions changed, a plugin update) appear in the terminal and cost the agent no tokens. A comment you wrote on the linked task yourself is passed to the agent, quoted as your words rather than instructions. An update notice shows at most once a day. If the plugin is older than eocrm's minimum, tracking pauses and keeps its queue until you update it (`/plugin marketplace update eocrm`; Codex: `codex plugin marketplace upgrade eocrm`). You're also told once per session when Agent work is off for the workspace or you're signed out.
112
+
113
+ ## What is sent
114
+
115
+ Run metadata (branch, repo, task key), plan items, commits (sha, subject), test commands and result lines (Codex reports no exit code, so its test runs have none), PR links, review findings, and turn boundaries and waiting (for permission or for you; Claude Code also for a question). Never your prompts, the assistant's replies or file contents. Everything is scrubbed for secrets and capped in length before it leaves the machine. Events are queued locally and retried; when the queue cannot be flushed the run shows as "tracking stale".
116
+
117
+ Token counts per model: Claude Code's come from the local session transcript and its subagent transcripts; Codex's come from Codex itself (its per-request hook), with no transcript read. Nothing else from either leaves the machine.
118
+
119
+ ## Troubleshooting
120
+
121
+ Run `/eocrm:status` for sign-in, workspace and pairing state.
122
+
123
+ ## Trust boundary
124
+
125
+ Environment a repo injects into hooks (`NODE_OPTIONS`, `NODE_EXTRA_CA_CERTS`, proxy variables) is outside what the plugin can defend. It relies on Claude Code's workspace trust: only trust repos you trust.
126
+
127
+ ## Releasing
128
+
129
+ Users get a release only when `version` in `.claude-plugin/plugin.json` changes: bump it (and `package.json`) in the release PR. Before a release run `claude plugin validate --strict .` locally (no model call) and put its result line in the PR.
130
+
131
+ ## Nightly smoke (setup)
132
+
133
+ `.github/workflows/nightly-smoke.yml` runs a REST-only round trip; it never runs `claude`. Without credentials it warns and passes.
134
+
135
+ - Secrets: `EOCRM_SMOKE_REGION`, `EOCRM_SMOKE_CLIENT_ID`, `EOCRM_SMOKE_REFRESH_TOKEN`, `SMOKE_SECRETS_PAT` (secrets write; stores the rotated refresh token).
136
+ - Variables: `EOCRM_SMOKE_WORKSPACE`, `EOCRM_SMOKE_TASK`.
137
+ - Runs never overlap (one `concurrency` group): each spends the stored refresh token once.
138
+ - Seed (and re-seed when the store step fails): sign the smoke member in with a separate `--data` dir so your own sign-in is untouched (`node scripts/eocrm.mjs login --data <dir> --region eu test`), then `node scripts/eocrm.mjs smoke-seed --data <dir> --repo <owner>/<repo>`. It writes the region, client id, refresh token and workspace through `gh` (stdin, never printed) and signs that data dir out, so the token family belongs to CI. Set `EOCRM_SMOKE_TASK` and `SMOKE_SECRETS_PAT` by hand.
139
+
140
+ ## License
141
+
142
+ Apache-2.0. "eocrm" is a trademark of eocrm; the license grants no right to use it.
@@ -0,0 +1,34 @@
1
+ import { dataDir, parseArgs } from '../lib/paths.mjs';
2
+ import { handle, logError, runClient } from '../lib/run.mjs';
3
+ import { flush } from '../lib/flush.mjs';
4
+ import { gitTimeout } from '../lib/state.mjs';
5
+
6
+ const HOOK_GIT_MS = 1000;
7
+
8
+ async function readStdin() {
9
+ const chunks = [];
10
+ for await (const chunk of process.stdin) chunks.push(chunk);
11
+ return Buffer.concat(chunks).toString('utf8');
12
+ }
13
+
14
+ async function main() {
15
+ const argv = process.argv.slice(2);
16
+ let data;
17
+ try {
18
+ data = dataDir({ argv, env: process.env });
19
+ const { event, harness } = parseArgs(argv);
20
+ const ctx = { data, env: process.env, now: Date.now, harness };
21
+ if (event === 'flush') {
22
+ await flush({ data, clientFor: runClient(ctx), harness });
23
+ return;
24
+ }
25
+ gitTimeout.ms = HOOK_GIT_MS;
26
+ const { stdout } = await handle(event, JSON.parse(await readStdin()), ctx);
27
+ if (stdout) await new Promise((resolve) => process.stdout.write(stdout, resolve));
28
+ } catch (e) {
29
+ if (data) logError(data, e);
30
+ }
31
+ }
32
+
33
+ // Exits at once: a request the reconciler gave up on must not keep the hook past its timeout.
34
+ main().finally(() => process.exit(0));
package/lib/api.mjs ADDED
@@ -0,0 +1,151 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { clean, scrub, LIMITS } from './scrub.mjs';
3
+ import { LockTimeout } from './state.mjs';
4
+
5
+ export class NetworkError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = 'NetworkError';
9
+ }
10
+ }
11
+
12
+ const START_TEXT = { branch: 255, worktree: 500, repo: 200 };
13
+ const EVENT_TEXT = {
14
+ label: LIMITS.stepLabel,
15
+ subject: LIMITS.commitSubject,
16
+ repo: LIMITS.commitRepo,
17
+ command: LIMITS.testCommand,
18
+ result_line: LIMITS.resultLine,
19
+ summary: LIMITS.findingSummary,
20
+ what: LIMITS.rulingWhat,
21
+ why: LIMITS.rulingWhy,
22
+ cost_if_wrong: LIMITS.rulingCostIfWrong,
23
+ };
24
+ const PLAN_ITEM_TEXT = 500;
25
+ const PLAN_PATH = 500;
26
+ const TASK_TITLE = 255;
27
+ const TASK_DESCRIPTION = 10000;
28
+ export const MAX_BODY = 1024 * 1024;
29
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
30
+ export const userAgent = (harness, agent = 'unknown') => (harness === 'cli' ? `eocrm-cli/${VERSION} (${agent})` : `eocrm-plugin/${VERSION} (${harness === 'codex' ? 'codex' : 'claude-code'})`);
31
+
32
+ class TooLarge extends Error {}
33
+
34
+ export async function readCapped(res) {
35
+ if (Number(res.headers.get('content-length')) > MAX_BODY) throw new TooLarge();
36
+ if (!res.body) return '';
37
+ const chunks = [];
38
+ let size = 0;
39
+ for await (const chunk of res.body) {
40
+ size += chunk.length;
41
+ if (size > MAX_BODY) throw new TooLarge();
42
+ chunks.push(chunk);
43
+ }
44
+ return Buffer.concat(chunks).toString('utf8');
45
+ }
46
+
47
+ function cleaned(obj, limits) {
48
+ const out = { ...obj };
49
+ for (const [k, limit] of Object.entries(limits)) if (typeof out[k] === 'string') out[k] = clean(out[k], limit);
50
+ return out;
51
+ }
52
+
53
+ export function cleanEvent(event) {
54
+ const out = cleaned(event, EVENT_TEXT);
55
+ // A truncated URL fails eocrm's uri format, so the url is only scrubbed.
56
+ if (typeof out.url === 'string') out.url = scrub(out.url);
57
+ if (typeof out.path === 'string') out.path = clean(out.path.trim(), PLAN_PATH);
58
+ if (Array.isArray(out.items)) out.items = out.items.map((i) => cleaned(i, { text: PLAN_ITEM_TEXT }));
59
+ return out;
60
+ }
61
+
62
+ export function createClient({ endpoints, workspace, store, fetch = globalThis.fetch, timeoutMs = 8000, lockTimeoutMs = 2500, harness, agent }) {
63
+ const base = workspace == null ? `${endpoints.issuer}/api` : endpoints.api(workspace);
64
+ const { issuer, key } = endpoints;
65
+
66
+ async function send(label, url, init) {
67
+ try {
68
+ const res = await fetch(url, { ...init, headers: { ...init.headers, 'user-agent': userAgent(harness, agent) }, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
69
+ const text = await readCapped(res);
70
+ let body = null;
71
+ if (text) {
72
+ try {
73
+ body = JSON.parse(text);
74
+ } catch {
75
+ body = text;
76
+ }
77
+ }
78
+ return { status: res.status, body };
79
+ } catch (e) {
80
+ const why = e?.name === 'TimeoutError' ? 'timeout' : e instanceof TooLarge ? 'response too large' : 'network error';
81
+ throw new NetworkError(`eocrm: ${label} failed (${why})`);
82
+ }
83
+ }
84
+
85
+ function once(method, path, json, access) {
86
+ const headers = { accept: 'application/json', authorization: `Bearer ${access}` };
87
+ if (json !== undefined) headers['content-type'] = 'application/json';
88
+ return send(`${method} ${path.split('?')[0]}`, base + path, { method, headers, body: json === undefined ? undefined : JSON.stringify(json) });
89
+ }
90
+
91
+ async function rotate(tokens, outcome) {
92
+ if (!tokens.refresh_token || !tokens.client_id) return null;
93
+ const r = await send('POST /oauth/token', `${issuer}/oauth/token`, {
94
+ method: 'POST',
95
+ headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
96
+ body: new URLSearchParams({ grant_type: 'refresh_token', client_id: tokens.client_id, refresh_token: tokens.refresh_token }).toString(),
97
+ });
98
+ if (r.status === 400 || r.status === 401) return null;
99
+ if (r.status === 429 || r.status >= 500) {
100
+ outcome.transient = { status: r.status, body: null };
101
+ return null;
102
+ }
103
+ if (r.status !== 200 || typeof r.body?.access_token !== 'string') throw new NetworkError(`eocrm: POST /oauth/token failed (status ${r.status})`);
104
+ return {
105
+ access_token: r.body.access_token,
106
+ refresh_token: r.body.refresh_token ?? tokens.refresh_token,
107
+ expires_at: Number(r.body.expires_in) > 0 ? Math.floor(Date.now() / 1000) + Number(r.body.expires_in) : null,
108
+ client_id: tokens.client_id,
109
+ };
110
+ }
111
+
112
+ // Refresh tokens rotate, so a refresh racing another process's would spend a revoked one.
113
+ async function refresh(tokens, outcome) {
114
+ const newer = (t) => (t?.access_token && t.access_token !== tokens.access_token ? t : null);
115
+ try {
116
+ return await store.update(key, async (latest) => (latest ? newer(latest) ?? rotate(tokens, outcome) : null), { timeoutMs: lockTimeoutMs });
117
+ } catch (e) {
118
+ if (!(e instanceof LockTimeout)) throw e;
119
+ const latest = newer(await store.get(key));
120
+ if (!latest) outcome.transient = { status: 503, body: null };
121
+ return latest;
122
+ }
123
+ }
124
+
125
+ async function call(method, path, json) {
126
+ const tokens = await store.get(key);
127
+ if (!tokens?.access_token) return { status: 401, body: null };
128
+ const first = await once(method, path, json, tokens.access_token);
129
+ if (first.status !== 401) return first;
130
+ const outcome = {};
131
+ const fresh = await refresh(tokens, outcome);
132
+ return fresh ? once(method, path, json, fresh.access_token) : outcome.transient ?? first;
133
+ }
134
+
135
+ const run = (id) => `/v1/agent-runs/${encodeURIComponent(id)}`;
136
+
137
+ return {
138
+ startRun: (body) => call('POST', '/v1/agent-runs', cleaned(body, START_TEXT)),
139
+ updateRun: (id, body) => call('PATCH', run(id), cleaned(body, { step: LIMITS.stepLabel })),
140
+ heartbeat: (id, ack = []) => call('POST', `${run(id)}/heartbeat`, ack.length ? { ack } : undefined),
141
+ recordEvents: (id, events, ack = []) => call('POST', `${run(id)}/events`, { events: events.map(cleanEvent), ...(ack.length ? { ack } : {}) }),
142
+ listEvents: (id, cursor) => call('GET', `${run(id)}/events${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`),
143
+ workspaces: () => call('GET', '/v1/agent-work/workspaces'),
144
+ conventions: () => call('GET', '/v1/agent-work/conventions'),
145
+ importTask: (body) => call('POST', '/v1/agent-work/tasks', {
146
+ ...cleaned(body, { client_ref: 500, space: 26, title: TASK_TITLE, description: TASK_DESCRIPTION }), plan: cleanEvent(body.plan),
147
+ }),
148
+ pairable: () => call('GET', '/v1/agent-runs/pairable'),
149
+ pair: (connection_id) => call('POST', '/v1/agent-runs/pair', { connection_id }),
150
+ };
151
+ }
@@ -0,0 +1,28 @@
1
+ export const AGENTS = ['claude_code', 'cursor', 'codex', 'cline', 'roo', 'opencode', 'aider'];
2
+
3
+ // First match wins; editor-hosted agents come before the editor they run in.
4
+ const SIGNALS = [
5
+ // aider appends " (aider)" to author/committer names by default, or adds "Co-authored-by: aider (<model>)" (aider.chat/docs/git.html, aider/repo.py)
6
+ ['aider', ({ commit }) => / \(aider\)$/.test(commit.author ?? '') || / \(aider\)$/.test(commit.committer ?? '') || /^co-authored-by:\s*aider\b/im.test(commit.message ?? '')],
7
+ // Cline's VS Code terminals: CLINE_ACTIVE=true (cline/cline apps/vscode/src/hosts/vscode/terminal/VscodeTerminalRegistry.ts)
8
+ ['cline', ({ env }) => Boolean(env.CLINE_ACTIVE)],
9
+ // Roo Code's VS Code terminal provider: ROO_ACTIVE=true (RooCodeInc/Roo-Code PR #11862, src/integrations/terminal/Terminal.ts)
10
+ ['roo', ({ env }) => Boolean(env.ROO_ACTIVE)],
11
+ // opencode sets OPENCODE=1 at start (opencode packages/opencode/src/index.ts); OPENCODE_CLIENT per @vercel/detect-agent
12
+ ['opencode', ({ env }) => env.OPENCODE === '1' || Boolean(env.OPENCODE_CLIENT)],
13
+ // cursor-agent sets CURSOR_AGENT; Cursor's agent terminal sets CURSOR_EXTENSION_HOST_ROLE=agent-exec (vercel/vercel packages/detect-agent).
14
+ // CURSOR_TRACE_ID is in every Cursor terminal, a person's too, so it is no signal.
15
+ ['cursor', ({ env }) => Boolean(env.CURSOR_AGENT) || env.CURSOR_EXTENSION_HOST_ROLE === 'agent-exec'],
16
+ // Claude Code sets CLAUDECODE=1 in its shells; CLAUDE_CODE per @vercel/detect-agent
17
+ ['claude_code', ({ env }) => Boolean(env.CLAUDECODE || env.CLAUDE_CODE)],
18
+ // Codex sets CODEX_THREAD_ID / CODEX_SANDBOX / CODEX_CI for its commands (@vercel/detect-agent)
19
+ ['codex', ({ env }) => Boolean(env.CODEX_THREAD_ID || env.CODEX_SANDBOX || env.CODEX_CI)],
20
+ // TERM_PROGRAM=vscode is any VS Code-based terminal, agent or not: no signal, the repo setting decides.
21
+ ];
22
+
23
+ export function detectAgent({ env = {}, commit = {} } = {}) {
24
+ return SIGNALS.find(([, test]) => test({ env, commit }))?.[0] ?? null;
25
+ }
26
+
27
+ // No signal and no repo setting: a person's commit, so no agent and no run.
28
+ export const agentOf = ({ env, commit, setting }) => detectAgent({ env, commit }) ?? (AGENTS.includes(setting) ? setting : null);