granttap-mcp 0.8.196 → 0.8.197

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.
Files changed (34) hide show
  1. package/README.md +3 -3
  2. package/THIRD_PARTY_LICENSES.txt +28 -0
  3. package/THIRD_PARTY_NOTICES.md +13 -0
  4. package/apps/bridge/src/approvals/cancellation/README.md +2 -0
  5. package/apps/bridge/src/approvals/cancellation/index.ts +4 -1
  6. package/apps/bridge/src/claude-open-questions/README.md +4 -0
  7. package/apps/bridge/src/codex-questions/README.md +6 -0
  8. package/apps/bridge/src/codex-questions/index.ts +8 -4
  9. package/apps/bridge/src/live-map/README.md +71 -0
  10. package/apps/bridge/src/live-map/classification/shell.ts +284 -0
  11. package/apps/bridge/src/live-map/classification/tools.ts +123 -0
  12. package/apps/bridge/src/live-map/index.ts +36 -0
  13. package/apps/bridge/src/live-map/observe.ts +119 -0
  14. package/apps/bridge/src/live-map/readers/claude.ts +84 -0
  15. package/apps/bridge/src/live-map/readers/codex.ts +98 -0
  16. package/apps/bridge/src/live-map/readers/entries.ts +44 -0
  17. package/apps/bridge/src/live-map/readers/shared.ts +108 -0
  18. package/apps/bridge/src/live-map/stream.ts +134 -0
  19. package/apps/bridge/src/live-map/tracker.ts +125 -0
  20. package/apps/bridge/src/monitor/handlers/inbound.ts +3 -0
  21. package/apps/bridge/src/monitor/support/runtime.ts +2 -0
  22. package/apps/mcp/src/mcp-tools/README.md +5 -1
  23. package/apps/mcp/src/mcp-tools/connect/relay.ts +71 -9
  24. package/apps/mcp/src/mcp-tools/interaction/questions.ts +16 -11
  25. package/cursor-plugin/README.md +1 -1
  26. package/cursor-plugin/mcp.json +1 -1
  27. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  28. package/package.json +1 -1
  29. package/packages/protocol/messages/README.md +13 -0
  30. package/packages/protocol/messages/approvals.ts +3 -1
  31. package/packages/protocol/messages/interaction/index.ts +5 -1
  32. package/packages/protocol/messages/live-map/index.ts +84 -0
  33. package/packages/protocol/messages/primitives.ts +8 -0
  34. package/packages/protocol/schema.ts +4 -0
package/README.md CHANGED
@@ -73,7 +73,7 @@ service need a durable path, not npm's temporary `npx` cache.
73
73
 
74
74
  ## What's new
75
75
 
76
- Available now, with GrantTap MCP 0.8.196 on npm and GrantTap 1.0.2 on the App Store:
76
+ Available now, with GrantTap MCP 0.8.197 on npm and GrantTap 1.0.2 on the App Store:
77
77
 
78
78
  - **Phones on the connection card.** In Claude (including the Claude desktop app),
79
79
  Codex, Cursor and Grok Build, the GrantTap card lists every phone paired with
@@ -744,8 +744,8 @@ trust.
744
744
  | `reconnect` | After explicit confirmation, show a one-time QR to reconnect or add an independent controller device while retaining the current room |
745
745
  | `remove_phones` | Ask the person to remove paired phones that are no longer used, by `notSeenForDays` (never the phone heard from most recently; `connection_status` marks the 30-day ones `stale`) and/or `phoneIds` from `connection_status`; nothing is removed without a yes on a phone, and the phone that answers, any phone heard from while the question is open, and the last phone stay |
746
746
  | `notify` | Send a non-blocking status of at most 2,000 characters that nobody answers, and/or one task-scoped Mesh event |
747
- | `ask_yes_no` | Ask a yes/no question and wait about three minutes for the explicit answer; a timeout is neither yes nor no |
748
- | `ask` | Ask an open question and wait about three minutes for typed or spoken text |
747
+ | `ask_yes_no` | Ask a yes/no question and wait about three minutes for the explicit answer; a timeout, or the person declining to answer, is neither yes nor no |
748
+ | `ask` | Ask an open question and wait about three minutes for typed or spoken text; the person may decline, and the agent hears so at once |
749
749
  | `request_sign_in` | Send an https sign-in page to the phone, wait for the person, and deliver the browser's loopback redirect once to the port the CLI listens on; returns `completed`, `cancelled` or `timed_out`, never the page or the redirect's contents |
750
750
  | `offload_task` | Request moving the calling Task to a compatible computer in its Mesh, keeping provider, model, effort and visible conversation; requires Automatic computer transfers, and `action=status` or `action=cancel` acts only on the caller's own request |
751
751
 
