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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
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;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} 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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } 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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions bun.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,7 @@
"@aws-sdk/client-iam": "^3.1080.0",
"@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 +76,8 @@
"winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0",
"zod": "^4.4.3"
},
"overrides": {
"@opentelemetry/core": "^2.10.0"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,4 +34,6 @@ USER bedrock_agentcore
# 9000: A2A Mode
EXPOSE 8080 8000 9000

CMD ["python", "-m", "main"]
# opentelemetry-instrument (from aws-opentelemetry-distro) starts a real
# TracerProvider; plain `python -m main` would export nothing.
CMD ["opentelemetry-instrument", "python", "-m", "main"]
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=...
98 changes: 94 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,26 @@ async function projectRoot(withNodeModules = false): Promise<string> {
return root;
}

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

Expand DownExpand Up@@ -193,3 +204,82 @@ 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, discoverCalls, runner } = harness([], { dir: directory });

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

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

test("reads the marked path even when uv writes progress to the merged output", async () => {
const root = await projectRoot();
const directory = await sitecustomizeDir();
const { calls, runner } = harness([], {
dir: directory,
noise: ["Resolved 12 packages", "Installed 12 packages"],
});

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

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 run discovery without an OTEL endpoint or for Node entrypoints", async () => {
const root = await projectRoot(true);
const { discoverCalls, runner } = harness();

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

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

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

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

expect(discoverCalls).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"),
});
});
});
65 changes: 63 additions & 2 deletions src/core/dev/codezip.ts
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
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;
};

const SITECUSTOMIZE_MARKER = "AGENTCORE_OTEL_SITECUSTOMIZE=";

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 +52,58 @@ 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) {
Comment thread
tejaskash marked this conversation as resolved.
const sitecustomizeDir = await this.findOtelSitecustomizeDir(directory, input.signal);
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,
signal: AbortSignal,
): Promise<string | undefined> {
const output: string[] = [];
// uv writes sync progress to stderr, which merges into onOutput, so the path
// is printed behind a marker and read from that line rather than the last one.
const script = `import opentelemetry.instrumentation.auto_instrumentation as m, os; print("${SITECUSTOMIZE_MARKER}" + os.path.dirname(m.__file__))`;
try {
await this.runProcess(["uv", "run", "python", "-c", script], {
cwd: directory,
onOutput: (chunk) => output.push(chunk),
signal,
});
} catch {
return undefined;
}
const marked = output
.join("")
.split("\n")
.map((line) => line.trim())
.find((line) => line.startsWith(SITECUSTOMIZE_MARKER));
const sitecustomizeDir = marked?.slice(SITECUSTOMIZE_MARKER.length);
if (!sitecustomizeDir || !existsSync(join(sitecustomizeDir, "sitecustomize.py")))
return undefined;
return sitecustomizeDir;
}
}

function commandForRuntime(
Expand Down
2 changes: 2 additions & 0 deletions src/core/dev/container.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -207,6 +207,8 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"--add-host",
"host.docker.internal:host-gateway",
"--env-file",
run.envFile!.path,
imageTag(root),
Expand Down
5 changes: 5 additions & 0 deletions src/core/dev/container.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,6 +183,11 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
// Docker Engine on Linux does not define host.docker.internal (Desktop,
// Podman, and Finch do); the mapping makes the OTLP endpoint rewrite
// resolve everywhere and is harmless where the name already exists.
"--add-host",
Comment thread
tejaskash marked this conversation as resolved.
"host.docker.internal:host-gateway",
Comment thread
tejaskash marked this conversation as resolved.
...awsMount,
"--env-file",
envFile,
Expand Down
Loading
Loading