@harness-gw/sdk 0.18.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
@@ -64,7 +64,7 @@ You need a running harness. Hermes is the primary one; see
64
64
  docker run --rm \
65
65
  -v "$PWD/config.yaml:/run/harness-gw/config.yaml:ro" \
66
66
  -v "$PWD/hermes-token:/run/secrets/hermes-token:ro" \
67
- ghcr.io/almogbaku/harness-gw:0.18.0 \
67
+ ghcr.io/almogbaku/harness-gw:0.19.0 \
68
68
  config check --config /run/harness-gw/config.yaml
69
69
  ```
70
70
 
@@ -74,7 +74,7 @@ You need a running harness. Hermes is the primary one; see
74
74
  docker run --rm -p 127.0.0.1:4100:4100 \
75
75
  -v "$PWD/config.yaml:/run/harness-gw/config.yaml:ro" \
76
76
  -v "$PWD/hermes-token:/run/secrets/hermes-token:ro" \
77
- ghcr.io/almogbaku/harness-gw:0.18.0 \
77
+ ghcr.io/almogbaku/harness-gw:0.19.0 \
78
78
  serve --config /run/harness-gw/config.yaml
79
79
  ```
80
80
 
@@ -909,7 +909,7 @@ function hgwAcpAgentPath2(agentId) {
909
909
  return `${HGW_ACP_AGENTS_PATH2}/${encodeURIComponent(agentId)}`;
910
910
  }
911
911
  var HGW_META_KEY2 = "hgw";
912
- var HGW_EXTENSION_VERSION2 = 3;
912
+ var HGW_EXTENSION_VERSION2 = 4;
913
913
  var HGW_AUTH_METHOD_INVITE2 = "hgw-invite";
914
914
  var HGW_ATTACHMENT_URI_SCHEME2 = "hgw-attachment:";
915
915
  var HGW_ARTIFACT_URI_SCHEME2 = "artifact:";
@@ -1089,6 +1089,13 @@ var HgwMessageMetaSchema2 = readObject({
1089
1089
  kind: NoticeKindSchema.optional()
1090
1090
  }).optional()
1091
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
+ });
1092
1099
  var CountSchema = z3.number().int().nonnegative();
1093
1100
  var HgwCostSchema2 = readObject({
1094
1101
  amount: z3.number().nonnegative(),
@@ -1319,4 +1326,4 @@ var PushUnregistrationSchema2 = z4.discriminatedUnion("transport", [
1319
1326
  })
1320
1327
  ]);
1321
1328
 
