sakura-infinity 0.0.0-stage → 0.1.1

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.
Files changed (82) hide show
  1. package/AGENT-GUIDE.md +104 -0
  2. package/LICENSE +21 -0
  3. package/README.md +275 -2
  4. package/dist/bin/flags.js +110 -0
  5. package/dist/bin/infinity.js +98 -0
  6. package/dist/bin/load-task.js +39 -0
  7. package/dist/bin/model.js +37 -0
  8. package/dist/bin/scaffold.js +121 -0
  9. package/dist/src/agent-worker.js +157 -0
  10. package/dist/src/backoff.js +12 -0
  11. package/dist/src/budget.js +49 -0
  12. package/dist/src/capacity.js +103 -0
  13. package/dist/src/clock.js +16 -0
  14. package/dist/src/code-leaderboard.js +48 -0
  15. package/dist/src/code-report.js +157 -0
  16. package/dist/src/command-class.js +59 -0
  17. package/dist/src/command-limits.js +46 -0
  18. package/dist/src/commit-plugin.js +36 -0
  19. package/dist/src/component.js +1 -0
  20. package/dist/src/csv.js +8 -0
  21. package/dist/src/defaults.js +35 -0
  22. package/dist/src/error-cluster.js +20 -0
  23. package/dist/src/evaluation.js +84 -0
  24. package/dist/src/form.js +191 -0
  25. package/dist/src/gate.js +111 -0
  26. package/dist/src/gpu-shim.js +165 -0
  27. package/dist/src/handoff.js +12 -0
  28. package/dist/src/hidden-keeper.js +183 -0
  29. package/dist/src/host.js +180 -0
  30. package/dist/src/jsonl.js +30 -0
  31. package/dist/src/ladder.js +118 -0
  32. package/dist/src/launch.js +123 -0
  33. package/dist/src/lean-kit.js +42 -0
  34. package/dist/src/lean-runner.js +84 -0
  35. package/dist/src/lean-setup.js +23 -0
  36. package/dist/src/lean-tool.js +57 -0
  37. package/dist/src/leftover.js +59 -0
  38. package/dist/src/machine-config.js +43 -0
  39. package/dist/src/machine-sampler.js +103 -0
  40. package/dist/src/machine-summary.js +64 -0
  41. package/dist/src/mode-factory.js +25 -0
  42. package/dist/src/mode.js +1 -0
  43. package/dist/src/network.js +12 -0
  44. package/dist/src/orchestrator.js +375 -0
  45. package/dist/src/planner.js +98 -0
  46. package/dist/src/platform.js +21 -0
  47. package/dist/src/pool.js +73 -0
  48. package/dist/src/pressure-brake.js +26 -0
  49. package/dist/src/proc-readings.js +207 -0
  50. package/dist/src/prompts.js +46 -0
  51. package/dist/src/records.js +2 -0
  52. package/dist/src/report.js +81 -0
  53. package/dist/src/review-loop.js +141 -0
  54. package/dist/src/review-rules.js +104 -0
  55. package/dist/src/review-run.js +110 -0
  56. package/dist/src/review-schedule.js +53 -0
  57. package/dist/src/review-snapshot.js +150 -0
  58. package/dist/src/run-layout.js +29 -0
  59. package/dist/src/run-notes.js +61 -0
  60. package/dist/src/run-recorder.js +51 -0
  61. package/dist/src/run-state.js +17 -0
  62. package/dist/src/run-status.js +37 -0
  63. package/dist/src/rung-meter.js +39 -0
  64. package/dist/src/safety-review.js +43 -0
  65. package/dist/src/sakura-tools.js +130 -0
  66. package/dist/src/shell-kit.js +113 -0
  67. package/dist/src/slot-gate.js +136 -0
  68. package/dist/src/slot-leases.js +64 -0
  69. package/dist/src/stuck.js +47 -0
  70. package/dist/src/submit-tool.js +99 -0
  71. package/dist/src/task-mode.js +170 -0
  72. package/dist/src/task.js +85 -0
  73. package/dist/src/verifier.js +115 -0
  74. package/dist/src/work-repo.js +50 -0
  75. package/dist/src/worker-policy.js +16 -0
  76. package/dist/tasks/math-odd-sum/task.js +6 -0
  77. package/dist/tasks/math-parity/task.js +6 -0
  78. package/dist/viewer/index.html +397 -0
  79. package/dist/viewer/run-reader.js +600 -0
  80. package/dist/viewer/server.js +160 -0
  81. package/dist/viewer/view.js +50 -0
  82. package/package.json +53 -4
