@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.
@@ -0,0 +1,207 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { withLock, readJson, writeJsonAtomic, remove } from './state.mjs';
5
+
6
+ const SERVICE = 'eocrm-claude-plugin';
7
+ const PRIVATE = { mode: 0o600 };
8
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
9
+ const PS_ARGS = ['-NoProfile', '-NonInteractive', '-Command', '-'];
10
+
11
+ export function spawnWithStdin(cmd, args, stdin = '', { timeoutMs = 15000 } = {}) {
12
+ return new Promise((resolve) => {
13
+ const done = (code, stdout = '') => resolve({ code, stdout });
14
+ let child;
15
+ try {
16
+ child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'ignore'], timeout: timeoutMs, windowsHide: true });
17
+ } catch {
18
+ return done(-1);
19
+ }
20
+ let out = '';
21
+ child.stdout.setEncoding('utf8').on('data', (d) => { out += d; });
22
+ child.stdin.on('error', () => {});
23
+ child.on('error', () => done(-1));
24
+ child.on('close', (code) => done(code ?? -1, out));
25
+ child.stdin.end(stdin);
26
+ });
27
+ }
28
+
29
+ const b64 = (s) => Buffer.from(s, 'utf8').toString('base64');
30
+
31
+ function asTokens(v) {
32
+ return v && typeof v === 'object' && typeof v.access_token === 'string' ? v : null;
33
+ }
34
+
35
+ function decode(s) {
36
+ try {
37
+ return asTokens(JSON.parse(Buffer.from(s.trim(), 'base64').toString('utf8')));
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ function lineTool(call, { set, get, del }) {
44
+ return {
45
+ async get(issuer, opts) {
46
+ const [cmd, args] = get(issuer);
47
+ const r = await call(cmd, args, '', opts);
48
+ return r.code === 0 && r.stdout.trim() ? decode(r.stdout) : null;
49
+ },
50
+ async set(issuer, tokens) {
51
+ const secret = b64(JSON.stringify(tokens));
52
+ const cmd = set(issuer, secret);
53
+ if (!cmd || (await call(...cmd)).code !== 0) return false;
54
+ const r = await call(...get(issuer));
55
+ return r.code === 0 && r.stdout.trim() === secret;
56
+ },
57
+ async del(issuer) {
58
+ await call(...del(issuer));
59
+ },
60
+ };
61
+ }
62
+
63
+ const SECURITY_LINE_MAX = 3500;
64
+
65
+ const darwin = (call, service) => lineTool(call, {
66
+ set: (a, s) => {
67
+ const line = `add-generic-password -U -s "${service}" -a "${a}" -w "${s}"\n`;
68
+ return Buffer.byteLength(line) > SECURITY_LINE_MAX ? null : ['security', ['-i'], line];
69
+ },
70
+ get: (a) => ['security', ['find-generic-password', '-s', service, '-a', a, '-w']],
71
+ del: (a) => ['security', ['delete-generic-password', '-s', service, '-a', a]],
72
+ });
73
+
74
+ const linux = (call, service) => lineTool(call, {
75
+ set: (a, s) => ['secret-tool', ['store', `--label=${service}`, 'service', service, 'account', a], s],
76
+ get: (a) => ['secret-tool', ['lookup', 'service', service, 'account', a]],
77
+ del: (a) => ['secret-tool', ['clear', 'service', service, 'account', a]],
78
+ });
79
+
80
+ function win32(call, data) {
81
+ const path = join(data, 'credentials.dpapi');
82
+ const ps = (line, opts) => call('powershell', PS_ARGS, `$ErrorActionPreference='Stop'\nAdd-Type -AssemblyName System.Security\n${line}\n\n`, opts);
83
+ const dpapi = async (fn, b64in, opts) => {
84
+ const r = await ps(`[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::${fn}([Convert]::FromBase64String('${b64in}'),$null,'CurrentUser'))`, opts);
85
+ return r.code === 0 ? r.stdout.trim() : null;
86
+ };
87
+ const read = async (opts) => {
88
+ if (!existsSync(path)) return {};
89
+ const { blob } = readJson(path, {});
90
+ if (typeof blob !== 'string' || !BASE64.test(blob)) return null;
91
+ const plain = await dpapi('Unprotect', blob, opts);
92
+ try {
93
+ return plain === null ? null : JSON.parse(Buffer.from(plain, 'base64').toString('utf8'));
94
+ } catch {
95
+ return null;
96
+ }
97
+ };
98
+ const write = async (map) => {
99
+ if (!Object.keys(map).length) {
100
+ remove(path);
101
+ return true;
102
+ }
103
+ const json = JSON.stringify(map);
104
+ const blob = await dpapi('Protect', b64(json));
105
+ if (blob === null) return false;
106
+ try {
107
+ writeJsonAtomic(path, { blob }, PRIVATE);
108
+ } catch {
109
+ return false;
110
+ }
111
+ return JSON.stringify(await read()) === json;
112
+ };
113
+ return {
114
+ async get(issuer, opts) {
115
+ return asTokens((await read(opts))?.[issuer]);
116
+ },
117
+ async set(issuer, tokens) {
118
+ const map = await read();
119
+ return map !== null && write({ ...map, [issuer]: tokens });
120
+ },
121
+ async del(issuer) {
122
+ const map = await read();
123
+ if (map && issuer in map) {
124
+ delete map[issuer];
125
+ await write(map);
126
+ }
127
+ },
128
+ };
129
+ }
130
+
131
+ function checkIssuer(issuer) {
132
+ if (typeof issuer !== 'string' || !/^https?:\/\/[^\s"'\\]+(?: https?:\/\/[^\s"'\\]+)?$/.test(issuer)) throw new Error('eocrm: invalid issuer');
133
+ }
134
+
135
+ export const storeFor = (data, harness) => credentialStore({ data, service: harness === 'cli' ? 'eocrm-cli' : SERVICE });
136
+
137
+ export function credentialStore({ data, platform = process.platform, run = spawnWithStdin, service = SERVICE }) {
138
+ const call = async (...a) => {
139
+ try {
140
+ return await run(...a);
141
+ } catch {
142
+ return { code: -1, stdout: '' };
143
+ }
144
+ };
145
+ const keychain = { darwin, linux, win32 }[platform]?.(call, platform === 'win32' ? data : service) ?? null;
146
+ const file = join(data, 'credentials.json');
147
+ const readFile = () => {
148
+ const map = readJson(file, {});
149
+ return map && typeof map === 'object' && !Array.isArray(map) ? map : {};
150
+ };
151
+ const dropFromFile = (issuer) => {
152
+ const map = readFile();
153
+ if (!(issuer in map)) return;
154
+ delete map[issuer];
155
+ if (Object.keys(map).length) writeJsonAtomic(file, map, PRIVATE);
156
+ else remove(file);
157
+ };
158
+ const locked = (fn, opts) => withLock(join(data, 'credentials.lock'), fn, opts);
159
+ const read = async (issuer, timeoutMs) => (keychain && await keychain.get(issuer, timeoutMs ? { timeoutMs } : undefined)) ?? asTokens(readFile()[issuer]);
160
+ const save = async (issuer, tokens) => {
161
+ if (keychain && await keychain.set(issuer, tokens)) {
162
+ dropFromFile(issuer);
163
+ return 'keychain';
164
+ }
165
+ try {
166
+ await keychain?.del(issuer);
167
+ } catch {
168
+ // best effort: the file write below must still happen
169
+ }
170
+ writeJsonAtomic(file, { ...readFile(), [issuer]: tokens }, PRIVATE);
171
+ return 'file';
172
+ };
173
+
174
+ return {
175
+ async get(issuer, { timeoutMs } = {}) {
176
+ checkIssuer(issuer);
177
+ return read(issuer, timeoutMs);
178
+ },
179
+ async set(issuer, tokens) {
180
+ checkIssuer(issuer);
181
+ return locked(() => save(issuer, tokens));
182
+ },
183
+ async update(issuer, fn, { timeoutMs } = {}) {
184
+ checkIssuer(issuer);
185
+ return locked(async () => {
186
+ const latest = await read(issuer, timeoutMs);
187
+ const next = await fn(latest);
188
+ if (next && next !== latest) await save(issuer, next);
189
+ return next;
190
+ }, timeoutMs ? { giveUpMs: timeoutMs } : undefined);
191
+ },
192
+ async where(issuer) {
193
+ checkIssuer(issuer);
194
+ return readFile()[issuer] ? 'file' : 'keychain';
195
+ },
196
+ // `when` sees the stored tokens under the lock; false keeps them.
197
+ async del(issuer, { when, timeoutMs } = {}) {
198
+ checkIssuer(issuer);
199
+ return locked(async () => {
200
+ if (when && !when(await read(issuer, timeoutMs))) return false;
201
+ if (keychain) await keychain.del(issuer);
202
+ dropFromFile(issuer);
203
+ return true;
204
+ }, timeoutMs ? { giveUpMs: timeoutMs } : undefined);
205
+ },
206
+ };
207
+ }
package/lib/detect.mjs ADDED
@@ -0,0 +1,279 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { basename, dirname, join, win32 } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { repoSlug, branchCommits, budget, localBranches, prView, prState } from './git.mjs';
6
+ import { git, worktreeOf, loadWorktree, saveWorktree, readJson, writeJsonAtomic } from './state.mjs';
7
+ import { append } from './outbox.mjs';
8
+ import { eventId } from './ids.mjs';
9
+ import { clean, LIMITS } from './scrub.mjs';
10
+ import { pathFor } from './plans.mjs';
11
+
12
+ const MARK = /^test:\s*/;
13
+ const SUMMARY = /\b(pass(ed)?|fail(ed|ures?)?|errors?|tests?|ok)\b/i;
14
+ const EXIT = /Exit code (\d+)/;
15
+ const COMMIT = /\bgit\b[^|;&\n]*\bcommit\b/;
16
+ const PR_URL = /https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/(\d+)/;
17
+ const WRAPPER = new Set(['sudo', 'time', 'env', 'nice', 'nohup', 'exec', 'command']);
18
+ const ASSIGNMENT = /^[A-Za-z_]\w*=/;
19
+ const MAX_PARSE = 64 * 1024;
20
+ const ANSI = new RegExp(String.raw`\x1b\[[0-9;?]*[ -/]*[@-~]`, 'g');
21
+ const TAIL = 64 * 1024;
22
+ const KEEP_COMMITS = 1000;
23
+ const DETECT_MS = 8000;
24
+ const KEEP_PRS = 100;
25
+ const AGENT = new Set(['Agent', 'Task']);
26
+ export const TASK_KEY = /(?<![A-Za-z0-9])[A-Z][A-Z0-9]{1,9}-[0-9]+(?![A-Za-z0-9])/;
27
+ const KEEP_PATHS = 50;
28
+ const MSYS_DRIVE = /^\/([A-Za-z])(?:\/|$)/;
29
+
30
+ const isBash = (input) => input?.tool_name === 'Bash' && typeof input.tool_input?.command === 'string';
31
+
32
+ export function output(input) {
33
+ if (input.hook_event_name === 'PostToolUseFailure') {
34
+ const error = String(input.error ?? '');
35
+ const code = EXIT.exec(error);
36
+ return code && { exit: Number(code[1]), text: error.slice(code.index + code[0].length) };
37
+ }
38
+ const r = input.tool_response;
39
+ if (typeof r === 'string') return { exit: null, text: r };
40
+ if (!r || r.interrupted) return null;
41
+ return { exit: r.exit === undefined ? 0 : Number.isInteger(r.exit) ? r.exit : null, text: [r.stdout, r.stderr].filter((s) => typeof s === 'string').join('\n') };
42
+ }
43
+
44
+ // Shell words per segment, split on unquoted ; & | ( ) and newlines.
45
+ export function segments(command) {
46
+ const out = [[]];
47
+ let word = null;
48
+ let quote = null;
49
+ const end = () => {
50
+ if (word !== null) out.at(-1).push(word);
51
+ word = null;
52
+ };
53
+ const text = command.slice(0, MAX_PARSE);
54
+ for (let i = 0; i < text.length; i++) {
55
+ const c = text[i];
56
+ if (quote) {
57
+ if (c === quote) quote = null;
58
+ else word += c === '\\' && quote === '"' && /["\\$`]/.test(text[i + 1] ?? '') ? text[++i] : c;
59
+ } else if (c === "'" || c === '"') {
60
+ quote = c;
61
+ word ??= '';
62
+ } else if (c === '\\' && i + 1 < text.length) word = (word ?? '') + text[++i];
63
+ else if (/[;&|()\n]/.test(c)) {
64
+ end();
65
+ if (out.at(-1).length) out.push([]);
66
+ } else if (/\s/.test(c)) end();
67
+ else word = (word ?? '') + c;
68
+ }
69
+ end();
70
+ return out.filter((s) => s.length);
71
+ }
72
+
73
+ function commandWords(words) {
74
+ let i = 0;
75
+ while (i < words.length && (ASSIGNMENT.test(words[i]) || WRAPPER.has(words[i]) || (i > 0 && WRAPPER.has(words[i - 1]) && words[i].startsWith('-')))) i++;
76
+ const rest = words.slice(i);
77
+ if (rest.length) rest[0] = rest[0].split(/[\\/]/).at(-1);
78
+ return rest;
79
+ }
80
+
81
+ export const segmentWords = (command) => segments(command).map(commandWords).filter((w) => w.length);
82
+
83
+ export function testRun(input) {
84
+ if (!isBash(input) || input.tool_input.run_in_background || input.is_interrupt) return null;
85
+ const { command, description } = input.tool_input;
86
+ if (typeof description !== 'string' || !MARK.test(description)) return null;
87
+ const label = description.replace(MARK, '').trim();
88
+ const out = output(input);
89
+ if (!label || !out) return null;
90
+ const line = out.text.slice(-TAIL).replace(ANSI, '').split(/\r?\n|\r/).map((l) => l.trim()).findLast((l) => SUMMARY.test(l));
91
+ return { command: clean(command, LIMITS.testCommand), label: clean(label, LIMITS.stepLabel), result_line: line ? clean(line, LIMITS.resultLine) : null, exit_code: out.exit };
92
+ }
93
+
94
+ export const isCommit = (command) => COMMIT.test(command);
95
+
96
+ const MERGE_VALUE_FLAG = /^(-[bFtAR]|--(repo|body|body-file|subject|author-email|match-head-commit))$/;
97
+ const CREATE_HEAD_FLAG = /^(-H|--head)$/;
98
+
99
+ function argOf(args, valueFlag) {
100
+ for (let i = 0; i < args.length; i++) {
101
+ if (valueFlag.test(args[i])) i++;
102
+ else if (!args[i].startsWith('-')) return args[i].replace(/^#(?=\d+$)/, '');
103
+ }
104
+ return null;
105
+ }
106
+
107
+ const flagValue = (args, flag) => {
108
+ const i = args.findIndex((a) => flag.test(a));
109
+ return i >= 0 ? args[i + 1] ?? null : (args.find((a) => /^--head=/.test(a))?.slice(7) ?? null);
110
+ };
111
+
112
+ const pr = (action, url, extra = {}) => {
113
+ const m = PR_URL.exec(url ?? '');
114
+ return m && { action, url: m[0], number: Number(m[1]), ...extra };
115
+ };
116
+
117
+ const ghPr = (command, sub) => segmentWords(command).find((w) => w[0] === 'gh' && w[1] === 'pr' && w[2] === sub)?.slice(3);
118
+
119
+ // open() is [{branch, url}] recorded at create; it outlives a branch that --delete-branch removed.
120
+ const CONFIRM = { opened: 'OPEN', merged: 'MERGED' };
121
+ const GH_EXISTS = /a pull request for branch "[^"]*" into branch "[^"]*" already exists/;
122
+
123
+ // Codex reports failed commands too, without an exit code: ask GitHub before trusting the output.
124
+ export function prEvent(input, { state = () => null, ...opts } = {}) {
125
+ const e = prGuess(input, opts);
126
+ const out = output(input);
127
+ if (!e || out?.exit !== null) return e;
128
+ if (e.action === 'opened' && GH_EXISTS.test(out.text)) return null;
129
+ return state(e.url) === CONFIRM[e.action] ? e : null;
130
+ }
131
+
132
+ function prGuess(input, { view = prView, open = () => [], branch = () => null, branches = () => null } = {}) {
133
+ if (!isBash(input) || input.hook_event_name === 'PostToolUseFailure') return null;
134
+ const { command } = input.tool_input;
135
+ const create = ghPr(command, 'create');
136
+ if (create) return pr('opened', output(input)?.text.slice(-TAIL), { branch: flagValue(create, CREATE_HEAD_FLAG) ?? branch() });
137
+ const args = ghPr(command, 'merge');
138
+ if (!args || args.some((a) => a === '--auto' || a === '--disable-auto')) return null;
139
+ const arg = argOf(args, MERGE_VALUE_FLAG);
140
+ if (PR_URL.test(arg ?? '')) return pr('merged', arg);
141
+ const stored = open();
142
+ const byNumber = (n) => stored.find((p) => PR_URL.exec(p.url)?.[1] === n);
143
+ if (arg) return pr('merged', (/^\d+$/.test(arg) ? byNumber(arg) : stored.find((p) => p.branch === arg))?.url ?? view(input.cwd, arg));
144
+ const current = branch();
145
+ const hit = stored.find((p) => p.branch && p.branch === current);
146
+ if (hit) return pr('merged', hit.url);
147
+ if (!args.some((a) => a === '-d' || a === '--delete-branch')) return pr('merged', view(input.cwd, null));
148
+ const local = branches();
149
+ const gone = local ? stored.filter((p) => p.branch && !local.includes(p.branch)) : [];
150
+ return gone.length === 1 ? pr('merged', gone[0].url) : null;
151
+ }
152
+
153
+ export function sddStep(input, ledgerPresent) {
154
+ if (!ledgerPresent || !AGENT.has(input?.tool_name)) return null;
155
+ const r = input.tool_response;
156
+ const background = input.tool_input?.run_in_background === true || r?.isAsync === true || r?.status === 'async_launched';
157
+ const phase = { PreToolUse: 'started', PostToolUse: background ? null : 'finished' }[input.hook_event_name];
158
+ const label = input.tool_input?.description;
159
+ if (!phase || typeof label !== 'string' || !label.trim()) return null;
160
+ return { phase, label: clean(label, LIMITS.stepLabel) };
161
+ }
162
+
163
+ // agent-<id>.meta.json is undocumented Claude Code internals.
164
+ export function subagentFinish(input) {
165
+ const tp = input.transcript_path;
166
+ const path = typeof input.agent_transcript_path === 'string' && input.agent_transcript_path ? input.agent_transcript_path
167
+ : typeof tp === 'string' && /^[\w-]+$/.test(input.agent_id ?? '') ? join(dirname(tp), basename(tp, '.jsonl'), 'subagents', `agent-${input.agent_id}.jsonl`) : null;
168
+ const meta = path ? readJson(path.replace(/\.jsonl$/, '.meta.json'), null) : null;
169
+ if (meta?.requestShape !== 'background' || typeof meta.toolUseId !== 'string') return null;
170
+ return { ...input, hook_event_name: 'PostToolUse', tool_name: 'Agent', tool_use_id: meta.toolUseId, tool_input: { description: meta.description }, tool_response: {} };
171
+ }
172
+
173
+ export function ledgerPresent(root) {
174
+ try {
175
+ const dir = join(root, '.superpowers', 'sdd');
176
+ return readdirSync(dir).some((d) => existsSync(join(dir, d, 'progress.md')));
177
+ } catch {
178
+ return false;
179
+ }
180
+ }
181
+
182
+ // The call's directory: hook cwd, Codex workdir, then a leading cd; null when a cd leaves it unknown.
183
+ function callDir(input) {
184
+ const cwd = pathFor(input.cwd).resolve(input.cwd, typeof input.tool_input?.workdir === 'string' ? input.tool_input.workdir : '.');
185
+ const first = isBash(input) ? segments(input.tool_input.command)[0] : null;
186
+ if (first?.[0] !== 'cd') return cwd;
187
+ if (first.length === 1 || first[1] === '-') return null;
188
+ if (first.length !== 2 || first[1].startsWith('-')) return cwd;
189
+ return cdTarget(cwd, first[1].replace(/^~(?=\/|$)/, homedir()));
190
+ }
191
+
192
+ // Git-bash on Windows spells C:\x as /c/x.
193
+ export function cdTarget(cwd, arg) {
194
+ const p = pathFor(cwd);
195
+ return p.resolve(cwd, p === win32 ? arg.replace(MSYS_DRIVE, (_, d) => `${d.toUpperCase()}:/`) : arg);
196
+ }
197
+
198
+ const branchOf = (gitDir) => {
199
+ try {
200
+ return /^ref: refs\/heads\/(.+)/.exec(readFileSync(join(gitDir, 'HEAD'), 'utf8'))?.[1] ?? '';
201
+ } catch {
202
+ return '';
203
+ }
204
+ };
205
+
206
+ // The worktree key and git dir are cached per session; the branch is read from HEAD on every call.
207
+ function worktreeTask(ctx, input, run) {
208
+ try {
209
+ const dir = callDir(input);
210
+ if (!dir || !existsSync(dir) || !/^[\w-]+$/.test(input.session_id)) return null;
211
+ const file = join(ctx.data, 'paths', `${input.session_id}.json`);
212
+ const cache = readJson(file, {});
213
+ let hit = cache[dir];
214
+ if (!hit) {
215
+ const [top, gitDir] = git(dir, ['rev-parse', '--show-toplevel', '--absolute-git-dir'], run).split('\n');
216
+ hit = { key: worktreeOf(dir, run, top ?? '').key, gitDir: gitDir ?? '' };
217
+ if (gitDir) writeJsonAtomic(file, Object.fromEntries([...Object.entries(cache), [dir, hit]].slice(-KEEP_PATHS)));
218
+ }
219
+ return loadWorktree(ctx.data, hit.key).taskKey ?? (hit.gitDir ? TASK_KEY.exec(branchOf(hit.gitDir))?.[0] : null) ?? null;
220
+ } catch {
221
+ return null;
222
+ }
223
+ }
224
+
225
+ // Git runs now, outside the lock; the session's task is read under it.
226
+ export function taskFor(ctx, input, run = budget(DETECT_MS, ctx.git)) {
227
+ const own = worktreeTask(ctx, input, run);
228
+ return (session) => own ?? session?.start?.task ?? null;
229
+ }
230
+
231
+ // Git and gh run before the lock, inside one budget; the returned closure queues under it.
232
+ export function detector(ctx, input) {
233
+ const { data } = ctx;
234
+ const sid = input.session_id;
235
+ const run = budget(DETECT_MS, ctx.git);
236
+ const command = input.tool_name === 'Bash' ? String(input.tool_input?.command ?? '') : '';
237
+ const called = callDir(input);
238
+ const dir = called && existsSync(called) ? called : input.cwd;
239
+ let wt;
240
+ const wtOf = () => (wt ??= worktreeOf(dir, run));
241
+ const test = testRun(input);
242
+ const commits = command && isCommit(command) ? branchCommits(dir, 200, run) : [];
243
+ const repo = commits.length ? repoSlug(dir, git(dir, ['remote', 'get-url', 'origin'], run)) : null;
244
+ const pull = prEvent(input, {
245
+ view: (_, arg) => prView(dir, arg, run),
246
+ state: (url) => prState(dir, url, run),
247
+ open: () => loadWorktree(data, wtOf().key).openPrs.filter((p) => typeof p?.url === 'string'),
248
+ branch: () => git(dir, ['symbolic-ref', '--short', '-q', 'HEAD'], run) || null,
249
+ branches: () => localBranches(dir, run),
250
+ });
251
+ const agentStep = sddStep(input, true);
252
+ const step = agentStep && ledgerPresent(wtOf().root) ? agentStep : null;
253
+ if (!test && !pull && !commits.length && !step) return () => false;
254
+ if (commits.length || pull) wtOf();
255
+
256
+ return (current, at, task_key = null) => {
257
+ const occurred_at = new Date(at).toISOString();
258
+ const queued = [];
259
+ const queue = (type, key, fields) => queued.push({ kind: 'event', sessionId: sid, event: { id: eventId(type, key), type, occurred_at, ...fields, task_key } });
260
+ if (test) queue('test_run', `${current.clientRunId}:${input.tool_use_id ?? randomUUID()}`, test);
261
+ if (step) queue('step', `${input.tool_use_id ?? randomUUID()}${step.phase}`, step);
262
+ if (commits.length || pull) {
263
+ const worktree = loadWorktree(data, wt.key);
264
+ const reported = new Set(worktree.reportedCommits);
265
+ const fresh = commits.filter((c) => !reported.has(c.sha));
266
+ for (const c of fresh) queue('commit', c.sha, { sha: c.sha, subject: c.subject, ...(repo ? { repo } : {}) });
267
+ let openPrs = worktree.openPrs.filter((p) => typeof p?.url === 'string');
268
+ if (pull) {
269
+ const { branch, ...event } = pull;
270
+ queue('pull_request', `${pull.action}:${pull.url}`, { ...event, repo: pull.url.split('/').slice(3, 5).join('/') });
271
+ openPrs = openPrs.filter((p) => p.url !== pull.url);
272
+ if (pull.action === 'opened') openPrs = [...openPrs, { branch, url: pull.url }].slice(-KEEP_PRS);
273
+ }
274
+ saveWorktree(data, wt.key, { root: wt.root, reportedCommits: [...worktree.reportedCommits, ...fresh.map((c) => c.sha)].slice(-KEEP_COMMITS), openPrs });
275
+ }
276
+ if (queued.length) append(data, ...queued);
277
+ return queued.length > 0;
278
+ };
279
+ }
@@ -0,0 +1,46 @@
1
+ export const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
2
+ export const REGIONS = ['eu', 'ru'];
3
+ const PROBE = 'x0probe0x';
4
+ const LOOPBACK = new Set(['127.0.0.1', '[::1]', 'localhost']);
5
+ const DEV_HOST = /(?:^|\.)eocrm(?:-test)?\.local$/;
6
+ const REFUSED = 'eocrm: EOCRM_ENDPOINTS needs {issuer, api} with a {workspace} placeholder, on loopback or https *.eocrm.local / *.eocrm-test.local';
7
+
8
+ // Repo-controlled env reaches hooks, so the override may only name dev hosts.
9
+ function trusted(text) {
10
+ let u;
11
+ try {
12
+ u = new URL(text);
13
+ } catch {
14
+ return null;
15
+ }
16
+ if (u.username || u.password || /[?#]/.test(text)) return null;
17
+ const ok = LOOPBACK.has(u.hostname) ? ['http:', 'https:'].includes(u.protocol) : u.protocol === 'https:' && DEV_HOST.test(u.hostname);
18
+ return ok ? u : null;
19
+ }
20
+
21
+ export function endpoints({ region, env = process.env }) {
22
+ if (!REGIONS.includes(region)) throw new Error(`eocrm: unknown region ${JSON.stringify(region)}`);
23
+ let issuer = `https://id.${region}.eocrm.io`;
24
+ let api = `https://{workspace}.${region}.eocrm.io/api`;
25
+ if (env.EOCRM_ENDPOINTS) {
26
+ let o;
27
+ try {
28
+ o = JSON.parse(env.EOCRM_ENDPOINTS);
29
+ } catch {
30
+ o = null;
31
+ }
32
+ if (typeof o?.issuer !== 'string' || typeof o.api !== 'string' || !o.api.includes('{workspace}')) throw new Error(REFUSED);
33
+ const i = trusted(o.issuer);
34
+ if (!i || !trusted(o.api.replaceAll('{workspace}', PROBE))) throw new Error(REFUSED);
35
+ issuer = i.origin;
36
+ api = o.api.replace(/\/+$/, '');
37
+ }
38
+ return {
39
+ issuer,
40
+ key: `${issuer} ${new URL(api.replaceAll('{workspace}', PROBE)).origin.replaceAll(PROBE, '{workspace}')}`,
41
+ api(workspace) {
42
+ if (typeof workspace !== 'string' || !SLUG.test(workspace)) throw new Error('eocrm: invalid workspace slug');
43
+ return api.replaceAll('{workspace}', workspace);
44
+ },
45
+ };
46
+ }