@hallohuman/hightea 0.1.15 → 0.1.30

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.
@@ -9789,7 +9789,13 @@ var SourceObservationSchema = object({
9789
9789
  }).strict();
9790
9790
  var ReadArgs = object({ address: Address }).strict();
9791
9791
  var ListArgs = object({ page: string2().min(1).max(4096).optional(), limit: number2().int().min(1).max(SOURCE_LIST_LIMIT_MAX) }).strict();
9792
- var AssignArgs = object({ address: Address, ownerMemberId: Id, expectedOwner: Id.nullable(), intentId: Id }).strict();
9792
+ var AssignArgs = object({
9793
+ address: Address,
9794
+ ownerMemberId: Id,
9795
+ expectedOwner: Id.nullable(),
9796
+ intentId: Id,
9797
+ ifRevision: string2().min(1).max(256).optional()
9798
+ }).strict();
9793
9799
  var WatchArgs = object({ on: boolean2() }).strict();
9794
9800
  var Caller = object({ memberId: Id }).strict();
9795
9801
  var request = (op, args) => object({ ...Binding, caller: Caller, op: literal(op), args }).strict();
@@ -9809,7 +9815,12 @@ var SourceListPageSchema = object({
9809
9815
  progressAsOf: string2().min(1).max(64).optional(),
9810
9816
  progressStale: object({ since: string2().min(1).max(64), reason: string2().min(1).max(4096) }).strict().optional()
9811
9817
  }).strict().refine((page) => page.rows.length > 0 || page.complete && page.next === null, { message: "a page carries at least one item" }).refine((page) => page.complete === (page.next === null), { message: "a page is complete exactly when it has no next token" });
