GeezerVison is showing github.com — fix(server): resumed Claude subagents are found on instances with their own home by coderdevang · Pull Request #17596 · pingdotgg/t3code
fix(server): resumed Claude subagents are found on instances with their own home
#17596
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(4)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
@@ -1,12 +1,18 @@
import { forkSession, getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
import {
forkSession,
getSessionMessages,
getSubagentMessages,
} from "@anthropic-ai/claude-agent-sdk";
import * as Schema from "effect/Schema";
// Nothing here may run on import: inside the executable `import.meta.main` is
// true for the whole bundle.
const decodeHistoryOptions = Schema.decodeSync(
Schema.fromJsonString(
Schema.Struct({
agentId: Schema.optionalKey(Schema.String),
dir: Schema.optionalKey(Schema.String),
limit: Schema.optionalKey(Schema.Number),
includeSystemMessages: Schema.optionalKey(Schema.Boolean),
upToMessageId: Schema.optionalKey(Schema.String),
}),
Expand All
@@ -18,15 +24,17 @@ export async function runClaudeHistoryWorker(
sessionId: string | undefined,
rawOptions: string | undefined,
): Promise<void> {
const options = decodeHistoryOptions(rawOptions ?? "{}");
const { agentId, ... options } = decodeHistoryOptions(rawOptions ?? "{}");
if (!sessionId) throw new Error("Claude history session id is required.");
const result =
method === "getSessionMessages"
? await getSessionMessages(sessionId, options)
: method === "forkSession"
? await forkSession(sessionId, options)
: (() => {
throw new Error("Unknown Claude history operation.");
})();
: method === "getSubagentMessages" && agentId
? await getSubagentMessages(sessionId, agentId, options)
: (() => {
throw new Error("Unknown Claude history operation.");
})();
process.stdout.write(JSON.stringify(result));
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2560,7 +2560,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
};
}),
forkSession: () => Effect.die("unused forkSession"),
subagentLaunchToolUseId: () => Effect.succeed(options?.subagentLaunchToolUseId ?? null),
subagentLaunchToolUseId: (input) =>
Effect.succeed(
input.environment?.CLAUDE_CONFIG_DIR === options?.environment?.CLAUDE_CONFIG_DIR
? (options?.subagentLaunchToolUseId ?? null)
: null,
),
assertComplete: Effect.void,
},
});
Expand Down
Expand Up
@@ -13039,7 +13044,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
it.effect("projects workflow member threads after resuming a restarted session ", () =>
it.effect("recovers workflow member output from the instance home after restart ", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWorkflowHarnessWithOptions({
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -110,6 +110,8 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
Expand Down
Expand Up
@@ -145,6 +147,7 @@ import {
} from "../../provider/claudeUsageLimits.ts";
import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "@t3tools/provider-core/server/orchestrationInstructions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import {
Expand Down
Expand Up
@@ -517,6 +520,7 @@ export interface ClaudeAgentSdkSubagentLookupInput {
readonly dir: string | null;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
readonly environment?: NodeJS.ProcessEnv;
}
const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
Expand All
@@ -533,6 +537,13 @@ function queryRunnerError(cause: unknown, method: string): ClaudeAgentSdkQueryRu
: new ClaudeAgentSdkQueryRunnerError({ cause, method });
}
const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const decodeClaudeSubagentMessages = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Array(Schema.Struct({ parent_tool_use_id: Schema.NullOr(Schema.String) })),
),
);
function closeClaudeQuery(queryRuntime: ClaudeQuery) {
return Effect.try({
try: () => queryRuntime.close(),
Expand Down
Expand Up
@@ -743,15 +754,76 @@ export function makeClaudeAgentSdkProtocolLogger(input: {
export const layerQueryRunner: Layer.Layer<
ClaudeAgentSdkQueryRunner,
never,
Crypto.Crypto | ProviderEventLoggers.ProviderEventLoggers
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers
> = Layer.effect(
ClaudeAgentSdkQueryRunner,
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
const agentScope = yield* AgentScope;
const platform = yield* HostProcess.Platform;
const readSubagentMessages = Effect.fn("ClaudeAgentSdkQueryRunner.readSubagentMessages")(
function* (input: ClaudeAgentSdkSubagentLookupInput) {
const options = { ...(input.dir === null ? {} : { dir: input.dir }), limit: 1 };
const hostEnvironment = yield* HostProcess.Environment;
if (
input.environment === undefined ||
input.environment.CLAUDE_CONFIG_DIR === hostEnvironment.CLAUDE_CONFIG_DIR
) {
return yield* Effect.tryPromise(() =>
getSubagentMessages(input.sessionId, input.agentId, options),
);
}
// SDK history reads process.env. Isolate the instance home in the existing worker.
const executablePath = yield* HostProcess.ExecutablePath;
const workerArguments = (yield* HostProcess.IsExecutable)
? ["__claude-history"]
: [
yield* path.fromFileUrl(
new URL(
import.meta.url.endsWith(".ts")
? "../../claude-history-worker.ts"
: "./claude-history-worker.mjs",
import.meta.url,
),
),
];
const result = yield* spawnAndCollect(
executablePath,
ChildProcess.make(
executablePath,
[
...workerArguments,
"getSubagentMessages",
input.sessionId,
encodeClaudeHistoryOptions({ ...options, agentId: input.agentId }),
],
{ env: { ...input.environment, ELECTRON_RUN_AS_NODE: "1" } },
),
).pipe(
Effect.timeout("30 seconds"),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
if (result.code !== 0) {
return yield* new ClaudeAgentSdkQueryRunnerError({
method: "getSubagentMessages",
cause:
result.stderr.trim() ||
new Error(`Claude history worker exited with ${result.code}.`),
});
}
return yield* decodeClaudeSubagentMessages(result.stdout);
},
Effect.mapError((cause) => queryRunnerError(cause, "getSubagentMessages")),
);
return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: crypto
.randomUUIDv4()
Expand Down
Expand Up
@@ -1046,14 +1118,7 @@ export const layerQueryRunner: Layer.Layer<
agentId: input.agentId,
},
});
const messages = yield* Effect.tryPromise({
try: () =>
getSubagentMessages(input.sessionId, input.agentId, {
...(input.dir === null ? {} : { dir: input.dir }),
limit: 1,
}),
catch: (cause) => queryRunnerError(cause, "getSubagentMessages"),
});
const messages = yield* readSubagentMessages(input);
const toolUseId = messages[0]?.parent_tool_use_id ?? null;
yield* logProtocolEvent({
direction: "incoming",
Expand Down
Expand Up
@@ -4484,6 +4549,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
dir: resume.context.input.runtimePolicy.cwd,
threadId: resume.context.input.threadId,
providerSessionId: input.providerSessionId,
environment: adapterOptions.environment,
})
.pipe(
Effect.catch(() =>
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -7,9 +7,12 @@ import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import { vi } from "vite-plus/test";
import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
Expand Down
Expand Up
@@ -95,6 +98,66 @@ const realQueryRunner = layerQueryRunner.pipe(
Layer.provide(NodeServices.layer),
);
it.live("finds a subagent launch in the instance Claude home", () =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-subagent-home-" });
const workspace = yield* fs.realPath(root);
const claudeHome = path.join(root, "claude");
const sessionId = yield* crypto.randomUUIDv4();
const agentId = "a0123456789abcdef";
const projectDir = path.join(claudeHome, "projects", workspace.replace(/[^a-zA-Z0-9]/g, "-"));
const subagentsDir = path.join(projectDir, sessionId, "subagents");
const entry = {
type: "user",
parentUuid: null,
sessionId,
cwd: workspace,
timestamp: "2026-01-01T00:00:00.000Z",
};
yield* fs.makeDirectory(subagentsDir, { recursive: true });
yield* fs.writeFileString(
path.join(projectDir, `${sessionId}.jsonl`),
JSON.stringify({
...entry,
uuid: yield* crypto.randomUUIDv4(),
isSidechain: false,
message: { role: "user", content: "Start a subagent." },
}) + "\n",
);
yield* fs.writeFileString(
path.join(subagentsDir, `agent-${agentId}.jsonl`),
JSON.stringify({
...entry,
uuid: yield* crypto.randomUUIDv4(),
isSidechain: true,
agentId,
message: { role: "user", content: "Review the change." },
}) + "\n",
);
// Claude stores the launching tool call in the transcript sidecar.
yield* fs.writeFileString(
path.join(subagentsDir, `agent-${agentId}.meta.json`),
JSON.stringify({ agentType: "general-purpose", toolUseId: "toolu_launch" }),
);
const runner = yield* ClaudeAgentSdkQueryRunner;
const input = {
sessionId,
agentId,
dir: workspace,
threadId: ThreadId.make("thread-instance-home"),
providerSessionId: ProviderSessionId.make("session-instance-home"),
environment: { ...(yield* HostProcess.Environment), CLAUDE_CONFIG_DIR: claudeHome },
};
assert.equal(yield* runner.subagentLaunchToolUseId(input), "toolu_launch");
}).pipe(Effect.provide(Layer.mergeAll(realQueryRunner, NodeServices.layer))),
),
);
function fakeClaudeCli(script: string): string {
const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
const cli = NodePath.join(dir, "claude");
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.