Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Consolidate credential context into one owner-grouped inventory (#2206)

Regan Bell5884b6e71ccd
diff --git a/skills-seed/use-shared-credential/SKILL.md b/skills-seed/use-shared-credential/SKILL.md
index 2f314a09d..5e978eff0 100644
--- a/skills-seed/use-shared-credential/SKILL.md
+++ b/skills-seed/use-shared-credential/SKILL.md
@@ -13,12 +13,15 @@ core stamps the secret onto the outbound call at the wire and returns the respon
## When this applies
-Your system prompt lists, under **"Shared org credentials available to you"**, any credentials
-vended to _this_ conversation — each with its slug, host, and the methods/paths you may use. If
-that section is absent (or your environment has no `AGENT_CREDENTIAL_TOKEN`), you have no shared
-broker credentials. A separately authorized personal login or connected app may still be
-available; use only its advertised capabilities and permissions. Never route around a denial
-or ask the user to paste a token.
+The **Credentials** inventory groups available credentials by owner. Organization rows marked
+`proxy` give the host and allowed methods/paths. Select the exact `service_<slug>` handle in
+`execute.credentials` for the command making the request. Core supplies
+`AGENT_CREDENTIAL_TOKEN` only to that command; its absence before selection does not mean
+access is missing. Use that token, not `AGENT_API_TOKEN`, for broker requests.
+
+Only listed credentials are available. A separately authorized personal login or connected
+app may also be available; use only its advertised capabilities and permissions. Never
+route around a denial or ask the user to paste a token.
## How to call it
@@ -40,6 +43,7 @@ The reply is an envelope — the upstream status + body, never the secret:
{ "status": 200, "contentType": "application/json", "body": "<the upstream response text>" }
```
+A non-2xx `status` is the upstream service’s response, not a broker failure.
Parse `body` as the upstream returned it (e.g. JSON). For a write (when the credential allows a
non-GET method), put the request payload in the `body` field of your POST.
diff --git a/src/api/contract.ts b/src/api/contract.ts
index 8561e9d66..3d7027098 100644
--- a/src/api/contract.ts
+++ b/src/api/contract.ts
@@ -1,3 +1 @@
export const CAPABILITY_HEADER = "x-agent-capability";
-
-export const CAPABILITY_CURL_AUTH = `-H "${CAPABILITY_HEADER}: $AGENT_API_TOKEN"`;
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 9044ab262..a208a6113 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -59,7 +59,12 @@ import { createBackgroundBroker } from "../connectors/background-exec-broker.ts"
import { createMonitorBroker, readBackgroundOutputTail } from "../monitors/monitor-broker.ts";
import { isPollSurface, isSilentPollReply } from "../triggers/run-trigger.ts";
import { envKey } from "../credentials/connector-token.ts";
-import { credentialHandle, renderKeychainManifest, type PublicServiceCredential } from "../credentials/keychain.ts";
+import {
+ credentialHandle,
+ renderKeychainManifest,
+ type PublicServiceCredential,
+ type KeychainManifestInput,
+} from "../credentials/keychain.ts";
import { finishProcessCredentials } from "../credentials/execute-files.ts";
import {
configuredConnectorProviders,
@@ -1471,7 +1476,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const connectorEnv: Record<string, string> = {};
const credsStart = Date.now();
const commandCredentials: CommandCredential[] = [];
- const credentialDescriptions: string[] = [];
+ const credentialDescriptions: NonNullable<KeychainManifestInput["execution"]> = [];
const credentialIdentities = new Map<string, string>();
const authorizeOwnerCredentials = async (): Promise<void> => {
@@ -1504,6 +1509,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
credential: CommandCredential,
description: string,
identity = credential.handle,
+ ownerId = actor.id,
+ credentialId?: string,
): void => {
const existing = credentialIdentities.get(credential.handle);
if (existing !== undefined) {
@@ -1512,9 +1519,13 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
}
credentialIdentities.set(credential.handle, identity);
commandCredentials.push(credential);
- credentialDescriptions.push(
- `- \`${credential.handle}\` — ${description}; execute scope \`${credential.scope ?? "scoped"}\`.`,
- );
+ credentialDescriptions.push({
+ handle: credential.handle,
+ ownerId,
+ description,
+ credentialId,
+ scope: credential.scope ?? "scoped",
+ });
};
const registerKeychainCredentials = async (addCredential: typeof addCredentialToCatalog): Promise<void> => {
if (external || strictReadOnly || !deps.keychain) return;
@@ -1523,7 +1534,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (credential.kind === "broker" || isBackendCredential(credential)) continue;
addCredential(
{
- handle: credentialHandle(credential.id),
+ handle: credentialHandle(credential),
resolve: async () => {
const prepared = await keychain.prepareMaterialize(grant.id, scopeId, actor.id);
return {
@@ -1535,6 +1546,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
},
`${credential.service}, owner ${credential.ownerId}, grant ${grant.id}`,
credential.id,
+ credential.ownerId,
+ credential.id,
);
}
const ownAllowed =
@@ -1546,7 +1559,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (credential.kind === "broker" || isBackendCredential(credential)) continue;
addCredential(
{
- handle: credentialHandle(credential.id),
+ handle: credentialHandle(credential),
scope: isolateOwnerKeychain ? "owner" : "scoped",
resolve: async () => {
await authorizeOwnerCredentials();
@@ -1557,6 +1570,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
},
`${credential.service}, owner ${credential.ownerId}`,
credential.id,
+ credential.ownerId,
+ credential.id,
);
}
}
@@ -1588,7 +1603,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (!healthy && !operatorFallback) continue;
addCredential(
{
- handle: `connector_${host.replace(/[^a-zA-Z0-9]/g, "_")}_${accountType ?? "default"}`,
+ handle: `connector:${host}:${accountType ?? "default"}`,
scope: isolateOwnerKeychain ? "owner" : "scoped",
resolve: async () => {
await authorizeOwnerCredentials();
@@ -1599,7 +1614,10 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
},
!healthy && operatorFallback
? `${host}, configured operator fallback; availability checked on use`
- : `${host} connector, owner ${actor.id}, account ${accountType ?? "default"}`,
+ : `${host} connector, account ${accountType ?? "default"}`,
+ healthy && status && "credentialId" in status ? status.credentialId : undefined,
+ actor.id,
+ healthy && status && "credentialId" in status ? status.credentialId : undefined,
);
}
}
@@ -1607,7 +1625,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
};
await registerConnectorCredentials(addCredentialToCatalog);
perf.credsMs += Date.now() - credsStart;
- let sharedCredsBlock = "";
// 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[] = [];
@@ -1763,52 +1780,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
deps.capabilitySecret ?? deps.signingSecret,
deps.capabilityTokenCompression,
);
- if (deps.serviceCreds) {
- const records = serviceCredRecords;
- const enabled = new Set(
- records
- .filter((r) => !isBackendCredential(r) && r.enabled && r.hasSecret && r.delivery !== "env")
- .map((r) => r.slug),
- );
- if (enabled.size > 0) {
- const slugs = [...grantedCredSlugs].filter((s) => enabled.has(s));
- if (slugs.length > 0) {
- const usable = records.filter((r) => slugs.includes(r.slug));
- const lines = usable.map((r) => {
- const methods = r.allowedMethods?.length ? r.allowedMethods.toSorted().join("/") : "GET";
- const paths = r.allowedPathPrefixes?.length
- ? `paths ${r.allowedPathPrefixes.toSorted().join(", ")}`
- : "any path";
- return `- \`${r.slug}\` (${r.name}; shared org credential) → ${r.host} (${methods}; ${paths})`;
- });
- sharedCredsBlock =
- "\n\n## Shared org credentials available to you\n" +
- "Select the corresponding `service_<slug>` handle in execute.credentials. You CANNOT see the secret — call the " +
- "target BY PROXY through the broker, which injects it server-side. Use exactly this (with the " +
- "$AGENT_CREDENTIAL_TOKEN env var, NOT $AGENT_API_TOKEN):\n" +
- "```\n" +
- 'curl -fsS -X POST "$AGENT_API_URL/v1/credentials/broker" \\\n' +
- ' -H "x-agent-capability: $AGENT_CREDENTIAL_TOKEN" \\\n' +
- ' -H "content-type: application/json" \\\n' +
- ' -d \'{"credential":"<slug>","method":"GET","url":"https://<host>/<path>?<query>"}\'\n' +
- "```\n" +
- 'The reply is `{"status":<upstream status>,"contentType":…,"body":"<upstream text>"}` — parse `body`. ' +
- "For Git smart HTTP clone/fetch/push using a shared org credential, use core as the Git remote " +
- "so the token stays server-side: " +
- "`$AGENT_API_URL/v1/credentials/git/<slug>/<repo-path>.git`, with " +
- '`git -c http.extraHeader="x-agent-capability: $AGENT_CREDENTIAL_TOKEN" ...`. ' +
- "Git through this route uses the configured org account, not automatically the requesting user's account; " +
- "a live personal OAuth connector does not switch this route's identity. The credential name is an admin label " +
- "and does not identify the upstream username. Choose among credentials authorized for this conversation " +
- "based on the task and the user's intent; a shared account is a valid choice, not an automatic fallback. " +
- "For personal Git access, use an authorized personal login that supports Git transport. " +
- "If the intended account is unclear before a write, clarify it rather than silently switching accounts. " +
- "A non-2xx `status` is the UPSTREAM service's own answer (e.g. a bad query or its auth), not a broker " +
- "error. Use ONLY these (slug → host; allowed methods; allowed paths):\n" +
- lines.sort().join("\n");
- }
- }
- }
}
const egressSecret = deps.capabilitySecret ?? deps.signingSecret;
const egressTokenForPolicy = async (egress: EgressPolicy): Promise<string | undefined> => {
@@ -1902,7 +1873,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
return { env: [{ key: credential.envKey!, value: current.secret }] };
},
},
- `${credential.name}, org credential, provides ${credential.envKey}`,
+ `${credential.name}; provides ${credential.envKey}`,
+ undefined,
+ "Organization",
);
} else if (deps.signingSecret && deps.apiBaseUrl) {
addCredential(
@@ -1910,7 +1883,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
handle: `service_${credential.slug}`,
resolve: async () => ({ env: [{ key: "AGENT_CREDENTIAL_TOKEN", value: await resolveBrokerToken() }] }),
},
- `org credential ${credential.slug}, provides scoped broker capability`,
+ `${credential.name}; proxy ${credential.host}; ${(credential.allowedMethods?.length ? credential.allowedMethods : ["GET"]).toSorted().join("/")}; ${credential.allowedPathPrefixes?.length ? `paths ${credential.allowedPathPrefixes.toSorted().join(", ")}` : "any path"}; use the use-shared-credential skill`,
+ undefined,
+ "Organization",
);
}
}
@@ -2340,11 +2315,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
)
systemPrompt +=
"\n\n## Connected app access\nComposio is configured in the backend. Load the composio skill and use /v1/composio through the authenticated agent API. No Composio project key is delivered to your computer; the backend checks account ownership and context access.";
- if (credentialDescriptions.length)
- systemPrompt +=
- "\n\n## Execution credentials\nRequest exact handles in execute.credentials:\n" +
- credentialDescriptions.sort().join("\n");
- systemPrompt += sharedCredsBlock;
if (actorIsOrgAdmin) {
systemPrompt +=
"\n\n## Acting for an org admin\n" +
@@ -2420,17 +2390,17 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
})().catch(swallowAs("orchestrator: conversation roster", null));
if (rosterBlock) systemPrompt += `\n\n${rosterBlock}`;
}
- if (!external && !strictReadOnly && deps.keychain && deps.signingSecret && deps.apiBaseUrl) {
+ if (!strictReadOnly && (deps.keychain || credentialDescriptions.length)) {
const audienceMembers = conversation.audience.filter((p) => p.type === "internal");
const members = [
...(audienceMembers.some((p) => samePerson(p.id, actor.id)) ? [] : [actor]),
...audienceMembers,
].map((p) => ({ id: p.id, ...(p.displayName ? { displayName: p.displayName } : {}) }));
const [entriesByOwner, connectorsByOwner, scopeGrants, scopeAsks] = await Promise.all([
- deps.keychain.listByOwners(members.map((m) => m.id)),
- deps.keychain.listConnectorsByOwners(members.map((m) => m.id)),
- deps.keychain.grantsForScope(scopeId),
- deps.keychain.listAsks({ requesterScopeId: scopeId }),
+ !external ? (deps.keychain?.listByOwners(members.map((m) => m.id)) ?? new Map()) : new Map(),
+ !external ? (deps.keychain?.listConnectorsByOwners(members.map((m) => m.id)) ?? new Map()) : new Map(),
+ !external ? (deps.keychain?.grantsForScope(scopeId) ?? []) : [],
+ !external ? (deps.keychain?.listAsks({ requesterScopeId: scopeId }) ?? []) : [],
]);
const keychainBlock = renderKeychainManifest({
scopeId,
@@ -2441,7 +2411,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
entriesByOwner,
connectorsByOwner,
scopeGrants,
- injected: [],
+ execution: credentialDescriptions,
scopeAsks,
});
if (keychainBlock) systemPrompt += `\n\n${keychainBlock}`;
diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.ts
index 7f96ec51a..69c2df296 100644
--- a/src/credentials/keychain.ts
+++ b/src/credentials/keychain.ts
@@ -2,7 +2,6 @@ import { createMemoryAdvisoryLock, type AdvisoryLock } from "../persistence/advi
import { orgId as configOrgId } from "../config.ts";
import { randomBytes } from "node:crypto";
import { scopeId as toScopeId, parseScopeId, type Destination, type ScopeId } from "../types.ts";
-import { CAPABILITY_CURL_AUTH } from "../api/contract.ts";
import type { DurableMap } from "../persistence/durable-map.ts";
import { encryptSecret, decryptSecret, type SecretKey } from "../connectors/connector-client-store.ts";
import { errMessage } from "../util/errors.ts";
@@ -443,8 +442,8 @@ function fingerprintOf(secret: string): string {
return hashId([secret]);
}
-export function credentialHandle(credentialId: string): string {
- return `kc_${credentialId.slice(0, 12)}`;
+export function credentialHandle(credential: Pick<KeychainCredential, "id" | "service">): string {
+ return `${encodeURIComponent(credential.service)}:${credential.id}`;
}
export interface FileCredentialSource {
@@ -508,7 +507,7 @@ function toMeta(rec: Omit<KeychainCredential, "secretEnc"> & { secretEnc?: strin
return {
...meta,
...((rec.kind === "env" || rec.kind === "file") && !isBackendCredential(rec)
- ? { credentialHandle: credentialHandle(rec.id) }
+ ? { credentialHandle: credentialHandle(rec) }
: {}),
};
}
@@ -830,9 +829,6 @@ export function createKeychain(deps: {
}
}
- const oauthExpired = (rec: KeychainCredentialMeta, t: number) =>
- rec.expiresAt !== undefined && t >= rec.expiresAt - oauthSkew;
-
async function connectorTokenForRecord(rec: KeychainCredential): Promise<string | null> {
const t = now();
const refreshable = rec.refresh?.refreshTokenEnc && deps.refreshConnector && rec.host ? rec.host : null;
@@ -845,25 +841,10 @@ export function createKeychain(deps: {
}
return pending;
}
- if (oauthExpired(rec, t) && !refreshable) return null;
+ if (oauthExpired(rec, t, oauthSkew) && !refreshable) return null;
return tryDecrypt(rec, (r) => decryptSecret(r.secretEnc, deps.key));
}
- function connectorMeta(rec: KeychainCredentialMeta, t: number): ConnectorMeta {
- const hasRefresh = !!rec.refresh?.refreshTokenEnc;
- const refreshFailed = typeof rec.refresh?.refreshFailedAt === "number";
- const tokenExpired = oauthExpired(rec, t);
- return {
- credentialId: rec.id,
- ownerId: rec.ownerId,
- host: rec.host ?? rec.service,
- ...(rec.refresh?.accountType ? { accountType: rec.refresh.accountType } : {}),
- ...(rec.expiresAt !== undefined ? { expiresAt: rec.expiresAt } : {}),
- connected: true,
- ...(tokenExpired && (!hasRefresh || refreshFailed) ? { needsReconnect: true } : {}),
- };
- }
-
async function saveCredential(input: SaveCredentialInput): Promise<KeychainCredentialMeta> {
const service = input.service.trim().toLowerCase();
if (!service) throw new KeychainError(400, "service required");
@@ -1419,7 +1400,7 @@ export function createKeychain(deps: {
const hasRefresh = !!rec.refresh?.refreshTokenEnc;
const refreshFailedAt = rec.refresh?.refreshFailedAt;
const refreshFailed = typeof refreshFailedAt === "number";
- const tokenExpired = oauthExpired(rec, now());
+ const tokenExpired = oauthExpired(rec, now(), oauthSkew);
return {
connected: true,
...(rec.expiresAt !== undefined ? { expiresAt: rec.expiresAt } : {}),
@@ -1461,7 +1442,7 @@ export function createKeychain(deps: {
await deps.creds.select({ omit: ["secretEnc"], where: byOwners(ownerIds) }),
ownerIds,
(c) => c.managed === "connector",
- (c) => connectorMeta(c, t),
+ (c) => connectorMeta(c, t, oauthSkew),
);
},
@@ -1606,21 +1587,17 @@ export interface KeychainManifestInput {
entriesByOwner: Map<string, KeychainCredentialMeta[]>;
connectorsByOwner?: Map<string, ConnectorMeta[]>;
scopeGrants: Array<{ grant: KeychainGrant; credential: KeychainCredentialMeta }>;
- injected: MaterializedEnvCred[];
+ execution?: Array<{
+ handle: string;
+ ownerId: string;
+ credentialId?: string;
+ description: string;
+ scope: "scoped" | "owner";
+ }>;
detectedByOwner?: Map<string, string[]>;
scopeAsks?: KeychainAsk[];
}
-const SAVE_HINT =
- "Saving logins (the owner's own DM only). Before running any CLI login, read the `interactive-login` skill and " +
- "follow it from the first step: it logs in under a temporary home and saves the result. Never log in against this " +
- "computer's $HOME; a token found there is not a saved login. Only keychain entries are durable and grantable. " +
- 'Save a token-style key right after it works: `curl -fsS -X POST "$AGENT_API_URL/v1/keychain/credentials" ' +
- CAPABILITY_CURL_AUTH +
- ' -H \'content-type: application/json\' -d \'{"service":"github","secret":"<token>","envKey":"GITHUB_TOKEN","accountLabel":"<who the service says they are>","expiresAt":<ms epoch, if the service reports one>}\'` — ' +
- "verify first (e.g. `gh api user`) and pass what the service reports as `accountLabel`. " +
- "Saved CLI logins are loaded only when requested through execute.credentials; updates made by the CLI are saved back after execution. If the provider can no longer refresh the session, re-run its interactive login.";
-
function expiryNote(c: KeychainCredentialMeta, now: number, own: boolean): string {
if (c.kind === "file" || typeof c.expiresAt !== "number") return "";
if (c.expiresAt < now) {
@@ -1631,44 +1608,43 @@ function expiryNote(c: KeychainCredentialMeta, now: number, own: boolean): strin
return `, expires at ${new Date(c.expiresAt).toISOString()}`;
}
-function credLine(
- owner: { id: string; displayName?: string },
- c: KeychainCredentialMeta,
- grantNote: string,
- now: number,
- own: boolean,
-): string {
- const who = owner.displayName ? `${owner.displayName} (${owner.id})` : owner.id;
+function credentialDescription(c: KeychainCredentialMeta, now: number, own: boolean): string {
+ if (c.managed === "connector") return connectorDescription(connectorMeta(c, now));
if (isBackendCredential(c))
- return `- ${who}: Composio backend access — use the composio skill and /v1/composio; this key cannot be loaded into a computer`;
- let slot = `files ${(c.targets ?? [c.target]).filter(Boolean).sort().join(", ")}`;
- if (c.kind === "env") {
- slot = c.fields
- ? c.fields
- .map((f) => `\`${f.envKey}\``)
+ return "Composio backend access — use the composio skill; cannot be loaded into a computer";
+ const slot =
+ c.kind === "env"
+ ? (c.fields?.map((f) => f.envKey) ?? [c.envKey])
+ .filter(Boolean)
.sort()
+ .map((key) => `\`${key}\``)
.join(" + ")
- : `\`${c.envKey}\``;
- }
- const label = c.accountLabel ? `, account ${c.accountLabel}` : "";
- return `- ${who}: ${c.service} (${slot}${label}${expiryNote(c, now, own)}) — credential id \`${c.id}\` — ${grantNote}`;
+ : `files ${(c.targets ?? [c.target]).filter(Boolean).sort().join(", ")}`;
+ return `${c.service} (${slot}${c.accountLabel ? `, account ${c.accountLabel}` : ""}${expiryNote(c, now, own)})`;
}
-function connectorLine(
- owner: { id: string; displayName?: string },
- cm: ConnectorMeta,
- grantNote: string,
- own: boolean,
-): string {
- const who = owner.displayName ? `${owner.displayName} (${owner.id})` : owner.id;
- const account = cm.accountType ? `, ${cm.accountType}` : "";
- let status = "";
- if (cm.needsReconnect) {
- status = own
- ? ", NEEDS RECONNECT — they must reconnect the app before it can be used"
- : ", NEEDS RECONNECT — owner must reconnect the app before a grant can be used";
- }
- return `- ${who}: connected app ${cm.host}${account}${status} — credential id \`${cm.credentialId}\` — ${grantNote}`;
+const oauthExpired = (rec: KeychainCredentialMeta, t: number, oauthSkew: number) =>
+ rec.expiresAt !== undefined && t >= rec.expiresAt - oauthSkew;
+
+function connectorMeta(rec: KeychainCredentialMeta, t: number, oauthSkew = 60_000): ConnectorMeta {
+ const hasRefresh = !!rec.refresh?.refreshTokenEnc;
+ const refreshFailed = typeof rec.refresh?.refreshFailedAt === "number";
+ const tokenExpired = oauthExpired(rec, t, oauthSkew);
+ return {
+ credentialId: rec.id,
+ ownerId: rec.ownerId,
+ host: rec.host ?? rec.service,
+ ...(rec.refresh?.accountType ? { accountType: rec.refresh.accountType } : {}),
+ ...(rec.expiresAt !== undefined ? { expiresAt: rec.expiresAt } : {}),
+ connected: true,
+ ...(tokenExpired && (!hasRefresh || refreshFailed) ? { needsReconnect: true } : {}),
+ };
+}
+
+function connectorDescription(cm: ConnectorMeta): string {
+ return `connected app ${cm.host}, account ${cm.accountType ?? "default"}${
+ cm.needsReconnect ? ", NEEDS RECONNECT — owner must reconnect the app before use" : ""
+ }${typeof cm.expiresAt === "number" ? `, token expires at ${new Date(cm.expiresAt).toISOString()}` : ""}`;
}
export const MAX_CREDENTIAL_FILES = 500;
@@ -1689,137 +1665,93 @@ function listed(c: Pick<KeychainCredential, "managed" | "kind">): boolean {
}
export function renderKeychainManifest(input: KeychainManifestInput, now: number = Date.now()): string {
- const lines: string[] = [];
- const byCred = new Map(input.scopeGrants.map((g) => [g.credential.id, g.grant]));
- const grantNoteFor = (id: string): string => {
- const g = byCred.get(id);
- if (!g) return "no grant for this conversation";
- const note =
- g.mode === "standing"
- ? `STANDING grant for this conversation (purpose: "${g.purpose}")`
- : `one-time grant \`${g.id}\` available (purpose: "${g.purpose}")`;
- return note;
+ const groups = new Map<string, Map<string, string>>();
+ const put = (ownerId: string, id: string, text: string): void => {
+ const owner = personKey(ownerId);
+ let rows = groups.get(owner);
+ if (!rows) groups.set(owner, (rows = new Map()));
+ rows.set(id, text);
};
const ownPersonal = input.scopeId === toScopeId("personal", input.actorId);
- 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 — execute.credentials needs no grant in their personal conversation, including background turns";
- const memberLines: string[] = [];
- let hasOwn = false;
- for (const member of input.members) {
- const own = (ownPersonal || openSpeaker) && samePerson(member.id, input.actorId);
- for (const c of input.entriesByOwner.get(member.id) ?? []) {
- const note = own ? OWN_NOTE : grantNoteFor(c.id);
- memberLines.push(credLine(member, c, note, now, own));
- hasOwn ||= own;
- }
- for (const cm of input.connectorsByOwner?.get(member.id) ?? []) {
- memberLines.push(connectorLine(member, cm, own ? OWN_NOTE : grantNoteFor(cm.credentialId), own));
- hasOwn ||= own;
- }
- }
-
- const detectedLines: string[] = [];
- for (const member of input.members) {
- const registered = new Set((input.entriesByOwner.get(member.id) ?? []).map((c) => c.service));
- const services = (input.detectedByOwner?.get(member.id) ?? []).filter((s) => !registered.has(s.toLowerCase()));
- if (!services.length) continue;
- const who = member.displayName ? `${member.displayName} (${member.id})` : member.id;
- detectedLines.push(
- `- ${who}: ${services.sort().join(", ")} — signed in on their own computer, not in the keychain`,
+ const openSpeaker = input.openSpeakerKeychain === true && input.conversationKind !== "dm";
+ const isOwn = (ownerId: string): boolean => (ownPersonal || openSpeaker) && samePerson(ownerId, input.actorId);
+ const grants = new Map(input.scopeGrants.map(({ grant, credential }) => [credential.id, grant]));
+ const execution = input.execution ?? [];
+ const access = (ownerId: string, id: string): string => {
+ if (grants.has(id)) return grantNote(id);
+ if (isOwn(ownerId))
+ return openSpeaker
+ ? "own; Open live turn only, isolated owner execution"
+ : "own; no grant needed (including background turns)";
+ return grantNote(id);
+ };
+ const grantNote = (id: string): string => {
+ const grant = grants.get(id);
+ if (!grant) return "no grant for this conversation";
+ return `${grant.mode === "standing" ? "STANDING" : "one-time"} grant \`${grant.id}\` (purpose: "${grant.purpose}")${
+ grant.expiresAt === undefined ? "" : `; expires at ${new Date(grant.expiresAt).toISOString()}`
+ }`;
+ };
+ const entries = new Map(input.scopeGrants.map(({ credential }) => [credential.id, credential]));
+ for (const member of input.members)
+ for (const credential of input.entriesByOwner.get(member.id) ?? []) entries.set(credential.id, credential);
+ for (const credential of entries.values()) {
+ const handles = execution
+ .filter((entry) => entry.credentialId === credential.id)
+ .map((entry) => `\`${entry.handle}\` (execute scope \`${entry.scope}\`)`)
+ .sort();
+ put(
+ credential.ownerId,
+ credential.id,
+ `- ${handles.join(", ") || `credential id \`${credential.id}\``} — ${credentialDescription(credential, now, isOwn(credential.ownerId))}; ${access(credential.ownerId, credential.id)}`,
);
}
-
- const 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 env credentials and connector tokens need no grant through execute.credentials, including background and scheduled turns. 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. " +
- ownershipGuidance +
- "A connector grant works exactly like any other: ask for it; the owner approves on the card.",
- );
- if (memberLines.length) {
- lines.push("", "In this conversation:", ...memberLines.sort());
- } else {
- lines.push("", "No keychain credentials registered yet for the people here.");
- }
-
- if (hasOwn && openSpeaker) {
- lines.push(
- "",
- `Use execute with scope:"owner" for commands needing the speaker's logins or connected apps. Request every credential, including saved CLI logins, explicitly using execute.credentials. Refreshed credential files are saved back after execution.`,
- "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(
- "",
- "Request every credential, including saved CLI logins, explicitly using execute.credentials. Refreshed credential files are saved back after execution.",
- );
+ for (const member of input.members) {
+ for (const connector of input.connectorsByOwner?.get(member.id) ?? []) {
+ const handles = execution
+ .filter((entry) => entry.credentialId === connector.credentialId)
+ .map((entry) => `\`${entry.handle}\` (execute scope \`${entry.scope}\`)`)
+ .sort();
+ put(
+ member.id,
+ connector.credentialId,
+ `- ${handles.join(", ") || `credential id \`${connector.credentialId}\``} — ${connectorDescription(connector)}; ${access(member.id, connector.credentialId)}`,
+ );
+ }
+ const registered = new Set((input.entriesByOwner.get(member.id) ?? []).map((c) => c.service.toLowerCase()));
+ for (const service of input.detectedByOwner?.get(member.id) ?? [])
+ if (!registered.has(service.toLowerCase()))
+ put(member.id, `detected:${service}`, `- ${service} — detected on their computer, NOT registered or grantable`);
}
-
- if (detectedLines.length) {
- lines.push(
- "",
- "Detected but NOT registered (not grantable yet):",
- ...detectedLines.sort(),
- "To make one usable here, its owner must first register it in their keychain from their own DM with you " +
- '(they can say "register my logins" there). A login living on someone\'s computer is not a grant — never claim access to it.',
- );
+ for (const entry of execution) {
+ if (entry.credentialId && groups.get(personKey(entry.ownerId))?.has(entry.credentialId)) continue;
+ put(entry.ownerId, entry.handle, `- \`${entry.handle}\` — ${entry.description}; execute scope \`${entry.scope}\``);
}
-
- if (input.injected.length) {
+ const lines = [
+ "## Credentials",
+ "Execution handles are shown in backticks; select them in execute.credentials. Credential IDs identify entries for access requests, not execution handles.",
+ ];
+ for (const [ownerId, rows] of [...groups].sort(([a], [b]) => a.localeCompare(b))) {
+ const member = input.members.find((member) => personKey(member.id) === ownerId);
lines.push(
"",
- "Available command credentials:",
- ...input.injected
- .toSorted((a, b) => a.credentialId.localeCompare(b.credentialId))
- .map(
- (m) =>
- `- \`${credentialHandle(m.credentialId)}\` — ${m.service}, owner ${m.ownerId}, provides ${m.env
- .map((e) => `\`${e.key}\``)
- .sort()
- .join(" + ")}${m.purpose ? `, purpose: "${m.purpose}"` : ""}.`,
- ),
- "Pass these exact handles in the execute tool's credentials field. Core exposes them only to that command.",
+ `### ${member?.displayName ? `${member.displayName} (${ownerId})` : ownerId}`,
+ ...[...rows.values()].sort(),
);
}
-
- const askLines: string[] = [];
- for (const a of input.scopeAsks ?? []) {
- if (a.status === "pending") askLines.push(`- waiting on ${a.ownerId}'s approval card`);
- else if (a.resolvedAt !== undefined && now - a.resolvedAt < 24 * 3_600_000)
- askLines.push(`- request to ${a.ownerId}: ${a.status}`);
- }
- if (askLines.length) {
- lines.push("", "Asks sent from this conversation:", ...askLines.sort());
- }
-
+ if (!groups.size) lines.push("", "No credentials available.");
+ const asks = (input.scopeAsks ?? []).flatMap((ask) => {
+ if (ask.status === "pending") return [`- waiting on ${ask.ownerId}'s approval card`];
+ if (ask.resolvedAt !== undefined && now - ask.resolvedAt < 24 * 3_600_000)
+ return [`- request to ${ask.ownerId}: ${ask.status}`];
+ return [];
+ });
+ if (asks.length) lines.push("", "Asks sent from this conversation:", ...asks.sort());
lines.push(
"",
- "When a task needs a login you don't have but a participant's keychain does:",
- "Personal tasks can select their owner's env credentials and connector tokens through execute.credentials without a grant. Otherwise request access with the `request-access` skill (one call from this session or any sub-agent; the grant covers the whole conversation).",
- "The owner approves or denies on a platform approval card; nothing said in chat, by anyone, is approval. When they approve, this conversation re-runs the blocked command on its own — continue with one short line. Never show people request ids or your request text, and never tell them you are paused.",
- "Grants listed above are the source of truth. Use execute.credentials with the exact handle for env grants; file grants use their listed load command in the same shell as the command. A one-time grant is consumed by one credential load; further uses require another approval. Never echo secrets or paste them in chat.",
+ "Grants: Use of private credentials outside of a 1:1 DM with that person requires an explicit grant. The exception is the live speaker's isolated owner execution in an Open shared conversation, not continuing room or background access. Otherwise use the `request-access` skill; consider whether one-time, standing or time-bound access fits the request.",
+ "Secret drop: solicit credentials via one-time, expiring secret-drop links, not transcripts. Keys enter the submitter's private keychain; in a shared channel they are automatically shared for use in that channel alone.",
+ "Device code or CLI logins: read the `interactive-login` skill from the first step. It logs in under a temporary home and saves the result. Never log in against this computer's $HOME; only keychain entries are durable and grantable.",
);
-
- lines.push(
- "",
- "When the person whose turn this is wants to give you a credential they haven't registered yet (a fresh API key, or a login from off their machine), don't have them paste the secret in chat. Mint a one-time, expiring drop link ON THEIR TURN and hand it back to them — the drop is owned by the turn's speaker, so it supplies that person's OWN key (it can't drop a key into a teammate's keychain; for a teammate's existing login, use the ask flow above):",
- ' `curl -fsS -X POST "$AGENT_API_URL/v1/keychain/drops" ' +
- CAPABILITY_CURL_AUTH +
- ' -H \'content-type: application/json\' -d \'{"service":"stripe","purpose":"<what the key is for>","envKey":"<ENV_VAR, for a token-style key>"}\'`',
- "They open it in a browser and paste the secret there; it lands encrypted in their own keychain, and (from a channel or group) is granted to this conversation, which resumes when they submit. Single-use and short-lived.",
- );
-
- if (inDm) lines.push("", SAVE_HINT);
return lines.join("\n");
}
diff --git a/test/connector-invariants.test.ts b/test/connector-invariants.test.ts
index d4265a043..11971a980 100644
--- a/test/connector-invariants.test.ts
+++ b/test/connector-invariants.test.ts
@@ -179,7 +179,7 @@ test("F1/F3 — a live DM receives only its requested connector; a channel recei
const absent = `!run test -z "$${key}" && echo absent`;
assert.equal((await built.app.turn({ ...turn("dm", absent), liveActor: true })).reply, "absent");
const command = `test "$${key}" = u1-gmail && echo authenticated`;
- const selected = `!execute ${JSON.stringify({ command, credentials: ["connector_gmail_googleapis_com_default"] })}`;
+ const selected = `!execute ${JSON.stringify({ command, credentials: ["connector:gmail.googleapis.com:default"] })}`;
assert.equal((await built.app.turn({ ...turn("dm", selected), liveActor: true })).reply, "authenticated");
assert.equal((await built.app.turn({ ...turn("dm", absent), liveActor: true })).reply, "absent");
assert.equal((await built.app.turn(turn("channel", absent))).reply, "absent");
@@ -218,7 +218,7 @@ for (const surface of ["cron", "loop"]) {
const key = envKey("gmail.googleapis.com");
const absent = `!run test -z "$${key}" && test -z "$OWNER_TOKEN" && echo absent`;
assert.equal((await built.app.turn(request(absent))).reply, "absent");
- const selected = `!execute ${JSON.stringify({ command: `test "$${key}" = u1-gmail && test "$OWNER_TOKEN" = owner-secret && echo authenticated`, credentials: ["connector_gmail_googleapis_com_default", credentialHandle(saved.id)] })}`;
+ const selected = `!execute ${JSON.stringify({ command: `test "$${key}" = u1-gmail && test "$OWNER_TOKEN" = owner-secret && echo authenticated`, credentials: ["connector:gmail.googleapis.com:default", credentialHandle(saved)] })}`;
assert.equal((await built.app.turn(request(selected))).reply, "authenticated");
assert.equal((await built.app.turn(request(absent))).reply, "absent");
await assert.rejects(
@@ -230,7 +230,7 @@ for (const surface of ["cron", "loop"]) {
);
await assert.rejects(
built.app.turn(
- request(`!execute ${JSON.stringify({ command: "true", credentials: [credentialHandle(other.id)] })}`),
+ request(`!execute ${JSON.stringify({ command: "true", credentials: [credentialHandle(other)] })}`),
),
/not available/,
);
@@ -280,11 +280,11 @@ for (const bulkInventory of [false, true])
};
const prompt = await built.app.turn({ ...turn("dm", "!sysprompt"), liveActor: true });
assert.deepEqual(accesses, []);
- assert.match(prompt.reply ?? "", /connector_gmail_googleapis_com_company/);
- if (expiredPersonal) assert.doesNotMatch(prompt.reply ?? "", /connector_gmail_googleapis_com_personal/);
- else assert.match(prompt.reply ?? "", /connector_gmail_googleapis_com_personal/);
+ assert.match(prompt.reply ?? "", /connector:gmail.googleapis.com:company/);
+ if (expiredPersonal) assert.doesNotMatch(prompt.reply ?? "", /connector:gmail.googleapis.com:personal/);
+ else assert.match(prompt.reply ?? "", /connector:gmail.googleapis.com:personal/);
for (const account of expiredPersonal ? ["company"] : ["personal", "company"]) {
- const text = `!execute ${JSON.stringify({ command: `test "$${envKey(host)}" = ${account}-token && echo selected`, credentials: [`connector_gmail_googleapis_com_${account}`] })}`;
+ const text = `!execute ${JSON.stringify({ command: `test "$${envKey(host)}" = ${account}-token && echo selected`, credentials: [`connector:gmail.googleapis.com:${account}`] })}`;
assert.equal((await built.app.turn({ ...turn("dm", text), liveActor: true })).reply, "selected");
}
assert.deepEqual(accesses, expiredPersonal ? ["company"] : ["personal", "company"]);
@@ -336,8 +336,8 @@ test("explicit default OAuth accounts remain discoverable through bulk metadata"
}),
);
const prompt = await built.app.turn({ ...turn("dm", "!sysprompt"), liveActor: true });
- assert.match(prompt.reply ?? "", /connector_gmail_googleapis_com_default/);
- const text = `!execute ${JSON.stringify({ command: `test "$${envKey(host)}" = explicit-default-token && echo selected`, credentials: ["connector_gmail_googleapis_com_default"] })}`;
+ assert.match(prompt.reply ?? "", /connector:gmail.googleapis.com:default/);
+ const text = `!execute ${JSON.stringify({ command: `test "$${envKey(host)}" = explicit-default-token && echo selected`, credentials: ["connector:gmail.googleapis.com:default"] })}`;
assert.equal((await built.app.turn({ ...turn("dm", text), liveActor: true })).reply, "selected");
});
@@ -367,10 +367,10 @@ for (const mixedOAuth of [false, true, "expired-default"] as const)
}),
);
const prompt = await built.app.turn({ ...turn("dm", "!sysprompt"), liveActor: true });
- assert.match(prompt.reply ?? "", /connector_gmail_googleapis_com_default.*configured operator fallback/);
- if (mixedOAuth === true) assert.match(prompt.reply ?? "", /connector_gmail_googleapis_com_personal/);
+ assert.match(prompt.reply ?? "", /connector:gmail.googleapis.com:default.*configured operator fallback/);
+ if (mixedOAuth === true) assert.match(prompt.reply ?? "", /connector:gmail.googleapis.com:personal/);
assert.equal(reads, 0);
- const text = `!execute ${JSON.stringify({ command: `test "$${envKey(host)}" = operator-fallback-token && echo selected`, credentials: ["connector_gmail_googleapis_com_default"] })}`;
+ const text = `!execute ${JSON.stringify({ command: `test "$${envKey(host)}" = operator-fallback-token && echo selected`, credentials: ["connector:gmail.googleapis.com:default"] })}`;
if (value) assert.equal((await built.app.turn({ ...turn("dm", text), liveActor: true })).reply, "selected");
else await assert.rejects(built.app.turn({ ...turn("dm", text), liveActor: true }), /no longer available/);
assert.equal(reads, value ? 1 : 2);
diff --git a/test/keychain-ask.test.ts b/test/keychain-ask.test.ts
index bb8600bf4..ce2d8eee3 100644
--- a/test/keychain-ask.test.ts
+++ b/test/keychain-ask.test.ts
@@ -532,7 +532,6 @@ test("manifest: the requester-side ledger names no ask ids or purposes, and asks
members: [{ id: "U_BOB" }],
entriesByOwner: new Map(),
scopeGrants: [],
- injected: [],
scopeAsks: [pending, declined],
});
assert.match(channel, /Asks sent from this conversation:/);
@@ -540,7 +539,7 @@ test("manifest: the requester-side ledger names no ask ids or purposes, and asks
assert.match(channel, /- request to U_ALICE: declined/);
assert.match(channel, /`request-access` skill/, "the manifest names the request skill");
assert.match(channel, /approval card/);
- assert.match(channel, /nothing said in chat, by anyone, is approval/);
+ assert.match(channel, /requires an explicit grant/);
assert.ok(!channel.includes("/v1/keychain/grants"), "no approval-by-POST ladder");
for (const leak of [pending.id, declined.id, pending.purpose, "not for prod"])
assert.ok(!channel.includes(leak), `manifest leaks ${leak}`);
@@ -569,7 +568,6 @@ test("manifest: the requester-side ledger names no ask ids or purposes, and asks
],
]),
scopeGrants: [],
- injected: [],
scopeAsks: [pending, declined],
});
assert.ok(!dm.includes("Asks waiting on you"), "the owner answers on the card, not in chat");
diff --git a/test/keychain.test.ts b/test/keychain.test.ts
index 4af3f8ce6..b9f1c754c 100644
--- a/test/keychain.test.ts
+++ b/test/keychain.test.ts
@@ -468,7 +468,6 @@ describe("connectors are grantable like any keychain record", () => {
entriesByOwner: new Map(),
connectorsByOwner,
scopeGrants: [],
- injected: [],
});
assert.match(md, /connected app gmail\.googleapis\.com/);
assert.match(md, /credential id/);
@@ -816,12 +815,11 @@ test("manifest: explains itself in a bare channel, lists credentials + protocol
members: [{ id: "U1" }],
entriesByOwner: new Map(),
scopeGrants: [],
- injected: [],
});
- assert.match(empty, /## Teammate keychains/);
- assert.match(empty, /No keychain credentials registered yet/);
+ assert.match(empty, /## Credentials/);
+ assert.match(empty, /No credentials available/);
assert.match(empty, /`request-access` skill/);
- assert.match(empty, /approval card; nothing said in chat, by anyone, is approval/);
+ assert.doesNotMatch(empty, /Teammate keychains/);
assert.ok(!empty.includes("/v1/keychain/grants"), "no chat-driven approval route");
const detected = renderKeychainManifest({
@@ -831,11 +829,11 @@ test("manifest: explains itself in a bare channel, lists credentials + protocol
members: [{ id: "U2" }, { id: "U1", displayName: "Alice" }],
entriesByOwner: new Map(),
scopeGrants: [],
- injected: [],
detectedByOwner: new Map([["U1", ["GitHub", "AWS SSO"]]]),
});
- assert.match(detected, /Detected but NOT registered/);
- assert.match(detected, /Alice \(U1\): AWS SSO, GitHub — signed in on their own computer/);
+ assert.match(detected, /NOT registered or grantable/);
+ assert.match(detected, /### Alice \(U1\)/);
+ assert.match(detected, /AWS SSO — detected/);
const k = kc();
const cred = await k.save(GH);
@@ -853,23 +851,22 @@ test("manifest: explains itself in a bare channel, lists credentials + protocol
members: [{ id: "U2" }, { id: "U1", displayName: "Alice" }],
entriesByOwner: new Map([["U1", await k.listByOwner("U1")]]),
scopeGrants: [{ grant, credential: cred }],
- injected: [
+ execution: [
{
credentialId: cred.id,
ownerId: "U1",
- service: "github",
- env: [{ key: "GITHUB_TOKEN", value: "x" }],
- grantId: grant.id,
- purpose: grant.purpose,
+ handle: credentialHandle(cred),
+ description: "github",
+ scope: "scoped",
},
],
});
- assert.match(block, /## Teammate keychains/);
- assert.match(block, /Alice \(U1\): github/);
- assert.match(block, new RegExp(`credential id \`${cred.id}\``));
+ assert.match(block, /## Credentials/);
+ assert.match(block, /### Alice \(U1\)/);
+ assert.match(block, new RegExp(`github:${cred.id}`));
assert.match(block, /STANDING grant .*gh for repo work here/);
- assert.match(block, /kc_[a-f0-9]{12}.*GITHUB_TOKEN/);
- assert.match(block, /execute tool.*credentials field/);
+ assert.match(block, /github:[a-f0-9]+.*GITHUB_TOKEN/);
+ assert.match(block, /select them in execute.credentials/);
assert.ok(!block.includes("/v1/keychain/grants"));
const login = renderKeychainManifest({
@@ -879,17 +876,13 @@ test("manifest: explains itself in a bare channel, lists credentials + protocol
members: [{ id: "U2" }],
entriesByOwner: new Map(),
scopeGrants: [],
- injected: [
+ execution: [
{
credentialId: "c1",
ownerId: "U1",
- service: "doordash",
- env: [
- { key: "DOORDASH_EMAIL", value: "x" },
- { key: "DOORDASH_PASSWORD", value: "y" },
- ],
- grantId: "g1",
- purpose: "billing",
+ handle: "doordash:c1",
+ description: "provides `DOORDASH_EMAIL` + `DOORDASH_PASSWORD`",
+ scope: "scoped",
},
],
});
@@ -913,12 +906,11 @@ test("manifest: own credentials need no grant but require explicit execution req
members: [{ id: "U1", displayName: "Alice" }],
entriesByOwner: new Map([["U1", await k.listByOwner("U1")]]),
scopeGrants: [],
- injected: [],
});
- assert.match(own, /file-login.*execute.credentials needs no grant/);
- assert.match(own, /their own — execute.credentials needs no grant/);
- assert.match(own, /including background and scheduled turns/);
- assert.match(own, /Request every credential, including saved CLI logins, explicitly using execute.credentials/);
+ assert.match(own, /file-login.*no grant needed/);
+ assert.match(own, /own; no grant needed/);
+ assert.match(own, /including background turns/);
+ assert.doesNotMatch(own, /Teammate keychains/);
assert.ok(!own.includes("no grant for this conversation"));
assert.match(
own,
@@ -934,7 +926,6 @@ test("manifest: own credentials need no grant but require explicit execution req
members: [{ id: "U2" }, { id: "U1", displayName: "Alice" }],
entriesByOwner: new Map([["U1", await k.listByOwner("U1")]]),
scopeGrants: [],
- injected: [],
});
assert.match(other, /no grant for this conversation/);
assert.match(other, /EXPIRED — ask the owner to re-auth before requesting a grant/);
@@ -947,7 +938,6 @@ test("manifest: own credentials need no grant but require explicit execution req
members: [{ id: "U1", displayName: "Alice" }],
entriesByOwner: new Map([["U1", await k.listByOwner("U1")]]),
scopeGrants: [],
- injected: [],
});
assert.ok(
!channel.includes("access is implied"),
@@ -1036,7 +1026,7 @@ describe("/v1/keychain routes (capability-authed)", () => {
assert.equal(res.status, 200);
const { credential } = (await res.json()) as any;
assert.equal(credential.ownerId, "U1");
- assert.equal(credential.credentialHandle, credentialHandle(credential.id));
+ assert.equal(credential.credentialHandle, credentialHandle(credential));
assert.ok(!JSON.stringify(credential).includes("ghp_u1"));
const mine = (await (await get("/v1/keychain/credentials", await capFor("U1"))).json()) as any;
@@ -1281,8 +1271,8 @@ test("turn e2e: prompt lists exact handles and keychain env credentials are neve
const audience = [{ externalId: "U_ASKER" }, { externalId: "U_OWNER", displayName: "Alice" }];
const sys = await built.app.turn(channelTurn("!sysprompt", "U_ASKER", audience));
assert.equal(sys.status, "ok");
- assert.match(sys.reply ?? "", /## Teammate keychains/);
- assert.match(sys.reply ?? "", /Alice \(U_OWNER\): github/);
+ assert.match(sys.reply ?? "", /## Credentials/);
+ assert.match(sys.reply ?? "", /### Alice \(U_OWNER\)/);
assert.match(sys.reply ?? "", /no grant for this conversation/);
assert.ok(!(sys.reply ?? "").includes("ghp_e2e"), "prompt never carries the secret");
await selectDefaultSandbox(built, "U_ASKER", "channel:C1");
@@ -1305,7 +1295,7 @@ test("turn e2e: prompt lists exact handles and keychain env credentials are neve
const sys2 = await built.app.turn(channelTurn("!sysprompt", "U_ASKER", audience));
assert.match(sys2.reply ?? "", /STANDING grant .*use my gh here for repo work/);
- assert.match(sys2.reply ?? "", new RegExp(`kc_${cred.id.slice(0, 12)}`));
+ assert.match(sys2.reply ?? "", new RegExp(`github:${cred.id}`));
await selectDefaultSandbox(built, "U_OWNER", "personal:U_OWNER");
mark = fakeSprites.execScripts().length;
@@ -1320,7 +1310,7 @@ test("turn e2e: prompt lists exact handles and keychain env credentials are neve
assert.ok(!execScriptsMention("ghp_e2e", mark), "unrequested secrets are never materialized");
const selected = await built.app.turn({
...dm,
- text: `!execute ${JSON.stringify({ command: 'test "$GITHUB_TOKEN" = ghp_e2e && echo selected', credentials: [credentialHandle(cred.id)] })}`,
+ text: `!execute ${JSON.stringify({ command: 'test "$GITHUB_TOKEN" = ghp_e2e && echo selected', credentials: [credentialHandle(cred)] })}`,
});
assert.equal(selected.reply, "selected");
assert.deepEqual(resolved, [cred.id]);
@@ -1441,7 +1431,6 @@ test("manifest timestamps stay stable until credentials and pending asks actuall
members: [{ id: "U1" }],
entriesByOwner: new Map([["U1", await k.listByOwner("U1")]]),
scopeGrants: [],
- injected: [],
scopeAsks: await k.listAsks({ requesterScopeId: "channel:C1" }),
},
now,
@@ -1513,14 +1502,12 @@ test("manifest inventories are canonical across discovery order without mutating
entriesByOwner: await k.listByOwners(["U2", "U1"]),
connectorsByOwner: await k.listConnectorsByOwners(["U2", "U1"]),
scopeGrants: [],
- injected: ["z", "a"].map((id) => ({
+ execution: ["z", "a"].map((id) => ({
credentialId: id,
ownerId: "U1",
- service: id,
- env: [
- { key: "Z", value: "z" },
- { key: "A", value: "a" },
- ],
+ handle: `${id}:${id}`,
+ description: id,
+ scope: "scoped",
})),
detectedByOwner: new Map([
["U1", ["zsh", "aws"]],
@@ -1532,8 +1519,7 @@ test("manifest inventories are canonical across discovery order without mutating
const first = renderKeychainManifest(input, 1000);
const reversed = structuredClone(input);
reversed.members.reverse();
- reversed.injected.reverse();
- for (const entry of reversed.injected) entry.env.reverse();
+ reversed.execution!.reverse();
for (const entries of reversed.entriesByOwner.values()) {
entries.reverse();
for (const entry of entries) {
@@ -1551,3 +1537,113 @@ test("manifest inventories are canonical across discovery order without mutating
reversed.connectorsByOwner!.get("U1")![0]!.needsReconnect = true;
assert.notEqual(renderKeychainManifest(reversed, 1000), first);
});
+
+test("manifest merges credential representations without conflating login identities or execution scopes", async () => {
+ const k = kc();
+ const ownerId = "[email protected]";
+ await k.setConnectorToken("gmail.googleapis.com", ownerId, { accessToken: "private-token", expiresAt: 5000 });
+ const connector = (await k.listConnectorsByOwners([ownerId])).get(ownerId)![0]!;
+ const credential = (await k.getCredential(connector.credentialId))!;
+ const grant = await k.createGrant({
+ ownerId,
+ credentialId: credential.id,
+ audienceScopeId: "channel:C1",
+ mode: "standing",
+ purpose: "mail",
+ });
+ const first = await k.save({
+ ownerId,
+ service: "aws",
+ envKey: "AWS_TOKEN",
+ secret: "first-secret",
+ accountLabel: "work",
+ expiresAt: 900,
+ });
+ const second = await k.save({
+ ownerId,
+ service: "aws",
+ envKey: "OTHER_AWS_TOKEN",
+ secret: "second-secret",
+ accountLabel: "personal",
+ expiresAt: 5000,
+ });
+ const input: Parameters<typeof renderKeychainManifest>[0] = {
+ scopeId: "channel:C1",
+ conversationKind: "channel",
+ openSpeakerKeychain: true,
+ actorId: "[email protected]",
+ members: [{ id: "[email protected]", displayName: "Alice" }],
+ entriesByOwner: new Map([["[email protected]", [first, second]]]),
+ connectorsByOwner: new Map([["[email protected]", [{ ...connector, needsReconnect: true }]]]),
+ scopeGrants: [{ grant, credential }],
+ execution: [
+ {
+ handle: credentialHandle(credential),
+ ownerId,
+ credentialId: credential.id,
+ scope: "scoped",
+ description: "mail grant",
+ },
+ {
+ handle: "connector:gmail.googleapis.com:default",
+ ownerId,
+ credentialId: credential.id,
+ scope: "owner",
+ description: "own mail",
+ },
+ ...[first, second].map((c) => ({
+ handle: credentialHandle(c),
+ ownerId,
+ credentialId: c.id,
+ scope: "owner" as const,
+ description: "aws",
+ })),
+ ],
+ };
+ const rendered = renderKeychainManifest(input, 1000);
+ assert.equal(rendered.split("### ").length - 1, 1);
+ assert.equal(rendered.split("connected app gmail.googleapis.com").length - 1, 1);
+ assert.ok(rendered.includes(`\`${credentialHandle(credential)}\` (execute scope \`scoped\`)`));
+ assert.ok(rendered.includes("`connector:gmail.googleapis.com:default` (execute scope `owner`)"));
+ assert.match(rendered, /NEEDS RECONNECT/);
+ assert.match(rendered, /token expires at/);
+ assert.match(rendered, /account work, EXPIRED/);
+ assert.match(rendered, /account personal, expires at/);
+ assert.notEqual(credentialHandle(first), credentialHandle(second));
+ for (const secret of ["private-token", "first-secret", "second-secret"]) assert.ok(!rendered.includes(secret));
+ input.execution!.reverse();
+ assert.equal(renderKeychainManifest(input, 1000), rendered);
+});
+
+test("granted connector keeps account and refresh semantics when owner is absent from roster", async () => {
+ const k = kc(() => 1000);
+ await k.setConnectorToken("gmail.googleapis.com", "U_OWNER", {
+ accessToken: "old-token",
+ refreshToken: "refresh-token",
+ expiresAt: 900,
+ accountType: "company",
+ });
+ const connector = (await k.listConnectorsByOwners(["U_OWNER"])).get("U_OWNER")![0]!;
+ const credential = (await k.getCredential(connector.credentialId))!;
+ const grant = await k.createGrant({
+ ownerId: "U_OWNER",
+ credentialId: credential.id,
+ audienceScopeId: "channel:C1",
+ mode: "standing",
+ purpose: "mail",
+ });
+ const rendered = renderKeychainManifest(
+ {
+ scopeId: "channel:C1",
+ conversationKind: "channel",
+ actorId: "U_ACTOR",
+ members: [{ id: "U_ACTOR" }],
+ entriesByOwner: new Map(),
+ scopeGrants: [{ grant, credential }],
+ },
+ 1000,
+ );
+ assert.match(rendered, /connected app gmail\.googleapis\.com, account company/);
+ assert.match(rendered, /STANDING grant/);
+ assert.doesNotMatch(rendered, /EXPIRED|NEEDS RECONNECT|refresh-token|old-token/);
+});
diff --git a/test/open-continuity-http.test.ts b/test/open-continuity-http.test.ts
index 97f5cbe3f..14bbea2b6 100644
--- a/test/open-continuity-http.test.ts
+++ b/test/open-continuity-http.test.ts
@@ -242,7 +242,7 @@ test("HTTP Open shared cron isolates synthetic owner credential and revokes reso
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' })}`,
+ task: `!proof ${JSON.stringify({ ownerAuth: true, credentials: [credentialHandle(credential)], 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");
@@ -282,7 +282,7 @@ for (const isPrivate of [false, true]) {
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' })}`,
+ task: `!proof ${JSON.stringify({ ownerAuth: true, credentials: [credentialHandle(credential)], 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;
@@ -332,7 +332,7 @@ test("HTTP legacy explicit private shared cron remains owner-authorized under is
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' })}`,
+ action: `!proof ${JSON.stringify({ ownerAuth: true, credentials: [credentialHandle(credential)], 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);
diff --git a/test/own-credential-automation.test.ts b/test/own-credential-automation.test.ts
index 8bad6bcdf..e5a08e8c8 100644
--- a/test/own-credential-automation.test.ts
+++ b/test/own-credential-automation.test.ts
@@ -31,7 +31,7 @@ async function setup() {
});
const read = `!execute ${JSON.stringify({
command: 'cat "$HOME/.aws/sso/cache/session.json"',
- credentials: [credentialHandle(credential.id)],
+ credentials: [credentialHandle(credential)],
})}`;
return { built, read };
}
diff --git a/test/save-login.test.ts b/test/save-login.test.ts
index f52975b6c..4189a6921 100644
--- a/test/save-login.test.ts
+++ b/test/save-login.test.ts
@@ -48,7 +48,7 @@ test("save-login uploads a private login home and re-saving keeps the entry and
return stdout;
};
- assert.match(await login("first"), /^saved aws \(2 files\) as kc_/);
+ assert.match(await login("first"), /^saved aws \(2 files\) as aws:/);
const [saved] = await keychain.listByOwner("U1");
const grant = await keychain.createGrant({
credentialId: saved!.id,
diff --git a/test/service-credential-route.test.ts b/test/service-credential-route.test.ts
index 333510e74..64748e7a2 100644
--- a/test/service-credential-route.test.ts
+++ b/test/service-credential-route.test.ts
@@ -1205,15 +1205,10 @@ test("the system prompt advertises an entitled credential (host/methods/paths) s
});
const res = await built.app.turn(dm("!sysprompt"));
const reply = res.reply ?? "";
- assert.match(reply, /Shared org credentials available to you/);
- assert.match(reply, /\/v1\/credentials\/broker/);
- assert.match(reply, /x-agent-capability: \$AGENT_CREDENTIAL_TOKEN/);
+ assert.match(reply, /### Organization/);
assert.match(reply, /x-firehose.*X firehose.*api\.x\.com.*GET.*\/2\/tweets\/search\//s);
- assert.match(reply, /clone\/fetch\/push using a shared org credential/);
- assert.match(reply, /configured org account, not automatically the requesting user's account/);
- assert.match(reply, /live personal OAuth connector does not switch this route's identity/);
- assert.match(reply, /Choose among credentials authorized for this conversation/);
- assert.match(reply, /does not identify the upstream username/);
+ assert.match(reply, /use-shared-credential/);
+ assert.doesNotMatch(reply, /curl -fsS -X POST.*credentials\/broker/);
});
test("the system prompt does NOT advertise a credential the session isn't entitled to", async () => {
@@ -1232,7 +1227,7 @@ test("the system prompt does NOT advertise a credential the session isn't entitl
grantedBy: "admin",
});
const res = await built.app.turn(dm("!sysprompt"));
- assert.doesNotMatch(res.reply ?? "", /Shared org credentials available to you/);
+ assert.doesNotMatch(res.reply ?? "", /### Organization/);
});
test("the published-apps switch defaults on, round-trips, survives a partial update, and rejects non-booleans", async () => {
@@ -1374,7 +1369,7 @@ test("credential prompt blocks are byte-identical across inventory and policy or
assert.equal(first.status, "ok");
assert.match(first.reply ?? "", /service_z-service/);
assert.match(first.reply ?? "", /service_a-service/);
- assert.match(first.reply ?? "", /Shared org credentials available to you/);
+ assert.match(first.reply ?? "", /### Organization/);
const list = built.serviceCreds.listServiceCredentials.bind(built.serviceCreds);
built.serviceCreds.listServiceCredentials = async (...args) =>
(await list(...args)).reverse().map((record) => ({
diff --git a/test/sharing-context-e2e.test.ts b/test/sharing-context-e2e.test.ts
index 4144966bf..3740e26a5 100644
--- a/test/sharing-context-e2e.test.ts
+++ b/test/sharing-context-e2e.test.ts
@@ -436,21 +436,21 @@ test("Open speaker keychain uses a disposable computer, follows the speaker, and
service: "custom-cli",
files: [{ path: ".custom-cli/auth", contentBase64: Buffer.from(`file_${id}`).toString("base64") }],
});
- handles.set(id, [credentialHandle(credential.id), credentialHandle(login.id)]);
+ handles.set(id, [credentialHandle(credential), credentialHandle(login)]);
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.match(prompt, /execute scope `owner`/);
+ assert.match(prompt, /### U1\n(?:(?!###)[\s\S])*npm[^\n]*own; Open live turn only/);
+ assert.match(prompt, /### U2\n(?:(?!###)[\s\S])*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"]))'`;
const selected = (id = "U1") =>
- `!execute ${JSON.stringify({ command: probe.replace('os.getenv("NPM_TOKEN","unset")', `str(os.getenv("NPM_TOKEN") == "npm_${id}")`).replace('os.getenv("VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM","unset")', `str(os.getenv("VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM") == "gmail_${id}")`), ownerAuth: true, credentials: [...handles.get(id)!, "connector_gmail_googleapis_com_default"] })}`;
+ `!execute ${JSON.stringify({ command: probe.replace('os.getenv("NPM_TOKEN","unset")', `str(os.getenv("NPM_TOKEN") == "npm_${id}")`).replace('os.getenv("VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM","unset")', `str(os.getenv("VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM") == "gmail_${id}")`), ownerAuth: true, credentials: [...handles.get(id)!, "connector:gmail.googleapis.com:default"] })}`;
assert.equal(await b.turn(selected(), true), "True|True|file_U1|unset|isolated");
assert.equal(await b.turn(selected("U2"), true, "U2"), "True|True|file_U2|unset|isolated");
for (const id of ["U1", "U2", "U1"]) {
@@ -460,8 +460,8 @@ test("Open speaker keychain uses a disposable computer, follows the speaker, and
);
}
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(ambientPrompt, /### U2\n(?:(?!###)[\s\S])*npm[^\n]*own; Open live turn only/);
+ assert.match(ambientPrompt, /### U1\n(?:(?!###)[\s\S])*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" },