本页列出 Paneflow 0.20.0 实现的全部 Lua API。函数说明保留英文。Paneflow 只向
全局 `paneflow` 表添加 API。它运行 Lua 5.4，并提供 `table`、`string`、`utf8`、
`math`、`coroutine`、`io`、`os` 和 `package` 库。`io.popen` 和 `os.execute`
会抛出错误：请用 `paneflow.exec` 运行程序，它从不启动 shell。`debug` 不会加载，
C 模块也无法加载。使用指南见 [Lua 脚本](/docs/scripting/lua)。

## 各函数的可用位置

Paneflow 在两个地方运行 Lua：配置文件 `init.lua`（位于 `$PANEFLOW_HOME`，否则为
`~/.paneflow`）和脚本。下面每个函数都带有标签，说明它在哪里可用：

| 标签 | 说明 |
| --- | --- |
| `Config` | 在 `init.lua` 中可用，worker 会加载它，并在文件变化时重新加载。 |
| `Script` | 在用 `paneflow do` 运行的脚本中可用。 |
| `Config at load` | 仅在加载时可用，即文件从上到下执行期间。 |
| `Config later` | 仅在之后可用，即在动作、事件处理函数或计时器中。 |

凡是不能完全可用的情况，都写在函数说明的开头。

- **Raises an error**：调用会带着消息中止代码。
- **No effect**：调用会被接受，但没有实际作用。脚本的按键绑定永远不会到达窗口。
- **Fails**：调用返回 `nil` 和原因。

会等待的函数（调用、`paneflow.wait`、`paneflow.sleep`、`paneflow.exec`、
`paneflow.ui`）在用 `coroutine.create` 或 `coroutine.wrap` 创建的协程中会抛出错误。

## 动作与按键绑定

### `paneflow.action(spec)`

Works in: Config at load, Script. Config, later: raises an error · Script: top level only, and the action exists only in that script.

Declare an action while init.lua loads. Keys, the command palette, `paneflow do <action>`, the API and agents can run it; agents only when `agents = true`. A later declaration with the same name replaces the earlier one, with a warning.

| spec | Description |
| --- | --- |
| `name` | Lowercase letters, digits and underscores |
| `title` | Shown in the command palette |
| `description` | Optional |
| `category` | Palette group, Actions by default |
| `keywords` | Extra words the palette filter matches |
| `args` | Argument types such as "string" or "number?", or JSON Schema tables |
| `agents` | Whether agents may run the action, false by default |
| `run` | `function(ctx, args)`, whose return value is the action's result |

```lua
paneflow.action{
  name = "dev_workspace",
  title = "Open a dev workspace",
  args = { cwd = "string" },
  run = function(ctx, args)
    return paneflow.workspace.create{ name = "dev", cwd = args.cwd }
  end,
}
```

A run is stopped after 30 s; a `paneflow.ui` prompt pauses that limit while it waits. Actions can invoke each other 16 deep.

### `paneflow.invoke(name[, args])`

Works in: Config, Script. Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Run an action with arguments and return what it returned, or nil and a message when it fails. In a script, an action the script declared runs in the script; any other runs on the worker.

### `paneflow.bind(key, action[, args])`

Works in: Config at load. Config, later: raises an error · Script: no effect.

Bind a key to an action name while init.lua loads. `key` uses the syntax of paneflow.json shortcuts, such as `"ctrl-alt-d"`. `action` is a Lua action or a built-in action name, and `args` are arguments for a Lua action.

A shortcut set in paneflow.json for the same key always wins. Otherwise the binding replaces the window's default for that key.

```lua
paneflow.bind("ctrl-alt-d", "dev_workspace", { cwd = "/srv/app" })
```

### `paneflow.unbind(key)`

Works in: Config at load. Config, later: raises an error · Script: no effect.

Remove this file's bindings of a key and drop the window's default for it.

### `paneflow.bindings()`

Works in: Config, Script. Script: lists only the script's own bindings.

Return the bindings init.lua declared, each a table with `key`, `action`, `args` and `source`.

### `paneflow.client.queue(name)`

Works in: Config, Script. Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Queue a built-in window action, by a name from `paneflow.client.list_actions`. Inside an action run, it runs once `run` returns without error and is dropped if the run fails. Anywhere else it is sent at once.

## 调用 Paneflow

### `paneflow.call(method[, params])`

Works in: Config, Script. Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Call any method by its full name. Returns the result, or nil, a message and the error code.

```lua
local result, message, code = paneflow.call("surface.list")
```

### `paneflow.<namespace>.<method>{...}`

Works in: Config, Script. Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Every method of the [API](/docs/reference/api) is a function that takes the method's parameters as one table and returns like `paneflow.call`.

The streams (`agent.follow`, `events.follow` and `events.subscribe`) cannot be called; react to events with `paneflow.on` or `paneflow.wait`.

```lua
local result = paneflow.surface.read{ surface_id = 7, lines = 20 }
```

