Nushell
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
  • 한국어
GitHub
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
  • 한국어
GitHub
  • Contributor Book
    • Introduction
    • Philosophy
    • Philosophy (0.80)
    • Commands
    • Plugins
    • Plugin protocol reference

Plugin protocol reference

How Nu runs plugins

Nu plugins must be an executable file with a filename starting with nu_plugin_. Plugins can run in one of two modes:

  1. Stdio mode, which must be supported. The plugin is passed --stdio as a command line argument. All interaction with the plugin is handled over standard input (stdin) and output (stdout). Standard error (stderr) is not redirected, and can be used by the plugin to print messages directly.

  2. Local socket mode, which may be supported (advertised via the LocalSocket feature). The plugin is passed --local-socket as the first command line argument, and then the path of the Unix domain socket or name of the Windows named pipe to use for communication. None of the standard input or output streams are redirected, and they may all be used to interact with the user's terminal. See the documentation specific to the feature for more details.

Other command line arguments are reserved for options that might be added in the future, including other communication methods. Plugins that support the protocol as described in this document should reject other arguments and print an informational message to stderr.

Immediately after spawning a plugin, Nu expects the plugin to send its encoding type. Currently two encoding types are supported: json and msgpack. The desired encoding type should be sent first with the length of the string as a single byte integer and then the encoding type string. That is, with C-like escape syntax, "\x04json" or "\x07msgpack". In this document, the JSON format will be used for readability, but the MessagePack format is largely equivalent. See the Encoding section for specific intricacies of the formats.

Nu will then send messages in the desired encoding. The first message is always Hello. The plugin must send a Hello message indicating the expected Nu version that it is compatible with, and any supported protocol features. The engine will also send a Hello message with its version, and any supported protocol features. The plugin may verify that it is compatible with the Nu version provided by the engine, but the engine will end communication with a plugin if it is determined to be unsupported. The plugin must not use protocol features it supports if they are not also confirmed to be supported by the engine in its Hello message. It is not permitted to send any other messages before sending Hello.

The plugin should then receive and respond to messages until its input stream is closed.

Typical plugin interaction after the initial handshake looks like this:

  1. The engine sends a Call. The call contains an ID used to identify the response.
  2. If the input of the call specified a stream, the engine will send stream messages. These do not need to be consumed before the plugin sends its response.
  3. The plugin sends a CallResponse, with the same ID from step 1.
  4. If the plugin specified stream data as output in the response, it should now send stream messages with the corresponding stream ID(s).

The plugin should respond to further plugin calls. The engine may send additional plugin calls before responses have been received, and it is up to the plugin to decide whether to handle each call immediately as it is received, or to process only one at a time and hold on to them for later. In any case, sending another plugin call before a response has been received should not cause an error.

The plugin may send engine calls during the execution of a call to request operations from the engine. Engine calls are only valid within the context of a call and may not be sent otherwise.

The engine may send a Goodbye message to the plugin indicating that it will no longer send any more plugin calls. Upon receiving this message, the plugin may choose not to accept any more plugin calls, and should exit after any in-progress plugin calls have finished.

Note: During the sequence, the engine may also send a Signal message asynchronously, such as when an interrupt (Ctrl+C) or reset signal is triggered. Plugins should handle these messages as they are received, for example, by pausing or stopping operations when an Interrupt signal is sent.

Hello

After the encoding type has been decided, both the engine and plugin must send a Hello message containing relevant version and protocol support information.

FieldTypeDescription
protocolstringMust be "nu-plugin".
versionstringThe engine's version, or the target version of Nu that the plugin supports.
featuresarrayProtocol features supported by the plugin. Unrecognized elements must be ignored.

To be accepted, the version specified must be semver compatible with the engine's version. "0.x.y" and "x.y.z" for differing values of "x" are considered to be incompatible. More precisely, the higher of the two versions must match a caret requirement on the lower one (for example, 0.116.2 matches ^0.116.0, but 0.117.0 does not). Pre-release suffixes such as -nightly.3 are ignored. If the versions are incompatible, the engine refuses to load the plugin.

Plugins may decide to refuse engine versions with more strict criteria than specified here.

Example:

{
  "Hello": {
    "protocol": "nu-plugin",
    "version": "0.116.0",
    "features": []
  }
}

Features

All features are maps that must contain at least a name key, and may contain other keys. Features that are not recognized by name must be ignored, and not cause an error. Plugins must only advertise support for features they implement, and should not determine the features they will advertise depending on the engine's Hello message.

LocalSocket feature

This feature advertises support for local socket communication, instead of stdio.

Example:

{
  "name": "LocalSocket"
}

When local socket communication is advertised to an engine supporting the feature, the engine will send Goodbye, cease stdio communication, and launch the plugin again with the --local-socket command line argument. The second argument is either a path to a Unix domain socket on Linux, Android, macOS, and other Unix-like operating systems, or the name of a named pipe (without the \\.\pipe\ prefix) on Windows.

In either case, during startup, the plugin is expected to establish two separate connections to the socket, in this order:

  1. The input stream connection, used to send messages from the engine to the plugin
  2. The output stream connection, used to send messages from the plugin to the engine

The connections are separate in order to facilitate ownership of the streams by separate threads. After these connections are both established, the engine will remove the socket, and will not accept further connections.

If local socket communication fails to initialize, the engine will abort, stop the plugin, and start it again with the stdio mode, even if the plugin supports local sockets. Whether local socket mode initialized successfully, and therefore the plugin is allowed to use stdio, can be observed when EngineInterface::is_using_stdio() returns false for Rust plugins.

Input messages

These are messages sent from the engine to the plugin. Hello and Stream messages are also included.

Call

The body of this message is a 2-tuple (array): (id, call). The engine sends unique IDs for each plugin call it makes. The ID is needed to send the CallResponse.

Metadata plugin call

Ask the plugin to send metadata about itself. Takes no arguments. Returns Metadata or Error

Example:

{
  "Call": [0, "Metadata"]
}

Signature plugin call

Ask the plugin to send its command signatures. Takes no arguments. Returns Signature or Error

Example:

{
  "Call": [0, "Signature"]
}

Run plugin call

Tell the plugin to run a command. The argument is the following map:

FieldTypeDescription
namestringThe name of the command to run
callEvaluatedCallInformation about the invocation, including arguments
inputPipelineDataHeaderPipeline input to the command

EvaluatedCall is a map:

FieldTypeDescription
headSpanThe position of the beginning of the command execution.
positionalValue arrayPositional arguments.
named2-tuple (spanned string, Value or null) arrayNamed arguments, such as switches.

The name of each named argument is a map with an item (the name) and a span (the position of the flag in the source). Named arguments are always sent by their long name, never their short name. A switch given without a value (e.g. --major) has a null value, but one given an explicit value (e.g. --major=false) has a Bool value. Switches that weren't given are not sent.

Returns PipelineData or Error.

Example:

"0.1.2" | inc --major
{
  "Call": [
    2,
    {
      "Run": {
        "name": "inc",
        "call": {
          "head": {
            "start": 169342,
            "end": 169345
          },
          "positional": [],
          "named": [
            [
              {
                "item": "major",
                "span": {
                  "start": 169346,
                  "end": 169353
                }
              },
              null
            ]
          ]
        },
        "input": {
          "Value": [
            {
              "String": {
                "val": "0.1.2",
                "span": {
                  "start": 169332,
                  "end": 169339
                }
              }
            },
            null
          ]
        }
      }
    }
  ]
}

GetCompletion plugin call

Ask the plugin for completion suggestions for an argument of one of its commands. The engine sends this call when the user asks for completions while typing an argument of a plugin command. This call is experimental, and its format is likely to change. The argument is the following map:

FieldTypeDescription
namestringThe name of the command being completed.
arg_typemapEither {"Flag": "<long name>"} or {"Positional": <index>}.
callmapInformation about the command call as parsed so far. See below.

call contains the following fields:

FieldTypeDescription
callmapThe parsed call (ast::Call), with unevaluated arguments. This is an internal Nu type.
stripbooleanWhether there is a placeholder in the input buffer.
posunsigned integerThe position of the cursor, in the same coordinates as spans, which can be used to find the placeholder in the arguments.

The inner call is a map:

FieldTypeDescription
decl_idunsigned integerThe declaration ID of the command.
headSpanThe span of the command name.
argumentsarrayOne entry for each argument typed so far, in order.
parser_infomapExtra expressions the parser stores for some built-in commands. Empty for plugins.

Each entry of arguments is a map with one key:

  • {"Positional": expression}: a positional argument.
  • {"Named": [name, short, expression]}: a flag. name is the long name as a spanned string (item and span), even when the user typed the short form. short is a spanned string or null, and expression is null for a switch or a flag whose value hasn't been typed yet.
  • {"Unknown": expression}: an argument that a signature with allows_unknown_args passes through.
  • {"Spread": expression}: a spread list, such as ...$args, filling rest arguments.

