@hallohuman/hightea 0.1.13 → 0.1.17

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.13",
8
+ version: "0.1.17",
9
9
  description: "The Hightea command line: join this machine to a Hightea workspace as a host.",
10
10
  publishConfig: {
11
11
  access: "public"
@@ -25,10 +25,10 @@ var package_default = {
25
25
  prepack: "bun run build"
26
26
  },
27
27
  dependencies: {
28
- "@ahpd/deploy": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-deploy-0.15.0-beorn.cc798055.tgz",
29
- "@ahpd/sdk": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-sdk-0.15.0-beorn.cc798055.tgz",
30
- "@ahpd/server": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-server-0.15.0-beorn.cc798055.tgz",
31
- "@ahpd/services": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-services-0.15.0-beorn.cc798055.tgz",
28
+ "@ahpd/deploy": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/ahpd-deploy-0.15.0-beorn.3a159188.tgz",
29
+ "@ahpd/sdk": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/ahpd-sdk-0.15.0-beorn.3a159188.tgz",
30
+ "@ahpd/server": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/ahpd-server-0.15.0-beorn.3a159188.tgz",
31
+ "@hallohuman/hightea-services": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/hallohuman-hightea-services-0.16.0-beorn.3a159188.tgz",
32
32
  "@silvery/commander": "0.29.3",
33
33
  ws: "8.21.0"
34
34
  },
@@ -45,7 +45,7 @@ async function runCli(argv, options) {
45
45
  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();
46
46
  program.command("apply <file>").description("Apply a native process-compose file, or a TypeScript program that returns a plan, to one machine's ahpd: preview first, write only with --yes.").option("--machine <url>", "The machine's ahpd WebSocket endpoint, e.g. ws://127.0.0.1:7777").option("--token <token>", "The machine's token for this client (default: AHP_TKN)").option("--yes", "Send the previewed changes; without it nothing is sent").option("--prune", "After the preview lists them, remove entries this same source created that the plan no longer carries").option("--json", "Print one JSON document").addHelpText("after", `
47
47
  Exit status: 0 previewed or applied; 1 the machine refused the plan or could not be reached.`).exitOverride().action(async (file, flags) => {
48
- const { applyFile } = await import("./chunk-1kzh6qrv.js");
48
+ const { applyFile } = await import("./chunk-3ah56pdt.js");
49
49
  code = await applyFile(file, {
50
50
  machine: flags.machine ?? "",
51
51
  token: flags.token ?? process.env.AHP_TKN,
@@ -58,7 +58,7 @@ Exit status: 0 previewed or applied; 1 the machine refused the plan or could not
58
58
  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", `
59
59
  Exit status: 0 registered; 2 pending, rerun the same command; 3 not authorised for that workspace or agent;
60
60
  4 an agent is already bound to another host; 1 any other failure.`).exitOverride().action(async (flags) => {
61
- const { hostJoin } = await import("./chunk-pk0ntfzc.js");
61
+ const { hostJoin } = await import("./chunk-1xykqbdm.js");
62
62
  code = await hostJoin({ origin: flags.origin ?? "", workspace: flags.workspace ?? "", code: flags.code ?? "", ownerConfig: flags.ownerConfig ?? "" }, { directory: options.pluginDirectory, version: options.version });
63
63
  });
64
64
  host.command("list").description("List the workspace's registered hosts and which agents each runs; a workspace owner sees every host.").option("--origin <url>", "The deployment, e.g. https://hightea.dev").option("--workspace <slug>", "The workspace slug").option("--session-file <file>", "File holding your signed-in ht_session cookie (default: HIGHTEA_SESSION_FILE)").option("--json", "Print one JSON document").addHelpText("after", `
@@ -83,14 +83,14 @@ Exit status: 0 removed or already removed; 3 your account is not this workspace'
83
83
  });
84
84
  });
85
85
  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) => {
86
- const { hostStatus } = await import("./chunk-pk0ntfzc.js");
86
+ const { hostStatus } = await import("./chunk-1xykqbdm.js");
87
87
  code = await hostStatus({ version: options.version, json: flags.json === true });
88
88
  });
89
89
  host.command("update").description("Move a joined host on this machine to this CLI's plugin bundle; same host id and credentials. Restart the host after.").option("--host <id>", "The joined host's id, when this machine holds more than one").addHelpText("after", `
90
90
  The old bundle is kept until the host has connected once on the new one; a later update removes it.
91
91
  ` + `A bundle newer than this CLI's is refused (HOST_UPDATE_DOWNGRADE).
92
92
  Exit status: 0 updated or already current; 1 any refusal, named on stderr.`).exitOverride().action(async (flags) => {
93
- const { hostUpdate } = await import("./chunk-pk0ntfzc.js");
93
+ const { hostUpdate } = await import("./chunk-1xykqbdm.js");
94
94
  code = await hostUpdate({ host: flags.host }, { directory: options.pluginDirectory, version: options.version });
95
95
  });
96
96
  const trust = host.command("trust").description("The browser and host keys this machine trusts to ask its agents through a room.").addHelpText("after", `
@@ -99,16 +99,16 @@ What it protects against: an ask forged by a compromised Hightea server or datab
99
99
  ` + "running as this machine's user, which can edit trusted-keys.json as it can config.json.").exitOverride();
100
100
  trust.command("add").description("Trust a browser's (or another host's) public key, under a name of your choosing.").argument("<name>", "A name for the key, e.g. the browser it came from").argument("<public-key>", "The raw Ed25519 public key, base64url, as the browser's Members page shows it").option("--host <id>", "Which of this machine's joined hosts, when it holds more than one").addHelpText("after", `
101
101
  Exit status: 0 trusted or already trusted; 1 any failure, with the file left unchanged.`).exitOverride().action(async (name, publicKey, flags) => {
102
- const { hostTrust } = await import("./chunk-f5kk24rj.js");
102
+ const { hostTrust } = await import("./chunk-hxs6jv2m.js");
103
103
  code = await hostTrust({ action: "add", name, publicKey, ...flags.host === undefined ? {} : { host: flags.host } });
104
104
  });
