portal-agent-cli 1.0.1 → 3.0.1

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,5 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 your-name
3
+ Copyright (c) 2026
4
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.
5
+ Permission is hereby granted, free of charge, to any
package/README.md CHANGED
@@ -1,113 +1,63 @@
1
1
  # portal-agent
2
2
 
3
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.
4
+ Chromium browser against the provider's own website. No
5
+ ```
6
6
 
7
- Supports **DeepSeek** and **ChatGPT**.
7
+ npm install -g portal-agent-cli
8
8
 
9
- ## Install
10
-
11
- npm install -g portal-agent-cli
9
+ ```
12
10
 
13
11
  ## Run
14
12
 
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
13
+ ```
32
14
 
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)
15
+ portal-agent --workspace F:/projects/my-app
38
16
 
39
- ## Environment variables
17
+ ```
40
18
 
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:
19
+ Or without installing:
63
20
 
64
- portal-tool: {"tool":"read_file","args":{"path":"notes.txt"}}
21
+ ```
65
22
 
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.
23
+ npx portal-agent-cli --workspace F:/projects/my-app
68
24
 
69
- ## Design notes
25
+ ```
70
26
 
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.
27
+ On first run, Chrome
28
+ ```
75
29
 
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.
30
+ portal-agent --workspace F:/proj exec "list the files here"
79
31
 
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.
32
+ ```
84
33
 
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`.
34
+ ## Tools
89
35
 
90
- **Loop breaker.** Identical tool calls are counted per turn. Three calls with
91
- the same arguments stops the turn.
36
+ | Tool | Description |
37
+ |------|-------------|
38
+ | `read_file(path, start_line?, end_line?)` | read with line numbers |
39
+ | `write_file(path, content)` | write a whole file (backs up existing) |
40
+ | `edit_file(path, old_string, new_string, replace_all?)`
41
+ ```
92
42
 
93
- ## Troubleshooting
43
+ - approval required
44
+ tool: shell
45
+ {
46
+ "command": "npm test"
47
+ }
48
+ allow? yes / always / no:
94
49
 
95
- **`No Chrome found`** -- install Chrome, Edge, or Brave, or set
96
- `PORTAL_BROWSER_PATH` to the full path of the browser executable.
50
+ ```
97
51
 
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.
52
+ Answering `a` approves that tool for the rest of the session.
101
53
 
102
- **`Message stayed in composer`** -- look at the Chrome window. If a
103
- Cancel/Send bar is showing, click Send once manually. Then resend.
54
+ ## Safety
104
55
 
105
- **`No response appeared within the timeout`** -- raise `--timeout`. DeepSeek
106
- can be slow under load.
56
+ -
57
+ ```
107
58
 
108
- **Selectors broken after a provider UI update** -- edit `lib/providers.mjs`
109
- and add or reorder selectors for the affected provider.
59
+ portal-tool: {"tool":"read_file","args":{"path":"notes.txt"}}
110
60
 
111
- ## License
61
+ ```
112
62
 
113
- MIT
63
+ Portal parses that line, runs the tool locally, and sends
package/lib/args.mjs CHANGED
@@ -1,55 +1,91 @@
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("3.0.1"); 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_DEEPTHINK set to off to skip DeepThink toggle");
82
+ console.log(" PORTAL_DEBUG print stack traces on error");
83
+ console.log(" PORTAL_YOLO same as --yolo");
84
+ console.log(" NO_COLOR disable color output");
49
85
  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");
86
+ console.log(t.bold("EXAMPLES"));
87
+ console.log(" portal-agent --workspace F:/projects/app");
88
+ console.log(" portal-agent -w . -p chatgpt");
89
+ console.log(" portal-agent exec \"list the files here\"");
54
90
  console.log("");
55
91
  }
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,46 @@ export function findBrowser() {
27
30
  return null;
28
31
  }
29
32
 
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
+
30
41
  export async function launch() {
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
+ ctx.on("page", function (page) {
62
+ page.on("dialog", function (d) {
63
+ d.dismiss().catch(function () {});
64
+ });
45
65
  });
66
+
67
+ return ctx;
46
68
  } catch (e) {
47
69
  const m = e.message || String(e);
48
70
  if (/ProcessSingleton|already running|profile/i.test(m)) {
49
71
  throw new Error(
50
- "Another Chrome window is using the same profile. " +
72
+ "Another Chrome window is using the Portal profile.\n" +
51
73
  "Close every Chrome window and try again."
52
74
  );
53
75
  }
package/lib/config.mjs ADDED
@@ -0,0 +1,77 @@
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
+ const localPath = join(config.ws, "portal.config.json");
67
+ if (existsSync(localPath)) {
68
+ try {
69
+ const local = JSON.parse(readFileSync(localPath, "utf8"));
70
+ Object.assign(config, local);
71
+ } catch (e) {
72
+ // ignore malformed local config
73
+ }
74
+ }
75
+
76
+ return config;
77
+ }
@@ -0,0 +1,55 @@
1
+ // Toggle DeepSeek's DeepThink reasoning mode. Without this, DeepSeek answers
2
+ // with the fast model and the output is shorter and less thorough.
3
+ //
4
+ // The button sits in the composer row with a label like "DeepThink" or
5
+ // "Deep Think". After clicking, it gains an active class or aria-pressed=true.
6
+
7
+ export async function enableDeepThink(page) {
8
+ if (process.env.PORTAL_DEEPTHINK === "off") return false;
9
+
10
+ const candidates = page.locator("button, [role=button], div[role=button]");
11
+ let total = 0;
12
+ try {
13
+ total = await candidates.count();
14
+ } catch (e) {
15
+ return false;
16
+ }
17
+ if (total === 0 || total > 400) return false;
18
+
19
+ for (let i = 0; i < total; i++) {
20
+ const btn = candidates.nth(i);
21
+ let text = "";
22
+ try {
23
+ text = ((await btn.textContent()) || "").trim();
24
+ } catch (e) {
25
+ continue;
26
+ }
27
+ if (!text) continue;
28
+
29
+ const isDeepthink = text === "DeepThink" ||
30
+ text === "Deep Think" ||
31
+ text.indexOf("DeepThink") >= 0 ||
32
+ text.indexOf("Deep Think") >= 0;
33
+
34
+ if (!isDeepthink) continue;
35
+
36
+ let pressed = "";
37
+ let cls = "";
38
+ try { pressed = (await btn.getAttribute("aria-pressed")) || ""; } catch (e) {}
39
+ try { cls = (await btn.getAttribute("class")) || ""; } catch (e) {}
40
+
41
+ const alreadyOn = pressed === "true" ||
42
+ /active|selected|on\b|enabled/i.test(cls);
43
+
44
+ if (alreadyOn) return true;
45
+
46
+ try {
47
+ await btn.click({ timeout: 2000 });
48
+ await new Promise(function (r) { setTimeout(r, 400); });
49
+ return true;
50
+ } catch (e) {
51
+ return false;
52
+ }
53
+ }
54
+ return false;
55
+ }
package/lib/exec.mjs CHANGED
@@ -1,27 +1,3 @@
1
1
  import { launch } from "./browser.mjs";
2
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
- }
3
+ import { waitForComposer } from "./wait
@@ -0,0 +1 @@
1
+ import {
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,61 +1,20 @@
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++;
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
- }
17
+ if (esc) { esc = false; continue; }
18
+ if (c === "\\") { esc = true; continue; }
19
+ if (c === String.fromCharCode(34)) { inStr = !inStr; continue; }
20
+ if (inStr