Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/globalConfig/accessor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
type GlobalConfig,
type GlobalConfigAccessor,
type GlobalConfigFileData,
type ReadWriteJson,
} from "./types";
import type { ReadWriteJson } from "../io";
import type { Logger } from "../logging";
import z from "zod";
import { globalConfigFileSchema } from "./types";
Expand Down
3 changes: 1 addition & 2 deletions src/globalConfig/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export { type GlobalConfigAccessor, type GlobalConfig, type ReadWriteJson } from "./types";
export { type GlobalConfigAccessor, type GlobalConfig } from "./types";
export { DefaultGlobalConfigAccessor } from "./accessor";
export { FsReadWriteJson } from "./json";
export { DEFAULT_GLOBAL_CONFIG } from "./config";
7 changes: 0 additions & 7 deletions src/globalConfig/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,3 @@ export interface GlobalConfigAccessor {
/** Validates and persists a new config. Throws on invalid shape. */
set(newConfig: GlobalConfig): Promise<GlobalConfig>;
}

export interface ReadWriteJson {
/** Reads data from the given file */
read<TSchema extends z.ZodType>(filePath: string, schema: TSchema): Promise<z.infer<TSchema>>;
/** Writes data to the given file */
write<TData extends object>(filePath: string, data: TData): Promise<TData>;
}
3 changes: 2 additions & 1 deletion src/handlers/config/config.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { createRootHandler } from "../index";
import { createSilentLogger, TestCoreClient, testIO } from "../../testing";
import { DefaultGlobalConfigAccessor, FsReadWriteJson } from "../../globalConfig";
import { DefaultGlobalConfigAccessor } from "../../globalConfig";
import { FsReadWriteJson } from "../../io";

describe("config", () => {
let tempDir: string;
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/harness/endpoint/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { renderTui } from "../../../tui";
import { Router } from "../../../router";
import type { AppIO, Core } from "../../types";
import type { AppIO } from "../../../io";
import type { Core } from "../../types";
import { createCreateEndpointHandler } from "./create";
import { createGetEndpointHandler } from "./get";
import { createListEndpointsHandler } from "./list";
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/harness/exec/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import z from "zod";
import { createHandler, flag, PathKey } from "../../../router";
import type { AppIO, Core } from "../../types.tsx";
import type { AppIO } from "../../../io";
import type { Core } from "../../types.tsx";
import { coreOptsFromCtx } from "../../utils.tsx";
import { JsonKey } from "../../keys.tsx";
import { JsonRendererKey, renderTuiAt } from "../../../tui";
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/harness/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { renderTui } from "../../tui";
import { withTuiOnEmptyFlagsAndArgs } from "../../middleware";
import { Router } from "../../router";
import type { AppIO, Core } from "../types";
import type { AppIO } from "../../io";
import type { Core } from "../types";
import { createGetHarnessHandler } from "./get";
import { createListHarnessHandler } from "./list";
import { createCreateHarnessHandler } from "./create";
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/harness/invoke/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import z from "zod";
import { createHandler, flag, PathKey } from "../../../router";
import type { AppIO, Core } from "../../types.tsx";
import type { AppIO } from "../../../io";
import type { Core } from "../../types.tsx";
import { coreOptsFromCtx } from "../../utils.tsx";
import { JsonKey } from "../../keys.tsx";
import { JsonRendererKey, renderTuiAt } from "../../../tui";
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/harness/version/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { renderTui } from "../../../tui";
import { Router } from "../../../router";
import type { AppIO, Core } from "../../types";
import type { AppIO } from "../../../io";
import type { Core } from "../../types";
import { createGetVersionHandler } from "./get";
import { createListVersionsHandler } from "./list";

Expand Down
2 changes: 1 addition & 1 deletion src/handlers/help.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CommandKey, type DefaultHandle } from "../router";
import type { AppIO } from "./types";
import type { AppIO } from "../io";

export function createHelpDefault(io: AppIO): DefaultHandle {
return async (ctx) => {
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/identity/api-key-credential-provider/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Router } from "../../../router";
import type { AppIO, Core } from "../../types";
import type { AppIO } from "../../../io";
import type { Core } from "../../types";
import { createHelpDefault } from "../../help";
import { createCreateApiKeyCredentialProviderHandler } from "./create";
import { createDeleteApiKeyCredentialProviderHandler } from "./delete";
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/identity/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Router } from "../../router";
import type { AppIO, Core } from "../types";
import type { AppIO } from "../../io";
import type { Core } from "../types";
import { createApiKeyCredentialProviderHandler } from "./api-key-credential-provider";
import { createHelpDefault } from "../help";

Expand Down
3 changes: 2 additions & 1 deletion src/handlers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { createConfigHandler } from "./config/";
import { createProjectHandler } from "./project/index.ts";
import { renderTui } from "../tui";
import { withRegion, withJsonRenderer, withLogging, withGlobalConfigAccessor } from "../middleware";
import type { AppIO, Core } from "./types.tsx";
import type { AppIO } from "../io";
import type { Core } from "./types.tsx";
import type { Logger } from "../logging";
import type { GlobalConfigAccessor } from "../globalConfig";

Expand Down
3 changes: 2 additions & 1 deletion src/handlers/runtime/endpoint/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Router } from "../../../router";
import { renderTui } from "../../../tui";
import type { AppIO, Core } from "../../types";
import type { AppIO } from "../../../io";
import type { Core } from "../../types";
import { createGetRuntimeEndpointHandler } from "./get";
import { createListRuntimeEndpointsHandler } from "./list";

