@harness-gw/sdk 0.17.0 → 0.19.0

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 CHANGED
@@ -35,7 +35,8 @@ guest ── invite link ──────► guest listener ─────
35
35
  permission requests and elicitations, and answer back the same way.
36
36
  - **MCP Apps.** Tool results that carry a `ui://` view are served to the client
37
37
  through the gateway, scoped to the tool call's own Session.
38
- - **Attachments, Artifacts, voice and Web Push** over plain HTTP routes.
38
+ - **Attachments, Artifacts, voice and push** (Web Push and APNs) over plain
39
+ HTTP routes.
39
40
  - **A framework-free browser SDK.** No React, no browser globals: location,
40
41
  storage, page visibility and logging arrive as options.
41
42
  - **Origin-checked by default.** Each listener admits only its listed browser
@@ -63,7 +64,7 @@ You need a running harness. Hermes is the primary one; see
63
64
  docker run --rm \
64
65
  -v "$PWD/config.yaml:/run/harness-gw/config.yaml:ro" \
65
66
  -v "$PWD/hermes-token:/run/secrets/hermes-token:ro" \
66
- ghcr.io/almogbaku/harness-gw:0.17.0 \
67
+ ghcr.io/almogbaku/harness-gw:0.19.0 \
67
68
  config check --config /run/harness-gw/config.yaml
68
69
  ```
69
70
 
@@ -73,7 +74,7 @@ You need a running harness. Hermes is the primary one; see
73
74
  docker run --rm -p 127.0.0.1:4100:4100 \
74
75
  -v "$PWD/config.yaml:/run/harness-gw/config.yaml:ro" \
75
76
  -v "$PWD/hermes-token:/run/secrets/hermes-token:ro" \
76
- ghcr.io/almogbaku/harness-gw:0.17.0 \
77
+ ghcr.io/almogbaku/harness-gw:0.19.0 \
77
78
  serve --config /run/harness-gw/config.yaml
78
79
  ```
79
80
 
@@ -103,17 +103,20 @@ function isMcpAppPolicyOrigin2(value) {
103
103
  return false;
104
104
  }
105
105
  }
106
+ var MCP_APP_BUNDLED_PAGE_ORIGIN2 = "tauri://localhost";
107
+ function isMcpAppFramingOrigin2(value) {
108
+ return value === MCP_APP_BUNDLED_PAGE_ORIGIN2 || isMcpAppPolicyOrigin2(value);
109
+ }
106
110
  function ownHosts({
107
111
  frameAncestors,
108
112
  sandboxOrigin
109
113
  }) {
110
- const origins = [...frameAncestors, sandboxOrigin];
111
- const invalid = origins.find((origin) => !isMcpAppPolicyOrigin2(origin));
114
+ const invalid = frameAncestors.find((origin) => !isMcpAppFramingOrigin2(origin)) ?? (isMcpAppPolicyOrigin2(sandboxOrigin) ? undefined : sandboxOrigin);
112
115
  if (invalid !== undefined)
113
116
  throw new Error(`Not an exact origin a sandbox policy can name: ${invalid}`);
114
117
  if (frameAncestors.includes(sandboxOrigin))
115
118
  throw new Error(`The sandbox origin is one of the host's: ${sandboxOrigin}`);
116
- return new Set(origins.map((origin) => new URL(origin).host));
119
+ return new Set([...frameAncestors, sandboxOrigin].filter((origin) => origin !== MCP_APP_BUNDLED_PAGE_ORIGIN2).map((origin) => new URL(origin).host));
117
120
  }
118
121
  function namesHost(domain, hosts) {
119
122
  try {
@@ -906,7 +909,7 @@ function hgwAcpAgentPath2(agentId) {
906
909
  return `${HGW_ACP_AGENTS_PATH2}/${encodeURIComponent(agentId)}`;
907
910
  }
908
911
  var HGW_META_KEY2 = "hgw";
909
- var HGW_EXTENSION_VERSION2 = 3;
912
+ var HGW_EXTENSION_VERSION2 = 4;
910
913
  var HGW_AUTH_METHOD_INVITE2 = "hgw-invite";
911
914
  var HGW_ATTACHMENT_URI_SCHEME2 = "hgw-attachment:";
912
915
  var HGW_ARTIFACT_URI_SCHEME2 = "artifact:";
@@ -1086,6 +1089,13 @@ var HgwMessageMetaSchema2 = readObject({
1086
1089
  kind: NoticeKindSchema.optional()
1087
1090
  }).optional()
1088
1091
  });
1092
+ var HgwMessageFailureMetaSchema2 = readObject({
1093
+ failure: readObject({
1094
+ message: z3.string().min(1).max(4096),
1095
+ code: z3.string().min(1).max(128).optional(),
1096
+ at: z3.iso.datetime().optional()
1097
+ })
1098
+ });
1089
1099
  var CountSchema = z3.number().int().nonnegative();
1090
1100
  var HgwCostSchema2 = readObject({
1091
1101
  amount: z3.number().nonnegative(),
@@ -1276,20 +1286,44 @@ var PushSubscriptionJsonSchema2 = z4.strictObject({
1276
1286
  auth: Base64UrlSchema.length(22)
1277
1287
  })
1278
1288
  });
1289
+ var apnsAvailability = { apns: z4.literal(true).optional() };
1279
1290
  var PushInfoSchema2 = z4.discriminatedUnion("status", [
1280
- z4.strictObject({ status: z4.literal("not-configured") }),
1291
+ z4.strictObject({ status: z4.literal("not-configured"), ...apnsAvailability }),
1281
1292
  z4.strictObject({
1282
1293
  status: z4.literal("available"),
1283
- publicKey: Base64UrlSchema.length(87)
1294
+ publicKey: Base64UrlSchema.length(87),
1295
+ ...apnsAvailability
1284
1296
  })
1285
1297
  ]);
1286
- var PushRegistrationSchema2 = z4.strictObject({
1287
- subscription: PushSubscriptionJsonSchema2,
1298
+ var devicePreferences = {
1288
1299
  locale: PushLocaleSchema2,
1289
1300
  categories: PushCategoriesSchema2
1290
- });
1291
- var PushUnregistrationSchema2 = z4.strictObject({
1292
- endpoint: z4.string().max(2048)
1293
- });
1301
+ };
1302
+ var WebPushRegistrationSchema2 = z4.strictObject({
1303
+ transport: z4.literal("web-push").optional(),
1304
+ subscription: PushSubscriptionJsonSchema2,
1305
+ ...devicePreferences
1306
+ });
1307
+ var ApnsDeviceTokenSchema2 = z4.string().regex(/^(?:[0-9a-f]{2}){32,100}$/iu).toLowerCase();
1308
+ var ApnsRegistrationSchema2 = z4.strictObject({
1309
+ transport: z4.literal("apns"),
1310
+ token: ApnsDeviceTokenSchema2,
1311
+ environment: z4.enum(["sandbox", "production"]),
1312
+ ...devicePreferences
1313
+ });
1314
+ var PushRegistrationSchema2 = z4.discriminatedUnion("transport", [
1315
+ WebPushRegistrationSchema2,
1316
+ ApnsRegistrationSchema2
1317
+ ]);
1318
+ var PushUnregistrationSchema2 = z4.discriminatedUnion("transport", [
1319
+ z4.strictObject({
1320
+ transport: z4.literal("web-push").optional(),
1321
+ endpoint: z4.string().max(2048)
1322
+ }),
1323
+ z4.strictObject({
1324
+ transport: z4.literal("apns"),
1325
+ token: ApnsDeviceTokenSchema2
1326
+ })
1327
+ ]);
1294
1328
 