9812
- var AssignReply = object({ intentId: Id, result: unknown(), observation: SourceObservationSchema }).strict();
9818
+ var AssignReply = object({
9819
+ intentId: Id,
9820
+ result: unknown(),
9821
+ observation: SourceObservationSchema,
9822
+ revision: Id.nullable().optional()
9823
+ }).strict();
9813
9824
  var BODIES = {
9814
9825
  read: object({ observation: SourceObservationSchema }).strict(),
9815
9826
  list: SourceListPageSchema,
@@ -9834,6 +9845,47 @@ var SourcePushSchema = object({ ...Binding, position: SourcePositionSchema, obse
9834
9845
  return observations.every((one, index) => one.position.epoch === position.epoch && (index === 0 || BigInt(one.position.ordinal) === BigInt(observations[index - 1].position.ordinal) + 1n));
9835
9846
  }, { message: "a push is one epoch of consecutive ordinals, numbered by its last" });
9836
9847
  var SourceAckSchema = object({ applied: SourcePositionSchema.nullable(), seq: number2().int().min(0), relist: boolean2() }).strict();
9848
+ // ../ahp/src/records.ts
9849
+ var RECORDS_SCHEME = "x-hh-records";
9850
+ var RECORDS_CHANGED = `${RECORDS_SCHEME}/changed`;
9851
+ var RECORDS_ASSIGN = "assign";
9852
+ var RECORDS_ASSIGN_GRANT = "records:assign";
9853
+ var RecordsAssignInputSchema = object({
9854
+ address: string2().min(1).max(1024),
9855
+ ownerMemberId: string2().min(1).max(256),
9856
+ expectedOwner: string2().min(1).max(256).nullable().optional(),
9857
+ ifRevision: string2().min(1).max(256),
9858
+ intentId: string2().min(1).max(256)
9859
+ }).strict();
9860
+ var SourceId = string2().min(1).max(256);
9861
+ var Address2 = string2().min(1).max(1024);
9862
+ var RecordsRecordSchema = object({
9863
+ address: Address2,
9864
+ revision: string2().min(1).max(256),
9865
+ scope: string2().min(1).max(256),
9866
+ columns: record(string2(), unknown()),
9867
+ extra: unknown().optional()
9868
+ }).strict();
9869
+ var RecordsSnapshotStateSchema = object({
9870
+ source: SourceId,
9871
+ epoch: string2().min(1).max(256),
9872
+ records: array(RecordsRecordSchema)
9873
+ }).strict();
9874
+ var RecordsChangedActionSchema = object({
9875
+ type: literal(RECORDS_CHANGED),
9876
+ source: SourceId,
9877
+ revision: string2().min(1).max(256),
9878
+ address: Address2,
9879
+ deleted: literal(true).optional(),
9880
+ record: RecordsRecordSchema.optional()
9881
+ }).strict();
9882
+ var RecordsActionNotificationSchema = object({
9883
+ channel: string2().min(1),
9884
+ serverSeq: number2().int().min(0).optional(),
9885
+ action: RecordsChangedActionSchema
9886
+ });
9887
+ var RECORDS_URI = new RegExp(`^${RECORDS_SCHEME}://[^/?#]+$`, "u");
9888
+ var isRecordsChannel = (channel) => channel === `${RECORDS_SCHEME}://` || RECORDS_URI.test(channel);
9837
9889
  // ../ahp/src/agent-records.ts
9838
9890
  var AgentRecordRowSchema = object({
9839
9891
  id: string2().min(1),
@@ -9867,8 +9919,9 @@ var MissingRefusalSchema = object({
9867
9919
  data: object({ staleRevision: literal(0) })
9868
9920
  });
9869
9921
  // ../ahp/src/host-requests.ts
9870
- var HOST_SCOPED_METHODS = ["subscribe", "x-ahpd/invokeOperation", "resourceRead"];
9922
+ var HOST_SCOPED_METHODS = ["subscribe", "x-ahpd/invokeOperation", "resourceRead", "listSessions", "authenticate"];
9871
9923
  var SERVICES_CHANNEL = "x-hh-services://";
9924
+ var SUBSCRIBE_CHANNELS = `${SERVICES_CHANNEL} and ${RECORDS_SCHEME}://<sourceId>`;
9872
9925
  var SERVICE_OPERATIONS = ["put", "remove", "start", "stop", "restart", "accept"];
9873
9926
  var SERVICES_BACKUP_URI = "hh-services://backup";
9874
9927
  var SERVICES_CHANGES_URI = "hh-services://changes";
@@ -9876,20 +9929,61 @@ var SERVICE_READ = /^(hh-service:\/\/[^/?#]+\/logs|hh-services:\/\/(backup|chang
9876
9929
  function hostScopedRefusal(method, params) {
9877
9930
  const named = (key) => typeof params[key] === "string" ? JSON.stringify(params[key]) : `no ${key}`;
9878
9931
  switch (method) {
9879
- case "subscribe":
9880
- if (params.channel === SERVICES_CHANNEL && Object.keys(params).length === 1)
9881
- return;
9882
- return `subscribe to ${named("channel")}${Object.keys(params).length > 1 ? " with more than a channel" : ""} is not one Hightea sends; only ${SERVICES_CHANNEL}`;
9883
- case "x-ahpd/invokeOperation":
9884
- if (params.channel !== SERVICES_CHANNEL)
9885
- return `x-ahpd/invokeOperation on ${named("channel")} is not one Hightea sends; only ${SERVICES_CHANNEL}`;
9886
- if (typeof params.operationId === "string" && SERVICE_OPERATIONS.includes(params.operationId))
9932
+ case "subscribe": {
9933
+ const channel = params.channel;
9934
+ if (Object.keys(params).length === 1 && typeof channel === "string" && (channel === SERVICES_CHANNEL || isRecordsChannel(channel)))
9887
9935
  return;
9888
- return `x-ahpd/invokeOperation ${named("operationId")} on ${SERVICES_CHANNEL} is not one Hightea sends; only ${SERVICE_OPERATIONS.join(", ")}`;
9936
+ return `subscribe to ${named("channel")}${Object.keys(params).length > 1 ? " with more than a channel" : ""} is not one Hightea sends; only ${SUBSCRIBE_CHANNELS}`;
9937
+ }
9938
+ case "x-ahpd/invokeOperation": {
9939
+ if (params.channel === SERVICES_CHANNEL) {
9940
+ if (typeof params.operationId === "string" && SERVICE_OPERATIONS.includes(params.operationId))
9941
+ return;
9942
+ return `x-ahpd/invokeOperation ${named("operationId")} on ${SERVICES_CHANNEL} is not one Hightea sends; only ${SERVICE_OPERATIONS.join(", ")}`;
9943
+ }
9944
+ if (params.channel === `${RECORDS_SCHEME}://`) {
9945
+ if (params.operationId === RECORDS_ASSIGN)
9946
+ return;
9947
+ return `x-ahpd/invokeOperation ${named("operationId")} on ${RECORDS_SCHEME}:// is not one Hightea sends; only ${RECORDS_ASSIGN} (${RECORDS_ASSIGN_GRANT})`;
9948
+ }
9949
+ return `x-ahpd/invokeOperation on ${named("channel")} is not one Hightea sends; only ${SERVICES_CHANNEL} and ${RECORDS_SCHEME}://`;
9950
+ }
9889
9951
  case "resourceRead":
9890
9952
  if (typeof params.uri === "string" && SERVICE_READ.test(params.uri))
9891
9953
  return;
9892
9954
  return `resourceRead of ${named("uri")} is not one Hightea sends; only hh-service://<name>/logs, ${SERVICES_BACKUP_URI} and ${SERVICES_CHANGES_URI}`;
9955
+ case "listSessions":
9956
+ if (params.channel === "ahp-root://" && Object.keys(params).length === 1)
9957
+ return;
9958
+ return `listSessions on ${named("channel")}${Object.keys(params).length > 1 ? " with more than a channel" : ""} is not one Hightea sends; only ahp-root://`;
9959
+ case "authenticate": {
9960
+ const keys = Object.keys(params).sort().join(",");
9961
+ if (keys !== "resource,target,token" && keys !== "expiresIn,resource,target,token") {
9962
+ return `authenticate naming ${JSON.stringify(keys)} is not one Hightea sends; only target, resource, token and expiresIn`;
9963
+ }
9964
+ if (typeof params.token !== "string")
9965
+ return "authenticate names no token";
9966
+ if (typeof params.resource !== "string" || params.resource === "")
9967
+ return `authenticate names ${named("resource")}`;
9968
+ const expiresIn = params.expiresIn;
9969
+ if (expiresIn !== undefined && !(typeof expiresIn === "number" && Number.isInteger(expiresIn) && expiresIn > 0)) {
9970
+ return "authenticate's expiresIn is not a positive integer of seconds";
9971
+ }
9972
+ const target = params.target;
9973
+ if (typeof target !== "object" || target === null || Array.isArray(target))
9974
+ return "authenticate names no target";
9975
+ const aimed = target;
9976
+ if (Object.keys(aimed).sort().join(",") !== "customizationId,kind,session") {
9977
+ return "authenticate's target carries more than kind, session and customizationId";
9978
+ }
9979
+ if (aimed.kind !== "mcpServer")
9980
+ return `authenticate's target kind is ${JSON.stringify(aimed.kind)}; only mcpServer`;
9981
+ if (typeof aimed.session !== "string" || aimed.session === "")
9982
+ return "authenticate's target names no session";
9983
+ if (typeof aimed.customizationId !== "string" || aimed.customizationId === "")
9984
+ return "authenticate's target names no server";
9985
+ return;
9986
+ }
9893
9987
  default:
9894
9988
  return `${JSON.stringify(method)} is not a host-scoped method; only ${HOST_SCOPED_METHODS.join(", ")}`;
9895
9989
  }
@@ -9910,6 +10004,7 @@ var HOST_REQUEST_TIMEOUT_MS = 1e4;
9910
10004
  var HOST_LOCAL_TIMEOUT_MS = HOST_REQUEST_TIMEOUT_MS - 1000;
9911
10005
  var HOST_REQUEST_ID_PREFIX = "host-request:";
9912
10006
  var AHP_PROTOCOL_VERSION = "1.1.0";
10007
+ var SIGNED_ENVELOPES_CAPABILITY = "signed-envelopes";
9913
10008
  var HostRequestMetaSchema = object({
9914
10009
  workspaceId: string2().min(1),
9915
10010
  hostId: string2().min(1),
@@ -9926,6 +10021,68 @@ function hostAnswerFrame(answer) {
9926
10021
  }
9927
10022
  return { error: { code: -32000, message: answer.reason, data: { reason: answer.reason } } };
9928
10023
  }
10024
+ var HostToolsServerSchema = object({
10025
+ resource: string2().min(1),
10026
+ customizationId: string2().min(1)
10027
+ }).strict();
10028
+ var HostToolsAnswerSchema = object({
10029
+ available: boolean2(),
10030
+ reason: string2().min(1).max(200).optional(),
10031
+ server: HostToolsServerSchema.optional()
10032
+ }).strict();
10033
+ var AHPD_HOST_TOOLS_KEY = "ahpd/hostTools";
10034
+ var HostSessionRowSchema = object({
10035
+ resource: string2().min(1),
10036
+ _meta: object({
10037
+ "hh/agentMemberId": string2().min(1),
10038
+ "hh/hostTools": HostToolsAnswerSchema.optional()
10039
+ }).strict()
10040
+ }).strict();
10041
+ var HostSessionChangedSchema = object({
10042
+ channel: literal("ahp-root://"),
10043
+ session: string2().min(1),
10044
+ changes: object({
10045
+ _meta: object({
10046
+ "hh/agentMemberId": string2().min(1),
10047
+ "hh/hostTools": HostToolsAnswerSchema
10048
+ }).strict()
10049
+ }).strict()
10050
+ }).strict();
10051
+ function narrowSessionMeta(meta, member, server) {
10052
+ const source = isRecord(meta) ? meta : {};
10053
+ const theirs = source["hh/agentMemberId"];
10054
+ if (theirs !== undefined && theirs !== member)
10055
+ return;
10056
+ const hostTools = HostToolsAnswerSchema.safeParse(source[AHPD_HOST_TOOLS_KEY]);
10057
+ if (!hostTools.success)
10058
+ return { "hh/agentMemberId": member };
10059
+ const available = hostTools.data.available && server !== undefined;
10060
+ return {
10061
+ "hh/agentMemberId": member,
10062
+ "hh/hostTools": {
10063
+ available: hostTools.data.available,
10064
+ ...hostTools.data.reason === undefined ? {} : { reason: hostTools.data.reason },
10065
+ ...available ? { server } : {}
10066
+ }
10067
+ };
10068
+ }
10069
+ function narrowSessionSummary(summary, member, server) {
10070
+ if (!isRecord(summary) || typeof summary.resource !== "string" || summary.resource === "")
10071
+ return;
10072
+ const meta = narrowSessionMeta(summary._meta, member, server);
10073
+ return meta === undefined ? undefined : { resource: summary.resource, _meta: meta };
10074
+ }
10075
+ var HostAuthRequiredSchema = object({
10076
+ channel: string2().min(1),
10077
+ resource: string2().min(1),
10078
+ reason: literal("expired")
10079
+ }).strict();
10080
+ function isRecord(value) {
10081
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10082
+ }
10083
+ // ../ahp/src/token-scope.ts
10084
+ var TOKEN_SCOPE_BASE = "event:all";
10085
+ var TOKEN_SCOPE_TOOLS_ALL = "tool:all";
9929
10086
  // ../ahp/src/index.ts
9930
10087
  var HOST_TO_CLOUD_EVENTS = [
9931
10088
  "session/ready",
@@ -9957,10 +10114,50 @@ var BOUNDED_ERROR_CODES = [
9957
10114
  "KEY_NOT_FOR_AUTHOR",
9958
10115
  "ASK_STALE",
9959
10116
  "ASK_REPLAYED",
9960
- "REPLAYED_ASK",
9961
10117
  "SERVICE_NOT_ALLOWED",
10118
+ "TURN_CANCELLED",
9962
10119
  ...SOURCE_ERROR_CODES
9963
10120
  ];
10121
+ var WAKE_TRIGGERS_MAX = 16;
10122
+ var WAKE_TRIGGER_BYTES_MAX = 48 * 1024;
10123
+ var WAKE_TRIGGERS_BYTES_MAX = 256 * 1024;
10124
+ var WakeTriggerSchema = object({
10125
+ id: string2().min(1),
10126
+ from: object({ memberId: string2().min(1) }).strict(),
10127
+ text: string2(),
10128
+ replyTo: string2().min(1).optional(),
10129
+ deleted: literal(true).optional(),
10130
+ signed: object({
10131
+ keyId: string2().min(1),
10132
+ createdAt: string2().min(1),
10133
+ signature: string2().min(1),
10134
+ clientId: string2().min(1),
10135
+ attachmentIds: array(string2().min(1))
10136
+ }).strict().optional()
10137
+ }).strict();
10138
+ var bytesOf = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
10139
+ var WakeTriggersSchema = array(WakeTriggerSchema).min(1).superRefine((triggers, ctx) => {
10140
+ if (triggers.length > WAKE_TRIGGERS_MAX) {
10141
+ ctx.addIssue({ code: "custom", message: `a wake carries at most ${WAKE_TRIGGERS_MAX} triggering envelopes, not ${triggers.length}` });
10142
+ return;
10143
+ }
10144
+ if (new Set(triggers.map((trigger) => trigger.id)).size !== triggers.length) {
10145
+ ctx.addIssue({ code: "custom", message: "a wake names each triggering message once" });
10146
+ return;
10147
+ }
10148
+ let total = 0;
10149
+ for (const trigger of triggers) {
10150
+ const size = bytesOf(trigger);
10151
+ if (size > WAKE_TRIGGER_BYTES_MAX) {
10152
+ ctx.addIssue({ code: "custom", message: `triggering envelope ${trigger.id} is ${size} bytes, over the ${WAKE_TRIGGER_BYTES_MAX}-byte limit` });
10153
+ return;
10154
+ }
10155
+ total += size;
10156
+ }
10157
+ if (total > WAKE_TRIGGERS_BYTES_MAX) {
10158
+ ctx.addIssue({ code: "custom", message: `the triggering envelopes take ${total} bytes, over the ${WAKE_TRIGGERS_BYTES_MAX}-byte limit` });
10159
+ }
10160
+ });
9964
10161
  var WakeMetaSchema = object({
9965
10162
  workspaceId: string2().min(1),
9966
10163
  deliveryId: string2().min(1),
@@ -9969,8 +10166,13 @@ var WakeMetaSchema = object({
9969
10166
  threadRef: string2().min(1),
9970
10167
  afterMessageId: string2().min(1).optional(),
9971
10168
  triggeringMessageIds: array(string2().min(1)).min(1).refine((ids) => new Set(ids).size === ids.length).optional(),
9972
- agentToken: string2().min(1).optional()
9973
- }).strict();
10169
+ triggering: WakeTriggersSchema.optional(),
10170
+ agentToken: string2().min(1).max(4096).optional()
10171
+ }).strict().superRefine((meta, ctx) => {
10172
+ if (meta.agentToken !== undefined && meta.triggering !== undefined) {
10173
+ ctx.addIssue({ code: "custom", message: "a wake carries its triggering envelopes or the older bearer, never both" });
10174
+ }
10175
+ });
9974
10176
  var HostToCloudFrameSchema = object({
9975
10177
  event: _enum(HOST_TO_CLOUD_EVENTS),
9976
10178
  channel: string2().min(1),
@@ -9988,6 +10190,23 @@ var HostToCloudFrameSchema = object({
9988
10190
  function parseHostToCloudFrame(input) {
9989
10191
  return HostToCloudFrameSchema.parse(input);
9990
10192
  }
10193
+ var HOST_ACTION_TYPES = [
10194
+ "session/ready",
10195
+ "chat/turnStarted",
10196
+ "chat/turnComplete",
10197
+ "chat/turnCancelled",
10198
+ "chat/error"
10199
+ ];
10200
+ var HostActionNotificationSchema = object({
10201
+ channel: string2().min(1),
10202
+ serverSeq: number2().int().min(0).optional(),
10203
+ origin: object({ clientId: string2().min(1), clientSeq: number2().int().min(1) }).optional(),
10204
+ action: object({
10205
+ type: _enum(HOST_ACTION_TYPES),
10206
+ turnId: string2().min(1).optional(),
10207
+ part: object({ error: object({ errorType: string2().min(1) }) }).optional()
10208
+ })
10209
+ });
9991
10210
  var HOST_HEADER = "Hightea-Host";
9992
10211
  var LEGACY_HOST_HEADER = "x-hightea-host";
9993
10212
 
@@ -9999,7 +10218,7 @@ var sessionKey = (workspaceId, agentMemberId, threadRef) => JSON.stringify([work
9999
10218
  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;
10000
10219
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
10001
10220
  var refuse = (code) => ({ ok: false, code });
10002
- function isRecord(value) {
10221
+ function isRecord2(value) {
10003
10222
  return typeof value === "object" && value !== null && !Array.isArray(value);
10004
10223
  }
10005
10224
  function exactKeys(value, required, optional = []) {
@@ -10011,7 +10230,7 @@ function readMeta(params) {
10011
10230
  return parsed.success ? parsed.data : undefined;
10012
10231
  }
10013
10232
  function checkCloudFrame(frame, registry) {
10014
- if (!isRecord(frame) || typeof frame.method !== "string")
10233
+ if (!isRecord2(frame) || typeof frame.method !== "string")
10015
10234
  return refuse("OPERATION_SHAPE_INVALID");
10016
10235
  if (!exactKeys(frame, ["method"], ["jsonrpc", "id", "params"]))
10017
10236
  return refuse("OPERATION_SHAPE_INVALID");
@@ -10020,7 +10239,7 @@ function checkCloudFrame(frame, registry) {
10020
10239
  return refuse("OPERATION_NOT_ALLOWLISTED");
10021
10240
  }
10022
10241
  const params = frame.params;
10023
- if (!isRecord(params))
10242
+ if (!isRecord2(params))
10024
10243
  return refuse("OPERATION_SHAPE_INVALID");
10025
10244
  const meta = readMeta(params);
10026
10245
  if (meta === undefined)
@@ -10032,7 +10251,7 @@ function checkCloudFrame(frame, registry) {
10032
10251
  return refuse("AGENT_NOT_MAPPED");
10033
10252
  const key = sessionKey(meta.workspaceId, meta.agentMemberId, meta.threadRef);
10034
10253
  const mapped = registry.sessions.get(key);
10035
- const { agentToken, ...publicMeta } = meta;
10254
+ const { triggering, agentToken, ...publicMeta } = meta;
10036
10255
  const id = frame.id;
10037
10256
  const head = { jsonrpc: "2.0", ...id === undefined ? {} : { id } };
10038
10257
  const channel = params.channel;
@@ -10054,7 +10273,7 @@ function checkCloudFrame(frame, registry) {
10054
10273
  params: { channel, provider: agent.provider, workingDirectories: [agent.workingDirectory] }
10055
10274
  },
10056
10275
  meta: publicMeta,
10057
- ...agentToken === undefined ? {} : { agentToken },
10276
+ ...triggering === undefined ? {} : { triggering },
10058
10277
  sessionKey: key
10059
10278
  };
10060
10279
  }
@@ -10070,7 +10289,7 @@ function checkCloudFrame(frame, registry) {
10070
10289
  operation: "subscribe",
10071
10290
  frame: { ...head, method, params: { channel } },
10072
10291
  meta: publicMeta,
10073
- ...agentToken === undefined ? {} : { agentToken },
10292
+ ...triggering === undefined ? {} : { triggering },
10074
10293
  sessionKey: key
10075
10294
  };
10076
10295
  }
@@ -10081,10 +10300,13 @@ function checkCloudFrame(frame, registry) {
10081
10300
  }
10082
10301
  if (typeof channel !== "string")
10083
10302
  return refuse("OPERATION_SHAPE_INVALID");
10084
- if (mapped?.chatUri === undefined || mapped.chatUri !== channel)
10303
+ if (mapped?.chatUri === undefined || mapped.chatUri !== channel) {
10304
+ if (registry.parked?.has(key) === true)
10305
+ return refuse("AGENT_NOT_MAPPED");
10085
10306
  return refuse("FOREIGN_SESSION");
10307
+ }
10086
10308
  const action = params.action;
10087
- if (!isRecord(action) || action.type !== "chat/turnStarted")
10309
+ if (!isRecord2(action) || action.type !== "chat/turnStarted")
10088
10310
  return refuse("OPERATION_NOT_ALLOWLISTED");
10089
10311
  if (!exactKeys(action, ["type", "turnId", "message"], ["startedAt"]))
10090
10312
  return refuse("OPERATION_SHAPE_INVALID");
@@ -10093,16 +10315,14 @@ function checkCloudFrame(frame, registry) {
10093
10315
  if (action.startedAt !== undefined && typeof action.startedAt !== "number")
10094
10316
  return refuse("OPERATION_SHAPE_INVALID");
10095
10317
  const message = action.message;
10096
- if (!isRecord(message) || !exactKeys(message, ["text", "origin"]) || typeof message.text !== "string") {
10318
+ if (!isRecord2(message) || !exactKeys(message, ["text", "origin"]) || typeof message.text !== "string") {
10097
10319
  return refuse("OPERATION_SHAPE_INVALID");
10098
10320
  }
10099
- if (!isRecord(message.origin) || !exactKeys(message.origin, ["kind"]) || message.origin.kind !== "user") {
10321
+ if (!isRecord2(message.origin) || !exactKeys(message.origin, ["kind"]) || message.origin.kind !== "user") {
10100
10322
  return refuse("OPERATION_SHAPE_INVALID");
10101
10323
  }
10102
10324
  if (message.text !== `wake ${meta.threadRef}`)
10103
10325
  return refuse("WAKE_TEXT_NOT_ALLOWED");
10104
- if (agentToken === undefined)
10105
- return refuse("TOKEN_EXPIRED_OR_REVOKED");
10106
10326
  return {
10107
10327
  ok: true,
10108
10328
  operation: "dispatchAction",
@@ -10121,7 +10341,8 @@ function checkCloudFrame(frame, registry) {
10121
10341
  }
10122
10342
  },
10123
10343
  meta: publicMeta,
10124
- agentToken,
10344
+ ...triggering === undefined ? {} : { triggering },
10345
+ ...agentToken === undefined ? {} : { readBearer: agentToken },
10125
10346
  sessionKey: key,
10126
10347
  turnId: action.turnId
10127
10348
  };
@@ -10172,7 +10393,7 @@ async function listHostServices(options) {
10172
10393
  } finally {
10173
10394
  if (subscribed) {
10174
10395
  try {
10175
- await options.peer.request("unsubscribe", { channel: SERVICES_CHANNEL }, HOST_LOCAL_TIMEOUT_MS);
10396
+ options.peer.notify("unsubscribe", { channel: SERVICES_CHANNEL });
10176
10397
  } catch (error) {
10177
10398
  options.log.error(`hightea-pipe: dropping the services subscription failed: ${error instanceof Error ? error.name : typeof error}`);
10178
10399
  }
@@ -10219,12 +10440,79 @@ async function listHostAgents(options) {
10219
10440
  const shown = rows.filter((row) => typeof row.id === "string" && providers.has(row.id));
10220
10441
  shown.sort((left, right) => String(left.id) < String(right.id) ? -1 : String(left.id) > String(right.id) ? 1 : 0);
10221
10442
  try {
10222
- await options.peer.request("unsubscribe", { channel: AGENTS_CHANNEL }, HOST_LOCAL_TIMEOUT_MS);
10443
+ options.peer.notify("unsubscribe", { channel: AGENTS_CHANNEL });
10223
10444
  } catch (error) {
10224
10445
  options.log.error(`hightea-pipe: dropping the agents subscription failed: ${error instanceof Error ? error.name : typeof error}`);
10225
10446
  }
10226
10447
  return { ok: true, result: { rows: shown } };
10227
10448
  }
10449
+ async function listHighteaSessions(options) {
10450
+ let answer;
10451
+ try {
10452
+ answer = await options.peer.request("listSessions", { channel: "ahp-root://" }, HOST_LOCAL_TIMEOUT_MS);
10453
+ } catch (error) {
10454
+ const answered = refusal(error);
10455
+ if (answered !== undefined)
10456
+ return { ok: false, reason: "refused", ...answered };
10457
+ options.log.error(`hightea-pipe: the session list is unreadable: ${error instanceof Error ? error.name : typeof error}`);
10458
+ if (timedOut(error))
10459
+ return { ok: false, reason: "timedOut" };
10460
+ return { ok: false, reason: "refused", code: -32603, message: "this host could not read ahpd's session list" };
10461
+ }
10462
+ const items = isRecord3(answer) && Array.isArray(answer.items) ? answer.items : undefined;
10463
+ if (items === undefined) {
10464
+ options.log.error("hightea-pipe: ahpd's listSessions result holds no items");
10465
+ return { ok: false, reason: "refused", code: -32603, message: "this host could not read ahpd's session list" };
10466
+ }
10467
+ const rows = [];
10468
+ const skipped = [];
10469
+ for (const item of items) {
10470
+ const uri = isRecord3(item) && typeof item.resource === "string" && item.resource !== "" ? item.resource : undefined;
10471
+ if (uri === undefined) {
10472
+ skipped.push("a summary with no resource");
10473
+ continue;
10474
+ }
10475
+ let member;
10476
+ try {
10477
+ member = options.memberOf(uri);
10478
+ } catch (error) {
10479
+ skipped.push(`${uri}: ${error instanceof Error ? error.message : String(error)}`);
10480
+ continue;
10481
+ }
10482
+ if (member === undefined)
10483
+ continue;
10484
+ const row = narrowSessionSummary(item, member, options.hostToolsServer(uri));
10485
+ if (row === undefined) {
10486
+ skipped.push(`${uri}: its summary names another member`);
10487
+ continue;
10488
+ }
10489
+ const hostTools = row._meta["hh/hostTools"];
10490
+ if (hostTools !== undefined)
10491
+ options.rememberHostTools?.(uri, hostTools);
10492
+ rows.push(row);
10493
+ }
10494
+ const listed = new Set(rows.map((row) => row.resource));
10495
+ for (const uri of options.ownSessions?.() ?? []) {
10496
+ if (listed.has(uri))
10497
+ continue;
10498
+ const member = options.memberOf(uri);
10499
+ if (member === undefined)
10500
+ continue;
10501
+ const answer = options.toolsAnswerOf?.(uri);
10502
+ if (answer === undefined) {
10503
+ skipped.push(`${uri}: provisional, and this pipe holds no tools answer for it yet`);
10504
+ continue;
10505
+ }
10506
+ const meta = narrowSessionMeta({ [AHPD_HOST_TOOLS_KEY]: answer }, member, options.hostToolsServer(uri));
10507
+ if (meta === undefined)
10508
+ continue;
10509
+ rows.push({ resource: uri, _meta: meta });
10510
+ }
10511
+ if (skipped.length > 0) {
10512
+ options.log.error(`hightea-pipe: skipped ${skipped.length} unreadable session row(s): ${skipped.join("; ").slice(0, 500)}`);
10513
+ }
10514
+ return { ok: true, result: { items: rows } };
10515
+ }
10228
10516
  async function answerHostRequest(input, options) {
10229
10517
  const meta = metaOf(input.meta);
10230
10518
  if (meta === undefined)
@@ -10233,7 +10521,7 @@ async function answerHostRequest(input, options) {
10233
10521
  if (!isHostRequestMethod(method) && !isHostScopedMethod(method))
10234
10522
  return { ok: false, reason: "outside" };
10235
10523
  const params = input.params;
10236
- if (!isRecord2(params))
10524
+ if (!isRecord3(params))
10237
10525
  return { ok: false, reason: "outside" };
10238
10526
  const carriesMember = "agentMemberId" in params;
10239
10527
  if (carriesMember && (typeof params.agentMemberId !== "string" || params.agentMemberId === ""))
@@ -10249,6 +10537,10 @@ async function answerHostRequest(input, options) {
10249
10537
  }
10250
10538
  if (method === "subscribe")
10251
10539
  return listHostServices(options);
10540
+ if (method === "listSessions")
10541
+ return listHighteaSessions(options);
10542
+ if (method === "authenticate")
10543
+ return authenticateHostTools(options, params);
10252
10544
  return runHostCommand(options, method, params);
10253
10545
  }
10254
10546
  if (method === "x-ahpd/agents/list") {
@@ -10275,12 +10567,33 @@ function metaOf(value) {
10275
10567
  const parsed = HostRequestMetaSchema.safeParse(value);
10276
10568
  return parsed.success ? parsed.data : undefined;
10277
10569
  }
10278
- function isRecord2(value) {
10570
+ function isRecord3(value) {
10279
10571
  return typeof value === "object" && value !== null && !Array.isArray(value);
10280
10572
  }
10281
10573
  function isHostRequestMethod(method) {
10282
10574
  return method === "x-ahpd/agents/list" || method === "x-ahpd/agents/put" || method === "x-ahpd/agents/remove" || method === "x-ahpd/agents/enable" || method === "x-ahpd/agents/pause" || method === "x-ahpd/agents/disable";
10283
10575
  }
10576
+ async function authenticateHostTools(options, params) {
10577
+ const target = params.target;
10578
+ if (typeof target.session !== "string" || options.memberOf(target.session) === undefined) {
10579
+ options.log.error("hightea-pipe: refused an authenticate aimed at a session this pipe did not make");
10580
+ return { ok: false, reason: "outside" };
10581
+ }
10582
+ const server = typeof target.session === "string" ? options.hostToolsServer(target.session) : undefined;
10583
+ if (server === undefined) {
10584
+ options.log.error("hightea-pipe: refused an authenticate: this host serves no Hightea MCP server, or the session has not yet said which customization is ours");
10585
+ return { ok: false, reason: "outside" };
10586
+ }
10587
+ if (target.customizationId !== server.customizationId) {
10588
+ options.log.error("hightea-pipe: refused an authenticate aimed at a server that is not this host's");
10589
+ return { ok: false, reason: "outside" };
10590
+ }
10591
+ if (params.resource !== server.resource) {
10592
+ options.log.error("hightea-pipe: refused an authenticate for a resource that is not this host's server");
10593
+ return { ok: false, reason: "outside" };
10594
+ }
10595
+ return runHostCommand(options, "authenticate", params);
10596
+ }
10284
10597
  async function runHostCommand(options, method, params) {
10285
10598
  try {
10286
10599
  const result = await options.peer.request(method, params, HOST_LOCAL_TIMEOUT_MS);
@@ -10294,73 +10607,6 @@ async function runHostCommand(options, method, params) {
10294
10607
  }
10295
10608
  }
10296
10609
 
10297
- // ../ahp-host/src/index.ts
10298
- class ActiveTurnTokenVault {
10299
- #activeBySession = new Map;
10300
- bindActiveTurn(credential) {
10301
- if (this.#activeBySession.has(credential.sessionId)) {
10302
- throw new Error(`Session ${credential.sessionId} already has an active turn credential; a queued wake cannot overwrite it`);
10303
- }
10304
- this.#activeBySession.set(credential.sessionId, credential);
10305
- }
10306
- renewActiveTurn(context, token, expiresAtMs, nowMs = Date.now()) {
10307
- const entry = this.#activeBySession.get(context.sessionId);
10308
- if (entry === undefined || entry.chatId !== context.chatId || entry.turnId !== context.turnId || entry.deliveryId !== context.deliveryId || entry.workspaceId !== context.workspaceId)
10309
- return false;
10310
- if (entry.expiresAtMs <= nowMs) {
10311
- this.#activeBySession.delete(context.sessionId);
10312
- return false;
10313
- }
10314
- if (token === "" || !Number.isFinite(expiresAtMs) || expiresAtMs <= entry.expiresAtMs)
10315
- return false;
10316
- this.#activeBySession.set(context.sessionId, { ...entry, token, expiresAtMs });
10317
- return true;
10318
- }
10319
- resolveForToolCall(context, nowMs = Date.now()) {
10320
- const entry = this.#activeBySession.get(context.sessionId);
10321
- if (entry === undefined) {
10322
- throw new Error(`No active-turn credential for session ${context.sessionId}`);
10323
- }
10324
- if (entry.chatId !== context.chatId || entry.turnId !== context.turnId) {
10325
- throw new Error(`Credential turn mismatch for session ${context.sessionId}: expected ${entry.chatId}/${entry.turnId}, got ${context.chatId}/${context.turnId}`);
10326
- }
10327
- if (nowMs >= entry.expiresAtMs) {
10328
- this.#activeBySession.delete(context.sessionId);
10329
- throw new Error(`Active-turn credential expired for session ${context.sessionId}`);
10330
- }
10331
- return {
10332
- token: entry.token,
10333
- deliveryId: entry.deliveryId,
10334
- threadRef: entry.threadRef,
10335
- agentMemberId: entry.agentMemberId,
10336
- ...entry.afterMessageId === undefined ? {} : { afterMessageId: entry.afterMessageId }
10337
- };
10338
- }
10339
- recordThreadRead(context, messageId, nowMs = Date.now()) {
10340
- this.resolveForToolCall(context, nowMs);
10341
- if (messageId === "")
10342
- throw new Error("read thread returned an empty message ID");
10343
- const entry = this.#activeBySession.get(context.sessionId);
10344
- this.#activeBySession.set(context.sessionId, { ...entry, afterMessageId: messageId });
10345
- }
10346
- revokeMember(workspaceId, agentMemberId) {
10347
- let dropped = 0;
10348
- for (const [sessionId, entry] of this.#activeBySession) {
10349
- if (entry.workspaceId === workspaceId && entry.agentMemberId === agentMemberId) {
10350
- this.#activeBySession.delete(sessionId);
10351
- dropped++;
10352
- }
10353
- }
10354
- return dropped;
10355
- }
10356
- clearTurn(sessionId, turnId) {
10357
- const entry = this.#activeBySession.get(sessionId);
10358
- if (entry === undefined || entry.turnId !== turnId)
10359
- return false;
10360
- return this.#activeBySession.delete(sessionId);
10361
- }
10362
- }
10363
-
10364
10610
  // ../ahp-host/src/ask-gate.ts
10365
10611
  import { createPrivateKey, createPublicKey as createPublicKey2, generateKeyPairSync, sign } from "node:crypto";
10366
10612
  import { appendFile, chmod, readFile, rename, writeFile } from "node:fs/promises";
@@ -10392,8 +10638,13 @@ function checkSignature(message, context) {
10392
10638
  if (signed === undefined)
10393
10639
  return { ok: false, code: "ASK_UNSIGNED", why: `message ${message.id} carries no signature` };
10394
10640
  const key = context.keys.find((trusted) => trusted.keyId === signed.keyId);
10395
- if (key === undefined)
10396
- return { ok: false, code: "ASK_UNSIGNED", why: `message ${message.id} is signed by key ${signed.keyId}, which this host does not trust` };
10641
+ if (key === undefined) {
10642
+ return {
10643
+ ok: false,
10644
+ code: "ROOM_ASKS_UNTRUSTED",
10645
+ why: `message ${message.id} is signed by key ${signed.keyId}, which this host does not trust yet; its owner approves that browser with \`hightea approve\` and the ask goes through`
10646
+ };
10647
+ }
10397
10648
  const bytes = signedPostBytes({
10398
10649
  workspaceId: context.workspaceId,
10399
10650
  roomId: context.roomId,
@@ -10433,7 +10684,7 @@ import { createHash } from "node:crypto";
10433
10684
  import { existsSync, readFileSync } from "node:fs";
10434
10685
  import { join } from "node:path";
10435
10686
  var TRUSTED_KEYS_FILE = "trusted-keys.json";
10436
- var TRUSTED_KEY_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
10687
+ var TRUSTED_KEY_NAME = /^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u;
10437
10688
  var BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u;
10438
10689
  var base64url2 = (bytes) => Buffer.from(bytes).toString("base64url");
10439
10690
  function trustedKeyId(publicKey) {
@@ -10546,6 +10797,34 @@ function threadOf(threadRef) {
10546
10797
  throw new AskRefusal("ASK_UNSIGNED", `the wake's thread ref ${threadRef} names no room thread`);
10547
10798
  return { roomId, rootMessageId };
10548
10799
  }
10800
+ function tokenFor(options, token, meta) {
10801
+ if (token === undefined || token === "") {
10802
+ throw new AskRefusal("ASK_UNSIGNED", `wake ${meta.deliveryId} carries no signed envelopes and this caller has no bearer to read its thread with`);
10803
+ }
10804
+ return token;
10805
+ }
10806
+ function carriedTriggers(carried, wanted, rootMessageId, meta) {
10807
+ const found = new Map;
10808
+ for (const trigger of carried) {
10809
+ const root = trigger.replyTo ?? trigger.id;
10810
+ if (root !== rootMessageId) {
10811
+ throw new AskRefusal("ASK_UNSIGNED", `wake ${meta.deliveryId} carries message ${trigger.id} from thread ${root}, not ${meta.threadRef}`);
10812
+ }
10813
+ found.set(trigger.id, {
10814
+ id: trigger.id,
10815
+ from: { memberId: trigger.from.memberId },
10816
+ text: trigger.text,
10817
+ ...trigger.replyTo === undefined ? {} : { replyTo: trigger.replyTo },
10818
+ ...trigger.deleted === undefined ? {} : { deleted: true },
10819
+ ...trigger.signed === undefined ? {} : { signed: trigger.signed }
10820
+ });
10821
+ }
10822
+ const ids = new Set(found.keys());
10823
+ if (ids.size !== wanted.length || wanted.some((id) => !ids.has(id))) {
10824
+ throw new AskRefusal("ASK_UNSIGNED", `wake ${meta.deliveryId} froze ${wanted.length} triggering messages and carried ${ids.size}, not the same ones`);
10825
+ }
10826
+ return found;
10827
+ }
10549
10828
 
10550
10829
  class AskGate {
10551
10830
  #options;
@@ -10557,10 +10836,11 @@ class AskGate {
10557
10836
  async admit(meta, token) {
10558
10837
  const { roomId, rootMessageId } = threadOf(meta.threadRef);
10559
10838
  const context = await signatureContext(this.#options, roomId);
10560
- const wanted = meta.triggeringMessageIds;
10561
- if (wanted === undefined)
10839
+ const carried = meta.triggering;
10840
+ const wanted = carried === undefined ? meta.triggeringMessageIds : carried.map((trigger) => trigger.id);
10841
+ if (wanted === undefined || wanted.length === 0)
10562
10842
  throw new AskRefusal("ASK_UNSIGNED", `wake ${meta.deliveryId} names no triggering message to check`);
10563
- const found = await this.#triggers(token, roomId, rootMessageId, meta.afterMessageId, new Set(wanted));
10843
+ const found = carried === undefined ? await this.#triggers(tokenFor(this.#options, token, meta), roomId, rootMessageId, meta.afterMessageId, new Set(wanted)) : carriedTriggers(carried, wanted, rootMessageId, meta);
10564
10844
  const now = (this.#options.now ?? Date.now)();
10565
10845
  const acted = await this.#load(now);
10566
10846
  const admitted = [];
@@ -10704,27 +10984,171 @@ function cloudOperationFailureCode(error) {
10704
10984
  }
10705
10985
  var SUPPORTED_PROTOCOL = AHP_PROTOCOL_VERSION;
10706
10986
  var REQUEST_TIMEOUT_MS = 15000;
10987
+ var GATEWAY_ACTIONS_META = "x-hh/actions";
10988
+ function forwardedAction(frame, context = {}) {
10989
+ const startedAtMs = context.startedAtMs ?? Date.now();
10990
+ const duration = Math.max(0, Date.now() - startedAtMs);
10991
+ const turn = frame.turnId === undefined || frame.turnId === "" ? {} : { turnId: frame.turnId };
10992
+ if (frame.event === "session/ready") {
10993
+ return { channel: frame.session, action: { type: "session/ready", ...turn } };
10994
+ }
10995
+ if (frame.event === "chat/turnStarted") {
10996
+ return {
10997
+ channel: frame.chat,
10998
+ action: {
10999
+ type: "chat/turnStarted",
11000
+ ...turn,
11001
+ startedAt: new Date(startedAtMs).toISOString()
11002
+ },
11003
+ ...frame.clientSeq === undefined ? {} : { origin: { clientId: context.clientId ?? "hightea-gateway", clientSeq: frame.clientSeq } }
11004
+ };
11005
+ }
11006
+ if (frame.event === "chat/turnComplete") {
11007
+ return { channel: frame.chat, action: { type: "chat/turnComplete", ...turn, duration } };
11008
+ }
11009
+ const errorType = frame.errorCode ?? "OPERATION_SHAPE_INVALID";
11010
+ if (errorType === "TURN_CANCELLED") {
11011
+ return { channel: frame.chat, action: { type: "chat/turnCancelled", ...turn, duration } };
11012
+ }
11013
+ return {
11014
+ channel: frame.chat,
11015
+ action: {
11016
+ type: "chat/error",
11017
+ ...turn,
11018
+ duration,
11019
+ part: { kind: "error", error: { errorType, message: "" } }
11020
+ }
11021
+ };
11022
+ }
10707
11023
  var attemptKey = (deliveryId, turnId) => JSON.stringify([deliveryId, turnId]);
11024
+ function newestTriggerMs(meta) {
11025
+ let newest;
11026
+ for (const trigger of meta.triggering ?? []) {
11027
+ const at = trigger.signed === undefined ? Number.NaN : Date.parse(trigger.signed.createdAt);
11028
+ if (!Number.isFinite(at))
11029
+ continue;
11030
+ if (newest === undefined || at > newest)
11031
+ newest = at;
11032
+ }
11033
+ return newest;
11034
+ }
10708
11035
  var PipeStateSchema = object({
10709
11036
  sessions: array(tuple([string2().min(1), object({ sessionUri: string2().min(1), chatUri: string2().min(1).optional() }).strict()])),
10710
11037
  dispatched: array(tuple([string2().min(1), array(string2().min(1))])),
10711
11038
  lastStatus: array(tuple([string2().min(1), HostToCloudFrameSchema]))
10712
11039
  }).strict();
11040
+ var LegacyHostToCloudFrameSchema = object({
11041
+ event: _enum(["session.created", "turn.started", "turn.finished", "turn.error"]),
11042
+ houseId: string2().min(1),
11043
+ deliveryId: string2().min(1),
11044
+ sessionId: string2().min(1),
11045
+ chatId: string2().min(1),
11046
+ turnId: string2().min(1).optional(),
11047
+ turnState: _enum(["created", "running", "finished", "error"]),
11048
+ statusCode: string2().min(1).max(64),
11049
+ errorCode: _enum(BOUNDED_ERROR_CODES).optional(),
11050
+ errorDetail: string2().max(256).optional()
11051
+ }).strict();
11052
+ var LEGACY_EVENTS = {
11053
+ "session.created": "session/ready",
11054
+ "turn.started": "chat/turnStarted",
11055
+ "turn.finished": "chat/turnComplete",
11056
+ "turn.error": "x-hh/turnFailed"
11057
+ };
11058
+ function upgradeLegacyFrame(frame) {
11059
+ return {
11060
+ event: LEGACY_EVENTS[frame.event],
11061
+ channel: frame.event === "session.created" ? frame.sessionId : frame.chatId,
11062
+ workspaceId: frame.houseId,
11063
+ deliveryId: frame.deliveryId,
11064
+ session: frame.sessionId,
11065
+ chat: frame.chatId,
11066
+ ...frame.turnId === undefined ? {} : { turnId: frame.turnId },
11067
+ turnState: frame.turnState,
11068
+ statusCode: frame.statusCode,
11069
+ ...frame.errorCode === undefined ? {} : { errorCode: frame.errorCode },
11070
+ ...frame.errorDetail === undefined ? {} : { errorDetail: frame.errorDetail }
11071
+ };
11072
+ }
11073
+ var PipeStateRecordSchema = object({
11074
+ sessions: array(tuple([string2().min(1), object({ sessionUri: string2().min(1), chatUri: string2().min(1).optional() }).strict()])),
11075
+ dispatched: array(tuple([string2().min(1), array(string2().min(1))])),
11076
+ lastStatus: array(unknown())
11077
+ }).strict();
11078
+ var statusKey = (frame) => frame.turnId === undefined ? frame.deliveryId : attemptKey(frame.deliveryId, frame.turnId);
11079
+ function describeIssues(error) {
11080
+ const shown = error.issues.slice(0, 3).map((issue) => `${issue.path.join(".") || "(record)"} ${issue.message}`);
11081
+ return `${shown.join("; ")}${error.issues.length > 3 ? `; and ${error.issues.length - 3} more` : ""}`;
11082
+ }
11083
+ function frameKind(entry) {
11084
+ const frame = Array.isArray(entry) ? entry[1] : entry;
11085
+ if (typeof frame === "object" && frame !== null) {
11086
+ const event = frame.event;
11087
+ if (typeof event === "string")
11088
+ return `event=${event}`;
11089
+ }
11090
+ return Array.isArray(entry) ? `a frame of ${typeof frame}` : `${entry === null ? "null" : typeof entry}`;
11091
+ }
11092
+ function readPipeState(loaded, log) {
11093
+ const record = PipeStateRecordSchema.safeParse(loaded);
11094
+ if (!record.success)
11095
+ throw new Error(`ahp-host: invalid durable state: ${describeIssues(record.error)}`);
11096
+ const lastStatus = [];
11097
+ let upgraded = 0;
11098
+ let dropped = 0;
11099
+ record.data.lastStatus.forEach((entry, index) => {
11100
+ const pair = tuple([string2().min(1), unknown()]).safeParse(entry);
11101
+ const key = pair.success ? pair.data[0] : "";
11102
+ const asCurrent = pair.success ? HostToCloudFrameSchema.safeParse(pair.data[1]) : undefined;
11103
+ const legacy = pair.success && asCurrent?.success === false ? LegacyHostToCloudFrameSchema.safeParse(pair.data[1]) : undefined;
11104
+ const frame = asCurrent?.success === true ? asCurrent.data : legacy?.success === true ? upgradeLegacyFrame(legacy.data) : undefined;
11105
+ if (frame === undefined) {
11106
+ dropped += 1;
11107
+ const legacyShaped = pair.success && typeof pair.data[1] === "object" && pair.data[1] !== null && "houseId" in pair.data[1];
11108
+ const reason = legacy?.success === false && legacyShaped ? `pre-0.1.11 shape: ${describeIssues(legacy.error)}` : asCurrent?.success === false ? describeIssues(asCurrent.error) : "not a [key, frame] entry";
11109
+ log.error(`ahp-host: dropped durable status frame lastStatus[${index}] (${frameKind(entry)}): ${reason}`);
11110
+ return;
11111
+ }
11112
+ if (statusKey(frame) !== key) {
11113
+ dropped += 1;
11114
+ log.error(`ahp-host: dropped durable status frame lastStatus[${index}] (event=${frame.event}): its key names a different delivery or turn`);
11115
+ return;
11116
+ }
11117
+ if (asCurrent?.success !== true) {
11118
+ upgraded += 1;
11119
+ log.error(`ahp-host: upgraded durable status frame lastStatus[${index}] (${frameKind(entry)} -> event=${frame.event}) from the pre-0.1.11 shape`);
11120
+ }
11121
+ lastStatus.push([key, frame]);
11122
+ });
11123
+ if (upgraded > 0 || dropped > 0) {
11124
+ log.error(`ahp-host: durable state repaired: ${upgraded} status frame(s) upgraded from the pre-0.1.11 shape, ${dropped} dropped; the pipe starts and rewrites the state`);
11125
+ }
11126
+ const sessions = record.data.sessions.map(([key, session]) => [key, {
11127
+ sessionUri: session.sessionUri,
11128
+ ...session.chatUri === undefined ? {} : { chatUri: session.chatUri }
11129
+ }]);
11130
+ return { sessions, dispatched: record.data.dispatched, lastStatus };
11131
+ }
10713
11132
 
10714
11133
  class WakePipe {
10715
- vault = new ActiveTurnTokenVault;
10716
11134
  #sessions = new Map;
10717
11135
  #dispatched = new Map;
10718
11136
  #active = new Map;
10719
11137
  #pendingInitialize = [];
10720
11138
  #queued = new Map;
10721
11139
  #subscribed = new Set;
11140
+ #live = new Map;
11141
+ #parked = new Map;
11142
+ #toolsIds = new Map;
11143
+ #toolsAnswers = new Map;
10722
11144
  #lastStatus = new Map;
10723
11145
  #writes = Promise.resolve();
10724
11146
  #storeError;
10725
11147
  #started = false;
10726
11148
  #seq = 0;
10727
11149
  #droppedInputRequests = 0;
11150
+ #actionsFromGateway = false;
11151
+ #gatewayClientId = "";
10728
11152
  peer;
10729
11153
  cloud;
10730
11154
  options;
@@ -10740,7 +11164,24 @@ class WakePipe {
10740
11164
  });
10741
11165
  }
10742
11166
  get registry() {
10743
- return { workspaceId: this.options.workspaceId, agents: this.options.agents, sessions: this.#sessions };
11167
+ return { workspaceId: this.options.workspaceId, agents: this.options.agents, sessions: this.#sessions, parked: this.#parked };
11168
+ }
11169
+ agentMemberOf(sessionUri) {
11170
+ for (const [key, mapped] of this.#sessions) {
11171
+ if (mapped.sessionUri !== sessionUri)
11172
+ continue;
11173
+ let parts;
11174
+ try {
11175
+ parts = JSON.parse(key);
11176
+ } catch (error) {
11177
+ throw new Error(`ahp-host: session key ${key} of ${sessionUri} is not a session key: ${String(error)}`);
11178
+ }
11179
+ if (!Array.isArray(parts) || typeof parts[1] !== "string" || parts[1] === "") {
11180
+ throw new Error(`ahp-host: session key ${key} of ${sessionUri} names no member`);
11181
+ }
11182
+ return parts[1];
11183
+ }
11184
+ return;
10744
11185
  }
10745
11186
  async start(clientId) {
10746
11187
  this.#started = false;
@@ -10753,24 +11194,24 @@ class WakePipe {
10753
11194
  this.#ready();
10754
11195
  return;
10755
11196
  }
10756
- const parsed = PipeStateSchema.safeParse(loaded);
10757
- if (!parsed.success)
10758
- throw new Error("ahp-host: invalid durable state");
10759
- const saved = parsed.data;
11197
+ const saved = readPipeState(loaded, this.options.log);
10760
11198
  for (const [key, session] of saved.sessions) {
11199
+ if (session.chatUri !== undefined) {
11200
+ this.#sessions.set(key, { sessionUri: session.sessionUri, chatUri: session.chatUri });
11201
+ continue;
11202
+ }
10761
11203
  let chatUri;
10762
11204
  try {
10763
11205
  chatUri = await this.#resumeSession(session.sessionUri);
10764
11206
  } catch (error) {
10765
11207
  if (cloudOperationFailureCode(error) === "AGENT_NOT_MAPPED") {
10766
- throw new UnmappedAgent(error instanceof Error ? error.message : String(error), { cause: error });
11208
+ this.#park(key, session.sessionUri, error);
11209
+ continue;
10767
11210
  }
10768
11211
  throw error;
10769
11212
  }
10770
11213
  this.#subscribed.delete(session.sessionUri);
10771
11214
  this.peer.notify("unsubscribe", { channel: session.sessionUri });
10772
- if (session.chatUri !== undefined && chatUri !== session.chatUri)
10773
- throw new Error("ahp-host: saved session answered a different chat");
10774
11215
  this.#sessions.set(key, { sessionUri: session.sessionUri, chatUri });
10775
11216
  }
10776
11217
  const interrupted = [];
@@ -10822,12 +11263,25 @@ class WakePipe {
10822
11263
  for (const id of this.#pendingInitialize.splice(0))
10823
11264
  this.#initializeAnswer(id);
10824
11265
  }
11266
+ #park(key, sessionUri, error) {
11267
+ const reason = error instanceof Error ? error.message : String(error);
11268
+ this.#parked.set(key, reason);
11269
+ this.#sessions.set(key, { sessionUri });
11270
+ this.options.log.error(`hightea-pipe: saved session ${sessionUri} is parked: ahpd will not resume it and its agent is not mapped ` + `(AGENT_NOT_MAPPED), so its wakes are refused by name; every other agent on this host carries on: ${reason}`);
11271
+ }
10825
11272
  #initialize(id, params) {
10826
11273
  const offered = typeof params === "object" && params !== null && Array.isArray(params.protocolVersions) ? params.protocolVersions.filter((version) => typeof version === "string") : [];
10827
11274
  if (!offered.includes(SUPPORTED_PROTOCOL)) {
10828
11275
  this.cloud.reply(id, { error: { code: -32005, message: "UnsupportedProtocolVersion", data: { supportedVersions: [SUPPORTED_PROTOCOL] } } });
10829
11276
  return;
10830
11277
  }
11278
+ const meta = params._meta;
11279
+ if (typeof meta === "object" && meta !== null && meta[GATEWAY_ACTIONS_META] === true) {
11280
+ this.#actionsFromGateway = true;
11281
+ }
11282
+ const clientId = params.clientId;
11283
+ if (typeof clientId === "string" && clientId !== "")
11284
+ this.#gatewayClientId = clientId;
10831
11285
  if (!this.#started) {
10832
11286
  this.#pendingInitialize.push(id);
10833
11287
  return;
@@ -10836,10 +11290,17 @@ class WakePipe {
10836
11290
  }
10837
11291
  #initializeAnswer(id) {
10838
11292
  const handshake = this.options.handshake;
11293
+ const sources = handshake?.sources?.();
11294
+ const meta = {
11295
+ ...handshake === undefined ? {} : { ahpd: handshake.ahpd },
11296
+ ...handshake?.capabilities === undefined || handshake.capabilities.length === 0 ? {} : { capabilities: handshake.capabilities },
11297
+ ...sources === undefined || sources.length === 0 ? {} : { sources }
11298
+ };
10839
11299
  this.cloud.reply(id, { result: {
10840
11300
  protocolVersion: SUPPORTED_PROTOCOL,
10841
11301
  serverSeq: 0,
10842
- ...handshake === undefined ? {} : { serverInfo: handshake.plugin, _meta: { ahpd: handshake.ahpd } },
11302
+ ...handshake === undefined ? {} : { serverInfo: handshake.plugin },
11303
+ ...Object.keys(meta).length === 0 ? {} : { _meta: meta },
10843
11304
  snapshots: []
10844
11305
  } });
10845
11306
  }
@@ -10853,8 +11314,7 @@ class WakePipe {
10853
11314
  if (this.#storeError === undefined) {
10854
11315
  this.#storeError = new Error("ahp-host: durable state write failed", { cause: error });
10855
11316
  for (const turn of this.#active.values()) {
10856
- this.vault.clearTurn(turn.sessionUri, turn.turnId);
10857
- this.#stopRenewal(turn);
11317
+ turn.cancelled = true;
10858
11318
  }
10859
11319
  this.options.log.error(`${this.#storeError.message}: ${String(error)}`);
10860
11320
  }
@@ -10862,13 +11322,6 @@ class WakePipe {
10862
11322
  });
10863
11323
  return this.#writes;
10864
11324
  }
10865
- resolveToolToken(context, nowMs = Date.now()) {
10866
- try {
10867
- return { ok: true, ...this.vault.resolveForToolCall(context, nowMs) };
10868
- } catch {
10869
- return { ok: false, code: "TOKEN_EXPIRED_OR_REVOKED" };
10870
- }
10871
- }
10872
11325
  async#revoke(id, params) {
10873
11326
  const ok = typeof params === "object" && params !== null && !Array.isArray(params) && Object.keys(params).sort().join(",") === "agentMemberId,workspaceId" && params.workspaceId === this.options.workspaceId && typeof params.agentMemberId === "string";
10874
11327
  if (!ok) {
@@ -10877,11 +11330,9 @@ class WakePipe {
10877
11330
  return;
10878
11331
  }
10879
11332
  const member = params.agentMemberId;
10880
- this.vault.revokeMember(this.options.workspaceId, member);
10881
11333
  for (const turn of this.#active.values()) {
10882
11334
  if (turn.workspaceId === this.options.workspaceId && turn.agentMemberId === member) {
10883
11335
  turn.cancelled = true;
10884
- this.#stopRenewal(turn);
10885
11336
  }
10886
11337
  }
10887
11338
  const reports = [];
@@ -10932,8 +11383,13 @@ class WakePipe {
10932
11383
  meta: frame._meta
10933
11384
  }, {
10934
11385
  agents: this.options.agents,
11386
+ memberOf: (uri) => this.agentMemberOf(uri),
10935
11387
  peer: this.peer,
10936
- log: this.options.log
11388
+ log: this.options.log,
11389
+ hostToolsServer: (uri) => this.#toolsServerOf(uri),
11390
+ rememberHostTools: (uri, answer) => this.#toolsAnswers.set(uri, answer),
11391
+ ownSessions: () => [...this.#sessions.values()].map((mapped) => mapped.sessionUri),
11392
+ toolsAnswerOf: (uri) => this.#toolsAnswers.get(uri)
10937
11393
  });
10938
11394
  this.cloud.hostRequestAnswer(requestId, answer);
10939
11395
  return;
@@ -10959,6 +11415,7 @@ class WakePipe {
10959
11415
  return;
10960
11416
  }
10961
11417
  try {
11418
+ let snapshot;
10962
11419
  if (decision.operation === "createSession") {
10963
11420
  const agent = this.options.agents.get(decision.meta.agentMemberId);
10964
11421
  if (agent === undefined)
@@ -10966,7 +11423,13 @@ class WakePipe {
10966
11423
  let winnerUri;
10967
11424
  let sessionUri;
10968
11425
  try {
10969
- sessionUri = await this.options.startSession({ owner: this.options.owner, provider: agent.provider, workingDirectory: fileURLToPath(agent.workingDirectory), tools: this.options.tools }, async (uri) => {
11426
+ sessionUri = await this.options.startSession({
11427
+ owner: this.options.owner,
11428
+ provider: agent.provider,
11429
+ workingDirectory: fileURLToPath(agent.workingDirectory),
11430
+ tools: this.options.tools,
11431
+ ...agent.settings === undefined ? {} : { config: agent.settings }
11432
+ }, async (uri) => {
10970
11433
  if (this.options.store?.reserve !== undefined) {
10971
11434
  const resolved = await this.options.store.reserve(decision.sessionKey, uri);
10972
11435
  this.#sessions.set(decision.sessionKey, { sessionUri: resolved });
@@ -10989,6 +11452,7 @@ class WakePipe {
10989
11452
  throw new Error("ahp-host: created session differs from its durable reservation");
10990
11453
  const chatUri = winnerUri !== undefined ? await this.#resumeSession(sessionUri) : await this.#subscribeSession(sessionUri);
10991
11454
  this.#sessions.set(decision.sessionKey, { sessionUri, chatUri });
11455
+ this.#live.set(sessionUri, Promise.resolve());
10992
11456
  await this.#save();
10993
11457
  await this.#status({
10994
11458
  event: "session/ready",
@@ -11003,13 +11467,24 @@ class WakePipe {
11003
11467
  });
11004
11468
  } else if (decision.operation === "subscribe") {
11005
11469
  const sessionUri = decision.frame.params.channel;
11006
- const chatUri = await this.#resumeSession(sessionUri);
11007
- this.#sessions.set(decision.sessionKey, { sessionUri, chatUri });
11470
+ const mapped = this.#sessions.get(decision.sessionKey);
11471
+ if (mapped?.sessionUri !== sessionUri || mapped.chatUri === undefined) {
11472
+ throw new Error("ahp-host: a subscribe reached a session this host has no chat for");
11473
+ }
11474
+ snapshot = { snapshot: { resource: sessionUri, state: { defaultChat: mapped.chatUri } } };
11008
11475
  } else {
11009
- await this.#sendTurn(decision.sessionKey, decision.frame, decision.meta, decision.agentToken, decision.turnId);
11476
+ await this.#sendTurn(decision.sessionKey, decision.frame, {
11477
+ ...decision.meta,
11478
+ ...decision.triggering === undefined ? {} : { triggering: decision.triggering },
11479
+ ...decision.readBearer === undefined ? {} : { readBearer: decision.readBearer }
11480
+ }, decision.turnId);
11481
+ }
11482
+ if (id !== undefined) {
11483
+ if (snapshot === undefined)
11484
+ this.cloud.answer(id, { ok: true });
11485
+ else
11486
+ this.cloud.reply(id, { result: snapshot });
11010
11487
  }
11011
- if (id !== undefined)
11012
- this.cloud.answer(id, { ok: true });
11013
11488
  } catch (error) {
11014
11489
  const code = cloudOperationFailureCode(error);
11015
11490
  this.options.log.error(`ahp-host: cloud operation ${decision.operation} failed (${code}): ${String(error)}`);
@@ -11017,6 +11492,21 @@ class WakePipe {
11017
11492
  this.cloud.answer(id, { ok: false, code });
11018
11493
  }
11019
11494
  }
11495
+ async#ensureLive(sessionUri, chatUri) {
11496
+ let live = this.#live.get(sessionUri);
11497
+ if (live === undefined) {
11498
+ live = this.#resumeSession(sessionUri).then((answered) => {
11499
+ if (answered !== chatUri)
11500
+ throw new Error("ahp-host: saved session answered a different chat");
11501
+ });
11502
+ this.#live.set(sessionUri, live);
11503
+ live.catch(() => {
11504
+ if (this.#live.get(sessionUri) === live)
11505
+ this.#live.delete(sessionUri);
11506
+ });
11507
+ }
11508
+ await live;
11509
+ }
11020
11510
  async#resumeSession(sessionUri) {
11021
11511
  const resumed = await this.options.startSession({ owner: this.options.owner, resume: sessionUri });
11022
11512
  if (resumed !== sessionUri)
@@ -11026,16 +11516,18 @@ class WakePipe {
11026
11516
  async#subscribeSession(sessionUri) {
11027
11517
  const answer = await this.peer.request("subscribe", { channel: sessionUri }, REQUEST_TIMEOUT_MS);
11028
11518
  this.#subscribed.add(sessionUri);
11519
+ this.#rememberToolsServer(sessionUri, answer?.snapshot?.state?.customizations);
11520
+ this.#rememberPublishedToolsAnswer(sessionUri, answer?.snapshot?.state);
11029
11521
  const chatUri = answer?.snapshot?.state?.defaultChat;
11030
11522
  if (typeof chatUri !== "string" || chatUri.length === 0) {
11031
11523
  throw new Error(`ahp-host: ${sessionUri} answered no defaultChat`);
11032
11524
  }
11033
11525
  return chatUri;
11034
11526
  }
11035
- async#sendTurn(key, frame, meta, token, turnId) {
11527
+ async#sendTurn(key, frame, meta, turnId) {
11036
11528
  const mapped = this.#sessions.get(key);
11037
- if (mapped?.chatUri === undefined || token === undefined || turnId === undefined) {
11038
- throw new Error("ahp-host: a turn reached dispatch without its mapping, token or turn id");
11529
+ if (mapped?.chatUri === undefined || turnId === undefined) {
11530
+ throw new Error("ahp-host: a turn reached dispatch without its mapping or turn id");
11039
11531
  }
11040
11532
  const seen = this.#dispatched.get(key) ?? new Set;
11041
11533
  const attempt = attemptKey(meta.deliveryId, turnId);
@@ -11043,19 +11535,16 @@ class WakePipe {
11043
11535
  const last = this.#lastStatus.get(attempt);
11044
11536
  await this.#writes;
11045
11537
  if (last !== undefined)
11046
- this.cloud.status(last);
11538
+ this.#send(last);
11047
11539
  return;
11048
11540
  }
11049
- if (this.options.tokenExpiresAt(token) === undefined)
11050
- throw new FrameRefusal("ahp-host: an agent token whose expiry cannot be read");
11051
11541
  if (this.options.admitTurn !== undefined)
11052
- await this.options.admitTurn(meta, token);
11542
+ await this.options.admitTurn(meta, meta.readBearer);
11543
+ await this.#ensureLive(mapped.sessionUri, mapped.chatUri);
11053
11544
  const running = this.#active.get(key);
11054
11545
  if (running !== undefined) {
11055
11546
  if (running.deliveryId === meta.deliveryId) {
11056
- this.vault.clearTurn(running.sessionUri, running.turnId);
11057
11547
  running.cancelled = true;
11058
- this.#stopRenewal(running);
11059
11548
  }
11060
11549
  const queued = this.#queued.get(key) ?? [];
11061
11550
  for (const old of queued) {
@@ -11066,35 +11555,20 @@ class WakePipe {
11066
11555
  this.#dispatched.set(key, seen);
11067
11556
  const queue = queued.filter((one) => one.meta.deliveryId !== meta.deliveryId || one.turnId === turnId);
11068
11557
  if (!queue.some((one) => one.meta.deliveryId === meta.deliveryId))
11069
- queue.push({ frame, meta, token, turnId });
11558
+ queue.push({ frame, meta, turnId });
11070
11559
  this.#queued.set(key, queue);
11071
11560
  await this.#save();
11072
11561
  return;
11073
11562
  }
11074
- await this.#dispatch(key, frame, meta, token, turnId);
11563
+ await this.#dispatch(key, frame, meta, turnId);
11075
11564
  }
11076
- async#dispatch(key, frame, meta, token, turnId) {
11565
+ async#dispatch(key, frame, meta, turnId) {
11077
11566
  const mapped = this.#sessions.get(key);
11078
11567
  if (mapped?.chatUri === undefined)
11079
11568
  throw new Error("ahp-host: dispatch has no mapped chat");
11080
11569
  if (this.#activeForChat(mapped.sessionUri, mapped.chatUri).length > 0) {
11081
11570
  throw new Error("ahp-host: wake already active for this session and chat");
11082
11571
  }
11083
- const expiresAtMs = this.options.tokenExpiresAt(token);
11084
- if (expiresAtMs === undefined)
11085
- throw new FrameRefusal("ahp-host: an agent token whose expiry cannot be read");
11086
- this.vault.bindActiveTurn({
11087
- sessionId: mapped.sessionUri,
11088
- chatId: mapped.chatUri,
11089
- turnId,
11090
- deliveryId: meta.deliveryId,
11091
- threadRef: meta.threadRef,
11092
- ...meta.afterMessageId === undefined ? {} : { afterMessageId: meta.afterMessageId },
11093
- workspaceId: meta.workspaceId,
11094
- agentMemberId: meta.agentMemberId,
11095
- token,
11096
- expiresAtMs
11097
- });
11098
11572
  const active = {
11099
11573
  key,
11100
11574
  deliveryId: meta.deliveryId,
@@ -11103,11 +11577,11 @@ class WakePipe {
11103
11577
  sessionUri: mapped.sessionUri,
11104
11578
  chatUri: mapped.chatUri,
11105
11579
  turnId,
11580
+ startedAtMs: Date.now(),
11106
11581
  clientSeq: dispatchClientSeq(frame),
11107
11582
  cancelled: false,
11108
11583
  stopReason: undefined,
11109
- finishing: false,
11110
- renewalTimer: undefined
11584
+ finishing: false
11111
11585
  };
11112
11586
  const seen = this.#dispatched.get(key) ?? new Set;
11113
11587
  seen.add(attemptKey(meta.deliveryId, turnId));
@@ -11131,57 +11605,127 @@ class WakePipe {
11131
11605
  await this.#next(active);
11132
11606
  return;
11133
11607
  }
11134
- this.#scheduleRenewal(active, expiresAtMs);
11135
11608
  if (!this.#subscribed.has(mapped.chatUri)) {
11136
11609
  this.#subscribed.add(mapped.chatUri);
11137
11610
  this.peer.request("subscribe", { channel: mapped.chatUri }, REQUEST_TIMEOUT_MS);
11138
11611
  }
11139
11612
  this.peer.notify("dispatchAction", { ...frame.params, clientSeq: ++this.#seq });
11140
11613
  }
11141
- #stopRenewal(turn) {
11142
- clearTimeout(turn.renewalTimer);
11143
- turn.renewalTimer = undefined;
11614
+ #activeForChat(sessionId, chatId) {
11615
+ return [...this.#active.values()].filter((turn) => turn.sessionUri === sessionId && turn.chatUri === chatId);
11616
+ }
11617
+ #sessionSummaryChanged(params) {
11618
+ this.#sessionSummaryChangedNarrowed(params);
11144
11619
  }
11145
- #scheduleRenewal(turn, expiresAtMs) {
11146
- const remaining = expiresAtMs - Date.now();
11147
- if (!Number.isFinite(remaining) || remaining <= 0)
11620
+ #serverStateChanged(sessionUri, action) {
11621
+ const server = this.#toolsServerOf(sessionUri);
11622
+ if (server === undefined || action.id !== server.customizationId)
11623
+ return;
11624
+ if (sessionUri === "" || this.agentMemberOf(sessionUri) === undefined)
11625
+ return;
11626
+ const state = isRecord(action.state) ? action.state : undefined;
11627
+ if (state?.kind !== "authRequired" || state.reason !== "expired")
11148
11628
  return;
11149
- turn.renewalTimer = setTimeout(() => void this.#renewToken(turn, expiresAtMs), Math.max(1, remaining - Math.min(60000, remaining / 2)));
11150
- turn.renewalTimer.unref?.();
11629
+ this.cloud.authRequired({ channel: sessionUri, resource: server.resource, reason: "expired" });
11151
11630
  }
11152
- async#renewToken(turn, previousExpiry) {
11153
- turn.renewalTimer = undefined;
11154
- const context = { sessionId: turn.sessionUri, chatId: turn.chatUri, turnId: turn.turnId, deliveryId: turn.deliveryId, workspaceId: turn.workspaceId };
11155
- if (this.#active.get(turn.key) !== turn || !this.resolveToolToken(context).ok)
11631
+ #toolsServerOf(sessionUri) {
11632
+ const host = this.options.hostTools;
11633
+ if (host === undefined)
11156
11634
  return;
11157
- try {
11158
- const result = await this.cloud.renewToken({ workspaceId: turn.workspaceId, deliveryId: turn.deliveryId, chatId: turn.chatUri, turnId: turn.turnId });
11159
- if (this.#active.get(turn.key) !== turn)
11160
- return this.#renewalError(turn, "TOKEN_RENEWAL_STALE");
11161
- if (result === null || typeof result !== "object" || Array.isArray(result) || Object.keys(result).sort().join(",") !== "agentToken,deliveryId,turnId")
11162
- return this.#renewalError(turn, "TOKEN_RENEWAL_INVALID");
11163
- const answer = result;
11164
- if (answer.deliveryId !== turn.deliveryId || answer.turnId !== turn.turnId || typeof answer.agentToken !== "string" || answer.agentToken === "") {
11165
- return this.#renewalError(turn, "TOKEN_RENEWAL_INVALID");
11166
- }
11167
- const expiresAtMs = this.options.tokenExpiresAt(answer.agentToken);
11168
- if (expiresAtMs === undefined || !Number.isFinite(expiresAtMs) || expiresAtMs <= previousExpiry || expiresAtMs <= Date.now()) {
11169
- return this.#renewalError(turn, "TOKEN_RENEWAL_INVALID");
11170
- }
11171
- if (!this.vault.renewActiveTurn(context, answer.agentToken, expiresAtMs))
11172
- return this.#renewalError(turn, "TOKEN_RENEWAL_STALE");
11173
- this.#scheduleRenewal(turn, expiresAtMs);
11174
- } catch {
11175
- this.#renewalError(turn, "TOKEN_RENEWAL_FAILED");
11176
- }
11635
+ const customizationId = this.#toolsIds.get(sessionUri);
11636
+ return customizationId === undefined ? undefined : { resource: host.resource, customizationId };
11177
11637
  }
11178
- #renewalError(turn, code) {
11179
- this.options.log.error(`hightea-pipe: ${code} ${JSON.stringify({ workspaceId: turn.workspaceId, deliveryId: turn.deliveryId, turnId: turn.turnId })}`);
11638
+ #rememberToolsServer(sessionUri, customizations) {
11639
+ const host = this.options.hostTools;
11640
+ if (host === undefined || !Array.isArray(customizations))
11641
+ return;
11642
+ const ours = customizations.find((one) => isRecord(one) && one.type === "mcpServer" && one.name === host.name);
11643
+ const id = ours !== undefined && typeof ours.id === "string" && ours.id !== "" ? ours.id : undefined;
11644
+ if (id === undefined)
11645
+ this.#toolsIds.delete(sessionUri);
11646
+ else
11647
+ this.#toolsIds.set(sessionUri, id);
11648
+ if (id === undefined)
11649
+ this.#toolsAnswers.set(sessionUri, { available: false, reason: "its backend published no Hightea MCP server" });
11650
+ else
11651
+ this.#toolsAnswers.set(sessionUri, { available: true });
11180
11652
  }
11181
- #activeForChat(sessionId, chatId) {
11182
- return [...this.#active.values()].filter((turn) => turn.sessionUri === sessionId && turn.chatUri === chatId);
11653
+ #rememberPublishedToolsAnswer(sessionUri, state) {
11654
+ if (this.options.hostTools === undefined)
11655
+ return;
11656
+ const raw = isRecord(state) ? isRecord(state["_meta"]) ? state["_meta"] : state : undefined;
11657
+ const published = HostToolsAnswerSchema.safeParse(raw?.[AHPD_HOST_TOOLS_KEY]);
11658
+ if (published.success)
11659
+ this.#toolsAnswers.set(sessionUri, published.data);
11660
+ }
11661
+ #announceToolsServer(sessionUri) {
11662
+ const member = this.agentMemberOf(sessionUri);
11663
+ const answer = this.#toolsAnswers.get(sessionUri);
11664
+ if (member === undefined || answer === undefined)
11665
+ return;
11666
+ const server = this.#toolsServerOf(sessionUri);
11667
+ const hostTools = {
11668
+ available: answer.available,
11669
+ ...answer.reason === undefined ? {} : { reason: answer.reason },
11670
+ ...answer.available && server !== undefined ? { server } : {}
11671
+ };
11672
+ this.cloud.sessionChanged({
11673
+ channel: "ahp-root://",
11674
+ session: sessionUri,
11675
+ changes: { _meta: { "hh/agentMemberId": member, "hh/hostTools": hostTools } }
11676
+ });
11677
+ }
11678
+ #sessionSummaryChangedNarrowed(params) {
11679
+ if (!isRecord(params)) {
11680
+ this.options.log.error("hightea-pipe: a root/sessionSummaryChanged carries no params object");
11681
+ return;
11682
+ }
11683
+ const sessionUri = params.session;
11684
+ if (typeof sessionUri !== "string" || sessionUri === "") {
11685
+ this.options.log.error("hightea-pipe: a root/sessionSummaryChanged names no session");
11686
+ return;
11687
+ }
11688
+ const member = this.agentMemberOf(sessionUri);
11689
+ if (member === undefined)
11690
+ return;
11691
+ const changes = isRecord(params.changes) ? params.changes : undefined;
11692
+ const changed = changes !== undefined && isRecord(changes._meta) ? changes._meta : undefined;
11693
+ const narrowed = narrowSessionMeta(changed, member, this.#toolsServerOf(sessionUri));
11694
+ if (narrowed === undefined) {
11695
+ this.options.log.error(`hightea-pipe: ${sessionUri} changed under another member's name; nothing was sent`);
11696
+ return;
11697
+ }
11698
+ const hostTools = narrowed["hh/hostTools"];
11699
+ if (hostTools === undefined) {
11700
+ if (changed?.[AHPD_HOST_TOOLS_KEY] !== undefined) {
11701
+ this.options.log.error(`hightea-pipe: ${sessionUri} changed ${AHPD_HOST_TOOLS_KEY} to a shape this host does not read`);
11702
+ }
11703
+ return;
11704
+ }
11705
+ this.#toolsAnswers.set(sessionUri, hostTools);
11706
+ this.cloud.sessionChanged({
11707
+ channel: "ahp-root://",
11708
+ session: sessionUri,
11709
+ changes: { _meta: { "hh/agentMemberId": narrowed["hh/agentMemberId"], "hh/hostTools": hostTools } }
11710
+ });
11183
11711
  }
11184
11712
  async#fromHost(message) {
11713
+ const stateParams = message?.params;
11714
+ if (stateParams?.action?.type === "session/customizationsChanged") {
11715
+ if (typeof stateParams.channel === "string" && this.agentMemberOf(stateParams.channel) !== undefined) {
11716
+ const before = this.#toolsIds.get(stateParams.channel);
11717
+ this.#rememberToolsServer(stateParams.channel, stateParams.action.customizations);
11718
+ if (this.#toolsIds.get(stateParams.channel) !== before)
11719
+ this.#announceToolsServer(stateParams.channel);
11720
+ }
11721
+ return;
11722
+ }
11723
+ if (stateParams?.action?.type === "session/mcpServerStateChanged") {
11724
+ this.#serverStateChanged(typeof stateParams.channel === "string" ? stateParams.channel : "", stateParams.action);
11725
+ return;
11726
+ }
11727
+ if (isRecord(message) && message.method === "root/sessionSummaryChanged")
11728
+ return this.#sessionSummaryChanged(message.params);
11185
11729
  const params = message?.params;
11186
11730
  const action = params?.action;
11187
11731
  if (action === undefined || typeof params?.channel !== "string")
@@ -11218,12 +11762,10 @@ class WakePipe {
11218
11762
  turn.stopStatusCode = malformedApproval ? "INPUT_REQUEST_UNATTRIBUTED" : turn.stopReason;
11219
11763
  if (malformedApproval)
11220
11764
  turn.stopDetail = `INPUT_REQUEST_UNATTRIBUTED:${requestId}`.slice(0, 256);
11221
- this.vault.clearTurn(turn.sessionUri, turn.turnId);
11222
- this.#stopRenewal(turn);
11223
11765
  this.peer.notify("dispatchAction", {
11224
11766
  channel: turn.chatUri,
11225
11767
  clientSeq: ++this.#seq,
11226
- action: { type: "chat/turnCancelled", turnId: turn.turnId }
11768
+ action: { type: "chat/turnCancelled", turnId: turn.turnId, duration: Math.max(0, Date.now() - turn.startedAtMs) }
11227
11769
  });
11228
11770
  return;
11229
11771
  }
@@ -11242,14 +11784,13 @@ class WakePipe {
11242
11784
  if (action.type === "chat/turnStarted") {
11243
11785
  if (turn.stopReason !== undefined)
11244
11786
  return;
11245
- await this.#status({ event: "chat/turnStarted", ...base, turnState: "running", statusCode: "TURN_RUNNING" });
11787
+ await this.#status({ event: "chat/turnStarted", ...base, turnState: "running", statusCode: "TURN_RUNNING" }, turn.startedAtMs);
11246
11788
  } else if (action.type === "chat/turnComplete" || action.type === "chat/turnCancelled" || action.type === "chat/error") {
11247
11789
  turn.finishing = true;
11248
11790
  const finished = action.type === "chat/turnComplete" && turn.stopReason === undefined;
11249
- const errorCode = turn.stopReason ?? "OPERATION_SHAPE_INVALID";
11250
- const statusCode = turn.stopStatusCode ?? turn.stopReason ?? "TURN_ENDED";
11251
- this.#stopRenewal(turn);
11252
- this.vault.clearTurn(turn.sessionUri, turn.turnId);
11791
+ const cancelled = action.type === "chat/turnCancelled" && turn.stopReason === undefined;
11792
+ const errorCode = turn.stopReason ?? (cancelled ? "TURN_CANCELLED" : "OPERATION_SHAPE_INVALID");
11793
+ const statusCode = turn.stopStatusCode ?? turn.stopReason ?? (cancelled ? "TURN_CANCELLED" : "TURN_ENDED");
11253
11794
  await this.#status(finished ? { event: "chat/turnComplete", ...base, turnState: "finished", statusCode: "TURN_FINISHED" } : {
11254
11795
  event: "x-hh/turnFailed",
11255
11796
  ...base,
@@ -11257,7 +11798,7 @@ class WakePipe {
11257
11798
  statusCode,
11258
11799
  errorCode,
11259
11800
  ...turn.stopDetail === undefined ? {} : { errorDetail: turn.stopDetail }
11260
- });
11801
+ }, turn.startedAtMs);
11261
11802
  this.#active.delete(turn.key);
11262
11803
  await this.#next(turn);
11263
11804
  }
@@ -11272,18 +11813,24 @@ class WakePipe {
11272
11813
  this.#subscribed.delete(done.sessionUri);
11273
11814
  this.peer.notify("unsubscribe", { channel: done.chatUri });
11274
11815
  this.peer.notify("unsubscribe", { channel: done.sessionUri });
11816
+ this.#live.delete(done.sessionUri);
11275
11817
  return;
11276
11818
  }
11277
- const expiresAtMs = this.options.tokenExpiresAt(next.token);
11278
- if (expiresAtMs !== undefined && expiresAtMs > Date.now()) {
11819
+ const newestTrigger = newestTriggerMs(next.meta);
11820
+ const unmeasurable = newestTrigger === undefined && next.meta.readBearer === undefined;
11821
+ const stale = newestTrigger !== undefined && Date.now() - newestTrigger > ASK_FRESH_MS;
11822
+ if (!stale && !unmeasurable) {
11279
11823
  try {
11280
- await this.#dispatch(done.key, next.frame, next.meta, next.token, next.turnId);
11824
+ await this.#dispatch(done.key, next.frame, next.meta, next.turnId);
11281
11825
  return;
11282
11826
  } catch (error) {
11283
11827
  if (this.#storeError !== undefined)
11284
11828
  throw error;
11285
11829
  }
11286
11830
  }
11831
+ if (stale || unmeasurable) {
11832
+ this.options.log.error(`ahp-host: queued wake ${next.meta.deliveryId} retired before dispatch (${newestTrigger === undefined ? "ASK_UNSIGNED: no signed triggering envelope and no bearer" : `ASK_STALE: newest trigger signed at ${new Date(newestTrigger).toISOString()}`})`);
11833
+ }
11287
11834
  const session = this.#sessions.get(done.key);
11288
11835
  await this.#status({
11289
11836
  event: "x-hh/turnFailed",
@@ -11295,21 +11842,29 @@ class WakePipe {
11295
11842
  turnId: next.turnId,
11296
11843
  turnState: "error",
11297
11844
  statusCode: "QUEUED_WAKE_NOT_RUN",
11298
- errorCode: "TOKEN_EXPIRED_OR_REVOKED"
11845
+ errorCode: unmeasurable ? "ASK_UNSIGNED" : "ASK_STALE"
11299
11846
  });
11300
11847
  await this.#next(done);
11301
11848
  }
11302
- #status(frame) {
11849
+ #status(frame, startedAtMs) {
11303
11850
  const checked = parseHostToCloudFrame(frame);
11304
11851
  this.#lastStatus.set(checked.turnId === undefined ? checked.deliveryId : attemptKey(checked.deliveryId, checked.turnId), checked);
11305
11852
  if (this.options.store === undefined) {
11306
- this.cloud.status(checked);
11853
+ this.#send(checked, startedAtMs);
11307
11854
  return Promise.resolve();
11308
11855
  }
11309
11856
  return this.#save().then(() => {
11310
- this.cloud.status(checked);
11857
+ this.#send(checked, startedAtMs);
11311
11858
  });
11312
11859
  }
11860
+ #send(frame, startedAtMs) {
11861
+ if (!this.#actionsFromGateway)
11862
+ return this.cloud.status(frame);
11863
+ this.cloud.action(forwardedAction(frame, {
11864
+ ...this.#gatewayClientId === "" ? {} : { clientId: this.#gatewayClientId },
11865
+ ...startedAtMs === undefined ? {} : { startedAtMs }
11866
+ }));
11867
+ }
11313
11868
  }
11314
11869
 
11315
11870
  // ../ahp-host/src/records-store.ts
@@ -11322,8 +11877,47 @@ var mappingSchema = object({
11322
11877
  sessionUri: string2().regex(SESSION_URI)
11323
11878
  }).strict();
11324
11879
  var mappingId = (key) => `session-${createHash2("sha256").update(key).digest("hex").slice(0, 32)}`;
11325
- function recordsPipeStore(records, owner, sessionOwner) {
11880
+ var chatSchema = object({
11881
+ id: string2(),
11882
+ version: literal(1),
11883
+ tuple: tupleSchema,
11884
+ sessionUri: string2().regex(SESSION_URI),
11885
+ chatUri: string2().min(1)
11886
+ }).strict();
11887
+ var chatId = (key) => `chat-${createHash2("sha256").update(key).digest("hex").slice(0, 32)}`;
11888
+ function recordsPipeStore(records, owner, sessionOwner, log, chats) {
11326
11889
  const known = new Map;
11890
+ const keptChats = new Map;
11891
+ const keepChat = async (key, session) => {
11892
+ if (chats === undefined || session.chatUri === undefined || keptChats.get(key) === session.chatUri)
11893
+ return;
11894
+ const tuple2 = tupleSchema.parse(JSON.parse(key));
11895
+ const id = chatId(key);
11896
+ try {
11897
+ await chats.put({ id, version: 1, tuple: tuple2, sessionUri: session.sessionUri, chatUri: session.chatUri }, { createOnly: true });
11898
+ } catch (error) {
11899
+ if (error?.code !== -32010)
11900
+ throw error;
11901
+ const actual = chatSchema.safeParse(await chats.get(id));
11902
+ if (!actual.success || actual.data.sessionUri !== session.sessionUri || actual.data.chatUri !== session.chatUri) {
11903
+ throw new Error("ahp-host: conflicting durable session chat", { cause: error });
11904
+ }
11905
+ }
11906
+ keptChats.set(key, session.chatUri);
11907
+ };
11908
+ const readChats = async () => {
11909
+ const read = new Map;
11910
+ for (const raw of await chats?.list() ?? []) {
11911
+ const parsed = chatSchema.safeParse(raw);
11912
+ if (!parsed.success)
11913
+ throw new Error("ahp-host: invalid durable session chat");
11914
+ const key = JSON.stringify(parsed.data.tuple);
11915
+ if (parsed.data.id !== chatId(key))
11916
+ throw new Error("ahp-host: durable session chat has a different key");
11917
+ read.set(key, { sessionUri: parsed.data.sessionUri, chatUri: parsed.data.chatUri });
11918
+ }
11919
+ return read;
11920
+ };
11327
11921
  const readMapping = (raw) => {
11328
11922
  const parsed = mappingSchema.safeParse(raw);
11329
11923
  if (!parsed.success)
@@ -11382,13 +11976,10 @@ function recordsPipeStore(records, owner, sessionOwner) {
11382
11976
  throw new Error("ahp-host: invalid durable state record");
11383
11977
  }
11384
11978
  const raw = record.version === 1 ? record.state : typeof record.state === "object" && record.state !== null ? { sessions: [], ...record.state } : record.state;
11385
- const parsed = PipeStateSchema.safeParse(raw);
11386
- if (!parsed.success || record.version === 2 && parsed.data.sessions.length !== 0)
11387
- throw new Error("ahp-host: invalid durable state");
11388
- state = { ...parsed.data, sessions: parsed.data.sessions.map(([key, session]) => [key, {
11389
- sessionUri: session.sessionUri,
11390
- ...session.chatUri === undefined ? {} : { chatUri: session.chatUri }
11391
- }]) };
11979
+ const read = readPipeState(raw, log);
11980
+ if (record.version === 2 && read.sessions.length !== 0)
11981
+ throw new Error("ahp-host: invalid durable state: a version 2 record holds no session mappings");
11982
+ state = read;
11392
11983
  }
11393
11984
  const mappings = new Map;
11394
11985
  for (const raw of await records.list()) {
@@ -11412,11 +12003,22 @@ function recordsPipeStore(records, owner, sessionOwner) {
11412
12003
  }
11413
12004
  if (record?.version === 1)
11414
12005
  await saveAttempts(state);
12006
+ keptChats.clear();
12007
+ for (const [key, chat] of await readChats()) {
12008
+ const session = mappings.get(key);
12009
+ if (session === undefined || session.sessionUri !== chat.sessionUri) {
12010
+ throw new Error("ahp-host: durable session chat names no mapping or a different session");
12011
+ }
12012
+ mappings.set(key, { sessionUri: session.sessionUri, chatUri: chat.chatUri });
12013
+ keptChats.set(key, chat.chatUri);
12014
+ }
11415
12015
  return { sessions: [...mappings], dispatched: state.dispatched, lastStatus: state.lastStatus };
11416
12016
  },
11417
12017
  save: async (state) => {
11418
- for (const [key, session] of state.sessions)
12018
+ for (const [key, session] of state.sessions) {
11419
12019
  await publish(key, session);
12020
+ await keepChat(key, session);
12021
+ }
11420
12022
  await saveAttempts(state);
11421
12023
  }
11422
12024
  };
@@ -11425,6 +12027,12 @@ function recordsPipeStore(records, owner, sessionOwner) {
11425
12027
  // ../ahp-host/src/link.ts
11426
12028
  import { randomUUID } from "node:crypto";
11427
12029
  var REQUEST_TIMEOUT_MS2 = 15000;
12030
+ var boundedReason = (error) => {
12031
+ if (error === null || typeof error !== "object")
12032
+ return;
12033
+ const message = error.message;
12034
+ return typeof message === "string" && BOUNDED_ERROR_CODES.includes(message) ? message : undefined;
12035
+ };
11428
12036
  function createCloudLink(options) {
11429
12037
  const { log, receive } = options;
11430
12038
  let stopped = false;
@@ -11497,8 +12105,9 @@ function createCloudLink(options) {
11497
12105
  if (response.jsonrpc === "2.0" && "result" in response && !("error" in response)) {
11498
12106
  entry.resolve(response.result);
11499
12107
  } else {
11500
- log.error("hightea-pipe: CONTROL_REQUEST_REFUSED");
11501
- entry.reject(new Error("CONTROL_REQUEST_REFUSED"));
12108
+ const reason = "error" in response ? boundedReason(response.error) : undefined;
12109
+ log.error(`hightea-pipe: CONTROL_REQUEST_REFUSED${reason === undefined ? "" : ` ${reason}`}`);
12110
+ entry.reject(new Error(reason === undefined ? "CONTROL_REQUEST_REFUSED" : `CONTROL_REQUEST_REFUSED ${reason}`));
11502
12111
  }
11503
12112
  return;
11504
12113
  }
@@ -11528,10 +12137,10 @@ function createCloudLink(options) {
11528
12137
  closeSocket(connection.socket);
11529
12138
  schedule();
11530
12139
  };
11531
- const refused = (code) => {
12140
+ const refused = (code, reason) => {
11532
12141
  if (stopped || current !== connection)
11533
12142
  return;
11534
- log.error(`hightea-pipe: CONTROL_SOCKET_REFUSED:${code}`);
12143
+ log.error(`${reason === undefined || reason === "" ? `hightea-pipe: CONTROL_SOCKET_REFUSED:${code}` : `hightea-pipe: CONTROL_SOCKET_REFUSED:${code}: ${reason}`}`);
11535
12144
  close();
11536
12145
  };
11537
12146
  try {
@@ -11552,8 +12161,8 @@ function createCloudLink(options) {
11552
12161
  });
11553
12162
  socket.addEventListener("error", () => lost("CONTROL_SOCKET_ERROR"));
11554
12163
  socket.addEventListener("close", (event) => {
11555
- if (event.code === 4003)
11556
- refused(4003);
12164
+ if (event.code === 4003 || event.code === 4004)
12165
+ refused(event.code, event.reason);
11557
12166
  else
11558
12167
  lost("CONTROL_SOCKET_CLOSED");
11559
12168
  });
@@ -11593,7 +12202,9 @@ function createCloudLink(options) {
11593
12202
  answer: (id, outcome) => send(outcome.ok ? { jsonrpc: "2.0", id, result: null } : { jsonrpc: "2.0", id, error: { code: -32000, message: outcome.code } }),
11594
12203
  reply: (id, answer) => send("result" in answer ? { jsonrpc: "2.0", id, result: answer.result } : { jsonrpc: "2.0", id, error: answer.error }),
11595
12204
  status: (frame) => send({ jsonrpc: "2.0", method: "x-hightea/status", params: frame }),
11596
- renewToken: (params) => request(`renew:${randomUUID()}`, "x-hightea/renewToken", { channel: "ahp-root://", ...params }),
12205
+ sessionChanged: (change) => void send({ jsonrpc: "2.0", method: "root/sessionSummaryChanged", params: change }),
12206
+ action: (params) => send({ jsonrpc: "2.0", method: "action", params }),
12207
+ authRequired: (params) => send({ jsonrpc: "2.0", method: "auth/required", params }),
11597
12208
  sourcePush: (params) => request(`push:${randomUUID()}`, "x-hightea/source/push", params),
11598
12209
  hostRequestAnswer: (id, outcome) => void send({ jsonrpc: "2.0", id, ...hostAnswerFrame(outcome) })
11599
12210
  };
@@ -11601,15 +12212,187 @@ function createCloudLink(options) {
11601
12212
 
11602
12213
  // ../ahp-host/src/km-source.ts
11603
12214
  import { spawn as spawn2 } from "node:child_process";
11604
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
12215
+ import { createHash as createHash3 } from "node:crypto";
11605
12216
  import { createInterface as createInterface2 } from "node:readline";
11606
12217
 
12218
+ // ../ahp-host/src/push-shell.ts
12219
+ import { randomUUID as randomUUID2 } from "node:crypto";
12220
+ var UNACKED_MAX = 1e4;
12221
+ var PUSH_FRAME_HEADROOM_BYTES = 1024;
12222
+ function planPushBatch(queue, envelopeBytes, budget) {
12223
+ let head = 0;
12224
+ while (head < queue.length && envelopeBytes + sourceFrameBytes(queue[head]) > budget)
12225
+ head++;
12226
+ const batch = [];
12227
+ let bytes = envelopeBytes;
12228
+ for (let index = head;index < queue.length; index++) {
12229
+ const one = queue[index];
12230
+ const size = sourceFrameBytes(one) + (batch.length === 0 ? 0 : 1);
12231
+ if (batch.length > 0 && bytes + size > budget)
12232
+ break;
12233
+ batch.push(one);
12234
+ bytes += size;
12235
+ }
12236
+ return { dropped: queue.slice(0, head), batch };
12237
+ }
12238
+
12239
+ class PushShell {
12240
+ sourceId;
12241
+ #epoch = "e_" + randomUUID2();
12242
+ #ordinal = 0n;
12243
+ #queue = [];
12244
+ #inFlight = false;
12245
+ #pushTimer;
12246
+ #lastPushAt = -Infinity;
12247
+ #pushFailures = 0;
12248
+ #retryAt = -Infinity;
12249
+ #watching = true;
12250
+ #stop = new AbortController;
12251
+ #o;
12252
+ #coalesce;
12253
+ #now;
12254
+ #unackedMax;
12255
+ constructor(options) {
12256
+ this.#o = options;
12257
+ this.sourceId = options.sourceId;
12258
+ this.#coalesce = options.coalesceMs ?? 2000;
12259
+ this.#now = options.now ?? Date.now;
12260
+ this.#unackedMax = options.unackedMax ?? UNACKED_MAX;
12261
+ }
12262
+ get epoch() {
12263
+ return this.#epoch;
12264
+ }
12265
+ get ordinal() {
12266
+ return this.#ordinal;
12267
+ }
12268
+ get watching() {
12269
+ return this.#watching;
12270
+ }
12271
+ get unacknowledged() {
12272
+ return this.#queue.length;
12273
+ }
12274
+ get stopped() {
12275
+ return this.#stop.signal.aborted;
12276
+ }
12277
+ #next() {
12278
+ this.#ordinal++;
12279
+ return { epoch: this.#epoch, ordinal: String(this.#ordinal) };
12280
+ }
12281
+ next() {
12282
+ return this.#next();
12283
+ }
12284
+ watch(on) {
12285
+ this.#watching = on;
12286
+ if (!on) {
12287
+ if (this.#pushTimer !== undefined) {
12288
+ clearTimeout(this.#pushTimer);
12289
+ this.#pushTimer = undefined;
12290
+ }
12291
+ return;
12292
+ }
12293
+ this.#pump();
12294
+ }
12295
+ enqueue(observations) {
12296
+ this.#queue.push(...observations);
12297
+ if (this.#queue.length > this.#unackedMax) {
12298
+ this.#o.log.error(`hightea-source: ${this.sourceId} has more than ${this.#unackedMax} unacknowledged observations; starting a new epoch`);
12299
+ this.#queue.length = 0;
12300
+ this.#epoch = "e_" + randomUUID2();
12301
+ this.#ordinal = 0n;
12302
+ this.#o.onOverflow();
12303
+ return;
12304
+ }
12305
+ this.#pump();
12306
+ }
12307
+ #pump() {
12308
+ if (!this.#watching || this.#inFlight || this.#queue.length === 0 || this.#pushTimer !== undefined || this.#stop.signal.aborted)
12309
+ return;
12310
+ const retryIn = this.#retryAt - this.#now();
12311
+ if (retryIn > 0) {
12312
+ this.#pushTimer = setTimeout(() => {
12313
+ this.#pushTimer = undefined;
12314
+ this.#pump();
12315
+ }, retryIn);
12316
+ return;
12317
+ }
12318
+ const wait = this.#lastPushAt + this.#coalesce - this.#now();
12319
+ if (wait > 0) {
12320
+ this.#pushTimer = setTimeout(() => {
12321
+ this.#pushTimer = undefined;
12322
+ this.#pump();
12323
+ }, wait);
12324
+ return;
12325
+ }
12326
+ const budget = SOURCE_FRAME_MAX_BYTES - PUSH_FRAME_HEADROOM_BYTES;
12327
+ const envelopeBytes = sourceFrameBytes({
12328
+ workspaceId: this.#o.workspaceId,
12329
+ sourceId: this.sourceId,
12330
+ hostId: this.#o.hostId,
12331
+ position: { epoch: this.#epoch, ordinal: "0" },
12332
+ observations: []
12333
+ });
12334
+ const { dropped, batch } = planPushBatch(this.#queue, envelopeBytes, budget);
12335
+ if (dropped.length > 0) {
12336
+ this.#queue.splice(0, dropped.length);
12337
+ for (const one of dropped) {
12338
+ this.#o.onOmit?.(one.change.op === "upsert" ? one.change.row.address : one.change.address, `${sourceFrameBytes(one)} bytes cannot fit a ${budget}-byte push frame even alone; a later change to that row is what reports it`);
12339
+ }
12340
+ }
12341
+ if (batch.length === 0)
12342
+ return;
12343
+ const last = batch[batch.length - 1];
12344
+ const epoch = this.#epoch;
12345
+ this.#inFlight = true;
12346
+ this.#lastPushAt = this.#now();
12347
+ this.#o.push({ workspaceId: this.#o.workspaceId, sourceId: this.sourceId, hostId: this.#o.hostId, position: last.position, observations: batch }).then((answer) => {
12348
+ if (this.#pushFailures > 0) {
12349
+ this.#o.log.info?.(`hightea-source: a push of ${this.sourceId} is answered again after ${this.#pushFailures} refusal(s)`);
12350
+ this.#pushFailures = 0;
12351
+ this.#retryAt = -Infinity;
12352
+ }
12353
+ const ack = SourceAckSchema.safeParse(answer);
12354
+ if (!ack.success) {
12355
+ this.#o.log.error(`hightea-source: the workspace answered a push of ${this.sourceId} outside its schema`);
12356
+ return;
12357
+ }
12358
+ const applied = ack.data.applied;
12359
+ if (applied === null || applied.epoch !== epoch || applied.epoch !== this.#epoch)
12360
+ return;
12361
+ const through = BigInt(applied.ordinal);
12362
+ let retire = 0;
12363
+ while (retire < this.#queue.length && BigInt(this.#queue[retire].position.ordinal) <= through)
12364
+ retire++;
12365
+ this.#queue.splice(0, retire);
12366
+ }, (error) => {
12367
+ this.#pushFailures++;
12368
+ const delay = Math.min(this.#coalesce * 2 ** Math.min(this.#pushFailures - 1, 5), 60000);
12369
+ this.#retryAt = this.#now() + delay;
12370
+ if (this.#pushFailures === 1) {
12371
+ const why = error instanceof Error ? error.message : String(error);
12372
+ this.#o.log.error(`hightea-source: a push of ${this.sourceId} was not answered: ${why}; retrying with backoff, next in ${Math.round(delay / 1000)} s`);
12373
+ }
12374
+ }).finally(() => {
12375
+ this.#inFlight = false;
12376
+ this.#pump();
12377
+ });
12378
+ }
12379
+ stop() {
12380
+ this.#stop.abort();
12381
+ if (this.#pushTimer !== undefined) {
12382
+ clearTimeout(this.#pushTimer);
12383
+ this.#pushTimer = undefined;
12384
+ }
12385
+ }
12386
+ }
12387
+
11607
12388
  // ../ahp-host/src/page-serve.ts
11608
12389
  import { spawn } from "node:child_process";
11609
12390
  import { createInterface } from "node:readline";
11610
12391
  var STDERR_MAX_BYTES = 64 * 1024;
11611
12392
  var KILL_GRACE_MS = 2000;
11612
12393
  var ANSWER_MAX_BYTES = 16 * 1024 * 1024;
12394
+ var ASK_QUEUE_MAX = 8;
12395
+ var ASK_QUEUE_WAIT_MS = 5000;
11613
12396
 
11614
12397
  class PageServeFault extends Error {
11615
12398
  code;
@@ -11639,6 +12422,7 @@ var openPageServe = (argv, signal) => {
11639
12422
  let stderr = "";
11640
12423
  let end;
11641
12424
  let pending;
12425
+ const queue = [];
11642
12426
  let seq = 0;
11643
12427
  let settle = () => {
11644
12428
  return;
@@ -11655,6 +12439,37 @@ var openPageServe = (argv, signal) => {
11655
12439
  clearTimeout(held.timer);
11656
12440
  held.reject(error);
11657
12441
  };
12442
+ function drain() {
12443
+ if (pending !== undefined || queue.length === 0 || end !== undefined)
12444
+ return;
12445
+ const next = queue.shift();
12446
+ if (next.timer !== undefined)
12447
+ clearTimeout(next.timer);
12448
+ begin(next.request, next.timeoutMs, next.resolve, next.reject);
12449
+ }
12450
+ function begin(request, timeoutMs, settleAnswer, failAnswer) {
12451
+ const mine = {
12452
+ seq: ++seq,
12453
+ traverse: "traverse" in request && request.traverse === true,
12454
+ pages: [],
12455
+ bytes: 0,
12456
+ askedAt: Date.now(),
12457
+ deadline: Date.now() + timeoutMs,
12458
+ resolve: settleAnswer,
12459
+ reject: failAnswer,
12460
+ timer: undefined
12461
+ };
12462
+ pending = mine;
12463
+ mine.timer = setTimeout(() => {
12464
+ fault("page-serve-timeout", `the reader did not answer seq ${mine.seq} in ${timeoutMs} ms`);
12465
+ }, timeoutMs);
12466
+ try {
12467
+ child.stdin.write(JSON.stringify({ seq: mine.seq, request }) + `
12468
+ `);
12469
+ } catch (error) {
12470
+ fault("page-serve-write-failed", `the request could not be written: ${error instanceof Error ? error.message : String(error)}`);
12471
+ }
12472
+ }
11658
12473
  const fault = (code, message) => {
11659
12474
  refusePending(new PageServeFault(code, message));
11660
12475
  signalGroup(child, "SIGKILL");
@@ -11693,6 +12508,7 @@ var openPageServe = (argv, signal) => {
11693
12508
  ...typeof refusal.hint === "string" ? { hint: refusal.hint } : {}
11694
12509
  }
11695
12510
  });
12511
+ drain();
11696
12512
  return;
11697
12513
  }
11698
12514
  if (frame.page === undefined && frame.progress !== undefined) {
@@ -11700,6 +12516,7 @@ var openPageServe = (argv, signal) => {
11700
12516
  if (held.timer !== undefined)
11701
12517
  clearTimeout(held.timer);
11702
12518
  held.resolve({ ...rss === undefined ? {} : { rss }, progress: frame.progress });
12519
+ drain();
11703
12520
  return;
11704
12521
  }
11705
12522
  if (frame.page === null || typeof frame.page !== "object" || Array.isArray(frame.page)) {
@@ -11719,6 +12536,7 @@ var openPageServe = (argv, signal) => {
11719
12536
  if (held.timer !== undefined)
11720
12537
  clearTimeout(held.timer);
11721
12538
  held.resolve({ pages: held.pages, ...rss === undefined ? {} : { rss } });
12539
+ drain();
11722
12540
  };
11723
12541
  createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY }).on("line", answer);
11724
12542
  child.stderr.setEncoding("utf8").on("data", (chunk) => {
@@ -11739,6 +12557,11 @@ hightea-page-serve: ${error.message}`;
11739
12557
  signalGroup(child, "SIGKILL");
11740
12558
  end = { code: killed === null ? code : null, stderr };
11741
12559
  refusePending(new PageServeFault("page-serve-reader-exited", `the reader is gone (${pageServeWhy(end)})`));
12560
+ for (const held of queue.splice(0)) {
12561
+ if (held.timer !== undefined)
12562
+ clearTimeout(held.timer);
12563
+ held.reject(new PageServeFault("page-serve-reader-exited", `the reader is gone (${pageServeWhy(end)})`));
12564
+ }
11742
12565
  settle(end);
11743
12566
  resolve();
11744
12567
  });
@@ -11761,21 +12584,34 @@ hightea-page-serve: ${error.message}`;
11761
12584
  return Promise.reject(new PageServeFault("page-serve-reader-exited", `the reader is gone (${pageServeWhy(end)})`));
11762
12585
  }
11763
12586
  if (pending !== undefined) {
11764
- return Promise.reject(new PageServeFault("page-serve-busy", "a page request is already outstanding"));
11765
- }
11766
- const mine = {
11767
- seq: ++seq,
11768
- traverse: "traverse" in request && request.traverse === true,
11769
- pages: [],
11770
- bytes: 0,
11771
- resolve: () => {
12587
+ if (Date.now() >= pending.deadline) {
12588
+ const missed = `the reader did not answer seq ${pending.seq} by its ${pending.deadline - pending.askedAt} ms deadline, and the slot was still held`;
12589
+ fault("page-serve-timeout", missed);
12590
+ return Promise.reject(new PageServeFault("page-serve-timeout", missed));
12591
+ }
12592
+ if (queue.length >= ASK_QUEUE_MAX) {
12593
+ return Promise.reject(new PageServeFault("page-serve-busy", `a page request is already outstanding and ${queue.length} more are waiting`));
12594
+ }
12595
+ const waitMs = Math.min(timeoutMs, ASK_QUEUE_WAIT_MS);
12596
+ const queued = { request, timeoutMs, waitMs, resolve: () => {
11772
12597
  return;
11773
- },
11774
- reject: () => {
12598
+ }, reject: () => {
11775
12599
  return;
11776
- },
11777
- timer: undefined
11778
- };
12600
+ }, timer: undefined };
12601
+ const waited = new Promise((resolve, reject) => {
12602
+ queued.resolve = resolve;
12603
+ queued.reject = reject;
12604
+ });
12605
+ queued.timer = setTimeout(() => {
12606
+ const at = queue.indexOf(queued);
12607
+ if (at < 0)
12608
+ return;
12609
+ queue.splice(at, 1);
12610
+ queued.reject(new PageServeFault("page-serve-busy", `a page request waited ${waitMs} ms for the one slot and seq ${pending === undefined ? "none" : pending.seq} is still unanswered`));
12611
+ }, waitMs);
12612
+ queue.push(queued);
12613
+ return waited;
12614
+ }
11779
12615
  let settleAnswer = () => {
11780
12616
  return;
11781
12617
  };
@@ -11786,18 +12622,7 @@ hightea-page-serve: ${error.message}`;
11786
12622
  settleAnswer = resolve;
11787
12623
  failAnswer = reject;
11788
12624
  });
11789
- mine.resolve = settleAnswer;
11790
- mine.reject = failAnswer;
11791
- pending = mine;
11792
- mine.timer = setTimeout(() => {
11793
- fault("page-serve-timeout", `the reader did not answer seq ${mine.seq} in ${timeoutMs} ms`);
11794
- }, timeoutMs);
11795
- try {
11796
- child.stdin.write(JSON.stringify({ seq: mine.seq, request }) + `
11797
- `);
11798
- } catch (error) {
11799
- fault("page-serve-write-failed", `the request could not be written: ${error instanceof Error ? error.message : String(error)}`);
11800
- }
12625
+ begin(request, timeoutMs, settleAnswer, failAnswer);
11801
12626
  return asked;
11802
12627
  },
11803
12628
  exited,
@@ -11811,7 +12636,6 @@ var GENERATIONS_KEPT = 8;
11811
12636
  var GENERATION_MAX_MS = 15 * 60000;
11812
12637
  var KM_PAGE_LIMIT = 1000;
11813
12638
  var READ_ATTEMPTS = 3;
11814
- var UNACKED_MAX = 1e4;
11815
12639
  var FEED_RESTART_MS = 5000;
11816
12640
  var PAGE_SERVE_RSS_CEILING = 512 * 1024 * 1024;
11817
12641
  var NOTICE_PATIENCE_MS = 30000;
@@ -11845,8 +12669,7 @@ class ListRefused extends Error {
11845
12669
 
11846
12670
  class KmSource {
11847
12671
  sourceId;
11848
- #epoch = "e_" + randomUUID2();
11849
- #ordinal = 0n;
12672
+ #shell;
11850
12673
  #reads = 0;
11851
12674
  #current;
11852
12675
  #kept = new Map;
@@ -11875,14 +12698,8 @@ class KmSource {
11875
12698
  #noHeadSaid = false;
11876
12699
  #dirty = false;
11877
12700
  #pendingChangeAt;
12701
+ #pendingChangeSource;
11878
12702
  #hintTimer;
11879
- #queue = [];
11880
- #inFlight = false;
11881
- #pushTimer;
11882
- #lastPushAt = -Infinity;
11883
- #pushFailures = 0;
11884
- #retryAt = -Infinity;
11885
- #watching = true;
11886
12703
  #watchTimer;
11887
12704
  #watchFloor;
11888
12705
  #watchRefresh;
@@ -11937,9 +12754,31 @@ class KmSource {
11937
12754
  this.#watchRefresh = options.watchRefreshMs;
11938
12755
  this.#now = options.now ?? Date.now;
11939
12756
  this.#native = new Map(Object.entries(options.config.members).map(([member, owner]) => [owner, member]));
12757
+ this.#shell = new PushShell({
12758
+ sourceId: options.config.sourceId,
12759
+ workspaceId: options.workspaceId,
12760
+ hostId: options.hostId,
12761
+ push: (params) => options.push(params),
12762
+ log: options.log,
12763
+ coalesceMs: this.#coalesce,
12764
+ now: this.#now,
12765
+ onOmit: (address, reason) => this.#omit(address, reason),
12766
+ onOverflow: () => {
12767
+ this.#kept.clear();
12768
+ const last = this.#current;
12769
+ if (last === undefined) {
12770
+ options.log.error(`hightea-source: ${options.config.sourceId} overflowed before its first read; reading for the new epoch`);
12771
+ this.#read().catch((error) => options.log.error(`hightea-source: reading ${options.config.sourceId} after an overflow failed: ${describe2(error)}`));
12772
+ return;
12773
+ }
12774
+ this.#current = undefined;
12775
+ const fresh = new Map(last.rows.map((held) => [held.row.address, { key: held.key, row: held.row }]));
12776
+ this.#diff(`${this.#shell.epoch}.${++this.#reads}`, last.snapshot, fresh);
12777
+ }
12778
+ });
11940
12779
  }
11941
12780
  get epoch() {
11942
- return this.#epoch;
12781
+ return this.#shell.epoch;
11943
12782
  }
11944
12783
  start() {
11945
12784
  this.#reader();
@@ -11948,10 +12787,9 @@ class KmSource {
11948
12787
  }
11949
12788
  async stop() {
11950
12789
  this.#stop.abort();
12790
+ this.#shell.stop();
11951
12791
  if (this.#hintTimer !== undefined)
11952
12792
  clearTimeout(this.#hintTimer);
11953
- if (this.#pushTimer !== undefined)
11954
- clearTimeout(this.#pushTimer);
11955
12793
  this.#clearWatchRefresh();
11956
12794
  if (this.#serveTimer !== undefined)
11957
12795
  clearTimeout(this.#serveTimer);
@@ -11964,9 +12802,11 @@ class KmSource {
11964
12802
  hint(line) {
11965
12803
  if (line !== undefined) {
11966
12804
  this.#noteHint(line);
11967
- const atMs = changeAtOf(line);
11968
- if (atMs !== undefined)
11969
- this.#pendingChangeAt = Math.min(this.#pendingChangeAt ?? atMs, atMs);
12805
+ const change = changeOf(line);
12806
+ if (change !== undefined && (this.#pendingChangeAt === undefined || change.at < this.#pendingChangeAt)) {
12807
+ this.#pendingChangeAt = change.at;
12808
+ this.#pendingChangeSource = change.source;
12809
+ }
11970
12810
  }
11971
12811
  if (this.#stop.signal.aborted)
11972
12812
  return;
@@ -11979,7 +12819,7 @@ class KmSource {
11979
12819
  const rested = this.#readEndedAt + Math.max(this.#readTookMs * (1 / this.#duty - 1), floor) - this.#now();
11980
12820
  const delay = Math.max(this.#hintCoalesce, rested);
11981
12821
  const age = this.#pendingChangeAt === undefined ? undefined : this.#now() - this.#pendingChangeAt;
11982
- this.#o.log.info?.(`hightea-source: ${this.sourceId} change hint: last read ${Math.round(this.#readTookMs)} ms at readDuty ${this.#duty}, ${shortFloor ? "incremental" : "full"} floor ${Math.round(floor)} ms, progress ceiling ${Math.round(this.#progressCeiling)} ms, hint window ${Math.round(this.#hintCoalesce)} ms, next read in ${Math.round(delay)} ms, change age ${age === undefined ? "unavailable" : `${Math.round(age)} ms`}`);
12822
+ this.#o.log.info?.(`hightea-source: ${this.sourceId} change hint: last read ${Math.round(this.#readTookMs)} ms at readDuty ${this.#duty}, ${shortFloor ? "incremental" : "full"} floor ${Math.round(floor)} ms, progress ceiling ${Math.round(this.#progressCeiling)} ms, hint window ${Math.round(this.#hintCoalesce)} ms, next read in ${Math.round(delay)} ms, change age ${age === undefined ? "unavailable" : `${Math.round(age)} ms${this.#pendingChangeSource === undefined ? "" : ` from ${this.#pendingChangeSource}`}`}`);
11983
12823
  this.#hintTimer = setTimeout(() => {
11984
12824
  this.#hintTimer = undefined;
11985
12825
  this.#read(shortFloor).catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${describe2(error)}`));
@@ -11995,13 +12835,12 @@ class KmSource {
11995
12835
  try {
11996
12836
  switch (request.op) {
11997
12837
  case "watch":
11998
- this.#watching = request.args.on;
11999
- if (this.#watching) {
12000
- this.#pump();
12838
+ this.#shell.watch(request.args.on);
12839
+ if (request.args.on)
12001
12840
  this.#armWatchRefresh();
12002
- } else
12841
+ else
12003
12842
  this.#clearWatchRefresh();
12004
- return { ...binding, op: "watch", outcome: "applied", body: { on: this.#watching } };
12843
+ return { ...binding, op: "watch", outcome: "applied", body: { on: this.#shell.watching } };
12005
12844
  case "list":
12006
12845
  return { ...binding, op: "list", outcome: "applied", ...this.#degraded ? { code: "SOURCE_READER_RESTARTING" } : {}, body: await this.#page(request.args, binding) };
12007
12846
  case "read": {
@@ -12061,14 +12900,35 @@ class KmSource {
12061
12900
  return page(next, rows);
12062
12901
  }
12063
12902
  async#assign(request, binding) {
12064
- const { address, ownerMemberId, expectedOwner, intentId } = request.args;
12903
+ return this.assign(request.args, binding, request.caller.memberId);
12904
+ }
12905
+ async assign(args, binding, callerMemberId) {
12906
+ const { address, ownerMemberId, expectedOwner, intentId, ifRevision } = args;
12065
12907
  const seat = this.#o.config.members[ownerMemberId];
12066
- const expected = expectedOwner === null ? null : this.#nativeOf(expectedOwner);
12908
+ const expected = expectedOwner === undefined || expectedOwner === null ? null : this.#nativeOf(expectedOwner);
12067
12909
  if (seat === undefined || expected === undefined)
12068
12910
  return { ...binding, op: "assign", outcome: "refused", code: "AGENT_NOT_MAPPED" };
12069
12911
  const key = this.#keyOf(address);
12070
12912
  if (key === undefined)
12071
12913
  return { ...binding, op: "assign", outcome: "refused", code: "INVALID_ADDRESS" };
12914
+ if (ifRevision !== undefined) {
12915
+ const before = await this.#readAfter();
12916
+ const seen = this.#observed(before, address);
12917
+ const revision = seen.change.op === "upsert" ? seen.change.row.version : null;
12918
+ if (revision !== ifRevision) {
12919
+ const held = seen.change.op === "upsert" ? seen.change.row.columns.owner ?? null : null;
12920
+ const current = held === null ? null : this.#nativeOf(held);
12921
+ if (current !== seat) {
12922
+ return {
12923
+ ...binding,
12924
+ op: "assign",
12925
+ outcome: "rejected",
12926
+ code: "STALE_EXPECTATION",
12927
+ body: { intentId, result: { owner: held }, revision, observation: seen }
12928
+ };
12929
+ }
12930
+ }
12931
+ }
12072
12932
  let env;
12073
12933
  if (this.#o.config.serviceIdentity) {
12074
12934
  try {
@@ -12084,7 +12944,7 @@ class KmSource {
12084
12944
  return { ...binding, op: "assign", outcome: "unknown", code };
12085
12945
  }
12086
12946
  }
12087
- const requester = { authority: `hightea:${request.workspaceId}`, subject: request.caller.memberId };
12947
+ const requester = { authority: `hightea:${binding.workspaceId}`, subject: callerMemberId };
12088
12948
  const ran = await this.#yrd([
12089
12949
  "issues",
12090
12950
  "assign",
@@ -12253,6 +13113,7 @@ class KmSource {
12253
13113
  }
12254
13114
  this.#dirty = false;
12255
13115
  this.#pendingChangeAt = undefined;
13116
+ this.#pendingChangeSource = undefined;
12256
13117
  const began = this.#now();
12257
13118
  const reading = this.#readOnce(scheduledAtIncrementalFloor, clientRead, awaitProjection).then((read) => {
12258
13119
  this.#readFailures = 0;
@@ -12293,7 +13154,7 @@ class KmSource {
12293
13154
  return Math.max(this.#watchFloor, 10 * p50);
12294
13155
  }
12295
13156
  #armWatchRefresh() {
12296
- if (this.#stop.signal.aborted || !this.#watching || this.#watchTimer !== undefined)
13157
+ if (this.#stop.signal.aborted || !this.#shell.watching || this.#watchTimer !== undefined)
12297
13158
  return;
12298
13159
  const interval = this.#watchIntervalMs();
12299
13160
  if (!(interval > 0))
@@ -12302,7 +13163,7 @@ class KmSource {
12302
13163
  const wait = Math.max(0, interval - (this.#now() - since));
12303
13164
  this.#watchTimer = setTimeout(() => {
12304
13165
  this.#watchTimer = undefined;
12305
- if (this.#stop.signal.aborted || !this.#watching)
13166
+ if (this.#stop.signal.aborted || !this.#shell.watching)
12306
13167
  return;
12307
13168
  if (this.#reading !== undefined) {
12308
13169
  this.#armWatchRefresh();
@@ -12331,7 +13192,7 @@ class KmSource {
12331
13192
  }
12332
13193
  async#readOnce(atIncrementalFloor, clientRead, awaitProjection = false) {
12333
13194
  for (let attempt = 1;; attempt++) {
12334
- const generation = `${this.#epoch}.${++this.#reads}`;
13195
+ const generation = `${this.#shell.epoch}.${++this.#reads}`;
12335
13196
  try {
12336
13197
  const cursor = this.#cursor;
12337
13198
  if (cursor !== undefined) {
@@ -12405,6 +13266,9 @@ class KmSource {
12405
13266
  this.#wholeReadClearsNotice(result.head);
12406
13267
  return this.#diff(generation, contentRevision(fresh), fresh);
12407
13268
  }
13269
+ #omit(id, reason) {
13270
+ this.#o.log.error(`hightea-source: row ${id} omitted: ${reason}`);
13271
+ }
12408
13272
  #collect(fresh, rows) {
12409
13273
  for (const one of rows) {
12410
13274
  const row = this.#row(one);
@@ -12415,7 +13279,7 @@ class KmSource {
12415
13279
  const value = issue.path.reduce((part, key) => typeof part === "object" && part !== null ? Reflect.get(part, key) : undefined, row);
12416
13280
  return issue.code === "too_big" && typeof value === "string" ? `${field} is ${value.length} chars, cap ${issue.maximum}` : `${field}: ${issue.message}`;
12417
13281
  });
12418
- this.#o.log.error(`hightea-source: row ${one.id} omitted: ${reasons.join("; ")}`);
13282
+ this.#omit(one.id, reasons.join("; "));
12419
13283
  continue;
12420
13284
  }
12421
13285
  if (sourceFrameBytes(row) > SOURCE_PAGE_BUDGET_BYTES)
@@ -12632,7 +13496,14 @@ class KmSource {
12632
13496
  if (extra.in_progress === flag && extra.in_progress_reason === (reason ?? null))
12633
13497
  continue;
12634
13498
  const facts = { id: extra.id, title: row.columns.title, status: row.columns.state, owner, project: row.columns.project, in_progress: flag, in_progress_reason: reason ?? null, updated_at: row.columns.updatedAt, closed_at: extra.closed_at ?? null };
12635
- fresh.set(address, { key: held.key, row: { ...row, version: contentVersion(facts), extra: { ...extra, in_progress: flag, in_progress_reason: reason ?? null } } });
13499
+ const projected = { ...row, version: contentVersion(facts), extra: { ...extra, in_progress: flag, in_progress_reason: reason ?? null } };
13500
+ const bytes = sourceFrameBytes(projected);
13501
+ if (bytes > SOURCE_PAGE_BUDGET_BYTES) {
13502
+ fresh.delete(address);
13503
+ this.#omit(extra.id, `the row is ${bytes} bytes with its progress, over the ${SOURCE_PAGE_BUDGET_BYTES}-byte row cap`);
13504
+ continue;
13505
+ }
13506
+ fresh.set(address, { key: held.key, row: projected });
12636
13507
  }
12637
13508
  if (projection.source === "unreadable")
12638
13509
  this.#o.log.error(`hightea-source: ${this.sourceId}: activity read unavailable; ${unknown} of ${fresh.size} materialized rows have unknown progress`);
@@ -12670,11 +13541,11 @@ class KmSource {
12670
13541
  const now = fresh.get(address);
12671
13542
  const was = last?.byAddress.get(address);
12672
13543
  if (now === undefined) {
12673
- observations.push({ position: this.#next(), change: { op: "delete", address } });
13544
+ observations.push({ position: this.#shell.next(), change: { op: "delete", address } });
12674
13545
  continue;
12675
13546
  }
12676
13547
  if (last !== undefined && (was === undefined || was.row.version !== now.row.version || !sameColumns(was.row, now.row))) {
12677
- const position = this.#next();
13548
+ const position = this.#shell.next();
12678
13549
  observations.push({ position, change: { op: "upsert", row: now.row } });
12679
13550
  byAddress.set(address, { key: now.key, row: now.row, at: BigInt(position.ordinal) });
12680
13551
  } else {
@@ -12683,27 +13554,25 @@ class KmSource {
12683
13554
  }
12684
13555
  if (last === undefined && byAddress.size > 0) {
12685
13556
  const first = byAddress.get(addresses[0]);
12686
- const position = this.#next();
13557
+ const position = this.#shell.next();
12687
13558
  observations.push({ position, change: { op: "upsert", row: first.row } });
12688
13559
  byAddress.set(first.row.address, { ...first, at: BigInt(position.ordinal) });
12689
13560
  }
12690
13561
  return this.#commit(generation, snapshot, observations, byAddress);
12691
13562
  }
12692
13563
  #commit(generation, snapshot, observations, byAddress) {
12693
- const read = { generation, snapshot, base: this.#ordinal, epoch: this.#epoch, rows: [...byAddress.values()], byAddress, at: this.#now() };
13564
+ const read = { generation, snapshot, base: this.#shell.ordinal, epoch: this.#shell.epoch, rows: [...byAddress.values()], byAddress, at: this.#now() };
12694
13565
  this.#current = read;
12695
13566
  this.#kept.set(generation, read);
12696
13567
  for (const [name, kept] of this.#kept) {
12697
13568
  if (this.#kept.size > GENERATIONS_KEPT || this.#now() - kept.at > GENERATION_MAX_MS)
12698
13569
  this.#kept.delete(name);
12699
13570
  }
12700
- this.#enqueue(observations);
13571
+ this.#shell.enqueue(observations);
13572
+ if (observations.length > 0)
13573
+ this.#o.onRecords?.(observations);
12701
13574
  return read;
12702
13575
  }
12703
- #next() {
12704
- this.#ordinal++;
12705
- return { epoch: this.#epoch, ordinal: String(this.#ordinal) };
12706
- }
12707
13576
  #addressOf(one) {
12708
13577
  return `issue:${this.sourceId}/${beadNumberFromPath(one.path) ?? one.id}`;
12709
13578
  }
@@ -12814,84 +13683,6 @@ class KmSource {
12814
13683
  const named = address.slice(prefix.length);
12815
13684
  return beadNumberFromPath(named) === null ? named : undefined;
12816
13685
  }
12817
- #enqueue(observations) {
12818
- this.#queue.push(...observations);
12819
- if (this.#queue.length > UNACKED_MAX) {
12820
- this.#o.log.error(`hightea-source: ${this.sourceId} has more than ${UNACKED_MAX} unacknowledged observations; starting a new epoch`);
12821
- this.#queue.length = 0;
12822
- this.#epoch = "e_" + randomUUID2();
12823
- this.#ordinal = 0n;
12824
- this.#kept.clear();
12825
- const last = this.#current;
12826
- this.#current = undefined;
12827
- const fresh = new Map(last.rows.map((held) => [held.row.address, { key: held.key, row: held.row }]));
12828
- this.#diff(`${this.#epoch}.${++this.#reads}`, last.snapshot, fresh);
12829
- return;
12830
- }
12831
- this.#pump();
12832
- }
12833
- #pump() {
12834
- if (!this.#watching || this.#inFlight || this.#queue.length === 0 || this.#pushTimer !== undefined || this.#stop.signal.aborted)
12835
- return;
12836
- const retryIn = this.#retryAt - this.#now();
12837
- if (retryIn > 0) {
12838
- this.#pushTimer = setTimeout(() => {
12839
- this.#pushTimer = undefined;
12840
- this.#pump();
12841
- }, retryIn);
12842
- return;
12843
- }
12844
- const wait = this.#lastPushAt + this.#coalesce - this.#now();
12845
- if (wait > 0) {
12846
- this.#pushTimer = setTimeout(() => {
12847
- this.#pushTimer = undefined;
12848
- this.#pump();
12849
- }, wait);
12850
- return;
12851
- }
12852
- const batch = [];
12853
- let bytes = 1024;
12854
- for (const one of this.#queue) {
12855
- const size = sourceFrameBytes(one);
12856
- if (batch.length > 0 && bytes + size > SOURCE_FRAME_MAX_BYTES)
12857
- break;
12858
- batch.push(one);
12859
- bytes += size;
12860
- }
12861
- const last = batch[batch.length - 1];
12862
- const epoch = this.#epoch;
12863
- this.#inFlight = true;
12864
- this.#lastPushAt = this.#now();
12865
- this.#o.push({ workspaceId: this.#o.workspaceId, sourceId: this.sourceId, hostId: this.#o.hostId, position: last.position, observations: batch }).then((answer) => {
12866
- if (this.#pushFailures > 0) {
12867
- this.#o.log.info?.(`hightea-source: a push of ${this.sourceId} is answered again after ${this.#pushFailures} refusal(s)`);
12868
- this.#pushFailures = 0;
12869
- this.#retryAt = -Infinity;
12870
- }
12871
- const ack = SourceAckSchema.safeParse(answer);
12872
- if (!ack.success) {
12873
- this.#o.log.error(`hightea-source: the workspace answered a push of ${this.sourceId} outside its schema`);
12874
- return;
12875
- }
12876
- const applied = ack.data.applied;
12877
- if (applied === null || applied.epoch !== epoch || applied.epoch !== this.#epoch)
12878
- return;
12879
- const through = BigInt(applied.ordinal);
12880
- let retire = 0;
12881
- while (retire < this.#queue.length && BigInt(this.#queue[retire].position.ordinal) <= through)
12882
- retire++;
12883
- this.#queue.splice(0, retire);
12884
- }, (error) => {
12885
- this.#pushFailures++;
12886
- const delay = Math.min(this.#coalesce * 2 ** Math.min(this.#pushFailures - 1, 5), 60000);
12887
- this.#retryAt = this.#now() + delay;
12888
- if (this.#pushFailures === 1)
12889
- this.#o.log.error(`hightea-source: a push of ${this.sourceId} was not answered: ${describe2(error)}; retrying with backoff, next in ${Math.round(delay / 1000)} s`);
12890
- }).finally(() => {
12891
- this.#inFlight = false;
12892
- this.#pump();
12893
- });
12894
- }
12895
13686
  async#yrd(args, env) {
12896
13687
  const { config } = this.#o;
12897
13688
  try {
@@ -13253,10 +14044,14 @@ var runChild = (argv, { timeoutMs, signal, env }) => new Promise((resolve, rejec
13253
14044
  resolve({ pid: child.pid, code: killed === null ? code : null, stdout, stderr });
13254
14045
  });
13255
14046
  });
13256
- var changeAtOf = (line) => {
14047
+ var changeOf = (line) => {
13257
14048
  try {
13258
14049
  const record = JSON.parse(line);
13259
- return typeof record.ts === "number" && Number.isFinite(record.ts) ? record.ts : undefined;
14050
+ if (typeof record.ts !== "number" || !Number.isFinite(record.ts))
14051
+ return;
14052
+ if (record.source === "item-history")
14053
+ return;
14054
+ return { at: record.ts, source: typeof record.source === "string" ? record.source : undefined };
13260
14055
  } catch {
13261
14056
  return;
13262
14057
  }
@@ -13305,24 +14100,301 @@ var followChild = (argv, { signal, onLine }) => new Promise((resolve, reject) =>
13305
14100
  });
13306
14101
  });
13307
14102
 
13308
- // ../ahp-host/src/source-channel.ts
13309
- function nearestIssues(issues, depth = 0) {
13310
- return issues.flatMap((issue) => {
13311
- if (depth >= 3 || issue.errors === undefined || issue.errors.length === 0)
13312
- return [issue];
13313
- return issue.errors.map((branch) => nearestIssues(branch, depth + 1)).reduce((best, one) => one.length < best.length ? one : best);
13314
- });
14103
+ // ../ahp-host/src/command-source.ts
14104
+ import { createHash as createHash4 } from "node:crypto";
14105
+ function isCommandSource(config) {
14106
+ return config.kind === "command";
14107
+ }
14108
+ var SCOPE = "all";
14109
+ var DEFAULT_TIMEOUT_MS = 60000;
14110
+ var STDERR_MAX = 400;
14111
+ var describe3 = (error) => error instanceof Error ? error.message : String(error);
14112
+ function firstLine(stderr) {
14113
+ const line = stderr.split(`
14114
+ `).map((one) => one.trim()).find((one) => one !== "") ?? "";
14115
+ return line.length > STDERR_MAX ? `${line.slice(0, STDERR_MAX)}…` : line;
14116
+ }
14117
+ function warn(log, line) {
14118
+ if (typeof log.info === "function")
14119
+ log.info(line);
14120
+ else
14121
+ log.error(line);
13315
14122
  }
13316
- var REQUEST = "x-hightea/source/request";
13317
- function createSourceChannel(options) {
13318
- const { log } = options;
13319
- const refuse = (connection, id, code) => connection.send({ jsonrpc: "2.0", id, error: { code: -32000, message: code } });
13320
- const answer = (connection, id, request, outcome, code) => send(connection, id, request, { workspaceId: request.workspaceId, sourceId: request.sourceId, hostId: request.hostId, op: request.op, outcome, code });
13321
- const send = (connection, id, request, result) => {
13322
- const frame = { jsonrpc: "2.0", id, result };
13323
- if (sourceFrameBytes(frame) > SOURCE_FRAME_MAX_BYTES) {
13324
- log.error(`hightea-source: FRAME_TOO_LARGE for ${request.op} on ${request.sourceId}`);
13325
- return answer(connection, id, request, "unknown", "FRAME_TOO_LARGE");
14123
+
14124
+ class CommandSource {
14125
+ sourceId;
14126
+ #o;
14127
+ #run;
14128
+ #now;
14129
+ #shell;
14130
+ #interval;
14131
+ #timeout;
14132
+ #reads = 0;
14133
+ #current;
14134
+ #reading;
14135
+ #lastFresh = new Map;
14136
+ #timer;
14137
+ #stop = new AbortController;
14138
+ constructor(options) {
14139
+ const { config } = options;
14140
+ if (config.command.length === 0)
14141
+ throw new Error(`the command source ${config.sourceId} declares no command`);
14142
+ if (config.key.trim() === "")
14143
+ throw new Error(`the command source ${config.sourceId} declares an empty key field`);
14144
+ const interval = config.intervalMs;
14145
+ if (!(Number.isFinite(interval) && interval > 0)) {
14146
+ throw new Error(`the command source ${config.sourceId} needs a positive intervalMs, not ${String(interval)}`);
14147
+ }
14148
+ this.#o = options;
14149
+ this.sourceId = config.sourceId;
14150
+ this.#run = options.run ?? runChild;
14151
+ this.#now = options.now ?? Date.now;
14152
+ this.#interval = interval;
14153
+ this.#timeout = options.childTimeoutMs ?? DEFAULT_TIMEOUT_MS;
14154
+ this.#shell = new PushShell({
14155
+ sourceId: config.sourceId,
14156
+ workspaceId: options.workspaceId,
14157
+ hostId: options.hostId,
14158
+ push: (params) => options.push(params),
14159
+ log: options.log,
14160
+ now: this.#now,
14161
+ ...options.coalesceMs === undefined ? {} : { coalesceMs: options.coalesceMs },
14162
+ onOmit: (address, reason) => options.log.error(`hightea-source: ${config.sourceId} row ${address} omitted: ${reason}`),
14163
+ onOverflow: () => this.#republish()
14164
+ });
14165
+ }
14166
+ get epoch() {
14167
+ return this.#shell.epoch;
14168
+ }
14169
+ start() {
14170
+ this.#tick();
14171
+ }
14172
+ async stop() {
14173
+ this.#stop.abort();
14174
+ this.#shell.stop();
14175
+ if (this.#timer !== undefined) {
14176
+ clearTimeout(this.#timer);
14177
+ this.#timer = undefined;
14178
+ }
14179
+ await this.#reading?.catch(() => {
14180
+ return;
14181
+ });
14182
+ }
14183
+ #tick() {
14184
+ if (this.#stop.signal.aborted)
14185
+ return;
14186
+ this.#read().catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} failed; keeping the last good dataset: ${describe3(error)}`)).finally(() => this.#schedule());
14187
+ }
14188
+ #schedule() {
14189
+ if (this.#stop.signal.aborted || this.#timer !== undefined)
14190
+ return;
14191
+ this.#timer = setTimeout(() => {
14192
+ this.#timer = undefined;
14193
+ this.#tick();
14194
+ }, this.#interval);
14195
+ }
14196
+ async#read() {
14197
+ const running = this.#reading;
14198
+ if (running !== undefined)
14199
+ return await running;
14200
+ const reading = this.#readOnce().finally(() => {
14201
+ this.#reading = undefined;
14202
+ });
14203
+ this.#reading = reading;
14204
+ return await reading;
14205
+ }
14206
+ async#readOnce() {
14207
+ const { config } = this.#o;
14208
+ let ran;
14209
+ try {
14210
+ ran = await this.#run(config.command, { timeoutMs: this.#timeout, signal: this.#stop.signal });
14211
+ } catch (error) {
14212
+ throw new Error(`the command ${config.command[0] ?? "(none)"} could not run: ${describe3(error)}`);
14213
+ }
14214
+ if (ran.code !== 0) {
14215
+ throw new Error(`the command exited ${ran.code === null ? "on a signal" : ran.code}${firstLine(ran.stderr) === "" ? "" : `: ${firstLine(ran.stderr)}`}`);
14216
+ }
14217
+ if (ran.stderr.trim() !== "")
14218
+ warn(this.#o.log, `hightea-source: ${this.sourceId} read warned: ${firstLine(ran.stderr)}`);
14219
+ const fresh = this.#parse(ran.stdout);
14220
+ return this.#commit(fresh);
14221
+ }
14222
+ #parse(stdout) {
14223
+ const { key } = this.#o.config;
14224
+ const lines = stdout.split(`
14225
+ `);
14226
+ const fresh = new Map;
14227
+ for (const [index, raw] of lines.entries()) {
14228
+ const line = raw.trim();
14229
+ if (line === "")
14230
+ continue;
14231
+ const at = `line ${index + 1}`;
14232
+ let value;
14233
+ try {
14234
+ value = JSON.parse(line);
14235
+ } catch (error) {
14236
+ throw new Error(`${at} is not JSON: ${describe3(error)}`);
14237
+ }
14238
+ if (value === null || typeof value !== "object" || Array.isArray(value))
14239
+ throw new Error(`${at} is not an object`);
14240
+ const record = value;
14241
+ for (const field of Object.keys(record)) {
14242
+ if (field !== key && field !== "columns" && field !== "extra" && field !== "version") {
14243
+ throw new Error(`${at} carries an unknown field "${field}"; a line is {${key}, columns, extra?, version?}`);
14244
+ }
14245
+ }
14246
+ const address = record[key];
14247
+ if (typeof address !== "string" || address.trim() === "")
14248
+ throw new Error(`${at} has no "${key}"; every row needs an address`);
14249
+ const version = record.version ?? createHash4("sha256").update(JSON.stringify([record.columns ?? null, record.extra ?? null])).digest("hex");
14250
+ if (typeof version !== "string" || version === "")
14251
+ throw new Error(`${at} carries an unusable "version"`);
14252
+ const parsed = SourceRowSchema.safeParse({ address, version, scope: SCOPE, columns: record.columns, extra: record.extra ?? null });
14253
+ if (!parsed.success) {
14254
+ const named = parsed.error.issues.slice(0, 3).map((issue) => `${issue.path.join(".") || "row"}: ${issue.message}`).join("; ");
14255
+ throw new Error(`${at} is not a row: ${named}`);
14256
+ }
14257
+ if (fresh.has(address))
14258
+ throw new Error(`${at} repeats the address ${address}; one line per row`);
14259
+ fresh.set(address, { key: address, row: parsed.data });
14260
+ }
14261
+ return fresh;
14262
+ }
14263
+ #commit(fresh) {
14264
+ const last = this.#current;
14265
+ const byAddress = new Map;
14266
+ const observations = [];
14267
+ const addresses = [...new Set([...fresh.keys(), ...last?.byAddress.keys() ?? []])].sort();
14268
+ for (const address of addresses) {
14269
+ const now = fresh.get(address);
14270
+ const was = last?.byAddress.get(address);
14271
+ if (now === undefined) {
14272
+ observations.push({ position: this.#shell.next(), change: { op: "delete", address } });
14273
+ continue;
14274
+ }
14275
+ if (was === undefined || was.row.version !== now.row.version) {
14276
+ const position = this.#shell.next();
14277
+ observations.push({ position, change: { op: "upsert", row: now.row } });
14278
+ byAddress.set(address, { row: now.row, at: BigInt(position.ordinal) });
14279
+ } else {
14280
+ byAddress.set(address, { row: now.row, at: was.at });
14281
+ }
14282
+ }
14283
+ this.#lastFresh = fresh;
14284
+ const snapshot = {
14285
+ generation: `${this.#shell.epoch}.${++this.#reads}`,
14286
+ epoch: this.#shell.epoch,
14287
+ base: this.#shell.ordinal,
14288
+ rows: [...byAddress.values()],
14289
+ byAddress,
14290
+ at: this.#now()
14291
+ };
14292
+ this.#current = snapshot;
14293
+ this.#shell.enqueue(observations);
14294
+ return snapshot;
14295
+ }
14296
+ #republish() {
14297
+ const rows = this.#lastFresh.size;
14298
+ if (rows > UNACKED_MAX) {
14299
+ this.#o.log.error(`hightea-source: ${this.sourceId} holds ${rows} rows, more than the ${UNACKED_MAX} one push may carry; shorten the command's answer`);
14300
+ return;
14301
+ }
14302
+ this.#current = undefined;
14303
+ if (rows === 0) {
14304
+ this.#read().catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after an overflow failed: ${describe3(error)}`));
14305
+ return;
14306
+ }
14307
+ this.#commit(this.#lastFresh);
14308
+ }
14309
+ async#latest() {
14310
+ return this.#current ?? await this.#read();
14311
+ }
14312
+ #observed(snapshot, address) {
14313
+ const held = snapshot.byAddress.get(address);
14314
+ if (held === undefined)
14315
+ return { position: { epoch: snapshot.epoch, ordinal: String(snapshot.base) }, change: { op: "delete", address } };
14316
+ return { position: { epoch: snapshot.epoch, ordinal: String(held.at) }, change: { op: "upsert", row: held.row } };
14317
+ }
14318
+ #page(args, binding, snapshot) {
14319
+ const offset = args.page === undefined ? 0 : Number(args.page);
14320
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > snapshot.rows.length)
14321
+ throw new Error(`the list token ${String(args.page)} does not name a page of this read`);
14322
+ const page = (end, items) => ({
14323
+ generation: snapshot.generation,
14324
+ snapshot: snapshot.generation,
14325
+ base: { epoch: snapshot.epoch, ordinal: String(snapshot.base) },
14326
+ rows: items,
14327
+ next: end >= snapshot.rows.length ? null : String(end),
14328
+ complete: end >= snapshot.rows.length
14329
+ });
14330
+ const rows = [];
14331
+ let bytes = 0;
14332
+ let next = offset;
14333
+ while (next < snapshot.rows.length && rows.length < args.limit) {
14334
+ const row = snapshot.rows[next].row;
14335
+ const size = sourceFrameBytes(row);
14336
+ const envelope = sourceFrameBytes({ ...binding, op: "list", outcome: "applied", body: page(next + 1, []) });
14337
+ if (envelope + bytes + size + rows.length > SOURCE_PAGE_BUDGET_BYTES) {
14338
+ if (rows.length === 0)
14339
+ throw new Error(`ITEM_TOO_LARGE: ${row.address}`);
14340
+ break;
14341
+ }
14342
+ rows.push(row);
14343
+ bytes += size;
14344
+ next++;
14345
+ }
14346
+ return page(next, rows);
14347
+ }
14348
+ async handle(request) {
14349
+ const binding = { workspaceId: request.workspaceId, sourceId: request.sourceId, hostId: request.hostId };
14350
+ const refuse = (code, outcome = "refused") => ({ ...binding, op: request.op, outcome, code });
14351
+ if (request.sourceId !== this.sourceId)
14352
+ return refuse("SOURCE_UNBOUND");
14353
+ try {
14354
+ switch (request.op) {
14355
+ case "watch":
14356
+ this.#shell.watch(request.args.on);
14357
+ if (request.args.on && this.#current === undefined) {
14358
+ this.#read().catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} on a watcher's first subscribe failed: ${describe3(error)}`));
14359
+ }
14360
+ return { ...binding, op: "watch", outcome: "applied", body: { on: this.#shell.watching } };
14361
+ case "list":
14362
+ return { ...binding, op: "list", outcome: "applied", body: this.#page(request.args, binding, await this.#latest()) };
14363
+ case "read":
14364
+ return { ...binding, op: "read", outcome: "applied", body: { observation: this.#observed(await this.#latest(), request.args.address) } };
14365
+ case "assign":
14366
+ this.#o.log.error(`hightea-source: ${this.sourceId} cannot assign ${request.args.address}: a command source has no write`);
14367
+ return refuse("SOURCE_UNAVAILABLE");
14368
+ }
14369
+ } catch (error) {
14370
+ const text = describe3(error);
14371
+ this.#o.log.error(`hightea-source: ${request.op} on ${this.sourceId} failed: ${text}`);
14372
+ if (text.startsWith("ITEM_TOO_LARGE: ")) {
14373
+ return { ...binding, op: request.op, outcome: "refused", code: "ITEM_TOO_LARGE", item: text.slice("ITEM_TOO_LARGE: ".length) };
14374
+ }
14375
+ return refuse("SOURCE_UNAVAILABLE", "unknown");
14376
+ }
14377
+ }
14378
+ }
14379
+
14380
+ // ../ahp-host/src/source-channel.ts
14381
+ function nearestIssues(issues, depth = 0) {
14382
+ return issues.flatMap((issue) => {
14383
+ if (depth >= 3 || issue.errors === undefined || issue.errors.length === 0)
14384
+ return [issue];
14385
+ return issue.errors.map((branch) => nearestIssues(branch, depth + 1)).reduce((best, one) => one.length < best.length ? one : best);
14386
+ });
14387
+ }
14388
+ var REQUEST = "x-hightea/source/request";
14389
+ function createSourceChannel(options) {
14390
+ const { log } = options;
14391
+ const refuse = (connection, id, code) => connection.send({ jsonrpc: "2.0", id, error: { code: -32000, message: code } });
14392
+ const answer = (connection, id, request, outcome, code) => send(connection, id, request, { workspaceId: request.workspaceId, sourceId: request.sourceId, hostId: request.hostId, op: request.op, outcome, code });
14393
+ const send = (connection, id, request, result) => {
14394
+ const frame = { jsonrpc: "2.0", id, result };
14395
+ if (sourceFrameBytes(frame) > SOURCE_FRAME_MAX_BYTES) {
14396
+ log.error(`hightea-source: FRAME_TOO_LARGE for ${request.op} on ${request.sourceId}`);
14397
+ return answer(connection, id, request, "unknown", "FRAME_TOO_LARGE");
13326
14398
  }
13327
14399
  return connection.send(frame);
13328
14400
  };
@@ -13374,10 +14446,130 @@ function createSourceChannel(options) {
13374
14446
  };
13375
14447
  }
13376
14448
 
14449
+ // ../ahp-host/src/records-channel.ts
14450
+ var SCHEME = "x-hh-records";
14451
+ var CHANNEL = `${SCHEME}://`;
14452
+ var CHANGED = `${SCHEME}/changed`;
14453
+ var SUBJECT = "records";
14454
+ var sourceOf = (uri) => {
14455
+ if (!uri.startsWith(CHANNEL))
14456
+ return;
14457
+ const rest = uri.slice(CHANNEL.length);
14458
+ if (rest === "" || rest.includes("/") || rest.includes("?"))
14459
+ return;
14460
+ return decodeURIComponent(rest);
14461
+ };
14462
+ function createRecordsChannel(context) {
14463
+ const bySource = new Map;
14464
+ let handle;
14465
+ const heldFor = (source) => {
14466
+ const held = bySource.get(source);
14467
+ if (held !== undefined)
14468
+ return held;
14469
+ const fresh = new Map;
14470
+ bySource.set(source, fresh);
14471
+ return fresh;
14472
+ };
14473
+ const entries = (source) => [...heldFor(source).values()];
14474
+ const channel = {
14475
+ grant: `${SUBJECT}:read`,
14476
+ snapshot: (uri) => {
14477
+ const source = sourceOf(uri);
14478
+ if (source === undefined) {
14479
+ const index = { sources: context.sources().map((one) => ({ ...one, count: heldFor(one.source).size })) };
14480
+ return index;
14481
+ }
14482
+ const known = context.sources().find((one) => one.source === source);
14483
+ if (known === undefined) {
14484
+ return { source, epoch: "", records: [], error: `this host offers no source ${source}; ${CHANNEL} lists the ones it does` };
14485
+ }
14486
+ const snapshot = { source, epoch: known.epoch, records: entries(source) };
14487
+ return snapshot;
14488
+ },
14489
+ describe: () => ({ title: "Records", description: `Each board source's records, one URI per source: ${CHANNEL}<sourceId>.` }),
14490
+ operations: {
14491
+ operations: () => [{
14492
+ id: RECORDS_ASSIGN,
14493
+ kind: SUBJECT,
14494
+ label: "Assign",
14495
+ description: `Sets one record's owner, against the revision the caller read; a stale revision is refused and nothing is written.`,
14496
+ scopes: [SUBJECT],
14497
+ grant: RECORDS_ASSIGN_GRANT,
14498
+ status: "idle",
14499
+ input: {
14500
+ type: "object",
14501
+ properties: {
14502
+ address: { type: "string", minLength: 1, maxLength: 1024 },
14503
+ ownerMemberId: { type: "string", minLength: 1, maxLength: 256 },
14504
+ expectedOwner: { type: ["string", "null"] },
14505
+ ifRevision: { type: "string", minLength: 1, maxLength: 256 },
14506
+ intentId: { type: "string", minLength: 1, maxLength: 256 }
14507
+ },
14508
+ required: ["address", "ownerMemberId", "ifRevision", "intentId"],
14509
+ additionalProperties: false
14510
+ }
14511
+ }],
14512
+ run: async (asked, _target, input, _reader, caller) => {
14513
+ if (asked.id !== RECORDS_ASSIGN)
14514
+ throw new Error(`${CHANNEL} offers no operation ${asked.id}; only ${RECORDS_ASSIGN}`);
14515
+ const parsed = RecordsAssignInputSchema.safeParse(input ?? {});
14516
+ if (!parsed.success) {
14517
+ throw new Error(`${RECORDS_ASSIGN} on ${CHANNEL}: ${parsed.error.issues.map((one) => `${one.path.join(".")} ${one.message}`).join("; ")}`);
14518
+ }
14519
+ if (context.assign === undefined)
14520
+ throw new Error(`${CHANNEL} has no source to assign on this host`);
14521
+ return context.assign(parsed.data, caller);
14522
+ }
14523
+ }
14524
+ };
14525
+ return {
14526
+ channel,
14527
+ bind: (next) => {
14528
+ handle = next;
14529
+ },
14530
+ held: entries,
14531
+ observe: (source, observations) => {
14532
+ const held = heldFor(source);
14533
+ for (const one of observations) {
14534
+ if (one.op === "delete") {
14535
+ const was = held.get(one.address);
14536
+ if (was === undefined)
14537
+ continue;
14538
+ held.delete(one.address);
14539
+ publish(source, { type: CHANGED, source, deleted: true, address: one.address, revision: one.revision });
14540
+ continue;
14541
+ }
14542
+ const record = {
14543
+ address: one.address,
14544
+ revision: one.revision,
14545
+ scope: one.scope ?? source,
14546
+ columns: one.columns ?? {},
14547
+ ...one.extra === undefined ? {} : { extra: one.extra }
14548
+ };
14549
+ const was = held.get(one.address);
14550
+ if (was !== undefined && was.revision === record.revision)
14551
+ continue;
14552
+ held.set(one.address, record);
14553
+ publish(source, { type: CHANGED, source, record, revision: record.revision });
14554
+ }
14555
+ }
14556
+ };
14557
+ function publish(source, action) {
14558
+ if (handle === undefined)
14559
+ return;
14560
+ try {
14561
+ handle.publish(`${CHANNEL}${encodeURIComponent(source)}`, action);
14562
+ } catch (error) {
14563
+ context.log.error(`hightea-records: publishing on ${CHANNEL}${source} failed: ${error instanceof Error ? error.message : String(error)}`);
14564
+ }
14565
+ }
14566
+ }
14567
+
13377
14568
  // ../ahp-host/src/pipe-stamp.ts
13378
- import { readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
14569
+ import { readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
13379
14570
  import { join as join3 } from "node:path";
13380
14571
  var PIPE_CONNECTED_STAMP = "pipe-connected.json";
14572
+ var PIPE_REFUSED_STAMP = "pipe-refused.json";
13381
14573
  function ownManifestVersion(manifest = new URL("./plugin.json", import.meta.url)) {
13382
14574
  let value;
13383
14575
  try {
@@ -13397,36 +14589,24 @@ function stampConnected(configDir, version, now = new Date) {
13397
14589
  `, { mode: 384 });
13398
14590
  renameSync(staged, file);
13399
14591
  }
13400
-
13401
- // ../ahp-host/src/plugin.ts
13402
- var name = "hightea-pipe";
13403
- var owner = `plugin:${name}`;
13404
- var hostTools = ["hightea_thread_read", "hightea_thread_post", "hightea_page_read", "hightea_page_write", "hightea_page_screenshot"];
13405
- function jwtExpiresAt(token) {
13406
- const parts = token.split(".");
13407
- if (parts.length !== 3)
13408
- return;
14592
+ function stampRefused(configDir, error, version, now = new Date) {
14593
+ const file = join3(configDir, PIPE_REFUSED_STAMP);
14594
+ const staged = `${file}.${process.pid}.tmp`;
14595
+ const refusal = { ...version === undefined ? {} : { version }, at: now.toISOString(), error };
14596
+ writeFileSync(staged, `${JSON.stringify(refusal, null, 2)}
14597
+ `, { mode: 384 });
14598
+ renameSync(staged, file);
14599
+ }
14600
+ function clearRefused(configDir) {
13409
14601
  try {
13410
- const claims = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
13411
- const exp = claims?.exp;
13412
- return typeof exp === "number" && Number.isFinite(exp) && exp > 0 ? exp * 1000 : undefined;
13413
- } catch {
13414
- return;
14602
+ unlinkSync(join3(configDir, PIPE_REFUSED_STAMP));
14603
+ } catch (error) {
14604
+ if (error.code !== "ENOENT")
14605
+ throw error;
13415
14606
  }
13416
14607
  }
13417
- function shareListener(peer) {
13418
- const listeners = [];
13419
- peer.onMessage((message) => {
13420
- for (const listener of listeners)
13421
- listener(message);
13422
- });
13423
- return {
13424
- request: (method, params, timeoutMs) => peer.request(method, params, timeoutMs),
13425
- notify: (method, params) => peer.notify(method, params),
13426
- onMessage: (listener) => void listeners.push(listener),
13427
- close: () => peer.close()
13428
- };
13429
- }
14608
+
14609
+ // ../ahp-host/src/house.ts
13430
14610
  function houseHeaders(token) {
13431
14611
  return { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" };
13432
14612
  }
@@ -13445,125 +14625,8 @@ async function houseCall(mcpUrl, headers, tool, args) {
13445
14625
  throw new Error(answer.error.message);
13446
14626
  return answer;
13447
14627
  }
13448
- function registerTools(host, mcpUrl, pipe, signing) {
13449
- const call = async (at, tool, args) => {
13450
- const activePipe = pipe();
13451
- const context = { sessionId: at.session, chatId: at.chat, turnId: at.turn() ?? "" };
13452
- const resolved = activePipe?.resolveToolToken(context);
13453
- if (resolved === undefined || !resolved.ok)
13454
- throw new Error("TOKEN_EXPIRED_OR_REVOKED");
13455
- const headers = houseHeaders(resolved.token);
13456
- if (tool === "post_message")
13457
- headers["idempotency-key"] = resolved.deliveryId;
13458
- if (tool === "read_thread" || tool === "post_message") {
13459
- const [roomId, messageId, extra] = resolved.threadRef.split("/");
13460
- if (!roomId || !messageId || extra !== undefined)
13461
- throw new Error("Invalid wake thread reference");
13462
- if (tool === "read_thread") {
13463
- args = { roomId, messageId, ...resolved.afterMessageId === undefined ? {} : { after: resolved.afterMessageId } };
13464
- } else {
13465
- const key = await signing.hostKey;
13466
- if (key === undefined || key instanceof Error) {
13467
- throw new Error(`HOST_KEY_UNAVAILABLE: this host cannot sign its agent's post${key instanceof Error ? `: ${key.message}` : " (its ahpd names no configDir)"}`);
13468
- }
13469
- const text = String(args.text ?? "");
13470
- args = {
13471
- text,
13472
- roomId,
13473
- deliveryId: resolved.deliveryId,
13474
- replyId: resolved.deliveryId,
13475
- sig: signHostPost(key, { workspaceId: signing.workspaceId, roomId, rootMessageId: messageId, authorMemberId: resolved.agentMemberId, clientId: resolved.deliveryId, body: text })
13476
- };
13477
- }
13478
- }
13479
- const answer = await houseCall(mcpUrl, headers, tool, args);
13480
- if (tool === "read_thread") {
13481
- const value = answer.result?.structuredContent;
13482
- 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 === "")) {
13483
- throw new Error("read_thread returned no valid root/replies paging result");
13484
- }
13485
- const current = activePipe?.resolveToolToken(context);
13486
- if (current === undefined || !current.ok)
13487
- throw new Error("TOKEN_EXPIRED_OR_REVOKED");
13488
- const last = value.replies.at(-1);
13489
- const position = last?.id ?? current.afterMessageId ?? value.root.id;
13490
- if (current.afterMessageId === resolved.afterMessageId)
13491
- activePipe.vault.recordThreadRead(context, position);
13492
- return JSON.stringify(await signing.gate.view(resolved.threadRef, value));
13493
- }
13494
- return (answer.result?.content ?? []).map((part) => part.text).join(`
13495
- `);
13496
- };
13497
- host.registerTool({
13498
- definition: {
13499
- name: "hightea_thread_read",
13500
- description: "You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",
13501
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
13502
- },
13503
- confirm: false,
13504
- optIn: true,
13505
- run: (_input, at) => call(at, "read_thread", {})
13506
- });
13507
- host.registerTool({
13508
- definition: {
13509
- name: "hightea_thread_post",
13510
- description: "Post your reply to the Hightea room thread you were woken in. Call it once with your answer.",
13511
- inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false }
13512
- },
13513
- confirm: false,
13514
- optIn: true,
13515
- run: (input, at) => call(at, "post_message", { text: String(input.text ?? "") })
13516
- });
13517
- host.registerTool({
13518
- definition: {
13519
- name: "hightea_page_read",
13520
- description: "Read a Hightea page: its current version and content.",
13521
- inputSchema: { type: "object", properties: { pageId: { type: "string" } }, required: ["pageId"], additionalProperties: false }
13522
- },
13523
- confirm: false,
13524
- optIn: true,
13525
- run: (input, at) => call(at, "page_read", { pageId: String(input.pageId ?? "") })
13526
- });
13527
- host.registerTool({
13528
- definition: {
13529
- name: "hightea_page_write",
13530
- description: "Replace a Hightea page's content. Pass the version you read as ifVersion; a stale write is refused.",
13531
- inputSchema: {
13532
- type: "object",
13533
- properties: { pageId: { type: "string" }, ifVersion: { type: "number" }, content: { type: "string" } },
13534
- required: ["pageId", "ifVersion", "content"],
13535
- additionalProperties: false
13536
- }
13537
- },
13538
- confirm: false,
13539
- optIn: true,
13540
- run: (input, at) => {
13541
- const args = input;
13542
- return call(at, "page_write", { pageId: String(args.pageId ?? ""), ifVersion: Number(args.ifVersion), content: String(args.content ?? "") });
13543
- }
13544
- });
13545
- host.registerTool({
13546
- definition: {
13547
- name: "hightea_page_screenshot",
13548
- description: "Capture a Hightea page as a stored image at its live version, then mention the page in your reply so a person sees the capture on the page card. A version that is not the live one is refused by name.",
13549
- inputSchema: {
13550
- type: "object",
13551
- properties: {
13552
- pageId: { type: "string" },
13553
- version: { type: "number", description: "Optional expected version; any version that is not live is refused (VERSION_NOT_CURRENT)." },
13554
- width: { type: "number", description: "Capture width in CSS pixels (16..2400)." },
13555
- height: { type: "number", description: "Minimum capture height in CSS pixels (16..2400)." },
13556
- format: { type: "string", enum: ["png", "webp"] }
13557
- },
13558
- required: ["pageId"],
13559
- additionalProperties: false
13560
- }
13561
- },
13562
- confirm: false,
13563
- optIn: true,
13564
- run: (input, at) => call(at, "page_screenshot", pageScreenshotArgs(input))
13565
- });
13566
- }
14628
+
14629
+ // ../ahp-host/src/tools.ts
13567
14630
  function pageScreenshotArgs(input) {
13568
14631
  const wanted = input ?? {};
13569
14632
  const pageId = wanted.pageId;
@@ -13585,6 +14648,463 @@ function pageScreenshotArgs(input) {
13585
14648
  }
13586
14649
  return args;
13587
14650
  }
14651
+ var TOOL_SPECS = [
14652
+ {
14653
+ name: "hightea_thread_read",
14654
+ description: "You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",
14655
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
14656
+ readOnly: true,
14657
+ toHouse: () => ({ tool: "read_thread", args: {} })
14658
+ },
14659
+ {
14660
+ name: "hightea_thread_post",
14661
+ description: "Post your reply to the Hightea room thread you were woken in. Call it once with your answer.",
14662
+ inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false },
14663
+ toHouse: (input) => ({ tool: "post_message", args: { text: String(input.text ?? "") } })
14664
+ },
14665
+ {
14666
+ name: "hightea_page_read",
14667
+ description: "Read a Hightea page: its current version and content.",
14668
+ inputSchema: { type: "object", properties: { pageId: { type: "string" } }, required: ["pageId"], additionalProperties: false },
14669
+ readOnly: true,
14670
+ toHouse: (input) => ({ tool: "page_read", args: { pageId: String(input.pageId ?? "") } })
14671
+ },
14672
+ {
14673
+ name: "hightea_page_write",
14674
+ description: "Replace a Hightea page's content. Pass the version you read as ifVersion; a stale write is refused.",
14675
+ inputSchema: {
14676
+ type: "object",
14677
+ properties: { pageId: { type: "string" }, ifVersion: { type: "number" }, content: { type: "string" } },
14678
+ required: ["pageId", "ifVersion", "content"],
14679
+ additionalProperties: false
14680
+ },
14681
+ toHouse: (input) => {
14682
+ const args = input;
14683
+ return { tool: "page_write", args: { pageId: String(args.pageId ?? ""), ifVersion: Number(args.ifVersion), content: String(args.content ?? "") } };
14684
+ }
14685
+ },
14686
+ {
14687
+ name: "hightea_page_screenshot",
14688
+ description: "Capture a Hightea page as a stored image at its live version, then mention the page in your reply so a person sees the capture on the page card. A version that is not the live one is refused by name.",
14689
+ inputSchema: {
14690
+ type: "object",
14691
+ properties: {
14692
+ pageId: { type: "string" },
14693
+ version: { type: "number", description: "Optional expected version; any version that is not live is refused (VERSION_NOT_CURRENT)." },
14694
+ width: { type: "number", description: "Capture width in CSS pixels (16..2400)." },
14695
+ height: { type: "number", description: "Minimum capture height in CSS pixels (16..2400)." },
14696
+ format: { type: "string", enum: ["png", "webp"] }
14697
+ },
14698
+ required: ["pageId"],
14699
+ additionalProperties: false
14700
+ },
14701
+ toHouse: (input) => ({ tool: "page_screenshot", args: pageScreenshotArgs(input) })
14702
+ }
14703
+ ];
14704
+ function toolSpec(name) {
14705
+ return TOOL_SPECS.find((spec) => spec.name === name);
14706
+ }
14707
+ function toolTokenScopes(name) {
14708
+ return toolSpec(name)?.readOnly === true ? [TOKEN_SCOPE_BASE] : [TOKEN_SCOPE_BASE, TOKEN_SCOPE_TOOLS_ALL];
14709
+ }
14710
+
14711
+ // ../ahp-host/src/host-tools-port.ts
14712
+ var HOST_TOOLS_NAME = "hightea";
14713
+
14714
+ // ../ahp-host/src/mcp-server.ts
14715
+ class McpRefusal extends Error {
14716
+ code;
14717
+ constructor(code, why) {
14718
+ super(`${code}: ${why}`);
14719
+ this.code = code;
14720
+ }
14721
+ }
14722
+ function threadOfRef(ref) {
14723
+ const bare = ref.startsWith("hightea://thread/") ? ref.slice("hightea://thread/".length) : ref;
14724
+ const query = bare.indexOf("?");
14725
+ const path = query < 0 ? bare : bare.slice(0, query);
14726
+ const [roomId, rootMessageId, extra] = path.split("/");
14727
+ if (!roomId || !rootMessageId || extra !== undefined) {
14728
+ throw new McpRefusal("THREAD_REF_INVALID", `${JSON.stringify(ref)} names no room thread (expected hightea://thread/<roomId>/<rootMessageId>)`);
14729
+ }
14730
+ return { roomId, rootMessageId };
14731
+ }
14732
+ function authOf(token) {
14733
+ const parts = token.split(".");
14734
+ let claims = {};
14735
+ if (parts.length === 3) {
14736
+ try {
14737
+ const value = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
14738
+ if (value !== null && typeof value === "object")
14739
+ claims = value;
14740
+ } catch {
14741
+ claims = {};
14742
+ }
14743
+ }
14744
+ const scope = typeof claims["scope"] === "string" ? claims["scope"].split(" ").filter((one) => one !== "") : undefined;
14745
+ return { token, ...scope === undefined ? {} : { scopes: scope } };
14746
+ }
14747
+
14748
+ class HighteaMcpServer {
14749
+ #options;
14750
+ #house;
14751
+ #reads = new Map;
14752
+ #askGate;
14753
+ constructor(options) {
14754
+ this.#options = options;
14755
+ this.#house = options.house ?? houseCall;
14756
+ }
14757
+ listTools() {
14758
+ return TOOL_SPECS.map((spec) => ({
14759
+ name: spec.name,
14760
+ description: spec.description,
14761
+ inputSchema: spec.inputSchema,
14762
+ ...spec.readOnly === true ? { annotations: { readOnlyHint: true } } : {}
14763
+ }));
14764
+ }
14765
+ async handleRpc(request, auth, sessionId) {
14766
+ const id = request.id ?? null;
14767
+ switch (request.method) {
14768
+ case "initialize":
14769
+ return { jsonrpc: "2.0", id, result: {
14770
+ protocolVersion: String(request.params?.["protocolVersion"] ?? "2025-06-18"),
14771
+ capabilities: { tools: {} },
14772
+ serverInfo: { name: "hightea", version: "0.1.0" }
14773
+ } };
14774
+ case "ping":
14775
+ return { jsonrpc: "2.0", id, result: null };
14776
+ case "tools/list":
14777
+ return { jsonrpc: "2.0", id, result: { tools: this.listTools() } };
14778
+ case "tools/call": {
14779
+ const name = request.params?.["name"];
14780
+ if (typeof name !== "string")
14781
+ return { jsonrpc: "2.0", id, error: { code: -32602, message: "tools/call needs a tool name" } };
14782
+ try {
14783
+ if (auth === undefined)
14784
+ throw new McpRefusal("TOKEN_EXPIRED_OR_REVOKED", "no Hightea token on this request");
14785
+ const result = await this.callTool(name, request.params?.["arguments"] ?? {}, auth, sessionId ?? "");
14786
+ return { jsonrpc: "2.0", id, result };
14787
+ } catch (error) {
14788
+ if (error instanceof McpRefusal || error instanceof AskRefusal) {
14789
+ return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: error.message }], isError: true } };
14790
+ }
14791
+ return { jsonrpc: "2.0", id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } };
14792
+ }
14793
+ }
14794
+ default:
14795
+ return { jsonrpc: "2.0", id, error: { code: -32601, message: `no method ${String(request.method)}` } };
14796
+ }
14797
+ }
14798
+ async callTool(name, input, auth, sessionId) {
14799
+ const spec = toolSpec(name);
14800
+ if (spec === undefined)
14801
+ throw new McpRefusal("TOOL_UNKNOWN", `no Hightea tool is named ${JSON.stringify(name)}`);
14802
+ const { tool, args } = spec.toHouse(input);
14803
+ const headers = houseHeaders(auth.token);
14804
+ if (tool === "read_thread" || tool === "post_message") {
14805
+ const turn = await this.#turn(auth.token);
14806
+ const thread = threadOfRef(turn.threadRef);
14807
+ const threadRef = `${thread.roomId}/${thread.rootMessageId}`;
14808
+ const row = `${sessionId}|${threadRef}`;
14809
+ if (tool === "read_thread") {
14810
+ await this.#gate().admit({ deliveryId: turn.deliveryId, threadRef, triggeringMessageIds: turn.triggeringMessageIds ?? [turn.deliveryId] }, auth.token);
14811
+ const after = this.#reads.get(row);
14812
+ const answer = await this.#house(this.#options.mcpUrl, headers, "read_thread", { roomId: thread.roomId, messageId: thread.rootMessageId, ...after === undefined ? {} : { after } });
14813
+ const value = validThreadRead(answer);
14814
+ const last = value.replies.at(-1)?.id;
14815
+ if (last !== undefined)
14816
+ this.#reads.set(row, last);
14817
+ return { content: [{ type: "text", text: JSON.stringify(await this.#gate().view(threadRef, value)) }] };
14818
+ }
14819
+ const key = await this.#options.hostKey;
14820
+ if (key === undefined || key instanceof Error) {
14821
+ throw new McpRefusal("HOST_KEY_UNAVAILABLE", `this host cannot sign its agent's post${key instanceof Error ? `: ${key.message}` : " (its ahpd names no configDir)"}`);
14822
+ }
14823
+ const text = String(args["text"] ?? "");
14824
+ headers["idempotency-key"] = turn.deliveryId;
14825
+ const answer = await this.#house(this.#options.mcpUrl, headers, "post_message", {
14826
+ text,
14827
+ roomId: thread.roomId,
14828
+ deliveryId: turn.deliveryId,
14829
+ replyId: turn.deliveryId,
14830
+ sig: signHostPost(key, {
14831
+ workspaceId: this.#options.workspaceId,
14832
+ roomId: thread.roomId,
14833
+ rootMessageId: thread.rootMessageId,
14834
+ authorMemberId: turn.member,
14835
+ clientId: turn.deliveryId,
14836
+ body: text
14837
+ })
14838
+ });
14839
+ return { content: [{ type: "text", text: textOf(answer) }] };
14840
+ }
14841
+ const answer = await this.#house(this.#options.mcpUrl, headers, tool, args);
14842
+ return { content: [{ type: "text", text: textOf(answer) }] };
14843
+ }
14844
+ async#turn(token) {
14845
+ return (this.#options.turnFacts ?? ((bearer) => this.#turnFromHouse(bearer)))(token);
14846
+ }
14847
+ async#turnFromHouse(token) {
14848
+ const answer = await this.#house(this.#options.mcpUrl, houseHeaders(token), "read_thread", { limit: 1 });
14849
+ return validTurnFacts(answer);
14850
+ }
14851
+ #gate() {
14852
+ if (this.#options.gate !== undefined)
14853
+ return this.#options.gate;
14854
+ if (this.#askGate === undefined) {
14855
+ this.#askGate = new AskGate({
14856
+ configDir: this.#options.configDir,
14857
+ workspaceId: this.#options.workspaceId,
14858
+ ownAgents: this.#options.ownAgents,
14859
+ hostKey: this.#options.hostKey,
14860
+ readThread: async (token, args) => {
14861
+ const answer = await this.#house(this.#options.mcpUrl, houseHeaders(token), "read_thread", args);
14862
+ return answer.result?.structuredContent;
14863
+ },
14864
+ now: this.#options.now ?? Date.now
14865
+ });
14866
+ }
14867
+ return this.#askGate;
14868
+ }
14869
+ }
14870
+ function validThreadRead(answer) {
14871
+ const value = answer.result?.structuredContent;
14872
+ const root = value?.["root"];
14873
+ const replies = value?.["replies"];
14874
+ const valid = value !== undefined && value !== null && typeof value === "object" && root !== undefined && root !== null && typeof root === "object" && typeof root.id === "string" && root.id !== "" && Array.isArray(replies) && replies.every((reply) => reply !== null && typeof reply === "object" && typeof reply.id === "string");
14875
+ if (!valid)
14876
+ throw new McpRefusal("READ_THREAD_INVALID", "read_thread returned no valid root/replies paging result");
14877
+ return value;
14878
+ }
14879
+ function textOf(answer) {
14880
+ return (answer.result?.content ?? []).map((part) => part.text).join(`
14881
+ `);
14882
+ }
14883
+ function validTurnFacts(answer) {
14884
+ const value = answer.result?.structuredContent;
14885
+ const turn = value?.["turn"];
14886
+ const text = (key) => {
14887
+ const found = turn?.[key];
14888
+ return typeof found === "string" && found !== "" ? found : undefined;
14889
+ };
14890
+ const ids = turn?.["triggeringMessageIds"];
14891
+ const roomId = text("roomId");
14892
+ const messageId = text("messageId");
14893
+ const deliveryId = text("deliveryId");
14894
+ const member = text("memberId");
14895
+ if (roomId === undefined || messageId === undefined || deliveryId === undefined || member === undefined || !Array.isArray(ids) || ids.some((id) => typeof id !== "string")) {
14896
+ throw new McpRefusal("TURN_FACTS_UNAVAILABLE", "the house's answer for this bearer carries no turn (roomId, messageId, deliveryId, memberId, triggeringMessageIds); nothing room-shaped is served rather than inventing one");
14897
+ }
14898
+ return { threadRef: `${roomId}/${messageId}`, deliveryId, member, triggeringMessageIds: ids };
14899
+ }
14900
+
14901
+ // ../ahp-host/src/declared-sources.ts
14902
+ var DECLARED_IDS_MAX = 64;
14903
+ var ID = /^[A-Za-z0-9_.:-]{1,200}$/u;
14904
+ var CODE = /^[A-Z_]{1,64}$/u;
14905
+ var MESSAGE_MAX = 200;
14906
+ function declaredAnswer(frame) {
14907
+ if (typeof frame !== "object" || frame === null)
14908
+ return null;
14909
+ const method = frame.method;
14910
+ if (method !== "x-hightea/source/declared")
14911
+ return null;
14912
+ const params = frame.params;
14913
+ if (typeof params !== "object" || params === null)
14914
+ return { bound: [], refused: [], dropped: 0 };
14915
+ const ids = (value) => Array.isArray(value) ? value.filter((one) => typeof one === "string" && ID.test(one)).slice(0, DECLARED_IDS_MAX) : [];
14916
+ const refused = (value) => {
14917
+ if (!Array.isArray(value))
14918
+ return [];
14919
+ const read = [];
14920
+ for (const one of value) {
14921
+ if (typeof one !== "object" || one === null)
14922
+ continue;
14923
+ const { sourceId, code, message } = one;
14924
+ if (typeof sourceId !== "string" || !ID.test(sourceId) || typeof code !== "string" || !CODE.test(code))
14925
+ continue;
14926
+ read.push({ sourceId, code, message: typeof message === "string" ? message.slice(0, MESSAGE_MAX) : "" });
14927
+ if (read.length === DECLARED_IDS_MAX)
14928
+ break;
14929
+ }
14930
+ return read;
14931
+ };
14932
+ const dropped = params.dropped;
14933
+ return {
14934
+ bound: ids(params.bound),
14935
+ refused: refused(params.refused),
14936
+ dropped: typeof dropped === "number" && Number.isSafeInteger(dropped) && dropped >= 0 ? dropped : 0
14937
+ };
14938
+ }
14939
+ function declaredLine(answer) {
14940
+ const refused = answer.refused.length === 0 ? "none refused" : `${String(answer.refused.length)} refused: ${answer.refused.map((one) => `${one.sourceId}=${one.code}${one.message === "" ? "" : ` (${one.message})`}`).join(", ")}`;
14941
+ const bound = answer.bound.length === 0 ? "none bound" : `bound ${answer.bound.join(", ")}`;
14942
+ const dropped = answer.dropped === 0 ? "" : `; ${String(answer.dropped)} declared id(s) were not readable`;
14943
+ return `hightea-source: declared sources — ${bound}; ${refused}${dropped}`;
14944
+ }
14945
+
14946
+ // ../ahp-host/src/mcp-http.ts
14947
+ import { createServer } from "node:http";
14948
+ function bearer(request) {
14949
+ const header = request.headers.get("authorization");
14950
+ if (header === null)
14951
+ return;
14952
+ const [scheme, ...rest] = header.split(" ");
14953
+ if (scheme?.toLowerCase() !== "bearer" || rest.length === 0)
14954
+ return;
14955
+ const token = rest.join(" ").trim();
14956
+ return token === "" ? undefined : token;
14957
+ }
14958
+ function unauthorized(options) {
14959
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32001, message: "Hightea token required" } }), {
14960
+ status: 401,
14961
+ headers: { "content-type": "application/json", "www-authenticate": `Bearer resource_metadata="${options.resourceMetadataUrl}"` }
14962
+ });
14963
+ }
14964
+ function shortOfScopes(options, tool, auth) {
14965
+ const needed = options.requiredScopes?.(tool) ?? [];
14966
+ if (needed.length === 0)
14967
+ return;
14968
+ const held = auth.scopes ?? [];
14969
+ const missing = needed.filter((scope) => !held.includes(scope));
14970
+ if (missing.length === 0)
14971
+ return;
14972
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32002, message: `insufficient_scope: ${missing.join(" ")}`, error: "insufficient_scope" } }), {
14973
+ status: 403,
14974
+ headers: {
14975
+ "content-type": "application/json",
14976
+ "www-authenticate": `Bearer error="insufficient_scope", scope="${needed.join(" ")}", resource_metadata="${options.resourceMetadataUrl}"`
14977
+ }
14978
+ });
14979
+ }
14980
+ var BODY_LIMIT_BYTES = 4 * 1024 * 1024;
14981
+ function httpHandler(server, options) {
14982
+ return async (request) => {
14983
+ if (request.method !== "POST")
14984
+ return new Response("Method Not Allowed", { status: 405, headers: { allow: "POST" } });
14985
+ let frame;
14986
+ try {
14987
+ frame = await request.json();
14988
+ } catch {
14989
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "the frame is not JSON" } }), {
14990
+ status: 400,
14991
+ headers: { "content-type": "application/json" }
14992
+ });
14993
+ }
14994
+ const token = bearer(request);
14995
+ const auth = token === undefined ? undefined : authOf(token);
14996
+ if (frame.method === "tools/call") {
14997
+ if (auth === undefined)
14998
+ return unauthorized(options);
14999
+ const tool = frame.params?.["name"];
15000
+ if (typeof tool === "string") {
15001
+ const refused = shortOfScopes(options, tool, auth);
15002
+ if (refused !== undefined)
15003
+ return refused;
15004
+ }
15005
+ }
15006
+ const sessionId = request.headers.get("mcp-session-id") ?? (frame.method === "initialize" ? crypto.randomUUID() : undefined);
15007
+ const answer = await server.handleRpc(frame, auth, sessionId);
15008
+ const headers = { "content-type": "application/json" };
15009
+ if (sessionId !== undefined)
15010
+ headers["mcp-session-id"] = sessionId;
15011
+ return new Response(JSON.stringify(answer), { status: 200, headers });
15012
+ };
15013
+ }
15014
+ function serveHttp(server, options) {
15015
+ const hostname = options.hostname ?? "127.0.0.1";
15016
+ const handler = httpHandler(server, options);
15017
+ const log = options.log ?? { error: (line) => console.error(line) };
15018
+ const http = createServer((incoming, outgoing) => void answer(incoming, outgoing, handler, log));
15019
+ const ready = new Promise((resolve, reject) => {
15020
+ const failed = (error) => reject(error);
15021
+ http.once("error", failed);
15022
+ http.listen(options.port, hostname, () => {
15023
+ http.off("error", failed);
15024
+ resolve();
15025
+ });
15026
+ });
15027
+ ready.catch(() => {
15028
+ return;
15029
+ });
15030
+ return {
15031
+ get url() {
15032
+ const address = http.address();
15033
+ const port = typeof address === "object" && address !== null ? address.port : options.port;
15034
+ return `http://${hostname}:${String(port)}/mcp`;
15035
+ },
15036
+ ready,
15037
+ stop: () => {
15038
+ http.closeAllConnections();
15039
+ http.close();
15040
+ }
15041
+ };
15042
+ }
15043
+ async function answer(incoming, outgoing, handler, log) {
15044
+ try {
15045
+ const chunks = [];
15046
+ let size = 0;
15047
+ for await (const chunk of incoming) {
15048
+ size += chunk.length;
15049
+ if (size > BODY_LIMIT_BYTES) {
15050
+ log.error(`hightea-mcp: a request body over ${String(BODY_LIMIT_BYTES)} bytes was refused (413)`);
15051
+ outgoing.writeHead(413, { "content-type": "application/json" });
15052
+ outgoing.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "this server refuses a request body this large" } }));
15053
+ incoming.destroy();
15054
+ return;
15055
+ }
15056
+ chunks.push(Buffer.from(chunk));
15057
+ }
15058
+ const headers = new Headers;
15059
+ for (const [name, value] of Object.entries(incoming.headers)) {
15060
+ if (value === undefined)
15061
+ continue;
15062
+ if (Array.isArray(value))
15063
+ for (const one of value)
15064
+ headers.append(name, one);
15065
+ else
15066
+ headers.set(name, value);
15067
+ }
15068
+ const body = Buffer.concat(chunks);
15069
+ const response = await handler(new Request(`http://${incoming.headers.host ?? "127.0.0.1"}${incoming.url ?? "/"}`, {
15070
+ method: incoming.method ?? "GET",
15071
+ headers,
15072
+ ...body.length === 0 ? {} : { body }
15073
+ }));
15074
+ const answered = Buffer.from(await response.arrayBuffer());
15075
+ outgoing.writeHead(response.status, Object.fromEntries(response.headers));
15076
+ outgoing.end(answered);
15077
+ } catch (error) {
15078
+ log.error(`hightea-mcp: a request could not be answered: ${error instanceof Error ? error.name : typeof error}`);
15079
+ outgoing.writeHead(500, { "content-type": "application/json" });
15080
+ outgoing.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "the Hightea MCP server could not answer this request" } }));
15081
+ }
15082
+ }
15083
+
15084
+ // ../ahp-host/src/plugin.ts
15085
+ var observedOf = (one) => one.change.op === "delete" ? { op: "delete", address: one.change.address, revision: `${one.position.epoch}#${one.position.ordinal}` } : { op: "upsert", address: one.change.row.address, revision: one.change.row.version, scope: one.change.row.scope, columns: one.change.row.columns, extra: one.change.row.extra };
15086
+ var name = "hightea-pipe";
15087
+ var owner = `plugin:${name}`;
15088
+ var hostTools = TOOL_SPECS.map((spec) => spec.name);
15089
+ function shareListener(peer) {
15090
+ const listeners = [];
15091
+ peer.onMessage((message) => {
15092
+ for (const listener of listeners)
15093
+ listener(message);
15094
+ });
15095
+ return {
15096
+ request: (method, params, timeoutMs) => peer.request(method, params, timeoutMs),
15097
+ notify: (method, params) => peer.notify(method, params),
15098
+ onMessage: (listener) => void listeners.push(listener),
15099
+ close: () => peer.close()
15100
+ };
15101
+ }
15102
+ function ownHeaders(options) {
15103
+ const value = options.headers;
15104
+ if (typeof value !== "object" || value === null || Array.isArray(value))
15105
+ throw new Error(`${name}: the plugin entry names no headers (headers), so this host cannot say which Hightea host it is`);
15106
+ return value;
15107
+ }
13588
15108
  function applyWith(host, options, seams) {
13589
15109
  const legacy = options.houseId;
13590
15110
  if (typeof options.workspaceId !== "string" || options.workspaceId === "") {
@@ -13592,8 +15112,18 @@ function applyWith(host, options, seams) {
13592
15112
  throw new Error("hightea-pipe: the plugin entry names no workspace (workspaceId)");
13593
15113
  options = { ...options, workspaceId: legacy };
13594
15114
  }
15115
+ const headers = ownHeaders(options);
13595
15116
  const own = typeof options.pluginVersion === "string" && options.pluginVersion !== "" ? { version: options.pluginVersion } : ownManifestVersion();
13596
15117
  const pluginVersion = "version" in own ? own.version : undefined;
15118
+ const recordRefusal = (error) => {
15119
+ if (host.configDir === undefined)
15120
+ return;
15121
+ try {
15122
+ stampRefused(host.configDir, String(error), pluginVersion);
15123
+ } catch (writeError) {
15124
+ host.log.error(`${name}: could not record the refused start in ${host.configDir}: ${String(writeError)}`);
15125
+ }
15126
+ };
13597
15127
  if (!("version" in own))
13598
15128
  host.log.error(`${name}: hello will name no plugin version: ${own.error}`);
13599
15129
  let connectedStamped = false;
@@ -13602,15 +15132,34 @@ function applyWith(host, options, seams) {
13602
15132
  let startup;
13603
15133
  let cloud;
13604
15134
  let kmSources = new Map;
15135
+ let toolsBound;
15136
+ let handlers = new Map;
15137
+ let assignOn;
15138
+ const records = createRecordsChannel({
15139
+ sources: () => [...kmSources.values()].map((one) => ({ source: one.sourceId, epoch: one.epoch })),
15140
+ log: host.log,
15141
+ assign: async (input, caller) => {
15142
+ if (assignOn === undefined)
15143
+ throw new Error("records:assign: no source is listening on this host yet");
15144
+ return assignOn(input, caller);
15145
+ }
15146
+ });
15147
+ records.bind(host.registerChannel(SCHEME, records.channel));
15148
+ host.registerGrants(SUBJECT, {
15149
+ title: "Board records",
15150
+ description: "Each board source's records as a channel: reading them, and assigning one record's owner against the revision that was read.",
15151
+ operations: [RECORDS_ASSIGN]
15152
+ });
13605
15153
  const stop = async () => {
13606
15154
  stopped = true;
13607
15155
  if (startup !== undefined)
13608
15156
  clearTimeout(startup);
13609
15157
  startup = undefined;
13610
15158
  cloud?.close();
13611
- await Promise.all([...kmSources.values()].map((source) => source.stop()));
15159
+ await Promise.all([...handlers.values()].map((source) => source.stop?.()));
13612
15160
  };
13613
15161
  host.registerClose(stop);
15162
+ host.registerClose(() => toolsBound?.stop());
13614
15163
  const hostKey = host.configDir === undefined ? Promise.resolve(undefined) : hostSigningKey(host.configDir).catch((error) => {
13615
15164
  const failure = error instanceof Error ? error : new Error(String(error));
13616
15165
  host.log.error(`${name}: ${failure.message}`);
@@ -13629,113 +15178,206 @@ function applyWith(host, options, seams) {
13629
15178
  }
13630
15179
  });
13631
15180
  const checks = seams.askGate ?? gate;
13632
- const signing = { workspaceId: options.workspaceId, hostKey, gate: checks };
13633
- if (options.mcpUrl !== undefined)
13634
- registerTools(host, options.mcpUrl, () => running, signing);
15181
+ if (host.registerSessionMeta === undefined) {
15182
+ host.log.error(`${name}: this ahpd cannot publish a session's member (registerSessionMeta is absent), so Hightea page rows for its sessions will name none`);
15183
+ } else {
15184
+ host.registerSessionMeta("hh/agentMemberId", (uri) => running?.agentMemberOf(uri));
15185
+ }
13635
15186
  host.on("listening", () => {
13636
15187
  if (stopped || startup !== undefined || cloud !== undefined)
13637
15188
  return;
13638
15189
  startup = setTimeout(() => {
13639
15190
  startup = undefined;
13640
- if (stopped)
13641
- return;
13642
- let initialized;
13643
- const hostId = options.headers[HOST_HEADER] ?? options.headers[LEGACY_HOST_HEADER] ?? "";
13644
- kmSources = new Map((options.sources ?? []).map((config) => [config.sourceId, new KmSource({
15191
+ startUp().catch((error) => {
15192
+ host.log.error(`${name}: the host could not start its connections: ${String(error)}`);
15193
+ recordRefusal(error);
15194
+ });
15195
+ }, 100);
15196
+ });
15197
+ async function startUp() {
15198
+ if (stopped)
15199
+ return;
15200
+ let initialized;
15201
+ const hostId = headers[HOST_HEADER] ?? headers[LEGACY_HOST_HEADER] ?? "";
15202
+ kmSources = new Map;
15203
+ handlers = new Map;
15204
+ for (const config of options.sources ?? []) {
15205
+ if (isCommandSource(config)) {
15206
+ handlers.set(config.sourceId, new CommandSource({
15207
+ config,
15208
+ workspaceId: options.workspaceId,
15209
+ hostId,
15210
+ log: host.log,
15211
+ push: (params) => link.sourcePush(params),
15212
+ ...seams.sourceChildren === undefined ? {} : { run: seams.sourceChildren.run }
15213
+ }));
15214
+ continue;
15215
+ }
15216
+ if (config.kind !== undefined && config.kind !== "km")
15217
+ throw new Error(`${name}: the plugin entry names a source kind it cannot construct (${JSON.stringify(config.kind)}) for ${config.sourceId}, so this start is refused rather than offering it as km`);
15218
+ const source = new KmSource({
13645
15219
  config,
13646
15220
  workspaceId: options.workspaceId,
13647
15221
  hostId,
13648
15222
  log: host.log,
13649
15223
  ...seams.sourceChildren,
15224
+ onRecords: (observations) => records.observe(config.sourceId, observations.map(observedOf)),
13650
15225
  serviceIdentityEnvironment: (binding) => {
13651
15226
  if (typeof host.serviceIdentityEnvironment !== "function")
13652
15227
  throw new Error("SERVICE_IDENTITY_UNAVAILABLE: native host callback missing");
13653
15228
  return host.serviceIdentityEnvironment(binding);
13654
15229
  },
13655
15230
  push: (params) => link.sourcePush(params)
13656
- })]));
13657
- const offered = new Set(kmSources.keys());
13658
- const sources = createSourceChannel({
13659
- workspaceId: options.workspaceId,
13660
- hostId,
13661
- bindings: () => offered,
13662
- log: host.log,
13663
- handler: { handle: (request) => kmSources.get(request.sourceId).handle(request) }
13664
15231
  });
13665
- const link = createCloudLink({
13666
- dial: (status) => {
13667
- const socket = new wrapper_default(options.cloudUrl, { headers: options.headers, handshakeTimeout: 15000, followRedirects: false });
13668
- socket.on("unexpected-response", (_request, response) => {
13669
- status(response.statusCode ?? 0);
13670
- response.resume();
13671
- socket.terminate();
13672
- });
13673
- return socket;
13674
- },
13675
- receive: (frame, connection) => {
13676
- if (sources.receive(frame, connection))
15232
+ kmSources.set(config.sourceId, source);
15233
+ handlers.set(config.sourceId, source);
15234
+ }
15235
+ assignOn = async (input, caller) => {
15236
+ const source = [...kmSources.values()].find((one) => input.address.startsWith(`issue:${one.sourceId}/`));
15237
+ if (source === undefined)
15238
+ return { outcome: "refused", code: "INVALID_ADDRESS" };
15239
+ const asked = caller?.owner?.id ?? `client:${caller?.client ?? "unknown"}`;
15240
+ return source.assign(input, { workspaceId: options.workspaceId, sourceId: source.sourceId, hostId }, asked);
15241
+ };
15242
+ const offered = new Set(handlers.keys());
15243
+ const sources = createSourceChannel({
15244
+ workspaceId: options.workspaceId,
15245
+ hostId,
15246
+ bindings: () => offered,
15247
+ log: host.log,
15248
+ handler: {
15249
+ handle: (request) => {
15250
+ const handler = handlers.get(request.sourceId);
15251
+ if (handler === undefined) {
15252
+ host.log.error(`hightea-source: no handler for ${request.sourceId} although it is bound here`);
15253
+ return Promise.resolve({ workspaceId: request.workspaceId, sourceId: request.sourceId, hostId: request.hostId, op: request.op, outcome: "refused", code: "SOURCE_UNAVAILABLE" });
15254
+ }
15255
+ return handler.handle(request);
15256
+ }
15257
+ }
15258
+ });
15259
+ let toolsServer;
15260
+ if (options.hostToolsPort !== undefined && options.mcpUrl !== undefined) {
15261
+ try {
15262
+ const server = new HighteaMcpServer({
15263
+ mcpUrl: options.mcpUrl,
15264
+ workspaceId: options.workspaceId,
15265
+ configDir: host.configDir,
15266
+ ownAgents: new Set(options.agents.map(([member]) => member)),
15267
+ hostKey,
15268
+ gate: checks
15269
+ });
15270
+ const bound = serveHttp(server, {
15271
+ port: options.hostToolsPort,
15272
+ resourceMetadataUrl: `http://127.0.0.1:${String(options.hostToolsPort)}/.well-known/oauth-protected-resource`,
15273
+ log: host.log,
15274
+ requiredScopes: toolTokenScopes
15275
+ });
15276
+ await bound.ready;
15277
+ if (stopped) {
15278
+ bound.stop();
15279
+ return;
15280
+ }
15281
+ toolsBound = bound;
15282
+ toolsServer = { resource: bound.url, name: HOST_TOOLS_NAME };
15283
+ } catch (error) {
15284
+ host.log.error(`${name}: the Hightea MCP server could not listen on 127.0.0.1:${String(options.hostToolsPort)} ` + `(another process may hold it), so no session is offered Hightea tools: ${String(error)}`);
15285
+ }
15286
+ }
15287
+ const link = createCloudLink({
15288
+ dial: (status) => {
15289
+ const socket = new wrapper_default(options.cloudUrl, { headers, handshakeTimeout: 15000, followRedirects: false });
15290
+ socket.on("unexpected-response", (_request, response) => {
15291
+ status(response.statusCode ?? 0);
15292
+ response.resume();
15293
+ socket.terminate();
15294
+ });
15295
+ return socket;
15296
+ },
15297
+ receive: (frame, connection) => {
15298
+ const declared = declaredAnswer(frame);
15299
+ if (declared !== null) {
15300
+ const say = host.log.info ?? host.log.error;
15301
+ say.call(host.log, declaredLine(declared));
15302
+ return;
15303
+ }
15304
+ if (sources.receive(frame, connection))
15305
+ return;
15306
+ pipe.fromCloud(frame);
15307
+ },
15308
+ log: host.log,
15309
+ opened: (connection) => {
15310
+ initialized ??= pipe.start(name);
15311
+ const hello = () => {
15312
+ if (stopped)
13677
15313
  return;
13678
- pipe.fromCloud(frame);
13679
- },
13680
- log: host.log,
13681
- opened: (connection) => {
13682
- initialized ??= pipe.start(name);
13683
- const hello = () => {
13684
- if (stopped)
13685
- return;
13686
- connection.send({ jsonrpc: "2.0", method: "x-hightea/hello", params: {
13687
- channel: "ahp-root://",
13688
- protocolVersions: [SUPPORTED_PROTOCOL],
13689
- plugin: { name, version: pluginVersion },
13690
- ahpd: options.ahpdVersion
13691
- } });
13692
- if (connectedStamped || pluginVersion === undefined || host.configDir === undefined)
13693
- return;
13694
- connectedStamped = true;
15314
+ connection.send({ jsonrpc: "2.0", method: "x-hightea/hello", params: {
15315
+ channel: "ahp-root://",
15316
+ protocolVersions: [SUPPORTED_PROTOCOL],
15317
+ plugin: { name, version: pluginVersion },
15318
+ ahpd: options.ahpdVersion,
15319
+ capabilities: [SIGNED_ENVELOPES_CAPABILITY],
15320
+ sources: [...handlers.keys()]
15321
+ } });
15322
+ if (host.configDir !== undefined) {
13695
15323
  try {
13696
- stampConnected(host.configDir, pluginVersion);
15324
+ clearRefused(host.configDir);
13697
15325
  } catch (error) {
13698
- host.log.error(`${name}: could not stamp this bundle's first connection in ${host.configDir}: ${String(error)}`);
13699
- }
13700
- };
13701
- initialized.then(hello, (error) => {
13702
- if (stopped)
13703
- return;
13704
- if (error instanceof UnmappedAgent && kmSources.size > 0) {
13705
- host.log.error(`${name}: agent conversations unavailable; declared sources remain connected: ${String(error)}`);
13706
- hello();
13707
- return;
15326
+ host.log.error(`${name}: could not clear the refused-start stamp in ${host.configDir}: ${String(error)}`);
13708
15327
  }
13709
- host.log.error(`${name}: could not start on the local ahpd: ${String(error)}`);
13710
- if (connection.close === undefined)
13711
- host.log.error(`${name}: this connection cannot be closed by name`);
13712
- else
13713
- connection.close(4001, "HOST_START_FAILED");
13714
- stop();
13715
- });
13716
- }
13717
- });
13718
- cloud = link;
13719
- for (const source of kmSources.values())
13720
- source.start();
13721
- const shared = shareListener(host.connect());
13722
- const pipe = new WakePipe(seams.peer === undefined ? shared : seams.peer(shared), link, {
13723
- workspaceId: options.workspaceId,
13724
- agents: new Map(options.agents),
13725
- tokenExpiresAt: seams.tokenExpiresAt ?? jwtExpiresAt,
13726
- owner,
13727
- tools: options.mcpUrl === undefined ? [] : hostTools,
13728
- startSession: (wanted, named) => host.startSession(wanted, named),
13729
- log: host.log,
13730
- store: recordsPipeStore(host.records("hightea"), owner, (uri) => host.sessionOwner(uri)),
13731
- admitTurn: (meta, token) => checks.admit(meta, token),
13732
- ...pluginVersion === undefined ? {} : {
13733
- handshake: { plugin: { name, version: pluginVersion }, ahpd: options.ahpdVersion }
15328
+ }
15329
+ if (connectedStamped || pluginVersion === undefined || host.configDir === undefined)
15330
+ return;
15331
+ connectedStamped = true;
15332
+ try {
15333
+ stampConnected(host.configDir, pluginVersion);
15334
+ } catch (error) {
15335
+ host.log.error(`${name}: could not stamp this bundle's first connection in ${host.configDir}: ${String(error)}`);
15336
+ }
15337
+ };
15338
+ initialized.then(hello, (error) => {
15339
+ if (stopped)
15340
+ return;
15341
+ if (error instanceof UnmappedAgent && kmSources.size > 0) {
15342
+ host.log.error(`${name}: agent conversations unavailable; declared sources remain connected: ${String(error)}`);
15343
+ hello();
15344
+ return;
15345
+ }
15346
+ host.log.error(`${name}: could not start on the local ahpd: ${String(error)}`);
15347
+ recordRefusal(error);
15348
+ if (connection.close === undefined)
15349
+ host.log.error(`${name}: this connection cannot be closed by name`);
15350
+ else
15351
+ connection.close(4001, "HOST_START_FAILED");
15352
+ stop();
15353
+ });
15354
+ }
15355
+ });
15356
+ cloud = link;
15357
+ for (const source of handlers.values())
15358
+ source.start?.();
15359
+ const shared = shareListener(host.connect());
15360
+ const pipe = new WakePipe(seams.peer === undefined ? shared : seams.peer(shared), link, {
15361
+ workspaceId: options.workspaceId,
15362
+ agents: new Map(options.agents),
15363
+ owner,
15364
+ tools: options.mcpUrl === undefined ? [] : hostTools,
15365
+ ...toolsServer === undefined ? {} : { hostTools: toolsServer },
15366
+ startSession: (wanted, named) => host.startSession(wanted, named),
15367
+ log: host.log,
15368
+ store: recordsPipeStore(host.records("hightea"), owner, (uri) => host.sessionOwner(uri), host.log, host.records("hightea/chats")),
15369
+ admitTurn: (meta, readBearer) => checks.admit(meta, readBearer),
15370
+ ...pluginVersion === undefined ? {} : {
15371
+ handshake: {
15372
+ plugin: { name, version: pluginVersion },
15373
+ ahpd: options.ahpdVersion,
15374
+ capabilities: [SIGNED_ENVELOPES_CAPABILITY],
15375
+ sources: () => [...handlers.keys()]
13734
15376
  }
13735
- });
13736
- running = pipe;
13737
- }, 100);
13738
- });
15377
+ }
15378
+ });
15379
+ running = pipe;
15380
+ }
13739
15381
  }
13740
15382
  function apply(host, options) {
13741
15383
  applyWith(host, options, {});
@@ -13744,11 +15386,8 @@ export {
13744
15386
  WakePipe,
13745
15387
  apply,
13746
15388
  applyWith,
13747
- houseCall,
13748
- jwtExpiresAt,
13749
15389
  name,
13750
15390
  pageScreenshotArgs,
13751
15391
  recordsPipeStore,
13752
- registerTools,
13753
15392
  shareListener
13754
15393
  };