hinacode 0.3.0-alpha.1 → 0.3.0-alpha.11

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/out/server/cli.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { createRequire as __createRequire } from "node:module";
2
2
  globalThis.require ??= __createRequire(import.meta.url);
3
- import { createRequire } from "node:module";
4
- import { d as dual, r as runFork, t as tapCause, h as hasInterruptsOnly, v as void_, s as squash, l as logError, c as constVoid, i as isEffect, a as isSuccess, w as withFiber, C as ConsoleRef, b as sync, T as TaggedError, A as ArraySchema, S as String$6, U as Union, e as hasProperty, o as optional$3, L as Literal, f as optionalKey, D as Defect, g as format, j as toCodecStringTree, k as decodeUnknownEffect, m as identity, n as succeed$2, p as fail, q as is, u as TrueLiterals, F as FalseLiterals, x as mapError, B as BooleanLiterals, I as Int$4, R as Reference, y as fnUntraced, z as scoped, Q as QuitError, E as Terminal, G as cached, H as suspend, P as Prototype, J as getOrElse, K as some, M as match, N as none, O as make$2, V as map$2, W as taggedEnum, X as match$1, Y as map$3, Z as isSome, _ as flatMap$1, $ as sync$1, a0 as empty, a1 as reduce, a2 as pipe, a3 as match$2, a4 as findFirstIndex, a5 as findFirst, a6 as findLast, a7 as isReadonlyArrayNonEmpty, a8 as ensuring, a9 as orDie, aa as take, ab as raceFirst, ac as pipeArguments, ad as catchTags, ae as fromUndefinedOr, af as isNotUndefined, ag as getOrUndefined, ah as assignProperty, ai as Service, aj as empty$1, ak as exists, al as gen, am as isNone, an as succeed$3, ao as value, ap as provideService, aq as Stdio, ar as catchFilter, as as isQuitError, at as succeed$4, au as fail$1, av as interrupt, aw as andThen, ax as catchTag, ay as result, az as make$3, aA as provideContext, aB as MinimumLogLevel, aC as Struct, aD as ApprovalRequest, aE as QuestionRequest, aF as SecretRequest, aG as Thread, aH as TaggedError$1, aI as seconds, aJ as decodeUnknownExit, aK as fromJsonString, aL as ServerFrame, aM as acquireRelease, aN as unbounded, aO as endUnsafe, aP as encodeUnknownEffect, aQ as RpcMethods, aR as timeoutOrElse, aS as callback, aT as methodKind, aU as offerUnsafe, aV as WebSocket, aW as REMOTE_PATH, aX as REMOTE_MAX_FRAME_BYTES, aY as succeedNone, aZ as cliSocketPath, a_ as all, a$ as fromResult, b0 as Number$2, b1 as forEach, b2 as AccessMode, b3 as ProviderId, b4 as promise, b5 as isFailure, b6 as toCheckoutTarget, b7 as noticeEvents, b8 as PushEvent, b9 as NullOr, ba as ThreadStatus, bb as try_, bc as as, bd as isThreadBusy, be as tryPromise, bf as tapError, bg as provide, bh as layer$1 } from "./chunks/remote-CwGJoiQN.js";
3
+ import { d as dual, r as runFork, t as tapCause, h as hasInterruptsOnly, v as void_, s as squash, l as logError, c as constVoid, i as isEffect, a as isSuccess, w as withFiber, C as ConsoleRef, b as sync, T as TaggedError, A as ArraySchema, S as String$6, U as Union, e as hasProperty, o as optional$3, L as Literal, f as optionalKey, D as Defect, g as format, j as toCodecStringTree, k as decodeUnknownEffect, m as identity, n as succeed$2, p as fail, q as is, u as TrueLiterals, F as FalseLiterals, x as mapError, B as BooleanLiterals, I as Int$4, R as Reference, y as fnUntraced, z as scoped, Q as QuitError, E as Terminal, G as cached, H as suspend, P as Prototype, J as getOrElse, K as some, M as match, N as none, O as make$2, V as map$2, W as taggedEnum, X as match$1, Y as map$3, Z as isSome, _ as flatMap$1, $ as sync$1, a0 as empty, a1 as reduce, a2 as pipe, a3 as match$2, a4 as findFirstIndex, a5 as findFirst, a6 as findLast, a7 as isReadonlyArrayNonEmpty, a8 as ensuring, a9 as orDie, aa as take, ab as raceFirst, ac as round, ad as pipeArguments, ae as catchTags, af as fromUndefinedOr, ag as isNotUndefined, ah as getOrUndefined, ai as assignProperty, aj as Service, ak as empty$1, al as exists, am as gen, an as isNone, ao as succeed$3, ap as value, aq as provideService, ar as Stdio, as as catchFilter, at as isQuitError, au as succeed$4, av as fail$1, aw as interrupt, ax as andThen, ay as catchTag, az as result, aA as make$3, aB as provideContext, aC as MinimumLogLevel, aD as Struct, aE as ApprovalRequest, aF as QuestionRequest, aG as SecretRequest, aH as Thread, aI as TaggedError$1, aJ as seconds, aK as decodeUnknownExit, aL as fromJsonString, aM as ServerFrame, aN as acquireRelease, aO as unbounded, aP as endUnsafe, aQ as encodeUnknownEffect, aR as RpcMethods, aS as timeoutOrElse, aT as callback, aU as methodKind, aV as offerUnsafe, aW as WebSocket, aX as REMOTE_PATH, aY as REMOTE_MAX_FRAME_BYTES, aZ as succeedNone, a_ as cliSocketPath, a$ as all, b0 as fromResult, b1 as Number$2, b2 as forEach, b3 as NullOr, b4 as Routine, b5 as AccessMode, b6 as ProviderId, b7 as promise, b8 as isFailure, b9 as toCheckoutTarget, ba as noticeEvents, bb as PushEvent, bc as ThreadStatus, bd as try_, be as as, bf as isThreadBusy, bg as tryPromise, bh as map$4, bi as packageJson, bj as tapError, bk as provide, bl as layer$1 } from "./chunks/remote-bP8M4Xnc.js";
5
4
  import { homedir } from "node:os";
