Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(plugins): recheck live authorization after final host lookup

Dash4d5b8e3098f0
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 780217894b,7495ca2ea2..f2b812af2c
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -11849,14 -11818,15 +11851,15 @@@ export function registerMakerIpc(maker
if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
},
});
- if (resolvedWorkingDir !== undefined && directory !== await realpathWorkingDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');
+ const directory = await resolveAuthorizedDirectory(params.workingDir ?? task.workingDir ?? '');
+ if (resolvedWorkingDir !== undefined && directory !== await resolveAuthorizedDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');
// get() waits behind plan registration in the existing receipt queue.
const currentReceipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
- if (!currentReceipt) throw new PluginTaskError('TASK_NOT_FOUND', 'Task not found');
- const data = JSON.parse(currentReceipt.payload);
+ if (!currentReceipt || currentReceipt.operation !== 'create' || epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Task ownership changed');
+ const data = readPluginTaskPlanReceipt(currentReceipt.payload);
const item = data.teamPlan?.items.find((x: {label:string})=>x.label===params.label);
const plannedDirectory = item && resolvedRoute
- ? await realpathWorkingDirectory(item.workingDir) : undefined;
+ ? await resolveAuthorizedDirectory(item.workingDir) : undefined;
const currentTask = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
if (epoch !== getCurrentDbClientSnapshot() || currentTask.revision !== task.revision) throw new PluginTaskError('STALE_REVISION','Task changed during directory validation');
// Last admission check also covers no-plan plugin tasks and revocation
diff --cc packages/maker-core/src/agents/claude-code/index.ts
index 03cea9c7b7,2e55fd043a..d7a7423bba
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@@ -2733,32 -2729,27 +2733,31 @@@ export class ClaudeCodeAgent extends Ba
writableRoots,
platform,
};
- const key = JSON.stringify(request);
- const cached = autoReviewDecisionCache.get(key);
- const pending = cached ?? resolveAutoReviewDecision(
- request,
- this.deps.reviewAutoPermissionAction,
- );
- if (!cached) autoReviewDecisionCache.set(key, pending);
- return pending.then<AutoReviewDecision>((decision) => (
- autoReviewDecisionCache.get(key) !== pending
- ? { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' }
- : directoryGeneration === autoReviewDirectoryGeneration
- ? decision
- : {
- verdict: 'block',
- reason: 'Directory permissions changed; retry with the current scope.',
- }
- )).then((decision) => {
- if (autoReviewDecisionCache.get(key) === pending && directoryGeneration === autoReviewDirectoryGeneration) {
- autoReviewActionContext.record(action, decision);
++ let key: string | undefined;
++ let pending: Promise<AutoReviewDecision> | undefined;
+ return withAutoReviewContext(request, this.deps.reviewAutoPermissionAction, (prepared) => {
+ if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)) {
+ return Promise.resolve({ verdict: 'block', reason: 'User instructions changed; retry against the current request.' });
+ }
- const key = JSON.stringify(prepared);
++ key = JSON.stringify(prepared);
+ const cached = autoReviewDecisionCache.get(key);
- const pending = cached ?? resolveAutoReviewDecision(
++ pending = cached ?? resolveAutoReviewDecision(
+ prepared,
+ this.deps.reviewAutoPermissionAction,
+ );
+ if (!cached) autoReviewDecisionCache.set(key, pending);
- return pending.then<AutoReviewDecision>((decision) => (
- autoReviewDecisionCache.get(key) !== pending
- ? { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' }
- : directoryGeneration === autoReviewDirectoryGeneration
- ? decision
- : {
- verdict: 'block',
- reason: 'Directory permissions changed; retry with the current scope.',
- }
- )).then((decision) => {
- if (autoReviewDecisionCache.get(key) === pending && directoryGeneration === autoReviewDirectoryGeneration) {
- autoReviewActionContext.record(action, decision);
- }
- return decision;
- });
++ return pending;
++ }, (decision) => {
++ if (!pending || !key) return decision;
++ if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)
++ || autoReviewDecisionCache.get(key) !== pending) {
++ return { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' };
++ }
++ if (directoryGeneration !== autoReviewDirectoryGeneration) {
++ return { verdict: 'block', reason: 'Directory permissions changed; retry with the current scope.' };
+ }
++ autoReviewActionContext.record(action, decision);
+ return decision;
});
};
// All models share the same detector, with independent per-sidechain history.
diff --cc packages/maker-core/src/agents/codex/index.ts
index a84ab2615b,efab6ea9a8..09d39b27e4
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@@ -5565,32 -5562,27 +5565,31 @@@ assertRouteCurrent()
),
platform: sessionReviewPlatform,
};
- const key = JSON.stringify(request);
- const cached = autoReviewDecisionCache.get(key);
- const pending = cached ?? resolveAutoReviewDecision(
- request,
- this.deps.reviewAutoPermissionAction,
- );
- if (!cached) autoReviewDecisionCache.set(key, pending);
- return pending.then<AutoReviewDecision>((decision) => (
- autoReviewDecisionCache.get(key) !== pending
- ? { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' }
- : directoryGeneration === autoReviewDirectoryGeneration
- ? decision
- : {
- verdict: 'block',
- reason: 'Directory permissions changed; retry with the current scope.',
- }
- )).then((decision) => {
- if (autoReviewDecisionCache.get(key) === pending && directoryGeneration === autoReviewDirectoryGeneration) {
- autoReviewActionContext.record(action, decision);
++ let key: string | undefined;
++ let pending: Promise<AutoReviewDecision> | undefined;
+ return withAutoReviewContext(request, this.deps.reviewAutoPermissionAction, (prepared) => {
+ if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)) {
+ return Promise.resolve({ verdict: 'block', reason: 'User instructions changed; retry against the current request.' });
+ }
- const key = JSON.stringify(prepared);
++ key = JSON.stringify(prepared);
+ const cached = autoReviewDecisionCache.get(key);
- const pending = cached ?? resolveAutoReviewDecision(
++ pending = cached ?? resolveAutoReviewDecision(
+ prepared,
+ this.deps.reviewAutoPermissionAction,
+ );
+ if (!cached) autoReviewDecisionCache.set(key, pending);
- return pending.then<AutoReviewDecision>((decision) => (
- autoReviewDecisionCache.get(key) !== pending
- ? { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' }
- : directoryGeneration === autoReviewDirectoryGeneration
- ? decision
- : {
- verdict: 'block',
- reason: 'Directory permissions changed; retry with the current scope.',
- }
- )).then((decision) => {
- if (autoReviewDecisionCache.get(key) === pending && directoryGeneration === autoReviewDirectoryGeneration) {
- autoReviewActionContext.record(action, decision);
- }
- return decision;
- });
++ return pending;
++ }, (decision) => {
++ if (!pending || !key) return decision;
++ if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)
++ || autoReviewDecisionCache.get(key) !== pending) {
++ return { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' };
++ }
++ if (directoryGeneration !== autoReviewDirectoryGeneration) {
++ return { verdict: 'block', reason: 'Directory permissions changed; retry with the current scope.' };
+ }
++ autoReviewActionContext.record(action, decision);
+ return decision;
});
};
const readonlyReferencesConfig = (): Record<string, unknown> => ({
diff --cc packages/maker-core/src/agents/pi/index.ts
index 1f8226da21,38327613af..3d387296ba
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@@ -3959,32 -3956,27 +3959,30 @@@ export class PiAgent extends BaseAgent
writableRoots: [opts.workingDir, ...mutableWritableDirs],
platform: opts.remoteHostId ? ('linux' as const) : process.platform,
};
- const cacheKey = JSON.stringify(request);
- let pending = autoReviewDecisionCache.get(cacheKey);
- if (!pending) {
- pending = resolveAutoReviewDecision(request, this.deps.reviewAutoPermissionAction);
- autoReviewDecisionCache.set(cacheKey, pending);
- }
- return pending.then<AutoReviewDecision>((decision) => (
- autoReviewDecisionCache.get(cacheKey) !== pending
- ? { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' }
- : directoryGeneration === autoReviewDirectoryGeneration
- && !directoryPermissionsPendingPersistence()
- ? decision
- : {
- verdict: 'block',
- reason: 'Directory permissions changed; retry with the current scope.',
- }
- )).then((decision) => {
- if (autoReviewDecisionCache.get(cacheKey) === pending && directoryGeneration === autoReviewDirectoryGeneration) {
- autoReviewActionContext.record(action, decision);
++ let cacheKey: string | undefined;
++ let pending: Promise<AutoReviewDecision> | undefined;
+ return withAutoReviewContext(request, this.deps.reviewAutoPermissionAction, (prepared) => {
+ if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)) {
+ return Promise.resolve({ verdict: 'block', reason: 'User instructions changed; retry against the current request.' });
+ }
- const cacheKey = JSON.stringify(prepared);
- let pending = autoReviewDecisionCache.get(cacheKey);
++ cacheKey = JSON.stringify(prepared);
++ pending = autoReviewDecisionCache.get(cacheKey);
+ if (!pending) {
+ pending = resolveAutoReviewDecision(prepared, this.deps.reviewAutoPermissionAction);
+ autoReviewDecisionCache.set(cacheKey, pending);
+ }
- return pending.then<AutoReviewDecision>((decision) => (
- autoReviewDecisionCache.get(cacheKey) !== pending
- ? { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' }
- : directoryGeneration === autoReviewDirectoryGeneration
- && !directoryPermissionsPendingPersistence()
- ? decision
- : {
- verdict: 'block',
- reason: 'Directory permissions changed; retry with the current scope.',
- }
- )).then((decision) => {
- if (autoReviewDecisionCache.get(cacheKey) === pending && directoryGeneration === autoReviewDirectoryGeneration) {
- autoReviewActionContext.record(action, decision);
- }
- return decision;
- });
++ return pending;
++ }, (decision) => {
++ if (!pending || !cacheKey) return decision;
++ if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)
++ || autoReviewDecisionCache.get(cacheKey) !== pending) {
++ return { verdict: 'block', reason: 'User instructions changed; retry against the latest authorization.' };
++ }
++ if (directoryGeneration !== autoReviewDirectoryGeneration || directoryPermissionsPendingPersistence()) {
++ return { verdict: 'block', reason: 'Directory permissions changed; retry with the current scope.' };
+ }
++ autoReviewActionContext.record(action, decision);
+ return decision;
});
};
let closed = false;
diff --cc packages/maker-core/src/agents/shared/auto-review-decision.ts
index 6d2b25b2d7,8b65aa11ec..81f9c4aa38
--- a/packages/maker-core/src/agents/shared/auto-review-decision.ts
+++ b/packages/maker-core/src/agents/shared/auto-review-decision.ts
@@@ -267,32 -255,9 +267,34 @@@ export interface AutoReviewRequest
platform: NodeJS.Platform;
}
-export type AutoReviewDelegate = (
+export type AutoReviewDelegate = ((request: AutoReviewRequest) => Promise<AutoReviewDecision | null>) & {
+ /** Re-resolve live Host authority before cache lookup and after any awaited decision. */
+ prepareRequest?: (request: AutoReviewRequest) => Promise<AutoReviewRequest>;
+};
+
+export async function withAutoReviewContext(
request: AutoReviewRequest,
-) => Promise<AutoReviewDecision | null>;
+ delegate: AutoReviewDelegate | undefined,
+ evaluate: (prepared: AutoReviewRequest) => Promise<AutoReviewDecision>,
++ finalize: (decision: AutoReviewDecision) => AutoReviewDecision = decision => decision,
+): Promise<AutoReviewDecision> {
+ try {
+ const prepared = delegate?.prepareRequest ? await delegate.prepareRequest(request) : request;
+ if (prepared.authorizationError) return { verdict: 'block', reason: prepared.authorizationError };
+ const fingerprint = JSON.stringify(prepared);
+ const decision = await evaluate(prepared);
+ if (delegate?.prepareRequest) {
+ const current = await delegate.prepareRequest(request);
+ if (current.authorizationError || JSON.stringify(current) !== fingerprint) {
+ return { verdict: 'block', reason: 'Delegated authorization changed; retry against the current scope.' };
+ }
+ }
- return decision;
++ // No await after the live runtime fence: Host lookup may outlive accepted input.
++ return finalize(decision);
+ } catch {
+ return { verdict: 'ask', unavailable: true, reason: 'Host could not verify the current authorization; this action needs your confirmation.' };
+ }
+}
/** Preserve the actual tool identity and arguments across progressive/Host approval entrypoints. */
export function toolAutoReviewAction(
diff --cc packages/maker-core/src/agents/shared/auto-review-final-freshness.test.ts
index 0000000000,0000000000..1f51b40760
new file mode 100644
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/auto-review-final-freshness.test.ts
@@@ -1,0 -1,0 +1,43 @@@
++import { readFileSync } from 'node:fs';
++import { describe, expect, it, vi } from 'vitest';
++import ts from 'typescript';
++import { withAutoReviewContext, type AutoReviewDelegate } from './auto-review-decision.js';
++
++// Exercise each production review closure while the final Host read is suspended.
++for (const engine of ['claude-code', 'codex', 'pi']) {
++ const source = readFileSync(new URL(`../${engine}/index.ts`, import.meta.url), 'utf8');
++ const start = source.indexOf(' const reviewAutoAction =');
++ const closure = source.slice(start, source.indexOf('\n };', start) + 7);
++ const script = ts.transpileModule(`
++ let currentAutoReviewIntent = 'Run tests';
++ let currentAutoReviewAuthority = undefined;
++ let autoReviewDirectoryGeneration = 0;
++ let persistencePending = false;
++ const directoryPermissionsPendingPersistence = () => persistencePending;
++ ${closure}
++ return {run:()=>reviewAutoAction({kind:'exec',command:'npm test'},['/work'],['/work'],'linux'),
++ invalidate:(kind)=>{if(kind==='intent') currentAutoReviewIntent='Do not publish';
++ if(kind==='cache') autoReviewDecisionCache.clear();
++ if(kind==='directory') autoReviewDirectoryGeneration++;
++ if(kind==='persistence') persistencePending=true;}};
++ `, {compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
++ describe(`${engine} final Auto runtime fence`,()=>{
++ it.each(['unchanged','intent','cache','directory',...(engine==='pi'?['persistence']:[])])('checks %s after the last Host await',async kind=>{
++ let calls=0, release!:()=>void, entered!:()=>void;
++ const waiting=new Promise<void>(resolve=>{entered=resolve;});
++ const barrier=new Promise<void>(resolve=>{release=resolve;});
++ const delegate:AutoReviewDelegate=async()=>({verdict:'allow'});
++ delegate.prepareRequest=async request=>{if(++calls===2){entered();await barrier;}return request;};
++ const record=vi.fn();
++ const deps={withAutoReviewContext,opts:{sessionId:'s',workingDir:'/work'},mutableProviderId:undefined,mutableModel:'m',mutableCatalogModel:'m',
++ autoReviewActionContext:{precedingBlockedActions:[],record},autoReviewDecisionCache:new Map(),
++ resolveAutoReviewDecision:vi.fn(async()=>({verdict:'allow'})),runtimeWorkspaceRoots:()=>['/work'],runtimeWritableRoots:()=>['/work'],
++ sessionReviewPlatform:'linux',mutableExtraDirs:[],mutableWritableDirs:[]};
++ const runtime=new Function(...Object.keys(deps),script).call({deps:{reviewAutoPermissionAction:delegate}},...Object.values(deps));
++ const result=runtime.run();await waiting;
++ expect(record).not.toHaveBeenCalled();runtime.invalidate(kind);release();
++ expect((await result).verdict).toBe(kind==='unchanged'?'allow':'block');
++ expect(record).toHaveBeenCalledTimes(kind==='unchanged'?1:0);
++ });
++ });
++}