Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Keep authorized resources continuous across Open conversations (#1552)

Joshua Francedb7afbf1de70
diff --git a/README.md b/README.md
index 1dff5d455..5b5f3f269 100644
--- a/README.md
+++ b/README.md
@@ -125,11 +125,19 @@ Sharing posture is independent:
The organization value is a ceiling, and personal and room scopes can opt out; Isolated
wins. “Follow organization” removes a personal or room override. Disabled memory recall
-and writable-only recall still apply. Open does not mount a personal workspace into a room, carry credentials or message
-history, widen writes, run in automation or ambient turns, cross organizations, add a
-teammate's entitlement, or weaken screening, command approvals, or egress. It can still
-reveal private information in a shared reply, so cross-context reads are provenance-labelled
-and audited.
+and writable-only recall still apply. Authenticated human-authored ambient turns use the same
+Open access as direct requests. The speaker can use their own connections on an isolated
+owner-auth computer and target their authorized sandboxes across conversations.
+Open shared crons can retain the owner's resource access and allow member edits, with a brief
+private notification to the owner. Membership and posture are rechecked rather than treating
+a saved conversation reference as permanent access. Scheduled owner access authorized through
+Open stops when Open is withdrawn; changing a job's text does not reset that requirement.
+
+Open does not mount a personal workspace into the shared computer, expose credentials to
+other participants, carry message history, cross organizations, or weaken screening, command
+approvals, or egress. File read/write and publication retain their own permissions.
+It can still reveal private information in a shared reply, so cross-context reads are
+provenance-labelled and audited.
[`SECURITY.md`](./SECURITY.md) has the threat model, the operator assumptions, and the
known limitations.
diff --git a/docs/sandbox-resources.md b/docs/sandbox-resources.md
index 9ceef60bf..46f00b12c 100644
--- a/docs/sandbox-resources.md
+++ b/docs/sandbox-resources.md
@@ -6,7 +6,7 @@ Before activation, agents have `execute`, `background`, and `sandbox` with `stat
`sandbox` actions `exec` and `start_process` accept `sandbox_id`. Without a target, execution requires the scope's stored default after activation. `set_default` accepts an ID or null; null clears the default. A new scope has no default. Retiring a sandbox requires clearing its default and stopping its jobs first. Retirement is available only for providers with direct scope deletion. It never provisions or restores a machine. Once retirement begins, execution stays blocked; interrupted or failed cleanup remains visible and can be retried. Retirement deletes its working state, so durable outputs should be published to Files or git beforehand.
-The initial agent interface restricts inventory and operations to the current owning scope, in addition to actor authorization. It does not yet offer cross-conversation access to every resource a person can access. Provider-native recovery status includes its own expiry; a sandbox record is not an indefinite backup guarantee.
+In Isolated posture, agent inventory and operations stay in the current owning scope. In Open posture, authenticated human turns and owner-authorized scheduled turns can also target the acting person's personal sandboxes and Open shared sandboxes where they are a current member. Access is rechecked for each operation; changing conversations does not transfer ownership or grant other participants personal access. Cross-context execution uses the target's existing workspace without copying the calling conversation's credentials, files, or capability tokens onto it. Defaults remain local to their owning scope. Cross-context commands must satisfy both the calling conversation's and target sandbox's command policies. Network access is narrowed to satisfy both egress policies. Provider-native recovery status includes its own expiry; a sandbox record is not an indefinite backup guarantee.
## Agent actions
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index 7e44dc095..ce53c6255 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -20,6 +20,7 @@ import { pickMatch, type DirectoryMember } from "../directory/directory-store.ts
import { externalMemberActive } from "../identity/external-members.ts";
import { hasRevisionEvents, recordMessageRevisions } from "../core/message-revisions.ts";
import { answerWebContextRequest } from "./web-context.ts";
+import { isOpenScopeMember } from "../resolution/sharing-access.ts";
import { availableRuntimeError, validateRuntimeChoice } from "./runtime-config.ts";
import { assertCronRuntime } from "../cron/runtime.ts";
import type { Cron } from "../types.ts";
@@ -123,6 +124,8 @@ export function createMessagingMethods(
| "resolveReachTarget"
> {
const { adminBase, resolveReachTargetFor } = h;
+ const openMember = (actorId: string, scope: ScopeId) =>
+ isOpenScopeMember({ actorId, scope, config: deps.config, isCurrentSharedScopeMember: h.principalCanWriteScope });
const { judgeAmbientContainer, ambientSelf } = ambient;
const contextRequests = deps.contextRequests ?? createMemoryMap<SurfaceContextRequest>();
const contextRequestListeners = new Set<(request: SurfaceContextRequest) => void>();
@@ -172,7 +175,10 @@ export function createMessagingMethods(
if (input.runAs === "scopeShared") {
if (input.ownerScopeId.startsWith("personal:"))
throw new Error("scopeShared requires a shared (channel/group) scope, not a personal one");
- if (!input.members?.length) throw new Error("scopeShared requires a member snapshot");
+ const open = await openMember(input.owner, input.ownerScopeId);
+ if (!input.members?.length && !open)
+ throw new Error("scopeShared requires a member snapshot or current Open scope membership");
+ if (open) input = { ...input, ownerResourcesRequireOpen: true };
}
const cron = await deps.crons.create(input);
deps.auditLog.record({
@@ -221,7 +227,10 @@ export function createMessagingMethods(
if (before.ownerScopeId.startsWith("personal:"))
throw new Error("scopeShared requires a shared (channel/group) scope, not a personal one");
const members = patch.members ?? before.members;
- if (!members?.length) throw new Error("scopeShared requires a member snapshot");
+ const open = await openMember(before.owner, before.ownerScopeId);
+ if (!members?.length && !open)
+ throw new Error("scopeShared requires a member snapshot or current Open scope membership");
+ if (open) patch = { ...patch, ownerResourcesRequireOpen: true };
}
const grantsReaffirmed = patch.unattendedGrants !== undefined;
const guardedPatch =
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index 3ff7ec56c..0abe9a362 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -18,6 +18,7 @@ import { samePerson } from "../directory/person.ts";
import { AdminError } from "../admin/admin-service.ts";
import { type ArtifactHome } from "./artifact-share.ts";
import { randomUUID } from "node:crypto";
+import { isOpenScopeMember } from "../resolution/sharing-access.ts";
import { MAX_ATTACHMENT_BYTES, mimeFromName, safeAttachmentName } from "../core/attachments.ts";
import { projectIdFromGroupRef, projectScopeId } from "../projects/project-store.ts";
@@ -74,6 +75,8 @@ export function createSessionMethods(
| "setProjectSlackChannel"
| "listScopeResources"
| "managesScope"
+ | "isOpenScopeMember"
+ | "isCurrentSharedScopeMember"
| "membershipControlsScope"
| "authorizesCapabilityScope"
| "updateSession"
@@ -729,6 +732,22 @@ export function createSessionMethods(
return principalCanManageScope(principalId, scope);
},
+ isCurrentSharedScopeMember(principalId, scope) {
+ const { kind } = parseScopeId(scope);
+ return kind === "channel" || kind === "group"
+ ? principalCanWriteScope(principalId, scope)
+ : Promise.resolve(false);
+ },
+
+ isOpenScopeMember(principalId, scope) {
+ return isOpenScopeMember({
+ actorId: principalId,
+ scope,
+ config: deps.config,
+ isCurrentSharedScopeMember: principalCanWriteScope,
+ });
+ },
+
membershipControlsScope(scope) {
return membershipControlsScope(scope);
},
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 959f616fd..60c368d9a 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -401,6 +401,8 @@ export interface App {
): Promise<FileListItem | null>;
listScopeResources(principalId: string, scope: ScopeId): Promise<ScopeResources | null>;
managesScope(principalId: string, scope: ScopeId): Promise<boolean>;
+ isCurrentSharedScopeMember(principalId: string, scope: ScopeId): Promise<boolean>;
+ isOpenScopeMember(principalId: string, scope: ScopeId): Promise<boolean>;
membershipControlsScope(scope: ScopeId): Promise<boolean>;
authorizesCapabilityScope(
claims: Pick<CapabilityClaims, "actorId" | "scopeId" | "scopeVersion" | "botActor" | "liveActor" | "members">,
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index bd26a4822..be4505db9 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -177,16 +177,20 @@ export interface ControlService {
}
export async function canAdministerCron(
- app: Pick<App, "membershipControlsScope" | "managesScope" | "samePerson">,
+ app: Pick<
+ App,
+ "membershipControlsScope" | "managesScope" | "samePerson" | "isCurrentSharedScopeMember" | "isOpenScopeMember"
+ >,
cron: Cron,
actorId: string,
callerScopeId?: ScopeId,
isActor?: (id: string) => Promise<boolean>,
): Promise<boolean> {
if (await app.membershipControlsScope(cron.ownerScopeId)) return app.managesScope(actorId, cron.ownerScopeId);
+ if (await (isActor ? isActor(cron.owner) : app.samePerson(cron.owner, actorId))) return true;
const team = cron.runAs === "scopeFloor" || cron.runAs === "scopeShared";
- if (!team && (await (isActor ? isActor(cron.owner) : app.samePerson(cron.owner, actorId)))) return true;
- if (team && cron.ownerScopeId === callerScopeId) return true;
+ if (team && cron.ownerScopeId === callerScopeId) return app.isCurrentSharedScopeMember(actorId, cron.ownerScopeId);
+ if (team && (await app.isOpenScopeMember(actorId, cron.ownerScopeId))) return true;
return app.managesScope(actorId, cron.ownerScopeId);
}
@@ -234,11 +238,14 @@ function cronPatchChanges(before: Cron, patch: CronPatch): boolean {
}
export async function resolveRunAsChange(
- app: Pick<App, "samePerson">,
+ app: Pick<App, "samePerson" | "isOpenScopeMember">,
before: Cron,
reqRunAs: "owner" | "scopeFloor" | "scopeShared" | undefined,
capability: { actorId: string; scopeId: string; members?: Principal[]; privateScope?: boolean },
-): Promise<{ ok: true; patch: Pick<CronPatch, "runAs" | "members"> } | ControlErr<"bad_request" | "forbidden">> {
+): Promise<
+ | { ok: true; patch: Pick<CronPatch, "runAs" | "members" | "ownerResourcesRequireOpen"> }
+ | ControlErr<"bad_request" | "forbidden">
+> {
const current = before.runAs ?? "owner";
if (reqRunAs === undefined || reqRunAs === current) return { ok: true, patch: {} };
if (!(await app.samePerson(capability.actorId, before.owner))) {
@@ -256,25 +263,36 @@ export async function resolveRunAsChange(
message: "a team mode needs a shared scope — this cron is personal (only you can use or edit it)",
};
}
- if (!(capability.members && capability.members.length > 0)) {
+ const openShared =
+ capability.scopeId === before.ownerScopeId &&
+ (await app.isOpenScopeMember(capability.actorId, before.ownerScopeId));
+ if (!(capability.members && capability.members.length > 0) && !(reqRunAs === "scopeShared" && openShared)) {
return {
ok: false,
code: "bad_request",
message: "switching to a team mode needs this conversation's member list — do it from the cron's channel",
};
}
- if (reqRunAs === "scopeShared" && !scopeIsMembershipControlled(before.ownerScopeId, capability)) {
+ if (reqRunAs === "scopeShared" && !scopeIsMembershipControlled(before.ownerScopeId, capability) && !openShared) {
return {
ok: false,
code: "bad_request",
- message: "scopeShared needs a private channel or group DM — change the mode from inside the cron's scope",
+ message:
+ "scopeShared needs a private or Open shared conversation you belong to — change the mode from inside the cron's scope",
};
}
- return { ok: true, patch: { runAs: reqRunAs, members: capability.members } };
+ return {
+ ok: true,
+ patch: {
+ runAs: reqRunAs,
+ members: capability.members,
+ ...(reqRunAs === "scopeShared" && openShared ? { ownerResourcesRequireOpen: true } : {}),
+ },
+ };
}
async function patchFromCronPatchRequest(
- app: Pick<App, "samePerson">,
+ app: Pick<App, "samePerson" | "isOpenScopeMember">,
before: Cron,
req: CronPatchRequest,
capability: CapabilityClaims,
@@ -335,14 +353,12 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
cron: Cron,
cap: CapabilityClaims,
changeSummary: string[],
- editFingerprint: string,
detail?: CronEditDetail,
): Promise<void> =>
notifyOwnerOfCronEdit(app, {
cron,
editorId: cap.actorId,
changeSummary,
- editFingerprint,
...(detail ? { detail } : {}),
});
return {
@@ -461,12 +477,15 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
}
const haveMembers = !!(capability.members && capability.members.length > 0);
+ const openShared =
+ ownerScopeId === capability.scopeId && (await app.isOpenScopeMember(capability.actorId, ownerScopeId));
const eligibleForShared =
- !ownerScopeId.startsWith("personal:") && scopeIsMembershipControlled(ownerScopeId, capability);
- let runAs: "owner" | "scopeFloor" | "scopeShared" = "owner";
+ !ownerScopeId.startsWith("personal:") && (scopeIsMembershipControlled(ownerScopeId, capability) || openShared);
+ let runAs: "owner" | "scopeFloor" | "scopeShared" =
+ req.runAs === undefined && openShared ? "scopeShared" : "owner";
if (req.runAs === "scopeFloor") runAs = "scopeFloor";
else if (req.runAs === "scopeShared") runAs = "scopeShared";
- if ((runAs === "scopeFloor" || runAs === "scopeShared") && !haveMembers) {
+ if ((runAs === "scopeFloor" || (runAs === "scopeShared" && !openShared)) && !haveMembers) {
return {
ok: false,
code: "members_unavailable",
@@ -479,7 +498,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
ok: false,
code: "bad_request",
message:
- "scopeShared needs a private channel or group DM you're in — not a public channel, a DM, or a different named channel",
+ "scopeShared needs a private or Open shared conversation you belong to — not a DM or a different named channel",
};
}
if (req.unattendedGrants !== undefined) {
@@ -521,6 +540,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
? { recipientConsent: { recipientId: consentRecipient, status: "pending" as const } }
: {}),
...(runAs === "scopeFloor" || runAs === "scopeShared" ? { runAs, members: capability.members } : {}),
+ ...(runAs === "scopeShared" && openShared ? { ownerResourcesRequireOpen: true } : {}),
...(req.unattendedGrants !== undefined ? { unattendedGrants: req.unattendedGrants } : {}),
};
try {
@@ -625,7 +645,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
if (patch.runAs !== undefined) changeSummary.push(`mode=${patch.runAs}`);
const detail: CronEditDetail =
req.schedule !== undefined ? { schedule: withDefaultTimezone(req.schedule, capability) } : {};
- await notifyEdit(cron, capability, changeSummary, JSON.stringify(patch), detail);
+ await notifyEdit(cron, capability, changeSummary, detail);
return { ok: true, cron };
} catch (e) {
return { ok: false, code: "cron_update_failed", message: errMessage(e) };
@@ -681,7 +701,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
...(ownFire ? {} : { by: capability.actorId }),
});
if (outcome === "missing") return { ok: false, code: "not_found", message: `no cron ${id}` };
- if (outcome === "applied" && !ownFire) await notifyEdit(cron, capability, ["note"], flattened);
+ if (outcome === "applied" && !ownFire) await notifyEdit(cron, capability, ["note"]);
return { ok: true, applied: outcome === "applied" };
},
@@ -691,7 +711,7 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
if (!(await canAdministerCron(app, cron, capability.actorId, capability.scopeId)))
return { ok: false, code: "forbidden", message: "not your cron" };
await app.deleteCron(id);
- await notifyEdit(cron, capability, ["deleted"], "deleted");
+ await notifyEdit(cron, capability, ["deleted"]);
return { ok: true };
},
@@ -704,8 +724,9 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
const refusal = await unattendedGrantRefusal(app, admin, cron, capability);
if (refusal) return { ok: false, code: "forbidden", message: refusal };
}
+ if (cron.enabled === enabled) return { ok: true, cron };
await app.setCronEnabled(id, enabled);
- await notifyEdit(cron, capability, [`enabled=${enabled}`], `enabled=${enabled}`);
+ await notifyEdit(cron, capability, [`enabled=${enabled}`]);
const after = await app.getCron(id);
return { ok: true, cron: after ?? cron };
},
@@ -756,15 +777,10 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
message: "destinationKey is not one of the destinations available for this conversation",
};
}
+ if (isDeepStrictEqual(cron.destination, resolved.destination)) return { ok: true, cron };
const updated = await app.setCronDestination(id, resolved.destination);
const destLabel = capability.destinations?.find((d) => d.key === destinationKey)?.label;
- await notifyEdit(
- cron,
- capability,
- ["destination"],
- `destination:${resolved.destination?.target ?? ""}`,
- destLabel ? { destinationLabel: destLabel } : undefined,
- );
+ await notifyEdit(cron, capability, ["destination"], destLabel ? { destinationLabel: destLabel } : undefined);
return { ok: true, cron: updated ?? cron };
},
diff --git a/src/api/routes/admin/artifacts.ts b/src/api/routes/admin/artifacts.ts
index 73b89362c..dfce328fe 100644
--- a/src/api/routes/admin/artifacts.ts
+++ b/src/api/routes/admin/artifacts.ts
@@ -1,3 +1,4 @@
+import { isDeepStrictEqual } from "node:util";
import { isCronRuntime } from "../../../cron/runtime.ts";
import { errMessage } from "../../../util/errors.ts";
import { parseScopeId, type Destination } from "../../../types.ts";
@@ -145,12 +146,13 @@ export async function putAdminCronDestination(ctx: ApiCtx): Promise<void> {
});
}
const next = destination === null ? undefined : destination;
+ if (isDeepStrictEqual(cron.destination, next))
+ return sendJson(res, 200, { cron: { id: cron.id, destination: cron.destination } });
const updated = await app.setCronDestination(id, next);
await notifyOwnerOfCronEdit(app, {
cron,
editorId: actor.id,
changeSummary: ["destination"],
- editFingerprint: `destination:${next?.target ?? "cleared"}`,
});
audit(deps, {
principalId: actor.id,
diff --git a/src/api/routes/turns.ts b/src/api/routes/turns.ts
index 6ef825f76..4601a2ea7 100644
--- a/src/api/routes/turns.ts
+++ b/src/api/routes/turns.ts
@@ -18,7 +18,7 @@ function isTurnRequest(body: unknown): body is TurnRequest {
function publicOrigin(origin: TurnOrigin | undefined): TurnOrigin | undefined {
if (origin?.kind !== "automation") return origin;
- const { useOwnerKeychain: _internalOnly, ...safe } = origin;
+ const { useOwnerKeychain: _internalOnly, ownerResourcesRequireOpen: _requireOpen, ...safe } = origin;
return safe;
}
@@ -39,6 +39,7 @@ function publicTurnOrigin(body: TurnRequest): { origin?: TurnOrigin; error?: str
function sanitizedTurnRequest(body: TurnRequest): { request: TurnRequest } | { error: string } {
const {
ownerKeychainUnion: _ownerKeychainUnion,
+ ownerResourcesRequireOpen: _ownerResourcesRequireOpen,
spawned: _spawned,
unattendedGrants: _unattendedGrants,
redeliveryKey: _redeliveryKey,
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 08d6e6e88..f24a2439f 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -203,6 +203,8 @@ import { createCompaction } from "./orchestrator/compaction.ts";
import { startLeaseKeepalive } from "./orchestrator/lease-keepalive.ts";
import { createSecurityClassifier } from "./orchestrator/security-screen.ts";
import { createTurnSandboxes } from "./orchestrator/sandboxes.ts";
+import type { EgressPolicy } from "../types.ts";
+import { isOpenScopeMember } from "../resolution/sharing-access.ts";
import { createSurfaceToolDeps, type SpineState } from "./orchestrator/surface-tools.ts";
import { createAttachStaging } from "./orchestrator/attach-tool.ts";
import { reconcileMessageRevisions, revisionAnchorAt } from "./message-revisions.ts";
@@ -1313,21 +1315,18 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (!resolution.approvalGrantModes[grant.scope]) continue;
commandUses.set(grant.approvalKey ?? grant.command, Infinity);
}
- const authorizeToolCall = (tool: string): boolean => {
- const key = `tool:${tool}`;
- const n = commandUses.get(key) ?? 0;
- if (n <= 0) return false;
- commandUses.set(key, n - 1);
+ const consumeApproval = (key: string): boolean => {
+ const uses = commandUses.get(key) ?? 0;
+ if (uses <= 0) return false;
+ commandUses.set(key, uses - 1);
return true;
};
- const authorizeCommand = (command: string, approvalKey?: string): boolean => {
+ const authorizeToolCall = (tool: string): boolean => consumeApproval(`tool:${tool}`);
+ const authorizeCommand = (command: string, approvalKey?: string, exactApprovalKey = false): boolean => {
let key = approvalKey ?? command;
if (approvalKey !== undefined && commandUses.has(approvalKey)) key = approvalKey;
- else if (commandUses.has(command)) key = command;
- const n = commandUses.get(key) ?? 0;
- if (n <= 0) return false;
- commandUses.set(key, n - 1);
- return true;
+ else if (!exactApprovalKey && commandUses.has(command)) key = command;
+ return consumeApproval(key);
};
const quarantineReleaseApprovals: Array<{
command: string;
@@ -1370,6 +1369,26 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const credentialCutoverServices = credentialServices.filter((service) => cutoverModeOf(service) !== "legacy");
const openSpeakerKeychain =
liveAuthorTurn && conversation.kind !== "dm" && sharingSources.includes(personalScope(actor.id));
+ const openAutomationKeychain =
+ input.origin.kind === "automation" &&
+ input.origin.useOwnerKeychain === true &&
+ conversation.kind !== "dm" &&
+ !!deps.config &&
+ !!deps.isCurrentSharedScopeMember &&
+ (await isOpenScopeMember({
+ actorId: actor.id,
+ scope: scopeId,
+ config: deps.config,
+ isCurrentSharedScopeMember: deps.isCurrentSharedScopeMember,
+ }));
+ if (
+ input.origin.kind === "automation" &&
+ input.origin.useOwnerKeychain === true &&
+ (input.origin.ownerResourcesRequireOpen === true ||
+ (conversation.kind === "channel" && conversation.isPrivate !== true)) &&
+ !openAutomationKeychain
+ )
+ return { status: "refused", reason: "owner-authorized automation requires current Open membership" };
const isolateOwnerKeychain =
openSpeakerKeychain ||
(conversation.kind !== "dm" && input.origin.kind === "automation" && input.origin.useOwnerKeychain === true);
@@ -1385,7 +1404,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const authorizeOwnerCredentials = async (): Promise<void> => {
if (
- openSpeakerKeychain &&
+ (openSpeakerKeychain || openAutomationKeychain) &&
(!(await isCurrentSharedScopeMember(actor.id, scopeId)) ||
(await deps.config?.resolveSharingPostureDurable(personalScope(actor.id), scopeId)) !== "open")
) {
@@ -1462,7 +1481,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (
!strictReadOnly &&
deps.connectorTokens &&
- ((conversation.kind === "dm" && liveAuthorTurn) || openSpeakerKeychain)
+ ((conversation.kind === "dm" && liveAuthorTurn) || openSpeakerKeychain || openAutomationKeychain)
) {
const tokens = deps.connectorTokens;
const inventory = tokens.listConnectorsByOwners
@@ -1484,7 +1503,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
addCredential(
{
handle: `connector_${host.replace(/[^a-zA-Z0-9]/g, "_")}_${accountType ?? "default"}`,
- scope: openSpeakerKeychain ? "owner" : "scoped",
+ scope: isolateOwnerKeychain ? "owner" : "scoped",
resolve: async () => {
await authorizeOwnerCredentials();
const token = await tokens.connectorAccessToken(host, actor.id, accountType);
@@ -1503,7 +1522,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
await registerConnectorCredentials(addCredentialToCatalog);
perf.credsMs += Date.now() - credsStart;
let sharedCredsBlock = "";
- let egressTokenForTurn: string | undefined;
// Service credentials: one read of the org's credential list and one grant scan feed both
// the env-delivery gate (below) and the broker token mint (further down). Same grants gate both.
let serviceCredRecords: PublicServiceCredential[] = [];
@@ -1676,22 +1694,20 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
}
}
const egressSecret = deps.capabilitySecret ?? deps.signingSecret;
- if (!strictReadOnly && egressSecret) {
- egressTokenForTurn = await mintCapabilityToken(
+ const egressTokenForPolicy = async (egress: EgressPolicy): Promise<string | undefined> => {
+ if (strictReadOnly || !egressSecret) return undefined;
+ return mintCapabilityToken(
{
...scopeAttestation,
aud: EGRESS_PROXY_AUD,
- egress: egressClaimAllowingControlPlane(
- resolution.egress,
- deps.apiBaseUrl ?? "",
- securityPolicy.denyPrivateNetworks,
- ),
+ egress: egressClaimAllowingControlPlane(egress, deps.apiBaseUrl ?? "", securityPolicy.denyPrivateNetworks),
exp: Date.now() + SANDBOX_CAPABILITY_TTL_MS,
},
egressSecret,
deps.capabilityTokenCompression,
);
- }
+ };
+ const egressTokenForTurn = await egressTokenForPolicy(resolution.egress);
const registerServiceCredentials = async (
addCredential: typeof addCredentialToCatalog,
requestedHandles: readonly string[],
@@ -1856,6 +1872,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
scopedCommand,
provision,
provisionScratch,
+ accessResource,
provisionResource,
provisionOwnerAuth,
useSkill,
@@ -1876,8 +1893,11 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
turnFilesDir,
connectorEnv,
egressTokenForTurn,
+ egressTokenForPolicy,
isolateOwnerKeychain,
- openSpeakerKeychain,
+ openSpeakerKeychain: openSpeakerKeychain || openAutomationKeychain,
+ openResourceAccess:
+ liveAuthorTurn || (input.origin.kind === "automation" && input.origin.useOwnerKeychain === true),
ownerAuthAvailable,
credentialTools,
credentialServices,
@@ -1997,11 +2017,18 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
};
} else {
const scope = input.approval.scope ?? "once";
+ const quarantineRelease = p.approvalKey?.startsWith("security-screen-release:") === true;
const recordDisallowsScope =
scope !== "once" &&
p.grantModes?.[scope] === false &&
- p.approvalKey?.startsWith("security-screen-release:") === true;
+ (quarantineRelease || p.approvalKey?.startsWith("sandbox:") === true);
if (scope !== "once" && (!resolution.approvalGrantModes[scope] || recordDisallowsScope)) {
+ let reason = `the "${scope}" approval option is disabled by an admin here — approve once or deny`;
+ if (recordDisallowsScope) {
+ reason = quarantineRelease
+ ? `quarantined content can only be released once — approve once or deny`
+ : `this approval does not allow the "${scope}" option — approve once or deny`;
+ }
deps.auditLog.record({
at: Date.now(),
principalId: actor.id,
@@ -2014,9 +2041,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
return {
status: "pending_approval",
sessionId: session.id,
- reason: recordDisallowsScope
- ? `quarantined content can only be released once — approve once or deny`
- : `the "${scope}" approval option is disabled by an admin here — approve once or deny`,
+ reason,
pendingApprovals: [
{
requestId: input.approval.requestId,
@@ -2459,6 +2484,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
provision,
provisionScratch,
provisionResource,
+ accessSandboxResource: accessResource,
...(provisionOwnerAuth ? { provisionOwnerAuth } : {}),
...(ownerAuthCommand ? { ownerAuthCommand } : {}),
...(scopedCommand ? { scopedCommand } : {}),
@@ -3894,6 +3920,14 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
> = [...(result.pendingApprovals ?? []), ...quarantineReleaseApprovals];
for (const pa of turnApprovals) {
const blocks = approvalBlocksInput(pa.kind, outcome);
+ const grantModes = pa.grantModes
+ ? {
+ grantModes: {
+ session: resolution.approvalGrantModes.session && pa.grantModes.session,
+ always: resolution.approvalGrantModes.always && pa.grantModes.always,
+ },
+ }
+ : grantModesField;
const command = pa.command;
const requestId = commandApprovalId(session.id, command);
const summary = pa.summary ?? (await approvalSummary(scopeId, command, pa.reason, pa.purpose));
@@ -3906,7 +3940,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
reason: pa.reason,
request,
blocksInput: blocks,
- ...(pa.grantModes ? { grantModes: pa.grantModes } : grantModesField),
+ ...grantModes,
...(pa.matched ? { matched: pa.matched } : {}),
...(pa.purpose ? { purpose: pa.purpose } : {}),
...(summary ? { summary } : {}),
@@ -3919,7 +3953,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
command,
reason: pa.reason,
blocksInput: blocks,
- ...(pa.grantModes ? { grantModes: pa.grantModes } : grantModesField),
+ ...grantModes,
...(pa.matched ? { matched: pa.matched } : {}),
...(pa.purpose ? { purpose: pa.purpose } : {}),
...(summary ? { summary } : {}),
@@ -3987,10 +4021,12 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
}
if (err instanceof NeedsApproval) {
const requestId = commandApprovalId(session.id, err.command);
- const grantModesField =
- resolution.approvalGrantModes.session && resolution.approvalGrantModes.always
- ? {}
- : { grantModes: resolution.approvalGrantModes };
+ const grantModesField = {
+ grantModes: {
+ session: resolution.approvalGrantModes.session && (err.grantModes?.session ?? true),
+ always: resolution.approvalGrantModes.always && (err.grantModes?.always ?? true),
+ },
+ };
const summary = await approvalSummary(scopeId, err.command, err.approvalReason);
try {
await withManagedRosterVersion(async () => {
diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.ts
index 4923d7e2f..56fec2e33 100644
--- a/src/core/orchestrator/sandboxes.ts
+++ b/src/core/orchestrator/sandboxes.ts
@@ -1,7 +1,10 @@
import type { Principal, Resolution, ScopeId, Session } from "../../types.ts";
import { personalScope } from "../../types.ts";
+import { intersectEgressPolicies } from "../../resolution/egress-policy.ts";
+import { isOpenScopeMember } from "../../resolution/sharing-access.ts";
import type { GapPhase } from "../../sessions/session-store.ts";
import { type SandboxHandle, supportsProcessSessions } from "../../sandbox/sandbox.ts";
+import type { SandboxAccessPlan } from "../../sandbox/sandbox-resources.ts";
import { reconcileProcesses } from "../../processes/reconcile.ts";
import {
deviceFlowCredOwner,
@@ -42,8 +45,10 @@ export interface TurnSandboxContext {
turnFilesDir: string;
connectorEnv: Record<string, string>;
egressTokenForTurn: string | undefined;
+ egressTokenForPolicy?: (policy: Resolution["egress"]) => Promise<string | undefined>;
isolateOwnerKeychain: boolean;
openSpeakerKeychain?: boolean;
+ openResourceAccess?: boolean;
ownerAuthAvailable: boolean;
credentialTools: readonly import("../../deployment/load-layer.ts").LayerCredentialTool[];
credentialServices: string[];
@@ -69,8 +74,10 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
turnFilesDir,
connectorEnv,
egressTokenForTurn,
+ egressTokenForPolicy,
isolateOwnerKeychain,
openSpeakerKeychain,
+ openResourceAccess,
ownerAuthAvailable,
credentialTools,
credentialServices,
@@ -95,8 +102,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
return keys.length ? `unset ${keys.join(" ")}; ` : "";
};
const scopedCommand = credentialCutoverServices.length
- ? (command: string, env: Record<string, string> = {}): string =>
- `${unsetBrokerEnv({ ...connectorEnv, ...env })}${command}`
+ ? (command: string, env = connectorEnv): string => `${unsetBrokerEnv(env)}${command}`
: undefined;
if (ownerAuthAvailable) {
ownerAuthCommand = (command, env = {}) => {
@@ -169,6 +175,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
}
: undefined;
const resourceHandles = new Map<string, SandboxHandle>();
+ const resourcePolicy = new Map<string, string>();
const resourcePendingHandles = new Map<string, SandboxHandle>();
const resourcePending = new Map<string, Promise<SandboxHandle>>();
let provisionInFlight: Promise<SandboxHandle> | null = null;
@@ -180,18 +187,42 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
});
return provisionInFlight;
};
- const prepareCredentials = async (handle: SandboxHandle, emit: typeof emitGapWork): Promise<void> => {
+ const prepareCredentials = async (
+ handle: SandboxHandle,
+ emit: typeof emitGapWork,
+ credentialScopeId = memoryScopeId,
+ ): Promise<void> => {
if (deps.keychain) {
const deviceFlowStart = Date.now();
+ const crossScope = credentialScopeId !== memoryScopeId;
+ const services = crossScope
+ ? [
+ ...new Set([
+ ...credentialServices,
+ ...((await deps.deviceFlowCutover?.listServices(credentialScopeId)) ?? []),
+ ]),
+ ]
+ : credentialServices;
+ const targetModes = new Map<string, DeviceFlowCutoverMode>();
+ if (crossScope) {
+ for (const service of services) {
+ const policy = await deps.deviceFlowCutover?.resolvePolicy(credentialScopeId, service);
+ targetModes.set(service, policy?.mode ?? "legacy");
+ }
+ }
+ const modeOf = (service: string): DeviceFlowCutoverMode => targetModes.get(service) ?? cutoverModeOf(service);
+ const excludedServices = [
+ ...new Set([...quarantinedServices, ...services.filter((service) => modeOf(service) === "ephemeral_only")]),
+ ];
const restoreOwnerId =
- input.origin.kind === "automation" && input.origin.useOwnerKeychain && !isolateOwnerKeychain
+ !crossScope && input.origin.kind === "automation" && input.origin.useOwnerKeychain && !isolateOwnerKeychain
? actor.id
- : deviceFlowCredOwner(memoryScopeId, actor.id);
+ : deviceFlowCredOwner(credentialScopeId, actor.id);
const resetGenerations = new Map<string, string>();
- for (const service of credentialServices) {
- if (cutoverModeOf(service) !== "legacy") continue;
+ for (const service of services) {
+ if (modeOf(service) !== "legacy") continue;
const generation = await deps.deviceFlowCutover?.residentResetGeneration(
- memoryScopeId,
+ credentialScopeId,
service,
handle.resourceId,
);
@@ -201,13 +232,14 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
const resetServices = [...resetGenerations.keys()].filter((service) =>
owned.some((record) => expandServiceAliases([service]).includes(record.service)),
);
- const removeServices = [...new Set([...quarantinedServices, ...resetServices])];
+ const removeServices = [...new Set([...excludedServices, ...resetServices])];
if (removeServices.length) {
await removeDeviceFlowLogins({
sandbox: deps.sandbox,
handle,
keychain: deps.keychain,
ownerId: restoreOwnerId,
+ ...(crossScope ? { allOrigins: true } : {}),
services: removeServices,
canonicalRoots: credentialTools
.filter((tool) => removeServices.includes(tool.service))
@@ -220,7 +252,8 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
handle,
keychain: deps.keychain,
ownerId: restoreOwnerId,
- ...(quarantinedServices.length ? { excludeServices: quarantinedServices } : {}),
+ ...(crossScope ? { allOrigins: true } : {}),
+ ...(excludedServices.length ? { excludeServices: excludedServices } : {}),
onAnomaly: (service, detail) =>
deps.errors?.record({
category: "keychain",
@@ -234,13 +267,13 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
deps.credentialUsage?.record({
slug: `keychain:${service}`,
host: "local",
- status: cutoverModeOf(service) === "prefer_ephemeral" ? "legacy_retained" : "legacy_restored",
+ status: modeOf(service) === "prefer_ephemeral" ? "legacy_retained" : "legacy_restored",
scopeLabel: scopeId,
principalId: actor.id,
});
}
for (const [service, generation] of resetGenerations) {
- await deps.deviceFlowCutover?.markResidentReset(memoryScopeId, service, generation, handle.resourceId);
+ await deps.deviceFlowCutover?.markResidentReset(credentialScopeId, service, generation, handle.resourceId);
}
} catch (err) {
deps.errors?.record(
@@ -348,7 +381,9 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
if (deps.skills)
void deps.skills.recordUse(resolution.skill.id).catch((e) => swallow("orchestrator: skill recordUse", e));
if (!shipsFiles) return { content, sourceScopeId: resolution.skill.scopeId };
- const handle = sandboxId ? await provisionResource(sandboxId) : await provision();
+ const access = sandboxId ? await accessResource(sandboxId) : undefined;
+ if (access?.crossScope) return { content, sourceScopeId: resolution.skill.scopeId };
+ const handle = access ? await provisionResource(access) : await provision();
await materializeSkillTree(handle, resolution, sandboxId);
const pack = packRoot(skillsRoot, resolution);
return {
@@ -358,26 +393,86 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
...(pack ? { packDir: pack } : {}),
};
};
- const provisionResource = (id: string): Promise<SandboxHandle> => {
- const existing = resourceHandles.get(id);
- if (existing) return Promise.resolve(existing);
+ const writableScopeId = resolution.layers.find((layer) => layer.mode === "rw")?.scopeId;
+ const canUseSandboxScope = async (target: ScopeId): Promise<boolean> => {
+ if (target === writableScopeId || target === scopeId) return true;
+ if (!openResourceAccess || actor.type !== "internal" || !deps.config || !deps.isCurrentSharedScopeMember)
+ return false;
+ const personal = personalScope(actor.id);
+ for (const scope of new Set([scopeId, target])) {
+ if (scope === personal) {
+ if ((await deps.config.resolveSharingPostureDurable(personal, scope)) !== "open") return false;
+ } else if (
+ !(await isOpenScopeMember({
+ actorId: actor.id,
+ scope,
+ config: deps.config,
+ isCurrentSharedScopeMember: deps.isCurrentSharedScopeMember,
+ }))
+ )
+ return false;
+ }
+ return true;
+ };
+ const accessResource = async (id: string): Promise<SandboxAccessPlan> => {
+ const resource = await deps.sandboxResources?.access(actor.id, id);
+ if (!resource || !(await canUseSandboxScope(resource.ownerScopeId)))
+ throw new Error("sandbox access is no longer authorized in this conversation");
+ const crossScope = resource.ownerScopeId !== writableScopeId && resource.ownerScopeId !== scopeId;
+ if (!crossScope) return { resource, crossScope: false, egress: resolution.egress, commandPolicy: null };
+ await deps.config!.refreshSecurity([resource.ownerScopeId]);
+ const credentialScopeId = resource.ownerScopeId === personalScope(actor.id) ? resource.ownerScopeId : undefined;
+ return {
+ resource,
+ crossScope: true,
+ egress: intersectEgressPolicies(resolution.egress, deps.config!.getEgress(resource.ownerScopeId)),
+ commandPolicy: deps.config!.getCommandPolicy(resource.ownerScopeId),
+ ...(credentialScopeId ? { credentialScopeId } : {}),
+ };
+ };
+ const provisionResource = async (
+ input: string | SandboxAccessPlan,
+ authorize?: (access: SandboxAccessPlan) => void,
+ ): Promise<SandboxHandle> => {
+ const access = typeof input === "string" ? await accessResource(input) : input;
+ const { resource, crossScope, egress, credentialScopeId } = access;
+ const id = resource.id;
const pending = resourcePending.get(id);
- if (pending) return pending;
+ if (pending) {
+ await pending;
+ return provisionResource(id, authorize);
+ }
+ authorize?.(access);
+ const policyKey = JSON.stringify({ egress, credentialScopeId });
+ const existing = resourceHandles.get(id);
+ if (existing && resourcePolicy.get(id) === policyKey) {
+ if (credentialScopeId) await prepareCredentials(existing, emitGapWork, credentialScopeId);
+ return existing;
+ }
const provisioned = (async () => {
- const resource = await deps.sandboxResources?.get(id);
- const ownerScope = resolution.layers.find((layer) => layer.mode === "rw")?.scopeId;
- if (!resource || (resource.ownerScopeId !== ownerScope && resource.ownerScopeId !== scopeId))
- throw new Error("sandbox does not belong to this conversation's writable scope");
- const handle = await deps.sandbox.provision(resolution.layers, {
+ const layers = crossScope
+ ? resolution.layers
+ .filter((layer) => layer.mode === "rw" || layer.mountPath === "global")
+ .map((layer) => (layer.mode === "rw" ? { ...layer, scopeId: resource.ownerScopeId } : layer))
+ : resolution.layers;
+ if (crossScope && egressTokenForTurn && !egressTokenForPolicy)
+ throw new Error("target sandbox egress authorization unavailable");
+ const egressToken = crossScope ? await egressTokenForPolicy?.(egress) : egressTokenForTurn;
+ const handle = await deps.sandbox.provision(layers, {
sandboxId: id,
- env: connectorEnv,
- egress: resolution.egress,
- ...(egressTokenForTurn ? { egressToken: egressTokenForTurn } : {}),
+ ...(!crossScope ? { env: connectorEnv } : {}),
+ ...(access.env ? { env: { ...access.env } } : {}),
+ egress,
+ ...(egressToken ? { egressToken } : {}),
});
resourcePendingHandles.set(id, handle);
- await prepareCredentials(handle, emitGapWork);
- await prepareTurnFiles(handle);
+ if (credentialScopeId) await prepareCredentials(handle, emitGapWork, credentialScopeId);
+ if (!crossScope) {
+ await prepareCredentials(handle, emitGapWork);
+ await prepareTurnFiles(handle);
+ }
resourceHandles.set(id, handle);
+ resourcePolicy.set(id, policyKey);
resourcePendingHandles.delete(id);
return handle;
})().finally(() => {
@@ -548,6 +643,15 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
),
);
};
+ const hasLiveProcesses = async (handle: SandboxHandle, fallbackScope: ScopeId): Promise<boolean> => {
+ if (!deps.processes) return false;
+ if (!handle.resourceId) return (await deps.processes.liveByScope(fallbackScope)).length > 0;
+ return (await deps.processes.listLive()).some(
+ (process) =>
+ process.sandboxId === handle.resourceId ||
+ (!process.sandboxId && process.scopeId === (handle.scopeId ?? fallbackScope)),
+ );
+ };
const reclaimBox = async (): Promise<void> => {
let ownerCleanupError: unknown;
if (ownerAuthProvisionInFlight) await ownerAuthProvisionInFlight.catch(() => {});
@@ -559,7 +663,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
let keepReachWarm = false;
if (deps.processes && supportsProcessSessions(deps.sandbox)) {
try {
- keepReachWarm = (await deps.processes.liveByScope(target)).length > 0;
+ keepReachWarm = await hasLiveProcesses(h, target);
} catch (e) {
swallow("orchestrator: reach live process check", e);
keepReachWarm = false;
@@ -621,11 +725,11 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
releases.push(
(async () => {
try {
- await clearTurnFiles(handle);
+ if (handle.scopeId === undefined || handle.scopeId === writableScopeId || handle.scopeId === scopeId)
+ await clearTurnFiles(handle);
} finally {
- const live = await deps.processes?.liveByScope(memoryScopeId).catch(() => []);
await deps.sandbox.teardown(handle, {
- keepWarm: live?.some((process) => process.sandboxId === handle.resourceId) ?? false,
+ keepWarm: await hasLiveProcesses(handle, memoryScopeId).catch(() => true),
});
}
})(),
@@ -649,7 +753,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
let keepWarm = false;
if (deps.processes && supportsProcessSessions(deps.sandbox)) {
try {
- keepWarm = (await deps.processes.liveByScope(memoryScopeId)).length > 0;
+ keepWarm = await hasLiveProcesses(handle, memoryScopeId);
} catch (e) {
swallow("orchestrator: live process check", e);
keepWarm = false;
@@ -670,6 +774,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
scopedCommand,
provision,
provisionScratch,
+ accessResource,
provisionResource,
provisionOwnerAuth,
useSkill,
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index 6952d24a2..9ea7a720b 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -82,6 +82,7 @@ export interface OrchestratorInput extends Omit<
| "securityScreenData"
| "triggerDestination"
| "ownerKeychainUnion"
+ | "ownerResourcesRequireOpen"
| "unprompted"
| "liveActor"
> {
diff --git a/src/core/turn-origin.ts b/src/core/turn-origin.ts
index 26ee2394b..5984d3cb9 100644
--- a/src/core/turn-origin.ts
+++ b/src/core/turn-origin.ts
@@ -9,6 +9,7 @@ type LegacyTurnOrigin = Pick<
| "securityScreenData"
| "triggerDestination"
| "ownerKeychainUnion"
+ | "ownerResourcesRequireOpen"
| "unprompted"
| "liveActor"
>;
@@ -32,6 +33,9 @@ export function resolveTurnOrigin(input: Partial<LegacyTurnOrigin> & { origin?:
...(screenData !== undefined ? { screenData } : {}),
...((typed.destination ?? legacy.destination) ? { destination: typed.destination ?? legacy.destination! } : {}),
...(typed.useOwnerKeychain || legacy.useOwnerKeychain ? { useOwnerKeychain: true } : {}),
+ ...(typed.ownerResourcesRequireOpen || legacy.ownerResourcesRequireOpen
+ ? { ownerResourcesRequireOpen: true }
+ : {}),
};
}
if (typed.kind === "human" && legacy.kind === "human") {
@@ -58,6 +62,7 @@ export function normalizeTurnOrigin(input: LegacyTurnOrigin): TurnOrigin {
...(input.securityScreenData !== undefined ? { screenData: input.securityScreenData } : {}),
...(input.triggerDestination ? { destination: input.triggerDestination } : {}),
...(input.ownerKeychainUnion === true ? { useOwnerKeychain: true } : {}),
+ ...(input.ownerResourcesRequireOpen === true ? { ownerResourcesRequireOpen: true } : {}),
};
}
if (input.unprompted === true) {
@@ -97,6 +102,7 @@ export function turnOriginRequestFields(origin: TurnOrigin): Partial<LegacyTurnO
...(origin.screenData !== undefined ? { securityScreenData: origin.screenData } : {}),
...(origin.destination ? { triggerDestination: origin.destination } : {}),
...(origin.useOwnerKeychain ? { ownerKeychainUnion: true } : {}),
+ ...(origin.ownerResourcesRequireOpen ? { ownerResourcesRequireOpen: true } : {}),
};
case "direct":
return {};
diff --git a/src/cron/authority.ts b/src/cron/authority.ts
index bb878b24e..80dcf62ca 100644
--- a/src/cron/authority.ts
+++ b/src/cron/authority.ts
@@ -4,13 +4,17 @@ import type { CapabilityClaims } from "../auth/capability-token.ts";
import type { App } from "../api/app.ts";
import type { AdminService } from "../admin/admin-service.ts";
-type TriggerAuthority = Pick<TriggerSpec, "owner" | "ownerScopeId" | "runAs" | "unattendedGrants" | "members">;
+type TriggerAuthority = Pick<
+ TriggerSpec,
+ "owner" | "ownerScopeId" | "runAs" | "ownerResourcesRequireOpen" | "unattendedGrants" | "members"
+>;
export function cronTriggerAuthority(cron: TriggerAuthority): TriggerAuthority {
return {
owner: cron.owner,
ownerScopeId: cron.ownerScopeId,
...(cron.runAs ? { runAs: cron.runAs } : {}),
+ ...(cron.ownerResourcesRequireOpen ? { ownerResourcesRequireOpen: true } : {}),
...(cron.unattendedGrants ? { unattendedGrants: [...cron.unattendedGrants] } : {}),
...(cron.members ? { members: cron.members } : {}),
};
diff --git a/src/cron/cron-store.ts b/src/cron/cron-store.ts
index a20f3c484..b8278510f 100644
--- a/src/cron/cron-store.ts
+++ b/src/cron/cron-store.ts
@@ -34,6 +34,7 @@ export interface CreateCronInput extends CreateTriggerInput {
action?: string;
message?: string;
runAs?: Cron["runAs"];
+ ownerResourcesRequireOpen?: boolean;
members?: Principal[];
unattendedGrants?: string[];
loopId?: string;
@@ -50,6 +51,7 @@ export interface CronPatch {
destination?: Destination;
members?: Principal[];
runAs?: Cron["runAs"];
+ ownerResourcesRequireOpen?: boolean;
unattendedGrants?: string[];
}
@@ -122,6 +124,7 @@ export function createCronStore(
contentPart(input.unattendedGrants),
contentPart(title),
...(input.loopId !== undefined ? [contentPart(input.loopId)] : []),
+ ...(input.ownerResourcesRequireOpen ? [contentPart("owner-resources-require-open")] : []),
...(input.runtime ? [contentPart(input.runtime)] : []),
]);
return createDeduped(backing, contentId, (id) => ({
@@ -133,6 +136,7 @@ export function createCronStore(
...(input.action !== undefined ? { action: input.action } : {}),
...(input.message !== undefined ? { message: input.message } : {}),
...(input.runAs ? { runAs: input.runAs } : {}),
+ ...(input.ownerResourcesRequireOpen ? { ownerResourcesRequireOpen: true } : {}),
...(input.members ? { members: input.members } : {}),
...(input.unattendedGrants ? { unattendedGrants: input.unattendedGrants } : {}),
...(input.loopId ? { loopId: input.loopId } : {}),
@@ -161,6 +165,7 @@ export function createCronStore(
if (patch.archived === true) fields.enabled = false;
if (patch.members !== undefined) fields.members = patch.members;
if (patch.runAs !== undefined) fields.runAs = patch.runAs;
+ if (patch.ownerResourcesRequireOpen === true) fields.ownerResourcesRequireOpen = true;
if (patch.unattendedGrants !== undefined) fields.unattendedGrants = patch.unattendedGrants;
return backing.merge(id, fields);
},
diff --git a/src/cron/scheduler.ts b/src/cron/scheduler.ts
index ab65c1aeb..62c5f7832 100644
--- a/src/cron/scheduler.ts
+++ b/src/cron/scheduler.ts
@@ -76,6 +76,7 @@ export interface SchedulerDeps {
identity: IdentityService;
run: (req: TurnRequest) => Promise<TurnResult>;
currentScopeMembers?: CurrentScopeMembers;
+ isOpenScopeMember?: TriggerDeps["isOpenScopeMember"];
now?: () => number;
maxFiresPerTick?: number;
leaderLease?: LeaderLease;
@@ -262,6 +263,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
run: deps.run,
...(deps.directory ? { directory: deps.directory } : {}),
...(deps.currentScopeMembers ? { currentScopeMembers: deps.currentScopeMembers } : {}),
+ ...(deps.isOpenScopeMember ? { isOpenScopeMember: deps.isOpenScopeMember } : {}),
...(deps.sessions ? { sessions: deps.sessions } : {}),
},
{
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index b8581fe33..89fad2ed1 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -62,6 +62,7 @@ export interface ToolContextRef {
matched?: string;
purpose?: string;
approvalKey?: string;
+ grantModes?: { session: boolean; always: boolean };
}>;
pausedOnApproval?: boolean;
emit?: (entry: { type: EntryType; payload: unknown; scopeLabel: ScopeId }) => void | Promise<unknown>;
@@ -622,6 +623,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
matched: e.matched,
...(purpose ? { purpose } : {}),
...(e.approvalKey ? { approvalKey: e.approvalKey } : {}),
+ ...(e.grantModes ? { grantModes: e.grantModes } : {}),
});
ref.pausedOnApproval = true;
return recordResult(
@@ -1993,6 +1995,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
matched: e.matched,
...(params.purpose ? { purpose: params.purpose } : {}),
...(e.approvalKey ? { approvalKey: e.approvalKey } : {}),
+ ...(e.grantModes ? { grantModes: e.grantModes } : {}),
});
ref.pausedOnApproval = true;
return recordResult(
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index e2a418c08..93f9caa3d 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -156,6 +156,7 @@ export interface HarnessTurnResult {
matched?: string;
purpose?: string;
approvalKey?: string;
+ grantModes?: { session: boolean; always: boolean };
}>;
pausedOnApproval?: boolean;
modelCalls?: number;
diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.ts
index 03f1c6836..3c2d3ee05 100644
--- a/src/harness/mock-harness.ts
+++ b/src/harness/mock-harness.ts
@@ -499,6 +499,7 @@ export function createMockHarness(): Harness {
kind: e.kind,
matched: e.matched,
...(e.approvalKey ? { approvalKey: e.approvalKey } : {}),
+ ...(e.grantModes ? { grantModes: e.grantModes } : {}),
});
reply = `[blocked] ${e.approvalReason}`;
}
@@ -520,6 +521,7 @@ export function createMockHarness(): Harness {
kind: e.kind,
matched: e.matched,
...(e.approvalKey ? { approvalKey: e.approvalKey } : {}),
+ ...(e.grantModes ? { grantModes: e.grantModes } : {}),
});
}
}
diff --git a/src/resolution/egress-policy.ts b/src/resolution/egress-policy.ts
index e5d4abb07..62b4796ff 100644
--- a/src/resolution/egress-policy.ts
+++ b/src/resolution/egress-policy.ts
@@ -83,3 +83,28 @@ export function egressDecision(host: string, policy: EgressPolicy | undefined):
}
return { allow: true, verdict: "ok" };
}
+
+export function intersectEgressPolicies(source: EgressPolicy, target: EgressPolicy | null): EgressPolicy {
+ if (!target) return source;
+ const left = source.allowedHosts ?? [];
+ const right = target.allowedHosts ?? [];
+ let allowedHosts = left.length ? left : right;
+ if (left.length && right.length) {
+ allowedHosts = [
+ ...new Set(
+ left.flatMap((a) =>
+ right.flatMap((b) => {
+ if (hostMatches(a, b)) return [a];
+ return hostMatches(b, a) ? [b] : [];
+ }),
+ ),
+ ),
+ ];
+ if (!allowedHosts.length) throw new Error("source and target sandbox egress allowlists have no overlap");
+ }
+ return {
+ allowedHosts,
+ deniedHosts: [...new Set([...(source.deniedHosts ?? []), ...(target.deniedHosts ?? [])])],
+ ...(source.denyPrivateNetworks || target.denyPrivateNetworks ? { denyPrivateNetworks: true } : {}),
+ };
+}
diff --git a/src/resolution/sharing-access.ts b/src/resolution/sharing-access.ts
index 8a845653b..deda0f7eb 100644
--- a/src/resolution/sharing-access.ts
+++ b/src/resolution/sharing-access.ts
@@ -24,6 +24,20 @@ interface SharingSourcesInput {
isCurrentSharedScopeMember?: IsCurrentSharedScopeMember;
}
+export async function isOpenScopeMember(input: {
+ actorId: string;
+ scope: ScopeId;
+ config: Pick<ScopedConfigStore, "resolveSharingPostureDurable">;
+ isCurrentSharedScopeMember: IsCurrentSharedScopeMember;
+}): Promise<boolean> {
+ const { kind } = parseScopeId(input.scope);
+ return (
+ (kind === "channel" || kind === "group") &&
+ (await input.isCurrentSharedScopeMember(input.actorId, input.scope)) &&
+ (await input.config.resolveSharingPostureDurable(personalScope(input.actorId), input.scope)) === "open"
+ );
+}
+
export async function sharingSourcesForTurn(input: SharingSourcesInput): Promise<ScopeId[]> {
if (
input.posture !== "open" ||
diff --git a/src/sandbox/sandbox-resources.ts b/src/sandbox/sandbox-resources.ts
index b6462de88..eebcefa84 100644
--- a/src/sandbox/sandbox-resources.ts
+++ b/src/sandbox/sandbox-resources.ts
@@ -1,7 +1,7 @@
import { randomUUID, createHash } from "node:crypto";
import type { DurableMap } from "../persistence/durable-map.ts";
import type { AdvisoryLock } from "../persistence/advisory-lock.ts";
-import { parseScopeId, type ScopeId } from "../types.ts";
+import { parseScopeId, type CommandPolicy, type EgressPolicy, type ScopeId } from "../types.ts";
import {
sandboxDefaultForScope,
type SandboxScopeDefaults,
@@ -27,6 +27,15 @@ export interface SandboxResource {
error?: string;
}
+export interface SandboxAccessPlan {
+ readonly resource: SandboxResource;
+ readonly crossScope: boolean;
+ readonly egress: EgressPolicy;
+ readonly commandPolicy: CommandPolicy | null;
+ readonly credentialScopeId?: ScopeId;
+ readonly env?: Readonly<Record<string, string>>;
+}
+
export interface SandboxDefault {
sandboxId: string | null;
}
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index 8e6a77da2..e160e5502 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -4,7 +4,7 @@ import type { RuntimeRequest, RuntimeResult } from "../harness/runtime-types.ts"
import { readContextFile } from "../resolution/context-files.ts";
import { contextMemory, type TurnContext } from "../resolution/turn-context.ts";
import { randomUUID } from "node:crypto";
-import type { SandboxResources } from "../sandbox/sandbox-resources.ts";
+import type { SandboxAccessPlan, SandboxResources } from "../sandbox/sandbox-resources.ts";
import { join } from "node:path";
import { interpolateSplitEnv } from "../deployment/deployment-layer.ts";
import type { CredentialPathSpec } from "../credentials/resident-paths.ts";
@@ -13,6 +13,7 @@ import { ROUTE_CACHE_TTL_MS, type SandboxBackendName } from "../sandbox/sandbox-
import type { SandboxMigrationRunner } from "../sandbox/sandbox-migration-runner.ts";
import { CapabilityUnsupportedError, hasParentPathSegment, supportsAgentComputerExport } from "../sandbox/sandbox.ts";
import type {
+ ApprovalGrantModes,
CommandPolicy,
CommandRule,
ConversationKind,
@@ -118,7 +119,15 @@ export class NeedsApproval extends Error {
kind: "approval";
matched?: string;
approvalKey?: string;
- constructor(command: string, reason: string, kind: "approval" = "approval", matched?: string, approvalKey?: string) {
+ grantModes?: ApprovalGrantModes;
+ constructor(
+ command: string,
+ reason: string,
+ kind: "approval" = "approval",
+ matched?: string,
+ approvalKey?: string,
+ grantModes?: ApprovalGrantModes,
+ ) {
super(`command requires approval: ${command}`);
this.name = "NeedsApproval";
this.command = command;
@@ -126,6 +135,7 @@ export class NeedsApproval extends Error {
this.kind = kind;
this.matched = matched;
this.approvalKey = approvalKey;
+ this.grantModes = grantModes;
}
}
@@ -434,7 +444,11 @@ export interface ToolContextDeps {
) => ReturnType<ToolContextDeps["commandPolicy"]>;
provision: () => Promise<SandboxHandle>;
provisionScratch?: () => Promise<SandboxHandle>;
- provisionResource?: (id: string) => Promise<SandboxHandle>;
+ provisionResource?: (
+ input: string | SandboxAccessPlan,
+ authorize?: (access: SandboxAccessPlan) => void,
+ ) => Promise<SandboxHandle>;
+ accessSandboxResource?: (id: string) => Promise<SandboxAccessPlan>;
provisionOwnerAuth?: () => Promise<SandboxHandle>;
ownerAuthCommand?: (command: string, env?: Record<string, string>) => string;
scopedCommand?: (command: string, env?: Record<string, string>) => string;
@@ -446,7 +460,7 @@ export interface ToolContextDeps {
layers: WorkspaceLayer[];
commandPolicy: () => CommandPolicy;
layerCommandRules?: () => readonly CommandRule[];
- authorizeCommand: (command: string, approvalKey?: string) => boolean;
+ authorizeCommand: (command: string, approvalKey?: string, exactApprovalKey?: boolean) => boolean;
grantedHandles: GrantedHandle[];
context?: TurnContext;
sharedMaterializeDir?: string;
@@ -505,6 +519,49 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
const persistExclude = deps.persistWritesToStore?.excludeDirs;
const orgScopeId = deps.layers.find((l) => l.mountPath === "global")?.scopeId ?? null;
+ const accessSandbox = async (id: string): Promise<SandboxAccessPlan> => {
+ if (!deps.sandboxResources || !deps.accessSandboxResource) throw new Error("sandbox inventory unavailable");
+ return deps.accessSandboxResource(id);
+ };
+
+ const authorizeExecution = (command: string, access?: SandboxAccessPlan, policy = deps.commandPolicy()): void => {
+ const source = evaluateCommandWithLayer(command, policy, deps.layerCommandRules?.() ?? []);
+ if (source.decision === "deny") throw new CommandDenied(command, source.reason ?? "denied by policy");
+ if (!access?.crossScope) {
+ if (source.decision === "require_approval" && !deps.authorizeCommand(command, source.approvalKey))
+ throw new NeedsApproval(
+ command,
+ source.reason ?? "requires approval",
+ "approval",
+ source.matched,
+ source.approvalKey,
+ );
+ return;
+ }
+ const target = access.commandPolicy
+ ? evaluateCommandWithLayer(command, access.commandPolicy, [])
+ : { decision: "allow" as const };
+ if (target.decision === "deny")
+ throw new CommandDenied(command, target.reason ?? "denied by target sandbox policy");
+ if (source.decision !== "require_approval" && target.decision !== "require_approval") return;
+ const approvalKey = `sandbox:${JSON.stringify([
+ access.resource.ownerScopeId,
+ source.approvalKey ?? command,
+ target.approvalKey ?? command,
+ ])}`;
+ const required = target.decision === "require_approval" ? target : source;
+ const grantModes = { session: false, always: false };
+ if (!deps.authorizeCommand(command, approvalKey, true))
+ throw new NeedsApproval(
+ command,
+ required.reason ?? "requires sandbox approval",
+ "approval",
+ required.matched,
+ approvalKey,
+ grantModes,
+ );
+ };
+
const ledger = deps.ledger ?? createNullLedger();
const runId = deps.runId;
const attempt = deps.attempt ?? 1;
@@ -557,7 +614,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
...(deps.commandCredentials?.length
? { commandCredentialHandles: deps.commandCredentials.map((credential) => credential.handle) }
: {}),
- ...(deps.sandboxResources
+ ...(deps.sandboxResources && deps.accessSandboxResource
? {
async sandboxResources(
action: "list" | "create" | "default" | "retire",
@@ -569,15 +626,22 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
const listed = await resources.list(deps.createdBy, writableScopeId);
return {
...listed,
- sandboxes: listed.sandboxes.filter((record) => record.ownerScopeId === writableScopeId),
+ sandboxes: (
+ await Promise.all(
+ listed.sandboxes.map(async (record) =>
+ deps.accessSandboxResource!(record.id)
+ .then((access) => access.resource)
+ .catch(() => null),
+ ),
+ )
+ ).filter((record) => record !== null),
};
}
if (action === "retire") {
if (!input?.sandboxId) throw new Error("retire requires sandbox_id");
- const record = await resources.access(deps.createdBy, input.sandboxId);
- if (record.ownerScopeId !== writableScopeId) throw new Error("retire this sandbox from its owning scope");
- await resources.retire(deps.createdBy, record.id);
- return { retired: record.id };
+ const { resource } = await accessSandbox(input.sandboxId);
+ await resources.retire(deps.createdBy, resource.id);
+ return { retired: resource.id };
}
if (action === "default") {
if (input?.sandboxId === undefined) throw new Error("default requires sandbox_id or null");
@@ -596,8 +660,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
if (sandboxId) {
const resources = deps.sandboxResources;
if (!resources) throw new Error("sandbox inventory unavailable");
- const record = await resources.access(deps.createdBy, sandboxId);
- if (record.ownerScopeId !== writableScopeId) throw new Error("inspect this sandbox from its owning scope");
+ await accessSandbox(sandboxId);
return resources.status(deps.createdBy, sandboxId);
}
if (!deps.sandbox.computerStatus) {
@@ -618,8 +681,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
if (sandboxId) {
const resources = deps.sandboxResources;
if (!resources) throw new Error("sandbox inventory unavailable");
- const record = await resources.access(deps.createdBy, sandboxId);
- if (record.ownerScopeId !== writableScopeId) throw new Error("restart this sandbox from its owning scope");
+ await accessSandbox(sandboxId);
return resources.restart(deps.createdBy, sandboxId);
}
if (!deps.sandbox.restartComputer) {
@@ -738,28 +800,24 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
if (target.kind === "error") throw new Error(target.message);
reached = { scopeId: target.scopeId, label: `#${target.channelName}` };
}
- const { decision, reason, matched, approvalKey } = evaluateCommandWithLayer(
- command,
- deps.commandPolicyForCredentials?.(requestedCredentials, ownerAuth) ?? deps.commandPolicy(),
- deps.layerCommandRules?.() ?? [],
- );
- if (decision === "deny") {
- throw new CommandDenied(command, reason ?? "denied by policy");
- }
- if (decision === "require_approval" && !deps.authorizeCommand(command, approvalKey)) {
- throw new NeedsApproval(command, reason ?? "requires approval", "approval", matched, approvalKey);
- }
+ const executionPolicy = () =>
+ deps.commandPolicyForCredentials?.(requestedCredentials, ownerAuth) ?? deps.commandPolicy();
let handle;
if (execOpts?.sandboxId) {
if (!deps.sandboxResources || !deps.provisionResource) throw new Error("sandbox inventory unavailable");
- const resource = await deps.sandboxResources.access(deps.createdBy, execOpts.sandboxId);
- if (resource.ownerScopeId !== writableScopeId)
- throw new Error("execute on this sandbox from its owning scope to preserve conversation isolation");
- handle = await deps.provisionResource(execOpts.sandboxId);
- } else if (reached) handle = await deps.reach!.provisionFor(reached.scopeId);
- else if (scratch) handle = await deps.provisionScratch!();
- else if (ownerAuth) handle = await deps.provisionOwnerAuth!();
- else handle = await deps.provision();
+ const access = await accessSandbox(execOpts.sandboxId);
+ handle = await deps.provisionResource(access, (current) => {
+ if (current.crossScope && requestedCredentials.length)
+ throw new Error("command credentials cannot be copied to another scope's computer");
+ authorizeExecution(command, current, executionPolicy());
+ });
+ } else {
+ authorizeExecution(command, undefined, executionPolicy());
+ if (reached) handle = await deps.reach!.provisionFor(reached.scopeId);
+ else if (scratch) handle = await deps.provisionScratch!();
+ else if (ownerAuth) handle = await deps.provisionOwnerAuth!();
+ else handle = await deps.provision();
+ }
const resolvedMs = execOpts?.timeoutSeconds != null ? execOpts.timeoutSeconds * 1000 : deps.execTimeoutMs;
const timeoutMs =
resolvedMs != null && deps.execTimeoutCeilingMs != null
@@ -813,7 +871,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
for (const credential of singleUse) await credential.commit?.();
const sandboxCommand = ownerAuth
? (deps.ownerAuthCommand?.(command, commandEnv) ?? command)
- : (deps.scopedCommand?.(command, commandEnv) ?? command);
+ : (deps.scopedCommand?.(command, { ...handle.env, ...commandEnv }) ?? command);
const commandHandle = Object.keys(commandEnv).length
? { ...handle, env: { ...handle.env, ...commandEnv } }
: handle;
@@ -909,13 +967,8 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
): Promise<SkillResult> {
opts?.signal?.throwIfAborted();
if (!deps.useSkill) return { content: null, sourceScopeId: null };
- if (opts?.sandboxId) {
- if (!deps.sandboxResources || !deps.provisionResource)
- throw new Error("named sandboxes are not available here");
- const record = await deps.sandboxResources.get(opts.sandboxId);
- if (!record) throw new Error(`unknown sandbox ${opts.sandboxId}`);
- if (record.ownerScopeId !== writableScopeId) throw new Error("load skills from the sandbox's owning scope");
- }
+ if (opts?.sandboxId && (!deps.sandboxResources || !deps.provisionResource))
+ throw new Error("named sandboxes are not available here");
return withAbort(() => deps.useSkill!(name, opts?.path ?? "SKILL.md", opts?.sandboxId), opts?.signal);
},
@@ -1189,24 +1242,17 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
let handle: SandboxHandle;
if (opts?.sandboxId) {
if (!deps.sandboxResources || !deps.provisionResource) throw new Error("sandbox inventory unavailable");
- const record = await deps.sandboxResources.access(deps.createdBy, opts.sandboxId);
- if (record.ownerScopeId !== writableScopeId) throw new Error("start work from the sandbox's owning scope");
- handle = await deps.provisionResource(opts.sandboxId);
- } else handle = await deps.provision();
- const { decision, reason, matched, approvalKey } = evaluateCommandWithLayer(
- command,
- deps.commandPolicy(),
- deps.layerCommandRules?.() ?? [],
- );
- if (decision === "deny") throw new CommandDenied(command, reason ?? "denied by policy");
- if (decision === "require_approval" && !deps.authorizeCommand(command, approvalKey)) {
- throw new NeedsApproval(command, reason ?? "requires approval", "approval", matched, approvalKey);
+ const access = await accessSandbox(opts.sandboxId);
+ handle = await deps.provisionResource(access, (current) => authorizeExecution(command, current));
+ } else {
+ authorizeExecution(command);
+ handle = await deps.provision();
}
return once(
() =>
deps.backgroundBroker!.start(
handle,
- deps.scopedCommand?.(command) ?? command,
+ deps.scopedCommand?.(command, handle.env) ?? command,
opts?.ttlSeconds ? opts.ttlSeconds * 1000 : undefined,
),
() => true,
diff --git a/src/triggers/edit-notice.ts b/src/triggers/edit-notice.ts
index f2fe3b11e..d87779ba1 100644
--- a/src/triggers/edit-notice.ts
+++ b/src/triggers/edit-notice.ts
@@ -2,7 +2,7 @@ import type { Cron, CronSchedule, Destination } from "../types.ts";
import { principalDestination } from "../reach/reach.ts";
import { personKeys } from "../directory/person.ts";
import { errMessage } from "../util/errors.ts";
-import { createHash } from "node:crypto";
+import { randomUUID } from "node:crypto";
export interface CronEditDetail {
schedule?: CronSchedule;
@@ -83,7 +83,7 @@ export interface CronEditNoticeSink {
export async function notifyOwnerOfCronEdit(
sink: CronEditNoticeSink,
- args: { cron: Cron; editorId: string; changeSummary: string[]; editFingerprint: string; detail?: CronEditDetail },
+ args: { cron: Cron; editorId: string; changeSummary: string[]; detail?: CronEditDetail },
onError?: (message: string) => void,
): Promise<void> {
const { cron } = args;
@@ -95,10 +95,6 @@ export async function notifyOwnerOfCronEdit(
]);
const ownerKeys = personKeys(owner, cron.owner);
if ([...personKeys(editor, args.editorId)].some((k) => ownerKeys.has(k))) return;
- const editKey = createHash("sha256")
- .update(`${cron.id}:${args.editorId}:${args.editFingerprint}`)
- .digest("hex")
- .slice(0, 16);
const url = sink.cronAdminUrl(cron);
const label = cron.title ?? "shared";
let ref = "shared";
@@ -118,7 +114,7 @@ export async function notifyOwnerOfCronEdit(
changes: args.changeSummary,
...(args.detail ? { detail: args.detail } : {}),
}),
- idempotencyKey: `cron-edit-notice:${cron.id}:${editKey}`,
+ idempotencyKey: `cron-edit-notice:${cron.id}:${randomUUID()}`,
});
} catch (e) {
(onError ?? ((m) => console.warn("[cron-edit-notice]", m)))(errMessage(e));
diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.ts
index d01218778..a1bc221b1 100644
--- a/src/triggers/run-trigger.ts
+++ b/src/triggers/run-trigger.ts
@@ -18,7 +18,7 @@ import { consentRequiredRecipient, recipientConsentSatisfied } from "./trigger-s
import { isVisible, type VisibilityDirectory } from "../directory/visibility.ts";
import type { DirectoryStore } from "../directory/directory-store.ts";
import { samePerson } from "../directory/person.ts";
-import type { CurrentScopeMembers } from "../resolution/scope-membership.ts";
+import { createIsCurrentSharedScopeMember, type CurrentScopeMembers } from "../resolution/scope-membership.ts";
const MEMBERSHIP_SKIP_NOTE = "the acting person is no longer a member of this trigger's home scope — run skipped";
const UNKNOWN_HOME_SKIP_NOTE =
@@ -30,8 +30,9 @@ export interface TriggerDeps {
identity: IdentityService;
run: (req: TurnRequest) => Promise<TurnResult>;
currentScopeMembers?: CurrentScopeMembers;
+ isOpenScopeMember?: (actorId: string, scope: ScopeId) => Promise<boolean>;
directory?: VisibilityDirectory & {
- get(principalId: string): Promise<{ displayName: string } | null>;
+ get(principalId: string): Promise<{ displayName: string; principalId?: string; slackId?: string } | null>;
channelPrivacy?(channelId: string): Promise<boolean | undefined>;
groupMembership?(groupId: string, principalId: string): Promise<boolean | undefined>;
conversationMembers?: DirectoryStore["conversationMembers"];
@@ -52,6 +53,7 @@ export interface TriggerSpec {
message?: string;
threadRef?: string;
runAs?: "owner" | "scopeFloor" | "scopeShared";
+ ownerResourcesRequireOpen?: boolean;
unattendedGrants?: string[];
members?: Principal[];
recipientConsent?: RecipientConsent;
@@ -196,8 +198,25 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
if (owner.type !== "internal") {
return { authzFailed: true, ran: false, note: "owner is no longer an internal principal" };
}
- if (isScopeShared && currentMembers && !currentMembers.some((member) => samePerson(member.id, spec.owner))) {
- return { authzFailed: true, ran: false, note: "scopeShared owner is no longer a current scope member" };
+ if (isScopeShared) {
+ if (spec.ownerResourcesRequireOpen && !(await deps.isOpenScopeMember?.(spec.owner, spec.ownerScopeId))) {
+ return {
+ authzFailed: true,
+ ran: false,
+ note: "scopeShared owner resource access requires current Open membership",
+ };
+ }
+ let sharedOwnerIsMember = spec.members?.some((member) => samePerson(member.id, spec.owner)) === true;
+ if (currentMembers) sharedOwnerIsMember = currentMembers.some((member) => samePerson(member.id, spec.owner));
+ else if (deps.directory) {
+ sharedOwnerIsMember = await createIsCurrentSharedScopeMember({
+ directory: deps.directory,
+ identity: deps.identity,
+ })(spec.owner, spec.ownerScopeId);
+ }
+ if (!sharedOwnerIsMember) {
+ return { authzFailed: true, ran: false, note: "scopeShared owner is no longer a current scope member" };
+ }
}
}
@@ -210,10 +229,12 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
let conversation: TurnRequest["conversation"] = { kind: "dm", threadRef };
if (ownerKind === "channel" || ownerKind === "group") {
const roster = await deps.directory?.conversationMembers?.(ownerKind, ownerRef).catch(() => undefined);
+ const isPrivate = ownerKind === "channel" ? await deps.directory?.channelPrivacy?.(ownerRef) : undefined;
conversation = {
kind: ownerKind,
channelRef: ownerRef,
threadRef,
+ ...(isPrivate !== undefined ? { isPrivate } : {}),
...(audience ? { audience } : {}),
...(roster ? { publishMembers: roster.map((m) => ({ externalId: m.principalId })) } : {}),
};
@@ -322,6 +343,7 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
...(spec.destination ? { triggerDestination: spec.destination } : {}),
...(liveDelivery ? { surfaceTools: true, addressed: true } : {}),
...(isScopeShared ? { ownerKeychainUnion: true } : {}),
+ ...(isScopeShared && spec.ownerResourcesRequireOpen ? { ownerResourcesRequireOpen: true } : {}),
idempotencyKey: spec.fireKey,
});
if (spec.deferWhenBusy && res.refusalKind === "session_busy") throw new FireDeferred();
diff --git a/src/types.ts b/src/types.ts
index e70ea6e19..954f41214 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -280,6 +280,7 @@ export interface Cron extends TriggerBase {
loopId?: string;
createdAt: number;
runAs?: "owner" | "scopeFloor" | "scopeShared";
+ ownerResourcesRequireOpen?: boolean;
members?: Principal[];
unattendedGrants?: string[];
@@ -601,7 +602,13 @@ export interface OverheardMessage {
export type TurnOrigin =
| { kind: "human"; messageTs?: string; entryTs?: string }
| { kind: "ambient"; entryTs?: string; live?: boolean }
- | { kind: "automation"; screenData?: string; destination?: Destination; useOwnerKeychain?: boolean }
+ | {
+ kind: "automation";
+ screenData?: string;
+ destination?: Destination;
+ useOwnerKeychain?: boolean;
+ ownerResourcesRequireOpen?: boolean;
+ }
| { kind: "direct" };
export interface TurnRequest {
@@ -633,6 +640,7 @@ export interface TurnRequest {
securityScreenData?: string;
triggerDestination?: Destination;
ownerKeychainUnion?: boolean;
+ ownerResourcesRequireOpen?: boolean;
unprompted?: boolean;
liveActor?: boolean;
botActor?: boolean;
diff --git a/src/wiring.ts b/src/wiring.ts
index 005706c00..2cf164df5 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -167,6 +167,7 @@ import {
type EnvironmentStore,
} from "./environments/environment-store.ts";
import { createIdempotencyStore, type IdempotencyRecord } from "./idempotency/idempotency-store.ts";
+import { isOpenScopeMember } from "./resolution/sharing-access.ts";
import { createScheduler, type Scheduler } from "./cron/scheduler.ts";
import { createPgBossCronQueue } from "./cron/job-queue.ts";
import { createWebhookStore, type WebhookHistory } from "./webhooks/webhook-store.ts";
@@ -1660,6 +1661,8 @@ export function buildApp(
const managesArtifactHome = createManagesArtifactHome({ managedGroups: projects, directory }, canManageScope);
const currentScopeMembers = createCurrentScopeMembers({ managedGroups: projects, directory, identity });
const isCurrentSharedScopeMember = createIsCurrentSharedScopeMember({ managedGroups: projects, directory, identity });
+ const openScopeMember = (actorId: string, scope: ScopeId) =>
+ isOpenScopeMember({ actorId, scope, config: configStore, isCurrentSharedScopeMember });
membership.canReadScope = canReadScope;
membership.canManageScope = canManageScope;
membership.canUseSandboxScope = async (actorId, scopeId) =>
@@ -2301,6 +2304,7 @@ export function buildApp(
run: (req) => app.turn(req),
directory,
currentScopeMembers,
+ isOpenScopeMember: openScopeMember,
sessions,
getCron: (id) => crons.get(id),
getAsk: (id) => keychain.getAsk(id),
@@ -2330,6 +2334,7 @@ export function buildApp(
run: (req) => app.turn(req),
directory,
currentScopeMembers,
+ isOpenScopeMember: openScopeMember,
sessions,
},
});
@@ -2371,6 +2376,7 @@ export function buildApp(
leaderLease,
directory,
currentScopeMembers,
+ isOpenScopeMember: openScopeMember,
sessions,
fireLoop: (loopId, fireKey, cronId) => loopFire.fire(loopId, fireKey, cronId),
...(config.databaseUrl
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index 710e535a1..dc3f13973 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -2835,7 +2835,10 @@ test("unified exec and process approvals preserve intent and action identity", a
const entries: Array<Record<string, unknown>> = [];
const tc = fakeToolContext();
tc.execute = tc.backgroundStart = async () => {
- throw new NeedsApproval("danger", "Review this", "approval");
+ throw new NeedsApproval("danger", "Review this", "approval", undefined, "sandbox:synthetic", {
+ session: false,
+ always: false,
+ });
};
const ref: ToolContextRef = {
current: tc,
@@ -2854,6 +2857,7 @@ test("unified exec and process approvals preserve intent and action identity", a
assert.equal(ref.pendingApprovals?.[0]?.command, "danger");
assert.ok(entries.every((e) => e.tool === "sandbox" && e.action === action));
assert.equal(ref.pendingApprovals?.[0]?.purpose, "Verify protected operation");
+ assert.deepEqual(ref.pendingApprovals?.[0]?.grantModes, { session: false, always: false });
}
});
diff --git a/test/aws-role-cutover.test.ts b/test/aws-role-cutover.test.ts
index 517cbdead..612980a17 100644
--- a/test/aws-role-cutover.test.ts
+++ b/test/aws-role-cutover.test.ts
@@ -114,6 +114,7 @@ test("shared ACMECLI cutover isolates brokered STS without shrinking the existin
kind: "channel" as const,
threadRef: "ch:C-owner-auth:cron",
channelRef: "C-owner-auth",
+ isPrivate: true,
audience: [bob, alice],
};
const npm = await built.keychain!.save({ ownerId: "BOB", service: "npm", secret: "npm_BOB", envKey: "NPM_TOKEN" });
@@ -423,6 +424,7 @@ test("cutover policy retains legacy files only in prefer-ephemeral mode", async
const conversation = {
kind: "channel" as const,
channelRef: "C-acmecli-fallback",
+ isPrivate: true,
audience: [actor],
};
diff --git a/test/control-service.test.ts b/test/control-service.test.ts
index 9126697c8..f5ebf367e 100644
--- a/test/control-service.test.ts
+++ b/test/control-service.test.ts
@@ -589,6 +589,11 @@ test("scopeShared is explicit: shared-scope crons default to owner, while collab
});
const { built, control } = setup();
+ await built.app.upsertChannels(
+ [{ channelId: "C9", name: "eng", isPrivate: true }],
+ members.map((member) => ({ channelId: "C9", principalId: member.id })),
+ );
+
const ownerDefault = await control.createCron(
{ title: "private digest", schedule: { everyMs: 3_600_000 }, action: "private digest" },
chanClaims("U1"),
@@ -659,6 +664,88 @@ test("scopeShared is explicit: shared-scope crons default to owner, while collab
assert.equal(personal.ok ? "" : personal.code, "bad_request");
});
+test("Open shared crons retain their owner across collaborator edits and re-check membership", async () => {
+ const { built, control } = setup();
+ const room = scopeId("channel", "C9");
+ const members = [
+ { id: "U1", type: "internal" as const },
+ { id: "U2", type: "internal" as const },
+ ];
+ await built.config.setSharingPosture(scopeId("org", "default-org"), "open");
+ await built.app.upsertDirectory([
+ { principalId: "U1", displayName: "Owner", type: "internal" },
+ { principalId: "U2", displayName: "Editor", type: "internal" },
+ ]);
+ const roster = (ids: string[]) =>
+ built.app.upsertChannels(
+ [{ channelId: "C9", name: "eng", isPrivate: false }],
+ ids.map((principalId) => ({ channelId: "C9", principalId })),
+ );
+ await roster(["U1", "U2"]);
+ const roomClaims = (actorId: string) =>
+ claims(actorId, room, {
+ liveActor: true,
+ members,
+ destination: { type: ROOM.type, target: ROOM.target, audienceScopeId: room },
+ destinations: [ROOM],
+ defaultDestinationKey: ROOM.key,
+ });
+ const request = { title: "Team digest", action: "summarize", schedule: { everyMs: 3_600_000 } };
+ const created = await control.createCron(request, roomClaims("U1"));
+ assert.ok(created.ok, JSON.stringify(created));
+ assert.equal(created.cron.runAs, "scopeShared");
+ assert.equal(created.cron.ownerResourcesRequireOpen, true);
+ const id = created.cron.id;
+ const edited = await control.patchCron(id, { action: "summarize changes" }, roomClaims("U2"));
+ assert.ok(edited.ok, JSON.stringify(edited));
+ assert.equal(edited.cron.owner, "U1");
+ assert.equal(edited.cron.createdBy, "U1");
+ assert.equal(edited.cron.runAs, "scopeShared");
+ assert.equal(edited.cron.ownerResourcesRequireOpen, true);
+ const notices = (await built.deliveries.pending("principal")).filter((d) =>
+ d.idempotencyKey.startsWith("cron-edit-notice:"),
+ );
+ assert.equal(notices.length, 1);
+ assert.equal(notices[0]!.destination.target, "U1");
+ assert.match(notices[0]!.text, /Editor.*Team digest.*do something different/);
+ assert.ok((await control.patchCron(id, { title: "Digest v2" }, claims("U2"))).ok);
+ await control.patchCron(id, { action: "summarize" }, roomClaims("U1"));
+ await control.patchCron(id, { action: "summarize changes" }, roomClaims("U2"));
+ const repeatedNotices = (await built.deliveries.pending("principal")).filter((d) =>
+ d.idempotencyKey.startsWith("cron-edit-notice:"),
+ );
+ assert.equal(repeatedNotices.length, 3, "repeating a reverted edit must notify again");
+
+ assert.ok((await control.getCron(id, claims("U1"))).ok);
+ const deniedMode = await control.patchCron(id, { runAs: "scopeFloor" }, roomClaims("U2"));
+ assert.equal(deniedMode.ok, false);
+ const floor = await control.patchCron(id, { runAs: "scopeFloor" }, roomClaims("U1"));
+ assert.ok(floor.ok && floor.cron.runAs === "scopeFloor");
+ const shared = await control.patchCron(id, { runAs: "scopeShared" }, roomClaims("U1"));
+ assert.ok(shared.ok && shared.cron.runAs === "scopeShared");
+ const noRoster = await control.createCron(
+ { ...request, title: "No roster digest" },
+ { ...roomClaims("U1"), members: undefined },
+ );
+ assert.ok(noRoster.ok && noRoster.cron.runAs === "scopeShared", JSON.stringify(noRoster));
+ const noRosterFloor = await control.createCron(
+ { ...request, runAs: "scopeFloor" },
+ { ...roomClaims("U1"), members: undefined },
+ );
+ assert.equal(noRosterFloor.ok, false);
+ const ownerOnly = await control.createCron({ ...request, runAs: "owner" }, roomClaims("U1"));
+ assert.ok(ownerOnly.ok && ownerOnly.cron.runAs !== "scopeShared");
+ const personal = await control.createCron(request, claims("U1"));
+ assert.ok(personal.ok && personal.cron.runAs !== "scopeShared");
+ await roster(["U1"]);
+ assert.equal((await control.patchCron(id, { title: "revoked edit" }, roomClaims("U2"))).ok, false);
+ assert.equal((await control.createCron({ ...request, runAs: "scopeShared" }, roomClaims("U2"))).ok, false);
+ await built.config.setSharingPosture(room, "isolated");
+ assert.ok((await control.setCronEnabled(id, false, claims("U1"))).ok);
+ assert.equal((await control.patchCron(id, { title: "revoked again" }, roomClaims("U2"))).ok, false);
+ assert.equal((await control.createCron({ ...request, runAs: "scopeShared" }, roomClaims("U1"))).ok, false);
+});
+
test("scopeShared is confined to membership-controlled scopes: a public channel defaults to owner and rejects explicit scopeShared", async () => {
const { control } = setup();
const pubScope = scopeId("channel", "C-PUBLIC");
@@ -704,7 +791,7 @@ test("app.createCron/updateCron backstop: scopeShared needs a shared scope + a m
});
test("a cron's mode (runAs) is editable in place, but only by the owner", async () => {
- const { control } = setup();
+ const { built, control } = setup();
const chanScope = scopeId("channel", "C9");
const members = [
{ id: "U1", type: "internal" as const },
@@ -719,6 +806,11 @@ test("a cron's mode (runAs) is editable in place, but only by the owner", async
defaultDestinationKey: ROOM.key,
});
+ await built.app.upsertChannels(
+ [{ channelId: "C9", name: "eng", isPrivate: true }],
+ members.map((member) => ({ channelId: "C9", principalId: member.id })),
+ );
+
const created = await control.createCron(
{ title: "t", schedule: { everyMs: 3_600_000 }, action: "x", runAs: "scopeShared" },
chanClaims("U1"),
diff --git a/test/cron-credential-resumption.test.ts b/test/cron-credential-resumption.test.ts
index 8ede5caf5..46c44f7ac 100644
--- a/test/cron-credential-resumption.test.ts
+++ b/test/cron-credential-resumption.test.ts
@@ -216,3 +216,20 @@ test("cron credential approval resumes a disabled one-shot job in its original f
assert.equal(f.requests[0]!.conversation.threadRef, f.ask.requesterThreadRef);
assert.equal((await f.deliveries.pending("principal")).length, 1);
});
+
+test("credential resumption retains the originating cron's Open requirement and rechecks it", async () => {
+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
+ await f.crons.update(f.cron.id, {
+ runAs: "scopeShared",
+ ownerResourcesRequireOpen: true,
+ members: [{ id: "U_ALICE", type: "internal" }],
+ });
+ let open = true;
+ f.deps.isOpenScopeMember = async () => open;
+ await fireAskResolution(f.deps, f.ask);
+ assert.equal(f.requests[0]?.ownerResourcesRequireOpen, true);
+ open = false;
+ const out = await fireAskResolution(f.deps, { ...f.ask, id: "revoked-open-ask" });
+ assert.equal(out.authzFailed, true);
+ assert.equal(f.requests.length, 1);
+});
diff --git a/test/cron-scheduler.test.ts b/test/cron-scheduler.test.ts
index 5cf910738..fe7404cfd 100644
--- a/test/cron-scheduler.test.ts
+++ b/test/cron-scheduler.test.ts
@@ -1707,6 +1707,39 @@ test("manual cron preparation and detached fire retain admission across pause",
await scheduler.stop();
});
+test("scheduler rechecks durable Open authorization on each marked shared fire", async () => {
+ const crons = createCronStore();
+ const calls: TurnRequest[] = [];
+ let open = true;
+ const scheduler = createScheduler({
+ crons,
+ deliveries: createDeliveryStore(),
+ idempotency: createIdempotencyStore(),
+ identity: createIdentityService(),
+ isOpenScopeMember: async () => open,
+ run: async (request) => {
+ calls.push(request);
+ return { status: "ok", reply: "done" };
+ },
+ });
+ const cron = await crons.create({
+ owner: "U1",
+ createdBy: "U1",
+ ownerScopeId: scopeId("group", "G1"),
+ runAs: "scopeShared",
+ ownerResourcesRequireOpen: true,
+ members: [member("U1")],
+ action: "digest",
+ schedule: { everyMs: 60_000 },
+ });
+ await runNowSettled(scheduler, cron.id);
+ assert.equal(calls[0]?.ownerResourcesRequireOpen, true);
+ open = false;
+ await runNowSettled(scheduler, cron.id);
+ assert.equal(calls.length, 1);
+ assert.equal((await crons.get(cron.id))?.enabled, false);
+});
+
test("scheduled and manual fires use the saved runtime; clearing it restores inherited behavior", async () => {
const { crons, calls, scheduler } = harness();
const runtime = { harnessId: "pi" as const, modelId: "gpt-6-luna", effortLevel: "low", fastMode: false };
diff --git a/test/cron-scope-shared.test.ts b/test/cron-scope-shared.test.ts
index 27d040d9e..1393dc827 100644
--- a/test/cron-scope-shared.test.ts
+++ b/test/cron-scope-shared.test.ts
@@ -115,6 +115,102 @@ describe("runTrigger: scopeShared unions the owner's keychain into the scope run
assert.equal(seen.length, 0);
});
+ it("a public scopeShared fire re-checks owner membership even without a private roster", async () => {
+ const { deps, seen } = captureDeps();
+ let member = true;
+ deps.currentScopeMembers = async () => undefined;
+ deps.directory = {
+ get: async () => ({ displayName: "Owner" }),
+ channelPrivacy: async () => false,
+ channelMember: async (_channel, principalId) => member && principalId === "U-carol",
+ groupMember: async () => false,
+ };
+ const spec = {
+ owner: "U-carol",
+ ownerScopeId: scopeId("channel", "C-eng"),
+ input: "digest",
+ fireKey: "public-active",
+ surface: "cron",
+ runAs: "scopeShared" as const,
+ members,
+ };
+ assert.equal((await runTrigger(deps, spec)).ran, true);
+ assert.equal(seen[0]!.actor.externalId, "U-carol");
+ assert.equal(seen[0]!.ownerKeychainUnion, true);
+ member = false;
+ const revoked = await runTrigger(deps, { ...spec, fireKey: "public-revoked" });
+ assert.equal(revoked.authzFailed, true);
+ assert.equal(revoked.ran, false);
+ assert.equal(seen.length, 1);
+ });
+
+ it("shared cron channel privacy comes from the current directory, not a saved roster", async () => {
+ for (const isPrivate of [true, false, undefined]) {
+ const { deps, seen } = captureDeps();
+ deps.currentScopeMembers = async () => members;
+ deps.directory = {
+ get: async () => ({ displayName: "Owner" }),
+ channelPrivacy: async () => isPrivate,
+ channelMember: async () => true,
+ groupMember: async () => false,
+ };
+ await runTrigger(deps, {
+ owner: "U-carol",
+ ownerScopeId: scopeId("channel", "C-eng"),
+ input: "digest",
+ fireKey: `privacy-${isPrivate}`,
+ surface: "cron",
+ runAs: "scopeShared",
+ members,
+ });
+ assert.equal(seen[0]!.conversation.isPrivate, isPrivate);
+ assert.equal(seen[0]!.ownerKeychainUnion, true);
+ }
+ });
+
+ it("a no-roster scopeShared fire fails closed without an authoritative membership source", async () => {
+ const { deps, seen } = captureDeps();
+ const out = await runTrigger(deps, {
+ owner: "U-carol",
+ ownerScopeId: scopeId("channel", "C-eng"),
+ input: "digest",
+ fireKey: "no-membership-source",
+ surface: "cron",
+ runAs: "scopeShared",
+ });
+ assert.equal(out.authzFailed, true);
+ assert.equal(seen.length, 0);
+ });
+
+ it("Open-origin shared fires require fresh authorization in public, private, and group scopes", async () => {
+ for (const scope of [scopeId("channel", "public"), scopeId("channel", "private"), scopeId("group", "g1")]) {
+ const { deps, seen } = captureDeps();
+ let open = true;
+ deps.isOpenScopeMember = async (owner, target) => {
+ assert.equal(owner, "U-carol");
+ assert.equal(target, scope);
+ return open;
+ };
+ const spec = {
+ owner: "U-carol",
+ ownerScopeId: scope,
+ input: "digest",
+ fireKey: `${scope}:open`,
+ surface: "cron",
+ runAs: "scopeShared" as const,
+ ownerResourcesRequireOpen: true,
+ members,
+ };
+ assert.equal((await runTrigger(deps, spec)).ran, true);
+ assert.equal(seen[0]?.ownerResourcesRequireOpen, true);
+ open = false;
+ assert.equal((await runTrigger(deps, { ...spec, fireKey: `${scope}:revoked` })).authzFailed, true);
+ assert.equal(seen.length, 1);
+ delete deps.isOpenScopeMember;
+ assert.equal((await runTrigger(deps, { ...spec, fireKey: `${scope}:missing` })).authzFailed, true);
+ }
+ });
+
it("scopeFloor refreshes its audience and re-actors to a current member", async () => {
const { deps, seen } = captureDeps();
const current = [{ id: "U3", type: "internal" as const }];
@@ -249,7 +345,6 @@ describe("notifyOwnerOfCronEdit: the one chokepoint both edit paths share", () =
cron: cron(),
editorId: "U-mate",
changeSummary: ["title"],
- editFingerprint: "f1",
});
assert.equal(enqueued.length, 1);
assert.equal(enqueued[0]!.destination.target, "U-owner");
@@ -267,7 +362,6 @@ describe("notifyOwnerOfCronEdit: the one chokepoint both edit paths share", () =
cron: cron({ owner: "[email protected]" }),
editorId: "U-alice",
changeSummary: ["task"],
- editFingerprint: "f1",
});
assert.equal(enqueued.length, 0, "same person via directory bridge → no notice");
});
@@ -278,7 +372,6 @@ describe("notifyOwnerOfCronEdit: the one chokepoint both edit paths share", () =
cron: cron({ owner: "[email protected]" }),
editorId: "[email protected]",
changeSummary: ["task"],
- editFingerprint: "f1",
});
assert.equal(enqueued.length, 0, "case-only difference → no notice");
});
@@ -289,7 +382,6 @@ describe("notifyOwnerOfCronEdit: the one chokepoint both edit paths share", () =
cron: cron(),
editorId: "U-owner",
changeSummary: ["title"],
- editFingerprint: "f1",
});
assert.equal(a.enqueued.length, 0, "owner editing own cron → no notice");
const b = fakeSink();
@@ -297,7 +389,6 @@ describe("notifyOwnerOfCronEdit: the one chokepoint both edit paths share", () =
cron: cron({ runAs: "scopeFloor" }),
editorId: "U-mate",
changeSummary: ["title"],
- editFingerprint: "f1",
});
assert.equal(b.enqueued.length, 0, "scopeFloor edit → no notice");
const c = fakeSink();
@@ -305,32 +396,28 @@ describe("notifyOwnerOfCronEdit: the one chokepoint both edit paths share", () =
cron: cron({ runAs: "owner" }),
editorId: "U-mate",
changeSummary: ["title"],
- editFingerprint: "f1",
});
assert.equal(c.enqueued.length, 0, "owner-mode edit → no notice");
});
- it("keys idempotency on edit content: same fingerprint repeats one key, a different edit gets a new one", async () => {
+ it("gives each successful edit its own delivery key, including a repeated earlier change", async () => {
const { sink, enqueued } = fakeSink();
await notifyOwnerOfCronEdit(sink, {
cron: cron(),
editorId: "U-mate",
changeSummary: ["title"],
- editFingerprint: "same",
});
await notifyOwnerOfCronEdit(sink, {
cron: cron(),
editorId: "U-mate",
changeSummary: ["title"],
- editFingerprint: "same",
});
await notifyOwnerOfCronEdit(sink, {
cron: cron(),
editorId: "U-mate",
changeSummary: ["task"],
- editFingerprint: "different",
});
- assert.equal(enqueued[0]!.idempotencyKey, enqueued[1]!.idempotencyKey, "identical retry → same idempotency key");
+ assert.notEqual(enqueued[0]!.idempotencyKey, enqueued[1]!.idempotencyKey, "repeated edit → new delivery key");
assert.notEqual(enqueued[0]!.idempotencyKey, enqueued[2]!.idempotencyKey, "distinct edit → new idempotency key");
});
});
diff --git a/test/cron-store.test.ts b/test/cron-store.test.ts
index 2e4b3d375..4f3c883fb 100644
--- a/test/cron-store.test.ts
+++ b/test/cron-store.test.ts
@@ -895,6 +895,26 @@ test("backfillFires survives a cron deleted mid-loop: entries still reach the ta
assert.equal((await backing.get("stays"))!.fireLog, undefined, "the surviving cron is still stripped");
});
+test("Open owner authorization is durable, distinct from legacy mode, and cannot be cleared by a patch", async () => {
+ const backing = createMemoryMap<Cron>();
+ const store = createCronStore(backing);
+ const input = {
+ ...base,
+ ownerScopeId: scopeId("group", "g1"),
+ runAs: "scopeShared" as const,
+ schedule: { everyMs: 60_000 },
+ };
+ const legacy = await store.create(input);
+ const open = await store.create({ ...input, ownerResourcesRequireOpen: true });
+ assert.notEqual(open.id, legacy.id);
+ const restored = createCronStore(backing);
+ assert.equal((await restored.get(open.id))?.ownerResourcesRequireOpen, true);
+ await restored.update(open.id, { title: "edited", runAs: "owner", ownerResourcesRequireOpen: false });
+ await restored.update(open.id, { runAs: "scopeShared" });
+ assert.equal((await restored.get(open.id))?.ownerResourcesRequireOpen, true);
+ assert.equal((await restored.get(legacy.id))?.ownerResourcesRequireOpen, undefined);
+});
+
test("cron runtime overrides survive store reload, distinguish creation, and clear without changing the task", async () => {
const backing = createMemoryMap<Cron>();
const store = createCronStore(backing);
diff --git a/test/execute-scratch.test.ts b/test/execute-scratch.test.ts
index 91b8f50c1..c0f1c02b4 100644
--- a/test/execute-scratch.test.ts
+++ b/test/execute-scratch.test.ts
@@ -509,6 +509,7 @@ test("scoped command wrappers preserve selected AWS credentials and clear unsele
input: {},
connectorEnv: {},
credentialCutoverServices: ["role-service"],
+ resolution: { layers: [] },
} as unknown as TurnSandboxContext);
const { ctx } = routingCtx({
scopedCommand: boxes.scopedCommand,
diff --git a/test/open-continuity-http.test.ts b/test/open-continuity-http.test.ts
new file mode 100644
index 000000000..db3042d24
--- /dev/null
+++ b/test/open-continuity-http.test.ts
@@ -0,0 +1,344 @@
+import "./support/auto-fake-sprites.ts";
+import { test, mock, type TestContext } from "node:test";
+import assert from "node:assert/strict";
+import type { AddressInfo } from "node:net";
+import { randomUUID } from "node:crypto";
+import { createMockHarness } from "../src/harness/mock-harness.ts";
+import type { HarnessTurnInput } from "../src/harness/harness.ts";
+import { mintCapabilityToken, type CapabilityClaims } from "../src/auth/capability-token.ts";
+import { signedHeaders } from "../plugins/chassis/src/core-client.ts";
+import { credentialHandle } from "../src/credentials/keychain.ts";
+import { testConfig } from "./support/test-config.ts";
+
+mock.module("../src/harness/mock-harness.ts", {
+ namedExports: {
+ createMockHarness: () => {
+ const h = createMockHarness();
+ const run = h.turns.runTurn;
+ h.turns.runTurn = async (turn: HarnessTurnInput) => {
+ const match = /!proof (\{[^\n]+\})/.exec(turn.input);
+ if (!match) return run(turn);
+ const command = JSON.parse(match[1]!) as {
+ id?: string;
+ ownerAuth?: boolean;
+ command: string;
+ credentials?: string[];
+ };
+ await turn.emit({ type: "user", payload: { text: turn.input }, scopeLabel: turn.scopeLabel });
+ let reply: string;
+ try {
+ const out = await turn.tools.execute(command.command, {
+ ...(command.id ? { sandboxId: command.id } : {}),
+ ...(command.ownerAuth ? { ownerAuth: true } : {}),
+ ...(command.credentials ? { credentials: command.credentials } : {}),
+ });
+ reply = out.stdout.trim() || out.stderr.trim();
+ } catch (e) {
+ reply = `DENIED: ${String(e)}`;
+ }
+ await turn.emit({ type: "assistant", payload: { text: reply }, scopeLabel: turn.scopeLabel });
+ return { reply };
+ };
+ return h;
+ },
+ },
+});
+const { buildApp } = await import("../src/wiring.ts");
+const { createServer } = await import("../src/api/server.ts");
+const SECRET = "synthetic-continuity-http-signing-key";
+const members = ["alice", "bob"].map((id) => ({ id, type: "internal" as const }));
+
+async function fixture(t: TestContext) {
+ const b = buildApp(testConfig({ signingSecret: SECRET, sandboxResourcesEnabled: true, memoryCapture: "off" }));
+ await b.config.hydrate?.();
+ await b.identity.hydrate();
+ await b.deploymentLayerReady;
+ await b.app.upsertDirectory(
+ ["alice", "bob", "stranger"].map((principalId) => ({
+ principalId,
+ displayName: principalId,
+ type: "internal" as const,
+ })),
+ );
+ const roster = (ids: string[]) =>
+ b.directory.replaceChannels(
+ [{ channelId: "public-room", name: "public-room", isPrivate: false }],
+ ids.map((principalId) => ({ channelId: "public-room", principalId })),
+ );
+ await roster(["alice", "bob"]);
+ await b.config.setSharingPosture("org:default-org", "open");
+ const sharedSandbox = await b.sandboxResources.create("alice", "channel:public-room", "sprites", "shared-proof");
+ await b.sandboxResources.setDefault("alice", "channel:public-room", sharedSandbox.id);
+ const server = createServer(b.app, {
+ signingSecret: SECRET,
+ scheduler: b.scheduler,
+ config: b.config,
+ admin: b.admin,
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ t.after(async () => {
+ await new Promise<void>((r) => server.close(() => r()));
+ b.scheduler.stop();
+ b.deploymentLayerRefresh.stop();
+ await b.runtime.stop();
+ });
+ const cap = (actorId: string, scopeId: CapabilityClaims["scopeId"] = "channel:public-room") =>
+ mintCapabilityToken(
+ {
+ actorId,
+ scopeId,
+ members,
+ liveActor: true,
+ exp: Date.now() + 600_000,
+ destination: { type: "slack", target: "public-room", audienceScopeId: "channel:public-room" },
+ },
+ SECRET,
+ );
+ const request = async (method: string, path: string, token: string, body?: unknown) => {
+ const response = await fetch(base + path, {
+ method,
+ headers: { "x-agent-capability": token, "content-type": "application/json" },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return {
+ status: response.status,
+ body: (await response.json()) as { cron: { id: string; runAs?: string }; runs?: Array<{ status: string }> },
+ };
+ };
+ const awaitFire = async (id: string, token: string) => {
+ const deadline = Date.now() + 10000;
+ while (Date.now() < deadline) {
+ const response = await request("GET", `/v1/crons/${id}/runs`, token);
+ assert.equal(response.status, 200, JSON.stringify(response.body));
+ if (response.body.runs?.some((f) => f.status !== "running")) return response.body.runs;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ assert.fail("HTTP scheduler fire did not finish within 10s");
+ };
+ const turn = async (
+ text: string,
+ actor = "alice",
+ room = true,
+ audience: { externalId: string; isExternalGuest?: boolean }[] = members.map((m) => ({ externalId: m.id })),
+ ) => {
+ const body = JSON.stringify({
+ surface: "test",
+ idempotencyKey: randomUUID(),
+ actor: { externalId: actor },
+ origin: { kind: "human" },
+ conversation: room
+ ? {
+ kind: "channel",
+ channelRef: "public-room",
+ threadRef: `proof:${actor}`,
+ audience,
+ publishMembers: audience,
+ }
+ : { kind: "dm", threadRef: `proof-dm:${actor}` },
+ text,
+ });
+ const response = await fetch(base + "/v1/turns", {
+ method: "POST",
+ headers: { ...signedHeaders(SECRET, "POST", "/v1/turns", body), "content-type": "application/json" },
+ body,
+ });
+ const result = (await response.json()) as { status: string; reply?: string; reason?: string };
+ return { ...result, http: response.status };
+ };
+ return { ...b, cap, request, turn, roster, awaitFire };
+}
+
+test("HTTP Open continuity: personal sandbox follows owner into shared channel and back, never another member", async (t) => {
+ const b = await fixture(t);
+ const resource = await b.sandboxResources.create("alice", "personal:alice", "sprites", "personal-proof");
+ const command = (cmd: string) => `!proof ${JSON.stringify({ id: resource.id, command: cmd })}`;
+ const first = await b.turn(command("printf continuity-sentinel > proof.txt; cat proof.txt"), "alice", false);
+ assert.equal(first.http, 200, JSON.stringify(first));
+ assert.equal(first.reply, "continuity-sentinel");
+ assert.equal((await b.turn(command("cat proof.txt"))).reply, "continuity-sentinel");
+ assert.match((await b.turn(command("cat proof.txt"), "bob")).reply ?? "", /DENIED/);
+ assert.match((await b.turn(command("cat proof.txt"), "stranger")).reply ?? "", /DENIED/);
+ await b.config.setSharingPosture("personal:alice", "isolated");
+ assert.match((await b.turn(command("cat proof.txt"))).reply ?? "", /DENIED/);
+ assert.equal((await b.turn(command("cat proof.txt"), "alice", false)).reply, "continuity-sentinel");
+ await b.config.clearSharingPosture("personal:alice");
+ await b.roster(["bob"]);
+ assert.equal((await b.turn(command("cat proof.txt"))).reply, "continuity-sentinel");
+ const guests = [{ externalId: "alice" }, { externalId: "guest", isExternalGuest: true }];
+ const refused = await b.turn(command("cat proof.txt"), "alice", true, guests);
+ assert.equal(refused.http, 403);
+ assert.equal(refused.status, "refused");
+ assert.equal(refused.reply, undefined);
+});
+
+test("HTTP Open continuity: public channel permits explicit shared cron", async (t) => {
+ const b = await fixture(t);
+ const response = await b.request("POST", "/v1/crons", await b.cap("alice"), {
+ title: "Shared proof",
+ schedule: { everyMs: 3600000 },
+ task: "hello",
+ runAs: "scopeShared",
+ });
+ assert.equal(response.status, 200, JSON.stringify(response.body));
+ assert.equal(response.body.cron.runAs, "scopeShared");
+});
+
+test("HTTP Open continuity: member edit keeps owner, notifies privately, fires with owner resources, and remains manageable in DM", async (t) => {
+ const b = await fixture(t);
+ const resource = await b.sandboxResources.create("alice", "personal:alice", "sprites", "cron-proof");
+ const action = `!proof ${JSON.stringify({ id: resource.id, command: "printf cron-owner-resource" })}`;
+ const owner = await b.cap("alice");
+ const member = await b.cap("bob");
+ const created = await b.request("POST", "/v1/crons", owner, {
+ title: "Continuity proof",
+ schedule: { everyMs: 3600000 },
+ task: action,
+ });
+ assert.equal(created.status, 200, JSON.stringify(created.body));
+ assert.equal(created.body.cron.runAs, "scopeShared", "Open shared cron defaults to owner-backed shared mode");
+ const id = created.body.cron.id as string;
+ const edit = await b.request("PATCH", `/v1/crons/${id}`, member, { title: "Member edited proof" });
+ assert.equal(edit.status, 200, JSON.stringify(edit.body));
+ assert.equal((await b.crons.get(id))?.owner, "alice");
+ assert.equal((await b.crons.get(id))?.runAs, "scopeShared");
+ const notices = await b.deliveries.pending("principal");
+ assert.equal(notices.length, 1);
+ assert.equal(notices[0]!.destination.target, "alice");
+ assert.match(notices[0]!.text, /bob.*renamed/);
+ assert.equal(
+ (await b.request("PATCH", `/v1/crons/${id}`, await b.cap("stranger"), { title: "hijacked" })).status,
+ 403,
+ );
+ assert.equal((await b.request("PATCH", `/v1/crons/${id}`, member, { runAs: "owner" })).status, 403);
+ const fired = await b.request("POST", `/v1/crons/${id}/run`, owner, {});
+ assert.equal(fired.status, 200, JSON.stringify(fired.body));
+ const log = await b.awaitFire(id, owner);
+ assert.ok(log?.length, "HTTP scheduler created a fire log");
+ assert.ok(
+ (await b.deliveries.pending("slack")).some((d) => d.text.includes("cron-owner-resource")),
+ JSON.stringify(log),
+ );
+ assert.equal(
+ (await b.request("PATCH", `/v1/crons/${id}`, await b.cap("alice", "personal:alice"), { title: "Back in personal" }))
+ .status,
+ 200,
+ );
+ assert.equal((await b.deliveries.pending("principal")).length, 1, "owner edits do not notify themselves");
+ await b.roster(["alice"]);
+ assert.equal((await b.request("PATCH", `/v1/crons/${id}`, member, { title: "revoked edit" })).status, 403);
+});
+
+test("HTTP Open shared cron isolates synthetic owner credential and revokes resource access", async (t) => {
+ const b = await fixture(t);
+ assert.ok(b.keychain);
+ const credential = await b.keychain.save({
+ ownerId: "alice",
+ service: "continuity-synthetic",
+ envKey: "CONTINUITY_PROOF_TOKEN",
+ secret: "synthetic-owner-sentinel",
+ });
+ const owner = await b.cap("alice");
+ const created = await b.request("POST", "/v1/crons", owner, {
+ title: "Owner keychain proof",
+ schedule: { everyMs: 3600000 },
+ task: `!proof ${JSON.stringify({ ownerAuth: true, credentials: [credentialHandle(credential.id)], command: 'test "$CONTINUITY_PROOF_TOKEN" = "synthetic-owner-sentinel" && printf owner-credential-present' })}`,
+ });
+ assert.equal(created.status, 200, JSON.stringify(created.body));
+ assert.equal(created.body.cron.runAs, "scopeShared");
+ const id = created.body.cron.id;
+ assert.equal((await b.request("POST", `/v1/crons/${id}/run`, owner, {})).status, 200);
+ const log = await b.awaitFire(id, owner);
+ assert.ok(
+ (await b.deliveries.pending("slack")).some((d) => d.text.includes("owner-credential-present")),
+ JSON.stringify(log),
+ );
+ assert.equal(
+ (await b.turn('!run printf "%s" "${CONTINUITY_PROOF_TOKEN-unset}"', "bob")).reply,
+ "unset",
+ "owner secret is not resident on the shared computer",
+ );
+ await b.roster(["bob"]);
+ const result = await b.scheduler.runNow(id);
+ if (result.started) await result.settled;
+ assert.equal((await b.crons.get(id))?.enabled, false, "owner membership revocation disables the shared cron");
+});
+
+for (const isPrivate of [false, true]) {
+ for (const veto of ["org:default-org", "personal:alice", "channel:public-room"]) {
+ test(`HTTP Open cron opt-out stops owner credentials before materialization (${isPrivate ? "private" : "public"}, ${veto})`, async (t) => {
+ const b = await fixture(t);
+ assert.ok(b.keychain);
+ await b.directory.replaceChannels(
+ [{ channelId: "public-room", name: "public-room", isPrivate }],
+ ["alice", "bob"].map((principalId) => ({ channelId: "public-room", principalId })),
+ );
+ const credential = await b.keychain.save({
+ ownerId: "alice",
+ service: "continuity-veto",
+ envKey: "CONTINUITY_VETO_TOKEN",
+ secret: "synthetic-veto-sentinel",
+ });
+ const response = await b.request("POST", "/v1/crons", await b.cap("alice"), {
+ title: "Opt-out proof",
+ schedule: { everyMs: 3600000 },
+ task: `!proof ${JSON.stringify({ ownerAuth: true, credentials: [credentialHandle(credential.id)], command: 'test "$CONTINUITY_VETO_TOKEN" = "synthetic-veto-sentinel" && printf veto-credential-present' })}`,
+ });
+ assert.equal(response.status, 200, JSON.stringify(response.body));
+ const id = response.body.cron.id;
+ assert.equal((await b.crons.get(id))?.ownerResourcesRequireOpen, true);
+ const initial = await b.scheduler.runNow(id);
+ assert.equal(initial.started, true);
+ if (initial.started) await initial.settled;
+ assert.ok((await b.deliveries.pending("slack")).some((d) => d.text.includes("veto-credential-present")));
+ const original = b.keychain.materializeOwnById.bind(b.keychain);
+ let materializations = 0;
+ b.keychain.materializeOwnById = async (...args: Parameters<typeof original>) => {
+ materializations++;
+ return original(...args);
+ };
+ await b.config.setSharingPosture(veto, "isolated");
+ const revoked = await b.scheduler.runNow(id);
+ if (revoked.started) await revoked.settled;
+ assert.equal(materializations, 0);
+ assert.equal((await b.crons.get(id))?.enabled, false);
+ assert.equal(
+ (await b.deliveries.pending("slack")).filter((d) => d.text.includes("veto-credential-present")).length,
+ 1,
+ );
+ assert.equal((await b.turn('!run printf "%s" "${CONTINUITY_VETO_TOKEN-unset}"', "bob")).reply, "unset");
+ });
+ }
+}
+
+test("HTTP legacy explicit private shared cron remains owner-authorized under isolated posture", async (t) => {
+ const b = await fixture(t);
+ assert.ok(b.keychain);
+ await b.directory.replaceChannels(
+ [{ channelId: "public-room", name: "private-room", isPrivate: true }],
+ ["alice", "bob"].map((principalId) => ({ channelId: "public-room", principalId })),
+ );
+ await b.config.setSharingPosture("org:default-org", "isolated");
+ const credential = await b.keychain.save({
+ ownerId: "alice",
+ service: "continuity-legacy",
+ envKey: "CONTINUITY_LEGACY_TOKEN",
+ secret: "synthetic-legacy-sentinel",
+ });
+ const cron = await b.crons.create({
+ owner: "alice",
+ createdBy: "alice",
+ ownerScopeId: "channel:public-room",
+ runAs: "scopeShared",
+ members,
+ schedule: { everyMs: 3600000 },
+ action: `!proof ${JSON.stringify({ ownerAuth: true, credentials: [credentialHandle(credential.id)], command: 'test "$CONTINUITY_LEGACY_TOKEN" = "synthetic-legacy-sentinel" && printf legacy-credential-present' })}`,
+ destination: { type: "slack", target: "public-room", audienceScopeId: "channel:public-room" },
+ });
+ assert.equal(cron.ownerResourcesRequireOpen, undefined);
+ const fired = await b.scheduler.runNow(cron.id);
+ assert.equal(fired.started, true);
+ if (fired.started) await fired.settled;
+ assert.ok((await b.deliveries.pending("slack")).some((d) => d.text.includes("legacy-credential-present")));
+ assert.equal((await b.turn('!run printf "%s" "${CONTINUITY_LEGACY_TOKEN-unset}"', "bob")).reply, "unset");
+});
diff --git a/test/person-identity.test.ts b/test/person-identity.test.ts
index 372aa0887..a4a8d8df0 100644
--- a/test/person-identity.test.ts
+++ b/test/person-identity.test.ts
@@ -73,6 +73,8 @@ describe("canAdminister: owner checks are same-person, not raw id equality", ()
return {
membershipControlsScope: async () => false,
managesScope: async () => false,
+ isCurrentSharedScopeMember: async () => false,
+ isOpenScopeMember: async () => false,
samePerson: (a: string, b: string) => samePersonInDirectory(dir, a, b),
};
}
@@ -178,14 +180,20 @@ describe("resolveRunAsChange: the owner gate is same-person, not raw id equality
await dir.replace([
{ principalId: "[email protected]", displayName: "Jordan", type: "internal", slackId: "U-jordan" },
]);
- const app = { samePerson: (a: string, b: string) => samePersonInDirectory(dir, a, b) };
+ const app = {
+ isOpenScopeMember: async () => false,
+ samePerson: (a: string, b: string) => samePersonInDirectory(dir, a, b),
+ };
const r = await resolveRunAsChange(app, shared(), "owner", capability);
assert.equal(r.ok, true);
if (r.ok) assert.equal(r.patch.runAs, "owner");
});
it("without the roster the bridge fails closed — forbidden", async () => {
- const app = { samePerson: (a: string, b: string) => samePersonInDirectory(createDirectoryStore(), a, b) };
+ const app = {
+ isOpenScopeMember: async () => false,
+ samePerson: (a: string, b: string) => samePersonInDirectory(createDirectoryStore(), a, b),
+ };
const r = await resolveRunAsChange(app, shared(), "owner", capability);
assert.equal(r.ok, false);
if (!r.ok) assert.equal(r.code, "forbidden");
diff --git a/test/sandbox-open-continuity.test.ts b/test/sandbox-open-continuity.test.ts
new file mode 100644
index 000000000..ded6250c1
--- /dev/null
+++ b/test/sandbox-open-continuity.test.ts
@@ -0,0 +1,532 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createTurnSandboxes, type TurnSandboxContext } from "../src/core/orchestrator/sandboxes.ts";
+import { createToolContext, NeedsApproval, type ToolContextDeps } from "../src/tools/primitives.ts";
+import { intersectEgressPolicies } from "../src/resolution/egress-policy.ts";
+import type { SandboxHandle } from "../src/sandbox/sandbox.ts";
+
+function fixture(
+ source = "group:project",
+ target = "personal:alice",
+ authority = true,
+ toolDeps: Partial<ToolContextDeps> = {},
+) {
+ const state = {
+ open: true,
+ member: true,
+ allowed: true,
+ cutoverMode: "legacy",
+ liveJobs: [] as Array<{ sandboxId: string; scopeId: string }>,
+ targetPolicy: { mode: "denylist", rules: [] } as import("../src/types.ts").CommandPolicy,
+ targetEgress: { allowedHosts: [], deniedHosts: [] } as import("../src/types.ts").EgressPolicy,
+ sourcePolicy: { mode: "denylist", rules: [] } as import("../src/types.ts").CommandPolicy,
+ provisionGate: null as Promise<void> | null,
+ };
+ const provisions: unknown[][] = [];
+ const writes: unknown[] = [];
+ const runs: SandboxHandle[] = [];
+ const commands: string[] = [];
+ const released: unknown[][] = [];
+ const credentialOwners: string[] = [];
+ const restored: Uint8Array[] = [];
+ const starts: SandboxHandle[] = [];
+ const resource = { id: "personal-box", ownerScopeId: target };
+ const commandUses = new Map<string, number>();
+ const approvalCalls: unknown[][] = [];
+ const egressClaims: unknown[] = [];
+ const config = {
+ resolveSharingPostureDurable: async () => (state.open ? "open" : "isolated"),
+ refreshSecurity: async () => {},
+ getCommandPolicy: () => state.targetPolicy,
+ getEgress: () => state.targetEgress,
+ };
+ const sandbox = {
+ provision: async (...args: unknown[]) => {
+ provisions.push(args);
+ if (state.provisionGate) await state.provisionGate;
+ return {
+ id: "machine",
+ resourceId: resource.id,
+ scopeId: target,
+ rootDir: "/workspace",
+ env: (args[1] as { env?: Record<string, string> }).env,
+ };
+ },
+ run: async (handle: SandboxHandle, command: string) => {
+ runs.push(handle);
+ commands.push(command);
+ return { stdout: "existing work", stderr: "", code: 0, timedOut: false };
+ },
+ removeDir: async (...args: unknown[]) => {
+ writes.push(args);
+ },
+ listDir: async () => [],
+ teardown: async (...args: unknown[]) => {
+ released.push(args);
+ },
+ writeFileBytes: async (_handle: unknown, _path: string, bytes: Uint8Array) => {
+ restored.push(bytes);
+ },
+ };
+ const roomSkill = {
+ skill: {
+ id: "room-tool",
+ scopeId: source,
+ manifest: {
+ name: "room-tool",
+ description: "room helper",
+ requiredCapabilities: [],
+ body: "synthetic-room-skill: run scripts/run.js",
+ files: [{ path: "scripts/run.js", content: "synthetic-room-skill-file" }],
+ },
+ signature: "",
+ status: "published",
+ createdBy: "bob",
+ version: 1,
+ grantedCapabilities: [],
+ approvals: [],
+ },
+ shadowed: [],
+ };
+ const resources = {
+ get: async () => resource,
+ access: async () => {
+ if (!state.allowed) throw new Error("permission revoked");
+ return resource;
+ },
+ list: async () => ({ sandboxes: [resource], defaultSandboxId: null }),
+ status: async () => ({ machine: "machine" }),
+ restart: async () => {},
+ retire: async () => {},
+ };
+ const turn = createTurnSandboxes({
+ deps: {
+ sandbox,
+ sandboxResources: resources,
+ processes: { listLive: async () => state.liveJobs },
+ deviceFlowCutover: {
+ listServices: async () => ["custom-login"],
+ resolvePolicy: async () => ({ mode: state.cutoverMode }),
+ residentResetGeneration: async () => null,
+ },
+ keychain: {
+ listByOwner: async () => [
+ { kind: "file", service: "custom-login", origin: "manual", targets: [".custom-login/token"] },
+ ],
+ materializeOwnFiles: async (owner: string) => {
+ credentialOwners.push(owner);
+ return [
+ {
+ service: "custom-login",
+ origin: "manual",
+ files: [
+ { path: ".custom-login/token", contentBase64: Buffer.from("synthetic-own-file").toString("base64") },
+ ],
+ },
+ ];
+ },
+ },
+ config,
+ isCurrentSharedScopeMember: async () => state.member,
+ },
+ actor: { id: "alice", type: "internal" },
+ input: { origin: { kind: "human" } },
+ session: { id: "session" },
+ resolution: {
+ egress: { allowedHosts: [], deniedHosts: ["source-denied.test"] },
+ layers: [
+ { scopeId: "org:test", mode: "ro", mountPath: "global" },
+ { scopeId: "team:private", mode: "ro", mountPath: "private" },
+ { scopeId: source, mode: "rw", mountPath: "" },
+ ],
+ },
+ scopeId: source,
+ memoryScopeId: source,
+ openResourceAccess: authority,
+ credentialServices: [],
+ credentialTools: [],
+ quarantinedServices: [],
+ cutoverModeOf: () => "legacy",
+ egressTokenForTurn: "synthetic-source-egress",
+ egressTokenForPolicy: async (policy: unknown) => {
+ egressClaims.push(policy);
+ return "synthetic-narrow-egress";
+ },
+ connectorEnv: { AGENT_API_TOKEN: "synthetic-room-capability", SHARED_SECRET: "synthetic-room-secret" },
+ credentialCutoverServices: [],
+ ownerAuthAvailable: false,
+ turnSessionDir: "turn/session",
+ turnFilesDir: "turn/session/fire",
+ visibleSkills: [roomSkill],
+ visibleSkillsForTurn: async () => [roomSkill],
+ emitGapWork: () => {},
+ perf: { credsMs: 0 },
+ } as unknown as TurnSandboxContext);
+ const tools = createToolContext({
+ sandbox,
+ sandboxResources: resources,
+ config,
+ provisionResource: turn.provisionResource,
+ accessSandboxResource: turn.accessResource,
+ provision: turn.provision,
+ useSkill: turn.useSkill,
+ layers: [{ scopeId: source, mode: "rw", mountPath: "" }],
+ commandPolicy: () => state.sourcePolicy,
+ authorizeCommand: (_command: string, key = _command, exact?: boolean) => {
+ approvalCalls.push([key, exact]);
+ const uses = commandUses.get(key) ?? 0;
+ if (uses <= 0) return false;
+ commandUses.set(key, uses - 1);
+ return true;
+ },
+ grantedHandles: [],
+ commandCredentials: [
+ { handle: "room-credential", env: [{ key: "ROOM_SECRET", value: "synthetic-room-credential" }] },
+ ],
+ backgroundBroker: {
+ start: async (handle: SandboxHandle) => {
+ starts.push(handle);
+ return { processId: "job" };
+ },
+ },
+ workspace: {},
+ deploy: {},
+ acl: {},
+ createdBy: "alice",
+ ...toolDeps,
+ } as unknown as ToolContextDeps);
+ return {
+ turn,
+ tools,
+ provisions,
+ writes,
+ runs,
+ starts,
+ credentialOwners,
+ restored,
+ egressClaims,
+ approvalCalls,
+ released,
+ commands,
+ approve: (key: string, mode: "once" | "session" | "always" = "once") =>
+ commandUses.set(key, (commandUses.get(key) ?? 0) + (mode === "once" ? 1 : Infinity)),
+ state,
+ };
+}
+
+test("Open shared requests execute on the owner's personal machine without moving room credentials or files", async () => {
+ const f = fixture();
+ assert.equal((await f.tools.execute("pwd", { sandboxId: "personal-box" })).stdout, "existing work");
+ assert.equal(f.provisions.length, 1);
+ assert.equal(JSON.stringify(f.provisions).includes("synthetic-room"), false);
+ assert.deepEqual(f.writes, []);
+ assert.deepEqual(f.credentialOwners, ["alice"]);
+ assert.equal(f.runs.at(-1)?.env?.OWN_SECRET, undefined);
+ assert.ok(f.restored.some((bytes) => Buffer.from(bytes).includes("synthetic-own-file")));
+ assert.equal(JSON.stringify(f.provisions).includes("team:private"), false);
+ const skill = await f.tools.skill("room-tool", { sandboxId: "personal-box" });
+ assert.match(skill.content ?? "", /synthetic-room-skill/);
+ assert.equal(skill.dir, undefined);
+ await f.turn.reclaimBox();
+ assert.deepEqual(f.writes, []);
+});
+
+test("Open cross-scope cached handles recheck membership, posture, and target authorization", async () => {
+ for (const revoke of ["revoke", "isolate", "deny"] as const) {
+ const f = fixture();
+ await f.turn.provisionResource("personal-box");
+ if (revoke === "revoke") f.state.member = false;
+ else if (revoke === "isolate") f.state.open = false;
+ else f.state.allowed = false;
+ await assert.rejects(f.turn.provisionResource("personal-box"), /authorized|permission/);
+ }
+});
+
+test("a command waiting on another provision rechecks the target policy before continuing", async () => {
+ const f = fixture();
+ let release!: () => void;
+ f.state.provisionGate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const first = f.turn.provisionResource("personal-box");
+ while (f.provisions.length === 0) await new Promise((resolve) => setImmediate(resolve));
+ const access = await f.turn.accessResource("personal-box");
+ const second = f.turn.provisionResource(access, (current) => {
+ if (current.commandPolicy?.rules.some((rule) => rule.decision === "deny")) throw new Error("policy changed");
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "blocked", decision: "deny" }] };
+ release();
+ await first;
+ await assert.rejects(second, /policy changed/);
+});
+
+test("a one-shot command approval is consumed once after a pending provision settles", async () => {
+ const f = fixture();
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "protected", decision: "require_approval" }] };
+ let approvalKey = "";
+ await assert.rejects(f.tools.execute("protected", { sandboxId: "personal-box" }), (error: unknown) => {
+ assert.ok(error instanceof NeedsApproval);
+ approvalKey = error.approvalKey!;
+ return true;
+ });
+ f.approve(approvalKey);
+ let release!: () => void;
+ f.state.provisionGate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const first = f.turn.provisionResource("personal-box");
+ while (f.provisions.length === 0) await new Promise((resolve) => setImmediate(resolve));
+ const execute = f.tools.execute("protected", { sandboxId: "personal-box" });
+ await new Promise((resolve) => setImmediate(resolve));
+ release();
+ await first;
+ assert.equal((await execute).stdout, "existing work");
+ await assert.rejects(f.tools.execute("protected", { sandboxId: "personal-box" }), NeedsApproval);
+});
+
+test("Open continuity works from a DM into a currently joined shared scope, not another person's computer", async () => {
+ await fixture("personal:alice", "group:project").turn.provisionResource("personal-box");
+ await assert.rejects(fixture("group:project", "personal:bob").turn.provisionResource("personal-box"), /authorized/);
+});
+
+test("Open continuity applies consistently to inventory and explicit management", async () => {
+ const f = fixture();
+ const listed = (await f.tools.sandboxResources!("list")) as { sandboxes: unknown[] };
+ assert.equal(listed.sandboxes.length, 1);
+ await f.tools.computerStatus("personal-box");
+ await f.tools.restartComputer("personal-box");
+ await f.tools.sandboxResources!("retire", { sandboxId: "personal-box" });
+ f.state.open = false;
+ assert.equal(((await f.tools.sandboxResources!("list")) as { sandboxes: unknown[] }).sandboxes.length, 0);
+ await assert.rejects(f.tools.computerStatus("personal-box"), /authorized/);
+});
+
+test("Open personal credentials never flow into another shared computer", async () => {
+ const f = fixture("personal:alice", "group:project");
+ await f.tools.execute("pwd", { sandboxId: "personal-box" });
+ assert.equal(JSON.stringify(f.provisions).includes("synthetic-own"), false);
+ assert.equal(JSON.stringify(f.provisions).includes("synthetic-room"), false);
+ assert.deepEqual(f.credentialOwners, []);
+ assert.deepEqual(f.restored, []);
+});
+
+test("background starts use the authorized personal target and recheck revocation", async () => {
+ const f = fixture();
+ await f.tools.backgroundStart("node work.js", { sandboxId: "personal-box" });
+ assert.equal(f.starts[0]?.scopeId, "personal:alice");
+ assert.equal(f.starts[0]?.env, undefined);
+ f.state.member = false;
+ await assert.rejects(f.tools.backgroundStart("node work.js", { sandboxId: "personal-box" }), /authorized/);
+});
+
+test("untrusted background authority and copying room command credentials are refused", async () => {
+ await assert.rejects(
+ fixture("group:project", "personal:alice", false).turn.provisionResource("personal-box"),
+ /authorized/,
+ );
+ const f = fixture();
+ await assert.rejects(
+ f.tools.execute("pwd", { sandboxId: "personal-box", credentials: ["room-credential"] }),
+ /cannot be copied/,
+ );
+ assert.deepEqual(f.provisions, []);
+});
+
+test("target command denials and approvals apply before either execution path can provision", async () => {
+ for (const decision of ["deny", "require_approval"] as const) {
+ const f = fixture();
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "blocked", decision }] };
+ await assert.rejects(f.tools.execute("blocked", { sandboxId: "personal-box" }));
+ await assert.rejects(f.tools.backgroundStart("blocked", { sandboxId: "personal-box" }));
+ assert.deepEqual(f.provisions, []);
+ }
+});
+
+test("cross-target egress policies narrow both provider policy and minted proxy capability", async () => {
+ const f = fixture();
+ f.state.targetEgress = { allowedHosts: ["api.example.test"], deniedHosts: ["target-denied.test"] };
+ await f.turn.provisionResource("personal-box");
+ const policy = { allowedHosts: ["api.example.test"], deniedHosts: ["source-denied.test", "target-denied.test"] };
+ assert.deepEqual(f.egressClaims, [policy]);
+ const opts = f.provisions[0]![1] as { egress: unknown; egressToken: string };
+ assert.deepEqual(opts.egress, policy);
+ assert.equal(opts.egressToken, "synthetic-narrow-egress");
+ f.state.targetEgress = { allowedHosts: ["new.example.test"], deniedHosts: [] };
+ await f.turn.provisionResource("personal-box");
+ assert.equal(f.egressClaims.length, 2);
+ assert.equal(f.provisions.length, 2);
+ assert.deepEqual((f.provisions[1]![1] as { egress: unknown }).egress, {
+ allowedHosts: ["new.example.test"],
+ deniedHosts: ["source-denied.test"],
+ });
+});
+
+test("cached personal access reapplies device-flow quarantine without injecting environment credentials", async () => {
+ const f = fixture();
+ const first = await f.turn.provisionResource("personal-box");
+ const firstRestores = f.restored.length;
+ f.state.cutoverMode = "ephemeral_only";
+ const second = await f.turn.provisionResource("personal-box");
+ assert.equal(second, first);
+ assert.ok(f.commands.some((command) => command.includes("rm -rf -- '.custom-login/token'")));
+ assert.equal(f.restored.length, firstRestores);
+ assert.equal(second.env, undefined);
+});
+
+test("cross-scope teardown preserves live jobs regardless of which conversation started them", async () => {
+ for (const jobScope of ["personal:alice", "group:project", "group:other"]) {
+ const f = fixture();
+ f.state.liveJobs = [{ sandboxId: "personal-box", scopeId: jobScope }];
+ await f.turn.provisionResource("personal-box");
+ await f.turn.reclaimBox();
+ assert.deepEqual(f.released[0]![1], { keepWarm: true });
+ }
+});
+
+test("egress intersection narrows host suffixes and refuses disjoint allowlists", () => {
+ assert.deepEqual(
+ intersectEgressPolicies(
+ { allowedHosts: ["example.test"], deniedHosts: ["deny.test"] },
+ { allowedHosts: ["api.example.test"], deniedHosts: ["other.test"] },
+ ),
+ { allowedHosts: ["api.example.test"], deniedHosts: ["deny.test", "other.test"] },
+ );
+ assert.throws(
+ () => intersectEgressPolicies({ allowedHosts: ["a.test"] }, { allowedHosts: ["b.test"] }),
+ /no overlap/,
+ );
+});
+
+test("two requiring policies produce one target-qualified one-shot approval", async () => {
+ for (const method of ["execute", "backgroundStart"] as const) {
+ const f = fixture();
+ f.state.sourcePolicy = { mode: "denylist", rules: [{ pattern: "protected", decision: "require_approval" }] };
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "command", decision: "require_approval" }] };
+ let approvalKey = "";
+ await assert.rejects(f.tools[method]("protected command", { sandboxId: "personal-box" }), (err: unknown) => {
+ assert.ok(err instanceof NeedsApproval);
+ assert.deepEqual(err.grantModes, { session: false, always: false });
+ approvalKey = err.approvalKey!;
+ assert.deepEqual(JSON.parse(approvalKey.slice("sandbox:".length)), ["personal:alice", "protected", "command"]);
+ return true;
+ });
+ assert.deepEqual(f.approvalCalls, [[approvalKey, true]]);
+ f.approve(approvalKey);
+ await f.tools[method]("protected command", { sandboxId: "personal-box" });
+ await assert.rejects(f.tools[method]("protected command", { sandboxId: "personal-box" }), NeedsApproval);
+ }
+});
+
+test("target denial wins before a source one-shot approval is consumed", async () => {
+ const f = fixture();
+ f.state.sourcePolicy = { mode: "denylist", rules: [{ pattern: "protected", decision: "require_approval" }] };
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "protected", decision: "deny" }] };
+ f.approve("protected", "once");
+ await assert.rejects(f.tools.execute("protected", { sandboxId: "personal-box" }), /denied/);
+ assert.deepEqual(f.approvalCalls, []);
+});
+
+test("cross-scope credential handles are refused without resolving or consuming grants", async () => {
+ const events: string[] = [];
+ const f = fixture("group:project", "personal:alice", true, {
+ commandCredentials: [
+ {
+ handle: "lazy",
+ resolve: async () => {
+ events.push("resolve");
+ return {
+ env: [{ key: "TOKEN", value: "synthetic-command-secret" }],
+ singleUse: true,
+ commit: async () => {
+ events.push("commit");
+ },
+ };
+ },
+ },
+ ],
+ });
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "protected", decision: "require_approval" }] };
+ await assert.rejects(
+ f.tools.execute("protected", { sandboxId: "personal-box", credentials: ["lazy"] }),
+ /cannot be copied/,
+ );
+ assert.deepEqual(events, []);
+ assert.deepEqual(f.approvalCalls, []);
+ assert.deepEqual(f.provisions, []);
+});
+
+test("credential-specific source policy still restricts an explicit cross-scope target", async () => {
+ const calls: unknown[] = [];
+ const f = fixture("group:project", "personal:alice", true, {
+ commandPolicyForCredentials: (handles, ownerAuth) => {
+ calls.push([handles, ownerAuth]);
+ return { mode: "denylist", rules: [{ pattern: "protected", decision: "deny" }] };
+ },
+ });
+ await assert.rejects(f.tools.execute("protected", { sandboxId: "personal-box" }), /denied/);
+ assert.deepEqual(calls, [[[], false]]);
+ assert.deepEqual(f.provisions, []);
+});
+
+test("credential-specific source approval intersects target policy without consuming approval on target denial", async () => {
+ const f = fixture("group:project", "personal:alice", true, {
+ commandPolicyForCredentials: () => ({
+ mode: "denylist",
+ rules: [{ pattern: "protected", decision: "require_approval" }],
+ }),
+ });
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "command", decision: "deny" }] };
+ f.approve("protected");
+ await assert.rejects(f.tools.execute("protected command", { sandboxId: "personal-box" }), /denied/);
+ assert.deepEqual(f.approvalCalls, []);
+ f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "command", decision: "require_approval" }] };
+ let approvalKey = "";
+ await assert.rejects(f.tools.execute("protected command", { sandboxId: "personal-box" }), (error: unknown) => {
+ assert.ok(error instanceof NeedsApproval);
+ assert.deepEqual(error.grantModes, { session: false, always: false });
+ approvalKey = error.approvalKey!;
+ assert.deepEqual(JSON.parse(approvalKey.slice("sandbox:".length)), ["personal:alice", "protected", "command"]);
+ return true;
+ });
+ f.approve(approvalKey);
+ await f.tools.execute("protected command", { sandboxId: "personal-box" });
+ await assert.rejects(f.tools.execute("protected command", { sandboxId: "personal-box" }), NeedsApproval);
+});
+
+test("same-scope explicit execution prepares credentials only after provisioning and wraps the effective env", async () => {
+ const events: string[] = [];
+ const f: ReturnType<typeof fixture> = fixture("group:project", "group:project", true, {
+ commandPolicyForCredentials: (handles, ownerAuth) => {
+ assert.deepEqual(handles, ["lazy"]);
+ assert.equal(ownerAuth, false);
+ events.push("policy");
+ return { mode: "denylist", rules: [] };
+ },
+ commandCredentials: [
+ {
+ handle: "lazy",
+ resolve: async () => {
+ assert.equal(f.provisions.length, 1);
+ events.push("resolve");
+ return {
+ env: [{ key: "TOKEN", value: "synthetic-command-secret" }],
+ singleUse: true,
+ commit: async () => {
+ events.push("commit");
+ },
+ };
+ },
+ },
+ ],
+ scopedCommand: (command, env) => {
+ events.push("wrap");
+ assert.equal(env?.TOKEN, "synthetic-command-secret");
+ assert.equal(env?.SHARED_SECRET, "synthetic-room-secret");
+ return command;
+ },
+ });
+ await f.tools.execute("pwd", { sandboxId: "personal-box", credentials: ["lazy"] });
+ assert.deepEqual(events, ["policy", "resolve", "commit", "wrap"]);
+ assert.equal(f.runs.at(-1)?.env?.TOKEN, "synthetic-command-secret");
+});
diff --git a/test/sandbox-resources.test.ts b/test/sandbox-resources.test.ts
index 8bcc5ae84..d42577082 100644
--- a/test/sandbox-resources.test.ts
+++ b/test/sandbox-resources.test.ts
@@ -70,7 +70,8 @@ function fixture(configure?: (backend: Sandbox) => void, legacyScopes = ["person
backends: { local: backend },
defaultBackend: "local",
lock: createMemoryAdvisoryLock(),
- canUseScope: async (actor: string, scope: string) => actor === "admin" || scope === `personal:${actor}`,
+ canUseScope: async (actor: string, scope: string) =>
+ actor === "admin" || scope === `personal:${actor}` || (actor === "alice" && scope === "channel:team"),
} satisfies Parameters<typeof createSandboxResources>[0];
const resources = createSandboxResources(options);
const router = createSandboxRouter({ routes, backends: { local: backend }, defaultBackend: "local", resources });
diff --git a/test/session-syscalls.test.ts b/test/session-syscalls.test.ts
index 01e8924be..e5da2e53a 100644
--- a/test/session-syscalls.test.ts
+++ b/test/session-syscalls.test.ts
@@ -1369,6 +1369,7 @@ test("nested delegated work retains the reminder destination without exposing su
scope,
);
const control = createControlService({
+ isOpenScopeMember: async () => false,
createCron: async (input: unknown) => ({ id: "reminder", ...(input as object) }),
} as never);
const reminder = await control.createCron(
diff --git a/test/sharing-posture.test.ts b/test/sharing-posture.test.ts
index 01e71b48a..5315f55f4 100644
--- a/test/sharing-posture.test.ts
+++ b/test/sharing-posture.test.ts
@@ -1,7 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
import { composeSharingPosture, parseSharingPosture, type SharingPosture } from "../src/resolution/sharing-posture.ts";
-import { carriedFileHandles, MAX_OPEN_SHARED_SCOPES, sharingSourcesForTurn } from "../src/resolution/sharing-access.ts";
+import {
+ carriedFileHandles,
+ isOpenScopeMember,
+ MAX_OPEN_SHARED_SCOPES,
+ sharingSourcesForTurn,
+} from "../src/resolution/sharing-access.ts";
import { createMemoryConfigStore, type PersistedSharingPosture } from "../src/resolution/config-store.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
import { scopeId, type Principal, type Session } from "../src/types.ts";
@@ -55,6 +60,35 @@ test("durable sharing policy composes organization, personal, and room vetoes an
assert.equal(await restarted.getSharingPostureOwnDurable(room), "open");
});
+test("Open membership re-checks durable organization, person, room, and membership restrictions", async () => {
+ const store = createMemoryMap<PersistedSharingPosture>();
+ const writer = createMemoryConfigStore("acme", { sharingPostures: store });
+ const reader = createMemoryConfigStore("acme", { sharingPostures: store });
+ const org = scopeId("org", "acme");
+ const personal = scopeId("personal", "U1");
+ const room = scopeId("channel", "C1");
+ let member = true;
+ const input = {
+ actorId: "U1",
+ scope: room,
+ config: reader,
+ isCurrentSharedScopeMember: async () => member,
+ };
+ assert.equal(await isOpenScopeMember(input), false);
+ await writer.setSharingPosture(org, "open");
+ assert.equal(await isOpenScopeMember(input), true);
+ for (const scope of [personal, room, org]) {
+ await writer.setSharingPosture(scope, "isolated");
+ assert.equal(await isOpenScopeMember(input), false);
+ await writer.setSharingPosture(scope, "open");
+ assert.equal(await isOpenScopeMember(input), true);
+ }
+ member = false;
+ assert.equal(await isOpenScopeMember(input), false);
+ member = true;
+ assert.equal(await isOpenScopeMember({ ...input, scope: personal }), false);
+});
+
test("open sources accept live human-authored ambient turns and bind carry to the authenticated actor", async () => {
const config = createMemoryConfigStore("acme", { defaultSharingPosture: "open" });
const sessions = { listByParticipant: async () => [] };
diff --git a/test/skills-source-read.test.ts b/test/skills-source-read.test.ts
index 9003aa014..0cc48d7ef 100644
--- a/test/skills-source-read.test.ts
+++ b/test/skills-source-read.test.ts
@@ -136,7 +136,7 @@ test("a body read avoids sandbox work and a file request materializes that skill
const turn = createTurnSandboxes({
deps: {
skills: { recordUse: async () => {} },
- sandboxResources: { get: async () => ({ ownerScopeId: "personal:U1" }) },
+ sandboxResources: { access: async () => ({ id: "resource-1", ownerScopeId: "personal:U1" }) },
sandbox: {
provision: async (_layers: unknown, options?: { sandboxId?: string }) => {
sandboxIds.push(options?.sandboxId);
diff --git a/test/swarms.test.ts b/test/swarms.test.ts
index 48aeb5f2b..cceddea17 100644
--- a/test/swarms.test.ts
+++ b/test/swarms.test.ts
@@ -899,7 +899,7 @@ test("the orchestrator sandbox path selects worker storage without changing auth
const forum = await sandboxes.create("alice", root.scopeId, "modal", "Forum");
assert.equal((await turn.provisionResource(forum.id)).resourceId, forum.id);
const foreign = await sandboxes.create("bob", "personal:bob", "modal", "Other scope");
- await assert.rejects(turn.provisionResource(foreign.id), /does not belong/);
+ await assert.rejects(turn.provisionResource(foreign.id), /requires permission to use its owning scope/);
});
test("durable worker rejects excessive swarm claims before calling the harness", async () => {
diff --git a/test/turn-origin.test.ts b/test/turn-origin.test.ts
index 50bd036c5..717ab4bca 100644
--- a/test/turn-origin.test.ts
+++ b/test/turn-origin.test.ts
@@ -102,3 +102,17 @@ test("matching automation origins preserve or combine every screening payload",
assert.match(merged.kind === "automation" ? (merged.screenData ?? "") : "", /typed/);
assert.match(merged.kind === "automation" ? (merged.screenData ?? "") : "", /legacy/);
});
+
+test("Open owner-resource requirement survives legacy and typed automation normalization", () => {
+ const origin: TurnOrigin = { kind: "automation", useOwnerKeychain: true, ownerResourcesRequireOpen: true };
+ assert.deepEqual(normalizeTurnOrigin(turnOriginRequestFields(origin)), origin);
+ assert.equal(resolveTurnOrigin({ origin, triggered: true }).kind, "automation");
+ assert.deepEqual(
+ resolveTurnOrigin({
+ origin: { kind: "automation", useOwnerKeychain: true },
+ triggered: true,
+ ownerResourcesRequireOpen: true,
+ }),
+ origin,
+ );
+});