portal-agent-cli 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 your-name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # portal-agent
2
+
3
+ Drive web AI products from the terminal with local tools. Uses a real
4
+ Chromium browser against the provider's own website. No model API key
5
+ required.
6
+
7
+ Supports **DeepSeek** and **ChatGPT**.
8
+
9
+ ## Install
10
+
11
+ npm install -g portal-agent-cli
12
+
13
+ ## Run
14
+
15
+ portal-agent --workspace F:/projects/my-app
16
+
17
+ Or without installing:
18
+
19
+ npx portal-agent-cli --workspace F:/projects/my-app
20
+
21
+ On first run, Chrome opens at the provider site. Log in there. The session
22
+ is stored in `~/.portal-agent/browser` and reused on later runs.
23
+
24
+ ## Commands inside the prompt
25
+
26
+ /cd <folder> change workspace mid-session
27
+ /pwd show current workspace
28
+ /help show all commands
29
+ /quit exit
30
+
31
+ ## Flags
32
+
33
+ -w, --workspace DIR folder the agent works in
34
+ --provider NAME deepseek (default) or chatgpt
35
+ --timeout MS response timeout (default 180000)
36
+ --login-timeout MS login wait (default 600000)
37
+ --max-steps N max tool steps per turn (default 8)
38
+
39
+ ## Environment variables
40
+
41
+ PORTAL_WORKSPACE same as --workspace
42
+ PORTAL_BROWSER_PATH explicit path to Chrome/Edge/Brave
43
+ PORTAL_PROVIDER default provider
44
+ CHROME_PATH alternative browser path
45
+
46
+ ## One-shot mode
47
+
48
+ portal-agent --workspace F:/proj exec "list the files here"
49
+
50
+ ## Tools the model can call
51
+
52
+ - `read_file(path, start_line?, end_line?)`
53
+ - `write_file(path, content)`
54
+ - `edit_file(path, old_string, new_string, replace_all?)`
55
+ - `list_files(path?)`
56
+ - `grep_search(pattern, case_sensitive?)`
57
+ - `shell(command)`
58
+
59
+ ## How it works
60
+
61
+ Portal launches Chrome, opens the provider site, and injects a system prompt
62
+ telling the model how to call tools. The model writes:
63
+
64
+ portal-tool: {"tool":"read_file","args":{"path":"notes.txt"}}
65
+
66
+ Portal parses that line, runs the tool locally, and sends the result back into
67
+ the same conversation. This repeats until the model stops calling tools.
68
+
69
+ ## Design notes
70
+
71
+ **Enter-first submit.** The DeepSeek composer has three buttons with the same
72
+ role (DeepThink, Search, Send). Enter always goes to the focused composer, so
73
+ Portal presses Enter first and only falls back to a "Send" button if the
74
+ composer still has text after five seconds.
75
+
76
+ **Paste-safe insertion.** Prompts are inserted with `keyboard.insertText`,
77
+ which behaves like typing rather than `fill`, which DeepSeek treats as a paste
78
+ and answers with a Cancel/Send confirmation dialog.
79
+
80
+ **Reply detection.** Portal counts assistant messages before sending, waits
81
+ for the count to rise, then skips any candidate whose text matches the prompt
82
+ it just sent. Without this, DeepSeek echoes your own message back as if it
83
+ were the reply.
84
+
85
+ **Backslash repair.** Models copy the Windows backslash style from the
86
+ workspace line in the system prompt. The parser repairs `\t`, `\h`, `\w`,
87
+ `\d`, and `\p` in tool-call JSON before parsing, so `L:\this\file.txt`
88
+ becomes `L:/this/file.txt`.
89
+
90
+ **Loop breaker.** Identical tool calls are counted per turn. Three calls with
91
+ the same arguments stops the turn.
92
+
93
+ ## Troubleshooting
94
+
95
+ **`No Chrome found`** -- install Chrome, Edge, or Brave, or set
96
+ `PORTAL_BROWSER_PATH` to the full path of the browser executable.
97
+
98
+ **`Another Chrome window is using the same profile`** -- close every Chrome
99
+ window and try again. Portal uses its own profile in `~/.portal-agent/browser`
100
+ but Chrome's profile lock is global.
101
+
102
+ **`Message stayed in composer`** -- look at the Chrome window. If a
103
+ Cancel/Send bar is showing, click Send once manually. Then resend.
104
+
105
+ **`No response appeared within the timeout`** -- raise `--timeout`. DeepSeek
106
+ can be slow under load.
107
+
108
+ **Selectors broken after a provider UI update** -- edit `lib/providers.mjs`
109
+ and add or reorder selectors for the affected provider.
110
+
111
+ ## License
112
+
113
+ MIT
package/lib/args.mjs ADDED
@@ -0,0 +1,55 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+
4
+ export function parseArgs() {
5
+ const a = process.argv.slice(2);
6
+ const o = {
7
+ ws: process.env.PORTAL_WORKSPACE || process.cwd(),
8
+ provider: process.env.PORTAL_PROVIDER || "deepseek",
9
+ maxSteps: 8,
10
+ timeout: 180000,
11
+ loginTimeout: 600000,
12
+ exec: null
13
+ };
14
+ let i = 0;
15
+ while (i < a.length) {
16
+ const t = a[i];
17
+ if (t === "-w" || t === "--workspace") o.ws = a[++i];
18
+ else if (t === "--provider") o.provider = a[++i];
19
+ else if (t === "--timeout") o.timeout = Number(a[++i]);
20
+ else if (t === "--login-timeout") o.loginTimeout = Number(a[++i]);
21
+ else if (t === "--max-steps") o.maxSteps = Number(a[++i]);
22
+ else if (t === "exec") { o.exec = a.slice(i + 1).join(" "); break; }
23
+ else if (t === "--help" || t === "-h") { help(); process.exit(0); }
24
+ else if (t === "--version" || t === "-v") { console.log("1.0.0"); process.exit(0); }
25
+ i++;
26
+ }
27
+ o.ws = resolve(o.ws);
28
+ if (!existsSync(o.ws)) {
29
+ console.error("workspace not found: " + o.ws);
30
+ process.exit(2);
31
+ }
32
+ return o;
33
+ }
34
+
35
+ function help() {
36
+ console.log("");
37
+ console.log("portal-agent -- drive web AI from the terminal");
38
+ console.log("");
39
+ console.log("Usage:");
40
+ console.log(" portal-agent --workspace DIR");
41
+ console.log(" portal-agent --workspace DIR exec TASK");
42
+ console.log("");
43
+ console.log("Flags:");
44
+ console.log(" -w, --workspace DIR folder the agent works in");
45
+ console.log(" --provider NAME deepseek (default) or chatgpt");
46
+ console.log(" --timeout MS response timeout (default 180000)");
47
+ console.log(" --login-timeout MS login wait (default 600000)");
48
+ console.log(" --max-steps N max tool steps per turn (default 8)");
49
+ console.log("");
50
+ console.log("Environment:");
51
+ console.log(" PORTAL_WORKSPACE same as --workspace");
52
+ console.log(" PORTAL_BROWSER_PATH explicit path to Chrome/Edge/Brave");
53
+ console.log(" PORTAL_PROVIDER default provider");
54
+ console.log("");
55
+ }
@@ -0,0 +1,56 @@
1
+ import { chromium } from "playwright";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir } from "node:fs/promises";
4
+ import { resolve, join } from "node:path";
5
+ import { homedir } from "node:os";
6
+
7
+ const CANDIDATES = [
8
+ process.env.PORTAL_BROWSER_PATH,
9
+ process.env.CHROME_PATH,
10
+ "C:/Program Files/Google/Chrome/Application/chrome.exe",
11
+ "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
12
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
13
+ "C:/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe",
14
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
15
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
16
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
17
+ "/usr/bin/google-chrome",
18
+ "/usr/bin/google-chrome-stable",
19
+ "/usr/bin/chromium",
20
+ "/usr/bin/chromium-browser"
21
+ ];
22
+
23
+ export function findBrowser() {
24
+ for (const p of CANDIDATES) {
25
+ if (p && existsSync(p)) return p;
26
+ }
27
+ return null;
28
+ }
29
+
30
+ export async function launch() {
31
+ const exe = findBrowser();
32
+ if (!exe) {
33
+ throw new Error(
34
+ "No Chrome, Chromium, Edge, or Brave found. " +
35
+ "Install one, or set PORTAL_BROWSER_PATH to its full path."
36
+ );
37
+ }
38
+ const dir = join(homedir(), ".portal-agent", "browser");
39
+ await mkdir(dir, { recursive: true });
40
+ try {
41
+ return await chromium.launchPersistentContext(dir, {
42
+ executablePath: exe,
43
+ headless: false,
44
+ viewport: { width: 1280, height: 900 }
45
+ });
46
+ } catch (e) {
47
+ const m = e.message || String(e);
48
+ if (/ProcessSingleton|already running|profile/i.test(m)) {
49
+ throw new Error(
50
+ "Another Chrome window is using the same profile. " +
51
+ "Close every Chrome window and try again."
52
+ );
53
+ }
54
+ throw new Error("Failed to launch Chromium: " + m);
55
+ }
56
+ }
package/lib/exec.mjs ADDED
@@ -0,0 +1,27 @@
1
+ import { launch } from "./browser.mjs";
2
+ import { getProvider } from "./providers.mjs";
3
+ import { waitForComposer } from "./wait.mjs";
4
+ import { runTurn } from "./turn.mjs";
5
+ import { setWs } from "./tools.mjs";
6
+
7
+ export async function runExec(opts) {
8
+ const provider = getProvider(opts.provider);
9
+ setWs(opts.ws);
10
+
11
+ const ctx = await launch();
12
+ const page = await ctx.newPage();
13
+ page.setDefaultTimeout(30000);
14
+
15
+ await page.goto(provider.url);
16
+ await waitForComposer(page, provider, opts.loginTimeout);
17
+
18
+ try {
19
+ await runTurn(page, provider, opts.exec, opts);
20
+ process.exitCode = 0;
21
+ } catch (e) {
22
+ console.error("error: " + (e.message || e));
23
+ process.exitCode = 1;
24
+ } finally {
25
+ await ctx.close().catch(function () {});
26
+ }
27
+ }
package/lib/parse.mjs ADDED
@@ -0,0 +1,61 @@
1
+ function findEnd(s, i) {
2
+ let d = 0;
3
+ let q = false;
4
+ let e = false;
5
+ for (let j = i; j < s.length; j++) {
6
+ const c = s[j];
7
+ if (e) {
8
+ e = false;
9
+ continue;
10
+ }
11
+ if (c === "\\") {
12
+ e = true;
13
+ continue;
14
+ }
15
+ if (c === String.fromCharCode(34)) {
16
+ q = !q;
17
+ continue;
18
+ }
19
+ if (q) continue;
20
+ if (c === "{") d++;
21
+ else if (c === "}") {
22
+ d--;
23
+ if (!d) return j + 1;
24
+ }
25
+ }
26
+ return -1;
27
+ }
28
+
29
+ function repair(raw) {
30
+ let s = raw;
31
+ const bad = ["\\t", "\\h", "\\w", "\\d", "\\p"];
32
+ for (const b of bad) s = s.split(b).join("/");
33
+ return s;
34
+ }
35
+
36
+ export function parseCalls(text) {
37
+ const out = [];
38
+ const re = /portal-tool[:\s]*/g;
39
+ let m;
40
+ while ((m = re.exec(text))) {
41
+ const b = text.indexOf("{", m.index + m[0].length);
42
+ if (b < 0) continue;
43
+ const e = findEnd(text, b);
44
+ if (e < 0) continue;
45
+ const raw = text.slice(b, e);
46
+ try {
47
+ out.push(JSON.parse(raw));
48
+ } catch (x) {
49
+ try {
50
+ out.push(JSON.parse(repair(raw)));
51
+ } catch (y) {
52
+ // skip malformed
53
+ }
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+
59
+ export function stripCalls(text) {
60
+ return text.replace(/portal-tool[\s\S]*?\n\}/g, "").trim();
61
+ }
package/lib/paste.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import { sleep } from "./wait.mjs";
2
+
3
+ export async function dismissPaste(page) {
4
+ const btns = page.locator("button, [role=button]");
5
+ let total = 0;
6
+ try {
7
+ total = await btns.count();
8
+ } catch (e) {
9
+ return;
10
+ }
11
+ if (total === 0 || total > 300) return;
12
+
13
+ for (let i = 0; i < total; i++) {
14
+ const b = btns.nth(i);
15
+ let text = "";
16
+ try {
17
+ text = ((await b.textContent()) || "").trim();
18
+ } catch (e) {
19
+ continue;
20
+ }
21
+ if (text !== "Cancel") continue;
22
+
23
+ for (let j = 0; j < total; j++) {
24
+ if (j === i) continue;
25
+ const sib = btns.nth(j);
26
+ let st = "";
27
+ try {
28
+ st = ((await sib.textContent()) || "").trim();
29
+ } catch (e) {
30
+ continue;
31
+ }
32
+ if (st === "Send") {
33
+ try {
34
+ await sib.click({ timeout: 1500 });
35
+ await sleep(200);
36
+ return;
37
+ } catch (e) {
38
+ // fall through
39
+ }
40
+ }
41
+ }
42
+
43
+ try {
44
+ await page.keyboard.press("Enter");
45
+ await sleep(150);
46
+ } catch (e) {
47
+ // ignore
48
+ }
49
+ return;
50
+ }
51
+ }
52
+
53
+ export async function composerEmpty(input, ms) {
54
+ const end = Date.now() + ms;
55
+ while (Date.now() < end) {
56
+ let v = "";
57
+ try {
58
+ v = await input.inputValue();
59
+ } catch (e) {
60
+ // contenteditable composers have no inputValue. Treat as sent.
61
+ return true;
62
+ }
63
+ if (!v || v.length === 0) return true;
64
+ await sleep(150);
65
+ }
66
+ return false;
67
+ }
@@ -0,0 +1,29 @@
1
+ export const PROVIDERS = {
2
+ deepseek: {
3
+ id: "deepseek",
4
+ label: "DeepSeek",
5
+ url: "https://chat.deepseek.com/",
6
+ input: "textarea",
7
+ submit: "button[aria-label=Send]",
8
+ response: "div.ds-markdown",
9
+ paste: true
10
+ },
11
+ chatgpt: {
12
+ id: "chatgpt",
13
+ label: "ChatGPT",
14
+ url: "https://chatgpt.com/",
15
+ input: "#prompt-textarea",
16
+ submit: "button[data-testid=send-button]",
17
+ response: "[data-message-author-role=assistant]",
18
+ paste: false
19
+ }
20
+ };
21
+
22
+ export function getProvider(id) {
23
+ const p = PROVIDERS[id];
24
+ if (!p) {
25
+ const names = Object.keys(PROVIDERS).join(", ");
26
+ throw new Error("unknown provider: " + id + ". Available: " + names);
27
+ }
28
+ return p;
29
+ }
package/lib/repl.mjs ADDED
@@ -0,0 +1,119 @@
1
+ import { createInterface } from "node:readline";
2
+ import { existsSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { launch } from "./browser.mjs";
5
+ import { getProvider } from "./providers.mjs";
6
+ import { waitForComposer } from "./wait.mjs";
7
+ import { runTurn } from "./turn.mjs";
8
+ import { setWs, getWs } from "./tools.mjs";
9
+
10
+ export async function runRepl(opts) {
11
+ const provider = getProvider(opts.provider);
12
+ setWs(opts.ws);
13
+
14
+ console.log("");
15
+ console.log("Portal -- web AI in your terminal");
16
+ console.log("workspace: " + getWs());
17
+ console.log("provider: " + provider.label);
18
+ console.log("");
19
+
20
+ const ctx = await launch();
21
+ const page = await ctx.newPage();
22
+ page.setDefaultTimeout(30000);
23
+
24
+ console.log("opening " + provider.label + "...");
25
+ await page.goto(provider.url);
26
+ console.log("");
27
+ console.log("Log in to " + provider.label + " in the Chrome window.");
28
+ console.log("Waiting up to " + Math.round(opts.loginTimeout / 1000) + "s.");
29
+ console.log("");
30
+
31
+ await waitForComposer(page, provider, opts.loginTimeout);
32
+
33
+ console.log("+ " + provider.label + " ready");
34
+ console.log("type /help for commands");
35
+ console.log("");
36
+
37
+ const rl = createInterface({
38
+ input: process.stdin,
39
+ output: process.stdout,
40
+ prompt: "> "
41
+ });
42
+ rl.prompt();
43
+
44
+ let busy = false;
45
+
46
+ rl.on("line", async function (line) {
47
+ const t = line.trim();
48
+
49
+ if (busy) {
50
+ rl.prompt();
51
+ return;
52
+ }
53
+ if (!t) {
54
+ rl.prompt();
55
+ return;
56
+ }
57
+ if (t === "/quit" || t === "/exit") {
58
+ rl.close();
59
+ return;
60
+ }
61
+ if (t === "/help") {
62
+ help();
63
+ rl.prompt();
64
+ return;
65
+ }
66
+ if (t === "/pwd") {
67
+ console.log(getWs());
68
+ rl.prompt();
69
+ return;
70
+ }
71
+ if (t.slice(0, 4) === "/cd ") {
72
+ changeDir(t.slice(4).trim(), rl);
73
+ return;
74
+ }
75
+
76
+ busy = true;
77
+ try {
78
+ await runTurn(page, provider, t, opts);
79
+ } catch (e) {
80
+ console.log("x " + (e.message || e));
81
+ }
82
+ busy = false;
83
+ console.log("");
84
+ rl.prompt();
85
+ });
86
+
87
+ rl.on("close", async function () {
88
+ console.log("");
89
+ console.log("closing browser...");
90
+ await ctx.close().catch(function () {});
91
+ process.exit(0);
92
+ });
93
+ }
94
+
95
+ function help() {
96
+ console.log(" /cd <folder> change workspace");
97
+ console.log(" /pwd show current workspace");
98
+ console.log(" /help show this help");
99
+ console.log(" /quit exit");
100
+ }
101
+
102
+ function changeDir(target, rl) {
103
+ if (!target) {
104
+ console.log("usage: /cd <folder>");
105
+ console.log("current: " + getWs());
106
+ rl.prompt();
107
+ return;
108
+ }
109
+ const clean = target.replace(/^"|"$/g, "");
110
+ const abs = resolve(clean);
111
+ if (!existsSync(abs)) {
112
+ console.log("not found: " + abs);
113
+ rl.prompt();
114
+ return;
115
+ }
116
+ setWs(abs);
117
+ console.log("workspace: " + getWs());
118
+ rl.prompt();
119
+ }
package/lib/send.mjs ADDED
@@ -0,0 +1,88 @@
1
+ import { sleep, norm } from "./wait.mjs";
2
+ import { dismissPaste, composerEmpty } from "./paste.mjs";
3
+
4
+ export async function send(page, provider, prompt, timeoutMs) {
5
+ const input = page.locator(provider.input).last();
6
+ await input.waitFor({ state: "visible", timeout: 30000 });
7
+ const before = await page.locator(provider.response).count();
8
+
9
+ await input.focus();
10
+ try {
11
+ await page.keyboard.press("Control+A");
12
+ await page.keyboard.press("Delete");
13
+ } catch (e) {
14
+ // composer may be empty
15
+ }
16
+
17
+ await page.keyboard.insertText(prompt);
18
+ await sleep(300);
19
+
20
+ if (provider.paste) await dismissPaste(page);
21
+
22
+ try {
23
+ await input.press("Enter");
24
+ } catch (e) {
25
+ // fall through to button
26
+ }
27
+
28
+ let ok = await composerEmpty(input, 5000);
29
+
30
+ if (!ok) {
31
+ const btn = page.locator(provider.submit).last();
32
+ try {
33
+ if (await btn.isVisible({ timeout: 1500 })) await btn.click();
34
+ } catch (e) {
35
+ // no button
36
+ }
37
+ ok = await composerEmpty(input, 3000);
38
+ }
39
+
40
+ if (!ok) {
41
+ throw new Error(
42
+ "Message stayed in composer. Look at the Chrome window: if a " +
43
+ "Cancel/Send bar is showing, click Send manually once, then resend."
44
+ );
45
+ }
46
+
47
+ const want = norm(prompt);
48
+ const end = Date.now() + timeoutMs;
49
+ let appeared = false;
50
+
51
+ while (Date.now() < end) {
52
+ const c = await page.locator(provider.response).count();
53
+ if (c > before) {
54
+ appeared = true;
55
+ break;
56
+ }
57
+ await sleep(300);
58
+ }
59
+
60
+ if (!appeared) throw new Error("No response appeared within the timeout.");
61
+
62
+ let last = "";
63
+ let stab = Date.now();
64
+
65
+ while (Date.now() < end) {
66
+ const node = page.locator(provider.response).last();
67
+ let tx = "";
68
+ try {
69
+ tx = (await node.textContent()) || "";
70
+ } catch (e) {
71
+ tx = "";
72
+ }
73
+ const n = norm(tx);
74
+ if (!n || n === want) {
75
+ await sleep(300);
76
+ continue;
77
+ }
78
+ if (tx !== last) {
79
+ last = tx;
80
+ stab = Date.now();
81
+ } else if (Date.now() - stab > 1500) {
82
+ return tx;
83
+ }
84
+ await sleep(300);
85
+ }
86
+
87
+ return last || "(timeout)";
88
+ }
package/lib/system.mjs ADDED
@@ -0,0 +1,24 @@
1
+ import { CATALOG } from "./tools.mjs";
2
+
3
+ export function buildSystem(ws) {
4
+ const shown = ws.split("\\").join("/");
5
+ return [
6
+ "You are a coding agent working in a terminal.",
7
+ "Workspace: " + shown,
8
+ "Use forward slashes in every path, even on Windows.",
9
+ "",
10
+ "To call a tool, write on its own line:",
11
+ "portal-tool: {\"tool\":\"name\",\"args\":{\"key\":\"value\"}}",
12
+ "",
13
+ "The JSON must use double quotes around keys and values.",
14
+ "Plain text only. Do not wrap the call in a code block.",
15
+ "One call per action. Never repeat a call with the same arguments.",
16
+ "",
17
+ "If a tool returns an empty result, that is final. Report it.",
18
+ "If unsure what to do, reply with plain prose and ask.",
19
+ "When done, reply with plain prose and no tool calls.",
20
+ "",
21
+ "Available tools:",
22
+ CATALOG
23
+ ].join("\n");
24
+ }
package/lib/tools.mjs ADDED
@@ -0,0 +1,151 @@
1
+ import { readFile, writeFile, mkdir, readdir, stat } from "node:fs/promises";
2
+ import { dirname, resolve, relative, sep, join } from "node:path";
3
+ import { spawn } from "node:child_process";
4
+
5
+ let ws = process.cwd();
6
+
7
+ export function setWs(p) {
8
+ ws = resolve(p);
9
+ }
10
+
11
+ export function getWs() {
12
+ return ws;
13
+ }
14
+
15
+ const IGNORE = new Set([
16
+ "node_modules", ".git", ".hg", ".svn", "dist", "build", "out",
17
+ ".next", ".nuxt", ".turbo", ".cache", "target", "__pycache__",
18
+ ".venv", "venv", "env", "coverage", ".idea", ".vscode"
19
+ ]);
20
+
21
+ function safe(p) {
22
+ const a = resolve(ws, p);
23
+ const r = relative(ws, a);
24
+ if (r === ".." || r.slice(0, 3) === "..\\" || r.slice(0, 3) === "../") {
25
+ throw new Error("path escapes workspace: " + p);
26
+ }
27
+ return a;
28
+ }
29
+
30
+ async function* walk(dir) {
31
+ let items;
32
+ try {
33
+ items = await readdir(dir, { withFileTypes: true });
34
+ } catch (e) {
35
+ return;
36
+ }
37
+ for (const it of items) {
38
+ if (IGNORE.has(it.name)) continue;
39
+ if (it.name.startsWith(".") && it.name !== ".env.example") continue;
40
+ const full = join(dir, it.name);
41
+ if (it.isDirectory()) yield* walk(full);
42
+ else if (it.isFile()) yield full;
43
+ }
44
+ }
45
+
46
+ export const tools = {
47
+ read_file: async function (a) {
48
+ const t = await readFile(safe(a.path), "utf8");
49
+ return t.length > 200000 ? t.slice(0, 200000) + "\n[truncated]" : t;
50
+ },
51
+
52
+ write_file: async function (a) {
53
+ const x = safe(a.path);
54
+ await mkdir(dirname(x), { recursive: true });
55
+ await writeFile(x, a.content || "", "utf8");
56
+ return "wrote " + (a.content || "").length + " bytes to " + a.path;
57
+ },
58
+
59
+ edit_file: async function (a) {
60
+ const x = safe(a.path);
61
+ const orig = await readFile(x, "utf8");
62
+ const n = orig.split(a.old_string).length - 1;
63
+ if (n === 0) return "old_string not found in " + a.path;
64
+ if (n > 1 && !a.replace_all) return "old_string appears " + n + " times";
65
+ const next = a.replace_all
66
+ ? orig.split(a.old_string).join(a.new_string)
67
+ : orig.replace(a.old_string, a.new_string);
68
+ await writeFile(x, next, "utf8");
69
+ return "edited " + a.path;
70
+ },
71
+
72
+ list_files: async function (a) {
73
+ const e = await readdir(safe(a.path || "."), { withFileTypes: true });
74
+ if (!e.length) return "EMPTY. Do not call list_files again.";
75
+ const names = e.map(function (x) {
76
+ return (x.isDirectory() ? "[dir] " : " ") + x.name;
77
+ });
78
+ names.sort();
79
+ return names.join("\n");
80
+ },
81
+
82
+ grep_search: async function (a) {
83
+ let re;
84
+ try {
85
+ re = new RegExp(a.pattern, a.case_sensitive ? "" : "i");
86
+ } catch (e) {
87
+ return "bad regex: " + e.message;
88
+ }
89
+ const hits = [];
90
+ for await (const f of walk(ws)) {
91
+ if (hits.length >= 80) break;
92
+ let info;
93
+ try {
94
+ info = await stat(f);
95
+ } catch (e) {
96
+ continue;
97
+ }
98
+ if (info.size > 512000) continue;
99
+ let t;
100
+ try {
101
+ t = await readFile(f, "utf8");
102
+ } catch (e) {
103
+ continue;
104
+ }
105
+ const lines = t.split("\n");
106
+ for (let i = 0; i < lines.length && hits.length < 80; i++) {
107
+ if (re.test(lines[i])) {
108
+ const rel = relative(ws, f).split(sep).join("/");
109
+ hits.push(rel + ":" + (i + 1) + ":" + lines[i].trim().slice(0, 200));
110
+ }
111
+ }
112
+ }
113
+ return hits.length ? hits.join("\n") : "no matches";
114
+ },
115
+
116
+ shell: function (a) {
117
+ const cmd = String(a.command || "");
118
+ if (!cmd) return Promise.resolve("shell requires command");
119
+ return new Promise(function (done) {
120
+ const c = spawn(cmd, { cwd: ws, shell: true, windowsHide: true });
121
+ let o = "";
122
+ let e = "";
123
+ if (c.stdout) c.stdout.on("data", function (d) { o += String(d); });
124
+ if (c.stderr) c.stderr.on("data", function (d) { e += String(d); });
125
+ const to = setTimeout(function () {
126
+ c.kill();
127
+ done("timed out after 60s");
128
+ }, 60000);
129
+ c.on("error", function (err) {
130
+ clearTimeout(to);
131
+ done("error: " + err.message);
132
+ });
133
+ c.on("close", function (code) {
134
+ clearTimeout(to);
135
+ const both = [o.trim(), e.trim()].filter(Boolean).join("\n");
136
+ let s = "exit " + code + "\n" + (both || "(no output)");
137
+ if (s.length > 65000) s = s.slice(0, 65000) + "\n[truncated]";
138
+ done(s);
139
+ });
140
+ });
141
+ }
142
+ };
143
+
144
+ export const CATALOG = [
145
+ "- read_file(path, start_line?, end_line?)",
146
+ "- write_file(path, content)",
147
+ "- edit_file(path, old_string, new_string, replace_all?)",
148
+ "- list_files(path?)",
149
+ "- grep_search(pattern, case_sensitive?)",
150
+ "- shell(command)"
151
+ ].join("\n");
package/lib/turn.mjs ADDED
@@ -0,0 +1,57 @@
1
+ import { send } from "./send.mjs";
2
+ import { parseCalls, stripCalls } from "./parse.mjs";
3
+ import { tools, getWs } from "./tools.mjs";
4
+ import { buildSystem } from "./system.mjs";
5
+
6
+ export async function runTurn(page, provider, prompt, opts) {
7
+ const sys = buildSystem(getWs());
8
+ const seen = new Map();
9
+ let next = sys + "\n\nTask: " + prompt;
10
+
11
+ for (let i = 0; i < opts.maxSteps; i++) {
12
+ console.log(" waiting for " + provider.label + "...");
13
+ const r = await send(page, provider, next, opts.timeout);
14
+ const calls = parseCalls(r);
15
+
16
+ if (!calls.length) {
17
+ const prose = stripCalls(r);
18
+ if (prose) console.log("\n" + prose + "\n");
19
+ return;
20
+ }
21
+
22
+ const results = [];
23
+ let stop = false;
24
+
25
+ for (const c of calls) {
26
+ const sig = c.tool + ":" + JSON.stringify(c.args || {});
27
+ const n = (seen.get(sig) || 0) + 1;
28
+ seen.set(sig, n);
29
+
30
+ if (n >= 3) {
31
+ console.log("loop detected: " + c.tool + " repeated. stopping.");
32
+ stop = true;
33
+ break;
34
+ }
35
+
36
+ console.log("> " + c.tool + " " + JSON.stringify(c.args || {}).slice(0, 120));
37
+
38
+ let out;
39
+ try {
40
+ const fn = tools[c.tool];
41
+ out = fn ? await fn(c.args || {}) : "unknown tool: " + c.tool;
42
+ } catch (e) {
43
+ out = "error: " + (e.message || e);
44
+ }
45
+
46
+ console.log(" " + String(out).slice(0, 240).split("\n").join("\n "));
47
+ results.push(c.tool + ":\n" + out);
48
+ }
49
+
50
+ if (stop) return;
51
+
52
+ next = "Results:\n\n" + results.join("\n\n") +
53
+ "\n\nContinue. Do not repeat any call with the same arguments.";
54
+ }
55
+
56
+ console.log("max steps reached for this turn.");
57
+ }
package/lib/wait.mjs ADDED
@@ -0,0 +1,32 @@
1
+ export function sleep(ms) {
2
+ return new Promise(function (r) { setTimeout(r, ms); });
3
+ }
4
+
5
+ export function norm(s) {
6
+ return String(s || "").replace(/\s+/g, " ").trim();
7
+ }
8
+
9
+ export async function waitForComposer(page, p, ms) {
10
+ const end = Date.now() + ms;
11
+ let hint = Date.now();
12
+ while (Date.now() < end) {
13
+ const loc = page.locator(p.input).last();
14
+ let ok = false;
15
+ try {
16
+ ok = await loc.isVisible({ timeout: 250 });
17
+ } catch (e) {
18
+ ok = false;
19
+ }
20
+ if (ok) return loc;
21
+ if (Date.now() - hint > 15000) {
22
+ const left = Math.round((end - Date.now()) / 1000);
23
+ process.stdout.write(" waiting for login (" + left + "s left)\n");
24
+ hint = Date.now();
25
+ }
26
+ await sleep(1000);
27
+ }
28
+ throw new Error(
29
+ "Timed out waiting for the composer. Log in to the provider " +
30
+ "and try again, or raise --login-timeout."
31
+ );
32
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "portal-agent-cli",
3
+ "version": "1.0.0",
4
+ "description": "Drive web AI products from the terminal with local tools. Enter-first submit, paste-safe insertion, prompt-echo skip, loop breaker.",
5
+ "type": "module",
6
+ "bin": {
7
+ "portal-agent": "./portal.mjs"
8
+ },
9
+ "main": "./portal.mjs",
10
+ "files": [
11
+ "portal.mjs",
12
+ "lib/",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "scripts": {
20
+ "start": "node portal.mjs",
21
+ "build": "pkg portal.mjs --targets node18-win-x64 --output portal.exe"
22
+ },
23
+ "dependencies": {
24
+ "playwright": "^1.48.0"
25
+ },
26
+ "devDependencies": {
27
+ "pkg": "^5.8.1"
28
+ },
29
+ "keywords": [
30
+ "browser",
31
+ "automation",
32
+ "cli",
33
+ "ai",
34
+ "agent",
35
+ "deepseek",
36
+ "chatgpt",
37
+ "playwright"
38
+ ],
39
+ "author": "your-name",
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/your-name/portal-agent-cli"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/your-name/portal-agent-cli/issues"
47
+ },
48
+ "homepage": "https://github.com/your-name/portal-agent-cli#readme"
49
+ }
package/portal.mjs ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "./lib/args.mjs";
3
+ import { runRepl } from "./lib/repl.mjs";
4
+ import { runExec } from "./lib/exec.mjs";
5
+
6
+ const opts = parseArgs();
7
+
8
+ const task = opts.exec ? runExec(opts) : runRepl(opts);
9
+
10
+ task.catch(function (e) {
11
+ console.error(e.message || e);
12
+ process.exit(1);
13
+ });