portal-agent-cli 1.0.1 → 3.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 CHANGED
@@ -1,21 +1,3 @@
1
1
  MIT License
2
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.
3
+ Copyright (c) 2026
package/README.md CHANGED
@@ -1,113 +1,55 @@
1
1
  # portal-agent
2
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.
3
+ Drive
4
+ ```
6
5
 
7
- Supports **DeepSeek** and **ChatGPT**.
6
+ npm install -g portal-agent-cli
8
7
 
9
- ## Install
10
-
11
- npm install -g portal-agent-cli
8
+ ```
12
9
 
13
10
  ## Run
14
11
 
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)
12
+ ```
38
13
 
39
- ## Environment variables
14
+ portal-agent --workspace F:/projects/my-app
40
15
 
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
16
+ ```
45
17
 
46
- ## One-shot mode
18
+ Or without installing
19
+ ```
47
20
 
48
- portal-agent --workspace F:/proj exec "list the files here"
21
+ npx portal-agent-cli --workspace F:/projects/my-app
49
22
 
50
- ## Tools the model can call
23
+ ```
51
24
 
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.
25
+ On first run, Chrome opens at the provider site. Log in there. The session
26
+ ```
84
27
 
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`.
28
+ portal-agent --workspace F:/proj exec "list the files here"
89
29
 
90
- **Loop breaker.** Identical tool calls are counted per turn. Three calls with
91
- the same arguments stops the turn.
30
+ ```
92
31
 
93
- ## Troubleshooting
32
+ ## Tools
94
33
 
95
- **`No Chrome found`** -- install Chrome, Edge, or Brave, or set
96
- `PORTAL_BROWSER_PATH` to the full path of the browser executable.
34
+ | Tool | Description |
35
+ |-|-|
36
+ ```
97
37
 
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.
38
+ - approval required
39
+ tool: shell
40
+ {
41
+ "command": "npm test"
42
+ }
43
+ allow? yes / always / no:
101
44
 
102
- **`Message stayed in composer`** -- look at the Chrome window. If a
103
- Cancel/Send bar is showing, click Send once manually. Then resend.
45
+ ```
104
46
 
105
- **`No response appeared within the timeout`** -- raise `--timeout`. DeepSeek
106
- can be slow under load.
47
+ Answer
48
+ ```
107
49
 
108
- **Selectors broken after a provider UI update** -- edit `lib/providers.mjs`
109
- and add or reorder selectors for the affected provider.
50
+ portal-tool: {"tool":"read_file","args":{"path":"notes.txt"}}
110
51
 
