@mycompbox/compbox-cli 1.20.0 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.tsbuildinfo +1 -1
- package/commands/configure.d.ts +2 -0
- package/commands/configure.d.ts.map +1 -1
- package/commands/configure.js +34 -55
- package/commands/configure.js.map +1 -1
- package/commands/deploy.d.ts +22 -0
- package/commands/deploy.d.ts.map +1 -0
- package/commands/deploy.js +96 -0
- package/commands/deploy.js.map +1 -0
- package/commands/doctor.d.ts +14 -12
- package/commands/doctor.d.ts.map +1 -1
- package/commands/doctor.js +35 -19
- package/commands/doctor.js.map +1 -1
- package/commands/repo.d.ts +24 -0
- package/commands/repo.d.ts.map +1 -0
- package/commands/repo.js +81 -0
- package/commands/repo.js.map +1 -0
- package/commands/run.d.ts +0 -15
- package/commands/run.d.ts.map +1 -1
- package/commands/run.js +45 -28
- package/commands/run.js.map +1 -1
- package/commands/workspace.d.ts +56 -0
- package/commands/workspace.d.ts.map +1 -0
- package/commands/workspace.js +177 -0
- package/commands/workspace.js.map +1 -0
- package/index.js +614 -127
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/utils/agent-invoker.d.ts +33 -1
- package/utils/agent-invoker.d.ts.map +1 -1
- package/utils/agent-invoker.js +83 -12
- package/utils/agent-invoker.js.map +1 -1
- package/utils/config-store.d.ts +30 -58
- package/utils/config-store.d.ts.map +1 -1
- package/utils/config-store.js +27 -47
- package/utils/config-store.js.map +1 -1
- package/utils/mailbox-client.d.ts +23 -0
- package/utils/mailbox-client.d.ts.map +1 -1
- package/utils/mailbox-client.js +20 -0
- package/utils/mailbox-client.js.map +1 -1
- package/utils/run-workspace.d.ts +34 -4
- package/utils/run-workspace.d.ts.map +1 -1
- package/utils/run-workspace.js +90 -18
- package/utils/run-workspace.js.map +1 -1
package/index.js
CHANGED
|
@@ -7,7 +7,7 @@ var __export = (target, all) => {
|
|
|
7
7
|
|
|
8
8
|
// src/index.ts
|
|
9
9
|
import { createRequire } from "node:module";
|
|
10
|
-
import { Command as
|
|
10
|
+
import { Command as Command15 } from "commander";
|
|
11
11
|
|
|
12
12
|
// src/commands/install.ts
|
|
13
13
|
import { Command } from "commander";
|
|
@@ -5911,6 +5911,72 @@ function complianceFromRecord(score) {
|
|
|
5911
5911
|
return { overall: s.overall, tier: s.tier, issues };
|
|
5912
5912
|
}
|
|
5913
5913
|
|
|
5914
|
+
// ../shared/dist/cloud-connect.js
|
|
5915
|
+
var GITHUB_OIDC_THUMBPRINTS = ["6938fd4d98bab03faadb97b34396831e3780aea1", "1c58a3a8518e8759bf075b76b750d4f2df264fcd"];
|
|
5916
|
+
var AWS_SETUP_FUNCTION = `import json, urllib.error, urllib.request
|
|
5917
|
+
import boto3
|
|
5918
|
+
|
|
5919
|
+
ISSUER = "token.actions.githubusercontent.com"
|
|
5920
|
+
|
|
5921
|
+
|
|
5922
|
+
def respond(event, ok, data=None, reason=""):
|
|
5923
|
+
body = json.dumps({
|
|
5924
|
+
"Status": "SUCCESS" if ok else "FAILED",
|
|
5925
|
+
"Reason": (reason or "See the function's CloudWatch logs")[:1000],
|
|
5926
|
+
"PhysicalResourceId": event.get("PhysicalResourceId") or event["LogicalResourceId"],
|
|
5927
|
+
"StackId": event["StackId"],
|
|
5928
|
+
"RequestId": event["RequestId"],
|
|
5929
|
+
"LogicalResourceId": event["LogicalResourceId"],
|
|
5930
|
+
"Data": data or {},
|
|
5931
|
+
}).encode()
|
|
5932
|
+
req = urllib.request.Request(event["ResponseURL"], data=body, method="PUT", headers={"Content-Type": ""})
|
|
5933
|
+
urllib.request.urlopen(req, timeout=30)
|
|
5934
|
+
|
|
5935
|
+
|
|
5936
|
+
def github_oidc():
|
|
5937
|
+
iam = boto3.client("iam")
|
|
5938
|
+
for p in iam.list_open_id_connect_providers()["OpenIDConnectProviderList"]:
|
|
5939
|
+
arn = p["Arn"]
|
|
5940
|
+
if arn.endswith("/" + ISSUER):
|
|
5941
|
+
if "sts.amazonaws.com" not in iam.get_open_id_connect_provider(OpenIDConnectProviderArn=arn)["ClientIDList"]:
|
|
5942
|
+
iam.add_client_id_to_open_id_connect_provider(OpenIDConnectProviderArn=arn, ClientID="sts.amazonaws.com")
|
|
5943
|
+
return arn
|
|
5944
|
+
return iam.create_open_id_connect_provider(
|
|
5945
|
+
Url="https://" + ISSUER, ClientIDList=["sts.amazonaws.com"], ThumbprintList=${JSON.stringify(GITHUB_OIDC_THUMBPRINTS)}
|
|
5946
|
+
)["OpenIDConnectProviderArn"]
|
|
5947
|
+
|
|
5948
|
+
|
|
5949
|
+
def notify(p):
|
|
5950
|
+
body = json.dumps({
|
|
5951
|
+
"token": p["Token"], "accountId": p["AccountId"], "region": p["Region"],
|
|
5952
|
+
"roleArn": p["RoleArn"], "stateBucket": p["Bucket"],
|
|
5953
|
+
}).encode()
|
|
5954
|
+
req = urllib.request.Request(p["Url"], data=body, method="POST", headers={"Content-Type": "application/json"})
|
|
5955
|
+
try:
|
|
5956
|
+
urllib.request.urlopen(req, timeout=30)
|
|
5957
|
+
except urllib.error.HTTPError as e:
|
|
5958
|
+
raise RuntimeError("CompBox said: " + e.read().decode(errors="replace")[:500])
|
|
5959
|
+
|
|
5960
|
+
|
|
5961
|
+
def handler(event, context):
|
|
5962
|
+
try:
|
|
5963
|
+
props = event["ResourceProperties"]
|
|
5964
|
+
if event["RequestType"] == "Delete":
|
|
5965
|
+
return respond(event, True)
|
|
5966
|
+
if props["Action"] == "oidc":
|
|
5967
|
+
return respond(event, True, {"Arn": github_oidc()})
|
|
5968
|
+
try:
|
|
5969
|
+
notify(props)
|
|
5970
|
+
except Exception:
|
|
5971
|
+
# The connect link expires; a later stack update shouldn't fail on it.
|
|
5972
|
+
if event["RequestType"] != "Update":
|
|
5973
|
+
raise
|
|
5974
|
+
respond(event, True)
|
|
5975
|
+
except Exception as e:
|
|
5976
|
+
print(e)
|
|
5977
|
+
respond(event, False, reason=str(e))
|
|
5978
|
+
`;
|
|
5979
|
+
|
|
5914
5980
|
// src/utils/config-store.ts
|
|
5915
5981
|
var CONFIG_DIR_ENV = "COMPBOX_CONFIG_DIR";
|
|
5916
5982
|
var PROJECT_DIR_ENV = "COMPBOX_PROJECT_DIR";
|
|
@@ -5969,28 +6035,22 @@ function applyPxpipeEnv(config, env = process.env) {
|
|
|
5969
6035
|
env.PXPIPE_ENABLED = "false";
|
|
5970
6036
|
}
|
|
5971
6037
|
}
|
|
5972
|
-
function
|
|
5973
|
-
const
|
|
5974
|
-
|
|
5975
|
-
|
|
6038
|
+
function resolveProjectDirForJob(projectRemote, opts) {
|
|
6039
|
+
const remote = normalizeGitRemote(projectRemote ?? "");
|
|
6040
|
+
if (remote.length === 0) {
|
|
6041
|
+
return { status: "no-remote" };
|
|
6042
|
+
}
|
|
6043
|
+
const entry = (opts.config?.projectDirs ?? []).find((e) => e.remote === remote);
|
|
6044
|
+
return entry ? { status: "registered", path: entry.path } : { status: "unregistered", remote };
|
|
6045
|
+
}
|
|
6046
|
+
function unusedLegacyProjectDir(config, env = process.env) {
|
|
6047
|
+
for (const candidate of [config?.projectDir, env[PROJECT_DIR_ENV]]) {
|
|
5976
6048
|
if (typeof candidate === "string" && candidate.trim().length > 0) {
|
|
5977
6049
|
return candidate.trim();
|
|
5978
6050
|
}
|
|
5979
6051
|
}
|
|
5980
6052
|
return void 0;
|
|
5981
6053
|
}
|
|
5982
|
-
function resolveProjectDirForJob(projectRemote, opts) {
|
|
5983
|
-
const remote = normalizeGitRemote(projectRemote ?? "");
|
|
5984
|
-
if (remote.length > 0) {
|
|
5985
|
-
const entry = (opts.config?.projectDirs ?? []).find((e) => e.remote === remote);
|
|
5986
|
-
if (entry) {
|
|
5987
|
-
return { status: "registered", path: entry.path };
|
|
5988
|
-
}
|
|
5989
|
-
return { status: "unregistered", remote };
|
|
5990
|
-
}
|
|
5991
|
-
const fallback = resolveProjectDir({ flag: opts.flag, env: opts.env, config: opts.config });
|
|
5992
|
-
return fallback !== void 0 ? { status: "fallback", path: fallback } : { status: "unresolved" };
|
|
5993
|
-
}
|
|
5994
6054
|
function isGitRepoDir(dir) {
|
|
5995
6055
|
try {
|
|
5996
6056
|
return existsSync4(join4(dir, ".git")) && statSync(dir).isDirectory();
|
|
@@ -6653,6 +6713,25 @@ var MailboxClient = class {
|
|
|
6653
6713
|
throw errorFromResponse(res, "saved failed");
|
|
6654
6714
|
}
|
|
6655
6715
|
}
|
|
6716
|
+
/**
|
|
6717
|
+
* Asks CompBox to open the run's pull request through the CompBox GitHub
|
|
6718
|
+
* app. Throws when the project isn't connected through the app (409), so
|
|
6719
|
+
* the caller can open it another way.
|
|
6720
|
+
*/
|
|
6721
|
+
async openPullRequest(machineToken, jobId, input) {
|
|
6722
|
+
let res;
|
|
6723
|
+
try {
|
|
6724
|
+
res = await this.http.post(`/api/v1/jobs/${jobId}/pull-request`, input, {
|
|
6725
|
+
headers: { Authorization: `Bearer ${machineToken}` }
|
|
6726
|
+
});
|
|
6727
|
+
} catch (error) {
|
|
6728
|
+
throw toMailboxError(error, "pull-request request failed");
|
|
6729
|
+
}
|
|
6730
|
+
if (res.status < 200 || res.status >= 300) {
|
|
6731
|
+
throw errorFromResponse(res, "pull-request failed");
|
|
6732
|
+
}
|
|
6733
|
+
return res.data.data;
|
|
6734
|
+
}
|
|
6656
6735
|
/** Reports what a run on the person's API key spent. */
|
|
6657
6736
|
async reportAiUsage(machineToken, jobId, usage) {
|
|
6658
6737
|
let res;
|
|
@@ -6921,6 +7000,7 @@ function installAutostart() {
|
|
|
6921
7000
|
}
|
|
6922
7001
|
|
|
6923
7002
|
// src/commands/configure.ts
|
|
7003
|
+
var PROJECT_FOLDER_QUESTION = "Add a project folder (a git checkout) \u2014 leave blank when done:";
|
|
6924
7004
|
function parseAiMode(value) {
|
|
6925
7005
|
if (value === "claude-subscription" || value === "api-key") {
|
|
6926
7006
|
return value;
|
|
@@ -7015,78 +7095,47 @@ Device pairing failed: ${message}`));
|
|
|
7015
7095
|
console.log(chalk7.gray(`
|
|
7016
7096
|
Device already paired as "${config.machineName ?? config.machineId}".`));
|
|
7017
7097
|
}
|
|
7018
|
-
const
|
|
7019
|
-
|
|
7098
|
+
const legacyDir = config.projectDir?.trim();
|
|
7099
|
+
const registeredPaths = () => new Set(listProjectDirs().map((e) => e.path));
|
|
7100
|
+
const firstDefault = [process.cwd(), legacyDir].find(
|
|
7101
|
+
(dir) => typeof dir === "string" && dir.length > 0 && isGitRepoDir(dir) && !registeredPaths().has(dir)
|
|
7102
|
+
);
|
|
7103
|
+
console.log("\n" + chalk7.bold("Project folders:"));
|
|
7020
7104
|
console.log(
|
|
7021
7105
|
chalk7.gray(
|
|
7022
|
-
"
|
|
7106
|
+
" Each project runs only in the folder you register for its repository (a git checkout\n with an origin remote). Add one folder per project. Leave blank when you are done."
|
|
7023
7107
|
)
|
|
7024
7108
|
);
|
|
7025
|
-
|
|
7026
|
-
|
|
7027
|
-
|
|
7028
|
-
|
|
7029
|
-
for (let attempt = 0; attempt < MAX_PROJECT_DIR_ATTEMPTS; attempt += 1) {
|
|
7030
|
-
const answer = (await promptText(
|
|
7031
|
-
projectDirQuestion,
|
|
7032
|
-
defaultDir !== void 0 ? { defaultValue: defaultDir } : {}
|
|
7033
|
-
)).trim();
|
|
7034
|
-
if (answer.length === 0) {
|
|
7035
|
-
projectDirSkipped = true;
|
|
7036
|
-
break;
|
|
7037
|
-
}
|
|
7038
|
-
if (isGitRepoDir(answer)) {
|
|
7039
|
-
updateConfig({ projectDir: answer });
|
|
7040
|
-
console.log(chalk7.green(`\u2714 Project directory set to ${answer}`));
|
|
7041
|
-
console.log(
|
|
7042
|
-
chalk7.gray(" Dispatched plan/orchestrate runs will operate in this repository.")
|
|
7043
|
-
);
|
|
7044
|
-
projectDirPersisted = true;
|
|
7045
|
-
break;
|
|
7046
|
-
}
|
|
7047
|
-
console.warn(
|
|
7048
|
-
chalk7.yellow(
|
|
7049
|
-
`\u26A0 ${answer} is not a git repository. Enter a path to a git checkout, or leave blank to skip.`
|
|
7109
|
+
if (legacyDir) {
|
|
7110
|
+
console.log(
|
|
7111
|
+
chalk7.gray(
|
|
7112
|
+
` Note: this computer no longer uses a single default folder (${legacyDir}). Register it here if you still want runs for its repository to use it.`
|
|
7050
7113
|
)
|
|
7051
7114
|
);
|
|
7052
7115
|
}
|
|
7053
|
-
|
|
7054
|
-
|
|
7055
|
-
|
|
7056
|
-
|
|
7057
|
-
|
|
7116
|
+
const MAX_PROJECT_DIR_PROMPTS = 10;
|
|
7117
|
+
for (let attempt = 0; attempt < MAX_PROJECT_DIR_PROMPTS; attempt += 1) {
|
|
7118
|
+
const offerDefault = attempt === 0 && firstDefault !== void 0;
|
|
7119
|
+
const answer = (await promptText(PROJECT_FOLDER_QUESTION, offerDefault ? { defaultValue: firstDefault } : {})).trim();
|
|
7120
|
+
if (answer.length === 0) break;
|
|
7121
|
+
try {
|
|
7122
|
+
const entry = addProjectDir(answer);
|
|
7123
|
+
console.log(chalk7.green(`\u2714 Registered ${entry.remote} \u2192 ${entry.path}`));
|
|
7124
|
+
} catch (error) {
|
|
7125
|
+
const message = error instanceof Error ? error.message : "unknown error";
|
|
7126
|
+
console.warn(chalk7.yellow(`\u26A0 ${message} Enter another folder, or leave blank to finish.`));
|
|
7058
7127
|
}
|
|
7128
|
+
}
|
|
7129
|
+
const registered = listProjectDirs();
|
|
7130
|
+
if (registered.length === 0) {
|
|
7059
7131
|
console.log(
|
|
7060
7132
|
chalk7.yellow(
|
|
7061
|
-
"\n\u26A0 No project
|
|
7062
|
-
)
|
|
7063
|
-
);
|
|
7064
|
-
console.log(
|
|
7065
|
-
chalk7.gray(
|
|
7066
|
-
" Set it later with `compbox run --project-dir <path>`, the COMPBOX_PROJECT_DIR env var, or by re-running `compbox configure`."
|
|
7133
|
+
"\n\u26A0 No project folders registered \u2014 runs sent to this computer will be refused until you add one."
|
|
7067
7134
|
)
|
|
7068
7135
|
);
|
|
7069
|
-
|
|
7070
|
-
|
|
7071
|
-
|
|
7072
|
-
"Register this repository (its origin remote \u2192 this path) so dispatched runs targeting it route to this machine?",
|
|
7073
|
-
true
|
|
7074
|
-
);
|
|
7075
|
-
if (registerAllowlist) {
|
|
7076
|
-
try {
|
|
7077
|
-
const entry = addProjectDir(process.cwd());
|
|
7078
|
-
console.log(chalk7.green(`\u2714 Registered ${entry.remote} \u2192 ${entry.path}`));
|
|
7079
|
-
console.log(
|
|
7080
|
-
chalk7.gray(" Manage the allowlist later with `compbox machines dirs list/add/rm`.")
|
|
7081
|
-
);
|
|
7082
|
-
} catch (error) {
|
|
7083
|
-
const message = error instanceof Error ? error.message : "unknown error";
|
|
7084
|
-
console.warn(chalk7.yellow(`\u26A0 Could not register this repository: ${message}`));
|
|
7085
|
-
console.warn(
|
|
7086
|
-
chalk7.gray(" You can register it later with `compbox machines dirs add`.")
|
|
7087
|
-
);
|
|
7088
|
-
}
|
|
7089
|
-
}
|
|
7136
|
+
console.log(chalk7.gray(" Add one later with `compbox machines dirs add <path-to-checkout>`."));
|
|
7137
|
+
} else {
|
|
7138
|
+
console.log(chalk7.gray(` ${String(registered.length)} project folder(s) registered. Manage them with \`compbox machines dirs list/add/rm\`.`));
|
|
7090
7139
|
}
|
|
7091
7140
|
const mcpConfigPath = options.mcpConfig ?? defaultMcpConfigPath();
|
|
7092
7141
|
const result = patchMcpConfig(mcpConfigPath, {
|
|
@@ -7695,26 +7744,40 @@ ${reRun}`
|
|
|
7695
7744
|
};
|
|
7696
7745
|
}
|
|
7697
7746
|
function projectDirCheck(config) {
|
|
7698
|
-
const name = "Project
|
|
7699
|
-
const
|
|
7700
|
-
if (
|
|
7747
|
+
const name = "Project folders registered";
|
|
7748
|
+
const entries = config.projectDirs ?? [];
|
|
7749
|
+
if (entries.length === 0) {
|
|
7701
7750
|
return {
|
|
7702
7751
|
name,
|
|
7703
7752
|
passed: false,
|
|
7704
|
-
detail: "No
|
|
7753
|
+
detail: "No project folders are registered \u2014 runs sent to this computer are refused until you add one with `compbox machines dirs add <path>` (or `compbox configure`)."
|
|
7705
7754
|
};
|
|
7706
7755
|
}
|
|
7707
|
-
|
|
7756
|
+
const broken = entries.filter((e) => !isGitRepoDir(e.path));
|
|
7757
|
+
if (broken.length > 0) {
|
|
7708
7758
|
return {
|
|
7709
7759
|
name,
|
|
7710
7760
|
passed: false,
|
|
7711
|
-
detail: `
|
|
7761
|
+
detail: `registered folder is not a git repo: ${broken.map((e) => `${e.remote} \u2192 ${e.path}`).join(", ")} \u2014 re-register it with \`compbox machines dirs add <path>\`.`
|
|
7712
7762
|
};
|
|
7713
7763
|
}
|
|
7714
7764
|
return {
|
|
7715
7765
|
name,
|
|
7716
7766
|
passed: true,
|
|
7717
|
-
detail:
|
|
7767
|
+
detail: entries.map((e) => `${e.remote} \u2192 ${e.path}`).join("; ")
|
|
7768
|
+
};
|
|
7769
|
+
}
|
|
7770
|
+
function legacyProjectDirCheck(config, env = process.env) {
|
|
7771
|
+
const name = "Old default folder";
|
|
7772
|
+
const dir = unusedLegacyProjectDir(config, env);
|
|
7773
|
+
if (dir === void 0) {
|
|
7774
|
+
return { name, passed: true, skipped: true, detail: "not set" };
|
|
7775
|
+
}
|
|
7776
|
+
return {
|
|
7777
|
+
name,
|
|
7778
|
+
passed: true,
|
|
7779
|
+
warning: true,
|
|
7780
|
+
detail: `${dir} is set as a default folder but is no longer used \u2014 runs go only to the folder registered for their project's repository. Register it with \`compbox machines dirs add ${dir}\` if you still want it.`
|
|
7718
7781
|
};
|
|
7719
7782
|
}
|
|
7720
7783
|
var doctorCommand = new Command7("doctor").description("Diagnose config, connectivity, machine pairing, MCP config, AI mode, and the service").option("--mcp-config <path>", "Path to the MCP config to check (default: ./.mcp.json)").action(async (options) => {
|
|
@@ -7867,6 +7930,7 @@ var doctorCommand = new Command7("doctor").description("Diagnose config, connect
|
|
|
7867
7930
|
}
|
|
7868
7931
|
results.push(await agentRuntimeCheck(config));
|
|
7869
7932
|
results.push(projectDirCheck(config));
|
|
7933
|
+
results.push(legacyProjectDirCheck(config));
|
|
7870
7934
|
if (process.platform === "darwin") {
|
|
7871
7935
|
results.push(checkBrewService());
|
|
7872
7936
|
}
|
|
@@ -8209,12 +8273,17 @@ function buildPlannerArgs(epicRequestId) {
|
|
|
8209
8273
|
}
|
|
8210
8274
|
function projectDirNotConfiguredMessage() {
|
|
8211
8275
|
return [
|
|
8212
|
-
"
|
|
8213
|
-
"
|
|
8214
|
-
" - `compbox
|
|
8215
|
-
"
|
|
8216
|
-
|
|
8217
|
-
|
|
8276
|
+
"This run has no project folder on this computer, so it can't run.",
|
|
8277
|
+
"Each run works only in the folder registered for its project's repository:",
|
|
8278
|
+
" - `compbox machines dirs add <path-to-your-checkout>` (or re-run `compbox configure`)",
|
|
8279
|
+
"CompBox never falls back to a default folder."
|
|
8280
|
+
].join("\n");
|
|
8281
|
+
}
|
|
8282
|
+
function noProjectRemoteMessage() {
|
|
8283
|
+
return [
|
|
8284
|
+
"This run isn't linked to a project repository, so this computer won't run it.",
|
|
8285
|
+
"Update CompBox (`brew upgrade compbox`) or connect the project's repository in its Settings \u2192 Repository, then send the run again.",
|
|
8286
|
+
"CompBox only runs work in the folder registered for its project's repository \u2014 never in a default folder."
|
|
8218
8287
|
].join("\n");
|
|
8219
8288
|
}
|
|
8220
8289
|
function unregisteredRemoteMessage(remote) {
|
|
@@ -8230,11 +8299,11 @@ function unregisteredRemoteMessage(remote) {
|
|
|
8230
8299
|
}
|
|
8231
8300
|
function projectDirNotGitRepoMessage(dir) {
|
|
8232
8301
|
return [
|
|
8233
|
-
`The
|
|
8234
|
-
"The planner runs the local `claude` CLI in this
|
|
8302
|
+
`The project folder registered for this run's repository is not a git repository: ${dir}`,
|
|
8303
|
+
"The planner runs the local `claude` CLI in this folder so the repo's .mcp.json (CompBox MCP)",
|
|
8235
8304
|
"and CLAUDE.md (@agent routing) load \u2014 both require a real checkout.",
|
|
8236
|
-
"
|
|
8237
|
-
"
|
|
8305
|
+
"Register the right checkout with `compbox machines dirs add <path>` (or re-run `compbox configure`),",
|
|
8306
|
+
"then re-run the job."
|
|
8238
8307
|
].join("\n");
|
|
8239
8308
|
}
|
|
8240
8309
|
function scanJsonObjects(text) {
|
|
@@ -8431,11 +8500,15 @@ ${stderr}`;
|
|
|
8431
8500
|
}
|
|
8432
8501
|
var ORCHESTRATOR_RUN_TIMEOUT_MS = 3 * 60 * 60 * 1e3;
|
|
8433
8502
|
var ORCHESTRATOR_HEARTBEAT_INTERVAL_MS = PLANNER_HEARTBEAT_INTERVAL_MS;
|
|
8503
|
+
var HEADLESS_ORCHESTRATE_REMINDER = "This is a non-interactive run: do NOT start sub-agents or reviews in the background and do not end your turn to wait for them. Run every step in this process and keep going until every feature is done or a hard gate stops the run.";
|
|
8434
8504
|
var ORCHESTRATOR_FINAL_TURN_MAX_CHARS = 4e3;
|
|
8435
8505
|
function buildOrchestratorArgs(epicId) {
|
|
8436
8506
|
return [
|
|
8437
8507
|
"-p",
|
|
8438
8508
|
`@orchestrator execute epic ${epicId} --non-interactive`,
|
|
8509
|
+
// H3 reminder: never background work in a print-mode run.
|
|
8510
|
+
"--append-system-prompt",
|
|
8511
|
+
HEADLESS_ORCHESTRATE_REMINDER,
|
|
8439
8512
|
// H1: unattended permission mode so print-mode tool use never blocks on an
|
|
8440
8513
|
// interactive "allow?" prompt (this path grants the full MCP surface).
|
|
8441
8514
|
"--permission-mode",
|
|
@@ -8447,7 +8520,7 @@ function orchestrateNotGitRepoMessage(dir) {
|
|
|
8447
8520
|
`The configured CompBox project directory is not a git repository: ${dir}`,
|
|
8448
8521
|
"The orchestrator runs the local `claude` CLI in this directory so the repo's .mcp.json (CompBox MCP)",
|
|
8449
8522
|
"and CLAUDE.md (@agent routing) load, and it drives builds/tests through git worktrees \u2014 all require a real checkout.",
|
|
8450
|
-
"
|
|
8523
|
+
"Register the right checkout with `compbox machines dirs add <path>` and re-run the job."
|
|
8451
8524
|
].join("\n");
|
|
8452
8525
|
}
|
|
8453
8526
|
function worktreeUnavailableMessage(dir) {
|
|
@@ -8488,7 +8561,19 @@ function defaultToolchainPresent(_dir) {
|
|
|
8488
8561
|
}
|
|
8489
8562
|
return false;
|
|
8490
8563
|
}
|
|
8564
|
+
function buildIncompleteRunResult(epicId, progress) {
|
|
8565
|
+
return {
|
|
8566
|
+
needsAttention: true,
|
|
8567
|
+
epicId,
|
|
8568
|
+
completedFeatures: progress.completedFeatures,
|
|
8569
|
+
totalFeatures: progress.totalFeatures,
|
|
8570
|
+
message: `The run stopped before finishing: ${String(progress.completedFeatures)} of ${String(progress.totalFeatures)} features done. Send the build again to continue.`
|
|
8571
|
+
};
|
|
8572
|
+
}
|
|
8491
8573
|
function describeRunBranch(finish) {
|
|
8574
|
+
if (finish.needsAttention) {
|
|
8575
|
+
return `Needs attention: the run's work was kept in ${finish.keptWorktree ?? "its run folder"} (branch ${finish.branch}) because it couldn't all be committed.`;
|
|
8576
|
+
}
|
|
8492
8577
|
if (finish.prUrl) return `Pull request: ${finish.prUrl}`;
|
|
8493
8578
|
if (finish.compareUrl) return `Branch ${finish.branch} was pushed. Open the pull request here: ${finish.compareUrl}`;
|
|
8494
8579
|
if (finish.commits === 0) return "No code changes were made.";
|
|
@@ -8632,6 +8717,25 @@ ${stderr}`;
|
|
|
8632
8717
|
finish({ status: "done", result: { epicId: ctx.epicId } });
|
|
8633
8718
|
});
|
|
8634
8719
|
});
|
|
8720
|
+
if (outcome.status === "done") {
|
|
8721
|
+
const readProgress = deps.epicProgress ?? (async () => {
|
|
8722
|
+
try {
|
|
8723
|
+
const job = await ctx.mailboxClient.postTurn(
|
|
8724
|
+
ctx.machineToken,
|
|
8725
|
+
ctx.jobId,
|
|
8726
|
+
`The orchestrator finished. Checking epic ${ctx.epicId}'s progress in CompBox\u2026`
|
|
8727
|
+
);
|
|
8728
|
+
return job.progress ?? null;
|
|
8729
|
+
} catch {
|
|
8730
|
+
return null;
|
|
8731
|
+
}
|
|
8732
|
+
});
|
|
8733
|
+
const progress = await readProgress();
|
|
8734
|
+
if (progress && progress.totalFeatures > 0 && progress.completedFeatures < progress.totalFeatures) {
|
|
8735
|
+
outcome.status = "failed";
|
|
8736
|
+
outcome.result = buildIncompleteRunResult(ctx.epicId, progress);
|
|
8737
|
+
}
|
|
8738
|
+
}
|
|
8635
8739
|
let branchLine = "";
|
|
8636
8740
|
if (deps.workspace && workspace) {
|
|
8637
8741
|
const resultError = outcome.result;
|
|
@@ -8651,8 +8755,17 @@ ${stderr}`;
|
|
|
8651
8755
|
pushed: finished.pushed,
|
|
8652
8756
|
...finished.prUrl ? { prUrl: finished.prUrl } : {},
|
|
8653
8757
|
...finished.compareUrl ? { compareUrl: finished.compareUrl } : {},
|
|
8654
|
-
...finished.notes.length > 0 ? { branchNotes: finished.notes } : {}
|
|
8758
|
+
...finished.notes.length > 0 ? { branchNotes: finished.notes } : {},
|
|
8759
|
+
...finished.keptWorktree ? { keptWorktree: finished.keptWorktree } : {}
|
|
8655
8760
|
};
|
|
8761
|
+
if (finished.needsAttention) {
|
|
8762
|
+
outcome.status = "failed";
|
|
8763
|
+
outcome.result = {
|
|
8764
|
+
...outcome.result,
|
|
8765
|
+
needsAttention: true,
|
|
8766
|
+
message: `The run's work couldn't be saved to its branch, so it was kept in ${finished.keptWorktree ?? "its run folder"}.` + (typeof outcome.result.message === "string" ? ` ${outcome.result.message}` : "")
|
|
8767
|
+
};
|
|
8768
|
+
}
|
|
8656
8769
|
}
|
|
8657
8770
|
try {
|
|
8658
8771
|
const summary = (outcome.status === "done" ? `Execution complete \u2014 epic ${ctx.epicId} finished all phases.` : `Orchestrator run ended: ${JSON.stringify(outcome.result).slice(0, ORCHESTRATOR_FINAL_TURN_MAX_CHARS)}`) + (branchLine ? `
|
|
@@ -8831,7 +8944,9 @@ var RunWorkspaceManager = class {
|
|
|
8831
8944
|
exists;
|
|
8832
8945
|
copyFile;
|
|
8833
8946
|
env;
|
|
8947
|
+
openPullRequest;
|
|
8834
8948
|
constructor(deps = {}) {
|
|
8949
|
+
this.openPullRequest = deps.openPullRequest;
|
|
8835
8950
|
this.run = deps.run ?? defaultCommandRunner;
|
|
8836
8951
|
this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
8837
8952
|
this.runsRoot = deps.runsRoot ?? join10(getConfigDir(), "runs");
|
|
@@ -8935,26 +9050,42 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
|
|
|
8935
9050
|
async finishLocked(input) {
|
|
8936
9051
|
const { workspace: ws } = input;
|
|
8937
9052
|
const notes = [];
|
|
8938
|
-
|
|
9053
|
+
const dirtyBefore = await this.isDirty(ws.dir);
|
|
9054
|
+
let commitFailed = false;
|
|
9055
|
+
if (dirtyBefore) {
|
|
8939
9056
|
await this.git(["add", "-A"], ws.dir);
|
|
8940
9057
|
const commit = await this.git(
|
|
8941
|
-
["commit", "-m", `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`],
|
|
9058
|
+
["commit", "--no-verify", "-m", `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`],
|
|
8942
9059
|
ws.dir
|
|
8943
9060
|
);
|
|
8944
9061
|
if (commit.status !== 0) {
|
|
8945
|
-
|
|
9062
|
+
commitFailed = true;
|
|
9063
|
+
notes.push(`Couldn't commit the remaining changes: ${firstLine(commit.stderr) || firstLine(commit.stdout) || "unknown error"}`);
|
|
8946
9064
|
}
|
|
8947
9065
|
}
|
|
8948
9066
|
const commits = Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0;
|
|
8949
9067
|
const base = { branch: ws.branch, commits, pushed: false, notes };
|
|
9068
|
+
if (commitFailed || dirtyBefore && await this.isDirty(ws.dir)) {
|
|
9069
|
+
notes.push(`The run's changes couldn't all be committed, so nothing was removed. They are safe in ${ws.dir} on branch ${ws.branch}.`);
|
|
9070
|
+
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
9071
|
+
}
|
|
8950
9072
|
if (commits === 0) {
|
|
8951
|
-
|
|
8952
|
-
|
|
8953
|
-
|
|
8954
|
-
|
|
9073
|
+
if (!dirtyBefore) {
|
|
9074
|
+
if (await this.removeWorktree(ws, notes)) {
|
|
9075
|
+
await this.git(["branch", "-D", ws.branch], ws.projectDir);
|
|
9076
|
+
} else {
|
|
9077
|
+
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
9078
|
+
}
|
|
9079
|
+
notes.push("The run made no code changes, so there is nothing to review.");
|
|
9080
|
+
return base;
|
|
9081
|
+
}
|
|
9082
|
+
notes.push(`The run's changes didn't end up in a commit, so nothing was removed. Check ${ws.dir} on branch ${ws.branch}.`);
|
|
9083
|
+
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
8955
9084
|
}
|
|
8956
9085
|
if (!ws.remote || this.env[RUN_PUSH_ENV] === "0") {
|
|
8957
|
-
await this.
|
|
9086
|
+
if (!await this.removeWorktree(ws, notes)) {
|
|
9087
|
+
return { ...base, keptWorktree: ws.dir, needsAttention: true };
|
|
9088
|
+
}
|
|
8958
9089
|
notes.push(
|
|
8959
9090
|
ws.remote ? `Pushing is turned off (${RUN_PUSH_ENV}=0). The work is on the local branch ${ws.branch}.` : `The repository has no remote, so the work is on the local branch ${ws.branch}.`
|
|
8960
9091
|
);
|
|
@@ -8975,10 +9106,21 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
|
|
|
8975
9106
|
"",
|
|
8976
9107
|
`${String(commits)} commit${commits === 1 ? "" : "s"} on \`${ws.branch}\`, based on \`${ws.baseBranch}\`.`
|
|
8977
9108
|
].join("\n");
|
|
8978
|
-
|
|
8979
|
-
if (
|
|
8980
|
-
|
|
8981
|
-
|
|
9109
|
+
let prUrl;
|
|
9110
|
+
if (this.openPullRequest) {
|
|
9111
|
+
try {
|
|
9112
|
+
prUrl = (await this.openPullRequest({ branch: ws.branch, base: ws.baseBranch, title, body, draft: !input.completed })).url;
|
|
9113
|
+
} catch {
|
|
9114
|
+
prUrl = void 0;
|
|
9115
|
+
}
|
|
9116
|
+
}
|
|
9117
|
+
let pr = { status: 0, stdout: "", stderr: "" };
|
|
9118
|
+
if (!prUrl) {
|
|
9119
|
+
const prArgs = ["pr", "create", "--base", ws.baseBranch, "--head", ws.branch, "--title", title, "--body", body];
|
|
9120
|
+
if (!input.completed) prArgs.push("--draft");
|
|
9121
|
+
pr = await this.run("gh", prArgs, ws.dir);
|
|
9122
|
+
prUrl = pr.status === 0 ? /https:\/\/\S+/.exec(pr.stdout)?.[0] : void 0;
|
|
9123
|
+
}
|
|
8982
9124
|
let compareUrl;
|
|
8983
9125
|
if (!prUrl) {
|
|
8984
9126
|
const remoteUrl = (await this.git(["remote", "get-url", ws.remote], ws.dir)).stdout.trim();
|
|
@@ -8987,8 +9129,32 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
|
|
|
8987
9129
|
`The branch was pushed, but the pull request couldn't be opened automatically${firstLine(pr.stderr) ? ` (${firstLine(pr.stderr)})` : ""}.` + (compareUrl ? " Use the link to open it." : ` Open a pull request for ${ws.branch} on your git host.`)
|
|
8988
9130
|
);
|
|
8989
9131
|
}
|
|
9132
|
+
const removed = await this.removeWorktree(ws, notes);
|
|
9133
|
+
return {
|
|
9134
|
+
...base,
|
|
9135
|
+
pushed: true,
|
|
9136
|
+
...prUrl ? { prUrl } : {},
|
|
9137
|
+
...compareUrl ? { compareUrl } : {},
|
|
9138
|
+
...removed ? {} : { keptWorktree: ws.dir, needsAttention: true }
|
|
9139
|
+
};
|
|
9140
|
+
}
|
|
9141
|
+
/** True when the worktree has uncommitted (or unreadable) state. */
|
|
9142
|
+
async isDirty(dir) {
|
|
9143
|
+
const status = await this.git(["status", "--porcelain"], dir);
|
|
9144
|
+
return status.status !== 0 || status.stdout.trim().length > 0;
|
|
9145
|
+
}
|
|
9146
|
+
/**
|
|
9147
|
+
* Removes a run's worktree — a separate step, run only once the worktree is
|
|
9148
|
+
* verified clean (everything is committed). Returns false, keeping the
|
|
9149
|
+
* worktree and noting why, when it still has changes.
|
|
9150
|
+
*/
|
|
9151
|
+
async removeWorktree(ws, notes) {
|
|
9152
|
+
if (await this.isDirty(ws.dir)) {
|
|
9153
|
+
notes.push(`The run's folder still has uncommitted changes, so it was kept: ${ws.dir} (branch ${ws.branch}).`);
|
|
9154
|
+
return false;
|
|
9155
|
+
}
|
|
8990
9156
|
await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
|
|
8991
|
-
return
|
|
9157
|
+
return true;
|
|
8992
9158
|
}
|
|
8993
9159
|
};
|
|
8994
9160
|
|
|
@@ -9230,15 +9396,16 @@ async function handleStartExecution(ctx, job) {
|
|
|
9230
9396
|
);
|
|
9231
9397
|
return;
|
|
9232
9398
|
}
|
|
9233
|
-
const routed = resolveProjectDirForJob(payload.projectRemote, {
|
|
9234
|
-
flag: ctx.projectDirFlag,
|
|
9235
|
-
config: readConfig()
|
|
9236
|
-
});
|
|
9399
|
+
const routed = resolveProjectDirForJob(payload.projectRemote, { config: readConfig() });
|
|
9237
9400
|
if (routed.status === "unregistered") {
|
|
9238
9401
|
await completeWithFailure(ctx, job, unregisteredRemoteMessage(routed.remote));
|
|
9239
9402
|
return;
|
|
9240
9403
|
}
|
|
9241
|
-
|
|
9404
|
+
if (routed.status === "no-remote") {
|
|
9405
|
+
await completeWithFailure(ctx, job, noProjectRemoteMessage());
|
|
9406
|
+
return;
|
|
9407
|
+
}
|
|
9408
|
+
const jobProjectDir = routed.path;
|
|
9242
9409
|
let keyRun;
|
|
9243
9410
|
if (payload.useAiKey) {
|
|
9244
9411
|
try {
|
|
@@ -9311,8 +9478,11 @@ async function handleStartExecution(ctx, job) {
|
|
|
9311
9478
|
// H4: keep this machine online during the long orchestrator run — the
|
|
9312
9479
|
// poll loop (its own heartbeat) is blocked for the whole job.
|
|
9313
9480
|
heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0),
|
|
9314
|
-
// Own branch + worktree per run, finishing with a pull request
|
|
9315
|
-
|
|
9481
|
+
// Own branch + worktree per run, finishing with a pull request (opened
|
|
9482
|
+
// through CompBox's GitHub app when the project is connected to it).
|
|
9483
|
+
workspace: new RunWorkspaceManager({
|
|
9484
|
+
openPullRequest: (input) => ctx.client.openPullRequest(ctx.machineToken, job.id, input)
|
|
9485
|
+
})
|
|
9316
9486
|
}
|
|
9317
9487
|
)
|
|
9318
9488
|
);
|
|
@@ -9400,10 +9570,18 @@ var runCommand = new Command8("run").description("Start the Agent Runner daemon
|
|
|
9400
9570
|
`Server-side hold per request, ms (default ${String(POLL_WAIT_MS)} \u2014 the server answers immediately and the daemon paces itself; raising this bills Cloud Run vCPU for the whole hold)`
|
|
9401
9571
|
).option(
|
|
9402
9572
|
"--project-dir <path>",
|
|
9403
|
-
"
|
|
9573
|
+
"Register a project folder (a git checkout) for its repository before starting \u2014 same as `compbox machines dirs add <path>`. There is no default folder."
|
|
9404
9574
|
).action(async (options) => {
|
|
9405
9575
|
if (options.projectDir && options.projectDir.trim().length > 0) {
|
|
9406
|
-
|
|
9576
|
+
try {
|
|
9577
|
+
const entry = addProjectDir(options.projectDir.trim());
|
|
9578
|
+
console.log(chalk9.green(`Registered ${entry.remote} \u2192 ${entry.path}`));
|
|
9579
|
+
} catch (error) {
|
|
9580
|
+
console.error(chalk9.red(`
|
|
9581
|
+
Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error.message : String(error)}`));
|
|
9582
|
+
process.exit(1);
|
|
9583
|
+
return;
|
|
9584
|
+
}
|
|
9407
9585
|
}
|
|
9408
9586
|
const config = readConfig();
|
|
9409
9587
|
applyPxpipeEnv(config);
|
|
@@ -9438,23 +9616,29 @@ var runCommand = new Command8("run").description("Start the Agent Runner daemon
|
|
|
9438
9616
|
}
|
|
9439
9617
|
const waitMs = options.waitMs ? Number.parseInt(options.waitMs, 10) : POLL_WAIT_MS;
|
|
9440
9618
|
const client = new MailboxClient(config.apiBaseUrl);
|
|
9441
|
-
const projectDir = resolveProjectDir({ flag: options.projectDir, config });
|
|
9442
9619
|
const jobContext = {
|
|
9443
9620
|
client,
|
|
9444
9621
|
machineToken,
|
|
9445
9622
|
apiBaseUrl: config.apiBaseUrl,
|
|
9446
9623
|
aiMode: config.aiMode,
|
|
9447
|
-
userApiToken: config.apiToken
|
|
9448
|
-
projectDir,
|
|
9449
|
-
// ENG-179: preserve the raw flag so per-job fallback resolution reproduces
|
|
9450
|
-
// flag→env→config precedence for jobs without a projectRemote.
|
|
9451
|
-
projectDirFlag: options.projectDir
|
|
9624
|
+
userApiToken: config.apiToken
|
|
9452
9625
|
};
|
|
9626
|
+
const folders = config.projectDirs ?? [];
|
|
9627
|
+
const legacyDir = unusedLegacyProjectDir(config);
|
|
9453
9628
|
console.log(chalk9.bold("\nCompBox Agent Runner\n"));
|
|
9454
9629
|
console.log(chalk9.gray(` Central: ${config.apiBaseUrl}`));
|
|
9455
9630
|
console.log(chalk9.gray(` Machine: ${config.machineName ?? config.machineId}`));
|
|
9456
9631
|
console.log(chalk9.gray(` AI mode: ${config.aiMode ?? "unset"}`));
|
|
9457
|
-
|
|
9632
|
+
if (folders.length === 0) {
|
|
9633
|
+
console.log(chalk9.yellow(" Projects: none registered \u2014 runs are refused until you add one (`compbox machines dirs add <path>`)."));
|
|
9634
|
+
} else {
|
|
9635
|
+
for (const entry of folders) {
|
|
9636
|
+
console.log(chalk9.gray(` Project: ${entry.remote} \u2192 ${entry.path}`));
|
|
9637
|
+
}
|
|
9638
|
+
}
|
|
9639
|
+
if (legacyDir) {
|
|
9640
|
+
console.log(chalk9.yellow(` Note: the old default folder (${legacyDir}) is no longer used. Runs go only to a project's registered folder.`));
|
|
9641
|
+
}
|
|
9458
9642
|
console.log(
|
|
9459
9643
|
chalk9.gray(
|
|
9460
9644
|
` Polling for jobs (every ${String(Math.round(IDLE_POLL_INTERVAL_MS / 1e3))}s idle, ${String(Math.round(ACTIVE_POLL_INTERVAL_MS / 1e3))}s while a session is active)...
|
|
@@ -9811,16 +9995,316 @@ machinesCommand.command("rm <id>").description("Remove (revoke) a paired machine
|
|
|
9811
9995
|
}
|
|
9812
9996
|
});
|
|
9813
9997
|
|
|
9998
|
+
// src/commands/repo.ts
|
|
9999
|
+
import { Command as Command12 } from "commander";
|
|
10000
|
+
import chalk13 from "chalk";
|
|
10001
|
+
function findProject(projects, query) {
|
|
10002
|
+
const q = query.trim().toLowerCase();
|
|
10003
|
+
return projects.find((p) => p.key.toLowerCase() === q) ?? projects.find((p) => p.name.toLowerCase() === q) ?? null;
|
|
10004
|
+
}
|
|
10005
|
+
async function listProjects(apiBaseUrl, apiToken) {
|
|
10006
|
+
const res = await fetch(`${apiBaseUrl.replace(/\/+$/, "")}/api/v1/teams?limit=100`, {
|
|
10007
|
+
headers: { Authorization: `Bearer ${apiToken}` }
|
|
10008
|
+
});
|
|
10009
|
+
if (!res.ok) throw new Error(`CompBox returned ${String(res.status)} listing projects`);
|
|
10010
|
+
const body = await res.json();
|
|
10011
|
+
return body.data ?? [];
|
|
10012
|
+
}
|
|
10013
|
+
var repoCommand = new Command12("repo").description("Set up projects' repositories on this computer");
|
|
10014
|
+
repoCommand.command("setup <project>").description("Clone (or adopt) a project's repository on this computer so its runs land there").option("--folder <path>", "Where to put it (default ~/CompBox/<repo>)").action(async (project, options) => {
|
|
10015
|
+
const config = readConfig();
|
|
10016
|
+
if (!config.apiBaseUrl || !config.apiToken) {
|
|
10017
|
+
console.error(chalk13.red("\nNot logged in. Run `compbox login` first."));
|
|
10018
|
+
process.exit(1);
|
|
10019
|
+
return;
|
|
10020
|
+
}
|
|
10021
|
+
let projects;
|
|
10022
|
+
try {
|
|
10023
|
+
projects = await listProjects(config.apiBaseUrl, config.apiToken);
|
|
10024
|
+
} catch (error) {
|
|
10025
|
+
console.error(chalk13.red(`
|
|
10026
|
+
${error instanceof Error ? error.message : "Could not reach CompBox."}`));
|
|
10027
|
+
process.exit(1);
|
|
10028
|
+
return;
|
|
10029
|
+
}
|
|
10030
|
+
const match = findProject(projects, project);
|
|
10031
|
+
if (!match) {
|
|
10032
|
+
console.error(chalk13.red(`
|
|
10033
|
+
No project called "${project}". Your projects: ${projects.map((p) => p.key).join(", ") || "none"}.`));
|
|
10034
|
+
process.exit(1);
|
|
10035
|
+
return;
|
|
10036
|
+
}
|
|
10037
|
+
if (!match.gitRemote) {
|
|
10038
|
+
console.error(
|
|
10039
|
+
chalk13.red(`
|
|
10040
|
+
${match.name} has no repository yet. Connect one on the project's Settings \u2192 Repository page first.`)
|
|
10041
|
+
);
|
|
10042
|
+
process.exit(1);
|
|
10043
|
+
return;
|
|
10044
|
+
}
|
|
10045
|
+
console.log(chalk13.gray(`
|
|
10046
|
+
Setting up ${match.name} (${match.gitRemote})...`));
|
|
10047
|
+
const outcome = await invokeConnectRepo({
|
|
10048
|
+
teamId: match.id,
|
|
10049
|
+
projectRemote: match.gitRemote,
|
|
10050
|
+
projectName: match.name,
|
|
10051
|
+
...options.folder && { folder: options.folder }
|
|
10052
|
+
});
|
|
10053
|
+
const result = outcome.result;
|
|
10054
|
+
if (outcome.status === "done") {
|
|
10055
|
+
console.log(chalk13.green(`\u2713 ${typeof result.message === "string" ? result.message : "Set up."}`));
|
|
10056
|
+
console.log(chalk13.gray(" The CompBox app reports it to CompBox on its next check-in."));
|
|
10057
|
+
} else {
|
|
10058
|
+
console.error(chalk13.red(`\u2716 ${typeof result.error === "string" ? result.error : "Setting it up failed."}`));
|
|
10059
|
+
process.exit(1);
|
|
10060
|
+
}
|
|
10061
|
+
});
|
|
10062
|
+
|
|
10063
|
+
// src/commands/workspace.ts
|
|
10064
|
+
import { Command as Command13 } from "commander";
|
|
10065
|
+
import chalk14 from "chalk";
|
|
10066
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
10067
|
+
import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync5 } from "node:fs";
|
|
10068
|
+
import { homedir as homedir7 } from "node:os";
|
|
10069
|
+
import { join as join12 } from "node:path";
|
|
10070
|
+
function readWorkspaceEnv(env = process.env) {
|
|
10071
|
+
const apiUrl = env.COMPBOX_API_URL?.trim();
|
|
10072
|
+
const jobId = env.COMPBOX_JOB_ID?.trim();
|
|
10073
|
+
const token = env.COMPBOX_WORKSPACE_TOKEN?.trim();
|
|
10074
|
+
if (!apiUrl || !jobId || !token) return null;
|
|
10075
|
+
return { apiUrl: apiUrl.replace(/\/+$/, ""), jobId, token };
|
|
10076
|
+
}
|
|
10077
|
+
async function workspaceApi(env, path3, method, fetchFn) {
|
|
10078
|
+
const res = await fetchFn(`${env.apiUrl}/api/v1/cloud-runs/workspace/${path3}`, {
|
|
10079
|
+
method,
|
|
10080
|
+
headers: { Authorization: `Bearer ${env.token}`, ...method === "POST" && { "Content-Type": "application/json" } },
|
|
10081
|
+
...method === "POST" && { body: "{}" }
|
|
10082
|
+
});
|
|
10083
|
+
if (!res.ok) {
|
|
10084
|
+
const body = await res.json().catch(() => null);
|
|
10085
|
+
throw new Error(body?.error?.message ?? `CompBox returned ${String(res.status)} for ${path3}`);
|
|
10086
|
+
}
|
|
10087
|
+
return (await res.json()).data;
|
|
10088
|
+
}
|
|
10089
|
+
var defaultRunner = (command, args, cwd) => {
|
|
10090
|
+
const res = spawnSync2(command, args, { cwd, encoding: "utf-8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
|
|
10091
|
+
if (res.status !== 0) {
|
|
10092
|
+
throw new Error(`${command} ${args[0] ?? ""} failed: ${(res.stderr || res.stdout || "").trim().split("\n").pop() ?? ""}`);
|
|
10093
|
+
}
|
|
10094
|
+
};
|
|
10095
|
+
function agentRoutingInstructions(agentsDir, compboxRoot = "/opt/compbox") {
|
|
10096
|
+
return `# CompBox cloud workspace
|
|
10097
|
+
|
|
10098
|
+
When a prompt starts with \`@<agent-name>\` (for example \`@planner\` or \`@orchestrator\`), read the agent file at \`${agentsDir}/<agent-name>.md\` in full and follow it exactly.
|
|
10099
|
+
|
|
10100
|
+
CompBox's own files live outside the project: any path an agent file mentions under \`.github/agents/\` or \`.github/skills/\` is at \`${compboxRoot}/.github/agents/\` or \`${compboxRoot}/.github/skills/\`. Never copy them into the project.
|
|
10101
|
+
|
|
10102
|
+
Never push to the default branch: work on the run's own branch.
|
|
10103
|
+
`;
|
|
10104
|
+
}
|
|
10105
|
+
async function runWorkspace(deps = {}) {
|
|
10106
|
+
const env = readWorkspaceEnv(deps.env);
|
|
10107
|
+
if (!env) {
|
|
10108
|
+
console.error(chalk14.red("Not a CompBox cloud workspace (COMPBOX_API_URL, COMPBOX_JOB_ID, COMPBOX_WORKSPACE_TOKEN)."));
|
|
10109
|
+
return 2;
|
|
10110
|
+
}
|
|
10111
|
+
const fetchFn = deps.fetchFn ?? fetch;
|
|
10112
|
+
const run = deps.run ?? defaultRunner;
|
|
10113
|
+
const home = deps.home ?? homedir7();
|
|
10114
|
+
const agentsDir = deps.agentsDir ?? "/opt/compbox/.github/agents/claude";
|
|
10115
|
+
const workDir = deps.workDir ?? "/workspace";
|
|
10116
|
+
const client = deps.client ?? new MailboxClient(env.apiUrl);
|
|
10117
|
+
const job = await client.nextJob(env.token, 0);
|
|
10118
|
+
if (job?.id !== env.jobId) {
|
|
10119
|
+
console.log("Nothing to do: the job has already finished.");
|
|
10120
|
+
return 0;
|
|
10121
|
+
}
|
|
10122
|
+
const fail = async (error) => {
|
|
10123
|
+
console.error(chalk14.red(error));
|
|
10124
|
+
await client.completeJob(env.token, job.id, "failed", { error }).catch(() => void 0);
|
|
10125
|
+
return 1;
|
|
10126
|
+
};
|
|
10127
|
+
const payload = job.payload ?? {};
|
|
10128
|
+
const repoDir = join12(workDir, "repo");
|
|
10129
|
+
let userApiToken;
|
|
10130
|
+
let keyRun;
|
|
10131
|
+
try {
|
|
10132
|
+
const git = await workspaceApi(env, "git-credentials", "GET", fetchFn);
|
|
10133
|
+
userApiToken = (await workspaceApi(env, "session", "POST", fetchFn)).userApiToken;
|
|
10134
|
+
const key = await client.getAiKey(env.token, job.id);
|
|
10135
|
+
keyRun = { apiKey: key.apiKey, model: key.model };
|
|
10136
|
+
run("git", ["config", "--global", "credential.helper", "!compbox workspace git-credential"]);
|
|
10137
|
+
run("git", ["config", "--global", "user.name", "CompBox"]);
|
|
10138
|
+
run("git", ["config", "--global", "user.email", "bot@mycompbox.com"]);
|
|
10139
|
+
mkdirSync8(workDir, { recursive: true });
|
|
10140
|
+
run("git", ["clone", "--branch", git.defaultBranch, git.cloneUrl, repoDir]);
|
|
10141
|
+
run("claude", [
|
|
10142
|
+
"mcp",
|
|
10143
|
+
"add",
|
|
10144
|
+
"--scope",
|
|
10145
|
+
"user",
|
|
10146
|
+
"-e",
|
|
10147
|
+
`API_BASE_URL=${env.apiUrl}`,
|
|
10148
|
+
"-e",
|
|
10149
|
+
`API_TOKEN=${userApiToken}`,
|
|
10150
|
+
"compbox",
|
|
10151
|
+
"--",
|
|
10152
|
+
"compbox-mcp"
|
|
10153
|
+
]);
|
|
10154
|
+
mkdirSync8(join12(home, ".claude"), { recursive: true });
|
|
10155
|
+
writeFileSync5(join12(home, ".claude", "CLAUDE.md"), agentRoutingInstructions(agentsDir));
|
|
10156
|
+
} catch (error) {
|
|
10157
|
+
return fail(`Setting up the cloud workspace failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
10158
|
+
}
|
|
10159
|
+
const heartbeat = () => client.heartbeat(env.token).then(() => void 0).catch(() => void 0);
|
|
10160
|
+
let outcome;
|
|
10161
|
+
if (payload.kind === "plan" && payload.epicRequestId) {
|
|
10162
|
+
outcome = await (deps.plan ?? invokeStartExecutionPlan)(
|
|
10163
|
+
{
|
|
10164
|
+
mailboxClient: client,
|
|
10165
|
+
machineToken: env.token,
|
|
10166
|
+
jobId: job.id,
|
|
10167
|
+
apiBaseUrl: env.apiUrl,
|
|
10168
|
+
userApiToken,
|
|
10169
|
+
epicRequestId: payload.epicRequestId,
|
|
10170
|
+
projectDir: repoDir,
|
|
10171
|
+
keyRun
|
|
10172
|
+
},
|
|
10173
|
+
{ heartbeat }
|
|
10174
|
+
);
|
|
10175
|
+
} else if (payload.kind === "orchestrate" && payload.epicId) {
|
|
10176
|
+
outcome = await (deps.orchestrate ?? invokeStartExecutionOrchestrate)(
|
|
10177
|
+
{
|
|
10178
|
+
mailboxClient: client,
|
|
10179
|
+
machineToken: env.token,
|
|
10180
|
+
jobId: job.id,
|
|
10181
|
+
epicId: payload.epicId,
|
|
10182
|
+
projectDir: repoDir,
|
|
10183
|
+
keyRun
|
|
10184
|
+
},
|
|
10185
|
+
{
|
|
10186
|
+
heartbeat,
|
|
10187
|
+
workspace: new RunWorkspaceManager({
|
|
10188
|
+
openPullRequest: (input) => client.openPullRequest(env.token, job.id, input)
|
|
10189
|
+
})
|
|
10190
|
+
}
|
|
10191
|
+
);
|
|
10192
|
+
} else {
|
|
10193
|
+
return fail("The job is missing what to plan or build.");
|
|
10194
|
+
}
|
|
10195
|
+
await client.completeJob(env.token, job.id, outcome.status, outcome.result);
|
|
10196
|
+
console.log(outcome.status === "done" ? chalk14.green("Finished.") : chalk14.yellow(`Stopped: ${JSON.stringify(outcome.result)}`));
|
|
10197
|
+
return outcome.status === "done" ? 0 : 1;
|
|
10198
|
+
}
|
|
10199
|
+
async function gitCredential(action, deps = {}) {
|
|
10200
|
+
if (action !== "get") return;
|
|
10201
|
+
const env = readWorkspaceEnv(deps.env);
|
|
10202
|
+
if (!env) return;
|
|
10203
|
+
const git = await workspaceApi(env, "git-credentials", "GET", deps.fetchFn ?? fetch);
|
|
10204
|
+
(deps.write ?? ((s) => process.stdout.write(s)))(`username=${git.username}
|
|
10205
|
+
password=${git.token}
|
|
10206
|
+
`);
|
|
10207
|
+
}
|
|
10208
|
+
var workspaceCommand = new Command13("workspace").description("Run inside a CompBox cloud workspace (used by CompBox)");
|
|
10209
|
+
workspaceCommand.command("run").description("Run this workspace's one plan or build job").action(async () => {
|
|
10210
|
+
process.exitCode = await runWorkspace();
|
|
10211
|
+
});
|
|
10212
|
+
workspaceCommand.command("git-credential <action>").description("Git credential helper for the workspace repository").action(async (action) => {
|
|
10213
|
+
await gitCredential(action);
|
|
10214
|
+
});
|
|
10215
|
+
|
|
10216
|
+
// src/commands/deploy.ts
|
|
10217
|
+
import { Command as Command14 } from "commander";
|
|
10218
|
+
import chalk15 from "chalk";
|
|
10219
|
+
var SLACK_MS = 6e4;
|
|
10220
|
+
var WAIT_LIMIT_MS = 30 * 6e4;
|
|
10221
|
+
async function call(deps, path3, init = {}) {
|
|
10222
|
+
const res = await (deps.fetchFn ?? fetch)(`${deps.apiBaseUrl.replace(/\/+$/, "")}/api/v1${path3}`, {
|
|
10223
|
+
method: init.method ?? "GET",
|
|
10224
|
+
headers: {
|
|
10225
|
+
Authorization: `Bearer ${deps.apiToken}`,
|
|
10226
|
+
...init.body !== void 0 && { "Content-Type": "application/json" }
|
|
10227
|
+
},
|
|
10228
|
+
...init.body !== void 0 && { body: JSON.stringify(init.body) }
|
|
10229
|
+
});
|
|
10230
|
+
const body = await res.json().catch(() => null);
|
|
10231
|
+
if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `CompBox returned ${String(res.status)}`);
|
|
10232
|
+
return body?.data;
|
|
10233
|
+
}
|
|
10234
|
+
async function deployProject(deps, teamId, environment, wait) {
|
|
10235
|
+
const log = deps.log ?? ((line) => {
|
|
10236
|
+
console.log(line);
|
|
10237
|
+
});
|
|
10238
|
+
const now = deps.now ?? Date.now;
|
|
10239
|
+
const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
10240
|
+
const startedAt = now();
|
|
10241
|
+
const queued = await call(deps, `/teams/${teamId}/deployments`, { method: "POST", body: { environment } });
|
|
10242
|
+
log(chalk15.gray(`Deploying to ${environment}...`));
|
|
10243
|
+
if (!wait) {
|
|
10244
|
+
log(`Started. When it's done it'll be at ${queued.url}`);
|
|
10245
|
+
return 0;
|
|
10246
|
+
}
|
|
10247
|
+
let last = "";
|
|
10248
|
+
while (now() - startedAt < WAIT_LIMIT_MS) {
|
|
10249
|
+
await sleep2(5e3);
|
|
10250
|
+
const list = await call(deps, `/teams/${teamId}/deployments`);
|
|
10251
|
+
const d = list.find((x) => x.environment === environment);
|
|
10252
|
+
const current = d?.runUrl && d.startedAt && Date.parse(d.startedAt) >= startedAt - SLACK_MS ? d : null;
|
|
10253
|
+
if (!current) continue;
|
|
10254
|
+
if (current.state !== last) {
|
|
10255
|
+
last = current.state;
|
|
10256
|
+
if (current.state === "in_progress") log(chalk15.gray(`Building and deploying (${current.runUrl ?? ""})...`));
|
|
10257
|
+
}
|
|
10258
|
+
if (current.state === "success") {
|
|
10259
|
+
log(chalk15.green(`
|
|
10260
|
+
Live: ${current.url}`));
|
|
10261
|
+
return 0;
|
|
10262
|
+
}
|
|
10263
|
+
if (current.state === "failure" || current.state === "cancelled") {
|
|
10264
|
+
log(chalk15.red(`
|
|
10265
|
+
The deploy ${current.state === "failure" ? "failed" : "was cancelled"}. Run log: ${current.runUrl ?? ""}`));
|
|
10266
|
+
return 1;
|
|
10267
|
+
}
|
|
10268
|
+
}
|
|
10269
|
+
log(chalk15.yellow(`
|
|
10270
|
+
Still running after 30 minutes. Follow it on GitHub; it'll be at ${queued.url}`));
|
|
10271
|
+
return 1;
|
|
10272
|
+
}
|
|
10273
|
+
var deployCommand = new Command14("deploy").description("Deploy a project (its default branch) and print the live address").argument("<project>", "The project's key (e.g. SHOP) or name").option("--env <environment>", "dev, stage or prod", "dev").option("--no-wait", "Start the deploy and don't wait for it").action(async (project, options) => {
|
|
10274
|
+
const config = readConfig();
|
|
10275
|
+
if (!config.apiBaseUrl || !config.apiToken) {
|
|
10276
|
+
console.error(chalk15.red("\nNot logged in. Run `compbox login` first."));
|
|
10277
|
+
process.exit(1);
|
|
10278
|
+
return;
|
|
10279
|
+
}
|
|
10280
|
+
const deps = { apiBaseUrl: config.apiBaseUrl, apiToken: config.apiToken };
|
|
10281
|
+
try {
|
|
10282
|
+
const projects = await listProjects(config.apiBaseUrl, config.apiToken);
|
|
10283
|
+
const match = findProject(projects, project);
|
|
10284
|
+
if (!match) {
|
|
10285
|
+
console.error(chalk15.red(`
|
|
10286
|
+
No project called "${project}". Your projects: ${projects.map((p) => p.key).join(", ") || "none"}.`));
|
|
10287
|
+
process.exit(1);
|
|
10288
|
+
return;
|
|
10289
|
+
}
|
|
10290
|
+
process.exitCode = await deployProject(deps, match.id, options.env, options.wait);
|
|
10291
|
+
} catch (error) {
|
|
10292
|
+
console.error(chalk15.red(`
|
|
10293
|
+
${error instanceof Error ? error.message : String(error)}`));
|
|
10294
|
+
process.exit(1);
|
|
10295
|
+
}
|
|
10296
|
+
});
|
|
10297
|
+
|
|
9814
10298
|
// src/index.ts
|
|
9815
10299
|
function resolveCliVersion() {
|
|
9816
10300
|
if (true) {
|
|
9817
|
-
return "1.
|
|
10301
|
+
return "1.21.0";
|
|
9818
10302
|
}
|
|
9819
10303
|
const require2 = createRequire(import.meta.url);
|
|
9820
10304
|
const pkg = require2("../package.json");
|
|
9821
10305
|
return pkg.version;
|
|
9822
10306
|
}
|
|
9823
|
-
var program = new
|
|
10307
|
+
var program = new Command15();
|
|
9824
10308
|
program.name("compbox").description("CompBox CLI \u2014 pair this machine, manage Skill Packs, and run the Agent Runner daemon").version(resolveCliVersion());
|
|
9825
10309
|
program.addCommand(installCommand);
|
|
9826
10310
|
program.addCommand(updateCommand);
|
|
@@ -9832,4 +10316,7 @@ program.addCommand(doctorCommand);
|
|
|
9832
10316
|
program.addCommand(runCommand);
|
|
9833
10317
|
program.addCommand(serviceCommand);
|
|
9834
10318
|
program.addCommand(machinesCommand);
|
|
10319
|
+
program.addCommand(repoCommand);
|
|
10320
|
+
program.addCommand(workspaceCommand);
|
|
10321
|
+
program.addCommand(deployCommand);
|
|
9835
10322
|
program.parse(process.argv);
|