An Expression, the parser's representation of the source code, is a map with the fields expr, span, span_id, and ty. ty is the type the parser inferred, in the same form as in signatures. expr, the expression itself, is an externally tagged enum with dozens of variants, defined by ast::Expr. Literals are the easiest to use: {"Int": 3}, {"Float": 1.5}, {"Bool": true}, {"String": "va"}, and {"Filepath": ["./x", false]}, where the boolean is true for a quoted path. Other expressions, such as {"Var": 74} for a variable or {"Subexpression": 12}, can't be evaluated during a completion call. If the cursor is on an argument the user hasn't started typing, arguments has no entry for it.

For example, take a command probe args with a --sw switch, a --num (-n) flag that takes an integer, and an optional positional argument. After the user types probe args --sw -n 3 and presses Tab, the engine asks for {"Positional": 0}, and arguments holds only the two flags:

[
  {
    "Named": [
      { "item": "sw", "span": { "start": 170715, "end": 170719 } },
      null,
      null
    ]
  },
  {
    "Named": [
      { "item": "num", "span": { "start": 170720, "end": 170722 } },
      null,
      {
        "expr": { "Int": 3 },
        "span": { "start": 170723, "end": 170724 },
        "span_id": 4932,
        "ty": "Int"
      }
    ]
  }
]

The plugin can make engine calls in the context of this call, but only the ones that don't change state or run code: GetConfig, GetPluginConfig, GetEnvVar, GetEnvVars, GetCurrentDir, GetHelp and GetSpanContents.

Returns CompletionItems or Error.

Example, for a plugin command spy with a --named flag, after the user typed spy --named and pressed Tab:

{
  "Call": [
    2,
    {
      "GetCompletion": {
        "name": "spy",
        "arg_type": {
          "Flag": "named"
        },
        "call": {
          "call": {
            "decl_id": 548,
            "head": {
              "start": 169438,
              "end": 169441
            },
            "arguments": [
              {
                "Named": [
                  {
                    "item": "named",
                    "span": {
                      "start": 169442,
                      "end": 169449
                    }
                  },
                  null,
                  null
                ]
              }
            ],
            "parser_info": {}
          },
          "strip": false,
          "pos": 169450
        }
      }
    }
  ]
}

CustomValueOp plugin call

Perform an operation on a custom value received from the plugin. The argument is a 2-tuple (array): (custom_value, op).

The custom value is specified in spanned format, as a PluginCustomValue without the type field, and not as a Value - see the examples.

In the examples below, $version is a variable holding a custom value named version that one of the plugin's commands returned earlier, so the Nu code only works with such a plugin loaded.

ToBaseValue

Returns a plain value that is representative of the custom value, or an error if this is not possible. Sending a custom value back for this operation is not allowed. The response type is PipelineData or Error. If the operation produces a stream, it will be consumed to a value.

Example:

{
  "Call": [
    0,
    {
      "CustomValueOp": [
        {
          "item": {
            "name": "version",
            "data": [0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0]
          },
          "span": {
            "start": 90,
            "end": 96
          }
        },
        "ToBaseValue"
      ]
    }
  ]
}
FollowPathInt

Returns the result of following a numeric cell path (e.g. $custom_value.0) on the custom value. This is most commonly used with custom types that act like lists or tables. The argument is a map:

FieldTypeDescription
indexspanned unsigned integerThe index to follow, as a map with item and span.
optionalbooleantrue if the path member was optional (.0?), in which case a missing index should produce Nothing instead of an error.

The response type is PipelineData or Error. The result may be another custom value. If the operation produces a stream, it will be consumed to a value.

Example:

$version.0
{
  "Call": [
    0,
    {
      "CustomValueOp": [
        {
          "item": {
            "name": "version",
            "data": [0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0]
          },
          "span": {
            "start": 90,
            "end": 96
          }
        },
        {
          "FollowPathInt": {
            "index": {
              "item": 0,
              "span": {
                "start": 320,
                "end": 321
              }
            },
            "optional": false
          }
        }
      ]
    }
  ]
}
FollowPathString

Returns the result of following a string cell path (e.g. $custom_value.field) on the custom value. This is most commonly used with custom types that act like lists or tables. The argument is a map:

FieldTypeDescription
column_namespanned stringThe column name to follow, as a map with item and span.
optionalbooleantrue if the path member was optional (.field?), in which case a missing column should produce Nothing instead of an error.
casingstring"Sensitive", or "Insensitive" if the path member was marked case-insensitive (.field!).

The response type is PipelineData or Error. The result may be another custom value. If the operation produces a stream, it will be consumed to a value.

Example:

$version.field
{
  "Call": [
    0,
    {
      "CustomValueOp": [
        {
          "item": {
            "name": "version",
            "data": [0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0]
          },
          "span": {
            "start": 90,
            "end": 96
          }
        },
        {
          "FollowPathString": {
            "column_name": {
              "item": "field",
              "span": {
                "start": 320,
                "end": 326
              }
            },
            "optional": false,
            "casing": "Sensitive"
          }
        }
      ]
    }
  ]
}
PartialCmp

Compares the custom value to another value and returns the Ordering that should be used, if any. This is used to order values, for example when sorting; comparison operators such as < are sent as an Operation instead. The argument type is a Value, which may be any value - not just the same custom value type. The response type is Ordering. Error may also be returned, but at present the error is unlikely to be presented to the user - the engine will act as if you had sent {"Ordering": null}.

Example (comparing two version custom values):

{
  "Call": [
    0,
    {
      "CustomValueOp": [
        {
          "item": {
            "name": "version",
            "data": [0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0]
          },
          "span": {
            "start": 90,
            "end": 96
          }
        },
        {
          "PartialCmp": {
            "Custom": {
              "val": {
                "type": "PluginCustomValue",
                "name": "version",
                "data": [0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0]
              },
              "span": {
                "start": 560,
                "end": 566
              }
            }
          }
        }
      ]
    }
  ]
}
Operation

Returns the result of evaluating an Operator on this custom value with another value. The argument is a 2-tuple: (operator, value), where operator is a spanned Operator and value is a Value, which may be any value - not just the same custom value type. The response type is PipelineData or Error. The result may be another custom value. If the operation produces a stream, it will be consumed to a value.

Example:

$version + 7
{
  "Call": [
    0,
    {
      "CustomValueOp": [
        {
          "item": {
            "name": "version",
            "data": [0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0]
          },
          "span": {
            "start": 90,
            "end": 96
          }
        },
        {
          "Operation": [
            {
              "item": {
                "Math": "Add"
              },
              "span": {
                "start": 180,
                "end": 181
              }
            },
            {
              "Int": {
                "val": 7,
                "span": {
                  "start": 183,
                  "end": 184
                }
              }
            }
          ]
        }
      ]
    }
  ]
}
Save

Saves the custom value to a file when it is piped to the save command, unless save first converts it based on the file extension (e.g. with to json for a .json file). The argument is a map:

FieldTypeDescription
pathspanned stringThe absolute path to save to, as a map with item and span.
save_call_spanSpanThe span of the save command call, useful for error messages.

The response type is Ok if the value was saved, or Error.

Example:

$version | save version.bin
{
  "Call": [
    0,
    {
      "CustomValueOp": [
        {
          "item": {
            "name": "version",
            "data": [0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0]
          },
          "span": {
            "start": 90,
            "end": 96
          }
        },
        {
          "Save": {
            "path": {
              "item": "/home/user/version.bin",
              "span": {
                "start": 104,
                "end": 115
              }
            },
            "save_call_span": {
              "start": 99,
              "end": 103
            }
          }
        }
      ]
    }
  ]
}
Dropped

This op is used to notify the plugin that a PluginCustomValue that had notify_on_drop set to true was dropped in the engine - i.e., all copies of it have gone out of scope. For more information on exactly under what circumstances this is sent, see the drop notification section of the plugin reference. The response type is Empty pipeline data or Error. The span sent with the custom value is always zero, as there is no source code associated with the drop.

Example:

{
  "Call": [
    0,
    {
      "CustomValueOp": [
        {
          "item": {
            "name": "handle",
            "data": [78, 60],
            "notify_on_drop": true
          },
          "span": {
            "start": 0,
            "end": 0
          }
        },
        "Dropped"
      ]
    }
  ]
}

EngineCallResponse

A response to an engine call made by the plugin. The argument is a 2-tuple (array): (engine_call_id, response)

The engine_call_id refers to the same number that the engine call being responded to originally contained. The plugin must send unique IDs for each engine call it makes. Like CallResponse, there are multiple types of responses:

Error engine call response

A failure result. Contains a LabeledError.

Example:

{
  "EngineCallResponse": [
    0,
    {
      "Error": {
        "msg": "The connection closed.",
        "labels": [],
        "code": null,
        "url": null,
        "help": null,
        "inner": []
      }
    }
  ]
}

PipelineData engine call response

A successful result with a Nu Value or stream. The body is a PipelineDataHeader.

Example:

{
  "EngineCallResponse": [
    0,
    {
      "PipelineData": {
        "ListStream": {
          "id": 23,
          "span": {
            "start": 8081,
            "end": 8087
          },
          "metadata": null
        }
      }
    }
  ]
}

