下面列出 @anyswarm/core 的主要公共类型。完整声明分别位于 Core types、Service types、后端配置、执行器适配器、文件策略、模型传输 与 默认 Worker 镜像常量。概念与实战请先阅读 搭建第一个 SDK Harness 与 AutoResearch 旗舰案例拆解。
所有公开值(完整列表见 SDK 与 API 参考)与公开类型均从 @anyswarm/core 根入口导入。以下声明覆盖 Runtime、文件、回执、Sandbox、Service 与 HarnessSession 作者边界。
Runtime、Profile、FileTree 与事件类型
export interface Profile {
/** Optional Harness instructions added to the standard startup prompt. */
prompt?: string;
model: string;
image: string;
writable: boolean;
services: Readonly<Record<string, readonly string[]>>;
spawnProfiles?: readonly string[];
allowContextFork?: boolean;
env?: Readonly<Record<string, string>>;
network?: { allow: readonly string[] };
collect?: CollectionSpec;
}
export interface CreateRuntimeOptions {
sandbox: Sandbox;
executor?: ExecutorKind;
models: Readonly<Record<string, ModelConfig>>;
connection?: RuntimeConnectionOptions;
profiles: Readonly<Record<string, Profile>>;
services: ServiceRegistry;
maxAgents: number;
outputDir: string;
agentAccessPolicy?: AgentAccessPolicy;
}
export interface FileEntry {
readonly encoding: 'utf8' | 'base64';
readonly data: string;
readonly mode?: 0o644 | 0o755;
}
export type FileTree = Readonly<Record<string, FileEntry>>;
export type CompleteFileDigest = `complete:sha256:${string}`;
export type PartialFileDigest = `partial:sha256:${string}`;
export interface FileSnapshotOptions {
requestId: string;
paths: readonly string[];
maxBytes?: number;
}
export interface CompleteFileSnapshotOptions extends FileSnapshotOptions {
paths: readonly ['.'];
}
export interface CompleteFileSnapshot {
readonly agentId: string;
readonly requestId: string;
readonly version: number;
readonly files: FileTree;
readonly scope: 'complete';
readonly digest: CompleteFileDigest;
}
export interface PartialFileSnapshot {
readonly agentId: string;
readonly requestId: string;
readonly version: number;
readonly files: FileTree;
readonly scope: 'partial';
readonly digest: PartialFileDigest;
}
export type FileSnapshot = CompleteFileSnapshot | PartialFileSnapshot;
export interface FileReplaceOptions {
requestId: string;
expectedDigest: CompleteFileDigest;
files: FileTree;
writable?: true;
}
export type FileReplaceReceipt = {
readonly agentId: string;
readonly requestId: string;
} & (
| { readonly status: 'completed'; readonly digest: CompleteFileDigest; readonly writable: boolean }
| { readonly status: 'failed'; readonly error: ErrorInfo }
| { readonly status: 'unknown' }
);
export interface CollectionSpec {
paths: readonly string[];
includeGit: boolean;
allowMissingGit?: boolean;
maxBytes: number;
required: boolean;
}
export type WorkspaceOptions = { id: string; mode: 'read-only' | 'read-write' };
export interface SpawnOptions {
forkFrom?: string;
requestId: string;
profile: string;
parentId?: string;
writable?: boolean;
files?: FileTree;
bindings?: Readonly<Record<string, string>>;
secretEnv?: Readonly<Record<string, string>>;
workspace?: WorkspaceOptions;
collect?: CollectionSpec;
}
export interface ErrorInfo {
code: string;
message: string;
retryable: boolean;
}
export interface ResourceError extends Error {
code: string;
operation: string;
runtimeId?: string;
agentId?: string;
requestId?: string;
cleanup: 'complete' | 'pending';
reportPath?: string;
details: readonly ErrorInfo[];
}
export type AgentStatus = 'starting' | 'idle' | 'running' | 'exited' | 'closing' | 'closed';
export interface AgentListFilter {
parentId?: string | null;
status?: AgentStatus | readonly AgentStatus[];
}
export interface AgentInfo {
id: string;
profile: string;
parentId?: string;
status: AgentStatus;
latestOutput?: string;
lastError?: ErrorInfo;
lastStop?: StopReceipt;
}
export type InputMode = 'steer' | 'followUp';
export interface SendOptions {
requestId: string;
mode?: InputMode;
source?: string;
steeringMode?: SteeringMode;
wakeIfIdle?: boolean;
}
export type InputReceipt =
| { inputId: string; status: 'accepted'; disposition: 'started' | 'queued' | 'handled' }
| { inputId: string; status: 'unknown' };
export type ConditionalInputReceipt = InputReceipt | { inputId: string; status: 'not-accepted'; reason: 'idle' };
export interface InterruptReceipt {
interruptId: string;
status: 'interrupted' | 'unknown';
discardedInputHashes?: readonly string[];
}
export type AgentInitialInputResult = InputReceipt | { status: 'rejected'; error: ErrorInfo } | null;
/** Built-in agent.spawn Service result, distinct from host Runtime.spawn. */
export interface AgentSpawnReceipt {
agent: AgentInfo;
initialInput: AgentInitialInputResult;
}
type AgentEvent = { agentId: string } & (
| { type: 'output'; text: string }
| { type: 'settled'; outcome: 'completed' | 'failed' | 'aborted'; output?: string; error?: ErrorInfo }
| { type: 'error'; error: ErrorInfo; fatal: boolean }
| { type: 'exit'; reason: string; expected: boolean }
);
export type RuntimeEvent = AgentEvent
| { type: 'agentChanged'; agentId: string }
| { type: 'runtimeChanged' }
| { type: 'management'; change: RuntimeManagementChange };
export type RuntimeState = 'open' | 'closing' | 'closed';
export interface InterruptOptions {
requestId: string;
timeoutMs?: number;
}
export interface StopOptions { timeoutMs?: number }
export interface CloseOptions { timeoutMs?: number }
export interface PendingCleanup {
kind: 'agent' | 'bridge' | 'model' | 'backend' | 'report' | 'service';
id: string;
action: 'await-startup' | 'stop-execution' | 'archive-session' | 'collect-artifacts' | 'delete-sandbox' | 'close' | 'save' | 'retire-service';
error?: ErrorInfo;
resourceKey?: string;
providerId?: string;
sandboxId?: string;
creation?: 'created' | 'pending' | 'absent';
executionStopped?: boolean;
}
export interface StopReceipt {
agentId: string;
execution: 'stopped' | 'unknown';
cleanup: 'complete' | 'pending';
artifacts: readonly string[];
sessionArchive?: string;
errors: readonly ErrorInfo[];
pending?: PendingCleanup;
}
export interface CloseReceipt {
agents: readonly StopReceipt[];
cleanup: 'complete' | 'pending';
errors: readonly ErrorInfo[];
pending: readonly PendingCleanup[];
outputDir: string;
reportPath?: string;
evidence: { path?: string; recorded: number; lost: number; pending: number };
}
export interface ProfileRegistration {
readonly actorId?: string;
readonly id: string;
readonly requestId: string;
readonly profile: Profile;
}
export interface ProfileDefinition {
readonly actorId?: string;
readonly id: string;
readonly digest: string;
readonly sequence: number;
readonly profile: Profile;
}
export interface RuntimeServiceRegistration {
readonly actorId?: string;
readonly requestId: string;
readonly registration: ServiceRegistration;
readonly deploymentRef: string;
readonly implementationId: string;
readonly ownership: 'run' | 'external';
}
export interface ServiceRetirement {
readonly actorId?: string;
readonly serviceId: string;
readonly requestId: string;
readonly timeoutMs?: number;
}
export interface RuntimeServiceDefinition {
readonly actorId?: string;
readonly id: string;
readonly manifest: ServiceManifest;
readonly sequence: number;
readonly state: 'ready' | 'retiring' | 'retired';
readonly deploymentRef?: string;
readonly implementationId?: string;
readonly ownership?: RuntimeServiceRegistration['ownership'];
readonly error?: ErrorInfo;
}
export type AgentAccessRequest = {
readonly runtimeId: string;
readonly callerId: string;
readonly agentId: string;
} & (
| { readonly operation: 'access_get' }
| { readonly operation: 'grant' | 'revoke'; readonly serviceId: string; readonly operations: readonly string[] }
);
export type AgentAccessPolicy = (request: AgentAccessRequest) => boolean;
export interface AgentAccess {
readonly agentId: string;
readonly version: number;
readonly services: Readonly<Record<string, readonly string[]>>;
}
export interface AgentAccessMutation {
readonly agentId: string;
readonly serviceId: string;
readonly operations: readonly string[];
readonly requestId: string;
}
export type AgentAccessGrant = AgentAccessMutation & { readonly binding?: string };
export interface RuntimeManagementSnapshot {
readonly sequence: number;
readonly profiles: readonly ProfileDefinition[];
readonly services: readonly RuntimeServiceDefinition[];
readonly access: readonly AgentAccess[];
}
export type RuntimeManagementChange = {
readonly sequence: number;
readonly caller: string;
readonly requestId: string;
} & (
| { readonly operation: 'profile.register'; readonly definition: ProfileDefinition }
| { readonly operation: 'service.register' | 'service.retire'; readonly definition: RuntimeServiceDefinition }
| { readonly operation: 'access.grant' | 'access.revoke'; readonly access: AgentAccess; readonly serviceId: string; readonly operations: readonly string[] }
);
export interface Runtime {
readonly id: string;
readonly state: RuntimeState;
spawn(options: SpawnOptions): Promise<AgentInfo>;
get(agentId: string): Promise<AgentInfo>;
list(filter?: AgentListFilter): Promise<AgentInfo[]>;
interrupt(agentId: string, options: InterruptOptions): Promise<InterruptReceipt>;
send(agentId: string, input: string, options: SendOptions & { wakeIfIdle?: true }): Promise<InputReceipt>;
send(agentId: string, input: string, options: SendOptions): Promise<ConditionalInputReceipt>;
onEvent(handler: (event: RuntimeEvent) => void | Promise<void>): () => void;
stop(agentId: string, options?: StopOptions): Promise<StopReceipt>;
close(options?: CloseOptions): Promise<CloseReceipt>;
readonly profiles: {
register(input: ProfileRegistration): Promise<ProfileDefinition>;
get(id: string): ProfileDefinition | null;
list(): readonly ProfileDefinition[];
};
readonly access: {
get(agentId: string): AgentAccess | null;
grant(input: AgentAccessGrant): Promise<AgentAccess>;
revoke(input: AgentAccessMutation): Promise<AgentAccess>;
};
readonly services: {
register(input: RuntimeServiceRegistration): Promise<RuntimeServiceDefinition>;
get(id: string): RuntimeServiceDefinition | null;
list(): readonly RuntimeServiceDefinition[];
retire(input: ServiceRetirement): Promise<RuntimeServiceDefinition>;
};
readonly management: { get(): RuntimeManagementSnapshot };
readonly files: RuntimeFiles;
}
export interface RuntimeFiles {
snapshot(agentId: string, options: CompleteFileSnapshotOptions): Promise<CompleteFileSnapshot>;
snapshot(agentId: string, options: FileSnapshotOptions): Promise<FileSnapshot>;
replace(agentId: string, options: FileReplaceOptions): Promise<FileReplaceReceipt>;
}
Sandbox 与 Runtime 连接配置
endpointHost 与 isolation 保留在迁移类型中,用于向旧配置返回明确的校验错误。内置 Provider 会在分配沙箱前拒绝 endpoint 改写与旧版精确 Workspace 磁盘配额;迁移对照见 Sandbox 资源与迁移表。
declare const sandboxBrand: unique symbol;
export interface Sandbox {
readonly [sandboxBrand]: true;
}
export interface SandboxConfig {
kind?: 'opensandbox';
endpoint?: string;
/** Migration alias for endpoint. */
lifecycleBaseUrl?: string;
apiKey?: string;
execdToken?: string;
endpointHost?: string;
useServerProxy?: boolean;
/** Assertion by the deployment administrator. Smoke verifies the actual policy. */
egressMode?: 'dns+nft';
resourceLimits?: { cpu: string; memory: string };
commandTimeoutMs?: number;
timeoutSeconds?: number;
isolation?:
| { network?: 'local-docker'; disk: { bytes: number; inodes: number } }
| { network?: 'api'; disk?: { bytes: number; inodes?: never } };
}
export type ExecutorKind = 'pi' | 'codex';
export type SteeringMode = 'all' | 'one-at-a-time';
export interface ExecutorCapabilities {
readonly activeSteer: boolean;
readonly followUp: boolean;
readonly conditionalInput: boolean;
readonly queuedInputCancellation: boolean;
readonly contextFork: boolean;
readonly steeringModes: readonly SteeringMode[];
}
export type ModelThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
export type ModelThinkingLevelMap = Partial<Record<ModelThinkingLevel, string | null>>;
export interface ModelCapabilities {
contextWindow: number;
maxOutputTokens: number;
tools: boolean;
reasoning: boolean;
thinkingLevelMap?: ModelThinkingLevelMap;
}
export interface ModelConfig {
provider: string;
model: string;
protocol?: 'responses' | 'chat-completions' | ModelTransport;
capabilities?: ModelCapabilities;
upstream: { url: string; headers: Readonly<Record<string, string>> };
}
export interface RuntimeConnectionOptions {
publicUrl?: string;
bindHost?: string;
bindPort?: number;
advertiseHost?: string;
bridge?: { host?: string; publicUrl?: string };
modelGateway?: {
host?: string;
advertiseHost?: string;
publicUrl?: string;
requestTimeoutMs?: number;
maxOutputTokens?: number | null;
/** Maximum new upstream attempts per Runtime and model alias, including unknown outcomes. */
maxRequests?: number;
};
}
Service 作者接口
export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
export type ServiceToolMode = 'direct' | 'code' | 'cli';
export type ServiceProvider = 'in-process' | 'http' | 'mcp' | 'cli';
export interface ServiceOperation {
description: string;
inputSchema?: Record<string, unknown>;
outputSchema?: Record<string, unknown>;
sideEffect?: 'read' | 'write';
idempotent?: boolean;
timeoutMs?: number;
usage?: string;
}
export interface ServiceInterface {
description: string;
operations: Readonly<Record<string, ServiceOperation>>;
}
export interface ServiceDefinition {
interface?: ServiceInterface;
provider: ServiceProvider;
endpoint?: ServiceManifest['endpoint'];
discoversOperations?: boolean;
create(): { adapter: ServiceAdapter; lifecycle?: ServiceLifecycle };
}
export type ServicePublicError = {
code: string;
message: string;
details?: JsonValue;
retryable?: boolean;
};
export interface ServiceCallMetadata {
operationId: string;
attemptId: string;
requestOutcome: 'not_executed' | 'returned' | 'unknown';
failureSource?: 'service' | 'bridge' | 'transport';
}
export type ServiceReply<T = JsonValue> = (
| { ok: true; result: T; content?: readonly ServiceContent[] }
| { ok: false; error: ServicePublicError; content?: readonly ServiceContent[] }
) & { meta?: ServiceCallMetadata };
持久化恢复选项
import type { CreateRuntimeOptions, RecoverRuntimeOptions } from "@anyswarm/core";
// CreateRuntimeOptions 新增字段
// persistence?: { deploymentId: string; contract: string; retainForMs?: number };
// operationLimits?: { prepare?: number; stop?: number; transfer?: number; queued?: number; waitMs?: number };
// RecoverRuntimeOptions 继承自 CreateRuntimeOptions
// runDirectory: string;
// cleanupOnly?: boolean;
// restoreService?(definition: RuntimeServiceDefinition): Promise<ServiceRegistration | undefined>;
默认值与恢复前提见 Runtime 持久化恢复。
HarnessSession 类型
- 核心契约与状态:
Harness与HarnessContext定义作者接口;HarnessSessionOptions配置单次会话;HarnessDescriptor与HarnessState分别描述开放能力与当前运行快照;HarnessEvent区分初始快照、状态变更、提问、操作回执、实时事件与最终结果。 - 成员控制与结果:
HarnessAgents返回 Runtime 查询与 Agent 控制回执,控制器可在core回执旁附加harnessEffects;HarnessResult保留业务结果、产物、清理状态、已提交命令与终态问题证据。 - 派发与 Runtime 托管:
HarnessDispatchRequest将调用方requestId、有界operationId与 Runsignal传入输入、控制与核对回调(查询原始 Runtime 回执时复用该operationId);HarnessRuntimeRunOptions为context.runWithRuntime配置自有 Runtime 工厂、业务回调、可选afterClose校验与清理超时。 - 人机提问:
HarnessQuestionRequest支持text、choice(带稳定选项 ID)与confirm(布尔回答);HarnessQuestionSource将提问绑定到 Run 内部来源,并附带取消信号与可选授权校验。