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
4 changes: 3 additions & 1 deletion apps/server/src/modules/agent/acp/agent-cli.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ vi.mock('@agenetes/agentlet-host', () => ({
getAgentlet: () => ({ status: 'connected' }),
discoverHarnesses: mocks.discover,
}),
resolveConnectedAgentletId: (target: string) =>
target === 'legacy-host' ? 'remote-machine' : target,
}));

let app: FastifyInstance | undefined;
Expand Down Expand Up @@ -119,7 +121,7 @@ describe('ACP agent CLI route', () => {
});

it('queries the edited Profile machine and projects Custom for older catalogues', async () => {
mocks.getProfile.mockReturnValue({ agentletId: 'remote-machine' });
mocks.getProfile.mockReturnValue({ agentletId: 'legacy-host' });
mocks.discover.mockResolvedValue({ harnesses: [] });
app = Fastify({ logger: false });
await app.register(createAcpAgentCliRoutes(), { prefix: '/api/acp' });
Expand Down
9 changes: 7 additions & 2 deletions apps/server/src/modules/agent/acp/agent-cli.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import {
getAgentletGateway,
getAgentProfileRegistry,
resolveConnectedAgentletId,
} from '@agenetes/agentlet-host';
import {
CUSTOM_COMMAND_CAPABILITIES,
Expand Down Expand Up @@ -46,8 +47,12 @@ async function detectAgentClis(target: {
: undefined;
if (target.profileId && !profile)
throw new Error('Agent Profile is unavailable');
const agentletId = profile?.agentletId ?? target.agentletId;
if (!agentletId) throw new Error('Agentlet target is required');
const requestedAgentletId = profile?.agentletId ?? target.agentletId;
if (!requestedAgentletId) throw new Error('Agentlet target is required');
const agentletId = profile
? resolveConnectedAgentletId(requestedAgentletId)
: requestedAgentletId;
if (!agentletId) throw new Error('Agentlet is not connected');
const connection = gateway.getAgentlet(agentletId);
if (connection?.status !== 'connected')
throw new Error('Agentlet is not connected');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
ensureAcpSession,
resolveAcpAgentletId,
} from '@agenetes/acp-driver';
import { resolveConnectedAgentletId } from '@agenetes/agentlet-host';

import { canvasAcpNamespace } from '../../workspace/paths.js';
import {
Expand Down Expand Up @@ -123,8 +124,10 @@ async function ensureSessionFromCanonicalSpec(
? { ...resolvedEnvironment, ...spec.spec.env }
: undefined;
const record = await agenetes.record(spec.namespace, spec.threadId);
const requestedAgentletId = resolveAcpAgentletId(spec);
return ensureAcpSession({
agentletId: resolveAcpAgentletId(spec),
agentletId:
resolveConnectedAgentletId(requestedAgentletId) ?? requestedAgentletId,
threadId: spec.threadId,
binding: spec.spec.binding,
namespace: spec.namespace,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,17 @@
}),
};
const gateway = {
getAgentlets: () => initialMachines.map((agentletId) => ({ agentletId })),
getAgentlets: () =>
initialMachines.map((agentletId) => ({
agentletId,
agentletProfile: {
machine: {
hostname: agentletId,
platform: 'linux',
arch: 'x64',
},
},
})),
onAgentletsChanged: (handler: (event: Event) => void) => {
listener = handler;
return vi.fn();
Expand Down Expand Up @@ -116,6 +126,7 @@
},
);
expect(context.profiles[0]).toMatchObject({
alias: 'GitHub Copilot (machine-a: linux x64)',
agentletId: 'machine-a',
workingDirPath: '/home/user/.agentlet/workspace/copilot',
launch: { kind: 'acp-command', command: 'copilot --acp' },
Expand All @@ -134,8 +145,8 @@
const context = setup();
const dispose = context.start();
await flush();
context.profiles[0]!.alias = 'My helper';

Check warning on line 148 in apps/server/src/modules/agent/acp/harness-profile-discovery.test.ts

View workflow job for this annotation

GitHub Actions / Lint / Format / Typecheck / Test / Build

Forbidden non-null assertion
context.profiles[0]!.customData!.preference = 'kept';

Check warning on line 149 in apps/server/src/modules/agent/acp/harness-profile-discovery.test.ts

View workflow job for this annotation

GitHub Actions / Lint / Format / Typecheck / Test / Build

Forbidden non-null assertion

Check warning on line 149 in apps/server/src/modules/agent/acp/harness-profile-discovery.test.ts

View workflow job for this annotation

GitHub Actions / Lint / Format / Typecheck / Test / Build

Forbidden non-null assertion
context.emit({ agentletId: 'machine-a', status: 'connected' });
context.emit({ agentletId: 'machine-a', status: 'connected' });
await flush();
Expand Down Expand Up @@ -277,7 +288,7 @@
const registry = createAgentProfileRegistry({ storageDir });
const legacy = registry.createProfile({
launchKind: 'acp-command',
alias: 'GitHub Copilot (machine-a)',
alias: 'GitHub Copilot (machine-a: linux x64)',
agentletId: 'machine-a',
workingDirPath: '/custom/work',
command: 'copilot --acp --model old-model',
Expand Down Expand Up @@ -328,7 +339,7 @@
.listProfiles()
.find((profile) => profile.launch.kind === 'acp-harness');
expect(typed).toMatchObject({
alias: 'GitHub Copilot (machine-a) [copilot]',
alias: 'GitHub Copilot (machine-a: linux x64) [copilot]',
workingDirPath: observation.harnesses[0].workingDirPath,
launch: {
kind: 'acp-harness',
Expand Down Expand Up @@ -395,7 +406,7 @@
const dispose = context.start();
await flush();
expect(context.profiles).toHaveLength(3);
expect(context.profiles[0]!.workingDirPath).toBe('/my/project');

Check warning on line 409 in apps/server/src/modules/agent/acp/harness-profile-discovery.test.ts

View workflow job for this annotation

GitHub Actions / Lint / Format / Typecheck / Test / Build

Forbidden non-null assertion
expect(
context.profiles.slice(1).map((profile) => profile.agentletId),
).toEqual(['machine-a', 'machine-b']);
Expand All @@ -414,7 +425,7 @@
log: context.log,
});
await flush();
const original = registry.listProfiles()[0]!;

Check warning on line 428 in apps/server/src/modules/agent/acp/harness-profile-discovery.test.ts

View workflow job for this annotation

GitHub Actions / Lint / Format / Typecheck / Test / Build

Forbidden non-null assertion
registry.patchProfile(original.id, { alias: 'Kept after restart' });
dispose();

Expand Down Expand Up @@ -525,7 +536,7 @@
context.emit({ agentletId: 'machine-a', status: 'connected' });
await flush();
expect(context.profiles).toHaveLength(1);
expect(context.profiles[0]!.id).toBe('profile-2');

Check warning on line 539 in apps/server/src/modules/agent/acp/harness-profile-discovery.test.ts

View workflow job for this annotation

GitHub Actions / Lint / Format / Typecheck / Test / Build

Forbidden non-null assertion
dispose();
});

Expand Down Expand Up @@ -588,7 +599,7 @@
const context = setup();
context.gateway.discoverHarnesses.mockResolvedValueOnce({
harnesses: [
{ ...observation.harnesses[0]!, installed: false },

Check warning on line 602 in apps/server/src/modules/agent/acp/harness-profile-discovery.test.ts

View workflow job for this annotation

GitHub Actions / Lint / Format / Typecheck / Test / Build

Forbidden non-null assertion
{
...observation.harnesses[0]!,
workingDirPath: undefined,
Expand Down
20 changes: 18 additions & 2 deletions apps/server/src/modules/agent/acp/harness-profile-discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

import { CUSTOM_COMMAND_WRAPPER_ID } from '@agentlet/protocol';

import { formatAgentletDeviceDisplayName } from '../agentlet-device-display.js';

import type {
AgentProfile,
AgentProfileRegistry,
Expand Down Expand Up @@ -76,7 +78,16 @@ export function mergeProfileCustomData(
}

interface DiscoveryGateway {
getAgentlets(filter: { status: 'connected' }): Array<{ agentletId: string }>;
getAgentlets(filter: { status: 'connected' }): Array<{
agentletId: string;
agentletProfile?: {
machine?: {
hostname?: string;
platform?: string;
arch?: string;
};
};
}>;
onAgentletsChanged(
handler: (event: {
agentletId: string;
Expand Down Expand Up @@ -149,7 +160,12 @@ export function registerHarnessProfileDiscovery({
);
});
if (existing) continue;
const defaultAlias = `${harness.displayName} (${agentletId})`;
const connection = gateway
.getAgentlets({ status: 'connected' })
.find((candidate) => candidate.agentletId === agentletId);
const defaultAlias = `${harness.displayName} (${formatAgentletDeviceDisplayName(
connection?.agentletProfile?.machine,
)})`;
const common = {
agentletId,
alias:
Expand Down
36 changes: 36 additions & 0 deletions apps/server/src/modules/agent/acp/profiles.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ vi.mock('@agenetes/agentlet-host', () => ({
},
})),
}),
resolveConnectedAgentletId: (target: string) => {
if (mocks.connectedIds.has(target)) return target;
const matches = [...mocks.connectedIds].filter(
(agentletId) => `${agentletId}-host` === target,
);
return matches.length === 1 ? matches[0] : undefined;
},
}));

vi.mock('./profile-schema-cache.js', () => ({
Expand Down Expand Up @@ -190,6 +197,7 @@ describe('ordinary Profile catalog routes', () => {
connectedDevices: [
expect.objectContaining({
agentletId: 'machine-a',
displayName: 'machine-a-host: linux x64',
profileCount: 1,
}),
expect.objectContaining({
Expand All @@ -198,11 +206,39 @@ describe('ordinary Profile catalog routes', () => {
}),
],
});

expect(mocks.registry.createProfile).not.toHaveBeenCalled();
expect(mocks.initializeDefaults).not.toHaveBeenCalled();
expect(mocks.discoverHarnesses).not.toHaveBeenCalled();
});

it('maps one hostname-era Profile to the unique connected device', async () => {
const legacyProfile = {
...commandProfile,
id: 'legacy-command',
agentletId: 'machine-a-host',
};
mocks.registry.listProfiles.mockReturnValue([legacyProfile]);
const server = await setup();
const response = await server.inject('/api/acp/profiles');

expect(response.statusCode).toBe(200);
expect(response.json()).toMatchObject({
profiles: [legacyProfile],
selectableProfileIds: ['legacy-command'],
connectedDevices: [
expect.objectContaining({
agentletId: 'machine-a',
profileCount: 1,
}),
expect.objectContaining({
agentletId: 'remote-machine',
profileCount: 0,
}),
],
});
});

it('rejects caller-created automatic provenance', async () => {
const server = await setup();
const response = await server.inject({
Expand Down
28 changes: 17 additions & 11 deletions apps/server/src/modules/agent/acp/profiles.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
getAgentProfileRegistry,
getAgentletGateway,
getDaemonSupervisor,
resolveConnectedAgentletId,
} from '@agenetes/agentlet-host';

import {
Expand All @@ -48,6 +49,7 @@ import {
getAgentDefaults,
initializeAgentDefaults,
} from '../agent-defaults.js';
import { formatAgentletDeviceDisplayName } from '../agentlet-device-display.js';

import type { AgentletConnection } from '@agenetes/agentlet-host';
import type {
Expand Down Expand Up @@ -88,7 +90,10 @@ async function validateHarnessLaunch(
try {
const gateway = getAgentletGateway();
if (!gateway) throw new Error('Agentlet Gateway is not ready');
const result = await gateway.discoverHarnesses(agentletId, {
const resolvedAgentletId = resolveConnectedAgentletId(agentletId);
if (!resolvedAgentletId)
throw new Error('The selected Agentlet is not connected');
const result = await gateway.discoverHarnesses(resolvedAgentletId, {
prepareWorkspaces: false,
});
const harness = result.harnesses.find(
Expand Down Expand Up @@ -117,7 +122,7 @@ async function validateHarnessLaunch(
});
return false;
}
await gateway.buildHarnessLaunch(agentletId, { launch });
await gateway.buildHarnessLaunch(resolvedAgentletId, { launch });
return true;
} catch (error) {
request.log.warn(
Expand Down Expand Up @@ -156,7 +161,9 @@ const acpProfilesRoutes: FastifyPluginAsync = async (app) => {
try {
const gateway = getAgentletGateway();
if (!gateway) throw new Error('Agentlet Gateway is not ready');
const agentletId = profile?.agentletId ?? parsed.data.agentletId;
const agentletId = profile
? resolveConnectedAgentletId(profile.agentletId)
: parsed.data.agentletId;
if (!agentletId || !isAgentletConnected(agentletId)) {
return reply.status(409).send({
code: 'agentlet_unavailable',
Expand Down Expand Up @@ -190,19 +197,18 @@ const acpProfilesRoutes: FastifyPluginAsync = async (app) => {
}
const profiles = registry.listProfiles();
const connected = getConnectedAgentlets();
const connectedIds = new Set(
connected.map((connection) => connection.agentletId),
);
const profileCounts = new Map<string, number>();
for (const profile of profiles) {
profileCounts.set(
profile.agentletId,
(profileCounts.get(profile.agentletId) ?? 0) + 1,
);
const agentletId = resolveConnectedAgentletId(profile.agentletId);
if (!agentletId) continue;
profileCounts.set(agentletId, (profileCounts.get(agentletId) ?? 0) + 1);
}
const connectedDevices = connected
.map((connection) => ({
agentletId: connection.agentletId,
displayName: formatAgentletDeviceDisplayName(
connection.agentletProfile?.machine,
),
...(connection.agentletProfile?.machine?.hostname
? { hostname: connection.agentletProfile.machine.hostname }
: {}),
Expand All @@ -225,7 +231,7 @@ const acpProfilesRoutes: FastifyPluginAsync = async (app) => {
return {
profiles,
selectableProfileIds: profiles
.filter((profile) => connectedIds.has(profile.agentletId))
.filter((profile) => resolveConnectedAgentletId(profile.agentletId))
.map((profile) => profile.id),
connectedDevices,
agentlet: getDaemonSupervisor().getStatus(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ vi.mock('@agenetes/acp-driver', () => ({
},
}));

vi.mock('@agenetes/agentlet-host', () => ({
resolveConnectedAgentletId: (agentletId: string) =>
agentletId === 'legacy-host' ? 'device-uuid' : agentletId,
}));

vi.mock('./external-agent-realization.js', () => ({
externalAgentRealization: { realize: vi.fn(), ensureSession: vi.fn() },
realizationHttpError: () => ({
Expand Down Expand Up @@ -115,6 +120,7 @@ describe('ACP cached-meta across awaited persistence', () => {
usage: null,
metaUpdatedAt: 32,
});

const server = await createApp();

const response = await server.inject({
Expand All @@ -135,6 +141,30 @@ describe('ACP cached-meta across awaited persistence', () => {
});
});

it('finds a live session through unique hostname-era placement resolution', async () => {
mocks.record = externalRecord('legacy-host');
mocks.live.set('device-uuid\u0000thread-1', {
availableCommands: [{ name: 'review', description: 'Review changes' }],
commandsUpdatedAt: 5,
availableModes: [],
currentModeId: null,
availableModels: [],
currentModelId: null,
configOptions: [],
selections: {},
sessionInfo: null,
usage: null,
metaUpdatedAt: 6,
});
const response = await (await createApp()).inject(CACHED_META_URL);

expect(response.statusCode).toBe(200);
expect(response.json()).toMatchObject({
source: 'thread',
availableCommands: [{ name: 'review' }],
});
});

it('does not invent a placement for a thread with no record', async () => {
mocks.live.set('agentlet-supervised\u0000thread-1', {
availableCommands: [],
Expand Down
4 changes: 3 additions & 1 deletion apps/server/src/modules/agent/acp/threads.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

import { acpSessionRegistry } from '@agenetes/acp-driver';
import { resolveConnectedAgentletId } from '@agenetes/agentlet-host';

import {
acpPermissionDecisionSchema,
Expand Down Expand Up @@ -151,7 +152,8 @@ async function resolveThreadAgentletId(
typeof driverSpec === 'object' &&
typeof (driverSpec as { agentletId?: unknown }).agentletId === 'string'
) {
return (driverSpec as { agentletId: string }).agentletId;
const agentletId = (driverSpec as { agentletId: string }).agentletId;
return resolveConnectedAgentletId(agentletId) ?? agentletId;
}
}
return undefined;
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/modules/agent/agent-defaults.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ vi.mock('./agent-defaults.js', () => ({
vi.mock('@agenetes/agentlet-host', () => ({
getAgentProfileRegistry: () =>
mocks.registryReady ? { getProfile: mocks.getProfile } : null,
getAgentletGateway: () => ({ getAgentlet: mocks.getAgentlet }),
resolveConnectedAgentletId: (target: string) =>
mocks.getAgentlet(target)?.status === 'connected' ? target : undefined,
}));
vi.mock('./acp/profile-schema-cache.js', () => ({
getProfileSchemaCache: mocks.getCache,
Expand Down
5 changes: 2 additions & 3 deletions apps/server/src/modules/agent/agent-defaults.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import {
getAgentProfileRegistry,
getAgentletGateway,
resolveConnectedAgentletId,
} from '@agenetes/agentlet-host';

import {
Expand Down Expand Up @@ -60,8 +60,7 @@ function projectDefaults(defaults: AgentDefaults): AgentDefaultsResponse {
? 'offline'
: !profile
? 'deleted'
: getAgentletGateway()?.getAgentlet(profile.agentletId)?.status ===
'connected'
: resolveConnectedAgentletId(profile.agentletId)
? 'available'
: 'offline',
// Missing observations and editable CLI labels do not prove lack of support.
Expand Down
Loading
Loading