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
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ describe("mobile project settings scope", () => {
...DEFAULT_SERVER_SETTINGS,
agentToolCapabilities: ["quality-records"],
projectSettingsOverrides: {
[firstProject]: { agentToolCapabilities: [], enableMemoryAutoRecall: true },
[firstProject]: { agentToolCapabilities: ["automation"], enableMemoryAutoRecall: true },
[secondProject]: { defaultAutoPull: true },
},
};
Expand All @@ -97,7 +97,7 @@ describe("mobile project settings scope", () => {
patch: {
projectSettingsOverrides: {
[firstProject]: {
agentToolCapabilities: ["memory"],
agentToolCapabilities: ["memory", "automation"],
enableMemoryAutoRecall: true,
},
[secondProject]: {
Expand All @@ -122,7 +122,7 @@ describe("mobile project settings scope", () => {
}),
environment(secondId, {
...DEFAULT_SERVER_SETTINGS,
agentToolCapabilities: [],
agentToolCapabilities: ["automation"],
}),
],
null,
Expand All @@ -131,7 +131,7 @@ describe("mobile project settings scope", () => {
planMobileAgentToolCapability(targets, false, "memory", false).map(
(write) => write.patch.agentToolCapabilities,
),
).toEqual([["quality-records"], []]);
).toEqual([["quality-records"], ["automation"]]);
});
it("edits each checkout's own override without changing either environment default", () => {
const firstSettings: ServerSettings = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ import * as ProviderSessionDirectory from "../src/provider/Services/ProviderSess
import * as ProviderSessionReaper from "../src/provider/Services/ProviderSessionReaper.ts";
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
import * as ServerLifecycleEvents from "../src/serverLifecycleEvents.ts";
import { parityStartupDependenciesLayer } from "../src/testUtils/parityDependencies.ts";
import * as BackgroundPolicy from "../src/background/BackgroundPolicy.ts";
import * as HostPowerMonitor from "../src/background/HostPowerMonitor.ts";
import * as ServerRuntimeStartup from "../src/serverRuntimeStartup.ts";
import * as ServerSettings from "../src/serverSettings.ts";
import * as AnalyticsService from "../src/telemetry/AnalyticsService.ts";
Expand Down Expand Up @@ -259,7 +262,13 @@ it.effect(

const secondRuntime = makePersistedRuntimeLayer(config.dbPath);
const startupLayer = ServerRuntimeStartup.layer.pipe(
Layer.provideMerge(parityStartupDependenciesLayer),
Layer.provideMerge(secondRuntime),
Layer.provideMerge(
BackgroundPolicy.layer.pipe(
Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())),
),
),
Layer.provideMerge(startupDependencies),
);

Expand Down
12 changes: 12 additions & 0 deletions apps/server/src/auth/RpcAuthorization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ describe("RPC authorization scopes", () => {
WS_METHODS.memoryRelated,
WS_METHODS.qualityRead,
WS_METHODS.qualitySubscribeChanges,
WS_METHODS.scheduledList,
WS_METHODS.scheduledGet,
WS_METHODS.ambientGet,
WS_METHODS.backgroundJobList,
WS_METHODS.backgroundJobOutput,
WS_METHODS.backgroundJobWait,
])
expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationReadScope);
for (const method of [
Expand All @@ -33,6 +39,11 @@ describe("RPC authorization scopes", () => {
WS_METHODS.memoryRemember,
WS_METHODS.memoryForget,
WS_METHODS.qualityUpdate,
WS_METHODS.scheduledCreate,
WS_METHODS.scheduledCancel,
WS_METHODS.backgroundJobStart,
WS_METHODS.backgroundJobCancel,
WS_METHODS.backgroundJobSubscribe,
])
expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope);
});
Expand All @@ -41,6 +52,7 @@ describe("RPC authorization scopes", () => {
for (const method of [
WS_METHODS.unattendedGrantCreate,
WS_METHODS.unattendedGrantRevoke,
WS_METHODS.ambientConfigure,
WS_METHODS.memoryGlobalRead,
WS_METHODS.memoryGlobalWrite,
])
Expand Down
15 changes: 15 additions & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,24 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.coordinationMailboxRead]: AuthOrchestrationReadScope,
[WS_METHODS.coordinationMailboxWrite]: AuthOrchestrationOperateScope,
[WS_METHODS.qualitySubscribeChanges]: AuthOrchestrationReadScope,
[WS_METHODS.ambientConfigure]: AuthAccessWriteScope,
[WS_METHODS.ambientGet]: AuthOrchestrationReadScope,
[WS_METHODS.ambientStop]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledCreate]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledList]: AuthOrchestrationReadScope,
[WS_METHODS.scheduledGet]: AuthOrchestrationReadScope,
[WS_METHODS.scheduledCancel]: AuthOrchestrationOperateScope,
[WS_METHODS.unattendedGrantCreate]: AuthAccessWriteScope,
[WS_METHODS.unattendedGrantList]: AuthOrchestrationReadScope,
[WS_METHODS.unattendedGrantRevoke]: AuthAccessWriteScope,
[WS_METHODS.backgroundJobStart]: AuthOrchestrationOperateScope,
[WS_METHODS.backgroundJobList]: AuthOrchestrationReadScope,
[WS_METHODS.backgroundJobGet]: AuthOrchestrationReadScope,
[WS_METHODS.backgroundJobOutput]: AuthOrchestrationReadScope,
[WS_METHODS.backgroundJobWait]: AuthOrchestrationReadScope,
[WS_METHODS.backgroundJobCancel]: AuthOrchestrationOperateScope,
[WS_METHODS.backgroundJobSubscribe]: AuthOrchestrationOperateScope,
[WS_METHODS.backgroundJobCleanup]: AuthOrchestrationOperateScope,
[WS_METHODS.memoryRemember]: AuthOrchestrationOperateScope,
[WS_METHODS.memoryRecall]: AuthOrchestrationReadScope,
[WS_METHODS.memorySearch]: AuthOrchestrationReadScope,
Expand Down
138 changes: 138 additions & 0 deletions apps/server/src/background/BackgroundJobAuthority.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { CommandId, EventId, type ThreadId } from "@t3tools/contracts";
import { BackgroundJobError } from "../../../../packages/contracts/src/backgroundJobs.ts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Option from "effect/Option";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
import * as UnattendedGrants from "../orchestration/UnattendedGrants.ts";
import * as ScheduledWork from "../orchestration/ScheduledWork.ts";
import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
import { BackgroundJobAuthority } from "./BackgroundJobs.ts";

const make = Effect.gen(function* () {
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const paths = yield* WorkspacePaths.WorkspacePaths;
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
const grants = yield* UnattendedGrants.UnattendedGrants;
const scheduled = yield* ScheduledWork.ScheduledWork;
const capabilities = yield* McpInvocationContext.makeThreadMcpCapabilities;
const wrap = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.mapError((cause) =>
Schema.is(BackgroundJobError)(cause)
? cause
: new BackgroundJobError({
code: "internal",
detail: "Host-job authority operation failed.",
cause,
}),
),
);
const findGrant = (caller: ThreadId) =>
wrap(
Effect.gen(function* () {
const invocation = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext);
const persisted = yield* snapshots.getThreadActivationAuthority(caller);
const retained =
(Option.isSome(invocation) ? invocation.value.unattendedAuthority : undefined) ??
Option.getOrUndefined(persisted);
const available = yield* grants.list({ callerThreadId: caller });
const grant = available.find(
(entry) =>
!entry.revoked &&
entry.hostJobs &&
(!retained ||
(entry.id === retained.grantId &&
entry.revision === retained.grantRevision &&
retained.ownerThreadId === caller &&
retained.mcpCapabilityCeiling.includes("background-jobs"))),
);
if (!grant)
return yield* new BackgroundJobError({
code: "forbidden",
detail: "Explicit client host-job consent is required.",
});
return grant;
}),
);
const authorize = (caller: ThreadId) =>
wrap(
Effect.gen(function* () {
const state = yield* snapshots.getWorkerState(caller);
if (Option.isNone(state))
return yield* new BackgroundJobError({
code: "not-found",
detail: "Host-job owner is unavailable.",
});
if (state.value.thread.worker?.stopRequestedAt != null)
return yield* new BackgroundJobError({
code: "forbidden",
detail: "Stopped workers cannot execute host jobs.",
});
const access = yield* capabilities(caller);
if (!access?.has("background-jobs"))
return yield* new BackgroundJobError({
code: "forbidden",
detail: "Host-job capability is disabled for this project or worker.",
});
const grant = yield* findGrant(caller);
if (grant.projectId !== state.value.thread.projectId)
return yield* new BackgroundJobError({
code: "forbidden",
detail: "Host-job consent belongs to another project.",
});
const project = yield* snapshots.getProjectShellById(state.value.thread.projectId);
if (Option.isNone(project))
return yield* new BackgroundJobError({
code: "not-found",
detail: "Host-job project is unavailable.",
});
const cwd = yield* paths.normalizeWorkspaceRoot(
state.value.thread.worktreePath ?? project.value.workspaceRoot,
);
return { projectId: project.value.id, cwd };
}),
);
return BackgroundJobAuthority.of({
authorize,
notify: (record, subscription) =>
wrap(
Effect.gen(function* () {
const key = `job-terminal:${record.id}:${subscription.callerThreadId}`;
if (subscription.notify)
yield* engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.make(key),
threadId: subscription.callerThreadId,
activity: {
id: EventId.make(key),
tone: record.state === "completed" ? "info" : "error",
kind: "background-job.terminal",
summary: `Background job ${record.id}: ${record.state}`,
payload: { jobId: record.id, state: record.state, exitCode: record.exitCode },
turnId: null,
createdAt: record.updatedAt,
},
createdAt: record.updatedAt,
});
if (subscription.wake) {
yield* authorize(subscription.callerThreadId);
const grant = yield* findGrant(subscription.callerThreadId);
yield* scheduled.create({
id: key,
callerThreadId: subscription.callerThreadId,
target: { type: "resume", threadId: subscription.callerThreadId },
prompt: `Background job ${record.id} finished with state ${record.state}. Retrieve its bounded output if needed.`,
delayMs: 0,
onBusy: "wait",
grantId: grant.id,
});
}
}),
),
});
});
export const layer = Layer.effect(BackgroundJobAuthority, make);
Loading
Loading