111
- ## License
52
+ ```
112
53
 
113
- MIT
54
+ Portal parses that line, runs the tool locally, and sends the result back
55
+ into the same conversation. This
package/lib/args.mjs CHANGED
@@ -1,55 +1,89 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
+ import { theme } from "./theme.mjs";
3
4
 
4
5
  export function parseArgs() {
5
6
  const a = process.argv.slice(2);
6
7
  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
8
+ ws: null,
9
+ provider: null,
10
+ model: null,
11
+ maxSteps: null,
12
+ timeout: null,
13
+ loginTimeout: null,
14
+ exec: null,
15
+ verbose: false,
16
+ yolo: false,
17
+ session: null,
18
+ resume: null,
19
+ theme: "auto"
13
20
  };
21
+
14
22
  let i = 0;
15
23
  while (i < a.length) {
16
24
  const t = a[i];
17
25
  if (t === "-w" || t === "--workspace") o.ws = a[++i];
18
- else if (t === "--provider") o.provider = a[++i];
26
+ else if (t === "-p" || t === "--provider") o.provider = a[++i];
27
+ else if (t === "--model") o.model = a[++i];
19
28
  else if (t === "--timeout") o.timeout = Number(a[++i]);
20
29
  else if (t === "--login-timeout") o.loginTimeout = Number(a[++i]);
21
30
  else if (t === "--max-steps") o.maxSteps = Number(a[++i]);
31
+ else if (t === "--session") o.session = a[++i];
32
+ else if (t === "--resume") o.resume = a[++i];
33
+ else if (t === "--theme") o.theme = a[++i];
34
+ else if (t === "--verbose" || t === "-V") o.verbose = true;
35
+ else if (t === "--yolo") o.yolo = true;
22
36
  else if (t === "exec") { o.exec = a.slice(i + 1).join(" "); break; }
23
37
  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); }
38
+ else if (t === "--version" || t === "-v") { console.log("2.0.0"); process.exit(0); }
25
39
  i++;
26
40
  }
27
- o.ws = resolve(o.ws);
28
- if (!existsSync(o.ws)) {
29
- console.error("workspace not found: " + o.ws);
30
- process.exit(2);
41
+
42
+ if (o.ws) {
43
+ o.ws = resolve(o.ws);
44
+ if (!existsSync(o.ws)) {
45
+ process.stderr.write("workspace not found: " + o.ws + "\n");
46
+ process.exit(2);
47
+ }
31
48
  }
49
+
32
50
  return o;
33
51
  }
34
52
 
35
53
  function help() {
54
+ const t = theme;
55
+ console.log("");
56
+ console.log(t.bold("portal-agent") + t.dim(" -- drive web AI from the terminal"));
36
57
  console.log("");
37
- console.log("portal-agent -- drive web AI from the terminal");
58
+ console.log(t.bold("USAGE"));
59
+ console.log(" portal-agent [options]");
60
+ console.log(" portal-agent [options] exec <task>");
38
61
  console.log("");
39
- console.log("Usage:");
40
- console.log(" portal-agent --workspace DIR");
41
- console.log(" portal-agent --workspace DIR exec TASK");
62
+ console.log(t.bold("OPTIONS"));
63
+ console.log(" -w, --workspace <dir> folder the agent works in");
64
+ console.log(" -p, --provider <name> deepseek | chatgpt | gemini | grok");
65
+ console.log(" --model <name> provider-specific model hint");
66
+ console.log(" --timeout <ms> response timeout (default 180000)");
67
+ console.log(" --login-timeout <ms> login wait (default 600000)");
68
+ console.log(" --max-steps <n> max tool steps per turn (default 12)");
69
+ console.log(" --session <name> start or reuse a named session");
70
+ console.log(" --resume <name> resume a saved session");
71
+ console.log(" --theme <name> auto | dark | light");
72
+ console.log(" -V, --verbose print config on startup");
73
+ console.log(" --yolo auto-approve every tool call");
74
+ console.log(" -h, --help show this help");
75
+ console.log(" -v, --version show version");
42
76
  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)");
77
+ console.log(t.bold("ENVIRONMENT"));
78
+ console.log(" PORTAL_WORKSPACE same as --workspace");
79
+ console.log(" PORTAL_PROVIDER default provider");
80
+ console.log(" PORTAL_BROWSER_PATH explicit browser executable");
81
+ console.log(" PORTAL_DEBUG print stack traces on error");
82
+ console.log(" PORTAL_YOLO same as --yolo");
49
83
  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");
84
+ console.log(t.bold("EXAMPLES"));
85
+ console.log(" portal-agent --workspace F:/projects/app");
86
+ console.log(" portal-agent -w . -p chatgpt");
87
+ console.log(" portal-agent exec \"list the files here\"");
54
88
  console.log("");
55
89
  }
package/lib/browser.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { chromium } from "playwright";
2
2
  import { existsSync } from "node:fs";
3
3
  import { mkdir } from "node:fs/promises";
4
- import { resolve, join } from "node:path";
4
+ import { join } from "node:path";
5
5
  import { homedir } from "node:os";
6
6
 
7
7
  const CANDIDATES = [
@@ -11,13 +11,16 @@ const CANDIDATES = [
11
11
  "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
12
12
  "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
13
13
  "C:/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe",
14
+ "C:/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
14
15
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
15
16
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
16
17
  "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
18
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
17
19
  "/usr/bin/google-chrome",
18
20
  "/usr/bin/google-chrome-stable",
19
21
  "/usr/bin/chromium",
20
- "/usr/bin/chromium-browser"
22
+ "/usr/bin/chromium-browser",
23
+ "/usr/bin/microsoft-edge"
21
24
  ];
22
25
 
23
26
  export function findBrowser() {
@@ -27,27 +30,48 @@ export function findBrowser() {
27
30
  return null;
28
31
  }
29
32
 
30
- export async function launch() {
33
+ export function listBrowsers() {
34
+ const found = [];
35
+ for (const p of CANDIDATES) {
36
+ if (p && existsSync(p)) found.push(p);
37
+ }
38
+ return found;
39
+ }
40
+
41
+ export async function launch(opts) {
31
42
  const exe = findBrowser();
32
43
  if (!exe) {
33
44
  throw new Error(
34
- "No Chrome, Chromium, Edge, or Brave found. " +
35
- "Install one, or set PORTAL_BROWSER_PATH to its full path."
45
+ "No Chrome, Chromium, Edge, or Brave found.\n" +
46
+ "Install one, or set PORTAL_BROWSER_PATH to the full path of your browser."
36
47
  );
37
48
  }
38
- const dir = join(homedir(), ".portal-agent", "browser");
39
- await mkdir(dir, { recursive: true });
49
+
50
+ const profileDir = join(homedir(), ".portal-agent", "browser");
51
+ await mkdir(profileDir, { recursive: true });
52
+
40
53
  try {
41
- return await chromium.launchPersistentContext(dir, {
54
+ const ctx = await chromium.launchPersistentContext(profileDir, {
42
55
  executablePath: exe,
43
56
  headless: false,
44
- viewport: { width: 1280, height: 900 }
57
+ viewport: { width: 1280, height: 900 },
58
+ args: ["--disable-blink-features=AutomationControlled"]
59
+ });
60
+
61
+ // Auto-dismiss dialogs (alert, confirm, prompt) so a stray modal cannot
62
+ // freeze the session.
63
+ ctx.on("page", function (page) {
64
+ page.on("dialog", function (d) {
65
+ d.dismiss().catch(function () {});
66
+ });
45
67
  });
68
+
69
+ return ctx;
46
70
  } catch (e) {
47
71
  const m = e.message || String(e);
48
72
  if (/ProcessSingleton|already running|profile/i.test(m)) {
49
73
  throw new Error(
50
- "Another Chrome window is using the same profile. " +
74
+ "Another Chrome window is using the Portal profile.\n" +
51
75
  "Close every Chrome window and try again."
52
76
  );
53
77
  }
package/lib/config.mjs ADDED
@@ -0,0 +1,78 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { resolve, join, dirname } from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { mkdir, writeFile } from "node:fs/promises";
5
+
6
+ const DEFAULTS = {
7
+ provider: "deepseek",
8
+ maxSteps: 12,
9
+ timeout: 180000,
10
+ loginTimeout: 600000,
11
+ theme: "auto",
12
+ yolo: false,
13
+ verbose: false,
14
+ instructions: ["PORTAL.md", "AGENTS.md", ".portal.md"],
15
+ ignored: [
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
+
22
+ export function configPath() {
23
+ return join(homedir(), ".portal-agent", "config.json");
24
+ }
25
+
26
+ export function readGlobalConfig() {
27
+ const p = configPath();
28
+ if (!existsSync(p)) return {};
29
+ try {
30
+ return JSON.parse(readFileSync(p, "utf8"));
31
+ } catch (e) {
32
+ return {};
33
+ }
34
+ }
35
+
36
+ export async function writeGlobalConfig(obj) {
37
+ const p = configPath();
38
+ await mkdir(dirname(p), { recursive: true });
39
+ await writeFile(p, JSON.stringify(obj, null, 2), "utf8");
40
+ }
41
+
42
+ export async function loadConfig(args) {
43
+ const global = readGlobalConfig();
44
+
45
+ const config = {
46
+ ...DEFAULTS,
47
+ ...global,
48
+ ws: args.ws || process.env.PORTAL_WORKSPACE || process.cwd(),
49
+ provider: args.provider || process.env.PORTAL_PROVIDER || global.provider || DEFAULTS.provider,
50
+ maxSteps: args.maxSteps || global.maxSteps || DEFAULTS.maxSteps,
51
+ timeout: args.timeout || global.timeout || DEFAULTS.timeout,
52
+ loginTimeout: args.loginTimeout || global.loginTimeout || DEFAULTS.loginTimeout,
53
+ theme: args.theme || global.theme || DEFAULTS.theme,
54
+ yolo: args.yolo || process.env.PORTAL_YOLO === "true" || global.yolo || DEFAULTS.yolo,
55
+ verbose: args.verbose || global.verbose || DEFAULTS.verbose,
56
+ exec: args.exec,
57
+ session: args.session || null,
58
+ resume: args.resume || null
59
+ };
60
+
61
+ config.ws = resolve(config.ws);
62
+ if (!existsSync(config.ws)) {
63
+ throw new Error("workspace does not exist: " + config.ws);
64
+ }
65
+
66
+ // Per-project config file
67
+ const localPath = join(config.ws, "portal.config.json");
68
+ if (existsSync(localPath)) {
69
+ try {
70
+ const local = JSON.parse(readFileSync(localPath, "utf8"));
71
+ Object.assign(config, local);
72
+ } catch (e) {
73
+ // ignore malformed local config
74
+ }
75
+ }
76
+
77
+ return config;
78
+ }
package/lib/exec.mjs CHANGED
@@ -2,26 +2,31 @@ import { launch } from "./browser.mjs";
2
2
  import { getProvider } from "./providers.mjs";
3
3
  import { waitForComposer } from "./wait.mjs";
4
4
  import { runTurn } from "./turn.mjs";
5
- import { setWs } from "./tools.mjs";
5
+ import { setWorkspace } from "./tools/path.mjs";
6
+ import { setIgnore } from "./tools/walk.mjs";
7
+ import { loadInstructions } from "./instructions.mjs";
8
+ import { info, error } from "./log.mjs";
6
9
 
7
- export async function runExec(opts) {
8
- const provider = getProvider(opts.provider);
9
- setWs(opts.ws);
10
+ export async function runExec(config) {
11
+ const provider = getProvider(config.provider);
12
+ setWorkspace(config.ws);
13
+ setIgnore(config.ignored);
14
+
15
+ config.instructionsText = await loadInstructions(config.ws);
10
16
 
11
17
  const ctx = await launch();
12
18
  const page = await ctx.newPage();
13
19
  page.setDefaultTimeout(30000);
14
20
 
21
+ info("opening " + provider.label + "...");
15
22
  await page.goto(provider.url);
16
- await waitForComposer(page, provider, opts.loginTimeout);
23
+ await waitForComposer(page, provider, config.loginTimeout);
17
24
 
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
- }
25
+ const session = {
26
+ id: "exec-" + Date.now(),
27
+ ws: config.ws,
28
+ provider: config.provider,
29
+ turns: [],
30
+ approvedAlways: [],
31
+ startedAt: Date.now(),
32
+
@@ -0,0 +1,44 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ const FILENAMES = ["PORTAL.md", "AGENTS.md", ".portal.md", "CLAUDE.md"];
5
+
6
+ let cache = null;
7
+ let cacheKey = "";
8
+
9
+ export async function loadInstructions(ws) {
10
+ for (const name of FILENAMES) {
11
+ const path = join(ws, name);
12
+ let info;
13
+ try {
14
+ info = await stat(path);
15
+ } catch (e) {
16
+ continue;
17
+ }
18
+
19
+ const key = path + ":" + info.mtimeMs;
20
+ if (cache && cacheKey === key) return cache;
21
+
22
+ try {
23
+ const content = await readFile(path, "utf8");
24
+ const trimmed = content.trim();
25
+ if (!trimmed) return null;
26
+ cache = [
27
+ "# Project instructions",
28
+ "",
29
+ "The user placed these instructions in " + name + ". Follow them.",
30
+ "",
31
+ trimmed
32
+ ].join("\n");
33
+ cacheKey = key;
34
+ return cache;
35
+ } catch (e) {
36
+ continue;
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+
42
+ export function activeInstructionFile() {
43
+ return cacheKey ? cacheKey.split(":")[0] : null;
44
+ }
package/lib/log.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import { theme } from "./theme.mjs";
2
+
3
+ export function info(s) {
4
+ process.stdout.write(theme.dim(s) + "\n");
5
+ }
6
+
7
+ export function warn(s) {
8
+ process.stdout.write(theme.warn("! " + s) + "\n");
9
+ }
10
+
11
+ export function error(s) {
12
+ process.stderr.write(theme.error("x " + s) + "\n");
13
+ }
14
+
15
+ export function ok(s) {
16
+ process.stdout.write(theme.ok("+ " + s) + "\n");
17
+ }
18
+
19
+ export function status(s) {
20
+ process.stdout.write(theme.dim(" " + s) + "\n");
21
+ }
22
+
23
+ export function tool(name, args) {
24
+ const preview = args ? JSON.stringify(args).slice(0, 140) : "";
25
+ process.stdout.write("\n" + theme.tool("> " + name) + " " + theme.dim(preview) + "\n");
26
+ }
27
+
28
+ export function toolResult(text, isError) {
29
+ const body = String(text || "").split("\n").slice(0, 12).join("\n ");
30
+ const prefix = isError ? theme.red(" x ") : theme.dim(" ");
31
+ process.stdout.write(prefix + body + "\n");
32
+ }
33
+
34
+ export function reply(text) {
35
+ if (!text) return;
36
+ process.stdout.write("\n" + theme.cyan("* ") + text + "\n");
37
+ }
38
+
39
+ export function blank() {
40
+ process.stdout.write("\n");
41
+ }
package/lib/parse.mjs CHANGED
@@ -1,53 +1,57 @@
1
- function findEnd(s, i) {
2
- let d = 0;
3
- let q = false;
4
- let e = false;
1
+ // Tool call protocol:
2
+ //
3
+ // portal-tool: {"tool":"name","args":{"key":"value"}}
4
+ //
5
+ // Written as plain text on its own line. The parser scans for the literal
6
+ // string "portal-tool", finds the balanced JSON object that follows, and
7
+ // tries to parse it. If parse fails, common Windows backslash escapes are
8
+ // repaired first (models copy "L:\this\file" and JSON sees \t, \h, \w as
9
+ // escapes that blow up the parse).
10
+
11
+ function findJsonEnd(s, i) {
12
+ let depth = 0;
13
+ let inStr = false;
14
+ let esc = false;
5
15
  for (let j = i; j < s.length; j++) {
6
16
  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++;
17
+ if (esc) { esc = false; continue; }
18
+ if (c === "\\") { esc = true; continue; }
19
+ if (c === String.fromCharCode(34)) { inStr = !inStr; continue; }
20
+ if (inStr) continue;
21
+ if (c === "{") depth++;
21
22
  else if (c === "}") {
22
- d--;
23
- if (!d) return j + 1;
23
+ depth--;
24
+ if (!depth) return j + 1;
24
25
  }
25
26
  }
26
27
  return -1;
27
28
  }
28
29
 
29
- function repair(raw) {
30
+ function repairBackslashes(raw) {
30
31
  let s = raw;
31
- const bad = ["\\t", "\\h", "\\w", "\\d", "\\p"];
32
+ const bad = ["\\t", "\\h", "\\w", "\\d", "\\p", "\\v", "\\x", "\\c"];
32
33
  for (const b of bad) s = s.split(b).join("/");
33
34
  return s;
34
35
  }
35
36
 
36
37
  export function parseCalls(text) {
37
38
  const out = [];
39
+ const seen = new Set();
38
40
  const re = /portal-tool[:\s]*/g;
39
41
  let m;
40
42
  while ((m = re.exec(text))) {
41
43
  const b = text.indexOf("{", m.index + m[0].length);
42
44
  if (b < 0) continue;
43
- const e = findEnd(text, b);
45
+ const e = findJsonEnd(text, b);
44
46
  if (e < 0) continue;
45
47
  const raw = text.slice(b, e);
48
+ if (seen.has(raw)) continue;
49
+ seen.add(raw);
46
50
  try {
47
51
  out.push(JSON.parse(raw));
48
52
  } catch (x) {
49
53
  try {
50
- out.push(JSON.parse(repair(raw)));
54
+ out.push(JSON.parse(repairBackslashes(raw)));
51
55
  } catch (y) {
52
56
  // skip malformed
53
57
  }
@@ -59,3 +63,7 @@ export function parseCalls(text) {
59
63
  export function stripCalls(text) {
60
64
  return text.replace(/portal-tool[\s\S]*?\n\}/g, "").trim();
61
65
  }
66
+
67
+ export function hasToolCall(text) {
68
+ return /portal-tool[:\s]*\{/.test(text);
69
+ }