> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Run shell command

Run a shell command or script in the workspace and return its exit code and output.

One endpoint serves three modes:

| Mode | Request | Response |
| - | - | - |
| Run (default) | no query flags | One JSON result when the command ends. |
| Stream | `stream=true` | NDJSON output records as they are produced, then a status record. |
| Explain | `explain=true` | The policy decision. Nothing runs. |

A `200` means the request was accepted, not that the command succeeded. Check `exit_code`. A policy refusal also returns `200`; check `decision` to know whether a policy refused anything. See Refused commands below.

The request stays open until the command ends, and closing it cancels the command. To leave work running, end the command with `&`; it returns at once and the work appears under [jobs](https://docs.mirage.strukto.ai/api/operations/jobs/list-jobs.md). Every result carries a `line_id` for the [lines](https://docs.mirage.strukto.ai/api/operations/lines/get-command.md) endpoints.

To send input, use a `multipart/form-data` body with a `stdin` part, or set `open_stdin=true` with `stream=true` to write while the command runs. See [Streaming and stdin](https://docs.mirage.strukto.ai/api/streaming.md).

## Stream output

Set `stream=true` to receive output as it is produced. Each line is one JSON record: output records carry base64 `data`, and the last record carries `status` and the final `result`.

```bash
curl --no-buffer --request POST \
  --url 'http://127.0.0.1:8765/v1/workspaces/{workspace_id}/shell?stream=true' \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '{"command":"echo hello"}'
```

```json
{"stream":"stdout","data":"aGVsbG8K"}
{"status":"done","result":{"exit_code":0,"stdout":"","stderr":"","decision":null,"line_id":"line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37"},"error":null}
```

## Explain a command

Set `explain=true` to get the policy decision without running the command. The response has one `node` per part of the line; the example below is trimmed to one command.

```bash
curl --request POST \
  --url 'http://127.0.0.1:8765/v1/workspaces/{workspace_id}/shell?explain=true' \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '{"command":"echo hello"}'
```

```json
{
  "line": "echo hello",
  "outcome": "allow",
  "reason": "",
  "decision": null,
  "exit_code": 0,
  "node": {
    "type": "line",
    "text": "echo hello",
    "children": [
      {
        "type": "command",
        "text": "echo hello",
        "command": "echo",
        "outcome": "allow",
        "children": []
      }
    ]
  }
}
```

## Refused commands

A policy refusal returns `200`. `decision` is set whenever a policy refused something on the line, and is `null` otherwise. The exit code alone does not tell you:

* A command refused before it runs usually exits `126` with `<command>: Permission denied`.
* A refusal about a path appears as that path's own error, such as exit `1`.
* A policy that judges a command after it ran sets exit `126` but does not undo its effects, and output already sent stays sent. A policy that judges the whole line after it ran drops the line's output.
* A pipeline exits with its last stage's status unless `pipefail` is set, so a refused earlier stage can leave the exit code at `0`.

A refusal does not always mean nothing ran, so do not retry a refused command blindly.

A command denied before it ran:

```json
{
  "exit_code": 126,
  "stdout": "",
  "stderr": "rm: Permission denied\n",
  "decision": {
    "kind": "deny",
    "reason": "rm is not allowed in this workspace",
    "policy": "PermissionsPolicy",
    "ask_id": null,
    "matched": {
      "command": ["rm"],
      "flags": [],
      "keys": []
    }
  },
  "line_id": "line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c38"
}
```

## Keep stdin open

With `stream=true` and `"open_stdin": true`, the first record carries the `line_id`, and you write input to that line while the command runs. See [Streaming and stdin](https://docs.mirage.strukto.ai/api/streaming.md) for the full flow.

```json 200
{
  "exit_code": 0,
  "stdout": "hello\n",
  "stderr": "",
  "decision": null,
  "line_id": "line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37"
}
```

> [accordion] Errors
>
> | Status | Meaning |
> | - | - |
> | `400` | The request is malformed or its options conflict. The body is not JSON (`invalid_json`), a field is missing, unknown or of the wrong type (`missing_field`, `unknown_field`, `invalid_value`, with `param`; a field of the multipart `request` part is named as in a JSON body), or `machine` names one the workspace does not have (`invalid_value`, `param` `machine`), refused before anything runs. Or the multipart parts are malformed, missing or out of order, or the options conflict, as `stream` with `explain`, `open_stdin` without `stream=true` or with a stdin part, or `explain` with a multipart body, `cwd`, `machine` or `open_stdin` set to `true` (`invalid_request`). |
> | `401` | The token is missing or wrong (`unauthorized`). |
> | `404` | The workspace, session, job, file or route does not exist, or the caller may not see it (`not_found`). |
> | `409` | Another server owns command execution for this workspace (`workspace_busy`; the message names that server), or the workspace is stopped (`workspace_stopped`). |
> | `429` | Past a rate limit (`rate_limited`), or a new session past max\_sessions (`session_limit`). |
> | `413` | The request body, a multipart part, or stdin exceeds its size limit (`too_large`). |
> | `499` | The running shell job was canceled (`canceled`). |
> | `500` | The command's job failed internally (`internal`). The message is always `internal server error`. The job's own error stays readable as `error` at `GET /v1/workspaces/&#123;workspace_id&#125;/lines/&#123;line_id&#125;`, and in a stream's final record. |
> | `503` | The server is shutting down and accepts no new commands (`shutting_down`). |
>
> See [error examples and recovery steps](https://docs.mirage.strukto.ai/api/errors.md). The [complete OpenAPI contract](https://github.com/strukto-ai/mirage/blob/main/docs/openapi.yaml) includes every response schema.


## OpenAPI

````yaml /openapi.yaml post /v1/workspaces/{workspace_id}/shell
openapi: 3.2.0
info:
  title: Mirage API
  version: '0.1'
servers:
  - url: http://127.0.0.1:8765
    description: A local server on its default port
security:
  - bearerAuth: []
tags:
  - name: Workspace operations
    x-group: Workspaces
  - name: Workspaces
    x-group: Lifecycle
    parent: Workspace operations
  - name: Sessions
  - name: Shell
    parent: Workspace operations
  - name: VFS
    parent: Workspace operations
  - name: Tools
  - name: Documents
    x-group: Agent Instructions
    parent: Workspace operations
  - name: Snapshots
  - name: Templates
    parent: Configuration
  - name: Saved VFS
    x-group: VFS
    parent: Configuration
  - name: Saved CLIs
    x-group: CLI
    parent: Configuration
  - name: Saved machines
    x-group: Machine
    parent: Configuration
  - name: Configuration
  - name: Policies
    parent: Configuration
  - name: Asks
    parent: Workspace operations
    x-group: Approval requests
  - name: Lines
    parent: Workspace operations
    x-group: Commands
  - name: Jobs
    parent: Workspace operations
  - name: Processes
    parent: Workspace operations
  - name: Machines
    parent: Workspace operations
  - name: Server
  - name: Service
    parent: Server
  - name: Daemon
    parent: Server
  - name: Auth
paths:
  /v1/workspaces/{workspace_id}/shell:
    post:
      tags:
        - Shell
      summary: Run shell command
      operationId: shell_v1_workspaces__workspace_id__shell_post
      parameters:
        - $ref: '#/components/parameters/workspaceId'
        - $ref: '#/components/parameters/sessionId'
        - name: explain
          in: query
          description: >-
            Return the policy decision for the command without running it. Only
            `command` is evaluated; `record` is ignored and `open_stdin` may be
            `false`. A multipart body, a body that sets `cwd` or `machine` (an
            empty string counts as set, `null` does not), or `open_stdin` set to
            `true`, is rejected with `400`. Cannot be combined with `stream`.
          required: false
          schema:
            type: boolean
            default: false
        - name: stream
          in: query
          description: >-
            Return output as it is produced, as NDJSON records ending with a
            status record. Cannot be combined with `explain`.
          required: false
          schema:
            type: boolean
            default: false
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ShellRequest'
            example:
              command: echo hello
          multipart/form-data:
            schema:
              type: object
              properties:
                request:
                  $ref: '#/components/schemas/ShellRequest'
                stdin:
                  type: string
                  format: binary
                  description: Up to 64 MiB, read as it arrives.
              required:
                - request
      responses:
        '200':
          description: >-
            The request was accepted. By default the body is one JSON result.
            With `explain=true` it is the policy decision and nothing ran. With
            `stream=true` it is NDJSON. A `200` does not mean the command
            succeeded; check `exit_code`.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: '#/components/schemas/ShellResult'
                  - $ref: '#/components/schemas/ShellExplanation'
              example:
                exit_code: 0
                stdout: |
                  hello
                stderr: ''
                decision: null
                line_id: line_019a5e2c-7b41-7c3e-9f20-4d8e1a6b5c37
            application/x-ndjson:
              schema:
                type: string
                description: >-
                  One JSON record per line. An output record has `stream`
                  (`stdout` or `stderr`) and base64 `data`. The last record has
                  `status` (`done`, `failed` or `canceled`), `result` and
                  `error`; its `result.stdout` and `result.stderr` are empty
                  because the output was already sent. With `open_stdin`, a
                  `line_id` record comes first.
      x-codeSamples:
        - lang: bash
          label: Run a command
          source: |
            curl --request POST \
              --url 'http://127.0.0.1:8765/v1/workspaces/{workspace_id}/shell' \
              --header 'Authorization: Bearer <token>' \
              --header 'Content-Type: application/json' \
              --data '{"command":"echo hello"}'
components:
  parameters:
    workspaceId:
      name: workspace_id
      in: path
      required: true
      description: Workspace ID.
      schema:
        type: string
      example: demo
    sessionId:
      name: session_id
      in: query
      required: false
      description: Session ID to use. If omitted, the default session is used.
      schema:
        type: string
      example: analysis
  schemas:
    ShellRequest:
      type: object
      properties:
        command:
          type: string
          description: Shell command or script to execute.
        cwd:
          anyOf:
            - type: string
            - type: 'null'
          description: >-
            Working directory for this command only. `null` is the same as
            omitting it.
        machine:
          anyOf:
            - type: string
            - type: 'null'
          description: >-
            Name of an entry under `machines` in the workspace config. If
            omitted or `null`, the machine is selected automatically. A name the
            workspace does not have is refused with `400` before anything runs.
        record:
          anyOf:
            - type: boolean
            - type: 'null'
          default: true
          description: >-
            Include this command in session history. Set `false` to keep it out;
            `null` is the default.
        open_stdin:
          anyOf:
            - type: boolean
            - type: 'null'
          default: false
          description: >-
            Keep stdin open for additional input. Requires `stream=true` and no
            stdin part; the first response record contains `line_id`. `null` is
            the default.
      required:
        - command
      additionalProperties: false
    ShellResult:
      type: object
      description: Returned by default, when the command has ended.
      properties:
        exit_code:
          type: integer
          description: >-
            Exit status of the command. `0` is success and `127` command not
            found. `126` usually means a policy refused the command before it
            ran, but a refusal can leave another code; check `decision`.
        stdout:
          type: string
          description: Standard output, decoded as UTF-8. Empty in a stream's final record.
        stderr:
          type: string
          description: Standard error, decoded as UTF-8. Empty in a stream's final record.
        decision:
          anyOf:
            - $ref: '#/components/schemas/PolicyDecision'
            - type: 'null'
          description: >-
            Set when a policy refused the command or any part of it, otherwise
            `null`. Part of the command may have run, and the exit code need not
            be `126`.
        line_id:
          type: string
          description: >-
            Command execution ID. Use it with `GET
            /v1/workspaces/{workspace_id}/lines/{line_id}`.
      required:
        - exit_code
        - stdout
        - stderr
        - decision
        - line_id
      title: Result
    ShellExplanation:
      allOf:
        - $ref: '#/components/schemas/Explanation'
        - type: object
          properties:
            line:
              type: string
            exit_code:
              type: integer
              description: >-
                What the line would exit with. A line refused whole exits with
                the refusal's code. A line where something is refused or asks
                exits as the run does, with every command the policies let
                through taken to succeed, so `sort x; ls` exits `0` even when
                `sort` is refused. A line nothing refuses exits `0`, whatever
                its commands would return.
            stderr:
              type: string
              description: >-
                The refusals the line would print, empty when nothing is
                refused.
            node:
              $ref: '#/components/schemas/ExplainNode'
      description: >-
        A line refused whole, by a rule before any of it runs or by the
        placement that would run it, answers with that refusal. Otherwise
        `outcome` is the strictest of every command on the line and every
        redirect no command owns (`{ cat; } < f`, `> f`), `deny` before `ask`
        before `allow`, and `reason`, `source` and `decision` come from the
        first part that gives it.
      title: Explanation (explain=true)
    PolicyDecision:
      type: object
      description: >-
        Why a policy refused a command or part of it. A refusal can come after
        the command ran and does not undo what it did.
      properties:
        kind:
          type: string
          enum:
            - deny
            - pending
            - failed
          description: >-
            `deny` when a policy refused it, `pending` when it waits for an
            approval, `failed` when a policy raised an error and so refused by
            default.
        reason:
          type: string
          description: Reason given by the policy or the approval request.
        policy:
          type: string
          description: Name of the policy that refused. Empty for `pending`.
        ask_id:
          anyOf:
            - type: string
            - type: 'null'
          description: Approval request ID, for `pending`.
        matched:
          anyOf:
            - $ref: '#/components/schemas/PolicyMatch'
            - type: 'null'
          description: >-
            What fired in the profile rule that refused, for `deny`. Null for
            any other refusal.
      required:
        - kind
        - reason
        - policy
        - ask_id
        - matched
    Explanation:
      type: object
      description: >-
        Policy evaluation for a request without executing it. Returned when
        `explain=true`.
      properties:
        outcome:
          type: string
          enum:
            - allow
            - deny
            - ask
          description: >-
            `ask` stays `ask` when an approval already covers the request; then
            `decision` is `null`.
        reason:
          type: string
          description: >-
            Reason returned by the policy that determined the outcome. Empty
            when nothing refuses or asks.
        source:
          type: string
          description: >-
            Where in the profile the deciding tree is written, `top` or a mount
            section such as `mounts./runbook`. Empty when no tree decided.
        answers:
          type: array
          items:
            $ref: '#/components/schemas/PolicyAnswer'
          description: Every policy's answer, in the order the policies are asked.
        decision:
          anyOf:
            - $ref: '#/components/schemas/PolicyDecision'
            - type: 'null'
          description: The record a refused request carries. `null` when it would run.
      required:
        - outcome
        - reason
        - source
        - answers
        - decision
    ExplainNode:
      type: object
      description: >-
        One part of the line. A `command` node carries its own policy outcome;
        other nodes group their children.
      properties:
        type:
          type: string
          description: What the part is, such as line, pipeline or command.
        text:
          type: string
          description: The part as written.
        children:
          type: array
          items:
            $ref: '#/components/schemas/ExplainNode'
        command:
          type: string
          description: The command name. Command nodes only.
        words:
          type: array
          items:
            $ref: '#/components/schemas/ExplainWord'
          description: The command line word by word. Command nodes only.
        outcome:
          type: string
          enum:
            - allow
            - deny
            - ask
          description: Command nodes only.
        reason:
          type: string
          description: Command nodes only.
        source:
          type: string
          description: >-
            Where in the profile the deciding rule is written. Command nodes
            only.
        decision:
          anyOf:
            - $ref: '#/components/schemas/PolicyDecision'
            - type: 'null'
          description: Command nodes only.
        answers:
          type: array
          items:
            $ref: '#/components/schemas/PolicyAnswer'
          description: Command nodes only.
        exit_code:
          type: integer
          description: >-
            What the command is refused with, 0 when it runs. Command nodes
            only.
        stderr:
          type: string
          description: Command nodes only.
        machine:
          type:
            - string
            - 'null'
          description: The machine the command is routed to. Command nodes only.
      required:
        - type
        - text
        - children
    PolicyMatch:
      type: object
      description: >-
        The command path, options and operand or value keys of the tree entry
        that refused the line, or the line's own command path when the root
        `"*"` refused it.
      properties:
        command:
          type: array
          items:
            type: string
          description: Command name and its subcommands, by their canonical names.
        flags:
          type: array
          items:
            type: string
          description: >-
            Options the pattern names, by their canonical spelling. Empty when
            it names none.
        keys:
          type: array
          items:
            type: string
          description: >-
            The operand and value keys the tree names on the way to the entry
            that fired, as written, such as `secret*` for `echo secret1` under
            `{echo: {operands: {"secret*": deny}}}`. Empty when it names none.
      required:
        - command
        - flags
        - keys
    PolicyAnswer:
      type: object
      description: One policy's answer to a request.
      properties:
        kind:
          type: string
          enum:
            - deny
            - ask
            - route
        reason:
          type: string
          description: Reason the policy gave.
        policy:
          type: string
          description: >-
            Name of the policy. Rules written in the profile answer as
            `PermissionsPolicy`.
        machine:
          anyOf:
            - type: string
            - type: 'null'
          description: Machine the request is routed to. Only for `route`.
      required:
        - kind
        - reason
        - policy
    ExplainWord:
      type: object
      properties:
        text:
          type: string
          description: The word as the command receives it, expanded.
        kind:
          type: string
          enum:
            - name
            - subcommand
            - option
            - value
            - operand
            - redirect
        option:
          type:
            - string
            - 'null'
          description: For a value, the option word that takes it, as typed.
        path:
          type:
            - string
            - 'null'
          description: The virtual path the word names.
      required:
        - text
        - kind
        - option
        - path
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        The server's token (MIRAGE_AUTH_TOKEN) or a JWT. A daemon in the default
        local mode with no token accepts requests without one.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.