Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

fix: subagent code mode not working (#293)

Srajan Asthana363a52205f3e
diff --git a/.changeset/20260817070300-code-mode-root-thread-only.md b/.changeset/20260817070300-code-mode-root-thread-only.md
new file mode 100644
index 000000000..2e38890c5
--- /dev/null
+++ b/.changeset/20260817070300-code-mode-root-thread-only.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge-core': patch
+---
+
+Wire shared sandbox Code Mode once in SessionHandle from main toolSets before building threads.
diff --git a/packages/trueforge-core/src/agent-session/ITurnResourceResolver.ts b/packages/trueforge-core/src/agent-session/ITurnResourceResolver.ts
index b11d570e3..585ef2d5f 100644
--- a/packages/trueforge-core/src/agent-session/ITurnResourceResolver.ts
+++ b/packages/trueforge-core/src/agent-session/ITurnResourceResolver.ts
@@ -7,6 +7,12 @@ import type { AgentTracing } from '../core/tracing/AgentTracing';
import type { TurnRecord } from './models/TurnRecord';
import type { AgentSpec } from './schemas/agentSpec';
+/** Result of {@link ITurnResourceResolver.resolveAgentDefinition}. */
+export interface ResolvedAgentDefinition {
+ definition: AgentDefinition;
+ extraCapabilities?: AgentCapability[] | undefined;
+}
+
/**
* Per-run wiring contract consumed by SessionHandle.createTurn(). Implementations hold
* per-request state (secrets, providers, caches) freely.
@@ -35,8 +41,8 @@ export interface ITurnResourceResolver<TTurnCustom extends object = Record<strin
tracing: AgentTracing;
}): Promise<Sandbox | undefined>;
/**
- * Called once per thread_id; calls for different ids may overlap (parallel
- * sub-agent spawns), so implementations must be concurrency-safe across ids.
+ * Called once per thread (rebuild or live sub-agent spawn); calls for different
+ * threads may overlap, so implementations must be concurrency-safe.
* `agent_info` is set for sub-agent threads. `previousTurn` is read-only:
* branch on it, but never load state into capabilities — return blank
* instances; the AgentThread constructor is the sole hydration path.
@@ -44,15 +50,11 @@ export interface ITurnResourceResolver<TTurnCustom extends object = Record<strin
*/
resolveAgentDefinition(input: {
spec: AgentSpec;
- thread_id: string;
agent_info?: AgentInfo | undefined;
previousTurn?: TurnRecord<TTurnCustom> | undefined;
signal: AbortSignal;
tracing: AgentTracing;
- }): Promise<{
- definition: AgentDefinition;
- extraCapabilities?: AgentCapability[] | undefined;
- }>;
+ }): Promise<ResolvedAgentDefinition>;
/**
* Release per-run resources. Called by the harness at the end of the run:
* by TurnHandle.stream() in its finally (AFTER the terminal state write), or by
diff --git a/packages/trueforge-core/src/agent-session/SessionHandle.ts b/packages/trueforge-core/src/agent-session/SessionHandle.ts
index e116cb98b..23acbc0e7 100644
--- a/packages/trueforge-core/src/agent-session/SessionHandle.ts
+++ b/packages/trueforge-core/src/agent-session/SessionHandle.ts
@@ -19,9 +19,9 @@ import type { CreateDynamicSubAgentThread } from '../core/runtime/CreateDynamicS
import type { Sandbox } from '../core/sandbox/Sandbox';
import type { AgentTracing } from '../core/tracing/AgentTracing';
import { builtinsFromSpec } from './builtinsFromSpec';
-import type { ITurnResourceResolver } from './ITurnResourceResolver';
+import type { ITurnResourceResolver, ResolvedAgentDefinition } from './ITurnResourceResolver';
import type { SessionRecord } from './models/SessionRecord';
-import { MAIN_THREAD_ID, type TurnRecord } from './models/TurnRecord';
+import { MAIN_THREAD_ID, type TurnRecord, type TurnSnapshot } from './models/TurnRecord';
import type { AgentSpec } from './schemas/agentSpec';
import type { SessionEventItem } from './schemas/events';
import { EventType, type TurnDoneEvent } from './schemas/events';
@@ -34,6 +34,7 @@ import { TurnHandle } from './TurnHandle';
/** How many recent ancestors SessionHandle persists on each turn. Store-local. */
const MAX_TURN_ANCESTORS = 20;
+
function resolvePreviousTurnId(requested: string | undefined, lastTurnId: string | null | undefined): string | null {
if (requested === 'none') {
return null;
@@ -112,6 +113,12 @@ function threadsRecordFromMap(threads: Map<string, AgentThread>): Record<string,
return out;
}
+// Current-turn thread ids. Main (`MAIN_THREAD_ID`) is always present — first turn
+// synthesizes it; later turns always carry it in the previous snapshot.
+function threadIdsForCurrentTurn(snapshot: TurnSnapshot | undefined): string[] {
+ return snapshot ? Object.keys(snapshot.threads) : [MAIN_THREAD_ID];
+}
+
export class SessionHandle<
TSessionCustom extends object = Record<string, never>,
TTurnCustom extends object = Record<string, never>,
@@ -205,15 +212,32 @@ export class SessionHandle<
tracing,
});
- const agentThreads = await this.buildThreads({
+ const definitionsByThreadId = await this.resolveAgentDefinitions({
previous,
resolver: input.resolver,
spec,
- sandbox,
tracing,
signal: input.signal,
});
+ // Wire Code Mode once from main toolSets before threads share the sandbox.
+ const mainDefinition = definitionsByThreadId.get(MAIN_THREAD_ID);
+ if (!mainDefinition) {
+ throw new Error('Unreachable: missing resolved agent definition for main thread');
+ }
+ if (sandbox) {
+ sandbox.configureCodeMode(mainDefinition.definition.toolSets ?? []);
+ }
+
+ const agentThreads = this.buildThreads({
+ previous,
+ resolver: input.resolver,
+ spec,
+ sandbox,
+ tracing,
+ definitionsByThreadId,
+ });
+
const createDynamicSubAgentThread = this.makeCreateDynamicSubAgentThread({
resolver: input.resolver,
previous,
@@ -364,55 +388,74 @@ export class SessionHandle<
});
}
- private async buildThreads(input: {
+ private async resolveAgentDefinitions(input: {
previous: TurnRecord<TTurnCustom> | undefined;
resolver: ITurnResourceResolver<TTurnCustom>;
spec: AgentSpec;
- sandbox: Sandbox | undefined;
tracing: AgentTracing;
signal: AbortSignal;
- }): Promise<Map<string, AgentThread>> {
+ }): Promise<Map<string, ResolvedAgentDefinition>> {
+ const snapshots = input.previous?.snapshot.threads;
+ const threadIds = threadIdsForCurrentTurn(input.previous?.snapshot);
+ const definitionsByThreadId = new Map<string, ResolvedAgentDefinition>();
+ await Promise.all(
+ threadIds.map(async threadId => {
+ const previousThreadSnapshot = snapshots?.[threadId];
+ const resolved = await input.resolver.resolveAgentDefinition({
+ spec: input.spec,
+ agent_info: previousThreadSnapshot?.agent_info ?? undefined,
+ previousTurn: input.previous,
+ signal: input.signal,
+ tracing: input.tracing,
+ });
+ definitionsByThreadId.set(threadId, resolved);
+ }),
+ );
+ return definitionsByThreadId;
+ }
+
+ private buildThreads(input: {
+ previous: TurnRecord<TTurnCustom> | undefined;
+ resolver: ITurnResourceResolver<TTurnCustom>;
+ spec: AgentSpec;
+ sandbox: Sandbox | undefined;
+ tracing: AgentTracing;
+ definitionsByThreadId: ReadonlyMap<string, ResolvedAgentDefinition>;
+ }): Map<string, AgentThread> {
const snapshots = input.previous?.snapshot.threads;
- const threadIds = snapshots ? Object.keys(snapshots) : [MAIN_THREAD_ID];
const map = new Map<string, AgentThread>();
- for (const threadId of threadIds) {
- const data = snapshots?.[threadId];
+ for (const threadId of threadIdsForCurrentTurn(input.previous?.snapshot)) {
+ const resolvedDefinition = input.definitionsByThreadId.get(threadId);
+ if (!resolvedDefinition) {
+ throw new Error(`Unreachable: missing resolved agent definition for thread '${threadId}'`);
+ }
map.set(
threadId,
- await this.buildThread({
+ this.buildThread({
threadId,
- data,
+ previousThreadSnapshot: snapshots?.[threadId],
resolver: input.resolver,
- previous: input.previous,
spec: input.spec,
sandbox: input.sandbox,
tracing: input.tracing,
- signal: input.signal,
+ resolvedDefinition,
}),
);
}
return map;
}
- private async buildThread(input: {
+ private buildThread(input: {
threadId: string;
- data?: AgentThreadSnapshot | undefined;
+ previousThreadSnapshot?: AgentThreadSnapshot | undefined;
resolver: ITurnResourceResolver<TTurnCustom>;
- previous: TurnRecord<TTurnCustom> | undefined;
spec: AgentSpec;
sandbox: Sandbox | undefined;
tracing: AgentTracing;
- signal: AbortSignal;
- }): Promise<AgentThread> {
- const { definition, extraCapabilities } = await input.resolver.resolveAgentDefinition({
- spec: input.spec,
- thread_id: input.threadId,
- agent_info: input.data?.agent_info ?? undefined,
- previousTurn: input.previous,
- signal: input.signal,
- tracing: input.tracing,
- });
- const isChild = Boolean(input.data?.parent);
+ resolvedDefinition: ResolvedAgentDefinition;
+ }): AgentThread {
+ const { definition, extraCapabilities } = input.resolvedDefinition;
+ const isChild = Boolean(input.previousThreadSnapshot?.parent);
const capabilities = [
...builtinsFromSpec({
spec: input.spec,
@@ -427,15 +470,15 @@ export class SessionHandle<
return new AgentThread({
definition,
threadId: input.threadId,
- title: input.data?.agent_info?.name ?? (isChild ? input.threadId : 'main'),
+ title: input.previousThreadSnapshot?.agent_info?.name ?? (isChild ? input.threadId : 'main'),
sandbox: input.sandbox,
- context: input.data?.context,
- currentContextUsage: input.data?.current_context_usage,
- parent: input.data?.parent ?? undefined,
- agentInfo: input.data?.agent_info ?? undefined,
- preComputedCompletion: input.data?.completion ?? undefined,
+ context: input.previousThreadSnapshot?.context,
+ currentContextUsage: input.previousThreadSnapshot?.current_context_usage,
+ parent: input.previousThreadSnapshot?.parent ?? undefined,
+ agentInfo: input.previousThreadSnapshot?.agent_info ?? undefined,
+ preComputedCompletion: input.previousThreadSnapshot?.completion ?? undefined,
capabilities,
- capabilityState: input.data?.capability_state ?? undefined,
+ capabilityState: input.previousThreadSnapshot?.capability_state ?? undefined,
tracing: input.tracing,
logger: input.resolver.logger,
});
@@ -451,7 +494,6 @@ export class SessionHandle<
return async params => {
const { definition, extraCapabilities } = await input.resolver.resolveAgentDefinition({
spec: input.spec,
- thread_id: params.threadId,
agent_info: params.request,
previousTurn: input.previous,
signal: params.signal,
diff --git a/packages/trueforge-core/src/agent-session/TurnResourceResolver.ts b/packages/trueforge-core/src/agent-session/TurnResourceResolver.ts
index ff1824f57..123e91050 100644
--- a/packages/trueforge-core/src/agent-session/TurnResourceResolver.ts
+++ b/packages/trueforge-core/src/agent-session/TurnResourceResolver.ts
@@ -1,16 +1,15 @@
import type { Logger } from 'winston';
-import type { AgentCapability } from '../core/capabilities/AgentCapability';
import type { ILLM } from '../core/llm/ILLM';
import type { ToolSource } from '../core/mcp/IMCPServer';
import { RemoteMCP, type RemoteMcpHeaders } from '../core/mcp/RemoteMCP';
import type { ToolSelectorConfig } from '../core/mcp/ToolSelectorPolicy';
import { ToolSet } from '../core/mcp/ToolSet';
-import type { AgentDefinition, ModelParams } from '../core/runtime/AgentDefinition';
+import type { ModelParams } from '../core/runtime/AgentDefinition';
import type { AgentInfo } from '../core/runtime/AgentThread.types';
import type { Sandbox, SandboxInfo } from '../core/sandbox/Sandbox';
import type { AgentTracing } from '../core/tracing/AgentTracing';
import { NOOP_AGENT_TRACING } from '../core/tracing/NoopAgentTracing';
-import type { ITurnResourceResolver } from './ITurnResourceResolver';
+import type { ITurnResourceResolver, ResolvedAgentDefinition } from './ITurnResourceResolver';
import type { TurnRecord } from './models/TurnRecord';
import type { AgentSpec } from './schemas/agentSpec';
@@ -161,15 +160,11 @@ export class TurnResourceResolver<
*/
async resolveAgentDefinition(input: {
spec: AgentSpec;
- thread_id: string;
agent_info?: AgentInfo | undefined;
previousTurn?: TurnRecord<TTurnCustom> | undefined;
signal: AbortSignal;
tracing: AgentTracing;
- }): Promise<{
- definition: AgentDefinition;
- extraCapabilities?: AgentCapability[] | undefined;
- }> {
+ }): Promise<ResolvedAgentDefinition> {
const { spec, agent_info: agentInfo, previousTurn, signal, tracing } = input;
const toolSets = await Promise.all(
(spec.mcp_servers ?? []).map(async entry => {
diff --git a/packages/trueforge-core/src/core/runtime/AgentThread.ts b/packages/trueforge-core/src/core/runtime/AgentThread.ts
index 3edbc2218..eb2094739 100644
--- a/packages/trueforge-core/src/core/runtime/AgentThread.ts
+++ b/packages/trueforge-core/src/core/runtime/AgentThread.ts
@@ -558,10 +558,6 @@ export class AgentThread {
});
}
- if (this.sandbox) {
- this.sandbox.configureCodeMode(this.definition.toolSets ?? []);
- }
-
this.instruction = this.buildInstruction(this.definition.instruction);
}
diff --git a/packages/trueforge-core/tests/agent-session/resolveAgentSpec.test.ts b/packages/trueforge-core/tests/agent-session/resolveAgentSpec.test.ts
index 2ad56ad21..74a158e92 100644
--- a/packages/trueforge-core/tests/agent-session/resolveAgentSpec.test.ts
+++ b/packages/trueforge-core/tests/agent-session/resolveAgentSpec.test.ts
@@ -54,7 +54,6 @@ describe('TurnResourceResolver.resolveAgentDefinition', () => {
const { definition } = await resolver.resolveAgentDefinition({
spec,
- thread_id: 'main',
signal: new AbortController().signal,
tracing: resolver.createTracing(),
});