@eocrm/cli 0.0.0-stage → 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/lib/login.mjs ADDED
@@ -0,0 +1,283 @@
1
+ import { createServer } from 'node:http';
2
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import { spawn as nodeSpawn } from 'node:child_process';
4
+ import { readFileSync } from 'node:fs';
5
+ import { endpoints as regionEndpoints, SLUG } from './endpoints.mjs';
6
+ import { createClient, readCapped, userAgent } from './api.mjs';
7
+ import { storeFor } from './credentials.mjs';
8
+ import { writeJsonAtomic } from './state.mjs';
9
+ import { accountFile, loadAccount } from './workspace.mjs';
10
+
11
+ export const PORTS = [53682, 53683, 53684];
12
+ export const CLI_CLIENT_ID = '00000000-0000-4000-8000-000000000005';
13
+ export const clientName = (harness) => ({ codex: 'Codex (eocrm plugin)', cli: 'eocrm CLI' })[harness] ?? 'Claude Code (eocrm plugin)';
14
+ const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
15
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
16
+ const NOT_FOUND = 'workspace not found or Agent work is off';
17
+
18
+ export class LoginError extends Error {
19
+ constructor(message, exitCode = 3, lines = [], invalidClient = false) {
20
+ super(message);
21
+ this.name = 'LoginError';
22
+ this.exitCode = exitCode;
23
+ this.lines = lines;
24
+ this.invalidClient = invalidClient;
25
+ }
26
+ }
27
+
28
+ const isWsl = () => {
29
+ try {
30
+ return readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft');
31
+ } catch {
32
+ return false;
33
+ }
34
+ };
35
+
36
+ export function openBrowser(url, { platform = process.platform, wsl = platform === 'linux' && isWsl(), spawn = nodeSpawn, print = (l) => process.stdout.write(`${l}\n`) } = {}) {
37
+ print(`open ${url} to sign in`);
38
+ const launch = (cmd, args, fallback) => {
39
+ try {
40
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
41
+ child.on('error', () => fallback?.());
42
+ child.unref();
43
+ } catch {
44
+ fallback?.();
45
+ }
46
+ };
47
+ if (platform === 'darwin') launch('open', [url]);
48
+ else if (platform === 'win32') launch('rundll32', ['url.dll,FileProtocolHandler', url]);
49
+ else if (wsl) launch('wslview', [url], () => launch('cmd.exe', ['/c', 'start', '""', url]));
50
+ else launch('xdg-open', [url]);
51
+ }
52
+
53
+ async function post(url, body, form, harness) {
54
+ try {
55
+ const res = await fetch(url, {
56
+ method: 'POST',
57
+ redirect: 'error',
58
+ signal: AbortSignal.timeout(15000),
59
+ headers: { accept: 'application/json', 'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json', 'user-agent': userAgent(harness) },
60
+ body: form ? new URLSearchParams(body).toString() : JSON.stringify(body),
61
+ });
62
+ return { status: res.status, body: await readCapped(res).then(JSON.parse).catch(() => null) };
63
+ } catch {
64
+ throw new LoginError(`POST ${new URL(url).pathname} failed (network error)`);
65
+ }
66
+ }
67
+
68
+ async function listen(server, ports) {
69
+ for (const port of ports) {
70
+ try {
71
+ await new Promise((ok, fail) => {
72
+ server.once('error', fail);
73
+ server.listen(port, '127.0.0.1', () => {
74
+ server.off('error', fail);
75
+ ok();
76
+ });
77
+ });
78
+ return port;
79
+ } catch (e) {
80
+ if (e.code !== 'EADDRINUSE') throw e;
81
+ }
82
+ }
83
+ throw new LoginError(`ports ${ports.join(', ')} are busy`);
84
+ }
85
+
86
+ const same = (a, b) => {
87
+ if (typeof a !== 'string') return false;
88
+ const [x, y] = [Buffer.from(a), Buffer.from(b)];
89
+ return x.length === y.length && timingSafeEqual(x, y);
90
+ };
91
+
92
+ export const plain = (s) => String(s ?? '').replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, ' ').trim();
93
+ const codeOf = (r) => (typeof r.body?.code === 'string' ? plain(r.body.code) : null);
94
+ const expiry = (r) => (Number(r.body?.expires_in) > 0 ? Math.floor(Date.now() / 1000) + Number(r.body.expires_in) : null);
95
+
96
+ function page(res, status, text) {
97
+ res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }).end(`${text}\n`);
98
+ }
99
+
100
+ // The printed URL is the local /start redirect, so the state never reaches the terminal.
101
+ async function authorize({ issuer, clientId, open, timeoutMs, ports }) {
102
+ const verifier = randomBytes(32).toString('base64url');
103
+ const state = randomBytes(32).toString('base64url');
104
+ const server = createServer();
105
+ const port = await listen(server, ports);
106
+ const host = `127.0.0.1:${port}`;
107
+ const redirect = `http://${host}/callback`;
108
+ const url = new URL(`${issuer}/oauth/authorize`);
109
+ url.search = new URLSearchParams({
110
+ response_type: 'code',
111
+ client_id: clientId,
112
+ redirect_uri: redirect,
113
+ scope: 'agent:runs',
114
+ state,
115
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
116
+ code_challenge_method: 'S256',
117
+ }).toString();
118
+ let timer;
119
+ try {
120
+ const code = await new Promise((resolve, reject) => {
121
+ timer = setTimeout(() => reject(new LoginError('sign-in timed out')), timeoutMs);
122
+ const handle = (req, res) => {
123
+ // A rebound DNS name reaching this port is not the browser we opened.
124
+ if (req.method !== 'GET' || req.headers.host !== host || !req.url.startsWith('/')) return page(res, 400, 'Not a sign-in request.');
125
+ const u = new URL(req.url, redirect);
126
+ if (u.pathname === '/start') return res.writeHead(302, { location: url.href, 'cache-control': 'no-store' }).end();
127
+ if (u.pathname !== '/callback' || !same(u.searchParams.get('state'), state)) return page(res, 400, 'This sign-in link is not valid.');
128
+ const got = u.searchParams.get('code');
129
+ page(res, got ? 200 : 400, got ? 'Signed in to eocrm. You can close this tab.' : 'Sign-in was cancelled.');
130
+ if (got) resolve(got);
131
+ else reject(new LoginError('sign-in was cancelled', 3, [], u.searchParams.get('error') === 'invalid_client'));
132
+ };
133
+ server.on('request', (req, res) => {
134
+ try {
135
+ handle(req, res);
136
+ } catch {
137
+ if (!res.headersSent) page(res, 400, 'Not a sign-in request.');
138
+ }
139
+ });
140
+ Promise.resolve().then(() => open(`http://${host}/start`)).catch(() => {});
141
+ });
142
+ return { code, verifier, redirect };
143
+ } finally {
144
+ clearTimeout(timer);
145
+ server.close();
146
+ server.closeAllConnections();
147
+ }
148
+ }
149
+
150
+ async function register(issuer, account, data, ports, harness) {
151
+ const r = await post(`${issuer}/oauth/register`, { client_name: clientName(harness), redirect_uris: ports.map((p) => `http://127.0.0.1:${p}/callback`) }, false, harness);
152
+ if (r.status !== 201 || typeof r.body?.client_id !== 'string') throw new LoginError(`client registration failed (status ${r.status})`);
153
+ account.clients = { ...account.clients, [issuer]: r.body.client_id };
154
+ writeJsonAtomic(accountFile(data), account);
155
+ return r.body.client_id;
156
+ }
157
+
158
+ async function exchange({ issuer, clientId, open, timeoutMs, ports, harness }) {
159
+ const { code, verifier, redirect } = await authorize({ issuer, clientId, open, timeoutMs, ports });
160
+ const r = await post(`${issuer}/oauth/token`, { grant_type: 'authorization_code', code, redirect_uri: redirect, client_id: clientId, code_verifier: verifier }, true, harness);
161
+ if (r.status === 200 && typeof r.body?.access_token === 'string') {
162
+ return { access_token: r.body.access_token, refresh_token: r.body.refresh_token, expires_at: expiry(r), client_id: clientId };
163
+ }
164
+ const why = typeof r.body?.error === 'string' ? plain(r.body.error) : `token status ${r.status}`;
165
+ throw new LoginError(`sign-in failed (${why})`, 3, [], r.body?.error === 'invalid_client');
166
+ }
167
+
168
+ // A client eocrm has forgotten is registered again, once.
169
+ async function signIn({ issuer, account, data, open, timeoutMs, ports, harness }) {
170
+ let clientId = account.clients?.[issuer] ?? await register(issuer, account, data, ports, harness);
171
+ try {
172
+ return await exchange({ issuer, clientId, open, timeoutMs, ports, harness });
173
+ } catch (e) {
174
+ if (!e.invalidClient) throw e;
175
+ clientId = await register(issuer, account, data, ports, harness);
176
+ try {
177
+ return await exchange({ issuer, clientId, open, timeoutMs, ports, harness });
178
+ } catch (again) {
179
+ throw again.invalidClient ? new LoginError('sign-in failed (invalid_client after registering again)') : again;
180
+ }
181
+ }
182
+ }
183
+
184
+ async function deviceEndpoint(issuer, harness) {
185
+ const meta = await fetch(`${issuer}/.well-known/oauth-authorization-server`, { redirect: 'error', signal: AbortSignal.timeout(15000), headers: { accept: 'application/json', 'user-agent': userAgent(harness) } })
186
+ .then(readCapped).then(JSON.parse).catch(() => null);
187
+ const found = meta?.device_authorization_endpoint;
188
+ return URL.canParse(found) && new URL(found).origin === issuer ? found : `${issuer}/oauth/device/code`;
189
+ }
190
+
191
+ // RFC 8628; eocrm leaves the slow_down back-off to the client.
192
+ export async function deviceSignIn({ issuer, harness, print, sleep = wait, now = Date.now }) {
193
+ const r = await post(await deviceEndpoint(issuer, harness), { client_id: CLI_CLIENT_ID, scope: 'agent:runs' }, true, harness);
194
+ const b = r.body;
195
+ if (r.status !== 200 || typeof b?.device_code !== 'string' || typeof b.user_code !== 'string' || typeof b.verification_uri !== 'string') throw new LoginError(`device sign-in failed (${codeOf(r) ?? `status ${r.status}`})`);
196
+ const ours = (u) => URL.canParse(u) && new URL(u).origin === issuer;
197
+ if (!ours(b.verification_uri) || (b.verification_uri_complete != null && !ours(b.verification_uri_complete))) throw new LoginError('device sign-in failed (verification link is not on the eocrm sign-in host)');
198
+ print(`open ${plain(b.verification_uri)} and enter the code ${plain(b.user_code)}`);
199
+ if (b.verification_uri_complete != null) print(`or open ${plain(b.verification_uri_complete)}`);
200
+ let interval = Number(b.interval) > 0 ? Number(b.interval) * 1000 : 5000;
201
+ const deadline = now() + (Number(b.expires_in) > 0 ? Number(b.expires_in) : 600) * 1000;
202
+ const expired = new LoginError('the code expired: run login --device again');
203
+ for (;;) {
204
+ await sleep(interval);
205
+ if (now() >= deadline) throw expired;
206
+ const t = await post(`${issuer}/oauth/token`, { grant_type: DEVICE_GRANT, device_code: b.device_code, client_id: CLI_CLIENT_ID }, true, harness).catch(() => null);
207
+ if (!t) continue;
208
+ if (t.status === 200 && typeof t.body?.access_token === 'string') return { access_token: t.body.access_token, refresh_token: t.body.refresh_token, expires_at: expiry(t), client_id: CLI_CLIENT_ID };
209
+ const error = t.body?.error;
210
+ if (error === 'slow_down') interval += 5000;
211
+ else if (error === 'access_denied') throw new LoginError('sign-in was denied');
212
+ else if (error === 'expired_token') throw expired;
213
+ else if (error !== 'authorization_pending') throw new LoginError(`sign-in failed (${typeof error === 'string' ? plain(error) : `token status ${t.status}`})`);
214
+ }
215
+ }
216
+
217
+ export async function requestPair(client, connectionId) {
218
+ const r = await client.pair(connectionId);
219
+ if (r.status === 202) return { status: 'requested', approveUrl: plain(r.body?.approve_url) };
220
+ const code = codeOf(r);
221
+ if (code === 'agent_already_paired') return { status: 'paired' };
222
+ if (code === 'pair_request_unavailable') return { status: 'requested', approveUrl: null };
223
+ return { status: 'standalone', refused: code ?? `status ${r.status}` };
224
+ }
225
+
226
+ export async function pairing(client) {
227
+ const r = await client.pairable();
228
+ if (r.status !== 200) return { status: 'standalone', refused: codeOf(r) ?? `status ${r.status}` };
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' };
232
+ }
233
+
234
+ function pickWorkspace(r) {
235
+ if (r.status === 404) throw new LoginError('workspace required', 2);
236
+ if (r.status !== 200) throw new LoginError(`sign-in failed (${codeOf(r) ?? `status ${r.status}`})`);
237
+ const on = (Array.isArray(r.body?.items) ? r.body.items : []).filter((w) => w?.agent_work === true && typeof w.slug === 'string' && SLUG.test(w.slug));
238
+ if (!on.length) throw new LoginError(NOT_FOUND);
239
+ if (on.length > 1) throw new LoginError('workspace required', 2, on.map((w) => `workspace ${w.slug} ${plain(w.name).replace(/\s+/g, ' ')}`));
240
+ return on[0].slug;
241
+ }
242
+
243
+ export function recordPairing(data, workspace, status) {
244
+ const account = loadAccount(data);
245
+ writeJsonAtomic(accountFile(data), { ...account, workspaces: { ...account.workspaces, [workspace]: status } });
246
+ }
247
+
248
+ 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 }) {
249
+ store ??= storeFor(data, harness);
250
+ if (!region) throw new LoginError('region required', 2);
251
+ if (workspace != null && !SLUG.test(workspace)) throw new LoginError('invalid workspace slug', 2);
252
+ let ep;
253
+ try {
254
+ ep = regionEndpoints({ region, env });
255
+ } catch (e) {
256
+ throw new LoginError(e.message.replace(/^eocrm: /, ''), 2);
257
+ }
258
+ const stored = loadAccount(data);
259
+ const account = stored.issuer === ep.issuer ? stored : { clients: stored.clients, keys: stored.keys, region, issuer: ep.issuer };
260
+ account.region = region;
261
+ account.keys = [...new Set([...(Array.isArray(account.keys) ? account.keys : []), ep.key])];
262
+ const client = (ws) => createClient({ endpoints: ep, workspace: ws ?? null, store, harness });
263
+ const probe = () => (workspace ? client(workspace).conventions() : client(null).workspaces());
264
+
265
+ let storage = await store.where(ep.key);
266
+ let first = (await store.get(ep.key))?.access_token ? await probe() : { status: 401 };
267
+ if (first.status === 401) {
268
+ storage = await store.set(ep.key, await (device ? deviceSignIn({ issuer: ep.issuer, harness, print, sleep }) : signIn({ issuer: ep.issuer, account, data, open, timeoutMs, ports, harness })));
269
+ writeJsonAtomic(accountFile(data), account);
270
+ first = await probe();
271
+ }
272
+ if (!workspace) {
273
+ workspace = pickWorkspace(first);
274
+ first = await client(workspace).conventions();
275
+ }
276
+ const code = codeOf(first);
277
+ if (first.status === 404 || first.status === 403) throw new LoginError(code ? `${NOT_FOUND} (${code})` : NOT_FOUND);
278
+ if (first.status !== 200) throw new LoginError(`sign-in failed (${code ?? `status ${first.status}`})`);
279
+
280
+ const paired = await pairing(client(workspace));
281
+ writeJsonAtomic(accountFile(data), { ...account, workspace, signedInAt: Date.now(), workspaces: { ...account.workspaces, [workspace]: paired.status } });
282
+ return { workspace, storage, pairing: paired };
283
+ }
package/lib/outbox.mjs ADDED
@@ -0,0 +1,130 @@
1
+ import { appendFileSync, readFileSync, readdirSync, renameSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomBytes, randomUUID } from 'node:crypto';
4
+ import { withLock, readJson, writeJsonAtomic, writeFileAtomic, remove, LockTimeout } from './state.mjs';
5
+ import { cleanEvent } from './api.mjs';
6
+ import { clean, LIMITS } from './scrub.mjs';
7
+
8
+ export const MAX_ENTRIES = 2000;
9
+ export const MAX_SPILLS = 50;
10
+ const SPILL_LOCK_MS = 500;
11
+
12
+ const file = (data) => join(data, 'outbox.jsonl');
13
+ const SPILL = /^outbox\.\d+\.[0-9a-f]+\.jsonl$/;
14
+ const LIFECYCLE = new Set(['start', 'finish']);
15
+
16
+ function parse(path) {
17
+ let text;
18
+ try {
19
+ text = readFileSync(path, 'utf8');
20
+ } catch {
21
+ return [];
22
+ }
23
+ return text.split('\n').flatMap((line) => {
24
+ try {
25
+ const entry = JSON.parse(line);
26
+ return entry && typeof entry === 'object' && typeof entry.sessionId === 'string' ? [entry] : [];
27
+ } catch {
28
+ return [];
29
+ }
30
+ });
31
+ }
32
+
33
+ export const readOutbox = (data) => parse(file(data));
34
+
35
+ const lines = (entries) => entries.map((e) => `${JSON.stringify(e)}\n`).join('');
36
+ export const writeOutbox = (data, entries) => writeFileAtomic(file(data), lines(entries));
37
+
38
+ const spills = (data) => {
39
+ try {
40
+ return readdirSync(data).filter((f) => SPILL.test(f)).map((f) => join(data, f));
41
+ } catch {
42
+ return [];
43
+ }
44
+ };
45
+
46
+ const replaces = (a, b) => a.sessionId === b.sessionId && a.kind === b.kind && (a.kind !== 'event' || a.event.id === b.event.id);
47
+ const admit = (entries, entry) => [...entries.filter((e) => !replaces(e, entry)), entry];
48
+
49
+ function prepared(entry) {
50
+ const next = { ...entry, seq: randomUUID() };
51
+ if (entry.kind === 'event') next.event = cleanEvent(entry.event);
52
+ if (entry.kind === 'step') next.step = clean(entry.step, LIMITS.stepLabel);
53
+ return next;
54
+ }
55
+
56
+ const droppedLog = (data) => join(data, 'dropped.log');
57
+
58
+ // Spill drops append one byte each (O_APPEND, no lock); rewrite folds them into dropped.json.
59
+ function foldDropped(data) {
60
+ const taken = `${droppedLog(data)}.${process.pid}.${randomBytes(4).toString('hex')}`;
61
+ try {
62
+ renameSync(droppedLog(data), taken);
63
+ } catch {
64
+ return 0;
65
+ }
66
+ let size;
67
+ try {
68
+ size = statSync(taken).size;
69
+ } catch {
70
+ size = 0;
71
+ }
72
+ remove(taken);
73
+ return size;
74
+ }
75
+
76
+ function capped(data, entries, alsoDropped = 0) {
77
+ const over = Math.max(0, entries.length - MAX_ENTRIES);
78
+ if (over + alsoDropped > 0) {
79
+ const dropped = join(data, 'dropped.json');
80
+ writeJsonAtomic(dropped, { count: (Number(readJson(dropped, {}).count) || 0) + over + alsoDropped });
81
+ }
82
+ if (over <= 0) return entries;
83
+ const rank = (e) => (e.kind === 'event' ? 0 : LIFECYCLE.has(e.kind) ? 2 : 1);
84
+ const gone = new Set([...entries].sort((a, b) => rank(a) - rank(b)).slice(0, over));
85
+ return entries.filter((e) => !gone.has(e));
86
+ }
87
+
88
+ // Caller holds withLock(data). Merges spills left by enqueues that timed out on the lock.
89
+ export function rewrite(data, fn) {
90
+ const spilled = spills(data);
91
+ let entries = readOutbox(data);
92
+ for (const path of spilled) for (const e of parse(path)) entries = admit(entries, e);
93
+ writeOutbox(data, capped(data, fn(entries), foldDropped(data)));
94
+ for (const path of spilled) remove(path);
95
+ }
96
+
97
+ export const append = (data, ...added) => rewrite(data, (entries) => added.reduce((all, e) => admit(all, prepared(e)), entries));
98
+
99
+ // The spill lock makes count-then-write atomic across processes; a finish is never dropped.
100
+ async function spill(data, entry) {
101
+ try {
102
+ await withLock(join(data, 'spill'), async () => {
103
+ if (spills(data).length >= MAX_SPILLS) throw new Error('eocrm: spill cap');
104
+ writeFileAtomic(join(data, `outbox.${process.pid}.${randomBytes(6).toString('hex')}.jsonl`), lines([entry]));
105
+ }, { giveUpMs: SPILL_LOCK_MS });
106
+ return true;
107
+ } catch {
108
+ if (entry.kind === 'finish') writeFileAtomic(join(data, `outbox.${process.pid}.${randomBytes(6).toString('hex')}.jsonl`), lines([entry]));
109
+ else appendFileSync(droppedLog(data), '.');
110
+ return entry.kind === 'finish';
111
+ }
112
+ }
113
+
114
+ // True when the entry reached the outbox or a spill file.
115
+
116
+ export async function enqueue(data, entry, lock) {
117
+ try {
118
+ const next = prepared(entry);
119
+ try {
120
+ await withLock(data, async () => rewrite(data, (entries) => admit(entries, next)), lock);
121
+ return true;
122
+ } catch (e) {
123
+ if (!(e instanceof LockTimeout)) return false;
124
+ return await spill(data, next);
125
+ }
126
+ } catch {
127
+ // tracking goes stale; a hook must never fail the session
128
+ return false;
129
+ }
130
+ }
package/lib/paths.mjs ADDED
@@ -0,0 +1,53 @@
1
+ import { chmodSync, mkdirSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join, posix, resolve, sep, win32 } from 'node:path';
4
+
5
+ export function dataDir({ argv, env, data, fallback }) {
6
+ const eq = argv.find((a) => a.startsWith('--data='));
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;
9
+ if (!dir) throw new Error('eocrm: no data dir');
10
+ mkdirSync(dir, { recursive: true });
11
+ if (process.platform !== 'win32') {
12
+ try {
13
+ chmodSync(dir, 0o700);
14
+ } catch {
15
+ // not ours or read-only: use it as it is
16
+ }
17
+ }
18
+ return dir;
19
+ }
20
+
21
+ export function parseArgs(argv) {
22
+ const hi = argv.indexOf('--harness');
23
+ const harness = hi >= 0 && ['codex', 'cli'].includes(argv[hi + 1]) ? argv[hi + 1] : 'claude';
24
+ const event = argv.find((a, i) => !a.startsWith('--') && argv[i - 1] !== '--data' && argv[i - 1] !== '--harness');
25
+ return { event, harness };
26
+ }
27
+
28
+ const codexHome = (env) => resolve(env.CODEX_HOME || join(homedir(), '.codex'));
29
+
30
+ export const codexData = (env) => join(codexHome(env), 'plugins', 'data', 'eocrm-eocrm');
31
+
32
+ const CACHED = /^(.+)[\\/]plugins[\\/]cache[\\/]([^\\/]+)[\\/]([^\\/]+)[\\/][^\\/]+[\\/]scripts[\\/][^\\/]+$/;
33
+
34
+ // <home>/plugins/cache/<marketplace>/<plugin>/<version>/scripts/x → <home>/plugins/data/<plugin>-<marketplace>
35
+ export function installData(script) {
36
+ const m = CACHED.exec(resolve(script));
37
+ return m ? join(m[1], 'plugins', 'data', `${m[3]}-${m[2]}`) : undefined;
38
+ }
39
+
40
+ export function cliData(env, platform = process.platform, home = homedir()) {
41
+ const path = platform === 'win32' ? win32 : posix;
42
+ const xdg = env.XDG_DATA_HOME ?? '';
43
+ if (platform === 'win32' ? /^(?:[A-Za-z]:[\\/]|\\\\)/.test(xdg) : posix.isAbsolute(xdg)) return path.join(xdg, 'eocrm');
44
+ if (platform === 'win32' && env.APPDATA) return path.join(env.APPDATA, 'eocrm');
45
+ return path.join(home, '.local', 'share', 'eocrm');
46
+ }
47
+
48
+ export function cliHarness({ flag, env, script }) {
49
+ if (flag) return flag === 'codex' ? 'codex' : 'claude';
50
+ if (env.CLAUDECODE || env.CLAUDE_PLUGIN_ROOT || env.CLAUDE_PLUGIN_DATA) return 'claude';
51
+ if (env.PLUGIN_ROOT || env.PLUGIN_DATA || env.CODEX_THREAD_ID) return 'codex';
52
+ return resolve(script).startsWith(join(codexHome(env), 'plugins') + sep) ? 'codex' : 'claude';
53
+ }