benignswarm 0.12.100 → 0.12.102
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/dist/antigravity.js +49 -6
- package/dist/args.js +2 -2
- package/dist/client.js +27 -5
- package/dist/commands/codex-start.js +17 -8
- package/dist/commands/install.js +18 -1
- package/dist/commands/join.js +14 -23
- package/dist/commands/machine-admin.js +184 -41
- package/dist/commands/machine.js +50 -27
- package/dist/commands/watch.js +85 -6
- package/dist/harness.js +78 -6
- package/dist/help.js +13 -6
- package/dist/machine-daemon.js +58 -0
- package/dist/output.js +3 -1
- package/dist/startup-jitter.js +22 -0
- package/dist/state.js +80 -4
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
4
|
import { createInterface } from "node:readline/promises";
|
|
3
5
|
import { bool, need, str } from "../args.js";
|
|
4
6
|
import { Client } from "../client.js";
|
|
5
|
-
import { loadAdmin, resolveAdminName } from "../config.js";
|
|
7
|
+
import { loadAdmin, resolveAdminName, splitRef } from "../config.js";
|
|
6
8
|
import { CliError } from "../errors.js";
|
|
7
9
|
import { table } from "../output.js";
|
|
8
10
|
import { CLI_VERSION } from "../version.js";
|
|
9
11
|
import { runMachineResize } from "./machine-resize.js";
|
|
10
12
|
import { poolSuggestionsAdmin } from "./routing-admin.js";
|
|
13
|
+
import { readState, stateFilePath, stateTransferContents } from "../state.js";
|
|
11
14
|
/**
|
|
12
15
|
* b9s-admin machine: provision machines over the operator's own ssh and declare the agent
|
|
13
16
|
* sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
|
|
@@ -730,14 +733,71 @@ function on(host, command, input) {
|
|
|
730
733
|
}
|
|
731
734
|
return ssh(host, command, input);
|
|
732
735
|
}
|
|
733
|
-
|
|
734
|
-
|
|
736
|
+
const STATE_ABSENT = "__B9S_AGENT_STATE_ABSENT__\n";
|
|
737
|
+
const STATE_PRESENT = "__B9S_AGENT_STATE_PRESENT__\n";
|
|
738
|
+
function statePathPrelude(ref) {
|
|
739
|
+
const { scope, name } = splitRef(ref);
|
|
740
|
+
return [
|
|
741
|
+
`new="$HOME/.b9s"; old="$HOME/.bschat";`,
|
|
742
|
+
`if [ -d "$new" ] && [ -d "$old" ] && [ ! -L "$old" ]; then printf '%s\\n' "both $new and $old are real directories; refusing to choose a state tree" >&2; exit 91; fi;`,
|
|
743
|
+
`if [ -L "$new" ]; then printf '%s\\n' "$new is a symlink; refusing to choose a state tree" >&2; exit 91; fi;`,
|
|
744
|
+
`if [ -e "$new" ] && [ ! -d "$new" ]; then printf '%s\\n' "$new is not a directory" >&2; exit 91; fi;`,
|
|
745
|
+
`if [ -e "$old" ] && [ ! -d "$old" ] && [ ! -L "$old" ]; then printf '%s\\n' "$old is not a directory" >&2; exit 91; fi;`,
|
|
746
|
+
`if [ -L "$old" ] && [ ! -d "$new" ]; then printf '%s\\n' "$old is a symlink but $new is not a directory" >&2; exit 91; fi;`,
|
|
747
|
+
`if [ -d "$new" ]; then root="$new"; elif [ -d "$old" ]; then root="$old"; else root="$new"; fi;`,
|
|
748
|
+
`path="$root/state/${scope}/${name}.json"; legacy="$root/state/${name}.json"; if [ ! -e "$path" ] && [ -f "$legacy" ]; then path="$legacy"; fi;`,
|
|
749
|
+
].join(" ");
|
|
750
|
+
}
|
|
751
|
+
function readAgentStateSnapshot(host, ref) {
|
|
752
|
+
if (host === "local") {
|
|
753
|
+
readState(ref);
|
|
754
|
+
const path = stateFilePath(ref);
|
|
755
|
+
return existsSync(path) ? readFileSync(path, "utf8") : null;
|
|
756
|
+
}
|
|
757
|
+
const result = on(host, `${statePathPrelude(ref)} if [ -f "$path" ]; then printf '${STATE_PRESENT}'; cat "$path"; elif [ -e "$path" ]; then printf '%s\\n' "agent state path is not a regular file" >&2; exit 92; else printf '${STATE_ABSENT}'; fi`);
|
|
758
|
+
if (result.status !== 0)
|
|
759
|
+
throw new CliError("state_read_failed", `could not read ${ref}'s state on ${host}: ${result.stderr.trim() || `exit ${result.status}`}`);
|
|
760
|
+
if (result.stdout.startsWith(STATE_ABSENT))
|
|
761
|
+
return null;
|
|
762
|
+
if (result.stdout.startsWith(STATE_PRESENT))
|
|
763
|
+
return result.stdout.slice(STATE_PRESENT.length);
|
|
764
|
+
throw new CliError("state_read_failed", `could not identify ${ref}'s state response from ${host}`);
|
|
765
|
+
}
|
|
766
|
+
function writeAgentStateSnapshot(host, ref, text, previousText) {
|
|
767
|
+
const path = host === "local" ? stateFilePath(ref) : "";
|
|
768
|
+
const expected = previousText === null ? "missing" : createHash("sha256").update(previousText).digest("hex");
|
|
769
|
+
const code = `const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');const file=process.argv[1],expected=process.argv[2],data=fs.readFileSync(0);let current=null;try{current=fs.readFileSync(file)}catch(e){if(e.code!=='ENOENT')throw e}const actual=current===null?'missing':crypto.createHash('sha256').update(current).digest('hex');if(actual!==expected){console.error('destination agent state changed during transfer');process.exit(93)}JSON.parse(data.toString('utf8'));fs.mkdirSync(path.dirname(file),{recursive:true});const tmp=file+'.b9s-move-'+process.pid+'.tmp';try{fs.writeFileSync(tmp,data,{mode:0o600});fs.chmodSync(tmp,0o600);fs.renameSync(tmp,file)}catch(e){try{fs.rmSync(tmp,{force:true})}catch{}throw e}`;
|
|
770
|
+
const command = host === "local"
|
|
771
|
+
? `node -e ${shellSingle(code)} ${shellSingle(path)} ${shellSingle(expected)}`
|
|
772
|
+
: `${statePathPrelude(ref)} node -e ${shellSingle(code)} "$path" ${shellSingle(expected)}`;
|
|
773
|
+
const result = on(host, command, text);
|
|
774
|
+
if (result.status !== 0)
|
|
775
|
+
throw new CliError("state_write_failed", `could not copy ${ref}'s state to ${host}: ${result.stderr.trim() || `exit ${result.status}`}`);
|
|
776
|
+
}
|
|
777
|
+
export function transferAgentState(ref, from, to, io = {
|
|
778
|
+
read: readAgentStateSnapshot,
|
|
779
|
+
write: writeAgentStateSnapshot,
|
|
780
|
+
}) {
|
|
781
|
+
if (from === to)
|
|
782
|
+
return false;
|
|
783
|
+
const source = io.read(from, ref);
|
|
784
|
+
if (source === null)
|
|
785
|
+
return false;
|
|
786
|
+
const destination = io.read(to, ref);
|
|
787
|
+
const contents = stateTransferContents(source, destination);
|
|
788
|
+
if (contents === null)
|
|
789
|
+
return false;
|
|
790
|
+
io.write(to, ref, contents, destination);
|
|
791
|
+
return true;
|
|
792
|
+
}
|
|
793
|
+
function machineMoveReadinessError(machine, harness, provider, sandbox, liveSample, nowMs = Date.now()) {
|
|
794
|
+
const report = liveSample ? liveSample.report : machine?.report;
|
|
735
795
|
if (!report || typeof report !== "object")
|
|
736
796
|
return `${machine?.name ?? "destination machine"} has not reported; no move was started there`;
|
|
737
|
-
const intervalSeconds = Number(report.report_interval_seconds ?? 30);
|
|
738
|
-
const reportedAt = Date.parse(machine.last_report_at ?? "");
|
|
797
|
+
const intervalSeconds = Number(liveSample?.report_interval_seconds ?? report.report_interval_seconds ?? 30);
|
|
798
|
+
const reportedAt = Date.parse(liveSample ? liveSample.at ?? "" : machine.last_report_at ?? "");
|
|
739
799
|
if (!Number.isFinite(reportedAt) || !Number.isFinite(intervalSeconds) || intervalSeconds <= 0 || nowMs - reportedAt > intervalSeconds * 4_000) {
|
|
740
|
-
return `${machine.name} has a missing or stale report; refresh the machine before moving an agent there`;
|
|
800
|
+
return `${machine.name} has a missing or stale ${liveSample ? "live sample" : "report"}; refresh the machine before moving an agent there`;
|
|
741
801
|
}
|
|
742
802
|
let facts = report[harness];
|
|
743
803
|
if (harness === "claude-code") {
|
|
@@ -767,7 +827,7 @@ function machineMoveReadinessError(machine, harness, provider, sandbox, nowMs =
|
|
|
767
827
|
return null;
|
|
768
828
|
}
|
|
769
829
|
/**
|
|
770
|
-
* agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--model m] [--effort e]
|
|
830
|
+
* agent move <project>/<agent> (--to <machine> --sandbox <mode> | --operation <id>) [--dir path|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--model m] [--effort e]
|
|
771
831
|
* [--carry note|thread] [--from local|<ssh host>] [--to-ssh <host>] [--thread id] [--wait min]
|
|
772
832
|
* [--force --confirm-force <project>/<agent>]
|
|
773
833
|
*
|
|
@@ -779,19 +839,99 @@ function machineMoveReadinessError(machine, harness, provider, sandbox, nowMs =
|
|
|
779
839
|
export async function agentMove(rest, p, out) {
|
|
780
840
|
const ref = rest[0] ?? "";
|
|
781
841
|
const [project, agent] = ref.split("/");
|
|
782
|
-
const
|
|
783
|
-
const
|
|
784
|
-
const
|
|
785
|
-
const
|
|
786
|
-
const
|
|
842
|
+
const operationId = str(p.flags, "operation");
|
|
843
|
+
const requestedTo = str(p.flags, "to");
|
|
844
|
+
const requestedSandbox = str(p.flags, "sandbox");
|
|
845
|
+
const requestedHarness = str(p.flags, "harness");
|
|
846
|
+
const requestedProvider = str(p.flags, "provider");
|
|
847
|
+
const requestedCarry = str(p.flags, "carry");
|
|
848
|
+
const requestedDir = str(p.flags, "dir");
|
|
849
|
+
const requestedModel = str(p.flags, "model");
|
|
850
|
+
const requestedEffort = str(p.flags, "effort");
|
|
851
|
+
const requestedThread = str(p.flags, "thread");
|
|
787
852
|
const from = str(p.flags, "from");
|
|
788
853
|
const forceConfirmation = str(p.flags, "confirm-force");
|
|
789
|
-
if (!project || !agent || !
|
|
790
|
-
throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]");
|
|
854
|
+
if (!project || !agent || (!operationId && (!requestedTo || !requestedSandbox)))
|
|
855
|
+
throw new CliError("usage", "agent move <project>/<agent> (--to <machine> --sandbox <mode> | --operation <id>) [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]");
|
|
791
856
|
if (forceConfirmation && !bool(p.flags, "force"))
|
|
792
857
|
throw new CliError("usage", "--confirm-force is valid only with --force");
|
|
793
858
|
if (forceConfirmation && forceConfirmation !== ref)
|
|
794
859
|
throw new CliError("confirmation_required", `--confirm-force must exactly match ${ref}`);
|
|
860
|
+
if (!from)
|
|
861
|
+
throw new CliError("usage", "--from local|<ssh host> is required so the trusted CLI can check the source before authorizing completion");
|
|
862
|
+
const c = adminClient(p);
|
|
863
|
+
const say = (l) => { if (!out.json)
|
|
864
|
+
process.stderr.write(`${l}\n`); };
|
|
865
|
+
const moveRoute = `/projects/${project}/agents/${agent}/moves`;
|
|
866
|
+
let move;
|
|
867
|
+
let to;
|
|
868
|
+
let sandbox;
|
|
869
|
+
let harness;
|
|
870
|
+
let provider;
|
|
871
|
+
let carry;
|
|
872
|
+
let dir;
|
|
873
|
+
let model = requestedModel;
|
|
874
|
+
let effort = requestedEffort;
|
|
875
|
+
let thread = requestedThread ?? null;
|
|
876
|
+
if (operationId) {
|
|
877
|
+
const loaded = await c.call("GET", `${moveRoute}/${encodeURIComponent(operationId)}`);
|
|
878
|
+
move = loaded.move;
|
|
879
|
+
if (move.status !== "requested")
|
|
880
|
+
throw new CliError("move_not_awaiting_execution", `move operation ${operationId} is ${move.status}; only a requested operation can be continued`);
|
|
881
|
+
const target = move.target;
|
|
882
|
+
const expected = [
|
|
883
|
+
["--to", requestedTo, move.to], ["--sandbox", requestedSandbox, target.sandbox], ["--harness", requestedHarness, target.harness],
|
|
884
|
+
["--provider", requestedProvider, target.provider], ["--carry", requestedCarry, move.carry], ["--dir", requestedDir, target.dir],
|
|
885
|
+
["--model", requestedModel, target.model], ["--effort", requestedEffort, target.effort], ["--thread", requestedThread, target.thread],
|
|
886
|
+
];
|
|
887
|
+
for (const [flag, supplied, stored] of expected) {
|
|
888
|
+
if (supplied !== undefined && supplied !== (stored == null ? undefined : String(stored))) {
|
|
889
|
+
throw new CliError("move_option_mismatch", `${flag}=${supplied} does not match move operation ${operationId}${stored == null ? " (not set on the operation)" : ` (${stored})`}`);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
if (str(p.flags, "turn-timeout") !== undefined && Number(str(p.flags, "turn-timeout")) !== target.turn_timeout) {
|
|
893
|
+
throw new CliError("move_option_mismatch", `--turn-timeout=${str(p.flags, "turn-timeout")} does not match move operation ${operationId} (${target.turn_timeout})`);
|
|
894
|
+
}
|
|
895
|
+
to = String(move.to);
|
|
896
|
+
sandbox = String(target.sandbox);
|
|
897
|
+
harness = String(target.harness ?? "codex");
|
|
898
|
+
provider = String(target.provider ?? "anthropic");
|
|
899
|
+
carry = String(move.carry ?? "note");
|
|
900
|
+
dir = String(target.dir ?? "auto");
|
|
901
|
+
model ??= typeof target.model === "string" ? target.model : undefined;
|
|
902
|
+
effort ??= typeof target.effort === "string" ? target.effort : undefined;
|
|
903
|
+
thread ??= typeof target.thread === "string" ? target.thread : null;
|
|
904
|
+
}
|
|
905
|
+
else {
|
|
906
|
+
to = requestedTo;
|
|
907
|
+
sandbox = requestedSandbox;
|
|
908
|
+
harness = requestedHarness ?? "codex";
|
|
909
|
+
provider = requestedProvider ?? "anthropic";
|
|
910
|
+
carry = requestedCarry ?? "note";
|
|
911
|
+
dir = requestedDir ?? "auto";
|
|
912
|
+
if (harness !== "codex" && harness !== "claude-code")
|
|
913
|
+
throw new CliError("usage", "agent move currently supports codex and claude-code sessions; DSH and Antigravity session behavior is unchanged");
|
|
914
|
+
if (provider !== "anthropic" && provider !== "deepseek")
|
|
915
|
+
throw new CliError("usage", "--provider must be anthropic or deepseek");
|
|
916
|
+
if (provider === "deepseek" && harness !== "claude-code")
|
|
917
|
+
throw new CliError("usage", "--provider deepseek requires --harness claude-code");
|
|
918
|
+
if (carry !== "note" && carry !== "thread")
|
|
919
|
+
throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
|
|
920
|
+
if (carry !== "thread" && thread)
|
|
921
|
+
throw new CliError("usage", "--thread is valid only with --carry thread");
|
|
922
|
+
if (carry === "thread" && harness !== "codex")
|
|
923
|
+
throw new CliError("usage", "--carry thread copies a Codex thread; a Claude Code agent moves with --carry note (its resume note), and its new machine starts a fresh session");
|
|
924
|
+
if (carry === "thread" && !from)
|
|
925
|
+
throw new CliError("usage", "--carry thread needs --from local|<ssh host>: the machine whose ~/.codex holds its thread");
|
|
926
|
+
const requested = await c.call("POST", moveRoute, {
|
|
927
|
+
to, carry, harness, provider, dir, sandbox,
|
|
928
|
+
...(model ? { model } : {}),
|
|
929
|
+
...(effort ? { effort } : {}),
|
|
930
|
+
...(thread ? { thread } : {}),
|
|
931
|
+
...(str(p.flags, "turn-timeout") ? { turn_timeout: Number(str(p.flags, "turn-timeout")) } : {}),
|
|
932
|
+
});
|
|
933
|
+
move = requested.move;
|
|
934
|
+
}
|
|
795
935
|
if (harness !== "codex" && harness !== "claude-code")
|
|
796
936
|
throw new CliError("usage", "agent move currently supports codex and claude-code sessions; DSH and Antigravity session behavior is unchanged");
|
|
797
937
|
if (provider !== "anthropic" && provider !== "deepseek")
|
|
@@ -800,37 +940,22 @@ export async function agentMove(rest, p, out) {
|
|
|
800
940
|
throw new CliError("usage", "--provider deepseek requires --harness claude-code");
|
|
801
941
|
if (carry !== "note" && carry !== "thread")
|
|
802
942
|
throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
|
|
803
|
-
if (carry !== "thread" &&
|
|
943
|
+
if (carry !== "thread" && thread)
|
|
804
944
|
throw new CliError("usage", "--thread is valid only with --carry thread");
|
|
805
|
-
if (carry === "thread" &&
|
|
945
|
+
if (carry === "thread" && harness !== "codex")
|
|
806
946
|
throw new CliError("usage", "--carry thread copies a Codex thread; a Claude Code agent moves with --carry note (its resume note), and its new machine starts a fresh session");
|
|
807
947
|
if (carry === "thread" && !from)
|
|
808
948
|
throw new CliError("usage", "--carry thread needs --from local|<ssh host>: the machine whose ~/.codex holds its thread");
|
|
809
|
-
if (!from)
|
|
810
|
-
throw new CliError("usage", "--from local|<ssh host> is required so the trusted CLI can check the source before authorizing completion");
|
|
811
|
-
const c = adminClient(p);
|
|
812
|
-
const say = (l) => { if (!out.json)
|
|
813
|
-
process.stderr.write(`${l}\n`); };
|
|
814
|
-
const moveRoute = `/projects/${project}/agents/${agent}/moves`;
|
|
815
|
-
const requested = await c.call("POST", moveRoute, {
|
|
816
|
-
to, carry, harness, provider, dir: str(p.flags, "dir") ?? "auto", sandbox,
|
|
817
|
-
...(str(p.flags, "model") ? { model: str(p.flags, "model") } : {}),
|
|
818
|
-
...(str(p.flags, "effort") ? { effort: str(p.flags, "effort") } : {}),
|
|
819
|
-
...(str(p.flags, "thread") ? { thread: str(p.flags, "thread") } : {}),
|
|
820
|
-
...(str(p.flags, "turn-timeout") ? { turn_timeout: Number(str(p.flags, "turn-timeout")) } : {}),
|
|
821
|
-
});
|
|
822
|
-
const move = requested.move;
|
|
823
949
|
const progressRoute = `${moveRoute}/${move.id}`;
|
|
824
950
|
if (!out.json)
|
|
825
951
|
say(` move ${move.id}: ${move.from ?? "source"} → ${to}; other agent keys will be revoked only after completion`);
|
|
826
|
-
await c.call("PATCH", progressRoute, { status: "checking", detail: "trusted CLI is checking local readiness and preparing the handoff" });
|
|
827
|
-
let thread = str(p.flags, "thread") ?? null;
|
|
828
|
-
let model = str(p.flags, "model");
|
|
829
|
-
let effort = str(p.flags, "effort");
|
|
952
|
+
await c.call("PATCH", progressRoute, { status: "checking", expected_status: "requested", detail: "trusted CLI is checking local readiness and preparing the handoff" });
|
|
830
953
|
let problems = [];
|
|
954
|
+
const destinationHost = str(p.flags, "to-ssh") ?? to;
|
|
831
955
|
try {
|
|
832
956
|
const destination = await c.call("GET", `/machines/${to}`);
|
|
833
|
-
const
|
|
957
|
+
const live = await c.call("GET", `/machines/${to}/live`);
|
|
958
|
+
const readinessError = machineMoveReadinessError(destination.machine, harness, provider, sandbox, live.latest ?? null);
|
|
834
959
|
if (readinessError)
|
|
835
960
|
throw new CliError("destination_not_ready", readinessError);
|
|
836
961
|
// 1. Work in progress must be on origin, or it stays behind on the old machine.
|
|
@@ -907,11 +1032,10 @@ export async function agentMove(rest, p, out) {
|
|
|
907
1032
|
const last = lastTurnSettings(src.stdout.slice(nl + 1));
|
|
908
1033
|
model ??= last.model ?? undefined;
|
|
909
1034
|
effort ??= last.effort ?? undefined;
|
|
910
|
-
const
|
|
911
|
-
const put = ssh(toHost, `mkdir -p ~/.codex/sessions/${JSON.stringify(rel.slice(0, rel.lastIndexOf("/")))} && cat > ~/.codex/sessions/${JSON.stringify(rel)}`, src.stdout.slice(nl + 1));
|
|
1035
|
+
const put = ssh(destinationHost, `mkdir -p ~/.codex/sessions/${JSON.stringify(rel.slice(0, rel.lastIndexOf("/")))} && cat > ~/.codex/sessions/${JSON.stringify(rel)}`, src.stdout.slice(nl + 1));
|
|
912
1036
|
if (put.status !== 0)
|
|
913
|
-
throw new CliError("copy_failed", `copying thread ${thread} to ${
|
|
914
|
-
say(` thread ${thread} copied to ${
|
|
1037
|
+
throw new CliError("copy_failed", `copying thread ${thread} to ${destinationHost}: ${put.stderr.trim()}`);
|
|
1038
|
+
say(` thread ${thread} copied to ${destinationHost} (${Math.round((src.stdout.length - nl) / 1024)} KB); the copy on ${from} is now a dead end: archive it in the Codex app there so nobody types into it`);
|
|
915
1039
|
}
|
|
916
1040
|
else {
|
|
917
1041
|
const wait = Number(str(p.flags, "wait") ?? "10");
|
|
@@ -927,6 +1051,8 @@ export async function agentMove(rest, p, out) {
|
|
|
927
1051
|
say(note ? ` resume note saved: ${note.title}` : ` no resume note within ${wait} min; it starts from its units, status and chat`);
|
|
928
1052
|
}
|
|
929
1053
|
}
|
|
1054
|
+
if (transferAgentState(ref, from, destinationHost))
|
|
1055
|
+
say(` read cursors, follows and watcher state copied to ${destinationHost}`);
|
|
930
1056
|
if (!model || !effort) {
|
|
931
1057
|
const st = ((await c.call("GET", `/projects/${project}/agents/status`)).statuses ?? []).find((s) => s.agent_name === agent);
|
|
932
1058
|
if (!model && st?.model && st.model !== "unknown")
|
|
@@ -949,7 +1075,8 @@ export async function agentMove(rest, p, out) {
|
|
|
949
1075
|
? "source-only work was not explicitly confirmed"
|
|
950
1076
|
: "local source check or context handoff failed";
|
|
951
1077
|
try {
|
|
952
|
-
|
|
1078
|
+
const refusalReason = error instanceof CliError ? `${error.code}: ${recordedDetail}` : recordedDetail;
|
|
1079
|
+
await c.call("PATCH", progressRoute, { status: "blocked", detail: recordedDetail, refusal_reason: refusalReason.slice(0, 1000) });
|
|
953
1080
|
}
|
|
954
1081
|
catch (recordError) {
|
|
955
1082
|
throw new CliError("move_progress_failed", `${detail}\nCould not record the blocked move operation: ${recordError instanceof Error ? recordError.message : String(recordError)}`);
|
|
@@ -965,7 +1092,23 @@ export async function agentMove(rest, p, out) {
|
|
|
965
1092
|
...(carry === "thread" && thread ? { thread } : {}),
|
|
966
1093
|
...(model ? { model } : {}), ...(effort ? { effort } : {}),
|
|
967
1094
|
});
|
|
968
|
-
|
|
1095
|
+
let r;
|
|
1096
|
+
try {
|
|
1097
|
+
r = await c.call("POST", `${progressRoute}/complete`, { carried_context_kind: carry });
|
|
1098
|
+
}
|
|
1099
|
+
catch (error) {
|
|
1100
|
+
const refusalReason = error instanceof CliError ? `${error.code}: server move completion failed` : "server move completion failed";
|
|
1101
|
+
try {
|
|
1102
|
+
const current = await c.call("GET", progressRoute);
|
|
1103
|
+
if (!current.move.completion_summary) {
|
|
1104
|
+
await c.call("PATCH", progressRoute, {
|
|
1105
|
+
status: "failed", detail: "server move completion failed", refusal_reason: refusalReason.slice(0, 1000),
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
catch { /* preserve the completion error; the server may already have recorded its failure summary */ }
|
|
1110
|
+
throw error;
|
|
1111
|
+
}
|
|
969
1112
|
return out.print([
|
|
970
1113
|
`Move ${move.id} completed: ${ref} now runs on ${to} (${r.session.harness}/${r.session.provider}, ${r.session.sandbox}, ${r.session.dir || "automatic checkout"}${thread ? `, thread ${thread}` : ", a fresh session"}); its daemon starts it within 30 s.`,
|
|
971
1114
|
r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
|
package/dist/commands/machine.js
CHANGED
|
@@ -12,14 +12,14 @@ import { applySparse } from "../git.js";
|
|
|
12
12
|
import { drainingUntil, writeMaintenance } from "../maintenance.js";
|
|
13
13
|
import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
|
|
14
14
|
import { readState, writeState } from "../state.js";
|
|
15
|
-
import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
15
|
+
import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
16
16
|
import { CLI_VERSION } from "../version.js";
|
|
17
17
|
import { probeCapabilities } from "../capabilities.js";
|
|
18
18
|
import { diskSpaceNotice } from "../notices.js";
|
|
19
19
|
import { verifyClaudeProvider } from "../providers.js";
|
|
20
20
|
import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard } from "../turn-guard.js";
|
|
21
21
|
import { defaultWorkspaceWritableRoots } from "../start-options.js";
|
|
22
|
-
import { antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
|
|
22
|
+
import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
|
|
23
23
|
import { bootTimeMs } from "../boot-time.js";
|
|
24
24
|
import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
|
|
25
25
|
import { agentContainerName, agentContainerRunArgs, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, validateDevcontainerSpec, } from "../container.js";
|
|
@@ -28,6 +28,7 @@ import { machineResourceTelemetry, parsePageSize } from "../machine-telemetry.js
|
|
|
28
28
|
import { macReadiness, macReadinessSteps } from "../macos-readiness.js";
|
|
29
29
|
import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
|
|
30
30
|
import { collectPruneProtection } from "../prune-protection.js";
|
|
31
|
+
import { runMachineDaemonLoop } from "../machine-daemon.js";
|
|
31
32
|
import { pruneProjectWorktrees } from "./worktrees.js";
|
|
32
33
|
export const machineFile = () => join(configRoot(), "machine.json");
|
|
33
34
|
export function loadMachine() {
|
|
@@ -77,7 +78,7 @@ export function maintenanceReport(drain, sessions) {
|
|
|
77
78
|
return drain ? { draining: true, until: drain.end, turns_running: sessions.filter((o) => o.turn?.running).length } : null;
|
|
78
79
|
}
|
|
79
80
|
/** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
|
|
80
|
-
export function startArgs(s, thread, writable = []) {
|
|
81
|
+
export function startArgs(s, thread, writable = [], startupJitterSeconds) {
|
|
81
82
|
return [
|
|
82
83
|
"start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--machine-session-id", s.id, "--json",
|
|
83
84
|
...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
|
|
@@ -85,6 +86,7 @@ export function startArgs(s, thread, writable = []) {
|
|
|
85
86
|
...(s.effort ? ["--effort", s.effort] : []),
|
|
86
87
|
...(thread ? ["--thread", thread] : []),
|
|
87
88
|
...(writable.length && s.sandbox === "workspace-write" ? writable.flatMap((path) => ["--writable-root", path]) : []),
|
|
89
|
+
...(startupJitterSeconds === undefined ? [] : ["--startup-jitter-seconds", String(startupJitterSeconds)]),
|
|
88
90
|
];
|
|
89
91
|
}
|
|
90
92
|
const KEY_CHECK_MS = 10 * 60_000;
|
|
@@ -97,6 +99,9 @@ export function turnFaultSessionFields(fault) {
|
|
|
97
99
|
return { turn_fault_at: new Date(fault.at).toISOString() };
|
|
98
100
|
}
|
|
99
101
|
const syncRunner = (cmd, args, opts) => spawnSync(cmd, args, { encoding: "utf8", timeout: opts?.timeout ?? 180_000, cwd: opts?.cwd, env: opts?.env });
|
|
102
|
+
const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
|
|
103
|
+
const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
|
|
104
|
+
const MACHINE_WATCHDOG_MS = 5 * 60_000;
|
|
100
105
|
export function resolvePinnedImageRef(image) {
|
|
101
106
|
const raw = (image?.rollback_digest ?? image?.active_digest)?.trim() ?? "";
|
|
102
107
|
if (!raw || /:latest\b/i.test(raw))
|
|
@@ -418,7 +423,7 @@ function readContainerStart(logsDir, agentRef) {
|
|
|
418
423
|
export async function launchDesiredSession(opts) {
|
|
419
424
|
const runner = opts.runner ?? syncRunner;
|
|
420
425
|
if (!opts.containerMode) {
|
|
421
|
-
return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable), {
|
|
426
|
+
return runner(opts.bin, startArgs(opts.s, opts.thread, opts.sessionWritable, opts.startupJitterSeconds), {
|
|
422
427
|
cwd: opts.s.dir,
|
|
423
428
|
timeout: 180_000,
|
|
424
429
|
env: { ...process.env, ...opts.secretEnv },
|
|
@@ -467,7 +472,7 @@ export async function launchDesiredSession(opts) {
|
|
|
467
472
|
B9S_AGENT: opts.s.agent,
|
|
468
473
|
B9S_HOME: "/home/agent/.b9s",
|
|
469
474
|
},
|
|
470
|
-
command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? ["/workspace"] : []), "--in-container"],
|
|
475
|
+
command: ["b9s", ...startArgs(opts.s, opts.thread, opts.s.sandbox === "workspace-write" ? ["/workspace"] : [], opts.startupJitterSeconds), "--in-container"],
|
|
471
476
|
});
|
|
472
477
|
const launchRes = runner(runtime, runArgs, {
|
|
473
478
|
cwd: opts.s.dir,
|
|
@@ -510,7 +515,13 @@ export async function launchDesiredSession(opts) {
|
|
|
510
515
|
}
|
|
511
516
|
/** One pass: make what runs here match what the operator declared, then report. */
|
|
512
517
|
export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
513
|
-
const client = Client.raw(m.url, m.key
|
|
518
|
+
const client = Client.raw(m.url, m.key, {
|
|
519
|
+
requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
|
|
520
|
+
signal: deps?.signal,
|
|
521
|
+
onRequest: (event) => log(event.phase === "start"
|
|
522
|
+
? `request start ${event.method} ${event.path}`
|
|
523
|
+
: `request end ${event.method} ${event.path} in ${event.durationMs}ms${event.error ? ` (${event.error})` : ""}`),
|
|
524
|
+
});
|
|
514
525
|
const me = await client.call("GET", "/machines/me");
|
|
515
526
|
const desired = me.sessions;
|
|
516
527
|
await answerWorktreeProcessQueries(client, desired, me.process_queries ?? [], log, deps?.worktreeProcessScanner ?? scanWorktreeProcesses);
|
|
@@ -679,6 +690,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
679
690
|
workdir,
|
|
680
691
|
runner,
|
|
681
692
|
probeSandbox: deps?.probeSandbox,
|
|
693
|
+
startupJitterSeconds: deps?.startupJitterSeconds,
|
|
682
694
|
});
|
|
683
695
|
}
|
|
684
696
|
finally {
|
|
@@ -1222,18 +1234,24 @@ const AGY_SANDBOX_PROBE_MODEL = "gemini-4-hydrogen-low";
|
|
|
1222
1234
|
const AGY_SANDBOX_PROBE_RESPONSE = "B9S_SANDBOX_OK";
|
|
1223
1235
|
let agySandboxCache = null;
|
|
1224
1236
|
/** Runs one cached no-op turn through Antigravity's real workspace-write terminal sandbox. */
|
|
1225
|
-
export function antigravitySandbox(force = false, path = process.env.PATH ?? "") {
|
|
1226
|
-
if (!force && agySandboxCache && agySandboxCache.path === path && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
|
|
1237
|
+
export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
|
|
1238
|
+
if (!force && agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === b9sBin && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
|
|
1227
1239
|
return agySandboxCache.result;
|
|
1228
|
-
|
|
1240
|
+
if (!b9sBin) {
|
|
1241
|
+
const result = { ok: false, error: `recorded b9s install is unavailable; expected ${join(configRoot(), "install.json")}` };
|
|
1242
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin };
|
|
1243
|
+
return result;
|
|
1244
|
+
}
|
|
1229
1245
|
let result;
|
|
1246
|
+
let work = null;
|
|
1230
1247
|
try {
|
|
1248
|
+
work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
|
|
1231
1249
|
const marker = join(work, ".b9s-sandbox-probe");
|
|
1232
1250
|
const quotedMarker = `'${marker.replace(/'/g, `'\\''`)}'`;
|
|
1233
|
-
const prompt = `Use your terminal tool once to run exactly: printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
|
|
1234
|
-
const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow:
|
|
1251
|
+
const prompt = `Use your terminal tool once to run exactly: b9s --version && printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
|
|
1252
|
+
const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions("api.benignswarm.org", configRoot(), b9sBin) } })];
|
|
1235
1253
|
const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
|
|
1236
|
-
encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work, env: { ...process.env, PATH: path },
|
|
1254
|
+
encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work, env: { ...process.env, PATH: antigravityPath(b9sBin, path) },
|
|
1237
1255
|
});
|
|
1238
1256
|
const parsed = parseAntigravityJson(r.stdout ?? "");
|
|
1239
1257
|
let wroteMarker = false;
|
|
@@ -1243,12 +1261,17 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "")
|
|
|
1243
1261
|
catch { /* a missing marker means the sandbox command did not run */ }
|
|
1244
1262
|
result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
|
|
1245
1263
|
? { ok: true, error: null }
|
|
1246
|
-
: { ok: false, error:
|
|
1264
|
+
: { ok: false, error: `sandbox could not run b9s --version and its no-op check (agy exit ${r.status ?? "unknown"}); verify recorded install ${b9sBin} and Node runtime ${process.execPath} are readable and executable inside the sandbox` };
|
|
1265
|
+
}
|
|
1266
|
+
catch (error) {
|
|
1267
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1268
|
+
result = { ok: false, error: `sandbox could not prepare b9s --version probe for recorded install ${b9sBin} with Node runtime ${process.execPath}: ${detail}` };
|
|
1247
1269
|
}
|
|
1248
1270
|
finally {
|
|
1249
|
-
|
|
1271
|
+
if (work)
|
|
1272
|
+
rmSync(work, { recursive: true, force: true });
|
|
1250
1273
|
}
|
|
1251
|
-
agySandboxCache = { at: Date.now(), result, path };
|
|
1274
|
+
agySandboxCache = { at: Date.now(), result, path, b9sBin };
|
|
1252
1275
|
return result;
|
|
1253
1276
|
}
|
|
1254
1277
|
function antigravityLoginFacts(path) {
|
|
@@ -1265,11 +1288,11 @@ function antigravityLoginFacts(path) {
|
|
|
1265
1288
|
};
|
|
1266
1289
|
}
|
|
1267
1290
|
/** Machine facts used by placement; the daemon probes login cheaply and caches the sandbox turn. */
|
|
1268
|
-
export function antigravityFacts(path = process.env.PATH ?? "") {
|
|
1291
|
+
export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
|
|
1269
1292
|
const facts = antigravityLoginFacts(path);
|
|
1270
1293
|
return {
|
|
1271
1294
|
...facts,
|
|
1272
|
-
sandbox: facts.logged_in ? antigravitySandbox(false, path) : null,
|
|
1295
|
+
sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin) : null,
|
|
1273
1296
|
};
|
|
1274
1297
|
}
|
|
1275
1298
|
/** Memory a new process could use: Linux's MemAvailable (free alone undercounts the page cache), else free. */
|
|
@@ -1328,7 +1351,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
1328
1351
|
const volumeFloorPct = diskFloorPct;
|
|
1329
1352
|
const req = "/etc/codex/requirements.toml";
|
|
1330
1353
|
const claude = (probes?.claude ?? (() => claudeReport(path, providersInUse)))();
|
|
1331
|
-
const bootedAt = bootTimeMs();
|
|
1354
|
+
const bootedAt = (opts.bootTime ?? bootTimeMs)();
|
|
1332
1355
|
const gitIdentity = (probes?.gitIdentity ?? (() => readGitIdentity()))();
|
|
1333
1356
|
const container = (probes?.container ?? (() => probeNestedSandbox()))();
|
|
1334
1357
|
const imds = (opts.imdsProbe ?? probeImdsIsolation)();
|
|
@@ -1341,6 +1364,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
1341
1364
|
metric_availability: { ...telemetryAvailability, home_volume: homeSpace ? "available" : "unavailable" },
|
|
1342
1365
|
// When this machine last booted: the server ends a maintenance window once the machine is back.
|
|
1343
1366
|
booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
|
|
1367
|
+
booted_at_exact: bootedAt === null ? null : new Date(bootedAt).toISOString(),
|
|
1344
1368
|
daemon_path: path,
|
|
1345
1369
|
bschat: { version: CLI_VERSION, bin: requireInstall().bin },
|
|
1346
1370
|
git_identity: gitIdentity,
|
|
@@ -1935,15 +1959,14 @@ export async function machine(p, out) {
|
|
|
1935
1959
|
if (!Number.isFinite(interval) || interval < 1 || interval > 3600)
|
|
1936
1960
|
throw new CliError("usage", "--interval must be from 1 to 3600 seconds");
|
|
1937
1961
|
log(`running every ${interval}s against ${m.url}`);
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
}
|
|
1962
|
+
const intervalMs = interval * 1000;
|
|
1963
|
+
return runMachineDaemonLoop({
|
|
1964
|
+
intervalMs,
|
|
1965
|
+
passBudgetMs: Math.max(MACHINE_PASS_BUDGET_MS, intervalMs * 4),
|
|
1966
|
+
watchdogMs: Math.max(MACHINE_WATCHDOG_MS, intervalMs * 10),
|
|
1967
|
+
reconcile: (signal) => reconcile(m, log, interval, { signal }),
|
|
1968
|
+
log,
|
|
1969
|
+
});
|
|
1947
1970
|
}
|
|
1948
1971
|
throw new CliError("usage", "machine bootstrap | run | once | status | prepare | service | processes --worktree <path>");
|
|
1949
1972
|
}
|