Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/code/src/linked-worktrees.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,59 @@ test('lane file tools are confined to the worktree and report the public workspa
);
});

test('lane writes create missing parents inside the worktree and report missing files', async (t) => {
const { parent, root } = await checkout();
t.after(() => rm(parent, { recursive: true, force: true }));
const tools = await laneTools(root);
const lane = join(root, '.worktrees', 'task-a');

await tools.execute({
protocolVersion: 1,
operation: 'write_file',
workspaceId: 'repo',
worktree: 'task-a',
path: 'packages/new-package/package.json',
content: '{}\n',
});
assert.equal(await readFile(join(lane, 'packages', 'new-package', 'package.json'), 'utf8'), '{}\n');
await assert.rejects(stat(join(root, 'packages')));

await rejects(
tools.execute({
protocolVersion: 1,
operation: 'read_file',
workspaceId: 'repo',
worktree: 'task-a',
path: '.checks/tests.log',
}),
'NOT_FOUND',
);

await symlink(root, join(lane, 'checkout-link'));
await rejects(
tools.execute({
protocolVersion: 1,
operation: 'write_file',
workspaceId: 'repo',
worktree: 'task-a',
path: 'checkout-link/escaped/notes.txt',
content: 'blocked',
}),
'INVALID_PATH',
);
await rejects(
tools.execute({
protocolVersion: 1,
operation: 'read_file',
workspaceId: 'repo',
worktree: 'task-a',
path: 'checkout-link/missing.txt',
}),
'INVALID_PATH',
);
await assert.rejects(stat(join(root, 'escaped')));
});