6
5
  import { resolve, sep, join } from "node:path";
7
6
  import { randomUUID } from "node:crypto";
@@ -22,10 +21,6 @@ import "net";
22
21
  import "tls";
23
22
  import "url";
24
23
  import "util";
25
- const round = /* @__PURE__ */ dual(2, (self, precision) => {
26
- const factor = Math.pow(10, precision);
27
- return Math.round(self * factor) / factor;
28
- });
29
24
  const defaultTeardown = (exit, onExit) => {
30
25
  if (isSuccess(exit)) return onExit(0);
31
26
  if (hasInterruptsOnly(exit.cause)) return onExit(130);
@@ -628,7 +623,7 @@ const Int$2 = (options) => {
628
623
  };
629
624
  const map$1 = /* @__PURE__ */ dual(2, (self, f) => flatMap(self, (a) => succeed$1(f(a))));
630
625
  const Password = (options) => basePrompt(options, "password").pipe(map$1(make$2));
631
- const run$3 = /* @__PURE__ */ fnUntraced(function* (self) {
626
+ const run$4 = /* @__PURE__ */ fnUntraced(function* (self) {
632
627
  const terminal = yield* Terminal;
633
628
  const input = yield* cached(terminal.readInput);
634
629
  return yield* runWithInput(self, terminal, input);
@@ -686,7 +681,7 @@ const proto = {
686
681
  .../* @__PURE__ */ Prototype({
687
682
  label: "Prompt",
688
683
  evaluate() {
689
- return run$3(this);
684
+ return run$4(this);
690
685
  }
691
686
  }),
692
687
  [TypeId$2]: {
@@ -4652,7 +4647,7 @@ const scanCommandLevel = (tokens, context) => {
4652
4647
  }
4653
4648
  return toLeafResult(state);
4654
4649
  };
4655
- const run$2 = /* @__PURE__ */ fnUntraced(function* (command, options) {
4650
+ const run$3 = /* @__PURE__ */ fnUntraced(function* (command, options) {
4656
4651
  const commandPath = options?.commandPath ?? [command.name];
4657
4652
  const selected = getCommandAtPath(command, commandPath);
4658
4653
  const commandLine = (options?.prefix ?? commandPath).map((value2) => commandLineArg(value2));
@@ -4702,7 +4697,7 @@ const promptCommand = /* @__PURE__ */ fnUntraced(function* (command, commandLine
4702
4697
  if (visibleSubcommands.length === 0) {
4703
4698
  return;
4704
4699
  }
4705
- const child = yield* run$3(Select({
4700
+ const child = yield* run$4(Select({
4706
4701
  message: "Command",
4707
4702
  choices: visibleSubcommands.map((command2) => ({
4708
4703
  title: command2.name,
@@ -4729,7 +4724,7 @@ const promptParam = /* @__PURE__ */ fnUntraced(function* (param) {
4729
4724
  const single = getUnderlyingSingleOrThrow(param);
4730
4725
  const metadata = getParamMetadata(param);
4731
4726
  if (metadata.isOptional) {
4732
- const include = yield* run$3(Confirm({
4727
+ const include = yield* run$4(Confirm({
4733
4728
  message: `Set ${renderParamLabel(single)}?`,
4734
4729
  initial: false
4735
4730
  }));
@@ -4738,7 +4733,7 @@ const promptParam = /* @__PURE__ */ fnUntraced(function* (param) {
4738
4733
  return [];
4739
4734
  }
4740
4735
  }
4741
- const count = !metadata.isVariadic ? 1 : yield* run$3(Int$2({
4736
+ const count = !metadata.isVariadic ? 1 : yield* run$4(Int$2({
4742
4737
  message: `${renderParamLabel(single)} count`,
4743
4738
  default: getOrElse(metadata.variadicMin, () => 0),
4744
4739
  min: getOrElse(metadata.variadicMin, () => 0),
@@ -4770,7 +4765,7 @@ const promptSingle = (single) => {
4770
4765
  const message = renderParamMessage(single);
4771
4766
  switch (single.primitiveType._tag) {
4772
4767
  case "Boolean":
4773
- return map$2(run$3(Confirm({
4768
+ return map$2(run$4(Confirm({
4774
4769
  message,
4775
4770
  label: {
4776
4771
  confirm: "true",
@@ -4783,7 +4778,7 @@ const promptSingle = (single) => {
4783
4778
  })), (value2) => commandLineArg(String(value2)));
4784
4779
  case "Choice": {
4785
4780
  const choices = getChoiceKeys(single.primitiveType) ?? [];
4786
- return map$2(run$3(Select({
4781
+ return map$2(run$4(Select({
4787
4782
  message,
4788
4783
  choices: choices.map((choice) => ({
4789
4784
  title: choice,
@@ -4792,23 +4787,23 @@ const promptSingle = (single) => {
4792
4787
  })), commandLineArg);
4793
4788
  }
4794
4789
  case "Date":
4795
- return map$2(run$3(Date({
4790
+ return map$2(run$4(Date({
4796
4791
  message
4797
4792
  })), (date) => commandLineArg(date.toISOString()));
4798
4793
  case "Finite":
4799
- return map$2(run$3(Number$1({
4794
+ return map$2(run$4(Number$1({
4800
4795
  message
4801
4796
  })), (value2) => commandLineArg(String(value2)));
4802
4797
  case "Int":
4803
- return map$2(run$3(Int$2({
4798
+ return map$2(run$4(Int$2({
4804
4799
  message
4805
4800
  })), (value2) => commandLineArg(String(value2)));
4806
4801
  case "Redacted":
4807
- return map$2(run$3(Password({
4802
+ return map$2(run$4(Password({
4808
4803
  message
4809
4804
  })), (value$1) => commandLineArg(value(value$1), "<redacted>"));
4810
4805
  default:
4811
- return map$2(run$3(String$4({
4806
+ return map$2(run$4(String$4({
4812
4807
  message
4813
4808
  })), commandLineArg);
4814
4809
  }
@@ -5035,7 +5030,7 @@ const showUserError = (error$1) => gen(function* () {
5035
5030
  yield* error(formatter.formatError(error$1));
5036
5031
  error$1[errorReported] = false;
5037
5032
  });
5038
- const run$1 = /* @__PURE__ */ dual(2, (command, config) => Stdio.use(({
5033
+ const run$2 = /* @__PURE__ */ dual(2, (command, config) => Stdio.use(({
5039
5034
  args
5040
5035
  }) => flatMap$1(args, (args2) => runWith(command, config)(args2))));
5041
5036
  const runWith = (command, config) => {
@@ -5096,12 +5091,12 @@ const runWith = (command, config) => {
5096
5091
  return yield* gen(function* () {
5097
5092
  yield* log$1(renderIntroduction(command.name, config.version, command.description, colors));
5098
5093
  const prefix = [command.name, ...args.filter((arg) => arg !== "--wizard" && !arg.startsWith("--wizard="))];
5099
- const wizardResult = yield* run$2(command, {
5094
+ const wizardResult = yield* run$3(command, {
5100
5095
  commandPath,
5101
5096
  prefix
5102
5097
  });
5103
5098
  yield* log$1(renderCompletion(wizardResult.displayArgs, colors));
5104
- const shouldRun = yield* run$3(Toggle({
5099
+ const shouldRun = yield* run$4(Toggle({
5105
5100
  message: "Run this command?",
5106
5101
  initial: true,
5107
5102
  active: "yes",
@@ -5437,6 +5432,86 @@ const inbox = make(
5437
5432
  "Print what waits on a human: open approvals, questions and secret requests, limited threads, and how many threads run or idle."
5438
5433
  )
5439
5434
  );
5435
+ const ListedRoutine = Struct({ ...Routine.fields, machine: NullOr(String$6) });
5436
+ const MIN_PREFIX = 4;
5437
+ const resolveRoutine = (raw, routines2) => {
5438
+ const ref = raw.toLowerCase();
5439
+ if (ref.length < MIN_PREFIX) return fail$1(usageError(`pass ${MIN_PREFIX}+ characters of a routine id`));
5440
+ const matches = routines2.filter((routine) => routine.id.startsWith(ref));
5441
+ if (matches.length === 1) return succeed$4(matches[0]);
5442
+ if (matches.length === 0) return fail$1(usageError(`no routine starts with ${ref}`));
5443
+ return fail$1(
5444
+ usageError(
5445
+ [
5446
+ `${ref} matches more than one routine:`,
5447
+ ...matches.map((routine) => ` ${routine.id.slice(0, 8)} ${routine.name}`)
5448
+ ].join("\n")
5449
+ )
5450
+ );
5451
+ };
5452
+ const withRoutine = (raw, use) => withClient(
5453
+ (client) => gen(function* () {
5454
+ const routine = yield* fromResult(resolveRoutine(raw, yield* client.call("routines.list", void 0)));
5455
+ return yield* use(client, routine);
5456
+ })
5457
+ );
5458
+ const routineArgument = String$2("routine").pipe(
5459
+ withDescription$2(`A routine id, or ${MIN_PREFIX}+ characters of it.`)
5460
+ );
5461
+ const ls$1 = make(
5462
+ "ls",
5463
+ {},
5464
+ () => emit(
5465
+ withClient(
5466
+ (client) => gen(function* () {
5467
+ const [routines2, machines2] = yield* all([
5468
+ client.call("routines.list", void 0),
5469
+ client.call("machines.list", void 0)
5470
+ ]);
5471
+ const listed = routines2.map((routine) => ({
5472
+ ...routine,
5473
+ machine: machines2.find((machine) => machine.projectIds.includes(routine.projectId))?.name ?? null
5474
+ }));
5475
+ return succeed(yield* encode(ArraySchema(ListedRoutine), listed));
5476
+ })
5477
+ )
5478
+ )
5479
+ ).pipe(withDescription("List routines on every machine, as JSON."));
5480
+ const run$1 = make(
5481
+ "run",
5482
+ { routine: routineArgument },
5483
+ (args) => emit(
5484
+ withRoutine(
5485
+ args.routine,
5486
+ (client, routine) => gen(function* () {
5487
+ const started = yield* client.call("routines.run", { id: routine.id });
5488
+ return succeed(yield* encode(RpcMethods["routines.run"].response, started));
5489
+ })
5490
+ )
5491
+ )
5492
+ ).pipe(withDescription("Run a routine now, whether or not it is enabled."));
5493
+ const setEnabled = (name, enabled, description) => make(
5494
+ name,
5495
+ { routine: routineArgument },
5496
+ (args) => emit(
5497
+ withRoutine(
5498
+ args.routine,
5499
+ (client, routine) => gen(function* () {
5500
+ const updated = yield* client.call("routines.update", { id: routine.id, enabled });
5501
+ return succeed(yield* encode(Routine, updated));
5502
+ })
5503
+ )
5504
+ )
5505
+ ).pipe(withDescription(description));
5506
+ const routines = make("routines").pipe(
5507
+ withDescription("List, run, enable and disable routines."),
5508
+ withSubcommands([
5509
+ ls$1,
5510
+ run$1,
5511
+ setEnabled("enable", true, "Enable a routine and schedule its next run."),
5512
+ setEnabled("disable", false, "Disable a routine. Its webhook answers 409 until it is enabled again.")
5513
+ ])
5514
+ );
5440
5515
  const OUTCOME_EXIT = { done: EXIT.done, failed: EXIT.failed, needsHuman: EXIT.needsHuman, limited: EXIT.limited };
5441
5516
  const outcomeOf = (push, threadId) => {
5442
5517
  if (push.type !== "thread.event" || push.threadId !== threadId) return void 0;
@@ -5788,7 +5863,7 @@ const serve = make(
5788
5863
  host: String$1("host").pipe(
5789
5864
  withMetavar("host"),
5790
5865
  withDescription$1(
5791
- "Address to bind, or HINACODE_SERVE_HOST. Defaults to this machine's Tailscale address. Use 127.0.0.1 to reach the cloud only through the relay."
5866
+ "Address to bind, or HINACODE_SERVE_HOST. Defaults to private, every private-network address of this machine. Use 127.0.0.1 to reach the cloud only through the relay."
5792
5867
  ),
5793
5868
  optional
5794
5869
  ),
@@ -5796,10 +5871,9 @@ const serve = make(
5796
5871
  withDefault(false),
5797
5872
  withDescription$1("Replace the token, which unpairs every client, or HINACODE_SERVE_ROTATE_TOKEN=1.")
5798
5873
  ),
5799
- relay: Literals("relay", ["on", "off"]).pipe(
5800
- withMetavar("on|off"),
5874
+ relay: Boolean("relay").pipe(
5801
5875
  withDescription$1(
5802
- "Reach the cloud from any network through the HinaCode relay, or HINACODE_SERVE_RELAY. on links it to your HinaCode account once, and needs cloudflared on PATH. off unlinks it."
5876
+ "Reach the cloud from any network through the HinaCode relay, or HINACODE_SERVE_RELAY. --relay prints a URL to sign in and link it to your HinaCode account. --no-relay removes it."
5803
5877
  ),
5804
5878
  optional
5805
5879
  )
@@ -5812,7 +5886,7 @@ const serve = make(
5812
5886
  {
5813
5887
  port: getOrUndefined(flags.port),
5814
5888
  host: getOrUndefined(flags.host),
5815
- relay: getOrUndefined(flags.relay),
5889
+ relay: getOrUndefined(map$4(flags.relay, (on) => on ? "on" : "off")),
5816
5890
  rotateToken: flags.rotateToken
5817
5891
  },
5818
5892
  userData
@@ -5831,12 +5905,12 @@ const pair = make(
5831
5905
  () => flatMap$1(cloudData, (userData) => runDaemon("pair", (daemon) => daemon.pair(userData)))
5832
5906
  ).pipe(withDescription("Print the pairing URLs and QR code of the cloud again, without restarting it."));
5833
5907
  const cloudCommands = [serve, pair];
5834
- const { version } = createRequire(import.meta.url)("../../package.json");
5908
+ const { version } = packageJson;
5835
5909
  const hinacode = make("hinacode").pipe(
5836
5910
  withDescription(
5837
5911
  "Drive the agents HinaCode runs on every machine you reach, from scripts and other programs. Every command prints one JSON document on stdout, except watch, which prints one JSON line per event."
5838
5912
  ),
5839
- withSubcommands([run, ...threadCommands, inbox, watch, ...cloudCommands]),
5913
+ withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands]),
5840
5914
  withGlobalFlags([DataDir])
5841
5915
  );
5842
5916
  const exitCode = (exit) => {
@@ -5846,7 +5920,7 @@ const exitCode = (exit) => {
5846
5920
  if (isCliError(error2)) return EXIT.usage;
5847
5921
  return getErrorExitCode(error2);
5848
5922
  };
5849
- run$1(hinacode, { version }).pipe(
5923
+ run$2(hinacode, { version }).pipe(
5850
5924
  tapError(
5851
5925
  (error2) => error2 instanceof CliFailure && error2.message !== "" || error2 instanceof RpcError ? sync$1(() => process.stderr.write(`hinacode: ${error2.message}
5852
5926
  `)) : void_