Skip to content
Closed
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
68 changes: 68 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2341,6 +2341,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
taskId: string,
) => Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
readonly environment?: NodeJS.ProcessEnv;
readonly onSessionInit?: (cwd: string) => Effect.Effect<void>;
readonly subagentLaunchToolUseId?: string;
readonly nativeSessionId?: string;
readonly settings?: ClaudeSettings;
Expand Down Expand Up @@ -2397,6 +2398,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator,
...(options?.onSessionInit === undefined ? {} : { onSessionInit: options.onSessionInit }),
continuationRequests: {
offer: (request) =>
Effect.sync(() => {
Expand Down Expand Up @@ -3180,6 +3182,72 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);

it.effect("reports the session cwd once per query, when the CLI's first init arrives", () =>
Effect.gen(function* () {
const initCwds: Array<string> = [];
const harness = yield* makeWakeHarnessWithOptions({
onSessionInit: (cwd) =>
Effect.sync(() => {
initCwds.push(cwd);
}),
});
const now = yield* DateTime.now;
const cwd = "/synthetic/worktree";
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd,
});
const init = (uuid: string) =>
claudeSdkFrame({
type: "system",
subtype: "init",
// The CLI may report a resolved path, never the one the client keys on.
cwd: "/private/synthetic/worktree",
session_id: WAKE_NATIVE_SESSION,
uuid,
});
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-init-1"),
text: "First.",
attachments: [],
runtimePolicy,
}),
);
yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000701"));
assert.deepEqual(initCwds, [cwd]);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000702", result: "One." }),
);
yield* Queue.take(harness.terminalReceipts);

// The CLI repeats init on every turn of one process; hooks ran once.
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-init-2"),
providerTurnOrdinal: 2,
text: "Second.",
attachments: [],
runtimePolicy,
}),
);
yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000703"));
assert.deepEqual(initCwds, [cwd]);
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);

it.effect("keeps usage warnings and provisioned overage silent", () =>
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
Expand Down
25 changes: 24 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3091,6 +3091,7 @@ interface ClaudeLiveQueryContext {
readonly queryPolicyKey: string;
// The selection this process runs now. Live changes update it.
selection: CompiledClaudeModelSelection;
readonly cwd: string | null;
readonly closed: Deferred.Deferred<void, never>;
// Retained for process-exit cleanup even when its last turn failed.
lastTurn: ActiveClaudeTurnContext | null;
Expand All @@ -3111,6 +3112,7 @@ interface ClaudeLiveQueryContext {
// is gone and never reports their end; any later task_started replaces the
// entry, so an entry still in this set runs nowhere.
readonly subagentsFromEarlierProcesses: ReadonlySet<ActiveClaudeSubagent>;
sessionInitReported: boolean;
}

interface ActiveClaudeToolCall {
Expand Down Expand Up @@ -3434,6 +3436,12 @@ export interface ClaudeAdapterV2Options {
readonly queryRunner: ClaudeAgentSdkQueryRunnerShape;
readonly scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>;
readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"];
/**
* Called with the query's cwd when its CLI process first reports `init`,
* which comes after SessionStart hooks have run. Once per query: the CLI
* repeats `init` on every turn.
*/
readonly onSessionInit?: (cwd: string) => Effect.Effect<void>;
/** Sink for wake-turn continuation requests; defaults to dropping them. */
readonly continuationRequests?: {
readonly offer: (
Expand Down Expand Up @@ -6729,6 +6737,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
}

const message = input.message;
if (
message.type === "system" &&
message.subtype === "init" &&
!liveQuery.sessionInitReported
) {
liveQuery.sessionInitReported = true;
if (liveQuery.cwd !== null && adapterOptions.onSessionInit) {
yield* adapterOptions.onSessionInit(liveQuery.cwd);
}
}
// Before any routing: a Monitor started during an idle wake turn
// reports its task before the drain replays the tool call.
yield* trackClaudeMonitorCalls(message);
Expand Down Expand Up @@ -8571,6 +8589,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
query: querySession,
queryPolicyKey,
selection: compiledSelection,
cwd: turnInput.runtimePolicy.cwd,
closed,
lastTurn: null,
promptEchoMode: "unknown",
Expand All @@ -8582,6 +8601,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
(subagent) => subagent.task.status === "running",
),
),
sessionInitReported: false,
};
yield* Ref.set(queryContext, context);
yield* querySession.messages.pipe(
Expand Down Expand Up @@ -9474,7 +9494,10 @@ export type ClaudeAdapterV2DriverEnv =
export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")(
function* (
input: ProviderAdapterDriverCreateInput<ClaudeSettings>,
hooks: Pick<ClaudeAdapterV2Options, "scopedLimitNames" | "onUsageLimits"> = {},
hooks: Pick<
ClaudeAdapterV2Options,
"scopedLimitNames" | "onUsageLimits" | "onSessionInit"
> = {},
) {
const { instanceId, environment, enabled, config } = input;
const fileSystem = yield* FileSystem.FileSystem;
Expand Down
15 changes: 14 additions & 1 deletion apps/server/src/provider/Drivers/ClaudeDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@
*/
import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import type * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/http";
import { ChildProcessSpawner } from "effect/process";

Expand Down Expand Up @@ -174,6 +177,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
});

const scopedLimitNames = yield* makeClaudeScopedLimitNames;
// Sessions report here once their startup hooks have run; the registry
// listens and rescans the cwd. A queue keeps a report made before the
// registry subscribes, and ending it with the instance ends the listener.
const workspaceRescans = yield* Queue.unbounded<string, Cause.Done>();
yield* Effect.addFinalizer(() => Queue.end(workspaceRescans));
const orchestrationAdapter = yield* createClaudeAdapterV2(
{
instanceId,
Expand All @@ -183,7 +191,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
enabled,
config,
},
{ scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
{
scopedLimitNames,
onUsageLimits: (update) => snapshot.applyUsageLimits(update),
onSessionInit: (cwd) => Queue.offer(workspaceRescans, cwd).pipe(Effect.asVoid),
},
).pipe(
Effect.mapError(
(cause) =>
Expand Down Expand Up @@ -362,6 +374,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
enabled,
snapshot,
invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
workspaceRescans: Stream.fromQueue(workspaceRescans),
snapshotForCwd: (cwd: string) =>
snapshot.getSnapshot.pipe(
Effect.flatMap((machineSnapshot) =>
Expand Down
Loading
Loading