Adopt userdata-v2 and subagent activity mapping
- Move desktop and server state paths to `userdata-v2` - Handle Codex subagent activity events in orchestration v2 - Update related path and lifecycle tests
This commit is contained in:
1 parent
b452303639
commit
3b864044c6
21 files changed
+786
-265
No files matched your search
@@ -126,7 +126,7 @@ const withIdentity = <A, E, R>(
|
||||
input.legacyPathProbeError
|
||||
? Effect.fail(input.legacyPathProbeError)
|
||||
: Effect.succeed(
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
|
||||
input.legacyPathExists === true && path.includes("T3 Code (Alpha v2)"),
|
||||
),
|
||||
readFileString: () =>
|
||||
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
|
||||
@@ -147,14 +147,14 @@ describe("DesktopAppIdentity", () => {
|
||||
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
|
||||
const userDataPath = yield* identity.resolveUserDataPath;
|
||||
|
||||
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha)");
|
||||
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha v2)");
|
||||
}),
|
||||
{ legacyPathExists: true },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves failures while inspecting the legacy userData path", () => {
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
|
||||
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha v2)";
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
|
||||
@@ -254,7 +254,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2/connection-catalog.json`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -271,11 +271,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
error,
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
|
||||
);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
`Failed to read the desktop connection catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -291,7 +291,7 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -309,11 +309,11 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
|
||||
);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.equal(error.path, `${baseDir}/userdata-v2`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
|
||||
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata-v2.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
@@ -398,14 +398,14 @@ describe("DesktopConnectionCatalogStore", () => {
|
||||
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
|
||||
);
|
||||
assert.equal(error.operation, "decrypt-catalog");
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
|
||||
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
|
||||
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
|
||||
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
|
||||
assert.instanceOf(decryptError.cause, Error);
|
||||
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
|
||||
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
|
||||
);
|
||||
assert.notEqual(error.message, decryptError.message);
|
||||
yield* Ref.set(failDecrypt, false);
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("derives production state paths under userdata", () =>
|
||||
it.effect("derives production state paths under userdata-v2", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment(
|
||||
{},
|
||||
@@ -88,10 +88,12 @@ describe("DesktopEnvironment", () => {
|
||||
);
|
||||
|
||||
assert.equal(environment.isDevelopment, false);
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.stateDir, "/tmp/t3/userdata-v2");
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata-v2/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata-v2/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata-v2/settings.json");
|
||||
assert.equal(environment.userDataDirName, "t3code-v2");
|
||||
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha v2)");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -155,9 +155,9 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata-v2");
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code-v2";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha v2)";
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
|
||||
@@ -358,7 +358,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const settingsPath = path.join(baseDir, "userdata", "settings.json");
|
||||
const settingsPath = path.join(baseDir, "userdata-v2", "settings.json");
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
|
||||
@@ -503,7 +503,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
};
|
||||
|
||||
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
|
||||
// config resolution lands in dev/ instead of userdata/. Inheriting through
|
||||
// config resolution lands in dev/ instead of userdata-v2/. Inheriting through
|
||||
// WSLENV is unreliable in practice (URL-shaped values with colons /
|
||||
// slashes get translated unpredictably depending on flags), and the
|
||||
// packaged build leaves devServerUrl as None anyway.
|
||||
|
||||
@@ -83,7 +83,7 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2/client-settings.json`,
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -403,7 +403,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-saved-environments-test-",
|
||||
});
|
||||
const registryPath = `${baseDir}/userdata/saved-environments.json`;
|
||||
const registryPath = `${baseDir}/userdata-v2/saved-environments.json`;
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -439,7 +439,7 @@ describe("DesktopSavedEnvironments", () => {
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "makeDirectory",
|
||||
pathOrDescriptor: `${baseDir}/userdata`,
|
||||
pathOrDescriptor: `${baseDir}/userdata-v2`,
|
||||
});
|
||||
const fileSystemLayer = Layer.succeed(
|
||||
FileSystem.FileSystem,
|
||||
@@ -455,11 +455,11 @@ describe("DesktopSavedEnvironments", () => {
|
||||
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
|
||||
assert.equal(error.operation, "create-directory");
|
||||
assert.equal(error.path, `${baseDir}/userdata`);
|
||||
assert.equal(error.path, `${baseDir}/userdata-v2`);
|
||||
assert.strictEqual(error.cause, permissionError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
|
||||
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata-v2.`,
|
||||
);
|
||||
assert.notEqual(error.message, permissionError.message);
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
|
||||
@@ -328,7 +328,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
||||
assert.equal(join(baseDir, "userdata-v2"), resolved.stateDir);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
devUrl: ServerConfig["Service"]["devUrl"],
|
||||
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
||||
const { join } = yield* Path.Path;
|
||||
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
|
||||
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata-v2");
|
||||
const dbPath = join(stateDir, "state.sqlite");
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
|
||||
@@ -778,6 +778,17 @@ export type CodexDynamicToolItem = Extract<
|
||||
{ readonly type: "mcpToolCall" | "dynamicToolCall" }
|
||||
>;
|
||||
|
||||
type CodexCollabAgentToolCallItem = Extract<
|
||||
CodexSchema.V2ItemCompletedNotification__ThreadItem,
|
||||
{ readonly type: "collabAgentToolCall" }
|
||||
>;
|
||||
|
||||
type CodexSubAgentActivityItem = Extract<
|
||||
| CodexSchema.V2ItemStartedNotification__ThreadItem
|
||||
| CodexSchema.V2ItemCompletedNotification__ThreadItem,
|
||||
{ readonly type: "subAgentActivity" }
|
||||
>;
|
||||
|
||||
export interface CodexAgentMessageDeltaUpdate {
|
||||
readonly turnId: string;
|
||||
readonly itemId: string;
|
||||
@@ -1573,133 +1584,181 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
});
|
||||
});
|
||||
|
||||
const registerSubagentThreads = (input: {
|
||||
const registerSubagentThread = (input: {
|
||||
readonly context: ActiveCodexTurnContext;
|
||||
readonly item: Extract<
|
||||
CodexSchema.V2ItemCompletedNotification__ThreadItem,
|
||||
{ type: "collabAgentToolCall" }
|
||||
>;
|
||||
readonly nativeThreadId: string;
|
||||
readonly nativeItemId: string;
|
||||
readonly nativeToolCallId: string;
|
||||
readonly prompt: string;
|
||||
readonly title: string | null;
|
||||
readonly model: string | null;
|
||||
readonly ordinal: number;
|
||||
readonly emitInitialPrompt: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.item.tool !== "spawnAgent" || input.item.receiverThreadIds.length === 0) {
|
||||
const registeredSubagents = yield* Ref.get(subagentThreads);
|
||||
if (registeredSubagents.has(input.nativeThreadId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
for (const [index, nativeThreadId] of input.item.receiverThreadIds.entries()) {
|
||||
const registeredSubagents = yield* Ref.get(subagentThreads);
|
||||
if (registeredSubagents.has(nativeThreadId)) {
|
||||
continue;
|
||||
}
|
||||
const subagentNodeId = idAllocator.derive.nodeFromProviderItem({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeItemId: input.nativeItemId,
|
||||
});
|
||||
const childRootNodeId = idAllocator.derive.nodeFromProviderItem({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeItemId: `${input.nativeItemId}:thread-root`,
|
||||
});
|
||||
const childThreadId = idAllocator.derive.threadFromProviderThread({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeThreadId: input.nativeThreadId,
|
||||
});
|
||||
const turnItemOrdinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
|
||||
const providerThread = {
|
||||
id: idAllocator.derive.providerThread({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeThreadId: input.nativeThreadId,
|
||||
}),
|
||||
driver: CODEX_PROVIDER,
|
||||
providerInstanceId: input.context.input.modelSelection.instanceId,
|
||||
providerSessionId: input.context.providerThread.providerSessionId,
|
||||
appThreadId: childThreadId,
|
||||
ownerNodeId: null,
|
||||
nativeThreadRef: {
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeId: input.nativeThreadId,
|
||||
strength: "strong" as const,
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle" as const,
|
||||
firstRunOrdinal: null,
|
||||
lastRunOrdinal: null,
|
||||
handoffIds: [],
|
||||
forkedFrom: {
|
||||
providerThreadId: input.context.providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationV2ProviderThread;
|
||||
const task = {
|
||||
id: subagentNodeId,
|
||||
threadId: input.context.input.threadId,
|
||||
runId: input.context.input.runId,
|
||||
parentNodeId: input.context.rootNodeId,
|
||||
origin: "provider_native",
|
||||
createdBy: "agent",
|
||||
driver: CODEX_PROVIDER,
|
||||
providerInstanceId: input.context.input.modelSelection.instanceId,
|
||||
providerThreadId: providerThread.id,
|
||||
childThreadId,
|
||||
nativeTaskRef: codexNativeItemRef(input.nativeItemId),
|
||||
prompt: input.prompt,
|
||||
title: input.title,
|
||||
model: input.model,
|
||||
status: "running",
|
||||
result: null,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationV2Subagent;
|
||||
const subagent = {
|
||||
parentContext: input.context,
|
||||
providerThread,
|
||||
subagentNodeId,
|
||||
childRootNodeId,
|
||||
childThreadId,
|
||||
nativeToolCallId: input.nativeToolCallId,
|
||||
ordinal: input.ordinal,
|
||||
startedAt: now,
|
||||
turnItemId: idAllocator.derive.turnItemFromProviderItem({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeItemId: input.nativeItemId,
|
||||
}),
|
||||
turnItemOrdinal,
|
||||
task,
|
||||
} satisfies CodexSubagentThreadContext;
|
||||
|
||||
const nativeItemId = `${input.item.id}:${nativeThreadId}`;
|
||||
const subagentNodeId = idAllocator.derive.nodeFromProviderItem({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeItemId,
|
||||
});
|
||||
const childRootNodeId = idAllocator.derive.nodeFromProviderItem({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeItemId: `${nativeItemId}:thread-root`,
|
||||
});
|
||||
const childThreadId = idAllocator.derive.threadFromProviderThread({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeThreadId,
|
||||
});
|
||||
const turnItemOrdinal = yield* resolveItemOrdinal(input.context, nativeItemId);
|
||||
const providerThread = {
|
||||
id: idAllocator.derive.providerThread({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeThreadId,
|
||||
}),
|
||||
driver: CODEX_PROVIDER,
|
||||
providerInstanceId: input.context.input.modelSelection.instanceId,
|
||||
providerSessionId: input.context.providerThread.providerSessionId,
|
||||
appThreadId: childThreadId,
|
||||
ownerNodeId: null,
|
||||
nativeThreadRef: {
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeId: nativeThreadId,
|
||||
strength: "strong" as const,
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle" as const,
|
||||
firstRunOrdinal: null,
|
||||
lastRunOrdinal: null,
|
||||
handoffIds: [],
|
||||
forkedFrom: {
|
||||
providerThreadId: input.context.providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationV2ProviderThread;
|
||||
const task = {
|
||||
yield* Ref.update(subagentThreads, (current) => {
|
||||
const updated = new Map(current);
|
||||
updated.set(input.nativeThreadId, subagent);
|
||||
return updated;
|
||||
});
|
||||
const childThread = makeSubagentChildThread({
|
||||
parentThread: input.context.input.appThread,
|
||||
childThreadId,
|
||||
parentNodeId: subagentNodeId,
|
||||
activeProviderThreadId: providerThread.id,
|
||||
providerInstanceId: input.context.input.modelSelection.instanceId,
|
||||
modelSelection: {
|
||||
...input.context.input.modelSelection,
|
||||
model: task.model ?? input.context.input.modelSelection.model,
|
||||
},
|
||||
title: subagentThreadTitle({
|
||||
parentTitle: input.context.input.appThread.title,
|
||||
prompt: task.prompt,
|
||||
title: task.title,
|
||||
ordinal: input.ordinal,
|
||||
}),
|
||||
now,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "app_thread.created",
|
||||
driver: CODEX_PROVIDER,
|
||||
appThread: childThread,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
node: {
|
||||
id: subagentNodeId,
|
||||
threadId: input.context.input.threadId,
|
||||
runId: input.context.input.runId,
|
||||
parentNodeId: input.context.rootNodeId,
|
||||
origin: "provider_native",
|
||||
createdBy: "agent",
|
||||
driver: CODEX_PROVIDER,
|
||||
providerInstanceId: input.context.input.modelSelection.instanceId,
|
||||
providerThreadId: providerThread.id,
|
||||
childThreadId,
|
||||
nativeTaskRef: codexNativeItemRef(nativeItemId),
|
||||
prompt: input.item.prompt ?? "",
|
||||
title: null,
|
||||
model:
|
||||
typeof input.item.model === "string" && input.item.model.length > 0
|
||||
? input.item.model
|
||||
: null,
|
||||
rootNodeId: input.context.rootNodeId,
|
||||
kind: "subagent",
|
||||
status: "running",
|
||||
result: null,
|
||||
countsForRun: false,
|
||||
providerThreadId: providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
nativeItemRef: codexNativeItemRef(input.nativeToolCallId),
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationV2Subagent;
|
||||
const subagent = {
|
||||
parentContext: input.context,
|
||||
providerThread,
|
||||
subagentNodeId,
|
||||
childRootNodeId,
|
||||
childThreadId,
|
||||
nativeToolCallId: input.item.id,
|
||||
ordinal: index + 1,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
node: {
|
||||
id: childRootNodeId,
|
||||
threadId: childThreadId,
|
||||
runId: null,
|
||||
parentNodeId: null,
|
||||
rootNodeId: childRootNodeId,
|
||||
kind: "root_turn",
|
||||
status: "running",
|
||||
countsForRun: false,
|
||||
providerThreadId: providerThread.id,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: codexNativeItemRef(input.nativeItemId),
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
turnItemId: idAllocator.derive.turnItemFromProviderItem({
|
||||
driver: CODEX_PROVIDER,
|
||||
nativeItemId,
|
||||
}),
|
||||
turnItemOrdinal,
|
||||
task,
|
||||
} satisfies CodexSubagentThreadContext;
|
||||
|
||||
yield* Ref.update(subagentThreads, (current) => {
|
||||
const updated = new Map(current);
|
||||
updated.set(nativeThreadId, subagent);
|
||||
return updated;
|
||||
});
|
||||
const childThread = makeSubagentChildThread({
|
||||
parentThread: input.context.input.appThread,
|
||||
childThreadId,
|
||||
parentNodeId: subagentNodeId,
|
||||
activeProviderThreadId: providerThread.id,
|
||||
providerInstanceId: input.context.input.modelSelection.instanceId,
|
||||
modelSelection: {
|
||||
...input.context.input.modelSelection,
|
||||
model: task.model ?? input.context.input.modelSelection.model,
|
||||
},
|
||||
title: subagentThreadTitle({
|
||||
parentTitle: input.context.input.appThread.title,
|
||||
prompt: task.prompt,
|
||||
title: task.title,
|
||||
ordinal: index + 1,
|
||||
}),
|
||||
now,
|
||||
createdBy: "agent",
|
||||
creationSource: "provider",
|
||||
});
|
||||
const promptNativeItemId = `${nativeItemId}:prompt`;
|
||||
completedAt: null,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "provider_thread.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
providerThread,
|
||||
});
|
||||
if (input.emitInitialPrompt && input.prompt.length > 0) {
|
||||
const promptNativeItemId = `${input.nativeItemId}:prompt`;
|
||||
const promptArtifacts = makeSubagentConversationArtifacts({
|
||||
messageId: idAllocator.derive.messageFromProviderItem({
|
||||
driver: CODEX_PROVIDER,
|
||||
@@ -1715,62 +1774,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
providerTurnId: null,
|
||||
nativeItemRef: codexNativeItemRef(promptNativeItemId),
|
||||
role: "user",
|
||||
text: task.prompt,
|
||||
text: input.prompt,
|
||||
ordinal: 100,
|
||||
now,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "app_thread.created",
|
||||
driver: CODEX_PROVIDER,
|
||||
appThread: childThread,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
node: {
|
||||
id: subagentNodeId,
|
||||
threadId: input.context.input.threadId,
|
||||
runId: input.context.input.runId,
|
||||
parentNodeId: input.context.rootNodeId,
|
||||
rootNodeId: input.context.rootNodeId,
|
||||
kind: "subagent",
|
||||
status: "running",
|
||||
countsForRun: false,
|
||||
providerThreadId: providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
nativeItemRef: codexNativeItemRef(input.item.id),
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
node: {
|
||||
id: childRootNodeId,
|
||||
threadId: childThreadId,
|
||||
runId: null,
|
||||
parentNodeId: null,
|
||||
rootNodeId: childRootNodeId,
|
||||
kind: "root_turn",
|
||||
status: "running",
|
||||
countsForRun: false,
|
||||
providerThreadId: providerThread.id,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: codexNativeItemRef(nativeItemId),
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "provider_thread.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
providerThread,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "message.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
@@ -1781,34 +1788,91 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
driver: CODEX_PROVIDER,
|
||||
turnItem: promptArtifacts.turnItem,
|
||||
});
|
||||
yield* emitSubagentTaskUpdate({
|
||||
subagent,
|
||||
status: "running",
|
||||
});
|
||||
}
|
||||
yield* emitSubagentTaskUpdate({
|
||||
subagent,
|
||||
status: "running",
|
||||
});
|
||||
|
||||
const pendingTurns = yield* Ref.modify(pendingSubagentTurns, (current) => {
|
||||
const pending = current.get(nativeThreadId) ?? [];
|
||||
const updated = new Map(current);
|
||||
updated.delete(nativeThreadId);
|
||||
return [pending, updated];
|
||||
});
|
||||
for (const pendingTurn of pendingTurns) {
|
||||
yield* emitSubagentProviderTurnStarted(subagent, pendingTurn);
|
||||
}
|
||||
const pendingTurns = yield* Ref.modify(pendingSubagentTurns, (current) => {
|
||||
const pending = current.get(input.nativeThreadId) ?? [];
|
||||
const updated = new Map(current);
|
||||
updated.delete(input.nativeThreadId);
|
||||
return [pending, updated];
|
||||
});
|
||||
for (const pendingTurn of pendingTurns) {
|
||||
yield* emitSubagentProviderTurnStarted(subagent, pendingTurn);
|
||||
}
|
||||
});
|
||||
|
||||
const updateSubagentStates = (input: {
|
||||
readonly item: Extract<
|
||||
CodexSchema.V2ItemCompletedNotification__ThreadItem,
|
||||
{ type: "collabAgentToolCall" }
|
||||
>;
|
||||
const registerSubagentThreads = (input: {
|
||||
readonly context: ActiveCodexTurnContext;
|
||||
readonly item: CodexCollabAgentToolCallItem;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.item.tool !== "spawnAgent") {
|
||||
if (input.item.tool !== "spawnAgent" || input.item.receiverThreadIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [index, nativeThreadId] of input.item.receiverThreadIds.entries()) {
|
||||
const model =
|
||||
typeof input.item.model === "string" && input.item.model.length > 0
|
||||
? input.item.model
|
||||
: null;
|
||||
yield* registerSubagentThread({
|
||||
context: input.context,
|
||||
nativeThreadId,
|
||||
nativeItemId: `${input.item.id}:${nativeThreadId}`,
|
||||
nativeToolCallId: input.item.id,
|
||||
prompt: input.item.prompt ?? "",
|
||||
title: null,
|
||||
model,
|
||||
ordinal: index + 1,
|
||||
emitInitialPrompt: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const registerSubagentActivity = (input: {
|
||||
readonly context: ActiveCodexTurnContext;
|
||||
readonly item: CodexSubAgentActivityItem;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.item.kind === "started") {
|
||||
const registeredSubagents = yield* Ref.get(subagentThreads);
|
||||
const ordinal =
|
||||
Array.from(registeredSubagents.values()).filter(
|
||||
(subagent) => subagent.parentContext.rootNodeId === input.context.rootNodeId,
|
||||
).length + 1;
|
||||
yield* registerSubagentThread({
|
||||
context: input.context,
|
||||
nativeThreadId: input.item.agentThreadId,
|
||||
nativeItemId: `${input.item.id}:${input.item.agentThreadId}`,
|
||||
nativeToolCallId: input.item.id,
|
||||
prompt: "",
|
||||
title: input.item.agentPath,
|
||||
model: null,
|
||||
ordinal,
|
||||
emitInitialPrompt: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const subagent = (yield* Ref.get(subagentThreads)).get(input.item.agentThreadId);
|
||||
if (subagent === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.item.kind === "interrupted") {
|
||||
yield* emitSubagentTaskUpdate({
|
||||
subagent,
|
||||
status: "interrupted",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const updateSubagentStates = (input: { readonly item: CodexCollabAgentToolCallItem }) =>
|
||||
Effect.gen(function* () {
|
||||
const subagents = yield* Ref.get(subagentThreads);
|
||||
for (const [nativeThreadId, state] of Object.entries(input.item.agentsStates)) {
|
||||
const subagent = subagents.get(nativeThreadId);
|
||||
@@ -2742,6 +2806,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.item.type === "subAgentActivity") {
|
||||
yield* registerSubagentActivity({
|
||||
context,
|
||||
item: payload.item,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.item.type === "commandExecution") {
|
||||
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
|
||||
yield* emitProviderEvent({
|
||||
@@ -2916,6 +2988,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.item.type === "subAgentActivity") {
|
||||
yield* registerSubagentActivity({
|
||||
context,
|
||||
item: payload.item,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.item.type !== "agentMessage") {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -20,8 +20,10 @@ import {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
@@ -251,3 +253,209 @@ it.effect("rechecks run ownership immediately before calling the provider", () =
|
||||
assert.equal(yield* Ref.get(providerStarts), 0);
|
||||
}).pipe(Effect.provide(RunExecutionTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("keeps ingesting owned child events after the root turn terminalizes", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread:run-execution-late-child");
|
||||
const childThreadId = ThreadId.make("thread:run-execution-late-child:child");
|
||||
const runId = RunId.make("run:run-execution-late-child");
|
||||
const attemptId = RunAttemptId.make("attempt:run-execution-late-child");
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const providerSessionId = ProviderSessionId.make("session:run-execution-late-child");
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread:run-execution-late-child");
|
||||
const childProviderThreadId = ProviderThreadId.make(
|
||||
"provider-thread:run-execution-late-child:child",
|
||||
);
|
||||
const rootProviderTurnId = ProviderTurnId.make("provider-turn:run-execution-late-child");
|
||||
const childProviderTurnId = ProviderTurnId.make("provider-turn:run-execution-late-child:child");
|
||||
const rootNodeId = NodeId.make("node:run-execution-late-child");
|
||||
const childNodeId = NodeId.make("node:run-execution-late-child:child");
|
||||
const subagentNodeId = NodeId.make("node:run-execution-late-child:subagent");
|
||||
const childMessageIngested = yield* Deferred.make<void>();
|
||||
const order = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const testLayer = runExecutionServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
|
||||
Layer.mock(EventSinkV2)({
|
||||
write: () => Effect.succeed([]),
|
||||
writeWithEffects: (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (
|
||||
input.events.some(
|
||||
(event) => event.type === "run.updated" && event.runId === runId,
|
||||
)
|
||||
) {
|
||||
yield* Ref.update(order, (current) => [...current, "root-finalized"]);
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
writeIfRunCurrent: () => Effect.succeed({ committed: true, storedEvents: [] }),
|
||||
}),
|
||||
idAllocatorLayer,
|
||||
Layer.mock(ProviderEventIngestorV2)({
|
||||
ingestNormalized: (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (
|
||||
input.event.type === "message.updated" &&
|
||||
input.event.message.threadId === childThreadId
|
||||
) {
|
||||
yield* Ref.update(order, (current) => [...current, "child-message"]);
|
||||
yield* Deferred.succeed(childMessageIngested, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
}),
|
||||
ServerSettingsService.layerTest(),
|
||||
),
|
||||
),
|
||||
);
|
||||
const events: ReadonlyArray<ProviderAdapterV2Event> = [
|
||||
{
|
||||
type: "app_thread.created",
|
||||
driver,
|
||||
appThread: {
|
||||
id: childThreadId,
|
||||
lineage: {
|
||||
parentThreadId: threadId,
|
||||
relationshipToParent: "subagent",
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
},
|
||||
} as ProviderAdapterV2Event,
|
||||
{
|
||||
type: "provider_thread.updated",
|
||||
driver,
|
||||
providerThread: {
|
||||
id: childProviderThreadId,
|
||||
appThreadId: childThreadId,
|
||||
},
|
||||
} as ProviderAdapterV2Event,
|
||||
{
|
||||
type: "subagent.updated",
|
||||
driver,
|
||||
subagent: {
|
||||
id: subagentNodeId,
|
||||
threadId,
|
||||
runId,
|
||||
status: "running",
|
||||
},
|
||||
} as ProviderAdapterV2Event,
|
||||
{
|
||||
type: "provider_turn.updated",
|
||||
driver,
|
||||
threadId: childThreadId,
|
||||
providerTurn: {
|
||||
id: childProviderTurnId,
|
||||
providerThreadId: childProviderThreadId,
|
||||
nodeId: childNodeId,
|
||||
runAttemptId: null,
|
||||
status: "running",
|
||||
},
|
||||
} as ProviderAdapterV2Event,
|
||||
{
|
||||
type: "turn.terminal",
|
||||
driver,
|
||||
providerThreadId,
|
||||
providerTurnId: rootProviderTurnId,
|
||||
runOrdinal: 1,
|
||||
status: "completed",
|
||||
failure: null,
|
||||
threadDisposition: "reusable",
|
||||
},
|
||||
{
|
||||
type: "message.updated",
|
||||
driver,
|
||||
message: {
|
||||
id: MessageId.make("message:run-execution-late-child:child"),
|
||||
threadId: childThreadId,
|
||||
runId: null,
|
||||
nodeId: childNodeId,
|
||||
role: "assistant",
|
||||
text: "Hello.",
|
||||
streaming: false,
|
||||
},
|
||||
} as ProviderAdapterV2Event,
|
||||
{
|
||||
type: "provider_turn.updated",
|
||||
driver,
|
||||
threadId: childThreadId,
|
||||
providerTurn: {
|
||||
id: childProviderTurnId,
|
||||
providerThreadId: childProviderThreadId,
|
||||
nodeId: childNodeId,
|
||||
runAttemptId: null,
|
||||
status: "completed",
|
||||
},
|
||||
} as ProviderAdapterV2Event,
|
||||
{
|
||||
type: "subagent.updated",
|
||||
driver,
|
||||
subagent: {
|
||||
id: subagentNodeId,
|
||||
threadId,
|
||||
runId,
|
||||
status: "completed",
|
||||
},
|
||||
} as ProviderAdapterV2Event,
|
||||
];
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const runExecution = yield* RunExecutionServiceV2;
|
||||
yield* runExecution.startRootRun({
|
||||
commandId: CommandId.make("command:run-execution-late-child"),
|
||||
appThread: { id: threadId } as OrchestrationV2AppThread,
|
||||
providerSessionId,
|
||||
session: {
|
||||
events: Stream.fromIterable(events),
|
||||
startTurn: () => Effect.void,
|
||||
} as unknown as ProviderAdapterV2SessionRuntime,
|
||||
run: {
|
||||
id: runId,
|
||||
threadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId,
|
||||
} as OrchestrationV2Run,
|
||||
rootNode: { id: rootNodeId } as OrchestrationV2ExecutionNode,
|
||||
checkpointScope: {
|
||||
id: CheckpointScopeId.make("checkpoint-scope:run-execution-late-child"),
|
||||
} as OrchestrationV2CheckpointScope,
|
||||
providerThread: {
|
||||
id: providerThreadId,
|
||||
driver,
|
||||
} as OrchestrationV2ProviderThread,
|
||||
attempt: {
|
||||
id: attemptId,
|
||||
providerTurnId: rootProviderTurnId,
|
||||
} as OrchestrationV2RunAttempt,
|
||||
attemptId,
|
||||
providerTurnOrdinal: 1,
|
||||
message: {
|
||||
messageId: MessageId.make("message:run-execution-late-child:user"),
|
||||
text: "Spawn a child and finish.",
|
||||
attachments: [],
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
},
|
||||
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
|
||||
runtimePolicy: {
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
|
||||
const observed = yield* Deferred.await(childMessageIngested).pipe(
|
||||
Effect.timeoutOption("2 seconds"),
|
||||
);
|
||||
assert.isTrue(Option.isSome(observed), "child message was not ingested after root terminal");
|
||||
assert.deepEqual(yield* Ref.get(order), ["root-finalized", "child-message"]);
|
||||
}),
|
||||
);
|
||||
@@ -1,13 +1,16 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ModelSelection,
|
||||
type NodeId,
|
||||
type OrchestrationV2AppThread,
|
||||
type OrchestrationV2CheckpointScope,
|
||||
type OrchestrationV2ExecutionNode,
|
||||
type OrchestrationV2ProviderFailure,
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2ProviderTurn,
|
||||
type OrchestrationV2Run,
|
||||
type OrchestrationV2RunAttempt,
|
||||
type OrchestrationV2Subagent,
|
||||
type OrchestrationV2TurnItem,
|
||||
type ProviderSessionId,
|
||||
type ProviderThreadId,
|
||||
@@ -54,6 +57,24 @@ export interface ProviderEventRouteIdentity {
|
||||
|
||||
type ProviderTerminalEvent = Extract<ProviderAdapterV2Event, { readonly type: "turn.terminal" }>;
|
||||
|
||||
function isTerminalProviderTurnStatus(status: OrchestrationV2ProviderTurn["status"]): boolean {
|
||||
return (
|
||||
status === "completed" ||
|
||||
status === "interrupted" ||
|
||||
status === "failed" ||
|
||||
status === "cancelled"
|
||||
);
|
||||
}
|
||||
|
||||
function isTerminalSubagentStatus(status: OrchestrationV2Subagent["status"]): boolean {
|
||||
return (
|
||||
status === "completed" ||
|
||||
status === "interrupted" ||
|
||||
status === "failed" ||
|
||||
status === "cancelled"
|
||||
);
|
||||
}
|
||||
|
||||
export function finalProviderThreadStatus(
|
||||
disposition: ProviderTerminalEvent["threadDisposition"],
|
||||
): OrchestrationV2ProviderThread["status"] {
|
||||
@@ -532,6 +553,82 @@ export const layer: Layer.Layer<
|
||||
: { relatedProviderThreadIds: input.relatedProviderThreadIds }),
|
||||
}),
|
||||
);
|
||||
const rootTerminalSeen = yield* Ref.make(false);
|
||||
const rootRunFinalized = yield* Ref.make(false);
|
||||
const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
|
||||
const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
|
||||
const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.get(rootRunFinalized)) {
|
||||
return;
|
||||
}
|
||||
const providerThread = yield* Ref.get(latestProviderThread);
|
||||
yield* writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
terminal,
|
||||
failureItemPersisted: terminal.status === "failed",
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(rootRunFinalized, true);
|
||||
});
|
||||
const trackChildLifecycle = (event: ProviderAdapterV2Event) =>
|
||||
Effect.gen(function* () {
|
||||
const routing = yield* Ref.get(eventRouting);
|
||||
if (event.type === "provider_turn.updated") {
|
||||
const isRoot =
|
||||
event.providerTurn.runAttemptId === input.attempt.id ||
|
||||
event.providerTurn.id === routing.rootProviderTurnId;
|
||||
if (!isRoot) {
|
||||
yield* Ref.update(activeChildProviderTurns, (current) => {
|
||||
const next = new Set(current);
|
||||
if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
|
||||
next.delete(event.providerTurn.id);
|
||||
} else {
|
||||
next.add(event.providerTurn.id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
if (event.type === "subagent.updated") {
|
||||
const belongsToRootRun = event.subagent.runId === input.run.id;
|
||||
const belongsToOwnedChildThread =
|
||||
event.subagent.threadId !== input.run.threadId &&
|
||||
routing.ownedThreadIds.has(event.subagent.threadId);
|
||||
if (belongsToRootRun || belongsToOwnedChildThread) {
|
||||
yield* Ref.update(activeChildSubagents, (current) => {
|
||||
const next = new Set(current);
|
||||
if (isTerminalSubagentStatus(event.subagent.status)) {
|
||||
next.delete(event.subagent.id);
|
||||
} else {
|
||||
next.add(event.subagent.id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
const shouldStopProviderEventIngestion = Effect.gen(function* () {
|
||||
if (!(yield* Ref.get(rootTerminalSeen))) {
|
||||
return false;
|
||||
}
|
||||
const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
|
||||
if (childProviderTurns.size > 0) {
|
||||
return false;
|
||||
}
|
||||
const childSubagents = yield* Ref.get(activeChildSubagents);
|
||||
return childSubagents.size === 0;
|
||||
});
|
||||
const eventSubscription =
|
||||
input.session.subscribeEvents === undefined
|
||||
? { events: input.session.events, close: Effect.void }
|
||||
@@ -540,8 +637,7 @@ export const layer: Layer.Layer<
|
||||
Stream.filterEffect((event) =>
|
||||
Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
|
||||
),
|
||||
Stream.takeUntil((event) => event.type === "turn.terminal"),
|
||||
Stream.runForEach((event) =>
|
||||
Stream.tap((event) =>
|
||||
Effect.gen(function* () {
|
||||
let storedEventCount = 0;
|
||||
if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) {
|
||||
@@ -581,9 +677,14 @@ export const layer: Layer.Layer<
|
||||
}
|
||||
if (event.type === "turn.terminal") {
|
||||
yield* Ref.set(terminalEvent, event);
|
||||
yield* Ref.set(rootTerminalSeen, true);
|
||||
yield* finalizeRootRun(event);
|
||||
}
|
||||
yield* trackChildLifecycle(event);
|
||||
}),
|
||||
),
|
||||
Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
|
||||
Stream.runDrain,
|
||||
Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
|
||||
Effect.flatMap(() =>
|
||||
Effect.gen(function* () {
|
||||
@@ -591,62 +692,55 @@ export const layer: Layer.Layer<
|
||||
if (terminal === null) {
|
||||
return;
|
||||
}
|
||||
const providerThread = yield* Ref.get(latestProviderThread);
|
||||
yield* writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
terminal,
|
||||
failureItemPersisted: terminal.status === "failed",
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
|
||||
),
|
||||
);
|
||||
yield* finalizeRootRun(terminal);
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("orchestration V2 provider event ingestion failed", {
|
||||
runId: input.run.id,
|
||||
cause,
|
||||
}).pipe(
|
||||
Effect.andThen(Ref.get(latestProviderThread)),
|
||||
Effect.flatMap((providerThread) =>
|
||||
Ref.get(latestTurnItemOrdinal).pipe(
|
||||
Effect.flatMap((latestItemOrdinal) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
class: "unknown",
|
||||
}),
|
||||
latestItemOrdinal + 1,
|
||||
),
|
||||
failureItemPersisted: false,
|
||||
}),
|
||||
Ref.get(rootRunFinalized).pipe(
|
||||
Effect.flatMap((finalized) =>
|
||||
Effect.logWarning("orchestration V2 provider event ingestion failed", {
|
||||
runId: input.run.id,
|
||||
cause,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
finalized
|
||||
? Effect.void
|
||||
: Ref.get(latestProviderThread).pipe(
|
||||
Effect.flatMap((providerThread) =>
|
||||
Ref.get(latestTurnItemOrdinal).pipe(
|
||||
Effect.flatMap((latestItemOrdinal) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
...(input.shouldFinalizeRun === undefined
|
||||
? {}
|
||||
: { shouldFinalizeRun: input.shouldFinalizeRun }),
|
||||
terminal: makeFailedTerminalEvent(
|
||||
makeProviderFailure({
|
||||
cause: Cause.squash(cause),
|
||||
class: "unknown",
|
||||
}),
|
||||
latestItemOrdinal + 1,
|
||||
),
|
||||
failureItemPersisted: false,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(writeCause) =>
|
||||
new RunExecutionIngestError({
|
||||
runId: input.run.id,
|
||||
cause: { ingest: cause, write: writeCause },
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(writeCause) =>
|
||||
new RunExecutionIngestError({
|
||||
runId: input.run.id,
|
||||
cause: { ingest: cause, write: writeCause },
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(eventSubscription.close),
|
||||
|
||||
@@ -136,6 +136,19 @@ const scenarioExpectations = {
|
||||
turnCompletedCount: 0,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
subagent_v2: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
|
||||
incoming: [
|
||||
"turn/started",
|
||||
"item/completed/subAgentActivity-started",
|
||||
"turn/started/child",
|
||||
"item/completed/child-answer",
|
||||
"turn/completed",
|
||||
],
|
||||
turnStartCount: 1,
|
||||
turnCompletedCount: 2,
|
||||
approvalRequestCount: 0,
|
||||
},
|
||||
multi_turn: {
|
||||
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
|
||||
incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
|
||||
|
||||
@@ -29,6 +29,8 @@ import { subagentInput } from "./subagent/input.ts";
|
||||
import { assertCursorSubagentOutput } from "./subagent/cursor_output.ts";
|
||||
import { assertSubagentContinueOutput } from "./subagent_continue/codex_output.ts";
|
||||
import { subagentContinueInput } from "./subagent_continue/input.ts";
|
||||
import { assertSubagentV2Output } from "./subagent_v2/codex_output.ts";
|
||||
import { subagentV2Input } from "./subagent_v2/input.ts";
|
||||
import { assertClaudeThreadRollbackOutput } from "./thread_rollback/claude_output.ts";
|
||||
import { assertThreadRollbackOutput } from "./thread_rollback/codex_output.ts";
|
||||
import { threadRollbackInput } from "./thread_rollback/input.ts";
|
||||
@@ -322,6 +324,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "subagent_v2",
|
||||
buildInput: subagentV2Input,
|
||||
providers: [
|
||||
{
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
transcriptFile: new URL("./subagent_v2/codex_transcript.ndjson", import.meta.url),
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
assertOutput: assertSubagentV2Output,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "opencode_subagent",
|
||||
buildInput: openCodeSubagentInput,
|
||||
|
||||
@@ -42,6 +42,7 @@ export const MESSAGE_STEERING_INITIAL_PROMPT =
|
||||
"Respond with exactly: steering fixture initial response";
|
||||
export const SUBAGENT_PROMPT =
|
||||
"Spawn 2 subagents, one to read package.json and one to read tsconfig.json";
|
||||
export const SUBAGENT_V2_PROMPT = "just say hello";
|
||||
export const OPENCODE_SUBAGENT_PROMPT =
|
||||
"Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK.";
|
||||
export const SUBAGENT_CONTINUE_PROMPT =
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import {
|
||||
assertBaseProjection,
|
||||
assertExecutionNodeKinds,
|
||||
assertNoExtraAppRunsForProviderChildren,
|
||||
assertRunProviderTurnCardinality,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
projectionFor,
|
||||
SUBAGENT_V2_PROMPT,
|
||||
} from "../shared.ts";
|
||||
|
||||
export function assertSubagentV2Output(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertBaseProjection({
|
||||
result,
|
||||
transcript,
|
||||
runCount: 1,
|
||||
runStatuses: ["completed"],
|
||||
});
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertTurnItemTypes(projection, ["user_message", "subagent", "assistant_message"]);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "subagent"]);
|
||||
assertRunProviderTurnCardinality({ projection, rootRunCount: 1 });
|
||||
assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 1 });
|
||||
assertUserMessagesInclude(projection, [SUBAGENT_V2_PROMPT]);
|
||||
assert.lengthOf(projection.subagents, 1);
|
||||
assert.lengthOf(result.shellSnapshot.threads, 2);
|
||||
|
||||
const subagent = projection.subagents[0]!;
|
||||
assert.equal(subagent.origin, "provider_native");
|
||||
assert.equal(subagent.createdBy, "agent");
|
||||
assert.equal(subagent.driver, "codex");
|
||||
assert.equal(subagent.title, "/root/hello_agent");
|
||||
assert.equal(subagent.prompt, "");
|
||||
assert.equal(subagent.status, "completed");
|
||||
assert.equal(subagent.result, "Hello.");
|
||||
assert.isNotNull(subagent.childThreadId);
|
||||
assert.isNotNull(subagent.providerThreadId);
|
||||
assert.isNotNull(subagent.nativeTaskRef);
|
||||
assert.isNotNull(subagent.completedAt);
|
||||
if (subagent.childThreadId === null) {
|
||||
throw new Error(`Subagent ${subagent.id} is missing its child thread`);
|
||||
}
|
||||
|
||||
const providerThread = projection.providerThreads.find(
|
||||
(thread) => thread.id === subagent.providerThreadId,
|
||||
);
|
||||
assert.isDefined(providerThread);
|
||||
assert.equal(providerThread.appThreadId, subagent.childThreadId);
|
||||
assert.isNull(providerThread.ownerNodeId);
|
||||
|
||||
const childProjection = result.projections.get(subagent.childThreadId);
|
||||
assert.isDefined(childProjection);
|
||||
assert.equal(childProjection.thread.lineage.parentThreadId, projection.thread.id);
|
||||
assert.equal(childProjection.thread.lineage.relationshipToParent, "subagent");
|
||||
assert.equal(childProjection.thread.activeProviderThreadId, providerThread.id);
|
||||
assert.lengthOf(childProjection.runs, 0);
|
||||
assert.lengthOf(childProjection.providerThreads, 1);
|
||||
assert.lengthOf(childProjection.providerTurns, 1);
|
||||
assertTurnItemTypes(childProjection, ["assistant_message"]);
|
||||
assert.isTrue(
|
||||
childProjection.turnItems.some(
|
||||
(item) => item.type === "assistant_message" && item.text.includes("Hello."),
|
||||
),
|
||||
"child thread must contain the post-root subagent response",
|
||||
);
|
||||
assert.equal(childProjection.providerTurns[0]?.status, "completed");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.141.0","scenario":"subagent_v2","metadata":{"source":"observed-codex-app-server-replay-fixture","fileName":"subagent_v2.ndjson","description":"Agents-v2 Codex subagent spawn observed from a real run: parent emits subAgentActivity(started), child emits a normal turn and final agent message."}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true},"clientInfo":{"name":"t3code_desktop","title":"T3 Code Desktop","version":"0.1.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.141.0","codexHome":"/tmp/codex-home","platformFamily":"unix","platformOs":"macos"}}}
|
||||
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
|
||||
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}}
|
||||
{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"native-v2-root-thread","sessionId":"native-v2-root-thread","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1782622440,"updatedAt":1782622440,"status":{"type":"idle"},"path":"/tmp/root-thread.jsonl","cwd":"/tmp","cliVersion":"0.141.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":null,"cwd":"/tmp","instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false},"reasoningEffort":"medium"}}}
|
||||
{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"just say hello","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-v2-root-thread"}}}
|
||||
{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"native-v2-root-turn","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
|
||||
{"type":"emit_inbound","label":"thread/status/changed/root-active","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-root-thread","status":{"type":"active","activeFlags":[]}}}}
|
||||
{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"native-v2-root-thread","turn":{"id":"native-v2-root-turn","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1782622440,"completedAt":null,"durationMs":null}}}}
|
||||
{"type":"emit_inbound","label":"item/completed/root-user","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"root-user-v2","clientId":null,"content":[{"type":"text","text":"just say hello","text_elements":[]}]},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622440261}}}
|
||||
{"type":"emit_inbound","label":"thread/status/changed/child-idle-before-start","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-child-thread","status":{"type":"idle"}}}}
|
||||
{"type":"emit_inbound","label":"item/completed/subAgentActivity-started","frame":{"method":"item/completed","params":{"item":{"type":"subAgentActivity","id":"call-v2-spawn","kind":"started","agentThreadId":"native-v2-child-thread","agentPath":"/root/hello_agent"},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622442529}}}
|
||||
{"type":"emit_inbound","label":"thread/status/changed/child-active","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-child-thread","status":{"type":"active","activeFlags":[]}}}}
|
||||
{"type":"emit_inbound","label":"turn/started/child","frame":{"method":"turn/started","params":{"threadId":"native-v2-child-thread","turn":{"id":"native-v2-child-turn","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1782622442,"completedAt":null,"durationMs":null}}}}
|
||||
{"type":"emit_inbound","label":"item/completed/root-commentary","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"root-commentary-v2","text":"I spawned a subagent to say hello.","phase":"commentary","memoryCitation":null},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622443818}}}
|
||||
{"type":"emit_inbound","label":"item/started/wait-agent","frame":{"method":"item/started","params":{"item":{"type":"collabAgentToolCall","id":"wait-call-v2","tool":"wait","status":"inProgress","senderThreadId":"native-v2-root-thread","receiverThreadIds":[],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{}},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","startedAtMs":1782622444012}}}
|
||||
{"type":"emit_inbound","label":"item/completed/wait-agent","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"wait-call-v2","tool":"wait","status":"completed","senderThreadId":"native-v2-root-thread","receiverThreadIds":[],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{}},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622454013}}}
|
||||
{"type":"emit_inbound","label":"item/completed/root-answer","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"root-answer-v2","text":"Subagent spawned as `/root/hello_agent`. It hasn't returned within the short wait window yet.","phase":"final_answer","memoryCitation":null},"threadId":"native-v2-root-thread","turnId":"native-v2-root-turn","completedAtMs":1782622455859}}}
|
||||
{"type":"emit_inbound","label":"thread/status/changed/root-idle","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-root-thread","status":{"type":"idle"}}}}
|
||||
{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"native-v2-root-thread","turn":{"id":"native-v2-root-turn","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1782622440,"completedAt":1782622455,"durationMs":15598}}}}
|
||||
{"type":"emit_inbound","label":"item/completed/child-answer","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"child-answer-v2","text":"Hello.","phase":"final_answer","memoryCitation":null},"threadId":"native-v2-child-thread","turnId":"native-v2-child-turn","completedAtMs":1782622463754}}}
|
||||
{"type":"emit_inbound","label":"thread/status/changed/child-idle","frame":{"method":"thread/status/changed","params":{"threadId":"native-v2-child-thread","status":{"type":"idle"}}}}
|
||||
{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"native-v2-child-thread","turn":{"id":"native-v2-child-turn","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1782622442,"completedAt":1782622463,"durationMs":21247}}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { SUBAGENT_V2_PROMPT, type OrchestratorFixtureInput } from "../shared.ts";
|
||||
|
||||
export function subagentV2Input(): OrchestratorFixtureInput {
|
||||
return {
|
||||
steps: [{ type: "message", text: SUBAGENT_V2_PROMPT }],
|
||||
};
|
||||
}
|
||||
@@ -189,7 +189,7 @@ describe("ssh tunnel scripts", () => {
|
||||
assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
|
||||
assert.include(
|
||||
buildRemoteLaunchScript(),
|
||||
'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
|
||||
'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata-v2/server-runtime.json"',
|
||||
);
|
||||
assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
|
||||
assert.include(
|
||||
|
||||
@@ -440,7 +440,7 @@ export const REMOTE_LAUNCH_SCRIPT = `set -eu
|
||||
STATE_KEY="$1"
|
||||
STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
|
||||
DEFAULT_SERVER_HOME="$HOME/.t3"
|
||||
DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"
|
||||
DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata-v2/server-runtime.json"
|
||||
PORT_FILE="$STATE_DIR/port"
|
||||
PID_FILE="$STATE_DIR/pid"
|
||||
MANAGED_FILE="$STATE_DIR/managed"
|
||||
|
||||
Reference in new issue
Block a user