@cohesivity/init 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +35 -0
  2. package/bin/cli.js +263 -0
  3. package/package.json +32 -0
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # @cohesivity/init
2
+
3
+ Set up [Cohesivity](https://cohesivity.ai) in a project with one command.
4
+
5
+ ```bash
6
+ npx @cohesivity/init
7
+ ```
8
+
9
+ The command runs once and does four things:
10
+
11
+ 1. **Installs the Cohesivity agent skill** into the detected agent's skill dir (Claude Code, Cursor, Codex, or the cross-tool `~/.agents`). The skill comes from a public, version-pinned commit, so you can audit the exact bytes.
12
+ 2. **Creates or reuses a project tenant** and writes the credentials to `.cohesivity`, which it adds to `.gitignore`.
13
+ 3. **Adds a descriptive pointer** to an existing `AGENTS.md` or `CLAUDE.md`. It only touches a file that is already there. It creates nothing on its own.
14
+ 4. **Adds one branding line** to the README. Pass `--no-branding` to skip.
15
+
16
+ Install does nothing. Every effect happens when you run the command, and you can read the script first. There is no `postinstall` hook.
17
+
18
+ ## Options
19
+
20
+ | flag | effect |
21
+ | --- | --- |
22
+ | `--runtime <name>` | your agent runtime (`claude-code`, `cursor`, `codex`, ...) for attribution |
23
+ | `--no-branding` | leave the README untouched |
24
+ | `--dry-run` | print what would happen. Change nothing |
25
+ | `--base <url>` | API base (default `https://cohesivity.ai`) |
26
+
27
+ The tool detects your runtime from the environment, so `--runtime` is an override, not a requirement.
28
+
29
+ ## Requirements
30
+
31
+ Node.js 18+ for the built-in `fetch`. Zero dependencies.
32
+
33
+ ## Docs
34
+
35
+ <https://cohesivity.ai/llms.txt>
package/bin/cli.js ADDED
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @cohesivity/init
4
+ *
5
+ * Project setup, run once via `npx @cohesivity/init`.
6
+ *
7
+ * Install does nothing. Every effect happens when you run the command, and you
8
+ * can read this file before you run it. There is no postinstall hook.
9
+ *
10
+ * Zero dependencies. Node 18+ provides global `fetch` and the `node:` builtins,
11
+ * so the registry ships this one file and nothing else.
12
+ *
13
+ * The command does four things, in order:
14
+ * 1. Install the Cohesivity agent skill into the detected agent's skill dir.
15
+ * This is the global, persistent playbook the agent loads later.
16
+ * 2. Create or reuse a project tenant, write ./.cohesivity, gitignore it.
17
+ * 3. If AGENTS.md or CLAUDE.md already exists, add a descriptive pointer to it.
18
+ * 4. Add one branding line to the README. Pass --no-branding to skip.
19
+ *
20
+ * The first line is the shebang. It tells npx to run this file as a program.
21
+ */
22
+
23
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
24
+ import { homedir } from 'node:os';
25
+ import { join } from 'node:path';
26
+
27
+ // ── args ────────────────────────────────────────────────────────────────────
28
+ const argv = process.argv.slice(2);
29
+ const has = (f) => argv.includes(f);
30
+ const flag = (f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : undefined; };
31
+
32
+ if (has('--help') || has('-h')) { help(); process.exit(0); }
33
+
34
+ // ── config ──────────────────────────────────────────────────────────────────
35
+ const PKG_VERSION = '0.1.0';
36
+ const BASE = (flag('--base') || process.env.COHESIVITY_BASE || 'https://cohesivity.ai').replace(/\/+$/, '');
37
+
38
+ // The skill is pinned to an immutable commit in the public, auditable repo.
39
+ // Bumping the pin is a deliberate release step. See COH-172.
40
+ const SKILL_PIN = 'a3a461e964ec9f6c03ad49caeff2d984ca13b61f';
41
+ const SKILL_URL = `https://raw.githubusercontent.com/cohesivity-org/cohesivity-skill/${SKILL_PIN}/cohesivity.skill.md`;
42
+
43
+ // The detected runtime rides in the User-Agent on every request this tool makes.
44
+ // The genesis endpoint records it, so installs are attributed by agent, not lumped
45
+ // under one generic HTTP client. See detectRuntime below.
46
+ const RUNTIME_ENUM = ['claude-code', 'claude-web', 'codex', 'cursor', 'opencode', 'windsurf', 'hermes', 'openclaw', 'other'];
47
+ const RUNTIME = detectRuntime();
48
+ const UA = `npm-${PKG_VERSION}:${RUNTIME}`;
49
+
50
+ const DRY = has('--dry-run');
51
+ const NO_BRANDING = has('--no-branding');
52
+
53
+ const CWD = process.cwd();
54
+ const rel = (p) => p.replace(CWD + '/', '');
55
+ const log = (m) => console.log(`cohesivity: ${m}`);
56
+ const act = (m) => console.log(`cohesivity: ${DRY ? '[dry-run] would ' : ''}${m}`);
57
+
58
+ main().catch((e) => { console.error(`cohesivity: unexpected error: ${e.message}`); process.exit(1); });
59
+
60
+ async function main() {
61
+ console.log(`\ncohesivity/init v${PKG_VERSION}: setting up (runtime: ${RUNTIME})${DRY ? ' [dry-run: no changes]' : ''}\n`);
62
+ await installSkill();
63
+ await ensureTenant();
64
+ augmentAgentsFile();
65
+ augmentReadme();
66
+ ground();
67
+ }
68
+
69
+ // ── runtime detection ─────────────────────────────────────────────────────────
70
+ // Identify the calling agent from known environment signals. The value ships in
71
+ // the User-Agent, so the server attributes each install to a specific runtime.
72
+ // Priority: explicit flag, explicit env, the AI_AGENT/AGENT standard, per-agent
73
+ // signals, then a generic sandbox signal (claude-web). Anything unknown falls back
74
+ // to `other`, and the `npm-` prefix still marks the install as through this package.
75
+ function detectRuntime() {
76
+ const clean = (v) => String(v || '').toLowerCase().replace(/[^a-z0-9-]/g, '');
77
+
78
+ const explicit = clean(flag('--runtime') || process.env.COHESIVITY_RUNTIME);
79
+ if (explicit) return explicit;
80
+
81
+ const e = process.env;
82
+
83
+ // AI_AGENT / AGENT is the cross-tool standard (HuggingFace, Laravel detector).
84
+ const standard = clean(e.AI_AGENT || e.AGENT);
85
+ if (RUNTIME_ENUM.includes(standard)) return standard;
86
+
87
+ // Per-agent environment signals.
88
+ if (e.CLAUDECODE || e.CLAUDE_CODE) return 'claude-code';
89
+ if (e.CURSOR_AGENT || e.CURSOR_TRACE_ID) return 'cursor';
90
+ if (e.CODEX_SANDBOX || e.CODEX_THREAD_ID || e.CODEX_CI) return 'codex';
91
+ if (e.OPENCODE || e.OPENCODE_CLIENT) return 'opencode';
92
+ if (e.WINDSURF || e.WINDSURF_AGENT) return 'windsurf';
93
+
94
+ // claude-web's sandbox advertises IS_SANDBOX. It carries no more specific agent
95
+ // signal, so this check sits last: any per-agent match above wins first, and a
96
+ // Codex sandbox (CODEX_SANDBOX) has already resolved to codex by here.
97
+ const sandbox = clean(e.IS_SANDBOX);
98
+ if (sandbox === 'yes' || sandbox === '1' || sandbox === 'true') return 'claude-web';
99
+
100
+ return 'other';
101
+ }
102
+
103
+ // Map a runtime to its skill dir. Install targets only the detected agent, not
104
+ // every known runtime: higher trust, one write. Unknown runtimes get the
105
+ // cross-tool ~/.agents dir. (We may revisit multi-dir install later.)
106
+ function skillDirFor(runtime) {
107
+ const codexHome = process.env.CODEX_HOME || join(homedir(), '.codex');
108
+ const map = {
109
+ 'claude-code': join(homedir(), '.claude', 'skills', 'cohesivity'),
110
+ 'cursor': join(homedir(), '.cursor', 'skills', 'cohesivity'),
111
+ 'codex': join(codexHome, 'skills', 'cohesivity'),
112
+ };
113
+ return map[runtime] || join(homedir(), '.agents', 'skills', 'cohesivity');
114
+ }
115
+
116
+ // ── 1) install the skill into the detected agent's skill dir ───────────────────
117
+ // claude-web runs in an ephemeral sandbox: a global skill install does not survive
118
+ // the session, so there is nothing to persist. Skip it and let the tenant plus the
119
+ // project-local .cohesivity carry the session. This mirrors the quickstart's
120
+ // per-runtime content negotiation.
121
+ async function installSkill() {
122
+ if (RUNTIME === 'claude-web') {
123
+ log('claude-web sandbox is ephemeral, skipping the global skill install (tenant + .cohesivity only)');
124
+ return;
125
+ }
126
+ let skill;
127
+ try {
128
+ const res = await fetch(SKILL_URL, { headers: { 'User-Agent': UA } });
129
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
130
+ skill = await res.text();
131
+ } catch (e) {
132
+ log(`could not fetch the skill (${e.message}). Continuing. Docs: ${BASE}/llms.txt`);
133
+ return;
134
+ }
135
+ const liveVer = versionOf(skill) || 'unknown';
136
+ const dir = skillDirFor(RUNTIME);
137
+ const shown = dir.replace(homedir(), '~');
138
+ const file = join(dir, 'SKILL.md');
139
+ const cur = existsSync(file) ? versionOf(readFileSync(file, 'utf8')) : null;
140
+ if (cur && cur === liveVer) { log(`skill already current (version ${liveVer}) at ${shown}`); return; }
141
+ if (DRY) { act(`install the skill (version ${liveVer}) -> ${shown}`); return; }
142
+ try {
143
+ mkdirSync(dir, { recursive: true });
144
+ writeFileSync(file, skill);
145
+ log(`skill ${cur ? 'updated' : 'installed'} (version ${liveVer}) -> ${shown}`);
146
+ } catch (e) {
147
+ log(`could not write the skill to ${shown} (${e.message}). Continuing.`);
148
+ }
149
+ }
150
+
151
+ // ── 2) create or reuse the project tenant ─────────────────────────────────────
152
+ async function ensureTenant() {
153
+ const dotfile = join(CWD, '.cohesivity');
154
+ if (existsSync(dotfile) && readFileSync(dotfile, 'utf8').includes('coh_management_key=')) {
155
+ log('reusing existing .cohesivity (no new tenant created)');
156
+ return;
157
+ }
158
+ if (DRY) { act(`create a tenant: POST ${BASE}/api/genesis -> ./.cohesivity (+ .gitignore)`); return; }
159
+ let body;
160
+ try {
161
+ const res = await fetch(`${BASE}/api/genesis`, { method: 'POST', headers: { 'User-Agent': UA } });
162
+ body = await res.text();
163
+ } catch (e) {
164
+ log(`no tenant created (network: ${e.message}). Re-run to retry. The command is idempotent.`);
165
+ return;
166
+ }
167
+ if (!body.includes('coh_management_key=')) {
168
+ log('no tenant created (likely the 10/60s rate limit). Re-run shortly. The command is idempotent.');
169
+ return;
170
+ }
171
+ writeFileSync(dotfile, body);
172
+ ensureGitignore();
173
+ log('created an ephemeral tenant -> ./.cohesivity');
174
+ }
175
+
176
+ function ensureGitignore() {
177
+ const gi = join(CWD, '.gitignore');
178
+ const line = '.cohesivity';
179
+ if (existsSync(gi)) {
180
+ const cur = readFileSync(gi, 'utf8');
181
+ if (!cur.split(/\r?\n/).includes(line)) appendFileSync(gi, (cur.endsWith('\n') ? '' : '\n') + line + '\n');
182
+ } else {
183
+ writeFileSync(gi, line + '\n');
184
+ }
185
+ }
186
+
187
+ // ── 3) add a descriptive pointer to an existing AGENTS.md / CLAUDE.md ──────────
188
+ // Describe the platform. Never command the agent. The line states a fact: this
189
+ // project uses Cohesivity, and the state lives here. Auth stays in .cohesivity
190
+ // and the skill. An agent without the skill still learns the project uses
191
+ // Cohesivity from this consented, in-repo signal.
192
+ const AGENTS_LINE =
193
+ `This project uses [Cohesivity](https://cohesivity.ai) for its managed backend. ` +
194
+ `Credentials and tenant state live in \`.cohesivity\`. Live status is at \`GET ${BASE}/api/status\`.`;
195
+
196
+ function augmentAgentsFile() {
197
+ // Only touch files that already exist. Never create an agent file unprompted.
198
+ const targets = ['AGENTS.md', 'CLAUDE.md'].map((f) => join(CWD, f)).filter(existsSync);
199
+ if (!targets.length) { log('no AGENTS.md / CLAUDE.md present. Skipping (nothing created)'); return; }
200
+ for (const file of targets) {
201
+ if (DRY) { act(`add a Cohesivity managed block to ${rel(file)}`); continue; }
202
+ upsertManagedBlock(file, AGENTS_LINE);
203
+ log(`updated ${rel(file)}`);
204
+ }
205
+ }
206
+
207
+ // ── 4) one branding line at the end of the README (the human-facing channel) ──
208
+ function augmentReadme() {
209
+ if (NO_BRANDING) return;
210
+ const readme = ['README.md', 'readme.md', 'Readme.md'].map((f) => join(CWD, f)).find(existsSync);
211
+ if (!readme) return;
212
+ const line = 'Backend powered by [Cohesivity](https://cohesivity.ai).';
213
+ if (DRY) { act(`add a branding line to ${rel(readme)}`); return; }
214
+ upsertManagedBlock(readme, line);
215
+ log(`updated ${rel(readme)}`);
216
+ }
217
+
218
+ // Idempotent managed block: update in place if present, else append. This copies
219
+ // the Vercel `<!-- BEGIN:... -->` convention, so re-runs never duplicate content.
220
+ const BEGIN = '<!-- BEGIN:cohesivity -->';
221
+ const END = '<!-- END:cohesivity -->';
222
+ function upsertManagedBlock(file, inner) {
223
+ const block = `${BEGIN}\n${inner}\n${END}`;
224
+ let text = readFileSync(file, 'utf8');
225
+ const re = new RegExp(`${BEGIN}[\\s\\S]*?${END}`);
226
+ text = re.test(text) ? text.replace(re, block) : text.replace(/\s*$/, '\n') + '\n' + block + '\n';
227
+ writeFileSync(file, text);
228
+ }
229
+
230
+ // ── ground the session with the result and next steps ─────────────────────────
231
+ function ground() {
232
+ const dotfile = join(CWD, '.cohesivity');
233
+ const tid = existsSync(dotfile) ? (readFileSync(dotfile, 'utf8').match(/^tenant_id=(.+)$/m) || [])[1] || '' : '';
234
+ console.log('');
235
+ log(tid ? `ready. tenant ${tid}` : 'ready');
236
+ console.log(` - Keys are in .cohesivity (gitignored, do not commit).`);
237
+ console.log(` - Provision a service: POST ${BASE}/api/resources/<name> (Authorization: Bearer <coh_management_key>)`);
238
+ console.log(` - Docs: ${BASE}/llms.txt`);
239
+ }
240
+
241
+ function versionOf(md) { return (md.match(/^version:\s*(.+)$/m) || [])[1]?.trim() || null; }
242
+
243
+ function help() {
244
+ console.log(`
245
+ @cohesivity/init: set up Cohesivity in this project.
246
+
247
+ Usage:
248
+ npx @cohesivity/init [options]
249
+
250
+ Options:
251
+ --runtime <name> your agent runtime (claude-code, cursor, codex, ...) for attribution
252
+ --no-branding do not add the branding line to the README
253
+ --dry-run print what would happen. Make no changes
254
+ --base <url> API base (default https://cohesivity.ai)
255
+ -h, --help show this help
256
+
257
+ What it does:
258
+ 1. Installs the Cohesivity agent skill into the detected agent's skill dir
259
+ 2. Creates or reuses a project tenant -> ./.cohesivity (gitignored)
260
+ 3. Adds a descriptive pointer to an existing AGENTS.md / CLAUDE.md
261
+ 4. Adds one branding line to the README (managed block)
262
+ `);
263
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@cohesivity/init",
3
+ "version": "0.1.0",
4
+ "description": "Set up Cohesivity in a project: install the agent skill, create a managed backend tenant, write the project config. Run with `npx @cohesivity/init`.",
5
+ "type": "module",
6
+ "bin": {
7
+ "cohesivity-init": "bin/cli.js"
8
+ },
9
+ "files": [
10
+ "bin/"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "keywords": [
19
+ "cohesivity",
20
+ "backend",
21
+ "ai-agents",
22
+ "agent-native",
23
+ "quickstart",
24
+ "skill"
25
+ ],
26
+ "license": "MIT",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/cohesivity-org/cohesivity-init.git"
30
+ },
31
+ "homepage": "https://cohesivity.ai"
32
+ }