@hallohuman/hightea 0.1.2 → 0.1.8
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 +187 -16
- package/dist/chunk-0ab6h39c.js +402 -0
- package/dist/chunk-3qbh10ga.js +12 -0
- package/dist/chunk-5mezgvms.js +139 -0
- package/dist/chunk-99e0mv8w.js +7313 -0
- package/dist/chunk-c8kc1c68.js +78 -0
- package/dist/chunk-d5h204vj.js +14 -0
- package/dist/{chunk-mcmsnaer.js → chunk-k2ws7xvy.js} +223 -21
- package/dist/chunk-py45wjd1.js +91 -0
- package/dist/chunk-sbqmqp8e.js +123 -0
- package/dist/chunk-v59kcfmj.js +347 -0
- package/dist/plugin/plugin.json +1 -1
- package/dist/plugin/plugin.mjs +2126 -112
- package/package.json +9 -5
- package/dist/chunk-9wxqnv9x.js +0 -149
package/dist/plugin/plugin.mjs
CHANGED
|
@@ -2929,7 +2929,7 @@ var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
|
2929
2929
|
var wrapper_default = import_websocket.default;
|
|
2930
2930
|
|
|
2931
2931
|
// ../ahp-host/src/records-store.ts
|
|
2932
|
-
import { createHash } from "node:crypto";
|
|
2932
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
2933
2933
|
|
|
2934
2934
|
// ../../node_modules/.bun/zod@4.6.7/node_modules/zod/v4/core/util.js
|
|
2935
2935
|
function getEnumValues(entries) {
|
|
@@ -3918,6 +3918,7 @@ function datetime(args) {
|
|
|
3918
3918
|
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
|
|
3919
3919
|
}
|
|
3920
3920
|
var anyString = /^[\s\S]{0,}$/;
|
|
3921
|
+
var integer = /^-?\d+$/;
|
|
3921
3922
|
var number = /^-?\d+(?:\.\d+)?$/;
|
|
3922
3923
|
var boolean = /^(?:true|false)$/i;
|
|
3923
3924
|
var lowercase = /^[^A-Z]*$/;
|
|
@@ -5594,6 +5595,161 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) {
|
|
|
5594
5595
|
}
|
|
5595
5596
|
return final;
|
|
5596
5597
|
}
|
|
5598
|
+
var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
|
|
5599
|
+
$ZodType.init(inst, def);
|
|
5600
|
+
const memo = globalConfig.memoizer;
|
|
5601
|
+
memo?.attach(inst);
|
|
5602
|
+
inst._zod.parse = (payload, ctx) => {
|
|
5603
|
+
const input = payload.value;
|
|
5604
|
+
if (!isPlainObject(input)) {
|
|
5605
|
+
payload.issues.push({
|
|
5606
|
+
expected: "record",
|
|
5607
|
+
code: "invalid_type",
|
|
5608
|
+
input,
|
|
5609
|
+
inst
|
|
5610
|
+
});
|
|
5611
|
+
return payload;
|
|
5612
|
+
}
|
|
5613
|
+
const proms = [];
|
|
5614
|
+
const values = def.keyType._zod.values;
|
|
5615
|
+
if (values && !def.partial) {
|
|
5616
|
+
payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
|
|
5617
|
+
const recordKeys = new Set;
|
|
5618
|
+
for (const key of values) {
|
|
5619
|
+
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
|
|
5620
|
+
recordKeys.add(typeof key === "number" ? key.toString() : key);
|
|
5621
|
+
if (key === "__proto__")
|
|
5622
|
+
continue;
|
|
5623
|
+
const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
|
|
5624
|
+
if (keyResult instanceof Promise) {
|
|
5625
|
+
throw new Error("Async schemas not supported in object keys currently");
|
|
5626
|
+
}
|
|
5627
|
+
if (keyResult.issues.length) {
|
|
5628
|
+
payload.issues.push({
|
|
5629
|
+
code: "invalid_key",
|
|
5630
|
+
origin: "record",
|
|
5631
|
+
issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
|
|
5632
|
+
input: key,
|
|
5633
|
+
path: [key],
|
|
5634
|
+
inst
|
|
5635
|
+
});
|
|
5636
|
+
continue;
|
|
5637
|
+
}
|
|
5638
|
+
const outKey = keyResult.value;
|
|
5639
|
+
if (outKey === "__proto__")
|
|
5640
|
+
continue;
|
|
5641
|
+
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
|
|
5642
|
+
if (result instanceof Promise) {
|
|
5643
|
+
proms.push(result.then((result) => {
|
|
5644
|
+
if (result.issues.length) {
|
|
5645
|
+
payload.issues.push(...prefixIssues(key, result.issues));
|
|
5646
|
+
}
|
|
5647
|
+
payload.value[outKey] = result.value;
|
|
5648
|
+
}));
|
|
5649
|
+
} else {
|
|
5650
|
+
if (result.issues.length) {
|
|
5651
|
+
payload.issues.push(...prefixIssues(key, result.issues));
|
|
5652
|
+
}
|
|
5653
|
+
payload.value[outKey] = result.value;
|
|
5654
|
+
}
|
|
5655
|
+
}
|
|
5656
|
+
}
|
|
5657
|
+
let unrecognized;
|
|
5658
|
+
for (const key in input) {
|
|
5659
|
+
if (!recordKeys.has(key)) {
|
|
5660
|
+
if (def.mode === "loose") {
|
|
5661
|
+
if (key === "__proto__")
|
|
5662
|
+
continue;
|
|
5663
|
+
payload.value[key] = input[key];
|
|
5664
|
+
} else {
|
|
5665
|
+
unrecognized = unrecognized ?? [];
|
|
5666
|
+
unrecognized.push(key);
|
|
5667
|
+
}
|
|
5668
|
+
}
|
|
5669
|
+
}
|
|
5670
|
+
if (unrecognized && unrecognized.length > 0) {
|
|
5671
|
+
payload.issues.push({
|
|
5672
|
+
code: "unrecognized_keys",
|
|
5673
|
+
input,
|
|
5674
|
+
inst,
|
|
5675
|
+
keys: unrecognized,
|
|
5676
|
+
continue: true
|
|
5677
|
+
});
|
|
5678
|
+
}
|
|
5679
|
+
} else {
|
|
5680
|
+
payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
|
|
5681
|
+
let unrecognized;
|
|
5682
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
5683
|
+
if (key === "__proto__")
|
|
5684
|
+
continue;
|
|
5685
|
+
if (!Object.prototype.propertyIsEnumerable.call(input, key))
|
|
5686
|
+
continue;
|
|
5687
|
+
let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
|
|
5688
|
+
if (keyResult instanceof Promise) {
|
|
5689
|
+
throw new Error("Async schemas not supported in object keys currently");
|
|
5690
|
+
}
|
|
5691
|
+
const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length;
|
|
5692
|
+
if (checkNumericKey) {
|
|
5693
|
+
const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
|
|
5694
|
+
if (retryResult instanceof Promise) {
|
|
5695
|
+
throw new Error("Async schemas not supported in object keys currently");
|
|
5696
|
+
}
|
|
5697
|
+
if (retryResult.issues.length === 0) {
|
|
5698
|
+
keyResult = retryResult;
|
|
5699
|
+
}
|
|
5700
|
+
}
|
|
5701
|
+
if (keyResult.issues.length) {
|
|
5702
|
+
if (def.mode === "loose") {
|
|
5703
|
+
payload.value[key] = input[key];
|
|
5704
|
+
} else if (values) {
|
|
5705
|
+
unrecognized = unrecognized ?? [];
|
|
5706
|
+
unrecognized.push(key);
|
|
5707
|
+
} else {
|
|
5708
|
+
payload.issues.push({
|
|
5709
|
+
code: "invalid_key",
|
|
5710
|
+
origin: "record",
|
|
5711
|
+
issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
|
|
5712
|
+
input: key,
|
|
5713
|
+
path: [key],
|
|
5714
|
+
inst
|
|
5715
|
+
});
|
|
5716
|
+
}
|
|
5717
|
+
continue;
|
|
5718
|
+
}
|
|
5719
|
+
const outKey = keyResult.value;
|
|
5720
|
+
if (outKey === "__proto__")
|
|
5721
|
+
continue;
|
|
5722
|
+
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
|
|
5723
|
+
if (result instanceof Promise) {
|
|
5724
|
+
proms.push(result.then((result) => {
|
|
5725
|
+
if (result.issues.length) {
|
|
5726
|
+
payload.issues.push(...prefixIssues(key, result.issues));
|
|
5727
|
+
}
|
|
5728
|
+
payload.value[outKey] = result.value;
|
|
5729
|
+
}));
|
|
5730
|
+
} else {
|
|
5731
|
+
if (result.issues.length) {
|
|
5732
|
+
payload.issues.push(...prefixIssues(key, result.issues));
|
|
5733
|
+
}
|
|
5734
|
+
payload.value[outKey] = result.value;
|
|
5735
|
+
}
|
|
5736
|
+
}
|
|
5737
|
+
if (unrecognized && unrecognized.length > 0) {
|
|
5738
|
+
payload.issues.push({
|
|
5739
|
+
code: "unrecognized_keys",
|
|
5740
|
+
input,
|
|
5741
|
+
inst,
|
|
5742
|
+
keys: unrecognized,
|
|
5743
|
+
continue: true
|
|
5744
|
+
});
|
|
5745
|
+
}
|
|
5746
|
+
}
|
|
5747
|
+
if (proms.length) {
|
|
5748
|
+
return Promise.all(proms).then(() => payload);
|
|
5749
|
+
}
|
|
5750
|
+
return payload;
|
|
5751
|
+
};
|
|
5752
|
+
});
|
|
5597
5753
|
var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
|
|
5598
5754
|
$ZodType.init(inst, def);
|
|
5599
5755
|
const values = getEnumValues(def.entries);
|
|
@@ -7698,7 +7854,112 @@ var tupleProcessor = (schema, ctx, _json, params) => {
|
|
|
7698
7854
|
if (typeof maximum === "number")
|
|
7699
7855
|
json.maxItems = maximum;
|
|
7700
7856
|
};
|
|
7857
|
+
function stringifyKeyNames(bySchema, json, visited) {
|
|
7858
|
+
if (json.$ref) {
|
|
7859
|
+
if (visited.has(json))
|
|
7860
|
+
return json;
|
|
7861
|
+
visited.add(json);
|
|
7862
|
+
const def = bySchema.get(json)?.def;
|
|
7863
|
+
if (!def)
|
|
7864
|
+
return json;
|
|
7865
|
+
const inlined = stringifyKeyNames(bySchema, def, visited);
|
|
7866
|
+
return inlined === def ? json : inlined;
|
|
7867
|
+
}
|
|
7868
|
+
for (const keyword of ["anyOf", "oneOf"]) {
|
|
7869
|
+
const branches = json[keyword];
|
|
7870
|
+
if (!Array.isArray(branches))
|
|
7871
|
+
continue;
|
|
7872
|
+
const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
|
|
7873
|
+
if (mapped.some((branch, i) => branch !== branches[i]))
|
|
7874
|
+
json = { ...json, [keyword]: mapped };
|
|
7875
|
+
}
|
|
7876
|
+
const types = Array.isArray(json.type) ? json.type : [json.type];
|
|
7877
|
+
const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
|
|
7878
|
+
const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);
|
|
7879
|
+
if (!numericType && !values?.some((v) => typeof v === "number"))
|
|
7880
|
+
return json;
|
|
7881
|
+
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
|
|
7882
|
+
if (rest.enum)
|
|
7883
|
+
rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
|
|
7884
|
+
else if (typeof rest.const === "number")
|
|
7885
|
+
rest.const = String(rest.const);
|
|
7886
|
+
if (!numericType)
|
|
7887
|
+
return rest;
|
|
7888
|
+
rest.type = "string";
|
|
7889
|
+
if (!values)
|
|
7890
|
+
rest.pattern = (types.includes("number") ? number : integer).source;
|
|
7891
|
+
return rest;
|
|
7892
|
+
}
|
|
7701
7893
|
var pendingRecords = new WeakMap;
|
|
7894
|
+
function rewriteKeyNames(ctx) {
|
|
7895
|
+
const bySchema = new Map;
|
|
7896
|
+
for (const entry of ctx.seen.values()) {
|
|
7897
|
+
if (entry.def && !bySchema.has(entry.schema))
|
|
7898
|
+
bySchema.set(entry.schema, entry);
|
|
7899
|
+
}
|
|
7900
|
+
const rewrites = new Map;
|
|
7901
|
+
for (const record of pendingRecords.get(ctx) ?? []) {
|
|
7902
|
+
const seen = ctx.seen.get(record);
|
|
7903
|
+
const names = (seen?.def ?? seen?.schema)?.propertyNames;
|
|
7904
|
+
if (!names || names === true || rewrites.has(names))
|
|
7905
|
+
continue;
|
|
7906
|
+
const rewritten = stringifyKeyNames(bySchema, names, new Set);
|
|
7907
|
+
if (rewritten !== names)
|
|
7908
|
+
rewrites.set(names, rewritten);
|
|
7909
|
+
}
|
|
7910
|
+
if (!rewrites.size)
|
|
7911
|
+
return;
|
|
7912
|
+
for (const entry of ctx.seen.values()) {
|
|
7913
|
+
for (const carrier of [entry.schema, entry.def]) {
|
|
7914
|
+
const rewritten = carrier && rewrites.get(carrier.propertyNames);
|
|
7915
|
+
if (rewritten)
|
|
7916
|
+
carrier.propertyNames = rewritten;
|
|
7917
|
+
}
|
|
7918
|
+
}
|
|
7919
|
+
}
|
|
7920
|
+
var recordProcessor = (schema, ctx, _json, params) => {
|
|
7921
|
+
const json = _json;
|
|
7922
|
+
const def = schema._zod.def;
|
|
7923
|
+
json.type = "object";
|
|
7924
|
+
const keyType = def.keyType;
|
|
7925
|
+
const patterns = aggregateChecks(keyType).patterns;
|
|
7926
|
+
if (def.mode === "loose" && patterns && patterns.size > 0) {
|
|
7927
|
+
const valueSchema = processSchema(def.valueType, ctx, {
|
|
7928
|
+
...params,
|
|
7929
|
+
path: [...params.path, "patternProperties", "*"]
|
|
7930
|
+
});
|
|
7931
|
+
json.patternProperties = {};
|
|
7932
|
+
for (const pattern of patterns) {
|
|
7933
|
+
assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
|
|
7934
|
+
}
|
|
7935
|
+
} else {
|
|
7936
|
+
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
|
|
7937
|
+
json.propertyNames = processSchema(def.keyType, ctx, {
|
|
7938
|
+
...params,
|
|
7939
|
+
path: [...params.path, "propertyNames"]
|
|
7940
|
+
});
|
|
7941
|
+
let pending = pendingRecords.get(ctx);
|
|
7942
|
+
if (!pending) {
|
|
7943
|
+
pending = [];
|
|
7944
|
+
pendingRecords.set(ctx, pending);
|
|
7945
|
+
ctx.deferred.push(() => rewriteKeyNames(ctx));
|
|
7946
|
+
}
|
|
7947
|
+
pending.push(schema);
|
|
7948
|
+
}
|
|
7949
|
+
json.additionalProperties = processSchema(def.valueType, ctx, {
|
|
7950
|
+
...params,
|
|
7951
|
+
path: [...params.path, "additionalProperties"]
|
|
7952
|
+
});
|
|
7953
|
+
}
|
|
7954
|
+
const keyValues = keyType._zod.values;
|
|
7955
|
+
const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined;
|
|
7956
|
+
if (keyValues && !def.partial && !omittableOnInput) {
|
|
7957
|
+
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
|
|
7958
|
+
if (validKeyValues.length > 0) {
|
|
7959
|
+
json.required = validKeyValues.map(String);
|
|
7960
|
+
}
|
|
7961
|
+
}
|
|
7962
|
+
};
|
|
7702
7963
|
var nullableProcessor = (schema, ctx, json, params) => {
|
|
7703
7964
|
const def = schema._zod.def;
|
|
7704
7965
|
const inner = processSchema(def.innerType, ctx, params);
|
|
@@ -8515,6 +8776,30 @@ function tuple(items, _paramsOrRest, _params) {
|
|
|
8515
8776
|
...normalizeParams(params)
|
|
8516
8777
|
});
|
|
8517
8778
|
}
|
|
8779
|
+
var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
|
|
8780
|
+
_ensureDefaultMemoizer();
|
|
8781
|
+
$ZodRecord.init(inst, def);
|
|
8782
|
+
ZodType.init(inst, def);
|
|
8783
|
+
inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
|
|
8784
|
+
inst.keyType = def.keyType;
|
|
8785
|
+
inst.valueType = def.valueType;
|
|
8786
|
+
});
|
|
8787
|
+
function record(keyType, valueType, params) {
|
|
8788
|
+
if (!valueType || !valueType._zod) {
|
|
8789
|
+
return new ZodRecord({
|
|
8790
|
+
type: "record",
|
|
8791
|
+
keyType: string2(),
|
|
8792
|
+
valueType: keyType,
|
|
8793
|
+
...normalizeParams(valueType)
|
|
8794
|
+
});
|
|
8795
|
+
}
|
|
8796
|
+
return new ZodRecord({
|
|
8797
|
+
type: "record",
|
|
8798
|
+
keyType,
|
|
8799
|
+
valueType,
|
|
8800
|
+
...normalizeParams(params)
|
|
8801
|
+
});
|
|
8802
|
+
}
|
|
8518
8803
|
var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
|
|
8519
8804
|
$ZodEnum.init(inst, def);
|
|
8520
8805
|
ZodType.init(inst, def);
|
|
@@ -9459,13 +9744,16 @@ var STATUS_ACTIVITY_MASK2 = (1 << 5) - 1;
|
|
|
9459
9744
|
var SOURCE_ERROR_CODES = [
|
|
9460
9745
|
"SOURCE_UNBOUND",
|
|
9461
9746
|
"SOURCE_UNAVAILABLE",
|
|
9747
|
+
"SERVICE_IDENTITY_UNAVAILABLE",
|
|
9748
|
+
"SERVICE_IDENTITY_NOT_GRANTED",
|
|
9462
9749
|
"NOT_MAPPED",
|
|
9463
9750
|
"INVALID_ADDRESS",
|
|
9464
9751
|
"HOST_OFFLINE",
|
|
9465
9752
|
"SOURCE_GAP",
|
|
9466
9753
|
"FRAME_TOO_LARGE",
|
|
9467
9754
|
"ITEM_TOO_LARGE",
|
|
9468
|
-
"STALE_EXPECTATION"
|
|
9755
|
+
"STALE_EXPECTATION",
|
|
9756
|
+
"SOURCE_READER_RESTARTING"
|
|
9469
9757
|
];
|
|
9470
9758
|
var SOURCE_FRAME_MAX_BYTES = 512 * 1024;
|
|
9471
9759
|
var SOURCE_PAGE_BUDGET_BYTES = 256 * 1024;
|
|
@@ -9487,6 +9775,7 @@ var SourceRowSchema = object({
|
|
|
9487
9775
|
state: Id,
|
|
9488
9776
|
owner: Id.nullable(),
|
|
9489
9777
|
parent: Address.nullable(),
|
|
9778
|
+
project: Address.nullable(),
|
|
9490
9779
|
labels: array(Id).max(256),
|
|
9491
9780
|
url: string2().max(2048).nullable(),
|
|
9492
9781
|
updatedAt: string2().max(64).nullable()
|
|
@@ -9518,7 +9807,9 @@ var SourceListPageSchema = object({
|
|
|
9518
9807
|
base: SourcePositionSchema,
|
|
9519
9808
|
rows: array(SourceRowSchema),
|
|
9520
9809
|
next: string2().min(1).max(4096).nullable(),
|
|
9521
|
-
complete: boolean2()
|
|
9810
|
+
complete: boolean2(),
|
|
9811
|
+
progressAsOf: string2().min(1).max(64).optional(),
|
|
9812
|
+
progressStale: object({ since: string2().min(1).max(64), reason: string2().min(1).max(4096) }).strict().optional()
|
|
9522
9813
|
}).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" });
|
|
9523
9814
|
var AssignReply = object({ intentId: Id, result: unknown(), observation: SourceObservationSchema }).strict();
|
|
9524
9815
|
var BODIES = {
|
|
@@ -9531,6 +9822,7 @@ var ErrorCode = _enum(SOURCE_ERROR_CODES);
|
|
|
9531
9822
|
var NOT_SOURCE_CODES = ["OPERATION_NOT_ALLOWLISTED", "INVALID_OPERATION_SHAPE"];
|
|
9532
9823
|
var response = (op) => union([
|
|
9533
9824
|
object({ ...Binding, op: literal(op), outcome: _enum(["applied", "noop"]), body: BODIES[op] }).strict(),
|
|
9825
|
+
object({ ...Binding, op: literal(op), outcome: _enum(["applied", "noop"]), code: literal("SOURCE_READER_RESTARTING"), body: BODIES[op] }).strict(),
|
|
9534
9826
|
object({ ...Binding, op: literal(op), outcome: literal("rejected"), code: ErrorCode, body: BODIES[op] }).strict(),
|
|
9535
9827
|
object({ ...Binding, op: literal(op), outcome: _enum(["unknown", "refused"]), code: union([ErrorCode.exclude(["ITEM_TOO_LARGE"]), _enum(NOT_SOURCE_CODES)]) }).strict(),
|
|
9536
9828
|
object({ ...Binding, op: literal(op), outcome: literal("refused"), code: literal("ITEM_TOO_LARGE"), item: Address }).strict()
|
|
@@ -9544,6 +9836,86 @@ var SourcePushSchema = object({ ...Binding, position: SourcePositionSchema, obse
|
|
|
9544
9836
|
return observations.every((one, index) => one.position.epoch === position.epoch && (index === 0 || BigInt(one.position.ordinal) === BigInt(observations[index - 1].position.ordinal) + 1n));
|
|
9545
9837
|
}, { message: "a push is one epoch of consecutive ordinals, numbered by its last" });
|
|
9546
9838
|
var SourceAckSchema = object({ applied: SourcePositionSchema.nullable(), seq: number2().int().min(0), relist: boolean2() }).strict();
|
|
9839
|
+
// ../ahp/src/agent-records.ts
|
|
9840
|
+
var AgentRecordRowSchema = object({
|
|
9841
|
+
id: string2().min(1),
|
|
9842
|
+
revision: number2().int().min(0),
|
|
9843
|
+
state: string2(),
|
|
9844
|
+
operations: array(string2())
|
|
9845
|
+
}).passthrough();
|
|
9846
|
+
var ifRevision = number2().int().min(0);
|
|
9847
|
+
var AgentPutRequestSchema = object({
|
|
9848
|
+
id: string2().min(1),
|
|
9849
|
+
engine: string2().min(1),
|
|
9850
|
+
owner: string2().min(1),
|
|
9851
|
+
name: string2().min(1),
|
|
9852
|
+
description: string2().optional(),
|
|
9853
|
+
tags: array(string2()).optional(),
|
|
9854
|
+
model: unknown().optional(),
|
|
9855
|
+
config: record(string2(), unknown()),
|
|
9856
|
+
ifRevision
|
|
9857
|
+
}).passthrough();
|
|
9858
|
+
var AgentRemoveRequestSchema = object({ id: string2().min(1), ifRevision }).strict();
|
|
9859
|
+
var AgentModeRequestSchema = object({ id: string2().min(1), ifRevision }).strict();
|
|
9860
|
+
var JSON_RPC_INVALID_PARAMS = -32602;
|
|
9861
|
+
var StaleRefusalSchema = object({
|
|
9862
|
+
code: literal(JSON_RPC_INVALID_PARAMS),
|
|
9863
|
+
message: string2(),
|
|
9864
|
+
data: object({ staleRevision: number2().int().min(1), row: AgentRecordRowSchema })
|
|
9865
|
+
});
|
|
9866
|
+
var MissingRefusalSchema = object({
|
|
9867
|
+
code: literal(JSON_RPC_INVALID_PARAMS),
|
|
9868
|
+
message: string2(),
|
|
9869
|
+
data: object({ staleRevision: literal(0) })
|
|
9870
|
+
});
|
|
9871
|
+
// ../ahp/src/host-requests.ts
|
|
9872
|
+
var HOST_SCOPED_METHODS = [
|
|
9873
|
+
"x-ahpd/services/list",
|
|
9874
|
+
"x-ahpd/services/put",
|
|
9875
|
+
"x-ahpd/services/remove",
|
|
9876
|
+
"x-ahpd/services/start",
|
|
9877
|
+
"x-ahpd/services/stop",
|
|
9878
|
+
"x-ahpd/services/restart",
|
|
9879
|
+
"x-ahpd/services/logs",
|
|
9880
|
+
"x-ahpd/services/acknowledge",
|
|
9881
|
+
"x-ahpd/services/backup"
|
|
9882
|
+
];
|
|
9883
|
+
var HOST_REQUEST_METHODS = [
|
|
9884
|
+
"x-ahpd/agents/list",
|
|
9885
|
+
"x-ahpd/agents/put",
|
|
9886
|
+
"x-ahpd/agents/remove",
|
|
9887
|
+
"x-ahpd/agents/enable",
|
|
9888
|
+
"x-ahpd/agents/pause",
|
|
9889
|
+
"x-ahpd/agents/disable",
|
|
9890
|
+
...HOST_SCOPED_METHODS
|
|
9891
|
+
];
|
|
9892
|
+
function isHostScopedMethod(method) {
|
|
9893
|
+
return HOST_SCOPED_METHODS.includes(method);
|
|
9894
|
+
}
|
|
9895
|
+
var HOST_REQUEST_TIMEOUT_MS = 1e4;
|
|
9896
|
+
var HOST_LOCAL_TIMEOUT_MS = HOST_REQUEST_TIMEOUT_MS - 1000;
|
|
9897
|
+
var requestId = string2().min(1).max(200);
|
|
9898
|
+
var HostRequestSchema = object({
|
|
9899
|
+
workspaceId: string2().min(1),
|
|
9900
|
+
hostId: string2().min(1),
|
|
9901
|
+
agentMemberId: string2().min(1).optional(),
|
|
9902
|
+
requestId,
|
|
9903
|
+
method: _enum(HOST_REQUEST_METHODS),
|
|
9904
|
+
params: record(string2(), unknown())
|
|
9905
|
+
}).strict();
|
|
9906
|
+
var HostRequestAnswerSchema = union([
|
|
9907
|
+
object({ ok: literal(true), result: unknown() }).strict(),
|
|
9908
|
+
object({
|
|
9909
|
+
ok: literal(false),
|
|
9910
|
+
reason: literal("refused"),
|
|
9911
|
+
code: number2(),
|
|
9912
|
+
message: string2(),
|
|
9913
|
+
data: unknown().optional()
|
|
9914
|
+
}).strict(),
|
|
9915
|
+
object({ ok: literal(false), reason: literal("unmapped") }).strict(),
|
|
9916
|
+
object({ ok: literal(false), reason: literal("timedOut") }).strict(),
|
|
9917
|
+
object({ ok: literal(false), reason: literal("outside") }).strict()
|
|
9918
|
+
]);
|
|
9547
9919
|
// ../ahp/src/index.ts
|
|
9548
9920
|
var HOST_TO_CLOUD_EVENTS = [
|
|
9549
9921
|
"session.created",
|
|
@@ -9565,6 +9937,12 @@ var BOUNDED_ERROR_CODES = [
|
|
|
9565
9937
|
"VERSION_UNSUPPORTED",
|
|
9566
9938
|
"WAKE_NOT_SENT",
|
|
9567
9939
|
"TURN_TIMED_OUT",
|
|
9940
|
+
"WAKE_TEXT_NOT_ALLOWED",
|
|
9941
|
+
"ROOM_ASKS_UNTRUSTED",
|
|
9942
|
+
"ASK_UNSIGNED",
|
|
9943
|
+
"KEY_NOT_FOR_AUTHOR",
|
|
9944
|
+
"ASK_STALE",
|
|
9945
|
+
"REPLAYED_ASK",
|
|
9568
9946
|
...SOURCE_ERROR_CODES
|
|
9569
9947
|
];
|
|
9570
9948
|
var WakeMetaSchema = object({
|
|
@@ -9698,6 +10076,8 @@ function checkCloudFrame(frame, registry) {
|
|
|
9698
10076
|
if (!isRecord(message.origin) || !exactKeys(message.origin, ["kind"]) || message.origin.kind !== "user") {
|
|
9699
10077
|
return refuse("INVALID_OPERATION_SHAPE");
|
|
9700
10078
|
}
|
|
10079
|
+
if (message.text !== `wake ${meta.threadRef}`)
|
|
10080
|
+
return refuse("WAKE_TEXT_NOT_ALLOWED");
|
|
9701
10081
|
if (agentToken === undefined)
|
|
9702
10082
|
return refuse("TOKEN_EXPIRED_OR_REVOKED");
|
|
9703
10083
|
return {
|
|
@@ -9733,6 +10113,109 @@ function isKnownSession(registry, uri) {
|
|
|
9733
10113
|
// ../ahp-host/src/runtime.ts
|
|
9734
10114
|
import { fileURLToPath } from "node:url";
|
|
9735
10115
|
|
|
10116
|
+
// ../ahp-host/src/host-request.ts
|
|
10117
|
+
var HOST_RECORD_OWNER = "host";
|
|
10118
|
+
var refusal = (error) => {
|
|
10119
|
+
if (typeof error !== "object" || error === null)
|
|
10120
|
+
return;
|
|
10121
|
+
const code = error.code;
|
|
10122
|
+
const message = error.message;
|
|
10123
|
+
if (typeof code !== "number" || typeof message !== "string")
|
|
10124
|
+
return;
|
|
10125
|
+
const data = error.data;
|
|
10126
|
+
return data === undefined ? { code, message } : { code, message, data };
|
|
10127
|
+
};
|
|
10128
|
+
var isCreate = (params) => params.ifRevision === 0;
|
|
10129
|
+
var timedOut = (error) => error instanceof Error && /timed? ?out|timeout/iu.test(error.message);
|
|
10130
|
+
var AGENTS_CHANNEL = "x-ahpd-agents://";
|
|
10131
|
+
function rowsOfSnapshot(answer) {
|
|
10132
|
+
const snapshot = typeof answer === "object" && answer !== null ? answer.snapshot : undefined;
|
|
10133
|
+
const state = typeof snapshot === "object" && snapshot !== null ? snapshot.state : undefined;
|
|
10134
|
+
const records = typeof state === "object" && state !== null ? state.records : undefined;
|
|
10135
|
+
if (!Array.isArray(records))
|
|
10136
|
+
throw new Error("hightea-pipe: the agents snapshot holds no records");
|
|
10137
|
+
return records.map((entry) => {
|
|
10138
|
+
if (typeof entry !== "object" || entry === null)
|
|
10139
|
+
throw new Error("hightea-pipe: an agents snapshot entry is not an object");
|
|
10140
|
+
const held = entry;
|
|
10141
|
+
if (typeof held.record === "object" && held.record !== null && !Array.isArray(held.record)) {
|
|
10142
|
+
if (typeof held.id !== "string")
|
|
10143
|
+
throw new Error("hightea-pipe: an agents snapshot entry names no id");
|
|
10144
|
+
return { id: held.id, ...held.record };
|
|
10145
|
+
}
|
|
10146
|
+
if (typeof held.id !== "string")
|
|
10147
|
+
throw new Error("hightea-pipe: an agents snapshot entry names no id");
|
|
10148
|
+
return held;
|
|
10149
|
+
});
|
|
10150
|
+
}
|
|
10151
|
+
async function listHostAgents(options) {
|
|
10152
|
+
const providers = new Set([...options.agents.values()].map((agent) => agent.provider));
|
|
10153
|
+
let answer;
|
|
10154
|
+
try {
|
|
10155
|
+
answer = await options.peer.request("subscribe", { channel: AGENTS_CHANNEL }, HOST_LOCAL_TIMEOUT_MS);
|
|
10156
|
+
} catch (error) {
|
|
10157
|
+
const answered = refusal(error);
|
|
10158
|
+
if (answered !== undefined)
|
|
10159
|
+
return { ok: false, reason: "refused", ...answered };
|
|
10160
|
+
options.log.error(`hightea-pipe: listing this host's agents ended without an answer` + (timedOut(error) ? " (timed out)" : "") + `: ${error instanceof Error ? error.name : typeof error}`);
|
|
10161
|
+
return { ok: false, reason: "timedOut" };
|
|
10162
|
+
}
|
|
10163
|
+
let rows;
|
|
10164
|
+
try {
|
|
10165
|
+
rows = rowsOfSnapshot(answer);
|
|
10166
|
+
} catch (error) {
|
|
10167
|
+
options.log.error(`hightea-pipe: ${error instanceof Error ? error.message : "the agents snapshot is unreadable"}`);
|
|
10168
|
+
return { ok: false, reason: "refused", code: -32603, message: "this host could not read ahpd's agent list" };
|
|
10169
|
+
}
|
|
10170
|
+
const shown = rows.filter((row) => typeof row.id === "string" && providers.has(row.id));
|
|
10171
|
+
shown.sort((left, right) => String(left.id) < String(right.id) ? -1 : String(left.id) > String(right.id) ? 1 : 0);
|
|
10172
|
+
try {
|
|
10173
|
+
await options.peer.request("unsubscribe", { channel: AGENTS_CHANNEL }, HOST_LOCAL_TIMEOUT_MS);
|
|
10174
|
+
} catch (error) {
|
|
10175
|
+
options.log.error(`hightea-pipe: dropping the agents subscription failed: ${error instanceof Error ? error.name : typeof error}`);
|
|
10176
|
+
}
|
|
10177
|
+
return { ok: true, result: { rows: shown } };
|
|
10178
|
+
}
|
|
10179
|
+
async function answerHostRequest(input, options) {
|
|
10180
|
+
const parsed = HostRequestSchema.safeParse(input);
|
|
10181
|
+
if (!parsed.success)
|
|
10182
|
+
return { ok: false, reason: "outside" };
|
|
10183
|
+
const request = parsed.data;
|
|
10184
|
+
if (request.workspaceId !== options.houseId)
|
|
10185
|
+
return { ok: false, reason: "unmapped" };
|
|
10186
|
+
if (isHostScopedMethod(request.method)) {
|
|
10187
|
+
if (request.agentMemberId !== undefined)
|
|
10188
|
+
return { ok: false, reason: "outside" };
|
|
10189
|
+
return runHostCommand(options, request.method, request.params);
|
|
10190
|
+
}
|
|
10191
|
+
if (request.method === "x-ahpd/agents/list") {
|
|
10192
|
+
if (request.agentMemberId !== undefined)
|
|
10193
|
+
return { ok: false, reason: "outside" };
|
|
10194
|
+
if (Object.keys(request.params).length !== 0)
|
|
10195
|
+
return { ok: false, reason: "outside" };
|
|
10196
|
+
return listHostAgents(options);
|
|
10197
|
+
}
|
|
10198
|
+
if (request.agentMemberId === undefined)
|
|
10199
|
+
return { ok: false, reason: "outside" };
|
|
10200
|
+
const agent = options.agents.get(request.agentMemberId);
|
|
10201
|
+
if (agent === undefined || agent.provider !== request.params.id)
|
|
10202
|
+
return { ok: false, reason: "unmapped" };
|
|
10203
|
+
const params = request.method === "x-ahpd/agents/put" && isCreate(request.params) ? { ...request.params, owner: HOST_RECORD_OWNER } : request.params;
|
|
10204
|
+
return runHostCommand(options, request.method, params);
|
|
10205
|
+
}
|
|
10206
|
+
async function runHostCommand(options, method, params) {
|
|
10207
|
+
try {
|
|
10208
|
+
const result = await options.peer.request(method, params, HOST_LOCAL_TIMEOUT_MS);
|
|
10209
|
+
return { ok: true, result: result ?? null };
|
|
10210
|
+
} catch (error) {
|
|
10211
|
+
const answered = refusal(error);
|
|
10212
|
+
if (answered !== undefined)
|
|
10213
|
+
return { ok: false, reason: "refused", ...answered };
|
|
10214
|
+
options.log.error(`hightea-pipe: host request ${method} ended without an answer` + (timedOut(error) ? " (timed out)" : "") + `: ${error instanceof Error ? error.name : typeof error}`);
|
|
10215
|
+
return { ok: false, reason: "timedOut" };
|
|
10216
|
+
}
|
|
10217
|
+
}
|
|
10218
|
+
|
|
9736
10219
|
// ../ahp-host/src/index.ts
|
|
9737
10220
|
class ActiveTurnTokenVault {
|
|
9738
10221
|
#activeBySession = new Map;
|
|
@@ -9771,6 +10254,7 @@ class ActiveTurnTokenVault {
|
|
|
9771
10254
|
token: entry.token,
|
|
9772
10255
|
deliveryId: entry.deliveryId,
|
|
9773
10256
|
threadRef: entry.threadRef,
|
|
10257
|
+
agentMemberId: entry.agentMemberId,
|
|
9774
10258
|
...entry.afterMessageId === undefined ? {} : { afterMessageId: entry.afterMessageId }
|
|
9775
10259
|
};
|
|
9776
10260
|
}
|
|
@@ -9799,6 +10283,314 @@ class ActiveTurnTokenVault {
|
|
|
9799
10283
|
}
|
|
9800
10284
|
}
|
|
9801
10285
|
|
|
10286
|
+
// ../ahp-host/src/ask-gate.ts
|
|
10287
|
+
import { createPrivateKey, createPublicKey as createPublicKey2, generateKeyPairSync, sign } from "node:crypto";
|
|
10288
|
+
import { appendFile, chmod, readFile, rename, writeFile } from "node:fs/promises";
|
|
10289
|
+
import { join as join2 } from "node:path";
|
|
10290
|
+
|
|
10291
|
+
// ../ahp/src/signed-post.ts
|
|
10292
|
+
function signedPostText(fields) {
|
|
10293
|
+
return JSON.stringify({
|
|
10294
|
+
v: 1,
|
|
10295
|
+
workspaceId: fields.workspaceId,
|
|
10296
|
+
roomId: fields.roomId,
|
|
10297
|
+
rootMessageId: fields.rootMessageId,
|
|
10298
|
+
authorMemberId: fields.authorMemberId,
|
|
10299
|
+
clientId: fields.clientId,
|
|
10300
|
+
body: fields.body,
|
|
10301
|
+
attachmentIds: [...fields.attachmentIds],
|
|
10302
|
+
createdAt: fields.createdAt
|
|
10303
|
+
});
|
|
10304
|
+
}
|
|
10305
|
+
function signedPostBytes(fields) {
|
|
10306
|
+
return new TextEncoder().encode(signedPostText(fields));
|
|
10307
|
+
}
|
|
10308
|
+
|
|
10309
|
+
// ../ahp-host/src/signed-asks.ts
|
|
10310
|
+
import { createPublicKey, verify } from "node:crypto";
|
|
10311
|
+
var ED25519_SPKI_HEADER = Buffer.from("302a300506032b6570032100", "hex");
|
|
10312
|
+
function checkSignature(message, context) {
|
|
10313
|
+
const signed = message.signed;
|
|
10314
|
+
if (signed === undefined)
|
|
10315
|
+
return { ok: false, code: "ASK_UNSIGNED", why: `message ${message.id} carries no signature` };
|
|
10316
|
+
const key = context.keys.find((trusted) => trusted.keyId === signed.keyId);
|
|
10317
|
+
if (key === undefined)
|
|
10318
|
+
return { ok: false, code: "ASK_UNSIGNED", why: `message ${message.id} is signed by key ${signed.keyId}, which this host does not trust` };
|
|
10319
|
+
const bytes = signedPostBytes({
|
|
10320
|
+
workspaceId: context.workspaceId,
|
|
10321
|
+
roomId: context.roomId,
|
|
10322
|
+
rootMessageId: message.replyTo ?? null,
|
|
10323
|
+
authorMemberId: message.from.memberId,
|
|
10324
|
+
clientId: signed.clientId,
|
|
10325
|
+
body: message.text,
|
|
10326
|
+
attachmentIds: signed.attachmentIds,
|
|
10327
|
+
createdAt: signed.createdAt
|
|
10328
|
+
});
|
|
10329
|
+
const signature = Buffer.from(signed.signature, "base64url");
|
|
10330
|
+
const publicKey = createPublicKey({ key: Buffer.concat([ED25519_SPKI_HEADER, Buffer.from(key.publicKey, "base64url")]), format: "der", type: "spki" });
|
|
10331
|
+
if (signature.length !== 64 || !verify(null, bytes, publicKey, signature)) {
|
|
10332
|
+
return { ok: false, code: "ASK_UNSIGNED", why: `message ${message.id}'s signature by ${key.name} does not match what the room returned (text, thread, author ${message.from.memberId}, or attachments)` };
|
|
10333
|
+
}
|
|
10334
|
+
if (context.ownKeyId !== undefined && key.keyId === context.ownKeyId && !context.ownAgents.has(message.from.memberId)) {
|
|
10335
|
+
return { ok: false, code: "KEY_NOT_FOR_AUTHOR", why: `message ${message.id} is signed by this host's key but attributed to ${message.from.memberId}, which this host does not run` };
|
|
10336
|
+
}
|
|
10337
|
+
return { ok: true, keyName: key.name, clientId: signed.clientId, createdAt: signed.createdAt };
|
|
10338
|
+
}
|
|
10339
|
+
function signedThreadView(read, context) {
|
|
10340
|
+
const shown = (message) => message.deleted === true ? { id: message.id, deleted: true } : message;
|
|
10341
|
+
const passes = (message) => message.deleted === true || checkSignature(message, context).ok;
|
|
10342
|
+
const rootPasses = passes(read.root);
|
|
10343
|
+
const replies = read.replies.filter(passes).map(shown);
|
|
10344
|
+
const omitted = (rootPasses ? 0 : 1) + read.replies.length - read.replies.filter(passes).length;
|
|
10345
|
+
return {
|
|
10346
|
+
...read,
|
|
10347
|
+
root: rootPasses ? shown(read.root) : { id: read.root.id, omitted: true },
|
|
10348
|
+
replies,
|
|
10349
|
+
...omitted === 0 ? {} : { omitted: `${String(omitted)} unsigned messages omitted` }
|
|
10350
|
+
};
|
|
10351
|
+
}
|
|
10352
|
+
|
|
10353
|
+
// ../ahp-host/src/trusted-keys.ts
|
|
10354
|
+
import { createHash } from "node:crypto";
|
|
10355
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10356
|
+
import { join } from "node:path";
|
|
10357
|
+
var TRUSTED_KEYS_FILE = "trusted-keys.json";
|
|
10358
|
+
var TRUSTED_KEY_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
|
|
10359
|
+
var BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u;
|
|
10360
|
+
var base64url2 = (bytes) => Buffer.from(bytes).toString("base64url");
|
|
10361
|
+
function trustedKeyId(publicKey) {
|
|
10362
|
+
if (!BASE64URL_32_BYTES.test(publicKey)) {
|
|
10363
|
+
return { error: "TRUST_KEY_INVALID: the public key must be 43 base64url characters (a raw 32-byte Ed25519 key), as the browser's Members page shows it" };
|
|
10364
|
+
}
|
|
10365
|
+
return { keyId: base64url2(createHash("sha256").update(Buffer.from(publicKey, "base64url")).digest()) };
|
|
10366
|
+
}
|
|
10367
|
+
function readTrustedKeys(configDir) {
|
|
10368
|
+
const file = join(configDir, TRUSTED_KEYS_FILE);
|
|
10369
|
+
if (!existsSync(file))
|
|
10370
|
+
return { state: "missing", file };
|
|
10371
|
+
let parsed;
|
|
10372
|
+
try {
|
|
10373
|
+
parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
10374
|
+
} catch (error) {
|
|
10375
|
+
throw new Error(`TRUST_FILE_UNREADABLE: ${file} is not JSON (${error.message})`);
|
|
10376
|
+
}
|
|
10377
|
+
const record = parsed;
|
|
10378
|
+
if (typeof parsed !== "object" || parsed === null || record.v !== 1 || !Array.isArray(record.keys)) {
|
|
10379
|
+
throw new Error(`TRUST_FILE_UNREADABLE: ${file} is not a version 1 list of trusted keys`);
|
|
10380
|
+
}
|
|
10381
|
+
for (const key of record.keys) {
|
|
10382
|
+
const row = key;
|
|
10383
|
+
const id = typeof row.publicKey === "string" ? trustedKeyId(row.publicKey) : undefined;
|
|
10384
|
+
if (typeof row.name !== "string" || !TRUSTED_KEY_NAME.test(row.name) || id === undefined || "error" in id || row.keyId !== id.keyId || typeof row.addedAt !== "string") {
|
|
10385
|
+
throw new Error(`TRUST_FILE_UNREADABLE: ${file} holds an entry that is not a valid trusted key: ${JSON.stringify(key)}`);
|
|
10386
|
+
}
|
|
10387
|
+
}
|
|
10388
|
+
return { state: "read", file, keys: record.keys };
|
|
10389
|
+
}
|
|
10390
|
+
|
|
10391
|
+
// ../ahp-host/src/ask-gate.ts
|
|
10392
|
+
class AskRefusal extends Error {
|
|
10393
|
+
code;
|
|
10394
|
+
constructor(code, why) {
|
|
10395
|
+
super(`${code}: ${why}`);
|
|
10396
|
+
this.code = code;
|
|
10397
|
+
}
|
|
10398
|
+
}
|
|
10399
|
+
var HOST_SIGNING_KEY_FILE = "host-signing-key";
|
|
10400
|
+
var ACTED_ASKS_FILE = "hightea-acted-asks.jsonl";
|
|
10401
|
+
var ASK_FRESH_MS = 10 * 60000;
|
|
10402
|
+
var ACTED_KEEP_MS = 30 * 24 * 60 * 60000;
|
|
10403
|
+
var THREAD_PAGES_MAX = 20;
|
|
10404
|
+
async function hostSigningKey(configDir, now = () => Date.now()) {
|
|
10405
|
+
const file = join2(configDir, HOST_SIGNING_KEY_FILE);
|
|
10406
|
+
let pem;
|
|
10407
|
+
try {
|
|
10408
|
+
pem = await readFile(file, "utf8");
|
|
10409
|
+
} catch (error) {
|
|
10410
|
+
if (error.code !== "ENOENT") {
|
|
10411
|
+
throw new Error(`HOST_KEY_UNREADABLE: ${file} exists but cannot be read (${String(error)}); it is never regenerated, fix or remove it by hand`);
|
|
10412
|
+
}
|
|
10413
|
+
}
|
|
10414
|
+
if (pem === undefined) {
|
|
10415
|
+
const made = generateKeyPairSync("ed25519").privateKey.export({ format: "pem", type: "pkcs8" }).toString();
|
|
10416
|
+
const temporary = `${file}.${String(process.pid)}.tmp`;
|
|
10417
|
+
await writeFile(temporary, made, { mode: 384, flag: "wx" });
|
|
10418
|
+
await chmod(temporary, 384);
|
|
10419
|
+
await rename(temporary, file);
|
|
10420
|
+
pem = made;
|
|
10421
|
+
}
|
|
10422
|
+
let privateKey;
|
|
10423
|
+
try {
|
|
10424
|
+
privateKey = createPrivateKey({ key: pem, format: "pem" });
|
|
10425
|
+
if (privateKey.asymmetricKeyType !== "ed25519")
|
|
10426
|
+
throw new Error(`a ${String(privateKey.asymmetricKeyType)} key, not Ed25519`);
|
|
10427
|
+
} catch (error) {
|
|
10428
|
+
throw new Error(`HOST_KEY_UNREADABLE: ${file} is not an Ed25519 PKCS8 key (${String(error)}); it is never regenerated, fix or remove it by hand`);
|
|
10429
|
+
}
|
|
10430
|
+
const publicKey = createPublicKey2(privateKey).export({ format: "jwk" }).x;
|
|
10431
|
+
const id = publicKey === undefined ? { error: "no public key" } : trustedKeyId(publicKey);
|
|
10432
|
+
if ("error" in id)
|
|
10433
|
+
throw new Error(`HOST_KEY_UNREADABLE: ${file}: ${id.error}`);
|
|
10434
|
+
return { privateKey, trusted: { name: "this-host", keyId: id.keyId, publicKey, addedAt: new Date(now()).toISOString() } };
|
|
10435
|
+
}
|
|
10436
|
+
function signHostPost(key, post, now = () => Date.now()) {
|
|
10437
|
+
const createdAt = new Date(now()).toISOString();
|
|
10438
|
+
const bytes = signedPostBytes({ ...post, attachmentIds: [], createdAt });
|
|
10439
|
+
return { keyId: key.trusted.keyId, createdAt, signature: sign(null, bytes, key.privateKey).toString("base64url") };
|
|
10440
|
+
}
|
|
10441
|
+
async function signatureContext(options, roomId) {
|
|
10442
|
+
if (options.configDir === undefined)
|
|
10443
|
+
throw new AskRefusal("ROOM_ASKS_UNTRUSTED", "this host's ahpd is too old for signed asks (it names no configDir)");
|
|
10444
|
+
const hostKey = await options.hostKey;
|
|
10445
|
+
if (hostKey instanceof Error)
|
|
10446
|
+
throw new AskRefusal("ROOM_ASKS_UNTRUSTED", hostKey.message);
|
|
10447
|
+
let keys;
|
|
10448
|
+
try {
|
|
10449
|
+
const read = await readTrustedKeys(options.configDir);
|
|
10450
|
+
keys = read.state === "read" ? read.keys : [];
|
|
10451
|
+
} catch (error) {
|
|
10452
|
+
throw new AskRefusal("ROOM_ASKS_UNTRUSTED", String(error instanceof Error ? error.message : error));
|
|
10453
|
+
}
|
|
10454
|
+
if (keys.length === 0)
|
|
10455
|
+
throw new AskRefusal("ROOM_ASKS_UNTRUSTED", "this host trusts no key yet; its owner runs `hightea host trust add`");
|
|
10456
|
+
const own = hostKey?.trusted;
|
|
10457
|
+
return {
|
|
10458
|
+
workspaceId: options.houseId,
|
|
10459
|
+
roomId,
|
|
10460
|
+
keys: own === undefined || keys.some((key) => key.keyId === own.keyId) ? keys : [...keys, own],
|
|
10461
|
+
...own === undefined ? {} : { ownKeyId: own.keyId },
|
|
10462
|
+
ownAgents: options.ownAgents
|
|
10463
|
+
};
|
|
10464
|
+
}
|
|
10465
|
+
function threadOf(threadRef) {
|
|
10466
|
+
const [roomId, rootMessageId, extra] = threadRef.split("/");
|
|
10467
|
+
if (!roomId || !rootMessageId || extra !== undefined)
|
|
10468
|
+
throw new AskRefusal("ASK_UNSIGNED", `the wake's thread ref ${threadRef} names no room thread`);
|
|
10469
|
+
return { roomId, rootMessageId };
|
|
10470
|
+
}
|
|
10471
|
+
|
|
10472
|
+
class AskGate {
|
|
10473
|
+
#options;
|
|
10474
|
+
#acted;
|
|
10475
|
+
#writes = Promise.resolve();
|
|
10476
|
+
constructor(options) {
|
|
10477
|
+
this.#options = options;
|
|
10478
|
+
}
|
|
10479
|
+
async admit(meta, token) {
|
|
10480
|
+
const { roomId, rootMessageId } = threadOf(meta.threadRef);
|
|
10481
|
+
const context = await signatureContext(this.#options, roomId);
|
|
10482
|
+
const wanted = meta.triggeringMessageIds;
|
|
10483
|
+
if (wanted === undefined)
|
|
10484
|
+
throw new AskRefusal("ASK_UNSIGNED", `wake ${meta.deliveryId} names no triggering message to check`);
|
|
10485
|
+
const found = await this.#triggers(token, roomId, rootMessageId, meta.afterMessageId, new Set(wanted));
|
|
10486
|
+
const now = (this.#options.now ?? Date.now)();
|
|
10487
|
+
const acted = await this.#load(now);
|
|
10488
|
+
const admitted = [];
|
|
10489
|
+
for (const id of wanted) {
|
|
10490
|
+
const message = found.get(id);
|
|
10491
|
+
if (message === undefined)
|
|
10492
|
+
throw new AskRefusal("ASK_UNSIGNED", `triggering message ${id} is not in thread ${meta.threadRef}`);
|
|
10493
|
+
const check = checkSignature(message, context);
|
|
10494
|
+
if (!check.ok)
|
|
10495
|
+
throw new AskRefusal(check.code, check.why);
|
|
10496
|
+
const before = acted.filter((one) => one.clientId === check.clientId);
|
|
10497
|
+
if (before.some((one) => one.deliveryId !== meta.deliveryId)) {
|
|
10498
|
+
throw new AskRefusal("REPLAYED_ASK", `the ask signed as ${check.clientId} (message ${id}) was already acted on under another wake`);
|
|
10499
|
+
}
|
|
10500
|
+
if (before.length > 0) {
|
|
10501
|
+
const first = Math.min(...before.map((one) => one.at));
|
|
10502
|
+
if (now - first > ASK_FRESH_MS) {
|
|
10503
|
+
throw new AskRefusal("REPLAYED_ASK", `wake ${meta.deliveryId} was first admitted at ${new Date(first).toISOString()}, more than 10 minutes ago; a new attempt of it is not admitted`);
|
|
10504
|
+
}
|
|
10505
|
+
continue;
|
|
10506
|
+
}
|
|
10507
|
+
const signedAt = Date.parse(check.createdAt);
|
|
10508
|
+
if (!Number.isFinite(signedAt) || Math.abs(now - signedAt) > ASK_FRESH_MS) {
|
|
10509
|
+
throw new AskRefusal("ASK_STALE", `message ${id} was signed at ${check.createdAt}, more than 10 minutes from this host's clock`);
|
|
10510
|
+
}
|
|
10511
|
+
admitted.push({ clientId: check.clientId, deliveryId: meta.deliveryId, at: now });
|
|
10512
|
+
}
|
|
10513
|
+
if (admitted.length > 0)
|
|
10514
|
+
await this.#remember(acted, admitted);
|
|
10515
|
+
}
|
|
10516
|
+
async view(threadRef, read) {
|
|
10517
|
+
return signedThreadView(read, await signatureContext(this.#options, threadOf(threadRef).roomId));
|
|
10518
|
+
}
|
|
10519
|
+
async#triggers(token, roomId, rootMessageId, after, wanted) {
|
|
10520
|
+
const found = new Map;
|
|
10521
|
+
let cursor = after ?? rootMessageId;
|
|
10522
|
+
for (let page = 0;page < THREAD_PAGES_MAX; page++) {
|
|
10523
|
+
const read = await this.#options.readThread(token, { roomId, messageId: rootMessageId, after: cursor });
|
|
10524
|
+
if (!isThreadRead(read))
|
|
10525
|
+
throw new AskRefusal("ASK_UNSIGNED", `read_thread answered no root and replies for ${roomId}/${rootMessageId}`);
|
|
10526
|
+
for (const message of [read.root, ...read.replies])
|
|
10527
|
+
if (wanted.has(message.id))
|
|
10528
|
+
found.set(message.id, message);
|
|
10529
|
+
const last = read.replies.at(-1);
|
|
10530
|
+
if (found.size === wanted.size || read.more !== true || last === undefined)
|
|
10531
|
+
break;
|
|
10532
|
+
cursor = last.id;
|
|
10533
|
+
}
|
|
10534
|
+
return found;
|
|
10535
|
+
}
|
|
10536
|
+
async#load(now) {
|
|
10537
|
+
this.#acted ??= (async () => {
|
|
10538
|
+
const file = join2(this.#options.configDir, ACTED_ASKS_FILE);
|
|
10539
|
+
let text = "";
|
|
10540
|
+
try {
|
|
10541
|
+
text = await readFile(file, "utf8");
|
|
10542
|
+
} catch (error) {
|
|
10543
|
+
if (error.code !== "ENOENT")
|
|
10544
|
+
throw new AskRefusal("ROOM_ASKS_UNTRUSTED", `${file} cannot be read: ${String(error)}`);
|
|
10545
|
+
}
|
|
10546
|
+
const rows = [];
|
|
10547
|
+
for (const [index, line] of text.split(`
|
|
10548
|
+
`).entries()) {
|
|
10549
|
+
if (line.trim() === "")
|
|
10550
|
+
continue;
|
|
10551
|
+
const row = JSON.parse(line);
|
|
10552
|
+
if (typeof row.clientId !== "string" || typeof row.deliveryId !== "string" || typeof row.at !== "number") {
|
|
10553
|
+
throw new AskRefusal("ROOM_ASKS_UNTRUSTED", `${file} line ${String(index + 1)} is not an acted ask; fix or remove the file by hand`);
|
|
10554
|
+
}
|
|
10555
|
+
rows.push(row);
|
|
10556
|
+
}
|
|
10557
|
+
const kept = rows.filter((row) => now - row.at < ACTED_KEEP_MS);
|
|
10558
|
+
if (kept.length < rows.length)
|
|
10559
|
+
await this.#rewrite(file, kept);
|
|
10560
|
+
return kept;
|
|
10561
|
+
})();
|
|
10562
|
+
const acted = this.#acted;
|
|
10563
|
+
acted.catch(() => {
|
|
10564
|
+
if (this.#acted === acted)
|
|
10565
|
+
this.#acted = undefined;
|
|
10566
|
+
});
|
|
10567
|
+
return acted;
|
|
10568
|
+
}
|
|
10569
|
+
async#rewrite(file, rows) {
|
|
10570
|
+
const temporary = `${file}.${String(process.pid)}.tmp`;
|
|
10571
|
+
await writeFile(temporary, rows.map((row) => `${JSON.stringify(row)}
|
|
10572
|
+
`).join(""), { mode: 384 });
|
|
10573
|
+
await rename(temporary, file);
|
|
10574
|
+
}
|
|
10575
|
+
async#remember(acted, rows) {
|
|
10576
|
+
acted.push(...rows);
|
|
10577
|
+
const file = join2(this.#options.configDir, ACTED_ASKS_FILE);
|
|
10578
|
+
const write = this.#writes.then(() => appendFile(file, rows.map((row) => `${JSON.stringify(row)}
|
|
10579
|
+
`).join(""), { mode: 384 }));
|
|
10580
|
+
this.#writes = write.catch(() => {
|
|
10581
|
+
return;
|
|
10582
|
+
});
|
|
10583
|
+
await write;
|
|
10584
|
+
}
|
|
10585
|
+
}
|
|
10586
|
+
function isThreadRead(value) {
|
|
10587
|
+
if (value === null || typeof value !== "object")
|
|
10588
|
+
return false;
|
|
10589
|
+
const read = value;
|
|
10590
|
+
const isMessage = (one) => one !== null && typeof one === "object" && typeof one.id === "string";
|
|
10591
|
+
return isMessage(read.root) && Array.isArray(read.replies) && read.replies.every(isMessage);
|
|
10592
|
+
}
|
|
10593
|
+
|
|
9802
10594
|
// ../ahp-host/src/runtime.ts
|
|
9803
10595
|
class UnmappedAgent extends Error {
|
|
9804
10596
|
}
|
|
@@ -9810,6 +10602,8 @@ var UNSTARTABLE_AGENT_TEXT = [
|
|
|
9810
10602
|
/: this conversation has no matching configured ACP process authority/u
|
|
9811
10603
|
];
|
|
9812
10604
|
function cloudOperationFailureCode(error) {
|
|
10605
|
+
if (error instanceof AskRefusal)
|
|
10606
|
+
return error.code;
|
|
9813
10607
|
if (error instanceof FrameRefusal)
|
|
9814
10608
|
return "INVALID_OPERATION_SHAPE";
|
|
9815
10609
|
if (error instanceof UnmappedAgent)
|
|
@@ -9874,7 +10668,15 @@ class WakePipe {
|
|
|
9874
10668
|
throw new Error("ahp-host: invalid durable state");
|
|
9875
10669
|
const saved = parsed.data;
|
|
9876
10670
|
for (const [key, session] of saved.sessions) {
|
|
9877
|
-
|
|
10671
|
+
let chatUri;
|
|
10672
|
+
try {
|
|
10673
|
+
chatUri = await this.#resumeSession(session.sessionUri);
|
|
10674
|
+
} catch (error) {
|
|
10675
|
+
if (cloudOperationFailureCode(error) === "UNMAPPED_LOCAL_AGENT") {
|
|
10676
|
+
throw new UnmappedAgent(error instanceof Error ? error.message : String(error), { cause: error });
|
|
10677
|
+
}
|
|
10678
|
+
throw error;
|
|
10679
|
+
}
|
|
9878
10680
|
this.#subscribed.delete(session.sessionUri);
|
|
9879
10681
|
this.peer.notify("unsubscribe", { channel: session.sessionUri });
|
|
9880
10682
|
if (session.chatUri !== undefined && chatUri !== session.chatUri)
|
|
@@ -9995,6 +10797,17 @@ class WakePipe {
|
|
|
9995
10797
|
this.cloud.answer(id, { ok: false, code: "WAKE_NOT_SENT" });
|
|
9996
10798
|
return;
|
|
9997
10799
|
}
|
|
10800
|
+
if (frame?.method === "x-hightea/host-request") {
|
|
10801
|
+
const requestId = String(id ?? "");
|
|
10802
|
+
const answer = await answerHostRequest(frame.params, {
|
|
10803
|
+
houseId: this.options.houseId,
|
|
10804
|
+
agents: this.options.agents,
|
|
10805
|
+
peer: this.peer,
|
|
10806
|
+
log: this.options.log
|
|
10807
|
+
});
|
|
10808
|
+
this.cloud.hostRequestAnswer(requestId, answer);
|
|
10809
|
+
return;
|
|
10810
|
+
}
|
|
9998
10811
|
if (frame?.method === "x-hightea/revoke") {
|
|
9999
10812
|
return this.#revoke(id, frame.params).catch(() => {
|
|
10000
10813
|
if (id !== undefined)
|
|
@@ -10003,6 +10816,9 @@ class WakePipe {
|
|
|
10003
10816
|
}
|
|
10004
10817
|
const decision = checkCloudFrame(frame, this.registry);
|
|
10005
10818
|
if (!decision.ok) {
|
|
10819
|
+
if (decision.code === "WAKE_TEXT_NOT_ALLOWED") {
|
|
10820
|
+
this.options.log.error(`hightea: refused turn ${String(id ?? "")}: its text is not the delivery's own wake (WAKE_TEXT_NOT_ALLOWED); nothing reached the agent`);
|
|
10821
|
+
}
|
|
10006
10822
|
if (id !== undefined)
|
|
10007
10823
|
this.cloud.answer(id, decision);
|
|
10008
10824
|
return;
|
|
@@ -10096,6 +10912,8 @@ class WakePipe {
|
|
|
10096
10912
|
}
|
|
10097
10913
|
if (this.options.tokenExpiresAt(token) === undefined)
|
|
10098
10914
|
throw new FrameRefusal("ahp-host: an agent token whose expiry cannot be read");
|
|
10915
|
+
if (this.options.admitTurn !== undefined)
|
|
10916
|
+
await this.options.admitTurn(meta, token);
|
|
10099
10917
|
const running = this.#active.get(key);
|
|
10100
10918
|
if (running !== undefined) {
|
|
10101
10919
|
if (running.deliveryId === meta.deliveryId) {
|
|
@@ -10362,7 +11180,7 @@ var mappingSchema = object({
|
|
|
10362
11180
|
owner: string2().min(1),
|
|
10363
11181
|
sessionUri: string2().regex(SESSION_URI)
|
|
10364
11182
|
}).strict();
|
|
10365
|
-
var mappingId = (key) => `session-${
|
|
11183
|
+
var mappingId = (key) => `session-${createHash2("sha256").update(key).digest("hex").slice(0, 32)}`;
|
|
10366
11184
|
function recordsPipeStore(records, owner, sessionOwner) {
|
|
10367
11185
|
const known = new Map;
|
|
10368
11186
|
const readMapping = (raw) => {
|
|
@@ -10628,19 +11446,238 @@ function createCloudLink(options) {
|
|
|
10628
11446
|
answer: (id, outcome) => send(outcome.ok ? { jsonrpc: "2.0", id, result: null } : { jsonrpc: "2.0", id, error: { code: -32000, message: outcome.code } }),
|
|
10629
11447
|
status: (frame) => send({ jsonrpc: "2.0", method: "x-hightea/status", params: frame }),
|
|
10630
11448
|
renewToken: (params) => request(`renew:${randomUUID()}`, "x-hightea/renewToken", params),
|
|
10631
|
-
sourcePush: (params) => request(`push:${randomUUID()}`, "x-hightea/source/push", params)
|
|
11449
|
+
sourcePush: (params) => request(`push:${randomUUID()}`, "x-hightea/source/push", params),
|
|
11450
|
+
hostRequestAnswer: (id, outcome) => void send({ jsonrpc: "2.0", id, result: outcome })
|
|
10632
11451
|
};
|
|
10633
11452
|
}
|
|
10634
11453
|
|
|
10635
11454
|
// ../ahp-host/src/km-source.ts
|
|
11455
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
11456
|
+
import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
|
|
11457
|
+
import { createInterface as createInterface2 } from "node:readline";
|
|
11458
|
+
|
|
11459
|
+
// ../ahp-host/src/page-serve.ts
|
|
10636
11460
|
import { spawn } from "node:child_process";
|
|
10637
|
-
import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
|
|
10638
11461
|
import { createInterface } from "node:readline";
|
|
11462
|
+
var STDERR_MAX_BYTES = 64 * 1024;
|
|
11463
|
+
var KILL_GRACE_MS = 2000;
|
|
11464
|
+
var ANSWER_MAX_BYTES = 16 * 1024 * 1024;
|
|
11465
|
+
|
|
11466
|
+
class PageServeFault extends Error {
|
|
11467
|
+
code;
|
|
11468
|
+
constructor(code, message) {
|
|
11469
|
+
super(message);
|
|
11470
|
+
this.code = code;
|
|
11471
|
+
}
|
|
11472
|
+
}
|
|
11473
|
+
function signalGroup(child, signal) {
|
|
11474
|
+
if (child.pid === undefined)
|
|
11475
|
+
return;
|
|
11476
|
+
try {
|
|
11477
|
+
process.kill(-child.pid, signal);
|
|
11478
|
+
} catch {}
|
|
11479
|
+
}
|
|
11480
|
+
function pageServeWhy(exit) {
|
|
11481
|
+
const said = exit.stderr.trim().split(`
|
|
11482
|
+
`).filter((line) => line !== "").pop();
|
|
11483
|
+
const status = exit.code === null ? "on a signal" : `exit ${exit.code}`;
|
|
11484
|
+
return said === undefined ? status : `${status}: ${said.slice(0, 400)}`;
|
|
11485
|
+
}
|
|
11486
|
+
var openPageServe = (argv, signal) => {
|
|
11487
|
+
const [command, ...args] = argv;
|
|
11488
|
+
if (command === undefined)
|
|
11489
|
+
throw new PageServeFault("page-serve-no-command", "the page reader has no command to run");
|
|
11490
|
+
const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], detached: true });
|
|
11491
|
+
let stderr = "";
|
|
11492
|
+
let end;
|
|
11493
|
+
let pending;
|
|
11494
|
+
let seq = 0;
|
|
11495
|
+
let settle = () => {
|
|
11496
|
+
return;
|
|
11497
|
+
};
|
|
11498
|
+
const exited = new Promise((resolve) => {
|
|
11499
|
+
settle = resolve;
|
|
11500
|
+
});
|
|
11501
|
+
const refusePending = (error) => {
|
|
11502
|
+
const held = pending;
|
|
11503
|
+
if (held === undefined)
|
|
11504
|
+
return;
|
|
11505
|
+
pending = undefined;
|
|
11506
|
+
if (held.timer !== undefined)
|
|
11507
|
+
clearTimeout(held.timer);
|
|
11508
|
+
held.reject(error);
|
|
11509
|
+
};
|
|
11510
|
+
const fault = (code, message) => {
|
|
11511
|
+
refusePending(new PageServeFault(code, message));
|
|
11512
|
+
signalGroup(child, "SIGKILL");
|
|
11513
|
+
};
|
|
11514
|
+
const answer = (line) => {
|
|
11515
|
+
if (line.trim() === "")
|
|
11516
|
+
return;
|
|
11517
|
+
let parsed;
|
|
11518
|
+
try {
|
|
11519
|
+
parsed = JSON.parse(line);
|
|
11520
|
+
} catch {
|
|
11521
|
+
fault("page-serve-frame-unparsable", `the reader answered a line that is not JSON: ${line.slice(0, 120)}`);
|
|
11522
|
+
return;
|
|
11523
|
+
}
|
|
11524
|
+
const frame = parsed;
|
|
11525
|
+
const rss = typeof frame.rss === "number" && Number.isFinite(frame.rss) ? frame.rss : undefined;
|
|
11526
|
+
const held = pending;
|
|
11527
|
+
if (held === undefined) {
|
|
11528
|
+
fault("page-serve-frame-unasked", `the reader answered seq ${String(frame.seq)} with no request outstanding`);
|
|
11529
|
+
return;
|
|
11530
|
+
}
|
|
11531
|
+
if (frame.seq !== held.seq) {
|
|
11532
|
+
fault("page-serve-frame-out-of-order", `the reader answered seq ${String(frame.seq)} while seq ${held.seq} was asked`);
|
|
11533
|
+
return;
|
|
11534
|
+
}
|
|
11535
|
+
const refusal = frame.refusal;
|
|
11536
|
+
if (refusal !== undefined && refusal !== null) {
|
|
11537
|
+
pending = undefined;
|
|
11538
|
+
if (held.timer !== undefined)
|
|
11539
|
+
clearTimeout(held.timer);
|
|
11540
|
+
held.resolve({
|
|
11541
|
+
...rss === undefined ? {} : { rss },
|
|
11542
|
+
refusal: {
|
|
11543
|
+
code: typeof refusal.code === "string" ? refusal.code : "page-serve-refused",
|
|
11544
|
+
message: typeof refusal.message === "string" ? refusal.message : "the reader refused without a message",
|
|
11545
|
+
...typeof refusal.hint === "string" ? { hint: refusal.hint } : {}
|
|
11546
|
+
}
|
|
11547
|
+
});
|
|
11548
|
+
return;
|
|
11549
|
+
}
|
|
11550
|
+
if (frame.page === undefined && frame.progress !== undefined) {
|
|
11551
|
+
pending = undefined;
|
|
11552
|
+
if (held.timer !== undefined)
|
|
11553
|
+
clearTimeout(held.timer);
|
|
11554
|
+
held.resolve({ ...rss === undefined ? {} : { rss }, progress: frame.progress });
|
|
11555
|
+
return;
|
|
11556
|
+
}
|
|
11557
|
+
if (frame.page === null || typeof frame.page !== "object" || Array.isArray(frame.page)) {
|
|
11558
|
+
fault("page-serve-frame-malformed", `the reader answered seq ${held.seq} outside the page shape`);
|
|
11559
|
+
return;
|
|
11560
|
+
}
|
|
11561
|
+
held.bytes += line.length;
|
|
11562
|
+
if (held.bytes > ANSWER_MAX_BYTES) {
|
|
11563
|
+
fault("page-serve-answer-too-large", `the reader's answer to seq ${held.seq} exceeded its byte budget (${ANSWER_MAX_BYTES} bytes)`);
|
|
11564
|
+
return;
|
|
11565
|
+
}
|
|
11566
|
+
const complete = frame.page.complete;
|
|
11567
|
+
held.pages.push(frame.page);
|
|
11568
|
+
if (held.traverse && complete !== true)
|
|
11569
|
+
return;
|
|
11570
|
+
pending = undefined;
|
|
11571
|
+
if (held.timer !== undefined)
|
|
11572
|
+
clearTimeout(held.timer);
|
|
11573
|
+
held.resolve({ pages: held.pages, ...rss === undefined ? {} : { rss } });
|
|
11574
|
+
};
|
|
11575
|
+
createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY }).on("line", answer);
|
|
11576
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
11577
|
+
if (stderr.length < STDERR_MAX_BYTES)
|
|
11578
|
+
stderr += chunk;
|
|
11579
|
+
});
|
|
11580
|
+
child.stdin.on("error", () => {
|
|
11581
|
+
if (stderr.length < STDERR_MAX_BYTES)
|
|
11582
|
+
stderr += `
|
|
11583
|
+
hightea-page-serve: the request pipe failed to write`;
|
|
11584
|
+
});
|
|
11585
|
+
child.on("error", (error) => {
|
|
11586
|
+
stderr += `
|
|
11587
|
+
hightea-page-serve: ${error.message}`;
|
|
11588
|
+
});
|
|
11589
|
+
const reaped = new Promise((resolve) => {
|
|
11590
|
+
child.on("close", (code, killed) => {
|
|
11591
|
+
signalGroup(child, "SIGKILL");
|
|
11592
|
+
end = { code: killed === null ? code : null, stderr };
|
|
11593
|
+
refusePending(new PageServeFault("page-serve-reader-exited", `the reader is gone (${pageServeWhy(end)})`));
|
|
11594
|
+
settle(end);
|
|
11595
|
+
resolve();
|
|
11596
|
+
});
|
|
11597
|
+
});
|
|
11598
|
+
const close = async () => {
|
|
11599
|
+
if (end !== undefined)
|
|
11600
|
+
return;
|
|
11601
|
+
child.stdin.end();
|
|
11602
|
+
signalGroup(child, "SIGTERM");
|
|
11603
|
+
const hard = setTimeout(() => signalGroup(child, "SIGKILL"), KILL_GRACE_MS);
|
|
11604
|
+
await reaped;
|
|
11605
|
+
clearTimeout(hard);
|
|
11606
|
+
};
|
|
11607
|
+
signal.addEventListener("abort", () => {
|
|
11608
|
+
close();
|
|
11609
|
+
}, { once: true });
|
|
11610
|
+
return {
|
|
11611
|
+
ask(request, timeoutMs) {
|
|
11612
|
+
if (end !== undefined) {
|
|
11613
|
+
return Promise.reject(new PageServeFault("page-serve-reader-exited", `the reader is gone (${pageServeWhy(end)})`));
|
|
11614
|
+
}
|
|
11615
|
+
if (pending !== undefined) {
|
|
11616
|
+
return Promise.reject(new PageServeFault("page-serve-busy", "a page request is already outstanding"));
|
|
11617
|
+
}
|
|
11618
|
+
const mine = {
|
|
11619
|
+
seq: ++seq,
|
|
11620
|
+
traverse: "traverse" in request && request.traverse === true,
|
|
11621
|
+
pages: [],
|
|
11622
|
+
bytes: 0,
|
|
11623
|
+
resolve: () => {
|
|
11624
|
+
return;
|
|
11625
|
+
},
|
|
11626
|
+
reject: () => {
|
|
11627
|
+
return;
|
|
11628
|
+
},
|
|
11629
|
+
timer: undefined
|
|
11630
|
+
};
|
|
11631
|
+
let settleAnswer = () => {
|
|
11632
|
+
return;
|
|
11633
|
+
};
|
|
11634
|
+
let failAnswer = () => {
|
|
11635
|
+
return;
|
|
11636
|
+
};
|
|
11637
|
+
const asked = new Promise((resolve, reject) => {
|
|
11638
|
+
settleAnswer = resolve;
|
|
11639
|
+
failAnswer = reject;
|
|
11640
|
+
});
|
|
11641
|
+
mine.resolve = settleAnswer;
|
|
11642
|
+
mine.reject = failAnswer;
|
|
11643
|
+
pending = mine;
|
|
11644
|
+
mine.timer = setTimeout(() => {
|
|
11645
|
+
fault("page-serve-timeout", `the reader did not answer seq ${mine.seq} in ${timeoutMs} ms`);
|
|
11646
|
+
}, timeoutMs);
|
|
11647
|
+
try {
|
|
11648
|
+
child.stdin.write(JSON.stringify({ seq: mine.seq, request }) + `
|
|
11649
|
+
`);
|
|
11650
|
+
} catch (error) {
|
|
11651
|
+
fault("page-serve-write-failed", `the request could not be written: ${error instanceof Error ? error.message : String(error)}`);
|
|
11652
|
+
}
|
|
11653
|
+
return asked;
|
|
11654
|
+
},
|
|
11655
|
+
exited,
|
|
11656
|
+
close
|
|
11657
|
+
};
|
|
11658
|
+
};
|
|
11659
|
+
|
|
11660
|
+
// ../ahp-host/src/km-source.ts
|
|
10639
11661
|
var OUTPUT_MAX_BYTES = 16 * 1024 * 1024;
|
|
10640
11662
|
var GENERATIONS_KEPT = 8;
|
|
10641
11663
|
var GENERATION_MAX_MS = 15 * 60000;
|
|
11664
|
+
var KM_PAGE_LIMIT = 1000;
|
|
11665
|
+
var READ_ATTEMPTS = 3;
|
|
10642
11666
|
var UNACKED_MAX = 1e4;
|
|
10643
11667
|
var FEED_RESTART_MS = 5000;
|
|
11668
|
+
var PAGE_SERVE_RSS_CEILING = 512 * 1024 * 1024;
|
|
11669
|
+
var NOTICE_PATIENCE_MS = 30000;
|
|
11670
|
+
var PROGRESS_CEILING_MS = 2000;
|
|
11671
|
+
var WATCH_FLOOR_MS = 2000;
|
|
11672
|
+
var PROGRESS_STALE_FAILURES = 3;
|
|
11673
|
+
var PROGRESS_STALE_MS = 5 * 60000;
|
|
11674
|
+
var REFRESH_TIMING_SAMPLE = 20;
|
|
11675
|
+
function gapOf(name, value) {
|
|
11676
|
+
if (!(Number.isFinite(value) && value >= 0)) {
|
|
11677
|
+
throw new Error(`${name} must be a finite number of milliseconds, 0 or more, not ${String(value)}`);
|
|
11678
|
+
}
|
|
11679
|
+
return value;
|
|
11680
|
+
}
|
|
10644
11681
|
|
|
10645
11682
|
class ItemTooLarge extends Error {
|
|
10646
11683
|
item;
|
|
@@ -10650,6 +11687,14 @@ class ItemTooLarge extends Error {
|
|
|
10650
11687
|
}
|
|
10651
11688
|
}
|
|
10652
11689
|
|
|
11690
|
+
class ListRefused extends Error {
|
|
11691
|
+
stderr;
|
|
11692
|
+
constructor(stderr) {
|
|
11693
|
+
super(`list refused: ${firstCode(stderr)}`);
|
|
11694
|
+
this.stderr = stderr;
|
|
11695
|
+
}
|
|
11696
|
+
}
|
|
11697
|
+
|
|
10653
11698
|
class KmSource {
|
|
10654
11699
|
sourceId;
|
|
10655
11700
|
#epoch = "e_" + randomUUID2();
|
|
@@ -10659,7 +11704,29 @@ class KmSource {
|
|
|
10659
11704
|
#kept = new Map;
|
|
10660
11705
|
#reading;
|
|
10661
11706
|
#readingNo = 0;
|
|
11707
|
+
#cursor;
|
|
11708
|
+
#stream;
|
|
11709
|
+
#serve;
|
|
11710
|
+
#serveUndeclared = false;
|
|
11711
|
+
#serveFailures = 0;
|
|
11712
|
+
#serveRetryAt = -Infinity;
|
|
11713
|
+
#serveTimer;
|
|
11714
|
+
#serveFallbackSaid = false;
|
|
11715
|
+
#degraded = false;
|
|
11716
|
+
#serveRestarts = 0;
|
|
11717
|
+
#hintedSeq;
|
|
11718
|
+
#noticeWaitingSince;
|
|
11719
|
+
#progressCache;
|
|
11720
|
+
#progressRefresh;
|
|
11721
|
+
#progressDirty = false;
|
|
11722
|
+
#progressAt;
|
|
11723
|
+
#progressFailures = 0;
|
|
11724
|
+
#progressFailedSince;
|
|
11725
|
+
#progressFailure;
|
|
11726
|
+
#feedUnparsableSaid = false;
|
|
11727
|
+
#noHeadSaid = false;
|
|
10662
11728
|
#dirty = false;
|
|
11729
|
+
#pendingChangeAt;
|
|
10663
11730
|
#hintTimer;
|
|
10664
11731
|
#queue = [];
|
|
10665
11732
|
#inFlight = false;
|
|
@@ -10668,6 +11735,11 @@ class KmSource {
|
|
|
10668
11735
|
#pushFailures = 0;
|
|
10669
11736
|
#retryAt = -Infinity;
|
|
10670
11737
|
#watching = true;
|
|
11738
|
+
#watchTimer;
|
|
11739
|
+
#watchFloor;
|
|
11740
|
+
#watchRefresh;
|
|
11741
|
+
#refreshes = [];
|
|
11742
|
+
#lastClientReadAt = -Infinity;
|
|
10671
11743
|
#stop = new AbortController;
|
|
10672
11744
|
#feed;
|
|
10673
11745
|
#o;
|
|
@@ -10676,22 +11748,43 @@ class KmSource {
|
|
|
10676
11748
|
#now;
|
|
10677
11749
|
#native;
|
|
10678
11750
|
#duty;
|
|
10679
|
-
#
|
|
11751
|
+
#minIncrementalGap;
|
|
11752
|
+
#minFullGap;
|
|
11753
|
+
#retryMs;
|
|
11754
|
+
#progressCeiling;
|
|
11755
|
+
#lastContinuationUnserved = false;
|
|
10680
11756
|
#readEndedAt = -Infinity;
|
|
10681
11757
|
#readTookMs = 0;
|
|
11758
|
+
#readFailures = 0;
|
|
10682
11759
|
#assigning = new Map;
|
|
10683
11760
|
constructor(options) {
|
|
10684
11761
|
this.#o = options;
|
|
10685
11762
|
this.sourceId = options.config.sourceId;
|
|
10686
11763
|
this.#run = options.run ?? runChild;
|
|
10687
11764
|
this.#coalesce = options.coalesceMs ?? 2000;
|
|
10688
|
-
this.#duty = options.readDuty ?? 0.1;
|
|
11765
|
+
this.#duty = options.readDuty ?? options.config.readDuty ?? 0.1;
|
|
10689
11766
|
if (!(this.#duty > 0 && this.#duty <= 1))
|
|
10690
11767
|
throw new Error(`readDuty must be in (0, 1], not ${this.#duty}`);
|
|
10691
|
-
this.#
|
|
10692
|
-
|
|
10693
|
-
|
|
10694
|
-
|
|
11768
|
+
this.#minIncrementalGap = gapOf("minIncrementalReadGapMs", options.config.minIncrementalReadGapMs);
|
|
11769
|
+
this.#minFullGap = gapOf("minFullReadGapMs", options.config.minFullReadGapMs);
|
|
11770
|
+
this.#retryMs = options.readRetryMs ?? 2000;
|
|
11771
|
+
if (!(Number.isFinite(this.#retryMs) && this.#retryMs >= 0)) {
|
|
11772
|
+
throw new Error(`readRetryMs must be a finite number of milliseconds, 0 or more, not ${this.#retryMs}`);
|
|
11773
|
+
}
|
|
11774
|
+
const progressCeiling = options.progressCeilingMs ?? PROGRESS_CEILING_MS;
|
|
11775
|
+
if (!(Number.isFinite(progressCeiling) && progressCeiling >= 0)) {
|
|
11776
|
+
throw new Error(`progressCeilingMs must be a finite number of milliseconds, 0 or more, not ${progressCeiling}`);
|
|
11777
|
+
}
|
|
11778
|
+
this.#progressCeiling = progressCeiling;
|
|
11779
|
+
const watchFloor = options.watchFloorMs ?? WATCH_FLOOR_MS;
|
|
11780
|
+
if (!(Number.isFinite(watchFloor) && watchFloor >= 0)) {
|
|
11781
|
+
throw new Error(`watchFloorMs must be a finite number of milliseconds, 0 or more, not ${String(watchFloor)}`);
|
|
11782
|
+
}
|
|
11783
|
+
this.#watchFloor = watchFloor;
|
|
11784
|
+
if (options.watchRefreshMs !== undefined && !(Number.isFinite(options.watchRefreshMs) && options.watchRefreshMs >= 0)) {
|
|
11785
|
+
throw new Error(`watchRefreshMs must be a finite number of milliseconds, 0 or more, not ${String(options.watchRefreshMs)}`);
|
|
11786
|
+
}
|
|
11787
|
+
this.#watchRefresh = options.watchRefreshMs;
|
|
10695
11788
|
this.#now = options.now ?? Date.now;
|
|
10696
11789
|
this.#native = new Map(Object.entries(options.config.members).map(([member, owner]) => [owner, member]));
|
|
10697
11790
|
}
|
|
@@ -10699,6 +11792,7 @@ class KmSource {
|
|
|
10699
11792
|
return this.#epoch;
|
|
10700
11793
|
}
|
|
10701
11794
|
start() {
|
|
11795
|
+
this.#reader();
|
|
10702
11796
|
this.#read().catch((error) => this.#o.log.error(`hightea-source: the first read of ${this.sourceId} failed: ${describe2(error)}`));
|
|
10703
11797
|
this.#feed = this.#follow();
|
|
10704
11798
|
}
|
|
@@ -10708,23 +11802,38 @@ class KmSource {
|
|
|
10708
11802
|
clearTimeout(this.#hintTimer);
|
|
10709
11803
|
if (this.#pushTimer !== undefined)
|
|
10710
11804
|
clearTimeout(this.#pushTimer);
|
|
11805
|
+
this.#clearWatchRefresh();
|
|
11806
|
+
if (this.#serveTimer !== undefined)
|
|
11807
|
+
clearTimeout(this.#serveTimer);
|
|
10711
11808
|
await this.#feed;
|
|
10712
11809
|
await this.#reading?.catch(() => {
|
|
10713
11810
|
return;
|
|
10714
11811
|
});
|
|
11812
|
+
await this.#serve?.close().catch((error) => this.#o.log.error(`hightea-source: the km reader of ${this.sourceId} did not close: ${describe2(error)}`));
|
|
10715
11813
|
}
|
|
10716
|
-
hint() {
|
|
11814
|
+
hint(line) {
|
|
11815
|
+
if (line !== undefined) {
|
|
11816
|
+
this.#noteHint(line);
|
|
11817
|
+
const atMs = changeAtOf(line);
|
|
11818
|
+
if (atMs !== undefined)
|
|
11819
|
+
this.#pendingChangeAt = Math.min(this.#pendingChangeAt ?? atMs, atMs);
|
|
11820
|
+
}
|
|
10717
11821
|
if (this.#stop.signal.aborted)
|
|
10718
11822
|
return;
|
|
10719
11823
|
if (this.#reading !== undefined || this.#hintTimer !== undefined) {
|
|
10720
11824
|
this.#dirty = true;
|
|
10721
11825
|
return;
|
|
10722
11826
|
}
|
|
10723
|
-
const
|
|
11827
|
+
const shortFloor = this.#cursor !== undefined && !this.#lastContinuationUnserved;
|
|
11828
|
+
const floor = shortFloor ? this.#minIncrementalGap : this.#minFullGap;
|
|
11829
|
+
const rested = this.#readEndedAt + Math.max(this.#readTookMs * (1 / this.#duty - 1), floor) - this.#now();
|
|
11830
|
+
const delay = Math.max(this.#coalesce, rested);
|
|
11831
|
+
const age = this.#pendingChangeAt === undefined ? undefined : this.#now() - this.#pendingChangeAt;
|
|
11832
|
+
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, next read in ${Math.round(delay)} ms, change age ${age === undefined ? "unavailable" : `${Math.round(age)} ms`}`);
|
|
10724
11833
|
this.#hintTimer = setTimeout(() => {
|
|
10725
11834
|
this.#hintTimer = undefined;
|
|
10726
|
-
this.#read().catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${describe2(error)}`));
|
|
10727
|
-
},
|
|
11835
|
+
this.#read(shortFloor).catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${describe2(error)}`));
|
|
11836
|
+
}, delay);
|
|
10728
11837
|
}
|
|
10729
11838
|
async handle(request) {
|
|
10730
11839
|
const binding = { workspaceId: request.workspaceId, sourceId: request.sourceId, hostId: request.hostId };
|
|
@@ -10737,11 +11846,14 @@ class KmSource {
|
|
|
10737
11846
|
switch (request.op) {
|
|
10738
11847
|
case "watch":
|
|
10739
11848
|
this.#watching = request.args.on;
|
|
10740
|
-
if (this.#watching)
|
|
11849
|
+
if (this.#watching) {
|
|
10741
11850
|
this.#pump();
|
|
11851
|
+
this.#armWatchRefresh();
|
|
11852
|
+
} else
|
|
11853
|
+
this.#clearWatchRefresh();
|
|
10742
11854
|
return { ...binding, op: "watch", outcome: "applied", body: { on: this.#watching } };
|
|
10743
11855
|
case "list":
|
|
10744
|
-
return { ...binding, op: "list", outcome: "applied", body: await this.#page(request.args) };
|
|
11856
|
+
return { ...binding, op: "list", outcome: "applied", ...this.#degraded ? { code: "SOURCE_READER_RESTARTING" } : {}, body: await this.#page(request.args, binding) };
|
|
10745
11857
|
case "read": {
|
|
10746
11858
|
const read = await this.#latest();
|
|
10747
11859
|
return { ...binding, op: "read", outcome: "applied", body: { observation: this.#observed(read, request.args.address) } };
|
|
@@ -10762,37 +11874,41 @@ class KmSource {
|
|
|
10762
11874
|
return refuse("SOURCE_UNAVAILABLE", "unknown");
|
|
10763
11875
|
}
|
|
10764
11876
|
}
|
|
10765
|
-
async#page(args) {
|
|
11877
|
+
async#page(args, binding) {
|
|
10766
11878
|
const token = args.page === undefined ? undefined : decodeToken(args.page);
|
|
10767
11879
|
const kept = token === undefined ? undefined : this.#kept.get(token.generation);
|
|
10768
|
-
const read = kept ?? await this.#read();
|
|
11880
|
+
const read = kept ?? await this.#read(false, true);
|
|
11881
|
+
if (kept === undefined)
|
|
11882
|
+
this.#lastClientReadAt = this.#now();
|
|
10769
11883
|
const offset = kept === undefined ? 0 : token.offset;
|
|
11884
|
+
const stale = this.#progressStale();
|
|
10770
11885
|
const rows = [];
|
|
11886
|
+
const page = (end, items) => ({
|
|
11887
|
+
generation: read.generation,
|
|
11888
|
+
snapshot: read.snapshot,
|
|
11889
|
+
base: { epoch: read.epoch, ordinal: String(read.base) },
|
|
11890
|
+
rows: items,
|
|
11891
|
+
next: end >= read.rows.length ? null : encodeToken(read.generation, end),
|
|
11892
|
+
complete: end >= read.rows.length,
|
|
11893
|
+
...this.#progressAt === undefined ? {} : { progressAsOf: new Date(this.#progressAt).toISOString() },
|
|
11894
|
+
...stale === undefined ? {} : { progressStale: stale }
|
|
11895
|
+
});
|
|
10771
11896
|
let bytes = 0;
|
|
10772
11897
|
let next = offset;
|
|
10773
11898
|
while (next < read.rows.length && rows.length < args.limit) {
|
|
10774
11899
|
const row = read.rows[next].row;
|
|
10775
11900
|
const size = sourceFrameBytes(row);
|
|
10776
|
-
|
|
11901
|
+
const envelope = sourceFrameBytes({ ...binding, op: "list", outcome: "applied", body: page(next + 1, []) });
|
|
11902
|
+
if (envelope + bytes + size + rows.length > SOURCE_PAGE_BUDGET_BYTES) {
|
|
10777
11903
|
if (rows.length === 0)
|
|
10778
11904
|
throw new ItemTooLarge(row.address);
|
|
10779
11905
|
break;
|
|
10780
11906
|
}
|
|
10781
|
-
if (rows.length > 0 && bytes + size > SOURCE_PAGE_BUDGET_BYTES)
|
|
10782
|
-
break;
|
|
10783
11907
|
rows.push(row);
|
|
10784
11908
|
bytes += size;
|
|
10785
11909
|
next++;
|
|
10786
11910
|
}
|
|
10787
|
-
|
|
10788
|
-
return {
|
|
10789
|
-
generation: read.generation,
|
|
10790
|
-
snapshot: read.snapshot,
|
|
10791
|
-
base: { epoch: read.epoch, ordinal: String(read.base) },
|
|
10792
|
-
rows,
|
|
10793
|
-
next: complete ? null : encodeToken(read.generation, next),
|
|
10794
|
-
complete
|
|
10795
|
-
};
|
|
11911
|
+
return page(next, rows);
|
|
10796
11912
|
}
|
|
10797
11913
|
async#assign(request, binding) {
|
|
10798
11914
|
const { address, ownerMemberId, expectedOwner, intentId } = request.args;
|
|
@@ -10803,6 +11919,21 @@ class KmSource {
|
|
|
10803
11919
|
const key = this.#keyOf(address);
|
|
10804
11920
|
if (key === undefined)
|
|
10805
11921
|
return { ...binding, op: "assign", outcome: "refused", code: "INVALID_ADDRESS" };
|
|
11922
|
+
let env;
|
|
11923
|
+
if (this.#o.config.serviceIdentity) {
|
|
11924
|
+
try {
|
|
11925
|
+
const identity = this.#o.serviceIdentityEnvironment?.(this.sourceId);
|
|
11926
|
+
if (!identity?.HAB_ID_TOKEN_FILE)
|
|
11927
|
+
throw new Error("SERVICE_IDENTITY_UNAVAILABLE");
|
|
11928
|
+
env = { HAB_ID_TOKEN_FILE: identity.HAB_ID_TOKEN_FILE };
|
|
11929
|
+
} catch (error) {
|
|
11930
|
+
if (!(error instanceof Error) || !/^SERVICE_IDENTITY_(?:NOT_GRANTED|UNAVAILABLE)(?::|$)/u.test(error.message))
|
|
11931
|
+
throw error;
|
|
11932
|
+
const code = error instanceof Error && error.message.startsWith("SERVICE_IDENTITY_NOT_GRANTED") ? "SERVICE_IDENTITY_NOT_GRANTED" : "SERVICE_IDENTITY_UNAVAILABLE";
|
|
11933
|
+
this.#o.log.error(`hightea-source: assign ${intentId} on ${this.sourceId}: ${code}`);
|
|
11934
|
+
return { ...binding, op: "assign", outcome: "unknown", code };
|
|
11935
|
+
}
|
|
11936
|
+
}
|
|
10806
11937
|
const requester = { authority: `hightea:${request.workspaceId}`, subject: request.caller.memberId };
|
|
10807
11938
|
const ran = await this.#yrd([
|
|
10808
11939
|
"issues",
|
|
@@ -10815,7 +11946,7 @@ class KmSource {
|
|
|
10815
11946
|
JSON.stringify(expected),
|
|
10816
11947
|
"--requested-by",
|
|
10817
11948
|
JSON.stringify(requester)
|
|
10818
|
-
]);
|
|
11949
|
+
], env);
|
|
10819
11950
|
const read = await this.#readAfter();
|
|
10820
11951
|
const observation = this.#observed(read, address);
|
|
10821
11952
|
const owner = observation.change.op === "upsert" ? observation.change.row.columns.owner : null;
|
|
@@ -10852,9 +11983,118 @@ class KmSource {
|
|
|
10852
11983
|
async#latest() {
|
|
10853
11984
|
return this.#current ?? await this.#read();
|
|
10854
11985
|
}
|
|
10855
|
-
#
|
|
11986
|
+
#reader() {
|
|
11987
|
+
if (this.#stop.signal.aborted || this.#serveUndeclared)
|
|
11988
|
+
return;
|
|
11989
|
+
if (this.#serve !== undefined)
|
|
11990
|
+
return this.#serve;
|
|
11991
|
+
if (this.#now() < this.#serveRetryAt)
|
|
11992
|
+
return;
|
|
11993
|
+
const open = this.#o.openServe ?? openPageServe;
|
|
11994
|
+
let reader;
|
|
11995
|
+
try {
|
|
11996
|
+
reader = open([...this.#o.config.yrd, "issues", "list-page-serve", "--project-root", this.#o.config.projectRoot], this.#stop.signal);
|
|
11997
|
+
} catch (error) {
|
|
11998
|
+
this.#readerEnded(undefined, { code: null, stderr: describe2(error) });
|
|
11999
|
+
return;
|
|
12000
|
+
}
|
|
12001
|
+
this.#serve = reader;
|
|
12002
|
+
reader.exited.then((exit) => this.#readerEnded(reader, exit), (error) => this.#readerEnded(reader, { code: null, stderr: describe2(error) }));
|
|
12003
|
+
return reader;
|
|
12004
|
+
}
|
|
12005
|
+
#readerEnded(reader, exit) {
|
|
12006
|
+
if (reader !== undefined && this.#serve !== reader)
|
|
12007
|
+
return;
|
|
12008
|
+
if (this.#serve === reader)
|
|
12009
|
+
this.#serve = undefined;
|
|
12010
|
+
if (this.#stop.signal.aborted)
|
|
12011
|
+
return;
|
|
12012
|
+
this.#serveFailures++;
|
|
12013
|
+
const delay = Math.min(this.#retryMs * 2 ** Math.min(this.#serveFailures - 1, 5), 60000);
|
|
12014
|
+
this.#serveRetryAt = this.#now() + delay;
|
|
12015
|
+
if (undeclaredReader(exit.stderr)) {
|
|
12016
|
+
this.#serveUndeclared = true;
|
|
12017
|
+
this.#o.log.error(`hightea-source: ${this.sourceId} declares no list-page-serve (${pageServeWhy(exit)}); reading with list-page, one process per read`);
|
|
12018
|
+
return;
|
|
12019
|
+
}
|
|
12020
|
+
this.#degraded = true;
|
|
12021
|
+
this.#serveRestarts++;
|
|
12022
|
+
this.#o.log.error(`hightea-source: ${this.sourceId}: km reader restarting, ${pageServeWhy(exit)} (restart ${this.#serveRestarts}, attempt ${this.#serveFailures}, in ${Math.round(delay / 1000)} s)`);
|
|
12023
|
+
if (this.#serveTimer !== undefined)
|
|
12024
|
+
return;
|
|
12025
|
+
this.#serveTimer = setTimeout(() => {
|
|
12026
|
+
this.#serveTimer = undefined;
|
|
12027
|
+
if (this.#stop.signal.aborted || this.#reader() === undefined)
|
|
12028
|
+
return;
|
|
12029
|
+
this.#o.log.info?.(`hightea-source: the km reader of ${this.sourceId} is back; reading it once to catch up`);
|
|
12030
|
+
this.#read().catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after the km reader returned failed: ${describe2(error)}`));
|
|
12031
|
+
}, delay);
|
|
12032
|
+
}
|
|
12033
|
+
async#listPage(request) {
|
|
12034
|
+
const reader = this.#reader();
|
|
12035
|
+
if (reader !== undefined) {
|
|
12036
|
+
try {
|
|
12037
|
+
const { progress: _progress, ...framed } = request;
|
|
12038
|
+
const answer = await reader.ask(framed, this.#o.childTimeoutMs ?? 120000);
|
|
12039
|
+
if ("refusal" in answer) {
|
|
12040
|
+
const { code, message, hint } = answer.refusal;
|
|
12041
|
+
return { ok: false, stderr: `page-serve: ${code}: ${message}${hint === undefined ? "" : ` (${hint})`}` };
|
|
12042
|
+
}
|
|
12043
|
+
this.#serveFailures = 0;
|
|
12044
|
+
this.#serveFallbackSaid = false;
|
|
12045
|
+
this.#degraded = false;
|
|
12046
|
+
const ceiling = this.#o.pageServeCeilingBytes ?? PAGE_SERVE_RSS_CEILING;
|
|
12047
|
+
if (answer.rss !== undefined && answer.rss > ceiling) {
|
|
12048
|
+
this.#o.log.error(`hightea-source: ${this.sourceId}: km reader restarting, rss ${mib(answer.rss)} MiB is above its ${mib(ceiling)} MiB ceiling (restart ${this.#serveRestarts + 1})`);
|
|
12049
|
+
reader.close();
|
|
12050
|
+
}
|
|
12051
|
+
if (!("pages" in answer)) {
|
|
12052
|
+
throw new PageServeFault("page-serve-frame-malformed", "the reader answered a progress frame where the page was asked for");
|
|
12053
|
+
}
|
|
12054
|
+
return { ok: true, stdout: pageFrames(answer.pages), from: "reader" };
|
|
12055
|
+
} catch (error) {
|
|
12056
|
+
if (!(error instanceof PageServeFault))
|
|
12057
|
+
throw error;
|
|
12058
|
+
this.#o.log.error(`hightea-source: ${this.sourceId}: km reader restarting, ${describe2(error)}; this read uses list-page`);
|
|
12059
|
+
}
|
|
12060
|
+
}
|
|
12061
|
+
if (!this.#serveUndeclared && !this.#serveFallbackSaid) {
|
|
12062
|
+
this.#serveFallbackSaid = true;
|
|
12063
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId} reads with list-page while its km reader restarts; one process per read`);
|
|
12064
|
+
}
|
|
12065
|
+
const ran = await this.#yrd(["issues", "list-page", JSON.stringify(request)]);
|
|
12066
|
+
return ran.code === 0 ? { ok: true, stdout: ran.stdout, from: "one-shot" } : { ok: false, stderr: ran.stderr };
|
|
12067
|
+
}
|
|
12068
|
+
#noteHint(line) {
|
|
12069
|
+
try {
|
|
12070
|
+
const record = JSON.parse(line);
|
|
12071
|
+
if (record.source === "item-history")
|
|
12072
|
+
return;
|
|
12073
|
+
if (typeof record.seq === "number" && Number.isSafeInteger(record.seq)) {
|
|
12074
|
+
this.#hintedSeq = Math.max(this.#hintedSeq ?? 0, record.seq);
|
|
12075
|
+
}
|
|
12076
|
+
} catch {
|
|
12077
|
+
if (this.#feedUnparsableSaid)
|
|
12078
|
+
return;
|
|
12079
|
+
this.#feedUnparsableSaid = true;
|
|
12080
|
+
this.#o.log.error(`hightea-source: ${this.sourceId}: km's change feed wrote a line that is not a journal record, so its changes carry no seq; freshness is checked against each answer's head only`);
|
|
12081
|
+
}
|
|
12082
|
+
}
|
|
12083
|
+
#wholeReadClearsNotice(head) {
|
|
12084
|
+
const hinted = this.#hintedSeq;
|
|
12085
|
+
this.#noticeWaitingSince = undefined;
|
|
12086
|
+
if (hinted === undefined)
|
|
12087
|
+
return;
|
|
12088
|
+
if (typeof head === "number" && head < hinted) {
|
|
12089
|
+
this.#o.log.error(`hightea-source: ${this.sourceId} read whole at head ${String(head)}, below the change notice at ${hinted}; that notice is not about this vault's journal`);
|
|
12090
|
+
}
|
|
12091
|
+
this.#hintedSeq = undefined;
|
|
12092
|
+
}
|
|
12093
|
+
#read(scheduledAtIncrementalFloor = false, clientRead = false, awaitProjection = false) {
|
|
10856
12094
|
if (this.#reading !== undefined) {
|
|
10857
12095
|
this.#dirty = true;
|
|
12096
|
+
if (clientRead)
|
|
12097
|
+
this.#progressDirty = true;
|
|
10858
12098
|
return this.#reading;
|
|
10859
12099
|
}
|
|
10860
12100
|
if (this.#hintTimer !== undefined) {
|
|
@@ -10862,11 +12102,19 @@ class KmSource {
|
|
|
10862
12102
|
this.#hintTimer = undefined;
|
|
10863
12103
|
}
|
|
10864
12104
|
this.#dirty = false;
|
|
12105
|
+
this.#pendingChangeAt = undefined;
|
|
10865
12106
|
const began = this.#now();
|
|
10866
|
-
const reading = this.#readOnce().
|
|
12107
|
+
const reading = this.#readOnce(scheduledAtIncrementalFloor, clientRead, awaitProjection).then((read) => {
|
|
12108
|
+
this.#readFailures = 0;
|
|
12109
|
+
return read;
|
|
12110
|
+
}, (error) => {
|
|
12111
|
+
this.#retryAfterFailure();
|
|
12112
|
+
throw error;
|
|
12113
|
+
}).finally(() => {
|
|
10867
12114
|
this.#reading = undefined;
|
|
10868
12115
|
this.#readEndedAt = this.#now();
|
|
10869
12116
|
this.#readTookMs = this.#readEndedAt - began;
|
|
12117
|
+
this.#armWatchRefresh();
|
|
10870
12118
|
if (this.#dirty && !this.#stop.signal.aborted) {
|
|
10871
12119
|
this.#dirty = false;
|
|
10872
12120
|
this.hint();
|
|
@@ -10876,17 +12124,392 @@ class KmSource {
|
|
|
10876
12124
|
this.#readingNo = this.#reads;
|
|
10877
12125
|
return reading;
|
|
10878
12126
|
}
|
|
10879
|
-
|
|
10880
|
-
|
|
10881
|
-
|
|
12127
|
+
#retryAfterFailure() {
|
|
12128
|
+
if (this.#stop.signal.aborted || this.#hintTimer !== undefined)
|
|
12129
|
+
return;
|
|
12130
|
+
this.#readFailures++;
|
|
12131
|
+
const delay = Math.min(this.#retryMs * 2 ** Math.min(this.#readFailures - 1, 5), 60000);
|
|
12132
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId} will read again in ${Math.round(delay / 1000)} s after a failed read`);
|
|
12133
|
+
this.#hintTimer = setTimeout(() => {
|
|
12134
|
+
this.#hintTimer = undefined;
|
|
12135
|
+
this.#read().catch((error) => this.#o.log.error(`hightea-source: retrying ${this.sourceId} after a failed read failed: ${describe2(error)}`));
|
|
12136
|
+
}, delay);
|
|
12137
|
+
}
|
|
12138
|
+
#watchIntervalMs() {
|
|
12139
|
+
if (this.#watchRefresh !== undefined)
|
|
12140
|
+
return this.#watchRefresh;
|
|
12141
|
+
const sample = [...this.#refreshes].sort((a, b) => a - b);
|
|
12142
|
+
const p50 = sample.length === 0 ? 0 : sample[Math.floor(sample.length / 2)];
|
|
12143
|
+
return Math.max(this.#watchFloor, 10 * p50);
|
|
12144
|
+
}
|
|
12145
|
+
#armWatchRefresh() {
|
|
12146
|
+
if (this.#stop.signal.aborted || !this.#watching || this.#watchTimer !== undefined)
|
|
12147
|
+
return;
|
|
12148
|
+
const interval = this.#watchIntervalMs();
|
|
12149
|
+
if (!(interval > 0))
|
|
12150
|
+
return;
|
|
12151
|
+
const since = Math.max(this.#readEndedAt, this.#lastClientReadAt);
|
|
12152
|
+
const wait = Math.max(0, interval - (this.#now() - since));
|
|
12153
|
+
this.#watchTimer = setTimeout(() => {
|
|
12154
|
+
this.#watchTimer = undefined;
|
|
12155
|
+
if (this.#stop.signal.aborted || !this.#watching)
|
|
12156
|
+
return;
|
|
12157
|
+
if (this.#reading !== undefined) {
|
|
12158
|
+
this.#armWatchRefresh();
|
|
12159
|
+
return;
|
|
12160
|
+
}
|
|
12161
|
+
this.#read(true, true, true).catch((error) => this.#o.log.error(`hightea-source: the watcher read of ${this.sourceId} failed: ${describe2(error)}`));
|
|
12162
|
+
}, wait);
|
|
12163
|
+
}
|
|
12164
|
+
#clearWatchRefresh() {
|
|
12165
|
+
if (this.#watchTimer === undefined)
|
|
12166
|
+
return;
|
|
12167
|
+
clearTimeout(this.#watchTimer);
|
|
12168
|
+
this.#watchTimer = undefined;
|
|
12169
|
+
}
|
|
12170
|
+
#armNoticeRead() {
|
|
12171
|
+
if (this.#stop.signal.aborted || this.#hintTimer !== undefined)
|
|
12172
|
+
return;
|
|
12173
|
+
this.#hintTimer = setTimeout(() => {
|
|
12174
|
+
this.#hintTimer = undefined;
|
|
12175
|
+
if (this.#reading !== undefined) {
|
|
12176
|
+
this.#dirty = true;
|
|
12177
|
+
return;
|
|
12178
|
+
}
|
|
12179
|
+
this.#read(true).catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after a trailing notice failed: ${describe2(error)}`));
|
|
12180
|
+
}, this.#minIncrementalGap);
|
|
12181
|
+
}
|
|
12182
|
+
async#readOnce(atIncrementalFloor, clientRead, awaitProjection = false) {
|
|
12183
|
+
for (let attempt = 1;; attempt++) {
|
|
12184
|
+
const generation = `${this.#epoch}.${++this.#reads}`;
|
|
12185
|
+
try {
|
|
12186
|
+
const cursor = this.#cursor;
|
|
12187
|
+
if (cursor !== undefined) {
|
|
12188
|
+
const changed = await this.#readChanged(generation, cursor, atIncrementalFloor, clientRead, awaitProjection);
|
|
12189
|
+
if (changed !== undefined)
|
|
12190
|
+
return changed;
|
|
12191
|
+
}
|
|
12192
|
+
return await this.#readWhole(generation);
|
|
12193
|
+
} catch (error) {
|
|
12194
|
+
if (attempt >= READ_ATTEMPTS || !(error instanceof ListRefused) || !movedUnderPin(error.stderr))
|
|
12195
|
+
throw error;
|
|
12196
|
+
this.#o.log.error(`hightea-source: read of ${this.sourceId} restarted after the vault moved (${attempt}/${READ_ATTEMPTS}): ${firstCode(error.stderr)}`);
|
|
12197
|
+
await this.#rest();
|
|
12198
|
+
}
|
|
12199
|
+
}
|
|
12200
|
+
}
|
|
12201
|
+
async#readWhole(generation) {
|
|
12202
|
+
const streamed = await this.#readStreamed(generation);
|
|
12203
|
+
if (streamed !== undefined)
|
|
12204
|
+
return streamed;
|
|
12205
|
+
return await this.#readPaged(generation);
|
|
12206
|
+
}
|
|
12207
|
+
async#readStreamed(generation) {
|
|
12208
|
+
if (this.#stream === false)
|
|
12209
|
+
return;
|
|
12210
|
+
const request = { binding: this.sourceId, population: "all-issues", generation, limit: KM_PAGE_LIMIT, traverse: true, progress: true };
|
|
12211
|
+
const ran = await this.#yrd(["issues", "list-page", JSON.stringify(request)]);
|
|
12212
|
+
if (ran.code !== 0) {
|
|
12213
|
+
if (!traversalUnavailable(ran.stderr))
|
|
12214
|
+
throw new ListRefused(ran.stderr);
|
|
12215
|
+
this.#stream = false;
|
|
12216
|
+
this.#o.log.error(`hightea-source: ${this.sourceId} has no one-process traversal (${firstCode(ran.stderr)}); checking a single-page native snapshot; larger snapshots require traversal`);
|
|
12217
|
+
return;
|
|
12218
|
+
}
|
|
12219
|
+
if (this.#stream === undefined)
|
|
12220
|
+
this.#stream = true;
|
|
12221
|
+
const read = kmTraversal(ran.stdout, generation);
|
|
12222
|
+
if (read.activityUnreadRows > 0) {
|
|
12223
|
+
this.#o.log.error(`hightea-source: ${this.sourceId}: activity read unavailable for ${read.activityUnreadRows} of ${read.rows.length} rows; progress remains unknown; check the declared activity command`);
|
|
12224
|
+
}
|
|
12225
|
+
const fresh = new Map;
|
|
12226
|
+
this.#collect(fresh, read.rows);
|
|
12227
|
+
const progressAt = this.#now();
|
|
12228
|
+
if (read.progress !== undefined)
|
|
12229
|
+
this.#progressCache = { value: read.progress, at: progressAt };
|
|
12230
|
+
this.#projectProgress(fresh, read.progress, progressAt);
|
|
12231
|
+
this.#rememberHead(read.head);
|
|
12232
|
+
this.#wholeReadClearsNotice(read.head);
|
|
12233
|
+
return this.#diff(generation, contentRevision(fresh), fresh);
|
|
12234
|
+
}
|
|
12235
|
+
async#readPaged(generation) {
|
|
12236
|
+
const request = { binding: this.sourceId, population: "all-issues", generation, limit: KM_PAGE_LIMIT, progress: true };
|
|
12237
|
+
const ran = await this.#yrd(["issues", "list-page", JSON.stringify(request)]);
|
|
10882
12238
|
if (ran.code !== 0)
|
|
10883
|
-
throw new
|
|
12239
|
+
throw new ListRefused(ran.stderr);
|
|
12240
|
+
const result = kmPage(ran.stdout);
|
|
12241
|
+
if (!result.complete) {
|
|
12242
|
+
if (this.#stream === false) {
|
|
12243
|
+
this.#stream = undefined;
|
|
12244
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId}: a paged whole read cannot serve this multi-page vault; asking the one-process traversal again`);
|
|
12245
|
+
}
|
|
12246
|
+
throw new Error("progress refresh needs one-process traversal for a multipage native snapshot");
|
|
12247
|
+
}
|
|
10884
12248
|
const fresh = new Map;
|
|
10885
|
-
|
|
12249
|
+
this.#collect(fresh, result.rows);
|
|
12250
|
+
const progressAt = this.#now();
|
|
12251
|
+
if (result.progress !== undefined)
|
|
12252
|
+
this.#progressCache = { value: result.progress, at: progressAt };
|
|
12253
|
+
this.#projectProgress(fresh, result.progress, progressAt);
|
|
12254
|
+
this.#rememberHead(result.head);
|
|
12255
|
+
this.#wholeReadClearsNotice(result.head);
|
|
12256
|
+
return this.#diff(generation, contentRevision(fresh), fresh);
|
|
12257
|
+
}
|
|
12258
|
+
#collect(fresh, rows) {
|
|
12259
|
+
for (const one of rows) {
|
|
10886
12260
|
const row = this.#row(one);
|
|
10887
|
-
|
|
12261
|
+
const checked = SourceRowSchema.safeParse(row);
|
|
12262
|
+
if (!checked.success) {
|
|
12263
|
+
const reasons = checked.error.issues.map((issue) => {
|
|
12264
|
+
const field = (issue.path[0] === "columns" ? issue.path.slice(1) : issue.path).join(".");
|
|
12265
|
+
const value = issue.path.reduce((part, key) => typeof part === "object" && part !== null ? Reflect.get(part, key) : undefined, row);
|
|
12266
|
+
return issue.code === "too_big" && typeof value === "string" ? `${field} is ${value.length} chars, cap ${issue.maximum}` : `${field}: ${issue.message}`;
|
|
12267
|
+
});
|
|
12268
|
+
this.#o.log.error(`hightea-source: row ${one.id} omitted: ${reasons.join("; ")}`);
|
|
12269
|
+
continue;
|
|
12270
|
+
}
|
|
12271
|
+
if (sourceFrameBytes(row) > SOURCE_PAGE_BUDGET_BYTES)
|
|
12272
|
+
throw new ItemTooLarge(row.address);
|
|
12273
|
+
fresh.set(row.address, { key: one.path, row });
|
|
10888
12274
|
}
|
|
10889
|
-
|
|
12275
|
+
}
|
|
12276
|
+
async#readChanged(generation, cursor, atIncrementalFloor, clientRead, awaitProjection) {
|
|
12277
|
+
const last = this.#current;
|
|
12278
|
+
if (last === undefined)
|
|
12279
|
+
return;
|
|
12280
|
+
const request = { binding: this.sourceId, population: "all-issues", generation, limit: KM_PAGE_LIMIT, changedSince: cursor, progress: true };
|
|
12281
|
+
const began = this.#now();
|
|
12282
|
+
const ran = await this.#listPage(request);
|
|
12283
|
+
const framedAt = this.#now();
|
|
12284
|
+
if (!ran.ok) {
|
|
12285
|
+
const moved = movedUnderPin(ran.stderr);
|
|
12286
|
+
const missingJournal = /--page changedSince \d+ needs the vault's journal at [^\n]+, which no daemon has written; do a full read(?:\r?\n|$)/u.test(ran.stderr);
|
|
12287
|
+
if (!moved && !unservableCursor(ran.stderr) && !missingJournal)
|
|
12288
|
+
throw new ListRefused(ran.stderr);
|
|
12289
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId} could not read after ${cursor} (${firstCode(ran.stderr)}); reading it whole`);
|
|
12290
|
+
return moved ? this.#unservedByConcurrency() : this.#unservedIncrementally(atIncrementalFloor);
|
|
12291
|
+
}
|
|
12292
|
+
const result = kmPage(ran.stdout);
|
|
12293
|
+
if (!result.complete) {
|
|
12294
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId} answered a bounded change list (${result.reason ?? "no reason named"}); reading it whole`);
|
|
12295
|
+
return this.#unservedIncrementally(atIncrementalFloor);
|
|
12296
|
+
}
|
|
12297
|
+
if (typeof result.head !== "number" || result.head < cursor) {
|
|
12298
|
+
throw new Error(`list-page answered changedSince ${cursor} at head ${String(result.head)}`);
|
|
12299
|
+
}
|
|
12300
|
+
const hinted = this.#hintedSeq;
|
|
12301
|
+
if (hinted !== undefined && result.head < hinted) {
|
|
12302
|
+
const waitingSince = this.#noticeWaitingSince ?? (this.#noticeWaitingSince = this.#now());
|
|
12303
|
+
if (this.#now() - waitingSince >= (this.#o.noticePatienceMs ?? NOTICE_PATIENCE_MS)) {
|
|
12304
|
+
this.#o.log.error(`hightea-source: ${this.sourceId} stayed below the change notice at ${hinted} for ${Math.round(this.#now() - waitingSince)} ms at head ${String(result.head)}; that notice is not about this vault's journal`);
|
|
12305
|
+
this.#hintedSeq = undefined;
|
|
12306
|
+
this.#noticeWaitingSince = undefined;
|
|
12307
|
+
} else {
|
|
12308
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId}: answer head ${String(result.head)} trails the change notice at ${hinted}; serving the delta and reading again`);
|
|
12309
|
+
this.#armNoticeRead();
|
|
12310
|
+
}
|
|
12311
|
+
} else if (hinted !== undefined) {
|
|
12312
|
+
this.#hintedSeq = undefined;
|
|
12313
|
+
this.#noticeWaitingSince = undefined;
|
|
12314
|
+
}
|
|
12315
|
+
const fresh = new Map(last.byAddress);
|
|
12316
|
+
const live = new Set(result.rows.map((one) => this.#addressOf(one)));
|
|
12317
|
+
const addressOf = new Map([...last.byAddress].map(([address, held]) => [held.key, address]));
|
|
12318
|
+
for (const address of live)
|
|
12319
|
+
fresh.delete(address);
|
|
12320
|
+
this.#collect(fresh, result.rows);
|
|
12321
|
+
if (this.#ancestorChangeNeedsWholeRead(last, fresh, live, addressOf, result.rows, result.removed)) {
|
|
12322
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId} saw an ancestor project or path change after ${cursor}; reading it whole`);
|
|
12323
|
+
return this.#unservedByConcurrency();
|
|
12324
|
+
}
|
|
12325
|
+
for (const path of result.removed) {
|
|
12326
|
+
const address = addressOf.get(path);
|
|
12327
|
+
if (address !== undefined && !live.has(address))
|
|
12328
|
+
fresh.delete(address);
|
|
12329
|
+
}
|
|
12330
|
+
if (ran.from === "reader") {
|
|
12331
|
+
const projection = await this.#progressFor(awaitProjection);
|
|
12332
|
+
if (projection !== undefined)
|
|
12333
|
+
this.#projectProgress(fresh, projection.value, projection.at);
|
|
12334
|
+
} else {
|
|
12335
|
+
const at = this.#now();
|
|
12336
|
+
if (result.progress !== undefined)
|
|
12337
|
+
this.#progressCache = { value: result.progress, at };
|
|
12338
|
+
this.#projectProgress(fresh, result.progress, at);
|
|
12339
|
+
}
|
|
12340
|
+
this.#cursor = result.head;
|
|
12341
|
+
this.#lastContinuationUnserved = false;
|
|
12342
|
+
const collectedAt = this.#now();
|
|
12343
|
+
const revision = contentRevision(fresh);
|
|
12344
|
+
const revisedAt = this.#now();
|
|
12345
|
+
const read = this.#diff(generation, revision, fresh);
|
|
12346
|
+
const ended = this.#now();
|
|
12347
|
+
if (clientRead || ended - began >= 500) {
|
|
12348
|
+
const kind = awaitProjection ? "watch" : clientRead ? "client" : "change";
|
|
12349
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId} ${kind} delta read ${Math.round(ended - began)} ms: yrd ${Math.round(framedAt - began)} ms, collect ${Math.round(collectedAt - framedAt)} ms, revision ${Math.round(revisedAt - collectedAt)} ms, diff ${Math.round(ended - revisedAt)} ms`);
|
|
12350
|
+
}
|
|
12351
|
+
return read;
|
|
12352
|
+
}
|
|
12353
|
+
#unservedIncrementally(atIncrementalFloor) {
|
|
12354
|
+
this.#lastContinuationUnserved = atIncrementalFloor;
|
|
12355
|
+
return;
|
|
12356
|
+
}
|
|
12357
|
+
#unservedByConcurrency() {
|
|
12358
|
+
this.#lastContinuationUnserved = false;
|
|
12359
|
+
return;
|
|
12360
|
+
}
|
|
12361
|
+
async#progressOnly() {
|
|
12362
|
+
const reader = this.#reader();
|
|
12363
|
+
if (reader === undefined)
|
|
12364
|
+
throw new Error("progress unavailable: list-page-serve not running");
|
|
12365
|
+
const answer = await reader.ask({ progress: true }, this.#o.childTimeoutMs ?? 120000);
|
|
12366
|
+
if ("refusal" in answer) {
|
|
12367
|
+
throw new Error(`progress unavailable: ${answer.refusal.code}: ${answer.refusal.message}`);
|
|
12368
|
+
}
|
|
12369
|
+
if (!("progress" in answer)) {
|
|
12370
|
+
throw new Error("progress unavailable: the reader answered a page where the frame was asked for");
|
|
12371
|
+
}
|
|
12372
|
+
const frame = answer.progress;
|
|
12373
|
+
if (frame !== undefined && Buffer.byteLength(JSON.stringify(frame)) > OUTPUT_MAX_BYTES) {
|
|
12374
|
+
throw new Error("progress refresh output exceeded its byte budget");
|
|
12375
|
+
}
|
|
12376
|
+
return frame;
|
|
12377
|
+
}
|
|
12378
|
+
async#progressFor(awaitFresh) {
|
|
12379
|
+
const cached = this.#progressCache;
|
|
12380
|
+
const stale = cached === undefined || this.#now() - cached.at >= this.#progressCeiling;
|
|
12381
|
+
if (!stale)
|
|
12382
|
+
return cached;
|
|
12383
|
+
if (cached === undefined || awaitFresh) {
|
|
12384
|
+
await this.#refreshProgress();
|
|
12385
|
+
const after = this.#progressCache;
|
|
12386
|
+
if (after === undefined)
|
|
12387
|
+
throw new Error("progress refresh completed without a projection");
|
|
12388
|
+
return after;
|
|
12389
|
+
}
|
|
12390
|
+
this.#refreshProgress().catch((error) => this.#o.log.error(`hightea-source: ${this.sourceId} activity projection refresh failed: ${describe2(error)}`));
|
|
12391
|
+
return cached;
|
|
12392
|
+
}
|
|
12393
|
+
#progressStale() {
|
|
12394
|
+
const since = this.#progressFailedSince;
|
|
12395
|
+
if (since === undefined || this.#progressFailure === undefined)
|
|
12396
|
+
return;
|
|
12397
|
+
if (this.#progressFailures < PROGRESS_STALE_FAILURES && this.#now() - since < PROGRESS_STALE_MS)
|
|
12398
|
+
return;
|
|
12399
|
+
return { since: new Date(since).toISOString(), reason: this.#progressFailure };
|
|
12400
|
+
}
|
|
12401
|
+
#refreshProgress() {
|
|
12402
|
+
if (this.#progressRefresh !== undefined) {
|
|
12403
|
+
this.#progressDirty = true;
|
|
12404
|
+
return this.#progressRefresh;
|
|
12405
|
+
}
|
|
12406
|
+
const run = (async () => {
|
|
12407
|
+
do {
|
|
12408
|
+
this.#progressDirty = false;
|
|
12409
|
+
const began = this.#now();
|
|
12410
|
+
try {
|
|
12411
|
+
const value = await this.#progressOnly();
|
|
12412
|
+
this.#refreshes.push(this.#now() - began);
|
|
12413
|
+
if (this.#refreshes.length > REFRESH_TIMING_SAMPLE)
|
|
12414
|
+
this.#refreshes.shift();
|
|
12415
|
+
this.#projectionOf(value);
|
|
12416
|
+
this.#progressCache = { value, at: this.#now() };
|
|
12417
|
+
this.#progressFailures = 0;
|
|
12418
|
+
this.#progressFailedSince = undefined;
|
|
12419
|
+
this.#progressFailure = undefined;
|
|
12420
|
+
} catch (error) {
|
|
12421
|
+
this.#progressFailures++;
|
|
12422
|
+
this.#progressFailedSince ??= this.#now();
|
|
12423
|
+
this.#progressFailure = describe2(error);
|
|
12424
|
+
throw error;
|
|
12425
|
+
}
|
|
12426
|
+
} while (this.#progressDirty && !this.#stop.signal.aborted);
|
|
12427
|
+
})().finally(() => {
|
|
12428
|
+
this.#progressRefresh = undefined;
|
|
12429
|
+
});
|
|
12430
|
+
this.#progressRefresh = run;
|
|
12431
|
+
return run;
|
|
12432
|
+
}
|
|
12433
|
+
#projectionOf(value) {
|
|
12434
|
+
const result = value;
|
|
12435
|
+
if (typeof result !== "object" || result === null || !Array.isArray(result.qualifying) || result.complete !== true) {
|
|
12436
|
+
throw new Error("progress refresh requires a complete terminal qualifying projection, not an ordinary page");
|
|
12437
|
+
}
|
|
12438
|
+
const source = result.source;
|
|
12439
|
+
const idle = result.default;
|
|
12440
|
+
if (!(source === "ok" || source === "undeclared" || source === "unreadable") || idle !== (source === "unreadable" ? null : false)) {
|
|
12441
|
+
throw new Error("progress refresh has an invalid progress.source/progress.default pair");
|
|
12442
|
+
}
|
|
12443
|
+
const holds = new Map;
|
|
12444
|
+
const actors = new Map;
|
|
12445
|
+
for (const entry of result.qualifying) {
|
|
12446
|
+
if (typeof entry !== "object" || entry === null)
|
|
12447
|
+
throw new Error("progress refresh carries a malformed qualifying entry");
|
|
12448
|
+
const one = entry;
|
|
12449
|
+
if (typeof one.id !== "string" || one.id.length === 0 || typeof one.reason !== "string" || one.reason.length === 0 || one.owner !== undefined && (typeof one.owner !== "string" || one.owner.length === 0)) {
|
|
12450
|
+
throw new Error("progress refresh qualifying entry needs identity, reason and an optional nonempty owner");
|
|
12451
|
+
}
|
|
12452
|
+
if (one.owner === undefined) {
|
|
12453
|
+
if (holds.has(one.id))
|
|
12454
|
+
throw new Error("progress refresh repeats a hold identity");
|
|
12455
|
+
holds.set(one.id, one.reason);
|
|
12456
|
+
} else {
|
|
12457
|
+
const owners = actors.get(one.id) ?? new Map;
|
|
12458
|
+
if (owners.has(one.owner))
|
|
12459
|
+
throw new Error("progress refresh repeats an identity/owner");
|
|
12460
|
+
owners.set(one.owner, one.reason);
|
|
12461
|
+
actors.set(one.id, owners);
|
|
12462
|
+
}
|
|
12463
|
+
}
|
|
12464
|
+
return { source, idle, holds, actors };
|
|
12465
|
+
}
|
|
12466
|
+
#projectProgress(fresh, value, at) {
|
|
12467
|
+
this.#applyProjection(fresh, this.#projectionOf(value));
|
|
12468
|
+
this.#progressAt = at;
|
|
12469
|
+
}
|
|
12470
|
+
#applyProjection(fresh, projection) {
|
|
12471
|
+
let unknown = 0;
|
|
12472
|
+
for (const [address, held] of fresh) {
|
|
12473
|
+
const row = held.row;
|
|
12474
|
+
const extra = row.extra;
|
|
12475
|
+
const number = beadNumberFromPath(held.key);
|
|
12476
|
+
const identity = number === null ? `path:${held.key.endsWith(".md") ? held.key.slice(0, -3) : held.key}` : `bead:${number}`;
|
|
12477
|
+
const owner = this.#nativeOf(row.columns.owner ?? "") ?? "";
|
|
12478
|
+
const reason = projection.holds.get(identity) ?? (owner === "" ? undefined : projection.actors.get(identity)?.get(owner));
|
|
12479
|
+
const flag = reason === undefined ? projection.idle : true;
|
|
12480
|
+
if (flag === null)
|
|
12481
|
+
unknown++;
|
|
12482
|
+
if (extra.in_progress === flag && extra.in_progress_reason === (reason ?? null))
|
|
12483
|
+
continue;
|
|
12484
|
+
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 };
|
|
12485
|
+
fresh.set(address, { key: held.key, row: { ...row, version: contentVersion(facts), extra: { ...extra, in_progress: flag, in_progress_reason: reason ?? null } } });
|
|
12486
|
+
}
|
|
12487
|
+
if (projection.source === "unreadable")
|
|
12488
|
+
this.#o.log.error(`hightea-source: ${this.sourceId}: activity read unavailable; ${unknown} of ${fresh.size} materialized rows have unknown progress`);
|
|
12489
|
+
}
|
|
12490
|
+
#rememberHead(head) {
|
|
12491
|
+
if (typeof head === "number") {
|
|
12492
|
+
this.#cursor = head;
|
|
12493
|
+
return;
|
|
12494
|
+
}
|
|
12495
|
+
this.#cursor = undefined;
|
|
12496
|
+
if (this.#noHeadSaid)
|
|
12497
|
+
return;
|
|
12498
|
+
this.#noHeadSaid = true;
|
|
12499
|
+
this.#o.log.info?.(`hightea-source: ${this.sourceId} names no journal to continue from; every read stays whole`);
|
|
12500
|
+
}
|
|
12501
|
+
async#rest() {
|
|
12502
|
+
if (this.#stop.signal.aborted)
|
|
12503
|
+
return;
|
|
12504
|
+
await new Promise((resolve) => {
|
|
12505
|
+
const done = () => {
|
|
12506
|
+
clearTimeout(timer);
|
|
12507
|
+
this.#stop.signal.removeEventListener("abort", done);
|
|
12508
|
+
resolve();
|
|
12509
|
+
};
|
|
12510
|
+
const timer = setTimeout(done, this.#retryMs);
|
|
12511
|
+
this.#stop.signal.addEventListener("abort", done, { once: true });
|
|
12512
|
+
});
|
|
10890
12513
|
}
|
|
10891
12514
|
#diff(generation, snapshot, fresh) {
|
|
10892
12515
|
const last = this.#current;
|
|
@@ -10914,8 +12537,10 @@ class KmSource {
|
|
|
10914
12537
|
observations.push({ position, change: { op: "upsert", row: first.row } });
|
|
10915
12538
|
byAddress.set(first.row.address, { ...first, at: BigInt(position.ordinal) });
|
|
10916
12539
|
}
|
|
10917
|
-
|
|
10918
|
-
|
|
12540
|
+
return this.#commit(generation, snapshot, observations, byAddress);
|
|
12541
|
+
}
|
|
12542
|
+
#commit(generation, snapshot, observations, byAddress) {
|
|
12543
|
+
const read = { generation, snapshot, base: this.#ordinal, epoch: this.#epoch, rows: [...byAddress.values()], byAddress, at: this.#now() };
|
|
10919
12544
|
this.#current = read;
|
|
10920
12545
|
this.#kept.set(generation, read);
|
|
10921
12546
|
for (const [name, kept] of this.#kept) {
|
|
@@ -10929,26 +12554,99 @@ class KmSource {
|
|
|
10929
12554
|
this.#ordinal++;
|
|
10930
12555
|
return { epoch: this.#epoch, ordinal: String(this.#ordinal) };
|
|
10931
12556
|
}
|
|
12557
|
+
#addressOf(one) {
|
|
12558
|
+
return `issue:${this.sourceId}/${beadNumberFromPath(one.path) ?? one.id}`;
|
|
12559
|
+
}
|
|
12560
|
+
#projectOf(one) {
|
|
12561
|
+
if (one.container === null || one.containerSource === null || one.containerSource === "beads-root")
|
|
12562
|
+
return null;
|
|
12563
|
+
const path = one.container.endsWith(".md") ? one.container : `${one.container}.md`;
|
|
12564
|
+
return `issue:${this.sourceId}/${beadNumberFromPath(path) ?? one.container}`;
|
|
12565
|
+
}
|
|
12566
|
+
#ancestorChangeNeedsWholeRead(last, fresh, live, addressOf, rows, removed) {
|
|
12567
|
+
const affectedProjects = new Set;
|
|
12568
|
+
const affectedPrefixes = new Set;
|
|
12569
|
+
for (const one of rows) {
|
|
12570
|
+
const address = this.#addressOf(one);
|
|
12571
|
+
const was = last.byAddress.get(address);
|
|
12572
|
+
const now = fresh.get(address);
|
|
12573
|
+
const projectChanged = was !== undefined && now !== undefined && was.row.columns.project !== now.row.columns.project;
|
|
12574
|
+
const moved = was !== undefined && now !== undefined && was.key !== now.key;
|
|
12575
|
+
const newProject = was === undefined && now !== undefined && now.row.columns.project === address;
|
|
12576
|
+
if (!projectChanged && !moved && !newProject)
|
|
12577
|
+
continue;
|
|
12578
|
+
affectedProjects.add(address);
|
|
12579
|
+
if (was?.row.columns.project !== undefined && was.row.columns.project !== null)
|
|
12580
|
+
affectedProjects.add(was.row.columns.project);
|
|
12581
|
+
if (was !== undefined)
|
|
12582
|
+
for (const prefix of folderPrefixesForPath(was.key))
|
|
12583
|
+
affectedPrefixes.add(prefix);
|
|
12584
|
+
if (now !== undefined)
|
|
12585
|
+
for (const prefix of folderPrefixesForPath(now.key))
|
|
12586
|
+
affectedPrefixes.add(prefix);
|
|
12587
|
+
}
|
|
12588
|
+
for (const path of removed) {
|
|
12589
|
+
for (const prefix of folderPrefixesForPath(path))
|
|
12590
|
+
affectedPrefixes.add(prefix);
|
|
12591
|
+
const address = addressOf.get(path);
|
|
12592
|
+
if (address !== undefined) {
|
|
12593
|
+
const was = last.byAddress.get(address);
|
|
12594
|
+
if (was !== undefined && was.row.columns.project === address)
|
|
12595
|
+
affectedProjects.add(address);
|
|
12596
|
+
}
|
|
12597
|
+
}
|
|
12598
|
+
if (affectedProjects.size === 0 && affectedPrefixes.size === 0)
|
|
12599
|
+
return false;
|
|
12600
|
+
for (const [address, held] of last.byAddress) {
|
|
12601
|
+
if (live.has(address))
|
|
12602
|
+
continue;
|
|
12603
|
+
if (held.row.columns.project !== null && affectedProjects.has(held.row.columns.project))
|
|
12604
|
+
return true;
|
|
12605
|
+
const key = held.key.startsWith("./") ? held.key.slice(2) : held.key;
|
|
12606
|
+
for (const prefix of affectedPrefixes)
|
|
12607
|
+
if (key.startsWith(prefix))
|
|
12608
|
+
return true;
|
|
12609
|
+
}
|
|
12610
|
+
return false;
|
|
12611
|
+
}
|
|
10932
12612
|
#row(one) {
|
|
10933
|
-
const address =
|
|
12613
|
+
const address = this.#addressOf(one);
|
|
10934
12614
|
const owner = one.owner.trim();
|
|
12615
|
+
const state = one.status.trim() === "" ? "none" : one.status.trim();
|
|
12616
|
+
const project = this.#projectOf(one);
|
|
12617
|
+
const version = contentVersion({
|
|
12618
|
+
id: one.id,
|
|
12619
|
+
title: one.title,
|
|
12620
|
+
status: state,
|
|
12621
|
+
owner,
|
|
12622
|
+
project,
|
|
12623
|
+
in_progress: one.in_progress,
|
|
12624
|
+
in_progress_reason: one.in_progress_reason,
|
|
12625
|
+
updated_at: one.updated_at,
|
|
12626
|
+
closed_at: one.closed_at
|
|
12627
|
+
});
|
|
10935
12628
|
const row = {
|
|
10936
12629
|
address,
|
|
10937
|
-
version
|
|
12630
|
+
version,
|
|
10938
12631
|
scope: "all",
|
|
10939
12632
|
columns: {
|
|
10940
12633
|
title: one.title,
|
|
10941
|
-
state
|
|
12634
|
+
state,
|
|
10942
12635
|
owner: owner === "" ? null : this.#native.get(owner) ?? `km:${owner}`,
|
|
10943
12636
|
parent: null,
|
|
12637
|
+
project,
|
|
10944
12638
|
labels: [],
|
|
10945
12639
|
url: null,
|
|
10946
|
-
updatedAt:
|
|
12640
|
+
updatedAt: one.updated_at
|
|
10947
12641
|
},
|
|
10948
|
-
extra: {
|
|
12642
|
+
extra: {
|
|
12643
|
+
path: one.path,
|
|
12644
|
+
id: one.id,
|
|
12645
|
+
in_progress: one.in_progress,
|
|
12646
|
+
in_progress_reason: one.in_progress_reason,
|
|
12647
|
+
closed_at: one.closed_at
|
|
12648
|
+
}
|
|
10949
12649
|
};
|
|
10950
|
-
if (one.title.length > 4096 || address.length > 1024 || sourceFrameBytes(row) > SOURCE_PAGE_BUDGET_BYTES)
|
|
10951
|
-
throw new ItemTooLarge(address);
|
|
10952
12650
|
return row;
|
|
10953
12651
|
}
|
|
10954
12652
|
#nativeOf(owner) {
|
|
@@ -10958,7 +12656,13 @@ class KmSource {
|
|
|
10958
12656
|
}
|
|
10959
12657
|
#keyOf(address) {
|
|
10960
12658
|
const prefix = `issue:${this.sourceId}/`;
|
|
10961
|
-
|
|
12659
|
+
if (!address.startsWith(prefix) || address.length <= prefix.length)
|
|
12660
|
+
return;
|
|
12661
|
+
const held = this.#current?.byAddress.get(address)?.key;
|
|
12662
|
+
if (held !== undefined)
|
|
12663
|
+
return held;
|
|
12664
|
+
const named = address.slice(prefix.length);
|
|
12665
|
+
return beadNumberFromPath(named) === null ? named : undefined;
|
|
10962
12666
|
}
|
|
10963
12667
|
#enqueue(observations) {
|
|
10964
12668
|
this.#queue.push(...observations);
|
|
@@ -11038,10 +12742,10 @@ class KmSource {
|
|
|
11038
12742
|
this.#pump();
|
|
11039
12743
|
});
|
|
11040
12744
|
}
|
|
11041
|
-
async#yrd(args) {
|
|
12745
|
+
async#yrd(args, env) {
|
|
11042
12746
|
const { config } = this.#o;
|
|
11043
12747
|
try {
|
|
11044
|
-
return await this.#run([...config.yrd, ...args, "--project-root", config.projectRoot], { timeoutMs: this.#o.childTimeoutMs ?? 120000, signal: this.#stop.signal });
|
|
12748
|
+
return await this.#run([...config.yrd, ...args, "--project-root", config.projectRoot], { timeoutMs: this.#o.childTimeoutMs ?? 120000, signal: this.#stop.signal, ...env === undefined ? {} : { env } });
|
|
11045
12749
|
} catch (error) {
|
|
11046
12750
|
throw new Error(`the yrd command ${config.yrd[0] ?? "(none)"} could not run: ${describe2(error)}`);
|
|
11047
12751
|
}
|
|
@@ -11052,7 +12756,7 @@ class KmSource {
|
|
|
11052
12756
|
while (!signal.aborted) {
|
|
11053
12757
|
const since = String(this.#now());
|
|
11054
12758
|
try {
|
|
11055
|
-
const ended = await follow([...this.#o.config.feed, "--since", since], { signal, onLine: () => this.hint() });
|
|
12759
|
+
const ended = await follow([...this.#o.config.feed, "--since", since], { signal, onLine: (line) => this.hint(line) });
|
|
11056
12760
|
if (signal.aborted)
|
|
11057
12761
|
return;
|
|
11058
12762
|
this.#o.log.error(`hightea-source: km's change feed for ${this.sourceId} ended (${ended.code ?? "signal"}): ${firstCode(ended.stderr)}`);
|
|
@@ -11072,27 +12776,199 @@ class KmSource {
|
|
|
11072
12776
|
}
|
|
11073
12777
|
}
|
|
11074
12778
|
}
|
|
11075
|
-
|
|
12779
|
+
var CONTAINER_SOURCES = new Set(["self", "ancestor", "folder-note", "beads-root"]);
|
|
12780
|
+
function folderPrefixesForPath(path) {
|
|
12781
|
+
const normalized = path.startsWith("./") ? path.slice(2) : path;
|
|
12782
|
+
const withoutMd = normalized.endsWith(".md") ? normalized.slice(0, -3) : normalized;
|
|
12783
|
+
if (withoutMd === "")
|
|
12784
|
+
return [];
|
|
12785
|
+
const prefixes = [`${withoutMd}/`];
|
|
12786
|
+
const slash = withoutMd.lastIndexOf("/");
|
|
12787
|
+
if (slash > 0) {
|
|
12788
|
+
const dir = withoutMd.slice(0, slash);
|
|
12789
|
+
const base = withoutMd.slice(slash + 1);
|
|
12790
|
+
const lower = base.toLowerCase();
|
|
12791
|
+
const dirBase = dir.slice(dir.lastIndexOf("/") + 1);
|
|
12792
|
+
if (lower === "index" || lower === "readme" || base === dirBase)
|
|
12793
|
+
prefixes.push(`${dir}/`);
|
|
12794
|
+
}
|
|
12795
|
+
return prefixes;
|
|
12796
|
+
}
|
|
12797
|
+
var NUMERIC_BEAD_LEAF = /^(\d{4,})-.+\.md$/u;
|
|
12798
|
+
var ISO_DATE_LEAF = /^\d{4}-\d{2}-\d{2}/u;
|
|
12799
|
+
function beadNumberFromPath(path) {
|
|
12800
|
+
const normalized = path.startsWith("./") ? path.slice(2) : path;
|
|
12801
|
+
if (!normalized.startsWith("@"))
|
|
12802
|
+
return null;
|
|
12803
|
+
const leafStart = normalized.lastIndexOf("/");
|
|
12804
|
+
if (leafStart < 0)
|
|
12805
|
+
return null;
|
|
12806
|
+
const leaf = normalized.slice(leafStart + 1);
|
|
12807
|
+
if (ISO_DATE_LEAF.test(leaf))
|
|
12808
|
+
return null;
|
|
12809
|
+
const match = NUMERIC_BEAD_LEAF.exec(leaf);
|
|
12810
|
+
const number = match === null ? Number.NaN : Number.parseInt(match[1], 10);
|
|
12811
|
+
return Number.isInteger(number) && number >= 0 ? number : null;
|
|
12812
|
+
}
|
|
12813
|
+
function instantColumn(row, key) {
|
|
12814
|
+
const value = row[key];
|
|
12815
|
+
if (value === undefined || value === null || value === "")
|
|
12816
|
+
return null;
|
|
12817
|
+
if (typeof value !== "string" || !Number.isFinite(Date.parse(value))) {
|
|
12818
|
+
throw new Error(`list-page answered ${key} outside an ISO instant`);
|
|
12819
|
+
}
|
|
12820
|
+
return new Date(value).toISOString();
|
|
12821
|
+
}
|
|
12822
|
+
function contentVersion(row) {
|
|
12823
|
+
return createHash3("sha256").update(`${row.id}\x00${row.title}\x00${row.status}\x00${row.owner}\x00${row.project ?? ""}\x00${String(row.in_progress)}\x00${row.in_progress_reason ?? ""}\x00${row.updated_at ?? ""}\x00${row.closed_at ?? ""}`).digest("hex").slice(0, 16);
|
|
12824
|
+
}
|
|
12825
|
+
function kmPage(stdout) {
|
|
12826
|
+
if (Buffer.byteLength(stdout) > OUTPUT_MAX_BYTES)
|
|
12827
|
+
throw new Error("progress refresh output exceeded its byte budget");
|
|
11076
12828
|
const envelope = JSON.parse(stdout);
|
|
11077
|
-
if (envelope.verb !== "list" ||
|
|
11078
|
-
throw new Error("list answered outside km's
|
|
11079
|
-
|
|
11080
|
-
|
|
11081
|
-
|
|
12829
|
+
if (envelope.verb !== "list-page" || typeof envelope.result !== "object" || envelope.result === null) {
|
|
12830
|
+
throw new Error("list-page answered outside km's page shape");
|
|
12831
|
+
}
|
|
12832
|
+
const result = envelope.result;
|
|
12833
|
+
if (typeof result.snapshot !== "string" || !Array.isArray(result.rows) || typeof result.complete !== "boolean" || !("next" in result) || result.next !== null && typeof result.next !== "string") {
|
|
12834
|
+
throw new Error("list-page answered outside km's page shape");
|
|
12835
|
+
}
|
|
12836
|
+
const text = (value) => typeof value === "string";
|
|
12837
|
+
const rows = result.rows.map((one) => {
|
|
12838
|
+
const outer = one;
|
|
12839
|
+
const row = typeof outer.row === "object" && outer.row !== null ? outer.row : outer;
|
|
11082
12840
|
if (!text(row.id) || !text(row.title) || !text(row.status) || !text(row.owner)) {
|
|
11083
|
-
throw new Error("list answered a row outside the declared columns (id, title, status, owner)");
|
|
12841
|
+
throw new Error("list-page answered a row outside the declared columns (id, title, status, owner)");
|
|
11084
12842
|
}
|
|
11085
12843
|
if ("content" in row || "description" in row)
|
|
11086
|
-
throw new Error("list answered a row carrying the issue body");
|
|
11087
|
-
const
|
|
11088
|
-
|
|
12844
|
+
throw new Error("list-page answered a row carrying the issue body");
|
|
12845
|
+
const flag = row.in_progress;
|
|
12846
|
+
if (flag !== undefined && flag !== null && typeof flag !== "boolean") {
|
|
12847
|
+
throw new Error("list-page answered in_progress outside a boolean or null");
|
|
12848
|
+
}
|
|
12849
|
+
const reason = row.in_progress_reason;
|
|
12850
|
+
if (reason !== undefined && reason !== null && typeof reason !== "string") {
|
|
12851
|
+
throw new Error("list-page answered in_progress_reason outside a string or null");
|
|
12852
|
+
}
|
|
12853
|
+
if (flag === true && typeof reason !== "string") {
|
|
12854
|
+
throw new Error("list-page answered in_progress true without the environment holding it");
|
|
12855
|
+
}
|
|
12856
|
+
const rawContainer = row.container;
|
|
12857
|
+
const rawContainerSource = row.containerSource;
|
|
12858
|
+
let container = null;
|
|
12859
|
+
let containerSource = null;
|
|
12860
|
+
if (rawContainer !== undefined || rawContainerSource !== undefined) {
|
|
12861
|
+
if (typeof rawContainer !== "string" || rawContainer.trim() === "" || typeof rawContainerSource !== "string" || !CONTAINER_SOURCES.has(rawContainerSource)) {
|
|
12862
|
+
throw new Error("list-page answered malformed container/containerSource");
|
|
12863
|
+
}
|
|
12864
|
+
container = rawContainer;
|
|
12865
|
+
containerSource = rawContainerSource;
|
|
12866
|
+
}
|
|
12867
|
+
const columns = {
|
|
12868
|
+
id: row.id,
|
|
12869
|
+
title: row.title,
|
|
12870
|
+
status: row.status,
|
|
12871
|
+
owner: row.owner,
|
|
12872
|
+
container,
|
|
12873
|
+
containerSource,
|
|
12874
|
+
in_progress: flag ?? null,
|
|
12875
|
+
in_progress_reason: reason ?? null,
|
|
12876
|
+
updated_at: instantColumn(row, "updated_at"),
|
|
12877
|
+
closed_at: instantColumn(row, "closed_at")
|
|
12878
|
+
};
|
|
12879
|
+
const path = text(outer.path) ? outer.path : columns.id;
|
|
12880
|
+
return { ...columns, path };
|
|
11089
12881
|
});
|
|
12882
|
+
const head = result.head;
|
|
12883
|
+
if (head !== undefined && head !== null && !(typeof head === "number" && Number.isSafeInteger(head) && head >= 0)) {
|
|
12884
|
+
throw new Error("list-page named a head that is not a journal seq");
|
|
12885
|
+
}
|
|
12886
|
+
const removed = result.removed;
|
|
12887
|
+
if (removed !== undefined && (!Array.isArray(removed) || !removed.every((one) => typeof one === "string"))) {
|
|
12888
|
+
throw new Error("list-page named removed rows outside km's shape");
|
|
12889
|
+
}
|
|
12890
|
+
const reason = result.reason;
|
|
12891
|
+
if (reason !== undefined && typeof reason !== "string")
|
|
12892
|
+
throw new Error("list-page named a reason that is not text");
|
|
12893
|
+
return {
|
|
12894
|
+
progress: result.progress,
|
|
12895
|
+
snapshot: result.snapshot,
|
|
12896
|
+
rows,
|
|
12897
|
+
next: result.next,
|
|
12898
|
+
complete: result.complete,
|
|
12899
|
+
head,
|
|
12900
|
+
removed: removed ?? [],
|
|
12901
|
+
reason
|
|
12902
|
+
};
|
|
11090
12903
|
}
|
|
11091
|
-
function
|
|
11092
|
-
|
|
12904
|
+
function kmTraversal(stdout, generation) {
|
|
12905
|
+
if (Buffer.byteLength(stdout) > OUTPUT_MAX_BYTES)
|
|
12906
|
+
throw new Error("progress refresh output exceeded its byte budget");
|
|
12907
|
+
const lines = stdout.split(`
|
|
12908
|
+
`);
|
|
12909
|
+
while (lines.length > 0 && lines[lines.length - 1].trim() === "")
|
|
12910
|
+
lines.pop();
|
|
12911
|
+
if (lines.length === 0)
|
|
12912
|
+
throw new Error("list-page traversal answered no frame");
|
|
12913
|
+
let first;
|
|
12914
|
+
const rows = [];
|
|
12915
|
+
let activityUnreadRows;
|
|
12916
|
+
let progress;
|
|
12917
|
+
lines.forEach((line) => {
|
|
12918
|
+
if (activityUnreadRows !== undefined)
|
|
12919
|
+
throw new Error("list-page traversal answered a frame after its terminal one");
|
|
12920
|
+
const value = JSON.parse(line);
|
|
12921
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
12922
|
+
throw new Error("list-page traversal answered a frame outside km's page shape");
|
|
12923
|
+
}
|
|
12924
|
+
const bare = value;
|
|
12925
|
+
const frame = bare.verb === "list-page" && typeof bare.result === "object" && bare.result !== null ? bare.result : bare;
|
|
12926
|
+
if (typeof frame.generation !== "string" || frame.generation !== generation) {
|
|
12927
|
+
throw new Error("list-page traversal answered a frame for another generation");
|
|
12928
|
+
}
|
|
12929
|
+
if (typeof frame.population !== "number" || !Number.isSafeInteger(frame.population) || frame.population < 0) {
|
|
12930
|
+
throw new Error("list-page traversal answered a frame with no population count");
|
|
12931
|
+
}
|
|
12932
|
+
if (frame.next !== null && typeof frame.next !== "string") {
|
|
12933
|
+
throw new Error("list-page traversal answered a frame with a malformed next token");
|
|
12934
|
+
}
|
|
12935
|
+
const page = kmPage(JSON.stringify({ verb: "list-page", result: frame }));
|
|
12936
|
+
if (first === undefined) {
|
|
12937
|
+
first = { snapshot: page.snapshot, head: page.head, population: frame.population };
|
|
12938
|
+
} else {
|
|
12939
|
+
if (page.snapshot !== first.snapshot)
|
|
12940
|
+
throw new Error("list-page traversal answered frames of two revisions");
|
|
12941
|
+
if (frame.population !== first.population)
|
|
12942
|
+
throw new Error("list-page traversal answered frames of two populations");
|
|
12943
|
+
if (page.head !== first.head)
|
|
12944
|
+
throw new Error("list-page traversal answered frames of two journal heads");
|
|
12945
|
+
}
|
|
12946
|
+
rows.push(...page.rows);
|
|
12947
|
+
if (frame.complete === true) {
|
|
12948
|
+
if (frame.next !== null)
|
|
12949
|
+
throw new Error("list-page traversal completed a frame that still names a next page");
|
|
12950
|
+
const meta = frame.meta;
|
|
12951
|
+
const count = typeof meta === "object" && meta !== null ? meta.activityUnreadRows : undefined;
|
|
12952
|
+
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > frame.population) {
|
|
12953
|
+
throw new Error(`list-page traversal terminal meta.activityUnreadRows must be an integer from 0 through ${frame.population}; got ${String(count)}`);
|
|
12954
|
+
}
|
|
12955
|
+
activityUnreadRows = count;
|
|
12956
|
+
progress = frame.progress;
|
|
12957
|
+
} else if (frame.next === null) {
|
|
12958
|
+
throw new Error("list-page traversal left a frame incomplete with no next page");
|
|
12959
|
+
}
|
|
12960
|
+
});
|
|
12961
|
+
if (activityUnreadRows === undefined)
|
|
12962
|
+
throw new Error("list-page traversal never completed");
|
|
12963
|
+
if (first === undefined)
|
|
12964
|
+
throw new Error("list-page traversal answered no frame");
|
|
12965
|
+
if (rows.length !== first.population) {
|
|
12966
|
+
throw new Error(`list-page traversal answered ${rows.length} rows of ${first.population}`);
|
|
12967
|
+
}
|
|
12968
|
+
return { snapshot: first.snapshot, head: first.head, rows, activityUnreadRows, progress };
|
|
11093
12969
|
}
|
|
11094
12970
|
function contentRevision(rows) {
|
|
11095
|
-
const hash =
|
|
12971
|
+
const hash = createHash3("sha256");
|
|
11096
12972
|
for (const address of [...rows.keys()].sort())
|
|
11097
12973
|
hash.update(`${address}\x00${rows.get(address).row.version}
|
|
11098
12974
|
`);
|
|
@@ -11114,8 +12990,30 @@ function decodeToken(token) {
|
|
|
11114
12990
|
return;
|
|
11115
12991
|
}
|
|
11116
12992
|
function firstCode(stderr) {
|
|
11117
|
-
|
|
12993
|
+
const named = /\b(yrd-[a-z-]+|page-source-[a-z-]+|page-serve-[a-z-]+|[A-Z][A-Z_]{3,})\b/u.exec(stderr)?.[1];
|
|
12994
|
+
if (named !== undefined)
|
|
12995
|
+
return named;
|
|
12996
|
+
const line = stderr.split(/\r?\n/u).map((one) => one.trim()).find((one) => one.length > 0);
|
|
12997
|
+
return line === undefined ? "no output" : line.slice(0, 140);
|
|
12998
|
+
}
|
|
12999
|
+
function unservableCursor(stderr) {
|
|
13000
|
+
return /\bpage-source-cursor-unservable\b|cursor[^\n]*(?:do a full read|retention|is older than the journal's retained start|is ahead of this store's watermark|is below watermark)/u.test(stderr);
|
|
13001
|
+
}
|
|
13002
|
+
function movedUnderPin(stderr) {
|
|
13003
|
+
return /\bpage-source-(?:moved|not-reconciled)\b/u.test(stderr);
|
|
13004
|
+
}
|
|
13005
|
+
function traversalUnavailable(stderr) {
|
|
13006
|
+
return /\byrd-issues-(?:provider-not-json|verb-unsupported)\b/u.test(stderr);
|
|
13007
|
+
}
|
|
13008
|
+
function undeclaredReader(stderr) {
|
|
13009
|
+
return /\blist-page-serve is not declared\b/u.test(stderr) || /\byrd-issues-verb-unsupported\b/u.test(stderr);
|
|
11118
13010
|
}
|
|
13011
|
+
function pageFrames(pages) {
|
|
13012
|
+
return pages.map((page) => JSON.stringify({ verb: "list-page", result: page })).join(`
|
|
13013
|
+
`) + `
|
|
13014
|
+
`;
|
|
13015
|
+
}
|
|
13016
|
+
var mib = (bytes) => Math.round(bytes / (1024 * 1024));
|
|
11119
13017
|
function describe2(error) {
|
|
11120
13018
|
if (error instanceof Error && "code" in error && typeof error.code === "string")
|
|
11121
13019
|
return error.code;
|
|
@@ -11135,28 +13033,32 @@ var GROUP_WATCHDOG = [
|
|
|
11135
13033
|
'exit "$s"'
|
|
11136
13034
|
].join(`
|
|
11137
13035
|
`);
|
|
11138
|
-
function spawnGroup(argv) {
|
|
11139
|
-
return
|
|
13036
|
+
function spawnGroup(argv, env) {
|
|
13037
|
+
return spawn2("/bin/sh", ["-c", GROUP_WATCHDOG, "hightea-spawn", ...argv], {
|
|
13038
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
13039
|
+
detached: true,
|
|
13040
|
+
...env === undefined ? {} : { env: { ...process.env, HAB_ID_TOKEN_FILE: env.HAB_ID_TOKEN_FILE } }
|
|
13041
|
+
});
|
|
11140
13042
|
}
|
|
11141
13043
|
function notFound(command, code, stderr) {
|
|
11142
13044
|
if (code !== 127 || !stderr.includes("hightea-spawn: ENOENT"))
|
|
11143
13045
|
return;
|
|
11144
13046
|
return Object.assign(new Error(`spawn ${command} ENOENT`), { code: "ENOENT" });
|
|
11145
13047
|
}
|
|
11146
|
-
function
|
|
13048
|
+
function signalGroup2(child, signal) {
|
|
11147
13049
|
if (child.pid === undefined)
|
|
11148
13050
|
return;
|
|
11149
13051
|
try {
|
|
11150
13052
|
process.kill(-child.pid, signal);
|
|
11151
13053
|
} catch {}
|
|
11152
13054
|
}
|
|
11153
|
-
var runChild = (argv, { timeoutMs, signal }) => new Promise((resolve, reject) => {
|
|
13055
|
+
var runChild = (argv, { timeoutMs, signal, env }) => new Promise((resolve, reject) => {
|
|
11154
13056
|
const [command, ...args] = argv;
|
|
11155
13057
|
if (command === undefined) {
|
|
11156
13058
|
reject(new Error("no command"));
|
|
11157
13059
|
return;
|
|
11158
13060
|
}
|
|
11159
|
-
const child = spawnGroup([command, ...args]);
|
|
13061
|
+
const child = spawnGroup([command, ...args], env);
|
|
11160
13062
|
let stdout = "";
|
|
11161
13063
|
let stderr = "";
|
|
11162
13064
|
let bytes = 0;
|
|
@@ -11164,8 +13066,8 @@ var runChild = (argv, { timeoutMs, signal }) => new Promise((resolve, reject) =>
|
|
|
11164
13066
|
const kill = () => {
|
|
11165
13067
|
if (child.exitCode !== null || child.signalCode !== null)
|
|
11166
13068
|
return;
|
|
11167
|
-
|
|
11168
|
-
hard ??= setTimeout(() =>
|
|
13069
|
+
signalGroup2(child, "SIGTERM");
|
|
13070
|
+
hard ??= setTimeout(() => signalGroup2(child, "SIGKILL"), 2000);
|
|
11169
13071
|
};
|
|
11170
13072
|
const deadline = setTimeout(kill, timeoutMs);
|
|
11171
13073
|
signal.addEventListener("abort", kill, { once: true });
|
|
@@ -11190,7 +13092,7 @@ var runChild = (argv, { timeoutMs, signal }) => new Promise((resolve, reject) =>
|
|
|
11190
13092
|
clearTimeout(deadline);
|
|
11191
13093
|
if (hard !== undefined)
|
|
11192
13094
|
clearTimeout(hard);
|
|
11193
|
-
|
|
13095
|
+
signalGroup2(child, "SIGKILL");
|
|
11194
13096
|
signal.removeEventListener("abort", kill);
|
|
11195
13097
|
if (!started)
|
|
11196
13098
|
return;
|
|
@@ -11201,6 +13103,14 @@ var runChild = (argv, { timeoutMs, signal }) => new Promise((resolve, reject) =>
|
|
|
11201
13103
|
resolve({ pid: child.pid, code: killed === null ? code : null, stdout, stderr });
|
|
11202
13104
|
});
|
|
11203
13105
|
});
|
|
13106
|
+
var changeAtOf = (line) => {
|
|
13107
|
+
try {
|
|
13108
|
+
const record = JSON.parse(line);
|
|
13109
|
+
return typeof record.ts === "number" && Number.isFinite(record.ts) ? record.ts : undefined;
|
|
13110
|
+
} catch {
|
|
13111
|
+
return;
|
|
13112
|
+
}
|
|
13113
|
+
};
|
|
11204
13114
|
var followChild = (argv, { signal, onLine }) => new Promise((resolve, reject) => {
|
|
11205
13115
|
const [command, ...args] = argv;
|
|
11206
13116
|
if (command === undefined) {
|
|
@@ -11213,13 +13123,13 @@ var followChild = (argv, { signal, onLine }) => new Promise((resolve, reject) =>
|
|
|
11213
13123
|
const kill = () => {
|
|
11214
13124
|
if (child.exitCode !== null || child.signalCode !== null)
|
|
11215
13125
|
return;
|
|
11216
|
-
|
|
11217
|
-
hard ??= setTimeout(() =>
|
|
13126
|
+
signalGroup2(child, "SIGTERM");
|
|
13127
|
+
hard ??= setTimeout(() => signalGroup2(child, "SIGKILL"), 2000);
|
|
11218
13128
|
};
|
|
11219
13129
|
signal.addEventListener("abort", kill, { once: true });
|
|
11220
|
-
|
|
13130
|
+
createInterface2({ input: child.stdout }).on("line", (line) => {
|
|
11221
13131
|
if (line.trim() !== "")
|
|
11222
|
-
onLine();
|
|
13132
|
+
onLine(line);
|
|
11223
13133
|
});
|
|
11224
13134
|
child.stderr.setEncoding("utf8").on("data", (chunk) => {
|
|
11225
13135
|
if (stderr.length < 64 * 1024)
|
|
@@ -11233,7 +13143,7 @@ var followChild = (argv, { signal, onLine }) => new Promise((resolve, reject) =>
|
|
|
11233
13143
|
child.on("close", (code, killed) => {
|
|
11234
13144
|
if (hard !== undefined)
|
|
11235
13145
|
clearTimeout(hard);
|
|
11236
|
-
|
|
13146
|
+
signalGroup2(child, "SIGKILL");
|
|
11237
13147
|
signal.removeEventListener("abort", kill);
|
|
11238
13148
|
if (!started)
|
|
11239
13149
|
return;
|
|
@@ -11246,6 +13156,13 @@ var followChild = (argv, { signal, onLine }) => new Promise((resolve, reject) =>
|
|
|
11246
13156
|
});
|
|
11247
13157
|
|
|
11248
13158
|
// ../ahp-host/src/source-channel.ts
|
|
13159
|
+
function nearestIssues(issues, depth = 0) {
|
|
13160
|
+
return issues.flatMap((issue) => {
|
|
13161
|
+
if (depth >= 3 || issue.errors === undefined || issue.errors.length === 0)
|
|
13162
|
+
return [issue];
|
|
13163
|
+
return issue.errors.map((branch) => nearestIssues(branch, depth + 1)).reduce((best, one) => one.length < best.length ? one : best);
|
|
13164
|
+
});
|
|
13165
|
+
}
|
|
11249
13166
|
var REQUEST = "x-hightea/source/request";
|
|
11250
13167
|
function createSourceChannel(options) {
|
|
11251
13168
|
const { log } = options;
|
|
@@ -11271,9 +13188,13 @@ function createSourceChannel(options) {
|
|
|
11271
13188
|
return answer(connection, id, request, "unknown", "SOURCE_UNAVAILABLE");
|
|
11272
13189
|
}
|
|
11273
13190
|
const parsed = SourceResponseSchema.safeParse(result);
|
|
11274
|
-
|
|
11275
|
-
|
|
11276
|
-
log.error(`hightea-source: ${request.op} on ${request.sourceId} returned an answer outside its schema`);
|
|
13191
|
+
if (!parsed.success) {
|
|
13192
|
+
const named = nearestIssues(parsed.error.issues).slice(0, 3).map((issue) => `${issue.path.join(".") || "answer"}: ${issue.message}`).join("; ").slice(0, 400);
|
|
13193
|
+
log.error(`hightea-source: ${request.op} on ${request.sourceId} returned an answer outside its schema: ${named}`);
|
|
13194
|
+
return answer(connection, id, request, "unknown", "SOURCE_UNAVAILABLE");
|
|
13195
|
+
}
|
|
13196
|
+
if (parsed.data.workspaceId !== request.workspaceId || parsed.data.sourceId !== request.sourceId || parsed.data.hostId !== request.hostId || parsed.data.op !== request.op) {
|
|
13197
|
+
log.error(`hightea-source: ${request.op} on ${request.sourceId} was answered for another binding: ` + `${parsed.data.op} on ${parsed.data.sourceId} in ${parsed.data.workspaceId} for ${parsed.data.hostId}`);
|
|
11277
13198
|
return answer(connection, id, request, "unknown", "SOURCE_UNAVAILABLE");
|
|
11278
13199
|
}
|
|
11279
13200
|
return send(connection, id, request, parsed.data);
|
|
@@ -11306,7 +13227,7 @@ function createSourceChannel(options) {
|
|
|
11306
13227
|
// ../ahp-host/src/plugin.ts
|
|
11307
13228
|
var name = "hightea-pipe";
|
|
11308
13229
|
var owner = `plugin:${name}`;
|
|
11309
|
-
var hostTools = ["hightea_read_thread", "hightea_post", "hightea_page_read", "hightea_page_write"];
|
|
13230
|
+
var hostTools = ["hightea_read_thread", "hightea_post", "hightea_page_read", "hightea_page_write", "hightea_page_screenshot"];
|
|
11310
13231
|
function jwtExpiresAt(token) {
|
|
11311
13232
|
const parts = token.split(".");
|
|
11312
13233
|
if (parts.length !== 3)
|
|
@@ -11332,38 +13253,56 @@ function shareListener(peer) {
|
|
|
11332
13253
|
close: () => peer.close()
|
|
11333
13254
|
};
|
|
11334
13255
|
}
|
|
11335
|
-
function
|
|
13256
|
+
function houseHeaders(token) {
|
|
13257
|
+
return { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" };
|
|
13258
|
+
}
|
|
13259
|
+
async function houseCall(mcpUrl, headers, tool, args) {
|
|
13260
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } });
|
|
13261
|
+
let answer;
|
|
13262
|
+
for (let attempt = 0;answer === undefined; attempt++) {
|
|
13263
|
+
try {
|
|
13264
|
+
answer = await (await fetch(mcpUrl, { method: "POST", headers, body })).json();
|
|
13265
|
+
} catch (error) {
|
|
13266
|
+
if (attempt >= 1)
|
|
13267
|
+
throw new Error(`HOUSE_UNREACHABLE: ${String(error)}`);
|
|
13268
|
+
}
|
|
13269
|
+
}
|
|
13270
|
+
if (answer.error !== undefined)
|
|
13271
|
+
throw new Error(answer.error.message);
|
|
13272
|
+
return answer;
|
|
13273
|
+
}
|
|
13274
|
+
function registerTools(host, mcpUrl, pipe, signing) {
|
|
11336
13275
|
const call = async (at, tool, args) => {
|
|
11337
13276
|
const activePipe = pipe();
|
|
11338
13277
|
const context = { sessionId: at.session, chatId: at.chat, turnId: at.turn() ?? "" };
|
|
11339
13278
|
const resolved = activePipe?.resolveToolToken(context);
|
|
11340
13279
|
if (resolved === undefined || !resolved.ok)
|
|
11341
13280
|
throw new Error("TOKEN_EXPIRED_OR_REVOKED");
|
|
11342
|
-
const headers =
|
|
11343
|
-
authorization: `Bearer ${resolved.token}`,
|
|
11344
|
-
"content-type": "application/json",
|
|
11345
|
-
accept: "application/json, text/event-stream"
|
|
11346
|
-
};
|
|
13281
|
+
const headers = houseHeaders(resolved.token);
|
|
11347
13282
|
if (tool === "post_message")
|
|
11348
13283
|
headers["idempotency-key"] = resolved.deliveryId;
|
|
11349
13284
|
if (tool === "read_thread" || tool === "post_message") {
|
|
11350
13285
|
const [roomId, messageId, extra] = resolved.threadRef.split("/");
|
|
11351
13286
|
if (!roomId || !messageId || extra !== undefined)
|
|
11352
13287
|
throw new Error("Invalid wake thread reference");
|
|
11353
|
-
|
|
11354
|
-
|
|
11355
|
-
|
|
11356
|
-
|
|
11357
|
-
|
|
11358
|
-
|
|
11359
|
-
|
|
11360
|
-
|
|
11361
|
-
|
|
11362
|
-
|
|
13288
|
+
if (tool === "read_thread") {
|
|
13289
|
+
args = { roomId, messageId, ...resolved.afterMessageId === undefined ? {} : { after: resolved.afterMessageId } };
|
|
13290
|
+
} else {
|
|
13291
|
+
const key = await signing.hostKey;
|
|
13292
|
+
if (key === undefined || key instanceof Error) {
|
|
13293
|
+
throw new Error(`HOST_KEY_UNAVAILABLE: this host cannot sign its agent's post${key instanceof Error ? `: ${key.message}` : " (its ahpd names no configDir)"}`);
|
|
13294
|
+
}
|
|
13295
|
+
const text = String(args.text ?? "");
|
|
13296
|
+
args = {
|
|
13297
|
+
text,
|
|
13298
|
+
roomId,
|
|
13299
|
+
deliveryId: resolved.deliveryId,
|
|
13300
|
+
replyId: resolved.deliveryId,
|
|
13301
|
+
sig: signHostPost(key, { workspaceId: signing.houseId, roomId, rootMessageId: messageId, authorMemberId: resolved.agentMemberId, clientId: resolved.deliveryId, body: text })
|
|
13302
|
+
};
|
|
11363
13303
|
}
|
|
11364
13304
|
}
|
|
11365
|
-
|
|
11366
|
-
throw new Error(answer.error.message);
|
|
13305
|
+
const answer = await houseCall(mcpUrl, headers, tool, args);
|
|
11367
13306
|
if (tool === "read_thread") {
|
|
11368
13307
|
const value = answer.result?.structuredContent;
|
|
11369
13308
|
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 === "")) {
|
|
@@ -11376,6 +13315,7 @@ function registerTools(host, mcpUrl, pipe) {
|
|
|
11376
13315
|
const position = last?.id ?? current.afterMessageId ?? value.root.id;
|
|
11377
13316
|
if (current.afterMessageId === resolved.afterMessageId)
|
|
11378
13317
|
activePipe.vault.recordThreadRead(context, position);
|
|
13318
|
+
return JSON.stringify(await signing.gate.view(resolved.threadRef, value));
|
|
11379
13319
|
}
|
|
11380
13320
|
return (answer.result?.content ?? []).map((part) => part.text).join(`
|
|
11381
13321
|
`);
|
|
@@ -11428,6 +13368,48 @@ function registerTools(host, mcpUrl, pipe) {
|
|
|
11428
13368
|
return call(at, "page_write", { pageId: String(args.pageId ?? ""), ifVersion: Number(args.ifVersion), content: String(args.content ?? "") });
|
|
11429
13369
|
}
|
|
11430
13370
|
});
|
|
13371
|
+
host.registerTool({
|
|
13372
|
+
definition: {
|
|
13373
|
+
name: "hightea_page_screenshot",
|
|
13374
|
+
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.",
|
|
13375
|
+
inputSchema: {
|
|
13376
|
+
type: "object",
|
|
13377
|
+
properties: {
|
|
13378
|
+
pageId: { type: "string" },
|
|
13379
|
+
version: { type: "number", description: "Optional expected version; any version that is not live is refused (VERSION_NOT_CURRENT)." },
|
|
13380
|
+
width: { type: "number", description: "Capture width in CSS pixels (16..2400)." },
|
|
13381
|
+
height: { type: "number", description: "Minimum capture height in CSS pixels (16..2400)." },
|
|
13382
|
+
format: { type: "string", enum: ["png", "webp"] }
|
|
13383
|
+
},
|
|
13384
|
+
required: ["pageId"],
|
|
13385
|
+
additionalProperties: false
|
|
13386
|
+
}
|
|
13387
|
+
},
|
|
13388
|
+
confirm: false,
|
|
13389
|
+
optIn: true,
|
|
13390
|
+
run: (input, at) => call(at, "page_screenshot", pageScreenshotArgs(input))
|
|
13391
|
+
});
|
|
13392
|
+
}
|
|
13393
|
+
function pageScreenshotArgs(input) {
|
|
13394
|
+
const wanted = input ?? {};
|
|
13395
|
+
const pageId = wanted.pageId;
|
|
13396
|
+
if (typeof pageId !== "string" || pageId.trim().length === 0)
|
|
13397
|
+
throw new Error("page_screenshot requires a non-empty string pageId");
|
|
13398
|
+
const args = { pageId };
|
|
13399
|
+
for (const key of ["version", "width", "height"]) {
|
|
13400
|
+
const value = wanted[key];
|
|
13401
|
+
if (value === undefined)
|
|
13402
|
+
continue;
|
|
13403
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
13404
|
+
throw new Error(`page_screenshot ${key} must be a number`);
|
|
13405
|
+
args[key] = value;
|
|
13406
|
+
}
|
|
13407
|
+
if (wanted.format !== undefined) {
|
|
13408
|
+
if (wanted.format !== "png" && wanted.format !== "webp")
|
|
13409
|
+
throw new Error("page_screenshot format is png or webp");
|
|
13410
|
+
args.format = wanted.format;
|
|
13411
|
+
}
|
|
13412
|
+
return args;
|
|
11431
13413
|
}
|
|
11432
13414
|
function applyWith(host, options, seams) {
|
|
11433
13415
|
let running;
|
|
@@ -11444,8 +13426,27 @@ function applyWith(host, options, seams) {
|
|
|
11444
13426
|
await Promise.all([...kmSources.values()].map((source) => source.stop()));
|
|
11445
13427
|
};
|
|
11446
13428
|
host.registerClose(stop);
|
|
13429
|
+
const hostKey = host.configDir === undefined ? Promise.resolve(undefined) : hostSigningKey(host.configDir).catch((error) => {
|
|
13430
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
13431
|
+
host.log.error(`${name}: ${failure.message}`);
|
|
13432
|
+
return failure;
|
|
13433
|
+
});
|
|
13434
|
+
const gate = new AskGate({
|
|
13435
|
+
configDir: host.configDir,
|
|
13436
|
+
houseId: options.houseId,
|
|
13437
|
+
ownAgents: new Set(options.agents.map(([member]) => member)),
|
|
13438
|
+
hostKey,
|
|
13439
|
+
readThread: async (token, args) => {
|
|
13440
|
+
if (options.mcpUrl === undefined)
|
|
13441
|
+
throw new AskRefusal("ROOM_ASKS_UNTRUSTED", "this host has no house MCP endpoint to read the ask from");
|
|
13442
|
+
const answer = await houseCall(options.mcpUrl, houseHeaders(token), "read_thread", args);
|
|
13443
|
+
return answer.result?.structuredContent;
|
|
13444
|
+
}
|
|
13445
|
+
});
|
|
13446
|
+
const checks = seams.askGate ?? gate;
|
|
13447
|
+
const signing = { houseId: options.houseId, hostKey, gate: checks };
|
|
11447
13448
|
if (options.mcpUrl !== undefined)
|
|
11448
|
-
registerTools(host, options.mcpUrl, () => running);
|
|
13449
|
+
registerTools(host, options.mcpUrl, () => running, signing);
|
|
11449
13450
|
host.on("listening", () => {
|
|
11450
13451
|
if (stopped || startup !== undefined || cloud !== undefined)
|
|
11451
13452
|
return;
|
|
@@ -11461,6 +13462,11 @@ function applyWith(host, options, seams) {
|
|
|
11461
13462
|
hostId,
|
|
11462
13463
|
log: host.log,
|
|
11463
13464
|
...seams.sourceChildren,
|
|
13465
|
+
serviceIdentityEnvironment: (binding) => {
|
|
13466
|
+
if (typeof host.serviceIdentityEnvironment !== "function")
|
|
13467
|
+
throw new Error("SERVICE_IDENTITY_UNAVAILABLE: native host callback missing");
|
|
13468
|
+
return host.serviceIdentityEnvironment(binding);
|
|
13469
|
+
},
|
|
11464
13470
|
push: (params) => link.sourcePush(params)
|
|
11465
13471
|
})]));
|
|
11466
13472
|
const offered = new Set(kmSources.keys());
|
|
@@ -11482,20 +13488,25 @@ function applyWith(host, options, seams) {
|
|
|
11482
13488
|
return socket;
|
|
11483
13489
|
},
|
|
11484
13490
|
receive: (frame, connection) => {
|
|
11485
|
-
|
|
11486
|
-
if (sources.receive(seen, connection))
|
|
13491
|
+
if (sources.receive(frame, connection))
|
|
11487
13492
|
return;
|
|
11488
|
-
pipe.fromCloud(
|
|
13493
|
+
pipe.fromCloud(frame);
|
|
11489
13494
|
},
|
|
11490
13495
|
log: host.log,
|
|
11491
13496
|
opened: (connection) => {
|
|
11492
13497
|
initialized ??= pipe.start(name);
|
|
11493
|
-
|
|
13498
|
+
const hello = () => {
|
|
11494
13499
|
if (!stopped)
|
|
11495
13500
|
connection.send({ jsonrpc: "2.0", method: "x-hightea/hello", params: { plugin: name, runtime: process.versions.bun === undefined ? "node" : "bun" } });
|
|
11496
|
-
}
|
|
13501
|
+
};
|
|
13502
|
+
initialized.then(hello, (error) => {
|
|
11497
13503
|
if (stopped)
|
|
11498
13504
|
return;
|
|
13505
|
+
if (error instanceof UnmappedAgent && kmSources.size > 0) {
|
|
13506
|
+
host.log.error(`${name}: agent conversations unavailable; declared sources remain connected: ${String(error)}`);
|
|
13507
|
+
hello();
|
|
13508
|
+
return;
|
|
13509
|
+
}
|
|
11499
13510
|
host.log.error(`${name}: could not start on the local ahpd: ${String(error)}`);
|
|
11500
13511
|
connection.send({ jsonrpc: "2.0", method: "x-hightea/fatal", params: { code: "HOST_START_FAILED" } });
|
|
11501
13512
|
stop();
|
|
@@ -11514,7 +13525,8 @@ function applyWith(host, options, seams) {
|
|
|
11514
13525
|
tools: options.mcpUrl === undefined ? [] : hostTools,
|
|
11515
13526
|
startSession: (wanted, named) => host.startSession(wanted, named),
|
|
11516
13527
|
log: host.log,
|
|
11517
|
-
store: recordsPipeStore(host.records("hightea"), owner, (uri) => host.sessionOwner(uri))
|
|
13528
|
+
store: recordsPipeStore(host.records("hightea"), owner, (uri) => host.sessionOwner(uri)),
|
|
13529
|
+
admitTurn: (meta, token) => checks.admit(meta, token)
|
|
11518
13530
|
});
|
|
11519
13531
|
running = pipe;
|
|
11520
13532
|
}, 100);
|
|
@@ -11527,8 +13539,10 @@ export {
|
|
|
11527
13539
|
WakePipe,
|
|
11528
13540
|
apply,
|
|
11529
13541
|
applyWith,
|
|
13542
|
+
houseCall,
|
|
11530
13543
|
jwtExpiresAt,
|
|
11531
13544
|
name,
|
|
13545
|
+
pageScreenshotArgs,
|
|
11532
13546
|
recordsPipeStore,
|
|
11533
13547
|
registerTools,
|
|
11534
13548
|
shareListener
|