1295
- export { CallToolResultSchema2, EmptyResultSchema2, ReadResourceResultSchema2, McpUiCspSchema2, isMcpAppCspDomain2, McpUiPermissionsSchema2, McpAppFilesSchema2, McpUiDomainSchema2, McpAppViewSchema2, viewerFileResult2, McpAppToolCallRequestSchema2, McpAppResourceReadRequestSchema2, McpAppModelContextRequestSchema2, MAX_MCP_APP_FILE_BYTES2, McpAppFileReadFailureSchema2, McpAppFileReadErrorDataSchema2, MCP_APP_SANDBOX_PATH2, isMcpAppPolicyOrigin2, appliedMcpAppCsp2, mcpAppSandboxPolicy2, SESSION_CATALOG_MAX_WINDOW2, RuntimeAuthStateSchema2, OperationCapabilitySchema2, RuntimeInfoSchema2, AgentAvatarSchema2, AgentCatalogEntrySchema2, AgentCatalogResponseSchema2, AgentUpdateFields2, writesAgentField2, AgentUpdateRequestSchema2, AgentUpdateResponseSchema2, SessionStatusSchema2, SessionPlatformSchema2, SessionSchema2, newestSessionFirst2, SessionCatalogResponseSchema2, StopReason2, ToolKind2, ToolLocationSchema2, DiffOperation2, DiffChangeSchema2, ToolDiffSchema2, SessionMessageErrorStatusSchema2, SessionMessageSchema2, SessionPlanActivityMessageSchema2, SessionCompactionActivityMessageSchema2, SessionChildActivityMessageSchema2, SessionActivityMessageSchema2, SessionHistoryResponseSchema2, SessionCreateRequestSchema2, SessionCreateResponseSchema2, SessionPatchRequestSchema2, TurnStopResponseSchema2, TurnSteerRequestSchema2, TurnSteerResponseSchema2, SlashCommandSchema2, MAX_SLASH_COMMANDS2, INTERACTION_PROTOCOL2, SessionWorkspaceCapabilitiesResponseSchema2, GuestRuntimeCapabilitiesResponseSchema2, SessionModelsResponseSchema2, SessionModelUpdateRequestSchema2, SessionModelUpdateResponseSchema2, SessionContextResponseSchema2, ArtifactDescriptorSchema2, SessionTodosResponseSchema2, SessionActivityResponseSchema2, SessionAttachmentStageRequestSchema2, SessionAttachmentStageResponseSchema2, SessionAudioResponseSchema2, SessionTranscriptionRequestSchema2, SessionTranscriptionResponseSchema2, SessionSpeechRequestSchema2, ErrorResponseSchema2, ACP_PROTOCOL_VERSION2, HGW_API_PREFIX2, HGW_ACP_PATH2, HGW_ACP_AGENTS_PATH2, hgwAcpAgentPath2, HGW_META_KEY2, HGW_EXTENSION_VERSION2, HGW_AUTH_METHOD_INVITE2, HGW_ATTACHMENT_URI_SCHEME2, HGW_ARTIFACT_URI_SCHEME2, HGW_METHODS2, HGW_PERMISSION_KIND_SESSION2, HGW_PLAN_ID2, HGW_JSONRPC_ERRORS2, HGW_MAX_FRAME_BYTES2, IdentifierSchema2, HgwExtensionsSchema2, HgwClientCapabilitiesMetaSchema2, HgwInitializeMetaSchema2, HgwLoginMetaSchema2, HgwSessionNewMetaSchema2, HgwSessionListMetaSchema2, HgwSessionSearchMetaSchema2, HgwSessionSearchResponseSchema2, HgwSessionInfoMetaSchema2, HgwSessionResumeMetaSchema2, HGW_REPLAY_POSITION2, HgwReplayPositionSchema2, HGW_REPLAY_BEFORE2, HgwReplayBeforeSchema2, HgwHistoryCursorSchema2, HgwHistoryPageResponseMetaSchema2, HgwHistoryPageTagSchema2, HgwSessionSetupResponseMetaSchema2, HgwSessionResumeResponseMetaSchema2, HgwPromptMetaSchema2, HgwSessionUpdateRequestSchema2, HgwSessionPartRequestSchema2, HgwSteerRequestSchema2, HgwSteerResponseSchema2, HgwFocusRequestSchema2, HgwAgentsListResponseSchema2, HgwAgentUpdateRequestSchema2, HgwAgentUpdateResponseSchema2, HgwTurnMetaSchema2, HgwNoticeMetaSchema2, HgwMessageMetaSchema2, HgwCostSchema2, HgwChildSessionMetaSchema2, HgwStateMetaSchema2, HgwChunkMetaSchema2, HgwToolCallMetaSchema2, HgwPlanMetaSchema2, HgwUsageMetaSchema2, HgwAvailableCommandsMetaSchema2, HgwPermissionMetaSchema2, HgwQuestionOptionSchema2, HgwQuestionSchema2, HgwElicitationMetaSchema2, HgwArtifactDescriptorSchema2, formatArtifactUri2, parseArtifactUri2, HgwComposerPrefillNotificationSchema2, HgwErrorNotificationSchema2, HGW_REQUEST_TEXT_MAX2, HgwActivityNotificationSchema2, PushCategorySchema2, categoryOf2, PushLocaleSchema2, PRESENCE_IDLE_MS2, PRESENCE_HEARTBEAT_MS2, PRESENCE_GRACE_MS2, PRESENCE_CLOSED_GRACE_MS2, COALESCE_WINDOW_MS2, PUSH_TEXT_LIMITS2, PushMessageSchema2, PushCategoriesSchema2, PushSubscriptionJsonSchema2, PushInfoSchema2, PushRegistrationSchema2, PushUnregistrationSchema2 };
1329
+ export { CallToolResultSchema2, EmptyResultSchema2, ReadResourceResultSchema2, McpUiCspSchema2, isMcpAppCspDomain2, McpUiPermissionsSchema2, McpAppFilesSchema2, McpUiDomainSchema2, McpAppViewSchema2, viewerFileResult2, McpAppToolCallRequestSchema2, McpAppResourceReadRequestSchema2, McpAppModelContextRequestSchema2, MAX_MCP_APP_FILE_BYTES2, McpAppFileReadFailureSchema2, McpAppFileReadErrorDataSchema2, MCP_APP_SANDBOX_PATH2, isMcpAppPolicyOrigin2, MCP_APP_BUNDLED_PAGE_ORIGIN2, isMcpAppFramingOrigin2, appliedMcpAppCsp2, mcpAppSandboxPolicy2, SESSION_CATALOG_MAX_WINDOW2, RuntimeAuthStateSchema2, OperationCapabilitySchema2, RuntimeInfoSchema2, AgentAvatarSchema2, AgentCatalogEntrySchema2, AgentCatalogResponseSchema2, AgentUpdateFields2, writesAgentField2, AgentUpdateRequestSchema2, AgentUpdateResponseSchema2, SessionStatusSchema2, SessionPlatformSchema2, SessionSchema2, newestSessionFirst2, SessionCatalogResponseSchema2, StopReason2, ToolKind2, ToolLocationSchema2, DiffOperation2, DiffChangeSchema2, ToolDiffSchema2, SessionMessageErrorStatusSchema2, SessionMessageSchema2, SessionPlanActivityMessageSchema2, SessionCompactionActivityMessageSchema2, SessionChildActivityMessageSchema2, SessionActivityMessageSchema2, SessionHistoryResponseSchema2, SessionCreateRequestSchema2, SessionCreateResponseSchema2, SessionPatchRequestSchema2, TurnStopResponseSchema2, TurnSteerRequestSchema2, TurnSteerResponseSchema2, SlashCommandSchema2, MAX_SLASH_COMMANDS2, INTERACTION_PROTOCOL2, SessionWorkspaceCapabilitiesResponseSchema2, GuestRuntimeCapabilitiesResponseSchema2, SessionModelsResponseSchema2, SessionModelUpdateRequestSchema2, SessionModelUpdateResponseSchema2, SessionContextResponseSchema2, ArtifactDescriptorSchema2, SessionTodosResponseSchema2, SessionActivityResponseSchema2, SessionAttachmentStageRequestSchema2, SessionAttachmentStageResponseSchema2, SessionAudioResponseSchema2, SessionTranscriptionRequestSchema2, SessionTranscriptionResponseSchema2, SessionSpeechRequestSchema2, ErrorResponseSchema2, ACP_PROTOCOL_VERSION2, HGW_API_PREFIX2, HGW_ACP_PATH2, HGW_ACP_AGENTS_PATH2, hgwAcpAgentPath2, HGW_META_KEY2, HGW_EXTENSION_VERSION2, HGW_AUTH_METHOD_INVITE2, HGW_ATTACHMENT_URI_SCHEME2, HGW_ARTIFACT_URI_SCHEME2, HGW_METHODS2, HGW_PERMISSION_KIND_SESSION2, HGW_PLAN_ID2, HGW_JSONRPC_ERRORS2, HGW_MAX_FRAME_BYTES2, IdentifierSchema2, HgwExtensionsSchema2, HgwClientCapabilitiesMetaSchema2, HgwInitializeMetaSchema2, HgwLoginMetaSchema2, HgwSessionNewMetaSchema2, HgwSessionListMetaSchema2, HgwSessionSearchMetaSchema2, HgwSessionSearchResponseSchema2, HgwSessionInfoMetaSchema2, HgwSessionResumeMetaSchema2, HGW_REPLAY_POSITION2, HgwReplayPositionSchema2, HGW_REPLAY_BEFORE2, HgwReplayBeforeSchema2, HgwHistoryCursorSchema2, HgwHistoryPageResponseMetaSchema2, HgwHistoryPageTagSchema2, HgwSessionSetupResponseMetaSchema2, HgwSessionResumeResponseMetaSchema2, HgwPromptMetaSchema2, HgwSessionUpdateRequestSchema2, HgwSessionPartRequestSchema2, HgwSteerRequestSchema2, HgwSteerResponseSchema2, HgwFocusRequestSchema2, HgwAgentsListResponseSchema2, HgwAgentUpdateRequestSchema2, HgwAgentUpdateResponseSchema2, HgwTurnMetaSchema2, HgwNoticeMetaSchema2, HgwMessageMetaSchema2, HgwMessageFailureMetaSchema2, HgwCostSchema2, HgwChildSessionMetaSchema2, HgwStateMetaSchema2, HgwChunkMetaSchema2, HgwToolCallMetaSchema2, HgwPlanMetaSchema2, HgwUsageMetaSchema2, HgwAvailableCommandsMetaSchema2, HgwPermissionMetaSchema2, HgwQuestionOptionSchema2, HgwQuestionSchema2, HgwElicitationMetaSchema2, HgwArtifactDescriptorSchema2, formatArtifactUri2, parseArtifactUri2, HgwComposerPrefillNotificationSchema2, HgwErrorNotificationSchema2, HGW_REQUEST_TEXT_MAX2, HgwActivityNotificationSchema2, PushCategorySchema2, categoryOf2, PushLocaleSchema2, PRESENCE_IDLE_MS2, PRESENCE_HEARTBEAT_MS2, PRESENCE_GRACE_MS2, PRESENCE_CLOSED_GRACE_MS2, COALESCE_WINDOW_MS2, PUSH_TEXT_LIMITS2, PushMessageSchema2, PushCategoriesSchema2, PushSubscriptionJsonSchema2, PushInfoSchema2, WebPushRegistrationSchema2, ApnsDeviceTokenSchema2, ApnsRegistrationSchema2, PushRegistrationSchema2, PushUnregistrationSchema2 };
@@ -134,15 +134,15 @@ export declare function createAcpWorkspaceClient({ connection, rest, agentIdFor,
134
134
  workspaceCapabilities: (sessionId: string) => {
135
135
  workspace: {
136
136
  slashCommands: {
137
- status: "unavailable";
138
- reason: string;
139
- } | {
140
137
  status: "available";
141
138
  scope: "session";
142
139
  commands: {
143
140
  name: string;
144
141
  description?: string | undefined;
145
142
  }[];
143
+ } | {
144
+ status: "unavailable";
145
+ reason: string;
146
146
  };
147
147
  models: {
148
148
  status: "unavailable";
@@ -104,6 +104,11 @@ export type ConnectionMachineDeps = {
104
104
  export declare function connectionMachine({ open, handshake, recover, inProcess, closeTransport, markReady, lose, logger, clock, }: ConnectionMachineDeps): import("xstate").StateMachine<{
105
105
  generation: number;
106
106
  attempt: number;
107
+ /** When the transport last recovered, and the attempt it started over. */
108
+ recovered?: {
109
+ at: number;
110
+ attempt: number;
111
+ };
107
112
  }, ConnectionEvent, {
108
113
  [x: string]: import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<unknown, import("xstate").NonReducibleUnknown, import("xstate").EventObject> | import("xstate").PromiseActorLogic<void, import("xstate").NonReducibleUnknown, import("xstate").EventObject>> | undefined;
109
114
  }, {
@@ -143,6 +148,9 @@ export declare function connectionMachine({ open, handshake, recover, inProcess,
143
148
  } | {
144
149
  type: "countAttempt";
145
150
  params: undefined;
151
+ } | {
152
+ type: "keepBackoff";
153
+ params: undefined;
146
154
  } | {
147
155
  type: "logTransition";
148
156
  params: {
@@ -160,7 +168,13 @@ export declare function connectionMachine({ open, handshake, recover, inProcess,
160
168
  } | {
161
169
  type: "resetAttempts";
162
170
  params: undefined;
171
+ } | {
172
+ type: "startOver";
173
+ params: undefined;
163
174
  }, {
175
+ type: "fellBehindAgain";
176
+ params: unknown;
177
+ } | {
164
178
  type: "inProcess";
165
179
  params: unknown;
166
180
  } | {
@@ -1,6 +1,6 @@
1
1
  import type { z } from "zod";
2
2
  import { SessionContextResponseSchema, SessionModelsResponseSchema, SessionWorkspaceCapabilitiesResponseSchema } from "../protocol/index.js";
3
- import { type PushRegistration } from "../protocol/push.js";
3
+ import { type PushRegistration, type PushUnregistration } from "../protocol/push.js";
4
4
  import { type McpAppFileReadFailure, type McpAppModelContextRequest, type McpAppResourceReadRequest, type McpAppToolCallRequest } from "../protocol/mcp-apps.js";
5
5
  import type { StagedAttachment } from "./workspace.js";
6
6
  export type HgwWorkspaceCapabilities = z.infer<typeof SessionWorkspaceCapabilitiesResponseSchema>;
@@ -164,14 +164,20 @@ export declare class HgwRemoteClient {
164
164
  }>;
165
165
  /** What this deployment offers for alerts while no tab is open. */
166
166
  pushInfo(signal?: AbortSignal): Promise<{
167
+ apns?: true | undefined;
167
168
  status: "not-configured";
168
169
  } | {
170
+ apns?: true | undefined;
169
171
  status: "available";
170
172
  publicKey: string;
171
173
  }>;
172
- /** Registering the same endpoint again is how a preference change travels. */
174
+ /**
175
+ * Registering the same device again is how a preference change travels. A
176
+ * registration naming no `transport` is a browser's, through Web Push.
177
+ */
173
178
  putPushSubscription(registration: PushRegistration): Promise<void>;
174
- deletePushSubscription(endpoint: string): Promise<void>;
179
+ /** Names the device by its transport's own key: an endpoint, or a token. */
180
+ deletePushSubscription(device: PushUnregistration): Promise<void>;
175
181
  /** REST authorizes byte routes per Agent, so every Session names its owner. */
176
182
  adoptSessionOwnership(sessionId: string, agentId: string): void;
177
183
  stageAttachments(sessionId: string, attachments: readonly StagedAttachment[]): Promise<{
@@ -1,6 +1,6 @@
1
1
  /** `@harness-gw/sdk`: the browser client for the gateway's ACP and HTTP APIs. */
2
2
  export { acpSocketUrl, createAcpConnection, isAuthenticationRequired, SILENT_LOGGER, type AcpConnectionOptions, type OwnerInspector, type PageSignals, } from "./connection.js";
3
- export type { AcpConnection, AcpConnectionOutage, AcpConnectionStatus, AcpHistoryPage, AcpPendingRequest, AcpSessionListener, AcpSessionReplayListener, AcpSessionSetup, AcpSessionState, AcpSessionUpdateListener, } from "./types.js";
3
+ export type { AcpConnection, AcpConnectionOutage, AcpConnectionStatus, AcpHistoryPage, AcpPendingRequest, AcpSessionListener, AcpSessionReplayListener, AcpSessionSetup, AcpSessionState, AcpSessionUpdateListener, AcpSubscribeOptions, } from "./types.js";
4
4
  export { createAcpWorkspaceClient, type AcpWorkspaceClient, type AcpWorkspaceClientOptions, } from "./acp-workspace-client.js";
5
5
  export { createAcpComposerStore, foldTurnUsage, projectModels, type AcpModelProjection, type AcpTurnUsage, } from "./acp-workspace-client-composer.js";
6
6
  export { createAcpApprovals, isSettledApproval, type AcpApproval, type AcpApprovalOption, type AcpApprovals, } from "./acp-approvals.js";
@@ -289,6 +289,17 @@ class AcpConnectionClosedError extends Error {
289
289
  }
290
290
  }
291
291
 
292
+ class HgwVersionMismatchError extends Error {
293
+ gatewayVersion;
294
+ clientVersion;
295
+ constructor(gatewayVersion, clientVersion) {
296
+ super(`The gateway speaks hgw extension version ${String(gatewayVersion)}; this client speaks version ${clientVersion}`);
297
+ this.gatewayVersion = gatewayVersion;
298
+ this.clientVersion = clientVersion;
299
+ this.name = "HgwVersionMismatchError";
300
+ }
301
+ }
302
+
292
303
  // client/limits.ts
293
304
  var HANDSHAKE_DEADLINE_MS = 1e4;
294
305
  var REQUEST_DEADLINE_MS = {
@@ -300,6 +311,7 @@ var REQUEST_DEADLINE_MS = {
300
311
  var LIVENESS_SILENCE_MS = 20000;
301
312
  var RECONNECT_BACKOFF = { baseMs: 250, capMs: 5000 };
302
313
  var STABLE_AFTER_MS = 60000;
314
+ var FELL_BEHIND_WINDOW_MS = STABLE_AFTER_MS;
303
315
  var PART_GRACE_MS = 2000;
304
316
  var CAPACITY_BACKOFF = { minMs: 30000, maxMs: 60000 };
305
317
 
@@ -395,9 +407,62 @@ function callEach(listeners, logger, event, ...args) {
395
407
  }
396
408
  }
397
409
 
410
+ // client/tolerant.ts
411
+ var MAX_PASSES = 8;
412
+ function unknownKeys(issues, prefix = []) {
413
+ const found = [];
414
+ for (const issue of issues) {
415
+ const path = [...prefix, ...issue.path];
416
+ if (issue.code === "unrecognized_keys")
417
+ found.push(...issue.keys.map((key) => [...path, key]));
418
+ else if (issue.code === "invalid_union") {
419
+ const branch = issue.errors.map((branchIssues) => unknownKeys(branchIssues, path)).find((keys) => keys !== undefined && keys.length > 0);
420
+ if (branch === undefined)
421
+ return;
422
+ found.push(...branch);
423
+ } else
424
+ return;
425
+ }
426
+ return found;
427
+ }
428
+ function withoutKey(value, path) {
429
+ const [head, ...rest] = path;
430
+ if (head === undefined || typeof value !== "object" || value === null)
431
+ return value;
432
+ const copy = Array.isArray(value) ? [...value] : { ...value };
433
+ if (rest.length === 0)
434
+ delete copy[head];
435
+ else
436
+ copy[head] = withoutKey(copy[head], rest);
437
+ return copy;
438
+ }
439
+ function tolerant(schema) {
440
+ const safeParse = (value) => {
441
+ let result = schema.safeParse(value);
442
+ for (let pass = 0;!result.success && pass < MAX_PASSES; pass += 1) {
443
+ const unknown = unknownKeys(result.error.issues);
444
+ if (!unknown?.length)
445
+ break;
446
+ value = unknown.reduce(withoutKey, value);
447
+ result = schema.safeParse(value);
448
+ }
449
+ return result;
450
+ };
451
+ return {
452
+ safeParse,
453
+ parse(value) {
454
+ const result = safeParse(value);
455
+ if (result.success)
456
+ return result.data;
457
+ throw result.error;
458
+ }
459
+ };
460
+ }
461
+
398
462
  // client/connection.ts
399
463
  var TRY_AGAIN_LATER = 1013;
400
464
  var POLICY_VIOLATION = 1008;
465
+ var READER_FELL_BEHIND = 4409;
401
466
  var SILENT_LOGGER = {
402
467
  debug: () => {},
403
468
  info: () => {},
@@ -460,14 +525,14 @@ function setupOfUpdate(update, meta) {
460
525
  return { configOptions: update.configOptions };
461
526
  if (!SessionUpdate.isAvailableCommandsUpdate(update))
462
527
  return;
463
- const capabilities = HgwAvailableCommandsMetaSchema2.safeParse(meta).data?.capabilities;
528
+ const capabilities = tolerant(HgwAvailableCommandsMetaSchema2).safeParse(meta).data?.capabilities;
464
529
  return {
465
530
  availableCommands: update.availableCommands,
466
531
  ...capabilities ? { capabilities } : {}
467
532
  };
468
533
  }
469
534
  function setupOfAnswer(answer) {
470
- const capabilities = HgwSessionSetupResponseMetaSchema2.safeParse(hgwMetaOf(answer._meta)).data?.capabilities;
535
+ const capabilities = tolerant(HgwSessionSetupResponseMetaSchema2).safeParse(hgwMetaOf(answer._meta)).data?.capabilities;
471
536
  return {
472
537
  configOptions: answer.configOptions ?? [],
473
538
  availableCommands: answer.availableCommands ?? [],
@@ -545,6 +610,11 @@ function connectionMachine({
545
610
  { guard: "inProcess", target: "closed" },
546
611
  { guard: "policyViolation", target: "closed" },
547
612
  { guard: "tryAgainLater", target: "capacity" },
613
+ {
614
+ guard: "fellBehindAgain",
615
+ target: "reconnecting",
616
+ actions: "keepBackoff"
617
+ },
548
618
  { target: "reconnecting" }
549
619
  ];
550
620
  return connectionSetup.extend({
@@ -557,7 +627,8 @@ function connectionMachine({
557
627
  guards: {
558
628
  inProcess: () => inProcess,
559
629
  policyViolation: ({ event }) => event.type === "closed" && event.code === POLICY_VIOLATION,
560
- tryAgainLater: ({ event }) => event.type === "closed" && event.code === TRY_AGAIN_LATER
630
+ tryAgainLater: ({ event }) => event.type === "closed" && event.code === TRY_AGAIN_LATER,
631
+ fellBehindAgain: ({ context, event }) => event.type === "closed" && event.code === READER_FELL_BEHIND && context.recovered !== undefined && clock.now() - context.recovered.at < FELL_BEHIND_WINDOW_MS
561
632
  },
562
633
  actions: {
563
634
  closeTransport: () => closeTransport(),
@@ -566,7 +637,20 @@ function connectionMachine({
566
637
  countAttempt: connectionSetup.assign({
567
638
  attempt: ({ context }) => context.attempt + 1
568
639
  }),
569
- resetAttempts: connectionSetup.assign({ attempt: 0 })
640
+ resetAttempts: connectionSetup.assign({
641
+ attempt: 0,
642
+ recovered: undefined
643
+ }),
644
+ startOver: connectionSetup.assign({
645
+ attempt: 0,
646
+ recovered: ({ context }) => ({
647
+ at: clock.now(),
648
+ attempt: context.attempt
649
+ })
650
+ }),
651
+ keepBackoff: connectionSetup.assign({
652
+ attempt: ({ context }) => Math.max(context.attempt, context.recovered?.attempt ?? 0)
653
+ })
570
654
  }
571
655
  }).createMachine({
572
656
  context: { generation: 0, attempt: 0 },
@@ -592,7 +676,7 @@ function connectionMachine({
592
676
  entry: "markReady",
593
677
  invoke: {
594
678
  src: "recover",
595
- onDone: { actions: "resetAttempts" },
679
+ onDone: { actions: "startOver" },
596
680
  onError: { actions: "closeTransport" }
597
681
  },
598
682
  on: { closed: onTransportClosed },
@@ -690,7 +774,7 @@ function readEach(entries, schema, skipped) {
690
774
  const kept = [];
691
775
  let unreadable;
692
776
  for (const entry of entries) {
693
- const read = schema.safeParse(entry);
777
+ const read = tolerant(schema).safeParse(entry);
694
778
  if (read.success)
695
779
  kept.push(read.data);
696
780
  else {
@@ -733,6 +817,7 @@ function createAcpConnection(options) {
733
817
  let agentCapabilities;
734
818
  let status = "connecting";
735
819
  let outage;
820
+ let versionMismatch;
736
821
  let started = false;
737
822
  let inspecting;
738
823
  let ended = false;
@@ -962,7 +1047,8 @@ function createAcpConnection(options) {
962
1047
  const announced = hgwMetaOf(response._meta);
963
1048
  agentCapabilities = response.capabilities ?? undefined;
964
1049
  if (announced?.version !== HGW_EXTENSION_VERSION2) {
965
- const error = new Error(`The gateway speaks hgw extension version ${String(announced?.version)}; this client speaks version ${HGW_EXTENSION_VERSION2}`);
1050
+ const error = new HgwVersionMismatchError(typeof announced?.version === "number" ? announced.version : undefined, HGW_EXTENSION_VERSION2);
1051
+ versionMismatch = error;
966
1052
  failInitialized?.(error);
967
1053
  failInitialized = undefined;
968
1054
  settleInitialized = undefined;
@@ -999,7 +1085,7 @@ function createAcpConnection(options) {
999
1085
  throw notOpen();
1000
1086
  if (signal.aborted)
1001
1087
  return;
1002
- const fromStart = !open.replayed || open.replayOwed;
1088
+ const fromStart = replayWanted(open);
1003
1089
  open.replayOwed = false;
1004
1090
  const named = [...open.listeners].find(({ listener }) => listener.agentId);
1005
1091
  const agentId = named?.listener.agentId ?? owners.get(sessionId);
@@ -1010,7 +1096,7 @@ function createAcpConnection(options) {
1010
1096
  const response = await requestOn(transport, fromStart ? "long" : "medium", (agent, options) => agent.request(methods2.agent.session.resume, {
1011
1097
  sessionId,
1012
1098
  cwd: AGENT_CWD,
1013
- replayFrom: fromStart ? { type: "start" } : rejoinCursor(open.position),
1099
+ ...fromStart ? { replayFrom: { type: "start" } } : open.replayed ? { replayFrom: rejoinCursor(open.position) } : {},
1014
1100
  _meta: {
1015
1101
  [HGW_META_KEY2]: agentId === undefined ? {} : { agentId }
1016
1102
  }
@@ -1037,12 +1123,15 @@ function createAcpConnection(options) {
1037
1123
  }
1038
1124
  }
1039
1125
  async function listAgents() {
1040
- const response = AgentsListEntriesSchema.parse(await request("short", (agent, options) => agent.request(HGW_METHODS2.agents.list, undefined, options), "read"));
1126
+ const response = tolerant(AgentsListEntriesSchema).parse(await request("short", (agent, options) => agent.request(HGW_METHODS2.agents.list, undefined, options), "read"));
1041
1127
  return {
1042
1128
  ...response,
1043
1129
  agents: readEach(response.agents, HgwAgentsListResponseSchema2.shape.agents.element, (entry) => logger.warn({ id: loggedId(entry, "summary", "id") }, "agents.entry_skipped"))
1044
1130
  };
1045
1131
  }
1132
+ function replayWanted(open) {
1133
+ return open.replayOwed || !open.replayed && [...open.listeners].some(({ replays }) => replays);
1134
+ }
1046
1135
  function settleOf({ listener }) {
1047
1136
  const settle = listener.replay?.();
1048
1137
  return settle ? [settle] : [];
@@ -1086,7 +1175,7 @@ function createAcpConnection(options) {
1086
1175
  const open = sessions.get(sessionId);
1087
1176
  if (!open)
1088
1177
  return Promise.reject(notOpen());
1089
- const served = open.replaying ? !open.replaying.delivered : !open.replayed || open.replayOwed;
1178
+ const served = open.replaying ? !open.replaying.delivered : replayWanted(open);
1090
1179
  if (!served)
1091
1180
  open.owner?.actor.send({ type: "replay" });
1092
1181
  return joined(sessionId);
@@ -1108,11 +1197,11 @@ function createAcpConnection(options) {
1108
1197
  for (const { listener } of open.listeners)
1109
1198
  callEach(listener.state ? [listener.state] : [], logger, "acp.listener.failed", next);
1110
1199
  }
1111
- function subscribe(sessionId, listener) {
1200
+ function subscribe(sessionId, listener, options = {}) {
1112
1201
  if (ended)
1113
1202
  return () => {};
1114
1203
  start();
1115
- const subscription = { listener };
1204
+ const subscription = { listener, replays: options.replay ?? true };
1116
1205
  const known = sessions.get(sessionId);
1117
1206
  if (known) {
1118
1207
  clock.clearTimeout(known.grace);
@@ -1120,6 +1209,8 @@ function createAcpConnection(options) {
1120
1209
  known.listeners.add(subscription);
1121
1210
  if (known.replaying && !known.replaying.delivered)
1122
1211
  known.replaying.settles.push(...settleOf(subscription));
1212
+ else if (subscription.replays && !known.replayed && !known.replaying)
1213
+ known.owner?.actor.send({ type: "replay" });
1123
1214
  hand(known, known.setup, [subscription]);
1124
1215
  return () => leave(sessionId, known, subscription);
1125
1216
  }
@@ -1151,14 +1242,18 @@ function createAcpConnection(options) {
1151
1242
  return;
1152
1243
  if (sessions.get(sessionId) !== open)
1153
1244
  return;
1245
+ startGrace(sessionId, open);
1246
+ }
1247
+ function startGrace(sessionId, open) {
1248
+ if (open.closing)
1249
+ return;
1154
1250
  open.grace = clock.setTimeout(() => part(sessionId, open), PART_GRACE_MS);
1155
1251
  }
1156
1252
  function openCreated(sessionId, answer) {
1157
1253
  let open = sessions.get(sessionId);
1158
1254
  if (!open) {
1159
- const created = openSession(sessionId, [], true);
1160
- created.grace = clock.setTimeout(() => part(sessionId, created), PART_GRACE_MS);
1161
- open = created;
1255
+ open = openSession(sessionId, [], true);
1256
+ startGrace(sessionId, open);
1162
1257
  }
1163
1258
  hand(open, report(open, setupOfAnswer(answer)));
1164
1259
  }
@@ -1174,6 +1269,28 @@ function createAcpConnection(options) {
1174
1269
  open.waiters?.reject(notOpen());
1175
1270
  open.waiters = undefined;
1176
1271
  }
1272
+ async function endSession(sessionId, send, ended) {
1273
+ const open = sessions.get(sessionId);
1274
+ if (open) {
1275
+ clock.clearTimeout(open.grace);
1276
+ open.grace = undefined;
1277
+ open.closing = true;
1278
+ }
1279
+ try {
1280
+ await request("short", send);
1281
+ } catch (error) {
1282
+ if (open) {
1283
+ open.closing = false;
1284
+ if (open.listeners.size === 0 && sessions.get(sessionId) === open)
1285
+ startGrace(sessionId, open);
1286
+ }
1287
+ throw error;
1288
+ }
1289
+ if (!open || sessions.get(sessionId) !== open)
1290
+ return;
1291
+ ended?.(open);
1292
+ forget(sessionId, open);
1293
+ }
1177
1294
  function part(sessionId, open) {
1178
1295
  forget(sessionId, open);
1179
1296
  if (open.state === "gone")
@@ -1352,6 +1469,9 @@ function createAcpConnection(options) {
1352
1469
  return outage;
1353
1470
  },
1354
1471
  subscribeOutage: (listener) => subscribeTo(outageListeners, listener),
1472
+ get versionMismatch() {
1473
+ return versionMismatch;
1474
+ },
1355
1475
  login,
1356
1476
  async newSession(meta) {
1357
1477
  const created = await request("short", (agent, options) => agent.request(methods2.agent.session.new, { cwd: AGENT_CWD, _meta: { [HGW_META_KEY2]: meta } }, options));
@@ -1414,21 +1534,14 @@ function createAcpConnection(options) {
1414
1534
  report(open, { configOptions: response.configOptions });
1415
1535
  return response.configOptions;
1416
1536
  },
1417
- async closeSession(sessionId) {
1418
- const open = sessions.get(sessionId);
1419
- if (open)
1420
- forget(sessionId, open);
1421
- await request("short", (agent, options) => agent.request(methods2.agent.session.close, { sessionId }, options));
1422
- },
1423
- async deleteSession(sessionId) {
1424
- await request("short", (agent, options) => agent.request(methods2.agent.session.delete, { sessionId }, options));
1425
- },
1537
+ closeSession: (sessionId) => endSession(sessionId, (agent, options) => agent.request(methods2.agent.session.close, { sessionId }, options)),
1538
+ deleteSession: (sessionId) => endSession(sessionId, (agent, options) => agent.request(methods2.agent.session.delete, { sessionId }, options), (open) => open.owner?.actor.send({ type: "gone" })),
1426
1539
  async updateSession(update) {
1427
1540
  await request("short", (agent, options) => agent.request(HGW_METHODS2.session.update, update, options));
1428
1541
  },
1429
1542
  async steer(steer) {
1430
1543
  assertFrameFits(steer);
1431
- return HgwSteerResponseSchema2.parse(await request("medium", (agent, options) => agent.request(HGW_METHODS2.session.steer, steer, options), { sessionId: steer.sessionId }));
1544
+ return tolerant(HgwSteerResponseSchema2).parse(await request("medium", (agent, options) => agent.request(HGW_METHODS2.session.steer, steer, options), { sessionId: steer.sessionId }));
1432
1545
  },
1433
1546
  focus(sessionId, presence) {
1434
1547
  const report = {
@@ -1446,7 +1559,7 @@ function createAcpConnection(options) {
1446
1559
  const response = await request("short", (agent, options) => agent.request(HGW_METHODS2.agents.update, update, options)).catch((error) => {
1447
1560
  throw agentUpdateError(error);
1448
1561
  });
1449
- return HgwAgentUpdateResponseSchema2.parse(response);
1562
+ return tolerant(HgwAgentUpdateResponseSchema2).parse(response);
1450
1563
  },
1451
1564
  subscribeNotification: (method, listener) => subscribeKeyed(notificationListeners, method, listener),
1452
1565
  subscribePendingRequests: (listener) => subscribeTo(pendingListeners, listener),
@@ -1506,7 +1619,7 @@ function projectModels(options) {
1506
1619
  function projectContext(update, meta) {
1507
1620
  if (update.size <= 0)
1508
1621
  return;
1509
- const aos = HgwUsageMetaSchema2.safeParse(meta);
1622
+ const aos = tolerant(HgwUsageMetaSchema2).safeParse(meta);
1510
1623
  return {
1511
1624
  usedTokens: update.used,
1512
1625
  maxTokens: update.size,
@@ -1699,7 +1812,7 @@ import {
1699
1812
  // client/hgw-notification.ts
1700
1813
  function subscribeHgwNotification(connection, method, schema, handler) {
1701
1814
  return connection.subscribeNotification(method, (params) => {
1702
- const parsed = schema.safeParse(params);
1815
+ const parsed = tolerant(schema).safeParse(params);
1703
1816
  if (parsed.success)
1704
1817
  handler(parsed.data);
1705
1818
  });
@@ -1851,7 +1964,7 @@ function createAcpSessionStore({
1851
1964
  }
1852
1965
  if (!SessionUpdate3.isPlanUpdate(update))
1853
1966
  return;
1854
- const plan = HgwPlanMetaSchema2.safeParse(meta);
1967
+ const plan = tolerant(HgwPlanMetaSchema2).safeParse(meta);
1855
1968
  if (plan.success)
1856
1969
  setTodos(sessionId, plan.data.todos);
1857
1970
  }
@@ -2575,7 +2688,7 @@ class McpAppFileReadError extends HgwClientError {
2575
2688
  }
2576
2689
  }
2577
2690
  async function normalizedError(response) {
2578
- const parsed = ErrorResponseSchema2.safeParse(await response.json().catch(() => {
2691
+ const parsed = tolerant(ErrorResponseSchema2).safeParse(await response.json().catch(() => {
2579
2692
  return;
2580
2693
  }));
2581
2694
  return parsed.success ? parsed.data.error : undefined;
@@ -2631,7 +2744,7 @@ class HgwRemoteClient {
2631
2744
  } catch {
2632
2745
  throw new HgwClientError("gateway-failure", "Invalid gateway response");
2633
2746
  }
2634
- const parsed = schema.safeParse(payload);
2747
+ const parsed = tolerant(schema).safeParse(payload);
2635
2748
  if (!parsed.success)
2636
2749
  throw new HgwClientError("gateway-failure", "Invalid gateway response");
2637
2750
  return parsed.data;
@@ -2645,9 +2758,9 @@ class HgwRemoteClient {
2645
2758
  async putPushSubscription(registration) {
2646
2759
  await this.#write("/push/subscriptions", "PUT", registration);
2647
2760
  }
2648
- async deletePushSubscription(endpoint) {
2649
- const request = PushUnregistrationSchema2.safeParse({ endpoint });
2650
- if (!request.success || !endpoint.trim())
2761
+ async deletePushSubscription(device) {
2762
+ const request = PushUnregistrationSchema2.safeParse(device);
2763
+ if (!request.success || "endpoint" in request.data && !request.data.endpoint.trim())
2651
2764
  throw new HgwClientError("gateway-failure", "Invalid push subscription");
2652
2765
  await this.#write("/push/subscriptions", "DELETE", request.data);
2653
2766
  }
@@ -2822,6 +2935,7 @@ export {
2822
2935
  AgentUpdateError,
2823
2936
  HgwClientError,
2824
2937
  HgwRemoteClient,
2938
+ HgwVersionMismatchError,
2825
2939
  McpAppFileReadError,
2826
2940
  PART_GRACE_MS,
2827
2941
  SILENT_LOGGER,
@@ -27,6 +27,15 @@ export declare const RECONNECT_BACKOFF: {
27
27
  };
28
28
  /** A transport up this long starts the backoff over, rejoined or not. */
29
29
  export declare const STABLE_AFTER_MS = 60000;
30
+ /**
31
+ * A transport the gateway closes as a reader that fell behind (4409) within
32
+ * this long of its recovery keeps the backoff that recovery started over, so a
33
+ * reader that keeps falling behind a running turn backs off as any repeated
34
+ * failure does, each cycle costing a rebuild and a resume of every Session.
35
+ * The same as STABLE_AFTER_MS: until then the transport has not shown that it
36
+ * keeps up.
37
+ */
38
+ export declare const FELL_BEHIND_WINDOW_MS = 60000;
30
39
  /**
31
40
  * How long an opened Session outlives its last listener before it parts, so
32
41
  * an unsubscribe a resubscribe follows at once, as Strict Mode does, costs
@@ -0,0 +1,15 @@
1
+ import type { z } from "zod";
2
+ /** What a parse boundary needs of a schema. */
3
+ type Schema<T> = Pick<z.ZodType<T>, "safeParse">;
4
+ /**
5
+ * `schema` as a client reads what the gateway sends: a key it does not know is
6
+ * dropped wherever a strict object sits, so a later gateway may add one, and
7
+ * every key it knows is still validated. A value that fails for any other
8
+ * reason, a known key of the wrong type, an unknown enum value or union
9
+ * variant, still fails. What a client sends stays strict.
10
+ */
11
+ export declare function tolerant<T>(schema: Schema<T>): {
12
+ safeParse: (value: unknown) => z.ZodSafeParseResult<T>;
13
+ parse(value: unknown): T;
14
+ };
15
+ export {};
@@ -3,6 +3,7 @@ import type { z } from "zod";
3
3
  import type { AgentCatalogResponseSchema } from "../protocol/index.js";
4
4
  import type { HgwAgentUpdateRequest, HgwAgentUpdateResponseSchema, HgwHistoryCursor, HgwInitializeMetaSchema, HgwPromptMetaSchema, HgwSessionListMetaSchema, HgwSessionNewMetaSchema, HgwSessionSearchMeta, HgwSessionUpdateRequestSchema, HgwSteerRequestSchema, HgwSteerResponseSchema } from "../protocol/acp.js";
5
5
  import type { HgwWorkspaceCapabilities } from "./hgw-client.js";
6
+ import type { HgwVersionMismatchError } from "./workspace.js";
6
7
  /**
7
8
  * The browser-side seam over one ACP v2 WebSocket connection to the gateway.
8
9
  * `connection.ts` implements it; the runtime, thread list, interactions, and
@@ -95,6 +96,19 @@ export type AcpSessionListener = {
95
96
  setup?: (setup: AcpSessionSetup) => void;
96
97
  state?: (state: AcpSessionState) => void;
97
98
  };
99
+ /** How one `subscribe` opens its Session. */
100
+ export type AcpSubscribeOptions = {
101
+ /**
102
+ * `false` opens the Session without asking for its history, as a send from
103
+ * outside its view does: the Session is made active on the connection, as a
104
+ * prompt needs, and while no subscription asks for a replay, its join names
105
+ * no `replayFrom`, which ACP answers with no replay at all, and a rejoin
106
+ * after a reconnect follows only what streams next. A later subscription
107
+ * that asks for one, to a Session not replayed yet, has it replayed from the
108
+ * start then, after any join in flight. Defaults to `true`.
109
+ */
110
+ replay?: boolean;
111
+ };
98
112
  /**
99
113
  * A read (`listAgents`, `listSessions`, `searchSessions`, `resumePage`) waits
100
114
  * out a reconnect and goes out again on the transport that recovers, and a
@@ -125,6 +139,13 @@ export interface AcpConnection {
125
139
  */
126
140
  readonly outage: AcpConnectionOutage | undefined;
127
141
  subscribeOutage(listener: (outage: AcpConnectionOutage | undefined) => void): () => void;
142
+ /**
143
+ * Set, before `status` turns `closed`, once a handshake finds the gateway
144
+ * speaking another hgw extension version: the first one, which fails
145
+ * `initialized` with the same error, or a reconnect's, after `initialized`
146
+ * has resolved. No other close sets it.
147
+ */
148
+ readonly versionMismatch: HgwVersionMismatchError | undefined;
128
149
  /**
129
150
  * Redeems a guest invitation. The connection keeps the token and replays the
130
151
  * login before it rejoins its Sessions on a recovered transport.
@@ -167,9 +188,10 @@ export interface AcpConnection {
167
188
  * parts, with `_hgw/session/part`, 2 s after the last listener leaves, so a
168
189
  * listener back within that grace costs neither a part nor a resume. A
169
190
  * listener that subscribes before anything of a from-start replay under way
170
- * has arrived takes part in that replay.
191
+ * has arrived takes part in that replay. A subscription with
192
+ * `{ replay: false }` asks for none (see `AcpSubscribeOptions`).
171
193
  */
172
- subscribe(sessionId: string, listener: AcpSessionListener): () => void;
194
+ subscribe(sessionId: string, listener: AcpSessionListener, options?: AcpSubscribeOptions): () => void;
173
195
  /** Resolves once the opened Session is joined; rejects once it is gone or parts. */
174
196
  joined(sessionId: string): Promise<void>;
175
197
  /**
@@ -191,7 +213,13 @@ export interface AcpConnection {
191
213
  * reported; a join that replays nothing leaves it as it was.
192
214
  */
193
215
  history(sessionId: string): HgwHistoryCursor | undefined;
194
- /** Prompts an opened Session once it is joined, as `setConfigOption` and `steer` write. */
216
+ /**
217
+ * Prompts an opened Session once it is joined, as `setConfigOption` and
218
+ * `steer` write. Open it first (`subscribe`, or `newSession` and
219
+ * `forkSession`, which open the Session they make): the gateway takes
220
+ * neither a prompt nor a config write of a Session no resume or create made
221
+ * active on the connection, and answers `-32002` naming it.
222
+ */
195
223
  prompt(sessionId: string, blocks: ContentBlock[], meta: z.infer<typeof HgwPromptMetaSchema>): Promise<{
196
224
  messageId: string;
197
225
  }>;
@@ -199,12 +227,22 @@ export interface AcpConnection {
199
227
  setConfigOption(sessionId: string, configId: string, value: string): Promise<SessionConfigOption[]>;
200
228
  /**
201
229
  * Ends the Session with ACP's `session/close`, which stops its work, and
202
- * forgets it here at once, with no `_hgw/session/part`: its listeners hear
203
- * nothing more of it, and nothing rejoins it. A Session the gateway no
204
- * longer has (`-32002`) is closed already, so that answer resolves too.
230
+ * forgets it here once the close succeeded, with no `_hgw/session/part`:
231
+ * its listeners hear nothing more of it, and nothing rejoins it. While the
232
+ * close is out its listeners still hear what the gateway shows the closer,
233
+ * and no grace parts it. A Session the gateway no longer has (`-32002`) is
234
+ * closed already, so that answer resolves too. A close that fails rejects
235
+ * with its error and changes nothing: the Session stays opened and joined,
236
+ * and may be closed again.
205
237
  */
206
238
  closeSession(sessionId: string): Promise<void>;
207
- /** Resolves, as `closeSession` does, for a Session already gone (`-32002`). */
239
+ /**
240
+ * Deletes the Session with ACP's `session/delete`, and once the delete
241
+ * succeeded, or found it already gone (`-32002`), forgets it here as
242
+ * `closeSession` does: its listeners' `state` hears `gone`, as for a
243
+ * Session the gateway reports gone, and then nothing more of it. A delete
244
+ * that fails changes nothing, as a failed close does.
245
+ */
208
246
  deleteSession(sessionId: string): Promise<void>;
209
247
  updateSession(request: z.infer<typeof HgwSessionUpdateRequestSchema>): Promise<void>;
210
248
  steer(request: z.infer<typeof HgwSteerRequestSchema>): Promise<z.infer<typeof HgwSteerResponseSchema>>;
@@ -26,6 +26,19 @@ export declare class AgentUpdateError extends Error {
26
26
  export declare class AcpConnectionClosedError extends Error {
27
27
  constructor(message?: string, options?: ErrorOptions);
28
28
  }
29
+ /**
30
+ * The gateway speaks another hgw extension version than this client, so the
31
+ * connection ended for good: no retry changes the gateway's version. Which
32
+ * side is older says which one to update.
33
+ */
34
+ export declare class HgwVersionMismatchError extends Error {
35
+ /** What the gateway's `initialize` announced; undefined for no number. */
36
+ readonly gatewayVersion: number | undefined;
37
+ readonly clientVersion: number;
38
+ constructor(
39
+ /** What the gateway's `initialize` announced; undefined for no number. */
40
+ gatewayVersion: number | undefined, clientVersion: number);
41
+ }
29
42
  export type SessionStatus = "idle" | "running" | "waiting-for-input" | "failed" | "unknown";
30
43
  export type ActivityBase = {
31
44
  id: string;
@@ -44,7 +44,7 @@ export declare const HGW_ACP_AGENTS_PATH: "/api/v1/acp/agents";
44
44
  /** One Agent's own ACP address, its id one path segment. */
45
45
  export declare function hgwAcpAgentPath(agentId: string): string;
46
46
  export declare const HGW_META_KEY: "hgw";
47
- export declare const HGW_EXTENSION_VERSION: 3;
47
+ export declare const HGW_EXTENSION_VERSION: 4;
48
48
  export declare const HGW_AUTH_METHOD_INVITE: "hgw-invite";
49
49
  export declare const HGW_ATTACHMENT_URI_SCHEME: "hgw-attachment:";
50
50
  export declare const HGW_ARTIFACT_URI_SCHEME: "artifact:";
@@ -120,7 +120,7 @@ export declare const HgwClientCapabilitiesMetaSchema: z.ZodObject<{
120
120
  }, z.core.$strip>;
121
121
  /** `InitializeResponse._meta.hgw` */
122
122
  export declare const HgwInitializeMetaSchema: z.ZodObject<{
123
- version: z.ZodLiteral<3>;
123
+ version: z.ZodLiteral<4>;
124
124
  role: z.ZodEnum<{
125
125
  guest: "guest";
126
126
  operator: "operator";
@@ -633,6 +633,23 @@ export declare const HgwMessageMetaSchema: z.ZodObject<{
633
633
  }, z.core.$strip>>;
634
634
  }, z.core.$strip>;
635
635
  export type HgwMessageMeta = z.infer<typeof HgwMessageMetaSchema>;
636
+ /**
637
+ * `_meta.hgw` of a replayed `agent_message` upsert whose message the provider
638
+ * stored as failed. ACP replays no past `state_update`, so the failure that
639
+ * ended the turn travels on the message it ended: what the live turn's idle
640
+ * `error` update said of it in `_meta.hgw` (`HgwStateMetaSchema`). The upsert
641
+ * follows the message's own parts and leaves their content as it stands; one
642
+ * that streamed nothing starts from `content: []`. Live, a failure is that
643
+ * idle update alone, never this.
644
+ */
645
+ export declare const HgwMessageFailureMetaSchema: z.ZodObject<{
646
+ failure: z.ZodObject<{
647
+ message: z.ZodString;
648
+ code: z.ZodOptional<z.ZodString>;
649
+ at: z.ZodOptional<z.ZodISODateTime>;
650
+ }, z.core.$strip>;
651
+ }, z.core.$strip>;
652
+ export type HgwMessageFailureMeta = z.infer<typeof HgwMessageFailureMetaSchema>;
636
653
  /** What a turn cost, as the provider priced it; ISO 4217 currency. */
637
654
  export declare const HgwCostSchema: z.ZodObject<{
638
655
  amount: z.ZodNumber;
@@ -355,7 +355,7 @@ export declare const MCP_APP_SANDBOX_PATH = "/mcp-app-sandbox.html";
355
355
  export type McpAppSandboxPolicyInput = {
356
356
  /**
357
357
  * The exact origins of the host's own pages, the only ones that may frame
358
- * the sandbox page.
358
+ * the sandbox page (`isMcpAppFramingOrigin`).
359
359
  */
360
360
  frameAncestors: readonly string[];
361
361
  /** The exact origin the sandbox page is served from. */
@@ -366,18 +366,33 @@ export type McpAppSandboxPolicyInput = {
366
366
  fileLocations?: readonly string[] | undefined;
367
367
  };
368
368
  /**
369
- * Whether a sandbox policy can name `value` as a framing page or as the
370
- * sandbox: an `http(s)` origin exactly as `URL` writes it, whose host is a name
371
- * or an IPv4 address. `mcpAppSandboxPolicy` throws for any other, so a host
372
- * checks its settings with this once, before it serves a view.
369
+ * Whether a sandbox policy can name `value` as the sandbox, or as a framing
370
+ * page served from the network: an `http(s)` origin exactly as `URL` writes
371
+ * it, whose host is a name or an IPv4 address. `mcpAppSandboxPolicy` throws for
372
+ * any other sandbox origin, so a host checks its settings with this once,
373
+ * before it serves a view.
373
374
  */
374
375
  export declare function isMcpAppPolicyOrigin(value: string): boolean;
376
+ /**
377
+ * The origin of the pages an app bundles and serves itself, from no network
378
+ * origin: the one framing page a sandbox policy names that is no `http(s)`
379
+ * origin. `URL` reads it as the opaque origin `null`, so it is matched as this
380
+ * exact string. It is never the sandbox, never a file location, and names no
381
+ * host, so no declared domain is dropped for naming it.
382
+ */
383
+ export declare const MCP_APP_BUNDLED_PAGE_ORIGIN = "tauri://localhost";
384
+ /**
385
+ * Whether a sandbox policy can name `value` as a framing page: an origin
386
+ * `isMcpAppPolicyOrigin` admits, or exactly `MCP_APP_BUNDLED_PAGE_ORIGIN`.
387
+ * `mcpAppSandboxPolicy` throws for any other.
388
+ */
389
+ export declare function isMcpAppFramingOrigin(value: string): boolean;
375
390
  /**
376
391
  * The domains a view's sandbox policy applies, per `_meta.ui.csp` list, as a
377
392
  * host reports them in `hostCapabilities.sandbox.csp`: those
378
393
  * `isMcpAppCspDomain` admits, lowercased and once each, without any that names
379
- * the host and port of a framing page or of the sandbox itself, whatever its
380
- * scheme. `undefined` when it applies none. Throws as `mcpAppSandboxPolicy`
394
+ * the host and port of an `http(s)` framing page or of the sandbox itself,
395
+ * whatever its scheme. `undefined` when it applies none. Throws as `mcpAppSandboxPolicy`
381
396
  * does for the origins.
382
397
  */
383
398
  export declare function appliedMcpAppCsp({ csp, ...origins }: Omit<McpAppSandboxPolicyInput, "fileLocations">): McpUiCsp | undefined;
@@ -390,9 +405,10 @@ export declare function appliedMcpAppCsp({ csp, ...origins }: Omit<McpAppSandbox
390
405
  * document renderer's decoders do.
391
406
  *
392
407
  * Anyone can ask for a sandbox page with any query, so every value is checked
393
- * before it is written: an ancestor or a sandbox origin that is no exact
394
- * origin (`isMcpAppPolicyOrigin`) throws, as does a sandbox origin among the
408
+ * before it is written: an ancestor that is no framing origin
409
+ * (`isMcpAppFramingOrigin`) or a sandbox origin that is no exact origin
410
+ * (`isMcpAppPolicyOrigin`) throws, as does a sandbox origin among the
395
411
  * ancestors, and a domain or a file location its rule refuses is dropped. A
396
- * file location is kept only on a framing page's origin.
412
+ * file location is kept only on an `http(s)` framing page's origin.
397
413
  */
398
414
  export declare function mcpAppSandboxPolicy({ fileLocations, ...view }: McpAppSandboxPolicyInput): string;
@@ -1,8 +1,9 @@
1
1
  import { z } from "zod";
2
2
  /**
3
- * Web Push contract shared by the browser, the service worker, and the gateway.
4
- * One message is about one Session. It always carries the category, the Agent
5
- * and Session ids, when the Session's newest event happened, and the device
3
+ * Push contract shared by the browser, the service worker, and the gateway. A
4
+ * device registers through one transport, Web Push or APNs. One Web Push
5
+ * message is about one Session. It always carries the category, the Agent and
6
+ * Session ids, when the Session's newest event happened, and the device
6
7
  * locale. A device whose registration is under 30 days old may also get the
7
8
  * Agent's name, the Session's title, and a preview of what is asked: each one
8
9
  * line, cut to its `PUSH_TEXT_LIMITS` entry, with credentials masked. Every
@@ -87,16 +88,31 @@ export declare const PushSubscriptionJsonSchema: z.ZodObject<{
87
88
  }, z.core.$strict>;
88
89
  }, z.core.$strict>;
89
90
  export type PushSubscriptionJson = z.infer<typeof PushSubscriptionJsonSchema>;
90
- /** `GET /push` */
91
+ /**
92
+ * `GET /push`: `status` and `publicKey` are Web Push's, and `apns` says
93
+ * whether a device may register through APNs.
94
+ */
91
95
  export declare const PushInfoSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
96
+ apns: z.ZodOptional<z.ZodLiteral<true>>;
92
97
  status: z.ZodLiteral<"not-configured">;
93
98
  }, z.core.$strict>, z.ZodObject<{
99
+ apns: z.ZodOptional<z.ZodLiteral<true>>;
94
100
  status: z.ZodLiteral<"available">;
95
101
  publicKey: z.ZodString;
96
102
  }, z.core.$strict>], "status">;
97
103
  export type PushInfo = z.infer<typeof PushInfoSchema>;
98
- /** `PUT /push/subscriptions` */
99
- export declare const PushRegistrationSchema: z.ZodObject<{
104
+ /** A browser's registration; one that names no `transport` is this one. */
105
+ export declare const WebPushRegistrationSchema: z.ZodObject<{
106
+ locale: z.ZodEnum<{
107
+ en: "en";
108
+ he: "he";
109
+ }>;
110
+ categories: z.ZodObject<{
111
+ input: z.ZodBoolean;
112
+ failure: z.ZodBoolean;
113
+ completion: z.ZodBoolean;
114
+ }, z.core.$strict>;
115
+ transport: z.ZodOptional<z.ZodLiteral<"web-push">>;
100
116
  subscription: z.ZodObject<{
101
117
  endpoint: z.ZodString;
102
118
  expirationTime: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
@@ -105,6 +121,16 @@ export declare const PushRegistrationSchema: z.ZodObject<{
105
121
  auth: z.ZodString;
106
122
  }, z.core.$strict>;
107
123
  }, z.core.$strict>;
124
+ }, z.core.$strict>;
125
+ export type WebPushRegistration = z.infer<typeof WebPushRegistrationSchema>;
126
+ /** An APNs device token: 32 to 100 bytes as hex, in either case, kept lowercase. */
127
+ export declare const ApnsDeviceTokenSchema: z.ZodString;
128
+ /**
129
+ * A device's APNs registration: its token, and the APNs environment that
130
+ * issued it. The topic and the credentials the gateway sends with are its own
131
+ * configuration, never a device's.
132
+ */
133
+ export declare const ApnsRegistrationSchema: z.ZodObject<{
108
134
  locale: z.ZodEnum<{
109
135
  en: "en";
110
136
  he: "he";
@@ -114,10 +140,58 @@ export declare const PushRegistrationSchema: z.ZodObject<{
114
140
  failure: z.ZodBoolean;
115
141
  completion: z.ZodBoolean;
116
142
  }, z.core.$strict>;
143
+ transport: z.ZodLiteral<"apns">;
144
+ token: z.ZodString;
145
+ environment: z.ZodEnum<{
146
+ production: "production";
147
+ sandbox: "sandbox";
148
+ }>;
117
149
  }, z.core.$strict>;
150
+ export type ApnsRegistration = z.infer<typeof ApnsRegistrationSchema>;
151
+ /** `PUT /push/subscriptions`: one device, by its transport. */
152
+ export declare const PushRegistrationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
153
+ locale: z.ZodEnum<{
154
+ en: "en";
155
+ he: "he";
156
+ }>;
157
+ categories: z.ZodObject<{
158
+ input: z.ZodBoolean;
159
+ failure: z.ZodBoolean;
160
+ completion: z.ZodBoolean;
161
+ }, z.core.$strict>;
162
+ transport: z.ZodOptional<z.ZodLiteral<"web-push">>;
163
+ subscription: z.ZodObject<{
164
+ endpoint: z.ZodString;
165
+ expirationTime: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
166
+ keys: z.ZodObject<{
167
+ p256dh: z.ZodString;
168
+ auth: z.ZodString;
169
+ }, z.core.$strict>;
170
+ }, z.core.$strict>;
171
+ }, z.core.$strict>, z.ZodObject<{
172
+ locale: z.ZodEnum<{
173
+ en: "en";
174
+ he: "he";
175
+ }>;
176
+ categories: z.ZodObject<{
177
+ input: z.ZodBoolean;
178
+ failure: z.ZodBoolean;
179
+ completion: z.ZodBoolean;
180
+ }, z.core.$strict>;
181
+ transport: z.ZodLiteral<"apns">;
182
+ token: z.ZodString;
183
+ environment: z.ZodEnum<{
184
+ production: "production";
185
+ sandbox: "sandbox";
186
+ }>;
187
+ }, z.core.$strict>], "transport">;
118
188
  export type PushRegistration = z.infer<typeof PushRegistrationSchema>;
119
- /** `DELETE /push/subscriptions` */
120
- export declare const PushUnregistrationSchema: z.ZodObject<{
189
+ /** `DELETE /push/subscriptions`: one device, by its transport's own key. */
190
+ export declare const PushUnregistrationSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
191
+ transport: z.ZodOptional<z.ZodLiteral<"web-push">>;
121
192
  endpoint: z.ZodString;
122
- }, z.core.$strict>;
193
+ }, z.core.$strict>, z.ZodObject<{
194
+ transport: z.ZodLiteral<"apns">;
195
+ token: z.ZodString;
196
+ }, z.core.$strict>], "transport">;
123
197
  export type PushUnregistration = z.infer<typeof PushUnregistrationSchema>;
@@ -17,6 +17,8 @@ import {
17
17
  McpAppFileReadErrorDataSchema2,
18
18
  MCP_APP_SANDBOX_PATH2,
19
19
  isMcpAppPolicyOrigin2,
20
+ MCP_APP_BUNDLED_PAGE_ORIGIN2,
21
+ isMcpAppFramingOrigin2,
20
22
  appliedMcpAppCsp2,
21
23
  mcpAppSandboxPolicy2,
22
24
  SESSION_CATALOG_MAX_WINDOW2,
@@ -120,6 +122,7 @@ import {
120
122
  HgwTurnMetaSchema2,
121
123
  HgwNoticeMetaSchema2,
122
124
  HgwMessageMetaSchema2,
125
+ HgwMessageFailureMetaSchema2,
123
126
  HgwCostSchema2,
124
127
  HgwChildSessionMetaSchema2,
125
128
  HgwStateMetaSchema2,
@@ -152,6 +155,9 @@ import {
152
155
  PushCategoriesSchema2,
153
156
  PushSubscriptionJsonSchema2,
154
157
  PushInfoSchema2,
158
+ WebPushRegistrationSchema2,
159
+ ApnsDeviceTokenSchema2,
160
+ ApnsRegistrationSchema2,
155
161
  PushRegistrationSchema2,
156
162
  PushUnregistrationSchema2
157
163
  } from "../chunks/index.js";
@@ -213,6 +219,8 @@ export {
213
219
  AgentUpdateFields2 as AgentUpdateFields,
214
220
  AgentUpdateRequestSchema2 as AgentUpdateRequestSchema,
215
221
  AgentUpdateResponseSchema2 as AgentUpdateResponseSchema,
222
+ ApnsDeviceTokenSchema2 as ApnsDeviceTokenSchema,
223
+ ApnsRegistrationSchema2 as ApnsRegistrationSchema,
216
224
  ArtifactDescriptorSchema2 as ArtifactDescriptorSchema,
217
225
  COALESCE_WINDOW_MS2 as COALESCE_WINDOW_MS,
218
226
  CallToolResultSchema2 as CallToolResultSchema,
@@ -257,6 +265,7 @@ export {
257
265
  HgwHistoryPageTagSchema2 as HgwHistoryPageTagSchema,
258
266
  HgwInitializeMetaSchema2 as HgwInitializeMetaSchema,
259
267
  HgwLoginMetaSchema2 as HgwLoginMetaSchema,
268
+ HgwMessageFailureMetaSchema2 as HgwMessageFailureMetaSchema,
260
269
  HgwMessageMetaSchema2 as HgwMessageMetaSchema,
261
270
  HgwNoticeMetaSchema2 as HgwNoticeMetaSchema,
262
271
  HgwPermissionMetaSchema2 as HgwPermissionMetaSchema,
@@ -290,6 +299,7 @@ export {
290
299
  MAX_SPEECH_BYTES,
291
300
  MAX_SPEECH_TEXT_BYTES,
292
301
  MAX_TRANSCRIPT_BYTES,
302
+ MCP_APP_BUNDLED_PAGE_ORIGIN2 as MCP_APP_BUNDLED_PAGE_ORIGIN,
293
303
  MCP_APP_SANDBOX_PATH2 as MCP_APP_SANDBOX_PATH,
294
304
  McpAppFileReadErrorDataSchema2 as McpAppFileReadErrorDataSchema,
295
305
  McpAppFileReadFailureSchema2 as McpAppFileReadFailureSchema,
@@ -357,11 +367,13 @@ export {
357
367
  TurnSteerRequestSchema2 as TurnSteerRequestSchema,
358
368
  TurnSteerResponseSchema2 as TurnSteerResponseSchema,
359
369
  TurnStopResponseSchema2 as TurnStopResponseSchema,
370
+ WebPushRegistrationSchema2 as WebPushRegistrationSchema,
360
371
  appliedMcpAppCsp2 as appliedMcpAppCsp,
361
372
  categoryOf2 as categoryOf,
362
373
  formatArtifactUri2 as formatArtifactUri,
363
374
  hgwAcpAgentPath2 as hgwAcpAgentPath,
364
375
  isMcpAppCspDomain2 as isMcpAppCspDomain,
376
+ isMcpAppFramingOrigin2 as isMcpAppFramingOrigin,
365
377
  isMcpAppPolicyOrigin2 as isMcpAppPolicyOrigin,
366
378
  mcpAppSandboxPolicy2 as mcpAppSandboxPolicy,
367
379
  newestSessionFirst2 as newestSessionFirst,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harness-gw/sdk",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "A gateway that puts Hermes, OpenClaw, and OpenCode behind one ACP WebSocket, and the browser client and protocol SDK for it.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",