package/AGENT-GUIDE.md ADDED
@@ -0,0 +1,104 @@
1
+ # Guide for an AI that runs Infinity Agent
2
+
3
+ You are an AI (or a script) that has to run many agents on one task and read what they produced. This page is all you need. Everything is also available to a person on the command line; the library and the tools below use the same code.
4
+
5
+ ## The idea in one minute
6
+
7
+ - A **task form** says what to do and how a result is scored. It is plain data (a TypeScript file `export default {...}`, a JSON file, or an object you pass to the tool).
8
+ - A **machine file** says what this computer can carry (how many agents, how many heavy commands at once). It is made by one command and is not part of the task.
9
+ - One call starts the run. Many agents work in parallel, each in its own Git directory. Every `submit` of an agent is scored by **your evaluator**, a program you write. The best score ranks.
10
+ - You watch the run from its files and stop it when you have enough.
11
+
12
+ ## Step by step
13
+
14
+ ### 1. Look at the machine
15
+
16
+ Command: `infinity recommend --write machine.json`. Tool: `infinity_recommend`. It reads cores, memory, GPU and other load, and says how many agents and how many heavy commands at once make sense. These are hints; the number of agents is your choice (1 to 100, more than the recommendation adds nothing).
17
+
18
+ ### 2. Write the form
19
+
20
+ Start from a template: `infinity new code my-task` (or `math`). It writes `my-task/task.ts` and, for code, an example `evaluate.py`.
21
+
22
+ The fields (a field that does not belong to the preset is refused with a message):
23
+
24
+ | Field | Preset | Meaning |
25
+ |---|---|---|
26
+ | `preset` | both | `"code"`: agents have a shell and `submit`. `"math"`: agents prove one Lean 4 statement (file tools and a `lean` check; no shell); the score is 1 for an accepted proof. |
27
+ | `name`, `summary` | both | Name for the report; one line for `--help`. |
28
+ | `prompt` | code (required), math (extra words) | The problem in words. Say the goal, what the agents see, what to hand in, what is forbidden. |
29
+ | `statement` | math (required) | The Lean source of a Prop. The proof must be `theorem main : Statement.Goal`. |
30
+ | `data` | code | `{ name: path }`: each name is a link in the agent's work directory to a read-only copy. For example, `{ data: "./inputs" }` exposes `data/`. |
31
+ | `hidden` | code | Paths only the evaluator may read (test labels, secret inputs). Moved away while the agents run, put back at the end. The evaluator finds their private paths in `INFINITY_HIDDEN_0`, `INFINITY_HIDDEN_1`, ... |
32
+ | `evaluate` | code | `{ program, run?, args?, timeoutMinutes? }` (a program, started outside the agents' shell) or, in TypeScript only, a function. |
33
+ | `metric` | code | `{ name, direction: "max" \| "min" }`; required with `evaluate`. |
34
+ | `stop` | code | `"until-stopped"` (default) or `{ targetScore }`. A math task always ends at the first accepted proof (leave `stop` out). |
35
+ | `review` | code | The safety review of agents' shell commands: on by default, `false` switches it off (the report says so). |
36
+ | `tokens`, `wallMinutes` | both | Token budget; the run ends in order after this many minutes. |
37
+ | `profile` | both | What one heavy command needs (`{ cpu: { threadsPerJob, memPerJobGb, heavyShare } }`); the recommendation reads it. |
38
+ | `evalSlots`, `submitIntervalMinutes`, `evalTimeoutMinutes` | code | Scoring at once (default 2); least minutes between two submits of one agent; longest scoring. |
39
+ | `leanPool`, `sandbox` | math | Lean processes at once; confine Lean with the macOS sandbox. |
40
+
41
+ Paths are relative to the folder of the form file (or to `formDir` when you pass the form to the tool).
42
+ Keep hidden labels outside every visible input directory. Keep the evaluator outside the visible inputs as well.
43
+
44
+ ### 3. Write the evaluator (code preset)
45
+
46
+ It is a program in any language. Infinity starts it for every `submit`, outside the agents' shell:
47
+
48
+ - environment: `INFINITY_WORK_DIR` (the agent's directory), `INFINITY_COMMIT`, `INFINITY_HIDDEN_0`, `INFINITY_HIDDEN_1`, ...; only PATH, HOME and LANG of the parent's environment are passed on (no key);
49
+ - it must print, as its last line, one JSON object: `{"score": 0.93, "metrics": {"other": 1}, "details": "words for the agent"}`;
50
+ - on an unusable submit print `{"score": null, "details": "why"}`.
51
+
52
+ Rules that matter, because agents **will** try to win by the cheapest means:
53
+ - Check the range and the format of what you read (a number out of range, a wrong length, missing columns), and say so in `details`.
54
+ - **Never put hidden data in `details`.** The agent reads it. Do not return labels, row values or anything one can decode them from.
55
+ - Keep the evaluator program outside what the agents can read; the loader lists it as protected automatically.
56
+ - If the score can be raised by something that is not the goal (hard-coding the hidden inputs, timing noise, reading the public source of the answer), the agents will find it. Say it is forbidden in the `prompt` and make the evaluator check for it.
57
+ - For a task such as "make this program faster": run the agent's program on **hidden** inputs, check the output first (a wrong answer scores `null`), then measure time (`direction: "min"`). Repeat the timing and take the median.
58
+
59
+ ### 4. Start
60
+
61
+ Command:
62
+
63
+ ```sh
64
+ infinity run ./my-task/task.ts --machine machine.json --agents 4 --wall-minutes 30 --view
65
+ ```
66
+
67
+ Flags win over the machine file. `--no-review` leaves the branch review out (it can cost about half of the tokens). `infinity --help` lists every flag; conflicting flags are refused with a message.
68
+
69
+ Tool: `infinity_run` with `{ form: {...}, formDir: "/abs/folder", agents: 4, wallMinutes: 30 }` (or `{ task: "<known task>" }`). It returns at once; the run goes on in the same process.
70
+
71
+ Library: `startRun(formPackage(form, baseDir), { model, agents, wallMinutes })`, see `src/launch.ts` and `src/form.ts`.
72
+
73
+ ### 5. Read the run
74
+
75
+ - `infinity_status` (or `handle.status()`): state, agents alive, tokens, best score, warnings, the newest events.
76
+ - Files in `runs/<name>-<time>/`: `report/report.html`, `report/leaderboard.csv`, `ledger.jsonl` (`result` lines are scored submits), `events.jsonl`, `machine.jsonl`, `agents/NNN/work/` (one Git repository per agent; the best solution is the commit named in the first row of the leaderboard).
77
+ - A person can look at it live: `infinity view runs` (read-only page on 127.0.0.1).
78
+
79
+ ### 6. Stop and resume
80
+
81
+ `infinity_stop` (or Ctrl-C, `handle.stop()`): agents stopped in order, report written, hidden data put back. Resume: `infinity run <same task> --resume runs/<run>` with the same flags.
82
+
83
+ ## Choosing the numbers
84
+
85
+ - **Agents:** start with the recommendation or smaller. More agents help only while the machine and the provider keep up; on throttling the ladder drops a rung by itself.
86
+ - **Budget:** always set `tokens` or `wallMinutes` for a first run. Reviews cost tokens.
87
+ - **A small first run** (2 agents, 10 to 20 minutes) shows whether the prompt and the evaluator work before you spend more.
88
+
89
+ ## What is not guaranteed
90
+
91
+ - Agents' shells run with the user's rights; there is no sandbox. The safety review and Infinity's rules lower the risk and prove nothing. Do not run it where secrets are within reach.
92
+ - Hidden data is protected by a private path and by review rules, not by the operating system.
93
+ - Machine readings and process cleanup need Linux; elsewhere a warning says what is missing.
94
+ - The model key is read from the environment (`DEEPSEEK_API_KEY` by default; `INFINITY_PROVIDER=openai` with `OPENAI_API_KEY`, or `anthropic` with `ANTHROPIC_API_KEY`) and never printed. Do not print the environment.
95
+
96
+ ## Common mistakes
97
+
98
+ | Message or symptom | Cause |
99
+ |---|---|
100
+ | `Invalid form ...: unknown field 'x'` | A field name is misspelled, or belongs to the other preset. |
101
+ | `metric is required with evaluate` | An evaluator needs a metric, and a metric needs an evaluator. |
102
+ | Many submits with `score: null` | The evaluator rejects what the agents hand in; read `details` in `ledger.jsonl` and fix the prompt or the evaluator message. |
103
+ | A score that is too good | The evaluator can be gamed; see the rules in step 3. |
104
+ | No scored submit for a long time | The commands are slow on this machine (use a smaller data sample), or only one heavy command runs at a time (`slots`). |
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025–2026 Vist233
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,276 @@
1
- # Temporary Holding Version
1
+ # Infinity (`sakura-infinity`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
5
+ There is one kind of task: agents improve a result and every submit is scored. What differs is the **tools** the agents get:
6
+
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
+
10
+ The test suite covers both tool kits. Real-model runs have also produced an accepted Lean proof and a scored Covertype submission.
11
+
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
+ ```
145
+
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.
147
+
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
+ ```
154
+
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.
156
+
157
+ ### 2. Configure the model
158
+
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.
160
+
161
+ ```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
+ ```
167
+
168
+ ### 3. Run a math task
169
+
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
173
+ ```
174
+
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`.
176
+
177
+ ### 4. Run a code task
178
+
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
+ ```
184
+
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).
186
+
187
+ ### 5. Your own task (no TypeScript needed)
188
+
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).
190
+
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
+ ```
196
+
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):
202
+
203
+ ```sh
204
+ node bin/infinity.ts view runs
205
+ ```
206
+
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.
208
+
209
+ ### 7. Read the results
210
+
211
+ Each run writes `runs/<task>-<time>/`:
212
+
213
+ | File | What it holds |
214
+ |---|---|
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) |
216
+ | `report/leaderboard.csv` | one row per scored result: agent, score, commit, work directory |
217
+ | `ledger.jsonl` | what each agent did; `result` lines are submissions |
218
+ | `events.jsonl` | rungs, throttles, reviews, refusals, warnings, `run_end` |
219
+ | `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>`) |
222
+
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.
224
+
225
+ ### 8. Stop and resume
226
+
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
232
+
233
+ ```ts
234
+ import { startRun } from "./src/launch.ts";
235
+ import { createInfinityTools } from "./src/sakura-tools.ts";
236
+ import { formPackage } from "./src/form.ts";
237
+ import form from "./tasks/covertype/task.ts";
238
+ const covertype = formPackage(form, "./tasks/covertype");
239
+
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)
245
+
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
248
+ ```
249
+
250
+ ### Known limits
251
+
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.
258
+
259
+ ## Lean and the sandbox
260
+
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.
266
+
267
+ ## Shell tasks (the code preset)
268
+
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`).
270
+
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`.
275
+
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`.
@@ -0,0 +1,110 @@
1
+ import { cpuOf } from "../src/capacity.js";
2
+ import { recommendRun } from "../src/launch.js";
3
+ /** Takes `--name value` out of the argument list; undefined when it is not there. */
4
+ export function takeNumber(args, name) {
5
+ const at = args.indexOf(`--${name}`);
6
+ if (at < 0)
7
+ return undefined;
8
+ const value = Number(args.splice(at, 2)[1]);
9
+ if (!Number.isFinite(value))
10
+ throw new Error(`--${name} needs a number`);
11
+ return value;
12
+ }
13
+ /** Takes `--name` (a switch without a value) out of the argument list. */
14
+ export function takeSwitch(args, name) {
15
+ const at = args.indexOf(`--${name}`);
16
+ if (at >= 0)
17
+ args.splice(at, 1);
18
+ return at >= 0;
19
+ }
20
+ /** The profile of a task, with the command line's `--threads`, `--mem-gb` and `--heavy-share` laid over it (they change the CPU part). */
21
+ export function profileWithFlags(base, args) {
22
+ const threadsPerJob = takeNumber(args, "threads");
23
+ const memPerJobGb = takeNumber(args, "mem-gb");
24
+ const heavyShare = takeNumber(args, "heavy-share");
25
+ return {
26
+ ...base,
27
+ cpu: {
28
+ ...cpuOf(base),
29
+ ...(threadsPerJob === undefined ? {} : { threadsPerJob }),
30
+ ...(memPerJobGb === undefined ? {} : { memPerJobGb }),
31
+ ...(heavyShare === undefined ? {} : { heavyShare }),
32
+ },
33
+ };
34
+ }
35
+ /** Prints what this machine can carry and returns the number of agents to use: the user's own always wins (for the synthetic benchmarks, which have no task package). */
36
+ export async function chooseAgents(profile, requested) {
37
+ const recommendation = await recommendRun(profile, requested);
38
+ for (const line of recommendation.lines)
39
+ console.log(line);
40
+ return { agents: recommendation.agents, capacity: recommendation.capacity, foreignBusyCores: recommendation.foreignBusyCores };
41
+ }
42
+ export const RUN_HELP = `usage: infinity run <task> [flags]
43
+
44
+ <task> a bundled example (math-parity, math-odd-sum; covertype in the repository), or the path of a form (.json or .ts) or of a module that exports a task package
45
+ Flags:
46
+ --agents N number of agents; always wins over the machine's recommendation (printed first)
47
+ --tokens N token budget
48
+ --no-token-limit run without the task's default token budget (not with --tokens)
49
+ --wall-minutes N end the run in order after N minutes
50
+ --review-minutes N minutes between two branch reviews of one agent (default 3)
51
+ --no-review leave the branch review out (not with --review-minutes)
52
+ --threads N threads per command (default 2), --mem-gb N memory per command, --heavy-share X share of time in heavy commands
53
+ --slots N CPU slots: at most N heavy commands at once (default: the recommended number); --gate is the default; --no-gate turns it off (not with --slots)
54
+ --pressure-brake hold the ladder while the machine is under pressure
55
+ --command-minutes N longest a single command may run (default 120)
56
+ --machine FILE the machine file made by "infinity recommend --write FILE"; flags win over it
57
+ --runs-dir DIR where runs are created (default runs)
58
+ --resume DIR continue a stopped run
59
+ --view [--view-port N] also serve the read-only run viewer while the run goes on (default port 4173)
60
+ The model: DEEPSEEK_API_KEY (the default provider); INFINITY_PROVIDER=openai with OPENAI_API_KEY, or anthropic with ANTHROPIC_API_KEY;
61
+ INFINITY_MODEL replaces the provider's default model. The key is read once and never printed.`;
62
+ const VALUE_FLAGS = ["agents", "tokens", "wall-minutes", "review-minutes", "threads", "mem-gb", "heavy-share", "slots", "command-minutes", "view-port"];
63
+ const SWITCHES = ["no-review", "no-token-limit", "gate", "no-gate", "pressure-brake", "view"];
64
+ /** The arguments after `infinity run`. Unknown flags and conflicting flags are errors, said in words. */
65
+ export function parseRunArgs(argv) {
66
+ const args = [...argv];
67
+ const value = (name) => takeNumber(args, name);
68
+ const text = (name) => {
69
+ const at = args.indexOf(`--${name}`);
70
+ if (at < 0)
71
+ return undefined;
72
+ const given = args.splice(at, 2)[1];
73
+ if (!given || given.startsWith("--"))
74
+ throw new Error(`--${name} needs a value`);
75
+ return given;
76
+ };
77
+ const runsDir = text("runs-dir");
78
+ const resume = text("resume");
79
+ const machine = text("machine");
80
+ const numbers = Object.fromEntries(VALUE_FLAGS.map((name) => [name, value(name)]));
81
+ const on = Object.fromEntries(SWITCHES.map((name) => [name, takeSwitch(args, name)]));
82
+ const [task, ...rest] = args;
83
+ if (!task || task.startsWith("--"))
84
+ throw new Error("say which task to run: infinity run <task> [flags]");
85
+ if (rest.length > 0)
86
+ throw new Error(`not understood: ${rest.join(" ")}`);
87
+ if (on["no-review"] && numbers["review-minutes"] !== undefined)
88
+ throw new Error("--no-review cannot be used with --review-minutes");
89
+ if (on["no-token-limit"] && numbers.tokens !== undefined)
90
+ throw new Error("--no-token-limit cannot be used with --tokens");
91
+ if (on["no-gate"] && (numbers.slots !== undefined || on.gate))
92
+ throw new Error("--no-gate cannot be used with --slots or --gate");
93
+ const gate = on["no-gate"] ? false : (numbers.slots ?? (on.gate ? true : undefined));
94
+ const options = {
95
+ ...(gate === undefined ? {} : { gate }),
96
+ ...(numbers.agents === undefined ? {} : { agents: numbers.agents }),
97
+ ...(on["no-token-limit"] ? { tokens: null } : numbers.tokens === undefined ? {} : { tokens: numbers.tokens }),
98
+ ...(numbers["wall-minutes"] === undefined ? {} : { wallMinutes: numbers["wall-minutes"] }),
99
+ ...(on["no-review"] ? { review: false } : numbers["review-minutes"] === undefined ? {} : { review: { everyMinutes: numbers["review-minutes"] } }),
100
+ ...(numbers.threads === undefined ? {} : { threads: numbers.threads }),
101
+ ...(numbers["mem-gb"] === undefined ? {} : { memGb: numbers["mem-gb"] }),
102
+ ...(numbers["heavy-share"] === undefined ? {} : { heavyShare: numbers["heavy-share"] }),
103
+ ...(on["pressure-brake"] ? { pressureBrake: true } : {}),
104
+ ...(numbers["command-minutes"] === undefined ? {} : { commandMinutes: numbers["command-minutes"] }),
105
+ ...(runsDir === undefined ? {} : { runsDir }),
106
+ ...(resume === undefined ? {} : { resume }),
107
+ commandLine: argv,
108
+ };
109
+ return { task, options, view: on.view ? { port: numbers["view-port"] ?? 4173 } : undefined, machine };
110
+ }
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
3
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
4
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
5
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
6
+ });
7
+ }
8
+ return path;
9
+ };
10
+ import { resolve } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { startRun } from "../src/launch.js";
13
+ import { machineOptions, readMachineConfig } from "../src/machine-config.js";
14
+ import { startViewer } from "../viewer/server.js";
15
+ import { runViewerCommand } from "../viewer/view.js";
16
+ import { RUN_HELP, parseRunArgs } from "./flags.js";
17
+ import { loadTaskPackage } from "./load-task.js";
18
+ import { modelFromEnv } from "./model.js";
19
+ import { recommend, scaffold } from "./scaffold.js";
20
+ const HELP = `infinity: run many agents on one task, and look at the run
21
+
22
+ ${RUN_HELP}
23
+
24
+ usage: infinity new <code|math> <folder>
25
+ writes a task form to start from
26
+
27
+ usage: infinity recommend [--task <task>] [--write machine.json]
28
+ what this computer can carry (agents, slots, threads), saved as a machine file
29
+
30
+ usage: infinity view <runs dir or run dir> [--port N] [--machine FILE]
31
+ serves the read-only run viewer (it only reads the run's files)
32
+
33
+ usage: infinity --help`;
34
+ async function run(argv) {
35
+ const command = parseRunArgs(argv);
36
+ const pack = await loadTaskPackage(command.task);
37
+ const machine = command.machine ? machineOptions(readMachineConfig(command.machine)) : {};
38
+ const environmentModule = process.env.INFINITY_WORKER_ENVIRONMENT;
39
+ const createEnvironment = environmentModule ? (await import(__rewriteRelativeImportExtension(pathToFileURL(resolve(environmentModule)).href))).createEnvironment : undefined;
40
+ if (environmentModule && typeof createEnvironment !== "function")
41
+ throw new Error("The worker environment module must export createEnvironment");
42
+ const model = modelFromEnv();
43
+ const viewerRoot = resolve(command.options.resume ?? command.options.runsDir ?? "runs");
44
+ const viewer = command.view ? await startViewer({ root: viewerRoot, port: command.view.port }) : undefined;
45
+ const stopping = new AbortController();
46
+ const stop = () => stopping.abort();
47
+ process.on("SIGINT", stop);
48
+ process.on("SIGTERM", stop);
49
+ try {
50
+ const handle = await startRun(pack, {
51
+ ...machine,
52
+ ...command.options,
53
+ model,
54
+ signal: stopping.signal,
55
+ ...(createEnvironment ? { createEnvironment } : {}),
56
+ });
57
+ for (const line of handle.recommendation.lines)
58
+ console.log(line);
59
+ if (viewer)
60
+ console.log(`Run viewer (read-only, live): http://127.0.0.1:${viewer.port}/`);
61
+ console.log(`Run directory: ${handle.runDir}`);
62
+ console.log(JSON.stringify(await handle.done));
63
+ }
64
+ finally {
65
+ process.off("SIGINT", stop);
66
+ process.off("SIGTERM", stop);
67
+ await viewer?.close();
68
+ }
69
+ }
70
+ async function main(argv) {
71
+ const [command, ...rest] = argv;
72
+ try {
73
+ if (command === "run")
74
+ await run(rest);
75
+ else if (command === "view")
76
+ await runViewerCommand(rest);
77
+ else if (command === "new")
78
+ for (const file of scaffold(rest))
79
+ console.log(`wrote ${file}`);
80
+ else if (command === "recommend")
81
+ for (const line of await recommend(rest))
82
+ console.log(line);
83
+ else {
84
+ console.log(HELP);
85
+ return command === undefined || command === "--help" || command === "-h" || command === "help" ? 0 : 2;
86
+ }
87
+ return 0;
88
+ }
89
+ catch (error) {
90
+ console.error(error instanceof Error ? error.message : String(error));
91
+ return 1;
92
+ }
93
+ }
94
+ if (import.meta.main) {
95
+ const code = await main(process.argv.slice(2));
96
+ if (code !== 0)
97
+ process.exit(code);
98
+ }