@@ -2832,3 +2832,31 @@ Redistributions in binary form must reproduce the above copyright notice, this l
2832
2832
 
2833
2833
  THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
2834
2834
  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2835
+
2836
+
2837
+ lot-map 340b98505c66372ecac13314a82ef4df92ff8640 — MIT (ported source, not a dependency)
2838
+ Source: https://github.com/alexeyw/lot-map
2839
+ The station names and the rules that read a tool call or a shell command line for its station are
2840
+ ported into apps/bridge/src/live-map/classification/ and packages/protocol/messages/live-map/.
2841
+
2842
+ MIT License
2843
+
2844
+ Copyright (c) 2026 Aleksei Volodin
2845
+
2846
+ Permission is hereby granted, free of charge, to any person obtaining a copy
2847
+ of this software and associated documentation files (the "Software"), to deal
2848
+ in the Software without restriction, including without limitation the rights
2849
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2850
+ copies of the Software, and to permit persons to whom the Software is
2851
+ furnished to do so, subject to the following conditions:
2852
+
2853
+ The above copyright notice and this permission notice shall be included in all
2854
+ copies or substantial portions of the Software.
2855
+
2856
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2857
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2858
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2859
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2860
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2861
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2862
+ SOFTWARE.
@@ -29,6 +29,19 @@ including `mcport` (MIT), `blazingly-json` (MIT), `serde` (MIT OR Apache-2.0), a
29
29
  BlindPlane crates (MIT OR Apache-2.0). Binary distributions must retain the
30
30
  complete license texts required by the exact dependency versions they contain.
31
31
 
32
+ ## Ported source: lot-map
33
+
34
+ The live map's ten stations and the rules that read a tool call or a shell
35
+ command line for its station are ported from
36
+ [lot-map](https://github.com/alexeyw/lot-map) by Aleksei Volodin (MIT,
37
+ commit `340b985`), a Claude Code mod that draws the same map in a pane beside
38
+ the chat. The ported code is in `apps/bridge/src/live-map/classification/`
39
+ and the station list in `packages/protocol/messages/live-map/`; each file
40
+ names its origin, and `THIRD_PARTY_LICENSES.txt` keeps lot-map's copyright and
41
+ license text. Those portions remain under the MIT license; the GrantTap
42
+ first-party license does not apply to them. GrantTap does not ship or run the
43
+ mod itself.
44
+
32
45
  ## Optional SweepLoom integration
33
46
 
34
47
  Provider storage inspection may invoke a separately installed SweepLoom CLI
@@ -4,5 +4,7 @@
4
4
  Ending that process cancels the durable request, publishes its terminal state
5
5
  and releases the waiter. Cancellation never manufactures an Allow or answers a
6
6
  question. Other live approval registrations and shared clients remain intact.
7
+ A string abort reason, such as a phone declining a yes/no question, becomes the
8
+ terminal note; otherwise the note says the agent stopped waiting.
7
9
 
8
10
  License: GrantTap Commercial Source License, in the repository-root `LICENSE`.
@@ -7,9 +7,12 @@ export function attachApprovalCancellation(client: RelayClient, request: Approva
7
7
  signal?: AbortSignal; handle?: ApprovalRegistrationHandle; cancel: () => void; close?: () => void;
8
8
  }): () => void {
9
9
  const abort = () => {
10
+ // The owner may say why it stopped waiting, such as the person declining on the phone.
11
+ const reason = options.signal?.reason;
12
+ const note = typeof reason === "string" && reason ? reason : "The agent stopped waiting for this answer.";
10
13
  try {
11
14
  const terminal = markApprovalTerminal(request.requestId, "cancelled", { decision: "deny",
12
- decidedBy: "cancelled", note: "The agent stopped waiting for this answer.", sessionId: request.sessionId }, Date.now(), options.handle);
15
+ decidedBy: "cancelled", note, sessionId: request.sessionId }, Date.now(), options.handle);
13
16
  if (terminal.outcome) void sendApprovalResolved(client, resolvedFromOutcome(terminal.outcome, terminal.request)).catch(() => {});
14
17
  } catch { /* Storage failure must still release the owned provider waiter. */ }
15
18
  finally { options.cancel(); options.close?.(); }
@@ -12,6 +12,10 @@ trailing `• ` choices; desktop app actions (commit, merge…) are left out bec
12
12
  only the desktop app runs them. The answer is an ordinary message to that chat,
13
13
  so current provider, pause, Task policy, the queue and receipts all apply.
14
14
 
15
+ These cards do not advertise a decline: the chat has already ended its turn, so
16
+ no agent waits for one. A phone may hide the card for itself; the chat still
17
+ holds the question until the person answers it.
18
+
15
19
  A later message from the person closes the card on every device: typed at the
16
20
  computer, a desktop button, or the phone reply itself. A newer question replaces
