Multiplayer agent harness for work.
Allow live speakers to use their keychain in Open conversations (#1307)
Joshua France4121bd2a4c8c
diff --git a/SECURITY.md b/SECURITY.mdindex bb3574749..f8ec950ab 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -92,8 +92,15 @@ turn's memory tool; they are not added to reusable sandbox API tokens. Candidateis limited to 100 recent sessions and 200 files, and binary files require explicit sharingbefore being copied into a different conversation's computer. Organization, personal, room, and source-room policy compose fail-closed, withIsolated winning. These reads are labelled and audited, but model output is not a disclosure-control. Open does not change transcript audience filtering, writes or memory capture,-credential materialization, automation or ambient turns, tenant boundaries, another+control. In an Open shared conversation, the authenticated internal speaker can use their+own keychain through isolated owner execution without creating a room grant. Credentials+are supplied only to a separate disposable computer, which is destroyed at turn end, not+the shared workspace. Each owner command rechecks composed sharing policy and current+membership. Other people's credentials and automated or ambient turns still require grants.+The raw keychain-use endpoint remains personal-or-grant-only. Command approvals remain in+force; code can still disclose secrets while using them, so this is not an output filter.+Open does not change transcript audience filtering, writes or memory capture,+automation or ambient turns, tenant boundaries, anotherperson's entitlement, command approvals, content screening, or egress. In Auto, carriedskills and their bundled files must pass screening before prompt inclusion or materialization;flagged, oversized, or unavailable screening leaves the carried skill inaccessible.diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex a0bf6030c..030a42cd1 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -1021,7 +1021,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {audience: conversation.audience,acl: deps.acl,origin: input.origin,- trustedLiveHuman: liveTurn,+ trustedLiveHuman: liveAuthorTurn,targetScope: scopeId,config: deps.config,sessions: deps.sessions,@@ -1340,11 +1340,14 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const cutoverModeOf = (service: string): DeviceFlowCutoverMode => cutoverModes.get(service) ?? "legacy";const quarantinedServices = credentialServices.filter((service) => cutoverModeOf(service) === "ephemeral_only");const credentialCutoverServices = credentialServices.filter((service) => cutoverModeOf(service) !== "legacy");+ const openSpeakerKeychain =+ liveAuthorTurn && conversation.kind !== "dm" && sharingSources.includes(personalScope(actor.id));const isolateOwnerKeychain =- deps.sharedOwnerAuthIsolation === true &&- conversation.kind !== "dm" &&- input.origin.kind === "automation" &&- input.origin.useOwnerKeychain === true;+ openSpeakerKeychain ||+ (deps.sharedOwnerAuthIsolation === true &&+ conversation.kind !== "dm" &&+ input.origin.kind === "automation" &&+ input.origin.useOwnerKeychain === true);let ownerAuthAvailable = isolateOwnerKeychain;if (deps.sharedOwnerAuthIsolation === true &&@@ -1401,13 +1404,13 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {keychainInjected.push(m);}}- if (!strictReadOnly && deps.connectorTokens && conversation.kind === "dm") {+ if (!strictReadOnly && deps.connectorTokens && (conversation.kind === "dm" || openSpeakerKeychain)) {for (const host of CONNECTOR_HOSTS) {const token =(await deps.connectorTokens.connectorAccessToken(host, actor.id, "personal")) ??(await deps.connectorTokens.connectorAccessToken(host, actor.id)) ??(await deps.connectorTokens.connectorAccessToken(host, actor.id, "company"));- if (token) connectorEnv[envKey(host)] = token;+ if (token) (openSpeakerKeychain ? ownerAuthEnv : connectorEnv)[envKey(host)] = token;}}perf.credsMs += Date.now() - credsStart;@@ -1698,6 +1701,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {connectorEnv,egressTokenForTurn,isolateOwnerKeychain,+ openSpeakerKeychain,ownerAuthAvailable,ownerAuthEnv,ownerEnvCredentialIds,@@ -1999,6 +2003,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const keychainBlock = renderKeychainManifest({scopeId,conversationKind: conversation.kind,+ openSpeakerKeychain,actorId: actor.id,members,entriesByOwner,diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.tsindex 56a5383ab..644a577bb 100644--- a/src/core/orchestrator/sandboxes.ts+++ b/src/core/orchestrator/sandboxes.ts@@ -1,4 +1,5 @@import type { Principal, Resolution, ScopeId, Session } from "../../types.ts";+import { personalScope } from "../../types.ts";import type { GapPhase } from "../../sessions/session-store.ts";import { type SandboxHandle, supportsProcessSessions } from "../../sandbox/sandbox.ts";import { reconcileProcesses } from "../../processes/reconcile.ts";@@ -37,6 +38,7 @@ export interface TurnSandboxContext {connectorEnv: Record<string, string>;egressTokenForTurn: string | undefined;isolateOwnerKeychain: boolean;+ openSpeakerKeychain?: boolean;ownerAuthAvailable: boolean;ownerAuthEnv: Record<string, string>;ownerEnvCredentialIds: string[];@@ -67,6 +69,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {connectorEnv,egressTokenForTurn,isolateOwnerKeychain,+ openSpeakerKeychain,ownerAuthAvailable,ownerAuthEnv,ownerEnvCredentialIds,@@ -99,6 +102,14 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {: undefined;if (ownerAuthAvailable) {ownerAuthCommand = (command) => {+ if (openSpeakerKeychain)+ deps.auditLog.record({+ at: Date.now(),+ principalId: actor.id,+ action: "keychain.open_speaker_use",+ resource: "isolated owner execution",+ scopeLabel: scopeId,+ });for (const credentialId of ownerEnvCredentialIds) {deps.auditLog.record({at: Date.now(),@@ -416,8 +427,15 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {return handle;};const provisionOwnerAuth = ownerAuthAvailable- ? (): Promise<SandboxHandle> => {- if (ownerAuthBox.handle) return Promise.resolve(ownerAuthBox.handle);+ ? async (): Promise<SandboxHandle> => {+ // Recheck each command, including commands reusing this turn's isolated computer.+ if (+ openSpeakerKeychain &&+ (!(await deps.isCurrentSharedScopeMember?.(actor.id, scopeId)) ||+ (await deps.config?.resolveSharingPostureDurable(personalScope(actor.id), scopeId)) !== "open")+ )+ throw new Error("Open speaker keychain access is no longer authorized");+ if (ownerAuthBox.handle) return ownerAuthBox.handle;if (ownerAuthBox.pending && !ownerAuthProvisionInFlight) {return Promise.reject(new Error("owner-auth box initialization failed and cleanup is still pending"));}@@ -441,6 +459,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {handle,keychain: deps.keychain,ownerId: actor.id,+ ...(openSpeakerKeychain ? { allOrigins: true } : {}),...(credentialCutoverServices.length ? { excludeServices: credentialCutoverServices } : {}),onAnomaly: (service, detail) =>deps.errors?.record({diff --git a/src/credentials/device-flow-persist.ts b/src/credentials/device-flow-persist.tsindex 79f3aa3fc..501c58331 100644--- a/src/credentials/device-flow-persist.ts+++ b/src/credentials/device-flow-persist.ts@@ -555,9 +555,11 @@ export async function registerLoginPaths(input: RegisterLoginInput): Promise<{ sreturn { service, captured: saved.includes(service) };}-export async function materializeDeviceFlowLogins(input: DeviceFlowPersistInput): Promise<string[]> {+export async function materializeDeviceFlowLogins(+ input: DeviceFlowPersistInput & { allOrigins?: boolean },+): Promise<string[]> {const bundles = (await input.keychain.materializeOwnFiles(input.ownerId)).filter(- (b) => b.origin === DEVICE_FLOW_ORIGIN && serviceSelected(input, b.service),+ (b) => (input.allOrigins === true || b.origin === DEVICE_FLOW_ORIGIN) && serviceSelected(input, b.service),);if (!bundles.length) return [];diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.tsindex 0b5649243..d456b6757 100644--- a/src/credentials/keychain.ts+++ b/src/credentials/keychain.ts@@ -1510,6 +1510,7 @@ export function renderAskNotice(export interface KeychainManifestInput {scopeId: ScopeId;conversationKind: "dm" | "channel" | "group";+ openSpeakerKeychain?: boolean;actorId: string;members: Array<{ id: string; displayName?: string }>;entriesByOwner: Map<string, KeychainCredentialMeta[]>;@@ -1588,11 +1589,15 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: number: `one-time grant \`${g.id}\` available (purpose: "${g.purpose}")`;};const ownPersonal = input.scopeId === toScopeId("personal", input.actorId);- const OWN_NOTE = "their own — no grant needed in this personal conversation";+ const openSpeaker =+ input.openSpeakerKeychain === true && (input.conversationKind === "channel" || input.conversationKind === "group");+ const OWN_NOTE = openSpeaker+ ? 'their own — available with execute scope:"owner" for this live Open turn; no grant needed'+ : "their own — no grant needed in this personal conversation";const memberLines: string[] = [];let hasOwn = false;for (const member of input.members) {- const own = ownPersonal && member.id === input.actorId;+ const own = (ownPersonal || openSpeaker) && samePerson(member.id, input.actorId);for (const c of input.entriesByOwner.get(member.id) ?? []) {memberLines.push(credLine(member, c, own ? OWN_NOTE : grantNoteFor(c.id), now, own));hasOwn ||= own;@@ -1614,12 +1619,17 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberconst inDm = input.conversationKind === "dm";+ let ownershipGuidance =+ "Using one here requires a grant from its OWNER — you never see another person's secret or token without one. ";+ if (ownPersonal)+ ownershipGuidance =+ "You are in this person's own personal conversation: their credentials need no grant here — access is implied. Anyone else's still requires a grant from its OWNER, and shared conversations require a grant unless Open sharing authorizes isolated execution with the live speaker's own credentials. ";+ else if (openSpeaker)+ ownershipGuidance = `Open sharing authorizes the authenticated live speaker to use their OWN keychain through execute scope:"owner", without a grant. Other people's credentials still require their owner's grant. This does not give the room or background jobs continuing access. `;lines.push("## Teammate keychains");lines.push("Teammates keep personal logins — and connected apps (Gmail, Calendar, Slack, …) — in a keychain. " +- (ownPersonal- ? "You are in this person's own personal conversation: their credentials need no grant here — access is implied. Anyone else's still requires a grant from its OWNER, and in a shared conversation EVERY credential needs one, including this person's own. "- : "Using one here requires a grant from its OWNER — you never see another person's secret or token without one. ") ++ ownershipGuidance +"A connector grant works exactly like any other: ask the owner, they approve on their own turn, then `use` it.",);if (memberLines.length) {@@ -1628,7 +1638,13 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberlines.push("", "No keychain credentials registered yet for the people here.");}- if (hasOwn) {+ if (hasOwn && openSpeaker) {+ lines.push(+ "",+ `Use execute with scope:"owner" for commands needing the speaker's logins or connected apps. Their env credentials, connector tokens and saved CLI logins are supplied there automatically, except services restricted to a dedicated credential tool. Do not load them through /v1/keychain/use on the shared computer.`,+ "This is a separate, disposable computer: it cannot see the shared workspace, and is destroyed at the end of this turn. Keep credential-using commands there; return only the results needed for the task. Never copy secrets into the shared workspace or pass them to background jobs. Normal command approvals still apply.",+ );+ } else if (hasOwn) {lines.push("","Use the execute tool handle for env-style logins. Load file-style bundles on demand with:",diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex 7de7724d4..e244a7b89 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -332,7 +332,8 @@ export function coreToolOptions(config: Config): CoreToolOptions {return {sandboxResources: config.sandboxResourcesEnabled,scratchExec: config.scratchExecEnabled,- ownerAuthExec: config.sharedOwnerAuthIsolation,+ // Availability is checked per turn; Open can be enabled without restarting the harness.+ ownerAuthExec: true,reachExec: config.reachExecEnabled,controlTools: Boolean(config.signingSecret && config.apiBaseUrl),execTimeoutMs: config.execTimeoutDefaultMs,@@ -734,7 +735,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):? '- "scratch": a blank, instant box. Same OS/runtimes/CLIs, shared org files & skills at ./global (read-only), firewalled network — but NO logins, NO credentials or capability tokens, and NOTHING persists past this turn. Prefer it for heavy self-contained work (crunching fetched material, throwaway experiments, parallel or disk-hungry runs needing no workspace files) — it keeps the sandbox responsive; if the run needs logins, workspace files, or its writes must survive, use scope:"scoped".\n': "") +(ownerAuthExec- ? "- \"owner\": available only to owner-authorized shared automation; this invocation-only auth box has org-global files plus the owner's credentials, no room workspace or $AGENT_API_* tokens, and is destroyed after the turn. Use for commands that need the owner's login without putting it on the shared computer.\n"+ ? "- \"owner\": available to the live speaker in Open shared conversations and to owner-authorized shared automation; this invocation-only auth box has org-global files plus the owner's credentials, no room workspace or $AGENT_API_* tokens, and is destroyed after the turn. Use for commands that need the owner's login without putting it on the shared computer.\n": "") +"- a room like \"#project-alpha\": a channel you and this person are both in — runs the command on THAT room's computer. Other rooms are places you VISIT: read, search, fetch (ls/grep/cat); don't rearrange. That box has none of this conversation's logins or capability tokens. Say where anything you bring back came from.\n" +"If a file or piece of work isn't on this computer, don't declare it lost — check the rooms listed under 'Other computers you can reach'.\n" +@@ -747,7 +748,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):`Run a shell command and return its stdout/stderr/exit code. Pick a computer with \`scope\`:\n` +'- "scoped" (DEFAULT): this conversation\'s sandbox — its workspace files, turn-private inbox paths, shared-file handles, cached logins, and $AGENT_API_* tokens; working state is retained within provider recovery limits; publish durable code to git and artifacts to Files.\n' +(ownerAuthExec- ? '- "owner": available only to owner-authorized shared automation; this invocation-only auth box has org-global files plus the owner\'s credentials, no shared workspace or $AGENT_API_* tokens, and is destroyed after the turn. Use it for owner-authenticated work in shared automation.\n'+ ? '- "owner": available to the live speaker in Open shared conversations and to owner-authorized shared automation; this invocation-only auth box has org-global files plus the owner\'s credentials, no shared workspace or $AGENT_API_* tokens, and is destroyed after the turn. Use it for credential-using commands without putting personal logins on the shared computer.\n': "") +(scratchExec? '- "scratch": a blank, instant box. Same OS/runtimes/CLIs, shared org files & skills at ./global (read-only), firewalled network — but NO logins, NO credentials or capability tokens ($AGENT_API_TOKEN etc. are absent), and NOTHING persists past this turn. Prefer it for heavy self-contained work — crunching or analyzing material you can fetch onto it, throwaway experiments, checks against public code, anything parallel or disk-hungry whose only product is the answer — because it keeps this conversation\'s computer responsive for everything else. Work on THIS conversation\'s workspace (its checkouts, uncommitted changes) and anything needing logins stays scoped; if a scratch run turns out to need those, re-run it with scope:"scoped".\n'diff --git a/src/resolution/sharing-access.ts b/src/resolution/sharing-access.tsindex 53c559d58..8a845653b 100644--- a/src/resolution/sharing-access.ts+++ b/src/resolution/sharing-access.ts@@ -28,7 +28,7 @@ export async function sharingSourcesForTurn(input: SharingSourcesInput): Promiseif (input.posture !== "open" ||input.actor.type !== "internal" ||- input.origin.kind !== "human" ||+ (input.origin.kind !== "human" && !(input.origin.kind === "ambient" && input.origin.live === true)) ||!input.trustedLiveHuman ||!input.config ||!input.isCurrentSharedScopeMemberdiff --git a/src/resolution/sharing-posture.ts b/src/resolution/sharing-posture.tsindex b88343e80..b55283f4c 100644--- a/src/resolution/sharing-posture.ts+++ b/src/resolution/sharing-posture.ts@@ -23,5 +23,5 @@ export function composeSharingPostures(export function renderSharingPosturePrompt(actor: Principal, sourceScopes: readonly ScopeId[]): string {if (sourceScopes.length === 0) return "";const actorLabel = actor.displayName?.trim() || actor.id;- return `## Sharing posture: Open\nThis live request can read ${actorLabel}'s personally entitled resources from outside this conversation. Those sources are labelled by origin: ${sourceScopes.join(", ")}. Open access can reveal private information in a shared reply. Use only what this request needs, do not volunteer or repeat unrelated private information, and prefer this conversation's own sources when they are sufficient. File discovery is limited to 200 files and 25 shared contexts from the 100 most recent sessions. Files not listed, and binary files, require an explicit share. Access is read-only; writes, message history, credentials, approvals, security screening, and egress remain scoped normally.`;+ return `## Sharing posture: Open\nThis live request can read ${actorLabel}'s personally entitled resources from outside this conversation. Those sources are labelled by origin: ${sourceScopes.join(", ")}. Open access can reveal private information in a shared reply. Use only what this request needs, do not volunteer or repeat unrelated private information, and prefer this conversation's own sources when they are sufficient. File discovery is limited to 200 files and 25 shared contexts from the 100 most recent sessions. Files not listed, and binary files, require an explicit share. Carried context is read-only. In Open shared conversations the authenticated live speaker can use their own keychain on a separate disposable computer; other people's credentials and background jobs remain grant-gated. Writes, message history, approvals, security screening, and egress remain scoped normally.`;}diff --git a/src/wiring.ts b/src/wiring.tsindex bfa91cb88..741a8804e 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1756,7 +1756,7 @@ export function buildApp(webhooks,resolveBaseModelId: () => orgBaseModelId() ?? fallback.modelId,...(config.scratchExecEnabled ? { scratchExec: true } : {}),- ...(config.sharedOwnerAuthIsolation ? { ownerAuthExec: true, sharedOwnerAuthIsolation: true } : {}),+ ...(config.sharedOwnerAuthIsolation ? { sharedOwnerAuthIsolation: true } : {}),directory,isCurrentSharedScopeMember,managedGroups: projects,diff --git a/test/open-speaker-keychain.test.ts b/test/open-speaker-keychain.test.tsnew file mode 100644index 000000000..fcfc279e8--- /dev/null+++ b/test/open-speaker-keychain.test.ts@@ -0,0 +1,72 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createTurnSandboxes, type TurnSandboxContext } from "../src/core/orchestrator/sandboxes.ts";+import { coreToolOptions } from "../src/harness/agent-tools.ts";+import { loadConfig } from "../src/config.ts";++test("Open owner execution is discoverable even when automation isolation defaults off", () => {+ const config = loadConfig({});+ assert.equal(config.sharedOwnerAuthIsolation, false);+ assert.equal(coreToolOptions(config).ownerAuthExec, true);+});++test("Open owner computer rechecks revocation before reuse and is destroyed, never shared", async () => {+ let member = true;+ let posture = "open";+ const global = { scopeId: "org:test", mode: "ro", mountPath: "global" };+ const handle = { id: "owner-test", cwd: "/tmp/owner-test" };+ const provisions: unknown[][] = [];+ const releases: unknown[][] = [];+ const audits: unknown[] = [];+ const context = {+ deps: {+ sandbox: {+ provision: async (...args: unknown[]) => {+ provisions.push(args);+ return handle;+ },+ teardown: async (...args: unknown[]) => {+ releases.push(args);+ },+ },+ auditLog: { record: (event: unknown) => audits.push(event) },+ config: { resolveSharingPostureDurable: async () => posture },+ isCurrentSharedScopeMember: async () => member,+ },+ input: {},+ actor: { id: "alice", type: "internal" },+ session: { id: "session-one" },+ resolution: { layers: [global, { scopeId: "channel:room", mode: "rw", mountPath: "." }] },+ scopeId: "channel:room",+ memoryScopeId: "channel:room",+ transferId: "turn-one",+ isolateOwnerKeychain: true,+ openSpeakerKeychain: true,+ ownerAuthAvailable: true,+ ownerAuthEnv: { TEST_TOKEN: "synthetic-secret" },+ ownerEnvCredentialIds: ["synthetic-id"],+ connectorEnv: {},+ credentialTools: [],+ credentialServices: [],+ credentialCutoverServices: [],+ quarantinedServices: [],+ } as unknown as TurnSandboxContext;+ const boxes = createTurnSandboxes(context);+ assert.equal(await boxes.provisionOwnerAuth!(), handle);+ assert.equal(await boxes.provisionOwnerAuth!(), handle);+ assert.equal(provisions.length, 1);+ assert.deepEqual(provisions[0]![0], [global]);+ assert.deepEqual((provisions[0]![1] as { scratch: unknown }).scratch, { key: "owner-auth:session-one:turn-one" });+ member = false;+ await assert.rejects(boxes.provisionOwnerAuth!(), /no longer authorized/);+ member = true;+ posture = "isolated";+ await assert.rejects(boxes.provisionOwnerAuth!(), /no longer authorized/);+ posture = "open";+ const command = boxes.ownerAuthCommand!("true");+ assert.match(command, /unset AGENT_API_TOKEN AGENT_OAUTH_CONSENT_TOKEN AGENT_CREDENTIAL_TOKEN/);+ assert.ok(!JSON.stringify(audits).includes("synthetic-secret"));+ await boxes.reclaimBox();+ assert.deepEqual(releases, [[handle, { destroy: true }]]);+ assert.equal(boxes.ownerAuthBox.handle, null);+});diff --git a/test/sharing-context-e2e.test.ts b/test/sharing-context-e2e.test.tsindex 81365f8cd..efb7af843 100644--- a/test/sharing-context-e2e.test.ts+++ b/test/sharing-context-e2e.test.ts@@ -84,6 +84,10 @@ test("sharing e2e: personal files and memories follow the speaker, opt-out, andassert.doesNotMatch(await b.turn("!sysprompt", true), /OWN_MEMORY_U2|open-personal-U2/);assert.match(await b.turn("!read shared/open-personal-U1/notes.txt", true, "U2"), /no file/);assert.equal(await b.turn("!read shared/open-personal-U2/notes.txt", true, "U2"), "BOB_PAYLOAD");+ assert.equal(+ await b.turn("!read shared/open-personal-U2/notes.txt", true, "U2", { origin: { kind: "ambient", live: true } }),+ "BOB_PAYLOAD",+ );await b.config.setSharingPosture("personal:U1", "isolated");await b.workspace.write("personal:U1", "notes.txt", "NEW_PRIVATE_PAYLOAD");assert.match(await b.turn("!read shared/open-personal-U1/notes.txt", true), /no file/);@@ -388,3 +392,102 @@ test("sharing e2e: screening off preserves carried skills without model calls",assert.equal(await b.turn("!run python3 skills/unscreened-helper/scripts/value.py", true), "SHARED_SKILL_OK");assert.equal(b.modelGateway.audit().filter((rec) => rec.model === "mock-security").length, 0);});++test("Open speaker keychain uses a disposable computer, follows the speaker, and never grants the room", async (t) => {+ const b = await fixture(t, {+ signingSecret: "open-keychain-test-signing-key",+ apiBaseUrl: "http://core.test",+ maxAttempts: 1,+ sharedOwnerAuthIsolation: false,+ });+ assert.ok(b.keychain);+ for (const id of ["U1", "U2"]) {+ await b.keychain.save({ ownerId: id, service: "npm", secret: `npm_${id}`, envKey: "NPM_TOKEN" });+ await b.keychain.save({+ ownerId: id,+ service: "custom-cli",+ files: [{ path: ".custom-cli/auth", contentBase64: Buffer.from(`file_${id}`).toString("base64") }],+ });+ await b.keychain.setConnectorToken("gmail.googleapis.com", id, {+ accessToken: `gmail_${id}`,+ expiresAt: Date.now() + 3600000,+ });+ }+ const prompt = await b.turn("!sysprompt", true);+ assert.match(prompt, /execute scope:"owner"/);+ assert.match(prompt, /U1[^\n]*npm[^\n]*no grant needed/);+ assert.match(prompt, /U2[^\n]*npm[^\n]*no grant for this conversation/);+ assert.ok(!prompt.includes("npm_U1"));+ await b.workspace.write("channel:C1", "room-only.txt", "room_data");+ const probe = `python3 -c 'import os,pathlib; p=pathlib.Path.home()/".custom-cli/auth"; print("|".join([os.getenv("NPM_TOKEN","unset"),os.getenv("VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM","unset"),p.read_text() if p.exists() else "absent",os.getenv("AGENT_API_TOKEN","unset"),"room" if pathlib.Path("room-only.txt").exists() else "isolated"]))'`;+ assert.equal(await b.turn(`!owner ${probe}`, true), "npm_U1|gmail_U1|file_U1|unset|isolated");+ assert.equal(await b.turn(`!owner ${probe}`, true, "U2"), "npm_U2|gmail_U2|file_U2|unset|isolated");+ for (const id of ["U1", "U2", "U1"]) {+ assert.equal(+ await b.turn(`!owner ${probe}`, true, id, { origin: { kind: "ambient", live: true } }),+ `npm_${id}|gmail_${id}|file_${id}|unset|isolated`,+ );+ }+ const ambientPrompt = await b.turn("!sysprompt", true, "U2", { origin: { kind: "ambient", live: true } });+ assert.match(ambientPrompt, /U2[^\n]*npm[^\n]*no grant needed/);+ assert.match(ambientPrompt, /U1[^\n]*npm[^\n]*no grant for this conversation/);+ assert.match(await b.turn(`!run ${probe}`, true, "U2"), /^unset\|unset\|absent\|/);+ await b.directory.replaceGroups([+ { groupId: "G1", principalId: "U1" },+ { groupId: "G1", principalId: "U2" },+ ]);+ for (const origin of [{ kind: "human" }, { kind: "ambient", live: true }] as const) {+ assert.equal(+ await b.turn(`!owner ${probe}`, true, "U1", {+ origin,+ conversation: {+ kind: "group",+ channelRef: "G1",+ threadRef: "G1:open-keychain",+ audience: [{ externalId: "U1" }, { externalId: "U2" }],+ publishMembers: [{ externalId: "U1" }, { externalId: "U2" }],+ },+ }),+ "npm_U1|gmail_U1|file_U1|unset|isolated",+ );+ }+ assert.deepEqual(await b.keychain.grantsForScope("group:G1"), []);+ assert.deepEqual(await b.keychain.grantsForScope("channel:C1"), []);+ assert.ok((await b.auditLog.events()).some((event) => event.action === "keychain.open_speaker_use"));+ // No speaker credential may persist through an owner-computer teardown.+ assert.equal(await b.turn(`!owner python3 -c 'open("retained.txt","w").write("private")'`, true), "(exit 0)");+ assert.equal(+ await b.turn(`!owner python3 -c 'import os; print("leaked" if os.path.exists("retained.txt") else "clean")'`, true),+ "clean",+ );+ let deniedTurn = 0;+ const denied = (origin: TurnRequest["origin"] = { kind: "human" }) =>+ b.turn("!owner true", true, "U1", {+ origin,+ conversation: {+ kind: "channel",+ channelRef: "C1",+ threadRef: `C1:keychain-denied-${++deniedTurn}`,+ audience: [{ externalId: "U1" }, { externalId: "U2" }],+ publishMembers: [{ externalId: "U1" }, { externalId: "U2" }],+ },+ });+ await b.config.setSharingPosture("personal:U1", "isolated");+ await assert.rejects(denied(), /owner-auth box is not available/);+ await assert.rejects(denied({ kind: "ambient", live: true }), /owner-auth box is not available/);+ await b.config.setSharingPosture("personal:U1", "open");+ await b.config.setSharingPosture("channel:C1", "isolated");+ await assert.rejects(denied(), /owner-auth box is not available/);+ await assert.rejects(denied({ kind: "ambient", live: true }), /owner-auth box is not available/);+ await b.config.setSharingPosture("channel:C1", "open");+ await b.config.setSharingPosture("org:default-org", "isolated");+ await assert.rejects(denied(), /owner-auth box is not available/);+ await assert.rejects(denied({ kind: "ambient", live: true }), /owner-auth box is not available/);+ await b.config.setSharingPosture("org:default-org", "open");+ await assert.rejects(denied({ kind: "automation" }), /owner-auth box is not available/);+ await assert.rejects(denied({ kind: "ambient" }), /owner-auth box is not available/);+ await assert.rejects(denied({ kind: "ambient", live: false }), /owner-auth box is not available/);+ await b.remove("U1");+ await assert.rejects(denied(), /owner-auth box is not available/);+ await assert.rejects(denied({ kind: "ambient", live: true }), /owner-auth box is not available/);+});diff --git a/test/sharing-posture.test.ts b/test/sharing-posture.test.tsindex 454785199..01e71b48a 100644--- a/test/sharing-posture.test.ts+++ b/test/sharing-posture.test.ts@@ -55,7 +55,7 @@ test("durable sharing policy composes organization, personal, and room vetoes anassert.equal(await restarted.getSharingPostureOwnDurable(room), "open");});-test("open sources require a live internal human and bind personal carry to the authenticated actor", async () => {+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 () => [] };const targetScope = scopeId("channel", "C1");@@ -71,7 +71,23 @@ test("open sources require a live internal human and bind personal carry to the};assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "human" } }), [scopeId("personal", "U2")]);assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "automation" } }), []);- assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "ambient", live: true } }), []);+ assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "ambient", live: true } }), [+ scopeId("personal", "U2"),+ ]);+ assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "ambient" } }), []);+ assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "ambient", live: false } }), []);+ assert.deepEqual(+ await sharingSourcesForTurn({ ...base, trustedLiveHuman: false, origin: { kind: "ambient", live: true } }),+ [],+ );+ assert.deepEqual(+ await sharingSourcesForTurn({+ ...base,+ isCurrentSharedScopeMember: async () => false,+ origin: { kind: "ambient", live: true },+ }),+ [],+ );assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "direct" } }), []);assert.deepEqual(await sharingSourcesForTurn({ ...base, actor: { id: "U2", type: "guest" }, origin: { kind: "human" } }),