Expand Down
3 changes: 2 additions & 1 deletion src/handlers/runtime/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { withTuiOnEmptyFlagsAndArgs } from "../../middleware";
import { Router } from "../../router";
import { renderTui } from "../../tui";
import type { AppIO, Core } from "../types";
import type { AppIO } from "../../io";
import type { Core } from "../types";
import { createRuntimeEndpointHandler } from "./endpoint";
import { createGetRuntimeHandler } from "./get";
import { createListRuntimesHandler } from "./list";
Expand Down
3 changes: 2 additions & 1 deletion src/handlers/runtime/version/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Router } from "../../../router";
import { renderTui } from "../../../tui";
import type { AppIO, Core } from "../../types";
import type { AppIO } from "../../../io";
import type { Core } from "../../types";
import { createGetRuntimeVersionHandler } from "./get";
import { createListRuntimeVersionsHandler } from "./list";

Expand Down
11 changes: 0 additions & 11 deletions src/handlers/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,6 @@ export interface Core {
projectManager: ProjectManager;
}

// AppIO is the set of standard streams the app reads from and writes to. It is
// injected at the edge (createRootHandler, from src/index.ts) and threaded down
// to the TUI renderer and handlers, so nothing reaches for the process streams
// (or console.*) directly. Production wiring passes the real process streams;
// tests pass in-memory fakes to capture output and drive input.
export interface AppIO {
stdin: NodeJS.ReadStream;
stdout: NodeJS.WriteStream;
stderr: NodeJS.WriteStream;
}

// ScreenProps is the common prop set every TUI screen receives. `ctx` carries the
// request context (resolved flags, command, path) and `core` the service clients,
// both threaded down by Root.
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import { join } from "path";
import { CoreClient } from "./core";
import { createControlClient, createDataClient, createIamClient } from "./core/factories";
import { createRootHandler } from "./handlers";
import { FsReadWriteJson } from "./io";
import { createFileLogger, LOG_LEVEL } from "./logging";
import { runWithExitCode } from "./runnable";
import { DefaultGlobalConfigAccessor, FsReadWriteJson } from "./globalConfig";
import { DefaultGlobalConfigAccessor } from "./globalConfig";