Config engine call response

A successful result of a GetConfig engine call. The body is a Config.

Example:

{
  "EngineCallResponse": [
    0,
    {
      "Config": {
        "filesize": {
          "unit": "Metric",
          "show_unit": true,
          "precision": 1
        },
        "table": {
          "mode": "Rounded",
          "index_mode": "Always",
          ...
        },
        "footer_mode": {
          "RowCount": 25
        },
        "float_precision": 2,
        "use_ansi_coloring": "Auto",
        "edit_mode": "Emacs",
        ...
      }
    }
  ]
}

This example is abbreviated, as the Config object is large and ever-changing. The Config section describes its structure.

ValueMap engine call response

A successful result for engine calls that produce plain maps, such as the GetEnvVars engine call. The body is a map from strings to Values.

Example:

{
  "EngineCallResponse": [
    0,
    {
      "ValueMap": {
        "FOO": {
          "String": {
            "val": "bar",
            "span": {
              "start": 2020,
              "end": 2024
            }
          }
        }
      }
    }
  ]
}

Identifier engine call response

A successful result for engine calls that produce internal identifiers, such as FindDecl. The body is a usize (unsigned integer, platform pointer size).

Example:

{
  "EngineCallResponse": [
    0,
    {
      "Identifier": 4221
    }
  ]
}

IrBlock engine call response

A successful result of a GetBlockIR engine call. The body is the compiled intermediate representation (IR) of a block, as an IrBlock. This is an internal Nu type that can change between versions.

Example (for the closure {|x| $x + 1}):

{
  "EngineCallResponse": [
    0,
    {
      "IrBlock": {
        "instructions": [
          { "LoadVariable": { "dst": 0, "var_id": 74, "preserve_origin": false } },
          { "LoadLiteral": { "dst": 1, "lit": { "Int": 1 } } },
          { "BinaryOp": { "lhs_dst": 0, "op": { "Math": "Add" }, "rhs": 1 } },
          { "Span": { "src_dst": 0 } },
          { "Return": { "src": 0 } }
        ],
        "spans": [
          { "start": 170521, "end": 170523 },
          { "start": 170526, "end": 170527 },
          { "start": 170524, "end": 170525 },
          { "start": 170521, "end": 170527 },
          { "start": 170516, "end": 170528 }
        ],
        "data": [],
        "comments": ["", "", "", "", ""],
        "register_count": 2,
        "file_count": 0
      }
    }
  ]
}

view ir prints the same block in a readable form:

view ir {|x| $x + 1}
# => # 2 registers, 5 instructions, 0 bytes of data
# =>    0: load-variable          %0, var 74
# =>    1: load-literal           %1, int(1)
# =>    2: binary-op              %0, Math(Add), %1
# =>    3: span                   %0
# =>    4: return                 %0

The IrBlock map has these fields:

FieldTypeDescription
instructionsarrayThe instructions, run in order from index 0. Jumps and branches refer to these indexes.
spansSpan arrayThe source span of each instruction, at the same index.
databyte arrayString and binary data that the instructions refer to. A DataSlice, {"start": 0, "len": 3}, is a range of these bytes.
commentsstring arrayA comment for each instruction, used when printing the IR. Usually empty strings.
register_countunsigned integerHow many registers the block uses. Registers are numbered from 0.
file_countunsigned integerHow many files the block opens for redirection.

Versions before 0.117.0 also had an ast array, with one entry per instruction.

Each instruction is an externally tagged enum. Most variants are maps that name their operands, where dst, src, src_dst, and similar fields are register numbers. LoadLiteral puts a literal in a register. Literals that hold text, such as {"String": {"start": 0, "len": 3}}, point into data. Call runs the command with the given decl_id, using the arguments that the Push* instructions before it collected. The full list of variants and their fields is in the Instruction and Literal documentation, and view ir shows which ones a given block uses.

All instructions in 0.117.0

A variant without fields is a bare string, such as "PopErrorHandler". The others are maps of their fields.

InstructionFieldsEffect
UnreachableMarks a code path that can't run. Reaching it is an error.
LoadLiteraldst, litLoads a literal into dst.
LoadValuedst, valLoads a copy of a value, such as the result of constant evaluation, into dst.
Movedst, srcMoves the value from src to dst, leaving src empty.
Clonedst, srcCopies a collected value from src to dst.
Collectsrc_dstCollects a stream into a value, ignoring errors in the stream.
TryCollectsrc_dstCollects a stream into a value, failing on an error in the stream.
Spansrc_dstGives the value the span of this instruction.
DropsrcDrops a value or stream without reading it.
DrainsrcReads a stream to its end and discards it, as ; does.
DrainIfEndsrcLike Drain, but only for the last element of a pipeline.
LoadVariabledst, var_id, preserve_originLoads a variable into dst.
StoreVariablevar_id, srcStores src in a variable.
DropVariablevar_idRemoves a variable from the stack.
LoadEnvdst, keyLoads an environment variable, failing if it doesn't exist.
LoadEnvOptdst, keyLoads an environment variable, or nothing if it doesn't exist.
StoreEnvkey, srcSets an environment variable.
PushPositionalsrcAdds a positional argument for the next Call.
AppendRestsrcAdds a spread list of arguments for the next Call.
PushFlagnameAdds a switch for the next Call.
PushShortFlagshortAdds a switch, by its short name, for the next Call.
PushNamedname, srcAdds a flag with a value for the next Call.
PushShortNamedshort, srcAdds a flag with a value, by its short name, for the next Call.
PushParserInfoname, infoAdds parser information for the next Call.
RedirectOutmodeSets where the next Call sends stdout.
RedirectErrmodeSets where the next Call sends stderr.
CheckErrRedirectedsrcFails if stderr wasn't redirected in the stream in src.
OpenFilefile_num, path, appendOpens a file for a redirection.
WriteFilefile_num, srcWrites src to a redirection file.
CloseFilefile_numCloses a redirection file.
Calldecl_id, src_dstCalls a command with src_dst as input, and puts its output in src_dst.
StringAppendsrc_dst, valAppends a value to a string, for string interpolation.
GlobFromsrc_dst, no_expandTurns a string into a glob.
ListPushsrc_dst, itemAdds an item to a list.
ListSpreadsrc_dst, itemsAdds all the items of a list to a list.
RecordInsertsrc_dst, key, valAdds a column to a record, failing if it exists.
RecordSpreadsrc_dst, itemsAdds all the columns of a record to a record.
Notsrc_dstNegates a boolean.
BinaryOplhs_dst, op, rhsApplies an Operator and puts the result in lhs_dst.
FollowCellPathsrc_dst, pathReplaces a value with the value at a cell path.
CloneCellPathdst, src, pathCopies the value at a cell path of src to dst.
UpsertCellPathsrc_dst, path, new_valueSets the value at a cell path.
UpdateVarCellPathvar_id, cell_path, new_valueSets the value at a cell path of a mutable variable, in place.
JumpindexContinues at instruction index.
BranchIfcond, indexJumps to index if cond is true.
BranchIfEmptysrc, indexJumps to index if src is empty or nothing.
Matchpattern, src, indexJumps to index and binds variables if src matches the pattern.
CheckMatchGuardsrcFails if a match guard isn't a boolean.
Iteratedst, stream, end_indexPuts the next item of stream in dst, or jumps to end_index at the end.
UnwindJumpindex, handlersJumps to index after leaving handlers levels of try, as break and continue do.
OnErrorindexStarts a catch handler at index.
OnErrorIntoindex, dstStarts a catch handler at index that receives the error in dst.
FinallyIntoindex, dstStarts a finally handler at index.
PopErrorHandlerEnds the innermost catch handler.
BeginFinallyMarks the start of a finally block.
EndFinallyMarks the end of a finally block.
ReturnEarlysrcReturns src early, running pending finally blocks first.
ReturnsrcReturns src from the block.

Signal

The Signal message type is used to relay a signal from the engine to the plugin, allowing the plugin to respond to various system-level or user-initiated signals. The message body consists of a SignalAction enum, which currently supports the following variants:

  • Interrupt: Sent when the engine receives an interrupt signal (such as Ctrl+C), to gracefully interrupt a plugin's operation.
  • Reset: Sent when the engine's reset_signals method is called, indicating that the plugin should reset its signal state. Only the REPL calls it, as Signal Handling in Plugins describes.

Example:

{
  "Signal": "Interrupt"
}

Goodbye

Indicate that no further plugin calls are expected, and that the plugin should exit as soon as it is finished processing any in-progress plugin calls.

This message is not a map, it is just a bare string, as it takes no arguments.

Example:

"Goodbye"

Output messages

These are messages sent from the plugin to the engine. Hello and Stream messages are also included.

CallResponse

Error plugin call response

An error occurred while attempting to fulfill the request. The body is a LabeledError.

It is strongly preferred to provide labeled messages whenever possible to let the user know where the problem might be in their script. If there is no more suitable span from a value that can be used, head from EvaluatedCall is a good fallback.

Example:

{
  "CallResponse": [
    0,
    {
      "Error": {
        "msg": "A really bad error occurred",
        "labels": [
          {
            "text": "I don't know, but it's over nine thousand!",
            "span": {
              "start": 9001,
              "end": 9007
            }
          }
        ],
        "code": "my_plugin::bad::really_bad",
        "url": "https://example.org/my_plugin/error/bad/really_bad.html",
        "help": "you can solve this by not doing the bad thing",
        "inner": [
          {
            "msg": "The bad thing"
          }
        ]
      }
    }
  ]
}

Ok plugin call response

A successful response with no data, used for operations that don't return anything, such as the Save custom value op. This message is not a map, it is just the bare string "Ok".

Example:

{
  "CallResponse": [0, "Ok"]
}

Metadata plugin call response

A successful response to a Metadata plugin call. The body contains fields that describe the plugin, none of which are required:

FieldTypeDescription
versionstring?The version of the plugin (not the protocol!). SemVer is recommended, but not required.

Example:

{
  "CallResponse": [
    0,
    {
      "Metadata": {
        "version": "1.2.3"
      }
    }
  ]
}

Signature plugin call response

A successful response to a Signature plugin call. The body is an array of signatures.

Example:

{
  "CallResponse": [
    0,
    {
      "Signature": [
        {
          "sig": {
            "name": "len",
            "description": "calculates the length of its input",
            "extra_description": "",
            "search_terms": [],
            "required_positional": [],
            "optional_positional": [
              {
                "name": "cell_path",
                "desc": "Cell path to measure.",
                "shape": "CellPath",
                "completion": null,
                "var_id": null,
                "default_value": null
              }
            ],
            "rest_positional": null,
            "named": [
              {
                "long": "help",
                "short": "h",
                "arg": null,
                "required": false,
                "desc": "Display the help message for this command",
                "completion": null,
                "var_id": null,
                "default_value": null
              }
            ],
            "input_output_types": [["String", "Int"]],
            "allow_variants_without_examples": false,
            "is_filter": false,
            "creates_scope": false,
            "allows_unknown_args": false,
            "complete": null,
            "category": "Default"
          },
          "examples": []
        }
      ]
    }
  ]
}

Each element has a sig map, which describes one command, and an examples array. The fields of sig:

FieldTypeDescription
namestringThe command name. A subcommand's name includes its parent, as in "len chars".
descriptionstringThe one-line description shown in help and in completions.
extra_descriptionstringLonger help text, shown below the description in help. May be empty.
search_termsstring arrayOther words that help --find matches.
required_positionalpositional arrayRequired positional arguments, in order.
optional_positionalpositional arrayOptional positional arguments, after the required ones.
rest_positionalpositional or nullAn argument that takes all remaining positional values, or null.
namedflag arrayFlags and switches. Include the help switch (-h) as in the example. The engine shows the help page itself, but without this entry --help is an unknown flag.
input_output_typesarray of Type pairsThe input types the command accepts, each with the output type it produces for that input. An empty array accepts any input.
allow_variants_without_examplesbooleanUsed only by Nushell's own tests of built-in commands. It has no effect on plugins.
is_filterbooleanNot used. Send false.
creates_scopebooleanWhether the parser opens a new variable scope for the call's arguments. Send false.
allows_unknown_argsbooleanPass undeclared flags and extra arguments through as positional values, the way extern does. A flag like --what arrives as the string "--what".
rejects_unknown_flagsboolean, optionalAdded in 0.117.0, and false if left out. With allows_unknown_args, an undeclared flag becomes a parse error, while extra positional values still pass through, like extern --strict.
completestring, map, or nullA completer for the whole command line, used by extern declarations. Send null.
categorystring or mapThe category in help commands, such as "Default", "Experimental", or "Filters", or {"Custom": "name"} for a category of your own.

A positional argument is a map with name, desc, shape, completion, var_id, and default_value. A flag is a map with long, short (a one-character string or null), arg (the shape of its value, or null for a switch), required, desc, completion, var_id, and default_value. In both:

  • shape and arg are a SyntaxShape, which tells the parser how to parse the argument. Simple shapes are strings, such as "Int", "String", "Filepath", "CellPath", or "Any". Others are maps, such as {"List": "Int"} or {"Closure": null} for a closure with any parameters.
  • completion is null, or {"List": ["alpha", "beta"]} to offer a fixed list of values when the user presses Tab. For values computed at that time, answer GetCompletion instead.
  • var_id is for commands defined in Nushell code. Send null.
  • default_value is a Value or null. help shows it, but the engine doesn't fill it in. When the user leaves the argument out, it's missing from the EvaluatedCall, and the plugin has to apply the default.

A Type is a string, such as "Any", "Nothing", "String", "Int", or "Binary", or a map for a type with parameters, such as {"List": "Int"}, {"Record": [["name", "String"], ["size", "Filesize"]]} (an empty array for any record), or {"Custom": "polars_dataframe"}.

Fields whose type allows null can be left out, and rejects_unknown_flags can be too. The others are required.

Each element of examples is a map with example, description, and result. example is the Nushell code, and result is a Value or null. help shows the examples and their results. The Rust SDK converts custom values in example results with the plugin's custom_value_to_base_value() before sending them.

Ordering plugin call response

A successful response to the PartialCmp custom value op. The body is either Ordering if the comparison is possible, or null if the values can't be compared.

Example:

{
  "CallResponse": [
    0,
    {
      "Ordering": "Less"
    }
  ]
}

Example with incomparable values:

{
  "CallResponse": [
    0,
    {
      "Ordering": null
    }
  ]
}

CompletionItems plugin call response

A successful response to a GetCompletion plugin call. The body is either null, which tells the engine to fall back to its default completions, or an array of suggestions (which may be empty, meaning that there are no suggestions). Each suggestion is a map:

FieldTypeDescription
valuestringThe text that will replace the argument being completed.
display_overridestring?Text to display to the user instead of value.
descriptionstring?A description of the suggestion.
extrastring array?Extra information, e.g. examples.
append_whitespacebooleanRequired. Whether to append a space after the suggestion is accepted.
match_indicesunsigned integer array?Indices of the graphemes in the suggestion that matched the typed text.
spanSpan?The part of the input buffer to replace, if different from the argument's span.
kindstring or map?The kind of suggestion, such as "File" or "Directory". See below.

Example:

{
  "CallResponse": [
    2,
    {
      "CompletionItems": [
        {
          "value": "alpha",
          "display_override": null,
          "description": "first choice",
          "extra": null,
          "append_whitespace": true,
          "match_indices": null,
          "span": null,
          "kind": null
        },
        {
          "value": "beta",
          "display_override": null,
          "description": null,
          "extra": null,
          "append_whitespace": true,
          "match_indices": null,
          "span": null,
          "kind": null
        }
      ]
    }
  ]
}

kind is null or one of these:

kindReported by commandline complete --detailed as
"CellPath"cell-path
"Directory"directory
"File"file
"Flag"flag
"Module"module
"Operator"operator
"Variable"variable
{"Command": [command_type, decl_id]}command, with the command type as its type
{"Value": type}value, with the type as its type

In the Command form, command_type is one of "Builtin", "Custom", "Keyword", "External", "Alias", or "Plugin", and decl_id is a declaration ID or null. In the Value form, type is a type in the same form as in signatures, such as "Int" or {"List": "String"}. Besides commandline complete, the Nushell language server uses kind to label suggestions in an editor.

The engine filters the suggestions against the text the user has typed, using the user's completion settings, and sorts them, so the plugin can return every candidate. The engine ignores a span that starts before the beginning of the command line, or ends before it starts, and uses the argument's own span instead.

PipelineData plugin call response

A successful result with a Nu Value or stream. The body is a PipelineDataHeader.

Example:

{
  "CallResponse": [
    0,
    {
      "PipelineData": {
        "Value": [
          {
            "Int": {
              "val": 42,
              "span": {
                "start": 12,
                "end": 14
              }
            }
          },
          null
        ]
      }
    }
  ]
}

EngineCall

Plugins can make engine calls during execution of a call. The body is a map with the following keys:

FieldTypeDescription
contextintegerThe ID of the call that this engine call relates to.
idintegerA unique ID for this engine call, in order to send the response.
callEngineCallOne of the options described below.

The context must be an ID of a call that was received that is currently in one of two states:

  1. The response has not been sent yet.
  2. The response contained stream data (i.e. ListStream or ByteStream), and at least one of the streams started by the response is still sending data (i.e. End has not been sent).

After a response has been fully sent, and streams have ended, the context from that call can no longer be used.

The engine call ID must be unique for the lifetime of the plugin, and it is suggested that this be a sequentially increasing number across all engine calls made by the plugin. It is not separated by context; the response only contains the id.

GetConfig engine call

Get the Nushell engine configuration. Returns a Config response if successful. In Rust, call EngineInterface::get_config(), which returns an Arc<Config>. Because the configuration is large, the engine only sends it when asked.

Example:

{
  "EngineCall": {
    "context": 0,
    "id": 0,
    "call": "GetConfig"
  }
}

