Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
d3c1fe7
feat(dev): collect local OTEL traces in project dev
tejaskash Aug 12, 2026
9494d7e
refactor(dev): drop unused collector server injection seam
tejaskash Aug 12, 2026
2e142b4
fix(dev): name aws-opentelemetry-distro in the missing-instrumentatio…
tejaskash Aug 12, 2026
881af19
fix(dev): address trace-identity, env-precedence, and Windows review …
tejaskash Aug 14, 2026
aabb87f
fix(ci): dedupe @opentelemetry/core past audit advisory; join paths i…
tejaskash Aug 17, 2026
b4c86d4
refactor(dev): split inspector presentation from raw OTLP storage; st…
tejaskash Aug 17, 2026
61fcf4d
feat(dev): add DevSupervisor for lazy multi-agent lifecycle
tejaskash Aug 17, 2026
2fb9a94
feat(dev): ship the Agent Inspector SPA through the asset pipeline
tejaskash Aug 17, 2026
6277145
fix(build): stage inspector SPA files with a neutral suffix for compile
tejaskash Aug 17, 2026
5bd135b
feat(io): add best-effort default-browser opener
tejaskash Aug 17, 2026
8493669
feat(dev): add the Agent Inspector HTTP server
tejaskash Aug 17, 2026
5918df3
feat(project): open the Agent Inspector from project dev by default
tejaskash Aug 17, 2026
db84811
refactor(dev): drop unread per-agent controller field
tejaskash Aug 17, 2026
4a0fa06
feat(dev): reload agents on agentcore.json edits; request-path effici…
tejaskash Aug 17, 2026
56c7345
refactor(dev): drop the Inspector's unwired AWS-backed routes
tejaskash Aug 17, 2026
937d318
refactor(dev): drop the Inspector's unreferenced wire-type module
tejaskash Aug 18, 2026
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
1 change: 1 addition & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,3 +35,4 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
.DS_Store

.agentreview
src/assets/agent-inspector/
821 changes: 818 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,8 +56,10 @@
"@aws-sdk/client-bedrock-agentcore-control": "^3.1102.0",
"@aws-sdk/client-cloudwatch-logs": "^3.1092.0",
"@aws-sdk/client-iam": "^3.1080.0",
"@aws/agent-inspector": "0.6.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
"@opentelemetry/otlp-transformer": "0.213.0",
"@opentelemetry/resources": "^2.10.0",
"@opentelemetry/sdk-metrics": "^2.10.0",
"@smithy/core": "3.29.3",
Expand All@@ -75,5 +77,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
25 changes: 25 additions & 0 deletions scripts/build.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,6 +21,29 @@ function discoverAssets(): string[] {
return files.sort().map((relativePath) => join(ASSETS_DIR, relativePath));
}

/**
* Stage the prebuilt Agent Inspector SPA into the asset tree (gitignored) so
* both distribution paths ship it through the ordinary asset machinery:
* `bundle` mirrors it into dist/assets/, `compile` embeds it in the binary.
* Every file gains a neutral `.asset` suffix — compile passes assets as
* Bun.build entrypoints, and a bare .html entrypoint would be bundled through
* Bun's HTML-imports pipeline instead of embedded verbatim. InspectorAssets
* strips the suffix when reading.
*/
async function stageInspectorAssets(): Promise<void> {
const source = join(REPO_ROOT, "node_modules", "@aws", "agent-inspector", "dist-assets");
if (!(await Bun.file(join(source, "index.html")).exists())) {
throw new Error("@aws/agent-inspector is not installed — run `bun install` before building.");
}
const target = join(ASSETS_DIR, "agent-inspector");
await $`rm -rf ${target}`;
await $`mkdir -p ${target}`;
const files = [...new Bun.Glob("**/*").scanSync({ cwd: source, onlyFiles: true })];
for (const file of files) {
await $`cp ${join(source, file)} ${join(target, `${file}.asset`)}`;
}
}