process.exit(
await runWithExitCode(async (argv: string[]) => {
Expand Down
3 changes: 3 additions & 0 deletions src/io/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { FsReadWriteJson } from "./json";
export { SourceResolutionError, SourceResolver, type SourceResolverConfig } from "./source";
export type { AppIO, ReadWriteJson } from "./types";
8 changes: 5 additions & 3 deletions src/globalConfig/json.tsx → src/io/json.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import z from "zod";
import { mkdir, readFile, writeFile } from "fs/promises";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";

import type z from "zod";

import type { Logger } from "../logging";
import type { ReadWriteJson } from "./types";
import { dirname } from "path";

type ReadWriteJsonConfig = {
logger: Logger;
Expand Down
187 changes: 187 additions & 0 deletions src/io/source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { PassThrough, Readable } from "node:stream";

import { SourceResolutionError, SourceResolver } from "./source";

const tempDirectories: string[] = [];

async function tempFile(contents: string | Uint8Array): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "agentcore-source-"));
tempDirectories.push(directory);
const path = join(directory, "source");
await writeFile(path, contents);
return path;
}

function stdin(...chunks: Uint8Array[]): NodeJS.ReadStream {
return Readable.from(chunks) as NodeJS.ReadStream;
}

afterEach(async () => {
await Promise.all(
tempDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
);
});

describe("SourceResolver bytes", () => {
test("passes undefined through", async () => {
const resolver = new SourceResolver({ stdin: stdin() });

expect(await resolver.resolveBytes("payload", undefined)).toBeUndefined();
});

test("encodes inline values as UTF-8", async () => {
const resolver = new SourceResolver({ stdin: stdin() });

expect(await resolver.resolveBytes("payload", "hello \u20ac")).toEqual(
new TextEncoder().encode("hello \u20ac"),
);
});

test("preserves arbitrary file bytes", async () => {
const bytes = Uint8Array.from([0, 255, 10, 1]);
const path = await tempFile(bytes);
const resolver = new SourceResolver({ stdin: stdin() });

expect(await resolver.resolveBytes("payload", `file://${path}`)).toEqual(bytes);
});

test("preserves arbitrary stdin bytes", async () => {
const bytes = Uint8Array.from([9, 0, 254]);
const resolver = new SourceResolver({ stdin: stdin(bytes) });

expect(await resolver.resolveBytes("payload", "-")).toEqual(bytes);
});

test("rejects a second stdin consumer and identifies both options", async () => {
const resolver = new SourceResolver({ stdin: stdin(new TextEncoder().encode("value")) });

await resolver.resolveText("payload", "-");
const resolution = resolver.resolveText("bearer-token", "-");

await expect(resolution).rejects.toBeInstanceOf(SourceResolutionError);
await expect(resolution).rejects.toThrow("'--bearer-token' conflicts with '--payload'");
});

test("claims stdin before concurrent resolutions can race", async () => {
const input = new PassThrough() as unknown as NodeJS.ReadStream;
const resolver = new SourceResolver({ stdin: input });
const first = resolver.resolveBytes("first", "-");
const second = resolver.resolveBytes("second", "-");

await expect(second).rejects.toThrow("'--second' conflicts with '--first'");
input.end("value");
expect(new TextDecoder().decode(await first)).toBe("value");
});

test("reports file failures with option and path context", async () => {
const missing = join(tmpdir(), "agentcore-source-missing", "secret-value");
const resolver = new SourceResolver({ stdin: stdin() });

const resolution = resolver.resolveBytes("payload", `file://${missing}`);
await expect(resolution).rejects.toBeInstanceOf(SourceResolutionError);
await expect(resolution).rejects.toThrow(`could not read '--payload' from file '${missing}'`);
});

test("wraps non-abort stdin failures with option context", async () => {
const input = new PassThrough() as unknown as NodeJS.ReadStream;
const resolver = new SourceResolver({ stdin: input });
const resolution = resolver.resolveBytes("payload", "-");
input.destroy(new Error("stream failed"));

await expect(resolution).rejects.toBeInstanceOf(SourceResolutionError);
await expect(resolution).rejects.toThrow("could not read '--payload' from stdin");
});
});

describe("SourceResolver text", () => {
test("passes undefined through", async () => {
const resolver = new SourceResolver({ stdin: stdin() });

expect(await resolver.resolveText("value", undefined)).toBeUndefined();
});

test("resolves inline, file, and stdin text without transforming it", async () => {
const path = await tempFile("file\nvalue");

expect(
await new SourceResolver({ stdin: stdin() }).resolveText("inline", " inline value "),
).toBe(" inline value ");
expect(await new SourceResolver({ stdin: stdin() }).resolveText("file", `file://${path}`)).toBe(
"file\nvalue",
);
expect(
await new SourceResolver({
stdin: stdin(new TextEncoder().encode("stdin\nvalue")),
}).resolveText("stdin", "-"),
).toBe("stdin\nvalue");
});

test("rejects malformed UTF-8 with option context", async () => {
const path = await tempFile(Uint8Array.from([0xff, 0x61]));
const resolver = new SourceResolver({ stdin: stdin() });
const resolution = resolver.resolveText("api-key", `file://${path}`);

await expect(resolution).rejects.toBeInstanceOf(SourceResolutionError);
await expect(resolution).rejects.toThrow("'--api-key' must contain valid UTF-8");
});
});

describe("SourceResolver cancellation", () => {
test("rejects an already-aborted inline resolution", async () => {
const controller = new AbortController();
controller.abort();
const resolver = new SourceResolver({
stdin: stdin(),
signal: controller.signal,
});
const resolution = resolver.resolveBytes("payload", "inline");

await expect(resolution).rejects.toMatchObject({ name: "AbortError" });
await expect(resolution).rejects.not.toBeInstanceOf(SourceResolutionError);
});

test("preserves AbortError from file resolution", async () => {
const path = await tempFile("payload");
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we update this test to abort after the file read starts? Aborting before resolveBytes() means throwIfAborted() exits early, so this never verifies that the signal reaches readFile().

controller.abort();
const resolver = new SourceResolver({
stdin: stdin(),
signal: controller.signal,
});
const resolution = resolver.resolveBytes("payload", `file://${path}`);

await expect(resolution).rejects.toMatchObject({ name: "AbortError" });
await expect(resolution).rejects.not.toBeInstanceOf(SourceResolutionError);
});

test("aborts while waiting for stdin and preserves AbortError", async () => {
const input = new PassThrough() as unknown as NodeJS.ReadStream;
const controller = new AbortController();
const resolver = new SourceResolver({
stdin: input,
signal: controller.signal,
});
const resolution = resolver.resolveBytes("payload", "-");

controller.abort();

try {
await expect(
Promise.race([
resolution,
Bun.sleep(100).then(() => {
throw new Error("stdin read did not abort");
}),
]),
).rejects.toMatchObject({ name: "AbortError" });
await expect(resolution).rejects.not.toBeInstanceOf(SourceResolutionError);
} finally {
input.destroy();
await resolution.catch(() => {});
}
});
});
Loading
Loading