GetPluginConfig engine call

Get the configuration for the plugin, from its section in $env.config.plugins.NAME if present. Returns a PipelineData response if successful, which will contain either a Value or be Empty if there is no configuration for the plugin set.

If the plugin configuration was specified as a closure, the engine evaluates that closure, with no arguments and in the scope of the plugin call, each time it receives this engine call, and returns the result. If the closure fails, the response is still PipelineData, with a Value that holds an Error value, not an error response. For example:

{
  "EngineCallResponse": [
    0,
    {
      "PipelineData": {
        "Value": [
          {
            "Error": {
              "error": {
                "msg": "boom",
                "labels": [{ "text": "", "span": { "start": 170716, "end": 170729 } }],
                "code": null,
                "url": null,
                "help": null,
                "inner": []
              },
              "span": { "start": 170740, "end": 170752 }
            }
          },
          null
        ]
      }
    }
  ]
}

In Rust, call EngineInterface::get_plugin_config(). Plugin configuration shows what it returns in each case.

Example:

{
  "EngineCall": {
    "context": 3,
    "id": 8,
    "call": "GetPluginConfig"
  }
}

GetEnvVar engine call

Get an environment variable from the caller's scope. Returns a PipelineData response if successful, which will contain either a Value or be Empty if the environment variable is not present.

Example:

{
  "EngineCall": {
    "context": 7,
    "id": 41,
    "call": {
      "GetEnvVar": "PATH"
    }
  }
}

GetEnvVars engine call

Get all environment variables from the caller's scope. Returns a ValueMap response if successful, with all of the environment variables in the scope.

Example:

{
  "EngineCall": {
    "context": 9,
    "id": 72,
    "call": "GetEnvVars"
  }
}

GetCurrentDir engine call

Get the current directory path in the caller's scope. This always returns an absolute path as a string Value pipeline data response if successful. The span contained within the value response is unlikely to be useful, and may be zero.

Example:

{
  "EngineCall": {
    "context": 7,
    "id": 40,
    "call": "GetCurrentDir"
  }
}

AddEnvVar engine call

Set an environment variable in the caller's scope. The environment variable can only be propagated to the caller's scope if called before the plugin call response is sent. Either way, it is propagated to other engine calls made within the same context. The argument is a 2-tuple: (name, value). The response type is Empty pipeline data when successful.

Example:

{
  "EngineCall": {
    "context": 7,
    "id": 42,
    "call": {
      "AddEnvVar": [
        "FOO",
        {
          "String": {
            "val": "bar",
            "span": {
              "start": 2020,
              "end": 2024
            }
          }
        }
      ]
    }
  }
}

GetHelp engine call

Get fully formatted help text for the current command. This can help with implementing top-level commands that just list their subcommands, rather than implementing any specific functionality. The response on success is Value pipeline data that always contains a string. It's the same text that --help prints. In Rust, call EngineInterface::get_help(), which returns a String.

Example:

{
  "EngineCall": {
    "context": 1,
    "id": 2,
    "call": "GetHelp"
  }
}

EnterForeground engine call

Moves the plugin to the foreground group for direct terminal access, in an operating system-defined manner. This should be called when the plugin is going to drive the terminal in raw mode, for example to implement a terminal UI. It will likely be necessary for the plugin to also be running in local socket mode in that case.

This call responds with Empty pipeline data on success when no action is required by the plugin. On Unix-like operating systems, if the response is Value pipeline data, it contains an Int which is the process group ID the plugin must join using setpgid() in order to be in the foreground.

This call will fail with an error if the plugin is already in the foreground.

The plugin should call LeaveForeground when it no longer needs to be in the foreground. Note that the plugin will also automatically be removed from the foreground when the plugin call response is received, even if the plugin call returns a stream.

In Rust, EngineInterface::enter_foreground() sends this call, joins the process group from the response if there is one, and returns a ForegroundGuard. Keep the guard alive while you use the terminal. Dropping it moves the plugin back to its own process group and sends LeaveForeground, but discards any error. Call .leave() on the guard instead to get that error as a Result. On Windows and other non-Unix platforms, a response that asks the plugin to join a process group makes enter_foreground() return an error, since process groups aren't supported there.

let guard = engine.enter_foreground()?;
// ... read keys and draw on the terminal ...
guard.leave()?;

Example:

{
  "EngineCall": {
    "context": 0,
    "id": 0,
    "call": "EnterForeground"
  }
}

LeaveForeground engine call

Resets the state set by EnterForeground.

If the plugin had been requested to change process groups by the response of EnterForeground, it should also reset that state by calling setpgid(0), since plugins are normally in their own process group.

This call responds with Empty pipeline data on success.

Example:

{
  "EngineCall": {
    "context": 0,
    "id": 0,
    "call": "LeaveForeground"
  }
}

GetSpanContents engine call

Get the contents of a Span from the engine. This can be used for viewing the source code that generated a value. The argument is a Span. The response on success is Value pipeline data containing a Binary value, as the result is not guaranteed to be valid UTF-8. In Rust, call EngineInterface::get_span_contents(span), which returns a Vec<u8>. Spans count bytes, so a span can cut through a multibyte character. Use String::from_utf8_lossy() to display the result.

Example:

{
  "EngineCall": {
    "context": 7,
    "id": 72,
    "call": {
      "GetSpanContents": {
        "start": 38881,
        "end": 39007
      }
    }
  }
}

EvalClosure engine call

Pass a Closure and arguments to the engine to be evaluated. Returns a PipelineData response if successful with the output of the closure, which may be a stream.

FieldTypeDescription
closurespanned ClosureThe closure to call, generally from a Value.
positionalValue arrayPositional arguments for the closure.
inputPipelineDataHeaderInput for the closure.
redirect_stdoutbooleanWhether to redirect stdout if the closure ends in an external command.
redirect_stderrbooleanWhether to redirect stderr if the closure ends in an external command.

The Closure is not wrapped as a Value - i.e., it doesn't have {"Closure": ...} around it.

Example:

{
  "EngineCall": {
    "context": 7,
    "id": 40,
    "call": {
      "EvalClosure": {
        "closure": {
          "item": {
            "block_id": 72,
            "captures": []
          },
          "span": {
            "start": 780,
            "end": 812
          }
        },
        "positional": [
          {
            "Int": {
              "val": 7,
              "span": {
                "start": 3080,
                "end": 3081
              }
            }
          }
        ],
        "input": "Empty",
        "redirect_stdout": true,
        "redirect_stderr": false
      }
    }
  }
}

FindDecl engine call

Find the declaration ID for a command in scope. The body is the name of the desired command, as a string. Returns an Identifier response if successful with the ID of the declared command, or an empty PipelineData response if the command with the given name couldn't be found in the scope of the plugin call.

It is recommended to provide a descriptive error about what command was required if the command wasn't found, as it is possible to hide even the core commands that are provided with Nushell. Finding and calling commands from the same or other plugins is supported, however keep in mind that doing things within the plugin is usually more efficient when possible.

Example:

{
  "EngineCall": {
    "context": 7,
    "id": 48,
    "call": {
      "FindDecl": "inc"
    }
  }
}

CallDecl engine call

Pass a command's declaration ID (found via FindDecl) and arguments to the engine to be called. Returns a PipelineData response if successful with the output of the command, which may be a stream.

FieldTypeDescription
decl_idunsigned integerThe ID of the declaration to call.
callEvaluatedCallArguments and head span for the call.
inputPipelineDataHeaderInput for the command.
redirect_stdoutbooleanWhether to redirect stdout if the declared command ends in an external command.
redirect_stderrbooleanWhether to redirect stderr if the declared command ends in an external command.

Example (calling "hello" | str length --grapheme-clusters, where str length was found by FindDecl with ID 226):

{
  "EngineCall": {
    "context": 7,
    "id": 49,
    "call": {
      "CallDecl": {
        "decl_id": 226,
        "call": {
          "head": {
            "start": 40400,
            "end": 40403
          },
          "positional": [],
          "named": [
            [
              {
                "item": "grapheme-clusters",
                "span": {
                  "start": 40404,
                  "end": 40423
                }
              },
              null
            ]
          ]
        },
        "input": {
          "Value": [
            {
              "String": {
                "val": "hello",
                "span": {
                  "start": 40390,
                  "end": 40397
                }
              }
            },
            null
          ]
        },
        "redirect_stdout": true,
        "redirect_stderr": false
      }
    }
  }
}

GetBlockIR engine call

Get the compiled intermediate representation (IR) of a block, such as the block of a Closure passed to the plugin. The argument is the block ID, as an unsigned integer. Returns an IrBlock response if successful, or an error if the block doesn't exist or wasn't compiled.

The IR format is internal to Nu and can change between versions, so plugins that use this call are likely to depend on a specific Nu version. In Rust, call EngineInterface::get_block_ir(block_id), which returns an IrBlock. A closure's block ID is closure.item.block_id.

Example:

{
  "EngineCall": {
    "context": 2,
    "id": 13,
    "call": {
      "GetBlockIR": 294
    }
  }
}

