Paneflow は 2 つの場所で Lua 5.4 を実行します。`paneflow do` は、あなたの
terminal や agent の shell tool から、独立した process で script を実行
します。各 Paneflow home の background process である worker は
`init.lua` を読み込み、あなたが command palette で選んだとき、または
script や agent が求めたときに、そこで宣言された action を実行します。

どちらも CLI と同じ registry にアクセスします。各 method は、その名前を
持つ Lua 関数です。`surface.list` は `paneflow.surface.list`、
`action.invoke` は `paneflow.action.invoke` です。script は多くの
method を呼び出して小さな結果を 1 つ返せるので、agent は method ごとに
1 回の tool call を使う代わりに、1 回の shell call で済みます。

**agent 向け TL;DR。** `paneflow api list` ですべての method を、
`paneflow api describe <method>` でその parameter を確認します。chunk は
`paneflow do -e 'return paneflow.surface.list()'` で実行します。実行
できる action は `paneflow actions` で一覧し、
`paneflow do <name> key=value --wait 20s` で 1 つ実行します。exit code
`4` と `running <run_id>` は、action がまだ実行中であることを意味します。
`paneflow do --resume <run_id> --wait 20s` で続けてください。

## script を実行するには？

`paneflow do` は Lua file、`-e` の後の chunk、または standard input から
script を読む `-` を受け取ります。`.lua` で終わるもの、または path
separator を含むものは file として扱われます。それ以外の単語は action の
名前です（後述）。script が返した値は 1 行の JSON として出力されます。

```lua
-- panes.lua
local listed = paneflow.surface.list()
return { panes = #listed.surfaces, who = paneflow.args.who }
```

```text
$ paneflow do panes.lua who=arthur
{"panes":2,"who":"arthur"}

$ paneflow do -e 'return #paneflow.surface.list().surfaces'
2

$ echo 'return paneflow.args.n * 2' | paneflow do - n=21
42
```

script の後の `key=value` の組は `paneflow.args` に入り、書き方によって
型が決まります。`n=2` は number、`on=true` は boolean、それ以外は
string です。`--args` は代わりに raw JSON を受け取り、`@path` なら file
から読み込みます。`--json` は結果をインデントします。

```text
$ paneflow do -e 'return paneflow.args' n=2 on=true env=prod
{"env":"prod","n":2,"on":true}

$ paneflow do --json -e 'return {n = paneflow.args.n}' --args '{"n": 3}'
{
  "n": 3
}
```

pane から起動した script は、その pane の workspace の event を受け取り
ます。`--all` を付けるとすべての workspace の event を受け取ります。
`--for 30s` はその時間が経つと script を止め、`--memory-limit <mib>` は
Lua state の memory に上限を設け、`--deadline <seconds>` は待機せずに
その時間実行し続ける Lua code を止めます。`paneflow.stop(n)` は exit
code `n` で script を終了し、Ctrl-C では `130` で終了します。

standard library は Lua のものですが、例外が 2 つあります。
`paneflow.exec` は program を shell を通さず引数リストから実行するため、
`io.popen` と `os.execute` は拒否されます。`require` は script の隣と、
Paneflow home の `lua` folder から module を探します。

```text
$ paneflow do -e 'return io.popen("ls")'
Error: (command line):1: io.popen is not available in Paneflow scripts: run programs with paneflow.exec, which takes an argument list and never starts a shell
```

## script が失敗するとどうなりますか？

Lua error は file と行番号付きで `Error: <message>` を出力し、`1` で
終了します。

```lua
-- hello.lua
return "hello " .. paneflow.args.name:upper()
```

```text
$ paneflow do hello.lua name=arthur
"hello ARTHUR"

$ paneflow do hello.lua
Error: hello.lua:1: attempt to index a nil value (field 'name')

$ paneflow do -e 'error("deploy refused: tests are red")'
Error: (command line):1: deploy refused: tests are red

$ paneflow do -e 'return 1 +'
Error: (command line):1: unexpected symbol near <eof>
```

失敗した method は error を raise しません。`nil`、message、JSON-RPC
error code を返すので、どうするかは script が決めます。

```text
$ paneflow do -e 'local result, message, code = paneflow.surface.read{ surface_id = 999 } return { message = message, code = code }'
{"code":-32000,"message":"Surface not found: no pane 999 on this host"}
```

