@hallohuman/hightea 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  // package.json
6
6
  var package_default = {
7
7
  name: "@hallohuman/hightea",
8
- version: "0.1.1",
8
+ version: "0.1.2",
9
9
  description: "The Hightea command line: join this machine to a Hightea workspace as a host.",
10
10
  publishConfig: { access: "public" },
11
11
  type: "module",
@@ -30,14 +30,40 @@ async function runCli(argv, options) {
30
30
  let code = 0;
31
31
  const program = new Command("hightea").description("Hightea: join this machine to a Hightea workspace as a host for your own agents.").version(options.version, "-v, --version").exitOverride();
32
32
  const host = program.command("host").description("This machine as a host: where your agents run.").exitOverride();
33
- host.command("join").description("Join this machine to a workspace with a one-use host join code from the workspace owner.").option("--origin <url>", "The deployment, e.g. https://hightea.dev").option("--workspace <slug>", "The workspace slug").option("--code <code>", "The one-use join code").option("--owner-config <file>", "Your owner configuration: agents, provider plugins and their credentials").exitOverride().action(async (flags) => {
34
- const { hostJoin } = await import("./chunk-24qdztvs.js");
33
+ host.command("join").description("Join this machine to a workspace with a one-use host join code from the workspace owner.").option("--origin <url>", "The deployment, e.g. https://hightea.dev").option("--workspace <slug>", "The workspace slug").option("--code <code>", "The one-use join code").option("--owner-config <file>", "Your owner configuration: agents, provider plugins and their credentials").addHelpText("after", `
34
+ Exit status: 0 registered; 2 pending, rerun the same command; 3 not authorised for that workspace or agent;
35
+ 4 an agent is already bound to another host; 1 any other failure.`).exitOverride().action(async (flags) => {
36
+ const { hostJoin } = await import("./chunk-mcmsnaer.js");
35
37
  code = await hostJoin({ origin: flags.origin ?? "", workspace: flags.workspace ?? "", code: flags.code ?? "", ownerConfig: flags.ownerConfig ?? "" }, { directory: options.pluginDirectory, version: options.version });
36
38
  });
37
39
  host.command("status").description("Show every joined host on this machine and whether its plugin bundle is intact. Changes nothing.").option("--json", "Print one JSON document").exitOverride().action(async (flags) => {
38
- const { hostStatus } = await import("./chunk-24qdztvs.js");
40
+ const { hostStatus } = await import("./chunk-mcmsnaer.js");
39
41
  code = await hostStatus({ version: options.version, json: flags.json === true });
40
42
  });
43
+ const source = program.command("source").description("A workspace's km sources: bind one to a host, or read its state.").exitOverride();
44
+ source.command("bind").description("Bind a km source to one of the workspace's hosts, as the workspace owner.").option("--origin <url>", "The deployment, e.g. https://hightea.dev").option("--workspace <slug>", "The workspace slug").option("--source <id>", "The source id, e.g. src_km").option("--host <id>", "The host id that serves the source").option("--session-file <file>", "File holding your signed-in ht_session cookie (default: HIGHTEA_SESSION_FILE)").option("--json", "Print one JSON document").addHelpText("after", `
45
+ Exit status: 0 bound; 3 your account is not this workspace's owner; 4 that source is bound to another host;
46
+ 1 any other failure.`).exitOverride().action(async (flags) => {
47
+ const { sourceBind } = await import("./chunk-9wxqnv9x.js");
48
+ code = await sourceBind({
49
+ origin: flags.origin ?? "",
50
+ workspace: flags.workspace ?? "",
51
+ source: flags.source ?? "",
52
+ host: flags.host ?? "",
53
+ sessionFile: flags.sessionFile,
54
+ json: flags.json === true
55
+ });
56
+ });
57
+ source.command("show").description("Read one source's binding, freshness and position; changes nothing.").option("--origin <url>", "The deployment, e.g. https://hightea.dev").option("--workspace <slug>", "The workspace slug").option("--source <id>", "The source id, e.g. src_km").option("--session-file <file>", "File holding your signed-in ht_session cookie (default: HIGHTEA_SESSION_FILE)").option("--json", "Print one JSON document").exitOverride().action(async (flags) => {
58
+ const { sourceShow } = await import("./chunk-9wxqnv9x.js");
59
+ code = await sourceShow({
60
+ origin: flags.origin ?? "",
61
+ workspace: flags.workspace ?? "",
62
+ source: flags.source ?? "",
63
+ sessionFile: flags.sessionFile,
64
+ json: flags.json === true
65
+ });
66
+ });
41
67
  try {
42
68
  await program.parseAsync([...argv], { from: "user" });
43
69
  } catch (error) {
@@ -0,0 +1,149 @@
1
+ // src/source.ts
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ var USAGE = `hightea source bind --origin https://your-deployment --workspace SLUG --source SOURCE --host HOST [--session-file FILE] [--json]
6
+ ` + "hightea source show --origin https://your-deployment --workspace SLUG --source SOURCE [--session-file FILE] [--json]";
7
+ var NOT_OWNER = new Set(["FORBIDDEN", "NOT_A_MEMBER", "UNAUTHENTICATED"]);
8
+ var BOUND_ELSEWHERE = "SOURCE_BINDING_CONFLICT";
9
+ function defaults() {
10
+ return {
11
+ fetch: (url, init) => globalThis.fetch(url, init),
12
+ readFile: (path) => readFile(path, "utf8"),
13
+ stat: (path) => stat(path),
14
+ env: process.env,
15
+ home: homedir(),
16
+ out: (line) => {
17
+ process.stdout.write(`${line}
18
+ `);
19
+ },
20
+ err: (line) => {
21
+ process.stderr.write(`${line}
22
+ `);
23
+ }
24
+ };
25
+ }
26
+ function checkedOrigin(origin) {
27
+ try {
28
+ const url = new URL(origin);
29
+ return url.protocol === "https:" && url.pathname === "/" && url.search === "" && url.hash === "" ? url.origin : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+ async function readSession(target, io) {
35
+ const file = target.sessionFile?.trim() || io.env.HIGHTEA_SESSION_FILE?.trim() || join(io.env.XDG_CONFIG_HOME?.trim() || join(io.home, ".config"), "hightea", "session");
36
+ let raw;
37
+ let mode;
38
+ try {
39
+ raw = await io.readFile(file);
40
+ mode = (await io.stat(file)).mode;
41
+ } catch (error) {
42
+ return { error: `SOURCE_SESSION_MISSING: no session in ${file} (${error.message}). Sign in to the deployment in a browser and write its ht_session cookie to that file, or pass --session-file.` };
43
+ }
44
+ if ((mode & 63) !== 0) {
45
+ return { error: `SOURCE_SESSION_EXPOSED: ${file} is mode 0${(mode & 511).toString(8).padStart(3, "0")}; run chmod 600 ${file}.` };
46
+ }
47
+ const lines = raw.split(`
48
+ `).map((line) => line.trim()).filter((line) => line.length > 0);
49
+ if (lines.length !== 1) {
50
+ return { error: `SOURCE_SESSION_INVALID: ${file} must hold exactly one non-empty line (the ht_session cookie value); it holds ${lines.length}.` };
51
+ }
52
+ return { cookie: lines[0] };
53
+ }
54
+ async function send(target, io, request) {
55
+ const origin = checkedOrigin(target.origin);
56
+ if (origin === null) {
57
+ return { exit: 1, error: `SOURCE_ORIGIN_INVALID: --origin must be the https deployment origin, e.g. https://hightea.dev (got ${JSON.stringify(target.origin)}).` };
58
+ }
59
+ if (target.workspace.trim().length === 0 || target.source.trim().length === 0) {
60
+ return { exit: 1, error: `SOURCE_INPUT: --workspace and --source are required.
61
+ ${USAGE}` };
62
+ }
63
+ const session = await readSession(target, io);
64
+ if ("error" in session)
65
+ return { exit: 1, error: session.error };
66
+ const url = `${origin}/api/ws/${encodeURIComponent(target.workspace)}/sources/${encodeURIComponent(target.source)}${request.path}`;
67
+ let response;
68
+ try {
69
+ response = await io.fetch(url, {
70
+ method: request.method,
71
+ headers: {
72
+ cookie: `ht_session=${session.cookie}`,
73
+ origin,
74
+ accept: "application/json",
75
+ "cache-control": "no-store",
76
+ ...request.body === undefined ? {} : { "content-type": "application/json" }
77
+ },
78
+ ...request.body === undefined ? {} : { body: JSON.stringify(request.body) }
79
+ });
80
+ } catch (error) {
81
+ return { exit: 1, error: `SOURCE_UNREACHABLE: ${request.what} ${request.method} ${url} did not answer: ${error.message}` };
82
+ }
83
+ const text = await response.text();
84
+ let answer = {};
85
+ if (text.length > 0) {
86
+ try {
87
+ const parsed = JSON.parse(text);
88
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
89
+ throw new SyntaxError("not a JSON object");
90
+ answer = parsed;
91
+ } catch (error) {
92
+ if (!(error instanceof SyntaxError))
93
+ throw error;
94
+ return { exit: 1, error: `SOURCE_ANSWER_INVALID: ${request.what} ${request.method} ${url} answered HTTP ${response.status} with non-JSON: ${text.slice(0, 300)}` };
95
+ }
96
+ }
97
+ if (response.ok)
98
+ return { answer };
99
+ const refusal = answer.error;
100
+ const code = typeof refusal?.code === "string" ? refusal.code : `HTTP_${response.status}`;
101
+ const message = typeof refusal?.message === "string" ? refusal.message : text.slice(0, 300);
102
+ const exit = NOT_OWNER.has(code) ? 3 : code === BOUND_ELSEWHERE ? 4 : 1;
103
+ return { exit, error: `${code}: ${message}` };
104
+ }
105
+ function datasetLine(source) {
106
+ const field = (name) => source[name] === null || source[name] === undefined ? "none" : String(source[name]);
107
+ const listing = source.listing === true ? ", first list running" : source.listing === false ? ", no list running" : "";
108
+ return `${field("status")} on ${field("hostId")} as dataset ${field("dataset")} (freshness ${field("freshness")}${listing})`;
109
+ }
110
+ async function sourceBind(target, io = defaults()) {
111
+ if (target.host.trim().length === 0) {
112
+ io.err(`SOURCE_INPUT: --host is required (the host id that serves the source).
113
+ ${USAGE}`);
114
+ return 1;
115
+ }
116
+ const sent = await send(target, io, { method: "POST", path: "/bind", body: { hostId: target.host.trim() }, what: "bind" });
117
+ if ("error" in sent) {
118
+ io.err(sent.error);
119
+ return sent.exit;
120
+ }
121
+ if (target.json) {
122
+ io.out(JSON.stringify(sent.answer));
123
+ return 0;
124
+ }
125
+ const source = sent.answer.source ?? {};
126
+ io.out(`bound ${String(source.sourceId ?? target.source)} to ${String(source.hostId ?? target.host)}: ${datasetLine(source)}`);
127
+ io.out("The source's first list fills its dataset; run `hightea source show` to watch its freshness.");
128
+ return 0;
129
+ }
130
+ async function sourceShow(target, io = defaults()) {
131
+ const sent = await send(target, io, { method: "GET", path: "", what: "read" });
132
+ if ("error" in sent) {
133
+ io.err(sent.error);
134
+ return sent.exit;
135
+ }
136
+ if (target.json) {
137
+ io.out(JSON.stringify(sent.answer));
138
+ return 0;
139
+ }
140
+ const source = sent.answer.source ?? {};
141
+ const position = source.position;
142
+ io.out(`${String(source.sourceId ?? target.source)}: ${datasetLine(source)}`);
143
+ io.out(`position ${position === null || position === undefined ? "none" : `${String(position.epoch)}/${String(position.ordinal)}`}, ` + `last error ${source.lastError === null || source.lastError === undefined ? "none" : String(source.lastError)}, ` + `dropped ${String(source.dropped ?? 0)}, duplicates ${String(source.duplicates ?? 0)}`);
144
+ return 0;
145
+ }
146
+ export {
147
+ sourceBind,
148
+ sourceShow
149
+ };
@@ -1,5 +1,6 @@
1
1
  // ../ahp-host/src/commands.ts
2
2
  import { readdir, readFile as readFile2 } from "node:fs/promises";
3
+ import { createRequire } from "node:module";
3
4
  import { homedir } from "node:os";
4
5
  import { basename, dirname as dirname3, isAbsolute as isAbsolute3, join as join5, resolve } from "node:path";
5
6
  import { fromEnvRef as fromEnvRef2, isRecord as isRecord3, readSecret, secretRef as secretRef2 } from "@ahpd/sdk";
@@ -5150,6 +5151,24 @@ function superRefine(fn, params) {
5150
5151
  return _superRefine(fn, params);
5151
5152
  }
5152
5153
  // ../members/src/host-join-types.ts
5154
+ var JOIN_ROUTE_REFUSAL_STATUS = {
5155
+ JOIN_LINK_INVALID: 410,
5156
+ JOIN_LINK_NOT_FOUND: 404,
5157
+ ROLE_NOT_ALLOWED: 400,
5158
+ NOT_A_MEMBER: 403,
5159
+ FORBIDDEN: 403,
5160
+ HOST_REGISTRATION_CANCELLED: 410,
5161
+ HOST_REGISTRATION_CONFLICT: 409,
5162
+ AGENT_HOST_CONFLICT: 409,
5163
+ HOST_REGISTRATION_MISSING: 409,
5164
+ INVALID_REQUEST: 400,
5165
+ BAD_ORIGIN: 403,
5166
+ UNAUTHENTICATED: 401,
5167
+ WORKSPACE_NOT_FOUND: 404
5168
+ };
5169
+ function isJoinRouteRefusalCode(value) {
5170
+ return typeof value === "string" && Object.hasOwn(JOIN_ROUTE_REFUSAL_STATUS, value);
5171
+ }
5153
5172
  var id = string2().min(1).max(256);
5154
5173
  var digest = string2().regex(/^sha256:[a-f0-9]{64}$/u);
5155
5174
  var version2 = string2().min(1).max(64);
@@ -5412,6 +5431,24 @@ async function saveHostJson(claim, directory, name, configuration) {
5412
5431
 
5413
5432
  // ../ahp-host/src/join.ts
5414
5433
  import { isRecord } from "@ahpd/sdk";
5434
+ class HostJoinRefusal extends Error {
5435
+ kind;
5436
+ status;
5437
+ serverCode;
5438
+ constructor(kind, status, serverCode) {
5439
+ super(kind);
5440
+ this.kind = kind;
5441
+ this.status = status;
5442
+ this.serverCode = serverCode;
5443
+ }
5444
+ }
5445
+ function refusalKind(status, serverCode) {
5446
+ if (status === 401 || status === 403)
5447
+ return "HOST_JOIN_NOT_AUTHORISED";
5448
+ if (serverCode === "AGENT_HOST_CONFLICT" || serverCode === "HOST_REGISTRATION_CONFLICT")
5449
+ return "HOST_JOIN_AGENT_BOUND";
5450
+ return "HOST_JOIN_REJECTED";
5451
+ }
5415
5452
  async function redeemHostClaim(claim) {
5416
5453
  await flushHostFile(claim.vaultFile);
5417
5454
  const intent = claim.intent;
@@ -5439,8 +5476,14 @@ async function redeemHostClaim(claim) {
5439
5476
  }
5440
5477
  if (response.status >= 500)
5441
5478
  throw new Error("HOST_JOIN_REMOTE_UNAVAILABLE");
5442
- if (!response.ok)
5443
- throw new Error("HOST_JOIN_REJECTED");
5479
+ if (!response.ok) {
5480
+ let error;
5481
+ try {
5482
+ error = await response.json();
5483
+ } catch {}
5484
+ const serverCode = isRecord(error) && isRecord(error.error) && isJoinRouteRefusalCode(error.error.code) ? error.error.code : undefined;
5485
+ throw new HostJoinRefusal(refusalKind(response.status, serverCode), response.status, serverCode);
5486
+ }
5444
5487
  let receipt;
5445
5488
  try {
5446
5489
  receipt = await response.json();
@@ -5703,6 +5746,8 @@ var DIAGNOSTICS = {
5703
5746
  HOST_JOIN_CANCELLED: "The owner cancelled this host registration. Keep the existing claim; request a new join code for another registration.",
5704
5747
  HOST_JOIN_LINK_UNAVAILABLE: "This join code is expired or unavailable. Keep the existing claim; request a new code if registration was not completed.",
5705
5748
  HOST_JOIN_REJECTED: "The deployment rejected registration. Check the deployment and workspace; the selected credential was retained.",
5749
+ HOST_JOIN_NOT_AUTHORISED: "The deployment refused this account for that workspace or agent. Join with the account that owns the agents in --owner-config; the selected credential was retained.",
5750
+ HOST_JOIN_AGENT_BOUND: "An agent in --owner-config already belongs to another host. Remove that host (or its registration) in the workspace, then rerun the same command; the selected credential was retained.",
5706
5751
  HOST_JOIN_RECEIPT_INVALID: "The deployment returned an invalid registration receipt. Keep this claim and retry against the correct deployment.",
5707
5752
  HOST_JOIN_CONFIG_CONFLICT: "Existing host configuration has different bindings or required settings. It was preserved; reconcile it with the original claim before retrying.",
5708
5753
  HOST_JOIN_CONFIG_CORRUPT: "Existing host configuration is invalid JSON. It was preserved for local repair; rerun after repairing it.",
@@ -5716,6 +5761,34 @@ function xdgHome(variable, fallback) {
5716
5761
  throw new Error("HOST_JOIN_UNSAFE_PATH");
5717
5762
  return home;
5718
5763
  }
5764
+ function installedDaemon() {
5765
+ const manifest = createRequire(import.meta.url).resolve("@ahpd/server/package.json");
5766
+ return { node: process.execPath, main: join5(dirname3(manifest), "dist", "main.js") };
5767
+ }
5768
+ var shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
5769
+ function hostStartCommand(claim, daemon = installedDaemon()) {
5770
+ return `XDG_CONFIG_HOME=${shellQuote(claim)} ${shellQuote(daemon.node)} ${shellQuote(daemon.main)} start`;
5771
+ }
5772
+ var SERVER_REFUSALS = {
5773
+ JOIN_LINK_INVALID: "the join code is no longer valid",
5774
+ JOIN_LINK_NOT_FOUND: "no such join code in that workspace",
5775
+ ROLE_NOT_ALLOWED: "the join code does not allow this role",
5776
+ NOT_A_MEMBER: "the signed-in account is not a member of that workspace",
5777
+ FORBIDDEN: "an agent in --owner-config belongs to another account",
5778
+ HOST_REGISTRATION_CANCELLED: "the owner cancelled this registration",
5779
+ HOST_REGISTRATION_CONFLICT: "this code was redeemed for a different host registration",
5780
+ AGENT_HOST_CONFLICT: "an agent already belongs to another active host",
5781
+ HOST_REGISTRATION_MISSING: "the pending registration is gone",
5782
+ INVALID_REQUEST: "the deployment did not accept this request's shape",
5783
+ BAD_ORIGIN: "the request came from another site",
5784
+ UNAUTHENTICATED: "the request carried no signed-in account",
5785
+ WORKSPACE_NOT_FOUND: "no such workspace for this account"
5786
+ };
5787
+ var REFUSAL_EXIT = { HOST_JOIN_NOT_AUTHORISED: 3, HOST_JOIN_AGENT_BOUND: 4, HOST_JOIN_REJECTED: 1 };
5788
+ function refusalLine(refusal) {
5789
+ const meaning = refusal.serverCode === undefined ? "" : ` The deployment says ${SERVER_REFUSALS[refusal.serverCode]}.`;
5790
+ return `${refusal.kind}: ${DIAGNOSTICS[refusal.kind]}${meaning} (HTTP ${refusal.status}, server code ${refusal.serverCode ?? "unrecognised"})`;
5791
+ }
5719
5792
  async function hostJoin(input, plugin) {
5720
5793
  try {
5721
5794
  const { origin, workspace, code, ownerConfig: ownerFile } = input;
@@ -5786,9 +5859,13 @@ async function hostJoin(input, plugin) {
5786
5859
  }
5787
5860
  }]
5788
5861
  });
5789
- console.log("Host registered; local configuration saved. Daemon startup requires platform setup.");
5862
+ console.log(`Host registered; local configuration saved. Start it with: ${hostStartCommand(claim.home)}`);
5790
5863
  return 0;
5791
5864
  } catch (error) {
5865
+ if (error instanceof HostJoinRefusal) {
5866
+ console.error(refusalLine(error));
5867
+ return REFUSAL_EXIT[error.kind];
5868
+ }
5792
5869
  const code = error instanceof Error && /^HOST_JOIN_[A-Z_]+$/u.test(error.message) ? error.message : "HOST_JOIN_INPUT";
5793
5870
  console.error(`${code}: ${DIAGNOSTICS[code] ?? "Local claim storage could not be safely published or flushed. Keep the existing files, check filesystem access and retry; no replacement credential was selected."}`);
5794
5871
  return 1;
@@ -5821,6 +5898,7 @@ async function readStatusEntry(claim) {
5821
5898
  claim,
5822
5899
  state: "joined",
5823
5900
  config,
5901
+ start: hostStartCommand(claim),
5824
5902
  pluginBundle,
5825
5903
  bundle,
5826
5904
  ...installed.ok ? { pluginVersion: installed.bundle.version } : {},
@@ -5866,6 +5944,7 @@ async function hostStatus(options) {
5866
5944
  `joined workspace ${entry.workspaceId} host ${entry.hostId}`,
5867
5945
  ` gateway ${entry.gateway ?? "(none)"}`,
5868
5946
  ` config ${entry.config}`,
5947
+ ` start ${entry.start}`,
5869
5948
  ` plugin ${entry.pluginBundle} (${entry.bundle}${versionNote(entry.pluginVersion, options.version)})`
5870
5949
  ].join(`
5871
5950
  `));
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "id": "hightea-pipe",
3
3
  "main": "./plugin.mjs",
4
- "version": "0.1.1"
4
+ "version": "0.1.2"
5
5
  }
@@ -9564,6 +9564,7 @@ var BOUNDED_ERROR_CODES = [
9564
9564
  "APPROVAL_REQUIRED",
9565
9565
  "VERSION_UNSUPPORTED",
9566
9566
  "WAKE_NOT_SENT",
9567
+ "TURN_TIMED_OUT",
9567
9568
  ...SOURCE_ERROR_CODES
9568
9569
  ];
9569
9570
  var WakeMetaSchema = object({
@@ -9799,6 +9800,25 @@ class ActiveTurnTokenVault {
9799
9800
  }
9800
9801
 
9801
9802
  // ../ahp-host/src/runtime.ts
9803
+ class UnmappedAgent extends Error {
9804
+ }
9805
+
9806
+ class FrameRefusal extends Error {
9807
+ }
9808
+ var UNSTARTABLE_AGENT_TEXT = [
9809
+ /No agent provider registered for: /u,
9810
+ /: this conversation has no matching configured ACP process authority/u
9811
+ ];
9812
+ function cloudOperationFailureCode(error) {
9813
+ if (error instanceof FrameRefusal)
9814
+ return "INVALID_OPERATION_SHAPE";
9815
+ if (error instanceof UnmappedAgent)
9816
+ return "UNMAPPED_LOCAL_AGENT";
9817
+ const text = error instanceof Error ? error.message : String(error);
9818
+ if (UNSTARTABLE_AGENT_TEXT.some((pattern) => pattern.test(text)))
9819
+ return "UNMAPPED_LOCAL_AGENT";
9820
+ return "WAKE_NOT_SENT";
9821
+ }
9802
9822
  var SUPPORTED_PROTOCOL = "1.1.0";
9803
9823
  var REQUEST_TIMEOUT_MS = 15000;
9804
9824
  var attemptKey = (deliveryId, turnId) => JSON.stringify([deliveryId, turnId]);
@@ -9972,7 +9992,7 @@ class WakePipe {
9972
9992
  const id = frame?.id;
9973
9993
  if (!this.#started || this.#storeError !== undefined) {
9974
9994
  if (id !== undefined)
9975
- this.cloud.answer(id, { ok: false, code: "INVALID_OPERATION_SHAPE" });
9995
+ this.cloud.answer(id, { ok: false, code: "WAKE_NOT_SENT" });
9976
9996
  return;
9977
9997
  }
9978
9998
  if (frame?.method === "x-hightea/revoke") {
@@ -9991,7 +10011,7 @@ class WakePipe {
9991
10011
  if (decision.operation === "session.create") {
9992
10012
  const agent = this.options.agents.get(decision.meta.agentMemberId);
9993
10013
  if (agent === undefined)
9994
- throw new Error("ahp-host: local agent mapping disappeared");
10014
+ throw new UnmappedAgent("ahp-host: local agent mapping disappeared");
9995
10015
  let winnerUri;
9996
10016
  let sessionUri;
9997
10017
  try {
@@ -10039,9 +10059,10 @@ class WakePipe {
10039
10059
  if (id !== undefined)
10040
10060
  this.cloud.answer(id, { ok: true });
10041
10061
  } catch (error) {
10042
- this.options.log.error(`ahp-host: cloud operation failed: ${String(error)}`);
10062
+ const code = cloudOperationFailureCode(error);
10063
+ this.options.log.error(`ahp-host: cloud operation ${decision.operation} failed (${code}): ${String(error)}`);
10043
10064
  if (id !== undefined)
10044
- this.cloud.answer(id, { ok: false, code: "INVALID_OPERATION_SHAPE" });
10065
+ this.cloud.answer(id, { ok: false, code });
10045
10066
  }
10046
10067
  }
10047
10068
  async#resumeSession(sessionUri) {
@@ -10074,7 +10095,7 @@ class WakePipe {
10074
10095
  return;
10075
10096
  }
10076
10097
  if (this.options.tokenExpiresAt(token) === undefined)
10077
- throw new Error("ahp-host: an agent token whose expiry cannot be read");
10098
+ throw new FrameRefusal("ahp-host: an agent token whose expiry cannot be read");
10078
10099
  const running = this.#active.get(key);
10079
10100
  if (running !== undefined) {
10080
10101
  if (running.deliveryId === meta.deliveryId) {
@@ -10107,7 +10128,7 @@ class WakePipe {
10107
10128
  }
10108
10129
  const expiresAtMs = this.options.tokenExpiresAt(token);
10109
10130
  if (expiresAtMs === undefined)
10110
- throw new Error("ahp-host: an agent token whose expiry cannot be read");
10131
+ throw new FrameRefusal("ahp-host: an agent token whose expiry cannot be read");
10111
10132
  this.vault.bindActiveTurn({
10112
10133
  sessionId: mapped.sessionUri,
10113
10134
  chatId: mapped.chatUri,
@@ -10613,9 +10634,8 @@ function createCloudLink(options) {
10613
10634
 
10614
10635
  // ../ahp-host/src/km-source.ts
10615
10636
  import { spawn } from "node:child_process";
10616
- import { randomUUID as randomUUID2 } from "node:crypto";
10637
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
10617
10638
  import { createInterface } from "node:readline";
10618
- var KM_PAGE_LIMIT = 1000;
10619
10639
  var OUTPUT_MAX_BYTES = 16 * 1024 * 1024;
10620
10640
  var GENERATIONS_KEPT = 8;
10621
10641
  var GENERATION_MAX_MS = 15 * 60000;
@@ -10645,6 +10665,8 @@ class KmSource {
10645
10665
  #inFlight = false;
10646
10666
  #pushTimer;
10647
10667
  #lastPushAt = -Infinity;
10668
+ #pushFailures = 0;
10669
+ #retryAt = -Infinity;
10648
10670
  #watching = true;
10649
10671
  #stop = new AbortController;
10650
10672
  #feed;
@@ -10654,6 +10676,7 @@ class KmSource {
10654
10676
  #now;
10655
10677
  #native;
10656
10678
  #duty;
10679
+ #minGap;
10657
10680
  #readEndedAt = -Infinity;
10658
10681
  #readTookMs = 0;
10659
10682
  #assigning = new Map;
@@ -10665,6 +10688,10 @@ class KmSource {
10665
10688
  this.#duty = options.readDuty ?? 0.1;
10666
10689
  if (!(this.#duty > 0 && this.#duty <= 1))
10667
10690
  throw new Error(`readDuty must be in (0, 1], not ${this.#duty}`);
10691
+ this.#minGap = options.config.minReadGapMs ?? 0;
10692
+ if (!(Number.isFinite(this.#minGap) && this.#minGap >= 0)) {
10693
+ throw new Error(`minReadGapMs must be a finite number of milliseconds, 0 or more, not ${this.#minGap}`);
10694
+ }
10668
10695
  this.#now = options.now ?? Date.now;
10669
10696
  this.#native = new Map(Object.entries(options.config.members).map(([member, owner]) => [owner, member]));
10670
10697
  }
@@ -10693,7 +10720,7 @@ class KmSource {
10693
10720
  this.#dirty = true;
10694
10721
  return;
10695
10722
  }
10696
- const rested = this.#readEndedAt + this.#readTookMs * (1 / this.#duty - 1) - this.#now();
10723
+ const rested = this.#readEndedAt + Math.max(this.#readTookMs * (1 / this.#duty - 1), this.#minGap) - this.#now();
10697
10724
  this.#hintTimer = setTimeout(() => {
10698
10725
  this.#hintTimer = undefined;
10699
10726
  this.#read().catch((error) => this.#o.log.error(`hightea-source: reading ${this.sourceId} after a change failed: ${describe2(error)}`));
@@ -10851,29 +10878,15 @@ class KmSource {
10851
10878
  }
10852
10879
  async#readOnce() {
10853
10880
  const generation = `${this.#epoch}.${++this.#reads}`;
10881
+ const ran = await this.#yrd(["issues", "list"]);
10882
+ if (ran.code !== 0)
10883
+ throw new Error(`list exited ${ran.code ?? "on a signal"}: ${firstCode(ran.stderr)}`);
10854
10884
  const fresh = new Map;
10855
- let snapshot;
10856
- let page;
10857
- for (;; ) {
10858
- const request = { binding: this.sourceId, population: "all-issues", generation, limit: KM_PAGE_LIMIT, ...page === undefined ? {} : { page } };
10859
- const ran = await this.#yrd(["issues", "list-page", JSON.stringify(request)]);
10860
- if (ran.code !== 0)
10861
- throw new Error(`list-page exited ${ran.code ?? "on a signal"}: ${firstCode(ran.stderr)}`);
10862
- const result = kmPage(ran.stdout);
10863
- if (snapshot !== undefined && result.snapshot !== snapshot)
10864
- throw new Error("list-page answered pages of two revisions");
10865
- snapshot = result.snapshot;
10866
- for (const one of result.rows) {
10867
- const row = this.#row(one);
10868
- fresh.set(row.address, { key: one.path, row });
10869
- }
10870
- if (result.complete)
10871
- break;
10872
- if (result.next === null)
10873
- throw new Error("list-page left a read incomplete with no next page");
10874
- page = result.next;
10885
+ for (const one of kmList(ran.stdout)) {
10886
+ const row = this.#row(one);
10887
+ fresh.set(row.address, { key: one.id, row });
10875
10888
  }
10876
- return this.#diff(generation, snapshot, fresh);
10889
+ return this.#diff(generation, contentRevision(fresh), fresh);
10877
10890
  }
10878
10891
  #diff(generation, snapshot, fresh) {
10879
10892
  const last = this.#current;
@@ -10917,24 +10930,24 @@ class KmSource {
10917
10930
  return { epoch: this.#epoch, ordinal: String(this.#ordinal) };
10918
10931
  }
10919
10932
  #row(one) {
10920
- const address = `issue:${this.sourceId}/${one.path}`;
10921
- const owner = one.row.owner.trim();
10933
+ const address = `issue:${this.sourceId}/${one.id}`;
10934
+ const owner = one.owner.trim();
10922
10935
  const row = {
10923
10936
  address,
10924
10937
  version: one.version,
10925
10938
  scope: "all",
10926
10939
  columns: {
10927
- title: one.row.title,
10928
- state: one.row.status.trim() === "" ? "none" : one.row.status.trim(),
10940
+ title: one.title,
10941
+ state: one.status.trim() === "" ? "none" : one.status.trim(),
10929
10942
  owner: owner === "" ? null : this.#native.get(owner) ?? `km:${owner}`,
10930
10943
  parent: null,
10931
10944
  labels: [],
10932
10945
  url: null,
10933
10946
  updatedAt: null
10934
10947
  },
10935
- extra: { path: one.path, id: one.row.id }
10948
+ extra: { path: one.id, id: one.id }
10936
10949
  };
10937
- if (one.row.title.length > 4096 || address.length > 1024 || sourceFrameBytes(row) > SOURCE_PAGE_BUDGET_BYTES)
10950
+ if (one.title.length > 4096 || address.length > 1024 || sourceFrameBytes(row) > SOURCE_PAGE_BUDGET_BYTES)
10938
10951
  throw new ItemTooLarge(address);
10939
10952
  return row;
10940
10953
  }
@@ -10966,6 +10979,14 @@ class KmSource {
10966
10979
  #pump() {
10967
10980
  if (!this.#watching || this.#inFlight || this.#queue.length === 0 || this.#pushTimer !== undefined || this.#stop.signal.aborted)
10968
10981
  return;
10982
+ const retryIn = this.#retryAt - this.#now();
10983
+ if (retryIn > 0) {
10984
+ this.#pushTimer = setTimeout(() => {
10985
+ this.#pushTimer = undefined;
10986
+ this.#pump();
10987
+ }, retryIn);
10988
+ return;
10989
+ }
10969
10990
  const wait = this.#lastPushAt + this.#coalesce - this.#now();
10970
10991
  if (wait > 0) {
10971
10992
  this.#pushTimer = setTimeout(() => {
@@ -10988,6 +11009,11 @@ class KmSource {
10988
11009
  this.#inFlight = true;
10989
11010
  this.#lastPushAt = this.#now();
10990
11011
  this.#o.push({ workspaceId: this.#o.houseId, sourceId: this.sourceId, hostId: this.#o.hostId, position: last.position, observations: batch }).then((answer) => {
11012
+ if (this.#pushFailures > 0) {
11013
+ this.#o.log.info?.(`hightea-source: a push of ${this.sourceId} is answered again after ${this.#pushFailures} refusal(s)`);
11014
+ this.#pushFailures = 0;
11015
+ this.#retryAt = -Infinity;
11016
+ }
10991
11017
  const ack = SourceAckSchema.safeParse(answer);
10992
11018
  if (!ack.success) {
10993
11019
  this.#o.log.error(`hightea-source: the workspace answered a push of ${this.sourceId} outside its schema`);
@@ -11001,7 +11027,13 @@ class KmSource {
11001
11027
  while (retire < this.#queue.length && BigInt(this.#queue[retire].position.ordinal) <= through)
11002
11028
  retire++;
11003
11029
  this.#queue.splice(0, retire);
11004
- }, (error) => this.#o.log.error(`hightea-source: a push of ${this.sourceId} was not answered: ${describe2(error)}`)).finally(() => {
11030
+ }, (error) => {
11031
+ this.#pushFailures++;
11032
+ const delay = Math.min(this.#coalesce * 2 ** Math.min(this.#pushFailures - 1, 5), 60000);
11033
+ this.#retryAt = this.#now() + delay;
11034
+ if (this.#pushFailures === 1)
11035
+ this.#o.log.error(`hightea-source: a push of ${this.sourceId} was not answered: ${describe2(error)}; retrying with backoff, next in ${Math.round(delay / 1000)} s`);
11036
+ }).finally(() => {
11005
11037
  this.#inFlight = false;
11006
11038
  this.#pump();
11007
11039
  });
@@ -11040,24 +11072,31 @@ class KmSource {
11040
11072
  }
11041
11073
  }
11042
11074
  }
11043
- function kmPage(stdout) {
11075
+ function kmList(stdout) {
11044
11076
  const envelope = JSON.parse(stdout);
11045
- const result = envelope.result;
11046
- if (envelope.verb !== "list-page" || result === undefined || typeof result.snapshot !== "string" || !Array.isArray(result.rows) || typeof result.complete !== "boolean" || result.next !== null && typeof result.next !== "string") {
11047
- throw new Error("list-page answered outside km's page shape");
11048
- }
11049
- const text = (value) => typeof value === "string";
11050
- const rows = result.rows.map((one) => {
11077
+ if (envelope.verb !== "list" || !Array.isArray(envelope.result))
11078
+ throw new Error("list answered outside km's list shape");
11079
+ return envelope.result.map((one) => {
11051
11080
  const row = one;
11052
- const columns = row.row;
11053
- if (!text(row.path) || !text(row.version) || columns === undefined || !text(columns.title) || !text(columns.status) || !text(columns.owner) || !text(columns.id)) {
11054
- throw new Error("list-page answered a row outside the declared columns (id, title, status, owner)");
11055
- }
11056
- if ("content" in columns || "description" in columns)
11057
- throw new Error("list-page answered a row carrying the issue body");
11058
- return row;
11081
+ const text = (value) => typeof value === "string";
11082
+ 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)");
11084
+ }
11085
+ if ("content" in row || "description" in row)
11086
+ throw new Error("list answered a row carrying the issue body");
11087
+ const columns = { id: row.id, title: row.title, status: row.status, owner: row.owner };
11088
+ return { ...columns, version: contentVersion(columns) };
11059
11089
  });
11060
- return { snapshot: result.snapshot, rows, next: result.next, complete: result.complete };
11090
+ }
11091
+ function contentVersion(row) {
11092
+ return createHash2("sha256").update(`${row.id}\x00${row.title}\x00${row.status}\x00${row.owner}`).digest("hex").slice(0, 16);
11093
+ }
11094
+ function contentRevision(rows) {
11095
+ const hash = createHash2("sha256");
11096
+ for (const address of [...rows.keys()].sort())
11097
+ hash.update(`${address}\x00${rows.get(address).row.version}
11098
+ `);
11099
+ return hash.digest("hex");
11061
11100
  }
11062
11101
  function sameColumns(a, b) {
11063
11102
  return JSON.stringify(a.columns) === JSON.stringify(b.columns);
@@ -11300,7 +11339,11 @@ function registerTools(host, mcpUrl, pipe) {
11300
11339
  const resolved = activePipe?.resolveToolToken(context);
11301
11340
  if (resolved === undefined || !resolved.ok)
11302
11341
  throw new Error("TOKEN_EXPIRED_OR_REVOKED");
11303
- const headers = { authorization: `Bearer ${resolved.token}`, "content-type": "application/json" };
11342
+ const headers = {
11343
+ authorization: `Bearer ${resolved.token}`,
11344
+ "content-type": "application/json",
11345
+ accept: "application/json, text/event-stream"
11346
+ };
11304
11347
  if (tool === "post_message")
11305
11348
  headers["idempotency-key"] = resolved.deliveryId;
11306
11349
  if (tool === "read_thread" || tool === "post_message") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hallohuman/hightea",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "The Hightea command line: join this machine to a Hightea workspace as a host.",
5
5
  "publishConfig": {
6
6
  "access": "public"