Skip to content

Commit dfe8ca3

Browse files
fix(server): recover Claude subagents from instance home
1 parent e7f4825 commit dfe8ca3

2 files changed

Lines changed: 88 additions & 14 deletions

File tree

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
1-
import { forkSession, getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
1+
import {
2+
forkSession,
3+
getSessionMessages,
4+
getSubagentMessages,
5+
} from "@anthropic-ai/claude-agent-sdk";
26
import * as Schema from "effect/Schema";
37

48
// Nothing here may run on import: inside the executable `import.meta.main` is
59
// true for the whole bundle.
610
const decodeHistoryOptions = Schema.decodeSync(
711
Schema.fromJsonString(
812
Schema.Struct({
13+
agentId: Schema.optionalKey(Schema.String),
914
dir: Schema.optionalKey(Schema.String),
15+
limit: Schema.optionalKey(Schema.Number),
1016
includeSystemMessages: Schema.optionalKey(Schema.Boolean),
1117
upToMessageId: Schema.optionalKey(Schema.String),
1218
}),
@@ -18,15 +24,17 @@ export async function runClaudeHistoryWorker(
1824
sessionId: string | undefined,
1925
rawOptions: string | undefined,
2026
): Promise<void> {
21-
const options = decodeHistoryOptions(rawOptions ?? "{}");
27+
const { agentId, ...options } = decodeHistoryOptions(rawOptions ?? "{}");
2228
if (!sessionId) throw new Error("Claude history session id is required.");
2329
const result =
2430
method === "getSessionMessages"
2531
? await getSessionMessages(sessionId, options)
2632
: method === "forkSession"
2733
? await forkSession(sessionId, options)
28-
: (() => {
29-
throw new Error("Unknown Claude history operation.");
30-
})();
34+
: method === "getSubagentMessages" && agentId
35+
? await getSubagentMessages(sessionId, agentId, options)
36+
: (() => {
37+
throw new Error("Unknown Claude history operation.");
38+
})();
3139
process.stdout.write(JSON.stringify(result));
3240
}

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 75 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ import * as Ref from "effect/Ref";
110110
import * as Schema from "effect/Schema";
111111
import * as Semaphore from "effect/Semaphore";
112112
import * as Stream from "effect/Stream";
113+
import * as ChildProcess from "effect/process/ChildProcess";
114+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
113115

114116
import { resolveAttachmentPath } from "../../attachmentStore.ts";
115117
import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
@@ -145,6 +147,7 @@ import {
145147
} from "../../provider/claudeUsageLimits.ts";
146148
import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
147149
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
150+
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
148151
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "@t3tools/provider-core/server/orchestrationInstructions";
149152
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
150153
import {
@@ -517,6 +520,7 @@ export interface ClaudeAgentSdkSubagentLookupInput {
517520
readonly dir: string | null;
518521
readonly threadId: ThreadId;
519522
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
523+
readonly environment?: NodeJS.ProcessEnv;
520524
}
521525

522526
const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
@@ -533,6 +537,13 @@ function queryRunnerError(cause: unknown, method: string): ClaudeAgentSdkQueryRu
533537
: new ClaudeAgentSdkQueryRunnerError({ cause, method });
534538
}
535539

540+
const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
541+
const decodeClaudeSubagentMessages = Schema.decodeUnknownEffect(
542+
Schema.fromJsonString(
543+
Schema.Array(Schema.Struct({ parent_tool_use_id: Schema.NullOr(Schema.String) })),
544+
),
545+
);
546+
536547
function closeClaudeQuery(queryRuntime: ClaudeQuery) {
537548
return Effect.try({
538549
try: () => queryRuntime.close(),
@@ -743,15 +754,76 @@ export function makeClaudeAgentSdkProtocolLogger(input: {
743754
export const layerQueryRunner: Layer.Layer<
744755
ClaudeAgentSdkQueryRunner,
745756
never,
746-
Crypto.Crypto | ProviderEventLoggers.ProviderEventLoggers
757+
| ChildProcessSpawner.ChildProcessSpawner
758+
| Crypto.Crypto
759+
| Path.Path
760+
| ProviderEventLoggers.ProviderEventLoggers
747761
> = Layer.effect(
748762
ClaudeAgentSdkQueryRunner,
749763
Effect.gen(function* () {
750764
const crypto = yield* Crypto.Crypto;
765+
const path = yield* Path.Path;
766+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
751767
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
752768
const agentScope = yield* AgentScope;
753769
const platform = yield* HostProcess.Platform;
754770

771+
const readSubagentMessages = Effect.fn("ClaudeAgentSdkQueryRunner.readSubagentMessages")(
772+
function* (input: ClaudeAgentSdkSubagentLookupInput) {
773+
const options = { ...(input.dir === null ? {} : { dir: input.dir }), limit: 1 };
774+
const hostEnvironment = yield* HostProcess.Environment;
775+
if (
776+
input.environment === undefined ||
777+
input.environment.CLAUDE_CONFIG_DIR === hostEnvironment.CLAUDE_CONFIG_DIR
778+
) {
779+
return yield* Effect.tryPromise(() =>
780+
getSubagentMessages(input.sessionId, input.agentId, options),
781+
);
782+
}
783+
784+
// SDK history reads process.env. Isolate the instance home in the existing worker.
785+
const executablePath = yield* HostProcess.ExecutablePath;
786+
const workerArguments = (yield* HostProcess.IsExecutable)
787+
? ["__claude-history"]
788+
: [
789+
yield* path.fromFileUrl(
790+
new URL(
791+
import.meta.url.endsWith(".ts")
792+
? "../../claude-history-worker.ts"
793+
: "./claude-history-worker.mjs",
794+
import.meta.url,
795+
),
796+
),
797+
];
798+
const result = yield* spawnAndCollect(
799+
executablePath,
800+
ChildProcess.make(
801+
executablePath,
802+
[
803+
...workerArguments,
804+
"getSubagentMessages",
805+
input.sessionId,
806+
encodeClaudeHistoryOptions({ ...options, agentId: input.agentId }),
807+
],
808+
{ env: { ...input.environment, ELECTRON_RUN_AS_NODE: "1" } },
809+
),
810+
).pipe(
811+
Effect.timeout("30 seconds"),
812+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
813+
);
814+
if (result.code !== 0) {
815+
return yield* new ClaudeAgentSdkQueryRunnerError({
816+
method: "getSubagentMessages",
817+
cause:
818+
result.stderr.trim() ||
819+
new Error(`Claude history worker exited with ${result.code}.`),
820+
});
821+
}
822+
return yield* decodeClaudeSubagentMessages(result.stdout);
823+
},
824+
Effect.mapError((cause) => queryRunnerError(cause, "getSubagentMessages")),
825+
);
826+
755827
return ClaudeAgentSdkQueryRunner.of({
756828
allocateSessionId: crypto
757829
.randomUUIDv4()
@@ -1046,14 +1118,7 @@ export const layerQueryRunner: Layer.Layer<
10461118
agentId: input.agentId,
10471119
},
10481120
});
1049-
const messages = yield* Effect.tryPromise({
1050-
try: () =>
1051-
getSubagentMessages(input.sessionId, input.agentId, {
1052-
...(input.dir === null ? {} : { dir: input.dir }),
1053-
limit: 1,
1054-
}),
1055-
catch: (cause) => queryRunnerError(cause, "getSubagentMessages"),
1056-
});
1121+
const messages = yield* readSubagentMessages(input);
10571122
const toolUseId = messages[0]?.parent_tool_use_id ?? null;
10581123
yield* logProtocolEvent({
10591124
direction: "incoming",
@@ -4484,6 +4549,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
44844549
dir: resume.context.input.runtimePolicy.cwd,
44854550
threadId: resume.context.input.threadId,
44864551
providerSessionId: input.providerSessionId,
4552+
environment: adapterOptions.environment,
44874553
})
44884554
.pipe(
44894555
Effect.catch(() =>

0 commit comments

Comments
 (0)