## 事件与计时器

| Event | Fields |
| --- | --- |
| `workspace.created` | - |
| `workspace.closed` | - |
| `workspace.renamed` | - |
| `workspace.selected` | - |
| `tab.created` | - |
| `tab.closed` | - |
| `tab.renamed` | - |
| `tab.selected` | - |
| `pane.created` | - |
| `pane.closed` | - |
| `pane.focused` | - |
| `surface.created` | - |
| `surface.closed` | - |
| `surface.renamed` | - |
| `layout.changed` | `revision` |
| `terminal.cwd_changed` | `cwd` |
| `terminal.title_changed` | `title` |
| `terminal.bell` | `bell_at_ms` |
| `terminal.exited` | `lifecycle` (`exited`, `failed`, `lost` or `unverified`); `exit_code` and, when a signal ended it, `signal`, when `lifecycle` is `exited` |
| `agent.state_changed` | `tool`, `previous` and `state` (`busy`, `idle`, `attention` or `errored`) |
| `config.reloaded` | `ok`, `found`, `path`, `actions`, `bindings`, `errors`, `warnings` and, when there is one, the first `problem` |
| `grant.changed` | `revision`, `revoked` and `grants` |
| `events.resync` | None: sent when buffered events were dropped |

## 事件类型

`paneflow.on` 和 `paneflow.wait` 从 worker 接收这些事件。各事件的触发时机见 [事件](/docs/reference/events)。`ev` 包含 `type`、
`seq`、事件带有时的 `session`，以及下列字段。surface、窗格、标签页和工作区的
ID 在 `ctx` 中。在 `paneflow do` 中，除非使用 `--all`，脚本只接收自己工作区的事件。

| Event | Fields |
| --- | --- |
| `workspace.created` | - |
| `workspace.closed` | - |
| `workspace.renamed` | - |
| `workspace.selected` | - |
| `tab.created` | - |
| `tab.closed` | - |
| `tab.renamed` | - |
| `tab.selected` | - |
| `pane.created` | - |
| `pane.closed` | - |
| `pane.focused` | - |
| `surface.created` | - |
| `surface.closed` | - |
| `surface.renamed` | - |
| `layout.changed` | `revision` |
| `terminal.cwd_changed` | `cwd` |
| `terminal.title_changed` | `title` |
| `terminal.bell` | `bell_at_ms` |
| `terminal.exited` | `lifecycle` (`exited`, `failed`, `lost` or `unverified`); `exit_code` and, when a signal ended it, `signal`, when `lifecycle` is `exited` |
| `agent.state_changed` | `tool`, `previous` and `state` (`busy`, `idle`, `attention` or `errored`) |
| `config.reloaded` | `ok`, `found`, `path`, `actions`, `bindings`, `errors`, `warnings` and, when there is one, the first `problem` |
| `grant.changed` | `revision`, `revoked` and `grants` |
| `events.resync` | None: sent when buffered events were dropped |

## 运行程序

### `paneflow.exec(argv[, opts])`

Works in: Config, Script. Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Run a program from an argument list, never through a shell, and wait for it. Returns the result, or nil and a message.

| opts | Description |
| --- | --- |
| `cwd` | Directory to run in |
| `env` | Variables to set, `false` removes one |
| `clear_env` | Start from an empty environment |
| `stdin` | Text to write to stdin, or `false` for no stdin |
| `timeout` | Seconds before the process tree is terminated |
| `stdout` | `false` discards, a function receives output as it arrives |
| `stderr` | `false` discards, a function receives output as it arrives |
| `text` | Decode output as text and turn CRLF into LF, true by default |
| `detach` | Keep the program running when the scope that started it ends; its output is discarded unless a function receives it |

| result | Description |
| --- | --- |
| `code` | The exit code, nil when a signal ended the program |
| `signal` | The signal that ended the program, on Unix |
| `stdout` | Captured output, nil when stdout = false |
| `stderr` | Captured errors, nil when stderr = false |
| `timed_out` | True when the timeout stopped the program |
| `ok` | True when the code is 0 and the program did not time out |

```lua
local result = paneflow.exec({ "git", "status", "--short" }, { cwd = "/srv/app" })
if result and result.ok then
  paneflow.log("info", result.stdout)
end
```

Each program runs in its own process tree. At the timeout it gets TERM, then KILL 2 s later.

### `paneflow.exec.start(argv[, opts])`

Works in: Config, Script.

Start a program and return a handle at once, or nil and a message. It takes the options of `paneflow.exec`.

The program is stopped when the code that started it ends (the init.lua load, an action run, a handler call or a timer callback), unless `detach` is set.

### `handle:wait([seconds])`

Works in: Config, Script. Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Wait for the program to end and return its result; nil and "timeout" when `seconds` pass first.

### `handle:write(data)`

Works in: Config, Script. Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Write to the program's stdin. Returns true, or nil and a message.

