An open-source, faster Devin alternative
TypeScript
CLI: opencomputer push to the project's automation repository (work 067)
Mohamed Habib via Computer0ca3fd0077a3
diff --git a/cli/src/api.ts b/cli/src/api.tsindex 0180b877..c66eadb4 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -1,5 +1,6 @@import { createHash } from "node:crypto";+import type { ProjectRepositoryCredential } from "./push.js";import type { ResolvedConfig } from "./config.js";import type { MemoryDeclaration, ProjectResourceManifest } from "./project.js";@@ -660,6 +661,14 @@ export class OpenComputerClient {);}+ /** A one-hour push credential for the project's automation repository (work 067). */+ projectRepositoryCredential(projectId: string) {+ return this.request<ProjectRepositoryCredential>(+ `/api/managed-agents/projects/${encodeURIComponent(projectId)}/repository/credentials`,+ { method: "POST" },+ );+ }+githubStatus(projectId: string) {return this.request<ManagedGitHubStatus>(`/api/managed-agents/projects/${encodeURIComponent(projectId)}/github`,diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 44fa1f0a..91913a4a 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -73,6 +73,7 @@ import {materializeTemplateCheckout,} from "./template-local.js";import { materializeProjectArchive } from "./project-local.js";+import { pushToProjectRepository } from "./push.js";import { spawnSync } from "node:child_process";import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";@@ -1003,6 +1004,30 @@ export async function runCommand(return;}+ if (command === "push") {+ const projectReference = option(args, "--project");+ const ref = args.shift();+ if (args.length) {+ throw new Error("Usage: opencomputer push [<ref>] [--project <id|slug>]");+ }+ const root = await findOpenComputerProjectRoot(process.cwd());+ const projectId = projectReference+ ? (+ (await client.projects()).find(+ (candidate) =>+ candidate.id === projectReference ||+ candidate.slug === projectReference,+ ) ?? { id: undefined }+ ).id+ : (await ensureProjectBinding(client, config, root)).projectId;+ if (!projectId) throw new Error(`Project ${projectReference} was not found.`);+ const credential = await client.projectRepositoryCredential(projectId);+ pushToProjectRepository({ credential, directory: root, ...(ref ? { ref } : {}) });+ if (globals.json) printJSON({ projectId, remoteUrl: credential.remoteUrl });+ else process.stdout.write(`Pushed to ${credential.remoteUrl}\n`);+ return;+ }+if (command === "template") {const action = args.shift();if (action === "clone") {diff --git a/cli/src/index.ts b/cli/src/index.tsindex ef8360cd..c59ac305 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -56,6 +56,7 @@ Usage:opencomputer template deploy <repository-url> [--project-name <name>] [--directory <path>] [--refresh]opencomputer template clone <repository-url> --commit <sha> --project <id> [--directory <path>]opencomputer project clone <project-id> [--directory <path>]+ opencomputer push [<ref>] [--project <id|slug>]opencomputer link (--project <id|slug> | --create-project <name>)opencomputer doctoropencomputer deploy --watch [--project <id|slug> | --create-project <name>]diff --git a/cli/src/push.test.ts b/cli/src/push.test.tsnew file mode 100644index 00000000..08e5019a--- /dev/null+++ b/cli/src/push.test.ts@@ -0,0 +1,59 @@+import { execFileSync } from "node:child_process";+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import assert from "node:assert/strict";+import { test } from "node:test";+import { gitPushEnvironment, pushToProjectRepository } from "./push.js";++const credential = {+ remoteUrl: "https://acme.code.storage/automation-prj_1.git",+ username: "t",+ password: "jwt",+ expiresAt: "2026-10-16T02:00:00.000Z",+};++test("authenticates git for the repository's origin only, outside argv", () => {+ assert.deepEqual(gitPushEnvironment(credential), {+ GIT_CONFIG_COUNT: "1",+ GIT_CONFIG_KEY_0: "http.https://acme.code.storage/.extraheader",+ GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from("t:jwt").toString("base64")}`,+ GIT_TERMINAL_PROMPT: "0",+ });+});++test("pushes HEAD to main and refuses to drop commits already there", () => {+ const git = (cwd: string, ...args: string[]) =>+ execFileSync(+ "git",+ ["-c", "user.name=t", "-c", "user.email=t@t", ...args],+ {+ cwd,+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ },+ ).trim();+ const root = mkdtempSync(join(tmpdir(), "oc-push-"));+ const remote = join(root, "remote.git");+ git(root, "init", "-q", "--bare", remote);+ const local = { ...credential, remoteUrl: `file://${remote}` };+ const work = (name: string) => {+ const directory = join(root, name);+ git(root, "init", "-q", directory);+ writeFileSync(join(directory, "agent.ts"), name);+ git(directory, "add", ".");+ git(directory, "commit", "-qm", name);+ return directory;+ };+ const computer = work("computer");+ pushToProjectRepository({ credential: local, directory: computer });+ assert.equal(+ git(remote, "rev-parse", "main"),+ git(computer, "rev-parse", "HEAD"),+ );+ assert.throws(+ () =>+ pushToProjectRepository({ credential: local, directory: work("laptop") }),+ /fetch and merge/,+ );+});diff --git a/cli/src/push.ts b/cli/src/push.tsnew file mode 100644index 00000000..ba04a7cd--- /dev/null+++ b/cli/src/push.ts@@ -0,0 +1,59 @@+import { spawnSync } from "node:child_process";++/** A one-hour push credential for a project's automation repository (work 067). */+export interface ProjectRepositoryCredential {+ remoteUrl: string;+ username: string;+ password: string;+ expiresAt: string;+}++/**+ * Git configuration that authenticates one push to the repository, passed in+ * the environment so the credential never appears in argv, a remote, or a+ * config file.+ */+export function gitPushEnvironment(+ credential: ProjectRepositoryCredential,+): Record<string, string> {+ const authorization = Buffer.from(+ `${credential.username}:${credential.password}`,+ ).toString("base64");+ return {+ GIT_CONFIG_COUNT: "1",+ GIT_CONFIG_KEY_0: `http.${new URL(credential.remoteUrl).origin}/.extraheader`,+ GIT_CONFIG_VALUE_0: `Authorization: Basic ${authorization}`,+ GIT_TERMINAL_PROMPT: "0",+ };+}++/**+ * Pushes `ref` (HEAD by default) of the git repository at `directory` to the+ * automation repository's `main`. Git refuses a push that would drop commits+ * already there, so a person and the computer cannot overwrite each other.+ */+export function pushToProjectRepository(input: {+ credential: ProjectRepositoryCredential;+ directory: string;+ ref?: string;+}): void {+ const result = spawnSync(+ "git",+ [+ "push",+ input.credential.remoteUrl,+ `${input.ref ?? "HEAD"}:refs/heads/main`,+ ],+ {+ cwd: input.directory,+ stdio: "inherit",+ env: { ...process.env, ...gitPushEnvironment(input.credential) },+ },+ );+ if (result.error) throw result.error;+ if (result.status !== 0) {+ throw new Error(+ "git push failed. If the repository has commits you do not, fetch and merge them first.",+ );+ }+}diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 881f2562..19703bc5 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -359,6 +359,45 @@ describe("managed agents proxy", () => {).resolves.toBe(true);});+ it("passes a project repository credential through uncached", async () => {+ const fetchSpy = vi.fn(async (target: RequestInfo | URL, init?: RequestInit) => {+ expect(String(target)).toBe(+ "https://managedagents.test/v1/projects/prj_test/repository/credentials",+ );+ expect(init?.method).toBe("POST");+ return Response.json({+ remoteUrl: "https://acme.code.storage/automation-prj_test.git",+ username: "t",+ password: "jwt",+ expiresAt: "2026-10-16T02:00:00.000Z",+ internal: "dropped",+ });+ });+ vi.stubGlobal("fetch", fetchSpy);++ const response = await proxyManagedAgents(+ new Request(+ "https://mo-oc-dev.com/api/managed-agents/projects/prj_test/repository/credentials",+ { method: "POST" },+ ),+ {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ },+ { orgID: "org_test", userID: "user_test", role: "member" },+ "/api/managed-agents",+ );++ expect(response.status).toBe(200);+ expect(response.headers.get("cache-control")).toBe("no-store");+ expect(await response.json()).toEqual({+ remoteUrl: "https://acme.code.storage/automation-prj_test.git",+ username: "t",+ password: "jwt",+ expiresAt: "2026-10-16T02:00:00.000Z",+ });+ });+it("streams project source without exposing upstream headers", async () => {const fetchSpy = vi.fn(async (target: RequestInfo | URL) => {expect(String(target)).toBe(diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 680e9826..5392a155 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -2337,9 +2337,35 @@ function publicSuccessBody(}return { url: url.toString(), expiresAt: body.expiresAt };}+ if (method === "POST" && PROJECT_REPOSITORY_CREDENTIAL_ROUTE.test(suffix)) {+ // A one-hour push credential for the project's automation repository+ // (work 067): the remote carries no credential of its own.+ const remote =+ typeof body.remoteUrl === "string" ? new URL(body.remoteUrl) : null;+ if (+ !remote ||+ remote.protocol !== "https:" ||+ remote.username ||+ remote.password ||+ typeof body.username !== "string" ||+ typeof body.password !== "string" ||+ typeof body.expiresAt !== "string"+ ) {+ throw new Error("Invalid project repository credential");+ }+ return {+ remoteUrl: remote.toString(),+ username: body.username,+ password: body.password,+ expiresAt: body.expiresAt,+ };+ }throw new Error("Unsupported managed agents response");}+const PROJECT_REPOSITORY_CREDENTIAL_ROUTE =+ /^\/projects\/[^/]+\/repository\/credentials$/;+function publicWorkspaceFile(value: unknown): Record<string, unknown> {const file = record(value) ?? {};return {@@ -2449,7 +2475,8 @@ async function publicSuccessResponse(suffix.includes("/webhooks") ||suffix.includes("/event-subscriptions") ||suffix.startsWith("/channels/slack/setups") ||- isLinearRouteSuffix(suffix)+ isLinearRouteSuffix(suffix) ||+ PROJECT_REPOSITORY_CREDENTIAL_ROUTE.test(suffix)) {headers.set("cache-control", "no-store");}@@ -2691,6 +2718,9 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {if (method === "GET" && /^\/projects\/[^/]+\/source-archive$/.test(suffix)) {return true;}+ if (method === "POST" && PROJECT_REPOSITORY_CREDENTIAL_ROUTE.test(suffix)) {+ return true;+ }if ((method === "GET" || method === "DELETE") &&/^\/projects\/[^/]+\/github$/.test(suffix)