🐛 Read code for the project being asked about, and say why a read failed

The code client sent its arguments without the tenant and project, so every call was
refused by the git service and the Copilot answered that it could not look. It now
binds both when it is created for one project, and a missing path or commit comes
back as a sentence the model can act on instead of a failed tool call.

The leak check also stopped treating a shared phrase as a leak: a twenty-character
run of the system prompt is evidence, "变成一次具体、能落地的改动" is the Copilot
describing itself to a customer.
This commit is contained in:
wishforge 2026-11-09 10:17:26 -08:00
parent 3f879c37d3
commit 13b7df84b0
5 changed files with 107 additions and 67 deletions

View File

@ -103,22 +103,25 @@ export class CodeWiki {
.trim()
.slice(0, 240 * 1024);
}
private async read(ref: string, path: string) {
private async read(code: CodeClient, ref: string, path: string) {
try {
const file = (await this.deps.code.blob({ ref, path: path as never })) as { content?: unknown };
const file = (await code.blob({ ref, path: path as never })) as { content?: unknown };
return typeof file.content === 'string' ? file.content : '';
} catch {
// A repository without a README, or a path the tool refuses, is simply no material.
return '';
}
}
private async overview(actor: Actor, projectId: string, ref: string) {
private async overview(actor: Actor, projectId: string, ref: string, code: CodeClient) {
const credential = await this.credential(actor);
if (!credential) return undefined;
const tree = (await this.deps.code.tree({ ref, depth: 2 }).catch(() => ({ entries: [] }))) as {
const tree = (await code.tree({ ref, depth: 2 }).catch(() => ({ entries: [] }))) as {
entries?: { path: string; size?: number }[];
};
const [readme, manifest] = await Promise.all([this.read(ref, 'README.md'), this.read(ref, 'package.json')]);
const [readme, manifest] = await Promise.all([
this.read(code, ref, 'README.md'),
this.read(code, ref, 'package.json'),
]);
const material = {
files: (tree.entries ?? []).slice(0, 200).map(entry => entry.path),
readme: readme.slice(0, 8000),
@ -134,10 +137,10 @@ export class CodeWiki {
JSON.stringify(material, null, 2),
);
}
private async constraints(actor: Actor, projectId: string, ref: string, gates: string) {
private async constraints(actor: Actor, projectId: string, ref: string, gates: string, code: CodeClient) {
const credential = await this.credential(actor);
if (!credential) return undefined;
const sources = await Promise.all(SOURCES.map(async path => [path, await this.read(ref, path)] as const));
const sources = await Promise.all(SOURCES.map(async path => [path, await this.read(code, ref, path)] as const));
const material = Object.fromEntries(
sources.filter(([, content]) => content).map(([path, content]) => [path, content.slice(0, 8000)]),
);
@ -152,10 +155,10 @@ export class CodeWiki {
JSON.stringify({ ...material, ...(gates ? { 'wiki/features/gates.md': gates.slice(0, 8000) } : {}) }, null, 2),
);
}
private async flows(actor: Actor, projectId: string, ref: string, wikiTitles: string[]) {
private async flows(actor: Actor, projectId: string, ref: string, wikiTitles: string[], code: CodeClient) {
const credential = await this.credential(actor);
if (!credential) return undefined;
const readme = await this.read(ref, 'README.md');
const readme = await this.read(code, ref, 'README.md');
return this.complete(
credential,
[
@ -167,8 +170,8 @@ export class CodeWiki {
);
}
/** Recent commits and recent runs: a table, rebuilt from the repository each time. */
private async changes(actor: Actor, projectId: string, ref: string) {
const log = (await this.deps.code.log({ ref, limit: 20 }).catch(() => ({ commits: [] }))) as {
private async changes(actor: Actor, projectId: string, ref: string, code: CodeClient) {
const log = (await code.log({ ref, limit: 20 }).catch(() => ({ commits: [] }))) as {
commits?: { sha: string; author: string; date: string; subject: string }[];
};
const runs = await this.deps.runs(actor, projectId).catch(() => []);
@ -224,6 +227,7 @@ export class CodeWiki {
throw new DomainError('INVALID_WIKI_KIND', 'Ask for overview, constraints, flows or changes', 400);
const snapshot = await this.deps.wiki.snapshot(actor, projectId, 'all');
const ref = snapshot.version;
const code = this.deps.code.forProject(actor.tenantId, projectId);
const gates = snapshot.files.find(file => file.path === 'wiki/features/gates.md')?.content ?? '';
const features = snapshot.files
.filter(file => file.path.startsWith('wiki/features/'))
@ -232,12 +236,12 @@ export class CodeWiki {
for (const kind of wanted) {
const content =
kind === 'overview'
? await this.overview(actor, projectId, ref)
? await this.overview(actor, projectId, ref, code)
: kind === 'constraints'
? await this.constraints(actor, projectId, ref, gates)
? await this.constraints(actor, projectId, ref, gates, code)
: kind === 'flows'
? await this.flows(actor, projectId, ref, features)
: await this.changes(actor, projectId, ref);
? await this.flows(actor, projectId, ref, features, code)
: await this.changes(actor, projectId, ref, code);
if (content) pages.push({ path: CODE_WIKI_PATHS[kind], content });
}
if (!pages.length)

View File

@ -220,12 +220,12 @@ async function requestRound(
});
if (!response.ok) {
const detail = await response.text().catch(() => '');
// The upstream body is not forwarded: it can name the gateway and its configuration.
throw new DomainError(
'COPILOT_UPSTREAM',
`The model gateway refused the request (${response.status})${detail ? '' : ''}`,
502,
// The upstream body is not forwarded to the browser, but its first line is what an operator
// needs to know why a gateway refused the request. It is scrubbed before it reaches a log.
console.warn(
`Copilot gateway refused ${response.status}: ${redactSecrets(detail).replace(/\s+/g, ' ').slice(0, 400)}`,
);
throw new DomainError('COPILOT_UPSTREAM', `The model gateway refused the request (${response.status})`, 502);
}
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.includes('text/event-stream') || !response.body) {
@ -401,11 +401,14 @@ export async function answerStreaming(input: StreamModelInput & { emit: StreamSi
if (result.audit) toolCalls.push(result.audit);
results.push({ type: 'tool_result', tool_use_id: block.id, content: redactSecrets(result.content) });
} catch (error) {
console.warn(
`Copilot tool ${block.name} failed: ${error instanceof Error ? error.message : 'unknown error'}`,
);
results.push({
type: 'tool_result',
tool_use_id: block.id,
is_error: true,
content: error instanceof DomainError ? '这个资料现在查不到。' : '这个资料现在查不到。',
content: '这个资料现在查不到。',
});
}
}

View File

@ -70,38 +70,62 @@ export interface CodeClient {
search(input: { ref: string; pattern: string; glob?: string }): Promise<unknown>;
log(input: { ref: string; since?: string; limit?: number }): Promise<unknown>;
show(input: { sha: string; path?: string }): Promise<unknown>;
/** Binds the tenant and project whose repository the calls read; every call needs one. */
forProject(tenantId: string, projectId: string): CodeClient;
}
/** The git service's read-only code views; the same admin channel the Wiki already uses. */
export function codeClient(env: NodeJS.ProcessEnv, fetcher: typeof fetch = fetch): CodeClient {
const base = env.WF_GIT_SERVICE_URL;
const token = env.WF_GIT_ADMIN_TOKEN;
const call = async (path: string, body: unknown, timeoutMs: number) => {
if (!base || !token) throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
const url = new URL(path, base);
if (url.protocol !== 'https:' && !plainHttpAllowed(env, url))
throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
let response: Response;
try {
response = await fetcher(url, {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
redirect: 'error',
signal: AbortSignal.timeout(timeoutMs),
});
} catch {
throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
}
if (!response.ok) throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
return response.json();
};
return {
tree: input => call('/code/tree', input, 3_000),
blob: input => call('/code/blob', input, 5_000),
search: input => call('/code/search', input, 10_000),
log: input => call('/code/log', input, 5_000),
show: input => call('/code/show', input, 8_000),
const make = (scope?: { tenantId: string; projectId: string }): CodeClient => {
const call = async (path: string, body: unknown, timeoutMs: number) => {
if (!base || !token) {
console.warn('code client: WF_GIT_SERVICE_URL or WF_GIT_ADMIN_TOKEN is not set');
throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
}
if (!scope) throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
const url = new URL(path, base);
if (url.protocol !== 'https:' && !plainHttpAllowed(env, url)) {
console.warn(`code client: ${url.protocol} is not allowed for ${url.hostname}`);
throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
}
let response: Response;
try {
response = await fetcher(url, {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ ...scope, ...(body as Record<string, unknown>) }),
redirect: 'error',
signal: AbortSignal.timeout(timeoutMs),
});
} catch (error) {
console.warn(
`code client: ${url.href} failed: ${error instanceof Error ? `${error.name}: ${error.message}` : 'unknown'}`,
);
throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
}
if (response.status === 400 || response.status === 404) {
// A path or commit that does not exist is an answer, not an outage: the model should be
// told it looked in the wrong place, not that the project is unreadable.
const payload = (await response.json().catch(() => ({}))) as { error?: string };
return { error: payload.error ?? 'NOT_FOUND' };
}
if (!response.ok) {
console.warn(`code client: ${url.pathname} answered ${response.status}`);
throw new DomainError('CODE_UNAVAILABLE', 'The project code cannot be read right now', 503);
}
return response.json();
};
return {
tree: input => call('/code/tree', input, 3_000),
blob: input => call('/code/blob', input, 5_000),
search: input => call('/code/search', input, 10_000),
log: input => call('/code/log', input, 5_000),
show: input => call('/code/show', input, 8_000),
forProject: (tenantId, projectId) => make({ tenantId, projectId }),
};
};
return make();
}
/** A namespace's recent log lines, already redacted by whoever serves them. */
export type LogReader = (input: { namespace: string; since: string }) => Promise<string>;
@ -142,6 +166,14 @@ const clamp = (value: unknown, fallback: number, min: number, max: number) => {
return Math.min(Math.max(number, min), max);
};
const text = (value: unknown, max: number) => (typeof value === 'string' ? value.slice(0, max) : '');
/** A tool result that is really "I could not find it" reads as a sentence, not as an error code. */
const missing = (value: unknown) => {
if (value && typeof value === 'object' && 'error' in value) {
const code = String((value as { error?: unknown }).error ?? 'NOT_FOUND');
return code === 'PAYLOAD_TOO_LARGE' ? '这个内容太大,没法一次读完。' : '这个提交或文件找不到。';
}
return undefined;
};
const result = (value: unknown) => {
const content = redactSecrets(typeof value === 'string' ? value : JSON.stringify(value, null, 2));
return content.length > RESULT_BYTES ? `${content.slice(0, RESULT_BYTES)}\n…(已截断)` : content;
@ -222,17 +254,13 @@ export async function runTool(context: ToolContext, name: string, input: Record<
if (name === 'read_file') {
const path = text(input.path, 512);
if (!path || deniedToolPath(path)) return { content: REFUSED_PATH, audit: audit({ path: '***' }) };
return {
content: result(
await context.code.blob({
ref: context.ref,
path,
from: clamp(input.from, 1, 1, 200_000),
to: clamp(input.to, 2000, 1, 200_000),
}),
),
audit: audit({ path }),
};
const file = await context.code.blob({
ref: context.ref,
path,
from: clamp(input.from, 1, 1, 200_000),
to: clamp(input.to, 2000, 1, 200_000),
});
return { content: missing(file) ?? result(file), audit: audit({ path }) };
}
if (name === 'search_code') {
const pattern = text(input.pattern, 200).trim();
@ -263,10 +291,8 @@ export async function runTool(context: ToolContext, name: string, input: Record<
const path = text(input.path, 512);
if (!/^[0-9a-f]{7,64}$/.test(sha)) return { content: '这个提交号看起来不对,请确认后重试。' };
if (path && deniedToolPath(path)) return { content: REFUSED_PATH, audit: audit({ sha }) };
return {
content: result(await context.code.show({ sha, path: path || undefined })),
audit: audit({ sha }),
};
const change = await context.code.show({ sha, path: path || undefined });
return { content: missing(change) ?? result(change), audit: audit({ sha }) };
}
if (name === 'get_run_summary') {
const runId = text(input.runId, 200).trim();

View File

@ -242,14 +242,16 @@ export const BLOCKED = '这类信息我不能提供,也不方便在这儿讨
*/
const SYSTEM_DIGEST = SYSTEM.replace(/\s+/g, '');
/**
* Any twelve characters of the prompt, not only a whole sentence: a model that truncates or
* reformats its instructions still must not hand them over piece by piece.
* A long run of the prompt, not a shared turn of phrase. The first sentence is deliberately
* excluded from the length test: "变成一次具体、能落地的改动" is how the Copilot describes itself
* to a customer, and repeating it is not a leak. Twenty characters is long enough that a genuine
* instruction cannot match by accident and short enough that a truncated copy still does.
*/
export function revealsSystemPrompt(value: string) {
const normalized = value.replace(/\s+/g, '');
if (normalized.includes('你是WishForge里的项目Copilot')) return true;
for (let index = 0; index + 12 <= SYSTEM_DIGEST.length; index += 4)
if (normalized.includes(SYSTEM_DIGEST.slice(index, index + 12))) return true;
for (let index = 0; index + 20 <= SYSTEM_DIGEST.length; index += 4)
if (normalized.includes(SYSTEM_DIGEST.slice(index, index + 20))) return true;
return false;
}
/** A credential, or the platform's own instructions, never reaches a customer. */
@ -633,7 +635,7 @@ export class Copilot {
actor,
ref: snapshot.version,
searchWiki: async query => retrieve(visible, query).files,
code: codeClient(this.env),
code: codeClient(this.env).forProject(actor.tenantId, projectId),
run: runId => this.control.run(actor, runId),
logs: logReader(this.env),
namespaces,

View File

@ -538,6 +538,11 @@ export async function createGitService(config: GitServiceConfig) {
return;
}
const code = error instanceof RuntimeError ? error.code : 'GIT_SERVICE_ERROR';
// A refused read is worth a line: the caller only sees "cannot read", the operator needs why.
if (request.url?.startsWith('/code/'))
console.warn(
`code ${request.url} refused: ${code} ${error instanceof Error ? error.message : ''}`.slice(0, 240),
);
const status =
code === 'UNAUTHORIZED'
? 401