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
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ describe("RPC authorization scopes", () => {
WS_METHODS.terminalClear,
WS_METHODS.terminalRestart,
WS_METHODS.terminalClose,
WS_METHODS.previewStopLocalServer,
]) {
expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
}
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.previewClearProfile]: AuthPreviewOperateScope,
[WS_METHODS.previewReportProfiles]: AuthPreviewOperateScope,
[WS_METHODS.previewReportStatus]: AuthPreviewOperateScope,
[WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope,
[WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
[WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ export const make = Effect.gen(function* () {
threadPullRequestLinking: true,
serverResolvedCommandContext: true,
threadStop: true,
...(hostPlatform === "win32" ? {} : { localServerStop: true }),
environmentIcon: true,
projectCloneTracking: true,
ignoredFileListing: true,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/observability/RpcInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.previewReportStatus]: "preview",
[WS_METHODS.subscribePreviewEvents]: "preview",
[WS_METHODS.subscribeDiscoveredLocalServers]: "preview",
[WS_METHODS.previewStopLocalServer]: "preview",
[WS_METHODS.deviceConfigure]: "device",
[WS_METHODS.deviceTestHost]: "device",
[WS_METHODS.deviceEasAccount]: "device",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";

import * as PortScanner from "../../preview/PortScanner.ts";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { WorkflowAgentTranscriptReadObserver } from "../workflowAgentTranscript.ts";
import * as ServerConfig from "../../config.ts";
Expand Down Expand Up @@ -2271,7 +2272,7 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
},
});
}).pipe(
Effect.provide(ClaudeAdapterV2.layerQueryRunner),
Effect.provide(ClaudeAdapterV2.layerQueryRunner.pipe(Layer.provide(PortScanner.layerTest))),
Effect.provideService(ProviderEventLoggers.ProviderEventLoggers, {
...ProviderEventLoggers.NoOpProviderEventLoggers,
native,
Expand Down
18 changes: 17 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ import {
type CompiledClaudeModelSelection,
} from "../../claudeModelOptions.ts";
import * as ServerConfig from "../../config.ts";
import * as PortScanner from "../../preview/PortScanner.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
Expand Down Expand Up @@ -902,6 +903,7 @@ export const layerQueryRunner: Layer.Layer<
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| Path.Path
| PortScanner.PortDiscovery
| ProviderEventLoggers.ProviderEventLoggers
> = Layer.effect(
ClaudeAgentSdkQueryRunner,
Expand All @@ -913,6 +915,8 @@ export const layerQueryRunner: Layer.Layer<
const agentScope = yield* AgentScope;
const platform = yield* HostProcess.Platform;
const runFork = Effect.runForkWith(yield* Effect.context<never>());
const hostEnvironment = yield* HostProcess.Environment;
const portDiscovery = yield* PortScanner.PortDiscovery;

return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: crypto
Expand All @@ -936,7 +940,15 @@ export const layerQueryRunner: Layer.Layer<
Stream.toAsyncIterable,
);
// Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
const { mcpServers, ...queryOptions } = input.options;
const { mcpServers, ...sdkOptions } = input.options;
// Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
const queryOptions = {
...sdkOptions,
env: {
...(sdkOptions.env ?? hostEnvironment),
[PortScanner.AGENT_THREAD_ENV]: input.threadId,
},
};
// The SDK can prepend a scope wrapper to native binaries; script entries run through node.
const binaryPath = queryOptions.pathToClaudeCodeExecutable;
const launch =
Expand Down Expand Up @@ -983,6 +995,10 @@ export const layerQueryRunner: Layer.Layer<
const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
const child = spawnProcess(spawnOptions);
spawnedProcess = child;
// A spawn that fails emits only "error".
const releaseAgent = portDiscovery.trackAgent();
child.once("exit", releaseAgent);
child.on("error", releaseAgent);
processExited = child.exitCode !== null || child.signalCode != null;
processExit = new Promise<void>((resolve) => {
if (processExited) resolve();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { AgentScope } from "@t3tools/shared/AgentScope";
import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
import * as PortScanner from "../../preview/PortScanner.ts";
import {
ClaudeAgentSdkQueryRunner,
type ClaudeAgentSdkQueryOpenInput,
Expand Down Expand Up @@ -66,6 +67,7 @@ const writeClaudeSession = Effect.fnUntraced(function* (configDir: string) {
});

const forkRunnerLayer = layerQueryRunner.pipe(
Layer.provide(PortScanner.layerTest),
Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })),
);

Expand Down Expand Up @@ -110,6 +112,7 @@ it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", (
).pipe(Effect.provide(NodeServices.layer)),
);
const realQueryRunner = layerQueryRunner.pipe(
Layer.provide(PortScanner.layerTest),
Layer.provide(
Layer.succeed(ProviderEventLoggers, {
native: undefined,
Expand Down Expand Up @@ -487,4 +490,54 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
yield* Effect.promise(() => turnStopped);
}),
);

it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => {
let runningAgents = 0;
let releaseAgent!: () => void;
const agentReleased = new Promise<void>((resolve) => (releaseAgent = resolve));
const runner = layerQueryRunner.pipe(
Layer.provide(
Layer.mock(PortScanner.PortDiscovery)({
trackAgent: () => {
runningAgents += 1;
return () => {
runningAgents -= 1;
releaseAgent();
};
},
}),
),
Layer.provide(
Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
const cli = fakeClaudeCli(
[
'dir=$(dirname "$0")',
`printf '%s' "$${PortScanner.AGENT_THREAD_ENV}" > "$dir/thread"`,
"cat > /dev/null",
].join("\n"),
);
const dir = NodePath.dirname(cli);
NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "thread")]);
yield* Effect.addFinalizer(() =>
Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
);
const threadRead = new Promise<string>((resolve) => {
let thread = "";
NodeFS.createReadStream(NodePath.join(dir, "thread"), "utf8")
.on("data", (chunk) => (thread += chunk))
.once("end", () => resolve(thread));
});

const session = yield* openFakeCli(cli);
assert.equal(yield* Effect.promise(() => threadRead), "thread-fake-cli");
assert.equal(runningAgents, 1);
yield* session.close;
yield* Effect.promise(() => agentReleased);
assert.equal(runningAgents, 0);
}).pipe(Effect.provide(runner));
});
});
Loading
Loading