1322
- 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, 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 };
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 };
@@ -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
  /** `@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";
@@ -311,6 +311,7 @@ var REQUEST_DEADLINE_MS = {
311
311
  var LIVENESS_SILENCE_MS = 20000;
312
312
  var RECONNECT_BACKOFF = { baseMs: 250, capMs: 5000 };
313
313
  var STABLE_AFTER_MS = 60000;
314
+ var FELL_BEHIND_WINDOW_MS = STABLE_AFTER_MS;
314
315
  var PART_GRACE_MS = 2000;
315
316
  var CAPACITY_BACKOFF = { minMs: 30000, maxMs: 60000 };
316
317
 
@@ -461,6 +462,7 @@ function tolerant(schema) {
461
462
  // client/connection.ts
462
463
  var TRY_AGAIN_LATER = 1013;
463
464
  var POLICY_VIOLATION = 1008;
465
+ var READER_FELL_BEHIND = 4409;
464
466
  var SILENT_LOGGER = {
465
467
  debug: () => {},
466
468
  info: () => {},
@@ -608,6 +610,11 @@ function connectionMachine({
608
610
  { guard: "inProcess", target: "closed" },
609
611
  { guard: "policyViolation", target: "closed" },
610
612
  { guard: "tryAgainLater", target: "capacity" },
613
+ {
614
+ guard: "fellBehindAgain",
615
+ target: "reconnecting",
616
+ actions: "keepBackoff"
617
+ },
611
618
  { target: "reconnecting" }
612
619
  ];
613
620
  return connectionSetup.extend({
@@ -620,7 +627,8 @@ function connectionMachine({
620
627
  guards: {
621
628
  inProcess: () => inProcess,
622
629
  policyViolation: ({ event }) => event.type === "closed" && event.code === POLICY_VIOLATION,
623
- 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
624
632
  },
625
633
  actions: {
626
634
  closeTransport: () => closeTransport(),
@@ -629,7 +637,20 @@ function connectionMachine({
629
637
  countAttempt: connectionSetup.assign({
630
638
  attempt: ({ context }) => context.attempt + 1
631
639
  }),
632
- 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
+ })
633
654
  }
634
655
  }).createMachine({
635
656
  context: { generation: 0, attempt: 0 },
@@ -655,7 +676,7 @@ function connectionMachine({
655
676
  entry: "markReady",
656
677
  invoke: {
657
678
  src: "recover",
658
- onDone: { actions: "resetAttempts" },
679
+ onDone: { actions: "startOver" },
659
680
  onError: { actions: "closeTransport" }
660
681
  },
661
682
  on: { closed: onTransportClosed },
@@ -1064,7 +1085,7 @@ function createAcpConnection(options) {
1064
1085
  throw notOpen();
1065
1086
  if (signal.aborted)
1066
1087
  return;
1067
- const fromStart = !open.replayed || open.replayOwed;
1088
+ const fromStart = replayWanted(open);
1068
1089
  open.replayOwed = false;
1069
1090
  const named = [...open.listeners].find(({ listener }) => listener.agentId);
1070
1091
  const agentId = named?.listener.agentId ?? owners.get(sessionId);
@@ -1075,7 +1096,7 @@ function createAcpConnection(options) {
1075
1096
  const response = await requestOn(transport, fromStart ? "long" : "medium", (agent, options) => agent.request(methods2.agent.session.resume, {
1076
1097
  sessionId,
1077
1098
  cwd: AGENT_CWD,
1078
- replayFrom: fromStart ? { type: "start" } : rejoinCursor(open.position),
1099
+ ...fromStart ? { replayFrom: { type: "start" } } : open.replayed ? { replayFrom: rejoinCursor(open.position) } : {},
1079
1100
  _meta: {
1080
1101
  [HGW_META_KEY2]: agentId === undefined ? {} : { agentId }
1081
1102
  }
@@ -1108,6 +1129,9 @@ function createAcpConnection(options) {
1108
1129
  agents: readEach(response.agents, HgwAgentsListResponseSchema2.shape.agents.element, (entry) => logger.warn({ id: loggedId(entry, "summary", "id") }, "agents.entry_skipped"))
1109
1130
  };
1110
1131
  }
1132
+ function replayWanted(open) {
1133
+ return open.replayOwed || !open.replayed && [...open.listeners].some(({ replays }) => replays);
1134
+ }
1111
1135
  function settleOf({ listener }) {
1112
1136
  const settle = listener.replay?.();
1113
1137
  return settle ? [settle] : [];
@@ -1151,7 +1175,7 @@ function createAcpConnection(options) {
1151
1175
  const open = sessions.get(sessionId);
1152
1176
  if (!open)
1153
1177
  return Promise.reject(notOpen());
1154
- const served = open.replaying ? !open.replaying.delivered : !open.replayed || open.replayOwed;
1178
+ const served = open.replaying ? !open.replaying.delivered : replayWanted(open);
1155
1179
  if (!served)
1156
1180
  open.owner?.actor.send({ type: "replay" });
1157
1181
  return joined(sessionId);
@@ -1173,11 +1197,11 @@ function createAcpConnection(options) {
1173
1197
  for (const { listener } of open.listeners)
1174
1198
  callEach(listener.state ? [listener.state] : [], logger, "acp.listener.failed", next);
1175
1199
  }
1176
- function subscribe(sessionId, listener) {
1200
+ function subscribe(sessionId, listener, options = {}) {
1177
1201
  if (ended)
1178
1202
  return () => {};
1179
1203
  start();
1180
- const subscription = { listener };
1204
+ const subscription = { listener, replays: options.replay ?? true };
1181
1205
  const known = sessions.get(sessionId);
1182
1206
  if (known) {
1183
1207
  clock.clearTimeout(known.grace);
@@ -1185,6 +1209,8 @@ function createAcpConnection(options) {
1185
1209
  known.listeners.add(subscription);
1186
1210
  if (known.replaying && !known.replaying.delivered)
1187
1211
  known.replaying.settles.push(...settleOf(subscription));
1212
+ else if (subscription.replays && !known.replayed && !known.replaying)
1213
+ known.owner?.actor.send({ type: "replay" });
1188
1214
  hand(known, known.setup, [subscription]);
1189
1215
  return () => leave(sessionId, known, subscription);
1190
1216
  }
@@ -1216,14 +1242,18 @@ function createAcpConnection(options) {
1216
1242
  return;
1217
1243
  if (sessions.get(sessionId) !== open)
1218
1244
  return;
1245
+ startGrace(sessionId, open);
1246
+ }
1247
+ function startGrace(sessionId, open) {
1248
+ if (open.closing)
1249
+ return;
1219
1250
  open.grace = clock.setTimeout(() => part(sessionId, open), PART_GRACE_MS);
1220
1251
  }
1221
1252
  function openCreated(sessionId, answer) {
1222
1253
  let open = sessions.get(sessionId);
1223
1254
  if (!open) {
1224
- const created = openSession(sessionId, [], true);
1225
- created.grace = clock.setTimeout(() => part(sessionId, created), PART_GRACE_MS);
1226
- open = created;
1255
+ open = openSession(sessionId, [], true);
1256
+ startGrace(sessionId, open);
1227
1257
  }
1228
1258
  hand(open, report(open, setupOfAnswer(answer)));
1229
1259
  }
@@ -1239,6 +1269,28 @@ function createAcpConnection(options) {
1239
1269
  open.waiters?.reject(notOpen());
1240
1270
  open.waiters = undefined;
1241
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
+ }
1242
1294
  function part(sessionId, open) {
1243
1295
  forget(sessionId, open);
1244
1296
  if (open.state === "gone")
@@ -1482,15 +1534,8 @@ function createAcpConnection(options) {
1482
1534
  report(open, { configOptions: response.configOptions });
1483
1535
  return response.configOptions;
1484
1536
  },
1485
- async closeSession(sessionId) {
1486
- const open = sessions.get(sessionId);
1487
- if (open)
1488
- forget(sessionId, open);
1489
- await request("short", (agent, options) => agent.request(methods2.agent.session.close, { sessionId }, options));
1490
- },
1491
- async deleteSession(sessionId) {
1492
- await request("short", (agent, options) => agent.request(methods2.agent.session.delete, { sessionId }, options));
1493
- },
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" })),
1494
1539
  async updateSession(update) {
1495
1540
  await request("short", (agent, options) => agent.request(HGW_METHODS2.session.update, update, options));
1496
1541
  },
@@ -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
@@ -96,6 +96,19 @@ export type AcpSessionListener = {
96
96
  setup?: (setup: AcpSessionSetup) => void;
97
97
  state?: (state: AcpSessionState) => void;
98
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
+ };
99
112
  /**
100
113
  * A read (`listAgents`, `listSessions`, `searchSessions`, `resumePage`) waits
101
114
  * out a reconnect and goes out again on the transport that recovers, and a
@@ -175,9 +188,10 @@ export interface AcpConnection {
175
188
  * parts, with `_hgw/session/part`, 2 s after the last listener leaves, so a
176
189
  * listener back within that grace costs neither a part nor a resume. A
177
190
  * listener that subscribes before anything of a from-start replay under way
178
- * 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`).
179
193
  */
