sakura-infinity 0.1.1 → 0.1.3

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 CHANGED
@@ -1,276 +1,137 @@
1
- # Infinity (`sakura-infinity`)
1
+ <p align="center">
2
+ <img src="./assets/readme-banner.png" alt="Infinity — Long-horizon research that runs to completion." width="100%" />
3
+ </p>
2
4
 
3
- Run many agents (1 to 100) in parallel on one task and keep the best result. Built on the [Sakura agent framework](https://www.npmjs.com/package/sakura-agent). A task is a small TypeScript package; one command (`infinity run <task>`) or one library call (`startRun`) runs it. It runs on the machine where it is started; for a remote machine, install and run it there.
5
+ # Infinity
4
6
 
5
- There is one kind of task: agents improve a result and every submit is scored. What differs is the **tools** the agents get:
7
+ [English](README.md) · [简体中文](README.zh-CN.md)
6
8
 
7
- - **shell** (the `code` preset): `read`, `write`, `edit`, `bash` and `submit`; each submit is scored by your evaluator on data the agents cannot see (machine learning, a faster program; for example `tasks/covertype/`).
8
- - **lean** (the `math` preset): file tools and a `lean` check; the evaluator is the Lean verifier (score 1 for an accepted proof), and the run ends at the first proof the local Lean accepts.
9
+ [![npm](https://img.shields.io/npm/v/sakura-infinity)](https://www.npmjs.com/package/sakura-infinity)
10
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D22.18-3c873a)](package.json)
11
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
9
12
 
10
- The test suite covers both tool kits. Real-model runs have also produced an accepted Lean proof and a scored Covertype submission.
13
+ **Many coding agents on one task. Every attempt is scored; you keep the best.**
11
14
 
12
- ## Quick start
13
-
14
- You need Node 22.18 or newer, and a key of DeepSeek, OpenAI or Anthropic. Math tasks also need Lean 4 (`curl https://elan.lean-lang.org/elan-init.sh -sSf | sh`); code tasks need whatever your evaluator runs (Python for the template).
15
-
16
- ```sh
17
- npm install -g sakura-infinity
18
- export DEEPSEEK_API_KEY=... # or INFINITY_PROVIDER=openai with OPENAI_API_KEY, or anthropic with ANTHROPIC_API_KEY
19
-
20
- infinity run math-parity --agents 3 --view # a bundled example: prove "n % 2 = 0 or n % 2 = 1"; ends at the first accepted proof
21
-
22
- infinity new code my-task # my-task/task.mts (the form) and my-task/evaluate.py (an example scorer)
23
- # edit the prompt in task.mts and the scoring in evaluate.py, then:
24
- infinity run ./my-task --agents 4 --wall-minutes 30 --view
25
- ```
26
-
27
- `--view` opens the run page at `http://127.0.0.1:4173/`: the best result first (score, agent, command, files, folder, commit), then time and tokens against their limits, what needs you, the score over time and the agents. The best solution is a Git commit in the agent's folder; the page shows where. `infinity --help` lists every flag; `infinity recommend --write machine.json` saves what this computer can carry.
28
-
29
- What a real install did on 2026-11-16 (macOS, DeepSeek): `math-parity` with one agent proved the statement for 9,104 tokens; the code template with one agent reached the top score of 100 and stopped at its 300,000-token budget. No key was written into either run.
30
-
31
- ## Architecture
32
-
33
- ### Components
34
-
35
- ```mermaid
36
- flowchart TB
37
- subgraph Entries
38
- CLI["infinity run / view<br/>(a person)"]
39
- LIB["startRun + Sakura tools<br/>infinity_run / status / stop<br/>(an Agent)"]
40
- end
41
- FORM["Task form (.ts / .json)<br/>+ machine file<br/>(infinity new / recommend)"] --> CLI
42
- FORM --> LIB
43
- CLI --> LAUNCH
44
- LIB --> LAUNCH
45
- LAUNCH["Run launcher (launch.ts)<br/>capacity recommendation, options, task package"] --> ORCH
46
-
47
- subgraph ORCH["Orchestrator (one Node process)"]
48
- direction TB
49
- LADDER["Ladder<br/>1, 2, 4 ... 100 agents"]
50
- GATE["Gate + Budget<br/>throttle brake, token budget"]
51
- RESCUE["Rescue<br/>restart stuck agents"]
52
- POOL["Resource pool<br/>Lean slots, evaluation slots,<br/>CPU slot gate, GPU slots"]
53
- KEEPER["Hidden keeper<br/>hides labels, journal, restores"]
54
- LEDGER["Ledger<br/>ledger.jsonl, events.jsonl,<br/>leaderboard, report"]
55
- SAMPLER["Machine sampler<br/>machine.jsonl every 5 s"]
56
- end
57
-
58
- ORCH --> MODES
59
- subgraph MODES["One task mode: scores every submit, with a tool kit"]
60
- MATH["Lean kit (math preset)<br/>read, write, lean check<br/>verifier = evaluator"]
61
- CODE["Shell kit (code preset)<br/>read, write, edit, bash, submit<br/>your evaluator"]
62
- end
63
-
64
- subgraph AGENTS["Sakura agents (1..N)"]
65
- AG["Own Git work dir, session file,<br/>tools, Goal"]
66
- end
67
- MODES --> AGENTS
68
- AGENTS -->|"model requests"| GATE
69
-
70
- subgraph REVIEW["Reviewers"]
71
- SAFE["Safety review<br/>risky commands + Infinity rules"]
72
- BRANCH["Branch review<br/>forked read-only reviewer,<br/>advice steered into the agent"]
73
- end
74
- AGENTS -.-> SAFE
75
- AGENTS -.-> BRANCH
76
- BRANCH -.->|"advice"| AGENTS
77
-
78
- VIEWER["Run viewer (read-only, 127.0.0.1)"] -.->|"reads the run directory"| LEDGER
79
- VIEWER -.-> SAMPLER
80
- ```
81
-
82
- The launcher turns the caller's choices and the machine's capacity into one task and starts the orchestrator; both entries use the same code. The orchestrator owns everything that is shared by all agents: how many live (ladder), the brake on model requests (gate), the token budget, the pools that limit heavy work, the hidden data, and the records. A mode defines what a submission is and how it is judged; the agents are Sakura agents, each in its own Git work directory. Reviewers and the viewer are optional parts: the viewer only reads the files of the run and never controls it.
83
-
84
- ### One run
85
-
86
- ```mermaid
87
- sequenceDiagram
88
- autonumber
89
- participant U as Person or Agent
90
- participant L as Launcher
91
- participant O as Orchestrator
92
- participant K as Hidden keeper
93
- participant A as Agents (1..N)
94
- participant M as Mode (verifier / evaluator)
95
- participant R as Reviewers
96
- participant D as Run directory
97
-
98
- U->>L: infinity run <task> / startRun
99
- L->>O: task, agents, budget, limits
100
- O->>K: hide labels (journal written)
101
- O->>D: run_start, state.json
102
- loop the ladder: 1, 2, 4 ... until the ceiling
103
- O->>A: start agents, each with a Goal and a strategy hint
104
- A->>A: work, commit every turn, run commands
105
- A->>M: submit (proof, or command + files + commit)
106
- M->>M: verify or evaluate on hidden data (pool slot)
107
- M->>D: result line in ledger.jsonl, leaderboard, report
108
- R-->>A: safety review of risky commands, advice from branch review
109
- O->>O: throttle? drop a rung. 3 replies each, no throttle? next rung
110
- end
111
- Note over O: stop rule: first proof, target score, token budget,<br/>wall limit, quota used up, or the user's stop
112
- U-->>O: stop() / Ctrl-C (optional)
113
- O->>A: stop agents in order
114
- O->>K: restore hidden labels
115
- O->>D: run_end, final report
116
- O-->>U: outcome (reason, bestScore, tokensUsed)
117
- ```
118
-
119
- A run starts by hiding the labels, then raises the number of live agents rung by rung while the provider does not throttle. Every submission is checked by the mode (Lean for math, your evaluator for code) and written to the ledger, which feeds the leaderboard and the report. The run ends by a stop rule or by the user; the agents are stopped, the labels are put back, and the final report is written.
120
-
121
- More detail: `docs/archive/02-architecture-draft.md`, `docs/13-design-review.md`, `docs/18-target-architecture.md`.
122
-
123
- ## How to run a test
124
-
125
- The sections below work from a clone of the repository (for development, and for the Covertype example, which prepares a data set next to the repository). From a clone, `node bin/infinity.ts` takes the place of `infinity`. All commands are run in the repository's directory.
126
-
127
- ### 1. Install from the repository
128
-
129
- You need Node 22.18 or newer and git. For math tasks you need Lean 4 (`curl https://elan.lean-lang.org/elan-init.sh -sSf | sh`; the program checks `lean --version` and `lake --version` at start and prints this command if they are missing; Mathlib is not needed). For the code task you need Python 3 with numpy, pandas and scikit-learn.
130
-
131
- ```sh
132
- npm install # sakura-agent comes from npm
133
- npm run check # types, lint, format, tests (about 3 minutes); optional
134
- ```
135
-
136
- ### Install on another machine
137
-
138
- Clone the public repository after the update has been pushed. Use the same commit on each machine when you need to reproduce a run.
139
-
140
- ```sh
141
- git clone https://github.com/Vist233/infinity_Agents.git infinity-agent
142
- cd infinity-agent
143
- npm ci
144
- ```
15
+ Infinity runs 1 to 100 agents in parallel on one task and scores each submission with your evaluator: a model's accuracy on hidden data, the speed of a program, a loss, or a Lean 4 proof. It is built on [Sakura](https://github.com/Vist233/Sakura), a complete coding agent you can build with, and published on npm as `sakura-infinity`.
145
16
 
146
- GitHub supplies the source. The lockfile supplies the dependency versions. A GitHub Release is optional. Keep your own task, input data and credentials on the machine that will run the agents. Use Node 22.18 or later and Git. Use Linux for host monitoring and command limits.
17
+ ## Why Infinity
147
18
 
148
- With your task and evaluator in `../my-task/`, configure the model as shown below and run:
149
-
150
- ```sh
151
- node bin/infinity.ts recommend --task ../my-task/task.ts --write ../my-task/machine.json
152
- node bin/infinity.ts run ../my-task/task.ts --machine ../my-task/machine.json --agents 3 --wall-minutes 30
153
- ```
19
+ Running more agents is easy; getting more out of them is not. Agents spend most of their time waiting for the model, while training a model or running a test suite needs the CPU. Infinity keeps those apart: **how many agents explore and how many heavy jobs run at once are separate limits.**
154
20
 
155
- Paths in the form are relative to the form file. Install the evaluator's dependencies on that machine before starting. See the [Agent guide](AGENT-GUIDE.md) for the task fields.
21
+ In a 16 vCPU capacity test (about 4.5 hours of runs), adding agents alone raised `load/core` from 1.63 to 1.97 without a stable gain in score. With 16 agents sharing 8 heavy-work slots, `load/core` fell to about 1.02 and the first scored result came after 16.5 minutes instead of 29.3. The GPU sat near 0%: the bottleneck of that task was the CPU. These are the results of one task on one machine, not a guarantee.
156
22
 
157
- ### 2. Configure the model
23
+ ## Quick start
158
24
 
159
- The providers are the official APIs of DeepSeek (the default), OpenAI and Anthropic. The key is read from the environment once, removed from it (the agents' commands never see it), and never printed or written.
25
+ You need Node 22.18 or newer and a key of DeepSeek, OpenAI or Anthropic. Math tasks also need Lean 4 (`curl https://elan.lean-lang.org/elan-init.sh -sSf | sh`); code tasks need whatever your evaluator runs (Python for the template).
160
26
 
161
27
  ```sh
162
- export DEEPSEEK_API_KEY=... # default: DeepSeek, model deepseek-flash
163
- export INFINITY_PROVIDER=openai OPENAI_API_KEY=... # or OpenAI (gpt-5)
164
- export INFINITY_PROVIDER=anthropic ANTHROPIC_API_KEY=... # or Anthropic (claude-sonnet-5-5)
165
- export INFINITY_MODEL=... # optional: another model of the chosen provider
166
- ```
28
+ npm install -g sakura-infinity
29
+ export DEEPSEEK_API_KEY=... # or INFINITY_PROVIDER=openai with OPENAI_API_KEY, or anthropic with ANTHROPIC_API_KEY
167
30
 
168
- ### 3. Run a math task
31
+ infinity run math-parity --agents 3 --view # a bundled example: prove "n % 2 = 0 or n % 2 = 1"; ends at the first accepted proof
169
32
 
170
- ```sh
171
- node bin/infinity.ts run math-parity --agents 3 --view # prove "n % 2 = 0 or n % 2 = 1"; ends at the first accepted proof
172
- node bin/infinity.ts run math-odd-sum --agents 10 --view # needs induction
33
+ infinity new code my-task # my-task/task.mts (the form) and my-task/evaluate.py (an example scorer)
34
+ # edit the prompt in task.mts and the scoring in evaluate.py, then:
35
+ infinity run ./my-task --agents 4 --wall-minutes 30 --view
173
36
  ```
174
37
 
175
- A real run with one agent proved `math-parity` in about 20 seconds for about 9,000 tokens. Your own statement: `node bin/infinity.ts new math my-statement`, edit the `statement` line, then `infinity run ./my-statement`.
38
+ `--view` opens the run page at `http://127.0.0.1:4173/`: the best result first (score, agent, commit, folder), then time and tokens against their limits, the score over time and the agents. `infinity --help` lists every flag; `infinity recommend --write machine.json` saves what this computer can carry.
176
39
 
177
- ### 4. Run a code task
40
+ The key is read from the environment once and removed from it: the agents' commands never see it, and it is never printed or written. `INFINITY_MODEL` picks another model of the chosen provider.
178
41
 
179
- ```sh
180
- python3 -m venv .venv-ml && .venv-ml/bin/pip install numpy pandas scikit-learn
181
- .venv-ml/bin/python tasks/covertype/prepare.py 150000 # once; a sample of the data (no number = all 581,012 rows)
182
- PATH="$PWD/.venv-ml/bin:$PATH" node bin/infinity.ts run covertype --agents 2 --tokens 1000000 --wall-minutes 20 --view
183
- ```
42
+ ## How a run works
184
43
 
185
- Covertype asks the agents to predict the forest cover type (7 classes); the score is accuracy on hidden labels. Start small, and use the sample: on a laptop, 2 agents on the full data had no scored submission after 20 minutes (training is slow and one CPU slot is shared), so expect the first scores later than in the math task. Flags: `node bin/infinity.ts --help` (conflicting flags are refused with a message). `--agents N` always wins over the machine's recommendation, which is printed first. `--no-review` leaves the branch review out (it can be about half of the tokens).
44
+ - **A task is a form.** The problem in words, what the agents may see, what is hidden, and a program that scores a submission. What the computer can carry is a separate machine file. Any "improve a result" task fits.
45
+ - **Two tool kits.** The `code` preset gives each agent `read`, `write`, `edit`, `bash`, `submit` and `handoff`; a submit is a command, listed files and a commit, scored by your evaluator on data the agents cannot see. The `math` preset gives file tools and a `lean` check; the Lean verifier is the evaluator, and the run ends at the first accepted proof.
46
+ - **A ladder of agents.** The run starts with one agent and doubles (1, 2, 4 … up to your ceiling) while the provider does not throttle; a throttling answer drops one rung, and a used-up quota stops the run.
47
+ - **Pools for heavy work.** CPU slots (`--slots N`), evaluation slots, Lean slots and GPU slots cap what runs at once, whatever the number of agents.
48
+ - **Hidden data stays hidden.** Labels are moved to a private path with a journal while the agents work and put back at the end, also on Ctrl-C and on a crash.
49
+ - **Everything is a file.** Each agent works in its own Git directory with a commit after every turn; the ledger, events, leaderboard and report are written to the run directory, and the viewer only reads them.
50
+ - **Stop rules.** First proof, target score, token budget, wall time, quota, or your stop.
186
51
 
187
- ### 5. Your own task (no TypeScript needed)
52
+ ## Built on Sakura
188
53
 
189
- A task is a **form** (a `.ts` object or a `.json` file): the problem in words, what the agents may see, what is hidden, and a program that scores a submission. What the computer can carry is a separate **machine file**. The code and the math presets are the same kind of form with different tools; nothing is fixed to one problem, so any "improve a result" task fits (a model's accuracy, the speed of a program, a loss).
54
+ Each agent is a Sakura agent with its own work directory, session file, tools and goal. Two reviewers use Sakura's composition:
190
55
 
191
- ```sh
192
- node bin/infinity.ts recommend --write machine.json # what this computer can carry (agents, slots, threads); edit by hand if you like
193
- node bin/infinity.ts new code my-task # my-task/task.ts (the form) and my-task/evaluate.py (an example scorer); or: new math my-task
194
- node bin/infinity.ts run ./my-task --machine machine.json --view
195
- ```
56
+ - **Safety review.** Sakura's review plugin judges risky commands; in front of it, Infinity's rules refuse pushing, ssh, uploads, killing by name, credential files, the hidden data, other agents' directories and the run's own files. `review: false` in a task switches it off, and the report says so.
57
+ - **Branch review (optional).** Every few minutes an agent's conversation is forked into a reviewer with the same model, system text and tools, so the provider's cache still applies, but a guard lets it only `read` files in the agent's directory. It answers `OK` or gives short advice, which is steered into the agent marked as not coming from the user. The scheduling, results and lifecycle are Infinity's code; Sakura provides the session fork, assembly, plugins and execution boundary. Its benefit is not measured and it costs tokens (about half of them in one real run); `--no-review` leaves it out.
196
58
 
197
- The form's fields and the rules for a good evaluator are in [AGENT-GUIDE.md](AGENT-GUIDE.md), which is written for an AI (or a script) that runs Infinity too. `tasks/covertype/task.ts` is a complete real example.
198
-
199
- ### 6. Open the viewer
200
-
201
- `--view` serves a read-only page at `http://127.0.0.1:4173/` (`--view-port N` changes it; the address is printed). It shows the rungs, scored submissions with the best-so-far line, the machine, the agents, the reviews and the leaderboard. It has no dependencies, binds to `127.0.0.1` only, answers GET only and never writes into a run. On its own, for a running or finished run (or a directory of runs, newest first):
59
+ ## Your own task
202
60
 
203
61
  ```sh
204
- node bin/infinity.ts view runs
62
+ infinity recommend --write machine.json # what this computer can carry (agents, slots, threads); edit it if you like
63
+ infinity new code my-task # or: infinity new math my-statement
64
+ infinity run ./my-task --machine machine.json --view
205
65
  ```
206
66
 
207
- On a remote machine forward the port (`ssh -L 4173:127.0.0.1:4173 host`), or show it to others with a token: `infinity view runs --host 0.0.0.0 --token <secret>` (or `INFINITY_VIEW_TOKEN`); open it once with `?token=<secret>`. With a token any Host is accepted, so a reverse proxy works without rewriting it.
67
+ The form's fields and the rules for a good evaluator are in [AGENT-GUIDE.md](AGENT-GUIDE.md), written for an AI or a script that runs Infinity too. [`tasks/covertype/task.ts`](tasks/covertype/task.ts) is a complete real example: predict the forest cover type (7 classes), scored by accuracy on hidden labels.
208
68
 
209
- ### 7. Read the results
69
+ ## Results of a run
210
70
 
211
71
  Each run writes `runs/<task>-<time>/`:
212
72
 
213
73
  | File | What it holds |
214
74
  |---|---|
215
- | `report/report.html` | leaderboard, score over time, reviews, warnings; a snapshot, rewritten at most once a minute after results, at each rung change and at the end (the viewer ranks live from the ledger) |
75
+ | `report/report.html` | leaderboard, score over time, reviews, warnings |
216
76
  | `report/leaderboard.csv` | one row per scored result: agent, score, commit, work directory |
217
77
  | `ledger.jsonl` | what each agent did; `result` lines are submissions |
218
78
  | `events.jsonl` | rungs, throttles, reviews, refusals, warnings, `run_end` |
219
79
  | `machine.jsonl` | machine readings every 5 s (Linux only) |
220
- | `run-facts.json`, `state.json` | the command line and the facts of the run; the state for resuming |
221
- | `agents/NNN/work/` | one Git repository per agent, a commit after every turn; the best solution is the commit named in the first row of the leaderboard (`git show <commit>`) |
80
+ | `agents/NNN/work/` | one Git repository per agent; the best solution is the commit in the first row of the leaderboard |
222
81
 
223
- The last line printed is the outcome, for example `{"reason":"target","tokensUsed":8781,"bestScore":1}` (a proof task scores 1 for an accepted proof and ends at the first one). Check that no key is in the run: `grep -rlF -- "$DEEPSEEK_API_KEY" runs/<run> | wc -l` must print 0.
82
+ The last line printed is the outcome, for example `{"reason":"target","tokensUsed":8781,"bestScore":1}`.
224
83
 
225
- ### 8. Stop and resume
84
+ - **Viewer.** `infinity view runs` serves a read-only page for a running or finished run. It binds to `127.0.0.1`, answers GET only and never writes into a run. On a remote machine forward the port (`ssh -L 4173:127.0.0.1:4173 host`), or share it with `--host 0.0.0.0 --token <secret>`.
85
+ - **Stop.** Ctrl-C, SIGTERM or `stop()` stops the agents in order, restores hidden labels and writes the report. `--wall-minutes N` and `--tokens N` set limits.
86
+ - **Resume.** `infinity run <task> --resume runs/<run> <the same flags>` reopens the sessions and work directories. After a hard kill (`kill -9`, power loss), put hidden labels back first: `node examples/recover-hidden.ts runs/<run>/.keeper` from a clone.
226
87
 
227
- - **Stop:** Ctrl-C, SIGTERM, or `stop()` from the library stops the agents, restores hidden labels and writes the report. `--wall-minutes N` records `wall` as the stop reason. Use `--tokens N` to set a budget or `--no-token-limit` to clear the task's default. For `startRun`, set `tokens: null` to clear the default.
228
- - **Resume:** `node bin/infinity.ts run covertype --resume runs/<run> <the same flags>` opens the existing sessions and work directories. A command that was interrupted must be started again by the agent.
229
- - After a hard kill (`kill -9`, power loss) put hidden labels back first: `node examples/recover-hidden.ts runs/<run>/.keeper`.
230
-
231
- ### 9. Use it as an Agent
88
+ ## Use it from code or from an agent
232
89
 
233
90
  ```ts
234
91
  import { startRun } from "./src/launch.ts";
235
92
  import { createInfinityTools } from "./src/sakura-tools.ts";
236
93
  import { formPackage } from "./src/form.ts";
237
94
  import form from "./tasks/covertype/task.ts";
238
- const covertype = formPackage(form, "./tasks/covertype");
239
95
 
240
- const run = await startRun(covertype, { model, agents: 8, wallMinutes: 45 }); // returns at once; the run goes on in this process
241
- console.log(run.runDir, run.recommendation.lines);
242
- console.log(run.status()); // read from the run's files: state, agents alive, tokens, best score
243
- console.log(run.events().events.slice(-3)); // the newest events; run.events(next) gives only what is new
244
- await run.stop(); // ends the run in order and waits (run.done settles on its own too)
96
+ const covertype = formPackage(form, "./tasks/covertype");
97
+ const run = await startRun(covertype, { model, agents: 8, wallMinutes: 45 }); // returns at once; the run goes on in this process
98
+ console.log(run.status()); // state, agents alive, tokens, best score
99
+ await run.stop(); // ends the run in order and waits
245
100
 
246
- const tools = createInfinityTools({ packs: [covertype], model }); // infinity_run, infinity_status, infinity_stop, infinity_recommend for a Sakura agent
247
- // infinity_run also takes a form written by the Agent itself: { form: {...}, formDir: "/abs/folder" }; see AGENT-GUIDE.md
101
+ // infinity_run, infinity_status, infinity_stop and infinity_recommend as tools for a Sakura agent
102
+ const tools = createInfinityTools({ packs: [covertype], model });
248
103
  ```
249
104
 
250
- ### Known limits
105
+ These imports work from a clone of this repository.
106
+
107
+ ## Limits
108
+
109
+ - **Linux for full function.** On macOS a run works, but machine readings, command limits and the cleanup of leftover processes are not supported; the report says so.
110
+ - **No sandbox.** The code agents run and Lean proof files have your user's rights, network included. The rules and the review lower the risk and prove nothing. Use a machine you can afford to lose files on, without secrets in the home directory.
111
+ - **Hidden labels are not blocked by the operating system.** They are moved to an unguessable path during the run; a shell can read what your user can read.
112
+ - **Not verified:** runs above 8 agents on macOS, GPU pools on real hardware, and the benefit of the branch review.
251
113
 
252
- - **The run side needs Linux for full function.** On macOS a run works, but machine readings, limits on commands and the cleanup of leftover processes are unsupported; the report and events say so in a warning. The recommended agent count there is only a hint.
253
- - **No sandbox.** Lean proof files and the code that agents run have your user's rights, network included. The review and the rules lower the risk and prove nothing. Run on a machine you can afford to lose files on, not on one with secrets in the home directory.
254
- - **Hidden labels are not blocked at the operating-system level.** They are moved to an unguessable private path during the run and restored at the end; the agents' shell can read files your user can read (`ShellGuard` is planned, not built).
255
- - **Provider quota.** A throttling answer drops one rung; when the quota is used up the run stops. A very long provider wait (days) is treated as a quota end.
256
- - **Not verified:** runs above 8 agents on this Mac, any real run without scripted help on a machine other than the owner's Mac and server, GPU pools on real hardware (a fake `nvidia-smi` is tested), a real run where nobody proves it, and the benefit of the branch review (not measured; it costs tokens).
257
- - **One flaky test:** `test/scale-code.test.ts` compares real timings and can fail when the machine is busy; it passes alone.
114
+ <details>
115
+ <summary>Lean safety</summary>
258
116
 
259
- ## Lean and the sandbox
117
+ A proof file is a program: Lean runs code at compile time (`#eval`, macros, `initialize`). There is no sandbox by default. Instead the Lean process gets a clean environment (only `PATH`, `HOME`, `LEAN_PATH`; no keys), the math agents have no shell and their file tools are confined to their work directory, and a deny-list rejects `#eval`, macros, `elab`, `initialize`, `unsafe`, `extern` and other imports at `submit` (it is not a boundary). `sandbox: true` in a task confines every Lean process on macOS with `sandbox-exec`; there is no sandbox on Linux in this version.
260
118
 
261
- - A proof task (the math preset) needs `lean` and `lake` on the PATH. Mathlib is optional and is checked at start only when a task asks for it.
262
- - **Without the sandbox, a proof file is a program that runs with your rights.** Lean runs code at compile time (`#eval`, macros, `initialize`). The owner decided that there is no sandbox by default. Instead: the Lean process gets a clean environment (only PATH, HOME, LEAN_PATH; no keys), the agents have no shell and their file tools are confined to their work directory, and a deny-list rejects `#eval`, macros, `elab`, `initialize`, `unsafe`, `extern` and other imports at `submit` (it is not a boundary).
263
- - `sandbox: true` in a task confines every Lean process on macOS with `sandbox-exec`. There is no sandbox on Linux in this version.
264
- - The official check accepts a proof only if it compiles, has no `sorry`, depends only on `propext`, `Classical.choice`, `Quot.sound`, and `theorem main` has exactly the type `Statement.Goal`.
265
- - Every agent checks the orchestrator's `../finished` marker for its Goal. A Lean result scores 1 when the verifier accepts the proof.
119
+ The check accepts a proof only if it compiles, has no `sorry`, depends only on `propext`, `Classical.choice` and `Quot.sound`, and `theorem main` has exactly the type `Statement.Goal`.
266
120
 
267
- ## Shell tasks (the code preset)
121
+ </details>
122
+
123
+ ## Development
124
+
125
+ ```sh
126
+ git clone https://github.com/Vist233/infinity_Agents.git infinity-agent
127
+ cd infinity-agent
128
+ npm ci
129
+ npm run check # types, lint, format, tests (about 3 minutes; uses real Lean when it is installed)
130
+ node bin/infinity.ts run math-parity --agents 1
131
+ ```
268
132
 
269
- Every agent has `read`, `write`, `edit`, `bash`, `submit` and `handoff`; the submit is command + listed files + commit, scored by your evaluator on data the agents cannot see. `handoff` (from `sakura-agent-tools`) lets agents share checked work packages through one store per machine (`~/.infinity/handoff`, moved by `INFINITY_HANDOFF_DIR`), shared by every agent of every run. Plans and decisions: `docs/05-general-mode-plan.md`, `docs/10-branch-review-and-first-ml-run-plan.md`, `docs/decisions.md`. A deployment can supply a Sakura tool environment through `INFINITY_WORKER_ENVIRONMENT` or `runTask(..., { createEnvironment })` to control shell access and accelerators (`docs/11-runbook.md`).
133
+ From a clone, `node bin/infinity.ts` takes the place of `infinity`. For the Covertype example: `python3 -m venv .venv-ml && .venv-ml/bin/pip install numpy pandas scikit-learn`, then `.venv-ml/bin/python tasks/covertype/prepare.py 150000` once.
270
134
 
271
- - **Branch review (optional):** every few minutes each agent's conversation is forked; a reviewer with the same model, system text and tools (so the provider's cache applies) may only `read` files in the agent's directory and says `OK` or gives short advice, which is steered into the agent marked as not coming from the user. It is not a gatekeeper and its benefit is not measured. It costs tokens: in the one real run, reviews were about half of the tokens counted.
272
- - **Safety review (`review`):** the framework's review plugin judges risky commands; in front of it Infinity's rules refuse pushing, ssh, uploads, killing by name, credential files, the hidden data, other agents' directories and the run's own files. `review: false` switches it off and the report says so.
273
- - **Hidden data:** moved away with a journal while the agents run and put back at the end (also on Ctrl-C and on a crash). The evaluator gets the private path. Even with a profile, the evaluator must not return hidden labels in its answer, and a hidden split that can be recomputed from public data is not hidden (covertype is public: the task forbids looking it up, which the rules and the reviewer enforce only as far as they notice).
274
- - The number of agents is yours to choose; the report only gives a hint (`docs/11-runbook.md`, "How many agents?"). Run-side limits (slots, thread limits, cleanup) are described in `docs/16-capacity-and-command-limits.md`. Where things stand: `docs/08-current-state.md`.
135
+ ## License
275
136
 
276
- Tests: `npm test` (about 3 minutes; uses real Lean when it is installed), `npm run check` (types, lint, format, tests), `npm run coverage`. Real-run evidence: `docs/test-report.md`.
137
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,137 @@
1
+ <p align="center">
2
+ <img src="./assets/readme-banner.png" alt="Infinity — Long-horizon research that runs to completion." width="100%" />
3
+ </p>
4
+
5
+ # Infinity
6
+
7
+ [English](README.md) · [简体中文](README.zh-CN.md)
8
+
9
+ [![npm](https://img.shields.io/npm/v/sakura-infinity)](https://www.npmjs.com/package/sakura-infinity)
10
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D22.18-3c873a)](package.json)
11
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
12
+
13
+ **多个 Coding Agent 做同一个任务。每次尝试都会评分,你保留最好的结果。**
14
+
15
+ Infinity 让 1 到 100 个 Agent 并行处理同一个任务,并用你的评测程序给每次提交打分:可以是模型在隐藏数据上的准确率、程序的运行速度、一个 loss,或者一个 Lean 4 证明。它基于 [Sakura](https://github.com/Vist233/Sakura)(一个你可以在其上构建的完整 Coding Agent)构建,在 npm 上发布为 `sakura-infinity`。
16
+
17
+ ## 为什么是 Infinity
18
+
19
+ 多跑几个 Agent 很容易,让它们真正多产出却不容易。Agent 大部分时间在等模型回复,而训练模型、跑测试却要占用 CPU。Infinity 把这两件事分开:**有多少个 Agent 在探索,和同时跑多少个重型任务,是两个独立的上限。**
20
+
21
+ 在一组 16 vCPU 的容量实验里(共约 4.5 小时),只增加 Agent 数量时,`load/core` 从 1.63 升到 1.97,分数没有稳定提升。16 个 Agent 共用 8 个重型任务槽位后,`load/core` 降到约 1.02,首个评分结果从 29.3 分钟提前到 16.5 分钟。GPU 利用率接近 0%:这个任务的瓶颈是 CPU。这是一台机器上一个任务的结果,不是保证。
22
+
23
+ ## 快速开始
24
+
25
+ 需要 Node 22.18 或更新版本,以及 DeepSeek、OpenAI 或 Anthropic 的 API Key。数学任务还需要 Lean 4(`curl https://elan.lean-lang.org/elan-init.sh -sSf | sh`);代码任务需要你的评测程序用到的环境(模板用 Python)。
26
+
27
+ ```sh
28
+ npm install -g sakura-infinity
29
+ export DEEPSEEK_API_KEY=... # 或 INFINITY_PROVIDER=openai 加 OPENAI_API_KEY,或 anthropic 加 ANTHROPIC_API_KEY
30
+
31
+ infinity run math-parity --agents 3 --view # 自带示例:证明 "n % 2 = 0 or n % 2 = 1";第一个证明被接受时结束
32
+
33
+ infinity new code my-task # 生成 my-task/task.mts(任务表单)和 my-task/evaluate.py(示例评分程序)
34
+ # 修改 task.mts 里的提示和 evaluate.py 里的评分,然后:
35
+ infinity run ./my-task --agents 4 --wall-minutes 30 --view
36
+ ```
37
+
38
+ `--view` 会在 `http://127.0.0.1:4173/` 打开运行页面:最上面是最好的结果(分数、Agent、提交、目录),然后是时间和 token 与上限的对比、分数随时间的变化和各个 Agent。`infinity --help` 列出所有参数;`infinity recommend --write machine.json` 保存这台电脑能承载多少。
39
+
40
+ API Key 只从环境变量读取一次,读完就从环境中移除:Agent 运行的命令看不到它,它也不会被打印或写入文件。`INFINITY_MODEL` 可以选择同一供应商的其他模型。
41
+
42
+ ## 一次运行是怎样进行的
43
+
44
+ - **任务就是一张表单。** 用文字写清问题、Agent 能看到什么、什么是隐藏的,再加一个给提交打分的程序。这台电脑能承载多少,写在单独的机器文件里。任何"改进一个结果"的任务都适用。
45
+ - **两套工具。** `code` 预设给每个 Agent `read`、`write`、`edit`、`bash`、`submit` 和 `handoff`;一次提交包括命令、列出的文件和一个 Git 提交,由你的评测程序在 Agent 看不到的数据上打分。`math` 预设给文件工具和 `lean` 检查;Lean 验证器就是评测程序,第一个证明被接受时运行结束。
46
+ - **Agent 数量逐级增加。** 运行从一个 Agent 开始,模型供应商不限流时逐级翻倍(1、2、4……直到你设的上限);遇到限流就降一级,配额用完就停止。
47
+ - **重型任务有槽位。** CPU 槽位(`--slots N`)、评测槽位、Lean 槽位和 GPU 槽位限制同时运行的重型任务数,与 Agent 数量无关。
48
+ - **隐藏数据保持隐藏。** Agent 工作时,标签被移到一个私有路径并记下日志,结束时放回原处;按 Ctrl-C 或崩溃时也会放回。
49
+ - **一切都是文件。** 每个 Agent 在自己的 Git 目录里工作,每轮结束都提交一次;账本、事件、排行榜和报告都写在运行目录里,查看页面只读取它们。
50
+ - **停止条件。** 第一个证明、目标分数、token 预算、运行时间、配额,或者你手动停止。
51
+
52
+ ## 基于 Sakura
53
+
54
+ 每个 Agent 都是一个 Sakura Agent,有自己的工作目录、会话文件、工具和目标。两种 Reviewer 用到了 Sakura 的组合能力:
55
+
56
+ - **安全审查。** 由 Sakura 的审查插件判断有风险的命令;在它之前,Infinity 自己的规则会拒绝推送、ssh、上传、按名字杀进程、读凭据文件、访问隐藏数据、进入其他 Agent 的目录和改动运行自身的文件。在任务里写 `review: false` 可以关掉它,报告里会注明。
57
+ - **Branch Review(可选)。** 每隔几分钟,把一个 Agent 的会话 fork 成一个 Reviewer。它用同样的模型、系统提示和工具声明,所以供应商的缓存仍然有效;但 Guard 只允许它 `read` 这个 Agent 目录里的文件。它回答 `OK` 或给出简短建议,建议会注入这个 Agent,并标明不是来自用户。调度、结果和生命周期是 Infinity 的代码;Sakura 提供会话 fork、装配、插件和执行边界。它的收益还没有测量过,而且要花 token(在一次真实运行里约占一半);`--no-review` 可以不用它。
58
+
59
+ ## 你自己的任务
60
+
61
+ ```sh
62
+ infinity recommend --write machine.json # 这台电脑能承载多少(Agent、槽位、线程);可以手动修改
63
+ infinity new code my-task # 或者:infinity new math my-statement
64
+ infinity run ./my-task --machine machine.json --view
65
+ ```
66
+
67
+ 表单的字段和写好评测程序的规则见 [AGENT-GUIDE.md](AGENT-GUIDE.md),它是写给同样会运行 Infinity 的 AI 或脚本看的。[`tasks/covertype/task.ts`](tasks/covertype/task.ts) 是一个完整的真实例子:预测森林覆盖类型(7 类),按隐藏标签上的准确率打分。
68
+
69
+ ## 运行结果
70
+
71
+ 每次运行写入 `runs/<task>-<time>/`:
72
+
73
+ | 文件 | 内容 |
74
+ |---|---|
75
+ | `report/report.html` | 排行榜、分数随时间的变化、审查记录、警告 |
76
+ | `report/leaderboard.csv` | 每个评分结果一行:Agent、分数、提交、工作目录 |
77
+ | `ledger.jsonl` | 每个 Agent 做了什么;`result` 行是提交 |
78
+ | `events.jsonl` | 级数变化、限流、审查、拒绝、警告、`run_end` |
79
+ | `machine.jsonl` | 每 5 秒一次的机器读数(仅 Linux) |
80
+ | `agents/NNN/work/` | 每个 Agent 一个 Git 仓库;最好的方案是排行榜第一行指向的提交 |
81
+
82
+ 最后打印的一行是运行结果,例如 `{"reason":"target","tokensUsed":8781,"bestScore":1}`。
83
+
84
+ - **查看页面。** `infinity view runs` 为正在运行或已结束的运行提供一个只读页面。它只绑定 `127.0.0.1`,只响应 GET,从不写入运行目录。在远程机器上可以转发端口(`ssh -L 4173:127.0.0.1:4173 host`),或者用 `--host 0.0.0.0 --token <secret>` 分享给别人。
85
+ - **停止。** Ctrl-C、SIGTERM 或 `stop()` 会按顺序停止 Agent、放回隐藏标签并写出报告。`--wall-minutes N` 和 `--tokens N` 设置上限。
86
+ - **续接。** `infinity run <task> --resume runs/<run> <同样的参数>` 重新打开会话和工作目录。被强制结束(`kill -9`、断电)之后,先在克隆的仓库里放回隐藏标签:`node examples/recover-hidden.ts runs/<run>/.keeper`。
87
+
88
+ ## 从代码或 Agent 中使用
89
+
90
+ ```ts
91
+ import { startRun } from "./src/launch.ts";
92
+ import { createInfinityTools } from "./src/sakura-tools.ts";
93
+ import { formPackage } from "./src/form.ts";
94
+ import form from "./tasks/covertype/task.ts";
95
+
96
+ const covertype = formPackage(form, "./tasks/covertype");
97
+ const run = await startRun(covertype, { model, agents: 8, wallMinutes: 45 }); // 立即返回;运行在当前进程里继续
98
+ console.log(run.status()); // 状态、存活的 Agent、token、最好分数
99
+ await run.stop(); // 按顺序结束运行并等待
100
+
101
+ // 把 infinity_run、infinity_status、infinity_stop 和 infinity_recommend 作为工具交给一个 Sakura Agent
102
+ const tools = createInfinityTools({ packs: [covertype], model });
103
+ ```
104
+
105
+ 这些 import 在克隆的仓库里可用。
106
+
107
+ ## 限制
108
+
109
+ - **完整功能需要 Linux。** 在 macOS 上可以运行,但不支持机器读数、命令限制和清理残留进程;报告里会注明。
110
+ - **没有沙箱。** Agent 运行的代码和 Lean 证明文件拥有你这个用户的权限,包括网络。规则和审查只能降低风险,不能证明安全。请在丢了文件也无所谓、主目录里没有密钥的机器上运行。
111
+ - **隐藏标签没有在操作系统层面封锁。** 运行期间它们被移到一个难以猜到的路径;Shell 能读到你这个用户能读的任何东西。
112
+ - **尚未验证:** macOS 上超过 8 个 Agent 的运行、真实硬件上的 GPU 槽位,以及 Branch Review 的收益。
113
+
114
+ <details>
115
+ <summary>Lean 的安全</summary>
116
+
117
+ 证明文件就是程序:Lean 在编译时会运行代码(`#eval`、宏、`initialize`)。默认没有沙箱,而是这样处理:Lean 进程只拿到干净的环境变量(只有 `PATH`、`HOME`、`LEAN_PATH`,没有密钥);数学任务的 Agent 没有 Shell,文件工具被限制在它的工作目录里;`submit` 时用一份黑名单拒绝 `#eval`、宏、`elab`、`initialize`、`unsafe`、`extern` 和其他 import(这不是边界)。在任务里写 `sandbox: true` 会在 macOS 上用 `sandbox-exec` 限制每个 Lean 进程;这个版本在 Linux 上没有沙箱。
118
+
119
+ 只有同时满足以下条件,证明才会被接受:能编译、没有 `sorry`、只依赖 `propext`、`Classical.choice` 和 `Quot.sound`,并且 `theorem main` 的类型恰好是 `Statement.Goal`。
120
+
121
+ </details>
122
+
123
+ ## 开发
124
+
125
+ ```sh
126
+ git clone https://github.com/Vist233/infinity_Agents.git infinity-agent
127
+ cd infinity-agent
128
+ npm ci
129
+ npm run check # 类型、lint、格式、测试(约 3 分钟;装了 Lean 时会用真实的 Lean)
130
+ node bin/infinity.ts run math-parity --agents 1
131
+ ```
132
+
133
+ 在克隆的仓库里,用 `node bin/infinity.ts` 代替 `infinity`。Covertype 示例需要先运行 `python3 -m venv .venv-ml && .venv-ml/bin/pip install numpy pandas scikit-learn`,再运行一次 `.venv-ml/bin/python tasks/covertype/prepare.py 150000`。
134
+
135
+ ## 许可证
136
+
137
+ MIT,见 [LICENSE](LICENSE)。
@@ -1,6 +1,6 @@
1
1
  // CPU slots are a resource of the machine, not of one run. Every run that has a slot gate writes down how many slots it holds; a run that starts while
2
2
  // others are live takes only what the cores leave over, so two runs on one machine cannot starve each other by both counting all the cores.
3
- import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
4
4
  import { availableParallelism, tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  /** One folder per machine (INFINITY_SLOT_LEASE_DIR moves it, for tests). */
@@ -41,22 +41,63 @@ function liveLeases(dir, self) {
41
41
  }
42
42
  return leases;
43
43
  }
44
+ /** A lock older than this was left by a process that died while claiming (a claim takes milliseconds). */
45
+ const STALE_LOCK_MS = 10_000;
46
+ /**
47
+ * Runs `fn` while holding the folder's lock (a directory: mkdir is atomic). Reading the leases and writing one's own must be one step, or two runs
48
+ * starting together both see the cores free and both take them all (formal/SlotLeases.tla). Without the lock after `waitMs`, it goes on anyway:
49
+ * a slot count that is too high is better than a run that cannot start.
50
+ */
51
+ function withLock(dir, fn, waitMs = 2_000) {
52
+ const lock = join(dir, ".lock");
53
+ const deadline = Date.now() + waitMs;
54
+ let held = false;
55
+ for (;;) {
56
+ try {
57
+ mkdirSync(dir, { recursive: true });
58
+ mkdirSync(lock);
59
+ held = true;
60
+ break;
61
+ }
62
+ catch {
63
+ try {
64
+ if (Date.now() - statSync(lock).mtimeMs > STALE_LOCK_MS)
65
+ rmSync(lock, { recursive: true, force: true });
66
+ }
67
+ catch {
68
+ // gone in the meantime
69
+ }
70
+ if (Date.now() > deadline)
71
+ break;
72
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
73
+ }
74
+ }
75
+ try {
76
+ return fn();
77
+ }
78
+ finally {
79
+ if (held)
80
+ rmSync(lock, { recursive: true, force: true });
81
+ }
82
+ }
44
83
  /** Takes up to `wanted` slots, leaving room for the slots of the other live runs on this machine (at least one slot is always given). */
45
84
  export function claimSlots(wanted, runDir, options = {}) {
46
85
  const dir = options.dir ?? defaultLeaseDir();
47
86
  const pid = options.pid ?? process.pid;
48
87
  const cores = options.cores ?? availableParallelism();
49
88
  const name = `${pid}-${runDir.replace(/[^A-Za-z0-9_.-]/g, "_").slice(-80)}.json`;
50
- const others = liveLeases(dir, name);
51
- const held = others.reduce((sum, lease) => sum + lease.slots, 0);
52
- const slots = Math.max(1, Math.min(wanted, cores - held));
53
- try {
54
- mkdirSync(dir, { recursive: true });
55
- writeFileSync(join(dir, name), JSON.stringify({ pid, runDir, slots }));
56
- }
57
- catch {
58
- // without a lease the other runs simply do not see this one
59
- }
89
+ const { others, held, slots } = withLock(dir, () => {
90
+ const others = liveLeases(dir, name);
91
+ const held = others.reduce((sum, lease) => sum + lease.slots, 0);
92
+ const slots = Math.max(1, Math.min(wanted, cores - held));
93
+ try {
94
+ writeFileSync(join(dir, name), JSON.stringify({ pid, runDir, slots }));
95
+ }
96
+ catch {
97
+ // without a lease the other runs simply do not see this one
98
+ }
99
+ return { others, held, slots };
100
+ });
60
101
  const note = slots < wanted
61
102
  ? `CPU slots: ${slots} instead of ${wanted}, because ${others.length} other run${others.length === 1 ? "" : "s"} on this machine hold${others.length === 1 ? "s" : ""} ${held} of the ${cores} cores (${others.map((lease) => lease.runDir).join(", ")}).`
62
103
  : undefined;
@@ -91,6 +91,7 @@ export class TaskMode {
91
91
  this.sharedLinks[name] = to;
92
92
  }
93
93
  if (keeper && originals.length > 0) {
94
+ keeper.restore(); // a resumed run: a killed earlier life of this run may still hold them in this keeper
94
95
  keeper.hide(originals);
95
96
  this.hiddenPaths = originals.map((path) => keeper.privatePath(path));
96
97
  this.guard = restoreOnExit(keeper, process, this.options.signal);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sakura-infinity",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "description": "Run many agents in parallel on one task and keep the best result: a code task scored by your evaluator, or a Lean 4 proof. Built on sakura-agent.",
6
6
  "license": "MIT",
@@ -49,6 +49,7 @@
49
49
  "files": [
50
50
  "dist",
51
51
  "README.md",
52
+ "README.zh-CN.md",
52
53
  "AGENT-GUIDE.md",
53
54
  "LICENSE"
54
55
  ]