17
21
  an older one. Records survive monitor restart and are replayed when a phone
@@ -13,6 +13,12 @@ wake notification. A native answer clears the corresponding card across devices.
13
13
  After a day, a GrantTap card expires without claiming the native question was
14
14
  answered. The Codex conversation remains the source of truth.
15
15
 
16
+ Cards advertise `questionDecline: decline-v1`. A phone that declines sends that
17
+ marker on its reply; Codex then receives a fixed answer saying the person chose
18
+ not to answer, through the same native item and delivery, never the phone's own
19
+ text or files. An older phone never sends the marker; an older computer never
20
+ advertises it, so the phone offers only its local hide.
21
+
16
22
  Replies use the original host question item ID and normal scoped phone delivery,
17
23
  including current provider, pause and Task policy. Native admission uses one
18
24
  stable delivery ID per question, so concurrent controllers cannot submit two
@@ -9,6 +9,8 @@ import { observedQuestions } from './source';
9
9
  export { codexQuestionText } from './observations';
10
10
 
11
11
  const RETENTION_MS = 24 * 60 * 60_000;
12
+ /** What Codex is told when the person declines: the native question still needs an answer to go on. */
13
+ export const DECLINED_ANSWER = 'The person chose not to answer this question. Continue without their answer.';
12
14
 
13
15
  /** Phone questions travel as device-encrypted control events, independently of task-key grants. */
