agent-lyceum 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -4
- package/README.zh-TW.md +20 -4
- package/dist/adapters/claude.js +2 -0
- package/dist/ask-answer.d.ts +10 -0
- package/dist/ask-answer.js +21 -0
- package/dist/ask-reply.d.ts +65 -0
- package/dist/ask-reply.js +165 -0
- package/dist/call.d.ts +35 -0
- package/dist/call.js +162 -0
- package/dist/cli.js +249 -20
- package/dist/config.d.ts +8 -0
- package/dist/config.js +9 -3
- package/dist/doctor.js +3 -0
- package/dist/mailbox.d.ts +9 -1
- package/dist/mailbox.js +11 -3
- package/dist/memory-tidy.d.ts +115 -0
- package/dist/memory-tidy.js +351 -0
- package/dist/policy.js +3 -2
- package/dist/prompt.d.ts +24 -0
- package/dist/prompt.js +113 -2
- package/dist/run-outcome.js +2 -0
- package/dist/run-session.d.ts +12 -0
- package/dist/run-session.js +104 -3
- package/dist/run-store.d.ts +5 -1
- package/dist/run-store.js +5 -3
- package/dist/schema.d.ts +5 -2
- package/dist/schema.js +4 -1
- package/dist/solo.d.ts +12 -0
- package/dist/solo.js +28 -0
- package/dist/status.d.ts +9 -1
- package/dist/status.js +32 -2
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -28,15 +28,30 @@ Requires Node 20+, plus `claude` and/or `codex` on your `PATH` (already logged i
|
|
|
28
28
|
| `project add <name> --dir <repo>` | Register a project. [details](docs/commands.md#project-add) |
|
|
29
29
|
| `project list` / `project remove <name> [--purge]` | List or unregister projects. [details](docs/commands.md#project-list-and-remove) |
|
|
30
30
|
| `validate [-p name] [--task-file f]` | Validate the merged config and show each agent's enforcement level. [details](docs/commands.md#validate) |
|
|
31
|
-
| `run ["task"] [--task-file f] [-p name]` | Give the task to the lead and run until done. [details](docs/commands.md#run) |
|
|
31
|
+
| `run ["task"] [--task-file f] [--agent a] [-p name]` | Give the task to the lead and run until done; with `--agent`, to one member alone. [details](docs/commands.md#run) |
|
|
32
|
+
| `call <agent> ["task"] [--task-file f] [--dir d]` | Call one global agent on its own, outside any project; prints its answer. [details](docs/commands.md#call) |
|
|
32
33
|
| `resume [run-id] [-p name]` | Continue an interrupted or failed run. [details](docs/commands.md#resume) |
|
|
34
|
+
| `answer <run-id> [--no-edit] [-p name]` | Answer the questions a waiting run asked, then continue it. [details](docs/commands.md#answer) |
|
|
33
35
|
| `status [-p name] [--monitor]` | Show agents, mail, the current wake-up and past runs (`--json`, `--monitor`). [details](docs/commands.md#status) |
|
|
34
36
|
| `clear <run-id> [-p name] [--dry-run] [--keep-worktrees]` | Delete a run with its task memory and worktrees. [details](docs/commands.md#clear) |
|
|
35
37
|
| `config show --resolved [-p name] [--json]` | Print every effective setting and where it came from. [details](docs/commands.md#config-show) |
|
|
36
38
|
| `doctor [-p name] [--json]` | Check config, git, the lock and runtime CLIs without running agents. [details](docs/commands.md#doctor) |
|
|
39
|
+
| `memory tidy [-p name] [--agent a] [--layer project\|global] [--dry-run]` | Have agents tidy their own memory (manual only; archives, never deletes). [details](docs/commands.md#memory-tidy) |
|
|
40
|
+
| `memory restore <timestamp> -p name --agent a` | Undo a tidy: move its archived files back. [details](docs/commands.md#memory-restore) |
|
|
37
41
|
| `unlock [-p name] --force` | Remove the project lock a crashed run left behind. [details](docs/commands.md#unlock) |
|
|
38
42
|
|
|
39
|
-
Ctrl-C cancels a run cleanly and it can be continued with `resume` ([Stopping a run](docs/commands.md#stopping-a-run)). `run` and `resume` exit `0` only when the lead reported `completed`, `2` for partial or blocked, `1` for failed, `130` for cancelled ([Exit codes](docs/commands.md#exit-codes)). Without `-p`, the project is inferred from the current directory ([Choosing the project](docs/commands.md#choosing-the-project)).
|
|
43
|
+
Ctrl-C cancels a run cleanly and it can be continued with `resume` ([Stopping a run](docs/commands.md#stopping-a-run)). `run` and `resume` exit `0` only when the lead reported `completed`, `2` for partial or blocked, `1` for failed, `3` while waiting for your answers, `130` for cancelled ([Exit codes](docs/commands.md#exit-codes)). Without `-p`, the project is inferred from the current directory ([Choosing the project](docs/commands.md#choosing-the-project)).
|
|
44
|
+
|
|
45
|
+
## Running one agent on its own
|
|
46
|
+
|
|
47
|
+
Two ways to give a task to a single agent instead of the whole team. The agent works alone: it cannot mail teammates, ask you questions or edit any `AGENT.md`.
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npx agent-lyceum run "tidy the form" --agent fe-member -p web # a member of the project, as an ordinary run
|
|
51
|
+
npx agent-lyceum call pm "is this ready to build?" --dir ~/code/web-app # a global agent, outside any project
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`run --agent` has a run id and the project lock, shows in `status`, and can be resumed; the agent ends the run with its own `done` mail. `call` needs no project at all: the agent comes from `team.yaml`, works in `--dir` (default: the current directory, which must not be inside or above the agent-lyceum home), prints only its final answer on stdout, and keeps `task.md`, `log/` and `result.md` in `<home>/calls/<call-id>/`. Details: [run](docs/commands.md#run) and [call](docs/commands.md#call).
|
|
40
55
|
|
|
41
56
|
## Monitor mod (Claude Code)
|
|
42
57
|
|
|
@@ -53,7 +68,7 @@ claude --plugin-dir /path/to/agent-lyceum/plugins/status-monitor
|
|
|
53
68
|
**Use it.**
|
|
54
69
|
- **Status line:** always on once loaded (`team 讀取中…` until the first poll, `team 無法取得狀態:…` when the CLI cannot run); shows the run state, round `n/max`, output tokens, the current step and unread mail. With several projects it shows one overview line (`team 1/3 running · a ... | b ...`).
|
|
55
70
|
- **Toasts:** a message pops up when a run finishes, is interrupted, or an agent's wake fails (prefixed `[project]` when several are watched). Nothing to do.
|
|
56
|
-
- **`/status-monitor`:** type it to open (or, if already open, close) the pane. It is off at session start unless `autoOpen` is set. In the **fullscreen layout** (`"tui": "fullscreen"` in `~/.claude/settings.json`, restart the session to apply; `/tui fullscreen` does the same) from 110 terminal columns it docks on the right at half the terminal width, and tabs and **關閉** (Close) can be clicked. Otherwise it shows above the prompt; the layout is fixed when the session starts, so a session started on the main screen stays that way. Keyboard (works in both): `x` closes, `1`-`9` or Tab/Enter switch task, Esc returns to the prompt, running the command again also closes. It shows, per project: the run id and state, task, progress and checklist, the agents working now and the queued mail, blocked integrations, notes and result summary, output tokens per runtime, per-agent wake statistics, the last 8 wakes. Each task
|
|
71
|
+
- **`/status-monitor`:** type it to open (or, if already open, close) the pane. It is off at session start unless `autoOpen` is set. In the **fullscreen layout** (`"tui": "fullscreen"` in `~/.claude/settings.json`, restart the session to apply; `/tui fullscreen` does the same) from 110 terminal columns it docks on the right at half the terminal width, and tabs and **關閉** (Close) can be clicked. Otherwise it shows above the prompt; the layout is fixed when the session starts, so a session started on the main screen stays that way. Keyboard (works in both): `x` closes, `1`-`9` or Tab/Enter switch task, Esc returns to the prompt, running the command again also closes. It shows, per project: the run id and state, task, progress and checklist, the agents working now and the queued mail, blocked integrations, notes and result summary, output tokens per runtime, per-agent wake statistics, the last 8 wakes. Each running task is a tab, newest first; finished and interrupted runs are not listed. It refreshes with the polling interval while open.
|
|
57
72
|
|
|
58
73
|
**Configure it.** In `~/.claude/settings.json` under `pluginConfigs."status-monitor@inline"` (`options`):
|
|
59
74
|
|
|
@@ -72,6 +87,7 @@ Changes take effect on the next session start. If the pane shows `無法取得
|
|
|
72
87
|
~/agent-lyceum-config/
|
|
73
88
|
├── team.yaml # global agent library
|
|
74
89
|
├── agents/<agent>/{AGENT.md, memory/} # global persona + cross-project memory
|
|
90
|
+
├── calls/<call-id>/{task.md, log/, result.md} # one folder per `call` (outside any project), plus .lock-<agent>
|
|
75
91
|
└── projects/<project>/
|
|
76
92
|
├── project.yaml # team, repo dir, overrides
|
|
77
93
|
├── agents/<agent>/{AGENT.md?, memory/} # project-level persona (optional) + project memory
|
|
@@ -93,7 +109,7 @@ agents:
|
|
|
93
109
|
qa-member: { can_message: [lead], owns: ["tests/**"] }
|
|
94
110
|
```
|
|
95
111
|
|
|
96
|
-
Agent fields: `runtime` (`claude-code`|`codex`; optional when `model` is recognizable: `opus`/`sonnet`/`haiku`/`claude-*` → Claude Code, `gpt-*`/`o3`/`*codex*` → Codex; precedence: project runtime > project model > global runtime > global model), `model`, `effort` (Claude Code: `low`|`medium`|`high`|`xhigh`|`max` via `--effort`; Codex: `minimal`|`low`|`medium`|`high`|`xhigh` via `model_reasoning_effort`; unset = CLI default), `agent_md`, `memory.global` / `memory.project`, `resume`, `can_message` (`all` or list; default `[lead]`, lead default `all`), `can_edit_agent_md` (default only the lead), `owns` (repo globs).
|
|
112
|
+
Agent fields: `runtime` (`claude-code`|`codex`; optional when `model` is recognizable: `opus`/`sonnet`/`haiku`/`claude-*` → Claude Code, `gpt-*`/`o3`/`*codex*` → Codex; precedence: project runtime > project model > global runtime > global model), `model`, `effort` (Claude Code: `low`|`medium`|`high`|`xhigh`|`max` via `--effort`; Codex: `minimal`|`low`|`medium`|`high`|`xhigh` via `model_reasoning_effort`; unset = CLI default), `agent_md`, `memory.global` / `memory.project`, `resume`, `can_message` (`all` or list; default `[lead]`, lead default `all`), `can_edit_agent_md` (default only the lead), `can_ask_user` (may send `type: ask` mail to you and pause the run for an answer; default only the lead), `owns` (repo globs).
|
|
97
113
|
|
|
98
114
|
Rules checked by `validate`: ≥ 2 agents (the lead and one member; the template has three), the lead is a listed agent, every agent has a runtime (explicit or inferred from `model`) and an existing `AGENT.md`, `effort` is valid for the agent's runtime (warning if `runtime` contradicts a recognizable `model`), `can_message` targets exist, memory dirs don't overlap, and with `max_parallel > 1` every non-lead agent needs non-overlapping `owns` and the repo must be a git repository.
|
|
99
115
|
|
package/README.zh-TW.md
CHANGED
|
@@ -28,15 +28,30 @@ npx agent-lyceum status
|
|
|
28
28
|
| `project add <name> --dir <repo>` | 註冊專案。 [詳細](docs/commands.zh-TW.md#project-add) |
|
|
29
29
|
| `project list` / `project remove <name> [--purge]` | 列出或取消註冊專案。 [詳細](docs/commands.zh-TW.md#project-list-and-remove) |
|
|
30
30
|
| `validate [-p name] [--task-file f]` | 驗證設定並顯示每個 agent 的防護等級。 [詳細](docs/commands.zh-TW.md#validate) |
|
|
31
|
-
| `run ["task"] [--task-file f] [-p name]` | 把任務交給 lead
|
|
31
|
+
| `run ["task"] [--task-file f] [--agent a] [-p name]` | 把任務交給 lead 並執行到結束;加 `--agent` 則只交給某個成員單獨做。 [詳細](docs/commands.zh-TW.md#run) |
|
|
32
|
+
| `call <agent> ["task"] [--task-file f] [--dir d]` | 單獨呼叫一個 global agent(不需專案),印出它的回答。 [詳細](docs/commands.zh-TW.md#call) |
|
|
32
33
|
| `resume [run-id] [-p name]` | 接續被中斷或失敗的 run。 [詳細](docs/commands.zh-TW.md#resume) |
|
|
34
|
+
| `answer <run-id> [--no-edit] [-p name]` | 回答等待中的 run 提出的問題,並接續執行。 [詳細](docs/commands.zh-TW.md#answer) |
|
|
33
35
|
| `status [-p name] [--monitor]` | 顯示 agent、信件、目前執行與歷次 run(支援 `--json`、`--monitor`)。 [詳細](docs/commands.zh-TW.md#status) |
|
|
34
36
|
| `clear <run-id> [-p name] [--dry-run] [--keep-worktrees]` | 刪除 run 與其任務記憶、worktree。 [詳細](docs/commands.zh-TW.md#clear) |
|
|
35
37
|
| `config show --resolved [-p name] [--json]` | 印出每項生效設定與其來源。 [詳細](docs/commands.zh-TW.md#config-show) |
|
|
36
38
|
| `doctor [-p name] [--json]` | 不執行 agent,檢查設定、git、鎖與 runtime CLI。 [詳細](docs/commands.zh-TW.md#doctor) |
|
|
39
|
+
| `memory tidy [-p name] [--agent a] [--layer project\|global] [--dry-run]` | 讓 agent 整理自己的記憶(只能手動觸發;封存而非刪除)。 [詳細](docs/commands.zh-TW.md#memory-tidy) |
|
|
40
|
+
| `memory restore <時間戳> -p name --agent a` | 還原一次整理:把封存的檔案搬回。 [詳細](docs/commands.zh-TW.md#memory-restore) |
|
|
37
41
|
| `unlock [-p name] --force` | 移除當機 run 留下的專案鎖。 [詳細](docs/commands.zh-TW.md#unlock) |
|
|
38
42
|
|
|
39
|
-
Ctrl-C 會乾淨地取消 run,之後可用 `resume` 接續([中止 run](docs/commands.zh-TW.md#中止-run))。`run`/`resume` 只有在 lead 回報 `completed` 時才 exit `0`;`partial`/`blocked` 為 `2`,`failed` 為 `1`,取消為 `130`([退出碼](docs/commands.zh-TW.md#退出碼))。未指定 `-p` 時,專案由目前目錄推斷([選擇專案](docs/commands.zh-TW.md#選擇專案))。
|
|
43
|
+
Ctrl-C 會乾淨地取消 run,之後可用 `resume` 接續([中止 run](docs/commands.zh-TW.md#中止-run))。`run`/`resume` 只有在 lead 回報 `completed` 時才 exit `0`;`partial`/`blocked` 為 `2`,`failed` 為 `1`,等待你回答時為 `3`,取消為 `130`([退出碼](docs/commands.zh-TW.md#退出碼))。未指定 `-p` 時,專案由目前目錄推斷([選擇專案](docs/commands.zh-TW.md#選擇專案))。
|
|
44
|
+
|
|
45
|
+
## 單獨呼叫一個 agent
|
|
46
|
+
|
|
47
|
+
有兩種方式把任務只交給單一 agent,而不是整個團隊。該 agent 獨自工作:不能寄信給隊友、不能向你提問、不能修改任何 `AGENT.md`。
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npx agent-lyceum run "整理表單" --agent fe-member -p web # 專案裡的一個成員,當作一般 run
|
|
51
|
+
npx agent-lyceum call pm "這個需求可以開工了嗎?" --dir ~/code/web-app # global agent,不屬於任何專案
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`run --agent` 有 run id 與專案鎖、會出現在 `status`、可以 `resume`;agent 用自己寄出的 `done` 結束 run。`call` 完全不需要專案:agent 取自 `team.yaml`,在 `--dir`(預設是目前目錄,且不可位於 agent-lyceum home 之內或之上)工作,stdout 只印它的最終回答,並在 `<home>/calls/<call-id>/` 留下 `task.md`、`log/` 與 `result.md`。細節見 [run](docs/commands.zh-TW.md#run) 與 [call](docs/commands.zh-TW.md#call)。
|
|
40
55
|
|
|
41
56
|
## 監控 mod(Claude Code)
|
|
42
57
|
|
|
@@ -53,7 +68,7 @@ claude --plugin-dir /path/to/agent-lyceum/plugins/status-monitor
|
|
|
53
68
|
**操作。**
|
|
54
69
|
- **狀態列:** 載入後常駐(第一次輪詢前顯示 `team 讀取中…`,CLI 跑不起來時顯示 `team 無法取得狀態:…`),顯示執行狀態、輪數 `n/max`、output tokens、目前步驟與未讀信件。監看多個專案時顯示一行總覽(`team 1/3 執行中 · a ... | b ...`)。
|
|
55
70
|
- **通知:** 執行完成、被中斷或某個 agent 喚醒失敗時會跳出訊息(監看多個專案時前面加 `[專案名]`),不需要任何操作。
|
|
56
|
-
- **`/status-monitor`:** 輸入即開啟面板(已開著則關閉)。session 啟動時預設不開,除非設定 `autoOpen`。在 **fullscreen 版面**(`~/.claude/settings.json` 設 `"tui": "fullscreen"` 後重開 session;`/tui fullscreen` 效果相同)且終端寬度 110 欄以上時,面板會靠右 dock 在終端寬度的一半,分頁與 **關閉** 都可以用滑鼠點。否則顯示在輸入框上方;版面在 session 啟動時就固定,從主畫面啟動的 session 不會變。鍵盤操作兩種版面都能用:`x` 關閉,`1`-`9` 或 Tab/Enter 切換任務,Esc 回到輸入框,再執行一次指令也會關閉。每個專案顯示:執行 id 與狀態、任務、進度與清單、正在工作的 agent 與排隊中的信件、受阻的整合、備註與結果摘要、各 runtime 的 output tokens、各 agent 的喚醒統計、最近 8
|
|
71
|
+
- **`/status-monitor`:** 輸入即開啟面板(已開著則關閉)。session 啟動時預設不開,除非設定 `autoOpen`。在 **fullscreen 版面**(`~/.claude/settings.json` 設 `"tui": "fullscreen"` 後重開 session;`/tui fullscreen` 效果相同)且終端寬度 110 欄以上時,面板會靠右 dock 在終端寬度的一半,分頁與 **關閉** 都可以用滑鼠點。否則顯示在輸入框上方;版面在 session 啟動時就固定,從主畫面啟動的 session 不會變。鍵盤操作兩種版面都能用:`x` 關閉,`1`-`9` 或 Tab/Enter 切換任務,Esc 回到輸入框,再執行一次指令也會關閉。每個專案顯示:執行 id 與狀態、任務、進度與清單、正在工作的 agent 與排隊中的信件、受阻的整合、備註與結果摘要、各 runtime 的 output tokens、各 agent 的喚醒統計、最近 8 次喚醒。每個執行中的任務是一個分頁,最新的排最前面;已結束或已中斷的不列出。面板開著時會依輪詢間隔自動更新。
|
|
57
72
|
|
|
58
73
|
**設定。** 在 `~/.claude/settings.json` 的 `pluginConfigs."status-monitor@inline"`(`options`):
|
|
59
74
|
|
|
@@ -72,6 +87,7 @@ claude --plugin-dir /path/to/agent-lyceum/plugins/status-monitor
|
|
|
72
87
|
~/agent-lyceum-config/
|
|
73
88
|
├── team.yaml # 全域 agent 庫
|
|
74
89
|
├── agents/<agent>/{AGENT.md, memory/} # 全域人設 + 跨專案記憶
|
|
90
|
+
├── calls/<call-id>/{task.md, log/, result.md} # 每次 `call`(不屬於任何專案)一個資料夾,另有 .lock-<agent>
|
|
75
91
|
└── projects/<project>/
|
|
76
92
|
├── project.yaml # 團隊、repo 路徑、覆寫設定
|
|
77
93
|
├── agents/<agent>/{AGENT.md?, memory/} # 專案層人設(選用)+ 專案記憶
|
|
@@ -94,7 +110,7 @@ agents:
|
|
|
94
110
|
qa-member: { can_message: [lead], owns: ["tests/**"] }
|
|
95
111
|
```
|
|
96
112
|
|
|
97
|
-
Agent 欄位:`runtime`(`claude-code`|`codex`;若 `model` 可辨識則可省略:`opus`/`sonnet`/`haiku`/`claude-*` → Claude Code,`gpt-*`/`o3`/`*codex*` → Codex;優先順序:專案 runtime > 專案 model > 全域 runtime > 全域 model)、`model`、`effort`(Claude Code:`low`|`medium`|`high`|`xhigh`|`max`,經 `--effort`;Codex:`minimal`|`low`|`medium`|`high`|`xhigh`,經 `model_reasoning_effort`;未設則用 CLI 預設)、`agent_md`、`memory.global` / `memory.project`、`resume`、`can_message`(`all` 或清單;預設 `[lead]`,lead 預設 `all`)、`can_edit_agent_md`(預設只有 lead)、`owns`(repo glob)。
|
|
113
|
+
Agent 欄位:`runtime`(`claude-code`|`codex`;若 `model` 可辨識則可省略:`opus`/`sonnet`/`haiku`/`claude-*` → Claude Code,`gpt-*`/`o3`/`*codex*` → Codex;優先順序:專案 runtime > 專案 model > 全域 runtime > 全域 model)、`model`、`effort`(Claude Code:`low`|`medium`|`high`|`xhigh`|`max`,經 `--effort`;Codex:`minimal`|`low`|`medium`|`high`|`xhigh`,經 `model_reasoning_effort`;未設則用 CLI 預設)、`agent_md`、`memory.global` / `memory.project`、`resume`、`can_message`(`all` 或清單;預設 `[lead]`,lead 預設 `all`)、`can_edit_agent_md`(預設只有 lead)、`can_ask_user`(可用 `type: ask` 信件向你提問並暫停 run 等待回答;預設只有 lead)、`owns`(repo glob)。
|
|
98
114
|
|
|
99
115
|
`validate` 檢查的規則:至少 2 個 agent(lead 加一位成員;範本預設是三位)、lead 在 agent 清單內、每個 agent 都有 runtime(明設或由 `model` 推斷)且 `AGENT.md` 存在、`effort` 對該 runtime 合法(若 `runtime` 與可辨識的 `model` 矛盾則警告)、`can_message` 的目標存在、記憶資料夾互不重疊,且當 `max_parallel > 1` 時,每個非 lead 的 agent 都必須有互不重疊的 `owns`,repo 也必須是 git repository。
|
|
100
116
|
|
package/dist/adapters/claude.js
CHANGED
|
@@ -35,6 +35,8 @@ export function buildClaudeSettings(project, agent) {
|
|
|
35
35
|
allow.push(rule("Edit", f));
|
|
36
36
|
const deny = pol.deny.flatMap(denyRules);
|
|
37
37
|
return {
|
|
38
|
+
// The user's own and plugin hooks (e.g. a hook that asks the user a question) would block every tool call of a headless wake-up.
|
|
39
|
+
disableAllHooks: true,
|
|
38
40
|
permissions: { allow, deny },
|
|
39
41
|
sandbox: {
|
|
40
42
|
enabled: true,
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface PrepareResult {
|
|
2
|
+
complete: boolean;
|
|
3
|
+
problems: string[];
|
|
4
|
+
path: string;
|
|
5
|
+
}
|
|
6
|
+
/** Read the ask-reply file of a waiting run. With `assumeDefaults`, unanswered questions that have a suggestion take it (and the file is saved). */
|
|
7
|
+
export declare function prepareAnswers(runDir: string, opts: {
|
|
8
|
+
assumeDefaults?: boolean;
|
|
9
|
+
}): PrepareResult;
|
|
10
|
+
export declare function openInEditor(file: string, env?: NodeJS.ProcessEnv): void;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { applyDefaults, askReplyPath, checkAnswers, describeCheck, isComplete, readAskReply, writeAskReply } from "./ask-reply.js";
|
|
3
|
+
/** Read the ask-reply file of a waiting run. With `assumeDefaults`, unanswered questions that have a suggestion take it (and the file is saved). */
|
|
4
|
+
export function prepareAnswers(runDir, opts) {
|
|
5
|
+
const file = askReplyPath(runDir);
|
|
6
|
+
let reply = readAskReply(runDir);
|
|
7
|
+
if (!reply)
|
|
8
|
+
return { complete: false, problems: ["ask-reply.md does not exist"], path: file };
|
|
9
|
+
if (opts.assumeDefaults) {
|
|
10
|
+
reply = applyDefaults(reply);
|
|
11
|
+
writeAskReply(runDir, reply);
|
|
12
|
+
}
|
|
13
|
+
const check = checkAnswers(reply);
|
|
14
|
+
return { complete: isComplete(check), problems: describeCheck(check), path: file };
|
|
15
|
+
}
|
|
16
|
+
export function openInEditor(file, env = process.env) {
|
|
17
|
+
const editor = env.VISUAL || env.EDITOR || "vi";
|
|
18
|
+
const r = spawnSync(`${editor} ${JSON.stringify(file)}`, { shell: true, stdio: "inherit", env });
|
|
19
|
+
if (r.error || (r.status ?? 0) !== 0)
|
|
20
|
+
throw new Error(`The editor "${editor}" failed${r.error ? `: ${r.error.message}` : ` (exit ${r.status})`}.`);
|
|
21
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
export declare const MAX_QUESTIONS_PER_ASK = 10;
|
|
2
|
+
export declare const ASK_REPLY_FILE = "ask-reply.md";
|
|
3
|
+
export type AnswerSource = "user" | "default";
|
|
4
|
+
export interface AskQuestion {
|
|
5
|
+
id: string;
|
|
6
|
+
text: string;
|
|
7
|
+
options?: string[];
|
|
8
|
+
suggested?: {
|
|
9
|
+
value: string;
|
|
10
|
+
reason?: string;
|
|
11
|
+
};
|
|
12
|
+
/** The agent that asked; the answer goes back to it. */
|
|
13
|
+
asker: string;
|
|
14
|
+
answer?: {
|
|
15
|
+
value: string;
|
|
16
|
+
by: AnswerSource;
|
|
17
|
+
};
|
|
18
|
+
/** The answer was already sent to the asker. */
|
|
19
|
+
delivered?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface AskReply {
|
|
22
|
+
status: "pending" | "answered";
|
|
23
|
+
/** Who asked the latest batch. */
|
|
24
|
+
askedBy: string;
|
|
25
|
+
/** The round of the latest batch. */
|
|
26
|
+
round: number;
|
|
27
|
+
questions: AskQuestion[];
|
|
28
|
+
}
|
|
29
|
+
export type NewQuestion = Omit<AskQuestion, "asker" | "answer" | "delivered">;
|
|
30
|
+
export declare const askReplyPath: (runDir: string) => string;
|
|
31
|
+
export declare function parseAskBody(body: string): {
|
|
32
|
+
ok: true;
|
|
33
|
+
questions: NewQuestion[];
|
|
34
|
+
} | {
|
|
35
|
+
ok: false;
|
|
36
|
+
error: string;
|
|
37
|
+
};
|
|
38
|
+
export declare function parseAskReply(text: string): AskReply;
|
|
39
|
+
export declare function renderAskReply(r: AskReply): string;
|
|
40
|
+
export declare function readAskReply(runDir: string): AskReply | undefined;
|
|
41
|
+
export declare function writeAskReply(runDir: string, r: AskReply): void;
|
|
42
|
+
/** Add a batch of questions, keeping everything already in the file. The same id with the same text is skipped (a re-routed ask after a crash). */
|
|
43
|
+
export declare function addBatch(existing: AskReply | undefined, asker: string, round: number, qs: NewQuestion[]): {
|
|
44
|
+
ok: true;
|
|
45
|
+
reply: AskReply;
|
|
46
|
+
} | {
|
|
47
|
+
ok: false;
|
|
48
|
+
error: string;
|
|
49
|
+
};
|
|
50
|
+
export interface AnswerCheck {
|
|
51
|
+
missing: string[];
|
|
52
|
+
invalid: {
|
|
53
|
+
id: string;
|
|
54
|
+
reason: string;
|
|
55
|
+
}[];
|
|
56
|
+
}
|
|
57
|
+
export declare const isComplete: (c: AnswerCheck) => boolean;
|
|
58
|
+
/** Only questions whose answer was not sent yet count. */
|
|
59
|
+
export declare function checkAnswers(r: AskReply): AnswerCheck;
|
|
60
|
+
export declare function describeCheck(c: AnswerCheck): string[];
|
|
61
|
+
export declare function applyDefaults(r: AskReply): AskReply;
|
|
62
|
+
export declare function askersWithAnswers(r: AskReply): string[];
|
|
63
|
+
/** The body of the `reply` mail that carries the answers back to `asker`. */
|
|
64
|
+
export declare function renderAnswers(r: AskReply, asker: string): string;
|
|
65
|
+
export declare function markDelivered(r: AskReply): AskReply;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { atomicWrite } from "./fs-util.js";
|
|
4
|
+
export const MAX_QUESTIONS_PER_ASK = 10;
|
|
5
|
+
export const ASK_REPLY_FILE = "ask-reply.md";
|
|
6
|
+
export const askReplyPath = (runDir) => path.join(runDir, "mail", ASK_REPLY_FILE);
|
|
7
|
+
// ---- a tiny reader for the few tags used here (no XML dependency) ----
|
|
8
|
+
const esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
9
|
+
const unesc = (s) => s.replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
10
|
+
function tags(xml, name) {
|
|
11
|
+
const re = new RegExp(`<${name}((?:\\s+[\\w-]+="[^"]*")*)\\s*(?:/>|>([\\s\\S]*?)</${name}>)`, "g");
|
|
12
|
+
return [...xml.matchAll(re)].map((m) => {
|
|
13
|
+
const attrs = {};
|
|
14
|
+
for (const a of (m[1] ?? "").matchAll(/([\w-]+)="([^"]*)"/g))
|
|
15
|
+
attrs[a[1]] = unesc(a[2]);
|
|
16
|
+
return { attrs, inner: m[2] ?? "" };
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
const first = (xml, name) => tags(xml, name)[0];
|
|
20
|
+
const textOf = (t) => unesc((t?.inner ?? "").trim());
|
|
21
|
+
// ---- the body of an `ask` mail ----
|
|
22
|
+
export function parseAskBody(body) {
|
|
23
|
+
const block = first(body, "ask");
|
|
24
|
+
if (!block)
|
|
25
|
+
return { ok: false, error: "the body has no <ask>…</ask> block" };
|
|
26
|
+
const found = tags(block.inner, "question");
|
|
27
|
+
if (found.length === 0)
|
|
28
|
+
return { ok: false, error: "the <ask> block needs at least one <question>" };
|
|
29
|
+
if (found.length > MAX_QUESTIONS_PER_ASK)
|
|
30
|
+
return { ok: false, error: `at most ${MAX_QUESTIONS_PER_ASK} questions per ask (got ${found.length}); ask the most important ones first` };
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
const questions = [];
|
|
33
|
+
for (const [i, q] of found.entries()) {
|
|
34
|
+
const id = q.attrs.id?.trim();
|
|
35
|
+
if (!id || !/^[\w.-]+$/.test(id))
|
|
36
|
+
return { ok: false, error: `question ${i + 1} needs an id attribute made of letters, digits, "_", "-" or "."` };
|
|
37
|
+
if (seen.has(id))
|
|
38
|
+
return { ok: false, error: `duplicate question id "${id}"` };
|
|
39
|
+
seen.add(id);
|
|
40
|
+
const text = textOf(first(q.inner, "text"));
|
|
41
|
+
if (!text)
|
|
42
|
+
return { ok: false, error: `question "${id}" needs a non-empty <text>` };
|
|
43
|
+
const options = tags(first(q.inner, "options")?.inner ?? "", "option").map((o) => textOf(o)).filter(Boolean);
|
|
44
|
+
const sug = first(q.inner, "suggested");
|
|
45
|
+
const suggested = sug && textOf(sug) ? { value: textOf(sug), ...(sug.attrs.reason ? { reason: sug.attrs.reason } : {}) } : undefined;
|
|
46
|
+
if (suggested && options.length && !options.includes(suggested.value))
|
|
47
|
+
return { ok: false, error: `the suggested value of question "${id}" must be one of its options` };
|
|
48
|
+
questions.push({ id, text, ...(options.length ? { options } : {}), ...(suggested ? { suggested } : {}) });
|
|
49
|
+
}
|
|
50
|
+
return { ok: true, questions };
|
|
51
|
+
}
|
|
52
|
+
// ---- the ask-reply file ----
|
|
53
|
+
export function parseAskReply(text) {
|
|
54
|
+
const root = first(text, "ask-reply");
|
|
55
|
+
if (!root)
|
|
56
|
+
throw new Error("ask-reply.md has no <ask-reply> root tag");
|
|
57
|
+
const askedBy = root.attrs.asked_by ?? "";
|
|
58
|
+
const questions = tags(root.inner, "question").map((q) => {
|
|
59
|
+
const ans = first(q.inner, "answer");
|
|
60
|
+
const value = textOf(ans);
|
|
61
|
+
const options = tags(first(q.inner, "options")?.inner ?? "", "option").map((o) => textOf(o));
|
|
62
|
+
const sug = first(q.inner, "suggested");
|
|
63
|
+
return {
|
|
64
|
+
id: q.attrs.id ?? "",
|
|
65
|
+
text: textOf(first(q.inner, "text")),
|
|
66
|
+
...(options.length ? { options } : {}),
|
|
67
|
+
...(sug && textOf(sug) ? { suggested: { value: textOf(sug), ...(sug.attrs.reason ? { reason: sug.attrs.reason } : {}) } } : {}),
|
|
68
|
+
asker: q.attrs.asker ?? askedBy,
|
|
69
|
+
...(value ? { answer: { value, by: ans?.attrs.by === "default" ? "default" : "user" } } : {}),
|
|
70
|
+
...(q.attrs.delivered === "true" ? { delivered: true } : {}),
|
|
71
|
+
};
|
|
72
|
+
});
|
|
73
|
+
return { status: root.attrs.status === "answered" ? "answered" : "pending", askedBy, round: Number(root.attrs.round) || 0, questions };
|
|
74
|
+
}
|
|
75
|
+
export function renderAskReply(r) {
|
|
76
|
+
const out = [`<ask-reply status="${r.status}" asked_by="${esc(r.askedBy)}" round="${r.round}">`];
|
|
77
|
+
for (const q of r.questions) {
|
|
78
|
+
out.push(` <question id="${esc(q.id)}" asker="${esc(q.asker)}"${q.delivered ? ` delivered="true"` : ""}>`);
|
|
79
|
+
out.push(` <text>${esc(q.text)}</text>`);
|
|
80
|
+
if (q.options?.length)
|
|
81
|
+
out.push(` <options>`, ...q.options.map((o) => ` <option>${esc(o)}</option>`), ` </options>`);
|
|
82
|
+
if (q.suggested)
|
|
83
|
+
out.push(` <suggested${q.suggested.reason ? ` reason="${esc(q.suggested.reason)}"` : ""}>${esc(q.suggested.value)}</suggested>`);
|
|
84
|
+
out.push(q.answer ? ` <answer by="${q.answer.by}">${esc(q.answer.value)}</answer>` : ` <answer></answer>`);
|
|
85
|
+
out.push(` </question>`);
|
|
86
|
+
}
|
|
87
|
+
out.push(`</ask-reply>`);
|
|
88
|
+
return out.join("\n") + "\n";
|
|
89
|
+
}
|
|
90
|
+
export function readAskReply(runDir) {
|
|
91
|
+
const file = askReplyPath(runDir);
|
|
92
|
+
if (!fs.existsSync(file))
|
|
93
|
+
return undefined;
|
|
94
|
+
return parseAskReply(fs.readFileSync(file, "utf8"));
|
|
95
|
+
}
|
|
96
|
+
export function writeAskReply(runDir, r) {
|
|
97
|
+
atomicWrite(askReplyPath(runDir), renderAskReply(r));
|
|
98
|
+
}
|
|
99
|
+
// ---- batches, answers ----
|
|
100
|
+
/** Add a batch of questions, keeping everything already in the file. The same id with the same text is skipped (a re-routed ask after a crash). */
|
|
101
|
+
export function addBatch(existing, asker, round, qs) {
|
|
102
|
+
const base = existing ?? { status: "pending", askedBy: asker, round, questions: [] };
|
|
103
|
+
const added = [];
|
|
104
|
+
for (const q of qs) {
|
|
105
|
+
const old = base.questions.find((x) => x.id === q.id);
|
|
106
|
+
if (old) {
|
|
107
|
+
if (old.text === q.text)
|
|
108
|
+
continue;
|
|
109
|
+
return { ok: false, error: `question id "${q.id}" is already used in this run for a different question; use a new id` };
|
|
110
|
+
}
|
|
111
|
+
added.push({ ...q, asker });
|
|
112
|
+
}
|
|
113
|
+
if (added.length === 0)
|
|
114
|
+
return { ok: true, reply: base };
|
|
115
|
+
return { ok: true, reply: { status: "pending", askedBy: asker, round, questions: [...base.questions, ...added] } };
|
|
116
|
+
}
|
|
117
|
+
export const isComplete = (c) => c.missing.length === 0 && c.invalid.length === 0;
|
|
118
|
+
function problem(q) {
|
|
119
|
+
const v = q.answer?.value.trim();
|
|
120
|
+
if (!v)
|
|
121
|
+
return undefined;
|
|
122
|
+
if (q.options?.length && !q.options.includes(v) && !/^other:\s*\S/.test(v))
|
|
123
|
+
return `must be one of: ${q.options.join(", ")} — or start with "other:" and write your own`;
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/** Only questions whose answer was not sent yet count. */
|
|
127
|
+
export function checkAnswers(r) {
|
|
128
|
+
const c = { missing: [], invalid: [] };
|
|
129
|
+
for (const q of r.questions) {
|
|
130
|
+
if (q.delivered)
|
|
131
|
+
continue;
|
|
132
|
+
if (!q.answer?.value.trim())
|
|
133
|
+
c.missing.push(q.id);
|
|
134
|
+
else {
|
|
135
|
+
const reason = problem(q);
|
|
136
|
+
if (reason)
|
|
137
|
+
c.invalid.push({ id: q.id, reason });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return c;
|
|
141
|
+
}
|
|
142
|
+
export function describeCheck(c) {
|
|
143
|
+
return [...c.missing.map((id) => `${id}: no answer yet`), ...c.invalid.map((i) => `${i.id}: ${i.reason}`)];
|
|
144
|
+
}
|
|
145
|
+
export function applyDefaults(r) {
|
|
146
|
+
return {
|
|
147
|
+
...r,
|
|
148
|
+
questions: r.questions.map((q) => (!q.delivered && !q.answer?.value.trim() && q.suggested ? { ...q, answer: { value: q.suggested.value, by: "default" } } : q)),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
export function askersWithAnswers(r) {
|
|
152
|
+
return [...new Set(r.questions.filter((q) => !q.delivered && q.answer?.value.trim()).map((q) => q.asker))];
|
|
153
|
+
}
|
|
154
|
+
/** The body of the `reply` mail that carries the answers back to `asker`. */
|
|
155
|
+
export function renderAnswers(r, asker) {
|
|
156
|
+
const out = [`<answers>`];
|
|
157
|
+
for (const q of r.questions.filter((x) => !x.delivered && x.asker === asker && x.answer?.value.trim())) {
|
|
158
|
+
out.push(` <question id="${esc(q.id)}">`, ` <text>${esc(q.text)}</text>`, ` <answer by="${q.answer?.by}">${esc(q.answer?.value ?? "")}</answer>`, ` </question>`);
|
|
159
|
+
}
|
|
160
|
+
out.push(`</answers>`);
|
|
161
|
+
return out.join("\n");
|
|
162
|
+
}
|
|
163
|
+
export function markDelivered(r) {
|
|
164
|
+
return { ...r, status: "answered", questions: r.questions.map((q) => (q.answer?.value.trim() ? { ...q, delivered: true } : q)) };
|
|
165
|
+
}
|
package/dist/call.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type Invoker } from "./adapters/index.js";
|
|
2
|
+
import { type ResolvedAgent, type ResolvedProject } from "./config.js";
|
|
3
|
+
export declare const CALL_PROJECT = "(call)";
|
|
4
|
+
export declare const callsDir: (home: string) => string;
|
|
5
|
+
export interface CallOptions {
|
|
6
|
+
home: string;
|
|
7
|
+
agent: string;
|
|
8
|
+
task: string;
|
|
9
|
+
/** Working directory; must exist. */
|
|
10
|
+
dir: string;
|
|
11
|
+
invoker?: Invoker;
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
say?: (line: string) => void;
|
|
14
|
+
}
|
|
15
|
+
export interface CallResult {
|
|
16
|
+
callId: string;
|
|
17
|
+
callDir: string;
|
|
18
|
+
ok: boolean;
|
|
19
|
+
cancelled: boolean;
|
|
20
|
+
/** The agent's final reply (empty when the call failed). */
|
|
21
|
+
text: string;
|
|
22
|
+
error?: string;
|
|
23
|
+
/** Protected files the agent changed and agent-lyceum put back. */
|
|
24
|
+
reverted: string[];
|
|
25
|
+
}
|
|
26
|
+
/** A global agent (from team.yaml) as a `call` uses it: global persona and memory, nobody to mail, nothing to ask, nothing to edit. */
|
|
27
|
+
export declare function resolveCallAgent(home: string, name: string): ResolvedAgent;
|
|
28
|
+
/** The made-up project a call runs in: the working directory is its repo, and every other path is inside the call's own folder. */
|
|
29
|
+
export declare function callProject(home: string, agent: ResolvedAgent, dir: string, callDir: string): ResolvedProject;
|
|
30
|
+
/** One call per agent at a time (two would write the same global memory). A lock whose process is gone, or that cannot be read, is taken over. */
|
|
31
|
+
export declare function lockAgent(home: string, agent: string, callId: string): {
|
|
32
|
+
release(): void;
|
|
33
|
+
};
|
|
34
|
+
/** Wake one global agent once, alone, in `dir`. Leaves task.md, log/ and result.md in `<home>/calls/<call-id>/`. */
|
|
35
|
+
export declare function callAgent(o: CallOptions): Promise<CallResult>;
|
package/dist/call.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { realInvoker } from "./adapters/index.js";
|
|
4
|
+
import { must } from "./assert.js";
|
|
5
|
+
import { ConfigError, loadGlobal, resolveProjectFrom } from "./config.js";
|
|
6
|
+
import { atomicWrite } from "./fs-util.js";
|
|
7
|
+
import { ProtectedGuard } from "./guard.js";
|
|
8
|
+
import { assertName, homePaths, isInside } from "./paths.js";
|
|
9
|
+
import { memoryDirs } from "./policy.js";
|
|
10
|
+
import { lockHolderAlive } from "./project-lock.js";
|
|
11
|
+
import { buildCallUserPrompt, buildSoloSystemPrompt } from "./prompt.js";
|
|
12
|
+
import { newRunId } from "./run-store.js";
|
|
13
|
+
import { DISPATCHER_DEFAULTS } from "./schema.js";
|
|
14
|
+
export const CALL_PROJECT = "(call)";
|
|
15
|
+
export const callsDir = (home) => path.join(home, "calls");
|
|
16
|
+
/** A global agent (from team.yaml) as a `call` uses it: global persona and memory, nobody to mail, nothing to ask, nothing to edit. */
|
|
17
|
+
export function resolveCallAgent(home, name) {
|
|
18
|
+
assertName("agent", name);
|
|
19
|
+
const g = loadGlobal(home);
|
|
20
|
+
if (!g.agents[name]) {
|
|
21
|
+
throw new ConfigError(`"${name}" is not an agent of the global library (${homePaths(home).globalConfig}). Global agents: ${Object.keys(g.agents).join(", ") || "(none)"}.`);
|
|
22
|
+
}
|
|
23
|
+
const p = resolveProjectFrom(home, CALL_PROJECT, g, { dir: home, team: { lead: name }, dispatcher: {}, agents: { [name]: {} } });
|
|
24
|
+
const a = must(p.agents[name], "the resolved agent");
|
|
25
|
+
if (!a.runtime)
|
|
26
|
+
throw new ConfigError(`Agent "${name}" has no runtime: set runtime (or a model) for it in team.yaml.`);
|
|
27
|
+
if (!fs.existsSync(a.agentMd))
|
|
28
|
+
throw new ConfigError(`AGENT.md of "${name}" not found: ${a.agentMd}`);
|
|
29
|
+
return {
|
|
30
|
+
...a,
|
|
31
|
+
memory: { global: a.memory.global ?? path.join(homePaths(home).globalAgentsDir, name, "memory") },
|
|
32
|
+
resume: false,
|
|
33
|
+
canMessage: [],
|
|
34
|
+
canAskUser: false,
|
|
35
|
+
canEditAgentMd: false,
|
|
36
|
+
owns: [],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** The made-up project a call runs in: the working directory is its repo, and every other path is inside the call's own folder. */
|
|
40
|
+
export function callProject(home, agent, dir, callDir) {
|
|
41
|
+
const paths = {
|
|
42
|
+
root: callDir,
|
|
43
|
+
config: path.join(callDir, "call.yaml"),
|
|
44
|
+
agentsDir: path.join(callDir, "agents"),
|
|
45
|
+
shared: path.join(callDir, "shared"),
|
|
46
|
+
common: path.join(callDir, "shared", "COMMON.md"),
|
|
47
|
+
inboxRoot: path.join(callDir, "mail", "inbox"),
|
|
48
|
+
outboxRoot: path.join(callDir, "mail", "outbox"),
|
|
49
|
+
runs: path.join(callDir, "runs"),
|
|
50
|
+
taskMemory: path.join(callDir, "task-memory"),
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
home,
|
|
54
|
+
name: CALL_PROJECT,
|
|
55
|
+
dir,
|
|
56
|
+
lead: agent.name,
|
|
57
|
+
dispatcher: { ...DISPATCHER_DEFAULTS, max_parallel: 1, workspace_mode: "shared" },
|
|
58
|
+
agents: { [agent.name]: agent },
|
|
59
|
+
paths,
|
|
60
|
+
solo: "call",
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function readHolder(file) {
|
|
64
|
+
try {
|
|
65
|
+
const j = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
66
|
+
return typeof j?.pid === "number" && typeof j?.call_id === "string" ? j : undefined;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** One call per agent at a time (two would write the same global memory). A lock whose process is gone, or that cannot be read, is taken over. */
|
|
73
|
+
export function lockAgent(home, agent, callId) {
|
|
74
|
+
const dir = callsDir(home);
|
|
75
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
76
|
+
const file = path.join(dir, `.lock-${agent}`);
|
|
77
|
+
const mine = JSON.stringify({ pid: process.pid, call_id: callId });
|
|
78
|
+
for (let attempt = 0;; attempt++) {
|
|
79
|
+
try {
|
|
80
|
+
fs.writeFileSync(file, mine, { flag: "wx" });
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
if (e.code !== "EEXIST")
|
|
85
|
+
throw e;
|
|
86
|
+
const cur = readHolder(file);
|
|
87
|
+
if (cur && lockHolderAlive({ pid: cur.pid }))
|
|
88
|
+
throw new Error(`${agent} is already being called (call ${cur.call_id}, pid ${cur.pid}). Wait for it to finish.`);
|
|
89
|
+
if (attempt >= 1)
|
|
90
|
+
throw new Error(`Could not take ${file}; try again.`);
|
|
91
|
+
fs.rmSync(file, { force: true });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
let released = false;
|
|
95
|
+
const release = () => {
|
|
96
|
+
if (released)
|
|
97
|
+
return;
|
|
98
|
+
released = true;
|
|
99
|
+
process.off("exit", release);
|
|
100
|
+
if (readHolder(file)?.call_id === callId)
|
|
101
|
+
fs.rmSync(file, { force: true });
|
|
102
|
+
};
|
|
103
|
+
process.on("exit", release);
|
|
104
|
+
return { release };
|
|
105
|
+
}
|
|
106
|
+
/** Wake one global agent once, alone, in `dir`. Leaves task.md, log/ and result.md in `<home>/calls/<call-id>/`. */
|
|
107
|
+
export async function callAgent(o) {
|
|
108
|
+
const say = o.say ?? ((s) => console.error(s));
|
|
109
|
+
const agent = resolveCallAgent(o.home, o.agent);
|
|
110
|
+
const dir = path.resolve(o.dir);
|
|
111
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
|
|
112
|
+
throw new Error(`Working directory not found: ${dir}`);
|
|
113
|
+
const real = (p) => {
|
|
114
|
+
try {
|
|
115
|
+
return fs.realpathSync(p);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return path.resolve(p);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const realDir = real(dir);
|
|
122
|
+
const realHome = real(o.home);
|
|
123
|
+
// The called agent is the only one listed, so only its files are protected: nothing may run where the rest of the home is writable.
|
|
124
|
+
if (isInside(realHome, realDir) || isInside(realDir, realHome)) {
|
|
125
|
+
throw new Error(`Working directory ${dir} overlaps the agent-lyceum home ${o.home}: a call could change other agents' files there. Pass a --dir that is neither inside nor above the agent-lyceum home.`);
|
|
126
|
+
}
|
|
127
|
+
if (!o.task.trim())
|
|
128
|
+
throw new Error("No task given: pass it as text or with --task-file.");
|
|
129
|
+
const callId = newRunId();
|
|
130
|
+
const callDir = path.join(callsDir(o.home), callId);
|
|
131
|
+
const lease = lockAgent(o.home, agent.name, callId);
|
|
132
|
+
try {
|
|
133
|
+
fs.mkdirSync(path.join(callDir, "log"), { recursive: true });
|
|
134
|
+
fs.writeFileSync(path.join(callDir, "task.md"), o.task);
|
|
135
|
+
for (const d of memoryDirs(agent))
|
|
136
|
+
fs.mkdirSync(d, { recursive: true });
|
|
137
|
+
const project = callProject(o.home, agent, dir, callDir);
|
|
138
|
+
const guard = new ProtectedGuard(project);
|
|
139
|
+
say(`Calling ${agent.name} in ${dir} (call ${callId})`);
|
|
140
|
+
const invoke = o.invoker ?? realInvoker;
|
|
141
|
+
const result = await invoke({
|
|
142
|
+
project,
|
|
143
|
+
agent,
|
|
144
|
+
workDir: callDir,
|
|
145
|
+
systemPrompt: buildSoloSystemPrompt(project, agent),
|
|
146
|
+
userPrompt: buildCallUserPrompt(agent, o.task),
|
|
147
|
+
timeoutSec: project.dispatcher.wake_timeout_sec,
|
|
148
|
+
signal: o.signal,
|
|
149
|
+
logDir: path.join(callDir, "log"),
|
|
150
|
+
}).catch((e) => ({ ok: false, text: "", exitCode: null, timedOut: false, error: e.message }));
|
|
151
|
+
const reverted = guard.check([agent]).map((v) => v.file);
|
|
152
|
+
for (const f of reverted)
|
|
153
|
+
say(`warn ${agent.name} changed ${f}; it was put back.`);
|
|
154
|
+
const cancelled = !!result.cancelled;
|
|
155
|
+
const error = result.ok ? undefined : cancelled ? "cancelled" : (result.error ?? (result.timedOut ? "timed out" : "failed"));
|
|
156
|
+
atomicWrite(path.join(callDir, "result.md"), result.ok ? `${result.text.trimEnd()}\n` : `# Call ${cancelled ? "cancelled" : "failed"}\n\n${error}\n`);
|
|
157
|
+
return { callId, callDir, ok: result.ok, cancelled, text: result.ok ? result.text : "", error, reverted };
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
lease.release();
|
|
161
|
+
}
|
|
162
|
+
}
|