105
105
  trust.command("remove").description("Stop trusting the key with this name; asks signed with it are refused from then on.").argument("<name>", "The key's name, as `hightea host trust list` shows it").option("--host <id>", "Which of this machine's joined hosts, when it holds more than one").addHelpText("after", `
106
106
  Exit status: 0 removed; 1 any failure, including an unknown name, with the file left unchanged.`).exitOverride().action(async (name, flags) => {
107
- const { hostTrust } = await import("./chunk-f5kk24rj.js");
107
+ const { hostTrust } = await import("./chunk-hxs6jv2m.js");
108
108
  code = await hostTrust({ action: "remove", name, ...flags.host === undefined ? {} : { host: flags.host } });
109
109
  });
110
110
  trust.command("list").description("List the keys this machine trusts. Changes nothing.").option("--host <id>", "Which of this machine's joined hosts, when it holds more than one").option("--json", "Print one JSON document").exitOverride().action(async (flags) => {
111
- const { hostTrust } = await import("./chunk-f5kk24rj.js");
111
+ const { hostTrust } = await import("./chunk-hxs6jv2m.js");
112
112
  code = await hostTrust({ action: "list", json: flags.json === true, ...flags.host === undefined ? {} : { host: flags.host } });
113
113
  });
114
114
  const auth = program.command("auth").description("Sign this machine in to a Hightea deployment for the owner commands.").exitOverride();
@@ -189,7 +189,7 @@ Exit status: 0 set; 3 your account is not this workspace's owner; 1 any other fa
189
189
  Exit status: 0 done; 3 your account may not manage this host's services; 1 any other failure, named on stderr.`).exitOverride().action(async (...args) => {
190
190
  const name = options.named ? String(args[0]) : undefined;
191
191
  const flags = options.named ? args[1] : args[0];
192
- const { serviceCommand } = await import("./chunk-n6qgzk8y.js");
192
+ const { serviceCommand } = await import("./chunk-6ae0ftqh.js");
193
193
  const text = (key) => typeof flags[key] === "string" ? flags[key] : undefined;
