@hallohuman/hightea-ahp-host 0.0.0-stage → 0.0.2

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/dist/plugin.js ADDED
@@ -0,0 +1,1927 @@
1
+ import {
2
+ ActiveTurnTokenVault2
3
+ } from "./chunk-92tg572q.js";
4
+ import {
5
+ string,
6
+ array,
7
+ object,
8
+ tuple,
9
+ _enum,
10
+ literal
11
+ } from "./chunk-7eha6eh3.js";
12
+
13
+ // src/plugin.ts
14
+ import WebSocket from "ws";
15
+
16
+ // src/records-store.ts
17
+ import { createHash } from "node:crypto";
18
+
19
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/common/state.js
20
+ var ChannelRecoveryKind;
21
+ (function(ChannelRecoveryKind) {
22
+ ChannelRecoveryKind["Snapshot"] = "snapshot";
23
+ ChannelRecoveryKind["Replay"] = "replay";
24
+ ChannelRecoveryKind["Live"] = "live";
25
+ })(ChannelRecoveryKind || (ChannelRecoveryKind = {}));
26
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-root/state.js
27
+ var PolicyState;
28
+ (function(PolicyState) {
29
+ PolicyState["Enabled"] = "enabled";
30
+ PolicyState["Disabled"] = "disabled";
31
+ PolicyState["Unconfigured"] = "unconfigured";
32
+ })(PolicyState || (PolicyState = {}));
33
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-session/state.js
34
+ var SessionLifecycle;
35
+ (function(SessionLifecycle) {
36
+ SessionLifecycle["Creating"] = "creating";
37
+ SessionLifecycle["Ready"] = "ready";
38
+ SessionLifecycle["Failed"] = "failed";
39
+ })(SessionLifecycle || (SessionLifecycle = {}));
40
+ var SessionStatus;
41
+ (function(SessionStatus) {
42
+ SessionStatus[SessionStatus["Idle"] = 1] = "Idle";
43
+ SessionStatus[SessionStatus["Error"] = 2] = "Error";
44
+ SessionStatus[SessionStatus["InProgress"] = 8] = "InProgress";
45
+ SessionStatus[SessionStatus["InputNeeded"] = 24] = "InputNeeded";
46
+ SessionStatus[SessionStatus["IsRead"] = 32] = "IsRead";
47
+ SessionStatus[SessionStatus["IsArchived"] = 64] = "IsArchived";
48
+ })(SessionStatus || (SessionStatus = {}));
49
+ var SessionOriginKind;
50
+ (function(SessionOriginKind) {
51
+ SessionOriginKind["Automation"] = "automation";
52
+ })(SessionOriginKind || (SessionOriginKind = {}));
53
+ var SessionInputRequestKind;
54
+ (function(SessionInputRequestKind) {
55
+ SessionInputRequestKind["ChatInput"] = "chatInput";
56
+ SessionInputRequestKind["ToolConfirmation"] = "toolConfirmation";
57
+ SessionInputRequestKind["ToolClientExecution"] = "toolClientExecution";
58
+ SessionInputRequestKind["ToolAuthentication"] = "toolAuthentication";
59
+ })(SessionInputRequestKind || (SessionInputRequestKind = {}));
60
+ var CustomizationType;
61
+ (function(CustomizationType) {
62
+ CustomizationType["Plugin"] = "plugin";
63
+ CustomizationType["Directory"] = "directory";
64
+ CustomizationType["Agent"] = "agent";
65
+ CustomizationType["Skill"] = "skill";
66
+ CustomizationType["Prompt"] = "prompt";
67
+ CustomizationType["Rule"] = "rule";
68
+ CustomizationType["Hook"] = "hook";
69
+ CustomizationType["McpServer"] = "mcpServer";
70
+ })(CustomizationType || (CustomizationType = {}));
71
+ var CustomizationEnablementKind;
72
+ (function(CustomizationEnablementKind) {
73
+ CustomizationEnablementKind["Global"] = "global";
74
+ CustomizationEnablementKind["Workspace"] = "workspace";
75
+ CustomizationEnablementKind["Session"] = "session";
76
+ })(CustomizationEnablementKind || (CustomizationEnablementKind = {}));
77
+ var CustomizationLoadStatus;
78
+ (function(CustomizationLoadStatus) {
79
+ CustomizationLoadStatus["Loading"] = "loading";
80
+ CustomizationLoadStatus["Loaded"] = "loaded";
81
+ CustomizationLoadStatus["Degraded"] = "degraded";
82
+ CustomizationLoadStatus["Error"] = "error";
83
+ })(CustomizationLoadStatus || (CustomizationLoadStatus = {}));
84
+ var McpServerStatus;
85
+ (function(McpServerStatus) {
86
+ McpServerStatus["Starting"] = "starting";
87
+ McpServerStatus["Ready"] = "ready";
88
+ McpServerStatus["AuthRequired"] = "authRequired";
89
+ McpServerStatus["Error"] = "error";
90
+ McpServerStatus["Stopped"] = "stopped";
91
+ })(McpServerStatus || (McpServerStatus = {}));
92
+ var McpAuthRequiredReason;
93
+ (function(McpAuthRequiredReason) {
94
+ McpAuthRequiredReason["Required"] = "required";
95
+ McpAuthRequiredReason["Expired"] = "expired";
96
+ McpAuthRequiredReason["InsufficientScope"] = "insufficientScope";
97
+ })(McpAuthRequiredReason || (McpAuthRequiredReason = {}));
98
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-chat/state.js
99
+ var BackgroundWorkKind;
100
+ (function(BackgroundWorkKind) {
101
+ BackgroundWorkKind["Shell"] = "shell";
102
+ BackgroundWorkKind["Subagent"] = "subagent";
103
+ })(BackgroundWorkKind || (BackgroundWorkKind = {}));
104
+ var ChatOriginKind;
105
+ (function(ChatOriginKind) {
106
+ ChatOriginKind["User"] = "user";
107
+ ChatOriginKind["Fork"] = "fork";
108
+ ChatOriginKind["SideChat"] = "sideChat";
109
+ ChatOriginKind["Tool"] = "tool";
110
+ })(ChatOriginKind || (ChatOriginKind = {}));
111
+ var ChatInteractivity;
112
+ (function(ChatInteractivity) {
113
+ ChatInteractivity["Full"] = "full";
114
+ ChatInteractivity["ReadOnly"] = "read-only";
115
+ ChatInteractivity["Hidden"] = "hidden";
116
+ })(ChatInteractivity || (ChatInteractivity = {}));
117
+ var PendingMessageKind;
118
+ (function(PendingMessageKind) {
119
+ PendingMessageKind["Steering"] = "steering";
120
+ PendingMessageKind["Queued"] = "queued";
121
+ })(PendingMessageKind || (PendingMessageKind = {}));
122
+ var ChatInputResponseKind;
123
+ (function(ChatInputResponseKind) {
124
+ ChatInputResponseKind["Accept"] = "accept";
125
+ ChatInputResponseKind["Decline"] = "decline";
126
+ ChatInputResponseKind["Cancel"] = "cancel";
127
+ })(ChatInputResponseKind || (ChatInputResponseKind = {}));
128
+ var ChatInputQuestionKind;
129
+ (function(ChatInputQuestionKind) {
130
+ ChatInputQuestionKind["Text"] = "text";
131
+ ChatInputQuestionKind["Number"] = "number";
132
+ ChatInputQuestionKind["Integer"] = "integer";
133
+ ChatInputQuestionKind["Boolean"] = "boolean";
134
+ ChatInputQuestionKind["SingleSelect"] = "single-select";
135
+ ChatInputQuestionKind["MultiSelect"] = "multi-select";
136
+ })(ChatInputQuestionKind || (ChatInputQuestionKind = {}));
137
+ var ChatInputAnswerValueKind;
138
+ (function(ChatInputAnswerValueKind) {
139
+ ChatInputAnswerValueKind["Text"] = "text";
140
+ ChatInputAnswerValueKind["Number"] = "number";
141
+ ChatInputAnswerValueKind["Boolean"] = "boolean";
142
+ ChatInputAnswerValueKind["Selected"] = "selected";
143
+ ChatInputAnswerValueKind["SelectedMany"] = "selected-many";
144
+ })(ChatInputAnswerValueKind || (ChatInputAnswerValueKind = {}));
145
+ var ChatInputAnswerState;
146
+ (function(ChatInputAnswerState) {
147
+ ChatInputAnswerState["Draft"] = "draft";
148
+ ChatInputAnswerState["Submitted"] = "submitted";
149
+ ChatInputAnswerState["Skipped"] = "skipped";
150
+ })(ChatInputAnswerState || (ChatInputAnswerState = {}));
151
+ var TurnState;
152
+ (function(TurnState) {
153
+ TurnState["Complete"] = "complete";
154
+ TurnState["Cancelled"] = "cancelled";
155
+ TurnState["Error"] = "error";
156
+ })(TurnState || (TurnState = {}));
157
+ var MessageAttachmentKind;
158
+ (function(MessageAttachmentKind) {
159
+ MessageAttachmentKind["Simple"] = "simple";
160
+ MessageAttachmentKind["EmbeddedResource"] = "embeddedResource";
161
+ MessageAttachmentKind["Resource"] = "resource";
162
+ MessageAttachmentKind["Annotations"] = "annotations";
163
+ MessageAttachmentKind["Chat"] = "chat";
164
+ })(MessageAttachmentKind || (MessageAttachmentKind = {}));
165
+ var MessageKind;
166
+ (function(MessageKind) {
167
+ MessageKind["User"] = "user";
168
+ MessageKind["Agent"] = "agent";
169
+ MessageKind["Tool"] = "tool";
170
+ MessageKind["Automation"] = "automation";
171
+ MessageKind["SystemNotification"] = "systemNotification";
172
+ })(MessageKind || (MessageKind = {}));
173
+ var ResponsePartKind;
174
+ (function(ResponsePartKind) {
175
+ ResponsePartKind["Markdown"] = "markdown";
176
+ ResponsePartKind["ContentRef"] = "contentRef";
177
+ ResponsePartKind["ToolCall"] = "toolCall";
178
+ ResponsePartKind["Reasoning"] = "reasoning";
179
+ ResponsePartKind["SystemNotification"] = "systemNotification";
180
+ ResponsePartKind["InputRequest"] = "inputRequest";
181
+ ResponsePartKind["Error"] = "error";
182
+ })(ResponsePartKind || (ResponsePartKind = {}));
183
+ var ToolCallStatus;
184
+ (function(ToolCallStatus) {
185
+ ToolCallStatus["Streaming"] = "streaming";
186
+ ToolCallStatus["PendingConfirmation"] = "pending-confirmation";
187
+ ToolCallStatus["Running"] = "running";
188
+ ToolCallStatus["AuthRequired"] = "auth-required";
189
+ ToolCallStatus["PendingResultConfirmation"] = "pending-result-confirmation";
190
+ ToolCallStatus["Completed"] = "completed";
191
+ ToolCallStatus["Cancelled"] = "cancelled";
192
+ })(ToolCallStatus || (ToolCallStatus = {}));
193
+ var ToolCallConfirmationReason;
194
+ (function(ToolCallConfirmationReason) {
195
+ ToolCallConfirmationReason["NotNeeded"] = "not-needed";
196
+ ToolCallConfirmationReason["UserAction"] = "user-action";
197
+ ToolCallConfirmationReason["Setting"] = "setting";
198
+ })(ToolCallConfirmationReason || (ToolCallConfirmationReason = {}));
199
+ var ToolCallRiskAssessmentKind;
200
+ (function(ToolCallRiskAssessmentKind) {
201
+ ToolCallRiskAssessmentKind["Judge"] = "judge";
202
+ })(ToolCallRiskAssessmentKind || (ToolCallRiskAssessmentKind = {}));
203
+ var ToolCallRiskAssessmentStatus;
204
+ (function(ToolCallRiskAssessmentStatus) {
205
+ ToolCallRiskAssessmentStatus["Loading"] = "loading";
206
+ ToolCallRiskAssessmentStatus["Complete"] = "complete";
207
+ })(ToolCallRiskAssessmentStatus || (ToolCallRiskAssessmentStatus = {}));
208
+ var ToolCallCancellationReason;
209
+ (function(ToolCallCancellationReason) {
210
+ ToolCallCancellationReason["Denied"] = "denied";
211
+ ToolCallCancellationReason["Skipped"] = "skipped";
212
+ ToolCallCancellationReason["ResultDenied"] = "result-denied";
213
+ })(ToolCallCancellationReason || (ToolCallCancellationReason = {}));
214
+ var ConfirmationOptionKind;
215
+ (function(ConfirmationOptionKind) {
216
+ ConfirmationOptionKind["Approve"] = "approve";
217
+ ConfirmationOptionKind["Deny"] = "deny";
218
+ })(ConfirmationOptionKind || (ConfirmationOptionKind = {}));
219
+ var ToolCallContributorKind;
220
+ (function(ToolCallContributorKind) {
221
+ ToolCallContributorKind["Client"] = "client";
222
+ ToolCallContributorKind["MCP"] = "mcp";
223
+ })(ToolCallContributorKind || (ToolCallContributorKind = {}));
224
+ var ToolResultContentType;
225
+ (function(ToolResultContentType) {
226
+ ToolResultContentType["Text"] = "text";
227
+ ToolResultContentType["EmbeddedResource"] = "embeddedResource";
228
+ ToolResultContentType["Resource"] = "resource";
229
+ ToolResultContentType["FileEdit"] = "fileEdit";
230
+ ToolResultContentType["Terminal"] = "terminal";
231
+ ToolResultContentType["Subagent"] = "subagent";
232
+ })(ToolResultContentType || (ToolResultContentType = {}));
233
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-terminal/state.js
234
+ var TerminalLifecycleStatus;
235
+ (function(TerminalLifecycleStatus) {
236
+ TerminalLifecycleStatus["Running"] = "running";
237
+ TerminalLifecycleStatus["Exited"] = "exited";
238
+ })(TerminalLifecycleStatus || (TerminalLifecycleStatus = {}));
239
+ var TerminalClaimKind;
240
+ (function(TerminalClaimKind) {
241
+ TerminalClaimKind["Client"] = "client";
242
+ TerminalClaimKind["Session"] = "session";
243
+ })(TerminalClaimKind || (TerminalClaimKind = {}));
244
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-changeset/state.js
245
+ var ChangesetStatus;
246
+ (function(ChangesetStatus) {
247
+ ChangesetStatus["Computing"] = "computing";
248
+ ChangesetStatus["Recomputing"] = "recomputing";
249
+ ChangesetStatus["Ready"] = "ready";
250
+ ChangesetStatus["Error"] = "error";
251
+ })(ChangesetStatus || (ChangesetStatus = {}));
252
+ var ChangesetFileStatus;
253
+ (function(ChangesetFileStatus) {
254
+ ChangesetFileStatus[ChangesetFileStatus["Editing"] = 1] = "Editing";
255
+ })(ChangesetFileStatus || (ChangesetFileStatus = {}));
256
+ var ChangesetOperationStatus;
257
+ (function(ChangesetOperationStatus) {
258
+ ChangesetOperationStatus["Idle"] = "idle";
259
+ ChangesetOperationStatus["Running"] = "running";
260
+ ChangesetOperationStatus["Error"] = "error";
261
+ ChangesetOperationStatus["Disabled"] = "disabled";
262
+ })(ChangesetOperationStatus || (ChangesetOperationStatus = {}));
263
+ var ChangesetOperationScope;
264
+ (function(ChangesetOperationScope) {
265
+ ChangesetOperationScope["Changeset"] = "changeset";
266
+ ChangesetOperationScope["Resource"] = "resource";
267
+ ChangesetOperationScope["Range"] = "range";
268
+ })(ChangesetOperationScope || (ChangesetOperationScope = {}));
269
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-resource-watch/state.js
270
+ var ResourceChangeType;
271
+ (function(ResourceChangeType) {
272
+ ResourceChangeType["Added"] = "added";
273
+ ResourceChangeType["Updated"] = "updated";
274
+ ResourceChangeType["Deleted"] = "deleted";
275
+ })(ResourceChangeType || (ResourceChangeType = {}));
276
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-automation/state.js
277
+ var AutomationOperation;
278
+ (function(AutomationOperation) {
279
+ AutomationOperation["Update"] = "update";
280
+ AutomationOperation["Remove"] = "remove";
281
+ AutomationOperation["Run"] = "run";
282
+ })(AutomationOperation || (AutomationOperation = {}));
283
+ var AutomationMisfirePolicy;
284
+ (function(AutomationMisfirePolicy) {
285
+ AutomationMisfirePolicy["Skip"] = "skip";
286
+ AutomationMisfirePolicy["RunOnce"] = "runOnce";
287
+ })(AutomationMisfirePolicy || (AutomationMisfirePolicy = {}));
288
+ var AutomationTriggerKind;
289
+ (function(AutomationTriggerKind) {
290
+ AutomationTriggerKind["Schedule"] = "schedule";
291
+ AutomationTriggerKind["Event"] = "event";
292
+ })(AutomationTriggerKind || (AutomationTriggerKind = {}));
293
+ var AutomationDisableConditionKind;
294
+ (function(AutomationDisableConditionKind) {
295
+ AutomationDisableConditionKind["AfterRuns"] = "afterRuns";
296
+ AutomationDisableConditionKind["AfterDate"] = "afterDate";
297
+ })(AutomationDisableConditionKind || (AutomationDisableConditionKind = {}));
298
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-automation-run/state.js
299
+ var AutomationRunStatus;
300
+ (function(AutomationRunStatus) {
301
+ AutomationRunStatus["Pending"] = "pending";
302
+ AutomationRunStatus["Running"] = "running";
303
+ AutomationRunStatus["Completed"] = "completed";
304
+ AutomationRunStatus["Failed"] = "failed";
305
+ AutomationRunStatus["Cancelled"] = "cancelled";
306
+ })(AutomationRunStatus || (AutomationRunStatus = {}));
307
+ var AutomationRunOriginKind;
308
+ (function(AutomationRunOriginKind) {
309
+ AutomationRunOriginKind["Manual"] = "manual";
310
+ AutomationRunOriginKind["Trigger"] = "trigger";
311
+ })(AutomationRunOriginKind || (AutomationRunOriginKind = {}));
312
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/common/actions.js
313
+ var ActionType;
314
+ (function(ActionType) {
315
+ ActionType["RootAgentsChanged"] = "root/agentsChanged";
316
+ ActionType["RootActiveSessionsChanged"] = "root/activeSessionsChanged";
317
+ ActionType["SessionReady"] = "session/ready";
318
+ ActionType["SessionCreationFailed"] = "session/creationFailed";
319
+ ActionType["SessionChatAdded"] = "session/chatAdded";
320
+ ActionType["SessionChatRemoved"] = "session/chatRemoved";
321
+ ActionType["SessionChatUpdated"] = "session/chatUpdated";
322
+ ActionType["SessionChatsReordered"] = "session/chatsReordered";
323
+ ActionType["SessionDefaultChatChanged"] = "session/defaultChatChanged";
324
+ ActionType["ChatTurnStarted"] = "chat/turnStarted";
325
+ ActionType["ChatDelta"] = "chat/delta";
326
+ ActionType["ChatResponsePart"] = "chat/responsePart";
327
+ ActionType["ChatToolCallStart"] = "chat/toolCallStart";
328
+ ActionType["ChatToolCallDelta"] = "chat/toolCallDelta";
329
+ ActionType["ChatToolCallReady"] = "chat/toolCallReady";
330
+ ActionType["ChatToolCallConfirmed"] = "chat/toolCallConfirmed";
331
+ ActionType["ChatToolCallComplete"] = "chat/toolCallComplete";
332
+ ActionType["ChatToolCallResultConfirmed"] = "chat/toolCallResultConfirmed";
333
+ ActionType["ChatToolCallContentChanged"] = "chat/toolCallContentChanged";
334
+ ActionType["ChatToolCallAuthRequired"] = "chat/toolCallAuthRequired";
335
+ ActionType["ChatToolCallAuthResolved"] = "chat/toolCallAuthResolved";
336
+ ActionType["ChatTurnComplete"] = "chat/turnComplete";
337
+ ActionType["ChatTurnCancelled"] = "chat/turnCancelled";
338
+ ActionType["ChatError"] = "chat/error";
339
+ ActionType["ChatTurnResume"] = "chat/turnResume";
340
+ ActionType["ChatActivityChanged"] = "chat/activityChanged";
341
+ ActionType["ChatBackgroundWorkSet"] = "chat/backgroundWorkSet";
342
+ ActionType["ChatBackgroundWorkRemoved"] = "chat/backgroundWorkRemoved";
343
+ ActionType["ChatMovableChanged"] = "chat/movableChanged";
344
+ ActionType["ChatChangesetsChanged"] = "chat/changesetsChanged";
345
+ ActionType["ChatCanvasesChanged"] = "chat/canvasesChanged";
346
+ ActionType["CanvasStateChanged"] = "canvas/stateChanged";
347
+ ActionType["ChatWorkingDirectorySet"] = "chat/workingDirectorySet";
348
+ ActionType["ChatWorkingDirectoryRemoved"] = "chat/workingDirectoryRemoved";
349
+ ActionType["SessionTitleChanged"] = "session/titleChanged";
350
+ ActionType["ChatUsage"] = "chat/usage";
351
+ ActionType["ChatReasoning"] = "chat/reasoning";
352
+ ActionType["SessionServerToolsChanged"] = "session/serverToolsChanged";
353
+ ActionType["SessionActiveClientSet"] = "session/activeClientSet";
354
+ ActionType["SessionActiveClientRemoved"] = "session/activeClientRemoved";
355
+ ActionType["SessionWorkingDirectorySet"] = "session/workingDirectorySet";
356
+ ActionType["SessionWorkingDirectoryRemoved"] = "session/workingDirectoryRemoved";
357
+ ActionType["SessionWorkingDirectoryReplaced"] = "session/workingDirectoryReplaced";
358
+ ActionType["SessionInputNeededSet"] = "session/inputNeededSet";
359
+ ActionType["SessionInputNeededRemoved"] = "session/inputNeededRemoved";
360
+ ActionType["ChatPendingMessageSet"] = "chat/pendingMessageSet";
361
+ ActionType["ChatPendingMessageRemoved"] = "chat/pendingMessageRemoved";
362
+ ActionType["ChatQueuedMessagesReordered"] = "chat/queuedMessagesReordered";
363
+ ActionType["ChatDraftChanged"] = "chat/draftChanged";
364
+ ActionType["ChatIsReadChanged"] = "chat/isReadChanged";
365
+ ActionType["ChatIsArchivedChanged"] = "chat/isArchivedChanged";
366
+ ActionType["ChatConfigChanged"] = "chat/configChanged";
367
+ ActionType["ChatMoved"] = "chat/moved";
368
+ ActionType["ChatInputRequested"] = "chat/inputRequested";
369
+ ActionType["ChatInputAnswerChanged"] = "chat/inputAnswerChanged";
370
+ ActionType["ChatInputCompleted"] = "chat/inputCompleted";
371
+ ActionType["SessionCustomizationsChanged"] = "session/customizationsChanged";
372
+ ActionType["SessionCustomizationToggled"] = "session/customizationToggled";
373
+ ActionType["SessionCustomizationUpdated"] = "session/customizationUpdated";
374
+ ActionType["SessionCustomizationRemoved"] = "session/customizationRemoved";
375
+ ActionType["SessionMcpServerStateChanged"] = "session/mcpServerStateChanged";
376
+ ActionType["SessionMcpServerStartRequested"] = "session/mcpServerStartRequested";
377
+ ActionType["SessionMcpServerStopRequested"] = "session/mcpServerStopRequested";
378
+ ActionType["SessionMcpServerBackgroundRequested"] = "session/mcpServerBackgroundRequested";
379
+ ActionType["ChatTruncated"] = "chat/truncated";
380
+ ActionType["ChatTurnsLoaded"] = "chat/turnsLoaded";
381
+ ActionType["SessionIsReadChanged"] = "session/isReadChanged";
382
+ ActionType["SessionIsArchivedChanged"] = "session/isArchivedChanged";
383
+ ActionType["SessionActivityChanged"] = "session/activityChanged";
384
+ ActionType["SessionChangesetsChanged"] = "session/changesetsChanged";
385
+ ActionType["SessionConfigChanged"] = "session/configChanged";
386
+ ActionType["SessionMetaChanged"] = "session/metaChanged";
387
+ ActionType["ChangesetStatusChanged"] = "changeset/statusChanged";
388
+ ActionType["ChangesetFileSet"] = "changeset/fileSet";
389
+ ActionType["ChangesetFileRemoved"] = "changeset/fileRemoved";
390
+ ActionType["ChangesetFilesReviewChanged"] = "changeset/filesReviewChanged";
391
+ ActionType["ChangesetContentChanged"] = "changeset/contentChanged";
392
+ ActionType["ChangesetOperationsChanged"] = "changeset/operationsChanged";
393
+ ActionType["ChangesetOperationStatusChanged"] = "changeset/operationStatusChanged";
394
+ ActionType["ChangesetCleared"] = "changeset/cleared";
395
+ ActionType["AnnotationsSet"] = "annotations/set";
396
+ ActionType["AnnotationsUpdated"] = "annotations/updated";
397
+ ActionType["AnnotationsRemoved"] = "annotations/removed";
398
+ ActionType["AnnotationsEntrySet"] = "annotations/entrySet";
399
+ ActionType["AnnotationsEntryRemoved"] = "annotations/entryRemoved";
400
+ ActionType["RootTerminalsChanged"] = "root/terminalsChanged";
401
+ ActionType["RootConfigChanged"] = "root/configChanged";
402
+ ActionType["TerminalData"] = "terminal/data";
403
+ ActionType["TerminalInput"] = "terminal/input";
404
+ ActionType["TerminalResized"] = "terminal/resized";
405
+ ActionType["TerminalClaimed"] = "terminal/claimed";
406
+ ActionType["TerminalTitleChanged"] = "terminal/titleChanged";
407
+ ActionType["TerminalCwdChanged"] = "terminal/cwdChanged";
408
+ ActionType["TerminalExited"] = "terminal/exited";
409
+ ActionType["TerminalCleared"] = "terminal/cleared";
410
+ ActionType["TerminalCommandDetectionAvailable"] = "terminal/commandDetectionAvailable";
411
+ ActionType["TerminalCommandExecuted"] = "terminal/commandExecuted";
412
+ ActionType["TerminalCommandFinished"] = "terminal/commandFinished";
413
+ ActionType["ResourceWatchChanged"] = "resourceWatch/changed";
414
+ ActionType["AutomationCreateRequested"] = "automation/createRequested";
415
+ ActionType["AutomationUpdateRequested"] = "automation/updateRequested";
416
+ ActionType["AutomationSet"] = "automation/set";
417
+ ActionType["AutomationRemoved"] = "automation/removed";
418
+ ActionType["AutomationRunLifecycleChanged"] = "automationRun/lifecycleChanged";
419
+ ActionType["AutomationRunSessionSet"] = "automationRun/sessionSet";
420
+ ActionType["AutomationRunSessionRemoved"] = "automationRun/sessionRemoved";
421
+ ActionType["AutomationRunPrimarySessionChanged"] = "automationRun/primarySessionChanged";
422
+ ActionType["AutomationRunCancelRequested"] = "automationRun/cancelRequested";
423
+ })(ActionType || (ActionType = {}));
424
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/action-origin.generated.js
425
+ var IS_CLIENT_DISPATCHABLE = {
426
+ [ActionType.RootAgentsChanged]: false,
427
+ [ActionType.RootActiveSessionsChanged]: false,
428
+ [ActionType.RootTerminalsChanged]: false,
429
+ [ActionType.RootConfigChanged]: true,
430
+ [ActionType.SessionReady]: false,
431
+ [ActionType.SessionCreationFailed]: false,
432
+ [ActionType.SessionChatAdded]: false,
433
+ [ActionType.SessionChatRemoved]: false,
434
+ [ActionType.SessionChatUpdated]: false,
435
+ [ActionType.SessionChatsReordered]: false,
436
+ [ActionType.SessionDefaultChatChanged]: false,
437
+ [ActionType.SessionTitleChanged]: true,
438
+ [ActionType.SessionServerToolsChanged]: false,
439
+ [ActionType.SessionActiveClientSet]: true,
440
+ [ActionType.SessionActiveClientRemoved]: true,
441
+ [ActionType.SessionWorkingDirectorySet]: true,
442
+ [ActionType.SessionWorkingDirectoryRemoved]: true,
443
+ [ActionType.SessionWorkingDirectoryReplaced]: true,
444
+ [ActionType.SessionInputNeededSet]: false,
445
+ [ActionType.SessionInputNeededRemoved]: false,
446
+ [ActionType.SessionCustomizationsChanged]: false,
447
+ [ActionType.SessionCustomizationToggled]: true,
448
+ [ActionType.SessionCustomizationUpdated]: false,
449
+ [ActionType.SessionCustomizationRemoved]: false,
450
+ [ActionType.SessionMcpServerStateChanged]: false,
451
+ [ActionType.SessionMcpServerStartRequested]: true,
452
+ [ActionType.SessionMcpServerStopRequested]: true,
453
+ [ActionType.SessionMcpServerBackgroundRequested]: true,
454
+ [ActionType.SessionIsReadChanged]: true,
455
+ [ActionType.SessionIsArchivedChanged]: true,
456
+ [ActionType.SessionActivityChanged]: false,
457
+ [ActionType.SessionChangesetsChanged]: false,
458
+ [ActionType.SessionConfigChanged]: true,
459
+ [ActionType.SessionMetaChanged]: false,
460
+ [ActionType.ChatTurnStarted]: true,
461
+ [ActionType.ChatDelta]: false,
462
+ [ActionType.ChatResponsePart]: false,
463
+ [ActionType.ChatToolCallStart]: false,
464
+ [ActionType.ChatToolCallDelta]: false,
465
+ [ActionType.ChatToolCallReady]: false,
466
+ [ActionType.ChatToolCallConfirmed]: true,
467
+ [ActionType.ChatToolCallComplete]: true,
468
+ [ActionType.ChatToolCallResultConfirmed]: true,
469
+ [ActionType.ChatToolCallContentChanged]: true,
470
+ [ActionType.ChatToolCallAuthRequired]: false,
471
+ [ActionType.ChatToolCallAuthResolved]: false,
472
+ [ActionType.ChatTurnComplete]: false,
473
+ [ActionType.ChatTurnCancelled]: true,
474
+ [ActionType.ChatError]: false,
475
+ [ActionType.ChatTurnResume]: true,
476
+ [ActionType.ChatActivityChanged]: false,
477
+ [ActionType.ChatBackgroundWorkSet]: false,
478
+ [ActionType.ChatBackgroundWorkRemoved]: false,
479
+ [ActionType.ChatMovableChanged]: false,
480
+ [ActionType.ChatChangesetsChanged]: false,
481
+ [ActionType.ChatCanvasesChanged]: false,
482
+ [ActionType.CanvasStateChanged]: false,
483
+ [ActionType.ChatWorkingDirectorySet]: true,
484
+ [ActionType.ChatWorkingDirectoryRemoved]: true,
485
+ [ActionType.ChatUsage]: false,
486
+ [ActionType.ChatReasoning]: false,
487
+ [ActionType.ChatPendingMessageSet]: true,
488
+ [ActionType.ChatPendingMessageRemoved]: true,
489
+ [ActionType.ChatQueuedMessagesReordered]: true,
490
+ [ActionType.ChatDraftChanged]: true,
491
+ [ActionType.ChatIsReadChanged]: true,
492
+ [ActionType.ChatIsArchivedChanged]: true,
493
+ [ActionType.ChatConfigChanged]: true,
494
+ [ActionType.ChatMoved]: false,
495
+ [ActionType.ChatInputRequested]: false,
496
+ [ActionType.ChatInputAnswerChanged]: true,
497
+ [ActionType.ChatInputCompleted]: true,
498
+ [ActionType.ChatTruncated]: true,
499
+ [ActionType.ChatTurnsLoaded]: false,
500
+ [ActionType.ChangesetStatusChanged]: false,
501
+ [ActionType.ChangesetFileSet]: false,
502
+ [ActionType.ChangesetFileRemoved]: false,
503
+ [ActionType.ChangesetFilesReviewChanged]: true,
504
+ [ActionType.ChangesetContentChanged]: false,
505
+ [ActionType.ChangesetOperationsChanged]: false,
506
+ [ActionType.ChangesetOperationStatusChanged]: false,
507
+ [ActionType.ChangesetCleared]: false,
508
+ [ActionType.AnnotationsSet]: true,
509
+ [ActionType.AnnotationsUpdated]: true,
510
+ [ActionType.AnnotationsRemoved]: true,
511
+ [ActionType.AnnotationsEntrySet]: true,
512
+ [ActionType.AnnotationsEntryRemoved]: true,
513
+ [ActionType.TerminalData]: false,
514
+ [ActionType.TerminalInput]: true,
515
+ [ActionType.TerminalResized]: true,
516
+ [ActionType.TerminalClaimed]: true,
517
+ [ActionType.TerminalTitleChanged]: true,
518
+ [ActionType.TerminalCwdChanged]: false,
519
+ [ActionType.TerminalExited]: false,
520
+ [ActionType.TerminalCleared]: true,
521
+ [ActionType.TerminalCommandDetectionAvailable]: false,
522
+ [ActionType.TerminalCommandExecuted]: false,
523
+ [ActionType.TerminalCommandFinished]: false,
524
+ [ActionType.ResourceWatchChanged]: false,
525
+ [ActionType.AutomationCreateRequested]: true,
526
+ [ActionType.AutomationUpdateRequested]: true,
527
+ [ActionType.AutomationSet]: false,
528
+ [ActionType.AutomationRemoved]: true,
529
+ [ActionType.AutomationRunLifecycleChanged]: false,
530
+ [ActionType.AutomationRunSessionSet]: false,
531
+ [ActionType.AutomationRunSessionRemoved]: false,
532
+ [ActionType.AutomationRunPrimarySessionChanged]: false,
533
+ [ActionType.AutomationRunCancelRequested]: true
534
+ };
535
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/window-exempt.generated.js
536
+ var WINDOW_EXEMPT_METHODS = [
537
+ "channel/credit",
538
+ "tcp/reset",
539
+ "unsubscribe"
540
+ ];
541
+ var windowExemptMethods = new Set(WINDOW_EXEMPT_METHODS);
542
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/common/commands.js
543
+ var PathStyle;
544
+ (function(PathStyle) {
545
+ PathStyle["Posix"] = "posix";
546
+ PathStyle["Windows"] = "windows";
547
+ })(PathStyle || (PathStyle = {}));
548
+ var ReconnectResultType;
549
+ (function(ReconnectResultType) {
550
+ ReconnectResultType["Replay"] = "replay";
551
+ ReconnectResultType["Snapshot"] = "snapshot";
552
+ })(ReconnectResultType || (ReconnectResultType = {}));
553
+ var ContentEncoding;
554
+ (function(ContentEncoding) {
555
+ ContentEncoding["Base64"] = "base64";
556
+ ContentEncoding["Utf8"] = "utf-8";
557
+ })(ContentEncoding || (ContentEncoding = {}));
558
+ var ResourceWriteMode;
559
+ (function(ResourceWriteMode) {
560
+ ResourceWriteMode["Truncate"] = "truncate";
561
+ ResourceWriteMode["Append"] = "append";
562
+ ResourceWriteMode["Insert"] = "insert";
563
+ })(ResourceWriteMode || (ResourceWriteMode = {}));
564
+ var ResourceType;
565
+ (function(ResourceType) {
566
+ ResourceType["File"] = "file";
567
+ ResourceType["Directory"] = "directory";
568
+ ResourceType["Symlink"] = "symlink";
569
+ })(ResourceType || (ResourceType = {}));
570
+ var AuthenticateTargetKind;
571
+ (function(AuthenticateTargetKind) {
572
+ AuthenticateTargetKind["McpServer"] = "mcpServer";
573
+ })(AuthenticateTargetKind || (AuthenticateTargetKind = {}));
574
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-session/commands.js
575
+ var CompletionItemKind;
576
+ (function(CompletionItemKind) {
577
+ CompletionItemKind["UserMessage"] = "userMessage";
578
+ })(CompletionItemKind || (CompletionItemKind = {}));
579
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-chat/commands.js
580
+ var ChatSourceKind;
581
+ (function(ChatSourceKind) {
582
+ ChatSourceKind["Fork"] = "fork";
583
+ ChatSourceKind["SideChat"] = "sideChat";
584
+ })(ChatSourceKind || (ChatSourceKind = {}));
585
+ var ChatMoveDestinationKind;
586
+ (function(ChatMoveDestinationKind) {
587
+ ChatMoveDestinationKind["Session"] = "session";
588
+ ChatMoveDestinationKind["NewSession"] = "newSession";
589
+ })(ChatMoveDestinationKind || (ChatMoveDestinationKind = {}));
590
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-changeset/commands.js
591
+ var ChangesetOperationTargetKind;
592
+ (function(ChangesetOperationTargetKind) {
593
+ ChangesetOperationTargetKind["Resource"] = "resource";
594
+ ChangesetOperationTargetKind["Range"] = "range";
595
+ })(ChangesetOperationTargetKind || (ChangesetOperationTargetKind = {}));
596
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/common/notifications.js
597
+ var AuthRequiredReason;
598
+ (function(AuthRequiredReason) {
599
+ AuthRequiredReason["Required"] = "required";
600
+ AuthRequiredReason["Expired"] = "expired";
601
+ })(AuthRequiredReason || (AuthRequiredReason = {}));
602
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/version/registry.js
603
+ var SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
604
+ "1.0.0",
605
+ "0.9.0"
606
+ ]);
607
+ var ACTION_INTRODUCED_IN = {
608
+ [ActionType.RootAgentsChanged]: "0.1.0",
609
+ [ActionType.RootActiveSessionsChanged]: "0.1.0",
610
+ [ActionType.SessionReady]: "0.1.0",
611
+ [ActionType.SessionCreationFailed]: "0.1.0",
612
+ [ActionType.SessionChatAdded]: "0.4.0",
613
+ [ActionType.SessionChatRemoved]: "0.4.0",
614
+ [ActionType.SessionChatUpdated]: "0.4.0",
615
+ [ActionType.SessionChatsReordered]: "0.9.0",
616
+ [ActionType.SessionDefaultChatChanged]: "0.4.0",
617
+ [ActionType.SessionTitleChanged]: "0.1.0",
618
+ [ActionType.SessionServerToolsChanged]: "0.1.0",
619
+ [ActionType.SessionActiveClientSet]: "0.5.0",
620
+ [ActionType.SessionActiveClientRemoved]: "0.5.0",
621
+ [ActionType.SessionWorkingDirectorySet]: "0.7.0",
622
+ [ActionType.SessionWorkingDirectoryRemoved]: "0.7.0",
623
+ [ActionType.SessionWorkingDirectoryReplaced]: "0.8.0",
624
+ [ActionType.SessionInputNeededSet]: "0.5.1",
625
+ [ActionType.SessionInputNeededRemoved]: "0.5.1",
626
+ [ActionType.SessionCustomizationsChanged]: "0.1.0",
627
+ [ActionType.SessionCustomizationToggled]: "0.1.0",
628
+ [ActionType.SessionCustomizationUpdated]: "0.1.0",
629
+ [ActionType.SessionCustomizationRemoved]: "0.2.0",
630
+ [ActionType.SessionMcpServerStateChanged]: "0.3.0",
631
+ [ActionType.SessionMcpServerStartRequested]: "0.5.2",
632
+ [ActionType.SessionMcpServerStopRequested]: "0.5.2",
633
+ [ActionType.SessionMcpServerBackgroundRequested]: "0.9.0",
634
+ [ActionType.SessionIsReadChanged]: "0.1.0",
635
+ [ActionType.SessionIsArchivedChanged]: "0.1.0",
636
+ [ActionType.SessionActivityChanged]: "0.1.0",
637
+ [ActionType.SessionChangesetsChanged]: "0.2.0",
638
+ [ActionType.SessionConfigChanged]: "0.1.0",
639
+ [ActionType.SessionMetaChanged]: "0.1.0",
640
+ [ActionType.ChatTurnStarted]: "0.4.0",
641
+ [ActionType.ChatDelta]: "0.4.0",
642
+ [ActionType.ChatResponsePart]: "0.4.0",
643
+ [ActionType.ChatToolCallStart]: "0.4.0",
644
+ [ActionType.ChatToolCallDelta]: "0.4.0",
645
+ [ActionType.ChatToolCallReady]: "0.4.0",
646
+ [ActionType.ChatToolCallConfirmed]: "0.4.0",
647
+ [ActionType.ChatToolCallComplete]: "0.4.0",
648
+ [ActionType.ChatToolCallResultConfirmed]: "0.4.0",
649
+ [ActionType.ChatToolCallContentChanged]: "0.4.0",
650
+ [ActionType.ChatToolCallAuthRequired]: "0.6.0",
651
+ [ActionType.ChatToolCallAuthResolved]: "0.6.0",
652
+ [ActionType.ChatTurnComplete]: "0.4.0",
653
+ [ActionType.ChatTurnCancelled]: "0.4.0",
654
+ [ActionType.ChatError]: "0.4.0",
655
+ [ActionType.ChatTurnResume]: "0.9.0",
656
+ [ActionType.ChatActivityChanged]: "0.5.0",
657
+ [ActionType.ChatBackgroundWorkSet]: "0.9.0",
658
+ [ActionType.ChatBackgroundWorkRemoved]: "0.9.0",
659
+ [ActionType.ChatMovableChanged]: "0.9.0",
660
+ [ActionType.ChatChangesetsChanged]: "0.9.0",
661
+ [ActionType.ChatCanvasesChanged]: "0.10.0",
662
+ [ActionType.CanvasStateChanged]: "0.10.0",
663
+ [ActionType.ChatWorkingDirectorySet]: "0.7.0",
664
+ [ActionType.ChatWorkingDirectoryRemoved]: "0.7.0",
665
+ [ActionType.ChatUsage]: "0.4.0",
666
+ [ActionType.ChatReasoning]: "0.4.0",
667
+ [ActionType.ChatPendingMessageSet]: "0.4.0",
668
+ [ActionType.ChatPendingMessageRemoved]: "0.4.0",
669
+ [ActionType.ChatQueuedMessagesReordered]: "0.4.0",
670
+ [ActionType.ChatDraftChanged]: "0.5.0",
671
+ [ActionType.ChatIsReadChanged]: "0.9.0",
672
+ [ActionType.ChatIsArchivedChanged]: "0.9.0",
673
+ [ActionType.ChatConfigChanged]: "1.1.0",
674
+ [ActionType.ChatMoved]: "1.1.0",
675
+ [ActionType.ChatInputRequested]: "0.4.0",
676
+ [ActionType.ChatInputAnswerChanged]: "0.4.0",
677
+ [ActionType.ChatInputCompleted]: "0.4.0",
678
+ [ActionType.ChatTruncated]: "0.4.0",
679
+ [ActionType.ChatTurnsLoaded]: "0.5.1",
680
+ [ActionType.ChangesetStatusChanged]: "0.2.0",
681
+ [ActionType.ChangesetFileSet]: "0.2.0",
682
+ [ActionType.ChangesetFileRemoved]: "0.2.0",
683
+ [ActionType.ChangesetFilesReviewChanged]: "0.6.0",
684
+ [ActionType.ChangesetContentChanged]: "0.4.0",
685
+ [ActionType.ChangesetOperationsChanged]: "0.2.0",
686
+ [ActionType.ChangesetOperationStatusChanged]: "0.3.0",
687
+ [ActionType.ChangesetCleared]: "0.2.0",
688
+ [ActionType.AnnotationsSet]: "0.4.0",
689
+ [ActionType.AnnotationsUpdated]: "0.4.0",
690
+ [ActionType.AnnotationsRemoved]: "0.4.0",
691
+ [ActionType.AnnotationsEntrySet]: "0.4.0",
692
+ [ActionType.AnnotationsEntryRemoved]: "0.4.0",
693
+ [ActionType.RootTerminalsChanged]: "0.1.0",
694
+ [ActionType.RootConfigChanged]: "0.1.0",
695
+ [ActionType.TerminalData]: "0.1.0",
696
+ [ActionType.TerminalInput]: "0.1.0",
697
+ [ActionType.TerminalResized]: "0.1.0",
698
+ [ActionType.TerminalClaimed]: "0.1.0",
699
+ [ActionType.TerminalTitleChanged]: "0.1.0",
700
+ [ActionType.TerminalCwdChanged]: "0.1.0",
701
+ [ActionType.TerminalExited]: "0.1.0",
702
+ [ActionType.TerminalCleared]: "0.1.0",
703
+ [ActionType.TerminalCommandDetectionAvailable]: "0.1.0",
704
+ [ActionType.TerminalCommandExecuted]: "0.1.0",
705
+ [ActionType.TerminalCommandFinished]: "0.1.0",
706
+ [ActionType.ResourceWatchChanged]: "0.2.0",
707
+ [ActionType.AutomationCreateRequested]: "0.8.0",
708
+ [ActionType.AutomationUpdateRequested]: "0.8.0",
709
+ [ActionType.AutomationSet]: "0.8.0",
710
+ [ActionType.AutomationRemoved]: "0.8.0",
711
+ [ActionType.AutomationRunLifecycleChanged]: "0.8.0",
712
+ [ActionType.AutomationRunSessionSet]: "0.8.0",
713
+ [ActionType.AutomationRunSessionRemoved]: "0.8.0",
714
+ [ActionType.AutomationRunPrimarySessionChanged]: "0.8.0",
715
+ [ActionType.AutomationRunCancelRequested]: "0.8.0"
716
+ };
717
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-session/reducer.js
718
+ var STATUS_ACTIVITY_MASK = (1 << 5) - 1;
719
+ // ../../node_modules/.bun/@microsoft+agent-host-protocol@1.1.0/node_modules/@microsoft/agent-host-protocol/dist/types/channels-chat/reducer.js
720
+ var STATUS_ACTIVITY_MASK2 = (1 << 5) - 1;
721
+ // ../ahp/src/index.ts
722
+ var HOST_TO_CLOUD_EVENTS = [
723
+ "session.created",
724
+ "turn.started",
725
+ "turn.finished",
726
+ "turn.error"
727
+ ];
728
+ var BOUNDED_ERROR_CODES = [
729
+ "OPERATION_NOT_ALLOWLISTED",
730
+ "INVALID_OPERATION_SHAPE",
731
+ "UNKNOWN_HOUSE_OR_MEMBER",
732
+ "UNMAPPED_LOCAL_AGENT",
733
+ "FOREIGN_SESSION_REFUSED",
734
+ "TOKEN_EXPIRED_OR_REVOKED",
735
+ "HOST_REVOKED",
736
+ "HOST_RESTARTED",
737
+ "INPUT_REQUIRED",
738
+ "APPROVAL_REQUIRED",
739
+ "VERSION_UNSUPPORTED",
740
+ "WAKE_NOT_SENT"
741
+ ];
742
+ var WakeMetaSchema = object({
743
+ houseId: string().min(1),
744
+ deliveryId: string().min(1),
745
+ turnId: string().min(1).optional(),
746
+ agentMemberId: string().min(1),
747
+ threadRef: string().min(1),
748
+ afterMessageId: string().min(1).optional(),
749
+ triggeringMessageIds: array(string().min(1)).min(1).refine((ids) => new Set(ids).size === ids.length).optional(),
750
+ agentToken: string().min(1).optional()
751
+ }).strict();
752
+ var HostToCloudFrameSchema = object({
753
+ event: _enum(HOST_TO_CLOUD_EVENTS),
754
+ houseId: string().min(1),
755
+ deliveryId: string().min(1),
756
+ sessionId: string().min(1),
757
+ chatId: string().min(1),
758
+ turnId: string().min(1).optional(),
759
+ turnState: _enum(["created", "running", "finished", "error"]),
760
+ statusCode: string().min(1).max(64),
761
+ errorCode: _enum(BOUNDED_ERROR_CODES).optional(),
762
+ errorDetail: string().max(256).optional()
763
+ }).strict();
764
+ function parseHostToCloudFrame(input) {
765
+ return HostToCloudFrameSchema.parse(input);
766
+ }
767
+
768
+ // src/pipe.ts
769
+ var sessionKey = (houseId, agentMemberId, threadRef) => JSON.stringify([houseId, agentMemberId, threadRef]);
770
+ var SESSION_URI = /^ahp-session:\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
771
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
772
+ var refuse = (code) => ({ ok: false, code });
773
+ function isRecord(value) {
774
+ return typeof value === "object" && value !== null && !Array.isArray(value);
775
+ }
776
+ function exactKeys(value, required, optional = []) {
777
+ const allowed = new Set([...required, ...optional]);
778
+ return required.every((key) => (key in value)) && Object.keys(value).every((key) => allowed.has(key));
779
+ }
780
+ function readMeta(params) {
781
+ const parsed = WakeMetaSchema.safeParse(params._meta);
782
+ return parsed.success ? parsed.data : undefined;
783
+ }
784
+ function checkCloudFrame(frame, registry) {
785
+ if (!isRecord(frame) || typeof frame.method !== "string")
786
+ return refuse("INVALID_OPERATION_SHAPE");
787
+ if (!exactKeys(frame, ["method"], ["jsonrpc", "id", "params"]))
788
+ return refuse("INVALID_OPERATION_SHAPE");
789
+ const method = frame.method;
790
+ if (method !== "createSession" && method !== "subscribe" && method !== "dispatchAction") {
791
+ return refuse("OPERATION_NOT_ALLOWLISTED");
792
+ }
793
+ const params = frame.params;
794
+ if (!isRecord(params))
795
+ return refuse("INVALID_OPERATION_SHAPE");
796
+ const meta = readMeta(params);
797
+ if (meta === undefined)
798
+ return refuse("INVALID_OPERATION_SHAPE");
799
+ if (meta.houseId !== registry.houseId)
800
+ return refuse("UNKNOWN_HOUSE_OR_MEMBER");
801
+ const agent = registry.agents.get(meta.agentMemberId);
802
+ if (agent === undefined)
803
+ return refuse("UNMAPPED_LOCAL_AGENT");
804
+ const key = sessionKey(meta.houseId, meta.agentMemberId, meta.threadRef);
805
+ const mapped = registry.sessions.get(key);
806
+ const { agentToken, ...publicMeta } = meta;
807
+ const id = frame.id;
808
+ const head = { jsonrpc: "2.0", ...id === undefined ? {} : { id } };
809
+ const channel = params.channel;
810
+ if (method === "createSession") {
811
+ if (!exactKeys(params, ["channel", "_meta"]))
812
+ return refuse("INVALID_OPERATION_SHAPE");
813
+ if (typeof channel !== "string" || !SESSION_URI.test(channel))
814
+ return refuse("INVALID_OPERATION_SHAPE");
815
+ if (mapped !== undefined)
816
+ return refuse("INVALID_OPERATION_SHAPE");
817
+ if (isKnownSession(registry, channel))
818
+ return refuse("FOREIGN_SESSION_REFUSED");
819
+ return {
820
+ ok: true,
821
+ operation: "session.create",
822
+ frame: {
823
+ ...head,
824
+ method,
825
+ params: { channel, provider: agent.provider, workingDirectories: [agent.workingDirectory] }
826
+ },
827
+ meta: publicMeta,
828
+ ...agentToken === undefined ? {} : { agentToken },
829
+ sessionKey: key
830
+ };
831
+ }
832
+ if (method === "subscribe") {
833
+ if (!exactKeys(params, ["channel", "_meta"]))
834
+ return refuse("INVALID_OPERATION_SHAPE");
835
+ if (typeof channel !== "string")
836
+ return refuse("INVALID_OPERATION_SHAPE");
837
+ if (mapped === undefined || mapped.sessionUri !== channel)
838
+ return refuse("FOREIGN_SESSION_REFUSED");
839
+ return {
840
+ ok: true,
841
+ operation: "session.open",
842
+ frame: { ...head, method, params: { channel } },
843
+ meta: publicMeta,
844
+ ...agentToken === undefined ? {} : { agentToken },
845
+ sessionKey: key
846
+ };
847
+ }
848
+ if (!exactKeys(params, ["channel", "clientSeq", "action", "_meta"]))
849
+ return refuse("INVALID_OPERATION_SHAPE");
850
+ if (typeof params.clientSeq !== "number" || !Number.isInteger(params.clientSeq) || params.clientSeq < 1) {
851
+ return refuse("INVALID_OPERATION_SHAPE");
852
+ }
853
+ if (typeof channel !== "string")
854
+ return refuse("INVALID_OPERATION_SHAPE");
855
+ if (mapped?.chatUri === undefined || mapped.chatUri !== channel)
856
+ return refuse("FOREIGN_SESSION_REFUSED");
857
+ const action = params.action;
858
+ if (!isRecord(action) || action.type !== "chat/turnStarted")
859
+ return refuse("OPERATION_NOT_ALLOWLISTED");
860
+ if (!exactKeys(action, ["type", "turnId", "message"], ["startedAt"]))
861
+ return refuse("INVALID_OPERATION_SHAPE");
862
+ if (typeof action.turnId !== "string" || !UUID.test(action.turnId))
863
+ return refuse("INVALID_OPERATION_SHAPE");
864
+ if (action.startedAt !== undefined && typeof action.startedAt !== "number")
865
+ return refuse("INVALID_OPERATION_SHAPE");
866
+ const message = action.message;
867
+ if (!isRecord(message) || !exactKeys(message, ["text", "origin"]) || typeof message.text !== "string") {
868
+ return refuse("INVALID_OPERATION_SHAPE");
869
+ }
870
+ if (!isRecord(message.origin) || !exactKeys(message.origin, ["kind"]) || message.origin.kind !== "user") {
871
+ return refuse("INVALID_OPERATION_SHAPE");
872
+ }
873
+ if (agentToken === undefined)
874
+ return refuse("TOKEN_EXPIRED_OR_REVOKED");
875
+ return {
876
+ ok: true,
877
+ operation: "turn.send",
878
+ frame: {
879
+ ...head,
880
+ method,
881
+ params: {
882
+ channel,
883
+ clientSeq: params.clientSeq,
884
+ action: {
885
+ type: "chat/turnStarted",
886
+ turnId: action.turnId,
887
+ ...action.startedAt === undefined ? {} : { startedAt: action.startedAt },
888
+ message: { text: message.text, origin: { kind: "user" } }
889
+ }
890
+ }
891
+ },
892
+ meta: publicMeta,
893
+ agentToken,
894
+ sessionKey: key,
895
+ turnId: action.turnId
896
+ };
897
+ }
898
+ function isKnownSession(registry, uri) {
899
+ for (const one of registry.sessions.values())
900
+ if (one.sessionUri === uri)
901
+ return true;
902
+ return false;
903
+ }
904
+
905
+ // src/runtime.ts
906
+ import { fileURLToPath } from "node:url";
907
+ var SUPPORTED_PROTOCOL = "1.1.0";
908
+ var REQUEST_TIMEOUT_MS = 15000;
909
+ var attemptKey = (deliveryId, turnId) => JSON.stringify([deliveryId, turnId]);
910
+ var PipeStateSchema = object({
911
+ sessions: array(tuple([string().min(1), object({ sessionUri: string().min(1), chatUri: string().min(1).optional() }).strict()])),
912
+ dispatched: array(tuple([string().min(1), array(string().min(1))])),
913
+ lastStatus: array(tuple([string().min(1), HostToCloudFrameSchema]))
914
+ }).strict();
915
+
916
+ class WakePipe {
917
+ vault = new ActiveTurnTokenVault2;
918
+ #sessions = new Map;
919
+ #dispatched = new Map;
920
+ #active = new Map;
921
+ #queued = new Map;
922
+ #subscribed = new Set;
923
+ #lastStatus = new Map;
924
+ #writes = Promise.resolve();
925
+ #storeError;
926
+ #started = false;
927
+ #seq = 0;
928
+ #droppedInputRequests = 0;
929
+ peer;
930
+ cloud;
931
+ options;
932
+ constructor(peer, cloud, options) {
933
+ this.peer = peer;
934
+ this.cloud = cloud;
935
+ this.options = options;
936
+ peer.onMessage((message) => {
937
+ this.#fromHost(message).catch((error) => {
938
+ if (error !== this.#storeError)
939
+ this.options.log.error(`ahp-host: local turn handling failed: ${String(error)}`);
940
+ });
941
+ });
942
+ }
943
+ get registry() {
944
+ return { houseId: this.options.houseId, agents: this.options.agents, sessions: this.#sessions };
945
+ }
946
+ async start(clientId) {
947
+ this.#started = false;
948
+ const answer = await this.peer.request("initialize", { channel: "ahp-root://", protocolVersions: [SUPPORTED_PROTOCOL], clientId }, REQUEST_TIMEOUT_MS);
949
+ if (answer?.protocolVersion !== SUPPORTED_PROTOCOL) {
950
+ throw new Error(`ahp-host: the local ahpd answered protocol ${String(answer?.protocolVersion)}, not ${SUPPORTED_PROTOCOL}`);
951
+ }
952
+ const loaded = await this.options.store?.load();
953
+ if (loaded === undefined) {
954
+ this.#started = true;
955
+ return;
956
+ }
957
+ const parsed = PipeStateSchema.safeParse(loaded);
958
+ if (!parsed.success)
959
+ throw new Error("ahp-host: invalid durable state");
960
+ const saved = parsed.data;
961
+ for (const [key, session] of saved.sessions) {
962
+ const chatUri = await this.#resumeSession(session.sessionUri);
963
+ this.#subscribed.delete(session.sessionUri);
964
+ this.peer.notify("unsubscribe", { channel: session.sessionUri });
965
+ if (session.chatUri !== undefined && chatUri !== session.chatUri)
966
+ throw new Error("ahp-host: saved session answered a different chat");
967
+ this.#sessions.set(key, { sessionUri: session.sessionUri, chatUri });
968
+ }
969
+ const interrupted = [];
970
+ const savedSessions = this.#sessions;
971
+ const savedStatuses = new Map(saved.lastStatus);
972
+ for (const [key, attempts] of saved.dispatched) {
973
+ for (const attempt of attempts) {
974
+ let ids;
975
+ try {
976
+ ids = tuple([string().min(1), string().min(1)]).parse(JSON.parse(attempt));
977
+ } catch {
978
+ throw new Error("ahp-host: invalid durable state attempt");
979
+ }
980
+ const [deliveryId, turnId] = ids;
981
+ const last = savedStatuses.get(attempt);
982
+ if (last !== undefined && (last.deliveryId !== deliveryId || last.turnId !== turnId)) {
983
+ throw new Error("ahp-host: invalid durable state attempt status");
984
+ }
985
+ if (last?.event === "turn.finished" || last?.event === "turn.error")
986
+ continue;
987
+ const session = savedSessions.get(key);
988
+ if (session?.chatUri === undefined)
989
+ throw new Error("ahp-host: invalid durable state attempt session");
990
+ interrupted.push({
991
+ event: "turn.error",
992
+ houseId: this.options.houseId,
993
+ deliveryId,
994
+ turnId,
995
+ sessionId: session.sessionUri,
996
+ chatId: session.chatUri,
997
+ turnState: "error",
998
+ statusCode: "HOST_RESTARTED",
999
+ errorCode: "HOST_RESTARTED"
1000
+ });
1001
+ }
1002
+ }
1003
+ for (const [key, ids] of saved.dispatched)
1004
+ this.#dispatched.set(key, new Set(ids));
1005
+ for (const [deliveryId, frame] of saved.lastStatus)
1006
+ this.#lastStatus.set(deliveryId, frame);
1007
+ for (const frame of interrupted)
1008
+ await this.#status(frame);
1009
+ await this.#save();
1010
+ this.#started = true;
1011
+ }
1012
+ #save() {
1013
+ const state = {
1014
+ sessions: [...this.#sessions],
1015
+ dispatched: [...this.#dispatched].map(([key, ids]) => [key, [...ids]]),
1016
+ lastStatus: [...this.#lastStatus]
1017
+ };
1018
+ this.#writes = this.#writes.then(() => this.options.store?.save(state)).catch((error) => {
1019
+ if (this.#storeError === undefined) {
1020
+ this.#storeError = new Error("ahp-host: durable state write failed", { cause: error });
1021
+ for (const turn of this.#active.values()) {
1022
+ this.vault.clearTurn(turn.sessionUri, turn.turnId);
1023
+ this.#stopRenewal(turn);
1024
+ }
1025
+ this.options.log.error(`${this.#storeError.message}: ${String(error)}`);
1026
+ }
1027
+ throw this.#storeError;
1028
+ });
1029
+ return this.#writes;
1030
+ }
1031
+ resolveToolToken(context, nowMs = Date.now()) {
1032
+ try {
1033
+ return { ok: true, ...this.vault.resolveForToolCall(context, nowMs) };
1034
+ } catch {
1035
+ return { ok: false, code: "TOKEN_EXPIRED_OR_REVOKED" };
1036
+ }
1037
+ }
1038
+ async#revoke(id, params) {
1039
+ const ok = typeof params === "object" && params !== null && !Array.isArray(params) && Object.keys(params).sort().join(",") === "agentMemberId,houseId" && params.houseId === this.options.houseId && typeof params.agentMemberId === "string";
1040
+ if (!ok) {
1041
+ if (id !== undefined)
1042
+ this.cloud.answer(id, { ok: false, code: "INVALID_OPERATION_SHAPE" });
1043
+ return;
1044
+ }
1045
+ const member = params.agentMemberId;
1046
+ this.vault.revokeMember(this.options.houseId, member);
1047
+ for (const turn of this.#active.values()) {
1048
+ if (turn.houseId === this.options.houseId && turn.agentMemberId === member) {
1049
+ turn.cancelled = true;
1050
+ this.#stopRenewal(turn);
1051
+ }
1052
+ }
1053
+ const reports = [];
1054
+ for (const [key, queue] of this.#queued) {
1055
+ const kept = queue.filter((one) => one.meta.agentMemberId !== member);
1056
+ const session = this.#sessions.get(key);
1057
+ for (const dropped of queue.filter((one) => one.meta.agentMemberId === member)) {
1058
+ reports.push(this.#status({
1059
+ event: "turn.error",
1060
+ houseId: dropped.meta.houseId,
1061
+ deliveryId: dropped.meta.deliveryId,
1062
+ sessionId: session?.sessionUri ?? "",
1063
+ chatId: session?.chatUri ?? "",
1064
+ turnId: dropped.turnId,
1065
+ turnState: "error",
1066
+ statusCode: "GRANT_REVOKED",
1067
+ errorCode: "TOKEN_EXPIRED_OR_REVOKED"
1068
+ }));
1069
+ }
1070
+ this.#queued.set(key, kept);
1071
+ }
1072
+ await Promise.all(reports);
1073
+ if (id !== undefined)
1074
+ this.cloud.answer(id, { ok: true });
1075
+ }
1076
+ async fromCloud(frame) {
1077
+ const id = frame?.id;
1078
+ if (!this.#started || this.#storeError !== undefined) {
1079
+ if (id !== undefined)
1080
+ this.cloud.answer(id, { ok: false, code: "INVALID_OPERATION_SHAPE" });
1081
+ return;
1082
+ }
1083
+ if (frame?.method === "x-hightea/revoke") {
1084
+ return this.#revoke(id, frame.params).catch(() => {
1085
+ if (id !== undefined)
1086
+ this.cloud.answer(id, { ok: false, code: "INVALID_OPERATION_SHAPE" });
1087
+ });
1088
+ }
1089
+ const decision = checkCloudFrame(frame, this.registry);
1090
+ if (!decision.ok) {
1091
+ if (id !== undefined)
1092
+ this.cloud.answer(id, decision);
1093
+ return;
1094
+ }
1095
+ try {
1096
+ if (decision.operation === "session.create") {
1097
+ const agent = this.options.agents.get(decision.meta.agentMemberId);
1098
+ if (agent === undefined)
1099
+ throw new Error("ahp-host: local agent mapping disappeared");
1100
+ let winnerUri;
1101
+ let sessionUri;
1102
+ try {
1103
+ sessionUri = await this.options.startSession({ owner: this.options.owner, provider: agent.provider, workingDirectory: fileURLToPath(agent.workingDirectory), tools: this.options.tools }, async (uri) => {
1104
+ if (this.options.store?.reserve !== undefined) {
1105
+ const resolved = await this.options.store.reserve(decision.sessionKey, uri);
1106
+ this.#sessions.set(decision.sessionKey, { sessionUri: resolved });
1107
+ if (resolved !== uri) {
1108
+ winnerUri = resolved;
1109
+ throw new Error("ahp-host: durable session mapping already won by an existing URI");
1110
+ }
1111
+ await this.#save();
1112
+ return;
1113
+ }
1114
+ this.#sessions.set(decision.sessionKey, { sessionUri: uri });
1115
+ await this.#save();
1116
+ });
1117
+ } catch (error) {
1118
+ if (winnerUri === undefined)
1119
+ throw error;
1120
+ sessionUri = winnerUri;
1121
+ }
1122
+ if (this.#sessions.get(decision.sessionKey)?.sessionUri !== sessionUri)
1123
+ throw new Error("ahp-host: created session differs from its durable reservation");
1124
+ const chatUri = winnerUri !== undefined ? await this.#resumeSession(sessionUri) : await this.#subscribeSession(sessionUri);
1125
+ this.#sessions.set(decision.sessionKey, { sessionUri, chatUri });
1126
+ await this.#save();
1127
+ await this.#status({
1128
+ event: "session.created",
1129
+ houseId: decision.meta.houseId,
1130
+ deliveryId: decision.meta.deliveryId,
1131
+ ...decision.meta.turnId === undefined ? {} : { turnId: decision.meta.turnId },
1132
+ sessionId: sessionUri,
1133
+ chatId: chatUri,
1134
+ turnState: "created",
1135
+ statusCode: "SESSION_CREATED"
1136
+ });
1137
+ } else if (decision.operation === "session.open") {
1138
+ const sessionUri = decision.frame.params.channel;
1139
+ const chatUri = await this.#resumeSession(sessionUri);
1140
+ this.#sessions.set(decision.sessionKey, { sessionUri, chatUri });
1141
+ } else {
1142
+ await this.#sendTurn(decision.sessionKey, decision.frame, decision.meta, decision.agentToken, decision.turnId);
1143
+ }
1144
+ if (id !== undefined)
1145
+ this.cloud.answer(id, { ok: true });
1146
+ } catch (error) {
1147
+ this.options.log.error(`ahp-host: cloud operation failed: ${String(error)}`);
1148
+ if (id !== undefined)
1149
+ this.cloud.answer(id, { ok: false, code: "INVALID_OPERATION_SHAPE" });
1150
+ }
1151
+ }
1152
+ async#resumeSession(sessionUri) {
1153
+ const resumed = await this.options.startSession({ owner: this.options.owner, resume: sessionUri });
1154
+ if (resumed !== sessionUri)
1155
+ throw new Error(`ahp-host: resumed session ${resumed} differs from ${sessionUri}`);
1156
+ return this.#subscribeSession(sessionUri);
1157
+ }
1158
+ async#subscribeSession(sessionUri) {
1159
+ const answer = await this.peer.request("subscribe", { channel: sessionUri }, REQUEST_TIMEOUT_MS);
1160
+ this.#subscribed.add(sessionUri);
1161
+ const chatUri = answer?.snapshot?.state?.defaultChat;
1162
+ if (typeof chatUri !== "string" || chatUri.length === 0) {
1163
+ throw new Error(`ahp-host: ${sessionUri} answered no defaultChat`);
1164
+ }
1165
+ return chatUri;
1166
+ }
1167
+ async#sendTurn(key, frame, meta, token, turnId) {
1168
+ const mapped = this.#sessions.get(key);
1169
+ if (mapped?.chatUri === undefined || token === undefined || turnId === undefined) {
1170
+ throw new Error("ahp-host: a turn reached dispatch without its mapping, token or turn id");
1171
+ }
1172
+ const seen = this.#dispatched.get(key) ?? new Set;
1173
+ const attempt = attemptKey(meta.deliveryId, turnId);
1174
+ if (seen.has(attempt)) {
1175
+ const last = this.#lastStatus.get(attempt);
1176
+ await this.#writes;
1177
+ if (last !== undefined)
1178
+ this.cloud.status(last);
1179
+ return;
1180
+ }
1181
+ if (this.options.tokenExpiresAt(token) === undefined)
1182
+ throw new Error("ahp-host: an agent token whose expiry cannot be read");
1183
+ const running = this.#active.get(key);
1184
+ if (running !== undefined) {
1185
+ if (running.deliveryId === meta.deliveryId) {
1186
+ this.vault.clearTurn(running.sessionUri, running.turnId);
1187
+ running.cancelled = true;
1188
+ this.#stopRenewal(running);
1189
+ }
1190
+ const queued = this.#queued.get(key) ?? [];
1191
+ for (const old of queued) {
1192
+ if (old.meta.deliveryId === meta.deliveryId && old.turnId !== turnId)
1193
+ seen.add(attemptKey(old.meta.deliveryId, old.turnId));
1194
+ }
1195
+ seen.add(attempt);
1196
+ this.#dispatched.set(key, seen);
1197
+ const queue = queued.filter((one) => one.meta.deliveryId !== meta.deliveryId || one.turnId === turnId);
1198
+ if (!queue.some((one) => one.meta.deliveryId === meta.deliveryId))
1199
+ queue.push({ frame, meta, token, turnId });
1200
+ this.#queued.set(key, queue);
1201
+ await this.#save();
1202
+ return;
1203
+ }
1204
+ seen.add(attempt);
1205
+ this.#dispatched.set(key, seen);
1206
+ await this.#dispatch(key, frame, meta, token, turnId);
1207
+ }
1208
+ async#dispatch(key, frame, meta, token, turnId) {
1209
+ const mapped = this.#sessions.get(key);
1210
+ if (mapped?.chatUri === undefined)
1211
+ throw new Error("ahp-host: dispatch has no mapped chat");
1212
+ const expiresAtMs = this.options.tokenExpiresAt(token);
1213
+ if (expiresAtMs === undefined)
1214
+ throw new Error("ahp-host: an agent token whose expiry cannot be read");
1215
+ this.vault.bindActiveTurn({
1216
+ sessionId: mapped.sessionUri,
1217
+ chatId: mapped.chatUri,
1218
+ turnId,
1219
+ deliveryId: meta.deliveryId,
1220
+ threadRef: meta.threadRef,
1221
+ ...meta.afterMessageId === undefined ? {} : { afterMessageId: meta.afterMessageId },
1222
+ houseId: meta.houseId,
1223
+ agentMemberId: meta.agentMemberId,
1224
+ token,
1225
+ expiresAtMs
1226
+ });
1227
+ const active = {
1228
+ key,
1229
+ deliveryId: meta.deliveryId,
1230
+ houseId: meta.houseId,
1231
+ agentMemberId: meta.agentMemberId,
1232
+ sessionUri: mapped.sessionUri,
1233
+ chatUri: mapped.chatUri,
1234
+ turnId,
1235
+ cancelled: false,
1236
+ stopReason: undefined,
1237
+ finishing: false,
1238
+ renewalTimer: undefined
1239
+ };
1240
+ this.#active.set(key, active);
1241
+ await this.#save();
1242
+ if (active.cancelled) {
1243
+ this.#active.delete(key);
1244
+ await this.#status({
1245
+ event: "turn.error",
1246
+ houseId: meta.houseId,
1247
+ deliveryId: meta.deliveryId,
1248
+ sessionId: mapped.sessionUri,
1249
+ chatId: mapped.chatUri,
1250
+ turnId,
1251
+ turnState: "error",
1252
+ statusCode: "QUEUED_WAKE_NOT_RUN",
1253
+ errorCode: "TOKEN_EXPIRED_OR_REVOKED"
1254
+ });
1255
+ await this.#next(active);
1256
+ return;
1257
+ }
1258
+ this.#scheduleRenewal(active, expiresAtMs);
1259
+ if (!this.#subscribed.has(mapped.chatUri)) {
1260
+ this.#subscribed.add(mapped.chatUri);
1261
+ this.peer.request("subscribe", { channel: mapped.chatUri }, REQUEST_TIMEOUT_MS);
1262
+ }
1263
+ this.peer.notify("dispatchAction", { ...frame.params, clientSeq: ++this.#seq });
1264
+ }
1265
+ #stopRenewal(turn) {
1266
+ clearTimeout(turn.renewalTimer);
1267
+ turn.renewalTimer = undefined;
1268
+ }
1269
+ #scheduleRenewal(turn, expiresAtMs) {
1270
+ const remaining = expiresAtMs - Date.now();
1271
+ if (!Number.isFinite(remaining) || remaining <= 0)
1272
+ return;
1273
+ turn.renewalTimer = setTimeout(() => void this.#renewToken(turn, expiresAtMs), Math.max(1, remaining - Math.min(60000, remaining / 2)));
1274
+ turn.renewalTimer.unref?.();
1275
+ }
1276
+ async#renewToken(turn, previousExpiry) {
1277
+ turn.renewalTimer = undefined;
1278
+ const context = { sessionId: turn.sessionUri, chatId: turn.chatUri, turnId: turn.turnId, deliveryId: turn.deliveryId, houseId: turn.houseId };
1279
+ if (this.#active.get(turn.key) !== turn || !this.resolveToolToken(context).ok)
1280
+ return;
1281
+ try {
1282
+ const result = await this.cloud.renewToken({ houseId: turn.houseId, deliveryId: turn.deliveryId, chatId: turn.chatUri, turnId: turn.turnId });
1283
+ if (this.#active.get(turn.key) !== turn)
1284
+ return this.#renewalError(turn, "TOKEN_RENEWAL_STALE");
1285
+ if (result === null || typeof result !== "object" || Array.isArray(result) || Object.keys(result).sort().join(",") !== "agentToken,deliveryId,turnId")
1286
+ return this.#renewalError(turn, "TOKEN_RENEWAL_INVALID");
1287
+ const answer = result;
1288
+ if (answer.deliveryId !== turn.deliveryId || answer.turnId !== turn.turnId || typeof answer.agentToken !== "string" || answer.agentToken === "") {
1289
+ return this.#renewalError(turn, "TOKEN_RENEWAL_INVALID");
1290
+ }
1291
+ const expiresAtMs = this.options.tokenExpiresAt(answer.agentToken);
1292
+ if (expiresAtMs === undefined || !Number.isFinite(expiresAtMs) || expiresAtMs <= previousExpiry || expiresAtMs <= Date.now()) {
1293
+ return this.#renewalError(turn, "TOKEN_RENEWAL_INVALID");
1294
+ }
1295
+ if (!this.vault.renewActiveTurn(context, answer.agentToken, expiresAtMs))
1296
+ return this.#renewalError(turn, "TOKEN_RENEWAL_STALE");
1297
+ this.#scheduleRenewal(turn, expiresAtMs);
1298
+ } catch {
1299
+ this.#renewalError(turn, "TOKEN_RENEWAL_FAILED");
1300
+ }
1301
+ }
1302
+ #renewalError(turn, code) {
1303
+ this.options.log.error(`hightea-pipe: ${code} ${JSON.stringify({ houseId: turn.houseId, deliveryId: turn.deliveryId, turnId: turn.turnId })}`);
1304
+ }
1305
+ async#fromHost(message) {
1306
+ const params = message?.params;
1307
+ const action = params?.action;
1308
+ if (action === undefined || typeof params?.channel !== "string")
1309
+ return;
1310
+ if (action.type === "session/inputNeededSet") {
1311
+ const request = action.request;
1312
+ const isApproval = request?.kind === "toolConfirmation" && request.toolCall?.status === "pending-confirmation";
1313
+ const isInput = request?.kind === "chatInput";
1314
+ if (!isApproval && !isInput)
1315
+ return;
1316
+ const requestId = typeof request.request?.id === "string" && request.request.id !== "" ? request.request.id : typeof request.id === "string" && request.id !== "" ? request.id : "unknown";
1317
+ if (typeof request.turnId !== "string" || request.turnId === "") {
1318
+ this.#droppedInputRequests++;
1319
+ const turn = [...this.#active.values()].find((one) => one.sessionUri === params.channel && one.chatUri === request.chat && !one.finishing && one.stopReason === undefined);
1320
+ this.options.log.error(`hightea-pipe: INPUT_REQUEST_UNATTRIBUTED ${JSON.stringify({
1321
+ sessionId: params.channel,
1322
+ chatId: typeof request.chat === "string" ? request.chat : "",
1323
+ requestId,
1324
+ droppedCount: this.#droppedInputRequests,
1325
+ ...turn === undefined ? {} : { houseId: turn.houseId, deliveryId: turn.deliveryId, turnId: turn.turnId }
1326
+ })}`);
1327
+ if (turn === undefined)
1328
+ return;
1329
+ turn.stopReason = "INVALID_OPERATION_SHAPE";
1330
+ turn.stopStatusCode = "INPUT_REQUEST_UNATTRIBUTED";
1331
+ turn.stopDetail = `INPUT_REQUEST_UNATTRIBUTED:${requestId}`.slice(0, 256);
1332
+ this.vault.clearTurn(turn.sessionUri, turn.turnId);
1333
+ this.#stopRenewal(turn);
1334
+ this.peer.notify("dispatchAction", {
1335
+ channel: turn.chatUri,
1336
+ clientSeq: ++this.#seq,
1337
+ action: { type: "chat/turnCancelled", turnId: turn.turnId }
1338
+ });
1339
+ return;
1340
+ }
1341
+ const turn = [...this.#active.values()].find((one) => one.sessionUri === params.channel && one.chatUri === request.chat && one.turnId === request.turnId);
1342
+ if (turn === undefined) {
1343
+ this.#droppedInputRequests++;
1344
+ this.options.log.error(`hightea-pipe: INPUT_REQUEST_UNMATCHED_TURN ${JSON.stringify({
1345
+ sessionId: params.channel,
1346
+ chatId: typeof request.chat === "string" ? request.chat : "",
1347
+ turnId: request.turnId,
1348
+ kind: request.kind,
1349
+ requestId,
1350
+ droppedCount: this.#droppedInputRequests
1351
+ })}`);
1352
+ return;
1353
+ }
1354
+ if (turn.finishing || turn.stopReason !== undefined)
1355
+ return;
1356
+ turn.stopReason = isInput ? "INPUT_REQUIRED" : "APPROVAL_REQUIRED";
1357
+ turn.stopStatusCode = turn.stopReason;
1358
+ this.vault.clearTurn(turn.sessionUri, turn.turnId);
1359
+ this.#stopRenewal(turn);
1360
+ this.peer.notify("dispatchAction", {
1361
+ channel: turn.chatUri,
1362
+ clientSeq: ++this.#seq,
1363
+ action: { type: "chat/turnCancelled", turnId: turn.turnId }
1364
+ });
1365
+ return;
1366
+ }
1367
+ const turn = [...this.#active.values()].find((one) => one.chatUri === params.channel && one.turnId === action.turnId);
1368
+ if (turn === undefined || turn.finishing)
1369
+ return;
1370
+ const base = {
1371
+ houseId: turn.houseId,
1372
+ deliveryId: turn.deliveryId,
1373
+ sessionId: turn.sessionUri,
1374
+ chatId: turn.chatUri,
1375
+ turnId: turn.turnId
1376
+ };
1377
+ if (action.type === "chat/turnStarted") {
1378
+ if (turn.stopReason !== undefined)
1379
+ return;
1380
+ await this.#status({ event: "turn.started", ...base, turnState: "running", statusCode: "TURN_RUNNING" });
1381
+ } else if (action.type === "chat/turnComplete" || action.type === "chat/turnCancelled" || action.type === "chat/error") {
1382
+ turn.finishing = true;
1383
+ const finished = action.type === "chat/turnComplete" && turn.stopReason === undefined;
1384
+ const errorCode = turn.stopReason ?? "INVALID_OPERATION_SHAPE";
1385
+ const statusCode = turn.stopStatusCode ?? turn.stopReason ?? "TURN_ENDED";
1386
+ this.#stopRenewal(turn);
1387
+ this.vault.clearTurn(turn.sessionUri, turn.turnId);
1388
+ await this.#status(finished ? { event: "turn.finished", ...base, turnState: "finished", statusCode: "TURN_FINISHED" } : {
1389
+ event: "turn.error",
1390
+ ...base,
1391
+ turnState: "error",
1392
+ statusCode,
1393
+ errorCode,
1394
+ ...turn.stopDetail === undefined ? {} : { errorDetail: turn.stopDetail }
1395
+ });
1396
+ this.#active.delete(turn.key);
1397
+ await this.#next(turn);
1398
+ }
1399
+ }
1400
+ async#next(done) {
1401
+ if (this.#active.has(done.key))
1402
+ return;
1403
+ const queue = this.#queued.get(done.key) ?? [];
1404
+ const next = queue.shift();
1405
+ if (next === undefined) {
1406
+ this.#subscribed.delete(done.chatUri);
1407
+ this.#subscribed.delete(done.sessionUri);
1408
+ this.peer.notify("unsubscribe", { channel: done.chatUri });
1409
+ this.peer.notify("unsubscribe", { channel: done.sessionUri });
1410
+ return;
1411
+ }
1412
+ const expiresAtMs = this.options.tokenExpiresAt(next.token);
1413
+ if (expiresAtMs !== undefined && expiresAtMs > Date.now()) {
1414
+ try {
1415
+ await this.#dispatch(done.key, next.frame, next.meta, next.token, next.turnId);
1416
+ return;
1417
+ } catch (error) {
1418
+ if (this.#storeError !== undefined)
1419
+ throw error;
1420
+ }
1421
+ }
1422
+ const session = this.#sessions.get(done.key);
1423
+ await this.#status({
1424
+ event: "turn.error",
1425
+ houseId: next.meta.houseId,
1426
+ deliveryId: next.meta.deliveryId,
1427
+ sessionId: session?.sessionUri ?? done.sessionUri,
1428
+ chatId: session?.chatUri ?? done.chatUri,
1429
+ turnId: next.turnId,
1430
+ turnState: "error",
1431
+ statusCode: "QUEUED_WAKE_NOT_RUN",
1432
+ errorCode: "TOKEN_EXPIRED_OR_REVOKED"
1433
+ });
1434
+ await this.#next(done);
1435
+ }
1436
+ #status(frame) {
1437
+ const checked = parseHostToCloudFrame(frame);
1438
+ this.#lastStatus.set(checked.turnId === undefined ? checked.deliveryId : attemptKey(checked.deliveryId, checked.turnId), checked);
1439
+ if (this.options.store === undefined) {
1440
+ this.cloud.status(checked);
1441
+ return Promise.resolve();
1442
+ }
1443
+ return this.#save().then(() => {
1444
+ this.cloud.status(checked);
1445
+ });
1446
+ }
1447
+ }
1448
+
1449
+ // src/records-store.ts
1450
+ var tupleSchema = tuple([string().min(1), string().min(1), string().min(1)]);
1451
+ var mappingSchema = object({
1452
+ id: string(),
1453
+ version: literal(1),
1454
+ tuple: tupleSchema,
1455
+ owner: string().min(1),
1456
+ sessionUri: string().regex(SESSION_URI)
1457
+ }).strict();
1458
+ var mappingId = (key) => `session-${createHash("sha256").update(key).digest("hex").slice(0, 32)}`;
1459
+ function recordsPipeStore(records, owner, sessionOwner) {
1460
+ const known = new Map;
1461
+ const readMapping = (raw) => {
1462
+ const parsed = mappingSchema.safeParse(raw);
1463
+ if (!parsed.success)
1464
+ throw new Error("ahp-host: invalid durable session mapping");
1465
+ const record = parsed.data;
1466
+ const key = JSON.stringify(record.tuple);
1467
+ if (record.id !== mappingId(key) || record.owner !== owner)
1468
+ throw new Error("ahp-host: durable session mapping has a different key or owner");
1469
+ return [key, { sessionUri: record.sessionUri }];
1470
+ };
1471
+ const reserve = async (key, sessionUri) => {
1472
+ const tuple2 = tupleSchema.parse(JSON.parse(key));
1473
+ if (JSON.stringify(tuple2) !== key || !SESSION_URI.test(sessionUri))
1474
+ throw new Error("ahp-host: invalid session mapping to publish");
1475
+ const existing = known.get(key);
1476
+ if (existing !== undefined)
1477
+ return existing.sessionUri;
1478
+ const id = mappingId(key);
1479
+ let winner = sessionUri;
1480
+ try {
1481
+ await records.put({ id, version: 1, tuple: tuple2, owner, sessionUri }, { createOnly: true });
1482
+ } catch (error) {
1483
+ if (error?.code !== -32010)
1484
+ throw error;
1485
+ const actual = await records.get(id);
1486
+ if (actual === undefined)
1487
+ throw error;
1488
+ const [actualKey, found] = readMapping(actual);
1489
+ if (actualKey !== key)
1490
+ throw new Error("ahp-host: conflicting durable session mapping", { cause: error });
1491
+ if (found.sessionUri !== sessionUri && await sessionOwner(found.sessionUri) !== owner) {
1492
+ throw new Error("ahp-host: durable session belongs to an unknown or different owner", { cause: error });
1493
+ }
1494
+ winner = found.sessionUri;
1495
+ }
1496
+ known.set(key, { sessionUri: winner });
1497
+ return winner;
1498
+ };
1499
+ const publish = async (key, session) => {
1500
+ const winner = await reserve(key, session.sessionUri);
1501
+ if (winner !== session.sessionUri)
1502
+ throw new Error("ahp-host: conflicting durable session mapping");
1503
+ };
1504
+ const saveAttempts = (state) => records.put({
1505
+ id: "state",
1506
+ version: 2,
1507
+ state: { dispatched: state.dispatched, lastStatus: state.lastStatus }
1508
+ });
1509
+ return {
1510
+ reserve,
1511
+ load: async () => {
1512
+ const record = await records.get("state");
1513
+ let state = { sessions: [], dispatched: [], lastStatus: [] };
1514
+ if (record !== undefined) {
1515
+ if (record.id !== "state" || record.version !== 1 && record.version !== 2 || !("state" in record)) {
1516
+ throw new Error("ahp-host: invalid durable state record");
1517
+ }
1518
+ const raw = record.version === 1 ? record.state : typeof record.state === "object" && record.state !== null ? { sessions: [], ...record.state } : record.state;
1519
+ const parsed = PipeStateSchema.safeParse(raw);
1520
+ if (!parsed.success || record.version === 2 && parsed.data.sessions.length !== 0)
1521
+ throw new Error("ahp-host: invalid durable state");
1522
+ state = { ...parsed.data, sessions: parsed.data.sessions.map(([key, session]) => [key, {
1523
+ sessionUri: session.sessionUri,
1524
+ ...session.chatUri === undefined ? {} : { chatUri: session.chatUri }
1525
+ }]) };
1526
+ }
1527
+ const mappings = new Map;
1528
+ for (const raw of await records.list()) {
1529
+ if (raw.id === "state")
1530
+ continue;
1531
+ const [key, session] = readMapping(raw);
1532
+ if (await sessionOwner(session.sessionUri) !== owner)
1533
+ throw new Error("ahp-host: durable session belongs to an unknown or different owner");
1534
+ mappings.set(key, session);
1535
+ }
1536
+ known.clear();
1537
+ for (const [key, session] of mappings)
1538
+ known.set(key, session);
1539
+ for (const [, session] of state.sessions) {
1540
+ if (await sessionOwner(session.sessionUri) !== owner)
1541
+ throw new Error("ahp-host: legacy session belongs to an unknown or different owner");
1542
+ }
1543
+ for (const [key, session] of state.sessions) {
1544
+ await publish(key, session);
1545
+ mappings.set(key, session);
1546
+ }
1547
+ if (record?.version === 1)
1548
+ await saveAttempts(state);
1549
+ return { sessions: [...mappings], dispatched: state.dispatched, lastStatus: state.lastStatus };
1550
+ },
1551
+ save: async (state) => {
1552
+ for (const [key, session] of state.sessions)
1553
+ await publish(key, session);
1554
+ await saveAttempts(state);
1555
+ }
1556
+ };
1557
+ }
1558
+
1559
+ // src/link.ts
1560
+ import { randomUUID } from "node:crypto";
1561
+ var REQUEST_TIMEOUT_MS2 = 15000;
1562
+ function createCloudLink(options) {
1563
+ const { log, receive } = options;
1564
+ let stopped = false;
1565
+ let wait = 1000;
1566
+ let retry;
1567
+ let current;
1568
+ const pending = new Map;
1569
+ const fail = (code, report = true) => {
1570
+ if (report)
1571
+ log.error(`hightea-pipe: ${code}`);
1572
+ for (const entry of pending.values()) {
1573
+ clearTimeout(entry.timer);
1574
+ entry.reject(new Error(code));
1575
+ }
1576
+ pending.clear();
1577
+ };
1578
+ const sendThrough = (connection, value) => {
1579
+ if (!stopped && connection !== undefined && connection === current && connection.live && connection.socket?.readyState === 1) {
1580
+ try {
1581
+ connection.socket.send(JSON.stringify(value));
1582
+ return true;
1583
+ } catch {}
1584
+ }
1585
+ log.error("hightea-pipe: CONTROL_SOCKET_UNAVAILABLE");
1586
+ return false;
1587
+ };
1588
+ const send = (value) => sendThrough(current, value);
1589
+ const closeSocket = (socket) => {
1590
+ if (socket === undefined || socket.readyState >= 2)
1591
+ return;
1592
+ try {
1593
+ socket.close();
1594
+ } catch {
1595
+ log.error("hightea-pipe: CONTROL_SOCKET_CLOSE_FAILED");
1596
+ }
1597
+ };
1598
+ const close = () => {
1599
+ if (stopped)
1600
+ return;
1601
+ stopped = true;
1602
+ if (retry !== undefined)
1603
+ clearTimeout(retry);
1604
+ retry = undefined;
1605
+ if (current !== undefined)
1606
+ current.live = false;
1607
+ fail("CONTROL_SOCKET_CLOSED", false);
1608
+ closeSocket(current?.socket);
1609
+ };
1610
+ const message = (event) => {
1611
+ let frame;
1612
+ try {
1613
+ frame = JSON.parse(String(event.data));
1614
+ } catch {
1615
+ log.error("hightea-pipe: CONTROL_FRAME_INVALID");
1616
+ return;
1617
+ }
1618
+ if (frame !== null && typeof frame === "object" && !Array.isArray(frame)) {
1619
+ const response = frame;
1620
+ if (response.method === undefined && (("result" in response) || ("error" in response))) {
1621
+ const entry = typeof response.id === "string" ? pending.get(response.id) : undefined;
1622
+ if (entry === undefined) {
1623
+ log.error("hightea-pipe: CONTROL_RESPONSE_UNKNOWN");
1624
+ return;
1625
+ }
1626
+ pending.delete(response.id);
1627
+ clearTimeout(entry.timer);
1628
+ if (response.jsonrpc === "2.0" && "result" in response && !("error" in response)) {
1629
+ entry.resolve(response.result);
1630
+ } else {
1631
+ log.error("hightea-pipe: CONTROL_REQUEST_REFUSED");
1632
+ entry.reject(new Error("CONTROL_REQUEST_REFUSED"));
1633
+ }
1634
+ return;
1635
+ }
1636
+ }
1637
+ receive(frame);
1638
+ };
1639
+ const connect = () => {
1640
+ if (stopped)
1641
+ return;
1642
+ const connection = { live: true, opened: false };
1643
+ current = connection;
1644
+ const schedule = () => {
1645
+ if (stopped || retry !== undefined)
1646
+ return;
1647
+ const delay = wait;
1648
+ wait = Math.min(wait * 2, 60000);
1649
+ retry = setTimeout(() => {
1650
+ retry = undefined;
1651
+ connect();
1652
+ }, delay);
1653
+ };
1654
+ const lost = (code) => {
1655
+ if (stopped || current !== connection || !connection.live)
1656
+ return;
1657
+ connection.live = false;
1658
+ fail(code);
1659
+ closeSocket(connection.socket);
1660
+ schedule();
1661
+ };
1662
+ const refused = (code) => {
1663
+ if (stopped || current !== connection)
1664
+ return;
1665
+ log.error(`hightea-pipe: CONTROL_SOCKET_REFUSED:${code}`);
1666
+ close();
1667
+ };
1668
+ try {
1669
+ const socket = options.dial((status) => {
1670
+ if (status === 401 || status === 403)
1671
+ refused(status);
1672
+ else
1673
+ lost("CONTROL_SOCKET_ERROR");
1674
+ });
1675
+ connection.socket = socket;
1676
+ socket.addEventListener("message", (event) => {
1677
+ if (!stopped && current === connection && connection.live)
1678
+ message(event);
1679
+ });
1680
+ socket.addEventListener("error", () => lost("CONTROL_SOCKET_ERROR"));
1681
+ socket.addEventListener("close", (event) => {
1682
+ if (event.code === 4003)
1683
+ refused(4003);
1684
+ else
1685
+ lost("CONTROL_SOCKET_CLOSED");
1686
+ });
1687
+ const opened = () => {
1688
+ if (stopped || current !== connection || !connection.live || connection.opened)
1689
+ return;
1690
+ connection.opened = true;
1691
+ wait = 1000;
1692
+ options.opened?.({ send: (value) => sendThrough(connection, value) });
1693
+ };
1694
+ socket.addEventListener("open", opened);
1695
+ if (stopped || !connection.live)
1696
+ closeSocket(socket);
1697
+ else if (socket.readyState === 1)
1698
+ opened();
1699
+ } catch {
1700
+ lost("CONTROL_SOCKET_ERROR");
1701
+ }
1702
+ };
1703
+ queueMicrotask(connect);
1704
+ return {
1705
+ send,
1706
+ close,
1707
+ answer: (id, outcome) => send(outcome.ok ? { jsonrpc: "2.0", id, result: null } : { jsonrpc: "2.0", id, error: { code: -32000, message: outcome.code } }),
1708
+ status: (frame) => send({ jsonrpc: "2.0", method: "x-hightea/status", params: frame }),
1709
+ renewToken: (params) => new Promise((resolve, reject) => {
1710
+ const id = `renew:${randomUUID()}`;
1711
+ const timer = setTimeout(() => {
1712
+ pending.delete(id);
1713
+ log.error("hightea-pipe: CONTROL_REQUEST_TIMEOUT");
1714
+ reject(new Error("CONTROL_REQUEST_TIMEOUT"));
1715
+ }, REQUEST_TIMEOUT_MS2);
1716
+ pending.set(id, { resolve, reject, timer });
1717
+ if (!send({ jsonrpc: "2.0", id, method: "x-hightea/renewToken", params })) {
1718
+ pending.delete(id);
1719
+ clearTimeout(timer);
1720
+ reject(new Error("CONTROL_SOCKET_UNAVAILABLE"));
1721
+ }
1722
+ })
1723
+ };
1724
+ }
1725
+
1726
+ // src/plugin.ts
1727
+ var name = "hightea-pipe";
1728
+ var owner = `plugin:${name}`;
1729
+ var hostTools = ["hightea_read_thread", "hightea_post", "hightea_page_read", "hightea_page_write"];
1730
+ function jwtExpiresAt(token) {
1731
+ const parts = token.split(".");
1732
+ if (parts.length !== 3)
1733
+ return;
1734
+ try {
1735
+ const claims = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
1736
+ const exp = claims?.exp;
1737
+ return typeof exp === "number" && Number.isFinite(exp) && exp > 0 ? exp * 1000 : undefined;
1738
+ } catch {
1739
+ return;
1740
+ }
1741
+ }
1742
+ function shareListener(peer) {
1743
+ const listeners = [];
1744
+ peer.onMessage((message) => {
1745
+ for (const listener of listeners)
1746
+ listener(message);
1747
+ });
1748
+ return {
1749
+ request: (method, params, timeoutMs) => peer.request(method, params, timeoutMs),
1750
+ notify: (method, params) => peer.notify(method, params),
1751
+ onMessage: (listener) => void listeners.push(listener),
1752
+ close: () => peer.close()
1753
+ };
1754
+ }
1755
+ function registerTools(host, mcpUrl, pipe) {
1756
+ const call = async (at, tool, args) => {
1757
+ const activePipe = pipe();
1758
+ const context = { sessionId: at.session, chatId: at.chat, turnId: at.turn() ?? "" };
1759
+ const resolved = activePipe?.resolveToolToken(context);
1760
+ if (resolved === undefined || !resolved.ok)
1761
+ throw new Error("TOKEN_EXPIRED_OR_REVOKED");
1762
+ const headers = { authorization: `Bearer ${resolved.token}`, "content-type": "application/json" };
1763
+ if (tool === "post_message")
1764
+ headers["idempotency-key"] = resolved.deliveryId;
1765
+ if (tool === "read_thread" || tool === "post_message") {
1766
+ const [roomId, messageId, extra] = resolved.threadRef.split("/");
1767
+ if (!roomId || !messageId || extra !== undefined)
1768
+ throw new Error("Invalid wake thread reference");
1769
+ args = tool === "read_thread" ? { roomId, messageId, ...resolved.afterMessageId === undefined ? {} : { after: resolved.afterMessageId } } : { ...args, roomId, deliveryId: resolved.deliveryId };
1770
+ }
1771
+ const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } });
1772
+ let answer;
1773
+ for (let attempt = 0;answer === undefined; attempt++) {
1774
+ try {
1775
+ answer = await (await fetch(mcpUrl, { method: "POST", headers, body })).json();
1776
+ } catch (error) {
1777
+ if (attempt >= 1)
1778
+ throw new Error(`HOUSE_UNREACHABLE: ${String(error)}`);
1779
+ }
1780
+ }
1781
+ if (answer.error !== undefined)
1782
+ throw new Error(answer.error.message);
1783
+ if (tool === "read_thread") {
1784
+ const value = answer.result?.structuredContent;
1785
+ if (value === null || typeof value !== "object" || !("root" in value) || !("replies" in value) || value.root === null || typeof value.root !== "object" || !("id" in value.root) || typeof value.root.id !== "string" || value.root.id === "" || !Array.isArray(value.replies) || value.replies.some((reply) => reply === null || typeof reply !== "object" || typeof reply.id !== "string" || reply.id === "")) {
1786
+ throw new Error("read_thread returned no valid root/replies paging result");
1787
+ }
1788
+ const current = activePipe?.resolveToolToken(context);
1789
+ if (current === undefined || !current.ok)
1790
+ throw new Error("TOKEN_EXPIRED_OR_REVOKED");
1791
+ const last = value.replies.at(-1);
1792
+ const position = last?.id ?? current.afterMessageId ?? value.root.id;
1793
+ if (current.afterMessageId === resolved.afterMessageId)
1794
+ activePipe.vault.recordThreadRead(context, position);
1795
+ }
1796
+ return (answer.result?.content ?? []).map((part) => part.text).join(`
1797
+ `);
1798
+ };
1799
+ host.registerTool({
1800
+ definition: {
1801
+ name: "hightea_read_thread",
1802
+ description: "You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",
1803
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
1804
+ },
1805
+ confirm: false,
1806
+ optIn: true,
1807
+ run: (_input, at) => call(at, "read_thread", {})
1808
+ });
1809
+ host.registerTool({
1810
+ definition: {
1811
+ name: "hightea_post",
1812
+ description: "Post your reply to the Hightea room thread you were woken in. Call it once with your answer.",
1813
+ inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false }
1814
+ },
1815
+ confirm: false,
1816
+ optIn: true,
1817
+ run: (input, at) => call(at, "post_message", { text: String(input.text ?? "") })
1818
+ });
1819
+ host.registerTool({
1820
+ definition: {
1821
+ name: "hightea_page_read",
1822
+ description: "Read a Hightea page: its current version and content.",
1823
+ inputSchema: { type: "object", properties: { pageId: { type: "string" } }, required: ["pageId"], additionalProperties: false }
1824
+ },
1825
+ confirm: false,
1826
+ optIn: true,
1827
+ run: (input, at) => call(at, "page_read", { pageId: String(input.pageId ?? "") })
1828
+ });
1829
+ host.registerTool({
1830
+ definition: {
1831
+ name: "hightea_page_write",
1832
+ description: "Replace a Hightea page's content. Pass the version you read as ifVersion; a stale write is refused.",
1833
+ inputSchema: {
1834
+ type: "object",
1835
+ properties: { pageId: { type: "string" }, ifVersion: { type: "number" }, content: { type: "string" } },
1836
+ required: ["pageId", "ifVersion", "content"],
1837
+ additionalProperties: false
1838
+ }
1839
+ },
1840
+ confirm: false,
1841
+ optIn: true,
1842
+ run: (input, at) => {
1843
+ const args = input;
1844
+ return call(at, "page_write", { pageId: String(args.pageId ?? ""), ifVersion: Number(args.ifVersion), content: String(args.content ?? "") });
1845
+ }
1846
+ });
1847
+ }
1848
+ function applyWith(host, options, seams) {
1849
+ let running;
1850
+ let stopped = false;
1851
+ let startup;
1852
+ let cloud;
1853
+ const stop = () => {
1854
+ stopped = true;
1855
+ if (startup !== undefined)
1856
+ clearTimeout(startup);
1857
+ startup = undefined;
1858
+ cloud?.close();
1859
+ };
1860
+ host.registerClose(stop);
1861
+ if (options.mcpUrl !== undefined)
1862
+ registerTools(host, options.mcpUrl, () => running);
1863
+ host.on("listening", () => {
1864
+ if (stopped || startup !== undefined || cloud !== undefined)
1865
+ return;
1866
+ startup = setTimeout(() => {
1867
+ startup = undefined;
1868
+ if (stopped)
1869
+ return;
1870
+ let initialized;
1871
+ const link = createCloudLink({
1872
+ dial: (status) => {
1873
+ const socket = new WebSocket(options.cloudUrl, { headers: options.headers, handshakeTimeout: 15000, followRedirects: false });
1874
+ socket.on("unexpected-response", (_request, response) => {
1875
+ status(response.statusCode ?? 0);
1876
+ response.resume();
1877
+ socket.terminate();
1878
+ });
1879
+ return socket;
1880
+ },
1881
+ receive: (frame) => {
1882
+ pipe.fromCloud(seams.cloudFrame === undefined ? frame : seams.cloudFrame(frame));
1883
+ },
1884
+ log: host.log,
1885
+ opened: (connection) => {
1886
+ initialized ??= pipe.start(name);
1887
+ initialized.then(() => {
1888
+ if (!stopped)
1889
+ connection.send({ jsonrpc: "2.0", method: "x-hightea/hello", params: { plugin: name, runtime: process.versions.bun === undefined ? "node" : "bun" } });
1890
+ }, (error) => {
1891
+ if (stopped)
1892
+ return;
1893
+ host.log.error(`${name}: could not start on the local ahpd: ${String(error)}`);
1894
+ connection.send({ jsonrpc: "2.0", method: "x-hightea/fatal", params: { code: "HOST_START_FAILED" } });
1895
+ stop();
1896
+ });
1897
+ }
1898
+ });
1899
+ cloud = link;
1900
+ const shared = shareListener(host.connect());
1901
+ const pipe = new WakePipe(seams.peer === undefined ? shared : seams.peer(shared), link, {
1902
+ houseId: options.houseId,
1903
+ agents: new Map(options.agents),
1904
+ tokenExpiresAt: seams.tokenExpiresAt ?? jwtExpiresAt,
1905
+ owner,
1906
+ tools: options.mcpUrl === undefined ? [] : hostTools,
1907
+ startSession: (wanted, named) => host.startSession(wanted, named),
1908
+ log: host.log,
1909
+ store: recordsPipeStore(host.records("hightea"), owner, (uri) => host.sessionOwner(uri))
1910
+ });
1911
+ running = pipe;
1912
+ }, 100);
1913
+ });
1914
+ }
1915
+ function apply(host, options) {
1916
+ applyWith(host, options, {});
1917
+ }
1918
+ export {
1919
+ WakePipe,
1920
+ apply,
1921
+ applyWith,
1922
+ jwtExpiresAt,
1923
+ name,
1924
+ recordsPipeStore,
1925
+ registerTools,
1926
+ shareListener
1927
+ };