14
16
  export async function publishCodexQuestions(client: RelayClient, sessions: SessionInfo[],
@@ -54,7 +56,7 @@ export async function publishCodexQuestions(client: RelayClient, sessions: Sessi
54
56
  } else if (!record.announced || options.replay) {
55
57
  const text = [record.question, ...record.options.map(value => '• ' + value)].join('\n');
56
58
  await client.send({ type: 'agent.event', kind: 'question', requestId: record.requestId,
57
- questionReplyFormat: 'attachments-v1',
59
+ questionReplyFormat: 'attachments-v1', questionDecline: 'decline-v1',
58
60
  sessionId: session.sessionId, agent: 'codex', projectId: session.projectId,
59
61
  taskId: session.taskId, computerId: session.computerId, text, createdAt: record.createdAt },
60
62
  'phone', { ttlMs: Math.max(1, record.createdAt + RETENTION_MS - Date.now()),
@@ -103,11 +105,13 @@ export async function handleCodexQuestionReply(client: RelayClient, message: Use
103
105
  return true;
104
106
  }
105
107
  const hasAttachments = !!(message.attachments?.length || message.attachmentRefs?.length);
106
- if (!message.text.trim() || message.text.length > 4_000
108
+ // A decline carries no words or files of the person's; Codex gets the fixed answer instead.
109
+ const declined = message.questionDecline === 'decline-v1';
110
+ if (declined ? hasAttachments : !message.text.trim() || message.text.length > 4_000
107
111
  || (hasAttachments && message.questionReplyFormat !== 'attachments-v1')) return false;
108
- return deliver(client, { ...message, requestId: undefined,
112
+ return deliver(client, { ...message, requestId: undefined, questionDecline: undefined,
109
113
  messageId: message.messageId ?? 'codex-answer-' + record.requestId,
110
- text: nativeAnswerEnvelope(record, message.text) }, publish, peerPublicKey,
114
+ text: nativeAnswerEnvelope(record, declined ? DECLINED_ANSWER : message.text) }, publish, peerPublicKey,
111
115
  { messageId: record.requestId, questionReply: true });
112
116
  }
113
117
 
@@ -0,0 +1,71 @@
1
+ # Live map
2
+
3
+ Public entry: `index.ts`. While a phone has a chat's live map open, this computer
4
+ sends it a compact stream of what the chat's agent does, by name only, and the
5
+ phone draws it: the agent in the centre, ten stations around it, a pulse along a
6
+ spoke for each call. The idea and the station rules come from
7
+ [lot-map](https://github.com/alexeyw/lot-map) (MIT, Aleksei Volodin), a Claude
8
+ Code mod that draws the same map beside the chat on the same computer. GrantTap
9
+ does not ship or run the mod; it reads the records it already reads for every
10
+ provider and the phone draws the map. See `THIRD_PARTY_NOTICES.md`.
11
+
12
+ ## Contract
13
+
14
+ The phone sends `session.pulses.subscribe { sessionId, active }` in its device
15
+ box when the map opens and renews it every few seconds; `active: false` or
16
+ twenty seconds without a renewal ends it. A renewal after more than ten seconds
17
+ of silence is a map opened again whose close was lost, and starts from a replay.
18
+ At most four maps are fed at once, a fifth taking the place of the oldest. Only the routing monitor answers.
19
+
20
+ Each open map gets at most one `session.pulses` frame a second, and one every
21
+ five seconds when nothing happens, so the phone can tell the map is live. A
22
+ frame holds at most 48 pulses and 12 KB; what does not fit is counted in
23
+ `dropped`, the newest kept. `running` names every call still at work, so a
24
+ phone that missed a frame ends what no longer runs; `counts` are each station's
25
+ calls in the chat's window, for the worn spokes. The first frame of a
26
+ subscription is a `replay` of the chat's last 24 pulses.
27
+
28
+ A pulse is a station, a name, `start`/`end`/`done`, `run`/`ok`/`error`/`blocked`,
29
+ its time and duration, a subagent's digest, how many run at that station at
30
+ once, and a `mark` for moments that are not calls: the person's message, the
31
+ answer, a model step or change, a compaction, the hook asking for approval.
32
+ The frame adds the model's name and, where the provider reports the window
33
+ (Codex), the share of the context window; for Claude only its tokens.
34
+
35
+ Frames travel under the chat's own key to the phone that asked, `reliable:
36
+ false` with a ten-second lifetime: never into the relay's mailbox, and in the
37
+ replaceable lane, so they cannot go ahead of an answer and are the first to
38
+ give way when the upload backs up. The chat's key is granted once per
39
+ subscription.
40
+
41
+ ## What leaves and what does not
42
+
43
+ The readers (`readers/`) take a chat's recent records: the last 768 KB of a
44
+ Claude or Codex file and 256 KB of each of up to three Claude subagent files
45
+ written in the last fifteen minutes, read again only when the file's size or
46
+ time changed; Cursor and Grok Build from the rows GrantTap already reads. The
47
+ classifiers (`classification/`) read a call's input to choose its station:
48
+ a shell line for the command it runs (`curl` is Network, `rg` is Files), a path
49
+ for Claude's or Codex's memory folder. A result is read only for an exit code or
50
+ for words that say a hook or the person refused it.
51
+
52
+ What leaves is a tool's name (`Bash`, `exec command`, `github: create issue`), a
53
+ skill's or agent type's name when it is a plain identifier, and a model's id.
54
+ Never an argument, path, host, command line, description, prompt, result or
55
+ message text. Provider call and subagent ids are replaced by digests.
56
+
57
+ ## Stations
58
+
59
+ `you` (messages, questions, plans and to-dos, GrantTap's own ask and notify),
60
+ `model` (each step, a compaction, a change of model), `memory`, `files`,
61
+ `shell`, `web` (Network: fetch, search, MCP servers, network commands),
62
+ `browser`, `agents`, `skills`, `hooks` (an approval GrantTap's hook asked for).
63
+ lot-map's Claude Code names are kept, and Codex (`exec_command`, `apply_patch`,
64
+ `update_plan`, `spawn_agent`, `web_search_call`), Cursor (`Shell`, `StrReplace`,
65
+ `CallMcpTool`) and Grok Build (`bash`, `read_file`) names are added.
66
+
67
+ Tests live in `tests/`, including a round trip between a real computer and
68
+ phone `RelayClient` through a relay that sees only ciphertext.
69
+
70
+ GrantTap Commercial Source License, except the ported lot-map portions, which
71
+ remain MIT; see the repository LICENSE and THIRD_PARTY_NOTICES.md.
@@ -0,0 +1,284 @@
1
+ // Which station a shell command line belongs to. Ported from lot-map's hooks/classify.ts
2
+ // (https://github.com/alexeyw/lot-map, MIT, Copyright (c) 2026 Aleksei Volodin; the license is in
3
+ // THIRD_PARTY_LICENSES.txt). Here the line is only read to pick the station: no word of it leaves.
4
+ import type { LiveMapStation } from "../../../../../packages/protocol/schema";
5
+
6
+ const slashes = (path: string): string => path.replace(/\\/g, "/");
7
+
8
+ /** Commands that work on files and nothing else: they read, search, move or edit them in place. */
9
+ const FILE_WORDS = new Set(["cat", "head", "tail", "sed", "grep", "rg", "find", "ls", "wc", "cp", "mv", "mkdir",
10
+ "touch", "diff", "cmp", "sort", "uniq", "cut", "tr", "awk", "tee", "stat", "file", "du", "tree", "ln", "basename",
11
+ "dirname", "realpath", "jq", "rm", "rmdir", "fd", "bat", "nl", "less", "more", "xxd", "od", "chmod", "patch"]);
12
+ const NEUTRAL_WORDS = new Set(["echo", "printf", "cd", "export", "true", "false", ":", "set", "pwd", "sleep", "which",
13
+ "test", "[", "[[", "read"]);
14
+ const NET_WORDS = new Set(["curl", "wget", "gh", "ssh", "scp", "sftp", "ftp", "rsync", "nc", "ncat", "telnet", "ping",
15
+ "dig", "nslookup", "nmap", "http", "https", "kubectl", "aws", "gcloud", "az"]);
16
+ /** Commands that reach the network only with some of their subcommands. */
17
+ const NET_SUBCOMMANDS: Record<string, ReadonlySet<string>> = {
18
+ git: new Set(["push", "pull", "fetch", "clone", "ls-remote", "submodule update", "remote update"]),
19
+ svn: new Set(["checkout", "co", "update", "up", "commit", "ci", "export"]),
20
+ hg: new Set(["clone", "pull", "push", "incoming", "outgoing"]),
21
+ npm: new Set(["install", "i", "ci", "add", "update", "publish", "view", "audit"]),
22
+ pnpm: new Set(["install", "i", "add", "update", "publish", "dlx"]),
23
+ yarn: new Set(["install", "add", "upgrade", "publish", "dlx"]),
24
+ bun: new Set(["install", "i", "add", "update", "publish"]),
25
+ pip: new Set(["install", "download"]),
26
+ pipx: new Set(["install", "upgrade", "upgrade-all", "run"]),
27
+ uv: new Set(["add", "sync", "lock", "publish", "tool install"]),
28
+ poetry: new Set(["install", "add", "update", "lock", "publish"]),
29
+ docker: new Set(["pull", "push", "login"]),
30
+ "docker compose": new Set(["pull", "push"]),
31
+ brew: new Set(["install", "update", "upgrade", "fetch"]),
32
+ cargo: new Set(["install", "fetch", "publish", "update"]),
33
+ go: new Set(["get", "install", "mod download"]),
34
+ apt: new Set(["install", "update", "upgrade", "full-upgrade", "dist-upgrade"]),
35
+ "apt-get": new Set(["install", "update", "upgrade", "dist-upgrade"]),
36
+ deno: new Set(["install", "add", "cache"]),
37
+ terraform: new Set(["init", "plan", "apply", "destroy", "import", "refresh"]),
38
+ helm: new Set(["install", "upgrade", "pull", "push", "repo", "search", "dependency"]),
39
+ openssl: new Set(["s_client"]),
40
+ };
41
+ const PY_MODULES = new Set(["pip", "uv", "pipx", "poetry"]);
42
+ /** Commands that run another command; `skip` is how many words of their own follow the flags. */
43
+ const WRAPPERS: Record<string, { takes?: readonly string[]; skip?: number; asks?: readonly string[] }> = {
44
+ sudo: { takes: ["-u", "-g", "-p", "-h", "-C", "-D", "-R", "-T", "-U", "-r", "-t"] },
45
+ doas: { takes: ["-u", "-C"] }, env: { takes: ["-u", "-C"] }, time: {},
46
+ timeout: { takes: ["-s", "-k"], skip: 1 }, nohup: {}, nice: { takes: ["-n"] }, ionice: { takes: ["-c", "-n"] },
47
+ stdbuf: { takes: ["-i", "-o", "-e"] }, caffeinate: { takes: ["-t", "-w"] }, command: { asks: ["-v", "-V"] },
48
+ exec: { takes: ["-a"] }, xargs: { takes: ["-n", "-I", "-P", "-L", "-d", "-E", "-s", "-a", "-J", "-R"] },
49
+ watch: { takes: ["-n", "--interval"] },
50
+ };
51
+ const ASSIGNMENT = /^[A-Za-z_]\w*=/;
52
+ const GIT_TAKES = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"]);
53
+ const DOCKER_TAKES = new Set(["-c", "--context", "-H", "--host", "--config", "-l", "--log-level", "-f", "--file", "-p",
54
+ "--project-name", "--profile", "--env-file", "--project-directory"]);
55
+ const DOCKER_ALONE = new Set(["-i", "-t", "-d", "-P", "-q", "-T", "--interactive", "--tty", "--detach", "--rm", "--init",
56
+ "--privileged", "--publish-all", "--read-only", "--no-healthcheck", "--quiet", "--no-deps", "--build"]);
57
+ const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh"]);
58
+ const BEFORE_A_COMMAND = new Set(["do", "then", "else", "elif", "if", "while", "until", "!", "{"]);
59
+ const NO_COMMAND = new Set(["for", "select", "case", "function", "done", "fi", "esac", "}"]);
60
+ /** A longer line is a script written inline, and what counts stands at its start. */
61
+ const READ = 8000;
62
+ const PS_FILE_WORDS = new Set(["get-content", "gc", "type", "set-content", "add-content", "out-file", "get-childitem",
63
+ "gci", "dir", "get-item", "gi", "select-string", "sls", "copy-item", "cpi", "copy", "move-item", "mi", "move",
64
+ "rename-item", "rni", "ren", "new-item", "ni", "md", "test-path", "resolve-path", "get-filehash"]);
65
+ const PS_NEUTRAL_WORDS = new Set(["write-host", "write-output", "set-location", "sl", "get-location", "gl",
66
+ "start-sleep", "select-object", "select", "where-object", "where", "?", "foreach-object", "foreach", "%",
67
+ "sort-object", "measure-object", "measure", "format-table", "ft", "format-list", "fl", "out-string", "out-null"]);
68
+ const PS_NET_WORDS = new Set(["invoke-webrequest", "iwr", "invoke-restmethod", "irm", "test-connection",
69
+ "test-netconnection", "resolve-dnsname", "start-bitstransfer"]);
70
+
71
+ const pastFlags = (words: string[], takes: { has(flag: string): boolean }): string[] => {
72
+ let i = 0;
73
+ while (i < words.length && (words[i] ?? "").startsWith("-")) i += takes.has(words[i] ?? "") ? 2 : 1;
74
+ return words.slice(i);
75
+ };
76
+
77
+ /** `sudo curl` is curl, and so is the curl behind `env A=1`, `timeout 5` or `xargs`. */
78
+ function unwrapped(words: string[], name: (word?: string) => string): string[] {
79
+ let rest = words;
80
+ for (let depth = 0; depth < 6; depth++) {
81
+ const wrapper = WRAPPERS[name(rest[0])];
82
+ if (wrapper === undefined || wrapper.asks?.some(flag => rest[1] === flag) === true) break;
83
+ rest = pastFlags(rest.slice(1), new Set(wrapper.takes ?? []));
84
+ let i = 0;
85
+ while (i < rest.length && ASSIGNMENT.test(rest[i] ?? "")) i++;
86
+ rest = rest.slice(i + (wrapper.skip ?? 0));
87
+ }
88
+ return rest;
89
+ }
90
+
91
+ /** What `docker exec` or `docker run` runs in a container: the words after the container's name. */
92
+ function insideContainer(words: string[]): string[] {
93
+ let i = 0;
94
+ while (i < words.length && (words[i] ?? "").startsWith("-")) {
95
+ const flag = words[i] ?? "";
96
+ i += DOCKER_ALONE.has(flag) || flag.includes("=") || /^-[itdqPT]{2,}$/.test(flag) ? 1 : 2;
97
+ }
98
+ return words.slice(i + 1);
99
+ }
100
+
101
+ const unquoted = (word: string): string => {
102
+ const q = word[0];
103
+ if (q !== '"' && q !== "'") return word;
104
+ const inner = word.length > 1 && word.endsWith(q) ? word.slice(1, -1) : word.slice(1);
105
+ return q === '"' ? inner.replace(/\\(["\\$`])/g, "$1") : inner;
106
+ };
107
+
108
+ /** A shell line without the text of its here-documents, unless a shell given no script runs them. */
109
+ function withoutHereDocuments(command: string): string {
110
+ if (!command.includes("<<")) return command;
111
+ const kept: string[] = [];
112
+ const waiting: { word: string; tabs: boolean; isRun: boolean }[] = [];
113
+ for (const line of command.split("\n")) {
114
+ const open = waiting[0];
115
+ if (open !== undefined) {
116
+ const text = (open.tabs ? line.replace(/^\t+/, "") : line).replace(/\r$/, "");
117
+ if (text === open.word) waiting.shift();
118
+ else if (open.isRun) kept.push(line);
119
+ continue;
120
+ }
121
+ kept.push(line);
122
+ for (const m of line.matchAll(/(?<!<)<<(?!<)(-?)\s*(["']?)([A-Za-z_][\w.]*)\2/g)) {
123
+ const before = line.slice(0, m.index);
124
+ if (before.lastIndexOf("((") > before.lastIndexOf("))")) continue;
125
+ const feeds = unwrapped(segments(before).pop() ?? [], base);
126
+ const isRun = SHELLS.has(base(feeds[0])) && feeds.slice(1).every(w => w.startsWith("-") && !/^-[a-z]*c$/.test(w));
127
+ waiting.push({ word: m[3] ?? "", tabs: m[1] === "-", isRun });
128
+ }
129
+ }
130
+ return kept.join("\n");
131
+ }
132
+
133
+ type Reading = { text: string; quote: "" | '"' | "'" | "$"; close: "" | ")" | "`" };
134
+
135
+ /** A shell line cut into its commands outside quotes; `deep` adds each command run inside `$(…)` or backticks. */
136
+ function pieces(line: string, deep: boolean, powershell: boolean): string[] {
137
+ const out: string[] = [];
138
+ const open: Reading[] = [{ text: "", quote: "", close: "" }];
139
+ const escape = powershell ? "`" : "\\";
140
+ const cut = (reading: Reading): void => { out.push(reading.text); reading.text = ""; };
141
+ for (let i = 0; i < line.length; i++) {
142
+ const top = open[open.length - 1] as Reading;
143
+ const c = line[i] ?? "";
144
+ const next = line[i + 1] ?? "";
145
+ if (top.quote === "'") {
146
+ top.text += c;
147
+ if (c === "'") top.quote = "";
148
+ continue;
149
+ }
150
+ if (c === "\\" && next === "\n" && !powershell) { top.text += " "; i++; continue; }
151
+ if (c === escape || (c === "\\" && top.quote === "$")) { top.text += c + next; i++; continue; }
152
+ const inside = deep && c === "$" && next === "(" ? ")" : deep && c === "`" && !powershell && top.close !== "`" ? "`" : "";
153
+ if (top.quote !== "") {
154
+ if ((top.quote === "$" && c === "'") || (top.quote === '"' && c === '"')) top.quote = "";
155
+ if (top.quote === '"' && inside !== "") {
156
+ open.push({ text: "", quote: "", close: inside });
157
+ if (inside === ")") i++;
158
+ top.text += " ";
159
+ } else top.text += c;
160
+ continue;
161
+ }
162
+ if (c === '"' || c === "'") { top.quote = c; top.text += c; }
163
+ else if (c === "$" && next === "'" && !powershell) { top.quote = "$"; top.text += "$'"; i++; }
164
+ else if (c === "#" && /^$|\s$/.test(top.text.slice(-1))) {
165
+ while (i + 1 < line.length && line[i + 1] !== "\n") i++;
166
+ } else if (c === "\n" || c === ";" || c === "|") cut(top);
167
+ else if (c === "&" && (next === "&" || !powershell)) {
168
+ // `2>&1` and `&>file` send output somewhere; they end no command.
169
+ if (next !== "&" && (next === ">" || /[<>]/.test(line[i - 1] ?? ""))) top.text += c;
170
+ else cut(top);
171
+ } else if (inside !== "" || (deep && c === "(")) {
172
+ open.push({ text: "", quote: "", close: inside === "`" ? "`" : ")" });
173
+ if (inside === ")") i++;
174
+ top.text += " ";
175
+ } else if (deep && (c === ")" || c === "`") && !(c === "`" && powershell)) {
176
+ cut(top);
177
+ if (top.close === c && open.length > 1) open.pop();
178
+ } else top.text += c;
179
+ }
180
+ for (const reading of open) out.push(reading.text);
181
+ return out;
182
+ }
183
+
184
+ const WORDS = /(?:\\[\s\S]|[^\s"'\\]|"(?:[^"\\]|\\[\s\S])*"?|'[^']*'?)+/g;
185
+ const PS_WORDS = /(?:[^\s"']|"[^"]*"?|'[^']*'?)+/g;
186
+
187
+ /** The words of each command in a shell line, leading assignments and construct words taken off. */
188
+ function segments(command: string, deep = false, constructs = false, powershell = false): string[][] {
189
+ return pieces(command, deep, powershell)
190
+ .map(part => part.match(powershell ? PS_WORDS : WORDS) ?? [])
191
+ .map(words => {
192
+ let i = 0;
193
+ while (i < words.length && ASSIGNMENT.test(words[i] ?? "")) i++;
194
+ if (!constructs) return words.slice(i);
195
+ let rest = words.slice(i);
196
+ for (;;) {
197
+ const head = rest[0] ?? "";
198
+ if (BEFORE_A_COMMAND.has(head)) rest = rest.slice(1);
199
+ else if (head.startsWith("(") && !head.startsWith("((")) rest = head.length > 1 ? [head.slice(1), ...rest.slice(1)] : rest.slice(1);
200
+ else break;
201
+ }
202
+ return NO_COMMAND.has(rest[0] ?? "") ? [] : rest;
203
+ })
204
+ .filter(words => words.length > 0);
205
+ }
206
+
207
+ /** A command's own name: no quotes, no folder; a Windows program without `.exe` and in lower case. */
208
+ const base = (word = ""): string => {
209
+ const name = slashes(word.replace(/["']/g, "")).split("/").pop() ?? word;
210
+ return /\.(?:exe|cmd|bat)$/i.test(name) ? name.replace(/\.(?:exe|cmd|bat)$/i, "").toLowerCase() : name;
211
+ };
212
+
213
+ /** Claude Code's memory folder; Codex keeps its memories under `~/.codex/memories`. */
214
+ export const isMemoryPath = (path: string): boolean =>
215
+ /\/\.claude\/projects\/[^/]+\/memory\//.test(slashes(path)) || /\/\.codex\/memories\//.test(slashes(path));
216
+
217
+ /** The station of a shell tool's line. `powershell` adds PowerShell's names and reads them in lower case. */
218
+ export function shellStation(command: string, powershell = false): LiveMapStation {
219
+ const name = (word?: string): string => (powershell ? base(word).toLowerCase() : base(word));
220
+ const own = (words: string[]): string[] => {
221
+ if (!powershell) return words;
222
+ let i = 0;
223
+ if (/^\$[\w:]+$/.test(words[0] ?? "") && words[1] === "=") i = 2;
224
+ if (words[i] === "&" || words[i] === ".") i++;
225
+ return words.slice(i);
226
+ };
227
+ const commands = (words: string[], deep = false, depth = 0): string[][] => {
228
+ const outer = unwrapped(words, name);
229
+ const head = name(outer[0]);
230
+ if (!powershell && depth < 3) {
231
+ let line: string | undefined;
232
+ if (head === "eval") line = outer.slice(1).map(unquoted).join(" ");
233
+ else if (SHELLS.has(head)) {
234
+ const at = outer.findIndex((w, i) => i > 0 && !w.startsWith("-"));
235
+ const flag = outer.findIndex((w, i) => i > 0 && /^-[a-z]*c$/.test(w));
236
+ if (flag > 0 && (at < 0 || at > flag) && outer[flag + 1] !== undefined) line = unquoted(outer[flag + 1] ?? "");
237
+ }
238
+ if (line !== undefined) return segments(line, deep, true).flatMap(inner => commands(inner, deep, depth + 1));
239
+ }
240
+ const all = [outer];
241
+ if (head === "find") {
242
+ outer.forEach((word, i) => {
243
+ if (!/^-(?:exec|execdir|ok|okdir)$/.test(word)) return;
244
+ const tail = outer.slice(i + 1);
245
+ const end = tail.findIndex(w => w === "\\;" || unquoted(w) === ";" || w === "+");
246
+ all.push(...commands(end < 0 ? tail : tail.slice(0, end), deep, depth + 1));
247
+ });
248
+ }
249
+ if (head === "docker" && depth < 3) {
250
+ let rest = pastFlags(outer.slice(1), DOCKER_TAKES);
251
+ if (rest[0] === "compose") rest = pastFlags(rest.slice(1), DOCKER_TAKES);
252
+ if (rest[0] === "container") rest = rest.slice(1);
253
+ if (rest[0] === "exec" || rest[0] === "run") all.push(...commands(insideContainer(rest.slice(1)), deep, depth + 1));
254
+ }
255
+ return all.filter(c => c.length > 0);
256
+ };
257
+ const isNet = (words: string[]): boolean => {
258
+ let head = name(words[0]);
259
+ let rest = words.slice(1);
260
+ if (NET_WORDS.has(head) || (powershell && PS_NET_WORDS.has(head))) return true;
261
+ if (/^(?:python[\d.]*|py)$/.test(head) && rest[0] === "-m" && PY_MODULES.has(rest[1] ?? "")) [head, rest] = [rest[1] ?? "", rest.slice(2)];
262
+ if (head === "uv" && rest[0] === "pip") [head, rest] = ["pip", rest.slice(1)];
263
+ if (/^pip[\d.]+$/.test(head)) head = "pip";
264
+ if (head === "yarn" && rest.every(w => w.startsWith("-"))) return true;
265
+ if (head === "git") rest = pastFlags(rest, GIT_TAKES);
266
+ if (head === "docker") {
267
+ rest = pastFlags(rest, DOCKER_TAKES);
268
+ if (rest[0] === "compose") [head, rest] = ["docker compose", pastFlags(rest.slice(1), DOCKER_TAKES)];
269
+ }
270
+ if (head === "npx") return rest.some(w => w === "-y" || w === "--yes");
271
+ const subs = NET_SUBCOMMANDS[head];
272
+ return subs !== undefined && (subs.has(rest[0] ?? "") || subs.has(`${rest[0] ?? ""} ${rest[1] ?? ""}`));
273
+ };
274
+ const read = (powershell ? command : withoutHereDocuments(command)).slice(0, READ);
275
+ const run = segments(read, false, !powershell, powershell).map(own).filter(words => words.length > 0)
276
+ .flatMap(words => commands(words));
277
+ if (run.some(isNet) || segments(read, true, !powershell, powershell).map(own)
278
+ .flatMap(words => commands(words, true)).some(isNet)) return "web";
279
+ const isNeutral = (head: string): boolean => NEUTRAL_WORDS.has(head) || (powershell && PS_NEUTRAL_WORDS.has(head));
280
+ const isFile = (head: string): boolean => FILE_WORDS.has(head) || (powershell && PS_FILE_WORDS.has(head));
281
+ const real = run.filter(words => !isNeutral(name(words[0])));
282
+ if (real.length > 0 && real.every(words => isFile(name(words[0])))) return isMemoryPath(read) ? "memory" : "files";
283
+ return "shell";
284
+ }