Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/server/src/binCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { serviceLauncherCommand } from "./cli/serviceLauncher.ts";
import { claudeHistoryCommand } from "./cli/claudeHistory.ts";
import { sshHelperCommand } from "./cli/sshHelper.ts";
import { serviceCommand } from "./cli/service.ts";
import { runnerCommand } from "./cli/runner.ts";
import { servicePreflightCommand } from "./cli/servicePreflight.ts";
import { themeCommand } from "./cli/theme.ts";
import { traceCommand } from "./cli/trace.ts";
Expand Down Expand Up @@ -93,6 +94,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
updateCommand,
uninstallCommand,
serviceLauncherCommand,
runnerCommand,
claudeHistoryCommand,
sshHelperCommand,

Expand Down
41 changes: 41 additions & 0 deletions apps/server/src/cli/runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// @effect-diagnostics nodeBuiltinImport:off -- the runner serves its own home directory.
import * as NodeOs from "node:os";

import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { Command, Flag } from "effect/cli";

import * as NodePtyAdapter from "../terminal/NodePtyAdapter.ts";
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
import { serveRunner } from "../runner/RunnerServer.ts";

export const runnerCommand = Command.make("runner", {
socket: Flag.String("socket").pipe(
Flag.withDescription("Unix socket to listen on. Omit under a systemd socket unit."),
Flag.optional,
),
allowRoot: Flag.String("allow-root").pipe(
Flag.withDescription("Directory outside the home that work may run in. Repeatable."),
Flag.between(0, 64),
),
}).pipe(
Command.withDescription(
"Run spawn requests from the T3 server as this user. Started by t3-runner@<user>.service.",
),
Command.withHandler(({ socket, allowRoot }) =>
Effect.gen(function* () {
const pty = yield* PtyAdapter.PtyAdapter;
const runPromise = Effect.runPromiseWith(yield* Effect.context<never>());
yield* Effect.promise(() =>
serveRunner({
...(Option.isSome(socket) ? { socketPath: socket.value } : {}),
home: NodeOs.homedir(),
allowedRoots: allowRoot,
env: process.env,
spawnPty: (input) => runPromise(pty.spawn(input)),
}),
);
return yield* Effect.never;
}).pipe(Effect.provide(NodePtyAdapter.layer)),
),
);
10 changes: 10 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ 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 { PrincipalExecution } from "../../runner/PrincipalExecution.ts";
import { spawnClaudeViaRunner } from "../../runner/RunnerClient.ts";

import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts";
Expand Down Expand Up @@ -955,6 +957,7 @@ export const layerQueryRunner: Layer.Layer<
const runFork = Effect.runForkWith(yield* Effect.context<never>());
const hostEnvironment = yield* HostProcess.Environment;
const portDiscovery = yield* PortScanner.PortDiscovery;
const execution = yield* PrincipalExecution;

