Skip to content

Commit 3340642

Browse files
authored
fix(setup): use the local Intelligence dashboard for browser login (#811)
* fix(setup): authenticate local Intelligence through its dashboard * fix(setup): discover local Intelligence offline from Desktop
1 parent e76c686 commit 3340642

5 files changed

Lines changed: 528 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,12 @@ A Bot is any endpoint speaking [AG-UI](https://github.com/ag-ui-protocol/ag-ui),
9898
For fresh self-hosted setup, set `INTELLIGENCE_API_URL` to that deployment's
9999
HTTPS API origin (or `http://localhost` for a local one) and run the helper
100100
without the two `npx` commands. It opens an isolated Chrome or Edge window for
101-
your usual sign-in and project choice; install either browser first. It writes
101+
your usual sign-in and project choice; install either browser first. For CLI-managed
102+
local evaluation installs, it discovers the matching dashboard with the installed or
103+
cached CopilotKit CLI and uses that dashboard for login and session requests. Discovery
104+
runs offline with Bun, without downloading the CLI or requiring `npx` on your PATH.
105+
If no CLI is available, manually hosted deployments use their API origin for sign-in. Complete the local auth
106+
approval shown in the browser when prompted. The runtime API URL stays unchanged. It writes
102107
the API URL, the key and the container, not `INTELLIGENCE_GATEWAY_WS_URL`, so
103108
set that one to the same deployment yourself. Once `openbot` exists, the server assigns it
104109
as the default by itself unless [Admin → Automatic Learning](docs/automatic-learning.md)
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
import { expect, test } from "bun:test";
2+
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import {
6+
localCliEntrypoint,
7+
runLocalIntelligenceCli,
8+
} from "./local-intelligence-cli";
9+
10+
async function fixture(
11+
run: (
12+
root: string,
13+
install: (path: string, version?: string, code?: string) => Promise<string>,
14+
) => Promise<void>,
15+
) {
16+
const root = await mkdtemp(join(tmpdir(), "openbot-cli-discovery-"));
17+
try {
18+
await run(
19+
root,
20+
async (
21+
path,
22+
version = "4.99.0",
23+
code = 'console.log(JSON.stringify({status:"completed",stacks:[],args:process.argv.slice(2),secret:process.env.INTELLIGENCE_API_KEY ?? null}));',
24+
) => {
25+
await mkdir(path, { recursive: true });
26+
await writeFile(
27+
join(path, "package.json"),
28+
JSON.stringify({
29+
name: "copilotkit",
30+
version,
31+
bin: { copilotkit: "index.js" },
32+
}),
33+
);
34+
const entry = join(path, "index.js");
35+
await writeFile(entry, code);
36+
return entry;
37+
},
38+
);
39+
} finally {
40+
await rm(root, { recursive: true, force: true });
41+
}
42+
}
43+
const minimalPath = "/usr/bin:/bin:/usr/sbin:/sbin";
44+
45+
test("minimal-PATH child uses an existing npm cache offline without exposing credentials", async () => {
46+
await fixture(async (root, install) => {
47+
await install(join(root, ".npm/_npx/cache/node_modules/copilotkit"));
48+
const environment = {
49+
PATH: minimalPath,
50+
HOME: root,
51+
npm_config_registry: "http://127.0.0.1:1",
52+
INTELLIGENCE_API_KEY: "private-value",
53+
};
54+
const result = await runLocalIntelligenceCli(
55+
["local", "list", "--json"],
56+
root,
57+
{ home: root, globalRoots: [], environment },
58+
);
59+
expect(result.exitCode).toBe(0);
60+
expect(JSON.parse(result.stdout)).toEqual({
61+
status: "completed",
62+
stacks: [],
63+
args: ["local", "list", "--json"],
64+
secret: null,
65+
});
66+
});
67+
});
68+
69+
test("installed CLI wins over cache; otherwise newest cached version wins deterministically", async () => {
70+
await fixture(async (root, install) => {
71+
await install(join(root, ".npm/_npx/z/node_modules/copilotkit"), "4.9.0");
72+
await install(
73+
join(root, ".npm/_npx/pre/node_modules/copilotkit"),
74+
"4.10.0-beta.1",
75+
);
76+
await install(
77+
join(root, ".npm/_npx/broken/node_modules/copilotkit"),
78+
"invalid-version",
79+
);
80+
const latest = await install(
81+
join(root, ".npm/_npx/a/node_modules/copilotkit"),
82+
"4.10.0",
83+
);
84+
expect(
85+
await localCliEntrypoint(root, { PATH: minimalPath }, root, []),
86+
).toBe(latest);
87+
const installed = await install(
88+
join(root, "node_modules/copilotkit"),
89+
"4.8.0",
90+
);
91+
expect(
92+
await localCliEntrypoint(root, { PATH: minimalPath }, root, []),
93+
).toBe(installed);
94+
});
95+
});
96+
97+
test("missing and malformed cache entries are unavailable without a registry invocation", async () => {
98+
await fixture(async (root) => {
99+
const cache = join(root, ".npm/_npx/partial/node_modules/copilotkit");
100+
await mkdir(cache, { recursive: true });
101+
await writeFile(join(cache, "package.json"), "not json");
102+
expect(
103+
await runLocalIntelligenceCli([], root, {
104+
home: root,
105+
globalRoots: [],
106+
environment: { PATH: minimalPath },
107+
}),
108+
).toEqual({ exitCode: 127, stdout: "" });
109+
});
110+
});
111+
112+
test("runtime failure is retained and stderr is not returned", async () => {
113+
await fixture(async (root, install) => {
114+
await install(
115+
join(root, "node_modules/copilotkit"),
116+
"4.0.0",
117+
'console.error("private diagnostic"); process.exit(2);',
118+
);
119+
expect(
120+
await runLocalIntelligenceCli([], root, {
121+
home: root,
122+
globalRoots: [],
123+
environment: { PATH: minimalPath },
124+
}),
125+
).toEqual({ exitCode: 2, stdout: "" });
126+
});
127+
});
128+
129+
test("cancellation terminates discovery and timeout is a runtime failure", async () => {
130+
await fixture(async (root, install) => {
131+
await install(
132+
join(root, "node_modules/copilotkit"),
133+
"4.0.0",
134+
"setInterval(() => {}, 1000);",
135+
);
136+
const controller = new AbortController();
137+
const pending = runLocalIntelligenceCli([], root, {
138+
home: root,
139+
globalRoots: [],
140+
environment: { PATH: minimalPath },
141+
signal: controller.signal,
142+
});
143+
setTimeout(() => controller.abort(new Error("cancelled")), 50);
144+
await expect(pending).rejects.toThrow("cancelled");
145+
expect(
146+
(
147+
await runLocalIntelligenceCli([], root, {
148+
home: root,
149+
globalRoots: [],
150+
environment: { PATH: minimalPath },
151+
timeoutMs: 50,
152+
})
153+
).exitCode,
154+
).toBe(1);
155+
});
156+
});

‎scripts/local-intelligence-cli.ts‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import { spawn } from "node:child_process";
2+
import { readdir, readFile, stat } from "node:fs/promises";
3+
import { homedir } from "node:os";
4+
import {
5+
delimiter,
6+
dirname,
7+
isAbsolute,
8+
join,
9+
relative,
10+
resolve,
11+
} from "node:path";
12+
import {
13+
cliEnvironment,
14+
type CliResult,
15+
} from "../server/src/learning/ensure-container";
16+
17+
/** Resolve only installed packages. Discovery must never contact a package registry. */
18+
export async function localCliEntrypoint(
19+
directory: string,
20+
environment: NodeJS.ProcessEnv = process.env,
21+
home = homedir(),
22+
globalRoots = [
23+
"/opt/homebrew/lib/node_modules/copilotkit",
24+
"/usr/local/lib/node_modules/copilotkit",
25+
],
26+
): Promise<string | undefined> {
27+
const entry = async (root: string) => {
28+
try {
29+
const pkg = JSON.parse(
30+
await readFile(join(root, "package.json"), "utf8"),
31+
);
32+
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.copilotkit;
33+
if (
34+
pkg.name !== "copilotkit" ||
35+
typeof bin !== "string" ||
36+
typeof pkg.version !== "string"
37+
)
38+
return;
39+
// Validate before sorting; stale metadata must not break other cached installs.
40+
Bun.semver.order(pkg.version, pkg.version);
41+
const path = resolve(root, bin);
42+
if (
43+
isAbsolute(relative(root, path)) ||
44+
relative(root, path).startsWith("..") ||
45+
!(await stat(path)).isFile()
46+
)
47+
return;
48+
return {
49+
path,
50+
version: pkg.version,
51+
};
52+
} catch {
53+
// Partial/stale package-cache entries are not installed CLIs.
54+
return;
55+
}
56+
};
57+
const npmPrefix =
58+
environment.npm_config_prefix ?? environment.NPM_CONFIG_PREFIX;
59+
const installed = [
60+
join(directory, "node_modules/copilotkit"),
61+
join(
62+
environment.BUN_INSTALL ?? join(home, ".bun"),
63+
"install/global/node_modules/copilotkit",
64+
),
65+
...(environment.APPDATA
66+
? [join(environment.APPDATA, "npm/node_modules/copilotkit")]
67+
: []),
68+
...(npmPrefix ? [join(npmPrefix, "lib/node_modules/copilotkit")] : []),
69+
...globalRoots,
70+
...(environment.PATH ?? "")
71+
.split(delimiter)
72+
.filter(Boolean)
73+
.map((bin) => join(dirname(bin), "lib/node_modules/copilotkit")),
74+
];
75+
for (const root of installed) {
76+
const found = await entry(root);
77+
if (found) return found.path;
78+
}
79+
// npm's npx cache is a complete installation with its dependency graph. Bun's raw
80+
// package cache is not, so only Bun's installed global package is considered above.
81+
const cacheRoot = join(
82+
environment.npm_config_cache ??
83+
environment.NPM_CONFIG_CACHE ??
84+
join(home, ".npm"),
85+
"_npx",
86+
);
87+
const cached: { path: string; version: string }[] = [];
88+
const names = await readdir(cacheRoot).catch(() => [] as string[]);
89+
for (const name of names.sort()) {
90+
const found = await entry(join(cacheRoot, name, "node_modules/copilotkit"));
91+
if (found) cached.push(found);
92+
}
93+
cached.sort(
94+
(a, b) =>
95+
Bun.semver.order(b.version, a.version) || a.path.localeCompare(b.path),
96+
);
97+
return cached[0]?.path;
98+
}
99+
100+
/** Execute the installed CLI with Desktop's already-resolved Bun, even with Finder's PATH. */
101+
export async function runLocalIntelligenceCli(
102+
args: string[],
103+
directory: string,
104+
options: {
105+
signal?: AbortSignal;
106+
environment?: NodeJS.ProcessEnv;
107+
home?: string;
108+
timeoutMs?: number;
109+
globalRoots?: string[];
110+
} = {},
111+
): Promise<CliResult> {
112+
options.signal?.throwIfAborted();
113+
const environment = options.environment ?? process.env;
114+
const entry = await localCliEntrypoint(
115+
directory,
116+
environment,
117+
options.home,
118+
options.globalRoots,
119+
);
120+
options.signal?.throwIfAborted();
121+
if (!entry) return { exitCode: 127, stdout: "" };
122+
return new Promise((resolveResult, reject) => {
123+
const child = spawn(process.execPath, [entry, ...args], {
124+
cwd: directory,
125+
env: cliEnvironment(environment),
126+
stdio: ["ignore", "pipe", "pipe"],
127+
});
128+
let stdout = "";
129+
const abort = () => child.kill("SIGKILL");
130+
options.signal?.addEventListener("abort", abort, { once: true });
131+
if (options.signal?.aborted) child.kill("SIGKILL");
132+
let timedOut = false;
133+
const timer = setTimeout(() => {
134+
timedOut = true;
135+
child.kill("SIGKILL");
136+
}, options.timeoutMs ?? 10_000);
137+
child.stdout.setEncoding("utf8");
138+
child.stdout.on("data", (chunk: string) => {
139+
stdout = (stdout + chunk).slice(0, 1_048_576);
140+
});
141+
child.stderr.resume();
142+
const finish = (exitCode: number) => {
143+
clearTimeout(timer);
144+
options.signal?.removeEventListener("abort", abort);
145+
if (options.signal?.aborted) reject(options.signal.reason);
146+
else resolveResult({ exitCode: timedOut ? 1 : exitCode, stdout });
147+
};
148+
child.on("error", () => finish(127));
149+
child.on("close", (code) => finish(code ?? 1));
150+
});
151+
}

0 commit comments

Comments
 (0)