@eocrm/cli 0.4.0 → 0.4.2

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/README.md CHANGED
@@ -1,9 +1,13 @@
1
- # eocrm plugins for Claude Code and Codex
1
+ # eocrm for coding agents
2
2
 
3
- Two plugins in one catalogue, for Claude Code and for Codex:
3
+ Track your coding agents' work in eocrm: runs, commits, plan steps and pull requests, against the task they belong to. Pick the setup that matches your tool:
4
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.
5
+ - **Any agent (Cline, Roo Code, Cursor, opencode, Aider, …): the `@eocrm/cli` package.** It reports through git hooks, so it needs no model tokens and no editor plugin. `npx @eocrm/cli init` in your repo. See [Use with any agent (CLI)](#use-with-any-agent-cli).
6
+ - **Claude Code or Codex: the plugins below**, installed from this repo's catalogue:
7
+ - **`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.
8
+ - **`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.
9
+
10
+ Teams that plan with [OpenSpec](https://github.com/Fission-AI/OpenSpec) get each change's `tasks.md` as a live eocrm checklist with either setup ([OpenSpec](#openspec)).
7
11
 
8
12
  ## Install (Claude Code)
9
13
 
@@ -65,7 +69,7 @@ Attribution is display only, not a trust boundary.
65
69
 
66
70
  ### Sign in
67
71
 
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).
72
+ `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. Without a workspace, an account with several lists them and stays signed in; pick one with `eocrm init <workspace>` or `eocrm login <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
73
 
70
74
  ### Commands
71
75
 
@@ -100,9 +104,11 @@ This copies the new version and repoints the hooks; `status` warns when the hook
100
104
 
101
105
  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
106
 
107
+ Updating to 0.4.2 asks you to sign in once more: Claude Code and Codex now keep separate keychain entries.
108
+
103
109
  ## Pair with your tools connection
104
110
 
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.
111
+ 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 lists it; pick it with `pair <id>` to send a pairing request, then 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
112
 
107
113
  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
114
 
@@ -15,8 +15,8 @@ async function main() {
15
15
  const argv = process.argv.slice(2);
16
16
  let data;
17
17
  try {
18
- data = dataDir({ argv, env: process.env });
19
18
  const { event, harness } = parseArgs(argv);
19
+ data = dataDir({ argv, env: process.env, harness });
20
20
  const ctx = { data, env: process.env, now: Date.now, harness };
21
21
  if (event === 'flush') {
22
22
  await flush({ data, clientFor: runClient(ctx), harness });
package/lib/cli/run.mjs CHANGED
@@ -3,7 +3,7 @@ import { appendFileSync, mkdirSync, readFileSync, renameSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { randomBytes } from 'node:crypto';
6
- import { git, worktreeOf, withLock, loadRun, saveRun, loadWorktree, saveWorktree, liveDirOf, liveSession, gitTimeout, remove } from '../state.mjs';
6
+ import { git, GitDeadline, worktreeOf, withLock, loadRun, saveRun, loadWorktree, saveWorktree, liveDirOf, liveSession, gitTimeout, remove } from '../state.mjs';
7
7
  import { append } from '../outbox.mjs';
8
8
  import { eventId } from '../ids.mjs';
9
9
  import { prStatus, repoSlug } from '../git.mjs';
@@ -138,15 +138,16 @@ export async function runHook(ctx, name, cwd, args = []) {
138
138
  if (!hook) return 'unknown hook';
139
139
  const budget = ctx.hookMs ?? HOOK_MS;
140
140
  Object.assign(gitTimeout, { ms: HOOK_GIT_MS, deadline: Date.now() + budget });
141
- if (!cloneEntry(ctx.data, cwd).initialized) return 'not initialized';
142
141
  let timer;
143
142
  const late = new Promise((resolve) => {
144
143
  timer = setTimeout(() => resolve('timeout'), budget);
145
144
  timer.unref?.();
146
145
  });
147
146
  try {
147
+ if (!cloneEntry(ctx.data, cwd).initialized) return 'not initialized';
148
148
  return await Promise.race([hook(ctx, cwd, args), late]);
149
149
  } catch (e) {
150
+ if (e instanceof GitDeadline) return 'timeout';
150
151
  logError(ctx.data, e);
151
152
  return 'failed';
152
153
  } finally {
@@ -3,7 +3,8 @@ import { existsSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { withLock, readJson, writeJsonAtomic, remove } from './state.mjs';
5
5
 
6
- const SERVICE = 'eocrm-claude-plugin';
6
+ const SERVICE = 'eocrm-claude-code-plugin';
7
+ const LEGACY = 'eocrm-claude-plugin';
7
8
  const PRIVATE = { mode: 0o600 };
8
9
  const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
9
10
  const PS_ARGS = ['-NoProfile', '-NonInteractive', '-Command', '-'];
@@ -132,7 +133,9 @@ function checkIssuer(issuer) {
132
133
  if (typeof issuer !== 'string' || !/^https?:\/\/[^\s"'\\]+(?: https?:\/\/[^\s"'\\]+)?$/.test(issuer)) throw new Error('eocrm: invalid issuer');
133
134
  }
134
135
 
135
- export const storeFor = (data, harness) => credentialStore({ data, service: harness === 'cli' ? 'eocrm-cli' : SERVICE });
136
+ const SERVICES = { cli: 'eocrm-cli', codex: 'eocrm-codex-plugin' };
137
+
138
+ export const storeFor = (data, harness, opts) => credentialStore({ data, service: SERVICES[harness] ?? SERVICE, ...opts });
136
139
 
137
140
  export function credentialStore({ data, platform = process.platform, run = spawnWithStdin, service = SERVICE }) {
138
141
  const call = async (...a) => {
@@ -143,6 +146,7 @@ export function credentialStore({ data, platform = process.platform, run = spawn
143
146
  }
144
147
  };
145
148
  const keychain = { darwin, linux, win32 }[platform]?.(call, platform === 'win32' ? data : service) ?? null;
149
+ const legacy = service === 'eocrm-cli' || platform === 'win32' ? null : { darwin, linux }[platform]?.(call, LEGACY);
146
150
  const file = join(data, 'credentials.json');
147
151
  const readFile = () => {
148
152
  const map = readJson(file, {});
@@ -172,6 +176,13 @@ export function credentialStore({ data, platform = process.platform, run = spawn
172
176
  };
173
177
 
174
178
  return {
179
+ async dropLegacy(issuer) {
180
+ try {
181
+ await legacy?.del(issuer);
182
+ } catch {
183
+ // best effort
184
+ }
185
+ },
175
186
  async get(issuer, { timeoutMs } = {}) {
176
187
  checkIssuer(issuer);
177
188
  return read(issuer, timeoutMs);
package/lib/login.mjs CHANGED
@@ -227,8 +227,7 @@ export async function pairing(client) {
227
227
  const r = await client.pairable();
228
228
  if (r.status !== 200) return { status: 'standalone', refused: codeOf(r) ?? `status ${r.status}` };
229
229
  const candidates = Array.isArray(r.body?.items) ? r.body.items : [];
230
- if (candidates.length > 1) return { status: 'choose', candidates };
231
- return candidates.length ? requestPair(client, candidates[0].id) : { status: 'standalone' };
230
+ return candidates.length ? { status: 'choose', candidates } : { status: 'standalone' };
232
231
  }
233
232
 
234
233
  function pickWorkspace(r) {
@@ -240,9 +239,12 @@ function pickWorkspace(r) {
240
239
  return on[0].slug;
241
240
  }
242
241
 
243
- export function recordPairing(data, workspace, status) {
242
+ export function recordPairing(data, workspace, status, target = null) {
244
243
  const account = loadAccount(data);
245
- writeJsonAtomic(accountFile(data), { ...account, workspaces: { ...account.workspaces, [workspace]: status } });
244
+ const pairTargets = { ...account.pairTargets };
245
+ if (status === 'requested' && target) pairTargets[workspace] = target;
246
+ else delete pairTargets[workspace];
247
+ writeJsonAtomic(accountFile(data), { ...account, workspaces: { ...account.workspaces, [workspace]: status }, pairTargets });
246
248
  }
247
249
 
248
250
  export async function login({ data, region, workspace, env = process.env, openBrowser: open = openBrowser, timeoutMs = 300000, store, ports = PORTS, harness = 'claude', device = false, print = (l) => process.stdout.write(`${l}\n`), sleep }) {
@@ -270,7 +272,13 @@ export async function login({ data, region, workspace, env = process.env, openBr
270
272
  first = await probe();
271
273
  }
272
274
  if (!workspace) {
273
- workspace = pickWorkspace(first);
275
+ try {
276
+ workspace = pickWorkspace(first);
277
+ } catch (e) {
278
+ // The CLI is signed in either way: it lists the workspaces instead of failing; the plugins ask for the slug.
279
+ if (harness === 'cli' && e.lines.length) return { workspace: null, storage, issuer: ep.issuer, choices: e.lines };
280
+ throw e;
281
+ }
274
282
  first = await client(workspace).conventions();
275
283
  }
276
284
  const code = codeOf(first);
@@ -278,6 +286,9 @@ export async function login({ data, region, workspace, env = process.env, openBr
278
286
  if (first.status !== 200) throw new LoginError(`sign-in failed (${code ?? `status ${first.status}`})`);
279
287
 
280
288
  const paired = await pairing(client(workspace));
281
- writeJsonAtomic(accountFile(data), { ...account, workspace, signedInAt: Date.now(), workspaces: { ...account.workspaces, [workspace]: paired.status } });
289
+ const pairTargets = { ...account.pairTargets };
290
+ delete pairTargets[workspace];
291
+ writeJsonAtomic(accountFile(data), { ...account, workspace, signedInAt: Date.now(), workspaces: { ...account.workspaces, [workspace]: paired.status }, ...(Object.keys(pairTargets).length && { pairTargets }) });
292
+ await store.dropLegacy?.(ep.key);
282
293
  return { workspace, storage, pairing: paired };
283
294
  }
package/lib/paths.mjs CHANGED
@@ -2,10 +2,10 @@ import { chmodSync, mkdirSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join, posix, resolve, sep, win32 } from 'node:path';
4
4
 
5
- export function dataDir({ argv, env, data, fallback }) {
5
+ export function dataDir({ argv, env, data, fallback, harness = 'claude' }) {
6
6
  const eq = argv.find((a) => a.startsWith('--data='));
7
7
  const i = argv.indexOf('--data');
8
- const dir = data || (eq && eq.slice(7)) || (i >= 0 && argv[i + 1]) || env.CLAUDE_PLUGIN_DATA || env.PLUGIN_DATA || fallback;
8
+ const dir = data || (eq && eq.slice(7)) || (i >= 0 && argv[i + 1]) || (harness === 'codex' ? env.PLUGIN_DATA : env.CLAUDE_PLUGIN_DATA) || fallback;
9
9
  if (!dir) throw new Error('eocrm: no data dir');
10
10
  mkdirSync(dir, { recursive: true });
11
11
  if (process.platform !== 'win32') {
package/lib/plans.mjs CHANGED
@@ -24,6 +24,8 @@ const CHANGE = /^openspec\/changes\/(?!archive\/tasks\.md$)(archive\/)?([^/]+)\/
24
24
  const OS_BOX = /^\s*(?:[-*+]|\d+[.)])\s+\[([ xX~])\]\s+(.*)$/;
25
25
  const OS_KEY = /^(\d+(?:\.\d+)+)\.?\s+(\S.*)$/;
26
26
  const DATED = /^\d{4}-\d{2}-\d{2}-(.+)$/;
27
+ const CHANGE_DIR = /^(openspec\/changes\/(?:archive\/)?[^/]+)\//;
28
+ const SHA = /^[0-9a-f]{40,64}$/;
27
29
  export const LINK = /<!--\s*eocrm:\s*([A-Z][A-Z0-9]{1,9}-[0-9]+)\s*-->/;
28
30
  const WIN = /^(?:[A-Za-z]:|\\\\)/;
29
31
  // Session paths follow the cwd's own shape, not the host's.
@@ -228,13 +230,28 @@ function fromLedger(root, pass) {
228
230
  return null;
229
231
  }
230
232
 
231
- function fromBranch(root, pass) {
233
+ // On the default branch the branch diff is empty: the run's own commits HEAD reaches name its plan, any file of a change its tasks.md.
234
+ function fromCommits(root, base, shas, exec) {
235
+ const own = Array.isArray(shas) ? shas.filter((s) => SHA.test(s)) : [];
236
+ if (!own.length || (base !== 'HEAD' && base !== git(root, ['rev-parse', 'HEAD'], exec))) return [];
237
+ const away = new Set(git(root, ['rev-list', '--ignore-missing', ...own, '--not', 'HEAD'], exec).split('\n'));
238
+ const reached = own.filter((s) => !away.has(s));
239
+ if (!reached.length) return [];
240
+ return git(root, ['log', '--ignore-missing', '--no-walk=unsorted', '--name-only', '-z', '--format=', ...reached, '--', PLANS_DIR, CHANGES_DIR], exec)
241
+ .split('\0').map((n) => {
242
+ const dir = CHANGE_DIR.exec(n)?.[1];
243
+ return dir ? `${dir}/tasks.md` : n;
244
+ });
245
+ }
246
+
247
+ function fromBranch(root, pass, own) {
232
248
  const { exec } = pass;
233
249
  const base = pass.base();
234
250
  const names = [
235
- git(root, ['diff', '--name-only', '-z', '--diff-filter=d', base, '--', PLANS_DIR, CHANGES_DIR], exec),
236
- git(root, ['ls-files', '-z', '--others', '--exclude-standard', '--', PLANS_DIR, CHANGES_DIR], exec),
237
- ].join('\0').split('\0').filter((n) => PLAN_FILE.test(n) || CHANGE.test(n));
251
+ ...git(root, ['diff', '--name-only', '-z', '--diff-filter=d', base, '--', PLANS_DIR, CHANGES_DIR], exec).split('\0'),
252
+ ...git(root, ['ls-files', '-z', '--others', '--exclude-standard', '--', PLANS_DIR, CHANGES_DIR], exec).split('\0'),
253
+ ...fromCommits(root, base, own, exec),
254
+ ].filter((n) => PLAN_FILE.test(n) || CHANGE.test(n));
238
255
  const files = [...new Set(names)].sort((a, b) => mtime(join(root, b)) - mtime(join(root, a)));
239
256
  for (const rel of files) {
240
257
  const found = load(root, rel, pass);
@@ -261,5 +278,5 @@ export function activePlan(cwd, run = {}, exec) {
261
278
  const todos = Array.isArray(run?.todos) && run.todos.length ? { source: 'todo', ...fromTodos(run.todos) } : null;
262
279
  let base;
263
280
  const pass = { exec, base: () => (base ??= mergeBase(root, exec) ?? 'HEAD') };
264
- return fromLedger(root, pass) ?? fromBranch(root, pass) ?? fromWritten(root, run?.written, pass) ?? todos;
281
+ return fromLedger(root, pass) ?? fromBranch(root, pass, run?.ownCommits) ?? fromWritten(root, run?.written, pass) ?? todos;
265
282
  }
package/lib/state.mjs CHANGED
@@ -125,14 +125,24 @@ export function writeFileAtomic(file, text, { mode = 0o666 } = {}) {
125
125
  // deadline (epoch ms), when set, caps every git call after it: a hook's whole budget, not one call's.
126
126
  export const gitTimeout = { ms: 5000, deadline: null };
127
127
 
128
+ export class GitDeadline extends Error {
129
+ constructor() {
130
+ super('eocrm: hook time budget spent');
131
+ this.name = 'GitDeadline';
132
+ }
133
+ }
134
+
135
+ // Past the deadline git throws: an empty answer would read as a fact (no commit, no live session).
128
136
  export const git = (cwd, args, run = execFileSync) => {
129
- const left = gitTimeout.deadline === null ? gitTimeout.ms : Math.min(gitTimeout.ms, gitTimeout.deadline - Date.now());
130
- if (left <= 0) return '';
137
+ const { deadline } = gitTimeout;
138
+ const left = deadline === null ? gitTimeout.ms : Math.min(gitTimeout.ms, deadline - Date.now());
131
139
  try {
132
- return run('git', args, { cwd, encoding: 'utf8', timeout: left, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
133
- } catch {
134
- return '';
140
+ if (left > 0) return run('git', args, { cwd, encoding: 'utf8', timeout: left, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
141
+ } catch (e) {
142
+ if (deadline !== null && e.code === 'ETIMEDOUT') throw new GitDeadline();
135
143
  }
144
+ if (deadline !== null && Date.now() >= deadline) throw new GitDeadline();
145
+ return '';
136
146
  };
137
147
 
138
148
  export function worktreeOf(cwd, run, top = git(cwd, ['rev-parse', '--show-toplevel'], run)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eocrm/cli",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
package/scripts/eocrm.mjs CHANGED
@@ -41,9 +41,18 @@ function pairingLines(p) {
41
41
 
42
42
  async function recheck({ data, env, store, workspace, region, harness }) {
43
43
  try {
44
- const result = await pairing(createClient({ endpoints: endpoints({ region, env }), workspace, store, harness }));
45
- if (result.status === 'choose' || result.refused) return ['pairing requested'];
46
- recordPairing(data, workspace, result.status);
44
+ const client = createClient({ endpoints: endpoints({ region, env }), workspace, store, harness });
45
+ let result = await pairing(client);
46
+ const target = loadAccount(data).pairTargets?.[workspace];
47
+ if (result.status === 'choose') {
48
+ if (!result.candidates.some((c) => c.id === target)) {
49
+ if (target) recordPairing(data, workspace, 'requested');
50
+ return pairingLines(result);
51
+ }
52
+ result = await requestPair(client, target);
53
+ }
54
+ if (result.refused) return ['pairing requested'];
55
+ recordPairing(data, workspace, result.status, target);
47
56
  return pairingLines(result);
48
57
  } catch {
49
58
  return ['pairing requested'];
@@ -109,6 +118,11 @@ const commands = {
109
118
  if (values.device && harness !== 'cli') throw new Usage('--device is for the eocrm CLI (npx @eocrm/cli login --device)');
110
119
  const region = values.region ?? 'eu';
111
120
  const result = await login({ data, region, workspace, env, store, harness, device: values.device, sleep, print: out, openBrowser: (u) => open(u, { print: out }) });
121
+ if (!result.workspace) {
122
+ const flag = region === 'eu' ? '' : ` --region ${region}`;
123
+ [`Signed in at ${new URL(result.issuer).host} (${region})`, ...result.choices, `choose one: eocrm init${flag} <workspace> in a repository, or eocrm login${flag} <workspace> for your default`].forEach((l) => out(l));
124
+ return null;
125
+ }
112
126
  const lines = [`${who(loadAccount(data), result.workspace)} (${region})`];
113
127
  if (result.storage === 'file') lines.push(`tokens stored in ${join(data, 'credentials.json')}: no keychain found`);
114
128
  lines.push(...pairingLines(result.pairing));
@@ -134,7 +148,7 @@ const commands = {
134
148
  const { workspace, region } = resolveWorkspace({ data, cwd });
135
149
  if (!workspace || !region) throw new Usage(`workspace required: run ${cmd(harness, 'login')} first`);
136
150
  const result = await requestPair(createClient({ endpoints: endpoints({ region, env }), workspace, store, harness }), id);
137
- recordPairing(data, workspace, result.status);
151
+ recordPairing(data, workspace, result.status, id);
138
152
  pairingLines(result).forEach((l) => out(l));
139
153
  return result.status === 'standalone' ? 3 : 0;
140
154
  },
@@ -227,6 +241,7 @@ const commands = {
227
241
  if (!signedIn) await commands.login({ ...ctx, positionals: [workspace] });
228
242
  if (workspace) useWorkspace({ data, cwd, workspace });
229
243
  const target = resolveWorkspace({ data, cwd }).workspace;
244
+ if (!target) throw new Usage('workspace required: eocrm init <workspace>');
230
245
  if (signedIn && account.issuer && target) out(who(account, target));
231
246
  const launcher = installCopy(data);
232
247
  const { done, skipped, lefthook } = install(cwd, { launcher, data });
@@ -375,7 +390,7 @@ export async function main({
375
390
  // The CLI ignores plugin data env, so its sign-in never lands in a plugin's dir.
376
391
  data = harness === 'cli'
377
392
  ? dataDir({ argv: [], env: {}, data: values.data || cliData(env) })
378
- : dataDir({ argv, env, data: values.data, fallback: harness === 'codex' ? installData(script) ?? codexData(env) : undefined });
393
+ : dataDir({ argv, env, data: values.data, harness, fallback: harness === 'codex' ? installData(script) ?? codexData(env) : undefined });
379
394
  } catch (e) {
380
395
  throw new Usage(e.message);
381
396
  }