test('lane commands register a confined root once, whatever siblings come and go', async (t) => {
const { parent, root } = await checkout();
t.after(() => rm(parent, { recursive: true, force: true }));
Expand Down
13 changes: 13 additions & 0 deletions packages/code/src/protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import {
isSupportedBridgeArtifactName,
isValidBridgeWorkerCapabilities,
isValidBridgeWorkerId,
isWorkspaceToolErrorCode,
isWorkspaceToolRequest,
isWorkspaceToolResult,
WORKSPACE_TOOL_ERROR_CODE_FALLBACKS,
workspaceIsolationKey,
workspaceIsolationKeysConflict,
workspaceIsolationParent,
Expand All @@ -19,6 +21,17 @@ import type {
WorkspacePreviewEditRequest,
} from './protocol.js';

test('every added workspace error code falls back to a legacy code', () => {
assert.equal(isWorkspaceToolErrorCode('NOT_FOUND'), true);
assert.equal(isWorkspaceToolErrorCode('MISSING'), false);
for (const [code, legacy] of Object.entries(WORKSPACE_TOOL_ERROR_CODE_FALLBACKS)) {
assert.equal(isWorkspaceToolErrorCode(code), true);
assert.equal(isWorkspaceToolErrorCode(legacy), true);
assert.equal(legacy in WORKSPACE_TOOL_ERROR_CODE_FALLBACKS, false);
}
assert.equal(WORKSPACE_TOOL_ERROR_CODE_FALLBACKS.NOT_FOUND, 'INVALID_PATH');
});

test('accepts gateway directory markers as artifacts', () => {
assert.equal(isSupportedBridgeArtifactName('.dirkeep'), true);
assert.equal(isSupportedBridgeArtifactName('nested/.dirkeep'), true);
Expand Down
13 changes: 13 additions & 0 deletions packages/code/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,8 @@ export interface BridgeWorkerRegistrationResponse {
supportedWorkspaceInstanceTypes?: ['git_worktree'];
/** Scheduling scopes this Code API can admit as independent lanes. */
supportedWorkspaceScopes?: ['git_linked_worktree'];
/** Added workspace tool error codes this Code API accepts in settlements. */
supportedWorkspaceToolErrorCodes?: WorkspaceToolErrorCode[];
}

/** Administrator-visible liveness for a configured worker. Credentials,
Expand Down Expand Up @@ -976,6 +978,7 @@ export interface BridgeRejectedSettlement {

export type WorkspaceToolErrorCode =
| 'INVALID_PATH'
| 'NOT_FOUND'
| 'INVALID_REQUEST'
| 'READ_LIMIT_EXCEEDED'
| 'WRITE_LIMIT_EXCEEDED'
Expand All @@ -994,6 +997,7 @@ export type WorkspaceToolErrorCode =

const WORKSPACE_TOOL_ERROR_CODES = new Set<WorkspaceToolErrorCode>([
'INVALID_PATH',
'NOT_FOUND',
'INVALID_REQUEST',
'READ_LIMIT_EXCEEDED',
'WRITE_LIMIT_EXCEEDED',
Expand All @@ -1011,6 +1015,15 @@ const WORKSPACE_TOOL_ERROR_CODES = new Set<WorkspaceToolErrorCode>([
'COMMAND_DISABLED',
]);

/**
* Codes added after the original settlement contract, each with the legacy code
* an older Code API accepts in its place. A worker reports an added code only
* after registration advertises it, and falls back if a settlement is refused.
*/
export const WORKSPACE_TOOL_ERROR_CODE_FALLBACKS: Readonly<
Partial<Record<WorkspaceToolErrorCode, WorkspaceToolErrorCode>>
> = { NOT_FOUND: 'INVALID_PATH' };

export function isWorkspaceToolErrorCode(
value: unknown,
): value is WorkspaceToolErrorCode {
Expand Down
12 changes: 7 additions & 5 deletions packages/code/src/root-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ export class WorkspaceRootAccess {
}
}

entry(path: string, operation: 'mkdir' | 'symlink' | 'readlink', target?: string): string | void {
entry(path: string, operation: 'mkdir' | 'symlink' | 'readlink', target?: string, mode = 0o700): string | void {
const parent = this.parent(path);
try {
if (operation === 'readlink') {
Expand All @@ -361,7 +361,7 @@ export class WorkspaceRootAccess {
return buffer.subarray(0, length).toString();
}
const result = operation === 'mkdir'
? mkdirAt!(parent.fd, parent.name, 0o700)
? mkdirAt!(parent.fd, parent.name, mode)
: symlinkAt!(target!, parent.fd, parent.name);
if (result !== 0) throw nativeError();
} finally { closeSync(parent.fd); }
Expand All @@ -378,6 +378,8 @@ export class WorkspaceRootAccess {
}

const context = new AsyncLocalStorage<WorkspaceRootAccess>();
/** Whether filesystem adapters in this call are anchored to a held root descriptor. */
export const holdsWorkspaceRoot = (): boolean => context.getStore() != null;
export async function withWorkspaceRoot<T>(
root: string,
identity: WorkspaceRootIdentity | undefined,
Expand Down Expand Up @@ -504,10 +506,10 @@ export const readdir = async (path: string, maxEntries = 200_000): Promise<strin
};
export const readlink = async (path: string): Promise<string> =>
context.getStore()?.entry(path, 'readlink') as string ?? fs.readlink(path);
export const mkdir = async (path: string): Promise<void> => {
export const mkdir = async (path: string, mode = 0o700): Promise<void> => {
const access = context.getStore();
if (access) access.entry(path, 'mkdir');
else await fs.mkdir(path, { mode: 0o700 });
if (access) access.entry(path, 'mkdir', undefined, mode);
else await fs.mkdir(path, { mode });
};
export const symlink = async (target: string, path: string): Promise<void> => {
const access = context.getStore();
Expand Down
31 changes: 30 additions & 1 deletion packages/code/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
workspaceIsolationKey,
workspaceIsolationKeysConflict,
workspaceIsolationParent,
WORKSPACE_TOOL_ERROR_CODE_FALLBACKS,
} from './protocol.js';
import { EndpointRuntimeSupervisor } from './runtime.js';
import { signBridgeRequest } from './identity.js';
Expand All @@ -28,6 +29,7 @@ import type {
BridgeWorkspaceToolOperation,
BridgeWorkspaceProgrammaticRequest,
RepositoryInstructionDescriptor,
WorkspaceToolErrorCode,
} from './protocol.js';
import type { RuntimeLease, RuntimeSupervisor } from './runtime.js';
import type { WorkspaceToolExecutor } from './workspace.js';
Expand Down Expand Up @@ -464,6 +466,8 @@ export class BridgeWorker {
private registrationCapabilities: BridgeWorkerCapabilities;
private activeCapabilities: BridgeWorkerCapabilities;
private instructionMetadataSupported = true;
/** Added error codes the current Code API registration accepts in settlements. */
private settlementErrorCodes: ReadonlySet<WorkspaceToolErrorCode> = new Set();
private registrationTtlMs = DEFAULT_REGISTRATION_TTL_MS;
private lastRegisteredAtMs = 0;
private maintenanceOnly = false;
Expand Down Expand Up @@ -803,6 +807,11 @@ export class BridgeWorker {
}
this.registrationTtlMs = registration.leaseTtlMs;
this.activeCapabilities = this.registrationCapabilities;
this.settlementErrorCodes = new Set(
Array.isArray(registration.supportedWorkspaceToolErrorCodes)
? registration.supportedWorkspaceToolErrorCodes
: [],
);
await this.options.onRegistered?.(registration);
if (
!this.maintenanceOnly &&
Expand Down Expand Up @@ -2085,7 +2094,7 @@ export class BridgeWorker {
...((assignment.executionKind === 'workspace_tool' ||
assignment.executionKind === 'workspace_programmatic') &&
error instanceof WorkspaceToolError
? { errorCode: error.code }
? { errorCode: this.settlementErrorCode(error.code) }
: {}),
error: (assignment.executionKind === 'workspace_tool' &&
isWorkspaceToolRequest(assignment.request) &&
Expand Down Expand Up @@ -2474,6 +2483,12 @@ export class BridgeWorker {
);
}

/** An older Code API refuses a settlement carrying a code it does not know. */
private settlementErrorCode(code: WorkspaceToolErrorCode): WorkspaceToolErrorCode {
if (this.settlementErrorCodes.has(code)) return code;
return WORKSPACE_TOOL_ERROR_CODE_FALLBACKS[code] ?? code;
}

private async settleWithRetry(
assignment: BridgeAssignment,
settlement: BridgeSettlement,
Expand Down Expand Up @@ -2525,6 +2540,20 @@ export class BridgeWorker {
} catch (error) {
lastError = error;
if (signal?.aborted) break;
const legacyErrorCode =
settlement.status === 'rejected' && settlement.errorCode != null
? WORKSPACE_TOOL_ERROR_CODE_FALLBACKS[settlement.errorCode]
: undefined;
if (
settlement.status === 'rejected' &&
legacyErrorCode != null &&
error instanceof BridgeProtocolError &&
error.status === 400
) {
/** A replica that predates the added code can still serve this settlement. */
settlement = { ...settlement, errorCode: legacyErrorCode };
continue;
}
if (
error instanceof BridgeProtocolError &&
error.status != null &&
Expand Down
106 changes: 106 additions & 0 deletions packages/code/src/workspace-worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,112 @@ test('worker omits pagination fields until Code API negotiates them', async () =
});
});

async function settleMissingFile(
registeredCodes: string[] | undefined,
rejectSettlement: (body: Record<string, unknown>) => boolean = () => false,
): Promise<{ settlements: Array<Record<string, unknown>>; failure?: unknown }> {
const settlements: Array<Record<string, unknown>> = [];
const workspaceCapabilities = {
protocolVersion: 1 as const,
operations: ['read_file' as const],
workspaces: [{ id: 'primary' }],
};
const worker = new BridgeWorker({
codeApiUrl: 'https://code.example/v1',
token: 'worker-secret',
workerId: 'vm-1',
incarnationId,
sandboxEndpoint: 'http://127.0.0.1:2000/api/v2',
capabilities: {
statefulWorkspace: false,
sandboxProfile: 'nsjail',
runtimes: [],
workspaceTools: workspaceCapabilities,
},
workspaceTools: {
capabilities: workspaceCapabilities,
async execute() {
throw new WorkspaceToolError('Workspace path does not exist', 'NOT_FOUND');
},
},
fetchImpl: async (input, init) => {
if (!String(input).endsWith('/settle')) {
return Response.json({
protocolVersion: 1,
workerId: 'vm-1',
incarnationId,
registeredAt: new Date().toISOString(),
leaseTtlMs: 60_000,
supportedWorkspaceToolOperations: ['read_file'],
...(registeredCodes ? { supportedWorkspaceToolErrorCodes: registeredCodes } : {}),
});
}
const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
settlements.push(body);
if (rejectSettlement(body)) {
return Response.json({ error: 'Invalid bridge settlement' }, { status: 400 });
}
return Response.json({ protocolVersion: 1, accepted: true });
},
});

await worker.register();
const failure = await worker.executeAndSettle({
protocolVersion: 1,
assignmentId: 'assignment-missing-file',
workerId: 'vm-1',
incarnationId,
generation: 1,
leaseToken: 'lease-token-that-is-long-enough-for-testing',
expiresAt: new Date(Date.now() + 5_000).toISOString(),
executionKind: 'workspace_tool',
request: {
protocolVersion: 1,
operation: 'read_file',
workspaceId: 'primary',
path: 'logs/pending.log',
},
}).then(() => undefined, (error: unknown) => error);
return { settlements, failure };
}

test('worker reports NOT_FOUND only to a Code API that advertised it', async () => {
const { settlements: supported } = await settleMissingFile(['NOT_FOUND']);
assert.deepEqual(
supported.map(({ status, errorCode, error }) => ({ status, errorCode, error })),
[{ status: 'rejected', errorCode: 'NOT_FOUND', error: 'Workspace path does not exist' }],
);

for (const registeredCodes of [undefined, [], ['SOMETHING_ELSE']]) {
const { settlements: legacy } = await settleMissingFile(registeredCodes);
assert.deepEqual(
legacy.map(({ status, errorCode, error }) => ({ status, errorCode, error })),
[{ status: 'rejected', errorCode: 'INVALID_PATH', error: 'Workspace path does not exist' }],
);
}
});

test('worker resends a refused NOT_FOUND settlement with its legacy code', async () => {
const { settlements, failure } = await settleMissingFile(
['NOT_FOUND'],
(body) => body.errorCode === 'NOT_FOUND',
);

assert.equal(failure, undefined);
assert.deepEqual(
settlements.map(({ errorCode }) => errorCode),
['NOT_FOUND', 'INVALID_PATH'],
);
});

test('worker does not resend a refused legacy settlement', async () => {
const { settlements, failure } = await settleMissingFile(undefined, () => true);

assert.deepEqual(settlements.map(({ errorCode }) => errorCode), ['INVALID_PATH']);
assert.ok(failure instanceof BridgeProtocolError);
assert.equal(failure.status, 400);
});

test('worker omits restricted workspaces that legacy registration would widen', async () => {
const registrations: Array<{
operations: string[];
Expand Down
Loading
Loading