@anureo/host 0.0.0-stage → 0.3.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/package.json +50 -4
- package/schema/v1/hx.schema.json +3422 -0
- package/src/catalog-store.ts +45 -0
- package/src/catalog-worker.ts +14 -0
- package/src/catalog.ts +179 -0
- package/src/compat.ts +7 -0
- package/src/errors.ts +24 -0
- package/src/host.ts +1229 -0
- package/src/index.ts +16 -0
- package/src/interaction-capture.ts +37 -0
- package/src/legacy-protocol/generated/types.ts +244 -0
- package/src/legacy-protocol/index.ts +37 -0
- package/src/native-subagent.ts +19 -0
- package/src/persistent-secrets.ts +34 -0
- package/src/protocol.ts +68 -0
- package/src/queue.ts +12 -0
- package/src/rpc.ts +43 -0
- package/src/scoped-host.ts +39 -0
- package/src/sqlite-bun.ts +12 -0
- package/src/sqlite-driver.ts +14 -0
- package/src/sqlite-node.ts +38 -0
- package/src/store.ts +408 -0
- package/src/subagents.ts +115 -0
- package/src/swarm-client.ts +113 -0
- package/src/swarm-workflows.ts +50 -0
- package/src/workspaces.ts +36 -0
- package/src/ws-bun-listener.ts +44 -0
- package/src/ws-connection.ts +127 -0
- package/src/ws-listener.ts +87 -0
- package/src/ws.ts +12 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { HarnessHost } from './host'
|
|
2
|
+
export type {
|
|
3
|
+
HostConnection, HostOptions, HostProjection, PermissionPolicyPort, Principal, Role,
|
|
4
|
+
RuntimeRegistration, RuntimeAuthStatus, FullAccessSession, PermissionDowngradeResult,
|
|
5
|
+
} from './host'
|
|
6
|
+
export { HostError } from './errors'
|
|
7
|
+
export { attachInteractionCapture, createInteractionCapture } from './interaction-capture'
|
|
8
|
+
export type { HostDispatcher, RpcNotification, RpcRequest, RpcResponse } from './rpc'
|
|
9
|
+
export type { CatalogWorker, CatalogDiagnostic } from './catalog-worker'
|
|
10
|
+
export type { CatalogModel } from './catalog-store'
|
|
11
|
+
export type { SessionRecord, HostStorage } from './store'
|
|
12
|
+
export type { SubagentDiscoveryPort, SubagentHistoryPort } from './subagents'
|
|
13
|
+
export * from './workspaces'
|
|
14
|
+
|
|
15
|
+
export type { HostActor, HostAuthorizationPolicy, CreateHostOptions } from './scoped-host'
|
|
16
|
+
export { createHarnessHost, createScopedHostDispatcher } from './scoped-host'
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Bridges 0.3 native interaction handlers into the host's manual RPC flow: handlers receive the full request (private payloads are stripped from the event stream) and park until the host settles them from hx.interaction.respond / cancel. */
|
|
2
|
+
import type { Client, InteractionHandlers } from "@anureo/sdk";
|
|
3
|
+
import type { InteractionRequested, InteractionResponse } from "@anureo/protocol";
|
|
4
|
+
|
|
5
|
+
/** Full requests captured from registered handlers plus the pending host settlements, keyed by native interaction id (unique per adapter instance). */
|
|
6
|
+
export interface InteractionCapture {
|
|
7
|
+
/** Full original requests, including privatePayload the event stream intentionally withholds. */
|
|
8
|
+
requests: Pick<Map<string, InteractionRequested>, "get">;
|
|
9
|
+
/** Handler promises parked for the host's manual answer; settled exactly once from respond/cancel RPCs. */
|
|
10
|
+
pending: Pick<Map<string, { resolve: (response: InteractionResponse) => void; reject: (cause: unknown) => void }>, "get" | "delete">;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const KINDS = ["approval", "userInput", "elicitation", "dynamicTool"] as const;
|
|
14
|
+
|
|
15
|
+
/** Build one capture per backend client, plus handlers that park adapter-local interactions for manual host settlement. */
|
|
16
|
+
export function createInteractionCapture(): { capture: InteractionCapture; handlers: InteractionHandlers } {
|
|
17
|
+
const requests = new Map<string, InteractionRequested>();
|
|
18
|
+
const pending = new Map<string, { resolve: (response: InteractionResponse) => void; reject: (cause: unknown) => void }>();
|
|
19
|
+
const capture: InteractionCapture = { requests, pending };
|
|
20
|
+
const handlers = Object.fromEntries(KINDS.map((kind) => [kind, async (request: InteractionRequested) => {
|
|
21
|
+
requests.set(request.interactionId, structuredClone(request));
|
|
22
|
+
return new Promise<InteractionResponse>((resolve, reject) => { pending.set(request.interactionId, { resolve, reject }); });
|
|
23
|
+
}])) as InteractionHandlers;
|
|
24
|
+
return { capture, handlers };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Read the capture attached to a client by a registration factory; undefined for clients built without capture handlers. */
|
|
28
|
+
export function clientInteractionCapture(client: Client): InteractionCapture | undefined {
|
|
29
|
+
return (client as Client & { interactionCapture?: InteractionCapture }).interactionCapture;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Attach the capture to a client instance (or the promise createClient resolves) so the host can find it after descriptor.create(). */
|
|
33
|
+
export async function attachInteractionCapture(client: Client | Promise<Client>, capture: InteractionCapture): Promise<Client> {
|
|
34
|
+
const resolved = await client;
|
|
35
|
+
(resolved as Client & { interactionCapture?: InteractionCapture }).interactionCapture = capture;
|
|
36
|
+
return resolved;
|
|
37
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// Generated from schema/v1/hx.schema.json; do not edit.
|
|
2
|
+
import type * as Ahp from '@anureo/protocol';
|
|
3
|
+
export type HxError = Ahp.HarnessError;
|
|
4
|
+
export type OperationState = "accepted" | "completed" | "failed" | "unknown";
|
|
5
|
+
export type OperationResult = { "operationId": string; "state": OperationState; "sessionId"?: string; "turnId"?: string; "revision"?: number; "outcomeUnknown": boolean; "result"?: Ahp.JsonValue; "error"?: HxError };
|
|
6
|
+
export type PublicInteraction = { "interactionId": string; "revision": number; "state": "pending" | "responding" | "resolved"; "request": Ahp.InteractionRequested; "resolution"?: Ahp.InteractionResult };
|
|
7
|
+
export type PublicSession = { "executionMode"?: "normal" | "swarm"; "id": string; "projectId": string; "ownerId": string; "adapterId": string; "runtimeConfigId": string; "cwd": string; "config": Ahp.JsonObject; "revision": number; "latestSeq": number; "status": "opening" | "ready" | "running" | "closing" | "closed" | "recoveryRequired"; "activeTurnId"?: string; "archived": boolean; "model"?: string; "pendingInteractions"?: Array<PublicInteraction>; "agentId"?: string; "title"?: string; "createdAt"?: number; "updatedAt"?: number; "capabilities"?: Ahp.Capabilities; "capabilityRevision"?: number; "bindingGeneration"?: number; "hostCapabilities"?: HostCapabilities; "workspace"?: PublicWorkspace; "managed"?: { "scopeId": string; "executionKey": string }; "goal"?: Ahp.GoalState; "parent"?: { "sessionId": string; "boundary": Ahp.Boundary; "bindingGeneration": number }; "fastMode"?: { "state": "off" | "cooldown" | "on"; "reason"?: string }; "subagents"?: Array<HxSubagent> };
|
|
8
|
+
export type HostLifecycleEvent = { "type": "host/operation" | "host/recovery" | "host/turnObservationEnded" | "host/turnInput" | "host/queue" | "host/binding" | "host/workspace" | "host/permissions" | "host/subagent"; "payload": Ahp.JsonObject };
|
|
9
|
+
export type HostEvent = { "sessionId": string; "hostSeq": number; "recordedAt": string; "source"?: { "streamId": string; "seq": number }; "event": (Ahp.AhpEventPayload) | (HostLifecycleEvent); "turnId"?: string; "itemId"?: string; "bindingGeneration"?: number };
|
|
10
|
+
export type HxNotification = { "jsonrpc": "2.0"; "method": "hx.event"; "params": { "sessionId": string; "hostSeq": number; "recordedAt": string; "source"?: { "streamId": string; "seq": number }; "event": (Ahp.AhpEventPayload) | (HostLifecycleEvent); "subscriptionId": string; "turnId"?: string; "itemId"?: string; "bindingGeneration"?: number } };
|
|
11
|
+
export type EventPage = { "events": Array<HostEvent>; "nextAfterSeq": number; "hasMore": boolean; "latestSeq": number; "earliestSeq": number; "throughSeq": number };
|
|
12
|
+
export type HxInitializeParams = { "protocolVersions": Array<number>; "clientInfo": Ahp.ClientInfo };
|
|
13
|
+
export type HxInitializeResult = { "protocolVersion": 1; "features": Array<string>; "limits": Ahp.JsonObject };
|
|
14
|
+
export type HxHarnessListParams = { "projectId": string };
|
|
15
|
+
export type HxHarnessListResult = { "harnesses": Array<{ "runtimeConfigId": string; "adapterId": string; "available": boolean; "reason"?: string; "capabilities"?: Ahp.Capabilities; "version"?: string; "providerId"?: string; "name"?: string; "authStatus"?: "unknown" | "required" | "ready" }> };
|
|
16
|
+
export type HxHarnessModelsParams = { "projectId": string; "runtimeConfigId": string };
|
|
17
|
+
export type HxHarnessModelsResult = { "models": Array<{ "id": string; "name": string; "isDefault"?: boolean; "group"?: "primary" | "more"; "effortLevels"?: Array<string>; "defaultEffort"?: string; "supportsFast"?: boolean }>; "source": string; "reason"?: string };
|
|
18
|
+
export type HxSessionCreateParams = { "executionMode"?: "normal" | "swarm"; "projectId": string; "runtimeConfigId": string; "model"?: string; "instructions"?: string; "config"?: Ahp.JsonObject; "idempotencyKey": string; "agentId"?: string; "workspace"?: WorkspaceRequest };
|
|
19
|
+
export type HxSessionCreateResult = OperationResult;
|
|
20
|
+
export type HxSessionGetParams = { "sessionId": string; "projectId"?: string };
|
|
21
|
+
export type HxSessionGetResult = PublicSession;
|
|
22
|
+
export type HxSessionListParams = { "projectId": string; "archived"?: boolean; "cursor"?: string; "limit"?: number };
|
|
23
|
+
export type HxSessionListResult = { "sessions": Array<PublicSession>; "nextCursor": (string) | (null) };
|
|
24
|
+
export type HostSessionListSummary = { "id": string; "scopeId": string; "title"?: string; "status": "opening" | "ready" | "running" | "closing" | "closed" | "recoveryRequired"; "runtimeConfigId": string; "updatedAt"?: number; "archived": boolean };
|
|
25
|
+
export type HostSessionListSummaryPage = { "sessions": Array<HostSessionListSummary>; "nextCursor": (string) | (null) };
|
|
26
|
+
export type HxSessionOpenParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number };
|
|
27
|
+
export type HxSessionOpenResult = OperationResult;
|
|
28
|
+
export type HxSessionCloseParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number };
|
|
29
|
+
export type HxSessionCloseResult = OperationResult;
|
|
30
|
+
export type HxSessionArchiveParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number };
|
|
31
|
+
export type HxSessionArchiveResult = OperationResult;
|
|
32
|
+
export type HxSessionRestoreParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number };
|
|
33
|
+
export type HxSessionRestoreResult = OperationResult;
|
|
34
|
+
export type HxSessionConfigSetParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "patch": Ahp.JsonObject };
|
|
35
|
+
export type HxSessionConfigSetResult = OperationResult;
|
|
36
|
+
export type HxSessionForkParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "boundary": Ahp.Boundary; "workspace"?: WorkspaceRequest };
|
|
37
|
+
export type HxSessionForkResult = OperationResult;
|
|
38
|
+
export type HxSessionRevertParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "boundary": Ahp.Boundary; "scope": Ahp.RevertScope };
|
|
39
|
+
export type HxSessionRevertResult = OperationResult;
|
|
40
|
+
export type HxSessionReconcileParams = { "sessionId": string; "projectId"?: string };
|
|
41
|
+
export type HxSessionReconcileResult = { "session": PublicSession; "operations": Array<OperationResult> };
|
|
42
|
+
export type HxHistoryReadParams = { "sessionId": string; "projectId"?: string; "cursor"?: string; "limit"?: number; "snapshotToken"?: string };
|
|
43
|
+
export type HxHistoryReadResult = Ahp.HistoryPage;
|
|
44
|
+
export type HxTurnStartParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "input": Array<Ahp.InputBlock>; "overrides"?: Ahp.JsonObject; "outputSchema"?: Ahp.JsonSchema; "references"?: Array<HxContextReference> };
|
|
45
|
+
export type HxTurnStartResult = OperationResult;
|
|
46
|
+
export type HxTurnSteerParams = { "sessionId": string; "projectId"?: string; "expectedTurnId": string; "input": Array<Ahp.InputBlock>; "idempotencyKey": string; "references"?: Array<HxContextReference> };
|
|
47
|
+
export type HxTurnSteerResult = OperationResult;
|
|
48
|
+
export type HxTurnInterruptParams = { "sessionId": string; "projectId"?: string; "turnId": string; "idempotencyKey": string };
|
|
49
|
+
export type HxTurnInterruptResult = OperationResult;
|
|
50
|
+
export type HxInteractionListParams = { "sessionId": string; "projectId"?: string; "state"?: "pending" | "responding" | "resolved" };
|
|
51
|
+
export type HxInteractionListResult = { "interactions": Array<PublicInteraction> };
|
|
52
|
+
export type HxInteractionPrivateGetParams = { "sessionId": string; "projectId"?: string; "interactionId": string };
|
|
53
|
+
export type HxInteractionPrivateGetResult = Ahp.JsonObject;
|
|
54
|
+
export type HxInteractionRespondParams = { "sessionId": string; "projectId"?: string; "interactionId": string; "expectedInteractionRevision": number; "idempotencyKey": string; "response": Ahp.InteractionResponse };
|
|
55
|
+
export type HxInteractionRespondResult = OperationResult;
|
|
56
|
+
export type HxInteractionCancelParams = { "sessionId": string; "projectId"?: string; "interactionId": string; "expectedInteractionRevision": number; "idempotencyKey": string; "reason"?: string };
|
|
57
|
+
export type HxInteractionCancelResult = OperationResult;
|
|
58
|
+
export type HxGoalSetParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "goal": Ahp.JsonObject };
|
|
59
|
+
export type HxGoalSetResult = OperationResult;
|
|
60
|
+
export type HxGoalClearParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number };
|
|
61
|
+
export type HxGoalClearResult = OperationResult;
|
|
62
|
+
export type HxCompactStartParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number };
|
|
63
|
+
export type HxCompactStartResult = OperationResult;
|
|
64
|
+
export type HxReviewStartParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "target": Ahp.JsonObject };
|
|
65
|
+
export type HxReviewStartResult = OperationResult;
|
|
66
|
+
export type HxOperationGetParams = ({ "operationId": string; "method"?: string; "target"?: string; "idempotencyKey"?: string }) | ({ "operationId"?: string; "method": string; "target": string; "idempotencyKey": string });
|
|
67
|
+
export type HxOperationGetResult = OperationResult;
|
|
68
|
+
export type HxEventsReadParams = { "sessionId": string; "projectId"?: string; "afterSeq"?: number; "throughSeq"?: number; "limit"?: number };
|
|
69
|
+
export type HxEventsReadResult = EventPage;
|
|
70
|
+
export type HxProjectionSnapshotParams = { "sessionId": string; "projectId"?: string };
|
|
71
|
+
export type HxProjectionSnapshotResult = { "checkpoint": ({ }) | (null); "seq": number; "latestSeq": number };
|
|
72
|
+
export type HxEventsSubscribeParams = { "sessionId": string; "projectId"?: string; "afterSeq": number };
|
|
73
|
+
export type HxEventsSubscribeResult = { "subscriptionId": string; "cutoverSeq": number; "earliestSeq": number };
|
|
74
|
+
export type HxEventsUnsubscribeParams = { "subscriptionId": string };
|
|
75
|
+
export type HxEventsUnsubscribeResult = { "removed": boolean };
|
|
76
|
+
export type SubscriptionError = { "subscriptionId": string; "code": string; "lastAvailableSeq": number };
|
|
77
|
+
export type HxContextReference = ({ "type": "workspace-file"; "resourceKey": string; "expectedRevision"?: string }) | ({ "type": "workspace-selection"; "resourceKey": string; "selectedText": string; "startLine"?: number; "endLine"?: number; "expectedRevision"?: string }) | ({ "type": "uploaded-file"; "blobRef": string; "displayName": string; "mimeType"?: string; "sizeBytes"?: number });
|
|
78
|
+
export type HxHarnessChangedParams = { "projectId": string; "revision": number };
|
|
79
|
+
export type HxHarnessChangedNotification = { "jsonrpc": "2.0"; "method": "hx.harness.changed"; "params": HxHarnessChangedParams };
|
|
80
|
+
export type HxServerNotification = (HxNotification) | (HxHarnessChangedNotification) | (HxCatalogChangedNotification);
|
|
81
|
+
export type HostCapabilities = { "queue": boolean; "worktree": boolean; "harnessSwitch": boolean; "managed": boolean; "subagents"?: boolean };
|
|
82
|
+
export type WorkspaceRequest = ({ "kind": "project" }) | ({ "kind": "worktree"; "name"?: string; "baseRef"?: string; "worktreeId"?: string });
|
|
83
|
+
export type PublicWorkspace = { "kind": "project" | "worktree"; "worktreeId"?: string; "name"?: string; "branch"?: string };
|
|
84
|
+
export type HxQueueItem = { "id": string; "turnId": string; "state": "queued" | "dispatching" | "running" | "completed" | "failed" | "unknown" | "cancelled"; "input": Array<Ahp.InputBlock>; "references"?: Array<HxContextReference>; "createdAt": number; "updatedAt": number; "operationId"?: string; "error"?: Ahp.HarnessError; "bindingGeneration": number };
|
|
85
|
+
export type HxQueueState = { "revision": number; "paused": boolean; "items": Array<HxQueueItem> };
|
|
86
|
+
export type HxQueueGetParams = { "sessionId": string; "projectId"?: string };
|
|
87
|
+
export type HxQueueGetResult = HxQueueState;
|
|
88
|
+
export type HxQueueEnqueueParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number; "input": Array<Ahp.InputBlock>; "references"?: Array<HxContextReference>; "overrides"?: Ahp.JsonObject; "outputSchema"?: Ahp.JsonSchema };
|
|
89
|
+
export type HxQueueEnqueueResult = OperationResult;
|
|
90
|
+
export type HxQueueUpdateParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number; "input": Array<Ahp.InputBlock>; "references"?: Array<HxContextReference>; "overrides"?: Ahp.JsonObject; "outputSchema"?: Ahp.JsonSchema; "itemId": string };
|
|
91
|
+
export type HxQueueUpdateResult = OperationResult;
|
|
92
|
+
export type HxQueueRemoveParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number; "itemId": string };
|
|
93
|
+
export type HxQueueRemoveResult = OperationResult;
|
|
94
|
+
export type HxQueueReorderParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number; "itemIds": Array<string> };
|
|
95
|
+
export type HxQueueReorderResult = OperationResult;
|
|
96
|
+
export type HxQueueClearParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number };
|
|
97
|
+
export type HxQueueClearResult = OperationResult;
|
|
98
|
+
export type HxQueuePauseParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number };
|
|
99
|
+
export type HxQueuePauseResult = OperationResult;
|
|
100
|
+
export type HxQueueResumeParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number };
|
|
101
|
+
export type HxQueueResumeResult = OperationResult;
|
|
102
|
+
export type HxQueueRunParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number; "itemId": string };
|
|
103
|
+
export type HxQueueRunResult = OperationResult;
|
|
104
|
+
export type HxQueueSteerParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number; "itemId": string; "expectedTurnId": string };
|
|
105
|
+
export type HxQueueSteerResult = OperationResult;
|
|
106
|
+
export type HxQueueRetryParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedQueueRevision": number; "itemId": string };
|
|
107
|
+
export type HxQueueRetryResult = OperationResult;
|
|
108
|
+
export type HxSessionHarnessSetParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "runtimeConfigId": string; "model"?: string };
|
|
109
|
+
export type HxSessionHarnessSetResult = OperationResult;
|
|
110
|
+
export type HxWorkspaceGetParams = { "sessionId": string; "projectId"?: string };
|
|
111
|
+
export type HxWorkspaceGetResult = PublicWorkspace;
|
|
112
|
+
export type HxWorkspaceIntegrateParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "force"?: boolean; "mode": "merge" | "patch"; "message"?: string };
|
|
113
|
+
export type HxWorkspaceIntegrateResult = OperationResult;
|
|
114
|
+
export type HxWorkspaceDiscardParams = { "sessionId": string; "projectId"?: string; "idempotencyKey": string; "expectedRevision": number; "force"?: boolean };
|
|
115
|
+
export type HxWorkspaceDiscardResult = OperationResult;
|
|
116
|
+
export type HxUsageEntry = { "sessionId": string; "agentId"?: string; "usage": (Ahp.Usage) | (null) };
|
|
117
|
+
export type HxUsageGetParams = { "projectId": string; "agentId"?: string; "includeArchived"?: boolean };
|
|
118
|
+
export type HxUsageGetResult = { "sessions": Array<HxUsageEntry>; "totals": { "input": (number) | (null); "output": (number) | (null); "total": (number) | (null) } };
|
|
119
|
+
export type HxTranscriptReadParams = { "sessionId": string; "projectId"?: string };
|
|
120
|
+
export type HxTranscriptReadResult = { "inherited": Array<HostEvent> };
|
|
121
|
+
export type CatalogCache = { "state": "empty" | "fresh" | "stale"; "lastSuccessAt": (number) | (null); "freshUntil": (number) | (null); "refreshing": boolean; "lastErrorCode"?: string; "nextRetryAt"?: number };
|
|
122
|
+
export type CatalogRuntime = { "runtimeConfigId": string; "adapterId": string; "available": boolean; "reason"?: string; "capabilities"?: Ahp.Capabilities; "version"?: string; "providerId"?: string; "name"?: string; "authStatus"?: "unknown" | "required" | "ready"; "readiness": "preparing" | "ready" | "unavailable"; "models"?: Array<{ "id": string; "name": string; "isDefault"?: boolean; "group"?: "primary" | "more"; "effortLevels"?: Array<string>; "defaultEffort"?: string; "supportsFast"?: boolean }>; "cache": CatalogCache };
|
|
123
|
+
export type HxCatalogGetParams = { "projectId": string; "runtimeConfigId"?: string };
|
|
124
|
+
export type HxCatalogGetResult = { "epoch": string; "revision": number; "runtimes": Array<CatalogRuntime> };
|
|
125
|
+
export type HxCatalogRefreshParams = { "projectId": string; "runtimeConfigId": string };
|
|
126
|
+
export type HxCatalogRefreshResult = { "accepted": boolean; "coalesced": boolean; "refreshId": string };
|
|
127
|
+
export type HxCatalogChangedParams = { "projectId": string; "epoch": string; "revision": number; "runtimeConfigIds": Array<string>; "changes": Array<"runtime" | "models" | "auth" | "refresh"> };
|
|
128
|
+
export type HxCatalogChangedNotification = { "jsonrpc": "2.0"; "method": "hx.catalog.changed"; "params": HxCatalogChangedParams };
|
|
129
|
+
export type HxSubagent = { "sessionId": string; "parentSessionId": string; "parentTurnId"?: string; "name": string; "task"?: string; "status": "running" | "completed" | "failed" | "interrupted" | "disconnected"; "canOpen": boolean; "createdAt": number; "updatedAt": number };
|
|
130
|
+
export type HxSubagentsListParams = { "sessionId": string; "projectId"?: string };
|
|
131
|
+
export type HxSubagentsListResult = { "subagents": Array<HxSubagent> };
|
|
132
|
+
export type HxSubagentsHistoryParams = { "sessionId": string; "projectId"?: string; "childSessionId": string; "cursor"?: string; "limit"?: number };
|
|
133
|
+
export type HxSubagentsHistoryResult = { "subagent": HxSubagent; "history": Ahp.HistoryPage };
|
|
134
|
+
export interface HxRequestMap {
|
|
135
|
+
"hx.initialize": HxInitializeParams;
|
|
136
|
+
"hx.harness.list": HxHarnessListParams;
|
|
137
|
+
"hx.harness.models": HxHarnessModelsParams;
|
|
138
|
+
"hx.session.create": HxSessionCreateParams;
|
|
139
|
+
"hx.session.get": HxSessionGetParams;
|
|
140
|
+
"hx.session.list": HxSessionListParams;
|
|
141
|
+
"hx.session.open": HxSessionOpenParams;
|
|
142
|
+
"hx.session.close": HxSessionCloseParams;
|
|
143
|
+
"hx.session.archive": HxSessionArchiveParams;
|
|
144
|
+
"hx.session.restore": HxSessionRestoreParams;
|
|
145
|
+
"hx.session.config.set": HxSessionConfigSetParams;
|
|
146
|
+
"hx.session.fork": HxSessionForkParams;
|
|
147
|
+
"hx.session.revert": HxSessionRevertParams;
|
|
148
|
+
"hx.session.reconcile": HxSessionReconcileParams;
|
|
149
|
+
"hx.history.read": HxHistoryReadParams;
|
|
150
|
+
"hx.turn.start": HxTurnStartParams;
|
|
151
|
+
"hx.turn.steer": HxTurnSteerParams;
|
|
152
|
+
"hx.turn.interrupt": HxTurnInterruptParams;
|
|
153
|
+
"hx.interaction.list": HxInteractionListParams;
|
|
154
|
+
"hx.interaction.private.get": HxInteractionPrivateGetParams;
|
|
155
|
+
"hx.interaction.respond": HxInteractionRespondParams;
|
|
156
|
+
"hx.interaction.cancel": HxInteractionCancelParams;
|
|
157
|
+
"hx.goal.set": HxGoalSetParams;
|
|
158
|
+
"hx.goal.clear": HxGoalClearParams;
|
|
159
|
+
"hx.compact.start": HxCompactStartParams;
|
|
160
|
+
"hx.review.start": HxReviewStartParams;
|
|
161
|
+
"hx.operation.get": HxOperationGetParams;
|
|
162
|
+
"hx.events.read": HxEventsReadParams;
|
|
163
|
+
"hx.projection.snapshot": HxProjectionSnapshotParams;
|
|
164
|
+
"hx.events.subscribe": HxEventsSubscribeParams;
|
|
165
|
+
"hx.events.unsubscribe": HxEventsUnsubscribeParams;
|
|
166
|
+
"hx.queue.get": HxQueueGetParams;
|
|
167
|
+
"hx.queue.enqueue": HxQueueEnqueueParams;
|
|
168
|
+
"hx.queue.update": HxQueueUpdateParams;
|
|
169
|
+
"hx.queue.remove": HxQueueRemoveParams;
|
|
170
|
+
"hx.queue.reorder": HxQueueReorderParams;
|
|
171
|
+
"hx.queue.clear": HxQueueClearParams;
|
|
172
|
+
"hx.queue.pause": HxQueuePauseParams;
|
|
173
|
+
"hx.queue.resume": HxQueueResumeParams;
|
|
174
|
+
"hx.queue.run": HxQueueRunParams;
|
|
175
|
+
"hx.queue.steer": HxQueueSteerParams;
|
|
176
|
+
"hx.queue.retry": HxQueueRetryParams;
|
|
177
|
+
"hx.session.harness.set": HxSessionHarnessSetParams;
|
|
178
|
+
"hx.workspace.get": HxWorkspaceGetParams;
|
|
179
|
+
"hx.workspace.integrate": HxWorkspaceIntegrateParams;
|
|
180
|
+
"hx.workspace.discard": HxWorkspaceDiscardParams;
|
|
181
|
+
"hx.usage.get": HxUsageGetParams;
|
|
182
|
+
"hx.transcript.read": HxTranscriptReadParams;
|
|
183
|
+
"hx.catalog.get": HxCatalogGetParams;
|
|
184
|
+
"hx.catalog.refresh": HxCatalogRefreshParams;
|
|
185
|
+
"hx.subagents.list": HxSubagentsListParams;
|
|
186
|
+
"hx.subagents.history": HxSubagentsHistoryParams;
|
|
187
|
+
}
|
|
188
|
+
export interface HxResultMap {
|
|
189
|
+
"hx.initialize": HxInitializeResult;
|
|
190
|
+
"hx.harness.list": HxHarnessListResult;
|
|
191
|
+
"hx.harness.models": HxHarnessModelsResult;
|
|
192
|
+
"hx.session.create": HxSessionCreateResult;
|
|
193
|
+
"hx.session.get": HxSessionGetResult;
|
|
194
|
+
"hx.session.list": HxSessionListResult;
|
|
195
|
+
"hx.session.open": HxSessionOpenResult;
|
|
196
|
+
"hx.session.close": HxSessionCloseResult;
|
|
197
|
+
"hx.session.archive": HxSessionArchiveResult;
|
|
198
|
+
"hx.session.restore": HxSessionRestoreResult;
|
|
199
|
+
"hx.session.config.set": HxSessionConfigSetResult;
|
|
200
|
+
"hx.session.fork": HxSessionForkResult;
|
|
201
|
+
"hx.session.revert": HxSessionRevertResult;
|
|
202
|
+
"hx.session.reconcile": HxSessionReconcileResult;
|
|
203
|
+
"hx.history.read": HxHistoryReadResult;
|
|
204
|
+
"hx.turn.start": HxTurnStartResult;
|
|
205
|
+
"hx.turn.steer": HxTurnSteerResult;
|
|
206
|
+
"hx.turn.interrupt": HxTurnInterruptResult;
|
|
207
|
+
"hx.interaction.list": HxInteractionListResult;
|
|
208
|
+
"hx.interaction.private.get": HxInteractionPrivateGetResult;
|
|
209
|
+
"hx.interaction.respond": HxInteractionRespondResult;
|
|
210
|
+
"hx.interaction.cancel": HxInteractionCancelResult;
|
|
211
|
+
"hx.goal.set": HxGoalSetResult;
|
|
212
|
+
"hx.goal.clear": HxGoalClearResult;
|
|
213
|
+
"hx.compact.start": HxCompactStartResult;
|
|
214
|
+
"hx.review.start": HxReviewStartResult;
|
|
215
|
+
"hx.operation.get": HxOperationGetResult;
|
|
216
|
+
"hx.events.read": HxEventsReadResult;
|
|
217
|
+
"hx.projection.snapshot": HxProjectionSnapshotResult;
|
|
218
|
+
"hx.events.subscribe": HxEventsSubscribeResult;
|
|
219
|
+
"hx.events.unsubscribe": HxEventsUnsubscribeResult;
|
|
220
|
+
"hx.queue.get": HxQueueGetResult;
|
|
221
|
+
"hx.queue.enqueue": HxQueueEnqueueResult;
|
|
222
|
+
"hx.queue.update": HxQueueUpdateResult;
|
|
223
|
+
"hx.queue.remove": HxQueueRemoveResult;
|
|
224
|
+
"hx.queue.reorder": HxQueueReorderResult;
|
|
225
|
+
"hx.queue.clear": HxQueueClearResult;
|
|
226
|
+
"hx.queue.pause": HxQueuePauseResult;
|
|
227
|
+
"hx.queue.resume": HxQueueResumeResult;
|
|
228
|
+
"hx.queue.run": HxQueueRunResult;
|
|
229
|
+
"hx.queue.steer": HxQueueSteerResult;
|
|
230
|
+
"hx.queue.retry": HxQueueRetryResult;
|
|
231
|
+
"hx.session.harness.set": HxSessionHarnessSetResult;
|
|
232
|
+
"hx.workspace.get": HxWorkspaceGetResult;
|
|
233
|
+
"hx.workspace.integrate": HxWorkspaceIntegrateResult;
|
|
234
|
+
"hx.workspace.discard": HxWorkspaceDiscardResult;
|
|
235
|
+
"hx.usage.get": HxUsageGetResult;
|
|
236
|
+
"hx.transcript.read": HxTranscriptReadResult;
|
|
237
|
+
"hx.catalog.get": HxCatalogGetResult;
|
|
238
|
+
"hx.catalog.refresh": HxCatalogRefreshResult;
|
|
239
|
+
"hx.subagents.list": HxSubagentsListResult;
|
|
240
|
+
"hx.subagents.history": HxSubagentsHistoryResult;
|
|
241
|
+
}
|
|
242
|
+
export type HxMethod = keyof HxRequestMap;
|
|
243
|
+
export const HX_METHODS = ["hx.initialize","hx.harness.list","hx.harness.models","hx.session.create","hx.session.get","hx.session.list","hx.session.open","hx.session.close","hx.session.archive","hx.session.restore","hx.session.config.set","hx.session.fork","hx.session.revert","hx.session.reconcile","hx.history.read","hx.turn.start","hx.turn.steer","hx.turn.interrupt","hx.interaction.list","hx.interaction.private.get","hx.interaction.respond","hx.interaction.cancel","hx.goal.set","hx.goal.clear","hx.compact.start","hx.review.start","hx.operation.get","hx.events.read","hx.projection.snapshot","hx.events.subscribe","hx.events.unsubscribe","hx.queue.get","hx.queue.enqueue","hx.queue.update","hx.queue.remove","hx.queue.reorder","hx.queue.clear","hx.queue.pause","hx.queue.resume","hx.queue.run","hx.queue.steer","hx.queue.retry","hx.session.harness.set","hx.workspace.get","hx.workspace.integrate","hx.workspace.discard","hx.usage.get","hx.transcript.read","hx.catalog.get","hx.catalog.refresh","hx.subagents.list","hx.subagents.history"] as const;
|
|
244
|
+
export const HX_DEFINITIONS = {"hx.initialize":["HxInitializeParams","HxInitializeResult"],"hx.harness.list":["HxHarnessListParams","HxHarnessListResult"],"hx.harness.models":["HxHarnessModelsParams","HxHarnessModelsResult"],"hx.session.create":["HxSessionCreateParams","HxSessionCreateResult"],"hx.session.get":["HxSessionGetParams","HxSessionGetResult"],"hx.session.list":["HxSessionListParams","HxSessionListResult"],"hx.session.open":["HxSessionOpenParams","HxSessionOpenResult"],"hx.session.close":["HxSessionCloseParams","HxSessionCloseResult"],"hx.session.archive":["HxSessionArchiveParams","HxSessionArchiveResult"],"hx.session.restore":["HxSessionRestoreParams","HxSessionRestoreResult"],"hx.session.config.set":["HxSessionConfigSetParams","HxSessionConfigSetResult"],"hx.session.fork":["HxSessionForkParams","HxSessionForkResult"],"hx.session.revert":["HxSessionRevertParams","HxSessionRevertResult"],"hx.session.reconcile":["HxSessionReconcileParams","HxSessionReconcileResult"],"hx.history.read":["HxHistoryReadParams","HxHistoryReadResult"],"hx.turn.start":["HxTurnStartParams","HxTurnStartResult"],"hx.turn.steer":["HxTurnSteerParams","HxTurnSteerResult"],"hx.turn.interrupt":["HxTurnInterruptParams","HxTurnInterruptResult"],"hx.interaction.list":["HxInteractionListParams","HxInteractionListResult"],"hx.interaction.private.get":["HxInteractionPrivateGetParams","HxInteractionPrivateGetResult"],"hx.interaction.respond":["HxInteractionRespondParams","HxInteractionRespondResult"],"hx.interaction.cancel":["HxInteractionCancelParams","HxInteractionCancelResult"],"hx.goal.set":["HxGoalSetParams","HxGoalSetResult"],"hx.goal.clear":["HxGoalClearParams","HxGoalClearResult"],"hx.compact.start":["HxCompactStartParams","HxCompactStartResult"],"hx.review.start":["HxReviewStartParams","HxReviewStartResult"],"hx.operation.get":["HxOperationGetParams","HxOperationGetResult"],"hx.events.read":["HxEventsReadParams","HxEventsReadResult"],"hx.projection.snapshot":["HxProjectionSnapshotParams","HxProjectionSnapshotResult"],"hx.events.subscribe":["HxEventsSubscribeParams","HxEventsSubscribeResult"],"hx.events.unsubscribe":["HxEventsUnsubscribeParams","HxEventsUnsubscribeResult"],"hx.queue.get":["HxQueueGetParams","HxQueueGetResult"],"hx.queue.enqueue":["HxQueueEnqueueParams","HxQueueEnqueueResult"],"hx.queue.update":["HxQueueUpdateParams","HxQueueUpdateResult"],"hx.queue.remove":["HxQueueRemoveParams","HxQueueRemoveResult"],"hx.queue.reorder":["HxQueueReorderParams","HxQueueReorderResult"],"hx.queue.clear":["HxQueueClearParams","HxQueueClearResult"],"hx.queue.pause":["HxQueuePauseParams","HxQueuePauseResult"],"hx.queue.resume":["HxQueueResumeParams","HxQueueResumeResult"],"hx.queue.run":["HxQueueRunParams","HxQueueRunResult"],"hx.queue.steer":["HxQueueSteerParams","HxQueueSteerResult"],"hx.queue.retry":["HxQueueRetryParams","HxQueueRetryResult"],"hx.session.harness.set":["HxSessionHarnessSetParams","HxSessionHarnessSetResult"],"hx.workspace.get":["HxWorkspaceGetParams","HxWorkspaceGetResult"],"hx.workspace.integrate":["HxWorkspaceIntegrateParams","HxWorkspaceIntegrateResult"],"hx.workspace.discard":["HxWorkspaceDiscardParams","HxWorkspaceDiscardResult"],"hx.usage.get":["HxUsageGetParams","HxUsageGetResult"],"hx.transcript.read":["HxTranscriptReadParams","HxTranscriptReadResult"],"hx.catalog.get":["HxCatalogGetParams","HxCatalogGetResult"],"hx.catalog.refresh":["HxCatalogRefreshParams","HxCatalogRefreshResult"],"hx.subagents.list":["HxSubagentsListParams","HxSubagentsListResult"],"hx.subagents.history":["HxSubagentsHistoryParams","HxSubagentsHistoryResult"]} as const;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import Ajv2020, { type ValidateFunction } from "ajv/dist/2020.js";
|
|
2
|
+
import ahpSchema from "@anureo/protocol/schema";
|
|
3
|
+
import schema from "../../schema/v1/hx.schema.json";
|
|
4
|
+
import { HX_DEFINITIONS, type HxMethod, type HxRequestMap, type HxResultMap } from "./generated/types";
|
|
5
|
+
export * from "./generated/types";
|
|
6
|
+
export { schema as hxSchema };
|
|
7
|
+
|
|
8
|
+
// 浏览器首屏不应在模块加载时就编译 JSON Schema 2020 元 schema(约 80ms 主线程):
|
|
9
|
+
// 延迟到第一次校验时再创建 Ajv;两份 schema 均为构建期生成并由测试覆盖,因此跳过运行时的 schema 自校验。
|
|
10
|
+
let ajvInstance:Ajv2020|undefined;
|
|
11
|
+
function getAjv():Ajv2020 {
|
|
12
|
+
if(!ajvInstance){
|
|
13
|
+
ajvInstance=new Ajv2020({strict:false,allErrors:true,validateSchema:false});
|
|
14
|
+
ajvInstance.addSchema(ahpSchema);ajvInstance.addSchema(schema);
|
|
15
|
+
}
|
|
16
|
+
return ajvInstance;
|
|
17
|
+
}
|
|
18
|
+
const cache=new Map<string,ValidateFunction>();
|
|
19
|
+
export class HxContractError extends Error {
|
|
20
|
+
readonly code="INVALID_PARAMS";
|
|
21
|
+
constructor(readonly method:string){super(`Invalid hx contract: ${method}`);}
|
|
22
|
+
}
|
|
23
|
+
function check(name:string,value:unknown):void {
|
|
24
|
+
let validate=cache.get(name);
|
|
25
|
+
if(!validate){validate=getAjv().compile({$ref:`${schema.$id}#/$defs/${name}`});cache.set(name,validate);}
|
|
26
|
+
if(!validate(value))throw new HxContractError(name);
|
|
27
|
+
}
|
|
28
|
+
export function isHxMethod(value:string):value is HxMethod{return Object.hasOwn(HX_DEFINITIONS,value);}
|
|
29
|
+
export function validateHxRequest<M extends HxMethod>(method:M,value:unknown):asserts value is HxRequestMap[M] {check(HX_DEFINITIONS[method][0],value);}
|
|
30
|
+
export function validateHxResult<M extends HxMethod>(method:M,value:unknown):asserts value is HxResultMap[M] {check(HX_DEFINITIONS[method][1],value);}
|
|
31
|
+
export function validateHostEvent(value:unknown):void {check("HostEvent",value);}
|
|
32
|
+
export function validateSubscriptionError(value:unknown):void {check("SubscriptionError",value);}
|
|
33
|
+
export function validateSessionListSummaryPage(value:unknown):void {check("HostSessionListSummaryPage",value);}
|
|
34
|
+
|
|
35
|
+
export function validateHarnessChanged(value:unknown):void {check("HxHarnessChangedParams",value);}
|
|
36
|
+
|
|
37
|
+
export function validateCatalogChanged(value:unknown):void {check("HxCatalogChangedParams",value);}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Item, JsonObject, SubagentItem } from '@anureo/protocol'
|
|
2
|
+
|
|
3
|
+
/** Recover only the structured native fallback emitted by older Codex adapters. */
|
|
4
|
+
export function nativeSubagentActivity(item: Item): SubagentItem | undefined {
|
|
5
|
+
if (item.type !== 'toolCall' || item.kind !== 'other' || item.nativeType !== 'subAgentActivity') return
|
|
6
|
+
const raw = item.raw
|
|
7
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || raw.type !== 'subAgentActivity'
|
|
8
|
+
|| raw.id !== item.id || typeof raw.agentThreadId !== 'string' || !raw.agentThreadId) return
|
|
9
|
+
const name = typeof raw.agentPath === 'string' ? raw.agentPath.split('/').filter(Boolean).at(-1) : undefined
|
|
10
|
+
const evidence: JsonObject = {}
|
|
11
|
+
for (const key of ['kind', 'agentPath', 'model', 'reasoningEffort']) if (typeof raw[key] === 'string') evidence[key] = raw[key]
|
|
12
|
+
return {
|
|
13
|
+
id: item.id, type: 'subagent', subagentId: raw.agentThreadId,
|
|
14
|
+
...(item.status ? { status: item.status } : {}), ...(item.startedAt ? { startedAt: item.startedAt } : {}),
|
|
15
|
+
...(item.durationMs !== undefined ? { durationMs: item.durationMs } : {}),
|
|
16
|
+
state: raw.kind === 'completed' ? 'completed' : raw.kind === 'interrupted' ? 'interrupted' : 'running',
|
|
17
|
+
...(name ? { name } : {}), extensions: { ...item.extensions, native: evidence },
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { SecretRedactor } from "@anureo/sdk";
|
|
2
|
+
import type { AhpEventPayload,JsonValue } from "@anureo/protocol";
|
|
3
|
+
import type { HarnessStore } from "./store";
|
|
4
|
+
import { HostError } from "./errors";
|
|
5
|
+
|
|
6
|
+
/** Only irreversible keyed hints persist; raw answers and their delta tails remain in memory. */
|
|
7
|
+
export class PersistentSecretRedactor extends SecretRedactor {
|
|
8
|
+
private readonly tails=new Map<string,string>();
|
|
9
|
+
private bytes=0;
|
|
10
|
+
constructor(private readonly store:HarnessStore,private readonly sessionId:string){super(value=>store.rememberPrivate(sessionId,value));}
|
|
11
|
+
override text(value:string):string{return this.store.scanPrivate(this.sessionId,value).text;}
|
|
12
|
+
override json(value:JsonValue):JsonValue {
|
|
13
|
+
if((typeof value==="number"||typeof value==="boolean")&&this.store.scanPrivate(this.sessionId,String(value)).text!==String(value))return "[redacted]";
|
|
14
|
+
return super.json(value);
|
|
15
|
+
}
|
|
16
|
+
override delta(stream:string,value:string):string {
|
|
17
|
+
const old=this.tails.get(stream)??"",result=this.store.scanPrivate(this.sessionId,old+value,false);
|
|
18
|
+
const bytes=new TextEncoder().encode(result.pending).byteLength-new TextEncoder().encode(old).byteLength;
|
|
19
|
+
if(this.bytes+bytes>16*1024*1024||(!this.tails.has(stream)&&result.pending&&this.tails.size>=2048))throw new HostError("BACKPRESSURE_EXCEEDED");
|
|
20
|
+
this.bytes+=bytes;
|
|
21
|
+
if(result.pending)this.tails.set(stream,result.pending);else this.tails.delete(stream);
|
|
22
|
+
return result.text;
|
|
23
|
+
}
|
|
24
|
+
override event(event:AhpEventPayload,turnId?:string):AhpEventPayload {
|
|
25
|
+
if(event.type==="item/completed"){
|
|
26
|
+
const itemId=event.payload.item.id;
|
|
27
|
+
const key=turnId===undefined?itemId:JSON.stringify([turnId,itemId]);
|
|
28
|
+
const tail=this.tails.get(key);
|
|
29
|
+
if(tail){this.bytes-=new TextEncoder().encode(tail).byteLength;this.tails.delete(key);}
|
|
30
|
+
}
|
|
31
|
+
if(event.type==="turn/completed"){this.tails.clear();this.bytes=0;}
|
|
32
|
+
return super.event(event,turnId);
|
|
33
|
+
}
|
|
34
|
+
}
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { validateHxRequest, validateHxResult, validateSessionListSummaryPage, type HostSessionListSummary, type HostSessionListSummaryPage, type HxMethod, type HxRequestMap, type HxResultMap, type PublicSession } from './legacy-protocol'
|
|
2
|
+
export { HX_METHODS, isHxMethod, validateHostEvent, validateSubscriptionError } from './legacy-protocol'
|
|
3
|
+
export type { HxMethod, HostEvent, EventPage, OperationResult } from './legacy-protocol'
|
|
4
|
+
|
|
5
|
+
export interface SessionListParams {
|
|
6
|
+
scopeId: string
|
|
7
|
+
archived?: boolean
|
|
8
|
+
cursor?: string
|
|
9
|
+
limit?: number
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type SessionSummary = HostSessionListSummary
|
|
13
|
+
export type SessionListResult = HostSessionListSummaryPage
|
|
14
|
+
|
|
15
|
+
type Scope<T> = {
|
|
16
|
+
[Property in keyof T as Property extends 'projectId' ? 'scopeId' : Property]: T[Property]
|
|
17
|
+
}
|
|
18
|
+
export type HostRequestMap = { [Method in HxMethod]: Scope<HxRequestMap[Method]> }
|
|
19
|
+
export type HostResultMap = Omit<{ [Method in HxMethod]: Scope<HxResultMap[Method]> }, 'hx.session.list' | 'hx.session.reconcile'> & {
|
|
20
|
+
'hx.session.list': SessionListResult
|
|
21
|
+
'hx.session.reconcile': Omit<HxResultMap['hx.session.reconcile'], 'session'> & { session: Scope<PublicSession> }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function validateHostRequest<Method extends HxMethod>(method: Method, params: unknown): asserts params is HostRequestMap[Method] {
|
|
25
|
+
validateHxRequest(method, scopeParams(params))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function validateHostResult<Method extends HxMethod>(method: Method, result: unknown): asserts result is HostResultMap[Method] {
|
|
29
|
+
if (method === 'hx.session.list') {
|
|
30
|
+
validateSessionListSummaryPage(result)
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
if (method === 'hx.session.reconcile' && result && typeof result === 'object' && 'session' in result) {
|
|
34
|
+
validateHxResult(method, { ...result, session: scopeParams(result.session) })
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
validateHxResult(method, scopeParams(result))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Translate only protocol envelope fields. User content and metadata are opaque. */
|
|
41
|
+
export function scopeParams(params: unknown): unknown {
|
|
42
|
+
if (!params || typeof params !== 'object' || Array.isArray(params)) return params
|
|
43
|
+
if (Object.hasOwn(params, 'projectId')) throw new TypeError('The Host protocol accepts scopeId')
|
|
44
|
+
if (!('scopeId' in params)) return params
|
|
45
|
+
const { scopeId, ...rest } = params
|
|
46
|
+
return { ...rest, projectId: scopeId }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function scopeObject(value: unknown): unknown {
|
|
50
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || !('projectId' in value)) return value
|
|
51
|
+
const { projectId, ...rest } = value
|
|
52
|
+
return { ...rest, scopeId: projectId }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function sessionSummary({ id, projectId, title, status, runtimeConfigId, updatedAt, archived }: Pick<PublicSession, 'id' | 'projectId' | 'title' | 'status' | 'runtimeConfigId' | 'updatedAt' | 'archived'>): SessionSummary {
|
|
56
|
+
return { id, scopeId: projectId, ...(title === undefined ? {} : { title }), status, runtimeConfigId, ...(updatedAt === undefined ? {} : { updatedAt }), archived }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function scopeResult(result: unknown, method?: string): unknown {
|
|
60
|
+
if (!result || typeof result !== 'object' || Array.isArray(result)) return result
|
|
61
|
+
if (method === 'hx.session.list') {
|
|
62
|
+
const page = result as HxResultMap['hx.session.list']
|
|
63
|
+
return { sessions: page.sessions.map(sessionSummary), nextCursor: page.nextCursor }
|
|
64
|
+
}
|
|
65
|
+
if ('session' in result) return { ...result, session: scopeObject(result.session) }
|
|
66
|
+
if ('operationId' in result && 'result' in result) return { ...result, result: scopeObject(result.result) }
|
|
67
|
+
return scopeObject(result)
|
|
68
|
+
}
|
package/src/queue.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { InputBlock,JsonObject,JsonSchema } from '@anureo/protocol';
|
|
2
|
+
import type { HxQueueItem,HxQueueState } from './legacy-protocol';
|
|
3
|
+
/** The durable execution snapshot stays private; public input is the caller's original content. */
|
|
4
|
+
export type StoredQueueItem=HxQueueItem&{
|
|
5
|
+
executionInput:InputBlock[];configSnapshot:JsonObject;modelSnapshot?:string;runtimeConfigId:string;ownerId:string;
|
|
6
|
+
overrides?:JsonObject;outputSchema?:JsonSchema;
|
|
7
|
+
};
|
|
8
|
+
export type StoredQueueState=Omit<HxQueueState,'items'>&{items:StoredQueueItem[]};
|
|
9
|
+
export function publicQueue(state:StoredQueueState):HxQueueState {
|
|
10
|
+
return {revision:state.revision,paused:state.paused,items:state.items.map(({executionInput,configSnapshot,modelSnapshot,runtimeConfigId,ownerId,overrides,outputSchema,...item})=>item)};
|
|
11
|
+
}
|
|
12
|
+
export const queuePending=(item:HxQueueItem)=>!['completed','cancelled'].includes(item.state);
|
package/src/rpc.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface RpcRequest {
|
|
2
|
+
id: number | null
|
|
3
|
+
method: string
|
|
4
|
+
params?: unknown
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface RpcNotification {
|
|
8
|
+
jsonrpc: '2.0'
|
|
9
|
+
method: string
|
|
10
|
+
params: unknown
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type RpcResponse = { jsonrpc: '2.0'; id: number | null } & (
|
|
14
|
+
| { result: unknown; error?: never }
|
|
15
|
+
| { error: { code: number; message: string; data?: unknown }; result?: never }
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
export interface HostConnection<Actor> {
|
|
19
|
+
id: string
|
|
20
|
+
principal(): Actor | null
|
|
21
|
+
send(notification: RpcNotification): void | Promise<void>
|
|
22
|
+
close?(): void
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface HostDispatcher<Actor> {
|
|
26
|
+
handle(connection: HostConnection<Actor>, request: RpcRequest): RpcResponse | Promise<RpcResponse>
|
|
27
|
+
disconnect(connectionId: string): void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function rpcError(id: number | null, code: number, message: string): RpcResponse {
|
|
31
|
+
return { jsonrpc: '2.0', id, error: { code, message } }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function decodeRequest(text: string): RpcRequest | RpcResponse {
|
|
35
|
+
let value: unknown
|
|
36
|
+
try { value = JSON.parse(text) } catch { return rpcError(null, -32700, 'Parse error') }
|
|
37
|
+
if (!value || typeof value !== 'object' || !('jsonrpc' in value) || value.jsonrpc !== '2.0'
|
|
38
|
+
|| !('id' in value) || typeof value.id !== 'number' || !Number.isSafeInteger(value.id)
|
|
39
|
+
|| !('method' in value) || typeof value.method !== 'string' || !value.method) {
|
|
40
|
+
return rpcError(null, -32600, 'Invalid Request')
|
|
41
|
+
}
|
|
42
|
+
return { id: value.id, method: value.method, ...('params' in value ? { params: value.params } : {}) }
|
|
43
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { HarnessHost, type HostOptions, type Principal, type Role } from './host'
|
|
2
|
+
import { scopeParams, scopeResult } from './protocol'
|
|
3
|
+
import { rpcError, type HostConnection, type HostDispatcher } from './rpc'
|
|
4
|
+
|
|
5
|
+
export interface HostActor { userId: string }
|
|
6
|
+
|
|
7
|
+
export type HostAuthorizationPolicy = (actor: HostActor, scopeId: string, minimum: Role) => boolean | Promise<boolean>
|
|
8
|
+
|
|
9
|
+
export interface CreateHostOptions extends Omit<HostOptions, 'applicationAuthorization' | 'can' | 'projectRoot'> {
|
|
10
|
+
authorize: HostAuthorizationPolicy
|
|
11
|
+
resolveWorkspace: HostOptions['projectRoot']
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createHarnessHost({ authorize, resolveWorkspace, ...options }: CreateHostOptions): HarnessHost {
|
|
15
|
+
return new HarnessHost({ ...options, can: authorize, projectRoot: resolveWorkspace, applicationAuthorization: true })
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Use the SDK scope-based protocol on a new endpoint. Cowork can keep its existing wire contract. */
|
|
19
|
+
export function createScopedHostDispatcher(host: HarnessHost): HostDispatcher<HostActor> {
|
|
20
|
+
return {
|
|
21
|
+
async handle(connection, request) {
|
|
22
|
+
const scoped: HostConnection<Principal> = {
|
|
23
|
+
...connection,
|
|
24
|
+
principal() {
|
|
25
|
+
const actor = connection.principal()
|
|
26
|
+
return actor ? { userId: actor.userId, mode: 'on' } : null
|
|
27
|
+
},
|
|
28
|
+
send(notification) { return connection.send({ ...notification, params: scopeResult(notification.params) }) },
|
|
29
|
+
}
|
|
30
|
+
let params: unknown
|
|
31
|
+
try { params = scopeParams(request.params) }
|
|
32
|
+
catch { return rpcError(request.id, -32602, 'Invalid params') }
|
|
33
|
+
const response = await host.handle(scoped, { ...request, params })
|
|
34
|
+
if ('error' in response) return response
|
|
35
|
+
return { ...response, result: scopeResult(response.result, request.method) }
|
|
36
|
+
},
|
|
37
|
+
disconnect: id => host.disconnect(id),
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SqliteHostStore, type SqliteStoreHooks } from './store'
|
|
3
|
+
|
|
4
|
+
export class HarnessStore extends SqliteHostStore {
|
|
5
|
+
constructor(file: string, hooks?: SqliteStoreHooks) {
|
|
6
|
+
super(file, (path, readonly) => new Database(path, readonly ? { readonly: true } : { create: true }), hooks)
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function createSqliteHostStorage(file: string): SqliteHostStore {
|
|
11
|
+
return new HarnessStore(file)
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type SqliteValue = string | number | bigint | Uint8Array | null
|
|
2
|
+
|
|
3
|
+
export interface SqliteConnection {
|
|
4
|
+
exec(sql: string): unknown
|
|
5
|
+
query(sql: string): {
|
|
6
|
+
get(...values: SqliteValue[]): unknown
|
|
7
|
+
all(...values: SqliteValue[]): unknown[]
|
|
8
|
+
run(...values: SqliteValue[]): unknown
|
|
9
|
+
}
|
|
10
|
+
transaction<Result>(run: () => Result): () => Result
|
|
11
|
+
close(): void
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type OpenSqlite = (file: string, readOnly?: boolean) => SqliteConnection
|