@cairnvibe/indexer 0.1.0 → 0.2.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/dist/cli.js CHANGED
@@ -17,6 +17,7 @@ const manifest_1 = require("./manifest");
17
17
  const diff_1 = require("./diff");
18
18
  const docs_1 = require("./docs");
19
19
  const init_1 = require("./init");
20
+ const setup_1 = require("./setup");
20
21
  function parseArgs(rest) {
21
22
  const positional = [];
22
23
  const flags = {};
@@ -43,11 +44,20 @@ async function main() {
43
44
  }
44
45
  if (command === "build") {
45
46
  const provider = flags.provider === "groq" ? "groq" : "anthropic";
46
- if (provider === "anthropic" && !process.env.ANTHROPIC_API_KEY) {
47
+ const keyMissing = provider === "anthropic" ? !process.env.ANTHROPIC_API_KEY : !process.env.GROQ_API_KEYS;
48
+ if (keyMissing && "if-configured" in flags) {
49
+ // Used by the prebuild hook `cairn setup` wires in: a deploy with no key
50
+ // set yet (e.g. the very first one, before env vars are configured on the
51
+ // hosting platform) skips this step instead of failing the whole build —
52
+ // the app still builds and runs, just without an updated manifest.
53
+ console.error(`cairn build --if-configured: no key set for ${provider} — skipping, leaving any existing ui-manifest.json as-is.`);
54
+ return;
55
+ }
56
+ if (provider === "anthropic" && keyMissing) {
47
57
  console.error("cairn build: ANTHROPIC_API_KEY is not set. Export it, or pass --provider groq, and re-run.");
48
58
  process.exit(1);
49
59
  }
50
- if (provider === "groq" && !process.env.GROQ_API_KEYS) {
60
+ if (provider === "groq" && keyMissing) {
51
61
  console.error("cairn build --provider groq: GROQ_API_KEYS is not set (comma-separated). Export it and re-run.");
52
62
  process.exit(1);
53
63
  }
@@ -92,6 +102,10 @@ async function main() {
92
102
  console.error(`wrote ${outPath}`);
93
103
  return;
94
104
  }
105
+ if (command === "setup") {
106
+ await (0, setup_1.runSetup)(dir);
107
+ return;
108
+ }
95
109
  if (command === "init") {
96
110
  const result = (0, init_1.runInit)(dir);
97
111
  console.error(`cairn init: detected ${result.framework}.`);
@@ -129,7 +143,8 @@ async function main() {
129
143
  return;
130
144
  }
131
145
  console.error("usage:");
132
- console.error(" cairn init <dir> (scaffolds the API route/server + .env.example, detects your framework)");
146
+ console.error(" cairn setup [dir] (the one-command path: installs deps, asks for keys — skippable, wires the widget in, builds once, auto-rebuilds on future `npm run build`)");
147
+ console.error(" cairn init <dir> (scaffolds the API route/server + .env.example, detects your framework — no prompts, no installs)");
133
148
  console.error(" cairn scan <dir>");
134
149
  console.error(" cairn build <dir> [--provider anthropic|groq] (Next.js source scan)");
135
150
  console.error(" cairn build <url> [--provider anthropic|groq] [--out <dir>] [--storage-state <file>] (any framework — crawls a running app; --storage-state replays a saved logged-in session for auth-gated apps)");
package/dist/init.js CHANGED
@@ -67,7 +67,7 @@ function runInit(dir) {
67
67
  }
68
68
  else {
69
69
  writeIfAbsent(node_path_1.default.join(absDir, "cairn-server.cjs"), STANDALONE_SERVER, result);
70
- result.nextSteps.push("1. cp .env.example .env and fill in your key(s).", "2. npm install express @cairnvibe/sdk @cairnvibe/core (@cairnvibe/sdk isn't on npm yet — see README.md's Quick start for the file: install path)", "3. Start your app, then: npx cairn build http://localhost:PORT (crawls the running app — works for any framework)", "4. node cairn-server.cjs (the copilot backend, separate from your app's own server)", "5. Add this to your HTML, pointed at wherever cairn-server.cjs is running:", ' <script src="/cairn-widget.js"></script>', ' <cairn-widget endpoint="http://localhost:4000/api/copilot"></cairn-widget>', " (copy node_modules/@cairnvibe/sdk/dist/cairn-widget.js into your app's static assets as cairn-widget.js)");
70
+ result.nextSteps.push("1. cp .env.example .env and fill in your key(s).", "2. npm install express @cairnvibe/sdk @cairnvibe/core", "3. Start your app, then: npx cairn build http://localhost:PORT (crawls the running app — works for any framework)", "4. node cairn-server.cjs (the copilot backend, separate from your app's own server)", "5. Add this to your HTML, pointed at wherever cairn-server.cjs is running:", ' <script src="/cairn-widget.js"></script>', ' <cairn-widget endpoint="http://localhost:4000/api/copilot"></cairn-widget>', " (copy node_modules/@cairnvibe/sdk/dist/cairn-widget.js into your app's static assets as cairn-widget.js)");
71
71
  }
72
72
  return result;
73
73
  }
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ // `cairn setup`'s one departure from `init`'s "never touch an existing
3
+ // file" rule — but only for this one, narrow, reversible edit (adding an
4
+ // import + one JSX tag), and only ever via a real AST parse, never blind
5
+ // string splicing. Any structure this doesn't recognize falls back to
6
+ // printing the two-line manual instruction instead of guessing — the
7
+ // same "don't corrupt what you don't understand" discipline `init` uses
8
+ // for whole files, applied here at the node level.
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.injectWidget = injectWidget;
14
+ const node_fs_1 = __importDefault(require("node:fs"));
15
+ const node_path_1 = __importDefault(require("node:path"));
16
+ const ts_morph_1 = require("ts-morph");
17
+ const WIDGET_JSX = `<Copilot registeredActions={[]} onDo={(action, target) => { /* run it through your own auth */ }} />`;
18
+ function findLayoutFile(absDir, framework) {
19
+ const candidates = framework === "next-app-router"
20
+ ? ["app/layout.tsx", "app/layout.jsx"]
21
+ : ["pages/_app.tsx", "pages/_app.jsx"];
22
+ for (const c of candidates) {
23
+ const p = node_path_1.default.join(absDir, c);
24
+ if (node_fs_1.default.existsSync(p))
25
+ return p;
26
+ }
27
+ return null;
28
+ }
29
+ function injectWidget(dir, framework) {
30
+ const absDir = node_path_1.default.resolve(dir);
31
+ const target = findLayoutFile(absDir, framework);
32
+ if (!target) {
33
+ return { injected: false, reason: "no app/layout.tsx or pages/_app.tsx found — add <Copilot/> manually" };
34
+ }
35
+ const relTarget = node_path_1.default.relative(absDir, target) || target;
36
+ const original = node_fs_1.default.readFileSync(target, "utf8");
37
+ if (original.includes("@cairnvibe/sdk") || original.includes("<Copilot")) {
38
+ return { injected: false, reason: `${relTarget} already references Copilot — leaving it alone` };
39
+ }
40
+ try {
41
+ const project = new ts_morph_1.Project({
42
+ useInMemoryFileSystem: false,
43
+ skipAddingFilesFromTsConfig: true,
44
+ compilerOptions: { jsx: ts_morph_1.ts.JsxEmit.ReactJSX, allowJs: true, esModuleInterop: true, target: ts_morph_1.ts.ScriptTarget.ES2022 },
45
+ });
46
+ const sf = project.addSourceFileAtPath(target);
47
+ const hasImport = sf.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "@cairnvibe/sdk");
48
+ if (!hasImport) {
49
+ sf.addImportDeclaration({ moduleSpecifier: "@cairnvibe/sdk", namedImports: ["Copilot"] });
50
+ }
51
+ // `insertText` at a position, not `replaceWithText` on a node — the latter
52
+ // asks ts-morph to structurally reconcile old vs. new trees, which fails
53
+ // ("children of the old and new trees were expected to have the same
54
+ // count") the moment the replacement text contains a whole new element
55
+ // rather than equivalent-shaped content. Plain positional insertion has
56
+ // no tree to reconcile, so it can't hit that class of error.
57
+ let inserted = false;
58
+ // App Router: insert right before </body>, wherever it is in the tree.
59
+ const bodyOpening = sf
60
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.JsxOpeningElement)
61
+ .find((el) => el.getTagNameNode().getText() === "body");
62
+ if (bodyOpening) {
63
+ const closing = bodyOpening.getParentIfKind(ts_morph_1.SyntaxKind.JsxElement)?.getClosingElement();
64
+ if (closing) {
65
+ sf.insertText(closing.getStart(), `${WIDGET_JSX}\n `);
66
+ inserted = true;
67
+ }
68
+ }
69
+ // App Router fallback: a custom layout with no literal <body> — drop it right after {children}.
70
+ if (!inserted) {
71
+ const childrenExpr = sf
72
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.JsxExpression)
73
+ .find((e) => e.getExpression()?.getText() === "children");
74
+ if (childrenExpr) {
75
+ sf.insertText(childrenExpr.getEnd(), `\n ${WIDGET_JSX}`);
76
+ inserted = true;
77
+ }
78
+ }
79
+ // Pages Router: wrap the returned <Component .../> as a sibling inside a fragment,
80
+ // wherever it sits (works whether or not it's already inside other providers).
81
+ // Insert the closing half first so the earlier (opening-half) position isn't shifted yet.
82
+ if (!inserted) {
83
+ const componentTag = sf
84
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.JsxSelfClosingElement)
85
+ .find((el) => el.getTagNameNode().getText() === "Component");
86
+ if (componentTag) {
87
+ // Capture both positions before either insertText call — the node
88
+ // reference goes stale ("removed or forgotten") the instant the
89
+ // first insertion changes the source text underneath it.
90
+ const start = componentTag.getStart();
91
+ const end = componentTag.getEnd();
92
+ sf.insertText(end, `\n ${WIDGET_JSX}\n </>`);
93
+ sf.insertText(start, `<>\n `);
94
+ inserted = true;
95
+ }
96
+ }
97
+ if (!inserted) {
98
+ return { injected: false, reason: `couldn't find a safe spot in ${relTarget} — add <Copilot/> manually` };
99
+ }
100
+ sf.saveSync();
101
+ return { injected: true, filePath: target };
102
+ }
103
+ catch (err) {
104
+ // Never leave a half-written file — ts-morph only writes on saveSync(),
105
+ // so a thrown error here means the original file on disk is untouched.
106
+ return { injected: false, reason: `couldn't safely modify ${relTarget} (${err.message}) — add <Copilot/> manually` };
107
+ }
108
+ }
package/dist/prompt.js ADDED
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ // A tiny prompt helper for `cairn setup` — built on Node's own `readline`
3
+ // deliberately, not a new dependency, for something this small. Every
4
+ // prompt this module offers is skippable: an empty answer means "skip,"
5
+ // never a forced choice, matching setup's whole "ask, don't require"
6
+ // design.
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.closePrompts = closePrompts;
12
+ exports.ask = ask;
13
+ exports.askYesNo = askYesNo;
14
+ exports.askOptional = askOptional;
15
+ const node_readline_1 = __importDefault(require("node:readline"));
16
+ let sharedInterface = null;
17
+ function rl() {
18
+ if (!sharedInterface) {
19
+ sharedInterface = node_readline_1.default.createInterface({ input: process.stdin, output: process.stdout });
20
+ }
21
+ return sharedInterface;
22
+ }
23
+ function closePrompts() {
24
+ sharedInterface?.close();
25
+ sharedInterface = null;
26
+ }
27
+ function ask(question) {
28
+ return new Promise((resolve) => rl().question(question, (answer) => resolve(answer.trim())));
29
+ }
30
+ /** A yes/no prompt. Empty answer (just pressing enter) takes `fallback`. */
31
+ async function askYesNo(question, fallback) {
32
+ const suffix = fallback ? " [Y/n] " : " [y/N] ";
33
+ const answer = (await ask(question + suffix)).toLowerCase();
34
+ if (!answer)
35
+ return fallback;
36
+ return answer.startsWith("y");
37
+ }
38
+ /** A free-text prompt where an empty answer means "skip this." Returns null when skipped. */
39
+ async function askOptional(question) {
40
+ const answer = await ask(question);
41
+ return answer.length > 0 ? answer : null;
42
+ }
package/dist/setup.js ADDED
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ // `cairn setup` — the one-command onboarding path: install what's
3
+ // needed, ask only for what's actually optional (skippable), scaffold
4
+ // the backend, wire the widget into the real layout file, build the
5
+ // manifest once now, and leave a `prebuild` hook so it rebuilds itself
6
+ // on every future `npm run build` without another manual step.
7
+ //
8
+ // Deliberately layered on top of `runInit` rather than replacing it —
9
+ // `init` stays the safe, deterministic, non-interactive primitive
10
+ // (never touches an existing file, never installs anything, never
11
+ // prompts); `setup` is the opinionated wizard built from those same
12
+ // primitives plus the two things `init` intentionally doesn't do:
13
+ // install dependencies and edit an existing layout file.
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.runSetup = runSetup;
19
+ const node_fs_1 = __importDefault(require("node:fs"));
20
+ const node_path_1 = __importDefault(require("node:path"));
21
+ const node_child_process_1 = require("node:child_process");
22
+ const init_1 = require("./init");
23
+ const inject_widget_1 = require("./inject-widget");
24
+ const prompt_1 = require("./prompt");
25
+ const l1_scan_1 = require("./l1-scan");
26
+ const l2_reachability_1 = require("./l2-reachability");
27
+ const l3_describe_1 = require("./l3-describe");
28
+ const llm_1 = require("./llm");
29
+ const manifest_1 = require("./manifest");
30
+ const core_1 = require("@cairnvibe/core");
31
+ const PACKAGES = ["@cairnvibe/core", "@cairnvibe/sdk", "@cairnvibe/indexer"];
32
+ function readPackageJson(absDir) {
33
+ const p = node_path_1.default.join(absDir, "package.json");
34
+ if (!node_fs_1.default.existsSync(p))
35
+ return null;
36
+ try {
37
+ return JSON.parse(node_fs_1.default.readFileSync(p, "utf8"));
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ function alreadyInstalled(pkg) {
44
+ if (!pkg)
45
+ return false;
46
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
47
+ return PACKAGES.every((p) => !!deps[p]);
48
+ }
49
+ async function runSetup(dir) {
50
+ const absDir = node_path_1.default.resolve(dir);
51
+ console.log(`cairn setup: looking at ${absDir}\n`);
52
+ // 1. Scaffold what init already safely can — framework detection, the
53
+ // backend route, .env.example. Never overwrites anything that exists.
54
+ const init = (0, init_1.runInit)(dir);
55
+ console.log(`Detected: ${init.framework}`);
56
+ for (const f of init.filesWritten)
57
+ console.log(` wrote ${node_path_1.default.relative(absDir, f) || f}`);
58
+ for (const f of init.filesSkipped)
59
+ console.log(` skipped ${node_path_1.default.relative(absDir, f) || f} (already exists)`);
60
+ console.log("");
61
+ if (init.framework === "other") {
62
+ // A generic backend needs a real framework decision (Express? Fastify? something
63
+ // else?) this wizard shouldn't guess at — print init's own manual steps instead
64
+ // of half-automating something it can't verify is right.
65
+ console.log("Not a detected Next.js project — falling back to the manual steps:\n");
66
+ for (const step of init.nextSteps)
67
+ console.log(` ${step}`);
68
+ return;
69
+ }
70
+ // 2. Install what's needed — the actual "one command" part. Skips
71
+ // cleanly if already present (e.g. re-running setup after a partial run).
72
+ const pkg = readPackageJson(absDir);
73
+ if (!alreadyInstalled(pkg)) {
74
+ console.log(`Installing ${PACKAGES.join(", ")} ...`);
75
+ try {
76
+ (0, node_child_process_1.execSync)(`npm install ${PACKAGES.join(" ")}`, { cwd: absDir, stdio: "inherit" });
77
+ }
78
+ catch {
79
+ console.error("\nnpm install failed — install these yourself and re-run `cairn setup`:");
80
+ console.error(` npm install ${PACKAGES.join(" ")}`);
81
+ return;
82
+ }
83
+ }
84
+ else {
85
+ console.log("Dependencies already installed — skipping.\n");
86
+ }
87
+ // 3. Ask only what's actually needed, everything skippable.
88
+ console.log("\nA couple of quick questions — press enter to skip anything you'll add later.\n");
89
+ let provider = null;
90
+ let providerKey = null;
91
+ const wantsLLM = await (0, prompt_1.askYesNo)("Set up an LLM provider now? (needed for the agent to actually answer anything)", true);
92
+ if (wantsLLM) {
93
+ const choice = (await (0, prompt_1.ask)("Anthropic or Groq? [anthropic] ")).toLowerCase();
94
+ provider = choice.startsWith("g") ? "groq" : "anthropic";
95
+ providerKey = await (0, prompt_1.askOptional)(provider === "anthropic" ? "Paste your ANTHROPIC_API_KEY: " : "Paste your GROQ_API_KEYS: ");
96
+ }
97
+ const wantsVoice = await (0, prompt_1.askYesNo)("Set up voice (Deepgram — speech in/out) now?", false);
98
+ const deepgramKey = wantsVoice ? await (0, prompt_1.askOptional)("Paste your DEEPGRAM_API_KEY: ") : null;
99
+ (0, prompt_1.closePrompts)();
100
+ // 4. Write a real .env (not just .env.example) with whatever was actually given.
101
+ const envLines = [];
102
+ if (provider === "anthropic")
103
+ envLines.push(`ANTHROPIC_API_KEY=${providerKey ?? ""}`);
104
+ if (provider === "groq")
105
+ envLines.push(`GROQ_API_KEYS=${providerKey ?? ""}`);
106
+ if (deepgramKey)
107
+ envLines.push(`DEEPGRAM_API_KEY=${deepgramKey}`);
108
+ envLines.push("CAIRN_REGISTERED_ACTIONS=");
109
+ const envPath = node_path_1.default.join(absDir, ".env");
110
+ if (!node_fs_1.default.existsSync(envPath)) {
111
+ node_fs_1.default.writeFileSync(envPath, envLines.join("\n") + "\n");
112
+ console.log(`\nwrote ${node_path_1.default.relative(absDir, envPath)}`);
113
+ }
114
+ else {
115
+ console.log(`\n${node_path_1.default.relative(absDir, envPath)} already exists — not overwriting; add keys there yourself if you skipped any above.`);
116
+ }
117
+ // 5. Wire the widget into the real layout file — the one thing `init`
118
+ // deliberately doesn't do. Falls back to printing instructions on
119
+ // anything it can't confidently parse.
120
+ const framework = init.framework;
121
+ const inject = (0, inject_widget_1.injectWidget)(dir, framework);
122
+ if (inject.injected) {
123
+ console.log(`wired <Copilot/> into ${node_path_1.default.relative(absDir, inject.filePath)}`);
124
+ }
125
+ else {
126
+ console.log(`\n<Copilot/> not auto-wired (${inject.reason}). Add it yourself:`);
127
+ console.log(' import { Copilot } from "@cairnvibe/sdk";');
128
+ console.log(" <Copilot registeredActions={[]} onDo={(action, target) => { /* run it */ }} />");
129
+ }
130
+ // 6. Build the manifest once now, if we actually have a usable key —
131
+ // no point trying (and failing loudly) with nothing to call.
132
+ const haveUsableKey = (provider === "anthropic" && providerKey) || (provider === "groq" && providerKey);
133
+ if (haveUsableKey) {
134
+ console.log(`\nBuilding the manifest (${provider}) ...`);
135
+ try {
136
+ // Reuse the same env-var-driven construction `cairn build` uses, rather
137
+ // than duplicating each client's options shape here — the .env written
138
+ // above already has this exact value, this just makes it live for the
139
+ // rest of this process too.
140
+ if (provider === "anthropic")
141
+ process.env.ANTHROPIC_API_KEY = providerKey;
142
+ if (provider === "groq")
143
+ process.env.GROQ_API_KEYS = providerKey;
144
+ const client = provider === "anthropic" ? new llm_1.AnthropicDescribeClient() : new llm_1.GroqDescribeClient();
145
+ const facts = (0, l1_scan_1.scanL1)(dir);
146
+ const l2 = (0, l2_reachability_1.computeL2)(dir, facts);
147
+ const l3 = await (0, l3_describe_1.describeAll)(dir, facts, client);
148
+ const manifest = core_1.ManifestSchema.parse((0, manifest_1.assembleManifest)(dir, facts, l2, l3));
149
+ node_fs_1.default.writeFileSync(node_path_1.default.join(absDir, "ui-manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
150
+ console.log(`wrote ui-manifest.json (${manifest.pages.length} page(s))`);
151
+ }
152
+ catch (err) {
153
+ console.error(`manifest build failed (${err.message}) — run \`npx cairn build .\` yourself once your key is confirmed working.`);
154
+ }
155
+ }
156
+ else {
157
+ console.log("\nNo key given yet — skipping the first build. Run `npx cairn build .` once you've added one to .env.");
158
+ }
159
+ // 7. Wire a prebuild hook so this stays current on every future build/deploy —
160
+ // "just build and redeploy" only works if the manifest regenerates itself.
161
+ if (pkg && !pkg.scripts?.prebuild?.includes("cairn build")) {
162
+ const pkgPath = node_path_1.default.join(absDir, "package.json");
163
+ const fresh = JSON.parse(node_fs_1.default.readFileSync(pkgPath, "utf8"));
164
+ fresh.scripts = fresh.scripts ?? {};
165
+ const providerFlag = provider === "groq" ? "groq" : "anthropic";
166
+ fresh.scripts.prebuild = fresh.scripts.prebuild
167
+ ? `${fresh.scripts.prebuild} && cairn build . --provider ${providerFlag} --if-configured`
168
+ : `cairn build . --provider ${providerFlag} --if-configured`;
169
+ node_fs_1.default.writeFileSync(pkgPath, JSON.stringify(fresh, null, 2) + "\n");
170
+ console.log('added a "prebuild" script — the manifest regenerates automatically on every `npm run build`.');
171
+ console.log("(--if-configured means a build with no key set yet skips this step instead of failing the whole build —");
172
+ console.log(" set the same key as an environment variable on whatever platform you deploy to.)");
173
+ }
174
+ console.log("\nDone. `npm run dev` and ask it something.");
175
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cairnvibe/indexer",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Cairn's analyzer and installer (the `cairn` CLI) — scans Next.js source or crawls any running app, and scaffolds the backend either way.",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },