Skip to content
Closed
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
6 changes: 4 additions & 2 deletions packages/command-surface/src/management/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts';

const artifactsCommandMetadata = defineFieldCommandMetadata(
'artifacts',
'List daemon or cloud provider artifacts for an active or completed session.',
'List artifacts for the authenticated tenant and producing lease, including retained output after close.',
{
provider: stringField(
'Cloud provider name, for example browserstack, aws-device-farm, or testmu.',
),
providerSessionId: stringField('Cloud provider session id or ARN.'),
providerSessionId: stringField(
'Cloud provider session id or ARN. Send the original producing lease scope.',
),
},
);

Expand Down
24 changes: 21 additions & 3 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,15 @@ import type { ReasonTable } from '@agent-device/kernel/errors';
export const DAEMON_HTTP_BASE_PATH = '/agent-device';
export const DAEMON_HTTP_TENANT_HEADER = 'x-agent-device-tenant';
// Names the lease a non-RPC request (upload, artifact download, request diagnostics) belongs to,
// as RPC calls name it in their body. Neither the daemon nor the proxy reads it; it lets a gateway
// in front of many daemons route those requests to the one holding the lease.
// as RPC calls name it in their body. The daemon reads it for lease admission and a gateway
// can route the request to the daemon holding the lease. The header is caller-declared.
export const DAEMON_HTTP_LEASE_HEADER = 'x-agent-device-lease-id';
/** Why an upload is refused before its staging directory is created. */
export const UPLOAD_CAPACITY_REASONS = {
// A new upload would exceed the active upload count or reserved byte budget.
exceeded: { reason: 'UPLOAD_CAPACITY_EXCEEDED' },
} as const satisfies ReasonTable<'uploads'>;
export const DAEMON_HTTP_RUN_HEADER = 'x-agent-device-run-id';
export const DAEMON_HTTP_NETWORK_ACCESS_HEADER = 'x-agent-device-network-access';
export const DAEMON_HTTP_PUBLIC_NETWORK_ACCESS = 'public-only';

Expand Down Expand Up @@ -120,11 +126,17 @@ export function buildDaemonHttpLeaseHeaders(leaseId: string | undefined): Record
return { [DAEMON_HTTP_LEASE_HEADER]: normalizedLeaseId };
}

export function buildDaemonHttpRunHeaders(runId: string | undefined): Record<string, string> {
const normalizedRunId = runId?.trim();
if (!normalizedRunId) return {};
return { [DAEMON_HTTP_RUN_HEADER]: normalizedRunId };
}

// See docs/adr/0006-daemon-rpc-protocol-version.md before changing this value.
// Enforced, not just documented: `test/wire-compat/` digests the declarations
// that cross this boundary and fails when one changes shape without a bump or
// an acknowledged-compatible entry (#1432).
export const DAEMON_RPC_PROTOCOL_VERSION = 3;
export const DAEMON_RPC_PROTOCOL_VERSION = 4;

/**
* The largest serialized daemon request, in UTF-8 bytes, that any transport reads: the socket
Expand All @@ -134,6 +146,10 @@ export const DAEMON_RPC_PROTOCOL_VERSION = 3;
* worst-case escaping. It also bounds the memory one unauthenticated connection can hold.
*/
export const DAEMON_REQUEST_MAX_BYTES = 64 * 1024 * 1024;
/** Time for receiving and authenticating an RPC before command execution begins. */
export const DAEMON_RPC_PREAUTH_TIMEOUT_MS = 5_000;
/** Maximum string ID length echoed in an RPC preauthorization timeout. */
export const DAEMON_RPC_PREAUTH_MAX_ID_LENGTH = 128;

export const DAEMON_HTTP_INSTANCE_HEADER = 'x-agent-device-instance';
export const DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER = 'x-agent-device-upstream-instance';
Expand Down Expand Up @@ -352,3 +368,5 @@ function dottedExtension(extension: string): string {
function remoteTempArtifactStem(prefix: string): string {
return `agent-device-${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}

export const DAEMON_HTTP_UPLOAD_SESSION_HEADER = 'x-agent-device-session';
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import http from 'node:http';
import { EventEmitter } from 'node:events';
import { afterEach, test, vi } from 'vitest';
import { isRequestCanceledError } from '@agent-device/kernel/errors';
import { DAEMON_RPC_PROTOCOL_VERSION } from '@agent-device/contracts/daemon-http';
import { sendToDaemon } from '../index.ts';

type Call = { method: string; path: string; at: number };
Expand All @@ -24,7 +25,10 @@ function fakeResponse(): EventEmitter {
* The first checked POST hangs before its socket connects. `/health` answers with `healthStatus`
* (and an instance ID, so a usable answer is cached); every other request answers.
*/
function firstCheckedConnectHangs(healthStatus = 200, healthProtocol = 3): Call[] {
function firstCheckedConnectHangs(
healthStatus = 200,
healthProtocol = DAEMON_RPC_PROTOCOL_VERSION,
): Call[] {
const calls: Call[] = [];
vi.spyOn(http, 'request').mockImplementation(((
options: { method?: string; path?: string },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async function remoteDaemon(answer: Answer = OK_ANSWER, pinned = false) {
JSON.stringify({
ok: true,
service: 'agent-device-daemon',
rpcProtocolVersion: 3,
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
...(pinned ? { instanceId: 'daemon-1' } : {}),
}),
);
Expand Down Expand Up @@ -536,7 +536,7 @@ test('after a stale-instance retry onto a daemon with no instance ID, the next o
JSON.stringify({
ok: true,
service: 'agent-device-daemon',
rpcProtocolVersion: 3,
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
...(replaced ? {} : { instanceId: 'old' }),
}),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,20 +226,27 @@ test('a daemon health payload without an upstream link or host arch parses as be
);
});

test.for(['daemon', 'upstream'] as const)(
'released protocol-2 %s cannot silently omit batch receipt delivery',
async (link, t) => {
test.for([
['daemon', 2],
['upstream', 2],
['daemon', 3],
['upstream', 3],
] as const)(
'released protocol-%s %s is refused before command RPC',
async ([link, releasedProtocol], t) => {
if (await skipWhenLoopbackUnavailable(t)) return;

const payload =
link === 'upstream' ? proxyHealth(2) : { ...DAEMON_LINK, rpcProtocolVersion: 2 };
link === 'upstream'
? proxyHealth(releasedProtocol)
: { ...DAEMON_LINK, rpcProtocolVersion: releasedProtocol };
await withHealthServer(payload, async (baseUrl) => {
await assert.rejects(
readRemoteDaemonHealth({ baseUrl, token: 't', pid: 0 }),
(error: unknown) => {
const failure = error as { code?: string; details?: Record<string, unknown> };
assert.equal(failure.code, 'COMMAND_FAILED');
assert.equal(failure.details?.remoteRpcProtocolVersion, 2);
assert.equal(failure.details?.remoteRpcProtocolVersion, releasedProtocol);
assert.equal(failure.details?.supportedRpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION);
return true;
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ export function createHumanControlHarness() {
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
androidObservation: clearAndroidObservationFixture,
platformResourceCleanup: platformResourceCleanupFixture(),
trackDownloadableArtifact: () => 'artifact-1',
});
return { registry, lease, sessionStore, sessionName, handleRequest };
}
2 changes: 1 addition & 1 deletion packages/daemon/src/core/__tests__/daemon-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ function makeHandler(
}
: undefined,
}),
trackDownloadableArtifact: () => 'artifact-id',

hostDiagnostics: hostDiagnosticsFixture(),
daemonPolicy,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ function leasedDaemon() {
leaseRegistry,
deviceInventoryGateways: createTestDeviceInventoryGateways(),
deviceRuntimeGateway: lifecycleDeviceRuntimeGateway,
trackDownloadableArtifact: () => 'artifact-id',
});
return {
root,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@ function makeHandler(gateway: DeviceRuntimeGateway<PlatformRuntimeOperations>) {
leaseRegistry,
deviceInventoryGateways: createTestDeviceInventoryGateways(),
deviceRuntimeGateway: gateway,
trackDownloadableArtifact: () => 'artifact',
}),
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ test('requireTenantOwnedEntry returns entries readable by the tenant', () => {
['owned', { tenantId: 'tenant-a' }],
]);
assert.equal(requireTenantOwnedEntry(map, 'shared', undefined, RESOURCE), map.get('shared'));
assert.equal(requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE), map.get('shared'));
assert.throws(
() => requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE),
/different tenant/,
);
assert.equal(requireTenantOwnedEntry(map, 'owned', 'tenant-a', RESOURCE), map.get('owned'));
});

Expand Down
66 changes: 0 additions & 66 deletions packages/daemon/src/core/capture-output-ownership.ts
Original file line number Diff line number Diff line change
@@ -1,71 +1,5 @@
import type { DaemonArtifact, DaemonResponseData } from '@agent-device/kernel/contracts';

const CAPTURE_OUTPUT_OWNERSHIP = Symbol('captureOutputOwnership');
type CaptureOutputOwnership = 'daemon' | 'caller';
type CaptureOutputOwner = Readonly<{
ownership: CaptureOutputOwnership;
tenantId?: string;
/** Null records an unleased producer. Undefined leaves ownership to the request. */
leaseVerifier?: string | null;
}>;
type CaptureOutputData = DaemonResponseData & {
[CAPTURE_OUTPUT_OWNERSHIP]?: CaptureOutputOwner;
};

/** Producer-owned capture facts stay private when the response is serialized. */
export function withCaptureOutputOwnership(
data: DaemonResponseData,
ownership: CaptureOutputOwnership,
tenantId?: string,
leaseVerifier?: string | null,
): DaemonResponseData {
return { ...data, [CAPTURE_OUTPUT_OWNERSHIP]: { ownership, tenantId, leaseVerifier } };
}

export function captureOutputOwnership(
data: DaemonResponseData,
): CaptureOutputOwnership | undefined {
const capture: CaptureOutputData = data;
return capture[CAPTURE_OUTPUT_OWNERSHIP]?.ownership;
}

export function captureOutputTenantId(data: DaemonResponseData): string | undefined {
const capture: CaptureOutputData = data;
return capture[CAPTURE_OUTPUT_OWNERSHIP]?.tenantId;
}

export function captureOutputLeaseVerifier(data: DaemonResponseData): string | null | undefined {
const capture: CaptureOutputData = data;
return capture[CAPTURE_OUTPUT_OWNERSHIP]?.leaseVerifier;
}

const DAEMON_DELIVERED_ARTIFACT = Symbol('daemonDeliveredArtifact');
type DeliveredArtifact = DaemonArtifact & {
[DAEMON_DELIVERED_ARTIFACT]?: Readonly<{ tenantId: string | undefined }>;
};

/**
* Marks an artifact the daemon produced for the caller itself, such as a remote recording's script
* version. It is registered for download for `tenantId` alone, whatever the request's tenant,
* capture filters, or network marker say. The mark stays private when the response is serialized.
*/
export function asDaemonDeliveredArtifact(
artifact: DaemonArtifact,
tenantId: string | undefined,
): DaemonArtifact {
const delivered: DeliveredArtifact = artifact;
delivered[DAEMON_DELIVERED_ARTIFACT] = { tenantId };
return delivered;
}

/** The delivery of a daemon-delivered artifact, or `undefined` for any other artifact. */
export function daemonDeliveredArtifact(
artifact: DaemonArtifact | undefined,
): Readonly<{ tenantId: string | undefined }> | undefined {
const delivered: DeliveredArtifact | undefined = artifact;
return delivered?.[DAEMON_DELIVERED_ARTIFACT];
}

const screenshotDeliveryPaths = new WeakMap<DaemonArtifact, string>();

/** Keep delivery metadata on the artifact that response views carry to the HTTP reply. */
Expand Down
3 changes: 3 additions & 0 deletions packages/daemon/src/core/daemon-request.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ArtifactOwner } from '../resources/artifact-tracking.ts';
import type { ExecutionPlan } from './execution-plan.ts';
import type { PreresolvedInteractionTarget } from '@agent-device/contracts/interaction';
import type { DeviceLease } from '@agent-device/contracts/device';
Expand Down Expand Up @@ -50,6 +51,8 @@ type DaemonRequestInternal = ReplayDispatchOptions & {
*/
retainDeviceExecutionLock?: (deviceId: string) => Promise<void>;
admittedLease?: DeviceLease;
admittedArtifactScope?: { principal: 'local' | 'declared' | 'attested'; owner: ArtifactOwner };
principal?: 'local' | 'declared' | 'attested';
sessionAuthorityActive?: () => boolean;
snapshotObservation?: Readonly<{
device: DeviceInfo;
Expand Down
66 changes: 51 additions & 15 deletions packages/daemon/src/core/session-script-publication-capability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import type {
} from '@agent-device/kernel/contracts';
import { readResponseWarnings } from '@agent-device/kernel/success-text';
import type { AuthorizedSession } from './session-store.ts';
import { asDaemonDeliveredArtifact } from './capture-output-ownership.ts';
import {
leaseVerifier,
commitProducedOutput,
type ArtifactOwner,
} from '../resources/artifact-tracking.ts';
import type { SessionState } from './session-state.ts';
import {
NO_SCRIPT_PUBLICATION,
Expand Down Expand Up @@ -230,6 +234,7 @@ type RemoteScriptVersion =
export type RemoteCloseScript = Readonly<{
delivery: RemoteScriptDelivery;
version?: RemoteScriptVersion;
owner: ArtifactOwner;
}>;

/** Numbers the next version of a remote recording, so the caller keeps the newest one. */
Expand All @@ -252,6 +257,7 @@ function withRemoteScriptVersion(
response: DaemonResponse,
delivery: RemoteScriptDelivery,
version: RemoteScriptVersion,
owner: ArtifactOwner,
): DaemonResponse {
if (!response.ok) return response;
const { publicationId } = delivery;
Expand All @@ -271,16 +277,19 @@ function withRemoteScriptVersion(
},
};
}
const artifact = asDaemonDeliveredArtifact(
const artifact = commitProducedOutput(
{
field: 'savedScript',
artifactPath: version.path,
artifactType: 'session-script',
path: version.path,
fileName: path.basename(version.path),
},
owner,
{
field: 'savedScript',
fileName: path.basename(version.path),
scriptPublicationId: publicationId,
scriptRevision: delivery.revision,
},
delivery.tenantId,
);
const artifacts = Array.isArray(data.artifacts) ? data.artifacts : [];
return { ok: true, data: { ...data, artifacts: [...artifacts, artifact] } };
Expand All @@ -305,16 +314,26 @@ export function remoteScriptVersionDelivery(
const result = authorized.writeScriptVersion();
if (result.written) {
const stamped = stampNextRevision(ref.session) ?? delivery;
return withRemoteScriptVersion(response, stamped, { path: result.path });
return withRemoteScriptVersion(
response,
stamped,
{ path: result.path },
scriptProducer(ref.session, delivery),
);
}
if (!result.error) return response;
// The daemon diagnostic keeps the cause; its daemon-host path stays out of the response.
return withRemoteScriptVersion(response, delivery, {
failure: {
message: 'The action succeeded, but the daemon could not write the remote recording.',
hint: 'The --save-script file keeps the previous version. The next recorded action or close delivers the full recording again.',
return withRemoteScriptVersion(
response,
delivery,
{
failure: {
message: 'The action succeeded, but the daemon could not write the remote recording.',
hint: 'The --save-script file keeps the previous version. The next recorded action or close delivers the full recording again.',
},
},
});
scriptProducer(ref.session, delivery),
);
};
}

Expand All @@ -333,11 +352,19 @@ export function remoteCloseScript(
if (writeFailed) {
const message = 'The session was closed, but the daemon could not write its final script.';
const hint = 'The --save-script file keeps the version from the last recorded action.';
return { delivery, version: { failure: { message, hint } } };
return {
delivery,
owner: scriptProducer(session, delivery),
version: { failure: { message, hint } },
};
}
const writtenPath = state.status === 'published' ? scriptTargetPath(state) : undefined;
if (!writtenPath) return { delivery };
return { delivery: stampNextRevision(session) ?? delivery, version: { path: writtenPath } };
if (!writtenPath) return { delivery, owner: scriptProducer(session, delivery) };
return {
delivery: stampNextRevision(session) ?? delivery,
owner: scriptProducer(session, delivery),
version: { path: writtenPath },
};
}

/**
Expand All @@ -354,5 +381,14 @@ export function remoteCloseScriptDelivery(
ok: true,
data: { ...response.data, scriptPublicationId: close.delivery.publicationId },
};
return close.version ? withRemoteScriptVersion(named, close.delivery, close.version) : named;
return close.version
? withRemoteScriptVersion(named, close.delivery, close.version, close.owner)
: named;
}

function scriptProducer(session: SessionState, delivery: RemoteScriptDelivery): ArtifactOwner {
return {
tenantId: delivery.tenantId,
leaseVerifier: session.lease ? leaseVerifier(session.lease.leaseId) : null,
};
}
Loading
Loading