194
194
  code = await serviceCommand({
195
195
  origin: text("origin") ?? "",
@@ -212,7 +212,7 @@ Exit status: 0 done; 3 your account may not manage this host's services; 1 any o
212
212
  serviceAction("acknowledge", "Accept the process-compose files as they are now, so drift stops alerting on a hand edit.");
213
213
  service.command("backup").description("Show Hightea's backup of a host's services and their change log, labelled with how far it reaches; works while the host is offline or revoked.").requiredOption("--host <id>", "The registered host's id").option("--origin <url>", "The deployment, e.g. https://hightea.dev").option("--workspace <slug>", "The workspace slug").option("--session-file <file>", "File holding your signed-in ht_session cookie (default: HIGHTEA_SESSION_FILE)").option("--json", "Print the backup as one JSON document").addHelpText("after", `
214
214
  Exit status: 0 shown; 3 your account may not read this host's backup; 1 any other failure, named on stderr.`).exitOverride().action(async (flags) => {
215
- const { serviceBackupCommand } = await import("./chunk-n6qgzk8y.js");
215
+ const { serviceBackupCommand } = await import("./chunk-6ae0ftqh.js");
216
216
  const text = (key) => typeof flags[key] === "string" ? flags[key] : undefined;
217
217
  code = await serviceBackupCommand({
218
218
  origin: text("origin") ?? "",
@@ -225,7 +225,7 @@ Exit status: 0 shown; 3 your account may not read this host's backup; 1 any othe
225
225
  });
226
226
  service.command("restore").description("Create a host's backed-up services on a new host, create-only: shows what it will create and asks first.").argument("[names...]", "Which services; every one in the backup when none is named").requiredOption("--from <id>", "The old host whose backup is read").option("--host <id>", "The new registered host's id; with --local, which of this machine's joined hosts").option("--local", "Create them on this machine, in-process, as you").option("--origin <url>", "The deployment, e.g. https://hightea.dev").option("--workspace <slug>", "The workspace slug").option("--session-file <file>", "File holding your signed-in ht_session cookie (default: HIGHTEA_SESSION_FILE)").option("--yes", "Do not ask; for scripts").option("--json", "Print each service's outcome as one JSON document").addHelpText("after", `
227
227
  Exit status: 0 every service created; 3 your account may not read the old host's backup; 1 anything else, each named.`).exitOverride().action(async (names, flags) => {
228
- const { serviceRestore } = await import("./chunk-n6qgzk8y.js");
228
+ const { serviceRestore } = await import("./chunk-6ae0ftqh.js");
229
229
  const text = (key) => typeof flags[key] === "string" ? flags[key] : undefined;
230
230
  code = await serviceRestore({
231
231
  origin: text("origin") ?? "",
@@ -239,7 +239,7 @@ Exit status: 0 every service created; 3 your account may not read the old host's
239
239
  for (const [verb, enable] of [["enable", true], ["disable", false]]) {
240
240
  service.command(verb).description(enable ? "On this machine: let Hightea list, read logs of, change, start and stop this machine's services (adds the services grants)." : "On this machine: stop Hightea managing this machine's services (removes the services grants).").option("--host <id>", "Which of this machine's joined hosts, when it holds more than one").addHelpText("after", `
241
241
  Exit status: 0 changed or already so; 1 any failure, named on stderr.`).exitOverride().action(async (flags) => {
242
- const { hostServicesGrants } = await import("./chunk-pk0ntfzc.js");
242
+ const { hostServicesGrants } = await import("./chunk-1xykqbdm.js");
243
243
  code = await hostServicesGrants({ enable, ...typeof flags.host === "string" ? { host: flags.host } : {} });
244
244
  });
245
245
  }
@@ -4,7 +4,7 @@ import {
4
4
  localHost2,
5
5
  hostServicesGrants2,
6
6
  hostUpdate2
7
- } from "./chunk-hqjkbadp.js";
7
+ } from "./chunk-h5s3wwdz.js";
8
8
  export {
9
9
  hostJoin2 as hostJoin,
10
10
  hostServicesGrants2 as hostServicesGrants,
@@ -6940,9 +6940,24 @@ var changedFields = (before, after) => {
6940
6940
  const b = fieldsOf(after);
6941
6941
  return neutralFields.filter((field) => canonical(a[field]) !== canonical(b[field]));
6942
6942
  };
6943
+ var SERVICES_CHANNEL = "x-hh-services://";
6944
+ var operate = (host, operationId, rest) => host.call("x-ahpd/invokeOperation", { channel: SERVICES_CHANNEL, operationId, ...rest });
6943
6945
  var listOf = async (host) => {
6944
- const answer = await host.call("x-ahpd/services/list", {});
6945
- return answer;
6946
+ const answer = await host.call("subscribe", { channel: SERVICES_CHANNEL });
6947
+ await host.call("unsubscribe", { channel: SERVICES_CHANNEL });
6948
+ const state = answer?.snapshot?.state;
6949
+ if (typeof state?.error === "string")
6950
+ throw new Error(`the machine's services could not be read: ${state.error}`);
6951
+ if (state === undefined || !Array.isArray(state.rows))
6952
+ throw new Error("the services channel answered no rows");
6953
+ const rows = state.rows;
6954
+ return {
6955
+ services: rows.flatMap((row) => row.record === undefined ? [] : [row.record]),
6956
+ readOnly: rows.flatMap((row) => row.readOnly === undefined ? [] : [{ name: row.name, reason: row.readOnly }]),
6957
+ capabilities: state.capabilities,
6958
+ ifVersion: state.ifVersion,
6959
+ ...typeof state.file === "string" ? { file: state.file } : {}
6960
+ };
6946
6961
  };
6947
6962
  async function preview(plan, host, options) {
6948
6963
  refuseUncarried(plan);
@@ -6984,18 +6999,18 @@ async function applyPreview(shown, host) {
6984
6999
  let ifVersion = shown.ifVersion;
6985
7000
  const written = [];
6986
7001
  for (const service of shown.create) {
6987
- const answer = await host.call("x-ahpd/services/put", { service, ifVersion: "absent" });
7002
+ const answer = await operate(host, "put", { input: { service, ifVersion: "absent" } });
6988
7003
  ifVersion = answer.ifVersion ?? ifVersion;
6989
7004
  written.push(service.name);
6990
7005
  }
6991
7006
  for (const entry of shown.change) {
6992
- const answer = await host.call("x-ahpd/services/put", { service: entry.after, ifVersion });
7007
+ const answer = await operate(host, "put", { input: { service: entry.after, ifVersion } });
6993
7008
  ifVersion = answer.ifVersion ?? ifVersion;
6994
7009
  written.push(entry.name);
6995
7010
  }
6996
7011
  const removed = [];
6997
7012
  for (const entry of shown.remove) {
6998
- const answer = await host.call("x-ahpd/services/remove", { name: entry.name, ifVersion });
7013
+ const answer = await operate(host, "remove", { target: { id: entry.name }, input: { ifVersion } });
6999
7014
  ifVersion = answer.ifVersion ?? ifVersion;
7000
7015
  removed.push(entry.name);
7001
7016
  }
@@ -45,11 +45,11 @@ function remoteDriver(target, io) {
45
45
  };
46
46
  }
47
47
  async function localDriver(target) {
48
- const { localHost } = await import("./chunk-pk0ntfzc.js");
48
+ const { localHost } = await import("./chunk-1xykqbdm.js");
49
49
  const found = await localHost(target.host);
50
50
  if ("error" in found)
51
51
  return found;
52
- const { localServices, LOG_LINES_MAX } = await import("@ahpd/services");
52
+ const { localServices, LOG_LINES_MAX } = await import("@hallohuman/hightea-services");
53
53
  const local = localServices(found.configDir);
54
54
  if (typeof local === "string")
55
55
  return { error: `SERVICE_NOT_CONFIGURED: ${local}` };
@@ -6722,17 +6722,7 @@ var MissingRefusalSchema = object({
6722
6722
  data: object({ staleRevision: literal(0) })
6723
6723
  });
6724
6724
  // ../ahp/src/host-requests.ts
6725
- var HOST_SCOPED_METHODS = [
6726
- "x-ahpd/services/list",
6727
- "x-ahpd/services/put",
6728
- "x-ahpd/services/remove",
6729
- "x-ahpd/services/start",
6730
- "x-ahpd/services/stop",
6731
- "x-ahpd/services/restart",
6732
- "x-ahpd/services/logs",
6733
- "x-ahpd/services/acknowledge",
6734
- "x-ahpd/services/backup"
6735
- ];
6725
+ var HOST_SCOPED_METHODS = ["subscribe", "x-ahpd/invokeOperation", "resourceRead"];
6736
6726
  var HOST_REQUEST_METHODS = [
6737
6727
  "x-ahpd/agents/list",
6738
6728
  "x-ahpd/agents/put",
@@ -7773,7 +7763,17 @@ async function hostStatus2(options) {
7773
7763
  }
7774
7764
  return 0;
7775
7765
  }
7776
- var SERVICES_GRANTS = ["services:list", "services:get", "services:put", "services:delete", "services:control"];
7766
+ var SERVICES_GRANTS = [
7767
+ "service:watch",
7768
+ "service:logs",
7769
+ "service:put",
7770
+ "service:remove",
7771
+ "service:start",
7772
+ "service:stop",
7773
+ "service:restart",
7774
+ "service:accept"
7775
+ ];
7776
+ var RETIRED_SERVICES_GRANTS = ["services:list", "services:get", "services:put", "services:delete", "services:control"];
7777
7777
  async function localHost2(host) {
7778
7778
  let claims;
7779
7779
  try {
@@ -7835,8 +7835,10 @@ async function hostServicesGrants2(options) {
7835
7835
  return 1;
7836
7836
  }
7837
7837
  const held = ours.grants ?? [];
7838
- const services = SERVICES_GRANTS;
7839
- const grants = options.enable ? [...held, ...SERVICES_GRANTS.filter((grant) => !held.includes(grant))] : held.filter((grant) => !services.includes(grant));
7838
+ const services = [...SERVICES_GRANTS, ...RETIRED_SERVICES_GRANTS];
7839
+ const retired = RETIRED_SERVICES_GRANTS;
7840
+ const kept = held.filter((grant) => !retired.includes(grant));
7841
+ const grants = options.enable ? [...kept, ...SERVICES_GRANTS.filter((grant) => !kept.includes(grant))] : held.filter((grant) => !services.includes(grant));
7840
7842
  const what = `Hightea managing this machine's services (host ${found.hostId})`;
7841
7843
  if (grants.length === held.length && grants.every((grant, index) => grant === held[index])) {
7842
7844
  console.log(`${what} is already ${options.enable ? "enabled" : "disabled"}; ${found.config} was left unchanged.`);
@@ -3,7 +3,7 @@ import {
3
3
  trustedKeyId,
4
4
  readTrustedKeys,
5
5
  localHost2
6
- } from "./chunk-hqjkbadp.js";
6
+ } from "./chunk-h5s3wwdz.js";
7
7
 
8
8
  // ../ahp-host/src/trust.ts
9
9
  import { writeJsonAtomic } from "@ahpd/sdk";
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "id": "hightea-pipe",
3
3
  "main": "./plugin.mjs",
4
- "version": "0.1.13"
4
+ "version": "0.1.17"
5
5
  }
@@ -9867,17 +9867,33 @@ var MissingRefusalSchema = object({
9867
9867
  data: object({ staleRevision: literal(0) })
9868
9868
  });
9869
9869
  // ../ahp/src/host-requests.ts
9870
- var HOST_SCOPED_METHODS = [
9871
- "x-ahpd/services/list",
9872
- "x-ahpd/services/put",
9873
- "x-ahpd/services/remove",
9874
- "x-ahpd/services/start",
9875
- "x-ahpd/services/stop",
9876
- "x-ahpd/services/restart",
9877
- "x-ahpd/services/logs",
9878
- "x-ahpd/services/acknowledge",
9879
- "x-ahpd/services/backup"
9880
- ];
9870
+ var HOST_SCOPED_METHODS = ["subscribe", "x-ahpd/invokeOperation", "resourceRead"];
9871
+ var SERVICES_CHANNEL = "x-hh-services://";
9872
+ var SERVICE_OPERATIONS = ["put", "remove", "start", "stop", "restart", "accept"];
9873
+ var SERVICES_BACKUP_URI = "hh-services://backup";
9874
+ var SERVICES_CHANGES_URI = "hh-services://changes";
9875
+ var SERVICE_READ = /^(hh-service:\/\/[^/?#]+\/logs|hh-services:\/\/(backup|changes))(\?[^#]*)?$/u;
9876
+ function hostScopedRefusal(method, params) {
9877
+ const named = (key) => typeof params[key] === "string" ? JSON.stringify(params[key]) : `no ${key}`;
9878
+ switch (method) {
9879
+ case "subscribe":
9880
+ if (params.channel === SERVICES_CHANNEL && Object.keys(params).length === 1)
9881
+ return;
9882
+ return `subscribe to ${named("channel")}${Object.keys(params).length > 1 ? " with more than a channel" : ""} is not one Hightea sends; only ${SERVICES_CHANNEL}`;
9883
+ case "x-ahpd/invokeOperation":
9884
+ if (params.channel !== SERVICES_CHANNEL)
9885
+ return `x-ahpd/invokeOperation on ${named("channel")} is not one Hightea sends; only ${SERVICES_CHANNEL}`;
9886
+ if (typeof params.operationId === "string" && SERVICE_OPERATIONS.includes(params.operationId))
9887
+ return;
9888
+ return `x-ahpd/invokeOperation ${named("operationId")} on ${SERVICES_CHANNEL} is not one Hightea sends; only ${SERVICE_OPERATIONS.join(", ")}`;
9889
+ case "resourceRead":
9890
+ if (typeof params.uri === "string" && SERVICE_READ.test(params.uri))
9891
+ return;
9892
+ return `resourceRead of ${named("uri")} is not one Hightea sends; only hh-service://<name>/logs, ${SERVICES_BACKUP_URI} and ${SERVICES_CHANGES_URI}`;
9893
+ default:
9894
+ return `${JSON.stringify(method)} is not a host-scoped method; only ${HOST_SCOPED_METHODS.join(", ")}`;
9895
+ }
9896
+ }
9881
9897
  var HOST_REQUEST_METHODS = [
9882
9898
  "x-ahpd/agents/list",
9883
9899
  "x-ahpd/agents/put",
@@ -9892,6 +9908,8 @@ function isHostScopedMethod(method) {
9892
9908
  }
9893
9909
  var HOST_REQUEST_TIMEOUT_MS = 1e4;
9894
9910
  var HOST_LOCAL_TIMEOUT_MS = HOST_REQUEST_TIMEOUT_MS - 1000;
9911
+ var HOST_REQUEST_ID_PREFIX = "host-request:";
9912
+ var AHP_PROTOCOL_VERSION = "1.1.0";
9895
9913
  var HostRequestMetaSchema = object({
9896
9914
  workspaceId: string2().min(1),
9897
9915
  hostId: string2().min(1),
@@ -10133,8 +10151,34 @@ var refusal = (error) => {
10133
10151
  var isCreate = (params) => params.ifRevision === 0;
10134
10152
  var timedOut = (error) => error instanceof Error && /timed? ?out|timeout/iu.test(error.message);
10135
10153
  var AGENTS_CHANNEL = "x-ahpd-agents://";
10136
- function ahpdServiceMethod(method) {
10137
- return method.replace(/^x-hh\/service\//u, "x-ahpd/services/");
10154
+ async function listHostServices(options) {
10155
+ let state;
10156
+ let subscribed = false;
10157
+ try {
10158
+ const answer = await options.peer.request("subscribe", { channel: SERVICES_CHANNEL }, HOST_LOCAL_TIMEOUT_MS);
10159
+ subscribed = true;
10160
+ const snapshot = typeof answer === "object" && answer !== null ? answer.snapshot : undefined;
10161
+ state = typeof snapshot === "object" && snapshot !== null ? snapshot.state : undefined;
10162
+ if (typeof state !== "object" || state === null)
10163
+ throw new Error("hightea-pipe: the services snapshot holds no state");
10164
+ } catch (error) {
10165
+ const answered = refusal(error);
10166
+ if (answered !== undefined)
10167
+ return { ok: false, reason: "refused", ...answered };
10168
+ options.log.error(`hightea-pipe: ${error instanceof Error ? error.message : "the services snapshot is unreadable"}`);
10169
+ if (timedOut(error))
10170
+ return { ok: false, reason: "timedOut" };
10171
+ return { ok: false, reason: "refused", code: -32603, message: "this host could not read ahpd's services" };
10172
+ } finally {
10173
+ if (subscribed) {
10174
+ try {
10175
+ options.peer.notify("unsubscribe", { channel: SERVICES_CHANNEL });
10176
+ } catch (error) {
10177
+ options.log.error(`hightea-pipe: dropping the services subscription failed: ${error instanceof Error ? error.name : typeof error}`);
10178
+ }
10179
+ }
10180
+ }
10181
+ return { ok: true, result: state };
10138
10182
  }
10139
10183
  function rowsOfSnapshot(answer) {
10140
10184
  const snapshot = typeof answer === "object" && answer !== null ? answer.snapshot : undefined;
@@ -10175,7 +10219,7 @@ async function listHostAgents(options) {
10175
10219
  const shown = rows.filter((row) => typeof row.id === "string" && providers.has(row.id));
10176
10220
  shown.sort((left, right) => String(left.id) < String(right.id) ? -1 : String(left.id) > String(right.id) ? 1 : 0);
10177
10221
  try {
10178
- await options.peer.request("unsubscribe", { channel: AGENTS_CHANNEL }, HOST_LOCAL_TIMEOUT_MS);
10222
+ options.peer.notify("unsubscribe", { channel: AGENTS_CHANNEL });
10179
10223
  } catch (error) {
10180
10224
  options.log.error(`hightea-pipe: dropping the agents subscription failed: ${error instanceof Error ? error.name : typeof error}`);
10181
10225
  }
@@ -10191,26 +10235,42 @@ async function answerHostRequest(input, options) {
10191
10235
  const params = input.params;
10192
10236
  if (!isRecord2(params))
10193
10237
  return { ok: false, reason: "outside" };
10238
+ const carriesMember = "agentMemberId" in params;
10239
+ if (carriesMember && (typeof params.agentMemberId !== "string" || params.agentMemberId === ""))
10240
+ return { ok: false, reason: "outside" };
10241
+ const memberId = carriesMember ? params.agentMemberId : meta.agentMemberId;
10194
10242
  if (isHostScopedMethod(method)) {
10195
- if (meta.agentMemberId !== undefined)
10243
+ if (memberId !== undefined)
10196
10244
  return { ok: false, reason: "outside" };
10197
- return runHostCommand(options, method, params, ahpdServiceMethod(method));
10245
+ const refused = hostScopedRefusal(method, params);
10246
+ if (refused !== undefined) {
10247
+ options.log.error(`hightea-pipe: refused a host request: ${refused}`);
10248
+ return { ok: false, reason: "outside" };
10249
+ }
10250
+ if (method === "subscribe")
10251
+ return listHostServices(options);
10252
+ return runHostCommand(options, method, params);
10198
10253
  }
10199
10254
  if (method === "x-ahpd/agents/list") {
10200
- if (meta.agentMemberId !== undefined)
10255
+ if (memberId !== undefined)
10201
10256
  return { ok: false, reason: "outside" };
10202
10257
  if (Object.keys(params).length !== 0)
10203
10258
  return { ok: false, reason: "outside" };
10204
10259
  return listHostAgents(options);
10205
10260
  }
10206
- if (meta.agentMemberId === undefined)
10261
+ if (memberId === undefined)
10207
10262
  return { ok: false, reason: "outside" };
10208
- const agent = options.agents.get(meta.agentMemberId);
10263
+ const agent = options.agents.get(memberId);
10209
10264
  if (agent === undefined || agent.provider !== params.id)
10210
10265
  return { ok: false, reason: "unmapped" };
10211
- const forwarded = method === "x-ahpd/agents/put" && isCreate(params) ? { ...params, owner: HOST_RECORD_OWNER } : params;
10266
+ const record = carriesMember ? withoutMemberId(params) : params;
10267
+ const forwarded = method === "x-ahpd/agents/put" && isCreate(record) ? { ...record, owner: HOST_RECORD_OWNER } : record;
10212
10268
  return runHostCommand(options, method, forwarded);
10213
10269
  }
10270
+ function withoutMemberId(params) {
10271
+ const { agentMemberId: _member, ...rest } = params;
10272
+ return rest;
10273
+ }
10214
10274
  function metaOf(value) {
10215
10275
  const parsed = HostRequestMetaSchema.safeParse(value);
10216
10276
  return parsed.success ? parsed.data : undefined;
@@ -10221,9 +10281,9 @@ function isRecord2(value) {
10221
10281
  function isHostRequestMethod(method) {
10222
10282
  return method === "x-ahpd/agents/list" || method === "x-ahpd/agents/put" || method === "x-ahpd/agents/remove" || method === "x-ahpd/agents/enable" || method === "x-ahpd/agents/pause" || method === "x-ahpd/agents/disable";
10223
10283
  }
10224
- async function runHostCommand(options, method, params, forwarded = method) {
10284
+ async function runHostCommand(options, method, params) {
10225
10285
  try {
10226
- const result = await options.peer.request(forwarded, params, HOST_LOCAL_TIMEOUT_MS);
10286
+ const result = await options.peer.request(method, params, HOST_LOCAL_TIMEOUT_MS);
10227
10287
  return { ok: true, result: result ?? null };
10228
10288
  } catch (error) {
10229
10289
  const answered = refusal(error);
@@ -10615,8 +10675,10 @@ class UnmappedAgent extends Error {
10615
10675
 
10616
10676
  class FrameRefusal extends Error {
10617
10677
  }
10618
- function isHostRequestMethodName(method) {
10619
- return HOST_REQUEST_METHODS.includes(method);
10678
+ function isHostCommandFrame(method, id) {
10679
+ if (!HOST_REQUEST_METHODS.includes(method))
10680
+ return false;
10681
+ return !isHostScopedMethod(method) || typeof id === "string" && id.startsWith(HOST_REQUEST_ID_PREFIX);
10620
10682
  }
10621
10683
  function dispatchClientSeq(frame) {
10622
10684
  const seq = frame.params.clientSeq;
@@ -10640,7 +10702,7 @@ function cloudOperationFailureCode(error) {
10640
10702
  return "AGENT_NOT_MAPPED";
10641
10703
  return "WAKE_NOT_SENT";
10642
10704
  }
10643
- var SUPPORTED_PROTOCOL = "1.1.0";
10705
+ var SUPPORTED_PROTOCOL = AHP_PROTOCOL_VERSION;
10644
10706
  var REQUEST_TIMEOUT_MS = 15000;
10645
10707
  var attemptKey = (deliveryId, turnId) => JSON.stringify([deliveryId, turnId]);
10646
10708
  var PipeStateSchema = object({
@@ -10648,12 +10710,105 @@ var PipeStateSchema = object({
10648
10710
  dispatched: array(tuple([string2().min(1), array(string2().min(1))])),
10649
10711
  lastStatus: array(tuple([string2().min(1), HostToCloudFrameSchema]))
10650
10712
  }).strict();
10713
+ var LegacyHostToCloudFrameSchema = object({
10714
+ event: _enum(["session.created", "turn.started", "turn.finished", "turn.error"]),
10715
+ houseId: string2().min(1),
10716
+ deliveryId: string2().min(1),
10717
+ sessionId: string2().min(1),
10718
+ chatId: string2().min(1),
10719
+ turnId: string2().min(1).optional(),
10720
+ turnState: _enum(["created", "running", "finished", "error"]),
10721
+ statusCode: string2().min(1).max(64),
10722
+ errorCode: _enum(BOUNDED_ERROR_CODES).optional(),
10723
+ errorDetail: string2().max(256).optional()
10724
+ }).strict();
10725
+ var LEGACY_EVENTS = {
10726
+ "session.created": "session/ready",
10727
+ "turn.started": "chat/turnStarted",
10728
+ "turn.finished": "chat/turnComplete",
10729
+ "turn.error": "x-hh/turnFailed"
10730
+ };
10731
+ function upgradeLegacyFrame(frame) {
10732
+ return {
10733
+ event: LEGACY_EVENTS[frame.event],
10734
+ channel: frame.event === "session.created" ? frame.sessionId : frame.chatId,
10735
+ workspaceId: frame.houseId,
10736
+ deliveryId: frame.deliveryId,
10737
+ session: frame.sessionId,
10738
+ chat: frame.chatId,
10739
+ ...frame.turnId === undefined ? {} : { turnId: frame.turnId },
10740
+ turnState: frame.turnState,
10741
+ statusCode: frame.statusCode,
10742
+ ...frame.errorCode === undefined ? {} : { errorCode: frame.errorCode },
10743
+ ...frame.errorDetail === undefined ? {} : { errorDetail: frame.errorDetail }
10744
+ };
10745
+ }
10746
+ var PipeStateRecordSchema = object({
10747
+ sessions: array(tuple([string2().min(1), object({ sessionUri: string2().min(1), chatUri: string2().min(1).optional() }).strict()])),
10748
+ dispatched: array(tuple([string2().min(1), array(string2().min(1))])),
10749
+ lastStatus: array(unknown())
10750
+ }).strict();
10751
+ var statusKey = (frame) => frame.turnId === undefined ? frame.deliveryId : attemptKey(frame.deliveryId, frame.turnId);
10752
+ function describeIssues(error) {
10753
+ const shown = error.issues.slice(0, 3).map((issue) => `${issue.path.join(".") || "(record)"} ${issue.message}`);
10754
+ return `${shown.join("; ")}${error.issues.length > 3 ? `; and ${error.issues.length - 3} more` : ""}`;
10755
+ }
10756
+ function frameKind(entry) {
10757
+ const frame = Array.isArray(entry) ? entry[1] : entry;
10758
+ if (typeof frame === "object" && frame !== null) {
10759
+ const event = frame.event;
10760
+ if (typeof event === "string")
10761
+ return `event=${event}`;
10762
+ }
10763
+ return Array.isArray(entry) ? `a frame of ${typeof frame}` : `${entry === null ? "null" : typeof entry}`;
10764
+ }
10765
+ function readPipeState(loaded, log) {
10766
+ const record = PipeStateRecordSchema.safeParse(loaded);
10767
+ if (!record.success)
10768
+ throw new Error(`ahp-host: invalid durable state: ${describeIssues(record.error)}`);
10769
+ const lastStatus = [];
10770
+ let upgraded = 0;
10771
+ let dropped = 0;
10772
+ record.data.lastStatus.forEach((entry, index) => {
10773
+ const pair = tuple([string2().min(1), unknown()]).safeParse(entry);
10774
+ const key = pair.success ? pair.data[0] : "";
10775
+ const asCurrent = pair.success ? HostToCloudFrameSchema.safeParse(pair.data[1]) : undefined;
10776
+ const legacy = pair.success && asCurrent?.success === false ? LegacyHostToCloudFrameSchema.safeParse(pair.data[1]) : undefined;
10777
+ const frame = asCurrent?.success === true ? asCurrent.data : legacy?.success === true ? upgradeLegacyFrame(legacy.data) : undefined;
10778
+ if (frame === undefined) {
10779
+ dropped += 1;
10780
+ const legacyShaped = pair.success && typeof pair.data[1] === "object" && pair.data[1] !== null && "houseId" in pair.data[1];
10781
+ const reason = legacy?.success === false && legacyShaped ? `pre-0.1.11 shape: ${describeIssues(legacy.error)}` : asCurrent?.success === false ? describeIssues(asCurrent.error) : "not a [key, frame] entry";
10782
+ log.error(`ahp-host: dropped durable status frame lastStatus[${index}] (${frameKind(entry)}): ${reason}`);
10783
+ return;
10784
+ }
10785
+ if (statusKey(frame) !== key) {
10786
+ dropped += 1;
10787
+ log.error(`ahp-host: dropped durable status frame lastStatus[${index}] (event=${frame.event}): its key names a different delivery or turn`);
10788
+ return;
10789
+ }
10790
+ if (asCurrent?.success !== true) {
10791
+ upgraded += 1;
10792
+ log.error(`ahp-host: upgraded durable status frame lastStatus[${index}] (${frameKind(entry)} -> event=${frame.event}) from the pre-0.1.11 shape`);
10793
+ }
10794
+ lastStatus.push([key, frame]);
10795
+ });
10796
+ if (upgraded > 0 || dropped > 0) {
10797
+ log.error(`ahp-host: durable state repaired: ${upgraded} status frame(s) upgraded from the pre-0.1.11 shape, ${dropped} dropped; the pipe starts and rewrites the state`);
10798
+ }
10799
+ const sessions = record.data.sessions.map(([key, session]) => [key, {
10800
+ sessionUri: session.sessionUri,
10801
+ ...session.chatUri === undefined ? {} : { chatUri: session.chatUri }
10802
+ }]);
10803
+ return { sessions, dispatched: record.data.dispatched, lastStatus };
10804
+ }
10651
10805
 
10652
10806
  class WakePipe {
10653
10807
  vault = new ActiveTurnTokenVault;
10654
10808
  #sessions = new Map;
10655
10809
  #dispatched = new Map;
10656
10810
  #active = new Map;
10811
+ #pendingInitialize = [];
10657
10812
  #queued = new Map;
10658
10813
  #subscribed = new Set;
10659
10814
  #lastStatus = new Map;
@@ -10687,13 +10842,10 @@ class WakePipe {
10687
10842
  }
10688
10843
  const loaded = await this.options.store?.load();
10689
10844
  if (loaded === undefined) {
10690
- this.#started = true;
10845
+ this.#ready();
10691
10846
  return;
10692
10847
  }
10693
- const parsed = PipeStateSchema.safeParse(loaded);
10694
- if (!parsed.success)
10695
- throw new Error("ahp-host: invalid durable state");
10696
- const saved = parsed.data;
10848
+ const saved = readPipeState(loaded, this.options.log);
10697
10849
  for (const [key, session] of saved.sessions) {
10698
10850
  let chatUri;
10699
10851
  try {
@@ -10752,7 +10904,33 @@ class WakePipe {
10752
10904
  for (const frame of interrupted)
10753
10905
  await this.#status(frame);
10754
10906
  await this.#save();
10907
+ this.#ready();
10908
+ }
10909
+ #ready() {
10755
10910
  this.#started = true;
10911
+ for (const id of this.#pendingInitialize.splice(0))
10912
+ this.#initializeAnswer(id);
10913
+ }
10914
+ #initialize(id, params) {
10915
+ const offered = typeof params === "object" && params !== null && Array.isArray(params.protocolVersions) ? params.protocolVersions.filter((version) => typeof version === "string") : [];
10916
+ if (!offered.includes(SUPPORTED_PROTOCOL)) {
10917
+ this.cloud.reply(id, { error: { code: -32005, message: "UnsupportedProtocolVersion", data: { supportedVersions: [SUPPORTED_PROTOCOL] } } });
10918
+ return;
10919
+ }
10920
+ if (!this.#started) {
10921
+ this.#pendingInitialize.push(id);
10922
+ return;
10923
+ }
10924
+ this.#initializeAnswer(id);
10925
+ }
10926
+ #initializeAnswer(id) {
10927
+ const handshake = this.options.handshake;
10928
+ this.cloud.reply(id, { result: {
10929
+ protocolVersion: SUPPORTED_PROTOCOL,
10930
+ serverSeq: 0,
10931
+ ...handshake === undefined ? {} : { serverInfo: handshake.plugin, _meta: { ahpd: handshake.ahpd } },
10932
+ snapshots: []
10933
+ } });
10756
10934
  }
10757
10935
  #save() {
10758
10936
  const state = {
@@ -10821,13 +10999,21 @@ class WakePipe {
10821
10999
  }
10822
11000
  async fromCloud(frame) {
10823
11001
  const id = frame?.id;
11002
+ if (frame?.method === "initialize") {
11003
+ if (id === undefined) {
11004
+ this.options.log.error("hightea-pipe: an initialize frame carries no id; nothing to answer");
11005
+ return;
11006
+ }
11007
+ this.#initialize(id, frame.params);
11008
+ return;
11009
+ }
10824
11010
  if (!this.#started || this.#storeError !== undefined) {
10825
11011
  if (id !== undefined)
10826
11012
  this.cloud.answer(id, { ok: false, code: "WAKE_NOT_SENT" });
10827
11013
  return;
10828
11014
  }
10829
11015
  const commandMethod = typeof frame?.method === "string" ? frame.method : undefined;
10830
- if (commandMethod !== undefined && isHostRequestMethodName(commandMethod)) {
11016
+ if (commandMethod !== undefined && isHostCommandFrame(commandMethod, id)) {
10831
11017
  const requestId = String(id ?? "");
10832
11018
  const answer = await answerHostRequest({
10833
11019
  method: commandMethod,
@@ -11006,6 +11192,7 @@ class WakePipe {
11006
11192
  sessionUri: mapped.sessionUri,
11007
11193
  chatUri: mapped.chatUri,
11008
11194
  turnId,
11195
+ startedAtMs: Date.now(),
11009
11196
  clientSeq: dispatchClientSeq(frame),
11010
11197
  cancelled: false,
11011
11198
  stopReason: undefined,
@@ -11126,7 +11313,7 @@ class WakePipe {
11126
11313
  this.peer.notify("dispatchAction", {
11127
11314
  channel: turn.chatUri,
11128
11315
  clientSeq: ++this.#seq,
11129
- action: { type: "chat/turnCancelled", turnId: turn.turnId }
11316
+ action: { type: "chat/turnCancelled", turnId: turn.turnId, duration: Math.max(0, Date.now() - turn.startedAtMs) }
11130
11317
  });
11131
11318
  return;
11132
11319
  }
@@ -11225,7 +11412,7 @@ var mappingSchema = object({
11225
11412
  sessionUri: string2().regex(SESSION_URI)
11226
11413
  }).strict();
11227
11414
  var mappingId = (key) => `session-${createHash2("sha256").update(key).digest("hex").slice(0, 32)}`;
11228
- function recordsPipeStore(records, owner, sessionOwner) {
11415
+ function recordsPipeStore(records, owner, sessionOwner, log) {
11229
11416
  const known = new Map;
11230
11417
  const readMapping = (raw) => {
11231
11418
  const parsed = mappingSchema.safeParse(raw);
@@ -11285,13 +11472,10 @@ function recordsPipeStore(records, owner, sessionOwner) {
11285
11472
  throw new Error("ahp-host: invalid durable state record");
11286
11473
  }
11287
11474
  const raw = record.version === 1 ? record.state : typeof record.state === "object" && record.state !== null ? { sessions: [], ...record.state } : record.state;
11288
- const parsed = PipeStateSchema.safeParse(raw);
11289
- if (!parsed.success || record.version === 2 && parsed.data.sessions.length !== 0)
11290
- throw new Error("ahp-host: invalid durable state");
11291
- state = { ...parsed.data, sessions: parsed.data.sessions.map(([key, session]) => [key, {
11292
- sessionUri: session.sessionUri,
11293
- ...session.chatUri === undefined ? {} : { chatUri: session.chatUri }
11294
- }]) };
11475
+ const read = readPipeState(raw, log);
11476
+ if (record.version === 2 && read.sessions.length !== 0)
11477
+ throw new Error("ahp-host: invalid durable state: a version 2 record holds no session mappings");
11478
+ state = read;
11295
11479
  }
11296
11480
  const mappings = new Map;
11297
11481
  for (const raw of await records.list()) {
@@ -11494,6 +11678,7 @@ function createCloudLink(options) {
11494
11678
  send,
11495
11679
  close,
11496
11680
  answer: (id, outcome) => send(outcome.ok ? { jsonrpc: "2.0", id, result: null } : { jsonrpc: "2.0", id, error: { code: -32000, message: outcome.code } }),
11681
+ reply: (id, answer) => send("result" in answer ? { jsonrpc: "2.0", id, result: answer.result } : { jsonrpc: "2.0", id, error: answer.error }),
11497
11682
  status: (frame) => send({ jsonrpc: "2.0", method: "x-hightea/status", params: frame }),
11498
11683
  renewToken: (params) => request(`renew:${randomUUID()}`, "x-hightea/renewToken", { channel: "ahp-root://", ...params }),
11499
11684
  sourcePush: (params) => request(`push:${randomUUID()}`, "x-hightea/source/push", params),
@@ -13629,8 +13814,11 @@ function applyWith(host, options, seams) {
13629
13814
  tools: options.mcpUrl === undefined ? [] : hostTools,
13630
13815
  startSession: (wanted, named) => host.startSession(wanted, named),
13631
13816
  log: host.log,
13632
- store: recordsPipeStore(host.records("hightea"), owner, (uri) => host.sessionOwner(uri)),
13633
- admitTurn: (meta, token) => checks.admit(meta, token)
13817
+ store: recordsPipeStore(host.records("hightea"), owner, (uri) => host.sessionOwner(uri), host.log),
13818
+ admitTurn: (meta, token) => checks.admit(meta, token),
13819
+ ...pluginVersion === undefined ? {} : {
13820
+ handshake: { plugin: { name, version: pluginVersion }, ahpd: options.ahpdVersion }
13821
+ }
13634
13822
  });
13635
13823
  running = pipe;
13636
13824
  }, 100);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hallohuman/hightea",
3
- "version": "0.1.13",
3
+ "version": "0.1.17",
4
4
  "description": "The Hightea command line: join this machine to a Hightea workspace as a host.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -20,15 +20,15 @@
20
20
  "prepack": "bun run build"
21
21
  },
22
22
  "dependencies": {
23
- "@ahpd/deploy": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-deploy-0.15.0-beorn.cc798055.tgz",
24
- "@ahpd/sdk": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-sdk-0.15.0-beorn.cc798055.tgz",
25
- "@ahpd/server": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-server-0.15.0-beorn.cc798055.tgz",
26
- "@ahpd/services": "https://github.com/beorn/ahpd/releases/download/hh-38507-cc798055/ahpd-services-0.15.0-beorn.cc798055.tgz",
23
+ "@ahpd/deploy": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/ahpd-deploy-0.15.0-beorn.3a159188.tgz",
24
+ "@ahpd/sdk": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/ahpd-sdk-0.15.0-beorn.3a159188.tgz",
25
+ "@ahpd/server": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/ahpd-server-0.15.0-beorn.3a159188.tgz",
26
+ "@hallohuman/hightea-services": "https://github.com/beorn/ahpd/releases/download/hh-38277-3a159188/hallohuman-hightea-services-0.16.0-beorn.3a159188.tgz",
27
27
  "@silvery/commander": "0.29.3",
28
28
  "ws": "8.21.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@hallohuman/hightea-ahp-host": "0.0.3",
32
- "@hallohuman/hightea-client": "0.0.1"
31
+ "@hallohuman/hightea-ahp-host": "workspace:*",
32
+ "@hallohuman/hightea-client": "workspace:*"
33
33
  }
34
34
  }