Option

Sets options that affect how the engine treats the plugin. No response is expected for this message.

GcDisabled option

Set to true to stop the plugin from being automatically garbage collected, or false to enable it again.

Example:

{
  "Option": {
    "GcDisabled": true
  }
}

Stream messages

Streams can be sent by both the plugin and the engine. The agent that is sending the stream is known as the producer, and the agent that receives the stream is known as the consumer.

All stream messages reference a stream ID. This identifier is an integer starting at zero and is specified by the producer in the message that described what the stream would be used for: for example, Call or CallResponse. A producer should not reuse identifiers it has used once before. The most obvious implementation is sequential, where each new stream gets an incremented number. It is not necessary for stream IDs to be totally unique across both the plugin and the engine: stream 0 from the plugin and stream 0 from the engine are different streams.

Data

This message is sent from producer to consumer. The body is a 2-tuple (array) of (id, data).

The data is either a List map for a list stream, in which case the body is the Value to be sent, or Raw for a raw stream, in which case the body is either an Ok map with a byte buffer, or an Err map with a LabeledError.

Examples:

{
  "Data": [
    0,
    {
      "List": {
        "String": {
          "val": "Hello, world!",
          "span": {
            "start": 40000,
            "end": 40015
          }
        }
      }
    }
  ]
}
{
  "Data": [
    0,
    {
      "Raw": {
        "Ok": [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
      }
    }
  ]
}
{
  "Data": [
    0,
    {
      "Raw": {
        "Err": {
          "msg": "disconnected",
          "labels": [],
          "code": null,
          "url": null,
          "help": null,
          "inner": []
        }
      }
    }
  ]
}

End

This message is sent from producer to consumer. The body is a single value, the id.

Must be sent at the end of a stream by the producer. The producer must not send any more Data messages after the end of the stream.

The consumer must send Drop in reply unless the stream ended because the consumer chose to drop the stream.

Example:

{
  "End": 0
}

Ack

This message is sent from consumer to producer. The body is a single value, the id.

Sent by the consumer in reply to each Data message, indicating that the consumer has finished processing that message. Ack is used for flow control. If a consumer does not need to process a stream immediately, or is having trouble keeping up, it should not send Ack messages until it is ready to process more Data.

Example:

{
  "Ack": 0
}

Drop

This message is sent from consumer to producer. The body is a single value, the id.

Sent by the consumer to indicate disinterest in further messages from a stream. The producer may send additional Data messages after Drop has been received, but should make an effort to stop sending messages and End the stream as soon as possible.

The consumer should not consider Data messages sent after Drop to be an error, unless End has already been received.

The producer must send End in reply unless the stream ended because the producer ended the stream.

Example:

{
  "Drop": 0
}

Signal Handling in Plugins

Plugins can respond to signals sent from the engine, such as interrupts (Ctrl+C) or resets, by registering handlers. The plugin’s signal handling methods allow for customizable responses to user or system actions, enhancing the plugin's integration with the Nu engine.

register_signal_handler

The register_signal_handler method allows a plugin to register a handler that will be called when a signal is received. This method accepts a closure with the following signature:

|action: SignalAction| { ... }

The closure will be invoked with the SignalAction variant received from the engine. This method returns an RAII guard that ensures the handler remains active until it is dropped.

Example Usage

Below is an example of registering a handler that responds to both Interrupt and Reset signals:

let _guard = engine.register_signal_handler(Box::new(move |action| {
    match action {
        SignalAction::Interrupt => eprintln!("Interrupt signal received"),
        SignalAction::Reset => eprintln!("Reset signal received"),
    }
}))?;

When you press Ctrl+C, Nu sends Interrupt to every plugin that is running, whether or not it is in the middle of a call. Only the REPL sends Reset. It sends one at the start of every iteration, before it draws the prompt, so a running plugin gets a Reset after each command line finishes. It also sends one when Ctrl+C interrupts the prompt while it is being drawn, and before it runs a line if the prompt or the line editor was interrupted. Scripts and nu -c never send it.

A handler runs on the thread that reads the plugin's input from Nu. Until the handler returns, the plugin receives nothing else: no stream data, no engine call responses, and no new calls. Keep handlers short and leave the real work to the thread that is running the call. The example ctrlc command in nu_plugin_example works this way. Its handler only sends on a channel, and run() waits on the other end. The list of handlers stays locked while they run, so registering a handler or dropping a guard from inside a handler never returns.

signals()

The signals() method returns the plugin's Signals. The SDK sets its interrupt flag when an Interrupt arrives and clears it on Reset, before it runs the registered handlers. The flag belongs to the whole plugin process. Every EngineInterface returns the same Signals, so an interrupt shows up in all of the plugin's calls that are running, and a Reset clears it for all of them.

interrupted() reports whether the flag is set:

if engine.signals().interrupted() {
    eprintln!("Operation was interrupted.");
}

check(&span) returns Err(ShellError::Interrupted { .. }) once the flag is set, so a long loop can stop with ?. That works in run(), which returns LabeledError, because LabeledError converts from ShellError:

for item in items {
    engine.signals().check(&call.head)?;
    // work on item
}

A list stream that the plugin builds with engine.signals(), for example with into_pipeline_data(span, engine.signals().clone()), checks the flag on each item and ends once it is set. PipelineData::map, which the double example in the plugins chapter uses, passes its signals argument on only when the input is a list or range value. When the input is already a stream, the mapped stream keeps the input stream's signals.

Encoding

JSON

The JSON encoding defines messages as JSON objects. No separator or padding is required. Whitespace within the message object as well as between messages is permitted, including newlines.

The engine is more strict about the format it emits: every message ends with a newline, and unnecessary whitespace and newlines will not be emitted within a message. It is explicitly supported for a plugin to choose to parse the input from the engine by parsing each line received as a separate message, as this is most commonly supported across all languages.

Byte arrays are encoded as plain JSON arrays of numbers representing each byte. While this is inefficient, it is maximally portable.

MessagePack should be preferred where possible if performance is desired.

MessagePack

MessagePack is a machine-first binary encoding format with a data model very similar to JSON. Messages are encoded as maps. There is no separator between messages, and no padding character is accepted.

Most messages are encoded in the same way as their JSON analogue. For example, the following Hello message in JSON:

{
  "Hello": {
    "protocol": "nu-plugin",
    "version": "0.116.0",
    "features": []
  }
}

is encoded in the MessagePack format as:

81                   // map, one element
  a5 "Hello"         // 5-character string
  83                 // map, three elements
    a8 "protocol"    // 8-character string
    a9 "nu-plugin"   // 9-character string
    a7 "version"     // 7-character string
    a7 "0.116.0"     // 7-character string
    a8 "features"    // 8-character string
    90               // array, zero elements

(verbatim byte strings quoted for readability, non-printable bytes in hexadecimal)

Byte arrays are encoded the same way as in JSON: as MessagePack arrays of integers, one per byte. When decoding, Nu also accepts MessagePack's native bin type for byte arrays. In general, the MessagePack encoding is much more efficient than JSON and should be the first choice for plugins where performance is important and MessagePack is available.

Value types

Rust documentation

The Value enum describes all structured data used in Nu.

Example:

{
  "Int": {
    "val": 5,
    "span": {
      "start": 90960,
      "end": 90963
    }
  }
}

Bool

A boolean.

FieldType
valboolean
spanSpan

Example:

true
{
  "Bool": {
    "val": true,
    "span": {
      "start": 4040,
      "end": 4044
    }
  }
}

Int

A 64-bit signed integer.

FieldType
valinteger
spanSpan

Example:

-2
{
  "Int": {
    "val": -2,
    "span": {
      "start": 4040,
      "end": 4042
    }
  }
}

Float

A 64-bit (double precision) floating point number.

FieldType
valdouble
spanSpan

Example:

36.4
{
  "Float": {
    "val": 36.4,
    "span": {
      "start": 8040,
      "end": 8044
    }
  }
}

Filesize

A quantity of bytes, internally a 64-bit signed integer representing the number of bytes. This is pretty-printed to the user with a more human scale, e.g. 32.4 MiB.

FieldType
valinteger
spanSpan

Example:

32.4MiB
{
  "Filesize": {
    "val": 33973862,
    "span": {
      "start": 7740,
      "end": 7747
    }
  }
}

Duration

A duration of time, internally a 64-bit signed integer representing the number of nanoseconds. This is pretty-printed to the user with a more human scale, e.g. 8sec 375ms 604µs 528ns.

FieldType
valinteger
spanSpan

Example:

8375604528ns
{
  "Duration": {
    "val": 8375604528,
    "span": {
      "start": 181462,
      "end": 181465
    }
  }
}

Date

A date/time value, including the time zone, represented in RFC 3339 format. This is printed to the user according to their locale.

FieldType
valstring
spanSpan

Example:

1996-12-19T16:39:57-08:00
{
  "Date": {
    "val": "1996-12-19T16:39:57-08:00",
    "span": {
      "start": 181525,
      "end": 181528
    }
  }
}

Range

A range of values.

FieldType
valstring
spanSpan

The range is encoded as a string, using Nu's range syntax:

FormMeaning
start..endFrom start to end, inclusive.
start..<endFrom start to end, excluding end.
start..From start, with no end.
start..next..endFrom start to end, with a step of next - start. This also works with ..<end or no end.

If any of the numbers contains a ., the range is a float range; otherwise, it is an int range. Nu always writes floats with a decimal point (1.0, not 1) and only writes the step if it isn't 1. Nu also fills in parts that were left out in the source code, so ..5 is sent as "0..5", and 5..1 (which counts down) is sent as "5..4..1".

Examples:

The unbounded range 0.. (don't type this one at the prompt on its own, as Nu will try to print every number in it):

{
  "Range": {
    "val": "0..",
    "span": {
      "start": 1380,
      "end": 1383
    }
  }
}
7..10
{
  "Range": {
    "val": "7..10",
    "span": {
      "start": 1380,
      "end": 1385
    }
  }
}
7..<10
{
  "Range": {
    "val": "7..<10",
    "span": {
      "start": 1380,
      "end": 1386
    }
  }
}
0..64..128
{
  "Range": {
    "val": "0..64..128",
    "span": {
      "start": 1380,
      "end": 1390
    }
  }
}
7.5..10.5
{
  "Range": {
    "val": "7.5..10.5",
    "span": {
      "start": 1380,
      "end": 1389
    }
  }
}

String

A UTF-8 string.

FieldType
valstring
spanSpan

Example:

"Hello, nu!"
{
  "String": {
    "val": "Hello, nu!",
    "span": {
      "start": 8990,
      "end": 9002
    }
  }
}

Glob

A filesystem glob, selecting multiple files or directories depending on the expansion of wildcards.

If no_expand is true, the expansion of wildcards is disabled and this just acts as a literal path.

FieldType
valstring
no_expandboolean
spanSpan

Example:

"src/**/*.rs" | into glob
{
  "Glob": {
    "val": "src/**/*.rs",
    "no_expand": false,
    "span": {
      "start": 9400,
      "end": 9413
    }
  }
}

Record

An associative key-value map. If records are contained in a list, this renders as a table. The keys are always strings, but the values may be any type.

FieldType
valmap: string ⇒ Value
spanSpan

Example:

{foo: 5, bar: "hello nushell"}
{
  "Record": {
    "val": {
      "foo": {
        "Int": {
          "val": 42,
          "span": {
            "start": 659813,
            "end": 659814
          }
        }
      },
      "bar": {
        "String": {
          "val": "hello nushell",
          "span": {
            "start": 659821,
            "end": 659836
          }
        }
      }
    },
    "span": {
      "start": 659807,
      "end": 659837
    }
  }
}

List

A list of values of any type.

FieldType
valsValue array
spanSpan

Example:

[1, 2, foo, bar]
{
  "List": {
    "vals": [
      {
        "Int": {
          "val": 1,
          "span": {
            "start": 659951,
            "end": 659952
          }
        }
      },
      {
        "Int": {
          "val": 2,
          "span": {
            "start": 659954,
            "end": 659955
          }
        }
      },
      {
        "String": {
          "val": "foo",
          "span": {
            "start": 659957,
            "end": 659960
          }
        }
      },
      {
        "String": {
          "val": "bar",
          "span": {
            "start": 659962,
            "end": 659965
          }
        }
      }
    ],
    "span": {
      "start": 659950,
      "end": 659966
    }
  }
}

Closure

A reference to a parsed block of Nushell code, with variables captured from scope.

FieldType
valClosure
spanSpan

Closure is defined as:

FieldType
block_idunsigned integer
capturesarray of pairs (unsigned integer var_id, Value)

The plugin should not try to inspect the contents of the closure. It is recommended that this is only used as an argument to the EvalClosure engine call. The exact representation of a closure is likely to change in the future to avoid serializing all of the captures.

Example:

let foo = "bar"
{ || $foo }
{
  "Closure": {
    "val": {
      "block_id": 1965,
      "captures": [
        [
          862,
          {
            "String": {
              "val": "bar",
              "span": {
                "start": 660030,
                "end": 660041
              }
            }
          }
        ]
      ]
    },
    "span": {
      "start": 660030,
      "end": 660041
    }
  }
}

Nothing

The absence of a value, represented by null within Nushell.

FieldType
spanSpan

Example:

null
{
  "Nothing": {
    "span": {
      "start": 64550,
      "end": 64554
    }
  }
}

Error

An error contained within a value. Trying to operate on the value will most likely cause the error to be forwarded. When writing plugins, error values should typically be handled by returning the error from the command when encountered.

FieldType
errorLabeledError
spanSpan

Note that the field containing the error is named error, not val.

Example, for the error created by:

error make {msg: "foo", help: "bar"}
# => Error: nu::shell::error
# =>
# =>   × foo
# =>    ╭─[repl_entry #1:1:12]
# =>  1 │ error make {msg: "foo", help: "bar"}
# =>    ·            ─────────────────────────
# =>    ╰────
# =>   help: bar
{
  "Error": {
    "error": {
      "msg": "foo",
      "labels": [
        {
          "text": "",
          "span": {
            "start": 11,
            "end": 36
          }
        }
      ],
      "code": null,
      "url": null,
      "help": "bar",
      "inner": []
    },
    "span": {
      "start": 0,
      "end": 36
    }
  }
}

Binary

An array of raw bytes. This is sometimes returned from operations that detect data that isn't valid as UTF-8, but can also be created with into binary or binary literals.

FieldType
valbyte array
spanSpan

Byte arrays are encoded as arrays of numbers in both JSON and MessagePack. See the MessagePack section for details.

Example:

0x[aa bb cc dd]
{
  "Binary": {
    "val": [170, 187, 204, 221],
    "span": {
      "start": 659637,
      "end": 659652
    }
  }
}

CellPath

Represents a path into subfields of lists, records, and tables.

FieldType
valstring
spanSpan

The cell path is encoded as a string: $ followed by each path member with a . in front of it. An empty cell path is $.. Members that are unsigned integers index into lists and tables. Other members are column names, which are quoted if necessary (e.g. $."a b" or $."0"). Each member can be followed by modifiers:

  • ! marks a column name as case-insensitive.
  • ? marks the member as optional. Optional path members will not cause errors if they can't be accessed - the path access will just return Nothing instead.

The spans of the individual path members are not sent.

Example:

$.foo.0?.bar
{
  "CellPath": {
    "val": "$.foo.0?.bar",
    "span": {
      "start": 659873,
      "end": 659887
    }
  }
}

Custom

Represents data types that extend the base nushell types with custom functionality. Plugins can use custom values to implement native-like data types that can be indexed by cell paths, operated on by operators, and compared in plugin-defined ways.

Custom values for plugins may only contain the following content map:

FieldTypeDescription
typestringMust be "PluginCustomValue".
namestringThe human-readable name of the custom value emitted by the plugin.
databyte arrayPlugin-defined representation of the custom value.
notify_on_dropbooleanEnable drop notification. Default false if not present.

Plugins will only be sent custom values that they have previously emitted. Custom values from other plugins or custom values used within the Nu engine itself are not permitted to be sent to or from the plugin.

notify_on_drop is an optional field that should be omitted if false, to save bytes. If this is not convenient for your implementation, "notify_on_drop": false is still valid, but it's preferred to not include it.

Example:

{
  "Custom": {
    "val": {
      "type": "PluginCustomValue",
      "name": "database",
      "data": [36, 190, 127, 40, 12, 3, 46, 83],
      "notify_on_drop": true
    },
    "span": {
      "start": 320,
      "end": 340
    }
  }
}

Embedded Nu types

Several types used within the protocol come from elsewhere in Nu's source code, especially the nu-protocol crate.

Rust enums are usually encoded in serde's default format:

"Variant"             // Variant
{ "Variant": value }  // Variant(value)
{ "Variant": [a, b] } // Variant(a, b)
{
  "Variant": {
    "one": 1,
    "two": 2
  }
}                     // Variant { one: 1, two: 2 }

Structs are encoded as maps of their fields, without the name of the struct.

Span

Documentation

Describes a region of code in the engine's memory, used mostly for providing diagnostic error messages to the user with context about where a value that caused an error came from.

FieldTypeDescription
startintegerThe index of the first character referenced.
endintegerThe index after the last character referenced.

PipelineDataHeader

Describes either a single value, or the beginning of a stream.

VariantDescription
EmptyNo values produced; an empty stream.
ValueA single value
ListStreamSpecify a list stream that will be sent.
ByteStreamSpecify a byte stream that will be sent.

Empty header variant

An empty stream. Nothing will be sent. There is no identifier, and this is equivalent to a Nothing value.

The representation is the following string:

"Empty"

Value header variant

A single value. Does not start a stream, so there is no identifier. The body is a 2-tuple (array): (value, metadata), where value is a Value and metadata is either PipelineMetadata or null. Both elements must be present.

Example:

{
  "Value": [
    {
      "Int": {
        "val": 2,
        "span": {
          "start": 9090,
          "end": 9093
        }
      }
    },
    null
  ]
}

Example with metadata, from "x" | metadata set --content-type "text/plain":

{
  "Value": [
    {
      "String": {
        "val": "x",
        "span": {
          "start": 169453,
          "end": 169456
        }
      }
    },
    {
      "data_source": "None",
      "path_columns": [],
      "content_type": "text/plain",
      "custom": {}
    }
  ]
}

ListStream header variant

Starts a list stream. Expect Data messages of the List variant with the referenced ID.

Contains ListStreamInfo, a map:

FieldTypeDescription
idintegerThe stream identifier
spanSpanThe source code reference that caused the stream.
metadataPipelineMetadata?Metadata about the stream, or null.

Example:

{
  "ListStream": {
    "id": 2,
    "span": {
      "start": 33911,
      "end": 33942
    },
    "metadata": null
  }
}

ByteStream header variant

Starts a byte stream. Expect Data messages of the Raw variant with the referenced ID.

FieldTypeDescription
idintegerThe stream identifier
spanSpanThe source code reference that caused the stream.
typeByteStreamTypeThe expected type of the stream.
metadataPipelineMetadata?Metadata about the stream, or null.

Byte streams carry a type field with one of the three following strings:

typeMeaning
"Binary"The stream contains binary data of unknown encoding, and should be treated as a binary value.
"String"The stream contains text data that is valid UTF-8, and should be treated as a string value.
"Unknown"The type of the byte stream is unknown and should be inferred depending on whether its contents can be decoded as valid UTF-8 or not.

The Unknown type is used by Nu to represent the output of external commands if they are not passed through into string or into binary to explicitly set their type. A command that declares an output type of exclusively either string or binary must explicitly type its output byte streams appropriately, to ensure they coerce to the correct type, rather than using Unknown.

Example:

{
  "ByteStream": {
    "id": 7,
    "span": {
      "start": 49011,
      "end": 49027
    },
    "type": "String",
    "metadata": null
  }
}

PipelineMetadata

Documentation

Metadata that can be attached to pipeline data, as shown by the metadata command. It is a map:

FieldTypeDescription
data_sourcestring or mapWhere the data came from: "None", "HtmlThemes", or {"FilePath": "<path>"}.
path_columnsstring arrayNames of columns that contain file paths (e.g. ["name"] for the output of ls).
content_typestring?The MIME type of the data, e.g. "application/json".
custommap: string ⇒ Value?Other metadata, set by commands and plugins. Defaults to an empty map.

data_source and path_columns are required.

Example, from open --raw data.json:

{
  "data_source": {
    "FilePath": "/home/user/data.json"
  },
  "path_columns": [],
  "content_type": "application/json",
  "custom": {}
}

LabeledError

Documentation

A flexible, generic error type, with any number of labeled spans.

FieldTypeDescription
msgstringThe main error message to show at the top of the error.
labelsErrorLabel array?Spans and messages to label the error in the source code.
codestring?A unique machine- and search-friendly code that can be matched against, e.g. nu::shell::missing_config_value
urlstring?A URL that links to additional information about the error.
helpstring?Additional help for the error, usually a hint about what the user might try.
innerLabeledError array?Additional errors referenced by the error, possibly the cause(s) of this error.

Most of the fields are not required - only msg must be present. ErrorLabel (in the labels array) is as follows:

FieldTypeDescription
textstringThe message for the label.
spanSpanThe span in the source code that the label should point to.

Tips

When reading the Rust source code for the nu-plugin crates, many places where LabeledError is specified here are actually represented as ShellError in that implementation. However, ShellError always serializes as if it were LabeledError, so the difference between the two can be ignored within the protocol.

Example:

{
  "msg": "A really bad error occurred",
  "labels": [
    {
      "text": "I don't know, but it's over nine thousand!",
      "span": {
        "start": 9001,
        "end": 9007
      }
    }
  ],
  "code": "my_plugin::bad::really_bad",
  "url": "https://example.org/my_plugin/error/bad/really_bad.html",
  "help": "you can solve this by not doing the bad thing",
  "inner": [
    {
      "msg": "The bad thing"
    }
  ]
}

Config

Documentation

This struct describes the configuration of Nushell. It is quite large and frequently changing, so please refer to the Rust documentation if there is anything you need from it.

It's a map with the same top-level keys as $env.config, 39 of them in 0.117.0: filesize, table, ls, clip, color_config, footer_mode, float_precision, recursion_limit, use_ansi_coloring, completions, edit_mode, show_hints, hinter, status_line, history, keybindings, abbreviations, menus, hooks, rm, shell_integration, buffer_editor, show_banner, bracketed_paste, render_right_prompt_on_last_line, explore, tui, cursor_shape, datetime_format, error_style, error_lines, display_errors, use_kitty_protocol, highlight_resolved_externals, auto_cd_implicit, duration_max_unit, max_last_result_size, plugins, and plugin_gc. The nested keys also follow $env.config, so the configuration reference describes what each one means. The values are serialized from Nushell's Rust types, though, so they don't always look like what $env.config shows:

  • A setting that takes one of a few words is the Rust variant name, which is capitalized: "edit_mode": "Emacs", "use_ansi_coloring": "Auto", "history": {"file_format": "Plaintext", ...}.
  • A setting with a choice of forms is a tagged map, such as "footer_mode": {"RowCount": 25} or "trim": {"Wrap": {"try_to_keep_words": true}} in table.
  • Durations are integers of nanoseconds, as in "plugin_gc": {"default": {"enabled": true, "stop_after": 10000000000}, ...}, except table.batch_duration, which uses the {"secs": 1, "nanos": 0} form. Filesizes, such as max_last_result_size, are integers of bytes.
  • Settings that can hold any Nushell value are Values. These are buffer_editor, the hooks in hooks, the entries of color_config, explore, tui, and plugins, and the fields of each entry in keybindings and menus. For example, "buffer_editor": {"Nothing": {"span": {"start": 0, "end": 0}}}.

Ordering

Documentation

We serialize the Rust Ordering type as literal strings, for example:

'Less'; // left hand side is less than right hand side
'Equal'; // both values are equal
'Greater'; // left hand side is greater than right hand side

Operator

Documentation

Serialized with serde's default enum representation, as a map from the operator's group to its name. These are all of the operators in 0.117.0:

Serialized formNushell operator
{"Comparison": "Equal"}==
{"Comparison": "NotEqual"}!=
{"Comparison": "LessThan"}<
{"Comparison": "GreaterThan"}>
{"Comparison": "LessThanOrEqual"}<=
{"Comparison": "GreaterThanOrEqual"}>=
{"Comparison": "RegexMatch"}=~
{"Comparison": "NotRegexMatch"}!~
{"Comparison": "In"}in
{"Comparison": "NotIn"}not-in
{"Comparison": "Has"}has
{"Comparison": "NotHas"}not-has
{"Comparison": "StartsWith"}starts-with
{"Comparison": "NotStartsWith"}not-starts-with
{"Comparison": "EndsWith"}ends-with
{"Comparison": "NotEndsWith"}not-ends-with
{"Comparison": "OlderThan"}older-than
{"Comparison": "NewerThan"}newer-than
{"Math": "Add"}+
{"Math": "Subtract"}-
{"Math": "Multiply"}*
{"Math": "Divide"}/
{"Math": "FloorDivide"}//
{"Math": "Modulo"}mod
{"Math": "Pow"}**
{"Math": "Concatenate"}++
{"Boolean": "And"}and
{"Boolean": "Or"}or
{"Boolean": "Xor"}xor
{"Bits": "BitAnd"}bit-and
{"Bits": "BitOr"}bit-or
{"Bits": "BitXor"}bit-xor
{"Bits": "ShiftLeft"}bit-shl
{"Bits": "ShiftRight"}bit-shr
{"Assignment": "Assign"}=
{"Assignment": "AddAssign"}+=
{"Assignment": "SubtractAssign"}-=
{"Assignment": "MultiplyAssign"}*=
{"Assignment": "DivideAssign"}/=
{"Assignment": "ConcatenateAssign"}++=

A plugin receives an operator in the Operation custom value op only when its custom value is on the left side. Compound assignments such as += and ++= arrive as the matching Math operator, so in practice a plugin never receives an Assignment operator. The has and not-has operators reverse their operands, so $list has $value arrives as In on $value when $value is the custom value.

SignalAction

The SignalAction enum is used to specify actions that the plugin should take in response to signals from the engine.

VariantDescription
InterruptIndicates an interrupt signal (e.g., Ctrl+C) was received. Plugins should pause, stop, or end their operation.
ResetIndicates a reset signal from the engine’s reset_signals function. Plugins should reset any internal signal states.

This enum can be used in conjunction with register_signal_handler to perform specific tasks when each signal type is received.

Edit this page on GitHub
Contributors: Devyn Cairns, Stefan Holderbach, Andy Gayton, Jan Klass, fdncred
Prev
Plugins