180
- subscribe(sessionId: string, listener: AcpSessionListener): () => void;
194
+ subscribe(sessionId: string, listener: AcpSessionListener, options?: AcpSubscribeOptions): () => void;
181
195
  /** Resolves once the opened Session is joined; rejects once it is gone or parts. */
182
196
  joined(sessionId: string): Promise<void>;
183
197
  /**
@@ -199,7 +213,13 @@ export interface AcpConnection {
199
213
  * reported; a join that replays nothing leaves it as it was.
200
214
  */
201
215
  history(sessionId: string): HgwHistoryCursor | undefined;
202
- /** 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
+ */
203
223
  prompt(sessionId: string, blocks: ContentBlock[], meta: z.infer<typeof HgwPromptMetaSchema>): Promise<{
204
224
  messageId: string;
205
225
  }>;
@@ -207,12 +227,22 @@ export interface AcpConnection {
207
227
  setConfigOption(sessionId: string, configId: string, value: string): Promise<SessionConfigOption[]>;
208
228
  /**
209
229
  * Ends the Session with ACP's `session/close`, which stops its work, and
210
- * forgets it here at once, with no `_hgw/session/part`: its listeners hear
211
- * nothing more of it, and nothing rejoins it. A Session the gateway no
212
- * 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.
213
237
  */
214
238
  closeSession(sessionId: string): Promise<void>;
215
- /** 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
+ */
216
246
  deleteSession(sessionId: string): Promise<void>;
217
247
  updateSession(request: z.infer<typeof HgwSessionUpdateRequestSchema>): Promise<void>;
218
248
  steer(request: z.infer<typeof HgwSteerRequestSchema>): Promise<z.infer<typeof HgwSteerResponseSchema>>;
@@ -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;
@@ -122,6 +122,7 @@ import {
122
122
  HgwTurnMetaSchema2,
123
123
  HgwNoticeMetaSchema2,
124
124
  HgwMessageMetaSchema2,
125
+ HgwMessageFailureMetaSchema2,
125
126
  HgwCostSchema2,
126
127
  HgwChildSessionMetaSchema2,
127
128
  HgwStateMetaSchema2,
@@ -264,6 +265,7 @@ export {
264
265
  HgwHistoryPageTagSchema2 as HgwHistoryPageTagSchema,
265
266
  HgwInitializeMetaSchema2 as HgwInitializeMetaSchema,
266
267
  HgwLoginMetaSchema2 as HgwLoginMetaSchema,
268
+ HgwMessageFailureMetaSchema2 as HgwMessageFailureMetaSchema,
267
269
  HgwMessageMetaSchema2 as HgwMessageMetaSchema,
268
270
  HgwNoticeMetaSchema2 as HgwNoticeMetaSchema,
269
271
  HgwPermissionMetaSchema2 as HgwPermissionMetaSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harness-gw/sdk",
3
- "version": "0.18.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",