### `handle:close_stdin()`

Works in: Config, Script.

Close the program's stdin.

### `handle:kill([signal])`

Works in: Config, Script.

Send a signal to the program, `TERM` by default.

### `handle:running()`

Works in: Config, Script.

Return whether the program is still running.

### `handle.pid`

Works in: Config, Script.

The program's process id. Call the handle's methods with a colon, as `handle:wait(5)`.

## 询问用户

### `paneflow.ui.input(spec)`

Works in: Config later, Script. Config, at load: fails with "failed" · Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Ask the user for a line of text in every window that can show it; the first answer wins and the action's 30 s limit pauses while it waits.

Returns the text, or nil and a reason when nobody answers: "cancelled", "timeout", "no_client", "unsupported", "busy", "rate_limited" or "failed" (with a detail).

| spec | Description |
| --- | --- |
| `title` | Required |
| `body` | Shown under the title, line breaks kept; at most 16384 bytes |
| `placeholder` | Optional |
| `value` | Text the field starts with |
| `confirm` | Label of the confirming row |
| `timeout` | Seconds before the prompt ends with "timeout", 300 by default, at most 3600 |

```lua
local branch, reason = paneflow.ui.input{ title = "New branch", placeholder = "feature/" }
```

### `paneflow.ui.pick(spec)`

Works in: Config later, Script. Config, at load: fails with "failed" · Raises inside a coroutine made with `coroutine.create` or `coroutine.wrap`.

Ask the user to choose among items; the answer is an id, a list of ids with `multiple`, or `{ text = ... }` with `allow_other`. It fails like `paneflow.ui.input` and takes its fields, plus:

| spec | Description |
| --- | --- |
| `items` | At most 2000; a string is its own id and title |
| `multiple` | Tick several items; the answer is the list of ids in the order of items |
| `allow_other` | Accept typed text that matches no item; the answer is `{ text = ... }` |

| item | Description |
| --- | --- |
| `id` | Returned when the item is chosen |
| `title` | The label shown and filtered on, the id by default |
| `subtitle` | Optional |
| `icon` | `document`, `folder`, `branch`, `terminal`, `code`, `server`, `database`, `package`, `globe`, `link`, `person`, `tag`, `clock`, `star`, `gear` or `plus` |
| `detail` | Text shown at the end of the row |
| `selected` | Starts ticked when `multiple` is true |

## 布局

### `paneflow.layout.pane([spec])`

Works in: Config, Script.

Build a pane node for a layout document, as `paneflow.workspace.create{ layout = ... }` and `paneflow.workspace.restore_layout` take. `spec` describes the pane's one surface (`command`, `cwd`, `name`, `env`, `focus` and the other surface fields), or lists several in `surfaces`.

```lua
paneflow.workspace.create{
  name = "review",
  layout = paneflow.layout.vertical(0.5,
    paneflow.layout.pane{ command = "claude" },
    paneflow.layout.pane{ command = "codex" }),
}
```

### `paneflow.layout.horizontal(ratio, first, second)`

Works in: Config, Script.

Stack two nodes, the first taking `ratio` of the height.

### `paneflow.layout.vertical(ratio, first, second)`

Works in: Config, Script.

Put two nodes side by side, the first taking `ratio` of the width.

## 其他函数

### `paneflow.json.encode(value[, pretty])`

Works in: Config, Script.

Encode a value; a table with keys 1 to n becomes an array, any other table an object. Returns the JSON, or nil and a message.

### `paneflow.json.decode(text)`

Works in: Config, Script.

Decode JSON; null becomes nil and integers stay integers. Returns the value, or nil and a message.

### `paneflow.log(level, message)`

Works in: Config, Script.

Log a message at the `debug`, `info`, `warn` or `error` level.

## 脚本值

### `paneflow.args`

Works in: Script. Config: an empty table.

The key=value pairs or the `--args` JSON given to `paneflow do`. An action receives its arguments as the second parameter of `run` instead.

### `paneflow.ctx`

Works in: Config, Script.

Where the code runs. Handlers and timers receive the same table as their first parameter.

| ctx | Description |
| --- | --- |
| `surface_id` | The surface the script, handler or timer belongs to |
| `pane_id` | The pane that holds it |
| `tab_id` | The tab that holds it |
| `workspace_id` | The layout workspace that holds it |
| `origin` | What started this code: "cli" in a script, "event" in init.lua, "timer" in a timer |

## 限制

- `init.lua` 每次加载都会得到全新的 Lua 状态，内存上限为 256 MiB。加载失败时，
  之前的配置保持生效。
- `init.lua` 在最后一次修改 300 ms 后重新加载，也可用 `paneflow config reload`
  重新加载。
- 动作运行 30 秒后会被停止，动作之间最多可嵌套调用 16 层。
- `paneflow do` 默认没有内存上限和时限，除非使用 `--memory-limit` 或 `--deadline`。