@hallohuman/hightea 0.1.17 → 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.
- package/dist/bin.js +171 -64
- package/dist/chunk-0r70ekxd.js +8 -0
- package/dist/chunk-13tpn1g6.js +465 -0
- package/dist/chunk-3rgfnt23.js +16 -0
- package/dist/{chunk-rs0vvh3x.js → chunk-9e325ntw.js} +15 -4
- package/dist/{chunk-3ah56pdt.js → chunk-cx3yvvkz.js} +174 -207
- package/dist/{chunk-h5s3wwdz.js → chunk-dvnzt54t.js} +1126 -2001
- package/dist/chunk-dvt4hb8z.js +1491 -0
- package/dist/chunk-gk8tyqac.js +184 -0
- package/dist/chunk-h8pdqn31.js +157 -0
- package/dist/{chunk-1xykqbdm.js → chunk-ph04jess.js} +5 -2
- package/dist/chunk-w0ebwtch.js +161 -0
- package/dist/{chunk-6ae0ftqh.js → chunk-y5r2yxx1.js} +1 -1
- package/dist/plugin/plugin.json +8 -1
- package/dist/plugin/plugin.mjs +2179 -627
- package/package.json +8 -5
- package/dist/chunk-hxs6jv2m.js +0 -91
package/dist/plugin/plugin.mjs
CHANGED
|
@@ -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({
|
|
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({
|
|
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
|
-
|
|
9881
|
-
|
|
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 `
|
|
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
|
-
|
|
9973
|
-
|
|
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
|
|
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 (!
|
|
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 (!
|
|
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
|
-
...
|
|
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
|
-
...
|
|
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 (!
|
|
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 (!
|
|
10318
|
+
if (!isRecord2(message) || !exactKeys(message, ["text", "origin"]) || typeof message.text !== "string") {
|
|
10097
10319
|
return refuse("OPERATION_SHAPE_INVALID");
|
|
10098
10320
|
}
|
|
10099
|
-
if (!
|
|
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
|
-
|
|
10344
|
+
...triggering === undefined ? {} : { triggering },
|
|
10345
|
+
...agentToken === undefined ? {} : { readBearer: agentToken },
|
|
10125
10346
|
sessionKey: key,
|
|
10126
10347
|
turnId: action.turnId
|
|
10127
10348
|
};
|
|
@@ -10225,6 +10446,73 @@ async function listHostAgents(options) {
|
|
|
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 (!
|
|
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
|
|
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 {
|
|
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._-]
|
|
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
|
|
10561
|
-
|
|
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,7 +10984,54 @@ 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))])),
|
|
@@ -10804,19 +11131,24 @@ function readPipeState(loaded, log) {
|
|
|
10804
11131
|
}
|
|
10805
11132
|
|
|
10806
11133
|
class WakePipe {
|
|
10807
|
-
vault = new ActiveTurnTokenVault;
|
|
10808
11134
|
#sessions = new Map;
|
|
10809
11135
|
#dispatched = new Map;
|
|
10810
11136
|
#active = new Map;
|
|
10811
11137
|
#pendingInitialize = [];
|
|
10812
11138
|
#queued = new Map;
|
|
10813
11139
|
#subscribed = new Set;
|
|
11140
|
+
#live = new Map;
|
|
11141
|
+
#parked = new Map;
|
|
11142
|
+
#toolsIds = new Map;
|
|
11143
|
+
#toolsAnswers = new Map;
|
|
10814
11144
|
#lastStatus = new Map;
|
|
10815
11145
|
#writes = Promise.resolve();
|
|
10816
11146
|
#storeError;
|
|
10817
11147
|
#started = false;
|
|
10818
11148
|
#seq = 0;
|
|
10819
11149
|
#droppedInputRequests = 0;
|
|
11150
|
+
#actionsFromGateway = false;
|
|
11151
|
+
#gatewayClientId = "";
|
|
10820
11152
|
peer;
|
|
10821
11153
|
cloud;
|
|
10822
11154
|
options;
|
|
@@ -10832,7 +11164,24 @@ class WakePipe {
|
|
|
10832
11164
|
});
|
|
10833
11165
|
}
|
|
10834
11166
|
get registry() {
|
|
10835
|
-
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;
|
|
10836
11185
|
}
|
|
10837
11186
|
async start(clientId) {
|
|
10838
11187
|
this.#started = false;
|
|
@@ -10847,19 +11196,22 @@ class WakePipe {
|
|
|
10847
11196
|
}
|
|
10848
11197
|
const saved = readPipeState(loaded, this.options.log);
|
|
10849
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
|
+
}
|
|
10850
11203
|
let chatUri;
|
|
10851
11204
|
try {
|
|
10852
11205
|
chatUri = await this.#resumeSession(session.sessionUri);
|
|
10853
11206
|
} catch (error) {
|
|
10854
11207
|
if (cloudOperationFailureCode(error) === "AGENT_NOT_MAPPED") {
|
|
10855
|
-
|
|
11208
|
+
this.#park(key, session.sessionUri, error);
|
|
11209
|
+
continue;
|
|
10856
11210
|
}
|
|
10857
11211
|
throw error;
|
|
10858
11212
|
}
|
|
10859
11213
|
this.#subscribed.delete(session.sessionUri);
|
|
10860
11214
|
this.peer.notify("unsubscribe", { channel: session.sessionUri });
|
|
10861
|
-
if (session.chatUri !== undefined && chatUri !== session.chatUri)
|
|
10862
|
-
throw new Error("ahp-host: saved session answered a different chat");
|
|
10863
11215
|
this.#sessions.set(key, { sessionUri: session.sessionUri, chatUri });
|
|
10864
11216
|
}
|
|
10865
11217
|
const interrupted = [];
|
|
@@ -10911,12 +11263,25 @@ class WakePipe {
|
|
|
10911
11263
|
for (const id of this.#pendingInitialize.splice(0))
|
|
10912
11264
|
this.#initializeAnswer(id);
|
|
10913
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
|
+
}
|
|
10914
11272
|
#initialize(id, params) {
|
|
10915
11273
|
const offered = typeof params === "object" && params !== null && Array.isArray(params.protocolVersions) ? params.protocolVersions.filter((version) => typeof version === "string") : [];
|
|
10916
11274
|
if (!offered.includes(SUPPORTED_PROTOCOL)) {
|
|
10917
11275
|
this.cloud.reply(id, { error: { code: -32005, message: "UnsupportedProtocolVersion", data: { supportedVersions: [SUPPORTED_PROTOCOL] } } });
|
|
10918
11276
|
return;
|
|
10919
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;
|
|
10920
11285
|
if (!this.#started) {
|
|
10921
11286
|
this.#pendingInitialize.push(id);
|
|
10922
11287
|
return;
|
|
@@ -10925,10 +11290,17 @@ class WakePipe {
|
|
|
10925
11290
|
}
|
|
10926
11291
|
#initializeAnswer(id) {
|
|
10927
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
|
+
};
|
|
10928
11299
|
this.cloud.reply(id, { result: {
|
|
10929
11300
|
protocolVersion: SUPPORTED_PROTOCOL,
|
|
10930
11301
|
serverSeq: 0,
|
|
10931
|
-
...handshake === undefined ? {} : { serverInfo: handshake.plugin
|
|
11302
|
+
...handshake === undefined ? {} : { serverInfo: handshake.plugin },
|
|
11303
|
+
...Object.keys(meta).length === 0 ? {} : { _meta: meta },
|
|
10932
11304
|
snapshots: []
|
|
10933
11305
|
} });
|
|
10934
11306
|
}
|
|
@@ -10942,8 +11314,7 @@ class WakePipe {
|
|
|
10942
11314
|
if (this.#storeError === undefined) {
|
|
10943
11315
|
this.#storeError = new Error("ahp-host: durable state write failed", { cause: error });
|
|
10944
11316
|
for (const turn of this.#active.values()) {
|
|
10945
|
-
|
|
10946
|
-
this.#stopRenewal(turn);
|
|
11317
|
+
turn.cancelled = true;
|
|
10947
11318
|
}
|
|
10948
11319
|
this.options.log.error(`${this.#storeError.message}: ${String(error)}`);
|
|
10949
11320
|
}
|
|
@@ -10951,13 +11322,6 @@ class WakePipe {
|
|
|
10951
11322
|
});
|
|
10952
11323
|
return this.#writes;
|
|
10953
11324
|
}
|
|
10954
|
-
resolveToolToken(context, nowMs = Date.now()) {
|
|
10955
|
-
try {
|
|
10956
|
-
return { ok: true, ...this.vault.resolveForToolCall(context, nowMs) };
|
|
10957
|
-
} catch {
|
|
10958
|
-
return { ok: false, code: "TOKEN_EXPIRED_OR_REVOKED" };
|
|
10959
|
-
}
|
|
10960
|
-
}
|
|
10961
11325
|
async#revoke(id, params) {
|
|
10962
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";
|
|
10963
11327
|
if (!ok) {
|
|
@@ -10966,11 +11330,9 @@ class WakePipe {
|
|
|
10966
11330
|
return;
|
|
10967
11331
|
}
|
|
10968
11332
|
const member = params.agentMemberId;
|
|
10969
|
-
this.vault.revokeMember(this.options.workspaceId, member);
|
|
10970
11333
|
for (const turn of this.#active.values()) {
|
|
10971
11334
|
if (turn.workspaceId === this.options.workspaceId && turn.agentMemberId === member) {
|
|
10972
11335
|
turn.cancelled = true;
|
|
10973
|
-
this.#stopRenewal(turn);
|
|
10974
11336
|
}
|
|
10975
11337
|
}
|
|
10976
11338
|
const reports = [];
|
|
@@ -11021,8 +11383,13 @@ class WakePipe {
|
|
|
11021
11383
|
meta: frame._meta
|
|
11022
11384
|
}, {
|
|
11023
11385
|
agents: this.options.agents,
|
|
11386
|
+
memberOf: (uri) => this.agentMemberOf(uri),
|
|
11024
11387
|
peer: this.peer,
|
|
11025
|
-
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)
|
|
11026
11393
|
});
|
|
11027
11394
|
this.cloud.hostRequestAnswer(requestId, answer);
|
|
11028
11395
|
return;
|
|
@@ -11048,6 +11415,7 @@ class WakePipe {
|
|
|
11048
11415
|
return;
|
|
11049
11416
|
}
|
|
11050
11417
|
try {
|
|
11418
|
+
let snapshot;
|
|
11051
11419
|
if (decision.operation === "createSession") {
|
|
11052
11420
|
const agent = this.options.agents.get(decision.meta.agentMemberId);
|
|
11053
11421
|
if (agent === undefined)
|
|
@@ -11055,7 +11423,13 @@ class WakePipe {
|
|
|
11055
11423
|
let winnerUri;
|
|
11056
11424
|
let sessionUri;
|
|
11057
11425
|
try {
|
|
11058
|
-
sessionUri = await this.options.startSession({
|
|
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) => {
|
|
11059
11433
|
if (this.options.store?.reserve !== undefined) {
|
|
11060
11434
|
const resolved = await this.options.store.reserve(decision.sessionKey, uri);
|
|
11061
11435
|
this.#sessions.set(decision.sessionKey, { sessionUri: resolved });
|
|
@@ -11078,6 +11452,7 @@ class WakePipe {
|
|
|
11078
11452
|
throw new Error("ahp-host: created session differs from its durable reservation");
|
|
11079
11453
|
const chatUri = winnerUri !== undefined ? await this.#resumeSession(sessionUri) : await this.#subscribeSession(sessionUri);
|
|
11080
11454
|
this.#sessions.set(decision.sessionKey, { sessionUri, chatUri });
|
|
11455
|
+
this.#live.set(sessionUri, Promise.resolve());
|
|
11081
11456
|
await this.#save();
|
|
11082
11457
|
await this.#status({
|
|
11083
11458
|
event: "session/ready",
|
|
@@ -11092,13 +11467,24 @@ class WakePipe {
|
|
|
11092
11467
|
});
|
|
11093
11468
|
} else if (decision.operation === "subscribe") {
|
|
11094
11469
|
const sessionUri = decision.frame.params.channel;
|
|
11095
|
-
const
|
|
11096
|
-
|
|
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 } } };
|
|
11097
11475
|
} else {
|
|
11098
|
-
await this.#sendTurn(decision.sessionKey, decision.frame,
|
|
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 });
|
|
11099
11487
|
}
|
|
11100
|
-
if (id !== undefined)
|
|
11101
|
-
this.cloud.answer(id, { ok: true });
|
|
11102
11488
|
} catch (error) {
|
|
11103
11489
|
const code = cloudOperationFailureCode(error);
|
|
11104
11490
|
this.options.log.error(`ahp-host: cloud operation ${decision.operation} failed (${code}): ${String(error)}`);
|
|
@@ -11106,6 +11492,21 @@ class WakePipe {
|
|
|
11106
11492
|
this.cloud.answer(id, { ok: false, code });
|
|
11107
11493
|
}
|
|
11108
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
|
+
}
|
|
11109
11510
|
async#resumeSession(sessionUri) {
|
|
11110
11511
|
const resumed = await this.options.startSession({ owner: this.options.owner, resume: sessionUri });
|
|
11111
11512
|
if (resumed !== sessionUri)
|
|
@@ -11115,16 +11516,18 @@ class WakePipe {
|
|
|
11115
11516
|
async#subscribeSession(sessionUri) {
|
|
11116
11517
|
const answer = await this.peer.request("subscribe", { channel: sessionUri }, REQUEST_TIMEOUT_MS);
|
|
11117
11518
|
this.#subscribed.add(sessionUri);
|
|
11519
|
+
this.#rememberToolsServer(sessionUri, answer?.snapshot?.state?.customizations);
|
|
11520
|
+
this.#rememberPublishedToolsAnswer(sessionUri, answer?.snapshot?.state);
|
|
11118
11521
|
const chatUri = answer?.snapshot?.state?.defaultChat;
|
|
11119
11522
|
if (typeof chatUri !== "string" || chatUri.length === 0) {
|
|
11120
11523
|
throw new Error(`ahp-host: ${sessionUri} answered no defaultChat`);
|
|
11121
11524
|
}
|
|
11122
11525
|
return chatUri;
|
|
11123
11526
|
}
|
|
11124
|
-
async#sendTurn(key, frame, meta,
|
|
11527
|
+
async#sendTurn(key, frame, meta, turnId) {
|
|
11125
11528
|
const mapped = this.#sessions.get(key);
|
|
11126
|
-
if (mapped?.chatUri === undefined ||
|
|
11127
|
-
throw new Error("ahp-host: a turn reached dispatch without its mapping
|
|
11529
|
+
if (mapped?.chatUri === undefined || turnId === undefined) {
|
|
11530
|
+
throw new Error("ahp-host: a turn reached dispatch without its mapping or turn id");
|
|
11128
11531
|
}
|
|
11129
11532
|
const seen = this.#dispatched.get(key) ?? new Set;
|
|
11130
11533
|
const attempt = attemptKey(meta.deliveryId, turnId);
|
|
@@ -11132,19 +11535,16 @@ class WakePipe {
|
|
|
11132
11535
|
const last = this.#lastStatus.get(attempt);
|
|
11133
11536
|
await this.#writes;
|
|
11134
11537
|
if (last !== undefined)
|
|
11135
|
-
this
|
|
11538
|
+
this.#send(last);
|
|
11136
11539
|
return;
|
|
11137
11540
|
}
|
|
11138
|
-
if (this.options.tokenExpiresAt(token) === undefined)
|
|
11139
|
-
throw new FrameRefusal("ahp-host: an agent token whose expiry cannot be read");
|
|
11140
11541
|
if (this.options.admitTurn !== undefined)
|
|
11141
|
-
await this.options.admitTurn(meta,
|
|
11542
|
+
await this.options.admitTurn(meta, meta.readBearer);
|
|
11543
|
+
await this.#ensureLive(mapped.sessionUri, mapped.chatUri);
|
|
11142
11544
|
const running = this.#active.get(key);
|
|
11143
11545
|
if (running !== undefined) {
|
|
11144
11546
|
if (running.deliveryId === meta.deliveryId) {
|
|
11145
|
-
this.vault.clearTurn(running.sessionUri, running.turnId);
|
|
11146
11547
|
running.cancelled = true;
|
|
11147
|
-
this.#stopRenewal(running);
|
|
11148
11548
|
}
|
|
11149
11549
|
const queued = this.#queued.get(key) ?? [];
|
|
11150
11550
|
for (const old of queued) {
|
|
@@ -11155,35 +11555,20 @@ class WakePipe {
|
|
|
11155
11555
|
this.#dispatched.set(key, seen);
|
|
11156
11556
|
const queue = queued.filter((one) => one.meta.deliveryId !== meta.deliveryId || one.turnId === turnId);
|
|
11157
11557
|
if (!queue.some((one) => one.meta.deliveryId === meta.deliveryId))
|
|
11158
|
-
queue.push({ frame, meta,
|
|
11558
|
+
queue.push({ frame, meta, turnId });
|
|
11159
11559
|
this.#queued.set(key, queue);
|
|
11160
11560
|
await this.#save();
|
|
11161
11561
|
return;
|
|
11162
11562
|
}
|
|
11163
|
-
await this.#dispatch(key, frame, meta,
|
|
11563
|
+
await this.#dispatch(key, frame, meta, turnId);
|
|
11164
11564
|
}
|
|
11165
|
-
async#dispatch(key, frame, meta,
|
|
11565
|
+
async#dispatch(key, frame, meta, turnId) {
|
|
11166
11566
|
const mapped = this.#sessions.get(key);
|
|
11167
11567
|
if (mapped?.chatUri === undefined)
|
|
11168
11568
|
throw new Error("ahp-host: dispatch has no mapped chat");
|
|
11169
11569
|
if (this.#activeForChat(mapped.sessionUri, mapped.chatUri).length > 0) {
|
|
11170
11570
|
throw new Error("ahp-host: wake already active for this session and chat");
|
|
11171
11571
|
}
|
|
11172
|
-
const expiresAtMs = this.options.tokenExpiresAt(token);
|
|
11173
|
-
if (expiresAtMs === undefined)
|
|
11174
|
-
throw new FrameRefusal("ahp-host: an agent token whose expiry cannot be read");
|
|
11175
|
-
this.vault.bindActiveTurn({
|
|
11176
|
-
sessionId: mapped.sessionUri,
|
|
11177
|
-
chatId: mapped.chatUri,
|
|
11178
|
-
turnId,
|
|
11179
|
-
deliveryId: meta.deliveryId,
|
|
11180
|
-
threadRef: meta.threadRef,
|
|
11181
|
-
...meta.afterMessageId === undefined ? {} : { afterMessageId: meta.afterMessageId },
|
|
11182
|
-
workspaceId: meta.workspaceId,
|
|
11183
|
-
agentMemberId: meta.agentMemberId,
|
|
11184
|
-
token,
|
|
11185
|
-
expiresAtMs
|
|
11186
|
-
});
|
|
11187
11572
|
const active = {
|
|
11188
11573
|
key,
|
|
11189
11574
|
deliveryId: meta.deliveryId,
|
|
@@ -11196,8 +11581,7 @@ class WakePipe {
|
|
|
11196
11581
|
clientSeq: dispatchClientSeq(frame),
|
|
11197
11582
|
cancelled: false,
|
|
11198
11583
|
stopReason: undefined,
|
|
11199
|
-
finishing: false
|
|
11200
|
-
renewalTimer: undefined
|
|
11584
|
+
finishing: false
|
|
11201
11585
|
};
|
|
11202
11586
|
const seen = this.#dispatched.get(key) ?? new Set;
|
|
11203
11587
|
seen.add(attemptKey(meta.deliveryId, turnId));
|
|
@@ -11221,57 +11605,127 @@ class WakePipe {
|
|
|
11221
11605
|
await this.#next(active);
|
|
11222
11606
|
return;
|
|
11223
11607
|
}
|
|
11224
|
-
this.#scheduleRenewal(active, expiresAtMs);
|
|
11225
11608
|
if (!this.#subscribed.has(mapped.chatUri)) {
|
|
11226
11609
|
this.#subscribed.add(mapped.chatUri);
|
|
11227
11610
|
this.peer.request("subscribe", { channel: mapped.chatUri }, REQUEST_TIMEOUT_MS);
|
|
11228
11611
|
}
|
|
11229
11612
|
this.peer.notify("dispatchAction", { ...frame.params, clientSeq: ++this.#seq });
|
|
11230
11613
|
}
|
|
11231
|
-
#
|
|
11232
|
-
|
|
11233
|
-
|
|
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);
|
|
11619
|
+
}
|
|
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")
|
|
11628
|
+
return;
|
|
11629
|
+
this.cloud.authRequired({ channel: sessionUri, resource: server.resource, reason: "expired" });
|
|
11234
11630
|
}
|
|
11235
|
-
#
|
|
11236
|
-
const
|
|
11237
|
-
if (
|
|
11631
|
+
#toolsServerOf(sessionUri) {
|
|
11632
|
+
const host = this.options.hostTools;
|
|
11633
|
+
if (host === undefined)
|
|
11238
11634
|
return;
|
|
11239
|
-
|
|
11240
|
-
|
|
11635
|
+
const customizationId = this.#toolsIds.get(sessionUri);
|
|
11636
|
+
return customizationId === undefined ? undefined : { resource: host.resource, customizationId };
|
|
11241
11637
|
}
|
|
11242
|
-
|
|
11243
|
-
|
|
11244
|
-
|
|
11245
|
-
if (this.#active.get(turn.key) !== turn || !this.resolveToolToken(context).ok)
|
|
11638
|
+
#rememberToolsServer(sessionUri, customizations) {
|
|
11639
|
+
const host = this.options.hostTools;
|
|
11640
|
+
if (host === undefined || !Array.isArray(customizations))
|
|
11246
11641
|
return;
|
|
11247
|
-
|
|
11248
|
-
|
|
11249
|
-
|
|
11250
|
-
|
|
11251
|
-
|
|
11252
|
-
|
|
11253
|
-
|
|
11254
|
-
|
|
11255
|
-
|
|
11256
|
-
}
|
|
11257
|
-
const expiresAtMs = this.options.tokenExpiresAt(answer.agentToken);
|
|
11258
|
-
if (expiresAtMs === undefined || !Number.isFinite(expiresAtMs) || expiresAtMs <= previousExpiry || expiresAtMs <= Date.now()) {
|
|
11259
|
-
return this.#renewalError(turn, "TOKEN_RENEWAL_INVALID");
|
|
11260
|
-
}
|
|
11261
|
-
if (!this.vault.renewActiveTurn(context, answer.agentToken, expiresAtMs))
|
|
11262
|
-
return this.#renewalError(turn, "TOKEN_RENEWAL_STALE");
|
|
11263
|
-
this.#scheduleRenewal(turn, expiresAtMs);
|
|
11264
|
-
} catch {
|
|
11265
|
-
this.#renewalError(turn, "TOKEN_RENEWAL_FAILED");
|
|
11266
|
-
}
|
|
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 });
|
|
11267
11652
|
}
|
|
11268
|
-
#
|
|
11269
|
-
this.options.
|
|
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
|
+
});
|
|
11270
11677
|
}
|
|
11271
|
-
#
|
|
11272
|
-
|
|
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
|
+
});
|
|
11273
11711
|
}
|
|
11274
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);
|
|
11275
11729
|
const params = message?.params;
|
|
11276
11730
|
const action = params?.action;
|
|
11277
11731
|
if (action === undefined || typeof params?.channel !== "string")
|
|
@@ -11308,8 +11762,6 @@ class WakePipe {
|
|
|
11308
11762
|
turn.stopStatusCode = malformedApproval ? "INPUT_REQUEST_UNATTRIBUTED" : turn.stopReason;
|
|
11309
11763
|
if (malformedApproval)
|
|
11310
11764
|
turn.stopDetail = `INPUT_REQUEST_UNATTRIBUTED:${requestId}`.slice(0, 256);
|
|
11311
|
-
this.vault.clearTurn(turn.sessionUri, turn.turnId);
|
|
11312
|
-
this.#stopRenewal(turn);
|
|
11313
11765
|
this.peer.notify("dispatchAction", {
|
|
11314
11766
|
channel: turn.chatUri,
|
|
11315
11767
|
clientSeq: ++this.#seq,
|
|
@@ -11332,14 +11784,13 @@ class WakePipe {
|
|
|
11332
11784
|
if (action.type === "chat/turnStarted") {
|
|
11333
11785
|
if (turn.stopReason !== undefined)
|
|
11334
11786
|
return;
|
|
11335
|
-
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);
|
|
11336
11788
|
} else if (action.type === "chat/turnComplete" || action.type === "chat/turnCancelled" || action.type === "chat/error") {
|
|
11337
11789
|
turn.finishing = true;
|
|
11338
11790
|
const finished = action.type === "chat/turnComplete" && turn.stopReason === undefined;
|
|
11339
|
-
const
|
|
11340
|
-
const
|
|
11341
|
-
|
|
11342
|
-
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");
|
|
11343
11794
|
await this.#status(finished ? { event: "chat/turnComplete", ...base, turnState: "finished", statusCode: "TURN_FINISHED" } : {
|
|
11344
11795
|
event: "x-hh/turnFailed",
|
|
11345
11796
|
...base,
|
|
@@ -11347,7 +11798,7 @@ class WakePipe {
|
|
|
11347
11798
|
statusCode,
|
|
11348
11799
|
errorCode,
|
|
11349
11800
|
...turn.stopDetail === undefined ? {} : { errorDetail: turn.stopDetail }
|
|
11350
|
-
});
|
|
11801
|
+
}, turn.startedAtMs);
|
|
11351
11802
|
this.#active.delete(turn.key);
|
|
11352
11803
|
await this.#next(turn);
|
|
11353
11804
|
}
|
|
@@ -11362,18 +11813,24 @@ class WakePipe {
|
|
|
11362
11813
|
this.#subscribed.delete(done.sessionUri);
|
|
11363
11814
|
this.peer.notify("unsubscribe", { channel: done.chatUri });
|
|
11364
11815
|
this.peer.notify("unsubscribe", { channel: done.sessionUri });
|
|
11816
|
+
this.#live.delete(done.sessionUri);
|
|
11365
11817
|
return;
|
|
11366
11818
|
}
|
|
11367
|
-
const
|
|
11368
|
-
|
|
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) {
|
|
11369
11823
|
try {
|
|
11370
|
-
await this.#dispatch(done.key, next.frame, next.meta, next.
|
|
11824
|
+
await this.#dispatch(done.key, next.frame, next.meta, next.turnId);
|
|
11371
11825
|
return;
|
|
11372
11826
|
} catch (error) {
|
|
11373
11827
|
if (this.#storeError !== undefined)
|
|
11374
11828
|
throw error;
|
|
11375
11829
|
}
|
|
11376
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
|
+
}
|
|
11377
11834
|
const session = this.#sessions.get(done.key);
|
|
11378
11835
|
await this.#status({
|
|
11379
11836
|
event: "x-hh/turnFailed",
|
|
@@ -11385,21 +11842,29 @@ class WakePipe {
|
|
|
11385
11842
|
turnId: next.turnId,
|
|
11386
11843
|
turnState: "error",
|
|
11387
11844
|
statusCode: "QUEUED_WAKE_NOT_RUN",
|
|
11388
|
-
errorCode: "
|
|
11845
|
+
errorCode: unmeasurable ? "ASK_UNSIGNED" : "ASK_STALE"
|
|
11389
11846
|
});
|
|
11390
11847
|
await this.#next(done);
|
|
11391
11848
|
}
|
|
11392
|
-
#status(frame) {
|
|
11849
|
+
#status(frame, startedAtMs) {
|
|
11393
11850
|
const checked = parseHostToCloudFrame(frame);
|
|
11394
11851
|
this.#lastStatus.set(checked.turnId === undefined ? checked.deliveryId : attemptKey(checked.deliveryId, checked.turnId), checked);
|
|
11395
11852
|
if (this.options.store === undefined) {
|
|
11396
|
-
this
|
|
11853
|
+
this.#send(checked, startedAtMs);
|
|
11397
11854
|
return Promise.resolve();
|
|
11398
11855
|
}
|
|
11399
11856
|
return this.#save().then(() => {
|
|
11400
|
-
this
|
|
11857
|
+
this.#send(checked, startedAtMs);
|
|
11401
11858
|
});
|
|
11402
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
|
+
}
|
|
11403
11868
|
}
|
|
11404
11869
|
|
|
11405
11870
|
// ../ahp-host/src/records-store.ts
|
|
@@ -11412,8 +11877,47 @@ var mappingSchema = object({
|
|
|
11412
11877
|
sessionUri: string2().regex(SESSION_URI)
|
|
11413
11878
|
}).strict();
|
|
11414
11879
|
var mappingId = (key) => `session-${createHash2("sha256").update(key).digest("hex").slice(0, 32)}`;
|
|
11415
|
-
|
|
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) {
|
|
11416
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
|
+
};
|
|
11417
11921
|
const readMapping = (raw) => {
|
|
11418
11922
|
const parsed = mappingSchema.safeParse(raw);
|
|
11419
11923
|
if (!parsed.success)
|
|
@@ -11499,11 +12003,22 @@ function recordsPipeStore(records, owner, sessionOwner, log) {
|
|
|
11499
12003
|
}
|
|
11500
12004
|
if (record?.version === 1)
|
|
11501
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
|
+
}
|
|
11502
12015
|
return { sessions: [...mappings], dispatched: state.dispatched, lastStatus: state.lastStatus };
|
|
11503
12016
|
},
|
|
11504
12017
|
save: async (state) => {
|
|
11505
|
-
for (const [key, session] of state.sessions)
|
|
12018
|
+
for (const [key, session] of state.sessions) {
|
|
11506
12019
|
await publish(key, session);
|
|
12020
|
+
await keepChat(key, session);
|
|
12021
|
+
}
|
|
11507
12022
|
await saveAttempts(state);
|
|
11508
12023
|
}
|
|
11509
12024
|
};
|
|
@@ -11512,6 +12027,12 @@ function recordsPipeStore(records, owner, sessionOwner, log) {
|
|
|
11512
12027
|
// ../ahp-host/src/link.ts
|
|
11513
12028
|
import { randomUUID } from "node:crypto";
|
|
11514
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
|
+
};
|
|
11515
12036
|
function createCloudLink(options) {
|
|
11516
12037
|
const { log, receive } = options;
|
|
11517
12038
|
let stopped = false;
|
|
@@ -11584,8 +12105,9 @@ function createCloudLink(options) {
|
|
|
11584
12105
|
if (response.jsonrpc === "2.0" && "result" in response && !("error" in response)) {
|
|
11585
12106
|
entry.resolve(response.result);
|
|
11586
12107
|
} else {
|
|
11587
|
-
|
|
11588
|
-
|
|
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}`));
|
|
11589
12111
|
}
|
|
11590
12112
|
return;
|
|
11591
12113
|
}
|
|
@@ -11615,10 +12137,10 @@ function createCloudLink(options) {
|
|
|
11615
12137
|
closeSocket(connection.socket);
|
|
11616
12138
|
schedule();
|
|
11617
12139
|
};
|
|
11618
|
-
const refused = (code) => {
|
|
12140
|
+
const refused = (code, reason) => {
|
|
11619
12141
|
if (stopped || current !== connection)
|
|
11620
12142
|
return;
|
|
11621
|
-
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}`}`);
|
|
11622
12144
|
close();
|
|
11623
12145
|
};
|
|
11624
12146
|
try {
|
|
@@ -11639,8 +12161,8 @@ function createCloudLink(options) {
|
|
|
11639
12161
|
});
|
|
11640
12162
|
socket.addEventListener("error", () => lost("CONTROL_SOCKET_ERROR"));
|
|
11641
12163
|
socket.addEventListener("close", (event) => {
|
|
11642
|
-
if (event.code === 4003)
|
|
11643
|
-
refused(
|
|
12164
|
+
if (event.code === 4003 || event.code === 4004)
|
|
12165
|
+
refused(event.code, event.reason);
|
|
11644
12166
|
else
|
|
11645
12167
|
lost("CONTROL_SOCKET_CLOSED");
|
|
11646
12168
|
});
|
|
@@ -11680,7 +12202,9 @@ function createCloudLink(options) {
|
|
|
11680
12202
|
answer: (id, outcome) => send(outcome.ok ? { jsonrpc: "2.0", id, result: null } : { jsonrpc: "2.0", id, error: { code: -32000, message: outcome.code } }),
|
|
11681
12203
|
reply: (id, answer) => send("result" in answer ? { jsonrpc: "2.0", id, result: answer.result } : { jsonrpc: "2.0", id, error: answer.error }),
|
|
11682
12204
|
status: (frame) => send({ jsonrpc: "2.0", method: "x-hightea/status", params: frame }),
|
|
11683
|
-
|
|
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 }),
|
|
11684
12208
|
sourcePush: (params) => request(`push:${randomUUID()}`, "x-hightea/source/push", params),
|
|
11685
12209
|
hostRequestAnswer: (id, outcome) => void send({ jsonrpc: "2.0", id, ...hostAnswerFrame(outcome) })
|
|
11686
12210
|
};
|
|
@@ -11688,32 +12212,204 @@ function createCloudLink(options) {
|
|
|
11688
12212
|
|
|
11689
12213
|
// ../ahp-host/src/km-source.ts
|
|
11690
12214
|
import { spawn as spawn2 } from "node:child_process";
|
|
11691
|
-
import { createHash as createHash3
|
|
12215
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
11692
12216
|
import { createInterface as createInterface2 } from "node:readline";
|
|
11693
12217
|
|
|
11694
|
-
// ../ahp-host/src/
|
|
11695
|
-
import {
|
|
11696
|
-
|
|
11697
|
-
var
|
|
11698
|
-
|
|
11699
|
-
|
|
11700
|
-
|
|
11701
|
-
|
|
11702
|
-
|
|
11703
|
-
|
|
11704
|
-
|
|
11705
|
-
|
|
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;
|
|
11706
12235
|
}
|
|
12236
|
+
return { dropped: queue.slice(0, head), batch };
|
|
11707
12237
|
}
|
|
11708
|
-
|
|
11709
|
-
|
|
11710
|
-
|
|
11711
|
-
|
|
11712
|
-
|
|
11713
|
-
|
|
11714
|
-
|
|
11715
|
-
|
|
11716
|
-
|
|
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
|
+
|
|
12388
|
+
// ../ahp-host/src/page-serve.ts
|
|
12389
|
+
import { spawn } from "node:child_process";
|
|
12390
|
+
import { createInterface } from "node:readline";
|
|
12391
|
+
var STDERR_MAX_BYTES = 64 * 1024;
|
|
12392
|
+
var KILL_GRACE_MS = 2000;
|
|
12393
|
+
var ANSWER_MAX_BYTES = 16 * 1024 * 1024;
|
|
12394
|
+
var ASK_QUEUE_MAX = 8;
|
|
12395
|
+
var ASK_QUEUE_WAIT_MS = 5000;
|
|
12396
|
+
|
|
12397
|
+
class PageServeFault extends Error {
|
|
12398
|
+
code;
|
|
12399
|
+
constructor(code, message) {
|
|
12400
|
+
super(message);
|
|
12401
|
+
this.code = code;
|
|
12402
|
+
}
|
|
12403
|
+
}
|
|
12404
|
+
function signalGroup(child, signal) {
|
|
12405
|
+
if (child.pid === undefined)
|
|
12406
|
+
return;
|
|
12407
|
+
try {
|
|
12408
|
+
process.kill(-child.pid, signal);
|
|
12409
|
+
} catch {}
|
|
12410
|
+
}
|
|
12411
|
+
function pageServeWhy(exit) {
|
|
12412
|
+
const said = exit.stderr.trim().split(`
|
|
11717
12413
|
`).filter((line) => line !== "").pop();
|
|
11718
12414
|
const status = exit.code === null ? "on a signal" : `exit ${exit.code}`;
|
|
11719
12415
|
return said === undefined ? status : `${status}: ${said.slice(0, 400)}`;
|
|
@@ -11726,6 +12422,7 @@ var openPageServe = (argv, signal) => {
|
|
|
11726
12422
|
let stderr = "";
|
|
11727
12423
|
let end;
|
|
11728
12424
|
let pending;
|
|
12425
|
+
const queue = [];
|
|
11729
12426
|
let seq = 0;
|
|
11730
12427
|
let settle = () => {
|
|
11731
12428
|
return;
|
|
@@ -11742,6 +12439,37 @@ var openPageServe = (argv, signal) => {
|
|
|
11742
12439
|
clearTimeout(held.timer);
|
|
11743
12440
|
held.reject(error);
|
|
11744
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
|
+
}
|
|
11745
12473
|
const fault = (code, message) => {
|
|
11746
12474
|
refusePending(new PageServeFault(code, message));
|
|
11747
12475
|
signalGroup(child, "SIGKILL");
|
|
@@ -11780,6 +12508,7 @@ var openPageServe = (argv, signal) => {
|
|
|
11780
12508
|
...typeof refusal.hint === "string" ? { hint: refusal.hint } : {}
|
|
11781
12509
|
}
|
|
11782
12510
|
});
|
|
12511
|
+
drain();
|
|
11783
12512
|
return;
|
|
11784
12513
|
}
|
|
11785
12514
|
if (frame.page === undefined && frame.progress !== undefined) {
|
|
@@ -11787,6 +12516,7 @@ var openPageServe = (argv, signal) => {
|
|
|
11787
12516
|
if (held.timer !== undefined)
|
|
11788
12517
|
clearTimeout(held.timer);
|
|
11789
12518
|
held.resolve({ ...rss === undefined ? {} : { rss }, progress: frame.progress });
|
|
12519
|
+
drain();
|
|
11790
12520
|
return;
|
|
11791
12521
|
}
|
|
11792
12522
|
if (frame.page === null || typeof frame.page !== "object" || Array.isArray(frame.page)) {
|
|
@@ -11806,6 +12536,7 @@ var openPageServe = (argv, signal) => {
|
|
|
11806
12536
|
if (held.timer !== undefined)
|
|
11807
12537
|
clearTimeout(held.timer);
|
|
11808
12538
|
held.resolve({ pages: held.pages, ...rss === undefined ? {} : { rss } });
|
|
12539
|
+
drain();
|
|
11809
12540
|
};
|
|
11810
12541
|
createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY }).on("line", answer);
|
|
11811
12542
|
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
@@ -11826,6 +12557,11 @@ hightea-page-serve: ${error.message}`;
|
|
|
11826
12557
|
signalGroup(child, "SIGKILL");
|
|
11827
12558
|
end = { code: killed === null ? code : null, stderr };
|
|
11828
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
|
+
}
|
|
11829
12565
|
settle(end);
|
|
11830
12566
|
resolve();
|
|
11831
12567
|
});
|
|
@@ -11848,21 +12584,34 @@ hightea-page-serve: ${error.message}`;
|
|
|
11848
12584
|
return Promise.reject(new PageServeFault("page-serve-reader-exited", `the reader is gone (${pageServeWhy(end)})`));
|
|
11849
12585
|
}
|
|
11850
12586
|
if (pending !== undefined) {
|
|
11851
|
-
|
|
11852
|
-
|
|
11853
|
-
|
|
11854
|
-
|
|
11855
|
-
|
|
11856
|
-
|
|
11857
|
-
|
|
11858
|
-
|
|
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: () => {
|
|
11859
12597
|
return;
|
|
11860
|
-
},
|
|
11861
|
-
reject: () => {
|
|
12598
|
+
}, reject: () => {
|
|
11862
12599
|
return;
|
|
11863
|
-
},
|
|
11864
|
-
|
|
11865
|
-
|
|
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
|
+
}
|
|
11866
12615
|
let settleAnswer = () => {
|
|
11867
12616
|
return;
|
|
11868
12617
|
};
|
|
@@ -11873,18 +12622,7 @@ hightea-page-serve: ${error.message}`;
|
|
|
11873
12622
|
settleAnswer = resolve;
|
|
11874
12623
|
failAnswer = reject;
|
|
11875
12624
|
});
|
|
11876
|
-
|
|
11877
|
-
mine.reject = failAnswer;
|
|
11878
|
-
pending = mine;
|
|
11879
|
-
mine.timer = setTimeout(() => {
|
|
11880
|
-
fault("page-serve-timeout", `the reader did not answer seq ${mine.seq} in ${timeoutMs} ms`);
|
|
11881
|
-
}, timeoutMs);
|
|
11882
|
-
try {
|
|
11883
|
-
child.stdin.write(JSON.stringify({ seq: mine.seq, request }) + `
|
|
11884
|
-
`);
|
|
11885
|
-
} catch (error) {
|
|
11886
|
-
fault("page-serve-write-failed", `the request could not be written: ${error instanceof Error ? error.message : String(error)}`);
|
|
11887
|
-
}
|
|
12625
|
+
begin(request, timeoutMs, settleAnswer, failAnswer);
|
|
11888
12626
|
return asked;
|
|
11889
12627
|
},
|
|
11890
12628
|
exited,
|
|
@@ -11898,7 +12636,6 @@ var GENERATIONS_KEPT = 8;
|
|
|
11898
12636
|
var GENERATION_MAX_MS = 15 * 60000;
|
|
11899
12637
|
var KM_PAGE_LIMIT = 1000;
|
|
11900
12638
|
var READ_ATTEMPTS = 3;
|
|
11901
|
-
var UNACKED_MAX = 1e4;
|
|
11902
12639
|
var FEED_RESTART_MS = 5000;
|
|
11903
12640
|
var PAGE_SERVE_RSS_CEILING = 512 * 1024 * 1024;
|
|
11904
12641
|
var NOTICE_PATIENCE_MS = 30000;
|
|
@@ -11932,8 +12669,7 @@ class ListRefused extends Error {
|
|
|
11932
12669
|
|
|
11933
12670
|
class KmSource {
|
|
11934
12671
|
sourceId;
|
|
11935
|
-
#
|
|
11936
|
-
#ordinal = 0n;
|
|
12672
|
+
#shell;
|
|
11937
12673
|
#reads = 0;
|
|
11938
12674
|
#current;
|
|
11939
12675
|
#kept = new Map;
|
|
@@ -11962,14 +12698,8 @@ class KmSource {
|
|
|
11962
12698
|
#noHeadSaid = false;
|
|
11963
12699
|
#dirty = false;
|
|
11964
12700
|
#pendingChangeAt;
|
|
12701
|
+
#pendingChangeSource;
|
|
11965
12702
|
#hintTimer;
|
|
11966
|
-
#queue = [];
|
|
11967
|
-
#inFlight = false;
|
|
11968
|
-
#pushTimer;
|
|
11969
|
-
#lastPushAt = -Infinity;
|
|
11970
|
-
#pushFailures = 0;
|
|
11971
|
-
#retryAt = -Infinity;
|
|
11972
|
-
#watching = true;
|
|
11973
12703
|
#watchTimer;
|
|
11974
12704
|
#watchFloor;
|
|
11975
12705
|
#watchRefresh;
|
|
@@ -12024,9 +12754,31 @@ class KmSource {
|
|
|
12024
12754
|
this.#watchRefresh = options.watchRefreshMs;
|
|
12025
12755
|
this.#now = options.now ?? Date.now;
|
|
12026
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
|
+
});
|
|
12027
12779
|
}
|
|
12028
12780
|
get epoch() {
|
|
12029
|
-
return this.#epoch;
|
|
12781
|
+
return this.#shell.epoch;
|
|
12030
12782
|
}
|
|
12031
12783
|
start() {
|
|
12032
12784
|
this.#reader();
|
|
@@ -12035,10 +12787,9 @@ class KmSource {
|
|
|
12035
12787
|
}
|
|
12036
12788
|
async stop() {
|
|
12037
12789
|
this.#stop.abort();
|
|
12790
|
+
this.#shell.stop();
|
|
12038
12791
|
if (this.#hintTimer !== undefined)
|
|
12039
12792
|
clearTimeout(this.#hintTimer);
|
|
12040
|
-
if (this.#pushTimer !== undefined)
|
|
12041
|
-
clearTimeout(this.#pushTimer);
|
|
12042
12793
|
this.#clearWatchRefresh();
|
|
12043
12794
|
if (this.#serveTimer !== undefined)
|
|
12044
12795
|
clearTimeout(this.#serveTimer);
|
|
@@ -12051,9 +12802,11 @@ class KmSource {
|
|
|
12051
12802
|
hint(line) {
|
|
12052
12803
|
if (line !== undefined) {
|
|
12053
12804
|
this.#noteHint(line);
|
|
12054
|
-
const
|
|
12055
|
-
if (
|
|
12056
|
-
this.#pendingChangeAt =
|
|
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
|
+
}
|
|
12057
12810
|
}
|
|
12058
12811
|
if (this.#stop.signal.aborted)
|
|
12059
12812
|
return;
|
|
@@ -12066,7 +12819,7 @@ class KmSource {
|
|
|
12066
12819
|
const rested = this.#readEndedAt + Math.max(this.#readTookMs * (1 / this.#duty - 1), floor) - this.#now();
|
|
12067
12820
|
const delay = Math.max(this.#hintCoalesce, rested);
|
|
12068
12821
|
const age = this.#pendingChangeAt === undefined ? undefined : this.#now() - this.#pendingChangeAt;
|
|
12069
|
-
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}`}`}`);
|
|
12070
12823
|
this.#hintTimer = setTimeout(() => {
|
|
12071
12824
|
this.#hintTimer = undefined;
|
|
12072
12825
|
this.#read(shortFloor).catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${describe2(error)}`));
|
|
@@ -12082,13 +12835,12 @@ class KmSource {
|
|
|
12082
12835
|
try {
|
|
12083
12836
|
switch (request.op) {
|
|
12084
12837
|
case "watch":
|
|
12085
|
-
this.#
|
|
12086
|
-
if (
|
|
12087
|
-
this.#pump();
|
|
12838
|
+
this.#shell.watch(request.args.on);
|
|
12839
|
+
if (request.args.on)
|
|
12088
12840
|
this.#armWatchRefresh();
|
|
12089
|
-
|
|
12841
|
+
else
|
|
12090
12842
|
this.#clearWatchRefresh();
|
|
12091
|
-
return { ...binding, op: "watch", outcome: "applied", body: { on: this.#watching } };
|
|
12843
|
+
return { ...binding, op: "watch", outcome: "applied", body: { on: this.#shell.watching } };
|
|
12092
12844
|
case "list":
|
|
12093
12845
|
return { ...binding, op: "list", outcome: "applied", ...this.#degraded ? { code: "SOURCE_READER_RESTARTING" } : {}, body: await this.#page(request.args, binding) };
|
|
12094
12846
|
case "read": {
|
|
@@ -12148,14 +12900,35 @@ class KmSource {
|
|
|
12148
12900
|
return page(next, rows);
|
|
12149
12901
|
}
|
|
12150
12902
|
async#assign(request, binding) {
|
|
12151
|
-
|
|
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;
|
|
12152
12907
|
const seat = this.#o.config.members[ownerMemberId];
|
|
12153
|
-
const expected = expectedOwner === null ? null : this.#nativeOf(expectedOwner);
|
|
12908
|
+
const expected = expectedOwner === undefined || expectedOwner === null ? null : this.#nativeOf(expectedOwner);
|
|
12154
12909
|
if (seat === undefined || expected === undefined)
|
|
12155
12910
|
return { ...binding, op: "assign", outcome: "refused", code: "AGENT_NOT_MAPPED" };
|
|
12156
12911
|
const key = this.#keyOf(address);
|
|
12157
12912
|
if (key === undefined)
|
|
12158
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
|
+
}
|
|
12159
12932
|
let env;
|
|
12160
12933
|
if (this.#o.config.serviceIdentity) {
|
|
12161
12934
|
try {
|
|
@@ -12171,7 +12944,7 @@ class KmSource {
|
|
|
12171
12944
|
return { ...binding, op: "assign", outcome: "unknown", code };
|
|
12172
12945
|
}
|
|
12173
12946
|
}
|
|
12174
|
-
const requester = { authority: `hightea:${
|
|
12947
|
+
const requester = { authority: `hightea:${binding.workspaceId}`, subject: callerMemberId };
|
|
12175
12948
|
const ran = await this.#yrd([
|
|
12176
12949
|
"issues",
|
|
12177
12950
|
"assign",
|
|
@@ -12340,6 +13113,7 @@ class KmSource {
|
|
|
12340
13113
|
}
|
|
12341
13114
|
this.#dirty = false;
|
|
12342
13115
|
this.#pendingChangeAt = undefined;
|
|
13116
|
+
this.#pendingChangeSource = undefined;
|
|
12343
13117
|
const began = this.#now();
|
|
12344
13118
|
const reading = this.#readOnce(scheduledAtIncrementalFloor, clientRead, awaitProjection).then((read) => {
|
|
12345
13119
|
this.#readFailures = 0;
|
|
@@ -12380,7 +13154,7 @@ class KmSource {
|
|
|
12380
13154
|
return Math.max(this.#watchFloor, 10 * p50);
|
|
12381
13155
|
}
|
|
12382
13156
|
#armWatchRefresh() {
|
|
12383
|
-
if (this.#stop.signal.aborted || !this.#watching || this.#watchTimer !== undefined)
|
|
13157
|
+
if (this.#stop.signal.aborted || !this.#shell.watching || this.#watchTimer !== undefined)
|
|
12384
13158
|
return;
|
|
12385
13159
|
const interval = this.#watchIntervalMs();
|
|
12386
13160
|
if (!(interval > 0))
|
|
@@ -12389,7 +13163,7 @@ class KmSource {
|
|
|
12389
13163
|
const wait = Math.max(0, interval - (this.#now() - since));
|
|
12390
13164
|
this.#watchTimer = setTimeout(() => {
|
|
12391
13165
|
this.#watchTimer = undefined;
|
|
12392
|
-
if (this.#stop.signal.aborted || !this.#watching)
|
|
13166
|
+
if (this.#stop.signal.aborted || !this.#shell.watching)
|
|
12393
13167
|
return;
|
|
12394
13168
|
if (this.#reading !== undefined) {
|
|
12395
13169
|
this.#armWatchRefresh();
|
|
@@ -12418,7 +13192,7 @@ class KmSource {
|
|
|
12418
13192
|
}
|
|
12419
13193
|
async#readOnce(atIncrementalFloor, clientRead, awaitProjection = false) {
|
|
12420
13194
|
for (let attempt = 1;; attempt++) {
|
|
12421
|
-
const generation = `${this.#epoch}.${++this.#reads}`;
|
|
13195
|
+
const generation = `${this.#shell.epoch}.${++this.#reads}`;
|
|
12422
13196
|
try {
|
|
12423
13197
|
const cursor = this.#cursor;
|
|
12424
13198
|
if (cursor !== undefined) {
|
|
@@ -12492,6 +13266,9 @@ class KmSource {
|
|
|
12492
13266
|
this.#wholeReadClearsNotice(result.head);
|
|
12493
13267
|
return this.#diff(generation, contentRevision(fresh), fresh);
|
|
12494
13268
|
}
|
|
13269
|
+
#omit(id, reason) {
|
|
13270
|
+
this.#o.log.error(`hightea-source: row ${id} omitted: ${reason}`);
|
|
13271
|
+
}
|
|
12495
13272
|
#collect(fresh, rows) {
|
|
12496
13273
|
for (const one of rows) {
|
|
12497
13274
|
const row = this.#row(one);
|
|
@@ -12502,7 +13279,7 @@ class KmSource {
|
|
|
12502
13279
|
const value = issue.path.reduce((part, key) => typeof part === "object" && part !== null ? Reflect.get(part, key) : undefined, row);
|
|
12503
13280
|
return issue.code === "too_big" && typeof value === "string" ? `${field} is ${value.length} chars, cap ${issue.maximum}` : `${field}: ${issue.message}`;
|
|
12504
13281
|
});
|
|
12505
|
-
this.#
|
|
13282
|
+
this.#omit(one.id, reasons.join("; "));
|
|
12506
13283
|
continue;
|
|
12507
13284
|
}
|
|
12508
13285
|
if (sourceFrameBytes(row) > SOURCE_PAGE_BUDGET_BYTES)
|
|
@@ -12719,7 +13496,14 @@ class KmSource {
|
|
|
12719
13496
|
if (extra.in_progress === flag && extra.in_progress_reason === (reason ?? null))
|
|
12720
13497
|
continue;
|
|
12721
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 };
|
|
12722
|
-
|
|
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 });
|
|
12723
13507
|
}
|
|
12724
13508
|
if (projection.source === "unreadable")
|
|
12725
13509
|
this.#o.log.error(`hightea-source: ${this.sourceId}: activity read unavailable; ${unknown} of ${fresh.size} materialized rows have unknown progress`);
|
|
@@ -12757,11 +13541,11 @@ class KmSource {
|
|
|
12757
13541
|
const now = fresh.get(address);
|
|
12758
13542
|
const was = last?.byAddress.get(address);
|
|
12759
13543
|
if (now === undefined) {
|
|
12760
|
-
observations.push({ position: this.#next(), change: { op: "delete", address } });
|
|
13544
|
+
observations.push({ position: this.#shell.next(), change: { op: "delete", address } });
|
|
12761
13545
|
continue;
|
|
12762
13546
|
}
|
|
12763
13547
|
if (last !== undefined && (was === undefined || was.row.version !== now.row.version || !sameColumns(was.row, now.row))) {
|
|
12764
|
-
const position = this.#next();
|
|
13548
|
+
const position = this.#shell.next();
|
|
12765
13549
|
observations.push({ position, change: { op: "upsert", row: now.row } });
|
|
12766
13550
|
byAddress.set(address, { key: now.key, row: now.row, at: BigInt(position.ordinal) });
|
|
12767
13551
|
} else {
|
|
@@ -12770,27 +13554,25 @@ class KmSource {
|
|
|
12770
13554
|
}
|
|
12771
13555
|
if (last === undefined && byAddress.size > 0) {
|
|
12772
13556
|
const first = byAddress.get(addresses[0]);
|
|
12773
|
-
const position = this.#next();
|
|
13557
|
+
const position = this.#shell.next();
|
|
12774
13558
|
observations.push({ position, change: { op: "upsert", row: first.row } });
|
|
12775
13559
|
byAddress.set(first.row.address, { ...first, at: BigInt(position.ordinal) });
|
|
12776
13560
|
}
|
|
12777
13561
|
return this.#commit(generation, snapshot, observations, byAddress);
|
|
12778
13562
|
}
|
|
12779
13563
|
#commit(generation, snapshot, observations, byAddress) {
|
|
12780
|
-
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() };
|
|
12781
13565
|
this.#current = read;
|
|
12782
13566
|
this.#kept.set(generation, read);
|
|
12783
13567
|
for (const [name, kept] of this.#kept) {
|
|
12784
13568
|
if (this.#kept.size > GENERATIONS_KEPT || this.#now() - kept.at > GENERATION_MAX_MS)
|
|
12785
13569
|
this.#kept.delete(name);
|
|
12786
13570
|
}
|
|
12787
|
-
this.#enqueue(observations);
|
|
13571
|
+
this.#shell.enqueue(observations);
|
|
13572
|
+
if (observations.length > 0)
|
|
13573
|
+
this.#o.onRecords?.(observations);
|
|
12788
13574
|
return read;
|
|
12789
13575
|
}
|
|
12790
|
-
#next() {
|
|
12791
|
-
this.#ordinal++;
|
|
12792
|
-
return { epoch: this.#epoch, ordinal: String(this.#ordinal) };
|
|
12793
|
-
}
|
|
12794
13576
|
#addressOf(one) {
|
|
12795
13577
|
return `issue:${this.sourceId}/${beadNumberFromPath(one.path) ?? one.id}`;
|
|
12796
13578
|
}
|
|
@@ -12901,84 +13683,6 @@ class KmSource {
|
|
|
12901
13683
|
const named = address.slice(prefix.length);
|
|
12902
13684
|
return beadNumberFromPath(named) === null ? named : undefined;
|
|
12903
13685
|
}
|
|
12904
|
-
#enqueue(observations) {
|
|
12905
|
-
this.#queue.push(...observations);
|
|
12906
|
-
if (this.#queue.length > UNACKED_MAX) {
|
|
12907
|
-
this.#o.log.error(`hightea-source: ${this.sourceId} has more than ${UNACKED_MAX} unacknowledged observations; starting a new epoch`);
|
|
12908
|
-
this.#queue.length = 0;
|
|
12909
|
-
this.#epoch = "e_" + randomUUID2();
|
|
12910
|
-
this.#ordinal = 0n;
|
|
12911
|
-
this.#kept.clear();
|
|
12912
|
-
const last = this.#current;
|
|
12913
|
-
this.#current = undefined;
|
|
12914
|
-
const fresh = new Map(last.rows.map((held) => [held.row.address, { key: held.key, row: held.row }]));
|
|
12915
|
-
this.#diff(`${this.#epoch}.${++this.#reads}`, last.snapshot, fresh);
|
|
12916
|
-
return;
|
|
12917
|
-
}
|
|
12918
|
-
this.#pump();
|
|
12919
|
-
}
|
|
12920
|
-
#pump() {
|
|
12921
|
-
if (!this.#watching || this.#inFlight || this.#queue.length === 0 || this.#pushTimer !== undefined || this.#stop.signal.aborted)
|
|
12922
|
-
return;
|
|
12923
|
-
const retryIn = this.#retryAt - this.#now();
|
|
12924
|
-
if (retryIn > 0) {
|
|
12925
|
-
this.#pushTimer = setTimeout(() => {
|
|
12926
|
-
this.#pushTimer = undefined;
|
|
12927
|
-
this.#pump();
|
|
12928
|
-
}, retryIn);
|
|
12929
|
-
return;
|
|
12930
|
-
}
|
|
12931
|
-
const wait = this.#lastPushAt + this.#coalesce - this.#now();
|
|
12932
|
-
if (wait > 0) {
|
|
12933
|
-
this.#pushTimer = setTimeout(() => {
|
|
12934
|
-
this.#pushTimer = undefined;
|
|
12935
|
-
this.#pump();
|
|
12936
|
-
}, wait);
|
|
12937
|
-
return;
|
|
12938
|
-
}
|
|
12939
|
-
const batch = [];
|
|
12940
|
-
let bytes = 1024;
|
|
12941
|
-
for (const one of this.#queue) {
|
|
12942
|
-
const size = sourceFrameBytes(one);
|
|
12943
|
-
if (batch.length > 0 && bytes + size > SOURCE_FRAME_MAX_BYTES)
|
|
12944
|
-
break;
|
|
12945
|
-
batch.push(one);
|
|
12946
|
-
bytes += size;
|
|
12947
|
-
}
|
|
12948
|
-
const last = batch[batch.length - 1];
|
|
12949
|
-
const epoch = this.#epoch;
|
|
12950
|
-
this.#inFlight = true;
|
|
12951
|
-
this.#lastPushAt = this.#now();
|
|
12952
|
-
this.#o.push({ workspaceId: this.#o.workspaceId, sourceId: this.sourceId, hostId: this.#o.hostId, position: last.position, observations: batch }).then((answer) => {
|
|
12953
|
-
if (this.#pushFailures > 0) {
|
|
12954
|
-
this.#o.log.info?.(`hightea-source: a push of ${this.sourceId} is answered again after ${this.#pushFailures} refusal(s)`);
|
|
12955
|
-
this.#pushFailures = 0;
|
|
12956
|
-
this.#retryAt = -Infinity;
|
|
12957
|
-
}
|
|
12958
|
-
const ack = SourceAckSchema.safeParse(answer);
|
|
12959
|
-
if (!ack.success) {
|
|
12960
|
-
this.#o.log.error(`hightea-source: the workspace answered a push of ${this.sourceId} outside its schema`);
|
|
12961
|
-
return;
|
|
12962
|
-
}
|
|
12963
|
-
const applied = ack.data.applied;
|
|
12964
|
-
if (applied === null || applied.epoch !== epoch || applied.epoch !== this.#epoch)
|
|
12965
|
-
return;
|
|
12966
|
-
const through = BigInt(applied.ordinal);
|
|
12967
|
-
let retire = 0;
|
|
12968
|
-
while (retire < this.#queue.length && BigInt(this.#queue[retire].position.ordinal) <= through)
|
|
12969
|
-
retire++;
|
|
12970
|
-
this.#queue.splice(0, retire);
|
|
12971
|
-
}, (error) => {
|
|
12972
|
-
this.#pushFailures++;
|
|
12973
|
-
const delay = Math.min(this.#coalesce * 2 ** Math.min(this.#pushFailures - 1, 5), 60000);
|
|
12974
|
-
this.#retryAt = this.#now() + delay;
|
|
12975
|
-
if (this.#pushFailures === 1)
|
|
12976
|
-
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`);
|
|
12977
|
-
}).finally(() => {
|
|
12978
|
-
this.#inFlight = false;
|
|
12979
|
-
this.#pump();
|
|
12980
|
-
});
|
|
12981
|
-
}
|
|
12982
13686
|
async#yrd(args, env) {
|
|
12983
13687
|
const { config } = this.#o;
|
|
12984
13688
|
try {
|
|
@@ -13340,10 +14044,14 @@ var runChild = (argv, { timeoutMs, signal, env }) => new Promise((resolve, rejec
|
|
|
13340
14044
|
resolve({ pid: child.pid, code: killed === null ? code : null, stdout, stderr });
|
|
13341
14045
|
});
|
|
13342
14046
|
});
|
|
13343
|
-
var
|
|
14047
|
+
var changeOf = (line) => {
|
|
13344
14048
|
try {
|
|
13345
14049
|
const record = JSON.parse(line);
|
|
13346
|
-
|
|
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 };
|
|
13347
14055
|
} catch {
|
|
13348
14056
|
return;
|
|
13349
14057
|
}
|
|
@@ -13392,15 +14100,292 @@ var followChild = (argv, { signal, onLine }) => new Promise((resolve, reject) =>
|
|
|
13392
14100
|
});
|
|
13393
14101
|
});
|
|
13394
14102
|
|
|
13395
|
-
// ../ahp-host/src/source
|
|
13396
|
-
|
|
13397
|
-
|
|
13398
|
-
|
|
13399
|
-
|
|
13400
|
-
|
|
13401
|
-
|
|
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);
|
|
13402
14122
|
}
|
|
13403
|
-
|
|
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";
|
|
13404
14389
|
function createSourceChannel(options) {
|
|
13405
14390
|
const { log } = options;
|
|
13406
14391
|
const refuse = (connection, id, code) => connection.send({ jsonrpc: "2.0", id, error: { code: -32000, message: code } });
|
|
@@ -13461,10 +14446,130 @@ function createSourceChannel(options) {
|
|
|
13461
14446
|
};
|
|
13462
14447
|
}
|
|
13463
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
|
+
|
|
13464
14568
|
// ../ahp-host/src/pipe-stamp.ts
|
|
13465
|
-
import { readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
|
|
14569
|
+
import { readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
13466
14570
|
import { join as join3 } from "node:path";
|
|
13467
14571
|
var PIPE_CONNECTED_STAMP = "pipe-connected.json";
|
|
14572
|
+
var PIPE_REFUSED_STAMP = "pipe-refused.json";
|
|
13468
14573
|
function ownManifestVersion(manifest = new URL("./plugin.json", import.meta.url)) {
|
|
13469
14574
|
let value;
|
|
13470
14575
|
try {
|
|
@@ -13484,36 +14589,24 @@ function stampConnected(configDir, version, now = new Date) {
|
|
|
13484
14589
|
`, { mode: 384 });
|
|
13485
14590
|
renameSync(staged, file);
|
|
13486
14591
|
}
|
|
13487
|
-
|
|
13488
|
-
|
|
13489
|
-
|
|
13490
|
-
|
|
13491
|
-
|
|
13492
|
-
|
|
13493
|
-
|
|
13494
|
-
|
|
13495
|
-
|
|
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) {
|
|
13496
14601
|
try {
|
|
13497
|
-
|
|
13498
|
-
|
|
13499
|
-
|
|
13500
|
-
|
|
13501
|
-
return;
|
|
14602
|
+
unlinkSync(join3(configDir, PIPE_REFUSED_STAMP));
|
|
14603
|
+
} catch (error) {
|
|
14604
|
+
if (error.code !== "ENOENT")
|
|
14605
|
+
throw error;
|
|
13502
14606
|
}
|
|
13503
14607
|
}
|
|
13504
|
-
|
|
13505
|
-
|
|
13506
|
-
peer.onMessage((message) => {
|
|
13507
|
-
for (const listener of listeners)
|
|
13508
|
-
listener(message);
|
|
13509
|
-
});
|
|
13510
|
-
return {
|
|
13511
|
-
request: (method, params, timeoutMs) => peer.request(method, params, timeoutMs),
|
|
13512
|
-
notify: (method, params) => peer.notify(method, params),
|
|
13513
|
-
onMessage: (listener) => void listeners.push(listener),
|
|
13514
|
-
close: () => peer.close()
|
|
13515
|
-
};
|
|
13516
|
-
}
|
|
14608
|
+
|
|
14609
|
+
// ../ahp-host/src/house.ts
|
|
13517
14610
|
function houseHeaders(token) {
|
|
13518
14611
|
return { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" };
|
|
13519
14612
|
}
|
|
@@ -13532,125 +14625,8 @@ async function houseCall(mcpUrl, headers, tool, args) {
|
|
|
13532
14625
|
throw new Error(answer.error.message);
|
|
13533
14626
|
return answer;
|
|
13534
14627
|
}
|
|
13535
|
-
|
|
13536
|
-
|
|
13537
|
-
const activePipe = pipe();
|
|
13538
|
-
const context = { sessionId: at.session, chatId: at.chat, turnId: at.turn() ?? "" };
|
|
13539
|
-
const resolved = activePipe?.resolveToolToken(context);
|
|
13540
|
-
if (resolved === undefined || !resolved.ok)
|
|
13541
|
-
throw new Error("TOKEN_EXPIRED_OR_REVOKED");
|
|
13542
|
-
const headers = houseHeaders(resolved.token);
|
|
13543
|
-
if (tool === "post_message")
|
|
13544
|
-
headers["idempotency-key"] = resolved.deliveryId;
|
|
13545
|
-
if (tool === "read_thread" || tool === "post_message") {
|
|
13546
|
-
const [roomId, messageId, extra] = resolved.threadRef.split("/");
|
|
13547
|
-
if (!roomId || !messageId || extra !== undefined)
|
|
13548
|
-
throw new Error("Invalid wake thread reference");
|
|
13549
|
-
if (tool === "read_thread") {
|
|
13550
|
-
args = { roomId, messageId, ...resolved.afterMessageId === undefined ? {} : { after: resolved.afterMessageId } };
|
|
13551
|
-
} else {
|
|
13552
|
-
const key = await signing.hostKey;
|
|
13553
|
-
if (key === undefined || key instanceof Error) {
|
|
13554
|
-
throw new Error(`HOST_KEY_UNAVAILABLE: this host cannot sign its agent's post${key instanceof Error ? `: ${key.message}` : " (its ahpd names no configDir)"}`);
|
|
13555
|
-
}
|
|
13556
|
-
const text = String(args.text ?? "");
|
|
13557
|
-
args = {
|
|
13558
|
-
text,
|
|
13559
|
-
roomId,
|
|
13560
|
-
deliveryId: resolved.deliveryId,
|
|
13561
|
-
replyId: resolved.deliveryId,
|
|
13562
|
-
sig: signHostPost(key, { workspaceId: signing.workspaceId, roomId, rootMessageId: messageId, authorMemberId: resolved.agentMemberId, clientId: resolved.deliveryId, body: text })
|
|
13563
|
-
};
|
|
13564
|
-
}
|
|
13565
|
-
}
|
|
13566
|
-
const answer = await houseCall(mcpUrl, headers, tool, args);
|
|
13567
|
-
if (tool === "read_thread") {
|
|
13568
|
-
const value = answer.result?.structuredContent;
|
|
13569
|
-
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 === "")) {
|
|
13570
|
-
throw new Error("read_thread returned no valid root/replies paging result");
|
|
13571
|
-
}
|
|
13572
|
-
const current = activePipe?.resolveToolToken(context);
|
|
13573
|
-
if (current === undefined || !current.ok)
|
|
13574
|
-
throw new Error("TOKEN_EXPIRED_OR_REVOKED");
|
|
13575
|
-
const last = value.replies.at(-1);
|
|
13576
|
-
const position = last?.id ?? current.afterMessageId ?? value.root.id;
|
|
13577
|
-
if (current.afterMessageId === resolved.afterMessageId)
|
|
13578
|
-
activePipe.vault.recordThreadRead(context, position);
|
|
13579
|
-
return JSON.stringify(await signing.gate.view(resolved.threadRef, value));
|
|
13580
|
-
}
|
|
13581
|
-
return (answer.result?.content ?? []).map((part) => part.text).join(`
|
|
13582
|
-
`);
|
|
13583
|
-
};
|
|
13584
|
-
host.registerTool({
|
|
13585
|
-
definition: {
|
|
13586
|
-
name: "hightea_thread_read",
|
|
13587
|
-
description: "You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",
|
|
13588
|
-
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
13589
|
-
},
|
|
13590
|
-
confirm: false,
|
|
13591
|
-
optIn: true,
|
|
13592
|
-
run: (_input, at) => call(at, "read_thread", {})
|
|
13593
|
-
});
|
|
13594
|
-
host.registerTool({
|
|
13595
|
-
definition: {
|
|
13596
|
-
name: "hightea_thread_post",
|
|
13597
|
-
description: "Post your reply to the Hightea room thread you were woken in. Call it once with your answer.",
|
|
13598
|
-
inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false }
|
|
13599
|
-
},
|
|
13600
|
-
confirm: false,
|
|
13601
|
-
optIn: true,
|
|
13602
|
-
run: (input, at) => call(at, "post_message", { text: String(input.text ?? "") })
|
|
13603
|
-
});
|
|
13604
|
-
host.registerTool({
|
|
13605
|
-
definition: {
|
|
13606
|
-
name: "hightea_page_read",
|
|
13607
|
-
description: "Read a Hightea page: its current version and content.",
|
|
13608
|
-
inputSchema: { type: "object", properties: { pageId: { type: "string" } }, required: ["pageId"], additionalProperties: false }
|
|
13609
|
-
},
|
|
13610
|
-
confirm: false,
|
|
13611
|
-
optIn: true,
|
|
13612
|
-
run: (input, at) => call(at, "page_read", { pageId: String(input.pageId ?? "") })
|
|
13613
|
-
});
|
|
13614
|
-
host.registerTool({
|
|
13615
|
-
definition: {
|
|
13616
|
-
name: "hightea_page_write",
|
|
13617
|
-
description: "Replace a Hightea page's content. Pass the version you read as ifVersion; a stale write is refused.",
|
|
13618
|
-
inputSchema: {
|
|
13619
|
-
type: "object",
|
|
13620
|
-
properties: { pageId: { type: "string" }, ifVersion: { type: "number" }, content: { type: "string" } },
|
|
13621
|
-
required: ["pageId", "ifVersion", "content"],
|
|
13622
|
-
additionalProperties: false
|
|
13623
|
-
}
|
|
13624
|
-
},
|
|
13625
|
-
confirm: false,
|
|
13626
|
-
optIn: true,
|
|
13627
|
-
run: (input, at) => {
|
|
13628
|
-
const args = input;
|
|
13629
|
-
return call(at, "page_write", { pageId: String(args.pageId ?? ""), ifVersion: Number(args.ifVersion), content: String(args.content ?? "") });
|
|
13630
|
-
}
|
|
13631
|
-
});
|
|
13632
|
-
host.registerTool({
|
|
13633
|
-
definition: {
|
|
13634
|
-
name: "hightea_page_screenshot",
|
|
13635
|
-
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.",
|
|
13636
|
-
inputSchema: {
|
|
13637
|
-
type: "object",
|
|
13638
|
-
properties: {
|
|
13639
|
-
pageId: { type: "string" },
|
|
13640
|
-
version: { type: "number", description: "Optional expected version; any version that is not live is refused (VERSION_NOT_CURRENT)." },
|
|
13641
|
-
width: { type: "number", description: "Capture width in CSS pixels (16..2400)." },
|
|
13642
|
-
height: { type: "number", description: "Minimum capture height in CSS pixels (16..2400)." },
|
|
13643
|
-
format: { type: "string", enum: ["png", "webp"] }
|
|
13644
|
-
},
|
|
13645
|
-
required: ["pageId"],
|
|
13646
|
-
additionalProperties: false
|
|
13647
|
-
}
|
|
13648
|
-
},
|
|
13649
|
-
confirm: false,
|
|
13650
|
-
optIn: true,
|
|
13651
|
-
run: (input, at) => call(at, "page_screenshot", pageScreenshotArgs(input))
|
|
13652
|
-
});
|
|
13653
|
-
}
|
|
14628
|
+
|
|
14629
|
+
// ../ahp-host/src/tools.ts
|
|
13654
14630
|
function pageScreenshotArgs(input) {
|
|
13655
14631
|
const wanted = input ?? {};
|
|
13656
14632
|
const pageId = wanted.pageId;
|
|
@@ -13672,6 +14648,463 @@ function pageScreenshotArgs(input) {
|
|
|
13672
14648
|
}
|
|
13673
14649
|
return args;
|
|
13674
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
|
+
}
|
|
13675
15108
|
function applyWith(host, options, seams) {
|
|
13676
15109
|
const legacy = options.houseId;
|
|
13677
15110
|
if (typeof options.workspaceId !== "string" || options.workspaceId === "") {
|
|
@@ -13679,8 +15112,18 @@ function applyWith(host, options, seams) {
|
|
|
13679
15112
|
throw new Error("hightea-pipe: the plugin entry names no workspace (workspaceId)");
|
|
13680
15113
|
options = { ...options, workspaceId: legacy };
|
|
13681
15114
|
}
|
|
15115
|
+
const headers = ownHeaders(options);
|
|
13682
15116
|
const own = typeof options.pluginVersion === "string" && options.pluginVersion !== "" ? { version: options.pluginVersion } : ownManifestVersion();
|
|
13683
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
|
+
};
|
|
13684
15127
|
if (!("version" in own))
|
|
13685
15128
|
host.log.error(`${name}: hello will name no plugin version: ${own.error}`);
|
|
13686
15129
|
let connectedStamped = false;
|
|
@@ -13689,15 +15132,34 @@ function applyWith(host, options, seams) {
|
|
|
13689
15132
|
let startup;
|
|
13690
15133
|
let cloud;
|
|
13691
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
|
+
});
|
|
13692
15153
|
const stop = async () => {
|
|
13693
15154
|
stopped = true;
|
|
13694
15155
|
if (startup !== undefined)
|
|
13695
15156
|
clearTimeout(startup);
|
|
13696
15157
|
startup = undefined;
|
|
13697
15158
|
cloud?.close();
|
|
13698
|
-
await Promise.all([...
|
|
15159
|
+
await Promise.all([...handlers.values()].map((source) => source.stop?.()));
|
|
13699
15160
|
};
|
|
13700
15161
|
host.registerClose(stop);
|
|
15162
|
+
host.registerClose(() => toolsBound?.stop());
|
|
13701
15163
|
const hostKey = host.configDir === undefined ? Promise.resolve(undefined) : hostSigningKey(host.configDir).catch((error) => {
|
|
13702
15164
|
const failure = error instanceof Error ? error : new Error(String(error));
|
|
13703
15165
|
host.log.error(`${name}: ${failure.message}`);
|
|
@@ -13716,113 +15178,206 @@ function applyWith(host, options, seams) {
|
|
|
13716
15178
|
}
|
|
13717
15179
|
});
|
|
13718
15180
|
const checks = seams.askGate ?? gate;
|
|
13719
|
-
|
|
13720
|
-
|
|
13721
|
-
|
|
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
|
+
}
|
|
13722
15186
|
host.on("listening", () => {
|
|
13723
15187
|
if (stopped || startup !== undefined || cloud !== undefined)
|
|
13724
15188
|
return;
|
|
13725
15189
|
startup = setTimeout(() => {
|
|
13726
15190
|
startup = undefined;
|
|
13727
|
-
|
|
13728
|
-
|
|
13729
|
-
|
|
13730
|
-
|
|
13731
|
-
|
|
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({
|
|
13732
15219
|
config,
|
|
13733
15220
|
workspaceId: options.workspaceId,
|
|
13734
15221
|
hostId,
|
|
13735
15222
|
log: host.log,
|
|
13736
15223
|
...seams.sourceChildren,
|
|
15224
|
+
onRecords: (observations) => records.observe(config.sourceId, observations.map(observedOf)),
|
|
13737
15225
|
serviceIdentityEnvironment: (binding) => {
|
|
13738
15226
|
if (typeof host.serviceIdentityEnvironment !== "function")
|
|
13739
15227
|
throw new Error("SERVICE_IDENTITY_UNAVAILABLE: native host callback missing");
|
|
13740
15228
|
return host.serviceIdentityEnvironment(binding);
|
|
13741
15229
|
},
|
|
13742
15230
|
push: (params) => link.sourcePush(params)
|
|
13743
|
-
})]));
|
|
13744
|
-
const offered = new Set(kmSources.keys());
|
|
13745
|
-
const sources = createSourceChannel({
|
|
13746
|
-
workspaceId: options.workspaceId,
|
|
13747
|
-
hostId,
|
|
13748
|
-
bindings: () => offered,
|
|
13749
|
-
log: host.log,
|
|
13750
|
-
handler: { handle: (request) => kmSources.get(request.sourceId).handle(request) }
|
|
13751
15231
|
});
|
|
13752
|
-
|
|
13753
|
-
|
|
13754
|
-
|
|
13755
|
-
|
|
13756
|
-
|
|
13757
|
-
|
|
13758
|
-
|
|
13759
|
-
|
|
13760
|
-
|
|
13761
|
-
|
|
13762
|
-
|
|
13763
|
-
|
|
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)
|
|
13764
15313
|
return;
|
|
13765
|
-
|
|
13766
|
-
|
|
13767
|
-
|
|
13768
|
-
|
|
13769
|
-
|
|
13770
|
-
|
|
13771
|
-
|
|
13772
|
-
|
|
13773
|
-
|
|
13774
|
-
channel: "ahp-root://",
|
|
13775
|
-
protocolVersions: [SUPPORTED_PROTOCOL],
|
|
13776
|
-
plugin: { name, version: pluginVersion },
|
|
13777
|
-
ahpd: options.ahpdVersion
|
|
13778
|
-
} });
|
|
13779
|
-
if (connectedStamped || pluginVersion === undefined || host.configDir === undefined)
|
|
13780
|
-
return;
|
|
13781
|
-
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) {
|
|
13782
15323
|
try {
|
|
13783
|
-
|
|
15324
|
+
clearRefused(host.configDir);
|
|
13784
15325
|
} catch (error) {
|
|
13785
|
-
host.log.error(`${name}: could not
|
|
13786
|
-
}
|
|
13787
|
-
};
|
|
13788
|
-
initialized.then(hello, (error) => {
|
|
13789
|
-
if (stopped)
|
|
13790
|
-
return;
|
|
13791
|
-
if (error instanceof UnmappedAgent && kmSources.size > 0) {
|
|
13792
|
-
host.log.error(`${name}: agent conversations unavailable; declared sources remain connected: ${String(error)}`);
|
|
13793
|
-
hello();
|
|
13794
|
-
return;
|
|
15326
|
+
host.log.error(`${name}: could not clear the refused-start stamp in ${host.configDir}: ${String(error)}`);
|
|
13795
15327
|
}
|
|
13796
|
-
|
|
13797
|
-
|
|
13798
|
-
|
|
13799
|
-
|
|
13800
|
-
|
|
13801
|
-
|
|
13802
|
-
})
|
|
13803
|
-
|
|
13804
|
-
|
|
13805
|
-
|
|
13806
|
-
|
|
13807
|
-
|
|
13808
|
-
|
|
13809
|
-
|
|
13810
|
-
|
|
13811
|
-
|
|
13812
|
-
|
|
13813
|
-
|
|
13814
|
-
|
|
13815
|
-
|
|
13816
|
-
|
|
13817
|
-
|
|
13818
|
-
|
|
13819
|
-
|
|
13820
|
-
|
|
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()]
|
|
13821
15376
|
}
|
|
13822
|
-
}
|
|
13823
|
-
|
|
13824
|
-
|
|
13825
|
-
}
|
|
15377
|
+
}
|
|
15378
|
+
});
|
|
15379
|
+
running = pipe;
|
|
15380
|
+
}
|
|
13826
15381
|
}
|
|
13827
15382
|
function apply(host, options) {
|
|
13828
15383
|
applyWith(host, options, {});
|
|
@@ -13831,11 +15386,8 @@ export {
|
|
|
13831
15386
|
WakePipe,
|
|
13832
15387
|
apply,
|
|
13833
15388
|
applyWith,
|
|
13834
|
-
houseCall,
|
|
13835
|
-
jwtExpiresAt,
|
|
13836
15389
|
name,
|
|
13837
15390
|
pageScreenshotArgs,
|
|
13838
15391
|
recordsPipeStore,
|
|
13839
|
-
registerTools,
|
|
13840
15392
|
shareListener
|
|
13841
15393
|
};
|