bin/mcp-vim

filter: Statementstmt 74.5% 393 / 527 Branchbran 56.5% 138 / 244 Conditioncond 46.6% 76 / 163 MC/DCmcdc 23.7% 19 / 80 Subroutinesub 69.6% 55 / 79 Podpod 0.0% 0 / 1 totaltotal 62.2% 681 / 1094 CC 165 SCAR 31.9
CC
165
Cov
65%
_on_upload_done
182.0
__ANON__
67.0
send_data
56.0
CRAP 24.2
« blib/lib/AnyEvent/MCP/Extension.pm ↑ Summary blib/lib/AnyEvent/MCP/Server/Connect.pm »
1 #!/opt/bin/perl
2  
3 =head1 NAME
4  
5 mcp-vim - MCP server for live Vim editors
6  
7 =head1 SYNOPSIS
8  
9 mcp-vim [--name NAME] [--bind ADDRESS[:PORT]] [--stdio] [--print-url]
10  
11 =head1 DESCRIPTION
12  
13 C<mcp-vim> lets MCP clients read and edit buffers in running Vim editors,
14 including changes that have not been saved to disk. An assistant can work
15 with the same text you are editing, and its changes appear in Vim for you
16 to review and save.
17  
18 It runs as a broker daemon. Each Vim editor needs the supplied Vim plugin,
19 which connects the editor to the broker. Your MCP client connects to the
20 same broker, which forwards requests to the editor and returns its replies.
21 The client can use MCP over HTTP or stdin/stdout; Vim always connects over
22 TCP using the plugin's private protocol.
23  
24 One broker can serve several Vim editors. Each editor connects with a
25 target name, allowing the client to list the connected editors and choose
26 which one to work with. Buffer IDs belong to the selected editor.
27  
28 See L</VIM PLUGIN INSTALLATION> for installing and connecting the Vim
29 plugin, and L<AnyEvent::MCP::Intro> for configuring an MCP client.
30  
31 =head1 FIRST USE
32  
33 Install the companion Vim plugin described below. Configure the MCP
34 client to launch:
35  
36 mcp-vim --stdio --name editor
37  
38 In another terminal, under the same user and configuration directory,
39 retrieve the listener's credential-bearing URL:
40  
41 mcp-vim --name editor --print-url
42  
43 Append a target name and enter the resulting command in Vim:
44  
45 :Mcp http://HOST:PORT/TOKEN/my-editor
46  
47 Then ask the assistant to call C<targets>, C<state>, and C<read-lines>
48 for a buffer in C<my-editor>. C<targets> shows whether Vim connected;
49 C<state> supplies buffer IDs and changedticks. Reads include unsaved text.
50  
51 Through a multibroker, tools have a prefix such as C<vim.targets>.
52 Start its mcp-vim child with C<--eager> so the listener exists before
53 the first tool call. Starting the broker alone does not connect Vim:
54 each editor must run C<:Mcp>. If connecting fails, check the broker's
55 C<--name>, bind address, token and configuration environment.
56 Edits require a current C<expected_changedtick>; they do not save files
57 until the separate C<save> tool or a writing Ex command is used.
58  
59 =head1 TOOLS
60  
61 C<targets> lists connected Vim sessions, and C<state> reports their buffers
62 and current cursor. C<read-lines> and C<grep> operate on live Vim buffers,
63 B<not> saved disk files. C<apply-diff> and C<substitute> edit buffers;
64 C<set-cursor> deliberately changes the visible editor position.
65 Use C<targets> first, then C<state> to obtain buffer IDs and changedticks.
66 A target identifies one connected editor; a buffer ID is local to that editor.
67  
68 Editing operations require the buffer's C<expected_changedtick> from a
69 recent state or read. A changed tick rejects stale edits instead of silently
70 applying them to a buffer that has moved on. Diff context must also match.
71 Explicitly addressed unloaded buffers can be loaded on demand, so reads
72 and edits are not necessarily free of editor side effects. A buffer edit
73 does not save the file to disk; the user remains in control of that step.
74  
75 =head2 Patch text and buffer lines
76  
77 C<apply-diff> accepts Unicode text. The private JSON protocol decodes it
78 into a Vim String; the plugin writes buffer lines in Vim's internal
79 C<&encoding> and sends the patch String to GNU patch. C<&fileencoding>
80 and C<&fileformat> govern saving the buffer, not these temporary files.
81 The UTF-8 path has been checked with non-ASCII text.
82  
83 Patching operates on complete logical lines, with a final newline,
84 independently of C<&endofline>. Nonempty output without that final newline
85 is rejected. Vim represents an embedded NUL in a buffer line as NL inside
86 the corresponding String; C<writefile>/C<readfile> preserve such bytes in
87 untouched lines.
88  
89 NUL-containing diffs are rejected by the broker before permission prompting
90 or forwarding: Vim's C<json_decode> would drop C<\u0000> from Strings.
91 There is no raw-byte diff transport for Vim yet. This differs from the
92 byte-oriented shared helper and the filesystem tool's raw-byte base64 form.
93  
94 =head2 Undo and redo
95  
96 C<undo> and C<redo> each move one step through the selected buffer's normal
97 Vim undo tree. Both require C<target>, C<buffer> and C<expected_changedtick>,
98 and use the C<write> permission. The tick is checked after loading and
99 entering that buffer. A stale tick or an unmodifiable buffer rejects the
100 operation. Neither tool saves the buffer.
101  
102 The result includes C<buffer>, the new C<changedtick>, C<changed>,
103 C<seq_cur> (the reached undo sequence), C<seq_last> (the latest allocated
104 sequence) and C<modified>. At the oldest/newest reachable state, the operation
105 succeeds with C<changed> false. Redo follows Vim's selected branch; it does
106 not switch to another branch or select an arbitrary historical sequence.
107  
108 When another buffer is selected, the caller's original buffer and view are
109 restored. In the current buffer, Vim's normal undo/redo cursor adjustment
110 is retained. Undo acts on ordinary buffer history, including human edits;
111 it does not identify or group changes made by an assistant.
112  
113 =head2 Open a file
114  
115 C<open> accepts C<target> and a nonempty C<path> without NUL. It adds the
116 pathname to Vim's buffer list and loads it without selecting it. Relative
117 paths use Vim's current effective directory at execution time. The pathname
118 is passed to C<bufadd>, not an Ex command or shell; wildcard and command
119 characters are literal. A missing file becomes an empty named buffer.
120  
121 An existing buffer is reused. Loaded contents, including unsaved edits,
122 are not reread from disk. The result reports C<buffer>, C<filename>,
123 C<changedtick>, C<line_count> and C<modified>, ready for subsequent tools.
124 No file is saved. Use C<set-cursor> separately to display the buffer.
125  
126 This requires the separate C<open> action. Loading can run normal Vim
127 autocommands and modelines, which can change editor state or fail after
128 side effects. An error does not undo buffer creation or those effects.
129 Permission scopes still cover an editor, not an individual pathname.
130  
131 =head2 Save modified buffers
132  
133 C<save> accepts C<target>, C<buffer> and C<expected_changedtick>. It runs
134 Vim's C<:update> in that buffer: an unmodified buffer needs no write; a
135 modified buffer is saved to its current filename. There is no filename
136 argument, save-as or force option. A stale tick rejects the operation.
137  
138 Saving requires the separate C<save> permission. A C<write> grant for
139 editing does not authorize saving. The result reports C<buffer>,
140 C<changedtick>, C<modified> and C<filename> after the command. Inspect
141 C<modified>: write autocommands can leave or make the buffer modified.
142  
143 Normal Vim write checks and autocommands apply. They can change text,
144 rename or remove buffers, write other files, or fail after side effects.
145 The tick guard checks the buffer before the command; it does not constrain
146 autocommands or detect external changes to the disk file. A removed or
147 unloaded target after the command produces an error even if a write occurred.
148 The caller's original buffer and view are restored when possible.
149  
150 =head2 Unrestricted Ex commands
151  
152 C<ex> accepts C<target> and C<command>. Without C<buffer>, it executes the
153 command text in that editor's current buffer, window and directory.
154 An optional C<buffer> makes that buffer current first and leaves it current
155 unless the command changes it. C<expected_changedtick> requires C<buffer>
156 and is checked in Vim immediately before executing the command, after
157 entering the buffer. A stale tick prevents execution. Buffer loading and
158 entering can still have their normal Vim side effects.
159  
160 For example, C<command =E<gt> "update"> with a buffer id and its latest
161 changedtick saves that buffer only if its contents have not changed since
162 you inspected it. The tick does not describe the disk file or prevent
163 autocommands from running.
164  
165 The command can change the buffer, window and directory,
166 access files, invoke shell commands or configured functions, and exit Vim.
167 It is not restricted to the current buffer. Prefer the dedicated tools
168 when they express the requested operation.
169  
170 The permission prompt includes the command text. Persistent choices cover
171 this exact command in this editor, any Ex command in this editor, or any
172 Ex command in all current and future editors. Exact means the complete
173 command string, including whitespace and newlines. Such a rule applies to
174 all buffers in that editor: approving C<update> is not approval for only
175 the buffer used in the original request. Commands can invoke mappings,
176 functions and autocommands whose behaviour changes independently of the
177 command text.
178  
179 The result is C<{output: STRING}>, containing captured Vim messages.
180 An error is returned as a tool error; effects before that error remain.
181 Use noninteractive commands. Message capture suppresses ordinary message
182 display, but does not prevent commands from prompting or blocking Vim.
183 Request cancellation stops waiting for the reply, not a command already
184 running in Vim. If a command exits Vim, the connection can close before
185 a reply is delivered.
186  
187 =head1 VIM PLUGIN INSTALLATION
188  
189 The Vim plugin is included in the AnyEvent::MCP source distribution as
190 C<vim/plugin/mcp-vim.vim>. Installing the Perl distribution does not install
191 the Vim plugin. From the source distribution, install it yourself:
192  
193 mkdir -p ~/.vim/plugin
194 cp vim/plugin/mcp-vim.vim ~/.vim/plugin/mcp-vim.vim
195  
196 Alternatively, download the published plugin:
197  
198 mkdir -p ~/.vim/plugin
199 wget -O ~/.vim/plugin/mcp-vim.vim \
200 https://dist.schmorp.de/mcp-vim/1/mcp-vim.vim
201  
202 The C</1/> is the major version of the private Vim/broker protocol, not
203 the MCP protocol or the Perl distribution. Restart Vim after installing
204 or updating the plugin.
205  
206 Connect a Vim instance with C<:Mcp URL>, appending the desired target name
207 to the broker URL (which C<mcp-vim --print-url> can show):
208  
209 :Mcp http://HOST:PORT/TOKEN/TARGET
210  
211 To avoid typing the URL prefix repeatedly, configure
212 C<g:mcp_broker_url> in your vimrc:
213  
214 let g:mcp_broker_url = 'http://HOST:PORT/TOKEN/'
215  
216 Then use C<:Mcp TARGET>, with the target name alone.
217  
218 Distinct Vim instances requesting the same target name receive suffixes
219 such as C< #2>. Reconnecting the same instance replaces its connection and
220 keeps its assigned name. Use C<targets> to obtain the actual names.
221  
222 The Vim plugin uses a private protocol, not MCP. Its initial raw JSON line is
223 C<["mcp-vim", cookie, major, minor, target, instance_id]>; subsequent messages
224 use Vim's ordinary JSON channel envelope. The broker accepts clients with the
225 same major version and a minor version no newer than its own. Keep the broker
226 and plugin versions compatible when updating them.
227  
228 The broker itself can connect to a multibroker using
229 C<--connect http://host:port/token/alias>. Its own TCP listener remains active
230 for Vim and browser connections. The multibroker URL and the Vim broker's own
231 listener URL have independent credentials.
232  
233 =head1 CONNECTIONS AND AUTHENTICATION
234  
235 By default, the broker derives a stable port in the 16384..32767 range
236 from its service-instance name, defaulting to C<default>. Managed users
237 have individually derived tokens. All enabled users may authenticate MCP
238 requests, but only C<connect_user> (default C<default>) may register Vim
239 editors or XPCSE WebSockets. Configured C<tokens> or repeated C<--token>
240 options replace managed credentials and admit those explicit tokens for all
241 connection types. Keep tokens private.
242  
243 By default the TCP listener binds IPv4 loopback on the name-derived port.
244 C<bind> in C<[instance NAME]> or C<--bind> overrides the address and port.
245  
246 C<--stdio>, or C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio>, additionally
247 serves MCP over stdin/stdout. The TCP listener remains active. In this mode
248 the process exits after stdio closes and pending responses have drained.
249  
250 C<--print-url> prints enabled user URLs, annotating the connect user;
251 C<--print-url=USER> selects one. Neither starts a listener. Normal startup does not print
252 the credential. Use the same C<HOME> and C<XDG_CONFIG_HOME> as the
253 running broker, for example when checking the URL of a systemd service
254 account. Changing the global master secret changes derived tokens and
255 invalidates URLs using those tokens. Explicitly configured tokens are
256 independent of the master secret.
257  
258 =head1 PERMISSIONS
259  
260 MCP tool calls require permission independently of connection authentication.
261 C<read> covers C<targets>, C<state>, C<read-lines> and C<grep>.
262 C<write> covers C<apply-diff>, C<substitute>, C<undo>, C<redo> and C<set-cursor>, including
263 changes to the visible editor position. C<save> authorizes the C<save> tool and is
264 independent of C<read> and C<write>. C<open> independently authorizes loading
265 files by pathname. C<exec> authorizes the unrestricted
266 C<ex> tool. Neither C<read> nor C<write> implies C<exec>, or each other.
267 Explicit all-action rules also match C<exec>. Dedicated
268 editing tools leave buffers unsaved; C<save> saves explicitly, and Ex
269 commands can save files or perform other arbitrary work.
270  
271 Permission prompts offer the selected editor (all its buffers), or all
272 editors including future connections. Listing target names has its own
273 scope. Rules identify editors by their assigned target names, not connection
274 IDs; a saved rule also applies to a later editor using that name.
275 Buffer filenames do not restrict these grants.
276  
277 C<apply-diff> attaches display-only C<View patch> details containing the
278 editor name, buffer number and supplied diff. YAD offers a separate viewer;
279 terminal and native MCP prompts show a bounded preview inline. These details
280 do not narrow a saved editor-wide write grant.
281  
282 Rules are stored in
283 C<$XDG_CONFIG_HOME/anyevent-mcp/rules/vim-NAME.ini>, or the corresponding
284 C<$HOME/.config> path. C<NAME> is the service-instance name. For example,
285 C<mcp-vim> uses C<rules/vim-default.ini>. Subjects are C<target:TARGET>
286 for read/write access to an editor and C<targets> for discovery. Ex subjects
287 are C<ex:JSON_TARGET:JSON_COMMAND>, where both JSON values are strings.
288 The helper offers exact and editor-wide matchers; there is no need to
289 write their quoting by hand. An omitted subject still matches all subjects.
290 An allow rule needs an empty C<sandbox-grants> value:
291  
292 [rule]
293 decision=allow
294 action=read
295 subject=target:my-editor
296 sandbox-grants=
297  
298 By default, questions go to the local permission helper. C<--ask tty> and
299 C<--ask yad> force the built-in terminal or YAD interface without fallback.
300 Use C<--ask mcp>
301 to ask through a client with form elicitation, or C<--ask auto> to use
302 elicitation when advertised and the helper otherwise. A declined elicitation
303 does not fall back to the helper. The environment variable
304 C<PERL_ANYEVENT_MCP_PERMISSION_ASK> supplies the default when C<--ask> is
305 omitted. See L<AnyEvent::MCP::Server::Permissions> for rule and prompt details.
306  
307 These checks apply to MCP tools over both HTTP and stdio. They do not change
308 the authenticated private Vim connection or the browser session protocol.
309 Reads can still load explicitly addressed buffers and trigger Vim's usual
310 loading behaviour; these permissions do not sandbox Vim.
311  
312 =head1 OPTIONS
313  
314 Shared switches are documented in
315 L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
316 The following shared switch has editor-specific behavior.
317  
318 =over
319  
320 =item --ask MODE
321  
322 Permission prompts: C<helper> (default), C<tty>, C<yad>, C<mcp> or
323 C<auto>, or C<none>. tty/yad force local interface; mcp delegates to
324 client, auto prefers native elicitation when offered, and none denies
325 unmatched requests. See L</PERMISSIONS>.
326  
327 =back
328  
329 =head2 Shared-option behavior
330  
331 =over
332  
333 =item --bind ADDRESS[:PORT]
334  
335 Also selects the address and port for private Vim and browser WebSockets.
336  
337 =item --token TOKEN
338  
339 Also authenticates private Vim and browser WebSocket connections.
340  
341 =item --stdio
342  
343 The private Vim/WebSocket listener remains active while MCP uses stdio.
344  
345 =item --connect URL
346  
347 The private Vim/WebSocket listener remains active while MCP connects
348 outward to a multibroker.
349  
350 =item --print-url[=USER]
351  
352 Prints the credential-bearing URL prefix for Vim clients. Append a
353 Vim target as described in L</FIRST USE>.
354  
355 =item --auto-allow TOOL[,ACTION[,CAPABILITY]]
356  
357 For example, C<--auto-allow '*,write'> allows buffer edits, but not
358 C<save>, C<open> or unrestricted C<exec>.
359  
360 =back
361  
362 =head1 SYSTEMD
363  
364 A service can run C</path/to/mcp-vim> directly. Set its C<HOME> and, if
365 needed, C<XDG_CONFIG_HOME> so it uses the intended global secret.
366 Run C<mcp-vim --print-url> as the service user to obtain the connection URL;
367 there is no separate install-time cookie generation step.
368  
369 =cut
370  
371 7 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
372  
373 7 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
374 6 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
375 6 ▶use Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
376 6 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
377 6 ▶use JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
378  
379 6 ▶use AnyEvent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
380 6 ▶use AnyEvent::Socket ();
Subroutine BEGIN: called CC=1 SCAR=0.0
381 6 ▶use AnyEvent::MCP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
382 6 ▶use AnyEvent::MCP::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
383 6 ▶use AnyEvent::MCP::Extension ();
Subroutine BEGIN: called CC=1 SCAR=0.0
384 6 ▶use AnyEvent::MCP::Server::HTTP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
385 6 ▶use AnyEvent::MCP::Server::Toolset ();
Subroutine BEGIN: called CC=1 SCAR=0.0
386 6 ▶use AnyEvent::MCP::Server::Permissions ();
Subroutine BEGIN: called CC=1 SCAR=0.0
387  
388 6 ▶use AnyEvent::MCP::Server::Simple qw(mcp_getoptions mcp_tool_help mcp_log mcp_log_request);
Subroutine BEGIN: called CC=1 SCAR=0.0
389  
390 3 our $PORT;
391 3 our $NICK;
392  
393 3 my $usage = "Usage: mcp-vim [OPTION]...\n";
394 3 my $server_options = mcp_getoptions
395 {
396 usage => $usage,
397 path => "/",
398 description => "Bridge live Vim buffers to MCP and browser WebSocket clients.\n"
399 . "With --stdio, the broker also serves MCP on stdin/stdout; TCP stays active.",
400 examples => " mcp-vim --name editor --bind 127.0.0.1:20792\n"
401 . " mcp-vim --name editor --print-url\n"
402 . " mcp-vim --auto-allow '*,write'",
403 }
404 ;
405 3 ▶@ARGV and die $usage;
Branch: 1 branch
BranchTrueFalseTotal
@ARGV and die $usage 0 3 3
406  
407 3 my $ask = delete $server_options->{ask};
408 3 my $name = $server_options->{name};
409 3 my $bind = $server_options->{bind};
410 3 ▶my @tokens = @{$server_options->{tokens} || []};
Condition100%2/2
$server_options->{'tokens'} || []
l!l
12
MC/DC100%1/1
$server_options->{'tokens'} || []
$server_options->{'tokens'}
Truth table100%2/2
A
A= $server_options->{'tokens'}
Aresult
11
00
411 3 my $connect = $server_options->{connect};
412 3 ▶my $stdio = $server_options->{stdio} || !defined $connect && $ENV{PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL} eq "stdio";
Condition50%3/6
$server_options->{'stdio'} || !defined($connect) && $ENV{'PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL'} eq 'stdio'
l!l&&r!l&&!r
210
not defined $connect and $ENV{"PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL"} eq "stdio"
!ll&&!rl&&r
001
MC/DC0%0/3
$server_options->{'stdio'} || !defined($connect) && $ENV{'PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL'} eq 'stdio'
$server_options->{'stdio'} not defined $connect $ENV{"PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL"} eq "stdio"
Truth table50%2/4
A || not(B) and C
A= $server_options->{'stdio'}B= not defined $connectC= $ENV{"PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL"} eq "stdio"
ABCresult
1XX1
0111
00X0
0100
413 3 ▶!($stdio && defined $connect) or die "Cannot combine --stdio and --connect\n";
Branch: 1 branch
BranchTrueFalseTotal
($stdio and defined $connect) and die "Cannot combine --stdio and --connect\n" 0 3 3
Condition33%1/3
$stdio and defined $connect
!ll&&!rl&&r
030
MC/DC0%0/2
$stdio and defined $connect
$stdio defined $connect
Truth table33%1/3
A and B
A= $stdioB= defined $connect
ABresult
0X0
100
111
414  
415 # private Vim/broker wire protocol (separate from the browser protocol)
416 3 my $vim_prot_major = 1;
417 3 my $vim_prot_minor = 0;
418  
419 3 my $config = AnyEvent::MCP::Config::global_config ();
420 3 my %http = $config->http_settings ($name, $bind);
421 3 my $host = $http{host};
422 3 $PORT = $http{port};
423  
424 3 ▶$http{tokens} = \@tokens if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 1 2 3
425 3 ▶$http{connect_tokens} = \@tokens if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 1 2 3
426 3 ▶delete $http{token_users} if @tokens;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens 1 2 3
427 3 my @accepted_tokens = @{$http{tokens}};
428 3 my @connect_tokens = @{$http{connect_tokens}};
429 3 ▶/\A[A-Za-z0-9_.~-]+\z/ or die "Invalid mcp-vim token\n" for @accepted_tokens;
Branch: 1 branch
BranchTrueFalseTotal
/\A[A-Za-z0-9_.~-]+\z/u or die "Invalid mcp-vim token\n" 4 0 4
430 3 my %connect_token = map { $_ => 1 } @connect_tokens;
431  
432 3 ▶$NICK //= (POSIX::uname)[1] || die "cannot determine mcp-vim hostname\n";
Condition50%2/4
$main::NICK //= (POSIX::uname())[1] || die("cannot determine mcp-vim hostname\n")
l!l
03
(POSIX::uname())[1] || die("cannot determine mcp-vim hostname\n")
l!l
30
MC/DC0%0/1
$main::NICK //= (POSIX::uname())[1] || die("cannot determine mcp-vim hostname\n")
$main::NICK
Truth table50%1/2
A
A= $main::NICK
Aresult
11
00
433  
434 3 our $JSON_CODER = JSON::XS->new->utf8;
435  
436 #############################################################################
437  
438 3 my %xpcse;
439 my %vim;
440 3 my %target;
441  
442 5 ▶sub targets_changed {
Subroutine targets_changed: called CC=2 SCAR=6.9
443 6 $_->send_json ([targets => keys %target]) for values %xpcse;
444 }
445  
446 #############################################################################
447  
448 27 ▶sub base::emit {
Subroutine emit: called CC=2 SCAR=7.1
Pod undocumented
449 28 my ($self, $type, @args) = @_;
450  
451 30 eval {
452 28 $type =~ y/-/_/;
453 28 $type = "_on_$type";
454  
455 28 $self->$type (@args);
456 };
457 27 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 28 28
458 0 warn "error executing $type callback: $@";
459 }
460 }
461  
462 #############################################################################
463 # vim
464  
465 3 @vim::ISA = base::;
466  
467 2 ▶sub vim::new {
Subroutine new: called CC=8 SCAR=21.1
468 2 my ($class, $hdl, $hello) = @_;
469  
470 2 my ($requested, $instance_id) = @$hello[4, 5];
471  
472 (my $old) = grep
473 defined $instance_id
474 && defined $_->{instance_id}
475 && $_->{requested} eq $requested
476 2 ▶ && $_->{instance_id} eq $instance_id,
Condition66%6/9
defined $instance_id && defined $_->{'instance_id'} && $_->{'requested'} eq $requested && $_->{'instance_id'} eq $instance_id
!ll&&!rl&&r
110
defined $instance_id and defined $_->{"instance_id"} and $_->{"requested"} eq $requested
!ll&&!rl&&r
011
defined $instance_id and defined $_->{"instance_id"}
!ll&&!rl&&r
011
MC/DC0%0/4
defined $instance_id && defined $_->{'instance_id'} && $_->{'requested'} eq $requested && $_->{'instance_id'} eq $instance_id
defined $instance_id defined $_->{"instance_id"} $_->{"requested"} eq $requested $_->{'instance_id'} eq $instance_id
Truth table20%1/5
A and B and C && D
A= defined $instance_idB= defined $_->{"instance_id"}C= $_->{"requested"} eq $requestedD= $_->{'instance_id'} eq $instance_id
ABCDresult
0XXX0
10XX0
110X0
11100
11111
477 values %vim;
478  
479 2 ▶ my $name = $old ? $old->{target} : $requested;
Branch: 1 branch
BranchTrueFalseTotal
$old ? : 0 3 3
480 2 ▶ $old->destroy if $old;
Branch: 1 branch
BranchTrueFalseTotal
if $old 0 3 3
481  
482 2 ▶ unless ($old) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($old) 2 1 3
483 2 my $n = 2;
484 $name = "$requested #" . $n++
485 2 ▶ while exists $target{$name};
Branch: 1 branch
BranchTrueFalseTotal
exists $target{$name} and do { $name = "$requested #" . $n++ } 0 3 3
486 }
487  
488 2 my $self = bless {
489 ah => $hdl,
490 target => $name,
491 requested => $requested,
492 instance_id => $instance_id,
493 }, $class;
494  
495 2 $vim{$self+0} = $self;
496  
497 2 AE::log debug => "new vim connection\n";
498  
499 # the line-based hello reader leaves subsequent bytes in the handle.
500 2 $hdl->{json} = AnyEvent::MCP::json_class ()->new->utf8->max_depth (512);
501 2 $hdl->rtimeout (0);
502  
503 {
504 2 Scalar::Util::weaken (my $self = $self);
505  
506 2 ▶ $hdl->on_error (sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
507 2 $_[0]->destroy;
508 2 $self->destroy;
509 2 });
510 }
511  
512 2 mcp_log "vim <$self->{target}> connected";
513 2 $target{$self->{target}} = $self;
514 2 targets_changed;
515  
516 2 $self->read_json;
517 2 $self
518 }
519  
520 28 ▶sub vim::read_json {
Subroutine read_json: called CC=1 SCAR=0.0
521 28 my ($self) = @_;
522  
523 28 Scalar::Util::weaken (my $weak_self = $self);
524  
525 26 ▶ $self->{ah}->push_read (json => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
526 26 my (undef, $packet) = @_;
527  
528 26 ▶ my $self = $weak_self or return;
Branch: 1 branch
BranchTrueFalseTotal
my $self = $weak_self or return 27 0 27
529  
530 26 $self->emit (@{ $packet->[1] });
531 26 $self->read_json;
532 28 });
533 }
534  
535 2 ▶sub vim::destroy {
Subroutine destroy: called CC=5 SCAR=16.4
536 2 my ($self) = @_;
537  
538 2 ▶ delete $vim{$self+0}
Branch: 1 branch
BranchTrueFalseTotal
delete $vim{$self + 0} or return 2 1 3
539 or return;
540  
541 2 $self->{ah}->destroy;
542  
543 2 ▶ if (my $save = delete $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $save = delete $self->{"save"}) 1 4 5
544 0 $save->{xpcse}->cancel_save ($save);
545 }
546  
547 2 delete $target{$self->{target}};
548 2 targets_changed;
549  
550 $_->(0, "vim disconnected")
551 2 ▶ for values %{ delete $self->{rpccb} || {} };
Condition33%1/3
delete $self->{'rpccb'} || {}
l!l
300
MC/DC100%1/1
delete $self->{'rpccb'} || {}
delete $self->{'rpccb'}
Truth table100%2/2
A
A= delete $self->{'rpccb'}
Aresult
11
00
552  
553 2 mcp_log "vim <$self->{target}> disconnected";
554 }
555  
556 27 ▶sub vim::send_msg {
Subroutine send_msg: called CC=1 SCAR=0.0
557 27 my ($self, $msg) = @_;
558  
559 27 $self->{ah}->push_write (json => [0, $msg]);
560  
561 27 AE::log trace => "$self->{target} < @$msg";#d#
562 }
563  
564 27 ▶sub vim::rpc_ {
Subroutine rpc_: called CC=1 SCAR=0.0
565 27 my $cb = pop;
566 27 my ($self, $cmd, @args) = @_;
567  
568 27 my $id = ++$self->{rpcid};
569 27 $self->{rpccb}{$id} = $cb;
570  
571 27 $self->send_msg ([call => $id, $cmd, @args]);
572 }
573  
574 26 ▶sub vim::_on_reply {
Subroutine _on_reply: called CC=2 SCAR=6.9
575 26 my ($self, $id, $success, $result) = @_; # also backtrace, but we completely ignore that
576  
577 26 ▶ my $cb = delete $self->{rpccb}{$id}
Branch: 1 branch
BranchTrueFalseTotal
my $cb = delete $self->{"rpccb"}{$id} or die "reply for id $id has no callback\n" 27 2 29
578 or die "reply for id $id has no callback\n";
579  
580 26 $cb->($success, $result);
581 }
582  
583 # startup session info
584 0 ▶sub vim::_on_session {
Subroutine _on_session: not called CC=1 SCAR=6.9
585 0 my ($self, $id, $state) = @_;
586  
587 0 $self->{session}{$id} = $state;
588 }
589  
590 0 ▶sub vim::_on_ack {
Subroutine _on_ack: not called CC=1 SCAR=6.9
591 0 my ($self, $bytes) = @_;
592 }
593  
594 # end of session list
595 0 ▶sub vim::_on_sessions_done {
Subroutine _on_sessions_done: not called CC=1 SCAR=6.9
596 0 my ($self) = @_;
597  
598 0 $self->send_msg ([echo => "connected as '$self->{target}'"]);
599 }
600  
601 0 ▶sub vim::_on_save {
Subroutine _on_save: not called CC=4 SCAR=30.0
602 0 my ($self, $id, $force) = @_;
603  
604 # a save's input belongs to Vim until eof; the browser queue owns the upload.
605 0 ▶ if (my $old = delete $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $old = delete $self->{"save"}) 0 0 0
606 0 $old->{xpcse}->cancel_save ($old);
607 }
608  
609 0 ▶ my $hdrs = $self->{session}{$id}
Branch: 1 branch
BranchTrueFalseTotal
my $hdrs = $self->{"session"}{$id} or return $self->send_msg(["echo", "${id}: session not found"]) 0 0 0
610 or return $self->send_msg ([echo => "$id: session not found"]);
611  
612 0 my ($xpcse) = grep $_->{origin} eq $hdrs->{origin}, values %xpcse;
613  
614 0 ▶ $xpcse
Branch: 1 branch
BranchTrueFalseTotal
$xpcse or return $self->send_msg(["echo", qq[${id}: no origin found, connect a tab for $hdrs->{"origin"}]]) 0 0 0
615 or return $self->send_msg ([echo => "$id: no origin found, connect a tab for $hdrs->{origin}"]);
616  
617 0 AE::log info => "save $id $hdrs->{origin}";
618 0 $self->send_msg ([echo => "requesting save to $hdrs->{origin}..."]);
619  
620 0 $self->{save} = $xpcse->save ($self, $id, $hdrs, $force);
621 }
622  
623 0 ▶sub vim::_on_data {
Subroutine _on_data: not called CC=2 SCAR=17.9
624 0 my ($self, $encoded) = @_;
625  
626 0 my $data = MIME::Base64::decode_base64 $encoded;
627  
628 0 ▶ if (my $save = $self->{save}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $save = $self->{'save'}) { } 0 0 0
629 0 push @{$save->{data}}, $data;
630 0 $save->{xpcse}->send_data;
631 } else {
632 # discard a rejected save's input without holding up its sender.
633 0 $self->send_msg ([ack => length $data]);
634 }
635 }
636  
637 0 ▶sub vim::_on_eof {
Subroutine _on_eof: not called CC=3 SCAR=24.8
638 0 my ($self, $success) = @_;
639  
640 my $save = delete $self->{save}
641 0 ▶ or return;
Branch: 1 branch
BranchTrueFalseTotal
my $save = delete $self->{"save"} or return 0 0 0
642  
643 0 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 0 0 0
644 0 $save->{eof} = 1;
645 0 $save->{xpcse}->send_data;
646 } else {
647 0 $save->{xpcse}->cancel_save ($save);
648 }
649 }
650  
651 0 ▶sub vim::_on_close {
Subroutine _on_close: not called CC=2 SCAR=17.9
652 0 my ($self, $id) = @_;
653  
654 0 ▶ my $hdrs = $self->{session}{$id}
Branch: 1 branch
BranchTrueFalseTotal
my $hdrs = $self->{"session"}{$id} or return $self->send_msg(["echo", "${id}: session not found"]) 0 0 0
655 or return $self->send_msg ([echo => "$id: session not found"]);
656  
657 0 AE::log debug => "vim session close $id";
658  
659 0 unlink $hdrs->{path};
660 0 delete $self->{session}{$id};
661 }
662  
663 0 ▶sub vim::session_open {
Subroutine session_open: not called CC=2 SCAR=16.3
664 0 my ($self, $hdrs) = @_;
665  
666 0 my $id = "s" . substr rand, 2;
667 0 $self->{session}{$id} = $hdrs;
668  
669 0 AE::log debug => "vim session open: $id $hdrs->{path}";
670  
671 0 my $filename = $hdrs->{filename};
672  
673 0 $filename =~ s/->/âž”/g;
674 0 $filename =~ s/::/∷/g;
675 0 $filename =~ s/\//∕/g;
676 0 $filename =~ s/[\/<>:"\\|\?\*\x00-\x1f]/_/g;
677  
678 0 ▶ $self->send_msg ([open => "$id", $filename // "unknown", $hdrs->{extension}, $hdrs]);
Condition50%1/2
$filename // "unknown"
l!l
01
MC/DC0%0/1
$filename // "unknown"
$filename
Truth table50%1/2
A
A= $filename
Aresult
11
00
679 }
680  
681 0 ▶sub vim::_on_quit {
Subroutine _on_quit: not called CC=1 SCAR=6.9
682 0 my ($self) = @_;
683  
684 0 $self->destroy;
685 }
686  
687 #############################################################################
688  
689 3 @xpcse::ISA = base::;
690  
691 1 ▶sub xpcse::new {
Subroutine new: called CC=1 SCAR=0.3
692 1 my ($class, $self) = @_;
693  
694 1 bless $self, $class;
695  
696 {
697 1 Scalar::Util::weaken (my $self = $self);
698  
699 0 ▶ $self->{conn}->on (finish => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
700 #AE::log trace => "on finish";#d#
701 0 $self->finish;
702 1 });
703  
704 1 ▶ $self->{conn}->on (each_message => sub {
Subroutine __ANON__: called CC=3 SCAR=13.2
705 1 eval {
706 1 my $opcode = $_[1]->opcode;
707  
708 1 ▶ if ($opcode == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opcode == 1) { } 1 0 1
709 1 AE::log trace => "websocket recv: " . $_[1]->body;
710  
711 1 $self->emit (@{ $JSON_CODER->decode ($_[1]->body) });
712  
713 } else {
714 0 my $data = $_[1]->body;
715 0 $self->{ondata_cb}($self, $data);
716 0 $self->send_json ([ack => length $data]);
717 }
718 };
719 1 ▶ if ($@) { # AnyEvent::WebScoket simply eats errors and silently disconnects
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
720 0 warn $@;
721 0 exit 1;
722 }
723 1 });
724  
725 0 ▶ $self->{pinger} = AE::timer 5, 10 * 60, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
726 # send regular pong frames, to satisfy nginx and to probe the connection
727 0 $self->{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 10, body => ""));
728 1 };
729 }
730  
731 1 $xpcse{$self+0} = $self; # keep alive
732  
733 1 $self->send_json ([nick => $NICK]);
734  
735 1 targets_changed;
736  
737 1 $self
738 }
739  
740 1 ▶sub xpcse::_on_xpcse_client {
Subroutine _on_xpcse_client: called CC=2 SCAR=7.0
741 1 my ($self, $version) = @_;
742  
743 1 ▶ if ($version != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($version != 1) 1 0 1
744 1 AE::log warn => "ws xpcse client version mismatch (me 1, them $version)";
745 1 $self->destroy;
746 1 return;
747 }
748 }
749  
750 0 ▶sub xpcse::_on_open {
Subroutine _on_open: not called CC=2 SCAR=17.9
751 0 my ($self, $target, $hdrs) = @_;
752  
753 0 ▶ if (my $vim = $target{$target}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = $target{$target}) { } 0 0 0
754 0 $self->{upload_vim} = $vim;
755  
756 0 $vim->session_open ($hdrs);
757  
758 0 ▶ $self->{ondata_cb} = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
759 0 ▶ $vim->send_msg ([data => MIME::Base64::encode_base64 $_[1], ""]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
760 0 };
761 } else {
762 0 ▶ $self->{ondata_cb} = sub { };
Subroutine __ANON__: not called CC=1 SCAR=6.9
763 }
764 }
765  
766 1 ▶sub xpcse::_on_eof {
Subroutine _on_eof: called CC=3 SCAR=14.2
767 1 my ($self, $success) = @_;
768  
769 1 ▶ if (my $vim = delete $self->{upload_vim}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = delete $self->{"upload_vim"}) 0 1 1
770 0 ▶ $vim->send_msg ([eof => $success*1]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
771 }
772  
773 1 delete $self->{ondata_cb};
774 }
775  
776 2 ▶sub xpcse::send_json {
Subroutine send_json: called CC=1 SCAR=0.0
777 2 $_[0]{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 1, body => $JSON_CODER->encode ($_[1])));
778 }
779  
780 0 ▶sub xpcse::send_bin {
Subroutine send_bin: not called CC=1 SCAR=6.9
781 0 $_[0]{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 2, body => $_[1]));
782 }
783  
784 1 ▶sub xpcse::destroy {
Subroutine destroy: called CC=10 SCAR=31.1
785 1 my ($self, $code) = @_;
786  
787 1 ▶ delete $xpcse{$self+0}
Branch: 1 branch
BranchTrueFalseTotal
delete $xpcse{$self + 0} or return 1 0 1
788 or return;
789  
790 1 ▶ $code ||= 1002;
Condition100%2/2
$code ||= 1002
l!l
11
MC/DC0%0/1
$code ||= 1002
$code
Truth table50%1/2
A
A= $code
Aresult
11
00
791  
792 1 delete $self->{pinger};
793  
794 1 $self->_on_eof (0);
795 1 ▶ for my $save (@{delete $self->{saves} || []}) {
Condition50%1/2
delete $self->{'saves'} || []
l!l
02
MC/DC0%0/1
delete $self->{'saves'} || []
delete $self->{'saves'}
Truth table50%1/2
A
A= delete $self->{'saves'}
Aresult
11
00
796 0 ▶ if (my $vim = $save->{vim}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $vim = $save->{"vim"}) 0 0 0
797 delete $vim->{save}
798 0 ▶ if $vim->{save} && $vim->{save} == $save;
Branch: 1 branch
BranchTrueFalseTotal
if $vim->{"save"} and $vim->{"save"} == $save 0 0 0
Condition0%0/3
$vim->{"save"} and $vim->{"save"} == $save
!ll&&!rl&&r
000
MC/DC0%0/2
$vim->{"save"} and $vim->{"save"} == $save
$vim->{"save"} $vim->{"save"} == $save
Truth table0%0/3
A and B
A= $vim->{"save"}B= $vim->{"save"} == $save
ABresult
0X0
100
111
799 0 ▶ $vim->send_msg ([echo => "$save->{session}: browser disconnected"]) if $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim{$vim + 0} 0 0 0
800 }
801 }
802  
803 1 my $conn = delete $self->{conn};
804  
805 1 ▶ $conn->close ($code) if $conn;
Branch: 1 branch
BranchTrueFalseTotal
if $conn 1 0 1
806  
807 1 AE::log debug => "websocket connection destroy $code";
808 }
809  
810 0 ▶sub xpcse::finish {
Subroutine finish: not called CC=1 SCAR=6.9
811 0 shift->destroy (@_);
812 }
813  
814 0 ▶sub xpcse::save {
Subroutine save: not called CC=2 SCAR=17.9
815 0 my ($self, $vim, $session, $hdrs, $force) = @_;
816  
817 0 ▶ my $save = {
Branch: 1 branch
BranchTrueFalseTotal
$force ? : 0 0 0
818 xpcse => $self,
819 vim => $vim,
820 session => $session,
821 hdrs => $hdrs,
822 force => $force ? 1 : 0,
823 data => [],
824 };
825  
826 # the queue and Vim input own the save; neither endpoint is kept alive by it.
827 0 Scalar::Util::weaken ($save->{xpcse});
828 0 Scalar::Util::weaken ($save->{vim});
829 0 push @{$self->{saves}}, $save;
830 0 $self->send_data;
831 0 $save
832 }
833  
834 0 ▶sub xpcse::send_data {
Subroutine send_data: not called CC=7 SCAR=40.3
835 0 my ($self) = @_;
836  
837 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
838 or return;
839  
840 0 ▶ unless (exists $save->{credit}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $save->{"credit"}) 0 0 0
841 0 $save->{credit} = 10e6;
842 # trailing flag is ignored by current browser clients.
843 0 $self->send_json ([upload => $save->{hdrs}, $save->{force}]);
844 }
845  
846 # a positive credit admits one whole chunk, even if it exceeds the window.
847 0 ▶ while (@{$save->{data}} && $save->{credit} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$save->{"data"};} and $save->{"credit"} > 0) 0 0 0
Condition0%0/3
@{$save->{"data"};} and $save->{"credit"} > 0
!ll&&!rl&&r
000
MC/DC0%0/2
@{$save->{"data"};} and $save->{"credit"} > 0
@{$save->{"data"};} $save->{"credit"} > 0
Truth table0%0/3
A and B
A= @{$save->{"data"};}B= $save->{"credit"} > 0
ABresult
0X0
100
111
848 0 my $data = shift @{$save->{data}};
849 0 $save->{credit} -= length $data;
850 0 $self->send_bin ($data);
851 }
852  
853 # eof is 1 when Vim has finished, 2 once the browser has been told.
854 0 ▶ if ($save->{eof} == 1 && !@{$save->{data}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($save->{"eof"} == 1 and not @{$save->{"data"};}) 0 0 0
Condition0%0/3
$save->{"eof"} == 1 and not @{$save->{"data"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$save->{"eof"} == 1 and not @{$save->{"data"};}
$save->{"eof"} == 1 not @{$save->{"data"};}
Truth table0%0/3
A and not(B)
A= $save->{"eof"} == 1B= not @{$save->{"data"};}
ABresult
0X0
100
111
855 0 $save->{eof} = 2;
856 0 $self->send_json (["upload-done"]);
857 }
858 }
859  
860 0 ▶sub xpcse::_on_ack {
Subroutine _on_ack: not called CC=6 SCAR=37.4
861 0 my ($self, $bytes) = @_;
862  
863 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
864 or return;
865  
866 $bytes =~ /\A[0-9]+\z/ && $bytes <= 10e6 - $save->{credit}
867 0 ▶ or return $self->destroy;
Branch: 1 branch
BranchTrueFalseTotal
$bytes =~ /\A[0-9]+\z/u and $bytes <= 10000000 - $save->{"credit"} or return $self->destroy 0 0 0
Condition0%0/3
$bytes =~ /\A[0-9]+\z/u and $bytes <= 10000000 - $save->{"credit"}
!ll&&!rl&&r
000
MC/DC0%0/2
$bytes =~ /\A[0-9]+\z/u and $bytes <= 10000000 - $save->{"credit"}
$bytes =~ /\A[0-9]+\z/u $bytes <= 10000000 - $save->{"credit"}
Truth table0%0/3
A and B
A= $bytes =~ /\A[0-9]+\z/uB= $bytes <= 10000000 - $save->{"credit"}
ABresult
0X0
100
111
868  
869 0 $save->{credit} += $bytes;
870  
871 # ack means receipt by the browser, independently of the final save result.
872 0 my $vim = $save->{vim};
873 0 ▶ $vim->send_msg ([ack => $bytes]) if $vim && $vim{$vim+0};
Branch: 1 branch
BranchTrueFalseTotal
if $vim and $vim{$vim + 0} 0 0 0
Condition0%0/3
$vim and $vim{$vim + 0}
!ll&&!rl&&r
000
MC/DC0%0/2
$vim and $vim{$vim + 0}
$vim $vim{$vim + 0}
Truth table0%0/3
A and B
A= $vimB= $vim{$vim + 0}
ABresult
0X0
100
111
874  
875 0 $self->send_data;
876 }
877  
878 0 ▶sub xpcse::_on_upload_done {
Subroutine _on_upload_done: not called CC=13 SCAR=52.0
879 0 my ($self, $status, $msg, $etag) = @_;
880  
881 0 ▶ my $save = $self->{saves}[0]
Branch: 1 branch
BranchTrueFalseTotal
my $save = $self->{"saves"}[0] or return 0 0 0
882 or return;
883  
884 0 ▶ $save->{eof} == 2
Branch: 1 branch
BranchTrueFalseTotal
$save->{"eof"} == 2 or return $self->destroy 0 0 0
885 or return $self->destroy;
886  
887 0 shift @{$self->{saves}};
888  
889 0 my $vim = $save->{vim};
890 0 ▶ if ($vim && $vim{$vim+0}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vim and $vim{$vim + 0}) 0 0 0
Condition0%0/3
$vim and $vim{$vim + 0}
!ll&&!rl&&r
000
MC/DC0%0/2
$vim and $vim{$vim + 0}
$vim $vim{$vim + 0}
Truth table0%0/3
A and B
A= $vimB= $vim{$vim + 0}
ABresult
0X0
100
111
891 0 ▶ if ($status == 200 && defined $etag && $etag =~ /\A"sha256:[a-f0-9]{64}"\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 200 and defined $etag and $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u) 0 0 0
Condition0%0/6
$status == 200 and defined $etag and $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
!ll&&!rl&&r
000
$status == 200 and defined $etag
!ll&&!rl&&r
000
MC/DC0%0/3
$status == 200 and defined $etag and $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
$status == 200 defined $etag $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
Truth table0%0/4
A and B and C
A= $status == 200B= defined $etagC= $etag =~ /\A"sha256:[a-f0-9]{64}"\z/u
ABCresult
0XX0
10X0
1100
1111
892 0 ▶ if (my $state = $vim->{session}{$save->{session}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $state = $vim->{"session"}{$save->{"session"}}) 0 0 0
893 0 $state->{etag} = $etag;
894 0 $vim->send_msg (["update-metadata" => $save->{session}, { etag => $etag }]);
895 }
896 }
897 0 ▶ if ($status != 200 || $msg =~ /\n/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status != 200 or $msg =~ /\n/u) { } 0 0 0
Condition0%0/3
$status != 200 or $msg =~ /\n/u
l!l&&r!l&&!r
000
MC/DC0%0/2
$status != 200 or $msg =~ /\n/u
$status != 200 $msg =~ /\n/u
Truth table0%0/3
A or B
A= $status != 200B= $msg =~ /\n/u
ABresult
1X1
011
000
898 0 $msg =~ s/^upload ok, but.*:\n+//;
899 0 $msg =~ s/\n\n+/\n/g;
900 0 $msg =~ s/\n\z//;
901 0 ▶ $vim->send_msg ([error => "error: " . ($status == 200 ? "" : "HTTP $status: ") . $msg]);
Branch: 1 branch
BranchTrueFalseTotal
$status == 200 ? : 0 0 0
902  
903 0 ▶ if ($msg =~ / line ([0-9]+), /) {
Branch: 1 branch
BranchTrueFalseTotal
if ($msg =~ / line ([0-9]+), /u) 0 0 0
904 0 $vim->send_msg ([goto => $save->{session}, $1, 1]);
905 }
906  
907 0 AE::log warn => "upload error: $status $msg";
908 } else {
909 0 $vim->send_msg ([echo => "$status $msg"]);
910 }
911 }
912  
913 # the browser's reply, rather than sending eof, releases the next upload.
914 0 $self->send_data;
915 }
916  
917 0 ▶sub xpcse::cancel_save {
Subroutine cancel_save: not called CC=2 SCAR=17.9
918 0 my ($self, $save) = @_;
919  
920 0 ▶ if ($self->{saves}[0] == $save) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'saves'}[0] == $save) { } 0 0 0
921 # there is no upload-abort message; closing prevents a partial POST.
922 0 $self->destroy (1011);
923 } else {
924 0 @{$self->{saves}} = grep $_ != $save, @{$self->{saves}};
925 }
926 }
927  
928 #############################################################################
929  
930 my $permissions = AnyEvent::MCP::Server::Permissions->new (
931 name => "vim-$name",
932 actions => {
933 read => "Read Vim target names, editor state and buffer contents",
934 open => "Load a file into a Vim buffer; autocommands and modelines may run",
935 write => "Change Vim buffer contents or the editor position",
936 save => "Save a Vim buffer to its current filename if modified",
937 exec => "Execute arbitrary Vim commands with full host-user privileges",
938 },
939 (defined $ask ? (ask => $ask) : ()),
940 3 ▶ auto_rules => [@{$server_options->{auto_rules} || []},
Branch: 1 branch
BranchTrueFalseTotal
defined $ask ? : 1 2 3
Condition50%1/2
$server_options->{'auto_rules'} || []
l!l
03
MC/DC0%0/1
$server_options->{'auto_rules'} || []
$server_options->{'auto_rules'}
Truth table50%1/2
A
A= $server_options->{'auto_rules'}
Aresult
11
00
941 $config->auto_rules ($name)],
942 );
943  
944 61 ▶sub vim_permission {
Subroutine vim_permission: called CC=9 SCAR=22.0
945 61 my ($req, $action, $name, $command, $details, $reason) = @_;
946  
947 61 ▶ my $subject = defined $name ? "target:$name" : "targets";
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 53 8 61
948 61 ▶ my $label = defined $name ? "editor '$name' (all buffers)" : "the list of connected editors";
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 53 8 61
949 61 my @subjects = (
950 { label => $label, match => $subject },
951 { label => "all Vim editors, including future connections", match => "^" },
952 );
953  
954 61 ▶ if (defined $command) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $command) 14 47 61
955 14 my $json = JSON::XS->new->allow_nonref;
956 14 my $editor = "ex:" . $json->encode ($name) . ":";
957 14 $subject = $editor . $json->encode ($command);
958 14 (my $preview = $command) =~ s/\s+/ /g;
959 14 ▶ $preview = substr ($preview, 0, 87) . "..." if length $preview > 90;
Branch: 1 branch
BranchTrueFalseTotal
if length $preview > 90 0 14 14
960 14 @subjects = (
961 { label => "This command: $preview (editor '$name', all buffers)", match => $subject },
962 { label => "any Ex command in editor '$name' (all buffers)", match => "^" . (quotemeta $editor) },
963 { label => "any Ex command in any Vim editor, including future connections", match => "^" },
964 );
965 }
966  
967 $req->require_permission ({
968 tool => $req->{tool},
969 61 ▶ action => $action,
Branch: 3 branches
BranchTrueFalseTotal
defined $name ? : 51 8 59
defined $command ? : 14 45 59
defined $details ? : 3 58 61
Condition100%2/2
$reason // qq[$req->{"tool"}: ] . (defined $name ? "Vim editor '${name}'" : "list connected Vim editors") . (defined $command ? "\n\n$command" : "")
l!l
259
MC/DC100%1/1
$reason // qq[$req->{"tool"}: ] . (defined $name ? "Vim editor '${name}'" : "list connected Vim editors") . (defined $command ? "\n\n$command" : "")
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
970 dimensions => { subject => { label => "Editor / command", value => $subject, choices => \@subjects } },
971 sandbox_grants => [],
972 reason => $reason // ("$req->{tool}: " . (defined $name ? "Vim editor '$name'" : "list connected Vim editors")
973 . (defined $command ? "\n\n$command" : "")),
974 (defined $details ? (details => $details) : ()),
975 });
976 }
977  
978 3 my $toolset = AnyEvent::MCP::Server::Toolset->new;
979 3 my $json = JSON::XS->new;
980  
981 25 ▶sub rpc_reply {
Subroutine rpc_reply: called CC=1 SCAR=0.0
982 25 my ($req, $format) = @_;
983  
984 25 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
985 25 my ($success, $result) = @_;
986  
987 25 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 1 24 25
988  
989 eval {
990 24 ▶ $success or die "$result\n";
Branch: 1 branch
BranchTrueFalseTotal
$success or die "$result\n" 19 5 24
991  
992 19 ▶ $req->reply ($format ? $format->($result) : {
Branch: 1 branch
BranchTrueFalseTotal
$format ? : 2 17 19
993 content => [{
994 type => "text",
995 text => $json->encode ($result),
996 }],
997 });
998 19 1
999 24 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $success or die "$result\n"; $req->reply($format ? &$format($result) : {"content", [{"type", "text", "text", $json->encode($result)}]}); 1 } } or do { my $error = $@; return if $req->{"cancelled"}; die $error if $req->{"finished"}; &AE::log("info", qq[mcp-tool $req->{"tool"}: $error]); $req->error($error) } 19 5 24
1000 5 my $error = $@;
1001  
1002 5 ▶ return if $req->{cancelled};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"cancelled"} 0 5 5
1003 5 ▶ die $error if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 0 5 5
1004  
1005 5 AE::log info => "mcp-tool $req->{tool}: $error";
1006 5 $req->error ($error);
1007 };
1008 }
1009 25 }
1010  
1011 $toolset->tool (targets =>
1012 "List connected Vim targets (human-readable editor/session IDs). Use if target unknown.",
1013 {
1014 type => "object",
1015 properties => {},
1016 },
1017 7 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1018 7 my ($req, $args) = @_;
1019  
1020 7 vim_permission $req, read => undef;
1021  
1022 5 AE::log debug => "vim targets";
1023  
1024 5 $req->reply ({
1025 content => [{
1026 type => "text",
1027 text => $json->encode ([sort keys %target]),
1028 }],
1029 });
1030 }
1031 3 );
1032  
1033 $toolset->tool (state =>
1034 "Get live Vim state; optional target selects one editor, omit for all. "
1035 . "Returns target => state: cwd, current buffer/cursor, buffer metadata. "
1036 . "Unloaded buffers have null changedtick/line_count; read/search before guarded edits. "
1037 . "Explicit buffer access loads on demand. "
1038 . "Call state each turn if current editor/buffer unknown. "
1039 . "Buffers are live editor state, not disk snapshots.",
1040 {
1041 type => "object",
1042 properties => {
1043 target => {
1044 type => "string",
1045 description => "Optional Vim target id from targets. Omit for all targets.",
1046 },
1047 },
1048 required => [],
1049 },
1050 9 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
1051 9 my ($req, $args) = @_;
1052  
1053 9 ▶ my @log = length $args->{target} ? $args->{target} : ();
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'target'} ? : 3 6 9
1054  
1055 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1056 9 AE::log debug => join " ", "vim state", @log;
1057  
1058 my @targets = length $args->{target}
1059 ? $args->{target}
1060 9 ▶ : keys %target;
Branch: 1 branch
BranchTrueFalseTotal
length $args->{'target'} ? : 3 6 9
1061  
1062 # permission retries must happen before any of the parallel RPCs start.
1063 9 vim_permission $req, read => $_ for @targets;
1064 5 ▶ vim_permission $req, read => undef unless @targets;
Branch: 1 branch
BranchTrueFalseTotal
unless @targets 1 4 5
1065  
1066 5 my %state;
1067 5 my $pending = @targets;
1068 5 my $reply = rpc_reply $req;
1069  
1070 5 ▶ return $reply->(1, \%state) unless $pending;
Branch: 1 branch
BranchTrueFalseTotal
unless $pending 1 4 5
1071  
1072 4 for my $name (@targets) {
1073 7 ▶ my $vim = $target{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$name} or die "target does not exist: $name\n" 7 0 7
1074 or die "target does not exist: $name\n";
1075  
1076 7 ▶ $vim->rpc_ (state => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1077 7 my ($success, $result) = @_;
1078  
1079 7 ▶ return $reply->(0, $result) unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 1 6 7
1080  
1081 6 $state{$name} = $result;
1082 6 ▶ $reply->(1, \%state) unless --$pending;
Branch: 1 branch
BranchTrueFalseTotal
unless --$pending 3 3 6
1083 7 });
1084 }
1085 }
1086 3 );
1087  
1088 $toolset->tool (read_lines =>
1089 "linenums=true prefixes absolute line number and colon. " .
1090 "Read live Vim ranges; load explicit buffer on demand. Returns JSON changedtick/range metadata, then two MCP text items per range: [range=start,end], newline-terminated lines.",
1091 {
1092 type => "object",
1093 properties => {
1094 target => {
1095 type => "string",
1096 description => "Vim target id.",
1097 },
1098 buffer => {
1099 type => "integer",
1100 description => "Buffer id from state.",
1101 },
1102 ranges => {
1103 type => "array",
1104 description => "One or more restricted Vim Ex ranges: %, ., $, positive line numbers, +/- offsets, /regex/, ?regex?, and optional , or ; between two addresses.",
1105 minItems => 1,
1106 items => { type => "string" },
1107 },
1108 linenums => {
1109 type => "boolean",
1110 default => JSON::XS::false,
1111 description => "Prefix each line with its absolute line number and a colon.",
1112 },
1113 },
1114 required => ["target", "buffer", "ranges"],
1115 },
1116 3 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1117 3 my ($req, $args) = @_;
1118  
1119 3 vim_permission $req, read => $args->{target};
1120  
1121 2 my @log = ($args->{target}, $args->{buffer}, @{$args->{ranges}});
1122  
1123 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1124 2 AE::log debug => join " ", "vim read-lines", @log;
1125  
1126 $target{$args->{target}}->rpc_ (
1127 2 ▶ read_lines => $args->{buffer}, $args->{ranges}, rpc_reply ($req, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1128 2 my ($result) = @_;
1129  
1130 2 my @ranges = @{$result->{ranges}};
1131 my $metadata = {
1132 changedtick => $result->{changedtick},
1133 ranges => [map {
1134 2 +{
1135 range => $_->{range},
1136 start => $_->{start},
1137 end => $_->{end},
1138 }
1139 4 } @ranges],
1140 };
1141  
1142 +{
1143 content => [
1144 {
1145 type => "text",
1146 text => $json->encode ($metadata),
1147 },
1148 2 map {{
1149 type => "text",
1150 text => "[range=$_->{start},$_->{end}]",
1151 }, {
1152 type => "text",
1153 4 text => do {
1154 4 my $line = $_->{start};
1155 4 ▶ join "", map { ($args->{linenums} ? $line++ . ":" : "") . "$_\n" } @{$_->{lines}};
Branch: 1 branch
BranchTrueFalseTotal
$args->{'linenums'} ? : 3 4 7
1156 },
1157 }} @ranges,
1158 ],
1159 }
1160 })
1161 2 );
1162 }
1163 3 );
1164  
1165 $toolset->tool (grep =>
1166 "Search Vim buffers; load explicit IDs on demand; empty buffers = all loaded buffers. "
1167 . "mode=regex: native Vim regex; mode=word: literal whole word. "
1168 . "Returns buffer/tick/line/column/text matches, truncated flag.",
1169 {
1170 type => "object",
1171 properties => {
1172 target => {
1173 type => "string",
1174 description => "Vim target id.",
1175 },
1176 buffers => {
1177 type => "array",
1178 description => "Buffer IDs; explicit IDs load on demand; [] = all loaded buffers.",
1179 items => { type => "integer" },
1180 },
1181 pattern => {
1182 type => "string",
1183 description => "Native Vim regex (mode=regex) or literal word (mode=word).",
1184 },
1185 mode => {
1186 type => "string",
1187 enum => ["regex", "word"],
1188 description => "Search syntax.",
1189 },
1190 max_results => {
1191 type => "integer",
1192 minimum => 1,
1193 description => "Max matches.",
1194 },
1195 },
1196 required => ["target", "buffers", "pattern", "mode", "max_results"],
1197 },
1198 6 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1199 6 my ($req, $args) = @_;
1200  
1201 6 vim_permission $req, read => $args->{target};
1202  
1203 5 my @buffers = map 0 + $_, @{$args->{buffers}};
1204 5 ▶ my $log_buffers = @buffers ? (join ",", map 0 + $_, @buffers) : "*";
Branch: 1 branch
BranchTrueFalseTotal
@buffers ? : 5 0 5
1205 my @log = (
1206 $args->{target},
1207 $log_buffers,
1208 $args->{mode},
1209 5 (substr $args->{pattern}, 0, 20),
1210 );
1211  
1212 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1213 5 AE::log debug => join " ", "vim grep", @log;
1214  
1215 $target{$args->{target}}->rpc_ (
1216 5 grep => \@buffers, $args->{pattern}, $args->{mode}, $args->{max_results}, rpc_reply ($req)
1217 );
1218 }
1219 3 );
1220  
1221 1 ▶sub normalize_udiff {
Subroutine normalize_udiff: called CC=22 SCAR=34.9
1222 1 my $diff = shift;
1223 1 my @line = split /\n/, $diff, -1;
1224 1 my $delta = 0;
1225 1 my $hunks = 0;
1226 1 my @max_offset;
1227  
1228 1 ▶ pop @line while @line and !length $line[-1];
Branch: 1 branch
BranchTrueFalseTotal
@line and not length $line[-1] and do { pop @line } 1 1 2
Condition66%2/3
@line and not length $line[-1]
!ll&&!rl&&r
011
MC/DC50%1/2
@line and not length $line[-1]
@line not length $line[-1]
Truth table66%2/3
A and not(B)
A= @lineB= not length $line[-1]
ABresult
0X0
100
111
1229  
1230 1 ▶ for (my $i = 0; $i < @line; ++$i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @line) 1 1 2
1231 1 ▶ next unless $line[$i] =~ /^@@ /;
Branch: 1 branch
BranchTrueFalseTotal
unless $line[$i] =~ /^\@@ /u 0 1 1
1232  
1233 1 ▶ $line[$i] =~ /^@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? @@(.*)$/
Branch: 1 branch
BranchTrueFalseTotal
$line[$i] =~ /^\@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? \@@(.*)$/u or die "normalize_udiff: bad hunk header '$line[$i]'\n" 1 0 1
1234 or die "normalize_udiff: bad hunk header '$line[$i]'\n";
1235  
1236 1 my ($old_start, $suffix) = ($1, $2);
1237 1 my ($old_count, $new_count) = (0, 0);
1238 1 my %old_line;
1239 1 my $j = $i + 1;
1240  
1241 # GNU patch mishandles hunks with more prefix than suffix context.
1242 # make the first context line an identity change without losing it.
1243 # see https://unix.stackexchange.com/questions/414542/does-patch-work-with-asymmetric-context
1244 1 ▶ splice @line, $i + 1, 1, "-$1", "+$1"
Branch: 1 branch
BranchTrueFalseTotal
if $line[$i + 1] =~ /^ (.*)\z/u 0 1 1
1245 if $line[$i + 1] =~ /^ (.*)\z/;
1246  
1247 1 ▶ for (; $j < @line; ++$j) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @line) 2 1 3
1248 2 ▶ last if $line[$j] =~ /^@@ /;
Branch: 1 branch
BranchTrueFalseTotal
if $line[$j] =~ /^\@@ /u 0 2 2
1249  
1250 2 my $tag = substr $line[$j], 0, 1;
1251  
1252 2 ▶ if ($tag eq " ") {
Branch: 4 branches
BranchTrueFalseTotal
if ($tag eq ' ') { } 0 2 2
elsif ($tag eq '-') { } 1 1 2
elsif ($tag eq '+') { } 1 0 1
elsif ($line[$j] eq '\\ No newline at end of file') { } 0 0 0
1253 0 ++$old_count;
1254 0 ++$new_count;
1255 0 $old_line{substr $line[$j], 1} = 1;
1256 } elsif ($tag eq "-") {
1257 1 ++$old_count;
1258 1 $old_line{substr $line[$j], 1} = 1;
1259 } elsif ($tag eq "+") {
1260 1 ++$new_count;
1261 } elsif ($line[$j] eq "\\ No newline at end of file") {
1262 # marker belongs to the preceding body line and counts neither side.
1263 } else {
1264 0 die "normalize_udiff: bad hunk line '$line[$j]'\n";
1265 }
1266 }
1267  
1268 1 ▶ $old_count or $new_count
Branch: 1 branch
BranchTrueFalseTotal
$old_count or $new_count or die "normalize_udiff: empty hunk at old line $old_start\n" 1 0 1
Condition33%1/3
$old_count or $new_count
l!l&&r!l&&!r
100
MC/DC0%0/2
$old_count or $new_count
$old_count $new_count
Truth table33%1/3
A or B
A= $old_countB= $new_count
ABresult
1X1
011
000
1269 or die "normalize_udiff: empty hunk at old line $old_start\n";
1270  
1271 1 ▶ $old_count or !$old_start
Branch: 1 branch
BranchTrueFalseTotal
$old_count or not $old_start or die 'normalize_udiff: hunk ' . ($hunks + 1) . " needs old-side context for insertion after old line $old_start\n" 1 0 1
Condition33%1/3
$old_count or not $old_start
l!l&&r!l&&!r
100
MC/DC0%0/2
$old_count or not $old_start
$old_count not $old_start
Truth table33%1/3
A or not(B)
A= $old_countB= not $old_start
ABresult
1X1
011
000
1272 or die "normalize_udiff: hunk " . ($hunks + 1)
1273 . " needs old-side context for insertion after old line $old_start\n";
1274  
1275 1 my $new_start = $old_start + $delta;
1276 1 ▶ ++$new_start unless $old_count;
Branch: 1 branch
BranchTrueFalseTotal
unless $old_count 0 1 1
1277 1 ▶ --$new_start unless $new_count;
Branch: 1 branch
BranchTrueFalseTotal
unless $new_count 0 1 1
1278  
1279 1 ▶ $new_start >= 0
Branch: 1 branch
BranchTrueFalseTotal
$new_start >= 0 or die "normalize_udiff: invalid new line $new_start\n" 1 0 1
1280 or die "normalize_udiff: invalid new line $new_start\n";
1281  
1282 1 $line[$i] = sprintf "@@ -%d,%d +%d,%d @@%s",
1283 $old_start, $old_count, $new_start, $new_count, $suffix;
1284  
1285 1 $delta += $new_count - $old_count;
1286 1 ++$hunks;
1287 1 my $max_offset = keys %old_line;
1288 1 ▶ --$max_offset
Branch: 1 branch
BranchTrueFalseTotal
if $max_offset 1 0 1
1289 if $max_offset;
1290 1 push @max_offset, $max_offset;
1291 1 $i = $j - 1;
1292 }
1293  
1294 1 ▶ $hunks
Branch: 1 branch
BranchTrueFalseTotal
$hunks or die "normalize_udiff: no hunks\n" 1 0 1
1295 or die "normalize_udiff: no hunks\n";
1296  
1297 1 ((join "\n", @line, ""), \@max_offset)
1298 }
1299  
1300 $toolset->tool (open =>
1301 "Load pathname into Vim buffer without selecting; reuse existing buffer without rereading. "
1302 . "Requires separate open permission. Relative paths use Vim's current directory. "
1303 . "No shell/wildcard/Ex parsing. Missing files create empty named buffers; no save. "
1304 . "Load autocommands/modelines run: may change editor or fail after side effects. "
1305 . "Returns buffer, filename, changedtick, line_count, modified.",
1306 {
1307 type => "object",
1308 properties => {
1309 target => { type => "string", description => "Vim target id." },
1310 path => { type => "string", minLength => 1, description => "File pathname, without NUL." },
1311 },
1312 required => ["target", "path"],
1313 additionalProperties => JSON::XS::false,
1314 },
1315 5 ▶ sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
1316 5 my ($req, $args) = @_;
1317  
1318 5 ▶ defined $args->{path} && !ref $args->{path} && length $args->{path} && $args->{path} !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"} and not $args->{"path"} =~ /\0/u or die "path must be a nonempty string without NUL\n" 2 3 5
Condition88%8/9
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"} and not $args->{"path"} =~ /\0/u
!ll&&!rl&&r
212
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"}
!ll&&!rl&&r
113
defined $args->{"path"} and not ref $args->{"path"}
!ll&&!rl&&r
014
MC/DC75%3/4
defined $args->{"path"} and not ref $args->{"path"} and length $args->{"path"} and not $args->{"path"} =~ /\0/u
defined $args->{"path"} not ref $args->{"path"} length $args->{"path"} not $args->{"path"} =~ /\0/u
Truth table80%4/5
A and not(B) and C and not(D)
A= defined $args->{"path"}B= not ref $args->{"path"}C= length $args->{"path"}D= not $args->{"path"} =~ /\0/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1319 or die "path must be a nonempty string without NUL\n";
1320 my $vim = $target{$args->{target}}
1321 2 ▶ or die "target does not exist: $args->{target}\n";
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$args->{"target"}} or die qq[target does not exist: $args->{"target"}\n] 2 0 2
1322  
1323 vim_permission $req, open => $args->{target}, undef, undef,
1324 2 "Open file in Vim editor '$args->{target}'\nPath: " . JSON::XS->new->allow_nonref->encode ($args->{path});
1325  
1326 1 AE::log debug => "vim open $args->{target} " . $json->encode (substr $args->{path}, 0, 80);
1327  
1328 1 $vim->rpc_ (open => $args->{path}, rpc_reply ($req));
1329 }
1330 3 );
1331  
1332 $toolset->tool (apply_diff =>
1333 "Apply relaxed unified diff to live Vim buffer; reject NUL. In @@ headers only old start (-N) matters: first hunk body line, including context; "
1334 . "other numbers ignored/recomputed (may be 0); '\@\@ -N \@\@' valid. "
1335 . "Requires current expected_changedtick and exact context (fuzz=0). Hunk relocation bounded by distinct old-side lines per hunk. Pure insertion only at buffer start; elsewhere include old-side context.",
1336 {
1337 type => "object",
1338 properties => {
1339 target => {
1340 type => "string",
1341 description => "Vim target id.",
1342 },
1343 buffer => {
1344 type => "integer",
1345 description => "Buffer id from current Vim state.",
1346 },
1347 diff => {
1348 type => "string",
1349 minLength => 1,
1350 description => "Unified diff: \@\@ old start (-N) is first hunk body line including context; other counts ignored (may be 0); \@\@ -N \@\@ valid. Pure insertion only at start; elsewhere old-side context required. Hunk relocation bound derived from distinct old-side lines.",
1351 },
1352 expected_changedtick => {
1353 type => "integer",
1354 description => "changedtick from latest state/read of this buffer.",
1355 },
1356 },
1357 required => ["target", "buffer", "diff", "expected_changedtick"],
1358 },
1359 4 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.8
1360 4 my ($req, $args) = @_;
1361  
1362 4 ▶ defined $args->{diff} && !ref $args->{diff} && $args->{diff} !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"diff"} and not ref $args->{"diff"} and not $args->{"diff"} =~ /\0/u or die "diff must be text without NUL\n" 3 1 4
Condition50%3/6
defined $args->{"diff"} and not ref $args->{"diff"} and not $args->{"diff"} =~ /\0/u
!ll&&!rl&&r
013
defined $args->{"diff"} and not ref $args->{"diff"}
!ll&&!rl&&r
004
MC/DC33%1/3
defined $args->{"diff"} and not ref $args->{"diff"} and not $args->{"diff"} =~ /\0/u
defined $args->{"diff"} not ref $args->{"diff"} not $args->{"diff"} =~ /\0/u
Truth table50%2/4
A and not(B) and not(C)
A= defined $args->{"diff"}B= not ref $args->{"diff"}C= not $args->{"diff"} =~ /\0/u
ABCresult
0XX0
10X0
1100
1111
1363 or die "diff must be text without NUL\n";
1364  
1365 3 my $buffer = $args->{buffer};
1366 vim_permission $req, write => $args->{target}, undef, {
1367 3 "View patch" => "Editor: $args->{target}\nBuffer: $buffer\n\n$args->{diff}",
1368 };
1369  
1370 1 my ($hunk, $body);
1371  
1372 1 for (split /\n/, $args->{diff}) {
1373 3 ▶ if (/^@@ /) {
Branch: 2 branches
BranchTrueFalseTotal
if (/^\@@ /u) { } 1 2 3
elsif ($hunk) { } 2 0 2
1374 1 ++$hunk;
1375 } elsif ($hunk) {
1376 2 ++$body;
1377 }
1378 }
1379  
1380 1 my @log = ($args->{target}, $args->{buffer}, $body);
1381  
1382 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1383 1 AE::log debug => join " ", "vim apply-diff", @log;
1384  
1385 $target{$args->{target}}->rpc_ (
1386 apply_patch =>
1387 $args->{buffer},
1388 (normalize_udiff $args->{diff}),
1389 1 $args->{expected_changedtick}, rpc_reply ($req)
1390 );
1391 }
1392 3 );
1393  
1394 $toolset->tool (substitute =>
1395 "Guarded Vim :substitute over live buffer range; for mechanical regex replacements. "
1396 . "Prefer apply-diff for structural/multiline edits. Native Vim regex pattern. "
1397 . "Native Vim :substitute replacement/flags. "
1398 . q{To clear the whole buffer, use range %, pattern \%^\_.*\%$, replacement empty, flags empty; Vim leaves one empty line. }
1399 . "expected_changedtick must match; otherwise stale error.",
1400 {
1401 type => "object",
1402 properties => {
1403 target => {
1404 type => "string",
1405 description => "Vim target id.",
1406 },
1407 buffer => {
1408 type => "integer",
1409 description => "Buffer id.",
1410 },
1411 range => {
1412 type => "string",
1413 description => "Restricted Vim Ex range: %, ., $, positive line numbers, +/- offsets, /regex/, ?regex?, and optional , or ; between two addresses.",
1414 },
1415 pattern => {
1416 type => "string",
1417 description => "Native Vim regex.",
1418 },
1419 replacement => {
1420 type => "string",
1421 description => "Native Vim :substitute replacement.",
1422 },
1423 flags => {
1424 type => "string",
1425 description => "Vim substitute flags; allowed: egiInp#lr.",
1426 pattern => "^[egiInp#lr]*\$",
1427 },
1428 expected_changedtick => {
1429 type => "integer",
1430 description => "changedtick from latest read/state.",
1431 },
1432 },
1433 required => [
1434 "target", "buffer", "range", "pattern", "replacement", "flags", "expected_changedtick"
1435 ],
1436 },
1437 2 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1438 2 my ($req, $args) = @_;
1439  
1440 2 vim_permission $req, write => $args->{target};
1441  
1442 my @log = (
1443 $args->{target}, $args->{buffer}, $args->{range},
1444 (substr $args->{pattern}, 0, 20),
1445 "=>",
1446 (substr $args->{replacement}, 0, 20),
1447 $args->{flags},
1448 1 );
1449  
1450 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1451 1 AE::log debug => join " ", "vim substitute", @log;
1452  
1453 $target{$args->{target}}->rpc_ (
1454 substitute => $args->{buffer}, $args->{range}, $args->{pattern},
1455 1 $args->{replacement}, $args->{flags}, $args->{expected_changedtick}, rpc_reply ($req)
1456 );
1457 }
1458 3 );
1459  
1460 3 for my $operation (qw(undo redo update)) {
1461 $toolset->tool (($operation eq "update" ? "save" : $operation) =>
1462 $operation eq "update"
1463 ? "Run Vim :update: save selected buffer to current filename only if modified. "
1464 . "Requires save permission and current expected_changedtick; no filename/force option. "
1465 . "Write autocommands run; failure may leave side effects (no rollback). "
1466 . "Returns buffer, changedtick, modified, filename. "
1467 . "Preserves caller's current buffer/view when possible."
1468 : ucfirst ($operation) . " one change in selected Vim buffer via undo tree. "
1469 . "Requires write permission and latest expected_changedtick. "
1470 . "Leaves edits unsaved; preserves caller's current buffer when editing another. "
1471 . "At history boundary: changed=false. "
1472 . "Returns buffer, changedtick, changed, seq_cur (reached undo sequence), seq_last, modified.",
1473 {
1474 type => "object",
1475 properties => {
1476 target => { type => "string", description => "Vim target id." },
1477 buffer => { type => "integer", minimum => 1, description => "Buffer id from current Vim state." },
1478 expected_changedtick => {
1479 type => "integer", minimum => 0,
1480 description => "changedtick from latest read/state of this buffer.",
1481 },
1482 },
1483 required => ["target", "buffer", "expected_changedtick"],
1484 additionalProperties => JSON::XS::false,
1485 },
1486 16 ▶ sub {
Subroutine __ANON__: called CC=10 SCAR=23.5
1487 16 my ($req, $args) = @_;
1488  
1489 16 ▶ defined $args->{buffer} && !ref $args->{buffer} && $args->{buffer} =~ /\A[1-9][0-9]*\z/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"buffer"} and not ref $args->{"buffer"} and $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u or die "buffer must be a positive integer\n" 13 3 16
Condition50%3/6
defined $args->{"buffer"} and not ref $args->{"buffer"} and $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
!ll&&!rl&&r
0313
defined $args->{"buffer"} and not ref $args->{"buffer"}
!ll&&!rl&&r
0016
MC/DC33%1/3
defined $args->{"buffer"} and not ref $args->{"buffer"} and $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
defined $args->{"buffer"} not ref $args->{"buffer"} $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
Truth table50%2/4
A and not(B) and C
A= defined $args->{"buffer"}B= not ref $args->{"buffer"}C= $args->{"buffer"} =~ /\A[1-9][0-9]*\z/u
ABCresult
0XX0
10X0
1100
1111
1490 or die "buffer must be a positive integer\n";
1491 defined $args->{expected_changedtick} && !ref $args->{expected_changedtick}
1492 13 ▶ && $args->{expected_changedtick} =~ /\A[0-9]+\z/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"} and $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u or die "expected_changedtick must be a nonnegative integer\n" 7 6 13
Condition83%5/6
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"} and $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
!ll&&!rl&&r
337
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"}
!ll&&!rl&&r
3010
MC/DC66%2/3
defined $args->{"expected_changedtick"} and not ref $args->{"expected_changedtick"} and $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
defined $args->{"expected_changedtick"} not ref $args->{"expected_changedtick"} $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
Truth table75%3/4
A and not(B) and C
A= defined $args->{"expected_changedtick"}B= not ref $args->{"expected_changedtick"}C= $args->{"expected_changedtick"} =~ /\A[0-9]+\z/u
ABCresult
0XX0
10X0
1100
1111
1493 or die "expected_changedtick must be a nonnegative integer\n";
1494  
1495 my $vim = $target{$args->{target}}
1496 7 ▶ or die "target does not exist: $args->{target}\n";
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$args->{"target"}} or die qq[target does not exist: $args->{"target"}\n] 7 0 7
1497  
1498 7 ▶ vim_permission $req, ($operation eq "update" ? "save" : "write") => $args->{target};
Branch: 1 branch
BranchTrueFalseTotal
$operation eq 'update' ? : 3 4 7
1499  
1500 AE::log debug => join " ", "vim", ($operation eq "update" ? "save" : $operation),
1501 4 ▶ $args->{target}, $args->{buffer};
Branch: 1 branch
BranchTrueFalseTotal
$operation eq 'update' ? : 2 2 4
1502 4 $vim->rpc_ ($operation => 0 + $args->{buffer}, 0 + $args->{expected_changedtick}, rpc_reply ($req));
1503 }
1504 9 ▶ );
Branch: 2 branches
BranchTrueFalseTotal
$operation eq 'update' ? : 3 6 9
$operation eq 'update' ? : 3 6 9
1505 }
1506  
1507 $toolset->tool (set_cursor =>
1508 "Show/select buffer and position Vim cursor. Unlike read/edit, intentionally changes user's "
1509 . "editor position. Optional expected_changedtick rejects stale buffer. "
1510 . "After edits in user's current buffer, move cursor to changed region so user sees it. "
1511 . "Avoid cursor movement for exploratory reads/searches unless useful.",
1512 {
1513 type => "object",
1514 properties => {
1515 target => {
1516 type => "string",
1517 description => "Vim target id.",
1518 },
1519 buffer => {
1520 type => "integer",
1521 description => "Buffer id.",
1522 },
1523 line => {
1524 type => "integer",
1525 minimum => 1,
1526 description => "1-based line.",
1527 },
1528 column => {
1529 type => "integer",
1530 minimum => 1,
1531 description => "1-based byte column as used by Vim col().",
1532 },
1533 expected_changedtick => {
1534 type => "integer",
1535 description => "Optional buffer changedtick guard.",
1536 },
1537 },
1538 required => ["target", "buffer", "line", "column"],
1539 },
1540 3 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1541 3 my ($req, $args) = @_;
1542  
1543 3 vim_permission $req, write => $args->{target};
1544  
1545 2 my @log = ($args->{target}, $args->{buffer}, $args->{line}, $args->{column});
1546  
1547 # keep log values copied: stringifying request scalars can change JSON::XS number/string encoding.
1548 2 AE::log debug => join " ", "vim set-cursor", @log;
1549  
1550 $target{$args->{target}}->rpc_ (
1551 2 ▶ set_cursor => @{$args}{qw(buffer line column)},
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{'expected_changedtick'} ? : 1 1 2
1552 2 (exists $args->{expected_changedtick} ? $args->{expected_changedtick} : ()), rpc_reply ($req)
1553 );
1554 }
1555 3 );
1556  
1557 $toolset->tool (ex =>
1558 "Execute unrestricted Vim Ex in current editor context; needs separate exec permission. "
1559 . "Can run shell, read/write files, invoke code, exit Vim with user's privileges. "
1560 . "Prefer dedicated read/edit/navigation tools. "
1561 . "command: Ex text, including separators/newlines; keep reviewable. "
1562 . "Optional buffer becomes current; expected_changedtick requires buffer, checked just before execution. "
1563 . "Persistent grants may cover exact command, any command in this editor, or all editors. "
1564 . "Returns {output: Vim messages} or Vim error; no rollback of earlier effects. "
1565 . "Use noninteractive commands; prompts/long runs block Vim; cancellation cannot undo execution.",
1566 {
1567 type => "object",
1568 properties => {
1569 target => { type => "string", description => "Vim target id." },
1570 command => { type => "string", minLength => 1, description => "Unrestricted Ex command text, without NUL." },
1571 buffer => { type => "integer", minimum => 1, description => "Optional buffer to make current before execution." },
1572 expected_changedtick => {
1573 type => "integer", minimum => 0,
1574 description => "Optional changedtick guard for buffer; requires buffer. A stale tick prevents execution.",
1575 },
1576 },
1577 required => ["target", "command"],
1578 },
1579 18 ▶ sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
1580 18 my ($req, $args) = @_;
1581  
1582 18 my $command = $args->{command};
1583 18 ▶ defined $command && !ref $command && length $command && $command !~ /\0/
Branch: 1 branch
BranchTrueFalseTotal
defined $command and not ref $command and length $command and not $command =~ /\0/u or die "command must be a nonempty string without NUL\n" 15 3 18
Condition88%8/9
defined $command and not ref $command and length $command and not $command =~ /\0/u
!ll&&!rl&&r
2115
defined $command and not ref $command and length $command
!ll&&!rl&&r
1116
defined $command and not ref $command
!ll&&!rl&&r
0117
MC/DC75%3/4
defined $command and not ref $command and length $command and not $command =~ /\0/u
defined $command not ref $command length $command not $command =~ /\0/u
Truth table80%4/5
A and not(B) and C and not(D)
A= defined $commandB= not ref $commandC= length $commandD= not $command =~ /\0/u
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1584 or die "command must be a nonempty string without NUL\n";
1585  
1586 !exists $args->{expected_changedtick} || exists $args->{buffer}
1587 15 ▶ or die "expected_changedtick requires buffer\n";
Branch: 1 branch
BranchTrueFalseTotal
not exists $args->{"expected_changedtick"} or exists $args->{"buffer"} or die "expected_changedtick requires buffer\n" 14 1 15
Condition100%3/3
not exists $args->{"expected_changedtick"} or exists $args->{"buffer"}
l!l&&r!l&&!r
1311
MC/DC100%2/2
not exists $args->{"expected_changedtick"} or exists $args->{"buffer"}
not exists $args->{"expected_changedtick"} exists $args->{"buffer"}
Truth table100%3/3
not(A) or B
A= not exists $args->{"expected_changedtick"}B= exists $args->{"buffer"}
ABresult
1X1
011
000
1588  
1589 my $vim = $target{$args->{target}}
1590 14 ▶ or die "target does not exist: $args->{target}\n";
Branch: 1 branch
BranchTrueFalseTotal
my $vim = $target{$args->{"target"}} or die qq[target does not exist: $args->{"target"}\n] 14 0 14
1591  
1592 14 vim_permission $req, exec => $args->{target}, $command;
1593  
1594 4 $vim->rpc_ (ex => $command, @{$args}{qw(buffer expected_changedtick)}, rpc_reply ($req));
1595 }
1596 3 );
1597  
1598 3 mcp_tool_help ($server_options->{tool_help}, $toolset);
1599  
1600 3 my $instructions = <<'EOF';
1601 Live Vim buffers, not disk snapshots. Use targets for editors, state for buffer IDs/changedticks.
1602 Read via read-lines/grep; explicit access may load unloaded buffers.
1603 open loads pathname without selecting; requires separate open permission.
1604 apply-diff/substitute/undo/redo modify live buffers; require current expected_changedtick; leave unsaved.
1605 save writes current filename only if modified; needs save permission and current expected_changedtick.
1606 set-cursor moves visible editor cursor; use to show edits or navigate.
1607 ex runs unrestricted Ex with full Vim privileges; requires separate exec permission. Prefer narrow tools.
1608 EOF
1609  
1610 my $custom_instructions = $server_options->{custom_instructions}
1611 // $config->{section}{"instance $name"}{custom_instructions}
1612 3 ▶ // $config->{section}{"program " . AnyEvent::MCP::Config::program_name ()}{custom_instructions};
Condition33%2/6
($server_options->{"custom_instructions"} // $config->{"section"}{"instance $name"}{"custom_instructions"}) // $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
l!l&&r!l&&!r
003
$server_options->{"custom_instructions"} // $config->{"section"}{"instance $name"}{"custom_instructions"}
l!l&&r!l&&!r
003
MC/DC0%0/3
($server_options->{"custom_instructions"} // $config->{"section"}{"instance $name"}{"custom_instructions"}) // $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
$server_options->{"custom_instructions"} $config->{"section"}{"instance $name"}{"custom_instructions"} $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
Truth table25%1/4
A // B // C
A= $server_options->{"custom_instructions"}B= $config->{"section"}{"instance $name"}{"custom_instructions"}C= $config->{"section"}{'program ' . AnyEvent::MCP::Config::program_name()}{"custom_instructions"}
ABCresult
1XX1
01X1
0011
0000
1613 3 ▶my %guidance = (
Branch: 1 branch
BranchTrueFalseTotal
defined $custom_instructions ? : 0 3 3
1614 instructions => $instructions,
1615 short_instructions => "Live Vim buffers: inspect, edit with changedtick guards (unsaved), navigate. Discover tools.",
1616 auto_instructions => 1,
1617 on_request => \&mcp_log_request,
1618 (defined $custom_instructions ? (custom_instructions => $custom_instructions) : ()),
1619 );
1620  
1621 my $mcp = AnyEvent::MCP::Server::HTTP->new (
1622 server_info => { name => "mcp-vim", version => "0" },
1623 %guidance,
1624 toolsets => [$toolset],
1625 permissions => $permissions,
1626 path => "/",
1627 tokens => \@accepted_tokens,
1628 token_users => $http{token_users},
1629 3 max_size => 100e6,
1630 origins => ["*"],
1631 connection_close => 1,
1632 );
1633  
1634 3 my $done = AE::cv;
1635 3 my $stdio_mcp;
1636  
1637 3 ▶if (defined $connect) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $connect) { } 0 3 3
elsif ($stdio) { } 3 0 3
1638 0 require AnyEvent::MCP::Server::Connect;
1639 $stdio_mcp = AnyEvent::MCP::Server::Connect->new (
1640 server_info => $mcp->{server_info},
1641 %guidance,
1642 toolsets => [$toolset],
1643 permissions => $permissions,
1644 max_size => 100e6,
1645 connect => $connect,
1646 0 ▶ on_close => sub { $done->send },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1647 0 );
1648 0 $stdio_mcp->start;
1649 } elsif ($stdio) {
1650 3 require AnyEvent::MCP::Server::JSONL;
1651  
1652 3 binmode STDIN;
1653 3 binmode STDOUT;
1654  
1655 $stdio_mcp = AnyEvent::MCP::Server::JSONL->new (
1656 server_info => $mcp->{server_info},
1657 %guidance,
1658 toolsets => [$toolset],
1659 permissions => $permissions,
1660 max_size => 100e6,
1661 3 ▶ on_connection_close => sub { $done->send },
Subroutine __ANON__: called CC=1 SCAR=0.0
1662 3 );
1663  
1664 3 $stdio_mcp->accept (\*STDIN, \*STDOUT);
1665 }
1666  
1667 #############################################################################
1668  
1669 3 ▶sub accept_json {
Subroutine accept_json: called CC=1 SCAR=1.9
1670 3 my ($fh) = @_;
1671  
1672 my $hdl = AnyEvent::Handle->new (
1673 fh => $fh,
1674 0 ▶ on_error => sub { $_[0]->destroy },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1675 0 ▶ on_eof => sub { $_[0]->destroy },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1676 3 );
1677  
1678 2 ▶ AnyEvent::MCP::Extension::accept ($hdl, \@connect_tokens, sub {
Subroutine __ANON__: called CC=15 SCAR=42.0
1679 2 my ($hdl, $hello) = @_;
1680  
1681 2 ▶ @$hello == 6 && $hello->[0] eq "mcp-vim"
Branch: 1 branch
BranchTrueFalseTotal
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5] and not ref $hello->[5] or die "Invalid private Vim hello\n" 2 0 2
Condition33%13/39
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5] and not ref $hello->[5]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2]
!ll&&!rl&&r
002
@$hello == 6 and $hello->[0] eq "mcp-vim"
!ll&&!rl&&r
002
MC/DC0%0/14
@$hello == 6 and $hello->[0] eq "mcp-vim" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[0-9]+\z/u and defined $hello->[3] and not ref $hello->[3] and $hello->[3] =~ /\A[0-9]+\z/u and $hello->[2] == $vim_prot_major and $hello->[3] <= $vim_prot_minor and defined $hello->[4] and not ref $hello->[4] and defined $hello->[5] and not ref $hello->[5]
@$hello == 6 $hello->[0] eq "mcp-vim" defined $hello->[2] not ref $hello->[2] $hello->[2] =~ /\A[0-9]+\z/u defined $hello->[3] not ref $hello->[3] $hello->[3] =~ /\A[0-9]+\z/u $hello->[2] == $vim_prot_major $hello->[3] <= $vim_prot_minor defined $hello->[4] not ref $hello->[4] defined $hello->[5] not ref $hello->[5]
Truth table6%1/15
A and B and C and not(D) and E and F and not(G) and H and I and J and K and not(L) and M and not(N)
A= @$hello == 6B= $hello->[0] eq "mcp-vim"C= defined $hello->[2]D= not ref $hello->[2]E= $hello->[2] =~ /\A[0-9]+\z/uF= defined $hello->[3]G= not ref $hello->[3]H= $hello->[3] =~ /\A[0-9]+\z/uI= $hello->[2] == $vim_prot_majorJ= $hello->[3] <= $vim_prot_minorK= defined $hello->[4]L= not ref $hello->[4]M= defined $hello->[5]N= not ref $hello->[5]
ABCDEFGHIJKLMNresult
0XXXXXXXXXXXXX0
10XXXXXXXXXXXX0
110XXXXXXXXXXX0
1110XXXXXXXXXX0
11110XXXXXXXXX0
111110XXXXXXXX0
1111110XXXXXXX0
11111110XXXXXX0
111111110XXXXX0
1111111110XXXX0
11111111110XXX0
111111111110XX0
1111111111110X0
111111111111100
111111111111111
1682 && defined $hello->[2] && !ref $hello->[2] && $hello->[2] =~ /\A[0-9]+\z/
1683 && defined $hello->[3] && !ref $hello->[3] && $hello->[3] =~ /\A[0-9]+\z/
1684 && $hello->[2] == $vim_prot_major && $hello->[3] <= $vim_prot_minor
1685 && defined $hello->[4] && !ref $hello->[4]
1686 && defined $hello->[5] && !ref $hello->[5]
1687 or die "Invalid private Vim hello\n";
1688  
1689 2 vim->new ($hdl, $hello);
1690 3 });
1691 }
1692  
1693 #############################################################################
1694  
1695 3 ▶sub accept_ws {
Subroutine accept_ws: called CC=2 SCAR=6.9
1696 3 my ($fh, $peer_host, $peer_port) = @_;
1697  
1698 3 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require AnyEvent::WebSocket::Server; require AnyEvent::WebSocket::Message; 1 } } or return &AE::log("warn", "WebSocket support unavailable: $@") 3 0 3
1699 3 require AnyEvent::WebSocket::Server;
1700 3 require AnyEvent::WebSocket::Message;
1701 3 1
1702 } or return AE::log warn => "WebSocket support unavailable: $@";
1703  
1704 # tcp_server has already formatted the numeric address for us.
1705 3 my $peer = AnyEvent::Socket::format_hostport $peer_host, $peer_port;
1706  
1707 3 my ($origin, $rejection);
1708  
1709 my $ws_server = new AnyEvent::WebSocket::Server
1710 max_payload_size => 1000e6,
1711 3 ▶ handshake => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1712 3 my ($req, $res) = @_;
1713  
1714 3 my ($cookie, $target) = $req->{resource_name} =~ m%^/([^/]+)/+(.+)\z%s;
1715 3 ▶ unless (defined $cookie && $connect_token{$cookie}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cookie and $connect_token{$cookie}) 2 1 3
Condition100%3/3
defined $cookie and $connect_token{$cookie}
!ll&&!rl&&r
111
MC/DC100%2/2
defined $cookie and $connect_token{$cookie}
defined $cookie $connect_token{$cookie}
Truth table100%3/3
A and B
A= defined $cookieB= $connect_token{$cookie}
ABresult
0X0
100
111
1716 2 ▶ $rejection = defined $cookie ? "invalid token" : "invalid path";
Branch: 1 branch
BranchTrueFalseTotal
defined $cookie ? : 1 1 2
1717 2 die "Vim WebSocket handshake rejected\n";
1718 }
1719  
1720 1 $origin = $target;
1721  
1722 1 AE::log info => "websocket connect for $origin";
1723 #$res->subprotocol ($prot);
1724  
1725 #$res->{subprotocol}
1726 # or return AE::log info => "no matching subprotocol";
1727  
1728 1 $res
1729 },
1730 3 ;
1731  
1732 3 ▶ $ws_server->establish ($fh)->cb (sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
1733 3 ▶ if (my $conn = eval { $_[0]->recv }) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $conn = eval { do { $_[0]->recv } }) { } 1 2 3
elsif ($rejection) { } 2 0 2
1734 1 xpcse->new ({ conn => $conn, origin => $origin });
1735 } elsif ($rejection) {
1736 2 AE::log warn => "Vim WebSocket rejected: $rejection ($peer)";
1737 } else {
1738 0 AE::log warn => "Vim WebSocket establishment failed from $peer: $@";
1739 }
1740 3 });
1741 }
1742  
1743 #############################################################################
1744  
1745 11 ▶AnyEvent::Socket::tcp_server $host, $PORT, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1746 11 ▶ my ($fh, $peer_host, $peer_port) = @_
Branch: 1 branch
BranchTrueFalseTotal
my($fh, $peer_host, $peer_port) = or return 11 0 11
1747 or return;
1748  
1749 11 ▶ my $watcher; $watcher = AE::io $fh, 0, sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
1750 11 undef $watcher;
1751  
1752 11 ▶ defined recv $fh, my $magic, 1, Socket::MSG_PEEK
Branch: 1 branch
BranchTrueFalseTotal
defined recv($fh, my $magic, 1, 2) or return 11 0 11
1753 or return;
1754  
1755 11 ▶ if ($magic eq "[") { # json
Branch: 3 branches
BranchTrueFalseTotal
if ($magic eq '[') { } 3 8 11
elsif ($magic eq 'P' or $magic eq 'O') { } 4 4 8
elsif ($magic eq 'G') { } 3 1 4
1756 3 accept_json $fh;
1757 ▶ } elsif ($magic eq "P" or $magic eq "O") { # HTTP POST/OPTIONS / MCP JSON-RPC 2.0
Condition66%2/3
$magic eq "P" or $magic eq "O"
l!l&&r!l&&!r
404
MC/DC50%1/2
$magic eq "P" or $magic eq "O"
$magic eq "P" $magic eq "O"
Truth table66%2/3
A or B
A= $magic eq "P"B= $magic eq "O"
ABresult
1X1
011
000
1758 4 $mcp->accept ($fh);
1759 } elsif ($magic eq "G") {
1760 3 accept_ws $fh, $peer_host, $peer_port;
1761 }
1762 11 };
1763 3 };
1764  
1765 3 $done->recv;
1766  
« blib/lib/AnyEvent/MCP/Extension.pm ↑ Summary blib/lib/AnyEvent/MCP/Server/Connect.pm »