/** Force asset files through the file loader so template .ts/.js are embedded as bytes, not compiled. */
function assetLoaderPlugin(): Bun.BunPlugin {
return {
Expand DownExpand Up@@ -49,6 +72,7 @@ async function assertAssetsAreText(assets: string[]): Promise<void> {
// Bun.build rejects with an AggregateError on failure (throw defaults to true),
// so build errors propagate to runWithExitCode like any other.
async function bundle(): Promise<void> {
await stageInspectorAssets();
await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: DIST,
Expand All@@ -64,6 +88,7 @@ async function bundle(): Promise<void> {
}

async function compile(target: string): Promise<void> {
await stageInspectorAssets();
const assets = discoverAssets();
await assertAssetsAreText(assets);

Expand Down
6 changes: 5 additions & 1 deletion src/assets/templates/shared/env.local.template
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
# Environment variables for local development.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
# CLI owns. While trace collection is on (the default), the CLI also owns the
# OTEL_* and AGENT_OBSERVABILITY_ENABLED variables so traces reach its local
# collector — pass --no-traces (or set instrumentation.enableOtel to false in
# agentcore.json) to disable collection and set your own.
# This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
81 changes: 77 additions & 4 deletions src/core/dev/codezip.test.ts
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { delimiter, join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
import type { ProcessEvent, ProcessRunner, ProcessStreamer, StreamProcessOptions } from "../../io";
import { CodeZipDevRunner } from "./codezip";

type ProcessCall = {
Expand DownExpand Up@@ -54,15 +54,22 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

function harness(output: ProcessEvent[] = []) {
function harness(output: ProcessEvent[] = [], probe: { dir?: string; fail?: boolean } = {}) {
const calls: ProcessCall[] = [];
const probeCalls: string[][] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
yield* output;
};
const fakeRunProcess: ProcessRunner = async (command, options) => {
probeCalls.push(command);
if (probe.fail) throw new Error("probe failed");
options.onOutput?.(`${probe.dir ?? ""}\n`);
};
return {
calls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess }),
probeCalls,
runner: new CodeZipDevRunner({ streamProcess: fakeStreamProcess, runProcess: fakeRunProcess }),
};
}

Expand DownExpand Up@@ -193,3 +200,69 @@ describe("CodeZipDevRunner", () => {
]);
});
});

describe("CodeZipDevRunner OTEL instrumentation", () => {
async function sitecustomizeDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), "otel-site-"));
tempDirectories.push(directory);
await writeFile(join(directory, "sitecustomize.py"), "");
return directory;
}

function otelInput(root: string, extraEnv: Record<string, string> = {}): DevServerInput {
const base = input(root, runtime());
return {
...base,
env: { ...base.env, OTEL_EXPORTER_OTLP_ENDPOINT: "http://127.0.0.1:4318", ...extraEnv },
};
}

test("prepends the sitecustomize directory to PYTHONPATH when instrumentation is installed", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, probeCalls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root)));

expect(probeCalls[0]?.slice(0, 4)).toEqual(["uv", "run", "python", "-c"]);
expect(calls[0]?.options.env?.PYTHONPATH).toBe(directory);
});

test("preserves an existing PYTHONPATH", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], { dir: directory });

await collect(runner.run(otelInput(root, { PYTHONPATH: "/existing" })));

expect(calls[0]?.options.env?.PYTHONPATH).toBe(`${directory}${delimiter}/existing`);
});

test("does not probe without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { probeCalls, runner } = harness();

await collect(runner.run(input(root, runtime())));
await collect(runner.run({ ...otelInput(root), runtime: runtime({ entrypoint: "index.js" }) }));

expect(probeCalls).toEqual([]);
});

test.each([
["probe failure", { fail: true }],
["missing sitecustomize.py", { dir: "/nonexistent" }],
] as const)("warns and starts untraced on %s", async (_case, probe) => {
const root = await projectRoot();
const { calls, probeCalls, runner } = harness([], probe);

const events = await collect(runner.run(otelInput(root)));

expect(probeCalls).toHaveLength(1);
expect(calls).toHaveLength(1);
expect(calls[0]?.options.env?.PYTHONPATH).toBeUndefined();
expect(events).toContainEqual({
type: "status",
message: expect.stringContaining("traces will not be collected"),
});
});
});
53 changes: 51 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";
import { delimiter, join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import {
runProcess,
streamProcess,
type ProcessRunner,
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
runProcess?: ProcessRunner;
};

export class CodeZipDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly runProcess: ProcessRunner;

constructor(config: CodeZipDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.runProcess = config.runProcess ?? runProcess;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand DownExpand Up@@ -41,8 +50,48 @@ export class CodeZipDevRunner implements DevRunner {

yield { type: "status", message: "Starting development server" };
const serverProcess = commandForRuntime(entrypoint!, directory, input);
if (entrypoint!.endsWith(".py") && input.env?.OTEL_EXPORTER_OTLP_ENDPOINT) {
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory);
if (sitecustomizeDir) {
const existing = serverProcess.options.env?.PYTHONPATH;
serverProcess.options.env = {
...serverProcess.options.env,
PYTHONPATH: existing ? `${sitecustomizeDir}${delimiter}${existing}` : sitecustomizeDir,
};
} else {
yield {
type: "status",
message:
"OTEL auto-instrumentation is not installed in the agent environment; traces will not be collected. Add aws-opentelemetry-distro to the agent's dependencies to enable them.",
};
}
}
yield* this.streamProcess(serverProcess.command, serverProcess.options);
}

/**
* Locate the auto-instrumentation sitecustomize.py directory inside the agent's
* uv environment. Prepending it to PYTHONPATH instruments every Python process —
* an `opentelemetry-instrument` wrapper would only instrument uvicorn's reloader
* parent, leaving the re-spawned worker processes untraced.
*/
private async findOtelSitecustomizeDir(directory: string): Promise<string | undefined> {
const output: string[] = [];
const probe =
"import opentelemetry.instrumentation.auto_instrumentation as m; import os; print(os.path.dirname(m.__file__))";
try {
await this.runProcess(["uv", "run", "python", "-c", probe], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
});
} catch {
return undefined;
}
const sitecustomizeDir = output.join("").trim().split("\n").at(-1)?.trim();
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
Loading
Loading