return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: crypto
Expand Down Expand Up @@ -988,8 +991,12 @@ export const layerQueryRunner: Layer.Layer<
},
};
// The SDK can prepend a scope wrapper to native binaries; script entries run through node.
const runner = yield* execution
.runnerFor(input.threadId)
.pipe(Effect.mapError((cause) => queryRunnerError(cause, "runner")));
const binaryPath = queryOptions.pathToClaudeCodeExecutable;
const launch =
runner !== undefined ||
binaryPath === undefined ||
CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
? undefined
Expand All @@ -1014,6 +1021,9 @@ export const layerQueryRunner: Layer.Layer<
const spawnProcess =
options.spawnClaudeCodeProcess ??
((spawnOptions: ClaudeSpawnOptions) => {
if (runner !== undefined) {
return spawnClaudeViaRunner(runner, spawnOptions, options.stderr) as ClaudeSpawnedProcess;
}
if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope);
const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
cwd: spawnOptions.cwd,
Expand Down
18 changes: 16 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { PrincipalExecution, passthroughAgentScope } from "../../runner/PrincipalExecution.ts";

import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts";
import * as PortScanner from "../../preview/PortScanner.ts";
Expand Down Expand Up @@ -1523,10 +1524,21 @@ export const layerAppServerClientFactory: Layer.Layer<
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers;
const agentScope = yield* AgentScope;
const execution = yield* PrincipalExecution;

return CodexAppServerClientFactory.of({
open: Effect.fn("CodexAdapterV2.open")(function* (input) {
const scope = yield* Scope.Scope;
const runnerSpawner = yield* execution.spawnerFor(input.threadId).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterOpenSessionError({
driver: CODEX_PROVIDER,
providerSessionId: input.providerSessionId,
cause,
}),
),
);
const environment = {
...codexAppServerEnvironment(input.environment),
...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}),
Expand All @@ -1538,8 +1550,10 @@ export const layerAppServerClientFactory: Layer.Layer<
),
env: environment,
threadId: input.threadId,
}).pipe(Effect.provideService(AgentScope, agentScope));
const handle = yield* spawner.spawn(command).pipe(
}).pipe(
Effect.provideService(AgentScope, runnerSpawner ? passthroughAgentScope : agentScope),
);
const handle = yield* (runnerSpawner ?? spawner).spawn(command).pipe(
Effect.provideService(Scope.Scope, scope),
Effect.mapError(
(cause) =>
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,10 @@ export interface ProjectionStoreV2Shape {
readonly getThreadsWithPullRequests: (
threadId?: ThreadId,
) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequests>, ProjectionStoreV2Error>;
/** Non-default principals owning a thread whose worktree is `cwd` or contains it. */
readonly getWorktreeOwners: (
cwd: string,
) => Effect.Effect<ReadonlyArray<string>, ProjectionStoreV2Error>;
readonly getThreadWorktreePaths: (options?: {
readonly includeArchived?: boolean;
}) => Effect.Effect<
Expand Down Expand Up @@ -6478,6 +6482,24 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
);

// ponytail: scans threads with a non-default owner per call; index owner and worktree if it shows up in profiles.
const getWorktreeOwners: ProjectionStoreV2Shape["getWorktreeOwners"] = (cwd) =>
sql<{ readonly owner: string }>`
SELECT DISTINCT json_extract(payload_json, '$.ownerPrincipal') AS owner
FROM orchestration_v2_projection_threads
WHERE deleted_at IS NULL
AND json_extract(payload_json, '$.ownerPrincipal') IS NOT NULL
AND json_extract(payload_json, '$.ownerPrincipal') != ${DEFAULT_PRINCIPAL_ID}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the default principal in worktree owner conflicts

If a default-owned thread and a non-default thread share a worktree path, this filter omits the default owner, leaving only the non-default owner in the result. spawnerForPath then routes Git and other processes for that path through the non-default user instead of failing closed, so include default ownership when detecting ambiguous paths.

Useful? React with 👍 / 👎.

AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
AND (
${cwd} = json_extract(payload_json, '$.worktreePath')
OR substr(${cwd}, 1, length(json_extract(payload_json, '$.worktreePath')) + 1) = json_extract(payload_json, '$.worktreePath') || '/'
)
`.pipe(
Effect.map((rows) => rows.map((row) => row.owner)),
Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
);

const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = (options) =>
sql<{ readonly thread_id: string; readonly worktree_path: string }>`
SELECT thread_id, json_extract(payload_json, '$.worktreePath') AS worktree_path
Expand Down Expand Up @@ -7094,6 +7116,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
getThread: readOnReader(getThread),
getSettlementCandidates: readOnReader(getSettlementCandidates),
getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests),
getWorktreeOwners: readOnReader(getWorktreeOwners),
getThreadWorktreePaths: readOnReader(getThreadWorktreePaths),
getOpenRemoteDelegatedTasks: getOpenRemoteDelegatedTasks.pipe(NodeSqliteClient.readOnly),
getThreadProjection,
Expand Down
12 changes: 12 additions & 0 deletions apps/server/src/orchestration-v2/ProviderSessionManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AgentScope } from "@t3tools/shared/AgentScope";
import { PrincipalExecution, requireRunnerSupport } from "../runner/PrincipalExecution.ts";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import {
Expand Down Expand Up @@ -346,6 +347,7 @@ export const layerWithOptions = (
const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
const agentScope = yield* AgentScope;
const principalExecution = yield* PrincipalExecution;
const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")(
function* (threadId: ThreadId) {
if (Option.isNone(serverSettings)) return { browser: true, device: false };
Expand Down Expand Up @@ -2165,6 +2167,16 @@ export const layerWithOptions = (
}),
),
);
yield* requireRunnerSupport(principalExecution, input.threadId, adapter.driver).pipe(
Effect.mapError(
(cause) =>
new ProviderSessionOpenError({
instanceId: input.modelSelection.instanceId,
providerSessionId: input.providerSessionId,
cause,
}),
),
);
const prepared = yield* prepareMcpSession(
input.threadId,
input.modelSelection.instanceId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ it.effect(
getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),
getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
getWorktreeOwners: () => Effect.die("unused getWorktreeOwners"),
getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"),
getThreadProjection: () => Effect.die("control effects must not load transcript"),
getTurnStartContext: () => Effect.die("unused"),
Expand Down
27 changes: 26 additions & 1 deletion apps/server/src/processRunner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as Context from "effect/Context";
import { PrincipalExecution } from "./runner/PrincipalExecution.ts";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -390,8 +391,32 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
export const make = Effect.fn("ProcessRunner.make")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;

const execution = yield* PrincipalExecution;

const run: ProcessRunner["Service"]["run"] = (input) =>
finalizeRunProcess(runProcessCore(spawner, input), input);
finalizeRunProcess(
Effect.gen(function* () {
const cwd = input.spawnCwd ?? input.cwd;
const runnerSpawner = cwd === undefined ? undefined : yield* execution.spawnerForPath(cwd);
return yield* runProcessCore(runnerSpawner ?? spawner, input);
}).pipe(
Effect.catchTag("RunnerUnavailableError", (cause) =>
Effect.fail(
new ProcessSpawnError({
command: input.command,
argumentCount: input.args.length,
cwd: input.cwd,
spawnCwd: input.spawnCwd,
resolvedCommand: input.command,
resolvedArgumentCount: input.args.length,
shell: false,
cause,
}),
),
),
),
input,
);

return ProcessRunner.of({
run,
Expand Down
Loading
Loading