hinacode 0.3.0-alpha.0 → 0.3.0-alpha.10

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,7 @@
1
1
  import { createRequire as __createRequire } from "node:module";
2
2
  globalThis.require ??= __createRequire(import.meta.url);
3
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-C_ScFpr0.js";
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 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 tapError, bj as provide, bk as layer$1 } from "./chunks/remote-pQ0bz_4K.js";
5
5
  import { homedir } from "node:os";
6
6
  import { resolve, sep, join } from "node:path";
7
7
  import { randomUUID } from "node:crypto";
@@ -22,10 +22,6 @@ import "net";
22
22
  import "tls";
23
23
  import "url";
24
24
  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
25
  const defaultTeardown = (exit, onExit) => {
30
26
  if (isSuccess(exit)) return onExit(0);
31
27
  if (hasInterruptsOnly(exit.cause)) return onExit(130);
@@ -628,7 +624,7 @@ const Int$2 = (options) => {
628
624
  };
629
625
  const map$1 = /* @__PURE__ */ dual(2, (self, f) => flatMap(self, (a) => succeed$1(f(a))));
630
626
  const Password = (options) => basePrompt(options, "password").pipe(map$1(make$2));
631
- const run$3 = /* @__PURE__ */ fnUntraced(function* (self) {
627
+ const run$4 = /* @__PURE__ */ fnUntraced(function* (self) {
632
628
  const terminal = yield* Terminal;
633
629
  const input = yield* cached(terminal.readInput);
634
630
  return yield* runWithInput(self, terminal, input);
@@ -686,7 +682,7 @@ const proto = {
686
682
  .../* @__PURE__ */ Prototype({
687
683
  label: "Prompt",
688
684
  evaluate() {
689
- return run$3(this);
685
+ return run$4(this);
690
686
  }
691
687
  }),
692
688
  [TypeId$2]: {
@@ -4652,7 +4648,7 @@ const scanCommandLevel = (tokens, context) => {
4652
4648
  }
4653
4649
  return toLeafResult(state);
4654
4650
  };
4655
- const run$2 = /* @__PURE__ */ fnUntraced(function* (command, options) {
4651
+ const run$3 = /* @__PURE__ */ fnUntraced(function* (command, options) {
4656
4652
  const commandPath = options?.commandPath ?? [command.name];
4657
4653
  const selected = getCommandAtPath(command, commandPath);
4658
4654
  const commandLine = (options?.prefix ?? commandPath).map((value2) => commandLineArg(value2));
@@ -4702,7 +4698,7 @@ const promptCommand = /* @__PURE__ */ fnUntraced(function* (command, commandLine
4702
4698
  if (visibleSubcommands.length === 0) {
4703
4699
  return;
4704
4700
  }
4705
- const child = yield* run$3(Select({
4701
+ const child = yield* run$4(Select({
4706
4702
  message: "Command",
4707
4703
  choices: visibleSubcommands.map((command2) => ({
4708
4704
  title: command2.name,
@@ -4729,7 +4725,7 @@ const promptParam = /* @__PURE__ */ fnUntraced(function* (param) {
4729
4725
  const single = getUnderlyingSingleOrThrow(param);
4730
4726
  const metadata = getParamMetadata(param);
4731
4727
  if (metadata.isOptional) {
4732
- const include = yield* run$3(Confirm({
4728
+ const include = yield* run$4(Confirm({
4733
4729
  message: `Set ${renderParamLabel(single)}?`,
4734
4730
  initial: false
4735
4731
  }));
@@ -4738,7 +4734,7 @@ const promptParam = /* @__PURE__ */ fnUntraced(function* (param) {
4738
4734
  return [];
4739
4735
  }
4740
4736
  }
4741
- const count = !metadata.isVariadic ? 1 : yield* run$3(Int$2({
4737
+ const count = !metadata.isVariadic ? 1 : yield* run$4(Int$2({
4742
4738
  message: `${renderParamLabel(single)} count`,
4743
4739
  default: getOrElse(metadata.variadicMin, () => 0),
4744
4740
  min: getOrElse(metadata.variadicMin, () => 0),
@@ -4770,7 +4766,7 @@ const promptSingle = (single) => {
4770
4766
  const message = renderParamMessage(single);
4771
4767
  switch (single.primitiveType._tag) {
4772
4768
  case "Boolean":
4773
- return map$2(run$3(Confirm({
4769
+ return map$2(run$4(Confirm({
4774
4770
  message,
4775
4771
  label: {
4776
4772
  confirm: "true",
@@ -4783,7 +4779,7 @@ const promptSingle = (single) => {
4783
4779
  })), (value2) => commandLineArg(String(value2)));
4784
4780
  case "Choice": {
4785
4781
  const choices = getChoiceKeys(single.primitiveType) ?? [];
4786
- return map$2(run$3(Select({
4782
+ return map$2(run$4(Select({
4787
4783
  message,
4788
4784
  choices: choices.map((choice) => ({
4789
4785
  title: choice,
@@ -4792,23 +4788,23 @@ const promptSingle = (single) => {
4792
4788
  })), commandLineArg);
4793
4789
  }
4794
4790
  case "Date":
4795
- return map$2(run$3(Date({
4791
+ return map$2(run$4(Date({
4796
4792
  message
4797
4793
  })), (date) => commandLineArg(date.toISOString()));
4798
4794
  case "Finite":
4799
- return map$2(run$3(Number$1({
4795
+ return map$2(run$4(Number$1({
4800
4796
  message
4801
4797
  })), (value2) => commandLineArg(String(value2)));
4802
4798
  case "Int":
4803
- return map$2(run$3(Int$2({
4799
+ return map$2(run$4(Int$2({
4804
4800
  message
4805
4801
  })), (value2) => commandLineArg(String(value2)));
4806
4802
  case "Redacted":
4807
- return map$2(run$3(Password({
4803
+ return map$2(run$4(Password({
4808
4804
  message
4809
4805
  })), (value$1) => commandLineArg(value(value$1), "<redacted>"));
4810
4806
  default:
4811
- return map$2(run$3(String$4({
4807
+ return map$2(run$4(String$4({
4812
4808
  message
4813
4809
  })), commandLineArg);
4814
4810
  }
@@ -5035,7 +5031,7 @@ const showUserError = (error$1) => gen(function* () {
5035
5031
  yield* error(formatter.formatError(error$1));
5036
5032
  error$1[errorReported] = false;
5037
5033
  });
5038
- const run$1 = /* @__PURE__ */ dual(2, (command, config) => Stdio.use(({
5034
+ const run$2 = /* @__PURE__ */ dual(2, (command, config) => Stdio.use(({
5039
5035
  args
5040
5036
  }) => flatMap$1(args, (args2) => runWith(command, config)(args2))));
5041
5037
  const runWith = (command, config) => {
@@ -5096,12 +5092,12 @@ const runWith = (command, config) => {
5096
5092
  return yield* gen(function* () {
5097
5093
  yield* log$1(renderIntroduction(command.name, config.version, command.description, colors));
5098
5094
  const prefix = [command.name, ...args.filter((arg) => arg !== "--wizard" && !arg.startsWith("--wizard="))];
5099
- const wizardResult = yield* run$2(command, {
5095
+ const wizardResult = yield* run$3(command, {
5100
5096
  commandPath,
5101
5097
  prefix
5102
5098
  });
5103
5099
  yield* log$1(renderCompletion(wizardResult.displayArgs, colors));
5104
- const shouldRun = yield* run$3(Toggle({
5100
+ const shouldRun = yield* run$4(Toggle({
5105
5101
  message: "Run this command?",
5106
5102
  initial: true,
5107
5103
  active: "yes",
@@ -5437,6 +5433,86 @@ const inbox = make(
5437
5433
  "Print what waits on a human: open approvals, questions and secret requests, limited threads, and how many threads run or idle."
5438
5434
  )
5439
5435
  );
5436
+ const ListedRoutine = Struct({ ...Routine.fields, machine: NullOr(String$6) });
5437
+ const MIN_PREFIX = 4;
5438
+ const resolveRoutine = (raw, routines2) => {
5439
+ const ref = raw.toLowerCase();
5440
+ if (ref.length < MIN_PREFIX) return fail$1(usageError(`pass ${MIN_PREFIX}+ characters of a routine id`));
5441
+ const matches = routines2.filter((routine) => routine.id.startsWith(ref));
5442
+ if (matches.length === 1) return succeed$4(matches[0]);
5443
+ if (matches.length === 0) return fail$1(usageError(`no routine starts with ${ref}`));
5444
+ return fail$1(
5445
+ usageError(
5446
+ [
5447
+ `${ref} matches more than one routine:`,
5448
+ ...matches.map((routine) => ` ${routine.id.slice(0, 8)} ${routine.name}`)
5449
+ ].join("\n")
5450
+ )
5451
+ );
5452
+ };
5453
+ const withRoutine = (raw, use) => withClient(
5454
+ (client) => gen(function* () {
5455
+ const routine = yield* fromResult(resolveRoutine(raw, yield* client.call("routines.list", void 0)));
5456
+ return yield* use(client, routine);
5457
+ })
5458
+ );
5459
+ const routineArgument = String$2("routine").pipe(
5460
+ withDescription$2(`A routine id, or ${MIN_PREFIX}+ characters of it.`)
5461
+ );
5462
+ const ls$1 = make(
5463
+ "ls",
5464
+ {},
5465
+ () => emit(
5466
+ withClient(
5467
+ (client) => gen(function* () {
5468
+ const [routines2, machines2] = yield* all([
5469
+ client.call("routines.list", void 0),
5470
+ client.call("machines.list", void 0)
5471
+ ]);
5472
+ const listed = routines2.map((routine) => ({
5473
+ ...routine,
5474
+ machine: machines2.find((machine) => machine.projectIds.includes(routine.projectId))?.name ?? null
5475
+ }));
5476
+ return succeed(yield* encode(ArraySchema(ListedRoutine), listed));
5477
+ })
5478
+ )
5479
+ )
5480
+ ).pipe(withDescription("List routines on every machine, as JSON."));
5481
+ const run$1 = make(
5482
+ "run",
5483
+ { routine: routineArgument },
5484
+ (args) => emit(
5485
+ withRoutine(
5486
+ args.routine,
5487
+ (client, routine) => gen(function* () {
5488
+ const started = yield* client.call("routines.run", { id: routine.id });
5489
+ return succeed(yield* encode(RpcMethods["routines.run"].response, started));
5490
+ })
5491
+ )
5492
+ )
5493
+ ).pipe(withDescription("Run a routine now, whether or not it is enabled."));
5494
+ const setEnabled = (name, enabled, description) => make(
5495
+ name,
5496
+ { routine: routineArgument },
5497
+ (args) => emit(
5498
+ withRoutine(
5499
+ args.routine,
5500
+ (client, routine) => gen(function* () {
5501
+ const updated = yield* client.call("routines.update", { id: routine.id, enabled });
5502
+ return succeed(yield* encode(Routine, updated));
5503
+ })
5504
+ )
5505
+ )
5506
+ ).pipe(withDescription(description));
5507
+ const routines = make("routines").pipe(
5508
+ withDescription("List, run, enable and disable routines."),
5509
+ withSubcommands([
5510
+ ls$1,
5511
+ run$1,
5512
+ setEnabled("enable", true, "Enable a routine and schedule its next run."),
5513
+ setEnabled("disable", false, "Disable a routine. Its webhook answers 409 until it is enabled again.")
5514
+ ])
5515
+ );
5440
5516
  const OUTCOME_EXIT = { done: EXIT.done, failed: EXIT.failed, needsHuman: EXIT.needsHuman, limited: EXIT.limited };
5441
5517
  const outcomeOf = (push, threadId) => {
5442
5518
  if (push.type !== "thread.event" || push.threadId !== threadId) return void 0;
@@ -5788,7 +5864,7 @@ const serve = make(
5788
5864
  host: String$1("host").pipe(
5789
5865
  withMetavar("host"),
5790
5866
  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."
5867
+ "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
5868
  ),
5793
5869
  optional
5794
5870
  ),
@@ -5796,10 +5872,9 @@ const serve = make(
5796
5872
  withDefault(false),
5797
5873
  withDescription$1("Replace the token, which unpairs every client, or HINACODE_SERVE_ROTATE_TOKEN=1.")
5798
5874
  ),
5799
- relay: Literals("relay", ["on", "off"]).pipe(
5800
- withMetavar("on|off"),
5875
+ relay: Boolean("relay").pipe(
5801
5876
  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."
5877
+ "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
5878
  ),
5804
5879
  optional
5805
5880
  )
@@ -5812,7 +5887,7 @@ const serve = make(
5812
5887
  {
5813
5888
  port: getOrUndefined(flags.port),
5814
5889
  host: getOrUndefined(flags.host),
5815
- relay: getOrUndefined(flags.relay),
5890
+ relay: getOrUndefined(map$4(flags.relay, (on) => on ? "on" : "off")),
5816
5891
  rotateToken: flags.rotateToken
5817
5892
  },
5818
5893
  userData
@@ -5836,7 +5911,7 @@ const hinacode = make("hinacode").pipe(
5836
5911
  withDescription(
5837
5912
  "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
5913
  ),
5839
- withSubcommands([run, ...threadCommands, inbox, watch, ...cloudCommands]),
5914
+ withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands]),
5840
5915
  withGlobalFlags([DataDir])
5841
5916
  );
5842
5917
  const exitCode = (exit) => {
@@ -5846,7 +5921,7 @@ const exitCode = (exit) => {
5846
5921
  if (isCliError(error2)) return EXIT.usage;
5847
5922
  return getErrorExitCode(error2);
5848
5923
  };
5849
- run$1(hinacode, { version }).pipe(
5924
+ run$2(hinacode, { version }).pipe(
5850
5925
  tapError(
5851
5926
  (error2) => error2 instanceof CliFailure && error2.message !== "" || error2 instanceof RpcError ? sync$1(() => process.stderr.write(`hinacode: ${error2.message}
5852
5927
  `)) : void_