Multiplayer agent harness for work.
import type { ReplayImageLoader } from "./replay-images.ts";
import type { ResumableToolCall } from "../core/turn-resume.ts";
import type { DocumentInput } from "../core/document-inputs.ts";
import type { RuntimeControl, HarnessHandoff } from "./runtime-types.ts";
import type {
AttachmentMeta,
ClientToolDeclaration,
ConversationTurn,
ScopeId,
Session,
SessionEntry,
TurnRequest,
TurnRuntime,
} from "../types.ts";
import type { HarnessId } from "../model/pi-models.ts";
import type { GapPhases, GapWork, LlmCallUsage, LlmTransportMeta, NewEntry } from "../sessions/session-store.ts";
export type { GapWork } from "../sessions/session-store.ts";
import type { OverheardEntryPayload } from "./replay.ts";
import type { GoalRecord } from "./goal.ts";
import type { GrindMeter } from "./grind.ts";
import type { McpToolDescriptor } from "../mcp/mcp-tool-service.ts";
import type { ProviderKeys } from "./pi-harness.ts";
import type { ToolContext } from "../tools/primitives.ts";
import type { SecurityScreenVerdict, ToolResultScreen, ToolResultScreenInput } from "../security/security-posture.ts";
export interface RuntimeChoice {
harnessId: HarnessId;
modelId: string;
effortLevel?: string;
fastMode?: boolean;
}
interface HarnessImage {
mimeType: string;
dataBase64: string;
artifactId?: string;
}
export function promptEnvelopeWithoutHistory(payload: unknown): unknown {
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
const envelope: Record<string, unknown> = {};
for (const [key, value] of Object.entries(payload)) {
if (key === "contents") continue;
if (key === "messages" || key === "input") {
if (Array.isArray(value)) {
const instructions = value.filter(
(item: unknown) =>
item !== null &&
typeof item === "object" &&
"role" in item &&
(item.role === "system" || item.role === "developer"),
);
if (instructions.length) envelope[key] = instructions;
}
} else {
envelope[key] = key === "context" ? promptEnvelopeWithoutHistory(value) : value;
}
}
return envelope;
}
export interface HarnessLlmRequestRecord {
turnSeq: number | null;
step: number;
model: string;
promptEnvelope?: unknown;
truncated: boolean;
transport?: LlmTransportMeta | null;
ttftMs?: number | null;
durationMs?: number | null;
stepGapMs?: number | null;
toolWallMs?: number[] | null;
gapPhases?: GapPhases | null;
usage?: LlmCallUsage | null;
}
export interface HarnessSecurityScreenInput {
payload: string;
harnessId?: string;
modelId?: string;
systemPrompt?: string;
signal: AbortSignal;
recordModelCall(rec: { model: string; inputTokens: number; entryCount: number }): void;
recordLlmRequest?(rec: HarnessLlmRequestRecord, signal?: AbortSignal): void | Promise<void>;
}
export interface HarnessTurnInput {
loadImage?: ReplayImageLoader;
session: Session;
runId?: string;
cancel?: AbortSignal;
continueTurn?: boolean;
resumeUserSeq?: number;
shutdown?: AbortSignal;
input: string;
triggerTs?: string;
entryTs?: string;
environment?: string;
timezone?: string;
priorTurns?: ConversationTurn[];
overheard?: OverheardEntryPayload[];
attachments?: AttachmentMeta[];
images?: HarnessImage[];
prepareSteer?(
text: string,
request?: TurnRequest,
): Promise<{
text: string;
attachments?: AttachmentMeta[];
images?: HarnessImage[];
documents?: DocumentInput[];
author?: string;
}>;
documents?: DocumentInput[];
runtime?: Partial<RuntimeChoice>;
runtimePurpose?: import("../resolution/config-store.ts").RuntimePurpose;
runtimeControl?: RuntimeControl;
runtimeActorId?: string;
readOnly?: boolean;
surfaceTools?: boolean;
delegateWork?: boolean;
surfaceName?: string;
clientTools?: readonly ClientToolDeclaration[];
pollFire?: boolean;
turnWallClockMs?: number;
systemPrompt: string;
history: SessionEntry[];
goal?: GoalRecord | null;
goalContinuation?: boolean;
goalMeter?: GrindMeter;
saveGoal?(goal: GoalRecord): Promise<void>;
goalInbox?: import("./goal.ts").GoalInbox;
tools: ToolContext;
mcpTools?: McpToolDescriptor[];
commandCredentialHandles?: readonly string[];
toolApprovalGate?(tool: string, callKey?: string): boolean;
emit(entry: NewEntry): Promise<SessionEntry>;
resumeToolCall?: ResumableToolCall;
scopeLabel: ScopeId;
orgScopeId: ScopeId;
providerKeys?: ProviderKeys;
runtimePinned?: boolean;
onRuntime?(runtime: TurnRuntime): void;
claudeOauthToken?: string;
recordModelCall(rec: { model: string; inputTokens: number; entryCount: number }): void;
recordLlmRequest?(rec: HarnessLlmRequestRecord, signal?: AbortSignal): void | Promise<void>;
onProgress?(p: { toolCalls: number; tokens?: number }): void;
onGapWork?(sink: (work: GapWork) => void): void;
onDelta?(chunk: string): void;
onReasoningDelta?(step: string, index: number, chunk: string): void;
onTextBlockStart?(phase?: "commentary" | "final_answer"): void | Promise<void>;
onToolCallStart?(name: string): void;
screenToolResult?(input: ToolResultScreenInput): Promise<ToolResultScreen>;
governGoal?: import("./goal.ts").GoalGovernor;
}
export interface HarnessTurnResult {
runtimeHandoff?: HarnessHandoff;
reply: string;
silent?: boolean;
stopped?: true;
stoppedByUser?: true;
pendingApprovals?: Array<{
command: string;
reason: string;
kind?: "approval";
matched?: string;
purpose?: string;
approvalKey?: string;
grantModes?: { session: boolean; always: boolean };
}>;
pausedOnApproval?: boolean;
modelCalls?: number;
cacheUsage?: { cacheRead: number; cacheWrite: number; uncachedInput: number };
}
export interface HarnessDetectInput {
session: Session;
message: string;
recentContext: string;
threadOpener?: string;
systemPrompt: string;
reactionGuidance?: string;
history: SessionEntry[];
recordModelCall(rec: { model: string; inputTokens: number; entryCount: number }): void;
}
export interface HarnessDetectResult {
respond: boolean;
reactions?: string[];
reason?: string;
}
export interface HarnessCompactInput {
session: Session;
history: SessionEntry[];
recordModelCall(rec: { model: string; inputTokens: number; entryCount: number }): void;
}
interface HarnessTurnController {
runTurn(input: HarnessTurnInput): Promise<HarnessTurnResult>;
close?(): Promise<void> | void;
resetSession?(sessionId: string): Promise<void> | void;
}
export interface HarnessModelUtilities {
shouldRespond?(input: HarnessDetectInput): Promise<HarnessDetectResult>;
compactHistory?(input: HarnessCompactInput): Promise<string>;
contextTokenBudget?(scopeLabel?: string, model?: string): number | undefined;
oneShot?(systemPrompt: string, prompt: string): Promise<string | undefined>;
judge?(systemPrompt: string, prompt: string, signal?: AbortSignal): Promise<string | undefined>;
screenSecurity?(input: HarnessSecurityScreenInput): Promise<SecurityScreenVerdict | undefined>;
pickAckEmoji?(text: string, candidates: readonly string[]): Promise<string | undefined>;
generateTitle?(transcript: string): Promise<string | undefined>;
summarizeApproval?(command: string, reason: string, purpose?: string): Promise<string | undefined>;
}
type HarnessControlTransport = "in-process" | "sdk" | "http" | "json-rpc" | "api";
type HarnessToolTransport = "in-process" | "plugin" | "dynamic" | "in-process-mcp" | "mcp";
type HarnessCapability =
"abort" | "steer" | "images" | "thinking-level" | "fast-mode" | "provider-sessions" | "goal-enforcement";
export interface HarnessAdapterProfile {
id: string;
controlTransport: HarnessControlTransport;
toolTransport: HarnessToolTransport;
transcriptFormat: string;
capabilities: ReadonlySet<HarnessCapability>;
}
export interface HarnessToolPresentation {
name(coreName: string): string;
}
export interface Harness {
profile: HarnessAdapterProfile;
turns: HarnessTurnController;
models: HarnessModelUtilities;
tools: HarnessToolPresentation;
}
export type HarnessImplementation = HarnessTurnController & HarnessModelUtilities;
export function defineHarness(
profile: HarnessAdapterProfile,
implementation: HarnessImplementation,
tools: HarnessToolPresentation = { name: (coreName) => coreName },
): Harness {
const turns: HarnessTurnController = {
runTurn: implementation.runTurn.bind(implementation),
...(implementation.close ? { close: implementation.close.bind(implementation) } : {}),
...(implementation.resetSession ? { resetSession: implementation.resetSession.bind(implementation) } : {}),
};
const models: HarnessModelUtilities = {
...(implementation.shouldRespond ? { shouldRespond: implementation.shouldRespond.bind(implementation) } : {}),
...(implementation.compactHistory ? { compactHistory: implementation.compactHistory.bind(implementation) } : {}),
...(implementation.contextTokenBudget
? { contextTokenBudget: implementation.contextTokenBudget.bind(implementation) }
: {}),
...(implementation.oneShot ? { oneShot: implementation.oneShot.bind(implementation) } : {}),
...(implementation.judge ? { judge: implementation.judge.bind(implementation) } : {}),
...(implementation.screenSecurity ? { screenSecurity: implementation.screenSecurity.bind(implementation) } : {}),
...(implementation.pickAckEmoji ? { pickAckEmoji: implementation.pickAckEmoji.bind(implementation) } : {}),
...(implementation.generateTitle ? { generateTitle: implementation.generateTitle.bind(implementation) } : {}),
...(implementation.summarizeApproval
? { summarizeApproval: implementation.summarizeApproval.bind(implementation) }
: {}),
};
return { profile, turns, models, tools };
}