script は CLI と同じ client です。pane への書き込みは `paneflow send` と
同じ gate を通ります。詳しくは
[安全に書き込むには？](/docs/scripting#安全に書き込むには)を参照してください。

## init.lua で action を宣言するには？

`init.lua` は Paneflow home にあります。`~/.paneflow/init.lua`、
Windows では `%USERPROFILE%\.paneflow\init.lua` です。worker は起動時と、
保存するたびにこれを読み込みます。各 `paneflow.action{...}` は action を
1 つ宣言します。小文字の `name`、command palette に表示される `title`、
`args` の型、`run` 関数を持ちます。

```lua
-- ~/.paneflow/init.lua
paneflow.action{
  name = "greet",
  title = "Greet",
  args = { name = "string" },
  run = function(ctx, args)
    return { greeting = "hello " .. args.name, origin = ctx.origin }
  end,
}

paneflow.action{
  name = "build",
  title = "Build the project",
  description = "Wait for a build to finish",
  agents = true,
  args = { seconds = "number?" },
  run = function(ctx, args)
    paneflow.sleep(args.seconds or 12)
    return "build finished"
  end,
}
```

ここでの `build` は長い job の代わりで、sleep するだけです。引数の型は
`string`、`number`、`integer`、`boolean`、`object`、`array`、`any` の
いずれかで、`?` で終わると省略可能になります。JSON Schema の table も
使えます。引数は `run` が始まる前に型と照合されます。`ctx.origin` は
run を開始したものを示します。`palette`、`key`、`cli`、`agent` などです。

```bash
paneflow config check ~/.paneflow/init.lua
paneflow config reload
paneflow actions
```

```text
$ paneflow config reload
/home/you/.paneflow/init.lua: loaded (2 actions, 0 bindings, 0 handlers, 0 timers)

$ paneflow actions
greet  Greet  [Actions]  init.lua:1
build  Build the project  [Actions]  init.lua:10
```

`paneflow config check <file>` は独立した process で file を読み込み、
問題を file と行番号付きで出力するので、誤りが worker に届くことは
ありません。reload に失敗した場合は、以前の configuration が維持されます。
`paneflow actions --json` は、各 action をその引数 schema、`agents`
flag、宣言された場所とともに出力します。

## action を実行するには？

`paneflow do <name>` は worker 上で action を実行し、`run` が返したものを
出力します。誤った引数は `run` が始まる前に失敗します。

```text
$ paneflow do greet name=arthur
{"greeting":"hello arthur","origin":"cli"}

$ paneflow do greet
Error: paneflow error -32050: missing argument "name"; the action takes name

$ paneflow do greet name=arthur extra=1
Error: paneflow error -32050: no argument named "extra"; the action takes name

$ paneflow do nope
Error: paneflow error -32602: no action named 'nope'; paneflow actions lists the actions init.lua declares
```

run は 30 秒後に停止されます。`paneflow.ui.input` や `paneflow.ui.pick`
でユーザーを待っている時間は数えません。

```text
$ paneflow do build seconds=40
Error: paneflow error -32051: timeout: the action build was stopped after 30 s
```

worker の configuration に触れずに action を試すには、自分の process で
file から実行します。
`paneflow do --action greet ./init.lua name=arthur`。

## 長い action で shell をブロックしないようにするには？

`--wait` がなければ、`paneflow do <name>` は action が終わるまで待ちます。
agent の shell tool には独自の timeout があるので、`--wait <duration>`
を渡してください。CLI は最大でその時間だけ待ちます。action が先に
終われば結果が出力され、exit code は `0` です。まだ実行中なら、CLI は
`running <run_id>` を出力して `4` で終了し、action は worker 上で実行を
続けます。

```text
$ paneflow do build seconds=1 --wait 10s
"build finished"

$ paneflow do build --wait 5s
running b322557838e3d024cc35e884b915b67a

$ paneflow do --resume b322557838e3d024cc35e884b915b67a --wait 20s
"build finished"
```

`--resume <run_id>` は待ち続けます。自分の `--wait` を渡した場合は、
最大でその時間だけ待ちます。run の結果は 1 回だけ返され、もう一度
resume すると失敗します。

```text
$ paneflow do --resume b322557838e3d024cc35e884b915b67a
Error: paneflow error -32602: no action run with id b322557838e3d024cc35e884b915b67a; its result was already returned or it never existed
```

`--wait` は action にだけ適用されます。script は終わるまで `paneflow do`
の process で実行されるので、`paneflow do panes.lua --wait 5s` は
`--wait applies to an action of init.lua, run by its name; a script runs
in this process until it ends` で失敗します。

## agent はどの action を実行できますか？

action が agent のために実行されるのは、`agents = true` を宣言している
場合だけです。worker は呼び出し元の process から agent を識別します。
Claude Code や Codex など Paneflow が認識する coding agent が pane で
起動した `paneflow do` は、call がどの origin を宣言していても、その
agent として実行されます。agent にとって、`agents = true` のない action
は存在しません。未知の名前と同じ message で失敗します。

```text
Error: paneflow error -32602: no action named 'greet'; paneflow actions lists the actions init.lua declares
```

agent は burst で最大 3 つの action を実行でき、その後は 1 秒に 1 つです。
それを超えると `paneflow do` は `rate limited` で失敗し、agent は 1 秒後に
再試行します。あなたは terminal、key、command palette から、すべての
action を実行できます。

## script や action からユーザーに質問するには？

`paneflow.ui.input` は 1 行の text を、`paneflow.ui.pick` は選択を
求めます。Paneflow は表示できるすべての window に質問を表示し、質問して
いる action または script の名前を示します。最初の回答が採用されます。
どちらも回答を返すか、`nil` と誰も回答しなかった理由を返します。理由は
`cancelled`、`timeout`、`no_client`（window が開いていない）、
`unsupported`、`busy`、または詳細付きの `failed` です。

```lua
paneflow.action{
  name = "new_branch",
  title = "New branch",
  agents = true,
  run = function()
    local name, reason = paneflow.ui.input{ title = "Branch name", value = "feature/" }
    if not name then return { cancelled = reason } end
    return { branch = name }
  end,
}

paneflow.action{
  name = "deploy",
  title = "Deploy",
  run = function()
    local target, reason = paneflow.ui.pick{
      title = "Deploy to",
      items = { "staging", { id = "prod", title = "Production", icon = "server" } },
    }
    if not target then return { cancelled = reason } end
    return { deployed = target }
  end,
}
```

```text
$ paneflow do new_branch
{"branch":"feature/login"}

$ paneflow do deploy
{"deployed":"prod"}
```

window が開いていない場合、同じ run はすぐに終わります。

```text
$ paneflow do new_branch
{"cancelled":"no_client"}
```

pick の item は string（それ自体が id と title になります）、または
`id`、`title`、`subtitle`、`icon`、`detail` を持つ table です。
`multiple = true` では、回答はユーザーがチェックした id のリストで、
`items` の順に並びます。`allow_other = true` では、どの item にも一致
しない text をユーザーが入力でき、回答は `{ text = ... }` になります。
質問はデフォルトで 300 秒待ちます。`timeout` で変更でき、最大は 3600
です。どちらの関数も action、event handler、timer、`paneflow do` script
で動作しますが、`init.lua` の読み込み中は使えません。

```text
$ paneflow do -e 'return paneflow.ui.pick{ title = "Deploy targets", items = { "staging", "prod", "dev" }, multiple = true }'
["staging","prod"]
```

agent の shell からは、`paneflow ask` で script なしに同じ種類の質問が
できます。
[agent はどうやって互いに message を送り、あなたに質問しますか？](/docs/scripting#how-do-agents-message-each-other-and-ask-you)
を参照してください。

## script が呼び出せる method を見つけるには？

`paneflow api list` は、実行中の process が提供するすべての method を、
それを所有する process とともに一覧します。
`paneflow api describe <method>` は、その parameter、result field、
call の例を表示します。同じ名前に dot を付けたものが Lua 関数です。

```text
$ paneflow api list | grep '^action\.'
action.list               worker  List the actions init.lua declared, with their titles, argument schemas and sources.
action.invoke             worker  Run an action of init.lua with arguments and return what it returned. Arguments are checked against its schema first; a run is stopped after 30 seconds. With wait_ms, a run still going past it answers {status: running, run_id} for action.wait. With ctx.origin agent, only an action declared with agents = true runs.
action.wait               worker  Keep waiting on an action run that action.invoke returned as {status: running, run_id}: the run's result with status done, the same running status, or the action's error.

$ paneflow api describe action.wait
action.wait
  Keep waiting on an action run that action.invoke returned as {status: running, run_id}: the run's result with status done, the same running status, or the action's error.

  owner: worker   gate: none   reply: ready

Parameters:
  run_id   string                required  default -
  wait_ms  integer >= 0          optional  default -         Milliseconds to wait, 0 by default, at most 25000

Result fields:
  result  any
  status  "done"|"running"|"rate_limited"
  run_id  string

Example:
  paneflow api call action.wait run_id=6f1c0e9a2b7d4c3e8f5a1b2c3d4e5f60 wait_ms=20000
```

`paneflow api list --json` と `paneflow api describe --json` は完全な
descriptor を出力します。`paneflow api call <method> key=value` は Lua
なしで method を 1 つ呼び出し、`paneflow api stubs` は Lua language
server 用の定義 file を出力するので、editor がすべての `paneflow.*`
関数を補完します。

## 関連

- [Scripting and automation](/docs/scripting): CLI、gate、agent verb。
- [Scripting reference](/docs/scripting/reference): すべての verb、method、exit code。