Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e29fcbd259 |
No files matched your search
@@ -639,9 +639,13 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
|
||||
...(cachedProviderOptions !== undefined ? { providerOptions: cachedProviderOptions } : {}),
|
||||
});
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedProviderOptions !== undefined
|
||||
? { providerOptions: cachedProviderOptions }
|
||||
: {},
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
|
||||
@@ -291,9 +291,13 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
yield* upsertSessionBinding(
|
||||
session,
|
||||
threadId,
|
||||
input.providerOptions !== undefined
|
||||
? { providerOptions: input.providerOptions }
|
||||
: {},
|
||||
);
|
||||
yield* analytics.record("provider.session.started", {
|
||||
provider: session.provider,
|
||||
runtimeMode: input.runtimeMode,
|
||||
|
||||
@@ -128,6 +128,18 @@
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"packages/harness-ws-server": {
|
||||
"name": "@t3tools/harness-ws-server",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
},
|
||||
},
|
||||
"packages/shared": {
|
||||
"name": "@t3tools/shared",
|
||||
"version": "0.0.0-alpha.1",
|
||||
@@ -685,6 +697,8 @@
|
||||
|
||||
"@t3tools/desktop": ["@t3tools/desktop@workspace:apps/desktop"],
|
||||
|
||||
"@t3tools/harness-ws-server": ["@t3tools/harness-ws-server@workspace:packages/harness-ws-server"],
|
||||
|
||||
"@t3tools/marketing": ["@t3tools/marketing@workspace:apps/marketing"],
|
||||
|
||||
"@t3tools/scripts": ["@t3tools/scripts@workspace:scripts"],
|
||||
|
||||
@@ -42,3 +42,9 @@ export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
|
||||
export type ApprovalRequestId = typeof ApprovalRequestId.Type;
|
||||
export const CheckpointRef = makeEntityId("CheckpointRef");
|
||||
export type CheckpointRef = typeof CheckpointRef.Type;
|
||||
export const HarnessSessionId = makeEntityId("HarnessSessionId");
|
||||
export type HarnessSessionId = typeof HarnessSessionId.Type;
|
||||
export const HarnessProfileId = makeEntityId("HarnessProfileId");
|
||||
export type HarnessProfileId = typeof HarnessProfileId.Type;
|
||||
export const HarnessConnectorId = makeEntityId("HarnessConnectorId");
|
||||
export type HarnessConnectorId = typeof HarnessConnectorId.Type;
|
||||
@@ -0,0 +1,245 @@
|
||||
import { Schema } from "effect";
|
||||
import {
|
||||
EventId,
|
||||
HarnessConnectorId,
|
||||
HarnessProfileId,
|
||||
HarnessSessionId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
RuntimeRequestId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
} from "./baseSchemas";
|
||||
|
||||
const UnknownRecord = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
export const HarnessKind = Schema.Literals(["codex-app-server", "claude-agent-sdk", "opencode"]);
|
||||
export type HarnessKind = typeof HarnessKind.Type;
|
||||
|
||||
export const HarnessAdapterFamily = Schema.Literals(["process", "sdk", "bridge"]);
|
||||
export type HarnessAdapterFamily = typeof HarnessAdapterFamily.Type;
|
||||
|
||||
export const HarnessConnectionMode = Schema.Literals(["spawned", "attached"]);
|
||||
export type HarnessConnectionMode = typeof HarnessConnectionMode.Type;
|
||||
|
||||
export const HarnessSessionState = Schema.Literals([
|
||||
"idle",
|
||||
"starting",
|
||||
"ready",
|
||||
"running",
|
||||
"waiting",
|
||||
"stopped",
|
||||
"error",
|
||||
]);
|
||||
export type HarnessSessionState = typeof HarnessSessionState.Type;
|
||||
|
||||
export const HarnessTurnState = Schema.Literals([
|
||||
"running",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
]);
|
||||
export type HarnessTurnState = typeof HarnessTurnState.Type;
|
||||
|
||||
export const HarnessModelSwitchMode = Schema.Literals([
|
||||
"unsupported",
|
||||
"restart-required",
|
||||
"in-session",
|
||||
]);
|
||||
export type HarnessModelSwitchMode = typeof HarnessModelSwitchMode.Type;
|
||||
|
||||
export const HarnessPermissionKind = Schema.Literals([
|
||||
"command",
|
||||
"file-read",
|
||||
"file-change",
|
||||
"tool",
|
||||
"exec",
|
||||
"other",
|
||||
]);
|
||||
export type HarnessPermissionKind = typeof HarnessPermissionKind.Type;
|
||||
|
||||
export const HarnessPermissionDecision = Schema.Literals([
|
||||
"accept",
|
||||
"accept-for-session",
|
||||
"decline",
|
||||
"cancel",
|
||||
]);
|
||||
export type HarnessPermissionDecision = typeof HarnessPermissionDecision.Type;
|
||||
|
||||
export const HarnessElicitationAnswer = Schema.Array(TrimmedNonEmptyString);
|
||||
export type HarnessElicitationAnswer = typeof HarnessElicitationAnswer.Type;
|
||||
|
||||
export const HarnessQuestionOption = Schema.Struct({
|
||||
label: TrimmedNonEmptyString,
|
||||
description: TrimmedNonEmptyString,
|
||||
});
|
||||
export type HarnessQuestionOption = typeof HarnessQuestionOption.Type;
|
||||
|
||||
export const HarnessQuestion = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
header: TrimmedNonEmptyString,
|
||||
question: TrimmedNonEmptyString,
|
||||
options: Schema.Array(HarnessQuestionOption),
|
||||
multiple: Schema.optional(Schema.Boolean),
|
||||
custom: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type HarnessQuestion = typeof HarnessQuestion.Type;
|
||||
|
||||
export const HarnessCapabilitySet = Schema.Struct({
|
||||
resume: Schema.Boolean,
|
||||
cancel: Schema.Boolean,
|
||||
modelSwitch: HarnessModelSwitchMode,
|
||||
permissions: Schema.Boolean,
|
||||
elicitation: Schema.Boolean,
|
||||
toolLifecycle: Schema.Boolean,
|
||||
reasoningStream: Schema.Boolean,
|
||||
planStream: Schema.Boolean,
|
||||
fileArtifacts: Schema.Boolean,
|
||||
checkpoints: Schema.Boolean,
|
||||
subagents: Schema.Boolean,
|
||||
});
|
||||
export type HarnessCapabilitySet = typeof HarnessCapabilitySet.Type;
|
||||
|
||||
export const CodexHarnessProfileConfig = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
homePath: Schema.optional(TrimmedNonEmptyString),
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
env: Schema.optional(UnknownRecord),
|
||||
});
|
||||
export type CodexHarnessProfileConfig = typeof CodexHarnessProfileConfig.Type;
|
||||
|
||||
export const ClaudeHarnessProfileConfig = Schema.Struct({
|
||||
modulePath: Schema.optional(TrimmedNonEmptyString),
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
env: Schema.optional(UnknownRecord),
|
||||
sessionMode: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ClaudeHarnessProfileConfig = typeof ClaudeHarnessProfileConfig.Type;
|
||||
|
||||
export const OpenCodeHarnessProfileConfig = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
baseUrl: Schema.optional(TrimmedNonEmptyString),
|
||||
directory: Schema.optional(TrimmedNonEmptyString),
|
||||
username: Schema.optional(TrimmedNonEmptyString),
|
||||
password: Schema.optional(TrimmedNonEmptyString),
|
||||
env: Schema.optional(UnknownRecord),
|
||||
});
|
||||
export type OpenCodeHarnessProfileConfig = typeof OpenCodeHarnessProfileConfig.Type;
|
||||
|
||||
export const HarnessProfileConfig = Schema.Struct({
|
||||
codexAppServer: Schema.optional(CodexHarnessProfileConfig),
|
||||
claudeAgentSdk: Schema.optional(ClaudeHarnessProfileConfig),
|
||||
opencode: Schema.optional(OpenCodeHarnessProfileConfig),
|
||||
});
|
||||
export type HarnessProfileConfig = typeof HarnessProfileConfig.Type;
|
||||
|
||||
export const HarnessProfile = Schema.Struct({
|
||||
id: HarnessProfileId,
|
||||
name: TrimmedNonEmptyString,
|
||||
harness: HarnessKind,
|
||||
adapterFamily: HarnessAdapterFamily,
|
||||
connectionMode: HarnessConnectionMode,
|
||||
enabled: Schema.Boolean,
|
||||
config: HarnessProfileConfig,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type HarnessProfile = typeof HarnessProfile.Type;
|
||||
|
||||
export const HarnessBinding = Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
profileId: Schema.NullOr(HarnessProfileId),
|
||||
harness: HarnessKind,
|
||||
adapterKey: TrimmedNonEmptyString,
|
||||
connectionMode: HarnessConnectionMode,
|
||||
nativeSessionId: Schema.optional(TrimmedNonEmptyString),
|
||||
nativeThreadId: Schema.optional(ThreadId),
|
||||
nativeTurnId: Schema.optional(TurnId),
|
||||
resumeCursor: Schema.optional(Schema.Unknown),
|
||||
metadata: Schema.optional(UnknownRecord),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type HarnessBinding = typeof HarnessBinding.Type;
|
||||
|
||||
export const HarnessSession = Schema.Struct({
|
||||
id: HarnessSessionId,
|
||||
profileId: Schema.NullOr(HarnessProfileId),
|
||||
harness: HarnessKind,
|
||||
adapterKey: TrimmedNonEmptyString,
|
||||
connectionMode: HarnessConnectionMode,
|
||||
title: Schema.NullOr(TrimmedNonEmptyString),
|
||||
cwd: Schema.NullOr(TrimmedNonEmptyString),
|
||||
model: Schema.NullOr(TrimmedNonEmptyString),
|
||||
mode: Schema.NullOr(TrimmedNonEmptyString),
|
||||
state: HarnessSessionState,
|
||||
activeTurnId: Schema.NullOr(TurnId),
|
||||
nativeSessionId: Schema.NullOr(TrimmedNonEmptyString),
|
||||
lastError: Schema.NullOr(TrimmedNonEmptyString),
|
||||
capabilities: HarnessCapabilitySet,
|
||||
metadata: Schema.optional(UnknownRecord),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type HarnessSession = typeof HarnessSession.Type;
|
||||
|
||||
export const HarnessPendingPermission = Schema.Struct({
|
||||
id: RuntimeRequestId,
|
||||
sessionId: HarnessSessionId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
kind: HarnessPermissionKind,
|
||||
title: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
args: Schema.optional(Schema.Unknown),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type HarnessPendingPermission = typeof HarnessPendingPermission.Type;
|
||||
|
||||
export const HarnessPendingElicitation = Schema.Struct({
|
||||
id: RuntimeRequestId,
|
||||
sessionId: HarnessSessionId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
questions: Schema.Array(HarnessQuestion),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type HarnessPendingElicitation = typeof HarnessPendingElicitation.Type;
|
||||
|
||||
export const HarnessConnectorHealth = Schema.Literals(["connected", "degraded", "disconnected"]);
|
||||
export type HarnessConnectorHealth = typeof HarnessConnectorHealth.Type;
|
||||
|
||||
export const HarnessConnector = Schema.Struct({
|
||||
id: HarnessConnectorId,
|
||||
profileId: Schema.NullOr(HarnessProfileId),
|
||||
harness: HarnessKind,
|
||||
adapterKey: TrimmedNonEmptyString,
|
||||
health: HarnessConnectorHealth,
|
||||
description: Schema.optional(TrimmedNonEmptyString),
|
||||
version: Schema.optional(TrimmedNonEmptyString),
|
||||
lastSeenAt: IsoDateTime,
|
||||
metadata: Schema.optional(UnknownRecord),
|
||||
});
|
||||
export type HarnessConnector = typeof HarnessConnector.Type;
|
||||
|
||||
export const HarnessSnapshot = Schema.Struct({
|
||||
sequence: NonNegativeInt,
|
||||
updatedAt: IsoDateTime,
|
||||
profiles: Schema.Array(HarnessProfile),
|
||||
sessions: Schema.Array(HarnessSession),
|
||||
bindings: Schema.Array(HarnessBinding),
|
||||
pendingPermissions: Schema.Array(HarnessPendingPermission),
|
||||
pendingElicitations: Schema.Array(HarnessPendingElicitation),
|
||||
connectors: Schema.Array(HarnessConnector),
|
||||
});
|
||||
export type HarnessSnapshot = typeof HarnessSnapshot.Type;
|
||||
|
||||
export const HarnessNativeFrame = Schema.Struct({
|
||||
id: EventId,
|
||||
sessionId: HarnessSessionId,
|
||||
harness: HarnessKind,
|
||||
adapterKey: TrimmedNonEmptyString,
|
||||
createdAt: IsoDateTime,
|
||||
source: TrimmedNonEmptyString,
|
||||
payload: Schema.Unknown,
|
||||
});
|
||||
export type HarnessNativeFrame = typeof HarnessNativeFrame.Type;
|
||||
@@ -0,0 +1,258 @@
|
||||
import { Schema } from "effect";
|
||||
import {
|
||||
EventId,
|
||||
HarnessConnectorId,
|
||||
HarnessSessionId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
TurnId,
|
||||
TrimmedNonEmptyString,
|
||||
} from "./baseSchemas";
|
||||
import {
|
||||
HarnessBinding,
|
||||
HarnessCapabilitySet,
|
||||
HarnessConnectionMode,
|
||||
HarnessKind,
|
||||
HarnessPermissionDecision,
|
||||
HarnessPermissionKind,
|
||||
HarnessQuestion,
|
||||
HarnessTurnState,
|
||||
} from "./harness";
|
||||
|
||||
const UnknownRecord = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
const HarnessEventBase = Schema.Struct({
|
||||
eventId: EventId,
|
||||
sessionId: HarnessSessionId,
|
||||
createdAt: IsoDateTime,
|
||||
sequence: NonNegativeInt,
|
||||
harness: HarnessKind,
|
||||
adapterKey: TrimmedNonEmptyString,
|
||||
connectionMode: HarnessConnectionMode,
|
||||
turnId: Schema.optional(TurnId),
|
||||
itemId: Schema.optional(RuntimeItemId),
|
||||
nativeRefs: Schema.optional(UnknownRecord),
|
||||
});
|
||||
export type HarnessEventBase = typeof HarnessEventBase.Type;
|
||||
|
||||
const SessionCreatedPayload = Schema.Struct({
|
||||
profileId: Schema.optional(TrimmedNonEmptyString),
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
mode: Schema.optional(TrimmedNonEmptyString),
|
||||
state: Schema.optional(
|
||||
Schema.Literals(["idle", "starting", "ready", "running", "waiting", "stopped", "error"]),
|
||||
),
|
||||
capabilities: Schema.optional(HarnessCapabilitySet),
|
||||
metadata: Schema.optional(UnknownRecord),
|
||||
});
|
||||
|
||||
const SessionBoundPayload = Schema.Struct({
|
||||
binding: HarnessBinding,
|
||||
});
|
||||
|
||||
const SessionStateChangedPayload = Schema.Struct({
|
||||
state: Schema.Literals(["idle", "starting", "ready", "running", "waiting", "stopped", "error"]),
|
||||
reason: Schema.optional(TrimmedNonEmptyString),
|
||||
recoverable: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
const SessionConfigChangedPayload = Schema.Struct({
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
mode: Schema.optional(TrimmedNonEmptyString),
|
||||
metadata: Schema.optional(UnknownRecord),
|
||||
});
|
||||
|
||||
const SessionCapabilitiesChangedPayload = Schema.Struct({
|
||||
capabilities: HarnessCapabilitySet,
|
||||
});
|
||||
|
||||
const SessionExitedPayload = Schema.Struct({
|
||||
reason: Schema.optional(TrimmedNonEmptyString),
|
||||
recoverable: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
const TurnStartedPayload = Schema.Struct({
|
||||
input: Schema.optional(Schema.String),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
mode: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const TurnStateChangedPayload = Schema.Struct({
|
||||
state: HarnessTurnState,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const TurnCompletedPayload = Schema.Struct({
|
||||
stopReason: Schema.optional(TrimmedNonEmptyString),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const TurnFailedPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const TurnCancelledPayload = Schema.Struct({
|
||||
reason: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const MessageStartedPayload = Schema.Struct({
|
||||
role: Schema.Literals(["user", "assistant", "system"]),
|
||||
stream: Schema.optional(Schema.Literals(["assistant", "reasoning", "plan"])),
|
||||
});
|
||||
|
||||
const MessageDeltaPayload = Schema.Struct({
|
||||
role: Schema.optional(Schema.Literals(["assistant", "system"])),
|
||||
stream: Schema.optional(Schema.Literals(["assistant", "reasoning", "plan"])),
|
||||
delta: Schema.String,
|
||||
});
|
||||
|
||||
const MessageCompletedPayload = Schema.Struct({
|
||||
role: Schema.optional(Schema.Literals(["assistant", "system"])),
|
||||
text: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
const ReasoningDeltaPayload = Schema.Struct({
|
||||
delta: Schema.String,
|
||||
});
|
||||
|
||||
const ReasoningSummaryPayload = Schema.Struct({
|
||||
text: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const PlanStep = Schema.Struct({
|
||||
step: TrimmedNonEmptyString,
|
||||
status: Schema.Literals(["pending", "in-progress", "completed"]),
|
||||
});
|
||||
|
||||
const PlanUpdatedPayload = Schema.Struct({
|
||||
explanation: Schema.optional(TrimmedNonEmptyString),
|
||||
steps: Schema.Array(PlanStep),
|
||||
});
|
||||
|
||||
const PlanDeltaPayload = Schema.Struct({
|
||||
delta: Schema.String,
|
||||
});
|
||||
|
||||
const PlanCompletedPayload = Schema.Struct({
|
||||
planMarkdown: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const ItemLifecyclePayload = Schema.Struct({
|
||||
itemType: TrimmedNonEmptyString,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
status: Schema.optional(TrimmedNonEmptyString),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const PermissionRequestedPayload = Schema.Struct({
|
||||
requestId: RuntimeRequestId,
|
||||
kind: HarnessPermissionKind,
|
||||
title: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
args: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const PermissionResolvedPayload = Schema.Struct({
|
||||
requestId: RuntimeRequestId,
|
||||
decision: HarnessPermissionDecision,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const ElicitationRequestedPayload = Schema.Struct({
|
||||
requestId: RuntimeRequestId,
|
||||
questions: Schema.Array(HarnessQuestion),
|
||||
});
|
||||
|
||||
const ElicitationResolvedPayload = Schema.Struct({
|
||||
requestId: RuntimeRequestId,
|
||||
answers: Schema.Array(Schema.Array(TrimmedNonEmptyString)),
|
||||
});
|
||||
|
||||
const ArtifactPersistedPayload = Schema.Struct({
|
||||
files: Schema.Array(
|
||||
Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
path: TrimmedNonEmptyString,
|
||||
kind: TrimmedNonEmptyString,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const ConnectorConnectedPayload = Schema.Struct({
|
||||
connectorId: HarnessConnectorId,
|
||||
description: Schema.optional(TrimmedNonEmptyString),
|
||||
version: Schema.optional(TrimmedNonEmptyString),
|
||||
metadata: Schema.optional(UnknownRecord),
|
||||
});
|
||||
|
||||
const ConnectorHealthChangedPayload = Schema.Struct({
|
||||
connectorId: HarnessConnectorId,
|
||||
health: Schema.Literals(["connected", "degraded", "disconnected"]),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const TransportMessagePayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const NativeFramePayload = Schema.Struct({
|
||||
source: TrimmedNonEmptyString,
|
||||
payload: Schema.Unknown,
|
||||
});
|
||||
|
||||
function defineEvent<Type extends string, Payload extends Schema.Top>(
|
||||
type: Type,
|
||||
payload: Payload,
|
||||
) {
|
||||
return Schema.Struct({
|
||||
...HarnessEventBase.fields,
|
||||
type: Schema.Literal(type),
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
export const HarnessEvent = Schema.Union([
|
||||
defineEvent("session.created", SessionCreatedPayload),
|
||||
defineEvent("session.bound", SessionBoundPayload),
|
||||
defineEvent("session.state.changed", SessionStateChangedPayload),
|
||||
defineEvent("session.config.changed", SessionConfigChangedPayload),
|
||||
defineEvent("session.capabilities.changed", SessionCapabilitiesChangedPayload),
|
||||
defineEvent("session.exited", SessionExitedPayload),
|
||||
defineEvent("turn.started", TurnStartedPayload),
|
||||
defineEvent("turn.state.changed", TurnStateChangedPayload),
|
||||
defineEvent("turn.completed", TurnCompletedPayload),
|
||||
defineEvent("turn.failed", TurnFailedPayload),
|
||||
defineEvent("turn.cancelled", TurnCancelledPayload),
|
||||
defineEvent("message.started", MessageStartedPayload),
|
||||
defineEvent("message.delta", MessageDeltaPayload),
|
||||
defineEvent("message.completed", MessageCompletedPayload),
|
||||
defineEvent("reasoning.delta", ReasoningDeltaPayload),
|
||||
defineEvent("reasoning.summary", ReasoningSummaryPayload),
|
||||
defineEvent("plan.updated", PlanUpdatedPayload),
|
||||
defineEvent("plan.delta", PlanDeltaPayload),
|
||||
defineEvent("plan.completed", PlanCompletedPayload),
|
||||
defineEvent("item.started", ItemLifecyclePayload),
|
||||
defineEvent("item.updated", ItemLifecyclePayload),
|
||||
defineEvent("item.completed", ItemLifecyclePayload),
|
||||
defineEvent("permission.requested", PermissionRequestedPayload),
|
||||
defineEvent("permission.resolved", PermissionResolvedPayload),
|
||||
defineEvent("elicitation.requested", ElicitationRequestedPayload),
|
||||
defineEvent("elicitation.resolved", ElicitationResolvedPayload),
|
||||
defineEvent("artifact.persisted", ArtifactPersistedPayload),
|
||||
defineEvent("connector.connected", ConnectorConnectedPayload),
|
||||
defineEvent("connector.disconnected", ConnectorConnectedPayload),
|
||||
defineEvent("connector.health.changed", ConnectorHealthChangedPayload),
|
||||
defineEvent("transport.warning", TransportMessagePayload),
|
||||
defineEvent("transport.error", TransportMessagePayload),
|
||||
defineEvent("native.frame", NativeFramePayload),
|
||||
]);
|
||||
export type HarnessEvent = typeof HarnessEvent.Type;
|
||||
@@ -0,0 +1,235 @@
|
||||
import { Schema, Struct } from "effect";
|
||||
import {
|
||||
HarnessConnectorId,
|
||||
HarnessProfileId,
|
||||
HarnessSessionId,
|
||||
NonNegativeInt,
|
||||
RuntimeRequestId,
|
||||
TrimmedNonEmptyString,
|
||||
} from "./baseSchemas";
|
||||
import {
|
||||
HarnessConnectionMode,
|
||||
HarnessNativeFrame,
|
||||
HarnessPermissionDecision,
|
||||
HarnessProfile,
|
||||
HarnessQuestion,
|
||||
HarnessSession,
|
||||
HarnessSnapshot,
|
||||
} from "./harness";
|
||||
import { HarnessEvent } from "./harnessEvents";
|
||||
|
||||
export const HARNESS_WS_METHODS = {
|
||||
listProfiles: "harness.listProfiles",
|
||||
upsertProfile: "harness.upsertProfile",
|
||||
deleteProfile: "harness.deleteProfile",
|
||||
listSessions: "harness.listSessions",
|
||||
getSnapshot: "harness.getSnapshot",
|
||||
createSession: "harness.createSession",
|
||||
attachSession: "harness.attachSession",
|
||||
resumeSession: "harness.resumeSession",
|
||||
sendTurn: "harness.sendTurn",
|
||||
cancelTurn: "harness.cancelTurn",
|
||||
resolvePermission: "harness.resolvePermission",
|
||||
resolveElicitation: "harness.resolveElicitation",
|
||||
updateSessionConfig: "harness.updateSessionConfig",
|
||||
replayEvents: "harness.replayEvents",
|
||||
getNativeFrames: "harness.getNativeFrames",
|
||||
} as const;
|
||||
|
||||
export const CONNECTOR_WS_METHODS = {
|
||||
register: "connector.register",
|
||||
bindProfile: "connector.bindProfile",
|
||||
acceptSession: "connector.acceptSession",
|
||||
publishEvent: "connector.publishEvent",
|
||||
publishRawFrame: "connector.publishRawFrame",
|
||||
heartbeat: "connector.heartbeat",
|
||||
completeCommand: "connector.completeCommand",
|
||||
} as const;
|
||||
|
||||
export const HARNESS_WS_CHANNELS = {
|
||||
event: "harness.event",
|
||||
snapshotUpdated: "harness.snapshot.updated",
|
||||
connectorUpdated: "harness.connector.updated",
|
||||
} as const;
|
||||
|
||||
const tagRequestBody = <const Tag extends string, const Fields extends Schema.Struct.Fields>(
|
||||
tag: Tag,
|
||||
schema: Schema.Struct<Fields>,
|
||||
) =>
|
||||
schema.mapFields(Struct.assign({ _tag: Schema.tag(tag) }), {
|
||||
unsafePreserveChecks: true,
|
||||
});
|
||||
|
||||
export const HarnessSendTurnInput = Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
input: Schema.optional(Schema.String),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
mode: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type HarnessSendTurnInput = typeof HarnessSendTurnInput.Type;
|
||||
|
||||
export const HarnessUpdateSessionConfigInput = Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
mode: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type HarnessUpdateSessionConfigInput = typeof HarnessUpdateSessionConfigInput.Type;
|
||||
|
||||
export const HarnessResolvePermissionInput = Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: HarnessPermissionDecision,
|
||||
});
|
||||
export type HarnessResolvePermissionInput = typeof HarnessResolvePermissionInput.Type;
|
||||
|
||||
export const HarnessResolveElicitationInput = Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
requestId: RuntimeRequestId,
|
||||
answers: Schema.Array(Schema.Array(TrimmedNonEmptyString)),
|
||||
});
|
||||
export type HarnessResolveElicitationInput = typeof HarnessResolveElicitationInput.Type;
|
||||
|
||||
export const HarnessClientRequestBody = Schema.Union([
|
||||
tagRequestBody(HARNESS_WS_METHODS.listProfiles, Schema.Struct({})),
|
||||
tagRequestBody(HARNESS_WS_METHODS.upsertProfile, Schema.Struct({ profile: HarnessProfile })),
|
||||
tagRequestBody(HARNESS_WS_METHODS.deleteProfile, Schema.Struct({ profileId: HarnessProfileId })),
|
||||
tagRequestBody(HARNESS_WS_METHODS.listSessions, Schema.Struct({})),
|
||||
tagRequestBody(HARNESS_WS_METHODS.getSnapshot, Schema.Struct({})),
|
||||
tagRequestBody(
|
||||
HARNESS_WS_METHODS.createSession,
|
||||
Schema.Struct({
|
||||
profileId: HarnessProfileId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
HARNESS_WS_METHODS.attachSession,
|
||||
Schema.Struct({
|
||||
profileId: HarnessProfileId,
|
||||
connectionMode: HarnessConnectionMode,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
HARNESS_WS_METHODS.resumeSession,
|
||||
Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(HARNESS_WS_METHODS.sendTurn, HarnessSendTurnInput),
|
||||
tagRequestBody(
|
||||
HARNESS_WS_METHODS.cancelTurn,
|
||||
Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(HARNESS_WS_METHODS.resolvePermission, HarnessResolvePermissionInput),
|
||||
tagRequestBody(HARNESS_WS_METHODS.resolveElicitation, HarnessResolveElicitationInput),
|
||||
tagRequestBody(HARNESS_WS_METHODS.updateSessionConfig, HarnessUpdateSessionConfigInput),
|
||||
tagRequestBody(
|
||||
HARNESS_WS_METHODS.replayEvents,
|
||||
Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
fromSequence: Schema.optional(NonNegativeInt),
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
HARNESS_WS_METHODS.getNativeFrames,
|
||||
Schema.Struct({
|
||||
sessionId: HarnessSessionId,
|
||||
}),
|
||||
),
|
||||
]);
|
||||
|
||||
export const HarnessConnectorRequestBody = Schema.Union([
|
||||
tagRequestBody(
|
||||
CONNECTOR_WS_METHODS.register,
|
||||
Schema.Struct({
|
||||
connectorId: HarnessConnectorId,
|
||||
description: Schema.optional(TrimmedNonEmptyString),
|
||||
version: Schema.optional(TrimmedNonEmptyString),
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
CONNECTOR_WS_METHODS.bindProfile,
|
||||
Schema.Struct({
|
||||
connectorId: HarnessConnectorId,
|
||||
profileId: HarnessProfileId,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
CONNECTOR_WS_METHODS.acceptSession,
|
||||
Schema.Struct({
|
||||
connectorId: HarnessConnectorId,
|
||||
sessionId: HarnessSessionId,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
CONNECTOR_WS_METHODS.publishEvent,
|
||||
Schema.Struct({
|
||||
event: HarnessEvent,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
CONNECTOR_WS_METHODS.publishRawFrame,
|
||||
Schema.Struct({
|
||||
frame: HarnessNativeFrame,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
CONNECTOR_WS_METHODS.heartbeat,
|
||||
Schema.Struct({
|
||||
connectorId: HarnessConnectorId,
|
||||
}),
|
||||
),
|
||||
tagRequestBody(
|
||||
CONNECTOR_WS_METHODS.completeCommand,
|
||||
Schema.Struct({
|
||||
connectorId: HarnessConnectorId,
|
||||
sessionId: HarnessSessionId,
|
||||
ok: Schema.Boolean,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
}),
|
||||
),
|
||||
]);
|
||||
|
||||
export const HarnessWebSocketRequest = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
body: HarnessClientRequestBody,
|
||||
});
|
||||
export type HarnessWebSocketRequest = typeof HarnessWebSocketRequest.Type;
|
||||
|
||||
export const HarnessConnectorWebSocketRequest = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
body: HarnessConnectorRequestBody,
|
||||
});
|
||||
export type HarnessConnectorWebSocketRequest = typeof HarnessConnectorWebSocketRequest.Type;
|
||||
|
||||
export const HarnessWebSocketResponse = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
result: Schema.optional(
|
||||
Schema.Union([
|
||||
Schema.Array(HarnessProfile),
|
||||
Schema.Array(HarnessSession),
|
||||
HarnessSnapshot,
|
||||
Schema.Array(HarnessEvent),
|
||||
Schema.Array(HarnessNativeFrame),
|
||||
Schema.Boolean,
|
||||
HarnessSession,
|
||||
HarnessProfile,
|
||||
]),
|
||||
),
|
||||
error: Schema.optional(
|
||||
Schema.Struct({
|
||||
message: Schema.String,
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type HarnessWebSocketResponse = typeof HarnessWebSocketResponse.Type;
|
||||
|
||||
export const HarnessWsPush = Schema.Struct({
|
||||
type: Schema.Literal("push"),
|
||||
channel: TrimmedNonEmptyString,
|
||||
data: Schema.Union([HarnessEvent, HarnessSnapshot, HarnessSession, HarnessQuestion]),
|
||||
});
|
||||
export type HarnessWsPush = typeof HarnessWsPush.Type;
|
||||
@@ -11,3 +11,6 @@ export * from "./git";
|
||||
export * from "./orchestration";
|
||||
export * from "./editor";
|
||||
export * from "./project";
|
||||
export * from "./harness";
|
||||
export * from "./harnessEvents";
|
||||
export * from "./harnessWs";
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "@t3tools/harness-ws-server",
|
||||
"version": "0.0.0-alpha.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
},
|
||||
"./adapters": {
|
||||
"types": "./src/adapters.ts",
|
||||
"import": "./src/adapters.ts"
|
||||
},
|
||||
"./connector": {
|
||||
"types": "./src/connector.ts",
|
||||
"import": "./src/connector.ts"
|
||||
},
|
||||
"./storage": {
|
||||
"types": "./src/storage.ts",
|
||||
"import": "./src/storage.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import type {
|
||||
HarnessCapabilitySet,
|
||||
HarnessConnectionMode,
|
||||
HarnessEvent,
|
||||
HarnessKind,
|
||||
HarnessProfile,
|
||||
HarnessSession,
|
||||
HarnessSessionId,
|
||||
HarnessPermissionDecision,
|
||||
RuntimeRequestId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export type HarnessAdapterFamily = "process" | "sdk" | "bridge";
|
||||
|
||||
export interface HarnessCreateSessionInput {
|
||||
readonly profile: HarnessProfile;
|
||||
readonly title?: string;
|
||||
}
|
||||
|
||||
export interface HarnessResumeSessionInput {
|
||||
readonly session: HarnessSession;
|
||||
}
|
||||
|
||||
export interface HarnessSendTurnInput {
|
||||
readonly session: HarnessSession;
|
||||
readonly input?: string;
|
||||
readonly model?: string;
|
||||
readonly mode?: string;
|
||||
}
|
||||
|
||||
export interface HarnessCancelTurnInput {
|
||||
readonly session: HarnessSession;
|
||||
readonly turnId?: TurnId;
|
||||
}
|
||||
|
||||
export interface HarnessResolvePermissionInput {
|
||||
readonly session: HarnessSession;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly decision: HarnessPermissionDecision;
|
||||
}
|
||||
|
||||
export interface HarnessResolveElicitationInput {
|
||||
readonly session: HarnessSession;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly answers: ReadonlyArray<ReadonlyArray<string>>;
|
||||
}
|
||||
|
||||
export interface HarnessUpdateSessionConfigInput {
|
||||
readonly session: HarnessSession;
|
||||
readonly title?: string;
|
||||
readonly model?: string;
|
||||
readonly mode?: string;
|
||||
}
|
||||
|
||||
export interface HarnessShutdownSessionInput {
|
||||
readonly session: HarnessSession;
|
||||
}
|
||||
|
||||
export interface HarnessEventStreamInput {
|
||||
readonly session: HarnessSession;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface HarnessAdapter {
|
||||
readonly key: string;
|
||||
readonly harness: HarnessKind;
|
||||
readonly family: HarnessAdapterFamily;
|
||||
readonly defaultConnectionMode: HarnessConnectionMode;
|
||||
readonly capabilities: HarnessCapabilitySet;
|
||||
validateProfile(profile: HarnessProfile): void;
|
||||
createSession(input: HarnessCreateSessionInput): Promise<HarnessSession>;
|
||||
resumeSession(input: HarnessResumeSessionInput): Promise<HarnessSession>;
|
||||
sendTurn(input: HarnessSendTurnInput): Promise<void>;
|
||||
cancelTurn(input: HarnessCancelTurnInput): Promise<void>;
|
||||
resolvePermission(input: HarnessResolvePermissionInput): Promise<void>;
|
||||
resolveElicitation(input: HarnessResolveElicitationInput): Promise<void>;
|
||||
updateSessionConfig(input: HarnessUpdateSessionConfigInput): Promise<void>;
|
||||
shutdownSession(input: HarnessShutdownSessionInput): Promise<void>;
|
||||
streamEvents?(input: HarnessEventStreamInput): AsyncIterable<HarnessEvent>;
|
||||
}
|
||||
|
||||
export class HarnessAdapterError extends Error {
|
||||
constructor(message: string, readonly details?: unknown) {
|
||||
super(message);
|
||||
this.name = "HarnessAdapterError";
|
||||
}
|
||||
}
|
||||
|
||||
export function assertHarness(profile: HarnessProfile, expected: HarnessKind): void {
|
||||
if (profile.harness !== expected) {
|
||||
throw new HarnessAdapterError(
|
||||
`Expected profile '${profile.id}' to target '${expected}', received '${profile.harness}'.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSessionHarness(session: HarnessSession, expected: HarnessKind): void {
|
||||
if (session.harness !== expected) {
|
||||
throw new HarnessAdapterError(
|
||||
`Expected session '${session.id}' to target '${expected}', received '${session.harness}'.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function hasSessionId(
|
||||
sessionId: HarnessSessionId,
|
||||
events: ReadonlyArray<HarnessEvent>,
|
||||
): boolean {
|
||||
return events.some((event) => event.sessionId === sessionId);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EventId, HarnessSessionId } from "@t3tools/contracts";
|
||||
import { createClaudeAgentSdkAdapter } from "./claude";
|
||||
|
||||
describe("createClaudeAgentSdkAdapter", () => {
|
||||
it("wraps SDK-native events into harness-scoped events", async () => {
|
||||
const adapter = createClaudeAgentSdkAdapter({
|
||||
sdk: {
|
||||
async createSession() {
|
||||
return { sessionId: "claude-session" };
|
||||
},
|
||||
async resumeSession() {},
|
||||
async sendTurn() {
|
||||
return {};
|
||||
},
|
||||
async cancelTurn() {},
|
||||
async resolvePermission() {},
|
||||
async resolveElicitation() {},
|
||||
async updateSessionConfig() {},
|
||||
async shutdownSession() {},
|
||||
async *streamEvents() {
|
||||
yield {
|
||||
eventId: EventId.makeUnsafe("evt-1"),
|
||||
sessionId: HarnessSessionId.makeUnsafe("claude-session"),
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
sequence: 1,
|
||||
type: "message.delta",
|
||||
payload: { role: "assistant", stream: "assistant", delta: "hello" },
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const session = await adapter.createSession({
|
||||
profile: {
|
||||
id: "profile-1" as never,
|
||||
name: "Claude",
|
||||
harness: "claude-agent-sdk",
|
||||
adapterFamily: "sdk",
|
||||
connectionMode: "spawned",
|
||||
enabled: true,
|
||||
config: { claudeAgentSdk: {} },
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
updatedAt: "2026-03-09T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
const events: string[] = [];
|
||||
for await (const event of adapter.streamEvents!({ session })) {
|
||||
events.push(event.harness);
|
||||
}
|
||||
|
||||
expect(events).toEqual(["claude-agent-sdk"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import type {
|
||||
HarnessCapabilitySet,
|
||||
HarnessEvent,
|
||||
HarnessProfile,
|
||||
HarnessSession,
|
||||
HarnessSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { HarnessSessionId as HarnessSessionIdSchema } from "@t3tools/contracts";
|
||||
import {
|
||||
type HarnessAdapter,
|
||||
HarnessAdapterError,
|
||||
type HarnessCancelTurnInput,
|
||||
type HarnessCreateSessionInput,
|
||||
type HarnessEventStreamInput,
|
||||
type HarnessResolveElicitationInput,
|
||||
type HarnessResolvePermissionInput,
|
||||
type HarnessResumeSessionInput,
|
||||
type HarnessSendTurnInput,
|
||||
type HarnessShutdownSessionInput,
|
||||
type HarnessUpdateSessionConfigInput,
|
||||
assertHarness,
|
||||
} from "./adapters";
|
||||
|
||||
export const CLAUDE_HARNESS_CAPABILITIES: HarnessCapabilitySet = {
|
||||
resume: true,
|
||||
cancel: true,
|
||||
modelSwitch: "restart-required",
|
||||
permissions: true,
|
||||
elicitation: true,
|
||||
toolLifecycle: true,
|
||||
reasoningStream: true,
|
||||
planStream: true,
|
||||
fileArtifacts: true,
|
||||
checkpoints: false,
|
||||
subagents: true,
|
||||
};
|
||||
|
||||
export type ClaudeAgentSdkEvent = Omit<HarnessEvent, "harness" | "adapterKey" | "connectionMode">;
|
||||
|
||||
export interface ClaudeAgentSdkLike {
|
||||
createSession(input: HarnessCreateSessionInput): Promise<{ sessionId: string; title?: string }>;
|
||||
resumeSession(input: HarnessResumeSessionInput): Promise<void>;
|
||||
sendTurn(input: HarnessSendTurnInput): Promise<{ turnId?: string }>;
|
||||
cancelTurn(input: HarnessCancelTurnInput): Promise<void>;
|
||||
resolvePermission(input: HarnessResolvePermissionInput): Promise<void>;
|
||||
resolveElicitation(input: HarnessResolveElicitationInput): Promise<void>;
|
||||
updateSessionConfig(input: HarnessUpdateSessionConfigInput): Promise<void>;
|
||||
shutdownSession(input: HarnessShutdownSessionInput): Promise<void>;
|
||||
streamEvents(input: HarnessEventStreamInput): AsyncIterable<ClaudeAgentSdkEvent>;
|
||||
}
|
||||
|
||||
export interface ClaudeHarnessAdapterOptions {
|
||||
readonly sdk: ClaudeAgentSdkLike;
|
||||
readonly adapterKey?: string;
|
||||
}
|
||||
|
||||
function toHarnessSession(
|
||||
input: HarnessCreateSessionInput,
|
||||
sessionId: string,
|
||||
adapterKey: string,
|
||||
title?: string,
|
||||
): HarnessSession {
|
||||
return {
|
||||
id: HarnessSessionIdSchema.makeUnsafe(sessionId),
|
||||
profileId: input.profile.id,
|
||||
harness: "claude-agent-sdk",
|
||||
adapterKey,
|
||||
connectionMode: input.profile.connectionMode,
|
||||
title: title ?? input.title ?? null,
|
||||
cwd: input.profile.config.claudeAgentSdk?.cwd ?? null,
|
||||
model: null,
|
||||
mode: input.profile.config.claudeAgentSdk?.sessionMode ?? null,
|
||||
state: "starting",
|
||||
activeTurnId: null,
|
||||
nativeSessionId: sessionId,
|
||||
lastError: null,
|
||||
capabilities: CLAUDE_HARNESS_CAPABILITIES,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export function createClaudeAgentSdkAdapter(
|
||||
options: ClaudeHarnessAdapterOptions,
|
||||
): HarnessAdapter {
|
||||
const adapterKey = options.adapterKey ?? "claude-agent-sdk";
|
||||
return {
|
||||
key: adapterKey,
|
||||
harness: "claude-agent-sdk",
|
||||
family: "sdk",
|
||||
defaultConnectionMode: "spawned",
|
||||
capabilities: CLAUDE_HARNESS_CAPABILITIES,
|
||||
validateProfile(profile: HarnessProfile) {
|
||||
assertHarness(profile, "claude-agent-sdk");
|
||||
},
|
||||
async createSession(input) {
|
||||
this.validateProfile(input.profile);
|
||||
const created = await options.sdk.createSession(input);
|
||||
return toHarnessSession(input, created.sessionId, adapterKey, created.title);
|
||||
},
|
||||
async resumeSession(input) {
|
||||
await options.sdk.resumeSession(input);
|
||||
return input.session;
|
||||
},
|
||||
async sendTurn(input) {
|
||||
await options.sdk.sendTurn(input);
|
||||
},
|
||||
resolvePermission(input) {
|
||||
return options.sdk.resolvePermission(input);
|
||||
},
|
||||
resolveElicitation(input) {
|
||||
return options.sdk.resolveElicitation(input);
|
||||
},
|
||||
cancelTurn(input) {
|
||||
return options.sdk.cancelTurn(input);
|
||||
},
|
||||
updateSessionConfig(input) {
|
||||
return options.sdk.updateSessionConfig(input);
|
||||
},
|
||||
shutdownSession(input) {
|
||||
return options.sdk.shutdownSession(input);
|
||||
},
|
||||
async *streamEvents(input) {
|
||||
for await (const event of options.sdk.streamEvents(input)) {
|
||||
yield {
|
||||
...event,
|
||||
harness: "claude-agent-sdk",
|
||||
adapterKey,
|
||||
connectionMode: input.session.connectionMode,
|
||||
} as HarnessEvent;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function assertClaudeSessionId(value: string | HarnessSessionId): HarnessSessionId {
|
||||
if (typeof value !== "string") {
|
||||
return value;
|
||||
}
|
||||
if (value.trim().length === 0) {
|
||||
throw new HarnessAdapterError("Claude session id must be non-empty.");
|
||||
}
|
||||
return HarnessSessionIdSchema.makeUnsafe(value);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { EventId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { mapCodexProviderRuntimeEventToHarnessEvents } from "./codex";
|
||||
|
||||
describe("mapCodexProviderRuntimeEventToHarnessEvents", () => {
|
||||
it("maps plan and elicitation flows into canonical harness events", () => {
|
||||
const planEvent = {
|
||||
type: "turn.plan.updated",
|
||||
eventId: EventId.makeUnsafe("evt-plan"),
|
||||
provider: "codex",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
payload: {
|
||||
explanation: "Thinking through the steps",
|
||||
plan: [{ step: "Inspect repo", status: "completed" }],
|
||||
},
|
||||
} as unknown as ProviderRuntimeEvent;
|
||||
|
||||
const mapped = mapCodexProviderRuntimeEventToHarnessEvents(planEvent);
|
||||
expect(mapped[0]?.type).toBe("plan.updated");
|
||||
if (mapped[0]?.type === "plan.updated") {
|
||||
expect(mapped[0].payload.steps[0]?.status).toBe("completed");
|
||||
}
|
||||
});
|
||||
|
||||
it("maps runtime request events into canonical permissions", () => {
|
||||
const requestEvent = {
|
||||
type: "request.opened",
|
||||
eventId: EventId.makeUnsafe("evt-permission"),
|
||||
provider: "codex",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
payload: {
|
||||
requestType: "exec_command_approval",
|
||||
detail: "Run bun lint",
|
||||
},
|
||||
requestId: "req-1",
|
||||
} as unknown as ProviderRuntimeEvent;
|
||||
|
||||
const mapped = mapCodexProviderRuntimeEventToHarnessEvents(requestEvent);
|
||||
expect(mapped[0]?.type).toBe("permission.requested");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,434 @@
|
||||
import type { HarnessCapabilitySet, HarnessEvent, ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { HarnessSessionId, RuntimeItemId, RuntimeRequestId, TurnId } from "@t3tools/contracts";
|
||||
|
||||
export const CODEX_HARNESS_CAPABILITIES: HarnessCapabilitySet = {
|
||||
resume: true,
|
||||
cancel: true,
|
||||
modelSwitch: "restart-required",
|
||||
permissions: true,
|
||||
elicitation: true,
|
||||
toolLifecycle: true,
|
||||
reasoningStream: true,
|
||||
planStream: true,
|
||||
fileArtifacts: true,
|
||||
checkpoints: true,
|
||||
subagents: true,
|
||||
};
|
||||
|
||||
interface CodexMapOptions {
|
||||
readonly sequenceStart?: number;
|
||||
readonly adapterKey?: string;
|
||||
}
|
||||
|
||||
type RuntimePlanStep = Extract<
|
||||
ProviderRuntimeEvent,
|
||||
{ readonly type: "turn.plan.updated" }
|
||||
>["payload"]["plan"][number];
|
||||
type RuntimeQuestion = Extract<
|
||||
ProviderRuntimeEvent,
|
||||
{ readonly type: "user-input.requested" }
|
||||
>["payload"]["questions"][number];
|
||||
type PersistedFile = Extract<
|
||||
ProviderRuntimeEvent,
|
||||
{ readonly type: "files.persisted" }
|
||||
>["payload"]["files"][number];
|
||||
|
||||
function harnessSessionIdFromRuntimeEvent(event: ProviderRuntimeEvent) {
|
||||
return HarnessSessionId.makeUnsafe(String(event.threadId));
|
||||
}
|
||||
|
||||
function itemIdFromRuntimeEvent(event: ProviderRuntimeEvent): RuntimeItemId | undefined {
|
||||
return event.itemId ? RuntimeItemId.makeUnsafe(String(event.itemId)) : undefined;
|
||||
}
|
||||
|
||||
function turnIdFromRuntimeEvent(event: ProviderRuntimeEvent): TurnId | undefined {
|
||||
return event.turnId ? TurnId.makeUnsafe(String(event.turnId)) : undefined;
|
||||
}
|
||||
|
||||
function requestIdFromRuntimeEvent(event: ProviderRuntimeEvent): RuntimeRequestId | undefined {
|
||||
return event.requestId ? RuntimeRequestId.makeUnsafe(String(event.requestId)) : undefined;
|
||||
}
|
||||
|
||||
function eventBase(
|
||||
event: ProviderRuntimeEvent,
|
||||
sequence: number,
|
||||
adapterKey: string,
|
||||
): Omit<HarnessEvent, "type" | "payload"> {
|
||||
return {
|
||||
eventId: event.eventId,
|
||||
sessionId: harnessSessionIdFromRuntimeEvent(event),
|
||||
createdAt: event.createdAt,
|
||||
sequence,
|
||||
harness: "codex-app-server",
|
||||
adapterKey,
|
||||
connectionMode: "spawned",
|
||||
...(event.turnId ? { turnId: turnIdFromRuntimeEvent(event) } : {}),
|
||||
...(event.itemId ? { itemId: itemIdFromRuntimeEvent(event) } : {}),
|
||||
...(event.raw ? { nativeRefs: { source: event.raw.source } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function withNativeFrame(
|
||||
event: ProviderRuntimeEvent,
|
||||
sequence: number,
|
||||
adapterKey: string,
|
||||
): HarnessEvent | undefined {
|
||||
if (!event.raw) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
...eventBase(event, sequence, adapterKey),
|
||||
type: "native.frame",
|
||||
payload: {
|
||||
source: event.raw.source,
|
||||
payload: event.raw.payload,
|
||||
},
|
||||
} as HarnessEvent;
|
||||
}
|
||||
|
||||
export function mapCodexProviderRuntimeEventToHarnessEvents(
|
||||
event: ProviderRuntimeEvent,
|
||||
options?: CodexMapOptions,
|
||||
): ReadonlyArray<HarnessEvent> {
|
||||
const start = options?.sequenceStart ?? 1;
|
||||
const adapterKey = options?.adapterKey ?? "codex-runtime-compat";
|
||||
let nextSequence = start;
|
||||
const events: HarnessEvent[] = [];
|
||||
const push = (mapped: HarnessEvent | undefined) => {
|
||||
if (mapped) {
|
||||
events.push(mapped);
|
||||
nextSequence += 1;
|
||||
}
|
||||
};
|
||||
|
||||
switch (event.type) {
|
||||
case "session.started":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "session.created",
|
||||
payload: {
|
||||
state: "starting",
|
||||
capabilities: CODEX_HARNESS_CAPABILITIES,
|
||||
...(event.payload.message ? { title: event.payload.message } : {}),
|
||||
...(event.payload.resume !== undefined ? { metadata: { resume: event.payload.resume } } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "session.configured":
|
||||
{
|
||||
const config = event.payload.config as Record<string, unknown>;
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "session.config.changed",
|
||||
payload: {
|
||||
...(typeof config.cwd === "string" ? { cwd: config.cwd } : {}),
|
||||
...(typeof config.model === "string" ? { model: config.model } : {}),
|
||||
...(typeof config.mode === "string" ? { mode: config.mode } : {}),
|
||||
metadata: config,
|
||||
},
|
||||
} as HarnessEvent);
|
||||
}
|
||||
break;
|
||||
|
||||
case "session.state.changed":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "session.state.changed",
|
||||
payload: {
|
||||
state:
|
||||
event.payload.state === "waiting"
|
||||
? "waiting"
|
||||
: event.payload.state === "running"
|
||||
? "running"
|
||||
: event.payload.state === "starting"
|
||||
? "starting"
|
||||
: event.payload.state === "error"
|
||||
? "error"
|
||||
: event.payload.state === "stopped"
|
||||
? "stopped"
|
||||
: "ready",
|
||||
...(event.payload.reason ? { reason: event.payload.reason } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "session.exited":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "session.exited",
|
||||
payload: {
|
||||
...(event.payload.reason ? { reason: event.payload.reason } : {}),
|
||||
...(event.payload.recoverable !== undefined
|
||||
? { recoverable: event.payload.recoverable }
|
||||
: {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "turn.started":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "turn.started",
|
||||
payload: event.payload.model ? { model: event.payload.model } : {},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "turn.completed": {
|
||||
const state = event.payload.state;
|
||||
if (state === "failed") {
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "turn.failed",
|
||||
payload: {
|
||||
message: event.payload.errorMessage ?? "Codex turn failed",
|
||||
...(event.payload.usage !== undefined ? { detail: event.payload.usage } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
} else if (state === "cancelled") {
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "turn.cancelled",
|
||||
payload: event.payload.stopReason ? { reason: event.payload.stopReason } : {},
|
||||
} as HarnessEvent);
|
||||
} else {
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
...(event.payload.stopReason ? { stopReason: event.payload.stopReason } : {}),
|
||||
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "turn.plan.updated":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "plan.updated",
|
||||
payload: {
|
||||
...(event.payload.explanation ? { explanation: event.payload.explanation } : {}),
|
||||
steps: event.payload.plan.map((step: RuntimePlanStep) => ({
|
||||
step: step.step,
|
||||
status:
|
||||
step.status === "inProgress"
|
||||
? "in-progress"
|
||||
: step.status === "completed"
|
||||
? "completed"
|
||||
: "pending",
|
||||
})),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "turn.proposed.delta":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "plan.delta",
|
||||
payload: {
|
||||
delta: event.payload.delta,
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "turn.proposed.completed":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "plan.completed",
|
||||
payload: {
|
||||
planMarkdown: event.payload.planMarkdown,
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "content.delta":
|
||||
if (event.payload.streamKind === "assistant_text") {
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "message.delta",
|
||||
payload: {
|
||||
role: "assistant",
|
||||
stream: "assistant",
|
||||
delta: event.payload.delta,
|
||||
},
|
||||
} as HarnessEvent);
|
||||
} else if (event.payload.streamKind === "reasoning_text") {
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "reasoning.delta",
|
||||
payload: {
|
||||
delta: event.payload.delta,
|
||||
},
|
||||
} as HarnessEvent);
|
||||
} else if (event.payload.streamKind === "reasoning_summary_text") {
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "reasoning.summary",
|
||||
payload: {
|
||||
text: event.payload.delta.trim() || "Reasoning summary",
|
||||
},
|
||||
} as HarnessEvent);
|
||||
} else if (event.payload.streamKind === "plan_text") {
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "plan.delta",
|
||||
payload: {
|
||||
delta: event.payload.delta,
|
||||
},
|
||||
} as HarnessEvent);
|
||||
}
|
||||
break;
|
||||
|
||||
case "item.started":
|
||||
case "item.updated":
|
||||
case "item.completed":
|
||||
push({
|
||||
...eventBase(
|
||||
event,
|
||||
nextSequence,
|
||||
adapterKey,
|
||||
),
|
||||
type:
|
||||
event.type === "item.started"
|
||||
? "item.started"
|
||||
: event.type === "item.updated"
|
||||
? "item.updated"
|
||||
: "item.completed",
|
||||
payload: {
|
||||
itemType: event.payload.itemType,
|
||||
...(event.payload.title ? { title: event.payload.title } : {}),
|
||||
...(event.payload.detail ? { detail: event.payload.detail } : {}),
|
||||
...(event.payload.status ? { status: event.payload.status } : {}),
|
||||
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "request.opened": {
|
||||
const requestId = requestIdFromRuntimeEvent(event);
|
||||
if (!requestId) break;
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "permission.requested",
|
||||
payload: {
|
||||
requestId,
|
||||
kind:
|
||||
event.payload.requestType === "file_read_approval"
|
||||
? "file-read"
|
||||
: event.payload.requestType === "file_change_approval" ||
|
||||
event.payload.requestType === "apply_patch_approval"
|
||||
? "file-change"
|
||||
: event.payload.requestType === "exec_command_approval" ||
|
||||
event.payload.requestType === "command_execution_approval"
|
||||
? "exec"
|
||||
: "other",
|
||||
title: event.payload.detail ?? event.payload.requestType,
|
||||
...(event.payload.detail ? { detail: event.payload.detail } : {}),
|
||||
...(event.payload.args !== undefined ? { args: event.payload.args } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
}
|
||||
|
||||
case "request.resolved": {
|
||||
const requestId = requestIdFromRuntimeEvent(event);
|
||||
if (!requestId) break;
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "permission.resolved",
|
||||
payload: {
|
||||
requestId,
|
||||
decision:
|
||||
event.payload.decision === "acceptForSession"
|
||||
? "accept-for-session"
|
||||
: event.payload.decision === "accept"
|
||||
? "accept"
|
||||
: event.payload.decision === "cancel"
|
||||
? "cancel"
|
||||
: "decline",
|
||||
...(event.payload.decision ? { detail: event.payload.decision } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
}
|
||||
|
||||
case "user-input.requested": {
|
||||
const requestId = requestIdFromRuntimeEvent(event);
|
||||
if (!requestId) break;
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "elicitation.requested",
|
||||
payload: {
|
||||
requestId,
|
||||
questions: event.payload.questions.map((question: RuntimeQuestion) => ({
|
||||
id: question.id,
|
||||
header: question.header,
|
||||
question: question.question,
|
||||
options: question.options,
|
||||
})),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
}
|
||||
|
||||
case "user-input.resolved": {
|
||||
const requestId = requestIdFromRuntimeEvent(event);
|
||||
if (!requestId) break;
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "elicitation.resolved",
|
||||
payload: {
|
||||
requestId,
|
||||
answers: Object.values(event.payload.answers).map((value) =>
|
||||
Array.isArray(value) ? value.map(String) : [String(value)],
|
||||
),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
}
|
||||
|
||||
case "files.persisted":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "artifact.persisted",
|
||||
payload: {
|
||||
files: event.payload.files.map((file: PersistedFile) => ({
|
||||
id: file.fileId,
|
||||
path: file.filename,
|
||||
kind: "file",
|
||||
})),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "runtime.warning":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "transport.warning",
|
||||
payload: {
|
||||
message: event.payload.message,
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
case "runtime.error":
|
||||
push({
|
||||
...eventBase(event, nextSequence, adapterKey),
|
||||
type: "transport.error",
|
||||
payload: {
|
||||
message: event.payload.message,
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
} as HarnessEvent);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
push(withNativeFrame(event, nextSequence, adapterKey));
|
||||
return events;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { HarnessConnectorId, HarnessProfileId } from "@t3tools/contracts";
|
||||
|
||||
export interface ConnectorRegistration {
|
||||
readonly connectorId: HarnessConnectorId;
|
||||
readonly profileId?: HarnessProfileId;
|
||||
readonly description?: string;
|
||||
readonly version?: string;
|
||||
}
|
||||
|
||||
export function createConnectorAuthHeaders(token: string): Record<string, string> {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export * from "./adapters";
|
||||
export * from "./claude";
|
||||
export * from "./codex";
|
||||
export * from "./connector";
|
||||
export * from "./projector";
|
||||
export * from "./server";
|
||||
export * from "./storage";
|
||||
export * from "./opencode";
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createOpenCodeHarnessAdapter } from "./opencode";
|
||||
|
||||
describe("createOpenCodeHarnessAdapter", () => {
|
||||
it("requires a baseUrl in the profile config", () => {
|
||||
const adapter = createOpenCodeHarnessAdapter();
|
||||
expect(() =>
|
||||
adapter.validateProfile({
|
||||
id: "profile-1" as never,
|
||||
name: "OpenCode",
|
||||
harness: "opencode",
|
||||
adapterFamily: "process",
|
||||
connectionMode: "spawned",
|
||||
enabled: true,
|
||||
config: {
|
||||
opencode: {},
|
||||
},
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
updatedAt: "2026-03-09T00:00:00.000Z",
|
||||
}),
|
||||
).toThrow(/baseUrl/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,441 @@
|
||||
import type {
|
||||
EventId,
|
||||
HarnessCapabilitySet,
|
||||
HarnessEvent,
|
||||
HarnessNativeFrame,
|
||||
HarnessProfile,
|
||||
HarnessSession,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
EventId as EventIdSchema,
|
||||
HarnessSessionId,
|
||||
RuntimeRequestId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
type HarnessAdapter,
|
||||
HarnessAdapterError,
|
||||
assertHarness,
|
||||
assertSessionHarness,
|
||||
} from "./adapters";
|
||||
|
||||
export const OPENCODE_HARNESS_CAPABILITIES: HarnessCapabilitySet = {
|
||||
resume: true,
|
||||
cancel: true,
|
||||
modelSwitch: "restart-required",
|
||||
permissions: true,
|
||||
elicitation: true,
|
||||
toolLifecycle: true,
|
||||
reasoningStream: false,
|
||||
planStream: true,
|
||||
fileArtifacts: true,
|
||||
checkpoints: false,
|
||||
subagents: true,
|
||||
};
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
interface OpenCodeSessionInfo {
|
||||
readonly id: string;
|
||||
readonly title?: string;
|
||||
}
|
||||
|
||||
interface OpenCodeSseEvent {
|
||||
readonly type: string;
|
||||
readonly properties: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface OpenCodeQuestionEvent {
|
||||
readonly id?: string;
|
||||
readonly header?: string;
|
||||
readonly question?: string;
|
||||
readonly options?: ReadonlyArray<{
|
||||
readonly label?: string;
|
||||
readonly description?: string;
|
||||
}>;
|
||||
readonly multiple?: boolean;
|
||||
readonly custom?: boolean;
|
||||
}
|
||||
|
||||
export interface OpenCodeHarnessAdapterOptions {
|
||||
readonly fetch?: FetchLike;
|
||||
readonly adapterKey?: string;
|
||||
}
|
||||
|
||||
function trim(value: string | undefined | null): string | undefined {
|
||||
const next = value?.trim();
|
||||
return next ? next : undefined;
|
||||
}
|
||||
|
||||
function makeBasicAuthHeader(username: string, password: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
|
||||
}
|
||||
|
||||
function requireBaseUrl(profile: HarnessProfile): string {
|
||||
const baseUrl = trim(profile.config.opencode?.baseUrl);
|
||||
if (!baseUrl) {
|
||||
throw new HarnessAdapterError(
|
||||
`OpenCode profile '${profile.id}' requires 'config.opencode.baseUrl'.`,
|
||||
);
|
||||
}
|
||||
return baseUrl.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function buildHeaders(profile: HarnessProfile): HeadersInit {
|
||||
const username = trim(profile.config.opencode?.username);
|
||||
const password = trim(profile.config.opencode?.password);
|
||||
if (username && password) {
|
||||
return {
|
||||
Authorization: makeBasicAuthHeader(username, password),
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
function makeEventId(session: HarnessSession, sequence: number): EventId {
|
||||
return EventIdSchema.makeUnsafe(`opencode:${session.id}:${sequence}`);
|
||||
}
|
||||
|
||||
function getSessionBaseUrl(session: HarnessSession): string {
|
||||
const baseUrl = trim(session.metadata?.baseUrl as string | undefined);
|
||||
if (!baseUrl) {
|
||||
throw new HarnessAdapterError("OpenCode session metadata is missing baseUrl.");
|
||||
}
|
||||
return baseUrl.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
async function decodeJson<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
throw new HarnessAdapterError(`OpenCode request failed with status ${response.status}.`, {
|
||||
status: response.status,
|
||||
text: await response.text(),
|
||||
});
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
async function* parseSseEvents(
|
||||
response: Response,
|
||||
session: HarnessSession,
|
||||
adapterKey: string,
|
||||
): AsyncIterable<HarnessEvent> {
|
||||
if (!response.body) {
|
||||
return;
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let sequence = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const frames = buffer.split("\n\n");
|
||||
buffer = frames.pop() ?? "";
|
||||
|
||||
for (const frame of frames) {
|
||||
const dataLine = frame
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith("data:"));
|
||||
if (!dataLine) {
|
||||
continue;
|
||||
}
|
||||
const json = dataLine.slice("data:".length).trim();
|
||||
if (!json) {
|
||||
continue;
|
||||
}
|
||||
const event = JSON.parse(json) as OpenCodeSseEvent;
|
||||
sequence += 1;
|
||||
const base: Omit<HarnessEvent, "payload"> = {
|
||||
eventId: makeEventId(session, sequence),
|
||||
sessionId: session.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
sequence,
|
||||
harness: "opencode",
|
||||
adapterKey,
|
||||
connectionMode: session.connectionMode,
|
||||
type: "native.frame",
|
||||
} as Omit<HarnessEvent, "payload">;
|
||||
|
||||
if (event.type === "permission.asked") {
|
||||
yield {
|
||||
...base,
|
||||
type: "permission.requested",
|
||||
payload: {
|
||||
requestId: RuntimeRequestId.makeUnsafe(String(event.properties.id)),
|
||||
kind: "other",
|
||||
title: String(
|
||||
event.properties.message ?? event.properties.permission ?? "Permission requested",
|
||||
),
|
||||
...(event.properties.message ? { detail: String(event.properties.message) } : {}),
|
||||
args: event.properties.metadata,
|
||||
},
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.type === "permission.replied") {
|
||||
yield {
|
||||
...base,
|
||||
type: "permission.resolved",
|
||||
payload: {
|
||||
requestId: RuntimeRequestId.makeUnsafe(String(event.properties.requestID)),
|
||||
decision:
|
||||
event.properties.reply === "always"
|
||||
? "accept-for-session"
|
||||
: event.properties.reply === "once"
|
||||
? "accept"
|
||||
: "decline",
|
||||
},
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.type === "question.asked") {
|
||||
yield {
|
||||
...base,
|
||||
type: "elicitation.requested",
|
||||
payload: {
|
||||
requestId: RuntimeRequestId.makeUnsafe(String(event.properties.id)),
|
||||
questions: Array.isArray(event.properties.questions)
|
||||
? event.properties.questions.map((question) => {
|
||||
const typedQuestion = question as OpenCodeQuestionEvent;
|
||||
return {
|
||||
id: String(typedQuestion.id ?? typedQuestion.header ?? "question"),
|
||||
header: String(typedQuestion.header ?? "Question"),
|
||||
question: String(typedQuestion.question ?? ""),
|
||||
options: Array.isArray(typedQuestion.options)
|
||||
? typedQuestion.options.map((option) => ({
|
||||
label: String(option.label ?? ""),
|
||||
description: String(option.description ?? ""),
|
||||
}))
|
||||
: [],
|
||||
...(typedQuestion.multiple !== undefined
|
||||
? { multiple: Boolean(typedQuestion.multiple) }
|
||||
: {}),
|
||||
...(typedQuestion.custom !== undefined
|
||||
? { custom: Boolean(typedQuestion.custom) }
|
||||
: {}),
|
||||
};
|
||||
})
|
||||
: [],
|
||||
},
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.type === "question.replied" || event.type === "question.rejected") {
|
||||
yield {
|
||||
...base,
|
||||
type: "elicitation.resolved",
|
||||
payload: {
|
||||
requestId: RuntimeRequestId.makeUnsafe(String(event.properties.requestID)),
|
||||
answers: Array.isArray(event.properties.answers)
|
||||
? event.properties.answers.map((answer) =>
|
||||
Array.isArray(answer) ? answer.map(String) : [String(answer)],
|
||||
)
|
||||
: [],
|
||||
},
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.type === "session.status") {
|
||||
const statusType = String((event.properties.status as { type?: string } | undefined)?.type ?? "idle");
|
||||
yield {
|
||||
...base,
|
||||
type: "session.state.changed",
|
||||
payload: {
|
||||
state: statusType === "busy" ? "running" : statusType === "retry" ? "waiting" : "ready",
|
||||
},
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
yield {
|
||||
...base,
|
||||
type: "native.frame",
|
||||
payload: {
|
||||
source: event.type,
|
||||
payload: event.properties,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toHarnessSession(profile: HarnessProfile, session: OpenCodeSessionInfo): HarnessSession {
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
id: HarnessSessionId.makeUnsafe(session.id),
|
||||
profileId: profile.id,
|
||||
harness: "opencode",
|
||||
adapterKey: "opencode-direct",
|
||||
connectionMode: profile.connectionMode,
|
||||
title: session.title ?? null,
|
||||
cwd: profile.config.opencode?.directory ?? null,
|
||||
model: null,
|
||||
mode: null,
|
||||
state: "ready",
|
||||
activeTurnId: null,
|
||||
nativeSessionId: session.id,
|
||||
lastError: null,
|
||||
capabilities: OPENCODE_HARNESS_CAPABILITIES,
|
||||
metadata: {
|
||||
baseUrl: requireBaseUrl(profile),
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
export function createOpenCodeHarnessAdapter(
|
||||
options?: OpenCodeHarnessAdapterOptions,
|
||||
): HarnessAdapter {
|
||||
const request = options?.fetch ?? fetch;
|
||||
const adapterKey = options?.adapterKey ?? "opencode-direct";
|
||||
|
||||
return {
|
||||
key: adapterKey,
|
||||
harness: "opencode",
|
||||
family: "process",
|
||||
defaultConnectionMode: "spawned",
|
||||
capabilities: OPENCODE_HARNESS_CAPABILITIES,
|
||||
validateProfile(profile) {
|
||||
assertHarness(profile, "opencode");
|
||||
requireBaseUrl(profile);
|
||||
},
|
||||
async createSession(input) {
|
||||
this.validateProfile(input.profile);
|
||||
const baseUrl = requireBaseUrl(input.profile);
|
||||
const response = await request(`${baseUrl}/session`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...buildHeaders(input.profile),
|
||||
},
|
||||
body: JSON.stringify(
|
||||
input.title ? { title: input.title } : {},
|
||||
),
|
||||
});
|
||||
const created = await decodeJson<OpenCodeSessionInfo>(response);
|
||||
return toHarnessSession(input.profile, created);
|
||||
},
|
||||
async resumeSession(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
return input.session;
|
||||
},
|
||||
async sendTurn(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
const baseUrl = getSessionBaseUrl(input.session);
|
||||
const response = await request(`${baseUrl}/session/${input.session.id}/message`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: input.input ?? "",
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HarnessAdapterError(`OpenCode prompt failed with status ${response.status}.`);
|
||||
}
|
||||
},
|
||||
async cancelTurn(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
const baseUrl = getSessionBaseUrl(input.session);
|
||||
const response = await request(`${baseUrl}/session/${input.session.id}/abort`, {
|
||||
method: "POST",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HarnessAdapterError(`OpenCode abort failed with status ${response.status}.`);
|
||||
}
|
||||
},
|
||||
async resolvePermission(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
const baseUrl = getSessionBaseUrl(input.session);
|
||||
const reply =
|
||||
input.decision === "accept-for-session"
|
||||
? "always"
|
||||
: input.decision === "accept"
|
||||
? "once"
|
||||
: "reject";
|
||||
const response = await request(`${baseUrl}/permission/${input.requestId}/reply`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ reply }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HarnessAdapterError(
|
||||
`OpenCode permission reply failed with status ${response.status}.`,
|
||||
);
|
||||
}
|
||||
},
|
||||
async resolveElicitation(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
const baseUrl = getSessionBaseUrl(input.session);
|
||||
const response = await request(`${baseUrl}/question/${input.requestId}/reply`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ answers: input.answers }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HarnessAdapterError(`OpenCode question reply failed with status ${response.status}.`);
|
||||
}
|
||||
},
|
||||
async updateSessionConfig(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
const baseUrl = getSessionBaseUrl(input.session);
|
||||
const response = await request(`${baseUrl}/session/${input.session.id}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(input.title !== undefined ? { title: input.title } : {}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new HarnessAdapterError(`OpenCode session update failed with status ${response.status}.`);
|
||||
}
|
||||
},
|
||||
async shutdownSession(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
return this.cancelTurn({ session: input.session });
|
||||
},
|
||||
async *streamEvents(input) {
|
||||
assertSessionHarness(input.session, "opencode");
|
||||
const baseUrl = getSessionBaseUrl(input.session);
|
||||
const response = await request(`${baseUrl}/event`, input.signal
|
||||
? {
|
||||
method: "GET",
|
||||
signal: input.signal,
|
||||
}
|
||||
: {
|
||||
method: "GET",
|
||||
});
|
||||
yield* parseSseEvents(response, input.session, adapterKey);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createOpenCodeNativeFrame(
|
||||
session: HarnessSession,
|
||||
source: string,
|
||||
payload: unknown,
|
||||
sequence: number,
|
||||
): HarnessNativeFrame {
|
||||
return {
|
||||
id: EventIdSchema.makeUnsafe(`opencode-frame:${session.id}:${sequence}`),
|
||||
sessionId: session.id,
|
||||
harness: "opencode",
|
||||
adapterKey: session.adapterKey,
|
||||
createdAt: new Date().toISOString(),
|
||||
source,
|
||||
payload,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EventId, HarnessSessionId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { createEmptyHarnessSnapshot, projectHarnessEvent } from "./projector";
|
||||
|
||||
describe("projectHarnessEvent", () => {
|
||||
it("tracks session lifecycle and pending interaction projections", () => {
|
||||
const sessionId = HarnessSessionId.makeUnsafe("session-1");
|
||||
let snapshot = createEmptyHarnessSnapshot("2026-03-09T00:00:00.000Z");
|
||||
|
||||
snapshot = projectHarnessEvent(snapshot, {
|
||||
eventId: EventId.makeUnsafe("evt-session"),
|
||||
sessionId,
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
sequence: 1,
|
||||
harness: "opencode",
|
||||
adapterKey: "opencode-direct",
|
||||
connectionMode: "spawned",
|
||||
type: "session.created",
|
||||
payload: {
|
||||
title: "OpenCode Session",
|
||||
state: "starting",
|
||||
capabilities: {
|
||||
resume: true,
|
||||
cancel: true,
|
||||
modelSwitch: "restart-required",
|
||||
permissions: true,
|
||||
elicitation: true,
|
||||
toolLifecycle: true,
|
||||
reasoningStream: false,
|
||||
planStream: true,
|
||||
fileArtifacts: true,
|
||||
checkpoints: false,
|
||||
subagents: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
snapshot = projectHarnessEvent(snapshot, {
|
||||
eventId: EventId.makeUnsafe("evt-permission"),
|
||||
sessionId,
|
||||
createdAt: "2026-03-09T00:00:01.000Z",
|
||||
sequence: 2,
|
||||
harness: "opencode",
|
||||
adapterKey: "opencode-direct",
|
||||
connectionMode: "spawned",
|
||||
type: "permission.requested",
|
||||
payload: {
|
||||
requestId: RuntimeRequestId.makeUnsafe("perm-1"),
|
||||
kind: "command",
|
||||
title: "Run command",
|
||||
},
|
||||
});
|
||||
|
||||
expect(snapshot.sessions).toHaveLength(1);
|
||||
expect(snapshot.pendingPermissions).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,313 @@
|
||||
import type {
|
||||
HarnessBinding,
|
||||
HarnessConnector,
|
||||
HarnessEvent,
|
||||
HarnessPendingElicitation,
|
||||
HarnessPendingPermission,
|
||||
HarnessSession,
|
||||
HarnessSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { HarnessProfileId } from "@t3tools/contracts";
|
||||
|
||||
function upsertById<T extends { readonly id: string }>(
|
||||
entries: ReadonlyArray<T>,
|
||||
entry: T,
|
||||
): ReadonlyArray<T> {
|
||||
const index = entries.findIndex((existing) => existing.id === entry.id);
|
||||
if (index < 0) {
|
||||
return [...entries, entry];
|
||||
}
|
||||
const next = entries.slice();
|
||||
next[index] = entry;
|
||||
return next;
|
||||
}
|
||||
|
||||
function updateSession(
|
||||
sessions: ReadonlyArray<HarnessSession>,
|
||||
sessionId: string,
|
||||
update: (session: HarnessSession) => HarnessSession,
|
||||
): ReadonlyArray<HarnessSession> {
|
||||
return sessions.map((session) => (session.id === sessionId ? update(session) : session));
|
||||
}
|
||||
|
||||
function removeById<T extends { readonly id: string }>(
|
||||
entries: ReadonlyArray<T>,
|
||||
id: string,
|
||||
): ReadonlyArray<T> {
|
||||
return entries.filter((entry) => entry.id !== id);
|
||||
}
|
||||
|
||||
export function createEmptyHarnessSnapshot(updatedAt: string): HarnessSnapshot {
|
||||
return {
|
||||
sequence: 0,
|
||||
updatedAt,
|
||||
profiles: [],
|
||||
sessions: [],
|
||||
bindings: [],
|
||||
pendingPermissions: [],
|
||||
pendingElicitations: [],
|
||||
connectors: [],
|
||||
};
|
||||
}
|
||||
|
||||
function applyBinding(
|
||||
bindings: ReadonlyArray<HarnessBinding>,
|
||||
binding: HarnessBinding,
|
||||
): ReadonlyArray<HarnessBinding> {
|
||||
const index = bindings.findIndex((existing) => existing.sessionId === binding.sessionId);
|
||||
if (index < 0) {
|
||||
return [...bindings, binding];
|
||||
}
|
||||
const next = bindings.slice();
|
||||
next[index] = binding;
|
||||
return next;
|
||||
}
|
||||
|
||||
function applyConnector(
|
||||
connectors: ReadonlyArray<HarnessConnector>,
|
||||
connector: HarnessConnector,
|
||||
): ReadonlyArray<HarnessConnector> {
|
||||
const index = connectors.findIndex((existing) => existing.id === connector.id);
|
||||
if (index < 0) {
|
||||
return [...connectors, connector];
|
||||
}
|
||||
const next = connectors.slice();
|
||||
next[index] = connector;
|
||||
return next;
|
||||
}
|
||||
|
||||
export function projectHarnessEvent(
|
||||
snapshot: HarnessSnapshot,
|
||||
event: HarnessEvent,
|
||||
): HarnessSnapshot {
|
||||
const nextBase: HarnessSnapshot = {
|
||||
...snapshot,
|
||||
sequence: event.sequence,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
|
||||
switch (event.type) {
|
||||
case "session.created": {
|
||||
const existing = nextBase.sessions.find((session) => session.id === event.sessionId);
|
||||
const session: HarnessSession = existing ?? {
|
||||
id: event.sessionId,
|
||||
profileId:
|
||||
typeof event.payload.profileId === "string"
|
||||
? HarnessProfileId.makeUnsafe(event.payload.profileId)
|
||||
: null,
|
||||
harness: event.harness,
|
||||
adapterKey: event.adapterKey,
|
||||
connectionMode: event.connectionMode,
|
||||
title: event.payload.title ?? null,
|
||||
cwd: event.payload.cwd ?? null,
|
||||
model: event.payload.model ?? null,
|
||||
mode: event.payload.mode ?? null,
|
||||
state: event.payload.state ?? "starting",
|
||||
activeTurnId: null,
|
||||
nativeSessionId: null,
|
||||
lastError: null,
|
||||
capabilities: event.payload.capabilities ?? {
|
||||
resume: false,
|
||||
cancel: false,
|
||||
modelSwitch: "unsupported",
|
||||
permissions: false,
|
||||
elicitation: false,
|
||||
toolLifecycle: false,
|
||||
reasoningStream: false,
|
||||
planStream: false,
|
||||
fileArtifacts: false,
|
||||
checkpoints: false,
|
||||
subagents: false,
|
||||
},
|
||||
...(event.payload.metadata ? { metadata: event.payload.metadata } : {}),
|
||||
createdAt: event.createdAt,
|
||||
updatedAt: event.createdAt,
|
||||
};
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: upsertById(nextBase.sessions, session),
|
||||
};
|
||||
}
|
||||
|
||||
case "session.bound":
|
||||
return {
|
||||
...nextBase,
|
||||
bindings: applyBinding(nextBase.bindings, event.payload.binding),
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
nativeSessionId: event.payload.binding.nativeSessionId ?? session.nativeSessionId,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "session.state.changed":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
state: event.payload.state,
|
||||
lastError:
|
||||
event.payload.state === "error" ? (event.payload.reason ?? session.lastError) : session.lastError,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "session.config.changed":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||
...(event.payload.cwd !== undefined ? { cwd: event.payload.cwd } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.mode !== undefined ? { mode: event.payload.mode } : {}),
|
||||
...(event.payload.metadata !== undefined ? { metadata: event.payload.metadata } : {}),
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "session.capabilities.changed":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
capabilities: event.payload.capabilities,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "session.exited":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
state: event.payload.recoverable === false ? "stopped" : session.state,
|
||||
lastError: event.payload.reason ?? session.lastError,
|
||||
activeTurnId: null,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "turn.started":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
state: "running",
|
||||
activeTurnId: event.turnId ?? session.activeTurnId,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "turn.completed":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
state: "ready",
|
||||
activeTurnId: null,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "turn.failed":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
state: "error",
|
||||
activeTurnId: null,
|
||||
lastError: event.payload.message,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "turn.cancelled":
|
||||
return {
|
||||
...nextBase,
|
||||
sessions: updateSession(nextBase.sessions, event.sessionId, (session) => ({
|
||||
...session,
|
||||
state: "ready",
|
||||
activeTurnId: null,
|
||||
updatedAt: event.createdAt,
|
||||
})),
|
||||
};
|
||||
|
||||
case "permission.requested": {
|
||||
const pending: HarnessPendingPermission = {
|
||||
id: event.payload.requestId,
|
||||
sessionId: event.sessionId,
|
||||
turnId: event.turnId ?? null,
|
||||
kind: event.payload.kind,
|
||||
title: event.payload.title,
|
||||
...(event.payload.detail ? { detail: event.payload.detail } : {}),
|
||||
...(event.payload.args !== undefined ? { args: event.payload.args } : {}),
|
||||
createdAt: event.createdAt,
|
||||
};
|
||||
return {
|
||||
...nextBase,
|
||||
pendingPermissions: upsertById(nextBase.pendingPermissions, pending),
|
||||
};
|
||||
}
|
||||
|
||||
case "permission.resolved":
|
||||
return {
|
||||
...nextBase,
|
||||
pendingPermissions: removeById(nextBase.pendingPermissions, event.payload.requestId),
|
||||
};
|
||||
|
||||
case "elicitation.requested": {
|
||||
const pending: HarnessPendingElicitation = {
|
||||
id: event.payload.requestId,
|
||||
sessionId: event.sessionId,
|
||||
turnId: event.turnId ?? null,
|
||||
questions: event.payload.questions,
|
||||
createdAt: event.createdAt,
|
||||
};
|
||||
return {
|
||||
...nextBase,
|
||||
pendingElicitations: upsertById(nextBase.pendingElicitations, pending),
|
||||
};
|
||||
}
|
||||
|
||||
case "elicitation.resolved":
|
||||
return {
|
||||
...nextBase,
|
||||
pendingElicitations: removeById(nextBase.pendingElicitations, event.payload.requestId),
|
||||
};
|
||||
|
||||
case "connector.connected":
|
||||
case "connector.disconnected":
|
||||
return {
|
||||
...nextBase,
|
||||
connectors: applyConnector(nextBase.connectors, {
|
||||
id: event.payload.connectorId,
|
||||
profileId: null,
|
||||
harness: event.harness,
|
||||
adapterKey: event.adapterKey,
|
||||
health: event.type === "connector.connected" ? "connected" : "disconnected",
|
||||
...(event.payload.description ? { description: event.payload.description } : {}),
|
||||
...(event.payload.version ? { version: event.payload.version } : {}),
|
||||
lastSeenAt: event.createdAt,
|
||||
...(event.payload.metadata ? { metadata: event.payload.metadata } : {}),
|
||||
}),
|
||||
};
|
||||
|
||||
case "connector.health.changed":
|
||||
return {
|
||||
...nextBase,
|
||||
connectors: applyConnector(nextBase.connectors, {
|
||||
id: event.payload.connectorId,
|
||||
profileId: null,
|
||||
harness: event.harness,
|
||||
adapterKey: event.adapterKey,
|
||||
health: event.payload.health,
|
||||
...(event.payload.detail ? { description: event.payload.detail } : {}),
|
||||
lastSeenAt: event.createdAt,
|
||||
}),
|
||||
};
|
||||
|
||||
default:
|
||||
return nextBase;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { HarnessProfileId } from "@t3tools/contracts";
|
||||
import type { HarnessAdapter } from "./adapters";
|
||||
import { HarnessService } from "./server";
|
||||
|
||||
function createTestAdapter(): HarnessAdapter {
|
||||
return {
|
||||
key: "claude-agent-sdk",
|
||||
harness: "claude-agent-sdk",
|
||||
family: "sdk",
|
||||
defaultConnectionMode: "spawned",
|
||||
capabilities: {
|
||||
resume: true,
|
||||
cancel: true,
|
||||
modelSwitch: "restart-required",
|
||||
permissions: true,
|
||||
elicitation: true,
|
||||
toolLifecycle: true,
|
||||
reasoningStream: true,
|
||||
planStream: true,
|
||||
fileArtifacts: true,
|
||||
checkpoints: false,
|
||||
subagents: true,
|
||||
},
|
||||
validateProfile() {},
|
||||
async createSession(input) {
|
||||
return {
|
||||
id: "claude-session" as never,
|
||||
profileId: input.profile.id,
|
||||
harness: "claude-agent-sdk",
|
||||
adapterKey: "claude-agent-sdk",
|
||||
connectionMode: "spawned",
|
||||
title: input.title ?? null,
|
||||
cwd: null,
|
||||
model: null,
|
||||
mode: null,
|
||||
state: "starting",
|
||||
activeTurnId: null,
|
||||
nativeSessionId: "native-claude-session",
|
||||
lastError: null,
|
||||
capabilities: this.capabilities,
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
updatedAt: "2026-03-09T00:00:00.000Z",
|
||||
};
|
||||
},
|
||||
async resumeSession(input) {
|
||||
return input.session;
|
||||
},
|
||||
async sendTurn() {},
|
||||
async cancelTurn() {},
|
||||
async resolvePermission() {},
|
||||
async resolveElicitation() {},
|
||||
async updateSessionConfig() {},
|
||||
async shutdownSession() {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("HarnessService", () => {
|
||||
it("creates sessions and projects canonical lifecycle events into the snapshot", async () => {
|
||||
const service = new HarnessService({
|
||||
adapters: [createTestAdapter()],
|
||||
now: () => "2026-03-09T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const profileId = HarnessProfileId.makeUnsafe("profile-claude");
|
||||
service.upsertProfile({
|
||||
id: profileId,
|
||||
name: "Claude",
|
||||
harness: "claude-agent-sdk",
|
||||
adapterFamily: "sdk",
|
||||
connectionMode: "spawned",
|
||||
enabled: true,
|
||||
config: {
|
||||
claudeAgentSdk: {},
|
||||
},
|
||||
createdAt: "2026-03-09T00:00:00.000Z",
|
||||
updatedAt: "2026-03-09T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const session = await service.createSession(profileId, "My Claude Session");
|
||||
const snapshot = service.getSnapshot();
|
||||
|
||||
expect(session.nativeSessionId).toBe("native-claude-session");
|
||||
expect(snapshot.sessions).toHaveLength(1);
|
||||
expect(snapshot.bindings).toHaveLength(1);
|
||||
expect(snapshot.sessions[0]?.title).toBe("My Claude Session");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,391 @@
|
||||
import type {
|
||||
HarnessEvent,
|
||||
HarnessNativeFrame,
|
||||
HarnessProfile,
|
||||
HarnessSession,
|
||||
HarnessSessionId,
|
||||
HarnessSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { EventId, HarnessSessionId as HarnessSessionIdSchema } from "@t3tools/contracts";
|
||||
import type {
|
||||
HarnessAdapter,
|
||||
HarnessResolveElicitationInput,
|
||||
HarnessResolvePermissionInput,
|
||||
HarnessSendTurnInput,
|
||||
HarnessUpdateSessionConfigInput,
|
||||
} from "./adapters";
|
||||
import { HarnessAdapterError } from "./adapters";
|
||||
import { HarnessMemoryStore } from "./storage";
|
||||
|
||||
interface LiveSessionState {
|
||||
readonly adapter: HarnessAdapter;
|
||||
readonly profile: HarnessProfile;
|
||||
session: HarnessSession;
|
||||
streamAbort?: AbortController;
|
||||
}
|
||||
|
||||
export interface HarnessServiceOptions {
|
||||
readonly adapters: ReadonlyArray<HarnessAdapter>;
|
||||
readonly store?: HarnessMemoryStore;
|
||||
readonly now?: () => string;
|
||||
}
|
||||
|
||||
export type HarnessEventListener = (event: HarnessEvent, snapshot: HarnessSnapshot) => void;
|
||||
|
||||
function asSessionKey(sessionId: HarnessSessionId): string {
|
||||
return String(sessionId);
|
||||
}
|
||||
|
||||
function findProfile(snapshot: HarnessSnapshot, profileId: HarnessProfile["id"]): HarnessProfile {
|
||||
const profile = snapshot.profiles.find((entry) => entry.id === profileId);
|
||||
if (!profile) {
|
||||
throw new HarnessAdapterError(`Unknown harness profile '${profileId}'.`);
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
function createEventId(prefix: string, sessionId: HarnessSessionId, sequence: number) {
|
||||
return EventId.makeUnsafe(`${prefix}:${sessionId}:${sequence}`);
|
||||
}
|
||||
|
||||
function buildSessionCreatedEvent(
|
||||
session: HarnessSession,
|
||||
sequence: number,
|
||||
createdAt: string,
|
||||
): HarnessEvent {
|
||||
return {
|
||||
eventId: createEventId("harness-session-created", session.id, sequence),
|
||||
sessionId: session.id,
|
||||
createdAt,
|
||||
sequence,
|
||||
harness: session.harness,
|
||||
adapterKey: session.adapterKey,
|
||||
connectionMode: session.connectionMode,
|
||||
type: "session.created",
|
||||
payload: {
|
||||
...(session.profileId ? { profileId: String(session.profileId) } : {}),
|
||||
...(session.title ? { title: session.title } : {}),
|
||||
...(session.cwd ? { cwd: session.cwd } : {}),
|
||||
...(session.model ? { model: session.model } : {}),
|
||||
...(session.mode ? { mode: session.mode } : {}),
|
||||
state: session.state,
|
||||
capabilities: session.capabilities,
|
||||
...(session.metadata ? { metadata: session.metadata } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildSessionBoundEvent(
|
||||
session: HarnessSession,
|
||||
profile: HarnessProfile,
|
||||
sequence: number,
|
||||
createdAt: string,
|
||||
): HarnessEvent | undefined {
|
||||
if (!session.nativeSessionId) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
eventId: createEventId("harness-session-bound", session.id, sequence),
|
||||
sessionId: session.id,
|
||||
createdAt,
|
||||
sequence,
|
||||
harness: session.harness,
|
||||
adapterKey: session.adapterKey,
|
||||
connectionMode: session.connectionMode,
|
||||
type: "session.bound",
|
||||
payload: {
|
||||
binding: {
|
||||
sessionId: session.id,
|
||||
profileId: profile.id,
|
||||
harness: session.harness,
|
||||
adapterKey: session.adapterKey,
|
||||
connectionMode: session.connectionMode,
|
||||
nativeSessionId: session.nativeSessionId,
|
||||
...(session.activeTurnId ? { nativeTurnId: session.activeTurnId } : {}),
|
||||
...(session.metadata ? { metadata: session.metadata } : {}),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildAttachedSession(profile: HarnessProfile, adapter: HarnessAdapter, now: string): HarnessSession {
|
||||
return {
|
||||
id: HarnessSessionIdSchema.makeUnsafe(`attached:${profile.id}:${now}`),
|
||||
profileId: profile.id,
|
||||
harness: profile.harness,
|
||||
adapterKey: adapter.key,
|
||||
connectionMode: "attached",
|
||||
title: `${profile.name} Attached Session`,
|
||||
cwd:
|
||||
profile.harness === "codex-app-server"
|
||||
? profile.config.codexAppServer?.cwd ?? null
|
||||
: profile.harness === "claude-agent-sdk"
|
||||
? profile.config.claudeAgentSdk?.cwd ?? null
|
||||
: profile.config.opencode?.directory ?? null,
|
||||
model: null,
|
||||
mode:
|
||||
profile.harness === "claude-agent-sdk"
|
||||
? profile.config.claudeAgentSdk?.sessionMode ?? null
|
||||
: null,
|
||||
state: "idle",
|
||||
activeTurnId: null,
|
||||
nativeSessionId: null,
|
||||
lastError: null,
|
||||
capabilities: adapter.capabilities,
|
||||
metadata: {
|
||||
attached: true,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
export class HarnessService {
|
||||
readonly #store: HarnessMemoryStore;
|
||||
readonly #adapters = new Map<string, HarnessAdapter>();
|
||||
readonly #listeners = new Set<HarnessEventListener>();
|
||||
readonly #liveSessions = new Map<string, LiveSessionState>();
|
||||
readonly #now: () => string;
|
||||
|
||||
constructor(options: HarnessServiceOptions) {
|
||||
this.#store = options.store ?? new HarnessMemoryStore();
|
||||
this.#now = options.now ?? (() => new Date().toISOString());
|
||||
for (const adapter of options.adapters) {
|
||||
this.#adapters.set(adapter.harness, adapter);
|
||||
}
|
||||
}
|
||||
|
||||
listProfiles(): ReadonlyArray<HarnessProfile> {
|
||||
return this.#store.listProfiles();
|
||||
}
|
||||
|
||||
upsertProfile(profile: HarnessProfile): HarnessProfile {
|
||||
const adapter = this.#resolveAdapter(profile.harness);
|
||||
adapter.validateProfile(profile);
|
||||
return this.#store.upsertProfile(profile);
|
||||
}
|
||||
|
||||
deleteProfile(profileId: HarnessProfile["id"]): boolean {
|
||||
return this.#store.deleteProfile(String(profileId));
|
||||
}
|
||||
|
||||
listSessions(): ReadonlyArray<HarnessSession> {
|
||||
return this.#store.getSnapshot().sessions;
|
||||
}
|
||||
|
||||
getSnapshot(): HarnessSnapshot {
|
||||
return this.#store.getSnapshot();
|
||||
}
|
||||
|
||||
replayEvents(sessionId: HarnessSessionId, fromSequence = 0): ReadonlyArray<HarnessEvent> {
|
||||
return this.#store.listEvents(sessionId, fromSequence);
|
||||
}
|
||||
|
||||
getNativeFrames(sessionId: HarnessSessionId): ReadonlyArray<HarnessNativeFrame> {
|
||||
return this.#store.listNativeFrames(sessionId);
|
||||
}
|
||||
|
||||
subscribe(listener: HarnessEventListener): () => void {
|
||||
this.#listeners.add(listener);
|
||||
return () => {
|
||||
this.#listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
async createSession(profileId: HarnessProfile["id"], title?: string): Promise<HarnessSession> {
|
||||
const snapshot = this.#store.getSnapshot();
|
||||
const profile = findProfile(snapshot, profileId);
|
||||
const adapter = this.#resolveAdapter(profile.harness);
|
||||
const session = await adapter.createSession({
|
||||
profile,
|
||||
...(title !== undefined ? { title } : {}),
|
||||
});
|
||||
this.#registerLiveSession(profile, adapter, session);
|
||||
this.#publish(buildSessionCreatedEvent(session, this.#nextSequence(), this.#now()));
|
||||
const bindingEvent = buildSessionBoundEvent(session, profile, this.#nextSequence(), this.#now());
|
||||
if (bindingEvent) {
|
||||
this.#publish(bindingEvent);
|
||||
}
|
||||
this.#startStreaming(asSessionKey(session.id));
|
||||
return this.#requireSession(session.id);
|
||||
}
|
||||
|
||||
async attachSession(profileId: HarnessProfile["id"]): Promise<HarnessSession> {
|
||||
const snapshot = this.#store.getSnapshot();
|
||||
const profile = findProfile(snapshot, profileId);
|
||||
const adapter = this.#resolveAdapter(profile.harness);
|
||||
const session = buildAttachedSession(profile, adapter, this.#now());
|
||||
this.#registerLiveSession(profile, adapter, session);
|
||||
this.#publish(buildSessionCreatedEvent(session, this.#nextSequence(), session.createdAt));
|
||||
return this.#requireSession(session.id);
|
||||
}
|
||||
|
||||
async resumeSession(sessionId: HarnessSessionId): Promise<HarnessSession> {
|
||||
const liveSession = await this.#resolveLiveSession(sessionId);
|
||||
const session = await liveSession.adapter.resumeSession({ session: liveSession.session });
|
||||
liveSession.session = session;
|
||||
this.#startStreaming(asSessionKey(sessionId));
|
||||
return session;
|
||||
}
|
||||
|
||||
async sendTurn(input: HarnessSendTurnInput & { readonly sessionId: HarnessSessionId }): Promise<void> {
|
||||
const liveSession = await this.#resolveLiveSession(input.sessionId);
|
||||
await liveSession.adapter.sendTurn({
|
||||
session: liveSession.session,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.mode !== undefined ? { mode: input.mode } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async cancelTurn(sessionId: HarnessSessionId): Promise<void> {
|
||||
const liveSession = await this.#resolveLiveSession(sessionId);
|
||||
await liveSession.adapter.cancelTurn({ session: liveSession.session });
|
||||
}
|
||||
|
||||
async resolvePermission(
|
||||
input: HarnessResolvePermissionInput & { readonly sessionId: HarnessSessionId },
|
||||
): Promise<void> {
|
||||
const liveSession = await this.#resolveLiveSession(input.sessionId);
|
||||
await liveSession.adapter.resolvePermission({
|
||||
session: liveSession.session,
|
||||
requestId: input.requestId,
|
||||
decision: input.decision,
|
||||
});
|
||||
}
|
||||
|
||||
async resolveElicitation(
|
||||
input: HarnessResolveElicitationInput & { readonly sessionId: HarnessSessionId },
|
||||
): Promise<void> {
|
||||
const liveSession = await this.#resolveLiveSession(input.sessionId);
|
||||
await liveSession.adapter.resolveElicitation({
|
||||
session: liveSession.session,
|
||||
requestId: input.requestId,
|
||||
answers: input.answers,
|
||||
});
|
||||
}
|
||||
|
||||
async updateSessionConfig(
|
||||
input: HarnessUpdateSessionConfigInput & { readonly sessionId: HarnessSessionId },
|
||||
): Promise<void> {
|
||||
const liveSession = await this.#resolveLiveSession(input.sessionId);
|
||||
await liveSession.adapter.updateSessionConfig({
|
||||
session: liveSession.session,
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.mode !== undefined ? { mode: input.mode } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async shutdownSession(sessionId: HarnessSessionId): Promise<void> {
|
||||
const liveSession = await this.#resolveLiveSession(sessionId);
|
||||
liveSession.streamAbort?.abort();
|
||||
await liveSession.adapter.shutdownSession({ session: liveSession.session });
|
||||
this.#liveSessions.delete(asSessionKey(sessionId));
|
||||
}
|
||||
|
||||
publishConnectorEvent(event: HarnessEvent): HarnessEvent {
|
||||
return this.#publish(event);
|
||||
}
|
||||
|
||||
#publish(event: HarnessEvent): HarnessEvent {
|
||||
const stored = this.#store.appendEvent(event);
|
||||
const snapshot = this.#store.getSnapshot();
|
||||
const key = asSessionKey(event.sessionId);
|
||||
const liveSession = this.#liveSessions.get(key);
|
||||
if (liveSession) {
|
||||
const updated = snapshot.sessions.find((session) => session.id === event.sessionId);
|
||||
if (updated) {
|
||||
liveSession.session = updated;
|
||||
}
|
||||
}
|
||||
for (const listener of this.#listeners) {
|
||||
listener(stored, snapshot);
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
#resolveAdapter(harness: HarnessProfile["harness"]): HarnessAdapter {
|
||||
const adapter = this.#adapters.get(harness);
|
||||
if (!adapter) {
|
||||
throw new HarnessAdapterError(`No harness adapter registered for '${harness}'.`);
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
|
||||
#registerLiveSession(profile: HarnessProfile, adapter: HarnessAdapter, session: HarnessSession): void {
|
||||
this.#liveSessions.set(asSessionKey(session.id), {
|
||||
adapter,
|
||||
profile,
|
||||
session,
|
||||
});
|
||||
}
|
||||
|
||||
async #resolveLiveSession(sessionId: HarnessSessionId): Promise<LiveSessionState> {
|
||||
const key = asSessionKey(sessionId);
|
||||
const existing = this.#liveSessions.get(key);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const session = this.#requireSession(sessionId);
|
||||
if (!session.profileId) {
|
||||
throw new HarnessAdapterError(`Session '${sessionId}' is missing a bound profile.`);
|
||||
}
|
||||
const profile = findProfile(this.#store.getSnapshot(), session.profileId);
|
||||
const adapter = this.#resolveAdapter(session.harness);
|
||||
const liveSession = { adapter, profile, session };
|
||||
this.#liveSessions.set(key, liveSession);
|
||||
return liveSession;
|
||||
}
|
||||
|
||||
#requireSession(sessionId: HarnessSessionId): HarnessSession {
|
||||
const session = this.#store.getSnapshot().sessions.find((entry) => entry.id === sessionId);
|
||||
if (!session) {
|
||||
throw new HarnessAdapterError(`Unknown harness session '${sessionId}'.`);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
#nextSequence(): number {
|
||||
return this.#store.getSnapshot().sequence + 1;
|
||||
}
|
||||
|
||||
#startStreaming(sessionKey: string): void {
|
||||
const liveSession = this.#liveSessions.get(sessionKey);
|
||||
if (!liveSession || !liveSession.adapter.streamEvents) {
|
||||
return;
|
||||
}
|
||||
liveSession.streamAbort?.abort();
|
||||
const controller = new AbortController();
|
||||
liveSession.streamAbort = controller;
|
||||
void (async () => {
|
||||
try {
|
||||
for await (const event of liveSession.adapter.streamEvents!({
|
||||
session: liveSession.session,
|
||||
signal: controller.signal,
|
||||
})) {
|
||||
this.#publish(event);
|
||||
}
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
this.#publish({
|
||||
eventId: createEventId("harness-stream-error", liveSession.session.id, this.#nextSequence()),
|
||||
sessionId: liveSession.session.id,
|
||||
createdAt: this.#now(),
|
||||
sequence: this.#nextSequence(),
|
||||
harness: liveSession.session.harness,
|
||||
adapterKey: liveSession.session.adapterKey,
|
||||
connectionMode: liveSession.session.connectionMode,
|
||||
type: "transport.error",
|
||||
payload: {
|
||||
message: error instanceof Error ? error.message : "Harness stream failed",
|
||||
},
|
||||
});
|
||||
}
|
||||
})();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import type {
|
||||
HarnessEvent,
|
||||
HarnessNativeFrame,
|
||||
HarnessProfile,
|
||||
HarnessSessionId,
|
||||
HarnessSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { createEmptyHarnessSnapshot, projectHarnessEvent } from "./projector";
|
||||
|
||||
export const HARNESS_SQLITE_SCHEMA_STATEMENTS = [
|
||||
`CREATE TABLE IF NOT EXISTS harness_profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
harness TEXT NOT NULL,
|
||||
adapter_family TEXT NOT NULL,
|
||||
connection_mode TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL,
|
||||
config_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT,
|
||||
harness TEXT NOT NULL,
|
||||
adapter_key TEXT NOT NULL,
|
||||
connection_mode TEXT NOT NULL,
|
||||
title TEXT,
|
||||
cwd TEXT,
|
||||
model TEXT,
|
||||
mode TEXT,
|
||||
state TEXT NOT NULL,
|
||||
active_turn_id TEXT,
|
||||
native_session_id TEXT,
|
||||
last_error TEXT,
|
||||
capabilities_json TEXT NOT NULL,
|
||||
metadata_json TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_bindings (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
profile_id TEXT,
|
||||
harness TEXT NOT NULL,
|
||||
adapter_key TEXT NOT NULL,
|
||||
connection_mode TEXT NOT NULL,
|
||||
native_session_id TEXT,
|
||||
native_thread_id TEXT,
|
||||
native_turn_id TEXT,
|
||||
resume_cursor_json TEXT,
|
||||
metadata_json TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_events (
|
||||
sequence INTEGER PRIMARY KEY,
|
||||
event_id TEXT NOT NULL UNIQUE,
|
||||
session_id TEXT NOT NULL,
|
||||
harness TEXT NOT NULL,
|
||||
adapter_key TEXT NOT NULL,
|
||||
connection_mode TEXT NOT NULL,
|
||||
turn_id TEXT,
|
||||
item_id TEXT,
|
||||
type TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
native_refs_json TEXT,
|
||||
payload_json TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_pending_permissions (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
turn_id TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
detail TEXT,
|
||||
args_json TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_pending_elicitations (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
turn_id TEXT,
|
||||
questions_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_connectors (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT,
|
||||
harness TEXT NOT NULL,
|
||||
adapter_key TEXT NOT NULL,
|
||||
health TEXT NOT NULL,
|
||||
description TEXT,
|
||||
version TEXT,
|
||||
last_seen_at TEXT NOT NULL,
|
||||
metadata_json TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_native_frames (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
harness TEXT NOT NULL,
|
||||
adapter_key TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS harness_blobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS projection_state (
|
||||
projector TEXT PRIMARY KEY,
|
||||
last_sequence INTEGER NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)`,
|
||||
] as const;
|
||||
|
||||
export class HarnessMemoryStore {
|
||||
#events: HarnessEvent[] = [];
|
||||
#profiles = new Map<string, HarnessProfile>();
|
||||
#nativeFrames = new Map<string, HarnessNativeFrame[]>();
|
||||
#snapshot: HarnessSnapshot;
|
||||
|
||||
constructor(nowIso = new Date().toISOString()) {
|
||||
this.#snapshot = createEmptyHarnessSnapshot(nowIso);
|
||||
}
|
||||
|
||||
upsertProfile(profile: HarnessProfile): HarnessProfile {
|
||||
this.#profiles.set(profile.id, profile);
|
||||
this.#snapshot = {
|
||||
...this.#snapshot,
|
||||
profiles: Array.from(this.#profiles.values()).toSorted((left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt),
|
||||
),
|
||||
updatedAt: profile.updatedAt,
|
||||
};
|
||||
return profile;
|
||||
}
|
||||
|
||||
deleteProfile(profileId: string): boolean {
|
||||
const deleted = this.#profiles.delete(profileId);
|
||||
if (!deleted) {
|
||||
return false;
|
||||
}
|
||||
this.#snapshot = {
|
||||
...this.#snapshot,
|
||||
profiles: Array.from(this.#profiles.values()).toSorted((left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt),
|
||||
),
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
appendEvent(event: HarnessEvent): HarnessEvent {
|
||||
this.#events.push(event);
|
||||
this.#snapshot = projectHarnessEvent(this.#snapshot, event);
|
||||
if (event.type === "native.frame") {
|
||||
const frame: HarnessNativeFrame = {
|
||||
id: event.eventId,
|
||||
sessionId: event.sessionId,
|
||||
harness: event.harness,
|
||||
adapterKey: event.adapterKey,
|
||||
createdAt: event.createdAt,
|
||||
source: event.payload.source,
|
||||
payload: event.payload.payload,
|
||||
};
|
||||
const existing = this.#nativeFrames.get(event.sessionId) ?? [];
|
||||
existing.push(frame);
|
||||
this.#nativeFrames.set(event.sessionId, existing);
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
listProfiles(): ReadonlyArray<HarnessProfile> {
|
||||
return this.#snapshot.profiles;
|
||||
}
|
||||
|
||||
listEvents(sessionId?: HarnessSessionId, fromSequence = 0): ReadonlyArray<HarnessEvent> {
|
||||
return this.#events.filter(
|
||||
(event) =>
|
||||
event.sequence >= fromSequence && (sessionId === undefined || event.sessionId === sessionId),
|
||||
);
|
||||
}
|
||||
|
||||
listNativeFrames(sessionId: HarnessSessionId): ReadonlyArray<HarnessNativeFrame> {
|
||||
return this.#nativeFrames.get(sessionId) ?? [];
|
||||
}
|
||||
|
||||
getSnapshot(): HarnessSnapshot {
|
||||
return this.#snapshot;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@t3tools/contracts": ["../contracts/src/index.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in new issue
Block a user